Advertisement
Guest User

IOT

a guest
Aug 21st, 2019
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 18.72 KB | None | 0 0
  1. dynamodb.py
  2. -------------------------------------
  3. def 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.  
  37. if __name__ == "__main__":
  38.     get_data_from_dynamodb()
  39.  
  40.  
  41.  
  42. jsonconverter.py
  43. --------------------------------------------------------------
  44. from decimal import Decimal
  45. import json
  46. import datetime
  47. import numpy
  48.  
  49. class 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.  
  63. def data_to_json(data):
  64.     json_data = json.dumps(data,cls=GenericEncoder)
  65.     print(json_data)
  66.     return json_data
  67.  
  68.  
  69. publishHeat.py
  70. ---------------------------------------------------------------------
  71. # Import SDK packages
  72. from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
  73. from time import sleep
  74. import Adafruit_DHT
  75.  
  76. pin=4
  77. host = "a1pem9ilz5vgjc-ats.iot.us-east-1.amazonaws.com"
  78. rootCAPath = "AmazonRootCA1.pem"
  79. certificatePath = "75198eb21f-certificate.pem.crt"
  80. privateKeyPath = "75198eb21f-private.pem.key"
  81.  
  82. my_rpi = AWSIoTMQTTClient("CPHeatPub")
  83. my_rpi.configureEndpoint(host, 8883)    
  84. my_rpi.configureCredentials(rootCAPath, privateKeyPath, certificatePath)
  85.  
  86. my_rpi.configureOfflinePublishQueueing(-1)  # Infinite offline Publish queueing
  87. my_rpi.configureDrainingFrequency(2)  # Draining: 2 Hz
  88. my_rpi.configureConnectDisconnectTimeout(10)  # 10 sec
  89. my_rpi.configureMQTTOperationTimeout(5)  # 5 sec
  90. my_rpi.connect()
  91.  
  92. # Publish to the same topic in a loop forever
  93. loopCount = 0
  94. while 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.  
  101. pubsub.py
  102. ----------------------------------------------------------
  103. # Import SDK packages
  104. from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
  105. from time import sleep
  106. from gpiozero import MCP3008
  107. import Adafruit_DHT
  108. from rpi_lcd import LCD
  109. lcd = LCD()
  110. led = LED(18)
  111. adc = MCP3008(channel=0)
  112. pin =4
  113. # Custom MQTT message callback
  114. def 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.    
  121. host = "axad8ecychu5n-ats.iot.us-east-1.amazonaws.com"
  122. rootCAPath = "AmazonRootCA1.pem"
  123. certificatePath = "75198eb21f-certificate.pem.crt"
  124. privateKeyPath = "75198eb21f-private.pem.key"
  125.  
  126.  
  127.  
  128. my_rpi = AWSIoTMQTTClient("pubsun170")
  129. my_rpi.configureEndpoint(host, 8883)
  130. my_rpi.configureCredentials(rootCAPath, privateKeyPath, certificatePath)
  131.  
  132. my_rpi.configureOfflinePublishQueueing(-1)  # Infinite offline Publish queueing
  133. my_rpi.configureDrainingFrequency(2)  # Draining: 2 Hz
  134. my_rpi.configureConnectDisconnectTimeout(10)  # 10 sec
  135. my_rpi.configureMQTTOperationTimeout(5)  # 5 sec
  136.  
  137. # Connect and subscribe to AWS IoT
  138. my_rpi.connect()
  139. my_rpi.subscribe("sensors/light", 1, customCallback)
  140. sleep(2)
  141.  
  142. count1 = True
  143. count2 = True
  144. def 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.          
  168. button.when_pressed = counterp1
  169.  
  170. # Publish to the same topic in a loop forever
  171. loopCount = 0
  172. while 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.  
  196. server.py
  197. -----------------------------------------------------------------------------------------
  198. # Import SDK packages
  199. from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
  200. from time import sleep
  201. from gpiozero import MCP3008
  202. import Adafruit_DHT
  203. from rpi_lcd import LCD
  204. lcd = LCD()
  205. led = LED(18)
  206. adc = MCP3008(channel=0)
  207. pin =4
  208. # Custom MQTT message callback
  209. def 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.    
  216. host = "axad8ecychu5n-ats.iot.us-east-1.amazonaws.com"
  217. rootCAPath = "AmazonRootCA1.pem"
  218. certificatePath = "75198eb21f-certificate.pem.crt"
  219. privateKeyPath = "75198eb21f-private.pem.key"
  220.  
  221.  
  222.  
  223. my_rpi = AWSIoTMQTTClient("pubsun170")
  224. my_rpi.configureEndpoint(host, 8883)
  225. my_rpi.configureCredentials(rootCAPath, privateKeyPath, certificatePath)
  226.  
  227. my_rpi.configureOfflinePublishQueueing(-1)  # Infinite offline Publish queueing
  228. my_rpi.configureDrainingFrequency(2)  # Draining: 2 Hz
  229. my_rpi.configureConnectDisconnectTimeout(10)  # 10 sec
  230. my_rpi.configureMQTTOperationTimeout(5)  # 5 sec
  231.  
  232. # Connect and subscribe to AWS IoT
  233. my_rpi.connect()
  234. my_rpi.subscribe("sensors/light", 1, customCallback)
  235. sleep(2)
  236.  
  237. count1 = True
  238. count2 = True
  239. def 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.          
  263. button.when_pressed = counterp1
  264.  
  265. # Publish to the same topic in a loop forever
  266. loopCount = 0
  267. while 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.  
  290. telegrambot.py
  291. ----------------------------------------------------------------
  292. from picamera import PiCamera
  293. from random import randint
  294. from time import sleep
  295. import botocore
  296. import telepot
  297. import boto3
  298. import time
  299. import os
  300. from gpiozero import  LED
  301.  
  302.  
  303. led = LED(18)
  304. my_bot_token = '812916353:AAFbUqga8c0iHmFV9g3SkuYG5KyR4pDkn9k'
  305. camera = PiCamera()
  306. timestring = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
  307. file_name = timestring + '.jpg'
  308. full_path = '/home/pi/Desktop/' + file_name
  309. deg = u'\xb0'
  310. degInString = deg.encode('utf8')
  311. # Create an S3 resource
  312. s3 = boto3.resource('s3', aws_access_key_id='ASIAXOQPA3DL7VN3OEOZ', aws_secret_access_key='8IVQIfRUzgnngbWcu5ZOshyIvETU6CtEY0P/c4dX',
  313. 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")
  314. bucket_name = 'sp-p1703263-s3-bucket'
  315.  
  316. def takePicture():
  317.     camera.capture(full_path)
  318.  
  319. def 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.  
  341. def 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.  
  350. def onLED():
  351.    led.on()
  352.    return "Got it, LED is now turned on..."
  353.  
  354. def offLED():
  355.    led.off()
  356.    return "Got it, LED is now turned off..."
  357.  
  358. def 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.  
  393. bot = telepot.Bot(my_bot_token)
  394. bot.message_loop(respondToMsg)
  395. print('Listening for RPi commands')
  396. while True:
  397.     sleep(1)
  398.  
  399.  
  400. dooraccess.py
  401. ---------------------------------------------------------------------------------
  402.  
  403. from gpiozero import MCP3008, LED,Button
  404. import mysql.connector
  405. from time import sleep
  406. import sys
  407. from rpi_lcd import LCD
  408. import Adafruit_DHT
  409. from signal import pause
  410. import gevent
  411. import gevent.monkey
  412. import RPi.GPIO as GPIO
  413. import MFRC522
  414. import signal
  415. from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
  416.  
  417. host = "a1pem9ilz5vgjc-ats.iot.us-east-1.amazonaws.com"
  418. rootCAPath = "AmazonRootCA1.pem"
  419. certificatePath = "95e7faaf66-certificate.pem.crt"
  420. privateKeyPath = "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.  
  432. uid = None
  433. prev_uid = None
  434. continue_reading = True
  435.  
  436. # Capture SIGINT for cleanup when the script is aborted
  437. def end_read(signal,frame):
  438.     global continue_reading
  439.     print "Ctrl+C captured, ending read."
  440.     continue_reading = False
  441.     GPIO.cleanup()
  442. def 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
  464. signal.signal(signal.SIGINT, end_read)
  465.  
  466. # Create an object of the class MFRC522
  467. mfrc522 = MFRC522.MFRC522()
  468.  
  469. # Welcome message
  470. print "Welcome to the MFRC522 data read example"
  471. print "Press Ctrl-C to stop."
  472.  
  473. # This loop keeps checking for chips.
  474. # If one is near it will get the UID
  475.  
  476. while 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.  
  554. heatdetector.py
  555. -------------------------------------------------------------------
  556. # Import SDK packages
  557. from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
  558. from time import sleep
  559. import Adafruit_DHT
  560. from gpiozero import MCP3008, LED,Button,Buzzer
  561. import nexmo
  562.  
  563. msgSender = nexmo.Client(key='91beec10', secret='kIAAc2GWl77JT1Zr')
  564.  
  565. bz = Buzzer(5)
  566.  
  567. host = "a1pem9ilz5vgjc-ats.iot.us-east-1.amazonaws.com"
  568. rootCAPath = "AmazonRootCA1.pem"
  569. certificatePath = "75198eb21f-certificate.pem.crt"
  570. privateKeyPath = "75198eb21f-private.pem.key"
  571.  
  572. my_rpi = AWSIoTMQTTClient("firedetecter")
  573. my_rpi.configureEndpoint(host, 8883)
  574. my_rpi.configureCredentials(rootCAPath, privateKeyPath, certificatePath)
  575.  
  576. my_rpi.configureOfflinePublishQueueing(-1)  # Infinite offline Publish queueing
  577. my_rpi.configureDrainingFrequency(2)  # Draining: 2 Hz
  578. my_rpi.configureConnectDisconnectTimeout(10)  # 10 sec
  579. my_rpi.configureMQTTOperationTimeout(5)  # 5 sec
  580. # Connect and subscribe to AWS IoT
  581. my_rpi.connect()
  582. loopCount = 0
  583.  
  584. led = LED(18)
  585. #LED On off commands
  586. def ledON():
  587.   led.on()
  588.   print("LED is on")
  589.  
  590.  
  591. def ledOFF():
  592.   led.off()
  593.   print("LED is off")
  594.  
  595. # Custom MQTT message callback
  596. def 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()  
  609. my_rpi.subscribe("smartroom/sensor/fire", 1, customCallback)
  610. sleep(2)
  611.  
  612. while True:
  613.     loopCount = loopCount + 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement