* add tsun_v2 default configuration * Add port 10000 for gen 3 plus inverters * add monitor_sn for solarman support * listen on port 10000 for solarman inverters * initial version for gen 3 plus support * refactoring split gen3 and gen3plus * refactoring * refactoring classes * refactor proxy statistic counter * - fix loggin levels - user super() in close() and __del__() * add config for gen 3 plus * Add solarman config support * refacot Message.. classes * rename class MessageG3 into Talent * refactor close() handler * refactor disc() handler * move loop() into the base class AsyncStream * move async_read, _write and _forward into base class * Cleanup * move server_loop and client_loop into basic class * add msg forwarding for solarman V5 protocol * move server_loop() and client_loop to class AsyncStream * rename AsyncStreamxx ton Connectionxx * fix unit tests * make more attributes privae * load .env file * wait after last test * ignore .env * add response handler * Update README.md * update unreleased changes * home assistant add more diagnostic values * fix typo * Update README.md Definition of the inverter generations added to the compatibility table * add ha couter for 'Internal SW Exceptions' * Update README.md Fixes an incorrect marking in the display of the configuration file * Update README.md Planning documented for MS-2000 support * S allius/issue33 (#34) * - fix issue 33 The TSUN Cloud now responds to contact_info and get_time messages with an empty display message and not with a response message as before. We tried to parse data from the empty message, which led to an exception * Add test with empty conn_ind from inverter * version 0.5.5 * add tsun_v2 default configuration * Add port 10000 for gen 3 plus inverters * add monitor_sn for solarman support * listen on port 10000 for solarman inverters initial version for gen 3 plus support * refactoring split gen3 and gen3plus * refactoring * refactoring classes * refactor proxy statistic counter * - fix loggin levels - user super() in close() and __del__() * add config for gen 3 plus * Add solarman config support * refacot Message.. classes * rename class MessageG3 into Talent * refactor close() handler * refactor disc() handler * move loop() into the base class AsyncStream * move async_read, _write and _forward into base class * Cleanup * move server_loop and client_loop into basic class * add msg forwarding for solarman V5 protocol * move server_loop() and client_loop to class AsyncStream * rename AsyncStreamxx ton Connectionxx * fix unit tests * make more attributes privae load .env file * wait after last test * ignore .env * add response handler
96 lines
3.2 KiB
Python
96 lines
3.2 KiB
Python
import asyncio
|
|
import logging
|
|
import aiomqtt
|
|
from config import Config
|
|
|
|
logger_mqtt = logging.getLogger('mqtt')
|
|
|
|
|
|
class Singleton(type):
|
|
_instances = {}
|
|
|
|
def __call__(cls, *args, **kwargs):
|
|
logger_mqtt.debug('singleton: __call__')
|
|
if cls not in cls._instances:
|
|
cls._instances[cls] = super(Singleton,
|
|
cls).__call__(*args, **kwargs)
|
|
return cls._instances[cls]
|
|
|
|
|
|
class Mqtt(metaclass=Singleton):
|
|
__client = None
|
|
__cb_MqttIsUp = None
|
|
|
|
def __init__(self, cb_MqttIsUp):
|
|
logger_mqtt.debug('MQTT: __init__')
|
|
if cb_MqttIsUp:
|
|
self.cb_MqttIsUp = cb_MqttIsUp
|
|
loop = asyncio.get_event_loop()
|
|
self.task = loop.create_task(self.__loop())
|
|
self.ha_restarts = 0
|
|
|
|
@property
|
|
def ha_restarts(self):
|
|
return self._ha_restarts
|
|
|
|
@ha_restarts.setter
|
|
def ha_restarts(self, value):
|
|
self._ha_restarts = value
|
|
|
|
def __del__(self):
|
|
logger_mqtt.debug('MQTT: __del__')
|
|
|
|
async def close(self) -> None:
|
|
logger_mqtt.debug('MQTT: close')
|
|
self.task.cancel()
|
|
try:
|
|
await self.task
|
|
except Exception as e:
|
|
logging.debug(f"Mqtt.close: exception: {e} ...")
|
|
|
|
async def publish(self, topic: str, payload: str | bytes | bytearray
|
|
| int | float | None = None) -> None:
|
|
if self.__client:
|
|
await self.__client.publish(topic, payload)
|
|
|
|
async def __loop(self) -> None:
|
|
mqtt = Config.get('mqtt')
|
|
ha = Config.get('ha')
|
|
logger_mqtt.info(f'start MQTT: host:{mqtt["host"]} port:'
|
|
f'{mqtt["port"]} '
|
|
f'user:{mqtt["user"]}')
|
|
self.__client = aiomqtt.Client(hostname=mqtt['host'],
|
|
port=mqtt['port'],
|
|
username=mqtt['user'],
|
|
password=mqtt['passwd'])
|
|
|
|
interval = 5 # Seconds
|
|
while True:
|
|
try:
|
|
async with self.__client:
|
|
logger_mqtt.info('MQTT broker connection established')
|
|
|
|
if self.cb_MqttIsUp:
|
|
await self.cb_MqttIsUp()
|
|
|
|
async with self.__client.messages() as messages:
|
|
await self.__client.subscribe(
|
|
f"{ha['auto_conf_prefix']}"
|
|
"/status")
|
|
async for message in messages:
|
|
status = message.payload.decode("UTF-8")
|
|
logger_mqtt.info('Home-Assistant Status:'
|
|
f' {status}')
|
|
if status == 'online':
|
|
self.ha_restarts += 1
|
|
await self.cb_MqttIsUp()
|
|
|
|
except aiomqtt.MqttError:
|
|
logger_mqtt.info(f"Connection lost; Reconnecting in {interval}"
|
|
" seconds ...")
|
|
await asyncio.sleep(interval)
|
|
except asyncio.CancelledError:
|
|
logger_mqtt.debug("MQTT task cancelled")
|
|
self.__client = None
|
|
return
|