예제 #1
0
def FW_updater_listener(device_client):
    while True:
        method_request = device_client.receive_method_request("FW_Update")
        fw_info_from_method = method_request.payload
        print(
            str(datetime.datetime.now()),
            "Received Firmware Upgrade Request: Version" +
            str(fw_info_from_method) + ", Initialiazing...")
        time.sleep(2)
        if fw_info >= fw_info_from_method:
            payload = {
                "result":
                False,
                "data": ("The Firmware Version Now is " + str(fw_info) +
                         ", Update Cancelled")
            }
            status = 403  # set return status code
            print(
                str(datetime.datetime.now()),
                "The Firmware Version is Latest, Firmware Upgrade Cancelled")
            method_response = MethodResponse.create_from_method_request(
                method_request, status, payload)
            # send response
            device_client.send_method_response(method_response)
        if fw_info < fw_info_from_method:
            payload = {
                "result":
                True,
                "data": ("The Firmware Version Now is " + str(fw_info) +
                         ", Update Task Now Begin...")
            }
            status = 200  # set return status code
            method_response = MethodResponse.create_from_method_request(
                method_request, status, payload)
            # send response
            device_client.send_method_response(method_response)
            print(str(datetime.datetime.now()),
                  "Step 1: New Firmware Version " + str(fw_info_from_method),
                  "is Set, Firmware Downloading...")
            time.sleep(2)
            print(str(datetime.datetime.now()),
                  "Step 2: Downloading Success, Validation Firmware file...")
            time.sleep(2)
            print(
                str(datetime.datetime.now()),
                "Step 3: Firmware Validation Passed, Start Firmware Upgrading..."
            )
            time.sleep(2)
            print(str(datetime.datetime.now()),
                  "Step 4: Upgrading Sucessful, Rebooting Device...")
            time.sleep(2)
            print(str(datetime.datetime.now()),
                  "Step 5: Device Successful Reconnected !!!")
 async def method_handler(method_request):
     if method_request.name == "get_data":
         print("Received request for data")
         method_response = MethodResponse.create_from_method_request(
             method_request, 200, "some data")
         await client.send_method_response(method_response)
     else:
         print("Unknown method request received: {}".format(
             method_request.name))
         method_response = MethodResponse.create_from_method_request(
             method_request, 400, None)
         await client.send_method_response(method_response)
async def direct_method_handler(method_request):
    print(f'executing direct method: {method_request.name}({method_request.payload})')

    if method_request.name == 'speak_to_me':
        # speaks the message via the Raspberry Pi onboard sound
        # plug in a pair of headphones to the 3.5mm jack to hear
        # uses espeak, install on the Pi with 'sudo apt install espeak'
        os.system(f'espeak "{method_request.payload}"')
        # send response - echo back the sent text message
        method_response = MethodResponse.create_from_method_request(method_request, 200, method_request.payload)
    else:
        # send bad request status code
        method_response = MethodResponse.create_from_method_request(method_request, 400, 'unknown command')

    await client.send_method_response(method_response)
예제 #4
0
async def direct_method_handler(device_client):
    while not terminate:
        method_request = (
            await device_client.receive_method_request()
        )  # Wait for unknown method calls
        print("executing direct method: %s(%s)" % (method_request.name, method_request.payload))

        method_response = None
        if method_request.name == "echo":
            # send response - echo back the payload
            method_response = MethodResponse.create_from_method_request(method_request, 200, method_request.payload)
        else:
            # send bad request status code
            method_response = MethodResponse.create_from_method_request(method_request, 400, "unknown command")

        await device_client.send_method_response(method_response)
예제 #5
0
async def command_listener(device_client):
    # Loop forever waiting for commands
    while True:
        # Wait for commands from IoT Central
        method_request = await device_client.receive_method_request("TooBright"
                                                                    )

        # Log that the command was received
        timestamp = datetime.strptime(
            datetime.now().strftime('%Y-%m-%d %H:%M %S'), '%Y-%m-%d %H:%M %S')
        print(timestamp, end='')
        print(" Too Bright Command handled")

        # Asynchronously light the LED
        # This will be run in the background, so the result can
        # be returned to IoT Central straight away, not 10 seconds later
        asyncio.gather(light_led(LED1, 10))

        # IoT Central expects a response from a command, saying if the call
        # was successful or not, so send a success response
        payload = {"result": True}

        # Build the response
        method_response = MethodResponse.create_from_method_request(
            method_request, 200, payload)

        # Send the response to IoT Central
        await device_client.send_method_response(method_response)
예제 #6
0
    def cloud_to_device_listener(self):
        """Listens in a seperate thread to incoming cloud-to-device requests. 
        
        Can fire methods on the Raspberry Pi locally, e.g. `self.start_fan` or `self.set_telemetry_interval`
        
        """
        while True:

            method_request = self.client.receive_method_request()
            print(
                f"\nMethod callback called with:\nmethodName = {method_request.name}\npayload = {method_request.payload}"
            )

            # Case switch for different methods that can be called from the cloud
            if method_request.name == "start_fan":
                response_status, response_payload = self.start_fan()
            elif method_request.name == "set_telemetry_interval":
                response_status, response_payload = self.set_telemetry_interval(
                    **method_request.payload)
            else:
                response_payload = {
                    "Response":
                    "Direct method {} not defined".format(method_request.name)
                }
                response_status = 404
            method_response = MethodResponse(method_request.request_id,
                                             response_status,
                                             payload=response_payload)
            self.client.send_method_response(method_response)
def method_listener(device_client):
    while True:
        method_request = device_client.receive_method_request(
            "Write_Value")  # Wait for method1 calls
        decoded_method = method_request.payload
        print(type(decoded_method))
        print("Writing message to RTU:", decoded_method)
        #判断数据类型执行写入操作
        if isinstance(decoded_method, dict):
            tty_client.write(json.dumps(decoded_method).encode())
        elif isinstance(decoded_method, int):
            tty_client.write(decoded_method)
        elif isinstance(decoded_method, float):
            byte = pack('d', decoded_method)
            tty_client.write(byte)
        else:
            tty_client.write(decoded_method.encode())
        payload = {
            "result": True,
            "data": "Write to RTU Successfully"
        }  # set response payload
        status = 200  # set return status code
        method_response = MethodResponse.create_from_method_request(
            method_request, status, payload)
        device_client.send_method_response(method_response)  # send response
예제 #8
0
        async def method_request_handler(method_request):
            payload = {
                "result": True,
                "data": "There is no direct method current."
            }  # set response payload
            status = 200  # set return status code
            print("invoked method: " + method_request.name)
            if method_request.name == "ShellCommandExecute":
                if "command" in method_request.payload and "args" in method_request.payload:
                    commandStr = method_request.payload["command"]
                    argsStr = method_request.payload["args"]
                    proc = subprocess.run("{} {}".format(commandStr, argsStr),
                                          shell=True,
                                          stdout=PIPE)
                    payload = {"result": str(proc.stdout)}
                else:
                    payload = {
                        "request":
                        "bad payload. command and args are necessary!"
                    }
                    status = 400

            print("invoked method: " + method_request.name)
            # Send the response
            method_response = MethodResponse.create_from_method_request(
                method_request, status, payload)
            await module_client.send_method_response(method_response)
예제 #9
0
def device_method_listener(device_client):
    global message_interval
    while True:
        # Receive method
        changed = False
        method_request = device_client.receive_method_request()
        print ('methodName = {}, payload = {}'.format(method_request.name, method_request.payload))
        if method_request.name == "SetTelemetryInterval":
            try:
                message_interval = int(method_request.payload)
                response_payload = {"Response": "Executed direct method {}".format(method_request.name)}
                response_status = 200
                changed = True
            except ValueError:
                response_payload = {"Response": "Invalid parameter"}
                response_status = 400
        else:
            response_payload = {"Response": "Direct method {} not defined".format(method_request.name)}
            response_status = 404
        # Response method
        method_response = MethodResponse(method_request.request_id, response_status, payload=response_payload)
        device_client.send_method_response(method_response)
        # Report
        if changed:
            reported_patch = {"telemetryInterval": message_interval}
            device_client.patch_twin_reported_properties(reported_patch)
예제 #10
0
def cloud_message_listener_thread(device_client, loop, device_name):
    async def receive_data(request):
        global RECEIVED_MESSAGES
        logging.info(f"device name {device_name} is : {request.payload}")
        RECEIVED_MESSAGES += 1
        logging.debug(f"mac_device_client details: {mac_device_client}")
        request.payload["mac"] = device_name.replace('_', ':')
        logging.debug(f"updated request payload: {request.payload}")
        await applicationDataRouter.application_data_router(
            request.payload, mac_appname_dict,
            routing_app_table)  #send payload to application data router
        logging.info(f"Total response published  {RECEIVED_MESSAGES}")

    while True:
        try:
            #Receive data from cloud
            method_request = loop.run_until_complete(
                device_client.receive_method_request())  # Wait for commands
            logging.info(
                f"Method request name from Iot Central: {method_request.name}")
        except Exception as e:
            logging.warning(f"error wile receiving message from cloud: {e}")

        try:
            #creating a response to be sent to Iot Hub
            response = MethodResponse.create_from_method_request(
                method_request, status=202)
            loop.run_until_complete(
                device_client.send_method_response(response))  # send response
        except Exception as e:
            logging.warning(f"Unable to send response to cloud: {e}")

        loop.run_until_complete(receive_data(method_request))
예제 #11
0
def device_method_listener(device_client):
    global INTERVAL
    while True:
        method_request = device_client.receive_method_request()
        print(
            "\nMethod callback called with:\nmethodName = {method_name}\npayload = {payload}"
            .format(method_name=method_request.name,
                    payload=method_request.payload))
        if method_request.name == "SetTelemetryInterval":
            try:
                INTERVAL = int(method_request.payload)
            except ValueError:
                response_payload = {"Response": "Invalid parameter"}
                response_status = 400
            else:
                response_payload = {
                    "Response":
                    "Executed direct method {}".format(method_request.name)
                }
                response_status = 200
        else:
            response_payload = {
                "Response":
                "Direct method {} not defined".format(method_request.name)
            }
            response_status = 404

        method_response = MethodResponse(method_request.request_id,
                                         response_status,
                                         payload=response_payload)
        device_client.send_method_response(method_response)
예제 #12
0
def device_method_listener(device_client):
    while True:
        method_request = device_client.receive_method_request()

        if method_request.name == "TakePicture":
            try:
                #Example how to read the payload content
                #payload = method_request.payload

                take_picture(camera_instance)
                send_telemetry(device_client)
            except ValueError:
                response_payload = {"Response": "Invalid parameter"}
                response_status = 400
            else:
                response_payload = {
                    "Response":
                    "Executed direct method {}".format(method_request.name)
                }
                response_status = 200
        else:
            response_payload = {
                "Response":
                "Direct method {} not defined".format(method_request.name)
            }
            response_status = 404

        method_response = MethodResponse(method_request.request_id,
                                         response_status,
                                         payload=response_payload)
        device_client.send_method_response(method_response)
    async def command_listener(device_client):
        while True:
            method_request = await device_client.receive_method_request()

            print('Call made to', method_request.name)

            colour = method_request.payload
            
            print('payload', colour)

            if isinstance(colour, dict):
                colour = colour['colour']

            print('payload2', colour)

            set_colour(colour)

            payload = {'result': True, 'data': colour}
            method_response = MethodResponse.create_from_method_request(
                method_request, 200, payload
            )
            await device_client.send_method_response(method_response)

            # Write the colour back as a property
            await device_client.patch_twin_reported_properties({'colour':colour})
예제 #14
0
async def execute_command_listener(
    device_client, method_name, user_command_handler, create_user_response_handler
):
    while True:
        if method_name:
            command_name = method_name
        else:
            command_name = None

        command_request = await device_client.receive_method_request(command_name)
        print("Command request received with payload")
        print(command_request.payload)

        values = {}
        if not command_request.payload:
            print("Payload was empty.")
        else:
            values = command_request.payload

        await user_command_handler(values)

        response_status = 200
        response_payload = create_user_response_handler(values)

        command_response = MethodResponse.create_from_method_request(
            command_request, response_status, response_payload
        )

        try:
            await device_client.send_method_response(command_response)
        except Exception:
            print("responding to the {command} command failed".format(command=method_name))
    async def method_request_handler(method_request):
        # Determine how to respond to the method request based on the method name
        if method_request.name == "method1":
            payload = {
                "result": True,
                "data": "some data"
            }  # set response payload
            status = 200  # set return status code
            print("executed method1")
        elif method_request.name == "method2":
            payload = {"result": True, "data": 1234}  # set response payload
            status = 200  # set return status code
            print("executed method2")
        else:
            payload = {
                "result": False,
                "data": "unknown method"
            }  # set response payload
            status = 400  # set return status code
            print("executed unknown method: " + method_request.name)

        # Send the response
        method_response = MethodResponse.create_from_method_request(
            method_request, status, payload)
        await device_client.send_method_response(method_response)
def device_method_listener(device_client):
    while True:
        method_request = device_client.receive_method_request()
        print (
            "\nMethod callback called with:\nmethodName = {method_name}\npayload = {payload}".format(
                method_name=method_request.name,
                payload=method_request.payload
            )
        )
        # On appelle la bonne méthode qui correspond à l'action
        if method_request.name == "CloseBlinds":
            try:
                room = method_request.payload
                close_blinds(room)
            except ValueError:
                response_payload = {"Response": "Invalid parameter"}
                response_status = 400
            else:
                response_payload = {"Response": "Executed direct method {}".format(method_request.name)}
                response_status = 200

        elif method_request.name == "OpenBlinds":
            try:
                room = method_request.payload
                open_blinds(room)
            except ValueError:
                response_payload = {"Response": "Invalid parameter"}
                response_status = 400
            else:
                response_payload = {"Response": "Executed direct method {}".format(method_request.name)}
                response_status = 200

        elif method_request.name == "IncreaseTemp":
            try:
                room = method_request.payload
                increase_temp(room)
            except ValueError:
                response_payload = {"Response": "Invalid parameter"}
                response_status = 400
            else:
                response_payload = {"Response": "Executed direct method {}".format(method_request.name)}
                response_status = 200

        elif method_request.name == "DecreaseTemp":
            try:
                room = method_request.payload
                decrease_temp(room)
            except ValueError:
                response_payload = {"Response": "Invalid parameter"}
                response_status = 400
            else:
                response_payload = {"Response": "Executed direct method {}".format(method_request.name)}
                response_status = 200
        
        else:
            response_payload = {"Response": "Direct method {} not defined".format(method_request.name)}
            response_status = 404

        method_response = MethodResponse(method_request.request_id, response_status, payload=response_payload)
        device_client.send_method_response(method_response)
예제 #17
0
    async def command_listener(device_client):
        while True:
            method_request = await device_client.receive_method_request()

            print('Call made to', method_request.name)

            payload = method_request.payload
            
            print('payload', payload)

            try:
                parsed = json.loads(payload)
                payload = parsed
            except:
                pass

            print('parsed payload', payload)

            await set_color(payload)

            response_payload = {'result': True, 'data': payload}
            method_response = MethodResponse.create_from_method_request(
                method_request, 200, response_payload
            )
            await device_client.send_method_response(method_response)

            # Write the color back as a property
            # encode the data as base64 as arrays are not supported in device twins
            json_string = json.dumps(payload)
            encoded = base64.b64encode(json_string.encode("utf-8")).decode('ascii')
            patch = {'encoded_color' : encoded}

            print('Patch:', patch)
            await device_client.patch_twin_reported_properties(patch)
    async def wait_for_method_and_return_response(self, methodName, requestAndResponse):
        # receive method request
        logger.info("Waiting for method request")
        request = await self.client.receive_method_request(methodName)
        logger.info("Method request received")

        # verify name and payload
        expected_name = methodName
        expected_payload = requestAndResponse.request_payload["payload"]
        if request.name == expected_name:
            if request.payload == expected_payload:
                logger.info("Method name and payload matched. Returning response")
                resp_status = requestAndResponse.status_code
                resp_payload = requestAndResponse.response_payload
            else:
                logger.info("Request payload doesn't match")
                logger.info("expected: " + expected_payload)
                logger.info("received: " + request.payload)
                resp_status = 500
                resp_payload = None
        else:
            logger.info("Method name doesn't match")
            logger.info("expected: '" + expected_name + "'")
            logger.info("received: '" + request.name + "'")
            resp_status = 404
            resp_payload = None

        # send method response
        response = MethodResponse(
            request_id=request.request_id, status=resp_status, payload=resp_payload
        )
        await self.client.send_method_response(response)
        logger.info("Method response sent")
예제 #19
0
    async def process_request(self, command_request):
        try:
            if command_request.name == "turnValveOn":
                user_command_handler=turn_valve_on_handler
                create_user_response_handler=turn_valve_on_response
            elif command_request.name == "turnValveOff":
                user_command_handler=turn_valve_off_handler
                create_user_response_handler=turn_valve_off_response
            else:
                print ("Unknown command: {0}".format(command_request.name))
                return
            print ("Processing command: {0}".format(command_request.name))

            values = {}
            if command_request.payload:
                values = command_request.payload

            await user_command_handler(self.__iot_device, values)

            response_status = 200
            response_payload = await create_user_response_handler(self.__iot_device, self.__device_client, values)

            command_response = MethodResponse.create_from_method_request(
                command_request, response_status, response_payload
            )

            await self.__device_client.send_method_response(command_response)
        except Exception as e:
            print("responding to the {command} command failed with {excep}".format(command=command_request.name, excep=e))
 def direct_method_listener(module_client, param_lock):
     while True:
         try:
             print("waiting for method invocation...")
             methodRequest = module_client.receive_method_request()
             print("received method invocation - '{}'({})".format(
                 methodRequest.name, methodRequest.payload))
             response = {}
             response_status = 200
             if methodRequest.name == "ShowText":
                 stShowText(methodRequest.payload, param_lock)
             elif methodRequest.name == "ShowImage":
                 stShowImage(methodRequest.payload, param_lock)
             elif methodRequest.name == "SetOptions":
                 stSetOptions(methodRequest.payload, param_lock)
             elif methodRequest.name == "Clear":
                 stClear(methodRequest.payload, param_lock)
             else:
                 response['message'] = "bad method name"
                 response_status = 404
             response = MethodResponse(methodRequest.request_id,
                                       response_status,
                                       payload=response)
             module_client.send_method_response(response)
         except Exception as error:
             print("exception happens - {}".format(error))
예제 #21
0
async def command_handler(method_request):
    print("Message received:", method_request.name)
    print("Message payload:", method_request.payload)

    # Determine how to respond to the command based on the IoT Hub direct method method name
    # which is the same as the IoT Central command name
    if method_request.name == "On":
        # For an On request, set the color based on the payload
        await set_color(method_request.payload)
        print("executed on")
    elif method_request.name == "Off":
        # For an Off request, set the color to 000000, which turns the pixels off
        await set_color("000000")
        print("executed off")
    else:
        print("Received unknown method: " + method_request.name)

    # Method calls have to return a response so IoT Central knows it was handled correctly,
    # So send a 200 response to show we handled this
    payload = {"result": True}
    status = 200

    # Send the response
    method_response = MethodResponse.create_from_method_request(method_request, status, payload)
    await device_client.send_method_response(method_response)
예제 #22
0
def method2_listener(device_client):
    while True:
        method_request = device_client.receive_method_request("method2")  # Wait for method2 calls
        payload = {"result": True, "data": 1234}  # set response payload
        status = 200  # set return status code
        print("executed method2")
        method_response = MethodResponse.create_from_method_request(method_request, status, payload)
        device_client.send_method_response(method_response)  # send response
예제 #23
0
 async def method_handler_shutdown(self, method_request):
     """Handle a shutdown request."""
     logger.debug("Shutting down because of method request, id: %s",
                  method_request.request_id)
     await self.send_method_response(
         MethodResponse.create_from_method_request(
             method_request, 200, payload={"shutdown": True}))
     self.shutdown_flag = True
예제 #24
0
def generic_method_listener(device_client):
    while True:
        method_request = device_client.receive_method_request()  # Wait for unknown method calls
        payload = {"result": False, "data": "unknown method"}  # set response payload
        status = 400  # set return status code
        print("executed unknown method: " + method_request.name)
        method_response = MethodResponse.create_from_method_request(method_request, status, payload)
        device_client.send_method_response(method_response)  # send response
예제 #25
0
async def execute_listener(
    device_client,
    component_name=None,
    method_name=None,
    user_command_handler=None,
    create_user_response_handler=None,
):
    """
    Coroutine for executing listeners. These will listen for command requests.
    They will take in a user provided handler and call the user provided handler
    according to the command request received.
    :param device_client: The device client
    :param component_name: The name of the device like "sensor"
    :param method_name: (optional) The specific method name to listen for. Eg could be "blink", "turnon" etc.
    If not provided the listener will listen for all methods.
    :param user_command_handler: (optional) The user provided handler that needs to be executed after receiving "command requests".
    If not provided nothing will be executed on receiving command.
    :param create_user_response_handler: (optional) The user provided handler that will create a response.
    If not provided a generic response will be created.
    :return:
    """
    while True:
        if component_name and method_name:
            command_name = component_name + "*" + method_name
        elif method_name:
            command_name = method_name
        else:
            command_name = None

        command_request = await device_client.receive_method_request(
            command_name)
        print("Command request received with payload")
        print(command_request.payload)

        values = pnp_helper.retrieve_values_dict_from_payload(command_request)

        if user_command_handler:
            await user_command_handler(values)
        else:
            print("No handler provided to execute")

        if method_name:
            response_status = 200
        else:
            response_status = 404
        if not create_user_response_handler:
            response_payload = pnp_helper.create_command_response_payload(
                method_name)
        else:
            response_payload = create_user_response_handler(values)
        command_response = MethodResponse.create_from_method_request(
            command_request, response_status, response_payload)

        try:
            await device_client.send_method_response(command_response)
        except Exception:
            print("responding to the {command} command failed".format(
                command=method_name))
예제 #26
0
 async def command_listener(device_client):
     global mode
     while True:
         method_request = await device_client.receive_method_request()
         payload = {'result': True, 'data': method_request.name}
         method_response = MethodResponse.create_from_method_request(
             method_request, 200, payload
         )
         await device_client.send_method_response(method_response)
예제 #27
0
 async def blink_command(request):
     print('Received synchronous call to blink')
     response = MethodResponse.create_from_method_request(
         request,
         status=200,
         payload={
             'description': f'Blinking LED every {request.payload} seconds'
         })
     await device_client.send_method_response(response)  # send response
     print(f'Blinking LED every {request.payload} seconds')
예제 #28
0
 async def method_handler(method_request):
     if method_request.name == "get_data":
         print("Received request for data")
         method_response = MethodResponse.create_from_method_request(
             method_request, 200, "some data")
         await module_client.send_method_response(method_response)
     elif method_request.name == "shutdown":
         print("Received request to shut down")
         method_response = MethodResponse.create_from_method_request(
             method_request, 200, None)
         await module_client.send_method_response(method_response)
         # Setting this event will cause client shutdown
         finished.set()
     else:
         print("Unknown method request received: {}".format(
             method_request.name))
         method_response = MethodResponse.create_from_method_request(
             method_request, 400, None)
         await module_client.send_method_response(method_response)
예제 #29
0
 async def coffeeoff_listener(device_client):
     while True:
         print("Wait for next coffeeoff method call")
         method_request = await device_client.receive_method_request(
             "coffeeoff")
         response = requests.get(url="http://myStrom-Coffee/relay?state=0")
         payload = {"result": response.ok}
         status = 200
         method_response = MethodResponse.create_from_method_request(
             method_request, status, payload)
         await device_client.send_method_response(method_response)
         print("Executed coffeeoff")
예제 #30
0
async def get_plant_metrics_command(device_client, method_request):
    # method_request = await device_client.receive_method_request(
    #     "get_plant_metrics"
    # )  # Wait for method1 calls

    readings = get_readings()
    payload = {"result": True, "data": readings}  # set response payload
    status = 200  # set return status code
    print("Sending plant metrics to IoT Hub")

    method_response = MethodResponse.create_from_method_request(
        method_request, status, payload)
    await device_client.send_method_response(method_response)