Skip to content

Commit

Permalink
Enhance error handling in RWSensor classes
Browse files Browse the repository at this point in the history
- Added validation to `NumberRWSensor` and `TimeRWSensor` to raise a `NotImplementedError` if the sensor address is not set, preventing invalid operations.
- Implemented a post-initialization check in `SystemTimeRWSensor` to ensure exactly 3 registers are provided, raising a `ValueError` if the condition is not met.
  • Loading branch information
maslyankov committed Jan 20, 2025
1 parent d0a9135 commit ad77e81
Showing 1 changed file with 10 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/sunsynk/rwsensors.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,8 @@ def dependencies(self) -> list[Sensor]:

def value_to_reg(self, value: ValType, resolve: ResolveType) -> RegType:
"""Get the reg value from a display value."""
if not self.address:
raise NotImplementedError("Cannot write to a sensor with no address")
fval = float(value) # type:ignore
minv = resolve_num(resolve, self.min, 0)
maxv = resolve_num(resolve, self.max, 100)
Expand Down Expand Up @@ -180,6 +182,12 @@ def value_to_reg(self, value: ValType, resolve: ResolveType) -> RegType:
class SystemTimeRWSensor(RWSensor):
"""Read & write time sensor."""

def __attrs_post_init__(self) -> None:
"""Run post init."""
super().__attrs_post_init__()
if len(self.address) != 3:
raise ValueError("SystemTimeRWSensor requires exactly 3 registers")

def value_to_reg(self, value: ValType, resolve: ResolveType) -> RegType:
"""Get the reg value from a display value."""
# pylint: disable=invalid-name
Expand Down Expand Up @@ -245,6 +253,8 @@ def reg_to_value(self, regs: RegType) -> ValType:

def value_to_reg(self, value: ValType, resolve: ResolveType) -> RegType:
"""Get the reg value from a display value."""
if not self.address:
raise NotImplementedError("Cannot write to a sensor with no address")
return self.reg(SSTime(string=str(value)).reg_value)

@staticmethod
Expand Down

0 comments on commit ad77e81

Please # to comment.