示例#1
0
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 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 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 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)
示例#5
0
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 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
    async def send_message(self, message, device_id, module_id, method_name):
        payload = {"body": json.loads(message.data), "properties": message.custom_properties}
        module_method = CloudToDeviceMethod(
            method_name=method_name,
            payload=payload,
            response_timeout_in_seconds=30)

        print("Invoking message called")
        resp = self.registry_manager.invoke_device_module_method(device_id, module_id, module_method)
        if resp.payload is not None:
            print(json.dumps(resp.payload))
示例#8
0
def invoke_device_method() -> str:
    print("Validating item...")

    # Create a method call with a long response time to allow the image classifier to run
    deviceMethod = CloudToDeviceMethod(method_name="ValidateItem", response_timeout_in_seconds=30, connect_timeout_in_seconds=30)

    # Invoke the method on the device
    method_result = registry_manager.invoke_device_method(device_id, deviceMethod)

    # Return the result from the method call
    return method_result.payload['Result']
def create_method_job_request():
    job = JobRequest()
    job.job_id = "methodJob-" + str(uuid.uuid4())
    job.type = "scheduleDeviceMethod"
    job.cloud_to_device_method = CloudToDeviceMethod(
        method_name="test_method",
        payload={"key": "value"},
        response_timeout_in_seconds=30,
        connect_timeout_in_seconds=15,
    )
    job.start_time = datetime.datetime.utcnow().isoformat()
    job.max_execution_time_in_seconds = 60
    job.query_condition = "*"
    return job
示例#10
0
 def invoke_method(self, method_name, payload):
     mutex.acquire()
     try:
         module_method = CloudToDeviceMethod(method_name=method_name,
                                             payload=payload,
                                             response_timeout_in_seconds=30)
         res = self.registry_manager.invoke_device_module_method(
             self.device_id, self.module_id, module_method)
         mutex.release()
         return res.as_dict()
     except:
         mutex.release()
         print("[ERROR] Failed to invoke direct method:",
               sys.exc_info(),
               flush=True)
         return {'error': 'failed to invoke direct method'}
 def invoke_method(self, method_name, payload):
     if not self.registry_manager:
         print("[WARNING] Not int edge evironment, ignore direct message",
               flush=True)
     mutex.acquire()
     try:
         module_method = CloudToDeviceMethod(method_name=method_name,
                                             payload=payload,
                                             response_timeout_in_seconds=30)
         res = self.registry_manager.invoke_device_module_method(
             self.device_id, self.module_id, module_method)
         mutex.release()
         return res.as_dict()
     except:
         mutex.release()
         print("[ERROR] Failed to invoke direct method:",
               sys.exc_info(),
               flush=True)
         return {"error": "failed to invoke direct method"}
示例#12
0
    def invoke_module_method(self, method):
        # Get the name of the Direct Method
        method_name =  method.method_name
        # Get the payload of the Direct Method
        payload = method.serialize()
        direct_method = CloudToDeviceMethod(method_name=method_name, payload=payload)
        
        print(self.printColors['green'].format("\n-----------------------  Request: %s  --------------------------------------------------\n" % method_name))
        print(json.dumps(payload, indent=4))
        
        # Invoke the Direct Method
        resp = self.registry_manager.invoke_device_module_method(self.device_id, self.module_id, direct_method)
        
        print(self.printColors['green'].format("\n---------------  Response: %s - Status: %s  ---------------\n" % (method_name, resp.status)))

        # Check if the execution was successful and print out the payload (if available)
        if resp.payload is not None and 'error' in resp.payload:
            raise Exception(json.dumps(resp.payload['error'], indent=4))
        elif resp.payload is not None:
            print(json.dumps(resp.payload, indent=4))
示例#13
0
    def invoke_module_method(self, method_name, payload):
        # make sure '@apiVersion' has been set
        payload['@apiVersion'] = self.api_version

        module_method = CloudToDeviceMethod(
            method_name=method_name,
            payload=payload,
            response_timeout_in_seconds=30)

        device_id = self.device_id
        try:
            if device_id is None:
                for device in self.device_list:
                    device_id = device.device_id
                    self.invoke_device_module_method(device_id, method_name, module_method, payload)
            else:
                self.invoke_device_module_method(device_id, method_name, module_method, payload)

        except Exception as ex:
            if ex.response.status_code == 404:
                print(">>>>>>>>>> Warning: device '%s' does not have the '%s' module deployed, or the module has not yet initalized <<<<<<<<<<" %
                      (device_id, self.module_id))
device_id = os.getenv("IOTHUB_DEVICE_ID")
module_id = os.getenv("IOTHUB_MODULE_ID")
method_name = "lockDoor"
method_payload = "now"

try:
    # RegistryManager
    iothub_registry_manager = IoTHubRegistryManager.from_connection_string(
        iothub_connection_str)

    # Create Module
    primary_key = "aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnoo"
    secondary_key = "111222333444555666777888999000aaabbbcccdddee"
    managed_by = ""
    new_module = iothub_registry_manager.create_module_with_sas(
        device_id, module_id, managed_by, primary_key, secondary_key)

    deviceMethod = CloudToDeviceMethod(method_name=method_name,
                                       payload=method_payload)
    iothub_registry_manager.invoke_device_module_method(
        device_id, module_id, deviceMethod)

    # Delete Module
    iothub_registry_manager.delete_module(device_id, module_id)
    print("Deleted Module {0}".format(module_id))

except Exception as ex:
    print("Unexpected error {0}".format(ex))
except KeyboardInterrupt:
    print("IoTHubRegistryManager sample stopped")
示例#15
0
 def InvokeModuleMethod(self, methodName, payload):
     moduleMethod = CloudToDeviceMethod(method_name=methodName,
                                        payload=payload)
     return self._registryManager.invoke_device_module_method(
         self._deviceId, self._moduleId, moduleMethod)