Nessuna descrizione

central_system.py 2.3KB

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