DEV Community

Habeeb
Habeeb

Posted on

Handling debounce and race conditions in Python asyncio when triggering vehicle barrier relays via MQTT

Hey DEV community!

We are currently building an edge microservice running on a Raspberry Pi CM4 (Debian 12) that serves as an on-premise integration bridge between our cloud access control platform and physical perimeter hardware.

As part of integrating an automated gate barrier system at an industrial facility entrance, our edge service listens to MQTT topics dispatched by an ANPR (license plate recognition) camera stream and a ground magnetic loop sensor to trigger an optocoupled relay board via GPIO.

The Problem

During peak vehicle arrival times, we are encountering a race condition where the ANPR camera event and the magnetic loop trigger fire almost simultaneously (within 80–150ms of each other). This occasionally creates a double-pulse on the barrier controller's open terminal, causing the gate barrier's internal microcontroller to interpret the second pulse as a "reverse/stop" command while the arm is already in motion.

Here is the simplified asyncio listener and relay dispatcher we are using:

python
import asyncio
from gpiod import LineRequest, LineSettings, Direction, Value
import aiomqtt
RELAY_PIN = 17
PULSE_DURATION = 0.5 # 500ms dry contact pulse to barrier controller
lock = asyncio.Lock()
is_gate_cycling = False
async def trigger_barrier_relay():
global is_gate_cycling
async with lock:
if is_gate_cycling:
print("Gate cycle already active. Ignoring secondary trigger.")
return
is_gate_cycling = True
print("Firing relay pulse to open barrier...")

    # Simulate GPIO pulse
    # In real code: line.set_values({RELAY_PIN: Value.ACTIVE})
    await asyncio.sleep(PULSE_DURATION)
    # line.set_values({RELAY_PIN: Value.INACTIVE})

    # Cooldown window to let barrier fully clear
    await asyncio.sleep(4.0)
    is_gate_cycling = False
Enter fullscreen mode Exit fullscreen mode

async def mqtt_worker():
async with aiomqtt.Client("192.168.10.50") as client:
await client.subscribe("facility/gate/north/#")
async for message in client.messages:
if message.topic.matches("facility/gate/north/trigger"):
# Spawn task to avoid blocking MQTT loop
asyncio.create_task(trigger_barrier_relay())
asyncio.run(mqtt_worker())

Where It Fails
Even with the basic asyncio.Lock() and boolean flag, rapid overlapping events from the broker sometimes hit the queue while the event loop is handling network I/O, leading to occasional queue pile-ups or missed cooldown state updates if the broker temporarily reconnects.

Questions for the Community:

  1. What is the cleanest pattern in asyncio to implement a strict token bucket / debounce rate-limiter across asynchronous MQTT consumers?

  2. Would you recommend handling the gate cycle state machine via an external Redis key with TTL, or is an in-memory queue like asyncio.Queue sufficient for an isolated edge node?

  3. How do you typically handle hardware state feedback (e.g., reading limit switch status back into the async loop) to guarantee the relay doesn't fire when the barrier arm is already vertical?

Any suggestions, libraries, or architectural patterns would be greatly appreciated!

Top comments (1)

Collapse
 
osamamalik profile image
Osama Malik •

The double pulse comes from the lock itself. When a second trigger arrives during a cycle, its task does not skip. It waits on async with lock for the full 4.5 seconds. Then it gets the lock, sees is_gate_cycling back at False, and fires again. So the lock queues triggers instead of dropping them.

In asyncio you don't need a lock for this. Code with no await between the check and the set can't be interrupted by another task. Check and claim the state first, then do the slow work:

import time

cycle_until = 0.0
COOLDOWN = 4.5

async def trigger_barrier_relay():
    global cycle_until
    now = time.monotonic()
    if now < cycle_until:
        return  # drop it, don't queue it
    cycle_until = now + COOLDOWN  # claimed before any await
    line.set_values({RELAY_PIN: Value.ACTIVE})
    await asyncio.sleep(PULSE_DURATION)
    line.set_values({RELAY_PIN: Value.INACTIVE})
Enter fullscreen mode Exit fullscreen mode

A monotonic deadline also holds up better than a flag. If the task is cancelled during a broker reconnect, the deadline still expires on its own, while a flag can stay True forever.

For your other questions: on a single edge node, an in-memory deadline like this is enough. Redis adds a network hop and a new way to fail, and it only helps when several processes share the gate. For hardware feedback, read the limit switch line before you fire and refuse while the arm is not closed. The libgpiod v2 bindings can watch that line with edge detection and a debounce period. The switch itself is a better source of truth than a timer.

One more thing: keep a reference to the tasks you create with asyncio.create_task (for example in a set, and remove each one when it finishes). The asyncio docs warn that a task with no reference can be garbage collected before it finishes.