| 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 RegistrationStatusType, ClearCacheStatusType, AuthorizationStatusType, \ |
| 10 | TransactionEventType, \ |
| 11 | Action |
| 12 | |
| 13 | # Setting up the logging configuration to display debug level messages. |
| 14 | logging.basicConfig(level=logging.DEBUG) |
| 15 | |
| 16 | |
| 17 | class RepeatTimer(Timer): |
| 18 | """ Class that inherits from the Timer class. It will run a |
| 19 | function at regular intervals.""" |
| 20 | |
| 21 | def run(self): |
| 22 | while not self.finished.wait(self.interval): |
| 23 | self.function(*self.args, **self.kwargs) |
| 24 | |
| 25 | |
| 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(), |
| 36 | interval=60, |
| 37 | status=RegistrationStatusType.accepted |
| 38 | ) |
| 39 | |
| 40 | @on(Action.Heartbeat) |
| 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()) |
| 44 | |
| 45 | @on(Action.StatusNotification) |
| 46 | async def on_status_notification(self, timestamp, evse_id, connector_id, connector_status, |
| 47 | **kwargs): |
| 48 | logging.info("Received StatusNotification") |
| 49 | return ocpp.v201.call_result.StatusNotification() |
| 50 | |
| 51 | @on(Action.Authorize) |
| 52 | async def on_authorize(self, id_token, **kwargs): |
| 53 | logging.info("Received Authorize") |
| 54 | return ocpp.v201.call_result.Authorize( |
| 55 | id_token_info={'status': AuthorizationStatusType.accepted} |
| 56 | ) |
| 57 | |
| 58 | @on(Action.TransactionEvent) |
| 59 | async def on_transaction_event(self, event_type, timestamp, trigger_reason, seq_no, |
| 60 | transaction_info, **kwargs): |
| 61 | match event_type: |
| 62 | case TransactionEventType.started: |
| 63 | logging.info("Received TransactionEvent Started") |
| 64 | return ocpp.v201.call_result.TransactionEvent( |
| 65 | id_token_info={'status': AuthorizationStatusType.accepted} |
| 66 | ) |
| 67 | case TransactionEventType.updated: |
| 68 | logging.info("Received TransactionEvent Updated") |
| 69 | return ocpp.v201.call_result.TransactionEvent( |
| 70 | total_cost=10 |
| 71 | ) |
| 72 | case TransactionEventType.ended: |
| 73 | logging.info("Received TransactionEvent Ended") |
| 74 | return ocpp.v201.call_result.TransactionEvent() |
| 75 | |
| 76 | @on(Action.MeterValues) |
| 77 | async def on_meter_values(self, evse_id, meter_value, **kwargs): |
| 78 | logging.info("Received MeterValues") |
| 79 | return ocpp.v201.call_result.MeterValues() |
| 80 | |
| 81 | # Request handlers to emit OCPP messages. |
| 82 | async def send_clear_cache(self): |
| 83 | request = ocpp.v201.call.ClearCache() |
| 84 | response = await self.call(request) |
| 85 | |
| 86 | if response.status == ClearCacheStatusType.accepted: |
| 87 | logging.info("Cache clearing successful") |
| 88 | else: |
| 89 | logging.info("Cache clearing failed") |
| 90 | |
| 91 | |
| 92 | # Function to handle new WebSocket connections. |
| 93 | async def on_connect(websocket, path): |
| 94 | """ For every new charge point that connects, create a ChargePoint instance and start |
| 95 | listening for messages.""" |
| 96 | try: |
| 97 | requested_protocols = websocket.request_headers['Sec-WebSocket-Protocol'] |
| 98 | except KeyError: |
| 99 | logging.info("Client hasn't requested any Subprotocol. Closing Connection") |
| 100 | return await websocket.close() |
| 101 | |
| 102 | if websocket.subprotocol: |
| 103 | logging.info("Protocols Matched: %s", websocket.subprotocol) |
| 104 | else: |
| 105 | logging.warning('Protocols Mismatched | Expected Subprotocols: %s,' |
| 106 | ' but client supports %s | Closing connection', |
| 107 | websocket.available_subprotocols, |
| 108 | requested_protocols |
| 109 | ) |
| 110 | return await websocket.close() |
| 111 | |
| 112 | charge_point_id = path.strip('/') |
| 113 | cp = ChargePoint(charge_point_id, websocket) |
| 114 | |
| 115 | # Start the ChargePoint instance to listen for incoming messages. |
| 116 | await cp.start() |
| 117 | |
| 118 | |
| 119 | # Main function to start the WebSocket server. |
| 120 | async def main(): |
| 121 | # Create the WebSocket server and specify the handler for new connections. |
| 122 | server = await websockets.serve( |
| 123 | on_connect, |
| 124 | '127.0.0.1', # Listen on loopback. |
| 125 | 9000, # Port number. |
| 126 | subprotocols=['ocpp2.0', 'ocpp2.0.1'] # Specify OCPP 2.0.1 subprotocols. |
| 127 | ) |
| 128 | logging.info("WebSocket Server Started") |
| 129 | # Wait for the server to close (runs indefinitely). |
| 130 | await server.wait_closed() |
| 131 | |
| 132 | |
| 133 | # Entry point of the script. |
| 134 | if __name__ == '__main__': |
| 135 | # Run the main function to start the server. |
| 136 | asyncio.run(main()) |