async def MessageSender(Client: IoTHubModuleClient, OutQueue: asyncio.Queue): try: while (True): data = await OutQueue.get() print('Message sender: ', data) msg = json.dumps(data) msg = Message(msg) try: await Client.send_message_to_output(msg, 'InterfaceOut') OutQueue.task_done() except Exception as ex: print('Unexpected error in sender: {}'.format(ex)) print('Finished sending') except asyncio.CancelledError: print('Message sender: Task cancelled')
def construct_output_message(graph_instance, device_id, inferences, event_time): logger.debug("Constructing output message") output_dict = { 'graphInstance': graph_instance, 'deviceId': device_id, 'inferences': inferences, 'eventTime': event_time } output_message_string = json.dumps(output_dict) output_message = Message(output_message_string, content_encoding='utf-8') logger.debug(f'Output message: {output_message}') return output_message
def send_telemetry(device_client): try: # Build the message with simulated telemetry values. # Example to send payload using json format #MSG_TXT = '{{"temperature": {temperature},"humidity": {humidity}}}' #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) #Send payload as a simple text message = Message("newImage") # Add a custom application property to the message. message.custom_properties["source"] = "edgeRaspberryPI" # Send the message. device_client.send_message(message) print("Message sent") except Exception as ex: print("Exception to send telemetry: %s" % ex)
def iothub_client_telemetry_sample_run(): try: client = iothub_client_init() print("Sending data to IoT Hub, press Ctrl-C to exit") while True: msg_txt_formatted = MSG.format(temperature=temperature, humidity=humidity) message = Message(msg_txt_formatted) print("Sending message: {}".format(message)) client.send_message(message) print("Message successfully sent") time.sleep(3) except KeyboardInterrupt: print("IoTHubClient stopped")
def callback(ch, method, properties, body): # print(str(body)) global client # Converts the message into a object that is readable to Azure message = Message(body) unsent = True while (unsent): try: client.send_message(message) print("Sending message: {}".format(message)) unsent = False except: print("Nothing was sent") time.sleep(10) client = iothub_client_init()
def readFromKafka(): try: client = iothub_client_init() kafkaReader = initKafkaReader() for msg in kafkaReader: decodeMessage = msg.value.decode('utf-8','ignore') print('Message received: {}'.format(decodeMessage)) message = Message(decodeMessage) client.send_message(message) except KeyboardInterrupt: print("Kafka reader stopped") except: print("Unexpected error:", sys.exc_info()[0])
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(3) except KeyboardInterrupt: print("IoTHubClient sample stopped")
async def send_test_message(i): print("sending message #" + str(i)) message_id = uuid.uuid4() csv_text = str(i) + "," + str(message_id) + ",test wind speed " + str( i) + "," + datetime.datetime.now().strftime("%d/%m/%Y %H:%M:%S") msg = Message(csv_text) msg.message_id = message_id msg.correlation_id = "correlation-1234" msg.custom_properties["tornado-warning"] = "yes" msg.content_encoding = "utf-8" msg.content_type = "application/csv" await device_client.send_message(msg) print("done sending message #" + str(i))
def callback(ch, method, properties, body): # print(str(body)) global client # Converts the message into a opbject that is readable to Azure message = Message(body) try: unsent = True while bool(unsent): if bool(client): client.send_message(body) print("Sending message: {}".format(body)) unsent = False else: client = iothub_client_init() except: client = iothub_client_init()
def start_planting(): try: client = listener.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=listener.device_method, args=(client,)) device_method_thread.daemon = True device_method_thread.start() # Intialise variables temperature = Temperature(20.0, TEMPERATURE_STATUS) humidity = Humidity(85.0, HUMIDITY_STATUS) plant_id = 1 days = 1 curr_reward = 0 # Start sending message while True: # Build the message with simulated telmetry values temp_info, humi_info, growth_state = generate_daily_msg(temperature, humidity, days) temp = temp_info["temperature"] humi = humi_info["humidity"] reward = temp_info["status"] + humi_info["status"] msg_txt_formatted = MESSAGE.format(deviceId= DEVICE_ID, plant_id=plant_id, temperature=temp, humidity=humi, state=growth_state, reward=reward) message = Message(msg_txt_formatted) # Go to a new day curr_reward += reward days += 1 # Plant a new mint after harvesting the old one if days > LIMIT_GROWING_DAYS or curr_reward >= LIMIT_GROWING_REWARD: days = 1 plant_id += 1 curr_reward = 0 # Send message print("Sending message: {}".format(message)) client.send_message(message) print("Message sent") time.sleep(listener.INTERVAL) except KeyboardInterrupt: print("Stopped planting")
def iothub_client_telemetry_sample_run(): try: aux_validate_connection_string() client = aux_iothub_client_init() print("IoT Hub Simulated body sensor") print("Press Ctrl-C to exit") #ENABLE THE RECEPTION THREAD, DEFINING THE TARGET METHOD message_listener_thread = threading.Thread(target=message_listener, args=(client, )) message_listener_thread.daemon = True message_listener_thread.start() #IT WILL RUN FOREVER UNLESS YOU STOP IT while True: #COLLECTING SENSOR VALUES #NEW METRIC COLLECTION SHOULD ADD CODE HERE temperature_measure = get_sensor_temperature() heart_rate_measure = get_sensor_heart_rate() sensor_data['device_name'] = DEVICE_NAME #STORING SENSOR VALUES IN DATA STRUCTURE #NEW METRIC COLLECTION SHOULD ADD CODE HERE sensor_data['temperature'] = temperature_measure sensor_data['heart_rate'] = heart_rate_measure #TRANFORMING IT TO JSON json_sensor_data = json.dumps(sensor_data) #CREATING AN AZURE IOT MESSAGE OBJECT azure_iot_message = Message(json_sensor_data) #ADDING A CUSTOM PROPERTY OF OUR CHOICE TO THE MESSAGE CALLED temperature_alert if temperature_measure > AUX_MAXIMUM_BODY_TEMPERATURE: azure_iot_message.custom_properties[ "temperature_alert"] = "true" else: azure_iot_message.custom_properties[ "temperature_alert"] = "false" #SETTING PROPER MESSAGE ENCODING azure_iot_message.content_encoding = 'utf-8' azure_iot_message.content_type = 'application/json' #SENDING THE MESSAGE print("Sending azure_iot_message: {}".format(azure_iot_message)) client.send_message(azure_iot_message) print("Message successfully sent") #SLEEPING FOR A SECOND BEFORE RESTARTING time.sleep(1) except KeyboardInterrupt: print("IoTHubClient sample stopped")
async def DataPlatformSender(Client: IoTHubModuleClient, CloudOut: asyncio.Queue): try: while (True): data = await CloudOut.get() try: print('Data platform sender: Message to send.', data) msg = json.dumps(data) msg = Message(msg) await Client.send_message_to_output(msg, 'AdapterOut') CloudOut.task_done() except Exception as ex: print('Data platform sender: Unexpected error in sender: {}'. format(ex)) print('Data platform sender: Finished sending') except asyncio.CancelledError: print('Data platform sender: Task cancelled')
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. pic = random.randrange(12) img_name = currentdir + '/' + str(pic) + '.bmp' with open(img_name, 'rb') as f: encoded_string = base64.b64encode(f.read()) img_data = encoded_string.decode("utf-8") data = { "Inputs" : { "WebServiceInput0" : [ { "image" : img_data, "id" : 0, "category" : "Discocytes-Test" } ] }, "GlobalParameters": {} } input_data = json.dumps(data) headers = {'Content-Type' : 'application/json'} headers['Authorization'] = f'Bearer {key}' resp = requests.post(scoring_uri, input_data, headers=headers) print(resp.text) msg_txt_formatted = MSG_TXT.format(picture=resp.text, bloodtype="discocytes") message = Message(msg_txt_formatted) # 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" )
async def send_telemetry(): print( f'Sending telemetry from the provisioned device every {delay} seconds' ) for track in gpx.tracks: for segment in track.segments: for point in segment.points: print('Point at ({0},{1}) -> {2}'.format( point.latitude, point.longitude, point.elevation)) print(datetime.now()) payload = json.dumps({ "long": point.longitude, "lat": point.latitude, "timestamp": str(datetime.now()) }) msg = Message(payload) await device_client.send_message(msg) time.sleep(delay)
def main(): try: client = iothub_client_init() manager = ProcessManager() manager.start_process(DEFAULT_COMMAND) #manager = Rtl433Stub() while True: lines = manager.get_stdout() #lines = manager.get_telemtry() for line in lines: prevMsg = None for txt in line: jsonobj = json.loads(txt) pkt = dict() pkt['dateTime'] = jsonobj['time'] pkt['model'] = jsonobj['model'] pkt['id'] = jsonobj['id'] pkt['channel'] = jsonobj['channel'] pkt['battery'] = jsonobj['battery_ok'] msg_type = jsonobj['subtype'] pkt['wind_speed'] = jsonobj['wind_avg_km_h'] if msg_type == 49: pkt['wind_dir'] = jsonobj['wind_dir_deg'] pkt['rain_mm'] = jsonobj['rain_mm'] elif msg_type == 56: pkt['temperature'] = jsonobj['temperature_C'] pkt['humidity'] = jsonobj['humidity'] if pkt != prevMsg: prevMsg = pkt message = Message(json.dumps(pkt)) print(message) print("Sending message...") try: client.send_message(message) except: print("Sending failed") time.sleep(.1) except KeyboardInterrupt: manager.stop_process()
async def send_alert_message(): print("Sending alert from device " + device_id) body_dict = {} body_dict['Weather'] = {} body_dict['Weather']['Temperature'] = random.randrange(76, 80, 1) body_dict['Weather']['Humidity'] = random.randrange(40, 60, 1) body_dict['Location'] = '28.424911, -81.468962' body_json = json.dumps(body_dict) print(body_json) msg = Message(body_json) msg.message_id = uuid.uuid4() msg.correlation_id = "correlation-1234" msg.custom_properties["Alert"] = "yes" msg.contentEncoding = "utf-8", msg.contentType = "application/json", await device_client.send_message(msg) print("Done sending alert message")
async def send_recurring_telemetry(device_client): # Connect the client. await device_client.connect() # Send recurring telemetry i = 0 while True: i += 1 msg = Message("test wind speed " + str(i)) msg.message_id = uuid.uuid4() msg.correlation_id = "correlation-1234" msg.custom_properties["tornado-warning"] = "yes" msg.content_encoding = "utf-8" msg.content_type = "application/json" print("sending message #" + str(i)) await device_client.send_message(msg) time.sleep(2)
def iothub_send_data(): msg_txt_formatted = MSG_TXT.format(ta=ta, tc=tc, aburrido=aburrido, dormido=dormido) 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 tc > 37: # message.custom_properties["tempAlert"] = "true" #else: # message.custom_properties["tempAlert"] = "false" # Send the message. print("Enviando Mensaje a Iot-Hub: {}".format(message)) device_client.send_message(message) print(message) print("Mensaje enviado con exito") device_client.disconnect() return
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. msg_txt_formatted = MSG_TXT.format(energy=Energy) message = Message(msg_txt_formatted) # 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(): 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() while True: # This loop checks for chips. If one is near it will get the UID try: while True: global mes_id rdr.wait_for_tag() (error, data) = rdr.request() if not error: print("\nKart Algilandi!") (error, uid) = rdr.anticoll() if not error: # Print UID kart_uid = str(uid[0])+" "+str(uid[1])+" "+str(uid[2])+" "+str(uid[3])+" "+str(uid[4]) print(kart_uid) time.sleep(2) mes_id+=1 msg_txt_formatted = MSG_TXT.format(mes_id=mes_id,kart_uid=kart_uid) message = Message(msg_txt_formatted) # Send the message. print( "Sending message: {}".format(message) ) client.send_message(message) print( "Message sent" ) time.sleep(INTERVAL) except KeyboardInterrupt: GPIO.cleanup() except KeyboardInterrupt: print ( "IoTHubClient sample stopped" )
async def main(): # This should ony be done once for every Device # vlaues from rest call - Create device provisioning_host = "global.azure-devices-provisioning.net" id_scope = "*************" deviceId = "*********************" primarykey = "*******************" # Provision device provisioning_device_client = ProvisioningDeviceClient.create_from_symmetric_key( provisioning_host=provisioning_host, registration_id=deviceId, id_scope=id_scope, symmetric_key=primarykey, ) registration_result = await provisioning_device_client.register() print(registration_result) # Creating a client for sending data if registration_result.status == "assigned": print("Provisioned the device") device_client = IoTHubDeviceClient.create_from_symmetric_key( symmetric_key=primarykey, hostname=registration_result.registration_state.assigned_hub, device_id=registration_result.registration_state.device_id, ) # Connect the client. await device_client.connect() msgData = '{"PeriodFrom":"2020-10-16T07:49:00Z","PeriodTo":"2020-10-16T07:50:00Z","AveragePowerConsumptionInKW":0.0,"AveragePowerGenerationInKW":27.0}' msg = Message(msgData, message_id=None, content_encoding="utf-8", content_type="application/json", output_name=None) await device_client.send_message(msg) print("Send message to AssetHUB") await device_client.disconnect()
def send_data(device, temp, humidity, gps, client): #msg_txt_formatted = MSG_TXT.format(deviceID=device,temperature=temp, humidity=humidity, init_lat=gps['initial']['lat'], init_long=gps['initial']['long'], final_lat=gps['final']['lat'], final_long=gps['final']['long'], current_lat=gps['current']['lat'], current_long=gps['current']['long']) #msg_txt_formatted = MSG_TXT.format(temperature=temp, humidity=humidity, initlat=gps['initial']['lat'], initlong=gps['initial']['long'], finallat=gps['final']['lat'], finallong=gps['final']['long'], currentlat=gps['current']['lat'], currentlong=gps['current']['long']) msg_txt_formatted = MSG_TXT.format(hashid=device,temperature=temp, humidity=humidity, initlat=gps['initial']['lat'], initlong=gps['initial']['long'],finallat=gps['final']['lat'], finallong=gps['final']['long'], currentlat=gps['current']['lat'], currentlong=gps['current']['long']) message = Message(msg_txt_formatted) print( "Sending message: {}".format(message) ) sample = {"deviceID": device,"temperature": temp,"humidity": humidity, "init_lat": gps['initial']['lat'], "init_long":gps['initial']['long'], "final_lat": gps['final']['lat'],"final_long":gps['final']['long'], "current_lat":gps['current']['lat'], "current_long": gps['current']['long']} #client.send_message(json.dumps(sample, ensure_ascii=False).encode('utf8')) client.send_message(message) print ( "Message successfully sent" )
def iothub_client_telemetry_sample_run(): try: client = iothub_client_init() print("IoT Hub device sending message") # Build the message. action = sys.argv[1] msg_txt_formatted = MSG_TXT.format(action=action) message = Message(msg_txt_formatted) # Send the message. print("Sending message: {}".format(msg_txt_formatted)) client.send_message(message) print("Message successfully sent") except KeyboardInterrupt: print("IoTHubClient sample stopped")
def sendMessageToCloud() : try : client = iotHubClientInit() print ("Sending periodic messages, CTRL+C to exit") while True: messageText = '{' for s in conf.Sensors: s.generateValue() if messageText != '{': messageText += ',' if s.ValueType == "bool": messageText += ' "' + s.Name + '" : "' + s.CurrentValue + '"' else: messageText += ' "' + s.Name + '" : ' + s.CurrentValue messageText += '}' message = Message(messageText) # custom application prop message.custom_properties["deviceGuid"] = conf.GUID message.custom_properties["deviceName"] = conf.Name message.custom_properties["locationId"] = conf.LocationId message.custom_properties["externalIp"] = ExternalIp # an IoT hub can filter on these properties without accesss to the message body for sensor in conf.Sensors: for alert in conf.Alerts: if sensor.Name == alert.SensorName: if sensor.ValueType == "bool": if alert.Operand.lower() == "equal" and bool(sensor.CurrentValue) == bool(alert.Value): message.custom_properties[alert.Name] = "true" continue sValue = float(sensor.CurrentValue) if alert.Operand.lower() == "greater" and sValue > alert.Value or \ alert.Operand.lower() == "equal" and sValue == alert.Value or \ alert.Operand.lower() == "smaller" and sValue < alert.Value: message.custom_properties[alert.Name] = "true" # send the message print("Sending: {}".format(message)) client.send_message(message) print("Message sent") time.sleep(conf.SleepInSeconds) except KeyboardInterrupt: print("IoTHubClient sample stopped")
def readMag(self): xh = self.bus.read_byte_data(Registers.LSM, Registers.XH) xl = self.bus.read_byte_data(Registers.LSM, Registers.XL) yl = self.bus.read_byte_data(Registers.LSM, Registers.YL) yh = self.bus.read_byte_data(Registers.LSM, Registers.YH) zl = self.bus.read_byte_data(Registers.LSM, Registers.ZL) zh = self.bus.read_byte_data(Registers.LSM, Registers.ZH) x = (np.int16)(int(xh) << 8) | int(xl) y = (np.int16)(int(yh) << 8) | int(yl) z = (np.int16)(int(zh) << 8) | int(zl) if self.oldX != x or self.oldY != y or self.oldZ != z: self.oldX = x self.oldY = y self.oldZ = z print("{}, {}, {}".format(x, y, z)) xCal, yCal, zCal = self.calibration.calibrateValues( int(x), int(y), int(z)) self.checkReferentPoints(xCal, yCal, zCal) status = self.calculateStatus(xCal, yCal, zCal) if status == Status.OTVOREN.value: print("Prozor je otvoren") if status == Status.ZATVOREN.value: print("Prozor je zatvoren") if status == Status.KIPER.value: print("Prozor je otvoren na kip") lsm = LSM303Dto() lsm.x = str(xCal) lsm.y = str(yCal) lsm.z = str(zCal) lsm.status = status lsm.uuid = self.uuid lsm.created = int(dt.now().timestamp()) print("Drekooooo" + str(lsm.created)) message = Message(lsm.getJson()) print(message) return message else: return None
def iothub_client_telemetry_example_run(): try: client = iothub_client_init() print("IoT Hub device sending periodic messages, press Ctrl-C to exit") # connect the client. client.connect() # Run a listener thread in the background listen_thread = threading.Thread(target=message_listener, args=(client, )) listen_thread.daemon = True listen_thread.start() while True: # Build the message with telemetry values. temperature = None while process.values: par, val = process.values.popitem() print("%s: %16s == %r" % (time.ctime(), par, val)) temperature = val[0] humidity = val[1] msg_txt_formatted = MSG_TXT.format(temperature=temperature, humidity=humidity) message = Message(msg_txt_formatted) # Send the message. print("Sending message: {}".format(message)) client.send_message(message) print("Message successfully sent") while failure.string: exc = failure.string.pop(0) print("%s: %s" % (time.ctime(), exc)) time.sleep(1) except KeyboardInterrupt: print("IoTHubClient example stopped") process.done = True poller.join() # finally, disconnect client.disconnect()
def iothub_send_data(): global aburrido global dormido global aburrido_last global dormido_last #print ( "Aburrido:", aburrido, " Aburrido_last:", aburrido_last, " Dormido:", dormido, " Dormido_last:", dormido_last) #read_data_sensor() if aburrido != aburrido_last or dormido != dormido_last: aburrido_last = aburrido dormido_last = dormido msg_txt_formatted = MSG_TXT.format(ta=ta, tc=tc, aburrido=aburrido, dormido=dormido) message = Message(msg_txt_formatted) #print( "Enviando Mensaje a Iot-Hub: {}".format(message) ) device_client.send_message(message) print (message) #print ( "Mensaje enviado con exito" ) device_client.disconnect() else: #print ( "Sin Cambios" ) pass
def SendTelemetry(client): while True: try: now = datetime.now() timestamp = datetime.timestamp(now) ill not take more pictures after the first one is taken t = time.localtime() timestamp = time.strftime('%b-%d-%Y_%H%M', t) pic_no = random.randint(1,1001) piece_no= random.randint(1,10001) roi_section=random.randint(1,5) plant_no=random.randint(1,6) line= random.randint(1,9) loc=1 camera=random.randint(1,5) node_version=1 confidence=round(random.uniform(0,1),4) project=1 type_photo=1 id_class=str(uuid.uuid1().hex) classification=random.getrandbits(1) id_roi=str(uuid.uuid4().hex) id_photo=str(uuid.uuid1().int) ini_string = {"pic_no":int(pic_no),"piece_no": int(piece_no), "roi_section":int(roi_section), "plant_no":int(plant_no), "line":int(line), "loc":int(loc), "camera":int(camera),"confidence":float(confidence),"classification":int(classification), "id_class":id_class, "id_photo":id_photo, "id_roi":id_roi} # printing initial json msg_txt_formatted = json.dumps(ini_string) message = Message(msg_txt_formatted) # Enviar mensaje al IotHub print( "Mensaje enviado: {}".format(message) ) client.send_message(message) print ( "Mensaje enviado satisfactoriamente" ) time.sleep(30) #client.disconnect() except Exception as e: print(e) print ( "Client del IotHub con Error" )
async def send_test_message(): print("Sending telemetry message from device " + device_id) body_dict = {} body_dict['Temperature'] = random.randrange(76, 80, 1) body_dict['Humidity'] = random.randrange(40, 60, 1) body_dict['Location'] = '28.424911, -81.468962' body_json = json.dumps(body_dict) print(body_json) msg = Message(body_json) msg.message_id = uuid.uuid4() msg.correlation_id = "correlation-1234" msg.contentEncoding = "utf-8", msg.contentType = "application/json", await device_client.send_message(msg) print("Done sending message")
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. generalInformation = "It's a beautiful day" incomingInformation = "Coffe machine is working great!" msg_txt_formatted = MSG_TXT.format( generalInformation=generalInformation, incomingInformation=incomingInformation) 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. print("Sending message: {}".format(message)) client.send_message(message) print("Message successfully sent") time.sleep(300) except KeyboardInterrupt: print("IoTHubClient sample stopped")