一个热爱技术的人必定向往有一个科技感十足的环境吧,那何不亲自实践一下属于技术人的座右铭:“技术改变世界”。html
就让咱们一步步动手搭建一个属于本身的“智能家居平台”吧(不要对这个名词抬杠啦,技术在手,怎么设计实现因人而异),本文只作抛砖引玉,各路大神若是有更好的想法能够各显神通,固然能在评论区留下更好的想法让你们共同窗习是再好不过啦。python
在文章最后附有全部源代码,有须要的能够自行下载,感谢Star~mysql
上一节咱们介绍了树莓派以及树莓派的GPIO的简单使用,这一节基于上一节的知识点采集屋内的温度和湿度数据,而且构建python脚本将采集到的数据写入到mysql数据库持久化。git
效果图:
github
那么接下来咱们就一步步讲解这个折腾的过程...sql
”某宝“购买一个DHT11模块,大概¥6,为了方便线路灵活链接,咱们购买了面包板和杜邦线若干。shell
硬件采购完毕,咱们开始搞软件部分~~~数据库
DHT11有三个IO接口,一个VCC(正极)接3.3v,一个GND接GND,剩下一个DATA接树莓派的任意一个GPIO。在设备上有印刷的字体标明了引脚,能够根据指示接到树莓派上。ubuntu
读取温度和湿度咱们可使用已经封装好的开源库:Adafruit_DHTwindows
import Adafruit_DHT # Use read_retry method. This will retry up to 15 times to # get a sensor reading (waiting 2 seconds between each retry). # this is bcm code humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.DHT11, 4)
为了便于咱们读写MySql,咱们须要一个 MySqlHelper.py,内容以下:
# coding=utf-8 import pymysql from Utility.Configs import Cfg_MySql class MySqlHelper: conn = None def __init__(self, db): cfg_mysql = Cfg_MySql() self.conn = pymysql.connect(host=cfg_mysql.get('host'), port=int(cfg_mysql.get('port')), user=cfg_mysql.get('user'), passwd=cfg_mysql.get('passwd'), db=db) def getConnAndCur(self): return self.conn,self.conn.cursor() def executeSql(self,sql): conn,cur = self.getConnAndCur() cur.execute(sql) conn.commit() cur.close() conn.close() # 用完记得释放 # cur.close() # conn.close()
mysql的链接信息是经过ini配置文件存储的,咱们还须要一个 Configs.py 读写配置文件,内容以下:
# coding=utf-8 import configparser # 树莓派的ubuntu系统里面若是要使用计划任务,则必须写成绝对路径,意味着这里须要加前缀 # RASPBERRY_PI_PATH = '/7tniy/SevenTiny.SmartHome' # Windows调试不须要加绝对路径 RASPBERRY_PI_PATH_ROOT = '' # get configuration config = configparser.ConfigParser() config.read(RASPBERRY_PI_PATH_ROOT + 'SmartHome.ini',encoding='UTF-8') class Cfg_MySql: __tag = 'MySql' def __init__(self): pass def get(self, name): return config.get(self.__tag, name)
咱们的配置文件 SmartHome.ini 放在项目根目录便可。内容以下:
[MySql] connectionstring = 1 host = 192.168.0.1 port = 3306 user = prod passwd = 123456xxx
数据库表结构:
/* Navicat MySQL Data Transfer Source Server : Source Server Version : 50644 Source Host : Source Database : SmartHome Target Server Type : MYSQL Target Server Version : 50644 File Encoding : 65001 Date: 2019-10-08 21:38:09 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for DailyMonitor -- ---------------------------- DROP TABLE IF EXISTS `DailyMonitor`; CREATE TABLE `DailyMonitor` ( `Id` int(11) NOT NULL AUTO_INCREMENT, `DateTime` datetime NOT NULL ON UPDATE CURRENT_TIMESTAMP, `Year` int(11) DEFAULT NULL, `Month` int(11) DEFAULT NULL, `Day` int(11) DEFAULT NULL, `Hour` int(11) DEFAULT NULL, `Temperature` double(255,0) DEFAULT NULL, `Humidity` double(255,0) DEFAULT NULL, PRIMARY KEY (`Id`) ) ENGINE=InnoDB AUTO_INCREMENT=1211 DEFAULT CHARSET=utf8;
- 建立mysql链接
- 经过DHT11获取温湿度
- 将数据异步写入MySql(每小时一次)
# coding=utf-8 from Utility.MySqlHelper import MySqlHelper import _thread import Adafruit_DHT import time import datetime import RPi.GPIO as GPIO import sys sys.path.append('..') def WriteToDb(timenow, year, month, day, hour, temp, humi): smartHomeDb = MySqlHelper("SmartHome") smartHomeDb.executeSql("INSERT INTO DailyMonitor (DateTime,Year,Month,Day,Hour,Temperature,Humidity) VALUES ('{0}',{1},{2},{3},{4},{5},{6})".format( timenow, year, month, day, hour, temp, humi)) # 已经写入数据库的小时标识,插入数据的同时,修改成下一个小时,用于比较是否须要写入 hasWriteToDbHour = datetime.datetime.now().hour while(True): # time timenow = datetime.datetime.now() # Use read_retry method. This will retry up to 15 times to # get a sensor reading (waiting 2 seconds between each retry). # this is bcm code humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.DHT11, 4) print('time:{0},humidity:{1}%,temperature:{2}*C'.format( datetime.datetime.now(), humidity, temperature)) # 异步将数据写入mysql if hasWriteToDbHour == timenow.hour: _thread.start_new_thread(WriteToDb, (timenow, timenow.year, timenow.month, timenow.day, timenow.hour, temperature, humidity)) if hasWriteToDbHour == 23: hasWriteToDbHour = 0 else: hasWriteToDbHour = hasWriteToDbHour + 1 time.sleep(2)
咱们经过SSH远程链接到树莓派的终端
经过FTP将咱们的项目上传到树莓派服务器
采用后台进程的方式运行咱们的主脚本(关闭终端进程不会退出)
nohup python SmartHomeScreen.py
这样咱们的信息采集脚本就一直在工做中了,每小时会采集一次温湿度,并存储到数据库表中。
经过本节内容,咱们实现了利用树莓派的GPIO和DHT11温湿度采集模块24小时实时采集环境中的温湿度,而且持久化到了MySql中,做为咱们后续监控面板和监控报表的基础数据。
后续章节咱们会介绍利用咱们采集的24小时温湿度数据制做温湿度报表... 效果预热: