In this part of the lesson, you will connect your virtual IoT device or Raspberry Pi to your IoT Hub, to send telemetry and receive commands.
The next step is to connect your device to IoT Hub.
-
Open the
soil-moisture-sensorfolder in VS Code. Make sure the virtual environment is running in the terminal if you are using a virtual IoT device. -
Install some additional Pip packages:
pip3 install azure-iot-device
azure-iot-deviceis a library to communicate with your IoT Hub. -
Add the following imports to the top of the
app.pyfile, below the existing imports:from azure.iot.device import IoTHubDeviceClient, Message, MethodResponse
This code imports the SDK to communicate with your IoT Hub.
-
Remove the
import paho.mqtt.client as mqttline as this library is no longer needed. Remove all the MQTT code including the topic names, all code that usesmqtt_clientand thehandle_command. Keep thewhile True:loop, just delete themqtt_client.publishline form this loop. -
Add the following code below the import statements:
connection_string = "<connection string>"
Replace
<connection string>with the connection string you retrieved for the device earlier in this lesson.馃拋 This is not best practice. Connection strings should never be stored in source code, as this can be checked into source code control and found by anyone. We are doing this here for the sake of simplicity. Ideally you should use something like an environment variable and a tool like
python-dotenv. You will learn more about this in an upcoming lesson. -
Below this code, add the following to create a device client object that can communicate with IoT Hub, and connect it:
device_client = IoTHubDeviceClient.create_from_connection_string(connection_string) print('Connecting') device_client.connect() print('Connected')
-
Run this code. You will see your device connect.
pi@raspberrypi:~/soil-moisture-sensor $ python3 app.py Connecting Connected Soil moisture: 379
Now that your device is connected, you can send telemetry to the IoT Hub instead of the MQTT broker.
-
Add the following code inside the
while Trueloop, just before the sleep:message = Message(json.dumps({ 'soil_moisture': soil_moisture })) device_client.send_message(message)
This code creates an IoT Hub
Messagecontaining the soil moisture reading as a JSON string, then sends this to the IoT Hub as a device to cloud message.
Your device needs to handle a command from the server code to control the relay. This is sent as a direct method request.
-
Add the following code before the
while Trueloop:def handle_method_request(request): print("Direct method received - ", request.name) if request.name == "relay_on": relay.on() elif request.name == "relay_off": relay.off()
This defines a method,
handle_method_request, that will be called when a direct method is called by the IoT Hub. Each direct method has a name, and this code expects a method calledrelay_onto turn the relay on, andrelay_offto turn the relay off.馃拋 This could also be implemented in a single direct method request, passing the desired state of the relay in a payload that can be passed with the method request and available from the
requestobject. -
Direct methods require a response to tell the calling code that they have been handled. Add the following code at the end of the
handle_method_requestfunction to create a response to the request:method_response = MethodResponse.create_from_method_request(request, 200) device_client.send_method_response(method_response)
This code sends a response to the direct method request with an HTTP status code of 200, and sends this back to the IoT Hub.
-
Add the following code below this function definition:
device_client.on_method_request_received = handle_method_request
This code tells the IoT Hub client to call the
handle_method_requestfunction when a direct method is called.
馃拋 You can find this code in the code/pi or code/virtual-device folder.
馃榾 Your soil moisture sensor program is connected to your IoT Hub!