Esempio n. 1
0
    def __init__(self, no_pi, base_url):
        self.base_url = base_url

        self.lcd = LCDManager(get_lcd_driver())
        self.lcd.start()
        self.upload_tracker = UploadTracker()
Esempio n. 2
0
    def __init__(self, no_pi, base_url):
        self.base_url = base_url

        self.lcd = LCDManager(get_lcd_driver())
        self.lcd.start()
        self.upload_tracker = UploadTracker()
Esempio n. 3
0
class Watcher(object):
    def __init__(self, no_pi, base_url):
        self.base_url = base_url

        self.lcd = LCDManager(get_lcd_driver())
        self.lcd.start()
        self.upload_tracker = UploadTracker()

    def initialize(self):
        work_dir = find_work_dir()

        if work_dir is None:
            raise RuntimeError('Can\'t find mimosa.json')

        logging.info('work dir found: %s', work_dir)

        try:
            self.config_file = os.path.join(work_dir, 'mimosa.json')
            self.config = json.loads(open(self.config_file).read())
        except Exception as e:
            raise RuntimeError('mimosa.json seems invalid')

        self.watch_dir = os.path.join(work_dir, 'to_upload')
        self.done_dir = os.path.join(work_dir, 'done')
        mkdir_if_not_exists(self.watch_dir)
        mkdir_if_not_exists(self.done_dir)

        logging.info('waiting for network manager to start')
        self.wait_for_network_manager_to_start()

        if not self.connect_to_wifi():
            raise RuntimeError('Can\'t find WiFi')

        logging.info('getting configuration updates')
        self.get_updates()

        if hasattr(self, 'need_to_reconnect_to_wifi'):
            self.lcd.write('Config Updated', 0)
            self.lcd.write('reconnecting...', 1)
            time.sleep(1)

            if not self.connect_to_wifi():
                raise RuntimeError('Can\'t find WiFi')

    def get_updates(self):
        url = '{}/config/{}'.format(self.base_url, self.config['username'])
        logging.info('config url: %s', url)

        try:
            config = requests.get(url).json()

            if 'error' in config:
                logging.error('server returned error when asking for config: %s', config['error'])
                return

            if config != self.config:
                logging.info('configuration changed!')
                if config['wifi'] != self.config['wifi']:
                    logging.info('wifi changed!')
                    self.need_to_reconnect_to_wifi = True
                else:
                    logging.info('wifi didn\'t change')

                self.config = config
                open(self.config_file, 'w').write(json.dumps(config))
            else:
                logging.info('configuration didn\'t change')
        except Exception:
            logging.exception('get updates')
         

    def wait_for_network_manager_to_start(self):
        while True:
            try:
                if pidof('NetworkManager'):
                    return
            except Exception:
                pass

            time.sleep(1)

    def connect_to_wifi(self):
        wifi_ssid = self.config['wifi']['ssid']
        wifi_pass = self.config['wifi']['pass']
        username = self.config['username']
        attempts = 5

        connected_wifi = get_connected_wifi()

        if connected_wifi == wifi_ssid:
            logging.info('connected to the wifi specified in mimosa.json')
            return True

        if connected_wifi is None:
            logging.error('not connected')
        else:
            logging.error('connected to %s, this is not what is specified in mimosa.json', connected_wifi)

        for attempt in xrange(attempts):
            self.lcd.write('Connecting to', 0)
            self.lcd.write('{}... {}/{}'.format(wifi_ssid[0:9], attempt + 1, attempts), 1)

            try:
                connect_to_wifi(wifi_ssid, wifi_pass)
                connected_wifi = get_connected_wifi()

                if connected_wifi == wifi_ssid:
                    logging.info('connected to the wifi specified in mimosa.json')
                    return True
            except Exception:
                logging.exception('connect to wifi')

            time.sleep(1)

        logging.error('couldn\'t connect to wifi specified in mimosa.json, trying any wifi')

        for attempt in xrange(attempts):
            self.lcd.write('Trying other', 0)
            self.lcd.write('WiFis.. {}/{}'.format(attempt + 1, attempts), 1)
            connect_to_any_wifi()
            connected_wifi = get_connected_wifi()

            logging.info('connected wifi: "%s"', connected_wifi)

            if connected_wifi is not None:
                return True

            time.sleep(1)

        self.lcd.write('No WiFi found', 0)
        self.lcd.write('Retrying...', 1)

    def update_lcd_with_upload_state(self):
        progress = self.upload_tracker.get_state()

        if progress:
            self.lcd.write(' '.join(progress) + ' ', 1)
        else:
            self.lcd.write('', 1)

    def wait_for_sane_state(self):
        attempts = 0

        while True:
            try:
                self.lcd.write('Initializing...', 0)
                self.initialize()
                break
            except Exception as e:
                logging.exception('initialize')

                if attempts > 5:
                    self.lcd.write('Init failed:', 0)
                    self.lcd.write(e.message + ' ', 1)

                attempts += 1
                time.sleep(1)

    def wait_for_connectivity(self):
        while True:
            if is_connected():
                return

            self.lcd.write('No network', 1)
            time.sleep(1)
        
    def print_wifi_info(self):
        connected_wifi = get_connected_wifi()
        if connected_wifi:
            self.lcd.write('{} ({}) '.format(connected_wifi, get_local_ip()), 0)
        else:
            self.lcd.write('No Wifi', 0)

    def watch(self):
        w = WatchDir(
            self.watch_dir,
            self.done_dir,
            self.config['username'],
            self.base_url,
            self.upload_tracker,
        )

        try:
            while True:
                self.print_wifi_info()
                self.wait_for_connectivity()
                w.enqueue_files()
                self.update_lcd_with_upload_state()
                time.sleep(1)
        except KeyboardInterrupt:
            logging.info('shut down the devil sound')
            suicide()

    def __del__(self):
        if hasattr(self, 'lcd'):
            self.lcd.stop()
Esempio n. 4
0
class Watcher(object):
    def __init__(self, no_pi, base_url):
        self.base_url = base_url

        self.lcd = LCDManager(get_lcd_driver())
        self.lcd.start()
        self.upload_tracker = UploadTracker()

    def initialize(self):
        work_dir = find_work_dir()

        if work_dir is None:
            raise RuntimeError('Can\'t find mimosa.json')

        logging.info('work dir found: %s', work_dir)

        try:
            self.config_file = os.path.join(work_dir, 'mimosa.json')
            self.config = json.loads(open(self.config_file).read())
        except Exception as e:
            raise RuntimeError('mimosa.json seems invalid')

        self.watch_dir = os.path.join(work_dir, 'to_upload')
        self.done_dir = os.path.join(work_dir, 'done')
        mkdir_if_not_exists(self.watch_dir)
        mkdir_if_not_exists(self.done_dir)

        logging.info('waiting for network manager to start')
        self.wait_for_network_manager_to_start()

        if not self.connect_to_wifi():
            raise RuntimeError('Can\'t find WiFi')

        logging.info('getting configuration updates')
        self.get_updates()

        if hasattr(self, 'need_to_reconnect_to_wifi'):
            self.lcd.write('Config Updated', 0)
            self.lcd.write('reconnecting...', 1)
            time.sleep(1)

            if not self.connect_to_wifi():
                raise RuntimeError('Can\'t find WiFi')

    def get_updates(self):
        url = '{}/config/{}'.format(self.base_url, self.config['username'])
        logging.info('config url: %s', url)

        try:
            config = requests.get(url).json()

            if 'error' in config:
                logging.error(
                    'server returned error when asking for config: %s',
                    config['error'])
                return

            if config != self.config:
                logging.info('configuration changed!')
                if config['wifi'] != self.config['wifi']:
                    logging.info('wifi changed!')
                    self.need_to_reconnect_to_wifi = True
                else:
                    logging.info('wifi didn\'t change')

                self.config = config
                open(self.config_file, 'w').write(json.dumps(config))
            else:
                logging.info('configuration didn\'t change')
        except Exception:
            logging.exception('get updates')

    def wait_for_network_manager_to_start(self):
        while True:
            try:
                if pidof('NetworkManager'):
                    return
            except Exception:
                pass

            time.sleep(1)

    def connect_to_wifi(self):
        wifi_ssid = self.config['wifi']['ssid']
        wifi_pass = self.config['wifi']['pass']
        username = self.config['username']
        attempts = 5

        connected_wifi = get_connected_wifi()

        if connected_wifi == wifi_ssid:
            logging.info('connected to the wifi specified in mimosa.json')
            return True

        if connected_wifi is None:
            logging.error('not connected')
        else:
            logging.error(
                'connected to %s, this is not what is specified in mimosa.json',
                connected_wifi)

        for attempt in xrange(attempts):
            self.lcd.write('Connecting to', 0)
            self.lcd.write(
                '{}... {}/{}'.format(wifi_ssid[0:9], attempt + 1, attempts), 1)

            try:
                connect_to_wifi(wifi_ssid, wifi_pass)
                connected_wifi = get_connected_wifi()

                if connected_wifi == wifi_ssid:
                    logging.info(
                        'connected to the wifi specified in mimosa.json')
                    return True
            except Exception:
                logging.exception('connect to wifi')

            time.sleep(1)

        logging.error(
            'couldn\'t connect to wifi specified in mimosa.json, trying any wifi'
        )

        for attempt in xrange(attempts):
            self.lcd.write('Trying other', 0)
            self.lcd.write('WiFis.. {}/{}'.format(attempt + 1, attempts), 1)
            connect_to_any_wifi()
            connected_wifi = get_connected_wifi()

            logging.info('connected wifi: "%s"', connected_wifi)

            if connected_wifi is not None:
                return True

            time.sleep(1)

        self.lcd.write('No WiFi found', 0)
        self.lcd.write('Retrying...', 1)

    def update_lcd_with_upload_state(self):
        progress = self.upload_tracker.get_state()

        if progress:
            self.lcd.write(' '.join(progress) + ' ', 1)
        else:
            self.lcd.write('', 1)

    def wait_for_sane_state(self):
        attempts = 0

        while True:
            try:
                self.lcd.write('Initializing...', 0)
                self.initialize()
                break
            except Exception as e:
                logging.exception('initialize')

                if attempts > 5:
                    self.lcd.write('Init failed:', 0)
                    self.lcd.write(e.message + ' ', 1)

                attempts += 1
                time.sleep(1)

    def wait_for_connectivity(self):
        while True:
            if is_connected():
                return

            self.lcd.write('No network', 1)
            time.sleep(1)

    def print_wifi_info(self):
        connected_wifi = get_connected_wifi()
        if connected_wifi:
            self.lcd.write('{} ({}) '.format(connected_wifi, get_local_ip()),
                           0)
        else:
            self.lcd.write('No Wifi', 0)

    def watch(self):
        w = WatchDir(
            self.watch_dir,
            self.done_dir,
            self.config['username'],
            self.base_url,
            self.upload_tracker,
        )

        try:
            while True:
                self.print_wifi_info()
                self.wait_for_connectivity()
                w.enqueue_files()
                self.update_lcd_with_upload_state()
                time.sleep(1)
        except KeyboardInterrupt:
            logging.info('shut down the devil sound')
            suicide()

    def __del__(self):
        if hasattr(self, 'lcd'):
            self.lcd.stop()