def iothub_client_telemetry_sample_run(): try: client = iothub_client_init() print("IoT Hub device sending periodic messages, press Ctrl-C to exit") temp = '' while True: # Build the message with simulated telemetry values. msg = open("/home/pi/Desktop/OpenVINO-YoloV3/out_files/data.json", 'r') content = msg.read() msg.close() #or content=="[\n]" or content=="[]" if (temp == content or content == ""): continue else: message = IoTHubMessage(content) temp = content # Send the message. print("Sending message: %s" % message.get_string()) client.send_event_async(message, send_confirmation_callback, None) except IoTHubError as iothub_error: print("Unexpected error %s from IoTHub" % iothub_error) return except KeyboardInterrupt: print("IoTHubClient sample stopped")
def main(protocol): try: print("\nPython %s\n" % sys.version) print("IoT Edge Client for Python") hub_manager = HubManager(protocol) print("Starting the IoT Hub Python sample using protocol %s..." % hub_manager.client_protocol) print( "The sample is now waiting for messages and will indefinitely. 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 % (temperature, humidity) message = IoTHubMessage(msg_txt_formatted) # Send the message. print("Steven demo sending message: %s" % message.get_string()) hub_manager.forward_event_to_output("temperatureOutput", message, 0) time.sleep(1) except IoTHubError as iothub_error: print("Unexpected error %s from IoTHub" % iothub_error) return except KeyboardInterrupt: print("IoTHubModuleClient 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: # Build the message with simulated telemetry values. liveReading = LIVE_READING + random.randrange(0, 1000) msg_txt_formatted = MSG_TXT % (liveReading) message = IoTHubMessage(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. prop_map = message.properties() if liveReading > 700: prop_map.add("highConsumptionAlert", "true") else: prop_map.add("highConsumptionAlert", "false") # Send the message. print( "Sending message: %s" % message.get_string() ) client.send_event_async(message, send_confirmation_callback, None) time.sleep(1) except IoTHubError as iothub_error: print ( "Unexpected error %s from IoTHub" % iothub_error ) return except KeyboardInterrupt: print ( "IoTHubClient sample stopped" )
def iothub_client_sample_run(): try: if (check_internet() == True): client = iothub_client_init() print("Connecting to IoT Hub") if client.protocol == IoTHubTransportProvider.MQTT: print("IoTHubClient is reporting state") reported_state = "{\"newState\":\"standBy\"}" #client.send_reported_state(reported_state, len(reported_state), send_reported_state_callback, SEND_REPORTED_STATE_CONTEXT) #telemetry.send_telemetry_data(parse_iot_hub_name(), EVENT_SUCCESS, "IoT hub connection is established") #while True: global MESSAGE_COUNT, MESSAGE_SWITCH if MESSAGE_SWITCH: # send a few messages every minute print("IoTHubClient sending %d messages" % MESSAGE_COUNT) #temperature = sensor.read_temperature() humidity_1 = get_humidity_1() temperature_1 = get_temperature_1() distance_1 = get_distance_1() distance_2 = get_distance_2() distance_3 = get_distance_3() distance_4 = get_distance_4() distance_5 = get_distance_5() distance_6 = get_distance_6() distance_7 = get_distance_7() distance_8 = get_distance_8() #distance_9 = get_distance_9() #distance_10 = get_distance_10() msg_txt_formatted = MSG_TXT % ( distance_1, distance_2, distance_3, distance_4, distance_5, distance_6, distance_7, distance_8, distance_8, distance_8) print(msg_txt_formatted) message = IoTHubMessage(msg_txt_formatted) # optional: assign ids message.message_id = "message_%d" % MESSAGE_COUNT message.correlation_id = "correlation_%d" % MESSAGE_COUNT # optional: assign properties prop_map = message.properties() prop_map.add("temperatureAlert", "true") client.send_event_async(message, send_confirmation_callback, MESSAGE_COUNT) print( "IoTHubClient.send_event_async accepted message [%d] for transmission to IoT Hub." % MESSAGE_COUNT) status = client.get_send_status() print("Send status: %s" % status) MESSAGE_COUNT += 1 time.sleep(2) except IoTHubError as iothub_error: print("Unexpected error %s from IoTHub" % iothub_error) telemetry.send_telemetry_data( parse_iot_hub_name(), EVENT_FAILED, "Unexpected error %s from IoTHub" % iothub_error) return 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") # Set up the callback method for direct method calls from the hub. client.set_device_method_callback(device_method_callback, None) while True: # Build the message with simulated telemetry values. msg_txt_formatted = MSG_TXT % (humidity, temperature) message = IoTHubMessage(msg_txt_formatted) # Send the message. print("Sending message: %s" % message.get_string()) client.send_event_async(message, send_confirmation_callback, None) time.sleep(INTERVAL) except IoTHubError as iothub_error: print("Unexpected error %s from IoTHub" % iothub_error) return 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: # Build the message with simulated telemetry values. temperature = TEMPERATURE + (random.random() * 15) humidity = HUMIDITY + (random.random() * 20) msg_txt_formatted = MSG_TXT % (temperature, humidity) message = IoTHubMessage(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. prop_map = message.properties() if temperature > 30: prop_map.add("temperatureAlert", "true") else: prop_map.add("temperatureAlert", "false") # Send the message. print( "Sending message: %s" % message.get_string() ) client.send_event_async(message, send_confirmation_callback, None) time.sleep(1) except IoTHubError as iothub_error: print ( "Unexpected error %s from IoTHub" % iothub_error ) return except KeyboardInterrupt: print ( "IoTHubClient sample stopped" )
def create_message(message_counter): AVG_WIND_SPEED = 10.0 MIN_TEMPERATURE = 20.0 MIN_HUMIDITY = 60.0 temperature = MIN_TEMPERATURE + (random.random() * 10) humidity = MIN_HUMIDITY + (random.random() * 20) msg_txt_formatted = MSG_TXT % ( AVG_WIND_SPEED + (random.random() * 4 + 2), temperature, humidity) # messages can be encoded as string or bytearray if (message_counter & 1) == 1: message = IoTHubMessage(bytearray(msg_txt_formatted, 'utf8')) else: message = IoTHubMessage(msg_txt_formatted) # optional: assign ids message.message_id = "message_%d" % message_counter message.correlation_id = "correlation_%d" % message_counter # optional: assign properties prop_map = message.properties() prop_map.add("temperatureAlert", 'true' if temperature > 28 else 'false') return message
def main(protocol): try: print ( "\nPython %s\n" % sys.version ) print ( "IoT Hub Client for Python" ) hub_manager = HubManager(protocol) print ( "Starting the OBD module using protocol %s..." % hub_manager.client_protocol ) print ( "This module is now waiting for messages and will indefinitely. Press Ctrl-C to exit. ") while True: obdMsg = obdreader.getVehicleTelemtries(DEVICE_ID) print("received obd msg: " + str(obdMsg)) if(obdMsg is not None): msg = IoTHubMessage(bytearray(obdMsg, 'utf8')) #in order to use IoT Hub message routing on body, we have to setup the content type and encoding set_content_result = msg.set_content_encoding_system_property("utf-8") set_content_type_result = msg.set_content_type_system_property("application/json") if set_content_result != 0: print("set_content_encoding_system_property FAILED") if set_content_type_result != 0: print("set_content_type_system_property FAILED") hub_manager.forward_event_to_output("obd", msg, 0) time.sleep(1) except IoTHubError as iothub_error: print ( "Unexpected error %s from IoTHub" % iothub_error ) return except KeyboardInterrupt: print ( "IoTHubModuleClient sample stopped" )
def read_and_send_measurements_from_sensehat(sense, hubManager): global SEND_SENSEHAT_CALLBACKS # sense.clear() temperature = sense.get_temperature() temperature_h = sense.get_temperature_from_humidity() temperature_p = sense.get_temperature_from_pressure() humidity = sense.get_humidity() pressure = sense.get_pressure() accelerometer = sense.get_accelerometer_raw() accel = "\"x\":{x:.5f},\"y\":{y:.5f},\"z\":{z:.5f}".format(**accelerometer) print("accelerometer - %s" % accel) timeCreated = datetime.datetime.utcnow().isoformat() MSG_TXT = "{\"temperature\": %.2f,\"temperature_h\": %.2f,\"temperature_p\": %.2f,\"humidity\": %.2f,\"pressure\": %.2f,\"accelerometer\":{%s},\"timeCreated\": \"%s\"}" msg_txt_formatted = MSG_TXT % (temperature, temperature_h, temperature_p, humidity, pressure, accel, timeCreated) print("Sending - :%s\n" % msg_txt_formatted) message = IoTHubMessage(msg_txt_formatted) prop_map = message.properties() prop_map.add("data-type", "sensing") prop_map.add("application", "Custom-vision-service-iot-edge-raspberry-pi-ext") hubManager.send_event_to_output("output2", message, 0) SEND_SENSEHAT_CALLBACKS += 1 print(" Total sensehat messages sent: %d" % SEND_SENSEHAT_CALLBACKS)
def iothub_client_sample_run(): try: client = iothub_client_init() if client.protocol == IoTHubTransportProvider.MQTT: print("IoTHubClient is reporting state") reported_state = "{\"newState\":\"standBy\"}" client.send_reported_state(reported_state, len(reported_state), send_reported_state_callback, SEND_REPORTED_STATE_CONTEXT) if not config.SIMULATED_DATA: sensor = BME280(address=config.I2C_ADDRESS) else: sensor = BME280SensorSimulator() while True: global MESSAGE_COUNT, MESSAGE_SWITCH if MESSAGE_SWITCH: # send a few messages every minute print("IoTHubClient sending %d messages" % MESSAGE_COUNT) cpu_percent = psutil.cpu_percent() memory = psutil.virtual_memory() memorypercent = float(memory.used) / float(memory.total) temperature = sensor.read_temperature() humidity = sensor.read_humidity() msg_txt_formatted = MSG_TXT % (temperature, humidity, cpu_percent, memorypercent) print(msg_txt_formatted) message = IoTHubMessage(msg_txt_formatted) # optional: assign ids message.message_id = "message_%d" % MESSAGE_COUNT message.correlation_id = "correlation_%d" % MESSAGE_COUNT # optional: assign properties prop_map = message.properties() prop_map.add( "temperatureAlert", "true" if temperature > TEMPERATURE_ALERT else "false") client.send_event_async(message, send_confirmation_callback, MESSAGE_COUNT) print( "IoTHubClient.send_event_async accepted message [%d] for transmission to IoT Hub." % MESSAGE_COUNT) status = client.get_send_status() print("Send status: %s" % status) MESSAGE_COUNT += 1 time.sleep(config.MESSAGE_TIMESPAN / 1000.0) except IoTHubError as iothub_error: print("Unexpected error %s from IoTHub" % iothub_error) telemetry.send_telemetry_data( parse_iot_hub_name(), EVENT_FAILED, "Unexpected error %s from IoTHub" % iothub_error) return except KeyboardInterrupt: print("IoTHubClient sample stopped") print_last_message_time(client)
def send_to_Hub_callback(strMessage): if strMessage == []: return message = IoTHubMessage(bytearray(strMessage, 'utf8')) prop_map = message.properties() prop_map.add("appid", "scanner") hubManager.send_event_to_output("output1", message, 0) print('sent from send_to_Hub_callback')
def iothub_client_sample_run(): try: client = iothub_client_init() if client.protocol == IoTHubTransportProvider.MQTT: print ( "IoTHubClient is reporting state" ) reported_state = "{\"newState\":\"standBy\"}" client.send_reported_state(reported_state, len(reported_state), send_reported_state_callback, SEND_REPORTED_STATE_CONTEXT) if not config.SIMULATED_DATA: sensor = BME280(address = config.I2C_ADDRESS) else: sensor = BME280SensorSimulator() telemetry.send_telemetry_data(parse_iot_hub_name(), EVENT_SUCCESS, "IoT hub connection is established") while True: global MESSAGE_COUNT,MESSAGE_SWITCH if MESSAGE_SWITCH: # send a few messages every minute print ( "IoTHubClient sending %d messages" % MESSAGE_COUNT ) temperature = sensor.read_temperature() humidity = sensor.read_humidity() timeStamp = time.time() dataValue = 0 if DEVICE_TYPE=="T": dataValue = temperature else : dataValue = humidity msg_txt_formatted = MSG_TXT % ( DEVICE_TYPE, DEVICE_ID, timeStamp, dataValue) print (msg_txt_formatted) message = IoTHubMessage(msg_txt_formatted) # optional: assign ids message.message_id = "message_%d" % MESSAGE_COUNT message.correlation_id = "correlation_%d" % MESSAGE_COUNT # optional: assign properties prop_map = message.properties() prop_map.add("temperatureAlert", "true" if temperature > TEMPERATURE_ALERT else "false") client.send_event_async(message, send_confirmation_callback, MESSAGE_COUNT) print ( "IoTHubClient.send_event_async accepted message [%d] for transmission to IoT Hub." % MESSAGE_COUNT ) status = client.get_send_status() print ( "Send status: %s" % status ) MESSAGE_COUNT += 1 time.sleep(config.MESSAGE_TIMESPAN / 1000.0) except IoTHubError as iothub_error: print ( "Unexpected error %s from IoTHub" % iothub_error ) telemetry.send_telemetry_data(parse_iot_hub_name(), EVENT_FAILED, "Unexpected error %s from IoTHub" % iothub_error) return except KeyboardInterrupt: print ( "IoTHubClient sample stopped" ) print_last_message_time(client)
def iothub_client_run(): try: client = iothub_client_init() if client.protocol == IoTHubTransportProvider.MQTT: print("IoTHubClient is reporting state") reported_state = "{\"newState\":\"standBy\"}" client.send_reported_state(reported_state, len(reported_state), send_reported_state_callback, SEND_REPORTED_STATE_CONTEXT) if not config.SIMULATED_DATA: sensor = Sensor(DEVICE_FILE) else: sensor = SensorSimulator() telemetry.send_telemetry_data(parse_iot_hub_name(), EVENT_SUCCESS, "IoT hub connection is established") before_temperature = 0 while True: global MESSAGE_COUNT, MESSAGE_SWITCH if MESSAGE_SWITCH: # send a few messages every minute print("IoTHubClient sending %d messages" % MESSAGE_COUNT) temperature = sensor.read_temperature() msg_txt_formatted = MSG_TXT % (DEVICE_NAME, temperature, before_temperature) print(msg_txt_formatted) message = IoTHubMessage(msg_txt_formatted) # optional: assign ids message.message_id = "message_%d" % MESSAGE_COUNT message.correlation_id = "correlation_%d" % MESSAGE_COUNT # optional: assign properties prop_map = message.properties() client.send_event_async(message, send_confirmation_callback, MESSAGE_COUNT) print( "IoTHubClient.send_event_async accepted message [%d] for transmission to IoT Hub." % MESSAGE_COUNT) status = client.get_send_status() print("Send status: %s" % status) before_temperature = temperature MESSAGE_COUNT += 1 time.sleep(config.MESSAGE_TIMESPAN / 1000.0) except IoTHubError as iothub_error: print("Unexpected error %s from IoTHub" % iothub_error) telemetry.send_telemetry_data( parse_iot_hub_name(), EVENT_FAILED, "Unexpected error %s from IoTHub" % iothub_error) return except KeyboardInterrupt: print("IoTHubClient sample stopped") print_last_message_time(client)
def iothub_client_sample_run(): try: client = iothub_client_init() if client.protocol == IoTHubTransportProvider.MQTT: print ( "IoTHubClient is reporting state" ) reported_state = "{\"newState\":\"standBy\"}" client.send_reported_state(reported_state, len(reported_state), send_reported_state_callback, SEND_REPORTED_STATE_CONTEXT) #if not config.SIMULATED_DATA: # sensor = BME280(address = config.I2C_ADDRESS) #else: #sensor = BME280SensorSimulator() #TEST sensor = Adafruit_DHT.DHT11 telemetry.send_telemetry_data(parse_iot_hub_name(), EVENT_SUCCESS, "IoT hub connection is established") while True: global MESSAGE_COUNT,MESSAGE_SWITCH if MESSAGE_SWITCH: #led_blink(config.CHANNEL_WATER_PUMP) #led_blink(config.CHANNEL_DRAINAGE) # send a few messages every minute print ( "IoTHubClient sending %d messages" % MESSAGE_COUNT ) #temperature = sensor.read_temperature() #TEST #humidity = sensor.read_humidity() #TEST humidity, temperature = Adafruit_DHT.read_retry(sensor, config.CHANNEL_TEMPERATURE_HUMIDITY) soilMoisture = GPIO.input(config.CHANNEL_SOIL_MOISTURE) isRaining = GPIO.input(config.CHANNEL_RAIN_SENSOR) msg_txt_formatted = MSG_TXT % ( temperature, humidity, soilMoisture, isRaining) print (msg_txt_formatted) message = IoTHubMessage(msg_txt_formatted) # optional: assign ids message.message_id = "message_%d" % MESSAGE_COUNT message.correlation_id = "correlation_%d" % MESSAGE_COUNT # optional: assign properties prop_map = message.properties() prop_map.add("temperatureAlert", "true" if temperature > TEMPERATURE_ALERT else "false") client.send_event_async(message, send_confirmation_callback, MESSAGE_COUNT) print ( "IoTHubClient.send_event_async accepted message [%d] for transmission to IoT Hub." % MESSAGE_COUNT ) status = client.get_send_status() print ( "Send status: %s" % status ) MESSAGE_COUNT += 1 time.sleep(config.MESSAGE_TIMESPAN / 1000.0) except IoTHubError as iothub_error: print ( "Unexpected error %s from IoTHub" % iothub_error ) telemetry.send_telemetry_data(parse_iot_hub_name(), EVENT_FAILED, "Unexpected error %s from IoTHub" % iothub_error) return except KeyboardInterrupt: print ( "IoTHubClient sample stopped" ) print_last_message_time(client)
def iothub_client_sample_run(): try: client = iothub_client_init() if client.protocol == IoTHubTransportProvider.MQTT: print("IoTHubClient is reporting state") reported_state = "{\"newState\":\"standBy\"}" client.send_reported_state(reported_state, len(reported_state), send_reported_state_callback, SEND_REPORTED_STATE_CONTEXT) telemetry.send_telemetry_data(parse_iot_hub_name(), EVENT_SUCCESS, "IoT hub connection is established") while True: #tripWire() global MESSAGE_COUNT, MESSAGE_SWITCH if MESSAGE_SWITCH: # send a few messages every minute print("IoTHubClient sending %d messages" % MESSAGE_COUNT) if tripWire() == 0: lightState = "ON" num = 0 else: lightState = "OFF" num = 1 #humidity = 1.23 #temperature = 4.56 #msg_txt_formatted = MSG_TXT % (temperature,humidity) msg_txt_formatted = MSG_TXT % num print(msg_txt_formatted) message = IoTHubMessage(msg_txt_formatted) message.message_id = "message_%d" % MESSAGE_COUNT message.correlation_id = "correlation_%d" % MESSAGE_COUNT prop_map = message.properties() prop_map.add("Lightstate", lightState) client.send_event_async(message, send_confirmation_callback, MESSAGE_COUNT) print( "IoTHubClient.send_event_async accepted message [%d] for transmission to IoT Hub." % MESSAGE_COUNT) status = client.get_send_status() print("Send status: %s" % status) MESSAGE_COUNT += 1 time.sleep(1) #Brandon except IoTHubError as iothub_error: print("Unexpected error %s from IoTHub" % iothub_error) telemetry.send_telemetry_data( parse_iot_hub_name(), EVENT_FAILED, "Unexpected error %s from IoTHub" % iothub_error) return except KeyboardInterrupt: GPIO.cleanup() print("IoTHubClient sample stopped") print_last_message_time(client)
def send_event_to_output(self, message, properties, send_context): event = IoTHubMessage(bytearray(message, 'utf8')) if len(properties) > 0: prop_map = event.properties() for key in properties: prop_map.add_or_update(key, properties[key]) self.client.send_event_async(event, send_confirmation_callback, send_context)
def iothub_client_telemetry_sample_run(): client = iothub_client_init() print ( "IoT Hub device sending periodic messages, press Ctrl-C to exit" ) try: temp = 0.01 hum = 0.01 [ temp,hum ] = dht(dht_sensor_port,0) #Get the temperature and Humidity from the DHT sensor #Change the second parameter to 0 when using DHT (instead of DHT Pro) #You will get very large number values if you don't! if (CtoF(temp) != lastTemp) and (hum != lastHum) and not math.isnan(temp) and not math.isnan(hum): #print("lowC : ",FtoC(tooLow),"C\t\t","rightC : ", FtoC(justRight),"C\t\t","highC : ",FtoC(tooHigh),"C") # comment these three lines #print("lowF : ",tooLow,"F\t\tjustRight : ",justRight,"F\t\ttoHigh : ",tooHigh,"F") # if no monitor display print("tempC : ", temp, "C\t\ttempF : ",CtoF(temp),"F\t\tHumidity =", hum,"%\r\n") #lastHum = hum # save temp & humidity values so that there is no update to the RGB LCD ftemp = CtoF(temp) # unless the value changes ftemp = temp # unless the value changes #lastTemp = ftemp # this reduces the flashing of the display # print "ftemp = ",ftemp," temp = ",temp # this was just for test and debug bgList = calcBG(ftemp) # Calculate background colors t = str(ftemp) # "stringify" the display values h = str(hum) # print "(",bgList[0],",",bgList[1],",",bgList[2],")" # this was to test and debug color value list setRGB(bgList[0],bgList[1],bgList[2]) # parse our list into the color settings setText("Temp:" + t + "C " + "Humidity :" + h + "%") # update the RGB LCD display # Build the message with real telemetry values. temperature = temp humidity = hum msg_txt_formatted = MSG_TXT % (temperature, humidity) message = IoTHubMessage(msg_txt_formatted) # print("JSON payload = " + 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. #prop_map = message.properties() #if temperature > 30: # prop_map.add("temperatureAlert", "true") #else: # prop_map.add("temperatureAlert", "false") # Send the message. print( "Sending message: %s" % message.get_string() ) client.send_event_async(message, send_confirmation_callback, None) time.sleep(5) except IoTHubError as iothub_error: print ( "Unexpected error %s from IoTHub" % iothub_error ) return except KeyboardInterrupt: print ( "IoTHubClient sample stopped" ) except (IOError,TypeError) as e: print("Error" + str(e))
def check(json_message): message = json.loads(json_message) temperature = message["temperature"] orientation = message["orientation"] acceleration = message["accelerometer"] # Limits: tempLimit = 35.0 orientateLowerLimit = 1.0 orientateUpperLimit = 350.0 accelerateLimit = 15.0 accelerateYawIdeal = 150.0 accelerateRollIdeal = 355.0 acceleratePitchIdeal = 355.0 # Yaw, Roll, Pitch: orientateRoll = orientation["roll"] orientatePitch = orientation["pitch"] accelerateYaw = acceleration["yaw"] accelerateRoll = acceleration["roll"] acceleratePitch = acceleration["pitch"] # Calculations: accelerateYawDiff = abs(accelerateYaw - accelerateYawIdeal) accelerateRollDiff = abs(accelerateRoll - accelerateRollIdeal) acceleratePitchDiff = abs(acceleratePitch - acceleratePitchIdeal) # End script if conditions are not normal: if temperature > tempLimit: client = iothub_client_init() lastmessage = IoTHubMessage(message_to_iothub()) client.send_event_async(lastmessage, send_confirmation_callback, None) return end_script() elif orientateRoll > orientateLowerLimit and orientateRoll < orientateUpperLimit: client = iothub_client_init() lastmessage = IoTHubMessage(message_to_iothub()) client.send_event_async(lastmessage, send_confirmation_callback, None) # return end_script() wait(2) elif orientatePitch > orientateLowerLimit and orientatePitch < orientateUpperLimit: client = iothub_client_init() lastmessage = IoTHubMessage(message_to_iothub()) client.send_event_async(lastmessage, send_confirmation_callback, None) # return end_script() wait(2) elif accelerateRollDiff > accelerateLimit or acceleratePitchDiff > accelerateLimit: client = iothub_client_init() lastmessage = IoTHubMessage(message_to_iothub()) client.send_event_async(lastmessage, send_confirmation_callback, None) # return end_script() wait(0.25)
def main(protocol): global messageCounter global hub_manager try: print("\nPython %s\n" % sys.version) print("IoT Hub Client for Python") hub_manager = HubManager(protocol) print("Starting the IoT Hub Python sample using protocol %s..." % hub_manager.client_protocol) while True: time.sleep(POLLINGfrequency) modbusclient = ModbusClient(POLLINGHost, port=502) try: modbusclient.connect() messageToSend = {} messageToSend['POLLINGHost'] = POLLINGHost messageToSend['dateTime'] = str(datetime.datetime.now()) messageToSend[ 'Las Vegas'] = modbusclient.read_holding_registers( 0, 1, unit=0x01).registers[0] messageToSend[ 'Stockholm'] = modbusclient.read_holding_registers( 1, 1, unit=0x01).registers[0] messageToSend[ 'Wadi Halfa'] = modbusclient.read_holding_registers( 2, 1, unit=0x01).registers[0] messageToSend[ 'MSFT Stock'] = modbusclient.read_holding_registers( 3, 1, unit=0x01).registers[0] messageToSend[ 'HPE Stock'] = modbusclient.read_holding_registers( 4, 1, unit=0x01).registers[0] IoTmessageToSend = IoTHubMessage( bytearray(json.dumps(messageToSend), 'utf8')) hub_manager.forward_event_to_output("output1", IoTmessageToSend, messageCounter) messageCounter += 1 except Exception: errorMessage = "{\"error\":\"" + str(sys.exc_info()[0]) + "\"}" IoTmessageToSend = IoTHubMessage( bytearray(errorMessage, 'utf8')) hub_manager.forward_event_to_output("output1", IoTmessageToSend, messageCounter) messageCounter += 1 modbusclient.close() except IoTHubError as iothub_error: print("Unexpected error %s from IoTHub" % iothub_error) return except KeyboardInterrupt: print("IoTHubModuleClient sample stopped")
def send(self, message): try: iothub_message = IoTHubMessage(message) self.messages_sent += 1 iothub_message.message_id = "message_%d" % self.messages_sent self.get_client().send_event_async(iothub_message, self.send_confirmation_callback, self.messages_sent) except IoTHubError as iothub_error: sys.stderr.write("IoTHub error: \"%s\"\n" % iothub_error) self.client = None
def iothub_client_telemetry_sample_run(events, bike_ids, rack_ids): try: client = iothub_client_init() print ( "IoT Hub device sending periodic messages, press Ctrl-C to exit" ) #while True: for event in events: # Build the message with simulated telemetry values. #temperature = TEMPERATURE + (random.random() * 15) #humidity = HUMIDITY + (random.random() * 20) #msg_txt_formatted = MSG_TXT % (temperature, humidity) # message = IoTHubMessage(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. # prop_map = message.properties() # if temperature > 30: # prop_map.add("temperatureAlert", "true") # else: # prop_map.add("temperatureAlert", "false") # # Send the message. # print( "Sending message: %s" % message.get_string() ) # client.send_event_async(message, send_confirmation_callback, None) # time.sleep(1) timestamp = event.time.strftime("%y-%m-%d %H:%M:%S") if event.type == Event.EventType.TAKE: rack_number = event.src else: rack_number = event.dest bike_number = event.bike msg_txt_formatted = MSG_TXT % (timestamp, rack_number, bike_number, event.type) message = IoTHubMessage(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. # prop_map = message.properties() # if temperature > 30: # prop_map.add("temperatureAlert", "true") # else: # prop_map.add("temperatureAlert", "false") # Send the message. print( "Sending message: %s" % message.get_string() ) client.send_event_async(message, send_confirmation_callback, None) time.sleep(1) except IoTHubError as iothub_error: print ( "Unexpected error %s from IoTHub" % iothub_error ) return except KeyboardInterrupt: print ( "IoTHubClient sample stopped" )
def send_event(self, event, properties, send_context): if not isinstance(event, IoTHubMessage): event = IoTHubMessage(bytearray(event, 'utf8')) if len(properties) > 0: prop_map = event.properties() for key in properties: prop_map.add_or_update(key, properties[key]) self.client.send_event_async( event, send_confirmation_callback, send_context)
def process_elevacion_type(message_lora, hubManager): global TwinPayload valid_data = False json_obj = {} # save deveui deveui = message_lora['deveui'] # if data isnt empty, then decode it, else create empty json for data. data_decoded = {} # check for existing data if message_lora['data']: # decode data data_decoded = base64.b64decode(message_lora['data']) data_decoded = data_decoded.decode('unicode_escape') else: print("Invalid message data.") # save decoded data as json object data_decoded_json = json.loads(str(data_decoded)) json_obj['time'] = message_lora['time'] # send message for first id if ('id' in TwinPayload['desired']['devices'][deveui] and ("stateA" in data_decoded_json)): valid_data = True json_obj['estado'] = data_decoded_json['stateA'] json_obj['id'] = TwinPayload['desired']['devices'][deveui]['id'] json_obj_ = check_prev(json_obj) # check previous would return None if the message is the same if json_obj_ != None: json_obj_.pop('time', 0) json_obj_['Fecha'] = time_parser(message_lora)[0] json_obj_['Hora'] = time_parser(message_lora)[1] new_message = json.dumps(json_obj_) new_message = IoTHubMessage(new_message) hubManager.forward_event_to_output("output1", new_message, 0) # send separate message for same-deveui/different-id scenario if (("id2" in TwinPayload['desired']['devices'][deveui]) and ("stateB" in data_decoded_json)): valid_data = True json_obj['estado'] = data_decoded_json['stateB'] json_obj['id'] = TwinPayload['desired']['devices'][deveui]['id2'] json_obj_ = check_prev(json_obj) # check previous would return None if the message is the same if json_obj_ != None: json_obj_.pop('time', 0) json_obj_['Fecha'] = time_parser(message_lora)[0] json_obj_['Hora'] = time_parser(message_lora)[1] new_message = json.dumps(json_obj_) new_message = IoTHubMessage(new_message) hubManager.forward_event_to_output("output1", new_message, 0) if not valid_data: print("Invalid data format.")
def onHttpRequestSave(): #request.form['rawData'] # Data Sample {'temperature': 'nan', 'humidity': 'nan'} resp = request.get_json() resp['EventTime'] = datetime.datetime.now().strftime("%I:%M%p %B %d, %Y") payload = json.dumps(resp) data_t = strftime("%Y-%m-%dT%H:%M:%S+00:00", gmtime()) #payload = '{ "data": '+payload+', "deviceId": "engine", "time": "'+data_t+'" }' #payload = payload print(payload, file=sys.stderr) print(type(payload),file=sys.stderr) headers = { 'Content-Type': "application/json", 'User-Agent': "PostmanRuntime/7.11.0", 'Accept': "*/*", 'Cache-Control': "no-cache", 'Postman-Token': "0fa806d0-eee9-4960-8984-941eb1d8a340,0f174457-1072-4871-a853-2c2c8224f3f8", 'Host': "us-central1-alwaystuned2019.cloudfunctions.net", 'accept-encoding': "gzip, deflate", 'content-length': "405", 'Connection': "keep-alive", 'cache-control': "no-cache" } response = requests.request("POST", url, data=payload, headers=headers) print(response.text, file=sys.stderr) try: client = iothub_client_init() print ( "IoT Hub device sending periodic messages, press Ctrl-C to exit", file=sys.stderr) message = IoTHubMessage(payload) # Add a custom application property to the message. # An IoT hub can filter on these properties without access to the message body. prop_map = message.properties() # Send the message. print( "Sending message: %s" % message.get_string() , file=sys.stderr) client.send_event_async(message, send_confirmation_callback, None) except IoTHubError as iothub_error: print ( "Unexpected error %s from IoTHub" % iothub_error , file=sys.stderr) return except KeyboardInterrupt: print ( "IoTHubClient sample stopped" , file=sys.stderr) print(resp, file=sys.stderr) return saveData()
def iothub_client_sample_run(): try: client = iothub_client_init() if client.protocol == IoTHubTransportProvider.MQTT: print ( "IoTHubClient is reporting state" ) reported_state = "{\"newState\":\"standBy\"}" client.send_reported_state(reported_state, len(reported_state), send_reported_state_callback, SEND_REPORTED_STATE_CONTEXT) while True: # send a few messages every minute print ( "IoTHubClient sending %d messages" % MESSAGE_COUNT ) for message_counter in range(0, MESSAGE_COUNT): temperature = MIN_TEMPERATURE + (random.random() * 10) humidity = MIN_HUMIDITY + (random.random() * 20) msg_txt_formatted = MSG_TXT % ( AVG_WIND_SPEED + (random.random() * 4 + 2), temperature, humidity) # messages can be encoded as string or bytearray if (message_counter & 1) == 1: message = IoTHubMessage(bytearray(msg_txt_formatted, 'utf8')) else: message = IoTHubMessage(msg_txt_formatted) # optional: assign ids message.message_id = "message_%d" % message_counter message.correlation_id = "correlation_%d" % message_counter # optional: assign properties prop_map = message.properties() prop_map.add("temperatureAlert", 'true' if temperature > 28 else 'false') client.send_event_async(message, send_confirmation_callback, message_counter) print ( "IoTHubClient.send_event_async accepted message [%d] for transmission to IoT Hub." % message_counter ) # Wait for Commands or exit print ( "IoTHubClient waiting for commands, press Ctrl-C to exit" ) status_counter = 0 while status_counter <= MESSAGE_COUNT: status = client.get_send_status() print ( "Send status: %s" % status ) time.sleep(10) status_counter += 1 except IoTHubError as iothub_error: print ( "Unexpected error %s from IoTHub" % iothub_error ) return except KeyboardInterrupt: print ( "IoTHubClient sample stopped" ) print_last_message_time(client)
def sendStringToIOTHub(self, messageString): message = IoTHubMessage(messageString) message.message_id = "message_%d" % self.MESSAGE_COUNT message.correlation_id = "correlation_%d" % self.MESSAGE_COUNT self.client.send_event_async(message, self.sendConfirmationCallback, self.MESSAGE_COUNT) status = self.client.get_send_status() print ( "Send status: %s" % status ) self.MESSAGE_COUNT += 1
def report_output(frame, res_json): json_string = json.dumps(res_json) print("Classification output: " + json_string) if enable_cloud_output: message = IoTHubMessage(json_string) print("Sending message: %s" % message.get_string()) client.send_event_async(message, send_confirmation_callback, None) if enable_local_jpeg_output: now = datetime.datetime.now() date_prefix = str(now).replace(" ", "_") retval = cv2.imwrite( os.path.join(local_output_dir, date_prefix + ".jpeg"), frame)
def send_to_Hub_callback(strMessage): message = IoTHubMessage(bytearray(strMessage, 'utf8')) # Setting these properties to allow routing of messages to other endpoints set_content_result = message.set_content_encoding_system_property("utf-8") set_content_type_result = message.set_content_type_system_property("application/json") if set_content_result != 0: print("set_content_encoding_system_property FAILED") if set_content_type_result != 0: print("set_content_type_system_property FAILED") hubManager.send_event_to_output("output1", message, 0)
def composeStartMessage(): msg_unformatted = {"startTime": time.asctime(time.localtime(time.time()))} msg_txt_formatted = json.dumps(msg_unformatted) message = IoTHubMessage(msg_txt_formatted) # optional: assign ids message.message_id = "message_%d" % MESSAGE_COUNT message.correlation_id = "correlation_%d" % MESSAGE_COUNT # optional: assign properties prop_map = message.properties() prop_map.add("startupMessage", "true") prop_map.add("telemetry", "false") return message
def read_sensor_data(mqttClient, sensor, pin, iccid, random): '''Loop that send the data to AWS''' while True: # Send payload if random == 't': message = IoTHubMessage(json.dumps(get_payload_random(iccid))) else: message = IoTHubMessage(json.dumps(get_payload(sensor, pin, iccid))) mqttClient.send_event_async(message, send_confirmation_callback, None) # delay 30 seconds before running next time.sleep(30)
def read_and_send_light(client): light_sensor = LightSensor() lux = light_sensor.get_lux() now = time.time() msg = MESSAGE_FORMAT_LIGHT % (DEVICE_ID, lux, now) print(msg) message = IoTHubMessage(msg) # optional: assign ids message.message_id = "message_%d" % MESSAGE_COUNT message.correlation_id = "correlation_%d" % MESSAGE_COUNT client.send_event_async(message, send_confirmation_callback, MESSAGE_COUNT)
def iothub_client_post_message(file_name): global ISSENDING ISSENDING = True while ISSENDING: message_client = iothub_client_init(MESSAGE_PROTOCOL) msg_txt_formatted = MSG_TXT % (DEVICEID, PROJECTNAME, file_name) message = IoTHubMessage(msg_txt_formatted) # Send the message. print("Sending message: %s" % message.get_string()) message_client.send_event_async(message, send_confirmation_callback, None) time.sleep(7)
def SendData(self, msg): global MESSAGE_COUNT record_time_local = datetime.now().strftime('%Y-%m-%dT%H:%M:%S.%f') print("\nsending message %d at %s" % (MESSAGE_COUNT, record_time_local)) print(msg) message = IoTHubMessage(msg) message.message_id = "message_%d" % MESSAGE_COUNT message.correlation_id = "correlation_%d" % MESSAGE_COUNT self.client.send_event_async("output1", message, send_confirmation_callback, 0) print("finished sending message %d\n" % (MESSAGE_COUNT))
def iothub_client_sample_run(): global gMQTTClient try: iotHubStopWatch = StopWatch(AZURE_REPORT_TIME) iotHubStopWatch.reset() client = iothub_client_init() if client.protocol == IoTHubTransportProvider.MQTT: print ( "IoTHubClient is reporting state" ) reported_state = "{\"newState\":\"standBy\"}" client.send_reported_state(reported_state, len(reported_state), send_reported_state_callback, SEND_REPORTED_STATE_CONTEXT) count = 1 while True: if (True == iotHubStopWatch.isExpired()): global gSendMessage if gSendMessage: message = IoTHubMessage("JimsFridgeStatus") message.message_id = "message_%d" % count message.correlation_id = "correlation_%d" % count prop_map = message.properties() prop_map.add("FreezerDoor", str(gFreezerDoor)) prop_map.add("FreezerTemp", str(gFreezerTemp)) prop_map.add("FridgeDoor", str(gFridgeDoor)) prop_map.add("FridgeTemp", str(gFridgeTemp)) prop_map.add("BoredTime", str(gBoredTime)) prop_map.add("LockoutTime", str(gLockoutTime)) prop_map.add("DoorTime", str(gDoorTime)) prop_map.add("LastTweet", urllib.quote(gLastTweet)) prop_map.add("WebTweet", gWebTweet) client.send_event_async(message, send_confirmation_callback, count) count = count + 1 status = client.get_send_status() iotHubStopWatch.reset() gMQTTClient.loop() time.sleep(0.01) pass except IoTHubError as iothub_error: print ( "Unexpected error %s from IoTHub" % iothub_error ) return except KeyboardInterrupt: print ( "IoTHubClient sample stopped" ) print_last_message_time(client)
def iothub_client_run(): try: client = iothub_client_init() if client.protocol == IoTHubTransportProvider.MQTT: print ( "IoTHubClient is reporting state" ) reported_state = "{\"newState\":\"standBy\"}" client.send_reported_state(reported_state, len(reported_state), send_reported_state_callback, SEND_REPORTED_STATE_CONTEXT) telemetry.send_telemetry_data(parse_iot_hub_name(), EVENT_SUCCESS, "IoT hub connection is established") while True: global MESSAGE_COUNT,MESSAGE_SWITCH if MESSAGE_SWITCH: #------------------------------------------------------------------------------------------- # This for loop reads the live data from the weather station and converts some of the data. # ptrraw is the WS pointer to circluar log buffer offset (16 bytes) # ptrhex ptr in Hex little endian # Convert to correct Relative Pressure HPA for location by adding 9.6 # Convert MPS to KPH # Error Handling: # Check for lost connection or null data. If found break from loop and do not send message #------------------------------------------------------------------------------------------- for data, ptr, logged in ws.live_data(): record_time_local = datetime.now().strftime('%Y-%m-%dT%H:%M:%S.%f') print("\n") print(record_time_local) ws_status = data['status'] ws_conn = data['status']['lost_connection'] # Check for lost connection if ws_conn == True: print("Lost Connection to Weather Station") break # Check for Null Data if ws_conn == None: print("No Data Returned From Weather Station") break # if connection OK process the data ptrraw = ptr ptrhex = "%04x" % ptr record_time_utc = data['idx'].strftime('%Y-%m-%d %H:%M:%S') hum_out = data['hum_out'] temp_out = data['temp_out'] hum_in = data['hum_in'] temp_in = data['temp_in'] abs_pres = data['abs_pressure']+9.6 wind_gust = data['wind_gust']*3.6 wind_avg = data['wind_ave']*3.6 wind_dir = data['wind_dir'] wind_pos = wind_direction(wind_dir) rain = data['rain'] msg_txt_formatted = MSG_TXT % ( DeviceID, record_time_local, hum_out, temp_out, hum_in, temp_in, abs_pres, wind_gust, wind_avg, wind_dir, wind_pos, rain) break if ws_conn == False: print ( "IoTHubClient sending %d messages" % MESSAGE_COUNT ) message = IoTHubMessage(msg_txt_formatted) # optional: assign ids message.message_id = "message_%d" % MESSAGE_COUNT message.correlation_id = "correlation_%d" % MESSAGE_COUNT # optional: assign properties prop_map = message.properties() prop_map.add("temperatureAlert", "true" if temp_out > TEMPERATURE_ALERT else "false") client.send_event_async(message, send_confirmation_callback, MESSAGE_COUNT) print ( "IoTHubClient.send_event_async accepted message [%d] for transmission to IoT Hub." % MESSAGE_COUNT ) status = client.get_send_status() print ( "Send status: %s" % status ) MESSAGE_COUNT += 1 time.sleep(config.MESSAGE_TIMESPAN / 1000.0) except IoTHubError as iothub_error: print ( "Unexpected error %s from IoTHub" % iothub_error ) telemetry.send_telemetry_data(parse_iot_hub_name(), EVENT_FAILED, "Unexpected error %s from IoTHub" % iothub_error) return except KeyboardInterrupt: print ( "IoTHubClient stopped" ) print_last_message_time(client)
def iothub_client_shared_transport_sample_run(): try: # create transport to share transport = IoTHubTransport(PROTOCOL, IOTHUBNAME, IOTHUBSUFFIX) client1 = iothub_client_init(transport, DEVICE_NAME1, DEVICE_KEY1) client1.set_message_callback(receive_message_callback1, RECEIVE_CONTEXT) client2 = iothub_client_init(transport, DEVICE_NAME2, DEVICE_KEY2) client2.set_message_callback(receive_message_callback2, RECEIVE_CONTEXT) print ( "IoTHubClient has been initialized" ) while True: # send a few messages every minute print ( "IoTHubClient sending %d messages" % MESSAGE_COUNT ) for message_counter in range(0, MESSAGE_COUNT): temperature = MIN_TEMPERATURE + (random.random() * 10) humidity = MIN_HUMIDITY + (random.random() * 20) msg_txt_formatted = MSG_TXT % ( AVG_WIND_SPEED + (random.random() * 4 + 2), temperature, humidity) # messages can be encoded as string or bytearray if (message_counter & 1) == 1: message = IoTHubMessage(bytearray(msg_txt_formatted, 'utf8')) else: message = IoTHubMessage(msg_txt_formatted) # optional: assign ids message.message_id = "message_%d" % message_counter message.correlation_id = "correlation_%d" % message_counter # optional: assign properties prop_map = message.properties() prop_map.add("temperatureAlert", 'true' if temperature > 28 else 'false') if (message_counter % 2) == 0: client1.send_event_async(message, send_confirmation_callback1, message_counter) else: client2.send_event_async(message, send_confirmation_callback2, message_counter) print ( "IoTHubClient.send_event_async accepted message [%d] for transmission to IoT Hub." % message_counter ) # Wait for Commands or exit print ( "IoTHubClient waiting for commands, press Ctrl-C to exit" ) status_counter = 0 while status_counter < MESSAGE_COUNT: status1 = client1.get_send_status() print ( "Send status client1: %s" % status1 ) status2 = client2.get_send_status() print ( "Send status client2: %s" % status2 ) time.sleep(10) status_counter += 1 except IoTHubError as iothub_error: print ( "Unexpected error %s from IoTHub" % iothub_error ) return except KeyboardInterrupt: print ( "IoTHubClient sample stopped" ) print_last_message_time(client1) print_last_message_time(client2)