More updates from PR feedback
This commit is contained in:
parent
e8caff8f36
commit
5251721514
17 changed files with 453 additions and 116 deletions
|
|
@ -399,7 +399,7 @@ max-args=6
|
|||
|
||||
# Maximum number of attributes for a class (see R0902).
|
||||
# max-attributes=7
|
||||
max-attributes=12
|
||||
max-attributes=13
|
||||
|
||||
# Maximum number of boolean expressions in a if statement
|
||||
max-bool-expr=5
|
||||
|
|
|
|||
2
LICENSE
2
LICENSE
|
|
@ -1,6 +1,6 @@
|
|||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2019 Brent Rubell for Adafruit Industries
|
||||
Copyright (c) 2020 Brent Rubell for Adafruit Industries, Jim Bennett, Elena Horton
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# The MIT License (MIT)
|
||||
#
|
||||
# Copyright (c) 2019 Jim Bennett
|
||||
# Copyright (c) 2020 Jim Bennett
|
||||
#
|
||||
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
# of this software and associated documentation files (the "Software"), to deal
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# The MIT License (MIT)
|
||||
#
|
||||
# Copyright (c) 2019 Jim Bennett
|
||||
# Copyright (c) 2020 Jim Bennett
|
||||
#
|
||||
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
# of this software and associated documentation files (the "Software"), to deal
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# The MIT License (MIT)
|
||||
#
|
||||
# Copyright (c) 2019 Jim Bennett
|
||||
# Copyright (c) 2020 Jim Bennett
|
||||
#
|
||||
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
# of this software and associated documentation files (the "Software"), to deal
|
||||
|
|
@ -35,7 +35,7 @@ import time
|
|||
import circuitpython_base64 as base64
|
||||
import circuitpython_hmac as hmac
|
||||
import circuitpython_parse as parse
|
||||
from adafruit_esp32spi.adafruit_esp32spi_wifimanager import ESPSPI_WiFiManager
|
||||
import adafruit_requests as requests
|
||||
import adafruit_logging as logging
|
||||
from adafruit_logging import Logger
|
||||
import adafruit_hashlib as hashlib
|
||||
|
|
@ -74,25 +74,21 @@ class DeviceRegistration:
|
|||
if error == status_code:
|
||||
raise DeviceRegistrationError("Error {0}: {1}".format(status_code, status_reason))
|
||||
|
||||
def __init__(self, wifi_manager: ESPSPI_WiFiManager, id_scope: str, device_id: str, key: str, logger: Logger = None):
|
||||
def __init__(self, socket, id_scope: str, device_id: str, key: str, logger: Logger = None):
|
||||
"""Creates an instance of the device registration service
|
||||
:param wifi_manager: WiFiManager object from ESPSPI_WiFiManager.
|
||||
:param socket: The network socket
|
||||
:param str id_scope: The ID scope of the device to register
|
||||
:param str device_id: The device ID of the device to register
|
||||
:param str key: The primary or secondary key of the device to register
|
||||
:param adafruit_logging.Logger logger: The logger to use to log messages
|
||||
:raises TypeError: if the WiFi manager is not the right type
|
||||
"""
|
||||
wifi_type = str(type(wifi_manager))
|
||||
if "ESPSPI_WiFiManager" not in wifi_type:
|
||||
raise TypeError("This library requires a WiFiManager object.")
|
||||
|
||||
self._wifi_manager = wifi_manager
|
||||
self._id_scope = id_scope
|
||||
self._device_id = device_id
|
||||
self._key = key
|
||||
self._logger = logger if logger is not None else logging.getLogger("log")
|
||||
|
||||
requests.set_socket(socket)
|
||||
|
||||
@staticmethod
|
||||
def compute_derived_symmetric_key(secret: str, msg: str) -> bytes:
|
||||
"""Computes a derived symmetric key from a secret and a message
|
||||
|
|
@ -155,7 +151,7 @@ class DeviceRegistration:
|
|||
gc.collect()
|
||||
try:
|
||||
self._logger.debug("Trying to send...")
|
||||
response = self._wifi_manager.put(url, json=body, headers=headers)
|
||||
response = requests.put(url, json=body, headers=headers)
|
||||
self._logger.debug("Sent!")
|
||||
break
|
||||
except RuntimeError as runtime_error:
|
||||
|
|
@ -180,7 +176,7 @@ class DeviceRegistration:
|
|||
gc.collect()
|
||||
try:
|
||||
self._logger.debug("Trying to send...")
|
||||
response = self._wifi_manager.get(url, headers=headers)
|
||||
response = requests.get(url, headers=headers)
|
||||
self._logger.debug("Sent!")
|
||||
break
|
||||
except RuntimeError as runtime_error:
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# The MIT License (MIT)
|
||||
#
|
||||
# Copyright (c) 2019 Jim Bennett
|
||||
# Copyright (c) 2020 Jim Bennett
|
||||
#
|
||||
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
# of this software and associated documentation files (the "Software"), to deal
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# The MIT License (MIT)
|
||||
#
|
||||
# Copyright (c) 2019 Jim Bennett
|
||||
# Copyright (c) 2020 Jim Bennett
|
||||
#
|
||||
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
# of this software and associated documentation files (the "Software"), to deal
|
||||
|
|
@ -31,8 +31,6 @@ An MQTT client for Azure IoT
|
|||
import gc
|
||||
import json
|
||||
import time
|
||||
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
|
||||
from adafruit_esp32spi.adafruit_esp32spi_wifimanager import ESPSPI_WiFiManager
|
||||
import adafruit_minimqtt as minimqtt
|
||||
from adafruit_minimqtt import MQTT
|
||||
import circuitpython_parse as parse
|
||||
|
|
@ -118,7 +116,7 @@ class IoTMQTT:
|
|||
|
||||
# Workaround for https://github.com/adafruit/Adafruit_CircuitPython_MiniMQTT/issues/25
|
||||
def _try_create_mqtt_client(self, hostname: str) -> None:
|
||||
minimqtt.set_socket(socket, self._wifi_manager.esp)
|
||||
minimqtt.set_socket(self._socket, self._iface)
|
||||
|
||||
self._mqtts = MQTT(
|
||||
broker=hostname,
|
||||
|
|
@ -338,7 +336,8 @@ class IoTMQTT:
|
|||
def __init__(
|
||||
self,
|
||||
callback: IoTMQTTCallback,
|
||||
wifi_manager: ESPSPI_WiFiManager,
|
||||
socket,
|
||||
iface,
|
||||
hostname: str,
|
||||
device_id: str,
|
||||
key: str,
|
||||
|
|
@ -346,8 +345,9 @@ class IoTMQTT:
|
|||
logger: logging = None,
|
||||
):
|
||||
"""Create the Azure IoT MQTT client
|
||||
:param wifi_manager: The WiFi manager
|
||||
:param IoTMQTTCallback callback: A callback class
|
||||
:param socket: The socket to communicate over
|
||||
:param iface: The network interface to communicate over
|
||||
:param str hostname: The hostname of the MQTT broker to connect to, get this by registering the device
|
||||
:param str device_id: The device ID of the device to register
|
||||
:param str key: The primary or secondary key of the device to register
|
||||
|
|
@ -355,7 +355,8 @@ class IoTMQTT:
|
|||
:param adafruit_logging logger: The logger
|
||||
"""
|
||||
self._callback = callback
|
||||
self._wifi_manager = wifi_manager
|
||||
self._socket = socket
|
||||
self._iface = iface
|
||||
self._mqtt_connected = False
|
||||
self._auth_response_received = False
|
||||
self._mqtts = None
|
||||
|
|
@ -368,6 +369,15 @@ class IoTMQTT:
|
|||
self._logger = logger if logger is not None else logging.getLogger("log")
|
||||
self._is_subscribed_to_twins = False
|
||||
|
||||
def _subscribe_to_core_topics(self):
|
||||
self._mqtts.subscribe("devices/{}/messages/events/#".format(self._device_id))
|
||||
self._mqtts.subscribe("devices/{}/messages/devicebound/#".format(self._device_id))
|
||||
self._mqtts.subscribe("$iothub/methods/#")
|
||||
|
||||
def _subscribe_to_twin_topics(self):
|
||||
self._mqtts.subscribe("$iothub/twin/PATCH/properties/desired/#") # twin desired property changes
|
||||
self._mqtts.subscribe("$iothub/twin/res/#") # twin properties response
|
||||
|
||||
def connect(self) -> bool:
|
||||
"""Connects to the MQTT broker
|
||||
:returns: True if the connection is successful, otherwise False
|
||||
|
|
@ -388,9 +398,7 @@ class IoTMQTT:
|
|||
self._mqtt_connected = True
|
||||
self._auth_response_received = True
|
||||
|
||||
self._mqtts.subscribe("devices/{}/messages/events/#".format(self._device_id))
|
||||
self._mqtts.subscribe("devices/{}/messages/devicebound/#".format(self._device_id))
|
||||
self._mqtts.subscribe("$iothub/methods/#")
|
||||
self._subscribe_to_core_topics()
|
||||
|
||||
return True
|
||||
|
||||
|
|
@ -402,8 +410,7 @@ class IoTMQTT:
|
|||
return
|
||||
|
||||
# do this separately as this is not supported in B1 hubs
|
||||
self._mqtts.subscribe("$iothub/twin/PATCH/properties/desired/#") # twin desired property changes
|
||||
self._mqtts.subscribe("$iothub/twin/res/#") # twin properties response
|
||||
self._subscribe_to_twin_topics()
|
||||
|
||||
self._get_device_settings()
|
||||
|
||||
|
|
@ -419,6 +426,44 @@ class IoTMQTT:
|
|||
self._mqtt_connected = False
|
||||
self._mqtts.disconnect()
|
||||
|
||||
# Workaround for https://github.com/adafruit/Adafruit_CircuitPython_MiniMQTT/issues/26
|
||||
def _fix_broker_name(self, hostname):
|
||||
try: # set broker IP
|
||||
self._mqtts.broker = self._iface.unpretty_ip(hostname)
|
||||
except ValueError: # set broker URL
|
||||
self._mqtts.broker = hostname
|
||||
|
||||
def reconnect(self) -> None:
|
||||
"""Reconnects to the MQTT broker
|
||||
"""
|
||||
self._logger.info("- iot_mqtt :: reconnect :: ")
|
||||
|
||||
self._auth_response_received = None
|
||||
|
||||
# Workaround for https://github.com/adafruit/Adafruit_CircuitPython_MiniMQTT/issues/25
|
||||
# Workaround for https://github.com/adafruit/Adafruit_CircuitPython_MiniMQTT/issues/26
|
||||
# Workaround for https://github.com/adafruit/Adafruit_CircuitPython_MiniMQTT/issues/28
|
||||
try:
|
||||
self._fix_broker_name(self._hostname)
|
||||
self._mqtts.connect()
|
||||
except ValueError:
|
||||
self._fix_broker_name("https://" + self._hostname)
|
||||
self._mqtts.connect()
|
||||
|
||||
self._logger.info("- iot_mqtt :: waiting for auth...")
|
||||
|
||||
while self._auth_response_received is None:
|
||||
self.loop()
|
||||
|
||||
self._logger.info("- iot_mqtt :: authed, subscribing...")
|
||||
|
||||
# Resubscribe
|
||||
self._subscribe_to_core_topics()
|
||||
if self._is_subscribed_to_twins:
|
||||
self._subscribe_to_twin_topics()
|
||||
|
||||
self._logger.info("- iot_mqtt :: resubscribed")
|
||||
|
||||
def is_connected(self) -> bool:
|
||||
"""Gets if there is an open connection to the MQTT broker
|
||||
:returns: True if there is an open connection, False if not
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# The MIT License (MIT)
|
||||
#
|
||||
# Copyright (c) 2019 Jim Bennett
|
||||
# Copyright (c) 2020 Jim Bennett
|
||||
#
|
||||
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
# of this software and associated documentation files (the "Software"), to deal
|
||||
|
|
@ -30,7 +30,6 @@ Connectivity to Azure IoT Central
|
|||
|
||||
import json
|
||||
import time
|
||||
from adafruit_esp32spi.adafruit_esp32spi_wifimanager import ESPSPI_WiFiManager
|
||||
import adafruit_logging as logging
|
||||
from .device_registration import DeviceRegistration
|
||||
from .iot_error import IoTError
|
||||
|
|
@ -87,23 +86,23 @@ class IoTCentralDevice(IoTMQTTCallback):
|
|||
self.on_property_changed(reported_property_name, reported_property_value, reported_version)
|
||||
|
||||
# pylint: disable=R0913
|
||||
def __init__(
|
||||
self, wifi_manager: ESPSPI_WiFiManager, id_scope: str, device_id: str, key: str, token_expires: int = 21600, logger: logging = None
|
||||
):
|
||||
def __init__(self, socket, iface, id_scope: str, device_id: str, key: str, token_expires: int = 21600, logger: logging = None):
|
||||
"""Create the Azure IoT Central device client
|
||||
:param wifi_manager: The WiFi manager
|
||||
:param socket: The network socket
|
||||
:param iface: The network interface
|
||||
:param str id_scope: The ID Scope of the device in IoT Central
|
||||
:param str device_id: The device ID of the device in IoT Central
|
||||
:param str key: The primary or secondary key of the device in IoT Central
|
||||
:param int token_expires: The number of seconds till the token expires, defaults to 6 hours
|
||||
:param adafruit_logging logger: The logger
|
||||
"""
|
||||
self._wifi_manager = wifi_manager
|
||||
self._socket = socket
|
||||
self._iface = iface
|
||||
self._id_scope = id_scope
|
||||
self._device_id = device_id
|
||||
self._key = key
|
||||
self._token_expires = token_expires
|
||||
self._logger = logger
|
||||
self._logger = logger if logger is not None else logging.getLogger("log")
|
||||
self._device_registration = None
|
||||
self._mqtt = None
|
||||
|
||||
|
|
@ -133,11 +132,11 @@ class IoTCentralDevice(IoTMQTTCallback):
|
|||
:raises DeviceRegistrationError: if the device cannot be registered successfully
|
||||
:raises RuntimeError: if the internet connection is not responding or is unable to connect
|
||||
"""
|
||||
self._device_registration = DeviceRegistration(self._wifi_manager, self._id_scope, self._device_id, self._key, self._logger)
|
||||
self._device_registration = DeviceRegistration(self._socket, self._id_scope, self._device_id, self._key, self._logger)
|
||||
|
||||
token_expiry = int(time.time() + self._token_expires)
|
||||
hostname = self._device_registration.register_device(token_expiry)
|
||||
self._mqtt = IoTMQTT(self, self._wifi_manager, hostname, self._device_id, self._key, self._token_expires, self._logger)
|
||||
self._mqtt = IoTMQTT(self, self._socket, self._iface, hostname, self._device_id, self._key, self._token_expires, self._logger)
|
||||
|
||||
self._mqtt.connect()
|
||||
self._mqtt.subscribe_to_twins()
|
||||
|
|
@ -151,6 +150,14 @@ class IoTCentralDevice(IoTMQTTCallback):
|
|||
|
||||
self._mqtt.disconnect()
|
||||
|
||||
def reconnect(self) -> None:
|
||||
"""Reconnects to the MQTT broker
|
||||
"""
|
||||
if self._mqtt is None:
|
||||
raise IoTError("You are not connected to IoT Central")
|
||||
|
||||
self._mqtt.reconnect()
|
||||
|
||||
def is_connected(self) -> bool:
|
||||
"""Gets if there is an open connection to the MQTT broker
|
||||
:returns: True if there is an open connection, False if not
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# The MIT License (MIT)
|
||||
#
|
||||
# Copyright (c) 2019 Jim Bennett
|
||||
# Copyright (c) 2020 Jim Bennett, Elena Horton
|
||||
#
|
||||
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
# of this software and associated documentation files (the "Software"), to deal
|
||||
|
|
@ -29,7 +29,6 @@ Connectivity to Azure IoT Hub
|
|||
"""
|
||||
|
||||
import json
|
||||
from adafruit_esp32spi.adafruit_esp32spi_wifimanager import ESPSPI_WiFiManager
|
||||
import adafruit_logging as logging
|
||||
from .iot_error import IoTError
|
||||
from .iot_mqtt import IoTMQTT, IoTMQTTCallback, IoTResponse
|
||||
|
|
@ -129,8 +128,16 @@ class IoTHubDevice(IoTMQTTCallback):
|
|||
# pylint: disable=E1102
|
||||
self._on_device_twin_reported_updated(reported_property_name, reported_property_value, reported_version)
|
||||
|
||||
def __init__(self, wifi_manager: ESPSPI_WiFiManager, device_connection_string: str, token_expires: int = 21600, logger: logging = None):
|
||||
self._wifi_manager = wifi_manager
|
||||
def __init__(self, socket, iface, device_connection_string: str, token_expires: int = 21600, logger: logging = None):
|
||||
"""Create the Azure IoT Central device client
|
||||
:param socket: The network socket
|
||||
:param iface: The network interface
|
||||
:param str device_connection_string: The Iot Hub device connection string
|
||||
:param int token_expires: The number of seconds till the token expires, defaults to 6 hours
|
||||
:param adafruit_logging logger: The logger
|
||||
"""
|
||||
self._socket = socket
|
||||
self._iface = iface
|
||||
self._token_expires = token_expires
|
||||
self._logger = logger if logger is not None else logging.getLogger("log")
|
||||
|
||||
|
|
@ -260,7 +267,7 @@ class IoTHubDevice(IoTMQTTCallback):
|
|||
:raises RuntimeError: if the internet connection is not responding or is unable to connect
|
||||
"""
|
||||
self._mqtt = IoTMQTT(
|
||||
self, self._wifi_manager, self._hostname, self._device_id, self._shared_access_key, self._token_expires, self._logger
|
||||
self, self._socket, self._iface, self._hostname, self._device_id, self._shared_access_key, self._token_expires, self._logger
|
||||
)
|
||||
self._mqtt.connect()
|
||||
|
||||
|
|
@ -276,6 +283,14 @@ class IoTHubDevice(IoTMQTTCallback):
|
|||
|
||||
self._mqtt.disconnect()
|
||||
|
||||
def reconnect(self) -> None:
|
||||
"""Reconnects to the MQTT broker
|
||||
"""
|
||||
if self._mqtt is None:
|
||||
raise IoTError("You are not connected to IoT Central")
|
||||
|
||||
self._mqtt.reconnect()
|
||||
|
||||
def is_connected(self) -> bool:
|
||||
"""Gets if there is an open connection to the MQTT broker
|
||||
:returns: True if there is an open connection, False if not
|
||||
|
|
|
|||
|
|
@ -2,7 +2,9 @@ import time
|
|||
import board
|
||||
import busio
|
||||
from digitalio import DigitalInOut
|
||||
import neopixel
|
||||
from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
|
||||
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
|
||||
from adafruit_ntp import NTP
|
||||
|
||||
# Get wifi details and more from a secrets.py file
|
||||
|
|
@ -25,15 +27,35 @@ except AttributeError:
|
|||
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
|
||||
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
|
||||
|
||||
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets)
|
||||
"""Use below for Most Boards"""
|
||||
status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards
|
||||
"""Uncomment below for ItsyBitsy M4"""
|
||||
# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
|
||||
# Uncomment below for an externally defined RGB LED
|
||||
# import adafruit_rgbled
|
||||
# from adafruit_esp32spi import PWMOut
|
||||
# RED_LED = PWMOut.PWMOut(esp, 26)
|
||||
# GREEN_LED = PWMOut.PWMOut(esp, 27)
|
||||
# BLUE_LED = PWMOut.PWMOut(esp, 25)
|
||||
# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)
|
||||
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
|
||||
|
||||
print("Connecting to WiFi...")
|
||||
|
||||
wifi.connect()
|
||||
|
||||
print("Connected to WiFi!")
|
||||
|
||||
print("Getting the time...")
|
||||
|
||||
ntp = NTP(esp)
|
||||
# Wait for a valid time to be received
|
||||
while not ntp.valid_time:
|
||||
time.sleep(5)
|
||||
ntp.set_time()
|
||||
|
||||
print("Time:", str(time.time()))
|
||||
|
||||
# To use Azure IoT Central, you will need to create an IoT Central app.
|
||||
# You can either create a free tier app that will live for 7 days without an Azure subscription,
|
||||
# Or a standard tier app that will last for ever with an Azure subscription.
|
||||
|
|
@ -63,7 +85,7 @@ from adafruit_azureiot import IoTCentralDevice
|
|||
from adafruit_azureiot.iot_mqtt import IoTResponse
|
||||
|
||||
# Create an IoT Hub device client and connect
|
||||
device = IoTCentralDevice(wifi, secrets["id_scope"], secrets["device_id"], secrets["key"])
|
||||
device = IoTCentralDevice(socket, esp, secrets["id_scope"], secrets["device_id"], secrets["key"])
|
||||
|
||||
# Subscribe to commands
|
||||
# Commands can be sent from the devices Dashboard in IoT Central, assuming
|
||||
|
|
@ -76,12 +98,26 @@ def command_executed(command_name: str, payload) -> IoTResponse:
|
|||
return IoTResponse(200, "OK")
|
||||
|
||||
|
||||
# Subscribe to the command execute event
|
||||
device.on_command_executed = command_executed
|
||||
|
||||
print("Connecting to Azure IoT Central...")
|
||||
|
||||
# Connect to IoT Central
|
||||
device.connect()
|
||||
|
||||
print("Connected to Azure IoT Central!")
|
||||
|
||||
while True:
|
||||
# Poll every second for messages from the cloud
|
||||
device.loop()
|
||||
try:
|
||||
# Poll every second for messages from the cloud
|
||||
device.loop()
|
||||
except (ValueError, RuntimeError) as e:
|
||||
print("Connection error, reconnecting\n", str(e))
|
||||
# If we lose connectivity, reset the wifi and reconnect
|
||||
wifi.reset()
|
||||
wifi.connect()
|
||||
device.reconnect()
|
||||
continue
|
||||
|
||||
time.sleep(1)
|
||||
|
|
|
|||
|
|
@ -4,7 +4,9 @@ import time
|
|||
import board
|
||||
import busio
|
||||
from digitalio import DigitalInOut
|
||||
import neopixel
|
||||
from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
|
||||
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
|
||||
from adafruit_ntp import NTP
|
||||
|
||||
# Get wifi details and more from a secrets.py file
|
||||
|
|
@ -27,15 +29,35 @@ except AttributeError:
|
|||
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
|
||||
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
|
||||
|
||||
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets)
|
||||
"""Use below for Most Boards"""
|
||||
status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards
|
||||
"""Uncomment below for ItsyBitsy M4"""
|
||||
# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
|
||||
# Uncomment below for an externally defined RGB LED
|
||||
# import adafruit_rgbled
|
||||
# from adafruit_esp32spi import PWMOut
|
||||
# RED_LED = PWMOut.PWMOut(esp, 26)
|
||||
# GREEN_LED = PWMOut.PWMOut(esp, 27)
|
||||
# BLUE_LED = PWMOut.PWMOut(esp, 25)
|
||||
# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)
|
||||
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
|
||||
|
||||
print("Connecting to WiFi...")
|
||||
|
||||
wifi.connect()
|
||||
|
||||
print("Connected to WiFi!")
|
||||
|
||||
print("Getting the time...")
|
||||
|
||||
ntp = NTP(esp)
|
||||
# Wait for a valid time to be received
|
||||
while not ntp.valid_time:
|
||||
time.sleep(5)
|
||||
ntp.set_time()
|
||||
|
||||
print("Time:", str(time.time()))
|
||||
|
||||
# To use Azure IoT Central, you will need to create an IoT Central app.
|
||||
# You can either create a free tier app that will live for 7 days without an Azure subscription,
|
||||
# Or a standard tier app that will last for ever with an Azure subscription.
|
||||
|
|
@ -64,7 +86,7 @@ while not ntp.valid_time:
|
|||
from adafruit_azureiot import IoTCentralDevice, IoTError
|
||||
|
||||
# Create an IoT Hub device client and connect
|
||||
device = IoTCentralDevice(wifi, secrets["id_scope"], secrets["device_id"], secrets["key"])
|
||||
device = IoTCentralDevice(socket, esp, secrets["id_scope"], secrets["device_id"], secrets["key"])
|
||||
|
||||
# don't connect
|
||||
# device.connect()
|
||||
|
|
|
|||
|
|
@ -3,7 +3,9 @@ import time
|
|||
import board
|
||||
import busio
|
||||
from digitalio import DigitalInOut
|
||||
import neopixel
|
||||
from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
|
||||
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
|
||||
from adafruit_ntp import NTP
|
||||
|
||||
# Get wifi details and more from a secrets.py file
|
||||
|
|
@ -26,15 +28,35 @@ except AttributeError:
|
|||
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
|
||||
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
|
||||
|
||||
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets)
|
||||
"""Use below for Most Boards"""
|
||||
status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards
|
||||
"""Uncomment below for ItsyBitsy M4"""
|
||||
# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
|
||||
# Uncomment below for an externally defined RGB LED
|
||||
# import adafruit_rgbled
|
||||
# from adafruit_esp32spi import PWMOut
|
||||
# RED_LED = PWMOut.PWMOut(esp, 26)
|
||||
# GREEN_LED = PWMOut.PWMOut(esp, 27)
|
||||
# BLUE_LED = PWMOut.PWMOut(esp, 25)
|
||||
# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)
|
||||
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
|
||||
|
||||
print("Connecting to WiFi...")
|
||||
|
||||
wifi.connect()
|
||||
|
||||
print("Connected to WiFi!")
|
||||
|
||||
print("Getting the time...")
|
||||
|
||||
ntp = NTP(esp)
|
||||
# Wait for a valid time to be received
|
||||
while not ntp.valid_time:
|
||||
time.sleep(5)
|
||||
ntp.set_time()
|
||||
|
||||
print("Time:", str(time.time()))
|
||||
|
||||
# To use Azure IoT Central, you will need to create an IoT Central app.
|
||||
# You can either create a free tier app that will live for 7 days without an Azure subscription,
|
||||
# Or a standard tier app that will last for ever with an Azure subscription.
|
||||
|
|
@ -63,7 +85,7 @@ while not ntp.valid_time:
|
|||
from adafruit_azureiot import IoTCentralDevice
|
||||
|
||||
# Create an IoT Hub device client and connect
|
||||
device = IoTCentralDevice(wifi, secrets["id_scope"], secrets["device_id"], secrets["key"])
|
||||
device = IoTCentralDevice(socket, esp, secrets["id_scope"], secrets["device_id"], secrets["key"])
|
||||
|
||||
# Subscribe to property changes
|
||||
# Properties can be updated either in code, or by adding a form to the view
|
||||
|
|
@ -72,22 +94,36 @@ def property_changed(property_name, property_value, version):
|
|||
print("Property", property_name, "updated to", str(property_value), "version", str(version))
|
||||
|
||||
|
||||
# Subscribe to the property changed event
|
||||
device.on_property_changed = property_changed
|
||||
|
||||
print("Connecting to Azure IoT Central...")
|
||||
|
||||
# Connect to IoT Central
|
||||
device.connect()
|
||||
|
||||
print("Connected to Azure IoT Central!")
|
||||
|
||||
message_counter = 60
|
||||
|
||||
while True:
|
||||
# Send property values every minute
|
||||
# You can see the values in the devices dashboard
|
||||
if message_counter >= 60:
|
||||
device.send_property("Desired_Temperature", random.randint(0, 50))
|
||||
message_counter = 0
|
||||
else:
|
||||
message_counter = message_counter + 1
|
||||
try:
|
||||
# Send property values every minute
|
||||
# You can see the values in the devices dashboard
|
||||
if message_counter >= 60:
|
||||
device.send_property("Desired_Temperature", random.randint(0, 50))
|
||||
message_counter = 0
|
||||
else:
|
||||
message_counter = message_counter + 1
|
||||
|
||||
# Poll every second for messages from the cloud
|
||||
device.loop()
|
||||
# Poll every second for messages from the cloud
|
||||
device.loop()
|
||||
except (ValueError, RuntimeError) as e:
|
||||
print("Connection error, reconnecting\n", str(e))
|
||||
# If we lose connectivity, reset the wifi and reconnect
|
||||
wifi.reset()
|
||||
wifi.connect()
|
||||
device.reconnect()
|
||||
continue
|
||||
|
||||
time.sleep(1)
|
||||
|
|
|
|||
|
|
@ -4,7 +4,9 @@ import time
|
|||
import board
|
||||
import busio
|
||||
from digitalio import DigitalInOut
|
||||
import neopixel
|
||||
from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
|
||||
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
|
||||
from adafruit_ntp import NTP
|
||||
|
||||
# Get wifi details and more from a secrets.py file
|
||||
|
|
@ -27,15 +29,35 @@ except AttributeError:
|
|||
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
|
||||
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
|
||||
|
||||
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets)
|
||||
"""Use below for Most Boards"""
|
||||
status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards
|
||||
"""Uncomment below for ItsyBitsy M4"""
|
||||
# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
|
||||
# Uncomment below for an externally defined RGB LED
|
||||
# import adafruit_rgbled
|
||||
# from adafruit_esp32spi import PWMOut
|
||||
# RED_LED = PWMOut.PWMOut(esp, 26)
|
||||
# GREEN_LED = PWMOut.PWMOut(esp, 27)
|
||||
# BLUE_LED = PWMOut.PWMOut(esp, 25)
|
||||
# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)
|
||||
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
|
||||
|
||||
print("Connecting to WiFi...")
|
||||
|
||||
wifi.connect()
|
||||
|
||||
print("Connected to WiFi!")
|
||||
|
||||
print("Getting the time...")
|
||||
|
||||
ntp = NTP(esp)
|
||||
# Wait for a valid time to be received
|
||||
while not ntp.valid_time:
|
||||
time.sleep(5)
|
||||
ntp.set_time()
|
||||
|
||||
print("Time:", str(time.time()))
|
||||
|
||||
# To use Azure IoT Central, you will need to create an IoT Central app.
|
||||
# You can either create a free tier app that will live for 7 days without an Azure subscription,
|
||||
# Or a standard tier app that will last for ever with an Azure subscription.
|
||||
|
|
@ -64,22 +86,36 @@ while not ntp.valid_time:
|
|||
from adafruit_azureiot import IoTCentralDevice
|
||||
|
||||
# Create an IoT Hub device client and connect
|
||||
device = IoTCentralDevice(wifi, secrets["id_scope"], secrets["device_id"], secrets["key"])
|
||||
device = IoTCentralDevice(socket, esp, secrets["id_scope"], secrets["device_id"], secrets["key"])
|
||||
|
||||
print("Connecting to Azure IoT Central...")
|
||||
|
||||
# Connect to IoT Central
|
||||
device.connect()
|
||||
|
||||
print("Connected to Azure IoT Central!")
|
||||
|
||||
message_counter = 60
|
||||
|
||||
while True:
|
||||
# Send telemetry every minute
|
||||
# You can see the values in the devices dashboard
|
||||
if message_counter >= 60:
|
||||
message = {"Temperature": random.randint(0, 50)}
|
||||
device.send_telemetry(json.dumps(message))
|
||||
message_counter = 0
|
||||
else:
|
||||
message_counter = message_counter + 1
|
||||
try:
|
||||
# Send telemetry every minute
|
||||
# You can see the values in the devices dashboard
|
||||
if message_counter >= 60:
|
||||
message = {"Temperature": random.randint(0, 50)}
|
||||
device.send_telemetry(json.dumps(message))
|
||||
message_counter = 0
|
||||
else:
|
||||
message_counter = message_counter + 1
|
||||
|
||||
# Poll every second for messages from the cloud
|
||||
device.loop()
|
||||
# Poll every second for messages from the cloud
|
||||
device.loop()
|
||||
except (ValueError, RuntimeError) as e:
|
||||
print("Connection error, reconnecting\n", str(e))
|
||||
# If we lose connectivity, reset the wifi and reconnect
|
||||
wifi.reset()
|
||||
wifi.connect()
|
||||
device.reconnect()
|
||||
continue
|
||||
|
||||
time.sleep(1)
|
||||
|
|
|
|||
|
|
@ -2,7 +2,9 @@ import time
|
|||
import board
|
||||
import busio
|
||||
from digitalio import DigitalInOut
|
||||
import neopixel
|
||||
from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
|
||||
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
|
||||
from adafruit_ntp import NTP
|
||||
|
||||
# Get wifi details and more from a secrets.py file
|
||||
|
|
@ -25,15 +27,35 @@ except AttributeError:
|
|||
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
|
||||
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
|
||||
|
||||
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets)
|
||||
"""Use below for Most Boards"""
|
||||
status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards
|
||||
"""Uncomment below for ItsyBitsy M4"""
|
||||
# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
|
||||
# Uncomment below for an externally defined RGB LED
|
||||
# import adafruit_rgbled
|
||||
# from adafruit_esp32spi import PWMOut
|
||||
# RED_LED = PWMOut.PWMOut(esp, 26)
|
||||
# GREEN_LED = PWMOut.PWMOut(esp, 27)
|
||||
# BLUE_LED = PWMOut.PWMOut(esp, 25)
|
||||
# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)
|
||||
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
|
||||
|
||||
print("Connecting to WiFi...")
|
||||
|
||||
wifi.connect()
|
||||
|
||||
print("Connected to WiFi!")
|
||||
|
||||
print("Getting the time...")
|
||||
|
||||
ntp = NTP(esp)
|
||||
# Wait for a valid time to be received
|
||||
while not ntp.valid_time:
|
||||
time.sleep(5)
|
||||
ntp.set_time()
|
||||
|
||||
print("Time:", str(time.time()))
|
||||
|
||||
# You will need an Azure subscription to create an Azure IoT Hub resource
|
||||
#
|
||||
# If you don't have an Azure subscription:
|
||||
|
|
@ -58,7 +80,7 @@ from adafruit_azureiot import IoTHubDevice
|
|||
from adafruit_azureiot.iot_mqtt import IoTResponse
|
||||
|
||||
# Create an IoT Hub device client and connect
|
||||
device = IoTHubDevice(wifi, secrets["device_connection_string"])
|
||||
device = IoTHubDevice(socket, esp, secrets["device_connection_string"])
|
||||
|
||||
# Subscribe to direct method calls
|
||||
# To invoke a method on the device, select it in the Azure Portal, select Direct Method,
|
||||
|
|
@ -71,12 +93,26 @@ def direct_method_invoked(method_name: str, payload) -> IoTResponse:
|
|||
return IoTResponse(200, "OK")
|
||||
|
||||
|
||||
# Subscribe to the direct method invoked event
|
||||
device.on_direct_method_invoked = direct_method_invoked
|
||||
|
||||
print("Connecting to Azure IoT Hub...")
|
||||
|
||||
# Connect to IoT Central
|
||||
device.connect()
|
||||
|
||||
print("Connected to Azure IoT Hub!")
|
||||
|
||||
while True:
|
||||
# Poll every second for messages from the cloud
|
||||
device.loop()
|
||||
try:
|
||||
# Poll every second for messages from the cloud
|
||||
device.loop()
|
||||
except (ValueError, RuntimeError) as e:
|
||||
print("Connection error, reconnecting\n", str(e))
|
||||
# If we lose connectivity, reset the wifi and reconnect
|
||||
wifi.reset()
|
||||
wifi.connect()
|
||||
device.reconnect()
|
||||
continue
|
||||
|
||||
time.sleep(1)
|
||||
|
|
|
|||
|
|
@ -4,7 +4,9 @@ import time
|
|||
import board
|
||||
import busio
|
||||
from digitalio import DigitalInOut
|
||||
import neopixel
|
||||
from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
|
||||
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
|
||||
from adafruit_ntp import NTP
|
||||
|
||||
# Get wifi details and more from a secrets.py file
|
||||
|
|
@ -27,15 +29,35 @@ except AttributeError:
|
|||
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
|
||||
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
|
||||
|
||||
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets)
|
||||
"""Use below for Most Boards"""
|
||||
status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards
|
||||
"""Uncomment below for ItsyBitsy M4"""
|
||||
# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
|
||||
# Uncomment below for an externally defined RGB LED
|
||||
# import adafruit_rgbled
|
||||
# from adafruit_esp32spi import PWMOut
|
||||
# RED_LED = PWMOut.PWMOut(esp, 26)
|
||||
# GREEN_LED = PWMOut.PWMOut(esp, 27)
|
||||
# BLUE_LED = PWMOut.PWMOut(esp, 25)
|
||||
# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)
|
||||
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
|
||||
|
||||
print("Connecting to WiFi...")
|
||||
|
||||
wifi.connect()
|
||||
|
||||
print("Connected to WiFi!")
|
||||
|
||||
print("Getting the time...")
|
||||
|
||||
ntp = NTP(esp)
|
||||
# Wait for a valid time to be received
|
||||
while not ntp.valid_time:
|
||||
time.sleep(5)
|
||||
ntp.set_time()
|
||||
|
||||
print("Time:", str(time.time()))
|
||||
|
||||
# You will need an Azure subscription to create an Azure IoT Hub resource
|
||||
#
|
||||
# If you don't have an Azure subscription:
|
||||
|
|
@ -59,7 +81,7 @@ while not ntp.valid_time:
|
|||
from adafruit_azureiot import IoTHubDevice
|
||||
|
||||
# Create an IoT Hub device client and connect
|
||||
device = IoTHubDevice(wifi, secrets["device_connection_string"])
|
||||
device = IoTHubDevice(socket, esp, secrets["device_connection_string"])
|
||||
|
||||
# Subscribe to cloud to device messages
|
||||
# To send a message to the device, select it in the Azure Portal, select Message To Device,
|
||||
|
|
@ -68,24 +90,38 @@ def cloud_to_device_message_received(body: str, properties: dict):
|
|||
print("Received message with body", body, "and properties", json.dumps(properties))
|
||||
|
||||
|
||||
# Subscribe to the cloud to device message received events
|
||||
device.on_cloud_to_device_message_received = cloud_to_device_message_received
|
||||
|
||||
print("Connecting to Azure IoT Hub...")
|
||||
|
||||
# Connect to IoT Central
|
||||
device.connect()
|
||||
|
||||
print("Connected to Azure IoT Hub!")
|
||||
|
||||
message_counter = 60
|
||||
|
||||
while True:
|
||||
# Send a device to cloud message every minute
|
||||
# You can see the overview of messages sent from the device in the Overview tab
|
||||
# of the IoT Hub in the Azure Portal
|
||||
if message_counter >= 60:
|
||||
message = {"Temperature": random.randint(0, 50)}
|
||||
device.send_device_to_cloud_message(json.dumps(message))
|
||||
message_counter = 0
|
||||
else:
|
||||
message_counter = message_counter + 1
|
||||
try:
|
||||
# Send a device to cloud message every minute
|
||||
# You can see the overview of messages sent from the device in the Overview tab
|
||||
# of the IoT Hub in the Azure Portal
|
||||
if message_counter >= 60:
|
||||
message = {"Temperature": random.randint(0, 50)}
|
||||
device.send_device_to_cloud_message(json.dumps(message))
|
||||
message_counter = 0
|
||||
else:
|
||||
message_counter = message_counter + 1
|
||||
|
||||
# Poll every second for messages from the cloud
|
||||
device.loop()
|
||||
# Poll every second for messages from the cloud
|
||||
device.loop()
|
||||
except (ValueError, RuntimeError) as e:
|
||||
print("Connection error, reconnecting\n", str(e))
|
||||
# If we lose connectivity, reset the wifi and reconnect
|
||||
wifi.reset()
|
||||
wifi.connect()
|
||||
device.reconnect()
|
||||
continue
|
||||
|
||||
time.sleep(1)
|
||||
|
|
|
|||
|
|
@ -4,7 +4,9 @@ import time
|
|||
import board
|
||||
import busio
|
||||
from digitalio import DigitalInOut
|
||||
import neopixel
|
||||
from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
|
||||
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
|
||||
from adafruit_ntp import NTP
|
||||
|
||||
# Get wifi details and more from a secrets.py file
|
||||
|
|
@ -27,15 +29,35 @@ except AttributeError:
|
|||
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
|
||||
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
|
||||
|
||||
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets)
|
||||
"""Use below for Most Boards"""
|
||||
status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards
|
||||
"""Uncomment below for ItsyBitsy M4"""
|
||||
# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
|
||||
# Uncomment below for an externally defined RGB LED
|
||||
# import adafruit_rgbled
|
||||
# from adafruit_esp32spi import PWMOut
|
||||
# RED_LED = PWMOut.PWMOut(esp, 26)
|
||||
# GREEN_LED = PWMOut.PWMOut(esp, 27)
|
||||
# BLUE_LED = PWMOut.PWMOut(esp, 25)
|
||||
# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)
|
||||
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
|
||||
|
||||
print("Connecting to WiFi...")
|
||||
|
||||
wifi.connect()
|
||||
|
||||
print("Connected to WiFi!")
|
||||
|
||||
print("Getting the time...")
|
||||
|
||||
ntp = NTP(esp)
|
||||
# Wait for a valid time to be received
|
||||
while not ntp.valid_time:
|
||||
time.sleep(5)
|
||||
ntp.set_time()
|
||||
|
||||
print("Time:", str(time.time()))
|
||||
|
||||
# You will need an Azure subscription to create an Azure IoT Hub resource
|
||||
#
|
||||
# If you don't have an Azure subscription:
|
||||
|
|
@ -59,23 +81,37 @@ while not ntp.valid_time:
|
|||
from adafruit_azureiot import IoTHubDevice
|
||||
|
||||
# Create an IoT Hub device client and connect
|
||||
device = IoTHubDevice(wifi, secrets["device_connection_string"])
|
||||
device = IoTHubDevice(socket, esp, secrets["device_connection_string"])
|
||||
|
||||
print("Connecting to Azure IoT Hub...")
|
||||
|
||||
# Connect to IoT Central
|
||||
device.connect()
|
||||
|
||||
print("Connected to Azure IoT Hub!")
|
||||
|
||||
message_counter = 60
|
||||
|
||||
while True:
|
||||
# Send a device to cloud message every minute
|
||||
# You can see the overview of messages sent from the device in the Overview tab
|
||||
# of the IoT Hub in the Azure Portal
|
||||
if message_counter >= 60:
|
||||
message = {"Temperature": random.randint(0, 50)}
|
||||
device.send_device_to_cloud_message(json.dumps(message))
|
||||
message_counter = 0
|
||||
else:
|
||||
message_counter = message_counter + 1
|
||||
try:
|
||||
# Send a device to cloud message every minute
|
||||
# You can see the overview of messages sent from the device in the Overview tab
|
||||
# of the IoT Hub in the Azure Portal
|
||||
if message_counter >= 60:
|
||||
message = {"Temperature": random.randint(0, 50)}
|
||||
device.send_device_to_cloud_message(json.dumps(message))
|
||||
message_counter = 0
|
||||
else:
|
||||
message_counter = message_counter + 1
|
||||
|
||||
# Poll every second for messages from the cloud
|
||||
device.loop()
|
||||
# Poll every second for messages from the cloud
|
||||
device.loop()
|
||||
except (ValueError, RuntimeError) as e:
|
||||
print("Connection error, reconnecting\n", str(e))
|
||||
# If we lose connectivity, reset the wifi and reconnect
|
||||
wifi.reset()
|
||||
wifi.connect()
|
||||
device.reconnect()
|
||||
continue
|
||||
|
||||
time.sleep(1)
|
||||
|
|
|
|||
|
|
@ -3,7 +3,9 @@ import time
|
|||
import board
|
||||
import busio
|
||||
from digitalio import DigitalInOut
|
||||
import neopixel
|
||||
from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
|
||||
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
|
||||
from adafruit_ntp import NTP
|
||||
|
||||
# Get wifi details and more from a secrets.py file
|
||||
|
|
@ -26,15 +28,35 @@ except AttributeError:
|
|||
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
|
||||
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
|
||||
|
||||
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets)
|
||||
"""Use below for Most Boards"""
|
||||
status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards
|
||||
"""Uncomment below for ItsyBitsy M4"""
|
||||
# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
|
||||
# Uncomment below for an externally defined RGB LED
|
||||
# import adafruit_rgbled
|
||||
# from adafruit_esp32spi import PWMOut
|
||||
# RED_LED = PWMOut.PWMOut(esp, 26)
|
||||
# GREEN_LED = PWMOut.PWMOut(esp, 27)
|
||||
# BLUE_LED = PWMOut.PWMOut(esp, 25)
|
||||
# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)
|
||||
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
|
||||
|
||||
print("Connecting to WiFi...")
|
||||
|
||||
wifi.connect()
|
||||
|
||||
print("Connected to WiFi!")
|
||||
|
||||
print("Getting the time...")
|
||||
|
||||
ntp = NTP(esp)
|
||||
# Wait for a valid time to be received
|
||||
while not ntp.valid_time:
|
||||
time.sleep(5)
|
||||
ntp.set_time()
|
||||
|
||||
print("Time:", str(time.time()))
|
||||
|
||||
# You will need an Azure subscription to create an Azure IoT Hub resource
|
||||
#
|
||||
# If you don't have an Azure subscription:
|
||||
|
|
@ -61,7 +83,7 @@ while not ntp.valid_time:
|
|||
from adafruit_azureiot import IoTHubDevice
|
||||
|
||||
# Create an IoT Hub device client and connect
|
||||
device = IoTHubDevice(wifi, secrets["device_connection_string"])
|
||||
device = IoTHubDevice(socket, esp, secrets["device_connection_string"])
|
||||
|
||||
# Subscribe to device twin desired property updates
|
||||
# To see these changes, update the desired properties for the device either in code
|
||||
|
|
@ -71,24 +93,38 @@ def device_twin_desired_updated(desired_property_name: str, desired_property_val
|
|||
print("Property", desired_property_name, "updated to", str(desired_property_value), "version", desired_version)
|
||||
|
||||
|
||||
# Subscribe to the device twin desired property updated event
|
||||
device.on_device_twin_desired_updated = device_twin_desired_updated
|
||||
|
||||
print("Connecting to Azure IoT Hub...")
|
||||
|
||||
# Connect to IoT Central
|
||||
device.connect()
|
||||
|
||||
print("Connected to Azure IoT Hub!")
|
||||
|
||||
message_counter = 60
|
||||
|
||||
while True:
|
||||
if message_counter >= 60:
|
||||
# Send a reported property twin update every minute
|
||||
# You can see these in the portal by selecting the device in the IoT Hub blade, selecting
|
||||
# Device Twin then looking for the updates in the 'reported' section
|
||||
patch = {"Temperature": random.randint(0, 50)}
|
||||
device.update_twin(patch)
|
||||
message_counter = 0
|
||||
else:
|
||||
message_counter = message_counter + 1
|
||||
try:
|
||||
if message_counter >= 60:
|
||||
# Send a reported property twin update every minute
|
||||
# You can see these in the portal by selecting the device in the IoT Hub blade, selecting
|
||||
# Device Twin then looking for the updates in the 'reported' section
|
||||
patch = {"Temperature": random.randint(0, 50)}
|
||||
device.update_twin(patch)
|
||||
message_counter = 0
|
||||
else:
|
||||
message_counter = message_counter + 1
|
||||
|
||||
# Poll every second for messages from the cloud
|
||||
device.loop()
|
||||
# Poll every second for messages from the cloud
|
||||
device.loop()
|
||||
except (ValueError, RuntimeError) as e:
|
||||
print("Connection error, reconnecting\n", str(e))
|
||||
# If we lose connectivity, reset the wifi and reconnect
|
||||
wifi.reset()
|
||||
wifi.connect()
|
||||
device.reconnect()
|
||||
continue
|
||||
|
||||
time.sleep(1)
|
||||
|
|
|
|||
Loading…
Reference in a new issue