question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Disconnect will show error in the console

See original GitHub issue

When I want to Disconnect I will receive this error in the console how can I handle it when the Disconnect command came from the frontend?

ERROR:websockets.server:Error in connection handler
Traceback (most recent call last):
  File "/Users/saeedrahmatolahi/Library/Python/3.8/lib/python/site-packages/websockets/legacy/server.py", line 293, in handler
    await self.ws_handler(self, path)
  File ".../central_system.py", line 69, in on_connect
    await charge_point.start()
  File ".../charge_point.py", line 123, in start
    message = await self._connection.recv()
  File ".../protocol.py", line 421, in recv
    await self.ensure_open()
  File ".../protocol.py", line 735, in ensure_open
    raise self.connection_closed_exc()
websockets.exceptions.ConnectionClosedError: code = 3001 (registered), reason = close connection

here is my codes

import asyncio
import logging
from datetime import datetime

from ocpp.v16.call import AuthorizePayload

try:
    import websockets
except ModuleNotFoundError:
    import sys
    print('error')
    sys.exit(1)

from ocpp.routing import on
from ocpp.v201 import ChargePoint as cp
from ocpp.v201 import call_result

logging.basicConfig(level=logging.INFO)


class ChargePoint(cp):
    @on('BootNotification', skip_schema_validation=True)
    def on_boot_notification(self, charging_station, reason, **kwargs):
        return call_result.BootNotificationPayload(
            current_time=datetime.utcnow().isoformat(),
            interval=10,
            status='Accepted'
        )

    @on('Heartbeat')
    def on_heartbeat(self):
        print('Got a Heartbeat!')
        return call_result.HeartbeatPayload(
            current_time=datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S') + "Z"
        )

    @on('Authorize', skip_schema_validation=True)
    def on_authorize(self):
        return call_result.AuthorizePayload(
            id_token_info={"id_tag": 23},
        )


async def on_connect(websocket, path):
    """ For every new charge point that connects, create a ChargePoint
    instance and start listening for messages.
    """
    try:
        requested_protocols = websocket.request_headers['Sec-WebSocket-Protocol']
    except KeyError:
        logging.info("Client hasn't requested any Sub protocol. "
                     "Closing Connection")
        logging.error("Client hasn't requested any Sub protocol. Closing Connection")
        return await websocket.close()
    if websocket.subprotocol:
        logging.info("Protocols Matched: %s", websocket.subprotocol)
    else:
        # In the websockets lib if no subprotocols are supported by the
        # client and the server, it proceeds without a subprotocol,
        # so we have to manually close the connection.
        logging.warning('Protocols Mismatched | Expected Subprotocols: %s,'
                        ' but client supports %s | Closing connection',
                        websocket.available_subprotocols,
                        requested_protocols)
        return await websocket.close()

    charge_point_id = path.strip('/')
    charge_point = ChargePoint(charge_point_id, websocket)
    await charge_point.start()


async def main():
    #  deep code ignore BindToAllNetworkInterfaces: <Example Purposes>
    server = await websockets.serve(
        on_connect,
        '0.0.0.0',
        9000,
        subprotocols=['ocpp1.6']
    )

    logging.info("Server Started listening to new connections...")
    await server.wait_closed()
    # server.close()

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

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Reactions:1
  • Comments:6

github_iconTop GitHub Comments

1reaction
OrangeTuxcommented, Aug 17, 2021

websocket.close() is a coroutine, so it need to be awaited. So

await websocket.close()
0reactions
SaeedRahmatolahicommented, Aug 18, 2021

websocket.close() is a coroutine, so it need to be awaited. So

await websocket.close()

thanks

Read more comments on GitHub >

github_iconTop Results From Across the Web

Hide errors and warnings from console - javascript
A dirty way to hide all Javascript console warnings is by overriding the console object's warn method: console.warn = () => {};.
Read more >
How to remove the console errors in axios ? - GeeksforGeeks
In this article, we will see the “Remove the console errors in Axios“. The console errors method outputs an error message to the...
Read more >
What do I do if I am disconnected on Xbox with the error ...
Select Network Settings, Advanced Settings, Alternative Mac Address, and finally Clear. Restart and shut down the Xbox. Disconnect the power cord from the...
Read more >
"The VMRC Console has Disconnected. Trying to reconnect ...
To resolve the error "The VMRC Console has Disconnected. Trying to reconnect", use one of these options: Disable application control for ...
Read more >
Overwatch 2 Console Error LC-208 - Blizzard Support
Common Problems. Unable to connect to Overwatch 2 on console; Disconnected from game servers. (LC-208). If your console ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found