| 1 | import asyncio |
| 2 | import logging |
| 3 | from datetime import datetime, timezone |
| 4 | from threading import Timer |
| 5 | |
| 6 | import ocpp.v201 |
| 7 | import websockets |
| 8 | from ocpp.routing import on |
| 9 | from ocpp.v201.enums import ( |
| 10 | Action, |
| 11 | AuthorizationStatusType, |
| 12 | ClearCacheStatusType, |
| 13 | RegistrationStatusType, |
| 14 | TransactionEventType, |
| 15 | ) |
| 16 | from websockets import ConnectionClosed |
| 17 | |
| 18 | # Setting up the logging configuration to display debug level messages. |
| 19 | logging.basicConfig(level=logging.DEBUG) |
| 20 | |
| 21 | ChargePoints = set() |
| 22 | |
| 23 | |
| 24 | class RepeatTimer(Timer): |
| 25 | """Class that inherits from the Timer class. It will run a |
| 26 | function at regular intervals.""" |
| 27 | |
| 28 | def run(self): |
| 29 | while not self.finished.wait(self.interval): |
| 30 | self.function(*self.args, **self.kwargs) |
| 31 | |
| 32 | |
| 33 | # Define a ChargePoint class inheriting from the OCPP 2.0.1 ChargePoint class. |
| 34 | class ChargePoint(ocpp.v201.ChargePoint): |
| 35 | def __init__(self, charge_point_id, connection): |
| 36 | super().__init__(self, charge_point_id, connection) |
| 37 | self._ws_ping_timer = RepeatTimer(60, self.web_socket_ping) |
| 38 | self._ws_ping_timer.start() |
| 39 | |
| 40 | def stop(self): |
| 41 | self._ws_ping_timer.cancel() |
| 42 | |
| 43 | def web_socket_ping(self): |
| 44 | try: |
| 45 | self._connection.ping() |
| 46 | except ConnectionClosed: |
| 47 | ChargePoints.remove(self) |
| 48 | self.stop() |
| 49 | |
| 50 | # Message handlers to receive OCPP messages. |
| 51 | @on(Action.BootNotification) |
| 52 | async def on_boot_notification(self, charging_station, reason, **kwargs): |
| 53 | logging.info("Received BootNotification") |
| 54 | # Create and return a BootNotification response with the current time, |
| 55 | # an interval of 60 seconds, and an accepted status. |
| 56 | return ocpp.v201.call_result.BootNotification( |
| 57 | current_time=datetime.now(timezone.utc).isoformat(), |
| 58 | interval=60, |
| 59 | status=RegistrationStatusType.accepted, |
| 60 | ) |
| 61 | |
| 62 | @on(Action.Heartbeat) |
| 63 | async def on_heartbeat(self, **kwargs): |
| 64 | logging.info("Received Heartbeat") |
| 65 | return ocpp.v201.call_result.Heartbeat( |
| 66 | current_time=datetime.now(timezone.utc).isoformat() |
| 67 | ) |
| 68 | |
| 69 | @on(Action.StatusNotification) |
| 70 | async def on_status_notification( |
| 71 | self, timestamp, evse_id: int, connector_id: int, connector_status, **kwargs |
| 72 | ): |
| 73 | logging.info("Received StatusNotification") |
| 74 | return ocpp.v201.call_result.StatusNotification() |
| 75 | |
| 76 | @on(Action.Authorize) |
| 77 | async def on_authorize(self, id_token, **kwargs): |
| 78 | logging.info("Received Authorize") |
| 79 | return ocpp.v201.call_result.Authorize( |
| 80 | id_token_info={"status": AuthorizationStatusType.accepted} |
| 81 | ) |
| 82 | |
| 83 | @on(Action.TransactionEvent) |
| 84 | async def on_transaction_event( |
| 85 | self, |
| 86 | event_type: TransactionEventType, |
| 87 | timestamp, |
| 88 | trigger_reason, |
| 89 | seq_no: int, |
| 90 | transaction_info, |
| 91 | **kwargs, |
| 92 | ): |
| 93 | match event_type: |
| 94 | case TransactionEventType.started: |
| 95 | logging.info("Received TransactionEvent Started") |
| 96 | return ocpp.v201.call_result.TransactionEvent( |
| 97 | id_token_info={"status": AuthorizationStatusType.accepted} |
| 98 | ) |
| 99 | case TransactionEventType.updated: |
| 100 | logging.info("Received TransactionEvent Updated") |
| 101 | return ocpp.v201.call_result.TransactionEvent(total_cost=10) |
| 102 | case TransactionEventType.ended: |
| 103 | logging.info("Received TransactionEvent Ended") |
| 104 | return ocpp.v201.call_result.TransactionEvent() |
| 105 | |
| 106 | @on(Action.MeterValues) |
| 107 | async def on_meter_values(self, evse_id: int, meter_value, **kwargs): |
| 108 | logging.info("Received MeterValues") |
| 109 | return ocpp.v201.call_result.MeterValues() |
| 110 | |
| 111 | # Request handlers to emit OCPP messages. |
| 112 | async def send_clear_cache(self): |
| 113 | request = ocpp.v201.call.ClearCache() |
| 114 | response = await self.call(request) |
| 115 | |
| 116 | if response.status == ClearCacheStatusType.accepted: |
| 117 | logging.info("Cache clearing successful") |
| 118 | else: |
| 119 | logging.info("Cache clearing failed") |
| 120 | |
| 121 | |
| 122 | # Function to handle new WebSocket connections. |
| 123 | async def on_connect(websocket, path): |
| 124 | """For every new charge point that connects, create a ChargePoint instance and start |
| 125 | listening for messages.""" |
| 126 | try: |
| 127 | requested_protocols = websocket.request_headers["Sec-WebSocket-Protocol"] |
| 128 | except KeyError: |
| 129 | logging.info("Client hasn't requested any Subprotocol. Closing Connection") |
| 130 | return await websocket.close() |
| 131 | |
| 132 | if websocket.subprotocol: |
| 133 | logging.info("Protocols Matched: %s", websocket.subprotocol) |
| 134 | else: |
| 135 | logging.warning( |
| 136 | "Protocols Mismatched | Expected Subprotocols: %s," |
| 137 | " but client supports %s | Closing connection", |
| 138 | websocket.available_subprotocols, |
| 139 | requested_protocols, |
| 140 | ) |
| 141 | return await websocket.close() |
| 142 | |
| 143 | charge_point_id = path.strip("/") |
| 144 | cp = ChargePoint(charge_point_id, websocket) |
| 145 | ChargePoints.add(cp) |
| 146 | |
| 147 | # Start the ChargePoint instance to listen for incoming messages. |
| 148 | await cp.start() |
| 149 | |
| 150 | |
| 151 | # Main function to start the WebSocket server. |
| 152 | async def main(): |
| 153 | # Create the WebSocket server and specify the handler for new connections. |
| 154 | server = await websockets.serve( |
| 155 | on_connect, |
| 156 | "127.0.0.1", # Listen on loopback. |
| 157 | 9000, # Port number. |
| 158 | subprotocols=["ocpp2.0", "ocpp2.0.1"], # Specify OCPP 2.0.1 subprotocols. |
| 159 | ) |
| 160 | logging.info("WebSocket Server Started") |
| 161 | # Wait for the server to close (runs indefinitely). |
| 162 | await server.wait_closed() |
| 163 | |
| 164 | |
| 165 | # Entry point of the script. |
| 166 | if __name__ == "__main__": |
| 167 | # Run the main function to start the server. |
| 168 | asyncio.run(main()) |