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