· 6 years ago · Aug 21, 2019, 11:06 PM
1dynamodb.py
2-------------------------------------
3def get_data_from_dynamodb():
4 try:
5 import boto3
6 from boto3.dynamodb.conditions import Key, Attr
7
8 dynamodb = boto3.resource('dynamodb',
9 aws_access_key_id="ASIAXOQPA3DLULG4BVZ5",
10 aws_secret_access_key="48ZgE+fUDijpvw0Usuyl8K54uxBv3HiZyviF8oRR",
11 aws_session_token="FQoGZXIvYXdzED8aDHinLtWBqeUaBHtdzCKTAruxB5zxJ79rRcpajNrBf1C8QlwXjAcDSLzvwdYX7B7noXjD+5Vkzklev5mQJabNzrxUVGAAUDZtlOfaDj0QmenYBnvxwnyyHhSZQDJyWUI645rGtYb5k9gOcP12hDSD5yC9wSDN3mrBnqbvPFsTxVbYPKGaHyGwUogbURhiVP04TIUQHXZ4tO02KNEOwBJgpl/mpKzGsSKOR/csl0q6fEplzT14RkrsSxsM09BzNydplEYMw7kT64GfbsQpf9VR1gsGT5kGKu3n9lCc3+k1+RZkSnGrUShVoiRyj9WxeK5cSt48q8xdVZNsYnilwfPA4fWeab9OLUGvg0jwwi+pp/eMywRMlHaqj2IYGdmsIvGnbqgWKMj29uoF",
12 region_name='us-east-1')
13 table = dynamodb.Table('iotdata')
14
15 startdate = '2019-08'
16
17 response = table.query(
18 KeyConditionExpression=Key('deviceid').eq('deviceid_chris')
19 & Key('datetimeid').begins_with(startdate),
20 ScanIndexForward=False
21 )
22
23 items = response['Items']
24
25 n=10 # limit to last 10 items
26 data = items[:n]
27 data_reversed = data[::-1]
28
29 return data_reversed
30
31 except:
32 import sys
33 print(sys.exc_info()[0])
34 print(sys.exc_info()[1])
35
36
37if __name__ == "__main__":
38 get_data_from_dynamodb()
39
40
41
42jsonconverter.py
43--------------------------------------------------------------
44from decimal import Decimal
45import json
46import datetime
47import numpy
48
49class GenericEncoder(json.JSONEncoder):
50
51 def default(self, obj):
52 if isinstance(obj, numpy.generic):
53 return numpy.asscalar(obj)
54 elif isinstance(obj, Decimal):
55 return str(obj)
56 elif isinstance(obj, datetime.datetime):
57 return obj.strftime('%Y-%m-%d %H:%M:%S')
58 elif isinstance(obj, Decimal):
59 return float(obj)
60 else:
61 return json.JSONEncoder.default(self, obj)
62
63def data_to_json(data):
64 json_data = json.dumps(data,cls=GenericEncoder)
65 print(json_data)
66 return json_data
67
68
69publishHeat.py
70---------------------------------------------------------------------
71# Import SDK packages
72from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
73from time import sleep
74import Adafruit_DHT
75
76pin=4
77host = "a1pem9ilz5vgjc-ats.iot.us-east-1.amazonaws.com"
78rootCAPath = "AmazonRootCA1.pem"
79certificatePath = "75198eb21f-certificate.pem.crt"
80privateKeyPath = "75198eb21f-private.pem.key"
81
82my_rpi = AWSIoTMQTTClient("CPHeatPub")
83my_rpi.configureEndpoint(host, 8883)
84my_rpi.configureCredentials(rootCAPath, privateKeyPath, certificatePath)
85
86my_rpi.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing
87my_rpi.configureDrainingFrequency(2) # Draining: 2 Hz
88my_rpi.configureConnectDisconnectTimeout(10) # 10 sec
89my_rpi.configureMQTTOperationTimeout(5) # 5 sec
90my_rpi.connect()
91
92# Publish to the same topic in a loop forever
93loopCount = 0
94while True:
95 humidity, temperature = Adafruit_DHT.read_retry(11, pin)
96 my_rpi.publish("smartroom/sensor/fire", str(temperature), 0)
97 print(temperature)
98 sleep(3)
99
100
101pubsub.py
102----------------------------------------------------------
103# Import SDK packages
104from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
105from time import sleep
106from gpiozero import MCP3008
107import Adafruit_DHT
108from rpi_lcd import LCD
109lcd = LCD()
110led = LED(18)
111adc = MCP3008(channel=0)
112pin =4
113# Custom MQTT message callback
114def customCallback(client, userdata, message):
115 print("Received a new message: ")
116 print(message.payload)
117 print("from topic: ")
118 print(message.topic)
119 print("--------------\n\n")
120
121host = "axad8ecychu5n-ats.iot.us-east-1.amazonaws.com"
122rootCAPath = "AmazonRootCA1.pem"
123certificatePath = "75198eb21f-certificate.pem.crt"
124privateKeyPath = "75198eb21f-private.pem.key"
125
126
127
128my_rpi = AWSIoTMQTTClient("pubsun170")
129my_rpi.configureEndpoint(host, 8883)
130my_rpi.configureCredentials(rootCAPath, privateKeyPath, certificatePath)
131
132my_rpi.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing
133my_rpi.configureDrainingFrequency(2) # Draining: 2 Hz
134my_rpi.configureConnectDisconnectTimeout(10) # 10 sec
135my_rpi.configureMQTTOperationTimeout(5) # 5 sec
136
137# Connect and subscribe to AWS IoT
138my_rpi.connect()
139my_rpi.subscribe("sensors/light", 1, customCallback)
140sleep(2)
141
142count1 = True
143count2 = True
144def counterp1():
145 global count1
146 global led
147 # count1 = True
148 if count1 == False:
149 led.off()
150 count1 = True
151 print(" led is offed")
152 else:
153 led.on()
154 count1 = False
155 print(" led is on")
156
157
158 # def ledON():
159 # led.on()
160 # print("LED is on")
161
162
163 # def ledOFF():
164 # led.off()
165 # print("LED is off")
166
167
168button.when_pressed = counterp1
169
170# Publish to the same topic in a loop forever
171loopCount = 0
172while True:
173 light = round(1024-(adc.value*1024))
174 humidity, temperature = Adafruit_DHT.read_retry(11, pin)
175 loopCount = loopCount+1
176 message = {}
177 message["deviceid"] = "deviceid_chris"
178 import datetime as datetime
179 now = datetime.datetime.now()
180 message["datetimeid"] = now.isoformat()
181 message["value"] = light
182 message["temp_value"] = temperature
183 message["humid_value"] = humidity
184 import json
185 my_rpi.publish("sensors/light", json.dumps(message), 1)
186 lcd.text('Light Value: {:.4f}'.format(light),1)
187 sleep(2)
188 lcd.text('Humidity: {:.1f}'.format(humidity), 1)
189
190
191 sleep(2)
192
193
194
195
196server.py
197-----------------------------------------------------------------------------------------
198# Import SDK packages
199from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
200from time import sleep
201from gpiozero import MCP3008
202import Adafruit_DHT
203from rpi_lcd import LCD
204lcd = LCD()
205led = LED(18)
206adc = MCP3008(channel=0)
207pin =4
208# Custom MQTT message callback
209def customCallback(client, userdata, message):
210 print("Received a new message: ")
211 print(message.payload)
212 print("from topic: ")
213 print(message.topic)
214 print("--------------\n\n")
215
216host = "axad8ecychu5n-ats.iot.us-east-1.amazonaws.com"
217rootCAPath = "AmazonRootCA1.pem"
218certificatePath = "75198eb21f-certificate.pem.crt"
219privateKeyPath = "75198eb21f-private.pem.key"
220
221
222
223my_rpi = AWSIoTMQTTClient("pubsun170")
224my_rpi.configureEndpoint(host, 8883)
225my_rpi.configureCredentials(rootCAPath, privateKeyPath, certificatePath)
226
227my_rpi.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing
228my_rpi.configureDrainingFrequency(2) # Draining: 2 Hz
229my_rpi.configureConnectDisconnectTimeout(10) # 10 sec
230my_rpi.configureMQTTOperationTimeout(5) # 5 sec
231
232# Connect and subscribe to AWS IoT
233my_rpi.connect()
234my_rpi.subscribe("sensors/light", 1, customCallback)
235sleep(2)
236
237count1 = True
238count2 = True
239def counterp1():
240 global count1
241 global led
242 # count1 = True
243 if count1 == False:
244 led.off()
245 count1 = True
246 print(" led is offed")
247 else:
248 led.on()
249 count1 = False
250 print(" led is on")
251
252
253 # def ledON():
254 # led.on()
255 # print("LED is on")
256
257
258 # def ledOFF():
259 # led.off()
260 # print("LED is off")
261
262
263button.when_pressed = counterp1
264
265# Publish to the same topic in a loop forever
266loopCount = 0
267while True:
268 light = round(1024-(adc.value*1024))
269 humidity, temperature = Adafruit_DHT.read_retry(11, pin)
270 loopCount = loopCount+1
271 message = {}
272 message["deviceid"] = "deviceid_chris"
273 import datetime as datetime
274 now = datetime.datetime.now()
275 message["datetimeid"] = now.isoformat()
276 message["value"] = light
277 message["temp_value"] = temperature
278 message["humid_value"] = humidity
279 import json
280 my_rpi.publish("sensors/light", json.dumps(message), 1)
281 lcd.text('Light Value: {:.4f}'.format(light),1)
282 sleep(2)
283 lcd.text('Humidity: {:.1f}'.format(humidity), 1)
284
285
286 sleep(2)
287
288
289
290telegrambot.py
291----------------------------------------------------------------
292from picamera import PiCamera
293from random import randint
294from time import sleep
295import botocore
296import telepot
297import boto3
298import time
299import os
300from gpiozero import LED
301
302
303led = LED(18)
304my_bot_token = '812916353:AAFbUqga8c0iHmFV9g3SkuYG5KyR4pDkn9k'
305camera = PiCamera()
306timestring = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
307file_name = timestring + '.jpg'
308full_path = '/home/pi/Desktop/' + file_name
309deg = u'\xb0'
310degInString = deg.encode('utf8')
311# Create an S3 resource
312s3 = boto3.resource('s3', aws_access_key_id='ASIAXOQPA3DL7VN3OEOZ', aws_secret_access_key='8IVQIfRUzgnngbWcu5ZOshyIvETU6CtEY0P/c4dX',
313aws_session_token="FQoGZXIvYXdzEDwaDPZNLzJ28fxhpKb7sSLsBHzujdFPJTVJPl6x9jynQ7Yq7PdZ3E5Wh+WFeXGBVtHwDEXPmndmVR3aPLf5cqOxphcvLTYZm3YCRnAiKpAicmPVC77tbxeIkxVsfPbdr2yB50pBRb5khdQegP4GUa3hd68NhtGvxLrLl9Wp4+iVeFLYwyGNQzEv1M20jA9lqE1wwho6/OX0Q11JRA7qAL7/si6+EhZjrtU1eN/x0j8/SH6yDPWf29CkYdTgbki8fJLD8kE4A++GCtzbFA36pFhOvKO0aZ49OfGGGCki6L3q9Aw3MtV3zRDq6vrXF/XwXTGfIt2pGo59K31ZdQ1Om4AVmVyKP98axOxHz1Oz79VZM/EbPhkbOnIY53H6C1ojCRCKpKRFF+KvSjvep8AHwPqwGMEFbYtaZYra928zGB4A012KLhC2QmXYFR7dkheckAb5xk7zRJjavm46aGBwkEoCwFFaxRu6/V2saQuxrnQeRVWlnVQlWqZG0h4bBDvR3+hF+G8lZVRfrMsHR/hdTqIm8FN4C5tBUS+xfCn5vYgGDz6AOFazQxLfmGBgIMAY+nBO6sCzkMQrtDv2+RrD6DvIJrT7m6auVyr2iHy8MNlE4bc137Ky2rDRV16Iqa8PBlzF5x2fcn/b9IDjUxCjpbOioox/4gdtjvbsj0mHdwkKuB9KD4R5B6eUbUXcyBxZzASMGVBxHPYdJgumwY9ftjX/ZFaWmkRbN59l35w9NIG7rCk5xmpGdlWNMTpDvrAId3d73C4YUWbGhIXLMSBwDw86IZK4odC4rXNEEEhyQPO1YAqZamDOZgW4NhTkQZPEtC0VN2UNejDiExtto1vJKNql9uoF")
314bucket_name = 'sp-p1703263-s3-bucket'
315
316def takePicture():
317 camera.capture(full_path)
318
319def uploadPicture():
320 exists = True
321 timestring = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
322 file_name = timestring + '.jpg'
323
324 try:
325 s3.meta.client.head_bucket(Bucket=bucket_name)
326 except botocore.exceptions.ClientError as e:
327 error_code = int(e.response['Error']['Code'])
328 if error_code == 404:
329 exists = False
330
331 if exists == False:
332 s3.create_bucket(Bucket=bucket_name,CreateBucketConfiguration={'LocationConstraint': 'us-west-2'})
333
334 # Upload a new file
335 s3.Object(bucket_name,
336 'home/User/{}'.format(file_name)).put(Body=open(full_path, 'rb'))
337 print("File uploaded")
338
339 os.remove(full_path)
340
341def retrievePicture():
342 try:
343 s3.Bucket(bucket_name).download_file('home/User/{}'.format(file_name),
344 full_path)
345 except botocore.exceptions.ClientError as e:
346 error_code = int(e.response['Error']['Code'])
347 if error_code == 404:
348 print("The object does not exist.")
349
350def onLED():
351 led.on()
352 return "Got it, LED is now turned on..."
353
354def offLED():
355 led.off()
356 return "Got it, LED is now turned off..."
357
358def respondToMsg(msg):
359 chat_id = msg['chat']['id']
360 command = msg['text']
361 print('Got command: {}'.format(command))
362
363 if (command == '/start'):
364 text = 'Welcome to CP House Bot!\nType /help for our available commands'
365 bot.sendMessage(chat_id, text)
366
367 elif (command == '/help'):
368 text = '''Here are our available commands:\n
369 /takepicture - Takes a picture from your RPi
370 /onLED - To on the LED light
371 /offLED - To off the LED light
372 '''
373 bot.sendMessage(chat_id, text)
374 elif (command == '/takepicture'):
375 takePicture()
376 bot.sendPhoto(chat_id, photo=open(full_path, 'rb'))
377 uploadPicture()
378 retrievePicture()
379 #os.remove(full_path)
380 elif (command == '/onLED'):
381 bot.sendMessage(chat_id, onLED())
382 elif (command == '/offLED'):
383 bot.sendMessage(chat_id, offLED())
384 elif ('/' in command):
385 text = command + ' is not recognized.\nType /help for our available commands.'
386 bot.sendMessage(chat_id, text)
387 else:
388 text = ['I do not understand you...', 'Huh?', 'Can you please repeat?', 'What do you mean?']
389 number = randint(0,3)
390 bot.sendMessage(chat_id, text[number])
391
392
393bot = telepot.Bot(my_bot_token)
394bot.message_loop(respondToMsg)
395print('Listening for RPi commands')
396while True:
397 sleep(1)
398
399
400dooraccess.py
401---------------------------------------------------------------------------------
402
403from gpiozero import MCP3008, LED,Button
404import mysql.connector
405from time import sleep
406import sys
407from rpi_lcd import LCD
408import Adafruit_DHT
409from signal import pause
410import gevent
411import gevent.monkey
412import RPi.GPIO as GPIO
413import MFRC522
414import signal
415from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
416
417host = "a1pem9ilz5vgjc-ats.iot.us-east-1.amazonaws.com"
418rootCAPath = "AmazonRootCA1.pem"
419certificatePath = "95e7faaf66-certificate.pem.crt"
420privateKeyPath = "95e7faaf66-private.pem.key"
421
422# my_rpi.configureEndpoint(host, 8883)
423# my_rpi.configureCredentials(rootCAPath, privateKeyPath, certificatePath)
424
425# my_rpi.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing
426# my_rpi.configureDrainingFrequency(2) # Draining: 2 Hz
427# my_rpi.configureConnectDisconnectTimeout(10) # 10 sec
428# my_rpi.configureMQTTOperationTimeout(5) # 5 sec
429# # Connect and subscribe to AWS IoT
430# my_rpi.connect()
431
432uid = None
433prev_uid = None
434continue_reading = True
435
436# Capture SIGINT for cleanup when the script is aborted
437def end_read(signal,frame):
438 global continue_reading
439 print "Ctrl+C captured, ending read."
440 continue_reading = False
441 GPIO.cleanup()
442def retrieveCard():
443 try:
444 import boto3
445 from boto3.dynamodb.conditions import Key, Attr
446
447 dynamodb = boto3.resource('dynamodb', region_name='us-east-1')
448 table = dynamodb.Table('access_door')
449
450 response = table.query(
451 KeyConditionExpression=Key('rfidNo')
452 )
453 item = response['Items']
454 print(item)
455 return item
456
457 except:
458 import sys
459 print(sys.exc_info()[0])
460 print(sys.exc_info()[1])
461
462
463# Hook the SIGINT
464signal.signal(signal.SIGINT, end_read)
465
466# Create an object of the class MFRC522
467mfrc522 = MFRC522.MFRC522()
468
469# Welcome message
470print "Welcome to the MFRC522 data read example"
471print "Press Ctrl-C to stop."
472
473# This loop keeps checking for chips.
474# If one is near it will get the UID
475
476while continue_reading:
477
478 # Scan for cards
479 (status,TagType) = mfrc522.MFRC522_Request(mfrc522.PICC_REQIDL)
480
481 # If a card is found
482 if status == mfrc522.MI_OK:
483 # Get the UID of the card
484 (status,uid) = mfrc522.MFRC522_Anticoll()
485 if uid!=prev_uid:
486 prev_uid = uid
487 print("New card detected! UID of card is {}".format(uid))
488 print(type(uid))
489 retrieveCard()
490
491
492
493
494# try:
495# u='AssignmentCA2';pw='Chris0688';
496# h='10.10.10.137';db='Assignment_Ca2_DB'
497# cnx = mysql.connector.connect(user=u,password=pw,host=h,database=db)
498# cursor = cnx.cursor()
499# print("Successfully connected to database!")
500
501
502# uid = None
503# prev_uid = None
504# continue_reading = True
505
506# # Capture SIGINT for cleanup when the script is aborted
507# def end_read(signal,frame):
508# global continue_reading
509# print "Ctrl+C captured, ending read."
510# continue_reading = False
511# GPIO.cleanup()
512
513# # Hook the SIGINT
514# signal.signal(signal.SIGINT, end_read)
515
516# # Create an object of the class MFRC522
517# mfrc522 = MFRC522.MFRC522()
518
519# # Welcome message
520# print "Welcome to the MFRC522 data read example"
521# print "Press Ctrl-C to stop."
522
523# # This loop keeps checking for chips.
524# # If one is near it will get the UID
525
526# while continue_reading:
527# update = True
528# while update:
529# (status,TagType) = mfrc522.MFRC522_Request(mfrc522.PICC_REQIDL)
530# if status == mfrc522.MI_OK:
531# (status,uid) = mfrc522.MFRC522_Anticoll()
532# if uid!=prev_uid:
533# prev_uid = uid
534# print("New card detected! UID of card is {}".format(uid))
535# authorised = 0
536# sql = "SELECT rfidCardNo FROM accessDoor"
537# cursor.execute(sql)
538# records = cursor.fetchall()
539# for i in records:
540# if i[0] == str(uid):
541# authorised += 1
542# else:
543# authorised += 0
544# if authorised == 1:
545# print("ACCESS ALLOWED")
546# else:
547# print("UNAUTHORISED ACCESS!")
548# except:
549# print(sys.exc_info()[0])
550# print(sys.exc_info()[1])
551
552
553
554heatdetector.py
555-------------------------------------------------------------------
556# Import SDK packages
557from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
558from time import sleep
559import Adafruit_DHT
560from gpiozero import MCP3008, LED,Button,Buzzer
561import nexmo
562
563msgSender = nexmo.Client(key='91beec10', secret='kIAAc2GWl77JT1Zr')
564
565bz = Buzzer(5)
566
567host = "a1pem9ilz5vgjc-ats.iot.us-east-1.amazonaws.com"
568rootCAPath = "AmazonRootCA1.pem"
569certificatePath = "75198eb21f-certificate.pem.crt"
570privateKeyPath = "75198eb21f-private.pem.key"
571
572my_rpi = AWSIoTMQTTClient("firedetecter")
573my_rpi.configureEndpoint(host, 8883)
574my_rpi.configureCredentials(rootCAPath, privateKeyPath, certificatePath)
575
576my_rpi.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing
577my_rpi.configureDrainingFrequency(2) # Draining: 2 Hz
578my_rpi.configureConnectDisconnectTimeout(10) # 10 sec
579my_rpi.configureMQTTOperationTimeout(5) # 5 sec
580# Connect and subscribe to AWS IoT
581my_rpi.connect()
582loopCount = 0
583
584led = LED(18)
585#LED On off commands
586def ledON():
587 led.on()
588 print("LED is on")
589
590
591def ledOFF():
592 led.off()
593 print("LED is off")
594
595# Custom MQTT message callback
596def customCallback(client, userdata, message):
597 print(message.payload.decode('UTF-8'))
598 if float(message.payload.decode('UTF-8')) > 25:
599 ledON()
600 bz.on()
601 msgSender.send_message({
602 'from': 'Nexmo',
603 'to': '6596551876',
604 'text': 'Potential fire !!!!!',
605 })
606 else:
607 ledOFF()
608 bz.off()
609my_rpi.subscribe("smartroom/sensor/fire", 1, customCallback)
610sleep(2)
611
612while True:
613 loopCount = loopCount + 1