def setup_platform(hass, config, add_devices, discovery_info=None): """Setup the Yr.no sensor.""" latitude = config.get(CONF_LATITUDE, hass.config.latitude) longitude = config.get(CONF_LONGITUDE, hass.config.longitude) elevation = config.get(CONF_ELEVATION) if None in (latitude, longitude): _LOGGER.error("Latitude or longitude not set in Home Assistant config") return False if elevation is None: elevation = location.elevation(latitude, longitude) coordinates = dict(lat=latitude, lon=longitude, msl=elevation) weather = YrData(coordinates) dev = [] for sensor_type in config[CONF_MONITORED_CONDITIONS]: dev.append(YrSensor(sensor_type, weather)) # add symbol as default sensor if len(dev) == 0: dev.append(YrSensor("symbol", weather)) add_devices(dev)
def setup_platform(hass, config, add_devices, discovery_info=None): """ Get the Yr.no sensor. """ if None in (hass.config.latitude, hass.config.longitude): _LOGGER.error("Latitude or longitude not set in Home Assistant config") return False elevation = config.get('elevation') if elevation is None: elevation = location.elevation(hass.config.latitude, hass.config.longitude) coordinates = dict(lat=hass.config.latitude, lon=hass.config.longitude, msl=elevation) weather = YrData(coordinates) dev = [] if 'monitored_conditions' in config: for variable in config['monitored_conditions']: if variable not in SENSOR_TYPES: _LOGGER.error('Sensor type: "%s" does not exist', variable) else: dev.append(YrSensor(variable, weather)) # add symbol as default sensor if len(dev) == 0: dev.append(YrSensor("symbol", weather)) add_devices(dev)
def create_default_config(config_dir, detect_location=True): """Create a default configuration file in given configuration directory. Return path to new config file if success, None if failed. This method needs to run in an executor. """ from homeassistant.components.config.group import (CONFIG_PATH as GROUP_CONFIG_PATH) config_path = os.path.join(config_dir, YAML_CONFIG_FILE) version_path = os.path.join(config_dir, VERSION_FILE) group_yaml_path = os.path.join(config_dir, GROUP_CONFIG_PATH) info = {attr: default for attr, default, _, _ in DEFAULT_CORE_CONFIG} location_info = detect_location and loc_util.detect_location_info() if location_info: if location_info.use_metric: info[CONF_UNIT_SYSTEM] = CONF_UNIT_SYSTEM_METRIC else: info[CONF_UNIT_SYSTEM] = CONF_UNIT_SYSTEM_IMPERIAL for attr, default, prop, _ in DEFAULT_CORE_CONFIG: if prop is None: continue info[attr] = getattr(location_info, prop) or default if location_info.latitude and location_info.longitude: info[CONF_ELEVATION] = loc_util.elevation(location_info.latitude, location_info.longitude) # Writing files with YAML does not create the most human readable results # So we're hard coding a YAML template. try: with open(config_path, 'w') as config_file: config_file.write("homeassistant:\n") for attr, _, _, description in DEFAULT_CORE_CONFIG: if info[attr] is None: continue elif description: config_file.write(" # {}\n".format(description)) config_file.write(" {}: {}\n".format(attr, info[attr])) config_file.write(DEFAULT_CONFIG) with open(version_path, 'wt') as version_file: version_file.write(__version__) with open(group_yaml_path, 'w'): pass return config_path except IOError: print('Unable to create default configuration file', config_path) return None
def create_default_config(config_dir, detect_location=True): """Create a default configuration file in given configuration directory. Return path to new config file if success, None if failed. This method needs to run in an executor. """ from homeassistant.components.config.group import ( CONFIG_PATH as GROUP_CONFIG_PATH) config_path = os.path.join(config_dir, YAML_CONFIG_FILE) version_path = os.path.join(config_dir, VERSION_FILE) group_yaml_path = os.path.join(config_dir, GROUP_CONFIG_PATH) info = {attr: default for attr, default, _, _ in DEFAULT_CORE_CONFIG} location_info = detect_location and loc_util.detect_location_info() if location_info: if location_info.use_metric: info[CONF_UNIT_SYSTEM] = CONF_UNIT_SYSTEM_METRIC else: info[CONF_UNIT_SYSTEM] = CONF_UNIT_SYSTEM_IMPERIAL for attr, default, prop, _ in DEFAULT_CORE_CONFIG: if prop is None: continue info[attr] = getattr(location_info, prop) or default if location_info.latitude and location_info.longitude: info[CONF_ELEVATION] = loc_util.elevation(location_info.latitude, location_info.longitude) # Writing files with YAML does not create the most human readable results # So we're hard coding a YAML template. try: with open(config_path, 'w') as config_file: config_file.write("homeassistant:\n") for attr, _, _, description in DEFAULT_CORE_CONFIG: if info[attr] is None: continue elif description: config_file.write(" # {}\n".format(description)) config_file.write(" {}: {}\n".format(attr, info[attr])) config_file.write(DEFAULT_CONFIG) with open(version_path, 'wt') as version_file: version_file.write(__version__) with open(group_yaml_path, 'w'): pass return config_path except IOError: print('Unable to create default configuration file', config_path) return None
def create_default_config(config_dir, detect_location=True): """Create a default configuration file in given configuration directory. Return path to new config file if success, None if failed. """ config_path = os.path.join(config_dir, YAML_CONFIG_FILE) version_path = os.path.join(config_dir, VERSION_FILE) info = {attr: default for attr, default, _, _ in DEFAULT_CONFIG} location_info = detect_location and loc_util.detect_location_info() if location_info: if location_info.use_fahrenheit: info[CONF_TEMPERATURE_UNIT] = 'F' for attr, default, prop, _ in DEFAULT_CONFIG: if prop is None: continue info[attr] = getattr(location_info, prop) or default if location_info.latitude and location_info.longitude: info[CONF_ELEVATION] = loc_util.elevation(location_info.latitude, location_info.longitude) # Writing files with YAML does not create the most human readable results # So we're hard coding a YAML template. try: with open(config_path, 'w') as config_file: config_file.write("homeassistant:\n") for attr, _, _, description in DEFAULT_CONFIG: if info[attr] is None: continue elif description: config_file.write(" # {}\n".format(description)) config_file.write(" {}: {}\n".format(attr, info[attr])) config_file.write("\n") for component, description in DEFAULT_COMPONENTS.items(): config_file.write("# {}\n".format(description)) config_file.write("{}\n\n".format(component)) with open(version_path, 'wt') as version_file: version_file.write(__version__) return config_path except IOError: print('Unable to create default configuration file', config_path) return None
def setup(hass, config): """Track the state of the sun.""" if None in (hass.config.latitude, hass.config.longitude): _LOGGER.error("Latitude or longitude not set in Home Assistant config") return False latitude = util.convert(hass.config.latitude, float) longitude = util.convert(hass.config.longitude, float) errors = [] if latitude is None: errors.append('Latitude needs to be a decimal value') elif -90 > latitude < 90: errors.append('Latitude needs to be -90 .. 90') if longitude is None: errors.append('Longitude needs to be a decimal value') elif -180 > longitude < 180: errors.append('Longitude needs to be -180 .. 180') if errors: _LOGGER.error('Invalid configuration received: %s', ", ".join(errors)) return False platform_config = config.get(DOMAIN, {}) elevation = platform_config.get(CONF_ELEVATION) if elevation is None: elevation = location_util.elevation(latitude, longitude) from astral import Location location = Location(('', '', latitude, longitude, hass.config.time_zone.zone, elevation)) sun = Sun(hass, location) sun.point_in_time_listener(dt_util.utcnow()) return True
def set_homeassistant_config(self): info = { attr: default for attr, default, _, _ in POLY_HOMEASSISTANT_CONFIG } location_info = True and loc_util.detect_location_info() # print(location_info) if location_info: if location_info.use_metric: info[CONF_UNIT_SYSTEM] = CONF_UNIT_SYSTEM_METRIC else: info[CONF_UNIT_SYSTEM] = CONF_UNIT_SYSTEM_IMPERIAL for attr, default, prop, _ in POLY_HOMEASSISTANT_CONFIG: if prop is None: continue info[attr] = getattr(location_info, prop) or default if location_info.latitude and location_info.longitude: info[CONF_ELEVATION] = loc_util.elevation( location_info.latitude, location_info.longitude) try: # write default config text with open(self._save_dir + 'configuration.yaml', 'wt') as config_file: config_file.write("homeassistant:\n") for attr, _, _, description in POLY_HOMEASSISTANT_CONFIG: if info[attr] is None: continue elif description: config_file.write(" # {}\n".format(description)) config_file.write(" {}: {}\n".format(attr, info[attr])) except IOError: _LOGGER.error("Unable to create default configuration file") finally: config_file.close()
def test_elevation_query_nonjson(self, mock_req): """Test if elevation API returns a non JSON value.""" mock_req.get(location_util.ELEVATION_URL, text='{ I am not JSON }') elevation = location_util.elevation(10, 10, _test_real=True) assert elevation == 0
def test_elevation_query_fails(self, mock_req): """Test elevation when the request to API fails.""" mock_req.get(location_util.ELEVATION_URL, text='{}', status_code=401) elevation = location_util.elevation(10, 10, _test_real=True) assert elevation == 0
def test_elevation_query_raises(self, mock_get): """Test elevation when the request to API fails.""" elevation = location_util.elevation(10, 10, _test_real=True) assert elevation == 0
def process_ha_core_config(hass, config): """Process the [homeassistant] section from the config.""" # pylint: disable=too-many-branches config = CORE_CONFIG_SCHEMA(config) hac = hass.config def set_time_zone(time_zone_str): """Helper method to set time zone.""" if time_zone_str is None: return time_zone = date_util.get_time_zone(time_zone_str) if time_zone: hac.time_zone = time_zone date_util.set_default_time_zone(time_zone) else: _LOGGER.error('Received invalid time zone %s', time_zone_str) for key, attr in ((CONF_LATITUDE, 'latitude'), (CONF_LONGITUDE, 'longitude'), (CONF_NAME, 'location_name'), (CONF_ELEVATION, 'elevation')): if key in config: setattr(hac, attr, config[key]) if CONF_TIME_ZONE in config: set_time_zone(config.get(CONF_TIME_ZONE)) set_customize(config.get(CONF_CUSTOMIZE) or {}) if CONF_TEMPERATURE_UNIT in config: hac.temperature_unit = config[CONF_TEMPERATURE_UNIT] # Shortcut if no auto-detection necessary if None not in (hac.latitude, hac.longitude, hac.temperature_unit, hac.time_zone, hac.elevation): return discovered = [] # If we miss some of the needed values, auto detect them if None in (hac.latitude, hac.longitude, hac.temperature_unit, hac.time_zone): info = loc_util.detect_location_info() if info is None: _LOGGER.error('Could not detect location information') return if hac.latitude is None and hac.longitude is None: hac.latitude = info.latitude hac.longitude = info.longitude discovered.append(('latitude', hac.latitude)) discovered.append(('longitude', hac.longitude)) if hac.temperature_unit is None: if info.use_fahrenheit: hac.temperature_unit = TEMP_FAHRENHEIT discovered.append(('temperature_unit', 'F')) else: hac.temperature_unit = TEMP_CELSIUS discovered.append(('temperature_unit', 'C')) if hac.location_name is None: hac.location_name = info.city discovered.append(('name', info.city)) if hac.time_zone is None: set_time_zone(info.time_zone) discovered.append(('time_zone', info.time_zone)) if hac.elevation is None and hac.latitude is not None and \ hac.longitude is not None: elevation = loc_util.elevation(hac.latitude, hac.longitude) hac.elevation = elevation discovered.append(('elevation', elevation)) if discovered: _LOGGER.warning( 'Incomplete core config. Auto detected %s', ', '.join('{}: {}'.format(key, val) for key, val in discovered))
def process_ha_core_config(hass, config): """Process the [homeassistant] section from the config.""" # pylint: disable=too-many-branches config = CORE_CONFIG_SCHEMA(config) hac = hass.config def set_time_zone(time_zone_str): """Helper method to set time zone.""" if time_zone_str is None: return time_zone = date_util.get_time_zone(time_zone_str) if time_zone: hac.time_zone = time_zone date_util.set_default_time_zone(time_zone) else: _LOGGER.error('Received invalid time zone %s', time_zone_str) for key, attr in ((CONF_LATITUDE, 'latitude'), (CONF_LONGITUDE, 'longitude'), (CONF_NAME, 'location_name'), (CONF_ELEVATION, 'elevation')): if key in config: setattr(hac, attr, config[key]) if CONF_TIME_ZONE in config: set_time_zone(config.get(CONF_TIME_ZONE)) set_customize(config.get(CONF_CUSTOMIZE) or {}) if CONF_UNIT_SYSTEM in config: if config[CONF_UNIT_SYSTEM] == CONF_UNIT_SYSTEM_IMPERIAL: hac.units = IMPERIAL_SYSTEM else: hac.units = METRIC_SYSTEM elif CONF_TEMPERATURE_UNIT in config: unit = config[CONF_TEMPERATURE_UNIT] if unit == TEMP_CELSIUS: hac.units = METRIC_SYSTEM else: hac.units = IMPERIAL_SYSTEM _LOGGER.warning("Found deprecated temperature unit in core config, " "expected unit system. Replace '%s: %s' with " "'%s: %s'", CONF_TEMPERATURE_UNIT, unit, CONF_UNIT_SYSTEM, hac.units.name) # Shortcut if no auto-detection necessary if None not in (hac.latitude, hac.longitude, hac.units, hac.time_zone, hac.elevation): return discovered = [] # If we miss some of the needed values, auto detect them if None in (hac.latitude, hac.longitude, hac.units, hac.time_zone): info = loc_util.detect_location_info() if info is None: _LOGGER.error('Could not detect location information') return if hac.latitude is None and hac.longitude is None: hac.latitude, hac.longitude = (info.latitude, info.longitude) discovered.append(('latitude', hac.latitude)) discovered.append(('longitude', hac.longitude)) if hac.units is None: hac.units = METRIC_SYSTEM if info.use_metric else IMPERIAL_SYSTEM discovered.append((CONF_UNIT_SYSTEM, hac.units.name)) if hac.location_name is None: hac.location_name = info.city discovered.append(('name', info.city)) if hac.time_zone is None: set_time_zone(info.time_zone) discovered.append(('time_zone', info.time_zone)) if hac.elevation is None and hac.latitude is not None and \ hac.longitude is not None: elevation = loc_util.elevation(hac.latitude, hac.longitude) hac.elevation = elevation discovered.append(('elevation', elevation)) if discovered: _LOGGER.warning( 'Incomplete core config. Auto detected %s', ', '.join('{}: {}'.format(key, val) for key, val in discovered))
def process_ha_core_config(hass, config): """Process the [homeassistant] section from the config.""" # pylint: disable=too-many-branches config = CORE_CONFIG_SCHEMA(config) hac = hass.config def set_time_zone(time_zone_str): """Helper method to set time zone.""" if time_zone_str is None: return time_zone = date_util.get_time_zone(time_zone_str) if time_zone: hac.time_zone = time_zone date_util.set_default_time_zone(time_zone) else: _LOGGER.error('Received invalid time zone %s', time_zone_str) for key, attr in ((CONF_LATITUDE, 'latitude'), (CONF_LONGITUDE, 'longitude'), (CONF_NAME, 'location_name'), (CONF_ELEVATION, 'elevation')): if key in config: setattr(hac, attr, config[key]) if CONF_TIME_ZONE in config: set_time_zone(config.get(CONF_TIME_ZONE)) set_customize(config.get(CONF_CUSTOMIZE) or {}) if CONF_UNIT_SYSTEM in config: if config[CONF_UNIT_SYSTEM] == CONF_UNIT_SYSTEM_IMPERIAL: hac.units = IMPERIAL_SYSTEM else: hac.units = METRIC_SYSTEM elif CONF_TEMPERATURE_UNIT in config: unit = config[CONF_TEMPERATURE_UNIT] if unit == TEMP_CELSIUS: hac.units = METRIC_SYSTEM else: hac.units = IMPERIAL_SYSTEM _LOGGER.warning( "Found deprecated temperature unit in core config, " "expected unit system. Replace '%s: %s' with " "'%s: %s'", CONF_TEMPERATURE_UNIT, unit, CONF_UNIT_SYSTEM, hac.units.name) # Shortcut if no auto-detection necessary if None not in (hac.latitude, hac.longitude, hac.units, hac.time_zone, hac.elevation): return discovered = [] # If we miss some of the needed values, auto detect them if None in (hac.latitude, hac.longitude, hac.units, hac.time_zone): info = loc_util.detect_location_info() if info is None: _LOGGER.error('Could not detect location information') return if hac.latitude is None and hac.longitude is None: hac.latitude, hac.longitude = (info.latitude, info.longitude) discovered.append(('latitude', hac.latitude)) discovered.append(('longitude', hac.longitude)) if hac.units is None: hac.units = METRIC_SYSTEM if info.use_metric else IMPERIAL_SYSTEM discovered.append((CONF_UNIT_SYSTEM, hac.units.name)) if hac.location_name is None: hac.location_name = info.city discovered.append(('name', info.city)) if hac.time_zone is None: set_time_zone(info.time_zone) discovered.append(('time_zone', info.time_zone)) if hac.elevation is None and hac.latitude is not None and \ hac.longitude is not None: elevation = loc_util.elevation(hac.latitude, hac.longitude) hac.elevation = elevation discovered.append(('elevation', elevation)) if discovered: _LOGGER.warning( 'Incomplete core config. Auto detected %s', ', '.join('{}: {}'.format(key, val) for key, val in discovered))