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