Skip to content

Commit

Permalink
Update samples and docs
Browse files Browse the repository at this point in the history
  • Loading branch information
askpatrickw committed Jan 25, 2022
1 parent 957f945 commit b58345d
Show file tree
Hide file tree
Showing 15 changed files with 775 additions and 26 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
.python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
Expand Down
24 changes: 22 additions & 2 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,9 @@ To create an Azure IoT Hub instance or an Azure IoT Central app, you will need a

- If you are not a student, head to `aka.ms/FreeAz <https://aka.ms/FreeAz>`_ and sign up to get $200 of credit for 30 days, as well as free tiers of a load of services. You will need a credit card for validation only, your card will not be charged.

ESP32SPI Networking
===================

To use this library, you will need to create an ESP32_SPI WifiManager, connected to WiFi. You will also need to set the current time, as this is used to generate time-based authentication keys. One way to do this is via the `Adafruit CircuitPython NTP <https://github.com/adafruit/Adafruit_CircuitPython_NTP>`_ library with the following code:

.. code-block:: python
Expand All @@ -74,6 +77,23 @@ To use this library, you will need to create an ESP32_SPI WifiManager, connected
time.sleep(5)
ntp.set_time()
Native Networking
=================
To use this library, with boards that have native networking support, you need to be connected to a network. You will also need to set the current time, as this is used to generate time-based authentication keys. One way to do this is by using the `Adafruit IoT Time Service <https://io.adafruit.com/api/docs/#time>`_ via the `Requests library <https://github.com/adafruit/Adafruit_CircuitPython_Requests/>_` with the following code:

.. code-block:: python
pool = socketpool.SocketPool(wifi.radio)
requests = adafruit_requests.Session(pool, ssl.create_default_context())
response = requests.get("https://io.adafruit.com/api/v2/time/seconds")
if response:
if response.status_code == 200:
r = rtc.RTC()
r.datetime = time.localtime(int(response.text))
print(f"System Time: {r.datetime}")
else:
print("Setting time failed")
Azure IoT Hub
-------------

Expand Down Expand Up @@ -172,7 +192,7 @@ To use Azure IoT Central, you will need to create an Azure IoT Central app, crea
- Head to `Azure IoT Central <https://apps.azureiotcentral.com/?WT.mc_id=academic-3168-jabenn>`__
- Follow the instructions in the `Microsoft Docs <https://docs.microsoft.com/azure/iot-central/core/quick-deploy-iot-central?WT.mc_id=academic-3168-jabenn>`__ to create an application. Every tier is free for up to 2 devices.
- Follow the instructions in the `Microsoft Docs <https://docs.microsoft.com/azure/iot-central/core/quick-create-simulated-device?WT.mc_id=academic-3168-jabenn>`__ to create a device template.
- Create a device based off the template, and select **Connect** to get the device connection details. Store the ID Scope, Device ID and either the Primary or secondary Key in your ``secrets.py`` file.
- Create a device based off the template, and select **Connect** to get the device connection details. Store the ID Scope, Device ID and either the primary or secondary device SAS key in your ``secrets.py`` file.

.. image:: iot-central-connect-button.png
:alt: The IoT Central connect button
Expand All @@ -194,7 +214,7 @@ To use Azure IoT Central, you will need to create an Azure IoT Central app, crea
# Azure IoT Central settings
"id_scope": "",
"device_id": "",
"key": ""
"device_sas_key": ""
}
**Connect your device to your Azure IoT Central app**
Expand Down
90 changes: 72 additions & 18 deletions docs/examples.rst
Original file line number Diff line number Diff line change
@@ -1,53 +1,107 @@
IoT Hub
IoT Hub ESP32SPI Networking
------------

Ensure your IoT Hub device works with this simple test.

.. literalinclude:: ../examples/azureiot_hub_simpletest.py
:caption: examples/azureiot_hub_simpletest.py
.. literalinclude:: ../examples/esp32spi/azureiot_hub_simpletest.py
:caption: examples/esp32spi/azureiot_hub_simpletest.py
:linenos:

Handle direct methods.

.. literalinclude:: ../examples/azureiot_hub_directmethods.py
:caption: examples/azureiot_hub_directmethods.py
.. literalinclude:: ../examples/esp32spi/azureiot_hub_directmethods.py
:caption: examples/esp32spi/azureiot_hub_directmethods.py
:linenos:

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

.. literalinclude:: ../examples/azureiot_hub_messages.py
:caption: examples/azureiot_hub_messages.py
.. literalinclude:: ../examples/esp32spi/azureiot_hub_messages.py
:caption: examples/esp32spi/azureiot_hub_messages.py
:linenos:

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

.. literalinclude:: ../examples/azureiot_hub_twin_operations.py
:caption: examples/azureiot_hub_twin_operations.py
.. literalinclude:: ../examples/esp32spi/azureiot_hub_twin_operations.py
:caption: examples/esp32spi/azureiot_hub_twin_operations.py
:linenos:

IoT Central
IoT Central ESP32SPI Networking
------------

Ensure your IoT Central device works with this simple test.

.. literalinclude:: ../examples/azureiot_central_simpletest.py
:caption: examples/azureiot_central_simpletest.py
.. literalinclude:: ../examples/esp32spi/azureiot_central_simpletest.py
:caption: examples/esp32spi/azureiot_central_simpletest.py
:linenos:

Handle commands.

.. literalinclude:: ../examples/azureiot_central_commands.py
:caption: examples/azureiot_central_commands.py
.. literalinclude:: ../examples/esp32spi/azureiot_central_commands.py
:caption: examples/esp32spi/azureiot_central_commands.py
:linenos:

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

.. literalinclude:: ../examples/azureiot_central_properties.py
:caption: examples/azureiot_central_properties.py
.. literalinclude:: ../examples/esp32spi/azureiot_central_properties.py
:caption: examples/esp32spi/azureiot_central_properties.py
:linenos:

Handle connection errors.

.. literalinclude:: ../examples/azureiot_central_notconnected.py
:caption: examples/azureiot_central_notconnected.py
.. literalinclude:: ../examples/esp32spi/azureiot_central_notconnected.py
:caption: examples/esp32spi/azureiot_central_notconnected.py
:linenos:

IoT Hub Native Networking
------------

Ensure your IoT Hub device works with this simple test.

.. literalinclude:: ../examples/native_networking/azureiot_hub_simpletest.py
:caption: examples/native_networking/azureiot_hub_simpletest.py
:linenos:

Handle direct methods.

.. literalinclude:: ../examples/native_networking/azureiot_hub_directmethods.py
:caption: examples/native_networking/azureiot_hub_directmethods.py
:linenos:

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

.. literalinclude:: ../examples/native_networking/azureiot_hub_messages.py
:caption: examples/native_networking/azureiot_hub_messages.py
:linenos:

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

.. literalinclude:: ../examples/native_networking/azureiot_hub_twin_operations.py
:caption: examples/native_networking/azureiot_hub_twin_operations.py
:linenos:

IoT Central Native Networking
------------

Ensure your IoT Central device works with this simple test.

.. literalinclude:: ../examples/native_networking/azureiot_central_simpletest.py
:caption: examples/native_networking/azureiot_central_simpletest.py
:linenos:

Handle commands.

.. literalinclude:: ../examples/native_networking/azureiot_central_commands.py
:caption: examples/native_networking/azureiot_central_commands.py
:linenos:

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

.. literalinclude:: ../examples/native_networking/azureiot_central_properties.py
:caption: examples/native_networking/azureiot_central_properties.py
:linenos:

Handle connection errors.

.. literalinclude:: ../examples/native_networking/azureiot_central_notconnected.py
:caption: examples/native_networking/azureiot_central_notconnected.py
:linenos:
2 changes: 1 addition & 1 deletion examples/ esp32spi /azureiot_central_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@
#
# 'id_scope' - the devices ID scope
# 'device_id' - the devices device id
# 'key' - the devices primary key
# 'device_sas_key' - the devices primary key
#
# The adafruit-circuitpython-azureiot library depends on the following libraries:
#
Expand Down
2 changes: 1 addition & 1 deletion examples/ esp32spi /azureiot_central_notconnected.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@
#
# 'id_scope' - the devices ID scope
# 'device_id' - the devices device id
# 'key' - the devices primary key
# 'device_sas_key' - the devices primary key
#
# The adafruit-circuitpython-azureiot library depends on the following libraries:
#
Expand Down
2 changes: 1 addition & 1 deletion examples/ esp32spi /azureiot_central_properties.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@
#
# 'id_scope' - the devices ID scope
# 'device_id' - the devices device id
# 'key' - the devices primary key
# 'device_sas_key' - the devices primary key
#
# The adafruit-circuitpython-azureiot library depends on the following libraries:
#
Expand Down
2 changes: 1 addition & 1 deletion examples/ esp32spi /azureiot_central_simpletest.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@
#
# 'id_scope' - the devices ID scope
# 'device_id' - the devices device id
# 'key' - the devices primary key
# 'device_sas_key' - the devices primary key
#
# The adafruit-circuitpython-azureiot library depends on the following libraries:
#
Expand Down
115 changes: 115 additions & 0 deletions examples/native_networking/azureiot_central_commands.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT

import ssl
import time

import rtc
import socketpool
import wifi

import adafruit_requests
from adafruit_azureiot import IoTCentralDevice
from adafruit_azureiot.iot_mqtt import IoTResponse

# Get wifi details and more from a secrets.py file
try:
from secrets import secrets
except ImportError:
print("WiFi secrets are kept in secrets.py, please add them there!")
raise

print("Connecting to WiFi...")
wifi.radio.connect(secrets["ssid"], secrets["password"])

print("Connected to WiFi!")

if time.localtime().tm_year < 2022:
print("Setting System Time in UTC")
pool = socketpool.SocketPool(wifi.radio)
requests = adafruit_requests.Session(pool, ssl.create_default_context())
response = requests.get("https://io.adafruit.com/api/v2/time/seconds")
if response:
if response.status_code == 200:
r = rtc.RTC()
r.datetime = time.localtime(int(response.text))
print(f"System Time: {r.datetime}")
else:
print("Setting time failed")
else:
print("Year seems good, skipping set 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.
# The standard tiers are free for up to 2 devices
#
# If you don't have an Azure subscription:
#
# If you are a student, head to https://aka.ms/FreeStudentAzure and sign up, validating with your
# student email address. This will give you $100 of Azure credit and free tiers of a load of
# service, renewable each year you are a student
#
# If you are not a student, head to https://aka.ms/FreeAz and sign up to get $200 of credit for 30
# days, as well as free tiers of a load of services
#
# Create an Azure IoT Central app by following these instructions: https://aka.ms/CreateIoTCentralApp
# Add a device template with telemetry, properties and commands, as well as a view to visualize the
# telemetry and execute commands, and a form to set properties.
#
# Next create a device using the device template, and select Connect to get the device connection details.
# Add the connection details to your secrets.py file, using the following values:
#
# 'id_scope' - the devices ID scope
# 'device_id' - the devices device id
# 'device_sas_key' - the devices primary key
#
# The adafruit-circuitpython-azureiot library depends on the following libraries:
#
# From the Adafruit CircuitPython Bundle (https://github.com/adafruit/Adafruit_CircuitPython_Bundle):
# * adafruit-circuitpython-minimqtt
# * adafruit-circuitpython-requests


# Create an IoT Hub device client and connect
esp = None
pool = socketpool.SocketPool(wifi.radio)
device = IoTCentralDevice(
pool, esp, secrets["id_scope"], secrets["device_id"], secrets["device_sas_key"]
)

# Subscribe to commands
# Commands can be sent from the devices Dashboard in IoT Central, assuming
# the device template and view has been set up with the commands
# Command handlers need to return a response to show if the command was handled
# successfully or not, returning an HTTP status code and message
def command_executed(command_name: str, payload) -> IoTResponse:
print("Command", command_name, "executed with payload", str(payload))
# return a status code and message to indicate if the command was handled correctly
return IoTResponse(200, "OK")


# Subscribe to the command execute event
device.on_command_executed = command_executed


print("Connecting to Azure IoT Central...")
device.connect()

print("Connected to Azure IoT Central!")

message_counter = 60

while True:
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)

0 comments on commit b58345d

Please sign in to comment.