V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
爱意满满的作品展示区。
caoz
V2EX  ›  分享创造

[折腾] 使用 MQTT / Python / Grafana 实现小米路由器网速查看与统计

  •  
  •   caoz ·
    CaoZ · 306 天前 · 1371 次点击
    这是一个创建于 306 天前的主题,其中的信息可能已经有所发展或是发生改变。

    小米 AX6000 路由器虽然身形巨大无比,但自带的网速查看功能却十分简陋,约等于没有。幸好系统是基于 OpenWrt 的,可以自己动手实现一个。

    Step 1: 寻找数据

    命令:

    ubus call trafficd hw '{"debug": true}'
    

    trafficd

    简单的命令却寻觅最久,机缘巧合之下才发现... 使用时加入 debug 参数以获得更多信息。


    Step 2:加工处理

    有了数据源就好做了,定时采样加工处理再展示即可。小米路由器自带了一部分 MQTT 工具,因此使用 MQTT 将数据源转发给电脑处理并入库,再使用 Grafana 做展示。即使电脑不一直开机也没关系,通过配置,MQTT broker 可持久化暂存未处理消息。

    2.1 安装 Mosquitto broker 2.0

    小强系统自带了 MQTT client ,只需安装支持 MQTT v5 的 broker 即可。手动下载 ipk 文件,解压后获得可执行文件(.\data.tar.gz\.\usr\sbin\mosquitto),将其上传到路由器中并注册为服务。如果 opkg 可用更佳。

    Cortex-A53: mosquitto-nossl_2.0.15-1_aarch64_cortex-a53.ipk

    更多https://mirrors.aliyun.com/openwrt/releases/22.03-SNAPSHOT/packages/

    创建配置文件:

    /etc/mosquitto.conf:

    # log_dest file /tmp/log/mosquitto.log
    user root
    bind_address 0.0.0.0
    allow_anonymous true
    

    /etc/init.d/mosquitto-2

    #!/bin/sh /etc/rc.common
    
    START=50
    
    start() {
        /data/cz/bin/mosquitto-2 -c /etc/mosquitto.conf -d
        return 0
    }
    

    2.2 定时采样

    创建 cron job 实现定时采样,可结合 sleep 实现分钟内采样。

    * * * * * ubus -S call trafficd hw '{"debug": true}' | mosquitto_pub -t 'home/router-stat' -q 2 -i client_pub -l -D publish user-property timestamp $(date +%s) >/dev/null 2>&1
    

    2.3 编写程序解析数据并入库

    使用 Python 编写 MQTT 消费者程序,解析数据并写入数据库。如果是 Windows 可以使用 nssm 将其注册为服务

    配置在 config.py 中。

    创建所需表:

    CREATE TABLE router_stat (
    	id INTEGER NOT NULL AUTO_INCREMENT,
    	ip VARCHAR(15),
    	mac CHAR(17),
    	network ENUM('2.4G','5G','Ethernet','Unknown'),
    	device VARCHAR(255),
    	rx_rate INTEGER,
    	tx_rate INTEGER,
    	timestamp DATETIME,
    	PRIMARY KEY (id)
    );
    

    2.4 安装 Grafana 并创建监控面板

    有了数据就可以用 Grafana 自由的创建监控面板了~

    比如创建一个 Time series 面板来查看上传下载总速度:

    select sum(rx_rate) as rx_rate, sum(tx_rate) as tx_rate, unix_timestamp(timestamp) as time from home.router_stat where $__timeFilter(timestamp) group by timestamp
    

    Screenshot:

    监控面板

    第 1 条附言  ·  306 天前

    创建表的 SQL 忘贴索引了,实际上用了 ORM,无需手动创建表,表不存在会自动创建。

    表的结构定义在 data.py 中。

    3 条回复    2023-06-27 18:52:17 +08:00
    wliansheng
        1
    wliansheng  
       306 天前
    6 ,有空我也试试
    Masoud2023
        2
    Masoud2023  
       306 天前
    写进 influx 查询比较快
    caoz
        3
    caoz  
    OP
       306 天前
    @Masoud2023 是的,但自己用数据量不多就没再安装个数据库...
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3111 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 13:37 · PVG 21:37 · LAX 06:37 · JFK 09:37
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.