Commit | Line | Data |
---|---|---|
fa16d389 S |
1 | import asyncio |
2 | import logging | |
fa16d389 | 3 | from datetime import datetime, timezone |
aea49501 | 4 | from threading import Timer |
fa16d389 | 5 | |
a89844d4 | 6 | import ocpp.v201 |
1a0d2c47 | 7 | import websockets |
fa16d389 | 8 | from ocpp.routing import on |
5dd22b9f JB |
9 | from ocpp.v201.enums import RegistrationStatusType, ClearCacheStatusType, AuthorizationStatusType, \ |
10 | Action | |
fa16d389 S |
11 | |
12 | # Setting up the logging configuration to display debug level messages. | |
13 | logging.basicConfig(level=logging.DEBUG) | |
14 | ||
1a0d2c47 | 15 | |
aea49501 JB |
16 | class RepeatTimer(Timer): |
17 | """ Class that inherits from the Timer class. It will run a | |
18 | function at regular intervals.""" | |
19 | ||
20 | def run(self): | |
21 | while not self.finished.wait(self.interval): | |
22 | self.function(*self.args, **self.kwargs) | |
23 | ||
24 | ||
fa16d389 | 25 | # Define a ChargePoint class inheriting from the OCPP 2.0.1 ChargePoint class. |
a89844d4 | 26 | class ChargePoint(ocpp.v201.ChargePoint): |
aea49501 | 27 | # Message handlers to receive OCPP messages. |
339f65ad | 28 | @on(Action.BootNotification) |
d6488e8d JB |
29 | async def on_boot_notification(self, charging_station, reason, **kwargs): |
30 | logging.info("Received BootNotification") | |
31 | # Create and return a BootNotification response with the current time, | |
5dd22b9f | 32 | # an interval of 60 seconds, and an accepted status. |
339f65ad | 33 | return ocpp.v201.call_result.BootNotification( |
d6488e8d | 34 | current_time=datetime.now(timezone.utc).isoformat(), |
115f3b17 | 35 | interval=60, |
d6488e8d JB |
36 | status=RegistrationStatusType.accepted |
37 | ) | |
1a0d2c47 | 38 | |
115f3b17 | 39 | @on(Action.Heartbeat) |
5dd22b9f | 40 | async def on_heartbeat(self, **kwargs): |
115f3b17 JB |
41 | logging.info("Received Heartbeat") |
42 | return ocpp.v201.call_result.Heartbeat(current_time=datetime.now(timezone.utc).isoformat()) | |
43 | ||
65c0600c | 44 | @on(Action.StatusNotification) |
5dd22b9f JB |
45 | async def on_status_notification(self, timestamp, evse_id, connector_id, connector_status, |
46 | **kwargs): | |
65c0600c JB |
47 | logging.info("Received StatusNotification") |
48 | return ocpp.v201.call_result.StatusNotification() | |
49 | ||
5dd22b9f JB |
50 | @on(Action.Authorize) |
51 | async def on_authorize(self, id_token, **kwargs): | |
52 | logging.info("Received Authorize") | |
53 | return ocpp.v201.call_result.Authorize( | |
54 | id_token_info={'status': AuthorizationStatusType.accepted}) | |
55 | ||
56 | @on(Action.MeterValues) | |
57 | async def on_meter_values(self, evse_id, meter_value, **kwargs): | |
58 | logging.info("Received MeterValues") | |
59 | return ocpp.v201.call_result.MeterValues() | |
60 | ||
d6488e8d | 61 | # Request handlers to emit OCPP messages. |
a89844d4 JB |
62 | async def send_clear_cache(self): |
63 | request = ocpp.v201.call.ClearCache() | |
64 | response = await self.call(request) | |
65 | ||
66 | if response.status == ClearCacheStatusType.accepted: | |
e1c2dac9 | 67 | logging.info("Cache clearing successful") |
a89844d4 JB |
68 | else: |
69 | logging.info("Cache clearing failed") | |
1a0d2c47 | 70 | |
fa16d389 S |
71 | |
72 | # Function to handle new WebSocket connections. | |
73 | async def on_connect(websocket, path): | |
d6488e8d JB |
74 | """ For every new charge point that connects, create a ChargePoint instance and start |
75 | listening for messages.""" | |
76 | try: | |
77 | requested_protocols = websocket.request_headers['Sec-WebSocket-Protocol'] | |
78 | except KeyError: | |
79 | logging.info("Client hasn't requested any Subprotocol. Closing Connection") | |
80 | return await websocket.close() | |
1a0d2c47 | 81 | |
d6488e8d JB |
82 | if websocket.subprotocol: |
83 | logging.info("Protocols Matched: %s", websocket.subprotocol) | |
84 | else: | |
85 | logging.warning('Protocols Mismatched | Expected Subprotocols: %s,' | |
86 | ' but client supports %s | Closing connection', | |
87 | websocket.available_subprotocols, | |
88 | requested_protocols) | |
89 | return await websocket.close() | |
1a0d2c47 | 90 | |
d6488e8d JB |
91 | charge_point_id = path.strip('/') |
92 | cp = ChargePoint(charge_point_id, websocket) | |
1a0d2c47 | 93 | |
d6488e8d JB |
94 | # Start the ChargePoint instance to listen for incoming messages. |
95 | await cp.start() | |
1a0d2c47 | 96 | |
fa16d389 S |
97 | |
98 | # Main function to start the WebSocket server. | |
99 | async def main(): | |
d6488e8d JB |
100 | # Create the WebSocket server and specify the handler for new connections. |
101 | server = await websockets.serve( | |
102 | on_connect, | |
103 | '127.0.0.1', # Listen on loopback. | |
104 | 9000, # Port number. | |
339f65ad | 105 | subprotocols=['ocpp2.0', 'ocpp2.0.1'] # Specify OCPP 2.0.1 subprotocols. |
d6488e8d JB |
106 | ) |
107 | logging.info("WebSocket Server Started") | |
108 | # Wait for the server to close (runs indefinitely). | |
109 | await server.wait_closed() | |
1a0d2c47 | 110 | |
fa16d389 S |
111 | |
112 | # Entry point of the script. | |
113 | if __name__ == '__main__': | |
d6488e8d JB |
114 | # Run the main function to start the server. |
115 | asyncio.run(main()) |