test: fix OCPP 2 server startup
[e-mobility-charging-stations-simulator.git] / tests / ocpp-server / server.py
1 import asyncio
2 import logging
3 from datetime import datetime, timezone
4 from threading import Timer
5
6 import ocpp.v201
7 import websockets
8 from ocpp.routing import on
9 from ocpp.v201.enums import RegistrationStatusType, ClearCacheStatusType, Action
10
11 # Setting up the logging configuration to display debug level messages.
12 logging.basicConfig(level=logging.DEBUG)
13
14
15 class RepeatTimer(Timer):
16 """ Class that inherits from the Timer class. It will run a
17 function at regular intervals."""
18
19 def run(self):
20 while not self.finished.wait(self.interval):
21 self.function(*self.args, **self.kwargs)
22
23
24 # Define a ChargePoint class inheriting from the OCPP 2.0.1 ChargePoint class.
25 class ChargePoint(ocpp.v201.ChargePoint):
26 # Message handlers to receive OCPP messages.
27 @on(Action.BootNotification)
28 async def on_boot_notification(self, charging_station, reason, **kwargs):
29 logging.info("Received BootNotification")
30 # Create and return a BootNotification response with the current time,
31 # an interval of 10 seconds, and an accepted status.
32 return ocpp.v201.call_result.BootNotification(
33 current_time=datetime.now(timezone.utc).isoformat(),
34 interval=10,
35 status=RegistrationStatusType.accepted
36 )
37
38 # Request handlers to emit OCPP messages.
39 async def send_clear_cache(self):
40 request = ocpp.v201.call.ClearCache()
41 response = await self.call(request)
42
43 if response.status == ClearCacheStatusType.accepted:
44 logging.info("Cache clearing successful")
45 else:
46 logging.info("Cache clearing failed")
47
48
49 # Function to handle new WebSocket connections.
50 async def on_connect(websocket, path):
51 """ For every new charge point that connects, create a ChargePoint instance and start
52 listening for messages."""
53 try:
54 requested_protocols = websocket.request_headers['Sec-WebSocket-Protocol']
55 except KeyError:
56 logging.info("Client hasn't requested any Subprotocol. Closing Connection")
57 return await websocket.close()
58
59 if websocket.subprotocol:
60 logging.info("Protocols Matched: %s", websocket.subprotocol)
61 else:
62 logging.warning('Protocols Mismatched | Expected Subprotocols: %s,'
63 ' but client supports %s | Closing connection',
64 websocket.available_subprotocols,
65 requested_protocols)
66 return await websocket.close()
67
68 charge_point_id = path.strip('/')
69 cp = ChargePoint(charge_point_id, websocket)
70
71 # Start the ChargePoint instance to listen for incoming messages.
72 await cp.start()
73
74
75 # Main function to start the WebSocket server.
76 async def main():
77 # Create the WebSocket server and specify the handler for new connections.
78 server = await websockets.serve(
79 on_connect,
80 '127.0.0.1', # Listen on loopback.
81 9000, # Port number.
82 subprotocols=['ocpp2.0', 'ocpp2.0.1'] # Specify OCPP 2.0.1 subprotocols.
83 )
84 logging.info("WebSocket Server Started")
85 # Wait for the server to close (runs indefinitely).
86 await server.wait_closed()
87
88
89 # Entry point of the script.
90 if __name__ == '__main__':
91 # Run the main function to start the server.
92 asyncio.run(main())