Bez popisu

central_system.py 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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.v20 import ChargePoint as cp
  15. from ocpp.v20 import call_result
  16. logging.basicConfig(level=logging.INFO)
  17. class ChargePoint(cp):
  18. @on("BootNotification")
  19. def on_boot_notification(self, charging_station, reason, **kwargs):
  20. return call_result.BootNotificationPayload(
  21. current_time=datetime.utcnow().isoformat(), interval=10, status="Accepted"
  22. )
  23. @on("Heartbeat")
  24. def on_heartbeat(self):
  25. print("Got a Heartbeat!")
  26. return call_result.HeartbeatPayload(
  27. current_time=datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S") + "Z"
  28. )
  29. async def on_connect(websocket, path):
  30. """For every new charge point that connects, create a ChargePoint
  31. instance and start listening for messages.
  32. """
  33. try:
  34. requested_protocols = websocket.request_headers["Sec-WebSocket-Protocol"]
  35. except KeyError:
  36. logging.error("Client hasn't requested any Subprotocol. Closing Connection")
  37. return await websocket.close()
  38. if websocket.subprotocol:
  39. logging.info("Protocols Matched: %s", websocket.subprotocol)
  40. else:
  41. # In the websockets lib if no subprotocols are supported by the
  42. # client and the server, it proceeds without a subprotocol,
  43. # so we have to manually close the connection.
  44. logging.warning(
  45. "Protocols Mismatched | Expected Subprotocols: %s,"
  46. " but client supports %s | Closing connection",
  47. websocket.available_subprotocols,
  48. requested_protocols,
  49. )
  50. return await websocket.close()
  51. charge_point_id = path.strip("/")
  52. cp = ChargePoint(charge_point_id, websocket)
  53. await cp.start()
  54. async def main():
  55. server = await websockets.serve(
  56. on_connect, "0.0.0.0", 9000, subprotocols=["ocpp2.0"]
  57. )
  58. logging.info("Server Started listening to new connections...")
  59. await server.wait_closed()
  60. if __name__ == "__main__":
  61. # asyncio.run() is used when running this example with Python >= 3.7v
  62. asyncio.run(main())