Skip to content

Iot Team Task #287 The machine telemetry simulator hose pressure information, machine identity, valve sensor

rbeeler edited this page Mar 24, 2020 · 4 revisions

Register Your New Device:

  1. Access your Azure Cloud Shell. This will be the very first icon to the right of the search bar at the top of your Azure page. It is a square with a sideways triangle in it. You will need to be granted access to the Iot-Hub-S3 in order to access this. Ask Yozelin for access.

  2. You will need to select the resource you will be using under advanced settings. Select Iot-Hub-S3, otherwise it will not give you access to the Could Shell.

  3. Once open, type this into your Cloud Shell(You may change the name of your python device, but make note of it for later): az iot hub device-identity create --hub-name Iot-Hub-S3 --device-id MyPythonDevice

  4. Run this in order to get the Connection String, and make note of it. This will be copied into your python code: az iot hub device-identity show-connection-string --hub-name Iot-Hub-S3 --device-id MyPythonDevice --output table

Have Python Code Ready

I recommend using the file name - SimulatedDevice.py - but you can name it whatever you want. Just make note of it, and use that filename for the remainder of the instructions. Here is an example of the python code will need to run. Be sure to include your own unique CONNECTION_STRING in the labeled variable. Note: If you look at the Microsoft documentation it uses integers instead of strings in the message it sends to the Iot-Hub, so there are some changes that need to be made. This example uses strings.

# Copyright (c) Microsoft. All rights reserved. # Licensed under the MIT license. See LICENSE file in the project root for full license information.

import random import time

# Using the Python Device SDK for IoT Hub: # https://github.com/Azure/azure-iot-sdk-python # The sample connects to a device-specific MQTT endpoint on your IoT Hub. from azure.iot.device import IoTHubDeviceClient, Message

# The device connection string to authenticate the device with your IoT hub. # Using the Azure CLI: # az iot hub device-identity show-connection-string --hub-name {YourIoTHubName} --device-id MyNodeDevice --output table CONNECTION_STRING = "HostName=Iot-Hub-S3.azure-devices.net;DeviceId=MyPythonDeviceTelemetry;SharedAccessKey=R/EayW1azIx4GonFt/ROyFPsB/HMPVR4e1n8dOgUtME="

# Define the JSON message to send to IoT Hub. MACHINEID = 123 VALVE_STATUS = ["LEAKING", "GOOD", "EXCELLENT"] HOSE_PRESSURE = ["LOW", "MEDIUM", "HIGH"] MSG_TXT = '{{"machineId": {machineId},"valve status": {valve_status},"hose pressure": {hose_status}}}'

def iothub_client_init(): # Create an IoT Hub client client = IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING) return client

def iothub_client_telemetry_sample_run():

`try:`
    `client = iothub_client_init()`
    `print ( "IoT Hub device sending periodic messages, press Ctrl-C to exit" )`

    `while True:`
        `# Build the message with simulated telemetry values.`
        `valve = str(random.choices(VALVE_STATUS))`
        `hose = str(random.choices(HOSE_PRESSURE))`
        `machineId = MACHINEID`
        `msg_txt_formatted = MSG_TXT.format(machineId=machineId, valve_status=valve, hose_status=hose)`
        `message = Message(msg_txt_formatted)`


        `# Send the message.`
        `print( "Sending message: {}".format(message) )`
        `client.send_message(message)`
        `print ( "Message successfully sent" )`
        `time.sleep(10)`

`except KeyboardInterrupt:`
    `print ( "IoTHubClient sample stopped" )`

if __name__ == '__main__': print ( "IoT Hub Quickstart #1 - Simulated device" ) print ( "Press Ctrl-C to exit" ) iothub_client_telemetry_sample_run()

Send Simulated Telemetry

  1. Navigate to the folder where your SimulatedDevice.py file is located(the file containing the python code you just created) in your command prompt.

  2. Run: pip install azure-iot-device

  3. Run: python SimulatedDevice.py

You should see the message being sent to the Hub in your command prompt. I was able to see the message sent, but then a few seconds later received an error regarding the connection to the Hub. I will post that error at the bottom of these instructions*.

Read Telemetry From the Iot-Hub

  1. Go back to your Cloud Shell. You may have to refresh the page.

  2. Run: az iot hub monitor-events --hub-name Iot-Hub-S3 --device-id MyPythonDevice Note: If you changed the name of your python device this is one of those places where you will need to adjust that name in your command.

You will now be able to see the message that was sent to your Hub, that you saw originally in your command prompt. And you are done!

*The error I received when sending a message to the Iot-Hub was about my MQTT endpoint. In the Microsoft documentation it does include that this port(8883) must be open. Although I made a rule in my firewall for this port, and it did not have any effect, I am confident that this is where my issue is. Despite this, when run on another network besides my home's network, it works just fine. If anyone else has this issue, I suggest taking a look at port 8883, as well as checking your proxy settings.

Here is the link to the documentation for device telemetry that walks you through all of these steps, as well as briefly mentions this port: https://docs.microsoft.com/en-us/azure/iot-hub/quickstart-send-telemetry-python

Error:

transport.connect raised error Traceback (most recent call last): File "C:\Users\ruthb\AppData\Local\Programs\Python\Python38-32\lib\site-packages\azure\iot\device\common\mqtt_transport.py", line 339, in connect rc = self._mqtt_client.connect( File "C:\Users\ruthb\AppData\Local\Programs\Python\Python38-32\lib\site-packages\paho\mqtt\client.py", line 937, in connect return self.reconnect() File "C:\Users\ruthb\AppData\Local\Programs\Python\Python38-32\lib\site-packages\paho\mqtt\client.py", line 1071, in reconnect sock = self._create_socket_connection() File "C:\Users\ruthb\AppData\Local\Programs\Python\Python38-32\lib\site-packages\paho\mqtt\client.py", line 3522, in _create_socket_connection return socket.create_connection(addr, source_address=source, timeout=self._keepalive) File "C:\Users\ruthb\AppData\Local\Programs\Python\Python38-32\lib\socket.py", line 808, in create_connection raise err File "C:\Users\ruthb\AppData\Local\Programs\Python\Python38-32\lib\socket.py", line 796, in create_connection sock.connect(sa) TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

The above exception was the direct cause of the following exception:

Traceback (most recent call last): File "C:\Users\ruthb\AppData\Local\Programs\Python\Python38-32\lib\site-packages\azure\iot\device\common\pipeline\pipeline_stages_mqtt.py", line 115, in _run_op self.transport.connect(password=self.sas_token) File "C:\Users\ruthb\AppData\Local\Programs\Python\Python38-32\lib\site-packages\azure\iot\device\common\mqtt_transport.py", line 345, in connect raise exceptions.ConnectionFailedError(cause=e) azure.iot.device.common.transport_exceptions.ConnectionFailedError: None caused by [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

ConnectOperation: completing with error None caused by [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond RetryStage(ConnectOperation): Op needs retry with interval 20 because of None caused by [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. Setting timer.

Clone this wiki locally