Skip to content

Commit

Permalink
auto reconnect
Browse files Browse the repository at this point in the history
  • Loading branch information
tolwi committed Sep 21, 2023
1 parent 59681be commit adc72c6
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 11 deletions.
31 changes: 22 additions & 9 deletions custom_components/ecoflow_cloud/mqtt/ecoflow_mqtt.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,11 +203,19 @@ def __init__(self, hass: HomeAssistant, entry: ConfigEntry, auth: EcoflowAuthent
self.client.connect(self.auth.mqtt_url, self.auth.mqtt_port, 30)
self.client.loop_start()

def reconnect(self):
_LOGGER.info(f"Re-connecting to MQTT Broker {self.auth.mqtt_url}:{self.auth.mqtt_port}")
self.client.loop_stop(True)
self.client.reconnect()
self.client.loop_start()
def is_connected(self):
return self.client.is_connected()

def reconnect(self) -> bool:
try:
_LOGGER.info(f"Re-connecting to MQTT Broker {self.auth.mqtt_url}:{self.auth.mqtt_port}")
self.client.loop_stop(True)
self.client.reconnect()
self.client.loop_start()
return True
except Exception as e:
_LOGGER.error(e)
return False

def on_connect(self, client, userdata, flags, rc):
match rc:
Expand Down Expand Up @@ -310,16 +318,21 @@ def __prepare_payload(self, command: dict):
payload.update(command)
return payload

def __send(self, topic: str, message: str):
try:
info = self.client.publish(topic, message, 1)
_LOGGER.debug("Sending " + message + " :" + str(info) + "(" + str(info.is_published()) + ")")
except RuntimeError as error:
_LOGGER.error(error)

def send_get_message(self, command: dict):
payload = self.__prepare_payload(command)
info = self.client.publish(self._get_topic, json.dumps(payload), 1)
_LOGGER.debug("Sending " + json.dumps(payload) + " :" + str(info) + "(" + str(info.is_published()) + ")")
self.__send(self._get_topic, json.dumps(payload))

def send_set_message(self, mqtt_state: dict[str, Any], command: dict):
self.data.update_to_target_state(mqtt_state)
payload = self.__prepare_payload(command)
info = self.client.publish(self._set_topic, json.dumps(payload), 1)
_LOGGER.debug("Sending " + json.dumps(payload) + " :" + str(info) + "(" + str(info.is_published()) + ")")
self.__send(self._set_topic, json.dumps(payload))

def stop(self):
self.client.loop_stop()
Expand Down
13 changes: 11 additions & 2 deletions custom_components/ecoflow_cloud/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,12 @@ def __check_status(self, now: datetime):
# online, updated and outdated - reconnect
self._attrs[ATTR_STATUS_RECONNECTS] = self._attrs[ATTR_STATUS_RECONNECTS] + 1
self._client.reconnect()
self.async_write_ha_state()

elif not self._client.is_connected(): # validate connection even for offline device
self._attrs[ATTR_STATUS_RECONNECTS] = self._attrs[ATTR_STATUS_RECONNECTS] + 1
self._client.reconnect()
self.async_write_ha_state()

def __params_update(self, data: dict[str, Any]):
self._attrs[ATTR_STATUS_DATA_LAST_UPDATE] = self._client.data.params_time()
Expand Down Expand Up @@ -324,8 +330,11 @@ async def async_added_to_hass(self):
await super().async_added_to_hass()

def _update_status(self, update_delta_sec):
self._attrs[ATTR_STATUS_UPDATES] = self._attrs[ATTR_STATUS_UPDATES] + 1
self.send_get_message({"version": "1.1", "moduleType": 0, "operateType": "latestQuotas", "params": {}})
if self._client.is_connected():
self._attrs[ATTR_STATUS_UPDATES] = self._attrs[ATTR_STATUS_UPDATES] + 1
self.send_get_message({"version": "1.1", "moduleType": 0, "operateType": "latestQuotas", "params": {}})
else:
super()._update_status(update_delta_sec)

def __get_reply_update(self, data: list[dict[str, Any]]):
d = data[0]
Expand Down

0 comments on commit adc72c6

Please sign in to comment.