#AzureIoT – Working with devices and Edge Modules to access Digital Twin Settings

Hi !

Once I got my real and 3D virtual device [smart door] working, it’s time to interact with the Digital Twin information from the IoT Edge device and also from the Iot Edge Module device.

Current documentation is kind of tricky, there are several demos on how to interact with the Device. However, working with Iot Edge Module Twin information, is more of a “guess and try” scenario.

So, here are some lessons learned from my experience. “Future Bruno” will avoid some headaches in the near future.

Important: I strongly advice to read “Get started with device twins“, in order to understand the different parts involved in this scenario.

Let’s start with the 2 packages that needs to be installed:

pip install azure-iot-hub
pip install azure-iot-device

And let’s start with the base scenario.

  • Important, line 10 uses the IoTHub connection string, not the device one.
  • Line 17 shows how to access to the twin device.
  • Line 22 shows how to access to the twin device modules.
  • Line 26 iterates and shows the modules id and connection state

# code based on
# https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-python-twin-getstarted
import sys
from time import sleep
from azure.iot.hub import IoTHubRegistryManager
from azure.iot.hub.models import Twin, TwinProperties, QuerySpecification, QueryResult
# connect using IoTHub connection string and device id with the module identity name
IOTHUB_CONNECTION_STRING = "IOT HUB Connection String"
DEVICE_ID = 'Device Id'
MODULE_ID = 'DoorController'
# create IoTHub Registry Manager
iothub_registry_manager = IoTHubRegistryManager(IOTHUB_CONNECTION_STRING)
# get twin reference https://docs.microsoft.com/en-us/rest/api/iothub/service/devices/get-twin
twin = iothub_registry_manager.get_twin(DEVICE_ID)
print(type(twin))
# get modules
# https://docs.microsoft.com/en-us/rest/api/iothub/service/modules/get-modules-on-device#module
modules = iothub_registry_manager.get_modules(DEVICE_ID)
print(type(modules))
# iterate through modules
for module in modules:
print(type(module))
print(module.module_id)
print(module.connection_state)

The console output shows a the device module and information.

<class 'azure.iot.hub.protocol.models.twin_py3.Twin'>
<class 'list'>
<class 'azure.iot.hub.protocol.models.module_py3.Module'>
$edgeAgent
Disconnected
<class 'azure.iot.hub.protocol.models.module_py3.Module'>
$edgeHub
Connected
<class 'azure.iot.hub.protocol.models.module_py3.Module'>
DoorController
Connected
<class 'azure.iot.hub.protocol.models.module_py3.Module'>
ImageDrawings
Disconnected
DoorController
Connected

In Azure IoT Explorer, we can see all the modules.

azure iot sample of module identitites

Each one may have their preferences, for me, Python “help()” is a great way to inspect each object structure and members.

In example adding this line after we get the twin object

# get twin reference https://docs.microsoft.com/en-us/rest/api/iothub/service/devices/get-twin
twin = iothub_registry_manager.get_twin(DEVICE_ID)
print(type(twin))
print(help(twin))

Will display this.

Help on Twin in module azure.iot.hub.protocol.models.twin_py3 object:

class Twin(msrest.serialization.Model)
 |  Twin(*, device_id: str = None, module_id: str = None, tags=None, properties=None, etag: str = None, version: int = None, device_etag: str = None, status=None, status_reason: str = None, status_update_time=None, connection_state=None, last_activity_time=None, cloud_to_device_message_count: int = None, authentication_type=None, x509_thumbprint=None, capabilities=None, device_scope: str = None, parent_scopes=None, **kwargs) -> None
 |
 |  The state information for a device or module. This is implicitly created
 |  and deleted when the corresponding device/ module identity is created or
 |  deleted in the IoT Hub.
 |
 |  :param device_id: The unique identifier of the device in the identity
 |   registry of the IoT Hub. It is a case-sensitive string (up to 128 char
 |   long) of ASCII 7-bit alphanumeric chars, and the following special
 |   characters {'-', ':', '.', '+', '%', '_', '#', '*', '?', '!', '(', ')',
 |   ',', '=', '@', ';', '$', '''}.
 |  :type device_id: str
 |  :param module_id: The unique identifier of the module in the identity
 |   registry of the IoT Hub. It is a case-sensitive string (up to 128 char
 |   long) of ASCII 7-bit alphanumeric chars, and the following special
 |   characters {'-', ':', '.', '+', '%', '_', '#', '*', '?', '!', '(', ')',
 |   ',', '=', '@', ';', '$', '''}.
 |  :type module_id: str
 |  :param tags: The collection of key-value pairs read and written by the
 |   solution back end. They are not visible to device apps. They keys are
 |   UTF-8 encoded, case-sensitive and up-to 1KB in length. Allowed characters
 |   exclude UNICODE control characters (segments C0 and C1), '.', '$' and
 |   space. The values are JSON objects, up-to 4KB in length.
 |  :type tags: dict[str, object]
 |  :param properties: The desired and reported properties of the twin.
 |  :type properties: ~protocol.models.TwinProperties
 |  :param etag: The string representing a ETag for the device twin, as per
 |   RFC7232.
 |  :type etag: str
 |  :param version: The version for the device twin including tags and desired
 |   properties
 |  :type version: long
 |  :param device_etag: The string representing a ETag for the device, as per
 |   RFC7232.
 |  :type device_etag: str
 |  :param status: The enabled status of the device. If disabled, the device
 |   cannot connect to the service. Possible values include: 'enabled',
 |   'disabled'
 |  :type status: str or ~protocol.models.enum
 |  :param status_reason: The reason for the current status of the device, if
 |   any.
 |  :type status_reason: str
 |  :param status_update_time: The date and time when the status of the device
 |   was last updated.
 |  :type status_update_time: datetime
 |  :param connection_state: The connection state of the device. Possible
-- More  --

Ok, that’s is for me for today. In next posts, I’ll show how to access and update Twin Properties for an Azure IoT Edge Module/

References

Happy coding!

Greetings

El Bruno



¿Con ganas de ponerte al día?

En Lemoncode te ofrecemos formación online impartida por profesionales que se baten el cobre en consultoría:

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: