223 lines
7.1 KiB
Python
223 lines
7.1 KiB
Python
"""Service for blinking lights in morse code."""
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import logging
|
|
from typing import Any
|
|
|
|
from homeassistant.core import HomeAssistant, ServiceCall
|
|
from homeassistant.helpers import entity_registry as er
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
# Morse code dictionary
|
|
MORSE_CODE = {
|
|
"A": ".-",
|
|
"B": "-...",
|
|
"C": "-.-.",
|
|
"D": "-..",
|
|
"E": ".",
|
|
"F": "..-.",
|
|
"G": "--.",
|
|
"H": "....",
|
|
"I": "..",
|
|
"J": ".---",
|
|
"K": "-.-",
|
|
"L": ".-..",
|
|
"M": "--",
|
|
"N": "-.",
|
|
"O": "---",
|
|
"P": ".--.",
|
|
"Q": "--.-",
|
|
"R": ".-.",
|
|
"S": "...",
|
|
"T": "-",
|
|
"U": "..-",
|
|
"V": "...-",
|
|
"W": ".--",
|
|
"X": "-..-",
|
|
"Y": "-.--",
|
|
"Z": "--..",
|
|
"0": "-----",
|
|
"1": ".----",
|
|
"2": "..---",
|
|
"3": "...--",
|
|
"4": "....-",
|
|
"5": ".....",
|
|
"6": "-....",
|
|
"7": "--...",
|
|
"8": "---..",
|
|
"9": "----.",
|
|
".": ".-.-.-",
|
|
",": "--..--",
|
|
"?": "..--..",
|
|
"'": ".----.",
|
|
"!": "-.-.--",
|
|
"/": "-..-.",
|
|
"(": "-.--.",
|
|
")": "-.--.-",
|
|
"&": ".-...",
|
|
":": "---...",
|
|
";": "-.-.-.",
|
|
"=": "-...-",
|
|
"+": ".-.-.",
|
|
"-": "-....-",
|
|
"_": "..--.-",
|
|
'"': ".-..-.",
|
|
"$": "...-..-",
|
|
"@": ".--.-.",
|
|
"#": "...---...", # Hash is short for dedicated SOS code
|
|
" ": " ",
|
|
}
|
|
|
|
# Timing constants (in seconds)
|
|
DOT_DURATION = 0.15 # Duration of a dot
|
|
DASH_DURATION = 0.6 # Duration of a dash (4x dot, instead of 3x, to look like better signaling with the transition of a LED)
|
|
ELEMENT_GAP = 0.15 # Gap between dots/dashes within a letter
|
|
LETTER_GAP = 0.6 # Gap between letters (4x dot, as above)
|
|
WORD_GAP = 1.8 # Gap between words (3x letter gap)
|
|
|
|
|
|
def text_to_morse(text: str) -> list[str]:
|
|
"""Convert text to morse code sequence."""
|
|
morse = []
|
|
for char in text.upper():
|
|
if char in MORSE_CODE:
|
|
morse.append(MORSE_CODE[char])
|
|
elif char == " ":
|
|
morse.append(" ") # Word separator
|
|
return morse
|
|
|
|
|
|
def calculate_transmission_time(
|
|
message: str,
|
|
dot_duration: float = DOT_DURATION,
|
|
dash_duration: float = DASH_DURATION,
|
|
element_gap: float = ELEMENT_GAP,
|
|
letter_gap: float = LETTER_GAP,
|
|
word_gap: float = WORD_GAP,
|
|
) -> float:
|
|
"""
|
|
Calculate the total time (in seconds) it would take to transmit a morse code message.
|
|
|
|
Args:
|
|
message: The text message to calculate transmission time for
|
|
dot_duration: Duration of a dot in seconds
|
|
dash_duration: Duration of a dash in seconds
|
|
element_gap: Gap between dots/dashes within a letter in seconds
|
|
letter_gap: Gap between letters in seconds
|
|
word_gap: Gap between words in seconds
|
|
|
|
Returns:
|
|
Total transmission time in seconds
|
|
"""
|
|
morse_sequence = text_to_morse(message)
|
|
total_time = 0.0
|
|
|
|
for i, morse_letter in enumerate(morse_sequence):
|
|
if morse_letter == " ":
|
|
# Word separator: add word gap
|
|
total_time += word_gap
|
|
else:
|
|
# Process each dot/dash in the letter
|
|
for j, element in enumerate(morse_letter):
|
|
if element == ".":
|
|
total_time += dot_duration
|
|
elif element == "-":
|
|
total_time += dash_duration
|
|
|
|
# Add gap between elements (except after last element)
|
|
if j < len(morse_letter) - 1:
|
|
total_time += element_gap
|
|
|
|
# Add gap between letters (except after last letter or before word separator)
|
|
if i < len(morse_sequence) - 1 and morse_sequence[i + 1] != " ":
|
|
total_time += letter_gap
|
|
|
|
return total_time
|
|
|
|
|
|
async def async_blink_morse_code(hass: HomeAssistant, data: dict[str, Any]) -> None:
|
|
"""Blink a light entity in morse code."""
|
|
_LOGGER.debug("async_blink_morse_code called with data: %s", data)
|
|
|
|
entity_ids = data.get("entity_id")
|
|
message = data.get("message", "")
|
|
dot_duration = data.get("dot_duration", DOT_DURATION)
|
|
dash_duration = data.get("dash_duration", DASH_DURATION)
|
|
element_gap = data.get("element_gap", ELEMENT_GAP)
|
|
letter_gap = data.get("letter_gap", LETTER_GAP)
|
|
word_gap = data.get("word_gap", WORD_GAP)
|
|
transition = data.get("transition", 0) # Default to 0 for instant on/off
|
|
|
|
_LOGGER.debug("Parsed parameters: entity_ids=%s, message='%s'", entity_ids, message)
|
|
|
|
if not entity_ids:
|
|
error_msg = "entity_id is required"
|
|
_LOGGER.error(error_msg)
|
|
raise ValueError(error_msg)
|
|
|
|
if not message:
|
|
error_msg = "message is required"
|
|
_LOGGER.error(error_msg)
|
|
raise ValueError(error_msg)
|
|
|
|
# Normalize entity_id to list
|
|
if isinstance(entity_ids, str):
|
|
entity_ids = [entity_ids]
|
|
|
|
_LOGGER.debug("Normalized entity_ids: %s", entity_ids)
|
|
|
|
# Verify entities exist
|
|
for entity_id in entity_ids:
|
|
state = hass.states.get(entity_id)
|
|
if not state:
|
|
error_msg = f"Entity {entity_id} not found"
|
|
_LOGGER.error(error_msg)
|
|
raise ValueError(error_msg)
|
|
_LOGGER.debug("Found entity %s: %s", entity_id, state.state)
|
|
|
|
# Convert message to morse code
|
|
morse_sequence = text_to_morse(message)
|
|
_LOGGER.info("Blinking morse code for message '%s': %s", message, morse_sequence)
|
|
|
|
# Blink the lights according to morse code
|
|
for i, morse_letter in enumerate(morse_sequence):
|
|
if morse_letter == " ":
|
|
# Word separator: wait for word gap
|
|
await asyncio.sleep(word_gap)
|
|
else:
|
|
# Process each dot/dash in the letter
|
|
for j, element in enumerate(morse_letter):
|
|
if element == ".":
|
|
# Dot: turn on, wait, turn off
|
|
await hass.services.async_call("light", "turn_on", {
|
|
"entity_id": entity_ids,
|
|
"transition": transition
|
|
})
|
|
await asyncio.sleep(dot_duration)
|
|
await hass.services.async_call("light", "turn_off", {
|
|
"entity_id": entity_ids,
|
|
"transition": transition
|
|
})
|
|
elif element == "-":
|
|
# Dash: turn on, wait longer, turn off
|
|
await hass.services.async_call("light", "turn_on", {
|
|
"entity_id": entity_ids,
|
|
"transition": transition
|
|
})
|
|
await asyncio.sleep(dash_duration)
|
|
await hass.services.async_call("light", "turn_off", {
|
|
"entity_id": entity_ids,
|
|
"transition": transition
|
|
})
|
|
|
|
# Add gap between elements (except after last element)
|
|
if j < len(morse_letter) - 1:
|
|
await asyncio.sleep(element_gap)
|
|
|
|
# Add gap between letters (except after last letter or before word separator)
|
|
if i < len(morse_sequence) - 1 and morse_sequence[i + 1] != " ":
|
|
await asyncio.sleep(letter_gap)
|
|
|