Нет описания

cs.py 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import asyncio
  2. import logging
  3. import websockets
  4. from datetime import datetime
  5. from ocpp.routing import on
  6. from ocpp.v201 import ChargePoint as cp
  7. from ocpp.v201 import call_result
  8. from ocpp.v201.enums import RegistrationStatusType
  9. logging.basicConfig(level=logging.INFO)
  10. class ChargePoint(cp):
  11. @on('BootNotification')
  12. async def on_boot_notification(self, charging_station, reason, **kwargs):
  13. return call_result.BootNotificationPayload(
  14. current_time=datetime.utcnow().isoformat(),
  15. interval=10,
  16. status=RegistrationStatusType.accepted
  17. )
  18. async def on_connect(websocket, path):
  19. """ For every new charge point that connects, create a ChargePoint
  20. instance and start listening for messages.
  21. """
  22. try:
  23. requested_protocols = websocket.request_headers[
  24. 'Sec-WebSocket-Protocol']
  25. except KeyError:
  26. logging.info("Client hasn't requested any Subprotocol. "
  27. "Closing Connection")
  28. return await websocket.close()
  29. if websocket.subprotocol:
  30. logging.info("Protocols Matched: %s", websocket.subprotocol)
  31. else:
  32. # In the websockets lib if no subprotocols are supported by the
  33. # client and the server, it proceeds without a subprotocol,
  34. # so we have to manually close the connection.
  35. logging.warning('Protocols Mismatched | Expected Subprotocols: %s,'
  36. ' but client supports %s | Closing connection',
  37. websocket.available_subprotocols,
  38. requested_protocols)
  39. return await websocket.close()
  40. charge_point_id = path.strip('/')
  41. cp = ChargePoint(charge_point_id, websocket)
  42. await cp.start()
  43. async def main():
  44. server = await websockets.serve(
  45. on_connect,
  46. '0.0.0.0',
  47. 9000,
  48. subprotocols=['ocpp1.6']
  49. )
  50. logging.info("WebSocket Server Started")
  51. await server.wait_closed()
  52. if __name__ == '__main__':
  53. asyncio.run(main())