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