Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- dynamodb.py
- -------------------------------------
- def get_data_from_dynamodb():
- try:
- import boto3
- from boto3.dynamodb.conditions import Key, Attr
- dynamodb = boto3.resource('dynamodb',
- aws_access_key_id="ASIAXOQPA3DLULG4BVZ5",
- aws_secret_access_key="48ZgE+fUDijpvw0Usuyl8K54uxBv3HiZyviF8oRR",
- aws_session_token="FQoGZXIvYXdzED8aDHinLtWBqeUaBHtdzCKTAruxB5zxJ79rRcpajNrBf1C8QlwXjAcDSLzvwdYX7B7noXjD+5Vkzklev5mQJabNzrxUVGAAUDZtlOfaDj0QmenYBnvxwnyyHhSZQDJyWUI645rGtYb5k9gOcP12hDSD5yC9wSDN3mrBnqbvPFsTxVbYPKGaHyGwUogbURhiVP04TIUQHXZ4tO02KNEOwBJgpl/mpKzGsSKOR/csl0q6fEplzT14RkrsSxsM09BzNydplEYMw7kT64GfbsQpf9VR1gsGT5kGKu3n9lCc3+k1+RZkSnGrUShVoiRyj9WxeK5cSt48q8xdVZNsYnilwfPA4fWeab9OLUGvg0jwwi+pp/eMywRMlHaqj2IYGdmsIvGnbqgWKMj29uoF",
- region_name='us-east-1')
- table = dynamodb.Table('iotdata')
- startdate = '2019-08'
- response = table.query(
- KeyConditionExpression=Key('deviceid').eq('deviceid_chris')
- & Key('datetimeid').begins_with(startdate),
- ScanIndexForward=False
- )
- items = response['Items']
- n=10 # limit to last 10 items
- data = items[:n]
- data_reversed = data[::-1]
- return data_reversed
- except:
- import sys
- print(sys.exc_info()[0])
- print(sys.exc_info()[1])
- if __name__ == "__main__":
- get_data_from_dynamodb()
- jsonconverter.py
- --------------------------------------------------------------
- from decimal import Decimal
- import json
- import datetime
- import numpy
- class GenericEncoder(json.JSONEncoder):
- def default(self, obj):
- if isinstance(obj, numpy.generic):
- return numpy.asscalar(obj)
- elif isinstance(obj, Decimal):
- return str(obj)
- elif isinstance(obj, datetime.datetime):
- return obj.strftime('%Y-%m-%d %H:%M:%S')
- elif isinstance(obj, Decimal):
- return float(obj)
- else:
- return json.JSONEncoder.default(self, obj)
- def data_to_json(data):
- json_data = json.dumps(data,cls=GenericEncoder)
- print(json_data)
- return json_data
- publishHeat.py
- ---------------------------------------------------------------------
- # Import SDK packages
- from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
- from time import sleep
- import Adafruit_DHT
- pin=4
- host = "a1pem9ilz5vgjc-ats.iot.us-east-1.amazonaws.com"
- rootCAPath = "AmazonRootCA1.pem"
- certificatePath = "75198eb21f-certificate.pem.crt"
- privateKeyPath = "75198eb21f-private.pem.key"
- my_rpi = AWSIoTMQTTClient("CPHeatPub")
- my_rpi.configureEndpoint(host, 8883)
- my_rpi.configureCredentials(rootCAPath, privateKeyPath, certificatePath)
- my_rpi.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing
- my_rpi.configureDrainingFrequency(2) # Draining: 2 Hz
- my_rpi.configureConnectDisconnectTimeout(10) # 10 sec
- my_rpi.configureMQTTOperationTimeout(5) # 5 sec
- my_rpi.connect()
- # Publish to the same topic in a loop forever
- loopCount = 0
- while True:
- humidity, temperature = Adafruit_DHT.read_retry(11, pin)
- my_rpi.publish("smartroom/sensor/fire", str(temperature), 0)
- print(temperature)
- sleep(3)
- pubsub.py
- ----------------------------------------------------------
- # Import SDK packages
- from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
- from time import sleep
- from gpiozero import MCP3008
- import Adafruit_DHT
- from rpi_lcd import LCD
- lcd = LCD()
- led = LED(18)
- adc = MCP3008(channel=0)
- pin =4
- # Custom MQTT message callback
- def customCallback(client, userdata, message):
- print("Received a new message: ")
- print(message.payload)
- print("from topic: ")
- print(message.topic)
- print("--------------\n\n")
- host = "axad8ecychu5n-ats.iot.us-east-1.amazonaws.com"
- rootCAPath = "AmazonRootCA1.pem"
- certificatePath = "75198eb21f-certificate.pem.crt"
- privateKeyPath = "75198eb21f-private.pem.key"
- my_rpi = AWSIoTMQTTClient("pubsun170")
- my_rpi.configureEndpoint(host, 8883)
- my_rpi.configureCredentials(rootCAPath, privateKeyPath, certificatePath)
- my_rpi.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing
- my_rpi.configureDrainingFrequency(2) # Draining: 2 Hz
- my_rpi.configureConnectDisconnectTimeout(10) # 10 sec
- my_rpi.configureMQTTOperationTimeout(5) # 5 sec
- # Connect and subscribe to AWS IoT
- my_rpi.connect()
- my_rpi.subscribe("sensors/light", 1, customCallback)
- sleep(2)
- count1 = True
- count2 = True
- def counterp1():
- global count1
- global led
- # count1 = True
- if count1 == False:
- led.off()
- count1 = True
- print(" led is offed")
- else:
- led.on()
- count1 = False
- print(" led is on")
- # def ledON():
- # led.on()
- # print("LED is on")
- # def ledOFF():
- # led.off()
- # print("LED is off")
- button.when_pressed = counterp1
- # Publish to the same topic in a loop forever
- loopCount = 0
- while True:
- light = round(1024-(adc.value*1024))
- humidity, temperature = Adafruit_DHT.read_retry(11, pin)
- loopCount = loopCount+1
- message = {}
- message["deviceid"] = "deviceid_chris"
- import datetime as datetime
- now = datetime.datetime.now()
- message["datetimeid"] = now.isoformat()
- message["value"] = light
- message["temp_value"] = temperature
- message["humid_value"] = humidity
- import json
- my_rpi.publish("sensors/light", json.dumps(message), 1)
- lcd.text('Light Value: {:.4f}'.format(light),1)
- sleep(2)
- lcd.text('Humidity: {:.1f}'.format(humidity), 1)
- sleep(2)
- server.py
- -----------------------------------------------------------------------------------------
- # Import SDK packages
- from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
- from time import sleep
- from gpiozero import MCP3008
- import Adafruit_DHT
- from rpi_lcd import LCD
- lcd = LCD()
- led = LED(18)
- adc = MCP3008(channel=0)
- pin =4
- # Custom MQTT message callback
- def customCallback(client, userdata, message):
- print("Received a new message: ")
- print(message.payload)
- print("from topic: ")
- print(message.topic)
- print("--------------\n\n")
- host = "axad8ecychu5n-ats.iot.us-east-1.amazonaws.com"
- rootCAPath = "AmazonRootCA1.pem"
- certificatePath = "75198eb21f-certificate.pem.crt"
- privateKeyPath = "75198eb21f-private.pem.key"
- my_rpi = AWSIoTMQTTClient("pubsun170")
- my_rpi.configureEndpoint(host, 8883)
- my_rpi.configureCredentials(rootCAPath, privateKeyPath, certificatePath)
- my_rpi.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing
- my_rpi.configureDrainingFrequency(2) # Draining: 2 Hz
- my_rpi.configureConnectDisconnectTimeout(10) # 10 sec
- my_rpi.configureMQTTOperationTimeout(5) # 5 sec
- # Connect and subscribe to AWS IoT
- my_rpi.connect()
- my_rpi.subscribe("sensors/light", 1, customCallback)
- sleep(2)
- count1 = True
- count2 = True
- def counterp1():
- global count1
- global led
- # count1 = True
- if count1 == False:
- led.off()
- count1 = True
- print(" led is offed")
- else:
- led.on()
- count1 = False
- print(" led is on")
- # def ledON():
- # led.on()
- # print("LED is on")
- # def ledOFF():
- # led.off()
- # print("LED is off")
- button.when_pressed = counterp1
- # Publish to the same topic in a loop forever
- loopCount = 0
- while True:
- light = round(1024-(adc.value*1024))
- humidity, temperature = Adafruit_DHT.read_retry(11, pin)
- loopCount = loopCount+1
- message = {}
- message["deviceid"] = "deviceid_chris"
- import datetime as datetime
- now = datetime.datetime.now()
- message["datetimeid"] = now.isoformat()
- message["value"] = light
- message["temp_value"] = temperature
- message["humid_value"] = humidity
- import json
- my_rpi.publish("sensors/light", json.dumps(message), 1)
- lcd.text('Light Value: {:.4f}'.format(light),1)
- sleep(2)
- lcd.text('Humidity: {:.1f}'.format(humidity), 1)
- sleep(2)
- telegrambot.py
- ----------------------------------------------------------------
- from picamera import PiCamera
- from random import randint
- from time import sleep
- import botocore
- import telepot
- import boto3
- import time
- import os
- from gpiozero import LED
- led = LED(18)
- my_bot_token = '812916353:AAFbUqga8c0iHmFV9g3SkuYG5KyR4pDkn9k'
- camera = PiCamera()
- timestring = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
- file_name = timestring + '.jpg'
- full_path = '/home/pi/Desktop/' + file_name
- deg = u'\xb0'
- degInString = deg.encode('utf8')
- # Create an S3 resource
- s3 = boto3.resource('s3', aws_access_key_id='ASIAXOQPA3DL7VN3OEOZ', aws_secret_access_key='8IVQIfRUzgnngbWcu5ZOshyIvETU6CtEY0P/c4dX',
- aws_session_token="FQoGZXIvYXdzEDwaDPZNLzJ28fxhpKb7sSLsBHzujdFPJTVJPl6x9jynQ7Yq7PdZ3E5Wh+WFeXGBVtHwDEXPmndmVR3aPLf5cqOxphcvLTYZm3YCRnAiKpAicmPVC77tbxeIkxVsfPbdr2yB50pBRb5khdQegP4GUa3hd68NhtGvxLrLl9Wp4+iVeFLYwyGNQzEv1M20jA9lqE1wwho6/OX0Q11JRA7qAL7/si6+EhZjrtU1eN/x0j8/SH6yDPWf29CkYdTgbki8fJLD8kE4A++GCtzbFA36pFhOvKO0aZ49OfGGGCki6L3q9Aw3MtV3zRDq6vrXF/XwXTGfIt2pGo59K31ZdQ1Om4AVmVyKP98axOxHz1Oz79VZM/EbPhkbOnIY53H6C1ojCRCKpKRFF+KvSjvep8AHwPqwGMEFbYtaZYra928zGB4A012KLhC2QmXYFR7dkheckAb5xk7zRJjavm46aGBwkEoCwFFaxRu6/V2saQuxrnQeRVWlnVQlWqZG0h4bBDvR3+hF+G8lZVRfrMsHR/hdTqIm8FN4C5tBUS+xfCn5vYgGDz6AOFazQxLfmGBgIMAY+nBO6sCzkMQrtDv2+RrD6DvIJrT7m6auVyr2iHy8MNlE4bc137Ky2rDRV16Iqa8PBlzF5x2fcn/b9IDjUxCjpbOioox/4gdtjvbsj0mHdwkKuB9KD4R5B6eUbUXcyBxZzASMGVBxHPYdJgumwY9ftjX/ZFaWmkRbN59l35w9NIG7rCk5xmpGdlWNMTpDvrAId3d73C4YUWbGhIXLMSBwDw86IZK4odC4rXNEEEhyQPO1YAqZamDOZgW4NhTkQZPEtC0VN2UNejDiExtto1vJKNql9uoF")
- bucket_name = 'sp-p1703263-s3-bucket'
- def takePicture():
- camera.capture(full_path)
- def uploadPicture():
- exists = True
- timestring = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
- file_name = timestring + '.jpg'
- try:
- s3.meta.client.head_bucket(Bucket=bucket_name)
- except botocore.exceptions.ClientError as e:
- error_code = int(e.response['Error']['Code'])
- if error_code == 404:
- exists = False
- if exists == False:
- s3.create_bucket(Bucket=bucket_name,CreateBucketConfiguration={'LocationConstraint': 'us-west-2'})
- # Upload a new file
- s3.Object(bucket_name,
- 'home/User/{}'.format(file_name)).put(Body=open(full_path, 'rb'))
- print("File uploaded")
- os.remove(full_path)
- def retrievePicture():
- try:
- s3.Bucket(bucket_name).download_file('home/User/{}'.format(file_name),
- full_path)
- except botocore.exceptions.ClientError as e:
- error_code = int(e.response['Error']['Code'])
- if error_code == 404:
- print("The object does not exist.")
- def onLED():
- led.on()
- return "Got it, LED is now turned on..."
- def offLED():
- led.off()
- return "Got it, LED is now turned off..."
- def respondToMsg(msg):
- chat_id = msg['chat']['id']
- command = msg['text']
- print('Got command: {}'.format(command))
- if (command == '/start'):
- text = 'Welcome to CP House Bot!\nType /help for our available commands'
- bot.sendMessage(chat_id, text)
- elif (command == '/help'):
- text = '''Here are our available commands:\n
- /takepicture - Takes a picture from your RPi
- /onLED - To on the LED light
- /offLED - To off the LED light
- '''
- bot.sendMessage(chat_id, text)
- elif (command == '/takepicture'):
- takePicture()
- bot.sendPhoto(chat_id, photo=open(full_path, 'rb'))
- uploadPicture()
- retrievePicture()
- #os.remove(full_path)
- elif (command == '/onLED'):
- bot.sendMessage(chat_id, onLED())
- elif (command == '/offLED'):
- bot.sendMessage(chat_id, offLED())
- elif ('/' in command):
- text = command + ' is not recognized.\nType /help for our available commands.'
- bot.sendMessage(chat_id, text)
- else:
- text = ['I do not understand you...', 'Huh?', 'Can you please repeat?', 'What do you mean?']
- number = randint(0,3)
- bot.sendMessage(chat_id, text[number])
- bot = telepot.Bot(my_bot_token)
- bot.message_loop(respondToMsg)
- print('Listening for RPi commands')
- while True:
- sleep(1)
- dooraccess.py
- ---------------------------------------------------------------------------------
- from gpiozero import MCP3008, LED,Button
- import mysql.connector
- from time import sleep
- import sys
- from rpi_lcd import LCD
- import Adafruit_DHT
- from signal import pause
- import gevent
- import gevent.monkey
- import RPi.GPIO as GPIO
- import MFRC522
- import signal
- from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
- host = "a1pem9ilz5vgjc-ats.iot.us-east-1.amazonaws.com"
- rootCAPath = "AmazonRootCA1.pem"
- certificatePath = "95e7faaf66-certificate.pem.crt"
- privateKeyPath = "95e7faaf66-private.pem.key"
- # my_rpi.configureEndpoint(host, 8883)
- # my_rpi.configureCredentials(rootCAPath, privateKeyPath, certificatePath)
- # my_rpi.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing
- # my_rpi.configureDrainingFrequency(2) # Draining: 2 Hz
- # my_rpi.configureConnectDisconnectTimeout(10) # 10 sec
- # my_rpi.configureMQTTOperationTimeout(5) # 5 sec
- # # Connect and subscribe to AWS IoT
- # my_rpi.connect()
- uid = None
- prev_uid = None
- continue_reading = True
- # Capture SIGINT for cleanup when the script is aborted
- def end_read(signal,frame):
- global continue_reading
- print "Ctrl+C captured, ending read."
- continue_reading = False
- GPIO.cleanup()
- def retrieveCard():
- try:
- import boto3
- from boto3.dynamodb.conditions import Key, Attr
- dynamodb = boto3.resource('dynamodb', region_name='us-east-1')
- table = dynamodb.Table('access_door')
- response = table.query(
- KeyConditionExpression=Key('rfidNo')
- )
- item = response['Items']
- print(item)
- return item
- except:
- import sys
- print(sys.exc_info()[0])
- print(sys.exc_info()[1])
- # Hook the SIGINT
- signal.signal(signal.SIGINT, end_read)
- # Create an object of the class MFRC522
- mfrc522 = MFRC522.MFRC522()
- # Welcome message
- print "Welcome to the MFRC522 data read example"
- print "Press Ctrl-C to stop."
- # This loop keeps checking for chips.
- # If one is near it will get the UID
- while continue_reading:
- # Scan for cards
- (status,TagType) = mfrc522.MFRC522_Request(mfrc522.PICC_REQIDL)
- # If a card is found
- if status == mfrc522.MI_OK:
- # Get the UID of the card
- (status,uid) = mfrc522.MFRC522_Anticoll()
- if uid!=prev_uid:
- prev_uid = uid
- print("New card detected! UID of card is {}".format(uid))
- print(type(uid))
- retrieveCard()
- # try:
- # u='AssignmentCA2';pw='Chris0688';
- # h='10.10.10.137';db='Assignment_Ca2_DB'
- # cnx = mysql.connector.connect(user=u,password=pw,host=h,database=db)
- # cursor = cnx.cursor()
- # print("Successfully connected to database!")
- # uid = None
- # prev_uid = None
- # continue_reading = True
- # # Capture SIGINT for cleanup when the script is aborted
- # def end_read(signal,frame):
- # global continue_reading
- # print "Ctrl+C captured, ending read."
- # continue_reading = False
- # GPIO.cleanup()
- # # Hook the SIGINT
- # signal.signal(signal.SIGINT, end_read)
- # # Create an object of the class MFRC522
- # mfrc522 = MFRC522.MFRC522()
- # # Welcome message
- # print "Welcome to the MFRC522 data read example"
- # print "Press Ctrl-C to stop."
- # # This loop keeps checking for chips.
- # # If one is near it will get the UID
- # while continue_reading:
- # update = True
- # while update:
- # (status,TagType) = mfrc522.MFRC522_Request(mfrc522.PICC_REQIDL)
- # if status == mfrc522.MI_OK:
- # (status,uid) = mfrc522.MFRC522_Anticoll()
- # if uid!=prev_uid:
- # prev_uid = uid
- # print("New card detected! UID of card is {}".format(uid))
- # authorised = 0
- # sql = "SELECT rfidCardNo FROM accessDoor"
- # cursor.execute(sql)
- # records = cursor.fetchall()
- # for i in records:
- # if i[0] == str(uid):
- # authorised += 1
- # else:
- # authorised += 0
- # if authorised == 1:
- # print("ACCESS ALLOWED")
- # else:
- # print("UNAUTHORISED ACCESS!")
- # except:
- # print(sys.exc_info()[0])
- # print(sys.exc_info()[1])
- heatdetector.py
- -------------------------------------------------------------------
- # Import SDK packages
- from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
- from time import sleep
- import Adafruit_DHT
- from gpiozero import MCP3008, LED,Button,Buzzer
- import nexmo
- msgSender = nexmo.Client(key='91beec10', secret='kIAAc2GWl77JT1Zr')
- bz = Buzzer(5)
- host = "a1pem9ilz5vgjc-ats.iot.us-east-1.amazonaws.com"
- rootCAPath = "AmazonRootCA1.pem"
- certificatePath = "75198eb21f-certificate.pem.crt"
- privateKeyPath = "75198eb21f-private.pem.key"
- my_rpi = AWSIoTMQTTClient("firedetecter")
- my_rpi.configureEndpoint(host, 8883)
- my_rpi.configureCredentials(rootCAPath, privateKeyPath, certificatePath)
- my_rpi.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing
- my_rpi.configureDrainingFrequency(2) # Draining: 2 Hz
- my_rpi.configureConnectDisconnectTimeout(10) # 10 sec
- my_rpi.configureMQTTOperationTimeout(5) # 5 sec
- # Connect and subscribe to AWS IoT
- my_rpi.connect()
- loopCount = 0
- led = LED(18)
- #LED On off commands
- def ledON():
- led.on()
- print("LED is on")
- def ledOFF():
- led.off()
- print("LED is off")
- # Custom MQTT message callback
- def customCallback(client, userdata, message):
- print(message.payload.decode('UTF-8'))
- if float(message.payload.decode('UTF-8')) > 25:
- ledON()
- bz.on()
- msgSender.send_message({
- 'from': 'Nexmo',
- 'to': '6596551876',
- 'text': 'Potential fire !!!!!',
- })
- else:
- ledOFF()
- bz.off()
- my_rpi.subscribe("smartroom/sensor/fire", 1, customCallback)
- sleep(2)
- while True:
- loopCount = loopCount + 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement