Skip to content

Latest commit

 

History

History
173 lines (115 loc) · 6.83 KB

iot-hub-python-python-file-upload.md

File metadata and controls

173 lines (115 loc) · 6.83 KB
title description author manager ms.service services ms.devlang ms.topic ms.date ms.author
Upload files from devices to Azure IoT Hub with Python | Microsoft Docs
How to upload files from a device to the cloud using Azure IoT device SDK for Python. Uploaded files are stored in an Azure storage blob container.
kgremban
timlt
iot-hub
iot-hub
python
conceptual
03/05/2018
kgremban

Upload files from your device to the cloud with IoT Hub

[!INCLUDE iot-hub-file-upload-language-selector]

This tutorial follows how to use the file upload capabilities of IoT Hub to upload a file to Azure blob storage. The tutorial shows you how to:

  • Securely provide a storage container for uploading a file.
  • Use the Python client to upload a file through your IoT hub.

The Get started with IoT Hub tutorial demonstrates the basic device-to-cloud messaging functionality of IoT Hub. However, in some scenarios you cannot easily map the data your devices send into the relatively small device-to-cloud messages that IoT Hub accepts. When you need to upland files from a device, you can still use the security and reliability of IoT Hub.

Note

IoT Hub Python SDK currently only supports uploading character-based files such as .txt files.

At the end of this tutorial you run the Python console app:

  • FileUpload.py, which uploads a file to storage using the Python Device SDK.

Note

IoT Hub supports many device platforms and languages (including C, .NET, Javascript, Python, and Java) through Azure IoT device SDKs. Refer to the Azure IoT Developer Center for step-by-step instructions on how to connect your device to Azure IoT Hub.

To complete this tutorial, you need the following:

Create an IoT hub

[!INCLUDE iot-hub-include-create-hub]

Retrieve connection string for IoT hub

[!INCLUDE iot-hub-include-find-connection-string]

Register a new device in the IoT hub

[!INCLUDE iot-hub-include-create-device]

[!INCLUDE iot-hub-associate-storage]

Upload a file from a device app

In this section, you create the device app to upload a file to IoT hub.

  1. At your command prompt, run the following command to install the azure-iothub-device-client package:

    pip install azure-iothub-device-client
    
  2. Using a text editor, create a FileUpload.py file in your working folder.

  3. Add the following import statements and variables at the start of the FileUpload.py file. Replace deviceConnectionString with the connection string of your IoT hub device:

    import time
    import sys
    import iothub_client
    import os
    from iothub_client import IoTHubClient, IoTHubClientError, IoTHubTransportProvider, IoTHubClientResult, IoTHubError
    
    CONNECTION_STRING = "[Device Connection String]"
    PROTOCOL = IoTHubTransportProvider.HTTP
    
    PATHTOFILE = "[Full path to file]"
    FILENAME = "[File name on storage after upload]"
  4. Create a callback for the upload_blob function:

    def blob_upload_conf_callback(result, user_context):
        if str(result) == 'OK':
            print ( "...file uploaded successfully." )
        else:
            print ( "...file upload callback returned: " + str(result) )
  5. Add the following code to connect the client and upload the file. Also include the main routine:

    def iothub_file_upload_sample_run():
        try:
            print ( "IoT Hub file upload sample, press Ctrl-C to exit" )
    
            client = IoTHubClient(CONNECTION_STRING, PROTOCOL)
    
            f = open(PATHTOFILE, "r")
            content = f.read()
    
            client.upload_blob_async(FILENAME, content, len(content), blob_upload_conf_callback, 0)
    
            print ( "" )
            print ( "File upload initiated..." )
    
            while True:
                time.sleep(30)
    
        except IoTHubError as iothub_error:
            print ( "Unexpected error %s from IoTHub" % iothub_error )
            return
        except KeyboardInterrupt:
            print ( "IoTHubClient sample stopped" )
        except:
            print ( "generic error" )
    
    if __name__ == '__main__':
        print ( "Simulating a file upload using the Azure IoT Hub Device SDK for Python" )
        print ( "    Protocol %s" % PROTOCOL )
        print ( "    Connection string=%s" % CONNECTION_STRING )
    
        iothub_file_upload_sample_run()
  6. Save and close the UploadFile.py file.

  7. Copy a sample text file to the working folder and rename it sample.txt.

    [!NOTE] IoT Hub Python SDK currently only supports uploading character-based files such as .txt files.

Run the application

Now you are ready to run the application.

  1. At a command prompt in your working folder, run the following command:

    python FileUpload.py
    
  2. The following screenshot shows the output from the FileUpload app:

    Output from simulated-device app

  3. You can use the portal to view the uploaded file in the storage container you configured:

    Uploaded file

Next steps

In this tutorial, you learned how to use the file upload capabilities of IoT Hub to simplify file uploads from devices. You can continue to explore IoT hub features and scenarios with the following articles: