1
0
mirror of https://github.com/pommi/python-itho-wpu.git synced 2024-12-21 18:43:27 +01:00

Compare commits

...

5 Commits

Author SHA1 Message Date
381dd4c6ec feat(itho-wpu): setsetting support
With action "setsetting" settings of an Itho WPU can be modified.
2023-07-19 16:31:49 +02:00
1ffd5a72d7 fix(itho_i2c): make loglevel in itho_i2c module adjustable 2023-07-19 15:35:04 +02:00
7a1140e26c feat(itho-wpu): getsettings support
A loop around getsetting based on the settings available in the
database to retrieve all settings from the WPU.

Example usage:
> ./itho-wpu.py --action getsettings
> 0. Niet Gebruikt: 0 (min: 0, max: 65535, step: 1)
> 1. Hardware Configuratie: 70 (min: 0, max: 65535, step: 1)
> 2. Jaar Inbedrijfstelling: 2010 (min: 2004, max: 2099, step: 1)
2023-07-19 15:35:04 +02:00
d28acae756 feat(itho-wpu): getsetting support
Action "getsetting" retrieves the value of a setting byi the provided id.

Example usage:
> ./itho-wpu.py --action getsetting --settingid 1
> 1. Hardware Configuratie: 70 (min: 0, max: 65535, step: 1)
> ./itho-wpu.py --action getsetting --settingid 2
> 2. Jaar Inbedrijfstelling: 2010 (min: 2004, max: 2099, step: 1)
2023-07-19 15:35:04 +02:00
620cdaf880 refactor: put datatype formatting in a separate function 2023-07-19 14:56:41 +02:00
3 changed files with 312 additions and 32 deletions

View File

@ -99,6 +99,39 @@ See the [pislave](https://github.com/ootjersb/pislave#wiring) project
... ...
``` ```
* Retrieve a single setting from the WPU
```
# ./itho-wpu.py --action getsetting --settingid 1
1. Hardware Configuratie: 70 (min: 0, max: 65535, step: 1)
```
* Retrieve all settings from the WPU
```
# ./itho-wpu.py --action getsettings
0. Niet Gebruikt: 0 (min: 0, max: 65535, step: 1)
1. Hardware Configuratie: 70 (min: 0, max: 65535, step: 1)
2. Jaar Inbedrijfstelling: 2010 (min: 2004, max: 2099, step: 1)
3. Datum Van Inbedrijfstelling: 101 (min: 0, max: 3112, step: 1)
4. Max Handbedieningstijd (min): 0 (min: 0, max: 600, step: 1)
5. Vorsttemp (°C): 2.0 (min: -10.0, max: 10.0, step: 0.1)
6. Offset Voor Vorst Temp (K): 2.0 (min: 0.0, max: 10.0, step: 0.1)
7. Differentie Van Vorst Om Elektrisch Element Te Starten (K): 1.5 (min: 0.0, max: 10.0, step: 0.1)
8. Fout Reset Tijd (min): 120 (min: 1, max: 1440, step: 1)
9. Loginterval Tijd (sec): 5 (min: 1, max: 300, step: 1)
...
```
* Change a setting of the WPU
```
# ./itho-wpu.py --action setsetting --settingid 139 --value 48
Current setting:
139. Blokkade Tijd Van Verwarmen Naar Koelen (uur): 24 (min: 0, max: 168, step: 1)
Setting `139` will be changed to `48`? [y/N] y
Updating setting 139 to `48`
Are you really sure? (Type uppercase yes): YES
139. Blokkade Tijd Van Verwarmen Naar Koelen (uur): 48 (min: 0, max: 168, step: 1)
```
# Exporting measurements # Exporting measurements
## InfluxDB ## InfluxDB

View File

@ -23,6 +23,8 @@ actions = {
"getserial": [0x90, 0xE1], "getserial": [0x90, 0xE1],
"getdatatype": [0xA4, 0x00], "getdatatype": [0xA4, 0x00],
"getdatalog": [0xA4, 0x01], "getdatalog": [0xA4, 0x01],
"getsetting": [0xA4, 0x10],
"setsetting": [0xA4, 0x10],
} }
@ -33,9 +35,20 @@ def parse_args():
"--action", "--action",
nargs="?", nargs="?",
required=True, required=True,
choices=actions.keys(), choices=list(actions.keys()) + ["getsettings"],
help="Execute an action", help="Execute an action",
) )
parser.add_argument(
"--settingid",
nargs="?",
type=int,
help="Setting identifier",
)
parser.add_argument(
"--value",
nargs="?",
help="Setting value",
)
parser.add_argument( parser.add_argument(
"--loglevel", "--loglevel",
nargs="?", nargs="?",
@ -75,7 +88,7 @@ class IthoWPU:
self.datatype = self.get("getdatatype") self.datatype = self.get("getdatatype")
self.heatpump_db = db.sqlite("heatpump.sqlite") self.heatpump_db = db.sqlite("heatpump.sqlite")
def get(self, action): def get(self, action, identifier=None, value=None):
if not self.no_cache: if not self.no_cache:
response = self.cache.get(action.replace("get", "")) response = self.cache.get(action.replace("get", ""))
if response is not None: if response is not None:
@ -93,7 +106,7 @@ class IthoWPU:
if not self.slave_only: if not self.slave_only:
master = I2CMaster(address=0x41, bus=1, queue=self._q) master = I2CMaster(address=0x41, bus=1, queue=self._q)
if action: if action:
response = master.execute_action(action) response = master.execute_action(action, identifier, value)
logger.debug(f"Response: {response}") logger.debug(f"Response: {response}")
master.close() master.close()
@ -150,6 +163,36 @@ class IthoWPU:
return datalog return datalog
return datalog return datalog
def get_settings(self):
listversion = self.get_listversion_from_nodeid()
parameterlist_version = self.heatpump_db.execute(
f"SELECT parameterlist FROM versiebeheer WHERE version = {listversion}"
)[0]["parameterlist"]
if parameterlist_version is None or not type(parameterlist_version) == int:
logger.error(f"Parameterlist not found in database for version {listversion}")
return None
settings = self.heatpump_db.execute(
"SELECT id, name, min, max, def, title, description, unit "
+ f"FROM parameterlijst_v{parameterlist_version}"
)
return settings
def get_setting_by_id(self, settingid):
listversion = self.get_listversion_from_nodeid()
parameterlist_version = self.heatpump_db.execute(
f"SELECT parameterlist FROM versiebeheer WHERE version = {listversion}"
)[0]["parameterlist"]
if parameterlist_version is None or not type(parameterlist_version) == int:
logger.error(f"Parameterlist not found in database for version {listversion}")
return None
setting_details = self.heatpump_db.execute(
"SELECT name, min, max, def, title, description, unit "
+ f"FROM parameterlijst_v{parameterlist_version} WHERE id = {settingid}"
)
if len(setting_details) != 1:
return None
return setting_details[0]
class IthoWPUCache: class IthoWPUCache:
def __init__(self): def __init__(self):
@ -219,6 +262,8 @@ def process_response(action, response, args, wpu):
from itho_export import export_to_influxdb from itho_export import export_to_influxdb
export_to_influxdb(action, measurements) export_to_influxdb(action, measurements)
elif action == "getsetting":
process_setting(response, wpu)
elif action == "getnodeid": elif action == "getnodeid":
process_nodeid(response) process_nodeid(response)
elif action == "getserial": elif action == "getserial":
@ -259,47 +304,213 @@ def process_datalog(response, wpu):
measurements = {} measurements = {}
for d in datalog: for d in datalog:
if d.type == 0x0 or d.type == 0xC: if d.type == 0x0 or d.type == 0xC:
m = message[d.index : d.index + 1] # noqa: E203 length = 1
num = int(m[0], 0) elif d.type == 0x10 or d.type == 0x12 or d.type == 0x90 or d.type == 0x92:
elif d.type == 0x10: length = 2
m = message[d.index : d.index + 2] # noqa: E203
num = (int(m[0], 0) << 8) + int(m[1], 0)
elif d.type == 0x12:
m = message[d.index : d.index + 2] # noqa: E203
num = round((int(m[0], 0) << 8) + int(m[1], 0) / 100, 2)
elif d.type == 0x90:
m = message[d.index : d.index + 2] # noqa: E203
num = (int(m[0], 0) << 8) + int(m[1], 0)
if num >= 32768:
num -= 65536
elif d.type == 0x92:
m = message[d.index : d.index + 2] # noqa: E203
num = (int(m[0], 0) << 8) + int(m[1], 0)
if num >= 32768:
num -= 65536
num = round(num / 100, 2)
elif d.type == 0x20: elif d.type == 0x20:
m = message[d.index : d.index + 4] # noqa: E203 length = 4
num = (int(m[0], 0) << 24) + (int(m[1], 0) << 16) + (int(m[2], 0) << 8) + int(m[3], 0)
else: else:
logger.error(f"Unknown message type for datalog {d.name}: {d.type}") logger.error(f"Unknown message type for datalog {d.label}: {d.type}")
num = format_datatype(d.label, message[d.index : d.index + length], d.type) # noqa: E203
logger.info(f"{d.description}: {num}") logger.info(f"{d.description}: {num}")
measurements[d.label] = num measurements[d.label] = num
return measurements return measurements
if __name__ == "__main__": def parse_setting(response, wpu):
message = response[5:]
settingid = int(message[17], 0)
setting = wpu.get_setting_by_id(settingid)
if setting is None:
logger.error(f"Setting '{settingid}' is invalid")
return
datatype = message[16]
value = format_datatype(setting["name"], message[0:4], datatype)
minimum = format_datatype(setting["name"], message[4:8], datatype)
maximum = format_datatype(setting["name"], message[8:12], datatype)
step = format_datatype(setting["name"], message[12:16], datatype)
return value, minimum, maximum, step
def process_setting(response, wpu):
message = response[5:]
settingid = int(message[17], 0)
setting = wpu.get_setting_by_id(settingid)
if setting is None:
logger.error(f"Setting '{settingid}' is invalid")
return
value, minimum, maximum, step = parse_setting(response, wpu)
logger.info(
"{}. {}{}: {} (min: {}, max: {}, step: {})".format(
settingid,
setting["title"].title(),
f' ({setting["unit"]})' if setting["unit"] is not None else "",
value,
minimum,
maximum,
step,
)
)
def process_settings(wpu, args):
settings = wpu.get_settings()
for setting in settings:
response = wpu.get("getsetting", int(setting["id"]))
if response is not None:
process_response("getsetting", response, args, wpu)
def process_setsetting(wpu, args):
logger.info("Current setting:")
response = wpu.get("getsetting", int(args.settingid))
if response is None:
return
process_response("getsetting", response, args, wpu)
message = response[5:]
datatype = message[16]
if args.value is None:
value = input("Provide a new value: ")
else:
value = args.value
# TODO: add support for negative values
if float(value) < 0:
logger.error("Negative values are not supported yet.")
return
logger.debug(f"New setting datatype: {datatype}")
logger.debug(f"New setting (input): {value}")
normalized_value = int(value.replace(".", ""))
logger.debug(f"New setting (normalized): {normalized_value}")
hex_list_value = [hex(v) for v in list(normalized_value.to_bytes(4, byteorder="big"))]
logger.debug(f"New setting (hex): {hex_list_value}")
parsed_value = format_datatype(args.settingid, hex_list_value, datatype)
logger.debug(f"New setting (parsed): {parsed_value}")
_, minimum, maximum, _ = parse_setting(response, wpu)
if parsed_value < minimum or parsed_value > maximum:
logger.error(f"New value `{parsed_value}` is not between `{minimum}` and `{maximum}`")
return
sure = input(f"Setting `{args.settingid}` will be changed to `{parsed_value}`? [y/N] ")
if sure in ["y", "Y"]:
logger.info(f"Updating setting {args.settingid} to `{parsed_value}`")
else:
logger.error("Aborted")
return
response = wpu.get("setsetting", args.settingid, normalized_value)
if response is None:
return
process_response("getsetting", response, args, wpu)
def format_datatype(name, m, dt):
"""
Transform a list of bytes to a readable number based on the datatype.
:param str name: Name/label of the data
:param list[str] m: List of bytes in hexadecimal string format
:param dt: Datatype
:type dt: str or int
"""
num = None
if type(dt) is str:
dt = int(dt, 0)
if dt == 0x0 or dt == 0xC:
num = int(m[-1], 0)
elif dt == 0x1:
num = round(int(m[-1], 0) / 10, 1)
elif dt == 0x2:
num = round(int(m[-1], 0) / 100, 2)
elif dt == 0x10:
num = (int(m[-2], 0) << 8) + int(m[-1], 0)
elif dt == 0x12:
num = round((int(m[-2], 0) << 8) + int(m[-1], 0) / 100, 2)
elif dt == 0x13:
num = round((int(m[-2], 0) << 8) + int(m[-1], 0) / 1000, 3)
elif dt == 0x14:
num = round((int(m[-2], 0) << 8) + int(m[-1], 0) / 10000, 4)
elif dt == 0x80:
num = int(m[-1], 0)
if num >= 128:
num -= 256
elif dt == 0x81:
num = int(m[-1], 0)
if num >= 128:
num -= 256
num = round(num / 10, 1)
elif dt == 0x82:
num = int(m[-1], 0)
if num >= 128:
num -= 256
num = round(num / 100, 2)
elif dt == 0x8F:
num = int(m[-1], 0)
if num >= 128:
num -= 256
num = round(num / 1000, 3)
elif dt == 0x90:
num = (int(m[-2], 0) << 8) + int(m[-1], 0)
if num >= 32768:
num -= 65536
elif dt == 0x91:
num = (int(m[-2], 0) << 8) + int(m[-1], 0)
if num >= 32768:
num -= 65536
num = round(num / 10, 2)
elif dt == 0x92:
num = (int(m[-2], 0) << 8) + int(m[-1], 0)
if num >= 32768:
num -= 65536
num = round(num / 100, 2)
elif dt == 0x20:
num = (int(m[-4], 0) << 24) + (int(m[-3], 0) << 16) + (int(m[-2], 0) << 8) + int(m[-1], 0)
else:
logger.error(f"Unknown datatype for '{name}': 0x{dt:X}")
return num
def main():
args = parse_args() args = parse_args()
if args.loglevel: if args.loglevel:
logger.setLevel(args.loglevel.upper()) logger.setLevel(args.loglevel.upper())
logging.getLogger("itho_i2c").setLevel(args.loglevel.upper())
if args.timestamp: if args.timestamp:
stdout_log_handler.setFormatter( stdout_log_handler.setFormatter(
logging.Formatter("%(asctime)-15s %(levelname)s: %(message)s") logging.Formatter("%(asctime)-15s %(levelname)s: %(message)s")
) )
if args.action in ["getsetting", "setsetting"] and args.settingid is None:
logger.error("`--settingid` is required with `--action getsetting`")
return
wpu = IthoWPU(args.master_only, args.slave_only, args.slave_timeout, args.no_cache) wpu = IthoWPU(args.master_only, args.slave_only, args.slave_timeout, args.no_cache)
response = wpu.get(args.action)
if args.action == "getsettings":
process_settings(wpu, args)
return
if args.action == "setsetting":
process_setsetting(wpu, args)
return
response = wpu.get(args.action, args.settingid)
if response is not None: if response is not None:
process_response(args.action, response, args, wpu) process_response(args.action, response, args, wpu)
if __name__ == "__main__":
main()

View File

@ -4,14 +4,21 @@ import logging
import pigpio import pigpio
import struct import struct
import time import time
import sys
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
stdout_log_handler = logging.StreamHandler(sys.stdout)
stdout_log_handler.setFormatter(logging.Formatter("%(message)s"))
logger.addHandler(stdout_log_handler)
actions = { actions = {
"getnodeid": [0x90, 0xE0], "getnodeid": [0x90, 0xE0],
"getserial": [0x90, 0xE1], "getserial": [0x90, 0xE1],
"getdatatype": [0xA4, 0x00], "getdatatype": [0xA4, 0x00],
"getdatalog": [0xA4, 0x01], "getdatalog": [0xA4, 0x01],
"getsetting": [0xA4, 0x10],
"setsetting": [0xA4, 0x10],
} }
@ -45,7 +52,31 @@ class I2CMaster:
self.i = I2CRaw(address=address, bus=bus) self.i = I2CRaw(address=address, bus=bus)
self.queue = queue self.queue = queue
def compose_request(self, action): def compose_request(self, action, identifier, value):
if action == "getsetting":
request = (
[0x80]
+ actions[action]
+ [0x04, 0x13] # read, length
+ [0x00, 0x00, 0x00, 0x00] # current
+ [0x00, 0x00, 0x00, 0x00] # min
+ [0x00, 0x00, 0x00, 0x00] # max
+ [0x00, 0x00, 0x00, 0x00] # step
+ [0x00, identifier, 0x00]
)
elif action == "setsetting":
byte_list_value = list(value.to_bytes(4, byteorder="big"))
request = (
[0x80]
+ actions[action]
+ [0x06, 0x13] # write, length
+ byte_list_value # new
+ [0x00, 0x00, 0x00, 0x00] # min
+ [0x00, 0x00, 0x00, 0x00] # max
+ [0x00, 0x00, 0x00, 0x00] # step
+ [0x00, identifier, 0x00]
)
else:
# 0x80 = source, 0x04 = msg_type, 0x00 = length # 0x80 = source, 0x04 = msg_type, 0x00 = length
request = [0x80] + actions[action] + [0x04, 0x00] request = [0x80] + actions[action] + [0x04, 0x00]
request.append(self.calculate_checksum(request)) request.append(self.calculate_checksum(request))
@ -60,11 +91,16 @@ class I2CMaster:
checksum = 0 checksum = 0
return checksum return checksum
def execute_action(self, action): def execute_action(self, action, identifier, value):
request = self.compose_request(action) request = self.compose_request(action, identifier, value)
request_in_hex = [hex(c) for c in request] request_in_hex = [hex(c) for c in request]
logger.debug(f"Request: {request_in_hex}") logger.debug(f"Request: {request_in_hex}")
result = None result = None
if action == "setsetting":
sure = input("Are you really sure? (Type uppercase yes): ")
if sure != "YES":
logger.error("Aborted")
return
for i in range(0, 20): for i in range(0, 20):
logger.debug(f"Executing action: {action}") logger.debug(f"Executing action: {action}")
self.i.write_i2c_block_data(request) self.i.write_i2c_block_data(request)