Search is not available for this dataset
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 |
---|---|---|---|---|---|---|---|---|---|---|---|
GenericThermostat._async_heater_turn_on | (self) | Turn heater toggleable device on. | Turn heater toggleable device on. | async def _async_heater_turn_on(self):
"""Turn heater toggleable device on."""
data = {ATTR_ENTITY_ID: self.heater_entity_id}
await self.hass.services.async_call(
HA_DOMAIN, SERVICE_TURN_ON, data, context=self._context
) | [
"async",
"def",
"_async_heater_turn_on",
"(",
"self",
")",
":",
"data",
"=",
"{",
"ATTR_ENTITY_ID",
":",
"self",
".",
"heater_entity_id",
"}",
"await",
"self",
".",
"hass",
".",
"services",
".",
"async_call",
"(",
"HA_DOMAIN",
",",
"SERVICE_TURN_ON",
",",
"data",
",",
"context",
"=",
"self",
".",
"_context",
")"
] | [
462,
4
] | [
467,
9
] | python | en | ['nl', 'en', 'en'] | True |
GenericThermostat._async_heater_turn_off | (self) | Turn heater toggleable device off. | Turn heater toggleable device off. | async def _async_heater_turn_off(self):
"""Turn heater toggleable device off."""
data = {ATTR_ENTITY_ID: self.heater_entity_id}
await self.hass.services.async_call(
HA_DOMAIN, SERVICE_TURN_OFF, data, context=self._context
) | [
"async",
"def",
"_async_heater_turn_off",
"(",
"self",
")",
":",
"data",
"=",
"{",
"ATTR_ENTITY_ID",
":",
"self",
".",
"heater_entity_id",
"}",
"await",
"self",
".",
"hass",
".",
"services",
".",
"async_call",
"(",
"HA_DOMAIN",
",",
"SERVICE_TURN_OFF",
",",
"data",
",",
"context",
"=",
"self",
".",
"_context",
")"
] | [
469,
4
] | [
474,
9
] | python | en | ['nl', 'en', 'en'] | True |
GenericThermostat.async_set_preset_mode | (self, preset_mode: str) | Set new preset mode. | Set new preset mode. | async def async_set_preset_mode(self, preset_mode: str):
"""Set new preset mode."""
if preset_mode == PRESET_AWAY and not self._is_away:
self._is_away = True
self._saved_target_temp = self._target_temp
self._target_temp = self._away_temp
await self._async_control_heating(force=True)
elif preset_mode == PRESET_NONE and self._is_away:
self._is_away = False
self._target_temp = self._saved_target_temp
await self._async_control_heating(force=True)
self.async_write_ha_state() | [
"async",
"def",
"async_set_preset_mode",
"(",
"self",
",",
"preset_mode",
":",
"str",
")",
":",
"if",
"preset_mode",
"==",
"PRESET_AWAY",
"and",
"not",
"self",
".",
"_is_away",
":",
"self",
".",
"_is_away",
"=",
"True",
"self",
".",
"_saved_target_temp",
"=",
"self",
".",
"_target_temp",
"self",
".",
"_target_temp",
"=",
"self",
".",
"_away_temp",
"await",
"self",
".",
"_async_control_heating",
"(",
"force",
"=",
"True",
")",
"elif",
"preset_mode",
"==",
"PRESET_NONE",
"and",
"self",
".",
"_is_away",
":",
"self",
".",
"_is_away",
"=",
"False",
"self",
".",
"_target_temp",
"=",
"self",
".",
"_saved_target_temp",
"await",
"self",
".",
"_async_control_heating",
"(",
"force",
"=",
"True",
")",
"self",
".",
"async_write_ha_state",
"(",
")"
] | [
476,
4
] | [
488,
35
] | python | en | ['en', 'sr', 'en'] | True |
dist | (proxy: Proxy, handler_dict: {object: Callable}) |
A decorator used to inject a ``communication module`` and ``message handlers``
to a local class so that it can be run in distributed mode.
|
A decorator used to inject a ``communication module`` and ``message handlers``
to a local class so that it can be run in distributed mode.
| def dist(proxy: Proxy, handler_dict: {object: Callable}):
"""
A decorator used to inject a ``communication module`` and ``message handlers``
to a local class so that it can be run in distributed mode.
"""
def dist_decorator(cls):
class Wrapper:
"""A wrapper class for ``cls``, the class to be decorated.
It contains a reference to the ``proxy`` and a ``message handler`` lookup table and defines a launch method
as the universal entry point for running a ``cls`` instance in distributed mode.
"""
def __init__(self, *args, **kwargs):
self.local_instance = cls(*args, **kwargs)
self.proxy = proxy
self._handler_function = {}
self._registry_table = RegisterTable(self.proxy.peers_name)
# Use functools.partial to freeze handling function's local_instance and proxy
# arguments to self.local_instance and self.proxy.
for constraint, handler_fun in handler_dict.items():
self._handler_function[handler_fun] = partial(handler_fun, self.local_instance, self.proxy)
self._registry_table.register_event_handler(constraint, handler_fun)
def __getattr__(self, name):
if name in self.__dict__:
return self.__dict__[name]
return getattr(self.local_instance, name)
def launch(self):
"""Universal entry point for running a ``cls`` instance in distributed mode."""
for message in self.proxy.receive():
self._registry_table.push(message)
triggered_event = self._registry_table.get()
for handler_fun, message_list in triggered_event:
self._handler_function[handler_fun](message_list)
return Wrapper
return dist_decorator | [
"def",
"dist",
"(",
"proxy",
":",
"Proxy",
",",
"handler_dict",
":",
"{",
"object",
":",
"Callable",
"}",
")",
":",
"def",
"dist_decorator",
"(",
"cls",
")",
":",
"class",
"Wrapper",
":",
"\"\"\"A wrapper class for ``cls``, the class to be decorated.\n\n It contains a reference to the ``proxy`` and a ``message handler`` lookup table and defines a launch method\n as the universal entry point for running a ``cls`` instance in distributed mode.\n \"\"\"",
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"local_instance",
"=",
"cls",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"proxy",
"=",
"proxy",
"self",
".",
"_handler_function",
"=",
"{",
"}",
"self",
".",
"_registry_table",
"=",
"RegisterTable",
"(",
"self",
".",
"proxy",
".",
"peers_name",
")",
"# Use functools.partial to freeze handling function's local_instance and proxy",
"# arguments to self.local_instance and self.proxy.",
"for",
"constraint",
",",
"handler_fun",
"in",
"handler_dict",
".",
"items",
"(",
")",
":",
"self",
".",
"_handler_function",
"[",
"handler_fun",
"]",
"=",
"partial",
"(",
"handler_fun",
",",
"self",
".",
"local_instance",
",",
"self",
".",
"proxy",
")",
"self",
".",
"_registry_table",
".",
"register_event_handler",
"(",
"constraint",
",",
"handler_fun",
")",
"def",
"__getattr__",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"in",
"self",
".",
"__dict__",
":",
"return",
"self",
".",
"__dict__",
"[",
"name",
"]",
"return",
"getattr",
"(",
"self",
".",
"local_instance",
",",
"name",
")",
"def",
"launch",
"(",
"self",
")",
":",
"\"\"\"Universal entry point for running a ``cls`` instance in distributed mode.\"\"\"",
"for",
"message",
"in",
"self",
".",
"proxy",
".",
"receive",
"(",
")",
":",
"self",
".",
"_registry_table",
".",
"push",
"(",
"message",
")",
"triggered_event",
"=",
"self",
".",
"_registry_table",
".",
"get",
"(",
")",
"for",
"handler_fun",
",",
"message_list",
"in",
"triggered_event",
":",
"self",
".",
"_handler_function",
"[",
"handler_fun",
"]",
"(",
"message_list",
")",
"return",
"Wrapper",
"return",
"dist_decorator"
] | [
12,
0
] | [
52,
25
] | python | en | ['en', 'error', 'th'] | False |
setup_platform | (hass, config, add_entities, discovery_info=None) | Set up the USGS Earthquake Hazards Program Feed platform. | Set up the USGS Earthquake Hazards Program Feed platform. | def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the USGS Earthquake Hazards Program Feed platform."""
scan_interval = config.get(CONF_SCAN_INTERVAL, SCAN_INTERVAL)
feed_type = config[CONF_FEED_TYPE]
coordinates = (
config.get(CONF_LATITUDE, hass.config.latitude),
config.get(CONF_LONGITUDE, hass.config.longitude),
)
radius_in_km = config[CONF_RADIUS]
minimum_magnitude = config[CONF_MINIMUM_MAGNITUDE]
# Initialize the entity manager.
feed = UsgsEarthquakesFeedEntityManager(
hass,
add_entities,
scan_interval,
coordinates,
feed_type,
radius_in_km,
minimum_magnitude,
)
def start_feed_manager(event):
"""Start feed manager."""
feed.startup()
hass.bus.listen_once(EVENT_HOMEASSISTANT_START, start_feed_manager) | [
"def",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"scan_interval",
"=",
"config",
".",
"get",
"(",
"CONF_SCAN_INTERVAL",
",",
"SCAN_INTERVAL",
")",
"feed_type",
"=",
"config",
"[",
"CONF_FEED_TYPE",
"]",
"coordinates",
"=",
"(",
"config",
".",
"get",
"(",
"CONF_LATITUDE",
",",
"hass",
".",
"config",
".",
"latitude",
")",
",",
"config",
".",
"get",
"(",
"CONF_LONGITUDE",
",",
"hass",
".",
"config",
".",
"longitude",
")",
",",
")",
"radius_in_km",
"=",
"config",
"[",
"CONF_RADIUS",
"]",
"minimum_magnitude",
"=",
"config",
"[",
"CONF_MINIMUM_MAGNITUDE",
"]",
"# Initialize the entity manager.",
"feed",
"=",
"UsgsEarthquakesFeedEntityManager",
"(",
"hass",
",",
"add_entities",
",",
"scan_interval",
",",
"coordinates",
",",
"feed_type",
",",
"radius_in_km",
",",
"minimum_magnitude",
",",
")",
"def",
"start_feed_manager",
"(",
"event",
")",
":",
"\"\"\"Start feed manager.\"\"\"",
"feed",
".",
"startup",
"(",
")",
"hass",
".",
"bus",
".",
"listen_once",
"(",
"EVENT_HOMEASSISTANT_START",
",",
"start_feed_manager",
")"
] | [
86,
0
] | [
111,
71
] | python | en | ['en', 'da', 'en'] | True |
UsgsEarthquakesFeedEntityManager.__init__ | (
self,
hass,
add_entities,
scan_interval,
coordinates,
feed_type,
radius_in_km,
minimum_magnitude,
) | Initialize the Feed Entity Manager. | Initialize the Feed Entity Manager. | def __init__(
self,
hass,
add_entities,
scan_interval,
coordinates,
feed_type,
radius_in_km,
minimum_magnitude,
):
"""Initialize the Feed Entity Manager."""
self._hass = hass
self._feed_manager = UsgsEarthquakeHazardsProgramFeedManager(
self._generate_entity,
self._update_entity,
self._remove_entity,
coordinates,
feed_type,
filter_radius=radius_in_km,
filter_minimum_magnitude=minimum_magnitude,
)
self._add_entities = add_entities
self._scan_interval = scan_interval | [
"def",
"__init__",
"(",
"self",
",",
"hass",
",",
"add_entities",
",",
"scan_interval",
",",
"coordinates",
",",
"feed_type",
",",
"radius_in_km",
",",
"minimum_magnitude",
",",
")",
":",
"self",
".",
"_hass",
"=",
"hass",
"self",
".",
"_feed_manager",
"=",
"UsgsEarthquakeHazardsProgramFeedManager",
"(",
"self",
".",
"_generate_entity",
",",
"self",
".",
"_update_entity",
",",
"self",
".",
"_remove_entity",
",",
"coordinates",
",",
"feed_type",
",",
"filter_radius",
"=",
"radius_in_km",
",",
"filter_minimum_magnitude",
"=",
"minimum_magnitude",
",",
")",
"self",
".",
"_add_entities",
"=",
"add_entities",
"self",
".",
"_scan_interval",
"=",
"scan_interval"
] | [
117,
4
] | [
140,
43
] | python | en | ['en', 'en', 'en'] | True |
UsgsEarthquakesFeedEntityManager.startup | (self) | Start up this manager. | Start up this manager. | def startup(self):
"""Start up this manager."""
self._feed_manager.update()
self._init_regular_updates() | [
"def",
"startup",
"(",
"self",
")",
":",
"self",
".",
"_feed_manager",
".",
"update",
"(",
")",
"self",
".",
"_init_regular_updates",
"(",
")"
] | [
142,
4
] | [
145,
36
] | python | en | ['en', 'en', 'en'] | True |
UsgsEarthquakesFeedEntityManager._init_regular_updates | (self) | Schedule regular updates at the specified interval. | Schedule regular updates at the specified interval. | def _init_regular_updates(self):
"""Schedule regular updates at the specified interval."""
track_time_interval(
self._hass, lambda now: self._feed_manager.update(), self._scan_interval
) | [
"def",
"_init_regular_updates",
"(",
"self",
")",
":",
"track_time_interval",
"(",
"self",
".",
"_hass",
",",
"lambda",
"now",
":",
"self",
".",
"_feed_manager",
".",
"update",
"(",
")",
",",
"self",
".",
"_scan_interval",
")"
] | [
147,
4
] | [
151,
9
] | python | en | ['en', 'en', 'en'] | True |
UsgsEarthquakesFeedEntityManager.get_entry | (self, external_id) | Get feed entry by external id. | Get feed entry by external id. | def get_entry(self, external_id):
"""Get feed entry by external id."""
return self._feed_manager.feed_entries.get(external_id) | [
"def",
"get_entry",
"(",
"self",
",",
"external_id",
")",
":",
"return",
"self",
".",
"_feed_manager",
".",
"feed_entries",
".",
"get",
"(",
"external_id",
")"
] | [
153,
4
] | [
155,
63
] | python | en | ['en', 'en', 'en'] | True |
UsgsEarthquakesFeedEntityManager._generate_entity | (self, external_id) | Generate new entity. | Generate new entity. | def _generate_entity(self, external_id):
"""Generate new entity."""
new_entity = UsgsEarthquakesEvent(self, external_id)
# Add new entities to HA.
self._add_entities([new_entity], True) | [
"def",
"_generate_entity",
"(",
"self",
",",
"external_id",
")",
":",
"new_entity",
"=",
"UsgsEarthquakesEvent",
"(",
"self",
",",
"external_id",
")",
"# Add new entities to HA.",
"self",
".",
"_add_entities",
"(",
"[",
"new_entity",
"]",
",",
"True",
")"
] | [
157,
4
] | [
161,
46
] | python | en | ['en', 'en', 'en'] | True |
UsgsEarthquakesFeedEntityManager._update_entity | (self, external_id) | Update entity. | Update entity. | def _update_entity(self, external_id):
"""Update entity."""
dispatcher_send(self._hass, SIGNAL_UPDATE_ENTITY.format(external_id)) | [
"def",
"_update_entity",
"(",
"self",
",",
"external_id",
")",
":",
"dispatcher_send",
"(",
"self",
".",
"_hass",
",",
"SIGNAL_UPDATE_ENTITY",
".",
"format",
"(",
"external_id",
")",
")"
] | [
163,
4
] | [
165,
77
] | python | en | ['es', 'en', 'en'] | False |
UsgsEarthquakesFeedEntityManager._remove_entity | (self, external_id) | Remove entity. | Remove entity. | def _remove_entity(self, external_id):
"""Remove entity."""
dispatcher_send(self._hass, SIGNAL_DELETE_ENTITY.format(external_id)) | [
"def",
"_remove_entity",
"(",
"self",
",",
"external_id",
")",
":",
"dispatcher_send",
"(",
"self",
".",
"_hass",
",",
"SIGNAL_DELETE_ENTITY",
".",
"format",
"(",
"external_id",
")",
")"
] | [
167,
4
] | [
169,
77
] | python | en | ['es', 'it', 'en'] | False |
UsgsEarthquakesEvent.__init__ | (self, feed_manager, external_id) | Initialize entity with data from feed entry. | Initialize entity with data from feed entry. | def __init__(self, feed_manager, external_id):
"""Initialize entity with data from feed entry."""
self._feed_manager = feed_manager
self._external_id = external_id
self._name = None
self._distance = None
self._latitude = None
self._longitude = None
self._attribution = None
self._place = None
self._magnitude = None
self._time = None
self._updated = None
self._status = None
self._type = None
self._alert = None
self._remove_signal_delete = None
self._remove_signal_update = None | [
"def",
"__init__",
"(",
"self",
",",
"feed_manager",
",",
"external_id",
")",
":",
"self",
".",
"_feed_manager",
"=",
"feed_manager",
"self",
".",
"_external_id",
"=",
"external_id",
"self",
".",
"_name",
"=",
"None",
"self",
".",
"_distance",
"=",
"None",
"self",
".",
"_latitude",
"=",
"None",
"self",
".",
"_longitude",
"=",
"None",
"self",
".",
"_attribution",
"=",
"None",
"self",
".",
"_place",
"=",
"None",
"self",
".",
"_magnitude",
"=",
"None",
"self",
".",
"_time",
"=",
"None",
"self",
".",
"_updated",
"=",
"None",
"self",
".",
"_status",
"=",
"None",
"self",
".",
"_type",
"=",
"None",
"self",
".",
"_alert",
"=",
"None",
"self",
".",
"_remove_signal_delete",
"=",
"None",
"self",
".",
"_remove_signal_update",
"=",
"None"
] | [
175,
4
] | [
192,
41
] | python | en | ['en', 'en', 'en'] | True |
UsgsEarthquakesEvent.async_added_to_hass | (self) | Call when entity is added to hass. | Call when entity is added to hass. | async def async_added_to_hass(self):
"""Call when entity is added to hass."""
self._remove_signal_delete = async_dispatcher_connect(
self.hass,
SIGNAL_DELETE_ENTITY.format(self._external_id),
self._delete_callback,
)
self._remove_signal_update = async_dispatcher_connect(
self.hass,
SIGNAL_UPDATE_ENTITY.format(self._external_id),
self._update_callback,
) | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
":",
"self",
".",
"_remove_signal_delete",
"=",
"async_dispatcher_connect",
"(",
"self",
".",
"hass",
",",
"SIGNAL_DELETE_ENTITY",
".",
"format",
"(",
"self",
".",
"_external_id",
")",
",",
"self",
".",
"_delete_callback",
",",
")",
"self",
".",
"_remove_signal_update",
"=",
"async_dispatcher_connect",
"(",
"self",
".",
"hass",
",",
"SIGNAL_UPDATE_ENTITY",
".",
"format",
"(",
"self",
".",
"_external_id",
")",
",",
"self",
".",
"_update_callback",
",",
")"
] | [
194,
4
] | [
205,
9
] | python | en | ['en', 'en', 'en'] | True |
UsgsEarthquakesEvent._delete_callback | (self) | Remove this entity. | Remove this entity. | def _delete_callback(self):
"""Remove this entity."""
self._remove_signal_delete()
self._remove_signal_update()
self.hass.async_create_task(self.async_remove()) | [
"def",
"_delete_callback",
"(",
"self",
")",
":",
"self",
".",
"_remove_signal_delete",
"(",
")",
"self",
".",
"_remove_signal_update",
"(",
")",
"self",
".",
"hass",
".",
"async_create_task",
"(",
"self",
".",
"async_remove",
"(",
")",
")"
] | [
208,
4
] | [
212,
56
] | python | en | ['en', 'en', 'en'] | True |
UsgsEarthquakesEvent._update_callback | (self) | Call update method. | Call update method. | def _update_callback(self):
"""Call update method."""
self.async_schedule_update_ha_state(True) | [
"def",
"_update_callback",
"(",
"self",
")",
":",
"self",
".",
"async_schedule_update_ha_state",
"(",
"True",
")"
] | [
215,
4
] | [
217,
49
] | python | en | ['en', 'sn', 'en'] | True |
UsgsEarthquakesEvent.should_poll | (self) | No polling needed for USGS Earthquake events. | No polling needed for USGS Earthquake events. | def should_poll(self):
"""No polling needed for USGS Earthquake events."""
return False | [
"def",
"should_poll",
"(",
"self",
")",
":",
"return",
"False"
] | [
220,
4
] | [
222,
20
] | python | en | ['en', 'en', 'en'] | True |
UsgsEarthquakesEvent.async_update | (self) | Update this entity from the data held in the feed manager. | Update this entity from the data held in the feed manager. | async def async_update(self):
"""Update this entity from the data held in the feed manager."""
_LOGGER.debug("Updating %s", self._external_id)
feed_entry = self._feed_manager.get_entry(self._external_id)
if feed_entry:
self._update_from_feed(feed_entry) | [
"async",
"def",
"async_update",
"(",
"self",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Updating %s\"",
",",
"self",
".",
"_external_id",
")",
"feed_entry",
"=",
"self",
".",
"_feed_manager",
".",
"get_entry",
"(",
"self",
".",
"_external_id",
")",
"if",
"feed_entry",
":",
"self",
".",
"_update_from_feed",
"(",
"feed_entry",
")"
] | [
224,
4
] | [
229,
46
] | python | en | ['en', 'en', 'en'] | True |
UsgsEarthquakesEvent._update_from_feed | (self, feed_entry) | Update the internal state from the provided feed entry. | Update the internal state from the provided feed entry. | def _update_from_feed(self, feed_entry):
"""Update the internal state from the provided feed entry."""
self._name = feed_entry.title
self._distance = feed_entry.distance_to_home
self._latitude = feed_entry.coordinates[0]
self._longitude = feed_entry.coordinates[1]
self._attribution = feed_entry.attribution
self._place = feed_entry.place
self._magnitude = feed_entry.magnitude
self._time = feed_entry.time
self._updated = feed_entry.updated
self._status = feed_entry.status
self._type = feed_entry.type
self._alert = feed_entry.alert | [
"def",
"_update_from_feed",
"(",
"self",
",",
"feed_entry",
")",
":",
"self",
".",
"_name",
"=",
"feed_entry",
".",
"title",
"self",
".",
"_distance",
"=",
"feed_entry",
".",
"distance_to_home",
"self",
".",
"_latitude",
"=",
"feed_entry",
".",
"coordinates",
"[",
"0",
"]",
"self",
".",
"_longitude",
"=",
"feed_entry",
".",
"coordinates",
"[",
"1",
"]",
"self",
".",
"_attribution",
"=",
"feed_entry",
".",
"attribution",
"self",
".",
"_place",
"=",
"feed_entry",
".",
"place",
"self",
".",
"_magnitude",
"=",
"feed_entry",
".",
"magnitude",
"self",
".",
"_time",
"=",
"feed_entry",
".",
"time",
"self",
".",
"_updated",
"=",
"feed_entry",
".",
"updated",
"self",
".",
"_status",
"=",
"feed_entry",
".",
"status",
"self",
".",
"_type",
"=",
"feed_entry",
".",
"type",
"self",
".",
"_alert",
"=",
"feed_entry",
".",
"alert"
] | [
231,
4
] | [
244,
38
] | python | en | ['en', 'en', 'en'] | True |
UsgsEarthquakesEvent.icon | (self) | Return the icon to use in the frontend. | Return the icon to use in the frontend. | def icon(self):
"""Return the icon to use in the frontend."""
return "mdi:pulse" | [
"def",
"icon",
"(",
"self",
")",
":",
"return",
"\"mdi:pulse\""
] | [
247,
4
] | [
249,
26
] | python | en | ['en', 'en', 'en'] | True |
UsgsEarthquakesEvent.source | (self) | Return source value of this external event. | Return source value of this external event. | def source(self) -> str:
"""Return source value of this external event."""
return SOURCE | [
"def",
"source",
"(",
"self",
")",
"->",
"str",
":",
"return",
"SOURCE"
] | [
252,
4
] | [
254,
21
] | python | en | ['en', 'en', 'en'] | True |
UsgsEarthquakesEvent.name | (self) | Return the name of the entity. | Return the name of the entity. | def name(self) -> Optional[str]:
"""Return the name of the entity."""
return self._name | [
"def",
"name",
"(",
"self",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"return",
"self",
".",
"_name"
] | [
257,
4
] | [
259,
25
] | python | en | ['en', 'en', 'en'] | True |
UsgsEarthquakesEvent.distance | (self) | Return distance value of this external event. | Return distance value of this external event. | def distance(self) -> Optional[float]:
"""Return distance value of this external event."""
return self._distance | [
"def",
"distance",
"(",
"self",
")",
"->",
"Optional",
"[",
"float",
"]",
":",
"return",
"self",
".",
"_distance"
] | [
262,
4
] | [
264,
29
] | python | en | ['en', 'en', 'en'] | True |
UsgsEarthquakesEvent.latitude | (self) | Return latitude value of this external event. | Return latitude value of this external event. | def latitude(self) -> Optional[float]:
"""Return latitude value of this external event."""
return self._latitude | [
"def",
"latitude",
"(",
"self",
")",
"->",
"Optional",
"[",
"float",
"]",
":",
"return",
"self",
".",
"_latitude"
] | [
267,
4
] | [
269,
29
] | python | en | ['en', 'la', 'en'] | True |
UsgsEarthquakesEvent.longitude | (self) | Return longitude value of this external event. | Return longitude value of this external event. | def longitude(self) -> Optional[float]:
"""Return longitude value of this external event."""
return self._longitude | [
"def",
"longitude",
"(",
"self",
")",
"->",
"Optional",
"[",
"float",
"]",
":",
"return",
"self",
".",
"_longitude"
] | [
272,
4
] | [
274,
30
] | python | en | ['en', 'en', 'en'] | True |
UsgsEarthquakesEvent.unit_of_measurement | (self) | Return the unit of measurement. | Return the unit of measurement. | def unit_of_measurement(self):
"""Return the unit of measurement."""
return DEFAULT_UNIT_OF_MEASUREMENT | [
"def",
"unit_of_measurement",
"(",
"self",
")",
":",
"return",
"DEFAULT_UNIT_OF_MEASUREMENT"
] | [
277,
4
] | [
279,
42
] | python | en | ['en', 'la', 'en'] | True |
UsgsEarthquakesEvent.device_state_attributes | (self) | Return the device state attributes. | Return the device state attributes. | def device_state_attributes(self):
"""Return the device state attributes."""
attributes = {}
for key, value in (
(ATTR_EXTERNAL_ID, self._external_id),
(ATTR_PLACE, self._place),
(ATTR_MAGNITUDE, self._magnitude),
(ATTR_TIME, self._time),
(ATTR_UPDATED, self._updated),
(ATTR_STATUS, self._status),
(ATTR_TYPE, self._type),
(ATTR_ALERT, self._alert),
(ATTR_ATTRIBUTION, self._attribution),
):
if value or isinstance(value, bool):
attributes[key] = value
return attributes | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"attributes",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"(",
"(",
"ATTR_EXTERNAL_ID",
",",
"self",
".",
"_external_id",
")",
",",
"(",
"ATTR_PLACE",
",",
"self",
".",
"_place",
")",
",",
"(",
"ATTR_MAGNITUDE",
",",
"self",
".",
"_magnitude",
")",
",",
"(",
"ATTR_TIME",
",",
"self",
".",
"_time",
")",
",",
"(",
"ATTR_UPDATED",
",",
"self",
".",
"_updated",
")",
",",
"(",
"ATTR_STATUS",
",",
"self",
".",
"_status",
")",
",",
"(",
"ATTR_TYPE",
",",
"self",
".",
"_type",
")",
",",
"(",
"ATTR_ALERT",
",",
"self",
".",
"_alert",
")",
",",
"(",
"ATTR_ATTRIBUTION",
",",
"self",
".",
"_attribution",
")",
",",
")",
":",
"if",
"value",
"or",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"attributes",
"[",
"key",
"]",
"=",
"value",
"return",
"attributes"
] | [
282,
4
] | [
298,
25
] | python | en | ['en', 'en', 'en'] | True |
create_mnist_model | (hyper_params, input_shape=(H, W, 1), num_classes=NUM_CLASSES) |
Create simple convolutional model
|
Create simple convolutional model
| def create_mnist_model(hyper_params, input_shape=(H, W, 1), num_classes=NUM_CLASSES):
'''
Create simple convolutional model
'''
layers = [
Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape),
Conv2D(64, (3, 3), activation='relu'),
MaxPooling2D(pool_size=(2, 2)),
Flatten(),
Dense(100, activation='relu'),
Dense(num_classes, activation='softmax')
]
model = Sequential(layers)
if hyper_params['optimizer'] == 'Adam':
optimizer = keras.optimizers.Adam(lr=hyper_params['learning_rate'])
else:
optimizer = keras.optimizers.SGD(lr=hyper_params['learning_rate'], momentum=0.9)
model.compile(loss=keras.losses.categorical_crossentropy, optimizer=optimizer, metrics=['accuracy'])
return model | [
"def",
"create_mnist_model",
"(",
"hyper_params",
",",
"input_shape",
"=",
"(",
"H",
",",
"W",
",",
"1",
")",
",",
"num_classes",
"=",
"NUM_CLASSES",
")",
":",
"layers",
"=",
"[",
"Conv2D",
"(",
"32",
",",
"kernel_size",
"=",
"(",
"3",
",",
"3",
")",
",",
"activation",
"=",
"'relu'",
",",
"input_shape",
"=",
"input_shape",
")",
",",
"Conv2D",
"(",
"64",
",",
"(",
"3",
",",
"3",
")",
",",
"activation",
"=",
"'relu'",
")",
",",
"MaxPooling2D",
"(",
"pool_size",
"=",
"(",
"2",
",",
"2",
")",
")",
",",
"Flatten",
"(",
")",
",",
"Dense",
"(",
"100",
",",
"activation",
"=",
"'relu'",
")",
",",
"Dense",
"(",
"num_classes",
",",
"activation",
"=",
"'softmax'",
")",
"]",
"model",
"=",
"Sequential",
"(",
"layers",
")",
"if",
"hyper_params",
"[",
"'optimizer'",
"]",
"==",
"'Adam'",
":",
"optimizer",
"=",
"keras",
".",
"optimizers",
".",
"Adam",
"(",
"lr",
"=",
"hyper_params",
"[",
"'learning_rate'",
"]",
")",
"else",
":",
"optimizer",
"=",
"keras",
".",
"optimizers",
".",
"SGD",
"(",
"lr",
"=",
"hyper_params",
"[",
"'learning_rate'",
"]",
",",
"momentum",
"=",
"0.9",
")",
"model",
".",
"compile",
"(",
"loss",
"=",
"keras",
".",
"losses",
".",
"categorical_crossentropy",
",",
"optimizer",
"=",
"optimizer",
",",
"metrics",
"=",
"[",
"'accuracy'",
"]",
")",
"return",
"model"
] | [
38,
0
] | [
59,
16
] | python | en | ['en', 'error', 'th'] | False |
load_mnist_data | (args) |
Load MNIST dataset
|
Load MNIST dataset
| def load_mnist_data(args):
'''
Load MNIST dataset
'''
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = (np.expand_dims(x_train, -1).astype(np.float) / 255.)[:args.num_train]
x_test = (np.expand_dims(x_test, -1).astype(np.float) / 255.)[:args.num_test]
y_train = keras.utils.to_categorical(y_train, NUM_CLASSES)[:args.num_train]
y_test = keras.utils.to_categorical(y_test, NUM_CLASSES)[:args.num_test]
LOG.debug('x_train shape: %s', (x_train.shape,))
LOG.debug('x_test shape: %s', (x_test.shape,))
return x_train, y_train, x_test, y_test | [
"def",
"load_mnist_data",
"(",
"args",
")",
":",
"(",
"x_train",
",",
"y_train",
")",
",",
"(",
"x_test",
",",
"y_test",
")",
"=",
"mnist",
".",
"load_data",
"(",
")",
"x_train",
"=",
"(",
"np",
".",
"expand_dims",
"(",
"x_train",
",",
"-",
"1",
")",
".",
"astype",
"(",
"np",
".",
"float",
")",
"/",
"255.",
")",
"[",
":",
"args",
".",
"num_train",
"]",
"x_test",
"=",
"(",
"np",
".",
"expand_dims",
"(",
"x_test",
",",
"-",
"1",
")",
".",
"astype",
"(",
"np",
".",
"float",
")",
"/",
"255.",
")",
"[",
":",
"args",
".",
"num_test",
"]",
"y_train",
"=",
"keras",
".",
"utils",
".",
"to_categorical",
"(",
"y_train",
",",
"NUM_CLASSES",
")",
"[",
":",
"args",
".",
"num_train",
"]",
"y_test",
"=",
"keras",
".",
"utils",
".",
"to_categorical",
"(",
"y_test",
",",
"NUM_CLASSES",
")",
"[",
":",
"args",
".",
"num_test",
"]",
"LOG",
".",
"debug",
"(",
"'x_train shape: %s'",
",",
"(",
"x_train",
".",
"shape",
",",
")",
")",
"LOG",
".",
"debug",
"(",
"'x_test shape: %s'",
",",
"(",
"x_test",
".",
"shape",
",",
")",
")",
"return",
"x_train",
",",
"y_train",
",",
"x_test",
",",
"y_test"
] | [
61,
0
] | [
75,
43
] | python | en | ['en', 'error', 'th'] | False |
train | (args, params) |
Train model
|
Train model
| def train(args, params):
'''
Train model
'''
x_train, y_train, x_test, y_test = load_mnist_data(args)
model = create_mnist_model(params)
# nni
model.fit(x_train, y_train, batch_size=args.batch_size, epochs=args.epochs, verbose=1,
validation_data=(x_test, y_test), callbacks=[SendMetrics(), TensorBoard(log_dir=TENSORBOARD_DIR)])
_, acc = model.evaluate(x_test, y_test, verbose=0)
LOG.debug('Final result is: %d', acc)
nni.report_final_result(acc) | [
"def",
"train",
"(",
"args",
",",
"params",
")",
":",
"x_train",
",",
"y_train",
",",
"x_test",
",",
"y_test",
"=",
"load_mnist_data",
"(",
"args",
")",
"model",
"=",
"create_mnist_model",
"(",
"params",
")",
"# nni",
"model",
".",
"fit",
"(",
"x_train",
",",
"y_train",
",",
"batch_size",
"=",
"args",
".",
"batch_size",
",",
"epochs",
"=",
"args",
".",
"epochs",
",",
"verbose",
"=",
"1",
",",
"validation_data",
"=",
"(",
"x_test",
",",
"y_test",
")",
",",
"callbacks",
"=",
"[",
"SendMetrics",
"(",
")",
",",
"TensorBoard",
"(",
"log_dir",
"=",
"TENSORBOARD_DIR",
")",
"]",
")",
"_",
",",
"acc",
"=",
"model",
".",
"evaluate",
"(",
"x_test",
",",
"y_test",
",",
"verbose",
"=",
"0",
")",
"LOG",
".",
"debug",
"(",
"'Final result is: %d'",
",",
"acc",
")",
"nni",
".",
"report_final_result",
"(",
"acc",
")"
] | [
92,
0
] | [
105,
32
] | python | en | ['en', 'error', 'th'] | False |
generate_default_params | () |
Generate default hyper parameters
|
Generate default hyper parameters
| def generate_default_params():
'''
Generate default hyper parameters
'''
return {
'optimizer': 'Adam',
'learning_rate': 0.001
} | [
"def",
"generate_default_params",
"(",
")",
":",
"return",
"{",
"'optimizer'",
":",
"'Adam'",
",",
"'learning_rate'",
":",
"0.001",
"}"
] | [
107,
0
] | [
114,
5
] | python | en | ['en', 'error', 'th'] | False |
SendMetrics.on_epoch_end | (self, epoch, logs={}) |
Run on end of each epoch
|
Run on end of each epoch
| def on_epoch_end(self, epoch, logs={}):
'''
Run on end of each epoch
'''
LOG.debug(logs)
# TensorFlow 2.0 API reference claims the key is `val_acc`, but in fact it's `val_accuracy`
if 'val_acc' in logs:
nni.report_intermediate_result(logs['val_acc'])
else:
nni.report_intermediate_result(logs['val_accuracy']) | [
"def",
"on_epoch_end",
"(",
"self",
",",
"epoch",
",",
"logs",
"=",
"{",
"}",
")",
":",
"LOG",
".",
"debug",
"(",
"logs",
")",
"# TensorFlow 2.0 API reference claims the key is `val_acc`, but in fact it's `val_accuracy`",
"if",
"'val_acc'",
"in",
"logs",
":",
"nni",
".",
"report_intermediate_result",
"(",
"logs",
"[",
"'val_acc'",
"]",
")",
"else",
":",
"nni",
".",
"report_intermediate_result",
"(",
"logs",
"[",
"'val_accuracy'",
"]",
")"
] | [
81,
4
] | [
90,
64
] | python | en | ['en', 'error', 'th'] | False |
AlbertTokenizerFast.build_inputs_with_special_tokens | (
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
) |
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
adding special tokens. An ALBERT sequence has the following format:
- single sequence: ``[CLS] X [SEP]``
- pair of sequences: ``[CLS] A [SEP] B [SEP]``
Args:
token_ids_0 (:obj:`List[int]`):
List of IDs to which the special tokens will be added
token_ids_1 (:obj:`List[int]`, `optional`, defaults to :obj:`None`):
Optional second list of IDs for sequence pairs.
Returns:
:obj:`List[int]`: list of `input IDs <../glossary.html#input-ids>`__ with the appropriate special tokens.
|
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
adding special tokens. An ALBERT sequence has the following format: | def build_inputs_with_special_tokens(
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
) -> List[int]:
"""
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
adding special tokens. An ALBERT sequence has the following format:
- single sequence: ``[CLS] X [SEP]``
- pair of sequences: ``[CLS] A [SEP] B [SEP]``
Args:
token_ids_0 (:obj:`List[int]`):
List of IDs to which the special tokens will be added
token_ids_1 (:obj:`List[int]`, `optional`, defaults to :obj:`None`):
Optional second list of IDs for sequence pairs.
Returns:
:obj:`List[int]`: list of `input IDs <../glossary.html#input-ids>`__ with the appropriate special tokens.
"""
sep = [self.sep_token_id]
cls = [self.cls_token_id]
if token_ids_1 is None:
return cls + token_ids_0 + sep
return cls + token_ids_0 + sep + token_ids_1 + sep | [
"def",
"build_inputs_with_special_tokens",
"(",
"self",
",",
"token_ids_0",
":",
"List",
"[",
"int",
"]",
",",
"token_ids_1",
":",
"Optional",
"[",
"List",
"[",
"int",
"]",
"]",
"=",
"None",
")",
"->",
"List",
"[",
"int",
"]",
":",
"sep",
"=",
"[",
"self",
".",
"sep_token_id",
"]",
"cls",
"=",
"[",
"self",
".",
"cls_token_id",
"]",
"if",
"token_ids_1",
"is",
"None",
":",
"return",
"cls",
"+",
"token_ids_0",
"+",
"sep",
"return",
"cls",
"+",
"token_ids_0",
"+",
"sep",
"+",
"token_ids_1",
"+",
"sep"
] | [
161,
4
] | [
184,
58
] | python | en | ['en', 'error', 'th'] | False |
AlbertTokenizerFast.get_special_tokens_mask | (
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
) |
Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
special tokens using the tokenizer ``prepare_for_model`` method.
Args:
token_ids_0 (:obj:`List[int]`):
List of ids.
token_ids_1 (:obj:`List[int]`, `optional`, defaults to :obj:`None`):
Optional second list of IDs for sequence pairs.
already_has_special_tokens (:obj:`bool`, `optional`, defaults to :obj:`False`):
Set to True if the token list is already formatted with special tokens for the model
Returns:
:obj:`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
special tokens using the tokenizer ``prepare_for_model`` method. | def get_special_tokens_mask(
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
) -> List[int]:
"""
Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
special tokens using the tokenizer ``prepare_for_model`` method.
Args:
token_ids_0 (:obj:`List[int]`):
List of ids.
token_ids_1 (:obj:`List[int]`, `optional`, defaults to :obj:`None`):
Optional second list of IDs for sequence pairs.
already_has_special_tokens (:obj:`bool`, `optional`, defaults to :obj:`False`):
Set to True if the token list is already formatted with special tokens for the model
Returns:
:obj:`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
"""
if already_has_special_tokens:
if token_ids_1 is not None:
raise ValueError(
"You should not supply a second sequence if the provided sequence of "
"ids is already formatted with special tokens for the model."
)
return list(map(lambda x: 1 if x in [self.sep_token_id, self.cls_token_id] else 0, token_ids_0))
if token_ids_1 is not None:
return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
return [1] + ([0] * len(token_ids_0)) + [1] | [
"def",
"get_special_tokens_mask",
"(",
"self",
",",
"token_ids_0",
":",
"List",
"[",
"int",
"]",
",",
"token_ids_1",
":",
"Optional",
"[",
"List",
"[",
"int",
"]",
"]",
"=",
"None",
",",
"already_has_special_tokens",
":",
"bool",
"=",
"False",
")",
"->",
"List",
"[",
"int",
"]",
":",
"if",
"already_has_special_tokens",
":",
"if",
"token_ids_1",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"\"You should not supply a second sequence if the provided sequence of \"",
"\"ids is already formatted with special tokens for the model.\"",
")",
"return",
"list",
"(",
"map",
"(",
"lambda",
"x",
":",
"1",
"if",
"x",
"in",
"[",
"self",
".",
"sep_token_id",
",",
"self",
".",
"cls_token_id",
"]",
"else",
"0",
",",
"token_ids_0",
")",
")",
"if",
"token_ids_1",
"is",
"not",
"None",
":",
"return",
"[",
"1",
"]",
"+",
"(",
"[",
"0",
"]",
"*",
"len",
"(",
"token_ids_0",
")",
")",
"+",
"[",
"1",
"]",
"+",
"(",
"[",
"0",
"]",
"*",
"len",
"(",
"token_ids_1",
")",
")",
"+",
"[",
"1",
"]",
"return",
"[",
"1",
"]",
"+",
"(",
"[",
"0",
"]",
"*",
"len",
"(",
"token_ids_0",
")",
")",
"+",
"[",
"1",
"]"
] | [
186,
4
] | [
215,
51
] | python | en | ['en', 'error', 'th'] | False |
AlbertTokenizerFast.create_token_type_ids_from_sequences | (
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
) |
Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
sequence pair mask has the following format:
::
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
| first sequence | second sequence |
if token_ids_1 is None, only returns the first portion of the mask (0s).
Args:
token_ids_0 (:obj:`List[int]`):
List of ids.
token_ids_1 (:obj:`List[int]`, `optional`, defaults to :obj:`None`):
Optional second list of IDs for sequence pairs.
Returns:
:obj:`List[int]`: List of `token type IDs <../glossary.html#token-type-ids>`_ according to the given
sequence(s).
|
Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
sequence pair mask has the following format: | def create_token_type_ids_from_sequences(
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
) -> List[int]:
"""
Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
sequence pair mask has the following format:
::
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
| first sequence | second sequence |
if token_ids_1 is None, only returns the first portion of the mask (0s).
Args:
token_ids_0 (:obj:`List[int]`):
List of ids.
token_ids_1 (:obj:`List[int]`, `optional`, defaults to :obj:`None`):
Optional second list of IDs for sequence pairs.
Returns:
:obj:`List[int]`: List of `token type IDs <../glossary.html#token-type-ids>`_ according to the given
sequence(s).
"""
sep = [self.sep_token_id]
cls = [self.cls_token_id]
if token_ids_1 is None:
return len(cls + token_ids_0 + sep) * [0]
return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1] | [
"def",
"create_token_type_ids_from_sequences",
"(",
"self",
",",
"token_ids_0",
":",
"List",
"[",
"int",
"]",
",",
"token_ids_1",
":",
"Optional",
"[",
"List",
"[",
"int",
"]",
"]",
"=",
"None",
")",
"->",
"List",
"[",
"int",
"]",
":",
"sep",
"=",
"[",
"self",
".",
"sep_token_id",
"]",
"cls",
"=",
"[",
"self",
".",
"cls_token_id",
"]",
"if",
"token_ids_1",
"is",
"None",
":",
"return",
"len",
"(",
"cls",
"+",
"token_ids_0",
"+",
"sep",
")",
"*",
"[",
"0",
"]",
"return",
"len",
"(",
"cls",
"+",
"token_ids_0",
"+",
"sep",
")",
"*",
"[",
"0",
"]",
"+",
"len",
"(",
"token_ids_1",
"+",
"sep",
")",
"*",
"[",
"1",
"]"
] | [
217,
4
] | [
246,
80
] | python | en | ['en', 'error', 'th'] | False |
test_validate_python | (mock_exit) | Test validate Python version method. | Test validate Python version method. | def test_validate_python(mock_exit):
"""Test validate Python version method."""
with patch("sys.version_info", new_callable=PropertyMock(return_value=(2, 7, 8))):
main.validate_python()
assert mock_exit.called is True
mock_exit.reset_mock()
with patch("sys.version_info", new_callable=PropertyMock(return_value=(3, 2, 0))):
main.validate_python()
assert mock_exit.called is True
mock_exit.reset_mock()
with patch("sys.version_info", new_callable=PropertyMock(return_value=(3, 4, 2))):
main.validate_python()
assert mock_exit.called is True
mock_exit.reset_mock()
with patch("sys.version_info", new_callable=PropertyMock(return_value=(3, 5, 2))):
main.validate_python()
assert mock_exit.called is True
mock_exit.reset_mock()
with patch(
"sys.version_info",
new_callable=PropertyMock(
return_value=(REQUIRED_PYTHON_VER[0] - 1,) + REQUIRED_PYTHON_VER[1:]
),
):
main.validate_python()
assert mock_exit.called is True
mock_exit.reset_mock()
with patch(
"sys.version_info", new_callable=PropertyMock(return_value=REQUIRED_PYTHON_VER)
):
main.validate_python()
assert mock_exit.called is False
mock_exit.reset_mock()
with patch(
"sys.version_info",
new_callable=PropertyMock(
return_value=(REQUIRED_PYTHON_VER[:2]) + (REQUIRED_PYTHON_VER[2] + 1,)
),
):
main.validate_python()
assert mock_exit.called is False
mock_exit.reset_mock() | [
"def",
"test_validate_python",
"(",
"mock_exit",
")",
":",
"with",
"patch",
"(",
"\"sys.version_info\"",
",",
"new_callable",
"=",
"PropertyMock",
"(",
"return_value",
"=",
"(",
"2",
",",
"7",
",",
"8",
")",
")",
")",
":",
"main",
".",
"validate_python",
"(",
")",
"assert",
"mock_exit",
".",
"called",
"is",
"True",
"mock_exit",
".",
"reset_mock",
"(",
")",
"with",
"patch",
"(",
"\"sys.version_info\"",
",",
"new_callable",
"=",
"PropertyMock",
"(",
"return_value",
"=",
"(",
"3",
",",
"2",
",",
"0",
")",
")",
")",
":",
"main",
".",
"validate_python",
"(",
")",
"assert",
"mock_exit",
".",
"called",
"is",
"True",
"mock_exit",
".",
"reset_mock",
"(",
")",
"with",
"patch",
"(",
"\"sys.version_info\"",
",",
"new_callable",
"=",
"PropertyMock",
"(",
"return_value",
"=",
"(",
"3",
",",
"4",
",",
"2",
")",
")",
")",
":",
"main",
".",
"validate_python",
"(",
")",
"assert",
"mock_exit",
".",
"called",
"is",
"True",
"mock_exit",
".",
"reset_mock",
"(",
")",
"with",
"patch",
"(",
"\"sys.version_info\"",
",",
"new_callable",
"=",
"PropertyMock",
"(",
"return_value",
"=",
"(",
"3",
",",
"5",
",",
"2",
")",
")",
")",
":",
"main",
".",
"validate_python",
"(",
")",
"assert",
"mock_exit",
".",
"called",
"is",
"True",
"mock_exit",
".",
"reset_mock",
"(",
")",
"with",
"patch",
"(",
"\"sys.version_info\"",
",",
"new_callable",
"=",
"PropertyMock",
"(",
"return_value",
"=",
"(",
"REQUIRED_PYTHON_VER",
"[",
"0",
"]",
"-",
"1",
",",
")",
"+",
"REQUIRED_PYTHON_VER",
"[",
"1",
":",
"]",
")",
",",
")",
":",
"main",
".",
"validate_python",
"(",
")",
"assert",
"mock_exit",
".",
"called",
"is",
"True",
"mock_exit",
".",
"reset_mock",
"(",
")",
"with",
"patch",
"(",
"\"sys.version_info\"",
",",
"new_callable",
"=",
"PropertyMock",
"(",
"return_value",
"=",
"REQUIRED_PYTHON_VER",
")",
")",
":",
"main",
".",
"validate_python",
"(",
")",
"assert",
"mock_exit",
".",
"called",
"is",
"False",
"mock_exit",
".",
"reset_mock",
"(",
")",
"with",
"patch",
"(",
"\"sys.version_info\"",
",",
"new_callable",
"=",
"PropertyMock",
"(",
"return_value",
"=",
"(",
"REQUIRED_PYTHON_VER",
"[",
":",
"2",
"]",
")",
"+",
"(",
"REQUIRED_PYTHON_VER",
"[",
"2",
"]",
"+",
"1",
",",
")",
")",
",",
")",
":",
"main",
".",
"validate_python",
"(",
")",
"assert",
"mock_exit",
".",
"called",
"is",
"False",
"mock_exit",
".",
"reset_mock",
"(",
")"
] | [
8,
0
] | [
62,
26
] | python | en | ['nl', 'et', 'en'] | False |
WeatherUpdateCoordinator.__init__ | (self, owm, latitude, longitude, forecast_mode, hass) | Initialize coordinator. | Initialize coordinator. | def __init__(self, owm, latitude, longitude, forecast_mode, hass):
"""Initialize coordinator."""
self._owm_client = owm
self._latitude = latitude
self._longitude = longitude
self._forecast_mode = forecast_mode
self._forecast_limit = None
if forecast_mode == FORECAST_MODE_DAILY:
self._forecast_limit = 15
super().__init__(
hass, _LOGGER, name=DOMAIN, update_interval=WEATHER_UPDATE_INTERVAL
) | [
"def",
"__init__",
"(",
"self",
",",
"owm",
",",
"latitude",
",",
"longitude",
",",
"forecast_mode",
",",
"hass",
")",
":",
"self",
".",
"_owm_client",
"=",
"owm",
"self",
".",
"_latitude",
"=",
"latitude",
"self",
".",
"_longitude",
"=",
"longitude",
"self",
".",
"_forecast_mode",
"=",
"forecast_mode",
"self",
".",
"_forecast_limit",
"=",
"None",
"if",
"forecast_mode",
"==",
"FORECAST_MODE_DAILY",
":",
"self",
".",
"_forecast_limit",
"=",
"15",
"super",
"(",
")",
".",
"__init__",
"(",
"hass",
",",
"_LOGGER",
",",
"name",
"=",
"DOMAIN",
",",
"update_interval",
"=",
"WEATHER_UPDATE_INTERVAL",
")"
] | [
47,
4
] | [
59,
9
] | python | it | ['it', 'ro', 'it'] | False |
WeatherUpdateCoordinator._get_owm_weather | (self) | Poll weather data from OWM. | Poll weather data from OWM. | async def _get_owm_weather(self):
"""Poll weather data from OWM."""
if (
self._forecast_mode == FORECAST_MODE_ONECALL_HOURLY
or self._forecast_mode == FORECAST_MODE_ONECALL_DAILY
):
weather = await self.hass.async_add_executor_job(
self._owm_client.one_call, self._latitude, self._longitude
)
else:
weather = await self.hass.async_add_executor_job(
self._get_legacy_weather_and_forecast
)
return weather | [
"async",
"def",
"_get_owm_weather",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"_forecast_mode",
"==",
"FORECAST_MODE_ONECALL_HOURLY",
"or",
"self",
".",
"_forecast_mode",
"==",
"FORECAST_MODE_ONECALL_DAILY",
")",
":",
"weather",
"=",
"await",
"self",
".",
"hass",
".",
"async_add_executor_job",
"(",
"self",
".",
"_owm_client",
".",
"one_call",
",",
"self",
".",
"_latitude",
",",
"self",
".",
"_longitude",
")",
"else",
":",
"weather",
"=",
"await",
"self",
".",
"hass",
".",
"async_add_executor_job",
"(",
"self",
".",
"_get_legacy_weather_and_forecast",
")",
"return",
"weather"
] | [
71,
4
] | [
85,
22
] | python | en | ['en', 'en', 'en'] | True |
WeatherUpdateCoordinator._get_legacy_weather_and_forecast | (self) | Get weather and forecast data from OWM. | Get weather and forecast data from OWM. | def _get_legacy_weather_and_forecast(self):
"""Get weather and forecast data from OWM."""
interval = self._get_forecast_interval()
weather = self._owm_client.weather_at_coords(self._latitude, self._longitude)
forecast = self._owm_client.forecast_at_coords(
self._latitude, self._longitude, interval, self._forecast_limit
)
return LegacyWeather(weather.weather, forecast.forecast.weathers) | [
"def",
"_get_legacy_weather_and_forecast",
"(",
"self",
")",
":",
"interval",
"=",
"self",
".",
"_get_forecast_interval",
"(",
")",
"weather",
"=",
"self",
".",
"_owm_client",
".",
"weather_at_coords",
"(",
"self",
".",
"_latitude",
",",
"self",
".",
"_longitude",
")",
"forecast",
"=",
"self",
".",
"_owm_client",
".",
"forecast_at_coords",
"(",
"self",
".",
"_latitude",
",",
"self",
".",
"_longitude",
",",
"interval",
",",
"self",
".",
"_forecast_limit",
")",
"return",
"LegacyWeather",
"(",
"weather",
".",
"weather",
",",
"forecast",
".",
"forecast",
".",
"weathers",
")"
] | [
87,
4
] | [
94,
73
] | python | en | ['en', 'en', 'en'] | True |
WeatherUpdateCoordinator._get_forecast_interval | (self) | Get the correct forecast interval depending on the forecast mode. | Get the correct forecast interval depending on the forecast mode. | def _get_forecast_interval(self):
"""Get the correct forecast interval depending on the forecast mode."""
interval = "daily"
if self._forecast_mode == FORECAST_MODE_HOURLY:
interval = "3h"
return interval | [
"def",
"_get_forecast_interval",
"(",
"self",
")",
":",
"interval",
"=",
"\"daily\"",
"if",
"self",
".",
"_forecast_mode",
"==",
"FORECAST_MODE_HOURLY",
":",
"interval",
"=",
"\"3h\"",
"return",
"interval"
] | [
96,
4
] | [
101,
23
] | python | en | ['en', 'en', 'en'] | True |
WeatherUpdateCoordinator._convert_weather_response | (self, weather_response) | Format the weather response correctly. | Format the weather response correctly. | def _convert_weather_response(self, weather_response):
"""Format the weather response correctly."""
current_weather = weather_response.current
forecast_weather = self._get_forecast_from_weather_response(weather_response)
return {
ATTR_API_TEMPERATURE: current_weather.temperature("celsius").get("temp"),
ATTR_API_PRESSURE: current_weather.pressure.get("press"),
ATTR_API_HUMIDITY: current_weather.humidity,
ATTR_API_WIND_BEARING: current_weather.wind().get("deg"),
ATTR_API_WIND_SPEED: current_weather.wind().get("speed"),
ATTR_API_CLOUDS: current_weather.clouds,
ATTR_API_RAIN: self._get_rain(current_weather.rain),
ATTR_API_SNOW: self._get_snow(current_weather.snow),
ATTR_API_WEATHER: current_weather.detailed_status,
ATTR_API_CONDITION: self._get_condition(current_weather.weather_code),
ATTR_API_WEATHER_CODE: current_weather.weather_code,
ATTR_API_FORECAST: forecast_weather,
} | [
"def",
"_convert_weather_response",
"(",
"self",
",",
"weather_response",
")",
":",
"current_weather",
"=",
"weather_response",
".",
"current",
"forecast_weather",
"=",
"self",
".",
"_get_forecast_from_weather_response",
"(",
"weather_response",
")",
"return",
"{",
"ATTR_API_TEMPERATURE",
":",
"current_weather",
".",
"temperature",
"(",
"\"celsius\"",
")",
".",
"get",
"(",
"\"temp\"",
")",
",",
"ATTR_API_PRESSURE",
":",
"current_weather",
".",
"pressure",
".",
"get",
"(",
"\"press\"",
")",
",",
"ATTR_API_HUMIDITY",
":",
"current_weather",
".",
"humidity",
",",
"ATTR_API_WIND_BEARING",
":",
"current_weather",
".",
"wind",
"(",
")",
".",
"get",
"(",
"\"deg\"",
")",
",",
"ATTR_API_WIND_SPEED",
":",
"current_weather",
".",
"wind",
"(",
")",
".",
"get",
"(",
"\"speed\"",
")",
",",
"ATTR_API_CLOUDS",
":",
"current_weather",
".",
"clouds",
",",
"ATTR_API_RAIN",
":",
"self",
".",
"_get_rain",
"(",
"current_weather",
".",
"rain",
")",
",",
"ATTR_API_SNOW",
":",
"self",
".",
"_get_snow",
"(",
"current_weather",
".",
"snow",
")",
",",
"ATTR_API_WEATHER",
":",
"current_weather",
".",
"detailed_status",
",",
"ATTR_API_CONDITION",
":",
"self",
".",
"_get_condition",
"(",
"current_weather",
".",
"weather_code",
")",
",",
"ATTR_API_WEATHER_CODE",
":",
"current_weather",
".",
"weather_code",
",",
"ATTR_API_FORECAST",
":",
"forecast_weather",
",",
"}"
] | [
103,
4
] | [
121,
9
] | python | en | ['en', 'en', 'en'] | True |
WeatherUpdateCoordinator._get_rain | (rain) | Get rain data from weather data. | Get rain data from weather data. | def _get_rain(rain):
"""Get rain data from weather data."""
if "all" in rain:
return round(rain["all"], 0)
if "1h" in rain:
return round(rain["1h"], 0)
return "not raining" | [
"def",
"_get_rain",
"(",
"rain",
")",
":",
"if",
"\"all\"",
"in",
"rain",
":",
"return",
"round",
"(",
"rain",
"[",
"\"all\"",
"]",
",",
"0",
")",
"if",
"\"1h\"",
"in",
"rain",
":",
"return",
"round",
"(",
"rain",
"[",
"\"1h\"",
"]",
",",
"0",
")",
"return",
"\"not raining\""
] | [
154,
4
] | [
160,
28
] | python | en | ['en', 'en', 'en'] | True |
WeatherUpdateCoordinator._get_snow | (snow) | Get snow data from weather data. | Get snow data from weather data. | def _get_snow(snow):
"""Get snow data from weather data."""
if snow:
if "all" in snow:
return round(snow["all"], 0)
if "1h" in snow:
return round(snow["1h"], 0)
return "not snowing"
return "not snowing" | [
"def",
"_get_snow",
"(",
"snow",
")",
":",
"if",
"snow",
":",
"if",
"\"all\"",
"in",
"snow",
":",
"return",
"round",
"(",
"snow",
"[",
"\"all\"",
"]",
",",
"0",
")",
"if",
"\"1h\"",
"in",
"snow",
":",
"return",
"round",
"(",
"snow",
"[",
"\"1h\"",
"]",
",",
"0",
")",
"return",
"\"not snowing\"",
"return",
"\"not snowing\""
] | [
163,
4
] | [
171,
28
] | python | en | ['en', 'en', 'en'] | True |
WeatherUpdateCoordinator._calc_precipitation | (rain, snow) | Calculate the precipitation. | Calculate the precipitation. | def _calc_precipitation(rain, snow):
"""Calculate the precipitation."""
rain_value = 0
if WeatherUpdateCoordinator._get_rain(rain) != "not raining":
rain_value = WeatherUpdateCoordinator._get_rain(rain)
snow_value = 0
if WeatherUpdateCoordinator._get_snow(snow) != "not snowing":
snow_value = WeatherUpdateCoordinator._get_snow(snow)
if round(rain_value + snow_value, 1) == 0:
return None
return round(rain_value + snow_value, 1) | [
"def",
"_calc_precipitation",
"(",
"rain",
",",
"snow",
")",
":",
"rain_value",
"=",
"0",
"if",
"WeatherUpdateCoordinator",
".",
"_get_rain",
"(",
"rain",
")",
"!=",
"\"not raining\"",
":",
"rain_value",
"=",
"WeatherUpdateCoordinator",
".",
"_get_rain",
"(",
"rain",
")",
"snow_value",
"=",
"0",
"if",
"WeatherUpdateCoordinator",
".",
"_get_snow",
"(",
"snow",
")",
"!=",
"\"not snowing\"",
":",
"snow_value",
"=",
"WeatherUpdateCoordinator",
".",
"_get_snow",
"(",
"snow",
")",
"if",
"round",
"(",
"rain_value",
"+",
"snow_value",
",",
"1",
")",
"==",
"0",
":",
"return",
"None",
"return",
"round",
"(",
"rain_value",
"+",
"snow_value",
",",
"1",
")"
] | [
174,
4
] | [
186,
48
] | python | en | ['en', 'it', 'en'] | True |
WeatherUpdateCoordinator._get_condition | (weather_code) | Get weather condition from weather data. | Get weather condition from weather data. | def _get_condition(weather_code):
"""Get weather condition from weather data."""
return [k for k, v in CONDITION_CLASSES.items() if weather_code in v][0] | [
"def",
"_get_condition",
"(",
"weather_code",
")",
":",
"return",
"[",
"k",
"for",
"k",
",",
"v",
"in",
"CONDITION_CLASSES",
".",
"items",
"(",
")",
"if",
"weather_code",
"in",
"v",
"]",
"[",
"0",
"]"
] | [
189,
4
] | [
191,
80
] | python | en | ['en', 'en', 'en'] | True |
LegacyWeather.__init__ | (self, current_weather, forecast) | Initialize weather object. | Initialize weather object. | def __init__(self, current_weather, forecast):
"""Initialize weather object."""
self.current = current_weather
self.forecast = forecast | [
"def",
"__init__",
"(",
"self",
",",
"current_weather",
",",
"forecast",
")",
":",
"self",
".",
"current",
"=",
"current_weather",
"self",
".",
"forecast",
"=",
"forecast"
] | [
197,
4
] | [
200,
32
] | python | en | ['en', 'en', 'en'] | True |
KeyedRateLimit.__init__ | (
self,
hass: HomeAssistant,
) | Initialize ratelimit tracker. | Initialize ratelimit tracker. | def __init__(
self,
hass: HomeAssistant,
):
"""Initialize ratelimit tracker."""
self.hass = hass
self._last_triggered: Dict[Hashable, datetime] = {}
self._rate_limit_timers: Dict[Hashable, asyncio.TimerHandle] = {} | [
"def",
"__init__",
"(",
"self",
",",
"hass",
":",
"HomeAssistant",
",",
")",
":",
"self",
".",
"hass",
"=",
"hass",
"self",
".",
"_last_triggered",
":",
"Dict",
"[",
"Hashable",
",",
"datetime",
"]",
"=",
"{",
"}",
"self",
".",
"_rate_limit_timers",
":",
"Dict",
"[",
"Hashable",
",",
"asyncio",
".",
"TimerHandle",
"]",
"=",
"{",
"}"
] | [
15,
4
] | [
22,
73
] | python | en | ['en', 'en', 'en'] | True |
KeyedRateLimit.async_has_timer | (self, key: Hashable) | Check if a rate limit timer is running. | Check if a rate limit timer is running. | def async_has_timer(self, key: Hashable) -> bool:
"""Check if a rate limit timer is running."""
if not self._rate_limit_timers:
return False
return key in self._rate_limit_timers | [
"def",
"async_has_timer",
"(",
"self",
",",
"key",
":",
"Hashable",
")",
"->",
"bool",
":",
"if",
"not",
"self",
".",
"_rate_limit_timers",
":",
"return",
"False",
"return",
"key",
"in",
"self",
".",
"_rate_limit_timers"
] | [
25,
4
] | [
29,
45
] | python | en | ['en', 'en', 'en'] | True |
KeyedRateLimit.async_triggered | (self, key: Hashable, now: Optional[datetime] = None) | Call when the action we are tracking was triggered. | Call when the action we are tracking was triggered. | def async_triggered(self, key: Hashable, now: Optional[datetime] = None) -> None:
"""Call when the action we are tracking was triggered."""
self.async_cancel_timer(key)
self._last_triggered[key] = now or dt_util.utcnow() | [
"def",
"async_triggered",
"(",
"self",
",",
"key",
":",
"Hashable",
",",
"now",
":",
"Optional",
"[",
"datetime",
"]",
"=",
"None",
")",
"->",
"None",
":",
"self",
".",
"async_cancel_timer",
"(",
"key",
")",
"self",
".",
"_last_triggered",
"[",
"key",
"]",
"=",
"now",
"or",
"dt_util",
".",
"utcnow",
"(",
")"
] | [
32,
4
] | [
35,
59
] | python | en | ['en', 'en', 'en'] | True |
KeyedRateLimit.async_cancel_timer | (self, key: Hashable) | Cancel a rate limit time that will call the action. | Cancel a rate limit time that will call the action. | def async_cancel_timer(self, key: Hashable) -> None:
"""Cancel a rate limit time that will call the action."""
if not self._rate_limit_timers or not self.async_has_timer(key):
return
self._rate_limit_timers.pop(key).cancel() | [
"def",
"async_cancel_timer",
"(",
"self",
",",
"key",
":",
"Hashable",
")",
"->",
"None",
":",
"if",
"not",
"self",
".",
"_rate_limit_timers",
"or",
"not",
"self",
".",
"async_has_timer",
"(",
"key",
")",
":",
"return",
"self",
".",
"_rate_limit_timers",
".",
"pop",
"(",
"key",
")",
".",
"cancel",
"(",
")"
] | [
38,
4
] | [
43,
49
] | python | en | ['en', 'en', 'en'] | True |
KeyedRateLimit.async_remove | (self) | Remove all timers. | Remove all timers. | def async_remove(self) -> None:
"""Remove all timers."""
for timer in self._rate_limit_timers.values():
timer.cancel()
self._rate_limit_timers.clear() | [
"def",
"async_remove",
"(",
"self",
")",
"->",
"None",
":",
"for",
"timer",
"in",
"self",
".",
"_rate_limit_timers",
".",
"values",
"(",
")",
":",
"timer",
".",
"cancel",
"(",
")",
"self",
".",
"_rate_limit_timers",
".",
"clear",
"(",
")"
] | [
46,
4
] | [
50,
39
] | python | en | ['en', 'en', 'en'] | True |
KeyedRateLimit.async_schedule_action | (
self,
key: Hashable,
rate_limit: Optional[timedelta],
now: datetime,
action: Callable,
*args: Any,
) | Check rate limits and schedule an action if we hit the limit.
If the rate limit is hit:
Schedules the action for when the rate limit expires
if there are no pending timers. The action must
be called in async.
Returns the time the rate limit will expire
If the rate limit is not hit:
Return None
| Check rate limits and schedule an action if we hit the limit. | def async_schedule_action(
self,
key: Hashable,
rate_limit: Optional[timedelta],
now: datetime,
action: Callable,
*args: Any,
) -> Optional[datetime]:
"""Check rate limits and schedule an action if we hit the limit.
If the rate limit is hit:
Schedules the action for when the rate limit expires
if there are no pending timers. The action must
be called in async.
Returns the time the rate limit will expire
If the rate limit is not hit:
Return None
"""
if rate_limit is None:
return None
last_triggered = self._last_triggered.get(key)
if not last_triggered:
return None
next_call_time = last_triggered + rate_limit
if next_call_time <= now:
self.async_cancel_timer(key)
return None
_LOGGER.debug(
"Reached rate limit of %s for %s and deferred action until %s",
rate_limit,
key,
next_call_time,
)
if key not in self._rate_limit_timers:
self._rate_limit_timers[key] = self.hass.loop.call_later(
(next_call_time - now).total_seconds(),
action,
*args,
)
return next_call_time | [
"def",
"async_schedule_action",
"(",
"self",
",",
"key",
":",
"Hashable",
",",
"rate_limit",
":",
"Optional",
"[",
"timedelta",
"]",
",",
"now",
":",
"datetime",
",",
"action",
":",
"Callable",
",",
"*",
"args",
":",
"Any",
",",
")",
"->",
"Optional",
"[",
"datetime",
"]",
":",
"if",
"rate_limit",
"is",
"None",
":",
"return",
"None",
"last_triggered",
"=",
"self",
".",
"_last_triggered",
".",
"get",
"(",
"key",
")",
"if",
"not",
"last_triggered",
":",
"return",
"None",
"next_call_time",
"=",
"last_triggered",
"+",
"rate_limit",
"if",
"next_call_time",
"<=",
"now",
":",
"self",
".",
"async_cancel_timer",
"(",
"key",
")",
"return",
"None",
"_LOGGER",
".",
"debug",
"(",
"\"Reached rate limit of %s for %s and deferred action until %s\"",
",",
"rate_limit",
",",
"key",
",",
"next_call_time",
",",
")",
"if",
"key",
"not",
"in",
"self",
".",
"_rate_limit_timers",
":",
"self",
".",
"_rate_limit_timers",
"[",
"key",
"]",
"=",
"self",
".",
"hass",
".",
"loop",
".",
"call_later",
"(",
"(",
"next_call_time",
"-",
"now",
")",
".",
"total_seconds",
"(",
")",
",",
"action",
",",
"*",
"args",
",",
")",
"return",
"next_call_time"
] | [
53,
4
] | [
101,
29
] | python | en | ['en', 'en', 'en'] | True |
Subprocess.run | (command: str, timeout: int = None) | Run one-time command with subprocess.run().
Args:
command (str): command to be executed.
timeout (int): timeout in seconds.
Returns:
str: return stdout of the command.
| Run one-time command with subprocess.run(). | def run(command: str, timeout: int = None) -> None:
"""Run one-time command with subprocess.run().
Args:
command (str): command to be executed.
timeout (int): timeout in seconds.
Returns:
str: return stdout of the command.
"""
# TODO: Windows node
completed_process = subprocess.run(
command,
shell=True,
executable="/bin/bash",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
timeout=timeout
)
if completed_process.returncode != 0:
raise Exception(completed_process.stderr)
sys.stderr.write(completed_process.stderr) | [
"def",
"run",
"(",
"command",
":",
"str",
",",
"timeout",
":",
"int",
"=",
"None",
")",
"->",
"None",
":",
"# TODO: Windows node",
"completed_process",
"=",
"subprocess",
".",
"run",
"(",
"command",
",",
"shell",
"=",
"True",
",",
"executable",
"=",
"\"/bin/bash\"",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
",",
"universal_newlines",
"=",
"True",
",",
"timeout",
"=",
"timeout",
")",
"if",
"completed_process",
".",
"returncode",
"!=",
"0",
":",
"raise",
"Exception",
"(",
"completed_process",
".",
"stderr",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"completed_process",
".",
"stderr",
")"
] | [
55,
4
] | [
77,
50
] | python | en | ['en', 'en', 'en'] | True |
_get_config_schema | (input_dict: Dict[str, Any] = None) |
Return schema defaults for init step based on user input/config dict.
Retain info already provided for future form views by setting them
as defaults in schema.
|
Return schema defaults for init step based on user input/config dict. | def _get_config_schema(input_dict: Dict[str, Any] = None) -> vol.Schema:
"""
Return schema defaults for init step based on user input/config dict.
Retain info already provided for future form views by setting them
as defaults in schema.
"""
if input_dict is None:
input_dict = {}
return vol.Schema(
{
vol.Required(
CONF_NAME, default=input_dict.get(CONF_NAME, DEFAULT_NAME)
): str,
vol.Required(CONF_HOST, default=input_dict.get(CONF_HOST)): str,
vol.Required(
CONF_DEVICE_CLASS,
default=input_dict.get(CONF_DEVICE_CLASS, DEFAULT_DEVICE_CLASS),
): vol.All(str, vol.Lower, vol.In([DEVICE_CLASS_TV, DEVICE_CLASS_SPEAKER])),
vol.Optional(
CONF_ACCESS_TOKEN, default=input_dict.get(CONF_ACCESS_TOKEN, "")
): str,
},
extra=vol.REMOVE_EXTRA,
) | [
"def",
"_get_config_schema",
"(",
"input_dict",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"None",
")",
"->",
"vol",
".",
"Schema",
":",
"if",
"input_dict",
"is",
"None",
":",
"input_dict",
"=",
"{",
"}",
"return",
"vol",
".",
"Schema",
"(",
"{",
"vol",
".",
"Required",
"(",
"CONF_NAME",
",",
"default",
"=",
"input_dict",
".",
"get",
"(",
"CONF_NAME",
",",
"DEFAULT_NAME",
")",
")",
":",
"str",
",",
"vol",
".",
"Required",
"(",
"CONF_HOST",
",",
"default",
"=",
"input_dict",
".",
"get",
"(",
"CONF_HOST",
")",
")",
":",
"str",
",",
"vol",
".",
"Required",
"(",
"CONF_DEVICE_CLASS",
",",
"default",
"=",
"input_dict",
".",
"get",
"(",
"CONF_DEVICE_CLASS",
",",
"DEFAULT_DEVICE_CLASS",
")",
",",
")",
":",
"vol",
".",
"All",
"(",
"str",
",",
"vol",
".",
"Lower",
",",
"vol",
".",
"In",
"(",
"[",
"DEVICE_CLASS_TV",
",",
"DEVICE_CLASS_SPEAKER",
"]",
")",
")",
",",
"vol",
".",
"Optional",
"(",
"CONF_ACCESS_TOKEN",
",",
"default",
"=",
"input_dict",
".",
"get",
"(",
"CONF_ACCESS_TOKEN",
",",
"\"\"",
")",
")",
":",
"str",
",",
"}",
",",
"extra",
"=",
"vol",
".",
"REMOVE_EXTRA",
",",
")"
] | [
50,
0
] | [
75,
5
] | python | en | ['en', 'error', 'th'] | False |
_get_pairing_schema | (input_dict: Dict[str, Any] = None) |
Return schema defaults for pairing data based on user input.
Retain info already provided for future form views by setting
them as defaults in schema.
|
Return schema defaults for pairing data based on user input. | def _get_pairing_schema(input_dict: Dict[str, Any] = None) -> vol.Schema:
"""
Return schema defaults for pairing data based on user input.
Retain info already provided for future form views by setting
them as defaults in schema.
"""
if input_dict is None:
input_dict = {}
return vol.Schema(
{vol.Required(CONF_PIN, default=input_dict.get(CONF_PIN, "")): str}
) | [
"def",
"_get_pairing_schema",
"(",
"input_dict",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"None",
")",
"->",
"vol",
".",
"Schema",
":",
"if",
"input_dict",
"is",
"None",
":",
"input_dict",
"=",
"{",
"}",
"return",
"vol",
".",
"Schema",
"(",
"{",
"vol",
".",
"Required",
"(",
"CONF_PIN",
",",
"default",
"=",
"input_dict",
".",
"get",
"(",
"CONF_PIN",
",",
"\"\"",
")",
")",
":",
"str",
"}",
")"
] | [
78,
0
] | [
90,
5
] | python | en | ['en', 'error', 'th'] | False |
_host_is_same | (host1: str, host2: str) | Check if host1 and host2 are the same. | Check if host1 and host2 are the same. | def _host_is_same(host1: str, host2: str) -> bool:
"""Check if host1 and host2 are the same."""
host1 = host1.split(":")[0]
host1 = host1 if is_ip_address(host1) else socket.gethostbyname(host1)
host2 = host2.split(":")[0]
host2 = host2 if is_ip_address(host2) else socket.gethostbyname(host2)
return host1 == host2 | [
"def",
"_host_is_same",
"(",
"host1",
":",
"str",
",",
"host2",
":",
"str",
")",
"->",
"bool",
":",
"host1",
"=",
"host1",
".",
"split",
"(",
"\":\"",
")",
"[",
"0",
"]",
"host1",
"=",
"host1",
"if",
"is_ip_address",
"(",
"host1",
")",
"else",
"socket",
".",
"gethostbyname",
"(",
"host1",
")",
"host2",
"=",
"host2",
".",
"split",
"(",
"\":\"",
")",
"[",
"0",
"]",
"host2",
"=",
"host2",
"if",
"is_ip_address",
"(",
"host2",
")",
"else",
"socket",
".",
"gethostbyname",
"(",
"host2",
")",
"return",
"host1",
"==",
"host2"
] | [
93,
0
] | [
99,
25
] | python | en | ['en', 'en', 'en'] | True |
VizioOptionsConfigFlow.__init__ | (self, config_entry: ConfigEntry) | Initialize vizio options flow. | Initialize vizio options flow. | def __init__(self, config_entry: ConfigEntry) -> None:
"""Initialize vizio options flow."""
self.config_entry = config_entry | [
"def",
"__init__",
"(",
"self",
",",
"config_entry",
":",
"ConfigEntry",
")",
"->",
"None",
":",
"self",
".",
"config_entry",
"=",
"config_entry"
] | [
105,
4
] | [
107,
40
] | python | it | ['it', 'fr', 'it'] | True |
VizioOptionsConfigFlow.async_step_init | (
self, user_input: Dict[str, Any] = None
) | Manage the vizio options. | Manage the vizio options. | async def async_step_init(
self, user_input: Dict[str, Any] = None
) -> Dict[str, Any]:
"""Manage the vizio options."""
if user_input is not None:
if user_input.get(CONF_APPS_TO_INCLUDE_OR_EXCLUDE):
user_input[CONF_APPS] = {
user_input[CONF_INCLUDE_OR_EXCLUDE]: user_input[
CONF_APPS_TO_INCLUDE_OR_EXCLUDE
].copy()
}
user_input.pop(CONF_INCLUDE_OR_EXCLUDE)
user_input.pop(CONF_APPS_TO_INCLUDE_OR_EXCLUDE)
return self.async_create_entry(title="", data=user_input)
options = vol.Schema(
{
vol.Optional(
CONF_VOLUME_STEP,
default=self.config_entry.options.get(
CONF_VOLUME_STEP, DEFAULT_VOLUME_STEP
),
): vol.All(vol.Coerce(int), vol.Range(min=1, max=10))
}
)
if self.config_entry.data[CONF_DEVICE_CLASS] == DEVICE_CLASS_TV:
default_include_or_exclude = (
CONF_EXCLUDE
if self.config_entry.options
and CONF_EXCLUDE in self.config_entry.options.get(CONF_APPS, {})
else CONF_INCLUDE
)
options = options.extend(
{
vol.Optional(
CONF_INCLUDE_OR_EXCLUDE,
default=default_include_or_exclude.title(),
): vol.All(
vol.In([CONF_INCLUDE.title(), CONF_EXCLUDE.title()]), vol.Lower
),
vol.Optional(
CONF_APPS_TO_INCLUDE_OR_EXCLUDE,
default=self.config_entry.options.get(CONF_APPS, {}).get(
default_include_or_exclude, []
),
): cv.multi_select(
[
APP_HOME["name"],
*[
app["name"]
for app in self.hass.data[DOMAIN][CONF_APPS].data
],
]
),
}
)
return self.async_show_form(step_id="init", data_schema=options) | [
"async",
"def",
"async_step_init",
"(",
"self",
",",
"user_input",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"None",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"if",
"user_input",
"is",
"not",
"None",
":",
"if",
"user_input",
".",
"get",
"(",
"CONF_APPS_TO_INCLUDE_OR_EXCLUDE",
")",
":",
"user_input",
"[",
"CONF_APPS",
"]",
"=",
"{",
"user_input",
"[",
"CONF_INCLUDE_OR_EXCLUDE",
"]",
":",
"user_input",
"[",
"CONF_APPS_TO_INCLUDE_OR_EXCLUDE",
"]",
".",
"copy",
"(",
")",
"}",
"user_input",
".",
"pop",
"(",
"CONF_INCLUDE_OR_EXCLUDE",
")",
"user_input",
".",
"pop",
"(",
"CONF_APPS_TO_INCLUDE_OR_EXCLUDE",
")",
"return",
"self",
".",
"async_create_entry",
"(",
"title",
"=",
"\"\"",
",",
"data",
"=",
"user_input",
")",
"options",
"=",
"vol",
".",
"Schema",
"(",
"{",
"vol",
".",
"Optional",
"(",
"CONF_VOLUME_STEP",
",",
"default",
"=",
"self",
".",
"config_entry",
".",
"options",
".",
"get",
"(",
"CONF_VOLUME_STEP",
",",
"DEFAULT_VOLUME_STEP",
")",
",",
")",
":",
"vol",
".",
"All",
"(",
"vol",
".",
"Coerce",
"(",
"int",
")",
",",
"vol",
".",
"Range",
"(",
"min",
"=",
"1",
",",
"max",
"=",
"10",
")",
")",
"}",
")",
"if",
"self",
".",
"config_entry",
".",
"data",
"[",
"CONF_DEVICE_CLASS",
"]",
"==",
"DEVICE_CLASS_TV",
":",
"default_include_or_exclude",
"=",
"(",
"CONF_EXCLUDE",
"if",
"self",
".",
"config_entry",
".",
"options",
"and",
"CONF_EXCLUDE",
"in",
"self",
".",
"config_entry",
".",
"options",
".",
"get",
"(",
"CONF_APPS",
",",
"{",
"}",
")",
"else",
"CONF_INCLUDE",
")",
"options",
"=",
"options",
".",
"extend",
"(",
"{",
"vol",
".",
"Optional",
"(",
"CONF_INCLUDE_OR_EXCLUDE",
",",
"default",
"=",
"default_include_or_exclude",
".",
"title",
"(",
")",
",",
")",
":",
"vol",
".",
"All",
"(",
"vol",
".",
"In",
"(",
"[",
"CONF_INCLUDE",
".",
"title",
"(",
")",
",",
"CONF_EXCLUDE",
".",
"title",
"(",
")",
"]",
")",
",",
"vol",
".",
"Lower",
")",
",",
"vol",
".",
"Optional",
"(",
"CONF_APPS_TO_INCLUDE_OR_EXCLUDE",
",",
"default",
"=",
"self",
".",
"config_entry",
".",
"options",
".",
"get",
"(",
"CONF_APPS",
",",
"{",
"}",
")",
".",
"get",
"(",
"default_include_or_exclude",
",",
"[",
"]",
")",
",",
")",
":",
"cv",
".",
"multi_select",
"(",
"[",
"APP_HOME",
"[",
"\"name\"",
"]",
",",
"*",
"[",
"app",
"[",
"\"name\"",
"]",
"for",
"app",
"in",
"self",
".",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"CONF_APPS",
"]",
".",
"data",
"]",
",",
"]",
")",
",",
"}",
")",
"return",
"self",
".",
"async_show_form",
"(",
"step_id",
"=",
"\"init\"",
",",
"data_schema",
"=",
"options",
")"
] | [
109,
4
] | [
169,
72
] | python | en | ['en', 'fa', 'en'] | True |
VizioConfigFlow.async_get_options_flow | (config_entry: ConfigEntry) | Get the options flow for this handler. | Get the options flow for this handler. | def async_get_options_flow(config_entry: ConfigEntry) -> VizioOptionsConfigFlow:
"""Get the options flow for this handler."""
return VizioOptionsConfigFlow(config_entry) | [
"def",
"async_get_options_flow",
"(",
"config_entry",
":",
"ConfigEntry",
")",
"->",
"VizioOptionsConfigFlow",
":",
"return",
"VizioOptionsConfigFlow",
"(",
"config_entry",
")"
] | [
180,
4
] | [
182,
51
] | python | en | ['en', 'en', 'en'] | True |
VizioConfigFlow.__init__ | (self) | Initialize config flow. | Initialize config flow. | def __init__(self) -> None:
"""Initialize config flow."""
self._user_schema = None
self._must_show_form = None
self._ch_type = None
self._pairing_token = None
self._data = None
self._apps = {} | [
"def",
"__init__",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"_user_schema",
"=",
"None",
"self",
".",
"_must_show_form",
"=",
"None",
"self",
".",
"_ch_type",
"=",
"None",
"self",
".",
"_pairing_token",
"=",
"None",
"self",
".",
"_data",
"=",
"None",
"self",
".",
"_apps",
"=",
"{",
"}"
] | [
184,
4
] | [
191,
23
] | python | en | ['de', 'en', 'en'] | True |
VizioConfigFlow._create_entry | (self, input_dict: Dict[str, Any]) | Create vizio config entry. | Create vizio config entry. | async def _create_entry(self, input_dict: Dict[str, Any]) -> Dict[str, Any]:
"""Create vizio config entry."""
# Remove extra keys that will not be used by entry setup
input_dict.pop(CONF_APPS_TO_INCLUDE_OR_EXCLUDE, None)
input_dict.pop(CONF_INCLUDE_OR_EXCLUDE, None)
if self._apps:
input_dict[CONF_APPS] = self._apps
return self.async_create_entry(title=input_dict[CONF_NAME], data=input_dict) | [
"async",
"def",
"_create_entry",
"(",
"self",
",",
"input_dict",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"# Remove extra keys that will not be used by entry setup",
"input_dict",
".",
"pop",
"(",
"CONF_APPS_TO_INCLUDE_OR_EXCLUDE",
",",
"None",
")",
"input_dict",
".",
"pop",
"(",
"CONF_INCLUDE_OR_EXCLUDE",
",",
"None",
")",
"if",
"self",
".",
"_apps",
":",
"input_dict",
"[",
"CONF_APPS",
"]",
"=",
"self",
".",
"_apps",
"return",
"self",
".",
"async_create_entry",
"(",
"title",
"=",
"input_dict",
"[",
"CONF_NAME",
"]",
",",
"data",
"=",
"input_dict",
")"
] | [
193,
4
] | [
202,
84
] | python | it | ['it', 'gl', 'it'] | True |
VizioConfigFlow.async_step_user | (
self, user_input: Dict[str, Any] = None
) | Handle a flow initialized by the user. | Handle a flow initialized by the user. | async def async_step_user(
self, user_input: Dict[str, Any] = None
) -> Dict[str, Any]:
"""Handle a flow initialized by the user."""
assert self.hass
errors = {}
if user_input is not None:
# Store current values in case setup fails and user needs to edit
self._user_schema = _get_config_schema(user_input)
if self.unique_id is None:
unique_id = await VizioAsync.get_unique_id(
user_input[CONF_HOST],
user_input[CONF_DEVICE_CLASS],
session=async_get_clientsession(self.hass, False),
)
# Check if unique ID was found, set unique ID, and abort if a flow with
# the same unique ID is already in progress
if not unique_id:
errors[CONF_HOST] = "cannot_connect"
elif (
await self.async_set_unique_id(
unique_id=unique_id, raise_on_progress=True
)
is not None
):
errors[CONF_HOST] = "existing_config_entry_found"
if not errors:
# pylint: disable=no-member # https://github.com/PyCQA/pylint/issues/3167
if self._must_show_form and self.context["source"] == SOURCE_ZEROCONF:
# Discovery should always display the config form before trying to
# create entry so that user can update default config options
self._must_show_form = False
elif user_input[
CONF_DEVICE_CLASS
] == DEVICE_CLASS_SPEAKER or user_input.get(CONF_ACCESS_TOKEN):
# Ensure config is valid for a device
if not await VizioAsync.validate_ha_config(
user_input[CONF_HOST],
user_input.get(CONF_ACCESS_TOKEN),
user_input[CONF_DEVICE_CLASS],
session=async_get_clientsession(self.hass, False),
):
errors["base"] = "cannot_connect"
if not errors:
return await self._create_entry(user_input)
# pylint: disable=no-member # https://github.com/PyCQA/pylint/issues/3167
elif self._must_show_form and self.context["source"] == SOURCE_IMPORT:
# Import should always display the config form if CONF_ACCESS_TOKEN
# wasn't included but is needed so that the user can choose to update
# their configuration.yaml or to proceed with config flow pairing. We
# will also provide contextual message to user explaining why
_LOGGER.warning(
"Couldn't complete configuration.yaml import: '%s' key is "
"missing. Either provide '%s' key in configuration.yaml or "
"finish setup by completing configuration via frontend",
CONF_ACCESS_TOKEN,
CONF_ACCESS_TOKEN,
)
self._must_show_form = False
else:
self._data = copy.deepcopy(user_input)
return await self.async_step_pair_tv()
schema = self._user_schema or _get_config_schema()
# pylint: disable=no-member # https://github.com/PyCQA/pylint/issues/3167
if errors and self.context["source"] == SOURCE_IMPORT:
# Log an error message if import config flow fails since otherwise failure is silent
_LOGGER.error(
"configuration.yaml import failure: %s", ", ".join(errors.values())
)
return self.async_show_form(step_id="user", data_schema=schema, errors=errors) | [
"async",
"def",
"async_step_user",
"(",
"self",
",",
"user_input",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"None",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"assert",
"self",
".",
"hass",
"errors",
"=",
"{",
"}",
"if",
"user_input",
"is",
"not",
"None",
":",
"# Store current values in case setup fails and user needs to edit",
"self",
".",
"_user_schema",
"=",
"_get_config_schema",
"(",
"user_input",
")",
"if",
"self",
".",
"unique_id",
"is",
"None",
":",
"unique_id",
"=",
"await",
"VizioAsync",
".",
"get_unique_id",
"(",
"user_input",
"[",
"CONF_HOST",
"]",
",",
"user_input",
"[",
"CONF_DEVICE_CLASS",
"]",
",",
"session",
"=",
"async_get_clientsession",
"(",
"self",
".",
"hass",
",",
"False",
")",
",",
")",
"# Check if unique ID was found, set unique ID, and abort if a flow with",
"# the same unique ID is already in progress",
"if",
"not",
"unique_id",
":",
"errors",
"[",
"CONF_HOST",
"]",
"=",
"\"cannot_connect\"",
"elif",
"(",
"await",
"self",
".",
"async_set_unique_id",
"(",
"unique_id",
"=",
"unique_id",
",",
"raise_on_progress",
"=",
"True",
")",
"is",
"not",
"None",
")",
":",
"errors",
"[",
"CONF_HOST",
"]",
"=",
"\"existing_config_entry_found\"",
"if",
"not",
"errors",
":",
"# pylint: disable=no-member # https://github.com/PyCQA/pylint/issues/3167",
"if",
"self",
".",
"_must_show_form",
"and",
"self",
".",
"context",
"[",
"\"source\"",
"]",
"==",
"SOURCE_ZEROCONF",
":",
"# Discovery should always display the config form before trying to",
"# create entry so that user can update default config options",
"self",
".",
"_must_show_form",
"=",
"False",
"elif",
"user_input",
"[",
"CONF_DEVICE_CLASS",
"]",
"==",
"DEVICE_CLASS_SPEAKER",
"or",
"user_input",
".",
"get",
"(",
"CONF_ACCESS_TOKEN",
")",
":",
"# Ensure config is valid for a device",
"if",
"not",
"await",
"VizioAsync",
".",
"validate_ha_config",
"(",
"user_input",
"[",
"CONF_HOST",
"]",
",",
"user_input",
".",
"get",
"(",
"CONF_ACCESS_TOKEN",
")",
",",
"user_input",
"[",
"CONF_DEVICE_CLASS",
"]",
",",
"session",
"=",
"async_get_clientsession",
"(",
"self",
".",
"hass",
",",
"False",
")",
",",
")",
":",
"errors",
"[",
"\"base\"",
"]",
"=",
"\"cannot_connect\"",
"if",
"not",
"errors",
":",
"return",
"await",
"self",
".",
"_create_entry",
"(",
"user_input",
")",
"# pylint: disable=no-member # https://github.com/PyCQA/pylint/issues/3167",
"elif",
"self",
".",
"_must_show_form",
"and",
"self",
".",
"context",
"[",
"\"source\"",
"]",
"==",
"SOURCE_IMPORT",
":",
"# Import should always display the config form if CONF_ACCESS_TOKEN",
"# wasn't included but is needed so that the user can choose to update",
"# their configuration.yaml or to proceed with config flow pairing. We",
"# will also provide contextual message to user explaining why",
"_LOGGER",
".",
"warning",
"(",
"\"Couldn't complete configuration.yaml import: '%s' key is \"",
"\"missing. Either provide '%s' key in configuration.yaml or \"",
"\"finish setup by completing configuration via frontend\"",
",",
"CONF_ACCESS_TOKEN",
",",
"CONF_ACCESS_TOKEN",
",",
")",
"self",
".",
"_must_show_form",
"=",
"False",
"else",
":",
"self",
".",
"_data",
"=",
"copy",
".",
"deepcopy",
"(",
"user_input",
")",
"return",
"await",
"self",
".",
"async_step_pair_tv",
"(",
")",
"schema",
"=",
"self",
".",
"_user_schema",
"or",
"_get_config_schema",
"(",
")",
"# pylint: disable=no-member # https://github.com/PyCQA/pylint/issues/3167",
"if",
"errors",
"and",
"self",
".",
"context",
"[",
"\"source\"",
"]",
"==",
"SOURCE_IMPORT",
":",
"# Log an error message if import config flow fails since otherwise failure is silent",
"_LOGGER",
".",
"error",
"(",
"\"configuration.yaml import failure: %s\"",
",",
"\", \"",
".",
"join",
"(",
"errors",
".",
"values",
"(",
")",
")",
")",
"return",
"self",
".",
"async_show_form",
"(",
"step_id",
"=",
"\"user\"",
",",
"data_schema",
"=",
"schema",
",",
"errors",
"=",
"errors",
")"
] | [
204,
4
] | [
280,
86
] | python | en | ['en', 'en', 'en'] | True |
VizioConfigFlow.async_step_import | (self, import_config: Dict[str, Any]) | Import a config entry from configuration.yaml. | Import a config entry from configuration.yaml. | async def async_step_import(self, import_config: Dict[str, Any]) -> Dict[str, Any]:
"""Import a config entry from configuration.yaml."""
# Check if new config entry matches any existing config entries
for entry in self.hass.config_entries.async_entries(DOMAIN):
# If source is ignore bypass host check and continue through loop
if entry.source == SOURCE_IGNORE:
continue
if await self.hass.async_add_executor_job(
_host_is_same, entry.data[CONF_HOST], import_config[CONF_HOST]
):
updated_options = {}
updated_data = {}
remove_apps = False
if entry.data[CONF_HOST] != import_config[CONF_HOST]:
updated_data[CONF_HOST] = import_config[CONF_HOST]
if entry.data[CONF_NAME] != import_config[CONF_NAME]:
updated_data[CONF_NAME] = import_config[CONF_NAME]
# Update entry.data[CONF_APPS] if import_config[CONF_APPS] differs, and
# pop entry.data[CONF_APPS] if import_config[CONF_APPS] is not specified
if entry.data.get(CONF_APPS) != import_config.get(CONF_APPS):
if not import_config.get(CONF_APPS):
remove_apps = True
else:
updated_options[CONF_APPS] = import_config[CONF_APPS]
if entry.data.get(CONF_VOLUME_STEP) != import_config[CONF_VOLUME_STEP]:
updated_options[CONF_VOLUME_STEP] = import_config[CONF_VOLUME_STEP]
if updated_options or updated_data or remove_apps:
new_data = entry.data.copy()
new_options = entry.options.copy()
if remove_apps:
new_data.pop(CONF_APPS)
new_options.pop(CONF_APPS)
if updated_data:
new_data.update(updated_data)
# options are stored in entry options and data so update both
if updated_options:
new_data.update(updated_options)
new_options.update(updated_options)
self.hass.config_entries.async_update_entry(
entry=entry, data=new_data, options=new_options
)
return self.async_abort(reason="updated_entry")
return self.async_abort(reason="already_configured_device")
self._must_show_form = True
# Store config key/value pairs that are not configurable in user step so they
# don't get lost on user step
if import_config.get(CONF_APPS):
self._apps = copy.deepcopy(import_config[CONF_APPS])
return await self.async_step_user(user_input=import_config) | [
"async",
"def",
"async_step_import",
"(",
"self",
",",
"import_config",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"# Check if new config entry matches any existing config entries",
"for",
"entry",
"in",
"self",
".",
"hass",
".",
"config_entries",
".",
"async_entries",
"(",
"DOMAIN",
")",
":",
"# If source is ignore bypass host check and continue through loop",
"if",
"entry",
".",
"source",
"==",
"SOURCE_IGNORE",
":",
"continue",
"if",
"await",
"self",
".",
"hass",
".",
"async_add_executor_job",
"(",
"_host_is_same",
",",
"entry",
".",
"data",
"[",
"CONF_HOST",
"]",
",",
"import_config",
"[",
"CONF_HOST",
"]",
")",
":",
"updated_options",
"=",
"{",
"}",
"updated_data",
"=",
"{",
"}",
"remove_apps",
"=",
"False",
"if",
"entry",
".",
"data",
"[",
"CONF_HOST",
"]",
"!=",
"import_config",
"[",
"CONF_HOST",
"]",
":",
"updated_data",
"[",
"CONF_HOST",
"]",
"=",
"import_config",
"[",
"CONF_HOST",
"]",
"if",
"entry",
".",
"data",
"[",
"CONF_NAME",
"]",
"!=",
"import_config",
"[",
"CONF_NAME",
"]",
":",
"updated_data",
"[",
"CONF_NAME",
"]",
"=",
"import_config",
"[",
"CONF_NAME",
"]",
"# Update entry.data[CONF_APPS] if import_config[CONF_APPS] differs, and",
"# pop entry.data[CONF_APPS] if import_config[CONF_APPS] is not specified",
"if",
"entry",
".",
"data",
".",
"get",
"(",
"CONF_APPS",
")",
"!=",
"import_config",
".",
"get",
"(",
"CONF_APPS",
")",
":",
"if",
"not",
"import_config",
".",
"get",
"(",
"CONF_APPS",
")",
":",
"remove_apps",
"=",
"True",
"else",
":",
"updated_options",
"[",
"CONF_APPS",
"]",
"=",
"import_config",
"[",
"CONF_APPS",
"]",
"if",
"entry",
".",
"data",
".",
"get",
"(",
"CONF_VOLUME_STEP",
")",
"!=",
"import_config",
"[",
"CONF_VOLUME_STEP",
"]",
":",
"updated_options",
"[",
"CONF_VOLUME_STEP",
"]",
"=",
"import_config",
"[",
"CONF_VOLUME_STEP",
"]",
"if",
"updated_options",
"or",
"updated_data",
"or",
"remove_apps",
":",
"new_data",
"=",
"entry",
".",
"data",
".",
"copy",
"(",
")",
"new_options",
"=",
"entry",
".",
"options",
".",
"copy",
"(",
")",
"if",
"remove_apps",
":",
"new_data",
".",
"pop",
"(",
"CONF_APPS",
")",
"new_options",
".",
"pop",
"(",
"CONF_APPS",
")",
"if",
"updated_data",
":",
"new_data",
".",
"update",
"(",
"updated_data",
")",
"# options are stored in entry options and data so update both",
"if",
"updated_options",
":",
"new_data",
".",
"update",
"(",
"updated_options",
")",
"new_options",
".",
"update",
"(",
"updated_options",
")",
"self",
".",
"hass",
".",
"config_entries",
".",
"async_update_entry",
"(",
"entry",
"=",
"entry",
",",
"data",
"=",
"new_data",
",",
"options",
"=",
"new_options",
")",
"return",
"self",
".",
"async_abort",
"(",
"reason",
"=",
"\"updated_entry\"",
")",
"return",
"self",
".",
"async_abort",
"(",
"reason",
"=",
"\"already_configured_device\"",
")",
"self",
".",
"_must_show_form",
"=",
"True",
"# Store config key/value pairs that are not configurable in user step so they",
"# don't get lost on user step",
"if",
"import_config",
".",
"get",
"(",
"CONF_APPS",
")",
":",
"self",
".",
"_apps",
"=",
"copy",
".",
"deepcopy",
"(",
"import_config",
"[",
"CONF_APPS",
"]",
")",
"return",
"await",
"self",
".",
"async_step_user",
"(",
"user_input",
"=",
"import_config",
")"
] | [
282,
4
] | [
342,
67
] | python | en | ['en', 'en', 'en'] | True |
VizioConfigFlow.async_step_zeroconf | (
self, discovery_info: Optional[DiscoveryInfoType] = None
) | Handle zeroconf discovery. | Handle zeroconf discovery. | async def async_step_zeroconf(
self, discovery_info: Optional[DiscoveryInfoType] = None
) -> Dict[str, Any]:
"""Handle zeroconf discovery."""
assert self.hass
# If host already has port, no need to add it again
if ":" not in discovery_info[CONF_HOST]:
discovery_info[
CONF_HOST
] = f"{discovery_info[CONF_HOST]}:{discovery_info[CONF_PORT]}"
# Set default name to discovered device name by stripping zeroconf service
# (`type`) from `name`
num_chars_to_strip = len(discovery_info[CONF_TYPE]) + 1
discovery_info[CONF_NAME] = discovery_info[CONF_NAME][:-num_chars_to_strip]
discovery_info[CONF_DEVICE_CLASS] = await async_guess_device_type(
discovery_info[CONF_HOST]
)
# Set unique ID early for discovery flow so we can abort if needed
unique_id = await VizioAsync.get_unique_id(
discovery_info[CONF_HOST],
discovery_info[CONF_DEVICE_CLASS],
session=async_get_clientsession(self.hass, False),
)
if not unique_id:
return self.async_abort(reason="cannot_connect")
await self.async_set_unique_id(unique_id=unique_id, raise_on_progress=True)
self._abort_if_unique_id_configured()
# Form must be shown after discovery so user can confirm/update configuration
# before ConfigEntry creation.
self._must_show_form = True
return await self.async_step_user(user_input=discovery_info) | [
"async",
"def",
"async_step_zeroconf",
"(",
"self",
",",
"discovery_info",
":",
"Optional",
"[",
"DiscoveryInfoType",
"]",
"=",
"None",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"assert",
"self",
".",
"hass",
"# If host already has port, no need to add it again",
"if",
"\":\"",
"not",
"in",
"discovery_info",
"[",
"CONF_HOST",
"]",
":",
"discovery_info",
"[",
"CONF_HOST",
"]",
"=",
"f\"{discovery_info[CONF_HOST]}:{discovery_info[CONF_PORT]}\"",
"# Set default name to discovered device name by stripping zeroconf service",
"# (`type`) from `name`",
"num_chars_to_strip",
"=",
"len",
"(",
"discovery_info",
"[",
"CONF_TYPE",
"]",
")",
"+",
"1",
"discovery_info",
"[",
"CONF_NAME",
"]",
"=",
"discovery_info",
"[",
"CONF_NAME",
"]",
"[",
":",
"-",
"num_chars_to_strip",
"]",
"discovery_info",
"[",
"CONF_DEVICE_CLASS",
"]",
"=",
"await",
"async_guess_device_type",
"(",
"discovery_info",
"[",
"CONF_HOST",
"]",
")",
"# Set unique ID early for discovery flow so we can abort if needed",
"unique_id",
"=",
"await",
"VizioAsync",
".",
"get_unique_id",
"(",
"discovery_info",
"[",
"CONF_HOST",
"]",
",",
"discovery_info",
"[",
"CONF_DEVICE_CLASS",
"]",
",",
"session",
"=",
"async_get_clientsession",
"(",
"self",
".",
"hass",
",",
"False",
")",
",",
")",
"if",
"not",
"unique_id",
":",
"return",
"self",
".",
"async_abort",
"(",
"reason",
"=",
"\"cannot_connect\"",
")",
"await",
"self",
".",
"async_set_unique_id",
"(",
"unique_id",
"=",
"unique_id",
",",
"raise_on_progress",
"=",
"True",
")",
"self",
".",
"_abort_if_unique_id_configured",
"(",
")",
"# Form must be shown after discovery so user can confirm/update configuration",
"# before ConfigEntry creation.",
"self",
".",
"_must_show_form",
"=",
"True",
"return",
"await",
"self",
".",
"async_step_user",
"(",
"user_input",
"=",
"discovery_info",
")"
] | [
344,
4
] | [
381,
68
] | python | de | ['de', 'sr', 'en'] | False |
VizioConfigFlow.async_step_pair_tv | (
self, user_input: Dict[str, Any] = None
) |
Start pairing process for TV.
Ask user for PIN to complete pairing process.
|
Start pairing process for TV. | async def async_step_pair_tv(
self, user_input: Dict[str, Any] = None
) -> Dict[str, Any]:
"""
Start pairing process for TV.
Ask user for PIN to complete pairing process.
"""
errors = {}
# Start pairing process if it hasn't already started
if not self._ch_type and not self._pairing_token:
dev = VizioAsync(
DEVICE_ID,
self._data[CONF_HOST],
self._data[CONF_NAME],
None,
self._data[CONF_DEVICE_CLASS],
session=async_get_clientsession(self.hass, False),
)
pair_data = await dev.start_pair()
if pair_data:
self._ch_type = pair_data.ch_type
self._pairing_token = pair_data.token
return await self.async_step_pair_tv()
return self.async_show_form(
step_id="user",
data_schema=_get_config_schema(self._data),
errors={"base": "cannot_connect"},
)
# Complete pairing process if PIN has been provided
if user_input and user_input.get(CONF_PIN):
dev = VizioAsync(
DEVICE_ID,
self._data[CONF_HOST],
self._data[CONF_NAME],
None,
self._data[CONF_DEVICE_CLASS],
session=async_get_clientsession(self.hass, False),
)
pair_data = await dev.pair(
self._ch_type, self._pairing_token, user_input[CONF_PIN]
)
if pair_data:
self._data[CONF_ACCESS_TOKEN] = pair_data.auth_token
self._must_show_form = True
# pylint: disable=no-member # https://github.com/PyCQA/pylint/issues/3167
if self.context["source"] == SOURCE_IMPORT:
# If user is pairing via config import, show different message
return await self.async_step_pairing_complete_import()
return await self.async_step_pairing_complete()
# If no data was retrieved, it's assumed that the pairing attempt was not
# successful
errors[CONF_PIN] = "complete_pairing_failed"
return self.async_show_form(
step_id="pair_tv",
data_schema=_get_pairing_schema(user_input),
errors=errors,
) | [
"async",
"def",
"async_step_pair_tv",
"(",
"self",
",",
"user_input",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"None",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"errors",
"=",
"{",
"}",
"# Start pairing process if it hasn't already started",
"if",
"not",
"self",
".",
"_ch_type",
"and",
"not",
"self",
".",
"_pairing_token",
":",
"dev",
"=",
"VizioAsync",
"(",
"DEVICE_ID",
",",
"self",
".",
"_data",
"[",
"CONF_HOST",
"]",
",",
"self",
".",
"_data",
"[",
"CONF_NAME",
"]",
",",
"None",
",",
"self",
".",
"_data",
"[",
"CONF_DEVICE_CLASS",
"]",
",",
"session",
"=",
"async_get_clientsession",
"(",
"self",
".",
"hass",
",",
"False",
")",
",",
")",
"pair_data",
"=",
"await",
"dev",
".",
"start_pair",
"(",
")",
"if",
"pair_data",
":",
"self",
".",
"_ch_type",
"=",
"pair_data",
".",
"ch_type",
"self",
".",
"_pairing_token",
"=",
"pair_data",
".",
"token",
"return",
"await",
"self",
".",
"async_step_pair_tv",
"(",
")",
"return",
"self",
".",
"async_show_form",
"(",
"step_id",
"=",
"\"user\"",
",",
"data_schema",
"=",
"_get_config_schema",
"(",
"self",
".",
"_data",
")",
",",
"errors",
"=",
"{",
"\"base\"",
":",
"\"cannot_connect\"",
"}",
",",
")",
"# Complete pairing process if PIN has been provided",
"if",
"user_input",
"and",
"user_input",
".",
"get",
"(",
"CONF_PIN",
")",
":",
"dev",
"=",
"VizioAsync",
"(",
"DEVICE_ID",
",",
"self",
".",
"_data",
"[",
"CONF_HOST",
"]",
",",
"self",
".",
"_data",
"[",
"CONF_NAME",
"]",
",",
"None",
",",
"self",
".",
"_data",
"[",
"CONF_DEVICE_CLASS",
"]",
",",
"session",
"=",
"async_get_clientsession",
"(",
"self",
".",
"hass",
",",
"False",
")",
",",
")",
"pair_data",
"=",
"await",
"dev",
".",
"pair",
"(",
"self",
".",
"_ch_type",
",",
"self",
".",
"_pairing_token",
",",
"user_input",
"[",
"CONF_PIN",
"]",
")",
"if",
"pair_data",
":",
"self",
".",
"_data",
"[",
"CONF_ACCESS_TOKEN",
"]",
"=",
"pair_data",
".",
"auth_token",
"self",
".",
"_must_show_form",
"=",
"True",
"# pylint: disable=no-member # https://github.com/PyCQA/pylint/issues/3167",
"if",
"self",
".",
"context",
"[",
"\"source\"",
"]",
"==",
"SOURCE_IMPORT",
":",
"# If user is pairing via config import, show different message",
"return",
"await",
"self",
".",
"async_step_pairing_complete_import",
"(",
")",
"return",
"await",
"self",
".",
"async_step_pairing_complete",
"(",
")",
"# If no data was retrieved, it's assumed that the pairing attempt was not",
"# successful",
"errors",
"[",
"CONF_PIN",
"]",
"=",
"\"complete_pairing_failed\"",
"return",
"self",
".",
"async_show_form",
"(",
"step_id",
"=",
"\"pair_tv\"",
",",
"data_schema",
"=",
"_get_pairing_schema",
"(",
"user_input",
")",
",",
"errors",
"=",
"errors",
",",
")"
] | [
383,
4
] | [
449,
9
] | python | en | ['en', 'error', 'th'] | False |
VizioConfigFlow._pairing_complete | (self, step_id: str) | Handle config flow completion. | Handle config flow completion. | async def _pairing_complete(self, step_id: str) -> Dict[str, Any]:
"""Handle config flow completion."""
if not self._must_show_form:
return await self._create_entry(self._data)
self._must_show_form = False
return self.async_show_form(
step_id=step_id,
data_schema=vol.Schema({}),
description_placeholders={"access_token": self._data[CONF_ACCESS_TOKEN]},
) | [
"async",
"def",
"_pairing_complete",
"(",
"self",
",",
"step_id",
":",
"str",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"if",
"not",
"self",
".",
"_must_show_form",
":",
"return",
"await",
"self",
".",
"_create_entry",
"(",
"self",
".",
"_data",
")",
"self",
".",
"_must_show_form",
"=",
"False",
"return",
"self",
".",
"async_show_form",
"(",
"step_id",
"=",
"step_id",
",",
"data_schema",
"=",
"vol",
".",
"Schema",
"(",
"{",
"}",
")",
",",
"description_placeholders",
"=",
"{",
"\"access_token\"",
":",
"self",
".",
"_data",
"[",
"CONF_ACCESS_TOKEN",
"]",
"}",
",",
")"
] | [
451,
4
] | [
461,
9
] | python | en | ['en', 'en', 'en'] | True |
VizioConfigFlow.async_step_pairing_complete | (
self, user_input: Dict[str, Any] = None
) |
Complete non-import sourced config flow.
Display final message to user confirming pairing.
|
Complete non-import sourced config flow. | async def async_step_pairing_complete(
self, user_input: Dict[str, Any] = None
) -> Dict[str, Any]:
"""
Complete non-import sourced config flow.
Display final message to user confirming pairing.
"""
return await self._pairing_complete("pairing_complete") | [
"async",
"def",
"async_step_pairing_complete",
"(",
"self",
",",
"user_input",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"None",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"return",
"await",
"self",
".",
"_pairing_complete",
"(",
"\"pairing_complete\"",
")"
] | [
463,
4
] | [
471,
63
] | python | en | ['en', 'error', 'th'] | False |
VizioConfigFlow.async_step_pairing_complete_import | (
self, user_input: Dict[str, Any] = None
) |
Complete import sourced config flow.
Display final message to user confirming pairing and displaying
access token.
|
Complete import sourced config flow. | async def async_step_pairing_complete_import(
self, user_input: Dict[str, Any] = None
) -> Dict[str, Any]:
"""
Complete import sourced config flow.
Display final message to user confirming pairing and displaying
access token.
"""
return await self._pairing_complete("pairing_complete_import") | [
"async",
"def",
"async_step_pairing_complete_import",
"(",
"self",
",",
"user_input",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"None",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"return",
"await",
"self",
".",
"_pairing_complete",
"(",
"\"pairing_complete_import\"",
")"
] | [
473,
4
] | [
482,
70
] | python | en | ['en', 'error', 'th'] | False |
test_subscribing_config_topic | (hass, mqtt_mock, setup_tasmota) | Test setting up discovery. | Test setting up discovery. | async def test_subscribing_config_topic(hass, mqtt_mock, setup_tasmota):
"""Test setting up discovery."""
discovery_topic = DEFAULT_PREFIX
assert mqtt_mock.async_subscribe.called
call_args = mqtt_mock.async_subscribe.mock_calls[0][1]
assert call_args[0] == discovery_topic + "/#"
assert call_args[2] == 0 | [
"async",
"def",
"test_subscribing_config_topic",
"(",
"hass",
",",
"mqtt_mock",
",",
"setup_tasmota",
")",
":",
"discovery_topic",
"=",
"DEFAULT_PREFIX",
"assert",
"mqtt_mock",
".",
"async_subscribe",
".",
"called",
"call_args",
"=",
"mqtt_mock",
".",
"async_subscribe",
".",
"mock_calls",
"[",
"0",
"]",
"[",
"1",
"]",
"assert",
"call_args",
"[",
"0",
"]",
"==",
"discovery_topic",
"+",
"\"/#\"",
"assert",
"call_args",
"[",
"2",
"]",
"==",
"0"
] | [
14,
0
] | [
21,
28
] | python | en | ['en', 'en', 'en'] | True |
test_future_discovery_message | (hass, mqtt_mock, caplog) | Test we handle backwards compatible discovery messages. | Test we handle backwards compatible discovery messages. | async def test_future_discovery_message(hass, mqtt_mock, caplog):
"""Test we handle backwards compatible discovery messages."""
config = copy.deepcopy(DEFAULT_CONFIG)
config["future_option"] = "BEST_SINCE_SLICED_BREAD"
config["so"]["another_future_option"] = "EVEN_BETTER"
with patch(
"homeassistant.components.tasmota.discovery.tasmota_get_device_config",
return_value={},
) as mock_tasmota_get_device_config:
await setup_tasmota_helper(hass)
async_fire_mqtt_message(
hass, f"{DEFAULT_PREFIX}/00000049A3BC/config", json.dumps(config)
)
await hass.async_block_till_done()
assert mock_tasmota_get_device_config.called | [
"async",
"def",
"test_future_discovery_message",
"(",
"hass",
",",
"mqtt_mock",
",",
"caplog",
")",
":",
"config",
"=",
"copy",
".",
"deepcopy",
"(",
"DEFAULT_CONFIG",
")",
"config",
"[",
"\"future_option\"",
"]",
"=",
"\"BEST_SINCE_SLICED_BREAD\"",
"config",
"[",
"\"so\"",
"]",
"[",
"\"another_future_option\"",
"]",
"=",
"\"EVEN_BETTER\"",
"with",
"patch",
"(",
"\"homeassistant.components.tasmota.discovery.tasmota_get_device_config\"",
",",
"return_value",
"=",
"{",
"}",
",",
")",
"as",
"mock_tasmota_get_device_config",
":",
"await",
"setup_tasmota_helper",
"(",
"hass",
")",
"async_fire_mqtt_message",
"(",
"hass",
",",
"f\"{DEFAULT_PREFIX}/00000049A3BC/config\"",
",",
"json",
".",
"dumps",
"(",
"config",
")",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"mock_tasmota_get_device_config",
".",
"called"
] | [
24,
0
] | [
40,
52
] | python | en | ['en', 'en', 'en'] | True |
test_valid_discovery_message | (hass, mqtt_mock, caplog) | Test discovery callback called. | Test discovery callback called. | async def test_valid_discovery_message(hass, mqtt_mock, caplog):
"""Test discovery callback called."""
config = copy.deepcopy(DEFAULT_CONFIG)
with patch(
"homeassistant.components.tasmota.discovery.tasmota_get_device_config",
return_value={},
) as mock_tasmota_get_device_config:
await setup_tasmota_helper(hass)
async_fire_mqtt_message(
hass, f"{DEFAULT_PREFIX}/00000049A3BC/config", json.dumps(config)
)
await hass.async_block_till_done()
assert mock_tasmota_get_device_config.called | [
"async",
"def",
"test_valid_discovery_message",
"(",
"hass",
",",
"mqtt_mock",
",",
"caplog",
")",
":",
"config",
"=",
"copy",
".",
"deepcopy",
"(",
"DEFAULT_CONFIG",
")",
"with",
"patch",
"(",
"\"homeassistant.components.tasmota.discovery.tasmota_get_device_config\"",
",",
"return_value",
"=",
"{",
"}",
",",
")",
"as",
"mock_tasmota_get_device_config",
":",
"await",
"setup_tasmota_helper",
"(",
"hass",
")",
"async_fire_mqtt_message",
"(",
"hass",
",",
"f\"{DEFAULT_PREFIX}/00000049A3BC/config\"",
",",
"json",
".",
"dumps",
"(",
"config",
")",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"mock_tasmota_get_device_config",
".",
"called"
] | [
43,
0
] | [
57,
52
] | python | en | ['en', 'en', 'en'] | True |
test_invalid_topic | (hass, mqtt_mock) | Test receiving discovery message on wrong topic. | Test receiving discovery message on wrong topic. | async def test_invalid_topic(hass, mqtt_mock):
"""Test receiving discovery message on wrong topic."""
with patch(
"homeassistant.components.tasmota.discovery.tasmota_get_device_config"
) as mock_tasmota_get_device_config:
await setup_tasmota_helper(hass)
async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/123456/configuration", "{}")
await hass.async_block_till_done()
assert not mock_tasmota_get_device_config.called | [
"async",
"def",
"test_invalid_topic",
"(",
"hass",
",",
"mqtt_mock",
")",
":",
"with",
"patch",
"(",
"\"homeassistant.components.tasmota.discovery.tasmota_get_device_config\"",
")",
"as",
"mock_tasmota_get_device_config",
":",
"await",
"setup_tasmota_helper",
"(",
"hass",
")",
"async_fire_mqtt_message",
"(",
"hass",
",",
"f\"{DEFAULT_PREFIX}/123456/configuration\"",
",",
"\"{}\"",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"not",
"mock_tasmota_get_device_config",
".",
"called"
] | [
60,
0
] | [
69,
56
] | python | en | ['en', 'en', 'en'] | True |
test_invalid_message | (hass, mqtt_mock, caplog) | Test receiving an invalid message. | Test receiving an invalid message. | async def test_invalid_message(hass, mqtt_mock, caplog):
"""Test receiving an invalid message."""
with patch(
"homeassistant.components.tasmota.discovery.tasmota_get_device_config"
) as mock_tasmota_get_device_config:
await setup_tasmota_helper(hass)
async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/123456/config", "asd")
await hass.async_block_till_done()
assert "Invalid discovery message" in caplog.text
assert not mock_tasmota_get_device_config.called | [
"async",
"def",
"test_invalid_message",
"(",
"hass",
",",
"mqtt_mock",
",",
"caplog",
")",
":",
"with",
"patch",
"(",
"\"homeassistant.components.tasmota.discovery.tasmota_get_device_config\"",
")",
"as",
"mock_tasmota_get_device_config",
":",
"await",
"setup_tasmota_helper",
"(",
"hass",
")",
"async_fire_mqtt_message",
"(",
"hass",
",",
"f\"{DEFAULT_PREFIX}/123456/config\"",
",",
"\"asd\"",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"\"Invalid discovery message\"",
"in",
"caplog",
".",
"text",
"assert",
"not",
"mock_tasmota_get_device_config",
".",
"called"
] | [
72,
0
] | [
82,
56
] | python | en | ['en', 'en', 'en'] | True |
test_invalid_mac | (hass, mqtt_mock, caplog) | Test topic is not matching device MAC. | Test topic is not matching device MAC. | async def test_invalid_mac(hass, mqtt_mock, caplog):
"""Test topic is not matching device MAC."""
config = copy.deepcopy(DEFAULT_CONFIG)
with patch(
"homeassistant.components.tasmota.discovery.tasmota_get_device_config"
) as mock_tasmota_get_device_config:
await setup_tasmota_helper(hass)
async_fire_mqtt_message(
hass, f"{DEFAULT_PREFIX}/00000049A3BA/config", json.dumps(config)
)
await hass.async_block_till_done()
assert "MAC mismatch" in caplog.text
assert not mock_tasmota_get_device_config.called | [
"async",
"def",
"test_invalid_mac",
"(",
"hass",
",",
"mqtt_mock",
",",
"caplog",
")",
":",
"config",
"=",
"copy",
".",
"deepcopy",
"(",
"DEFAULT_CONFIG",
")",
"with",
"patch",
"(",
"\"homeassistant.components.tasmota.discovery.tasmota_get_device_config\"",
")",
"as",
"mock_tasmota_get_device_config",
":",
"await",
"setup_tasmota_helper",
"(",
"hass",
")",
"async_fire_mqtt_message",
"(",
"hass",
",",
"f\"{DEFAULT_PREFIX}/00000049A3BA/config\"",
",",
"json",
".",
"dumps",
"(",
"config",
")",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"\"MAC mismatch\"",
"in",
"caplog",
".",
"text",
"assert",
"not",
"mock_tasmota_get_device_config",
".",
"called"
] | [
85,
0
] | [
99,
56
] | python | en | ['en', 'en', 'en'] | True |
test_correct_config_discovery | (
hass, mqtt_mock, caplog, device_reg, entity_reg, setup_tasmota
) | Test receiving valid discovery message. | Test receiving valid discovery message. | async def test_correct_config_discovery(
hass, mqtt_mock, caplog, device_reg, entity_reg, setup_tasmota
):
"""Test receiving valid discovery message."""
config = copy.deepcopy(DEFAULT_CONFIG)
config["rl"][0] = 1
mac = config["mac"]
async_fire_mqtt_message(
hass,
f"{DEFAULT_PREFIX}/{mac}/config",
json.dumps(config),
)
await hass.async_block_till_done()
# Verify device and registry entries are created
device_entry = device_reg.async_get_device(set(), {("mac", mac)})
assert device_entry is not None
entity_entry = entity_reg.async_get("switch.test")
assert entity_entry is not None
state = hass.states.get("switch.test")
assert state is not None
assert state.name == "Test"
assert (mac, "switch", "relay", 0) in hass.data[ALREADY_DISCOVERED] | [
"async",
"def",
"test_correct_config_discovery",
"(",
"hass",
",",
"mqtt_mock",
",",
"caplog",
",",
"device_reg",
",",
"entity_reg",
",",
"setup_tasmota",
")",
":",
"config",
"=",
"copy",
".",
"deepcopy",
"(",
"DEFAULT_CONFIG",
")",
"config",
"[",
"\"rl\"",
"]",
"[",
"0",
"]",
"=",
"1",
"mac",
"=",
"config",
"[",
"\"mac\"",
"]",
"async_fire_mqtt_message",
"(",
"hass",
",",
"f\"{DEFAULT_PREFIX}/{mac}/config\"",
",",
"json",
".",
"dumps",
"(",
"config",
")",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"# Verify device and registry entries are created",
"device_entry",
"=",
"device_reg",
".",
"async_get_device",
"(",
"set",
"(",
")",
",",
"{",
"(",
"\"mac\"",
",",
"mac",
")",
"}",
")",
"assert",
"device_entry",
"is",
"not",
"None",
"entity_entry",
"=",
"entity_reg",
".",
"async_get",
"(",
"\"switch.test\"",
")",
"assert",
"entity_entry",
"is",
"not",
"None",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"switch.test\"",
")",
"assert",
"state",
"is",
"not",
"None",
"assert",
"state",
".",
"name",
"==",
"\"Test\"",
"assert",
"(",
"mac",
",",
"\"switch\"",
",",
"\"relay\"",
",",
"0",
")",
"in",
"hass",
".",
"data",
"[",
"ALREADY_DISCOVERED",
"]"
] | [
102,
0
] | [
127,
71
] | python | en | ['nl', 'en', 'en'] | True |
test_device_discover | (
hass, mqtt_mock, caplog, device_reg, entity_reg, setup_tasmota
) | Test setting up a device. | Test setting up a device. | async def test_device_discover(
hass, mqtt_mock, caplog, device_reg, entity_reg, setup_tasmota
):
"""Test setting up a device."""
config = copy.deepcopy(DEFAULT_CONFIG)
mac = config["mac"]
async_fire_mqtt_message(
hass,
f"{DEFAULT_PREFIX}/{mac}/config",
json.dumps(config),
)
await hass.async_block_till_done()
# Verify device and registry entries are created
device_entry = device_reg.async_get_device(set(), {("mac", mac)})
assert device_entry is not None
assert device_entry.manufacturer == "Tasmota"
assert device_entry.model == config["md"]
assert device_entry.name == config["dn"]
assert device_entry.sw_version == config["sw"] | [
"async",
"def",
"test_device_discover",
"(",
"hass",
",",
"mqtt_mock",
",",
"caplog",
",",
"device_reg",
",",
"entity_reg",
",",
"setup_tasmota",
")",
":",
"config",
"=",
"copy",
".",
"deepcopy",
"(",
"DEFAULT_CONFIG",
")",
"mac",
"=",
"config",
"[",
"\"mac\"",
"]",
"async_fire_mqtt_message",
"(",
"hass",
",",
"f\"{DEFAULT_PREFIX}/{mac}/config\"",
",",
"json",
".",
"dumps",
"(",
"config",
")",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"# Verify device and registry entries are created",
"device_entry",
"=",
"device_reg",
".",
"async_get_device",
"(",
"set",
"(",
")",
",",
"{",
"(",
"\"mac\"",
",",
"mac",
")",
"}",
")",
"assert",
"device_entry",
"is",
"not",
"None",
"assert",
"device_entry",
".",
"manufacturer",
"==",
"\"Tasmota\"",
"assert",
"device_entry",
".",
"model",
"==",
"config",
"[",
"\"md\"",
"]",
"assert",
"device_entry",
".",
"name",
"==",
"config",
"[",
"\"dn\"",
"]",
"assert",
"device_entry",
".",
"sw_version",
"==",
"config",
"[",
"\"sw\"",
"]"
] | [
130,
0
] | [
150,
50
] | python | en | ['en', 'en', 'en'] | True |
test_device_discover_deprecated | (
hass, mqtt_mock, caplog, device_reg, entity_reg, setup_tasmota
) | Test setting up a device with deprecated discovery message. | Test setting up a device with deprecated discovery message. | async def test_device_discover_deprecated(
hass, mqtt_mock, caplog, device_reg, entity_reg, setup_tasmota
):
"""Test setting up a device with deprecated discovery message."""
config = copy.deepcopy(DEFAULT_CONFIG_9_0_0_3)
mac = config["mac"]
async_fire_mqtt_message(
hass,
f"{DEFAULT_PREFIX}/{mac}/config",
json.dumps(config),
)
await hass.async_block_till_done()
# Verify device and registry entries are created
device_entry = device_reg.async_get_device(set(), {("mac", mac)})
assert device_entry is not None
assert device_entry.manufacturer == "Tasmota"
assert device_entry.model == config["md"]
assert device_entry.name == config["dn"]
assert device_entry.sw_version == config["sw"] | [
"async",
"def",
"test_device_discover_deprecated",
"(",
"hass",
",",
"mqtt_mock",
",",
"caplog",
",",
"device_reg",
",",
"entity_reg",
",",
"setup_tasmota",
")",
":",
"config",
"=",
"copy",
".",
"deepcopy",
"(",
"DEFAULT_CONFIG_9_0_0_3",
")",
"mac",
"=",
"config",
"[",
"\"mac\"",
"]",
"async_fire_mqtt_message",
"(",
"hass",
",",
"f\"{DEFAULT_PREFIX}/{mac}/config\"",
",",
"json",
".",
"dumps",
"(",
"config",
")",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"# Verify device and registry entries are created",
"device_entry",
"=",
"device_reg",
".",
"async_get_device",
"(",
"set",
"(",
")",
",",
"{",
"(",
"\"mac\"",
",",
"mac",
")",
"}",
")",
"assert",
"device_entry",
"is",
"not",
"None",
"assert",
"device_entry",
".",
"manufacturer",
"==",
"\"Tasmota\"",
"assert",
"device_entry",
".",
"model",
"==",
"config",
"[",
"\"md\"",
"]",
"assert",
"device_entry",
".",
"name",
"==",
"config",
"[",
"\"dn\"",
"]",
"assert",
"device_entry",
".",
"sw_version",
"==",
"config",
"[",
"\"sw\"",
"]"
] | [
153,
0
] | [
173,
50
] | python | en | ['en', 'en', 'en'] | True |
test_device_update | (
hass, mqtt_mock, caplog, device_reg, entity_reg, setup_tasmota
) | Test updating a device. | Test updating a device. | async def test_device_update(
hass, mqtt_mock, caplog, device_reg, entity_reg, setup_tasmota
):
"""Test updating a device."""
config = copy.deepcopy(DEFAULT_CONFIG)
config["md"] = "Model 1"
config["dn"] = "Name 1"
config["sw"] = "v1.2.3.4"
mac = config["mac"]
async_fire_mqtt_message(
hass,
f"{DEFAULT_PREFIX}/{mac}/config",
json.dumps(config),
)
await hass.async_block_till_done()
# Verify device entry is created
device_entry = device_reg.async_get_device(set(), {("mac", mac)})
assert device_entry is not None
# Update device parameters
config["md"] = "Another model"
config["dn"] = "Another name"
config["sw"] = "v6.6.6"
async_fire_mqtt_message(
hass,
f"{DEFAULT_PREFIX}/{mac}/config",
json.dumps(config),
)
await hass.async_block_till_done()
# Verify device entry is updated
device_entry = device_reg.async_get_device(set(), {("mac", mac)})
assert device_entry is not None
assert device_entry.model == "Another model"
assert device_entry.name == "Another name"
assert device_entry.sw_version == "v6.6.6" | [
"async",
"def",
"test_device_update",
"(",
"hass",
",",
"mqtt_mock",
",",
"caplog",
",",
"device_reg",
",",
"entity_reg",
",",
"setup_tasmota",
")",
":",
"config",
"=",
"copy",
".",
"deepcopy",
"(",
"DEFAULT_CONFIG",
")",
"config",
"[",
"\"md\"",
"]",
"=",
"\"Model 1\"",
"config",
"[",
"\"dn\"",
"]",
"=",
"\"Name 1\"",
"config",
"[",
"\"sw\"",
"]",
"=",
"\"v1.2.3.4\"",
"mac",
"=",
"config",
"[",
"\"mac\"",
"]",
"async_fire_mqtt_message",
"(",
"hass",
",",
"f\"{DEFAULT_PREFIX}/{mac}/config\"",
",",
"json",
".",
"dumps",
"(",
"config",
")",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"# Verify device entry is created",
"device_entry",
"=",
"device_reg",
".",
"async_get_device",
"(",
"set",
"(",
")",
",",
"{",
"(",
"\"mac\"",
",",
"mac",
")",
"}",
")",
"assert",
"device_entry",
"is",
"not",
"None",
"# Update device parameters",
"config",
"[",
"\"md\"",
"]",
"=",
"\"Another model\"",
"config",
"[",
"\"dn\"",
"]",
"=",
"\"Another name\"",
"config",
"[",
"\"sw\"",
"]",
"=",
"\"v6.6.6\"",
"async_fire_mqtt_message",
"(",
"hass",
",",
"f\"{DEFAULT_PREFIX}/{mac}/config\"",
",",
"json",
".",
"dumps",
"(",
"config",
")",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"# Verify device entry is updated",
"device_entry",
"=",
"device_reg",
".",
"async_get_device",
"(",
"set",
"(",
")",
",",
"{",
"(",
"\"mac\"",
",",
"mac",
")",
"}",
")",
"assert",
"device_entry",
"is",
"not",
"None",
"assert",
"device_entry",
".",
"model",
"==",
"\"Another model\"",
"assert",
"device_entry",
".",
"name",
"==",
"\"Another name\"",
"assert",
"device_entry",
".",
"sw_version",
"==",
"\"v6.6.6\""
] | [
176,
0
] | [
214,
46
] | python | en | ['es', 'en', 'en'] | True |
test_device_remove | (
hass, mqtt_mock, caplog, device_reg, entity_reg, setup_tasmota
) | Test removing a discovered device. | Test removing a discovered device. | async def test_device_remove(
hass, mqtt_mock, caplog, device_reg, entity_reg, setup_tasmota
):
"""Test removing a discovered device."""
config = copy.deepcopy(DEFAULT_CONFIG)
mac = config["mac"]
async_fire_mqtt_message(
hass,
f"{DEFAULT_PREFIX}/{mac}/config",
json.dumps(config),
)
await hass.async_block_till_done()
# Verify device entry is created
device_entry = device_reg.async_get_device(set(), {("mac", mac)})
assert device_entry is not None
async_fire_mqtt_message(
hass,
f"{DEFAULT_PREFIX}/{mac}/config",
"",
)
await hass.async_block_till_done()
# Verify device entry is removed
device_entry = device_reg.async_get_device(set(), {("mac", mac)})
assert device_entry is None | [
"async",
"def",
"test_device_remove",
"(",
"hass",
",",
"mqtt_mock",
",",
"caplog",
",",
"device_reg",
",",
"entity_reg",
",",
"setup_tasmota",
")",
":",
"config",
"=",
"copy",
".",
"deepcopy",
"(",
"DEFAULT_CONFIG",
")",
"mac",
"=",
"config",
"[",
"\"mac\"",
"]",
"async_fire_mqtt_message",
"(",
"hass",
",",
"f\"{DEFAULT_PREFIX}/{mac}/config\"",
",",
"json",
".",
"dumps",
"(",
"config",
")",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"# Verify device entry is created",
"device_entry",
"=",
"device_reg",
".",
"async_get_device",
"(",
"set",
"(",
")",
",",
"{",
"(",
"\"mac\"",
",",
"mac",
")",
"}",
")",
"assert",
"device_entry",
"is",
"not",
"None",
"async_fire_mqtt_message",
"(",
"hass",
",",
"f\"{DEFAULT_PREFIX}/{mac}/config\"",
",",
"\"\"",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"# Verify device entry is removed",
"device_entry",
"=",
"device_reg",
".",
"async_get_device",
"(",
"set",
"(",
")",
",",
"{",
"(",
"\"mac\"",
",",
"mac",
")",
"}",
")",
"assert",
"device_entry",
"is",
"None"
] | [
217,
0
] | [
244,
31
] | python | en | ['en', 'en', 'en'] | True |
test_device_remove_stale | (hass, mqtt_mock, caplog, device_reg, setup_tasmota) | Test removing a stale (undiscovered) device does not throw. | Test removing a stale (undiscovered) device does not throw. | async def test_device_remove_stale(hass, mqtt_mock, caplog, device_reg, setup_tasmota):
"""Test removing a stale (undiscovered) device does not throw."""
mac = "00000049A3BC"
config_entry = hass.config_entries.async_entries("tasmota")[0]
# Create a device
device_reg.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={("mac", mac)},
)
# Verify device entry was created
device_entry = device_reg.async_get_device(set(), {("mac", mac)})
assert device_entry is not None
# Remove the device
device_reg.async_remove_device(device_entry.id)
# Verify device entry is removed
device_entry = device_reg.async_get_device(set(), {("mac", mac)})
assert device_entry is None | [
"async",
"def",
"test_device_remove_stale",
"(",
"hass",
",",
"mqtt_mock",
",",
"caplog",
",",
"device_reg",
",",
"setup_tasmota",
")",
":",
"mac",
"=",
"\"00000049A3BC\"",
"config_entry",
"=",
"hass",
".",
"config_entries",
".",
"async_entries",
"(",
"\"tasmota\"",
")",
"[",
"0",
"]",
"# Create a device",
"device_reg",
".",
"async_get_or_create",
"(",
"config_entry_id",
"=",
"config_entry",
".",
"entry_id",
",",
"connections",
"=",
"{",
"(",
"\"mac\"",
",",
"mac",
")",
"}",
",",
")",
"# Verify device entry was created",
"device_entry",
"=",
"device_reg",
".",
"async_get_device",
"(",
"set",
"(",
")",
",",
"{",
"(",
"\"mac\"",
",",
"mac",
")",
"}",
")",
"assert",
"device_entry",
"is",
"not",
"None",
"# Remove the device",
"device_reg",
".",
"async_remove_device",
"(",
"device_entry",
".",
"id",
")",
"# Verify device entry is removed",
"device_entry",
"=",
"device_reg",
".",
"async_get_device",
"(",
"set",
"(",
")",
",",
"{",
"(",
"\"mac\"",
",",
"mac",
")",
"}",
")",
"assert",
"device_entry",
"is",
"None"
] | [
247,
0
] | [
268,
31
] | python | en | ['en', 'en', 'en'] | True |
test_device_rediscover | (
hass, mqtt_mock, caplog, device_reg, entity_reg, setup_tasmota
) | Test removing a device. | Test removing a device. | async def test_device_rediscover(
hass, mqtt_mock, caplog, device_reg, entity_reg, setup_tasmota
):
"""Test removing a device."""
config = copy.deepcopy(DEFAULT_CONFIG)
mac = config["mac"]
async_fire_mqtt_message(
hass,
f"{DEFAULT_PREFIX}/{mac}/config",
json.dumps(config),
)
await hass.async_block_till_done()
# Verify device entry is created
device_entry1 = device_reg.async_get_device(set(), {("mac", mac)})
assert device_entry1 is not None
async_fire_mqtt_message(
hass,
f"{DEFAULT_PREFIX}/{mac}/config",
"",
)
await hass.async_block_till_done()
# Verify device entry is removed
device_entry = device_reg.async_get_device(set(), {("mac", mac)})
assert device_entry is None
async_fire_mqtt_message(
hass,
f"{DEFAULT_PREFIX}/{mac}/config",
json.dumps(config),
)
await hass.async_block_till_done()
# Verify device entry is created, and id is reused
device_entry = device_reg.async_get_device(set(), {("mac", mac)})
assert device_entry is not None
assert device_entry1.id == device_entry.id | [
"async",
"def",
"test_device_rediscover",
"(",
"hass",
",",
"mqtt_mock",
",",
"caplog",
",",
"device_reg",
",",
"entity_reg",
",",
"setup_tasmota",
")",
":",
"config",
"=",
"copy",
".",
"deepcopy",
"(",
"DEFAULT_CONFIG",
")",
"mac",
"=",
"config",
"[",
"\"mac\"",
"]",
"async_fire_mqtt_message",
"(",
"hass",
",",
"f\"{DEFAULT_PREFIX}/{mac}/config\"",
",",
"json",
".",
"dumps",
"(",
"config",
")",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"# Verify device entry is created",
"device_entry1",
"=",
"device_reg",
".",
"async_get_device",
"(",
"set",
"(",
")",
",",
"{",
"(",
"\"mac\"",
",",
"mac",
")",
"}",
")",
"assert",
"device_entry1",
"is",
"not",
"None",
"async_fire_mqtt_message",
"(",
"hass",
",",
"f\"{DEFAULT_PREFIX}/{mac}/config\"",
",",
"\"\"",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"# Verify device entry is removed",
"device_entry",
"=",
"device_reg",
".",
"async_get_device",
"(",
"set",
"(",
")",
",",
"{",
"(",
"\"mac\"",
",",
"mac",
")",
"}",
")",
"assert",
"device_entry",
"is",
"None",
"async_fire_mqtt_message",
"(",
"hass",
",",
"f\"{DEFAULT_PREFIX}/{mac}/config\"",
",",
"json",
".",
"dumps",
"(",
"config",
")",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"# Verify device entry is created, and id is reused",
"device_entry",
"=",
"device_reg",
".",
"async_get_device",
"(",
"set",
"(",
")",
",",
"{",
"(",
"\"mac\"",
",",
"mac",
")",
"}",
")",
"assert",
"device_entry",
"is",
"not",
"None",
"assert",
"device_entry1",
".",
"id",
"==",
"device_entry",
".",
"id"
] | [
271,
0
] | [
310,
46
] | python | en | ['en', 'en', 'en'] | True |
test_entity_duplicate_discovery | (hass, mqtt_mock, caplog, setup_tasmota) | Test entities are not duplicated. | Test entities are not duplicated. | async def test_entity_duplicate_discovery(hass, mqtt_mock, caplog, setup_tasmota):
"""Test entities are not duplicated."""
config = copy.deepcopy(DEFAULT_CONFIG)
config["rl"][0] = 1
mac = config["mac"]
async_fire_mqtt_message(
hass,
f"{DEFAULT_PREFIX}/{mac}/config",
json.dumps(config),
)
async_fire_mqtt_message(
hass,
f"{DEFAULT_PREFIX}/{mac}/config",
json.dumps(config),
)
await hass.async_block_till_done()
state = hass.states.get("switch.test")
state_duplicate = hass.states.get("binary_sensor.beer1")
assert state is not None
assert state.name == "Test"
assert state_duplicate is None
assert (
f"Entity already added, sending update: switch ('{mac}', 'switch', 'relay', 0)"
in caplog.text
) | [
"async",
"def",
"test_entity_duplicate_discovery",
"(",
"hass",
",",
"mqtt_mock",
",",
"caplog",
",",
"setup_tasmota",
")",
":",
"config",
"=",
"copy",
".",
"deepcopy",
"(",
"DEFAULT_CONFIG",
")",
"config",
"[",
"\"rl\"",
"]",
"[",
"0",
"]",
"=",
"1",
"mac",
"=",
"config",
"[",
"\"mac\"",
"]",
"async_fire_mqtt_message",
"(",
"hass",
",",
"f\"{DEFAULT_PREFIX}/{mac}/config\"",
",",
"json",
".",
"dumps",
"(",
"config",
")",
",",
")",
"async_fire_mqtt_message",
"(",
"hass",
",",
"f\"{DEFAULT_PREFIX}/{mac}/config\"",
",",
"json",
".",
"dumps",
"(",
"config",
")",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"switch.test\"",
")",
"state_duplicate",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"binary_sensor.beer1\"",
")",
"assert",
"state",
"is",
"not",
"None",
"assert",
"state",
".",
"name",
"==",
"\"Test\"",
"assert",
"state_duplicate",
"is",
"None",
"assert",
"(",
"f\"Entity already added, sending update: switch ('{mac}', 'switch', 'relay', 0)\"",
"in",
"caplog",
".",
"text",
")"
] | [
313,
0
] | [
340,
5
] | python | en | ['en', 'en', 'en'] | True |
test_entity_duplicate_removal | (hass, mqtt_mock, caplog, setup_tasmota) | Test removing entity twice. | Test removing entity twice. | async def test_entity_duplicate_removal(hass, mqtt_mock, caplog, setup_tasmota):
"""Test removing entity twice."""
config = copy.deepcopy(DEFAULT_CONFIG)
config["rl"][0] = 1
mac = config["mac"]
async_fire_mqtt_message(
hass,
f"{DEFAULT_PREFIX}/{mac}/config",
json.dumps(config),
)
await hass.async_block_till_done()
config["rl"][0] = 0
async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config))
await hass.async_block_till_done()
assert f"Removing entity: switch ('{mac}', 'switch', 'relay', 0)" in caplog.text
caplog.clear()
async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config))
await hass.async_block_till_done()
assert "Removing entity: switch" not in caplog.text | [
"async",
"def",
"test_entity_duplicate_removal",
"(",
"hass",
",",
"mqtt_mock",
",",
"caplog",
",",
"setup_tasmota",
")",
":",
"config",
"=",
"copy",
".",
"deepcopy",
"(",
"DEFAULT_CONFIG",
")",
"config",
"[",
"\"rl\"",
"]",
"[",
"0",
"]",
"=",
"1",
"mac",
"=",
"config",
"[",
"\"mac\"",
"]",
"async_fire_mqtt_message",
"(",
"hass",
",",
"f\"{DEFAULT_PREFIX}/{mac}/config\"",
",",
"json",
".",
"dumps",
"(",
"config",
")",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"config",
"[",
"\"rl\"",
"]",
"[",
"0",
"]",
"=",
"0",
"async_fire_mqtt_message",
"(",
"hass",
",",
"f\"{DEFAULT_PREFIX}/{mac}/config\"",
",",
"json",
".",
"dumps",
"(",
"config",
")",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"f\"Removing entity: switch ('{mac}', 'switch', 'relay', 0)\"",
"in",
"caplog",
".",
"text",
"caplog",
".",
"clear",
"(",
")",
"async_fire_mqtt_message",
"(",
"hass",
",",
"f\"{DEFAULT_PREFIX}/{mac}/config\"",
",",
"json",
".",
"dumps",
"(",
"config",
")",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"\"Removing entity: switch\"",
"not",
"in",
"caplog",
".",
"text"
] | [
343,
0
] | [
363,
55
] | python | en | ['en', 'en', 'en'] | True |
async_setup_entry | (hass, config_entry, async_add_entities) | Set up the Smappee sensor. | Set up the Smappee sensor. | async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the Smappee sensor."""
smappee_base = hass.data[DOMAIN][config_entry.entry_id]
entities = []
for service_location in smappee_base.smappee.service_locations.values():
# Add all basic sensors (realtime values and aggregators)
# Some are available in local only env
for sensor in TREND_SENSORS:
if not service_location.local_polling or TREND_SENSORS[sensor][5]:
entities.append(
SmappeeSensor(
smappee_base=smappee_base,
service_location=service_location,
sensor=sensor,
attributes=TREND_SENSORS[sensor],
)
)
if service_location.has_reactive_value:
for reactive_sensor in REACTIVE_SENSORS:
entities.append(
SmappeeSensor(
smappee_base=smappee_base,
service_location=service_location,
sensor=reactive_sensor,
attributes=REACTIVE_SENSORS[reactive_sensor],
)
)
# Add solar sensors (some are available in local only env)
if service_location.has_solar_production:
for sensor in SOLAR_SENSORS:
if not service_location.local_polling or SOLAR_SENSORS[sensor][5]:
entities.append(
SmappeeSensor(
smappee_base=smappee_base,
service_location=service_location,
sensor=sensor,
attributes=SOLAR_SENSORS[sensor],
)
)
# Add all CT measurements
for measurement_id, measurement in service_location.measurements.items():
entities.append(
SmappeeSensor(
smappee_base=smappee_base,
service_location=service_location,
sensor="load",
attributes=[
measurement.name,
None,
POWER_WATT,
measurement_id,
DEVICE_CLASS_POWER,
],
)
)
# Add phase- and line voltages if available
if service_location.has_voltage_values:
for sensor_name, sensor in VOLTAGE_SENSORS.items():
if service_location.phase_type in sensor[5]:
entities.append(
SmappeeSensor(
smappee_base=smappee_base,
service_location=service_location,
sensor=sensor_name,
attributes=sensor,
)
)
# Add Gas and Water sensors
for sensor_id, sensor in service_location.sensors.items():
for channel in sensor.channels:
gw_icon = "mdi:gas-cylinder"
if channel.get("type") == "water":
gw_icon = "mdi:water"
entities.append(
SmappeeSensor(
smappee_base=smappee_base,
service_location=service_location,
sensor="sensor",
attributes=[
channel.get("name"),
gw_icon,
channel.get("uom"),
f"{sensor_id}-{channel.get('channel')}",
None,
],
)
)
async_add_entities(entities, True) | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
",",
"config_entry",
",",
"async_add_entities",
")",
":",
"smappee_base",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"config_entry",
".",
"entry_id",
"]",
"entities",
"=",
"[",
"]",
"for",
"service_location",
"in",
"smappee_base",
".",
"smappee",
".",
"service_locations",
".",
"values",
"(",
")",
":",
"# Add all basic sensors (realtime values and aggregators)",
"# Some are available in local only env",
"for",
"sensor",
"in",
"TREND_SENSORS",
":",
"if",
"not",
"service_location",
".",
"local_polling",
"or",
"TREND_SENSORS",
"[",
"sensor",
"]",
"[",
"5",
"]",
":",
"entities",
".",
"append",
"(",
"SmappeeSensor",
"(",
"smappee_base",
"=",
"smappee_base",
",",
"service_location",
"=",
"service_location",
",",
"sensor",
"=",
"sensor",
",",
"attributes",
"=",
"TREND_SENSORS",
"[",
"sensor",
"]",
",",
")",
")",
"if",
"service_location",
".",
"has_reactive_value",
":",
"for",
"reactive_sensor",
"in",
"REACTIVE_SENSORS",
":",
"entities",
".",
"append",
"(",
"SmappeeSensor",
"(",
"smappee_base",
"=",
"smappee_base",
",",
"service_location",
"=",
"service_location",
",",
"sensor",
"=",
"reactive_sensor",
",",
"attributes",
"=",
"REACTIVE_SENSORS",
"[",
"reactive_sensor",
"]",
",",
")",
")",
"# Add solar sensors (some are available in local only env)",
"if",
"service_location",
".",
"has_solar_production",
":",
"for",
"sensor",
"in",
"SOLAR_SENSORS",
":",
"if",
"not",
"service_location",
".",
"local_polling",
"or",
"SOLAR_SENSORS",
"[",
"sensor",
"]",
"[",
"5",
"]",
":",
"entities",
".",
"append",
"(",
"SmappeeSensor",
"(",
"smappee_base",
"=",
"smappee_base",
",",
"service_location",
"=",
"service_location",
",",
"sensor",
"=",
"sensor",
",",
"attributes",
"=",
"SOLAR_SENSORS",
"[",
"sensor",
"]",
",",
")",
")",
"# Add all CT measurements",
"for",
"measurement_id",
",",
"measurement",
"in",
"service_location",
".",
"measurements",
".",
"items",
"(",
")",
":",
"entities",
".",
"append",
"(",
"SmappeeSensor",
"(",
"smappee_base",
"=",
"smappee_base",
",",
"service_location",
"=",
"service_location",
",",
"sensor",
"=",
"\"load\"",
",",
"attributes",
"=",
"[",
"measurement",
".",
"name",
",",
"None",
",",
"POWER_WATT",
",",
"measurement_id",
",",
"DEVICE_CLASS_POWER",
",",
"]",
",",
")",
")",
"# Add phase- and line voltages if available",
"if",
"service_location",
".",
"has_voltage_values",
":",
"for",
"sensor_name",
",",
"sensor",
"in",
"VOLTAGE_SENSORS",
".",
"items",
"(",
")",
":",
"if",
"service_location",
".",
"phase_type",
"in",
"sensor",
"[",
"5",
"]",
":",
"entities",
".",
"append",
"(",
"SmappeeSensor",
"(",
"smappee_base",
"=",
"smappee_base",
",",
"service_location",
"=",
"service_location",
",",
"sensor",
"=",
"sensor_name",
",",
"attributes",
"=",
"sensor",
",",
")",
")",
"# Add Gas and Water sensors",
"for",
"sensor_id",
",",
"sensor",
"in",
"service_location",
".",
"sensors",
".",
"items",
"(",
")",
":",
"for",
"channel",
"in",
"sensor",
".",
"channels",
":",
"gw_icon",
"=",
"\"mdi:gas-cylinder\"",
"if",
"channel",
".",
"get",
"(",
"\"type\"",
")",
"==",
"\"water\"",
":",
"gw_icon",
"=",
"\"mdi:water\"",
"entities",
".",
"append",
"(",
"SmappeeSensor",
"(",
"smappee_base",
"=",
"smappee_base",
",",
"service_location",
"=",
"service_location",
",",
"sensor",
"=",
"\"sensor\"",
",",
"attributes",
"=",
"[",
"channel",
".",
"get",
"(",
"\"name\"",
")",
",",
"gw_icon",
",",
"channel",
".",
"get",
"(",
"\"uom\"",
")",
",",
"f\"{sensor_id}-{channel.get('channel')}\"",
",",
"None",
",",
"]",
",",
")",
")",
"async_add_entities",
"(",
"entities",
",",
"True",
")"
] | [
143,
0
] | [
238,
38
] | python | en | ['en', 'st', 'en'] | True |
SmappeeSensor.__init__ | (self, smappee_base, service_location, sensor, attributes) | Initialize the Smappee sensor. | Initialize the Smappee sensor. | def __init__(self, smappee_base, service_location, sensor, attributes):
"""Initialize the Smappee sensor."""
self._smappee_base = smappee_base
self._service_location = service_location
self._sensor = sensor
self.data = None
self._state = None
self._name = attributes[0]
self._icon = attributes[1]
self._unit_of_measurement = attributes[2]
self._sensor_id = attributes[3]
self._device_class = attributes[4] | [
"def",
"__init__",
"(",
"self",
",",
"smappee_base",
",",
"service_location",
",",
"sensor",
",",
"attributes",
")",
":",
"self",
".",
"_smappee_base",
"=",
"smappee_base",
"self",
".",
"_service_location",
"=",
"service_location",
"self",
".",
"_sensor",
"=",
"sensor",
"self",
".",
"data",
"=",
"None",
"self",
".",
"_state",
"=",
"None",
"self",
".",
"_name",
"=",
"attributes",
"[",
"0",
"]",
"self",
".",
"_icon",
"=",
"attributes",
"[",
"1",
"]",
"self",
".",
"_unit_of_measurement",
"=",
"attributes",
"[",
"2",
"]",
"self",
".",
"_sensor_id",
"=",
"attributes",
"[",
"3",
"]",
"self",
".",
"_device_class",
"=",
"attributes",
"[",
"4",
"]"
] | [
244,
4
] | [
255,
42
] | python | en | ['en', 'en', 'en'] | True |
SmappeeSensor.name | (self) | Return the name for this sensor. | Return the name for this sensor. | def name(self):
"""Return the name for this sensor."""
if self._sensor in ["sensor", "load"]:
return (
f"{self._service_location.service_location_name} - "
f"{self._sensor.title()} - {self._name}"
)
return f"{self._service_location.service_location_name} - {self._name}" | [
"def",
"name",
"(",
"self",
")",
":",
"if",
"self",
".",
"_sensor",
"in",
"[",
"\"sensor\"",
",",
"\"load\"",
"]",
":",
"return",
"(",
"f\"{self._service_location.service_location_name} - \"",
"f\"{self._sensor.title()} - {self._name}\"",
")",
"return",
"f\"{self._service_location.service_location_name} - {self._name}\""
] | [
258,
4
] | [
266,
79
] | python | en | ['en', 'ceb', 'en'] | True |
SmappeeSensor.icon | (self) | Icon to use in the frontend. | Icon to use in the frontend. | def icon(self):
"""Icon to use in the frontend."""
return self._icon | [
"def",
"icon",
"(",
"self",
")",
":",
"return",
"self",
".",
"_icon"
] | [
269,
4
] | [
271,
25
] | python | en | ['en', 'en', 'en'] | True |
SmappeeSensor.state | (self) | Return the state of the sensor. | Return the state of the sensor. | def state(self):
"""Return the state of the sensor."""
return self._state | [
"def",
"state",
"(",
"self",
")",
":",
"return",
"self",
".",
"_state"
] | [
274,
4
] | [
276,
26
] | python | en | ['en', 'en', 'en'] | True |
SmappeeSensor.device_class | (self) | Return the class of this device, from component DEVICE_CLASSES. | Return the class of this device, from component DEVICE_CLASSES. | def device_class(self):
"""Return the class of this device, from component DEVICE_CLASSES."""
return self._device_class | [
"def",
"device_class",
"(",
"self",
")",
":",
"return",
"self",
".",
"_device_class"
] | [
279,
4
] | [
281,
33
] | python | en | ['en', 'en', 'en'] | True |
SmappeeSensor.unit_of_measurement | (self) | Return the unit of measurement of this entity, if any. | Return the unit of measurement of this entity, if any. | def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return self._unit_of_measurement | [
"def",
"unit_of_measurement",
"(",
"self",
")",
":",
"return",
"self",
".",
"_unit_of_measurement"
] | [
284,
4
] | [
286,
40
] | python | en | ['en', 'en', 'en'] | True |
SmappeeSensor.unique_id | (
self,
) | Return the unique ID for this sensor. | Return the unique ID for this sensor. | def unique_id(
self,
):
"""Return the unique ID for this sensor."""
if self._sensor in ["load", "sensor"]:
return (
f"{self._service_location.device_serial_number}-"
f"{self._service_location.service_location_id}-"
f"{self._sensor}-{self._sensor_id}"
)
return (
f"{self._service_location.device_serial_number}-"
f"{self._service_location.service_location_id}-"
f"{self._sensor}"
) | [
"def",
"unique_id",
"(",
"self",
",",
")",
":",
"if",
"self",
".",
"_sensor",
"in",
"[",
"\"load\"",
",",
"\"sensor\"",
"]",
":",
"return",
"(",
"f\"{self._service_location.device_serial_number}-\"",
"f\"{self._service_location.service_location_id}-\"",
"f\"{self._sensor}-{self._sensor_id}\"",
")",
"return",
"(",
"f\"{self._service_location.device_serial_number}-\"",
"f\"{self._service_location.service_location_id}-\"",
"f\"{self._sensor}\"",
")"
] | [
289,
4
] | [
304,
9
] | python | en | ['en', 'la', 'en'] | True |
SmappeeSensor.device_info | (self) | Return the device info for this sensor. | Return the device info for this sensor. | def device_info(self):
"""Return the device info for this sensor."""
return {
"identifiers": {(DOMAIN, self._service_location.device_serial_number)},
"name": self._service_location.service_location_name,
"manufacturer": "Smappee",
"model": self._service_location.device_model,
"sw_version": self._service_location.firmware_version,
} | [
"def",
"device_info",
"(",
"self",
")",
":",
"return",
"{",
"\"identifiers\"",
":",
"{",
"(",
"DOMAIN",
",",
"self",
".",
"_service_location",
".",
"device_serial_number",
")",
"}",
",",
"\"name\"",
":",
"self",
".",
"_service_location",
".",
"service_location_name",
",",
"\"manufacturer\"",
":",
"\"Smappee\"",
",",
"\"model\"",
":",
"self",
".",
"_service_location",
".",
"device_model",
",",
"\"sw_version\"",
":",
"self",
".",
"_service_location",
".",
"firmware_version",
",",
"}"
] | [
307,
4
] | [
315,
9
] | python | en | ['en', 'en', 'en'] | True |
SmappeeSensor.async_update | (self) | Get the latest data from Smappee and update the state. | Get the latest data from Smappee and update the state. | async def async_update(self):
"""Get the latest data from Smappee and update the state."""
await self._smappee_base.async_update()
if self._sensor == "total_power":
self._state = self._service_location.total_power
elif self._sensor == "total_reactive_power":
self._state = self._service_location.total_reactive_power
elif self._sensor == "solar_power":
self._state = self._service_location.solar_power
elif self._sensor == "alwayson":
self._state = self._service_location.alwayson
elif self._sensor in [
"phase_voltages_a",
"phase_voltages_b",
"phase_voltages_c",
]:
phase_voltages = self._service_location.phase_voltages
if phase_voltages is not None:
if self._sensor == "phase_voltages_a":
self._state = phase_voltages[0]
elif self._sensor == "phase_voltages_b":
self._state = phase_voltages[1]
elif self._sensor == "phase_voltages_c":
self._state = phase_voltages[2]
elif self._sensor in ["line_voltages_a", "line_voltages_b", "line_voltages_c"]:
line_voltages = self._service_location.line_voltages
if line_voltages is not None:
if self._sensor == "line_voltages_a":
self._state = line_voltages[0]
elif self._sensor == "line_voltages_b":
self._state = line_voltages[1]
elif self._sensor == "line_voltages_c":
self._state = line_voltages[2]
elif self._sensor in [
"power_today",
"power_current_hour",
"power_last_5_minutes",
"solar_today",
"solar_current_hour",
"alwayson_today",
]:
trend_value = self._service_location.aggregated_values.get(self._sensor)
self._state = round(trend_value) if trend_value is not None else None
elif self._sensor == "load":
self._state = self._service_location.measurements.get(
self._sensor_id
).active_total
elif self._sensor == "sensor":
sensor_id, channel_id = self._sensor_id.split("-")
sensor = self._service_location.sensors.get(int(sensor_id))
for channel in sensor.channels:
if channel.get("channel") == int(channel_id):
self._state = channel.get("value_today") | [
"async",
"def",
"async_update",
"(",
"self",
")",
":",
"await",
"self",
".",
"_smappee_base",
".",
"async_update",
"(",
")",
"if",
"self",
".",
"_sensor",
"==",
"\"total_power\"",
":",
"self",
".",
"_state",
"=",
"self",
".",
"_service_location",
".",
"total_power",
"elif",
"self",
".",
"_sensor",
"==",
"\"total_reactive_power\"",
":",
"self",
".",
"_state",
"=",
"self",
".",
"_service_location",
".",
"total_reactive_power",
"elif",
"self",
".",
"_sensor",
"==",
"\"solar_power\"",
":",
"self",
".",
"_state",
"=",
"self",
".",
"_service_location",
".",
"solar_power",
"elif",
"self",
".",
"_sensor",
"==",
"\"alwayson\"",
":",
"self",
".",
"_state",
"=",
"self",
".",
"_service_location",
".",
"alwayson",
"elif",
"self",
".",
"_sensor",
"in",
"[",
"\"phase_voltages_a\"",
",",
"\"phase_voltages_b\"",
",",
"\"phase_voltages_c\"",
",",
"]",
":",
"phase_voltages",
"=",
"self",
".",
"_service_location",
".",
"phase_voltages",
"if",
"phase_voltages",
"is",
"not",
"None",
":",
"if",
"self",
".",
"_sensor",
"==",
"\"phase_voltages_a\"",
":",
"self",
".",
"_state",
"=",
"phase_voltages",
"[",
"0",
"]",
"elif",
"self",
".",
"_sensor",
"==",
"\"phase_voltages_b\"",
":",
"self",
".",
"_state",
"=",
"phase_voltages",
"[",
"1",
"]",
"elif",
"self",
".",
"_sensor",
"==",
"\"phase_voltages_c\"",
":",
"self",
".",
"_state",
"=",
"phase_voltages",
"[",
"2",
"]",
"elif",
"self",
".",
"_sensor",
"in",
"[",
"\"line_voltages_a\"",
",",
"\"line_voltages_b\"",
",",
"\"line_voltages_c\"",
"]",
":",
"line_voltages",
"=",
"self",
".",
"_service_location",
".",
"line_voltages",
"if",
"line_voltages",
"is",
"not",
"None",
":",
"if",
"self",
".",
"_sensor",
"==",
"\"line_voltages_a\"",
":",
"self",
".",
"_state",
"=",
"line_voltages",
"[",
"0",
"]",
"elif",
"self",
".",
"_sensor",
"==",
"\"line_voltages_b\"",
":",
"self",
".",
"_state",
"=",
"line_voltages",
"[",
"1",
"]",
"elif",
"self",
".",
"_sensor",
"==",
"\"line_voltages_c\"",
":",
"self",
".",
"_state",
"=",
"line_voltages",
"[",
"2",
"]",
"elif",
"self",
".",
"_sensor",
"in",
"[",
"\"power_today\"",
",",
"\"power_current_hour\"",
",",
"\"power_last_5_minutes\"",
",",
"\"solar_today\"",
",",
"\"solar_current_hour\"",
",",
"\"alwayson_today\"",
",",
"]",
":",
"trend_value",
"=",
"self",
".",
"_service_location",
".",
"aggregated_values",
".",
"get",
"(",
"self",
".",
"_sensor",
")",
"self",
".",
"_state",
"=",
"round",
"(",
"trend_value",
")",
"if",
"trend_value",
"is",
"not",
"None",
"else",
"None",
"elif",
"self",
".",
"_sensor",
"==",
"\"load\"",
":",
"self",
".",
"_state",
"=",
"self",
".",
"_service_location",
".",
"measurements",
".",
"get",
"(",
"self",
".",
"_sensor_id",
")",
".",
"active_total",
"elif",
"self",
".",
"_sensor",
"==",
"\"sensor\"",
":",
"sensor_id",
",",
"channel_id",
"=",
"self",
".",
"_sensor_id",
".",
"split",
"(",
"\"-\"",
")",
"sensor",
"=",
"self",
".",
"_service_location",
".",
"sensors",
".",
"get",
"(",
"int",
"(",
"sensor_id",
")",
")",
"for",
"channel",
"in",
"sensor",
".",
"channels",
":",
"if",
"channel",
".",
"get",
"(",
"\"channel\"",
")",
"==",
"int",
"(",
"channel_id",
")",
":",
"self",
".",
"_state",
"=",
"channel",
".",
"get",
"(",
"\"value_today\"",
")"
] | [
317,
4
] | [
370,
60
] | python | en | ['en', 'en', 'en'] | True |
post_stix | (manager, content_block, collection_ids, service_id) |
Callback function for when our taxii server gets new data
Will convert it to a MISPEvent and push to the server
|
Callback function for when our taxii server gets new data
Will convert it to a MISPEvent and push to the server
| def post_stix(manager, content_block, collection_ids, service_id):
'''
Callback function for when our taxii server gets new data
Will convert it to a MISPEvent and push to the server
'''
# Load the package
log.info("Posting STIX...")
block = content_block.content
if isinstance(block, bytes):
block = block.decode()
package = pymisp.tools.stix.load_stix(StringIO(block))
log.info("STIX loaded succesfully.")
values = [x.value for x in package.attributes]
log.info("Extracted %s", values)
for attrib in values:
log.info("Checking for existence of %s", attrib)
search = MISP.search("attributes", values=str(attrib))
if search["response"]["Attribute"] != []:
# This means we have it!
log.info("%s is a duplicate, we'll ignore it.", attrib)
package.attributes.pop([x.value for x in package.attributes].index(attrib))
else:
log.info("%s is unique, we'll keep it", attrib)
# Push the event to MISP
# TODO: There's probably a proper method to do this rather than json_full
# But I don't wanna read docs
if (len(package.attributes) > 0):
log.info("Uploading event to MISP with attributes %s", [x.value for x in package.attributes])
MISP.add_event(package)
else:
log.info("No attributes, not bothering.") | [
"def",
"post_stix",
"(",
"manager",
",",
"content_block",
",",
"collection_ids",
",",
"service_id",
")",
":",
"# Load the package",
"log",
".",
"info",
"(",
"\"Posting STIX...\"",
")",
"block",
"=",
"content_block",
".",
"content",
"if",
"isinstance",
"(",
"block",
",",
"bytes",
")",
":",
"block",
"=",
"block",
".",
"decode",
"(",
")",
"package",
"=",
"pymisp",
".",
"tools",
".",
"stix",
".",
"load_stix",
"(",
"StringIO",
"(",
"block",
")",
")",
"log",
".",
"info",
"(",
"\"STIX loaded succesfully.\"",
")",
"values",
"=",
"[",
"x",
".",
"value",
"for",
"x",
"in",
"package",
".",
"attributes",
"]",
"log",
".",
"info",
"(",
"\"Extracted %s\"",
",",
"values",
")",
"for",
"attrib",
"in",
"values",
":",
"log",
".",
"info",
"(",
"\"Checking for existence of %s\"",
",",
"attrib",
")",
"search",
"=",
"MISP",
".",
"search",
"(",
"\"attributes\"",
",",
"values",
"=",
"str",
"(",
"attrib",
")",
")",
"if",
"search",
"[",
"\"response\"",
"]",
"[",
"\"Attribute\"",
"]",
"!=",
"[",
"]",
":",
"# This means we have it!",
"log",
".",
"info",
"(",
"\"%s is a duplicate, we'll ignore it.\"",
",",
"attrib",
")",
"package",
".",
"attributes",
".",
"pop",
"(",
"[",
"x",
".",
"value",
"for",
"x",
"in",
"package",
".",
"attributes",
"]",
".",
"index",
"(",
"attrib",
")",
")",
"else",
":",
"log",
".",
"info",
"(",
"\"%s is unique, we'll keep it\"",
",",
"attrib",
")",
"# Push the event to MISP",
"# TODO: There's probably a proper method to do this rather than json_full",
"# But I don't wanna read docs",
"if",
"(",
"len",
"(",
"package",
".",
"attributes",
")",
">",
"0",
")",
":",
"log",
".",
"info",
"(",
"\"Uploading event to MISP with attributes %s\"",
",",
"[",
"x",
".",
"value",
"for",
"x",
"in",
"package",
".",
"attributes",
"]",
")",
"MISP",
".",
"add_event",
"(",
"package",
")",
"else",
":",
"log",
".",
"info",
"(",
"\"No attributes, not bothering.\"",
")"
] | [
49,
0
] | [
82,
49
] | python | en | ['en', 'error', 'th'] | False |
setup_platform | (hass, config, add_entities, discovery_info=None) | Set up the MyChevy sensors. | Set up the MyChevy sensors. | def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the MyChevy sensors."""
if discovery_info is None:
return
hub = hass.data[MYCHEVY_DOMAIN]
sensors = [MyChevyStatus()]
for sconfig in SENSORS:
for car in hub.cars:
sensors.append(EVSensor(hub, sconfig, car.vid))
add_entities(sensors) | [
"def",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"if",
"discovery_info",
"is",
"None",
":",
"return",
"hub",
"=",
"hass",
".",
"data",
"[",
"MYCHEVY_DOMAIN",
"]",
"sensors",
"=",
"[",
"MyChevyStatus",
"(",
")",
"]",
"for",
"sconfig",
"in",
"SENSORS",
":",
"for",
"car",
"in",
"hub",
".",
"cars",
":",
"sensors",
".",
"append",
"(",
"EVSensor",
"(",
"hub",
",",
"sconfig",
",",
"car",
".",
"vid",
")",
")",
"add_entities",
"(",
"sensors",
")"
] | [
34,
0
] | [
45,
25
] | python | en | ['en', 'fr', 'en'] | True |
MyChevyStatus.__init__ | (self) | Initialize sensor with car connection. | Initialize sensor with car connection. | def __init__(self):
"""Initialize sensor with car connection."""
self._state = None | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"_state",
"=",
"None"
] | [
54,
4
] | [
56,
26
] | python | en | ['en', 'en', 'en'] | True |
MyChevyStatus.async_added_to_hass | (self) | Register callbacks. | Register callbacks. | async def async_added_to_hass(self):
"""Register callbacks."""
self.async_on_remove(
self.hass.helpers.dispatcher.async_dispatcher_connect(
UPDATE_TOPIC, self.success
)
)
self.async_on_remove(
self.hass.helpers.dispatcher.async_dispatcher_connect(
ERROR_TOPIC, self.error
)
) | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
":",
"self",
".",
"async_on_remove",
"(",
"self",
".",
"hass",
".",
"helpers",
".",
"dispatcher",
".",
"async_dispatcher_connect",
"(",
"UPDATE_TOPIC",
",",
"self",
".",
"success",
")",
")",
"self",
".",
"async_on_remove",
"(",
"self",
".",
"hass",
".",
"helpers",
".",
"dispatcher",
".",
"async_dispatcher_connect",
"(",
"ERROR_TOPIC",
",",
"self",
".",
"error",
")",
")"
] | [
58,
4
] | [
70,
9
] | python | en | ['en', 'no', 'en'] | False |
MyChevyStatus.success | (self) | Update state, trigger updates. | Update state, trigger updates. | def success(self):
"""Update state, trigger updates."""
if self._state != MYCHEVY_SUCCESS:
_LOGGER.debug("Successfully connected to mychevy website")
self._state = MYCHEVY_SUCCESS
self.async_write_ha_state() | [
"def",
"success",
"(",
"self",
")",
":",
"if",
"self",
".",
"_state",
"!=",
"MYCHEVY_SUCCESS",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Successfully connected to mychevy website\"",
")",
"self",
".",
"_state",
"=",
"MYCHEVY_SUCCESS",
"self",
".",
"async_write_ha_state",
"(",
")"
] | [
73,
4
] | [
78,
35
] | python | co | ['da', 'co', 'en'] | False |
MyChevyStatus.error | (self) | Update state, trigger updates. | Update state, trigger updates. | def error(self):
"""Update state, trigger updates."""
_LOGGER.error(
"Connection to mychevy website failed. "
"This probably means the mychevy to OnStar link is down"
)
self._state = MYCHEVY_ERROR
self.async_write_ha_state() | [
"def",
"error",
"(",
"self",
")",
":",
"_LOGGER",
".",
"error",
"(",
"\"Connection to mychevy website failed. \"",
"\"This probably means the mychevy to OnStar link is down\"",
")",
"self",
".",
"_state",
"=",
"MYCHEVY_ERROR",
"self",
".",
"async_write_ha_state",
"(",
")"
] | [
81,
4
] | [
88,
35
] | python | co | ['da', 'co', 'en'] | False |
MyChevyStatus.icon | (self) | Return the icon. | Return the icon. | def icon(self):
"""Return the icon."""
return self._icon | [
"def",
"icon",
"(",
"self",
")",
":",
"return",
"self",
".",
"_icon"
] | [
91,
4
] | [
93,
25
] | python | en | ['en', 'sr', 'en'] | True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.