本文整理汇总了Python中homeassistant.helpers.typing.ConfigType类的典型用法代码示例。如果您正苦于以下问题:Python ConfigType类的具体用法?Python ConfigType怎么用?Python ConfigType使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ConfigType类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: async_setup_platform
async def async_setup_platform(hass: HomeAssistantType, config: ConfigType,
async_add_devices, discovery_info=None):
"""Set up the WUnderground sensor."""
latitude = config.get(CONF_LATITUDE, hass.config.latitude)
longitude = config.get(CONF_LONGITUDE, hass.config.longitude)
pws_id = config.get(CONF_PWS_ID)
rest = WUndergroundData(
hass, config.get(CONF_API_KEY), pws_id,
config.get(CONF_LANG), latitude, longitude)
if pws_id is None:
unique_id_base = "@{:06f},{:06f}".format(longitude, latitude)
else:
# Manually specified weather station, use that for unique_id
unique_id_base = pws_id
sensors = []
for variable in config[CONF_MONITORED_CONDITIONS]:
sensors.append(WUndergroundSensor(hass, rest, variable,
unique_id_base))
await rest.async_update()
if not rest.data:
raise PlatformNotReady
async_add_devices(sensors, True)
示例2: validate_device_has_at_least_one_identifier
def validate_device_has_at_least_one_identifier(value: ConfigType) -> \
ConfigType:
"""Validate that a device info entry has at least one identifying value."""
if not value.get(CONF_IDENTIFIERS) and not value.get(CONF_CONNECTIONS):
raise vol.Invalid("Device must have at least one identifying value in "
"'identifiers' and/or 'connections'")
return value
示例3: async_setup_platform
async def async_setup_platform(hass: HomeAssistantType, config: ConfigType,
async_add_devices, discovery_info=None):
"""Set up the cast platform."""
import pychromecast
# Import CEC IGNORE attributes
pychromecast.IGNORE_CEC += config.get(CONF_IGNORE_CEC, [])
hass.data.setdefault(ADDED_CAST_DEVICES_KEY, {})
hass.data.setdefault(KNOWN_CHROMECASTS_KEY, {})
# None -> use discovery; (host, port) -> manually specify chromecast.
want_host = None
if discovery_info:
want_host = (discovery_info.get('host'), discovery_info.get('port'))
elif CONF_HOST in config:
want_host = (config.get(CONF_HOST), DEFAULT_PORT)
enable_discovery = False
if want_host is None:
# We were explicitly told to enable pychromecast discovery.
enable_discovery = True
elif want_host[1] != DEFAULT_PORT:
# We're trying to add a group, so we have to use pychromecast's
# discovery to get the correct friendly name.
enable_discovery = True
if enable_discovery:
@callback
def async_cast_discovered(chromecast):
"""Callback for when a new chromecast is discovered."""
if want_host is not None and \
(chromecast.host, chromecast.port) != want_host:
return # for groups, only add requested device
cast_device = _async_create_cast_device(hass, chromecast)
if cast_device is not None:
async_add_devices([cast_device])
async_dispatcher_connect(hass, SIGNAL_CAST_DISCOVERED,
async_cast_discovered)
# Re-play the callback for all past chromecasts, store the objects in
# a list to avoid concurrent modification resulting in exception.
for chromecast in list(hass.data[KNOWN_CHROMECASTS_KEY].values()):
async_cast_discovered(chromecast)
hass.async_add_job(_setup_internal_discovery, hass)
else:
# Manually add a "normal" Chromecast, we can do that without discovery.
try:
chromecast = await hass.async_add_job(
pychromecast.Chromecast, *want_host)
except pychromecast.ChromecastConnectionError as err:
_LOGGER.warning("Can't set up chromecast on %s: %s",
want_host[0], err)
raise PlatformNotReady
key = (chromecast.host, chromecast.port, chromecast.uuid)
cast_device = _async_create_cast_device(hass, chromecast)
if cast_device is not None:
hass.data[KNOWN_CHROMECASTS_KEY][key] = chromecast
async_add_devices([cast_device])
示例4: setup_platform
def setup_platform(hass, config: ConfigType,
add_devices: Callable[[list], None], discovery_info=None):
"""Set up the Sesame platform."""
import pysesame
email = config.get(CONF_EMAIL)
password = config.get(CONF_PASSWORD)
add_devices([SesameDevice(sesame) for
sesame in pysesame.get_sesames(email, password)])
示例5: from_config
def from_config(config: ConfigType, config_validation: bool=True):
"""Turn a condition configuration into a method."""
factory = getattr(
sys.modules[__name__],
FROM_CONFIG_FORMAT.format(config.get(CONF_CONDITION)), None)
if factory is None:
raise HomeAssistantError('Invalid condition "{}" specified {}'.format(
config.get(CONF_CONDITION), config))
return factory(config, config_validation)
示例6: async_setup
async def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool:
"""Start the MQTT protocol service."""
conf = config.get(DOMAIN) # type: Optional[ConfigType]
# We need this because discovery can cause components to be set up and
# otherwise it will not load the users config.
# This needs a better solution.
hass.data[DATA_MQTT_HASS_CONFIG] = config
if conf is None:
# If we have a config entry, setup is done by that config entry.
# If there is no config entry, this should fail.
return bool(hass.config_entries.async_entries(DOMAIN))
conf = dict(conf)
if CONF_EMBEDDED in conf or CONF_BROKER not in conf:
if (conf.get(CONF_PASSWORD) is None and
config.get('http', {}).get('api_password') is not None):
_LOGGER.error(
"Starting from release 0.76, the embedded MQTT broker does not"
" use api_password as default password anymore. Please set"
" password configuration. See https://home-assistant.io/docs/"
"mqtt/broker#embedded-broker for details")
return False
broker_config = await _async_setup_server(hass, config)
if broker_config is None:
_LOGGER.error("Unable to start embedded MQTT broker")
return False
conf.update({
CONF_BROKER: broker_config[0],
CONF_PORT: broker_config[1],
CONF_USERNAME: broker_config[2],
CONF_PASSWORD: broker_config[3],
CONF_CERTIFICATE: broker_config[4],
CONF_PROTOCOL: broker_config[5],
CONF_CLIENT_KEY: None,
CONF_CLIENT_CERT: None,
CONF_TLS_INSECURE: None,
})
hass.data[DATA_MQTT_CONFIG] = conf
# Only import if we haven't before.
if not hass.config_entries.async_entries(DOMAIN):
hass.async_create_task(hass.config_entries.flow.async_init(
DOMAIN, context={'source': config_entries.SOURCE_IMPORT},
data={}
))
return True
示例7: zone_from_config
def zone_from_config(config: ConfigType,
config_validation: bool = True) -> Callable[..., bool]:
"""Wrap action method with zone based condition."""
if config_validation:
config = cv.ZONE_CONDITION_SCHEMA(config)
entity_id = config.get(CONF_ENTITY_ID)
zone_entity_id = config.get(CONF_ZONE)
def if_in_zone(hass: HomeAssistant,
variables: TemplateVarsType = None) -> bool:
"""Test if condition."""
return zone(hass, zone_entity_id, entity_id)
return if_in_zone
示例8: time_from_config
def time_from_config(config: ConfigType,
config_validation: bool = True) -> Callable[..., bool]:
"""Wrap action method with time based condition."""
if config_validation:
config = cv.TIME_CONDITION_SCHEMA(config)
before = config.get(CONF_BEFORE)
after = config.get(CONF_AFTER)
weekday = config.get(CONF_WEEKDAY)
def time_if(hass: HomeAssistant,
variables: TemplateVarsType = None) -> bool:
"""Validate time based if-condition."""
return time(before, after, weekday)
return time_if
示例9: state_from_config
def state_from_config(config: ConfigType,
config_validation: bool = True) -> Callable[..., bool]:
"""Wrap action method with state based condition."""
if config_validation:
config = cv.STATE_CONDITION_SCHEMA(config)
entity_id = config.get(CONF_ENTITY_ID)
req_state = cast(str, config.get(CONF_STATE))
for_period = config.get('for')
def if_state(hass: HomeAssistant,
variables: TemplateVarsType = None) -> bool:
"""Test if condition."""
return state(hass, entity_id, req_state, for_period)
return if_state
示例10: async_from_config
def async_from_config(config: ConfigType, config_validation: bool = True):
"""Turn a condition configuration into a method.
Should be run on the event loop.
"""
for fmt in (ASYNC_FROM_CONFIG_FORMAT, FROM_CONFIG_FORMAT):
factory = getattr(sys.modules[__name__], fmt.format(config.get(CONF_CONDITION)), None)
if factory:
break
if factory is None:
raise HomeAssistantError('Invalid condition "{}" specified {}'.format(config.get(CONF_CONDITION), config))
return factory(config, config_validation)
示例11: async_setup_scanner_platform
def async_setup_scanner_platform(hass: HomeAssistantType, config: ConfigType,
scanner: Any, async_see_device: Callable):
"""Helper method to connect scanner-based platform to device tracker.
This method is a coroutine.
"""
interval = config.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL)
# Initial scan of each mac we also tell about host name for config
seen = set() # type: Any
def device_tracker_scan(now: dt_util.dt.datetime):
"""Called when interval matches."""
found_devices = scanner.scan_devices()
for mac in found_devices:
if mac in seen:
host_name = None
else:
host_name = scanner.get_device_name(mac)
seen.add(mac)
hass.add_job(async_see_device(mac=mac, host_name=host_name))
async_track_utc_time_change(
hass, device_tracker_scan, second=range(0, 60, interval))
hass.async_add_job(device_tracker_scan, None)
示例12: async_setup
def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up the recorder."""
conf = config.get(DOMAIN, {})
keep_days = conf.get(CONF_PURGE_KEEP_DAYS)
purge_interval = conf.get(CONF_PURGE_INTERVAL)
if keep_days is None and purge_interval != 0:
_LOGGER.warning(
"From version 0.64.0 the 'recorder' component will by default "
"purge data older than 10 days. To keep data longer you must "
"configure 'purge_keep_days' or 'purge_interval'.")
db_url = conf.get(CONF_DB_URL, None)
if not db_url:
db_url = DEFAULT_URL.format(
hass_config_path=hass.config.path(DEFAULT_DB_FILE))
include = conf.get(CONF_INCLUDE, {})
exclude = conf.get(CONF_EXCLUDE, {})
instance = hass.data[DATA_INSTANCE] = Recorder(
hass=hass, keep_days=keep_days, purge_interval=purge_interval,
uri=db_url, include=include, exclude=exclude)
instance.async_initialize()
instance.start()
@asyncio.coroutine
def async_handle_purge_service(service):
"""Handle calls to the purge service."""
instance.do_adhoc_purge(service.data[ATTR_KEEP_DAYS])
hass.services.async_register(
DOMAIN, SERVICE_PURGE, async_handle_purge_service,
schema=SERVICE_PURGE_SCHEMA)
return (yield from instance.async_db_ready)
示例13: async_setup
def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up the recorder."""
conf = config.get(DOMAIN, {})
keep_days = conf.get(CONF_PURGE_KEEP_DAYS)
purge_interval = conf.get(CONF_PURGE_INTERVAL)
db_url = conf.get(CONF_DB_URL, None)
if not db_url:
db_url = DEFAULT_URL.format(
hass_config_path=hass.config.path(DEFAULT_DB_FILE))
include = conf.get(CONF_INCLUDE, {})
exclude = conf.get(CONF_EXCLUDE, {})
instance = hass.data[DATA_INSTANCE] = Recorder(
hass=hass, keep_days=keep_days, purge_interval=purge_interval,
uri=db_url, include=include, exclude=exclude)
instance.async_initialize()
instance.start()
@asyncio.coroutine
def async_handle_purge_service(service):
"""Handle calls to the purge service."""
instance.do_adhoc_purge(service.data[ATTR_KEEP_DAYS])
hass.services.async_register(
DOMAIN, SERVICE_PURGE, async_handle_purge_service,
schema=SERVICE_PURGE_SCHEMA)
return (yield from instance.async_db_ready)
示例14: sun_from_config
def sun_from_config(config: ConfigType,
config_validation: bool = True) -> Callable[..., bool]:
"""Wrap action method with sun based condition."""
if config_validation:
config = cv.SUN_CONDITION_SCHEMA(config)
before = config.get('before')
after = config.get('after')
before_offset = config.get('before_offset')
after_offset = config.get('after_offset')
def time_if(hass: HomeAssistant,
variables: TemplateVarsType = None) -> bool:
"""Validate time based if-condition."""
return sun(hass, before, after, before_offset, after_offset)
return time_if
示例15: async_setup_scanner_platform
def async_setup_scanner_platform(hass: HomeAssistantType, config: ConfigType,
scanner: Any, async_see_device: Callable,
platform: str):
"""Set up the connect scanner-based platform to device tracker.
This method must be run in the event loop.
"""
interval = config.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL)
update_lock = asyncio.Lock(loop=hass.loop)
scanner.hass = hass
# Initial scan of each mac we also tell about host name for config
seen = set() # type: Any
@asyncio.coroutine
def async_device_tracker_scan(now: dt_util.dt.datetime):
"""Handle interval matches."""
if update_lock.locked():
_LOGGER.warning(
"Updating device list from %s took longer than the scheduled "
"scan interval %s", platform, interval)
return
with (yield from update_lock):
found_devices = yield from scanner.async_scan_devices()
for mac in found_devices:
if mac in seen:
host_name = None
else:
host_name = yield from scanner.async_get_device_name(mac)
seen.add(mac)
try:
extra_attributes = (yield from
scanner.async_get_extra_attributes(mac))
except NotImplementedError:
extra_attributes = dict()
kwargs = {
'mac': mac,
'host_name': host_name,
'source_type': SOURCE_TYPE_ROUTER,
'attributes': {
'scanner': scanner.__class__.__name__,
**extra_attributes
}
}
zone_home = hass.states.get(zone.ENTITY_ID_HOME)
if zone_home:
kwargs['gps'] = [zone_home.attributes[ATTR_LATITUDE],
zone_home.attributes[ATTR_LONGITUDE]]
kwargs['gps_accuracy'] = 0
hass.async_add_job(async_see_device(**kwargs))
async_track_time_interval(hass, async_device_tracker_scan, interval)
hass.async_add_job(async_device_tracker_scan(None))