USE iot_log;

-- 创建同时记录上下线状态的超级表
CREATE STABLE IF NOT EXISTS device_status_log (
    ts TIMESTAMP,         -- 事件发生时间
    event VARCHAR(16),    -- 事件类型: 'connected' 或 'disconnected'
    reason VARCHAR(64),   -- 下线原因（上线时填 'clean_start' 或 'none'）
    peername VARCHAR(64)  -- 客户端 IP 及端口
) TAGS (
    clientid VARCHAR(128),
    username VARCHAR(128)
);

-- emqx 设备离线 rules
SELECT
    clientid,
    username,
    peername,
    reason,
    disconnected_at AS ts,
    'disconnected' AS event
FROM
    "$events/client_disconnected"

-- emqx 设备离线 action
INSERT INTO mqtt.device_${clientid}
USING mqtt.device_status_log TAGS ('${clientid}', '${username}')
VALUES (${ts}, '${event}', '${reason}', '${peername}');

-- emqx 设备上线 rules
SELECT
    clientid,
    username,
    peername,
    connected_at AS ts,
    'connected' AS event
FROM
    "$events/client_connected"

-- emqx 设备上线 action
INSERT INTO mqtt.device_${clientid}
USING mqtt.device_status_log TAGS ('${clientid}', '${username}')
VALUES (${ts}, '${event}', 'none', '${peername}');