Debian Codegraph @

examples/v21/central_system.py

raw
1 import asyncio
2 import logging
3 from datetime import datetime, timezone
4
5 try:
6 import websockets
7 except ModuleNotFoundError:
8 print("This example relies on the 'websockets' package.")
9 print("Please install it by running: ")
10 print()
11 print(" $ pip install websockets")
12 import sys
13
14 sys.exit(1)
15
16 from ocpp.routing import on
17 from ocpp.v21 import ChargePoint as cp
18 from ocpp.v21 import call_result
19 from ocpp.v21.enums import Action
20
21 logging.basicConfig(level=logging.INFO)
22
23
24 class ChargePoint(cp):
25 @on(Action.boot_notification)
26 def on_boot_notification(self, charging_station, reason, **kwargs):
27 return call_result.BootNotification(
28 current_time=datetime.now(timezone.utc).isoformat(),
29 interval=10,
30 status="Accepted",
31 )
32
33 @on(Action.heartbeat)
34 def on_heartbeat(self):
35 print("Got a Heartbeat!")
36 return call_result.Heartbeat(
37 current_time=datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S") + "Z"
38 )
39
40
41 async def on_connect(websocket):
42 """For every new charge point that connects, create a ChargePoint
43 instance and start listening for messages.
44 """
45 try:
46 requested_protocols = websocket.request.headers["Sec-WebSocket-Protocol"]
47 except KeyError:
48 logging.error("Client hasn't requested any Subprotocol. Closing Connection")
49 return await websocket.close()
50 if websocket.subprotocol:
51 logging.info("Protocols Matched: %s", websocket.subprotocol)
52 else:
53 # In the websockets lib if no subprotocols are supported by the
54 # client and the server, it proceeds without a subprotocol,
55 # so we have to manually close the connection.
56 logging.warning(
57 "Protocols Mismatched | Expected Subprotocols: %s,"
58 " but client supports %s | Closing connection",
59 websocket.available_subprotocols,
60 requested_protocols,
61 )
62 return await websocket.close()
63
64 charge_point_id = websocket.request.path.strip("/")
65 charge_point = ChargePoint(charge_point_id, websocket)
66
67 await charge_point.start()
68
69
70 async def main():
71 # deepcode ignore BindToAllNetworkInterfaces: <Example Purposes>
72 server = await websockets.serve(
73 on_connect, "0.0.0.0", 9000, subprotocols=["ocpp2.1"]
74 )
75
76 logging.info("Server Started listening to new connections...")
77 await server.wait_closed()
78
79
80 if __name__ == "__main__":
81 # asyncio.run() is used when running this example with Python >= 3.7v
82 asyncio.run(main())