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
, AuthorizationStatusType
, \
12 # Setting up the logging configuration to display debug level messages.
13 logging
.basicConfig(level
=logging
.DEBUG
)
16 class RepeatTimer(Timer
):
17 """ Class that inherits from the Timer class. It will run a
18 function at regular intervals."""
21 while not self
.finished
.wait(self
.interval
):
22 self
.function(*self
.args
, **self
.kwargs
)
25 # Define a ChargePoint class inheriting from the OCPP 2.0.1 ChargePoint class.
26 class ChargePoint(ocpp
.v201
.ChargePoint
):
27 # Message handlers to receive OCPP messages.
28 @on(Action
.BootNotification
)
29 async def on_boot_notification(self
, charging_station
, reason
, **kwargs
):
30 logging
.info("Received BootNotification")
31 # Create and return a BootNotification response with the current time,
32 # an interval of 60 seconds, and an accepted status.
33 return ocpp
.v201
.call_result
.BootNotification(
34 current_time
=datetime
.now(timezone
.utc
).isoformat(),
36 status
=RegistrationStatusType
.accepted
40 async def on_heartbeat(self
, **kwargs
):
41 logging
.info("Received Heartbeat")
42 return ocpp
.v201
.call_result
.Heartbeat(current_time
=datetime
.now(timezone
.utc
).isoformat())
44 @on(Action
.StatusNotification
)
45 async def on_status_notification(self
, timestamp
, evse_id
, connector_id
, connector_status
,
47 logging
.info("Received StatusNotification")
48 return ocpp
.v201
.call_result
.StatusNotification()
51 async def on_authorize(self
, id_token
, **kwargs
):
52 logging
.info("Received Authorize")
53 return ocpp
.v201
.call_result
.Authorize(
54 id_token_info
={'status': AuthorizationStatusType
.accepted
})
56 @on(Action
.MeterValues
)
57 async def on_meter_values(self
, evse_id
, meter_value
, **kwargs
):
58 logging
.info("Received MeterValues")
59 return ocpp
.v201
.call_result
.MeterValues()
61 # Request handlers to emit OCPP messages.
62 async def send_clear_cache(self
):
63 request
= ocpp
.v201
.call
.ClearCache()
64 response
= await self
.call(request
)
66 if response
.status
== ClearCacheStatusType
.accepted
:
67 logging
.info("Cache clearing successful")
69 logging
.info("Cache clearing failed")
72 # Function to handle new WebSocket connections.
73 async def on_connect(websocket
, path
):
74 """ For every new charge point that connects, create a ChargePoint instance and start
75 listening for messages."""
77 requested_protocols
= websocket
.request_headers
['Sec-WebSocket-Protocol']
79 logging
.info("Client hasn't requested any Subprotocol. Closing Connection")
80 return await websocket
.close()
82 if websocket
.subprotocol
:
83 logging
.info("Protocols Matched: %s", websocket
.subprotocol
)
85 logging
.warning('Protocols Mismatched | Expected Subprotocols: %s,'
86 ' but client supports %s | Closing connection',
87 websocket
.available_subprotocols
,
89 return await websocket
.close()
91 charge_point_id
= path
.strip('/')
92 cp
= ChargePoint(charge_point_id
, websocket
)
94 # Start the ChargePoint instance to listen for incoming messages.
98 # Main function to start the WebSocket server.
100 # Create the WebSocket server and specify the handler for new connections.
101 server
= await websockets
.serve(
103 '127.0.0.1', # Listen on loopback.
105 subprotocols
=['ocpp2.0', 'ocpp2.0.1'] # Specify OCPP 2.0.1 subprotocols.
107 logging
.info("WebSocket Server Started")
108 # Wait for the server to close (runs indefinitely).
109 await server
.wait_closed()
112 # Entry point of the script.
113 if __name__
== '__main__':
114 # Run the main function to start the server.