DEV Community

Cristian Manuel Montoya villegas
Cristian Manuel Montoya villegas

Posted on Edited on

Designing Automated Rule Engines in Python for Real-Time IoT Control

Why Rule-Based Automation Beats Hardcoded Thresholds

When managing physical actuators like dosing pumps, fans, or valves in automated systems, hardcoding if/else conditions inside firmware makes updates slow and error-prone. A lightweight rule engine on the backend or edge gateway lets operators adjust thresholds dynamically without reflashing hardware.

Building a Simple JSON Rule Evaluator in Python

Here is a clean pattern to evaluate incoming sensor telemetry against dynamic rules with cooldown protection to prevent relay chatter:

import time

class RuleEngine:
    def __init__(self, cooldown_seconds: int = 60):
        self.cooldown = cooldown_seconds
        self.last_triggered = {}

    def evaluate(self, sensor_data: dict, rules: list) -> list:
        actions_to_run = []
        now = time.time()

        for rule in rules:
            metric = rule["metric"]
            if metric not in sensor_data:
                continue

            value = sensor_data[metric]
            op = rule["operator"]
            target = rule["threshold"]

            triggered = (
                (op == ">" and value > target) or
                (op == "<" and value < target)
            )

            if triggered:
                last_time = self.last_triggered.get(rule["id"], 0)
                if now - last_time >= self.cooldown:
                    self.last_triggered[rule["id"]] = now
                    actions_to_run.append(rule["action"])

        return actions_to_run
Enter fullscreen mode Exit fullscreen mode

Conclusion

Separating control logic from sensor ingestion keeps edge devices simple while giving operators safe, predictable automation with built-in cooldown intervals.

Top comments (0)