async def send_telemetry(device_client): # Form the sturcture of message payload telemetry_data_raw_temp = '{{"Device_Type": "Temp_Sensor", "Temperature": {temperature},"Humidity": {humidity}}}' telemetry_data_raw_human = '{{"Device_Type": "Human_Sensor", "IsOccupied": {occupation_status}}}' # Generate payload data while True: temperature_set = 22 + random.random() * 3 humidity_set = 50 + random.random() * 10 if humidity_set >= 55: occupation_set = 1 else: occupation_set = 0 # Form messages sent to IoT Hub temp_data_formatted = telemetry_data_raw_temp.format( temperature=temperature_set, humidity=humidity_set, occupation_status=occupation_set) human_data_formatted = telemetry_data_raw_human.format( occupation_status=occupation_set) telemetry_data_temp = Message(temp_data_formatted) telemetry_data_human = Message(human_data_formatted) # Sending data to IoT Hub with interval await device_client.send_message(telemetry_data_temp) print(str(datetime.datetime.now()), "Sending Telemetry: ", telemetry_data_temp) await asyncio.sleep(5) await device_client.send_message(telemetry_data_human) print(str(datetime.datetime.now()), "Sending Telemetry: ", telemetry_data_human) await asyncio.sleep(telemetry_interval)
def send_telemetry(device_client): global telemetry_interval, send_data telemetry_data_raw = '{{"voltage": {voltage},"ampere": {ampere},"walt": {walt}}}' temp_telemetry_raw = '{{"Temperature": {temp},"Humidity": {humi}}}' while True: time.sleep(telemetry_interval) if send_data == True: voltageset = 220 + (random.random() * 10) ampereset = 10 + random.random() waltset = (voltageset * ampereset) / 1000 device_telemetry_data_formatted = telemetry_data_raw.format( voltage=voltageset, ampere=ampereset, walt=waltset) device_telemetry_data = Message(device_telemetry_data_formatted) print(str(datetime.datetime.now()), "Sending Telemetry: ", device_telemetry_data) Temperatureset = 20 + (random.random()*3) Humidityset = 50 + (random.random()*6) temp_telemetry_data_formatted = temp_telemetry_raw.format( temp=Temperatureset, humi=Humidityset) temp_telemetry_data = Message(temp_telemetry_data_formatted) print(str(datetime.datetime.now()), "Sending Telemetry: ", temp_telemetry_data) device_client.send_message(device_telemetry_data) device_client.send_message(temp_telemetry_data)
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: while ser.in_waiting > 0: # While there is data in Serial line = ser.readline() # Read a line in serial # print("Line: {}".format(line)) try: line1 = str(line.decode("UTF-8")) except: msg_txt_formatted = MSG_TXT.format( temperature="err", device="err", timestamp1="decode err", timestamp2="err", battery="err", ) message = Message(msg_txt_formatted) print("Sending message: {}".format(message)) client.send_message(message) broken_line = line1.replace("\r", "").replace("\n", "").split(",") # print("Broken line: {}".format(broken_line)) # Extract vlues from the serial line try: device = broken_line[0] battery = broken_line[1] timestamp2 = time.time() except: device = 00 battery = 00 timestamp2 = time.time() # print (broken_line) t0 = 2 while t0 < (len(broken_line) - 1): temperature = broken_line[t0 + 1] timestamp1 = broken_line[t0] # print(t0) t0 = t0 + 2 msg_txt_formatted = MSG_TXT.format( temperature=temperature, device=device, timestamp1=timestamp1, timestamp2=timestamp2, battery=battery, ) message = Message(msg_txt_formatted) print("Sending message: {}".format(message)) client.send_message(message) time.sleep(0.1) except KeyboardInterrupt: print("IoTHubClient sample stopped")
async def input1_listener(module_client): controlList = initialize_controlList() dataList = initialize_dataList() while True: try: input_message = await module_client.receive_message_on_input("input1") # blocking call message = input_message.data messageText = message.decode('utf-8') print(f"Message text: {messageText}") messageJSON = json.loads(messageText) print(f"Message json: {messageJSON}") pipe, sensor, pipeId, sensorId = get_pipe_sensor_ids(messageJSON["id"]) dataList[pipeId-1][sensorId-1] = messageJSON["flow"] print(f"Current sensor datalist: {dataList}") try: controlList.remove(messageJSON["id"]) print(f"Rest of sensors to receive from: {controlList}") except: print(f"Duplicated measure for {messageJSON['id']}") outMsgData = {} outMsgData["type"], outMsgData["pipe"], outMsgData["sensor"], outMsgData["pipe_sensor"], outMsgData["flow"], outMsgData["unit"], outMsgData["timestamp"] = "telemetry", pipe, sensor, messageJSON["id"], messageJSON["flow"], messageJSON["unit"], messageJSON["timestamp"] outMsgJSON = json.dumps(outMsgData) #msgFormatted = TLM_MSG_TXT.format(pipe=pipe, sensor=sensor, pipe_sensor=messageJSON["id"], flow=messageJSON["flow"], unit=messageJSON["unit"], timestamp=messageJSON["timestamp"]) outMsg = Message(outMsgJSON) print(outMsg.data) # Send Telemetry message to IoTHub await module_client.send_message_to_output(outMsg, "output2") print('Telemetry sent to IoTHub') if not controlList: print("Collected telemetry from all sensors") leaks, codes = detect_leak(dataList) print(f"Leaks detected: {leaks}") # Reset control list controlList = initialize_controlList() for i, leak in enumerate(leaks): leak_loc = leak.split("-") print(leak_loc) alMsgData = {} alMsgData["type"], alMsgData["pipe"], alMsgData["zone"], alMsgData["pipe_zone"], alMsgData["alarm"], alMsgData["timestamp"] = "alarm", leak_loc[0], leak_loc[1], leak, codes[i], messageJSON["timestamp"] alMsgJSON = json.dumps(alMsgData) print(alMsgJSON) alMsg = Message(alMsgJSON) await module_client.send_message_to_output(alMsg, "output1") await module_client.send_message_to_output(alMsg, "output2") print('Sent alarm message to IoTHub to sensors') except Exception as ex: print ( "Unexpected error in input1_listener: %s" % ex )
def iothub_client_telemetry_sample_run(): try: client = iothub_client_init() input1 = open('input.csv', 'r') print("IoT Hub device sending periodic messages, press Ctrl-C to exit") messageId = 0 Lines = input1.readlines() for line in Lines: print(line) x = line.split(',') FieldId = str(x[0]) Date = x[1] GatewayId = str(x[2]) DeviceId = str(x[3]) msg_txt_formatted = MSG_TXT.format(FieldId=FieldId, Date=Date, GatewayId=GatewayId, DeviceId=DeviceId) message = Message(msg_txt_formatted) print("Sending message: {}".format(message)) client.send_message(message) print(message) print("Message successfully sent") time.sleep(3) except OSError as e: print('Error: ' + str(e))
def build_message(payload): msg = Message(payload) msg.message_id = uuid.uuid4() msg.content_encoding = "utf-8" msg.content_type = "application/json" return msg
def run(self): print( "IoT Hub devices sending periodic messages, press Ctrl-C to exit") try: while True: # Build the message with simulated telemetry values. distance = self.DISTANCE - (random.random() * 200) intensity = self.INTENSITY - (random.random() * 150) msg_txt_formatted = self.MSG_TXT.format( distance=distance, intensity=intensity) #, intruder_img=intruder_img) message = Message(msg_txt_formatted) # Add a custom application property to the message. # An IoT hub can filter on these properties without access to the message body. if distance < 150 and intensity < 200: message.custom_properties["intruderAlert"] = "true" file = "intruderAlert{}.jpg".format(random.choice([0, 1])) with open(file, "r") as f: intruder_img = f else: message.custom_properties["intruderAlert"] = "false" intruder_img = "None" # Send the message. print("Sending message: {}".format(message)) self.client.send_message(message) print("Message sent") time.sleep(self.INTERVAL) except KeyboardInterrupt: print("intruderAlert stopped")
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. temperature,apparentTemperature,humidity = getWeatherInfo() msg_txt_formatted = MSG_TXT.format(temperature=temperature, apparentTemperature = apparentTemperature,humidity=humidity ) message = Message(msg_txt_formatted) # Add a custom application property to the message. # An IoT hub can filter on these properties without access to the message body. if float(temperature) > 30: message.custom_properties["temperatureAlert"] = "true" else: message.custom_properties["temperatureAlert"] = "false" # Send the message. print( "Sending message: {}".format(message) ) client.send_message(message) print ( "Message successfully sent" ) time.sleep(300) #obtain data every 5 minutes except KeyboardInterrupt: print ( "IoTHubClient sample stopped" )
def test_central_validate_messages_success(self): (template_id, _) = self._create_device_template() (device_id, _) = self._create_device(instance_of=template_id) credentials = self._get_credentials(device_id) device_client = helpers.dps_connect_device(device_id, credentials) enqueued_time = utility.calculate_millisec_since_unix_epoch_utc( ) - 10000 payload = {"Bool": True} msg = Message( data=json.dumps(payload), content_encoding="utf-8", content_type="application/json", ) device_client.send_message(msg) # Validate the messages output = self._get_validate_messages_output(device_id, enqueued_time) self._delete_device(device_id) self._delete_device_template(template_id) assert output assert "Successfully parsed 1 message(s)" in output assert "No errors detected" in output
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. broken_water = str(random.choices(BROKEN_WATER, weights1)).strip('[]') water_flow_issue = str(random.choices(WATER_FLOW_ISSUE, weights2)).strip('[]') missing_coffee = str(random.choices(MISSING_COFFEE, weights1)).strip('[]') #message formatting and message msg_txt_formatted = MSG_TXT.format( broken_water=broken_water, missing_coffee=missing_coffee, water_flow_issue=water_flow_issue) message = Message(msg_txt_formatted) # Send the message. print("Sending message: {}".format(message)) client.send_message(message) print("Message successfully sent") #time between messages time.sleep(60) except KeyboardInterrupt: #quits with control/c print("IoTHubClient sample stopped")
def iothub_client_telemetry_sample_run(): try: client = iothub_client_init() # Build the message with simulated telemetry values. temperature,pressure,humidity = readBME280All() humidity = round(humidity, 2) msg_txt_formatted = MSG_TXT.format(temperature=temperature, humidity=humidity, pressure=pressure) message = Message(msg_txt_formatted, content_encoding='utf-8', content_type='application/json') # Add a custom application property to the message. # An IoT hub can filter on these properties without access to the message body. if temperature > 30: message.custom_properties["temperatureAlert"] = "true" else: message.custom_properties["temperatureAlert"] = "false" # Send the message. print( "Sending message: {}".format(message) ) client.send_message(message) publish.multiple([ {'topic': "balkon/temperature", 'payload': temperature}, {'topic': "balkon/humidity", 'payload': humidity} ], hostname="192.168.0.138") print ( "Message successfully sent" ) except KeyboardInterrupt: print ( "IoTHubClient sample stopped" )
async def main(connection_string, adjust): try: client = get_client(connection_string) await client.connect() print("Simulating Power Consumption for Digital Twins") print("To stop press Ctrl + C") while True: # Telemetry message = Message("{\"Consumption\": " + str( round( float(adjust) * float(mydict[round_time( datetime.now().strftime("%H:%M"))]), 3)) + "}", content_encoding="utf-8", content_type="application/json") # Send the message each 5 seconds. await client.send_message(message) print("Message successfully sent waiting 5 sec.") print("{\"Consumption\": " + str( round( float(adjust) * float(mydict[round_time( datetime.now().strftime("%H:%M"))]), 3)) + "}") time.sleep(5) except KeyboardInterrupt: print("IoTHubClient sample stopped")
def iothub_client_telemetry_sample_run(): # put message together and send sample information try: client = iothub_client_init() print("IoT Hub device sending periodic messages, press Ctrl-C to exit") while True: # format message machineId = MACHINEID model = MODEL modelNum = MODELNUM serialNum = SERIALNUM vendorNum = VENDORNUM locationId = LOCATIONID msg_txt_formatted = MSG_TXT.format(machineId=machineId, model=model, modelNum=modelNum, serialNum=serialNum, vendorNum=vendorNum, locationId=locationId) message = Message(msg_txt_formatted) # send message. print("Sending message: {}".format(message)) client.send_message(message) print("Message successfully sent") time.sleep(5) except KeyboardInterrupt: print("IoTHubClient sample stopped")
def push_signal(): try: client = iothub_client_init() print("IoT Hub device sending periodic messages, press Ctrl-C to exit") # Start a thread to listen device_method_thread = threading.Thread(target=device_method_listener, args=(client, )) device_method_thread.daemon = True device_method_thread.start() x = 0 while True: # Build the message with simulated telemetry values. Source_Voltage = voltage_source * math.cos(2 * math.pi * x) + ( random.random() * 15) Load_Voltage = (voltage_source * math.cos(2 * math.pi * (x + 0.5)) + (random.random() * 15)) / impedance msg_txt_formatted = MSG_TXT.format(Source_Voltage=Source_Voltage, Load_Voltage=Load_Voltage) message = Message(msg_txt_formatted) # Send the message. print("Sending message: {}".format(message)) client.send_message(message) print("Message successfully sent") time.sleep(INTERVAL) x += INTERVAL except KeyboardInterrupt: print("Signal Lost")
def iothub_client_telemetry_sample_run(): try: client = iothub_client_init() print("IoT Hub device sending periodic messages, press Ctrl-C to exit") df = pd.read_excel('Genset Log1.xls') # replace field that's entirely space (or empty) with NaN df.replace(r'^\s*$', np.nan, regex=True, inplace=True) df.fillna('', inplace=True) for index, row in df.iterrows(): ser_dict = row.to_dict() ser_dict['eventTime'] = str(datetime.now()) msg_txt_formatted = str(ser_dict).replace("'", '"') print(msg_txt_formatted) message = Message(msg_txt_formatted) # Send the message. print("Sending message: {}".format(message)) # client.send_message(message) print("Message successfully sent") time.sleep(3) except KeyboardInterrupt: print("IoTHubClient sample stopped")
def send_life_report(self): while True: try: patch = self.client.send_message(Message("alive")) time.sleep(60) except: sys.exit(1)
def send_weather_data(): try: client = iothub_client_init() print ( "IoT Hub device sending periodic messages, press Ctrl-C to exit" ) while True: # Get weather data data = get_weather_data(URL) # Build the message with simulated telemetry values. temperature = int(data['temperature']) precipitation = int(data['precipitation'].strip('%')) humidity = int(data['humidity'].strip('%')) wind = int(data['wind'].strip(' km/h')) msg_txt_formatted = MSG_TXT.format(temperature=temperature, precipitation=precipitation, humidity=humidity, wind=wind) message = Message(msg_txt_formatted) # Add a custom application property to the message. # An IoT hub can filter on these properties without access to the message body. if int(temperature) > 35: # High temperature warning message.custom_properties["temperatureAlert"] = "true" else: message.custom_properties["temperatureAlert"] = "false" # Send the message. print( "Sending message: {}".format(message) ) client.send_message(message) print ( "Message successfully sent" ) time.sleep(600) except KeyboardInterrupt: print ( "IoTHubClient sample stopped" )
async def send_message(module_client): print("Running Send Message") payload = { "timestamp": str(time.time()), "inferences": [{ "type": "text", "subtype": "", "inferenceId": "", "relatedInferences": [], "text": { "value": "gASVDA4AAAAAAAB9lCiMBWJveGVzlIwVbnVtcHkuY29yZS5tdWx0aWFycmF5lIwMX3JlY29uc3Ry\\ndWN0lJOUjAVudW1weZSMB25kYXJyYXmUk5RLAIWUQwFilIeUUpQoSwFLAUsEhpRoBYwFZHR5cGWU\\nk5SMAmY0lImIh5RSlChLA4wBPJROTk5K/////0r/////SwB0lGKJQxC/t8JEoQFURIFv00Tkc25E\\nlHSUYowGc2NvcmVzlGgEaAdLAIWUaAmHlFKUKEsBSwGFlGgRiUMEAvh/P5R0lGKMB2NsYXNzZXOU\\naARoB0sAhZRoCYeUUpQoSwFLAYWUaA6MAmk4lImIh5RSlChLA2gSTk5OSv////9K/////0sAdJRi\\niUMIAQAAAAAAAACUdJRijAZsYWJlbHOUaARoB0sAhZRoCYeUUpQoSwFLAYWUaA6MA1UxNJSJiIeU\\nUpQoSwNoEk5OTks4SwRLCHSUYolDOGwAAAB1AAAAZwAAAGcAAABhAAAAZwAAAGUAAAB0AAAAcgAA\\nAGEAAABpAAAAbAAAAGUAAAByAAAAlHSUYowFbWFza3OUaARoB0sAhZRoCYeUUpQoSwFLAUscSxyH\\nlGgRiUJADAAAy6OKOvpBGDxy/wI+g1UAP/yiJD9MiFc/96dsPzY8dD81mW8/V/hwPxUXaT+e8Wg/\\nmU9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p": 0, "extensions": {}, "valueCase": "text" } }] } while True: payload["timestamp"] = str(datetime.datetime.now()) print(payload["timestamp"]) msg = Message(json.dumps(payload)) msg.message_id = uuid.uuid4() print(payload["timestamp"]) msg.custom_properties["payload"] = "Jay" await module_client.send_message_to_output( msg, "outputpayload") print("Sent....") await asyncio.sleep(.1) #Sleep for 100 ms
async def send_telemetry(self, telemetry_data): if not self._isConnected: if self._doReconnect: print("try reconnect...") await self._do_connect() print("done") return False if "$.sub" in telemetry_data: component = telemetry_data["$.sub"] del telemetry_data["$.sub"] else: component = None msg = Message(json.dumps(telemetry_data)) msg.content_enconding = "utf-8" msg.content_type = "application/json" if component is not None: msg.custom_properties["$.sub"] = component print("Send message") try: await asyncio.wait_for(self._clientHandle.send_message(msg), timeout=10) except: print("caught an exception from send_message().") await self.disconnect() self._isConnected = False self._doReconnect = True return False return True
async def receive_message_listener(module_client): print("Running Receive Message") while True: input_message = await module_client.receive_message_on_input( "inputpayload") # blocking call #Read At readDateTime = datetime.datetime.now() message = input_message.data message_text = message.decode('utf-8') data = json.loads(message_text) genDateTime = datetime.datetime.strptime( data["timestamp"], '%Y-%m-%d %H:%M:%S.%f') diff = readDateTime - genDateTime diff_secs = diff.total_seconds() print("{}^^^^^^^{}^^^^^^^{}".format(data["timestamp"], readDateTime, diff_secs)) outmessage_JSON = { "sent": str(data["timestamp"]), "received": str(readDateTime), "diffsecs": diff_secs } outmessage_text = json.dumps(outmessage_JSON) out_message = Message(outmessage_text) await module_client.send_message_to_output( input_message, "output1")
def test_central_monitor_events(self): (template_id, _) = self._create_device_template() (device_id, _) = self._create_device(instance_of=template_id) credentials = self._get_credentials(device_id) device_client = helpers.dps_connect_device(device_id, credentials) enqueued_time = utility.calculate_millisec_since_unix_epoch_utc( ) - 10000 payload = {"Bool": True} msg = Message( data=json.dumps(payload), content_encoding="utf-8", content_type="application/json", ) device_client.send_message(msg) # Test with invalid app-id self.cmd( "iot central diagnostics monitor-events --app-id {} -y".format( APP_ID + "zzz"), expect_failure=True, ) # Ensure no failure output = self._get_monitor_events_output(device_id, enqueued_time) self._delete_device(device_id) self._delete_device_template(template_id) assert '"Bool": true' in output assert device_id in output
def iothub_client_telemetry_sample_run(): global count try: client = iothub_client_init() print("IoT Hub device sending periodic messages, press Ctrl-C to exit") while count < NBR_MESSAGE: # Build the message with simulated telemetry values. temperature = TEMPERATURE + (random.random() * 15) humidity = HUMIDITY + (random.random() * 20) msg_txt_formatted = MSG_TXT.format( temperature=temperature, humidity=humidity, count=count) message = Message(msg_txt_formatted) message.content_encoding = "utf-8" message.content_type = "application/json" # Add a custom application property to the message. # An IoT hub can filter on these properties without access to the message body. if temperature > 30: message.custom_properties["temperatureAlert"] = "true" else: message.custom_properties["temperatureAlert"] = "false" message.custom_properties["SendingTime"] = datetime.datetime.now() # Send the message. print("Sending message: {}".format(message)) client.send_message(message) time.sleep(1) print("Message successfully sent") count += 1 except KeyboardInterrupt: print("IoTHubClient sample stopped")
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: # format message machineId = 200 model = '"Virtu Series"' modelNum = MODELNUM modelPhoto = MODELPHOTO serialNum = SERIALNUM vendorNum = VENDORID locationId = LOCATIONID status = '"green"' statusDescription = '"Normal"' msg_txt_formatted = MSG_TXT.format(machineId=machineId, model=model, modelNum=modelNum, modelPhoto=modelPhoto, serialNum=serialNum, vendorNum=vendorNum, locationId=locationId, status=status, statusDescription=statusDescription) message = Message(msg_txt_formatted) # send message. print( "Sending message: {}".format(message) ) client.send_message(message) print ( "Message successfully sent" ) # Pause time before next message time.sleep(60) #change per requirment / demo set for to send info every min. except KeyboardInterrupt: print ( "IoTHubClient sample stopped" )
def getReadings(): readings['temperature'] = TEMPERATURE + (random.random() * 15) readings['humidity'] = HUMIDITY + (random.random() * 20) msg_txt_formatted = json.dumps(readings) message = Message(msg_txt_formatted) return(message)
def test_script_object_to_outgoing_message(payload): """ Convert an object that we received from a test script into something that we can pass into the iothub sdk. """ return Message(bytearray(json.dumps(payload.body), "utf-8"))
def send_message(self, msg): print("start transmitting {}".format(msg)) message = Message(msg) self.client.send_message(message) t = self.executor.submit(self.client.send_message, message) print("{} has been sent to iothub".format(msg)) return t.result()
def iothub_client_telemetry_sample_run(deviceID, room): try: client = iothub_client_init() print ( "IoT Hub device sending periodic messages, press Ctrl-C to exit" ) DEVICEid = deviceID ROOM = room #temperature = TEMPERATURE + (random.random() * 15) #humidity = HUMIDITY + (random.random() * 20) #device = 3 msg_txt_formatted = MSG_TXT.format(deviceID=DEVICEid, room=ROOM) message = Message(msg_txt_formatted) # Add a custom application property to the message. # An IoT hub can filter on these properties without access to the message body. # Send the message. print( "Sending message: {}".format(message) ) client.send_message(message) print ( "Message successfully sent" ) time.sleep(1) except KeyboardInterrupt: print ( "IoTHubClient sample stopped" )
def iothub_client_transfer(): try: client = iothub_client_connect() print( "Connection established with IoT Hub. Vehicle speeds are now being monitored." ) while True: # Speed simulation in effect. speed = SPEED + (random.uniform(-20, 20)) msg_txt_formatted = MSG_TXT.format(speed=speed) message = Message(msg_txt_formatted) # Identify detected speeding. if speed > 108: message.custom_properties["speedAlert"] = "true" else: message.custom_properties["speedAlert"] = "false" print("Speed Detected: {}".format(message)) client.send_message(message) if speed > 108: print("ALERT: Speeding!") # Random interval to simulate realistic gap between camera readings. time.sleep(random.uniform(0.2, 12.0)) except KeyboardInterrupt: print("Communication halted with IoT Hub. (User Input)")
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. temperature = TEMPERATURE + (random.random() * 15) humidity = HUMIDITY + (random.random() * 20) msg_txt_formatted = MSG_TXT.format(temperature=temperature, humidity=humidity) message = Message(msg_txt_formatted) # Add a custom application property to the message. # An IoT hub can filter on these properties without access to the message body. if temperature > 30: message.custom_properties["temperatureAlert"] = "true" else: message.custom_properties["temperatureAlert"] = "false" # Send the message. print("Sending message: {}".format(message)) client.send_message(message) print("Message successfully sent") time.sleep(1) except KeyboardInterrupt: print("IoTHubClient sample stopped")
def iothub_client_telemetry_sample_run(): timeTaken = 0 try: client = iothub_client_init() print("IoT Hub device sending periodic messages, press Ctrl-C to exit") while True: # Building the message temperature = TEMPERATURE + (random.random() * 15) humidity = HUMIDITY + (random.random() * 20) moisture = MOISTURE + (random.random() * 20) timeTaken += 0.1 msg_txt_formatted = MSG_TXT.format(temperature=temperature, humidity=humidity, moisture=moisture, time=timeTaken) message = Message(msg_txt_formatted) # Add a warning message if temp goes above the required limit set if temperature > 30: message.custom_properties["temperatureAlert"] = "true" else: message.custom_properties["temperatureAlert"] = "false" # Sends the message. print("Sending message: {}".format(message)) client.send_message(message) print("Message successfully sent") time.sleep(1) except KeyboardInterrupt: print("IoTHubClient sample stopped")