simple-ocpp-cs/app/routers/ocpp_v1.py

48 lines
1.8 KiB
Python
Raw Normal View History

2024-03-28 21:23:25 +01:00
import logging
from fastapi import APIRouter, WebSocket, WebSocketException
2024-04-13 22:43:03 +02:00
from app.ocpp_proto import chargepoint_manager
from app.ocpp_proto.chargepoint import ChargePoint
from app.util.websocket_wrapper import WebSocketWrapper
2024-03-28 21:23:25 +01:00
router = APIRouter()
2024-04-13 22:43:03 +02:00
@router.websocket("/{charging_station_friendly_name}")
2024-03-28 21:23:25 +01:00
async def websocket_endpoint(
*,
websocket: WebSocket,
2024-04-13 22:43:03 +02:00
charging_station_friendly_name: str,
2024-03-28 21:23:25 +01:00
):
""" For every new charging station that connects, create a ChargePoint
instance and start listening for messages.
"""
2024-04-13 22:43:03 +02:00
if (websocket.user.friendly_name != charging_station_friendly_name):
2024-03-28 21:23:25 +01:00
raise WebSocketException(code=1008, reason="Username doesn't match chargepoint identifier")
2024-04-13 22:43:03 +02:00
logging.info("Charging station '%s' (%s) connected", charging_station_friendly_name, websocket.user.id)
2024-03-28 21:23:25 +01:00
# Check protocols
try:
requested_protocols = websocket.headers['sec-websocket-protocol']
logging.info("Protocols advertised by charging station: %s", requested_protocols)
except KeyError:
logging.warning("Charging station hasn't advertised any subprotocol. "
"Closing Connection")
return await websocket.close()
if "ocpp2.0.1" in requested_protocols:
logging.info("Matched supported protocol: ocpp2.0.1")
else:
logging.warning('Protocols mismatched | Expected subprotocols: %s,'
' but client supports %s | Closing connection',
"ocpp2.0.1",
requested_protocols)
await websocket.accept()
await websocket.close()
return
# Accept connection and begin communication
await websocket.accept(subprotocol="ocpp2.0.1")
2024-04-13 22:43:03 +02:00
cp = ChargePoint(charging_station_friendly_name, WebSocketWrapper(websocket))
await chargepoint_manager.start(websocket.user.id, cp)