def main(): parser = argparse.ArgumentParser( description='Raspberry Pi sampler for LEaRN project') parser.add_argument('-c', '--config', type=str, required=False) parser.add_argument('-t', '--configtest', action='store_true') args = parser.parse_args() if args.config is not None: assert (os.path.exists(args.config)) os.environ[ENV_YAML_PATH] = args.config if args.configtest: try: c = Config().config except ConfigurationError as e: print("Configuration is invalid: {0}".format(e.message)) sys.exit(1) print("Configuration is valid.") sys.exit(0) config = Config().config global logger logger = configure_logger(config) logger.info("Raspberry Pi Sampler: entering.") try: GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) sample() except KeyboardInterrupt: GPIO.cleanup() finally: logger.info("Raspberry Pi Sampler: exiting.")
def test_config_one_ro(self): os.environ[ENV_YAML_PATH] = '../data/config1_props.yml' c = Config(unittest=True).config # Simulator self.assertTrue(CFG_SIMULATOR in c) self.assertTrue(c[CFG_SIMULATOR]) # Logging self.assertTrue(CFG_LOGGING_LOGGER_PATH in c) self.assertEqual(c[CFG_LOGGING_LOGGER_PATH], '/var/log/sensor.log') # Spooler self.assertTrue(CFG_SPOOLER_DB_PATH in c) self.assertEqual(c[CFG_SPOOLER_DB_PATH], '/var/spool/mqueue/sensor.sqlite') # Thing self.assertTrue(CFG_THING in c) t = c[CFG_THING] self.assertEqual(t.thing_id, '5474a427-f565-4233-8f82-a8178534b150') self.assertEqual(t.location_id, 'f5610fb9-1556-42d8-862c-1d290a9b5c58') # Sensors sensors = c[CFG_SENSORS] self.assertEqual(len(sensors), 2) # 1st sensor s = sensors[0] self.assertTrue(isinstance(s, Sensor)) self.assertEqual(CFG_SENSOR_TYPE_MQ131, s.typ) self.assertEqual(s.adc_type, ADCType.MCP3002) ops = s.observed_properties self.assertEqual(len(ops), 1) # First (only) observed property o = ops[0] self.assertTrue(isinstance(o, ObservedProperty)) self.assertEqual(o.name, 'ozone') self.assertEqual(o.datastream_id, '1af6b695-07c0-4024-aeb8-4ddf64dbf458')
def spool_data(q): config = Config().config logger = configure_logger(config) logger.info("Spooler: entering.") repo = SqliteRepository(config) while True: try: logger.debug("Spooler: getting from queue...") obs = q.get() logger.debug("Spooler: received observation: {0}".format(str(obs))) if isinstance(obs, Observation): repo.create_observation(obs) elif isinstance(obs, MultiObservation): repo.create_multiobservation(obs) else: raise TypeError("Observation of type {0} is unknown".format( obs.__class__.__name__)) logger.debug("Spooler: observation stored in database") except KeyboardInterrupt: break except Exception as e: logger.exception("Spooler: caught exception: {0}".format(str(e))) finally: pass logger.info("Spooler: exiting.")
def test_config_one(self): os.environ[ENV_YAML_PATH] = '../data/config1.yml' c = Config(unittest=True).config # Simulator self.assertTrue(CFG_SIMULATOR in c) self.assertTrue(c[CFG_SIMULATOR]) # Logging self.assertTrue(CFG_LOGGING_LOGGER_PATH in c) self.assertEqual(c[CFG_LOGGING_LOGGER_PATH], '/var/log/sensor.log') self.assertTrue(c[CFG_LOGGING_LEVEL_CONSOLE], logging.INFO) self.assertTrue(c[CFG_LOGGING_LEVEL_FILE], logging.DEBUG) # Spooler self.assertTrue(CFG_SPOOLER_DB_PATH in c) self.assertEqual(c[CFG_SPOOLER_DB_PATH], '/var/spool/mqueue/sensor.sqlite') # Thing self.assertTrue(CFG_THING in c) t = c[CFG_THING] self.assertEqual(t.thing_id, '5474a427-f565-4233-8f82-a8178534b150') self.assertEqual(t.location_id, 'f5610fb9-1556-42d8-862c-1d290a9b5c58') # Sensors sensors = c[CFG_SENSORS] self.assertEqual(len(sensors), 2) # 1st sensor s = sensors[0] self.assertTrue(isinstance(s, Sensor)) self.assertEqual(CFG_SENSOR_TYPE_MQ131, s.typ) ops = s.observed_properties self.assertEqual(len(ops), 1) # First (only) observed property o = ops[0] self.assertTrue(isinstance(o, ObservedProperty)) self.assertEqual(o.name, 'ozone') self.assertEqual(o.datastream_id, '1af6b695-07c0-4024-aeb8-4ddf64dbf458') # 2nd sensor s = sensors[1] self.assertTrue(isinstance(s, MultiSensor)) self.assertEqual(CFG_SENSOR_TYPE_DHT11, s.typ) opn = s.observed_property_names self.assertEqual(len(opn), 2) # First observed property name self.assertEqual(opn[0], 'air_temperature') # Second observed property name self.assertEqual(opn[1], 'relative_humidity') # Transports transports = c[CFG_TRANSPORTS] self.assertEqual(len(transports), 1) t = transports[0] self.assertTrue(isinstance(t, HttpsTransport)) self.assertEqual(CFG_TRANSPORT_TYPE_HTTPS, t.typ) self.assertEqual('https://myservice.com/auth', t.auth_url()) self.assertEqual('https://myservice.com/v1.0/', t.url()) self.assertEqual('6d770f60-9912-4545-9d3c-9e8dcf4a0dad', t.jwt_id()) self.assertEqual('faac9ce4-fd2d-476b-9984-aee2b71dfc8e', t.jwt_key()) self.assertEqual(timedelta(minutes=15), t.jwt_token_ttl_minutes()) self.assertEqual(15, t.transmit_interval_seconds()) self.assertEqual(False, t.verify_ssl())
def main(): parser = argparse.ArgumentParser(description='Simulate a sensor') parser.add_argument('-d', '--startdate', nargs=5, type=int, default=[2017, 1, 1, 0, 0], help='Start date for data: YYYY MM DD HH MM') parser.add_argument('-i', '--dateint', type=int, default=1, help='Number of minutes between subsequent data') parser.add_argument('-c', '--config', type=str, required=False) parser.add_argument('-t', '--configtest', action='store_true') args = parser.parse_args() if args.config is not None: assert (os.path.exists(args.config)) os.environ[ENV_YAML_PATH] = args.config if args.configtest: try: c = Config().config except ConfigurationError as e: print("Configuration is invalid: {0}".format(e.message)) sys.exit(1) print("Configuration is valid.") sys.exit(0) config = Config().config global logger logger = configure_logger(config) start_date = datetime(year=args.startdate[0], month=args.startdate[1], day=args.startdate[2], hour=args.startdate[3], minute=args.startdate[4]) print("Start date: {0}".format(str(start_date))) date_interval = timedelta(minutes=args.dateint) print("Date interval: {0} minutes".format(str(date_interval))) sample(start_date=start_date, date_interval=date_interval)
def setUp(self): os.environ[ENV_YAML_PATH] = './test_sqlite.yml' global config config = Config(unittest=True).config try: os.unlink(config[CFG_SPOOLER_DB_PATH]) except FileNotFoundError: pass
def test_config_adc_non_default(self): os.environ[ENV_YAML_PATH] = '../data/config1_adc.yml' c = Config(unittest=True).config # Sensors sensors = c[CFG_SENSORS] self.assertEqual(len(sensors), 2) # 1st sensor s = sensors[0] self.assertTrue(isinstance(s, Sensor)) self.assertEqual(CFG_SENSOR_TYPE_MQ131, s.typ) self.assertEqual(s.adc_type, ADCType.ADS1015)
def generate_observations_minute(): config = Config().config logger = configure_logger(config) logger.debug("Begin generate_observations_minute...") thing = config[CFG_THING] # Iterate over sensors and generate observations sensors = config[CFG_SENSORS] logger.debug("Iterating over {0} sensors...".format(len(sensors))) for s in sensors: logger.debug(str(s)) logger.debug("Calling generate_observations for sensor type {0}...".format(s.typ)) observations = s.generate_observations() logger.debug("Enqueing observations...") [logger.debug(str(o)) for o in observations]
def main(): parser = argparse.ArgumentParser(description='Test Raspberry Pi sensors') parser.add_argument('-c', '--config', type=str, required=False) args = parser.parse_args() if args.config is not None: assert (os.path.exists(args.config)) os.environ[ENV_YAML_PATH] = args.config config = Config().config global logger logger = configure_logger(config) logger.info("Transmitter: entering.") repo = SqliteRepository(config) s = sched.scheduler(time.time, time.sleep) while True: try: # Get the transmit interval from the env var set by balenaCloud transmit_interval = os.environ.get('TRANSMIT_INTERVAL') if transmit_interval is None: logger.info("Transmitter: TRANSMIT_INTERVAL is not defined. We will default to 15 seconds unless this is set.") transmit_interval = 15 else: transmit_interval = float(transmit_interval) transports = config[CFG_TRANSPORTS] logger.debug("Transmitter: scheduling network transmissions for {0} transports...".format(len(transports))) for t in transports: s.enter(transmit_interval, SCHEDULE_PRIORITY_DEFAULT, t.transmit, argument=(repo,)) logger.debug("Transmitter: Running scheduler...") s.run() logger.debug("Transmitter: End of iteration.") except KeyboardInterrupt: break except AuthenticationException as ae: logger.exception("Transmitter: {0}".format(ae.message)) except TransmissionException as te: logger.exception("Transmitter: {0}".format(te.message)) finally: pass logger.info("Transmitter: exiting.")
def test_config_one_dupe_transport(self): os.environ[ENV_YAML_PATH] = '../data/config1-dupe-transport.yml' with self.assertRaises(ConfigurationError): c = Config(unittest=True).config
def test_config_adc_invalid(self): os.environ[ENV_YAML_PATH] = '../data/config1_adc_invalid.yml' with self.assertRaises(ValueError): c = Config(unittest=True).config
def get_instance(): # Avoid circular import from sensors.config import Config return configure_logger(Config().config)