Nenhuma Descrição

main.py 2.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import asyncio
  2. import logging
  3. from datetime import datetime, timezone
  4. from ocpp.v16.enums import Action, RegistrationStatus, AuthorizationStatus
  5. from ocpp.v16.datatypes import IdTagInfo
  6. from ocpp.v16 import call_result
  7. try:
  8. import websockets
  9. except ModuleNotFoundError:
  10. print("This example relies on the 'websockets' package.")
  11. print("Please install it by running: ")
  12. print()
  13. print(" $ pip install websockets")
  14. import sys
  15. sys.exit(1)
  16. from ocpp.routing import on
  17. from ocpp.v16 import ChargePoint as cp
  18. from ocpp.v16 import call_result
  19. from ocpp.v16.enums import Action, RegistrationStatus
  20. logging.basicConfig(level=logging.INFO)
  21. class ChargePoint(cp):
  22. @on(Action.boot_notification)
  23. def on_boot_notification(
  24. self, charge_point_vendor: str, charge_point_model: str, **kwargs
  25. ):
  26. return call_result.BootNotification(
  27. current_time=datetime.now(timezone.utc).isoformat(),
  28. interval=10,
  29. status=RegistrationStatus.accepted,
  30. )
  31. @on(Action.start_transaction)
  32. def on_start_transaction(
  33. self,
  34. connector_id: int,
  35. id_tag: str,
  36. meter_start: int,
  37. timestamp: str,
  38. **kwargs
  39. ):
  40. print(f"🔌 StartTransaction received from CP with ID tag: {id_tag}")
  41. return call_result.StartTransaction(
  42. transaction_id=1234, # You can generate a real one if needed
  43. id_tag_info={
  44. "status": AuthorizationStatus.accepted
  45. }
  46. )
  47. async def on_connect(websocket):
  48. """For every new charge point that connects, create a ChargePoint
  49. instance and start listening for messages.
  50. """
  51. try:
  52. requested_protocols = websocket.request.headers["Sec-WebSocket-Protocol"]
  53. except KeyError:
  54. logging.error("Client hasn't requested any Subprotocol. Closing Connection")
  55. return await websocket.close()
  56. if websocket.subprotocol:
  57. logging.info("Protocols Matched: %s", websocket.subprotocol)
  58. else:
  59. # In the websockets lib if no subprotocols are supported by the
  60. # client and the server, it proceeds without a subprotocol,
  61. # so we have to manually close the connection.
  62. logging.warning(
  63. "Protocols Mismatched | Expected Subprotocols: %s,"
  64. " but client supports %s | Closing connection",
  65. websocket.available_subprotocols,
  66. requested_protocols,
  67. )
  68. return await websocket.close()
  69. charge_point_id = websocket.request.path.strip("/")
  70. cp = ChargePoint(charge_point_id, websocket)
  71. await cp.start()
  72. async def main():
  73. server = await websockets.serve(
  74. on_connect, "0.0.0.0", 9000, subprotocols=["ocpp1.6"]
  75. )
  76. logging.info("Server Started listening to new connections...")
  77. await server.wait_closed()
  78. if __name__ == "__main__":
  79. # asyncio.run() is used when running this example with Python >= 3.7v
  80. asyncio.run(main())