def test_load_bad_data(): """Test error from trying to load unserialisable data.""" fname = _path_for("test5") with open(fname, "w") as fh: fh.write(TEST_BAD_SERIALIED) with pytest.raises(HomeAssistantError): load_json(fname)
def test_load_bad_data(self): """Test error from trying to load unserialisable data.""" fname = self._path_for("test5") with open(fname, "w") as fh: fh.write(TEST_BAD_SERIALIED) with self.assertRaises(HomeAssistantError): load_json(fname)
def load(): """Load the bookmarks synchronously.""" try: self.bookmarks = load_json( self.hass.config.path(PERSISTENCE_BOOKMARKS), default=[]) self.favorites = load_json( self.hass.config.path(PERSISTENCE_FAVORITES), default=[]) except Exception as e: _LOGGER.error("Can't load bookmarks data: " + str(e))
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Nanoleaf light.""" if DATA_NANOLEAF not in hass.data: hass.data[DATA_NANOLEAF] = {} token = "" if discovery_info is not None: host = discovery_info["host"] name = None device_id = discovery_info["properties"]["id"] # if device already exists via config, skip discovery setup if host in hass.data[DATA_NANOLEAF]: return _LOGGER.info("Discovered a new Nanoleaf: %s", discovery_info) conf = load_json(hass.config.path(CONFIG_FILE)) if host in conf and device_id not in conf: conf[device_id] = conf.pop(host) save_json(hass.config.path(CONFIG_FILE), conf) token = conf.get(device_id, {}).get("token", "") else: host = config[CONF_HOST] name = config[CONF_NAME] token = config[CONF_TOKEN] nanoleaf_light = Nanoleaf(host) if not token: token = nanoleaf_light.request_token() if not token: _LOGGER.error( "Could not generate the auth token, did you press " "and hold the power button on %s" "for 5-7 seconds?", name, ) return conf = load_json(hass.config.path(CONFIG_FILE)) conf[host] = {"token": token} save_json(hass.config.path(CONFIG_FILE), conf) nanoleaf_light.token = token try: info = nanoleaf_light.info except Unavailable: _LOGGER.error("Could not connect to Nanoleaf Light: %s on %s", name, host) return if name is None: name = info.name hass.data[DATA_NANOLEAF][host] = nanoleaf_light add_entities([NanoleafLight(nanoleaf_light, name)], True)
def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the Sony Bravia TV platform.""" host = config.get(CONF_HOST) psk = config.get(CONF_PSK) mac = config.get(CONF_MAC) broadcast = config.get(CONF_BROADCAST) name = config.get(CONF_NAME) amp = config.get(CONF_AMP) android = config.get(CONF_ANDROID) source_filter = config.get(CONF_SOURCE_FILTER) pin = None if host is None: _LOGGER.error("No TV IP address found in configuration file") return # If no PSK is entered in the config file the PIN config is started if psk is None: bravia_config = load_json(hass.config.path(BRAVIA_CONFIG_FILE)) while bravia_config: # Set up a configured TV host_ip, host_config = bravia_config.popitem() if host_ip == host: pin = host_config['pin'] mac = host_config['mac'] name = config.get(CONF_NAME) add_devices([BraviaTVDevice(host, psk, mac, broadcast, name, pin, amp, android, source_filter)]) return setup_bravia(config, pin, hass, add_devices) else: add_devices([BraviaTVDevice(host, psk, mac, broadcast, name, pin, amp, android, source_filter)])
def _load_json(self): state_json_path = self._hass.config.path(STATE_JSON_FILE) if os.path.isfile(state_json_path): state_json = load_json(state_json_path) return state_json else: return {}
def setup_outh_client(hass, client_id, client_secret): config_path = hass.config.path(TOKEN_FILE) config_file = None if os.path.isfile(config_path): config_file = load_json(config_path) def token_saver(token): save_json(config_path, token) if not client_id: raise Exception("Client id is not specified in config") elif not client_secret: raise Exception("Client secret is not specified in config") auto_refesh_args = {'client_id': client_id, 'client_secret': client_secret} callback_url = f"{hass.config.api.base_url}{AUTH_CALLBACK_PATH}" oauth = OAuth2Session(client_id=client_id, scope=SCOPES, redirect_uri=callback_url, token=config_file, auto_refresh_url=TOKEN_URL, auto_refresh_kwargs=auto_refesh_args, token_updater=token_saver) retry = Retry(status=3, connect=3, status_forcelist=[500, 502, 503, 504]) adapter = HTTPAdapter(max_retries=retry) oauth.mount("http://", adapter) oauth.mount("https://", adapter) return oauth, config_file
def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the Nokia Health sensor.""" config_path = hass.config.path(NOKIA_HEALTH_CONFIG_FILE) username = config.get(CONF_USERNAME) if os.path.isfile(config_path): config_file = load_json(config_path) if config_file.get( username) is None: # User has no tokens in config dict request_app_setup(hass, config, add_devices, config_path) return False else: config_file = save_json(config_path, DEFAULT_CONFIG) request_app_setup(hass, config, add_devices, config_path) return False if "nokia_health" in _CONFIGURING: hass.components.configurator.request_done( _CONFIGURING.pop("nokia_health")) # use the per user config only config_file = config_file.get(username) data_manager = NokiaHealthDataManager(config_file) devices = [] monitored_conditions = config.get(CONF_MONITORED_CONDITIONS) for measurement_attribute in monitored_conditions: device = NokiaHealthSensor(data_manager, username, config_file.get("user_id"), measurement_attribute) devices.append(device) add_devices(devices) return True
def success(): """Set up was successful.""" conf = load_json(hass.config.path(CONFIG_FILE)) conf[host] = {'identity': identity, 'key': key} save_json(hass.config.path(CONFIG_FILE), conf) configurator.request_done(instance)
def __init__(self, hass, config, see): """Initialize.""" from pytile import Client _LOGGER.debug('Received configuration data: %s', config) # Load the client UUID (if it exists): config_data = load_json(hass.config.path(CLIENT_UUID_CONFIG_FILE)) if config_data: _LOGGER.debug('Using existing client UUID') self._client = Client(config[CONF_USERNAME], config[CONF_PASSWORD], config_data['client_uuid']) else: _LOGGER.debug('Generating new client UUID') self._client = Client(config[CONF_USERNAME], config[CONF_PASSWORD]) if not save_json(hass.config.path(CLIENT_UUID_CONFIG_FILE), {'client_uuid': self._client.client_uuid}): _LOGGER.error("Failed to save configuration file") _LOGGER.debug('Client UUID: %s', self._client.client_uuid) _LOGGER.debug('User UUID: %s', self._client.user_uuid) self._show_inactive = config.get(CONF_SHOW_INACTIVE) self._types = config.get(CONF_MONITORED_VARIABLES) self.devices = {} self.see = see track_utc_time_change(hass, self._update_info, second=range(0, 60, 30)) self._update_info()
def axis_device_discovered(service, discovery_info): """Call when axis devices has been found.""" host = discovery_info[CONF_HOST] name = discovery_info['hostname'] serialnumber = discovery_info['properties']['macaddress'] if serialnumber not in AXIS_DEVICES: config_file = load_json(hass.config.path(CONFIG_FILE)) if serialnumber in config_file: # Device config previously saved to file try: device_config = DEVICE_SCHEMA(config_file[serialnumber]) device_config[CONF_HOST] = host except vol.Invalid as err: _LOGGER.error("Bad data from %s. %s", CONFIG_FILE, err) return False if not setup_device(hass, config, device_config): _LOGGER.error( "Couldn't set up %s", device_config[CONF_NAME]) else: # New device, create configuration request for UI request_configuration(hass, config, name, host, serialnumber) else: # Device already registered, but on a different IP device = AXIS_DEVICES[serialnumber] device.config.host = host dispatcher_send(hass, DOMAIN + '_' + device.name + '_new_ip', host)
def _load_json(filename): """Wrapper, because we actually want to handle invalid json.""" try: return load_json(filename) except HomeAssistantError: pass return {}
def load(): """Load the codes synchronously.""" try: self.rf_codes = load_json( self.hass.config.path(PERSISTENCE_RF_ENTITIES), default=[]) except Exception as e: _LOGGER.error("Can't load rf_codes data: " + str(e))
def _load_config(filename): """Load configuration.""" try: return load_json(filename) except HomeAssistantError: pass return {}
async def async_init_bosch(self): """Initialize Bosch gateway module.""" _LOGGER.debug("Checking connection to Bosch gateway as %s.", self._host) try: await self.gateway.check_connection() except (FirmwareException, UnknownDevice) as err: create_notification_firmware(hass=self.hass, msg=err) _LOGGER.error(err) if not self.gateway.uuid: _LOGGER.error( "Cannot connect to Bosch gateway, host %s with UUID: %s", self._host, self.uuid, ) return False _LOGGER.debug("Bosch BUS detected: %s", self.gateway.bus_type) if not self.gateway.database: custom_db = load_json(self.hass.config.path(CUSTOM_DB), default=None) if custom_db: _LOGGER.info("Loading custom db file.") self.gateway.custom_initialize(custom_db) if self.gateway.database: supported_bosch = await self.gateway.get_capabilities() for supported in supported_bosch: element = SUPPORTED_PLATFORMS[supported] if element not in self.supported_platforms: self.supported_platforms.append(element) self.hass.data[DOMAIN][self.uuid][GATEWAY] = self.gateway _LOGGER.info("Bosch initialized.") return True
def configuration_callback(callback_data): """Call when configuration is submitted.""" if CONF_INCLUDE not in callback_data: configurator.notify_errors( request_id, "Functionality mandatory.") return False callback_data[CONF_INCLUDE] = callback_data[CONF_INCLUDE].split() callback_data[CONF_HOST] = host if CONF_NAME not in callback_data: callback_data[CONF_NAME] = name try: device_config = DEVICE_SCHEMA(callback_data) except vol.Invalid: configurator.notify_errors( request_id, "Bad input, please check spelling.") return False if setup_device(hass, config, device_config): del device_config['events'] del device_config['signal'] config_file = load_json(hass.config.path(CONFIG_FILE)) config_file[serialnumber] = dict(device_config) save_json(hass.config.path(CONFIG_FILE), config_file) configurator.request_done(request_id) else: configurator.notify_errors( request_id, "Failed to register, please try again.") return False
def test_overwrite_and_reload(self): """Test that we can overwrite an existing file and read back.""" fname = self._path_for("test3") save_json(fname, TEST_JSON_A) save_json(fname, TEST_JSON_B) data = load_json(fname) self.assertEqual(data, TEST_JSON_B)
def load_translations_files(translation_files): """Load and parse translation.json files.""" loaded = {} for component, translation_file in translation_files.items(): loaded[component] = load_json(translation_file) return loaded
def test_overwrite_and_reload(): """Test that we can overwrite an existing file and read back.""" fname = _path_for("test3") save_json(fname, TEST_JSON_A) save_json(fname, TEST_JSON_B) data = load_json(fname) assert data == TEST_JSON_B
def success(): """Signal successful setup.""" conf = load_json(hass.config.path(CONFIG_FILE)) conf[host] = {CONF_API_KEY: api_key} save_json(hass.config.path(CONFIG_FILE), conf) req_config = _CONFIGURING.pop(host) configurator.request_done(req_config)
def get_session(self): import os if not os.path.isfile(self.config_path): return self.login_session() else: self.session = load_json(self.config_path)['SESSION'] return self.session
async def async_init_bosch(self): """Initialize Bosch gateway module.""" _LOGGER.debug("Checking connection to Bosch gateway as %s.", self.address) if not await self.gateway.check_connection(): _LOGGER.error( "Cannot connect to Bosch gateway, host %s with UUID: %s", self.address, self.uuid, ) return False _LOGGER.debug("Bosch BUS detected: %s", self.gateway.bus_type) if not self.gateway.database: custom_db = load_json(self.hass.config.path(CUSTOM_DB), default=None) if custom_db: _LOGGER.info("Loading custom db file.") self.gateway.custom_initialize(custom_db) if self.gateway.database: supported_bosch = await self.gateway.get_capabilities() for supported in supported_bosch: self.supported_platforms.append(SUPPORTED_PLATFORMS[supported]) self.gateway.initialize_sensors(self._sensors_list) self.supported_platforms.append(SENSOR) self.hass.data[DOMAIN][self.uuid][GATEWAY] = self.gateway _LOGGER.info("Bosch initialized.") return True
def success(): """Set up was successful.""" conf = load_json(hass.config.path(CONFIG_FILE)) conf[host] = {'api_key': api_key} save_json(hass.config.path(CONFIG_FILE), conf) req_config = _CONFIGURING.pop(host) hass.async_add_job(configurator.request_done, req_config)
def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the SABnzbd platform.""" from pysabnzbd import SabnzbdApi if discovery_info is not None: host = discovery_info.get(CONF_HOST) port = discovery_info.get(CONF_PORT) name = DEFAULT_NAME use_ssl = discovery_info.get('properties', {}).get('https', '0') == '1' else: host = config.get(CONF_HOST) port = config.get(CONF_PORT) name = config.get(CONF_NAME, DEFAULT_NAME) use_ssl = config.get(CONF_SSL) uri_scheme = 'https://' if use_ssl else 'http://' base_url = "{}{}:{}/".format(uri_scheme, host, port) api_key = config.get(CONF_API_KEY) if not api_key: conf = load_json(hass.config.path(CONFIG_FILE)) if conf.get(base_url, {}).get('api_key'): api_key = conf[base_url]['api_key'] if not _check_sabnzbd(SabnzbdApi, base_url, api_key): request_configuration(base_url, name, hass, config, add_devices, SabnzbdApi) return setup_sabnzbd(base_url, api_key, name, hass, config, add_devices, SabnzbdApi)
def success(): """Setup was successful.""" conf = load_json(hass.config.path(CONFIG_FILE)) conf[host] = {CONF_API_KEY: api_key} save_json(hass.config.path(CONFIG_FILE), conf) req_config = _CONFIGURING.pop(host) configurator.request_done(req_config)
async def setup_fitbit(hass, config): _LOGGER.debug('Initializing Fitbit fitness push services') from fitbit import Fitbit from homeassistant.components.fitbit.sensor import ( FITBIT_CONFIG_FILE, ATTR_ACCESS_TOKEN as FITBIT_ATTR_ACCESS_TOKEN, ATTR_REFRESH_TOKEN as FITBIT_ATTR_REFRESH_TOKEN, ATTR_CLIENT_ID as FITBIT_ATTR_CLIENT_ID, ATTR_CLIENT_SECRET as FITBIT_ATTR_CLIENT_SECRET, ATTR_LAST_SAVED_AT as FITBIT_ATTR_LAST_SAVED_AT) config_path = hass.config.path(FITBIT_CONFIG_FILE) if os.path.isfile(config_path): config_file = load_json(config_path) else: _LOGGER.warn("No Fitbit config file found") return None access_token = config_file.get(FITBIT_ATTR_ACCESS_TOKEN) refresh_token = config_file.get(FITBIT_ATTR_REFRESH_TOKEN) expires_at = config_file.get(FITBIT_ATTR_LAST_SAVED_AT) if None in (access_token, refresh_token): _LOGGER.warn("Fitbit config file is not initialized") return None return Fitbit( config_file.get(FITBIT_ATTR_CLIENT_ID), config_file.get(FITBIT_ATTR_CLIENT_SECRET), access_token=access_token, refresh_token=refresh_token, expires_at=expires_at, refresh_cb=lambda x: None, )
def _load_config(filename): """Load configuration.""" try: return load_json(filename, []) except HomeAssistantError: pass return []
async def async_setup(hass, config): """Setup nibe uplink component""" store = hass.config.path('nibe.json') def save_json_local(data): save_json(store, data) from nibeuplink import Uplink scope = None if config[DOMAIN].get(CONF_WRITEACCESS): scope = ['READSYSTEM', 'WRITESYSTEM'] else: scope = ['READSYSTEM'] uplink = Uplink(client_id=config[DOMAIN].get(CONF_CLIENT_ID), client_secret=config[DOMAIN].get(CONF_CLIENT_SECRET), redirect_uri=config[DOMAIN].get(CONF_REDIRECT_URI), access_data=load_json(store), access_data_write=save_json_local, scope=scope) if not uplink.access_data: view = NibeAuthView(hass, uplink, config[DOMAIN], async_setup_systems) hass.http.register_view(view) view.async_request_config() else: hass.async_add_job(async_setup_systems(hass, config[DOMAIN], uplink)) return True
def success(): """Set up was successful.""" conf = load_json(hass.config.path(config.get(CONF_FILENAME))) conf[host] = {'credentials': credentials} save_json(hass.config.path(config.get(CONF_FILENAME)), conf) req_config = _CONFIGURING.pop(host) hass.async_add_job(configurator.request_done, req_config)
def _load_json(filename): """Load JSON, handling invalid syntax.""" try: return load_json(filename) except HomeAssistantError: pass return {}
def axis_device_discovered(service, discovery_info): """Called when axis devices has been found.""" host = discovery_info[CONF_HOST] name = discovery_info['hostname'] serialnumber = discovery_info['properties']['macaddress'] if serialnumber not in AXIS_DEVICES: config_file = load_json(hass.config.path(CONFIG_FILE)) if serialnumber in config_file: # Device config previously saved to file try: device_config = DEVICE_SCHEMA(config_file[serialnumber]) device_config[CONF_HOST] = host except vol.Invalid as err: _LOGGER.error("Bad data from %s. %s", CONFIG_FILE, err) return False if not setup_device(hass, config, device_config): _LOGGER.error("Couldn\'t set up %s", device_config[CONF_NAME]) else: # New device, create configuration request for UI request_configuration(hass, config, name, host, serialnumber) else: # Device already registered, but on a different IP device = AXIS_DEVICES[serialnumber] device.config.host = host dispatcher_send(hass, DOMAIN + '_' + device.name + '_new_ip', host)
def configuration_callback(callback_data): """Called when config is submitted.""" if CONF_INCLUDE not in callback_data: configurator.notify_errors(request_id, "Functionality mandatory.") return False callback_data[CONF_INCLUDE] = callback_data[CONF_INCLUDE].split() callback_data[CONF_HOST] = host if CONF_NAME not in callback_data: callback_data[CONF_NAME] = name try: device_config = DEVICE_SCHEMA(callback_data) except vol.Invalid: configurator.notify_errors(request_id, "Bad input, please check spelling.") return False if setup_device(hass, config, device_config): config_file = load_json(hass.config.path(CONFIG_FILE)) config_file[serialnumber] = dict(device_config) save_json(hass.config.path(CONFIG_FILE), config_file) configurator.request_done(request_id) else: configurator.notify_errors( request_id, "Failed to register, please try again.") return False
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Nanoleaf light.""" from pynanoleaf import Nanoleaf, Unavailable if DATA_NANOLEAF not in hass.data: hass.data[DATA_NANOLEAF] = dict() token = '' if discovery_info is not None: host = discovery_info['host'] name = discovery_info['hostname'] # if device already exists via config, skip discovery setup if host in hass.data[DATA_NANOLEAF]: return _LOGGER.info("Discovered a new Nanoleaf: %s", discovery_info) conf = load_json(hass.config.path(CONFIG_FILE)) if conf.get(host, {}).get('token'): token = conf[host]['token'] else: host = config[CONF_HOST] name = config[CONF_NAME] token = config[CONF_TOKEN] nanoleaf_light = Nanoleaf(host) if not token: token = nanoleaf_light.request_token() if not token: _LOGGER.error( "Could not generate the auth token, did you press " "and hold the power button on %s" "for 5-7 seconds?", name) return conf = load_json(hass.config.path(CONFIG_FILE)) conf[host] = {'token': token} save_json(hass.config.path(CONFIG_FILE), conf) nanoleaf_light.token = token try: nanoleaf_light.available except Unavailable: _LOGGER.error("Could not connect to Nanoleaf Light: %s on %s", name, host) return hass.data[DATA_NANOLEAF][host] = nanoleaf_light add_entities([NanoleafLight(nanoleaf_light, name)], True)
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Nanoleaf light.""" from pynanoleaf import Nanoleaf, Unavailable if DATA_NANOLEAF not in hass.data: hass.data[DATA_NANOLEAF] = dict() token = '' if discovery_info is not None: host = discovery_info['host'] name = discovery_info['hostname'] # if device already exists via config, skip discovery setup if host in hass.data[DATA_NANOLEAF]: return _LOGGER.info("Discovered a new Nanoleaf: %s", discovery_info) conf = load_json(hass.config.path(CONFIG_FILE)) if conf.get(host, {}).get('token'): token = conf[host]['token'] else: host = config[CONF_HOST] name = config[CONF_NAME] token = config[CONF_TOKEN] nanoleaf_light = Nanoleaf(host) if not token: token = nanoleaf_light.request_token() if not token: _LOGGER.error("Could not generate the auth token, did you press " "and hold the power button on %s" "for 5-7 seconds?", name) return conf = load_json(hass.config.path(CONFIG_FILE)) conf[host] = {'token': token} save_json(hass.config.path(CONFIG_FILE), conf) nanoleaf_light.token = token try: nanoleaf_light.available except Unavailable: _LOGGER.error( "Could not connect to Nanoleaf Light: %s on %s", name, host) return hass.data[DATA_NANOLEAF][host] = nanoleaf_light add_entities([NanoleafLight(nanoleaf_light, name)], True)
def get_english(): global english if english is None: translations = join(dirname(root.__file__), "translations", "en.json") json = load_json(translations) english = json["config"]["step"]["choose_entities"]["data"] return english
def test_save_and_load_private(): """Test we can load private files and that they are protected.""" fname = _path_for("test2") save_json(fname, TEST_JSON_A, private=True) data = load_json(fname) assert data == TEST_JSON_A stats = os.stat(fname) assert stats.st_mode & 0o77 == 0
def test_save_and_load_private(self): """Test we can load private files and that they are protected.""" fname = self._path_for("test2") save_json(fname, TEST_JSON_A, private=True) data = load_json(fname) self.assertEqual(data, TEST_JSON_A) stats = os.stat(fname) self.assertEqual(stats.st_mode & 0o77, 0)
def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the Nanoleaf Aurora device.""" import nanoleaf import nanoleaf.setup if DATA_NANOLEAF_AURORA not in hass.data: hass.data[DATA_NANOLEAF_AURORA] = dict() token = '' if discovery_info is not None: host = discovery_info['host'] name = discovery_info['hostname'] # if device already exists via config, skip discovery setup if host in hass.data[DATA_NANOLEAF_AURORA]: return _LOGGER.info("Discovered a new Aurora: %s", discovery_info) conf = load_json(hass.config.path(CONFIG_FILE)) if conf.get(host, {}).get('token'): token = conf[host]['token'] else: host = config[CONF_HOST] name = config[CONF_NAME] token = config[CONF_TOKEN] if not token: token = nanoleaf.setup.generate_auth_token(host) if not token: _LOGGER.error("Could not generate the auth token, did you press " "and hold the power button on %s" "for 5-7 seconds?", name) return conf = load_json(hass.config.path(CONFIG_FILE)) conf[host] = {'token': token} save_json(hass.config.path(CONFIG_FILE), conf) aurora_light = nanoleaf.Aurora(host, token) if aurora_light.on is None: _LOGGER.error( "Could not connect to Nanoleaf Aurora: %s on %s", name, host) return hass.data[DATA_NANOLEAF_AURORA][host] = aurora_light add_devices([AuroraLight(aurora_light, name)], True)
def load_translations_files(translation_files: Dict[str, str]) \ -> Dict[str, Dict[str, Any]]: """Load and parse translation.json files.""" loaded = {} for component, translation_file in translation_files.items(): loaded_json = load_json(translation_file) assert isinstance(loaded_json, dict) loaded[component] = loaded_json return loaded
def load_games(self): """Load games for sources.""" g_file = self._games_filename try: games = load_json(g_file) # If file does not exist, create empty file. except FileNotFoundError: games = {} self.save_games(games) return games
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the GPMDP platform.""" codeconfig = load_json(hass.config.path(GPMDP_CONFIG_FILE)) if codeconfig: code = codeconfig.get('CODE') elif discovery_info is not None: if 'gpmdp' in _CONFIGURING: return code = None else: code = None setup_gpmdp(hass, config, code, add_entities)
def test_custom_encoder(self): """Test serializing with a custom encoder.""" class MockJSONEncoder(JSONEncoder): """Mock JSON encoder.""" def default(self, o): """Mock JSON encode method.""" return "9" fname = self._path_for("test6") save_json(fname, Mock(), encoder=MockJSONEncoder) data = load_json(fname) self.assertEqual(data, "9")
def fitbit_configuration_callback(callback_data): """Handle configuration updates.""" config_path = hass.config.path(FITBIT_CONFIG_FILE) if os.path.isfile(config_path): config_file = load_json(config_path) if config_file == DEFAULT_CONFIG: error_msg = ("You didn't correctly modify fitbit.conf", " please try again") configurator.notify_errors(_CONFIGURING['fitbit'], error_msg) else: setup_platform(hass, config, add_entities, discovery_info) else: setup_platform(hass, config, add_entities, discovery_info)
def _get_auth_tokens(self): """ Read sorted authentication tokens from disk. Returns the auth_tokens dictionary. """ try: auth_tokens = load_json(self._session_filepath) return auth_tokens except HomeAssistantError as ex: _LOGGER.warning( "Loading authentication tokens from file '%s' failed: %s", self._session_filepath, str(ex)) return {}
def setup_switch(device_id, name, insteonhub, hass, add_devices_callback): """Set up the switch.""" if device_id in _CONFIGURING: request_id = _CONFIGURING.pop(device_id) configurator = hass.components.configurator configurator.request_done(request_id) _LOGGER.info("Device configuration done") conf_switch = load_json(hass.config.path(INSTEON_LOCAL_SWITCH_CONF)) if device_id not in conf_switch: conf_switch[device_id] = name save_json(hass.config.path(INSTEON_LOCAL_SWITCH_CONF), conf_switch) device = insteonhub.switch(device_id) add_devices_callback([InsteonLocalSwitchDevice(device, name)])
def setup_fan(device_id, name, insteonhub, hass, add_devices_callback): """Set up the fan.""" if device_id in _CONFIGURING: request_id = _CONFIGURING.pop(device_id) configurator = hass.components.configurator configurator.request_done(request_id) _LOGGER.info("Device configuration done!") conf_fans = load_json(hass.config.path(INSTEON_LOCAL_FANS_CONF)) if device_id not in conf_fans: conf_fans[device_id] = name save_json(hass.config.path(INSTEON_LOCAL_FANS_CONF), conf_fans) device = insteonhub.fan(device_id) add_devices_callback([InsteonLocalFanDevice(device, name)])
def setup_light(device_id, name, insteonhub, hass, add_devices_callback): """Set up the light.""" if device_id in _CONFIGURING: request_id = _CONFIGURING.pop(device_id) configurator = hass.components.configurator configurator.request_done(request_id) _LOGGER.debug("Device configuration done") conf_lights = load_json(hass.config.path(INSTEON_LOCAL_LIGHTS_CONF)) if device_id not in conf_lights: conf_lights[device_id] = name save_json(hass.config.path(INSTEON_LOCAL_LIGHTS_CONF), conf_lights) device = insteonhub.dimmer(device_id) add_devices_callback([InsteonLocalDimmerDevice(device, name)])
def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the Sony Bravia TV platform.""" host = config.get(CONF_HOST) if host is None: return pin = None bravia_config = load_json(hass.config.path(BRAVIA_CONFIG_FILE)) while bravia_config: # Set up a configured TV host_ip, host_config = bravia_config.popitem() if host_ip == host: pin = host_config['pin'] mac = host_config['mac'] name = config.get(CONF_NAME) add_devices([BraviaTVDevice(host, mac, name, pin)]) return setup_bravia(config, pin, hass, add_devices)
def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the Insteon local switch platform.""" insteonhub = hass.data['insteon_local'] conf_switches = load_json(hass.config.path(INSTEON_LOCAL_SWITCH_CONF)) if conf_switches: for device_id in conf_switches: setup_switch( device_id, conf_switches[device_id], insteonhub, hass, add_devices) else: linked = insteonhub.get_linked() for device_id in linked: if linked[device_id]['cat_type'] == 'switch'\ and device_id not in conf_switches: request_configuration(device_id, insteonhub, linked[device_id]['model_name'] + ' ' + linked[device_id]['sku'], hass, add_devices)
def setup_platform(hass, config, add_entities_callback, discovery_info=None): """Set up the Plex platform.""" if PLEX_DATA not in hass.data: hass.data[PLEX_DATA] = {} # get config from plex.conf file_config = load_json(hass.config.path(PLEX_CONFIG_FILE)) if file_config: # Setup a configured PlexServer host, host_config = file_config.popitem() token = host_config['token'] try: has_ssl = host_config['ssl'] except KeyError: has_ssl = False try: verify_ssl = host_config['verify'] except KeyError: verify_ssl = True # Via discovery elif discovery_info is not None: # Parse discovery data host = discovery_info.get('host') port = discovery_info.get('port') host = '%s:%s' % (host, port) _LOGGER.info("Discovered PLEX server: %s", host) if host in _CONFIGURING: return token = None has_ssl = False verify_ssl = True else: return setup_plexserver( host, token, has_ssl, verify_ssl, hass, config, add_entities_callback )
def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the Insteon local light platform.""" insteonhub = hass.data['insteon_local'] conf_lights = load_json(hass.config.path(INSTEON_LOCAL_LIGHTS_CONF)) if conf_lights: for device_id in conf_lights: setup_light(device_id, conf_lights[device_id], insteonhub, hass, add_devices) else: linked = insteonhub.get_linked() for device_id in linked: if (linked[device_id]['cat_type'] == 'dimmer' and device_id not in conf_lights): request_configuration(device_id, insteonhub, linked[device_id]['model_name'] + ' ' + linked[device_id]['sku'], hass, add_devices)
def setup(hass, config): """Set up the iOS component.""" global CONFIG_FILE global CONFIG_FILE_PATH CONFIG_FILE_PATH = hass.config.path(CONFIGURATION_FILE) CONFIG_FILE = load_json(CONFIG_FILE_PATH) if CONFIG_FILE == {}: CONFIG_FILE[ATTR_DEVICES] = {} discovery.load_platform(hass, 'notify', DOMAIN, {}, config) discovery.load_platform(hass, 'sensor', DOMAIN, {}, config) hass.http.register_view(iOSIdentifyDeviceView) app_config = config.get(DOMAIN, {}) hass.http.register_view(iOSPushConfigView(app_config.get(CONF_PUSH, {}))) return True
def __init__(self, hass, config, see): """Initialize.""" from pytile import Client _LOGGER.debug('Received configuration data: %s', config) # Load the client UUID (if it exists): config_data = load_json(hass.config.path(CLIENT_UUID_CONFIG_FILE)) if config_data: _LOGGER.debug('Using existing client UUID') self._client = Client( config[CONF_USERNAME], config[CONF_PASSWORD], config_data['client_uuid']) else: _LOGGER.debug('Generating new client UUID') self._client = Client( config[CONF_USERNAME], config[CONF_PASSWORD]) if not save_json( hass.config.path(CLIENT_UUID_CONFIG_FILE), {'client_uuid': self._client.client_uuid}): _LOGGER.error("Failed to save configuration file") _LOGGER.debug('Client UUID: %s', self._client.client_uuid) _LOGGER.debug('User UUID: %s', self._client.user_uuid) self._types = config.get(CONF_MONITORED_VARIABLES) self.devices = {} self.see = see track_utc_time_change( hass, self._update_info, second=range(0, 60, 30)) self._update_info()
def setup(hass, config): """Set up the Wink component.""" import pywink from pubnubsubhandler import PubNubSubscriptionHandler if hass.data.get(DOMAIN) is None: hass.data[DOMAIN] = { 'unique_ids': [], 'entities': {}, 'oauth': {}, 'configuring': {}, 'pubnub': None, 'configurator': False } if config.get(DOMAIN) is not None: client_id = config[DOMAIN].get(ATTR_CLIENT_ID) client_secret = config[DOMAIN].get(ATTR_CLIENT_SECRET) email = config[DOMAIN].get(CONF_EMAIL) password = config[DOMAIN].get(CONF_PASSWORD) local_control = config[DOMAIN].get(CONF_LOCAL_CONTROL) else: client_id = None client_secret = None email = None password = None local_control = None hass.data[DOMAIN]['configurator'] = True if None not in [client_id, client_secret]: _LOGGER.info("Using legacy OAuth authentication") if not local_control: pywink.disable_local_control() hass.data[DOMAIN]["oauth"]["client_id"] = client_id hass.data[DOMAIN]["oauth"]["client_secret"] = client_secret hass.data[DOMAIN]["oauth"]["email"] = email hass.data[DOMAIN]["oauth"]["password"] = password pywink.legacy_set_wink_credentials(email, password, client_id, client_secret) else: _LOGGER.info("Using OAuth authentication") if not local_control: pywink.disable_local_control() config_path = hass.config.path(WINK_CONFIG_FILE) if os.path.isfile(config_path): config_file = load_json(config_path) if config_file == DEFAULT_CONFIG: _request_app_setup(hass, config) return True # else move on because the user modified the file else: save_json(config_path, DEFAULT_CONFIG) _request_app_setup(hass, config) return True if DOMAIN in hass.data[DOMAIN]['configuring']: _configurator = hass.data[DOMAIN]['configuring'] hass.components.configurator.request_done(_configurator.pop( DOMAIN)) # Using oauth access_token = config_file.get(ATTR_ACCESS_TOKEN) refresh_token = config_file.get(ATTR_REFRESH_TOKEN) # This will be called after authorizing Home-Assistant if None not in (access_token, refresh_token): pywink.set_wink_credentials(config_file.get(ATTR_CLIENT_ID), config_file.get(ATTR_CLIENT_SECRET), access_token=access_token, refresh_token=refresh_token) # This is called to create the redirect so the user can Authorize # Home . else: redirect_uri = '{}{}'.format( hass.config.api.base_url, WINK_AUTH_CALLBACK_PATH) wink_auth_start_url = pywink.get_authorization_url( config_file.get(ATTR_CLIENT_ID), redirect_uri) hass.http.register_redirect(WINK_AUTH_START, wink_auth_start_url) hass.http.register_view(WinkAuthCallbackView( config, config_file, pywink.request_token)) _request_oauth_completion(hass, config) return True pywink.set_user_agent(USER_AGENT) hass.data[DOMAIN]['pubnub'] = PubNubSubscriptionHandler( pywink.get_subscription_key()) def _subscribe(): hass.data[DOMAIN]['pubnub'].subscribe() # Call subscribe after the user sets up wink via the configurator # All other methods will complete setup before # EVENT_HOMEASSISTANT_START is called meaning they # will call subscribe via the method below. (start_subscription) if hass.data[DOMAIN]['configurator']: _subscribe() def keep_alive_call(event_time): """Call the Wink API endpoints to keep PubNub working.""" _LOGGER.info("Polling the Wink API to keep PubNub updates flowing") pywink.set_user_agent(str(int(time.time()))) _temp_response = pywink.get_user() _LOGGER.debug(str(json.dumps(_temp_response))) time.sleep(1) pywink.set_user_agent(USER_AGENT) _temp_response = pywink.wink_api_fetch() _LOGGER.debug(str(json.dumps(_temp_response))) # Call the Wink API every hour to keep PubNub updates flowing track_time_interval(hass, keep_alive_call, timedelta(minutes=60)) def start_subscription(event): """Start the PubNub subscription.""" _subscribe() hass.bus.listen(EVENT_HOMEASSISTANT_START, start_subscription) def stop_subscription(event): """Stop the PubNub subscription.""" hass.data[DOMAIN]['pubnub'].unsubscribe() hass.data[DOMAIN]['pubnub'] = None hass.bus.listen(EVENT_HOMEASSISTANT_STOP, stop_subscription) def save_credentials(event): """Save currently set OAuth credentials.""" if hass.data[DOMAIN]["oauth"].get("email") is None: config_path = hass.config.path(WINK_CONFIG_FILE) _config = pywink.get_current_oauth_credentials() save_json(config_path, _config) hass.bus.listen(EVENT_HOMEASSISTANT_STOP, save_credentials) # Save the users potentially updated oauth credentials at a regular # interval to prevent them from being expired after a HA reboot. track_time_interval(hass, save_credentials, timedelta(minutes=60)) def force_update(call): """Force all devices to poll the Wink API.""" _LOGGER.info("Refreshing Wink states from API") for entity_list in hass.data[DOMAIN]['entities'].values(): # Throttle the calls to Wink API for entity in entity_list: time.sleep(1) entity.schedule_update_ha_state(True) hass.services.register(DOMAIN, SERVICE_REFRESH_STATES, force_update) def pull_new_devices(call): """Pull new devices added to users Wink account since startup.""" _LOGGER.info("Getting new devices from Wink API") for _component in WINK_COMPONENTS: discovery.load_platform(hass, _component, DOMAIN, {}, config) hass.services.register(DOMAIN, SERVICE_ADD_NEW_DEVICES, pull_new_devices) def set_pairing_mode(call): """Put the hub in provided pairing mode.""" hub_name = call.data.get('hub_name') pairing_mode = call.data.get('pairing_mode') kidde_code = call.data.get('kidde_radio_code') for hub in WINK_HUBS: if hub.name() == hub_name: hub.pair_new_device(pairing_mode, kidde_radio_code=kidde_code) def rename_device(call): """Set specified device's name.""" # This should only be called on one device at a time. found_device = None entity_id = call.data.get('entity_id')[0] all_devices = [] for list_of_devices in hass.data[DOMAIN]['entities'].values(): all_devices += list_of_devices for device in all_devices: if device.entity_id == entity_id: found_device = device if found_device is not None: name = call.data.get('name') found_device.wink.set_name(name) hass.services.register(DOMAIN, SERVICE_RENAME_DEVICE, rename_device, schema=RENAME_DEVICE_SCHEMA) def delete_device(call): """Delete specified device.""" # This should only be called on one device at a time. found_device = None entity_id = call.data.get('entity_id')[0] all_devices = [] for list_of_devices in hass.data[DOMAIN]['entities'].values(): all_devices += list_of_devices for device in all_devices: if device.entity_id == entity_id: found_device = device if found_device is not None: found_device.wink.remove_device() hass.services.register(DOMAIN, SERVICE_DELETE_DEVICE, delete_device, schema=DELETE_DEVICE_SCHEMA) hubs = pywink.get_hubs() for hub in hubs: if hub.device_manufacturer() == 'wink': WINK_HUBS.append(hub) if WINK_HUBS: hass.services.register( DOMAIN, SERVICE_SET_PAIRING_MODE, set_pairing_mode, schema=SET_PAIRING_MODE_SCHEMA) def service_handle(service): """Handle services.""" entity_ids = service.data.get('entity_id') all_sirens = [] for switch in hass.data[DOMAIN]['entities']['switch']: if isinstance(switch, WinkSirenDevice): all_sirens.append(switch) sirens_to_set = [] if entity_ids is None: sirens_to_set = all_sirens else: for siren in all_sirens: if siren.entity_id in entity_ids: sirens_to_set.append(siren) for siren in sirens_to_set: _man = siren.wink.device_manufacturer() if (service.service != SERVICE_SET_AUTO_SHUTOFF and service.service != SERVICE_ENABLE_SIREN and _man not in ('dome', 'wink')): _LOGGER.error("Service only valid for Dome or Wink sirens") return if service.service == SERVICE_ENABLE_SIREN: siren.wink.set_state(service.data.get(ATTR_ENABLED)) elif service.service == SERVICE_SET_AUTO_SHUTOFF: siren.wink.set_auto_shutoff( service.data.get(ATTR_AUTO_SHUTOFF)) elif service.service == SERVICE_SET_CHIME_VOLUME: siren.wink.set_chime_volume(service.data.get(ATTR_VOLUME)) elif service.service == SERVICE_SET_SIREN_VOLUME: siren.wink.set_siren_volume(service.data.get(ATTR_VOLUME)) elif service.service == SERVICE_SET_SIREN_TONE: siren.wink.set_siren_sound(service.data.get(ATTR_TONE)) elif service.service == SERVICE_ENABLE_CHIME: siren.wink.set_chime(service.data.get(ATTR_TONE)) elif service.service == SERVICE_SIREN_STROBE_ENABLED: siren.wink.set_siren_strobe_enabled( service.data.get(ATTR_ENABLED)) elif service.service == SERVICE_CHIME_STROBE_ENABLED: siren.wink.set_chime_strobe_enabled( service.data.get(ATTR_ENABLED)) # Load components for the devices in Wink that we support for wink_component in WINK_COMPONENTS: hass.data[DOMAIN]['entities'][wink_component] = [] discovery.load_platform(hass, wink_component, DOMAIN, {}, config) component = EntityComponent(_LOGGER, DOMAIN, hass) sirens = [] has_dome_or_wink_siren = False for siren in pywink.get_sirens(): _man = siren.device_manufacturer() if _man in ("dome", "wink"): has_dome_or_wink_siren = True _id = siren.object_id() + siren.name() if _id not in hass.data[DOMAIN]['unique_ids']: sirens.append(WinkSirenDevice(siren, hass)) if sirens: hass.services.register(DOMAIN, SERVICE_SET_AUTO_SHUTOFF, service_handle, schema=SET_AUTO_SHUTOFF_SCHEMA) hass.services.register(DOMAIN, SERVICE_ENABLE_SIREN, service_handle, schema=ENABLED_SIREN_SCHEMA) if has_dome_or_wink_siren: hass.services.register(DOMAIN, SERVICE_SET_SIREN_TONE, service_handle, schema=SET_SIREN_TONE_SCHEMA) hass.services.register(DOMAIN, SERVICE_ENABLE_CHIME, service_handle, schema=SET_CHIME_MODE_SCHEMA) hass.services.register(DOMAIN, SERVICE_SET_SIREN_VOLUME, service_handle, schema=SET_VOLUME_SCHEMA) hass.services.register(DOMAIN, SERVICE_SET_CHIME_VOLUME, service_handle, schema=SET_VOLUME_SCHEMA) hass.services.register(DOMAIN, SERVICE_SIREN_STROBE_ENABLED, service_handle, schema=SET_STROBE_ENABLED_SCHEMA) hass.services.register(DOMAIN, SERVICE_CHIME_STROBE_ENABLED, service_handle, schema=SET_STROBE_ENABLED_SCHEMA) component.add_entities(sirens) return True