树莓派上传系统数据到MQTT服务器

树莓派上传系统数据到MQTT服务器

前段时间购买了一个服务器,安装了MQTT服务器,实现一些智能家居的功能。同时手头上有一个树莓派,慢慢部署一些功能,第一个就是上传树莓派的系统资源到MQTT,这样手机端或者小屏幕可以实时获取和显示。

参考:https://www.jianshu.com/p/06d23de47aed
https://blog.csdn.net/lhh08hasee/article/details/88025436
https://moe.best/tutorial/frp.html

一、编写树莓派python程序

1. 安装必要库

使用python3运行程序,需要使用到psutil库获取系统资源和paho-mqtt库上传数据到MQTT服务器。

pip3 install psutil
pip3 install paho-mqtt

2. 代码

使用nano或vim将以下python代码存储,起名为"publish_res_mqtt.py"。需修改mqtt服务器ip地址、端口、账户和密码。

#!/usr/bin/env python
#coding:utf-8

import time
import json
import psutil
import random
from paho.mqtt import client as mqtt_client

broker = 'xx.xx.xx.xx'  # mqtt代理服务器地址
port = 1883				# 端口
keepalive = 60     		# 与代理通信之间允许的最长时间段(以秒为单位)              
topic = "/pi/res"  		# 消息主题
client_id = f'python-mqtt-pub-{random.randint(0, 1000)}'  # 客户端id不能重复

def to_M(n):
    '''将B转换为M'''
    u = 1024 * 1024
    m = round(n / u, 2)
    return m

def get_info():
    '''获取系统硬件信息:cpu利用率,cpu个数,系统负载,内存信息等'''
    cpu_percent = psutil.cpu_percent(interval=1)
    cpu_count = psutil.cpu_count()
    mem = psutil.virtual_memory()
    mem_total, men_free = to_M(mem.total), to_M(mem.free)
    mem_percent = mem.percent
    info = {
        'cpu_percent': cpu_percent,
        'cpu_count' : cpu_count,
        'mem_total': mem_total,
        'mem_percent': mem_percent,
        'men_free': men_free
    }
    # mqtt只能传输字符串数据
    return json.dumps(info)

def connect_mqtt():
    '''连接mqtt代理服务器'''
    def on_connect(client, userdata, flags, rc):
        '''连接回调函数'''
        # 响应状态码为0表示连接成功
        if rc == 0:
            print("Connected to MQTT OK!")
        else:
            print("Failed to connect, return code %d\n", rc)
    # 连接mqtt代理服务器,并获取连接引用
    # client = mqtt_client.Client(client_id) 由于mqtt_client更新,需要使用下面的指令限定版本
    client = mqtt_client.Client(mqtt_client.CallbackAPIVersion.VERSION1, client_id)
    client.username_pw_set("xxx", "xxx")		# 连接MQTT的账户和密码
    client.on_connect = on_connect
    client.connect(broker, port, keepalive)
    return client

def publish(client):
    '''发布消息'''
    while True:
        '''每隔4秒发布一次服务器信息'''
        time.sleep(4)
        msg = get_info()
        result = client.publish(topic, msg)
        status = result[0]
        if status == 0:
            print(f"Send `{msg}` to topic `{topic}`")
        else:
            print(f"Failed to send message to topic {topic}")

def run():
    '''运行发布者'''
    client = connect_mqtt()
    # 运行一个线程来自动调用loop()处理网络事件, 非阻塞
    client.loop_start()
    publish(client)

if __name__ == '__main__':
    run()

3. 测试

使用以下命令运行程序,查看输出。

python3 publish_res_mqtt.py

三、后台运行

1. 使用nohup实现后台运行

nohup python3 publish_res_mqtt.py &

四、手机端显示

1. 使用mqtt客户端,接受数据并显示,如下图

在这里插入图片描述

  • 4
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值