示例#1
0
def main():

    value = "Jarvis Focus"

    # Grove - 16x2 LCD(White on Blue) connected to I2C port
    lcd = JHD1802()

    display_in_lcd(lcd, 0, value)
    time.sleep(2)
    display_in_lcd(lcd, 0, "Identify")
    display_in_lcd(lcd, 1, "Temp-Humi")
    time.sleep(2)
    # Grove - Light Sensor connected to port A0
    light_sensor = GroveLightSensor(0)

    # Range Sensor - D24
    ultrasonic_range_senor = GroveUltrasonicRanger(24)

    # Motion Sensor - D18
    motion_sensor = GroveMiniPIRMotionSensor(18)

    # Grove - Temperature&Humidity Sensor connected to port D5
    climate_sensor = DHT('11', 5)

    # Grove - LED Button connected to port D16
    button = GroveLedButton(16)

    def on_detect():
        print('motion detected')
        
    motion_sensor.on_detect = on_detect

    def on_event(index, event, tm):
        if event & Button.EV_SINGLE_CLICK:
            print('single click')
            button.led.light(True)

        elif event & Button.EV_LONG_PRESS:
            print('long press')
            button.led.light(False)
    button.on_event = on_event
    
    while True:
        distance = ultrasonic_range_senor.get_distance()
        print('{} cm'.format(distance))
        light_sensor_output = light_sensor.light
        humi, temp = climate_sensor.read()
        row_one = f"L:{light_sensor_output}"
        row_two = f"H:{humi}-T:{temp}"
        display_in_lcd(lcd, 0, row_one)
        display_in_lcd(lcd, 1, row_two)
        time.sleep(2)
示例#2
0
def main():
    ledbtn = GroveLedButton(5)

    while True:
        ledbtn.led.light(True)
        time.sleep(1)

        ledbtn.led.light(False)
        time.sleep(1)
示例#3
0
def main():
    print("Initializing")
    now = int(time.time())
    # Grove - LED Button connected to port D5
    button = GroveLedButton(16)

    def on_event(index, event, tm):
        if event & Button.EV_SINGLE_CLICK:
            print(f"Button Clicked")
            capture()

    button.on_event = on_event

    print("Registering event for button")

    while True:
        now = int(time.time())
        time.sleep(1)
示例#4
0
def main():
    # Grove - LED Button connected to port D5
    button = GroveLedButton(5)

    # Grove - Buzzer connected to PWM port
    buzzer = upmBuzzer.Buzzer(getGpioLookup('GPIO12'))

    def on_event(index, event, tm):
        if event & Button.EV_SINGLE_CLICK:
            print('single click')
            button.led.light(True)
            buzzer.playSound(upmBuzzer.BUZZER_DO, 500000)

        elif event & Button.EV_LONG_PRESS:
            print('long press')
            button.led.light(False)
            buzzer.playSound(upmBuzzer.BUZZER_DO, 1000000)

    button.on_event = on_event

    while True:
        time.sleep(1)
示例#5
0
def main():

    # Grove - Servo connected to PWM port
    servo = GroveServo(12)
    servo_angle = 90

    # Grove - mini PIR motion pir_sensor connected to port D5
    pir_sensor = GroveMiniPIRMotionSensor(5)

    # Grove - Ultrasonic Ranger connected to port D16
    ultrasonic_sensor = GroveUltrasonicRanger(16)

    # Grove - LED Button connected to port D18
    button = GroveLedButton(18)

    # Grove - Moisture Sensor connected to port A0
    moisture_sensor = GroveMoistureSensor(0)

    # Grove - Light Sensor connected to port A2
    light_sensor = GroveLightSensor(2)
    light_state = False

    # Grove - Temperature&Humidity Sensor connected to port D22
    dht_sensor = DHT('11', 22)

    # Callback for server RPC requests (Used for control servo and led blink)
    def on_server_side_rpc_request(request_id, request_body):
        log.info('received rpc: {}, {}'.format(request_id, request_body))
        if request_body['method'] == 'getLedState':
            client.send_rpc_reply(request_id, light_state)
        elif request_body['method'] == 'setLedState':
            light_state = request_body['params']
            button.led.light(light_state)
        elif request_body['method'] == 'setServoAngle':
            servo_angle = float(request_body['params'])
            servo.setAngle(servo_angle)
        elif request_body['method'] == 'getServoAngle':
            client.send_rpc_reply(request_id, servo_angle)

    # Connecting to ThingsBoard
    client = TBDeviceMqttClient(thingsboard_server, access_token)
    client.set_server_side_rpc_request_handler(on_server_side_rpc_request)
    client.connect()

    # Callback on detect the motion from motion sensor
    def on_detect():
        log.info('motion detected')
        telemetry = {"motion": True}
        client.send_telemetry(telemetry)
        time.sleep(5)
        # Deactivating the motion in Dashboard
        client.send_telemetry({"motion": False})
        log.info("Motion alert deactivated")

    # Callback from button if it was pressed or unpressed
    def on_event(index, event, tm):
        if button._GroveLedButton__btn.is_pressed():
            log.debug('button: single click')
            telemetry = {"button_press": True}
            client.send_telemetry(telemetry)
            log.info("Pressed")
        else:
            log.debug('button: single click')
            telemetry = {"button_press": False}
            client.send_telemetry(telemetry)
            log.info("Unpressed")
        if event & Button.EV_SINGLE_CLICK:
            button.led.light(True)
        elif event & Button.EV_DOUBLE_CLICK:
            button.led.blink()
        elif event & Button.EV_LONG_PRESS:
            button.led.light(False)

    # Adding the callback to the motion sensor
    pir_sensor.on_detect = on_detect
    # Adding the callback to the button
    button.on_event = on_event
    try:
        while True:
            distance = ultrasonic_sensor.get_distance()
            log.debug('distance: {} cm'.format(distance))

            humidity, temperature = dht_sensor.read()
            log.debug('temperature: {}C, humidity: {}%'.format(
                temperature, humidity))

            moisture = moisture_sensor.moisture
            log.debug('moisture: {}'.format(moisture))

            log.debug('light: {}'.format(light_sensor.light))

            # Formatting the data for sending to ThingsBoard
            telemetry = {
                'distance': distance,
                'temperature': temperature,
                'humidity': humidity,
                'moisture': moisture,
                'light': light_sensor.light
            }

            # Sending the data
            client.send_telemetry(telemetry).get()

            time.sleep(.1)
    except Exception as e:
        raise e
    finally:
        client.disconnect()
示例#6
0
def on_resubscribe_complete(resubscribe_future):
    resubscribe_results = resubscribe_future.result()
    print("Resubscribe results: {}".format(resubscribe_results))

    for topic, qos in resubscribe_results['topics']:
        if qos is None:
            sys.exit("Server rejected resubscribe to topic: {}".format(topic))


lcd = JHD1802()
lcd.setCursor(0, 0)
lcd.write("Hello Raspberry")

# Grove - LED Button connected to port D22
button = GroveLedButton(22)


# Callback when the subscribed topic receives a message
def on_message_received(topic, payload, **kwargs):

    print("Received message from topic '{}': {}".format(topic, payload))
    lcd.setCursor(0, 0)
    lcd.write(str(payload))
    if ("led" in str(payload)):
        if ("true" in str(payload)):
            button.led.light(True)
        else:
            button.led.light(False)

    global received_count
def main():
    relay = GroveRelay(18)
    button = GroveLedButton(5)
    lcd = JHD1802()
    temp_humd_sensor = DHT('11',16)
    classifier = '/home/pi/Desktop/Application/haarcascade_frontalface_default.xml'
    lcd.setCursor(0,0)
    lcd.write("System Activated")
    def doorbell_ring(index,event,tm):
        if event & Button.EV_SINGLE_CLICK:
            time_string = datetime.datetime.now().strftime("%H:%M:%S")
            lcd.setCursor(0,0)
            lcd.write("Doorbell Pressed")
            print("[INFO]Doorbell Rung...")
            button.led.light(True)
            lcd.setCursor(1,0)
            lcd.write("Look at Camera  ")
            time.sleep(2)
            with picamera.PiCamera() as camera:
                camera.resolution = (320, 240)
                lcd.setCursor(1,0)
                lcd.write("3 2 1...        ")
                time.sleep(3)
                camera.capture(stream,format='jpeg')
                lcd.setCursor(1,0)
                lcd.write("Image Captured ")
                print("[INFO]Image Captured...")
            data = pickle.loads(open('/home/pi/Desktop/Application/encodings.pickle', "rb").read())
            buff = numpy.frombuffer(stream.getvalue(), dtype=numpy.uint8)
            image = cv2.imdecode(buff, 1)
            face_cascade = cv2.CascadeClassifier(classifier)
            gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
            rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
            faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1,minNeighbors=5, minSize=(30, 30),flags=cv2.CASCADE_SCALE_IMAGE)
            boxes = [(y, x + w, y + h, x) for (x, y, w, h) in faces]
            encodings = face_recognition.face_encodings(rgb, boxes)
            names = []
            face_detected = False
            for encoding in encodings:
                matches = face_recognition.compare_faces(data["encodings"],encoding)
                name = "Unknown"
                if True in matches:
                     matchedIdxs = [i for (i, b) in enumerate(matches) if b]
                     counts = {}
                     for i in matchedIdxs:
                         name = data["names"][i]
                         counts[name] = counts.get(name, 0) + 1
                     name = max(counts, key=counts.get)
                names.append(name)
            for ((top, right, bottom, left), name) in zip(boxes, names):
                cv2.rectangle(image, (left, top), (right, bottom),(0, 255, 0), 2)
                y = top - 15 if top - 15 > 15 else top + 15
                cv2.putText(image, name, (left, y), cv2.FONT_HERSHEY_SIMPLEX,0.75, (0, 255, 0), 2)
                face_detected = True
                if name != 'Unknown':
                     print("[INFO]Face Detected...")
                     print('[INFO] Entry Granted')
                     lcd.setCursor(0,0)
                     lcd.write("Welcome Home    ")
                     lcd.setCursor(1,0)
                     lcd.write("{}!          ".format(name))
                     relay.on()
                     print("[INFO] Door Locked")
                     time.sleep(5)
                     relay.off()
                else:
                     print('[INFO] Entry Denied ')
                     lcd.setCursor(0,0)
                     lcd.write("Face Unknown    ")
                     lcd.setCursor(1,0)
                     lcd.write("Contact Owner   ")
                     print('[INFO] Door Locked')
                     relay.off()
            if not face_detected:
               lcd.setCursor(0,0)
               lcd.write("No Face Detected ")
               lcd.setCursor(1,0)
               lcd.write("Try Again...     ")
            button.led.light(False)
            cv2.imwrite(path1+'/'+time_string+'.jpg',image)
            print("[INFO]Image Stored...\n")
            time.sleep(5)
            humidity,temperature = temp_humd_sensor.read()
            lcd.setCursor(0,0)
            lcd.write("Temperature: {0:2}C".format(temperature))
            lcd.setCursor(1,0)
            lcd.write("Humidity: {0:5}%".format(humidity))
    button.on_event = doorbell_ring
    while True:
            client_socket, address = server_socket.accept()
            print("[INFO] Connection Established")
            full_message = client_socket.recv(8)
            decoded_message = full_message.decode('utf-8')
            print('[INCOMING SIGNAL] {}'.format(decoded_message))
            if(decoded_message == '1'):
               relay.on()
               lcd.setCursor(0,0)
               lcd.write("Welcome Home!   ")
               lcd.setCursor(1,0)
               lcd.write("Door Unlocked...")
               print("[INFO] Door Open")
               time.sleep(3)
            elif (decoded_message == '2'):
               relay.off()
               lcd.setCursor(0,0)
               lcd.write("Entry Denied    ")
               lcd.setCursor(1,0)
               lcd.write("Door Locked...  ")
               print("[INFO] Door Closed")
               time.sleep(3)
            elif(decoded_message == '4'):
               try:
                  with picamera.PiCamera() as camera:
                         print("[INFO] Live Video Stream Started...")
                         while True:
                            client, address = server_socket.accept()
                            message = client.recv(8)
                            try:
                               check = message.decode('utf-8')
                               if(check == '1'):
                                  camera.capture('video.jpg')
                                  photo = 'video.jpg'
                                  file = open(photo,'rb')
                                  byte = file.read(1024)
                                  while(byte):
                                     client.send(byte)
                                     byte = file.read(1024)
                                  file.close()
                                  client.close()
                               elif(check == '0'):
                                  client.close()
                                  break
                            finally:
                               try:
                                  client.close()
                               finally:
                                  pass
               finally:
                   print("[INFO] Live Video Stream Ended...")
            elif(decoded_message == '5'):
                     humidity,temperature = temp_humd_sensor.read()
                     data  = str(humidity) + ' ' +  str(temperature)
                     client,address = server_socket.accept()
                     try:
                        client.send(data.encode('utf-8'))
                        client.close()
                     except:
                        try:
                          client.close()
                        except:
                          pass
            humidity,temperature = temp_humd_sensor.read()
            lcd.setCursor(0,0)
            lcd.write("Temperature: {0:2}C".format(temperature))
            lcd.setCursor(1,0)
            lcd.write("Humidity: {0:5}%".format(humidity))
示例#8
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
from grove.gpio import GPIO
from grove.factory import Factory
from grove.button import Button
from grove.grove_ryb_led_button import GroveLedButton

__all__ = ["GroveRelay"]

#------
# Global Variables
#------
button = GroveLedButton(5)
lcd = Factory.getDisplay("JHD1802")
relayPin = 12
totalTime = 5


class GroveRelay(GPIO):
    '''
    Class for Grove - Relay

    Args:
        pin(int): number of digital pin the relay connected.
    '''
    def __init__(self, pin):
        super(GroveRelay, self).__init__(pin, GPIO.OUT)

    def on(self):
        '''