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
LazyEventPartialState.attributes_icon
(self)
Extract the icon from the decoded attributes or json.
Extract the icon from the decoded attributes or json.
def attributes_icon(self): """Extract the icon from the decoded attributes or json.""" if self._attributes: return self._attributes.get(ATTR_ICON) result = ICON_JSON_EXTRACT.search(self._row.attributes) return result and result.group(1)
[ "def", "attributes_icon", "(", "self", ")", ":", "if", "self", ".", "_attributes", ":", "return", "self", ".", "_attributes", ".", "get", "(", "ATTR_ICON", ")", "result", "=", "ICON_JSON_EXTRACT", ".", "search", "(", "self", ".", "_row", ".", "attributes", ")", "return", "result", "and", "result", ".", "group", "(", "1", ")" ]
[ 692, 4 ]
[ 698, 41 ]
python
en
['en', 'en', 'en']
True
LazyEventPartialState.data_entity_id
(self)
Extract the entity id from the decoded data or json.
Extract the entity id from the decoded data or json.
def data_entity_id(self): """Extract the entity id from the decoded data or json.""" if self._event_data: return self._event_data.get(ATTR_ENTITY_ID) result = ENTITY_ID_JSON_EXTRACT.search(self._row.event_data) return result and result.group(1)
[ "def", "data_entity_id", "(", "self", ")", ":", "if", "self", ".", "_event_data", ":", "return", "self", ".", "_event_data", ".", "get", "(", "ATTR_ENTITY_ID", ")", "result", "=", "ENTITY_ID_JSON_EXTRACT", ".", "search", "(", "self", ".", "_row", ".", "event_data", ")", "return", "result", "and", "result", ".", "group", "(", "1", ")" ]
[ 701, 4 ]
[ 707, 41 ]
python
en
['en', 'en', 'en']
True
LazyEventPartialState.data_domain
(self)
Extract the domain from the decoded data or json.
Extract the domain from the decoded data or json.
def data_domain(self): """Extract the domain from the decoded data or json.""" if self._event_data: return self._event_data.get(ATTR_DOMAIN) result = DOMAIN_JSON_EXTRACT.search(self._row.event_data) return result and result.group(1)
[ "def", "data_domain", "(", "self", ")", ":", "if", "self", ".", "_event_data", ":", "return", "self", ".", "_event_data", ".", "get", "(", "ATTR_DOMAIN", ")", "result", "=", "DOMAIN_JSON_EXTRACT", ".", "search", "(", "self", ".", "_row", ".", "event_data", ")", "return", "result", "and", "result", ".", "group", "(", "1", ")" ]
[ 710, 4 ]
[ 716, 41 ]
python
en
['en', 'en', 'en']
True
LazyEventPartialState.attributes
(self)
State attributes.
State attributes.
def attributes(self): """State attributes.""" if not self._attributes: if ( self._row.attributes is None or self._row.attributes == EMPTY_JSON_OBJECT ): self._attributes = {} else: self._attributes = json.loads(self._row.attributes) return self._attributes
[ "def", "attributes", "(", "self", ")", ":", "if", "not", "self", ".", "_attributes", ":", "if", "(", "self", ".", "_row", ".", "attributes", "is", "None", "or", "self", ".", "_row", ".", "attributes", "==", "EMPTY_JSON_OBJECT", ")", ":", "self", ".", "_attributes", "=", "{", "}", "else", ":", "self", ".", "_attributes", "=", "json", ".", "loads", "(", "self", ".", "_row", ".", "attributes", ")", "return", "self", ".", "_attributes" ]
[ 719, 4 ]
[ 729, 31 ]
python
en
['en', 'en', 'en']
False
LazyEventPartialState.data
(self)
Event data.
Event data.
def data(self): """Event data.""" if not self._event_data: if self._row.event_data == EMPTY_JSON_OBJECT: self._event_data = {} else: self._event_data = json.loads(self._row.event_data) return self._event_data
[ "def", "data", "(", "self", ")", ":", "if", "not", "self", ".", "_event_data", ":", "if", "self", ".", "_row", ".", "event_data", "==", "EMPTY_JSON_OBJECT", ":", "self", ".", "_event_data", "=", "{", "}", "else", ":", "self", ".", "_event_data", "=", "json", ".", "loads", "(", "self", ".", "_row", ".", "event_data", ")", "return", "self", ".", "_event_data" ]
[ 732, 4 ]
[ 739, 31 ]
python
fr
['fr', 'la', 'it']
False
LazyEventPartialState.time_fired_isoformat
(self)
Time event was fired in utc isoformat.
Time event was fired in utc isoformat.
def time_fired_isoformat(self): """Time event was fired in utc isoformat.""" if not self._time_fired_isoformat: self._time_fired_isoformat = process_timestamp_to_utc_isoformat( self._row.time_fired or dt_util.utcnow() ) return self._time_fired_isoformat
[ "def", "time_fired_isoformat", "(", "self", ")", ":", "if", "not", "self", ".", "_time_fired_isoformat", ":", "self", ".", "_time_fired_isoformat", "=", "process_timestamp_to_utc_isoformat", "(", "self", ".", "_row", ".", "time_fired", "or", "dt_util", ".", "utcnow", "(", ")", ")", "return", "self", ".", "_time_fired_isoformat" ]
[ 742, 4 ]
[ 749, 41 ]
python
en
['en', 'en', 'en']
True
EntityAttributeCache.__init__
(self, hass)
Init the cache.
Init the cache.
def __init__(self, hass): """Init the cache.""" self._hass = hass self._cache = {}
[ "def", "__init__", "(", "self", ",", "hass", ")", ":", "self", ".", "_hass", "=", "hass", "self", ".", "_cache", "=", "{", "}" ]
[ 759, 4 ]
[ 762, 24 ]
python
en
['en', 'en', 'en']
True
EntityAttributeCache.get
(self, entity_id, attribute, event)
Lookup an attribute for an entity or get it from the cache.
Lookup an attribute for an entity or get it from the cache.
def get(self, entity_id, attribute, event): """Lookup an attribute for an entity or get it from the cache.""" if entity_id in self._cache: if attribute in self._cache[entity_id]: return self._cache[entity_id][attribute] else: self._cache[entity_id] = {} current_state = self._hass.states.get(entity_id) if current_state: # Try the current state as its faster than decoding the # attributes self._cache[entity_id][attribute] = current_state.attributes.get(attribute) else: # If the entity has been removed, decode the attributes # instead self._cache[entity_id][attribute] = event.attributes.get(attribute) return self._cache[entity_id][attribute]
[ "def", "get", "(", "self", ",", "entity_id", ",", "attribute", ",", "event", ")", ":", "if", "entity_id", "in", "self", ".", "_cache", ":", "if", "attribute", "in", "self", ".", "_cache", "[", "entity_id", "]", ":", "return", "self", ".", "_cache", "[", "entity_id", "]", "[", "attribute", "]", "else", ":", "self", ".", "_cache", "[", "entity_id", "]", "=", "{", "}", "current_state", "=", "self", ".", "_hass", ".", "states", ".", "get", "(", "entity_id", ")", "if", "current_state", ":", "# Try the current state as its faster than decoding the", "# attributes", "self", ".", "_cache", "[", "entity_id", "]", "[", "attribute", "]", "=", "current_state", ".", "attributes", ".", "get", "(", "attribute", ")", "else", ":", "# If the entity has been removed, decode the attributes", "# instead", "self", ".", "_cache", "[", "entity_id", "]", "[", "attribute", "]", "=", "event", ".", "attributes", ".", "get", "(", "attribute", ")", "return", "self", ".", "_cache", "[", "entity_id", "]", "[", "attribute", "]" ]
[ 764, 4 ]
[ 782, 48 ]
python
en
['en', 'en', 'en']
True
async_request_stream
(hass, entity_id, fmt)
Request a stream for a camera entity.
Request a stream for a camera entity.
async def async_request_stream(hass, entity_id, fmt): """Request a stream for a camera entity.""" camera = _get_camera_from_entity_id(hass, entity_id) camera_prefs = hass.data[DATA_CAMERA_PREFS].get(entity_id) async with async_timeout.timeout(10): source = await camera.stream_source() if not source: raise HomeAssistantError( f"{camera.entity_id} does not support play stream service" ) return request_stream( hass, source, fmt=fmt, keepalive=camera_prefs.preload_stream, options=camera.stream_options, )
[ "async", "def", "async_request_stream", "(", "hass", ",", "entity_id", ",", "fmt", ")", ":", "camera", "=", "_get_camera_from_entity_id", "(", "hass", ",", "entity_id", ")", "camera_prefs", "=", "hass", ".", "data", "[", "DATA_CAMERA_PREFS", "]", ".", "get", "(", "entity_id", ")", "async", "with", "async_timeout", ".", "timeout", "(", "10", ")", ":", "source", "=", "await", "camera", ".", "stream_source", "(", ")", "if", "not", "source", ":", "raise", "HomeAssistantError", "(", "f\"{camera.entity_id} does not support play stream service\"", ")", "return", "request_stream", "(", "hass", ",", "source", ",", "fmt", "=", "fmt", ",", "keepalive", "=", "camera_prefs", ".", "preload_stream", ",", "options", "=", "camera", ".", "stream_options", ",", ")" ]
[ 129, 0 ]
[ 148, 5 ]
python
en
['es', 'pt', 'en']
False
async_get_image
(hass, entity_id, timeout=10)
Fetch an image from a camera entity.
Fetch an image from a camera entity.
async def async_get_image(hass, entity_id, timeout=10): """Fetch an image from a camera entity.""" camera = _get_camera_from_entity_id(hass, entity_id) with suppress(asyncio.CancelledError, asyncio.TimeoutError): async with async_timeout.timeout(timeout): image = await camera.async_camera_image() if image: return Image(camera.content_type, image) raise HomeAssistantError("Unable to get image")
[ "async", "def", "async_get_image", "(", "hass", ",", "entity_id", ",", "timeout", "=", "10", ")", ":", "camera", "=", "_get_camera_from_entity_id", "(", "hass", ",", "entity_id", ")", "with", "suppress", "(", "asyncio", ".", "CancelledError", ",", "asyncio", ".", "TimeoutError", ")", ":", "async", "with", "async_timeout", ".", "timeout", "(", "timeout", ")", ":", "image", "=", "await", "camera", ".", "async_camera_image", "(", ")", "if", "image", ":", "return", "Image", "(", "camera", ".", "content_type", ",", "image", ")", "raise", "HomeAssistantError", "(", "\"Unable to get image\"", ")" ]
[ 152, 0 ]
[ 163, 51 ]
python
en
['en', 'en', 'en']
True
async_get_stream_source
(hass, entity_id)
Fetch the stream source for a camera entity.
Fetch the stream source for a camera entity.
async def async_get_stream_source(hass, entity_id): """Fetch the stream source for a camera entity.""" camera = _get_camera_from_entity_id(hass, entity_id) return await camera.stream_source()
[ "async", "def", "async_get_stream_source", "(", "hass", ",", "entity_id", ")", ":", "camera", "=", "_get_camera_from_entity_id", "(", "hass", ",", "entity_id", ")", "return", "await", "camera", ".", "stream_source", "(", ")" ]
[ 167, 0 ]
[ 171, 39 ]
python
en
['en', 'en', 'en']
True
async_get_mjpeg_stream
(hass, request, entity_id)
Fetch an mjpeg stream from a camera entity.
Fetch an mjpeg stream from a camera entity.
async def async_get_mjpeg_stream(hass, request, entity_id): """Fetch an mjpeg stream from a camera entity.""" camera = _get_camera_from_entity_id(hass, entity_id) return await camera.handle_async_mjpeg_stream(request)
[ "async", "def", "async_get_mjpeg_stream", "(", "hass", ",", "request", ",", "entity_id", ")", ":", "camera", "=", "_get_camera_from_entity_id", "(", "hass", ",", "entity_id", ")", "return", "await", "camera", ".", "handle_async_mjpeg_stream", "(", "request", ")" ]
[ 175, 0 ]
[ 179, 58 ]
python
en
['en', 'cy', 'en']
True
async_get_still_stream
(request, image_cb, content_type, interval)
Generate an HTTP MJPEG stream from camera images. This method must be run in the event loop.
Generate an HTTP MJPEG stream from camera images.
async def async_get_still_stream(request, image_cb, content_type, interval): """Generate an HTTP MJPEG stream from camera images. This method must be run in the event loop. """ response = web.StreamResponse() response.content_type = CONTENT_TYPE_MULTIPART.format("--frameboundary") await response.prepare(request) async def write_to_mjpeg_stream(img_bytes): """Write image to stream.""" await response.write( bytes( "--frameboundary\r\n" "Content-Type: {}\r\n" "Content-Length: {}\r\n\r\n".format(content_type, len(img_bytes)), "utf-8", ) + img_bytes + b"\r\n" ) last_image = None while True: img_bytes = await image_cb() if not img_bytes: break if img_bytes != last_image: await write_to_mjpeg_stream(img_bytes) # Chrome seems to always ignore first picture, # print it twice. if last_image is None: await write_to_mjpeg_stream(img_bytes) last_image = img_bytes await asyncio.sleep(interval) return response
[ "async", "def", "async_get_still_stream", "(", "request", ",", "image_cb", ",", "content_type", ",", "interval", ")", ":", "response", "=", "web", ".", "StreamResponse", "(", ")", "response", ".", "content_type", "=", "CONTENT_TYPE_MULTIPART", ".", "format", "(", "\"--frameboundary\"", ")", "await", "response", ".", "prepare", "(", "request", ")", "async", "def", "write_to_mjpeg_stream", "(", "img_bytes", ")", ":", "\"\"\"Write image to stream.\"\"\"", "await", "response", ".", "write", "(", "bytes", "(", "\"--frameboundary\\r\\n\"", "\"Content-Type: {}\\r\\n\"", "\"Content-Length: {}\\r\\n\\r\\n\"", ".", "format", "(", "content_type", ",", "len", "(", "img_bytes", ")", ")", ",", "\"utf-8\"", ",", ")", "+", "img_bytes", "+", "b\"\\r\\n\"", ")", "last_image", "=", "None", "while", "True", ":", "img_bytes", "=", "await", "image_cb", "(", ")", "if", "not", "img_bytes", ":", "break", "if", "img_bytes", "!=", "last_image", ":", "await", "write_to_mjpeg_stream", "(", "img_bytes", ")", "# Chrome seems to always ignore first picture,", "# print it twice.", "if", "last_image", "is", "None", ":", "await", "write_to_mjpeg_stream", "(", "img_bytes", ")", "last_image", "=", "img_bytes", "await", "asyncio", ".", "sleep", "(", "interval", ")", "return", "response" ]
[ 182, 0 ]
[ 222, 19 ]
python
en
['en', 'en', 'en']
True
_get_camera_from_entity_id
(hass, entity_id)
Get camera component from entity_id.
Get camera component from entity_id.
def _get_camera_from_entity_id(hass, entity_id): """Get camera component from entity_id.""" component = hass.data.get(DOMAIN) if component is None: raise HomeAssistantError("Camera integration not set up") camera = component.get_entity(entity_id) if camera is None: raise HomeAssistantError("Camera not found") if not camera.is_on: raise HomeAssistantError("Camera is off") return camera
[ "def", "_get_camera_from_entity_id", "(", "hass", ",", "entity_id", ")", ":", "component", "=", "hass", ".", "data", ".", "get", "(", "DOMAIN", ")", "if", "component", "is", "None", ":", "raise", "HomeAssistantError", "(", "\"Camera integration not set up\"", ")", "camera", "=", "component", ".", "get_entity", "(", "entity_id", ")", "if", "camera", "is", "None", ":", "raise", "HomeAssistantError", "(", "\"Camera not found\"", ")", "if", "not", "camera", ".", "is_on", ":", "raise", "HomeAssistantError", "(", "\"Camera is off\"", ")", "return", "camera" ]
[ 225, 0 ]
[ 240, 17 ]
python
en
['en', 'en', 'en']
True
async_setup
(hass, config)
Set up the camera component.
Set up the camera component.
async def async_setup(hass, config): """Set up the camera component.""" component = hass.data[DOMAIN] = EntityComponent( _LOGGER, DOMAIN, hass, SCAN_INTERVAL ) prefs = CameraPreferences(hass) await prefs.async_initialize() hass.data[DATA_CAMERA_PREFS] = prefs hass.http.register_view(CameraImageView(component)) hass.http.register_view(CameraMjpegStream(component)) hass.components.websocket_api.async_register_command( WS_TYPE_CAMERA_THUMBNAIL, websocket_camera_thumbnail, SCHEMA_WS_CAMERA_THUMBNAIL ) hass.components.websocket_api.async_register_command(ws_camera_stream) hass.components.websocket_api.async_register_command(websocket_get_prefs) hass.components.websocket_api.async_register_command(websocket_update_prefs) await component.async_setup(config) async def preload_stream(_): for camera in component.entities: camera_prefs = prefs.get(camera.entity_id) if not camera_prefs.preload_stream: continue async with async_timeout.timeout(10): source = await camera.stream_source() if not source: continue request_stream(hass, source, keepalive=True, options=camera.stream_options) hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, preload_stream) @callback def update_tokens(time): """Update tokens of the entities.""" for entity in component.entities: entity.async_update_token() entity.async_write_ha_state() hass.helpers.event.async_track_time_interval(update_tokens, TOKEN_CHANGE_INTERVAL) component.async_register_entity_service( SERVICE_ENABLE_MOTION, CAMERA_SERVICE_SCHEMA, "async_enable_motion_detection" ) component.async_register_entity_service( SERVICE_DISABLE_MOTION, CAMERA_SERVICE_SCHEMA, "async_disable_motion_detection" ) component.async_register_entity_service( SERVICE_TURN_OFF, CAMERA_SERVICE_SCHEMA, "async_turn_off" ) component.async_register_entity_service( SERVICE_TURN_ON, CAMERA_SERVICE_SCHEMA, "async_turn_on" ) component.async_register_entity_service( SERVICE_SNAPSHOT, CAMERA_SERVICE_SNAPSHOT, async_handle_snapshot_service ) component.async_register_entity_service( SERVICE_PLAY_STREAM, CAMERA_SERVICE_PLAY_STREAM, async_handle_play_stream_service, ) component.async_register_entity_service( SERVICE_RECORD, CAMERA_SERVICE_RECORD, async_handle_record_service ) return True
[ "async", "def", "async_setup", "(", "hass", ",", "config", ")", ":", "component", "=", "hass", ".", "data", "[", "DOMAIN", "]", "=", "EntityComponent", "(", "_LOGGER", ",", "DOMAIN", ",", "hass", ",", "SCAN_INTERVAL", ")", "prefs", "=", "CameraPreferences", "(", "hass", ")", "await", "prefs", ".", "async_initialize", "(", ")", "hass", ".", "data", "[", "DATA_CAMERA_PREFS", "]", "=", "prefs", "hass", ".", "http", ".", "register_view", "(", "CameraImageView", "(", "component", ")", ")", "hass", ".", "http", ".", "register_view", "(", "CameraMjpegStream", "(", "component", ")", ")", "hass", ".", "components", ".", "websocket_api", ".", "async_register_command", "(", "WS_TYPE_CAMERA_THUMBNAIL", ",", "websocket_camera_thumbnail", ",", "SCHEMA_WS_CAMERA_THUMBNAIL", ")", "hass", ".", "components", ".", "websocket_api", ".", "async_register_command", "(", "ws_camera_stream", ")", "hass", ".", "components", ".", "websocket_api", ".", "async_register_command", "(", "websocket_get_prefs", ")", "hass", ".", "components", ".", "websocket_api", ".", "async_register_command", "(", "websocket_update_prefs", ")", "await", "component", ".", "async_setup", "(", "config", ")", "async", "def", "preload_stream", "(", "_", ")", ":", "for", "camera", "in", "component", ".", "entities", ":", "camera_prefs", "=", "prefs", ".", "get", "(", "camera", ".", "entity_id", ")", "if", "not", "camera_prefs", ".", "preload_stream", ":", "continue", "async", "with", "async_timeout", ".", "timeout", "(", "10", ")", ":", "source", "=", "await", "camera", ".", "stream_source", "(", ")", "if", "not", "source", ":", "continue", "request_stream", "(", "hass", ",", "source", ",", "keepalive", "=", "True", ",", "options", "=", "camera", ".", "stream_options", ")", "hass", ".", "bus", ".", "async_listen_once", "(", "EVENT_HOMEASSISTANT_START", ",", "preload_stream", ")", "@", "callback", "def", "update_tokens", "(", "time", ")", ":", "\"\"\"Update tokens of the entities.\"\"\"", "for", "entity", "in", "component", ".", "entities", ":", "entity", ".", "async_update_token", "(", ")", "entity", ".", "async_write_ha_state", "(", ")", "hass", ".", "helpers", ".", "event", ".", "async_track_time_interval", "(", "update_tokens", ",", "TOKEN_CHANGE_INTERVAL", ")", "component", ".", "async_register_entity_service", "(", "SERVICE_ENABLE_MOTION", ",", "CAMERA_SERVICE_SCHEMA", ",", "\"async_enable_motion_detection\"", ")", "component", ".", "async_register_entity_service", "(", "SERVICE_DISABLE_MOTION", ",", "CAMERA_SERVICE_SCHEMA", ",", "\"async_disable_motion_detection\"", ")", "component", ".", "async_register_entity_service", "(", "SERVICE_TURN_OFF", ",", "CAMERA_SERVICE_SCHEMA", ",", "\"async_turn_off\"", ")", "component", ".", "async_register_entity_service", "(", "SERVICE_TURN_ON", ",", "CAMERA_SERVICE_SCHEMA", ",", "\"async_turn_on\"", ")", "component", ".", "async_register_entity_service", "(", "SERVICE_SNAPSHOT", ",", "CAMERA_SERVICE_SNAPSHOT", ",", "async_handle_snapshot_service", ")", "component", ".", "async_register_entity_service", "(", "SERVICE_PLAY_STREAM", ",", "CAMERA_SERVICE_PLAY_STREAM", ",", "async_handle_play_stream_service", ",", ")", "component", ".", "async_register_entity_service", "(", "SERVICE_RECORD", ",", "CAMERA_SERVICE_RECORD", ",", "async_handle_record_service", ")", "return", "True" ]
[ 243, 0 ]
[ 313, 15 ]
python
en
['en', 'en', 'en']
True
async_setup_entry
(hass, entry)
Set up a config entry.
Set up a config entry.
async def async_setup_entry(hass, entry): """Set up a config entry.""" return await hass.data[DOMAIN].async_setup_entry(entry)
[ "async", "def", "async_setup_entry", "(", "hass", ",", "entry", ")", ":", "return", "await", "hass", ".", "data", "[", "DOMAIN", "]", ".", "async_setup_entry", "(", "entry", ")" ]
[ 316, 0 ]
[ 318, 59 ]
python
en
['en', 'en', 'en']
True
async_unload_entry
(hass, entry)
Unload a config entry.
Unload a config entry.
async def async_unload_entry(hass, entry): """Unload a config entry.""" return await hass.data[DOMAIN].async_unload_entry(entry)
[ "async", "def", "async_unload_entry", "(", "hass", ",", "entry", ")", ":", "return", "await", "hass", ".", "data", "[", "DOMAIN", "]", ".", "async_unload_entry", "(", "entry", ")" ]
[ 321, 0 ]
[ 323, 60 ]
python
en
['en', 'es', 'en']
True
websocket_camera_thumbnail
(hass, connection, msg)
Handle get camera thumbnail websocket command. Async friendly.
Handle get camera thumbnail websocket command.
async def websocket_camera_thumbnail(hass, connection, msg): """Handle get camera thumbnail websocket command. Async friendly. """ _LOGGER.warning("The websocket command 'camera_thumbnail' has been deprecated") try: image = await async_get_image(hass, msg["entity_id"]) await connection.send_big_result( msg["id"], { "content_type": image.content_type, "content": base64.b64encode(image.content).decode("utf-8"), }, ) except HomeAssistantError: connection.send_message( websocket_api.error_message( msg["id"], "image_fetch_failed", "Unable to fetch image" ) )
[ "async", "def", "websocket_camera_thumbnail", "(", "hass", ",", "connection", ",", "msg", ")", ":", "_LOGGER", ".", "warning", "(", "\"The websocket command 'camera_thumbnail' has been deprecated\"", ")", "try", ":", "image", "=", "await", "async_get_image", "(", "hass", ",", "msg", "[", "\"entity_id\"", "]", ")", "await", "connection", ".", "send_big_result", "(", "msg", "[", "\"id\"", "]", ",", "{", "\"content_type\"", ":", "image", ".", "content_type", ",", "\"content\"", ":", "base64", ".", "b64encode", "(", "image", ".", "content", ")", ".", "decode", "(", "\"utf-8\"", ")", ",", "}", ",", ")", "except", "HomeAssistantError", ":", "connection", ".", "send_message", "(", "websocket_api", ".", "error_message", "(", "msg", "[", "\"id\"", "]", ",", "\"image_fetch_failed\"", ",", "\"Unable to fetch image\"", ")", ")" ]
[ 549, 0 ]
[ 569, 9 ]
python
en
['en', 'st', 'en']
True
ws_camera_stream
(hass, connection, msg)
Handle get camera stream websocket command. Async friendly.
Handle get camera stream websocket command.
async def ws_camera_stream(hass, connection, msg): """Handle get camera stream websocket command. Async friendly. """ try: entity_id = msg["entity_id"] camera = _get_camera_from_entity_id(hass, entity_id) camera_prefs = hass.data[DATA_CAMERA_PREFS].get(entity_id) async with async_timeout.timeout(10): source = await camera.stream_source() if not source: raise HomeAssistantError( f"{camera.entity_id} does not support play stream service" ) fmt = msg["format"] url = request_stream( hass, source, fmt=fmt, keepalive=camera_prefs.preload_stream, options=camera.stream_options, ) connection.send_result(msg["id"], {"url": url}) except HomeAssistantError as ex: _LOGGER.error("Error requesting stream: %s", ex) connection.send_error(msg["id"], "start_stream_failed", str(ex)) except asyncio.TimeoutError: _LOGGER.error("Timeout getting stream source") connection.send_error( msg["id"], "start_stream_failed", "Timeout getting stream source" )
[ "async", "def", "ws_camera_stream", "(", "hass", ",", "connection", ",", "msg", ")", ":", "try", ":", "entity_id", "=", "msg", "[", "\"entity_id\"", "]", "camera", "=", "_get_camera_from_entity_id", "(", "hass", ",", "entity_id", ")", "camera_prefs", "=", "hass", ".", "data", "[", "DATA_CAMERA_PREFS", "]", ".", "get", "(", "entity_id", ")", "async", "with", "async_timeout", ".", "timeout", "(", "10", ")", ":", "source", "=", "await", "camera", ".", "stream_source", "(", ")", "if", "not", "source", ":", "raise", "HomeAssistantError", "(", "f\"{camera.entity_id} does not support play stream service\"", ")", "fmt", "=", "msg", "[", "\"format\"", "]", "url", "=", "request_stream", "(", "hass", ",", "source", ",", "fmt", "=", "fmt", ",", "keepalive", "=", "camera_prefs", ".", "preload_stream", ",", "options", "=", "camera", ".", "stream_options", ",", ")", "connection", ".", "send_result", "(", "msg", "[", "\"id\"", "]", ",", "{", "\"url\"", ":", "url", "}", ")", "except", "HomeAssistantError", "as", "ex", ":", "_LOGGER", ".", "error", "(", "\"Error requesting stream: %s\"", ",", "ex", ")", "connection", ".", "send_error", "(", "msg", "[", "\"id\"", "]", ",", "\"start_stream_failed\"", ",", "str", "(", "ex", ")", ")", "except", "asyncio", ".", "TimeoutError", ":", "_LOGGER", ".", "error", "(", "\"Timeout getting stream source\"", ")", "connection", ".", "send_error", "(", "msg", "[", "\"id\"", "]", ",", "\"start_stream_failed\"", ",", "\"Timeout getting stream source\"", ")" ]
[ 580, 0 ]
[ 614, 9 ]
python
ca
['nl', 'ca', 'en']
False
websocket_get_prefs
(hass, connection, msg)
Handle request for account info.
Handle request for account info.
async def websocket_get_prefs(hass, connection, msg): """Handle request for account info.""" prefs = hass.data[DATA_CAMERA_PREFS].get(msg["entity_id"]) connection.send_result(msg["id"], prefs.as_dict())
[ "async", "def", "websocket_get_prefs", "(", "hass", ",", "connection", ",", "msg", ")", ":", "prefs", "=", "hass", ".", "data", "[", "DATA_CAMERA_PREFS", "]", ".", "get", "(", "msg", "[", "\"entity_id\"", "]", ")", "connection", ".", "send_result", "(", "msg", "[", "\"id\"", "]", ",", "prefs", ".", "as_dict", "(", ")", ")" ]
[ 621, 0 ]
[ 624, 54 ]
python
en
['en', 'en', 'en']
True
websocket_update_prefs
(hass, connection, msg)
Handle request for account info.
Handle request for account info.
async def websocket_update_prefs(hass, connection, msg): """Handle request for account info.""" prefs = hass.data[DATA_CAMERA_PREFS] changes = dict(msg) changes.pop("id") changes.pop("type") entity_id = changes.pop("entity_id") await prefs.async_update(entity_id, **changes) connection.send_result(msg["id"], prefs.get(entity_id).as_dict())
[ "async", "def", "websocket_update_prefs", "(", "hass", ",", "connection", ",", "msg", ")", ":", "prefs", "=", "hass", ".", "data", "[", "DATA_CAMERA_PREFS", "]", "changes", "=", "dict", "(", "msg", ")", "changes", ".", "pop", "(", "\"id\"", ")", "changes", ".", "pop", "(", "\"type\"", ")", "entity_id", "=", "changes", ".", "pop", "(", "\"entity_id\"", ")", "await", "prefs", ".", "async_update", "(", "entity_id", ",", "*", "*", "changes", ")", "connection", ".", "send_result", "(", "msg", "[", "\"id\"", "]", ",", "prefs", ".", "get", "(", "entity_id", ")", ".", "as_dict", "(", ")", ")" ]
[ 635, 0 ]
[ 645, 69 ]
python
en
['en', 'en', 'en']
True
async_handle_snapshot_service
(camera, service)
Handle snapshot services calls.
Handle snapshot services calls.
async def async_handle_snapshot_service(camera, service): """Handle snapshot services calls.""" hass = camera.hass filename = service.data[ATTR_FILENAME] filename.hass = hass snapshot_file = filename.async_render(variables={ATTR_ENTITY_ID: camera}) # check if we allow to access to that file if not hass.config.is_allowed_path(snapshot_file): _LOGGER.error("Can't write %s, no access to path!", snapshot_file) return image = await camera.async_camera_image() def _write_image(to_file, image_data): """Executor helper to write image.""" if not os.path.exists(os.path.dirname(to_file)): os.makedirs(os.path.dirname(to_file), exist_ok=True) with open(to_file, "wb") as img_file: img_file.write(image_data) try: await hass.async_add_executor_job(_write_image, snapshot_file, image) except OSError as err: _LOGGER.error("Can't write image to file: %s", err)
[ "async", "def", "async_handle_snapshot_service", "(", "camera", ",", "service", ")", ":", "hass", "=", "camera", ".", "hass", "filename", "=", "service", ".", "data", "[", "ATTR_FILENAME", "]", "filename", ".", "hass", "=", "hass", "snapshot_file", "=", "filename", ".", "async_render", "(", "variables", "=", "{", "ATTR_ENTITY_ID", ":", "camera", "}", ")", "# check if we allow to access to that file", "if", "not", "hass", ".", "config", ".", "is_allowed_path", "(", "snapshot_file", ")", ":", "_LOGGER", ".", "error", "(", "\"Can't write %s, no access to path!\"", ",", "snapshot_file", ")", "return", "image", "=", "await", "camera", ".", "async_camera_image", "(", ")", "def", "_write_image", "(", "to_file", ",", "image_data", ")", ":", "\"\"\"Executor helper to write image.\"\"\"", "if", "not", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "dirname", "(", "to_file", ")", ")", ":", "os", ".", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "to_file", ")", ",", "exist_ok", "=", "True", ")", "with", "open", "(", "to_file", ",", "\"wb\"", ")", "as", "img_file", ":", "img_file", ".", "write", "(", "image_data", ")", "try", ":", "await", "hass", ".", "async_add_executor_job", "(", "_write_image", ",", "snapshot_file", ",", "image", ")", "except", "OSError", "as", "err", ":", "_LOGGER", ".", "error", "(", "\"Can't write image to file: %s\"", ",", "err", ")" ]
[ 648, 0 ]
[ 673, 59 ]
python
en
['en', 'nl', 'en']
True
async_handle_play_stream_service
(camera, service_call)
Handle play stream services calls.
Handle play stream services calls.
async def async_handle_play_stream_service(camera, service_call): """Handle play stream services calls.""" async with async_timeout.timeout(10): source = await camera.stream_source() if not source: raise HomeAssistantError( f"{camera.entity_id} does not support play stream service" ) hass = camera.hass camera_prefs = hass.data[DATA_CAMERA_PREFS].get(camera.entity_id) fmt = service_call.data[ATTR_FORMAT] entity_ids = service_call.data[ATTR_MEDIA_PLAYER] url = request_stream( hass, source, fmt=fmt, keepalive=camera_prefs.preload_stream, options=camera.stream_options, ) data = { ATTR_MEDIA_CONTENT_ID: f"{get_url(hass)}{url}", ATTR_MEDIA_CONTENT_TYPE: FORMAT_CONTENT_TYPE[fmt], } # It is required to send a different payload for cast media players cast_entity_ids = [ entity for entity, source in entity_sources(hass).items() if entity in entity_ids and source["domain"] == "cast" ] other_entity_ids = list(set(entity_ids) - set(cast_entity_ids)) if cast_entity_ids: await hass.services.async_call( DOMAIN_MP, SERVICE_PLAY_MEDIA, { ATTR_ENTITY_ID: cast_entity_ids, **data, ATTR_MEDIA_EXTRA: { "stream_type": "LIVE", "media_info": { "hlsVideoSegmentFormat": "fmp4", }, }, }, blocking=True, context=service_call.context, ) if other_entity_ids: await hass.services.async_call( DOMAIN_MP, SERVICE_PLAY_MEDIA, { ATTR_ENTITY_ID: other_entity_ids, **data, }, blocking=True, context=service_call.context, )
[ "async", "def", "async_handle_play_stream_service", "(", "camera", ",", "service_call", ")", ":", "async", "with", "async_timeout", ".", "timeout", "(", "10", ")", ":", "source", "=", "await", "camera", ".", "stream_source", "(", ")", "if", "not", "source", ":", "raise", "HomeAssistantError", "(", "f\"{camera.entity_id} does not support play stream service\"", ")", "hass", "=", "camera", ".", "hass", "camera_prefs", "=", "hass", ".", "data", "[", "DATA_CAMERA_PREFS", "]", ".", "get", "(", "camera", ".", "entity_id", ")", "fmt", "=", "service_call", ".", "data", "[", "ATTR_FORMAT", "]", "entity_ids", "=", "service_call", ".", "data", "[", "ATTR_MEDIA_PLAYER", "]", "url", "=", "request_stream", "(", "hass", ",", "source", ",", "fmt", "=", "fmt", ",", "keepalive", "=", "camera_prefs", ".", "preload_stream", ",", "options", "=", "camera", ".", "stream_options", ",", ")", "data", "=", "{", "ATTR_MEDIA_CONTENT_ID", ":", "f\"{get_url(hass)}{url}\"", ",", "ATTR_MEDIA_CONTENT_TYPE", ":", "FORMAT_CONTENT_TYPE", "[", "fmt", "]", ",", "}", "# It is required to send a different payload for cast media players", "cast_entity_ids", "=", "[", "entity", "for", "entity", ",", "source", "in", "entity_sources", "(", "hass", ")", ".", "items", "(", ")", "if", "entity", "in", "entity_ids", "and", "source", "[", "\"domain\"", "]", "==", "\"cast\"", "]", "other_entity_ids", "=", "list", "(", "set", "(", "entity_ids", ")", "-", "set", "(", "cast_entity_ids", ")", ")", "if", "cast_entity_ids", ":", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN_MP", ",", "SERVICE_PLAY_MEDIA", ",", "{", "ATTR_ENTITY_ID", ":", "cast_entity_ids", ",", "*", "*", "data", ",", "ATTR_MEDIA_EXTRA", ":", "{", "\"stream_type\"", ":", "\"LIVE\"", ",", "\"media_info\"", ":", "{", "\"hlsVideoSegmentFormat\"", ":", "\"fmp4\"", ",", "}", ",", "}", ",", "}", ",", "blocking", "=", "True", ",", "context", "=", "service_call", ".", "context", ",", ")", "if", "other_entity_ids", ":", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN_MP", ",", "SERVICE_PLAY_MEDIA", ",", "{", "ATTR_ENTITY_ID", ":", "other_entity_ids", ",", "*", "*", "data", ",", "}", ",", "blocking", "=", "True", ",", "context", "=", "service_call", ".", "context", ",", ")" ]
[ 676, 0 ]
[ 739, 9 ]
python
en
['fr', 'en', 'en']
True
async_handle_record_service
(camera, call)
Handle stream recording service calls.
Handle stream recording service calls.
async def async_handle_record_service(camera, call): """Handle stream recording service calls.""" async with async_timeout.timeout(10): source = await camera.stream_source() if not source: raise HomeAssistantError(f"{camera.entity_id} does not support record service") hass = camera.hass filename = call.data[CONF_FILENAME] filename.hass = hass video_path = filename.async_render(variables={ATTR_ENTITY_ID: camera}) data = { CONF_STREAM_SOURCE: source, CONF_FILENAME: video_path, CONF_DURATION: call.data[CONF_DURATION], CONF_LOOKBACK: call.data[CONF_LOOKBACK], } await hass.services.async_call( DOMAIN_STREAM, SERVICE_RECORD, data, blocking=True, context=call.context )
[ "async", "def", "async_handle_record_service", "(", "camera", ",", "call", ")", ":", "async", "with", "async_timeout", ".", "timeout", "(", "10", ")", ":", "source", "=", "await", "camera", ".", "stream_source", "(", ")", "if", "not", "source", ":", "raise", "HomeAssistantError", "(", "f\"{camera.entity_id} does not support record service\"", ")", "hass", "=", "camera", ".", "hass", "filename", "=", "call", ".", "data", "[", "CONF_FILENAME", "]", "filename", ".", "hass", "=", "hass", "video_path", "=", "filename", ".", "async_render", "(", "variables", "=", "{", "ATTR_ENTITY_ID", ":", "camera", "}", ")", "data", "=", "{", "CONF_STREAM_SOURCE", ":", "source", ",", "CONF_FILENAME", ":", "video_path", ",", "CONF_DURATION", ":", "call", ".", "data", "[", "CONF_DURATION", "]", ",", "CONF_LOOKBACK", ":", "call", ".", "data", "[", "CONF_LOOKBACK", "]", ",", "}", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN_STREAM", ",", "SERVICE_RECORD", ",", "data", ",", "blocking", "=", "True", ",", "context", "=", "call", ".", "context", ")" ]
[ 742, 0 ]
[ 764, 5 ]
python
en
['en', 'it', 'en']
True
Camera.__init__
(self)
Initialize a camera.
Initialize a camera.
def __init__(self): """Initialize a camera.""" self.is_streaming = False self.stream_options = {} self.content_type = DEFAULT_CONTENT_TYPE self.access_tokens: collections.deque = collections.deque([], 2) self.async_update_token()
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "is_streaming", "=", "False", "self", ".", "stream_options", "=", "{", "}", "self", ".", "content_type", "=", "DEFAULT_CONTENT_TYPE", "self", ".", "access_tokens", ":", "collections", ".", "deque", "=", "collections", ".", "deque", "(", "[", "]", ",", "2", ")", "self", ".", "async_update_token", "(", ")" ]
[ 329, 4 ]
[ 335, 33 ]
python
co
['es', 'co', 'it']
False
Camera.should_poll
(self)
No need to poll cameras.
No need to poll cameras.
def should_poll(self): """No need to poll cameras.""" return False
[ "def", "should_poll", "(", "self", ")", ":", "return", "False" ]
[ 338, 4 ]
[ 340, 20 ]
python
en
['en', 'en', 'en']
True
Camera.entity_picture
(self)
Return a link to the camera feed as entity picture.
Return a link to the camera feed as entity picture.
def entity_picture(self): """Return a link to the camera feed as entity picture.""" return ENTITY_IMAGE_URL.format(self.entity_id, self.access_tokens[-1])
[ "def", "entity_picture", "(", "self", ")", ":", "return", "ENTITY_IMAGE_URL", ".", "format", "(", "self", ".", "entity_id", ",", "self", ".", "access_tokens", "[", "-", "1", "]", ")" ]
[ 343, 4 ]
[ 345, 78 ]
python
en
['en', 'en', 'en']
True
Camera.supported_features
(self)
Flag supported features.
Flag supported features.
def supported_features(self): """Flag supported features.""" return 0
[ "def", "supported_features", "(", "self", ")", ":", "return", "0" ]
[ 348, 4 ]
[ 350, 16 ]
python
en
['da', 'en', 'en']
True
Camera.is_recording
(self)
Return true if the device is recording.
Return true if the device is recording.
def is_recording(self): """Return true if the device is recording.""" return False
[ "def", "is_recording", "(", "self", ")", ":", "return", "False" ]
[ 353, 4 ]
[ 355, 20 ]
python
en
['en', 'en', 'en']
True
Camera.brand
(self)
Return the camera brand.
Return the camera brand.
def brand(self): """Return the camera brand.""" return None
[ "def", "brand", "(", "self", ")", ":", "return", "None" ]
[ 358, 4 ]
[ 360, 19 ]
python
en
['en', 'bs', 'en']
True
Camera.motion_detection_enabled
(self)
Return the camera motion detection status.
Return the camera motion detection status.
def motion_detection_enabled(self): """Return the camera motion detection status.""" return None
[ "def", "motion_detection_enabled", "(", "self", ")", ":", "return", "None" ]
[ 363, 4 ]
[ 365, 19 ]
python
en
['en', 'en', 'en']
True
Camera.model
(self)
Return the camera model.
Return the camera model.
def model(self): """Return the camera model.""" return None
[ "def", "model", "(", "self", ")", ":", "return", "None" ]
[ 368, 4 ]
[ 370, 19 ]
python
en
['en', 'co', 'en']
True
Camera.frame_interval
(self)
Return the interval between frames of the mjpeg stream.
Return the interval between frames of the mjpeg stream.
def frame_interval(self): """Return the interval between frames of the mjpeg stream.""" return 0.5
[ "def", "frame_interval", "(", "self", ")", ":", "return", "0.5" ]
[ 373, 4 ]
[ 375, 18 ]
python
en
['en', 'en', 'en']
True
Camera.stream_source
(self)
Return the source of the stream.
Return the source of the stream.
async def stream_source(self): """Return the source of the stream.""" return None
[ "async", "def", "stream_source", "(", "self", ")", ":", "return", "None" ]
[ 377, 4 ]
[ 379, 19 ]
python
en
['en', 'en', 'en']
True
Camera.camera_image
(self)
Return bytes of camera image.
Return bytes of camera image.
def camera_image(self): """Return bytes of camera image.""" raise NotImplementedError()
[ "def", "camera_image", "(", "self", ")", ":", "raise", "NotImplementedError", "(", ")" ]
[ 381, 4 ]
[ 383, 35 ]
python
en
['en', 'zu', 'en']
True
Camera.async_camera_image
(self)
Return bytes of camera image.
Return bytes of camera image.
async def async_camera_image(self): """Return bytes of camera image.""" return await self.hass.async_add_executor_job(self.camera_image)
[ "async", "def", "async_camera_image", "(", "self", ")", ":", "return", "await", "self", ".", "hass", ".", "async_add_executor_job", "(", "self", ".", "camera_image", ")" ]
[ 385, 4 ]
[ 387, 72 ]
python
en
['en', 'zu', 'en']
True
Camera.handle_async_still_stream
(self, request, interval)
Generate an HTTP MJPEG stream from camera images.
Generate an HTTP MJPEG stream from camera images.
async def handle_async_still_stream(self, request, interval): """Generate an HTTP MJPEG stream from camera images.""" return await async_get_still_stream( request, self.async_camera_image, self.content_type, interval )
[ "async", "def", "handle_async_still_stream", "(", "self", ",", "request", ",", "interval", ")", ":", "return", "await", "async_get_still_stream", "(", "request", ",", "self", ".", "async_camera_image", ",", "self", ".", "content_type", ",", "interval", ")" ]
[ 389, 4 ]
[ 393, 9 ]
python
en
['en', 'en', 'en']
True
Camera.handle_async_mjpeg_stream
(self, request)
Serve an HTTP MJPEG stream from the camera. This method can be overridden by camera platforms to proxy a direct stream from the camera.
Serve an HTTP MJPEG stream from the camera.
async def handle_async_mjpeg_stream(self, request): """Serve an HTTP MJPEG stream from the camera. This method can be overridden by camera platforms to proxy a direct stream from the camera. """ return await self.handle_async_still_stream(request, self.frame_interval)
[ "async", "def", "handle_async_mjpeg_stream", "(", "self", ",", "request", ")", ":", "return", "await", "self", ".", "handle_async_still_stream", "(", "request", ",", "self", ".", "frame_interval", ")" ]
[ 395, 4 ]
[ 401, 81 ]
python
en
['en', 'en', 'en']
True
Camera.state
(self)
Return the camera state.
Return the camera state.
def state(self): """Return the camera state.""" if self.is_recording: return STATE_RECORDING if self.is_streaming: return STATE_STREAMING return STATE_IDLE
[ "def", "state", "(", "self", ")", ":", "if", "self", ".", "is_recording", ":", "return", "STATE_RECORDING", "if", "self", ".", "is_streaming", ":", "return", "STATE_STREAMING", "return", "STATE_IDLE" ]
[ 404, 4 ]
[ 410, 25 ]
python
en
['en', 'co', 'en']
True
Camera.is_on
(self)
Return true if on.
Return true if on.
def is_on(self): """Return true if on.""" return True
[ "def", "is_on", "(", "self", ")", ":", "return", "True" ]
[ 413, 4 ]
[ 415, 19 ]
python
en
['en', 'mt', 'en']
True
Camera.turn_off
(self)
Turn off camera.
Turn off camera.
def turn_off(self): """Turn off camera.""" raise NotImplementedError()
[ "def", "turn_off", "(", "self", ")", ":", "raise", "NotImplementedError", "(", ")" ]
[ 417, 4 ]
[ 419, 35 ]
python
en
['en', 'ja', 'en']
True
Camera.async_turn_off
(self)
Turn off camera.
Turn off camera.
async def async_turn_off(self): """Turn off camera.""" await self.hass.async_add_executor_job(self.turn_off)
[ "async", "def", "async_turn_off", "(", "self", ")", ":", "await", "self", ".", "hass", ".", "async_add_executor_job", "(", "self", ".", "turn_off", ")" ]
[ 421, 4 ]
[ 423, 61 ]
python
en
['en', 'ja', 'en']
True
Camera.turn_on
(self)
Turn off camera.
Turn off camera.
def turn_on(self): """Turn off camera.""" raise NotImplementedError()
[ "def", "turn_on", "(", "self", ")", ":", "raise", "NotImplementedError", "(", ")" ]
[ 425, 4 ]
[ 427, 35 ]
python
en
['en', 'ja', 'en']
True
Camera.async_turn_on
(self)
Turn off camera.
Turn off camera.
async def async_turn_on(self): """Turn off camera.""" await self.hass.async_add_executor_job(self.turn_on)
[ "async", "def", "async_turn_on", "(", "self", ")", ":", "await", "self", ".", "hass", ".", "async_add_executor_job", "(", "self", ".", "turn_on", ")" ]
[ 429, 4 ]
[ 431, 60 ]
python
en
['en', 'ja', 'en']
True
Camera.enable_motion_detection
(self)
Enable motion detection in the camera.
Enable motion detection in the camera.
def enable_motion_detection(self): """Enable motion detection in the camera.""" raise NotImplementedError()
[ "def", "enable_motion_detection", "(", "self", ")", ":", "raise", "NotImplementedError", "(", ")" ]
[ 433, 4 ]
[ 435, 35 ]
python
en
['en', 'en', 'en']
True
Camera.async_enable_motion_detection
(self)
Call the job and enable motion detection.
Call the job and enable motion detection.
async def async_enable_motion_detection(self): """Call the job and enable motion detection.""" await self.hass.async_add_executor_job(self.enable_motion_detection)
[ "async", "def", "async_enable_motion_detection", "(", "self", ")", ":", "await", "self", ".", "hass", ".", "async_add_executor_job", "(", "self", ".", "enable_motion_detection", ")" ]
[ 437, 4 ]
[ 439, 76 ]
python
en
['en', 'en', 'en']
True
Camera.disable_motion_detection
(self)
Disable motion detection in camera.
Disable motion detection in camera.
def disable_motion_detection(self): """Disable motion detection in camera.""" raise NotImplementedError()
[ "def", "disable_motion_detection", "(", "self", ")", ":", "raise", "NotImplementedError", "(", ")" ]
[ 441, 4 ]
[ 443, 35 ]
python
en
['it', 'en', 'en']
True
Camera.async_disable_motion_detection
(self)
Call the job and disable motion detection.
Call the job and disable motion detection.
async def async_disable_motion_detection(self): """Call the job and disable motion detection.""" await self.hass.async_add_executor_job(self.disable_motion_detection)
[ "async", "def", "async_disable_motion_detection", "(", "self", ")", ":", "await", "self", ".", "hass", ".", "async_add_executor_job", "(", "self", ".", "disable_motion_detection", ")" ]
[ 445, 4 ]
[ 447, 77 ]
python
en
['en', 'en', 'en']
True
Camera.state_attributes
(self)
Return the camera state attributes.
Return the camera state attributes.
def state_attributes(self): """Return the camera state attributes.""" attrs = {"access_token": self.access_tokens[-1]} if self.model: attrs["model_name"] = self.model if self.brand: attrs["brand"] = self.brand if self.motion_detection_enabled: attrs["motion_detection"] = self.motion_detection_enabled return attrs
[ "def", "state_attributes", "(", "self", ")", ":", "attrs", "=", "{", "\"access_token\"", ":", "self", ".", "access_tokens", "[", "-", "1", "]", "}", "if", "self", ".", "model", ":", "attrs", "[", "\"model_name\"", "]", "=", "self", ".", "model", "if", "self", ".", "brand", ":", "attrs", "[", "\"brand\"", "]", "=", "self", ".", "brand", "if", "self", ".", "motion_detection_enabled", ":", "attrs", "[", "\"motion_detection\"", "]", "=", "self", ".", "motion_detection_enabled", "return", "attrs" ]
[ 450, 4 ]
[ 463, 20 ]
python
en
['en', 'co', 'en']
True
Camera.async_update_token
(self)
Update the used token.
Update the used token.
def async_update_token(self): """Update the used token.""" self.access_tokens.append( hashlib.sha256(_RND.getrandbits(256).to_bytes(32, "little")).hexdigest() )
[ "def", "async_update_token", "(", "self", ")", ":", "self", ".", "access_tokens", ".", "append", "(", "hashlib", ".", "sha256", "(", "_RND", ".", "getrandbits", "(", "256", ")", ".", "to_bytes", "(", "32", ",", "\"little\"", ")", ")", ".", "hexdigest", "(", ")", ")" ]
[ 466, 4 ]
[ 470, 9 ]
python
en
['en', 'en', 'en']
True
CameraView.__init__
(self, component: EntityComponent)
Initialize a basic camera view.
Initialize a basic camera view.
def __init__(self, component: EntityComponent) -> None: """Initialize a basic camera view.""" self.component = component
[ "def", "__init__", "(", "self", ",", "component", ":", "EntityComponent", ")", "->", "None", ":", "self", ".", "component", "=", "component" ]
[ 478, 4 ]
[ 480, 34 ]
python
en
['en', 'en', 'en']
True
CameraView.get
(self, request: web.Request, entity_id: str)
Start a GET request.
Start a GET request.
async def get(self, request: web.Request, entity_id: str) -> web.Response: """Start a GET request.""" camera = self.component.get_entity(entity_id) if camera is None: raise web.HTTPNotFound() authenticated = ( request[KEY_AUTHENTICATED] or request.query.get("token") in camera.access_tokens ) if not authenticated: raise web.HTTPUnauthorized() if not camera.is_on: _LOGGER.debug("Camera is off") raise web.HTTPServiceUnavailable() return await self.handle(request, camera)
[ "async", "def", "get", "(", "self", ",", "request", ":", "web", ".", "Request", ",", "entity_id", ":", "str", ")", "->", "web", ".", "Response", ":", "camera", "=", "self", ".", "component", ".", "get_entity", "(", "entity_id", ")", "if", "camera", "is", "None", ":", "raise", "web", ".", "HTTPNotFound", "(", ")", "authenticated", "=", "(", "request", "[", "KEY_AUTHENTICATED", "]", "or", "request", ".", "query", ".", "get", "(", "\"token\"", ")", "in", "camera", ".", "access_tokens", ")", "if", "not", "authenticated", ":", "raise", "web", ".", "HTTPUnauthorized", "(", ")", "if", "not", "camera", ".", "is_on", ":", "_LOGGER", ".", "debug", "(", "\"Camera is off\"", ")", "raise", "web", ".", "HTTPServiceUnavailable", "(", ")", "return", "await", "self", ".", "handle", "(", "request", ",", "camera", ")" ]
[ 482, 4 ]
[ 501, 49 ]
python
en
['en', 'lb', 'en']
True
CameraView.handle
(self, request, camera)
Handle the camera request.
Handle the camera request.
async def handle(self, request, camera): """Handle the camera request.""" raise NotImplementedError()
[ "async", "def", "handle", "(", "self", ",", "request", ",", "camera", ")", ":", "raise", "NotImplementedError", "(", ")" ]
[ 503, 4 ]
[ 505, 35 ]
python
en
['en', 'en', 'en']
True
CameraImageView.handle
(self, request: web.Request, camera: Camera)
Serve camera image.
Serve camera image.
async def handle(self, request: web.Request, camera: Camera) -> web.Response: """Serve camera image.""" with suppress(asyncio.CancelledError, asyncio.TimeoutError): async with async_timeout.timeout(10): image = await camera.async_camera_image() if image: return web.Response(body=image, content_type=camera.content_type) raise web.HTTPInternalServerError()
[ "async", "def", "handle", "(", "self", ",", "request", ":", "web", ".", "Request", ",", "camera", ":", "Camera", ")", "->", "web", ".", "Response", ":", "with", "suppress", "(", "asyncio", ".", "CancelledError", ",", "asyncio", ".", "TimeoutError", ")", ":", "async", "with", "async_timeout", ".", "timeout", "(", "10", ")", ":", "image", "=", "await", "camera", ".", "async_camera_image", "(", ")", "if", "image", ":", "return", "web", ".", "Response", "(", "body", "=", "image", ",", "content_type", "=", "camera", ".", "content_type", ")", "raise", "web", ".", "HTTPInternalServerError", "(", ")" ]
[ 514, 4 ]
[ 523, 43 ]
python
bs
['es', 'bs', 'en']
False
CameraMjpegStream.handle
(self, request: web.Request, camera: Camera)
Serve camera stream, possibly with interval.
Serve camera stream, possibly with interval.
async def handle(self, request: web.Request, camera: Camera) -> web.Response: """Serve camera stream, possibly with interval.""" interval = request.query.get("interval") if interval is None: return await camera.handle_async_mjpeg_stream(request) try: # Compose camera stream from stills interval = float(request.query.get("interval")) if interval < MIN_STREAM_INTERVAL: raise ValueError(f"Stream interval must be be > {MIN_STREAM_INTERVAL}") return await camera.handle_async_still_stream(request, interval) except ValueError as err: raise web.HTTPBadRequest() from err
[ "async", "def", "handle", "(", "self", ",", "request", ":", "web", ".", "Request", ",", "camera", ":", "Camera", ")", "->", "web", ".", "Response", ":", "interval", "=", "request", ".", "query", ".", "get", "(", "\"interval\"", ")", "if", "interval", "is", "None", ":", "return", "await", "camera", ".", "handle_async_mjpeg_stream", "(", "request", ")", "try", ":", "# Compose camera stream from stills", "interval", "=", "float", "(", "request", ".", "query", ".", "get", "(", "\"interval\"", ")", ")", "if", "interval", "<", "MIN_STREAM_INTERVAL", ":", "raise", "ValueError", "(", "f\"Stream interval must be be > {MIN_STREAM_INTERVAL}\"", ")", "return", "await", "camera", ".", "handle_async_still_stream", "(", "request", ",", "interval", ")", "except", "ValueError", "as", "err", ":", "raise", "web", ".", "HTTPBadRequest", "(", ")", "from", "err" ]
[ 532, 4 ]
[ 545, 47 ]
python
en
['en', 'en', 'en']
True
async_setup
(hass, config)
Set up the SPC component.
Set up the SPC component.
async def async_setup(hass, config): """Set up the SPC component.""" async def async_upate_callback(spc_object): if isinstance(spc_object, Area): async_dispatcher_send(hass, SIGNAL_UPDATE_ALARM.format(spc_object.id)) elif isinstance(spc_object, Zone): async_dispatcher_send(hass, SIGNAL_UPDATE_SENSOR.format(spc_object.id)) session = aiohttp_client.async_get_clientsession(hass) spc = SpcWebGateway( loop=hass.loop, session=session, api_url=config[DOMAIN].get(CONF_API_URL), ws_url=config[DOMAIN].get(CONF_WS_URL), async_callback=async_upate_callback, ) hass.data[DATA_API] = spc if not await spc.async_load_parameters(): _LOGGER.error("Failed to load area/zone information from SPC") return False # add sensor devices for each zone (typically motion/fire/door sensors) hass.async_create_task( discovery.async_load_platform(hass, "binary_sensor", DOMAIN, {}, config) ) # create a separate alarm panel for each area hass.async_create_task( discovery.async_load_platform(hass, "alarm_control_panel", DOMAIN, {}, config) ) # start listening for incoming events over websocket spc.start() return True
[ "async", "def", "async_setup", "(", "hass", ",", "config", ")", ":", "async", "def", "async_upate_callback", "(", "spc_object", ")", ":", "if", "isinstance", "(", "spc_object", ",", "Area", ")", ":", "async_dispatcher_send", "(", "hass", ",", "SIGNAL_UPDATE_ALARM", ".", "format", "(", "spc_object", ".", "id", ")", ")", "elif", "isinstance", "(", "spc_object", ",", "Zone", ")", ":", "async_dispatcher_send", "(", "hass", ",", "SIGNAL_UPDATE_SENSOR", ".", "format", "(", "spc_object", ".", "id", ")", ")", "session", "=", "aiohttp_client", ".", "async_get_clientsession", "(", "hass", ")", "spc", "=", "SpcWebGateway", "(", "loop", "=", "hass", ".", "loop", ",", "session", "=", "session", ",", "api_url", "=", "config", "[", "DOMAIN", "]", ".", "get", "(", "CONF_API_URL", ")", ",", "ws_url", "=", "config", "[", "DOMAIN", "]", ".", "get", "(", "CONF_WS_URL", ")", ",", "async_callback", "=", "async_upate_callback", ",", ")", "hass", ".", "data", "[", "DATA_API", "]", "=", "spc", "if", "not", "await", "spc", ".", "async_load_parameters", "(", ")", ":", "_LOGGER", ".", "error", "(", "\"Failed to load area/zone information from SPC\"", ")", "return", "False", "# add sensor devices for each zone (typically motion/fire/door sensors)", "hass", ".", "async_create_task", "(", "discovery", ".", "async_load_platform", "(", "hass", ",", "\"binary_sensor\"", ",", "DOMAIN", ",", "{", "}", ",", "config", ")", ")", "# create a separate alarm panel for each area", "hass", ".", "async_create_task", "(", "discovery", ".", "async_load_platform", "(", "hass", ",", "\"alarm_control_panel\"", ",", "DOMAIN", ",", "{", "}", ",", "config", ")", ")", "# start listening for incoming events over websocket", "spc", ".", "start", "(", ")", "return", "True" ]
[ 36, 0 ]
[ 75, 15 ]
python
en
['en', 'en', 'en']
True
PoolEmptyException.__str__
(self)
proxypool is used out :return:
proxypool is used out :return:
def __str__(self): """ proxypool is used out :return: """ return repr('no proxy in proxypool')
[ "def", "__str__", "(", "self", ")", ":", "return", "repr", "(", "'no proxy in proxypool'", ")" ]
[ 1, 4 ]
[ 6, 44 ]
python
en
['en', 'error', 'th']
False
_get_default_logging_level
()
If TRANSFORMERS_VERBOSITY env var is set to one of the valid choices return that as the new default level. If it is not - fall back to ``_default_log_level``
If TRANSFORMERS_VERBOSITY env var is set to one of the valid choices return that as the new default level. If it is not - fall back to ``_default_log_level``
def _get_default_logging_level(): """ If TRANSFORMERS_VERBOSITY env var is set to one of the valid choices return that as the new default level. If it is not - fall back to ``_default_log_level`` """ env_level_str = os.getenv("TRANSFORMERS_VERBOSITY", None) if env_level_str: if env_level_str in log_levels: return log_levels[env_level_str] else: logging.getLogger().warning( f"Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, " f"has to be one of: { ', '.join(log_levels.keys()) }" ) return _default_log_level
[ "def", "_get_default_logging_level", "(", ")", ":", "env_level_str", "=", "os", ".", "getenv", "(", "\"TRANSFORMERS_VERBOSITY\"", ",", "None", ")", "if", "env_level_str", ":", "if", "env_level_str", "in", "log_levels", ":", "return", "log_levels", "[", "env_level_str", "]", "else", ":", "logging", ".", "getLogger", "(", ")", ".", "warning", "(", "f\"Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, \"", "f\"has to be one of: { ', '.join(log_levels.keys()) }\"", ")", "return", "_default_log_level" ]
[ 45, 0 ]
[ 59, 29 ]
python
en
['en', 'error', 'th']
False
get_logger
(name: Optional[str] = None)
Return a logger with the specified name. This function is not supposed to be directly accessed unless you are writing a custom transformers module.
Return a logger with the specified name.
def get_logger(name: Optional[str] = None) -> logging.Logger: """ Return a logger with the specified name. This function is not supposed to be directly accessed unless you are writing a custom transformers module. """ if name is None: name = _get_library_name() _configure_library_root_logger() return logging.getLogger(name)
[ "def", "get_logger", "(", "name", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "logging", ".", "Logger", ":", "if", "name", "is", "None", ":", "name", "=", "_get_library_name", "(", ")", "_configure_library_root_logger", "(", ")", "return", "logging", ".", "getLogger", "(", "name", ")" ]
[ 104, 0 ]
[ 115, 34 ]
python
en
['en', 'error', 'th']
False
get_verbosity
()
Return the current level for the 🤗 Transformers's root logger as an int. Returns: :obj:`int`: The logging level. .. note:: 🤗 Transformers has following logging levels: - 50: ``transformers.logging.CRITICAL`` or ``transformers.logging.FATAL`` - 40: ``transformers.logging.ERROR`` - 30: ``transformers.logging.WARNING`` or ``transformers.logging.WARN`` - 20: ``transformers.logging.INFO`` - 10: ``transformers.logging.DEBUG``
Return the current level for the 🤗 Transformers's root logger as an int.
def get_verbosity() -> int: """ Return the current level for the 🤗 Transformers's root logger as an int. Returns: :obj:`int`: The logging level. .. note:: 🤗 Transformers has following logging levels: - 50: ``transformers.logging.CRITICAL`` or ``transformers.logging.FATAL`` - 40: ``transformers.logging.ERROR`` - 30: ``transformers.logging.WARNING`` or ``transformers.logging.WARN`` - 20: ``transformers.logging.INFO`` - 10: ``transformers.logging.DEBUG`` """ _configure_library_root_logger() return _get_library_root_logger().getEffectiveLevel()
[ "def", "get_verbosity", "(", ")", "->", "int", ":", "_configure_library_root_logger", "(", ")", "return", "_get_library_root_logger", "(", ")", ".", "getEffectiveLevel", "(", ")" ]
[ 118, 0 ]
[ 137, 57 ]
python
en
['en', 'error', 'th']
False
set_verbosity
(verbosity: int)
Set the vebosity level for the 🤗 Transformers's root logger. Args: verbosity (:obj:`int`): Logging level, e.g., one of: - ``transformers.logging.CRITICAL`` or ``transformers.logging.FATAL`` - ``transformers.logging.ERROR`` - ``transformers.logging.WARNING`` or ``transformers.logging.WARN`` - ``transformers.logging.INFO`` - ``transformers.logging.DEBUG``
Set the vebosity level for the 🤗 Transformers's root logger.
def set_verbosity(verbosity: int) -> None: """ Set the vebosity level for the 🤗 Transformers's root logger. Args: verbosity (:obj:`int`): Logging level, e.g., one of: - ``transformers.logging.CRITICAL`` or ``transformers.logging.FATAL`` - ``transformers.logging.ERROR`` - ``transformers.logging.WARNING`` or ``transformers.logging.WARN`` - ``transformers.logging.INFO`` - ``transformers.logging.DEBUG`` """ _configure_library_root_logger() _get_library_root_logger().setLevel(verbosity)
[ "def", "set_verbosity", "(", "verbosity", ":", "int", ")", "->", "None", ":", "_configure_library_root_logger", "(", ")", "_get_library_root_logger", "(", ")", ".", "setLevel", "(", "verbosity", ")" ]
[ 140, 0 ]
[ 156, 50 ]
python
en
['en', 'error', 'th']
False
set_verbosity_info
()
Set the verbosity to the :obj:`INFO` level.
Set the verbosity to the :obj:`INFO` level.
def set_verbosity_info(): """Set the verbosity to the :obj:`INFO` level.""" return set_verbosity(INFO)
[ "def", "set_verbosity_info", "(", ")", ":", "return", "set_verbosity", "(", "INFO", ")" ]
[ 159, 0 ]
[ 161, 30 ]
python
en
['en', 'en', 'en']
True
set_verbosity_warning
()
Set the verbosity to the :obj:`WARNING` level.
Set the verbosity to the :obj:`WARNING` level.
def set_verbosity_warning(): """Set the verbosity to the :obj:`WARNING` level.""" return set_verbosity(WARNING)
[ "def", "set_verbosity_warning", "(", ")", ":", "return", "set_verbosity", "(", "WARNING", ")" ]
[ 164, 0 ]
[ 166, 33 ]
python
en
['en', 'en', 'en']
True
set_verbosity_debug
()
Set the verbosity to the :obj:`DEBUG` level.
Set the verbosity to the :obj:`DEBUG` level.
def set_verbosity_debug(): """Set the verbosity to the :obj:`DEBUG` level.""" return set_verbosity(DEBUG)
[ "def", "set_verbosity_debug", "(", ")", ":", "return", "set_verbosity", "(", "DEBUG", ")" ]
[ 169, 0 ]
[ 171, 31 ]
python
en
['en', 'en', 'en']
True
set_verbosity_error
()
Set the verbosity to the :obj:`ERROR` level.
Set the verbosity to the :obj:`ERROR` level.
def set_verbosity_error(): """Set the verbosity to the :obj:`ERROR` level.""" return set_verbosity(ERROR)
[ "def", "set_verbosity_error", "(", ")", ":", "return", "set_verbosity", "(", "ERROR", ")" ]
[ 174, 0 ]
[ 176, 31 ]
python
en
['en', 'sr', 'en']
True
disable_default_handler
()
Disable the default handler of the HuggingFace Transformers's root logger.
Disable the default handler of the HuggingFace Transformers's root logger.
def disable_default_handler() -> None: """Disable the default handler of the HuggingFace Transformers's root logger.""" _configure_library_root_logger() assert _default_handler is not None _get_library_root_logger().removeHandler(_default_handler)
[ "def", "disable_default_handler", "(", ")", "->", "None", ":", "_configure_library_root_logger", "(", ")", "assert", "_default_handler", "is", "not", "None", "_get_library_root_logger", "(", ")", ".", "removeHandler", "(", "_default_handler", ")" ]
[ 179, 0 ]
[ 185, 62 ]
python
en
['en', 'en', 'en']
True
enable_default_handler
()
Enable the default handler of the HuggingFace Transformers's root logger.
Enable the default handler of the HuggingFace Transformers's root logger.
def enable_default_handler() -> None: """Enable the default handler of the HuggingFace Transformers's root logger.""" _configure_library_root_logger() assert _default_handler is not None _get_library_root_logger().addHandler(_default_handler)
[ "def", "enable_default_handler", "(", ")", "->", "None", ":", "_configure_library_root_logger", "(", ")", "assert", "_default_handler", "is", "not", "None", "_get_library_root_logger", "(", ")", ".", "addHandler", "(", "_default_handler", ")" ]
[ 188, 0 ]
[ 194, 59 ]
python
en
['en', 'en', 'en']
True
add_handler
(handler: logging.Handler)
adds a handler to the HuggingFace Transformers's root logger.
adds a handler to the HuggingFace Transformers's root logger.
def add_handler(handler: logging.Handler) -> None: """adds a handler to the HuggingFace Transformers's root logger.""" _configure_library_root_logger() assert handler is not None _get_library_root_logger().addHandler(handler)
[ "def", "add_handler", "(", "handler", ":", "logging", ".", "Handler", ")", "->", "None", ":", "_configure_library_root_logger", "(", ")", "assert", "handler", "is", "not", "None", "_get_library_root_logger", "(", ")", ".", "addHandler", "(", "handler", ")" ]
[ 197, 0 ]
[ 203, 50 ]
python
en
['en', 'en', 'en']
True
remove_handler
(handler: logging.Handler)
removes given handler from the HuggingFace Transformers's root logger.
removes given handler from the HuggingFace Transformers's root logger.
def remove_handler(handler: logging.Handler) -> None: """removes given handler from the HuggingFace Transformers's root logger.""" _configure_library_root_logger() assert handler is not None and handler not in _get_library_root_logger().handlers _get_library_root_logger().removeHandler(handler)
[ "def", "remove_handler", "(", "handler", ":", "logging", ".", "Handler", ")", "->", "None", ":", "_configure_library_root_logger", "(", ")", "assert", "handler", "is", "not", "None", "and", "handler", "not", "in", "_get_library_root_logger", "(", ")", ".", "handlers", "_get_library_root_logger", "(", ")", ".", "removeHandler", "(", "handler", ")" ]
[ 206, 0 ]
[ 212, 53 ]
python
en
['en', 'en', 'en']
True
disable_propagation
()
Disable propagation of the library log outputs. Note that log propagation is disabled by default.
Disable propagation of the library log outputs. Note that log propagation is disabled by default.
def disable_propagation() -> None: """ Disable propagation of the library log outputs. Note that log propagation is disabled by default. """ _configure_library_root_logger() _get_library_root_logger().propagate = False
[ "def", "disable_propagation", "(", ")", "->", "None", ":", "_configure_library_root_logger", "(", ")", "_get_library_root_logger", "(", ")", ".", "propagate", "=", "False" ]
[ 215, 0 ]
[ 221, 48 ]
python
en
['en', 'error', 'th']
False
enable_propagation
()
Enable propagation of the library log outputs. Please disable the HuggingFace Transformers's default handler to prevent double logging if the root logger has been configured.
Enable propagation of the library log outputs. Please disable the HuggingFace Transformers's default handler to prevent double logging if the root logger has been configured.
def enable_propagation() -> None: """ Enable propagation of the library log outputs. Please disable the HuggingFace Transformers's default handler to prevent double logging if the root logger has been configured. """ _configure_library_root_logger() _get_library_root_logger().propagate = True
[ "def", "enable_propagation", "(", ")", "->", "None", ":", "_configure_library_root_logger", "(", ")", "_get_library_root_logger", "(", ")", ".", "propagate", "=", "True" ]
[ 224, 0 ]
[ 231, 47 ]
python
en
['en', 'error', 'th']
False
enable_explicit_format
()
Enable explicit formatting for every HuggingFace Transformers's logger. The explicit formatter is as follows: :: [LEVELNAME|FILENAME|LINE NUMBER] TIME >> MESSAGE All handlers currently bound to the root logger are affected by this method.
Enable explicit formatting for every HuggingFace Transformers's logger. The explicit formatter is as follows:
def enable_explicit_format() -> None: """ Enable explicit formatting for every HuggingFace Transformers's logger. The explicit formatter is as follows: :: [LEVELNAME|FILENAME|LINE NUMBER] TIME >> MESSAGE All handlers currently bound to the root logger are affected by this method. """ handlers = _get_library_root_logger().handlers for handler in handlers: formatter = logging.Formatter("[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s") handler.setFormatter(formatter)
[ "def", "enable_explicit_format", "(", ")", "->", "None", ":", "handlers", "=", "_get_library_root_logger", "(", ")", ".", "handlers", "for", "handler", "in", "handlers", ":", "formatter", "=", "logging", ".", "Formatter", "(", "\"[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s\"", ")", "handler", ".", "setFormatter", "(", "formatter", ")" ]
[ 234, 0 ]
[ 248, 39 ]
python
en
['en', 'error', 'th']
False
reset_format
()
Resets the formatting for HuggingFace Transformers's loggers. All handlers currently bound to the root logger are affected by this method.
Resets the formatting for HuggingFace Transformers's loggers.
def reset_format() -> None: """ Resets the formatting for HuggingFace Transformers's loggers. All handlers currently bound to the root logger are affected by this method. """ handlers = _get_library_root_logger().handlers for handler in handlers: handler.setFormatter(None)
[ "def", "reset_format", "(", ")", "->", "None", ":", "handlers", "=", "_get_library_root_logger", "(", ")", ".", "handlers", "for", "handler", "in", "handlers", ":", "handler", ".", "setFormatter", "(", "None", ")" ]
[ 251, 0 ]
[ 260, 34 ]
python
en
['en', 'error', 'th']
False
test_deprecated_base_class
(caplog)
Test deprecated base class.
Test deprecated base class.
def test_deprecated_base_class(caplog): """Test deprecated base class.""" class CustomAlarm(alarm_control_panel.AlarmControlPanel): def supported_features(self): pass CustomAlarm() assert "AlarmControlPanel is deprecated, modify CustomAlarm" in caplog.text
[ "def", "test_deprecated_base_class", "(", "caplog", ")", ":", "class", "CustomAlarm", "(", "alarm_control_panel", ".", "AlarmControlPanel", ")", ":", "def", "supported_features", "(", "self", ")", ":", "pass", "CustomAlarm", "(", ")", "assert", "\"AlarmControlPanel is deprecated, modify CustomAlarm\"", "in", "caplog", ".", "text" ]
[ 4, 0 ]
[ 12, 79 ]
python
en
['en', 'en', 'en']
True
async_setup
(hass: HomeAssistantType, config: ConfigType)
Set up ptvsd debugger.
Set up ptvsd debugger.
async def async_setup(hass: HomeAssistantType, config: ConfigType): """Set up ptvsd debugger.""" _LOGGER.warning( "ptvsd is deprecated and will be removed in Home Assistant Core 0.120." "The debugpy integration can be used as a full replacement for ptvsd" ) # This is a local import, since importing this at the top, will cause # ptvsd to hook into `sys.settrace`. So does `coverage` to generate # coverage, resulting in a battle and incomplete code test coverage. import ptvsd # pylint: disable=import-outside-toplevel conf = config[DOMAIN] host = conf[CONF_HOST] port = conf[CONF_PORT] ptvsd.enable_attach((host, port)) wait = conf[CONF_WAIT] if wait: _LOGGER.warning("Waiting for ptvsd connection on %s:%s", host, port) ready = Event() def waitfor(): ptvsd.wait_for_attach() hass.loop.call_soon_threadsafe(ready.set) Thread(target=waitfor).start() await ready.wait() else: _LOGGER.warning("Listening for ptvsd connection on %s:%s", host, port) return True
[ "async", "def", "async_setup", "(", "hass", ":", "HomeAssistantType", ",", "config", ":", "ConfigType", ")", ":", "_LOGGER", ".", "warning", "(", "\"ptvsd is deprecated and will be removed in Home Assistant Core 0.120.\"", "\"The debugpy integration can be used as a full replacement for ptvsd\"", ")", "# This is a local import, since importing this at the top, will cause", "# ptvsd to hook into `sys.settrace`. So does `coverage` to generate", "# coverage, resulting in a battle and incomplete code test coverage.", "import", "ptvsd", "# pylint: disable=import-outside-toplevel", "conf", "=", "config", "[", "DOMAIN", "]", "host", "=", "conf", "[", "CONF_HOST", "]", "port", "=", "conf", "[", "CONF_PORT", "]", "ptvsd", ".", "enable_attach", "(", "(", "host", ",", "port", ")", ")", "wait", "=", "conf", "[", "CONF_WAIT", "]", "if", "wait", ":", "_LOGGER", ".", "warning", "(", "\"Waiting for ptvsd connection on %s:%s\"", ",", "host", ",", "port", ")", "ready", "=", "Event", "(", ")", "def", "waitfor", "(", ")", ":", "ptvsd", ".", "wait_for_attach", "(", ")", "hass", ".", "loop", ".", "call_soon_threadsafe", "(", "ready", ".", "set", ")", "Thread", "(", "target", "=", "waitfor", ")", ".", "start", "(", ")", "await", "ready", ".", "wait", "(", ")", "else", ":", "_LOGGER", ".", "warning", "(", "\"Listening for ptvsd connection on %s:%s\"", ",", "host", ",", "port", ")", "return", "True" ]
[ 36, 0 ]
[ 69, 15 ]
python
en
['en', 'fil', 'en']
True
test_config_entry_not_ready
( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker )
Test the configuration entry not ready.
Test the configuration entry not ready.
async def test_config_entry_not_ready( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker ) -> None: """Test the configuration entry not ready.""" entry = await setup_integration(hass, aioclient_mock, connection_error=True) assert entry.state == ENTRY_STATE_SETUP_RETRY
[ "async", "def", "test_config_entry_not_ready", "(", "hass", ":", "HomeAssistant", ",", "aioclient_mock", ":", "AiohttpClientMocker", ")", "->", "None", ":", "entry", "=", "await", "setup_integration", "(", "hass", ",", "aioclient_mock", ",", "connection_error", "=", "True", ")", "assert", "entry", ".", "state", "==", "ENTRY_STATE_SETUP_RETRY" ]
[ 17, 0 ]
[ 22, 49 ]
python
en
['en', 'en', 'en']
True
test_config_entry_reauth
( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker )
Test the configuration entry needing to be re-authenticated.
Test the configuration entry needing to be re-authenticated.
async def test_config_entry_reauth( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker ) -> None: """Test the configuration entry needing to be re-authenticated.""" with patch.object(hass.config_entries.flow, "async_init") as mock_flow_init: entry = await setup_integration(hass, aioclient_mock, invalid_auth=True) assert entry.state == ENTRY_STATE_SETUP_ERROR mock_flow_init.assert_called_once_with( DOMAIN, context={CONF_SOURCE: SOURCE_REAUTH}, data={"config_entry_id": entry.entry_id, **entry.data}, )
[ "async", "def", "test_config_entry_reauth", "(", "hass", ":", "HomeAssistant", ",", "aioclient_mock", ":", "AiohttpClientMocker", ")", "->", "None", ":", "with", "patch", ".", "object", "(", "hass", ".", "config_entries", ".", "flow", ",", "\"async_init\"", ")", "as", "mock_flow_init", ":", "entry", "=", "await", "setup_integration", "(", "hass", ",", "aioclient_mock", ",", "invalid_auth", "=", "True", ")", "assert", "entry", ".", "state", "==", "ENTRY_STATE_SETUP_ERROR", "mock_flow_init", ".", "assert_called_once_with", "(", "DOMAIN", ",", "context", "=", "{", "CONF_SOURCE", ":", "SOURCE_REAUTH", "}", ",", "data", "=", "{", "\"config_entry_id\"", ":", "entry", ".", "entry_id", ",", "*", "*", "entry", ".", "data", "}", ",", ")" ]
[ 25, 0 ]
[ 38, 5 ]
python
en
['en', 'en', 'en']
True
test_unload_config_entry
( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker )
Test the configuration entry unloading.
Test the configuration entry unloading.
async def test_unload_config_entry( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker ) -> None: """Test the configuration entry unloading.""" with patch( "homeassistant.components.sonarr.sensor.async_setup_entry", return_value=True, ): entry = await setup_integration(hass, aioclient_mock) assert hass.data[DOMAIN] assert entry.entry_id in hass.data[DOMAIN] assert entry.state == ENTRY_STATE_LOADED await hass.config_entries.async_unload(entry.entry_id) await hass.async_block_till_done() assert entry.entry_id not in hass.data[DOMAIN] assert entry.state == ENTRY_STATE_NOT_LOADED
[ "async", "def", "test_unload_config_entry", "(", "hass", ":", "HomeAssistant", ",", "aioclient_mock", ":", "AiohttpClientMocker", ")", "->", "None", ":", "with", "patch", "(", "\"homeassistant.components.sonarr.sensor.async_setup_entry\"", ",", "return_value", "=", "True", ",", ")", ":", "entry", "=", "await", "setup_integration", "(", "hass", ",", "aioclient_mock", ")", "assert", "hass", ".", "data", "[", "DOMAIN", "]", "assert", "entry", ".", "entry_id", "in", "hass", ".", "data", "[", "DOMAIN", "]", "assert", "entry", ".", "state", "==", "ENTRY_STATE_LOADED", "await", "hass", ".", "config_entries", ".", "async_unload", "(", "entry", ".", "entry_id", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "entry", ".", "entry_id", "not", "in", "hass", ".", "data", "[", "DOMAIN", "]", "assert", "entry", ".", "state", "==", "ENTRY_STATE_NOT_LOADED" ]
[ 41, 0 ]
[ 59, 48 ]
python
en
['en', 'en', 'en']
True
_process_timestamp
(ts)
Process a timestamp into datetime object.
Process a timestamp into datetime object.
def _process_timestamp(ts): """Process a timestamp into datetime object.""" if ts is None: return None if ts.tzinfo is None: return dt_util.UTC.localize(ts) return dt_util.as_utc(ts)
[ "def", "_process_timestamp", "(", "ts", ")", ":", "if", "ts", "is", "None", ":", "return", "None", "if", "ts", ".", "tzinfo", "is", "None", ":", "return", "dt_util", ".", "UTC", ".", "localize", "(", "ts", ")", "return", "dt_util", ".", "as_utc", "(", "ts", ")" ]
[ 167, 0 ]
[ 173, 29 ]
python
cs
['pt', 'cs', 'en']
False
Events.from_event
(event)
Create an event database object from a native event.
Create an event database object from a native event.
def from_event(event): """Create an event database object from a native event.""" return Events( event_type=event.event_type, event_data=json.dumps(event.data, cls=JSONEncoder), origin=str(event.origin), time_fired=event.time_fired, )
[ "def", "from_event", "(", "event", ")", ":", "return", "Events", "(", "event_type", "=", "event", ".", "event_type", ",", "event_data", "=", "json", ".", "dumps", "(", "event", ".", "data", ",", "cls", "=", "JSONEncoder", ")", ",", "origin", "=", "str", "(", "event", ".", "origin", ")", ",", "time_fired", "=", "event", ".", "time_fired", ",", ")" ]
[ 46, 4 ]
[ 53, 9 ]
python
en
['en', 'en', 'en']
True
Events.to_native
(self)
Convert to a natve HA Event.
Convert to a natve HA Event.
def to_native(self): """Convert to a natve HA Event.""" try: return Event( self.event_type, json.loads(self.event_data), EventOrigin(self.origin), _process_timestamp(self.time_fired), ) except ValueError: # When json.loads fails _LOGGER.exception("Error converting to event: %s", self) return None
[ "def", "to_native", "(", "self", ")", ":", "try", ":", "return", "Event", "(", "self", ".", "event_type", ",", "json", ".", "loads", "(", "self", ".", "event_data", ")", ",", "EventOrigin", "(", "self", ".", "origin", ")", ",", "_process_timestamp", "(", "self", ".", "time_fired", ")", ",", ")", "except", "ValueError", ":", "# When json.loads fails", "_LOGGER", ".", "exception", "(", "\"Error converting to event: %s\"", ",", "self", ")", "return", "None" ]
[ 55, 4 ]
[ 67, 23 ]
python
ca
['en', 'ca', 'pt']
False
States.from_event
(event)
Create object from a state_changed event.
Create object from a state_changed event.
def from_event(event): """Create object from a state_changed event.""" entity_id = event.data["entity_id"] state = event.data.get("new_state") dbstate = States(entity_id=entity_id) # State got deleted if state is None: dbstate.state = "" dbstate.domain = split_entity_id(entity_id)[0] dbstate.attributes = "{}" dbstate.last_changed = event.time_fired dbstate.last_updated = event.time_fired else: dbstate.domain = state.domain dbstate.state = state.state dbstate.attributes = json.dumps(dict(state.attributes), cls=JSONEncoder) dbstate.last_changed = state.last_changed dbstate.last_updated = state.last_updated return dbstate
[ "def", "from_event", "(", "event", ")", ":", "entity_id", "=", "event", ".", "data", "[", "\"entity_id\"", "]", "state", "=", "event", ".", "data", ".", "get", "(", "\"new_state\"", ")", "dbstate", "=", "States", "(", "entity_id", "=", "entity_id", ")", "# State got deleted", "if", "state", "is", "None", ":", "dbstate", ".", "state", "=", "\"\"", "dbstate", ".", "domain", "=", "split_entity_id", "(", "entity_id", ")", "[", "0", "]", "dbstate", ".", "attributes", "=", "\"{}\"", "dbstate", ".", "last_changed", "=", "event", ".", "time_fired", "dbstate", ".", "last_updated", "=", "event", ".", "time_fired", "else", ":", "dbstate", ".", "domain", "=", "state", ".", "domain", "dbstate", ".", "state", "=", "state", ".", "state", "dbstate", ".", "attributes", "=", "json", ".", "dumps", "(", "dict", "(", "state", ".", "attributes", ")", ",", "cls", "=", "JSONEncoder", ")", "dbstate", ".", "last_changed", "=", "state", ".", "last_changed", "dbstate", ".", "last_updated", "=", "state", ".", "last_updated", "return", "dbstate" ]
[ 90, 4 ]
[ 111, 22 ]
python
en
['en', 'en', 'en']
True
States.to_native
(self)
Convert to an HA state object.
Convert to an HA state object.
def to_native(self): """Convert to an HA state object.""" try: return State( self.entity_id, self.state, json.loads(self.attributes), _process_timestamp(self.last_changed), _process_timestamp(self.last_updated), ) except ValueError: # When json.loads fails _LOGGER.exception("Error converting row to state: %s", self) return None
[ "def", "to_native", "(", "self", ")", ":", "try", ":", "return", "State", "(", "self", ".", "entity_id", ",", "self", ".", "state", ",", "json", ".", "loads", "(", "self", ".", "attributes", ")", ",", "_process_timestamp", "(", "self", ".", "last_changed", ")", ",", "_process_timestamp", "(", "self", ".", "last_updated", ")", ",", ")", "except", "ValueError", ":", "# When json.loads fails", "_LOGGER", ".", "exception", "(", "\"Error converting row to state: %s\"", ",", "self", ")", "return", "None" ]
[ 113, 4 ]
[ 126, 23 ]
python
en
['en', 'en', 'en']
True
RecorderRuns.entity_ids
(self, point_in_time=None)
Return the entity ids that existed in this run. Specify point_in_time if you want to know which existed at that point in time inside the run.
Return the entity ids that existed in this run.
def entity_ids(self, point_in_time=None): """Return the entity ids that existed in this run. Specify point_in_time if you want to know which existed at that point in time inside the run. """ from sqlalchemy.orm.session import Session session = Session.object_session(self) assert session is not None, "RecorderRuns need to be persisted" query = session.query(distinct(States.entity_id)).filter( States.last_updated >= self.start ) if point_in_time is not None: query = query.filter(States.last_updated < point_in_time) elif self.end is not None: query = query.filter(States.last_updated < self.end) return [row[0] for row in query]
[ "def", "entity_ids", "(", "self", ",", "point_in_time", "=", "None", ")", ":", "from", "sqlalchemy", ".", "orm", ".", "session", "import", "Session", "session", "=", "Session", ".", "object_session", "(", "self", ")", "assert", "session", "is", "not", "None", ",", "\"RecorderRuns need to be persisted\"", "query", "=", "session", ".", "query", "(", "distinct", "(", "States", ".", "entity_id", ")", ")", ".", "filter", "(", "States", ".", "last_updated", ">=", "self", ".", "start", ")", "if", "point_in_time", "is", "not", "None", ":", "query", "=", "query", ".", "filter", "(", "States", ".", "last_updated", "<", "point_in_time", ")", "elif", "self", ".", "end", "is", "not", "None", ":", "query", "=", "query", ".", "filter", "(", "States", ".", "last_updated", "<", "self", ".", "end", ")", "return", "[", "row", "[", "0", "]", "for", "row", "in", "query", "]" ]
[ 139, 4 ]
[ 160, 40 ]
python
en
['en', 'en', 'en']
True
RecorderRuns.to_native
(self)
Return self, native format is this model.
Return self, native format is this model.
def to_native(self): """Return self, native format is this model.""" return self
[ "def", "to_native", "(", "self", ")", ":", "return", "self" ]
[ 162, 4 ]
[ 164, 19 ]
python
en
['en', 'en', 'en']
True
test_valve_switches
(hass, config_entry, aioclient_mock_fixture)
Test Flo by Moen valve switches.
Test Flo by Moen valve switches.
async def test_valve_switches(hass, config_entry, aioclient_mock_fixture): """Test Flo by Moen valve switches.""" config_entry.add_to_hass(hass) assert await async_setup_component( hass, FLO_DOMAIN, {CONF_USERNAME: TEST_USER_ID, CONF_PASSWORD: TEST_PASSWORD} ) await hass.async_block_till_done() assert len(hass.data[FLO_DOMAIN][config_entry.entry_id]["devices"]) == 1 entity_id = "switch.shutoff_valve" assert hass.states.get(entity_id).state == STATE_ON await hass.services.async_call( DOMAIN, "turn_off", {"entity_id": entity_id}, blocking=True ) assert hass.states.get(entity_id).state == STATE_OFF await hass.services.async_call( DOMAIN, "turn_on", {"entity_id": entity_id}, blocking=True ) assert hass.states.get(entity_id).state == STATE_ON
[ "async", "def", "test_valve_switches", "(", "hass", ",", "config_entry", ",", "aioclient_mock_fixture", ")", ":", "config_entry", ".", "add_to_hass", "(", "hass", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "FLO_DOMAIN", ",", "{", "CONF_USERNAME", ":", "TEST_USER_ID", ",", "CONF_PASSWORD", ":", "TEST_PASSWORD", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "hass", ".", "data", "[", "FLO_DOMAIN", "]", "[", "config_entry", ".", "entry_id", "]", "[", "\"devices\"", "]", ")", "==", "1", "entity_id", "=", "\"switch.shutoff_valve\"", "assert", "hass", ".", "states", ".", "get", "(", "entity_id", ")", ".", "state", "==", "STATE_ON", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "\"turn_off\"", ",", "{", "\"entity_id\"", ":", "entity_id", "}", ",", "blocking", "=", "True", ")", "assert", "hass", ".", "states", ".", "get", "(", "entity_id", ")", ".", "state", "==", "STATE_OFF", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "\"turn_on\"", ",", "{", "\"entity_id\"", ":", "entity_id", "}", ",", "blocking", "=", "True", ")", "assert", "hass", ".", "states", ".", "get", "(", "entity_id", ")", ".", "state", "==", "STATE_ON" ]
[ 9, 0 ]
[ 30, 55 ]
python
en
['en', 'en', 'en']
True
validate_above_below
(value)
Validate that above and below can co-exist.
Validate that above and below can co-exist.
def validate_above_below(value): """Validate that above and below can co-exist.""" above = value.get(CONF_ABOVE) below = value.get(CONF_BELOW) if above is None or below is None: return value if above > below: raise vol.Invalid( f"A value can never be above {above} and below {below} at the same time. You probably want two different triggers.", ) return value
[ "def", "validate_above_below", "(", "value", ")", ":", "above", "=", "value", ".", "get", "(", "CONF_ABOVE", ")", "below", "=", "value", ".", "get", "(", "CONF_BELOW", ")", "if", "above", "is", "None", "or", "below", "is", "None", ":", "return", "value", "if", "above", ">", "below", ":", "raise", "vol", ".", "Invalid", "(", "f\"A value can never be above {above} and below {below} at the same time. You probably want two different triggers.\"", ",", ")", "return", "value" ]
[ 26, 0 ]
[ 39, 16 ]
python
en
['en', 'en', 'en']
True
async_attach_trigger
( hass, config, action, automation_info, *, platform_type="numeric_state" )
Listen for state changes based on configuration.
Listen for state changes based on configuration.
async def async_attach_trigger( hass, config, action, automation_info, *, platform_type="numeric_state" ) -> CALLBACK_TYPE: """Listen for state changes based on configuration.""" entity_ids = config.get(CONF_ENTITY_ID) below = config.get(CONF_BELOW) above = config.get(CONF_ABOVE) time_delta = config.get(CONF_FOR) template.attach(hass, time_delta) value_template = config.get(CONF_VALUE_TEMPLATE) unsub_track_same = {} entities_triggered = set() period: dict = {} attribute = config.get(CONF_ATTRIBUTE) job = HassJob(action) if value_template is not None: value_template.hass = hass def variables(entity_id): """Return a dict with trigger variables.""" return { "trigger": { "platform": "numeric_state", "entity_id": entity_id, "below": below, "above": above, "attribute": attribute, } } @callback def check_numeric_state(entity_id, from_s, to_s): """Return True if criteria are now met.""" if to_s is None: return False return condition.async_numeric_state( hass, to_s, below, above, value_template, variables(entity_id), attribute ) @callback def state_automation_listener(event): """Listen for state changes and calls action.""" entity_id = event.data.get("entity_id") from_s = event.data.get("old_state") to_s = event.data.get("new_state") @callback def call_action(): """Call action with right context.""" hass.async_run_hass_job( job, { "trigger": { "platform": platform_type, "entity_id": entity_id, "below": below, "above": above, "from_state": from_s, "to_state": to_s, "for": time_delta if not time_delta else period[entity_id], "description": f"numeric state of {entity_id}", } }, to_s.context, ) matching = check_numeric_state(entity_id, from_s, to_s) if not matching: entities_triggered.discard(entity_id) elif entity_id not in entities_triggered: entities_triggered.add(entity_id) if time_delta: try: period[entity_id] = cv.positive_time_period( template.render_complex(time_delta, variables(entity_id)) ) except (exceptions.TemplateError, vol.Invalid) as ex: _LOGGER.error( "Error rendering '%s' for template: %s", automation_info["name"], ex, ) entities_triggered.discard(entity_id) return unsub_track_same[entity_id] = async_track_same_state( hass, period[entity_id], call_action, entity_ids=entity_id, async_check_same_func=check_numeric_state, ) else: call_action() unsub = async_track_state_change_event(hass, entity_ids, state_automation_listener) @callback def async_remove(): """Remove state listeners async.""" unsub() for async_remove in unsub_track_same.values(): async_remove() unsub_track_same.clear() return async_remove
[ "async", "def", "async_attach_trigger", "(", "hass", ",", "config", ",", "action", ",", "automation_info", ",", "*", ",", "platform_type", "=", "\"numeric_state\"", ")", "->", "CALLBACK_TYPE", ":", "entity_ids", "=", "config", ".", "get", "(", "CONF_ENTITY_ID", ")", "below", "=", "config", ".", "get", "(", "CONF_BELOW", ")", "above", "=", "config", ".", "get", "(", "CONF_ABOVE", ")", "time_delta", "=", "config", ".", "get", "(", "CONF_FOR", ")", "template", ".", "attach", "(", "hass", ",", "time_delta", ")", "value_template", "=", "config", ".", "get", "(", "CONF_VALUE_TEMPLATE", ")", "unsub_track_same", "=", "{", "}", "entities_triggered", "=", "set", "(", ")", "period", ":", "dict", "=", "{", "}", "attribute", "=", "config", ".", "get", "(", "CONF_ATTRIBUTE", ")", "job", "=", "HassJob", "(", "action", ")", "if", "value_template", "is", "not", "None", ":", "value_template", ".", "hass", "=", "hass", "def", "variables", "(", "entity_id", ")", ":", "\"\"\"Return a dict with trigger variables.\"\"\"", "return", "{", "\"trigger\"", ":", "{", "\"platform\"", ":", "\"numeric_state\"", ",", "\"entity_id\"", ":", "entity_id", ",", "\"below\"", ":", "below", ",", "\"above\"", ":", "above", ",", "\"attribute\"", ":", "attribute", ",", "}", "}", "@", "callback", "def", "check_numeric_state", "(", "entity_id", ",", "from_s", ",", "to_s", ")", ":", "\"\"\"Return True if criteria are now met.\"\"\"", "if", "to_s", "is", "None", ":", "return", "False", "return", "condition", ".", "async_numeric_state", "(", "hass", ",", "to_s", ",", "below", ",", "above", ",", "value_template", ",", "variables", "(", "entity_id", ")", ",", "attribute", ")", "@", "callback", "def", "state_automation_listener", "(", "event", ")", ":", "\"\"\"Listen for state changes and calls action.\"\"\"", "entity_id", "=", "event", ".", "data", ".", "get", "(", "\"entity_id\"", ")", "from_s", "=", "event", ".", "data", ".", "get", "(", "\"old_state\"", ")", "to_s", "=", "event", ".", "data", ".", "get", "(", "\"new_state\"", ")", "@", "callback", "def", "call_action", "(", ")", ":", "\"\"\"Call action with right context.\"\"\"", "hass", ".", "async_run_hass_job", "(", "job", ",", "{", "\"trigger\"", ":", "{", "\"platform\"", ":", "platform_type", ",", "\"entity_id\"", ":", "entity_id", ",", "\"below\"", ":", "below", ",", "\"above\"", ":", "above", ",", "\"from_state\"", ":", "from_s", ",", "\"to_state\"", ":", "to_s", ",", "\"for\"", ":", "time_delta", "if", "not", "time_delta", "else", "period", "[", "entity_id", "]", ",", "\"description\"", ":", "f\"numeric state of {entity_id}\"", ",", "}", "}", ",", "to_s", ".", "context", ",", ")", "matching", "=", "check_numeric_state", "(", "entity_id", ",", "from_s", ",", "to_s", ")", "if", "not", "matching", ":", "entities_triggered", ".", "discard", "(", "entity_id", ")", "elif", "entity_id", "not", "in", "entities_triggered", ":", "entities_triggered", ".", "add", "(", "entity_id", ")", "if", "time_delta", ":", "try", ":", "period", "[", "entity_id", "]", "=", "cv", ".", "positive_time_period", "(", "template", ".", "render_complex", "(", "time_delta", ",", "variables", "(", "entity_id", ")", ")", ")", "except", "(", "exceptions", ".", "TemplateError", ",", "vol", ".", "Invalid", ")", "as", "ex", ":", "_LOGGER", ".", "error", "(", "\"Error rendering '%s' for template: %s\"", ",", "automation_info", "[", "\"name\"", "]", ",", "ex", ",", ")", "entities_triggered", ".", "discard", "(", "entity_id", ")", "return", "unsub_track_same", "[", "entity_id", "]", "=", "async_track_same_state", "(", "hass", ",", "period", "[", "entity_id", "]", ",", "call_action", ",", "entity_ids", "=", "entity_id", ",", "async_check_same_func", "=", "check_numeric_state", ",", ")", "else", ":", "call_action", "(", ")", "unsub", "=", "async_track_state_change_event", "(", "hass", ",", "entity_ids", ",", "state_automation_listener", ")", "@", "callback", "def", "async_remove", "(", ")", ":", "\"\"\"Remove state listeners async.\"\"\"", "unsub", "(", ")", "for", "async_remove", "in", "unsub_track_same", ".", "values", "(", ")", ":", "async_remove", "(", ")", "unsub_track_same", ".", "clear", "(", ")", "return", "async_remove" ]
[ 61, 0 ]
[ 170, 23 ]
python
en
['en', 'en', 'en']
True
test_zwave_ws_api
(hass, mock_openzwave, hass_ws_client)
Test Z-Wave websocket API.
Test Z-Wave websocket API.
async def test_zwave_ws_api(hass, mock_openzwave, hass_ws_client): """Test Z-Wave websocket API.""" await async_setup_component( hass, "zwave", { "zwave": { CONF_AUTOHEAL: False, CONF_USB_STICK_PATH: "/dev/zwave", CONF_POLLING_INTERVAL: 6000, CONF_NETWORK_KEY: "0xTE, 0xST, 0xTE, 0xST, 0xTE, 0xST, 0xTE, 0xST, 0xTE, 0xST, 0xTE, 0xST, 0xTE, 0xST, 0xTE, 0xST", } }, ) await hass.async_block_till_done() client = await hass_ws_client(hass) await client.send_json({ID: 5, TYPE: "zwave/get_config"}) msg = await client.receive_json() result = msg["result"] assert result[CONF_USB_STICK_PATH] == "/dev/zwave" assert not result[CONF_AUTOHEAL] assert result[CONF_POLLING_INTERVAL] == 6000 await client.send_json({ID: 6, TYPE: "zwave/get_migration_config"}) msg = await client.receive_json() result = msg["result"] assert result[CONF_USB_STICK_PATH] == "/dev/zwave" assert ( result[CONF_NETWORK_KEY] == "0xTE, 0xST, 0xTE, 0xST, 0xTE, 0xST, 0xTE, 0xST, 0xTE, 0xST, 0xTE, 0xST, 0xTE, 0xST, 0xTE, 0xST" )
[ "async", "def", "test_zwave_ws_api", "(", "hass", ",", "mock_openzwave", ",", "hass_ws_client", ")", ":", "await", "async_setup_component", "(", "hass", ",", "\"zwave\"", ",", "{", "\"zwave\"", ":", "{", "CONF_AUTOHEAL", ":", "False", ",", "CONF_USB_STICK_PATH", ":", "\"/dev/zwave\"", ",", "CONF_POLLING_INTERVAL", ":", "6000", ",", "CONF_NETWORK_KEY", ":", "\"0xTE, 0xST, 0xTE, 0xST, 0xTE, 0xST, 0xTE, 0xST, 0xTE, 0xST, 0xTE, 0xST, 0xTE, 0xST, 0xTE, 0xST\"", ",", "}", "}", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "client", "=", "await", "hass_ws_client", "(", "hass", ")", "await", "client", ".", "send_json", "(", "{", "ID", ":", "5", ",", "TYPE", ":", "\"zwave/get_config\"", "}", ")", "msg", "=", "await", "client", ".", "receive_json", "(", ")", "result", "=", "msg", "[", "\"result\"", "]", "assert", "result", "[", "CONF_USB_STICK_PATH", "]", "==", "\"/dev/zwave\"", "assert", "not", "result", "[", "CONF_AUTOHEAL", "]", "assert", "result", "[", "CONF_POLLING_INTERVAL", "]", "==", "6000", "await", "client", ".", "send_json", "(", "{", "ID", ":", "6", ",", "TYPE", ":", "\"zwave/get_migration_config\"", "}", ")", "msg", "=", "await", "client", ".", "receive_json", "(", ")", "result", "=", "msg", "[", "\"result\"", "]", "assert", "result", "[", "CONF_USB_STICK_PATH", "]", "==", "\"/dev/zwave\"", "assert", "(", "result", "[", "CONF_NETWORK_KEY", "]", "==", "\"0xTE, 0xST, 0xTE, 0xST, 0xTE, 0xST, 0xTE, 0xST, 0xTE, 0xST, 0xTE, 0xST, 0xTE, 0xST, 0xTE, 0xST\"", ")" ]
[ 11, 0 ]
[ 48, 5 ]
python
da
['en', 'da', 'it']
False
test_connection_failed_error
(mock_error, hass)
Try to connect at 127.0.0.1:5001 with socket error.
Try to connect at 127.0.0.1:5001 with socket error.
async def test_connection_failed_error(mock_error, hass): """Try to connect at 127.0.0.1:5001 with socket error.""" with assert_setup_component(4): with patch("pilight.pilight.Client", side_effect=socket.error) as mock_client: assert not await async_setup_component( hass, pilight.DOMAIN, {pilight.DOMAIN: {}} ) mock_client.assert_called_once_with( host=pilight.DEFAULT_HOST, port=pilight.DEFAULT_PORT ) assert mock_error.call_count == 1
[ "async", "def", "test_connection_failed_error", "(", "mock_error", ",", "hass", ")", ":", "with", "assert_setup_component", "(", "4", ")", ":", "with", "patch", "(", "\"pilight.pilight.Client\"", ",", "side_effect", "=", "socket", ".", "error", ")", "as", "mock_client", ":", "assert", "not", "await", "async_setup_component", "(", "hass", ",", "pilight", ".", "DOMAIN", ",", "{", "pilight", ".", "DOMAIN", ":", "{", "}", "}", ")", "mock_client", ".", "assert_called_once_with", "(", "host", "=", "pilight", ".", "DEFAULT_HOST", ",", "port", "=", "pilight", ".", "DEFAULT_PORT", ")", "assert", "mock_error", ".", "call_count", "==", "1" ]
[ 64, 0 ]
[ 74, 45 ]
python
en
['en', 'en', 'en']
True
test_connection_timeout_error
(mock_error, hass)
Try to connect at 127.0.0.1:5001 with socket timeout.
Try to connect at 127.0.0.1:5001 with socket timeout.
async def test_connection_timeout_error(mock_error, hass): """Try to connect at 127.0.0.1:5001 with socket timeout.""" with assert_setup_component(4): with patch("pilight.pilight.Client", side_effect=socket.timeout) as mock_client: assert not await async_setup_component( hass, pilight.DOMAIN, {pilight.DOMAIN: {}} ) mock_client.assert_called_once_with( host=pilight.DEFAULT_HOST, port=pilight.DEFAULT_PORT ) assert mock_error.call_count == 1
[ "async", "def", "test_connection_timeout_error", "(", "mock_error", ",", "hass", ")", ":", "with", "assert_setup_component", "(", "4", ")", ":", "with", "patch", "(", "\"pilight.pilight.Client\"", ",", "side_effect", "=", "socket", ".", "timeout", ")", "as", "mock_client", ":", "assert", "not", "await", "async_setup_component", "(", "hass", ",", "pilight", ".", "DOMAIN", ",", "{", "pilight", ".", "DOMAIN", ":", "{", "}", "}", ")", "mock_client", ".", "assert_called_once_with", "(", "host", "=", "pilight", ".", "DEFAULT_HOST", ",", "port", "=", "pilight", ".", "DEFAULT_PORT", ")", "assert", "mock_error", ".", "call_count", "==", "1" ]
[ 78, 0 ]
[ 88, 45 ]
python
en
['en', 'en', 'en']
True
test_send_code_no_protocol
(hass)
Try to send data without protocol information, should give error.
Try to send data without protocol information, should give error.
async def test_send_code_no_protocol(hass): """Try to send data without protocol information, should give error.""" with assert_setup_component(4): assert await async_setup_component(hass, pilight.DOMAIN, {pilight.DOMAIN: {}}) # Call without protocol info, should raise an error try: await hass.services.async_call( pilight.DOMAIN, pilight.SERVICE_NAME, service_data={"noprotocol": "test", "value": 42}, blocking=True, ) await hass.async_block_till_done() except MultipleInvalid as error: assert "required key not provided @ data['protocol']" in str(error)
[ "async", "def", "test_send_code_no_protocol", "(", "hass", ")", ":", "with", "assert_setup_component", "(", "4", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "pilight", ".", "DOMAIN", ",", "{", "pilight", ".", "DOMAIN", ":", "{", "}", "}", ")", "# Call without protocol info, should raise an error", "try", ":", "await", "hass", ".", "services", ".", "async_call", "(", "pilight", ".", "DOMAIN", ",", "pilight", ".", "SERVICE_NAME", ",", "service_data", "=", "{", "\"noprotocol\"", ":", "\"test\"", ",", "\"value\"", ":", "42", "}", ",", "blocking", "=", "True", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "except", "MultipleInvalid", "as", "error", ":", "assert", "\"required key not provided @ data['protocol']\"", "in", "str", "(", "error", ")" ]
[ 92, 0 ]
[ 107, 79 ]
python
en
['en', 'en', 'en']
True
test_send_code
(mock_pilight_error, hass)
Try to send proper data.
Try to send proper data.
async def test_send_code(mock_pilight_error, hass): """Try to send proper data.""" with assert_setup_component(4): assert await async_setup_component(hass, pilight.DOMAIN, {pilight.DOMAIN: {}}) # Call with protocol info, should not give error service_data = {"protocol": "test", "value": 42} await hass.services.async_call( pilight.DOMAIN, pilight.SERVICE_NAME, service_data=service_data, blocking=True, ) await hass.async_block_till_done() error_log_call = mock_pilight_error.call_args_list[-1] service_data["protocol"] = [service_data["protocol"]] assert str(service_data) in str(error_log_call)
[ "async", "def", "test_send_code", "(", "mock_pilight_error", ",", "hass", ")", ":", "with", "assert_setup_component", "(", "4", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "pilight", ".", "DOMAIN", ",", "{", "pilight", ".", "DOMAIN", ":", "{", "}", "}", ")", "# Call with protocol info, should not give error", "service_data", "=", "{", "\"protocol\"", ":", "\"test\"", ",", "\"value\"", ":", "42", "}", "await", "hass", ".", "services", ".", "async_call", "(", "pilight", ".", "DOMAIN", ",", "pilight", ".", "SERVICE_NAME", ",", "service_data", "=", "service_data", ",", "blocking", "=", "True", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "error_log_call", "=", "mock_pilight_error", ".", "call_args_list", "[", "-", "1", "]", "service_data", "[", "\"protocol\"", "]", "=", "[", "service_data", "[", "\"protocol\"", "]", "]", "assert", "str", "(", "service_data", ")", "in", "str", "(", "error_log_call", ")" ]
[ 113, 0 ]
[ 129, 55 ]
python
en
['en', 'en', 'en']
True
test_send_code_fail
(mock_pilight_error, hass)
Check IOError exception error message.
Check IOError exception error message.
async def test_send_code_fail(mock_pilight_error, hass): """Check IOError exception error message.""" with assert_setup_component(4): with patch("pilight.pilight.Client.send_code", side_effect=IOError): assert await async_setup_component( hass, pilight.DOMAIN, {pilight.DOMAIN: {}} ) # Call with protocol info, should not give error service_data = {"protocol": "test", "value": 42} await hass.services.async_call( pilight.DOMAIN, pilight.SERVICE_NAME, service_data=service_data, blocking=True, ) await hass.async_block_till_done() error_log_call = mock_pilight_error.call_args_list[-1] assert "Pilight send failed" in str(error_log_call)
[ "async", "def", "test_send_code_fail", "(", "mock_pilight_error", ",", "hass", ")", ":", "with", "assert_setup_component", "(", "4", ")", ":", "with", "patch", "(", "\"pilight.pilight.Client.send_code\"", ",", "side_effect", "=", "IOError", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "pilight", ".", "DOMAIN", ",", "{", "pilight", ".", "DOMAIN", ":", "{", "}", "}", ")", "# Call with protocol info, should not give error", "service_data", "=", "{", "\"protocol\"", ":", "\"test\"", ",", "\"value\"", ":", "42", "}", "await", "hass", ".", "services", ".", "async_call", "(", "pilight", ".", "DOMAIN", ",", "pilight", ".", "SERVICE_NAME", ",", "service_data", "=", "service_data", ",", "blocking", "=", "True", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "error_log_call", "=", "mock_pilight_error", ".", "call_args_list", "[", "-", "1", "]", "assert", "\"Pilight send failed\"", "in", "str", "(", "error_log_call", ")" ]
[ 134, 0 ]
[ 152, 63 ]
python
es
['eu', 'es', 'it']
False
test_send_code_delay
(mock_pilight_error, hass)
Try to send proper data with delay afterwards.
Try to send proper data with delay afterwards.
async def test_send_code_delay(mock_pilight_error, hass): """Try to send proper data with delay afterwards.""" with assert_setup_component(4): assert await async_setup_component( hass, pilight.DOMAIN, {pilight.DOMAIN: {pilight.CONF_SEND_DELAY: 5.0}}, ) # Call with protocol info, should not give error service_data1 = {"protocol": "test11", "value": 42} service_data2 = {"protocol": "test22", "value": 42} await hass.services.async_call( pilight.DOMAIN, pilight.SERVICE_NAME, service_data=service_data1, blocking=True, ) await hass.services.async_call( pilight.DOMAIN, pilight.SERVICE_NAME, service_data=service_data2, blocking=True, ) service_data1["protocol"] = [service_data1["protocol"]] service_data2["protocol"] = [service_data2["protocol"]] async_fire_time_changed(hass, dt_util.utcnow()) await hass.async_block_till_done() error_log_call = mock_pilight_error.call_args_list[-1] assert str(service_data1) in str(error_log_call) new_time = dt_util.utcnow() + timedelta(seconds=5) async_fire_time_changed(hass, new_time) await hass.async_block_till_done() error_log_call = mock_pilight_error.call_args_list[-1] assert str(service_data2) in str(error_log_call)
[ "async", "def", "test_send_code_delay", "(", "mock_pilight_error", ",", "hass", ")", ":", "with", "assert_setup_component", "(", "4", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "pilight", ".", "DOMAIN", ",", "{", "pilight", ".", "DOMAIN", ":", "{", "pilight", ".", "CONF_SEND_DELAY", ":", "5.0", "}", "}", ",", ")", "# Call with protocol info, should not give error", "service_data1", "=", "{", "\"protocol\"", ":", "\"test11\"", ",", "\"value\"", ":", "42", "}", "service_data2", "=", "{", "\"protocol\"", ":", "\"test22\"", ",", "\"value\"", ":", "42", "}", "await", "hass", ".", "services", ".", "async_call", "(", "pilight", ".", "DOMAIN", ",", "pilight", ".", "SERVICE_NAME", ",", "service_data", "=", "service_data1", ",", "blocking", "=", "True", ",", ")", "await", "hass", ".", "services", ".", "async_call", "(", "pilight", ".", "DOMAIN", ",", "pilight", ".", "SERVICE_NAME", ",", "service_data", "=", "service_data2", ",", "blocking", "=", "True", ",", ")", "service_data1", "[", "\"protocol\"", "]", "=", "[", "service_data1", "[", "\"protocol\"", "]", "]", "service_data2", "[", "\"protocol\"", "]", "=", "[", "service_data2", "[", "\"protocol\"", "]", "]", "async_fire_time_changed", "(", "hass", ",", "dt_util", ".", "utcnow", "(", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "error_log_call", "=", "mock_pilight_error", ".", "call_args_list", "[", "-", "1", "]", "assert", "str", "(", "service_data1", ")", "in", "str", "(", "error_log_call", ")", "new_time", "=", "dt_util", ".", "utcnow", "(", ")", "+", "timedelta", "(", "seconds", "=", "5", ")", "async_fire_time_changed", "(", "hass", ",", "new_time", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "error_log_call", "=", "mock_pilight_error", ".", "call_args_list", "[", "-", "1", "]", "assert", "str", "(", "service_data2", ")", "in", "str", "(", "error_log_call", ")" ]
[ 158, 0 ]
[ 194, 56 ]
python
en
['en', 'en', 'en']
True
test_start_stop
(mock_pilight_error, hass)
Check correct startup and stop of pilight daemon.
Check correct startup and stop of pilight daemon.
async def test_start_stop(mock_pilight_error, hass): """Check correct startup and stop of pilight daemon.""" with assert_setup_component(4): assert await async_setup_component(hass, pilight.DOMAIN, {pilight.DOMAIN: {}}) # Test startup await hass.async_start() await hass.async_block_till_done() error_log_call = mock_pilight_error.call_args_list[-2] assert "PilightDaemonSim callback" in str(error_log_call) error_log_call = mock_pilight_error.call_args_list[-1] assert "PilightDaemonSim start" in str(error_log_call) # Test stop with patch.object(hass.loop, "stop"): await hass.async_stop() error_log_call = mock_pilight_error.call_args_list[-1] assert "PilightDaemonSim stop" in str(error_log_call)
[ "async", "def", "test_start_stop", "(", "mock_pilight_error", ",", "hass", ")", ":", "with", "assert_setup_component", "(", "4", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "pilight", ".", "DOMAIN", ",", "{", "pilight", ".", "DOMAIN", ":", "{", "}", "}", ")", "# Test startup", "await", "hass", ".", "async_start", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "error_log_call", "=", "mock_pilight_error", ".", "call_args_list", "[", "-", "2", "]", "assert", "\"PilightDaemonSim callback\"", "in", "str", "(", "error_log_call", ")", "error_log_call", "=", "mock_pilight_error", ".", "call_args_list", "[", "-", "1", "]", "assert", "\"PilightDaemonSim start\"", "in", "str", "(", "error_log_call", ")", "# Test stop", "with", "patch", ".", "object", "(", "hass", ".", "loop", ",", "\"stop\"", ")", ":", "await", "hass", ".", "async_stop", "(", ")", "error_log_call", "=", "mock_pilight_error", ".", "call_args_list", "[", "-", "1", "]", "assert", "\"PilightDaemonSim stop\"", "in", "str", "(", "error_log_call", ")" ]
[ 200, 0 ]
[ 218, 61 ]
python
en
['en', 'en', 'en']
True
test_receive_code
(mock_debug, hass)
Check if code receiving via pilight daemon works.
Check if code receiving via pilight daemon works.
async def test_receive_code(mock_debug, hass): """Check if code receiving via pilight daemon works.""" with assert_setup_component(4): assert await async_setup_component(hass, pilight.DOMAIN, {pilight.DOMAIN: {}}) # Test startup await hass.async_start() await hass.async_block_till_done() expected_message = dict( { "protocol": PilightDaemonSim.test_message["protocol"], "uuid": PilightDaemonSim.test_message["uuid"], }, **PilightDaemonSim.test_message["message"], ) debug_log_call = mock_debug.call_args_list[-3] # Check if all message parts are put on event bus for key, value in expected_message.items(): assert str(key) in str(debug_log_call) assert str(value) in str(debug_log_call)
[ "async", "def", "test_receive_code", "(", "mock_debug", ",", "hass", ")", ":", "with", "assert_setup_component", "(", "4", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "pilight", ".", "DOMAIN", ",", "{", "pilight", ".", "DOMAIN", ":", "{", "}", "}", ")", "# Test startup", "await", "hass", ".", "async_start", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "expected_message", "=", "dict", "(", "{", "\"protocol\"", ":", "PilightDaemonSim", ".", "test_message", "[", "\"protocol\"", "]", ",", "\"uuid\"", ":", "PilightDaemonSim", ".", "test_message", "[", "\"uuid\"", "]", ",", "}", ",", "*", "*", "PilightDaemonSim", ".", "test_message", "[", "\"message\"", "]", ",", ")", "debug_log_call", "=", "mock_debug", ".", "call_args_list", "[", "-", "3", "]", "# Check if all message parts are put on event bus", "for", "key", ",", "value", "in", "expected_message", ".", "items", "(", ")", ":", "assert", "str", "(", "key", ")", "in", "str", "(", "debug_log_call", ")", "assert", "str", "(", "value", ")", "in", "str", "(", "debug_log_call", ")" ]
[ 223, 0 ]
[ 244, 52 ]
python
en
['nl', 'en', 'en']
True
test_whitelist_exact_match
(mock_debug, hass)
Check whitelist filter with matched data.
Check whitelist filter with matched data.
async def test_whitelist_exact_match(mock_debug, hass): """Check whitelist filter with matched data.""" with assert_setup_component(4): whitelist = { "protocol": [PilightDaemonSim.test_message["protocol"]], "uuid": [PilightDaemonSim.test_message["uuid"]], "id": [PilightDaemonSim.test_message["message"]["id"]], "unit": [PilightDaemonSim.test_message["message"]["unit"]], } assert await async_setup_component( hass, pilight.DOMAIN, {pilight.DOMAIN: {"whitelist": whitelist}} ) await hass.async_start() await hass.async_block_till_done() expected_message = dict( { "protocol": PilightDaemonSim.test_message["protocol"], "uuid": PilightDaemonSim.test_message["uuid"], }, **PilightDaemonSim.test_message["message"], ) debug_log_call = mock_debug.call_args_list[-3] # Check if all message parts are put on event bus for key, value in expected_message.items(): assert str(key) in str(debug_log_call) assert str(value) in str(debug_log_call)
[ "async", "def", "test_whitelist_exact_match", "(", "mock_debug", ",", "hass", ")", ":", "with", "assert_setup_component", "(", "4", ")", ":", "whitelist", "=", "{", "\"protocol\"", ":", "[", "PilightDaemonSim", ".", "test_message", "[", "\"protocol\"", "]", "]", ",", "\"uuid\"", ":", "[", "PilightDaemonSim", ".", "test_message", "[", "\"uuid\"", "]", "]", ",", "\"id\"", ":", "[", "PilightDaemonSim", ".", "test_message", "[", "\"message\"", "]", "[", "\"id\"", "]", "]", ",", "\"unit\"", ":", "[", "PilightDaemonSim", ".", "test_message", "[", "\"message\"", "]", "[", "\"unit\"", "]", "]", ",", "}", "assert", "await", "async_setup_component", "(", "hass", ",", "pilight", ".", "DOMAIN", ",", "{", "pilight", ".", "DOMAIN", ":", "{", "\"whitelist\"", ":", "whitelist", "}", "}", ")", "await", "hass", ".", "async_start", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "expected_message", "=", "dict", "(", "{", "\"protocol\"", ":", "PilightDaemonSim", ".", "test_message", "[", "\"protocol\"", "]", ",", "\"uuid\"", ":", "PilightDaemonSim", ".", "test_message", "[", "\"uuid\"", "]", ",", "}", ",", "*", "*", "PilightDaemonSim", ".", "test_message", "[", "\"message\"", "]", ",", ")", "debug_log_call", "=", "mock_debug", ".", "call_args_list", "[", "-", "3", "]", "# Check if all message parts are put on event bus", "for", "key", ",", "value", "in", "expected_message", ".", "items", "(", ")", ":", "assert", "str", "(", "key", ")", "in", "str", "(", "debug_log_call", ")", "assert", "str", "(", "value", ")", "in", "str", "(", "debug_log_call", ")" ]
[ 249, 0 ]
[ 277, 52 ]
python
en
['en', 'en', 'en']
True
test_whitelist_partial_match
(mock_debug, hass)
Check whitelist filter with partially matched data, should work.
Check whitelist filter with partially matched data, should work.
async def test_whitelist_partial_match(mock_debug, hass): """Check whitelist filter with partially matched data, should work.""" with assert_setup_component(4): whitelist = { "protocol": [PilightDaemonSim.test_message["protocol"]], "id": [PilightDaemonSim.test_message["message"]["id"]], } assert await async_setup_component( hass, pilight.DOMAIN, {pilight.DOMAIN: {"whitelist": whitelist}} ) await hass.async_start() await hass.async_block_till_done() expected_message = dict( { "protocol": PilightDaemonSim.test_message["protocol"], "uuid": PilightDaemonSim.test_message["uuid"], }, **PilightDaemonSim.test_message["message"], ) debug_log_call = mock_debug.call_args_list[-3] # Check if all message parts are put on event bus for key, value in expected_message.items(): assert str(key) in str(debug_log_call) assert str(value) in str(debug_log_call)
[ "async", "def", "test_whitelist_partial_match", "(", "mock_debug", ",", "hass", ")", ":", "with", "assert_setup_component", "(", "4", ")", ":", "whitelist", "=", "{", "\"protocol\"", ":", "[", "PilightDaemonSim", ".", "test_message", "[", "\"protocol\"", "]", "]", ",", "\"id\"", ":", "[", "PilightDaemonSim", ".", "test_message", "[", "\"message\"", "]", "[", "\"id\"", "]", "]", ",", "}", "assert", "await", "async_setup_component", "(", "hass", ",", "pilight", ".", "DOMAIN", ",", "{", "pilight", ".", "DOMAIN", ":", "{", "\"whitelist\"", ":", "whitelist", "}", "}", ")", "await", "hass", ".", "async_start", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "expected_message", "=", "dict", "(", "{", "\"protocol\"", ":", "PilightDaemonSim", ".", "test_message", "[", "\"protocol\"", "]", ",", "\"uuid\"", ":", "PilightDaemonSim", ".", "test_message", "[", "\"uuid\"", "]", ",", "}", ",", "*", "*", "PilightDaemonSim", ".", "test_message", "[", "\"message\"", "]", ",", ")", "debug_log_call", "=", "mock_debug", ".", "call_args_list", "[", "-", "3", "]", "# Check if all message parts are put on event bus", "for", "key", ",", "value", "in", "expected_message", ".", "items", "(", ")", ":", "assert", "str", "(", "key", ")", "in", "str", "(", "debug_log_call", ")", "assert", "str", "(", "value", ")", "in", "str", "(", "debug_log_call", ")" ]
[ 282, 0 ]
[ 308, 52 ]
python
en
['en', 'en', 'en']
True
test_whitelist_or_match
(mock_debug, hass)
Check whitelist filter with several subsection, should work.
Check whitelist filter with several subsection, should work.
async def test_whitelist_or_match(mock_debug, hass): """Check whitelist filter with several subsection, should work.""" with assert_setup_component(4): whitelist = { "protocol": [ PilightDaemonSim.test_message["protocol"], "other_protocol", ], "id": [PilightDaemonSim.test_message["message"]["id"]], } assert await async_setup_component( hass, pilight.DOMAIN, {pilight.DOMAIN: {"whitelist": whitelist}} ) await hass.async_start() await hass.async_block_till_done() expected_message = dict( { "protocol": PilightDaemonSim.test_message["protocol"], "uuid": PilightDaemonSim.test_message["uuid"], }, **PilightDaemonSim.test_message["message"], ) debug_log_call = mock_debug.call_args_list[-3] # Check if all message parts are put on event bus for key, value in expected_message.items(): assert str(key) in str(debug_log_call) assert str(value) in str(debug_log_call)
[ "async", "def", "test_whitelist_or_match", "(", "mock_debug", ",", "hass", ")", ":", "with", "assert_setup_component", "(", "4", ")", ":", "whitelist", "=", "{", "\"protocol\"", ":", "[", "PilightDaemonSim", ".", "test_message", "[", "\"protocol\"", "]", ",", "\"other_protocol\"", ",", "]", ",", "\"id\"", ":", "[", "PilightDaemonSim", ".", "test_message", "[", "\"message\"", "]", "[", "\"id\"", "]", "]", ",", "}", "assert", "await", "async_setup_component", "(", "hass", ",", "pilight", ".", "DOMAIN", ",", "{", "pilight", ".", "DOMAIN", ":", "{", "\"whitelist\"", ":", "whitelist", "}", "}", ")", "await", "hass", ".", "async_start", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "expected_message", "=", "dict", "(", "{", "\"protocol\"", ":", "PilightDaemonSim", ".", "test_message", "[", "\"protocol\"", "]", ",", "\"uuid\"", ":", "PilightDaemonSim", ".", "test_message", "[", "\"uuid\"", "]", ",", "}", ",", "*", "*", "PilightDaemonSim", ".", "test_message", "[", "\"message\"", "]", ",", ")", "debug_log_call", "=", "mock_debug", ".", "call_args_list", "[", "-", "3", "]", "# Check if all message parts are put on event bus", "for", "key", ",", "value", "in", "expected_message", ".", "items", "(", ")", ":", "assert", "str", "(", "key", ")", "in", "str", "(", "debug_log_call", ")", "assert", "str", "(", "value", ")", "in", "str", "(", "debug_log_call", ")" ]
[ 313, 0 ]
[ 342, 52 ]
python
en
['en', 'en', 'en']
True