def scan_for_tilt_data(self) -> list: """ scan for tilt and return data if found """ data = [] LOGGER.debug('Looking for events') for beacon in blescan.get_events(self.sock): uuid = beacon.get('uuid') if uuid is None: continue color = constants.TILT_DEVICES.get(uuid) if color: data.append({ 'color': color, 'gravity': float(beacon['minor']/1000), 'temp': beacon['major'], 'mac': beacon['mac'], 'timestamp': datetime.now().isoformat(), 'uuid': uuid }) else: LOGGER.debug( "Beacon UUID is not a tilt device: %s", uuid ) return data
def run( keep_running: bool, config_file: str = 'config.ini', ): """ main cli entrypoint Args: keep_running (bool): Whether or not to keep running. Default: False config_file (str): The configuration file location to load. """ file = pathlib.Path(config_file) if not file.exists(): raise ConfigurationFileNotFoundException() CONFIG.read(config_file) logging_level = 'INFO' try: logging_level = CONFIG['general'].get('logging_level', 'INFO') except KeyError: pass LOGGER.setLevel(logging.getLevelName(logging_level)) device = tilt_device.TiltDevice() signal.signal(signal.SIGINT, partial(terminate_process, device)) device.start() threading.Thread( target=scan_and_emit_thread, name='tilty_daemon', args=(device, CONFIG, keep_running) ).start() if keep_running: while True: pass
def stop(self) -> None: """ Stop scanning and device Args: """ LOGGER.debug('Stopping device socket') blescan.hci_disable_le_scan(self.sock)
def scan_and_emit_thread(device: tilt_device.TiltDevice, config: configparser.ConfigParser, keep_running: bool = False) -> None: """ method that calls the needful Args: device (TiltDevice): The bluetooth device to operate on. config (dict): The parsed configuration keep_running (bool): Whether or not to keep running. Default: False """ emitters = parse_config(config) click.echo('Scanning for Tilt data...') gravity_offset = float( safe_get_key(CONFIG, 'general', {}).get('gravity_offset', '0')) LOGGER.debug('Gravity offset: %f', gravity_offset) temperature_offset = float( safe_get_key(CONFIG, 'general', {}).get('temperature_offset', '0')) LOGGER.debug('Temperature offset: %f', temperature_offset) scan_and_emit(device, emitters, gravity_offset, temperature_offset) while keep_running: LOGGER.debug('Scanning for Tilt data...') try: scan_and_emit(device, emitters, gravity_offset, temperature_offset) except Exception as exception: # pylint: disable=broad-except LOGGER.error("%s\n%s", str(exception), traceback.format_tb(exception.__traceback__)) sleep_time = int(CONFIG['general'].get('sleep_interval', '1')) LOGGER.debug('Sleeping for %s....', sleep_time) sleep(sleep_time)
def start(self) -> None: """ Start scanning and device Args: """ LOGGER.debug('Setting scan parameters and enabling LE scan') blescan.hci_le_set_scan_parameters(self.sock) blescan.hci_enable_le_scan(self.sock)
def __init__(self, device_id: int = 0) -> None: """ Initializer Args: device_id: (int) represents the device id for HCI sock: the socket to open """ LOGGER.debug('Opening device socket') self.sock = bluez.hci_open_dev(device_id)
def scan_for_tilt_data(self) -> List[dict]: """ scan for tilt and return data if found """ data = {} LOGGER.debug('Looking for events') for beacon in blescan.get_events(self.sock): if beacon['uuid'] in constants.TILT_DEVICES: data[beacon['uuid']] = { 'color': constants.TILT_DEVICES[beacon['uuid']], 'gravity': float(beacon['minor'] / 1000), 'temp': beacon['major'], 'mac': beacon['mac'], 'timestamp': datetime.now().isoformat(), } else: LOGGER.debug("Beacon UUID is not a tilt device: %s", beacon['uuid']) return list(data.values())
def run( keep_running: bool, config_file: str = 'config.ini', ): """ main cli entrypoint Args: keep_running (bool): Whether or not to keep running. Default: False config_file (str): The configuration file location to load. """ file = pathlib.Path(config_file) if not file.exists(): raise ConfigurationFileNotFoundException() CONFIG.read(config_file) handler = logging.StreamHandler(sys.stdout) logging_level = 'INFO' try: logging_level = CONFIG['general'].get('logging_level', 'INFO') logfile = CONFIG['general'].get('logfile', None) if logfile: handler = logging.FileHandler(filename=logfile) except KeyError: pass LOGGER.setLevel(logging.getLevelName(logging_level)) handler.setLevel(logging_level) LOGGER.addHandler(handler) keep_running_flag = threading.Event() if keep_running: keep_running_flag.set() device = tilt_device.TiltDevice() signal.signal(signal.SIGINT, partial(terminate_process, device, keep_running_flag)) device.start() main_thread = threading.Thread(target=scan_and_emit_thread, name='tilty_daemon', args=(device, CONFIG, keep_running_flag)) main_thread.start() main_thread.join()
def scan_and_emit_thread( device: tilt_device.TiltDevice, config: configparser.ConfigParser, keep_running: bool = False ) -> None: """ method that calls the needful Args: device (TiltDevice): The bluetooth device to operate on. config (dict): The parsed configuration keep_running (bool): Whether or not to keep running. Default: False """ emitters = parse_config(config) click.echo('Scanning for Tilt data...') scan_and_emit(device, emitters) while keep_running: LOGGER.debug('Scanning for Tilt data...') scan_and_emit(device, emitters) sleep_time = int(CONFIG['general'].get('sleep_interval', '1')) LOGGER.debug('Sleeping for %s....', sleep_time) sleep(sleep_time)
def scan_and_emit(device: tilt_device.TiltDevice, emitters: List[dict]): """ Scans and emits the data via the loaded emitters. Args: device (TiltDevice): The bluetooth device to operate on. emitters ([dict]): The emitters to use. """ LOGGER.debug('Starting device scan') tilt_data = device.scan_for_tilt_data() if tilt_data: for event in tilt_data: LOGGER.debug('tilt data retrieved') LOGGER.info(event) emit(emitters=emitters, tilt_data=event) else: LOGGER.debug('No tilt data')
def scan_and_emit(device: tilt_device.TiltDevice, emitters: List[dict]): """ Scans and emits the data via the loaded emitters. Args: device (TiltDevice): The bluetooth device to operate on. emitters ([dict]): The emitters to use. """ LOGGER.debug('Starting device scan') tilt_data = device.scan_for_tilt_data() if len(tilt_data) > 0: LOGGER.debug('tilt data retrieved') for datum in tilt_data: click.echo(datum) emit(emitters=emitters, tilt_data=tilt_data) else: LOGGER.debug('No tilt data')
def scan_and_emit_thread(device: tilt_device.TiltDevice, config: configparser.ConfigParser, keep_running: threading.Event) -> None: """ method that calls the needful Args: device (TiltDevice): The bluetooth device to operate on. config (dict): The parsed configuration keep_running (threading.Event): Whether or not to keep running. Default: False """ emitters = parse_config(config) click.echo('Scanning for Tilt data...') scan_and_emit(device, emitters) while keep_running.is_set(): LOGGER.debug('Scanning for Tilt data...') try: scan_and_emit(device, emitters) except Exception as exception: # pylint: disable=broad-except LOGGER.error("%s\n%s", str(exception), traceback.format_tb(exception.__traceback__)) sleep_time = int(CONFIG['general'].get('sleep_interval', '1')) LOGGER.debug('Sleeping for %s....', sleep_time) sleep(sleep_time)