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 (0)