Пример #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)
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
Пример #5
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)
Пример #6
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)
Пример #7
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)
Пример #8
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))
Пример #9
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))
Пример #10
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 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)
    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})
Пример #13
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))
Пример #14
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)
Пример #15
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
Пример #16
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
Пример #17
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
Пример #18
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))
Пример #19
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)
Пример #20
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')
Пример #21
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)
Пример #22
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")
Пример #23
0
async def pump_water_command(device_client, method_request):
    # method_request = await device_client.receive_method_request(
    #     "pump_water"
    # )  # Wait for method1 calls

    water_plant()

    payload = {"result": True}  # set response payload
    status = 200  # set return status code

    method_response = MethodResponse.create_from_method_request(
        method_request, status, payload)
    await device_client.send_method_response(method_response)
Пример #24
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)
Пример #25
0
def generic_method_listener(device_client):
    while True:
        method_request = (device_client.receive_method_request()
                          )  # Wait for unknown method calls
        # set response payload
        payload = {"result": False, "data": "Unrecognized Method"}
        status = 400  # set return status code
        print(str(datetime.datetime.now()),
              "Receiving Unknown Method: " + method_request.name)
        method_response = MethodResponse.create_from_method_request(
            method_request, status, payload)
        # send response
        device_client.send_method_response(method_response)
Пример #26
0
 async def failure_request_listener(device_client_PyPi):
     while True:
         # 1). wait for unknown method call
         method_request = (await
                           device_client_PyPi.receive_method_request())
         print("executed unknown method: " + method_request.name)
         # 2). set response payload & return status code
         payload = {"result": False, "data": "unknown method"}
         status = 400
         # 3). send response
         method_response = MethodResponse.create_from_method_request(
             method_request, status, payload)
         await device_client_PyPi.send_method_response(method_response)
Пример #27
0
def method_request_handler(method_request):
    if method_request.name == "reboot":
        payload = {"result": True, "data": "some data"}
        status = 200

        ## RESENDING ANSWER
        method_response = MethodResponse.create_from_method_request(
            method_request, status, payload)
        device_client.send_method_response(method_response)
        print("executed reboot")

        ## SEND REPORTED PROPERTY TO TWIN
        reported_properties = {"bootstatus": "ok"}
        device_client.patch_twin_reported_properties(reported_properties)
    else:
        payload = {"result": False, "data": "unknown method"}
        status = 400

        ## RESENDING ANSWER
        method_response = MethodResponse.create_from_method_request(
            method_request, status, payload)
        device_client.send_method_response(method_response)
        print("executed unknown method: " + method_request.name)
Пример #28
0
async def method_request_handler(method_request):
    print("Received message")
    print(method_request.payload)
    status = 400  # set return status code

    if method_request.name == 'invokeDetectedObjectsMessage':
        print("Calling function to output detectedObjects message")
        status = await send_detectedObjects_message(method_request.payload)
    else:
        print('Message received on unknown input route')

    print("Sent detectedObjects message")
    method_response = MethodResponse.create_from_method_request(method_request, status)
    await module_client.send_method_response(method_response)
 async def method1_listener(module_client):
     while True:
         method_request = await module_client.receive_method_request(
             "method1")  # Wait for method1 calls
         print("Message received : %s " % method_request.payload)
         payload = {
             "result": True,
             "data": "some data"
         }  # set response payload
         status = 200  # set return status code
         print("executed method1")
         method_response = MethodResponse.create_from_method_request(
             method_request, status, payload)
         await module_client.send_method_response(method_response
                                                  )  # send response
Пример #30
0
    async def command_listener(device_client):
        while True:
            method_request = await device_client.receive_method_request('needs_watering')
            needs_watering = method_request.payload
            print('Needs watering:', needs_watering)
            payload = {'result': True}

            if needs_watering:
                led.on()
            else:
                led.off()

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