main.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. #!/usr/bin/env python3
  2. import argparse
  3. import asyncio
  4. import signal
  5. import traceback
  6. import aiomqtt
  7. from bleak import BleakScanner
  8. from bleak.exc import BleakError, BleakDeviceNotFoundError
  9. from src.homeassistant import MqttSensor
  10. from src.bleclient import BleClient, Result
  11. from src.variables import variables, VariableContainer, battery_and_load_parameters, switches
  12. request_interval = 20 # In seconds
  13. reconnect_interval = 5 # In seconds
  14. async def request_and_publish_details(sensor: MqttSensor, mppt: BleClient) -> None:
  15. details = await mppt.request_details()
  16. if details:
  17. print(f"Battery: {details['battery_percentage'].value}% ({details['battery_voltage'].value}V)")
  18. await sensor.publish(details)
  19. else:
  20. print("No values recieved")
  21. async def subscribe_and_watch(sensor: MqttSensor, mppt: BleClient):
  22. parameters = battery_and_load_parameters[:12] + switches
  23. await sensor.subscribe(parameters)
  24. await sensor.store_config(switches)
  25. while True:
  26. command = await sensor.get_command()
  27. print(f"Received command to set {command.name} to '{command.value}'")
  28. results = await mppt.write([command])
  29. await sensor.publish(results)
  30. async def run_mppt(sensor: MqttSensor, address: str):
  31. task = None
  32. loop = asyncio.get_event_loop()
  33. try:
  34. async with BleClient(address) as mppt:
  35. task = loop.create_task(subscribe_and_watch(sensor, mppt))
  36. parameters = await mppt.request_parameters()
  37. await sensor.publish(parameters)
  38. while True:
  39. await request_and_publish_details(sensor, mppt)
  40. await asyncio.sleep(request_interval)
  41. if not task.cancelled() and task.exception:
  42. break
  43. except EOFError:
  44. pass
  45. except asyncio.TimeoutError:
  46. print("BLE communication timed out")
  47. return
  48. except BleakDeviceNotFoundError:
  49. print(f"BLE device with address {address} was not found")
  50. return
  51. except BleakError as e:
  52. print(f"BLE error occurred: {e}")
  53. return
  54. finally:
  55. if task:
  56. task.cancel()
  57. try:
  58. await task
  59. except asyncio.CancelledError:
  60. pass
  61. print("BLE device disconnected")
  62. async def run_mqtt(address, host, port, username, password):
  63. while True:
  64. try:
  65. async with MqttSensor(hostname=host, port=port, username=username, password=password) as sensor:
  66. print(f"Connected to MQTT broker at {host}:{port}")
  67. while True:
  68. await run_mppt(sensor, address)
  69. await asyncio.sleep(reconnect_interval)
  70. except aiomqtt.MqttError as error:
  71. print(f'Error "{error}". Reconnecting in {reconnect_interval} seconds.')
  72. except asyncio.CancelledError:
  73. raise # Re-raise the CancelledError to stop the task
  74. except Exception as e:
  75. print(traceback.format_exc())
  76. await asyncio.sleep(reconnect_interval)
  77. async def main(*args):
  78. try:
  79. loop = asyncio.get_running_loop()
  80. task = loop.create_task(run_mqtt(*args))
  81. # Setup signal handler to cancel the task on termination
  82. for signame in {'SIGINT', 'SIGTERM'}:
  83. loop.add_signal_handler(getattr(signal, signame),
  84. task.cancel)
  85. await task # Wait for the task to complete
  86. except asyncio.CancelledError:
  87. pass # Task was cancelled, no need for an error message
  88. async def list_services(address):
  89. async with BleClient(address) as mppt:
  90. await mppt.list_services()
  91. async def scan_for_devices():
  92. devices = await BleakScanner.discover()
  93. if not devices:
  94. print("No BLE devices found.")
  95. else:
  96. print("Available BLE devices:")
  97. for device in devices:
  98. print(f"{device.address} - {device.name}")
  99. return devices
  100. if __name__ == '__main__':
  101. parser = argparse.ArgumentParser(description='Solarlife MPPT BLE Client')
  102. parser.add_argument('address', help='BLE device address')
  103. parser.add_argument('--host', help='MQTT broker host', default='localhost')
  104. parser.add_argument('--port', help='MQTT broker port', default=1883, type=int)
  105. parser.add_argument('--username', help='MQTT username')
  106. parser.add_argument('--password', help='MQTT password')
  107. parser.add_argument('--list-services', help='List GATT services', action='store_true')
  108. parser.add_argument('--scan', help='Scan for bluetooth devices', action='store_true')
  109. args = parser.parse_args()
  110. if args.scan:
  111. asyncio.run(scan_for_devices())
  112. elif args.list_services:
  113. asyncio.run(list_services(args.address))
  114. else:
  115. asyncio.run(main(args.address, args.host, args.port, args.username, args.password))