从原始处理程序之外的函数返回websocket调用

2024-05-01 21:30:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用websocket和asyncio为特定功能构建一种请求路由器

问题是:我需要在异步流内部混合一些排序。我需要处理一个websocket请求,向另一个服务器发出请求,并将答案返回给原始请求者。但我需要保持异步,同时保持第二个websocket连接打开

这里我举了一个例子,我尝试了但没有成功。我在on_boot_notification()处理原始请求,但我必须使用从send_boot_notification()获得的信息进行应答

有人能帮我吗

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()

Tags: fromimportselfasynciomainonstatuscall