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