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