IoT Hub ESP32 AirLift Networking
Ensure your IoT Hub device works with this simple test.
1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
2# SPDX-License-Identifier: MIT
3
4import json
5import random
6import time
7from os import getenv
8
9import adafruit_connection_manager
10import board
11import busio
12import neopixel
13import rtc
14from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
15from digitalio import DigitalInOut
16
17# Get WiFi details and Azure keys, ensure these are setup in settings.toml
18ssid = getenv("CIRCUITPY_WIFI_SSID")
19password = getenv("CIRCUITPY_WIFI_PASSWORD")
20device_connection_string = getenv("device_connection_string")
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_pixel = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards
37"""Uncomment below for ItsyBitsy M4"""
38# status_pixel = 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_pixel = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)
46wifi = adafruit_esp32spi_wifimanager.WiFiManager(esp, ssid, password, status_pixel=status_pixel)
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 settings.toml 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
93from adafruit_azureiot import IoTHubDevice
94
95pool = adafruit_connection_manager.get_radio_socketpool(esp)
96ssl_context = adafruit_connection_manager.get_radio_ssl_context(esp)
97# Create an IoT Hub device client and connect
98device = IoTHubDevice(pool, ssl_context, device_connection_string)
99
100print("Connecting to Azure IoT Hub...")
101
102# Connect to IoT Central
103device.connect()
104
105print("Connected to Azure IoT Hub!")
106
107message_counter = 60
108
109while True:
110 try:
111 # Send a device to cloud message every minute
112 # You can see the overview of messages sent from the device in the Overview tab
113 # of the IoT Hub in the Azure Portal
114 if message_counter >= 60:
115 message = {"Temperature": random.randint(0, 50)}
116 device.send_device_to_cloud_message(json.dumps(message))
117 message_counter = 0
118 else:
119 message_counter += 1
120
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 wifi.reset()
126 wifi.connect()
127 device.reconnect()
128 continue
129 time.sleep(1)
Handle direct methods.
1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
2# SPDX-License-Identifier: MIT
3
4import time
5from os import getenv
6
7import adafruit_connection_manager
8import board
9import busio
10import neopixel
11import rtc
12from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
13from digitalio import DigitalInOut
14
15# Get WiFi details and Azure keys, ensure these are setup in settings.toml
16ssid = getenv("CIRCUITPY_WIFI_SSID")
17password = getenv("CIRCUITPY_WIFI_PASSWORD")
18device_connection_string = getenv("device_connection_string")
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_pixel = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards
35"""Uncomment below for ItsyBitsy M4"""
36# status_pixel = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
37# Uncomment below for an externally defined RGB LED
38# import adafruit_rgbled
39# from adafruit_esp32spi import PWMOut
40# RED_LED = PWMOut.PWMOut(esp, 26)
41# GREEN_LED = PWMOut.PWMOut(esp, 27)
42# BLUE_LED = PWMOut.PWMOut(esp, 25)
43# status_pixel = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)
44wifi = adafruit_esp32spi_wifimanager.WiFiManager(esp, ssid, password, status_pixel=status_pixel)
45
46print("Connecting to WiFi...")
47
48wifi.connect()
49
50print("Connected to WiFi!")
51
52print("Getting the time...")
53
54# get_time will raise ValueError if the time isn't available yet so loop until
55# it works.
56now_utc = None
57while now_utc is None:
58 try:
59 now_utc = time.localtime(esp.get_time()[0])
60 except ValueError:
61 pass
62rtc.RTC().datetime = now_utc
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:
78# https://aka.ms/AzurePortalHome.
79# Instructions to create an IoT Hub and device are here: https://aka.ms/CreateIoTHub
80#
81# The free tier of IoT Hub allows up to 8,000 messages a day, so try not to send messages too often
82# if you are using the free tier
83#
84# Once you have a hub and a device, copy the device primary connection string.
85# Add it to the settings.toml file in an entry called device_connection_string
86#
87# The adafruit-circuitpython-azureiot library depends on the following libraries:
88#
89# From the Adafruit CircuitPython Bundle https://github.com/adafruit/Adafruit_CircuitPython_Bundle:
90# * adafruit-circuitpython-minimqtt
91from adafruit_azureiot import IoTHubDevice
92from adafruit_azureiot.iot_mqtt import IoTResponse
93
94pool = adafruit_connection_manager.get_radio_socketpool(esp)
95ssl_context = adafruit_connection_manager.get_radio_ssl_context(esp)
96# Create an IoT Hub device client and connect
97device = IoTHubDevice(pool, ssl_context, device_connection_string)
98
99
100# Subscribe to direct method calls
101# To invoke a method on the device, select it in the Azure Portal, select Direct Method,
102# fill in the method name and payload, then select Invoke Method
103# Direct method handlers need to return a response to show if the method was handled
104# successfully or not, returning an HTTP status code and message
105def direct_method_invoked(method_name: str, payload) -> IoTResponse:
106 print("Received direct method", method_name, "with data", str(payload))
107 # return a status code and message to indicate if the direct method was handled correctly
108 return IoTResponse(200, "OK")
109
110
111# Subscribe to the direct method invoked event
112device.on_direct_method_invoked = direct_method_invoked
113
114print("Connecting to Azure IoT Hub...")
115
116# Connect to IoT Central
117device.connect()
118
119print("Connected to Azure IoT Hub!")
120
121while True:
122 try:
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)
Send device to cloud messages, and handle cloud to device messages.
1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
2# SPDX-License-Identifier: MIT
3
4import json
5import random
6import time
7from os import getenv
8
9import adafruit_connection_manager
10import board
11import busio
12import neopixel
13import rtc
14from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
15from digitalio import DigitalInOut
16
17# Get WiFi details and Azure keys, ensure these are setup in settings.toml
18ssid = getenv("CIRCUITPY_WIFI_SSID")
19password = getenv("CIRCUITPY_WIFI_PASSWORD")
20device_connection_string = getenv("device_connection_string")
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_pixel = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards
37"""Uncomment below for ItsyBitsy M4"""
38# status_pixel = 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_pixel = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)
46wifi = adafruit_esp32spi_wifimanager.WiFiManager(esp, ssid, password, status_pixel=status_pixel)
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 settings.toml 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
93from adafruit_azureiot import IoTHubDevice
94
95pool = adafruit_connection_manager.get_radio_socketpool(esp)
96ssl_context = adafruit_connection_manager.get_radio_ssl_context(esp)
97# Create an IoT Hub device client and connect
98device = IoTHubDevice(pool, ssl_context, device_connection_string)
99
100
101# Subscribe to cloud to device messages
102# To send a message to the device, select it in the Azure Portal, select Message To Device,
103# fill in the message and any properties you want to add, then select Send Message
104def cloud_to_device_message_received(body: str, properties: dict):
105 print("Received message with body", body, "and properties", json.dumps(properties))
106
107
108# Subscribe to the cloud to device message received events
109device.on_cloud_to_device_message_received = cloud_to_device_message_received
110
111print("Connecting to Azure IoT Hub...")
112
113# Connect to IoT Central
114device.connect()
115
116print("Connected to Azure IoT Hub!")
117
118message_counter = 60
119
120while True:
121 try:
122 # Send a device to cloud message every minute
123 # You can see the overview of messages sent from the device in the Overview tab
124 # of the IoT Hub in the Azure Portal
125 if message_counter >= 60:
126 message = {"Temperature": random.randint(0, 50)}
127 device.send_device_to_cloud_message(json.dumps(message))
128 message_counter = 0
129 else:
130 message_counter += 1
131
132 # Poll every second for messages from the cloud
133 device.loop()
134 except (ValueError, RuntimeError) as e:
135 print("Connection error, reconnecting\n", str(e))
136 wifi.reset()
137 wifi.connect()
138 device.reconnect()
139 continue
140 time.sleep(1)
Update the reported properties of the devices device twin, and receive updates to desired properties.
1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
2# SPDX-License-Identifier: MIT
3
4import random
5import time
6from os import getenv
7
8import adafruit_connection_manager
9import board
10import busio
11import neopixel
12import rtc
13from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
14from digitalio import DigitalInOut
15
16# Get WiFi details and Azure keys, ensure these are setup in settings.toml
17ssid = getenv("CIRCUITPY_WIFI_SSID")
18password = getenv("CIRCUITPY_WIFI_PASSWORD")
19device_connection_string = getenv("device_connection_string")
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_pixel = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards
36"""Uncomment below for ItsyBitsy M4"""
37# status_pixel = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
38# Uncomment below for an externally defined RGB LED
39# import adafruit_rgbled
40# from adafruit_esp32spi import PWMOut
41# RED_LED = PWMOut.PWMOut(esp, 26)
42# GREEN_LED = PWMOut.PWMOut(esp, 27)
43# BLUE_LED = PWMOut.PWMOut(esp, 25)
44# status_pixel = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)
45wifi = adafruit_esp32spi_wifimanager.WiFiManager(esp, ssid, password, status_pixel=status_pixel)
46
47print("Connecting to WiFi...")
48
49wifi.connect()
50
51print("Connected to WiFi!")
52
53print("Getting the time...")
54
55# get_time will raise ValueError if the time isn't available yet so loop until
56# it works.
57now_utc = None
58while now_utc is None:
59 try:
60 now_utc = time.localtime(esp.get_time()[0])
61 except ValueError:
62 pass
63rtc.RTC().datetime = now_utc
64
65print("Time:", str(time.time()))
66
67# You will need an Azure subscription to create an Azure IoT Hub resource
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 Hub and an IoT device in the Azure portal here:
79# https://aka.ms/AzurePortalHome.
80# Instructions to create an IoT Hub and device are here: https://aka.ms/CreateIoTHub
81#
82# The free tier of IoT Hub allows up to 8,000 messages a day, so try not to send messages too often
83# if you are using the free tier
84#
85# Once you have a hub and a device, copy the device primary connection string.
86# Add it to the settings.toml file in an entry called device_connection_string
87#
88# To us twins, you will need either a free or standard tier IoT Hub. Basic tier doesn't
89# support twins
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
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, device_connection_string)
101
102
103# Subscribe to device twin desired property updates
104# To see these changes, update the desired properties for the device either in code
105# or in the Azure portal by selecting the device in the IoT Hub blade, selecting
106# Device Twin then adding or amending an entry in the 'desired' section
107def device_twin_desired_updated(
108 desired_property_name: str, desired_property_value, desired_version: int
109):
110 print(
111 "Property",
112 desired_property_name,
113 "updated to",
114 str(desired_property_value),
115 "version",
116 desired_version,
117 )
118
119
120# Subscribe to the device twin desired property updated event
121device.on_device_twin_desired_updated = device_twin_desired_updated
122
123print("Connecting to Azure IoT Hub...")
124
125# Connect to IoT Central
126device.connect()
127
128print("Connected to Azure IoT Hub!")
129
130message_counter = 60
131
132while True:
133 try:
134 if message_counter >= 60:
135 # Send a reported property twin update every minute
136 # You can see these in the portal by selecting the device in the IoT Hub blade,
137 # selecting device Twin then looking for the updates in the 'reported' section
138 patch = {"Temperature": random.randint(0, 50)}
139 device.update_twin(patch)
140 message_counter = 0
141 else:
142 message_counter += 1
143
144 # Poll every second for messages from the cloud
145 device.loop()
146 except (ValueError, RuntimeError) as e:
147 print("Connection error, reconnecting\n", str(e))
148 wifi.reset()
149 wifi.connect()
150 device.reconnect()
151 continue
152 time.sleep(1)
IoT Central ESP32 AirLift Networking
Ensure your IoT Central device works with this simple test.
1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
2# SPDX-License-Identifier: MIT
3
4import json
5import random
6import time
7from os import getenv
8
9import adafruit_connection_manager
10import board
11import busio
12import neopixel
13import rtc
14from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
15from digitalio import DigitalInOut
16
17# Get WiFi details and AWS Keys, ensure these are setup in settings.toml
18ssid = getenv("CIRCUITPY_WIFI_SSID")
19password = getenv("CIRCUITPY_WIFI_PASSWORD")
20id_scope = getenv("id_scope")
21device_id = getenv("device_id")
22device_sas_key = getenv("device_sas_key")
23
24# ESP32 Setup
25try:
26 esp32_cs = DigitalInOut(board.ESP_CS)
27 esp32_ready = DigitalInOut(board.ESP_BUSY)
28 esp32_reset = DigitalInOut(board.ESP_RESET)
29except AttributeError:
30 esp32_cs = DigitalInOut(board.D13)
31 esp32_ready = DigitalInOut(board.D11)
32 esp32_reset = DigitalInOut(board.D12)
33
34spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
35esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
36
37"""Use below for Most Boards"""
38status_pixel = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards
39"""Uncomment below for ItsyBitsy M4"""
40# status_pixel = 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_pixel = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)
48wifi = adafruit_esp32spi_wifimanager.WiFiManager(esp, ssid, password, status_pixel=status_pixel)
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 settings.toml 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
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 id_scope,
110 device_id,
111 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.
1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
2# SPDX-License-Identifier: MIT
3
4import time
5from os import getenv
6
7import adafruit_connection_manager
8import board
9import busio
10import neopixel
11import rtc
12from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
13from digitalio import DigitalInOut
14
15# Get WiFi details and AWS Keys, ensure these are setup in settings.toml
16ssid = getenv("CIRCUITPY_WIFI_SSID")
17password = getenv("CIRCUITPY_WIFI_PASSWORD")
18id_scope = getenv("id_scope")
19device_id = getenv("device_id")
20device_sas_key = getenv("device_sas_key")
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_pixel = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards
37"""Uncomment below for ItsyBitsy M4"""
38# status_pixel = 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_pixel = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)
46wifi = adafruit_esp32spi_wifimanager.WiFiManager(esp, ssid, password, status_pixel=status_pixel)
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 settings.toml 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
99from adafruit_azureiot import IoTCentralDevice
100from adafruit_azureiot.iot_mqtt import IoTResponse
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 id_scope,
109 device_id,
110 device_sas_key,
111)
112
113
114# Subscribe to commands
115# Commands can be sent from the devices Dashboard in IoT Central, assuming
116# the device template and view has been set up with the commands
117# Command handlers need to return a response to show if the command was handled
118# successfully or not, returning an HTTP status code and message
119def command_executed(command_name: str, payload) -> IoTResponse:
120 print("Command", command_name, "executed with payload", str(payload))
121 # return a status code and message to indicate if the command was handled correctly
122 return IoTResponse(200, "OK")
123
124
125# Subscribe to the command execute event
126device.on_command_executed = command_executed
127
128print("Connecting to Azure IoT Central...")
129
130# Connect to IoT Central
131device.connect()
132
133print("Connected to Azure IoT Central!")
134
135while True:
136 try:
137 # Poll every second for messages from the cloud
138 device.loop()
139 except (ValueError, RuntimeError) as e:
140 print("Connection error, reconnecting\n", str(e))
141 # If we lose connectivity, reset the wifi and reconnect
142 wifi.reset()
143 wifi.connect()
144 device.reconnect()
145 continue
146
147 time.sleep(1)
Update the properties of the device, and receive updates to properties.
1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
2# SPDX-License-Identifier: MIT
3
4import random
5import time
6from os import getenv
7
8import adafruit_connection_manager
9import board
10import busio
11import neopixel
12import rtc
13from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
14from digitalio import DigitalInOut
15
16# Get WiFi details and AWS Keys, ensure these are setup in settings.toml
17ssid = getenv("CIRCUITPY_WIFI_SSID")
18password = getenv("CIRCUITPY_WIFI_PASSWORD")
19id_scope = getenv("id_scope")
20device_id = getenv("device_id")
21device_sas_key = getenv("device_sas_key")
22
23# ESP32 Setup
24try:
25 esp32_cs = DigitalInOut(board.ESP_CS)
26 esp32_ready = DigitalInOut(board.ESP_BUSY)
27 esp32_reset = DigitalInOut(board.ESP_RESET)
28except AttributeError:
29 esp32_cs = DigitalInOut(board.D13)
30 esp32_ready = DigitalInOut(board.D11)
31 esp32_reset = DigitalInOut(board.D12)
32
33spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
34esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
35
36"""Use below for Most Boards"""
37status_pixel = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards
38"""Uncomment below for ItsyBitsy M4"""
39# status_pixel = 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_pixel = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)
47wifi = adafruit_esp32spi_wifimanager.WiFiManager(esp, ssid, password, status_pixel=status_pixel)
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 settings.toml 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
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 id_scope,
109 device_id,
110 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.
1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
2# SPDX-License-Identifier: MIT
3
4import json
5import random
6import time
7from os import getenv
8
9import adafruit_connection_manager
10import board
11import busio
12import neopixel
13import rtc
14from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
15from digitalio import DigitalInOut
16
17# Get WiFi details and AWS Keys, ensure these are setup in settings.toml
18ssid = getenv("CIRCUITPY_WIFI_SSID")
19password = getenv("CIRCUITPY_WIFI_PASSWORD")
20id_scope = getenv("id_scope")
21device_id = getenv("device_id")
22device_sas_key = getenv("device_sas_key")
23
24# ESP32 Setup
25try:
26 esp32_cs = DigitalInOut(board.ESP_CS)
27 esp32_ready = DigitalInOut(board.ESP_BUSY)
28 esp32_reset = DigitalInOut(board.ESP_RESET)
29except AttributeError:
30 esp32_cs = DigitalInOut(board.D13)
31 esp32_ready = DigitalInOut(board.D11)
32 esp32_reset = DigitalInOut(board.D12)
33
34spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
35esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
36
37"""Use below for Most Boards"""
38status_pixel = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards
39"""Uncomment below for ItsyBitsy M4"""
40# status_pixel = 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_pixel = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)
48wifi = adafruit_esp32spi_wifimanager.WiFiManager(esp, ssid, password, status_pixel=status_pixel)
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 settings.toml 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
93from adafruit_azureiot import (
94 IoTCentralDevice,
95 IoTError,
96)
97
98pool = adafruit_connection_manager.get_radio_socketpool(esp)
99ssl_context = adafruit_connection_manager.get_radio_ssl_context(esp)
100# Create an IoT Hub device client and connect
101device = IoTCentralDevice(
102 pool,
103 ssl_context,
104 id_scope,
105 device_id,
106 device_sas_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)
IoT Hub Native Networking
Ensure your IoT Hub device works with this simple test.
1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
2# SPDX-License-Identifier: MIT
3
4import json
5import random
6import time
7from os import getenv
8
9import adafruit_connection_manager
10import adafruit_ntp
11import rtc
12import wifi
13
14from adafruit_azureiot import IoTHubDevice
15
16# Get WiFi details and Azure keys, ensure these are setup in settings.toml
17ssid = getenv("CIRCUITPY_WIFI_SSID")
18password = getenv("CIRCUITPY_WIFI_PASSWORD")
19device_connection_string = getenv("device_connection_string")
20
21print("Connecting to WiFi...")
22wifi.radio.connect(ssid, 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 settings.toml 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, device_connection_string)
68
69print("Connecting to Azure IoT Hub...")
70
71# Connect to IoT Central
72device.connect()
73
74print("Connected to Azure IoT Hub!")
75
76message_counter = 60
77
78while True:
79 try:
80 # Send a device to cloud message every minute
81 # You can see the overview of messages sent from the device in the Overview tab
82 # of the IoT Hub in the Azure Portal
83 if message_counter >= 60:
84 message = {"Temperature": random.randint(0, 50)}
85 device.send_device_to_cloud_message(json.dumps(message))
86 message_counter = 0
87 else:
88 message_counter += 1
89
90 # Poll every second for messages from the cloud
91 device.loop()
92 except (ValueError, RuntimeError) as e:
93 print("Connection error, reconnecting\n", str(e))
94 # If we lose connectivity, reset the wifi and reconnect
95 wifi.radio.enabled = False
96 wifi.radio.enabled = True
97 wifi.radio.connect(ssid, password)
98 device.reconnect()
99 continue
100 time.sleep(1)
Handle direct methods.
1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
2# SPDX-License-Identifier: MIT
3
4import time
5from os import getenv
6
7import adafruit_connection_manager
8import adafruit_ntp
9import rtc
10import wifi
11
12from adafruit_azureiot import IoTHubDevice
13from adafruit_azureiot.iot_mqtt import IoTResponse
14
15# Get WiFi details, ensure these are setup in settings.toml
16ssid = getenv("CIRCUITPY_WIFI_SSID")
17password = getenv("CIRCUITPY_WIFI_PASSWORD")
18device_connection_string = getenv("device_connection_string")
19
20print("Connecting to WiFi...")
21wifi.radio.connect(ssid, password)
22
23pool = adafruit_connection_manager.get_radio_socketpool(wifi.radio)
24ssl_context = adafruit_connection_manager.get_radio_ssl_context(wifi.radio)
25
26print("Connected to WiFi!")
27
28if time.localtime().tm_year < 2022:
29 print("Setting System Time in UTC")
30 ntp = adafruit_ntp.NTP(pool, tz_offset=0)
31
32 # NOTE: This changes the system time so make sure you aren't assuming that time
33 # doesn't jump.
34 rtc.RTC().datetime = ntp.datetime
35else:
36 print("Year seems good, skipping set time.")
37
38# You will need an Azure subscription to create an Azure IoT Hub resource
39#
40# If you don't have an Azure subscription:
41#
42# If you are a student, head to https://aka.ms/FreeStudentAzure and sign up, validating with your
43# student email address. This will give you $100 of Azure credit and free tiers of a load of
44# service, renewable each year you are a student
45#
46# If you are not a student, head to https://aka.ms/FreeAz and sign up to get $200 of credit for 30
47# days, as well as free tiers of a load of services
48#
49# Create an Azure IoT Hub and an IoT device in the Azure portal here:
50# https://aka.ms/AzurePortalHome.
51# Instructions to create an IoT Hub and device are here: https://aka.ms/CreateIoTHub
52#
53# The free tier of IoT Hub allows up to 8,000 messages a day, so try not to send messages too often
54# if you are using the free tier
55#
56# Once you have a hub and a device, copy the device primary connection string.
57# Add it to the settings.toml file in an entry called device_connection_string
58#
59# The adafruit-circuitpython-azureiot library depends on the following libraries:
60#
61# From the Adafruit CircuitPython Bundle https://github.com/adafruit/Adafruit_CircuitPython_Bundle:
62# * adafruit-circuitpython-minimqtt
63
64
65# Create an IoT Hub device client and connect
66device = IoTHubDevice(pool, ssl_context, device_connection_string)
67
68
69# Subscribe to direct method calls
70# To invoke a method on the device, select it in the Azure Portal, select Direct Method,
71# fill in the method name and payload, then select Invoke Method
72# Direct method handlers need to return a response to show if the method was handled
73# successfully or not, returning an HTTP status code and message
74def direct_method_invoked(method_name: str, payload) -> IoTResponse:
75 print("Received direct method", method_name, "with data", str(payload))
76 # return a status code and message to indicate if the direct method was handled correctly
77 return IoTResponse(200, "OK")
78
79
80# Subscribe to the direct method invoked event
81device.on_direct_method_invoked = direct_method_invoked
82print("Connecting to Azure IoT Hub...")
83
84# Connect to IoT Central
85device.connect()
86
87print("Connected to Azure IoT Hub!")
88
89while True:
90 try:
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(ssid, password)
99 device.reconnect()
100 continue
101
102 time.sleep(1)
Send device to cloud messages, and handle cloud to device messages.
1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
2# SPDX-License-Identifier: MIT
3
4import json
5import random
6import time
7from os import getenv
8
9import adafruit_connection_manager
10import adafruit_ntp
11import rtc
12import wifi
13
14from adafruit_azureiot import IoTHubDevice
15
16# Get WiFi details and Azure keys, ensure these are setup in settings.toml
17ssid = getenv("CIRCUITPY_WIFI_SSID")
18password = getenv("CIRCUITPY_WIFI_PASSWORD")
19device_connection_string = getenv("device_connection_string")
20
21print("Connecting to WiFi...")
22wifi.radio.connect(ssid, 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 settings.toml 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, device_connection_string)
68
69
70# Subscribe to cloud to device messages
71# To send a message to the device, select it in the Azure Portal, select Message To Device,
72# fill in the message and any properties you want to add, then select Send Message
73def cloud_to_device_message_received(body: str, properties: dict):
74 print("Received message with body", body, "and properties", json.dumps(properties))
75
76
77# Subscribe to the cloud to device message received events
78device.on_cloud_to_device_message_received = cloud_to_device_message_received
79
80print("Connecting to Azure IoT Hub...")
81device.connect()
82
83print("Connected to Azure IoT Hub!")
84
85message_counter = 60
86
87while True:
88 try:
89 # Send a device to cloud message every minute
90 # You can see the overview of messages sent from the device in the Overview tab
91 # of the IoT Hub in the Azure Portal
92 if message_counter >= 60:
93 message = {"Temperature": random.randint(0, 50)}
94 device.send_device_to_cloud_message(json.dumps(message))
95 message_counter = 0
96 else:
97 message_counter += 1
98
99 # Poll every second for messages from the cloud
100 device.loop()
101 except (ValueError, RuntimeError) as e:
102 print("Connection error, reconnecting\n", str(e))
103 # If we lose connectivity, reset the wifi and reconnect
104 wifi.radio.enabled = False
105 wifi.radio.enabled = True
106 wifi.radio.connect(ssid, password)
107 device.reconnect()
108 continue
109 time.sleep(1)
Update the reported properties of the devices device twin, and receive updates to desired properties.
1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
2# SPDX-License-Identifier: MIT
3
4import random
5import time
6from os import getenv
7
8import adafruit_connection_manager
9import adafruit_ntp
10import rtc
11import wifi
12
13from adafruit_azureiot import IoTHubDevice
14
15# Get WiFi details and Azure keys, ensure these are setup in settings.toml
16ssid = getenv("CIRCUITPY_WIFI_SSID")
17password = getenv("CIRCUITPY_WIFI_PASSWORD")
18device_connection_string = getenv("device_connection_string")
19
20print("Connecting to WiFi...")
21wifi.radio.connect(ssid, password)
22
23pool = adafruit_connection_manager.get_radio_socketpool(wifi.radio)
24ssl_context = adafruit_connection_manager.get_radio_ssl_context(wifi.radio)
25
26print("Connected to WiFi!")
27
28if time.localtime().tm_year < 2022:
29 print("Setting System Time in UTC")
30 ntp = adafruit_ntp.NTP(pool, tz_offset=0)
31
32 # NOTE: This changes the system time so make sure you aren't assuming that time
33 # doesn't jump.
34 rtc.RTC().datetime = ntp.datetime
35else:
36 print("Year seems good, skipping set time.")
37
38# You will need an Azure subscription to create an Azure IoT Hub resource
39#
40# If you don't have an Azure subscription:
41#
42# If you are a student, head to https://aka.ms/FreeStudentAzure and sign up, validating with your
43# student email address. This will give you $100 of Azure credit and free tiers of a load of
44# service, renewable each year you are a student
45#
46# If you are not a student, head to https://aka.ms/FreeAz and sign up to get $200 of credit for 30
47# days, as well as free tiers of a load of services
48#
49# Create an Azure IoT Hub and an IoT device in the Azure portal here:
50# https://aka.ms/AzurePortalHome.
51# Instructions to create an IoT Hub and device are here: https://aka.ms/CreateIoTHub
52#
53# The free tier of IoT Hub allows up to 8,000 messages a day, so try not to send messages too often
54# if you are using the free tier
55#
56# Once you have a hub and a device, copy the device primary connection string.
57# Add it to the settings.toml file in an entry called device_connection_string
58#
59# The adafruit-circuitpython-azureiot library depends on the following libraries:
60#
61# From the Adafruit CircuitPython Bundle https://github.com/adafruit/Adafruit_CircuitPython_Bundle:
62# * adafruit-circuitpython-minimqtt
63
64
65# Create an IoT Hub device client and connect
66device = IoTHubDevice(pool, ssl_context, device_connection_string)
67
68
69# Subscribe to device twin desired property updates
70# To see these changes, update the desired properties for the device either in code
71# or in the Azure portal by selecting the device in the IoT Hub blade, selecting
72# Device Twin then adding or amending an entry in the 'desired' section
73def device_twin_desired_updated(
74 desired_property_name: str, desired_property_value, desired_version: int
75):
76 print(
77 "Property",
78 desired_property_name,
79 "updated to",
80 str(desired_property_value),
81 "version",
82 desired_version,
83 )
84
85
86# Subscribe to the device twin desired property updated event
87device.on_device_twin_desired_updated = device_twin_desired_updated
88
89print("Connecting to Azure IoT Hub...")
90device.connect()
91
92print("Connected to Azure IoT Hub!")
93
94message_counter = 60
95
96while True:
97 try:
98 if message_counter >= 60:
99 # Send a reported property twin update every minute
100 # You can see these in the portal by selecting the device in the IoT Hub blade,
101 # selecting device Twin then looking for the updates in the 'reported' section
102 patch = {"Temperature": random.randint(0, 50)}
103 device.update_twin(patch)
104 message_counter = 0
105 else:
106 message_counter += 1
107
108 # Poll every second for messages from the cloud
109 device.loop()
110 except (ValueError, RuntimeError) as e:
111 print("Connection error, reconnecting\n", str(e))
112 # If we lose connectivity, reset the wifi and reconnect
113 wifi.radio.enabled = False
114 wifi.radio.enabled = True
115 wifi.radio.connect(ssid, password)
116 device.reconnect()
117 continue
118 time.sleep(1)
IoT Central Native Networking
Ensure your IoT Central device works with this simple test.
1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
2# SPDX-License-Identifier: MIT
3
4import json
5import random
6import time
7from os import getenv
8
9import adafruit_connection_manager
10import adafruit_ntp
11import rtc
12import wifi
13
14from adafruit_azureiot import IoTCentralDevice
15
16# Get WiFi details and AWS Keys, ensure these are setup in settings.toml
17ssid = getenv("CIRCUITPY_WIFI_SSID")
18password = getenv("CIRCUITPY_WIFI_PASSWORD")
19id_scope = getenv("id_scope")
20device_id = getenv("device_id")
21device_sas_key = getenv("device_sas_key")
22
23print("Connecting to WiFi...")
24wifi.radio.connect(ssid, password)
25
26pool = adafruit_connection_manager.get_radio_socketpool(wifi.radio)
27ssl_context = adafruit_connection_manager.get_radio_ssl_context(wifi.radio)
28
29print("Connected to WiFi!")
30
31if time.localtime().tm_year < 2022:
32 print("Setting System Time in UTC")
33 ntp = adafruit_ntp.NTP(pool, tz_offset=0)
34
35 # NOTE: This changes the system time so make sure you aren't assuming that time
36 # doesn't jump.
37 rtc.RTC().datetime = ntp.datetime
38else:
39 print("Year seems good, skipping set time.")
40
41# To use Azure IoT Central, you will need to create an IoT Central app.
42# You can either create a free tier app that will live for 7 days without an Azure subscription,
43# Or a standard tier app that will last for ever with an Azure subscription.
44# The standard tiers are free for up to 2 devices
45#
46# If you don't have an Azure subscription:
47#
48# If you are a student, head to https://aka.ms/FreeStudentAzure and sign up, validating with your
49# student email address. This will give you $100 of Azure credit and free tiers of a load of
50# service, renewable each year you are a student
51#
52# If you are not a student, head to https://aka.ms/FreeAz and sign up to get $200 of credit for 30
53# days, as well as free tiers of a load of services
54#
55# Create an Azure IoT Central app by following these instructions:
56# https://aka.ms/CreateIoTCentralApp
57# Add a device template with telemetry, properties and commands, as well as a view to visualize the
58# telemetry and execute commands, and a form to set properties.
59#
60# Next create a device using the device template, and select Connect to get the device connection
61# details.
62# Add the connection details to your settings.toml file, using the following values:
63#
64# 'id_scope' - the devices ID scope
65# 'device_id' - the devices device id
66# 'device_sas_key' - the devices primary key
67#
68# The adafruit-circuitpython-azureiot library depends on the following libraries:
69#
70# From the Adafruit CircuitPython Bundle https://github.com/adafruit/Adafruit_CircuitPython_Bundle:
71# * adafruit-circuitpython-minimqtt
72
73
74# Create an IoT Hub device client and connect
75device = IoTCentralDevice(
76 pool,
77 ssl_context,
78 id_scope,
79 device_id,
80 device_sas_key,
81)
82
83print("Connecting to Azure IoT Central...")
84device.connect()
85
86print("Connected to Azure IoT Central!")
87
88message_counter = 60
89
90while True:
91 try:
92 # Send telemetry every minute
93 # You can see the values in the devices dashboard
94 if message_counter >= 60:
95 message = {"Temperature": random.randint(0, 50)}
96 device.send_telemetry(json.dumps(message))
97 message_counter = 0
98 else:
99 message_counter += 1
100
101 # Poll every second for messages from the cloud
102 device.loop()
103 except (ValueError, RuntimeError) as e:
104 print("Connection error, reconnecting\n", str(e))
105 wifi.radio.enabled = False
106 wifi.radio.enabled = True
107 wifi.radio.connect(ssid, password)
108 device.reconnect()
109 continue
110 time.sleep(1)
Handle commands.
1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
2# SPDX-License-Identifier: MIT
3
4import time
5from os import getenv
6
7import adafruit_connection_manager
8import adafruit_ntp
9import rtc
10import wifi
11
12from adafruit_azureiot import IoTCentralDevice
13from adafruit_azureiot.iot_mqtt import IoTResponse
14
15# Get WiFi details and AWS Keys, ensure these are setup in settings.toml
16ssid = getenv("CIRCUITPY_WIFI_SSID")
17password = getenv("CIRCUITPY_WIFI_PASSWORD")
18id_scope = getenv("id_scope")
19device_id = getenv("device_id")
20device_sas_key = getenv("device_sas_key")
21
22print("Connecting to WiFi...")
23wifi.radio.connect(ssid, 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 settings.toml 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 id_scope,
78 device_id,
79 device_sas_key,
80)
81
82
83# Subscribe to commands
84# Commands can be sent from the devices Dashboard in IoT Central, assuming
85# the device template and view has been set up with the commands
86# Command handlers need to return a response to show if the command was handled
87# successfully or not, returning an HTTP status code and message
88def command_executed(command_name: str, payload) -> IoTResponse:
89 print("Command", command_name, "executed with payload", str(payload))
90 # return a status code and message to indicate if the command was handled correctly
91 return IoTResponse(200, "OK")
92
93
94# Subscribe to the command execute event
95device.on_command_executed = command_executed
96
97
98print("Connecting to Azure IoT Central...")
99device.connect()
100
101print("Connected to Azure IoT Central!")
102
103message_counter = 60
104
105while True:
106 try:
107 # Poll every second for messages from the cloud
108 device.loop()
109 except (ValueError, RuntimeError) as e:
110 print("Connection error, reconnecting\n", str(e))
111 # If we lose connectivity, reset the wifi and reconnect
112 wifi.reset()
113 wifi.connect()
114 device.reconnect()
115 continue
116
117 time.sleep(1)
Update the properties of the device, and receive updates to properties.
1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
2# SPDX-License-Identifier: MIT
3
4import random
5import time
6from os import getenv
7
8import adafruit_connection_manager
9import adafruit_ntp
10import rtc
11import wifi
12
13from adafruit_azureiot import IoTCentralDevice
14
15# Get WiFi details and AWS Keys, ensure these are setup in settings.toml
16ssid = getenv("CIRCUITPY_WIFI_SSID")
17password = getenv("CIRCUITPY_WIFI_PASSWORD")
18id_scope = getenv("id_scope")
19device_id = getenv("device_id")
20device_sas_key = getenv("device_sas_key")
21
22print("Connecting to WiFi...")
23wifi.radio.connect(ssid, 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 settings.toml 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 id_scope,
78 device_id,
79 device_sas_key,
80)
81
82
83# Subscribe to property changes
84# Properties can be updated either in code, or by adding a form to the view
85# in the device template, and setting the value on the dashboard for the device
86def property_changed(property_name, property_value, version):
87 print(
88 "Property",
89 property_name,
90 "updated to",
91 str(property_value),
92 "version",
93 str(version),
94 )
95
96
97# Subscribe to the property changed event
98device.on_property_changed = property_changed
99
100print("Connecting to Azure IoT Central...")
101device.connect()
102
103print("Connected to Azure IoT Central!")
104
105message_counter = 60
106
107while True:
108 try:
109 # Send property values every minute
110 # You can see the values in the devices dashboard
111 if message_counter >= 60:
112 device.send_property("Desired_Temperature", random.randint(0, 50))
113 message_counter = 0
114 else:
115 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 wifi.reset()
122 wifi.connect()
123 device.reconnect()
124 continue
125 time.sleep(1)
Handle connection errors.
1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
2# SPDX-License-Identifier: MIT
3
4import json
5import random
6import time
7from os import getenv
8
9import adafruit_connection_manager
10import adafruit_ntp
11import rtc
12import wifi
13
14from adafruit_azureiot import (
15 IoTCentralDevice,
16 IoTError,
17)
18
19# Get WiFi details and AWS Keys, ensure these are setup in settings.toml
20ssid = getenv("CIRCUITPY_WIFI_SSID")
21password = getenv("CIRCUITPY_WIFI_PASSWORD")
22id_scope = getenv("id_scope")
23device_id = getenv("device_id")
24device_sas_key = getenv("device_sas_key")
25
26print("Connecting to WiFi...")
27wifi.radio.connect(ssid, password)
28
29pool = adafruit_connection_manager.get_radio_socketpool(wifi.radio)
30ssl_context = adafruit_connection_manager.get_radio_ssl_context(wifi.radio)
31
32print("Connected to WiFi!")
33
34if time.localtime().tm_year < 2022:
35 print("Setting System Time in UTC")
36 ntp = adafruit_ntp.NTP(pool, tz_offset=0)
37
38 # NOTE: This changes the system time so make sure you aren't assuming that time
39 # doesn't jump.
40 rtc.RTC().datetime = ntp.datetime
41else:
42 print("Year seems good, skipping set time.")
43
44# To use Azure IoT Central, you will need to create an IoT Central app.
45# You can either create a free tier app that will live for 7 days without an Azure subscription,
46# Or a standard tier app that will last for ever with an Azure subscription.
47# The standard tiers are free for up to 2 devices
48#
49# If you don't have an Azure subscription:
50#
51# If you are a student, head to https://aka.ms/FreeStudentAzure and sign up, validating with your
52# student email address. This will give you $100 of Azure credit and free tiers of a load of
53# service, renewable each year you are a student
54#
55# If you are not a student, head to https://aka.ms/FreeAz and sign up to get $200 of credit for 30
56# days, as well as free tiers of a load of services
57#
58# Create an Azure IoT Central app by following these instructions:
59# https://aka.ms/CreateIoTCentralApp
60# Add a device template with telemetry, properties and commands, as well as a view to visualize the
61# telemetry and execute commands, and a form to set properties.
62#
63# Next create a device using the device template, and select Connect to get the device connection
64# details.
65# Add the connection details to your settings.toml file, using the following values:
66#
67# 'id_scope' - the devices ID scope
68# 'device_id' - the devices device id
69# 'device_sas_key' - the devices primary key
70#
71# The adafruit-circuitpython-azureiot library depends on the following libraries:
72#
73# From the Adafruit CircuitPython Bundle https://github.com/adafruit/Adafruit_CircuitPython_Bundle:
74# * adafruit-circuitpython-minimqtt
75
76
77# Create an IoT Hub device client and connect
78device = IoTCentralDevice(
79 pool,
80 ssl_context,
81 id_scope,
82 device_id,
83 device_sas_key,
84)
85
86# don't connect
87# device.connect()
88
89try:
90 message = {"Temperature": random.randint(0, 50)}
91 device.send_telemetry(json.dumps(message))
92except IoTError as iot_error:
93 print("Error - ", iot_error.message)