From ad77e819a8414d5898185cf5d8f4e2734c5781db Mon Sep 17 00:00:00 2001 From: maslyankov Date: Mon, 20 Jan 2025 23:53:39 +0200 Subject: [PATCH] Enhance error handling in RWSensor classes - 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. --- src/sunsynk/rwsensors.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/sunsynk/rwsensors.py b/src/sunsynk/rwsensors.py index b89851d7..e5f405d6 100644 --- a/src/sunsynk/rwsensors.py +++ b/src/sunsynk/rwsensors.py @@ -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) @@ -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 @@ -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