IoT Hub

Ensure your IoT Hub device works with this simple test.

examples/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
 11from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
 12import adafruit_esp32spi.adafruit_esp32spi_socket as socket
 13from adafruit_ntp import NTP
 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
 58ntp = NTP(esp)
 59# Wait for a valid time to be received
 60while not ntp.valid_time:
 61    time.sleep(5)
 62    ntp.set_time()
 63
 64print("Time:", str(time.time()))
 65
 66# You will need an Azure subscription to create an Azure IoT Hub resource
 67#
 68# If you don't have an Azure subscription:
 69#
 70# If you are a student, head to https://aka.ms/FreeStudentAzure and sign up, validating with your
 71#  student email address. This will give you $100 of Azure credit and free tiers of a load of
 72#  service, renewable each year you are a student
 73#
 74# If you are not a student, head to https://aka.ms/FreeAz and sign up to get $200 of credit for 30
 75#  days, as well as free tiers of a load of services
 76#
 77# Create an Azure IoT Hub and an IoT device in the Azure portal here: https://aka.ms/AzurePortalHome.
 78# Instructions to create an IoT Hub and device are here: https://aka.ms/CreateIoTHub
 79#
 80# The free tier of IoT Hub allows up to 8,000 messages a day, so try not to send messages too often
 81# if you are using the free tier
 82#
 83# Once you have a hub and a device, copy the device primary connection string.
 84# Add it to the secrets.py file in an entry called device_connection_string
 85#
 86# The adafruit-circuitpython-azureiot library depends on the following libraries:
 87#
 88# From the Adafruit CircuitPython Bundle (https://github.com/adafruit/Adafruit_CircuitPython_Bundle):
 89# * adafruit-circuitpython-minimqtt
 90# * adafruit-circuitpython-requests
 91from adafruit_azureiot import IoTHubDevice  # pylint: disable=wrong-import-position
 92
 93# Create an IoT Hub device client and connect
 94device = IoTHubDevice(socket, esp, secrets["device_connection_string"])
 95
 96print("Connecting to Azure IoT Hub...")
 97
 98# Connect to IoT Central
 99device.connect()
100
101print("Connected to Azure IoT Hub!")
102
103message_counter = 60
104
105while True:
106    try:
107        # Send a device to cloud message every minute
108        # You can see the overview of messages sent from the device in the Overview tab
109        # of the IoT Hub in the Azure Portal
110        if message_counter >= 60:
111            message = {"Temperature": random.randint(0, 50)}
112            device.send_device_to_cloud_message(json.dumps(message))
113            message_counter = 0
114        else:
115            message_counter = message_counter + 1
116
117        # Poll every second for messages from the cloud
118        device.loop()
119    except (ValueError, RuntimeError) as e:
120        print("Connection error, reconnecting\n", str(e))
121        # If we lose connectivity, reset the wifi and reconnect
122        wifi.reset()
123        wifi.connect()
124        device.reconnect()
125        continue
126
127    time.sleep(1)

Handle direct methods.

examples/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
  9from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
 10import adafruit_esp32spi.adafruit_esp32spi_socket as socket
 11from adafruit_ntp import NTP
 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
 56ntp = NTP(esp)
 57# Wait for a valid time to be received
 58while not ntp.valid_time:
 59    time.sleep(5)
 60    ntp.set_time()
 61
 62print("Time:", str(time.time()))
 63
 64# You will need an Azure subscription to create an Azure IoT Hub resource
 65#
 66# If you don't have an Azure subscription:
 67#
 68# If you are a student, head to https://aka.ms/FreeStudentAzure and sign up, validating with your
 69#  student email address. This will give you $100 of Azure credit and free tiers of a load of
 70#  service, renewable each year you are a student
 71#
 72# If you are not a student, head to https://aka.ms/FreeAz and sign up to get $200 of credit for 30
 73#  days, as well as free tiers of a load of services
 74#
 75# Create an Azure IoT Hub and an IoT device in the Azure portal here: https://aka.ms/AzurePortalHome.
 76# Instructions to create an IoT Hub and device are here: https://aka.ms/CreateIoTHub
 77#
 78# The free tier of IoT Hub allows up to 8,000 messages a day, so try not to send messages too often
 79# if you are using the free tier
 80#
 81# Once you have a hub and a device, copy the device primary connection string.
 82# Add it to the secrets.py file in an entry called device_connection_string
 83#
 84# The adafruit-circuitpython-azureiot library depends on the following libraries:
 85#
 86# From the Adafruit CircuitPython Bundle (https://github.com/adafruit/Adafruit_CircuitPython_Bundle):
 87# * adafruit-circuitpython-minimqtt
 88# * adafruit-circuitpython-requests
 89# pylint: disable=wrong-import-position
 90from adafruit_azureiot import IoTHubDevice
 91from adafruit_azureiot.iot_mqtt import IoTResponse
 92
 93# pylint: enable=wrong-import-position
 94
 95# Create an IoT Hub device client and connect
 96device = IoTHubDevice(socket, esp, secrets["device_connection_string"])
 97
 98# Subscribe to direct method calls
 99# To invoke a method on the device, select it in the Azure Portal, select Direct Method,
100# fill in the method name and payload, then select Invoke Method
101# Direct method handlers need to return a response to show if the method was handled
102# successfully or not, returning an HTTP status code and message
103def direct_method_invoked(method_name: str, payload) -> IoTResponse:
104    print("Received direct method", method_name, "with data", str(payload))
105    # return a status code and message to indicate if the direct method was handled correctly
106    return IoTResponse(200, "OK")
107
108
109# Subscribe to the direct method invoked event
110device.on_direct_method_invoked = direct_method_invoked
111
112print("Connecting to Azure IoT Hub...")
113
114# Connect to IoT Central
115device.connect()
116
117print("Connected to Azure IoT Hub!")
118
119while True:
120    try:
121        # Poll every second for messages from the cloud
122        device.loop()
123    except (ValueError, RuntimeError) as e:
124        print("Connection error, reconnecting\n", str(e))
125        # If we lose connectivity, reset the wifi and reconnect
126        wifi.reset()
127        wifi.connect()
128        device.reconnect()
129        continue
130
131    time.sleep(1)

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

examples/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
 11from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
 12import adafruit_esp32spi.adafruit_esp32spi_socket as socket
 13from adafruit_ntp import NTP
 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
 58ntp = NTP(esp)
 59# Wait for a valid time to be received
 60while not ntp.valid_time:
 61    time.sleep(5)
 62    ntp.set_time()
 63
 64print("Time:", str(time.time()))
 65
 66# You will need an Azure subscription to create an Azure IoT Hub resource
 67#
 68# If you don't have an Azure subscription:
 69#
 70# If you are a student, head to https://aka.ms/FreeStudentAzure and sign up, validating with your
 71#  student email address. This will give you $100 of Azure credit and free tiers of a load of
 72#  service, renewable each year you are a student
 73#
 74# If you are not a student, head to https://aka.ms/FreeAz and sign up to get $200 of credit for 30
 75#  days, as well as free tiers of a load of services
 76#
 77# Create an Azure IoT Hub and an IoT device in the Azure portal here: https://aka.ms/AzurePortalHome.
 78# Instructions to create an IoT Hub and device are here: https://aka.ms/CreateIoTHub
 79#
 80# The free tier of IoT Hub allows up to 8,000 messages a day, so try not to send messages too often
 81# if you are using the free tier
 82#
 83# Once you have a hub and a device, copy the device primary connection string.
 84# Add it to the secrets.py file in an entry called device_connection_string
 85#
 86# The adafruit-circuitpython-azureiot library depends on the following libraries:
 87#
 88# From the Adafruit CircuitPython Bundle (https://github.com/adafruit/Adafruit_CircuitPython_Bundle):
 89# * adafruit-circuitpython-minimqtt
 90# * adafruit-circuitpython-requests
 91from adafruit_azureiot import IoTHubDevice  # pylint: disable=wrong-import-position
 92
 93# Create an IoT Hub device client and connect
 94device = IoTHubDevice(socket, esp, secrets["device_connection_string"])
 95
 96# Subscribe to cloud to device messages
 97# To send a message to the device, select it in the Azure Portal, select Message To Device,
 98# fill in the message and any properties you want to add, then select Send Message
 99def cloud_to_device_message_received(body: str, properties: dict):
100    print("Received message with body", body, "and properties", json.dumps(properties))
101
102
103# Subscribe to the cloud to device message received events
104device.on_cloud_to_device_message_received = cloud_to_device_message_received
105
106print("Connecting to Azure IoT Hub...")
107
108# Connect to IoT Central
109device.connect()
110
111print("Connected to Azure IoT Hub!")
112
113message_counter = 60
114
115while True:
116    try:
117        # Send a device to cloud message every minute
118        # You can see the overview of messages sent from the device in the Overview tab
119        # of the IoT Hub in the Azure Portal
120        if message_counter >= 60:
121            message = {"Temperature": random.randint(0, 50)}
122            device.send_device_to_cloud_message(json.dumps(message))
123            message_counter = 0
124        else:
125            message_counter = message_counter + 1
126
127        # Poll every second for messages from the cloud
128        device.loop()
129    except (ValueError, RuntimeError) as e:
130        print("Connection error, reconnecting\n", str(e))
131        # If we lose connectivity, reset the wifi and reconnect
132        wifi.reset()
133        wifi.connect()
134        device.reconnect()
135        continue
136
137    time.sleep(1)

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

examples/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
 10from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
 11import adafruit_esp32spi.adafruit_esp32spi_socket as socket
 12from adafruit_ntp import NTP
 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
 57ntp = NTP(esp)
 58# Wait for a valid time to be received
 59while not ntp.valid_time:
 60    time.sleep(5)
 61    ntp.set_time()
 62
 63print("Time:", str(time.time()))
 64
 65# You will need an Azure subscription to create an Azure IoT Hub resource
 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 Hub and an IoT device in the Azure portal here: https://aka.ms/AzurePortalHome.
 77# Instructions to create an IoT Hub and device are here: https://aka.ms/CreateIoTHub
 78#
 79# The free tier of IoT Hub allows up to 8,000 messages a day, so try not to send messages too often
 80# if you are using the free tier
 81#
 82# Once you have a hub and a device, copy the device primary connection string.
 83# Add it to the secrets.py file in an entry called device_connection_string
 84#
 85# To us twins, you will need either a free or standard tier IoT Hub. Basic tier doesn't
 86# support twins
 87#
 88# The adafruit-circuitpython-azureiot library depends on the following libraries:
 89#
 90# From the Adafruit CircuitPython Bundle (https://github.com/adafruit/Adafruit_CircuitPython_Bundle):
 91# * adafruit-circuitpython-minimqtt
 92# * adafruit-circuitpython-requests
 93from adafruit_azureiot import IoTHubDevice  # pylint: disable=wrong-import-position
 94
 95# Create an IoT Hub device client and connect
 96device = IoTHubDevice(socket, esp, secrets["device_connection_string"])
 97
 98# Subscribe to device twin desired property updates
 99# To see these changes, update the desired properties for the device either in code
100# or in the Azure portal by selecting the device in the IoT Hub blade, selecting
101# Device Twin then adding or amending an entry in the 'desired' section
102def device_twin_desired_updated(
103    desired_property_name: str, desired_property_value, desired_version: int
104):
105    print(
106        "Property",
107        desired_property_name,
108        "updated to",
109        str(desired_property_value),
110        "version",
111        desired_version,
112    )
113
114
115# Subscribe to the device twin desired property updated event
116device.on_device_twin_desired_updated = device_twin_desired_updated
117
118print("Connecting to Azure IoT Hub...")
119
120# Connect to IoT Central
121device.connect()
122
123print("Connected to Azure IoT Hub!")
124
125message_counter = 60
126
127while True:
128    try:
129        if message_counter >= 60:
130            # Send a reported property twin update every minute
131            # You can see these in the portal by selecting the device in the IoT Hub blade, selecting
132            # Device Twin then looking for the updates in the 'reported' section
133            patch = {"Temperature": random.randint(0, 50)}
134            device.update_twin(patch)
135            message_counter = 0
136        else:
137            message_counter = message_counter + 1
138
139        # Poll every second for messages from the cloud
140        device.loop()
141    except (ValueError, RuntimeError) as e:
142        print("Connection error, reconnecting\n", str(e))
143        # If we lose connectivity, reset the wifi and reconnect
144        wifi.reset()
145        wifi.connect()
146        device.reconnect()
147        continue
148
149    time.sleep(1)

IoT Central

Ensure your IoT Central device works with this simple test.

examples/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
 11from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
 12import adafruit_esp32spi.adafruit_esp32spi_socket as socket
 13from adafruit_ntp import NTP
 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
 58ntp = NTP(esp)
 59# Wait for a valid time to be received
 60while not ntp.valid_time:
 61    time.sleep(5)
 62    ntp.set_time()
 63
 64print("Time:", str(time.time()))
 65
 66# To use Azure IoT Central, you will need to create an IoT Central app.
 67# You can either create a free tier app that will live for 7 days without an Azure subscription,
 68# Or a standard tier app that will last for ever with an Azure subscription.
 69# The standard tiers are free for up to 2 devices
 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 Central app by following these instructions: https://aka.ms/CreateIoTCentralApp
 81# Add a device template with telemetry, properties and commands, as well as a view to visualize the
 82# telemetry and execute commands, and a form to set properties.
 83#
 84# Next create a device using the device template, and select Connect to get the device connection details.
 85# Add the connection details to your secrets.py file, using the following values:
 86#
 87# 'id_scope' - the devices ID scope
 88# 'device_id' - the devices device id
 89# 'key' - the devices primary key
 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
 95# * adafruit-circuitpython-requests
 96from adafruit_azureiot import IoTCentralDevice  # pylint: disable=wrong-import-position
 97
 98# Create an IoT Hub device client and connect
 99device = IoTCentralDevice(
100    socket, esp, secrets["id_scope"], secrets["device_id"], secrets["key"]
101)
102
103print("Connecting to Azure IoT Central...")
104
105# Connect to IoT Central
106device.connect()
107
108print("Connected to Azure IoT Central!")
109
110message_counter = 60
111
112while True:
113    try:
114        # Send telemetry every minute
115        # You can see the values in the devices dashboard
116        if message_counter >= 60:
117            message = {"Temperature": random.randint(0, 50)}
118            device.send_telemetry(json.dumps(message))
119            message_counter = 0
120        else:
121            message_counter = 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        # If we lose connectivity, reset the wifi and reconnect
128        wifi.reset()
129        wifi.connect()
130        device.reconnect()
131        continue
132
133    time.sleep(1)

Handle commands.

examples/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
  9from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
 10import adafruit_esp32spi.adafruit_esp32spi_socket as socket
 11from adafruit_ntp import NTP
 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
 56ntp = NTP(esp)
 57# Wait for a valid time to be received
 58while not ntp.valid_time:
 59    time.sleep(5)
 60    ntp.set_time()
 61
 62print("Time:", str(time.time()))
 63
 64# To use Azure IoT Central, you will need to create an IoT Central app.
 65# You can either create a free tier app that will live for 7 days without an Azure subscription,
 66# Or a standard tier app that will last for ever with an Azure subscription.
 67# The standard tiers are free for up to 2 devices
 68#
 69# If you don't have an Azure subscription:
 70#
 71# If you are a student, head to https://aka.ms/FreeStudentAzure and sign up, validating with your
 72#  student email address. This will give you $100 of Azure credit and free tiers of a load of
 73#  service, renewable each year you are a student
 74#
 75# If you are not a student, head to https://aka.ms/FreeAz and sign up to get $200 of credit for 30
 76#  days, as well as free tiers of a load of services
 77#
 78# Create an Azure IoT Central app by following these instructions: https://aka.ms/CreateIoTCentralApp
 79# Add a device template with telemetry, properties and commands, as well as a view to visualize the
 80# telemetry and execute commands, and a form to set properties.
 81#
 82# Next create a device using the device template, and select Connect to get the device connection 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# '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# * adafruit-circuitpython-requests
 94# pylint: disable=wrong-import-position
 95from adafruit_azureiot import IoTCentralDevice
 96from adafruit_azureiot.iot_mqtt import IoTResponse
 97
 98# pylint: enable=wrong-import-position
 99
100# Create an IoT Hub device client and connect
101device = IoTCentralDevice(
102    socket, esp, secrets["id_scope"], secrets["device_id"], secrets["key"]
103)
104
105# Subscribe to commands
106# Commands can be sent from the devices Dashboard in IoT Central, assuming
107# the device template and view has been set up with the commands
108# Command handlers need to return a response to show if the command was handled
109# successfully or not, returning an HTTP status code and message
110def command_executed(command_name: str, payload) -> IoTResponse:
111    print("Command", command_name, "executed with payload", str(payload))
112    # return a status code and message to indicate if the command was handled correctly
113    return IoTResponse(200, "OK")
114
115
116# Subscribe to the command execute event
117device.on_command_executed = command_executed
118
119print("Connecting to Azure IoT Central...")
120
121# Connect to IoT Central
122device.connect()
123
124print("Connected to Azure IoT Central!")
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)

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

examples/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
 10from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
 11import adafruit_esp32spi.adafruit_esp32spi_socket as socket
 12from adafruit_ntp import NTP
 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
 57ntp = NTP(esp)
 58# Wait for a valid time to be received
 59while not ntp.valid_time:
 60    time.sleep(5)
 61    ntp.set_time()
 62
 63print("Time:", str(time.time()))
 64
 65# To use Azure IoT Central, you will need to create an IoT Central app.
 66# You can either create a free tier app that will live for 7 days without an Azure subscription,
 67# Or a standard tier app that will last for ever with an Azure subscription.
 68# The standard tiers are free for up to 2 devices
 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 Central app by following these instructions: https://aka.ms/CreateIoTCentralApp
 80# Add a device template with telemetry, properties and commands, as well as a view to visualize the
 81# telemetry and execute commands, and a form to set properties.
 82#
 83# Next create a device using the device template, and select Connect to get the device connection details.
 84# Add the connection details to your secrets.py file, using the following values:
 85#
 86# 'id_scope' - the devices ID scope
 87# 'device_id' - the devices device id
 88# 'key' - the devices primary key
 89#
 90# The adafruit-circuitpython-azureiot library depends on the following libraries:
 91#
 92# From the Adafruit CircuitPython Bundle (https://github.com/adafruit/Adafruit_CircuitPython_Bundle):
 93# * adafruit-circuitpython-minimqtt
 94# * adafruit-circuitpython-requests
 95from adafruit_azureiot import IoTCentralDevice  # pylint: disable=wrong-import-position
 96
 97# Create an IoT Hub device client and connect
 98device = IoTCentralDevice(
 99    socket, esp, secrets["id_scope"], secrets["device_id"], secrets["key"]
100)
101
102# Subscribe to property changes
103# Properties can be updated either in code, or by adding a form to the view
104# in the device template, and setting the value on the dashboard for the device
105def property_changed(property_name, property_value, version):
106    print(
107        "Property",
108        property_name,
109        "updated to",
110        str(property_value),
111        "version",
112        str(version),
113    )
114
115
116# Subscribe to the property changed event
117device.on_property_changed = property_changed
118
119print("Connecting to Azure IoT Central...")
120
121# Connect to IoT Central
122device.connect()
123
124print("Connected to Azure IoT Central!")
125
126message_counter = 60
127
128while True:
129    try:
130        # Send property values every minute
131        # You can see the values in the devices dashboard
132        if message_counter >= 60:
133            device.send_property("Desired_Temperature", random.randint(0, 50))
134            message_counter = 0
135        else:
136            message_counter = message_counter + 1
137
138        # Poll every second for messages from the cloud
139        device.loop()
140    except (ValueError, RuntimeError) as e:
141        print("Connection error, reconnecting\n", str(e))
142        # If we lose connectivity, reset the wifi and reconnect
143        wifi.reset()
144        wifi.connect()
145        device.reconnect()
146        continue
147
148    time.sleep(1)

Handle connection errors.

examples/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
 11from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
 12import adafruit_esp32spi.adafruit_esp32spi_socket as socket
 13from adafruit_ntp import NTP
 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
 58ntp = NTP(esp)
 59# Wait for a valid time to be received
 60while not ntp.valid_time:
 61    time.sleep(5)
 62    ntp.set_time()
 63
 64print("Time:", str(time.time()))
 65
 66# To use Azure IoT Central, you will need to create an IoT Central app.
 67# You can either create a free tier app that will live for 7 days without an Azure subscription,
 68# Or a standard tier app that will last for ever with an Azure subscription.
 69# The standard tiers are free for up to 2 devices
 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 Central app by following these instructions: https://aka.ms/CreateIoTCentralApp
 81# Add a device template with telemetry, properties and commands, as well as a view to visualize the
 82# telemetry and execute commands, and a form to set properties.
 83#
 84# Next create a device using the device template, and select Connect to get the device connection details.
 85# Add the connection details to your secrets.py file, using the following values:
 86#
 87# 'id_scope' - the devices ID scope
 88# 'device_id' - the devices device id
 89# 'key' - the devices primary key
 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
 95# * adafruit-circuitpython-requests
 96# pylint: disable=wrong-import-position
 97from adafruit_azureiot import (
 98    IoTCentralDevice,
 99    IoTError,
100)
101
102# pylint: enable=wrong-import-position
103
104# Create an IoT Hub device client and connect
105device = IoTCentralDevice(
106    socket, esp, secrets["id_scope"], secrets["device_id"], secrets["key"]
107)
108
109# don't connect
110# device.connect()
111
112try:
113    message = {"Temperature": random.randint(0, 50)}
114    device.send_telemetry(json.dumps(message))
115except IoTError as iot_error:
116    print("Error - ", iot_error.message)