Merge branch 'main' into issue39-ocpp2
[e-mobility-charging-stations-simulator.git] / tests / ocpp-server / server.py
CommitLineData
b794f42e 1import argparse
fa16d389
S
2import asyncio
3import logging
fa16d389 4from datetime import datetime, timezone
aea49501 5from threading import Timer
fa16d389 6
a89844d4 7import ocpp.v201
1a0d2c47 8import websockets
fa16d389 9from ocpp.routing import on
d4aa9700
JB
10from ocpp.v201.enums import (
11 Action,
12 AuthorizationStatusType,
13 ClearCacheStatusType,
14 RegistrationStatusType,
f937c172 15 ReportBaseType,
b794f42e 16 TransactionEventType,
d4aa9700 17)
a5c2d21f 18from websockets import ConnectionClosed
fa16d389
S
19
20# Setting up the logging configuration to display debug level messages.
21logging.basicConfig(level=logging.DEBUG)
22
a5c2d21f
JB
23ChargePoints = set()
24
1a0d2c47 25
aea49501 26class 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 36class 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 98 @on(Action.GetBaseReport)
1f71f83f 99 async def on_get_base_report(
100 self, request_id: int, report_base: ReportBaseType, **kwargs
101 ):
7c945b4a 102 logging.info("Received %s", Action.GetBaseReport)
b2254601 103 return ocpp.v201.call_result.GetBaseReport(
1f71f83f 104 id_token_info={"status": ReportBaseType.accepted}
105 )
f937c172 106
d6488e8d 107 # Request handlers to emit OCPP messages.
a89844d4
JB
108 async def send_clear_cache(self):
109 request = ocpp.v201.call.ClearCache()
110 response = await self.call(request)
111
112 if response.status == ClearCacheStatusType.accepted:
7628b7e6 113 logging.info("%s successful", Action.ClearCache)
a89844d4 114 else:
7628b7e6 115 logging.info("%s failed", Action.ClearCache)
1a0d2c47 116
f937c172 117 async def send_get_base_report(self):
b794f42e 118 request = ocpp.v201.call.GetBaseReport(
119 reportBase=ReportBaseType.ConfigurationInventory
299eb3fa
S
120 )
121 response = await self.call(request)
b794f42e 122
299eb3fa
S
123 if response.status == ReportBaseType.accepted:
124 logging.info("%s successful", Action.GetBaseReport)
125 else:
891ae31d 126 logging.info("%s failed", Action.GetBaseReport)
b2254601 127
f937c172 128
f937c172
S
129# Function to send OCPP command
130async def send_ocpp_command(cp, command_name, delay=None, period=None):
299eb3fa
S
131 try:
132 match command_name:
133 case Action.ClearCache:
134 logging.info("%s Send:", Action.ClearCache)
135 await cp.send_clear_cache()
136 case Action.GetBaseReport:
137 logging.info("%s Send:", Action.GetBaseReport)
138 await cp.send_get_base_report()
299eb3fa 139 except Exception:
e1702c32 140 logging.exception(
141 f"Not supported or Failure while processing command {command_name}"
142 )
299eb3fa 143
f937c172
S
144 if delay:
145 await asyncio.sleep(delay)
146
f937c172 147 if period:
b738a0fc 148 my_timer = RepeatTimer(
149 period, asyncio.create_task, [cp.send_ocpp_command(command_name)]
150 )
299eb3fa 151 my_timer.start()
f937c172 152
fa16d389
S
153
154# Function to handle new WebSocket connections.
299eb3fa 155async def on_connect(websocket, path):
d4aa9700 156 """For every new charge point that connects, create a ChargePoint instance and start
d6488e8d
JB
157 listening for messages."""
158 try:
d4aa9700 159 requested_protocols = websocket.request_headers["Sec-WebSocket-Protocol"]
d6488e8d
JB
160 except KeyError:
161 logging.info("Client hasn't requested any Subprotocol. Closing Connection")
162 return await websocket.close()
1a0d2c47 163
d6488e8d
JB
164 if websocket.subprotocol:
165 logging.info("Protocols Matched: %s", websocket.subprotocol)
166 else:
d4aa9700
JB
167 logging.warning(
168 "Protocols Mismatched | Expected Subprotocols: %s,"
169 " but client supports %s | Closing connection",
170 websocket.available_subprotocols,
171 requested_protocols,
172 )
d6488e8d 173 return await websocket.close()
1a0d2c47 174
d4aa9700 175 charge_point_id = path.strip("/")
d6488e8d 176 cp = ChargePoint(charge_point_id, websocket)
1a0d2c47 177
a5c2d21f 178 ChargePoints.add(cp)
7628b7e6
JB
179 try:
180 await cp.start()
7c945b4a 181
7628b7e6
JB
182 except ConnectionClosed:
183 logging.info("ChargePoint %s closed connection", cp.id)
184 ChargePoints.remove(cp)
950b6c5a 185 logging.debug("Connected ChargePoint(s): %d", len(ChargePoints))
1a0d2c47 186
b738a0fc 187
fa16d389
S
188# Main function to start the WebSocket server.
189async def main():
b2254601 190 # Define argument parser
299eb3fa
S
191 parser = argparse.ArgumentParser(description="OCPP2 Charge Point Simulator")
192 parser.add_argument("--command", type=str, help="OCPP2 Command Name")
b2254601
S
193 parser.add_argument("--delay", type=int, help="Delay in seconds")
194 parser.add_argument("--period", type=int, help="Period in seconds")
195
d6488e8d
JB
196 # Create the WebSocket server and specify the handler for new connections.
197 server = await websockets.serve(
299eb3fa 198 on_connect,
d4aa9700 199 "127.0.0.1", # Listen on loopback.
d6488e8d 200 9000, # Port number.
d4aa9700 201 subprotocols=["ocpp2.0", "ocpp2.0.1"], # Specify OCPP 2.0.1 subprotocols.
d6488e8d
JB
202 )
203 logging.info("WebSocket Server Started")
f937c172 204
299eb3fa
S
205 args = parser.parse_args()
206
207 if args.command:
208 for cp in ChargePoints:
209 asyncio.create_task(
210 send_ocpp_command(cp, args.command, args.delay, args.period)
b738a0fc 211 )
299eb3fa 212
d6488e8d
JB
213 # Wait for the server to close (runs indefinitely).
214 await server.wait_closed()
1a0d2c47 215
fa16d389
S
216
217# Entry point of the script.
d4aa9700 218if __name__ == "__main__":
d6488e8d
JB
219 # Run the main function to start the server.
220 asyncio.run(main())