def iothub_try(self, json, connection): try: client = self.iothub_client_init(connection) message_counter = 0 msg_txt_formatted = json # messages can be encoded as string or bytearray #print ( msg_txt_formatted ) 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 client.send_event_async(message, send_confirmation_callback, message_counter) status = client.get_send_status() print("Send status: %s" % status) time.sleep(5) message_counter += 1 except IoTHubError as iothub_error: print("Unexpected error %s from IoTHub" % iothub_error) return except KeyboardInterrupt: print("IoTHubClient sample stopped")
def safebikely_run(): try: logger.info("Starting main thread") client = iothub_client_init() while True: global MESSAGE_STATUS, MESSAGE_LASTWILL if MESSAGE_STATUS: msg_formatted = MSG_STATUS % (myID,OKAY) message = IoTHubMessage(msg_formatted) logger.info ("Sending msg: %s", msg_formatted) client.send_event_async(message, send_confirmation_callback, MESSAGE_COUNT) MESSAGE_STATUS = False if MESSAGE_LASTWILL: msg_formatted = MSG_LASTWILL % myID message = IoTHubMessage(msg_formatted) message.message_id = "message_%d" % MESSAGE_COUNT message.correlation_id = "correlation_%d" % MESSAGE_COUNT logger.info("Sending LastWill message") client.send_event_async(message, send_confirmation_callback, MESSAGE_COUNT) MESSAGE_LASTWILL = False time.sleep(0.1) except KeyboardInterrupt as error: logger.debug("Error %s",error) print_last_message_time(client) except Exception as error: logger.debug("Error %s", error)
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 iothub_client_telemetry_sample_run(): try: client = iothub_client_init() print("IoT Hub device sending periodic messages, press Ctrl-C to exit") count = 0 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) ### Optional message.message_id = "message_%d" % count message.correlation_id = "correlation_%d" % count # 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 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 = SenseHat() print 'PI SenseHat Object Created' else: # sensor = BME280(address = config.I2C_ADDRESS) 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.get_temperature() humidity = sensor.get_humidity() msg_txt_formatted = MSG_TXT % (temperature, humidity) 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 main(protocol): try: print ( "\nPython %s\n" % sys.version ) print ( "IoT Hub Client for Python" ) hub_manager = HubManager(protocol) device_client = iothub_client_init() print ( "IoTHubClient sending %d messages" % MESSAGE_COUNT ) message = IoTHubMessage("mridu test message from module!!!!") message_counter = 0 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", 'false') device_client.send_event(message, properties=prop_map, send_context=message_counter) 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: 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") message_counter = 0 while True: msg_txt_formatted = "Event!" # 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() generate_message(prop_map, generate_ticket_id(), datetime.now()) 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) message_counter += 1 sleep(np.random.randint(10)) except IoTHubError as iothub_error: print("Unexpected error %s from IoTHub" % iothub_error) return except KeyboardInterrupt: print("IoTHubClient sample stopped")
def iothub_client_detection_run(json_object): 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, ) message = IoTHubMessage(json_object) # optional: assign ids message.message_id = "message_%d" % 1 message.correlation_id = "correlation_%d" % 1 client.send_event_async(message, send_confirmation_callback, 1) print("IoTHubClient.send_event_async accepted message [%d] \ for transmission to IoT Hub." % 1) # Wait for Commands or exit # print ("IoTHubClient waiting for commands, press Ctrl-C to exit") 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 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 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 send_to_iot(self, data, did, connection): try: client = self.iothub_client_init(connection) message_counter = 0 msg_txt_formatted = json.dumps(data) print ( msg_txt_formatted ) if (message_counter & 1) == 1: message = IoTHubMessage(bytearray(msg_txt_formatted, 'utf8')) client.send_event_async(message, send_confirmation_callback, message_counter) time.sleep(2) else: message = IoTHubMessage(msg_txt_formatted) message.message_id = "message_%d" % message_counter message.correlation_id = "correlation_%d" % message_counter client.send_event_async(message, send_confirmation_callback, message_counter) time.sleep(2) except IoTHubError as iothub_error: print ( "Unexpected error %s from IoTHub" % iothub_error ) return except KeyboardInterrupt: print ( "IoTHubClient sample stopped" )
def iothub_client(): try: #Initialice Client client = iothub_client_init() print("IoT Device Simulator, press Ctrl-C to exit") #Specifies message format and values msg_txt_formatted = MSG_TXT % INTERFACE_PARAM_A message_counter = 0 inp = 0 while inp != 4: print("Press 1 to send a message to IOT Hub (Simulated message") print("Press 2 to send a picture to IOT Hub (Simulated message") print("Press 4 to EXIT") # 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_text = "PropMsg_%d" % message_counter prop_map.add("Property", prop_text) inp = int(input()) if inp == 1: #Sends a message to the Hub, reveives confirmation callback, adds counter 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) if inp == 2: #Sends a file to Azure Storage Blob filename = "hello.jpg" content1 = open(filename, "rb") content = content1.read() #Send and shows confirmation client.upload_blob_async(filename, content, len(content), blob_upload_conf_callback, 1001) #status = client.get_send_status() #print ( "Send status: %s" % status ) message_counter += 1 if inp == 4: break 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: 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_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 ncd_send_message(msg, client): print(msg) message = IoTHubMessage(msg) message.type = "Telemetry" message.message_id = "message_0" message.correlation_id = "correlation_0" # # optional: assign properties prop_map = message.properties() client.send_event_async(message, send_confirmation_callback, 0) print ( "IoTHubClient.send_event_async accepted message for transmission to IoT Hub.")
def iothub_client_sample_run(msg): 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) x = True while x == True: # send a few messages every minute print("IoTHubClient sending %d messages" % MESSAGE_COUNT) for message_counter in range(0, MESSAGE_COUNT): msg_txt_formatted = msg print "7777777777777777777777777777777777777777777777777777777" print msg_txt_formatted print "8888888888888888888888888888888888888888888888888888888" # 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, 1) print( "IoTHubClient.send_event_async accepted message [%d] for transmission to IoT Hub." % message_counter) print("IoTHubClient waiting for commands, press Ctrl-C to exit") status = client.get_send_status() x = False status_counter = 0 while status_counter <= 0: status = client.get_send_status() print("Send status: %s" % status) time.sleep(1) status_counter += 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: 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 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_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 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(): 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) sensor = ping() 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) distance = sensor.get_distance() msg_txt_formatted = MSG_TXT % (distance) 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) 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 composeMessage(sensors, relays): msg_txt_formatted = readDeviceData(sensors, relays, remoteRelay, logger) 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("statusMessage", "true") prop_map.add("telemetry", "true") return message
def iothub_client_sample_x509_run(): try: client = iothub_client_init() while True: # send a few messages every minute print("IoTHubClient sending %d messages" % MESSAGE_COUNT) for message_counter in range(0, MESSAGE_COUNT): msg_txt_formatted = MSG_TXT % (AVG_WIND_SPEED + (random.random() * 4 + 2)) # 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_text = "PropMsg_%d" % message_counter prop_map.add("Property", prop_text) 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 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_telemetry_sample_run(): #Main funktion skickar meddelanden try: client = iothub_client_init() print("IoT Device Simulator, press Ctrl-C to exit") message_counter = 0 inp = 0 while inp != 4: print("Press 1 to send a mesage to IOT Hub (Simulated message") msg_txt_formatted = MSG_TXT % (AVG_WIND_SPEED + (random.random() * 4 + 2)) # 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_text = "PropMsg_%d" % message_counter prop_map.add("Property", prop_text) inp = int(input()) if inp == 1: 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) #status = client.get_send_status() #print ( "Send status: %s" % status ) #time.sleep(5) # 5 sekunder delay i loopen #status = client.get_send_status() #print ( "Send status: %s" % status ) message_counter += 1 #break # Ta bort för att fortsätta i en loop except IoTHubError as iothub_error: print("Unexpected error %s from IoTHub" % iothub_error) return except KeyboardInterrupt: print("IoTHubClient sample stopped")
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) while True: global MESSAGE_COUNT, MESSAGE_SWITCH if MESSAGE_SWITCH: # send a few messages every minute print("IoTHubClient sending %d messages" % MESSAGE_COUNT) #value = random.uniform(0,100) value = getSensor.read_ad_channel() value = getSensor.dataprocessing(value) msg_txt_formatted = "{\"Device\":\"Raspberry_VT\",\"Humidity\":\"%d\"}" % value 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("Alert", "true" if value < ALERTVALUE 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(MESSAGE_TIMESPAN / 1000.0) except IoTHubError as iothub_error: print("Unexpected error %s from IoTHub" % iothub_error) return except KeyboardInterrupt: print("IoTHubClient for VT stopped") print_last_message_time(client)
def iothub_client_telemetry_sample_run(): try: client = iothub_client_init() print("IoT Hub device sending periodic messages, press Ctrl-C to exit") message_counter = 0 while True: random_id = random.randint(1, 4) random_capacity = random.random() date = "\"" + datetime.datetime.now().strftime( '%Y-%m-%d %H:%M:%S') + "\"" msg_txt_formatted = "{\"capacidad\":" + str( random_capacity ) + ", \"fecha\": " + date + ", \"id_bote\":" + str( random_id) + "}" print(msg_txt_formatted) 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_text = "PropMsg_%d" % message_counter prop_map.add("Property", prop_text) 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) status = client.get_send_status() print("Send status: %s" % status) time.sleep(30) status = client.get_send_status() print("Send status: %s" % status) message_counter += 1 except IoTHubError as iothub_error: print("Unexpected error %s from IoTHub" % iothub_error) return except KeyboardInterrupt: print("IoTHubClient sample stopped")
def iothub_try(self): try: client = self.iothub_client_init() message_counter = 0 while True: is_update = self.check_for_updates() if is_update == True: print("TTRRUUEE") j = { "Total Cars: ": self.TOTAL_TARGETS.__str__(), "Average Speed: ": self.MEAN_SPEED.__str__(), "Max Speed: ": self.MAX_SPEED.__str__(), "Min Speed: ": self.MIN_SPEED.__str__(), "Raw Data: ": self.DATA.__str__() } msg_txt_formatted = json.dumps(j) # messages can be encoded as string or bytearray print(msg_txt_formatted) if (message_counter & 1) == 1: message = IoTHubMessage( bytearray(msg_txt_formatted, 'utf8')) client.send_event_async(message, send_confirmation_callback, message_counter) else: message = IoTHubMessage(msg_txt_formatted) message.message_id = "message_%d" % message_counter message.correlation_id = "correlation_%d" % message_counter client.send_event_async(message, send_confirmation_callback, message_counter) is_update = False else: status = client.get_send_status() print("Send status: %s" % status) time.sleep(10) message_counter += 1 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") message_counter = 1 while True: msg_txt_formatted = MSG_TXT % (message_counter, AVG_TEMP + (random.random() * 15), AVG_HUM + (random.random() * 20)) # 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_text = "PropMsg_%d" % message_counter prop_map.add("Property", prop_text) 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) status = client.get_send_status() print("Send status: %s" % status) time.sleep(0.5) status = client.get_send_status() print("Send status: %s" % status) message_counter += 1 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\n") message_counter = 0 filename = 'data{0}.csv' while True: print(filename.format(0,)) torque, displacement, velocity, acceleration = get_values_from_file(filename=filename.format(0,)) msg = MSG_TXT % (str(torque), str(displacement), str(velocity), str(acceleration)) b_array = bytearray(msg, 'utf8') message = IoTHubMessage(b_array) # optional: assign ids message.message_id = "message_%d" % message_counter message.correlation_id = "correlation_%d" % message_counter # optional: assign properties #prop_text = "bytearray_%d" % message_counter #prop_map = message.properties() #prop_map.add("Property", prop_text) 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) status = client.get_send_status() print("Send status: %s" % status) time.sleep(2) status = client.get_send_status() print("Send status: %s" % status) message_counter += 1 print() 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: 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: global MESSAGE_COUNT # send a few messages every minute print("IoTHubClient sending %d messages" % MESSAGE_COUNT) msg_txt_formatted = str(power_readings) 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("telemetryType", "powerGeneration") 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 # for some reason without this sleep message wouldn't be delivered time.sleep(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 iothub_client_telemetry_sample_run(): try: client = iothub_client_init() print("IoT Hub device sending periodic messages, press Ctrl-C to exit") message_counter = 0 while True: msg_txt_formatted = json.dumps({ "ticketId": str(uuid.uuid4()), "entryTime": strftime("%Y-%m-%d %H:%M:%S", gmtime()) }) # 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_text = "PropMsg_%d" % message_counter prop_map.add("Property", prop_text) 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) status = client.get_send_status() print("Send status: %s" % status) time.sleep(30) status = client.get_send_status() print("Send status: %s" % status) message_counter += 1 except IoTHubError as iothub_error: print("Unexpected error %s from IoTHub" % iothub_error) return except KeyboardInterrupt: print("IoTHubClient sample stopped")
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)
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)