IoT Hub ESP32 AirLift Networking

Ensure your IoT Hub device works with this simple test.

examples/azureiot_esp32spi/azureiot_hub_simpletest.py
  1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
  2# SPDX-License-Identifier: MIT
  3
  4import json
  5import random
  6import time
  7import board
  8import busio
  9from digitalio import DigitalInOut
 10import neopixel
 11import rtc
 12from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
 13import adafruit_connection_manager
 14
 15# Get wifi details and more from a secrets.py file
 16try:
 17    from secrets import secrets
 18except ImportError:
 19    print("WiFi secrets are kept in secrets.py, please add them there!")
 20    raise
 21
 22# ESP32 Setup
 23try:
 24    esp32_cs = DigitalInOut(board.ESP_CS)
 25    esp32_ready = DigitalInOut(board.ESP_BUSY)
 26    esp32_reset = DigitalInOut(board.ESP_RESET)
 27except AttributeError:
 28    esp32_cs = DigitalInOut(board.D13)
 29    esp32_ready = DigitalInOut(board.D11)
 30    esp32_reset = DigitalInOut(board.D12)
 31
 32spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
 33esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
 34
 35"""Use below for Most Boards"""
 36status_light = neopixel.NeoPixel(
 37    board.NEOPIXEL, 1, brightness=0.2
 38)  # Uncomment for Most Boards
 39"""Uncomment below for ItsyBitsy M4"""
 40# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
 41# Uncomment below for an externally defined RGB LED
 42# import adafruit_rgbled
 43# from adafruit_esp32spi import PWMOut
 44# RED_LED = PWMOut.PWMOut(esp, 26)
 45# GREEN_LED = PWMOut.PWMOut(esp, 27)
 46# BLUE_LED = PWMOut.PWMOut(esp, 25)
 47# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)
 48wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
 49
 50print("Connecting to WiFi...")
 51
 52wifi.connect()
 53
 54print("Connected to WiFi!")
 55
 56print("Getting the time...")
 57
 58# get_time will raise ValueError if the time isn't available yet so loop until
 59# it works.
 60now_utc = None
 61while now_utc is None:
 62    try:
 63        now_utc = time.localtime(esp.get_time()[0])
 64    except ValueError:
 65        pass
 66rtc.RTC().datetime = now_utc
 67
 68print("Time:", str(time.time()))
 69
 70# You will need an Azure subscription to create an Azure IoT Hub resource
 71#
 72# If you don't have an Azure subscription:
 73#
 74# If you are a student, head to https://aka.ms/FreeStudentAzure and sign up, validating with your
 75#  student email address. This will give you $100 of Azure credit and free tiers of a load of
 76#  service, renewable each year you are a student
 77#
 78# If you are not a student, head to https://aka.ms/FreeAz and sign up to get $200 of credit for 30
 79#  days, as well as free tiers of a load of services
 80#
 81# Create an Azure IoT Hub and an IoT device in the Azure portal here:
 82# https://aka.ms/AzurePortalHome.
 83# Instructions to create an IoT Hub and device are here: https://aka.ms/CreateIoTHub
 84#
 85# The free tier of IoT Hub allows up to 8,000 messages a day, so try not to send messages too often
 86# if you are using the free tier
 87#
 88# Once you have a hub and a device, copy the device primary connection string.
 89# Add it to the secrets.py file in an entry called device_connection_string
 90#
 91# The adafruit-circuitpython-azureiot library depends on the following libraries:
 92#
 93# From the Adafruit CircuitPython Bundle https://github.com/adafruit/Adafruit_CircuitPython_Bundle:
 94# * adafruit-circuitpython-minimqtt
 95from adafruit_azureiot import IoTHubDevice  # pylint: disable=wrong-import-position
 96
 97pool = adafruit_connection_manager.get_radio_socketpool(esp)
 98ssl_context = adafruit_connection_manager.get_radio_ssl_context(esp)
 99# Create an IoT Hub device client and connect
100device = IoTHubDevice(pool, ssl_context, secrets["device_connection_string"])
101
102print("Connecting to Azure IoT Hub...")
103
104# Connect to IoT Central
105device.connect()
106
107print("Connected to Azure IoT Hub!")
108
109message_counter = 60
110
111while True:
112    try:
113        # Send a device to cloud message every minute
114        # You can see the overview of messages sent from the device in the Overview tab
115        # of the IoT Hub in the Azure Portal
116        if message_counter >= 60:
117            message = {"Temperature": random.randint(0, 50)}
118            device.send_device_to_cloud_message(json.dumps(message))
119            message_counter = 0
120        else:
121            message_counter += 1
122
123        # Poll every second for messages from the cloud
124        device.loop()
125    except (ValueError, RuntimeError) as e:
126        print("Connection error, reconnecting\n", str(e))
127        wifi.reset()
128        wifi.connect()
129        device.reconnect()
130        continue
131    time.sleep(1)

Handle direct methods.

examples/azureiot_esp32spi/azureiot_hub_directmethods.py
  1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
  2# SPDX-License-Identifier: MIT
  3
  4import time
  5import board
  6import busio
  7from digitalio import DigitalInOut
  8import neopixel
  9import rtc
 10from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
 11import adafruit_connection_manager
 12
 13# Get wifi details and more from a secrets.py file
 14try:
 15    from secrets import secrets
 16except ImportError:
 17    print("WiFi secrets are kept in secrets.py, please add them there!")
 18    raise
 19
 20# ESP32 Setup
 21try:
 22    esp32_cs = DigitalInOut(board.ESP_CS)
 23    esp32_ready = DigitalInOut(board.ESP_BUSY)
 24    esp32_reset = DigitalInOut(board.ESP_RESET)
 25except AttributeError:
 26    esp32_cs = DigitalInOut(board.D13)
 27    esp32_ready = DigitalInOut(board.D11)
 28    esp32_reset = DigitalInOut(board.D12)
 29
 30spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
 31esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
 32
 33"""Use below for Most Boards"""
 34status_light = neopixel.NeoPixel(
 35    board.NEOPIXEL, 1, brightness=0.2
 36)  # Uncomment for Most Boards
 37"""Uncomment below for ItsyBitsy M4"""
 38# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
 39# Uncomment below for an externally defined RGB LED
 40# import adafruit_rgbled
 41# from adafruit_esp32spi import PWMOut
 42# RED_LED = PWMOut.PWMOut(esp, 26)
 43# GREEN_LED = PWMOut.PWMOut(esp, 27)
 44# BLUE_LED = PWMOut.PWMOut(esp, 25)
 45# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)
 46wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
 47
 48print("Connecting to WiFi...")
 49
 50wifi.connect()
 51
 52print("Connected to WiFi!")
 53
 54print("Getting the time...")
 55
 56# get_time will raise ValueError if the time isn't available yet so loop until
 57# it works.
 58now_utc = None
 59while now_utc is None:
 60    try:
 61        now_utc = time.localtime(esp.get_time()[0])
 62    except ValueError:
 63        pass
 64rtc.RTC().datetime = now_utc
 65
 66print("Time:", str(time.time()))
 67
 68# You will need an Azure subscription to create an Azure IoT Hub resource
 69#
 70# If you don't have an Azure subscription:
 71#
 72# If you are a student, head to https://aka.ms/FreeStudentAzure and sign up, validating with your
 73#  student email address. This will give you $100 of Azure credit and free tiers of a load of
 74#  service, renewable each year you are a student
 75#
 76# If you are not a student, head to https://aka.ms/FreeAz and sign up to get $200 of credit for 30
 77#  days, as well as free tiers of a load of services
 78#
 79# Create an Azure IoT Hub and an IoT device in the Azure portal here:
 80# https://aka.ms/AzurePortalHome.
 81# Instructions to create an IoT Hub and device are here: https://aka.ms/CreateIoTHub
 82#
 83# The free tier of IoT Hub allows up to 8,000 messages a day, so try not to send messages too often
 84# if you are using the free tier
 85#
 86# Once you have a hub and a device, copy the device primary connection string.
 87# Add it to the secrets.py file in an entry called device_connection_string
 88#
 89# The adafruit-circuitpython-azureiot library depends on the following libraries:
 90#
 91# From the Adafruit CircuitPython Bundle https://github.com/adafruit/Adafruit_CircuitPython_Bundle:
 92# * adafruit-circuitpython-minimqtt
 93# pylint: disable=wrong-import-position
 94from adafruit_azureiot import IoTHubDevice
 95from adafruit_azureiot.iot_mqtt import IoTResponse
 96
 97# pylint: enable=wrong-import-position
 98
 99pool = adafruit_connection_manager.get_radio_socketpool(esp)
100ssl_context = adafruit_connection_manager.get_radio_ssl_context(esp)
101# Create an IoT Hub device client and connect
102device = IoTHubDevice(pool, ssl_context, secrets["device_connection_string"])
103
104
105# Subscribe to direct method calls
106# To invoke a method on the device, select it in the Azure Portal, select Direct Method,
107# fill in the method name and payload, then select Invoke Method
108# Direct method handlers need to return a response to show if the method was handled
109# successfully or not, returning an HTTP status code and message
110def direct_method_invoked(method_name: str, payload) -> IoTResponse:
111    print("Received direct method", method_name, "with data", str(payload))
112    # return a status code and message to indicate if the direct method was handled correctly
113    return IoTResponse(200, "OK")
114
115
116# Subscribe to the direct method invoked event
117device.on_direct_method_invoked = direct_method_invoked
118
119print("Connecting to Azure IoT Hub...")
120
121# Connect to IoT Central
122device.connect()
123
124print("Connected to Azure IoT Hub!")
125
126while True:
127    try:
128        # Poll every second for messages from the cloud
129        device.loop()
130    except (ValueError, RuntimeError) as e:
131        print("Connection error, reconnecting\n", str(e))
132        # If we lose connectivity, reset the wifi and reconnect
133        wifi.reset()
134        wifi.connect()
135        device.reconnect()
136        continue
137
138    time.sleep(1)

Send device to cloud messages, and handle cloud to device messages.

examples/azureiot_esp32spi/azureiot_hub_messages.py
  1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
  2# SPDX-License-Identifier: MIT
  3
  4import json
  5import random
  6import time
  7import board
  8import busio
  9from digitalio import DigitalInOut
 10import neopixel
 11import rtc
 12from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
 13import adafruit_connection_manager
 14
 15# Get wifi details and more from a secrets.py file
 16try:
 17    from secrets import secrets
 18except ImportError:
 19    print("WiFi secrets are kept in secrets.py, please add them there!")
 20    raise
 21
 22# ESP32 Setup
 23try:
 24    esp32_cs = DigitalInOut(board.ESP_CS)
 25    esp32_ready = DigitalInOut(board.ESP_BUSY)
 26    esp32_reset = DigitalInOut(board.ESP_RESET)
 27except AttributeError:
 28    esp32_cs = DigitalInOut(board.D13)
 29    esp32_ready = DigitalInOut(board.D11)
 30    esp32_reset = DigitalInOut(board.D12)
 31
 32spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
 33esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
 34
 35"""Use below for Most Boards"""
 36status_light = neopixel.NeoPixel(
 37    board.NEOPIXEL, 1, brightness=0.2
 38)  # Uncomment for Most Boards
 39"""Uncomment below for ItsyBitsy M4"""
 40# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
 41# Uncomment below for an externally defined RGB LED
 42# import adafruit_rgbled
 43# from adafruit_esp32spi import PWMOut
 44# RED_LED = PWMOut.PWMOut(esp, 26)
 45# GREEN_LED = PWMOut.PWMOut(esp, 27)
 46# BLUE_LED = PWMOut.PWMOut(esp, 25)
 47# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)
 48wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
 49
 50print("Connecting to WiFi...")
 51
 52wifi.connect()
 53
 54print("Connected to WiFi!")
 55
 56print("Getting the time...")
 57
 58# get_time will raise ValueError if the time isn't available yet so loop until
 59# it works.
 60now_utc = None
 61while now_utc is None:
 62    try:
 63        now_utc = time.localtime(esp.get_time()[0])
 64    except ValueError:
 65        pass
 66rtc.RTC().datetime = now_utc
 67
 68print("Time:", str(time.time()))
 69
 70# You will need an Azure subscription to create an Azure IoT Hub resource
 71#
 72# If you don't have an Azure subscription:
 73#
 74# If you are a student, head to https://aka.ms/FreeStudentAzure and sign up, validating with your
 75#  student email address. This will give you $100 of Azure credit and free tiers of a load of
 76#  service, renewable each year you are a student
 77#
 78# If you are not a student, head to https://aka.ms/FreeAz and sign up to get $200 of credit for 30
 79#  days, as well as free tiers of a load of services
 80#
 81# Create an Azure IoT Hub and an IoT device in the Azure portal here:
 82# https://aka.ms/AzurePortalHome.
 83# Instructions to create an IoT Hub and device are here: https://aka.ms/CreateIoTHub
 84#
 85# The free tier of IoT Hub allows up to 8,000 messages a day, so try not to send messages too often
 86# if you are using the free tier
 87#
 88# Once you have a hub and a device, copy the device primary connection string.
 89# Add it to the secrets.py file in an entry called device_connection_string
 90#
 91# The adafruit-circuitpython-azureiot library depends on the following libraries:
 92#
 93# From the Adafruit CircuitPython Bundle https://github.com/adafruit/Adafruit_CircuitPython_Bundle:
 94# * adafruit-circuitpython-minimqtt
 95from adafruit_azureiot import IoTHubDevice  # pylint: disable=wrong-import-position
 96
 97pool = adafruit_connection_manager.get_radio_socketpool(esp)
 98ssl_context = adafruit_connection_manager.get_radio_ssl_context(esp)
 99# Create an IoT Hub device client and connect
100device = IoTHubDevice(pool, ssl_context, secrets["device_connection_string"])
101
102
103# Subscribe to cloud to device messages
104# To send a message to the device, select it in the Azure Portal, select Message To Device,
105# fill in the message and any properties you want to add, then select Send Message
106def cloud_to_device_message_received(body: str, properties: dict):
107    print("Received message with body", body, "and properties", json.dumps(properties))
108
109
110# Subscribe to the cloud to device message received events
111device.on_cloud_to_device_message_received = cloud_to_device_message_received
112
113print("Connecting to Azure IoT Hub...")
114
115# Connect to IoT Central
116device.connect()
117
118print("Connected to Azure IoT Hub!")
119
120message_counter = 60
121
122while True:
123    try:
124        # Send a device to cloud message every minute
125        # You can see the overview of messages sent from the device in the Overview tab
126        # of the IoT Hub in the Azure Portal
127        if message_counter >= 60:
128            message = {"Temperature": random.randint(0, 50)}
129            device.send_device_to_cloud_message(json.dumps(message))
130            message_counter = 0
131        else:
132            message_counter += 1
133
134        # Poll every second for messages from the cloud
135        device.loop()
136    except (ValueError, RuntimeError) as e:
137        print("Connection error, reconnecting\n", str(e))
138        wifi.reset()
139        wifi.connect()
140        device.reconnect()
141        continue
142    time.sleep(1)

Update the reported properties of the devices device twin, and receive updates to desired properties.

examples/azureiot_esp32spi/azureiot_hub_twin_operations.py
  1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
  2# SPDX-License-Identifier: MIT
  3
  4import random
  5import time
  6import board
  7import busio
  8from digitalio import DigitalInOut
  9import neopixel
 10import rtc
 11from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
 12import adafruit_connection_manager
 13
 14# Get wifi details and more from a secrets.py file
 15try:
 16    from secrets import secrets
 17except ImportError:
 18    print("WiFi secrets are kept in secrets.py, please add them there!")
 19    raise
 20
 21# ESP32 Setup
 22try:
 23    esp32_cs = DigitalInOut(board.ESP_CS)
 24    esp32_ready = DigitalInOut(board.ESP_BUSY)
 25    esp32_reset = DigitalInOut(board.ESP_RESET)
 26except AttributeError:
 27    esp32_cs = DigitalInOut(board.D13)
 28    esp32_ready = DigitalInOut(board.D11)
 29    esp32_reset = DigitalInOut(board.D12)
 30
 31spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
 32esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
 33
 34"""Use below for Most Boards"""
 35status_light = neopixel.NeoPixel(
 36    board.NEOPIXEL, 1, brightness=0.2
 37)  # Uncomment for Most Boards
 38"""Uncomment below for ItsyBitsy M4"""
 39# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
 40# Uncomment below for an externally defined RGB LED
 41# import adafruit_rgbled
 42# from adafruit_esp32spi import PWMOut
 43# RED_LED = PWMOut.PWMOut(esp, 26)
 44# GREEN_LED = PWMOut.PWMOut(esp, 27)
 45# BLUE_LED = PWMOut.PWMOut(esp, 25)
 46# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)
 47wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
 48
 49print("Connecting to WiFi...")
 50
 51wifi.connect()
 52
 53print("Connected to WiFi!")
 54
 55print("Getting the time...")
 56
 57# get_time will raise ValueError if the time isn't available yet so loop until
 58# it works.
 59now_utc = None
 60while now_utc is None:
 61    try:
 62        now_utc = time.localtime(esp.get_time()[0])
 63    except ValueError:
 64        pass
 65rtc.RTC().datetime = now_utc
 66
 67print("Time:", str(time.time()))
 68
 69# You will need an Azure subscription to create an Azure IoT Hub resource
 70#
 71# If you don't have an Azure subscription:
 72#
 73# If you are a student, head to https://aka.ms/FreeStudentAzure and sign up, validating with your
 74#  student email address. This will give you $100 of Azure credit and free tiers of a load of
 75#  service, renewable each year you are a student
 76#
 77# If you are not a student, head to https://aka.ms/FreeAz and sign up to get $200 of credit for 30
 78#  days, as well as free tiers of a load of services
 79#
 80# Create an Azure IoT Hub and an IoT device in the Azure portal here:
 81# https://aka.ms/AzurePortalHome.
 82# Instructions to create an IoT Hub and device are here: https://aka.ms/CreateIoTHub
 83#
 84# The free tier of IoT Hub allows up to 8,000 messages a day, so try not to send messages too often
 85# if you are using the free tier
 86#
 87# Once you have a hub and a device, copy the device primary connection string.
 88# Add it to the secrets.py file in an entry called device_connection_string
 89#
 90# To us twins, you will need either a free or standard tier IoT Hub. Basic tier doesn't
 91# support twins
 92#
 93# The adafruit-circuitpython-azureiot library depends on the following libraries:
 94#
 95# From the Adafruit CircuitPython Bundle https://github.com/adafruit/Adafruit_CircuitPython_Bundle:
 96# * adafruit-circuitpython-minimqtt
 97from adafruit_azureiot import IoTHubDevice  # pylint: disable=wrong-import-position
 98
 99pool = adafruit_connection_manager.get_radio_socketpool(esp)
100ssl_context = adafruit_connection_manager.get_radio_ssl_context(esp)
101# Create an IoT Hub device client and connect
102device = IoTHubDevice(pool, ssl_context, secrets["device_connection_string"])
103
104
105# Subscribe to device twin desired property updates
106# To see these changes, update the desired properties for the device either in code
107# or in the Azure portal by selecting the device in the IoT Hub blade, selecting
108# Device Twin then adding or amending an entry in the 'desired' section
109def device_twin_desired_updated(
110    desired_property_name: str, desired_property_value, desired_version: int
111):
112    print(
113        "Property",
114        desired_property_name,
115        "updated to",
116        str(desired_property_value),
117        "version",
118        desired_version,
119    )
120
121
122# Subscribe to the device twin desired property updated event
123device.on_device_twin_desired_updated = device_twin_desired_updated
124
125print("Connecting to Azure IoT Hub...")
126
127# Connect to IoT Central
128device.connect()
129
130print("Connected to Azure IoT Hub!")
131
132message_counter = 60
133
134while True:
135    try:
136        if message_counter >= 60:
137            # Send a reported property twin update every minute
138            # You can see these in the portal by selecting the device in the IoT Hub blade,
139            # selecting device Twin then looking for the updates in the 'reported' section
140            patch = {"Temperature": random.randint(0, 50)}
141            device.update_twin(patch)
142            message_counter = 0
143        else:
144            message_counter += 1
145
146        # Poll every second for messages from the cloud
147        device.loop()
148    except (ValueError, RuntimeError) as e:
149        print("Connection error, reconnecting\n", str(e))
150        wifi.reset()
151        wifi.connect()
152        device.reconnect()
153        continue
154    time.sleep(1)

IoT Central ESP32 AirLift Networking

Ensure your IoT Central device works with this simple test.

examples/azureiot_esp32spi/azureiot_central_simpletest.py
  1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
  2# SPDX-License-Identifier: MIT
  3
  4import json
  5import random
  6import time
  7import board
  8import busio
  9from digitalio import DigitalInOut
 10import neopixel
 11import rtc
 12from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
 13import adafruit_connection_manager
 14
 15# Get wifi details and more from a secrets.py file
 16try:
 17    from secrets import secrets
 18except ImportError:
 19    print("WiFi secrets are kept in secrets.py, please add them there!")
 20    raise
 21
 22# ESP32 Setup
 23try:
 24    esp32_cs = DigitalInOut(board.ESP_CS)
 25    esp32_ready = DigitalInOut(board.ESP_BUSY)
 26    esp32_reset = DigitalInOut(board.ESP_RESET)
 27except AttributeError:
 28    esp32_cs = DigitalInOut(board.D13)
 29    esp32_ready = DigitalInOut(board.D11)
 30    esp32_reset = DigitalInOut(board.D12)
 31
 32spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
 33esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
 34
 35"""Use below for Most Boards"""
 36status_light = neopixel.NeoPixel(
 37    board.NEOPIXEL, 1, brightness=0.2
 38)  # Uncomment for Most Boards
 39"""Uncomment below for ItsyBitsy M4"""
 40# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
 41# Uncomment below for an externally defined RGB LED
 42# import adafruit_rgbled
 43# from adafruit_esp32spi import PWMOut
 44# RED_LED = PWMOut.PWMOut(esp, 26)
 45# GREEN_LED = PWMOut.PWMOut(esp, 27)
 46# BLUE_LED = PWMOut.PWMOut(esp, 25)
 47# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)
 48wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
 49
 50print("Connecting to WiFi...")
 51
 52wifi.connect()
 53
 54print("Connected to WiFi!")
 55
 56print("Getting the time...")
 57
 58# get_time will raise ValueError if the time isn't available yet so loop until
 59# it works.
 60now_utc = None
 61while now_utc is None:
 62    try:
 63        now_utc = time.localtime(esp.get_time()[0])
 64    except ValueError:
 65        pass
 66rtc.RTC().datetime = now_utc
 67
 68print("Time:", str(time.time()))
 69
 70# To use Azure IoT Central, you will need to create an IoT Central app.
 71# You can either create a free tier app that will live for 7 days without an Azure subscription,
 72# Or a standard tier app that will last for ever with an Azure subscription.
 73# The standard tiers are free for up to 2 devices
 74#
 75# If you don't have an Azure subscription:
 76#
 77# If you are a student, head to https://aka.ms/FreeStudentAzure and sign up, validating with your
 78#  student email address. This will give you $100 of Azure credit and free tiers of a load of
 79#  service, renewable each year you are a student
 80#
 81# If you are not a student, head to https://aka.ms/FreeAz and sign up to get $200 of credit for 30
 82#  days, as well as free tiers of a load of services
 83#
 84# Create an Azure IoT Central app by following these instructions:
 85# https://aka.ms/CreateIoTCentralApp
 86# Add a device template with telemetry, properties and commands, as well as a view to visualize the
 87# telemetry and execute commands, and a form to set properties.
 88#
 89# Next create a device using the device template, and select Connect to get the device connection
 90# details.
 91# Add the connection details to your secrets.py file, using the following values:
 92#
 93# 'id_scope' - the devices ID scope
 94# 'device_id' - the devices device id
 95# 'device_sas_key' - the devices primary key
 96#
 97# The adafruit-circuitpython-azureiot library depends on the following libraries:
 98#
 99# From the Adafruit CircuitPython Bundle https://github.com/adafruit/Adafruit_CircuitPython_Bundle:
100# * adafruit-circuitpython-minimqtt
101from adafruit_azureiot import IoTCentralDevice  # pylint: disable=wrong-import-position
102
103pool = adafruit_connection_manager.get_radio_socketpool(esp)
104ssl_context = adafruit_connection_manager.get_radio_ssl_context(esp)
105# Create an IoT Hub device client and connect
106device = IoTCentralDevice(
107    pool,
108    ssl_context,
109    secrets["id_scope"],
110    secrets["device_id"],
111    secrets["device_sas_key"],
112)
113
114print("Connecting to Azure IoT Central...")
115
116# Connect to IoT Central
117device.connect()
118
119print("Connected to Azure IoT Central!")
120
121message_counter = 60
122
123while True:
124    try:
125        # Send telemetry every minute
126        # You can see the values in the devices dashboard
127        if message_counter >= 60:
128            message = {"Temperature": random.randint(0, 50)}
129            device.send_telemetry(json.dumps(message))
130            message_counter = 0
131        else:
132            message_counter += 1
133
134        # Poll every second for messages from the cloud
135        device.loop()
136    except (ValueError, RuntimeError) as e:
137        print("Connection error, reconnecting\n", str(e))
138        # If we lose connectivity, reset the wifi and reconnect
139        wifi.reset()
140        wifi.connect()
141        device.reconnect()
142        continue
143
144    time.sleep(1)

Handle commands.

examples/azureiot_esp32spi/azureiot_central_commands.py
  1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
  2# SPDX-License-Identifier: MIT
  3
  4import time
  5import board
  6import busio
  7from digitalio import DigitalInOut
  8import neopixel
  9import rtc
 10from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
 11import adafruit_connection_manager
 12
 13# Get wifi details and more from a secrets.py file
 14try:
 15    from secrets import secrets
 16except ImportError:
 17    print("WiFi secrets are kept in secrets.py, please add them there!")
 18    raise
 19
 20# ESP32 Setup
 21try:
 22    esp32_cs = DigitalInOut(board.ESP_CS)
 23    esp32_ready = DigitalInOut(board.ESP_BUSY)
 24    esp32_reset = DigitalInOut(board.ESP_RESET)
 25except AttributeError:
 26    esp32_cs = DigitalInOut(board.D13)
 27    esp32_ready = DigitalInOut(board.D11)
 28    esp32_reset = DigitalInOut(board.D12)
 29
 30spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
 31esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
 32
 33"""Use below for Most Boards"""
 34status_light = neopixel.NeoPixel(
 35    board.NEOPIXEL, 1, brightness=0.2
 36)  # Uncomment for Most Boards
 37"""Uncomment below for ItsyBitsy M4"""
 38# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
 39# Uncomment below for an externally defined RGB LED
 40# import adafruit_rgbled
 41# from adafruit_esp32spi import PWMOut
 42# RED_LED = PWMOut.PWMOut(esp, 26)
 43# GREEN_LED = PWMOut.PWMOut(esp, 27)
 44# BLUE_LED = PWMOut.PWMOut(esp, 25)
 45# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)
 46wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
 47
 48print("Connecting to WiFi...")
 49
 50wifi.connect()
 51
 52print("Connected to WiFi!")
 53
 54print("Getting the time...")
 55
 56# get_time will raise ValueError if the time isn't available yet so loop until
 57# it works.
 58now_utc = None
 59while now_utc is None:
 60    try:
 61        now_utc = time.localtime(esp.get_time()[0])
 62    except ValueError:
 63        pass
 64rtc.RTC().datetime = now_utc
 65
 66print("Time:", str(time.time()))
 67
 68# To use Azure IoT Central, you will need to create an IoT Central app.
 69# You can either create a free tier app that will live for 7 days without an Azure subscription,
 70# Or a standard tier app that will last for ever with an Azure subscription.
 71# The standard tiers are free for up to 2 devices
 72#
 73# If you don't have an Azure subscription:
 74#
 75# If you are a student, head to https://aka.ms/FreeStudentAzure and sign up, validating with your
 76#  student email address. This will give you $100 of Azure credit and free tiers of a load of
 77#  service, renewable each year you are a student
 78#
 79# If you are not a student, head to https://aka.ms/FreeAz and sign up to get $200 of credit for 30
 80#  days, as well as free tiers of a load of services
 81#
 82# Create an Azure IoT Central app by following these instructions:
 83# https://aka.ms/CreateIoTCentralApp
 84# Add a device template with telemetry, properties and commands, as well as a view to visualize the
 85# telemetry and execute commands, and a form to set properties.
 86#
 87# Next create a device using the device template, and select Connect to get the device connection
 88# details.
 89# Add the connection details to your secrets.py file, using the following values:
 90#
 91# 'id_scope' - the devices ID scope
 92# 'device_id' - the devices device id
 93# 'device_sas_key' - the devices primary key
 94#
 95# The adafruit-circuitpython-azureiot library depends on the following libraries:
 96#
 97# From the Adafruit CircuitPython Bundle https://github.com/adafruit/Adafruit_CircuitPython_Bundle:
 98# * adafruit-circuitpython-minimqtt
 99# pylint: disable=wrong-import-position
100from adafruit_azureiot import IoTCentralDevice
101from adafruit_azureiot.iot_mqtt import IoTResponse
102
103# pylint: enable=wrong-import-position
104
105pool = adafruit_connection_manager.get_radio_socketpool(esp)
106ssl_context = adafruit_connection_manager.get_radio_ssl_context(esp)
107# Create an IoT Hub device client and connect
108device = IoTCentralDevice(
109    pool,
110    ssl_context,
111    secrets["id_scope"],
112    secrets["device_id"],
113    secrets["device_sas_key"],
114)
115
116
117# Subscribe to commands
118# Commands can be sent from the devices Dashboard in IoT Central, assuming
119# the device template and view has been set up with the commands
120# Command handlers need to return a response to show if the command was handled
121# successfully or not, returning an HTTP status code and message
122def command_executed(command_name: str, payload) -> IoTResponse:
123    print("Command", command_name, "executed with payload", str(payload))
124    # return a status code and message to indicate if the command was handled correctly
125    return IoTResponse(200, "OK")
126
127
128# Subscribe to the command execute event
129device.on_command_executed = command_executed
130
131print("Connecting to Azure IoT Central...")
132
133# Connect to IoT Central
134device.connect()
135
136print("Connected to Azure IoT Central!")
137
138while True:
139    try:
140        # Poll every second for messages from the cloud
141        device.loop()
142    except (ValueError, RuntimeError) as e:
143        print("Connection error, reconnecting\n", str(e))
144        # If we lose connectivity, reset the wifi and reconnect
145        wifi.reset()
146        wifi.connect()
147        device.reconnect()
148        continue
149
150    time.sleep(1)

Update the properties of the device, and receive updates to properties.

examples/azureiot_esp32spi/azureiot_central_properties.py
  1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
  2# SPDX-License-Identifier: MIT
  3
  4import random
  5import time
  6import board
  7import busio
  8from digitalio import DigitalInOut
  9import neopixel
 10import rtc
 11from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
 12import adafruit_connection_manager
 13
 14# Get wifi details and more from a secrets.py file
 15try:
 16    from secrets import secrets
 17except ImportError:
 18    print("WiFi secrets are kept in secrets.py, please add them there!")
 19    raise
 20
 21# ESP32 Setup
 22try:
 23    esp32_cs = DigitalInOut(board.ESP_CS)
 24    esp32_ready = DigitalInOut(board.ESP_BUSY)
 25    esp32_reset = DigitalInOut(board.ESP_RESET)
 26except AttributeError:
 27    esp32_cs = DigitalInOut(board.D13)
 28    esp32_ready = DigitalInOut(board.D11)
 29    esp32_reset = DigitalInOut(board.D12)
 30
 31spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
 32esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
 33
 34"""Use below for Most Boards"""
 35status_light = neopixel.NeoPixel(
 36    board.NEOPIXEL, 1, brightness=0.2
 37)  # Uncomment for Most Boards
 38"""Uncomment below for ItsyBitsy M4"""
 39# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
 40# Uncomment below for an externally defined RGB LED
 41# import adafruit_rgbled
 42# from adafruit_esp32spi import PWMOut
 43# RED_LED = PWMOut.PWMOut(esp, 26)
 44# GREEN_LED = PWMOut.PWMOut(esp, 27)
 45# BLUE_LED = PWMOut.PWMOut(esp, 25)
 46# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)
 47wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
 48
 49print("Connecting to WiFi...")
 50
 51wifi.connect()
 52
 53print("Connected to WiFi!")
 54
 55print("Getting the time...")
 56
 57# get_time will raise ValueError if the time isn't available yet so loop until
 58# it works.
 59now_utc = None
 60while now_utc is None:
 61    try:
 62        now_utc = time.localtime(esp.get_time()[0])
 63    except ValueError:
 64        pass
 65rtc.RTC().datetime = now_utc
 66
 67print("Time:", str(time.time()))
 68
 69# To use Azure IoT Central, you will need to create an IoT Central app.
 70# You can either create a free tier app that will live for 7 days without an Azure subscription,
 71# Or a standard tier app that will last for ever with an Azure subscription.
 72# The standard tiers are free for up to 2 devices
 73#
 74# If you don't have an Azure subscription:
 75#
 76# If you are a student, head to https://aka.ms/FreeStudentAzure and sign up, validating with your
 77#  student email address. This will give you $100 of Azure credit and free tiers of a load of
 78#  service, renewable each year you are a student
 79#
 80# If you are not a student, head to https://aka.ms/FreeAz and sign up to get $200 of credit for 30
 81#  days, as well as free tiers of a load of services
 82#
 83# Create an Azure IoT Central app by following these instructions:
 84# https://aka.ms/CreateIoTCentralApp
 85# Add a device template with telemetry, properties and commands, as well as a view to visualize the
 86# telemetry and execute commands, and a form to set properties.
 87#
 88# Next create a device using the device template, and select Connect to get the device connection
 89# details.
 90# Add the connection details to your secrets.py file, using the following values:
 91#
 92# 'id_scope' - the devices ID scope
 93# 'device_id' - the devices device id
 94# 'device_sas_key' - the devices primary key
 95#
 96# The adafruit-circuitpython-azureiot library depends on the following libraries:
 97#
 98# From the Adafruit CircuitPython Bundle https://github.com/adafruit/Adafruit_CircuitPython_Bundle:
 99# * adafruit-circuitpython-minimqtt
100from adafruit_azureiot import IoTCentralDevice  # pylint: disable=wrong-import-position
101
102pool = adafruit_connection_manager.get_radio_socketpool(esp)
103ssl_context = adafruit_connection_manager.get_radio_ssl_context(esp)
104# Create an IoT Hub device client and connect
105device = IoTCentralDevice(
106    pool,
107    ssl_context,
108    secrets["id_scope"],
109    secrets["device_id"],
110    secrets["device_sas_key"],
111)
112
113
114# Subscribe to property changes
115# Properties can be updated either in code, or by adding a form to the view
116# in the device template, and setting the value on the dashboard for the device
117def property_changed(property_name, property_value, version):
118    print(
119        "Property",
120        property_name,
121        "updated to",
122        str(property_value),
123        "version",
124        str(version),
125    )
126
127
128# Subscribe to the property changed event
129device.on_property_changed = property_changed
130
131print("Connecting to Azure IoT Central...")
132
133# Connect to IoT Central
134device.connect()
135
136print("Connected to Azure IoT Central!")
137
138message_counter = 60
139
140while True:
141    try:
142        # Send property values every minute
143        # You can see the values in the devices dashboard
144        if message_counter >= 60:
145            device.send_property("Desired_Temperature", random.randint(0, 50))
146            message_counter = 0
147        else:
148            message_counter += 1
149
150        # Poll every second for messages from the cloud
151        device.loop()
152    except (ValueError, RuntimeError) as e:
153        print("Connection error, reconnecting\n", str(e))
154        wifi.reset()
155        wifi.connect()
156        device.reconnect()
157        continue
158    time.sleep(1)

Handle connection errors.

examples/azureiot_esp32spi/azureiot_central_notconnected.py
  1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
  2# SPDX-License-Identifier: MIT
  3
  4import json
  5import random
  6import time
  7import board
  8import busio
  9from digitalio import DigitalInOut
 10import neopixel
 11import rtc
 12from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
 13import adafruit_connection_manager
 14
 15# Get wifi details and more from a secrets.py file
 16try:
 17    from secrets import secrets
 18except ImportError:
 19    print("WiFi secrets are kept in secrets.py, please add them there!")
 20    raise
 21
 22# ESP32 Setup
 23try:
 24    esp32_cs = DigitalInOut(board.ESP_CS)
 25    esp32_ready = DigitalInOut(board.ESP_BUSY)
 26    esp32_reset = DigitalInOut(board.ESP_RESET)
 27except AttributeError:
 28    esp32_cs = DigitalInOut(board.D13)
 29    esp32_ready = DigitalInOut(board.D11)
 30    esp32_reset = DigitalInOut(board.D12)
 31
 32spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
 33esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
 34
 35"""Use below for Most Boards"""
 36status_light = neopixel.NeoPixel(
 37    board.NEOPIXEL, 1, brightness=0.2
 38)  # Uncomment for Most Boards
 39"""Uncomment below for ItsyBitsy M4"""
 40# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
 41# Uncomment below for an externally defined RGB LED
 42# import adafruit_rgbled
 43# from adafruit_esp32spi import PWMOut
 44# RED_LED = PWMOut.PWMOut(esp, 26)
 45# GREEN_LED = PWMOut.PWMOut(esp, 27)
 46# BLUE_LED = PWMOut.PWMOut(esp, 25)
 47# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)
 48wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
 49
 50print("Connecting to WiFi...")
 51
 52wifi.connect()
 53
 54print("Connected to WiFi!")
 55
 56print("Getting the time...")
 57
 58rtc.RTC().datetime = time.localtime(esp.get_time()[0])
 59
 60print("Time:", str(time.time()))
 61
 62# To use Azure IoT Central, you will need to create an IoT Central app.
 63# You can either create a free tier app that will live for 7 days without an Azure subscription,
 64# Or a standard tier app that will last for ever with an Azure subscription.
 65# The standard tiers are free for up to 2 devices
 66#
 67# If you don't have an Azure subscription:
 68#
 69# If you are a student, head to https://aka.ms/FreeStudentAzure and sign up, validating with your
 70#  student email address. This will give you $100 of Azure credit and free tiers of a load of
 71#  service, renewable each year you are a student
 72#
 73# If you are not a student, head to https://aka.ms/FreeAz and sign up to get $200 of credit for 30
 74#  days, as well as free tiers of a load of services
 75#
 76# Create an Azure IoT Central app by following these instructions:
 77# https://aka.ms/CreateIoTCentralApp
 78# Add a device template with telemetry, properties and commands, as well as a view to visualize the
 79# telemetry and execute commands, and a form to set properties.
 80#
 81# Next create a device using the device template, and select Connect to get the device connection
 82# details.
 83# Add the connection details to your secrets.py file, using the following values:
 84#
 85# 'id_scope' - the devices ID scope
 86# 'device_id' - the devices device id
 87# 'device_sas_key' - the devices primary key
 88#
 89# The adafruit-circuitpython-azureiot library depends on the following libraries:
 90#
 91# From the Adafruit CircuitPython Bundle https://github.com/adafruit/Adafruit_CircuitPython_Bundle:
 92# * adafruit-circuitpython-minimqtt
 93# pylint: disable=wrong-import-position
 94from adafruit_azureiot import (
 95    IoTCentralDevice,
 96    IoTError,
 97)
 98
 99# pylint: enable=wrong-import-position
100
101pool = adafruit_connection_manager.get_radio_socketpool(esp)
102ssl_context = adafruit_connection_manager.get_radio_ssl_context(esp)
103# Create an IoT Hub device client and connect
104device = IoTCentralDevice(
105    pool,
106    ssl_context,
107    secrets["id_scope"],
108    secrets["device_id"],
109    secrets["device_sas_key"],
110)
111
112# don't connect
113# device.connect()
114
115try:
116    message = {"Temperature": random.randint(0, 50)}
117    device.send_telemetry(json.dumps(message))
118except IoTError as iot_error:
119    print("Error - ", iot_error.message)

IoT Hub Native Networking

Ensure your IoT Hub device works with this simple test.

examples/azureiot_native_networking/azureiot_hub_simpletest.py
  1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
  2# SPDX-License-Identifier: MIT
  3
  4import json
  5import random
  6import time
  7
  8import rtc
  9import wifi
 10
 11import adafruit_connection_manager
 12import adafruit_ntp
 13from adafruit_azureiot import IoTHubDevice
 14
 15# Get wifi details and more from a secrets.py file
 16try:
 17    from secrets import secrets
 18except ImportError:
 19    print("WiFi secrets are kept in secrets.py, please add them there!")
 20    raise
 21
 22print("Connecting to WiFi...")
 23wifi.radio.connect(secrets["ssid"], secrets["password"])
 24
 25pool = adafruit_connection_manager.get_radio_socketpool(wifi.radio)
 26ssl_context = adafruit_connection_manager.get_radio_ssl_context(wifi.radio)
 27
 28print("Connected to WiFi!")
 29
 30if time.localtime().tm_year < 2022:
 31    print("Setting System Time in UTC")
 32    ntp = adafruit_ntp.NTP(pool, tz_offset=0)
 33
 34    # NOTE: This changes the system time so make sure you aren't assuming that time
 35    # doesn't jump.
 36    rtc.RTC().datetime = ntp.datetime
 37else:
 38    print("Year seems good, skipping set time.")
 39
 40# You will need an Azure subscription to create an Azure IoT Hub resource
 41#
 42# If you don't have an Azure subscription:
 43#
 44# If you are a student, head to https://aka.ms/FreeStudentAzure and sign up, validating with your
 45#  student email address. This will give you $100 of Azure credit and free tiers of a load of
 46#  service, renewable each year you are a student
 47#
 48# If you are not a student, head to https://aka.ms/FreeAz and sign up to get $200 of credit for 30
 49#  days, as well as free tiers of a load of services
 50#
 51# Create an Azure IoT Hub and an IoT device in the Azure portal here:
 52# https://aka.ms/AzurePortalHome.
 53# Instructions to create an IoT Hub and device are here: https://aka.ms/CreateIoTHub
 54#
 55# The free tier of IoT Hub allows up to 8,000 messages a day, so try not to send messages too often
 56# if you are using the free tier
 57#
 58# Once you have a hub and a device, copy the device primary connection string.
 59# Add it to the secrets.py file in an entry called device_connection_string
 60#
 61# The adafruit-circuitpython-azureiot library depends on the following libraries:
 62#
 63# From the Adafruit CircuitPython Bundle https://github.com/adafruit/Adafruit_CircuitPython_Bundle:
 64# * adafruit-circuitpython-minimqtt
 65
 66
 67# Create an IoT Hub device client and connect
 68device = IoTHubDevice(pool, ssl_context, secrets["device_connection_string"])
 69
 70print("Connecting to Azure IoT Hub...")
 71
 72# Connect to IoT Central
 73device.connect()
 74
 75print("Connected to Azure IoT Hub!")
 76
 77message_counter = 60
 78
 79while True:
 80    try:
 81        # Send a device to cloud message every minute
 82        # You can see the overview of messages sent from the device in the Overview tab
 83        # of the IoT Hub in the Azure Portal
 84        if message_counter >= 60:
 85            message = {"Temperature": random.randint(0, 50)}
 86            device.send_device_to_cloud_message(json.dumps(message))
 87            message_counter = 0
 88        else:
 89            message_counter += 1
 90
 91        # Poll every second for messages from the cloud
 92        device.loop()
 93    except (ValueError, RuntimeError) as e:
 94        print("Connection error, reconnecting\n", str(e))
 95        # If we lose connectivity, reset the wifi and reconnect
 96        wifi.radio.enabled = False
 97        wifi.radio.enabled = True
 98        wifi.radio.connect(secrets["ssid"], secrets["password"])
 99        device.reconnect()
100        continue
101    time.sleep(1)

Handle direct methods.

examples/azureiot_native_networking/azureiot_hub_directmethods.py
  1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
  2# SPDX-License-Identifier: MIT
  3
  4import time
  5
  6import rtc
  7import wifi
  8
  9import adafruit_connection_manager
 10import adafruit_ntp
 11from adafruit_azureiot import IoTHubDevice
 12from adafruit_azureiot.iot_mqtt import IoTResponse
 13
 14# Get wifi details and more from a secrets.py file
 15try:
 16    from secrets import secrets
 17except ImportError:
 18    print("WiFi secrets are kept in secrets.py, please add them there!")
 19    raise
 20
 21print("Connecting to WiFi...")
 22wifi.radio.connect(secrets["ssid"], secrets["password"])
 23
 24pool = adafruit_connection_manager.get_radio_socketpool(wifi.radio)
 25ssl_context = adafruit_connection_manager.get_radio_ssl_context(wifi.radio)
 26
 27print("Connected to WiFi!")
 28
 29if time.localtime().tm_year < 2022:
 30    print("Setting System Time in UTC")
 31    ntp = adafruit_ntp.NTP(pool, tz_offset=0)
 32
 33    # NOTE: This changes the system time so make sure you aren't assuming that time
 34    # doesn't jump.
 35    rtc.RTC().datetime = ntp.datetime
 36else:
 37    print("Year seems good, skipping set time.")
 38
 39# You will need an Azure subscription to create an Azure IoT Hub resource
 40#
 41# If you don't have an Azure subscription:
 42#
 43# If you are a student, head to https://aka.ms/FreeStudentAzure and sign up, validating with your
 44#  student email address. This will give you $100 of Azure credit and free tiers of a load of
 45#  service, renewable each year you are a student
 46#
 47# If you are not a student, head to https://aka.ms/FreeAz and sign up to get $200 of credit for 30
 48#  days, as well as free tiers of a load of services
 49#
 50# Create an Azure IoT Hub and an IoT device in the Azure portal here:
 51# https://aka.ms/AzurePortalHome.
 52# Instructions to create an IoT Hub and device are here: https://aka.ms/CreateIoTHub
 53#
 54# The free tier of IoT Hub allows up to 8,000 messages a day, so try not to send messages too often
 55# if you are using the free tier
 56#
 57# Once you have a hub and a device, copy the device primary connection string.
 58# Add it to the secrets.py file in an entry called device_connection_string
 59#
 60# The adafruit-circuitpython-azureiot library depends on the following libraries:
 61#
 62# From the Adafruit CircuitPython Bundle https://github.com/adafruit/Adafruit_CircuitPython_Bundle:
 63# * adafruit-circuitpython-minimqtt
 64
 65
 66# Create an IoT Hub device client and connect
 67device = IoTHubDevice(pool, ssl_context, secrets["device_connection_string"])
 68
 69
 70# Subscribe to direct method calls
 71# To invoke a method on the device, select it in the Azure Portal, select Direct Method,
 72# fill in the method name and payload, then select Invoke Method
 73# Direct method handlers need to return a response to show if the method was handled
 74# successfully or not, returning an HTTP status code and message
 75def direct_method_invoked(method_name: str, payload) -> IoTResponse:
 76    print("Received direct method", method_name, "with data", str(payload))
 77    # return a status code and message to indicate if the direct method was handled correctly
 78    return IoTResponse(200, "OK")
 79
 80
 81# Subscribe to the direct method invoked event
 82device.on_direct_method_invoked = direct_method_invoked
 83print("Connecting to Azure IoT Hub...")
 84
 85# Connect to IoT Central
 86device.connect()
 87
 88print("Connected to Azure IoT Hub!")
 89
 90while True:
 91    try:
 92        # Poll every second for messages from the cloud
 93        device.loop()
 94    except (ValueError, RuntimeError) as e:
 95        print("Connection error, reconnecting\n", str(e))
 96        # If we lose connectivity, reset the wifi and reconnect
 97        wifi.radio.enabled = False
 98        wifi.radio.enabled = True
 99        wifi.radio.connect(secrets["ssid"], secrets["password"])
100        device.reconnect()
101        continue
102
103    time.sleep(1)

Send device to cloud messages, and handle cloud to device messages.

examples/azureiot_native_networking/azureiot_hub_messages.py
  1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
  2# SPDX-License-Identifier: MIT
  3
  4import json
  5import random
  6import time
  7
  8import rtc
  9import wifi
 10
 11import adafruit_connection_manager
 12import adafruit_ntp
 13from adafruit_azureiot import IoTHubDevice
 14
 15# Get wifi details and more from a secrets.py file
 16try:
 17    from secrets import secrets
 18except ImportError:
 19    print("WiFi secrets are kept in secrets.py, please add them there!")
 20    raise
 21
 22print("Connecting to WiFi...")
 23wifi.radio.connect(secrets["ssid"], secrets["password"])
 24
 25pool = adafruit_connection_manager.get_radio_socketpool(wifi.radio)
 26ssl_context = adafruit_connection_manager.get_radio_ssl_context(wifi.radio)
 27
 28print("Connected to WiFi!")
 29
 30if time.localtime().tm_year < 2022:
 31    print("Setting System Time in UTC")
 32    ntp = adafruit_ntp.NTP(pool, tz_offset=0)
 33
 34    # NOTE: This changes the system time so make sure you aren't assuming that time
 35    # doesn't jump.
 36    rtc.RTC().datetime = ntp.datetime
 37else:
 38    print("Year seems good, skipping set time.")
 39
 40# You will need an Azure subscription to create an Azure IoT Hub resource
 41#
 42# If you don't have an Azure subscription:
 43#
 44# If you are a student, head to https://aka.ms/FreeStudentAzure and sign up, validating with your
 45#  student email address. This will give you $100 of Azure credit and free tiers of a load of
 46#  service, renewable each year you are a student
 47#
 48# If you are not a student, head to https://aka.ms/FreeAz and sign up to get $200 of credit for 30
 49#  days, as well as free tiers of a load of services
 50#
 51# Create an Azure IoT Hub and an IoT device in the Azure portal here:
 52# https://aka.ms/AzurePortalHome.
 53# Instructions to create an IoT Hub and device are here: https://aka.ms/CreateIoTHub
 54#
 55# The free tier of IoT Hub allows up to 8,000 messages a day, so try not to send messages too often
 56# if you are using the free tier
 57#
 58# Once you have a hub and a device, copy the device primary connection string.
 59# Add it to the secrets.py file in an entry called device_connection_string
 60#
 61# The adafruit-circuitpython-azureiot library depends on the following libraries:
 62#
 63# From the Adafruit CircuitPython Bundle https://github.com/adafruit/Adafruit_CircuitPython_Bundle:
 64# * adafruit-circuitpython-minimqtt
 65
 66
 67# Create an IoT Hub device client and connect
 68device = IoTHubDevice(pool, ssl_context, secrets["device_connection_string"])
 69
 70
 71# Subscribe to cloud to device messages
 72# To send a message to the device, select it in the Azure Portal, select Message To Device,
 73# fill in the message and any properties you want to add, then select Send Message
 74def cloud_to_device_message_received(body: str, properties: dict):
 75    print("Received message with body", body, "and properties", json.dumps(properties))
 76
 77
 78# Subscribe to the cloud to device message received events
 79device.on_cloud_to_device_message_received = cloud_to_device_message_received
 80
 81print("Connecting to Azure IoT Hub...")
 82device.connect()
 83
 84print("Connected to Azure IoT Hub!")
 85
 86message_counter = 60
 87
 88while True:
 89    try:
 90        # Send a device to cloud message every minute
 91        # You can see the overview of messages sent from the device in the Overview tab
 92        # of the IoT Hub in the Azure Portal
 93        if message_counter >= 60:
 94            message = {"Temperature": random.randint(0, 50)}
 95            device.send_device_to_cloud_message(json.dumps(message))
 96            message_counter = 0
 97        else:
 98            message_counter += 1
 99
100        # Poll every second for messages from the cloud
101        device.loop()
102    except (ValueError, RuntimeError) as e:
103        print("Connection error, reconnecting\n", str(e))
104        # If we lose connectivity, reset the wifi and reconnect
105        wifi.radio.enabled = False
106        wifi.radio.enabled = True
107        wifi.radio.connect(secrets["ssid"], secrets["password"])
108        device.reconnect()
109        continue
110    time.sleep(1)

Update the reported properties of the devices device twin, and receive updates to desired properties.

examples/azureiot_native_networking/azureiot_hub_twin_operations.py
  1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
  2# SPDX-License-Identifier: MIT
  3
  4import random
  5import time
  6
  7import rtc
  8import wifi
  9
 10import adafruit_connection_manager
 11import adafruit_ntp
 12from adafruit_azureiot import IoTHubDevice
 13
 14# Get wifi details and more from a secrets.py file
 15try:
 16    from secrets import secrets
 17except ImportError:
 18    print("WiFi secrets are kept in secrets.py, please add them there!")
 19    raise
 20
 21print("Connecting to WiFi...")
 22wifi.radio.connect(secrets["ssid"], secrets["password"])
 23
 24pool = adafruit_connection_manager.get_radio_socketpool(wifi.radio)
 25ssl_context = adafruit_connection_manager.get_radio_ssl_context(wifi.radio)
 26
 27print("Connected to WiFi!")
 28
 29if time.localtime().tm_year < 2022:
 30    print("Setting System Time in UTC")
 31    ntp = adafruit_ntp.NTP(pool, tz_offset=0)
 32
 33    # NOTE: This changes the system time so make sure you aren't assuming that time
 34    # doesn't jump.
 35    rtc.RTC().datetime = ntp.datetime
 36else:
 37    print("Year seems good, skipping set time.")
 38
 39# You will need an Azure subscription to create an Azure IoT Hub resource
 40#
 41# If you don't have an Azure subscription:
 42#
 43# If you are a student, head to https://aka.ms/FreeStudentAzure and sign up, validating with your
 44#  student email address. This will give you $100 of Azure credit and free tiers of a load of
 45#  service, renewable each year you are a student
 46#
 47# If you are not a student, head to https://aka.ms/FreeAz and sign up to get $200 of credit for 30
 48#  days, as well as free tiers of a load of services
 49#
 50# Create an Azure IoT Hub and an IoT device in the Azure portal here:
 51# https://aka.ms/AzurePortalHome.
 52# Instructions to create an IoT Hub and device are here: https://aka.ms/CreateIoTHub
 53#
 54# The free tier of IoT Hub allows up to 8,000 messages a day, so try not to send messages too often
 55# if you are using the free tier
 56#
 57# Once you have a hub and a device, copy the device primary connection string.
 58# Add it to the secrets.py file in an entry called device_connection_string
 59#
 60# The adafruit-circuitpython-azureiot library depends on the following libraries:
 61#
 62# From the Adafruit CircuitPython Bundle https://github.com/adafruit/Adafruit_CircuitPython_Bundle:
 63# * adafruit-circuitpython-minimqtt
 64
 65
 66# Create an IoT Hub device client and connect
 67device = IoTHubDevice(pool, ssl_context, secrets["device_connection_string"])
 68
 69
 70# Subscribe to device twin desired property updates
 71# To see these changes, update the desired properties for the device either in code
 72# or in the Azure portal by selecting the device in the IoT Hub blade, selecting
 73# Device Twin then adding or amending an entry in the 'desired' section
 74def device_twin_desired_updated(
 75    desired_property_name: str, desired_property_value, desired_version: int
 76):
 77    print(
 78        "Property",
 79        desired_property_name,
 80        "updated to",
 81        str(desired_property_value),
 82        "version",
 83        desired_version,
 84    )
 85
 86
 87# Subscribe to the device twin desired property updated event
 88device.on_device_twin_desired_updated = device_twin_desired_updated
 89
 90print("Connecting to Azure IoT Hub...")
 91device.connect()
 92
 93print("Connected to Azure IoT Hub!")
 94
 95message_counter = 60
 96
 97while True:
 98    try:
 99        if message_counter >= 60:
100            # Send a reported property twin update every minute
101            # You can see these in the portal by selecting the device in the IoT Hub blade,
102            # selecting device Twin then looking for the updates in the 'reported' section
103            patch = {"Temperature": random.randint(0, 50)}
104            device.update_twin(patch)
105            message_counter = 0
106        else:
107            message_counter += 1
108
109        # Poll every second for messages from the cloud
110        device.loop()
111    except (ValueError, RuntimeError) as e:
112        print("Connection error, reconnecting\n", str(e))
113        # If we lose connectivity, reset the wifi and reconnect
114        wifi.radio.enabled = False
115        wifi.radio.enabled = True
116        wifi.radio.connect(secrets["ssid"], secrets["password"])
117        device.reconnect()
118        continue
119    time.sleep(1)

IoT Central Native Networking

Ensure your IoT Central device works with this simple test.

examples/azureiot_native_networking/azureiot_central_simpletest.py
  1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
  2# SPDX-License-Identifier: MIT
  3
  4import json
  5import random
  6import time
  7
  8import rtc
  9import wifi
 10
 11import adafruit_connection_manager
 12import adafruit_ntp
 13from adafruit_azureiot import IoTCentralDevice
 14
 15# Get wifi details and more from a secrets.py file
 16try:
 17    from secrets import secrets
 18except ImportError:
 19    print("WiFi secrets are kept in secrets.py, please add them there!")
 20    raise
 21
 22print("Connecting to WiFi...")
 23wifi.radio.connect(secrets["ssid"], secrets["password"])
 24
 25pool = adafruit_connection_manager.get_radio_socketpool(wifi.radio)
 26ssl_context = adafruit_connection_manager.get_radio_ssl_context(wifi.radio)
 27
 28print("Connected to WiFi!")
 29
 30if time.localtime().tm_year < 2022:
 31    print("Setting System Time in UTC")
 32    ntp = adafruit_ntp.NTP(pool, tz_offset=0)
 33
 34    # NOTE: This changes the system time so make sure you aren't assuming that time
 35    # doesn't jump.
 36    rtc.RTC().datetime = ntp.datetime
 37else:
 38    print("Year seems good, skipping set time.")
 39
 40# To use Azure IoT Central, you will need to create an IoT Central app.
 41# You can either create a free tier app that will live for 7 days without an Azure subscription,
 42# Or a standard tier app that will last for ever with an Azure subscription.
 43# The standard tiers are free for up to 2 devices
 44#
 45# If you don't have an Azure subscription:
 46#
 47# If you are a student, head to https://aka.ms/FreeStudentAzure and sign up, validating with your
 48#  student email address. This will give you $100 of Azure credit and free tiers of a load of
 49#  service, renewable each year you are a student
 50#
 51# If you are not a student, head to https://aka.ms/FreeAz and sign up to get $200 of credit for 30
 52#  days, as well as free tiers of a load of services
 53#
 54# Create an Azure IoT Central app by following these instructions:
 55# https://aka.ms/CreateIoTCentralApp
 56# Add a device template with telemetry, properties and commands, as well as a view to visualize the
 57# telemetry and execute commands, and a form to set properties.
 58#
 59# Next create a device using the device template, and select Connect to get the device connection
 60# details.
 61# Add the connection details to your secrets.py file, using the following values:
 62#
 63# 'id_scope' - the devices ID scope
 64# 'device_id' - the devices device id
 65# 'device_sas_key' - the devices primary key
 66#
 67# The adafruit-circuitpython-azureiot library depends on the following libraries:
 68#
 69# From the Adafruit CircuitPython Bundle https://github.com/adafruit/Adafruit_CircuitPython_Bundle:
 70# * adafruit-circuitpython-minimqtt
 71
 72
 73# Create an IoT Hub device client and connect
 74device = IoTCentralDevice(
 75    pool,
 76    ssl_context,
 77    secrets["id_scope"],
 78    secrets["device_id"],
 79    secrets["device_sas_key"],
 80)
 81
 82print("Connecting to Azure IoT Central...")
 83device.connect()
 84
 85print("Connected to Azure IoT Central!")
 86
 87message_counter = 60
 88
 89while True:
 90    try:
 91        # Send telemetry every minute
 92        # You can see the values in the devices dashboard
 93        if message_counter >= 60:
 94            message = {"Temperature": random.randint(0, 50)}
 95            device.send_telemetry(json.dumps(message))
 96            message_counter = 0
 97        else:
 98            message_counter += 1
 99
100        # Poll every second for messages from the cloud
101        device.loop()
102    except (ValueError, RuntimeError) as e:
103        print("Connection error, reconnecting\n", str(e))
104        wifi.radio.enabled = False
105        wifi.radio.enabled = True
106        wifi.radio.connect(secrets["ssid"], secrets["password"])
107        device.reconnect()
108        continue
109    time.sleep(1)

Handle commands.

examples/azureiot_native_networking/azureiot_central_commands.py
  1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
  2# SPDX-License-Identifier: MIT
  3
  4import time
  5
  6import rtc
  7import wifi
  8
  9import adafruit_connection_manager
 10import adafruit_ntp
 11from adafruit_azureiot import IoTCentralDevice
 12from adafruit_azureiot.iot_mqtt import IoTResponse
 13
 14# Get wifi details and more from a secrets.py file
 15try:
 16    from secrets import secrets
 17except ImportError:
 18    print("WiFi secrets are kept in secrets.py, please add them there!")
 19    raise
 20
 21print("Connecting to WiFi...")
 22wifi.radio.connect(secrets["ssid"], secrets["password"])
 23
 24pool = adafruit_connection_manager.get_radio_socketpool(wifi.radio)
 25ssl_context = adafruit_connection_manager.get_radio_ssl_context(wifi.radio)
 26
 27print("Connected to WiFi!")
 28
 29if time.localtime().tm_year < 2022:
 30    print("Setting System Time in UTC")
 31    ntp = adafruit_ntp.NTP(pool, tz_offset=0)
 32
 33    # NOTE: This changes the system time so make sure you aren't assuming that time
 34    # doesn't jump.
 35    rtc.RTC().datetime = ntp.datetime
 36else:
 37    print("Year seems good, skipping set time.")
 38
 39# To use Azure IoT Central, you will need to create an IoT Central app.
 40# You can either create a free tier app that will live for 7 days without an Azure subscription,
 41# Or a standard tier app that will last for ever with an Azure subscription.
 42# The standard tiers are free for up to 2 devices
 43#
 44# If you don't have an Azure subscription:
 45#
 46# If you are a student, head to https://aka.ms/FreeStudentAzure and sign up, validating with your
 47#  student email address. This will give you $100 of Azure credit and free tiers of a load of
 48#  service, renewable each year you are a student
 49#
 50# If you are not a student, head to https://aka.ms/FreeAz and sign up to get $200 of credit for 30
 51#  days, as well as free tiers of a load of services
 52#
 53# Create an Azure IoT Central app by following these instructions:
 54# https://aka.ms/CreateIoTCentralApp
 55# Add a device template with telemetry, properties and commands, as well as a view to visualize the
 56# telemetry and execute commands, and a form to set properties.
 57#
 58# Next create a device using the device template, and select Connect to get the device connection
 59# details.
 60# Add the connection details to your secrets.py file, using the following values:
 61#
 62# 'id_scope' - the devices ID scope
 63# 'device_id' - the devices device id
 64# 'device_sas_key' - the devices primary key
 65#
 66# The adafruit-circuitpython-azureiot library depends on the following libraries:
 67#
 68# From the Adafruit CircuitPython Bundle https://github.com/adafruit/Adafruit_CircuitPython_Bundle:
 69# * adafruit-circuitpython-minimqtt
 70
 71
 72# Create an IoT Hub device client and connect
 73device = IoTCentralDevice(
 74    pool,
 75    ssl_context,
 76    secrets["id_scope"],
 77    secrets["device_id"],
 78    secrets["device_sas_key"],
 79)
 80
 81
 82# Subscribe to commands
 83# Commands can be sent from the devices Dashboard in IoT Central, assuming
 84# the device template and view has been set up with the commands
 85# Command handlers need to return a response to show if the command was handled
 86# successfully or not, returning an HTTP status code and message
 87def command_executed(command_name: str, payload) -> IoTResponse:
 88    print("Command", command_name, "executed with payload", str(payload))
 89    # return a status code and message to indicate if the command was handled correctly
 90    return IoTResponse(200, "OK")
 91
 92
 93# Subscribe to the command execute event
 94device.on_command_executed = command_executed
 95
 96
 97print("Connecting to Azure IoT Central...")
 98device.connect()
 99
100print("Connected to Azure IoT Central!")
101
102message_counter = 60
103
104while True:
105    try:
106        # Poll every second for messages from the cloud
107        device.loop()
108    except (ValueError, RuntimeError) as e:
109        print("Connection error, reconnecting\n", str(e))
110        # If we lose connectivity, reset the wifi and reconnect
111        wifi.reset()
112        wifi.connect()
113        device.reconnect()
114        continue
115
116    time.sleep(1)

Update the properties of the device, and receive updates to properties.

examples/azureiot_native_networking/azureiot_central_properties.py
  1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
  2# SPDX-License-Identifier: MIT
  3
  4import random
  5import time
  6
  7import rtc
  8import wifi
  9
 10import adafruit_connection_manager
 11import adafruit_ntp
 12from adafruit_azureiot import IoTCentralDevice
 13
 14# Get wifi details and more from a secrets.py file
 15try:
 16    from secrets import secrets
 17except ImportError:
 18    print("WiFi secrets are kept in secrets.py, please add them there!")
 19    raise
 20
 21print("Connecting to WiFi...")
 22wifi.radio.connect(secrets["ssid"], secrets["password"])
 23
 24pool = adafruit_connection_manager.get_radio_socketpool(wifi.radio)
 25ssl_context = adafruit_connection_manager.get_radio_ssl_context(wifi.radio)
 26
 27print("Connected to WiFi!")
 28
 29if time.localtime().tm_year < 2022:
 30    print("Setting System Time in UTC")
 31    ntp = adafruit_ntp.NTP(pool, tz_offset=0)
 32
 33    # NOTE: This changes the system time so make sure you aren't assuming that time
 34    # doesn't jump.
 35    rtc.RTC().datetime = ntp.datetime
 36else:
 37    print("Year seems good, skipping set time.")
 38
 39# To use Azure IoT Central, you will need to create an IoT Central app.
 40# You can either create a free tier app that will live for 7 days without an Azure subscription,
 41# Or a standard tier app that will last for ever with an Azure subscription.
 42# The standard tiers are free for up to 2 devices
 43#
 44# If you don't have an Azure subscription:
 45#
 46# If you are a student, head to https://aka.ms/FreeStudentAzure and sign up, validating with your
 47#  student email address. This will give you $100 of Azure credit and free tiers of a load of
 48#  service, renewable each year you are a student
 49#
 50# If you are not a student, head to https://aka.ms/FreeAz and sign up to get $200 of credit for 30
 51#  days, as well as free tiers of a load of services
 52#
 53# Create an Azure IoT Central app by following these instructions:
 54# https://aka.ms/CreateIoTCentralApp
 55# Add a device template with telemetry, properties and commands, as well as a view to visualize the
 56# telemetry and execute commands, and a form to set properties.
 57#
 58# Next create a device using the device template, and select Connect to get the device connection
 59# details.
 60# Add the connection details to your secrets.py file, using the following values:
 61#
 62# 'id_scope' - the devices ID scope
 63# 'device_id' - the devices device id
 64# 'device_sas_key' - the devices primary key
 65#
 66# The adafruit-circuitpython-azureiot library depends on the following libraries:
 67#
 68# From the Adafruit CircuitPython Bundle https://github.com/adafruit/Adafruit_CircuitPython_Bundle:
 69# * adafruit-circuitpython-minimqtt
 70
 71
 72# Create an IoT Hub device client and connect
 73device = IoTCentralDevice(
 74    pool,
 75    ssl_context,
 76    secrets["id_scope"],
 77    secrets["device_id"],
 78    secrets["device_sas_key"],
 79)
 80
 81
 82# Subscribe to property changes
 83# Properties can be updated either in code, or by adding a form to the view
 84# in the device template, and setting the value on the dashboard for the device
 85def property_changed(property_name, property_value, version):
 86    print(
 87        "Property",
 88        property_name,
 89        "updated to",
 90        str(property_value),
 91        "version",
 92        str(version),
 93    )
 94
 95
 96# Subscribe to the property changed event
 97device.on_property_changed = property_changed
 98
 99print("Connecting to Azure IoT Central...")
100device.connect()
101
102print("Connected to Azure IoT Central!")
103
104message_counter = 60
105
106while True:
107    try:
108        # Send property values every minute
109        # You can see the values in the devices dashboard
110        if message_counter >= 60:
111            device.send_property("Desired_Temperature", random.randint(0, 50))
112            message_counter = 0
113        else:
114            message_counter += 1
115
116        # Poll every second for messages from the cloud
117        device.loop()
118    except (ValueError, RuntimeError) as e:
119        print("Connection error, reconnecting\n", str(e))
120        wifi.reset()
121        wifi.connect()
122        device.reconnect()
123        continue
124    time.sleep(1)

Handle connection errors.

examples/azureiot_native_networking/azureiot_central_notconnected.py
 1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
 2# SPDX-License-Identifier: MIT
 3
 4import json
 5import random
 6import time
 7
 8import rtc
 9import wifi
10
11import adafruit_connection_manager
12import adafruit_ntp
13from adafruit_azureiot import (
14    IoTCentralDevice,
15    IoTError,
16)
17
18# Get wifi details and more from a secrets.py file
19try:
20    from secrets import secrets
21except ImportError:
22    print("WiFi secrets are kept in secrets.py, please add them there!")
23    raise
24
25print("Connecting to WiFi...")
26wifi.radio.connect(secrets["ssid"], secrets["password"])
27
28pool = adafruit_connection_manager.get_radio_socketpool(wifi.radio)
29ssl_context = adafruit_connection_manager.get_radio_ssl_context(wifi.radio)
30
31print("Connected to WiFi!")
32
33if time.localtime().tm_year < 2022:
34    print("Setting System Time in UTC")
35    ntp = adafruit_ntp.NTP(pool, tz_offset=0)
36
37    # NOTE: This changes the system time so make sure you aren't assuming that time
38    # doesn't jump.
39    rtc.RTC().datetime = ntp.datetime
40else:
41    print("Year seems good, skipping set time.")
42
43# To use Azure IoT Central, you will need to create an IoT Central app.
44# You can either create a free tier app that will live for 7 days without an Azure subscription,
45# Or a standard tier app that will last for ever with an Azure subscription.
46# The standard tiers are free for up to 2 devices
47#
48# If you don't have an Azure subscription:
49#
50# If you are a student, head to https://aka.ms/FreeStudentAzure and sign up, validating with your
51#  student email address. This will give you $100 of Azure credit and free tiers of a load of
52#  service, renewable each year you are a student
53#
54# If you are not a student, head to https://aka.ms/FreeAz and sign up to get $200 of credit for 30
55#  days, as well as free tiers of a load of services
56#
57# Create an Azure IoT Central app by following these instructions:
58# https://aka.ms/CreateIoTCentralApp
59# Add a device template with telemetry, properties and commands, as well as a view to visualize the
60# telemetry and execute commands, and a form to set properties.
61#
62# Next create a device using the device template, and select Connect to get the device connection
63# details.
64# Add the connection details to your secrets.py file, using the following values:
65#
66# 'id_scope' - the devices ID scope
67# 'device_id' - the devices device id
68# 'device_sas_key' - the devices primary key
69#
70# The adafruit-circuitpython-azureiot library depends on the following libraries:
71#
72# From the Adafruit CircuitPython Bundle https://github.com/adafruit/Adafruit_CircuitPython_Bundle:
73# * adafruit-circuitpython-minimqtt
74
75
76# Create an IoT Hub device client and connect
77device = IoTCentralDevice(
78    pool,
79    ssl_context,
80    secrets["id_scope"],
81    secrets["device_id"],
82    secrets["device_sas_key"],
83)
84
85# don't connect
86# device.connect()
87
88try:
89    message = {"Temperature": random.randint(0, 50)}
90    device.send_telemetry(json.dumps(message))
91except IoTError as iot_error:
92    print("Error - ", iot_error.message)