async def send_data(): global BATTERY_CAPACITY while BATTERY_CAPACITY > 0: mensaje = { "bateria": BATTERY_CAPACITY, "temperatura": random.randint(35, 100), "humedad": random.randint(0, 100), "latitud": round(random.uniform(40.400000, 40.450000), 6), "longitud": round(random.uniform(-3.800000, -3.700000), 6) } BATTERY_CAPACITY -= 1 msg = Message(json.dumps(mensaje)) msg.message_id = uuid.uuid4() msg.correlation_id = "tfmId" if mensaje.get("temperatura") > 95: msg.custom_properties["fire"] = "yes" else: msg.custom_properties["fire"] = "no" print("Sending data: ", msg) await module_client.send_message_to_output(msg, "data_output") time.sleep(0.5)
def main(): # The connection string for a device should never be stored in code. For the sake of simplicity we're using an environment variable here. conn_str = os.getenv("IOTHUB_DEVICE_CONNECTION_STRING") # The client object is used to interact with your Azure IoT hub. device_client = IoTHubDeviceClient.create_from_connection_string(conn_str) print("IoTHub Device Client Recurring Telemetry Sample") print("Press Ctrl+C to exit") try: # Connect the client. 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)) device_client.send_message(msg) time.sleep(2) except KeyboardInterrupt: print("User initiated exit") except Exception: print("Unexpected exception!") raise finally: device_client.shutdown()
async def send_message(device_client, i): msg_body = json.dumps(simulated_telemetry_data(i)) print('sending message: {}'.format(msg_body)) msg_id = uuid.uuid4() msg = Message(msg_body) msg.message_id = msg_id msg.correlation_id = msg_id await device_client.send_message(msg)
async def send_test_message(i): print("sending message #" + str(i)) msg = Message("test wind speed " + str(i)) msg.message_id = uuid.uuid4() msg.correlation_id = "correlation-1234" msg.custom_properties["tornado-warning"] = "yes" await device_client.send_message(msg) print("done sending message #" + str(i))
async def send_to_Hub_callback(strMessage): print("Start sending message") print(strMessage) msg = Message(strMessage) msg.message_id = uuid.uuid4() msg.correlation_id = "test-1234" await hubManager.send_message_to_output(msg,"output1") print("Done sending message")
async def send_test_message(i): print("sending message #" + str(i)) 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" await module_client.send_message(msg) print("done sending message #" + str(i))
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))
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")
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)
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 input1_listener(module_client): global LATEST_TAG while True: input_message = await module_client.receive_message_on_input("input1") data = json.loads(input_message.data) highestProbabilityTag = highestProbabilityTagMeetingThreshold(data, 0.6) if highestProbabilityTag == "none": print("Not sending alert to hub => no tag reached probability") elif highestProbabilityTag == "Negative": print("Not sending alert to hub => Negative tag") else: print("Sending alert to hub for: {}".format(highestProbabilityTag)) output_msg = Message("{'tag':'"+highestProbabilityTag+"'}") output_msg.message_id = uuid.uuid4() output_msg.correlation_id = "test-1234" await module_client.send_message_to_output(output_msg,"output1") print("Latest tag: " + LATEST_TAG)
async def send_test_message(i): global led_manager global message_index print("sending message #" + str(message_index)) body_dict = {} body_dict['Weather'] = {} body_dict['Weather']['Temperature'] = random.randrange(65, 75, 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"] = "no" msg.contentEncoding = "utf-8", msg.contentType = "application/json", await device_client.send_message(msg) print('Message #' + str(message_index) + ' sent') led_manager.set_led(i, 'On', 0, 255, 0, True) message_index = message_index + 1
def processsendcache(devceclient): try: number = 0 Path("./sendcache/").mkdir(parents=True, exist_ok=True) for filename1 in os.listdir('./sendcache/'): if number == 30: break number += 1 print(filename1) f = open('./sendcache/' + filename1, 'r') x = json.load(f) print(x) bytes = x.encode('utf-8', 'replace') msg = Message(jsonString) msg.message_id = uuid.uuid4() msg.correlation_id = "correlation-1234" #msg.custom_properties["tornado-warning"] = "yes" devceclient.send_message(msg) os.remove('./sendcache/' + filename1) except: print("An exception occurred on processing to sendcache! (" + filename1 + ")")
async def send_test_message(i): time.sleep(1) print("sending message #" + str(i)) msg = Message( "{ \"MGPID\": 48, \"MGPLabel\": \"X_tilt\", \"MGPName\": \"X_tilt\", \"Timestamp\": \"2020-08-12 17:57:02\", \"usec\": 492949, \"ParamVal\": \"88.000000\" }" ) msg.message_id = uuid.uuid4() msg.correlation_id = "correlation-1234" msg.custom_properties = { "CustomerId": "1", "ProgramId": 2, "RegionId": 1964, "DeviceType": "4a", "MessageVersion": 23, "VIN": 3215, "ESN": 4232545, "DeviceSignalTimestamp": 7, "Provider": "Dana", "DeviceReleaseVersion": 1.0, "PlantId": 38 } await device_client.send_message(msg) print("done sending message #" + str(i))
def on_message(client, userdata, message): logger.info(f'Message received: {message.payload}') logger.info('Parsing Payload JSON...') # try and parse to Json json_data = json.loads(message.payload) if not isinstance(json_data, dict): return obj = json_data.get('object') if not obj: logging.warning('Parsed JSON did not contain "object".') else: logger.info('DeviceID : ', json_data.get('devEUI')) obj['APPLICATION_ID'] = APPLICATION_ID obj['devEUI'] = json_data['devEUI'] json_data_str = json.dumps(obj) logger.info(f'Object: {json_data_str}') logger.info('Azure: sending message...') message_to_azure = Message(json_data_str) message_to_azure.message_id = uuid.uuid4() message_to_azure.correlation_id = 'correlation-1234' logger.info('Azure:Connecting azure client') azure_client.connect() logger.info('Azure:Connected Azure client. Sending message...') azure_client.send_message(message_to_azure) logger.info('Azure: Message Sent. ') azure_client.disconnect()
x509 = X509( cert_file=os.getenv("X509_CERT_FILE"), key_file=os.getenv("X509_KEY_FILE"), pass_phrase=os.getenv("PASS_PHRASE"), ) module_client = IoTHubModuleClient.create_from_x509_certificate( hostname=hostname, x509=x509, device_id=device_id, module_id=module_id) module_client.connect() # send 5 messages with a 1 second pause between each message for i in range(1, 6): print("sending message #" + str(i)) msg = Message("test wind speed " + str(i)) msg.message_id = uuid.uuid4() msg.correlation_id = "correlation-1234" msg.custom_properties["tornado-warning"] = "yes" module_client.send_d2c_message(msg) time.sleep(1) # send only string messages for i in range(6, 11): print("sending message #" + str(i)) module_client.send_d2c_message("test payload message " + str(i)) time.sleep(1) # finally, disconnect module_client.disconnect()
async def sensor_data(): msg = Message("Acceleration: "+str(node.readAccel())+"; "+"Humidity: " + str(node.readHum())+"; "+"Temperature: " + str(node.readTemp())+"; "+"Lux: " + str(node.readLux())+"; "+"ADC1: " + str(node.readAdc(0))+"; "+"ADC2: " + str(node.readAdc(1))+"; "+"ADC3: " + str(node.readAdc(2))+"; "+"ADC4: " + str(node.readAdc(3))) msg.message_id = uuid.uuid4() msg.correlation_id = "correlation-1234" await device_client.send_message(msg)
def main(): #while (1==1): # Read the config config = configparser.ConfigParser() try: config.read('TempLogger.config') except: print("An exception occurred on reading configuration!") sys.exit() myserial = getserial() deviceId = 'raspi' + myserial IoTHubDeviceConnectionString = 'HostName=' + config['AzIoTHub'][ 'HostName'] + ';DeviceId=' + deviceId + ';SharedAccessKey=' + config[ 'AzIoTHubDevice']['SharedAccessKey'] print(deviceId) timestamp = datetime.datetime.utcnow().isoformat() obj = getISSPosition() jsonString = JSONEncoder().encode({ "DeviceID": deviceId, "TimestampUTC": timestamp, "longitude": obj['iss_position']['longitude'], "latitude": obj['iss_position']['latitude'], "cpuTemperature": str(getCpuTemperature()), "S1Temperature": str(getSensorTemp('28-041643c28fff')), "S2Temperature": str(getSensorTemp('28-031643ddf8ff')), "S3Temperature": str(getSensorTemp('28-0316440316ff')), "S4Temperature": str(getSensorTemp('28-031644338cff')), "S5Temperature": str(getSensorTemp('28-0316443b9eff')), "OperatingMinutes": str(getUptime()) }) # The client object is used to interact with your Azure IoT hub. print(IoTHubDeviceConnectionString) device_client = IoTHubDeviceClient.create_from_connection_string( IoTHubDeviceConnectionString) try: # Connect the client. device_client.connect() msg = Message(jsonString) msg.message_id = uuid.uuid4() msg.correlation_id = "correlation-1234" #msg.custom_properties["tornado-warning"] = "yes" device_client.send_message(msg) except Exception as inst: print("An exception occurred on sending message. (" + inst + ")") writetosendcache(jsonString) finally: # finally, disconnect try: device_client.disconnect() except Exception as e: print("An exception occurred disconnet device client. (" + e + ")")