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 iot_device_updatetelemetry_interval(): # Try-except in use as webservice may fail try: # Create registry manager registry_manager = IoTHubRegistryManager(connection_string) # Call the direct method device_method = CloudToDeviceMethod(method_name=method_name, payload=method_payload) device_response = registry_manager.invoke_device_method( device_id, device_method) # Provide feedback to user print("") print("Device Method Called") print("Device Method Name : {0}".format(method_name)) print("Device Method Payload : {0}".format(method_payload)) print("Device Response") print("Response Status : {0}".format(device_response.status)) print("Response Payload : {0}".format(device_response.payload)) # Allow user to close service connection input("Press Enter to continue ...\n") except Exception as ex: print("Unexpected error") return except KeyboardInterrupt: print("Device Instruction stopped")
def iothub_devicemethod_sample_run( callback_method: str = "start_fan", callback_payload: dict = {}, ): """Simulate a cloud-to-device message to an IoT device to run a method. Args: callback_method (str, optional): Function that will be called on the IoT Device. Defaults to `start_fan`. callback_payload (dict, optional): additional data that can be processed by the IoT Device. Defaults to `{}`. """ try: # Create IoTHubRegistryManager registry_manager = IoTHubRegistryManager(CONNECTION_STRING) # Call the direct method. deviceMethod = CloudToDeviceMethod(method_name=callback_method, payload=callback_payload) response = registry_manager.invoke_device_method( DEVICE_ID, deviceMethod) print("") print("Device Method called") print("Device Method name : {0}".format(callback_method)) print("Device Method payload : {0}".format(callback_payload)) print("") print("Response status : {0}".format(response.status)) print("Response payload : {0}".format(response.payload)) input("Press Enter to continue...\n") except KeyboardInterrupt: print("") print("IoTHubDeviceMethod sample stopped")
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 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 call_method(method_name, param): # Create IoTHubRegistryManager registry_manager = IoTHubRegistryManager(CONNECTION_STRING) # Call the direct method. deviceMethod = CloudToDeviceMethod(method_name=method_name, payload=param) response = registry_manager.invoke_device_method(DEVICE_ID, deviceMethod)
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 main(msg: func.ServiceBusMessage): """When a message arrives on the servicebus, send a trigger to IoT Hub to start the fan for that device. Args: msg (func.ServiceBusMessage): Message from the connected Queue in a Azure ServiceBus """ # Extract the method into a dictionary msg_dict = json.loads(msg.get_body().decode("utf-8")) logging.info( f"Python ServiceBus queue trigger processed message: {msg_dict}") # Enable a connection with the IoT Hub. The connectionstring for the IoT Hub # is preloaded in the Azure Functions configurations. connectino_string_iothub = os.getenv("connectionStringIotHub") registry_manager = IoTHubRegistryManager(connectino_string_iothub) # Settings for the method that the IoT Device should run upon receiving the message. callback_method = "start_fan" callback_payload = {} device_method = CloudToDeviceMethod(method_name=callback_method, payload=callback_payload) # Sending the actual cloud-to-device message and invoke a function on the IoT device. device_id = msg_dict["IoTHub"]["ConnectionDeviceId"] response = registry_manager.invoke_device_method(device_id, device_method) print("") print("Device Method called") print("Device Method name : {0}".format(callback_method)) print("Device Method payload : {0}".format(callback_payload)) print("") print("Response status : {0}".format(response.status)) print("Response payload : {0}".format(response.payload))
def iothub_devicemethod_sample_run(): try: # Create IoTHubRegistryManager registry_manager = IoTHubRegistryManager(CONNECTION_STRING) # Call the direct method. deviceMethod = CloudToDeviceMethod(method_name=METHOD_NAME, payload=METHOD_PAYLOAD) response = registry_manager.invoke_device_method(DEVICE_ID, deviceMethod) print ( "" ) print ( "Device Method called" ) print ( "Device Method name : {0}".format(METHOD_NAME) ) print ( "Device Method payload : {0}".format(METHOD_PAYLOAD) ) print ( "" ) print ( "Response status : {0}".format(response.status) ) print ( "Response payload : {0}".format(response.payload) ) input("Press Enter to continue...\n") except Exception as ex: print ( "" ) print ( "Unexpected error {0}".format(ex) ) return except KeyboardInterrupt: print ( "" ) print ( "IoTHubDeviceMethod sample stopped" )
def __init__(self, ioThubConnectionString, deviceId, moduleId, operationsApiVersion): self._iotHubConnStr = ioThubConnectionString self._deviceId = deviceId self._moduleId = moduleId self._apiVersion = operationsApiVersion self._registryManager = IoTHubRegistryManager(self._iotHubConnStr)
def __init__(self): if is_edge(): self.registry_manager = IoTHubRegistryManager( IOTHUB_CONNECTION_STRING) else: self.registry_manager = None self.device_id = DEVICE_ID self.module_id = MODULE_ID
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 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 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 create_remote_device_adapter(device_name, iot_device_name): registry_manager = IoTHubRegistryManager(connection_string=connection_string) try: iot_device = registry_manager.get_device(device_id=iot_device_name) except Exception as ex: iot_device = registry_manager.create_device_with_certificate_authority(device_id=iot_device_name, status="enabled") remote_device_properties = RemoteDeviceAdapterProperties(target=RemoteDeviceAdapterTarget(host="camerasimulator"), iot_hub_device_connection=IotHubDeviceConnection(device_id=iot_device_name,credentials=SymmetricKeyCredentials(key=iot_device.authentication.symmetric_key))) return RemoteDeviceAdapter(name=device_name, properties=remote_device_properties)
def invoke_method_helper(method): direct_method = CloudToDeviceMethod(method_name=method.method_name, payload=method.serialize()) registry_manager = IoTHubRegistryManager(connection_string) payload = registry_manager.invoke_device_module_method(device_id, module_d, direct_method).payload if payload is not None and 'error' in payload: print(payload['error']) return None return payload
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 __init__(self): self.device_id = getenv(constants.device_id) self.device_tag = getenv(constants.device_tag) self.tag_value = getenv(constants.tag_value) self.module_id = getenv(constants.module_id) self.api_version = constants.topology_api_version self.registry_manager = IoTHubRegistryManager(getenv(constants.iot_connection_string)) if self.device_id is None: self.device_list = self.get_device_list()
def get_azure_client(): connection_string = get_connection_string() azure_iot_hub_mock = os.environ.get("AZURE_IOTHUB_MOCK") if azure_iot_hub_mock: client = IoTHubRegistryManager( connection_string=connection_string, host="mock_host", token_credential="test_token", ) client.protocol.config.connection.verify = False return client return IoTHubRegistryManager.from_connection_string(connection_string)
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 __init__(self): config_data = pathlib.Path('appsettings.json').read_text() config = json.loads(config_data) self.device_id = config['deviceId'] self.module_id = config['moduleId'] self.registry_manager = IoTHubRegistryManager(config['IoThubConnectionString']) self.rtsp_url = config['rtspUrl'] self.printColors = { 'yellow': '\033[93m {}\033[00m', 'green': '\033[92m {}\033[00m', 'red': '\033[91m {}\033[00m' }
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 __init__(self): if is_edge(): try: self.registry_manager = IoTHubRegistryManager( IOTHUB_CONNECTION_STRING) except: logger.warning( 'IoTHub authentication failed. The server will terminate in 10 seconds.') time.sleep(10) sys.exit(-1) else: self.registry_manager = None self.device_id = DEVICE_ID self.module_id = MODULE_ID
def create_devices_and_find_endpoints(stations): ''' Creates all stations that currently do not exist in the IoT Hub as new devices. Adds 'hub_endpoint' attribute to all stations (no matter whether it already exists in the hub or not) which can be used to send messages to the stations ''' # TODO: make create_and_get_devices indepentent of stations to allow reusing it in other iot use cases connection_string = os.getenv("IOT_HUB_CONNECTION_STRING") host = os.getenv("IOT_HUB_HOSTNAME") try: iot_manager = IoTHubRegistryManager(connection_string) # note that 'get_devices() only works for cnt of devices <= 1000, # otherwise querying keys is more complex AND time consuming dev_list = iot_manager.get_devices() # convert list to dict for easy access devices = { dev_list[i].device_id: dev_list[i] for i in range(0, len(dev_list)) } del dev_list new_devices = [] for station in stations.values(): device_name = station.get('station_name', station.get('station_id', '')) device = devices.get(device_name, None) if device != None: # if device already exists, only add its endpoint to the station station['hub_endpoint'] = get_endpoint_uri( host, device_name, device.authentication.symmetric_key.primary_key) else: # otherwise create device object and add its endpoint to station # the actual creation of the device in the hub happens at the end in a bulk new_device, new_endpoint = create_device(device_name, host) station['hub_endpoint'] = new_endpoint new_devices.append(new_device) # splitting operations in chunks prevents to large messages # that raise exceptions insert_chunks = chunks(new_devices, __CHUNK_SIZE) for chunk in insert_chunks: iot_manager.bulk_create_or_update_devices(chunk) except Exception as ex: print("Unexpected error {0}".format(ex))
def get_iot(): """get iot""" try: iot = IoTHubRegistryManager(IOT_HUB_CONNECTION_STRING) except: iot = None return iot
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 __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 delete_all_devices(): ''' Deletes all devices in the Azure IoT Hub. This function is not used in the Azure Function but can be useful, if you want to reset the Azure Environment. ''' connection_string = os.getenv("IOT_HUB_CONNECTION_STRING") iot_manager = IoTHubRegistryManager(connection_string) dev_list = iot_manager.get_devices() delete_list = [] for d in dev_list: dev = ExportImportDevice(id=d.device_id) dev.import_mode = "delete" delete_list.append(dev) # splitting operations in chunks prevents to large messages # that raise exceptions del_chunks = chunks(delete_list, __CHUNK_SIZE) for chunk in del_chunks: iot_manager.bulk_create_or_update_devices(chunk)
def stdin_listener(): iothub_registry_manager = IoTHubRegistryManager( IOTHUB_CONNECTION_STRING) twin = iothub_registry_manager.get_twin(DEVICE_ID) while True: selection = input("Q: quit, F: forward, S: stop/free\n") if selection == "Q" or selection == "q": print("Quitting...") break elif selection == "F" or selection == "f": twin_patch = Twin(properties=TwinProperties( desired={'command': 'forward'})) twin = iothub_registry_manager.update_twin( DEVICE_ID, twin_patch, twin.etag) elif selection == "S" or selection == "s": twin_patch = Twin(properties=TwinProperties( desired={'command': 'stop'})) twin = iothub_registry_manager.update_twin( DEVICE_ID, twin_patch, twin.etag)