def is_on(hass, entity_id=None): """Load up the module to call the is_on method. If there is no entity id given we will check all. """ if entity_id: group = get_component('group') entity_ids = group.expand_entity_ids(hass, [entity_id]) else: entity_ids = hass.states.entity_ids() for entity_id in entity_ids: domain = split_entity_id(entity_id)[0] module = get_component(domain) try: if module.is_on(hass, entity_id): return True except AttributeError: # module is None or method is_on does not exist _LOGGER.exception("Failed to call %s.is_on for %s", module, entity_id) return False
def setUp(self): # pylint: disable=invalid-name """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() event_decorators.HASS = self.hass self.scanner = loader.get_component('device_tracker.test').get_scanner( None, None) self.scanner.reset() self.scanner.come_home('DEV1') loader.get_component('light.test').init() self.assertTrue( device_tracker.setup( self.hass, {device_tracker.DOMAIN: { CONF_PLATFORM: 'test' }})) self.assertTrue( light.setup(self.hass, {light.DOMAIN: { CONF_PLATFORM: 'test' }})) self.assertTrue( sun.setup(self.hass, {sun.DOMAIN: { sun.CONF_ELEVATION: 0 }}))
def is_on(hass, entity_id=None): """Load up the module to call the is_on method. If there is no entity id given we will check all. """ if entity_id: group = get_component('group') entity_ids = group.expand_entity_ids(hass, [entity_id]) else: entity_ids = hass.states.entity_ids() for entity_id in entity_ids: domain = split_entity_id(entity_id)[0] module = get_component(domain) try: if module.is_on(hass, entity_id): return True except AttributeError: # module is None or method is_on does not exist _LOGGER.exception("Failed to call %s.is_on for %s", module, entity_id) return False
def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the Fitbit sensor.""" config_path = hass.config.path(FITBIT_CONFIG_FILE) if os.path.isfile(config_path): config_file = config_from_file(config_path) if config_file == DEFAULT_CONFIG: request_app_setup(hass, config, add_devices, config_path, discovery_info=None) return False else: config_file = config_from_file(config_path, DEFAULT_CONFIG) request_app_setup(hass, config, add_devices, config_path, discovery_info=None) return False if "fitbit" in _CONFIGURING: get_component("configurator").request_done(_CONFIGURING.pop("fitbit")) import fitbit access_token = config_file.get("access_token") refresh_token = config_file.get("refresh_token") if None not in (access_token, refresh_token): authd_client = fitbit.Fitbit(config_file.get("client_id"), config_file.get("client_secret"), access_token=access_token, refresh_token=refresh_token) if int(time.time()) - config_file.get("last_saved_at", 0) > 3600: authd_client.client.refresh_token() authd_client.system = authd_client.user_profile_get()["user"]["locale"] dev = [] for resource in config.get("monitored_resources", FITBIT_DEFAULT_RESOURCE_LIST): dev.append(FitbitSensor(authd_client, config_path, resource, hass.config.temperature_unit == TEMP_CELSIUS)) add_devices(dev) else: oauth = fitbit.api.FitbitOauth2Client(config_file.get("client_id"), config_file.get("client_secret")) redirect_uri = "{}{}".format(hass.config.api.base_url, FITBIT_AUTH_CALLBACK_PATH) fitbit_auth_start_url, _ = oauth.authorize_token_url( redirect_uri=redirect_uri, scope=["activity", "heartrate", "nutrition", "profile", "settings", "sleep", "weight"]) hass.wsgi.register_redirect(FITBIT_AUTH_START, fitbit_auth_start_url) hass.wsgi.register_view(FitbitAuthCallbackView(hass, config, add_devices, oauth)) request_oauth_completion(hass)
def setup(hass, config): """Setup Insteon Hub component. This will automatically import associated lights. """ if not validate_config( config, {DOMAIN: [CONF_USERNAME, CONF_PASSWORD, CONF_API_KEY]}, _LOGGER): return False import insteon username = config[DOMAIN][CONF_USERNAME] password = config[DOMAIN][CONF_PASSWORD] api_key = config[DOMAIN][CONF_API_KEY] global INSTEON INSTEON = insteon.Insteon(username, password, api_key) if INSTEON is None: _LOGGER.error("Could not connect to Insteon service.") return comp_name = 'light' discovery = DISCOVER_LIGHTS component = get_component(comp_name) bootstrap.setup_component(hass, component.DOMAIN, config) hass.bus.fire( EVENT_PLATFORM_DISCOVERED, {ATTR_SERVICE: discovery, ATTR_DISCOVERED: {}}) return True
def setup_platform(hass, config, add_devices, discovery_info=None): """Setup the available OctoPrint sensors.""" octoprint = get_component('octoprint') name = config.get(CONF_NAME, "OctoPrint") monitored_conditions = config.get("monitored_conditions", SENSOR_TYPES.keys()) devices = [] types = ["actual", "target"] for octo_type in monitored_conditions: if octo_type == "Temperatures": for tool in octoprint.OCTOPRINT.get_tools(): for temp_type in types: new_sensor = OctoPrintSensor(octoprint.OCTOPRINT, temp_type, temp_type, name, SENSOR_TYPES[octo_type][3], SENSOR_TYPES[octo_type][0], SENSOR_TYPES[octo_type][1], tool) devices.append(new_sensor) elif octo_type in SENSOR_TYPES: new_sensor = OctoPrintSensor(octoprint.OCTOPRINT, octo_type, SENSOR_TYPES[octo_type][2], name, SENSOR_TYPES[octo_type][3], SENSOR_TYPES[octo_type][0], SENSOR_TYPES[octo_type][1]) devices.append(new_sensor) else: _LOGGER.error("Unknown OctoPrint sensor type: %s", octo_type) add_devices(devices)
def setup(hass, config): """Setup the Wink component.""" logger = logging.getLogger(__name__) if not validate_config(config, {DOMAIN: [CONF_ACCESS_TOKEN]}, logger): return False import pywink pywink.set_bearer_token(config[DOMAIN][CONF_ACCESS_TOKEN]) # Load components for the devices in the Wink that we support for component_name, func_exists, discovery_type in ( ('light', pywink.get_bulbs, DISCOVER_LIGHTS), ('switch', lambda: pywink.get_switches or pywink.get_sirens or pywink.get_powerstrip_outlets, DISCOVER_SWITCHES), ('binary_sensor', pywink.get_sensors, DISCOVER_BINARY_SENSORS), ('sensor', lambda: pywink.get_sensors or pywink.get_eggtrays, DISCOVER_SENSORS), ('lock', pywink.get_locks, DISCOVER_LOCKS), ('garage_door', pywink.get_garage_doors, DISCOVER_GARAGE_DOORS)): if func_exists(): component = get_component(component_name) # Ensure component is loaded bootstrap.setup_component(hass, component.DOMAIN, config) # Fire discovery event hass.bus.fire(EVENT_PLATFORM_DISCOVERED, { ATTR_SERVICE: discovery_type, ATTR_DISCOVERED: {} }) return True
def test_light_profiles(self): """Test light profiles.""" platform = loader.get_component('light.test') platform.init() user_light_file = self.hass.config.path(light.LIGHT_PROFILES_FILE) with open(user_light_file, 'w') as user_file: user_file.write('id,x,y,brightness\n') user_file.write('test,.4,.6,100\n') self.assertTrue(light.setup( self.hass, {light.DOMAIN: {CONF_PLATFORM: 'test'}} )) dev1, dev2, dev3 = platform.DEVICES light.turn_on(self.hass, dev1.entity_id, profile='test') self.hass.pool.block_till_done() method, data = dev1.last_call('turn_on') self.assertEqual( {light.ATTR_XY_COLOR: (.4, .6), light.ATTR_BRIGHTNESS: 100}, data)
def test_light_profiles(self): """Test light profiles.""" platform = loader.get_component('light.test') platform.init() user_light_file = self.hass.config.path(light.LIGHT_PROFILES_FILE) with open(user_light_file, 'w') as user_file: user_file.write('id,x,y,brightness\n') user_file.write('test,.4,.6,100\n') self.assertTrue( light.setup(self.hass, {light.DOMAIN: { CONF_PLATFORM: 'test' }})) dev1, dev2, dev3 = platform.DEVICES light.turn_on(self.hass, dev1.entity_id, profile='test') self.hass.pool.block_till_done() method, data = dev1.last_call('turn_on') self.assertEqual( { light.ATTR_XY_COLOR: (.4, .6), light.ATTR_BRIGHTNESS: 100 }, data)
def setup_tv(host, hass, add_devices): """Setup a phue bridge based on host parameter.""" from pylgtv import WebOsClient from pylgtv import PyLGTVPairException client = WebOsClient(host) if not client.is_registered(): if host in _CONFIGURING: # Try to pair. try: client.register() except PyLGTVPairException: _LOGGER.warning( 'Connected to LG WebOS TV at %s but not paired.', host) return except OSError: _LOGGER.error('Unable to connect to host %s.', host) return else: # Not registered, request configuration. _LOGGER.warning('LG WebOS TV at %s needs to be paired.', host) request_configuration(host, hass, add_devices) return # If we came here and configuring this host, mark as done. if client.is_registered() and host in _CONFIGURING: request_id = _CONFIGURING.pop(host) configurator = get_component('configurator') configurator.request_done(request_id) add_devices([LgWebOSDevice(host)])
def setup(hass, base_config): """Common setup for Vera devices.""" global VERA_CONTROLLER import pyvera as veraApi config = base_config.get(DOMAIN) base_url = config.get('vera_controller_url') if not base_url: _LOGGER.error("The required parameter 'vera_controller_url'" " was not found in config") return False VERA_CONTROLLER, _ = veraApi.init_controller(base_url) def stop_subscription(event): """Shutdown Vera subscriptions and subscription thread on exit.""" _LOGGER.info("Shutting down subscriptions.") VERA_CONTROLLER.stop() hass.bus.listen_once(EVENT_BLUMATE_STOP, stop_subscription) try: all_devices = VERA_CONTROLLER.get_devices( list(DEVICE_CATEGORIES.keys())) except RequestException: # There was a network related error connecting to the vera controller. _LOGGER.exception("Error communicating with Vera API") return False exclude = config.get(CONF_EXCLUDE, []) if not isinstance(exclude, list): _LOGGER.error("'exclude' must be a list of device_ids") return False lights_ids = config.get(CONF_LIGHTS, []) if not isinstance(lights_ids, list): _LOGGER.error("'lights' must be a list of device_ids") return False for device in all_devices: if device.device_id in exclude: continue dev_type = DEVICE_CATEGORIES.get(device.category) if dev_type is None: continue if dev_type == SWITCH and device.device_id in lights_ids: dev_type = LIGHT VERA_DEVICES[dev_type].append(device) for comp_name, discovery in (((BINARY_SENSOR, DISCOVER_BINARY_SENSORS), (SENSOR, DISCOVER_SENSORS), (LIGHT, DISCOVER_LIGHTS), (SWITCH, DISCOVER_SWITCHES))): component = get_component(comp_name) bootstrap.setup_component(hass, component.DOMAIN, base_config) hass.bus.fire(EVENT_PLATFORM_DISCOVERED, { ATTR_SERVICE: discovery, ATTR_DISCOVERED: {} }) return True
def test_activate_scene(self): """Test active scene.""" test_light = loader.get_component('light.test') test_light.init() self.assertTrue(light.setup(self.hass, { light.DOMAIN: {'platform': 'test'} })) light_1, light_2 = test_light.DEVICES[0:2] light.turn_off(self.hass, [light_1.entity_id, light_2.entity_id]) self.hass.pool.block_till_done() self.assertTrue(scene.setup(self.hass, { 'scene': [{ 'name': 'test', 'entities': { light_1.entity_id: 'on', light_2.entity_id: { 'state': 'on', 'brightness': 100, } } }] })) scene.activate(self.hass, 'scene.test') self.hass.pool.block_till_done() self.assertTrue(light_1.is_on) self.assertTrue(light_2.is_on) self.assertEqual(100, light_2.last_call('turn_on')[1].get('brightness'))
def setup(hass, config): """Setup ISY994 component. This will automatically import associated lights, switches, and sensors. """ import PyISY # pylint: disable=global-statement # check for required values in configuration file if not validate_config(config, {DOMAIN: [CONF_HOST, CONF_USERNAME, CONF_PASSWORD]}, _LOGGER): return False # Pull and parse standard configuration. user = config[DOMAIN][CONF_USERNAME] password = config[DOMAIN][CONF_PASSWORD] host = urlparse(config[DOMAIN][CONF_HOST]) addr = host.geturl() if host.scheme == 'http': addr = addr.replace('http://', '') https = False elif host.scheme == 'https': addr = addr.replace('https://', '') https = True else: _LOGGER.error('isy994 host value in configuration file is invalid.') return False port = host.port addr = addr.replace(':{}'.format(port), '') # Pull and parse optional configuration. global SENSOR_STRING global HIDDEN_STRING SENSOR_STRING = str(config[DOMAIN].get('sensor_string', SENSOR_STRING)) HIDDEN_STRING = str(config[DOMAIN].get('hidden_string', HIDDEN_STRING)) tls_version = config[DOMAIN].get(CONF_TLS_VER, None) # Connect to ISY controller. global ISY ISY = PyISY.ISY(addr, port, user, password, use_https=https, tls_ver=tls_version, log=_LOGGER) if not ISY.connected: return False # Listen for HA stop to disconnect. hass.bus.listen_once(EVENT_BLUMATE_STOP, stop) # Load components for the devices in the ISY controller that we support. for comp_name, discovery in ((('sensor', DISCOVER_SENSORS), ('light', DISCOVER_LIGHTS), ('switch', DISCOVER_SWITCHES))): component = get_component(comp_name) bootstrap.setup_component(hass, component.DOMAIN, config) hass.bus.fire(EVENT_PLATFORM_DISCOVERED, {ATTR_SERVICE: discovery, ATTR_DISCOVERED: {}}) ISY.auto_update = True return True
def setup(hass, config): """Setup Insteon Hub component. This will automatically import associated lights. """ if not validate_config( config, {DOMAIN: [CONF_USERNAME, CONF_PASSWORD, CONF_API_KEY]}, _LOGGER): return False import insteon username = config[DOMAIN][CONF_USERNAME] password = config[DOMAIN][CONF_PASSWORD] api_key = config[DOMAIN][CONF_API_KEY] global INSTEON INSTEON = insteon.Insteon(username, password, api_key) if INSTEON is None: _LOGGER.error("Could not connect to Insteon service.") return comp_name = 'light' discovery = DISCOVER_LIGHTS component = get_component(comp_name) bootstrap.setup_component(hass, component.DOMAIN, config) hass.bus.fire(EVENT_PLATFORM_DISCOVERED, { ATTR_SERVICE: discovery, ATTR_DISCOVERED: {} }) return True
def request_configuration(host, hass, add_devices_callback): """Request configuration steps from the user.""" configurator = get_component('configurator') # We got an error if this method is called while we are configuring if host in _CONFIGURING: configurator.notify_errors(_CONFIGURING[host], "Failed to register, please try again.") return def plex_configuration_callback(data): """The actions to do when our configuration callback is called.""" setup_plexserver(host, data.get('token'), hass, add_devices_callback) _CONFIGURING[host] = configurator.request_config( hass, "Plex Media Server", plex_configuration_callback, description=('Enter the X-Plex-Token'), description_image="/static/images/config_plex_mediaserver.png", submit_caption="Confirm", fields=[{ 'id': 'token', 'name': 'X-Plex-Token', 'type': '' }])
def test_update_stale(self): """Test stalled update.""" scanner = get_component('device_tracker.test').SCANNER scanner.reset() scanner.come_home('DEV1') register_time = datetime(2015, 9, 15, 23, tzinfo=dt_util.UTC) scan_time = datetime(2015, 9, 15, 23, 1, tzinfo=dt_util.UTC) with patch('blumate.components.device_tracker.dt_util.utcnow', return_value=register_time): self.assertTrue(device_tracker.setup(self.hass, { 'device_tracker': { 'platform': 'test', 'consider_home': 59, }})) self.assertEqual(STATE_HOME, self.hass.states.get('device_tracker.dev1').state) scanner.leave_home('DEV1') with patch('blumate.components.device_tracker.dt_util.utcnow', return_value=scan_time): fire_time_changed(self.hass, scan_time) self.hass.pool.block_till_done() self.assertEqual(STATE_NOT_HOME, self.hass.states.get('device_tracker.dev1').state)
def setup(hass, config): """Setup the Wink component.""" logger = logging.getLogger(__name__) if not validate_config(config, {DOMAIN: [CONF_ACCESS_TOKEN]}, logger): return False import pywink pywink.set_bearer_token(config[DOMAIN][CONF_ACCESS_TOKEN]) # Load components for the devices in the Wink that we support for component_name, func_exists, discovery_type in ( ('light', pywink.get_bulbs, DISCOVER_LIGHTS), ('switch', lambda: pywink.get_switches or pywink.get_sirens or pywink. get_powerstrip_outlets, DISCOVER_SWITCHES), ('binary_sensor', pywink.get_sensors, DISCOVER_BINARY_SENSORS), ('sensor', lambda: pywink.get_sensors or pywink.get_eggtrays, DISCOVER_SENSORS), ('lock', pywink.get_locks, DISCOVER_LOCKS), ('garage_door', pywink.get_garage_doors, DISCOVER_GARAGE_DOORS)): if func_exists(): component = get_component(component_name) # Ensure component is loaded bootstrap.setup_component(hass, component.DOMAIN, config) # Fire discovery event hass.bus.fire(EVENT_PLATFORM_DISCOVERED, { ATTR_SERVICE: discovery_type, ATTR_DISCOVERED: {} }) return True
def setup(hass, config): """Setup the MQTT example component.""" mqtt = loader.get_component('mqtt') topic = config[DOMAIN].get('topic', DEFAULT_TOPIC) entity_id = 'mqtt_example.last_message' # Listen to a message on MQTT. def message_received(topic, payload, qos): """A new MQTT message has been received.""" hass.states.set(entity_id, payload) mqtt.subscribe(hass, topic, message_received) hass.states.set(entity_id, 'No messages') # Service to publish a message on MQTT. def set_state_service(call): """Service to send a message.""" mqtt.publish(hass, topic, call.data.get('new_state')) # Register our service with BluMate. hass.services.register(DOMAIN, 'set_state', set_state_service) # Return boolean to indicate that initialization was successfully. return True
def request_configuration(host, hass, add_devices_callback, filename, allow_unreachable): """Request configuration steps from the user.""" configurator = get_component('configurator') # We got an error if this method is called while we are configuring if host in _CONFIGURING: configurator.notify_errors( _CONFIGURING[host], "Failed to register, please try again.") return # pylint: disable=unused-argument def hue_configuration_callback(data): """The actions to do when our configuration callback is called.""" setup_bridge(host, hass, add_devices_callback, filename, allow_unreachable) _CONFIGURING[host] = configurator.request_config( hass, "Philips Hue", hue_configuration_callback, description=("Press the button on the bridge to register Philips Hue " "with Home Assistant."), description_image="/static/images/config_philips_hue.jpg", submit_caption="I have pressed the button" )
def setup_ecobee(hass, network, config): """Setup Ecobee thermostat.""" # If ecobee has a PIN then it needs to be configured. if network.pin is not None: request_configuration(network, hass, config) return if 'ecobee' in _CONFIGURING: configurator = get_component('configurator') configurator.request_done(_CONFIGURING.pop('ecobee')) # Ensure component is loaded bootstrap.setup_component(hass, 'thermostat', config) bootstrap.setup_component(hass, 'sensor', config) hold_temp = config[DOMAIN].get(HOLD_TEMP, False) # Fire thermostat discovery event hass.bus.fire(EVENT_PLATFORM_DISCOVERED, { ATTR_SERVICE: DISCOVER_THERMOSTAT, ATTR_DISCOVERED: {'hold_temp': hold_temp} }) # Fire sensor discovery event hass.bus.fire(EVENT_PLATFORM_DISCOVERED, { ATTR_SERVICE: DISCOVER_SENSORS, ATTR_DISCOVERED: {} })
def __init__(self, device): """Initialize the WeMo sensor.""" self.wemo = device self._state = None wemo = get_component('wemo') wemo.SUBSCRIPTION_REGISTRY.register(self.wemo) wemo.SUBSCRIPTION_REGISTRY.on(self.wemo, None, self._update_callback)
def test_config_yaml_alias_anchor(self): """Test the usage of YAML aliases and anchors. The following test scene configuration is equivalent to: scene: - name: test entities: light_1: &light_1_state state: 'on' brightness: 100 light_2: *light_1_state When encountering a YAML alias/anchor, the PyYAML parser will use a reference to the original dictionary, instead of creating a copy, so care needs to be taken to not modify the original. """ test_light = loader.get_component('light.test') test_light.init() self.assertTrue( light.setup(self.hass, {light.DOMAIN: { 'platform': 'test' }})) light_1, light_2 = test_light.DEVICES[0:2] light.turn_off(self.hass, [light_1.entity_id, light_2.entity_id]) self.hass.pool.block_till_done() entity_state = { 'state': 'on', 'brightness': 100, } self.assertTrue( scene.setup( self.hass, { 'scene': [{ 'name': 'test', 'entities': { light_1.entity_id: entity_state, light_2.entity_id: entity_state, } }] })) scene.activate(self.hass, 'scene.test') self.hass.pool.block_till_done() self.assertTrue(light_1.is_on) self.assertTrue(light_2.is_on) self.assertEqual(100, light_1.last_call('turn_on')[1].get('brightness')) self.assertEqual(100, light_2.last_call('turn_on')[1].get('brightness'))
def __init__(self, device): """Initialize the WeMo switch.""" self.wemo = device self.insight_params = None self.maker_params = None self._state = None wemo = get_component('wemo') wemo.SUBSCRIPTION_REGISTRY.register(self.wemo) wemo.SUBSCRIPTION_REGISTRY.on(self.wemo, None, self._update_callback)
def test_discovery(self): """Test discovery.""" scanner = get_component('device_tracker.test').SCANNER with patch.dict(device_tracker.DISCOVERY_PLATFORMS, {'test': 'test'}): with patch.object(scanner, 'scan_devices') as mock_scan: self.assertTrue(device_tracker.setup(self.hass, { device_tracker.DOMAIN: {CONF_PLATFORM: 'test'}})) fire_service_discovered(self.hass, 'test', {}) self.assertTrue(mock_scan.called)
def test_extract_entity_ids(self): """Test extract_entity_ids method.""" self.hass.states.set('light.Bowl', STATE_ON) self.hass.states.set('light.Ceiling', STATE_OFF) self.hass.states.set('light.Kitchen', STATE_OFF) loader.get_component('group').Group( self.hass, 'test', ['light.Ceiling', 'light.Kitchen']) call = ha.ServiceCall('light', 'turn_on', {ATTR_ENTITY_ID: 'light.Bowl'}) self.assertEqual(['light.bowl'], service.extract_entity_ids(self.hass, call)) call = ha.ServiceCall('light', 'turn_on', {ATTR_ENTITY_ID: 'group.test'}) self.assertEqual(['light.ceiling', 'light.kitchen'], service.extract_entity_ids(self.hass, call))
def setup_platform(hass, config, add_devices_callback, discovery_info=None): """Setup access to Netatmo Welcome cameras.""" netatmo = get_component('netatmo') home = config.get(CONF_HOME, None) data = WelcomeData(netatmo.NETATMO_AUTH, home) for camera_name in data.get_camera_names(): if ATTR_CAMERAS in config: if camera_name not in config[ATTR_CAMERAS]: continue add_devices_callback([WelcomeCamera(data, camera_name, home)])
def setup_platform(hass, config, add_devices_callback, discovery_info=None): """Setup access to Netatmo Welcome cameras.""" netatmo = get_component('netatmo') home = config.get(CONF_HOME, None) data = WelcomeData(netatmo.NETATMO_AUTH, home) for camera_name in data.get_camera_names(): if ATTR_CAMERAS in config: if camera_name not in config[ATTR_CAMERAS]: continue add_devices_callback([WelcomeCamera(data, camera_name, home)])
def test_extract_entity_ids(self): """Test extract_entity_ids method.""" self.hass.states.set('light.Bowl', STATE_ON) self.hass.states.set('light.Ceiling', STATE_OFF) self.hass.states.set('light.Kitchen', STATE_OFF) loader.get_component('group').Group(self.hass, 'test', ['light.Ceiling', 'light.Kitchen']) call = ha.ServiceCall('light', 'turn_on', {ATTR_ENTITY_ID: 'light.Bowl'}) self.assertEqual(['light.bowl'], service.extract_entity_ids(self.hass, call)) call = ha.ServiceCall('light', 'turn_on', {ATTR_ENTITY_ID: 'group.test'}) self.assertEqual(['light.ceiling', 'light.kitchen'], service.extract_entity_ids(self.hass, call))
def test_config_yaml_alias_anchor(self): """Test the usage of YAML aliases and anchors. The following test scene configuration is equivalent to: scene: - name: test entities: light_1: &light_1_state state: 'on' brightness: 100 light_2: *light_1_state When encountering a YAML alias/anchor, the PyYAML parser will use a reference to the original dictionary, instead of creating a copy, so care needs to be taken to not modify the original. """ test_light = loader.get_component('light.test') test_light.init() self.assertTrue(light.setup(self.hass, { light.DOMAIN: {'platform': 'test'} })) light_1, light_2 = test_light.DEVICES[0:2] light.turn_off(self.hass, [light_1.entity_id, light_2.entity_id]) self.hass.pool.block_till_done() entity_state = { 'state': 'on', 'brightness': 100, } self.assertTrue(scene.setup(self.hass, { 'scene': [{ 'name': 'test', 'entities': { light_1.entity_id: entity_state, light_2.entity_id: entity_state, } }] })) scene.activate(self.hass, 'scene.test') self.hass.pool.block_till_done() self.assertTrue(light_1.is_on) self.assertTrue(light_2.is_on) self.assertEqual(100, light_1.last_call('turn_on')[1].get('brightness')) self.assertEqual(100, light_2.last_call('turn_on')[1].get('brightness'))
def setUp(self): # pylint: disable=invalid-name """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() platform = loader.get_component('switch.test') platform.init() self.assertTrue(switch.setup( self.hass, {switch.DOMAIN: {CONF_PLATFORM: 'test'}} )) # Switch 1 is ON, switch 2 is OFF self.switch_1, self.switch_2, self.switch_3 = \ platform.DEVICES
def test_adding_unknown_device_to_config(self): """Test the adding of unknown devices to configuration file.""" scanner = get_component('device_tracker.test').SCANNER scanner.reset() scanner.come_home('DEV1') self.assertTrue(device_tracker.setup(self.hass, { device_tracker.DOMAIN: {CONF_PLATFORM: 'test'}})) config = device_tracker.load_config(self.yaml_devices, self.hass, timedelta(seconds=0), 0) assert len(config) == 1 assert config[0].dev_id == 'dev1' assert config[0].track
def setup_platform(hass, config, add_devices, discovery_info=None): """Setup the available BloomSky weather sensors.""" logger = logging.getLogger(__name__) bloomsky = get_component('bloomsky') sensors = config.get('monitored_conditions', SENSOR_TYPES) for device in bloomsky.BLOOMSKY.devices.values(): for variable in sensors: if variable in SENSOR_TYPES: add_devices( [BloomSkySensor(bloomsky.BLOOMSKY, device, variable)]) else: logger.error("Cannot find definition for device: %s", variable)
def setUp(self): # pylint: disable=invalid-name """Setup things to be run when tests are started.""" self.hass = get_test_home_assistant() event_decorators.HASS = self.hass self.scanner = loader.get_component( 'device_tracker.test').get_scanner(None, None) self.scanner.reset() self.scanner.come_home('DEV1') loader.get_component('light.test').init() self.assertTrue(device_tracker.setup(self.hass, { device_tracker.DOMAIN: {CONF_PLATFORM: 'test'} })) self.assertTrue(light.setup(self.hass, { light.DOMAIN: {CONF_PLATFORM: 'test'} })) self.assertTrue(sun.setup( self.hass, {sun.DOMAIN: {sun.CONF_ELEVATION: 0}}))
def setup_platform(hass, config, add_devices, discovery_info=None): """Setup the available BloomSky weather binary sensors.""" logger = logging.getLogger(__name__) bloomsky = get_component('bloomsky') sensors = config.get('monitored_conditions', SENSOR_TYPES) for device in bloomsky.BLOOMSKY.devices.values(): for variable in sensors: if variable in SENSOR_TYPES: add_devices([BloomSkySensor(bloomsky.BLOOMSKY, device, variable)]) else: logger.error("Cannot find definition for device: %s", variable)
def test_setup_two_platforms(self): """Test with bad configuration.""" # Test if switch component returns 0 switches test_platform = loader.get_component('switch.test') test_platform.init(True) loader.set_component('switch.test2', test_platform) test_platform.init(False) self.assertTrue(switch.setup( self.hass, { switch.DOMAIN: {CONF_PLATFORM: 'test'}, '{} 2'.format(switch.DOMAIN): {CONF_PLATFORM: 'test2'}, } ))
def test_broken_light_profiles(self): """Test light profiles.""" platform = loader.get_component('light.test') platform.init() user_light_file = self.hass.config.path(light.LIGHT_PROFILES_FILE) # Setup a wrong light file with open(user_light_file, 'w') as user_file: user_file.write('id,x,y,brightness\n') user_file.write('I,WILL,NOT,WORK\n') self.assertFalse(light.setup( self.hass, {light.DOMAIN: {CONF_PLATFORM: 'test'}} ))
def test_broken_light_profiles(self): """Test light profiles.""" platform = loader.get_component('light.test') platform.init() user_light_file = self.hass.config.path(light.LIGHT_PROFILES_FILE) # Setup a wrong light file with open(user_light_file, 'w') as user_file: user_file.write('id,x,y,brightness\n') user_file.write('I,WILL,NOT,WORK\n') self.assertFalse( light.setup(self.hass, {light.DOMAIN: { CONF_PLATFORM: 'test' }}))
def extract_entity_ids(hass, service_call): """Helper method to extract a list of entity ids from a service call. Will convert group entity ids to the entity ids it represents. """ if not (service_call.data and ATTR_ENTITY_ID in service_call.data): return [] group = get_component('group') # Entity ID attr can be a list or a string service_ent_id = service_call.data[ATTR_ENTITY_ID] if isinstance(service_ent_id, str): return group.expand_entity_ids(hass, [service_ent_id]) return [ent_id for ent_id in group.expand_entity_ids(hass, service_ent_id)]
def extract_entity_ids(hass, service_call): """Helper method to extract a list of entity ids from a service call. Will convert group entity ids to the entity ids it represents. """ if not (service_call.data and ATTR_ENTITY_ID in service_call.data): return [] group = get_component('group') # Entity ID attr can be a list or a string service_ent_id = service_call.data[ATTR_ENTITY_ID] if isinstance(service_ent_id, str): return group.expand_entity_ids(hass, [service_ent_id]) return [ent_id for ent_id in group.expand_entity_ids(hass, service_ent_id)]
def test_device_hidden(self): """Test hidden devices.""" dev_id = 'test_entity' entity_id = device_tracker.ENTITY_ID_FORMAT.format(dev_id) device = device_tracker.Device( self.hass, timedelta(seconds=180), 0, True, dev_id, None, away_hide=True) device_tracker.update_config(self.yaml_devices, dev_id, device) scanner = get_component('device_tracker.test').SCANNER scanner.reset() self.assertTrue(device_tracker.setup(self.hass, { device_tracker.DOMAIN: {CONF_PLATFORM: 'test'}})) self.assertTrue(self.hass.states.get(entity_id) .attributes.get(ATTR_HIDDEN))
def _discover(self, found_devices, component_name): """Send discovery event if component not yet discovered.""" if not len(found_devices): return _LOGGER.info("discovered %d new %s devices", len(found_devices), component_name) component = get_component(component_name) bootstrap.setup_component(self._hass, component.DOMAIN, self._config) discovery_type = DISCOVERY_TYPES[component_name] self._hass.bus.fire(EVENT_PLATFORM_DISCOVERED, {ATTR_SERVICE: discovery_type, ATTR_DISCOVERED: found_devices})
def setup_platform(hass, config, add_devices, discovery_info=None): """Setup the available OctoPrint binary sensors.""" octoprint = get_component('octoprint') name = config.get(CONF_NAME, "OctoPrint") monitored_conditions = config.get("monitored_conditions", SENSOR_TYPES.keys()) devices = [] for octo_type in monitored_conditions: if octo_type in SENSOR_TYPES: new_sensor = OctoPrintBinarySensor( octoprint.OCTOPRINT, octo_type, SENSOR_TYPES[octo_type][2], name, SENSOR_TYPES[octo_type][3], SENSOR_TYPES[octo_type][0], SENSOR_TYPES[octo_type][1], "flags") devices.append(new_sensor) else: _LOGGER.error("Unknown OctoPrint sensor type: %s", octo_type) add_devices(devices)
def test_flux_with_custom_colortemps(self): """Test the flux with custom start and stop colortemps.""" platform = loader.get_component('light.test') platform.init() self.assertTrue( light.setup(self.hass, {light.DOMAIN: {CONF_PLATFORM: 'test'}})) dev1 = platform.DEVICES[0] # Verify initial state of light state = self.hass.states.get(dev1.entity_id) self.assertEqual(STATE_ON, state.state) self.assertIsNone(state.attributes.get('xy_color')) self.assertIsNone(state.attributes.get('brightness')) test_time = dt_util.now().replace(hour=17, minute=30, second=0) sunset_time = test_time.replace(hour=17, minute=0, second=0) sunrise_time = test_time.replace(hour=5, minute=0, second=0) + timedelta(days=1) with patch('blumate.util.dt.now', return_value=test_time): with patch('blumate.components.sun.next_rising', return_value=sunrise_time): with patch('blumate.components.sun.next_setting', return_value=sunset_time): assert setup_component(self.hass, switch.DOMAIN, { switch.DOMAIN: { 'platform': 'flux', 'name': 'flux', 'lights': [dev1.entity_id], 'start_colortemp': '1000', 'stop_colortemp': '6000' } }) turn_on_calls = mock_service( self.hass, light.DOMAIN, SERVICE_TURN_ON) switch.turn_on(self.hass, 'switch.flux') self.hass.pool.block_till_done() fire_time_changed(self.hass, test_time) self.hass.pool.block_till_done() call = turn_on_calls[-1] self.assertEqual(call.data[light.ATTR_BRIGHTNESS], 167) self.assertEqual(call.data[light.ATTR_XY_COLOR], [0.461, 0.389])
def _discover(hass, config, found_devices, component_name): """Setup and send the discovery event.""" if not len(found_devices): return _LOGGER.info("discovered %d new %s devices", len(found_devices), component_name) component = get_component(component_name) bootstrap.setup_component(hass, component.DOMAIN, config) signal_repetitions = config[DOMAIN].get(ATTR_SIGNAL_REPETITIONS) hass.bus.fire(EVENT_PLATFORM_DISCOVERED, {ATTR_SERVICE: DISCOVERY_TYPES[component_name], ATTR_DISCOVERED: {ATTR_DISCOVER_DEVICES: found_devices, ATTR_DISCOVER_CONFIG: signal_repetitions}})
def test_group_all_devices(self): """Test grouping of devices.""" dev_id = 'test_entity' entity_id = device_tracker.ENTITY_ID_FORMAT.format(dev_id) device = device_tracker.Device( self.hass, timedelta(seconds=180), 0, True, dev_id, None, away_hide=True) device_tracker.update_config(self.yaml_devices, dev_id, device) scanner = get_component('device_tracker.test').SCANNER scanner.reset() self.assertTrue(device_tracker.setup(self.hass, { device_tracker.DOMAIN: {CONF_PLATFORM: 'test'}})) state = self.hass.states.get(device_tracker.ENTITY_ID_ALL_DEVICES) self.assertIsNotNone(state) self.assertEqual(STATE_NOT_HOME, state.state) self.assertSequenceEqual((entity_id,), state.attributes.get(ATTR_ENTITY_ID))
def request_configuration(host, hass, add_devices): """Request configuration steps from the user.""" configurator = get_component('configurator') # We got an error if this method is called while we are configuring if host in _CONFIGURING: configurator.notify_errors( _CONFIGURING[host], 'Failed to pair, please try again.') return # pylint: disable=unused-argument def lgtv_configuration_callback(data): """The actions to do when our configuration callback is called.""" setup_tv(host, hass, add_devices) _CONFIGURING[host] = configurator.request_config( hass, 'LG WebOS TV', lgtv_configuration_callback, description='Click start and accept the pairing request on your tv.', description_image='/static/images/config_webos.png', submit_caption='Start pairing request' )
def setup_platform(hass, config, add_devices, discovery_info=None): """Setup the available OctoPrint binary sensors.""" octoprint = get_component('octoprint') name = config.get(CONF_NAME, "OctoPrint") monitored_conditions = config.get("monitored_conditions", SENSOR_TYPES.keys()) devices = [] for octo_type in monitored_conditions: if octo_type in SENSOR_TYPES: new_sensor = OctoPrintBinarySensor(octoprint.OCTOPRINT, octo_type, SENSOR_TYPES[octo_type][2], name, SENSOR_TYPES[octo_type][3], SENSOR_TYPES[octo_type][0], SENSOR_TYPES[octo_type][1], "flags") devices.append(new_sensor) else: _LOGGER.error("Unknown OctoPrint sensor type: %s", octo_type) add_devices(devices)
def test_flux_when_switch_is_off(self): """Test the flux switch when it is off.""" platform = loader.get_component('light.test') platform.init() self.assertTrue( light.setup(self.hass, {light.DOMAIN: {CONF_PLATFORM: 'test'}})) dev1 = platform.DEVICES[0] # Verify initial state of light state = self.hass.states.get(dev1.entity_id) self.assertEqual(STATE_ON, state.state) self.assertIsNone(state.attributes.get('xy_color')) self.assertIsNone(state.attributes.get('brightness')) test_time = dt_util.now().replace(hour=10, minute=30, second=0) sunset_time = test_time.replace(hour=17, minute=0, second=0) sunrise_time = test_time.replace(hour=5, minute=0, second=0) + timedelta(days=1) with patch('blumate.util.dt.now', return_value=test_time): with patch('blumate.components.sun.next_rising', return_value=sunrise_time): with patch('blumate.components.sun.next_setting', return_value=sunset_time): assert setup_component(self.hass, switch.DOMAIN, { switch.DOMAIN: { 'platform': 'flux', 'name': 'flux', 'lights': [dev1.entity_id] } }) turn_on_calls = mock_service( self.hass, light.DOMAIN, SERVICE_TURN_ON) fire_time_changed(self.hass, test_time) self.hass.pool.block_till_done() self.assertEqual(0, len(turn_on_calls))
def test_activate_scene(self): """Test active scene.""" test_light = loader.get_component('light.test') test_light.init() self.assertTrue( light.setup(self.hass, {light.DOMAIN: { 'platform': 'test' }})) light_1, light_2 = test_light.DEVICES[0:2] light.turn_off(self.hass, [light_1.entity_id, light_2.entity_id]) self.hass.pool.block_till_done() self.assertTrue( scene.setup( self.hass, { 'scene': [{ 'name': 'test', 'entities': { light_1.entity_id: 'on', light_2.entity_id: { 'state': 'on', 'brightness': 100, } } }] })) scene.activate(self.hass, 'scene.test') self.hass.pool.block_till_done() self.assertTrue(light_1.is_on) self.assertTrue(light_2.is_on) self.assertEqual(100, light_2.last_call('turn_on')[1].get('brightness'))
def setup_platform(hass, config, add_devices, discovery_info=None): """Setup the available Netatmo weather sensors.""" netatmo = get_component('netatmo') data = NetAtmoData(netatmo.NETATMO_AUTH, config.get(CONF_STATION, None)) dev = [] try: # Iterate each module for module_name, monitored_conditions in config[ATTR_MODULE].items(): # Test if module exist """ if module_name not in data.get_module_names(): _LOGGER.error('Module name: "%s" not found', module_name) continue # Only create sensor for monitored """ for variable in monitored_conditions: if variable not in SENSOR_TYPES: _LOGGER.error('Sensor type: "%s" does not exist', variable) else: dev.append(NetAtmoSensor(data, module_name, variable)) except KeyError: pass add_devices(dev)