Skip to main content

Access to Microsoft Azure IoT from CircuitPython

Project description

Adafruit_CircuitPython_AzureIoT

Documentation Status Discord Build Status

A CircuitPython device library for Microsoft Azure IoT Services from a CircuitPython device. This library only supports key-base authentication, it currently doesn’t support X.509 certificates.

Installing from PyPI

On supported GNU/Linux systems like the Raspberry Pi, you can install the driver locally from PyPI. To install for current user:

pip3 install adafruit-circuitpython-azureiot

To install system-wide (this may be required in some cases):

sudo pip3 install adafruit-circuitpython-azureiot

To install in a virtual environment in your current project:

mkdir project-name && cd project-name
python3 -m venv .venv
source .venv/bin/activate
pip3 install adafruit-circuitpython-azureiot

Dependencies

This driver depends on:

Please ensure all dependencies are available on the CircuitPython filesystem. This is easily achieved by downloading the Adafruit library and driver bundle.

Usage Example

This library supports both Azure IoT Hub and Azure IoT Central.

To create an Azure IoT Hub instance or an Azure IoT Central app, you will need an Azure subscription. If you don’t have an Azure subscription, you can sign up for free:

  • If you are a student 18 or over, head to aka.ms/FreeStudentAzure and sign up, validating with your student email address. This will give you $100 of Azure credit and free tiers of a load of service, renewable each year you are a student. You will not need a credit card.

  • If you are not a student, head to aka.ms/FreeAz and sign up to get $200 of credit for 30 days, as well as free tiers of a load of services. You will need a credit card for validation only, your card will not be charged.

ESP32 AirLift Networking

To use this library, you will need to create an ESP32_SPI WifiManager, connected to WiFi. You will also need to set the current time, as this is used to generate time-based authentication keys. One way to do this is with the following code:

# get_time will raise ValueError if the time isn't available yet so loop until
# it works.
now_utc = None
while now_utc is None:
    try:
        now_utc = time.localtime(esp.get_time()[0])
    except ValueError:
        pass
rtc.RTC().datetime = now_utc

Native Networking

To use this library, with boards that have native networking support, you need to be connected to a network. You will also need to set the current time, as this is used to generate time-based authentication keys. One way to do this is the Adafruit NTP library with the following code:

pool = socketpool.SocketPool(wifi.radio)
ntp = adafruit_ntp.NTP(pool, tz_offset=0)

# NOTE: This changes the system time so make sure you aren't assuming that time
# doesn't jump.
rtc.RTC().datetime = ntp.datetime

Azure IoT Hub

To interact with Azure IoT Hub, you will need to create a hub, and a register a device inside that hub. There is a free tier available, and this free tier allows up to 8,000 messages a day, so try not to send messages too often if you are using this tier.

  • Open the Azure Portal.

  • Follow the instructions in Microsoft Docs to create an Azure IoT Hub and register a device.

  • Copy the devices Primary or secondary connection string, and add this to your secrets.py file.

You can find the device connection string by selecting the IoT Hub in the Azure Portal, selecting Explorer -> IoT devices, then selecting your device.

Locating the device in the IoT hub blade

Locating the device in the IoT hub blade

Then copy either the primary or secondary connection string using the copy button next to the value.

Copy the primary connection string

Copy the primary connection string

Connect your device to Azure IoT Hub

from adafruit_azureiot import IoTHubDevice

device = IoTHubDevice(wifi, secrets["device_connection_string"])
device.connect()

Once the device is connected, you will regularly need to run a loop to poll for messages from the cloud.

while True:
    device.loop()
    time.sleep(1)

Send a device to cloud message

message = {"Temperature": temp}
device.send_device_to_cloud_message(json.dumps(message))

Receive device to cloud messages

def cloud_to_device_message_received(body: str, properties: dict):
    print("Received message with body", body, "and properties", json.dumps(properties))

# Subscribe to cloud to device messages
device.on_cloud_to_device_message_received = cloud_to_device_message_received

Receive direct methods

def direct_method_invoked(method_name: str, payload) -> IoTResponse:
    print("Received direct method", method_name, "with data", str(payload))
    # return a status code and message to indicate if the direct method was handled correctly
    return IoTResponse(200, "OK")

# Subscribe to direct methods
device.on_direct_method_invoked = direct_method_invoked

Update reported properties on the device twin

This is not supported on Basic tier IoT Hubs, only on the free and standard tiers.

patch = {"Temperature": temp}
device.update_twin(patch)

Subscribe to desired property changes on the device twin

This is not supported on Basic tier IoT Hubs, only on the free and standard tiers.

def device_twin_desired_updated(desired_property_name: str, desired_property_value, desired_version: int):
    print("Property", desired_property_name, "updated to", str(desired_property_value), "version", desired_version)

# Subscribe to desired property changes
device.on_device_twin_desired_updated = device_twin_desired_updated

Azure IoT Central

To use Azure IoT Central, you will need to create an Azure IoT Central app, create a device template and register a device against the template.

  • Head to Azure IoT Central

  • Follow the instructions in the Microsoft Docs to create an application. Every tier is free for up to 2 devices.

  • Follow the instructions in the Microsoft Docs to create a device template.

  • Create a device based off the template, and select Connect to get the device connection details. Store the ID Scope, Device ID and either the primary or secondary device SAS key in your secrets.py file.

The IoT Central connect button

The connect button

The IoT Central connection details dialog

The connection details dialog

secrets = {
    # WiFi settings
    "ssid": "",
    "password": "",

    # Azure IoT Central settings
    "id_scope": "",
    "device_id": "",
    "device_sas_key": ""
}

Connect your device to your Azure IoT Central app

from adafruit_azureiot import IoTCentralDevice

device = IoTCentralDevice(wifi, secrets["id_scope"], secrets["device_id"], secrets["device_sas_key"])
device.connect()

Once the device is connected, you will regularly need to run a loop to poll for messages from the cloud.

while True:
    device.loop()
    time.sleep(1)

Send telemetry

message = {"Temperature": temp}
device.send_telemetry(json.dumps(message))

Listen for commands

def command_executed(command_name: str, payload) -> IoTResponse:
    print("Command", command_name, "executed with payload", str(payload))
    # return a status code and message to indicate if the command was handled correctly
    return IoTResponse(200, "OK")

# Subscribe to commands
device.on_command_executed = command_executed

Update properties

device.send_property("Desired_Temperature", temp)

Listen for property updates

def property_changed(property_name, property_value, version):
    print("Property", property_name, "updated to", str(property_value), "version", str(version))

# Subscribe to property updates
device.on_property_changed = property_changed

Learning more about Azure IoT services

If you want to learn more about setting up or using Azure IoT Services, check out the following resources:

Documentation

API documentation for this library can be found on Read the Docs.

For information on building library documentation, please check out this guide.

Contributing

Contributions are welcome! Please read our Code of Conduct before contributing to help this project stay welcoming.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

adafruit-circuitpython-azureiot-2.5.8.tar.gz (495.1 kB view details)

Uploaded Source

File details

Details for the file adafruit-circuitpython-azureiot-2.5.8.tar.gz.

File metadata

File hashes

Hashes for adafruit-circuitpython-azureiot-2.5.8.tar.gz
Algorithm Hash digest
SHA256 e4b0acc145e32399c81dc1b79d0a08714c89ad05367323a23b7270d1f389adbd
MD5 6f9fe074aa4d6f27a7cf05a1f03292ba
BLAKE2b-256 ae22b35e5f582a9182b0f7e41c2bd0b3fe04c4b2633d0858875ea7a99bc558e7

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page