/
app.py
98 lines (77 loc) · 3.07 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
from configparser import RawConfigParser
from rethinkdb import r
import RPi.GPIO as GPIO
import mariadb
import time
import datetime
import traceback
import smtplib
config = RawConfigParser()
config.read('appconfig.ini')
mdb_connection = mariadb.connect(
user=config.get('mariadb', 'user'),
password=config.get('mariadb', 'password'),
database=config.get('mariadb', 'database'),
host=config.get('mariadb', 'host'),
)
mdb_cursor = mdb_connection.cursor()
r.connect(config.get('rethinkdb', 'host'), config.get('rethinkdb', 'port')).repl()
gmail_user = config.get('gmail', 'user')
gmail_password = config.get('gmail', 'password')
sent_from = gmail_user
to = [config.get('gmail', 'to')]
subject = 'Miscare neautorizata detectata'
fmt = '%Y-%m-%d %H:%M:%S'
last_update = datetime.datetime.strptime(datetime.datetime.now().strftime(fmt), fmt)
GPIO.setmode(GPIO.BCM)
MOTION_SENSOR_PIN = 4
BUZZ_PIN = 26
LED_RED_PIN = 12
LED_YELLOW_PIN = 16
LED_GREEN_PIN = 20
GPIO.setup(MOTION_SENSOR_PIN, GPIO.IN)
GPIO.setup(BUZZ_PIN, GPIO.OUT) # BUzzer
GPIO.setup(LED_RED_PIN, GPIO.OUT) # RED LED
GPIO.setup(LED_GREEN_PIN, GPIO.OUT) # GREEN LED
GPIO.setup(LED_YELLOW_PIN, GPIO.OUT) # YELLOW LED
GPIO.output(LED_YELLOW_PIN, GPIO.HIGH)
GPIO.output(LED_RED_PIN, GPIO.LOW)
GPIO.output(LED_GREEN_PIN, GPIO.LOW)
try:
time.sleep(2)
while True:
if GPIO.input(MOTION_SENSOR_PIN):
log_time = datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S")
r.db('rpi').table(config.get('rethinkdb', 'motion_table')).insert({
'room_id': 'bedroom_1',
'date': log_time
}).run()
mdb_cursor.execute("SELECT value as state_value FROM location_stats WHERE name = 'state' ")
# print content
row = mdb_cursor.fetchone()
log_time = datetime.datetime.strptime(datetime.datetime.now().strftime(fmt), fmt)
timeDiff = (log_time - last_update).seconds
if row[0] == '1':
if timeDiff > 60:
body = f"Miscare neautorizata la {log_time}"
email_text = f'From: {sent_from} \n To: {", ".join(to)} \n Subject: {subject} \n \n {body}'
print(email_text)
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
server.login(gmail_user, gmail_password)
server.sendmail(sent_from, to, email_text)
server.close()
last_update = datetime.datetime.strptime(datetime.datetime.now().strftime(fmt), fmt)
GPIO.output(LED_RED_PIN, GPIO.HIGH)
# GPIO.output(BUZZ_PIN, GPIO.HIGH)
else:
GPIO.output(LED_GREEN_PIN, GPIO.HIGH)
time.sleep(2) # to avoid multiple detection
GPIO.output(LED_RED_PIN, GPIO.LOW)
GPIO.output(LED_GREEN_PIN, GPIO.LOW)
GPIO.output(BUZZ_PIN, GPIO.LOW)
time.sleep(0.1) # loop delay, should be less than detection delay
except Exception as e:
print (e)
traceback.print_exc()
GPIO.cleanup()