Exemplo n.º 1
0
    def on(self):
        self.mode_servo()

        for _ in range(2):
            time.sleep(0.5)
            kit.servo[SWITCH_CHANNEL].angle = 170
            time.sleep(1)
            kit.servo[SWITCH_CHANNEL].angle = 90

        firebase_controller.log_event('AUXDEVICES', 'Switch On')

        return 'mute'
Exemplo n.º 2
0
    def off(self):
        self.mode_servo()


        kit.servo[SWITCH_CHANNEL].angle = 0
        time.sleep(1)
        kit.servo[SWITCH_CHANNEL].angle = 90


        firebase_controller.log_event('AUXDEVICES', 'Switch Off')


        return 'mute'
Exemplo n.º 3
0
def enable_privacy():
    global privacy_mode

    firebase_controller.log_event('SYS', '~ mode enabled')

    led_queue.put(['privacy', True])

    privacy_mode = True

    with open('privacy', 'w') as file:
        file.write('True')

    mail_controller.send_mail('Privacy Mode Enabled', '  has been enabled.', [])
Exemplo n.º 4
0
    def __init__(self, pwm_queue_in, shared_callback_dict_in):
        self.pwm_queue = pwm_queue_in

        self.led_queue = multiprocessing.Queue()

        self.command_queue = multiprocessing.Queue()

        self.shared_callback_dict = shared_callback_dict_in

        self.alarm_command_queue = multiprocessing.Queue()

        sensor_process = multiprocessing.Process(target=self.sensor_processor,
                                                 args=())
        sensor_process.start()

        led_process = multiprocessing.Process(target=self.led_processor,
                                              args=())
        led_process.start()

        firebase_controller.log_event('SYSTEMSTATE', 'System online')
Exemplo n.º 5
0
    def sensor_processor(self):
        # TODO

        # camera feed kill code
        # read/write only sections in db

        # Db schema
        # /users
        #   |- user stuff
        # /logs
        #   |- logs obviously
        # /settings
        #   |- system state
        #   |   |- armed status
        #   |   |- alarm status
        #   |   |- ready status
        #   |   |- grace period
        #   |- sensor data
        #   |   |- sensor x -> x pin, status
        # /instructions
        #   |- armed

        # LED Patterms
        # Startup -
        # Sensor open - Red blink
        # Sensor closed - Blue blink
        # Sensor closed (ready) - Green blink
        # Armed (Action) -
        # Disarmed (Action) - Green blink
        # Armed (status) - Red pulsing
        # Alarm - alarm

        # pin : {'state': True/False, 'name': name}
        try:
            sensors = firebase_admin.firestore.client(app=None).collection(
                'settings').document('sensorConfig').get().to_dict()
        except:
            traceback.print_exc()
            sensors = {
                '4': {
                    'open': False,
                    'name': 'Zone A',
                    'time_opened': -1
                },
                '17': {
                    'open': False,
                    'name': 'Zone B',
                    'time_opened': -1
                }
            }

        desk_light_relay = LED(27)
        desk_light_relay.on()

        print('Sensor Config:', sensors)

        self.setup_pins(sensors)

        # Get current state from db first
        system_state = {
            'silent': False,
            'armed': False,
            'ready': None,
            'alarm': False,
            'deskON': False
        }

        try:
            old_system_state = firebase_admin.firestore.client(
                app=None).collection('settings').document(
                    'systemState').get().to_dict()

            print(old_system_state)

            if old_system_state['armed']:
                self.command_queue.put(['ARM', None])

            if old_system_state['deskON']:
                self.command_queue.put(['DESKON', None])

            if old_system_state['silent']:
                self.command_queue.put(['SILENT', None])

        except:
            traceback.print_exc()

        #sensors_ref.set(sensors)
        #system_state_ref.set(system_state)

        firebase_controller.update_system_state(system_state)
        firebase_controller.update_sensor_state(sensors)

        while True:

            old_system_state = copy.deepcopy(system_state)
            old_sensors = copy.deepcopy(sensors)

            secured = True

            # Check sensors
            for i in sensors:

                try:
                    sensor_open = GPIO.input(int(i)) == GPIO.LOW

                    if sensor_open:
                        secured = False

                    if sensor_open != sensors[i]['open']:
                        sensors[i]['open'] = sensor_open

                        if sensor_open:
                            self.led_queue.put(['sensor_opened', True])

                            sensors[i]['time_opened'] = time.time()

                            firebase_controller.log_event(
                                'SENSOR',
                                'SENSOR OPENED: ' + sensors[i]['name'])

                        else:
                            self.led_queue.put(['sensor_closed', True])

                            firebase_controller.log_event(
                                'SENSOR',
                                'SENSOR CLOSED: ' + sensors[i]['name'])

                        print('Status changed - OPEN: %s, SENSOR: %s' %
                              (sensor_open, sensors[i]['name']))

                        # Update db
                        # Update log

                except:
                    print('Something went wrong')
                    traceback.print_exc()

            # State update
            if system_state['ready'] != secured:
                if system_state[
                        'armed'] and not secured and not system_state['alarm']:

                    self.alarm_command_queue.put(sensors)

                    print('ALARM!')

                    self.led_queue.put(['flashlight', True])

                    if system_state['silent']:
                        firebase_controller.log_event(
                            'ALARM', 'ALARM TRIGGERED! (SILENT)')

                        self.alarm_command_queue.put('silent')
                    else:
                        firebase_controller.log_event('ALARM',
                                                      'ALARM TRIGGERED!')

                    if not system_state['silent']:

                        system_state['alarm'] = True

                        self.led_queue.put(['alarm', True])

                        self.pwm_queue.put('on')

                        time.sleep(1)

                        self.pwm_queue.put('alarm')

                if secured:
                    # led_queue.put(['ready_status', True])
                    self.led_queue.put(['open_status', False])
                else:
                    # led_queue.put(['ready_status', False])
                    self.led_queue.put(['open_status', True])

            system_state['ready'] = secured

            # Check commands
            try:
                command, callback_id = self.command_queue.get_nowait()

                if command == 'ARM':

                    if system_state['ready'] and not system_state['armed']:
                        system_state['armed'] = True

                        self.led_queue.put(['armed', True])
                        self.led_queue.put(['armed_status', True])

                        self.pwm_queue.put('mode_change')

                        firebase_controller.log_event('SYSTEMSTATE',
                                                      'SYSTEM ARMED')

                        self.shared_callback_dict[callback_id] = [
                            200, {
                                "status": "System armed"
                            }
                        ]
                    else:
                        self.led_queue.put(['error', True])
                        print('System not ready')

                        self.pwm_queue.put('error')

                        if system_state['armed']:
                            self.shared_callback_dict[callback_id] = [
                                500, {
                                    "status": "System already armed"
                                }
                            ]
                        else:
                            self.shared_callback_dict[callback_id] = [
                                500, {
                                    "status": "System not ready"
                                }
                            ]

                elif command == 'DISARM':

                    if system_state['armed']:
                        system_state['armed'] = False

                        self.led_queue.put(['armed_status', False])
                        self.led_queue.put(['alarm', False])
                        self.alarm_command_queue.put(False)
                        self.led_queue.put(['flashlight', False])
                        self.led_queue.put(['disarmed', True])

                        self.pwm_queue.put('mute')
                        self.pwm_queue.put('mode_change')

                        firebase_controller.log_event('SYSTEMSTATE',
                                                      'SYSTEM DISARMED')

                        #TODO                #Cancel alarm

                        system_state['alarm'] = False

                        self.shared_callback_dict[callback_id] = [
                            200, {
                                "status": "System disarmed"
                            }
                        ]

                    else:
                        self.led_queue.put(['error', True])
                        print('System not ready')

                        self.pwm_queue.put('error')

                        self.shared_callback_dict[callback_id] = [
                            500, {
                                "status": "System not armed"
                            }
                        ]

                elif command == 'WATCHING':
                    self.led_queue.put(['camera_watched', True])

                elif command == 'NOWATCHING':
                    self.led_queue.put(['camera_watched', False])

                elif command == 'RECORDING':
                    self.led_queue.put(['recording', True])

                elif command == 'NORECORDING':
                    self.led_queue.put(['recording', False])

                elif command == 'DESKON':

                    system_state['deskON'] = True

                    desk_light_relay.off()

                    self.shared_callback_dict[callback_id] = [
                        200, {
                            "status": "Light on!"
                        }
                    ]

                elif command == 'DESKOFF':

                    system_state['deskON'] = True

                    desk_light_relay.on()

                    time.sleep(0.5)

                    desk_light_relay.off()

                    self.shared_callback_dict[callback_id] = [
                        200, {
                            "status": "Light off!"
                        }
                    ]

                elif command == 'SILENT':
                    system_state['silent'] = True

                    self.led_queue.put(['silent', True])

                    self.shared_callback_dict[callback_id] = [
                        200, {
                            "status": "Silent mode enabled"
                        }
                    ]

                elif command == 'UNSILENT':
                    system_state['silent'] = False

                    self.led_queue.put(['silent', False])

                    self.shared_callback_dict[callback_id] = [
                        200, {
                            "status": "Silent mode disabled"
                        }
                    ]
                else:
                    print('What is this command? ' + command)

            except queue.Empty:
                pass

            except:
                traceback.print_exc()

            if old_system_state != system_state:
                # Something has changed
                #system_state_ref.set(system_state)

                firebase_controller.update_system_state(system_state)

            if old_sensors != sensors:
                # Something has changed
                #sensors_ref.set(sensors)

                firebase_controller.update_sensor_state(sensors)

                self.pwm_queue.put('zone_change')

            for s in sensors:
                last_time = sensors[s]['time_opened']

                if sensors[s]['open']:
                    if time.time(
                    ) - last_time > 5 * 60 and last_time != -1:  # More than 5 minutes have passed

                        mail_controller.send_mail(
                            'Zone open!',
                            'Sensor "%s" has been open since %s!' %
                            (sensors[s]['name'],
                             datetime.datetime.fromtimestamp(last_time)), [])

                        print('Reminder email sent!')

                        sensors[s][
                            'time_opened'] = -1  # So we don't get spammed

            # Fixes bounce issues
            time.sleep(0.1)
Exemplo n.º 6
0
    def do_GET(self):

        global active_connections, privacy_mode

        if privacy_mode:
            self.send_response(500)
            self.send_header('Content-type', 'application/json')
            self.end_headers()

            self.wfile.write(b'{"status": "Unknown Error"}')

            traceback.print_exc()
            print(self.path)

            return

        print('Camera request')

        try:
            path, user = self.path[1:].split('?')

            frame_name = int(path)

            # If frame is in valid domain
            if 0 <= frame_name < len(frames):

                self.send_response(200)
                self.send_header('Content-type', 'multipart/x-mixed-replace; boundary=--jpgboundary')
                self.end_headers()

                if user != 'INTERNAL':
                    firebase_controller.log_event('CAMERA', user + ' is watching the feed')
                    active_connections += 1

                if user not in watching:
                    watching[user] = 0

                watching[user] += 1

                firebase_controller.update_watching(watching)

                if active_connections == 1:
                    command_queue.put(['WATCHING', None])

                # Start frame send loop
                while True:
                    try:

                        if privacy_mode:
                            raise Exception

                        # Get frame
                        img = frames[frame_name]()[1]

                        # Turn greyscale
                        imgRGB = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)

                        jpg = Image.fromarray(imgRGB)

                        # Convert frame to jpg byte magic
                        with BytesIO() as output:
                            jpg.save(output, format='JPEG')

                            self.wfile.write(b"--jpgboundary")
                            self.send_header('Content-type', 'image/jpeg')
                            self.send_header('Content-length', str(len(output.getvalue())))
                            self.end_headers()

                            jpg.save(self.wfile, format='JPEG')

                            # Delay to maintain framerate
                            # Too low and frames will buffer
                            # Too high and framerate will suffer

                            time.sleep(0.05)
                    except:
                        print('Ayy it broke')

                        if user != 'INTERNAL':
                            firebase_controller.log_event('CAMERA', user + ' terminated the feed')
                            active_connections -= 1

                        watching[user] -= 1

                        firebase_controller.update_watching(watching)


                        if active_connections == 0:
                            command_queue.put(['NOWATCHING', None])

                        traceback.print_exc()
                        break



        except:

            self.send_response(500)
            self.send_header('Content-type', 'application/json')
            self.end_headers()

            self.wfile.write(b'{"status": "Unknown Error (wtf you broke something)"}')

            traceback.print_exc()
            print(self.path)

            return
Exemplo n.º 7
0
    def do_POST(self):

        global privacy_mode

        path = self.path[1:]

        callback_id = str(uuid.uuid4())

        #print(self.rfile.read(int(self.headers.get('Content-Length'))))

        if path == 'goodnight':

            pwm_queue.put('off')
            command_queue.put(['DESKOFF', callback_id])
            #command_queue.put(['ARM', callback_id])

            pass

        elif path == 'leaving':

            pwm_queue.put('countdown')
            led_queue.put(['countdown', time.time() + COUNTDOWN_DELAY])

            time.sleep(COUNTDOWN_DELAY)


            led_queue.put(['countdown', False])
            pwm_queue.put('off')
            command_queue.put(['DESKOFF', callback_id])

            with open('privacy', 'w') as file:
                file.write('True')
            time.sleep(2)

            command_queue.put(['ARM', callback_id])

            pass

        elif path == 'home':

            now = int(time.strftime('%H:%M:%S').split(':')[0])

            command_queue.put(['DESKON', callback_id])

            if 7 > now or now >= 17:
                pwm_queue.put('on')

                time.sleep(5)

            command_queue.put(['DISARM', callback_id])


            pass

        elif path == 'arm':

            command_queue.put(['ARM', callback_id])

            self.handle_callback(callback_id)

            return

        elif path == 'disarm':

            command_queue.put(['DISARM', callback_id])

            self.handle_callback(callback_id)

            return

        elif path == 'lightON':

            firebase_controller.log_event('AUXDEVICES', 'Flashlight On')

            led_queue.put(['flashlight', True])

            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()

            self.wfile.write(b'{"status": "Command queued"}')

            return

        elif path == 'lightOFF':

            firebase_controller.log_event('AUXDEVICES', 'Flashlight Off')

            led_queue.put(['flashlight', False])

            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()

            self.wfile.write(b'{"status": "Command queued"}')

            return

        elif path == 'popomode':

            firebase_controller.log_event('AUXDEVICES', 'Popo mode')

            led_queue.put(['alarm', True])

            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()

            self.wfile.write(b'{"status": "Command queued"}')

            return

        elif path == 'privacyON':


            enable_privacy()

            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()

            self.wfile.write(b'{"status": "Done."}')

            return

        elif path == 'privacyOFF':

            firebase_controller.log_event('SYS', '~ mode disabled')

            led_queue.put(['privacy', False])

            privacy_mode = False

            os.remove('privacy')

            #with open('privacy', 'w') as file:
            #    file.write('False')

            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()

            self.wfile.write(b'{"status": "Done."}')

            return

        elif path == 'discomode':

            firebase_controller.log_event('AUXDEVICES', 'Disco mode')

            command_queue.put(['DESKOFF', callback_id])
            pwm_queue.put('off')
            led_queue.put(['rainbow', True])

            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()

            self.wfile.write(b'{"status": "Command queued"}')

            return


        elif path == 'nodiscomode':

            firebase_controller.log_event('AUXDEVICES', 'No disco mode')

            led_queue.put(['rainbow', False])

            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()

            self.wfile.write(b'{"status": "Command queued"}')

            return



        elif path == 'switchON':

            pwm_queue.put('on')

            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()

            self.wfile.write(b'{"status": "Command queued"}')

            return

        elif path == 'switchOFF':

            pwm_queue.put('off')

            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()

            self.wfile.write(b'{"status": "Command queued"}')

            return

        elif path == 'deskON':

            command_queue.put(['DESKON', callback_id])

            firebase_controller.log_event('AUXDEVICES', 'Desk light On')

            self.handle_callback(callback_id)

            return

        elif path == 'deskOFF':

            command_queue.put(['DESKOFF', callback_id])

            firebase_controller.log_event('AUXDEVICES', 'Desk light Off')

            self.handle_callback(callback_id)

            return

        elif path == 'SILENT':

            command_queue.put(['SILENT', callback_id])

            firebase_controller.log_event('SYSTEM', 'SILENT MODE ENABLED')


            mail_controller.send_mail('Silent Mode Enabled', 'Silent mode has been enabled.', [])


            self.handle_callback(callback_id)

            return

        elif path == 'UNSILENT':

            command_queue.put(['UNSILENT', callback_id])

            firebase_controller.log_event('SYSTEM', 'SILENT MODE DISABLED')

            self.handle_callback(callback_id)

            return

        elif path == 'heartbeat':

            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()

            return

        elif path == 'reboot':

            print('Me Reboot')

            firebase_controller.log_event('SYSTEM', 'Reboot command issued.')
            os.system('sudo reboot')

            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()

            self.wfile.write(b'{"status": "Executed"}')

            return

        elif path == 'pcsuspend':

            firebase_controller.log_event('AUX', 'Suspend PC command issued.')
            os.system('sudo -u pi ssh -oStrictHostKeyChecking=no %s "suspend"' % e['PC_ADDRESS'])

            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()

            self.wfile.write(b'{"status": "Executed"}')

            return


        elif path == 'pclock':

            firebase_controller.log_event('AUX', 'Lock PC command issued.')
            os.system('sudo -u pi ssh -oStrictHostKeyChecking=no %s "lock"' % e['PC_ADDRESS'])

            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()

            self.wfile.write(b'{"status": "Executed"}')

            return