一個熱愛技術的人必定向往有一個科技感十足的環境吧,那何不親自實踐一下屬於技術人的座右銘:「技術改變世界」。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小時溫溼度數據製做溫溼度報表... 效果預熱: