自己动手实现智能家居之温湿度数据采集存储(DHT11,MySql)

在这里插入代码片

DHT11有三个IO接口,一个VCC(正极)接3.3v,一个GND接GND,剩下一个DATA接树莓派的任意一个GPIO。在设备上有印刷的字体标明了引脚,可以根据指示接到树莓派上。

使用开源类库Adafruit_DHT获取温湿度

读取温度和湿度我们可以使用已经封装好的开源库:Adafruit_DHT

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;
主监控脚本 SmartHomeScreen.py 内容

创建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远程连接到树莓派的终端

PI

通过FTP将我们的项目上传到树莓派服务器

采用后台进程的方式运行我们的主脚本(关闭终端进程不会退出)

nohup python SmartHomeScreen.py

这样我们的信息采集脚本就一直在工作中了,每小时会采集一次温湿度,并存储到数据库表中。

【注意事项】

树莓派中默认安装的python版本是2.7,我们的代码是采用python3编写的,可能有不兼容的情况,需要重新安装python3.6以上版本
我们的GPIO类库是不能在没有GPIO支持的设备上调试的,也就是说在windows本地调试毫无意义,并且安装GPIO的包会出现各种问题,建议直接将代码复制到树莓派调试,无需在本地调试
亚马逊测评 www.yisuping.com

发布了0 篇原创文章 · 获赞 7 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/ting2909/article/details/102455358