identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
sequence
start_point
sequence
end_point
sequence
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
test_extract_all_use_match_all
(hass, caplog)
Test extract all with None and *.
Test extract all with None and *.
async def test_extract_all_use_match_all(hass, caplog): """Test extract all with None and *.""" component = EntityComponent(_LOGGER, DOMAIN, hass) await component.async_add_entities( [MockEntity(name="test_1"), MockEntity(name="test_2")] ) call = ha.ServiceCall("test", "service", {"entity_id": "all"}) assert ["test_domain.test_1", "test_domain.test_2"] == sorted( ent.entity_id for ent in await component.async_extract_from_service(call) ) assert ( "Not passing an entity ID to a service to target all entities is deprecated" ) not in caplog.text
[ "async", "def", "test_extract_all_use_match_all", "(", "hass", ",", "caplog", ")", ":", "component", "=", "EntityComponent", "(", "_LOGGER", ",", "DOMAIN", ",", "hass", ")", "await", "component", ".", "async_add_entities", "(", "[", "MockEntity", "(", "name", "=", "\"test_1\"", ")", ",", "MockEntity", "(", "name", "=", "\"test_2\"", ")", "]", ")", "call", "=", "ha", ".", "ServiceCall", "(", "\"test\"", ",", "\"service\"", ",", "{", "\"entity_id\"", ":", "\"all\"", "}", ")", "assert", "[", "\"test_domain.test_1\"", ",", "\"test_domain.test_2\"", "]", "==", "sorted", "(", "ent", ".", "entity_id", "for", "ent", "in", "await", "component", ".", "async_extract_from_service", "(", "call", ")", ")", "assert", "(", "\"Not passing an entity ID to a service to target all entities is deprecated\"", ")", "not", "in", "caplog", ".", "text" ]
[ 424, 0 ]
[ 438, 24 ]
python
en
['en', 'en', 'en']
True
test_register_entity_service
(hass)
Test not expanding a group.
Test not expanding a group.
async def test_register_entity_service(hass): """Test not expanding a group.""" entity = MockEntity(entity_id=f"{DOMAIN}.entity") calls = [] @ha.callback def appender(**kwargs): calls.append(kwargs) entity.async_called_by_service = appender component = EntityComponent(_LOGGER, DOMAIN, hass) await component.async_add_entities([entity]) component.async_register_entity_service( "hello", {"some": str}, "async_called_by_service" ) with pytest.raises(vol.Invalid): await hass.services.async_call( DOMAIN, "hello", {"entity_id": entity.entity_id, "invalid": "data"}, blocking=True, ) assert len(calls) == 0 await hass.services.async_call( DOMAIN, "hello", {"entity_id": entity.entity_id, "some": "data"}, blocking=True ) assert len(calls) == 1 assert calls[0] == {"some": "data"} await hass.services.async_call( DOMAIN, "hello", {"entity_id": ENTITY_MATCH_ALL, "some": "data"}, blocking=True ) assert len(calls) == 2 assert calls[1] == {"some": "data"} await hass.services.async_call( DOMAIN, "hello", {"entity_id": ENTITY_MATCH_NONE, "some": "data"}, blocking=True ) assert len(calls) == 2 await hass.services.async_call( DOMAIN, "hello", {"area_id": ENTITY_MATCH_NONE, "some": "data"}, blocking=True ) assert len(calls) == 2
[ "async", "def", "test_register_entity_service", "(", "hass", ")", ":", "entity", "=", "MockEntity", "(", "entity_id", "=", "f\"{DOMAIN}.entity\"", ")", "calls", "=", "[", "]", "@", "ha", ".", "callback", "def", "appender", "(", "*", "*", "kwargs", ")", ":", "calls", ".", "append", "(", "kwargs", ")", "entity", ".", "async_called_by_service", "=", "appender", "component", "=", "EntityComponent", "(", "_LOGGER", ",", "DOMAIN", ",", "hass", ")", "await", "component", ".", "async_add_entities", "(", "[", "entity", "]", ")", "component", ".", "async_register_entity_service", "(", "\"hello\"", ",", "{", "\"some\"", ":", "str", "}", ",", "\"async_called_by_service\"", ")", "with", "pytest", ".", "raises", "(", "vol", ".", "Invalid", ")", ":", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "\"hello\"", ",", "{", "\"entity_id\"", ":", "entity", ".", "entity_id", ",", "\"invalid\"", ":", "\"data\"", "}", ",", "blocking", "=", "True", ",", ")", "assert", "len", "(", "calls", ")", "==", "0", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "\"hello\"", ",", "{", "\"entity_id\"", ":", "entity", ".", "entity_id", ",", "\"some\"", ":", "\"data\"", "}", ",", "blocking", "=", "True", ")", "assert", "len", "(", "calls", ")", "==", "1", "assert", "calls", "[", "0", "]", "==", "{", "\"some\"", ":", "\"data\"", "}", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "\"hello\"", ",", "{", "\"entity_id\"", ":", "ENTITY_MATCH_ALL", ",", "\"some\"", ":", "\"data\"", "}", ",", "blocking", "=", "True", ")", "assert", "len", "(", "calls", ")", "==", "2", "assert", "calls", "[", "1", "]", "==", "{", "\"some\"", ":", "\"data\"", "}", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "\"hello\"", ",", "{", "\"entity_id\"", ":", "ENTITY_MATCH_NONE", ",", "\"some\"", ":", "\"data\"", "}", ",", "blocking", "=", "True", ")", "assert", "len", "(", "calls", ")", "==", "2", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "\"hello\"", ",", "{", "\"area_id\"", ":", "ENTITY_MATCH_NONE", ",", "\"some\"", ":", "\"data\"", "}", ",", "blocking", "=", "True", ")", "assert", "len", "(", "calls", ")", "==", "2" ]
[ 441, 0 ]
[ 488, 26 ]
python
en
['en', 'en', 'en']
True
test_valid_config
(hass)
Test configuration.
Test configuration.
async def test_valid_config(hass): """Test configuration.""" assert await async_setup_component( hass, "rfxtrx", { "rfxtrx": { "device": "/dev/serial/by-id/usb" + "-RFXCOM_RFXtrx433_A1Y0NJGR-if00-port0", } }, )
[ "async", "def", "test_valid_config", "(", "hass", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "\"rfxtrx\"", ",", "{", "\"rfxtrx\"", ":", "{", "\"device\"", ":", "\"/dev/serial/by-id/usb\"", "+", "\"-RFXCOM_RFXtrx433_A1Y0NJGR-if00-port0\"", ",", "}", "}", ",", ")" ]
[ 12, 0 ]
[ 23, 5 ]
python
en
['en', 'fr', 'en']
False
test_valid_config2
(hass)
Test configuration.
Test configuration.
async def test_valid_config2(hass): """Test configuration.""" assert await async_setup_component( hass, "rfxtrx", { "rfxtrx": { "device": "/dev/serial/by-id/usb" + "-RFXCOM_RFXtrx433_A1Y0NJGR-if00-port0", "debug": True, } }, )
[ "async", "def", "test_valid_config2", "(", "hass", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "\"rfxtrx\"", ",", "{", "\"rfxtrx\"", ":", "{", "\"device\"", ":", "\"/dev/serial/by-id/usb\"", "+", "\"-RFXCOM_RFXtrx433_A1Y0NJGR-if00-port0\"", ",", "\"debug\"", ":", "True", ",", "}", "}", ",", ")" ]
[ 26, 0 ]
[ 38, 5 ]
python
en
['en', 'fr', 'en']
False
test_invalid_config
(hass)
Test configuration.
Test configuration.
async def test_invalid_config(hass): """Test configuration.""" assert not await async_setup_component(hass, "rfxtrx", {"rfxtrx": {}}) assert not await async_setup_component( hass, "rfxtrx", { "rfxtrx": { "device": "/dev/serial/by-id/usb" + "-RFXCOM_RFXtrx433_A1Y0NJGR-if00-port0", "invalid_key": True, } }, )
[ "async", "def", "test_invalid_config", "(", "hass", ")", ":", "assert", "not", "await", "async_setup_component", "(", "hass", ",", "\"rfxtrx\"", ",", "{", "\"rfxtrx\"", ":", "{", "}", "}", ")", "assert", "not", "await", "async_setup_component", "(", "hass", ",", "\"rfxtrx\"", ",", "{", "\"rfxtrx\"", ":", "{", "\"device\"", ":", "\"/dev/serial/by-id/usb\"", "+", "\"-RFXCOM_RFXtrx433_A1Y0NJGR-if00-port0\"", ",", "\"invalid_key\"", ":", "True", ",", "}", "}", ",", ")" ]
[ 41, 0 ]
[ 55, 5 ]
python
en
['en', 'fr', 'en']
False
test_fire_event
(hass, rfxtrx)
Test fire event.
Test fire event.
async def test_fire_event(hass, rfxtrx): """Test fire event.""" entry_data = create_rfx_test_cfg( device="/dev/serial/by-id/usb-RFXCOM_RFXtrx433_A1Y0NJGR-if00-port0", automatic_add=True, devices={ "0b1100cd0213c7f210010f51": {"fire_event": True}, "0716000100900970": {"fire_event": True}, }, ) mock_entry = MockConfigEntry(domain="rfxtrx", unique_id=DOMAIN, data=entry_data) mock_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_entry.entry_id) await hass.async_block_till_done() await hass.async_start() calls = [] @callback def record_event(event): """Add recorded event to set.""" assert event.event_type == "rfxtrx_event" calls.append(event.data) hass.bus.async_listen(EVENT_RFXTRX_EVENT, record_event) await rfxtrx.signal("0b1100cd0213c7f210010f51") await rfxtrx.signal("0716000100900970") assert calls == [ { "packet_type": 17, "sub_type": 0, "type_string": "AC", "id_string": "213c7f2:16", "data": "0b1100cd0213c7f210010f51", "values": {"Command": "On", "Rssi numeric": 5}, }, { "packet_type": 22, "sub_type": 0, "type_string": "Byron SX", "id_string": "00:90", "data": "0716000100900970", "values": {"Command": "Chime", "Rssi numeric": 7, "Sound": 9}, }, ]
[ "async", "def", "test_fire_event", "(", "hass", ",", "rfxtrx", ")", ":", "entry_data", "=", "create_rfx_test_cfg", "(", "device", "=", "\"/dev/serial/by-id/usb-RFXCOM_RFXtrx433_A1Y0NJGR-if00-port0\"", ",", "automatic_add", "=", "True", ",", "devices", "=", "{", "\"0b1100cd0213c7f210010f51\"", ":", "{", "\"fire_event\"", ":", "True", "}", ",", "\"0716000100900970\"", ":", "{", "\"fire_event\"", ":", "True", "}", ",", "}", ",", ")", "mock_entry", "=", "MockConfigEntry", "(", "domain", "=", "\"rfxtrx\"", ",", "unique_id", "=", "DOMAIN", ",", "data", "=", "entry_data", ")", "mock_entry", ".", "add_to_hass", "(", "hass", ")", "await", "hass", ".", "config_entries", ".", "async_setup", "(", "mock_entry", ".", "entry_id", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "await", "hass", ".", "async_start", "(", ")", "calls", "=", "[", "]", "@", "callback", "def", "record_event", "(", "event", ")", ":", "\"\"\"Add recorded event to set.\"\"\"", "assert", "event", ".", "event_type", "==", "\"rfxtrx_event\"", "calls", ".", "append", "(", "event", ".", "data", ")", "hass", ".", "bus", ".", "async_listen", "(", "EVENT_RFXTRX_EVENT", ",", "record_event", ")", "await", "rfxtrx", ".", "signal", "(", "\"0b1100cd0213c7f210010f51\"", ")", "await", "rfxtrx", ".", "signal", "(", "\"0716000100900970\"", ")", "assert", "calls", "==", "[", "{", "\"packet_type\"", ":", "17", ",", "\"sub_type\"", ":", "0", ",", "\"type_string\"", ":", "\"AC\"", ",", "\"id_string\"", ":", "\"213c7f2:16\"", ",", "\"data\"", ":", "\"0b1100cd0213c7f210010f51\"", ",", "\"values\"", ":", "{", "\"Command\"", ":", "\"On\"", ",", "\"Rssi numeric\"", ":", "5", "}", ",", "}", ",", "{", "\"packet_type\"", ":", "22", ",", "\"sub_type\"", ":", "0", ",", "\"type_string\"", ":", "\"Byron SX\"", ",", "\"id_string\"", ":", "\"00:90\"", ",", "\"data\"", ":", "\"0716000100900970\"", ",", "\"values\"", ":", "{", "\"Command\"", ":", "\"Chime\"", ",", "\"Rssi numeric\"", ":", "7", ",", "\"Sound\"", ":", "9", "}", ",", "}", ",", "]" ]
[ 58, 0 ]
[ 106, 5 ]
python
en
['fr', 'lb', 'en']
False
test_send
(hass, rfxtrx)
Test configuration.
Test configuration.
async def test_send(hass, rfxtrx): """Test configuration.""" entry_data = create_rfx_test_cfg(device="/dev/null", devices={}) mock_entry = MockConfigEntry(domain="rfxtrx", unique_id=DOMAIN, data=entry_data) mock_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_entry.entry_id) await hass.async_block_till_done() await hass.services.async_call( "rfxtrx", "send", {"event": "0a520802060101ff0f0269"}, blocking=True ) assert rfxtrx.transport.send.mock_calls == [ call(bytearray(b"\x0a\x52\x08\x02\x06\x01\x01\xff\x0f\x02\x69")) ]
[ "async", "def", "test_send", "(", "hass", ",", "rfxtrx", ")", ":", "entry_data", "=", "create_rfx_test_cfg", "(", "device", "=", "\"/dev/null\"", ",", "devices", "=", "{", "}", ")", "mock_entry", "=", "MockConfigEntry", "(", "domain", "=", "\"rfxtrx\"", ",", "unique_id", "=", "DOMAIN", ",", "data", "=", "entry_data", ")", "mock_entry", ".", "add_to_hass", "(", "hass", ")", "await", "hass", ".", "config_entries", ".", "async_setup", "(", "mock_entry", ".", "entry_id", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "await", "hass", ".", "services", ".", "async_call", "(", "\"rfxtrx\"", ",", "\"send\"", ",", "{", "\"event\"", ":", "\"0a520802060101ff0f0269\"", "}", ",", "blocking", "=", "True", ")", "assert", "rfxtrx", ".", "transport", ".", "send", ".", "mock_calls", "==", "[", "call", "(", "bytearray", "(", "b\"\\x0a\\x52\\x08\\x02\\x06\\x01\\x01\\xff\\x0f\\x02\\x69\"", ")", ")", "]" ]
[ 109, 0 ]
[ 125, 5 ]
python
en
['en', 'fr', 'en']
False
get_tracker
(hass, config)
Create a tracker.
Create a tracker.
async def get_tracker(hass, config): """Create a tracker.""" yaml_path = hass.config.path(YAML_DEVICES) conf = config.get(DOMAIN, []) conf = conf[0] if conf else {} consider_home = conf.get(CONF_CONSIDER_HOME, DEFAULT_CONSIDER_HOME) defaults = conf.get(CONF_NEW_DEVICE_DEFAULTS, {}) track_new = conf.get(CONF_TRACK_NEW) if track_new is None: track_new = defaults.get(CONF_TRACK_NEW, DEFAULT_TRACK_NEW) devices = await async_load_config(yaml_path, hass, consider_home) tracker = DeviceTracker(hass, consider_home, track_new, defaults, devices) return tracker
[ "async", "def", "get_tracker", "(", "hass", ",", "config", ")", ":", "yaml_path", "=", "hass", ".", "config", ".", "path", "(", "YAML_DEVICES", ")", "conf", "=", "config", ".", "get", "(", "DOMAIN", ",", "[", "]", ")", "conf", "=", "conf", "[", "0", "]", "if", "conf", "else", "{", "}", "consider_home", "=", "conf", ".", "get", "(", "CONF_CONSIDER_HOME", ",", "DEFAULT_CONSIDER_HOME", ")", "defaults", "=", "conf", ".", "get", "(", "CONF_NEW_DEVICE_DEFAULTS", ",", "{", "}", ")", "track_new", "=", "conf", ".", "get", "(", "CONF_TRACK_NEW", ")", "if", "track_new", "is", "None", ":", "track_new", "=", "defaults", ".", "get", "(", "CONF_TRACK_NEW", ",", "DEFAULT_TRACK_NEW", ")", "devices", "=", "await", "async_load_config", "(", "yaml_path", ",", "hass", ",", "consider_home", ")", "tracker", "=", "DeviceTracker", "(", "hass", ",", "consider_home", ",", "track_new", ",", "defaults", ",", "devices", ")", "return", "tracker" ]
[ 53, 0 ]
[ 68, 18 ]
python
en
['en', 'gd', 'en']
True
async_load_config
( path: str, hass: HomeAssistantType, consider_home: timedelta )
Load devices from YAML configuration file. This method is a coroutine.
Load devices from YAML configuration file.
async def async_load_config( path: str, hass: HomeAssistantType, consider_home: timedelta ): """Load devices from YAML configuration file. This method is a coroutine. """ dev_schema = vol.Schema( { vol.Required(CONF_NAME): cv.string, vol.Optional(CONF_ICON, default=None): vol.Any(None, cv.icon), vol.Optional("track", default=False): cv.boolean, vol.Optional(CONF_MAC, default=None): vol.Any( None, vol.All(cv.string, vol.Upper) ), vol.Optional("gravatar", default=None): vol.Any(None, cv.string), vol.Optional("picture", default=None): vol.Any(None, cv.string), vol.Optional(CONF_CONSIDER_HOME, default=consider_home): vol.All( cv.time_period, cv.positive_timedelta ), } ) result = [] try: devices = await hass.async_add_executor_job(load_yaml_config_file, path) except HomeAssistantError as err: LOGGER.error("Unable to load %s: %s", path, str(err)) return [] except FileNotFoundError: return [] for dev_id, device in devices.items(): # Deprecated option. We just ignore it to avoid breaking change device.pop("vendor", None) device.pop("hide_if_away", None) try: device = dev_schema(device) device["dev_id"] = cv.slugify(dev_id) except vol.Invalid as exp: async_log_exception(exp, dev_id, devices, hass) else: result.append(Device(hass, **device)) return result
[ "async", "def", "async_load_config", "(", "path", ":", "str", ",", "hass", ":", "HomeAssistantType", ",", "consider_home", ":", "timedelta", ")", ":", "dev_schema", "=", "vol", ".", "Schema", "(", "{", "vol", ".", "Required", "(", "CONF_NAME", ")", ":", "cv", ".", "string", ",", "vol", ".", "Optional", "(", "CONF_ICON", ",", "default", "=", "None", ")", ":", "vol", ".", "Any", "(", "None", ",", "cv", ".", "icon", ")", ",", "vol", ".", "Optional", "(", "\"track\"", ",", "default", "=", "False", ")", ":", "cv", ".", "boolean", ",", "vol", ".", "Optional", "(", "CONF_MAC", ",", "default", "=", "None", ")", ":", "vol", ".", "Any", "(", "None", ",", "vol", ".", "All", "(", "cv", ".", "string", ",", "vol", ".", "Upper", ")", ")", ",", "vol", ".", "Optional", "(", "\"gravatar\"", ",", "default", "=", "None", ")", ":", "vol", ".", "Any", "(", "None", ",", "cv", ".", "string", ")", ",", "vol", ".", "Optional", "(", "\"picture\"", ",", "default", "=", "None", ")", ":", "vol", ".", "Any", "(", "None", ",", "cv", ".", "string", ")", ",", "vol", ".", "Optional", "(", "CONF_CONSIDER_HOME", ",", "default", "=", "consider_home", ")", ":", "vol", ".", "All", "(", "cv", ".", "time_period", ",", "cv", ".", "positive_timedelta", ")", ",", "}", ")", "result", "=", "[", "]", "try", ":", "devices", "=", "await", "hass", ".", "async_add_executor_job", "(", "load_yaml_config_file", ",", "path", ")", "except", "HomeAssistantError", "as", "err", ":", "LOGGER", ".", "error", "(", "\"Unable to load %s: %s\"", ",", "path", ",", "str", "(", "err", ")", ")", "return", "[", "]", "except", "FileNotFoundError", ":", "return", "[", "]", "for", "dev_id", ",", "device", "in", "devices", ".", "items", "(", ")", ":", "# Deprecated option. We just ignore it to avoid breaking change", "device", ".", "pop", "(", "\"vendor\"", ",", "None", ")", "device", ".", "pop", "(", "\"hide_if_away\"", ",", "None", ")", "try", ":", "device", "=", "dev_schema", "(", "device", ")", "device", "[", "\"dev_id\"", "]", "=", "cv", ".", "slugify", "(", "dev_id", ")", "except", "vol", ".", "Invalid", "as", "exp", ":", "async_log_exception", "(", "exp", ",", "dev_id", ",", "devices", ",", "hass", ")", "else", ":", "result", ".", "append", "(", "Device", "(", "hass", ",", "*", "*", "device", ")", ")", "return", "result" ]
[ 500, 0 ]
[ 542, 17 ]
python
en
['en', 'en', 'en']
True
update_config
(path: str, dev_id: str, device: Device)
Add device to YAML configuration file.
Add device to YAML configuration file.
def update_config(path: str, dev_id: str, device: Device): """Add device to YAML configuration file.""" with open(path, "a") as out: device = { device.dev_id: { ATTR_NAME: device.name, ATTR_MAC: device.mac, ATTR_ICON: device.icon, "picture": device.config_picture, "track": device.track, } } out.write("\n") out.write(dump(device))
[ "def", "update_config", "(", "path", ":", "str", ",", "dev_id", ":", "str", ",", "device", ":", "Device", ")", ":", "with", "open", "(", "path", ",", "\"a\"", ")", "as", "out", ":", "device", "=", "{", "device", ".", "dev_id", ":", "{", "ATTR_NAME", ":", "device", ".", "name", ",", "ATTR_MAC", ":", "device", ".", "mac", ",", "ATTR_ICON", ":", "device", ".", "icon", ",", "\"picture\"", ":", "device", ".", "config_picture", ",", "\"track\"", ":", "device", ".", "track", ",", "}", "}", "out", ".", "write", "(", "\"\\n\"", ")", "out", ".", "write", "(", "dump", "(", "device", ")", ")" ]
[ 545, 0 ]
[ 558, 31 ]
python
en
['en', 'en', 'en']
True
get_gravatar_for_email
(email: str)
Return an 80px Gravatar for the given email address. Async friendly.
Return an 80px Gravatar for the given email address.
def get_gravatar_for_email(email: str): """Return an 80px Gravatar for the given email address. Async friendly. """ return ( f"https://www.gravatar.com/avatar/" f"{hashlib.md5(email.encode('utf-8').lower()).hexdigest()}.jpg?s=80&d=wavatar" )
[ "def", "get_gravatar_for_email", "(", "email", ":", "str", ")", ":", "return", "(", "f\"https://www.gravatar.com/avatar/\"", "f\"{hashlib.md5(email.encode('utf-8').lower()).hexdigest()}.jpg?s=80&d=wavatar\"", ")" ]
[ 561, 0 ]
[ 570, 5 ]
python
en
['en', 'en', 'en']
True
DeviceTracker.__init__
( self, hass: HomeAssistantType, consider_home: timedelta, track_new: bool, defaults: dict, devices: Sequence, )
Initialize a device tracker.
Initialize a device tracker.
def __init__( self, hass: HomeAssistantType, consider_home: timedelta, track_new: bool, defaults: dict, devices: Sequence, ) -> None: """Initialize a device tracker.""" self.hass = hass self.devices = {dev.dev_id: dev for dev in devices} self.mac_to_dev = {dev.mac: dev for dev in devices if dev.mac} self.consider_home = consider_home self.track_new = ( track_new if track_new is not None else defaults.get(CONF_TRACK_NEW, DEFAULT_TRACK_NEW) ) self.defaults = defaults self._is_updating = asyncio.Lock() for dev in devices: if self.devices[dev.dev_id] is not dev: LOGGER.warning("Duplicate device IDs detected %s", dev.dev_id) if dev.mac and self.mac_to_dev[dev.mac] is not dev: LOGGER.warning("Duplicate device MAC addresses detected %s", dev.mac)
[ "def", "__init__", "(", "self", ",", "hass", ":", "HomeAssistantType", ",", "consider_home", ":", "timedelta", ",", "track_new", ":", "bool", ",", "defaults", ":", "dict", ",", "devices", ":", "Sequence", ",", ")", "->", "None", ":", "self", ".", "hass", "=", "hass", "self", ".", "devices", "=", "{", "dev", ".", "dev_id", ":", "dev", "for", "dev", "in", "devices", "}", "self", ".", "mac_to_dev", "=", "{", "dev", ".", "mac", ":", "dev", "for", "dev", "in", "devices", "if", "dev", ".", "mac", "}", "self", ".", "consider_home", "=", "consider_home", "self", ".", "track_new", "=", "(", "track_new", "if", "track_new", "is", "not", "None", "else", "defaults", ".", "get", "(", "CONF_TRACK_NEW", ",", "DEFAULT_TRACK_NEW", ")", ")", "self", ".", "defaults", "=", "defaults", "self", ".", "_is_updating", "=", "asyncio", ".", "Lock", "(", ")", "for", "dev", "in", "devices", ":", "if", "self", ".", "devices", "[", "dev", ".", "dev_id", "]", "is", "not", "dev", ":", "LOGGER", ".", "warning", "(", "\"Duplicate device IDs detected %s\"", ",", "dev", ".", "dev_id", ")", "if", "dev", ".", "mac", "and", "self", ".", "mac_to_dev", "[", "dev", ".", "mac", "]", "is", "not", "dev", ":", "LOGGER", ".", "warning", "(", "\"Duplicate device MAC addresses detected %s\"", ",", "dev", ".", "mac", ")" ]
[ 74, 4 ]
[ 99, 85 ]
python
en
['es', 'en', 'en']
True
DeviceTracker.see
( self, mac: str = None, dev_id: str = None, host_name: str = None, location_name: str = None, gps: GPSType = None, gps_accuracy: int = None, battery: int = None, attributes: dict = None, source_type: str = SOURCE_TYPE_GPS, picture: str = None, icon: str = None, consider_home: timedelta = None, )
Notify the device tracker that you see a device.
Notify the device tracker that you see a device.
def see( self, mac: str = None, dev_id: str = None, host_name: str = None, location_name: str = None, gps: GPSType = None, gps_accuracy: int = None, battery: int = None, attributes: dict = None, source_type: str = SOURCE_TYPE_GPS, picture: str = None, icon: str = None, consider_home: timedelta = None, ): """Notify the device tracker that you see a device.""" self.hass.add_job( self.async_see( mac, dev_id, host_name, location_name, gps, gps_accuracy, battery, attributes, source_type, picture, icon, consider_home, ) )
[ "def", "see", "(", "self", ",", "mac", ":", "str", "=", "None", ",", "dev_id", ":", "str", "=", "None", ",", "host_name", ":", "str", "=", "None", ",", "location_name", ":", "str", "=", "None", ",", "gps", ":", "GPSType", "=", "None", ",", "gps_accuracy", ":", "int", "=", "None", ",", "battery", ":", "int", "=", "None", ",", "attributes", ":", "dict", "=", "None", ",", "source_type", ":", "str", "=", "SOURCE_TYPE_GPS", ",", "picture", ":", "str", "=", "None", ",", "icon", ":", "str", "=", "None", ",", "consider_home", ":", "timedelta", "=", "None", ",", ")", ":", "self", ".", "hass", ".", "add_job", "(", "self", ".", "async_see", "(", "mac", ",", "dev_id", ",", "host_name", ",", "location_name", ",", "gps", ",", "gps_accuracy", ",", "battery", ",", "attributes", ",", "source_type", ",", "picture", ",", "icon", ",", "consider_home", ",", ")", ")" ]
[ 101, 4 ]
[ 132, 9 ]
python
en
['en', 'en', 'en']
True
DeviceTracker.async_see
( self, mac: str = None, dev_id: str = None, host_name: str = None, location_name: str = None, gps: GPSType = None, gps_accuracy: int = None, battery: int = None, attributes: dict = None, source_type: str = SOURCE_TYPE_GPS, picture: str = None, icon: str = None, consider_home: timedelta = None, )
Notify the device tracker that you see a device. This method is a coroutine.
Notify the device tracker that you see a device.
async def async_see( self, mac: str = None, dev_id: str = None, host_name: str = None, location_name: str = None, gps: GPSType = None, gps_accuracy: int = None, battery: int = None, attributes: dict = None, source_type: str = SOURCE_TYPE_GPS, picture: str = None, icon: str = None, consider_home: timedelta = None, ): """Notify the device tracker that you see a device. This method is a coroutine. """ registry = await async_get_registry(self.hass) if mac is None and dev_id is None: raise HomeAssistantError("Neither mac or device id passed in") if mac is not None: mac = str(mac).upper() device = self.mac_to_dev.get(mac) if not device: dev_id = util.slugify(host_name or "") or util.slugify(mac) else: dev_id = cv.slug(str(dev_id).lower()) device = self.devices.get(dev_id) if device: await device.async_seen( host_name, location_name, gps, gps_accuracy, battery, attributes, source_type, consider_home, ) if device.track: device.async_write_ha_state() return # Guard from calling see on entity registry entities. entity_id = f"{DOMAIN}.{dev_id}" if registry.async_is_registered(entity_id): LOGGER.error( "The see service is not supported for this entity %s", entity_id ) return # If no device can be found, create it dev_id = util.ensure_unique_string(dev_id, self.devices.keys()) device = Device( self.hass, consider_home or self.consider_home, self.track_new, dev_id, mac, picture=picture, icon=icon, ) self.devices[dev_id] = device if mac is not None: self.mac_to_dev[mac] = device await device.async_seen( host_name, location_name, gps, gps_accuracy, battery, attributes, source_type, ) if device.track: device.async_write_ha_state() self.hass.bus.async_fire( EVENT_NEW_DEVICE, { ATTR_ENTITY_ID: device.entity_id, ATTR_HOST_NAME: device.host_name, ATTR_MAC: device.mac, }, ) # update known_devices.yaml self.hass.async_create_task( self.async_update_config( self.hass.config.path(YAML_DEVICES), dev_id, device ) )
[ "async", "def", "async_see", "(", "self", ",", "mac", ":", "str", "=", "None", ",", "dev_id", ":", "str", "=", "None", ",", "host_name", ":", "str", "=", "None", ",", "location_name", ":", "str", "=", "None", ",", "gps", ":", "GPSType", "=", "None", ",", "gps_accuracy", ":", "int", "=", "None", ",", "battery", ":", "int", "=", "None", ",", "attributes", ":", "dict", "=", "None", ",", "source_type", ":", "str", "=", "SOURCE_TYPE_GPS", ",", "picture", ":", "str", "=", "None", ",", "icon", ":", "str", "=", "None", ",", "consider_home", ":", "timedelta", "=", "None", ",", ")", ":", "registry", "=", "await", "async_get_registry", "(", "self", ".", "hass", ")", "if", "mac", "is", "None", "and", "dev_id", "is", "None", ":", "raise", "HomeAssistantError", "(", "\"Neither mac or device id passed in\"", ")", "if", "mac", "is", "not", "None", ":", "mac", "=", "str", "(", "mac", ")", ".", "upper", "(", ")", "device", "=", "self", ".", "mac_to_dev", ".", "get", "(", "mac", ")", "if", "not", "device", ":", "dev_id", "=", "util", ".", "slugify", "(", "host_name", "or", "\"\"", ")", "or", "util", ".", "slugify", "(", "mac", ")", "else", ":", "dev_id", "=", "cv", ".", "slug", "(", "str", "(", "dev_id", ")", ".", "lower", "(", ")", ")", "device", "=", "self", ".", "devices", ".", "get", "(", "dev_id", ")", "if", "device", ":", "await", "device", ".", "async_seen", "(", "host_name", ",", "location_name", ",", "gps", ",", "gps_accuracy", ",", "battery", ",", "attributes", ",", "source_type", ",", "consider_home", ",", ")", "if", "device", ".", "track", ":", "device", ".", "async_write_ha_state", "(", ")", "return", "# Guard from calling see on entity registry entities.", "entity_id", "=", "f\"{DOMAIN}.{dev_id}\"", "if", "registry", ".", "async_is_registered", "(", "entity_id", ")", ":", "LOGGER", ".", "error", "(", "\"The see service is not supported for this entity %s\"", ",", "entity_id", ")", "return", "# If no device can be found, create it", "dev_id", "=", "util", ".", "ensure_unique_string", "(", "dev_id", ",", "self", ".", "devices", ".", "keys", "(", ")", ")", "device", "=", "Device", "(", "self", ".", "hass", ",", "consider_home", "or", "self", ".", "consider_home", ",", "self", ".", "track_new", ",", "dev_id", ",", "mac", ",", "picture", "=", "picture", ",", "icon", "=", "icon", ",", ")", "self", ".", "devices", "[", "dev_id", "]", "=", "device", "if", "mac", "is", "not", "None", ":", "self", ".", "mac_to_dev", "[", "mac", "]", "=", "device", "await", "device", ".", "async_seen", "(", "host_name", ",", "location_name", ",", "gps", ",", "gps_accuracy", ",", "battery", ",", "attributes", ",", "source_type", ",", ")", "if", "device", ".", "track", ":", "device", ".", "async_write_ha_state", "(", ")", "self", ".", "hass", ".", "bus", ".", "async_fire", "(", "EVENT_NEW_DEVICE", ",", "{", "ATTR_ENTITY_ID", ":", "device", ".", "entity_id", ",", "ATTR_HOST_NAME", ":", "device", ".", "host_name", ",", "ATTR_MAC", ":", "device", ".", "mac", ",", "}", ",", ")", "# update known_devices.yaml", "self", ".", "hass", ".", "async_create_task", "(", "self", ".", "async_update_config", "(", "self", ".", "hass", ".", "config", ".", "path", "(", "YAML_DEVICES", ")", ",", "dev_id", ",", "device", ")", ")" ]
[ 134, 4 ]
[ 230, 9 ]
python
en
['en', 'en', 'en']
True
DeviceTracker.async_update_config
(self, path, dev_id, device)
Add device to YAML configuration file. This method is a coroutine.
Add device to YAML configuration file.
async def async_update_config(self, path, dev_id, device): """Add device to YAML configuration file. This method is a coroutine. """ async with self._is_updating: await self.hass.async_add_executor_job( update_config, self.hass.config.path(YAML_DEVICES), dev_id, device )
[ "async", "def", "async_update_config", "(", "self", ",", "path", ",", "dev_id", ",", "device", ")", ":", "async", "with", "self", ".", "_is_updating", ":", "await", "self", ".", "hass", ".", "async_add_executor_job", "(", "update_config", ",", "self", ".", "hass", ".", "config", ".", "path", "(", "YAML_DEVICES", ")", ",", "dev_id", ",", "device", ")" ]
[ 232, 4 ]
[ 240, 13 ]
python
en
['en', 'en', 'en']
True
DeviceTracker.async_update_stale
(self, now: dt_util.dt.datetime)
Update stale devices. This method must be run in the event loop.
Update stale devices.
def async_update_stale(self, now: dt_util.dt.datetime): """Update stale devices. This method must be run in the event loop. """ for device in self.devices.values(): if (device.track and device.last_update_home) and device.stale(now): self.hass.async_create_task(device.async_update_ha_state(True))
[ "def", "async_update_stale", "(", "self", ",", "now", ":", "dt_util", ".", "dt", ".", "datetime", ")", ":", "for", "device", "in", "self", ".", "devices", ".", "values", "(", ")", ":", "if", "(", "device", ".", "track", "and", "device", ".", "last_update_home", ")", "and", "device", ".", "stale", "(", "now", ")", ":", "self", ".", "hass", ".", "async_create_task", "(", "device", ".", "async_update_ha_state", "(", "True", ")", ")" ]
[ 243, 4 ]
[ 250, 79 ]
python
en
['ro', 'en', 'en']
True
DeviceTracker.async_setup_tracked_device
(self)
Set up all not exists tracked devices. This method is a coroutine.
Set up all not exists tracked devices.
async def async_setup_tracked_device(self): """Set up all not exists tracked devices. This method is a coroutine. """ async def async_init_single_device(dev): """Init a single device_tracker entity.""" await dev.async_added_to_hass() dev.async_write_ha_state() tasks = [] for device in self.devices.values(): if device.track and not device.last_seen: tasks.append( self.hass.async_create_task(async_init_single_device(device)) ) if tasks: await asyncio.wait(tasks)
[ "async", "def", "async_setup_tracked_device", "(", "self", ")", ":", "async", "def", "async_init_single_device", "(", "dev", ")", ":", "\"\"\"Init a single device_tracker entity.\"\"\"", "await", "dev", ".", "async_added_to_hass", "(", ")", "dev", ".", "async_write_ha_state", "(", ")", "tasks", "=", "[", "]", "for", "device", "in", "self", ".", "devices", ".", "values", "(", ")", ":", "if", "device", ".", "track", "and", "not", "device", ".", "last_seen", ":", "tasks", ".", "append", "(", "self", ".", "hass", ".", "async_create_task", "(", "async_init_single_device", "(", "device", ")", ")", ")", "if", "tasks", ":", "await", "asyncio", ".", "wait", "(", "tasks", ")" ]
[ 252, 4 ]
[ 271, 37 ]
python
en
['en', 'en', 'en']
True
Device.__init__
( self, hass: HomeAssistantType, consider_home: timedelta, track: bool, dev_id: str, mac: str, name: str = None, picture: str = None, gravatar: str = None, icon: str = None, )
Initialize a device.
Initialize a device.
def __init__( self, hass: HomeAssistantType, consider_home: timedelta, track: bool, dev_id: str, mac: str, name: str = None, picture: str = None, gravatar: str = None, icon: str = None, ) -> None: """Initialize a device.""" self.hass = hass self.entity_id = f"{DOMAIN}.{dev_id}" # Timedelta object how long we consider a device home if it is not # detected anymore. self.consider_home = consider_home # Device ID self.dev_id = dev_id self.mac = mac # If we should track this device self.track = track # Configured name self.config_name = name # Configured picture if gravatar is not None: self.config_picture = get_gravatar_for_email(gravatar) else: self.config_picture = picture self.icon = icon self.source_type = None self._attributes = {}
[ "def", "__init__", "(", "self", ",", "hass", ":", "HomeAssistantType", ",", "consider_home", ":", "timedelta", ",", "track", ":", "bool", ",", "dev_id", ":", "str", ",", "mac", ":", "str", ",", "name", ":", "str", "=", "None", ",", "picture", ":", "str", "=", "None", ",", "gravatar", ":", "str", "=", "None", ",", "icon", ":", "str", "=", "None", ",", ")", "->", "None", ":", "self", ".", "hass", "=", "hass", "self", ".", "entity_id", "=", "f\"{DOMAIN}.{dev_id}\"", "# Timedelta object how long we consider a device home if it is not", "# detected anymore.", "self", ".", "consider_home", "=", "consider_home", "# Device ID", "self", ".", "dev_id", "=", "dev_id", "self", ".", "mac", "=", "mac", "# If we should track this device", "self", ".", "track", "=", "track", "# Configured name", "self", ".", "config_name", "=", "name", "# Configured picture", "if", "gravatar", "is", "not", "None", ":", "self", ".", "config_picture", "=", "get_gravatar_for_email", "(", "gravatar", ")", "else", ":", "self", ".", "config_picture", "=", "picture", "self", ".", "icon", "=", "icon", "self", ".", "source_type", "=", "None", "self", ".", "_attributes", "=", "{", "}" ]
[ 291, 4 ]
[ 331, 29 ]
python
en
['es', 'en', 'en']
True
Device.name
(self)
Return the name of the entity.
Return the name of the entity.
def name(self): """Return the name of the entity.""" return self.config_name or self.host_name or self.dev_id or DEVICE_DEFAULT_NAME
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "config_name", "or", "self", ".", "host_name", "or", "self", ".", "dev_id", "or", "DEVICE_DEFAULT_NAME" ]
[ 334, 4 ]
[ 336, 87 ]
python
en
['en', 'en', 'en']
True
Device.state
(self)
Return the state of the device.
Return the state of the device.
def state(self): """Return the state of the device.""" return self._state
[ "def", "state", "(", "self", ")", ":", "return", "self", ".", "_state" ]
[ 339, 4 ]
[ 341, 26 ]
python
en
['en', 'en', 'en']
True
Device.entity_picture
(self)
Return the picture of the device.
Return the picture of the device.
def entity_picture(self): """Return the picture of the device.""" return self.config_picture
[ "def", "entity_picture", "(", "self", ")", ":", "return", "self", ".", "config_picture" ]
[ 344, 4 ]
[ 346, 34 ]
python
en
['en', 'en', 'en']
True
Device.state_attributes
(self)
Return the device state attributes.
Return the device state attributes.
def state_attributes(self): """Return the device state attributes.""" attr = {ATTR_SOURCE_TYPE: self.source_type} if self.gps: attr[ATTR_LATITUDE] = self.gps[0] attr[ATTR_LONGITUDE] = self.gps[1] attr[ATTR_GPS_ACCURACY] = self.gps_accuracy if self.battery: attr[ATTR_BATTERY] = self.battery return attr
[ "def", "state_attributes", "(", "self", ")", ":", "attr", "=", "{", "ATTR_SOURCE_TYPE", ":", "self", ".", "source_type", "}", "if", "self", ".", "gps", ":", "attr", "[", "ATTR_LATITUDE", "]", "=", "self", ".", "gps", "[", "0", "]", "attr", "[", "ATTR_LONGITUDE", "]", "=", "self", ".", "gps", "[", "1", "]", "attr", "[", "ATTR_GPS_ACCURACY", "]", "=", "self", ".", "gps_accuracy", "if", "self", ".", "battery", ":", "attr", "[", "ATTR_BATTERY", "]", "=", "self", ".", "battery", "return", "attr" ]
[ 349, 4 ]
[ 361, 19 ]
python
en
['en', 'en', 'en']
True
Device.device_state_attributes
(self)
Return device state attributes.
Return device state attributes.
def device_state_attributes(self): """Return device state attributes.""" return self._attributes
[ "def", "device_state_attributes", "(", "self", ")", ":", "return", "self", ".", "_attributes" ]
[ 364, 4 ]
[ 366, 31 ]
python
en
['es', 'en', 'en']
True
Device.async_seen
( self, host_name: str = None, location_name: str = None, gps: GPSType = None, gps_accuracy=0, battery: int = None, attributes: dict = None, source_type: str = SOURCE_TYPE_GPS, consider_home: timedelta = None, )
Mark the device as seen.
Mark the device as seen.
async def async_seen( self, host_name: str = None, location_name: str = None, gps: GPSType = None, gps_accuracy=0, battery: int = None, attributes: dict = None, source_type: str = SOURCE_TYPE_GPS, consider_home: timedelta = None, ): """Mark the device as seen.""" self.source_type = source_type self.last_seen = dt_util.utcnow() self.host_name = host_name or self.host_name self.location_name = location_name self.consider_home = consider_home or self.consider_home if battery: self.battery = battery if attributes: self._attributes.update(attributes) self.gps = None if gps is not None: try: self.gps = float(gps[0]), float(gps[1]) self.gps_accuracy = gps_accuracy or 0 except (ValueError, TypeError, IndexError): self.gps = None self.gps_accuracy = 0 LOGGER.warning("Could not parse gps value for %s: %s", self.dev_id, gps) await self.async_update()
[ "async", "def", "async_seen", "(", "self", ",", "host_name", ":", "str", "=", "None", ",", "location_name", ":", "str", "=", "None", ",", "gps", ":", "GPSType", "=", "None", ",", "gps_accuracy", "=", "0", ",", "battery", ":", "int", "=", "None", ",", "attributes", ":", "dict", "=", "None", ",", "source_type", ":", "str", "=", "SOURCE_TYPE_GPS", ",", "consider_home", ":", "timedelta", "=", "None", ",", ")", ":", "self", ".", "source_type", "=", "source_type", "self", ".", "last_seen", "=", "dt_util", ".", "utcnow", "(", ")", "self", ".", "host_name", "=", "host_name", "or", "self", ".", "host_name", "self", ".", "location_name", "=", "location_name", "self", ".", "consider_home", "=", "consider_home", "or", "self", ".", "consider_home", "if", "battery", ":", "self", ".", "battery", "=", "battery", "if", "attributes", ":", "self", ".", "_attributes", ".", "update", "(", "attributes", ")", "self", ".", "gps", "=", "None", "if", "gps", "is", "not", "None", ":", "try", ":", "self", ".", "gps", "=", "float", "(", "gps", "[", "0", "]", ")", ",", "float", "(", "gps", "[", "1", "]", ")", "self", ".", "gps_accuracy", "=", "gps_accuracy", "or", "0", "except", "(", "ValueError", ",", "TypeError", ",", "IndexError", ")", ":", "self", ".", "gps", "=", "None", "self", ".", "gps_accuracy", "=", "0", "LOGGER", ".", "warning", "(", "\"Could not parse gps value for %s: %s\"", ",", "self", ".", "dev_id", ",", "gps", ")", "await", "self", ".", "async_update", "(", ")" ]
[ 368, 4 ]
[ 402, 33 ]
python
en
['en', 'en', 'en']
True
Device.stale
(self, now: dt_util.dt.datetime = None)
Return if device state is stale. Async friendly.
Return if device state is stale.
def stale(self, now: dt_util.dt.datetime = None): """Return if device state is stale. Async friendly. """ return ( self.last_seen is None or (now or dt_util.utcnow()) - self.last_seen > self.consider_home )
[ "def", "stale", "(", "self", ",", "now", ":", "dt_util", ".", "dt", ".", "datetime", "=", "None", ")", ":", "return", "(", "self", ".", "last_seen", "is", "None", "or", "(", "now", "or", "dt_util", ".", "utcnow", "(", ")", ")", "-", "self", ".", "last_seen", ">", "self", ".", "consider_home", ")" ]
[ 404, 4 ]
[ 412, 9 ]
python
en
['en', 'en', 'en']
True
Device.mark_stale
(self)
Mark the device state as stale.
Mark the device state as stale.
def mark_stale(self): """Mark the device state as stale.""" self._state = STATE_NOT_HOME self.gps = None self.last_update_home = False
[ "def", "mark_stale", "(", "self", ")", ":", "self", ".", "_state", "=", "STATE_NOT_HOME", "self", ".", "gps", "=", "None", "self", ".", "last_update_home", "=", "False" ]
[ 414, 4 ]
[ 418, 37 ]
python
en
['en', 'en', 'en']
True
Device.async_update
(self)
Update state of entity. This method is a coroutine.
Update state of entity.
async def async_update(self): """Update state of entity. This method is a coroutine. """ if not self.last_seen: return if self.location_name: self._state = self.location_name elif self.gps is not None and self.source_type == SOURCE_TYPE_GPS: zone_state = zone.async_active_zone( self.hass, self.gps[0], self.gps[1], self.gps_accuracy ) if zone_state is None: self._state = STATE_NOT_HOME elif zone_state.entity_id == zone.ENTITY_ID_HOME: self._state = STATE_HOME else: self._state = zone_state.name elif self.stale(): self.mark_stale() else: self._state = STATE_HOME self.last_update_home = True
[ "async", "def", "async_update", "(", "self", ")", ":", "if", "not", "self", ".", "last_seen", ":", "return", "if", "self", ".", "location_name", ":", "self", ".", "_state", "=", "self", ".", "location_name", "elif", "self", ".", "gps", "is", "not", "None", "and", "self", ".", "source_type", "==", "SOURCE_TYPE_GPS", ":", "zone_state", "=", "zone", ".", "async_active_zone", "(", "self", ".", "hass", ",", "self", ".", "gps", "[", "0", "]", ",", "self", ".", "gps", "[", "1", "]", ",", "self", ".", "gps_accuracy", ")", "if", "zone_state", "is", "None", ":", "self", ".", "_state", "=", "STATE_NOT_HOME", "elif", "zone_state", ".", "entity_id", "==", "zone", ".", "ENTITY_ID_HOME", ":", "self", ".", "_state", "=", "STATE_HOME", "else", ":", "self", ".", "_state", "=", "zone_state", ".", "name", "elif", "self", ".", "stale", "(", ")", ":", "self", ".", "mark_stale", "(", ")", "else", ":", "self", ".", "_state", "=", "STATE_HOME", "self", ".", "last_update_home", "=", "True" ]
[ 420, 4 ]
[ 443, 40 ]
python
en
['en', 'en', 'en']
True
Device.async_added_to_hass
(self)
Add an entity.
Add an entity.
async def async_added_to_hass(self): """Add an entity.""" await super().async_added_to_hass() state = await self.async_get_last_state() if not state: return self._state = state.state self.last_update_home = state.state == STATE_HOME self.last_seen = dt_util.utcnow() for attr, var in ( (ATTR_SOURCE_TYPE, "source_type"), (ATTR_GPS_ACCURACY, "gps_accuracy"), (ATTR_BATTERY, "battery"), ): if attr in state.attributes: setattr(self, var, state.attributes[attr]) if ATTR_LONGITUDE in state.attributes: self.gps = ( state.attributes[ATTR_LATITUDE], state.attributes[ATTR_LONGITUDE], )
[ "async", "def", "async_added_to_hass", "(", "self", ")", ":", "await", "super", "(", ")", ".", "async_added_to_hass", "(", ")", "state", "=", "await", "self", ".", "async_get_last_state", "(", ")", "if", "not", "state", ":", "return", "self", ".", "_state", "=", "state", ".", "state", "self", ".", "last_update_home", "=", "state", ".", "state", "==", "STATE_HOME", "self", ".", "last_seen", "=", "dt_util", ".", "utcnow", "(", ")", "for", "attr", ",", "var", "in", "(", "(", "ATTR_SOURCE_TYPE", ",", "\"source_type\"", ")", ",", "(", "ATTR_GPS_ACCURACY", ",", "\"gps_accuracy\"", ")", ",", "(", "ATTR_BATTERY", ",", "\"battery\"", ")", ",", ")", ":", "if", "attr", "in", "state", ".", "attributes", ":", "setattr", "(", "self", ",", "var", ",", "state", ".", "attributes", "[", "attr", "]", ")", "if", "ATTR_LONGITUDE", "in", "state", ".", "attributes", ":", "self", ".", "gps", "=", "(", "state", ".", "attributes", "[", "ATTR_LATITUDE", "]", ",", "state", ".", "attributes", "[", "ATTR_LONGITUDE", "]", ",", ")" ]
[ 445, 4 ]
[ 467, 13 ]
python
en
['en', 'cy', 'en']
True
DeviceScanner.scan_devices
(self)
Scan for devices.
Scan for devices.
def scan_devices(self) -> List[str]: """Scan for devices.""" raise NotImplementedError()
[ "def", "scan_devices", "(", "self", ")", "->", "List", "[", "str", "]", ":", "raise", "NotImplementedError", "(", ")" ]
[ 475, 4 ]
[ 477, 35 ]
python
en
['no', 'en', 'en']
True
DeviceScanner.async_scan_devices
(self)
Scan for devices.
Scan for devices.
async def async_scan_devices(self) -> Any: """Scan for devices.""" return await self.hass.async_add_executor_job(self.scan_devices)
[ "async", "def", "async_scan_devices", "(", "self", ")", "->", "Any", ":", "return", "await", "self", ".", "hass", ".", "async_add_executor_job", "(", "self", ".", "scan_devices", ")" ]
[ 479, 4 ]
[ 481, 72 ]
python
en
['no', 'en', 'en']
True
DeviceScanner.get_device_name
(self, device: str)
Get the name of a device.
Get the name of a device.
def get_device_name(self, device: str) -> str: """Get the name of a device.""" raise NotImplementedError()
[ "def", "get_device_name", "(", "self", ",", "device", ":", "str", ")", "->", "str", ":", "raise", "NotImplementedError", "(", ")" ]
[ 483, 4 ]
[ 485, 35 ]
python
en
['en', 'en', 'en']
True
DeviceScanner.async_get_device_name
(self, device: str)
Get the name of a device.
Get the name of a device.
async def async_get_device_name(self, device: str) -> Any: """Get the name of a device.""" return await self.hass.async_add_executor_job(self.get_device_name, device)
[ "async", "def", "async_get_device_name", "(", "self", ",", "device", ":", "str", ")", "->", "Any", ":", "return", "await", "self", ".", "hass", ".", "async_add_executor_job", "(", "self", ".", "get_device_name", ",", "device", ")" ]
[ 487, 4 ]
[ 489, 83 ]
python
en
['en', 'en', 'en']
True
DeviceScanner.get_extra_attributes
(self, device: str)
Get the extra attributes of a device.
Get the extra attributes of a device.
def get_extra_attributes(self, device: str) -> dict: """Get the extra attributes of a device.""" raise NotImplementedError()
[ "def", "get_extra_attributes", "(", "self", ",", "device", ":", "str", ")", "->", "dict", ":", "raise", "NotImplementedError", "(", ")" ]
[ 491, 4 ]
[ 493, 35 ]
python
en
['en', 'en', 'en']
True
DeviceScanner.async_get_extra_attributes
(self, device: str)
Get the extra attributes of a device.
Get the extra attributes of a device.
async def async_get_extra_attributes(self, device: str) -> Any: """Get the extra attributes of a device.""" return await self.hass.async_add_executor_job(self.get_extra_attributes, device)
[ "async", "def", "async_get_extra_attributes", "(", "self", ",", "device", ":", "str", ")", "->", "Any", ":", "return", "await", "self", ".", "hass", ".", "async_add_executor_job", "(", "self", ".", "get_extra_attributes", ",", "device", ")" ]
[ 495, 4 ]
[ 497, 88 ]
python
en
['en', 'en', 'en']
True
test_import_usb
(hass, dsmr_connection_send_validate_fixture)
Test we can import.
Test we can import.
async def test_import_usb(hass, dsmr_connection_send_validate_fixture): """Test we can import.""" await setup.async_setup_component(hass, "persistent_notification", {}) entry_data = { "port": "/dev/ttyUSB0", "dsmr_version": "2.2", "precision": 4, "reconnect_interval": 30, } with patch("homeassistant.components.dsmr.async_setup_entry", return_value=True): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_IMPORT}, data=entry_data, ) assert result["type"] == "create_entry" assert result["title"] == "/dev/ttyUSB0" assert result["data"] == {**entry_data, **SERIAL_DATA}
[ "async", "def", "test_import_usb", "(", "hass", ",", "dsmr_connection_send_validate_fixture", ")", ":", "await", "setup", ".", "async_setup_component", "(", "hass", ",", "\"persistent_notification\"", ",", "{", "}", ")", "entry_data", "=", "{", "\"port\"", ":", "\"/dev/ttyUSB0\"", ",", "\"dsmr_version\"", ":", "\"2.2\"", ",", "\"precision\"", ":", "4", ",", "\"reconnect_interval\"", ":", "30", ",", "}", "with", "patch", "(", "\"homeassistant.components.dsmr.async_setup_entry\"", ",", "return_value", "=", "True", ")", ":", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "config_entries", ".", "SOURCE_IMPORT", "}", ",", "data", "=", "entry_data", ",", ")", "assert", "result", "[", "\"type\"", "]", "==", "\"create_entry\"", "assert", "result", "[", "\"title\"", "]", "==", "\"/dev/ttyUSB0\"", "assert", "result", "[", "\"data\"", "]", "==", "{", "*", "*", "entry_data", ",", "*", "*", "SERIAL_DATA", "}" ]
[ 15, 0 ]
[ 35, 58 ]
python
en
['en', 'en', 'en']
True
test_import_usb_failed_connection
( hass, dsmr_connection_send_validate_fixture )
Test we can import.
Test we can import.
async def test_import_usb_failed_connection( hass, dsmr_connection_send_validate_fixture ): """Test we can import.""" (connection_factory, transport, protocol) = dsmr_connection_send_validate_fixture await setup.async_setup_component(hass, "persistent_notification", {}) entry_data = { "port": "/dev/ttyUSB0", "dsmr_version": "2.2", "precision": 4, "reconnect_interval": 30, } # override the mock to have it fail the first time and succeed after first_fail_connection_factory = AsyncMock( return_value=(transport, protocol), side_effect=chain([serial.serialutil.SerialException], repeat(DEFAULT)), ) with patch( "homeassistant.components.dsmr.async_setup_entry", return_value=True ), patch( "homeassistant.components.dsmr.config_flow.create_dsmr_reader", first_fail_connection_factory, ): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_IMPORT}, data=entry_data, ) assert result["type"] == "abort" assert result["reason"] == "cannot_connect"
[ "async", "def", "test_import_usb_failed_connection", "(", "hass", ",", "dsmr_connection_send_validate_fixture", ")", ":", "(", "connection_factory", ",", "transport", ",", "protocol", ")", "=", "dsmr_connection_send_validate_fixture", "await", "setup", ".", "async_setup_component", "(", "hass", ",", "\"persistent_notification\"", ",", "{", "}", ")", "entry_data", "=", "{", "\"port\"", ":", "\"/dev/ttyUSB0\"", ",", "\"dsmr_version\"", ":", "\"2.2\"", ",", "\"precision\"", ":", "4", ",", "\"reconnect_interval\"", ":", "30", ",", "}", "# override the mock to have it fail the first time and succeed after", "first_fail_connection_factory", "=", "AsyncMock", "(", "return_value", "=", "(", "transport", ",", "protocol", ")", ",", "side_effect", "=", "chain", "(", "[", "serial", ".", "serialutil", ".", "SerialException", "]", ",", "repeat", "(", "DEFAULT", ")", ")", ",", ")", "with", "patch", "(", "\"homeassistant.components.dsmr.async_setup_entry\"", ",", "return_value", "=", "True", ")", ",", "patch", "(", "\"homeassistant.components.dsmr.config_flow.create_dsmr_reader\"", ",", "first_fail_connection_factory", ",", ")", ":", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "config_entries", ".", "SOURCE_IMPORT", "}", ",", "data", "=", "entry_data", ",", ")", "assert", "result", "[", "\"type\"", "]", "==", "\"abort\"", "assert", "result", "[", "\"reason\"", "]", "==", "\"cannot_connect\"" ]
[ 38, 0 ]
[ 72, 47 ]
python
en
['en', 'en', 'en']
True
test_import_usb_no_data
(hass, dsmr_connection_send_validate_fixture)
Test we can import.
Test we can import.
async def test_import_usb_no_data(hass, dsmr_connection_send_validate_fixture): """Test we can import.""" (connection_factory, transport, protocol) = dsmr_connection_send_validate_fixture await setup.async_setup_component(hass, "persistent_notification", {}) entry_data = { "port": "/dev/ttyUSB0", "dsmr_version": "2.2", "precision": 4, "reconnect_interval": 30, } # override the mock to have it fail the first time and succeed after wait_closed = AsyncMock( return_value=(transport, protocol), side_effect=chain([asyncio.TimeoutError], repeat(DEFAULT)), ) protocol.wait_closed = wait_closed with patch("homeassistant.components.dsmr.async_setup_entry", return_value=True): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_IMPORT}, data=entry_data, ) assert result["type"] == "abort" assert result["reason"] == "cannot_communicate"
[ "async", "def", "test_import_usb_no_data", "(", "hass", ",", "dsmr_connection_send_validate_fixture", ")", ":", "(", "connection_factory", ",", "transport", ",", "protocol", ")", "=", "dsmr_connection_send_validate_fixture", "await", "setup", ".", "async_setup_component", "(", "hass", ",", "\"persistent_notification\"", ",", "{", "}", ")", "entry_data", "=", "{", "\"port\"", ":", "\"/dev/ttyUSB0\"", ",", "\"dsmr_version\"", ":", "\"2.2\"", ",", "\"precision\"", ":", "4", ",", "\"reconnect_interval\"", ":", "30", ",", "}", "# override the mock to have it fail the first time and succeed after", "wait_closed", "=", "AsyncMock", "(", "return_value", "=", "(", "transport", ",", "protocol", ")", ",", "side_effect", "=", "chain", "(", "[", "asyncio", ".", "TimeoutError", "]", ",", "repeat", "(", "DEFAULT", ")", ")", ",", ")", "protocol", ".", "wait_closed", "=", "wait_closed", "with", "patch", "(", "\"homeassistant.components.dsmr.async_setup_entry\"", ",", "return_value", "=", "True", ")", ":", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "config_entries", ".", "SOURCE_IMPORT", "}", ",", "data", "=", "entry_data", ",", ")", "assert", "result", "[", "\"type\"", "]", "==", "\"abort\"", "assert", "result", "[", "\"reason\"", "]", "==", "\"cannot_communicate\"" ]
[ 75, 0 ]
[ 104, 51 ]
python
en
['en', 'en', 'en']
True
test_import_usb_wrong_telegram
(hass, dsmr_connection_send_validate_fixture)
Test we can import.
Test we can import.
async def test_import_usb_wrong_telegram(hass, dsmr_connection_send_validate_fixture): """Test we can import.""" (connection_factory, transport, protocol) = dsmr_connection_send_validate_fixture await setup.async_setup_component(hass, "persistent_notification", {}) entry_data = { "port": "/dev/ttyUSB0", "dsmr_version": "2.2", "precision": 4, "reconnect_interval": 30, } protocol.telegram = {} with patch("homeassistant.components.dsmr.async_setup_entry", return_value=True): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_IMPORT}, data=entry_data, ) assert result["type"] == "abort" assert result["reason"] == "cannot_communicate"
[ "async", "def", "test_import_usb_wrong_telegram", "(", "hass", ",", "dsmr_connection_send_validate_fixture", ")", ":", "(", "connection_factory", ",", "transport", ",", "protocol", ")", "=", "dsmr_connection_send_validate_fixture", "await", "setup", ".", "async_setup_component", "(", "hass", ",", "\"persistent_notification\"", ",", "{", "}", ")", "entry_data", "=", "{", "\"port\"", ":", "\"/dev/ttyUSB0\"", ",", "\"dsmr_version\"", ":", "\"2.2\"", ",", "\"precision\"", ":", "4", ",", "\"reconnect_interval\"", ":", "30", ",", "}", "protocol", ".", "telegram", "=", "{", "}", "with", "patch", "(", "\"homeassistant.components.dsmr.async_setup_entry\"", ",", "return_value", "=", "True", ")", ":", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "config_entries", ".", "SOURCE_IMPORT", "}", ",", "data", "=", "entry_data", ",", ")", "assert", "result", "[", "\"type\"", "]", "==", "\"abort\"", "assert", "result", "[", "\"reason\"", "]", "==", "\"cannot_communicate\"" ]
[ 107, 0 ]
[ 130, 51 ]
python
en
['en', 'en', 'en']
True
test_import_network
(hass, dsmr_connection_send_validate_fixture)
Test we can import from network.
Test we can import from network.
async def test_import_network(hass, dsmr_connection_send_validate_fixture): """Test we can import from network.""" await setup.async_setup_component(hass, "persistent_notification", {}) entry_data = { "host": "localhost", "port": "1234", "dsmr_version": "2.2", "precision": 4, "reconnect_interval": 30, } with patch("homeassistant.components.dsmr.async_setup_entry", return_value=True): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_IMPORT}, data=entry_data, ) assert result["type"] == "create_entry" assert result["title"] == "localhost:1234" assert result["data"] == {**entry_data, **SERIAL_DATA}
[ "async", "def", "test_import_network", "(", "hass", ",", "dsmr_connection_send_validate_fixture", ")", ":", "await", "setup", ".", "async_setup_component", "(", "hass", ",", "\"persistent_notification\"", ",", "{", "}", ")", "entry_data", "=", "{", "\"host\"", ":", "\"localhost\"", ",", "\"port\"", ":", "\"1234\"", ",", "\"dsmr_version\"", ":", "\"2.2\"", ",", "\"precision\"", ":", "4", ",", "\"reconnect_interval\"", ":", "30", ",", "}", "with", "patch", "(", "\"homeassistant.components.dsmr.async_setup_entry\"", ",", "return_value", "=", "True", ")", ":", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "config_entries", ".", "SOURCE_IMPORT", "}", ",", "data", "=", "entry_data", ",", ")", "assert", "result", "[", "\"type\"", "]", "==", "\"create_entry\"", "assert", "result", "[", "\"title\"", "]", "==", "\"localhost:1234\"", "assert", "result", "[", "\"data\"", "]", "==", "{", "*", "*", "entry_data", ",", "*", "*", "SERIAL_DATA", "}" ]
[ 133, 0 ]
[ 154, 58 ]
python
en
['en', 'en', 'en']
True
test_import_update
(hass, dsmr_connection_send_validate_fixture)
Test we can import.
Test we can import.
async def test_import_update(hass, dsmr_connection_send_validate_fixture): """Test we can import.""" await setup.async_setup_component(hass, "persistent_notification", {}) entry_data = { "port": "/dev/ttyUSB0", "dsmr_version": "2.2", "precision": 4, "reconnect_interval": 30, } entry = MockConfigEntry( domain=DOMAIN, data=entry_data, unique_id="/dev/ttyUSB0", ) entry.add_to_hass(hass) with patch( "homeassistant.components.dsmr.async_setup_entry", return_value=True ), patch("homeassistant.components.dsmr.async_unload_entry", return_value=True): await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() new_entry_data = { "port": "/dev/ttyUSB0", "dsmr_version": "2.2", "precision": 3, "reconnect_interval": 30, } with patch( "homeassistant.components.dsmr.async_setup_entry", return_value=True ), patch("homeassistant.components.dsmr.async_unload_entry", return_value=True): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_IMPORT}, data=new_entry_data, ) await hass.async_block_till_done() assert result["type"] == "abort" assert result["reason"] == "already_configured" assert entry.data["precision"] == 3
[ "async", "def", "test_import_update", "(", "hass", ",", "dsmr_connection_send_validate_fixture", ")", ":", "await", "setup", ".", "async_setup_component", "(", "hass", ",", "\"persistent_notification\"", ",", "{", "}", ")", "entry_data", "=", "{", "\"port\"", ":", "\"/dev/ttyUSB0\"", ",", "\"dsmr_version\"", ":", "\"2.2\"", ",", "\"precision\"", ":", "4", ",", "\"reconnect_interval\"", ":", "30", ",", "}", "entry", "=", "MockConfigEntry", "(", "domain", "=", "DOMAIN", ",", "data", "=", "entry_data", ",", "unique_id", "=", "\"/dev/ttyUSB0\"", ",", ")", "entry", ".", "add_to_hass", "(", "hass", ")", "with", "patch", "(", "\"homeassistant.components.dsmr.async_setup_entry\"", ",", "return_value", "=", "True", ")", ",", "patch", "(", "\"homeassistant.components.dsmr.async_unload_entry\"", ",", "return_value", "=", "True", ")", ":", "await", "hass", ".", "config_entries", ".", "async_setup", "(", "entry", ".", "entry_id", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "new_entry_data", "=", "{", "\"port\"", ":", "\"/dev/ttyUSB0\"", ",", "\"dsmr_version\"", ":", "\"2.2\"", ",", "\"precision\"", ":", "3", ",", "\"reconnect_interval\"", ":", "30", ",", "}", "with", "patch", "(", "\"homeassistant.components.dsmr.async_setup_entry\"", ",", "return_value", "=", "True", ")", ",", "patch", "(", "\"homeassistant.components.dsmr.async_unload_entry\"", ",", "return_value", "=", "True", ")", ":", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "config_entries", ".", "SOURCE_IMPORT", "}", ",", "data", "=", "new_entry_data", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "result", "[", "\"type\"", "]", "==", "\"abort\"", "assert", "result", "[", "\"reason\"", "]", "==", "\"already_configured\"", "assert", "entry", ".", "data", "[", "\"precision\"", "]", "==", "3" ]
[ 157, 0 ]
[ 203, 39 ]
python
en
['en', 'en', 'en']
True
test_options_flow
(hass)
Test options flow.
Test options flow.
async def test_options_flow(hass): """Test options flow.""" await setup.async_setup_component(hass, "persistent_notification", {}) entry_data = { "port": "/dev/ttyUSB0", "dsmr_version": "2.2", "precision": 4, "reconnect_interval": 30, } entry = MockConfigEntry( domain=DOMAIN, data=entry_data, unique_id="/dev/ttyUSB0", ) entry.add_to_hass(hass) result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == "form" assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={ "time_between_update": 15, }, ) with patch( "homeassistant.components.dsmr.async_setup_entry", return_value=True ), patch("homeassistant.components.dsmr.async_unload_entry", return_value=True): assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() assert entry.options == {"time_between_update": 15}
[ "async", "def", "test_options_flow", "(", "hass", ")", ":", "await", "setup", ".", "async_setup_component", "(", "hass", ",", "\"persistent_notification\"", ",", "{", "}", ")", "entry_data", "=", "{", "\"port\"", ":", "\"/dev/ttyUSB0\"", ",", "\"dsmr_version\"", ":", "\"2.2\"", ",", "\"precision\"", ":", "4", ",", "\"reconnect_interval\"", ":", "30", ",", "}", "entry", "=", "MockConfigEntry", "(", "domain", "=", "DOMAIN", ",", "data", "=", "entry_data", ",", "unique_id", "=", "\"/dev/ttyUSB0\"", ",", ")", "entry", ".", "add_to_hass", "(", "hass", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "options", ".", "async_init", "(", "entry", ".", "entry_id", ")", "assert", "result", "[", "\"type\"", "]", "==", "\"form\"", "assert", "result", "[", "\"step_id\"", "]", "==", "\"init\"", "result", "=", "await", "hass", ".", "config_entries", ".", "options", ".", "async_configure", "(", "result", "[", "\"flow_id\"", "]", ",", "user_input", "=", "{", "\"time_between_update\"", ":", "15", ",", "}", ",", ")", "with", "patch", "(", "\"homeassistant.components.dsmr.async_setup_entry\"", ",", "return_value", "=", "True", ")", ",", "patch", "(", "\"homeassistant.components.dsmr.async_unload_entry\"", ",", "return_value", "=", "True", ")", ":", "assert", "result", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_CREATE_ENTRY", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "entry", ".", "options", "==", "{", "\"time_between_update\"", ":", "15", "}" ]
[ 206, 0 ]
[ 243, 55 ]
python
en
['en', 'fr', 'en']
True
setup_platform
(hass, config, add_entities, discovery_info=None)
Set up the BeagleBone Black GPIO devices.
Set up the BeagleBone Black GPIO devices.
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the BeagleBone Black GPIO devices.""" pins = config[CONF_PINS] switches = [] for pin, params in pins.items(): switches.append(BBBGPIOSwitch(pin, params)) add_entities(switches)
[ "def", "setup_platform", "(", "hass", ",", "config", ",", "add_entities", ",", "discovery_info", "=", "None", ")", ":", "pins", "=", "config", "[", "CONF_PINS", "]", "switches", "=", "[", "]", "for", "pin", ",", "params", "in", "pins", ".", "items", "(", ")", ":", "switches", ".", "append", "(", "BBBGPIOSwitch", "(", "pin", ",", "params", ")", ")", "add_entities", "(", "switches", ")" ]
[ 26, 0 ]
[ 33, 26 ]
python
en
['en', 'pt', 'en']
True
BBBGPIOSwitch.__init__
(self, pin, params)
Initialize the pin.
Initialize the pin.
def __init__(self, pin, params): """Initialize the pin.""" self._pin = pin self._name = params[CONF_NAME] or DEVICE_DEFAULT_NAME self._state = params[CONF_INITIAL] self._invert_logic = params[CONF_INVERT_LOGIC] bbb_gpio.setup_output(self._pin) if self._state is False: bbb_gpio.write_output(self._pin, 1 if self._invert_logic else 0) else: bbb_gpio.write_output(self._pin, 0 if self._invert_logic else 1)
[ "def", "__init__", "(", "self", ",", "pin", ",", "params", ")", ":", "self", ".", "_pin", "=", "pin", "self", ".", "_name", "=", "params", "[", "CONF_NAME", "]", "or", "DEVICE_DEFAULT_NAME", "self", ".", "_state", "=", "params", "[", "CONF_INITIAL", "]", "self", ".", "_invert_logic", "=", "params", "[", "CONF_INVERT_LOGIC", "]", "bbb_gpio", ".", "setup_output", "(", "self", ".", "_pin", ")", "if", "self", ".", "_state", "is", "False", ":", "bbb_gpio", ".", "write_output", "(", "self", ".", "_pin", ",", "1", "if", "self", ".", "_invert_logic", "else", "0", ")", "else", ":", "bbb_gpio", ".", "write_output", "(", "self", ".", "_pin", ",", "0", "if", "self", ".", "_invert_logic", "else", "1", ")" ]
[ 39, 4 ]
[ 51, 76 ]
python
en
['en', 'en', 'en']
True
BBBGPIOSwitch.name
(self)
Return the name of the switch.
Return the name of the switch.
def name(self): """Return the name of the switch.""" return self._name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name" ]
[ 54, 4 ]
[ 56, 25 ]
python
en
['en', 'en', 'en']
True
BBBGPIOSwitch.should_poll
(self)
No polling needed.
No polling needed.
def should_poll(self): """No polling needed.""" return False
[ "def", "should_poll", "(", "self", ")", ":", "return", "False" ]
[ 59, 4 ]
[ 61, 20 ]
python
en
['en', 'en', 'en']
True
BBBGPIOSwitch.is_on
(self)
Return true if device is on.
Return true if device is on.
def is_on(self): """Return true if device is on.""" return self._state
[ "def", "is_on", "(", "self", ")", ":", "return", "self", ".", "_state" ]
[ 64, 4 ]
[ 66, 26 ]
python
en
['en', 'fy', 'en']
True
BBBGPIOSwitch.turn_on
(self, **kwargs)
Turn the device on.
Turn the device on.
def turn_on(self, **kwargs): """Turn the device on.""" bbb_gpio.write_output(self._pin, 0 if self._invert_logic else 1) self._state = True self.schedule_update_ha_state()
[ "def", "turn_on", "(", "self", ",", "*", "*", "kwargs", ")", ":", "bbb_gpio", ".", "write_output", "(", "self", ".", "_pin", ",", "0", "if", "self", ".", "_invert_logic", "else", "1", ")", "self", ".", "_state", "=", "True", "self", ".", "schedule_update_ha_state", "(", ")" ]
[ 68, 4 ]
[ 72, 39 ]
python
en
['en', 'en', 'en']
True
BBBGPIOSwitch.turn_off
(self, **kwargs)
Turn the device off.
Turn the device off.
def turn_off(self, **kwargs): """Turn the device off.""" bbb_gpio.write_output(self._pin, 1 if self._invert_logic else 0) self._state = False self.schedule_update_ha_state()
[ "def", "turn_off", "(", "self", ",", "*", "*", "kwargs", ")", ":", "bbb_gpio", ".", "write_output", "(", "self", ".", "_pin", ",", "1", "if", "self", ".", "_invert_logic", "else", "0", ")", "self", ".", "_state", "=", "False", "self", ".", "schedule_update_ha_state", "(", ")" ]
[ 74, 4 ]
[ 78, 39 ]
python
en
['en', 'en', 'en']
True
ngram_attention_bias
(sequence_length, ngram, device, dtype)
This function computes the bias for the predict stream
This function computes the bias for the predict stream
def ngram_attention_bias(sequence_length, ngram, device, dtype): """ This function computes the bias for the predict stream """ left_block = torch.ones((ngram, sequence_length, sequence_length), device=device, dtype=dtype) * float("-inf") right_block = left_block.detach().clone() # create bias for stream_idx in range(ngram): right_block[stream_idx].fill_diagonal_(0, wrap=False) left_block[stream_idx].triu_(-stream_idx + 1) left_block[:, :, 0] = 0 return torch.cat([left_block, right_block], dim=2)
[ "def", "ngram_attention_bias", "(", "sequence_length", ",", "ngram", ",", "device", ",", "dtype", ")", ":", "left_block", "=", "torch", ".", "ones", "(", "(", "ngram", ",", "sequence_length", ",", "sequence_length", ")", ",", "device", "=", "device", ",", "dtype", "=", "dtype", ")", "*", "float", "(", "\"-inf\"", ")", "right_block", "=", "left_block", ".", "detach", "(", ")", ".", "clone", "(", ")", "# create bias", "for", "stream_idx", "in", "range", "(", "ngram", ")", ":", "right_block", "[", "stream_idx", "]", ".", "fill_diagonal_", "(", "0", ",", "wrap", "=", "False", ")", "left_block", "[", "stream_idx", "]", ".", "triu_", "(", "-", "stream_idx", "+", "1", ")", "left_block", "[", ":", ",", ":", ",", "0", "]", "=", "0", "return", "torch", ".", "cat", "(", "[", "left_block", ",", "right_block", "]", ",", "dim", "=", "2", ")" ]
[ 169, 0 ]
[ 181, 54 ]
python
en
['en', 'error', 'th']
False
compute_relative_buckets
(num_buckets, max_distance, relative_positions, is_bidirectional=False)
This function computes individual parts of the relative position buckets. For more detail, see paper.
This function computes individual parts of the relative position buckets. For more detail, see paper.
def compute_relative_buckets(num_buckets, max_distance, relative_positions, is_bidirectional=False): """ This function computes individual parts of the relative position buckets. For more detail, see paper. """ inv_relative_positions = -relative_positions rel_positions_bucket = 0 if is_bidirectional: num_buckets = num_buckets // 2 rel_positions_bucket = ( rel_positions_bucket + torch.lt(inv_relative_positions, torch.zeros_like(inv_relative_positions)).int() * num_buckets ) inv_relative_positions = torch.abs(inv_relative_positions) else: inv_relative_positions = torch.max(inv_relative_positions, torch.zeros_like(inv_relative_positions)) max_exact = num_buckets // 2 is_small = torch.lt(inv_relative_positions, max_exact) val_if_large = max_exact + torch.log(inv_relative_positions.float() / max_exact) / math.log( max_distance / max_exact ) * (num_buckets - max_exact) val_if_large = torch.min(val_if_large, torch.ones_like(val_if_large) * (num_buckets - 1)).int() rel_positions_bucket = rel_positions_bucket + torch.where(is_small, inv_relative_positions.int(), val_if_large) return rel_positions_bucket
[ "def", "compute_relative_buckets", "(", "num_buckets", ",", "max_distance", ",", "relative_positions", ",", "is_bidirectional", "=", "False", ")", ":", "inv_relative_positions", "=", "-", "relative_positions", "rel_positions_bucket", "=", "0", "if", "is_bidirectional", ":", "num_buckets", "=", "num_buckets", "//", "2", "rel_positions_bucket", "=", "(", "rel_positions_bucket", "+", "torch", ".", "lt", "(", "inv_relative_positions", ",", "torch", ".", "zeros_like", "(", "inv_relative_positions", ")", ")", ".", "int", "(", ")", "*", "num_buckets", ")", "inv_relative_positions", "=", "torch", ".", "abs", "(", "inv_relative_positions", ")", "else", ":", "inv_relative_positions", "=", "torch", ".", "max", "(", "inv_relative_positions", ",", "torch", ".", "zeros_like", "(", "inv_relative_positions", ")", ")", "max_exact", "=", "num_buckets", "//", "2", "is_small", "=", "torch", ".", "lt", "(", "inv_relative_positions", ",", "max_exact", ")", "val_if_large", "=", "max_exact", "+", "torch", ".", "log", "(", "inv_relative_positions", ".", "float", "(", ")", "/", "max_exact", ")", "/", "math", ".", "log", "(", "max_distance", "/", "max_exact", ")", "*", "(", "num_buckets", "-", "max_exact", ")", "val_if_large", "=", "torch", ".", "min", "(", "val_if_large", ",", "torch", ".", "ones_like", "(", "val_if_large", ")", "*", "(", "num_buckets", "-", "1", ")", ")", ".", "int", "(", ")", "rel_positions_bucket", "=", "rel_positions_bucket", "+", "torch", ".", "where", "(", "is_small", ",", "inv_relative_positions", ".", "int", "(", ")", ",", "val_if_large", ")", "return", "rel_positions_bucket" ]
[ 184, 0 ]
[ 208, 31 ]
python
en
['en', 'error', 'th']
False
compute_all_stream_relative_buckets
(num_buckets, max_distance, position_ids)
This function computes both main and predict relative position buckets. For more detail, see paper.
This function computes both main and predict relative position buckets. For more detail, see paper.
def compute_all_stream_relative_buckets(num_buckets, max_distance, position_ids): """ This function computes both main and predict relative position buckets. For more detail, see paper. """ # main stream main_stream_relative_positions = position_ids.unsqueeze(1).repeat(1, position_ids.size(-1), 1) main_stream_relative_positions = main_stream_relative_positions - position_ids.unsqueeze(-1) # predicting stream predicting_stream_relative_positions = torch.cat((position_ids - 1, position_ids), dim=-1).unsqueeze(1) predicting_stream_relative_positions = predicting_stream_relative_positions.repeat(1, position_ids.size(-1), 1) predicting_stream_relative_positions = predicting_stream_relative_positions - position_ids.unsqueeze(-1) # get both position buckets main_relative_position_buckets = compute_relative_buckets( num_buckets, max_distance, main_stream_relative_positions, is_bidirectional=False ) predict_relative_position_buckets = compute_relative_buckets( num_buckets, max_distance, predicting_stream_relative_positions, is_bidirectional=False ) return main_relative_position_buckets, predict_relative_position_buckets
[ "def", "compute_all_stream_relative_buckets", "(", "num_buckets", ",", "max_distance", ",", "position_ids", ")", ":", "# main stream", "main_stream_relative_positions", "=", "position_ids", ".", "unsqueeze", "(", "1", ")", ".", "repeat", "(", "1", ",", "position_ids", ".", "size", "(", "-", "1", ")", ",", "1", ")", "main_stream_relative_positions", "=", "main_stream_relative_positions", "-", "position_ids", ".", "unsqueeze", "(", "-", "1", ")", "# predicting stream", "predicting_stream_relative_positions", "=", "torch", ".", "cat", "(", "(", "position_ids", "-", "1", ",", "position_ids", ")", ",", "dim", "=", "-", "1", ")", ".", "unsqueeze", "(", "1", ")", "predicting_stream_relative_positions", "=", "predicting_stream_relative_positions", ".", "repeat", "(", "1", ",", "position_ids", ".", "size", "(", "-", "1", ")", ",", "1", ")", "predicting_stream_relative_positions", "=", "predicting_stream_relative_positions", "-", "position_ids", ".", "unsqueeze", "(", "-", "1", ")", "# get both position buckets", "main_relative_position_buckets", "=", "compute_relative_buckets", "(", "num_buckets", ",", "max_distance", ",", "main_stream_relative_positions", ",", "is_bidirectional", "=", "False", ")", "predict_relative_position_buckets", "=", "compute_relative_buckets", "(", "num_buckets", ",", "max_distance", ",", "predicting_stream_relative_positions", ",", "is_bidirectional", "=", "False", ")", "return", "main_relative_position_buckets", ",", "predict_relative_position_buckets" ]
[ 211, 0 ]
[ 231, 76 ]
python
en
['en', 'error', 'th']
False
AccuWeatherFlowHandler.async_step_user
(self, user_input=None)
Handle a flow initialized by the user.
Handle a flow initialized by the user.
async def async_step_user(self, user_input=None): """Handle a flow initialized by the user.""" # Under the terms of use of the API, one user can use one free API key. Due to # the small number of requests allowed, we only allow one integration instance. if self._async_current_entries(): return self.async_abort(reason="single_instance_allowed") errors = {} if user_input is not None: websession = async_get_clientsession(self.hass) try: async with timeout(10): accuweather = AccuWeather( user_input[CONF_API_KEY], websession, latitude=user_input[CONF_LATITUDE], longitude=user_input[CONF_LONGITUDE], ) await accuweather.async_get_location() except (ApiError, ClientConnectorError, asyncio.TimeoutError, ClientError): errors["base"] = "cannot_connect" except InvalidApiKeyError: errors[CONF_API_KEY] = "invalid_api_key" except RequestsExceededError: errors[CONF_API_KEY] = "requests_exceeded" else: await self.async_set_unique_id( accuweather.location_key, raise_on_progress=False ) return self.async_create_entry( title=user_input[CONF_NAME], data=user_input ) return self.async_show_form( step_id="user", data_schema=vol.Schema( { vol.Required(CONF_API_KEY): str, vol.Optional( CONF_LATITUDE, default=self.hass.config.latitude ): cv.latitude, vol.Optional( CONF_LONGITUDE, default=self.hass.config.longitude ): cv.longitude, vol.Optional( CONF_NAME, default=self.hass.config.location_name ): str, } ), errors=errors, )
[ "async", "def", "async_step_user", "(", "self", ",", "user_input", "=", "None", ")", ":", "# Under the terms of use of the API, one user can use one free API key. Due to", "# the small number of requests allowed, we only allow one integration instance.", "if", "self", ".", "_async_current_entries", "(", ")", ":", "return", "self", ".", "async_abort", "(", "reason", "=", "\"single_instance_allowed\"", ")", "errors", "=", "{", "}", "if", "user_input", "is", "not", "None", ":", "websession", "=", "async_get_clientsession", "(", "self", ".", "hass", ")", "try", ":", "async", "with", "timeout", "(", "10", ")", ":", "accuweather", "=", "AccuWeather", "(", "user_input", "[", "CONF_API_KEY", "]", ",", "websession", ",", "latitude", "=", "user_input", "[", "CONF_LATITUDE", "]", ",", "longitude", "=", "user_input", "[", "CONF_LONGITUDE", "]", ",", ")", "await", "accuweather", ".", "async_get_location", "(", ")", "except", "(", "ApiError", ",", "ClientConnectorError", ",", "asyncio", ".", "TimeoutError", ",", "ClientError", ")", ":", "errors", "[", "\"base\"", "]", "=", "\"cannot_connect\"", "except", "InvalidApiKeyError", ":", "errors", "[", "CONF_API_KEY", "]", "=", "\"invalid_api_key\"", "except", "RequestsExceededError", ":", "errors", "[", "CONF_API_KEY", "]", "=", "\"requests_exceeded\"", "else", ":", "await", "self", ".", "async_set_unique_id", "(", "accuweather", ".", "location_key", ",", "raise_on_progress", "=", "False", ")", "return", "self", ".", "async_create_entry", "(", "title", "=", "user_input", "[", "CONF_NAME", "]", ",", "data", "=", "user_input", ")", "return", "self", ".", "async_show_form", "(", "step_id", "=", "\"user\"", ",", "data_schema", "=", "vol", ".", "Schema", "(", "{", "vol", ".", "Required", "(", "CONF_API_KEY", ")", ":", "str", ",", "vol", ".", "Optional", "(", "CONF_LATITUDE", ",", "default", "=", "self", ".", "hass", ".", "config", ".", "latitude", ")", ":", "cv", ".", "latitude", ",", "vol", ".", "Optional", "(", "CONF_LONGITUDE", ",", "default", "=", "self", ".", "hass", ".", "config", ".", "longitude", ")", ":", "cv", ".", "longitude", ",", "vol", ".", "Optional", "(", "CONF_NAME", ",", "default", "=", "self", ".", "hass", ".", "config", ".", "location_name", ")", ":", "str", ",", "}", ")", ",", "errors", "=", "errors", ",", ")" ]
[ 24, 4 ]
[ 76, 9 ]
python
en
['en', 'en', 'en']
True
AccuWeatherFlowHandler.async_get_options_flow
(config_entry)
Options callback for AccuWeather.
Options callback for AccuWeather.
def async_get_options_flow(config_entry): """Options callback for AccuWeather.""" return AccuWeatherOptionsFlowHandler(config_entry)
[ "def", "async_get_options_flow", "(", "config_entry", ")", ":", "return", "AccuWeatherOptionsFlowHandler", "(", "config_entry", ")" ]
[ 80, 4 ]
[ 82, 58 ]
python
en
['en', 'en', 'en']
True
AccuWeatherOptionsFlowHandler.__init__
(self, config_entry)
Initialize AccuWeather options flow.
Initialize AccuWeather options flow.
def __init__(self, config_entry): """Initialize AccuWeather options flow.""" self.config_entry = config_entry
[ "def", "__init__", "(", "self", ",", "config_entry", ")", ":", "self", ".", "config_entry", "=", "config_entry" ]
[ 88, 4 ]
[ 90, 40 ]
python
en
['en', 'en', 'en']
True
AccuWeatherOptionsFlowHandler.async_step_init
(self, user_input=None)
Manage the options.
Manage the options.
async def async_step_init(self, user_input=None): """Manage the options.""" return await self.async_step_user()
[ "async", "def", "async_step_init", "(", "self", ",", "user_input", "=", "None", ")", ":", "return", "await", "self", ".", "async_step_user", "(", ")" ]
[ 92, 4 ]
[ 94, 43 ]
python
en
['en', 'en', 'en']
True
AccuWeatherOptionsFlowHandler.async_step_user
(self, user_input=None)
Handle a flow initialized by the user.
Handle a flow initialized by the user.
async def async_step_user(self, user_input=None): """Handle a flow initialized by the user.""" if user_input is not None: return self.async_create_entry(title="", data=user_input) return self.async_show_form( step_id="user", data_schema=vol.Schema( { vol.Optional( CONF_FORECAST, default=self.config_entry.options.get(CONF_FORECAST, False), ): bool } ), )
[ "async", "def", "async_step_user", "(", "self", ",", "user_input", "=", "None", ")", ":", "if", "user_input", "is", "not", "None", ":", "return", "self", ".", "async_create_entry", "(", "title", "=", "\"\"", ",", "data", "=", "user_input", ")", "return", "self", ".", "async_show_form", "(", "step_id", "=", "\"user\"", ",", "data_schema", "=", "vol", ".", "Schema", "(", "{", "vol", ".", "Optional", "(", "CONF_FORECAST", ",", "default", "=", "self", ".", "config_entry", ".", "options", ".", "get", "(", "CONF_FORECAST", ",", "False", ")", ",", ")", ":", "bool", "}", ")", ",", ")" ]
[ 96, 4 ]
[ 111, 9 ]
python
en
['en', 'en', 'en']
True
test_water_heater_create_sensors
(hass)
Test creation of water heater.
Test creation of water heater.
async def test_water_heater_create_sensors(hass): """Test creation of water heater.""" await async_init_integration(hass) state = hass.states.get("water_heater.water_heater") assert state.state == "auto" expected_attributes = { "current_temperature": None, "friendly_name": "Water Heater", "max_temp": 31.0, "min_temp": 16.0, "operation_list": ["auto", "heat", "off"], "operation_mode": "auto", "supported_features": 3, "target_temp_high": None, "target_temp_low": None, "temperature": 65.0, } # Only test for a subset of attributes in case # HA changes the implementation and a new one appears assert all(item in state.attributes.items() for item in expected_attributes.items()) state = hass.states.get("water_heater.second_water_heater") assert state.state == "heat" expected_attributes = { "current_temperature": None, "friendly_name": "Second Water Heater", "max_temp": 31.0, "min_temp": 16.0, "operation_list": ["auto", "heat", "off"], "operation_mode": "heat", "supported_features": 3, "target_temp_high": None, "target_temp_low": None, "temperature": 30.0, } # Only test for a subset of attributes in case # HA changes the implementation and a new one appears assert all(item in state.attributes.items() for item in expected_attributes.items())
[ "async", "def", "test_water_heater_create_sensors", "(", "hass", ")", ":", "await", "async_init_integration", "(", "hass", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"water_heater.water_heater\"", ")", "assert", "state", ".", "state", "==", "\"auto\"", "expected_attributes", "=", "{", "\"current_temperature\"", ":", "None", ",", "\"friendly_name\"", ":", "\"Water Heater\"", ",", "\"max_temp\"", ":", "31.0", ",", "\"min_temp\"", ":", "16.0", ",", "\"operation_list\"", ":", "[", "\"auto\"", ",", "\"heat\"", ",", "\"off\"", "]", ",", "\"operation_mode\"", ":", "\"auto\"", ",", "\"supported_features\"", ":", "3", ",", "\"target_temp_high\"", ":", "None", ",", "\"target_temp_low\"", ":", "None", ",", "\"temperature\"", ":", "65.0", ",", "}", "# Only test for a subset of attributes in case", "# HA changes the implementation and a new one appears", "assert", "all", "(", "item", "in", "state", ".", "attributes", ".", "items", "(", ")", "for", "item", "in", "expected_attributes", ".", "items", "(", ")", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"water_heater.second_water_heater\"", ")", "assert", "state", ".", "state", "==", "\"heat\"", "expected_attributes", "=", "{", "\"current_temperature\"", ":", "None", ",", "\"friendly_name\"", ":", "\"Second Water Heater\"", ",", "\"max_temp\"", ":", "31.0", ",", "\"min_temp\"", ":", "16.0", ",", "\"operation_list\"", ":", "[", "\"auto\"", ",", "\"heat\"", ",", "\"off\"", "]", ",", "\"operation_mode\"", ":", "\"heat\"", ",", "\"supported_features\"", ":", "3", ",", "\"target_temp_high\"", ":", "None", ",", "\"target_temp_low\"", ":", "None", ",", "\"temperature\"", ":", "30.0", ",", "}", "# Only test for a subset of attributes in case", "# HA changes the implementation and a new one appears", "assert", "all", "(", "item", "in", "state", ".", "attributes", ".", "items", "(", ")", "for", "item", "in", "expected_attributes", ".", "items", "(", ")", ")" ]
[ 5, 0 ]
[ 46, 88 ]
python
en
['en', 'en', 'en']
True
async_set_txt
(hass, txt)
Set the txt record. Pass in None to remove it. This is a legacy helper method. Do not use it for new tests.
Set the txt record. Pass in None to remove it.
async def async_set_txt(hass, txt): """Set the txt record. Pass in None to remove it. This is a legacy helper method. Do not use it for new tests. """ await hass.services.async_call( duckdns.DOMAIN, duckdns.SERVICE_SET_TXT, {duckdns.ATTR_TXT: txt}, blocking=True )
[ "async", "def", "async_set_txt", "(", "hass", ",", "txt", ")", ":", "await", "hass", ".", "services", ".", "async_call", "(", "duckdns", ".", "DOMAIN", ",", "duckdns", ".", "SERVICE_SET_TXT", ",", "{", "duckdns", ".", "ATTR_TXT", ":", "txt", "}", ",", "blocking", "=", "True", ")" ]
[ 21, 0 ]
[ 28, 5 ]
python
en
['en', 'en', 'en']
True
setup_duckdns
(hass, aioclient_mock)
Fixture that sets up DuckDNS.
Fixture that sets up DuckDNS.
def setup_duckdns(hass, aioclient_mock): """Fixture that sets up DuckDNS.""" aioclient_mock.get( duckdns.UPDATE_URL, params={"domains": DOMAIN, "token": TOKEN}, text="OK" ) hass.loop.run_until_complete( async_setup_component( hass, duckdns.DOMAIN, {"duckdns": {"domain": DOMAIN, "access_token": TOKEN}} ) )
[ "def", "setup_duckdns", "(", "hass", ",", "aioclient_mock", ")", ":", "aioclient_mock", ".", "get", "(", "duckdns", ".", "UPDATE_URL", ",", "params", "=", "{", "\"domains\"", ":", "DOMAIN", ",", "\"token\"", ":", "TOKEN", "}", ",", "text", "=", "\"OK\"", ")", "hass", ".", "loop", ".", "run_until_complete", "(", "async_setup_component", "(", "hass", ",", "duckdns", ".", "DOMAIN", ",", "{", "\"duckdns\"", ":", "{", "\"domain\"", ":", "DOMAIN", ",", "\"access_token\"", ":", "TOKEN", "}", "}", ")", ")" ]
[ 32, 0 ]
[ 42, 5 ]
python
en
['en', 'ca', 'en']
True
test_setup
(hass, aioclient_mock)
Test setup works if update passes.
Test setup works if update passes.
async def test_setup(hass, aioclient_mock): """Test setup works if update passes.""" aioclient_mock.get( duckdns.UPDATE_URL, params={"domains": DOMAIN, "token": TOKEN}, text="OK" ) result = await async_setup_component( hass, duckdns.DOMAIN, {"duckdns": {"domain": DOMAIN, "access_token": TOKEN}} ) await hass.async_block_till_done() assert result assert aioclient_mock.call_count == 1 async_fire_time_changed(hass, utcnow() + timedelta(minutes=5)) await hass.async_block_till_done() assert aioclient_mock.call_count == 2
[ "async", "def", "test_setup", "(", "hass", ",", "aioclient_mock", ")", ":", "aioclient_mock", ".", "get", "(", "duckdns", ".", "UPDATE_URL", ",", "params", "=", "{", "\"domains\"", ":", "DOMAIN", ",", "\"token\"", ":", "TOKEN", "}", ",", "text", "=", "\"OK\"", ")", "result", "=", "await", "async_setup_component", "(", "hass", ",", "duckdns", ".", "DOMAIN", ",", "{", "\"duckdns\"", ":", "{", "\"domain\"", ":", "DOMAIN", ",", "\"access_token\"", ":", "TOKEN", "}", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "result", "assert", "aioclient_mock", ".", "call_count", "==", "1", "async_fire_time_changed", "(", "hass", ",", "utcnow", "(", ")", "+", "timedelta", "(", "minutes", "=", "5", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "aioclient_mock", ".", "call_count", "==", "2" ]
[ 45, 0 ]
[ 62, 41 ]
python
en
['en', 'en', 'en']
True
test_setup_backoff
(hass, aioclient_mock)
Test setup fails if first update fails.
Test setup fails if first update fails.
async def test_setup_backoff(hass, aioclient_mock): """Test setup fails if first update fails.""" aioclient_mock.get( duckdns.UPDATE_URL, params={"domains": DOMAIN, "token": TOKEN}, text="KO" ) result = await async_setup_component( hass, duckdns.DOMAIN, {"duckdns": {"domain": DOMAIN, "access_token": TOKEN}} ) assert result await hass.async_block_till_done() assert aioclient_mock.call_count == 1 # Copy of the DuckDNS intervals from duckdns/__init__.py intervals = ( INTERVAL, timedelta(minutes=1), timedelta(minutes=5), timedelta(minutes=15), timedelta(minutes=30), ) tme = utcnow() await hass.async_block_till_done() _LOGGER.debug("Backoff...") for idx in range(1, len(intervals)): tme += intervals[idx] async_fire_time_changed(hass, tme) await hass.async_block_till_done() assert aioclient_mock.call_count == idx + 1
[ "async", "def", "test_setup_backoff", "(", "hass", ",", "aioclient_mock", ")", ":", "aioclient_mock", ".", "get", "(", "duckdns", ".", "UPDATE_URL", ",", "params", "=", "{", "\"domains\"", ":", "DOMAIN", ",", "\"token\"", ":", "TOKEN", "}", ",", "text", "=", "\"KO\"", ")", "result", "=", "await", "async_setup_component", "(", "hass", ",", "duckdns", ".", "DOMAIN", ",", "{", "\"duckdns\"", ":", "{", "\"domain\"", ":", "DOMAIN", ",", "\"access_token\"", ":", "TOKEN", "}", "}", ")", "assert", "result", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "aioclient_mock", ".", "call_count", "==", "1", "# Copy of the DuckDNS intervals from duckdns/__init__.py", "intervals", "=", "(", "INTERVAL", ",", "timedelta", "(", "minutes", "=", "1", ")", ",", "timedelta", "(", "minutes", "=", "5", ")", ",", "timedelta", "(", "minutes", "=", "15", ")", ",", "timedelta", "(", "minutes", "=", "30", ")", ",", ")", "tme", "=", "utcnow", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "_LOGGER", ".", "debug", "(", "\"Backoff...\"", ")", "for", "idx", "in", "range", "(", "1", ",", "len", "(", "intervals", ")", ")", ":", "tme", "+=", "intervals", "[", "idx", "]", "async_fire_time_changed", "(", "hass", ",", "tme", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "aioclient_mock", ".", "call_count", "==", "idx", "+", "1" ]
[ 65, 0 ]
[ 95, 51 ]
python
en
['ms', 'lb', 'en']
False
test_service_set_txt
(hass, aioclient_mock, setup_duckdns)
Test set txt service call.
Test set txt service call.
async def test_service_set_txt(hass, aioclient_mock, setup_duckdns): """Test set txt service call.""" # Empty the fixture mock requests aioclient_mock.clear_requests() aioclient_mock.get( duckdns.UPDATE_URL, params={"domains": DOMAIN, "token": TOKEN, "txt": "some-txt"}, text="OK", ) assert aioclient_mock.call_count == 0 await async_set_txt(hass, "some-txt") assert aioclient_mock.call_count == 1
[ "async", "def", "test_service_set_txt", "(", "hass", ",", "aioclient_mock", ",", "setup_duckdns", ")", ":", "# Empty the fixture mock requests", "aioclient_mock", ".", "clear_requests", "(", ")", "aioclient_mock", ".", "get", "(", "duckdns", ".", "UPDATE_URL", ",", "params", "=", "{", "\"domains\"", ":", "DOMAIN", ",", "\"token\"", ":", "TOKEN", ",", "\"txt\"", ":", "\"some-txt\"", "}", ",", "text", "=", "\"OK\"", ",", ")", "assert", "aioclient_mock", ".", "call_count", "==", "0", "await", "async_set_txt", "(", "hass", ",", "\"some-txt\"", ")", "assert", "aioclient_mock", ".", "call_count", "==", "1" ]
[ 98, 0 ]
[ 111, 41 ]
python
en
['en', 'lb', 'en']
True
test_service_clear_txt
(hass, aioclient_mock, setup_duckdns)
Test clear txt service call.
Test clear txt service call.
async def test_service_clear_txt(hass, aioclient_mock, setup_duckdns): """Test clear txt service call.""" # Empty the fixture mock requests aioclient_mock.clear_requests() aioclient_mock.get( duckdns.UPDATE_URL, params={"domains": DOMAIN, "token": TOKEN, "txt": "", "clear": "true"}, text="OK", ) assert aioclient_mock.call_count == 0 await async_set_txt(hass, None) assert aioclient_mock.call_count == 1
[ "async", "def", "test_service_clear_txt", "(", "hass", ",", "aioclient_mock", ",", "setup_duckdns", ")", ":", "# Empty the fixture mock requests", "aioclient_mock", ".", "clear_requests", "(", ")", "aioclient_mock", ".", "get", "(", "duckdns", ".", "UPDATE_URL", ",", "params", "=", "{", "\"domains\"", ":", "DOMAIN", ",", "\"token\"", ":", "TOKEN", ",", "\"txt\"", ":", "\"\"", ",", "\"clear\"", ":", "\"true\"", "}", ",", "text", "=", "\"OK\"", ",", ")", "assert", "aioclient_mock", ".", "call_count", "==", "0", "await", "async_set_txt", "(", "hass", ",", "None", ")", "assert", "aioclient_mock", ".", "call_count", "==", "1" ]
[ 114, 0 ]
[ 127, 41 ]
python
en
['en', 'en', 'en']
True
test_async_track_time_interval_backoff
(hass)
Test setup fails if first update fails.
Test setup fails if first update fails.
async def test_async_track_time_interval_backoff(hass): """Test setup fails if first update fails.""" ret_val = False call_count = 0 tme = None async def _return(now): nonlocal call_count, ret_val, tme if tme is None: tme = now call_count += 1 return ret_val intervals = ( INTERVAL, INTERVAL * 2, INTERVAL * 5, INTERVAL * 9, INTERVAL * 10, INTERVAL * 11, INTERVAL * 12, ) async_track_time_interval_backoff(hass, _return, intervals) await hass.async_block_till_done() assert call_count == 1 _LOGGER.debug("Backoff...") for idx in range(1, len(intervals)): tme += intervals[idx] async_fire_time_changed(hass, tme + timedelta(seconds=0.1)) await hass.async_block_till_done() assert call_count == idx + 1 _LOGGER.debug("Max backoff reached - intervals[-1]") for _idx in range(1, 10): tme += intervals[-1] async_fire_time_changed(hass, tme + timedelta(seconds=0.1)) await hass.async_block_till_done() assert call_count == idx + 1 + _idx _LOGGER.debug("Reset backoff") call_count = 0 ret_val = True tme += intervals[-1] async_fire_time_changed(hass, tme + timedelta(seconds=0.1)) await hass.async_block_till_done() assert call_count == 1 _LOGGER.debug("No backoff - intervals[0]") for _idx in range(2, 10): tme += intervals[0] async_fire_time_changed(hass, tme + timedelta(seconds=0.1)) await hass.async_block_till_done() assert call_count == _idx
[ "async", "def", "test_async_track_time_interval_backoff", "(", "hass", ")", ":", "ret_val", "=", "False", "call_count", "=", "0", "tme", "=", "None", "async", "def", "_return", "(", "now", ")", ":", "nonlocal", "call_count", ",", "ret_val", ",", "tme", "if", "tme", "is", "None", ":", "tme", "=", "now", "call_count", "+=", "1", "return", "ret_val", "intervals", "=", "(", "INTERVAL", ",", "INTERVAL", "*", "2", ",", "INTERVAL", "*", "5", ",", "INTERVAL", "*", "9", ",", "INTERVAL", "*", "10", ",", "INTERVAL", "*", "11", ",", "INTERVAL", "*", "12", ",", ")", "async_track_time_interval_backoff", "(", "hass", ",", "_return", ",", "intervals", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "call_count", "==", "1", "_LOGGER", ".", "debug", "(", "\"Backoff...\"", ")", "for", "idx", "in", "range", "(", "1", ",", "len", "(", "intervals", ")", ")", ":", "tme", "+=", "intervals", "[", "idx", "]", "async_fire_time_changed", "(", "hass", ",", "tme", "+", "timedelta", "(", "seconds", "=", "0.1", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "call_count", "==", "idx", "+", "1", "_LOGGER", ".", "debug", "(", "\"Max backoff reached - intervals[-1]\"", ")", "for", "_idx", "in", "range", "(", "1", ",", "10", ")", ":", "tme", "+=", "intervals", "[", "-", "1", "]", "async_fire_time_changed", "(", "hass", ",", "tme", "+", "timedelta", "(", "seconds", "=", "0.1", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "call_count", "==", "idx", "+", "1", "+", "_idx", "_LOGGER", ".", "debug", "(", "\"Reset backoff\"", ")", "call_count", "=", "0", "ret_val", "=", "True", "tme", "+=", "intervals", "[", "-", "1", "]", "async_fire_time_changed", "(", "hass", ",", "tme", "+", "timedelta", "(", "seconds", "=", "0.1", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "call_count", "==", "1", "_LOGGER", ".", "debug", "(", "\"No backoff - intervals[0]\"", ")", "for", "_idx", "in", "range", "(", "2", ",", "10", ")", ":", "tme", "+=", "intervals", "[", "0", "]", "async_fire_time_changed", "(", "hass", ",", "tme", "+", "timedelta", "(", "seconds", "=", "0.1", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "call_count", "==", "_idx" ]
[ 130, 0 ]
[ 188, 33 ]
python
en
['ms', 'lb', 'en']
False
setup_platform
(hass, config, add_entities, discovery_info=None)
Set up the ZoneMinder switch platform.
Set up the ZoneMinder switch platform.
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the ZoneMinder switch platform.""" on_state = MonitorState(config.get(CONF_COMMAND_ON)) off_state = MonitorState(config.get(CONF_COMMAND_OFF)) switches = [] for zm_client in hass.data[ZONEMINDER_DOMAIN].values(): monitors = zm_client.get_monitors() if not monitors: _LOGGER.warning("Could not fetch monitors from ZoneMinder") return for monitor in monitors: switches.append(ZMSwitchMonitors(monitor, on_state, off_state)) add_entities(switches)
[ "def", "setup_platform", "(", "hass", ",", "config", ",", "add_entities", ",", "discovery_info", "=", "None", ")", ":", "on_state", "=", "MonitorState", "(", "config", ".", "get", "(", "CONF_COMMAND_ON", ")", ")", "off_state", "=", "MonitorState", "(", "config", ".", "get", "(", "CONF_COMMAND_OFF", ")", ")", "switches", "=", "[", "]", "for", "zm_client", "in", "hass", ".", "data", "[", "ZONEMINDER_DOMAIN", "]", ".", "values", "(", ")", ":", "monitors", "=", "zm_client", ".", "get_monitors", "(", ")", "if", "not", "monitors", ":", "_LOGGER", ".", "warning", "(", "\"Could not fetch monitors from ZoneMinder\"", ")", "return", "for", "monitor", "in", "monitors", ":", "switches", ".", "append", "(", "ZMSwitchMonitors", "(", "monitor", ",", "on_state", ",", "off_state", ")", ")", "add_entities", "(", "switches", ")" ]
[ 22, 0 ]
[ 37, 26 ]
python
en
['en', 'de', 'en']
True
ZMSwitchMonitors.__init__
(self, monitor, on_state, off_state)
Initialize the switch.
Initialize the switch.
def __init__(self, monitor, on_state, off_state): """Initialize the switch.""" self._monitor = monitor self._on_state = on_state self._off_state = off_state self._state = None
[ "def", "__init__", "(", "self", ",", "monitor", ",", "on_state", ",", "off_state", ")", ":", "self", ".", "_monitor", "=", "monitor", "self", ".", "_on_state", "=", "on_state", "self", ".", "_off_state", "=", "off_state", "self", ".", "_state", "=", "None" ]
[ 45, 4 ]
[ 50, 26 ]
python
en
['en', 'en', 'en']
True
ZMSwitchMonitors.name
(self)
Return the name of the switch.
Return the name of the switch.
def name(self): """Return the name of the switch.""" return f"{self._monitor.name} State"
[ "def", "name", "(", "self", ")", ":", "return", "f\"{self._monitor.name} State\"" ]
[ 53, 4 ]
[ 55, 44 ]
python
en
['en', 'en', 'en']
True
ZMSwitchMonitors.update
(self)
Update the switch value.
Update the switch value.
def update(self): """Update the switch value.""" self._state = self._monitor.function == self._on_state
[ "def", "update", "(", "self", ")", ":", "self", ".", "_state", "=", "self", ".", "_monitor", ".", "function", "==", "self", ".", "_on_state" ]
[ 57, 4 ]
[ 59, 62 ]
python
en
['en', 'en', 'en']
True
ZMSwitchMonitors.is_on
(self)
Return True if entity is on.
Return True if entity is on.
def is_on(self): """Return True if entity is on.""" return self._state
[ "def", "is_on", "(", "self", ")", ":", "return", "self", ".", "_state" ]
[ 62, 4 ]
[ 64, 26 ]
python
en
['en', 'cy', 'en']
True
ZMSwitchMonitors.turn_on
(self, **kwargs)
Turn the entity on.
Turn the entity on.
def turn_on(self, **kwargs): """Turn the entity on.""" self._monitor.function = self._on_state
[ "def", "turn_on", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_monitor", ".", "function", "=", "self", ".", "_on_state" ]
[ 66, 4 ]
[ 68, 47 ]
python
en
['en', 'en', 'en']
True
ZMSwitchMonitors.turn_off
(self, **kwargs)
Turn the entity off.
Turn the entity off.
def turn_off(self, **kwargs): """Turn the entity off.""" self._monitor.function = self._off_state
[ "def", "turn_off", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_monitor", ".", "function", "=", "self", ".", "_off_state" ]
[ 70, 4 ]
[ 72, 48 ]
python
en
['en', 'en', 'en']
True
help_test_availability_when_connection_lost
( hass, mqtt_client_mock, mqtt_mock, domain, config, sensor_config=None, entity_id="test", )
Test availability after MQTT disconnection. This is a test helper for the TasmotaAvailability mixin.
Test availability after MQTT disconnection.
async def help_test_availability_when_connection_lost( hass, mqtt_client_mock, mqtt_mock, domain, config, sensor_config=None, entity_id="test", ): """Test availability after MQTT disconnection. This is a test helper for the TasmotaAvailability mixin. """ async_fire_mqtt_message( hass, f"{DEFAULT_PREFIX}/{config[CONF_MAC]}/config", json.dumps(config), ) await hass.async_block_till_done() if sensor_config: async_fire_mqtt_message( hass, f"{DEFAULT_PREFIX}/{config[CONF_MAC]}/sensors", json.dumps(sensor_config), ) await hass.async_block_till_done() # Device online async_fire_mqtt_message( hass, get_topic_tele_will(config), config_get_state_online(config), ) state = hass.states.get(f"{domain}.{entity_id}") assert state.state != STATE_UNAVAILABLE # Disconnected from MQTT server -> state changed to unavailable mqtt_mock.connected = False await hass.async_add_executor_job(mqtt_client_mock.on_disconnect, None, None, 0) await hass.async_block_till_done() await hass.async_block_till_done() await hass.async_block_till_done() state = hass.states.get(f"{domain}.{entity_id}") assert state.state == STATE_UNAVAILABLE # Reconnected to MQTT server -> state still unavailable mqtt_mock.connected = True await hass.async_add_executor_job(mqtt_client_mock.on_connect, None, None, None, 0) await hass.async_block_till_done() await hass.async_block_till_done() await hass.async_block_till_done() state = hass.states.get(f"{domain}.{entity_id}") assert state.state == STATE_UNAVAILABLE # Receive LWT again async_fire_mqtt_message( hass, get_topic_tele_will(config), config_get_state_online(config), ) state = hass.states.get(f"{domain}.{entity_id}") assert state.state != STATE_UNAVAILABLE
[ "async", "def", "help_test_availability_when_connection_lost", "(", "hass", ",", "mqtt_client_mock", ",", "mqtt_mock", ",", "domain", ",", "config", ",", "sensor_config", "=", "None", ",", "entity_id", "=", "\"test\"", ",", ")", ":", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{config[CONF_MAC]}/config\"", ",", "json", ".", "dumps", "(", "config", ")", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "if", "sensor_config", ":", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{config[CONF_MAC]}/sensors\"", ",", "json", ".", "dumps", "(", "sensor_config", ")", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "# Device online", "async_fire_mqtt_message", "(", "hass", ",", "get_topic_tele_will", "(", "config", ")", ",", "config_get_state_online", "(", "config", ")", ",", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "f\"{domain}.{entity_id}\"", ")", "assert", "state", ".", "state", "!=", "STATE_UNAVAILABLE", "# Disconnected from MQTT server -> state changed to unavailable", "mqtt_mock", ".", "connected", "=", "False", "await", "hass", ".", "async_add_executor_job", "(", "mqtt_client_mock", ".", "on_disconnect", ",", "None", ",", "None", ",", "0", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "f\"{domain}.{entity_id}\"", ")", "assert", "state", ".", "state", "==", "STATE_UNAVAILABLE", "# Reconnected to MQTT server -> state still unavailable", "mqtt_mock", ".", "connected", "=", "True", "await", "hass", ".", "async_add_executor_job", "(", "mqtt_client_mock", ".", "on_connect", ",", "None", ",", "None", ",", "None", ",", "0", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "f\"{domain}.{entity_id}\"", ")", "assert", "state", ".", "state", "==", "STATE_UNAVAILABLE", "# Receive LWT again", "async_fire_mqtt_message", "(", "hass", ",", "get_topic_tele_will", "(", "config", ")", ",", "config_get_state_online", "(", "config", ")", ",", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "f\"{domain}.{entity_id}\"", ")", "assert", "state", ".", "state", "!=", "STATE_UNAVAILABLE" ]
[ 98, 0 ]
[ 160, 43 ]
python
en
['en', 'en', 'en']
True
help_test_availability
( hass, mqtt_mock, domain, config, sensor_config=None, entity_id="test", )
Test availability. This is a test helper for the TasmotaAvailability mixin.
Test availability.
async def help_test_availability( hass, mqtt_mock, domain, config, sensor_config=None, entity_id="test", ): """Test availability. This is a test helper for the TasmotaAvailability mixin. """ async_fire_mqtt_message( hass, f"{DEFAULT_PREFIX}/{config[CONF_MAC]}/config", json.dumps(config), ) await hass.async_block_till_done() if sensor_config: async_fire_mqtt_message( hass, f"{DEFAULT_PREFIX}/{config[CONF_MAC]}/sensors", json.dumps(sensor_config), ) await hass.async_block_till_done() state = hass.states.get(f"{domain}.{entity_id}") assert state.state == STATE_UNAVAILABLE async_fire_mqtt_message( hass, get_topic_tele_will(config), config_get_state_online(config), ) state = hass.states.get(f"{domain}.{entity_id}") assert state.state != STATE_UNAVAILABLE async_fire_mqtt_message( hass, get_topic_tele_will(config), config_get_state_offline(config), ) state = hass.states.get(f"{domain}.{entity_id}") assert state.state == STATE_UNAVAILABLE
[ "async", "def", "help_test_availability", "(", "hass", ",", "mqtt_mock", ",", "domain", ",", "config", ",", "sensor_config", "=", "None", ",", "entity_id", "=", "\"test\"", ",", ")", ":", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{config[CONF_MAC]}/config\"", ",", "json", ".", "dumps", "(", "config", ")", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "if", "sensor_config", ":", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{config[CONF_MAC]}/sensors\"", ",", "json", ".", "dumps", "(", "sensor_config", ")", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "f\"{domain}.{entity_id}\"", ")", "assert", "state", ".", "state", "==", "STATE_UNAVAILABLE", "async_fire_mqtt_message", "(", "hass", ",", "get_topic_tele_will", "(", "config", ")", ",", "config_get_state_online", "(", "config", ")", ",", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "f\"{domain}.{entity_id}\"", ")", "assert", "state", ".", "state", "!=", "STATE_UNAVAILABLE", "async_fire_mqtt_message", "(", "hass", ",", "get_topic_tele_will", "(", "config", ")", ",", "config_get_state_offline", "(", "config", ")", ",", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "f\"{domain}.{entity_id}\"", ")", "assert", "state", ".", "state", "==", "STATE_UNAVAILABLE" ]
[ 163, 0 ]
[ 208, 43 ]
python
en
['fr', 'ga', 'en']
False
help_test_availability_discovery_update
( hass, mqtt_mock, domain, config, sensor_config=None, entity_id="test", )
Test update of discovered TasmotaAvailability. This is a test helper for the TasmotaAvailability mixin.
Test update of discovered TasmotaAvailability.
async def help_test_availability_discovery_update( hass, mqtt_mock, domain, config, sensor_config=None, entity_id="test", ): """Test update of discovered TasmotaAvailability. This is a test helper for the TasmotaAvailability mixin. """ # customize availability topic config1 = copy.deepcopy(config) config1[CONF_PREFIX][PREFIX_TELE] = "tele1" config1[CONF_OFFLINE] = "offline1" config1[CONF_ONLINE] = "online1" config2 = copy.deepcopy(config) config2[CONF_PREFIX][PREFIX_TELE] = "tele2" config2[CONF_OFFLINE] = "offline2" config2[CONF_ONLINE] = "online2" data1 = json.dumps(config1) data2 = json.dumps(config2) availability_topic1 = get_topic_tele_will(config1) availability_topic2 = get_topic_tele_will(config2) assert availability_topic1 != availability_topic2 offline1 = config_get_state_offline(config1) offline2 = config_get_state_offline(config2) assert offline1 != offline2 online1 = config_get_state_online(config1) online2 = config_get_state_online(config2) assert online1 != online2 async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{config1[CONF_MAC]}/config", data1) await hass.async_block_till_done() if sensor_config: async_fire_mqtt_message( hass, f"{DEFAULT_PREFIX}/{config[CONF_MAC]}/sensors", json.dumps(sensor_config), ) await hass.async_block_till_done() state = hass.states.get(f"{domain}.{entity_id}") assert state.state == STATE_UNAVAILABLE async_fire_mqtt_message(hass, availability_topic1, online1) state = hass.states.get(f"{domain}.{entity_id}") assert state.state != STATE_UNAVAILABLE async_fire_mqtt_message(hass, availability_topic1, offline1) state = hass.states.get(f"{domain}.{entity_id}") assert state.state == STATE_UNAVAILABLE # Change availability settings async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{config2[CONF_MAC]}/config", data2) await hass.async_block_till_done() # Verify we are no longer subscribing to the old topic or payload async_fire_mqtt_message(hass, availability_topic1, online1) async_fire_mqtt_message(hass, availability_topic1, online2) async_fire_mqtt_message(hass, availability_topic2, online1) state = hass.states.get(f"{domain}.{entity_id}") assert state.state == STATE_UNAVAILABLE # Verify we are subscribing to the new topic async_fire_mqtt_message(hass, availability_topic2, online2) state = hass.states.get(f"{domain}.{entity_id}") assert state.state != STATE_UNAVAILABLE
[ "async", "def", "help_test_availability_discovery_update", "(", "hass", ",", "mqtt_mock", ",", "domain", ",", "config", ",", "sensor_config", "=", "None", ",", "entity_id", "=", "\"test\"", ",", ")", ":", "# customize availability topic", "config1", "=", "copy", ".", "deepcopy", "(", "config", ")", "config1", "[", "CONF_PREFIX", "]", "[", "PREFIX_TELE", "]", "=", "\"tele1\"", "config1", "[", "CONF_OFFLINE", "]", "=", "\"offline1\"", "config1", "[", "CONF_ONLINE", "]", "=", "\"online1\"", "config2", "=", "copy", ".", "deepcopy", "(", "config", ")", "config2", "[", "CONF_PREFIX", "]", "[", "PREFIX_TELE", "]", "=", "\"tele2\"", "config2", "[", "CONF_OFFLINE", "]", "=", "\"offline2\"", "config2", "[", "CONF_ONLINE", "]", "=", "\"online2\"", "data1", "=", "json", ".", "dumps", "(", "config1", ")", "data2", "=", "json", ".", "dumps", "(", "config2", ")", "availability_topic1", "=", "get_topic_tele_will", "(", "config1", ")", "availability_topic2", "=", "get_topic_tele_will", "(", "config2", ")", "assert", "availability_topic1", "!=", "availability_topic2", "offline1", "=", "config_get_state_offline", "(", "config1", ")", "offline2", "=", "config_get_state_offline", "(", "config2", ")", "assert", "offline1", "!=", "offline2", "online1", "=", "config_get_state_online", "(", "config1", ")", "online2", "=", "config_get_state_online", "(", "config2", ")", "assert", "online1", "!=", "online2", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{config1[CONF_MAC]}/config\"", ",", "data1", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "if", "sensor_config", ":", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{config[CONF_MAC]}/sensors\"", ",", "json", ".", "dumps", "(", "sensor_config", ")", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "f\"{domain}.{entity_id}\"", ")", "assert", "state", ".", "state", "==", "STATE_UNAVAILABLE", "async_fire_mqtt_message", "(", "hass", ",", "availability_topic1", ",", "online1", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "f\"{domain}.{entity_id}\"", ")", "assert", "state", ".", "state", "!=", "STATE_UNAVAILABLE", "async_fire_mqtt_message", "(", "hass", ",", "availability_topic1", ",", "offline1", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "f\"{domain}.{entity_id}\"", ")", "assert", "state", ".", "state", "==", "STATE_UNAVAILABLE", "# Change availability settings", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{config2[CONF_MAC]}/config\"", ",", "data2", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "# Verify we are no longer subscribing to the old topic or payload", "async_fire_mqtt_message", "(", "hass", ",", "availability_topic1", ",", "online1", ")", "async_fire_mqtt_message", "(", "hass", ",", "availability_topic1", ",", "online2", ")", "async_fire_mqtt_message", "(", "hass", ",", "availability_topic2", ",", "online1", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "f\"{domain}.{entity_id}\"", ")", "assert", "state", ".", "state", "==", "STATE_UNAVAILABLE", "# Verify we are subscribing to the new topic", "async_fire_mqtt_message", "(", "hass", ",", "availability_topic2", ",", "online2", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "f\"{domain}.{entity_id}\"", ")", "assert", "state", ".", "state", "!=", "STATE_UNAVAILABLE" ]
[ 211, 0 ]
[ 280, 43 ]
python
en
['en', 'en', 'en']
True
help_test_availability_poll_state
( hass, mqtt_client_mock, mqtt_mock, domain, config, poll_topic, poll_payload, sensor_config=None, )
Test polling of state when device is available. This is a test helper for the TasmotaAvailability mixin.
Test polling of state when device is available.
async def help_test_availability_poll_state( hass, mqtt_client_mock, mqtt_mock, domain, config, poll_topic, poll_payload, sensor_config=None, ): """Test polling of state when device is available. This is a test helper for the TasmotaAvailability mixin. """ async_fire_mqtt_message( hass, f"{DEFAULT_PREFIX}/{config[CONF_MAC]}/config", json.dumps(config), ) await hass.async_block_till_done() if sensor_config: async_fire_mqtt_message( hass, f"{DEFAULT_PREFIX}/{config[CONF_MAC]}/sensors", json.dumps(sensor_config), ) await hass.async_block_till_done() mqtt_mock.async_publish.reset_mock() # Device online, verify poll for state async_fire_mqtt_message( hass, get_topic_tele_will(config), config_get_state_online(config), ) await hass.async_block_till_done() await hass.async_block_till_done() await hass.async_block_till_done() mqtt_mock.async_publish.assert_called_once_with(poll_topic, poll_payload, 0, False) mqtt_mock.async_publish.reset_mock() # Disconnected from MQTT server mqtt_mock.connected = False await hass.async_add_executor_job(mqtt_client_mock.on_disconnect, None, None, 0) await hass.async_block_till_done() await hass.async_block_till_done() await hass.async_block_till_done() assert not mqtt_mock.async_publish.called # Reconnected to MQTT server mqtt_mock.connected = True await hass.async_add_executor_job(mqtt_client_mock.on_connect, None, None, None, 0) await hass.async_block_till_done() await hass.async_block_till_done() await hass.async_block_till_done() assert not mqtt_mock.async_publish.called # Device online, verify poll for state async_fire_mqtt_message( hass, get_topic_tele_will(config), config_get_state_online(config), ) await hass.async_block_till_done() await hass.async_block_till_done() await hass.async_block_till_done() mqtt_mock.async_publish.assert_called_once_with(poll_topic, poll_payload, 0, False)
[ "async", "def", "help_test_availability_poll_state", "(", "hass", ",", "mqtt_client_mock", ",", "mqtt_mock", ",", "domain", ",", "config", ",", "poll_topic", ",", "poll_payload", ",", "sensor_config", "=", "None", ",", ")", ":", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{config[CONF_MAC]}/config\"", ",", "json", ".", "dumps", "(", "config", ")", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "if", "sensor_config", ":", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{config[CONF_MAC]}/sensors\"", ",", "json", ".", "dumps", "(", "sensor_config", ")", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "mqtt_mock", ".", "async_publish", ".", "reset_mock", "(", ")", "# Device online, verify poll for state", "async_fire_mqtt_message", "(", "hass", ",", "get_topic_tele_will", "(", "config", ")", ",", "config_get_state_online", "(", "config", ")", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "mqtt_mock", ".", "async_publish", ".", "assert_called_once_with", "(", "poll_topic", ",", "poll_payload", ",", "0", ",", "False", ")", "mqtt_mock", ".", "async_publish", ".", "reset_mock", "(", ")", "# Disconnected from MQTT server", "mqtt_mock", ".", "connected", "=", "False", "await", "hass", ".", "async_add_executor_job", "(", "mqtt_client_mock", ".", "on_disconnect", ",", "None", ",", "None", ",", "0", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "not", "mqtt_mock", ".", "async_publish", ".", "called", "# Reconnected to MQTT server", "mqtt_mock", ".", "connected", "=", "True", "await", "hass", ".", "async_add_executor_job", "(", "mqtt_client_mock", ".", "on_connect", ",", "None", ",", "None", ",", "None", ",", "0", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "not", "mqtt_mock", ".", "async_publish", ".", "called", "# Device online, verify poll for state", "async_fire_mqtt_message", "(", "hass", ",", "get_topic_tele_will", "(", "config", ")", ",", "config_get_state_online", "(", "config", ")", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "mqtt_mock", ".", "async_publish", ".", "assert_called_once_with", "(", "poll_topic", ",", "poll_payload", ",", "0", ",", "False", ")" ]
[ 283, 0 ]
[ 349, 87 ]
python
en
['en', 'en', 'en']
True
help_test_discovery_removal
( hass, mqtt_mock, caplog, domain, config1, config2, sensor_config1=None, sensor_config2=None, entity_id="test", name="Test", )
Test removal of discovered entity.
Test removal of discovered entity.
async def help_test_discovery_removal( hass, mqtt_mock, caplog, domain, config1, config2, sensor_config1=None, sensor_config2=None, entity_id="test", name="Test", ): """Test removal of discovered entity.""" device_reg = await hass.helpers.device_registry.async_get_registry() entity_reg = await hass.helpers.entity_registry.async_get_registry() data1 = json.dumps(config1) data2 = json.dumps(config2) assert config1[CONF_MAC] == config2[CONF_MAC] async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{config1[CONF_MAC]}/config", data1) await hass.async_block_till_done() if sensor_config1: async_fire_mqtt_message( hass, f"{DEFAULT_PREFIX}/{config1[CONF_MAC]}/sensors", json.dumps(sensor_config1), ) await hass.async_block_till_done() # Verify device and entity registry entries are created device_entry = device_reg.async_get_device(set(), {("mac", config1[CONF_MAC])}) assert device_entry is not None entity_entry = entity_reg.async_get(f"{domain}.{entity_id}") assert entity_entry is not None # Verify state is added state = hass.states.get(f"{domain}.{entity_id}") assert state is not None assert state.name == name async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{config2[CONF_MAC]}/config", data2) await hass.async_block_till_done() if sensor_config1: async_fire_mqtt_message( hass, f"{DEFAULT_PREFIX}/{config2[CONF_MAC]}/sensors", json.dumps(sensor_config2), ) await hass.async_block_till_done() # Verify entity registry entries are cleared device_entry = device_reg.async_get_device(set(), {("mac", config2[CONF_MAC])}) assert device_entry is not None entity_entry = entity_reg.async_get(f"{domain}.{entity_id}") assert entity_entry is None # Verify state is removed state = hass.states.get(f"{domain}.{entity_id}") assert state is None
[ "async", "def", "help_test_discovery_removal", "(", "hass", ",", "mqtt_mock", ",", "caplog", ",", "domain", ",", "config1", ",", "config2", ",", "sensor_config1", "=", "None", ",", "sensor_config2", "=", "None", ",", "entity_id", "=", "\"test\"", ",", "name", "=", "\"Test\"", ",", ")", ":", "device_reg", "=", "await", "hass", ".", "helpers", ".", "device_registry", ".", "async_get_registry", "(", ")", "entity_reg", "=", "await", "hass", ".", "helpers", ".", "entity_registry", ".", "async_get_registry", "(", ")", "data1", "=", "json", ".", "dumps", "(", "config1", ")", "data2", "=", "json", ".", "dumps", "(", "config2", ")", "assert", "config1", "[", "CONF_MAC", "]", "==", "config2", "[", "CONF_MAC", "]", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{config1[CONF_MAC]}/config\"", ",", "data1", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "if", "sensor_config1", ":", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{config1[CONF_MAC]}/sensors\"", ",", "json", ".", "dumps", "(", "sensor_config1", ")", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "# Verify device and entity registry entries are created", "device_entry", "=", "device_reg", ".", "async_get_device", "(", "set", "(", ")", ",", "{", "(", "\"mac\"", ",", "config1", "[", "CONF_MAC", "]", ")", "}", ")", "assert", "device_entry", "is", "not", "None", "entity_entry", "=", "entity_reg", ".", "async_get", "(", "f\"{domain}.{entity_id}\"", ")", "assert", "entity_entry", "is", "not", "None", "# Verify state is added", "state", "=", "hass", ".", "states", ".", "get", "(", "f\"{domain}.{entity_id}\"", ")", "assert", "state", "is", "not", "None", "assert", "state", ".", "name", "==", "name", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{config2[CONF_MAC]}/config\"", ",", "data2", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "if", "sensor_config1", ":", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{config2[CONF_MAC]}/sensors\"", ",", "json", ".", "dumps", "(", "sensor_config2", ")", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "# Verify entity registry entries are cleared", "device_entry", "=", "device_reg", ".", "async_get_device", "(", "set", "(", ")", ",", "{", "(", "\"mac\"", ",", "config2", "[", "CONF_MAC", "]", ")", "}", ")", "assert", "device_entry", "is", "not", "None", "entity_entry", "=", "entity_reg", ".", "async_get", "(", "f\"{domain}.{entity_id}\"", ")", "assert", "entity_entry", "is", "None", "# Verify state is removed", "state", "=", "hass", ".", "states", ".", "get", "(", "f\"{domain}.{entity_id}\"", ")", "assert", "state", "is", "None" ]
[ 352, 0 ]
[ 411, 24 ]
python
en
['en', 'en', 'en']
True
help_test_discovery_update_unchanged
( hass, mqtt_mock, caplog, domain, config, discovery_update, sensor_config=None, entity_id="test", name="Test", )
Test update of discovered component with and without changes. This is a test helper for the MqttDiscoveryUpdate mixin.
Test update of discovered component with and without changes.
async def help_test_discovery_update_unchanged( hass, mqtt_mock, caplog, domain, config, discovery_update, sensor_config=None, entity_id="test", name="Test", ): """Test update of discovered component with and without changes. This is a test helper for the MqttDiscoveryUpdate mixin. """ config1 = copy.deepcopy(config) config2 = copy.deepcopy(config) config2[CONF_PREFIX][PREFIX_CMND] = "cmnd2" config2[CONF_PREFIX][PREFIX_TELE] = "tele2" data1 = json.dumps(config1) data2 = json.dumps(config2) async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{config[CONF_MAC]}/config", data1) await hass.async_block_till_done() if sensor_config: async_fire_mqtt_message( hass, f"{DEFAULT_PREFIX}/{config[CONF_MAC]}/sensors", json.dumps(sensor_config), ) await hass.async_block_till_done() state = hass.states.get(f"{domain}.{entity_id}") assert state is not None assert state.name == name async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{config[CONF_MAC]}/config", data1) await hass.async_block_till_done() if sensor_config: async_fire_mqtt_message( hass, f"{DEFAULT_PREFIX}/{config[CONF_MAC]}/sensors", json.dumps(sensor_config), ) await hass.async_block_till_done() assert not discovery_update.called async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{config[CONF_MAC]}/config", data2) await hass.async_block_till_done() assert discovery_update.called
[ "async", "def", "help_test_discovery_update_unchanged", "(", "hass", ",", "mqtt_mock", ",", "caplog", ",", "domain", ",", "config", ",", "discovery_update", ",", "sensor_config", "=", "None", ",", "entity_id", "=", "\"test\"", ",", "name", "=", "\"Test\"", ",", ")", ":", "config1", "=", "copy", ".", "deepcopy", "(", "config", ")", "config2", "=", "copy", ".", "deepcopy", "(", "config", ")", "config2", "[", "CONF_PREFIX", "]", "[", "PREFIX_CMND", "]", "=", "\"cmnd2\"", "config2", "[", "CONF_PREFIX", "]", "[", "PREFIX_TELE", "]", "=", "\"tele2\"", "data1", "=", "json", ".", "dumps", "(", "config1", ")", "data2", "=", "json", ".", "dumps", "(", "config2", ")", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{config[CONF_MAC]}/config\"", ",", "data1", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "if", "sensor_config", ":", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{config[CONF_MAC]}/sensors\"", ",", "json", ".", "dumps", "(", "sensor_config", ")", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "f\"{domain}.{entity_id}\"", ")", "assert", "state", "is", "not", "None", "assert", "state", ".", "name", "==", "name", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{config[CONF_MAC]}/config\"", ",", "data1", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "if", "sensor_config", ":", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{config[CONF_MAC]}/sensors\"", ",", "json", ".", "dumps", "(", "sensor_config", ")", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "not", "discovery_update", ".", "called", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{config[CONF_MAC]}/config\"", ",", "data2", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "discovery_update", ".", "called" ]
[ 414, 0 ]
[ 465, 34 ]
python
en
['en', 'en', 'en']
True
help_test_discovery_device_remove
( hass, mqtt_mock, domain, unique_id, config, sensor_config=None )
Test domain entity is removed when device is removed.
Test domain entity is removed when device is removed.
async def help_test_discovery_device_remove( hass, mqtt_mock, domain, unique_id, config, sensor_config=None ): """Test domain entity is removed when device is removed.""" device_reg = await hass.helpers.device_registry.async_get_registry() entity_reg = await hass.helpers.entity_registry.async_get_registry() config = copy.deepcopy(config) data = json.dumps(config) async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{config[CONF_MAC]}/config", data) await hass.async_block_till_done() if sensor_config: async_fire_mqtt_message( hass, f"{DEFAULT_PREFIX}/{config[CONF_MAC]}/sensors", json.dumps(sensor_config), ) await hass.async_block_till_done() device = device_reg.async_get_device(set(), {("mac", config[CONF_MAC])}) assert device is not None assert entity_reg.async_get_entity_id(domain, "tasmota", unique_id) async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{config[CONF_MAC]}/config", "") await hass.async_block_till_done() device = device_reg.async_get_device(set(), {("mac", config[CONF_MAC])}) assert device is None assert not entity_reg.async_get_entity_id(domain, "tasmota", unique_id)
[ "async", "def", "help_test_discovery_device_remove", "(", "hass", ",", "mqtt_mock", ",", "domain", ",", "unique_id", ",", "config", ",", "sensor_config", "=", "None", ")", ":", "device_reg", "=", "await", "hass", ".", "helpers", ".", "device_registry", ".", "async_get_registry", "(", ")", "entity_reg", "=", "await", "hass", ".", "helpers", ".", "entity_registry", ".", "async_get_registry", "(", ")", "config", "=", "copy", ".", "deepcopy", "(", "config", ")", "data", "=", "json", ".", "dumps", "(", "config", ")", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{config[CONF_MAC]}/config\"", ",", "data", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "if", "sensor_config", ":", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{config[CONF_MAC]}/sensors\"", ",", "json", ".", "dumps", "(", "sensor_config", ")", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "device", "=", "device_reg", ".", "async_get_device", "(", "set", "(", ")", ",", "{", "(", "\"mac\"", ",", "config", "[", "CONF_MAC", "]", ")", "}", ")", "assert", "device", "is", "not", "None", "assert", "entity_reg", ".", "async_get_entity_id", "(", "domain", ",", "\"tasmota\"", ",", "unique_id", ")", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{config[CONF_MAC]}/config\"", ",", "\"\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "device", "=", "device_reg", ".", "async_get_device", "(", "set", "(", ")", ",", "{", "(", "\"mac\"", ",", "config", "[", "CONF_MAC", "]", ")", "}", ")", "assert", "device", "is", "None", "assert", "not", "entity_reg", ".", "async_get_entity_id", "(", "domain", ",", "\"tasmota\"", ",", "unique_id", ")" ]
[ 468, 0 ]
[ 497, 75 ]
python
en
['en', 'en', 'en']
True
help_test_entity_id_update_subscriptions
( hass, mqtt_mock, domain, config, topics=None, sensor_config=None, entity_id="test" )
Test MQTT subscriptions are managed when entity_id is updated.
Test MQTT subscriptions are managed when entity_id is updated.
async def help_test_entity_id_update_subscriptions( hass, mqtt_mock, domain, config, topics=None, sensor_config=None, entity_id="test" ): """Test MQTT subscriptions are managed when entity_id is updated.""" entity_reg = await hass.helpers.entity_registry.async_get_registry() config = copy.deepcopy(config) data = json.dumps(config) mqtt_mock.async_subscribe.reset_mock() async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{config[CONF_MAC]}/config", data) await hass.async_block_till_done() if sensor_config: async_fire_mqtt_message( hass, f"{DEFAULT_PREFIX}/{config[CONF_MAC]}/sensors", json.dumps(sensor_config), ) await hass.async_block_till_done() if not topics: topics = [get_topic_tele_state(config), get_topic_tele_will(config)] assert len(topics) > 0 state = hass.states.get(f"{domain}.{entity_id}") assert state is not None assert mqtt_mock.async_subscribe.call_count == len(topics) for topic in topics: mqtt_mock.async_subscribe.assert_any_call(topic, ANY, ANY, ANY) mqtt_mock.async_subscribe.reset_mock() entity_reg.async_update_entity( f"{domain}.{entity_id}", new_entity_id=f"{domain}.milk" ) await hass.async_block_till_done() state = hass.states.get(f"{domain}.{entity_id}") assert state is None state = hass.states.get(f"{domain}.milk") assert state is not None for topic in topics: mqtt_mock.async_subscribe.assert_any_call(topic, ANY, ANY, ANY)
[ "async", "def", "help_test_entity_id_update_subscriptions", "(", "hass", ",", "mqtt_mock", ",", "domain", ",", "config", ",", "topics", "=", "None", ",", "sensor_config", "=", "None", ",", "entity_id", "=", "\"test\"", ")", ":", "entity_reg", "=", "await", "hass", ".", "helpers", ".", "entity_registry", ".", "async_get_registry", "(", ")", "config", "=", "copy", ".", "deepcopy", "(", "config", ")", "data", "=", "json", ".", "dumps", "(", "config", ")", "mqtt_mock", ".", "async_subscribe", ".", "reset_mock", "(", ")", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{config[CONF_MAC]}/config\"", ",", "data", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "if", "sensor_config", ":", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{config[CONF_MAC]}/sensors\"", ",", "json", ".", "dumps", "(", "sensor_config", ")", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "if", "not", "topics", ":", "topics", "=", "[", "get_topic_tele_state", "(", "config", ")", ",", "get_topic_tele_will", "(", "config", ")", "]", "assert", "len", "(", "topics", ")", ">", "0", "state", "=", "hass", ".", "states", ".", "get", "(", "f\"{domain}.{entity_id}\"", ")", "assert", "state", "is", "not", "None", "assert", "mqtt_mock", ".", "async_subscribe", ".", "call_count", "==", "len", "(", "topics", ")", "for", "topic", "in", "topics", ":", "mqtt_mock", ".", "async_subscribe", ".", "assert_any_call", "(", "topic", ",", "ANY", ",", "ANY", ",", "ANY", ")", "mqtt_mock", ".", "async_subscribe", ".", "reset_mock", "(", ")", "entity_reg", ".", "async_update_entity", "(", "f\"{domain}.{entity_id}\"", ",", "new_entity_id", "=", "f\"{domain}.milk\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "f\"{domain}.{entity_id}\"", ")", "assert", "state", "is", "None", "state", "=", "hass", ".", "states", ".", "get", "(", "f\"{domain}.milk\"", ")", "assert", "state", "is", "not", "None", "for", "topic", "in", "topics", ":", "mqtt_mock", ".", "async_subscribe", ".", "assert_any_call", "(", "topic", ",", "ANY", ",", "ANY", ",", "ANY", ")" ]
[ 500, 0 ]
[ 543, 71 ]
python
en
['en', 'en', 'en']
True
help_test_entity_id_update_discovery_update
( hass, mqtt_mock, domain, config, sensor_config=None, entity_id="test" )
Test MQTT discovery update after entity_id is updated.
Test MQTT discovery update after entity_id is updated.
async def help_test_entity_id_update_discovery_update( hass, mqtt_mock, domain, config, sensor_config=None, entity_id="test" ): """Test MQTT discovery update after entity_id is updated.""" entity_reg = await hass.helpers.entity_registry.async_get_registry() config = copy.deepcopy(config) data = json.dumps(config) topic = get_topic_tele_will(config) async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{config[CONF_MAC]}/config", data) await hass.async_block_till_done() if sensor_config: async_fire_mqtt_message( hass, f"{DEFAULT_PREFIX}/{config[CONF_MAC]}/sensors", json.dumps(sensor_config), ) await hass.async_block_till_done() async_fire_mqtt_message(hass, topic, config_get_state_online(config)) state = hass.states.get(f"{domain}.{entity_id}") assert state.state != STATE_UNAVAILABLE async_fire_mqtt_message(hass, topic, config_get_state_offline(config)) state = hass.states.get(f"{domain}.{entity_id}") assert state.state == STATE_UNAVAILABLE entity_reg.async_update_entity( f"{domain}.{entity_id}", new_entity_id=f"{domain}.milk" ) await hass.async_block_till_done() assert hass.states.get(f"{domain}.milk") assert config[CONF_PREFIX][PREFIX_TELE] != "tele2" config[CONF_PREFIX][PREFIX_TELE] = "tele2" data = json.dumps(config) async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{config[CONF_MAC]}/config", data) await hass.async_block_till_done() assert len(hass.states.async_entity_ids(domain)) == 1 topic = get_topic_tele_will(config) async_fire_mqtt_message(hass, topic, config_get_state_online(config)) state = hass.states.get(f"{domain}.milk") assert state.state != STATE_UNAVAILABLE
[ "async", "def", "help_test_entity_id_update_discovery_update", "(", "hass", ",", "mqtt_mock", ",", "domain", ",", "config", ",", "sensor_config", "=", "None", ",", "entity_id", "=", "\"test\"", ")", ":", "entity_reg", "=", "await", "hass", ".", "helpers", ".", "entity_registry", ".", "async_get_registry", "(", ")", "config", "=", "copy", ".", "deepcopy", "(", "config", ")", "data", "=", "json", ".", "dumps", "(", "config", ")", "topic", "=", "get_topic_tele_will", "(", "config", ")", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{config[CONF_MAC]}/config\"", ",", "data", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "if", "sensor_config", ":", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{config[CONF_MAC]}/sensors\"", ",", "json", ".", "dumps", "(", "sensor_config", ")", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "async_fire_mqtt_message", "(", "hass", ",", "topic", ",", "config_get_state_online", "(", "config", ")", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "f\"{domain}.{entity_id}\"", ")", "assert", "state", ".", "state", "!=", "STATE_UNAVAILABLE", "async_fire_mqtt_message", "(", "hass", ",", "topic", ",", "config_get_state_offline", "(", "config", ")", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "f\"{domain}.{entity_id}\"", ")", "assert", "state", ".", "state", "==", "STATE_UNAVAILABLE", "entity_reg", ".", "async_update_entity", "(", "f\"{domain}.{entity_id}\"", ",", "new_entity_id", "=", "f\"{domain}.milk\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "hass", ".", "states", ".", "get", "(", "f\"{domain}.milk\"", ")", "assert", "config", "[", "CONF_PREFIX", "]", "[", "PREFIX_TELE", "]", "!=", "\"tele2\"", "config", "[", "CONF_PREFIX", "]", "[", "PREFIX_TELE", "]", "=", "\"tele2\"", "data", "=", "json", ".", "dumps", "(", "config", ")", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{config[CONF_MAC]}/config\"", ",", "data", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_entity_ids", "(", "domain", ")", ")", "==", "1", "topic", "=", "get_topic_tele_will", "(", "config", ")", "async_fire_mqtt_message", "(", "hass", ",", "topic", ",", "config_get_state_online", "(", "config", ")", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "f\"{domain}.milk\"", ")", "assert", "state", ".", "state", "!=", "STATE_UNAVAILABLE" ]
[ 546, 0 ]
[ 591, 43 ]
python
en
['en', 'en', 'en']
True
validate_schema
(schema)
Decorate a webhook function with a schema.
Decorate a webhook function with a schema.
def validate_schema(schema): """Decorate a webhook function with a schema.""" if isinstance(schema, dict): schema = vol.Schema(schema) def wrapper(func): """Wrap function so we validate schema.""" @wraps(func) async def validate_and_run(hass, config_entry, data): """Validate input and call handler.""" try: data = schema(data) except vol.Invalid as ex: err = vol.humanize.humanize_error(data, ex) _LOGGER.error("Received invalid webhook payload: %s", err) return empty_okay_response() return await func(hass, config_entry, data) return validate_and_run return wrapper
[ "def", "validate_schema", "(", "schema", ")", ":", "if", "isinstance", "(", "schema", ",", "dict", ")", ":", "schema", "=", "vol", ".", "Schema", "(", "schema", ")", "def", "wrapper", "(", "func", ")", ":", "\"\"\"Wrap function so we validate schema.\"\"\"", "@", "wraps", "(", "func", ")", "async", "def", "validate_and_run", "(", "hass", ",", "config_entry", ",", "data", ")", ":", "\"\"\"Validate input and call handler.\"\"\"", "try", ":", "data", "=", "schema", "(", "data", ")", "except", "vol", ".", "Invalid", "as", "ex", ":", "err", "=", "vol", ".", "humanize", ".", "humanize_error", "(", "data", ",", "ex", ")", "_LOGGER", ".", "error", "(", "\"Received invalid webhook payload: %s\"", ",", "err", ")", "return", "empty_okay_response", "(", ")", "return", "await", "func", "(", "hass", ",", "config_entry", ",", "data", ")", "return", "validate_and_run", "return", "wrapper" ]
[ 121, 0 ]
[ 143, 18 ]
python
en
['en', 'en', 'en']
True
handle_webhook
( hass: HomeAssistantType, webhook_id: str, request: Request )
Handle webhook callback.
Handle webhook callback.
async def handle_webhook( hass: HomeAssistantType, webhook_id: str, request: Request ) -> Response: """Handle webhook callback.""" if webhook_id in hass.data[DOMAIN][DATA_DELETED_IDS]: return Response(status=410) config_entry = hass.data[DOMAIN][DATA_CONFIG_ENTRIES][webhook_id] device_name = config_entry.data[ATTR_DEVICE_NAME] try: req_data = await request.json() except ValueError: _LOGGER.warning("Received invalid JSON from mobile_app device: %s", device_name) return empty_okay_response(status=HTTP_BAD_REQUEST) if ( ATTR_WEBHOOK_ENCRYPTED not in req_data and config_entry.data[ATTR_SUPPORTS_ENCRYPTION] ): _LOGGER.warning( "Refusing to accept unencrypted webhook from %s", device_name, ) return error_response(ERR_ENCRYPTION_REQUIRED, "Encryption required") try: req_data = WEBHOOK_PAYLOAD_SCHEMA(req_data) except vol.Invalid as ex: err = vol.humanize.humanize_error(req_data, ex) _LOGGER.error( "Received invalid webhook from %s with payload: %s", device_name, err ) return empty_okay_response() webhook_type = req_data[ATTR_WEBHOOK_TYPE] webhook_payload = req_data.get(ATTR_WEBHOOK_DATA, {}) if req_data[ATTR_WEBHOOK_ENCRYPTED]: enc_data = req_data[ATTR_WEBHOOK_ENCRYPTED_DATA] webhook_payload = _decrypt_payload(config_entry.data[CONF_SECRET], enc_data) if webhook_type not in WEBHOOK_COMMANDS: _LOGGER.error( "Received invalid webhook from %s of type: %s", device_name, webhook_type ) return empty_okay_response() _LOGGER.debug( "Received webhook payload from %s for type %s: %s", device_name, webhook_type, webhook_payload, ) # Shield so we make sure we finish the webhook, even if sender hangs up. return await asyncio.shield( WEBHOOK_COMMANDS[webhook_type](hass, config_entry, webhook_payload) )
[ "async", "def", "handle_webhook", "(", "hass", ":", "HomeAssistantType", ",", "webhook_id", ":", "str", ",", "request", ":", "Request", ")", "->", "Response", ":", "if", "webhook_id", "in", "hass", ".", "data", "[", "DOMAIN", "]", "[", "DATA_DELETED_IDS", "]", ":", "return", "Response", "(", "status", "=", "410", ")", "config_entry", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "DATA_CONFIG_ENTRIES", "]", "[", "webhook_id", "]", "device_name", "=", "config_entry", ".", "data", "[", "ATTR_DEVICE_NAME", "]", "try", ":", "req_data", "=", "await", "request", ".", "json", "(", ")", "except", "ValueError", ":", "_LOGGER", ".", "warning", "(", "\"Received invalid JSON from mobile_app device: %s\"", ",", "device_name", ")", "return", "empty_okay_response", "(", "status", "=", "HTTP_BAD_REQUEST", ")", "if", "(", "ATTR_WEBHOOK_ENCRYPTED", "not", "in", "req_data", "and", "config_entry", ".", "data", "[", "ATTR_SUPPORTS_ENCRYPTION", "]", ")", ":", "_LOGGER", ".", "warning", "(", "\"Refusing to accept unencrypted webhook from %s\"", ",", "device_name", ",", ")", "return", "error_response", "(", "ERR_ENCRYPTION_REQUIRED", ",", "\"Encryption required\"", ")", "try", ":", "req_data", "=", "WEBHOOK_PAYLOAD_SCHEMA", "(", "req_data", ")", "except", "vol", ".", "Invalid", "as", "ex", ":", "err", "=", "vol", ".", "humanize", ".", "humanize_error", "(", "req_data", ",", "ex", ")", "_LOGGER", ".", "error", "(", "\"Received invalid webhook from %s with payload: %s\"", ",", "device_name", ",", "err", ")", "return", "empty_okay_response", "(", ")", "webhook_type", "=", "req_data", "[", "ATTR_WEBHOOK_TYPE", "]", "webhook_payload", "=", "req_data", ".", "get", "(", "ATTR_WEBHOOK_DATA", ",", "{", "}", ")", "if", "req_data", "[", "ATTR_WEBHOOK_ENCRYPTED", "]", ":", "enc_data", "=", "req_data", "[", "ATTR_WEBHOOK_ENCRYPTED_DATA", "]", "webhook_payload", "=", "_decrypt_payload", "(", "config_entry", ".", "data", "[", "CONF_SECRET", "]", ",", "enc_data", ")", "if", "webhook_type", "not", "in", "WEBHOOK_COMMANDS", ":", "_LOGGER", ".", "error", "(", "\"Received invalid webhook from %s of type: %s\"", ",", "device_name", ",", "webhook_type", ")", "return", "empty_okay_response", "(", ")", "_LOGGER", ".", "debug", "(", "\"Received webhook payload from %s for type %s: %s\"", ",", "device_name", ",", "webhook_type", ",", "webhook_payload", ",", ")", "# Shield so we make sure we finish the webhook, even if sender hangs up.", "return", "await", "asyncio", ".", "shield", "(", "WEBHOOK_COMMANDS", "[", "webhook_type", "]", "(", "hass", ",", "config_entry", ",", "webhook_payload", ")", ")" ]
[ 146, 0 ]
[ 206, 5 ]
python
en
['en', 'xh', 'en']
True
webhook_call_service
(hass, config_entry, data)
Handle a call service webhook.
Handle a call service webhook.
async def webhook_call_service(hass, config_entry, data): """Handle a call service webhook.""" try: await hass.services.async_call( data[ATTR_DOMAIN], data[ATTR_SERVICE], data[ATTR_SERVICE_DATA], blocking=True, context=registration_context(config_entry.data), ) except (vol.Invalid, ServiceNotFound, Exception) as ex: _LOGGER.error( "Error when calling service during mobile_app " "webhook (device name: %s): %s", config_entry.data[ATTR_DEVICE_NAME], ex, ) raise HTTPBadRequest() from ex return empty_okay_response()
[ "async", "def", "webhook_call_service", "(", "hass", ",", "config_entry", ",", "data", ")", ":", "try", ":", "await", "hass", ".", "services", ".", "async_call", "(", "data", "[", "ATTR_DOMAIN", "]", ",", "data", "[", "ATTR_SERVICE", "]", ",", "data", "[", "ATTR_SERVICE_DATA", "]", ",", "blocking", "=", "True", ",", "context", "=", "registration_context", "(", "config_entry", ".", "data", ")", ",", ")", "except", "(", "vol", ".", "Invalid", ",", "ServiceNotFound", ",", "Exception", ")", "as", "ex", ":", "_LOGGER", ".", "error", "(", "\"Error when calling service during mobile_app \"", "\"webhook (device name: %s): %s\"", ",", "config_entry", ".", "data", "[", "ATTR_DEVICE_NAME", "]", ",", "ex", ",", ")", "raise", "HTTPBadRequest", "(", ")", "from", "ex", "return", "empty_okay_response", "(", ")" ]
[ 217, 0 ]
[ 236, 32 ]
python
en
['en', 'lb', 'en']
True
webhook_fire_event
(hass, config_entry, data)
Handle a fire event webhook.
Handle a fire event webhook.
async def webhook_fire_event(hass, config_entry, data): """Handle a fire event webhook.""" event_type = data[ATTR_EVENT_TYPE] hass.bus.async_fire( event_type, data[ATTR_EVENT_DATA], EventOrigin.remote, context=registration_context(config_entry.data), ) return empty_okay_response()
[ "async", "def", "webhook_fire_event", "(", "hass", ",", "config_entry", ",", "data", ")", ":", "event_type", "=", "data", "[", "ATTR_EVENT_TYPE", "]", "hass", ".", "bus", ".", "async_fire", "(", "event_type", ",", "data", "[", "ATTR_EVENT_DATA", "]", ",", "EventOrigin", ".", "remote", ",", "context", "=", "registration_context", "(", "config_entry", ".", "data", ")", ",", ")", "return", "empty_okay_response", "(", ")" ]
[ 246, 0 ]
[ 255, 32 ]
python
en
['en', 'lb', 'en']
True
webhook_stream_camera
(hass, config_entry, data)
Handle a request to HLS-stream a camera.
Handle a request to HLS-stream a camera.
async def webhook_stream_camera(hass, config_entry, data): """Handle a request to HLS-stream a camera.""" camera = hass.states.get(data[ATTR_CAMERA_ENTITY_ID]) if camera is None: return webhook_response( {"success": False}, registration=config_entry.data, status=HTTP_BAD_REQUEST, ) resp = {"mjpeg_path": "/api/camera_proxy_stream/%s" % (camera.entity_id)} if camera.attributes[ATTR_SUPPORTED_FEATURES] & CAMERA_SUPPORT_STREAM: try: resp["hls_path"] = await hass.components.camera.async_request_stream( camera.entity_id, "hls" ) except HomeAssistantError: resp["hls_path"] = None else: resp["hls_path"] = None return webhook_response(resp, registration=config_entry.data)
[ "async", "def", "webhook_stream_camera", "(", "hass", ",", "config_entry", ",", "data", ")", ":", "camera", "=", "hass", ".", "states", ".", "get", "(", "data", "[", "ATTR_CAMERA_ENTITY_ID", "]", ")", "if", "camera", "is", "None", ":", "return", "webhook_response", "(", "{", "\"success\"", ":", "False", "}", ",", "registration", "=", "config_entry", ".", "data", ",", "status", "=", "HTTP_BAD_REQUEST", ",", ")", "resp", "=", "{", "\"mjpeg_path\"", ":", "\"/api/camera_proxy_stream/%s\"", "%", "(", "camera", ".", "entity_id", ")", "}", "if", "camera", ".", "attributes", "[", "ATTR_SUPPORTED_FEATURES", "]", "&", "CAMERA_SUPPORT_STREAM", ":", "try", ":", "resp", "[", "\"hls_path\"", "]", "=", "await", "hass", ".", "components", ".", "camera", ".", "async_request_stream", "(", "camera", ".", "entity_id", ",", "\"hls\"", ")", "except", "HomeAssistantError", ":", "resp", "[", "\"hls_path\"", "]", "=", "None", "else", ":", "resp", "[", "\"hls_path\"", "]", "=", "None", "return", "webhook_response", "(", "resp", ",", "registration", "=", "config_entry", ".", "data", ")" ]
[ 260, 0 ]
[ 283, 65 ]
python
en
['en', 'en', 'en']
True
webhook_render_template
(hass, config_entry, data)
Handle a render template webhook.
Handle a render template webhook.
async def webhook_render_template(hass, config_entry, data): """Handle a render template webhook.""" resp = {} for key, item in data.items(): try: tpl = template.Template(item[ATTR_TEMPLATE], hass) resp[key] = tpl.async_render(item.get(ATTR_TEMPLATE_VARIABLES)) except template.TemplateError as ex: resp[key] = {"error": str(ex)} return webhook_response(resp, registration=config_entry.data)
[ "async", "def", "webhook_render_template", "(", "hass", ",", "config_entry", ",", "data", ")", ":", "resp", "=", "{", "}", "for", "key", ",", "item", "in", "data", ".", "items", "(", ")", ":", "try", ":", "tpl", "=", "template", ".", "Template", "(", "item", "[", "ATTR_TEMPLATE", "]", ",", "hass", ")", "resp", "[", "key", "]", "=", "tpl", ".", "async_render", "(", "item", ".", "get", "(", "ATTR_TEMPLATE_VARIABLES", ")", ")", "except", "template", ".", "TemplateError", "as", "ex", ":", "resp", "[", "key", "]", "=", "{", "\"error\"", ":", "str", "(", "ex", ")", "}", "return", "webhook_response", "(", "resp", ",", "registration", "=", "config_entry", ".", "data", ")" ]
[ 295, 0 ]
[ 305, 65 ]
python
en
['hu', 'lb', 'en']
False
webhook_update_location
(hass, config_entry, data)
Handle an update location webhook.
Handle an update location webhook.
async def webhook_update_location(hass, config_entry, data): """Handle an update location webhook.""" hass.helpers.dispatcher.async_dispatcher_send( SIGNAL_LOCATION_UPDATE.format(config_entry.entry_id), data ) return empty_okay_response()
[ "async", "def", "webhook_update_location", "(", "hass", ",", "config_entry", ",", "data", ")", ":", "hass", ".", "helpers", ".", "dispatcher", ".", "async_dispatcher_send", "(", "SIGNAL_LOCATION_UPDATE", ".", "format", "(", "config_entry", ".", "entry_id", ")", ",", "data", ")", "return", "empty_okay_response", "(", ")" ]
[ 321, 0 ]
[ 326, 32 ]
python
en
['en', 'lb', 'en']
True
webhook_update_registration
(hass, config_entry, data)
Handle an update registration webhook.
Handle an update registration webhook.
async def webhook_update_registration(hass, config_entry, data): """Handle an update registration webhook.""" new_registration = {**config_entry.data, **data} device_registry = await dr.async_get_registry(hass) device_registry.async_get_or_create( config_entry_id=config_entry.entry_id, identifiers={(DOMAIN, config_entry.data[ATTR_DEVICE_ID])}, manufacturer=new_registration[ATTR_MANUFACTURER], model=new_registration[ATTR_MODEL], name=new_registration[ATTR_DEVICE_NAME], sw_version=new_registration[ATTR_OS_VERSION], ) hass.config_entries.async_update_entry(config_entry, data=new_registration) await hass_notify.async_reload(hass, DOMAIN) return webhook_response( safe_registration(new_registration), registration=new_registration, )
[ "async", "def", "webhook_update_registration", "(", "hass", ",", "config_entry", ",", "data", ")", ":", "new_registration", "=", "{", "*", "*", "config_entry", ".", "data", ",", "*", "*", "data", "}", "device_registry", "=", "await", "dr", ".", "async_get_registry", "(", "hass", ")", "device_registry", ".", "async_get_or_create", "(", "config_entry_id", "=", "config_entry", ".", "entry_id", ",", "identifiers", "=", "{", "(", "DOMAIN", ",", "config_entry", ".", "data", "[", "ATTR_DEVICE_ID", "]", ")", "}", ",", "manufacturer", "=", "new_registration", "[", "ATTR_MANUFACTURER", "]", ",", "model", "=", "new_registration", "[", "ATTR_MODEL", "]", ",", "name", "=", "new_registration", "[", "ATTR_DEVICE_NAME", "]", ",", "sw_version", "=", "new_registration", "[", "ATTR_OS_VERSION", "]", ",", ")", "hass", ".", "config_entries", ".", "async_update_entry", "(", "config_entry", ",", "data", "=", "new_registration", ")", "await", "hass_notify", ".", "async_reload", "(", "hass", ",", "DOMAIN", ")", "return", "webhook_response", "(", "safe_registration", "(", "new_registration", ")", ",", "registration", "=", "new_registration", ",", ")" ]
[ 340, 0 ]
[ 362, 5 ]
python
en
['en', 'lb', 'en']
True
webhook_enable_encryption
(hass, config_entry, data)
Handle a encryption enable webhook.
Handle a encryption enable webhook.
async def webhook_enable_encryption(hass, config_entry, data): """Handle a encryption enable webhook.""" if config_entry.data[ATTR_SUPPORTS_ENCRYPTION]: _LOGGER.warning( "Refusing to enable encryption for %s because it is already enabled!", config_entry.data[ATTR_DEVICE_NAME], ) return error_response( ERR_ENCRYPTION_ALREADY_ENABLED, "Encryption already enabled" ) if not supports_encryption(): _LOGGER.warning( "Unable to enable encryption for %s because libsodium is unavailable!", config_entry.data[ATTR_DEVICE_NAME], ) return error_response(ERR_ENCRYPTION_NOT_AVAILABLE, "Encryption is unavailable") secret = secrets.token_hex(SecretBox.KEY_SIZE) data = {**config_entry.data, ATTR_SUPPORTS_ENCRYPTION: True, CONF_SECRET: secret} hass.config_entries.async_update_entry(config_entry, data=data) return json_response({"secret": secret})
[ "async", "def", "webhook_enable_encryption", "(", "hass", ",", "config_entry", ",", "data", ")", ":", "if", "config_entry", ".", "data", "[", "ATTR_SUPPORTS_ENCRYPTION", "]", ":", "_LOGGER", ".", "warning", "(", "\"Refusing to enable encryption for %s because it is already enabled!\"", ",", "config_entry", ".", "data", "[", "ATTR_DEVICE_NAME", "]", ",", ")", "return", "error_response", "(", "ERR_ENCRYPTION_ALREADY_ENABLED", ",", "\"Encryption already enabled\"", ")", "if", "not", "supports_encryption", "(", ")", ":", "_LOGGER", ".", "warning", "(", "\"Unable to enable encryption for %s because libsodium is unavailable!\"", ",", "config_entry", ".", "data", "[", "ATTR_DEVICE_NAME", "]", ",", ")", "return", "error_response", "(", "ERR_ENCRYPTION_NOT_AVAILABLE", ",", "\"Encryption is unavailable\"", ")", "secret", "=", "secrets", ".", "token_hex", "(", "SecretBox", ".", "KEY_SIZE", ")", "data", "=", "{", "*", "*", "config_entry", ".", "data", ",", "ATTR_SUPPORTS_ENCRYPTION", ":", "True", ",", "CONF_SECRET", ":", "secret", "}", "hass", ".", "config_entries", ".", "async_update_entry", "(", "config_entry", ",", "data", "=", "data", ")", "return", "json_response", "(", "{", "\"secret\"", ":", "secret", "}", ")" ]
[ 366, 0 ]
[ 390, 44 ]
python
en
['es', 'en', 'en']
True
webhook_register_sensor
(hass, config_entry, data)
Handle a register sensor webhook.
Handle a register sensor webhook.
async def webhook_register_sensor(hass, config_entry, data): """Handle a register sensor webhook.""" entity_type = data[ATTR_SENSOR_TYPE] unique_id = data[ATTR_SENSOR_UNIQUE_ID] device_name = config_entry.data[ATTR_DEVICE_NAME] unique_store_key = f"{config_entry.data[CONF_WEBHOOK_ID]}_{unique_id}" existing_sensor = unique_store_key in hass.data[DOMAIN][entity_type] data[CONF_WEBHOOK_ID] = config_entry.data[CONF_WEBHOOK_ID] # If sensor already is registered, update current state instead if existing_sensor: _LOGGER.debug( "Re-register for %s of existing sensor %s", device_name, unique_id ) entry = hass.data[DOMAIN][entity_type][unique_store_key] data = {**entry, **data} hass.data[DOMAIN][entity_type][unique_store_key] = data hass.data[DOMAIN][DATA_STORE].async_delay_save( lambda: savable_state(hass), DELAY_SAVE ) if existing_sensor: async_dispatcher_send(hass, SIGNAL_SENSOR_UPDATE, data) else: register_signal = f"{DOMAIN}_{data[ATTR_SENSOR_TYPE]}_register" async_dispatcher_send(hass, register_signal, data) return webhook_response( {"success": True}, registration=config_entry.data, status=HTTP_CREATED, )
[ "async", "def", "webhook_register_sensor", "(", "hass", ",", "config_entry", ",", "data", ")", ":", "entity_type", "=", "data", "[", "ATTR_SENSOR_TYPE", "]", "unique_id", "=", "data", "[", "ATTR_SENSOR_UNIQUE_ID", "]", "device_name", "=", "config_entry", ".", "data", "[", "ATTR_DEVICE_NAME", "]", "unique_store_key", "=", "f\"{config_entry.data[CONF_WEBHOOK_ID]}_{unique_id}\"", "existing_sensor", "=", "unique_store_key", "in", "hass", ".", "data", "[", "DOMAIN", "]", "[", "entity_type", "]", "data", "[", "CONF_WEBHOOK_ID", "]", "=", "config_entry", ".", "data", "[", "CONF_WEBHOOK_ID", "]", "# If sensor already is registered, update current state instead", "if", "existing_sensor", ":", "_LOGGER", ".", "debug", "(", "\"Re-register for %s of existing sensor %s\"", ",", "device_name", ",", "unique_id", ")", "entry", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "entity_type", "]", "[", "unique_store_key", "]", "data", "=", "{", "*", "*", "entry", ",", "*", "*", "data", "}", "hass", ".", "data", "[", "DOMAIN", "]", "[", "entity_type", "]", "[", "unique_store_key", "]", "=", "data", "hass", ".", "data", "[", "DOMAIN", "]", "[", "DATA_STORE", "]", ".", "async_delay_save", "(", "lambda", ":", "savable_state", "(", "hass", ")", ",", "DELAY_SAVE", ")", "if", "existing_sensor", ":", "async_dispatcher_send", "(", "hass", ",", "SIGNAL_SENSOR_UPDATE", ",", "data", ")", "else", ":", "register_signal", "=", "f\"{DOMAIN}_{data[ATTR_SENSOR_TYPE]}_register\"", "async_dispatcher_send", "(", "hass", ",", "register_signal", ",", "data", ")", "return", "webhook_response", "(", "{", "\"success\"", ":", "True", "}", ",", "registration", "=", "config_entry", ".", "data", ",", "status", "=", "HTTP_CREATED", ",", ")" ]
[ 410, 0 ]
[ 445, 5 ]
python
en
['en', 'da', 'en']
True
webhook_update_sensor_states
(hass, config_entry, data)
Handle an update sensor states webhook.
Handle an update sensor states webhook.
async def webhook_update_sensor_states(hass, config_entry, data): """Handle an update sensor states webhook.""" sensor_schema_full = vol.Schema( { vol.Optional(ATTR_SENSOR_ATTRIBUTES, default={}): dict, vol.Optional(ATTR_SENSOR_ICON, default="mdi:cellphone"): cv.icon, vol.Required(ATTR_SENSOR_STATE): vol.Any(None, bool, str, int, float), vol.Required(ATTR_SENSOR_TYPE): vol.In(SENSOR_TYPES), vol.Required(ATTR_SENSOR_UNIQUE_ID): cv.string, } ) device_name = config_entry.data[ATTR_DEVICE_NAME] resp = {} for sensor in data: entity_type = sensor[ATTR_SENSOR_TYPE] unique_id = sensor[ATTR_SENSOR_UNIQUE_ID] unique_store_key = f"{config_entry.data[CONF_WEBHOOK_ID]}_{unique_id}" if unique_store_key not in hass.data[DOMAIN][entity_type]: _LOGGER.error( "Refusing to update %s non-registered sensor: %s", device_name, unique_store_key, ) err_msg = f"{entity_type} {unique_id} is not registered" resp[unique_id] = { "success": False, "error": {"code": ERR_SENSOR_NOT_REGISTERED, "message": err_msg}, } continue entry = hass.data[DOMAIN][entity_type][unique_store_key] try: sensor = sensor_schema_full(sensor) except vol.Invalid as err: err_msg = vol.humanize.humanize_error(sensor, err) _LOGGER.error( "Received invalid sensor payload from %s for %s: %s", device_name, unique_id, err_msg, ) resp[unique_id] = { "success": False, "error": {"code": ERR_INVALID_FORMAT, "message": err_msg}, } continue new_state = {**entry, **sensor} hass.data[DOMAIN][entity_type][unique_store_key] = new_state async_dispatcher_send(hass, SIGNAL_SENSOR_UPDATE, new_state) resp[unique_id] = {"success": True} hass.data[DOMAIN][DATA_STORE].async_delay_save( lambda: savable_state(hass), DELAY_SAVE ) return webhook_response(resp, registration=config_entry.data)
[ "async", "def", "webhook_update_sensor_states", "(", "hass", ",", "config_entry", ",", "data", ")", ":", "sensor_schema_full", "=", "vol", ".", "Schema", "(", "{", "vol", ".", "Optional", "(", "ATTR_SENSOR_ATTRIBUTES", ",", "default", "=", "{", "}", ")", ":", "dict", ",", "vol", ".", "Optional", "(", "ATTR_SENSOR_ICON", ",", "default", "=", "\"mdi:cellphone\"", ")", ":", "cv", ".", "icon", ",", "vol", ".", "Required", "(", "ATTR_SENSOR_STATE", ")", ":", "vol", ".", "Any", "(", "None", ",", "bool", ",", "str", ",", "int", ",", "float", ")", ",", "vol", ".", "Required", "(", "ATTR_SENSOR_TYPE", ")", ":", "vol", ".", "In", "(", "SENSOR_TYPES", ")", ",", "vol", ".", "Required", "(", "ATTR_SENSOR_UNIQUE_ID", ")", ":", "cv", ".", "string", ",", "}", ")", "device_name", "=", "config_entry", ".", "data", "[", "ATTR_DEVICE_NAME", "]", "resp", "=", "{", "}", "for", "sensor", "in", "data", ":", "entity_type", "=", "sensor", "[", "ATTR_SENSOR_TYPE", "]", "unique_id", "=", "sensor", "[", "ATTR_SENSOR_UNIQUE_ID", "]", "unique_store_key", "=", "f\"{config_entry.data[CONF_WEBHOOK_ID]}_{unique_id}\"", "if", "unique_store_key", "not", "in", "hass", ".", "data", "[", "DOMAIN", "]", "[", "entity_type", "]", ":", "_LOGGER", ".", "error", "(", "\"Refusing to update %s non-registered sensor: %s\"", ",", "device_name", ",", "unique_store_key", ",", ")", "err_msg", "=", "f\"{entity_type} {unique_id} is not registered\"", "resp", "[", "unique_id", "]", "=", "{", "\"success\"", ":", "False", ",", "\"error\"", ":", "{", "\"code\"", ":", "ERR_SENSOR_NOT_REGISTERED", ",", "\"message\"", ":", "err_msg", "}", ",", "}", "continue", "entry", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "entity_type", "]", "[", "unique_store_key", "]", "try", ":", "sensor", "=", "sensor_schema_full", "(", "sensor", ")", "except", "vol", ".", "Invalid", "as", "err", ":", "err_msg", "=", "vol", ".", "humanize", ".", "humanize_error", "(", "sensor", ",", "err", ")", "_LOGGER", ".", "error", "(", "\"Received invalid sensor payload from %s for %s: %s\"", ",", "device_name", ",", "unique_id", ",", "err_msg", ",", ")", "resp", "[", "unique_id", "]", "=", "{", "\"success\"", ":", "False", ",", "\"error\"", ":", "{", "\"code\"", ":", "ERR_INVALID_FORMAT", ",", "\"message\"", ":", "err_msg", "}", ",", "}", "continue", "new_state", "=", "{", "*", "*", "entry", ",", "*", "*", "sensor", "}", "hass", ".", "data", "[", "DOMAIN", "]", "[", "entity_type", "]", "[", "unique_store_key", "]", "=", "new_state", "async_dispatcher_send", "(", "hass", ",", "SIGNAL_SENSOR_UPDATE", ",", "new_state", ")", "resp", "[", "unique_id", "]", "=", "{", "\"success\"", ":", "True", "}", "hass", ".", "data", "[", "DOMAIN", "]", "[", "DATA_STORE", "]", ".", "async_delay_save", "(", "lambda", ":", "savable_state", "(", "hass", ")", ",", "DELAY_SAVE", ")", "return", "webhook_response", "(", "resp", ",", "registration", "=", "config_entry", ".", "data", ")" ]
[ 466, 0 ]
[ 530, 65 ]
python
en
['en', 'lb', 'en']
True
webhook_get_zones
(hass, config_entry, data)
Handle a get zones webhook.
Handle a get zones webhook.
async def webhook_get_zones(hass, config_entry, data): """Handle a get zones webhook.""" zones = [ hass.states.get(entity_id) for entity_id in sorted(hass.states.async_entity_ids(ZONE_DOMAIN)) ] return webhook_response(zones, registration=config_entry.data)
[ "async", "def", "webhook_get_zones", "(", "hass", ",", "config_entry", ",", "data", ")", ":", "zones", "=", "[", "hass", ".", "states", ".", "get", "(", "entity_id", ")", "for", "entity_id", "in", "sorted", "(", "hass", ".", "states", ".", "async_entity_ids", "(", "ZONE_DOMAIN", ")", ")", "]", "return", "webhook_response", "(", "zones", ",", "registration", "=", "config_entry", ".", "data", ")" ]
[ 534, 0 ]
[ 540, 66 ]
python
nl
['nl', 'nl', 'en']
True
webhook_get_config
(hass, config_entry, data)
Handle a get config webhook.
Handle a get config webhook.
async def webhook_get_config(hass, config_entry, data): """Handle a get config webhook.""" hass_config = hass.config.as_dict() resp = { "latitude": hass_config["latitude"], "longitude": hass_config["longitude"], "elevation": hass_config["elevation"], "unit_system": hass_config["unit_system"], "location_name": hass_config["location_name"], "time_zone": hass_config["time_zone"], "components": hass_config["components"], "version": hass_config["version"], "theme_color": MANIFEST_JSON["theme_color"], } if CONF_CLOUDHOOK_URL in config_entry.data: resp[CONF_CLOUDHOOK_URL] = config_entry.data[CONF_CLOUDHOOK_URL] try: resp[CONF_REMOTE_UI_URL] = hass.components.cloud.async_remote_ui_url() except hass.components.cloud.CloudNotAvailable: pass return webhook_response(resp, registration=config_entry.data)
[ "async", "def", "webhook_get_config", "(", "hass", ",", "config_entry", ",", "data", ")", ":", "hass_config", "=", "hass", ".", "config", ".", "as_dict", "(", ")", "resp", "=", "{", "\"latitude\"", ":", "hass_config", "[", "\"latitude\"", "]", ",", "\"longitude\"", ":", "hass_config", "[", "\"longitude\"", "]", ",", "\"elevation\"", ":", "hass_config", "[", "\"elevation\"", "]", ",", "\"unit_system\"", ":", "hass_config", "[", "\"unit_system\"", "]", ",", "\"location_name\"", ":", "hass_config", "[", "\"location_name\"", "]", ",", "\"time_zone\"", ":", "hass_config", "[", "\"time_zone\"", "]", ",", "\"components\"", ":", "hass_config", "[", "\"components\"", "]", ",", "\"version\"", ":", "hass_config", "[", "\"version\"", "]", ",", "\"theme_color\"", ":", "MANIFEST_JSON", "[", "\"theme_color\"", "]", ",", "}", "if", "CONF_CLOUDHOOK_URL", "in", "config_entry", ".", "data", ":", "resp", "[", "CONF_CLOUDHOOK_URL", "]", "=", "config_entry", ".", "data", "[", "CONF_CLOUDHOOK_URL", "]", "try", ":", "resp", "[", "CONF_REMOTE_UI_URL", "]", "=", "hass", ".", "components", ".", "cloud", ".", "async_remote_ui_url", "(", ")", "except", "hass", ".", "components", ".", "cloud", ".", "CloudNotAvailable", ":", "pass", "return", "webhook_response", "(", "resp", ",", "registration", "=", "config_entry", ".", "data", ")" ]
[ 544, 0 ]
[ 568, 65 ]
python
en
['en', 'nl', 'en']
True
webhook_scan_tag
(hass, config_entry, data)
Handle a fire event webhook.
Handle a fire event webhook.
async def webhook_scan_tag(hass, config_entry, data): """Handle a fire event webhook.""" await tag.async_scan_tag( hass, data["tag_id"], config_entry.data[ATTR_DEVICE_ID], registration_context(config_entry.data), ) return empty_okay_response()
[ "async", "def", "webhook_scan_tag", "(", "hass", ",", "config_entry", ",", "data", ")", ":", "await", "tag", ".", "async_scan_tag", "(", "hass", ",", "data", "[", "\"tag_id\"", "]", ",", "config_entry", ".", "data", "[", "ATTR_DEVICE_ID", "]", ",", "registration_context", "(", "config_entry", ".", "data", ")", ",", ")", "return", "empty_okay_response", "(", ")" ]
[ 573, 0 ]
[ 581, 32 ]
python
en
['en', 'lb', 'en']
True
test_empty_config
(hass)
Test a default config will be create for empty config.
Test a default config will be create for empty config.
async def test_empty_config(hass): """Test a default config will be create for empty config.""" with async_patch("aiobotocore.AioSession", new=MockAioSession): await async_setup_component(hass, "aws", {"aws": {}}) await hass.async_block_till_done() sessions = hass.data[aws.DATA_SESSIONS] assert sessions is not None assert len(sessions) == 1 session = sessions.get("default") assert isinstance(session, MockAioSession) # we don't validate auto-created default profile session.get_user.assert_not_awaited()
[ "async", "def", "test_empty_config", "(", "hass", ")", ":", "with", "async_patch", "(", "\"aiobotocore.AioSession\"", ",", "new", "=", "MockAioSession", ")", ":", "await", "async_setup_component", "(", "hass", ",", "\"aws\"", ",", "{", "\"aws\"", ":", "{", "}", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "sessions", "=", "hass", ".", "data", "[", "aws", ".", "DATA_SESSIONS", "]", "assert", "sessions", "is", "not", "None", "assert", "len", "(", "sessions", ")", "==", "1", "session", "=", "sessions", ".", "get", "(", "\"default\"", ")", "assert", "isinstance", "(", "session", ",", "MockAioSession", ")", "# we don't validate auto-created default profile", "session", ".", "get_user", ".", "assert_not_awaited", "(", ")" ]
[ 32, 0 ]
[ 44, 41 ]
python
en
['en', 'en', 'en']
True
test_empty_credential
(hass)
Test a default config will be create for empty credential section.
Test a default config will be create for empty credential section.
async def test_empty_credential(hass): """Test a default config will be create for empty credential section.""" with async_patch("aiobotocore.AioSession", new=MockAioSession): await async_setup_component( hass, "aws", { "aws": { "notify": [ { "service": "lambda", "name": "New Lambda Test", "region_name": "us-east-1", } ] } }, ) await hass.async_block_till_done() sessions = hass.data[aws.DATA_SESSIONS] assert sessions is not None assert len(sessions) == 1 session = sessions.get("default") assert isinstance(session, MockAioSession) assert hass.services.has_service("notify", "new_lambda_test") is True await hass.services.async_call( "notify", "new_lambda_test", {"message": "test", "target": "ARN"}, blocking=True ) session.invoke.assert_awaited_once()
[ "async", "def", "test_empty_credential", "(", "hass", ")", ":", "with", "async_patch", "(", "\"aiobotocore.AioSession\"", ",", "new", "=", "MockAioSession", ")", ":", "await", "async_setup_component", "(", "hass", ",", "\"aws\"", ",", "{", "\"aws\"", ":", "{", "\"notify\"", ":", "[", "{", "\"service\"", ":", "\"lambda\"", ",", "\"name\"", ":", "\"New Lambda Test\"", ",", "\"region_name\"", ":", "\"us-east-1\"", ",", "}", "]", "}", "}", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "sessions", "=", "hass", ".", "data", "[", "aws", ".", "DATA_SESSIONS", "]", "assert", "sessions", "is", "not", "None", "assert", "len", "(", "sessions", ")", "==", "1", "session", "=", "sessions", ".", "get", "(", "\"default\"", ")", "assert", "isinstance", "(", "session", ",", "MockAioSession", ")", "assert", "hass", ".", "services", ".", "has_service", "(", "\"notify\"", ",", "\"new_lambda_test\"", ")", "is", "True", "await", "hass", ".", "services", ".", "async_call", "(", "\"notify\"", ",", "\"new_lambda_test\"", ",", "{", "\"message\"", ":", "\"test\"", ",", "\"target\"", ":", "\"ARN\"", "}", ",", "blocking", "=", "True", ")", "session", ".", "invoke", ".", "assert_awaited_once", "(", ")" ]
[ 47, 0 ]
[ 77, 40 ]
python
en
['en', 'en', 'en']
True
test_profile_credential
(hass)
Test credentials with profile name.
Test credentials with profile name.
async def test_profile_credential(hass): """Test credentials with profile name.""" with async_patch("aiobotocore.AioSession", new=MockAioSession): await async_setup_component( hass, "aws", { "aws": { "credentials": {"name": "test", "profile_name": "test-profile"}, "notify": [ { "service": "sns", "credential_name": "test", "name": "SNS Test", "region_name": "us-east-1", } ], } }, ) await hass.async_block_till_done() sessions = hass.data[aws.DATA_SESSIONS] assert sessions is not None assert len(sessions) == 1 session = sessions.get("test") assert isinstance(session, MockAioSession) assert hass.services.has_service("notify", "sns_test") is True await hass.services.async_call( "notify", "sns_test", {"title": "test", "message": "test", "target": "ARN"}, blocking=True, ) session.publish.assert_awaited_once()
[ "async", "def", "test_profile_credential", "(", "hass", ")", ":", "with", "async_patch", "(", "\"aiobotocore.AioSession\"", ",", "new", "=", "MockAioSession", ")", ":", "await", "async_setup_component", "(", "hass", ",", "\"aws\"", ",", "{", "\"aws\"", ":", "{", "\"credentials\"", ":", "{", "\"name\"", ":", "\"test\"", ",", "\"profile_name\"", ":", "\"test-profile\"", "}", ",", "\"notify\"", ":", "[", "{", "\"service\"", ":", "\"sns\"", ",", "\"credential_name\"", ":", "\"test\"", ",", "\"name\"", ":", "\"SNS Test\"", ",", "\"region_name\"", ":", "\"us-east-1\"", ",", "}", "]", ",", "}", "}", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "sessions", "=", "hass", ".", "data", "[", "aws", ".", "DATA_SESSIONS", "]", "assert", "sessions", "is", "not", "None", "assert", "len", "(", "sessions", ")", "==", "1", "session", "=", "sessions", ".", "get", "(", "\"test\"", ")", "assert", "isinstance", "(", "session", ",", "MockAioSession", ")", "assert", "hass", ".", "services", ".", "has_service", "(", "\"notify\"", ",", "\"sns_test\"", ")", "is", "True", "await", "hass", ".", "services", ".", "async_call", "(", "\"notify\"", ",", "\"sns_test\"", ",", "{", "\"title\"", ":", "\"test\"", ",", "\"message\"", ":", "\"test\"", ",", "\"target\"", ":", "\"ARN\"", "}", ",", "blocking", "=", "True", ",", ")", "session", ".", "publish", ".", "assert_awaited_once", "(", ")" ]
[ 80, 0 ]
[ 115, 41 ]
python
en
['en', 'en', 'en']
True
test_access_key_credential
(hass)
Test credentials with access key.
Test credentials with access key.
async def test_access_key_credential(hass): """Test credentials with access key.""" with async_patch("aiobotocore.AioSession", new=MockAioSession): await async_setup_component( hass, "aws", { "aws": { "credentials": [ {"name": "test", "profile_name": "test-profile"}, { "name": "key", "aws_access_key_id": "test-key", "aws_secret_access_key": "test-secret", }, ], "notify": [ { "service": "sns", "credential_name": "key", "name": "SNS Test", "region_name": "us-east-1", } ], } }, ) await hass.async_block_till_done() sessions = hass.data[aws.DATA_SESSIONS] assert sessions is not None assert len(sessions) == 2 session = sessions.get("key") assert isinstance(session, MockAioSession) assert hass.services.has_service("notify", "sns_test") is True await hass.services.async_call( "notify", "sns_test", {"title": "test", "message": "test", "target": "ARN"}, blocking=True, ) session.publish.assert_awaited_once()
[ "async", "def", "test_access_key_credential", "(", "hass", ")", ":", "with", "async_patch", "(", "\"aiobotocore.AioSession\"", ",", "new", "=", "MockAioSession", ")", ":", "await", "async_setup_component", "(", "hass", ",", "\"aws\"", ",", "{", "\"aws\"", ":", "{", "\"credentials\"", ":", "[", "{", "\"name\"", ":", "\"test\"", ",", "\"profile_name\"", ":", "\"test-profile\"", "}", ",", "{", "\"name\"", ":", "\"key\"", ",", "\"aws_access_key_id\"", ":", "\"test-key\"", ",", "\"aws_secret_access_key\"", ":", "\"test-secret\"", ",", "}", ",", "]", ",", "\"notify\"", ":", "[", "{", "\"service\"", ":", "\"sns\"", ",", "\"credential_name\"", ":", "\"key\"", ",", "\"name\"", ":", "\"SNS Test\"", ",", "\"region_name\"", ":", "\"us-east-1\"", ",", "}", "]", ",", "}", "}", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "sessions", "=", "hass", ".", "data", "[", "aws", ".", "DATA_SESSIONS", "]", "assert", "sessions", "is", "not", "None", "assert", "len", "(", "sessions", ")", "==", "2", "session", "=", "sessions", ".", "get", "(", "\"key\"", ")", "assert", "isinstance", "(", "session", ",", "MockAioSession", ")", "assert", "hass", ".", "services", ".", "has_service", "(", "\"notify\"", ",", "\"sns_test\"", ")", "is", "True", "await", "hass", ".", "services", ".", "async_call", "(", "\"notify\"", ",", "\"sns_test\"", ",", "{", "\"title\"", ":", "\"test\"", ",", "\"message\"", ":", "\"test\"", ",", "\"target\"", ":", "\"ARN\"", "}", ",", "blocking", "=", "True", ",", ")", "session", ".", "publish", ".", "assert_awaited_once", "(", ")" ]
[ 118, 0 ]
[ 160, 41 ]
python
en
['en', 'en', 'en']
True
test_notify_credential
(hass)
Test notify service can use access key directly.
Test notify service can use access key directly.
async def test_notify_credential(hass): """Test notify service can use access key directly.""" with async_patch("aiobotocore.AioSession", new=MockAioSession): await async_setup_component( hass, "aws", { "aws": { "notify": [ { "service": "sqs", "credential_name": "test", "name": "SQS Test", "region_name": "us-east-1", "aws_access_key_id": "some-key", "aws_secret_access_key": "some-secret", } ] } }, ) await hass.async_block_till_done() sessions = hass.data[aws.DATA_SESSIONS] assert sessions is not None assert len(sessions) == 1 assert isinstance(sessions.get("default"), MockAioSession) assert hass.services.has_service("notify", "sqs_test") is True await hass.services.async_call( "notify", "sqs_test", {"message": "test", "target": "ARN"}, blocking=True )
[ "async", "def", "test_notify_credential", "(", "hass", ")", ":", "with", "async_patch", "(", "\"aiobotocore.AioSession\"", ",", "new", "=", "MockAioSession", ")", ":", "await", "async_setup_component", "(", "hass", ",", "\"aws\"", ",", "{", "\"aws\"", ":", "{", "\"notify\"", ":", "[", "{", "\"service\"", ":", "\"sqs\"", ",", "\"credential_name\"", ":", "\"test\"", ",", "\"name\"", ":", "\"SQS Test\"", ",", "\"region_name\"", ":", "\"us-east-1\"", ",", "\"aws_access_key_id\"", ":", "\"some-key\"", ",", "\"aws_secret_access_key\"", ":", "\"some-secret\"", ",", "}", "]", "}", "}", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "sessions", "=", "hass", ".", "data", "[", "aws", ".", "DATA_SESSIONS", "]", "assert", "sessions", "is", "not", "None", "assert", "len", "(", "sessions", ")", "==", "1", "assert", "isinstance", "(", "sessions", ".", "get", "(", "\"default\"", ")", ",", "MockAioSession", ")", "assert", "hass", ".", "services", ".", "has_service", "(", "\"notify\"", ",", "\"sqs_test\"", ")", "is", "True", "await", "hass", ".", "services", ".", "async_call", "(", "\"notify\"", ",", "\"sqs_test\"", ",", "{", "\"message\"", ":", "\"test\"", ",", "\"target\"", ":", "\"ARN\"", "}", ",", "blocking", "=", "True", ")" ]
[ 163, 0 ]
[ 194, 5 ]
python
en
['en', 'en', 'en']
True
test_notify_credential_profile
(hass)
Test notify service can use profile directly.
Test notify service can use profile directly.
async def test_notify_credential_profile(hass): """Test notify service can use profile directly.""" with async_patch("aiobotocore.AioSession", new=MockAioSession): await async_setup_component( hass, "aws", { "aws": { "notify": [ { "service": "sqs", "name": "SQS Test", "region_name": "us-east-1", "profile_name": "test", } ] } }, ) await hass.async_block_till_done() sessions = hass.data[aws.DATA_SESSIONS] assert sessions is not None assert len(sessions) == 1 assert isinstance(sessions.get("default"), MockAioSession) assert hass.services.has_service("notify", "sqs_test") is True await hass.services.async_call( "notify", "sqs_test", {"message": "test", "target": "ARN"}, blocking=True )
[ "async", "def", "test_notify_credential_profile", "(", "hass", ")", ":", "with", "async_patch", "(", "\"aiobotocore.AioSession\"", ",", "new", "=", "MockAioSession", ")", ":", "await", "async_setup_component", "(", "hass", ",", "\"aws\"", ",", "{", "\"aws\"", ":", "{", "\"notify\"", ":", "[", "{", "\"service\"", ":", "\"sqs\"", ",", "\"name\"", ":", "\"SQS Test\"", ",", "\"region_name\"", ":", "\"us-east-1\"", ",", "\"profile_name\"", ":", "\"test\"", ",", "}", "]", "}", "}", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "sessions", "=", "hass", ".", "data", "[", "aws", ".", "DATA_SESSIONS", "]", "assert", "sessions", "is", "not", "None", "assert", "len", "(", "sessions", ")", "==", "1", "assert", "isinstance", "(", "sessions", ".", "get", "(", "\"default\"", ")", ",", "MockAioSession", ")", "assert", "hass", ".", "services", ".", "has_service", "(", "\"notify\"", ",", "\"sqs_test\"", ")", "is", "True", "await", "hass", ".", "services", ".", "async_call", "(", "\"notify\"", ",", "\"sqs_test\"", ",", "{", "\"message\"", ":", "\"test\"", ",", "\"target\"", ":", "\"ARN\"", "}", ",", "blocking", "=", "True", ")" ]
[ 197, 0 ]
[ 226, 5 ]
python
en
['en', 'en', 'en']
True