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
list
start_point
list
end_point
list
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
test_tv_supported_features
( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker )
Test supported features for Roku TV.
Test supported features for Roku TV.
async def test_tv_supported_features( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker ) -> None: """Test supported features for Roku TV.""" await setup_integration( hass, aioclient_mock, device="rokutv", app="tvinput-dtv", host=TV_HOST, unique_id=TV_SERIAL, ) state = hass.states.get(TV_ENTITY_ID) assert ( SUPPORT_PREVIOUS_TRACK | SUPPORT_NEXT_TRACK | SUPPORT_VOLUME_STEP | SUPPORT_VOLUME_MUTE | SUPPORT_SELECT_SOURCE | SUPPORT_PAUSE | SUPPORT_PLAY | SUPPORT_PLAY_MEDIA | SUPPORT_TURN_ON | SUPPORT_TURN_OFF | SUPPORT_BROWSE_MEDIA == state.attributes.get("supported_features") )
[ "async", "def", "test_tv_supported_features", "(", "hass", ":", "HomeAssistantType", ",", "aioclient_mock", ":", "AiohttpClientMocker", ")", "->", "None", ":", "await", "setup_integration", "(", "hass", ",", "aioclient_mock", ",", "device", "=", "\"rokutv\"", ",", ...
[ 172, 0 ]
[ 199, 5 ]
python
en
['en', 'en', 'en']
True
test_attributes
( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker )
Test attributes.
Test attributes.
async def test_attributes( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker ) -> None: """Test attributes.""" await setup_integration(hass, aioclient_mock) state = hass.states.get(MAIN_ENTITY_ID) assert state.state == STATE_HOME assert state.attributes.get(ATTR_MEDIA_CONTENT_TYPE) is None assert state.attributes.get(ATTR_APP_ID) is None assert state.attributes.get(ATTR_APP_NAME) == "Roku" assert state.attributes.get(ATTR_INPUT_SOURCE) == "Roku"
[ "async", "def", "test_attributes", "(", "hass", ":", "HomeAssistantType", ",", "aioclient_mock", ":", "AiohttpClientMocker", ")", "->", "None", ":", "await", "setup_integration", "(", "hass", ",", "aioclient_mock", ")", "state", "=", "hass", ".", "states", ".", ...
[ 202, 0 ]
[ 214, 60 ]
python
en
['en', 'la', 'en']
False
test_attributes_app
( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker )
Test attributes for app.
Test attributes for app.
async def test_attributes_app( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker ) -> None: """Test attributes for app.""" await setup_integration(hass, aioclient_mock, app="netflix") state = hass.states.get(MAIN_ENTITY_ID) assert state.state == STATE_ON assert state.attributes.get(ATTR_MEDIA_CONTENT_TYPE) == MEDIA_TYPE_APP assert state.attributes.get(ATTR_APP_ID) == "12" assert state.attributes.get(ATTR_APP_NAME) == "Netflix" assert state.attributes.get(ATTR_INPUT_SOURCE) == "Netflix"
[ "async", "def", "test_attributes_app", "(", "hass", ":", "HomeAssistantType", ",", "aioclient_mock", ":", "AiohttpClientMocker", ")", "->", "None", ":", "await", "setup_integration", "(", "hass", ",", "aioclient_mock", ",", "app", "=", "\"netflix\"", ")", "state",...
[ 217, 0 ]
[ 229, 63 ]
python
en
['en', 'en', 'en']
True
test_attributes_app_media_playing
( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker )
Test attributes for app with playing media.
Test attributes for app with playing media.
async def test_attributes_app_media_playing( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker ) -> None: """Test attributes for app with playing media.""" await setup_integration(hass, aioclient_mock, app="pluto", media_state="play") state = hass.states.get(MAIN_ENTITY_ID) assert state.state == STATE_PLAYING assert state.attributes.get(ATTR_MEDIA_CONTENT_TYPE) == MEDIA_TYPE_APP assert state.attributes.get(ATTR_MEDIA_DURATION) == 6496 assert state.attributes.get(ATTR_MEDIA_POSITION) == 38 assert state.attributes.get(ATTR_APP_ID) == "74519" assert state.attributes.get(ATTR_APP_NAME) == "Pluto TV - It's Free TV" assert state.attributes.get(ATTR_INPUT_SOURCE) == "Pluto TV - It's Free TV"
[ "async", "def", "test_attributes_app_media_playing", "(", "hass", ":", "HomeAssistantType", ",", "aioclient_mock", ":", "AiohttpClientMocker", ")", "->", "None", ":", "await", "setup_integration", "(", "hass", ",", "aioclient_mock", ",", "app", "=", "\"pluto\"", ","...
[ 232, 0 ]
[ 246, 79 ]
python
en
['en', 'en', 'en']
True
test_attributes_app_media_paused
( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker )
Test attributes for app with paused media.
Test attributes for app with paused media.
async def test_attributes_app_media_paused( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker ) -> None: """Test attributes for app with paused media.""" await setup_integration(hass, aioclient_mock, app="pluto", media_state="pause") state = hass.states.get(MAIN_ENTITY_ID) assert state.state == STATE_PAUSED assert state.attributes.get(ATTR_MEDIA_CONTENT_TYPE) == MEDIA_TYPE_APP assert state.attributes.get(ATTR_MEDIA_DURATION) == 6496 assert state.attributes.get(ATTR_MEDIA_POSITION) == 313 assert state.attributes.get(ATTR_APP_ID) == "74519" assert state.attributes.get(ATTR_APP_NAME) == "Pluto TV - It's Free TV" assert state.attributes.get(ATTR_INPUT_SOURCE) == "Pluto TV - It's Free TV"
[ "async", "def", "test_attributes_app_media_paused", "(", "hass", ":", "HomeAssistantType", ",", "aioclient_mock", ":", "AiohttpClientMocker", ")", "->", "None", ":", "await", "setup_integration", "(", "hass", ",", "aioclient_mock", ",", "app", "=", "\"pluto\"", ",",...
[ 249, 0 ]
[ 263, 79 ]
python
en
['en', 'en', 'en']
True
test_attributes_screensaver
( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker )
Test attributes for app with screensaver.
Test attributes for app with screensaver.
async def test_attributes_screensaver( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker ) -> None: """Test attributes for app with screensaver.""" await setup_integration(hass, aioclient_mock, app="screensaver") state = hass.states.get(MAIN_ENTITY_ID) assert state.state == STATE_IDLE assert state.attributes.get(ATTR_MEDIA_CONTENT_TYPE) is None assert state.attributes.get(ATTR_APP_ID) is None assert state.attributes.get(ATTR_APP_NAME) == "Roku" assert state.attributes.get(ATTR_INPUT_SOURCE) == "Roku"
[ "async", "def", "test_attributes_screensaver", "(", "hass", ":", "HomeAssistantType", ",", "aioclient_mock", ":", "AiohttpClientMocker", ")", "->", "None", ":", "await", "setup_integration", "(", "hass", ",", "aioclient_mock", ",", "app", "=", "\"screensaver\"", ")"...
[ 266, 0 ]
[ 278, 60 ]
python
en
['en', 'en', 'en']
True
test_tv_attributes
( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker )
Test attributes for Roku TV.
Test attributes for Roku TV.
async def test_tv_attributes( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker ) -> None: """Test attributes for Roku TV.""" await setup_integration( hass, aioclient_mock, device="rokutv", app="tvinput-dtv", host=TV_HOST, unique_id=TV_SERIAL, ) state = hass.states.get(TV_ENTITY_ID) assert state.state == STATE_ON assert state.attributes.get(ATTR_APP_ID) == "tvinput.dtv" assert state.attributes.get(ATTR_APP_NAME) == "Antenna TV" assert state.attributes.get(ATTR_INPUT_SOURCE) == "Antenna TV" assert state.attributes.get(ATTR_MEDIA_CONTENT_TYPE) == MEDIA_TYPE_CHANNEL assert state.attributes.get(ATTR_MEDIA_CHANNEL) == "getTV (14.3)" assert state.attributes.get(ATTR_MEDIA_TITLE) == "Airwolf"
[ "async", "def", "test_tv_attributes", "(", "hass", ":", "HomeAssistantType", ",", "aioclient_mock", ":", "AiohttpClientMocker", ")", "->", "None", ":", "await", "setup_integration", "(", "hass", ",", "aioclient_mock", ",", "device", "=", "\"rokutv\"", ",", "app", ...
[ 281, 0 ]
[ 302, 62 ]
python
en
['en', 'en', 'en']
True
test_services
( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker )
Test the different media player services.
Test the different media player services.
async def test_services( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker ) -> None: """Test the different media player services.""" await setup_integration(hass, aioclient_mock) with patch("homeassistant.components.roku.Roku.remote") as remote_mock: await hass.services.async_call( MP_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: MAIN_ENTITY_ID}, blocking=True ) remote_mock.assert_called_once_with("poweroff") with patch("homeassistant.components.roku.Roku.remote") as remote_mock: await hass.services.async_call( MP_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: MAIN_ENTITY_ID}, blocking=True ) remote_mock.assert_called_once_with("poweron") with patch("homeassistant.components.roku.Roku.remote") as remote_mock: await hass.services.async_call( MP_DOMAIN, SERVICE_MEDIA_PAUSE, {ATTR_ENTITY_ID: MAIN_ENTITY_ID}, blocking=True, ) remote_mock.assert_called_once_with("play") with patch("homeassistant.components.roku.Roku.remote") as remote_mock: await hass.services.async_call( MP_DOMAIN, SERVICE_MEDIA_PLAY, {ATTR_ENTITY_ID: MAIN_ENTITY_ID}, blocking=True, ) remote_mock.assert_called_once_with("play") with patch("homeassistant.components.roku.Roku.remote") as remote_mock: await hass.services.async_call( MP_DOMAIN, SERVICE_MEDIA_PLAY_PAUSE, {ATTR_ENTITY_ID: MAIN_ENTITY_ID}, blocking=True, ) remote_mock.assert_called_once_with("play") with patch("homeassistant.components.roku.Roku.remote") as remote_mock: await hass.services.async_call( MP_DOMAIN, SERVICE_MEDIA_NEXT_TRACK, {ATTR_ENTITY_ID: MAIN_ENTITY_ID}, blocking=True, ) remote_mock.assert_called_once_with("forward") with patch("homeassistant.components.roku.Roku.remote") as remote_mock: await hass.services.async_call( MP_DOMAIN, SERVICE_MEDIA_PREVIOUS_TRACK, {ATTR_ENTITY_ID: MAIN_ENTITY_ID}, blocking=True, ) remote_mock.assert_called_once_with("reverse") with patch("homeassistant.components.roku.Roku.launch") as launch_mock: await hass.services.async_call( MP_DOMAIN, SERVICE_PLAY_MEDIA, { ATTR_ENTITY_ID: MAIN_ENTITY_ID, ATTR_MEDIA_CONTENT_TYPE: MEDIA_TYPE_APP, ATTR_MEDIA_CONTENT_ID: "11", }, blocking=True, ) launch_mock.assert_called_once_with("11") with patch("homeassistant.components.roku.Roku.remote") as remote_mock: await hass.services.async_call( MP_DOMAIN, SERVICE_SELECT_SOURCE, {ATTR_ENTITY_ID: MAIN_ENTITY_ID, ATTR_INPUT_SOURCE: "Home"}, blocking=True, ) remote_mock.assert_called_once_with("home") with patch("homeassistant.components.roku.Roku.launch") as launch_mock: await hass.services.async_call( MP_DOMAIN, SERVICE_SELECT_SOURCE, {ATTR_ENTITY_ID: MAIN_ENTITY_ID, ATTR_INPUT_SOURCE: "Netflix"}, blocking=True, ) launch_mock.assert_called_once_with("12") with patch("homeassistant.components.roku.Roku.launch") as launch_mock: await hass.services.async_call( MP_DOMAIN, SERVICE_SELECT_SOURCE, {ATTR_ENTITY_ID: MAIN_ENTITY_ID, ATTR_INPUT_SOURCE: 12}, blocking=True, ) launch_mock.assert_called_once_with("12")
[ "async", "def", "test_services", "(", "hass", ":", "HomeAssistantType", ",", "aioclient_mock", ":", "AiohttpClientMocker", ")", "->", "None", ":", "await", "setup_integration", "(", "hass", ",", "aioclient_mock", ")", "with", "patch", "(", "\"homeassistant.component...
[ 305, 0 ]
[ 417, 49 ]
python
en
['en', 'en', 'en']
True
test_tv_services
( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker )
Test the media player services related to Roku TV.
Test the media player services related to Roku TV.
async def test_tv_services( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker ) -> None: """Test the media player services related to Roku TV.""" await setup_integration( hass, aioclient_mock, device="rokutv", app="tvinput-dtv", host=TV_HOST, unique_id=TV_SERIAL, ) with patch("homeassistant.components.roku.Roku.remote") as remote_mock: await hass.services.async_call( MP_DOMAIN, SERVICE_VOLUME_UP, {ATTR_ENTITY_ID: TV_ENTITY_ID}, blocking=True ) remote_mock.assert_called_once_with("volume_up") with patch("homeassistant.components.roku.Roku.remote") as remote_mock: await hass.services.async_call( MP_DOMAIN, SERVICE_VOLUME_DOWN, {ATTR_ENTITY_ID: TV_ENTITY_ID}, blocking=True, ) remote_mock.assert_called_once_with("volume_down") with patch("homeassistant.components.roku.Roku.remote") as remote_mock: await hass.services.async_call( MP_DOMAIN, SERVICE_VOLUME_MUTE, {ATTR_ENTITY_ID: TV_ENTITY_ID, ATTR_MEDIA_VOLUME_MUTED: True}, blocking=True, ) remote_mock.assert_called_once_with("volume_mute") with patch("homeassistant.components.roku.Roku.tune") as tune_mock: await hass.services.async_call( MP_DOMAIN, SERVICE_PLAY_MEDIA, { ATTR_ENTITY_ID: TV_ENTITY_ID, ATTR_MEDIA_CONTENT_TYPE: MEDIA_TYPE_CHANNEL, ATTR_MEDIA_CONTENT_ID: "55", }, blocking=True, ) tune_mock.assert_called_once_with("55")
[ "async", "def", "test_tv_services", "(", "hass", ":", "HomeAssistantType", ",", "aioclient_mock", ":", "AiohttpClientMocker", ")", "->", "None", ":", "await", "setup_integration", "(", "hass", ",", "aioclient_mock", ",", "device", "=", "\"rokutv\"", ",", "app", ...
[ 420, 0 ]
[ 472, 47 ]
python
en
['en', 'en', 'en']
True
test_media_browse
(hass, aioclient_mock, hass_ws_client)
Test browsing media.
Test browsing media.
async def test_media_browse(hass, aioclient_mock, hass_ws_client): """Test browsing media.""" await setup_integration( hass, aioclient_mock, device="rokutv", app="tvinput-dtv", host=TV_HOST, unique_id=TV_SERIAL, ) client = await hass_ws_client(hass) await client.send_json( { "id": 1, "type": "media_player/browse_media", "entity_id": TV_ENTITY_ID, } ) msg = await client.receive_json() assert msg["id"] == 1 assert msg["type"] == TYPE_RESULT assert msg["success"] assert msg["result"] assert msg["result"]["title"] == "Media Library" assert msg["result"]["media_class"] == MEDIA_CLASS_DIRECTORY assert msg["result"]["media_content_type"] == "library" assert msg["result"]["can_expand"] assert not msg["result"]["can_play"] assert len(msg["result"]["children"]) == 2 # test apps await client.send_json( { "id": 2, "type": "media_player/browse_media", "entity_id": TV_ENTITY_ID, "media_content_type": MEDIA_TYPE_APPS, "media_content_id": "apps", } ) msg = await client.receive_json() assert msg["id"] == 2 assert msg["type"] == TYPE_RESULT assert msg["success"] assert msg["result"] assert msg["result"]["title"] == "Apps" assert msg["result"]["media_class"] == MEDIA_CLASS_DIRECTORY assert msg["result"]["media_content_type"] == MEDIA_TYPE_APPS assert msg["result"]["children_media_class"] == MEDIA_CLASS_APP assert msg["result"]["can_expand"] assert not msg["result"]["can_play"] assert len(msg["result"]["children"]) == 11 assert msg["result"]["children_media_class"] == MEDIA_CLASS_APP assert msg["result"]["children"][0]["title"] == "Satellite TV" assert msg["result"]["children"][0]["media_content_type"] == MEDIA_TYPE_APP assert msg["result"]["children"][0]["media_content_id"] == "tvinput.hdmi2" assert ( "/browse_media/app/tvinput.hdmi2" in msg["result"]["children"][0]["thumbnail"] ) assert msg["result"]["children"][0]["can_play"] assert msg["result"]["children"][3]["title"] == "Roku Channel Store" assert msg["result"]["children"][3]["media_content_type"] == MEDIA_TYPE_APP assert msg["result"]["children"][3]["media_content_id"] == "11" assert "/browse_media/app/11" in msg["result"]["children"][3]["thumbnail"] assert msg["result"]["children"][3]["can_play"] # test channels await client.send_json( { "id": 3, "type": "media_player/browse_media", "entity_id": TV_ENTITY_ID, "media_content_type": MEDIA_TYPE_CHANNELS, "media_content_id": "channels", } ) msg = await client.receive_json() assert msg["id"] == 3 assert msg["type"] == TYPE_RESULT assert msg["success"] assert msg["result"] assert msg["result"]["title"] == "Channels" assert msg["result"]["media_class"] == MEDIA_CLASS_DIRECTORY assert msg["result"]["media_content_type"] == MEDIA_TYPE_CHANNELS assert msg["result"]["children_media_class"] == MEDIA_CLASS_CHANNEL assert msg["result"]["can_expand"] assert not msg["result"]["can_play"] assert len(msg["result"]["children"]) == 2 assert msg["result"]["children_media_class"] == MEDIA_CLASS_CHANNEL assert msg["result"]["children"][0]["title"] == "WhatsOn" assert msg["result"]["children"][0]["media_content_type"] == MEDIA_TYPE_CHANNEL assert msg["result"]["children"][0]["media_content_id"] == "1.1" assert msg["result"]["children"][0]["can_play"] # test invalid media type await client.send_json( { "id": 4, "type": "media_player/browse_media", "entity_id": TV_ENTITY_ID, "media_content_type": "invalid", "media_content_id": "invalid", } ) msg = await client.receive_json() assert msg["id"] == 4 assert msg["type"] == TYPE_RESULT assert not msg["success"]
[ "async", "def", "test_media_browse", "(", "hass", ",", "aioclient_mock", ",", "hass_ws_client", ")", ":", "await", "setup_integration", "(", "hass", ",", "aioclient_mock", ",", "device", "=", "\"rokutv\"", ",", "app", "=", "\"tvinput-dtv\"", ",", "host", "=", ...
[ 475, 0 ]
[ 598, 29 ]
python
en
['en', 'jv', 'en']
True
test_integration_services
( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker )
Test integration services.
Test integration services.
async def test_integration_services( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker ) -> None: """Test integration services.""" await setup_integration(hass, aioclient_mock) with patch("homeassistant.components.roku.Roku.search") as search_mock: await hass.services.async_call( DOMAIN, SERVICE_SEARCH, {ATTR_ENTITY_ID: MAIN_ENTITY_ID, ATTR_KEYWORD: "Space Jam"}, blocking=True, ) search_mock.assert_called_once_with("Space Jam")
[ "async", "def", "test_integration_services", "(", "hass", ":", "HomeAssistantType", ",", "aioclient_mock", ":", "AiohttpClientMocker", ")", "->", "None", ":", "await", "setup_integration", "(", "hass", ",", "aioclient_mock", ")", "with", "patch", "(", "\"homeassista...
[ 601, 0 ]
[ 614, 56 ]
python
en
['en', 'da', 'en']
True
get_service
(hass, config, discovery_info=None)
Get the Notify.Events notification service.
Get the Notify.Events notification service.
def get_service(hass, config, discovery_info=None): """Get the Notify.Events notification service.""" return NotifyEventsNotificationService(hass.data[DOMAIN][CONF_TOKEN])
[ "def", "get_service", "(", "hass", ",", "config", ",", "discovery_info", "=", "None", ")", ":", "return", "NotifyEventsNotificationService", "(", "hass", ".", "data", "[", "DOMAIN", "]", "[", "CONF_TOKEN", "]", ")" ]
[ 33, 0 ]
[ 35, 73 ]
python
en
['en', 'en', 'en']
True
NotifyEventsNotificationService.__init__
(self, token)
Initialize the service.
Initialize the service.
def __init__(self, token): """Initialize the service.""" self.token = token
[ "def", "__init__", "(", "self", ",", "token", ")", ":", "self", ".", "token", "=", "token" ]
[ 41, 4 ]
[ 43, 26 ]
python
en
['en', 'en', 'en']
True
NotifyEventsNotificationService.file_exists
(self, filename)
Check if a file exists on disk and is in authorized path.
Check if a file exists on disk and is in authorized path.
def file_exists(self, filename) -> bool: """Check if a file exists on disk and is in authorized path.""" if not self.hass.config.is_allowed_path(filename): return False return os.path.isfile(filename)
[ "def", "file_exists", "(", "self", ",", "filename", ")", "->", "bool", ":", "if", "not", "self", ".", "hass", ".", "config", ".", "is_allowed_path", "(", "filename", ")", ":", "return", "False", "return", "os", ".", "path", ".", "isfile", "(", "filenam...
[ 45, 4 ]
[ 49, 39 ]
python
en
['en', 'en', 'en']
True
NotifyEventsNotificationService.attach_file
(self, msg: Message, item: dict, kind: str = ATTR_FILE_KIND_FILE)
Append a file or image to message.
Append a file or image to message.
def attach_file(self, msg: Message, item: dict, kind: str = ATTR_FILE_KIND_FILE): """Append a file or image to message.""" file_name = None mime_type = None if ATTR_FILE_NAME in item: file_name = item[ATTR_FILE_NAME] if ATTR_FILE_MIME_TYPE in item: mime_type = item[ATTR_FILE_MIME_TYPE] if ATTR_FILE_URL in item: if kind == ATTR_FILE_KIND_IMAGE: msg.add_image_from_url(item[ATTR_FILE_URL], file_name, mime_type) else: msg.add_file_from_url(item[ATTR_FILE_URL], file_name, mime_type) elif ATTR_FILE_CONTENT in item: if kind == ATTR_FILE_KIND_IMAGE: msg.add_image_from_content( item[ATTR_FILE_CONTENT], file_name, mime_type ) else: msg.add_file_from_content(item[ATTR_FILE_CONTENT], file_name, mime_type) elif ATTR_FILE_PATH in item: file_exists = self.file_exists(item[ATTR_FILE_PATH]) if file_exists: if kind == ATTR_FILE_KIND_IMAGE: msg.add_image(item[ATTR_FILE_PATH], file_name, mime_type) else: msg.add_file(item[ATTR_FILE_PATH], file_name, mime_type) else: _LOGGER.error("File does not exist: %s", item[ATTR_FILE_PATH])
[ "def", "attach_file", "(", "self", ",", "msg", ":", "Message", ",", "item", ":", "dict", ",", "kind", ":", "str", "=", "ATTR_FILE_KIND_FILE", ")", ":", "file_name", "=", "None", "mime_type", "=", "None", "if", "ATTR_FILE_NAME", "in", "item", ":", "file_n...
[ 51, 4 ]
[ 83, 78 ]
python
en
['en', 'en', 'en']
True
NotifyEventsNotificationService.prepare_message
(self, message, data)
Prepare a message to send.
Prepare a message to send.
def prepare_message(self, message, data) -> Message: """Prepare a message to send.""" msg = Message(message) if ATTR_TITLE in data: msg.set_title(data[ATTR_TITLE]) if ATTR_LEVEL in data: try: msg.set_level(data[ATTR_LEVEL]) except ValueError as error: _LOGGER.warning("Setting level error: %s", error) if ATTR_PRIORITY in data: try: msg.set_priority(data[ATTR_PRIORITY]) except ValueError as error: _LOGGER.warning("Setting priority error: %s", error) if ATTR_IMAGES in data: for image in data[ATTR_IMAGES]: self.attach_file(msg, image, ATTR_FILE_KIND_IMAGE) if ATTR_FILES in data: for file in data[ATTR_FILES]: self.attach_file(msg, file) return msg
[ "def", "prepare_message", "(", "self", ",", "message", ",", "data", ")", "->", "Message", ":", "msg", "=", "Message", "(", "message", ")", "if", "ATTR_TITLE", "in", "data", ":", "msg", ".", "set_title", "(", "data", "[", "ATTR_TITLE", "]", ")", "if", ...
[ 85, 4 ]
[ 112, 18 ]
python
en
['en', 'it', 'en']
True
NotifyEventsNotificationService.send_message
(self, message, **kwargs)
Send a message.
Send a message.
def send_message(self, message, **kwargs): """Send a message.""" data = kwargs.get(ATTR_DATA) or {} msg = self.prepare_message(message, data) msg.send(self.token)
[ "def", "send_message", "(", "self", ",", "message", ",", "*", "*", "kwargs", ")", ":", "data", "=", "kwargs", ".", "get", "(", "ATTR_DATA", ")", "or", "{", "}", "msg", "=", "self", ".", "prepare_message", "(", "message", ",", "data", ")", "msg", "....
[ 114, 4 ]
[ 119, 28 ]
python
en
['en', 'lb', 'en']
True
test_allowed_sender
(hass)
Test emails from allowed sender.
Test emails from allowed sender.
async def test_allowed_sender(hass): """Test emails from allowed sender.""" test_message = email.message.Message() test_message["From"] = "sender@test.com" test_message["Subject"] = "Test" test_message["Date"] = datetime.datetime(2016, 1, 1, 12, 44, 57) test_message.set_payload("Test Message") sensor = imap_email_content.EmailContentSensor( hass, FakeEMailReader(deque([test_message])), "test_emails_sensor", ["sender@test.com"], None, ) sensor.entity_id = "sensor.emailtest" sensor.async_schedule_update_ha_state(True) await hass.async_block_till_done() assert "Test" == sensor.state assert "Test Message" == sensor.device_state_attributes["body"] assert "sender@test.com" == sensor.device_state_attributes["from"] assert "Test" == sensor.device_state_attributes["subject"] assert ( datetime.datetime(2016, 1, 1, 12, 44, 57) == sensor.device_state_attributes["date"] )
[ "async", "def", "test_allowed_sender", "(", "hass", ")", ":", "test_message", "=", "email", ".", "message", ".", "Message", "(", ")", "test_message", "[", "\"From\"", "]", "=", "\"sender@test.com\"", "test_message", "[", "\"Subject\"", "]", "=", "\"Test\"", "t...
[ 30, 0 ]
[ 56, 5 ]
python
en
['en', 'en', 'en']
True
test_multi_part_with_text
(hass)
Test multi part emails.
Test multi part emails.
async def test_multi_part_with_text(hass): """Test multi part emails.""" msg = MIMEMultipart("alternative") msg["Subject"] = "Link" msg["From"] = "sender@test.com" text = "Test Message" html = "<html><head></head><body>Test Message</body></html>" textPart = MIMEText(text, "plain") htmlPart = MIMEText(html, "html") msg.attach(textPart) msg.attach(htmlPart) sensor = imap_email_content.EmailContentSensor( hass, FakeEMailReader(deque([msg])), "test_emails_sensor", ["sender@test.com"], None, ) sensor.entity_id = "sensor.emailtest" sensor.async_schedule_update_ha_state(True) await hass.async_block_till_done() assert "Link" == sensor.state assert "Test Message" == sensor.device_state_attributes["body"]
[ "async", "def", "test_multi_part_with_text", "(", "hass", ")", ":", "msg", "=", "MIMEMultipart", "(", "\"alternative\"", ")", "msg", "[", "\"Subject\"", "]", "=", "\"Link\"", "msg", "[", "\"From\"", "]", "=", "\"sender@test.com\"", "text", "=", "\"Test Message\"...
[ 59, 0 ]
[ 86, 67 ]
python
en
['en', 'en', 'en']
True
test_multi_part_only_html
(hass)
Test multi part emails with only HTML.
Test multi part emails with only HTML.
async def test_multi_part_only_html(hass): """Test multi part emails with only HTML.""" msg = MIMEMultipart("alternative") msg["Subject"] = "Link" msg["From"] = "sender@test.com" html = "<html><head></head><body>Test Message</body></html>" htmlPart = MIMEText(html, "html") msg.attach(htmlPart) sensor = imap_email_content.EmailContentSensor( hass, FakeEMailReader(deque([msg])), "test_emails_sensor", ["sender@test.com"], None, ) sensor.entity_id = "sensor.emailtest" sensor.async_schedule_update_ha_state(True) await hass.async_block_till_done() assert "Link" == sensor.state assert ( "<html><head></head><body>Test Message</body></html>" == sensor.device_state_attributes["body"] )
[ "async", "def", "test_multi_part_only_html", "(", "hass", ")", ":", "msg", "=", "MIMEMultipart", "(", "\"alternative\"", ")", "msg", "[", "\"Subject\"", "]", "=", "\"Link\"", "msg", "[", "\"From\"", "]", "=", "\"sender@test.com\"", "html", "=", "\"<html><head></...
[ 89, 0 ]
[ 116, 5 ]
python
en
['en', 'en', 'en']
True
test_multi_part_only_other_text
(hass)
Test multi part emails with only other text.
Test multi part emails with only other text.
async def test_multi_part_only_other_text(hass): """Test multi part emails with only other text.""" msg = MIMEMultipart("alternative") msg["Subject"] = "Link" msg["From"] = "sender@test.com" other = "Test Message" htmlPart = MIMEText(other, "other") msg.attach(htmlPart) sensor = imap_email_content.EmailContentSensor( hass, FakeEMailReader(deque([msg])), "test_emails_sensor", ["sender@test.com"], None, ) sensor.entity_id = "sensor.emailtest" sensor.async_schedule_update_ha_state(True) await hass.async_block_till_done() assert "Link" == sensor.state assert "Test Message" == sensor.device_state_attributes["body"]
[ "async", "def", "test_multi_part_only_other_text", "(", "hass", ")", ":", "msg", "=", "MIMEMultipart", "(", "\"alternative\"", ")", "msg", "[", "\"Subject\"", "]", "=", "\"Link\"", "msg", "[", "\"From\"", "]", "=", "\"sender@test.com\"", "other", "=", "\"Test Me...
[ 119, 0 ]
[ 143, 67 ]
python
en
['en', 'en', 'en']
True
test_multiple_emails
(hass)
Test multiple emails.
Test multiple emails.
async def test_multiple_emails(hass): """Test multiple emails.""" states = [] test_message1 = email.message.Message() test_message1["From"] = "sender@test.com" test_message1["Subject"] = "Test" test_message1["Date"] = datetime.datetime(2016, 1, 1, 12, 44, 57) test_message1.set_payload("Test Message") test_message2 = email.message.Message() test_message2["From"] = "sender@test.com" test_message2["Subject"] = "Test 2" test_message2["Date"] = datetime.datetime(2016, 1, 1, 12, 44, 57) test_message2.set_payload("Test Message 2") def state_changed_listener(entity_id, from_s, to_s): states.append(to_s) async_track_state_change(hass, ["sensor.emailtest"], state_changed_listener) sensor = imap_email_content.EmailContentSensor( hass, FakeEMailReader(deque([test_message1, test_message2])), "test_emails_sensor", ["sender@test.com"], None, ) sensor.entity_id = "sensor.emailtest" sensor.async_schedule_update_ha_state(True) await hass.async_block_till_done() sensor.async_schedule_update_ha_state(True) await hass.async_block_till_done() assert "Test" == states[0].state assert "Test 2" == states[1].state assert "Test Message 2" == sensor.device_state_attributes["body"]
[ "async", "def", "test_multiple_emails", "(", "hass", ")", ":", "states", "=", "[", "]", "test_message1", "=", "email", ".", "message", ".", "Message", "(", ")", "test_message1", "[", "\"From\"", "]", "=", "\"sender@test.com\"", "test_message1", "[", "\"Subject...
[ 146, 0 ]
[ 185, 69 ]
python
da
['pt', 'da', 'en']
False
test_sender_not_allowed
(hass)
Test not whitelisted emails.
Test not whitelisted emails.
async def test_sender_not_allowed(hass): """Test not whitelisted emails.""" test_message = email.message.Message() test_message["From"] = "sender@test.com" test_message["Subject"] = "Test" test_message["Date"] = datetime.datetime(2016, 1, 1, 12, 44, 57) test_message.set_payload("Test Message") sensor = imap_email_content.EmailContentSensor( hass, FakeEMailReader(deque([test_message])), "test_emails_sensor", ["other@test.com"], None, ) sensor.entity_id = "sensor.emailtest" sensor.async_schedule_update_ha_state(True) await hass.async_block_till_done() assert sensor.state is None
[ "async", "def", "test_sender_not_allowed", "(", "hass", ")", ":", "test_message", "=", "email", ".", "message", ".", "Message", "(", ")", "test_message", "[", "\"From\"", "]", "=", "\"sender@test.com\"", "test_message", "[", "\"Subject\"", "]", "=", "\"Test\"", ...
[ 188, 0 ]
[ 207, 31 ]
python
en
['en', 'en', 'en']
True
test_template
(hass)
Test value template.
Test value template.
async def test_template(hass): """Test value template.""" test_message = email.message.Message() test_message["From"] = "sender@test.com" test_message["Subject"] = "Test" test_message["Date"] = datetime.datetime(2016, 1, 1, 12, 44, 57) test_message.set_payload("Test Message") sensor = imap_email_content.EmailContentSensor( hass, FakeEMailReader(deque([test_message])), "test_emails_sensor", ["sender@test.com"], Template("{{ subject }} from {{ from }} with message {{ body }}", hass), ) sensor.entity_id = "sensor.emailtest" sensor.async_schedule_update_ha_state(True) await hass.async_block_till_done() assert "Test from sender@test.com with message Test Message" == sensor.state
[ "async", "def", "test_template", "(", "hass", ")", ":", "test_message", "=", "email", ".", "message", ".", "Message", "(", ")", "test_message", "[", "\"From\"", "]", "=", "\"sender@test.com\"", "test_message", "[", "\"Subject\"", "]", "=", "\"Test\"", "test_me...
[ 210, 0 ]
[ 229, 80 ]
python
en
['nl', 'en', 'en']
True
FakeEMailReader.__init__
(self, messages)
Set up the fake email reader.
Set up the fake email reader.
def __init__(self, messages): """Set up the fake email reader.""" self._messages = messages
[ "def", "__init__", "(", "self", ",", "messages", ")", ":", "self", ".", "_messages", "=", "messages" ]
[ 15, 4 ]
[ 17, 33 ]
python
en
['en', 'en', 'en']
True
FakeEMailReader.connect
(self)
Stay always Connected.
Stay always Connected.
def connect(self): """Stay always Connected.""" return True
[ "def", "connect", "(", "self", ")", ":", "return", "True" ]
[ 19, 4 ]
[ 21, 19 ]
python
en
['en', 'en', 'en']
True
FakeEMailReader.read_next
(self)
Get the next email.
Get the next email.
def read_next(self): """Get the next email.""" if len(self._messages) == 0: return None return self._messages.popleft()
[ "def", "read_next", "(", "self", ")", ":", "if", "len", "(", "self", ".", "_messages", ")", "==", "0", ":", "return", "None", "return", "self", ".", "_messages", ".", "popleft", "(", ")" ]
[ 23, 4 ]
[ 27, 39 ]
python
en
['en', 'en', 'en']
True
test_tracking_home
(hass, mock_weather)
Test we track home.
Test we track home.
async def test_tracking_home(hass, mock_weather): """Test we track home.""" await hass.config_entries.flow.async_init("met", context={"source": "onboarding"}) await hass.async_block_till_done() assert len(hass.states.async_entity_ids("weather")) == 1 assert len(mock_weather.mock_calls) == 4 # Test the hourly sensor is disabled by default registry = await hass.helpers.entity_registry.async_get_registry() state = hass.states.get("weather.test_home_hourly") assert state is None entry = registry.async_get("weather.test_home_hourly") assert entry assert entry.disabled assert entry.disabled_by == "integration" # Test we track config await hass.config.async_update(latitude=10, longitude=20) await hass.async_block_till_done() assert len(mock_weather.mock_calls) == 8 entry = hass.config_entries.async_entries()[0] await hass.config_entries.async_remove(entry.entry_id) assert len(hass.states.async_entity_ids("weather")) == 0
[ "async", "def", "test_tracking_home", "(", "hass", ",", "mock_weather", ")", ":", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "\"met\"", ",", "context", "=", "{", "\"source\"", ":", "\"onboarding\"", "}", ")", "await", "hass"...
[ 6, 0 ]
[ 32, 60 ]
python
en
['en', 'en', 'en']
True
test_not_tracking_home
(hass, mock_weather)
Test when we not track home.
Test when we not track home.
async def test_not_tracking_home(hass, mock_weather): """Test when we not track home.""" # Pre-create registry entry for disabled by default hourly weather registry = await hass.helpers.entity_registry.async_get_registry() registry.async_get_or_create( WEATHER_DOMAIN, DOMAIN, "10-20-hourly", suggested_object_id="somewhere_hourly", disabled_by=None, ) await hass.config_entries.flow.async_init( "met", context={"source": "user"}, data={"name": "Somewhere", "latitude": 10, "longitude": 20, "elevation": 0}, ) await hass.async_block_till_done() assert len(hass.states.async_entity_ids("weather")) == 2 assert len(mock_weather.mock_calls) == 4 # Test we do not track config await hass.config.async_update(latitude=10, longitude=20) await hass.async_block_till_done() assert len(mock_weather.mock_calls) == 4 entry = hass.config_entries.async_entries()[0] await hass.config_entries.async_remove(entry.entry_id) assert len(hass.states.async_entity_ids("weather")) == 0
[ "async", "def", "test_not_tracking_home", "(", "hass", ",", "mock_weather", ")", ":", "# Pre-create registry entry for disabled by default hourly weather", "registry", "=", "await", "hass", ".", "helpers", ".", "entity_registry", ".", "async_get_registry", "(", ")", "regi...
[ 35, 0 ]
[ 65, 60 ]
python
en
['en', 'en', 'en']
True
linkcode_resolve
(domain, info)
Determine the URL corresponding to Python object.
Determine the URL corresponding to Python object.
def linkcode_resolve(domain, info): """Determine the URL corresponding to Python object.""" if domain != "py": return None modname = info["module"] fullname = info["fullname"] submod = sys.modules.get(modname) if submod is None: return None obj = submod for part in fullname.split("."): try: obj = getattr(obj, part) except: return None try: fn = inspect.getsourcefile(obj) except: fn = None if not fn: return None try: source, lineno = inspect.findsource(obj) except: lineno = None if lineno: linespec = "#L%d" % (lineno + 1) else: linespec = "" index = fn.find("/homeassistant/") if index == -1: index = 0 fn = fn[index:] return f"{GITHUB_URL}/blob/{code_branch}/{fn}{linespec}"
[ "def", "linkcode_resolve", "(", "domain", ",", "info", ")", ":", "if", "domain", "!=", "\"py\"", ":", "return", "None", "modname", "=", "info", "[", "\"module\"", "]", "fullname", "=", "info", "[", "\"fullname\"", "]", "submod", "=", "sys", ".", "modules...
[ 99, 0 ]
[ 134, 60 ]
python
en
['en', 'en', 'en']
True
_async_save_refresh_token
(hass, config_entry, token)
Save a refresh token to the config entry.
Save a refresh token to the config entry.
def _async_save_refresh_token(hass, config_entry, token): """Save a refresh token to the config entry.""" hass.config_entries.async_update_entry( config_entry, data={**config_entry.data, CONF_TOKEN: token} )
[ "def", "_async_save_refresh_token", "(", "hass", ",", "config_entry", ",", "token", ")", ":", "hass", ".", "config_entries", ".", "async_update_entry", "(", "config_entry", ",", "data", "=", "{", "*", "*", "config_entry", ".", "data", ",", "CONF_TOKEN", ":", ...
[ 144, 0 ]
[ 148, 5 ]
python
en
['en', 'en', 'en']
True
async_get_client_id
(hass)
Get a client ID (based on the HASS unique ID) for the SimpliSafe API. Note that SimpliSafe requires full, "dashed" versions of UUIDs.
Get a client ID (based on the HASS unique ID) for the SimpliSafe API.
async def async_get_client_id(hass): """Get a client ID (based on the HASS unique ID) for the SimpliSafe API. Note that SimpliSafe requires full, "dashed" versions of UUIDs. """ hass_id = await hass.helpers.instance_id.async_get() return str(UUID(hass_id))
[ "async", "def", "async_get_client_id", "(", "hass", ")", ":", "hass_id", "=", "await", "hass", ".", "helpers", ".", "instance_id", ".", "async_get", "(", ")", "return", "str", "(", "UUID", "(", "hass_id", ")", ")" ]
[ 151, 0 ]
[ 157, 29 ]
python
en
['en', 'en', 'en']
True
async_register_base_station
(hass, system, config_entry_id)
Register a new bridge.
Register a new bridge.
async def async_register_base_station(hass, system, config_entry_id): """Register a new bridge.""" device_registry = await dr.async_get_registry(hass) device_registry.async_get_or_create( config_entry_id=config_entry_id, identifiers={(DOMAIN, system.serial)}, manufacturer="SimpliSafe", model=system.version, name=system.address, )
[ "async", "def", "async_register_base_station", "(", "hass", ",", "system", ",", "config_entry_id", ")", ":", "device_registry", "=", "await", "dr", ".", "async_get_registry", "(", "hass", ")", "device_registry", ".", "async_get_or_create", "(", "config_entry_id", "=...
[ 160, 0 ]
[ 169, 5 ]
python
en
['en', 'ca', 'en']
True
async_setup
(hass, config)
Set up the SimpliSafe component.
Set up the SimpliSafe component.
async def async_setup(hass, config): """Set up the SimpliSafe component.""" hass.data[DOMAIN] = {DATA_CLIENT: {}, DATA_LISTENER: {}} return True
[ "async", "def", "async_setup", "(", "hass", ",", "config", ")", ":", "hass", ".", "data", "[", "DOMAIN", "]", "=", "{", "DATA_CLIENT", ":", "{", "}", ",", "DATA_LISTENER", ":", "{", "}", "}", "return", "True" ]
[ 172, 0 ]
[ 175, 15 ]
python
en
['en', 'en', 'en']
True
async_setup_entry
(hass, config_entry)
Set up SimpliSafe as config entry.
Set up SimpliSafe as config entry.
async def async_setup_entry(hass, config_entry): """Set up SimpliSafe as config entry.""" hass.data[DOMAIN][DATA_LISTENER][config_entry.entry_id] = [] entry_updates = {} if not config_entry.unique_id: # If the config entry doesn't already have a unique ID, set one: entry_updates["unique_id"] = config_entry.data[CONF_USERNAME] if CONF_CODE in config_entry.data: # If an alarm code was provided as part of configuration.yaml, pop it out of # the config entry's data and move it to options: data = {**config_entry.data} entry_updates["data"] = data entry_updates["options"] = { **config_entry.options, CONF_CODE: data.pop(CONF_CODE), } if entry_updates: hass.config_entries.async_update_entry(config_entry, **entry_updates) _verify_domain_control = verify_domain_control(hass, DOMAIN) client_id = await async_get_client_id(hass) websession = aiohttp_client.async_get_clientsession(hass) try: api = await API.login_via_token( config_entry.data[CONF_TOKEN], client_id=client_id, session=websession ) except InvalidCredentialsError: LOGGER.error("Invalid credentials provided") return False except SimplipyError as err: LOGGER.error("Config entry failed: %s", err) raise ConfigEntryNotReady from err _async_save_refresh_token(hass, config_entry, api.refresh_token) simplisafe = hass.data[DOMAIN][DATA_CLIENT][config_entry.entry_id] = SimpliSafe( hass, api, config_entry ) await simplisafe.async_init() for platform in SUPPORTED_PLATFORMS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(config_entry, platform) ) @callback def verify_system_exists(coro): """Log an error if a service call uses an invalid system ID.""" async def decorator(call): """Decorate.""" system_id = int(call.data[ATTR_SYSTEM_ID]) if system_id not in simplisafe.systems: LOGGER.error("Unknown system ID in service call: %s", system_id) return await coro(call) return decorator @callback def v3_only(coro): """Log an error if the decorated coroutine is called with a v2 system.""" async def decorator(call): """Decorate.""" system = simplisafe.systems[int(call.data[ATTR_SYSTEM_ID])] if system.version != 3: LOGGER.error("Service only available on V3 systems") return await coro(call) return decorator @verify_system_exists @_verify_domain_control async def clear_notifications(call): """Clear all active notifications.""" system = simplisafe.systems[call.data[ATTR_SYSTEM_ID]] try: await system.clear_notifications() except SimplipyError as err: LOGGER.error("Error during service call: %s", err) return @verify_system_exists @_verify_domain_control async def remove_pin(call): """Remove a PIN.""" system = simplisafe.systems[call.data[ATTR_SYSTEM_ID]] try: await system.remove_pin(call.data[ATTR_PIN_LABEL_OR_VALUE]) except SimplipyError as err: LOGGER.error("Error during service call: %s", err) return @verify_system_exists @_verify_domain_control async def set_pin(call): """Set a PIN.""" system = simplisafe.systems[call.data[ATTR_SYSTEM_ID]] try: await system.set_pin(call.data[ATTR_PIN_LABEL], call.data[ATTR_PIN_VALUE]) except SimplipyError as err: LOGGER.error("Error during service call: %s", err) return @verify_system_exists @v3_only @_verify_domain_control async def set_system_properties(call): """Set one or more system parameters.""" system = simplisafe.systems[call.data[ATTR_SYSTEM_ID]] try: await system.set_properties( { prop: value for prop, value in call.data.items() if prop != ATTR_SYSTEM_ID } ) except SimplipyError as err: LOGGER.error("Error during service call: %s", err) return for service, method, schema in [ ("clear_notifications", clear_notifications, None), ("remove_pin", remove_pin, SERVICE_REMOVE_PIN_SCHEMA), ("set_pin", set_pin, SERVICE_SET_PIN_SCHEMA), ( "set_system_properties", set_system_properties, SERVICE_SET_SYSTEM_PROPERTIES_SCHEMA, ), ]: async_register_admin_service(hass, DOMAIN, service, method, schema=schema) hass.data[DOMAIN][DATA_LISTENER][config_entry.entry_id].append( config_entry.add_update_listener(async_reload_entry) ) return True
[ "async", "def", "async_setup_entry", "(", "hass", ",", "config_entry", ")", ":", "hass", ".", "data", "[", "DOMAIN", "]", "[", "DATA_LISTENER", "]", "[", "config_entry", ".", "entry_id", "]", "=", "[", "]", "entry_updates", "=", "{", "}", "if", "not", ...
[ 178, 0 ]
[ 321, 15 ]
python
en
['en', 'pt', 'en']
True
async_unload_entry
(hass, entry)
Unload a SimpliSafe config entry.
Unload a SimpliSafe config entry.
async def async_unload_entry(hass, entry): """Unload a SimpliSafe config entry.""" unload_ok = all( await asyncio.gather( *[ hass.config_entries.async_forward_entry_unload(entry, component) for component in SUPPORTED_PLATFORMS ] ) ) if unload_ok: hass.data[DOMAIN][DATA_CLIENT].pop(entry.entry_id) for remove_listener in hass.data[DOMAIN][DATA_LISTENER].pop(entry.entry_id): remove_listener() return unload_ok
[ "async", "def", "async_unload_entry", "(", "hass", ",", "entry", ")", ":", "unload_ok", "=", "all", "(", "await", "asyncio", ".", "gather", "(", "*", "[", "hass", ".", "config_entries", ".", "async_forward_entry_unload", "(", "entry", ",", "component", ")", ...
[ 324, 0 ]
[ 339, 20 ]
python
en
['en', 'en', 'en']
True
async_reload_entry
(hass, config_entry)
Handle an options update.
Handle an options update.
async def async_reload_entry(hass, config_entry): """Handle an options update.""" await hass.config_entries.async_reload(config_entry.entry_id)
[ "async", "def", "async_reload_entry", "(", "hass", ",", "config_entry", ")", ":", "await", "hass", ".", "config_entries", ".", "async_reload", "(", "config_entry", ".", "entry_id", ")" ]
[ 342, 0 ]
[ 344, 65 ]
python
en
['en', 'en', 'en']
True
SimpliSafeWebsocket.__init__
(self, hass, websocket)
Initialize.
Initialize.
def __init__(self, hass, websocket): """Initialize.""" self._hass = hass self._websocket = websocket
[ "def", "__init__", "(", "self", ",", "hass", ",", "websocket", ")", ":", "self", ".", "_hass", "=", "hass", "self", ".", "_websocket", "=", "websocket" ]
[ 350, 4 ]
[ 353, 35 ]
python
en
['en', 'en', 'it']
False
SimpliSafeWebsocket._on_connect
()
Define a handler to fire when the websocket is connected.
Define a handler to fire when the websocket is connected.
def _on_connect(): """Define a handler to fire when the websocket is connected.""" LOGGER.info("Connected to websocket")
[ "def", "_on_connect", "(", ")", ":", "LOGGER", ".", "info", "(", "\"Connected to websocket\"", ")" ]
[ 356, 4 ]
[ 358, 45 ]
python
en
['en', 'en', 'en']
True
SimpliSafeWebsocket._on_disconnect
()
Define a handler to fire when the websocket is disconnected.
Define a handler to fire when the websocket is disconnected.
def _on_disconnect(): """Define a handler to fire when the websocket is disconnected.""" LOGGER.info("Disconnected from websocket")
[ "def", "_on_disconnect", "(", ")", ":", "LOGGER", ".", "info", "(", "\"Disconnected from websocket\"", ")" ]
[ 361, 4 ]
[ 363, 50 ]
python
en
['en', 'en', 'en']
True
SimpliSafeWebsocket._on_event
(self, event)
Define a handler to fire when a new SimpliSafe event arrives.
Define a handler to fire when a new SimpliSafe event arrives.
def _on_event(self, event): """Define a handler to fire when a new SimpliSafe event arrives.""" LOGGER.debug("New websocket event: %s", event) async_dispatcher_send( self._hass, TOPIC_UPDATE_WEBSOCKET.format(event.system_id), event ) if event.event_type not in WEBSOCKET_EVENTS_TO_TRIGGER_HASS_EVENT: return if event.sensor_type: sensor_type = event.sensor_type.name else: sensor_type = None self._hass.bus.async_fire( EVENT_SIMPLISAFE_EVENT, event_data={ ATTR_LAST_EVENT_CHANGED_BY: event.changed_by, ATTR_LAST_EVENT_TYPE: event.event_type, ATTR_LAST_EVENT_INFO: event.info, ATTR_LAST_EVENT_SENSOR_NAME: event.sensor_name, ATTR_LAST_EVENT_SENSOR_SERIAL: event.sensor_serial, ATTR_LAST_EVENT_SENSOR_TYPE: sensor_type, ATTR_SYSTEM_ID: event.system_id, ATTR_LAST_EVENT_TIMESTAMP: event.timestamp, }, )
[ "def", "_on_event", "(", "self", ",", "event", ")", ":", "LOGGER", ".", "debug", "(", "\"New websocket event: %s\"", ",", "event", ")", "async_dispatcher_send", "(", "self", ".", "_hass", ",", "TOPIC_UPDATE_WEBSOCKET", ".", "format", "(", "event", ".", "system...
[ 365, 4 ]
[ 392, 9 ]
python
en
['en', 'en', 'en']
True
SimpliSafeWebsocket.async_connect
(self)
Register handlers and connect to the websocket.
Register handlers and connect to the websocket.
async def async_connect(self): """Register handlers and connect to the websocket.""" self._websocket.on_connect(self._on_connect) self._websocket.on_disconnect(self._on_disconnect) self._websocket.on_event(self._on_event) await self._websocket.async_connect()
[ "async", "def", "async_connect", "(", "self", ")", ":", "self", ".", "_websocket", ".", "on_connect", "(", "self", ".", "_on_connect", ")", "self", ".", "_websocket", ".", "on_disconnect", "(", "self", ".", "_on_disconnect", ")", "self", ".", "_websocket", ...
[ 394, 4 ]
[ 400, 45 ]
python
en
['en', 'en', 'en']
True
SimpliSafeWebsocket.async_disconnect
(self)
Disconnect from the websocket.
Disconnect from the websocket.
async def async_disconnect(self): """Disconnect from the websocket.""" await self._websocket.async_disconnect()
[ "async", "def", "async_disconnect", "(", "self", ")", ":", "await", "self", ".", "_websocket", ".", "async_disconnect", "(", ")" ]
[ 402, 4 ]
[ 404, 48 ]
python
en
['en', 'en', 'en']
True
SimpliSafe.__init__
(self, hass, api, config_entry)
Initialize.
Initialize.
def __init__(self, hass, api, config_entry): """Initialize.""" self._api = api self._emergency_refresh_token_used = False self._hass = hass self._system_notifications = {} self.config_entry = config_entry self.coordinator = None self.initial_event_to_use = {} self.systems = {} self.websocket = SimpliSafeWebsocket(hass, api.websocket)
[ "def", "__init__", "(", "self", ",", "hass", ",", "api", ",", "config_entry", ")", ":", "self", ".", "_api", "=", "api", "self", ".", "_emergency_refresh_token_used", "=", "False", "self", ".", "_hass", "=", "hass", "self", ".", "_system_notifications", "=...
[ 410, 4 ]
[ 420, 65 ]
python
en
['en', 'en', 'it']
False
SimpliSafe._async_process_new_notifications
(self, system)
Act on any new system notifications.
Act on any new system notifications.
def _async_process_new_notifications(self, system): """Act on any new system notifications.""" if self._hass.state != CoreState.running: # If HASS isn't fully running yet, it may cause the SIMPLISAFE_NOTIFICATION # event to fire before dependent components (like automation) are fully # ready. If that's the case, skip: return latest_notifications = set(system.notifications) to_add = latest_notifications.difference( self._system_notifications[system.system_id] ) if not to_add: return LOGGER.debug("New system notifications: %s", to_add) self._system_notifications[system.system_id].update(to_add) for notification in to_add: text = notification.text if notification.link: text = f"{text} For more information: {notification.link}" self._hass.bus.async_fire( EVENT_SIMPLISAFE_NOTIFICATION, event_data={ ATTR_CATEGORY: notification.category, ATTR_CODE: notification.code, ATTR_MESSAGE: text, ATTR_TIMESTAMP: notification.timestamp, }, )
[ "def", "_async_process_new_notifications", "(", "self", ",", "system", ")", ":", "if", "self", ".", "_hass", ".", "state", "!=", "CoreState", ".", "running", ":", "# If HASS isn't fully running yet, it may cause the SIMPLISAFE_NOTIFICATION", "# event to fire before dependent ...
[ 423, 4 ]
[ 457, 13 ]
python
en
['en', 'en', 'en']
True
SimpliSafe.async_init
(self)
Initialize the data class.
Initialize the data class.
async def async_init(self): """Initialize the data class.""" asyncio.create_task(self.websocket.async_connect()) async def async_websocket_disconnect(_): """Define an event handler to disconnect from the websocket.""" await self.websocket.async_disconnect() self._hass.data[DOMAIN][DATA_LISTENER][self.config_entry.entry_id].append( self._hass.bus.async_listen_once( EVENT_HOMEASSISTANT_STOP, async_websocket_disconnect ) ) self.systems = await self._api.get_systems() for system in self.systems.values(): self._system_notifications[system.system_id] = set() self._hass.async_create_task( async_register_base_station( self._hass, system, self.config_entry.entry_id ) ) # Future events will come from the websocket, but since subscription to the # websocket doesn't provide the most recent event, we grab it from the REST # API to ensure event-related attributes aren't empty on startup: try: self.initial_event_to_use[ system.system_id ] = await system.get_latest_event() except SimplipyError as err: LOGGER.error("Error while fetching initial event: %s", err) self.initial_event_to_use[system.system_id] = {} self.coordinator = DataUpdateCoordinator( self._hass, LOGGER, name=self.config_entry.data[CONF_USERNAME], update_interval=DEFAULT_SCAN_INTERVAL, update_method=self.async_update, )
[ "async", "def", "async_init", "(", "self", ")", ":", "asyncio", ".", "create_task", "(", "self", ".", "websocket", ".", "async_connect", "(", ")", ")", "async", "def", "async_websocket_disconnect", "(", "_", ")", ":", "\"\"\"Define an event handler to disconnect f...
[ 459, 4 ]
[ 500, 9 ]
python
en
['en', 'en', 'en']
True
SimpliSafe.async_update
(self)
Get updated data from SimpliSafe.
Get updated data from SimpliSafe.
async def async_update(self): """Get updated data from SimpliSafe.""" async def async_update_system(system): """Update a system.""" await system.update(cached=system.version != 3) self._async_process_new_notifications(system) tasks = [async_update_system(system) for system in self.systems.values()] results = await asyncio.gather(*tasks, return_exceptions=True) for result in results: if isinstance(result, InvalidCredentialsError): if self._emergency_refresh_token_used: matching_flows = [ flow for flow in self._hass.config_entries.flow.async_progress() if flow["context"].get("source") == SOURCE_REAUTH and flow["context"].get("unique_id") == self.config_entry.unique_id ] if not matching_flows: self._hass.async_create_task( self._hass.config_entries.flow.async_init( DOMAIN, context={ "source": SOURCE_REAUTH, "unique_id": self.config_entry.unique_id, }, data=self.config_entry.data, ) ) raise UpdateFailed("Update failed with stored refresh token") LOGGER.warning("SimpliSafe cloud error; trying stored refresh token") self._emergency_refresh_token_used = True try: await self._api.refresh_access_token( self.config_entry.data[CONF_TOKEN] ) return except SimplipyError as err: raise UpdateFailed( # pylint: disable=raise-missing-from f"Error while using stored refresh token: {err}" ) if isinstance(result, EndpointUnavailable): # In case the user attempts an action not allowed in their current plan, # we merely log that message at INFO level (so the user is aware, # but not spammed with ERROR messages that they cannot change): LOGGER.info(result) if isinstance(result, SimplipyError): raise UpdateFailed(f"SimpliSafe error while updating: {result}") if self._api.refresh_token != self.config_entry.data[CONF_TOKEN]: _async_save_refresh_token( self._hass, self.config_entry, self._api.refresh_token ) # If we've reached this point using an emergency refresh token, we're in the # clear and we can discard it: if self._emergency_refresh_token_used: self._emergency_refresh_token_used = False
[ "async", "def", "async_update", "(", "self", ")", ":", "async", "def", "async_update_system", "(", "system", ")", ":", "\"\"\"Update a system.\"\"\"", "await", "system", ".", "update", "(", "cached", "=", "system", ".", "version", "!=", "3", ")", "self", "."...
[ 502, 4 ]
[ 568, 54 ]
python
en
['en', 'en', 'en']
True
SimpliSafeEntity.__init__
(self, simplisafe, system, name, *, serial=None)
Initialize.
Initialize.
def __init__(self, simplisafe, system, name, *, serial=None): """Initialize.""" super().__init__(simplisafe.coordinator) self._name = name self._online = True self._simplisafe = simplisafe self._system = system self.websocket_events_to_listen_for = [ EVENT_CONNECTION_LOST, EVENT_CONNECTION_RESTORED, ] if serial: self._serial = serial else: self._serial = system.serial try: sensor_type = EntityTypes( simplisafe.initial_event_to_use[system.system_id].get("sensorType") ) except ValueError: sensor_type = EntityTypes.unknown self._attrs = { ATTR_LAST_EVENT_INFO: simplisafe.initial_event_to_use[system.system_id].get( "info" ), ATTR_LAST_EVENT_SENSOR_NAME: simplisafe.initial_event_to_use[ system.system_id ].get("sensorName"), ATTR_LAST_EVENT_SENSOR_TYPE: sensor_type.name, ATTR_LAST_EVENT_TIMESTAMP: simplisafe.initial_event_to_use[ system.system_id ].get("eventTimestamp"), ATTR_SYSTEM_ID: system.system_id, } self._device_info = { "identifiers": {(DOMAIN, system.system_id)}, "manufacturer": "SimpliSafe", "model": system.version, "name": name, "via_device": (DOMAIN, system.serial), }
[ "def", "__init__", "(", "self", ",", "simplisafe", ",", "system", ",", "name", ",", "*", ",", "serial", "=", "None", ")", ":", "super", "(", ")", ".", "__init__", "(", "simplisafe", ".", "coordinator", ")", "self", ".", "_name", "=", "name", "self", ...
[ 574, 4 ]
[ 618, 9 ]
python
en
['en', 'en', 'it']
False
SimpliSafeEntity.available
(self)
Return whether the entity is available.
Return whether the entity is available.
def available(self): """Return whether the entity is available.""" # We can easily detect if the V3 system is offline, but no simple check exists # for the V2 system. Therefore, assuming the coordinator hasn't failed, we mark # the entity as available if: # 1. We can verify that the system is online (assuming True if we can't) # 2. We can verify that the entity is online return not (self._system.version == 3 and self._system.offline) and self._online
[ "def", "available", "(", "self", ")", ":", "# We can easily detect if the V3 system is offline, but no simple check exists", "# for the V2 system. Therefore, assuming the coordinator hasn't failed, we mark", "# the entity as available if:", "# 1. We can verify that the system is online (assuming...
[ 621, 4 ]
[ 628, 88 ]
python
en
['en', 'en', 'en']
True
SimpliSafeEntity.device_info
(self)
Return device registry information for this entity.
Return device registry information for this entity.
def device_info(self): """Return device registry information for this entity.""" return self._device_info
[ "def", "device_info", "(", "self", ")", ":", "return", "self", ".", "_device_info" ]
[ 631, 4 ]
[ 633, 32 ]
python
en
['en', 'en', 'en']
True
SimpliSafeEntity.device_state_attributes
(self)
Return the state attributes.
Return the state attributes.
def device_state_attributes(self): """Return the state attributes.""" return self._attrs
[ "def", "device_state_attributes", "(", "self", ")", ":", "return", "self", ".", "_attrs" ]
[ 636, 4 ]
[ 638, 26 ]
python
en
['en', 'en', 'en']
True
SimpliSafeEntity.name
(self)
Return the name of the entity.
Return the name of the entity.
def name(self): """Return the name of the entity.""" return f"{self._system.address} {self._name}"
[ "def", "name", "(", "self", ")", ":", "return", "f\"{self._system.address} {self._name}\"" ]
[ 641, 4 ]
[ 643, 53 ]
python
en
['en', 'en', 'en']
True
SimpliSafeEntity.unique_id
(self)
Return the unique ID of the entity.
Return the unique ID of the entity.
def unique_id(self): """Return the unique ID of the entity.""" return self._serial
[ "def", "unique_id", "(", "self", ")", ":", "return", "self", ".", "_serial" ]
[ 646, 4 ]
[ 648, 27 ]
python
en
['en', 'en', 'en']
True
SimpliSafeEntity._async_internal_update_from_websocket_event
(self, event)
Perform internal websocket handling prior to handing off.
Perform internal websocket handling prior to handing off.
def _async_internal_update_from_websocket_event(self, event): """Perform internal websocket handling prior to handing off.""" if event.event_type == EVENT_CONNECTION_LOST: self._online = False elif event.event_type == EVENT_CONNECTION_RESTORED: self._online = True # It's uncertain whether SimpliSafe events will still propagate down the # websocket when the base station is offline. Just in case, we guard against # further action until connection is restored: if not self._online: return if event.sensor_type: sensor_type = event.sensor_type.name else: sensor_type = None self._attrs.update( { ATTR_LAST_EVENT_INFO: event.info, ATTR_LAST_EVENT_SENSOR_NAME: event.sensor_name, ATTR_LAST_EVENT_SENSOR_TYPE: sensor_type, ATTR_LAST_EVENT_TIMESTAMP: event.timestamp, } ) self.async_update_from_websocket_event(event)
[ "def", "_async_internal_update_from_websocket_event", "(", "self", ",", "event", ")", ":", "if", "event", ".", "event_type", "==", "EVENT_CONNECTION_LOST", ":", "self", ".", "_online", "=", "False", "elif", "event", ".", "event_type", "==", "EVENT_CONNECTION_RESTORE...
[ 651, 4 ]
[ 678, 53 ]
python
en
['en', 'af', 'en']
True
SimpliSafeEntity._handle_coordinator_update
(self)
Update the entity with new REST API data.
Update the entity with new REST API data.
def _handle_coordinator_update(self): """Update the entity with new REST API data.""" self.async_update_from_rest_api() self.async_write_ha_state()
[ "def", "_handle_coordinator_update", "(", "self", ")", ":", "self", ".", "async_update_from_rest_api", "(", ")", "self", ".", "async_write_ha_state", "(", ")" ]
[ 681, 4 ]
[ 684, 35 ]
python
en
['en', 'en', 'en']
True
SimpliSafeEntity._handle_websocket_update
(self, event)
Update the entity with new websocket data.
Update the entity with new websocket data.
def _handle_websocket_update(self, event): """Update the entity with new websocket data.""" # Ignore this event if it belongs to a system other than this one: if event.system_id != self._system.system_id: return # Ignore this event if this entity hasn't expressed interest in its type: if event.event_type not in self.websocket_events_to_listen_for: return # Ignore this event if it belongs to a entity with a different serial # number from this one's: if ( event.event_type in WEBSOCKET_EVENTS_REQUIRING_SERIAL and event.sensor_serial != self._serial ): return self._async_internal_update_from_websocket_event(event) self.async_write_ha_state()
[ "def", "_handle_websocket_update", "(", "self", ",", "event", ")", ":", "# Ignore this event if it belongs to a system other than this one:", "if", "event", ".", "system_id", "!=", "self", ".", "_system", ".", "system_id", ":", "return", "# Ignore this event if this entity ...
[ 687, 4 ]
[ 706, 35 ]
python
en
['en', 'en', 'en']
True
SimpliSafeEntity.async_added_to_hass
(self)
Register callbacks.
Register callbacks.
async def async_added_to_hass(self): """Register callbacks.""" await super().async_added_to_hass() self.async_on_remove( async_dispatcher_connect( self.hass, TOPIC_UPDATE_WEBSOCKET.format(self._system.system_id), self._handle_websocket_update, ) ) self.async_update_from_rest_api()
[ "async", "def", "async_added_to_hass", "(", "self", ")", ":", "await", "super", "(", ")", ".", "async_added_to_hass", "(", ")", "self", ".", "async_on_remove", "(", "async_dispatcher_connect", "(", "self", ".", "hass", ",", "TOPIC_UPDATE_WEBSOCKET", ".", "format...
[ 708, 4 ]
[ 720, 41 ]
python
en
['en', 'no', 'en']
False
SimpliSafeEntity.async_update_from_rest_api
(self)
Update the entity with the provided REST API data.
Update the entity with the provided REST API data.
def async_update_from_rest_api(self): """Update the entity with the provided REST API data.""" raise NotImplementedError()
[ "def", "async_update_from_rest_api", "(", "self", ")", ":", "raise", "NotImplementedError", "(", ")" ]
[ 723, 4 ]
[ 725, 35 ]
python
en
['en', 'en', 'en']
True
SimpliSafeEntity.async_update_from_websocket_event
(self, event)
Update the entity with the provided websocket event.
Update the entity with the provided websocket event.
def async_update_from_websocket_event(self, event): """Update the entity with the provided websocket event."""
[ "def", "async_update_from_websocket_event", "(", "self", ",", "event", ")", ":" ]
[ 728, 4 ]
[ 729, 66 ]
python
en
['en', 'en', 'en']
True
SimpliSafeBaseSensor.__init__
(self, simplisafe, system, sensor)
Initialize.
Initialize.
def __init__(self, simplisafe, system, sensor): """Initialize.""" super().__init__(simplisafe, system, sensor.name, serial=sensor.serial) self._device_info["identifiers"] = {(DOMAIN, sensor.serial)} self._device_info["model"] = sensor.type.name self._device_info["name"] = sensor.name self._sensor = sensor self._sensor_type_human_name = " ".join( [w.title() for w in self._sensor.type.name.split("_")] )
[ "def", "__init__", "(", "self", ",", "simplisafe", ",", "system", ",", "sensor", ")", ":", "super", "(", ")", ".", "__init__", "(", "simplisafe", ",", "system", ",", "sensor", ".", "name", ",", "serial", "=", "sensor", ".", "serial", ")", "self", "."...
[ 735, 4 ]
[ 744, 9 ]
python
en
['en', 'en', 'it']
False
SimpliSafeBaseSensor.name
(self)
Return the name of the sensor.
Return the name of the sensor.
def name(self): """Return the name of the sensor.""" return f"{self._system.address} {self._name} {self._sensor_type_human_name}"
[ "def", "name", "(", "self", ")", ":", "return", "f\"{self._system.address} {self._name} {self._sensor_type_human_name}\"" ]
[ 747, 4 ]
[ 749, 84 ]
python
en
['en', 'mi', 'en']
True
color_rgb_to_int
(red: int, green: int, blue: int)
Return a RGB color as an integer.
Return a RGB color as an integer.
def color_rgb_to_int(red: int, green: int, blue: int) -> int: """Return a RGB color as an integer.""" return red * 256 * 256 + green * 256 + blue
[ "def", "color_rgb_to_int", "(", "red", ":", "int", ",", "green", ":", "int", ",", "blue", ":", "int", ")", "->", "int", ":", "return", "red", "*", "256", "*", "256", "+", "green", "*", "256", "+", "blue" ]
[ 35, 0 ]
[ 37, 47 ]
python
en
['en', 'ga', 'en']
True
color_int_to_rgb
(value: int)
Return an RGB tuple from an integer.
Return an RGB tuple from an integer.
def color_int_to_rgb(value: int) -> Tuple[int, int, int]: """Return an RGB tuple from an integer.""" return (value >> 16, (value >> 8) & 0xFF, value & 0xFF)
[ "def", "color_int_to_rgb", "(", "value", ":", "int", ")", "->", "Tuple", "[", "int", ",", "int", ",", "int", "]", ":", "return", "(", "value", ">>", "16", ",", "(", "value", ">>", "8", ")", "&", "0xFF", ",", "value", "&", "0xFF", ")" ]
[ 40, 0 ]
[ 42, 59 ]
python
en
['en', 'mt', 'en']
True
async_setup_platform
(hass, config, async_add_entities, discovery_info=None)
Set up the EverLights lights from configuration.yaml.
Set up the EverLights lights from configuration.yaml.
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the EverLights lights from configuration.yaml.""" lights = [] for ipaddr in config[CONF_HOSTS]: api = pyeverlights.EverLights(ipaddr, async_get_clientsession(hass)) try: status = await api.get_status() effects = await api.get_all_patterns() except pyeverlights.ConnectionError as err: raise PlatformNotReady from err else: lights.append(EverLightsLight(api, pyeverlights.ZONE_1, status, effects)) lights.append(EverLightsLight(api, pyeverlights.ZONE_2, status, effects)) async_add_entities(lights)
[ "async", "def", "async_setup_platform", "(", "hass", ",", "config", ",", "async_add_entities", ",", "discovery_info", "=", "None", ")", ":", "lights", "=", "[", "]", "for", "ipaddr", "in", "config", "[", "CONF_HOSTS", "]", ":", "api", "=", "pyeverlights", ...
[ 45, 0 ]
[ 64, 30 ]
python
en
['en', 'en', 'en']
True
EverLightsLight.__init__
(self, api, channel, status, effects)
Initialize the light.
Initialize the light.
def __init__(self, api, channel, status, effects): """Initialize the light.""" self._api = api self._channel = channel self._status = status self._effects = effects self._mac = status["mac"] self._error_reported = False self._hs_color = [255, 255] self._brightness = 255 self._effect = None self._available = True
[ "def", "__init__", "(", "self", ",", "api", ",", "channel", ",", "status", ",", "effects", ")", ":", "self", ".", "_api", "=", "api", "self", ".", "_channel", "=", "channel", "self", ".", "_status", "=", "status", "self", ".", "_effects", "=", "effec...
[ 70, 4 ]
[ 81, 30 ]
python
en
['en', 'en', 'en']
True
EverLightsLight.unique_id
(self)
Return a unique ID.
Return a unique ID.
def unique_id(self) -> str: """Return a unique ID.""" return f"{self._mac}-{self._channel}"
[ "def", "unique_id", "(", "self", ")", "->", "str", ":", "return", "f\"{self._mac}-{self._channel}\"" ]
[ 84, 4 ]
[ 86, 45 ]
python
ca
['fr', 'ca', 'en']
False
EverLightsLight.available
(self)
Return True if entity is available.
Return True if entity is available.
def available(self) -> bool: """Return True if entity is available.""" return self._available
[ "def", "available", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "_available" ]
[ 89, 4 ]
[ 91, 30 ]
python
en
['en', 'en', 'en']
True
EverLightsLight.name
(self)
Return the name of the device.
Return the name of the device.
def name(self): """Return the name of the device.""" return f"EverLights {self._mac} Zone {self._channel}"
[ "def", "name", "(", "self", ")", ":", "return", "f\"EverLights {self._mac} Zone {self._channel}\"" ]
[ 94, 4 ]
[ 96, 61 ]
python
en
['en', 'en', 'en']
True
EverLightsLight.is_on
(self)
Return true if device is on.
Return true if device is on.
def is_on(self): """Return true if device is on.""" return self._status[f"ch{self._channel}Active"] == 1
[ "def", "is_on", "(", "self", ")", ":", "return", "self", ".", "_status", "[", "f\"ch{self._channel}Active\"", "]", "==", "1" ]
[ 99, 4 ]
[ 101, 60 ]
python
en
['en', 'fy', 'en']
True
EverLightsLight.brightness
(self)
Return the brightness of this light between 0..255.
Return the brightness of this light between 0..255.
def brightness(self): """Return the brightness of this light between 0..255.""" return self._brightness
[ "def", "brightness", "(", "self", ")", ":", "return", "self", ".", "_brightness" ]
[ 104, 4 ]
[ 106, 31 ]
python
en
['en', 'en', 'en']
True
EverLightsLight.hs_color
(self)
Return the color property.
Return the color property.
def hs_color(self): """Return the color property.""" return self._hs_color
[ "def", "hs_color", "(", "self", ")", ":", "return", "self", ".", "_hs_color" ]
[ 109, 4 ]
[ 111, 29 ]
python
en
['en', 'en', 'en']
True
EverLightsLight.effect
(self)
Return the effect property.
Return the effect property.
def effect(self): """Return the effect property.""" return self._effect
[ "def", "effect", "(", "self", ")", ":", "return", "self", ".", "_effect" ]
[ 114, 4 ]
[ 116, 27 ]
python
en
['en', 'en', 'en']
True
EverLightsLight.supported_features
(self)
Flag supported features.
Flag supported features.
def supported_features(self): """Flag supported features.""" return SUPPORT_EVERLIGHTS
[ "def", "supported_features", "(", "self", ")", ":", "return", "SUPPORT_EVERLIGHTS" ]
[ 119, 4 ]
[ 121, 33 ]
python
en
['da', 'en', 'en']
True
EverLightsLight.effect_list
(self)
Return the list of supported effects.
Return the list of supported effects.
def effect_list(self): """Return the list of supported effects.""" return self._effects
[ "def", "effect_list", "(", "self", ")", ":", "return", "self", ".", "_effects" ]
[ 124, 4 ]
[ 126, 28 ]
python
en
['en', 'en', 'en']
True
EverLightsLight.async_turn_on
(self, **kwargs)
Turn the light on.
Turn the light on.
async def async_turn_on(self, **kwargs): """Turn the light on.""" hs_color = kwargs.get(ATTR_HS_COLOR, self._hs_color) brightness = kwargs.get(ATTR_BRIGHTNESS, self._brightness) effect = kwargs.get(ATTR_EFFECT) if effect is not None: colors = await self._api.set_pattern_by_id(self._channel, effect) rgb = color_int_to_rgb(colors[0]) hsv = color_util.color_RGB_to_hsv(*rgb) hs_color = hsv[:2] brightness = hsv[2] / 100 * 255 else: rgb = color_util.color_hsv_to_RGB(*hs_color, brightness / 255 * 100) colors = [color_rgb_to_int(*rgb)] await self._api.set_pattern(self._channel, colors) self._hs_color = hs_color self._brightness = brightness self._effect = effect
[ "async", "def", "async_turn_on", "(", "self", ",", "*", "*", "kwargs", ")", ":", "hs_color", "=", "kwargs", ".", "get", "(", "ATTR_HS_COLOR", ",", "self", ".", "_hs_color", ")", "brightness", "=", "kwargs", ".", "get", "(", "ATTR_BRIGHTNESS", ",", "self"...
[ 128, 4 ]
[ 150, 29 ]
python
en
['en', 'et', 'en']
True
EverLightsLight.async_turn_off
(self, **kwargs)
Turn the light off.
Turn the light off.
async def async_turn_off(self, **kwargs): """Turn the light off.""" await self._api.clear_pattern(self._channel)
[ "async", "def", "async_turn_off", "(", "self", ",", "*", "*", "kwargs", ")", ":", "await", "self", ".", "_api", ".", "clear_pattern", "(", "self", ".", "_channel", ")" ]
[ 152, 4 ]
[ 154, 52 ]
python
en
['en', 'zh', 'en']
True
EverLightsLight.async_update
(self)
Synchronize state with control box.
Synchronize state with control box.
async def async_update(self): """Synchronize state with control box.""" try: self._status = await self._api.get_status() except pyeverlights.ConnectionError: if self._available: _LOGGER.warning("EverLights control box connection lost") self._available = False else: if not self._available: _LOGGER.warning("EverLights control box connection restored") self._available = True
[ "async", "def", "async_update", "(", "self", ")", ":", "try", ":", "self", ".", "_status", "=", "await", "self", ".", "_api", ".", "get_status", "(", ")", "except", "pyeverlights", ".", "ConnectionError", ":", "if", "self", ".", "_available", ":", "_LOGG...
[ 156, 4 ]
[ 167, 34 ]
python
en
['en', 'en', 'en']
True
mock_legacy_time
(legacy_patchable_time)
Make time patchable for all the tests.
Make time patchable for all the tests.
def mock_legacy_time(legacy_patchable_time): """Make time patchable for all the tests.""" yield
[ "def", "mock_legacy_time", "(", "legacy_patchable_time", ")", ":", "yield" ]
[ 30, 0 ]
[ 32, 9 ]
python
en
['en', 'en', 'en']
True
test_reload
(hass)
Verify we can reload filter sensors.
Verify we can reload filter sensors.
async def test_reload(hass): """Verify we can reload filter sensors.""" await hass.async_add_executor_job( init_recorder_component, hass ) # force in memory db hass.states.async_set("sensor.test_monitored", 12345) await async_setup_component( hass, "sensor", { "sensor": { "platform": "statistics", "name": "test", "entity_id": "sensor.test_monitored", "sampling_size": 100, } }, ) await hass.async_block_till_done() await hass.async_start() await hass.async_block_till_done() assert len(hass.states.async_all()) == 2 assert hass.states.get("sensor.test") yaml_path = path.join( _get_fixtures_base_path(), "fixtures", "statistics/configuration.yaml", ) with patch.object(hass_config, "YAML_CONFIG_FILE", yaml_path): await hass.services.async_call( DOMAIN, SERVICE_RELOAD, {}, blocking=True, ) await hass.async_block_till_done() assert len(hass.states.async_all()) == 2 assert hass.states.get("sensor.test") is None assert hass.states.get("sensor.cputest")
[ "async", "def", "test_reload", "(", "hass", ")", ":", "await", "hass", ".", "async_add_executor_job", "(", "init_recorder_component", ",", "hass", ")", "# force in memory db", "hass", ".", "states", ".", "async_set", "(", "\"sensor.test_monitored\"", ",", "12345", ...
[ 453, 0 ]
[ 497, 44 ]
python
en
['en', 'da', 'en']
True
TestStatisticsSensor.setup_method
(self, method)
Set up things to be run when tests are started.
Set up things to be run when tests are started.
def setup_method(self, method): """Set up things to be run when tests are started.""" self.hass = get_test_home_assistant() self.values = [17, 20, 15.2, 5, 3.8, 9.2, 6.7, 14, 6] self.count = len(self.values) self.min = min(self.values) self.max = max(self.values) self.total = sum(self.values) self.mean = round(sum(self.values) / len(self.values), 2) self.median = round(statistics.median(self.values), 2) self.deviation = round(statistics.stdev(self.values), 2) self.variance = round(statistics.variance(self.values), 2) self.change = round(self.values[-1] - self.values[0], 2) self.average_change = round(self.change / (len(self.values) - 1), 2) self.change_rate = round(self.change / (60 * (self.count - 1)), 2) self.addCleanup(self.hass.stop)
[ "def", "setup_method", "(", "self", ",", "method", ")", ":", "self", ".", "hass", "=", "get_test_home_assistant", "(", ")", "self", ".", "values", "=", "[", "17", ",", "20", ",", "15.2", ",", "5", ",", "3.8", ",", "9.2", ",", "6.7", ",", "14", ",...
[ 38, 4 ]
[ 53, 39 ]
python
en
['en', 'en', 'en']
True
TestStatisticsSensor.test_binary_sensor_source
(self)
Test if source is a sensor.
Test if source is a sensor.
def test_binary_sensor_source(self): """Test if source is a sensor.""" values = ["on", "off", "on", "off", "on", "off", "on"] assert setup_component( self.hass, "sensor", { "sensor": { "platform": "statistics", "name": "test", "entity_id": "binary_sensor.test_monitored", } }, ) self.hass.block_till_done() self.hass.start() self.hass.block_till_done() for value in values: self.hass.states.set("binary_sensor.test_monitored", value) self.hass.block_till_done() state = self.hass.states.get("sensor.test") assert str(len(values)) == state.state
[ "def", "test_binary_sensor_source", "(", "self", ")", ":", "values", "=", "[", "\"on\"", ",", "\"off\"", ",", "\"on\"", ",", "\"off\"", ",", "\"on\"", ",", "\"off\"", ",", "\"on\"", "]", "assert", "setup_component", "(", "self", ".", "hass", ",", "\"sensor...
[ 55, 4 ]
[ 80, 46 ]
python
en
['en', 'bg', 'en']
True
TestStatisticsSensor.test_sensor_source
(self)
Test if source is a sensor.
Test if source is a sensor.
def test_sensor_source(self): """Test if source is a sensor.""" assert setup_component( self.hass, "sensor", { "sensor": { "platform": "statistics", "name": "test", "entity_id": "sensor.test_monitored", } }, ) self.hass.block_till_done() self.hass.start() self.hass.block_till_done() for value in self.values: self.hass.states.set( "sensor.test_monitored", value, {ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS} ) self.hass.block_till_done() state = self.hass.states.get("sensor.test") assert str(self.mean) == state.state assert self.min == state.attributes.get("min_value") assert self.max == state.attributes.get("max_value") assert self.variance == state.attributes.get("variance") assert self.median == state.attributes.get("median") assert self.deviation == state.attributes.get("standard_deviation") assert self.mean == state.attributes.get("mean") assert self.count == state.attributes.get("count") assert self.total == state.attributes.get("total") assert TEMP_CELSIUS == state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) assert self.change == state.attributes.get("change") assert self.average_change == state.attributes.get("average_change")
[ "def", "test_sensor_source", "(", "self", ")", ":", "assert", "setup_component", "(", "self", ".", "hass", ",", "\"sensor\"", ",", "{", "\"sensor\"", ":", "{", "\"platform\"", ":", "\"statistics\"", ",", "\"name\"", ":", "\"test\"", ",", "\"entity_id\"", ":", ...
[ 82, 4 ]
[ 119, 76 ]
python
en
['en', 'bg', 'en']
True
TestStatisticsSensor.test_sampling_size
(self)
Test rotation.
Test rotation.
def test_sampling_size(self): """Test rotation.""" assert setup_component( self.hass, "sensor", { "sensor": { "platform": "statistics", "name": "test", "entity_id": "sensor.test_monitored", "sampling_size": 5, } }, ) self.hass.block_till_done() self.hass.start() self.hass.block_till_done() for value in self.values: self.hass.states.set( "sensor.test_monitored", value, {ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS} ) self.hass.block_till_done() state = self.hass.states.get("sensor.test") assert 3.8 == state.attributes.get("min_value") assert 14 == state.attributes.get("max_value")
[ "def", "test_sampling_size", "(", "self", ")", ":", "assert", "setup_component", "(", "self", ".", "hass", ",", "\"sensor\"", ",", "{", "\"sensor\"", ":", "{", "\"platform\"", ":", "\"statistics\"", ",", "\"name\"", ":", "\"test\"", ",", "\"entity_id\"", ":", ...
[ 121, 4 ]
[ 149, 54 ]
python
en
['en', 'haw', 'en']
False
TestStatisticsSensor.test_sampling_size_1
(self)
Test validity of stats requiring only one sample.
Test validity of stats requiring only one sample.
def test_sampling_size_1(self): """Test validity of stats requiring only one sample.""" assert setup_component( self.hass, "sensor", { "sensor": { "platform": "statistics", "name": "test", "entity_id": "sensor.test_monitored", "sampling_size": 1, } }, ) self.hass.block_till_done() self.hass.start() self.hass.block_till_done() for value in self.values[-3:]: # just the last 3 will do self.hass.states.set( "sensor.test_monitored", value, {ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS} ) self.hass.block_till_done() state = self.hass.states.get("sensor.test") # require only one data point assert self.values[-1] == state.attributes.get("min_value") assert self.values[-1] == state.attributes.get("max_value") assert self.values[-1] == state.attributes.get("mean") assert self.values[-1] == state.attributes.get("median") assert self.values[-1] == state.attributes.get("total") assert 0 == state.attributes.get("change") assert 0 == state.attributes.get("average_change") # require at least two data points assert STATE_UNKNOWN == state.attributes.get("variance") assert STATE_UNKNOWN == state.attributes.get("standard_deviation")
[ "def", "test_sampling_size_1", "(", "self", ")", ":", "assert", "setup_component", "(", "self", ".", "hass", ",", "\"sensor\"", ",", "{", "\"sensor\"", ":", "{", "\"platform\"", ":", "\"statistics\"", ",", "\"name\"", ":", "\"test\"", ",", "\"entity_id\"", ":"...
[ 151, 4 ]
[ 189, 74 ]
python
en
['en', 'en', 'en']
True
TestStatisticsSensor.test_max_age
(self)
Test value deprecation.
Test value deprecation.
def test_max_age(self): """Test value deprecation.""" now = dt_util.utcnow() mock_data = { "return_time": datetime(now.year + 1, 8, 2, 12, 23, tzinfo=dt_util.UTC) } def mock_now(): return mock_data["return_time"] with patch( "homeassistant.components.statistics.sensor.dt_util.utcnow", new=mock_now ): assert setup_component( self.hass, "sensor", { "sensor": { "platform": "statistics", "name": "test", "entity_id": "sensor.test_monitored", "max_age": {"minutes": 3}, } }, ) self.hass.block_till_done() self.hass.start() self.hass.block_till_done() for value in self.values: self.hass.states.set( "sensor.test_monitored", value, {ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS}, ) self.hass.block_till_done() # insert the next value one minute later mock_data["return_time"] += timedelta(minutes=1) state = self.hass.states.get("sensor.test") assert 6 == state.attributes.get("min_value") assert 14 == state.attributes.get("max_value")
[ "def", "test_max_age", "(", "self", ")", ":", "now", "=", "dt_util", ".", "utcnow", "(", ")", "mock_data", "=", "{", "\"return_time\"", ":", "datetime", "(", "now", ".", "year", "+", "1", ",", "8", ",", "2", ",", "12", ",", "23", ",", "tzinfo", "...
[ 191, 4 ]
[ 234, 54 ]
python
da
['fr', 'da', 'en']
False
TestStatisticsSensor.test_max_age_without_sensor_change
(self)
Test value deprecation.
Test value deprecation.
def test_max_age_without_sensor_change(self): """Test value deprecation.""" now = dt_util.utcnow() mock_data = { "return_time": datetime(now.year + 1, 8, 2, 12, 23, tzinfo=dt_util.UTC) } def mock_now(): return mock_data["return_time"] with patch( "homeassistant.components.statistics.sensor.dt_util.utcnow", new=mock_now ): assert setup_component( self.hass, "sensor", { "sensor": { "platform": "statistics", "name": "test", "entity_id": "sensor.test_monitored", "max_age": {"minutes": 3}, } }, ) self.hass.block_till_done() self.hass.start() self.hass.block_till_done() for value in self.values: self.hass.states.set( "sensor.test_monitored", value, {ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS}, ) self.hass.block_till_done() # insert the next value 30 seconds later mock_data["return_time"] += timedelta(seconds=30) state = self.hass.states.get("sensor.test") assert 3.8 == state.attributes.get("min_value") assert 15.2 == state.attributes.get("max_value") # wait for 3 minutes (max_age). mock_data["return_time"] += timedelta(minutes=3) fire_time_changed(self.hass, mock_data["return_time"]) self.hass.block_till_done() state = self.hass.states.get("sensor.test") assert state.attributes.get("min_value") == STATE_UNKNOWN assert state.attributes.get("max_value") == STATE_UNKNOWN assert state.attributes.get("count") == 0
[ "def", "test_max_age_without_sensor_change", "(", "self", ")", ":", "now", "=", "dt_util", ".", "utcnow", "(", ")", "mock_data", "=", "{", "\"return_time\"", ":", "datetime", "(", "now", ".", "year", "+", "1", ",", "8", ",", "2", ",", "12", ",", "23", ...
[ 236, 4 ]
[ 290, 53 ]
python
da
['fr', 'da', 'en']
False
TestStatisticsSensor.test_change_rate
(self)
Test min_age/max_age and change_rate.
Test min_age/max_age and change_rate.
def test_change_rate(self): """Test min_age/max_age and change_rate.""" now = dt_util.utcnow() mock_data = { "return_time": datetime(now.year + 1, 8, 2, 12, 23, 42, tzinfo=dt_util.UTC) } def mock_now(): return mock_data["return_time"] with patch( "homeassistant.components.statistics.sensor.dt_util.utcnow", new=mock_now ): assert setup_component( self.hass, "sensor", { "sensor": { "platform": "statistics", "name": "test", "entity_id": "sensor.test_monitored", } }, ) self.hass.block_till_done() self.hass.start() self.hass.block_till_done() for value in self.values: self.hass.states.set( "sensor.test_monitored", value, {ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS}, ) self.hass.block_till_done() # insert the next value one minute later mock_data["return_time"] += timedelta(minutes=1) state = self.hass.states.get("sensor.test") assert datetime( now.year + 1, 8, 2, 12, 23, 42, tzinfo=dt_util.UTC ) == state.attributes.get("min_age") assert datetime( now.year + 1, 8, 2, 12, 23 + self.count - 1, 42, tzinfo=dt_util.UTC ) == state.attributes.get("max_age") assert self.change_rate == state.attributes.get("change_rate")
[ "def", "test_change_rate", "(", "self", ")", ":", "now", "=", "dt_util", ".", "utcnow", "(", ")", "mock_data", "=", "{", "\"return_time\"", ":", "datetime", "(", "now", ".", "year", "+", "1", ",", "8", ",", "2", ",", "12", ",", "23", ",", "42", "...
[ 292, 4 ]
[ 339, 70 ]
python
en
['en', 'en', 'en']
True
TestStatisticsSensor.test_initialize_from_database
(self)
Test initializing the statistics from the database.
Test initializing the statistics from the database.
def test_initialize_from_database(self): """Test initializing the statistics from the database.""" # enable the recorder init_recorder_component(self.hass) self.hass.block_till_done() self.hass.data[recorder.DATA_INSTANCE].block_till_done() # store some values for value in self.values: self.hass.states.set( "sensor.test_monitored", value, {ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS} ) self.hass.block_till_done() # wait for the recorder to really store the data wait_recording_done(self.hass) # only now create the statistics component, so that it must read the # data from the database assert setup_component( self.hass, "sensor", { "sensor": { "platform": "statistics", "name": "test", "entity_id": "sensor.test_monitored", "sampling_size": 100, } }, ) self.hass.block_till_done() self.hass.start() self.hass.block_till_done() # check if the result is as in test_sensor_source() state = self.hass.states.get("sensor.test") assert str(self.mean) == state.state
[ "def", "test_initialize_from_database", "(", "self", ")", ":", "# enable the recorder", "init_recorder_component", "(", "self", ".", "hass", ")", "self", ".", "hass", ".", "block_till_done", "(", ")", "self", ".", "hass", ".", "data", "[", "recorder", ".", "DA...
[ 341, 4 ]
[ 376, 44 ]
python
en
['en', 'en', 'en']
True
TestStatisticsSensor.test_initialize_from_database_with_maxage
(self)
Test initializing the statistics from the database.
Test initializing the statistics from the database.
def test_initialize_from_database_with_maxage(self): """Test initializing the statistics from the database.""" now = dt_util.utcnow() mock_data = { "return_time": datetime(now.year + 1, 8, 2, 12, 23, 42, tzinfo=dt_util.UTC) } def mock_now(): return mock_data["return_time"] # Testing correct retrieval from recorder, thus we do not # want purging to occur within the class itself. def mock_purge(self): return # Set maximum age to 3 hours. max_age = 3 # Determine what our minimum age should be based on test values. expected_min_age = mock_data["return_time"] + timedelta( hours=len(self.values) - max_age ) # enable the recorder init_recorder_component(self.hass) self.hass.block_till_done() self.hass.data[recorder.DATA_INSTANCE].block_till_done() with patch( "homeassistant.components.statistics.sensor.dt_util.utcnow", new=mock_now ), patch.object(StatisticsSensor, "_purge_old", mock_purge): # store some values for value in self.values: self.hass.states.set( "sensor.test_monitored", value, {ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS}, ) self.hass.block_till_done() # insert the next value 1 hour later mock_data["return_time"] += timedelta(hours=1) # wait for the recorder to really store the data wait_recording_done(self.hass) # only now create the statistics component, so that it must read # the data from the database assert setup_component( self.hass, "sensor", { "sensor": { "platform": "statistics", "name": "test", "entity_id": "sensor.test_monitored", "sampling_size": 100, "max_age": {"hours": max_age}, } }, ) self.hass.block_till_done() self.hass.block_till_done() self.hass.start() self.hass.block_till_done() # check if the result is as in test_sensor_source() state = self.hass.states.get("sensor.test") assert expected_min_age == state.attributes.get("min_age") # The max_age timestamp should be 1 hour before what we have right # now in mock_data['return_time']. assert mock_data["return_time"] == state.attributes.get("max_age") + timedelta( hours=1 )
[ "def", "test_initialize_from_database_with_maxage", "(", "self", ")", ":", "now", "=", "dt_util", ".", "utcnow", "(", ")", "mock_data", "=", "{", "\"return_time\"", ":", "datetime", "(", "now", ".", "year", "+", "1", ",", "8", ",", "2", ",", "12", ",", ...
[ 378, 4 ]
[ 450, 9 ]
python
en
['en', 'en', 'en']
True
async_setup_entry
(hass, config_entry, async_add_entities)
Set up Z-Wave Light from Config Entry.
Set up Z-Wave Light from Config Entry.
async def async_setup_entry(hass, config_entry, async_add_entities): """Set up Z-Wave Light from Config Entry.""" @callback def async_add_light(light): """Add Z-Wave Light.""" async_add_entities([light]) async_dispatcher_connect(hass, "zwave_new_light", async_add_light)
[ "async", "def", "async_setup_entry", "(", "hass", ",", "config_entry", ",", "async_add_entities", ")", ":", "@", "callback", "def", "async_add_light", "(", "light", ")", ":", "\"\"\"Add Z-Wave Light.\"\"\"", "async_add_entities", "(", "[", "light", "]", ")", "asyn...
[ 63, 0 ]
[ 71, 70 ]
python
en
['en', 'en', 'en']
True
get_device
(node, values, node_config, **kwargs)
Create Z-Wave entity device.
Create Z-Wave entity device.
def get_device(node, values, node_config, **kwargs): """Create Z-Wave entity device.""" refresh = node_config.get(CONF_REFRESH_VALUE) delay = node_config.get(CONF_REFRESH_DELAY) _LOGGER.debug( "node=%d value=%d node_config=%s CONF_REFRESH_VALUE=%s" " CONF_REFRESH_DELAY=%s", node.node_id, values.primary.value_id, node_config, refresh, delay, ) if node.has_command_class(const.COMMAND_CLASS_SWITCH_COLOR): return ZwaveColorLight(values, refresh, delay) return ZwaveDimmer(values, refresh, delay)
[ "def", "get_device", "(", "node", ",", "values", ",", "node_config", ",", "*", "*", "kwargs", ")", ":", "refresh", "=", "node_config", ".", "get", "(", "CONF_REFRESH_VALUE", ")", "delay", "=", "node_config", ".", "get", "(", "CONF_REFRESH_DELAY", ")", "_LO...
[ 74, 0 ]
[ 90, 46 ]
python
en
['en', 'pl', 'en']
True
brightness_state
(value)
Return the brightness and state.
Return the brightness and state.
def brightness_state(value): """Return the brightness and state.""" if value.data > 0: return round((value.data / 99) * 255), STATE_ON return 0, STATE_OFF
[ "def", "brightness_state", "(", "value", ")", ":", "if", "value", ".", "data", ">", "0", ":", "return", "round", "(", "(", "value", ".", "data", "/", "99", ")", "*", "255", ")", ",", "STATE_ON", "return", "0", ",", "STATE_OFF" ]
[ 93, 0 ]
[ 97, 23 ]
python
en
['en', 'en', 'en']
True
byte_to_zwave_brightness
(value)
Convert brightness in 0-255 scale to 0-99 scale. `value` -- (int) Brightness byte value from 0-255.
Convert brightness in 0-255 scale to 0-99 scale.
def byte_to_zwave_brightness(value): """Convert brightness in 0-255 scale to 0-99 scale. `value` -- (int) Brightness byte value from 0-255. """ if value > 0: return max(1, round((value / 255) * 99)) return 0
[ "def", "byte_to_zwave_brightness", "(", "value", ")", ":", "if", "value", ">", "0", ":", "return", "max", "(", "1", ",", "round", "(", "(", "value", "/", "255", ")", "*", "99", ")", ")", "return", "0" ]
[ 100, 0 ]
[ 107, 12 ]
python
en
['en', 'en', 'en']
True
ct_to_hs
(temp)
Convert color temperature (mireds) to hs.
Convert color temperature (mireds) to hs.
def ct_to_hs(temp): """Convert color temperature (mireds) to hs.""" colorlist = list( color_util.color_temperature_to_hs( color_util.color_temperature_mired_to_kelvin(temp) ) ) return [int(val) for val in colorlist]
[ "def", "ct_to_hs", "(", "temp", ")", ":", "colorlist", "=", "list", "(", "color_util", ".", "color_temperature_to_hs", "(", "color_util", ".", "color_temperature_mired_to_kelvin", "(", "temp", ")", ")", ")", "return", "[", "int", "(", "val", ")", "for", "val...
[ 110, 0 ]
[ 117, 42 ]
python
en
['en', 'en', 'en']
True
ZwaveDimmer.__init__
(self, values, refresh, delay)
Initialize the light.
Initialize the light.
def __init__(self, values, refresh, delay): """Initialize the light.""" ZWaveDeviceEntity.__init__(self, values, DOMAIN) self._brightness = None self._state = None self._supported_features = None self._delay = delay self._refresh_value = refresh self._zw098 = None # Enable appropriate workaround flags for our device # Make sure that we have values for the key before converting to int if self.node.manufacturer_id.strip() and self.node.product_id.strip(): specific_sensor_key = ( int(self.node.manufacturer_id, 16), int(self.node.product_id, 16), ) if specific_sensor_key in DEVICE_MAPPINGS: if DEVICE_MAPPINGS[specific_sensor_key] == WORKAROUND_ZW098: _LOGGER.debug("AEOTEC ZW098 workaround enabled") self._zw098 = 1 # Used for value change event handling self._refreshing = False self._timer = None _LOGGER.debug( "self._refreshing=%s self.delay=%s", self._refresh_value, self._delay ) self.value_added() self.update_properties()
[ "def", "__init__", "(", "self", ",", "values", ",", "refresh", ",", "delay", ")", ":", "ZWaveDeviceEntity", ".", "__init__", "(", "self", ",", "values", ",", "DOMAIN", ")", "self", ".", "_brightness", "=", "None", "self", ".", "_state", "=", "None", "s...
[ 123, 4 ]
[ 152, 32 ]
python
en
['en', 'en', 'en']
True
ZwaveDimmer.update_properties
(self)
Update internal properties based on zwave values.
Update internal properties based on zwave values.
def update_properties(self): """Update internal properties based on zwave values.""" # Brightness self._brightness, self._state = brightness_state(self.values.primary)
[ "def", "update_properties", "(", "self", ")", ":", "# Brightness", "self", ".", "_brightness", ",", "self", ".", "_state", "=", "brightness_state", "(", "self", ".", "values", ".", "primary", ")" ]
[ 154, 4 ]
[ 157, 77 ]
python
en
['en', 'af', 'en']
True
ZwaveDimmer.value_added
(self)
Call when a new value is added to this entity.
Call when a new value is added to this entity.
def value_added(self): """Call when a new value is added to this entity.""" self._supported_features = SUPPORT_BRIGHTNESS if self.values.dimming_duration is not None: self._supported_features |= SUPPORT_TRANSITION
[ "def", "value_added", "(", "self", ")", ":", "self", ".", "_supported_features", "=", "SUPPORT_BRIGHTNESS", "if", "self", ".", "values", ".", "dimming_duration", "is", "not", "None", ":", "self", ".", "_supported_features", "|=", "SUPPORT_TRANSITION" ]
[ 159, 4 ]
[ 163, 58 ]
python
en
['en', 'en', 'en']
True
ZwaveDimmer.value_changed
(self)
Call when a value for this entity's node has changed.
Call when a value for this entity's node has changed.
def value_changed(self): """Call when a value for this entity's node has changed.""" if self._refresh_value: if self._refreshing: self._refreshing = False else: def _refresh_value(): """Use timer callback for delayed value refresh.""" self._refreshing = True self.values.primary.refresh() if self._timer is not None and self._timer.isAlive(): self._timer.cancel() self._timer = Timer(self._delay, _refresh_value) self._timer.start() return super().value_changed()
[ "def", "value_changed", "(", "self", ")", ":", "if", "self", ".", "_refresh_value", ":", "if", "self", ".", "_refreshing", ":", "self", ".", "_refreshing", "=", "False", "else", ":", "def", "_refresh_value", "(", ")", ":", "\"\"\"Use timer callback for delayed...
[ 165, 4 ]
[ 183, 31 ]
python
en
['en', 'en', 'en']
True
ZwaveDimmer.brightness
(self)
Return the brightness of this light between 0..255.
Return the brightness of this light between 0..255.
def brightness(self): """Return the brightness of this light between 0..255.""" return self._brightness
[ "def", "brightness", "(", "self", ")", ":", "return", "self", ".", "_brightness" ]
[ 186, 4 ]
[ 188, 31 ]
python
en
['en', 'en', 'en']
True
ZwaveDimmer.is_on
(self)
Return true if device is on.
Return true if device is on.
def is_on(self): """Return true if device is on.""" return self._state == STATE_ON
[ "def", "is_on", "(", "self", ")", ":", "return", "self", ".", "_state", "==", "STATE_ON" ]
[ 191, 4 ]
[ 193, 38 ]
python
en
['en', 'fy', 'en']
True