From 3aa6b13615eaf46e2a5d11788a92337e08b1ff6f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Odd=20Str=C3=A5b=C3=B8?= <oddstr13@openshell.no>
Date: Sun, 10 Dec 2023 23:52:38 +0100
Subject: [PATCH] Fix writing of multiple words to charge controller

---
 srnemqtt/protocol.py | 23 ++++++++++++++++++++---
 1 file changed, 20 insertions(+), 3 deletions(-)

diff --git a/srnemqtt/protocol.py b/srnemqtt/protocol.py
index 4229a4a..ff52a13 100644
--- a/srnemqtt/protocol.py
+++ b/srnemqtt/protocol.py
@@ -153,8 +153,8 @@ def readMemory(fh: BaseInterface, address: int, words: int = 1) -> Optional[byte
 
 
 def writeMemory(fh: BaseInterface, address: int, data: bytes):
-    if len(data) % 2:
-        raise ValueError(f"Data must consist of two-byte words, got {len(data)} bytes")
+    if len(data) != 2:
+        raise ValueError(f"Data must consist of a two-byte word, got {len(data)} bytes")
 
     header = construct_write_request(address)
     write(fh, header + data)
@@ -166,7 +166,11 @@ def writeMemory(fh: BaseInterface, address: int, data: bytes):
     header = fh.read(3)
     if header and len(header) == 3:
         operation, size, address = header
-        rdata = fh.read(size * 2)
+        log(header)
+        # size field is zero when writing device name for whatever reason
+        # write command seems to only accept a single word, so this is fine;
+        # we just hardcode the number of bytes read to two here.
+        rdata = fh.read(2)
         _crc = fh.read(2)
         if rdata and _crc:
             try:
@@ -183,6 +187,19 @@ def writeMemory(fh: BaseInterface, address: int, data: bytes):
     return None
 
 
+def writeMemoryMultiple(fh: BaseInterface, address: int, data: bytes):
+    if len(data) % 2:
+        raise ValueError(f"Data must consist of two-byte words, got {len(data)} bytes")
+    res = bytearray()
+    for i in range(len(data) // 2):
+        d = data[i * 2 : (i + 1) * 2]
+        log(address + i, d)
+        r = writeMemory(fh, address + i, d)
+        if r:
+            res.extend(r)
+    return res
+
+
 def try_read_parse(
     dev: BaseInterface,
     address: int,