Exemple #1
0
    def laser():
        API_KEY = "d1c0747d-cf58-4b22-b97a-cfae6ba9ae2e"
        DEVIVE_ID = "BOLT7487042"
        Mybolt = Bolt(API_KEY, DEVIVE_ID)
        sms = Sms(conf.SSID, conf.AUTH_TOKEN, conf.TO_NUMBER, conf.FROM_NUMBER)

        print(json.loads(Mybolt.isOnline())['value'])
        while True:
            response = Mybolt.analogRead('A0')
            data = json.loads(response)
            print(data['value'])
            try:
                sensor_value = int(data['value'])
                print(sensor_value)
                if sensor_value < 1020:
                    #response = sms.send_sms(" an unwanted access")
                    response = Mybolt.digitalWrite('4', 'HIGH')
                    sleep(0)

                else:
                    response = Mybolt.digitalWrite('4', 'LOW')

            except Exception as e:
                print("error", e)
                sleep(10000)
Exemple #2
0
class CarLight:
    def __init__(self):
        # Enter your own generated bolt API Key & Your own Device Id
        self.api_key = "638f9a4d-809a-4e47-ac2a-4436e195b503"
        self.device_id = "BOLT290339"

        # Setting Threshold value
        self.maximum_limit = 170

        ## Connecting to the bolt IoT Module
        self.mybolt = Bolt(self.api_key, self.device_id)
        print(format("Automatic Car light Controller and Adjuster", '_^50'))
        self.error = '{"success": "0", "message": "A Connection error occurred"}'
        self.offline = '{"value": "offline", "time": null, "success": 1}'

    def start(self):
        #  Checking Bolt Device is offline or Online
        result = self.mybolt.isOnline()
        if result == self.error:
            print(
                "\n Check weather your computer or bolt device is connected to Internet....."
            )
        elif result == self.offline:
            print("\n Bolt Device is offline")
        else:
            while True:
                print("\n Collecting Value from Sensor")
                # Collecting Response from the sensor
                response = self.mybolt.analogRead('A0')
                data = json.loads(response)
                if data['value'].isnumeric():
                    intent = int(data['value'])
                    print("value from sensor is: " + str(intent))
                    # Comparing Light Intensity & Threshold Value
                    if intent > self.maximum_limit:
                        # If light Intensity is Higher Than Threshold Value Then Dipper is On.
                        analog_ack = self.mybolt.analogWrite('1', '120')
                        digital_ack = self.mybolt.digitalWrite('0', 'LOW')
                        print("Car's Dipper light is On ")
                    else:
                        # Else Main Headlight is On & Dipper is Off
                        analog_ack = self.mybolt.digitalWrite('0', 'HIGH')
                        digital_ack = self.mybolt.digitalWrite('1', 'LOW')
                        print("Car's main Headlight is On")
                else:
                    print(f"[Error] {data['value']}")
                time.sleep(1)
Exemple #3
0
def tamper_check(device_id, device_api, sql_curr, db):
    # Init bolt instance
    mydevice = Bolt(device_api, device_id)
    # Check device status
    response = mydevice.isOnline()
    if 'online' in response:
        mydevice.digitalWrite(LED, 'HIGH')
        # CHECK TAMPER PIN
        tamper_pin = json.loads(mydevice.digitalRead(TPIN))
        if tamper_pin['value'] == '1':
            print("Status OK", device_id)
            # LOG UPDATE
            sql_curr.callproc('log_update', ('1', 'Routine Check', '0'))
            db.commit()
            # ActiveDevice TABLE update
            sql_curr.callproc('update_status', ('1', '0'))
            db.commit()
        else:
            print("TAMPERED!!_,DEVICE_ID:", device_id)
            # REGISTERED TAMPER
            sql_curr.callproc('update_status', ('1', '1'))
            db.commit()
            sql_curr.callproc('log_update', ('1', 'Lock tampered', '1'))
            db.commit()
            sql_curr.callproc('deactivate_device')
            db.commit()
            # TURN OFF GLOW
            mydevice.digitalWrite(LED, 'LOW')
            # SEND SMS
            sql_curr.callproc('get_tamper_report')
            data = sql_curr.stored_results()
            for d in data:
                row = d.fetchone()
                msg = "TAMPERED DEVICE ID {} TIME {}".format(device_id, row[1])
                sendSms(row[0].strip(), msg)
                break
    else:
        sql_curr.callproc('update_status', ('0', '0'))
        db.commit()
        sql_curr.callproc('log_update', ('0', 'Device OFFLINE', '0'))
        db.commit()
    del mydevice
    return
def transmit(api,dev_id,i):
    print("Transmitter ON")
    mybolt = Bolt(api, dev_id)
    flag=1
    while flag:
        time.sleep(10)
        response = mybolt.digitalRead('3') #ACK PIN Read
        data = json.loads(response)
        if int(data['value'])==1:
            rantime=random.choice(range(2,5,1))#random time is selected
            time.sleep(rantime)                #waits for random time
            response = mybolt.digitalRead('3') #ACK PIN Read
            data = json.loads(response)
            if int(data['value'])==1:
                time.sleep(3)
                response = mybolt.digitalWrite('0','LOW')   #ack pin made zero,indicate active transmission
                time.sleep(5)
                response = mybolt.digitalWrite(str(i),'HIGH')# i is the pin number of device to be made high
                return
Exemple #5
0
def service_check(device_id, device_api, sql_curr, db):
    # Init bolt instance
    mydevice = Bolt(device_api, device_id)
    # Check device status
    response = mydevice.isOnline()
    if 'online' in response:
        # GLOW RESPONSE BULB
        mydevice.digitalWrite(LED, 'HIGH')
        # CHECK TAMPER PIN
        tamper_pin = json.loads(mydevice.digitalRead(TPIN))
        if tamper_pin['value'] == '1':
            print("LOCK INIT__DEVICE:", device_id)
            # LOG UPDATE
            sql_curr.callproc('log_update', ('1', 'Lock Activated', '0'))
            db.commit()
            # MOVE TO ACTIVE DEVICES
            sql_curr.callproc('activate_device')
            db.commit()
            # BLINK RESPONSE BULB
            for i in range(3):
                mydevice.digitalWrite(LED, 'LOW')
                sleep(BLK_INTV)
                mydevice.digitalWrite(LED, 'HIGH')
                sleep(BLK_INTV)
        #else:
        # REGISTERED TAMPER
        #sql_curr.callproc('log_update', args = (1, 'Lock found tampered', 1))
        #sql_curr.callproc('faulty_device')
    del mydevice
    return
Exemple #6
0
def alert(frame):

    #we convert numpy array frame to an RGB image and save as my.png because only images are sent via the telegram bot
    img = Image.fromarray(frame, 'RGB')
    img.save('my.png')
    bot = telegram.Bot(
        token=conf.TELEGRAM_BOT_ID)  #configure telegram chat bot

    #configuring and switching on the buzzer and switching off after a certain time
    mybolt = Bolt(conf.API_KEY, conf.DEVICE_ID)
    response = mybolt.digitalWrite('0', 'HIGH')
    #time.sleep(10)
    response = mybolt.digitalWrite('0', 'LOW')

    #We send the captured photo in binary mode of the intruder along with a caption to telegram
    try:
        bot.send_photo(chat_id=conf.TELEGRAM_CHAT_ID,
                       photo=open('my.png', 'rb'),
                       caption="Intruder Alert!")
    except Exception as e:  #raise exception if not sent
        print("An error occurred in sending the alert message via Telegram")
        print(e)
Exemple #7
0
    def laser():
        api_key = "b42f36a3-9e5b-440c-8fa4-c57de4e5c4ca"
        device_id = "BOLT3732040"
        mybolt = Bolt(api_key, device_id)
        sms = Sms(conf.SSID, conf.AUTH_TOKEN, conf.TO_NUMBER, conf.FROM_NUMBER)

        print(json.loads(mybolt.isOnline())['value'])
        while True:
            response = mybolt.analogRead('A0')
            data = json.loads(response)
            print(data['value'])
            try:
                sensor_value = int(data['value'])
                print(sensor_value)
                if sensor_value < 1020:
                    response = sms.send_sms(" an unwanted access")
                    response = mybolt.digitalWrite('0', 'HIGH')
                    sleep(20000)

            except Exception as e:
                print("error", e)
                sleep(10000)
 try:
     sensor_value = int(data['value'])
 except e:
     print("There was an error while parsing the response: ", e)
     continue
 bound = compute_bounds(history_data, conf.FRAME_SIZE, conf.MUL_FACTOR)
 if not bound:
     required_data_count = conf.FRAME_SIZE - len(history_data)
     print("Not enough data to compute Z-score. Need ", required_data_count,
           " more data points")
     history_data.append(int(data['value']))
     time.sleep(10)
     continue
 try:
     if sensor_value > bound[0]:
         buzz = mybolt.digitalWrite('1', "HIGH")
         print(buzz)
         time.sleep(2)
         api_object = get_api_object(config)
         tweet = (
             "Temperature increased suddenly Current Temperature is: " +
             str(sensor_valuec))
         status = api_object.update_status(status=tweet)
         print("Tweeted")
         response = sms.send_sms(
             "Temperature increased suddenly Current Temperature is: " +
             str(sensor_valuec))
         print("Response:", response)
         print(
             "Anomaly of the temperature occured because of increase in temperature."
         )
def get_frame():

    api_key = "xxxxxxx"
    device_id  = "xxxxxxx"
    mybolt = Bolt(api_key, device_id)
    response = mybolt.isOnline()
    print(response)

    refIm = cv2.imread("refFrame.jpg")
    vid1 = cv2.VideoCapture('latestData.mp4')
    vid2 = cv2.VideoCapture('latestData.mp4')
    vid3 = cv2.VideoCapture('latestData.mp4')
    vid4 = cv2.VideoCapture('latestData.mp4')
    temp = np.zeros(refIm.shape,"uint8")
    timer = temp.copy()
    index=0
    li=[[5,49],[7,32],[9,4],[10,43],[12,14],[14,3],[15,46],[2,20],[17,17]]

    red_img=cv2.imread("traffic_lights/red.png")
    yellow_img=cv2.imread("traffic_lights/yellow.png")
    green_img=cv2.imread("traffic_lights/green.png")

    #------------_DEBUG3-------------------#
    red_img=cv2.resize(red_img,(100,200),None)
    yellow_img=cv2.resize(yellow_img,(100,200),None)
    green_img=cv2.resize(green_img,(100,200),None)

    while True:
        # setting the video frame for different lanes#
        #For lane1 #

        lane1_start_time = calcFrame(li[index][0],li[index][1] )
        print("index",index)
        vid1.set(1, lane1_start_time)
        _, frame1 = vid1.read()
        
        
        index=(index+1)%9
        #For lane2 #
        lane2_start_time = calcFrame(li[index][0],li[index][1])
        print("index",index)
        vid2.set(1, lane2_start_time)
        _, frame2 = vid2.read()

        index=(index+1)%9
        #For lane3#
        lane3_start_time = calcFrame(li[index][0],li[index][1])
        print("index",index)
        vid3.set(1, lane3_start_time)
        _, frame3 = vid3.read()

        index=(index+1)%9
        #For lane4#
        lane4_start_time = calcFrame(li[index][0],li[index][1])
        print("index",index)
        vid4.set(1, lane4_start_time)
        _, frame4 = vid4.read()

        index=(index+1)%9
        # display window. fWin is the final Video#
        st0 = np.hstack((temp, frame1, temp))
        st1 = np.hstack((frame4, timer, frame2))
        st2 = np.hstack((temp, frame3, temp))
        fWin = np.vstack((st0, st1, st2))

        #------------DEBUG1-----------#
        print(temp.shape,st0.shape,red_img.shape)
        next_predected_time = 0
        if next_predected_time == 0:
            predected_time = int(process(frame1))
        else:
            predected_time = int(next_predected_time)

        #print("predicted time is",predected_time)
        t0 = time.clock()
        t0 = time.time()
        mybolt.digitalWrite(0,'LOW')
        while (time.time()-t0<=predected_time):
            rem_time=predected_time-(time.time()-t0)
            print("frame 1")
            ret1, frame1 = vid1.read()
            st0 = np.hstack((temp, frame1, temp))
            st1 = np.hstack((frame4, timer, frame2))
            st2 = np.hstack((temp, frame3, temp))

            if rem_time<7:
                testing = np.hstack((yellow_img,red_img,red_img,red_img))
            else:
                testing = np.hstack((green_img,red_img,red_img,red_img))

              #------------DEBUG2-----------#
            
            testing=cv2.resize(testing,(st0.shape[1],st0.shape[0]+200),None)

            fWin = np.vstack((st0,st1,st2,testing))
            x, y = int(fWin.shape[0] / 2) + 50, int(fWin.shape[1] / 2) - 80
            cv2.putText(fWin, 'Green Window for Lane 1:', (x-280, y-50), cv2.FONT_HERSHEY_PLAIN, 1.0, (0, 255, 0))
            cv2.putText(fWin, str(int(rem_time)), (x - 200, y), cv2.FONT_HERSHEY_DUPLEX, 1.0, (0, 0, 255))


            imgencode=cv2.imencode('.jpg',fWin)[1]
            stringData=imgencode.tostring()
            yield (b'--frame\r\n'b'Content-Type: text/plain\r\n\r\n'+stringData+b'\r\n')


            #cv2.imshow("frame", fWin)
            #cv2.waitKey(1)
            
            if int(rem_time)==5:
                print("processing frame 2")
                next_predected_time=(process(frame2))
            print(rem_time)

        predected_time=next_predected_time

        mybolt.digitalWrite(0,'HIGH')
        mybolt.digitalWrite(1,'LOW')
        #For Frame2#
        t0 = time.clock()
        t0 = time.time()
        next_predected_time = 0
        while (time.time() - t0 <= predected_time):
            rem_time = predected_time - (time.time() - t0)
            print("frame 2")
            ret2, frame2 = vid2.read()
            st0 = np.hstack((temp, frame1, temp))
            st1 = np.hstack((frame4, timer, frame2))
            st2 = np.hstack((temp, frame3, temp))
            

            #-- Traffic Lights --#
            if rem_time<7:
                testing = np.hstack((red_img,yellow_img,red_img,red_img))
            else:
                testing = np.hstack((red_img,green_img,red_img,red_img))

            
            testing=cv2.resize(testing,(st0.shape[1],st0.shape[0]+200),None)
            fWin = np.vstack((st0,st1,st2,testing))
            x, y = int(fWin.shape[0] / 2) + 50, int(fWin.shape[1] / 2) - 80
            cv2.putText(fWin, 'Green Window for Lane 2:', (x - 280, y - 50), cv2.FONT_HERSHEY_PLAIN, 1.0, (0, 255, 0))
            cv2.putText(fWin, str(int(rem_time)), (x - 200, y), cv2.FONT_HERSHEY_DUPLEX, 1.0, (0, 0, 255))

            
            imgencode=cv2.imencode('.jpg',fWin)[1]
            stringData=imgencode.tostring()
            yield (b'--frame\r\n'b'Content-Type: text/plain\r\n\r\n'+stringData+b'\r\n')

            
            if int(rem_time) == 5:
                print("processing frame3")
                next_predected_time = (process(frame3))
            print(rem_time)

        predected_time=next_predected_time

        mybolt.digitalWrite(1,'HIGH')
        mybolt.digitalWrite(2,'LOW')
        #For Frame3#
        t0 = time.clock()
        t0 = time.time()
        next_predected_time = 0
        while (time.time() - t0 <= predected_time):

            rem_time = predected_time - (time.time() - t0)
            print("frame 3")
            ret2, frame3 = vid3.read()
            st0 = np.hstack((temp, frame1, temp))
            st1 = np.hstack((frame4, timer, frame2))
            st2 = np.hstack((temp, frame3, temp))

            if rem_time<7:
                testing = np.hstack((red_img,red_img,yellow_img,red_img))
            else:
                testing = np.hstack((red_img,red_img,green_img,red_img))

            testing=cv2.resize(testing,(st0.shape[1],st0.shape[0]+200),None)
            fWin = np.vstack((st0, st1, st2,testing))
            x, y = int(fWin.shape[0] / 2) + 50, int(fWin.shape[1] / 2) - 80
            cv2.putText(fWin, 'Green Window for Lane 3:', (x - 280, y - 50), cv2.FONT_HERSHEY_PLAIN, 1.0, (0, 255, 0))
            cv2.putText(fWin, str(int(rem_time)), (x - 200, y), cv2.FONT_HERSHEY_DUPLEX, 1.0, (0, 0, 255))

            imgencode=cv2.imencode('.jpg',fWin)[1]
            stringData=imgencode.tostring()
            yield (b'--frame\r\n'b'Content-Type: text/plain\r\n\r\n'+stringData+b'\r\n')

            
            if int(rem_time) == 5:
                print("processing frame4")
                next_predected_time = process(frame4)
            print(rem_time)

        predected_time=next_predected_time
        mybolt.digitalWrite(2,'HIGH')
        mybolt.digitalWrite(3,'LOW')
        #For Frame4#
        t0 = time.clock()
        t0 = time.time()
        next_predected_time = 0
        while (time.time() - t0 <= predected_time):
            rem_time = predected_time - (time.time() - t0)
            print("frame 4")
            ret2, frame4 = vid4.read()
            st0 = np.hstack((temp, frame1, temp))
            st1 = np.hstack((frame4, timer, frame2))
            st2 = np.hstack((temp, frame3, temp))
            if rem_time<7:
                testing = np.hstack((red_img,red_img,red_img,yellow_img))
            else:
                testing = np.hstack((red_img,red_img,red_img,green_img))

            testing=cv2.resize(testing,(st0.shape[1],st0.shape[0]+200),None)
            fWin = np.vstack((st0, st1, st2,testing))
            x, y = int(fWin.shape[0] / 2) + 50, int(fWin.shape[1] / 2) - 80
            cv2.putText(fWin, 'Green Window for Lane 4:', (x - 280, y - 50), cv2.FONT_HERSHEY_PLAIN, 1.0, (0, 255, 0))
            cv2.putText(fWin, str(int(rem_time)), (x - 200, y), cv2.FONT_HERSHEY_DUPLEX, 1.0, (0, 0, 255))

            imgencode=cv2.imencode('.jpg',fWin)[1]
            stringData=imgencode.tostring()
            yield (b'--frame\r\n'b'Content-Type: text/plain\r\n\r\n'+stringData+b'\r\n')

            rem_time = predected_time - (time.time() - t0)
            if int(rem_time) == 5:
                print("processing frame 1")
                next_predected_time = process(frame1)
            print(rem_time)
        mybolt.digitalWrite(3,'HIGH')
import conf, json, time
from boltiot import Bolt, Sms

API_KEY = "b42f36a3-9e5b-440c-8fa4-c57de4e5c4ca"
DEVIVE_ID = "BOLT3732040"
Mybolt = Bolt(API_KEY, DEVIVE_ID)
SSID = 'ACce54c48ff0e1271d7d50012d96ec89a3'
AUTH_TOKEN = 'edaf33cf519a6efe6c8991f8bd397047'
FROM_NUMBER = '+15083926124 '
TO_NUMBER = '+918077423699'

sms = Sms(SSID, AUTH_TOKEN, TO_NUMBER, FROM_NUMBER)

print(json.loads(Mybolt.isOnline())['value'])
while True:
    response = Mybolt.analogRead('A0')
    data = json.loads(response)
    print(data['value'])
    try:
        sensor_value = int(data['value'])
        print(sensor_value)
        if sensor_value < 1020:
            #response = sms.send_sms(" an unwanted access")
            response = Mybolt.digitalWrite('4', 'HIGH')
            break

    except Exception as e:
        print("error", e)
        time.sleep(10000)
Exemple #11
0
    except e:
        print("There was an error while parsing the response: ", e)
        continue

    bound = compute_bounds(history_data, conf.FRAME_SIZE, conf.MUL_FACTOR)
    if not bound:
        required_data_count = conf.FRAME_SIZE - len(history_data)
        print("Not enough data to compute Z-score. Need ", required_data_count,
              " more data points")
        history_data.append(int(data['value']))
        time.sleep(10)
        continue

    try:
        if sensor_value > bound[0]:
            buzz = mybolt.digitalWrite('1', "HIGH")
            print(buzz)
            print("Temperature Altered anomously, sending alerts!")
            """ SMS """
            print("The temperature level increased suddenly. Sending an SMS")
            response = sms.send_sms(
                "Someone Opened the Refrigerator, The temperature has raised to:"
                + str(sensor_value))
            print("This is the response ", response)
            """ MAIL """
            print("Making request to Mailgun to send an email")
            response = mailer.send_email(
                "Alert",
                "The Current temperature sensor value is " + str(sensor_value))
            response_text = json.loads(response.text)
            print("Response received from Mailgun is:" +
Exemple #12
0
        print("There was an error while parsing the response: ", e)
        continue

    bound = compute_bounds(history_data, conf.FRAME_SIZE, conf.MUL_FACTOR)
    if not bound:
        required_data_count = conf.FRAME_SIZE - len(history_data)
        print("Not enough data to compute Z-score. Need ", required_data_count,
              " more data points")
        history_data.append(int(data['value']))
        time.sleep(10)
        continue

    try:
        if sensor_value > bound[0]:
            print("Someone is at the Door")
            resp = mybolt.digitalWrite('0', 'HIGH')
            print(resp)
            response = sms.send_sms(
                "Someone is Standing on the door. Open the gate")
            print("This is the response ", response)
        elif sensor_value < bound[1]:
            print("Someone is at the Door")
            resp = mybolt.digitalWrite('0', 'HIGH')
            print(resp)
            response = sms.send_sms(
                "Someone is Standing on the door. Open the gate")
            print("This is the response ", response)
        history_data.append(sensor_value)
    except Exception as e:
        print("Error", e)
    time.sleep(10)  #time interval
Exemple #13
0
import time
import requests
from boltiot import Bolt

SELLING_PRICE = 1720.56
API_KEY = "XXXX"        # Replace with your API key
DEVICE_ID = "XXXXX"     # Replace with your Device ID

bolt = Bolt(API_KEY, DEVICE_ID)


def price_check():
    url = "https://min-api.cryptocompare.com/data/price"
    query_string = {"fsym":"BTC", "tsyms":"USD"}
    response = requests.request("GET", url, params=query_string)
    response = json.loads(response.text)
    current_price = response["USD"]
    return current_price


while True:
    market_price = price_check()
    print("Market price is :", market_price)
    print("Selling price is :", SELLING_PRICE)
    if market_price > SELLING_PRICE:
        bolt.digitalWrite("0", "HIGH")
        time.sleep(5)
        bolt.digitalWrite("0", "LOW")
        continue
    time.sleep(5)
    temperature = sensor_value / 10.24
    print("The temperature right now is ", temperature, "degree celsius")
    bound = compute_bounds(history_data, conf.frame_size, conf.multi_factor)

    if not bound:
        required_data_count = conf.frame_size - len(history_data)
        print("Not enough data to compute Z-score. Need ", required_data_count,
              " more data points")
        history_data.append(int(data['value']))
        time.sleep(30)
        continue

    try:
        if sensor_value > bound[0]:
            print("The temperature has risen suddenly.")
            response = mybolt.digitalWrite("1", 'HIGH')
            time.sleep(5)
            response = mybolt.digitalWrite("1", 'LOW')
            print(response)
        if sensor_value < bound[1]:
            print("The temperature has decreased suddenly.")
            response = mybolt.digitalWrite("3", 'HIGH')
            time.sleep(5)
            response = mybolt.digitalWrite("3", 'LOW')
            print(response)

        history_data.append(sensor_value)
    except Exception as e:
        print("Error", e)
    time.sleep(30)
 print(recv_data)
 if ((recv_data) == ''):
     print("Arduino is starting")
     time.sleep(5)
 elif ((recv_data) == 'Command timed out'):
     print("Command Timed out")
 elif (((recv_data) == '\n') or ((recv_data) == '\r')):
     print("")
 else:
     time.sleep(5)
     x = re.findall("\D", recv_data)
     if (x):
         continue
     elif int(recv_data) < 20:
         print(recv_data)
         mybolt.digitalWrite(0, 'HIGH')
         mydb = mysql.connector.connect(host="localhost",
                                        user="******",
                                        passwd="123",
                                        database="sensor")
         mySql_insert_query = """INSERT INTO analysis (Distance_at_cm,LED_status,Connected_device) VALUES ('Less than 20 cm','1','BOLT_IOT & ARDUINO') """
         cursor = mydb.cursor()
         cursor.execute(mySql_insert_query)
         mydb.commit()
         cursor.close()
         print(cursor.rowcount, "record inserted.")
         time.sleep(5)
     elif int(recv_data) > 20:
         mybolt.digitalWrite(0, 'LOW')
         mydb = mysql.connector.connect(host="localhost",
                                        user="******",
import conf
from boltiot import Sms, Bolt
import json, time

minimum_limit = 90
maximum_limit = 136

mybolt = Bolt(conf.API_KEY, conf.DEVICE_ID)
sms = Sms(conf.SID, conf.AUTH_TOKEN, conf.TO_NUMBER, conf.FROM_NUMBER)

while True:
    print("Reading sensor value")
    response = mybolt.analogRead('A0')
    data = json.loads(response)
    print("Sensor value is: " + str(data['value']))
    try:
        sensor_value = int(data['value'])
        if sensor_value > maximum_limit or sensor_value < minimum_limit:
            print(mybolt.digitalWrite('0', 'HIGH'))

            print("Making request to Twilio to send a SMS")
            response = sms.send_sms(
                "ALERT!!! INTRUDER DETECTED turning on the security alarm as the sensor value has reached "
                + str(sensor_value))
            print("Response received from Twilio is: " + str(response))
            print("Status of SMS at Twilio is :" + str(response.status))
    except Exception as e:
        print("Error occured: Below are the details")
        print(e)
    time.sleep(4)
    tag = soup("span")
    Effected_people = tag[4].contents[0]
    for i in range(9):
        if i == 1 or i == 5:
            continue
        y = y + Effected_people[i]
    x = int(y)
    return (x)


#———————Execution starts from here————————————
Effected_people = getting_value()
apikey = input("Enter API Key")
Bolt_id = input("Enter the Bolt_ID")
device = Bolt(apikey, Bolt_id)
for i in range(1000):
    print(device.isOnline())
    response = device.serialBegin(9600)
    x = getting_value()
    z = checking1(x, 0)
    response2 = device.serialWrite(x)
    print(response2)
    time.sleep(100)  #time.sleep(100) with delay for execution for 100 sec
    y = getting_value()
    z = checking1(y, 1)
    response2 = device.serialWrite(y)
    if (z == 1):
        device.digitalWrite('0', 'HIGH')
        time.sleep(5)
        device.digitalWrite('0', 'LOW')
#Sends telegram message to particular telegram channel
def send_telegram_message(message):
    """Sends message via Telegram"""
    url = "https://api.telegram.org/" + telegram_bot_id + "/sendMessage"
    data = {"chat_id": telegram_chat_id, "text": message}
    try:
        response = requests.request("POST", url, params=data)
        telegram_data = json.loads(response.text)
        return telegram_data["ok"]
    except Exception as e:
        print("An error occurred in sending the alert message via Telegram")
        print(e)
        return False


response = mybolt.digitalWrite('0', 'HIGH')  #ACK PIN Setted
data = json.loads(response)
time.sleep(3)

#Since Receiver should be always ready,hence permanent loop
while 1:
    response = mybolt.digitalRead('3')  #ACK PIN
    data = json.loads(response)

    #Low ACK pin means active transission
    if int(data['value']) == 0:
        print("Found Info!!")
        flag = 1
        #Is kept high because on transmitter part there might be delay mismatch so it waits for data
        while flag:
            time.sleep(10)
Exemple #19
0
        if data["success"] != 1:
            print("Request not successfull")
            print("This is the response->", data)
            return -999
        sensor_value = int(data["value"])
        return sensor_value
    except Exception as e:
        print("Something went wrong when returning the sensor value")
        print(e)
        return -999


while True:
    print("*******************************")
    print("Loop Starting")
    mybolt.digitalWrite("2", "HIGH")  # Both buzzer and led will be 'ON' which
    mybolt.digitalWrite("1",
                        "HIGH")  # indicate that the loop has started and you
    time.sleep(0.5)  # need to place the temperature sensor
    mybolt.digitalWrite("2", "LOW")  # between your arms
    mybolt.digitalWrite("1", "LOW")
    print(
        "Reading time 15 secs")  # Read the temperature of your body for 15 sec
    time.sleep(15)
    sensor_value = get_sensor_value_from_pin("A0")
    print(sensor_value)

    if (sensor_value > threshold):  # true, means the Person has fever
        print("Making request to Twilio to send a SMS")
        response = sms.send_sms(
            "Alert! The Person has fever. Body temperure is" +
import requests, time, math, json
from boltiot import Bolt
import conf2 as conf	#my Configuration File

data = [] 	#Empty list for storing sensor values...
mybolt = Bolt(conf.bolt_api_key, conf.device_id) #My Bolt
mybolt.digitalWrite(0,"LOW")

#Function:Get Sensor Value
def get_sv(pin):
	try:
		response = mybolt.analogRead(pin)
		data = json.loads(response)
		if data["success"]!=1:
			print("Rquest Failed")
			print("Response:",data)
			return -999
		sensor_value = int(data["value"])
		return sensor_value
	except Exception as e:
		print("Something went wrong")
		print(e)
		return -999

#Function:Send Telegram Message
def send_tm(message):
	url = "https://api.telegram.org/"+conf.telegram_bot_id+"/sendMessage"
	data = {
		"chat_id":conf.telegram_chat_id,
		"text":message
	}
Exemple #21
0
    response = check_device_status()
    if response != True:
        time.sleep(10)
        continue
    # Step 2 : Sending Welcome message with options.
    message = "Welcome to Advanced Irrigation System\nMade with ❤\n" + "-" * 55 + "\nSelect Mode -\n1. Manual ON\n2. Manual OFF\n3. AUTO\n4. Venting Mode"
    response = send_telegram_message(message)
    if response != True:
        continue
    time.sleep(10)
    # Step 3 : Getting last message from telegram
    text, message_id = get_last_message()
    # Step 4 : Checking with previous message & message_id
    if (text != last_text) or (message_id != last_message_id):
        if (text == "1") or (text == "Manual on") or (text == "manual on"):
            mybolt.digitalWrite('1', 'HIGH')
            mybolt.digitalWrite('2', 'HIGH')

            message = "Manual ON active, Irrigation valve fully open!"
            print(message)
            r = requests.get(
                'https://cloud.boltiot.com/remote/5aa5c2bf-f593-42a7-9a08-c0406022333e/servoMultiWrite?pins=3,4&values=180,0&deviceName=BOLT3848684'
            )
            send_telegram_message(message)
        elif (text == "2") or (text == "Manual OFF") or (text == "manual off"):
            mybolt.digitalWrite('1', 'LOW')
            mybolt.digitalWrite('2', 'LOW')

            message = "Manual OFF active, Irrigation valve fully closed!"
            print(message)
            r = requests.get(
from boltiot import Bolt
import time
api_key = "445c90a1-ce8b-4621-99c1-ce356fb17eef"
device_id = "BOLT6094114"
mybolt = Bolt(api_key, device_id)
response = mybolt.digitalWrite('0', 'HIGH')
print(response)
time.sleep(5)
response = mybolt.digitalWrite('0', 'LOW')
print(response)
Exemple #23
0
    client = twilio.rest.Client(account_sid, auth_token)

    message = client.messages \
        .create(
             body='There has been a breach in your house.',
             from_='+12563872330',#this remains the same
             to='+16695006489' #keep your phone number here
         )


while True: #Infinite loop
    while alarm == 0: #If alarm is off
        response = mybolt.digitalRead('3') #check if it is being activated
        if (response == HIGH):
            print("Security System is activated")
            mybolt.digitalWrite('2', 'HIGH') #Turn on LED to indicate Aalarm is activated
            mybolt.digitalWrite('4', 'LOW')
            alarm = 1
        elif (response == LOW):
            print ("Waiting for Security System to be activated....")
        else:
            print ("Probelm in getting value from pin 3")
        time.sleep(5) #check once in every 5 seconds to avoid exceeding API rate lmit


    while alarm == 1: #If alarm is on
        response = mybolt.digitalRead('4') #check is it is being de-activated
        if (response == HIGH):
            print("Security System is De-activated")
            mybolt.digitalWrite('2', 'LOW')#Turn off LED to indicate Aalarm is De-activated
            mybolt.digitalWrite('3', 'LOW')
from firebase import firebase
from boltiot import Bolt
api_key ="2618ae2f-37a9-4eb7-9da1-29b1708258f2"
device_id ="BOLT14856162"
mybolt = Bolt(api_key,device_id)
connect=firebase.FirebaseApplication("https://siva-iot-light.firebaseio.com/", None)
while True:
    a = connect.get("/sivaiotlight/",None)
    b=a.get("off")
    if b == "1":
        mybolt.digitalWrite('0','HIGH')
    else:
        mybolt.digitalWrite('0','LOW')
    print(b)
Exemple #25
0

def send_message(message):

    url = "https://api.telegram.org/" + bolt_conf.telegram_bot_id + "/sendMessage"
    data = {"chat_id": bolt_conf.telegram_chat_id, "text": message}
    try:
        response = requests.request("POST", url, params=data)
        print("Telegram Response from request:", response.text)
        telegram_response = json.loads(response.text)
        return telegram_response["ok"]
    except Exception as e:
        print("An error occured in sending price alert")
        print(e)
        return False


while True:

    if get_bitcoin_price() != set_price:

        message = "Alert ! Price changed to: " + str(get_bitcoin_price())
        bit_amu_bot = send_message(message)
        print(bit_amu_bot)
        for i in range(1, 10):
            if i % 2 == 0:
                buzz_active = buzzer.digitalWrite("0", "HIGH")
            else:
                buzz_active = buzzer.digitalWrite("0", "LOW")
    time.sleep(30)