Ir al contenido

← Todas las funcionalidades

Telemetría MQTT por Wi-Fi con un Ardbox Q Lite: ejemplo completo

El Ardbox Q Lite publica sus entradas en un broker MQTT por Wi-Fi y activa una salida con un mensaje MQTT.

Qué hace

Cada 5 segundos la app de Linux lee las entradas con Arduino Bridge y las publica en JSON en ardbox-q-lite/line1/inputs. Un mensaje 1 o 0 en ardbox-q-lite/line1/output/set activa o desactiva la salida.

Qué necesitas

  • Ardbox Q Lite AD o ADR con alimentación de 12 a 24 Vdc.
  • Arduino IDE 2.0+ con el paquete de placas de Industrial Shields (placa: Ardbox Q, tu versión).
  • Arduino App Lab para ejecutar la app de Linux.

Cómo ponerlo en marcha

  1. Carga sketch/sketch.ino con Arduino IDE.
  2. Crea una app en Arduino App Lab con app.yaml y python/main.py de esta página, y ejecútala.
  3. Antes de ejecutar la app, pon en BROKER de python/main.py la dirección de tu broker MQTT.

sketch/sketch.ino

/*
  Ardbox Q Lite example 05: microcontroller side

  Gives the Linux app access to the inputs and one output through Arduino Bridge.
  Output: Q0.0 on Ardbox Q Lite AD, relay R1 on Ardbox Q Lite ADR.
  Upload with Arduino IDE 2.0+ or arduino-cli, board Ardbox Q, your version.
*/

#include <Arduino_RouterBridge.h>

#if defined(IS_ARDBOX_Q_RELAY)
const pin_size_t OUT = R1;    // Ardbox Q Lite ADR: relay R1
#else
const pin_size_t OUT = Q0_0;  // Ardbox Q Lite AD: digital output Q0.0
#endif

const pin_size_t DIGITAL_IN[] = { I0_0, I0_1, I0_2, I0_3 };
const pin_size_t ANALOG_IN[]  = { I0_4, I0_5, I0_6, I0_7, I0_8, I0_9 };

// Digital input 0 to 3 (I0.0 to I0.3). Returns -1 if the channel does not exist.
int readDigital(int ch) {
  if (ch < 0 || ch > 3) return -1;
  return digitalRead(DIGITAL_IN[ch]);
}

// Analog input 0 to 5 (I0.4 to I0.9), raw value 0 to 1023 (10 bits by default).
int readAnalog(int ch) {
  if (ch < 0 || ch > 5) return -1;
  return analogRead(ANALOG_IN[ch]);
}

bool setOutput(bool on) {
  digitalWrite(OUT, on ? HIGH : LOW);
  return on;
}

void setup() {
  for (pin_size_t p : DIGITAL_IN) pinMode(p, INPUT);
  pinMode(OUT, OUTPUT);
  Bridge.begin();
  Bridge.provide_safe("read_digital", readDigital);
  Bridge.provide_safe("read_analog", readAnalog);
  Bridge.provide_safe("set_output", setOutput);
}

void loop() {}

python/main.py

"""
Ardbox Q Lite example 05: MQTT telemetry over Wi-Fi

Publishes the inputs every 5 seconds as JSON to <BASE>/inputs and switches
the output when "1" or "0" arrives on <BASE>/output/set.

1. Upload sketch/sketch.ino with Arduino IDE (board Ardbox Q, your version).
2. Set BROKER (and user/password if your broker needs them).
3. Run this app from Arduino App Lab (requirements.txt installs paho-mqtt).
"""
import json
import time

import paho.mqtt.client as mqtt
from arduino.app_utils import *

BROKER = "192.168.1.10"   # your MQTT broker
PORT = 1883
BASE = "ardbox-q-lite/line1"
PERIOD_S = 5

pending_output = None


def on_message(client, userdata, msg):
    global pending_output
    pending_output = msg.payload.decode().strip() in ("1", "on", "true")


client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
client.on_message = on_message
client.connect(BROKER, PORT, keepalive=60)
client.subscribe(BASE + "/output/set")
client.loop_start()


def loop():
    global pending_output
    if pending_output is not None:
        Bridge.call("set_output", pending_output)
        client.publish(BASE + "/output", "1" if pending_output else "0", retain=True)
        pending_output = None

    data = {
        "time": int(time.time()),
        "digital": [Bridge.call("read_digital", ch) for ch in range(4)],
        "analog": [Bridge.call("read_analog", ch) for ch in range(6)],
    }
    client.publish(BASE + "/inputs", json.dumps(data))
    time.sleep(PERIOD_S)


App.run(user_loop=loop)

app.yaml

name: Ardbox Q Lite MQTT telemetry
description: Publishes the inputs to an MQTT broker and switches the output from MQTT
icon: "📡"
bricks: []

python/requirements.txt

paho-mqtt>=2.0