3 from datetime
import datetime
, timezone
4 from threading
import Timer
8 from ocpp
.routing
import on
9 from ocpp
.v201
.enums
import (
11 AuthorizationStatusType
,
13 RegistrationStatusType
,
17 # Setting up the logging configuration to display debug level messages.
18 logging
.basicConfig(level
=logging
.DEBUG
)
21 class RepeatTimer(Timer
):
22 """Class that inherits from the Timer class. It will run a
23 function at regular intervals."""
26 while not self
.finished
.wait(self
.interval
):
27 self
.function(*self
.args
, **self
.kwargs
)
30 # Define a ChargePoint class inheriting from the OCPP 2.0.1 ChargePoint class.
31 class ChargePoint(ocpp
.v201
.ChargePoint
):
32 # Message handlers to receive OCPP messages.
33 @on(Action
.BootNotification
)
34 async def on_boot_notification(self
, charging_station
, reason
, **kwargs
):
35 logging
.info("Received BootNotification")
36 # Create and return a BootNotification response with the current time,
37 # an interval of 60 seconds, and an accepted status.
38 return ocpp
.v201
.call_result
.BootNotification(
39 current_time
=datetime
.now(timezone
.utc
).isoformat(),
41 status
=RegistrationStatusType
.accepted
,
45 async def on_heartbeat(self
, **kwargs
):
46 logging
.info("Received Heartbeat")
47 return ocpp
.v201
.call_result
.Heartbeat(
48 current_time
=datetime
.now(timezone
.utc
).isoformat()
51 @on(Action
.StatusNotification
)
52 async def on_status_notification(
53 self
, timestamp
, evse_id
: int, connector_id
: int, connector_status
, **kwargs
55 logging
.info("Received StatusNotification")
56 return ocpp
.v201
.call_result
.StatusNotification()
59 async def on_authorize(self
, id_token
, **kwargs
):
60 logging
.info("Received Authorize")
61 return ocpp
.v201
.call_result
.Authorize(
62 id_token_info
={"status": AuthorizationStatusType
.accepted
}
65 @on(Action
.TransactionEvent
)
66 async def on_transaction_event(
68 event_type
: TransactionEventType
,
76 case TransactionEventType
.started
:
77 logging
.info("Received TransactionEvent Started")
78 return ocpp
.v201
.call_result
.TransactionEvent(
79 id_token_info
={"status": AuthorizationStatusType
.accepted
}
81 case TransactionEventType
.updated
:
82 logging
.info("Received TransactionEvent Updated")
83 return ocpp
.v201
.call_result
.TransactionEvent(total_cost
=10)
84 case TransactionEventType
.ended
:
85 logging
.info("Received TransactionEvent Ended")
86 return ocpp
.v201
.call_result
.TransactionEvent()
88 @on(Action
.MeterValues
)
89 async def on_meter_values(self
, evse_id
: int, meter_value
, **kwargs
):
90 logging
.info("Received MeterValues")
91 return ocpp
.v201
.call_result
.MeterValues()
93 # Request handlers to emit OCPP messages.
94 async def send_clear_cache(self
):
95 request
= ocpp
.v201
.call
.ClearCache()
96 response
= await self
.call(request
)
98 if response
.status
== ClearCacheStatusType
.accepted
:
99 logging
.info("Cache clearing successful")
101 logging
.info("Cache clearing failed")
104 # Function to handle new WebSocket connections.
105 async def on_connect(websocket
, path
):
106 """For every new charge point that connects, create a ChargePoint instance and start
107 listening for messages."""
109 requested_protocols
= websocket
.request_headers
["Sec-WebSocket-Protocol"]
111 logging
.info("Client hasn't requested any Subprotocol. Closing Connection")
112 return await websocket
.close()
114 if websocket
.subprotocol
:
115 logging
.info("Protocols Matched: %s", websocket
.subprotocol
)
118 "Protocols Mismatched | Expected Subprotocols: %s,"
119 " but client supports %s | Closing connection",
120 websocket
.available_subprotocols
,
123 return await websocket
.close()
125 charge_point_id
= path
.strip("/")
126 cp
= ChargePoint(charge_point_id
, websocket
)
128 # Start the ChargePoint instance to listen for incoming messages.
132 # Main function to start the WebSocket server.
134 # Create the WebSocket server and specify the handler for new connections.
135 server
= await websockets
.serve(
137 "127.0.0.1", # Listen on loopback.
139 subprotocols
=["ocpp2.0", "ocpp2.0.1"], # Specify OCPP 2.0.1 subprotocols.
141 logging
.info("WebSocket Server Started")
142 # Wait for the server to close (runs indefinitely).
143 await server
.wait_closed()
146 # Entry point of the script.
147 if __name__
== "__main__":
148 # Run the main function to start the server.