3 from datetime
import datetime
, timezone
4 from threading
import Timer
8 from ocpp
.routing
import on
9 from ocpp
.v201
.enums
import RegistrationStatusType
, ClearCacheStatusType
, Action
11 # Setting up the logging configuration to display debug level messages.
12 logging
.basicConfig(level
=logging
.DEBUG
)
15 class RepeatTimer(Timer
):
16 """ Class that inherits from the Timer class. It will run a
17 function at regular intervals."""
20 while not self
.finished
.wait(self
.interval
):
21 self
.function(*self
.args
, **self
.kwargs
)
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(),
35 status
=RegistrationStatusType
.accepted
39 async def on_heartbeat(self
, charging_station
, **kwargs
):
40 logging
.info("Received Heartbeat")
41 return ocpp
.v201
.call_result
.Heartbeat(current_time
=datetime
.now(timezone
.utc
).isoformat())
43 # Request handlers to emit OCPP messages.
44 async def send_clear_cache(self
):
45 request
= ocpp
.v201
.call
.ClearCache()
46 response
= await self
.call(request
)
48 if response
.status
== ClearCacheStatusType
.accepted
:
49 logging
.info("Cache clearing successful")
51 logging
.info("Cache clearing failed")
54 # Function to handle new WebSocket connections.
55 async def on_connect(websocket
, path
):
56 """ For every new charge point that connects, create a ChargePoint instance and start
57 listening for messages."""
59 requested_protocols
= websocket
.request_headers
['Sec-WebSocket-Protocol']
61 logging
.info("Client hasn't requested any Subprotocol. Closing Connection")
62 return await websocket
.close()
64 if websocket
.subprotocol
:
65 logging
.info("Protocols Matched: %s", websocket
.subprotocol
)
67 logging
.warning('Protocols Mismatched | Expected Subprotocols: %s,'
68 ' but client supports %s | Closing connection',
69 websocket
.available_subprotocols
,
71 return await websocket
.close()
73 charge_point_id
= path
.strip('/')
74 cp
= ChargePoint(charge_point_id
, websocket
)
76 # Start the ChargePoint instance to listen for incoming messages.
80 # Main function to start the WebSocket server.
82 # Create the WebSocket server and specify the handler for new connections.
83 server
= await websockets
.serve(
85 '127.0.0.1', # Listen on loopback.
87 subprotocols
=['ocpp2.0', 'ocpp2.0.1'] # Specify OCPP 2.0.1 subprotocols.
89 logging
.info("WebSocket Server Started")
90 # Wait for the server to close (runs indefinitely).
91 await server
.wait_closed()
94 # Entry point of the script.
95 if __name__
== '__main__':
96 # Run the main function to start the server.