部分图片
功能介绍
材料
1.树莓派
2.温湿度传感器,土壤湿度传感器,红外循迹传感器,步进电机,直流电机,光电门,水泵,AD/DA转换模块,舵机。
智能门禁模块
1.实时监控门口情况。
2.人脸识别开门,若为主人则开门,若为陌生人则发送邮件通知主人并且发送陌生人邮件。
通过调用百度api实现人脸识别
####1.1
创建应用。创建完毕后,下载SDK文档,因为是在树莓派中运行,所以选中python HTTP SDK下载到本地。在人脸库管理中新建用户组,再从用户组中新建人脸id和照片;
####1.2
项目部署.
sdk传输至树莓派上
把下载好的SDK压缩包解压,可以通过ftp或者smb的方式,把文件传输到到树莓派你想放的目录下,然后cd进入该目录;
安装pip以及setuptools
wget https://files.pythonhosted.org/packages/45/ae/8a0ad77defb7cc903f09e551d88b443304a9bd6e6f124e75c0fbbf6de8f7/pip-18.1.tar.gz
tar zxvf pip-18.0.tar.gz
cd ../pip-18.0/
sudo python setup.py install
安装pip
wget https://files.pythonhosted.org/packages/37/1b/b25507861991beeade31473868463dad0e58b1978c209de27384ae541b0b/setuptools-40.6.3.zip
unzip setuptools-40.6.3.zip
cd setuptools-40.6.3
sudo python setup.py build
sudo python setup.py install
安装人脸识别SDK
pip install baidu-aip
python setup.py install
####1.3
代码部分
from aip import AipFace
from picamera import PiCamera
import urllib.request
import RPi.GPIO as GPIO
import base64
import time
#百度人脸识别API账号信息
APP_ID = '18333248'
API_KEY = 'HrfpWmTASGVQTGQ2UQO29IGY'
SECRET_KEY ='7x8m9vuKWH5XeVV8GeLkly8OkqUpzfPz'
client = AipFace(APP_ID, API_KEY, SECRET_KEY)#创建一个客户端用以访问百度云
#图像编码方式
IMAGE_TYPE='BASE64'
camera = PiCamera()#定义一个摄像头对象
#用户组
GROUP = 'yusheng01'
#照相函数
def getimage():
camera.resolution = (1024,768)#摄像界面为1024*768
camera.start_preview()#开始摄像
time.sleep(2)
camera.capture('faceimage.jpg')#拍照并保存
time.sleep(2)
#对图片的格式进行转换
def transimage():
f = open('faceimage.jpg','rb')
img = base64.b64encode(f.read())
return img
#上传到百度api进行人脸检测
def go_api(image):
result = client.search(str(image, 'utf-8'), IMAGE_TYPE, GROUP);#在百度云人脸库中寻找有没有匹配的人脸
if result['error_msg'] == 'SUCCESS':#如果成功了
name = result['result']['user_list'][0]['user_id']#获取名字
score = result['result']['user_list'][0]['score']#获取相似度
if score > 80:#如果相似度大于80
if name == 'yusheng_02':
print("欢迎%s !" % name)
time.sleep(3)
if name == 'xiaoming':
print("欢迎%s !" % name)
time.sleep(3)
if name == "xiaoyu":
print("欢迎%s !" % name)
else:
print("对不起,我不认识你!")
name = 'Unknow'
return 0
curren_time = time.asctime(time.localtime(time.time()))#获取当前时间
#将人员出入的记录保存到Log.txt中
f = open('Log.txt','a')
f.write("Person: " + name + " " + "Time:" + str(curren_time)+'\n')
f.close()
return 1
if result['error_msg'] == 'pic not has face':
print('检测不到人脸')
time.sleep(2)
return 0
else:
print(result['error_code']+' ' + result['error_code'])
return 0
#主函数
if __name__ == '__main__':
while True:
print('准备')
if True:
getimage()#拍照
img = transimage()#转换照片格式
res = go_api(img)#将转换了格式的图片上传到百度云
if(res == 1):#是人脸库中的人
print("开门")
else:
print("关门")
print('稍等三秒进入下一个')
time.sleep(3)
邮件发送
import smtplib
from email.header import Header # 用来设置邮件头和邮件主题
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText # 发送正文只包含简单文本的邮件,引入MIMEText即可
from email.mime.image import MIMEImage
from datetime import datetime
def send_email(sender_email, reciver_email, authorization_code, smtp_server, email_title, email_body):
# message = MIMEText(email_body, 'plain', 'utf-8') # 邮件正文,'plain'表示纯文本,'utf-8'保证多语言兼容性
message = MIMEMultipart('related')
message['From'] = sender_email # 邮件上显示的发件人
message['To'] = reciver_email # 邮件上显示的收件人
message['Subject'] = Header(email_title, 'utf-8') # 邮件主题
att = MIMEText(open('/home/pi/SDK/faceimage.jpg', 'rb').read(), 'base64', 'utf-8')
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment; filename="PeopleInHouse.jpg"'
message.attach(att)
try:
smtp = smtplib.SMTP() # 创建一个连接
smtp.connect(smtp_server) # 连接发送邮件的服务器
smtp.login(sender_email, authorization_code) # 登录服务器
smtp.sendmail(sender_email, reciver_email, message.as_string()) # 填入邮件的相关信息并发送
print("邮件发送成功!!!")
smtp.quit()
except smtplib.SMTPException:
print("邮件发送失败!!!")
Now_Time = str(datetime.now()).split(" ")[1]
Hour = Now_Time.split(":")[0]
Minute = Now_Time.split(":")[1]
Second = Now_Time.split(":")[2].split(".")[0]
title = "!有人于" + Hour + "时" + Minute + "分" + Second + "秒拜访家中"
body = "提醒!有人于" + Hour + "时" + Minute + "分" + Second + "秒拜访家中"
sender_email = '2806630776@qq.com'
reciver_email = '2806630776@qq.com'
code = 'kzscdwglsrrqdged'
server_name = 'smtp.qq.com'
#主函数
if __name__ == '__main__':
while True:
print('准备')
if True:
getimage()#拍照
img = transimage()#转换照片格式
res = go_api(img)#将转换了格式的图片上传到百度云
if(res == 1):#是人脸库中的人
print("开门")
else:
print("关门")
send_email(sender_email, reciver_email, authorization_code, smtp_server, email_title, email_body)
print('稍等三秒进入下一个')
time.sleep(3)
实时监控
参考:实时监控配置
温度烟雾监控模块
温度过高自动开启降温风扇
烟雾浓度过高报警
class tempSensor:
__t = 0
__pin = -1
__sensor = None
PATH = '/sys/bus/w1/devices/28-3c01f096176d/w1_slave'
def __init__(self, pin):
self.__pin = pin
def readRaw(self):
f = open(self.PATH, 'r')
lines = f.readlines()
f.close()
return lines
def readT(self):
lines = self.readRaw()
try:
while lines[0].strip()[-3:] != 'YES':
sleep(0.2)
lines = self.readRaw()
except IndexError:
print('index error, try later')
pass
try:
equals_pos = lines[1].find('t=')
if equals_pos != -1:
temp_string = lines[1][equals_pos + 2:]
temp_c = float(temp_string) / 1000.0
else:
temp_c = 404
return temp_c
except IndexError:
print('index error, try later')
return 404
def getT(self):
self.__t = self.readT()
return self.__t
class buzzer:
__pin = -1
__freq = 0.0
def __init__(self, pin, freq):
self.__pin = pin
gpio.setup(self.__pin, gpio.OUT)
gpio.output(self.__pin, gpio.HIGH)
self.__freq = freq
def play(self):
n = time.time()
while time.time() - n <= 60: # 响60sec
gpio.output(self.__pin, gpio.LOW)
sleep(1.0 / self.__freq)
gpio.output(self.__pin, gpio.HIGH)
sleep(1.0 / self.__freq)
智能窗帘模块
当光照度达到预设值时,自动开启窗帘。
class lightSensor:
__bus = None
def __init__(self):
self.__bus = smbus.SMBus(1)
self.__bus.write_byte(DEV_ADDR, CMD_PWR_ON)
self.__bus.write_byte(DEV_ADDR, CMD_RESET)
self.__bus.write_byte(DEV_ADDR, CMD_SEN100H)
self.__bus.write_byte(DEV_ADDR, CMD_SEN100L)
self.__bus.write_byte(DEV_ADDR, CMD_PWR_OFF)
def read(self):
self.__bus.write_byte(DEV_ADDR, CMD_PWR_ON)
self.__bus.write_byte(DEV_ADDR, CMD_THRES2)
sleep(0.2)
res = self.__bus.read_word_data(DEV_ADDR, 0)
# read_word_data
res = ((res >> 8) & 0xff) | (res << 8) & 0xff00
res = round(res / (2 * 1.2), 2)
return res
class stepMotor:
__pinA = -1
__pinB = -1
__pinC = -1
__pinD = -1
__step = 0
__state = 1 # 0,1分别表示当前窗帘的关闭/开启状态
def __init__(self, a, b, c, d):
self.__pinA = a
self.__pinB = b
self.__pinC = c
self.__pinD = d
gpio.setup(self.__pinA, gpio.OUT)
gpio.setup(self.__pinB, gpio.OUT)
gpio.setup(self.__pinC, gpio.OUT)
gpio.setup(self.__pinD, gpio.OUT)
def __setStep__(self, a, b, c, d):
gpio.output(self.__pinA, a)
gpio.output(self.__pinB, b)
gpio.output(self.__pinC, c)
gpio.output(self.__pinD, d)
def stop(self):
gpio.output(self.__pinA, gpio.LOW)
gpio.output(self.__pinB, gpio.LOW)
gpio.output(self.__pinC, gpio.LOW)
gpio.output(self.__pinD, gpio.LOW)
def forward(self, delay, steps):
for i in range(steps):
self.__setStep__(1, 0, 1, 0)
sleep(delay)
self.__setStep__(0, 1, 1, 0)
sleep(delay)
self.__setStep__(0, 1, 0, 1)
sleep(delay)
self.__setStep__(1, 0, 0, 1)
sleep(delay)
def backward(self, delay, steps):
for i in range(steps):
self.__setStep__(0, 1, 0, 1)
sleep(delay)
self.__setStep__(0, 1, 1, 0)
sleep(delay)
self.__setStep__(1, 0, 1, 0)
sleep(delay)
self.__setStep__(1, 0, 0, 1)
sleep(delay)
def open(self):
if self.__state == 0:
self.backward(0.008, 270)
self.stop()
self.__state = 1
else:
pass
def close(self):
if self.__state == 1:
self.forward(0.008, 270)
self.stop()
self.__state = 0
else:
pass
智能水龙头模块
红外控制水龙头
class infraredSensor:
__pin = -1
__times = 0
__timeStamp = 0
def __init__(self, pin):
self.__pin = pin
gpio.setup(self.__pin, gpio.IN)
self.__timeStamp = time.time()
def read(self):
return gpio.input(self.__pin)
def increase(self):
if (time.time() - self.__timeStamp) > 60 * 60 * 24: # 每24小时更新一次水龙头开启次数
self.__times = 0
self.__timeStamp = time.time()
else:
self.__times += 1
def getTimes(self):
return self.__times
class water:
__pin = -1
def __init__(self, pin):
self.__pin = pin
gpio.setup(self.__pin, gpio.OUT)
gpio.output(self.__pin, gpio.LOW)
def play(self):
gpio.output(self.__pin, gpio.HIGH)
sleep(5)
gpio.output(self.__pin, gpio.LOW)
土壤湿度模块
光电门模块
当有人通过时,可以判断人员进入或者出去
微信小程序
巴法云平台