Skip to content

Commit

Permalink
fix: Disconnect when register writing fails
Browse files Browse the repository at this point in the history
- Only when auto_reconnect is disabled
  • Loading branch information
davidrapan committed Jul 17, 2024
1 parent c0016bb commit 1672353
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 17 deletions.
15 changes: 10 additions & 5 deletions custom_components/solarman/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@
_LOGGER = logging.getLogger(__name__)

class InverterApi(PySolarmanV5Async):
def __init__(self, address, serial, port, mb_slave_id):
super().__init__(address, serial, port = port, mb_slave_id = mb_slave_id, logger = _LOGGER, auto_reconnect = True, socket_timeout = TIMINGS_SOCKET_TIMEOUT)
def __init__(self, address, serial, port, mb_slave_id, auto_reconnect):
super().__init__(address, serial, port = port, mb_slave_id = mb_slave_id, logger = _LOGGER, auto_reconnect = auto_reconnect, socket_timeout = TIMINGS_SOCKET_TIMEOUT)
self.status_lastUpdate = "N/A"
self.status = -1

Expand Down Expand Up @@ -128,11 +128,12 @@ async def async_read(self, params, code, start, end) -> None:

class Inverter(InverterApi):
def __init__(self, address, serial, port, mb_slave_id, name, mac, lookup_path, lookup_file):
super().__init__(address, serial, port, mb_slave_id)
super().__init__(address, serial, port, mb_slave_id, AUTO_RECONNECT)
self.name = name
self.mac = mac
self.lookup_path = lookup_path
self.lookup_file = lookup_file if lookup_file and not lookup_file == "parameters.yaml" else "deye_hybrid.yaml"
self.auto_reconnect = AUTO_RECONNECT

#execute_async(self.load())

Expand Down Expand Up @@ -197,6 +198,8 @@ async def async_get(self, runtime = 0):
_LOGGER.warning(f"Querying ({start} - {end}) failed. #{runtime} [{format_exception(e)}]")

await asyncio.sleep(TIMINGS_QUERY_EXCEPT_SLEEP)
#if (n := ACTION_RETRY_ATTEMPTS - attempts_left) >= 1:
# await asyncio.sleep(n)

_LOGGER.debug(f"Querying {'succeeded.' if result == 1 else f'attempts left: {attempts_left}{'' if attempts_left > 0 else ', aborting.'}'}")

Expand Down Expand Up @@ -226,7 +229,8 @@ async def service_write_holding_register(self, register, value) -> bool:
_LOGGER.debug(f"service_write_holding_register: {register}, response: {response}")
except Exception as e:
_LOGGER.warning(f"service_write_holding_register: {register}, value: {value} failed. [{format_exception(e)}]")
#await self.async_disconnect()
if not self.auto_reconnect:
await self.async_disconnect()
raise
return True

Expand All @@ -238,6 +242,7 @@ async def service_write_multiple_holding_registers(self, register, values) -> bo
_LOGGER.debug(f"service_write_multiple_holding_register: {register}, response: {response}")
except Exception as e:
_LOGGER.warning(f"service_write_multiple_holding_registers: {register}, values: {values} failed. [{format_exception(e)}]")
#await self.async_disconnect()
if not self.auto_reconnect:
await self.async_disconnect()
raise
return True
2 changes: 2 additions & 0 deletions custom_components/solarman/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@
DEFAULT_BATTERY_NOMINAL_VOLTAGE = 48
DEFAULT_BATTERY_LIFE_CYCLE_RATING = 6000

AUTO_RECONNECT = True

ACTION_RETRY_ATTEMPTS = 5

TIMINGS_INTERVAL = 5
Expand Down
2 changes: 1 addition & 1 deletion custom_components/solarman/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def _create_sensor(coordinator, sensor, battery_nominal_voltage, battery_life_cy
elif sensor["name"] in ("Battery SOH", "Battery State", "Today Battery Life Cycles", "Total Battery Life Cycles"):
entity = SolarmanBatterySensor(coordinator, sensor, battery_nominal_voltage, battery_life_cycle_rating)
#elif "switch" in sensor and sensor["switch"]:
# entity = SolarmanSwitchSensor(coordinator, sensor, battery_life_cycle_rating)
# entity = SolarmanSwitchEntity(coordinator, sensor, battery_life_cycle_rating)
else:
entity = SolarmanSensor(coordinator, sensor, battery_life_cycle_rating)

Expand Down
19 changes: 8 additions & 11 deletions custom_components/solarman/switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

from homeassistant.components.template.sensor import SensorTemplate
from homeassistant.components.template.sensor import TriggerSensorEntity
from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription
from homeassistant.components.switch import SwitchEntity, SwitchDeviceClass, SwitchEntityDescription
from homeassistant.helpers.template import Template

from homeassistant.core import HomeAssistant, callback
Expand All @@ -31,7 +31,7 @@

def _create_sensor(coordinator, sensor, battery_nominal_voltage, battery_life_cycle_rating):
try:
entity = SolarmanSwitchSensor(coordinator, sensor, battery_life_cycle_rating)
entity = SolarmanSwitchEntity(coordinator, sensor, battery_life_cycle_rating)

entity.update()

Expand Down Expand Up @@ -62,23 +62,20 @@ async def async_unload_entry(hass: HomeAssistant, config: ConfigEntry) -> bool:
_LOGGER.debug(f"async_unload_entry: {config.options}")
return True

class SolarmanSwitchSensor(SolarmanSensor, SwitchEntity):
class SolarmanSwitchEntity(SolarmanSensor, SwitchEntity):
def __init__(self, coordinator, sensor, battery_life_cycle_rating):
SolarmanSensor.__init__(self, coordinator, sensor, battery_life_cycle_rating)

# Set the category of the sensor.
self._attr_entity_category = (EntityCategory.CONFIG)

self._attr_device_class = "switch"
# Set The Device Class of the entity.
self._attr_device_class = SwitchDeviceClass.SWITCH
# Set The Category of the entity.
self._attr_entity_category = EntityCategory.CONFIG

registers = sensor["registers"]
registers_length = len(registers)

if registers_length > 0:
self.register = sensor["registers"][0]

if registers_length > 1:
_LOGGER.warning(f"SolarmanSwitchSensor.__init__: Contains more than 1 register!")
_LOGGER.warning(f"SolarmanSwitchEntity.__init__: Contains more than 1 register!")

@property
def is_on(self) -> bool | None:
Expand Down

0 comments on commit 1672353

Please sign in to comment.