Package: adafruit-circuitpython-azureiot
Adafruit_CircuitPython_AzureIoTA CircuitPython device library forMicrosoft Azure IoT Servicesfrom a CircuitPython device. This library only supports key-base authentication, it currently doesn’t support X.509 certificates.Installing from PyPIOn supported GNU/Linux systems like the Raspberry Pi, you can install the driver locallyfrom
PyPI. To install for current user:pip3installadafruit-circuitpython-azureiotTo install system-wide (this may be required in some cases):sudopip3installadafruit-circuitpython-azureiotTo install in a virtual environment in your current project:mkdirproject-name&&cdproject-namepython3-mvenv.venvsource.venv/bin/activatepip3installadafruit-circuitpython-azureiotDependenciesThis driver depends on:Adafruit CircuitPythonAdafruit CircuitPython MiniMQTTAdafruit CircuitPython RequestsAdafruit CircuitPython BinASCIIAdafruit CircuitPython LoggingPlease ensure all dependencies are available on the CircuitPython filesystem.
This is easily achieved by downloadingthe Adafruit library and driver bundle.Board Compatibility:The following built-in modules must be available: gc, json, ssl, timeUsage ExampleThis library supports bothAzure IoT HubandAzure 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 toaka.ms/FreeStudentAzureand 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 toaka.ms/FreeAzand 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 NetworkingTo 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=Nonewhilenow_utcisNone:try:now_utc=time.localtime(esp.get_time()[0])exceptValueError:passrtc.RTC().datetime=now_utcNative NetworkingTo 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 theAdafruit NTP librarywith 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.datetimeAzure IoT HubTo 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 theAzure Portal.Follow the instructions inMicrosoft Docsto create an Azure IoT Hub and register a device.Copy the devices Primary or secondary connection string, and add this to yoursecrets.pyfile.You can find the device connection string by selecting the IoT Hub in theAzure Portal,selecting Explorer -> IoT devices, then selecting your device.Locating the device in the IoT hub bladeThen copy either the primary or secondary connection string using the copy button next to the value.Copy the primary connection stringConnect your device to Azure IoT Hubfromadafruit_azureiotimportIoTHubDevicedevice=IoTHubDevice(wifi,secrets["device_connection_string"])device.connect()Once the device is connected, you will regularly need to run aloopto poll for messages from the cloud.whileTrue:device.loop()time.sleep(1)Send a device to cloud messagemessage={"Temperature":temp}device.send_device_to_cloud_message(json.dumps(message))Receive device to cloud messagesdefcloud_to_device_message_received(body:str,properties:dict):print("Received message with body",body,"and properties",json.dumps(properties))# Subscribe to cloud to device messagesdevice.on_cloud_to_device_message_received=cloud_to_device_message_receivedReceive direct methodsdefdirect_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 correctlyreturnIoTResponse(200,"OK")# Subscribe to direct methodsdevice.on_direct_method_invoked=direct_method_invokedUpdate reported properties on the device twinThis 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 twinThis is not supported on Basic tier IoT Hubs, only on the free and standard tiers.defdevice_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 changesdevice.on_device_twin_desired_updated=device_twin_desired_updatedAzure IoT CentralTo 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 toAzure IoT CentralFollow the instructions in theMicrosoft Docsto create an application. Every tier is free for up to 2 devices.Follow the instructions in theMicrosoft Docsto create a device template.Create a device based off the template, and selectConnectto get the device connection details. Store the ID Scope, Device ID and either the primary or secondary device SAS key in yoursecrets.pyfile.The connect buttonThe connection details dialogsecrets={# WiFi settings"ssid":"","password":"",# Azure IoT Central settings"id_scope":"","device_id":"","device_sas_key":""}Connect your device to your Azure IoT Central appfromadafruit_azureiotimportIoTCentralDevicedevice=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 aloopto poll for messages from the cloud.whileTrue:device.loop()time.sleep(1)Send telemetrymessage={"Temperature":temp}device.send_telemetry(json.dumps(message))Listen for commandsdefcommand_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 correctlyreturnIoTResponse(200,"OK")# Subscribe to commandsdevice.on_command_executed=command_executedUpdate propertiesdevice.send_property("Desired_Temperature",temp)Listen for property updatesdefproperty_changed(property_name,property_value,version):print("Property",property_name,"updated to",str(property_value),"version",str(version))# Subscribe to property updatesdevice.on_property_changed=property_changedLearning more about Azure IoT servicesIf you want to learn more about setting up or using Azure IoT Services, check out the following resources:Azure IoT documentation on Microsoft DocsIoT learning paths and modules on Microsoft Learn- Free, online, self-guided hands on learning with Azure IoT servicesDocumentationAPI documentation for this library can be found onRead the Docs.For information on building library documentation, please check outthis guide.ContributingContributions are welcome! Please read ourCode of Conductbefore contributing to help this project stay welcoming.