Returning a websocket call from a function outside of the original handler

  python, python-asyncio, websocket

I am trying to build a kind of request router for a specific functionality using websocket and asyncio.

The problem is: I need to mix a little of sequencing inside of the asynchronous flow. I need to handle a websocket request, make a request to another server and return the answer to the original requester. But as I need to keep things asynchronous and also keep the second websocket connection opened.

Here I have an example that I tried without success. I handle the original request at on_boot_notification(), but I must answer using the info I get from send_boot_notification().

May anyone help me?

import asyncio
from datetime import datetime

try:
    import websockets
except ModuleNotFoundError:
    print("This example relies on the 'websockets' package.")
    print("Please install it by running: ")
    print()
    print(" $ pip install websockets")
    import sys
    sys.exit(1)

from ocpp.routing import on
from ocpp.v16 import ChargePoint as cp
from ocpp.v16.enums import Action, RegistrationStatus
from ocpp.v16 import call_result
from ocpp.v16 import call
from ocpp.v16.call_result import BootNotificationPayload

class ChargePoint(cp):

    async def send_boot_notification(self):
        request = call.BootNotificationPayload(
            charge_point_model="Optimus",
            charge_point_vendor="The Mobility House"
        )
        response = await self.call(request)

        if response.status ==  RegistrationStatus.accepted:
            print("Connected to central system.")
        else:
            print("Connection to backend failed")

        heartbeatInterval = response.interval
        currentTime = response.current_time
        status = response.status

        print('')
        print('heartbeatInterval = '+str(heartbeatInterval))
        print('currentTime = '+str(currentTime))
        print('status = '+status)
        print('')

        #THAT'S WHERE I WANT TO RETURN THE ORIGINAL CALL RESULT
        return self._call_result.BootNotificationPayload(
        current_time = currentTime,
        interval = heartbeatInterval,
        status = status
        )
        

    @on(Action.BootNotification)
    async def on_boot_notitication(self, charge_point_vendor, charge_point_model, **kwargs):
        print('BootNotification received. Model '+charge_point_model+' from vendor '+charge_point_vendor)
        print('Sending further notification to main CS')
        print('')

        async with websockets.connect(
        'ws://127.0.0.1:8080/steve/websocket/CentralSystemService/'+self.id,
        subprotocols = ['ocpp1.6']
        ) as ws:

            cp = ChargePoint(self.id, ws)
            await asyncio.gather(cp.start(), cp.send_boot_notification())

        #THAT'S HOW I KNOW IT WORKS, RETURNING FROM INSIDE THE ORIGINAL HANDLER
        # return call_result.BootNotificationPayload(
        # current_time = currentTime,
        # interval = heartbeatInterval,
        # status = status
        # )

async def on_connect(websocket, path):
    """ For every new charge point that connects, create a ChargePoint instance
    and start listening for messages.
    """
    charge_point_id = path.strip('/')
    cp = ChargePoint(charge_point_id, websocket)

    await cp.start()


async def main():
    server = await websockets.serve(
        on_connect,
        '0.0.0.0',
        9000,
        subprotocols = ['ocpp1.6']
    )

    await server.wait_closed()


if __name__ == '__main__':
    try:
        # asyncio.run() is used when running this example with Python 3.7 and
        # higher.
        asyncio.run(main())
    except AttributeError:
        # For Python 3.6 a bit more code is required to run the main() task on
        # an event loop.
        loop = asyncio.get_event_loop()
        loop.run_until_complete(main())
        loop.close()

Source: Python Questions

LEAVE A COMMENT