Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
3.8 kB
4
Indexable
Never
import paho.mqtt.client as mqtt
import os
import time
import json
import requests

# ... [Keep all the imports and global variables from the original script] ...

# New global variables for message comparison
previous_msg = None
last_sent_times = []

def fetch_sampling_frequencies():
    # ... [Keep this function as is] ...

def on_message_local(client, userdata, message):
    # ... [Keep this function as is] ...

def extract_sensor_values_and_interval(message):
    parts = message.split('#')
    if len(parts) < 3:
        return None, None
    
    sensor_values_str = parts[2]
    sensor_values = [float(val) for val in sensor_values_str.split(',')]
    
    return sensor_values, fetch_sampling_frequencies()

def create_message_for_sensor(message, sensor_index, sensor_value):
    parts = message.split('#')
    sensor_values = parts[2].split(',')
    
    modified_sensor_values = ['X' if i != sensor_index else f'{sensor_value:.2f}' for i in range(len(sensor_values))]
    
    parts[2] = ','.join(modified_sensor_values)
    return '#'.join(parts)

def forward_message(topic, payload):
    global aws_connected, previous_msg, last_sent_times
    
    if not aws_connected:
        print("AWS broker not connected. Message not sent.")
        return False

    current_time = time.time()
    new_sensor_vals, sensor_intervals = extract_sensor_values_and_interval(payload)
    
    if new_sensor_vals is None:
        print("Error: Invalid sensor data format")
        return False
    
    if previous_msg is None:
        previous_msg = payload
        last_sent_times = [current_time] * len(new_sensor_vals)
        for i, sensor_value in enumerate(new_sensor_vals):
            msg_to_send = create_message_for_sensor(payload, i, sensor_value)
            try:
                result = aws_client.publish(topic, msg_to_send)
                if result.rc == mqtt.MQTT_ERR_SUCCESS:
                    print(f"Initial message sent to AWS broker for sensor {i}: {msg_to_send}")
                else:
                    print(f"Failed to send initial message to AWS broker for sensor {i}, result code: {result.rc}")
                    return False
            except Exception as e:
                print(f"Exception while sending initial message to AWS broker: {e}")
                aws_connected = False
                return False
        return True
    
    prev_sensor_vals, _ = extract_sensor_values_and_interval(previous_msg)
    
    for i, (prev_val, new_val, interval) in enumerate(zip(prev_sensor_vals, new_sensor_vals, sensor_intervals)):
        percentage_change = abs((new_val - prev_val) / prev_val) * 100 if prev_val != 0 else float('inf')
        
        if percentage_change > 2 or (current_time - last_sent_times[i] >= interval):
            msg_to_send = create_message_for_sensor(payload, i, new_val)
            try:
                result = aws_client.publish(topic, msg_to_send)
                if result.rc == mqtt.MQTT_ERR_SUCCESS:
                    print(f"Message sent to AWS broker for sensor {i} due to {'variation' if percentage_change > 2 else 'time interval'}: {msg_to_send}")
                    last_sent_times[i] = current_time
                else:
                    print(f"Failed to send message to AWS broker for sensor {i}, result code: {result.rc}")
                    return False
            except Exception as e:
                print(f"Exception while sending message to AWS broker: {e}")
                aws_connected = False
                return False
    
    previous_msg = payload
    return True

# ... [Keep all other functions and the main execution loop as they were in the original script] ...
Leave a Comment