forked from mobilityhouse/ocpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcentral_system.py
80 lines (64 loc) · 2.46 KB
/
central_system.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import asyncio
import logging
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.v201 import ChargePoint as cp
from ocpp.v201 import call_result
from ocpp.v201.enums import Action
logging.basicConfig(level=logging.INFO)
class ChargePoint(cp):
@on(Action.boot_notification)
def on_boot_notification(self, charging_station, reason, **kwargs):
return call_result.BootNotificationPayload(
current_time=datetime.utcnow().isoformat(), interval=10, status="Accepted"
)
@on(Action.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"
)
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.error("Client hasn't requested any Subprotocol. 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():
# deepcode ignore BindToAllNetworkInterfaces: <Example Purposes>
server = await websockets.serve(
on_connect, "0.0.0.0", 9000, subprotocols=["ocpp2.0.1"]
)
logging.info("Server Started listening to new connections...")
await server.wait_closed()
if __name__ == "__main__":
# asyncio.run() is used when running this example with Python >= 3.7v
asyncio.run(main())