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
, \
10 TransactionEventType
, \
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(Action
.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 60 seconds, and an accepted status.
34 return ocpp
.v201
.call_result
.BootNotification(
35 current_time
=datetime
.now(timezone
.utc
).isoformat(),
37 status
=RegistrationStatusType
.accepted
41 async def on_heartbeat(self
, **kwargs
):
42 logging
.info("Received Heartbeat")
43 return ocpp
.v201
.call_result
.Heartbeat(current_time
=datetime
.now(timezone
.utc
).isoformat())
45 @on(Action
.StatusNotification
)
46 async def on_status_notification(self
, timestamp
, evse_id
: int, connector_id
: int,
49 logging
.info("Received StatusNotification")
50 return ocpp
.v201
.call_result
.StatusNotification()
53 async def on_authorize(self
, id_token
, **kwargs
):
54 logging
.info("Received Authorize")
55 return ocpp
.v201
.call_result
.Authorize(
56 id_token_info
={'status': AuthorizationStatusType
.accepted
}
59 @on(Action
.TransactionEvent
)
60 async def on_transaction_event(self
, event_type
: TransactionEventType
, timestamp
,
61 trigger_reason
, seq_no
: int,
62 transaction_info
, **kwargs
):
64 case TransactionEventType
.started
:
65 logging
.info("Received TransactionEvent Started")
66 return ocpp
.v201
.call_result
.TransactionEvent(
67 id_token_info
={'status': AuthorizationStatusType
.accepted
}
69 case TransactionEventType
.updated
:
70 logging
.info("Received TransactionEvent Updated")
71 return ocpp
.v201
.call_result
.TransactionEvent(
74 case TransactionEventType
.ended
:
75 logging
.info("Received TransactionEvent Ended")
76 return ocpp
.v201
.call_result
.TransactionEvent()
78 @on(Action
.MeterValues
)
79 async def on_meter_values(self
, evse_id
: int, meter_value
, **kwargs
):
80 logging
.info("Received MeterValues")
81 return ocpp
.v201
.call_result
.MeterValues()
83 # Request handlers to emit OCPP messages.
84 async def send_clear_cache(self
):
85 request
= ocpp
.v201
.call
.ClearCache()
86 response
= await self
.call(request
)
88 if response
.status
== ClearCacheStatusType
.accepted
:
89 logging
.info("Cache clearing successful")
91 logging
.info("Cache clearing failed")
94 # Function to handle new WebSocket connections.
95 async def on_connect(websocket
, path
):
96 """ For every new charge point that connects, create a ChargePoint instance and start
97 listening for messages."""
99 requested_protocols
= websocket
.request_headers
['Sec-WebSocket-Protocol']
101 logging
.info("Client hasn't requested any Subprotocol. Closing Connection")
102 return await websocket
.close()
104 if websocket
.subprotocol
:
105 logging
.info("Protocols Matched: %s", websocket
.subprotocol
)
107 logging
.warning('Protocols Mismatched | Expected Subprotocols: %s,'
108 ' but client supports %s | Closing connection',
109 websocket
.available_subprotocols
,
112 return await websocket
.close()
114 charge_point_id
= path
.strip('/')
115 cp
= ChargePoint(charge_point_id
, websocket
)
117 # Start the ChargePoint instance to listen for incoming messages.
121 # Main function to start the WebSocket server.
123 # Create the WebSocket server and specify the handler for new connections.
124 server
= await websockets
.serve(
126 '127.0.0.1', # Listen on loopback.
128 subprotocols
=['ocpp2.0', 'ocpp2.0.1'] # Specify OCPP 2.0.1 subprotocols.
130 logging
.info("WebSocket Server Started")
131 # Wait for the server to close (runs indefinitely).
132 await server
.wait_closed()
135 # Entry point of the script.
136 if __name__
== '__main__':
137 # Run the main function to start the server.