Azure Cloud Services for Raspberry Pi 4: How to update digital twin on your device
Introduction
Microsoft Azure provides a variety of cloud computing services including artificial intelligence, machine learning, IoT, storage, security, networking, media, integration and so on. Among tens of thousands of IoT end devices, Raspberry Pi is one of the most popular and useful platforms that used in many areas because of its low cost, modularity, and open design. Raspberry Pi 4 is the latest powerful model with Quad core Cortex-A72 64-bit processor, 2 HDMI ports, 40 pin GPIO header and hardware video decode capability. Azure IoT Hub is an Azure service that lets you manage your IoT devices from the cloud and ingest high volumes of device telemetry to the cloud for storage or processing. Device twins are JSON documents that store device state information including metadata, configurations, and conditions. Azure IoT Hub maintains a device twin for each device that you connect to IoT Hub.
In this article, we will walk you through the steps required to update digital twin for your Raspberry Pi 4 model B with Python Azure IoT SDK. We will repeatedly send device to cloud messages that contain real-time temperature information.
Prerequisites
1. Raspberry Pi 4 model B
2. DHT11 Temperature & Humidity sensor
Hardware Connection
Here we use BCM Pin 17 as the communication channel between Raspberry Pi and DHT 11. And BCM Pin 4 is configured as the data input from PIR sensor to Raspberry Pi. The hardware scheme is the same as we presented here “Azure Cloud Services for Raspberry Pi 4: How to send sensor data to Azure IoT Hub”.
Install Azure IoTHub Client Library
Open your Raspberry Pi terminal and install Azure IoT Hub library for Python:
1.pip3 install azure-iot-hub
2.pip3 install asyncio
Create Azure Services
In this project, we will use Azure IoTHub. Please refer to the section “Create an Azure IoTHub and Register a New Device” in this wiki article “Azure Cloud Services for Raspberry Pi 4: How to send sensor data to Azure IoT Hub” to create services for Azure IoTHub. You will need the connection string from the resource you create to connect your device to the Azure IoTHub services.
Create and Debug Python Code on Raspberry Pi
Currently, there are several Python IDE on Raspberry Pi. Thonny Python IDE is bundled with the Raspbian OS. We can launch it by click Programming -> Thonny Python IDE. Then copy and paste the following code.
01.import asyncio
02.import board
03.import RPi.GPIO as GPIO
04.import dht11
05.from azure.iot.hub.models import Twin, TwinProperties
06.from azure.iot.hub import IoTHubRegistryManager
07.
08.iothub_connection_str = "HostName=***.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=***"
09.device_id = "MyRPi"
10.DELAY = 5
11.
12.async def main():
13.
14. try:
15. # Create IoTHubRegistryManager
16. iothub_registry_manager = IoTHubRegistryManager.from_connection_string(iothub_connection_str)
17.
18. # Initialize GPIO
19. GPIO.setwarnings(False)
20. GPIO.setmode(GPIO.BCM)
21. GPIO.cleanup()
22.
23. # Read data using pin GPIO17
24. dhtDevice = dht11.DHT11(pin=17)
25.
26. GPIO.setup(4, GPIO.IN) #PIR
27.
28. print("Sending serivce started. Press Ctrl-C to exit")
29. # Get device twin
30. twin = iothub_registry_manager.get_twin(device_id)
31. print(twin)
32. print("")
33.
34. while True:
35.
36. try:
37. #DHT11
38. result = dhtDevice.read()
39. #PIR
40. if GPIO.input(4):
41. pir = 1
42. else:
43. pir = 0
44.
45. if result.is_valid():
46. temperature = result.temperature
47. humidity = result.humidity
48. # Update twin
49. twin_patch = Twin()
50. twin_patch.properties = TwinProperties(desired={"temperature": temperature})
51. updated_twin = iothub_registry_manager.update_twin(device_id, twin_patch)
52. print("The twin patch has been successfully applied")
53.
54. else:
55. # print("Error: %d" % result.error_code)
56. continue
57.
58. await asyncio.sleep(DELAY)
59.
60. except KeyboardInterrupt:
61. print("Service stopped")
62. GPIO.cleanup()
63. break
64.
65. except Exception as error:
66. print(error.args[0])
67.
68.if __name__ == '__main__':
69. asyncio.run(main())
Please do substitute the connection string with yours that created in section “Create Azure Services”. Press Run or Debug button to start the process. You will see the output information in Shell window as shown in Fig. 1.
Fig. 1 Debug information on Shell window
Firstly, the device twin is obtained by get_twin method. And the detail information will be printed. Then, the temperature will be reported as desired property from the device to the cloud every 5 seconds.
Remotely review the device twin with Azure IoT Explorer
Install and run Azure IoT Explorer, choose the IoTHub and device that you created. And then click Device twin. We will see the device twin information in detail, which is shown in Fig. 2 as follows. If you click Refresh button, you will notice that the temperature will be updated every 5 seconds.
Fig. 2 Device twin displayed on Azure IoT Explorer
Summary
In this tutorial, we have presented how to update digital twin for Raspberry Pi 4 model B with Python Azure IoT SDK.
Resources
- MS Docs for Azure IoT Hub.
- MS Docs for Connect Raspberry Pi to Azure IoT Hub.
- MS Docs for Device twins.
- Azure IoT Explorer: Install and use Azure IoT Explorer.