Merge branch 'main' into mqtt_lwt
This commit is contained in:
@@ -13,4 +13,4 @@ RUN apt-get update && \
|
||||
COPY hc2mqtt hc-login HCDevice.py HCSocket.py HCxml2json.py ./
|
||||
|
||||
ENTRYPOINT ["python3"]
|
||||
CMD ["hc2mqtt", "--config", "/config/config.ini"]
|
||||
CMD ["hc2mqtt", "--config", "./config/config.ini"]
|
||||
|
||||
82
HCDevice.py
82
HCDevice.py
@@ -92,21 +92,55 @@ class HCDevice:
|
||||
|
||||
return result
|
||||
|
||||
# Based on PR submitted https://github.com/Skons/hcpy/pull/1
|
||||
def test_program_data(self, data):
|
||||
if "program" not in data:
|
||||
raise TypeError("Message data invalid, no program specified.")
|
||||
|
||||
if isinstance(data["program"], int) is False:
|
||||
raise TypeError("Message data invalid, UID in 'program' must be an integer.")
|
||||
|
||||
# devices.json stores UID as string
|
||||
uid = str(data["program"])
|
||||
if uid not in self.features:
|
||||
raise ValueError(
|
||||
f"Unable to configure appliance. Program UID {uid} is not valid"
|
||||
" for this device."
|
||||
)
|
||||
|
||||
feature = self.features[uid]
|
||||
# Diswasher is Dishcare.Dishwasher.Program.{name}
|
||||
# Hood is Cooking.Common.Program.{name}
|
||||
# May also be in the format BSH.Common.Program.Favorite.001
|
||||
if ".Program." not in feature["name"]:
|
||||
raise ValueError(
|
||||
f"Unable to configure appliance. Program UID {uid} is not a valid"
|
||||
f" program - {feature['name']}."
|
||||
)
|
||||
|
||||
if "options" in data:
|
||||
for option_uid in data["options"]:
|
||||
if str(option_uid) not in self.features:
|
||||
raise ValueError(
|
||||
f"Unable to configure appliance. Option UID {uid} is not"
|
||||
" valid for this device."
|
||||
)
|
||||
|
||||
# Test the feature of an appliance agains a data object
|
||||
def test_feature(self, data):
|
||||
if "uid" not in data:
|
||||
raise Exception("{self.name}. Unable to configure appliance. UID is required.")
|
||||
raise Exception("Unable to configure appliance. UID is required.")
|
||||
|
||||
if isinstance(data["uid"], int) is False:
|
||||
raise Exception("{self.name}. Unable to configure appliance. UID must be an integer.")
|
||||
raise Exception("Unable to configure appliance. UID must be an integer.")
|
||||
|
||||
if "value" not in data:
|
||||
raise Exception("{self.name}. Unable to configure appliance. Value is required.")
|
||||
raise Exception("Unable to configure appliance. Value is required.")
|
||||
|
||||
# Check if the uid is present for this appliance
|
||||
uid = str(data["uid"])
|
||||
if uid not in self.features:
|
||||
raise Exception(f"{self.name}. Unable to configure appliance. UID {uid} is not valid.")
|
||||
raise Exception(f"Unable to configure appliance. UID {uid} is not valid.")
|
||||
|
||||
feature = self.features[uid]
|
||||
|
||||
@@ -114,14 +148,14 @@ class HCDevice:
|
||||
print(now(), self.name, f"Processing feature {feature['name']} with uid {uid}")
|
||||
if "access" not in feature:
|
||||
raise Exception(
|
||||
f"{self.name}. Unable to configure appliance."
|
||||
"Unable to configure appliance. "
|
||||
f"Feature {feature['name']} with uid {uid} does not have access."
|
||||
)
|
||||
|
||||
access = feature["access"].lower()
|
||||
if access != "readwrite" and access != "writeonly":
|
||||
raise Exception(
|
||||
f"{self.name}. Unable to configure appliance."
|
||||
"Unable to configure appliance. "
|
||||
f"Feature {feature['name']} with uid {uid} has got access {feature['access']}."
|
||||
)
|
||||
|
||||
@@ -130,16 +164,16 @@ class HCDevice:
|
||||
if isinstance(data["value"], int) is False:
|
||||
raise Exception(
|
||||
f"Unable to configure appliance. The value {data['value']} must be an integer."
|
||||
f"Allowed values are {feature['values']}."
|
||||
f" Allowed values are {feature['values']}."
|
||||
)
|
||||
value = str(data["value"])
|
||||
# values are strings in the feature list,
|
||||
# but always seem to be an integer. An integer must be provided
|
||||
if value not in feature["values"]:
|
||||
raise Exception(
|
||||
f"{self.name}. Unable to configure appliance."
|
||||
f"Value {data['value']} is not a valid value."
|
||||
f"Allowed values are {feature['values']}."
|
||||
"Unable to configure appliance. "
|
||||
f"Value {data['value']} is not a valid value. "
|
||||
f"Allowed values are {feature['values']}. "
|
||||
)
|
||||
|
||||
if "min" in feature:
|
||||
@@ -151,13 +185,11 @@ class HCDevice:
|
||||
or data["value"] > max
|
||||
):
|
||||
raise Exception(
|
||||
f"{self.name}. Unable to configure appliance."
|
||||
f"Value {data['value']} is not a valid value."
|
||||
"Unable to configure appliance. "
|
||||
f"Value {data['value']} is not a valid value. "
|
||||
f"The value must be an integer in the range {min} and {max}."
|
||||
)
|
||||
|
||||
return True
|
||||
|
||||
def recv(self):
|
||||
try:
|
||||
buf = self.ws.recv()
|
||||
@@ -198,10 +230,13 @@ class HCDevice:
|
||||
|
||||
if data is not None:
|
||||
if action == "POST":
|
||||
if self.test_feature(data) is False:
|
||||
return
|
||||
msg["data"] = [data]
|
||||
else:
|
||||
if resource == "/ro/values":
|
||||
# Raises exceptions on failure
|
||||
self.test_feature(data)
|
||||
elif resource == "/ro/activeProgram":
|
||||
# Raises exception on failure
|
||||
self.test_program_data(data)
|
||||
|
||||
msg["data"] = [data]
|
||||
|
||||
try:
|
||||
@@ -294,17 +329,6 @@ class HCDevice:
|
||||
self.services[service["service"]] = {
|
||||
"version": service["version"],
|
||||
}
|
||||
# print(self.name, now(), "services", self.services)
|
||||
|
||||
# we should figure out which ones to query now
|
||||
# if "iz" in self.services:
|
||||
# self.get("/iz/info", version=self.services["iz"]["version"])
|
||||
# if "ni" in self.services:
|
||||
# self.get("/ni/info", version=self.services["ni"]["version"])
|
||||
# if "ei" in self.services:
|
||||
# self.get("/ei/deviceReady", version=self.services["ei"]["version"], action="NOTIFY")
|
||||
|
||||
# self.get("/if/info")
|
||||
|
||||
else:
|
||||
print(now(), self.name, "Unknown", msg)
|
||||
|
||||
26
README.md
26
README.md
@@ -20,14 +20,14 @@ To avoid running into issues later with your default python installs, it's recom
|
||||
```bash
|
||||
python3 -m venv venv
|
||||
source venv/bin/activate
|
||||
git clone https://github.com/osresearch/hcpy
|
||||
git clone https://github.com/hcpy2-0/hcpy
|
||||
cd hcpy
|
||||
pip3 install -r requirements.txt
|
||||
```
|
||||
|
||||
Install the Python dependencies; the `sslpsk` one is a little weird
|
||||
and we might need to revisit it later.
|
||||
|
||||
Alternatively an environment can be built with docker and/or docker-compose which has the necessary dependencies.
|
||||
|
||||
### For Mac Users
|
||||
Installing `sslpsk` needs some extra steps:
|
||||
@@ -65,10 +65,10 @@ your mDNS or DNS server resolves the names correctly.
|
||||
|
||||
## Home Connect to MQTT
|
||||
|
||||
Use the following config/config.ini example:
|
||||
Use the following ./config/config.ini example:
|
||||
|
||||
```
|
||||
devices_file = "/config/devices.json"
|
||||
devices_file = "./config/devices.json"
|
||||
mqtt_host = "localhost"
|
||||
mqtt_username = "mqtt"
|
||||
mqtt_password = "password"
|
||||
@@ -435,6 +435,24 @@ Synchronize with time server, `false` is disabled
|
||||
{"uid":547,"value":false}
|
||||
```
|
||||
|
||||
### Starting a Program
|
||||
|
||||
The MQTT client listens on /{prefix}/{devicename}/activeProgram for a JSON message to start a program. The JSON should be in the following format:
|
||||
|
||||
```json
|
||||
{"program":{uid},"options":[{"uid":{uid},"value":{value}}]}
|
||||
```
|
||||
|
||||
To start a dishwasher on eco mode (`Dishcare.Dishwasher.Program.Eco50`):
|
||||
```json
|
||||
{"program":8196}
|
||||
```
|
||||
|
||||
To start a dishwasher on eco mode in 10 miuntes (`BSH.Common.Option.StartInRelative`):
|
||||
```json
|
||||
{"program":8196,"options":[{"uid":558,"value":600}]}
|
||||
```
|
||||
|
||||
## FRIDA tools
|
||||
|
||||
Moved to [`README-frida.md`](README-frida.md)
|
||||
|
||||
@@ -4,4 +4,4 @@ services:
|
||||
build: .
|
||||
restart: on-failure
|
||||
volumes:
|
||||
- ./config:/config
|
||||
- ./config:/app/config
|
||||
|
||||
46
hc2mqtt
46
hc2mqtt
@@ -111,21 +111,40 @@ def client_connect(client, device, mqtt_topic):
|
||||
print(msg.topic)
|
||||
mqtt_state = msg.payload.decode()
|
||||
mqtt_topic = msg.topic.split("/")
|
||||
print(now(), f"received mqtt message {mqtt_state}")
|
||||
print(now(), f"{msg.topic} received mqtt message {mqtt_state}")
|
||||
|
||||
try:
|
||||
if len(mqtt_topic) >= 2:
|
||||
device_name = mqtt_topic[-2]
|
||||
topic = mqtt_topic[-1]
|
||||
else:
|
||||
raise Exception(f"Invalid mqtt topic {msg.topic}.")
|
||||
|
||||
try:
|
||||
msg = json.loads(mqtt_state)
|
||||
if "uid" in msg:
|
||||
dev[mqtt_topic[-2]].get("/ro/values", 1, "POST", msg)
|
||||
except ValueError as e:
|
||||
raise ValueError(f"Invalid JSON in message: {mqtt_state}.") from e
|
||||
|
||||
if topic == "set":
|
||||
resource = "/ro/values"
|
||||
elif topic == "activeProgram":
|
||||
resource = "/ro/activeProgram"
|
||||
else:
|
||||
raise Exception(f"Payload {msg} is not correctly formatted")
|
||||
raise Exception(f"Payload topic {topic} is unknown.")
|
||||
|
||||
dev[device_name].get(resource, 1, "POST", msg)
|
||||
except Exception as e:
|
||||
print("ERROR", e, file=sys.stderr)
|
||||
print(now(), device_name, "ERROR", e, file=sys.stderr)
|
||||
|
||||
host = device["host"]
|
||||
device_topics = topics
|
||||
client.on_message = on_message
|
||||
active_program = False
|
||||
|
||||
for value in device["features"]:
|
||||
# If the device has the ActiveProgram feature it allows programs to be started and
|
||||
# scheduled via /ro/activeProgram
|
||||
if "BSH.Common.Root.ActiveProgram" == device["features"][value]["name"]:
|
||||
active_program = True
|
||||
if (
|
||||
"access" in device["features"][value]
|
||||
and "read" in device["features"][value]["access"].lower()
|
||||
@@ -141,6 +160,16 @@ def client_connect(client, device, mqtt_topic):
|
||||
if not topic.isdigit(): # We only want the named topics
|
||||
state[device_topics[topic]] = None
|
||||
|
||||
mqtt_set_topic = mqtt_topic + "/set"
|
||||
print(now(), device["name"], f"set topic: {mqtt_set_topic}")
|
||||
client.subscribe(mqtt_set_topic)
|
||||
|
||||
if active_program:
|
||||
mqtt_active_program_topic = mqtt_topic + "/activeProgram"
|
||||
print(now(), device["name"], f"program topic: {mqtt_active_program_topic}")
|
||||
client.subscribe(mqtt_active_program_topic)
|
||||
|
||||
client.on_message = on_message
|
||||
|
||||
while True:
|
||||
try:
|
||||
@@ -164,11 +193,6 @@ def client_connect(client, device, mqtt_topic):
|
||||
if value is None:
|
||||
continue
|
||||
|
||||
# new_topic = topics[topic]
|
||||
# if new_topic == "remaining":
|
||||
# state["remainingseconds"] = value
|
||||
# value = "%d:%02d" % (value / 60 / 60, (value / 60) % 60)
|
||||
|
||||
new_topic = device_topics[topic]
|
||||
state[new_topic] = value
|
||||
update = True
|
||||
|
||||
Reference in New Issue
Block a user