From 45daf5cc1a565e406d654bdf146dc8626e1fdca7 Mon Sep 17 00:00:00 2001 From: maslyankov Date: Mon, 20 Jan 2025 22:15:00 +0200 Subject: [PATCH] Refactor `pack_value` function and enhance bitmask handling - Updated `pack_value` to return `RegType` instead of a tuple, improving type clarity. - Removed deprecated `patch_bitmask` function and reintroduced it with improved implementation. - Simplified `NumberRWSensor` to utilize `pack_value` for dynamic register packing based on address length. - Enhanced code readability and maintainability by consolidating bitmask operations. --- src/sunsynk/helpers.py | 14 +++++++------- src/sunsynk/rwsensors.py | 7 +------ 2 files changed, 8 insertions(+), 13 deletions(-) diff --git a/src/sunsynk/helpers.py b/src/sunsynk/helpers.py index 7d1c4ec1..7cdfb21f 100644 --- a/src/sunsynk/helpers.py +++ b/src/sunsynk/helpers.py @@ -13,7 +13,7 @@ NumType = float | int -def pack_value(value: int, bits: int = 16, signed: bool = True) -> int | tuple[int, int]: +def pack_value(value: int, bits: int = 16, signed: bool = True) -> RegType: """Pack a value into register format. Args: @@ -27,7 +27,7 @@ def pack_value(value: int, bits: int = 16, signed: bool = True) -> int | tuple[i """ if bits == 16: fmt = 'h' if signed else 'H' - return struct.unpack('H', struct.pack(fmt, value))[0] + return struct.unpack('H', struct.pack(fmt, value)) if bits == 32: fmt = 'i' if signed else 'I' return struct.unpack('2H', struct.pack(fmt, value)) @@ -102,6 +102,11 @@ def hex_str(regs: RegType, address: RegType | None = None) -> str: return f"{{{' '.join(res)}}}" +def patch_bitmask(value: int, patch: int, bitmask: int) -> int: + """Combine bitmask values.""" + return (patch & bitmask) + (value & (0xFFFF - bitmask)) + + class SSTime: """Deals with inverter time format conversion complexities.""" @@ -151,8 +156,3 @@ def str_value(self, value: str) -> None: self.minutes = int(hours) * 60 + int(minutes) except ValueError: _LOGGER.warning("Invalid time string: %s (expected hh:mm)", value) - - -def patch_bitmask(value: int, patch: int, bitmask: int) -> int: - """Combine bitmask values.""" - return (patch & bitmask) + (value & (0xFFFF - bitmask)) diff --git a/src/sunsynk/rwsensors.py b/src/sunsynk/rwsensors.py index 3acfca70..32883799 100644 --- a/src/sunsynk/rwsensors.py +++ b/src/sunsynk/rwsensors.py @@ -82,12 +82,7 @@ def value_to_reg(self, value: ValType, resolve: ResolveType) -> RegType: maxv = resolve_num(resolve, self.max, 100) val = int(max(minv, min(maxv, fval)) / abs(self.factor)) - if len(self.address) == 1: - return self.reg(pack_value(val, bits=16, signed=self.factor < 0)) - if len(self.address) == 2: - low, high = pack_value(val, bits=32, signed=self.factor < 0) # type: ignore - return self.reg(low, high) - raise NotImplementedError(f"Address length not supported: {self.address}") + return self.reg(*pack_value(val, bits=len(self.addrees)*16, signed=self.factor < 0)) @attrs.define(slots=True, eq=False)