树莓派python安装mqtt库
pip3 install paho-mqtt
定时获取树莓派温度、CPU、内存、硬盘信息,使用公共服务器broker.emqx.io进行数据推送,上代码
import os import random import time import json from paho.mqtt import client as mqtt_client broker = 'broker.emqx.io' port = 1883 topic = "/python/mqtt" # generate client ID with pub prefix randomly client_id = f'python-mqtt-{random.randint(0, 1000)}' # Return CPU temperature as a character string def getCPUtemperature(): res = os.popen('vcgencmd measure_temp').readline() return(res.replace("temp=","").replace("'C\n","")) # Return RAM information (unit=kb) in a list # Index 0: total RAM # Index 1: used RAM # Index 2: free RAM def getRAMinfo(): p = os.popen('free') i = 0 while 1: i = i + 1 line = p.readline() if i==2: return(line.split()[1:4]) # Return % of CPU used by user as a character string def getCPUuse(): return(str(os.popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip())) # Return information about disk space as a list (unit included) # Index 0: total disk space # Index 1: used disk space # Index 2: remaining disk space # Index 3: percentage of disk used def getDiskSpace(): p = os.popen("df -h /") i = 0 while 1: i = i +1 line = p.readline() if i==2: return(line.split()[1:5]) def connect_mqtt(): def on_connect(client, userdata, flags, rc): if rc == 0: print("Connected to MQTT Broker!") else: print("Failed to connect, return code %d\n", rc) client = mqtt_client.Client(client_id) client.on_connect = on_connect client.connect(broker, port) return client def publish(client): # CPU informatiom CPU_temp = getCPUtemperature() CPU_usage = getCPUuse() # RAM information # Output is in kb, here I convert it in Mb for readability RAM_stats = getRAMinfo() RAM_total = round(int(RAM_stats[0]) / 1000,1) RAM_used = round(int(RAM_stats[1]) / 1000,1) RAM_free = round(int(RAM_stats[2]) / 1000,1) # Disk information DISK_stats = getDiskSpace() DISK_total = DISK_stats[0] DISK_used = DISK_stats[1] result = client.publish(topic, json.dumps({"CPU Temperature":CPU_temp,"CPU Use":CPU_usage,"RAM Total":str(RAM_total)+' MB',"RAM Used":str(RAM_used)+' MB',"RAM Free":str(RAM_free)+' MB',"DISK Total":str(DISK_total)+'B',"DISK Used":str(DISK_used)+'B'})) 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() publish(client) if __name__ == '__main__': run()
在线测试工具:http://tools.emqx.io/
点击connect连接服务器。
点击New Subscription,topic输入代码第九行定义的topic主题名称,也就是“/python/mqtt”