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