Search is not available for this dataset
identifier
stringlengths 1
155
| parameters
stringlengths 2
6.09k
| docstring
stringlengths 11
63.4k
| docstring_summary
stringlengths 0
63.4k
| function
stringlengths 29
99.8k
| function_tokens
sequence | start_point
sequence | end_point
sequence | language
stringclasses 1
value | docstring_language
stringlengths 2
7
| docstring_language_predictions
stringlengths 18
23
| is_langid_reliable
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|---|---|---|
async_register_command | (
hass: HomeAssistant,
command_or_handler: Union[str, const.WebSocketCommandHandler],
handler: Optional[const.WebSocketCommandHandler] = None,
schema: Optional[vol.Schema] = None,
) | Register a websocket command. | Register a websocket command. | def async_register_command(
hass: HomeAssistant,
command_or_handler: Union[str, const.WebSocketCommandHandler],
handler: Optional[const.WebSocketCommandHandler] = None,
schema: Optional[vol.Schema] = None,
) -> None:
"""Register a websocket command."""
# pylint: disable=protected-access
if handler is None:
handler = cast(const.WebSocketCommandHandler, command_or_handler)
command = handler._ws_command # type: ignore
schema = handler._ws_schema # type: ignore
else:
command = command_or_handler
handlers = hass.data.get(DOMAIN)
if handlers is None:
handlers = hass.data[DOMAIN] = {}
handlers[command] = (handler, schema) | [
"def",
"async_register_command",
"(",
"hass",
":",
"HomeAssistant",
",",
"command_or_handler",
":",
"Union",
"[",
"str",
",",
"const",
".",
"WebSocketCommandHandler",
"]",
",",
"handler",
":",
"Optional",
"[",
"const",
".",
"WebSocketCommandHandler",
"]",
"=",
"None",
",",
"schema",
":",
"Optional",
"[",
"vol",
".",
"Schema",
"]",
"=",
"None",
",",
")",
"->",
"None",
":",
"# pylint: disable=protected-access",
"if",
"handler",
"is",
"None",
":",
"handler",
"=",
"cast",
"(",
"const",
".",
"WebSocketCommandHandler",
",",
"command_or_handler",
")",
"command",
"=",
"handler",
".",
"_ws_command",
"# type: ignore",
"schema",
"=",
"handler",
".",
"_ws_schema",
"# type: ignore",
"else",
":",
"command",
"=",
"command_or_handler",
"handlers",
"=",
"hass",
".",
"data",
".",
"get",
"(",
"DOMAIN",
")",
"if",
"handlers",
"is",
"None",
":",
"handlers",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"=",
"{",
"}",
"handlers",
"[",
"command",
"]",
"=",
"(",
"handler",
",",
"schema",
")"
] | [
43,
0
] | [
60,
41
] | python | en | ['en', 'lb', 'en'] | True |
async_setup | (hass, config) | Initialize the websocket API. | Initialize the websocket API. | async def async_setup(hass, config):
"""Initialize the websocket API."""
hass.http.register_view(http.WebsocketAPIView)
commands.async_register_commands(hass, async_register_command)
return True | [
"async",
"def",
"async_setup",
"(",
"hass",
",",
"config",
")",
":",
"hass",
".",
"http",
".",
"register_view",
"(",
"http",
".",
"WebsocketAPIView",
")",
"commands",
".",
"async_register_commands",
"(",
"hass",
",",
"async_register_command",
")",
"return",
"True"
] | [
63,
0
] | [
67,
15
] | python | en | ['en', 'zu', 'en'] | True |
PlaybackThread.clear_queue | (self) | Remove all pending playbacks. | Remove all pending playbacks. | def clear_queue(self):
"""Remove all pending playbacks."""
while not self.queue.empty():
self.queue.get()
try:
self.p.terminate()
except Exception as e:
LOG.error(e) | [
"def",
"clear_queue",
"(",
"self",
")",
":",
"while",
"not",
"self",
".",
"queue",
".",
"empty",
"(",
")",
":",
"self",
".",
"queue",
".",
"get",
"(",
")",
"try",
":",
"self",
".",
"p",
".",
"terminate",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"LOG",
".",
"error",
"(",
"e",
")"
] | [
83,
4
] | [
90,
24
] | python | en | ['en', 'ceb', 'en'] | True |
PlaybackThread.run | (self) | Thread main loop. Get audio and extra data from queue and play.
The queue messages is a tuple containing
snd_type: 'mp3' or 'wav' telling the loop what format the data is in
data: path to temporary audio data
videmes: list of visemes to display while playing
listen: if listening should be triggered at the end of the sentence.
Playback of audio is started and the visemes are sent over the bus
the loop then wait for the playback process to finish before starting
checking the next position in queue.
If the queue is empty the tts.end_audio() is called possibly triggering
listening.
| Thread main loop. Get audio and extra data from queue and play. | def run(self):
"""Thread main loop. Get audio and extra data from queue and play.
The queue messages is a tuple containing
snd_type: 'mp3' or 'wav' telling the loop what format the data is in
data: path to temporary audio data
videmes: list of visemes to display while playing
listen: if listening should be triggered at the end of the sentence.
Playback of audio is started and the visemes are sent over the bus
the loop then wait for the playback process to finish before starting
checking the next position in queue.
If the queue is empty the tts.end_audio() is called possibly triggering
listening.
"""
while not self._terminated:
listen = False
ident = None
try:
(snd_type, data, visemes, ident, listen) = self.queue.get(timeout=2)
self.blink(0.5)
if not self._processing_queue:
self._processing_queue = True
self.tts.begin_audio(ident)
stopwatch = Stopwatch()
with stopwatch:
if snd_type == 'wav':
self.p = play_wav(data, environment=self.pulse_env)
elif snd_type == 'mp3':
self.p = play_mp3(data, environment=self.pulse_env)
if visemes:
self.show_visemes(visemes)
if self.p:
self.p.communicate()
self.p.wait()
report_timing(ident, 'speech_playback', stopwatch)
if self.queue.empty():
self.tts.end_audio(listen, ident)
self._processing_queue = False
self.blink(0.2)
except Empty:
pass
except Exception as e:
LOG.exception(e)
if self._processing_queue:
self.tts.end_audio(listen, ident)
self._processing_queue = False | [
"def",
"run",
"(",
"self",
")",
":",
"while",
"not",
"self",
".",
"_terminated",
":",
"listen",
"=",
"False",
"ident",
"=",
"None",
"try",
":",
"(",
"snd_type",
",",
"data",
",",
"visemes",
",",
"ident",
",",
"listen",
")",
"=",
"self",
".",
"queue",
".",
"get",
"(",
"timeout",
"=",
"2",
")",
"self",
".",
"blink",
"(",
"0.5",
")",
"if",
"not",
"self",
".",
"_processing_queue",
":",
"self",
".",
"_processing_queue",
"=",
"True",
"self",
".",
"tts",
".",
"begin_audio",
"(",
"ident",
")",
"stopwatch",
"=",
"Stopwatch",
"(",
")",
"with",
"stopwatch",
":",
"if",
"snd_type",
"==",
"'wav'",
":",
"self",
".",
"p",
"=",
"play_wav",
"(",
"data",
",",
"environment",
"=",
"self",
".",
"pulse_env",
")",
"elif",
"snd_type",
"==",
"'mp3'",
":",
"self",
".",
"p",
"=",
"play_mp3",
"(",
"data",
",",
"environment",
"=",
"self",
".",
"pulse_env",
")",
"if",
"visemes",
":",
"self",
".",
"show_visemes",
"(",
"visemes",
")",
"if",
"self",
".",
"p",
":",
"self",
".",
"p",
".",
"communicate",
"(",
")",
"self",
".",
"p",
".",
"wait",
"(",
")",
"report_timing",
"(",
"ident",
",",
"'speech_playback'",
",",
"stopwatch",
")",
"if",
"self",
".",
"queue",
".",
"empty",
"(",
")",
":",
"self",
".",
"tts",
".",
"end_audio",
"(",
"listen",
",",
"ident",
")",
"self",
".",
"_processing_queue",
"=",
"False",
"self",
".",
"blink",
"(",
"0.2",
")",
"except",
"Empty",
":",
"pass",
"except",
"Exception",
"as",
"e",
":",
"LOG",
".",
"exception",
"(",
"e",
")",
"if",
"self",
".",
"_processing_queue",
":",
"self",
".",
"tts",
".",
"end_audio",
"(",
"listen",
",",
"ident",
")",
"self",
".",
"_processing_queue",
"=",
"False"
] | [
92,
4
] | [
141,
50
] | python | en | ['en', 'en', 'en'] | True |
PlaybackThread.show_visemes | (self, pairs) | Send viseme data to enclosure
Arguments:
pairs(list): Visime and timing pair
Returns:
True if button has been pressed.
| Send viseme data to enclosure | def show_visemes(self, pairs):
"""Send viseme data to enclosure
Arguments:
pairs(list): Visime and timing pair
Returns:
True if button has been pressed.
"""
if self.enclosure:
self.enclosure.mouth_viseme(time(), pairs) | [
"def",
"show_visemes",
"(",
"self",
",",
"pairs",
")",
":",
"if",
"self",
".",
"enclosure",
":",
"self",
".",
"enclosure",
".",
"mouth_viseme",
"(",
"time",
"(",
")",
",",
"pairs",
")"
] | [
143,
4
] | [
153,
54
] | python | en | ['en', 'id', 'en'] | True |
PlaybackThread.clear | (self) | Clear all pending actions for the TTS playback thread. | Clear all pending actions for the TTS playback thread. | def clear(self):
"""Clear all pending actions for the TTS playback thread."""
self.clear_queue() | [
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"clear_queue",
"(",
")"
] | [
155,
4
] | [
157,
26
] | python | en | ['en', 'en', 'en'] | True |
PlaybackThread.blink | (self, rate=1.0) | Blink mycroft's eyes | Blink mycroft's eyes | def blink(self, rate=1.0):
"""Blink mycroft's eyes"""
if self.enclosure and random.random() < rate:
self.enclosure.eyes_blink("b") | [
"def",
"blink",
"(",
"self",
",",
"rate",
"=",
"1.0",
")",
":",
"if",
"self",
".",
"enclosure",
"and",
"random",
".",
"random",
"(",
")",
"<",
"rate",
":",
"self",
".",
"enclosure",
".",
"eyes_blink",
"(",
"\"b\"",
")"
] | [
159,
4
] | [
162,
42
] | python | en | ['en', 'hu', 'en'] | True |
PlaybackThread.stop | (self) | Stop thread | Stop thread | def stop(self):
"""Stop thread"""
self._terminated = True
self.clear_queue() | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"_terminated",
"=",
"True",
"self",
".",
"clear_queue",
"(",
")"
] | [
164,
4
] | [
167,
26
] | python | en | ['en', 'sr', 'en'] | False |
TTS.load_spellings | (self) | Load phonetic spellings of words as dictionary | Load phonetic spellings of words as dictionary | def load_spellings(self):
"""Load phonetic spellings of words as dictionary"""
path = join('text', self.lang.lower(), 'phonetic_spellings.txt')
spellings_file = resolve_resource_file(path)
if not spellings_file:
return {}
try:
with open(spellings_file) as f:
lines = filter(bool, f.read().split('\n'))
lines = [i.split(':') for i in lines]
return {key.strip(): value.strip() for key, value in lines}
except ValueError:
LOG.exception('Failed to load phonetic spellings.')
return {} | [
"def",
"load_spellings",
"(",
"self",
")",
":",
"path",
"=",
"join",
"(",
"'text'",
",",
"self",
".",
"lang",
".",
"lower",
"(",
")",
",",
"'phonetic_spellings.txt'",
")",
"spellings_file",
"=",
"resolve_resource_file",
"(",
"path",
")",
"if",
"not",
"spellings_file",
":",
"return",
"{",
"}",
"try",
":",
"with",
"open",
"(",
"spellings_file",
")",
"as",
"f",
":",
"lines",
"=",
"filter",
"(",
"bool",
",",
"f",
".",
"read",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
")",
"lines",
"=",
"[",
"i",
".",
"split",
"(",
"':'",
")",
"for",
"i",
"in",
"lines",
"]",
"return",
"{",
"key",
".",
"strip",
"(",
")",
":",
"value",
".",
"strip",
"(",
")",
"for",
"key",
",",
"value",
"in",
"lines",
"}",
"except",
"ValueError",
":",
"LOG",
".",
"exception",
"(",
"'Failed to load phonetic spellings.'",
")",
"return",
"{",
"}"
] | [
227,
4
] | [
240,
21
] | python | en | ['en', 'en', 'en'] | True |
TTS.begin_audio | (self, ident=None) | Helper function for child classes to call in execute() | Helper function for child classes to call in execute() | def begin_audio(self, ident=None):
"""Helper function for child classes to call in execute()"""
# Create signals informing start of speech
self.bus.emit(Message("recognizer_loop:audio_output_start", context={"ident": ident})) | [
"def",
"begin_audio",
"(",
"self",
",",
"ident",
"=",
"None",
")",
":",
"# Create signals informing start of speech",
"self",
".",
"bus",
".",
"emit",
"(",
"Message",
"(",
"\"recognizer_loop:audio_output_start\"",
",",
"context",
"=",
"{",
"\"ident\"",
":",
"ident",
"}",
")",
")"
] | [
242,
4
] | [
245,
94
] | python | en | ['en', 'en', 'en'] | True |
TTS.end_audio | (self, listen=False, ident=None) | Helper function for child classes to call in execute().
Sends the recognizer_loop:audio_output_end message (indicating
that speaking is done for the moment) as well as trigger listening
if it has been requested. It also checks if cache directory needs
cleaning to free up disk space.
Arguments:
listen (bool): indication if listening trigger should be sent.
ident (str): Identifier of the input utterance associated with the response
| Helper function for child classes to call in execute(). | def end_audio(self, listen=False, ident=None):
"""Helper function for child classes to call in execute().
Sends the recognizer_loop:audio_output_end message (indicating
that speaking is done for the moment) as well as trigger listening
if it has been requested. It also checks if cache directory needs
cleaning to free up disk space.
Arguments:
listen (bool): indication if listening trigger should be sent.
ident (str): Identifier of the input utterance associated with the response
"""
self.bus.emit(Message("recognizer_loop:audio_output_end", context={"ident": ident}))
if listen:
self.bus.emit(Message('mycroft.mic.listen'))
# Clean the cache as needed
cache_dir = mycroft.util.get_cache_directory("tts/" + self.tts_name)
mycroft.util.curate_cache(cache_dir, min_free_percent=100)
# This check will clear the "signal"
check_for_signal("isSpeaking") | [
"def",
"end_audio",
"(",
"self",
",",
"listen",
"=",
"False",
",",
"ident",
"=",
"None",
")",
":",
"self",
".",
"bus",
".",
"emit",
"(",
"Message",
"(",
"\"recognizer_loop:audio_output_end\"",
",",
"context",
"=",
"{",
"\"ident\"",
":",
"ident",
"}",
")",
")",
"if",
"listen",
":",
"self",
".",
"bus",
".",
"emit",
"(",
"Message",
"(",
"'mycroft.mic.listen'",
")",
")",
"# Clean the cache as needed",
"cache_dir",
"=",
"mycroft",
".",
"util",
".",
"get_cache_directory",
"(",
"\"tts/\"",
"+",
"self",
".",
"tts_name",
")",
"mycroft",
".",
"util",
".",
"curate_cache",
"(",
"cache_dir",
",",
"min_free_percent",
"=",
"100",
")",
"# This check will clear the \"signal\"",
"check_for_signal",
"(",
"\"isSpeaking\"",
")"
] | [
247,
4
] | [
268,
38
] | python | en | ['en', 'en', 'en'] | True |
TTS.init | (self, bus) | Performs intial setup of TTS object.
Arguments:
bus: Mycroft messagebus connection
| Performs intial setup of TTS object. | def init(self, bus):
"""Performs intial setup of TTS object.
Arguments:
bus: Mycroft messagebus connection
"""
self.bus = bus
self.playback.init(self)
if EnclosureAPI:
self.enclosure = EnclosureAPI(self.bus)
self.playback.enclosure = self.enclosure | [
"def",
"init",
"(",
"self",
",",
"bus",
")",
":",
"self",
".",
"bus",
"=",
"bus",
"self",
".",
"playback",
".",
"init",
"(",
"self",
")",
"if",
"EnclosureAPI",
":",
"self",
".",
"enclosure",
"=",
"EnclosureAPI",
"(",
"self",
".",
"bus",
")",
"self",
".",
"playback",
".",
"enclosure",
"=",
"self",
".",
"enclosure"
] | [
270,
4
] | [
280,
52
] | python | en | ['en', 'en', 'en'] | True |
TTS.get_tts | (self, sentence, wav_file, request=None) | Abstract method that a tts implementation needs to implement.
Should get data from tts.
Arguments:
sentence(str): Sentence to synthesize
wav_file(str): output file
request(dict): Dict of tts request data
Returns:
tuple: (wav_file, phoneme)
| Abstract method that a tts implementation needs to implement. | def get_tts(self, sentence, wav_file, request=None):
"""Abstract method that a tts implementation needs to implement.
Should get data from tts.
Arguments:
sentence(str): Sentence to synthesize
wav_file(str): output file
request(dict): Dict of tts request data
Returns:
tuple: (wav_file, phoneme)
"""
pass | [
"def",
"get_tts",
"(",
"self",
",",
"sentence",
",",
"wav_file",
",",
"request",
"=",
"None",
")",
":",
"pass"
] | [
282,
4
] | [
295,
12
] | python | en | ['en', 'en', 'en'] | True |
TTS.modify_tag | (self, tag) | Override to modify each supported ssml tag | Override to modify each supported ssml tag | def modify_tag(self, tag):
"""Override to modify each supported ssml tag"""
return tag | [
"def",
"modify_tag",
"(",
"self",
",",
"tag",
")",
":",
"return",
"tag"
] | [
297,
4
] | [
299,
18
] | python | en | ['en', 'en', 'en'] | True |
TTS.validate_ssml | (self, utterance) | Check if engine supports ssml, if not remove all tags.
Remove unsupported / invalid tags
Arguments:
utterance(str): Sentence to validate
Returns:
validated_sentence (str)
| Check if engine supports ssml, if not remove all tags. | def validate_ssml(self, utterance):
"""Check if engine supports ssml, if not remove all tags.
Remove unsupported / invalid tags
Arguments:
utterance(str): Sentence to validate
Returns:
validated_sentence (str)
"""
# if ssml is not supported by TTS engine remove all tags
if not self.ssml_tags:
return self.remove_ssml(utterance)
# find ssml tags in string
tags = re.findall('<[^>]*>', utterance)
for tag in tags:
if any(supported in tag for supported in self.ssml_tags):
utterance = utterance.replace(tag, self.modify_tag(tag))
else:
# remove unsupported tag
utterance = utterance.replace(tag, "")
# return text with supported ssml tags only
return utterance.replace(" ", " ") | [
"def",
"validate_ssml",
"(",
"self",
",",
"utterance",
")",
":",
"# if ssml is not supported by TTS engine remove all tags",
"if",
"not",
"self",
".",
"ssml_tags",
":",
"return",
"self",
".",
"remove_ssml",
"(",
"utterance",
")",
"# find ssml tags in string",
"tags",
"=",
"re",
".",
"findall",
"(",
"'<[^>]*>'",
",",
"utterance",
")",
"for",
"tag",
"in",
"tags",
":",
"if",
"any",
"(",
"supported",
"in",
"tag",
"for",
"supported",
"in",
"self",
".",
"ssml_tags",
")",
":",
"utterance",
"=",
"utterance",
".",
"replace",
"(",
"tag",
",",
"self",
".",
"modify_tag",
"(",
"tag",
")",
")",
"else",
":",
"# remove unsupported tag",
"utterance",
"=",
"utterance",
".",
"replace",
"(",
"tag",
",",
"\"\"",
")",
"# return text with supported ssml tags only",
"return",
"utterance",
".",
"replace",
"(",
"\" \"",
",",
"\" \"",
")"
] | [
305,
4
] | [
331,
43
] | python | en | ['en', 'en', 'en'] | True |
TTS._preprocess_sentence | (self, sentence) | Default preprocessing is no preprocessing.
This method can be overridden to create chunks suitable to the
TTS engine in question.
Arguments:
sentence (str): sentence to preprocess
Returns:
list: list of sentence parts
| Default preprocessing is no preprocessing. | def _preprocess_sentence(self, sentence):
"""Default preprocessing is no preprocessing.
This method can be overridden to create chunks suitable to the
TTS engine in question.
Arguments:
sentence (str): sentence to preprocess
Returns:
list: list of sentence parts
"""
return [sentence] | [
"def",
"_preprocess_sentence",
"(",
"self",
",",
"sentence",
")",
":",
"return",
"[",
"sentence",
"]"
] | [
333,
4
] | [
345,
25
] | python | en | ['en', 'es', 'en'] | True |
TTS.execute | (self, sentence, ident=None, listen=False, message=None) | Convert sentence to speech, preprocessing out unsupported ssml
The method caches results if possible using the hash of the
sentence.
Arguments:
sentence: Sentence to be spoken
ident: Id reference to current interaction
listen: True if listen should be triggered at the end
of the utterance.
message: Message associated with request
| Convert sentence to speech, preprocessing out unsupported ssml | def execute(self, sentence, ident=None, listen=False, message=None):
"""Convert sentence to speech, preprocessing out unsupported ssml
The method caches results if possible using the hash of the
sentence.
Arguments:
sentence: Sentence to be spoken
ident: Id reference to current interaction
listen: True if listen should be triggered at the end
of the utterance.
message: Message associated with request
"""
sentence = self.validate_ssml(sentence)
# multi lang support
# NOTE this is kinda optional because skills will translate
# However speak messages might be sent directly to bus
# this is here to cover that use case
# # check for user specified language
# if message and hasattr(message, "user_data"):
# user_lang = message.user_data.get("lang") or self.language_config["user"]
# else:
# user_lang = self.language_config["user"]
#
# detected_lang = self.lang_detector.detect(sentence)
# LOG.debug("Detected language: {lang}".format(lang=detected_lang))
# if detected_lang != user_lang.split("-")[0]:
# sentence = self.translator.translate(sentence, user_lang)
create_signal("isSpeaking")
try:
return self._execute(sentence, ident, listen, message)
except Exception:
# If an error occurs end the audio sequence through an empty entry
self.queue.put(EMPTY_PLAYBACK_QUEUE_TUPLE)
# Re-raise to allow the Exception to be handled externally as well.
raise | [
"def",
"execute",
"(",
"self",
",",
"sentence",
",",
"ident",
"=",
"None",
",",
"listen",
"=",
"False",
",",
"message",
"=",
"None",
")",
":",
"sentence",
"=",
"self",
".",
"validate_ssml",
"(",
"sentence",
")",
"# multi lang support",
"# NOTE this is kinda optional because skills will translate",
"# However speak messages might be sent directly to bus",
"# this is here to cover that use case",
"# # check for user specified language",
"# if message and hasattr(message, \"user_data\"):",
"# user_lang = message.user_data.get(\"lang\") or self.language_config[\"user\"]",
"# else:",
"# user_lang = self.language_config[\"user\"]",
"#",
"# detected_lang = self.lang_detector.detect(sentence)",
"# LOG.debug(\"Detected language: {lang}\".format(lang=detected_lang))",
"# if detected_lang != user_lang.split(\"-\")[0]:",
"# sentence = self.translator.translate(sentence, user_lang)",
"create_signal",
"(",
"\"isSpeaking\"",
")",
"try",
":",
"return",
"self",
".",
"_execute",
"(",
"sentence",
",",
"ident",
",",
"listen",
",",
"message",
")",
"except",
"Exception",
":",
"# If an error occurs end the audio sequence through an empty entry",
"self",
".",
"queue",
".",
"put",
"(",
"EMPTY_PLAYBACK_QUEUE_TUPLE",
")",
"# Re-raise to allow the Exception to be handled externally as well.",
"raise"
] | [
347,
4
] | [
385,
17
] | python | en | ['en', 'en', 'en'] | True |
TTS.viseme | (self, phonemes) | Create visemes from phonemes. Needs to be implemented for all
tts backends.
Arguments:
phonemes(str): String with phoneme data
| Create visemes from phonemes. Needs to be implemented for all
tts backends. | def viseme(self, phonemes):
"""Create visemes from phonemes. Needs to be implemented for all
tts backends.
Arguments:
phonemes(str): String with phoneme data
"""
return None | [
"def",
"viseme",
"(",
"self",
",",
"phonemes",
")",
":",
"return",
"None"
] | [
544,
4
] | [
551,
19
] | python | en | ['en', 'en', 'en'] | True |
TTS.clear_cache | () | Remove all cached files. | Remove all cached files. | def clear_cache():
"""Remove all cached files."""
if not os.path.exists(mycroft.util.get_cache_directory('tts')):
return
for d in os.listdir(mycroft.util.get_cache_directory("tts")):
dir_path = os.path.join(mycroft.util.get_cache_directory("tts"), d)
if os.path.isdir(dir_path):
for f in os.listdir(dir_path):
file_path = os.path.join(dir_path, f)
if os.path.isfile(file_path):
os.unlink(file_path)
# If no sub-folders are present, check if it is a file & clear it
elif os.path.isfile(dir_path):
os.unlink(dir_path) | [
"def",
"clear_cache",
"(",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"mycroft",
".",
"util",
".",
"get_cache_directory",
"(",
"'tts'",
")",
")",
":",
"return",
"for",
"d",
"in",
"os",
".",
"listdir",
"(",
"mycroft",
".",
"util",
".",
"get_cache_directory",
"(",
"\"tts\"",
")",
")",
":",
"dir_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"mycroft",
".",
"util",
".",
"get_cache_directory",
"(",
"\"tts\"",
")",
",",
"d",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"dir_path",
")",
":",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"dir_path",
")",
":",
"file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dir_path",
",",
"f",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"file_path",
")",
":",
"os",
".",
"unlink",
"(",
"file_path",
")",
"# If no sub-folders are present, check if it is a file & clear it",
"elif",
"os",
".",
"path",
".",
"isfile",
"(",
"dir_path",
")",
":",
"os",
".",
"unlink",
"(",
"dir_path",
")"
] | [
554,
4
] | [
567,
35
] | python | en | ['en', 'en', 'en'] | True |
TTS.save_phonemes | (self, key, phonemes) | Cache phonemes
Arguments:
key: Hash key for the sentence
phonemes: phoneme string to save
| Cache phonemes | def save_phonemes(self, key, phonemes):
"""Cache phonemes
Arguments:
key: Hash key for the sentence
phonemes: phoneme string to save
"""
cache_dir = mycroft.util.get_cache_directory("tts/" + self.tts_name)
pho_file = os.path.join(cache_dir, key + ".pho")
try:
with open(pho_file, "w") as cachefile:
cachefile.write(phonemes)
except Exception as e:
LOG.error(e)
LOG.exception("Failed to write {} to cache".format(pho_file))
pass | [
"def",
"save_phonemes",
"(",
"self",
",",
"key",
",",
"phonemes",
")",
":",
"cache_dir",
"=",
"mycroft",
".",
"util",
".",
"get_cache_directory",
"(",
"\"tts/\"",
"+",
"self",
".",
"tts_name",
")",
"pho_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"cache_dir",
",",
"key",
"+",
"\".pho\"",
")",
"try",
":",
"with",
"open",
"(",
"pho_file",
",",
"\"w\"",
")",
"as",
"cachefile",
":",
"cachefile",
".",
"write",
"(",
"phonemes",
")",
"except",
"Exception",
"as",
"e",
":",
"LOG",
".",
"error",
"(",
"e",
")",
"LOG",
".",
"exception",
"(",
"\"Failed to write {} to cache\"",
".",
"format",
"(",
"pho_file",
")",
")",
"pass"
] | [
569,
4
] | [
584,
16
] | python | en | ['en', 'en', 'it'] | False |
TTS.load_phonemes | (self, key) | Load phonemes from cache file.
Arguments:
key: Key identifying phoneme cache
| Load phonemes from cache file. | def load_phonemes(self, key):
"""Load phonemes from cache file.
Arguments:
key: Key identifying phoneme cache
"""
pho_file = os.path.join(
mycroft.util.get_cache_directory("tts/" + self.tts_name),
key + ".pho")
if os.path.exists(pho_file):
try:
with open(pho_file, "r") as cachefile:
phonemes = cachefile.read().strip()
return phonemes
except Exception as e:
LOG.error(e)
LOG.debug("Failed to read .PHO from cache")
return None | [
"def",
"load_phonemes",
"(",
"self",
",",
"key",
")",
":",
"pho_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"mycroft",
".",
"util",
".",
"get_cache_directory",
"(",
"\"tts/\"",
"+",
"self",
".",
"tts_name",
")",
",",
"key",
"+",
"\".pho\"",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"pho_file",
")",
":",
"try",
":",
"with",
"open",
"(",
"pho_file",
",",
"\"r\"",
")",
"as",
"cachefile",
":",
"phonemes",
"=",
"cachefile",
".",
"read",
"(",
")",
".",
"strip",
"(",
")",
"return",
"phonemes",
"except",
"Exception",
"as",
"e",
":",
"LOG",
".",
"error",
"(",
"e",
")",
"LOG",
".",
"debug",
"(",
"\"Failed to read .PHO from cache\"",
")",
"return",
"None"
] | [
586,
4
] | [
603,
19
] | python | en | ['en', 'en', 'en'] | True |
TTSFactory.create | (config=None) | Factory method to create a TTS engine based on configuration.
The configuration file ``mycroft.conf`` contains a ``tts`` section with
the name of a TTS module to be read by this method.
"tts": {
"module": <engine_name>
}
| Factory method to create a TTS engine based on configuration. | def create(config=None):
"""Factory method to create a TTS engine based on configuration.
The configuration file ``mycroft.conf`` contains a ``tts`` section with
the name of a TTS module to be read by this method.
"tts": {
"module": <engine_name>
}
"""
config = config or get_neon_audio_config()
lang = config.get("language", {}).get("user") or config.get("lang", "en-us")
tts_module = config.get('tts', {}).get('module', 'mimic')
tts_config = config.get('tts', {}).get(tts_module, {})
tts_lang = tts_config.get('lang', lang)
try:
if tts_module in TTSFactory.CLASSES:
clazz = TTSFactory.CLASSES[tts_module]
else:
clazz = load_tts_plugin(tts_module)
LOG.info('Loaded plugin {}'.format(tts_module))
if clazz is None:
raise ValueError('TTS module not found')
tts = clazz(tts_lang, tts_config)
tts.validator.validate()
except Exception as e:
LOG.error(e)
# Fallback to mimic if an error occurs while loading.
if tts_module != 'mimic':
LOG.exception('The selected TTS backend couldn\'t be loaded. '
'Falling back to Mimic')
clazz = TTSFactory.CLASSES.get('mimic')
tts = clazz(tts_lang, tts_config)
tts.validator.validate()
else:
LOG.exception('The TTS could not be loaded.')
raise
return tts | [
"def",
"create",
"(",
"config",
"=",
"None",
")",
":",
"config",
"=",
"config",
"or",
"get_neon_audio_config",
"(",
")",
"lang",
"=",
"config",
".",
"get",
"(",
"\"language\"",
",",
"{",
"}",
")",
".",
"get",
"(",
"\"user\"",
")",
"or",
"config",
".",
"get",
"(",
"\"lang\"",
",",
"\"en-us\"",
")",
"tts_module",
"=",
"config",
".",
"get",
"(",
"'tts'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'module'",
",",
"'mimic'",
")",
"tts_config",
"=",
"config",
".",
"get",
"(",
"'tts'",
",",
"{",
"}",
")",
".",
"get",
"(",
"tts_module",
",",
"{",
"}",
")",
"tts_lang",
"=",
"tts_config",
".",
"get",
"(",
"'lang'",
",",
"lang",
")",
"try",
":",
"if",
"tts_module",
"in",
"TTSFactory",
".",
"CLASSES",
":",
"clazz",
"=",
"TTSFactory",
".",
"CLASSES",
"[",
"tts_module",
"]",
"else",
":",
"clazz",
"=",
"load_tts_plugin",
"(",
"tts_module",
")",
"LOG",
".",
"info",
"(",
"'Loaded plugin {}'",
".",
"format",
"(",
"tts_module",
")",
")",
"if",
"clazz",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'TTS module not found'",
")",
"tts",
"=",
"clazz",
"(",
"tts_lang",
",",
"tts_config",
")",
"tts",
".",
"validator",
".",
"validate",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"LOG",
".",
"error",
"(",
"e",
")",
"# Fallback to mimic if an error occurs while loading.",
"if",
"tts_module",
"!=",
"'mimic'",
":",
"LOG",
".",
"exception",
"(",
"'The selected TTS backend couldn\\'t be loaded. '",
"'Falling back to Mimic'",
")",
"clazz",
"=",
"TTSFactory",
".",
"CLASSES",
".",
"get",
"(",
"'mimic'",
")",
"tts",
"=",
"clazz",
"(",
"tts_lang",
",",
"tts_config",
")",
"tts",
".",
"validator",
".",
"validate",
"(",
")",
"else",
":",
"LOG",
".",
"exception",
"(",
"'The TTS could not be loaded.'",
")",
"raise",
"return",
"tts"
] | [
667,
4
] | [
706,
18
] | python | en | ['en', 'en', 'en'] | True |
test_invalid_message_format | (websocket_client) | Test sending invalid JSON. | Test sending invalid JSON. | async def test_invalid_message_format(websocket_client):
"""Test sending invalid JSON."""
await websocket_client.send_json({"type": 5})
msg = await websocket_client.receive_json()
assert msg["type"] == const.TYPE_RESULT
error = msg["error"]
assert error["code"] == const.ERR_INVALID_FORMAT
assert error["message"].startswith("Message incorrectly formatted") | [
"async",
"def",
"test_invalid_message_format",
"(",
"websocket_client",
")",
":",
"await",
"websocket_client",
".",
"send_json",
"(",
"{",
"\"type\"",
":",
"5",
"}",
")",
"msg",
"=",
"await",
"websocket_client",
".",
"receive_json",
"(",
")",
"assert",
"msg",
"[",
"\"type\"",
"]",
"==",
"const",
".",
"TYPE_RESULT",
"error",
"=",
"msg",
"[",
"\"error\"",
"]",
"assert",
"error",
"[",
"\"code\"",
"]",
"==",
"const",
".",
"ERR_INVALID_FORMAT",
"assert",
"error",
"[",
"\"message\"",
"]",
".",
"startswith",
"(",
"\"Message incorrectly formatted\"",
")"
] | [
9,
0
] | [
18,
71
] | python | en | ['en', 'da', 'en'] | True |
test_invalid_json | (websocket_client) | Test sending invalid JSON. | Test sending invalid JSON. | async def test_invalid_json(websocket_client):
"""Test sending invalid JSON."""
await websocket_client.send_str("this is not JSON")
msg = await websocket_client.receive()
assert msg.type == WSMsgType.close | [
"async",
"def",
"test_invalid_json",
"(",
"websocket_client",
")",
":",
"await",
"websocket_client",
".",
"send_str",
"(",
"\"this is not JSON\"",
")",
"msg",
"=",
"await",
"websocket_client",
".",
"receive",
"(",
")",
"assert",
"msg",
".",
"type",
"==",
"WSMsgType",
".",
"close"
] | [
21,
0
] | [
27,
38
] | python | en | ['en', 'da', 'en'] | True |
test_quiting_hass | (hass, websocket_client) | Test sending invalid JSON. | Test sending invalid JSON. | async def test_quiting_hass(hass, websocket_client):
"""Test sending invalid JSON."""
with patch.object(hass.loop, "stop"):
await hass.async_stop()
msg = await websocket_client.receive()
assert msg.type == WSMsgType.CLOSE | [
"async",
"def",
"test_quiting_hass",
"(",
"hass",
",",
"websocket_client",
")",
":",
"with",
"patch",
".",
"object",
"(",
"hass",
".",
"loop",
",",
"\"stop\"",
")",
":",
"await",
"hass",
".",
"async_stop",
"(",
")",
"msg",
"=",
"await",
"websocket_client",
".",
"receive",
"(",
")",
"assert",
"msg",
".",
"type",
"==",
"WSMsgType",
".",
"CLOSE"
] | [
30,
0
] | [
37,
38
] | python | en | ['en', 'da', 'en'] | True |
test_unknown_command | (websocket_client) | Test get_panels command. | Test get_panels command. | async def test_unknown_command(websocket_client):
"""Test get_panels command."""
await websocket_client.send_json({"id": 5, "type": "unknown_command"})
msg = await websocket_client.receive_json()
assert not msg["success"]
assert msg["error"]["code"] == const.ERR_UNKNOWN_COMMAND | [
"async",
"def",
"test_unknown_command",
"(",
"websocket_client",
")",
":",
"await",
"websocket_client",
".",
"send_json",
"(",
"{",
"\"id\"",
":",
"5",
",",
"\"type\"",
":",
"\"unknown_command\"",
"}",
")",
"msg",
"=",
"await",
"websocket_client",
".",
"receive_json",
"(",
")",
"assert",
"not",
"msg",
"[",
"\"success\"",
"]",
"assert",
"msg",
"[",
"\"error\"",
"]",
"[",
"\"code\"",
"]",
"==",
"const",
".",
"ERR_UNKNOWN_COMMAND"
] | [
40,
0
] | [
46,
60
] | python | en | ['nl', 'en', 'en'] | True |
test_handler_failing | (hass, websocket_client) | Test a command that raises. | Test a command that raises. | async def test_handler_failing(hass, websocket_client):
"""Test a command that raises."""
hass.components.websocket_api.async_register_command(
"bla",
Mock(side_effect=TypeError),
messages.BASE_COMMAND_MESSAGE_SCHEMA.extend({"type": "bla"}),
)
await websocket_client.send_json({"id": 5, "type": "bla"})
msg = await websocket_client.receive_json()
assert msg["id"] == 5
assert msg["type"] == const.TYPE_RESULT
assert not msg["success"]
assert msg["error"]["code"] == const.ERR_UNKNOWN_ERROR | [
"async",
"def",
"test_handler_failing",
"(",
"hass",
",",
"websocket_client",
")",
":",
"hass",
".",
"components",
".",
"websocket_api",
".",
"async_register_command",
"(",
"\"bla\"",
",",
"Mock",
"(",
"side_effect",
"=",
"TypeError",
")",
",",
"messages",
".",
"BASE_COMMAND_MESSAGE_SCHEMA",
".",
"extend",
"(",
"{",
"\"type\"",
":",
"\"bla\"",
"}",
")",
",",
")",
"await",
"websocket_client",
".",
"send_json",
"(",
"{",
"\"id\"",
":",
"5",
",",
"\"type\"",
":",
"\"bla\"",
"}",
")",
"msg",
"=",
"await",
"websocket_client",
".",
"receive_json",
"(",
")",
"assert",
"msg",
"[",
"\"id\"",
"]",
"==",
"5",
"assert",
"msg",
"[",
"\"type\"",
"]",
"==",
"const",
".",
"TYPE_RESULT",
"assert",
"not",
"msg",
"[",
"\"success\"",
"]",
"assert",
"msg",
"[",
"\"error\"",
"]",
"[",
"\"code\"",
"]",
"==",
"const",
".",
"ERR_UNKNOWN_ERROR"
] | [
49,
0
] | [
62,
58
] | python | en | ['en', 'fr', 'en'] | True |
test_invalid_vol | (hass, websocket_client) | Test a command that raises invalid vol error. | Test a command that raises invalid vol error. | async def test_invalid_vol(hass, websocket_client):
"""Test a command that raises invalid vol error."""
hass.components.websocket_api.async_register_command(
"bla",
Mock(side_effect=TypeError),
messages.BASE_COMMAND_MESSAGE_SCHEMA.extend(
{"type": "bla", vol.Required("test_config"): str}
),
)
await websocket_client.send_json({"id": 5, "type": "bla", "test_config": 5})
msg = await websocket_client.receive_json()
assert msg["id"] == 5
assert msg["type"] == const.TYPE_RESULT
assert not msg["success"]
assert msg["error"]["code"] == const.ERR_INVALID_FORMAT
assert "expected str for dictionary value" in msg["error"]["message"] | [
"async",
"def",
"test_invalid_vol",
"(",
"hass",
",",
"websocket_client",
")",
":",
"hass",
".",
"components",
".",
"websocket_api",
".",
"async_register_command",
"(",
"\"bla\"",
",",
"Mock",
"(",
"side_effect",
"=",
"TypeError",
")",
",",
"messages",
".",
"BASE_COMMAND_MESSAGE_SCHEMA",
".",
"extend",
"(",
"{",
"\"type\"",
":",
"\"bla\"",
",",
"vol",
".",
"Required",
"(",
"\"test_config\"",
")",
":",
"str",
"}",
")",
",",
")",
"await",
"websocket_client",
".",
"send_json",
"(",
"{",
"\"id\"",
":",
"5",
",",
"\"type\"",
":",
"\"bla\"",
",",
"\"test_config\"",
":",
"5",
"}",
")",
"msg",
"=",
"await",
"websocket_client",
".",
"receive_json",
"(",
")",
"assert",
"msg",
"[",
"\"id\"",
"]",
"==",
"5",
"assert",
"msg",
"[",
"\"type\"",
"]",
"==",
"const",
".",
"TYPE_RESULT",
"assert",
"not",
"msg",
"[",
"\"success\"",
"]",
"assert",
"msg",
"[",
"\"error\"",
"]",
"[",
"\"code\"",
"]",
"==",
"const",
".",
"ERR_INVALID_FORMAT",
"assert",
"\"expected str for dictionary value\"",
"in",
"msg",
"[",
"\"error\"",
"]",
"[",
"\"message\"",
"]"
] | [
65,
0
] | [
82,
73
] | python | en | ['en', 'fr', 'en'] | True |
test_scenes | (hass, generic_data, sent_messages) | Test setting up config entry. | Test setting up config entry. | async def test_scenes(hass, generic_data, sent_messages):
"""Test setting up config entry."""
receive_message = await setup_ozw(hass, fixture=generic_data)
events = async_capture_events(hass, "ozw.scene_activated")
# Publish fake scene event on mqtt
message = MQTTMessage(
topic="OpenZWave/1/node/39/instance/1/commandclass/43/value/562950622511127/",
payload={
"Label": "Scene",
"Value": 16,
"Units": "",
"Min": -2147483648,
"Max": 2147483647,
"Type": "Int",
"Instance": 1,
"CommandClass": "COMMAND_CLASS_SCENE_ACTIVATION",
"Index": 0,
"Node": 7,
"Genre": "User",
"Help": "",
"ValueIDKey": 122339347,
"ReadOnly": False,
"WriteOnly": False,
"ValueSet": False,
"ValuePolled": False,
"ChangeVerified": False,
"Event": "valueChanged",
"TimeStamp": 1579630367,
},
)
message.encode()
receive_message(message)
# wait for the event
await hass.async_block_till_done()
assert len(events) == 1
assert events[0].data["scene_value_id"] == 16
# Publish fake central scene event on mqtt
message = MQTTMessage(
topic="OpenZWave/1/node/39/instance/1/commandclass/91/value/281476005806100/",
payload={
"Label": "Scene 1",
"Value": {
"List": [
{"Value": 0, "Label": "Inactive"},
{"Value": 1, "Label": "Pressed 1 Time"},
{"Value": 2, "Label": "Key Released"},
{"Value": 3, "Label": "Key Held down"},
],
"Selected": "Pressed 1 Time",
"Selected_id": 1,
},
"Units": "",
"Min": 0,
"Max": 0,
"Type": "List",
"Instance": 1,
"CommandClass": "COMMAND_CLASS_CENTRAL_SCENE",
"Index": 1,
"Node": 61,
"Genre": "User",
"Help": "",
"ValueIDKey": 281476005806100,
"ReadOnly": False,
"WriteOnly": False,
"ValueSet": False,
"ValuePolled": False,
"ChangeVerified": False,
"Event": "valueChanged",
"TimeStamp": 1579640710,
},
)
message.encode()
receive_message(message)
# wait for the event
await hass.async_block_till_done()
assert len(events) == 2
assert events[1].data["scene_id"] == 1
assert events[1].data["scene_label"] == "Scene 1"
assert events[1].data["scene_value_label"] == "Pressed 1 Time" | [
"async",
"def",
"test_scenes",
"(",
"hass",
",",
"generic_data",
",",
"sent_messages",
")",
":",
"receive_message",
"=",
"await",
"setup_ozw",
"(",
"hass",
",",
"fixture",
"=",
"generic_data",
")",
"events",
"=",
"async_capture_events",
"(",
"hass",
",",
"\"ozw.scene_activated\"",
")",
"# Publish fake scene event on mqtt",
"message",
"=",
"MQTTMessage",
"(",
"topic",
"=",
"\"OpenZWave/1/node/39/instance/1/commandclass/43/value/562950622511127/\"",
",",
"payload",
"=",
"{",
"\"Label\"",
":",
"\"Scene\"",
",",
"\"Value\"",
":",
"16",
",",
"\"Units\"",
":",
"\"\"",
",",
"\"Min\"",
":",
"-",
"2147483648",
",",
"\"Max\"",
":",
"2147483647",
",",
"\"Type\"",
":",
"\"Int\"",
",",
"\"Instance\"",
":",
"1",
",",
"\"CommandClass\"",
":",
"\"COMMAND_CLASS_SCENE_ACTIVATION\"",
",",
"\"Index\"",
":",
"0",
",",
"\"Node\"",
":",
"7",
",",
"\"Genre\"",
":",
"\"User\"",
",",
"\"Help\"",
":",
"\"\"",
",",
"\"ValueIDKey\"",
":",
"122339347",
",",
"\"ReadOnly\"",
":",
"False",
",",
"\"WriteOnly\"",
":",
"False",
",",
"\"ValueSet\"",
":",
"False",
",",
"\"ValuePolled\"",
":",
"False",
",",
"\"ChangeVerified\"",
":",
"False",
",",
"\"Event\"",
":",
"\"valueChanged\"",
",",
"\"TimeStamp\"",
":",
"1579630367",
",",
"}",
",",
")",
"message",
".",
"encode",
"(",
")",
"receive_message",
"(",
"message",
")",
"# wait for the event",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"len",
"(",
"events",
")",
"==",
"1",
"assert",
"events",
"[",
"0",
"]",
".",
"data",
"[",
"\"scene_value_id\"",
"]",
"==",
"16",
"# Publish fake central scene event on mqtt",
"message",
"=",
"MQTTMessage",
"(",
"topic",
"=",
"\"OpenZWave/1/node/39/instance/1/commandclass/91/value/281476005806100/\"",
",",
"payload",
"=",
"{",
"\"Label\"",
":",
"\"Scene 1\"",
",",
"\"Value\"",
":",
"{",
"\"List\"",
":",
"[",
"{",
"\"Value\"",
":",
"0",
",",
"\"Label\"",
":",
"\"Inactive\"",
"}",
",",
"{",
"\"Value\"",
":",
"1",
",",
"\"Label\"",
":",
"\"Pressed 1 Time\"",
"}",
",",
"{",
"\"Value\"",
":",
"2",
",",
"\"Label\"",
":",
"\"Key Released\"",
"}",
",",
"{",
"\"Value\"",
":",
"3",
",",
"\"Label\"",
":",
"\"Key Held down\"",
"}",
",",
"]",
",",
"\"Selected\"",
":",
"\"Pressed 1 Time\"",
",",
"\"Selected_id\"",
":",
"1",
",",
"}",
",",
"\"Units\"",
":",
"\"\"",
",",
"\"Min\"",
":",
"0",
",",
"\"Max\"",
":",
"0",
",",
"\"Type\"",
":",
"\"List\"",
",",
"\"Instance\"",
":",
"1",
",",
"\"CommandClass\"",
":",
"\"COMMAND_CLASS_CENTRAL_SCENE\"",
",",
"\"Index\"",
":",
"1",
",",
"\"Node\"",
":",
"61",
",",
"\"Genre\"",
":",
"\"User\"",
",",
"\"Help\"",
":",
"\"\"",
",",
"\"ValueIDKey\"",
":",
"281476005806100",
",",
"\"ReadOnly\"",
":",
"False",
",",
"\"WriteOnly\"",
":",
"False",
",",
"\"ValueSet\"",
":",
"False",
",",
"\"ValuePolled\"",
":",
"False",
",",
"\"ChangeVerified\"",
":",
"False",
",",
"\"Event\"",
":",
"\"valueChanged\"",
",",
"\"TimeStamp\"",
":",
"1579640710",
",",
"}",
",",
")",
"message",
".",
"encode",
"(",
")",
"receive_message",
"(",
"message",
")",
"# wait for the event",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"len",
"(",
"events",
")",
"==",
"2",
"assert",
"events",
"[",
"1",
"]",
".",
"data",
"[",
"\"scene_id\"",
"]",
"==",
"1",
"assert",
"events",
"[",
"1",
"]",
".",
"data",
"[",
"\"scene_label\"",
"]",
"==",
"\"Scene 1\"",
"assert",
"events",
"[",
"1",
"]",
".",
"data",
"[",
"\"scene_value_label\"",
"]",
"==",
"\"Pressed 1 Time\""
] | [
6,
0
] | [
87,
66
] | python | en | ['en', 'en', 'en'] | True |
async_setup | (hass, config) | Set up the Plant component. | Set up the Plant component. | async def async_setup(hass, config):
"""Set up the Plant component."""
component = EntityComponent(_LOGGER, DOMAIN, hass)
entities = []
for plant_name, plant_config in config[DOMAIN].items():
_LOGGER.info("Added plant %s", plant_name)
entity = Plant(plant_name, plant_config)
entities.append(entity)
await component.async_add_entities(entities)
return True | [
"async",
"def",
"async_setup",
"(",
"hass",
",",
"config",
")",
":",
"component",
"=",
"EntityComponent",
"(",
"_LOGGER",
",",
"DOMAIN",
",",
"hass",
")",
"entities",
"=",
"[",
"]",
"for",
"plant_name",
",",
"plant_config",
"in",
"config",
"[",
"DOMAIN",
"]",
".",
"items",
"(",
")",
":",
"_LOGGER",
".",
"info",
"(",
"\"Added plant %s\"",
",",
"plant_name",
")",
"entity",
"=",
"Plant",
"(",
"plant_name",
",",
"plant_config",
")",
"entities",
".",
"append",
"(",
"entity",
")",
"await",
"component",
".",
"async_add_entities",
"(",
"entities",
")",
"return",
"True"
] | [
114,
0
] | [
125,
15
] | python | en | ['en', 'en', 'en'] | True |
Plant.__init__ | (self, name, config) | Initialize the Plant component. | Initialize the Plant component. | def __init__(self, name, config):
"""Initialize the Plant component."""
self._config = config
self._sensormap = {}
self._readingmap = {}
self._unit_of_measurement = {}
for reading, entity_id in config["sensors"].items():
self._sensormap[entity_id] = reading
self._readingmap[reading] = entity_id
self._state = None
self._name = name
self._battery = None
self._moisture = None
self._conductivity = None
self._temperature = None
self._brightness = None
self._problems = PROBLEM_NONE
self._conf_check_days = 3 # default check interval: 3 days
if CONF_CHECK_DAYS in self._config:
self._conf_check_days = self._config[CONF_CHECK_DAYS]
self._brightness_history = DailyHistory(self._conf_check_days) | [
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"config",
")",
":",
"self",
".",
"_config",
"=",
"config",
"self",
".",
"_sensormap",
"=",
"{",
"}",
"self",
".",
"_readingmap",
"=",
"{",
"}",
"self",
".",
"_unit_of_measurement",
"=",
"{",
"}",
"for",
"reading",
",",
"entity_id",
"in",
"config",
"[",
"\"sensors\"",
"]",
".",
"items",
"(",
")",
":",
"self",
".",
"_sensormap",
"[",
"entity_id",
"]",
"=",
"reading",
"self",
".",
"_readingmap",
"[",
"reading",
"]",
"=",
"entity_id",
"self",
".",
"_state",
"=",
"None",
"self",
".",
"_name",
"=",
"name",
"self",
".",
"_battery",
"=",
"None",
"self",
".",
"_moisture",
"=",
"None",
"self",
".",
"_conductivity",
"=",
"None",
"self",
".",
"_temperature",
"=",
"None",
"self",
".",
"_brightness",
"=",
"None",
"self",
".",
"_problems",
"=",
"PROBLEM_NONE",
"self",
".",
"_conf_check_days",
"=",
"3",
"# default check interval: 3 days",
"if",
"CONF_CHECK_DAYS",
"in",
"self",
".",
"_config",
":",
"self",
".",
"_conf_check_days",
"=",
"self",
".",
"_config",
"[",
"CONF_CHECK_DAYS",
"]",
"self",
".",
"_brightness_history",
"=",
"DailyHistory",
"(",
"self",
".",
"_conf_check_days",
")"
] | [
162,
4
] | [
183,
70
] | python | en | ['en', 'en', 'en'] | True |
Plant._state_changed_event | (self, event) | Sensor state change event. | Sensor state change event. | def _state_changed_event(self, event):
"""Sensor state change event."""
self.state_changed(event.data.get("entity_id"), event.data.get("new_state")) | [
"def",
"_state_changed_event",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"state_changed",
"(",
"event",
".",
"data",
".",
"get",
"(",
"\"entity_id\"",
")",
",",
"event",
".",
"data",
".",
"get",
"(",
"\"new_state\"",
")",
")"
] | [
186,
4
] | [
188,
84
] | python | bs | ['es', 'bs', 'en'] | False |
Plant.state_changed | (self, entity_id, new_state) | Update the sensor status. | Update the sensor status. | def state_changed(self, entity_id, new_state):
"""Update the sensor status."""
if new_state is None:
return
value = new_state.state
_LOGGER.debug("Received callback from %s with value %s", entity_id, value)
if value == STATE_UNKNOWN:
return
reading = self._sensormap[entity_id]
if reading == READING_MOISTURE:
if value != STATE_UNAVAILABLE:
value = int(float(value))
self._moisture = value
elif reading == READING_BATTERY:
if value != STATE_UNAVAILABLE:
value = int(float(value))
self._battery = value
elif reading == READING_TEMPERATURE:
if value != STATE_UNAVAILABLE:
value = float(value)
self._temperature = value
elif reading == READING_CONDUCTIVITY:
if value != STATE_UNAVAILABLE:
value = int(float(value))
self._conductivity = value
elif reading == READING_BRIGHTNESS:
if value != STATE_UNAVAILABLE:
value = int(float(value))
self._brightness = value
self._brightness_history.add_measurement(
self._brightness, new_state.last_updated
)
else:
raise HomeAssistantError(
f"Unknown reading from sensor {entity_id}: {value}"
)
if ATTR_UNIT_OF_MEASUREMENT in new_state.attributes:
self._unit_of_measurement[reading] = new_state.attributes.get(
ATTR_UNIT_OF_MEASUREMENT
)
self._update_state() | [
"def",
"state_changed",
"(",
"self",
",",
"entity_id",
",",
"new_state",
")",
":",
"if",
"new_state",
"is",
"None",
":",
"return",
"value",
"=",
"new_state",
".",
"state",
"_LOGGER",
".",
"debug",
"(",
"\"Received callback from %s with value %s\"",
",",
"entity_id",
",",
"value",
")",
"if",
"value",
"==",
"STATE_UNKNOWN",
":",
"return",
"reading",
"=",
"self",
".",
"_sensormap",
"[",
"entity_id",
"]",
"if",
"reading",
"==",
"READING_MOISTURE",
":",
"if",
"value",
"!=",
"STATE_UNAVAILABLE",
":",
"value",
"=",
"int",
"(",
"float",
"(",
"value",
")",
")",
"self",
".",
"_moisture",
"=",
"value",
"elif",
"reading",
"==",
"READING_BATTERY",
":",
"if",
"value",
"!=",
"STATE_UNAVAILABLE",
":",
"value",
"=",
"int",
"(",
"float",
"(",
"value",
")",
")",
"self",
".",
"_battery",
"=",
"value",
"elif",
"reading",
"==",
"READING_TEMPERATURE",
":",
"if",
"value",
"!=",
"STATE_UNAVAILABLE",
":",
"value",
"=",
"float",
"(",
"value",
")",
"self",
".",
"_temperature",
"=",
"value",
"elif",
"reading",
"==",
"READING_CONDUCTIVITY",
":",
"if",
"value",
"!=",
"STATE_UNAVAILABLE",
":",
"value",
"=",
"int",
"(",
"float",
"(",
"value",
")",
")",
"self",
".",
"_conductivity",
"=",
"value",
"elif",
"reading",
"==",
"READING_BRIGHTNESS",
":",
"if",
"value",
"!=",
"STATE_UNAVAILABLE",
":",
"value",
"=",
"int",
"(",
"float",
"(",
"value",
")",
")",
"self",
".",
"_brightness",
"=",
"value",
"self",
".",
"_brightness_history",
".",
"add_measurement",
"(",
"self",
".",
"_brightness",
",",
"new_state",
".",
"last_updated",
")",
"else",
":",
"raise",
"HomeAssistantError",
"(",
"f\"Unknown reading from sensor {entity_id}: {value}\"",
")",
"if",
"ATTR_UNIT_OF_MEASUREMENT",
"in",
"new_state",
".",
"attributes",
":",
"self",
".",
"_unit_of_measurement",
"[",
"reading",
"]",
"=",
"new_state",
".",
"attributes",
".",
"get",
"(",
"ATTR_UNIT_OF_MEASUREMENT",
")",
"self",
".",
"_update_state",
"(",
")"
] | [
191,
4
] | [
232,
28
] | python | en | ['en', 'id', 'en'] | True |
Plant._update_state | (self) | Update the state of the class based sensor data. | Update the state of the class based sensor data. | def _update_state(self):
"""Update the state of the class based sensor data."""
result = []
for sensor_name in self._sensormap.values():
params = self.READINGS[sensor_name]
value = getattr(self, f"_{sensor_name}")
if value is not None:
if value == STATE_UNAVAILABLE:
result.append(f"{sensor_name} unavailable")
else:
if sensor_name == READING_BRIGHTNESS:
result.append(
self._check_min(
sensor_name, self._brightness_history.max, params
)
)
else:
result.append(self._check_min(sensor_name, value, params))
result.append(self._check_max(sensor_name, value, params))
result = [r for r in result if r is not None]
if result:
self._state = STATE_PROBLEM
self._problems = ", ".join(result)
else:
self._state = STATE_OK
self._problems = PROBLEM_NONE
_LOGGER.debug("New data processed")
self.async_write_ha_state() | [
"def",
"_update_state",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"for",
"sensor_name",
"in",
"self",
".",
"_sensormap",
".",
"values",
"(",
")",
":",
"params",
"=",
"self",
".",
"READINGS",
"[",
"sensor_name",
"]",
"value",
"=",
"getattr",
"(",
"self",
",",
"f\"_{sensor_name}\"",
")",
"if",
"value",
"is",
"not",
"None",
":",
"if",
"value",
"==",
"STATE_UNAVAILABLE",
":",
"result",
".",
"append",
"(",
"f\"{sensor_name} unavailable\"",
")",
"else",
":",
"if",
"sensor_name",
"==",
"READING_BRIGHTNESS",
":",
"result",
".",
"append",
"(",
"self",
".",
"_check_min",
"(",
"sensor_name",
",",
"self",
".",
"_brightness_history",
".",
"max",
",",
"params",
")",
")",
"else",
":",
"result",
".",
"append",
"(",
"self",
".",
"_check_min",
"(",
"sensor_name",
",",
"value",
",",
"params",
")",
")",
"result",
".",
"append",
"(",
"self",
".",
"_check_max",
"(",
"sensor_name",
",",
"value",
",",
"params",
")",
")",
"result",
"=",
"[",
"r",
"for",
"r",
"in",
"result",
"if",
"r",
"is",
"not",
"None",
"]",
"if",
"result",
":",
"self",
".",
"_state",
"=",
"STATE_PROBLEM",
"self",
".",
"_problems",
"=",
"\", \"",
".",
"join",
"(",
"result",
")",
"else",
":",
"self",
".",
"_state",
"=",
"STATE_OK",
"self",
".",
"_problems",
"=",
"PROBLEM_NONE",
"_LOGGER",
".",
"debug",
"(",
"\"New data processed\"",
")",
"self",
".",
"async_write_ha_state",
"(",
")"
] | [
234,
4
] | [
263,
35
] | python | en | ['en', 'en', 'en'] | True |
Plant._check_min | (self, sensor_name, value, params) | If configured, check the value against the defined minimum value. | If configured, check the value against the defined minimum value. | def _check_min(self, sensor_name, value, params):
"""If configured, check the value against the defined minimum value."""
if "min" in params and params["min"] in self._config:
min_value = self._config[params["min"]]
if value < min_value:
return f"{sensor_name} low" | [
"def",
"_check_min",
"(",
"self",
",",
"sensor_name",
",",
"value",
",",
"params",
")",
":",
"if",
"\"min\"",
"in",
"params",
"and",
"params",
"[",
"\"min\"",
"]",
"in",
"self",
".",
"_config",
":",
"min_value",
"=",
"self",
".",
"_config",
"[",
"params",
"[",
"\"min\"",
"]",
"]",
"if",
"value",
"<",
"min_value",
":",
"return",
"f\"{sensor_name} low\""
] | [
265,
4
] | [
270,
43
] | python | en | ['en', 'en', 'en'] | True |
Plant._check_max | (self, sensor_name, value, params) | If configured, check the value against the defined maximum value. | If configured, check the value against the defined maximum value. | def _check_max(self, sensor_name, value, params):
"""If configured, check the value against the defined maximum value."""
if "max" in params and params["max"] in self._config:
max_value = self._config[params["max"]]
if value > max_value:
return f"{sensor_name} high"
return None | [
"def",
"_check_max",
"(",
"self",
",",
"sensor_name",
",",
"value",
",",
"params",
")",
":",
"if",
"\"max\"",
"in",
"params",
"and",
"params",
"[",
"\"max\"",
"]",
"in",
"self",
".",
"_config",
":",
"max_value",
"=",
"self",
".",
"_config",
"[",
"params",
"[",
"\"max\"",
"]",
"]",
"if",
"value",
">",
"max_value",
":",
"return",
"f\"{sensor_name} high\"",
"return",
"None"
] | [
272,
4
] | [
278,
19
] | python | en | ['en', 'en', 'en'] | True |
Plant.async_added_to_hass | (self) | After being added to hass, load from history. | After being added to hass, load from history. | async def async_added_to_hass(self):
"""After being added to hass, load from history."""
if ENABLE_LOAD_HISTORY and "recorder" in self.hass.config.components:
# only use the database if it's configured
await self.hass.async_add_executor_job(self._load_history_from_db)
self.async_write_ha_state()
async_track_state_change_event(
self.hass, list(self._sensormap), self._state_changed_event
)
for entity_id in self._sensormap:
state = self.hass.states.get(entity_id)
if state is not None:
self.state_changed(entity_id, state) | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
":",
"if",
"ENABLE_LOAD_HISTORY",
"and",
"\"recorder\"",
"in",
"self",
".",
"hass",
".",
"config",
".",
"components",
":",
"# only use the database if it's configured",
"await",
"self",
".",
"hass",
".",
"async_add_executor_job",
"(",
"self",
".",
"_load_history_from_db",
")",
"self",
".",
"async_write_ha_state",
"(",
")",
"async_track_state_change_event",
"(",
"self",
".",
"hass",
",",
"list",
"(",
"self",
".",
"_sensormap",
")",
",",
"self",
".",
"_state_changed_event",
")",
"for",
"entity_id",
"in",
"self",
".",
"_sensormap",
":",
"state",
"=",
"self",
".",
"hass",
".",
"states",
".",
"get",
"(",
"entity_id",
")",
"if",
"state",
"is",
"not",
"None",
":",
"self",
".",
"state_changed",
"(",
"entity_id",
",",
"state",
")"
] | [
280,
4
] | [
294,
52
] | python | en | ['en', 'en', 'en'] | True |
Plant._load_history_from_db | (self) | Load the history of the brightness values from the database.
This only needs to be done once during startup.
| Load the history of the brightness values from the database. | def _load_history_from_db(self):
"""Load the history of the brightness values from the database.
This only needs to be done once during startup.
"""
start_date = datetime.now() - timedelta(days=self._conf_check_days)
entity_id = self._readingmap.get(READING_BRIGHTNESS)
if entity_id is None:
_LOGGER.debug(
"Not reading the history from the database as "
"there is no brightness sensor configured"
)
return
_LOGGER.debug("Initializing values for %s from the database", self._name)
with session_scope(hass=self.hass) as session:
query = (
session.query(States)
.filter(
(States.entity_id == entity_id.lower())
and (States.last_updated > start_date)
)
.order_by(States.last_updated.asc())
)
states = execute(query, to_native=True, validate_entity_ids=False)
for state in states:
# filter out all None, NaN and "unknown" states
# only keep real values
try:
self._brightness_history.add_measurement(
int(state.state), state.last_updated
)
except ValueError:
pass
_LOGGER.debug("Initializing from database completed") | [
"def",
"_load_history_from_db",
"(",
"self",
")",
":",
"start_date",
"=",
"datetime",
".",
"now",
"(",
")",
"-",
"timedelta",
"(",
"days",
"=",
"self",
".",
"_conf_check_days",
")",
"entity_id",
"=",
"self",
".",
"_readingmap",
".",
"get",
"(",
"READING_BRIGHTNESS",
")",
"if",
"entity_id",
"is",
"None",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Not reading the history from the database as \"",
"\"there is no brightness sensor configured\"",
")",
"return",
"_LOGGER",
".",
"debug",
"(",
"\"Initializing values for %s from the database\"",
",",
"self",
".",
"_name",
")",
"with",
"session_scope",
"(",
"hass",
"=",
"self",
".",
"hass",
")",
"as",
"session",
":",
"query",
"=",
"(",
"session",
".",
"query",
"(",
"States",
")",
".",
"filter",
"(",
"(",
"States",
".",
"entity_id",
"==",
"entity_id",
".",
"lower",
"(",
")",
")",
"and",
"(",
"States",
".",
"last_updated",
">",
"start_date",
")",
")",
".",
"order_by",
"(",
"States",
".",
"last_updated",
".",
"asc",
"(",
")",
")",
")",
"states",
"=",
"execute",
"(",
"query",
",",
"to_native",
"=",
"True",
",",
"validate_entity_ids",
"=",
"False",
")",
"for",
"state",
"in",
"states",
":",
"# filter out all None, NaN and \"unknown\" states",
"# only keep real values",
"try",
":",
"self",
".",
"_brightness_history",
".",
"add_measurement",
"(",
"int",
"(",
"state",
".",
"state",
")",
",",
"state",
".",
"last_updated",
")",
"except",
"ValueError",
":",
"pass",
"_LOGGER",
".",
"debug",
"(",
"\"Initializing from database completed\"",
")"
] | [
296,
4
] | [
332,
61
] | python | en | ['en', 'en', 'en'] | True |
Plant.should_poll | (self) | No polling needed. | No polling needed. | def should_poll(self):
"""No polling needed."""
return False | [
"def",
"should_poll",
"(",
"self",
")",
":",
"return",
"False"
] | [
335,
4
] | [
337,
20
] | python | en | ['en', 'en', 'en'] | True |
Plant.name | (self) | Return the name of the sensor. | Return the name of the sensor. | def name(self):
"""Return the name of the sensor."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | [
340,
4
] | [
342,
25
] | python | en | ['en', 'mi', 'en'] | True |
Plant.state | (self) | Return the state of the entity. | Return the state of the entity. | def state(self):
"""Return the state of the entity."""
return self._state | [
"def",
"state",
"(",
"self",
")",
":",
"return",
"self",
".",
"_state"
] | [
345,
4
] | [
347,
26
] | python | en | ['en', 'en', 'en'] | True |
Plant.state_attributes | (self) | Return the attributes of the entity.
Provide the individual measurements from the
sensor in the attributes of the device.
| Return the attributes of the entity. | def state_attributes(self):
"""Return the attributes of the entity.
Provide the individual measurements from the
sensor in the attributes of the device.
"""
attrib = {
ATTR_PROBLEM: self._problems,
ATTR_SENSORS: self._readingmap,
ATTR_DICT_OF_UNITS_OF_MEASUREMENT: self._unit_of_measurement,
}
for reading in self._sensormap.values():
attrib[reading] = getattr(self, f"_{reading}")
if self._brightness_history.max is not None:
attrib[ATTR_MAX_BRIGHTNESS_HISTORY] = self._brightness_history.max
return attrib | [
"def",
"state_attributes",
"(",
"self",
")",
":",
"attrib",
"=",
"{",
"ATTR_PROBLEM",
":",
"self",
".",
"_problems",
",",
"ATTR_SENSORS",
":",
"self",
".",
"_readingmap",
",",
"ATTR_DICT_OF_UNITS_OF_MEASUREMENT",
":",
"self",
".",
"_unit_of_measurement",
",",
"}",
"for",
"reading",
"in",
"self",
".",
"_sensormap",
".",
"values",
"(",
")",
":",
"attrib",
"[",
"reading",
"]",
"=",
"getattr",
"(",
"self",
",",
"f\"_{reading}\"",
")",
"if",
"self",
".",
"_brightness_history",
".",
"max",
"is",
"not",
"None",
":",
"attrib",
"[",
"ATTR_MAX_BRIGHTNESS_HISTORY",
"]",
"=",
"self",
".",
"_brightness_history",
".",
"max",
"return",
"attrib"
] | [
350,
4
] | [
368,
21
] | python | en | ['en', 'en', 'en'] | True |
DailyHistory.__init__ | (self, max_length) | Create new DailyHistory with a maximum length of the history. | Create new DailyHistory with a maximum length of the history. | def __init__(self, max_length):
"""Create new DailyHistory with a maximum length of the history."""
self.max_length = max_length
self._days = None
self._max_dict = {}
self.max = None | [
"def",
"__init__",
"(",
"self",
",",
"max_length",
")",
":",
"self",
".",
"max_length",
"=",
"max_length",
"self",
".",
"_days",
"=",
"None",
"self",
".",
"_max_dict",
"=",
"{",
"}",
"self",
".",
"max",
"=",
"None"
] | [
377,
4
] | [
382,
23
] | python | en | ['en', 'en', 'en'] | True |
DailyHistory.add_measurement | (self, value, timestamp=None) | Add a new measurement for a certain day. | Add a new measurement for a certain day. | def add_measurement(self, value, timestamp=None):
"""Add a new measurement for a certain day."""
day = (timestamp or datetime.now()).date()
if not isinstance(value, (int, float)):
return
if self._days is None:
self._days = deque()
self._add_day(day, value)
else:
current_day = self._days[-1]
if day == current_day:
self._max_dict[day] = max(value, self._max_dict[day])
elif day > current_day:
self._add_day(day, value)
else:
_LOGGER.warning("Received old measurement, not storing it")
self.max = max(self._max_dict.values()) | [
"def",
"add_measurement",
"(",
"self",
",",
"value",
",",
"timestamp",
"=",
"None",
")",
":",
"day",
"=",
"(",
"timestamp",
"or",
"datetime",
".",
"now",
"(",
")",
")",
".",
"date",
"(",
")",
"if",
"not",
"isinstance",
"(",
"value",
",",
"(",
"int",
",",
"float",
")",
")",
":",
"return",
"if",
"self",
".",
"_days",
"is",
"None",
":",
"self",
".",
"_days",
"=",
"deque",
"(",
")",
"self",
".",
"_add_day",
"(",
"day",
",",
"value",
")",
"else",
":",
"current_day",
"=",
"self",
".",
"_days",
"[",
"-",
"1",
"]",
"if",
"day",
"==",
"current_day",
":",
"self",
".",
"_max_dict",
"[",
"day",
"]",
"=",
"max",
"(",
"value",
",",
"self",
".",
"_max_dict",
"[",
"day",
"]",
")",
"elif",
"day",
">",
"current_day",
":",
"self",
".",
"_add_day",
"(",
"day",
",",
"value",
")",
"else",
":",
"_LOGGER",
".",
"warning",
"(",
"\"Received old measurement, not storing it\"",
")",
"self",
".",
"max",
"=",
"max",
"(",
"self",
".",
"_max_dict",
".",
"values",
"(",
")",
")"
] | [
384,
4
] | [
401,
47
] | python | en | ['en', 'en', 'en'] | True |
DailyHistory._add_day | (self, day, value) | Add a new day to the history.
Deletes the oldest day, if the queue becomes too long.
| Add a new day to the history. | def _add_day(self, day, value):
"""Add a new day to the history.
Deletes the oldest day, if the queue becomes too long.
"""
if len(self._days) == self.max_length:
oldest = self._days.popleft()
del self._max_dict[oldest]
self._days.append(day)
if not isinstance(value, (int, float)):
return
self._max_dict[day] = value | [
"def",
"_add_day",
"(",
"self",
",",
"day",
",",
"value",
")",
":",
"if",
"len",
"(",
"self",
".",
"_days",
")",
"==",
"self",
".",
"max_length",
":",
"oldest",
"=",
"self",
".",
"_days",
".",
"popleft",
"(",
")",
"del",
"self",
".",
"_max_dict",
"[",
"oldest",
"]",
"self",
".",
"_days",
".",
"append",
"(",
"day",
")",
"if",
"not",
"isinstance",
"(",
"value",
",",
"(",
"int",
",",
"float",
")",
")",
":",
"return",
"self",
".",
"_max_dict",
"[",
"day",
"]",
"=",
"value"
] | [
403,
4
] | [
414,
35
] | python | en | ['en', 'en', 'en'] | True |
async_setup | (hass, config) | Track the state of the sun. | Track the state of the sun. | async def async_setup(hass, config):
"""Track the state of the sun."""
if config.get(CONF_ELEVATION) is not None:
_LOGGER.warning(
"Elevation is now configured in Home Assistant core. "
"See https://www.home-assistant.io/docs/configuration/basic/"
)
Sun(hass)
return True | [
"async",
"def",
"async_setup",
"(",
"hass",
",",
"config",
")",
":",
"if",
"config",
".",
"get",
"(",
"CONF_ELEVATION",
")",
"is",
"not",
"None",
":",
"_LOGGER",
".",
"warning",
"(",
"\"Elevation is now configured in Home Assistant core. \"",
"\"See https://www.home-assistant.io/docs/configuration/basic/\"",
")",
"Sun",
"(",
"hass",
")",
"return",
"True"
] | [
74,
0
] | [
82,
15
] | python | en | ['en', 'en', 'en'] | True |
Sun.__init__ | (self, hass) | Initialize the sun. | Initialize the sun. | def __init__(self, hass):
"""Initialize the sun."""
self.hass = hass
self.location = None
self._state = self.next_rising = self.next_setting = None
self.next_dawn = self.next_dusk = None
self.next_midnight = self.next_noon = None
self.solar_elevation = self.solar_azimuth = None
self.rising = self.phase = None
self._next_change = None
def update_location(_event):
location = get_astral_location(self.hass)
if location == self.location:
return
self.location = location
self.update_events()
update_location(None)
self.hass.bus.async_listen(EVENT_CORE_CONFIG_UPDATE, update_location) | [
"def",
"__init__",
"(",
"self",
",",
"hass",
")",
":",
"self",
".",
"hass",
"=",
"hass",
"self",
".",
"location",
"=",
"None",
"self",
".",
"_state",
"=",
"self",
".",
"next_rising",
"=",
"self",
".",
"next_setting",
"=",
"None",
"self",
".",
"next_dawn",
"=",
"self",
".",
"next_dusk",
"=",
"None",
"self",
".",
"next_midnight",
"=",
"self",
".",
"next_noon",
"=",
"None",
"self",
".",
"solar_elevation",
"=",
"self",
".",
"solar_azimuth",
"=",
"None",
"self",
".",
"rising",
"=",
"self",
".",
"phase",
"=",
"None",
"self",
".",
"_next_change",
"=",
"None",
"def",
"update_location",
"(",
"_event",
")",
":",
"location",
"=",
"get_astral_location",
"(",
"self",
".",
"hass",
")",
"if",
"location",
"==",
"self",
".",
"location",
":",
"return",
"self",
".",
"location",
"=",
"location",
"self",
".",
"update_events",
"(",
")",
"update_location",
"(",
"None",
")",
"self",
".",
"hass",
".",
"bus",
".",
"async_listen",
"(",
"EVENT_CORE_CONFIG_UPDATE",
",",
"update_location",
")"
] | [
90,
4
] | [
109,
77
] | python | en | ['en', 'en', 'en'] | True |
Sun.name | (self) | Return the name. | Return the name. | def name(self):
"""Return the name."""
return "Sun" | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"\"Sun\""
] | [
112,
4
] | [
114,
20
] | python | en | ['en', 'ig', 'en'] | True |
Sun.state | (self) | Return the state of the sun. | Return the state of the sun. | def state(self):
"""Return the state of the sun."""
# 0.8333 is the same value as astral uses
if self.solar_elevation > -0.833:
return STATE_ABOVE_HORIZON
return STATE_BELOW_HORIZON | [
"def",
"state",
"(",
"self",
")",
":",
"# 0.8333 is the same value as astral uses",
"if",
"self",
".",
"solar_elevation",
">",
"-",
"0.833",
":",
"return",
"STATE_ABOVE_HORIZON",
"return",
"STATE_BELOW_HORIZON"
] | [
117,
4
] | [
123,
34
] | python | en | ['en', 'en', 'en'] | True |
Sun.state_attributes | (self) | Return the state attributes of the sun. | Return the state attributes of the sun. | def state_attributes(self):
"""Return the state attributes of the sun."""
return {
STATE_ATTR_NEXT_DAWN: self.next_dawn.isoformat(),
STATE_ATTR_NEXT_DUSK: self.next_dusk.isoformat(),
STATE_ATTR_NEXT_MIDNIGHT: self.next_midnight.isoformat(),
STATE_ATTR_NEXT_NOON: self.next_noon.isoformat(),
STATE_ATTR_NEXT_RISING: self.next_rising.isoformat(),
STATE_ATTR_NEXT_SETTING: self.next_setting.isoformat(),
STATE_ATTR_ELEVATION: self.solar_elevation,
STATE_ATTR_AZIMUTH: self.solar_azimuth,
STATE_ATTR_RISING: self.rising,
} | [
"def",
"state_attributes",
"(",
"self",
")",
":",
"return",
"{",
"STATE_ATTR_NEXT_DAWN",
":",
"self",
".",
"next_dawn",
".",
"isoformat",
"(",
")",
",",
"STATE_ATTR_NEXT_DUSK",
":",
"self",
".",
"next_dusk",
".",
"isoformat",
"(",
")",
",",
"STATE_ATTR_NEXT_MIDNIGHT",
":",
"self",
".",
"next_midnight",
".",
"isoformat",
"(",
")",
",",
"STATE_ATTR_NEXT_NOON",
":",
"self",
".",
"next_noon",
".",
"isoformat",
"(",
")",
",",
"STATE_ATTR_NEXT_RISING",
":",
"self",
".",
"next_rising",
".",
"isoformat",
"(",
")",
",",
"STATE_ATTR_NEXT_SETTING",
":",
"self",
".",
"next_setting",
".",
"isoformat",
"(",
")",
",",
"STATE_ATTR_ELEVATION",
":",
"self",
".",
"solar_elevation",
",",
"STATE_ATTR_AZIMUTH",
":",
"self",
".",
"solar_azimuth",
",",
"STATE_ATTR_RISING",
":",
"self",
".",
"rising",
",",
"}"
] | [
126,
4
] | [
138,
9
] | python | en | ['en', 'en', 'en'] | True |
Sun.update_events | (self, now=None) | Update the attributes containing solar events. | Update the attributes containing solar events. | def update_events(self, now=None):
"""Update the attributes containing solar events."""
# Grab current time in case system clock changed since last time we ran.
utc_point_in_time = dt_util.utcnow()
self._next_change = utc_point_in_time + timedelta(days=400)
# Work our way around the solar cycle, figure out the next
# phase. Some of these are stored.
self.location.solar_depression = "astronomical"
self._check_event(utc_point_in_time, "dawn", PHASE_NIGHT)
self.location.solar_depression = "nautical"
self._check_event(utc_point_in_time, "dawn", PHASE_ASTRONOMICAL_TWILIGHT)
self.location.solar_depression = "civil"
self.next_dawn = self._check_event(
utc_point_in_time, "dawn", PHASE_NAUTICAL_TWILIGHT
)
self.next_rising = self._check_event(
utc_point_in_time, SUN_EVENT_SUNRISE, PHASE_TWILIGHT
)
self.location.solar_depression = -10
self._check_event(utc_point_in_time, "dawn", PHASE_SMALL_DAY)
self.next_noon = self._check_event(utc_point_in_time, "solar_noon", None)
self._check_event(utc_point_in_time, "dusk", PHASE_DAY)
self.next_setting = self._check_event(
utc_point_in_time, SUN_EVENT_SUNSET, PHASE_SMALL_DAY
)
self.location.solar_depression = "civil"
self.next_dusk = self._check_event(utc_point_in_time, "dusk", PHASE_TWILIGHT)
self.location.solar_depression = "nautical"
self._check_event(utc_point_in_time, "dusk", PHASE_NAUTICAL_TWILIGHT)
self.location.solar_depression = "astronomical"
self._check_event(utc_point_in_time, "dusk", PHASE_ASTRONOMICAL_TWILIGHT)
self.next_midnight = self._check_event(
utc_point_in_time, "solar_midnight", None
)
self.location.solar_depression = "civil"
# if the event was solar midday or midnight, phase will now
# be None. Solar noon doesn't always happen when the sun is
# even in the day at the poles, so we can't rely on it.
# Need to calculate phase if next is noon or midnight
if self.phase is None:
elevation = self.location.solar_elevation(self._next_change)
if elevation >= 10:
self.phase = PHASE_DAY
elif elevation >= 0:
self.phase = PHASE_SMALL_DAY
elif elevation >= -6:
self.phase = PHASE_TWILIGHT
elif elevation >= -12:
self.phase = PHASE_NAUTICAL_TWILIGHT
elif elevation >= -18:
self.phase = PHASE_ASTRONOMICAL_TWILIGHT
else:
self.phase = PHASE_NIGHT
self.rising = self.next_noon < self.next_midnight
_LOGGER.debug(
"sun phase_update@%s: phase=%s", utc_point_in_time.isoformat(), self.phase
)
self.update_sun_position()
# Set timer for the next solar event
event.async_track_point_in_utc_time(
self.hass, self.update_events, self._next_change
)
_LOGGER.debug("next time: %s", self._next_change.isoformat()) | [
"def",
"update_events",
"(",
"self",
",",
"now",
"=",
"None",
")",
":",
"# Grab current time in case system clock changed since last time we ran.",
"utc_point_in_time",
"=",
"dt_util",
".",
"utcnow",
"(",
")",
"self",
".",
"_next_change",
"=",
"utc_point_in_time",
"+",
"timedelta",
"(",
"days",
"=",
"400",
")",
"# Work our way around the solar cycle, figure out the next",
"# phase. Some of these are stored.",
"self",
".",
"location",
".",
"solar_depression",
"=",
"\"astronomical\"",
"self",
".",
"_check_event",
"(",
"utc_point_in_time",
",",
"\"dawn\"",
",",
"PHASE_NIGHT",
")",
"self",
".",
"location",
".",
"solar_depression",
"=",
"\"nautical\"",
"self",
".",
"_check_event",
"(",
"utc_point_in_time",
",",
"\"dawn\"",
",",
"PHASE_ASTRONOMICAL_TWILIGHT",
")",
"self",
".",
"location",
".",
"solar_depression",
"=",
"\"civil\"",
"self",
".",
"next_dawn",
"=",
"self",
".",
"_check_event",
"(",
"utc_point_in_time",
",",
"\"dawn\"",
",",
"PHASE_NAUTICAL_TWILIGHT",
")",
"self",
".",
"next_rising",
"=",
"self",
".",
"_check_event",
"(",
"utc_point_in_time",
",",
"SUN_EVENT_SUNRISE",
",",
"PHASE_TWILIGHT",
")",
"self",
".",
"location",
".",
"solar_depression",
"=",
"-",
"10",
"self",
".",
"_check_event",
"(",
"utc_point_in_time",
",",
"\"dawn\"",
",",
"PHASE_SMALL_DAY",
")",
"self",
".",
"next_noon",
"=",
"self",
".",
"_check_event",
"(",
"utc_point_in_time",
",",
"\"solar_noon\"",
",",
"None",
")",
"self",
".",
"_check_event",
"(",
"utc_point_in_time",
",",
"\"dusk\"",
",",
"PHASE_DAY",
")",
"self",
".",
"next_setting",
"=",
"self",
".",
"_check_event",
"(",
"utc_point_in_time",
",",
"SUN_EVENT_SUNSET",
",",
"PHASE_SMALL_DAY",
")",
"self",
".",
"location",
".",
"solar_depression",
"=",
"\"civil\"",
"self",
".",
"next_dusk",
"=",
"self",
".",
"_check_event",
"(",
"utc_point_in_time",
",",
"\"dusk\"",
",",
"PHASE_TWILIGHT",
")",
"self",
".",
"location",
".",
"solar_depression",
"=",
"\"nautical\"",
"self",
".",
"_check_event",
"(",
"utc_point_in_time",
",",
"\"dusk\"",
",",
"PHASE_NAUTICAL_TWILIGHT",
")",
"self",
".",
"location",
".",
"solar_depression",
"=",
"\"astronomical\"",
"self",
".",
"_check_event",
"(",
"utc_point_in_time",
",",
"\"dusk\"",
",",
"PHASE_ASTRONOMICAL_TWILIGHT",
")",
"self",
".",
"next_midnight",
"=",
"self",
".",
"_check_event",
"(",
"utc_point_in_time",
",",
"\"solar_midnight\"",
",",
"None",
")",
"self",
".",
"location",
".",
"solar_depression",
"=",
"\"civil\"",
"# if the event was solar midday or midnight, phase will now",
"# be None. Solar noon doesn't always happen when the sun is",
"# even in the day at the poles, so we can't rely on it.",
"# Need to calculate phase if next is noon or midnight",
"if",
"self",
".",
"phase",
"is",
"None",
":",
"elevation",
"=",
"self",
".",
"location",
".",
"solar_elevation",
"(",
"self",
".",
"_next_change",
")",
"if",
"elevation",
">=",
"10",
":",
"self",
".",
"phase",
"=",
"PHASE_DAY",
"elif",
"elevation",
">=",
"0",
":",
"self",
".",
"phase",
"=",
"PHASE_SMALL_DAY",
"elif",
"elevation",
">=",
"-",
"6",
":",
"self",
".",
"phase",
"=",
"PHASE_TWILIGHT",
"elif",
"elevation",
">=",
"-",
"12",
":",
"self",
".",
"phase",
"=",
"PHASE_NAUTICAL_TWILIGHT",
"elif",
"elevation",
">=",
"-",
"18",
":",
"self",
".",
"phase",
"=",
"PHASE_ASTRONOMICAL_TWILIGHT",
"else",
":",
"self",
".",
"phase",
"=",
"PHASE_NIGHT",
"self",
".",
"rising",
"=",
"self",
".",
"next_noon",
"<",
"self",
".",
"next_midnight",
"_LOGGER",
".",
"debug",
"(",
"\"sun phase_update@%s: phase=%s\"",
",",
"utc_point_in_time",
".",
"isoformat",
"(",
")",
",",
"self",
".",
"phase",
")",
"self",
".",
"update_sun_position",
"(",
")",
"# Set timer for the next solar event",
"event",
".",
"async_track_point_in_utc_time",
"(",
"self",
".",
"hass",
",",
"self",
".",
"update_events",
",",
"self",
".",
"_next_change",
")",
"_LOGGER",
".",
"debug",
"(",
"\"next time: %s\"",
",",
"self",
".",
"_next_change",
".",
"isoformat",
"(",
")",
")"
] | [
150,
4
] | [
217,
69
] | python | en | ['en', 'en', 'en'] | True |
Sun.update_sun_position | (self, now=None) | Calculate the position of the sun. | Calculate the position of the sun. | def update_sun_position(self, now=None):
"""Calculate the position of the sun."""
# Grab current time in case system clock changed since last time we ran.
utc_point_in_time = dt_util.utcnow()
self.solar_azimuth = round(self.location.solar_azimuth(utc_point_in_time), 2)
self.solar_elevation = round(
self.location.solar_elevation(utc_point_in_time), 2
)
_LOGGER.debug(
"sun position_update@%s: elevation=%s azimuth=%s",
utc_point_in_time.isoformat(),
self.solar_elevation,
self.solar_azimuth,
)
self.async_write_ha_state()
# Next update as per the current phase
delta = _PHASE_UPDATES[self.phase]
# if the next update is within 1.25 of the next
# position update just drop it
if utc_point_in_time + delta * 1.25 > self._next_change:
return
event.async_track_point_in_utc_time(
self.hass, self.update_sun_position, utc_point_in_time + delta
) | [
"def",
"update_sun_position",
"(",
"self",
",",
"now",
"=",
"None",
")",
":",
"# Grab current time in case system clock changed since last time we ran.",
"utc_point_in_time",
"=",
"dt_util",
".",
"utcnow",
"(",
")",
"self",
".",
"solar_azimuth",
"=",
"round",
"(",
"self",
".",
"location",
".",
"solar_azimuth",
"(",
"utc_point_in_time",
")",
",",
"2",
")",
"self",
".",
"solar_elevation",
"=",
"round",
"(",
"self",
".",
"location",
".",
"solar_elevation",
"(",
"utc_point_in_time",
")",
",",
"2",
")",
"_LOGGER",
".",
"debug",
"(",
"\"sun position_update@%s: elevation=%s azimuth=%s\"",
",",
"utc_point_in_time",
".",
"isoformat",
"(",
")",
",",
"self",
".",
"solar_elevation",
",",
"self",
".",
"solar_azimuth",
",",
")",
"self",
".",
"async_write_ha_state",
"(",
")",
"# Next update as per the current phase",
"delta",
"=",
"_PHASE_UPDATES",
"[",
"self",
".",
"phase",
"]",
"# if the next update is within 1.25 of the next",
"# position update just drop it",
"if",
"utc_point_in_time",
"+",
"delta",
"*",
"1.25",
">",
"self",
".",
"_next_change",
":",
"return",
"event",
".",
"async_track_point_in_utc_time",
"(",
"self",
".",
"hass",
",",
"self",
".",
"update_sun_position",
",",
"utc_point_in_time",
"+",
"delta",
")"
] | [
220,
4
] | [
245,
9
] | python | en | ['en', 'en', 'en'] | True |
setup_cors | (app, origins) | Set up CORS. | Set up CORS. | def setup_cors(app, origins):
"""Set up CORS."""
# This import should remain here. That way the HTTP integration can always
# be imported by other integrations without it's requirements being installed.
# pylint: disable=import-outside-toplevel
import aiohttp_cors
cors = aiohttp_cors.setup(
app,
defaults={
host: aiohttp_cors.ResourceOptions(
allow_headers=ALLOWED_CORS_HEADERS, allow_methods="*"
)
for host in origins
},
)
cors_added = set()
def _allow_cors(route, config=None):
"""Allow CORS on a route."""
if hasattr(route, "resource"):
path = route.resource
else:
path = route
if not isinstance(path, VALID_CORS_TYPES):
return
path = path.canonical
if path.startswith("/api/hassio_ingress/"):
return
if path in cors_added:
return
cors.add(route, config)
cors_added.add(path)
app["allow_cors"] = lambda route: _allow_cors(
route,
{
"*": aiohttp_cors.ResourceOptions(
allow_headers=ALLOWED_CORS_HEADERS, allow_methods="*"
)
},
)
if not origins:
return
async def cors_startup(app):
"""Initialize CORS when app starts up."""
for resource in list(app.router.resources()):
_allow_cors(resource)
app.on_startup.append(cors_startup) | [
"def",
"setup_cors",
"(",
"app",
",",
"origins",
")",
":",
"# This import should remain here. That way the HTTP integration can always",
"# be imported by other integrations without it's requirements being installed.",
"# pylint: disable=import-outside-toplevel",
"import",
"aiohttp_cors",
"cors",
"=",
"aiohttp_cors",
".",
"setup",
"(",
"app",
",",
"defaults",
"=",
"{",
"host",
":",
"aiohttp_cors",
".",
"ResourceOptions",
"(",
"allow_headers",
"=",
"ALLOWED_CORS_HEADERS",
",",
"allow_methods",
"=",
"\"*\"",
")",
"for",
"host",
"in",
"origins",
"}",
",",
")",
"cors_added",
"=",
"set",
"(",
")",
"def",
"_allow_cors",
"(",
"route",
",",
"config",
"=",
"None",
")",
":",
"\"\"\"Allow CORS on a route.\"\"\"",
"if",
"hasattr",
"(",
"route",
",",
"\"resource\"",
")",
":",
"path",
"=",
"route",
".",
"resource",
"else",
":",
"path",
"=",
"route",
"if",
"not",
"isinstance",
"(",
"path",
",",
"VALID_CORS_TYPES",
")",
":",
"return",
"path",
"=",
"path",
".",
"canonical",
"if",
"path",
".",
"startswith",
"(",
"\"/api/hassio_ingress/\"",
")",
":",
"return",
"if",
"path",
"in",
"cors_added",
":",
"return",
"cors",
".",
"add",
"(",
"route",
",",
"config",
")",
"cors_added",
".",
"add",
"(",
"path",
")",
"app",
"[",
"\"allow_cors\"",
"]",
"=",
"lambda",
"route",
":",
"_allow_cors",
"(",
"route",
",",
"{",
"\"*\"",
":",
"aiohttp_cors",
".",
"ResourceOptions",
"(",
"allow_headers",
"=",
"ALLOWED_CORS_HEADERS",
",",
"allow_methods",
"=",
"\"*\"",
")",
"}",
",",
")",
"if",
"not",
"origins",
":",
"return",
"async",
"def",
"cors_startup",
"(",
"app",
")",
":",
"\"\"\"Initialize CORS when app starts up.\"\"\"",
"for",
"resource",
"in",
"list",
"(",
"app",
".",
"router",
".",
"resources",
"(",
")",
")",
":",
"_allow_cors",
"(",
"resource",
")",
"app",
".",
"on_startup",
".",
"append",
"(",
"cors_startup",
")"
] | [
20,
0
] | [
77,
39
] | python | en | ['en', 'bg', 'en'] | True |
async_setup_entry | (hass, entry, async_add_entities) | Set up a Luftdaten sensor based on a config entry. | Set up a Luftdaten sensor based on a config entry. | async def async_setup_entry(hass, entry, async_add_entities):
"""Set up a Luftdaten sensor based on a config entry."""
luftdaten = hass.data[DOMAIN][DATA_LUFTDATEN_CLIENT][entry.entry_id]
sensors = []
for sensor_type in luftdaten.sensor_conditions:
try:
name, icon, unit = SENSORS[sensor_type]
except KeyError:
_LOGGER.debug("Unknown sensor value type: %s", sensor_type)
continue
sensors.append(
LuftdatenSensor(
luftdaten, sensor_type, name, icon, unit, entry.data[CONF_SHOW_ON_MAP]
)
)
async_add_entities(sensors, True) | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
",",
"entry",
",",
"async_add_entities",
")",
":",
"luftdaten",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"DATA_LUFTDATEN_CLIENT",
"]",
"[",
"entry",
".",
"entry_id",
"]",
"sensors",
"=",
"[",
"]",
"for",
"sensor_type",
"in",
"luftdaten",
".",
"sensor_conditions",
":",
"try",
":",
"name",
",",
"icon",
",",
"unit",
"=",
"SENSORS",
"[",
"sensor_type",
"]",
"except",
"KeyError",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Unknown sensor value type: %s\"",
",",
"sensor_type",
")",
"continue",
"sensors",
".",
"append",
"(",
"LuftdatenSensor",
"(",
"luftdaten",
",",
"sensor_type",
",",
"name",
",",
"icon",
",",
"unit",
",",
"entry",
".",
"data",
"[",
"CONF_SHOW_ON_MAP",
"]",
")",
")",
"async_add_entities",
"(",
"sensors",
",",
"True",
")"
] | [
26,
0
] | [
44,
37
] | python | en | ['en', 'da', 'en'] | True |
LuftdatenSensor.__init__ | (self, luftdaten, sensor_type, name, icon, unit, show) | Initialize the Luftdaten sensor. | Initialize the Luftdaten sensor. | def __init__(self, luftdaten, sensor_type, name, icon, unit, show):
"""Initialize the Luftdaten sensor."""
self._async_unsub_dispatcher_connect = None
self.luftdaten = luftdaten
self._icon = icon
self._name = name
self._data = None
self.sensor_type = sensor_type
self._unit_of_measurement = unit
self._show_on_map = show
self._attrs = {} | [
"def",
"__init__",
"(",
"self",
",",
"luftdaten",
",",
"sensor_type",
",",
"name",
",",
"icon",
",",
"unit",
",",
"show",
")",
":",
"self",
".",
"_async_unsub_dispatcher_connect",
"=",
"None",
"self",
".",
"luftdaten",
"=",
"luftdaten",
"self",
".",
"_icon",
"=",
"icon",
"self",
".",
"_name",
"=",
"name",
"self",
".",
"_data",
"=",
"None",
"self",
".",
"sensor_type",
"=",
"sensor_type",
"self",
".",
"_unit_of_measurement",
"=",
"unit",
"self",
".",
"_show_on_map",
"=",
"show",
"self",
".",
"_attrs",
"=",
"{",
"}"
] | [
50,
4
] | [
60,
24
] | python | en | ['en', 'en', 'nl'] | True |
LuftdatenSensor.icon | (self) | Return the icon. | Return the icon. | def icon(self):
"""Return the icon."""
return self._icon | [
"def",
"icon",
"(",
"self",
")",
":",
"return",
"self",
".",
"_icon"
] | [
63,
4
] | [
65,
25
] | python | en | ['en', 'sr', 'en'] | True |
LuftdatenSensor.state | (self) | Return the state of the device. | Return the state of the device. | def state(self):
"""Return the state of the device."""
if self._data is not None:
return self._data[self.sensor_type] | [
"def",
"state",
"(",
"self",
")",
":",
"if",
"self",
".",
"_data",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_data",
"[",
"self",
".",
"sensor_type",
"]"
] | [
68,
4
] | [
71,
47
] | python | en | ['en', 'en', 'en'] | True |
LuftdatenSensor.unit_of_measurement | (self) | Return the unit of measurement of this entity, if any. | Return the unit of measurement of this entity, if any. | def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return self._unit_of_measurement | [
"def",
"unit_of_measurement",
"(",
"self",
")",
":",
"return",
"self",
".",
"_unit_of_measurement"
] | [
74,
4
] | [
76,
40
] | python | en | ['en', 'en', 'en'] | True |
LuftdatenSensor.should_poll | (self) | Disable polling. | Disable polling. | def should_poll(self):
"""Disable polling."""
return False | [
"def",
"should_poll",
"(",
"self",
")",
":",
"return",
"False"
] | [
79,
4
] | [
81,
20
] | python | en | ['fr', 'en', 'en'] | False |
LuftdatenSensor.unique_id | (self) | Return a unique, friendly identifier for this entity. | Return a unique, friendly identifier for this entity. | def unique_id(self) -> str:
"""Return a unique, friendly identifier for this entity."""
if self._data is not None:
return f"{self._data['sensor_id']}_{self.sensor_type}" | [
"def",
"unique_id",
"(",
"self",
")",
"->",
"str",
":",
"if",
"self",
".",
"_data",
"is",
"not",
"None",
":",
"return",
"f\"{self._data['sensor_id']}_{self.sensor_type}\""
] | [
84,
4
] | [
87,
66
] | python | en | ['en', 'en', 'en'] | True |
LuftdatenSensor.device_state_attributes | (self) | Return the state attributes. | Return the state attributes. | def device_state_attributes(self):
"""Return the state attributes."""
self._attrs[ATTR_ATTRIBUTION] = DEFAULT_ATTRIBUTION
if self._data is not None:
self._attrs[ATTR_SENSOR_ID] = self._data["sensor_id"]
on_map = ATTR_LATITUDE, ATTR_LONGITUDE
no_map = "lat", "long"
lat_format, lon_format = on_map if self._show_on_map else no_map
try:
self._attrs[lon_format] = self._data["longitude"]
self._attrs[lat_format] = self._data["latitude"]
return self._attrs
except KeyError:
return | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"self",
".",
"_attrs",
"[",
"ATTR_ATTRIBUTION",
"]",
"=",
"DEFAULT_ATTRIBUTION",
"if",
"self",
".",
"_data",
"is",
"not",
"None",
":",
"self",
".",
"_attrs",
"[",
"ATTR_SENSOR_ID",
"]",
"=",
"self",
".",
"_data",
"[",
"\"sensor_id\"",
"]",
"on_map",
"=",
"ATTR_LATITUDE",
",",
"ATTR_LONGITUDE",
"no_map",
"=",
"\"lat\"",
",",
"\"long\"",
"lat_format",
",",
"lon_format",
"=",
"on_map",
"if",
"self",
".",
"_show_on_map",
"else",
"no_map",
"try",
":",
"self",
".",
"_attrs",
"[",
"lon_format",
"]",
"=",
"self",
".",
"_data",
"[",
"\"longitude\"",
"]",
"self",
".",
"_attrs",
"[",
"lat_format",
"]",
"=",
"self",
".",
"_data",
"[",
"\"latitude\"",
"]",
"return",
"self",
".",
"_attrs",
"except",
"KeyError",
":",
"return"
] | [
90,
4
] | [
105,
22
] | python | en | ['en', 'en', 'en'] | True |
LuftdatenSensor.async_added_to_hass | (self) | Register callbacks. | Register callbacks. | async def async_added_to_hass(self):
"""Register callbacks."""
@callback
def update():
"""Update the state."""
self.async_schedule_update_ha_state(True)
self._async_unsub_dispatcher_connect = async_dispatcher_connect(
self.hass, TOPIC_UPDATE, update
) | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
":",
"@",
"callback",
"def",
"update",
"(",
")",
":",
"\"\"\"Update the state.\"\"\"",
"self",
".",
"async_schedule_update_ha_state",
"(",
"True",
")",
"self",
".",
"_async_unsub_dispatcher_connect",
"=",
"async_dispatcher_connect",
"(",
"self",
".",
"hass",
",",
"TOPIC_UPDATE",
",",
"update",
")"
] | [
107,
4
] | [
117,
9
] | python | en | ['en', 'no', 'en'] | False |
LuftdatenSensor.async_will_remove_from_hass | (self) | Disconnect dispatcher listener when removed. | Disconnect dispatcher listener when removed. | async def async_will_remove_from_hass(self):
"""Disconnect dispatcher listener when removed."""
if self._async_unsub_dispatcher_connect:
self._async_unsub_dispatcher_connect() | [
"async",
"def",
"async_will_remove_from_hass",
"(",
"self",
")",
":",
"if",
"self",
".",
"_async_unsub_dispatcher_connect",
":",
"self",
".",
"_async_unsub_dispatcher_connect",
"(",
")"
] | [
119,
4
] | [
122,
50
] | python | en | ['en', 'en', 'en'] | True |
LuftdatenSensor.async_update | (self) | Get the latest data and update the state. | Get the latest data and update the state. | async def async_update(self):
"""Get the latest data and update the state."""
try:
self._data = self.luftdaten.data[DATA_LUFTDATEN]
except KeyError:
return | [
"async",
"def",
"async_update",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_data",
"=",
"self",
".",
"luftdaten",
".",
"data",
"[",
"DATA_LUFTDATEN",
"]",
"except",
"KeyError",
":",
"return"
] | [
124,
4
] | [
129,
18
] | python | en | ['en', 'en', 'en'] | True |
ModelCard.save_pretrained | (self, save_directory_or_file) | Save a model card object to the directory or file `save_directory_or_file`. | Save a model card object to the directory or file `save_directory_or_file`. | def save_pretrained(self, save_directory_or_file):
"""Save a model card object to the directory or file `save_directory_or_file`."""
if os.path.isdir(save_directory_or_file):
# If we save using the predefined names, we can load using `from_pretrained`
output_model_card_file = os.path.join(save_directory_or_file, MODEL_CARD_NAME)
else:
output_model_card_file = save_directory_or_file
self.to_json_file(output_model_card_file)
logger.info("Model card saved in {}".format(output_model_card_file)) | [
"def",
"save_pretrained",
"(",
"self",
",",
"save_directory_or_file",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"save_directory_or_file",
")",
":",
"# If we save using the predefined names, we can load using `from_pretrained`",
"output_model_card_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"save_directory_or_file",
",",
"MODEL_CARD_NAME",
")",
"else",
":",
"output_model_card_file",
"=",
"save_directory_or_file",
"self",
".",
"to_json_file",
"(",
"output_model_card_file",
")",
"logger",
".",
"info",
"(",
"\"Model card saved in {}\"",
".",
"format",
"(",
"output_model_card_file",
")",
")"
] | [
70,
4
] | [
79,
76
] | python | en | ['en', 'en', 'en'] | True |
ModelCard.from_pretrained | (cls, pretrained_model_name_or_path, **kwargs) | r"""
Instantiate a :class:`~transformers.ModelCard` from a pre-trained model model card.
Parameters:
pretrained_model_name_or_path: either:
- a string, the `model id` of a pretrained model card hosted inside a model repo on huggingface.co.
Valid model ids can be located at the root-level, like ``bert-base-uncased``, or namespaced under a
user or organization name, like ``dbmdz/bert-base-german-cased``.
- a path to a `directory` containing a model card file saved using the
:func:`~transformers.ModelCard.save_pretrained` method, e.g.: ``./my_model_directory/``.
- a path or url to a saved model card JSON `file`, e.g.: ``./my_model_directory/modelcard.json``.
cache_dir: (`optional`) string:
Path to a directory in which a downloaded pre-trained model card should be cached if the standard cache
should not be used.
kwargs: (`optional`) dict: key/value pairs with which to update the ModelCard object after loading.
- The values in kwargs of any keys which are model card attributes will be used to override the loaded
values.
- Behavior concerning key/value pairs whose keys are *not* model card attributes is controlled by the
`return_unused_kwargs` keyword parameter.
proxies: (`optional`) dict, default None:
A dictionary of proxy servers to use by protocol or endpoint, e.g.: {'http': 'foo.bar:3128',
'http://hostname': 'foo.bar:4012'}. The proxies are used on each request.
find_from_standard_name: (`optional`) boolean, default True:
If the pretrained_model_name_or_path ends with our standard model or config filenames, replace them
with our standard modelcard filename. Can be used to directly feed a model/config url and access the
colocated modelcard.
return_unused_kwargs: (`optional`) bool:
- If False, then this function returns just the final model card object.
- If True, then this functions returns a tuple `(model card, unused_kwargs)` where `unused_kwargs` is a
dictionary consisting of the key/value pairs whose keys are not model card attributes: ie the part of
kwargs which has not been used to update `ModelCard` and is otherwise ignored.
Examples::
modelcard = ModelCard.from_pretrained('bert-base-uncased') # Download model card from huggingface.co and cache.
modelcard = ModelCard.from_pretrained('./test/saved_model/') # E.g. model card was saved using `save_pretrained('./test/saved_model/')`
modelcard = ModelCard.from_pretrained('./test/saved_model/modelcard.json')
modelcard = ModelCard.from_pretrained('bert-base-uncased', output_attentions=True, foo=False)
| r"""
Instantiate a :class:`~transformers.ModelCard` from a pre-trained model model card. | def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
r"""
Instantiate a :class:`~transformers.ModelCard` from a pre-trained model model card.
Parameters:
pretrained_model_name_or_path: either:
- a string, the `model id` of a pretrained model card hosted inside a model repo on huggingface.co.
Valid model ids can be located at the root-level, like ``bert-base-uncased``, or namespaced under a
user or organization name, like ``dbmdz/bert-base-german-cased``.
- a path to a `directory` containing a model card file saved using the
:func:`~transformers.ModelCard.save_pretrained` method, e.g.: ``./my_model_directory/``.
- a path or url to a saved model card JSON `file`, e.g.: ``./my_model_directory/modelcard.json``.
cache_dir: (`optional`) string:
Path to a directory in which a downloaded pre-trained model card should be cached if the standard cache
should not be used.
kwargs: (`optional`) dict: key/value pairs with which to update the ModelCard object after loading.
- The values in kwargs of any keys which are model card attributes will be used to override the loaded
values.
- Behavior concerning key/value pairs whose keys are *not* model card attributes is controlled by the
`return_unused_kwargs` keyword parameter.
proxies: (`optional`) dict, default None:
A dictionary of proxy servers to use by protocol or endpoint, e.g.: {'http': 'foo.bar:3128',
'http://hostname': 'foo.bar:4012'}. The proxies are used on each request.
find_from_standard_name: (`optional`) boolean, default True:
If the pretrained_model_name_or_path ends with our standard model or config filenames, replace them
with our standard modelcard filename. Can be used to directly feed a model/config url and access the
colocated modelcard.
return_unused_kwargs: (`optional`) bool:
- If False, then this function returns just the final model card object.
- If True, then this functions returns a tuple `(model card, unused_kwargs)` where `unused_kwargs` is a
dictionary consisting of the key/value pairs whose keys are not model card attributes: ie the part of
kwargs which has not been used to update `ModelCard` and is otherwise ignored.
Examples::
modelcard = ModelCard.from_pretrained('bert-base-uncased') # Download model card from huggingface.co and cache.
modelcard = ModelCard.from_pretrained('./test/saved_model/') # E.g. model card was saved using `save_pretrained('./test/saved_model/')`
modelcard = ModelCard.from_pretrained('./test/saved_model/modelcard.json')
modelcard = ModelCard.from_pretrained('bert-base-uncased', output_attentions=True, foo=False)
"""
cache_dir = kwargs.pop("cache_dir", None)
proxies = kwargs.pop("proxies", None)
find_from_standard_name = kwargs.pop("find_from_standard_name", True)
return_unused_kwargs = kwargs.pop("return_unused_kwargs", False)
if pretrained_model_name_or_path in ALL_PRETRAINED_CONFIG_ARCHIVE_MAP:
# For simplicity we use the same pretrained url than the configuration files
# but with a different suffix (modelcard.json). This suffix is replaced below.
model_card_file = ALL_PRETRAINED_CONFIG_ARCHIVE_MAP[pretrained_model_name_or_path]
elif os.path.isdir(pretrained_model_name_or_path):
model_card_file = os.path.join(pretrained_model_name_or_path, MODEL_CARD_NAME)
elif os.path.isfile(pretrained_model_name_or_path) or is_remote_url(pretrained_model_name_or_path):
model_card_file = pretrained_model_name_or_path
else:
model_card_file = hf_bucket_url(pretrained_model_name_or_path, filename=MODEL_CARD_NAME, mirror=None)
if find_from_standard_name or pretrained_model_name_or_path in ALL_PRETRAINED_CONFIG_ARCHIVE_MAP:
model_card_file = model_card_file.replace(CONFIG_NAME, MODEL_CARD_NAME)
model_card_file = model_card_file.replace(WEIGHTS_NAME, MODEL_CARD_NAME)
model_card_file = model_card_file.replace(TF2_WEIGHTS_NAME, MODEL_CARD_NAME)
try:
# Load from URL or cache if already cached
resolved_model_card_file = cached_path(model_card_file, cache_dir=cache_dir, proxies=proxies)
if resolved_model_card_file == model_card_file:
logger.info("loading model card file {}".format(model_card_file))
else:
logger.info(
"loading model card file {} from cache at {}".format(model_card_file, resolved_model_card_file)
)
# Load model card
modelcard = cls.from_json_file(resolved_model_card_file)
except (EnvironmentError, json.JSONDecodeError):
# We fall back on creating an empty model card
modelcard = cls()
# Update model card with kwargs if needed
to_remove = []
for key, value in kwargs.items():
if hasattr(modelcard, key):
setattr(modelcard, key, value)
to_remove.append(key)
for key in to_remove:
kwargs.pop(key, None)
logger.info("Model card: %s", str(modelcard))
if return_unused_kwargs:
return modelcard, kwargs
else:
return modelcard | [
"def",
"from_pretrained",
"(",
"cls",
",",
"pretrained_model_name_or_path",
",",
"*",
"*",
"kwargs",
")",
":",
"cache_dir",
"=",
"kwargs",
".",
"pop",
"(",
"\"cache_dir\"",
",",
"None",
")",
"proxies",
"=",
"kwargs",
".",
"pop",
"(",
"\"proxies\"",
",",
"None",
")",
"find_from_standard_name",
"=",
"kwargs",
".",
"pop",
"(",
"\"find_from_standard_name\"",
",",
"True",
")",
"return_unused_kwargs",
"=",
"kwargs",
".",
"pop",
"(",
"\"return_unused_kwargs\"",
",",
"False",
")",
"if",
"pretrained_model_name_or_path",
"in",
"ALL_PRETRAINED_CONFIG_ARCHIVE_MAP",
":",
"# For simplicity we use the same pretrained url than the configuration files",
"# but with a different suffix (modelcard.json). This suffix is replaced below.",
"model_card_file",
"=",
"ALL_PRETRAINED_CONFIG_ARCHIVE_MAP",
"[",
"pretrained_model_name_or_path",
"]",
"elif",
"os",
".",
"path",
".",
"isdir",
"(",
"pretrained_model_name_or_path",
")",
":",
"model_card_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"pretrained_model_name_or_path",
",",
"MODEL_CARD_NAME",
")",
"elif",
"os",
".",
"path",
".",
"isfile",
"(",
"pretrained_model_name_or_path",
")",
"or",
"is_remote_url",
"(",
"pretrained_model_name_or_path",
")",
":",
"model_card_file",
"=",
"pretrained_model_name_or_path",
"else",
":",
"model_card_file",
"=",
"hf_bucket_url",
"(",
"pretrained_model_name_or_path",
",",
"filename",
"=",
"MODEL_CARD_NAME",
",",
"mirror",
"=",
"None",
")",
"if",
"find_from_standard_name",
"or",
"pretrained_model_name_or_path",
"in",
"ALL_PRETRAINED_CONFIG_ARCHIVE_MAP",
":",
"model_card_file",
"=",
"model_card_file",
".",
"replace",
"(",
"CONFIG_NAME",
",",
"MODEL_CARD_NAME",
")",
"model_card_file",
"=",
"model_card_file",
".",
"replace",
"(",
"WEIGHTS_NAME",
",",
"MODEL_CARD_NAME",
")",
"model_card_file",
"=",
"model_card_file",
".",
"replace",
"(",
"TF2_WEIGHTS_NAME",
",",
"MODEL_CARD_NAME",
")",
"try",
":",
"# Load from URL or cache if already cached",
"resolved_model_card_file",
"=",
"cached_path",
"(",
"model_card_file",
",",
"cache_dir",
"=",
"cache_dir",
",",
"proxies",
"=",
"proxies",
")",
"if",
"resolved_model_card_file",
"==",
"model_card_file",
":",
"logger",
".",
"info",
"(",
"\"loading model card file {}\"",
".",
"format",
"(",
"model_card_file",
")",
")",
"else",
":",
"logger",
".",
"info",
"(",
"\"loading model card file {} from cache at {}\"",
".",
"format",
"(",
"model_card_file",
",",
"resolved_model_card_file",
")",
")",
"# Load model card",
"modelcard",
"=",
"cls",
".",
"from_json_file",
"(",
"resolved_model_card_file",
")",
"except",
"(",
"EnvironmentError",
",",
"json",
".",
"JSONDecodeError",
")",
":",
"# We fall back on creating an empty model card",
"modelcard",
"=",
"cls",
"(",
")",
"# Update model card with kwargs if needed",
"to_remove",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"hasattr",
"(",
"modelcard",
",",
"key",
")",
":",
"setattr",
"(",
"modelcard",
",",
"key",
",",
"value",
")",
"to_remove",
".",
"append",
"(",
"key",
")",
"for",
"key",
"in",
"to_remove",
":",
"kwargs",
".",
"pop",
"(",
"key",
",",
"None",
")",
"logger",
".",
"info",
"(",
"\"Model card: %s\"",
",",
"str",
"(",
"modelcard",
")",
")",
"if",
"return_unused_kwargs",
":",
"return",
"modelcard",
",",
"kwargs",
"else",
":",
"return",
"modelcard"
] | [
82,
4
] | [
181,
28
] | python | cy | ['en', 'cy', 'hi'] | False |
ModelCard.from_dict | (cls, json_object) | Constructs a `ModelCard` from a Python dictionary of parameters. | Constructs a `ModelCard` from a Python dictionary of parameters. | def from_dict(cls, json_object):
"""Constructs a `ModelCard` from a Python dictionary of parameters."""
return cls(**json_object) | [
"def",
"from_dict",
"(",
"cls",
",",
"json_object",
")",
":",
"return",
"cls",
"(",
"*",
"*",
"json_object",
")"
] | [
184,
4
] | [
186,
33
] | python | en | ['en', 'en', 'en'] | True |
ModelCard.from_json_file | (cls, json_file) | Constructs a `ModelCard` from a json file of parameters. | Constructs a `ModelCard` from a json file of parameters. | def from_json_file(cls, json_file):
"""Constructs a `ModelCard` from a json file of parameters."""
with open(json_file, "r", encoding="utf-8") as reader:
text = reader.read()
dict_obj = json.loads(text)
return cls(**dict_obj) | [
"def",
"from_json_file",
"(",
"cls",
",",
"json_file",
")",
":",
"with",
"open",
"(",
"json_file",
",",
"\"r\"",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"as",
"reader",
":",
"text",
"=",
"reader",
".",
"read",
"(",
")",
"dict_obj",
"=",
"json",
".",
"loads",
"(",
"text",
")",
"return",
"cls",
"(",
"*",
"*",
"dict_obj",
")"
] | [
189,
4
] | [
194,
30
] | python | en | ['en', 'en', 'en'] | True |
ModelCard.to_dict | (self) | Serializes this instance to a Python dictionary. | Serializes this instance to a Python dictionary. | def to_dict(self):
"""Serializes this instance to a Python dictionary."""
output = copy.deepcopy(self.__dict__)
return output | [
"def",
"to_dict",
"(",
"self",
")",
":",
"output",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"__dict__",
")",
"return",
"output"
] | [
202,
4
] | [
205,
21
] | python | en | ['en', 'en', 'en'] | True |
ModelCard.to_json_string | (self) | Serializes this instance to a JSON string. | Serializes this instance to a JSON string. | def to_json_string(self):
"""Serializes this instance to a JSON string."""
return json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n" | [
"def",
"to_json_string",
"(",
"self",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"self",
".",
"to_dict",
"(",
")",
",",
"indent",
"=",
"2",
",",
"sort_keys",
"=",
"True",
")",
"+",
"\"\\n\""
] | [
207,
4
] | [
209,
74
] | python | en | ['en', 'en', 'en'] | True |
ModelCard.to_json_file | (self, json_file_path) | Save this instance to a json file. | Save this instance to a json file. | def to_json_file(self, json_file_path):
""" Save this instance to a json file."""
with open(json_file_path, "w", encoding="utf-8") as writer:
writer.write(self.to_json_string()) | [
"def",
"to_json_file",
"(",
"self",
",",
"json_file_path",
")",
":",
"with",
"open",
"(",
"json_file_path",
",",
"\"w\"",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"as",
"writer",
":",
"writer",
".",
"write",
"(",
"self",
".",
"to_json_string",
"(",
")",
")"
] | [
211,
4
] | [
214,
47
] | python | en | ['en', 'en', 'en'] | True |
setup_platform | (hass, config, add_entities, discovery_info=None) | Set up the NX584 binary sensor platform. | Set up the NX584 binary sensor platform. | def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the NX584 binary sensor platform."""
host = config.get(CONF_HOST)
port = config.get(CONF_PORT)
exclude = config.get(CONF_EXCLUDE_ZONES)
zone_types = config.get(CONF_ZONE_TYPES)
try:
client = nx584_client.Client(f"http://{host}:{port}")
zones = client.list_zones()
except requests.exceptions.ConnectionError as ex:
_LOGGER.error("Unable to connect to NX584: %s", str(ex))
return False
version = [int(v) for v in client.get_version().split(".")]
if version < [1, 1]:
_LOGGER.error("NX584 is too old to use for sensors (>=0.2 required)")
return False
zone_sensors = {
zone["number"]: NX584ZoneSensor(
zone, zone_types.get(zone["number"], DEVICE_CLASS_OPENING)
)
for zone in zones
if zone["number"] not in exclude
}
if zone_sensors:
add_entities(zone_sensors.values())
watcher = NX584Watcher(client, zone_sensors)
watcher.start()
else:
_LOGGER.warning("No zones found on NX584")
return True | [
"def",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"host",
"=",
"config",
".",
"get",
"(",
"CONF_HOST",
")",
"port",
"=",
"config",
".",
"get",
"(",
"CONF_PORT",
")",
"exclude",
"=",
"config",
".",
"get",
"(",
"CONF_EXCLUDE_ZONES",
")",
"zone_types",
"=",
"config",
".",
"get",
"(",
"CONF_ZONE_TYPES",
")",
"try",
":",
"client",
"=",
"nx584_client",
".",
"Client",
"(",
"f\"http://{host}:{port}\"",
")",
"zones",
"=",
"client",
".",
"list_zones",
"(",
")",
"except",
"requests",
".",
"exceptions",
".",
"ConnectionError",
"as",
"ex",
":",
"_LOGGER",
".",
"error",
"(",
"\"Unable to connect to NX584: %s\"",
",",
"str",
"(",
"ex",
")",
")",
"return",
"False",
"version",
"=",
"[",
"int",
"(",
"v",
")",
"for",
"v",
"in",
"client",
".",
"get_version",
"(",
")",
".",
"split",
"(",
"\".\"",
")",
"]",
"if",
"version",
"<",
"[",
"1",
",",
"1",
"]",
":",
"_LOGGER",
".",
"error",
"(",
"\"NX584 is too old to use for sensors (>=0.2 required)\"",
")",
"return",
"False",
"zone_sensors",
"=",
"{",
"zone",
"[",
"\"number\"",
"]",
":",
"NX584ZoneSensor",
"(",
"zone",
",",
"zone_types",
".",
"get",
"(",
"zone",
"[",
"\"number\"",
"]",
",",
"DEVICE_CLASS_OPENING",
")",
")",
"for",
"zone",
"in",
"zones",
"if",
"zone",
"[",
"\"number\"",
"]",
"not",
"in",
"exclude",
"}",
"if",
"zone_sensors",
":",
"add_entities",
"(",
"zone_sensors",
".",
"values",
"(",
")",
")",
"watcher",
"=",
"NX584Watcher",
"(",
"client",
",",
"zone_sensors",
")",
"watcher",
".",
"start",
"(",
")",
"else",
":",
"_LOGGER",
".",
"warning",
"(",
"\"No zones found on NX584\"",
")",
"return",
"True"
] | [
41,
0
] | [
74,
15
] | python | en | ['en', 'pt', 'en'] | True |
NX584ZoneSensor.__init__ | (self, zone, zone_type) | Initialize the nx594 binary sensor. | Initialize the nx594 binary sensor. | def __init__(self, zone, zone_type):
"""Initialize the nx594 binary sensor."""
self._zone = zone
self._zone_type = zone_type | [
"def",
"__init__",
"(",
"self",
",",
"zone",
",",
"zone_type",
")",
":",
"self",
".",
"_zone",
"=",
"zone",
"self",
".",
"_zone_type",
"=",
"zone_type"
] | [
80,
4
] | [
83,
35
] | python | en | ['en', 'haw', 'en'] | True |
NX584ZoneSensor.device_class | (self) | Return the class of this sensor, from DEVICE_CLASSES. | Return the class of this sensor, from DEVICE_CLASSES. | def device_class(self):
"""Return the class of this sensor, from DEVICE_CLASSES."""
return self._zone_type | [
"def",
"device_class",
"(",
"self",
")",
":",
"return",
"self",
".",
"_zone_type"
] | [
86,
4
] | [
88,
30
] | python | en | ['en', 'en', 'en'] | True |
NX584ZoneSensor.should_poll | (self) | No polling needed. | No polling needed. | def should_poll(self):
"""No polling needed."""
return False | [
"def",
"should_poll",
"(",
"self",
")",
":",
"return",
"False"
] | [
91,
4
] | [
93,
20
] | python | en | ['en', 'en', 'en'] | True |
NX584ZoneSensor.name | (self) | Return the name of the binary sensor. | Return the name of the binary sensor. | def name(self):
"""Return the name of the binary sensor."""
return self._zone["name"] | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_zone",
"[",
"\"name\"",
"]"
] | [
96,
4
] | [
98,
33
] | python | en | ['en', 'mi', 'en'] | True |
NX584ZoneSensor.is_on | (self) | Return true if the binary sensor is on. | Return true if the binary sensor is on. | def is_on(self):
"""Return true if the binary sensor is on."""
# True means "faulted" or "open" or "abnormal state"
return self._zone["state"] | [
"def",
"is_on",
"(",
"self",
")",
":",
"# True means \"faulted\" or \"open\" or \"abnormal state\"",
"return",
"self",
".",
"_zone",
"[",
"\"state\"",
"]"
] | [
101,
4
] | [
104,
34
] | python | en | ['en', 'fy', 'en'] | True |
NX584ZoneSensor.device_state_attributes | (self) | Return the state attributes. | Return the state attributes. | def device_state_attributes(self):
"""Return the state attributes."""
return {"zone_number": self._zone["number"]} | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"return",
"{",
"\"zone_number\"",
":",
"self",
".",
"_zone",
"[",
"\"number\"",
"]",
"}"
] | [
107,
4
] | [
109,
52
] | python | en | ['en', 'en', 'en'] | True |
NX584Watcher.__init__ | (self, client, zone_sensors) | Initialize NX584 watcher thread. | Initialize NX584 watcher thread. | def __init__(self, client, zone_sensors):
"""Initialize NX584 watcher thread."""
super().__init__()
self.daemon = True
self._client = client
self._zone_sensors = zone_sensors | [
"def",
"__init__",
"(",
"self",
",",
"client",
",",
"zone_sensors",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
")",
"self",
".",
"daemon",
"=",
"True",
"self",
".",
"_client",
"=",
"client",
"self",
".",
"_zone_sensors",
"=",
"zone_sensors"
] | [
115,
4
] | [
120,
41
] | python | en | ['en', 'pl', 'en'] | True |
NX584Watcher._run | (self) | Throw away any existing events so we don't replay history. | Throw away any existing events so we don't replay history. | def _run(self):
"""Throw away any existing events so we don't replay history."""
self._client.get_events()
while True:
events = self._client.get_events()
if events:
self._process_events(events) | [
"def",
"_run",
"(",
"self",
")",
":",
"self",
".",
"_client",
".",
"get_events",
"(",
")",
"while",
"True",
":",
"events",
"=",
"self",
".",
"_client",
".",
"get_events",
"(",
")",
"if",
"events",
":",
"self",
".",
"_process_events",
"(",
"events",
")"
] | [
136,
4
] | [
142,
44
] | python | en | ['en', 'en', 'en'] | True |
NX584Watcher.run | (self) | Run the watcher. | Run the watcher. | def run(self):
"""Run the watcher."""
while True:
try:
self._run()
except requests.exceptions.ConnectionError:
_LOGGER.error("Failed to reach NX584 server")
time.sleep(10) | [
"def",
"run",
"(",
"self",
")",
":",
"while",
"True",
":",
"try",
":",
"self",
".",
"_run",
"(",
")",
"except",
"requests",
".",
"exceptions",
".",
"ConnectionError",
":",
"_LOGGER",
".",
"error",
"(",
"\"Failed to reach NX584 server\"",
")",
"time",
".",
"sleep",
"(",
"10",
")"
] | [
144,
4
] | [
151,
30
] | python | en | ['en', 'lb', 'en'] | True |
test_form | (hass) | Test we get the form. | Test we get the form. | async def test_form(hass):
"""Test we get the form."""
await setup.async_setup_component(hass, "avri", {})
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == "form"
assert result["errors"] == {}
with patch(
"homeassistant.components.avri.async_setup_entry",
return_value=True,
) as mock_setup_entry:
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
"zip_code": "1234AB",
"house_number": 42,
"house_number_extension": "",
"country_code": "NL",
},
)
assert result2["type"] == "create_entry"
assert result2["title"] == "1234AB 42"
assert result2["data"] == {
"id": "1234AB 42",
"zip_code": "1234AB",
"house_number": 42,
"house_number_extension": "",
"country_code": "NL",
}
await hass.async_block_till_done()
assert len(mock_setup_entry.mock_calls) == 1 | [
"async",
"def",
"test_form",
"(",
"hass",
")",
":",
"await",
"setup",
".",
"async_setup_component",
"(",
"hass",
",",
"\"avri\"",
",",
"{",
"}",
")",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"config_entries",
".",
"SOURCE_USER",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"\"form\"",
"assert",
"result",
"[",
"\"errors\"",
"]",
"==",
"{",
"}",
"with",
"patch",
"(",
"\"homeassistant.components.avri.async_setup_entry\"",
",",
"return_value",
"=",
"True",
",",
")",
"as",
"mock_setup_entry",
":",
"result2",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"{",
"\"zip_code\"",
":",
"\"1234AB\"",
",",
"\"house_number\"",
":",
"42",
",",
"\"house_number_extension\"",
":",
"\"\"",
",",
"\"country_code\"",
":",
"\"NL\"",
",",
"}",
",",
")",
"assert",
"result2",
"[",
"\"type\"",
"]",
"==",
"\"create_entry\"",
"assert",
"result2",
"[",
"\"title\"",
"]",
"==",
"\"1234AB 42\"",
"assert",
"result2",
"[",
"\"data\"",
"]",
"==",
"{",
"\"id\"",
":",
"\"1234AB 42\"",
",",
"\"zip_code\"",
":",
"\"1234AB\"",
",",
"\"house_number\"",
":",
"42",
",",
"\"house_number_extension\"",
":",
"\"\"",
",",
"\"country_code\"",
":",
"\"NL\"",
",",
"}",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"len",
"(",
"mock_setup_entry",
".",
"mock_calls",
")",
"==",
"1"
] | [
7,
0
] | [
40,
48
] | python | en | ['en', 'en', 'en'] | True |
test_form_invalid_house_number | (hass) | Test we handle invalid house number. | Test we handle invalid house number. | async def test_form_invalid_house_number(hass):
"""Test we handle invalid house number."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
"zip_code": "1234AB",
"house_number": -1,
"house_number_extension": "",
"country_code": "NL",
},
)
assert result2["type"] == "form"
assert result2["errors"] == {"house_number": "invalid_house_number"} | [
"async",
"def",
"test_form_invalid_house_number",
"(",
"hass",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"config_entries",
".",
"SOURCE_USER",
"}",
")",
"result2",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"{",
"\"zip_code\"",
":",
"\"1234AB\"",
",",
"\"house_number\"",
":",
"-",
"1",
",",
"\"house_number_extension\"",
":",
"\"\"",
",",
"\"country_code\"",
":",
"\"NL\"",
",",
"}",
",",
")",
"assert",
"result2",
"[",
"\"type\"",
"]",
"==",
"\"form\"",
"assert",
"result2",
"[",
"\"errors\"",
"]",
"==",
"{",
"\"house_number\"",
":",
"\"invalid_house_number\"",
"}"
] | [
43,
0
] | [
60,
72
] | python | en | ['en', 'en', 'en'] | True |
test_form_invalid_country_code | (hass) | Test we handle invalid county code. | Test we handle invalid county code. | async def test_form_invalid_country_code(hass):
"""Test we handle invalid county code."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
"zip_code": "1234AB",
"house_number": 42,
"house_number_extension": "",
"country_code": "foo",
},
)
assert result2["type"] == "form"
assert result2["errors"] == {"country_code": "invalid_country_code"} | [
"async",
"def",
"test_form_invalid_country_code",
"(",
"hass",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"config_entries",
".",
"SOURCE_USER",
"}",
")",
"result2",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"{",
"\"zip_code\"",
":",
"\"1234AB\"",
",",
"\"house_number\"",
":",
"42",
",",
"\"house_number_extension\"",
":",
"\"\"",
",",
"\"country_code\"",
":",
"\"foo\"",
",",
"}",
",",
")",
"assert",
"result2",
"[",
"\"type\"",
"]",
"==",
"\"form\"",
"assert",
"result2",
"[",
"\"errors\"",
"]",
"==",
"{",
"\"country_code\"",
":",
"\"invalid_country_code\"",
"}"
] | [
63,
0
] | [
80,
72
] | python | en | ['en', 'en', 'en'] | True |
FlickConfigFlow.async_step_user | (self, user_input=None) | Handle gathering login info. | Handle gathering login info. | async def async_step_user(self, user_input=None):
"""Handle gathering login info."""
errors = {}
if user_input is not None:
try:
await self._validate_input(user_input)
except CannotConnect:
errors["base"] = "cannot_connect"
except InvalidAuth:
errors["base"] = "invalid_auth"
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
await self.async_set_unique_id(
f"flick_electric_{user_input[CONF_USERNAME]}"
)
self._abort_if_unique_id_configured()
return self.async_create_entry(
title=f"Flick Electric: {user_input[CONF_USERNAME]}",
data=user_input,
)
return self.async_show_form(
step_id="user", data_schema=DATA_SCHEMA, errors=errors
) | [
"async",
"def",
"async_step_user",
"(",
"self",
",",
"user_input",
"=",
"None",
")",
":",
"errors",
"=",
"{",
"}",
"if",
"user_input",
"is",
"not",
"None",
":",
"try",
":",
"await",
"self",
".",
"_validate_input",
"(",
"user_input",
")",
"except",
"CannotConnect",
":",
"errors",
"[",
"\"base\"",
"]",
"=",
"\"cannot_connect\"",
"except",
"InvalidAuth",
":",
"errors",
"[",
"\"base\"",
"]",
"=",
"\"invalid_auth\"",
"except",
"Exception",
":",
"# pylint: disable=broad-except",
"_LOGGER",
".",
"exception",
"(",
"\"Unexpected exception\"",
")",
"errors",
"[",
"\"base\"",
"]",
"=",
"\"unknown\"",
"else",
":",
"await",
"self",
".",
"async_set_unique_id",
"(",
"f\"flick_electric_{user_input[CONF_USERNAME]}\"",
")",
"self",
".",
"_abort_if_unique_id_configured",
"(",
")",
"return",
"self",
".",
"async_create_entry",
"(",
"title",
"=",
"f\"Flick Electric: {user_input[CONF_USERNAME]}\"",
",",
"data",
"=",
"user_input",
",",
")",
"return",
"self",
".",
"async_show_form",
"(",
"step_id",
"=",
"\"user\"",
",",
"data_schema",
"=",
"DATA_SCHEMA",
",",
"errors",
"=",
"errors",
")"
] | [
57,
4
] | [
83,
9
] | python | en | ['en', 'jv', 'en'] | True |
setup_comp | (hass) | Initialize components. | Initialize components. | async def setup_comp(hass):
"""Initialize components."""
assert await async_setup_component(hass, fan.DOMAIN, {"fan": {"platform": "demo"}})
await hass.async_block_till_done() | [
"async",
"def",
"setup_comp",
"(",
"hass",
")",
":",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"fan",
".",
"DOMAIN",
",",
"{",
"\"fan\"",
":",
"{",
"\"platform\"",
":",
"\"demo\"",
"}",
"}",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")"
] | [
18,
0
] | [
21,
38
] | python | en | ['de', 'en', 'en'] | False |
test_turn_on | (hass) | Test turning on the device. | Test turning on the device. | async def test_turn_on(hass):
"""Test turning on the device."""
state = hass.states.get(FAN_ENTITY_ID)
assert state.state == STATE_OFF
await hass.services.async_call(
fan.DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: FAN_ENTITY_ID}, blocking=True
)
state = hass.states.get(FAN_ENTITY_ID)
assert state.state == STATE_ON
await hass.services.async_call(
fan.DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: FAN_ENTITY_ID, fan.ATTR_SPEED: fan.SPEED_HIGH},
blocking=True,
)
state = hass.states.get(FAN_ENTITY_ID)
assert state.state == STATE_ON
assert state.attributes[fan.ATTR_SPEED] == fan.SPEED_HIGH | [
"async",
"def",
"test_turn_on",
"(",
"hass",
")",
":",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"FAN_ENTITY_ID",
")",
"assert",
"state",
".",
"state",
"==",
"STATE_OFF",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"fan",
".",
"DOMAIN",
",",
"SERVICE_TURN_ON",
",",
"{",
"ATTR_ENTITY_ID",
":",
"FAN_ENTITY_ID",
"}",
",",
"blocking",
"=",
"True",
")",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"FAN_ENTITY_ID",
")",
"assert",
"state",
".",
"state",
"==",
"STATE_ON",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"fan",
".",
"DOMAIN",
",",
"SERVICE_TURN_ON",
",",
"{",
"ATTR_ENTITY_ID",
":",
"FAN_ENTITY_ID",
",",
"fan",
".",
"ATTR_SPEED",
":",
"fan",
".",
"SPEED_HIGH",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"FAN_ENTITY_ID",
")",
"assert",
"state",
".",
"state",
"==",
"STATE_ON",
"assert",
"state",
".",
"attributes",
"[",
"fan",
".",
"ATTR_SPEED",
"]",
"==",
"fan",
".",
"SPEED_HIGH"
] | [
24,
0
] | [
43,
61
] | python | en | ['en', 'en', 'en'] | True |
test_turn_off | (hass) | Test turning off the device. | Test turning off the device. | async def test_turn_off(hass):
"""Test turning off the device."""
state = hass.states.get(FAN_ENTITY_ID)
assert state.state == STATE_OFF
await hass.services.async_call(
fan.DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: FAN_ENTITY_ID}, blocking=True
)
state = hass.states.get(FAN_ENTITY_ID)
assert state.state == STATE_ON
await hass.services.async_call(
fan.DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: FAN_ENTITY_ID}, blocking=True
)
state = hass.states.get(FAN_ENTITY_ID)
assert state.state == STATE_OFF | [
"async",
"def",
"test_turn_off",
"(",
"hass",
")",
":",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"FAN_ENTITY_ID",
")",
"assert",
"state",
".",
"state",
"==",
"STATE_OFF",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"fan",
".",
"DOMAIN",
",",
"SERVICE_TURN_ON",
",",
"{",
"ATTR_ENTITY_ID",
":",
"FAN_ENTITY_ID",
"}",
",",
"blocking",
"=",
"True",
")",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"FAN_ENTITY_ID",
")",
"assert",
"state",
".",
"state",
"==",
"STATE_ON",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"fan",
".",
"DOMAIN",
",",
"SERVICE_TURN_OFF",
",",
"{",
"ATTR_ENTITY_ID",
":",
"FAN_ENTITY_ID",
"}",
",",
"blocking",
"=",
"True",
")",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"FAN_ENTITY_ID",
")",
"assert",
"state",
".",
"state",
"==",
"STATE_OFF"
] | [
46,
0
] | [
61,
35
] | python | en | ['en', 'en', 'en'] | True |
test_turn_off_without_entity_id | (hass) | Test turning off all fans. | Test turning off all fans. | async def test_turn_off_without_entity_id(hass):
"""Test turning off all fans."""
state = hass.states.get(FAN_ENTITY_ID)
assert state.state == STATE_OFF
await hass.services.async_call(
fan.DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: FAN_ENTITY_ID}, blocking=True
)
state = hass.states.get(FAN_ENTITY_ID)
assert state.state == STATE_ON
await hass.services.async_call(
fan.DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: ENTITY_MATCH_ALL}, blocking=True
)
state = hass.states.get(FAN_ENTITY_ID)
assert state.state == STATE_OFF | [
"async",
"def",
"test_turn_off_without_entity_id",
"(",
"hass",
")",
":",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"FAN_ENTITY_ID",
")",
"assert",
"state",
".",
"state",
"==",
"STATE_OFF",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"fan",
".",
"DOMAIN",
",",
"SERVICE_TURN_ON",
",",
"{",
"ATTR_ENTITY_ID",
":",
"FAN_ENTITY_ID",
"}",
",",
"blocking",
"=",
"True",
")",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"FAN_ENTITY_ID",
")",
"assert",
"state",
".",
"state",
"==",
"STATE_ON",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"fan",
".",
"DOMAIN",
",",
"SERVICE_TURN_OFF",
",",
"{",
"ATTR_ENTITY_ID",
":",
"ENTITY_MATCH_ALL",
"}",
",",
"blocking",
"=",
"True",
")",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"FAN_ENTITY_ID",
")",
"assert",
"state",
".",
"state",
"==",
"STATE_OFF"
] | [
64,
0
] | [
79,
35
] | python | en | ['en', 'en', 'en'] | True |
test_set_direction | (hass) | Test setting the direction of the device. | Test setting the direction of the device. | async def test_set_direction(hass):
"""Test setting the direction of the device."""
state = hass.states.get(FAN_ENTITY_ID)
assert state.state == STATE_OFF
await hass.services.async_call(
fan.DOMAIN,
fan.SERVICE_SET_DIRECTION,
{ATTR_ENTITY_ID: FAN_ENTITY_ID, fan.ATTR_DIRECTION: fan.DIRECTION_REVERSE},
blocking=True,
)
state = hass.states.get(FAN_ENTITY_ID)
assert state.attributes[fan.ATTR_DIRECTION] == fan.DIRECTION_REVERSE | [
"async",
"def",
"test_set_direction",
"(",
"hass",
")",
":",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"FAN_ENTITY_ID",
")",
"assert",
"state",
".",
"state",
"==",
"STATE_OFF",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"fan",
".",
"DOMAIN",
",",
"fan",
".",
"SERVICE_SET_DIRECTION",
",",
"{",
"ATTR_ENTITY_ID",
":",
"FAN_ENTITY_ID",
",",
"fan",
".",
"ATTR_DIRECTION",
":",
"fan",
".",
"DIRECTION_REVERSE",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"FAN_ENTITY_ID",
")",
"assert",
"state",
".",
"attributes",
"[",
"fan",
".",
"ATTR_DIRECTION",
"]",
"==",
"fan",
".",
"DIRECTION_REVERSE"
] | [
82,
0
] | [
94,
72
] | python | en | ['en', 'en', 'en'] | True |
test_set_speed | (hass) | Test setting the speed of the device. | Test setting the speed of the device. | async def test_set_speed(hass):
"""Test setting the speed of the device."""
state = hass.states.get(FAN_ENTITY_ID)
assert state.state == STATE_OFF
await hass.services.async_call(
fan.DOMAIN,
fan.SERVICE_SET_SPEED,
{ATTR_ENTITY_ID: FAN_ENTITY_ID, fan.ATTR_SPEED: fan.SPEED_LOW},
blocking=True,
)
state = hass.states.get(FAN_ENTITY_ID)
assert state.attributes[fan.ATTR_SPEED] == fan.SPEED_LOW | [
"async",
"def",
"test_set_speed",
"(",
"hass",
")",
":",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"FAN_ENTITY_ID",
")",
"assert",
"state",
".",
"state",
"==",
"STATE_OFF",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"fan",
".",
"DOMAIN",
",",
"fan",
".",
"SERVICE_SET_SPEED",
",",
"{",
"ATTR_ENTITY_ID",
":",
"FAN_ENTITY_ID",
",",
"fan",
".",
"ATTR_SPEED",
":",
"fan",
".",
"SPEED_LOW",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"FAN_ENTITY_ID",
")",
"assert",
"state",
".",
"attributes",
"[",
"fan",
".",
"ATTR_SPEED",
"]",
"==",
"fan",
".",
"SPEED_LOW"
] | [
97,
0
] | [
109,
60
] | python | en | ['en', 'en', 'en'] | True |
test_oscillate | (hass) | Test oscillating the fan. | Test oscillating the fan. | async def test_oscillate(hass):
"""Test oscillating the fan."""
state = hass.states.get(FAN_ENTITY_ID)
assert state.state == STATE_OFF
assert not state.attributes.get(fan.ATTR_OSCILLATING)
await hass.services.async_call(
fan.DOMAIN,
fan.SERVICE_OSCILLATE,
{ATTR_ENTITY_ID: FAN_ENTITY_ID, fan.ATTR_OSCILLATING: True},
blocking=True,
)
state = hass.states.get(FAN_ENTITY_ID)
assert state.attributes[fan.ATTR_OSCILLATING] is True
await hass.services.async_call(
fan.DOMAIN,
fan.SERVICE_OSCILLATE,
{ATTR_ENTITY_ID: FAN_ENTITY_ID, fan.ATTR_OSCILLATING: False},
blocking=True,
)
state = hass.states.get(FAN_ENTITY_ID)
assert state.attributes[fan.ATTR_OSCILLATING] is False | [
"async",
"def",
"test_oscillate",
"(",
"hass",
")",
":",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"FAN_ENTITY_ID",
")",
"assert",
"state",
".",
"state",
"==",
"STATE_OFF",
"assert",
"not",
"state",
".",
"attributes",
".",
"get",
"(",
"fan",
".",
"ATTR_OSCILLATING",
")",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"fan",
".",
"DOMAIN",
",",
"fan",
".",
"SERVICE_OSCILLATE",
",",
"{",
"ATTR_ENTITY_ID",
":",
"FAN_ENTITY_ID",
",",
"fan",
".",
"ATTR_OSCILLATING",
":",
"True",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"FAN_ENTITY_ID",
")",
"assert",
"state",
".",
"attributes",
"[",
"fan",
".",
"ATTR_OSCILLATING",
"]",
"is",
"True",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"fan",
".",
"DOMAIN",
",",
"fan",
".",
"SERVICE_OSCILLATE",
",",
"{",
"ATTR_ENTITY_ID",
":",
"FAN_ENTITY_ID",
",",
"fan",
".",
"ATTR_OSCILLATING",
":",
"False",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"FAN_ENTITY_ID",
")",
"assert",
"state",
".",
"attributes",
"[",
"fan",
".",
"ATTR_OSCILLATING",
"]",
"is",
"False"
] | [
112,
0
] | [
134,
58
] | python | en | ['en', 'en', 'en'] | True |
test_is_on | (hass) | Test is on service call. | Test is on service call. | async def test_is_on(hass):
"""Test is on service call."""
assert not fan.is_on(hass, FAN_ENTITY_ID)
await hass.services.async_call(
fan.DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: FAN_ENTITY_ID}, blocking=True
)
assert fan.is_on(hass, FAN_ENTITY_ID) | [
"async",
"def",
"test_is_on",
"(",
"hass",
")",
":",
"assert",
"not",
"fan",
".",
"is_on",
"(",
"hass",
",",
"FAN_ENTITY_ID",
")",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"fan",
".",
"DOMAIN",
",",
"SERVICE_TURN_ON",
",",
"{",
"ATTR_ENTITY_ID",
":",
"FAN_ENTITY_ID",
"}",
",",
"blocking",
"=",
"True",
")",
"assert",
"fan",
".",
"is_on",
"(",
"hass",
",",
"FAN_ENTITY_ID",
")"
] | [
137,
0
] | [
144,
41
] | python | en | ['en', 'en', 'en'] | True |
async_setup_entry | (hass, entry, async_add_entities) | Set up the StarLine sensors. | Set up the StarLine sensors. | async def async_setup_entry(hass, entry, async_add_entities):
"""Set up the StarLine sensors."""
account: StarlineAccount = hass.data[DOMAIN][entry.entry_id]
entities = []
for device in account.api.devices.values():
for key, value in SENSOR_TYPES.items():
sensor = StarlineSensor(account, device, key, *value)
if sensor.state is not None:
entities.append(sensor)
async_add_entities(entities) | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
",",
"entry",
",",
"async_add_entities",
")",
":",
"account",
":",
"StarlineAccount",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"entry",
".",
"entry_id",
"]",
"entities",
"=",
"[",
"]",
"for",
"device",
"in",
"account",
".",
"api",
".",
"devices",
".",
"values",
"(",
")",
":",
"for",
"key",
",",
"value",
"in",
"SENSOR_TYPES",
".",
"items",
"(",
")",
":",
"sensor",
"=",
"StarlineSensor",
"(",
"account",
",",
"device",
",",
"key",
",",
"*",
"value",
")",
"if",
"sensor",
".",
"state",
"is",
"not",
"None",
":",
"entities",
".",
"append",
"(",
"sensor",
")",
"async_add_entities",
"(",
"entities",
")"
] | [
19,
0
] | [
28,
32
] | python | en | ['en', 'bs', 'en'] | True |
StarlineSensor.__init__ | (
self,
account: StarlineAccount,
device: StarlineDevice,
key: str,
name: str,
device_class: str,
unit: str,
icon: str,
) | Initialize StarLine sensor. | Initialize StarLine sensor. | def __init__(
self,
account: StarlineAccount,
device: StarlineDevice,
key: str,
name: str,
device_class: str,
unit: str,
icon: str,
):
"""Initialize StarLine sensor."""
super().__init__(account, device, key, name)
self._device_class = device_class
self._unit = unit
self._icon = icon | [
"def",
"__init__",
"(",
"self",
",",
"account",
":",
"StarlineAccount",
",",
"device",
":",
"StarlineDevice",
",",
"key",
":",
"str",
",",
"name",
":",
"str",
",",
"device_class",
":",
"str",
",",
"unit",
":",
"str",
",",
"icon",
":",
"str",
",",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"account",
",",
"device",
",",
"key",
",",
"name",
")",
"self",
".",
"_device_class",
"=",
"device_class",
"self",
".",
"_unit",
"=",
"unit",
"self",
".",
"_icon",
"=",
"icon"
] | [
34,
4
] | [
48,
25
] | python | en | ['en', 'hr', 'it'] | False |
StarlineSensor.icon | (self) | Icon to use in the frontend, if any. | Icon to use in the frontend, if any. | def icon(self):
"""Icon to use in the frontend, if any."""
if self._key == "battery":
return icon_for_battery_level(
battery_level=self._device.battery_level_percent,
charging=self._device.car_state.get("ign", False),
)
if self._key == "gsm_lvl":
return icon_for_signal_level(signal_level=self._device.gsm_level_percent)
return self._icon | [
"def",
"icon",
"(",
"self",
")",
":",
"if",
"self",
".",
"_key",
"==",
"\"battery\"",
":",
"return",
"icon_for_battery_level",
"(",
"battery_level",
"=",
"self",
".",
"_device",
".",
"battery_level_percent",
",",
"charging",
"=",
"self",
".",
"_device",
".",
"car_state",
".",
"get",
"(",
"\"ign\"",
",",
"False",
")",
",",
")",
"if",
"self",
".",
"_key",
"==",
"\"gsm_lvl\"",
":",
"return",
"icon_for_signal_level",
"(",
"signal_level",
"=",
"self",
".",
"_device",
".",
"gsm_level_percent",
")",
"return",
"self",
".",
"_icon"
] | [
51,
4
] | [
60,
25
] | python | en | ['en', 'en', 'en'] | True |
StarlineSensor.state | (self) | Return the state of the sensor. | Return the state of the sensor. | def state(self):
"""Return the state of the sensor."""
if self._key == "battery":
return self._device.battery_level
if self._key == "balance":
return self._device.balance.get("value")
if self._key == "ctemp":
return self._device.temp_inner
if self._key == "etemp":
return self._device.temp_engine
if self._key == "gsm_lvl":
return self._device.gsm_level_percent
return None | [
"def",
"state",
"(",
"self",
")",
":",
"if",
"self",
".",
"_key",
"==",
"\"battery\"",
":",
"return",
"self",
".",
"_device",
".",
"battery_level",
"if",
"self",
".",
"_key",
"==",
"\"balance\"",
":",
"return",
"self",
".",
"_device",
".",
"balance",
".",
"get",
"(",
"\"value\"",
")",
"if",
"self",
".",
"_key",
"==",
"\"ctemp\"",
":",
"return",
"self",
".",
"_device",
".",
"temp_inner",
"if",
"self",
".",
"_key",
"==",
"\"etemp\"",
":",
"return",
"self",
".",
"_device",
".",
"temp_engine",
"if",
"self",
".",
"_key",
"==",
"\"gsm_lvl\"",
":",
"return",
"self",
".",
"_device",
".",
"gsm_level_percent",
"return",
"None"
] | [
63,
4
] | [
75,
19
] | python | en | ['en', 'en', 'en'] | True |
StarlineSensor.unit_of_measurement | (self) | Get the unit of measurement. | Get the unit of measurement. | def unit_of_measurement(self):
"""Get the unit of measurement."""
if self._key == "balance":
return self._device.balance.get("currency") or "₽"
return self._unit | [
"def",
"unit_of_measurement",
"(",
"self",
")",
":",
"if",
"self",
".",
"_key",
"==",
"\"balance\"",
":",
"return",
"self",
".",
"_device",
".",
"balance",
".",
"get",
"(",
"\"currency\"",
")",
"or",
"\"₽\"",
"return",
"self",
".",
"_unit"
] | [
78,
4
] | [
82,
25
] | python | en | ['en', 'fr', 'en'] | True |
StarlineSensor.device_class | (self) | Return the class of the sensor. | Return the class of the sensor. | def device_class(self):
"""Return the class of the sensor."""
return self._device_class | [
"def",
"device_class",
"(",
"self",
")",
":",
"return",
"self",
".",
"_device_class"
] | [
85,
4
] | [
87,
33
] | python | en | ['en', 'pt', 'en'] | True |
StarlineSensor.device_state_attributes | (self) | Return the state attributes of the sensor. | Return the state attributes of the sensor. | def device_state_attributes(self):
"""Return the state attributes of the sensor."""
if self._key == "balance":
return self._account.balance_attrs(self._device)
if self._key == "gsm_lvl":
return self._account.gsm_attrs(self._device)
return None | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"if",
"self",
".",
"_key",
"==",
"\"balance\"",
":",
"return",
"self",
".",
"_account",
".",
"balance_attrs",
"(",
"self",
".",
"_device",
")",
"if",
"self",
".",
"_key",
"==",
"\"gsm_lvl\"",
":",
"return",
"self",
".",
"_account",
".",
"gsm_attrs",
"(",
"self",
".",
"_device",
")",
"return",
"None"
] | [
90,
4
] | [
96,
19
] | python | en | ['en', 'en', 'en'] | True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.