Нет описания

central_system.py 2.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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.v201 import ChargePoint as cp
  15. from ocpp.v201 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. charge_point = ChargePoint(charge_point_id, websocket)
  53. await charge_point.start()
  54. async def main():
  55. # deepcode ignore BindToAllNetworkInterfaces: <Example Purposes>
  56. server = await websockets.serve(
  57. on_connect, "0.0.0.0", 9000, subprotocols=["ocpp2.0.1"]
  58. )
  59. logging.info("Server Started listening to new connections...")
  60. await server.wait_closed()
  61. if __name__ == "__main__":
  62. # asyncio.run() is used when running this example with Python >= 3.7v
  63. asyncio.run(main())