Commit | Line | Data |
---|---|---|
b794f42e | 1 | import argparse |
fa16d389 | 2 | import asyncio |
b2254601 | 3 | from functools import partial |
fa16d389 | 4 | import logging |
fa16d389 | 5 | from datetime import datetime, timezone |
aea49501 | 6 | from threading import Timer |
fa16d389 | 7 | |
a89844d4 | 8 | import ocpp.v201 |
1a0d2c47 | 9 | import websockets |
fa16d389 | 10 | from ocpp.routing import on |
d4aa9700 JB |
11 | from ocpp.v201.enums import ( |
12 | Action, | |
13 | AuthorizationStatusType, | |
14 | ClearCacheStatusType, | |
15 | RegistrationStatusType, | |
f937c172 | 16 | ReportBaseType, |
b794f42e | 17 | TransactionEventType, |
d4aa9700 | 18 | ) |
a5c2d21f | 19 | from websockets import ConnectionClosed |
fa16d389 S |
20 | |
21 | # Setting up the logging configuration to display debug level messages. | |
22 | logging.basicConfig(level=logging.DEBUG) | |
23 | ||
a5c2d21f JB |
24 | ChargePoints = set() |
25 | ||
1a0d2c47 | 26 | |
aea49501 | 27 | class RepeatTimer(Timer): |
d4aa9700 | 28 | """Class that inherits from the Timer class. It will run a |
aea49501 JB |
29 | function at regular intervals.""" |
30 | ||
31 | def run(self): | |
32 | while not self.finished.wait(self.interval): | |
33 | self.function(*self.args, **self.kwargs) | |
34 | ||
35 | ||
fa16d389 | 36 | # Define a ChargePoint class inheriting from the OCPP 2.0.1 ChargePoint class. |
a89844d4 | 37 | class ChargePoint(ocpp.v201.ChargePoint): |
aea49501 | 38 | # Message handlers to receive OCPP messages. |
339f65ad | 39 | @on(Action.BootNotification) |
d6488e8d | 40 | async def on_boot_notification(self, charging_station, reason, **kwargs): |
7628b7e6 | 41 | logging.info("Received %s", Action.BootNotification) |
d6488e8d | 42 | # Create and return a BootNotification response with the current time, |
5dd22b9f | 43 | # an interval of 60 seconds, and an accepted status. |
339f65ad | 44 | return ocpp.v201.call_result.BootNotification( |
d6488e8d | 45 | current_time=datetime.now(timezone.utc).isoformat(), |
115f3b17 | 46 | interval=60, |
d4aa9700 | 47 | status=RegistrationStatusType.accepted, |
d6488e8d | 48 | ) |
1a0d2c47 | 49 | |
115f3b17 | 50 | @on(Action.Heartbeat) |
5dd22b9f | 51 | async def on_heartbeat(self, **kwargs): |
7628b7e6 | 52 | logging.info("Received %s", Action.Heartbeat) |
d4aa9700 JB |
53 | return ocpp.v201.call_result.Heartbeat( |
54 | current_time=datetime.now(timezone.utc).isoformat() | |
55 | ) | |
115f3b17 | 56 | |
65c0600c | 57 | @on(Action.StatusNotification) |
d4aa9700 JB |
58 | async def on_status_notification( |
59 | self, timestamp, evse_id: int, connector_id: int, connector_status, **kwargs | |
60 | ): | |
7628b7e6 | 61 | logging.info("Received %s", Action.StatusNotification) |
65c0600c JB |
62 | return ocpp.v201.call_result.StatusNotification() |
63 | ||
5dd22b9f JB |
64 | @on(Action.Authorize) |
65 | async def on_authorize(self, id_token, **kwargs): | |
7628b7e6 | 66 | logging.info("Received %s", Action.Authorize) |
5dd22b9f | 67 | return ocpp.v201.call_result.Authorize( |
d4aa9700 | 68 | id_token_info={"status": AuthorizationStatusType.accepted} |
8430af0a | 69 | ) |
5dd22b9f | 70 | |
22c4f1fc | 71 | @on(Action.TransactionEvent) |
d4aa9700 JB |
72 | async def on_transaction_event( |
73 | self, | |
74 | event_type: TransactionEventType, | |
75 | timestamp, | |
76 | trigger_reason, | |
77 | seq_no: int, | |
78 | transaction_info, | |
79 | **kwargs, | |
80 | ): | |
22c4f1fc JB |
81 | match event_type: |
82 | case TransactionEventType.started: | |
7628b7e6 | 83 | logging.info("Received %s Started", Action.TransactionEvent) |
22c4f1fc | 84 | return ocpp.v201.call_result.TransactionEvent( |
d4aa9700 | 85 | id_token_info={"status": AuthorizationStatusType.accepted} |
8430af0a | 86 | ) |
22c4f1fc | 87 | case TransactionEventType.updated: |
7628b7e6 | 88 | logging.info("Received %s Updated", Action.TransactionEvent) |
d4aa9700 | 89 | return ocpp.v201.call_result.TransactionEvent(total_cost=10) |
22c4f1fc | 90 | case TransactionEventType.ended: |
7628b7e6 | 91 | logging.info("Received %s Ended", Action.TransactionEvent) |
22c4f1fc JB |
92 | return ocpp.v201.call_result.TransactionEvent() |
93 | ||
5dd22b9f | 94 | @on(Action.MeterValues) |
c7f80bf9 | 95 | async def on_meter_values(self, evse_id: int, meter_value, **kwargs): |
7628b7e6 | 96 | logging.info("Received %s", Action.MeterValues) |
5dd22b9f JB |
97 | return ocpp.v201.call_result.MeterValues() |
98 | ||
f937c172 | 99 | @on(Action.GetBaseReport) |
b2254601 | 100 | async def on_get_base_report(self, request_id: int, report_base: ReportBaseType, **kwargs): |
7c945b4a | 101 | logging.info("Received %s", Action.GetBaseReport) |
b2254601 S |
102 | return ocpp.v201.call_result.GetBaseReport( |
103 | id_token_info={"status": ReportBaseType.accepted} | |
104 | ) | |
f937c172 | 105 | |
d6488e8d | 106 | # Request handlers to emit OCPP messages. |
a89844d4 JB |
107 | async def send_clear_cache(self): |
108 | request = ocpp.v201.call.ClearCache() | |
109 | response = await self.call(request) | |
110 | ||
111 | if response.status == ClearCacheStatusType.accepted: | |
7628b7e6 | 112 | logging.info("%s successful", Action.ClearCache) |
a89844d4 | 113 | else: |
7628b7e6 | 114 | logging.info("%s failed", Action.ClearCache) |
1a0d2c47 | 115 | |
f937c172 | 116 | async def send_get_base_report(self): |
b794f42e | 117 | request = ocpp.v201.call.GetBaseReport( |
118 | reportBase=ReportBaseType.ConfigurationInventory | |
119 | ) # Use correct ReportBaseType | |
f937c172 S |
120 | try: |
121 | response = await self.call(request) | |
ba0a7592 | 122 | logging.info("Send %s", Action.GetBaseReport) |
f937c172 | 123 | |
b2254601 S |
124 | if response.status == ReportBaseType.accepted: |
125 | logging.info("%s successful", Action.GetBaseReport) | |
f937c172 | 126 | else: |
b2254601 | 127 | logging.info("%s failed", Action.GetBaseReport) |
f937c172 | 128 | |
b2254601 S |
129 | except ConnectionClosed as e: |
130 | logging.error("Connection closed: %s", str(e)) | |
b794f42e | 131 | |
b2254601 S |
132 | except Exception as e: |
133 | logging.error("Unexpected error occurred: %s", str(e)) | |
134 | ||
135 | logging.info("send_get_base_report done.") | |
f937c172 | 136 | |
f937c172 | 137 | |
b794f42e | 138 | |
f937c172 S |
139 | # Function to send OCPP command |
140 | async def send_ocpp_command(cp, command_name, delay=None, period=None): | |
141 | # If delay is not None, sleep for delay seconds | |
142 | if delay: | |
143 | await asyncio.sleep(delay) | |
144 | ||
145 | # If period is not None, send command repeatedly with period interval | |
146 | if period: | |
7c945b4a S |
147 | async def send_command_repeatedly(): |
148 | while True: | |
b5185375 | 149 | command_name = await cp.receive_command() |
7c945b4a S |
150 | try: |
151 | match command_name: | |
39d32b71 | 152 | case Action.ClearCache: |
7c945b4a | 153 | logging.info("ClearCache parser working") |
7068f7f3 | 154 | await cp.send_clear_cache() |
04578196 | 155 | case Action.GetBaseReport: |
7c945b4a | 156 | logging.info("GetBaseReport parser working") |
12798afb | 157 | await cp.send_get_base_report() |
7c945b4a S |
158 | case _: |
159 | logging.warning(f"Unsupported command {command_name}") | |
b2254601 S |
160 | except Exception as e: |
161 | logging.exception(f"Failure while processing command {command_name}") | |
7c945b4a S |
162 | finally: |
163 | await asyncio.sleep(period) | |
164 | ||
165 | timer = RepeatTimer(period, send_command_repeatedly) | |
166 | await timer.start() | |
167 | await timer.wait_closed() # Wait for timer to finish before exiting | |
f937c172 | 168 | |
f937c172 | 169 | else: |
b794f42e | 170 | if command_name == "GetBaseReport": |
f937c172 S |
171 | await cp.send_get_base_report() |
172 | ||
fa16d389 S |
173 | |
174 | # Function to handle new WebSocket connections. | |
b2254601 | 175 | async def on_connect(websocket, path, args): |
d4aa9700 | 176 | """For every new charge point that connects, create a ChargePoint instance and start |
d6488e8d JB |
177 | listening for messages.""" |
178 | try: | |
d4aa9700 | 179 | requested_protocols = websocket.request_headers["Sec-WebSocket-Protocol"] |
d6488e8d JB |
180 | except KeyError: |
181 | logging.info("Client hasn't requested any Subprotocol. Closing Connection") | |
182 | return await websocket.close() | |
1a0d2c47 | 183 | |
d6488e8d JB |
184 | if websocket.subprotocol: |
185 | logging.info("Protocols Matched: %s", websocket.subprotocol) | |
186 | else: | |
d4aa9700 JB |
187 | logging.warning( |
188 | "Protocols Mismatched | Expected Subprotocols: %s," | |
189 | " but client supports %s | Closing connection", | |
190 | websocket.available_subprotocols, | |
191 | requested_protocols, | |
192 | ) | |
d6488e8d | 193 | return await websocket.close() |
1a0d2c47 | 194 | |
d4aa9700 | 195 | charge_point_id = path.strip("/") |
d6488e8d | 196 | cp = ChargePoint(charge_point_id, websocket) |
1a0d2c47 | 197 | |
a5c2d21f | 198 | ChargePoints.add(cp) |
7628b7e6 JB |
199 | try: |
200 | await cp.start() | |
7c945b4a S |
201 | # Check if request argument is specified |
202 | if args.request: | |
b2254601 | 203 | asyncio.create_task(send_ocpp_command(cp, args.request, args.delay, args.period)) |
7c945b4a | 204 | |
7628b7e6 JB |
205 | except ConnectionClosed: |
206 | logging.info("ChargePoint %s closed connection", cp.id) | |
207 | ChargePoints.remove(cp) | |
950b6c5a | 208 | logging.debug("Connected ChargePoint(s): %d", len(ChargePoints)) |
1a0d2c47 | 209 | |
fa16d389 S |
210 | |
211 | # Main function to start the WebSocket server. | |
212 | async def main(): | |
b2254601 S |
213 | # Define argument parser |
214 | parser = argparse.ArgumentParser(description="OCPP Charge Point Simulator") | |
215 | parser.add_argument("--request", type=str, help="OCPP 2 Command Name") | |
216 | parser.add_argument("--delay", type=int, help="Delay in seconds") | |
217 | parser.add_argument("--period", type=int, help="Period in seconds") | |
218 | ||
219 | args = parser.parse_args() | |
220 | ||
d4eddfae | 221 | on_connect_bound = partial(on_connect, args=args) # Add args to on_connect |
b2254601 | 222 | |
d6488e8d JB |
223 | # Create the WebSocket server and specify the handler for new connections. |
224 | server = await websockets.serve( | |
d4eddfae | 225 | on_connect_bound, |
d4aa9700 | 226 | "127.0.0.1", # Listen on loopback. |
d6488e8d | 227 | 9000, # Port number. |
d4aa9700 | 228 | subprotocols=["ocpp2.0", "ocpp2.0.1"], # Specify OCPP 2.0.1 subprotocols. |
d6488e8d JB |
229 | ) |
230 | logging.info("WebSocket Server Started") | |
f937c172 | 231 | |
d6488e8d JB |
232 | # Wait for the server to close (runs indefinitely). |
233 | await server.wait_closed() | |
1a0d2c47 | 234 | |
fa16d389 S |
235 | |
236 | # Entry point of the script. | |
d4aa9700 | 237 | if __name__ == "__main__": |
d6488e8d JB |
238 | # Run the main function to start the server. |
239 | asyncio.run(main()) |