test: reformat ocpp server python using pep8 rules
[e-mobility-charging-stations-simulator.git] / tests / ocpp-server / server.py
1 import asyncio
2 import logging
3 from datetime import datetime, timezone
4
5 import websockets
6 from ocpp.routing import on
7 from ocpp.v201 import ChargePoint as cp
8 from ocpp.v201 import call_result
9 from ocpp.v201.enums import RegistrationStatusType, GenericDeviceModelStatusType
10
11 # Setting up the logging configuration to display debug level messages.
12 logging.basicConfig(level=logging.DEBUG)
13
14
15 # Define a ChargePoint class inheriting from the OCPP 2.0.1 ChargePoint class.
16 class ChargePoint(cp):
17 # Define a handler for the BootNotification message.
18 @on('BootNotification')
19 async def on_boot_notification(self, charging_station, reason, **kwargs):
20 logging.info("Received BootNotification")
21 # Create and return a BootNotification response with the current time,
22 # an interval of 10 seconds, and an accepted status.
23 return call_result.BootNotification(
24 current_time=datetime.now(timezone.utc).isoformat(),
25 interval=10,
26 status=RegistrationStatusType.accepted
27 )
28
29 # Define a handler for the GetBaseReport message.
30 @on('GetBaseReport')
31 async def on_get_base_report(self, request_id, report_base, **kwargs):
32 try:
33 logging.info(
34 f"Received GetBaseReport request with RequestId: {request_id} and ReportBase: {report_base}")
35
36 # Create a mock response for demonstration purposes, indicating the report is accepted.
37 response = call_result.GetBaseReport(
38 status=GenericDeviceModelStatusType.accepted
39 )
40
41 logging.info(f"Sending GetBaseReport response: {response}")
42 return response
43 except Exception as e:
44 # Log any errors that occur while handling the GetBaseReport request.
45 logging.error(f"Error handling GetBaseReport request: {e}", exc_info=True)
46 # Return a rejected status in case of error.
47 return call_result.GetBaseReport(
48 status=GenericDeviceModelStatusType.rejected
49 )
50
51
52 # Function to handle new WebSocket connections.
53 async def on_connect(websocket, path):
54 """ For every new charge point that connects, create a ChargePoint instance and start
55 listening for messages."""
56 try:
57 requested_protocols = websocket.request_headers['Sec-WebSocket-Protocol']
58 except KeyError:
59 logging.info("Client hasn't requested any Subprotocol. Closing Connection")
60 return await websocket.close()
61
62 if websocket.subprotocol:
63 logging.info("Protocols Matched: %s", websocket.subprotocol)
64 else:
65 logging.warning('Protocols Mismatched | Expected Subprotocols: %s,'
66 ' but client supports %s | Closing connection',
67 websocket.available_subprotocols,
68 requested_protocols)
69 return await websocket.close()
70
71 charge_point_id = path.strip('/')
72 cp = ChargePoint(charge_point_id, websocket)
73
74 # Start the ChargePoint instance to listen for incoming messages.
75 await cp.start()
76
77
78 # Main function to start the WebSocket server.
79 async def main():
80 # Create the WebSocket server and specify the handler for new connections.
81 server = await websockets.serve(
82 on_connect,
83 '127.0.0.1', # Listen on loopback.
84 9000, # Port number.
85 subprotocols=['ocpp2.0', 'ocpp2.0.1'] # Specify OCPP 2.0.1 subprotocols.
86 )
87 logging.info("WebSocket Server Started")
88 # Wait for the server to close (runs indefinitely).
89 await server.wait_closed()
90
91
92 # Entry point of the script.
93 if __name__ == '__main__':
94 # Run the main function to start the server.
95 asyncio.run(main())