class HubManager(object): def __init__(self, connection_string, protocol=IoTHubTransportProvider.MQTT): self.client_protocol = protocol self.client = IoTHubClient(connection_string, protocol) if protocol == IoTHubTransportProvider.HTTP: self.client.set_option("timeout", TIMEOUT) self.client.set_option("MinimumPollingTime", MINIMUM_POLLING_TIME) # set the time until a message times out self.client.set_option("messageTimeout", 100000) def send_event(self, event, properties, send_context): if not isinstance(event, IoTHubMessage): event = IoTHubMessage(bytearray(event, 'utf8')) event.set_content_encoding_system_property('utf-8') event.set_content_type_system_property('application/json') event.properties().add('deviceId', 'RaspberryPi3') 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 send_reported_state(self, reported_state, size, user_context): self.client.send_reported_state(reported_state, size, send_reported_state_callback, user_context)
class Sender(object): def __init__(self, connection_string, certificate_path=False, protocol=PROTOCOL): self.client_protocol = protocol self.client = IoTHubClient(connection_string, protocol) # set the time until a message times out self.client.set_option('messageTimeout', MESSAGE_TIMEOUT) # some embedded platforms need certificate information if certificate_path: self.set_certificates(certificate_path) def set_certificates(self, certificate_path): file = open(certificate_path, 'r') try: self.client.set_option('TrustedCerts', file.read()) print('IoT Edge TrustedCerts set successfully') except IoTHubClientError as iothub_client_error: print('Setting IoT Edge TrustedCerts failed (%s)' % iothub_client_error) file.close() 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)
class IoTHubDevice: def __init__(self, iothub_name, device_id, device_key, suffix='.azure-devices.net'): self.device_id = device_id device_connection_string = 'HostName={0}{1};DeviceId={2};SharedAccessKey={3}'.format( iothub_name, suffix, device_id, device_key ) self.client = IoTHubClient(device_connection_string, IoTHubTransportProvider.MQTT) # HTTP, AMQP, MQTT ? def send_message(self, message): m = IoTHubMessage(message) # string or bytearray self.client.send_event_async(m, IoTHubDevice.__dummy_send_confirmation_callback, 0) def send_reported_state(self, state, send_reported_state_callback = None, user_context = None): if send_reported_state_callback is None: send_reported_state_callback = IoTHubDevice.__dummy_send_reported_state_callback state_json = json.dumps(state) self.client.send_reported_state(state_json, len(state_json), send_reported_state_callback, user_context) @staticmethod def __dummy_send_confirmation_callback(message, result, user_context): pass #print(result) @staticmethod def __dummy_send_reported_state_callback(status_code, user_context): pass
def iothub_client_sample_run(): try: # prepare iothub client client = IoTHubClient(CONNECTION_STRING, IoTHubTransportProvider.MQTT) # to enable MQTT logging set to 1 client.set_option("logtrace", 0) client.set_message_callback(receive_message_callback, RECEIVE_CONTEXT) while True: # send a few messages every minute print ( "IoTHubClient sending message" ) msg_txt_formatted = MSG_TXT % "This is a test" message = IoTHubMessage(msg_txt_formatted) client.send_event_async(message, send_confirmation_callback, SEND_CONTEXT) print ( "IoTHubClient.send_event_async accepted message for transmission to IoT Hub." ) time.sleep(SLEEP_TIME) except IoTHubError as iothub_error: print ( "Unexpected error %s from IoTHub" % iothub_error ) return except KeyboardInterrupt: print ( "IoTHubClient sample stopped" )
class HubManager(object): def __init__( self, connection_string): self.client_protocol = PROTOCOL self.client = IoTHubClient(connection_string, PROTOCOL) # set the time until a message times out self.client.set_option("messageTimeout", MESSAGE_TIMEOUT) # some embedded platforms need certificate information self.set_certificates() def set_certificates(self): isWindows = sys.platform.lower() in ['windows', 'win32'] if not isWindows: CERT_FILE = os.environ['EdgeModuleCACertificateFile'] print("Adding TrustedCerts from: {0}".format(CERT_FILE)) # this brings in x509 privateKey and certificate file = open(CERT_FILE) try: self.client.set_option("TrustedCerts", file.read()) print ( "set_option TrustedCerts successful" ) except IoTHubClientError as iothub_client_error: print ( "set_option TrustedCerts failed (%s)" % iothub_client_error ) file.close() # Forwards the message received onto the next stage in the process. def send_analysis_to_output(self, msg): msg_txt = json.dumps(msg) hubmessage = IoTHubMessage(bytearray(msg_txt, 'utf8')) self.client.send_event_async("output1", hubmessage, device_message_callback, 0)
def main(): while True: client = IoTHubClient(CONNECTION_STRING, PROTOCOL) payload = json.dumps(get_sys_params(CPUDELAYSAMPLE)) message = IoTHubMessage(payload) client.send_event_async(message, send_confirmation_callback, None) logger.debug("Msg sent") time.sleep(GLOBALDELAYSAMPLE)
class IoTHubDevice: def __init__(self, iothub_name, device_id, device_key, suffix='.azure-devices.net'): self.iothub_name = iothub_name self.device_id = device_id self.device_key = device_key self.policy_name = 'device' self.suffix = suffix device_connection_string = self.__get_device_connection_string() self.client = IoTHubClient( device_connection_string, IoTHubTransportProvider.MQTT) # HTTP, AMQP, MQTT ? def send_message(self, message): m = IoTHubMessage(message) # string or bytearray self.client.send_event_async( m, IoTHubDevice.__dummy_send_confirmation_callback, 0) def send_reported_state(self, state): state_json = json.dumps(state) self.client.send_reported_state( state_json, len(state_json), IoTHubDevice.__dummy_send_reported_state_callback, 0) def __get_device_connection_string(self, expiry=3600): ttl = time() + expiry uri = '{0}{1}/devices/{2}'.format(self.iothub_name, self.suffix, self.device_id) sign_key = "%s\n%d" % ((quote_plus(uri)), int(ttl)) signature = b64encode( HMAC(b64decode(self.device_key), sign_key.encode('utf-8'), sha256).digest()) rawtoken = {'sr': uri, 'sig': signature, 'se': str(int(ttl))} if self.policy_name is not None: rawtoken['skn'] = self.policy_name sas = 'SharedAccessSignature ' + urlencode(rawtoken) return 'HostName={0}{1};DeviceId={2};SharedAccessSignature={3}'.format( self.iothub_name, self.suffix, self.device_id, sas) @staticmethod def __dummy_send_confirmation_callback(message, result, user_context): pass # print(result) @staticmethod def __dummy_send_reported_state_callback(status_code, user_context): pass
def send_data(message_data, asset_name): print("data to be send") print(message_data) my_json_string = json.dumps(message_data) print(my_json_string) message = str(my_json_string).encode() print("encoded data is {}".format(message)) client = IoTHubClient(CONNECTION_STRING, PROTOCOL) message = IoTHubMessage(message) client.send_event_async(message, send_confirmation_callback, asset_name) print("Message transmitted to IoT Hub") time.sleep(3)
def iothub_client_post_message(): global ISSENDING ISSENDING = True while ISSENDING: client = IoTHubClient(HUB_CONNECTION_STRING, MESSAGE_PROTOCOL) print("IoT Hub device sending periodic messages, press Ctrl-C to exit") msg_txt_formatted = MSG_TXT % (DEVICEID, PROJECTNAME, FILENAME) 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(7)
class HubManager(object): def __init__(self, connection_string): self.client_protocol = PROTOCOL self.client = IoTHubClient(connection_string, PROTOCOL) self.conn = pymssql.connect('sql:1433', 'SA', 'Strong!Passw0rd', "MeasurementsDB") self.cursor = self.conn.cursor() # set the time until a message times out self.client.set_option("messageTimeout", MESSAGE_TIMEOUT) # some embedded platforms need certificate information self.set_certificates() # sets the callback when a message arrives on "input1" queue. Messages sent to # other inputs or to the default will be silently discarded. self.client.set_message_callback("input1", receive_message_callback, self) def set_certificates(self): isWindows = sys.platform.lower() in ['windows', 'win32'] if not isWindows: CERT_FILE = os.environ['EdgeModuleCACertificateFile'] print("Adding TrustedCerts from: {0}".format(CERT_FILE)) # this brings in x509 privateKey and certificate file = open(CERT_FILE) try: self.client.set_option("TrustedCerts", file.read()) print("set_option TrustedCerts successful") except IoTHubClientError as iothub_client_error: print("set_option TrustedCerts failed (%s)" % iothub_client_error) file.close() # Forwards the message received onto the next stage in the process. def forward_event_to_output(self, outputQueueName, event, send_context): self.client.send_event_async(outputQueueName, event, send_confirmation_callback, send_context) def store_to_db(self, sender, receiver): self.cursor.execute( 'INSERT INTO MeasurementsDB.dbo.test (Sender, Receiver) Values ({0}, {1});' .format(sender, receiver)) self.conn.commit() ts = int(time.time() * 1000) self.cursor.execute( 'INSERT INTO MeasurementsDB.dbo.result (Sender, Receiver, DB) Values ({0}, {1}, {2});' .format(sender, receiver, ts))
class HubManager(object): def __init__( self, connection_string, protocol=IoTHubTransportProvider.MQTT): self.client_protocol = protocol self.client = IoTHubClient(connection_string, protocol) if protocol == IoTHubTransportProvider.HTTP: self.client.set_option("timeout", TIMEOUT) self.client.set_option("MinimumPollingTime", MINIMUM_POLLING_TIME) # set the time until a message times out self.client.set_option("messageTimeout", MESSAGE_TIMEOUT) # some embedded platforms need certificate information # self.set_certificates() self.client.set_message_callback(receive_message_callback, RECEIVE_CONTEXT) self.client.set_device_twin_callback(device_twin_callback, TWIN_CONTEXT) self.client.set_device_method_callback(device_method_callback, METHOD_CONTEXT) def set_certificates(self): from iothub_client_cert import CERTIFICATES try: self.client.set_option("TrustedCerts", CERTIFICATES) print ( "set_option TrustedCerts successful" ) except IoTHubClientError as iothub_client_error: print ( "set_option TrustedCerts failed (%s)" % iothub_client_error ) 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 send_reported_state(self, reported_state, size, user_context): self.client.send_reported_state( reported_state, size, send_reported_state_callback, user_context) def upload_to_blob(self, destinationfilename, source, size, usercontext): self.client.upload_blob_async( destinationfilename, source, size, blob_upload_conf_callback, usercontext)
class HubManager(object): def __init__( self, connection_string, protocol=IoTHubTransportProvider.MQTT): self.client_protocol = protocol self.client = IoTHubClient(connection_string, protocol) if protocol == IoTHubTransportProvider.HTTP: self.client.set_option("timeout", TIMEOUT) self.client.set_option("MinimumPollingTime", MINIMUM_POLLING_TIME) # set the time until a message times out self.client.set_option("messageTimeout", MESSAGE_TIMEOUT) # some embedded platforms need certificate information # self.set_certificates() self.client.set_message_callback(receive_message_callback, RECEIVE_CONTEXT) self.client.set_device_twin_callback(device_twin_callback, TWIN_CONTEXT) self.client.set_device_method_callback(device_method_callback, METHOD_CONTEXT) def set_certificates(self): from iothub_client_cert import CERTIFICATES try: self.client.set_option("TrustedCerts", CERTIFICATES) print ( "set_option TrustedCerts successful" ) except IoTHubClientError as iothub_client_error: print ( "set_option TrustedCerts failed (%s)" % iothub_client_error ) 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 send_reported_state(self, reported_state, size, user_context): self.client.send_reported_state( reported_state, size, send_reported_state_callback, user_context) def upload_to_blob(self, destinationfilename, source, size, usercontext): self.client.upload_blob_async( destinationfilename, source, size, blob_upload_conf_callback, usercontext)
class Station: """ Models a Bike Station. """ def __init__(self, id, name, conn_string, listening_port=8080): self.id = id self.port = listening_port self.name = name self.messaging = Messaging(port=listening_port) self.is_running = False self.iothub_client = IoTHubClient(conn_string, PROTOCOL) logging.info("Station was created successfully.") def notify_iothub(self, msg): json_msg = msg.to_json() iot_hub_msg = IoTHubMessage(json_msg) self.iothub_client.send_event_async(iot_hub_msg, self.iothub_callback, None) logging.info("Station notified hub") def iothub_callback(self, message, result, user_context): logging.info ( "IoT Hub responded to message with status: %s" % (result) ) def run(self): self.is_running = True logging.info("Station {} is now running! Listening on port {}".format(self.name, self.port)) msg_thread = threading.Thread(target=self.messaging.start_listening) msg_thread.daemon = True msg_thread.start() while self.is_running: msg = self.messaging.get_message() logging.info("Processing new message...") if msg.type == Message.MessageType.BIKE_TAKE: self.notify_iothub(msg) elif msg.type == Message.MessageType.BIKE_RETURN: self.notify_iothub(msg) elif msg.type == Message.MessageType.SHUTDOWN: self.is_running = False pass else: #TODO bad message logging.warn("Encountered unknown message type :" + msg.type) pass logging.info("Station {} shutdown.".format(self.name))
def iothub_client_prov_hsm_sample_run(): client = IoTHubClient(IOTHUB_URI, DEVICE_ID, SECURITY_TYPE, PROTOCOL) print ( "IoTHubClient sending %d messages" % MESSAGE_COUNT ) for message_counter in range(0, MESSAGE_COUNT): message = create_message(message_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 ) # 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
class HubManager(object): def __init__(self, connectionString, messageTimeout, protocol, verbose): ''' Communicate with the Edge Hub :param str connectionString: Edge Hub connection string :param int messageTimeout: the maximum time in milliseconds until a message times out. The timeout period starts at IoTHubClient.send_event_async. By default, messages do not expire. :param IoTHubTransportProvider protocol: Choose HTTP, AMQP or MQTT as transport protocol. Currently only MQTT is supported. ''' self.connectionString = connectionString self.messageTimeout = messageTimeout self.protocol = protocol self.client_protocol = self.protocol self.client = IoTHubClient(self.connectionString, self.protocol) self.client.set_option("messageTimeout", self.messageTimeout) if verbose: self.client.set_option("logtrace", 1) # enables MQTT logging self.set_certificates( ) # some embedded platforms need certificate information def set_certificates(self): isWindows = sys.platform.lower() in ['windows', 'win32'] return if not isWindows: CERT_FILE = os.environ['CertFile', '/etc/ssl/certs/ca-certificates.crt'] print("Adding TrustedCerts from: {0}".format(CERT_FILE)) # this brings in x509 privateKey and certificate file = open(CERT_FILE) try: self.client.set_option("TrustedCerts", file.read()) print("set_option TrustedCerts successful") except IoTHubClientError as iothub_client_error: print("set_option TrustedCerts failed (%s)" % iothub_client_error) file.close() def send_event_to_output(self, outputQueueName, event, send_context): self.client.send_event_async(outputQueueName, event, send_confirmation_callback, send_context)
class HubManager(object): def __init__( self, connection_string): self.client_protocol = PROTOCOL self.client = IoTHubClient(connection_string, PROTOCOL) # set the time until a message times out self.client.set_option("messageTimeout", MESSAGE_TIMEOUT) # some embedded platforms need certificate information self.set_certificates() # set a TWIN callback self.client.set_device_twin_callback(device_twin_callback, self) # sets the callback when a message arrives on "input1" queue. Messages sent to # other inputs or to the default will be silently discarded. self.client.set_message_callback("input1", receive_message_callback, self) def set_certificates(self): isWindows = sys.platform.lower() in ['windows', 'win32'] if not isWindows: CERT_FILE = os.environ['EdgeModuleCACertificateFile'] print("Adding TrustedCerts from: {0}".format(CERT_FILE)) # this brings in x509 privateKey and certificate file = open(CERT_FILE) try: self.client.set_option("TrustedCerts", file.read()) print ( "set_option TrustedCerts successful" ) except IoTHubClientError as iothub_client_error: print ( "set_option TrustedCerts failed (%s)" % iothub_client_error ) file.close() # Forwards the message received onto the next stage in the process. def forward_event_to_output(self, outputQueueName, event, send_context): self.client.send_event_async( outputQueueName, event, send_confirmation_callback, send_context)
def Start(self): print ("Camera index: " + str(self.camIndex)) cap = cv.VideoCapture(self.camIndex) # Flag to stop processing stop = 0 # Init movidius device plugin = IEPlugin(device="MYRIAD") # Init face counter faceCounter = FaceCounter(plugin) if (cap.open(self.camIndex) == 0): print("Camera not found") return while(stop == 0): # Get image from camera res, frame = cap.read() if(res): # Detect faces faces = faceCounter.CountFaces(frame) # Send data to IoT Hub client = IoTHubClient(DeviceConnectionString, IoTHubTransportProvider.MQTT) message = IoTHubMessage("{\"FaceCount\":\"" + str(faces) + "\"}") client.send_event_async(message, self.send_confirmation_callback, 0) print("Face count detected: " + str(faces)) else: print("Could not get a frame") # Sleep for one second if(cv.waitKey(1000) != -1): stop = 1 cap.release()
class HubManager(object): def __init__(self, connection_string, protocol=IoTHubTransportProvider.MQTT): self.client_protocol = protocol self.client = IoTHubClient(connection_string, protocol) if protocol == IoTHubTransportProvider.HTTP: self.client.set_option("timeout", TIMEOUT) self.client.set_option("MinimumPollingTime", MINIMUM_POLLING_TIME) # set the time until a message times out self.client.set_option("messageTimeout", MESSAGE_TIMEOUT) # some embedded platforms need certificate information self.set_certificates() def set_certificates(self): from iothub_client_cert import CERTIFICATES try: CERT_FILE = os.environ['EdgeModuleCACertificateFile'] file = open(CERT_FILE) self.client.set_option("TrustedCerts", file.read()) print("set_option TrustedCerts successful") except IoTHubClientError as iothub_client_error: print("set_option TrustedCerts failed (%s)" % iothub_client_error) file.close() # Sends a message to the queue with outputQueueName, "temperatureOutput" in the case of the sample. def send_event_to_output(self, outputQueueName, 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(outputQueueName, event, send_confirmation_callback, send_context)
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: for new_data in gps_socket: if new_data: data_stream.unpack(new_data) if data_stream.lat == "n/a": print("Ingen GPS signal") break else: latitude = float(data_stream.lat) longitude = float(data_stream.lon) speedy = float(data_stream.speed) * 3.6 msg_txt_formatted = MSG_TXT % (latitude, longitude, speedy) mydate = datetime.datetime.now() csvstr = datetime.datetime.strftime(mydate, '%d/%m-%Y %H:%M:%S') if data_stream.speed == "n/a": speedy = data_stream.speed else: speedy = float(data_stream.speed) * 3.6 client = IoTHubClient(CONNECTION_STRING, PROTOCOL) message = IoTHubMessage(msg_txt_formatted) client.send_event_async(message, send_confirmation_callback, None) print(csvstr+": IoT Hub: "+msg_txt_formatted) #gemmer csvfil med titel csvstr with open(filename, "a") as csv_file: csv_app = csv.writer(csv_file) csv_app.writerow([csvstr, data_stream.lat, data_stream.lon, speedy]) time.sleep(1) except IoTHubError as iothub_error: print ( "Unexpected error %s from IoTHub" % iothub_error ) return except KeyboardInterrupt: print ( "IoTHubClient sample stopped" )
def main(): print("Starting device...") message_counter = 1 while True: try: client = IoTHubClient(CONNECTION_STRING, PROTOCOL) message = IoTHubMessage( json.dumps({ "entryTime": datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"), "ticketId": str(uuid.uuid4()) })) message.message_id = "message_%d" % message_counter message.correlation_id = "correlation_%d" % message_counter prop_map = message.properties() prop_map.add( "CreationTimeUtc", datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")) prop_map.add("CorrelationId", str(uuid.uuid4())) client.send_event_async(message, send_confirmation_callback, message_counter) print( f"IoTHubClient.send_event_async accepted message {message.get_string()}" ) message_counter += 1 time.sleep(INTERVAL_SECONDS) except Exception as e: print(e) time.sleep(INTERVAL_SECONDS * 2)
def __init__(self,ldr = [],temp = [],dust = [],conduct = []): active_pins = [] inactive_pins = [] State.__init__(self,active_pins,inactive_pins) PROTOCOL = IoTHubTransportProvider.MQTT #remove last item from list, to prevent incorrect data when exiting idle state middle in reading data ldr = ldr[:-1] temp = temp[:-1] dust = dust[:-1] conduct = conduct[:-1] ldr_values = ldr temp_values = temp dust_values = dust conductivity_values = conduct #calculate average ldr_average = average(ldr_values) temp_average = average(temp_values) dust_average = average(dust_values) conductivity_average = average(conductivity_values) print(" ") print("---- AVERAGE SENSOR VALUES ----") print("LDR :" + str(round(ldr_average,2))) print("Temp :" + str(round(temp_average,2))) print("Dust :" + str(round(dust_average,2))) print("Con :" + str(round(conductivity_average,2))) print(" ---- ---- ---- ---- ---- ") #TODO: variable id's ldr_data = json.dumps(data_to_json(ldr_sensor_id,ldr_average)) temp_data = json.dumps(data_to_json(temp_sensor_id,temp_average)) conduct_data = json.dumps(data_to_json(conduct_sensor_id,conductivity_average)) dust_data = json.dumps(data_to_json(dust_sensor_id,dust_average)) #send to IoT hub client = IoTHubClient(CONNECTION_STRING, PROTOCOL) ldr_message = IoTHubMessage(ldr_data) temp_message = IoTHubMessage(temp_data) conduct_message = IoTHubMessage(conduct_data) dust_message = IoTHubMessage(dust_data) client.send_event_async(ldr_message, send_confirmation_callback, None) client.send_event_async(temp_message, send_confirmation_callback, None) client.send_event_async(conduct_message, send_confirmation_callback, None) client.send_event_async(dust_message, send_confirmation_callback, None) print("Messages transmitted to IoT Hub") State.go_idle()
status, result, connect_string = sas_token.get_connection_string() if status != return_values.OK: print("Connection request has failed. Response: {}".format(return_values.RetValDescription(result))) print("Quitting") else: print("Connection request success. String: {}".format(connect_string)) client = IoTHubClient(connect_string.encode("utf-8"), IoTHubTransportProvider.MQTT) client.set_option("logtrace", 0) client.set_message_callback( receive_message_callback, CONTEXT) client.set_device_twin_callback( device_twin_callback, CONTEXT) client.set_device_method_callback( device_method_callback, CONTEXT) message_counter = 0 while True: val = raw_input("Press a key\n") if val == 'q': break else: print("Sending message") message = IoTHubMessage("Test Message") message.message_id = "message_%d" % message_counter message.correlation_id = "correlation_%d" % message_counter client.send_event_async(message, send_confirmation_callback, message_counter) message_counter += 1
class IotHub: def __init__(self, hardware, queue): self.method_callbacks = 0 self.hardware = hardware self.queue = queue self._init_client() def _init_client(self): # Connect to iot-hub self.client = IoTHubClient(IOTHUB_CONNECTION, IoTHubTransportProvider.AMQP) # Settings self.client.set_option("messageTimeout", IOTHUB_MESSAGE_TIMEOUT) self.client.set_device_method_callback(self.device_method_callback, 0) def send_confirmation_callback(self, message, result, user_context): print( "Confirmation received for message with result {}".format(result)) print(" message_id: %s" % message.message_id) print(" correlation_id: %s" % message.correlation_id) def send_message(self, payload): message_id = uuid4() message = IoTHubMessage(bytearray(payload, 'utf8')) self.client.send_event_async(message, self.send_confirmation_callback, message_id) print("Message {} accepted for transmission to IoT Hub.".format( message_id)) return self.client.get_send_status() # Gets invoked by message from the cloud def device_method_callback(self, method_name, payload, user_context): print( "Method callback called with: methodName = {}, payload = {}, context = {}" .format(method_name, payload, user_context)) msg = json.loads(payload) try: if method_name == 'list': response = self.hardware.list_methods() elif method_name == 'cancel': self.queue.cancel() response = "ok" else: method_payload = msg['payload'] if 'payload' in msg else {} self.queue.append("invoke_method", { "method": method_name, "payload": method_payload, }) response = "ok" status = 200 except NotImplementedError: response = 'Method not defined' status = 404 except ValueError as inst: response = inst.args status = 400 except queue.Full: response = "Too many items in queue" status = 503 except Exception as inst: response = inst.args status = 500 return_value = DeviceMethodReturnValue() return_value.status = status return_value.response = json_dumps({'Response': response}) return return_value
def send(dictionary, connection_string): msg_counter = 0 #Arbituary client = IoTHubClient(connection_string, IoTHubTransportProvider.MQTT) client.send_event_async(createMsg(dictionary), message_callback, msg_counter)
print("TEMP: " + str(temperatureData)) print("DUST: " + str(dustData)) print("CON: " + str(conductivityData)) print("---- LISTS ----") print(ldrValues) print(tempValues) print(dustValues) print(conductivityValues) print("---- END DATA [" + str(n) + "] ----") print(" ") #Wait exactly 30 seconds by waiting a certain amount of seconds at each sensor time.sleep(delay / amount_of_values) #Send to IoT Hub message = IoTHubMessage(ldrData) client.send_event_async(message, send_confirmation_callback, None) message2 = IoTHubMessage(temperatureData) client.send_event_async(message2, send_confirmation_callback, None) message3 = IoTHubMessage(conductivityData) client.send_event_async(message3, send_confirmation_callback, None) message4 = IoTHubMessage(dustData) client.send_event_async(message4, send_confirmation_callback, None) print("Messages transmitted to IoT Hub")
i = 0 try: while True and i < 500: with open('test.jpg', 'rb') as fd: i += 1 # fd = open('test.jpg') img_str = fd.read() b64 = base64.b64encode(img_str) b64string = b64.decode('utf-8') message = {'message': b64string, 'message_sent': time.time()} messageJson = json.dumps(message) size = sys.getsizeof(message) iot_hub_message = IoTHubMessage(messageJson) print("Sent size: {}".format(str(size))) client.send_event_async(iot_hub_message, send_confirmation_callback, None) print('Request {}\n'.format(i)) time.sleep(1) except KeyboardInterrupt: stats.close() exit(0) while True: try: print('Waiting for response') time.sleep(10) except KeyboardInterrupt: stats.close() exit(0)
class AzureIoTClient(object): def __init__( self, connection_string, logger, protocol=IoTHubTransportProvider.MQTT, message_timeout=10000, # Callback handlers receive_message_callback=noop, send_event_callback=noop, reported_state_callback=noop): self._connection_string = connection_string self._logger = logger self._protocol = protocol self._message_timeout = message_timeout self.receive_message_callback = receive_message_callback self.send_event_callback = send_event_callback self.reported_state_callback = reported_state_callback self.client = None self._send_context = 0 self._reported_state_context = 0 def connect(self): self._logger.info("Connecting") self.client = IoTHubClient(self._connection_string, self._protocol) # set the time until a message times out self.client.set_option("messageTimeout", self._message_timeout) self.client.set_message_callback(self._receive_message_callback, RECEIVE_CONTEXT) def disconnect(self): self._logger.info("Disconnecting") self.client = None def _receive_message_callback(self, message, context): message_buffer = message.get_bytearray() size = len(message_buffer) body = message_buffer[:size].decode('utf-8') self._logger.debug("Data: {}, Size={}, counter".format( body, size, context)) map_properties = message.properties() properties = map_properties.get_internals() self._logger.debug(" Properties: {}".format(properties)) if self.receive_message_callback: try: body = json.loads(body) except (json_decode_error, ValueError): # ignore if no json, pass it to callback as decoded body pass try: self.receive_message_callback(body, properties) except ValueError: return IoTHubMessageDispositionResult.REJECTED return IoTHubMessageDispositionResult.ACCEPTED def send_event(self, event, properties=None): """ Sends an event Args: event (dict): event values properties (dict): values to send as properties """ if not isinstance(event, IoTHubMessage): event = json.dumps(event) event = IoTHubMessage(bytearray(event, 'utf8')) if properties and 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, self._send_event_callback, self._send_context) self._send_context += 1 def _send_event_callback(self, message, result, user_context): self._logger.debug( "Confirmation[{}] received for send event message, result: {}". format(user_context, result)) map_properties = message.properties() key_value_pair = map_properties.get_internals() self._logger.debug("Properties: {}".format(key_value_pair)) # notify block is requested if self.send_event_callback: self.send_event_callback(result, key_value_pair) def send_reported_state(self, reported_state): """ Sends a reported state Args: reported_state (dict): state to report """ reported_state = json.dumps(reported_state) self.client.send_reported_state(reported_state, len(reported_state), self._send_reported_state_callback, self._reported_state_context) self._reported_state_context += 1 def _send_reported_state_callback(self, result, user_context): self._logger.debug("Confirmation for reported state received with:" "\nresult = {}\ncontext = {}".format( result, user_context)) # notify block is requested if self.reported_state_callback: self.reported_state_callback(result)
msg_counter = 0 # Arbitrary requests.get( "https://api.telegram.org/bot" + botToken + "/sendMessage?chat_id=" + chatId + "&text={} started".format(scannerId)) # Boot notification to Telegram bootMsgDict = { "devicegroup": "beaconScanner", "topic": "scannerStatus", "project": projectNum, "scannerId": scannerId, "datetime": str(datetime.datetime.now().isoformat()), "status": 0 } try: client.send_event_async(createMsg(bootMsgDict), message_callback, msg_counter) # Boot notification to IoTHub except Exception: requests.get("https://api.telegram.org/bot" + botToken + "/sendMessage?chat_id=" + chatId + "&text={} IoTHub error {}".format(scannerId, iothub_error)) os.system( "wait $" + str(os.getpid()) + "; sudo python3 /home/pi/Documents/Python/IndoorLocation/BLEScanFiltered.py" ) while True: timenow = datetime.datetime.now() if timenow.minute % 15 == 0 and timenow.second < 10: # Heartbeat requests.get( "https://api.telegram.org/bot" + botToken + "/sendMessage?chat_id=" + chatId +
import obd import time import json import serial import re from iothub_client import IoTHubClient, IoTHubTransportProvider, IoTHubMessage # Azure IoT Hub CONNECTION_STRING = "HostName=OBDLOG.azure-devices.net;DeviceId=RPi1;SharedAccessKey=/uGkNvfJAs//p+57idGGWKGJOY+t8HmfuUQFvda8RhU=" PROTOCOL = IoTHubTransportProvider.MQTT # confirmation callback def send_confirmation_callback(message, result, user_context): print("Confirmation received for message with result = %s" % (result)) client = IoTHubClient(CONNECTION_STRING, PROTOCOL) # OBD serial port devices = obd.scan_serial() # GPS serial port gps_ser = serial.Serial("/dev/ttyS0", 115200) gps_buff = ["AT+CGNSPWR=1\r\n", "AT+CGNSSEQ=\"RMC\"\r\n", "AT+CGNSINF\r\n"] # Object for JSON.stringify() prejsonValues = {} # connect to vehicle try: connection = obd.OBD(devices[0]) pids = connection.supported_commands print(str(devices[0])) except Exception as ELM_missing: print("Chyba pripojenia k vozidlu: " + str(ELM_missing)) exit()
class Azure: def __init__(self, application, device_config): global azure_singelton if azure_singelton is None: azure_singelton = self else: raise Exception("AZURE: AzureIot instance already created") with open('azure.json') as f: self.config = json.load(f) if self.config['connection_string'].find(device_config.deviceid) == -1: raise Exception( "Azure connection string does not match configured device id") self.application = application self.hubClient = IoTHubClient(self.config['connection_string'], PROTOCOL) if self.hubClient.protocol == IoTHubTransportProvider.MQTT or self.hubClient.protocol == IoTHubTransportProvider.MQTT_WS: self.hubClient.set_device_twin_callback(device_twin_callback, TWIN_CONTEXT) # Report current state to cloud def update_reported_state(self, reported): try: # Report new state to HUB reported_state = json.dumps(reported) self.hubClient.send_reported_state(reported_state, len(reported_state), send_reported_state_callback, SEND_REPORTED_STATE_CONTEXT) return True except IoTHubError as iothub_error: print( "AZURE: Unexpected error from IoTHub when reporting state: %s" % iothub_error) return False # Post telemetry to cloud def post_telemetry(self, telemetry): try: message = IoTHubMessage(json.dumps(telemetry)) self.hubClient.send_event_async(message, send_confirmation_callback, None) return True except IoTHubError as iothub_error: print( "AZURE: Unexpected error from IoTHub when posting telemetry: %s" % iothub_error) return False # Keep cloud connection open (not needed for azure) def kick(self): pass # Local callbacks from iot_client def device_twin_callback(self, update_state, payload, user_context): print("AZURE: Twin callback called with updateStatus: '%s'" % update_state) payload_json = json.loads(payload) if update_state == iothub_client.iothub_client.IoTHubTwinUpdateState.COMPLETE: desired_state = payload_json["desired"].copy() else: desired_state = payload_json.copy() self.application.device_twin_update(desired_state) def send_confirmation_callback(self, message, result, user_context): print("AZURE: IoT Hub responded to message with status: %s" % (result)) def send_reported_state_callback(self, status_code, user_context): print( "AZURE: Confirmation for reported state called with status_code: %d" % status_code)
class DeviceClient(object): def __init__(self, connection_string, protocol=IoTHubTransportProvider.MQTT): print("Device Client __init__ ....creating IoTHubClient connection!") print("Connection String = %s" % connection_string) self.client_protocol = protocol self.client = IoTHubClient(connection_string, protocol) if protocol == IoTHubTransportProvider.HTTP: self.client.set_option("timeout", TIMEOUT) self.client.set_option("MinimumPollingTime", MINIMUM_POLLING_TIME) # set the time until a message times out self.client.set_option("messageTimeout", MESSAGE_TIMEOUT) # some embedded platforms need certificate information # self.set_certificates() self.client.set_message_callback(self.receive_message_callback, RECEIVE_CONTEXT) self.client.set_device_twin_callback(self.device_twin_callback, TWIN_CONTEXT) self.client.set_device_method_callback(self.device_method_callback, METHOD_CONTEXT) def set_certificates(self, client): from iothub_client_cert import CERTIFICATES try: self.client.set_option("TrustedCerts", CERTIFICATES) print("set_option TrustedCerts successful") except IoTHubClientError as iothub_client_error: print("set_option TrustedCerts failed (%s)" % iothub_client_error) 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, self.send_confirmation_callback, send_context) def send_reported_state(self, reported_state, size, user_context): self.client.send_reported_state(reported_state, size, self.send_reported_state_callback, user_context) def upload_to_blob(self, destinationfilename, source, size, usercontext): self.client.upload_blob_async(destinationfilename, source, size, self.blob_upload_conf_callback, usercontext) def send_confirmation_callback(self, message, result, user_context): global SEND_CALLBACKS print("Confirmation[%d] received for message with result = %s" % (user_context, result)) map_properties = message.properties() key_value_pair = map_properties.get_internals() print(" Properties: %s" % key_value_pair) SEND_CALLBACKS += 1 print(" Total calls confirmed: %d" % SEND_CALLBACKS) def receive_message_callback(self, message, counter): global RECEIVE_CALLBACKS message_buffer = message.get_bytearray() size = len(message_buffer) print("<SimDevice> Received Message [%d]:" % counter) print(" Data: <<<%s>>> & Size=%d" % (message_buffer[:size].decode('utf-8'), size)) map_properties = message.properties() key_value_pair = map_properties.get_internals() print(" Properties: %s" % key_value_pair) counter += 1 RECEIVE_CALLBACKS += 1 print(" Total calls received: %d" % RECEIVE_CALLBACKS) return IoTHubMessageDispositionResult.ACCEPTED def device_twin_callback(self, update_state, payload, user_context): global TWIN_CALLBACKS print( "\nTwin callback called with:\nupdateStatus = %s\npayload = %s\ncontext = %s" % (update_state, payload, user_context)) TWIN_CALLBACKS += 1 print("Total calls confirmed: %d\n" % TWIN_CALLBACKS) def send_reported_state_callback(self, status_code, user_context): global SEND_REPORTED_STATE_CALLBACKS print( "Confirmation for reported state received with:\nstatus_code = [%d]\ncontext = %s" % (status_code, user_context)) SEND_REPORTED_STATE_CALLBACKS += 1 print(" Total calls confirmed: %d" % SEND_REPORTED_STATE_CALLBACKS) def device_method_callback(self, method_name, payload, user_context): global METHOD_CALLBACKS print( "\nMethod callback called with:\nmethodName = %s\npayload = %s\ncontext = %s" % (method_name, payload, user_context)) METHOD_CALLBACKS += 1 print("Total calls confirmed: %d\n" % METHOD_CALLBACKS) device_method_return_value = DeviceMethodReturnValue() device_method_return_value.response = "{ \"Response\": \"This is the response from the device\" }" device_method_return_value.status = 200 return device_method_return_value def blob_upload_conf_callback(self, result, user_context): global BLOB_CALLBACKS print( "Blob upload confirmation[%d] received for message with result = %s" % (user_context, result)) BLOB_CALLBACKS += 1 print(" Total calls confirmed: %d" % BLOB_CALLBACKS) def connection_status_callback(self, result, reason, user_context): global CONNECTION_STATUS_CALLBACKS print("Connection status changed[%d] with:" % (user_context)) print(" reason: %d" % reason) print(" result: %s" % result) CONNECTION_STATUS_CALLBACKS += 1 print(" Total calls confirmed: %d" % CONNECTION_STATUS_CALLBACKS)