def iothub_messaging_sample_run(): try: # Create IoTHubRegistryManager registry_manager = IoTHubRegistryManager(CONNECTION_STRING) for i in range(0, MESSAGE_COUNT): print('Sending message: {0}'.format(i)) data = MSG_TXT props = {} # optional: assign system properties props.update(messageId="message_%d" % i) props.update(correlationId="correlation_%d" % i) props.update(contentType="application/json") # optional: assign application properties prop_text = "PropMsg_%d" % i props.update(testProperty=prop_text) registry_manager.send_c2d_message(DEVICE_ID, data, properties=props) except Exception as ex: print("Unexpected error {0}" % ex) return except KeyboardInterrupt: print("IoT Hub C2D Messaging service sample stopped")
def iothub_messaging_sample_run(): try: # Create IoTHubRegistryManager registry_manager = IoTHubRegistryManager(CONNECTION_STRING) for i in range(0, MESSAGE_COUNT): logging.info('Sending message: {0}'.format(i)) data = DEVICE_MESSAGE props = {} # # optional: assign system properties # props.update(messageId = "message_%d" % i) # props.update(correlationId = "correlation_%d" % i) # props.update(contentType = "application/json") # optional: assign application properties # prop_text = "PropMsg_%d" % i # props.update(testProperty = prop_text) registry_manager.send_c2d_message(DEVICE_ID, data, properties=props) # try: # # Try Python 2.xx first # raw_input("Press Enter to continue...\n") # except: # pass # # Use Python 3.xx in the case of exception # input("Press Enter to continue...\n") except Exception as ex: logging.info("Unexpected error {0}" % ex) return except KeyboardInterrupt: logging.info("IoT Hub C2D Messaging service sample stopped")
def get_farm_data(device_id): # query farm data correspoding to device client = CosmosClient(Cosmos.URL, Cosmos.KEY) farms_container = client.get_database_client(Cosmos.DATABASE).get_container_client(Cosmos.FARMS_CONTAINER) query = """SELECT c FROM farms f JOIN c IN f.farms_arr WHERE c.base_station.deviceId = @dev_id""" items = list(farms_container.query_items( query=query, parameters=[{ "name":"@dev_id", "value": device_id }], enable_cross_partition_query=True )) props = { 'TYPE': 'RESPONSE', 'EVENT': 'FARM_DATA_LOADED' } payload = json.dumps(items[0]['c']) # write back response to the device registry_manager = IoTHubRegistryManager(IoTHub.CONNECTION_STRING) registry_manager.send_c2d_message(device_id, payload, properties=props)
def iothub_messaging_sample_run(): try: # Create IoTHubRegistryManager registry_manager = IoTHubRegistryManager(CONNECTION_STRING_SERVICE) for i in range(0, MESSAGE_COUNT): print('Sending message: {0}'.format(i)) data = MSG_TXT % (AVG_WIND_SPEED + (random.random() * 4 + 2)) props = {} # optional: assign system properties props.update(messageId="message_%d" % i) props.update(correlationId="correlation_%d" % i) props.update(contentType="application/json") # optional: assign application properties props.update(testProperty=random.randint(0, 1)) registry_manager.send_c2d_message( DEVICE_ID, data, properties=props) input("Press Enter to continue...\n") except Exception as ex: print("Unexpected error {0}" % ex) return except KeyboardInterrupt: print("IoT Hub C2D Messaging service sample stopped")
def aux_iot_hub_send_message_to_device(device_name, message_body, message_properties): #CONNECT TO THE IOT HUB DEVICE REGISTRY MANAGER aux_iot_hub_registry_manager = IoTHubRegistryManager( AUX_IOT_HUB_CONNECTION_STRING) message_properties.update(contentType="application/json") aux_iot_hub_registry_manager.send_c2d_message(device_name, message_body, message_properties)
def iothub_messaging_sample_run(data): global count registry_manager = IoTHubRegistryManager(CONNECTION_STRING) count += 1 print('Sending message: {0}'.format(count)) print('Data send: {0}'.format(data)) props = {} registry_manager.send_c2d_message(DEVICE_ID, data, properties=props)
def send_C2D_message(): conn_string = Config.IOTHUB_CONNECTION_STRING device_id = Config.IOTHUB_DEVICE_ID registry_manager = IoTHubRegistryManager(conn_string) data = "New Settings Saved!" registry_manager.send_c2d_message( device_id, data)
def main(req: func.HttpRequest) -> func.HttpResponse: logging.info('Python HTTP trigger function processed a request.') connectionString = get_connection_string() hub = IoTHubRegistryManager(connectionString) hub.send_c2d_message(DeviceName, "coffeeon") return func.HttpResponse( "The coffee on command has been sent successfully.", status_code=200)
def main(req: func.HttpRequest) -> func.HttpResponse: # fetch the deviceId from the request try: device_id = req.params['device_id'] sensor_id = req.params['sensor_id'] except (ValueError, KeyError) as e: return func.HttpResponse("Incorrect request body", status_code=422) props = {'TYPE': 'REMOTE_INVOCATION', 'EVENT': 'FLY_DRONE'} payload = json.dumps({'device_id': device_id, 'sensor_id': sensor_id}) registry_manager = IoTHubRegistryManager(IoTHub.CONNECTION_STRING) registry_manager.send_c2d_message(device_id, payload, properties=props) return func.HttpResponse("Invoked", status_code=200)
def iothub_messaging_sample_run(msg): try: # IoTHubRegistryManager registry_manager = IoTHubRegistryManager(CONNECTION_STRING) for i in range(0, MESSAGE_COUNT): logging.info('Sending message: {0}'.format(i)) data = msg props = {} registry_manager.send_c2d_message(DEVICE_ID, data, properties=props) except Exception as ex: logging.info(f"Unexpected error {ex}") return
def LockUnlock(action): registry_manager = IoTHubRegistryManager(CONNECTION_STRING) data = MSG_TXT % action props = {} # optional: assign system properties # i = i + 1 # props.update(messageId = "message_%d" % i) #props.update(correlationId = "correlation_%d" % i) props.update(contentType="application/json") # optional: assign application properties #prop_text = "PropMsg_%d" % i #props.update(testProperty = prop_text) registry_manager.send_c2d_message(DEVICE_ID, data, properties=props) return json.dumps({'success': True}), 200, { 'ContentType': 'application/json' }
class Server(object): def __init__(self, HOST='localhost', PORT=7734): self.SERVER_HOST = 'localhost' self.SERVER_PORT = 7734 self.HOST = HOST self.DIR = 'rfc' # file directory Path(self.DIR).mkdir(exist_ok=True) self.UPLOAD_PORT = None self.version = 0 self.trainer = Trainer() self.version = 0 self.id = str(random.randint(0, 5000)) self.lock = threading.Lock() self.h = 100 self.w = 100 self.s3 = boto3.client('s3') # self.s3 = boto3.client('s3', region_name=location) print("Conntected to AWS") # response = s3.list_buckets() print() def start(self): try: self.registry_manager = IoTHubRegistryManager(CONNECTION_server) os.system( 'az iot hub device-identity create --device-id %s --hub-name pathak' % (self.id)) print("ID of the client created = %s" % (self.id)) print("Connecting the Python IoT Hub") self.CONNECTION_STRING = os.popen( "az iot hub device-identity show-connection-string --device-id %s --hub-name pathak -o table" % (self.id)).read() self.CONNECTION_STRING = self.CONNECTION_STRING.split()[-1] client = IoTHubDeviceClient.create_from_connection_string( self.CONNECTION_STRING) except Exception as e: print("Problems with IOT HUB") os._exit(0) print("Connected") self.uploader = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.uploader.bind(('', 0)) self.UPLOAD_PORT = self.uploader.getsockname()[1] self.uploader.listen(5) print('Listening on the upload port %s' % self.UPLOAD_PORT) message_listener_thread = threading.Thread( target=self.message_listener, args=(client, )) message_listener_thread.daemon = True message_listener_thread.start() self.cli() def message_listener(self, client): port = self.UPLOAD_PORT host = socket.gethostname() while True: message = client.receive_message() message = str(message.data) message = message[2:].split() id = message[0] source_port = message[1] source_host = message[2] source_version = message[3] peer = socket.socket(socket.AF_INET, socket.SOCK_STREAM) peer.connect((source_host, int(source_port))) if len(message) == 5: filename = self.DIR + "/" + 'checkpoint.pth.tar' self.trainer.package(filename) filesize = os.path.getsize(filename) peer.send(str(filesize).encode()) send_size = 0 with open(filename, "rb") as f: while send_size < int(filesize): bytes_read = f.read(BUFFER_SIZE) peer.sendall(bytes_read) send_size += len(bytes_read) else: data = self.id + " " + str( self.UPLOAD_PORT) + " " + socket.gethostname() + " " + str( self.version) peer.sendall(data.encode('utf-8')) def cli(self): self.command_dict = { '1': self.check_version, '2': self.check_peer, '3': self.look_up, '4': self.train, '5': self.classify, '6': self.download, '7': self.shutdown } while True: try: req = input( '\n1: Check Model Version\n2: Check Peers\n3: Look up storage \n4: Train Image \n5: Classify Image \n6: Download \n7: Shut Down\nEnter your request: ' ) self.command_dict.setdefault(req, self.invalid_input)() except MyException as e: print(e) except Exception: print('System Error.') except BaseException: self.shutdown() def check_version(self): print("Current Model Version is %d" % (self.version)) def check_peer(self, display=True): if display: print("Listening to peers, Avaliable peers:") peers = json.loads( os.popen( "az iot hub device-identity list --hub-name pathak -o json"). read()) so_far = self.version device_id = 0 for peer in peers: if peer['deviceId'] == self.id: continue else: DEVICE_ID = peer['deviceId'] data = self.id + " " + str( self.UPLOAD_PORT) + " " + socket.gethostname() + " " + str( self.version) try: self.registry_manager.send_c2d_message(DEVICE_ID, data) requester, addr = self.uploader.accept() message = requester.recv(1024).decode() message = message.split() if int(message[3]) > so_far: so_far = int(message[3]) device_id = DEVICE_ID if display: print( "Device id (IOT) %s Device id recieved: %s\tPORT: %s\tHOST: %s\tVersion: %s" % (DEVICE_ID, message[0], message[1], message[2], message[3])) except Exception as e: print( "peer information not available, most likely due to token expiry" ) return self.version, self.id return so_far, device_id def look_up(self): print("Local Storage") print(os.listdir("rfc")) files = [] print("Looking Cloud Storage") s3_result = self.s3.list_objects_v2(Bucket=bucket_name, Delimiter="/") if 'Contents' not in s3_result and 'CommonPrefixes' not in s3_result: print("empty bucket") else: files = [] if s3_result.get('Contents'): for key in s3_result['Contents']: print("Downloading ", key['Key']) metadata = self.s3.head_object(Bucket=bucket_name, Key=key['Key']) files.append((key['Key'], metadata["Metadata"]["label"])) with open(self.DIR + "/" + key['Key'], 'wb') as f: self.s3.download_fileobj(bucket_name, key['Key'], f) print("UPDATED Local Storage") print(os.listdir("rfc")) def train(self): self.download() # title = "1.png" # label = 1 title = input('Enter image name: ') label = input('Enter label: ') filename = self.DIR + "/" + title self.s3.upload_file(filename, bucket_name, title, ExtraArgs={'Metadata': { 'label': str(label) }}) file = Path('%s/%s' % (self.DIR, title)) image = Image.open(file) image = image.resize((self.h, self.w)) label = int(label) loss = self.trainer.train(image, label) print("Training Loss %f" % (loss)) self.version += 1 # image.show() # data_string = pickle.dumps(image, -1) # # data_loaded = pickle.loads(data_string) # if not file.is_file(): # raise MyException('File Not Exit!') # # msg = {"label" : label , "data": data_string , "host": socket.gethostname(), "POST": self.UPLOAD_PORT} # # data_loaded = pickle.loads(str.encode(c)) # self.server.sendall(msg.encode('utf-8')) # self.server.sendall(data_string) # res = self.server.recv(1024).decode() # print('Recieve response: \n%s' % res) def classify(self): # cmp --silent ./rfc/checkpoint.pth.tar ../rfc/checkpoint.pth.tar || echo "files are different" self.download() # title = "1.png" title = input('Enter image name: ') # label = input('Enter label: ') file = Path('%s/%s' % (self.DIR, title)) image = Image.open(file) image = image.resize((self.h, self.w)) output = self.trainer.evaluate(image) print("Predicted Label %d" % (output)) return def download(self): print("Searching peers for latest model version") so_far, device_id = self.check_peer(display=False) filename = self.DIR + "/" + 'checkpoint.pth.tar' if int(so_far) > self.version: print("Latest Version Located on device", device_id) self.version = int(so_far) data = self.id + " " + str( self.UPLOAD_PORT) + " " + socket.gethostname() + " " + str( self.version) + " q" self.registry_manager.send_c2d_message(device_id, data) requester, addr = self.uploader.accept() filesize = requester.recv(1024).decode() rec_size = 0 with open(filename, "wb") as f: while rec_size < int(filesize): bytes_read = requester.recv(BUFFER_SIZE) f.write(bytes_read) rec_size += len(bytes_read) print("Model Download complete") self.trainer.load_package(filename) else: print("Current Version is already the latest") return def invalid_input(self): raise MyException('Invalid Input.') def shutdown(self): try: print("deleting the device on hub") # az iot hub device-identity delete --device-id 1803 --hub-name pathak os.system( 'az iot hub device-identity delete --device-id %s --hub-name pathak' % (self.id)) print('\nShutting Down...') except Exception: print("IoT Hub C2D Messaging service sample stopped") os._exit(0)
class ServiceHelperSync(object): def __init__(self): self._executor = ThreadPoolExecutor() self._registry_manager = IoTHubRegistryManager( iothub_connection_string) logger.info( "Creating EventHubConsumerClient with consumer_group = {}".format( eventhub_consumer_group)) self._eventhub_consumer_client = EventHubConsumerClient.from_connection_string( eventhub_connection_string, consumer_group=eventhub_consumer_group) self._eventhub_future = self._executor.submit(self._eventhub_thread) self.device_id = None self.module_id = None self.incoming_patch_queue = queue.Queue() self.cv = threading.Condition() self.incoming_eventhub_events = {} def set_identity(self, device_id, module_id): if device_id != self.device_id or module_id != self.module_id: self.device_id = device_id self.module_id = module_id self.incoming_patch_queue = queue.Queue() with self.cv: if self.incoming_eventhub_events: logger.warning( "Abandoning incoming events with IDs {}".format( str(list(self.incoming_eventhub_events.keys())))) self.incoming_eventhub_events = {} def set_desired_properties(self, desired_props): if self.module_id: self._registry_manager.update_module_twin( self.device_id, self.module_id, Twin(properties=TwinProperties(desired=desired_props)), "*", ) else: self._registry_manager.update_twin( self.device_id, Twin(properties=TwinProperties(desired=desired_props)), "*") def invoke_method( self, method_name, payload, connect_timeout_in_seconds=30, response_timeout_in_seconds=None, ): request = CloudToDeviceMethod( method_name=method_name, payload=payload, response_timeout_in_seconds=response_timeout_in_seconds, connect_timeout_in_seconds=connect_timeout_in_seconds, ) if self.module_id: response = self._registry_manager.invoke_device_module_method( self.device_id, self.module_id, request) else: response = self._registry_manager.invoke_device_method( self.device_id, request) return response def send_c2d(self, payload, properties): if self.module_id: raise TypeError("sending C2D to modules is not supported") self._registry_manager.send_c2d_message(self.device_id, payload, properties) def wait_for_eventhub_arrival(self, message_id, timeout=600): def get_event(inner_message_id): with self.cv: arrivals = self.incoming_eventhub_events # if message_id is not set, return any message if not inner_message_id and len(arrivals): id = list(arrivals.keys())[0] logger.info( "wait_for_eventhub_arrival(None) returning msgid={}". format(id)) else: id = inner_message_id if id and (id in arrivals): value = arrivals[id] del arrivals[id] return value else: return None if timeout: end_time = time.time() + timeout else: end_time = None with self.cv: while True: ev = get_event(message_id) if ev: return ev elif time.time() >= end_time: logger.warning( "timeout waiting for message with msgid={}".format( message_id)) return None elif end_time: self.cv.wait(timeout=end_time - time.time()) else: self.cv.wait() def get_next_reported_patch_arrival(self, block=True, timeout=20): try: return self.incoming_patch_queue.get(block=block, timeout=timeout) except queue.Empty: raise Exception( "reported patch did not arrive within {} seconds".format( timeout)) def shutdown(self): if self._eventhub_consumer_client: self._eventhub_consumer_client.close() def _convert_incoming_event(self, event): try: event_body = event.body_as_json() except TypeError: event_body = event.body_as_str() device_id = get_device_id_from_event(event) module_id = get_module_id_from_event(event) if get_message_source_from_event(event) == "twinChangeEvents": return copy.deepcopy(event_body.get("properties", {})) else: message = EventhubEvent() message.device_id = device_id message.module_id = module_id message.message_body = event_body if event.message.properties: message.properties = convert_binary_dict_to_string_dict( event.properties) message.content_type = event.message.properties.content_type.decode( "utf-8") message.system_properties = convert_binary_dict_to_string_dict( event.system_properties) return message def _store_eventhub_arrival(self, converted_event): message_id = converted_event.system_properties.get( "message-id", "no-message-id-{}".format(uuid.uuid4())) if message_id: with self.cv: self.incoming_eventhub_events[message_id] = converted_event self.cv.notify_all() def _store_patch_arrival(self, converted_event): self.incoming_patch_queue.put(converted_event) def _eventhub_thread(self): def on_error(partition_context, error): logger.error("EventHub on_error: {}".format( str(error) or type(error))) def on_partition_initialize(partition_context): logger.warning("EventHub on_partition_initialize") def on_partition_close(partition_context, reason): logger.warning("EventHub on_partition_close: {}".format(reason)) def on_event_batch(partition_context, events): try: for event in events: device_id = get_device_id_from_event(event) module_id = get_module_id_from_event(event) if device_id == self.device_id and module_id == self.module_id: converted_event = self._convert_incoming_event(event) if type(converted_event) == EventhubEvent: if "message-id" in converted_event.system_properties: logger.info( "Received event with msgid={}".format( converted_event. system_properties["message-id"])) else: logger.info( "Received event with no message id") else: logger.info( "Received {} for device {}, module {}".format( get_message_source_from_event(event), device_id, module_id, )) if isinstance(converted_event, EventhubEvent): self._store_eventhub_arrival(converted_event) else: self._store_patch_arrival(converted_event) except Exception: logger.error("Error on on_event_batch", exc_info=True) raise try: with self._eventhub_consumer_client: logger.info("Starting EventHub receive") self._eventhub_consumer_client.receive_batch( max_wait_time=2, on_event_batch=on_event_batch, on_error=on_error, on_partition_initialize=on_partition_initialize, on_partition_close=on_partition_close, ) except Exception: logger.error("_eventhub_thread exception", exc_info=True) raise
class ServiceHelperSync(object): def __init__(self): self._client_list = ClientList() self._executor = ThreadPoolExecutor() self._registry_manager = IoTHubRegistryManager( iothub_connection_string) self._digital_twin_client = DigitalTwinClient.from_connection_string( iothub_connection_string) self._eventhub_consumer_client = EventHubConsumerClient.from_connection_string( eventhub_connection_string, consumer_group=eventhub_consumer_group) self._eventhub_future = self._executor.submit(self._eventhub_thread) def start_watching(self, device_id, module_id): self._client_list.get_or_create(device_id, module_id) def stop_watching(self, device_id, module_id): self._client_list.remove(device_id, module_id) def get_next_incoming_event(self, device_id, module_id, block=True, timeout=None): return self._client_list.get_incoming_event_queue.get(block=block, timeout=timeout) def set_desired_properties(self, device_id, module_id, desired_props): if module_id: self._registry_manager.update_module_twin( device_id, module_id, Twin(properties=TwinProperties(desired=desired_props)), "*") else: self._registry_manager.update_twin( device_id, Twin(properties=TwinProperties(desired=desired_props)), "*") def invoke_method( self, device_id, module_id, method_name, payload, connect_timeout_in_seconds=None, response_timeout_in_seconds=None, ): request = CloudToDeviceMethod( method_name=method_name, payload=payload, response_timeout_in_seconds=response_timeout_in_seconds, connect_timeout_in_seconds=connect_timeout_in_seconds, ) if module_id: response = self._registry_manager.invoke_device_module_method( device_id, module_id, request) else: response = self._registry_manager.invoke_device_method( device_id, request) return response def invoke_pnp_command( self, device_id, module_id, component_name, command_name, payload, connect_timeout_in_seconds=None, response_timeout_in_seconds=None, ): assert not module_id # TODO if component_name: return self._digital_twin_client.invoke_component_command( device_id, component_name, command_name, payload, connect_timeout_in_seconds, response_timeout_in_seconds, ) else: return self._digital_twin_client.invoke_command( device_id, command_name, payload, connect_timeout_in_seconds, response_timeout_in_seconds, ) def get_pnp_properties(self, device_id, module_id): assert not module_id # TODO return self._digital_twin_client.get_digital_twin(device_id) def update_pnp_properties(self, device_id, module_id, properties): assert not module_id # TODO return self._digital_twin_client.update_digital_twin( device_id, properties) def send_c2d(self, device_id, module_id, payload, properties): assert not module_id # TODO self._registry_manager.send_c2d_message(device_id, payload, properties) def get_next_eventhub_arrival(self, device_id, module_id, block=True, timeout=None): return self._client_list.get_incoming_event_queue( device_id, module_id).get(block=block, timeout=timeout) def get_next_reported_patch_arrival(self, device_id, module_id, block=True, timeout=None): return self._client_list.get_incoming_patch_queue( device_id, module_id).get(block=block, timeout=timeout) def shutdown(self): if self._eventhub_consumer_client: self._eventhub_consumer_client.close() def _convert_incoming_event(self, event): event_body = event.body_as_json() device_id = get_device_id_from_event(event) module_id = None # TODO: extract module_id if get_message_source_from_event(event) == "twinChangeEvents": return copy.deepcopy(event_body.get("properties", {})) else: message = C2dMessage() message.device_id = device_id message.module_id = module_id message.message_body = event_body message.content_type = event.message.properties.content_type.decode( "utf-8") message.system_properties = convert_binary_dict_to_string_dict( event.system_properties) message.properties = convert_binary_dict_to_string_dict( event.properties) return message def _eventhub_thread(self): def on_error(partition_context, error): logger.error("EventHub on_error: {}".format( str(error) or type(error))) def on_partition_initialize(partition_context): logger.warning("EventHub on_partition_initialize") def on_partition_close(partition_context, reason): # commented out because it causes ugly warning spew on shutdown # logger.warning("EventHub on_partition_close: {}".format(reason)) pass def on_event(partition_context, event): if event: device_id = get_device_id_from_event(event) module_id = None # TODO: extract module_id if get_message_source_from_event(event) == "twinChangeEvents": queue = self._client_list.get_incoming_patch_queue( device_id, module_id) else: queue = self._client_list.get_incoming_event_queue( device_id, module_id) if queue: logger.info("Received {} for device {}, module {}".format( get_message_source_from_event(event), device_id, module_id)) queue.put(self._convert_incoming_event(event)) try: with self._eventhub_consumer_client: logger.info("Starting EventHub receive") self._eventhub_consumer_client.receive( on_event, on_error=on_error, on_partition_initialize=on_partition_initialize, on_partition_close=on_partition_close, max_wait_time=3600, ) except Exception: logger.error("_eventhub_thread exception", exc_info=True) raise
import sys import os from azure.iot.hub import IoTHubRegistryManager connection_str = os.getenv("IOTHUB_CONNECTION_STRING") device_id = os.getenv("IOTHUB_DEVICE_ID") try: # Create IoTHubRegistryManager registry_manager = IoTHubRegistryManager(connection_str) print("Conn String: {0}".format(connection_str)) # Send Message To Device send_message = "Sending c2d message 1" registry_manager.send_c2d_message(device_id, send_message) # Send 2nd Message To Device with property send_message = b"{ 'message': 'this is message 2' }" registry_manager.send_c2d_message(device_id, send_message, { "contentType": "application/json", "prop1": "value1" }) # Send 2nd Message To Device with property send_message = "Sending c2d message 3" registry_manager.send_c2d_message(device_id, send_message, properties={ "prop1": "value1", "correlationId": "1234"
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- import sys import os from azure.iot.hub import IoTHubRegistryManager connection_str = os.getenv("IOTHUB_CONNECTION_STRING") device_id = os.getenv("IOTHUB_DEVICE_ID") send_message = "C2D message to be send to device" try: # Create IoTHubRegistryManager registry_manager = IoTHubRegistryManager(connection_str) print("Conn String: {0}".format(connection_str)) # Send Message To Device registry_manager.send_c2d_message(device_id, send_message) except Exception as ex: print("Unexpected error {0}".format(ex)) except KeyboardInterrupt: print("iothub_statistics stopped")
def main(msg: func.ServiceBusMessage): registry_manager = IoTHubRegistryManager( os.environ.get('iothubConnectionString')) # Get message from service bus inputMsg = json.loads(msg.get_body().decode('utf-8')) # Update connection string information host = os.environ.get('postgreSQL_host') dbname = os.environ.get('postgreSQL_dbname') user = os.environ.get('postgreSQL_user') password = os.environ.get('postgreSQL_password') sslmode = "require" conn_string = "host={0} user={1} dbname={2} password={3} sslmode={4}".format( host, user, dbname, password, sslmode) conn = psycopg2.connect(conn_string) cursor = conn.cursor() # Create table if there's no table for the device cursor.execute( "CREATE TABLE IF NOT EXISTS %s (id SERIAL PRIMARY KEY, a float, b float, c float, d float, \ e float, f float, y float, date_time TIMESTAMP);" % inputMsg['deviceID']) filename1 = str(uuid.uuid4()) currentData = np.array([[ inputMsg['a'], inputMsg['b'], inputMsg['c'], inputMsg['d'], inputMsg['e'], inputMsg['f'] ]]) pickle.dump(currentData.reshape(-1, 6), open(filename1 + '.sav', 'wb')) r = requests.post('https://oshpoctrf.azurewebsites.net/api/oshpociot6', files={'files': open(filename1 + '.sav', 'rb')}) df1 = pd.read_json(r.text) day0_y = df1[0]["result"] os.remove(filename1 + '.sav') cursor.execute("INSERT INTO %s (a, b, c, d, e, f, y, date_time) VALUES (%f, %f, %f, %f, %f, %f, %f, CURRENT_TIMESTAMP);" \ % (inputMsg['deviceID'], inputMsg['a'], inputMsg['b'], inputMsg['c'], inputMsg['d'], inputMsg['e'], inputMsg['f'], day0_y)) cursor.execute("SELECT (y) FROM %s ORDER BY id DESC LIMIT 5;" % inputMsg['deviceID']) # Counting current rows, if rows < 4 then no serial predict data produce cursor.execute("SELECT COUNT(id) FROM %s;" % inputMsg['deviceID']) if cursor.fetchall()[0][0] > 4: # Get previous y data cursor.execute( "SELECT (y) FROM %s ORDER BY id DESC LIMIT 4 OFFSET 1;" % inputMsg['deviceID']) timeSeriesData = cursor.fetchall() day1_y = timeSeriesData[0][0] day2_y = timeSeriesData[1][0] day3_y = timeSeriesData[2][0] day4_y = timeSeriesData[3][0] timeSeriesData_array = np.array( [[[day0_y, day1_y, day2_y, day3_y, day4_y], [day0_y, day1_y, day2_y, day3_y, day4_y], [day0_y, day1_y, day2_y, day3_y, day4_y]]]) filename2 = str(uuid.uuid4()) pickle.dump(timeSeriesData_array.reshape(-1, 3, 5), open(filename2 + '.sav', 'wb')) r = requests.post( 'https://oshpoctrf.azurewebsites.net/api/Timeseries_RF', files={'files': open(filename2 + '.sav', 'rb')}) df2 = pd.read_json(r.text) os.remove(filename2 + '.sav') registry_manager.send_c2d_message( inputMsg['deviceID'], "\n" + inputMsg['deviceID'] + "\ny: " + str(day0_y) + "\n\nTime series data\n" + str(df2)) else: registry_manager.send_c2d_message( inputMsg['deviceID'], "\n" + inputMsg['deviceID'] + "\ny: " + str(day0_y) + "\ndata not enough for time series data") # Clean up conn.commit() cursor.close() conn.close() logging.info('Python ServiceBus queue trigger processed message: %s', msg.get_body().decode('utf-8'))