This commit is contained in:
2024-11-05 16:34:56 +01:00
parent d57becf736
commit 9582790160
2 changed files with 39 additions and 23 deletions

View File

@ -43,11 +43,12 @@ context['publish'] = PUBLISH_PREFIX
try:
boxes = json.loads(BOXES_CONFIG)
# here, boxes store their internal state
boxes['context'] = {}
# boxes structure added to global context to give process_message access to it
context['boxes'] = boxes
# add context dict to each box in the list
for box_name, config in boxes.items():
config['context'] = {}
except json.JSONDecodeError as e:
logger.error(f"Error parsing JSON configuration for boxes: {e}")
sys.exit(1)
@ -55,8 +56,15 @@ except json.JSONDecodeError as e:
# Load box-specific topic prefixes from JSON
try:
box_topic_prefixes = json.loads(BOX_TOPIC_PREFIXES_CONFIG)
except json.JSONDecodeError as e:
logger.error(f"Error parsing JSON configuration for box-specific topic prefixes: {e}")
# Validation: Check if the required keys are present
required_keys = {'window', 'high_temp', 'cmd'}
missing_keys = required_keys - box_topic_prefixes.keys()
if missing_keys:
raise ValueError(f"Error: The following keys are missing in MQTT_BOX_TOPIC_PREFIXES: {', '.join(missing_keys)}")
except (json.JSONDecodeError, ValueError) as e:
logger.error(str(e))
sys.exit(1)
# Load central topics from JSON
@ -66,6 +74,7 @@ except json.JSONDecodeError as e:
logger.error(f"Error parsing JSON configuration for central topics: {e}")
sys.exit(1)
# Generate CLIENT_ID from UUID and optional prefix
CLIENT_PREFIX = os.getenv("MQTT_CLIENT_PREFIX", "MQTTClient")
CLIENT_ID = f"{CLIENT_PREFIX}_{uuid.uuid4()}"
@ -86,19 +95,24 @@ def on_connect(client, userdata, flags, rc):
continue
# Generate topics based on configured box-specific prefixes and box label
topics = {}
for topic_key, prefix in box_topic_prefixes.items():
if topic_key == 'window':
for window in boxes.windows:
topics[topic_key] = f"{prefix}{label}"
config["subscribe"] = topics # Store the generated topics
# Subscribe to the topics for the box and create mapping
for topic_key, topic in topics.items():
client.subscribe(topic)
topic_mapping[topic] = (box_name, topic_key)
logger.info(f"[{box_name}] Subscribed to '{topic}' (Key: '{topic_key}')")
windows = config.get("windows", [])
if not windows:
logger.warning(f"[{box_name}] No 'windows' defined.")
continue
for window in windows:
# Form the new topic_key by combining 'window' and the window name
enhanced_topic_key = f"{topic_key}/{window}"
topic = f"{prefix}{label}/{window}"
client.subscribe(topic)
topic_mapping[topic] = (box_name, enhanced_topic_key)
logger.info(f"[{box_name}] Subscribed to '{topic}' (Key: '{enhanced_topic_key}')")
else:
topic = f"{prefix}{label}"
client.subscribe(topic)
topic_mapping[topic] = (box_name, topic_key)
logger.info(f"[{box_name}] Subscribed to '{topic}' (Key: '{topic_key}')")
# Subscribe to central topics and create mappings
for central_key, central_topic in central_topics.items():

View File

@ -5,24 +5,26 @@ from loguru import logger
# boxes: structure of boxes
# client: MQTT client
#
# boxes['context']
# boxes['box_name']['context']
# store here what ever is require to represent the state of the box
def process_message(box_name, topic_key, payload, context):
try:
logger.info(f"[{box_name}] Processing message for '{topic_key}': {payload}")
match topic_key:
case 'window':
match topic_key.split('/'):
case [ primary_key, sub_key ] if primary_key == 'window':
pass
case 'high_temp':
case [ primary_key ] if primary_key == 'high_temp':
pass
case 'cmd':
case [ primary_key ] if primary_key == 'cmd':
pass
case 'general_off':
case [ primary_key ] if primary_key == 'general_off':
pass
case 'maintenance_mode':
case [ primary_key ] if primary_key == 'maintenance_mode':
pass
case _:
raise Error(f"Unexcepted topic_key: {topic_key}, {payload}")
# Example processing: Implement your specific logic here
# For example, perform calculations or store data.