-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
237 lines (197 loc) · 6.56 KB
/
main.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
#!/usr/bin/env python
import os
import sys
import time
import json
import socket
import requests
import ConfigParser
import RPi.GPIO as GPIO
from datetime import datetime
from pubnub import Pubnub
from cloudant.account import Cloudant
from cloudant.database import CloudantDatabase
config = ConfigParser.ConfigParser()
config.read('config.ini')
# connect to cloudant
db_name = config.get('Cloudant', 'db_name')
db_username = config.get('Cloudant', 'username')
db_api_key = config.get('Cloudant', 'api_key')
db_api_pass = config.get('Cloudant', 'api_pass')
client = Cloudant(db_api_key, db_api_pass,
url='https://'+db_username+'.cloudant.com')
# Pubnub setup
publish_key = config.get('Pubnub', 'publish_key')
subscribe_key = config.get('Pubnub', 'subscribe_key')
pubnub_channel_pi = config.get('Pubnub', 'channel_pi')
pubnub_channel_client = config.get('Pubnub', 'channel_client')
pubnub = Pubnub(publish_key=publish_key, subscribe_key=subscribe_key)
# GPIO setup
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
PIR_PIN = 18 # for sensors
GPIO.setup(PIR_PIN, GPIO.IN) #
GREEN_LED = 13 # for the LEDs
RED_LED = 26 # green : indicates that the system is running
GPIO.setup(GREEN_LED, GPIO.OUT) # red : indicates alert
GPIO.setup(RED_LED, GPIO.OUT) #
# Global state vars
system_paused = False
email_notification = True
def callback(resp, channel):
try:
if (resp['type'] == 'control_request'):
print('Pubnub: callback')
control(resp['option'])
except:
pass
finally:
pass
def error(message):
print('Pubnub: ERROR : ' + str(message))
def connect(message):
print('Pubnub: connected')
def reconnect(message):
print('Pubnub: reconnected')
def disconnect(message):
print('Pubnub: disconnected')
def prettify_time(timestamp):
format = '%Y-%m-%dT%H:%M:%S'
return datetime.fromtimestamp(timestamp).strftime(format)
def upload(t_pretty, filename, manual=False):
print('Uploading to db...')
# compute the pk for this new entry
db = CloudantDatabase(client, db_name)
resp = db.get_view_raw_result('_design/view', 'log', reduce=True)
if not resp['rows']:
pk = 1
else:
pk = resp['rows'][0]['value']
pk += 1
docid = 'log:' + str(pk)
data = {
'_id' : docid,
'pk' : pk,
'timestamp': t_pretty,
'filename' : filename,
'manual' : manual
}
new_document = client[db_name].create_document(data)
fp = open('img/'+filename, 'rb')
data = fp.read()
fp.close()
new_document.put_attachment(filename, 'image/jpeg', data)
if new_document.exists():
print('Upload success!')
# send live feed to webpage
payload = {'type': 'doc', 'doc': new_document}
pubnub.publish(pubnub_channel_pi, payload)
return docid
print('Failed to upload image.')
return False
def send_email(t_pretty, filename, docid):
print('Sending email...')
payload = {
'option' : 'email',
'timestamp' : t_pretty,
'secret_key' : config.get('Secret', 'key'),
'email' : config.get('Email', 'email'),
'filename' : filename,
'url_image' : docid + '/' + filename,
'img_type' : 'image/jpeg',
'url_webpage': config.get('API', 'control_webpage'),
}
url = config.get('API', 'email')
r = requests.post(url, payload)
print(r.text)
def say_cheese(timestamp):
format = '%Y-%m-%dT%H-%M-%S'
filename = datetime.fromtimestamp(timestamp).strftime(format)
filename = filename + '.jpg'
camera_resolution = config.get('Camera', 'resolution')
command = 'fswebcam -r %s %s' % (camera_resolution, 'img/'+filename)
os.system(command)
return filename
def alert(PIR_PIN):
global system_paused, email_notification
if system_paused:
return True
# red led ON
GPIO.output(RED_LED, True)
print('\r\n!!!!! Intruder Alert !!!!!\r\n')
t = time.time()
t_pretty = prettify_time(t)
filename = say_cheese(t)
docid = upload(t_pretty, filename)
if (email_notification):
send_email(t_pretty, filename, docid)
# red led OFF
GPIO.output(RED_LED, False)
return True
def control(option):
global system_paused, email_notification
print('Pubnub control option: ' + option)
t = time.time()
t_pretty = prettify_time(t)
msg = ''
if option == 'take_pic':
if (upload(t_pretty, say_cheese(t), True)):
msg = 'Picture taken!'
elif option == 'pause':
system_paused = True
msg = 'System paused.'
elif option == 'resume':
system_paused = False
msg = 'Resuming system.'
elif option == 'email_on':
email_notification = True
msg = 'Email notification turned on.'
elif option == 'email_off':
email_notification = False
msg = 'Email notification off.'
elif option == 'ping':
msg = 'Pong!'
msg = msg + (' [System: paused]' if system_paused else '')
msg = msg + ' [Email notification: ' + \
('on' if email_notification else 'off') + ']'
else:
msg = 'Unknown remote control option.'
print(msg)
# publish the response object
pubnub.publish(pubnub_channel_pi, {'type': 'control_resp', 'msg': msg})
print('publish complete')
def has_internet():
remote_server = 'www.google.com'
try:
host = socket.gethostbyname(remote_server)
s = socket.create_connection((host, 80), 2)
return True
except:
pass
return False
if __name__ == '__main__':
# ensure we have internet connection
# mark every 10 minutes
startup_time = time.time()
while not has_internet():
elapsed = time.time() - startup_time
if elapsed % 600 == 0:
print '%s mins without internet connection...' % (elapsed/60)
# connect to cloudant client
client.connect()
# subscribe to client channel
pubnub.subscribe(channels=pubnub_channel_client, callback=callback, error=callback,
connect=connect, reconnect=reconnect, disconnect=disconnect)
# ensure red led is off
GPIO.output(RED_LED, False)
try:
print('Booting system...')
GPIO.add_event_detect(PIR_PIN, GPIO.RISING, callback=alert)
# indicate the system is ready
GPIO.output(GREEN_LED, True)
while True:
time.sleep(100)
finally:
print('Shutting down...')
pubnub.unsubscribe(channel=pubnub_channel_client)
GPIO.cleanup()