Cleanup error checking and exceptions

This commit is contained in:
Meatballs1
2024-03-20 11:56:52 +00:00
parent b1f20b82b5
commit f127fce93f
2 changed files with 51 additions and 50 deletions

View File

@@ -95,24 +95,19 @@ class HCDevice:
# Based on PR submitted https://github.com/Skons/hcpy/pull/1 # Based on PR submitted https://github.com/Skons/hcpy/pull/1
def test_program_data(self, data): def test_program_data(self, data):
if "program" not in data: if "program" not in data:
raise Exception("{self.name}. Message data invalid, no program specified.") raise TypeError("Message data invalid, no program specified.")
if isinstance(data["program"], str):
try: if isinstance(data["program"],int) is False:
data["program"] = int(data["program"]) raise TypeError(
except Exception: f"Message data invalid, UID in 'program' must be an integer."
raise Exception(
"{self.name}. Message data invalid, UID in 'program' must be an integer."
)
elif isinstance(data["program"], int) is False:
raise Exception(
"{self.name}. Message data invalid. UID in 'program' must be an integer."
) )
# devices.json stores UID as string
uid = str(data["program"]) uid = str(data["program"])
if uid not in self.features: if uid not in self.features:
raise Exception( raise ValueError(
f"{self.name}. Unable to configure appliance. Program UID {uid} is not valid" f"Unable to configure appliance. Program UID {uid} is not valid"
" for this device." " for this device."
) )
@@ -121,34 +116,34 @@ class HCDevice:
# Hood is Cooking.Common.Program.{name} # Hood is Cooking.Common.Program.{name}
# May also be in the format BSH.Common.Program.Favorite.001 # May also be in the format BSH.Common.Program.Favorite.001
if ".Program." not in feature["name"]: if ".Program." not in feature["name"]:
raise Exception( raise ValueError(
f"{self.name}. Unable to configure appliance. Program UID {uid} is not a valid" f"Unable to configure appliance. Program UID {uid} is not a valid"
"program." f" program - {feature['name']}."
) )
if "options" in data: if "options" in data:
for option_uid in data["options"]: for option_uid in data["options"]:
if str(option_uid) not in self.features: if str(option_uid) not in self.features:
raise Exception( raise ValueError(
f"{self.name}. Unable to configure appliance. Option UID {uid} is not" f"Unable to configure appliance. Option UID {uid} is not"
" valid for this device." " valid for this device."
) )
# Test the feature of an appliance agains a data object # Test the feature of an appliance agains a data object
def test_feature(self, data): def test_feature(self, data):
if "uid" not in 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: 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: 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 # Check if the uid is present for this appliance
uid = str(data["uid"]) uid = str(data["uid"])
if uid not in self.features: 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] feature = self.features[uid]
@@ -156,14 +151,14 @@ class HCDevice:
print(now(), self.name, f"Processing feature {feature['name']} with uid {uid}") print(now(), self.name, f"Processing feature {feature['name']} with uid {uid}")
if "access" not in feature: if "access" not in feature:
raise Exception( raise Exception(
f"{self.name}. Unable to configure appliance." "Unable to configure appliance. "
f"Feature {feature['name']} with uid {uid} does not have access." f"Feature {feature['name']} with uid {uid} does not have access."
) )
access = feature["access"].lower() access = feature["access"].lower()
if access != "readwrite" and access != "writeonly": if access != "readwrite" and access != "writeonly":
raise Exception( 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']}." f"Feature {feature['name']} with uid {uid} has got access {feature['access']}."
) )
@@ -179,7 +174,7 @@ class HCDevice:
# but always seem to be an integer. An integer must be provided # but always seem to be an integer. An integer must be provided
if value not in feature["values"]: if value not in feature["values"]:
raise Exception( raise Exception(
f"{self.name}. Unable to configure appliance." "Unable to configure appliance. "
f"Value {data['value']} is not a valid value. " f"Value {data['value']} is not a valid value. "
f"Allowed values are {feature['values']}. " f"Allowed values are {feature['values']}. "
) )
@@ -193,7 +188,7 @@ class HCDevice:
or data["value"] > max or data["value"] > max
): ):
raise Exception( raise Exception(
f"{self.name}. Unable to configure appliance." "Unable to configure appliance. "
f"Value {data['value']} is not a valid value. " f"Value {data['value']} is not a valid value. "
f"The value must be an integer in the range {min} and {max}." f"The value must be an integer in the range {min} and {max}."
) )
@@ -238,13 +233,14 @@ class HCDevice:
if data is not None: if data is not None:
if action == "POST": if action == "POST":
if "resource" == "/ro/values": if resource == "/ro/values":
# Raises exceptions on failure # Raises exceptions on failure
self.test_feature(data) self.test_feature(data)
elif "resource" == "/ro/activeProgram": elif resource == "/ro/activeProgram":
# Raises exception on failure # Raises exception on failure
self.test_program_data(data) self.test_program_data(data)
msg["data"] = [data] msg["data"] = [data]
try: try:

21
hc2mqtt
View File

@@ -88,27 +88,32 @@ dev = {}
def client_connect(client, device, mqtt_topic): def client_connect(client, device, mqtt_topic):
def on_message(client, userdata, msg): def on_message(client, userdata, msg):
print(msg.topic)
mqtt_state = msg.payload.decode() mqtt_state = msg.payload.decode()
mqtt_topic = msg.topic.split("/") 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: if len(mqtt_topic) >= 2:
device_name = mqtt_topic[-2] device_name = mqtt_topic[-2]
topic = mqtt_topic[-1] topic = mqtt_topic[-1]
else: else:
raise Exception(f"Invalid mqtt topic {msg.topic}") raise Exception(f"Invalid mqtt topic {msg.topic}.")
try: try:
msg = json.loads(mqtt_state) msg = json.loads(mqtt_state)
if topic == "set" and "uid" in msg: except ValueError as e:
dev[device_name].get("/ro/values", 1, "POST", msg) raise ValueError(f"Invalid JSON in message: {mqtt_state}.") from e
if topic == "set":
resource = "/ro/values"
elif topic == "activeProgram": elif topic == "activeProgram":
dev[device_name].get("/ro/activeProgram", 1, "POST", msg) resource = "/ro/activeProgram"
else: 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: except Exception as e:
print("ERROR", e, file=sys.stderr) print(now(), device_name, "ERROR", e, file=sys.stderr)
host = device["host"] host = device["host"]
device_topics = topics device_topics = topics