教程!基于树莓派+传感器+阿里云IoT的智能家居管理

发布时间 2023-09-18 17:20:15作者: 柯慕灵

时隔一年半,才发现这篇内容怎么还在草稿箱里,怪不得那么多人问我问题,绷不住了

以下代码均在同一文件夹下
在终端执行运行run.py文件即可

  1. run.py
1.	
#!/usr/bin/python3
2.	
3.	import aliLink,mqttd,rpi
4.	import time,json
5.	import Adafruit_DHT
6.	import time
7.	import LCD1602
8.	import flame_sensor
9.	import buzzer_1
10.	import rain_detector
11.	import gas_sensor
12.	import relay
13.	from threading import Thread
14.	
15.	pin = 19  # DHT11 温湿度传感器管脚定义
16.	Buzzer = 20    # 有源蜂鸣器管脚定义
17.	
18.	# GPIO口定义
19.	sensor = Adafruit_DHT.DHT11
20.	
21.	
22.	
23.	
24.	# 三元素(iot后台获取)
25.	ProductKey = 'a11lzCDSgZP'
26.	DeviceName = 'IU6aSETyiImFPSkpcywm'
27.	DeviceSecret = "2551eb5f630c372743c538e9b87bfe6d"
28.	# topic (iot后台获取)
29.	POST = '/sys/a11lzCDSgZP/IU6aSETyiImFPSkpcywm/thing/event/property/post'  # 上报消息到云
30.	POST_REPLY = '/sys/a11lzCDSgZP/IU6aSETyiImFPSkpcywm/thing/event/property/post_reply'
31.	SET = '/sys/a11lzCDSgZP/IU6aSETyiImFPSkpcywm/thing/service/property/set'  # 订阅云端指令
32.	
33.	
34.	#窗户开关
35.	window = 0
36.	window_status = 0
37.	Thread(target=relay.close).start()
38.	
39.	# 消息回调(云端下发消息的回调函数)
40.	def on_message(client, userdata, msg):
41.	    #print(msg.payload)
42.	    Msg = json.loads(msg.payload)
43.	
44.	    global window,window_status
45.	    window = Msg['params']['window']
46.	    print(msg.payload)  # 开关值
47.	    if window_status != window:
48.	        window_status = window
49.	        if window == 1:
50.	            Thread(target=relay.open).start()
51.	        else:
52.	            Thread(target=relay.close).start()
53.	
54.	
55.	
56.	#连接回调(与阿里云建立链接后的回调函数)
57.	def on_connect(client, userdata, flags, rc):
58.	    pass
59.	
60.	
61.	
62.	# 链接信息
63.	Server,ClientId,userNmae,Password = aliLink.linkiot(DeviceName,ProductKey,DeviceSecret)
64.	
65.	# mqtt链接
66.	mqtt = mqttd.MQTT(Server,ClientId,userNmae,Password)
67.	mqtt.subscribe(SET) # 订阅服务器下发消息topic
68.	mqtt.begin(on_message,on_connect)
69.	
70.	
71.	
72.	# 信息获取上报,每2秒钟上报一次系统参数
73.	while True:
74.	    #获取指示灯状态
75.	    power_stats=int(rpi.getLed())
76.	    if(power_stats == 0):
77.	        power_LED = 0
78.	    else:
79.	        power_LED = 1
80.	
81.	    # CPU 信息
82.	    CPU_temp = float(rpi.getCPUtemperature())  # 温度   ℃
83.	    CPU_usage = float(rpi.getCPUuse())         # 占用率 %
84.	
85.	    # RAM 信息
86.	    RAM_stats =rpi.getRAMinfo()
87.	    RAM_total =round(int(RAM_stats[0]) /1000,1)    #
88.	    RAM_used =round(int(RAM_stats[1]) /1000,1)
89.	    RAM_free =round(int(RAM_stats[2]) /1000,1)
90.	
91.	    # Disk 信息
92.	    DISK_stats =rpi.getDiskSpace()
93.	    DISK_total = float(DISK_stats[0][:-1])
94.	    DISK_used = float(DISK_stats[1][:-1])
95.	    DISK_perc = float(DISK_stats[3][:-1])
96.	
97.	    #温度,湿度
98.	    humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
99.	
100.	    # LCD显示
101.	    LCD = 0
102.	    try:
103.	        LCD1602.init(0x27, 1)          # 初始化显示屏
104.	        LCD1602.write(0, 0, 'humidity:    ' + str(int(humidity)) + '%')
105.	        LCD1602.write(0, 1, 'temperature: ' + str(int(temperature)) + '\'')  # 在第二行显示world!
106.	        LCD = 1
107.	    except:
108.	        print("显示屏连接不稳定,请检查")
109.	        LCD = 0
110.	
111.	    # 蜂鸣器
112.	    buzzer = 0
113.	
114.	    # 火焰传感器
115.	    flame_sensor.setup()
116.	    if flame_sensor.fire() == 0:
117.	        flame = 1
118.	        buzzer_1.buzzer_on() #让铃声叫
119.	        buzzer = 1
120.	    else:
121.	        flame = 0
122.	        buzzer_1.buzzer_off() #铃声不叫
123.	        buzzer = 0
124.	
125.	    # 烟雾传感器
126.	    gas = gas_sensor.gas()
127.	
128.	    # 雨滴传感器
129.	    rain_detector.setup()
130.	    if rain_detector.rain() == 0:
131.	        rain = 1
132.	    else:
133.	        rain = 0
134.	
135.	    # 构建与云端模型一致的消息结构
136.	    updateMsn = {
137.	        'cpu_temperature':CPU_temp,
138.	        'cpu_usage':CPU_usage,
139.	        'RAM_total':RAM_total,
140.	        'RAM_used':RAM_used,
141.	        'RAM_free':RAM_free,
142.	        'DISK_total':DISK_total,
143.	        'DISK_used_space':DISK_used,
144.	        'DISK_used_percentage':DISK_perc,
145.	        'PowerLed':power_LED,
146.	        'temperature':temperature,
147.	        'humidity':humidity,
148.	        'window':window,
149.	        'LCD':LCD,
150.	        'buzzer':buzzer,
151.	        'flame':flame,
152.	        'rain':rain,
153.	        'gas':gas
154.	    }
155.	    JsonUpdataMsn = aliLink.Alink(updateMsn)
156.	    print(JsonUpdataMsn)
157.	
158.	    mqtt.push(POST,JsonUpdataMsn) # 定时向阿里云IOT推送我们构建好的Alink协议数据
159.	
160.	    time.sleep(2) # 睡两秒,因为阿里云有每分钟上发信息次数限制