3 from datetime
import datetime
, timezone
4 from threading
import Timer
5 from typing
import Sequence
9 from ocpp
.routing
import on
10 from ocpp
.v201
import call_result
11 from ocpp
.v201
.enums
import RegistrationStatusType
, ClearCacheStatusType
13 # Setting up the logging configuration to display debug level messages.
14 logging
.basicConfig(level
=logging
.DEBUG
)
17 class RepeatTimer(Timer
):
18 """ Class that inherits from the Timer class. It will run a
19 function at regular intervals."""
22 while not self
.finished
.wait(self
.interval
):
23 self
.function(*self
.args
, **self
.kwargs
)
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(),
37 status
=RegistrationStatusType
.accepted
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
)
45 if response
.status
== ClearCacheStatusType
.accepted
:
46 logging
.info("Cache clearing successful")
48 logging
.info("Cache clearing failed")
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."""
56 requested_protocols
= websocket
.request_headers
['Sec-WebSocket-Protocol']
58 logging
.info("Client hasn't requested any Subprotocol. Closing Connection")
59 return await websocket
.close()
61 if websocket
.subprotocol
:
62 logging
.info("Protocols Matched: %s", websocket
.subprotocol
)
64 logging
.warning('Protocols Mismatched | Expected Subprotocols: %s,'
65 ' but client supports %s | Closing connection',
66 websocket
.available_subprotocols
,
68 return await websocket
.close()
70 charge_point_id
= path
.strip('/')
71 cp
= ChargePoint(charge_point_id
, websocket
)
73 # Start the ChargePoint instance to listen for incoming messages.
77 # Main function to start the WebSocket server.
79 # Create the WebSocket server and specify the handler for new connections.
80 server
= await websockets
.serve(
82 '127.0.0.1', # Listen on loopback.
84 subprotocols
=Sequence
['ocpp2.0', 'ocpp2.0.1'] # Specify OCPP 2.0.1 subprotocols.
86 logging
.info("WebSocket Server Started")
87 # Wait for the server to close (runs indefinitely).
88 await server
.wait_closed()
91 # Entry point of the script.
92 if __name__
== '__main__':
93 # Run the main function to start the server.