通过为树莓派主板增加一个温湿度传感器,实现Raspberry Pi 4计算机在服务器机房中搜集环境数据。
前提条件
硬件连接
安装依赖程序
传感器的数据传递功能需要安装依赖程序开启。
修改和验证源码程序
您需要修改树莓派计算机的源码程序文件,将新属性(机房温度、机房湿度)数据添加到协议字段中。
通过为树莓派主板增加一个温湿度传感器,实现Raspberry Pi 4计算机在服务器机房中搜集环境数据。
传感器的数据传递功能需要安装依赖程序开启。
cd /home/pi/Desktop
sudo apt update
sudo apt install git
git clone https://github.com/adafruit/Adafruit_Python_DHT.git
cd Adafruit_Python_DHT
sudo python3 setup.py install
cd /
python3
import Adafruit_DHT
humidity, temperature = Adafruit_DHT.read_retry(11, 4)
humidity,temperature
您需要修改树莓派计算机的源码程序文件,将新属性(机房温度、机房湿度)数据添加到协议字段中。
请对比以下内容修改run.py文件并保存。
#!/usr/bin/python3
import aliLink,mqttd,rpi
import time,json
import Adafruit_DHT
# 三元素(iot后台获取)
ProductKey = '***'
DeviceName = 'raspberrypi4-******'
DeviceSecret = "assef***"
# topic (iot后台获取)
POST = '/sys/***/raspberrypi4-***/thing/event/property/post' # 上报消息到云
POST_REPLY = '/sys/***/raspberrypi4-***/thing/event/property/post_reply'
SET = '/sys/***/raspberrypi4-***/thing/service/property/set' # 订阅云端指令
# 消息回调(云端下发消息的回调函数)
def on_message(client, userdata, msg):
#print(msg.payload)
Msg = json.loads(msg.payload)
switch = Msg['params']['PowerLed']
rpi.powerLed(switch)
print(msg.payload) # 开关值
#连接回调(与阿里云建立链接后的回调函数)
def on_connect(client, userdata, flags, rc):
pass
# 链接信息
Server,ClientId,userNmae,Password = aliLink.linkiot(DeviceName,ProductKey,DeviceSecret)
# mqtt链接
mqtt = mqttd.MQTT(Server,ClientId,userNmae,Password)
mqtt.subscribe(SET) # 订阅服务器下发消息topic
mqtt.begin(on_message,on_connect)
# 信息获取上报,每10秒钟上报一次系统参数
while True:
time.sleep(10)
#获取指示灯状态
power_stats=int(rpi.getLed())
if(power_stats==0):
power_LED = 0
else:
power_LED = 1
# CPU 信息
CPU_temp = float(rpi.getCPUtemperature()) # 温度 ℃
CPU_usage = float(rpi.getCPUuse()) # 占用率 %
# RAM 信息
RAM_stats =rpi.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 信息
DISK_stats =rpi.getDiskSpace()
DISK_total = float(DISK_stats[0][:-1])
DISK_used = float(DISK_stats[1][:-1])
DISK_perc = float(DISK_stats[3][:-1])
# 获取传感器信息
humidity, temperature = Adafruit_DHT.read_retry(11, 4)
# 构建与云端模型一致的消息结构
updateMsn = {
'cpu_temperature':CPU_temp,
'cpu_usage':CPU_usage,
'RAM_total':RAM_total,
'RAM_used':RAM_used,
'RAM_free':RAM_free,
'DISK_total':DISK_total,
'DISK_used_space':DISK_used,
'DISK_used_percentage':DISK_perc,
'PowerLed':power_LED,
'temperature':temperature,
'humidity':humidity
}
JsonUpdataMsn = aliLink.Alink(updateMsn)
print(JsonUpdataMsn)
mqtt.push(POST,JsonUpdataMsn) # 定时向阿里云IOT推送我们构建好的Alink协议数据
cd /home/pi/Desktop/code/
python3 run.py
在文档使用中是否遇到以下问题
更多建议
匿名提交