iobroker.assistant 1.4.13 → 1.4.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -237,6 +237,9 @@ train it twice.
237
237
  Placeholder for the next version (at the beginning of the line):
238
238
  ### **WORK IN PROGRESS**
239
239
  -->
240
+ ### 1.4.14 (2026-11-07)
241
+ * (@GermanBluefox) ESPHome satellites, dialog mode: a satellite that does not listen again after an answer (it stopped the answer itself — stop word, tap) ends the mode instead of leaving it on while nobody listens; the log says how much of the answer was played
242
+
240
243
  ### 1.4.13 (2026-11-07)
241
244
  * (@GermanBluefox) If fullcalendar is installed, it must be 3.1.0 or later (the version with the event API that commands for later use)
242
245
  * (@GermanBluefox) Devices renamed in the device list keep their room, type and all their states again (`@iobroker/mcp-server` 1.9.2): before, such a device lost its room, so "the light in the kitchen" was not understood, and a light lost the switch next to its level
@@ -220,6 +220,14 @@ const DIALOG_CHECK_MS = 5000;
220
220
  * open its microphone again — an ESPHome device does that only after a reply has played.
221
221
  */
222
222
  const DIALOG_PAUSE_MS = 250;
223
+ /**
224
+ * Dialog mode: once its reply has played, the device opens the microphone again by itself (ThirdReality after its
225
+ * "continue conversation delay", 0.5 s by default). Nothing within this time: it does not listen, and the mode goes off
226
+ * — its stop word or a tap ended the reply, or it lost the flag.
227
+ */
228
+ const DIALOG_REOPEN_MS = 6000;
229
+ /** A reply that ended this much earlier than its length was cut on the device. */
230
+ const REPLY_CUT_MS = 500;
223
231
  /** "Yes" and "no" as a button answer is passed on: the words of the satellite's language, which pi-agent also takes. */
224
232
  const YES_NO = {
225
233
  en: ['Yes', 'No'],
@@ -495,6 +503,11 @@ class EsphomeConnection {
495
503
  /** Dialog mode: when something was last recognised (or the mode was switched on). */
496
504
  dialogHeardAt = 0;
497
505
  dialogTimer = null;
506
+ /** Dialog mode: when the last reply went out (0 = none pending) and how long it is. */
507
+ dialogReplyAt = 0;
508
+ dialogReplyMs = 0;
509
+ /** Dialog mode: waits for the device to listen again after its reply, see {@link onReplyPlayed}. */
510
+ dialogReopenTimer = null;
498
511
  constructor(device, opts) {
499
512
  this.opts = opts;
500
513
  this.host = device.ip.trim();
@@ -598,6 +611,7 @@ class EsphomeConnection {
598
611
  clearInterval(this.dialogTimer);
599
612
  this.dialogTimer = null;
600
613
  }
614
+ this.cancelDialogReopen();
601
615
  }
602
616
  setOffline() {
603
617
  if (this.online) {
@@ -743,6 +757,7 @@ class EsphomeConnection {
743
757
  }
744
758
  this.opts.log.debug(`ESPHome ${this.deviceName}: playback finished (success=${message.getSuccess()})`);
745
759
  this.status('idle');
760
+ this.onReplyPlayed();
746
761
  return;
747
762
  case 'PingRequest':
748
763
  this.send(new esphomeProto_1.pb.PingResponse());
@@ -930,6 +945,7 @@ class EsphomeConnection {
930
945
  this.opts.log.debug(`ESPHome ${this.deviceName}: pipeline already running — ignoring wake`);
931
946
  return;
932
947
  }
948
+ this.cancelDialogReopen();
933
949
  const phrase = request.getWakeWordPhrase();
934
950
  if (Date.now() < this.ignoreFollowUpUntil) {
935
951
  // The microphone for the question a button already answered: close it at once. In this state the device
@@ -1031,6 +1047,8 @@ class EsphomeConnection {
1031
1047
  }
1032
1048
  this.dialogOn = on;
1033
1049
  this.dialogHeardAt = Date.now();
1050
+ this.dialogReplyAt = 0;
1051
+ this.cancelDialogReopen();
1034
1052
  if (this.dialogTimer) {
1035
1053
  clearInterval(this.dialogTimer);
1036
1054
  this.dialogTimer = null;
@@ -1039,17 +1057,20 @@ class EsphomeConnection {
1039
1057
  ? ` (nothing said for ${exports.DIALOG_IDLE_MS / 60_000} min)`
1040
1058
  : reason === 'stop'
1041
1059
  ? ' (the device was stopped)'
1042
- : reason === 'offline'
1043
- ? ' (offline)'
1044
- : reason === 'error'
1045
- ? ' (the voice pipeline failed)'
1046
- : '';
1060
+ : reason === 'no-listen'
1061
+ ? ' (the device did not listen again after the reply)'
1062
+ : reason === 'offline'
1063
+ ? ' (offline)'
1064
+ : reason === 'error'
1065
+ ? ' (the voice pipeline failed)'
1066
+ : '';
1047
1067
  this.opts.log.info(`ESPHome ${this.deviceName}: dialog mode ${on ? 'on' : 'off'}${why}`);
1048
1068
  this.opts.onDialog?.(this.deviceName, this.room, on, reason);
1049
1069
  if (on) {
1050
1070
  this.dialogTimer = setInterval(() => this.checkDialogIdle(), DIALOG_CHECK_MS);
1051
1071
  this.dialogTimer.unref();
1052
1072
  if (open && this.online && !this.capture && !this.runOpen) {
1073
+ this.noteDialogReply((open.pcm.length / 2 / open.sampleRate) * 1000);
1053
1074
  void this.announce(open.pcm, open.sampleRate, true, '', false).catch(e => this.opts.log.warn(`ESPHome ${this.deviceName}: opening the microphone failed — ${e.message}`));
1054
1075
  }
1055
1076
  return;
@@ -1073,6 +1094,46 @@ class EsphomeConnection {
1073
1094
  }
1074
1095
  this.setDialog(false, 'idle');
1075
1096
  }
1097
+ /** Dialog mode: a reply went out after which the device should listen again. */
1098
+ noteDialogReply(ms) {
1099
+ if (this.dialogOn) {
1100
+ this.dialogReplyAt = Date.now();
1101
+ this.dialogReplyMs = ms;
1102
+ }
1103
+ }
1104
+ /**
1105
+ * Dialog mode: the device reports that its reply has played (or was stopped). It should open the microphone again
1106
+ * now; one that does not — its stop word or a tap ended the reply, or it dropped the conversation flag — would
1107
+ * leave the mode on while nobody listens. A wake word during the reply starts a new run in time and keeps it.
1108
+ */
1109
+ onReplyPlayed() {
1110
+ if (!this.dialogOn || !this.dialogReplyAt || this.capture) {
1111
+ return;
1112
+ }
1113
+ const playedMs = Date.now() - this.dialogReplyAt;
1114
+ const replyMs = this.dialogReplyMs;
1115
+ this.dialogReplyAt = 0;
1116
+ this.cancelDialogReopen();
1117
+ this.dialogReopenTimer = setTimeout(() => {
1118
+ this.dialogReopenTimer = null;
1119
+ if (!this.dialogOn || this.capture || this.runOpen) {
1120
+ return;
1121
+ }
1122
+ const s = (ms) => (ms / 1000).toFixed(1);
1123
+ this.opts.log.info(playedMs + REPLY_CUT_MS < replyMs
1124
+ ? `ESPHome ${this.deviceName}: the device stopped the reply after ${s(playedMs)} of ${s(replyMs)} s ` +
1125
+ `(its stop word, a tap or its wake word) and does not listen again`
1126
+ : `ESPHome ${this.deviceName}: the device played the reply but did not open its microphone again`);
1127
+ this.setDialog(false, 'no-listen');
1128
+ }, DIALOG_REOPEN_MS);
1129
+ this.dialogReopenTimer.unref();
1130
+ }
1131
+ cancelDialogReopen() {
1132
+ if (this.dialogReopenTimer) {
1133
+ clearTimeout(this.dialogReopenTimer);
1134
+ this.dialogReopenTimer = null;
1135
+ }
1136
+ }
1076
1137
  /**
1077
1138
  * The device asks to end the conversation (`VoiceAssistantRequest{start:false}`): a button, or the wake word
1078
1139
  * said again while a request is running — that is how ESPHome's voice_assistant stops. While it waits for an
@@ -1337,6 +1398,7 @@ class EsphomeConnection {
1337
1398
  this.event(EVENT.TTS_END, { url });
1338
1399
  // linux-voice-assistant reads the flag here (ignoring "0"), ESPHome at INTENT_END
1339
1400
  this.event(EVENT.RUN_END, conversation);
1401
+ this.noteDialogReply((ttsPcm.length / 2 / sampleRate) * 1000);
1340
1402
  this.questionUntil = followUp ? Date.now() + (ttsPcm.length / 2 / sampleRate) * 1000 + QUESTION_OPEN_MS : 0;
1341
1403
  this.armPlaybackTimeout();
1342
1404
  }
@@ -1369,6 +1431,7 @@ class EsphomeConnection {
1369
1431
  this.event(EVENT.TTS_START, { text: '' });
1370
1432
  this.event(EVENT.TTS_END, { url });
1371
1433
  this.event(EVENT.RUN_END, { continue_conversation: '1' });
1434
+ this.noteDialogReply((clip.length / 2 / sampleRate) * 1000);
1372
1435
  this.armPlaybackTimeout();
1373
1436
  }
1374
1437
  catch (e) {
@@ -1 +1 @@
1
- {"version":3,"file":"esphome.js","sourceRoot":"","sources":["../../../src/lib/voice/esphome.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwNA,8BAGC;AAGD,0CASC;AAwBD,sDA0BC;AAGD,sCAGC;AAGD,wCAI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AAC;QACxB,CAAC,EAAE,mBAAmB,CAAC,CAAC;QACxB,IAAI,CAAC,aAAa,CAAC,KAAK,EAAE,CAAC;IAC/B,CAAC;IAEO,KAAK,CAAC,IAAY,EAAE,IAA6B;QACrD,IAAI,IAAI,KAAK,KAAK,CAAC,SAAS,EAAE,CAAC;YAC3B,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;QACxB,CAAC;aAAM,IAAI,IAAI,KAAK,KAAK,CAAC,OAAO,EAAE,CAAC;YAChC,IAAI,CAAC,OAAO,GAAG,KAAK,CAAC;QACzB,CAAC;aAAM,IAAI,IAAI,KAAK,KAAK,CAAC,KAAK,EAAE,CAAC;YAC9B,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QAClC,CAAC;QACD,MAAM,OAAO,GAAG,IAAI,iBAAE,CAAC,2BAA2B,EAAE,CAAC;QACrD,OAAO,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;QAC3B,MAAM,KAAK,GAA8B,EAAE,CAAC;QAC5C,KAAK,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,IAAI,IAAI,EAAE,CAAC,EAAE,CAAC;YACrD,MAAM,IAAI,GAAG,IAAI,iBAAE,CAAC,uBAAuB,EAAE,CAAC;YAC9C,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;YACnB,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;YACrB,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACrB,CAAC;QACD,OAAO,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;QAC3B,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACvB,CAAC;CACJ","sourcesContent":["/**\n * ESPHome voice satellites — the fourth transport, next to the UDP server (`voiceServer.ts`) and the\n * Wyoming endpoint (`wyoming.ts`).\n *\n * Unlike those two, this one is a **client**: an ESPHome voice satellite is a *server* that waits on\n * TCP 6053 for the home-automation controller to connect and drive it. We therefore dial out to each\n * configured device and play the role Home Assistant normally plays. That covers the ThirdReality\n * Voice & Music Assistant (Dev Edition), the Home Assistant Voice PE and any box running\n * OHF-Voice/linux-voice-assistant.\n *\n * Flow for one utterance (verified against the firmware's `src/satellite/Satellite.cpp`):\n *\n * device → VoiceAssistantRequest{start, wake_word_phrase} wake word fired on the device\n * we → VoiceAssistantResponse{port:0} 0 = audio over the API, no UDP\n * we → RUN_START, WAKE_WORD_END, STT_START, STT_VAD_START\n * device → VoiceAssistantAudio … 16 kHz mono s16le, *until told to stop*\n * we → STT_VAD_END ← the device has no VAD of its own\n * we → STT_END{text}, INTENT_START, INTENT_END, TTS_START{text}, TTS_END{url}, RUN_END\n * device → fetches the URL over HTTP, plays it, VoiceAssistantAnnounceFinished\n *\n * Two consequences shape this file: end-of-speech detection is ours (`vad.ts`), and the spoken reply\n * has to be reachable over HTTP (`mediaServer.ts`) rather than streamed down the socket.\n *\n * The first one also makes the **dialog mode** possible ({@link EsphomeConnection.setDialog}): the device streams as\n * long as we do not end the utterance, so while nobody speaks the detector just starts over, and every reply asks the\n * device to open its microphone again (`continue_conversation`). Talking goes on without a wake word until the mode\n * is switched off, the device is stopped, or nobody said anything for {@link DIALOG_IDLE_MS}.\n */\nimport * as net from 'node:net';\nimport {\n pb,\n encode,\n decode,\n type PbMessage,\n type AuthenticationResponse,\n type DeviceInfoResponse,\n type HelloResponse,\n type VoiceAssistantAnnounceFinished,\n type VoiceAssistantAudio,\n type VoiceAssistantConfigurationResponse,\n type VoiceAssistantEventData,\n type VoiceAssistantRequestMsg,\n} from './esphomeProto';\nimport { EntityRegistry, isEntityStateMessage, isListEntityMessage, type EsphomeEntity } from './esphomeEntities';\nimport { SpeechDetector, type CaptureEnd, type Bytes, type VadReport } from './vad';\nimport { prepareForStt } from './speechAudio';\nimport { chooseReplyFormat, encodeReply, type ExternalEncoder, type ReplyFormat } from './replyFormat';\nimport { levelProfile, type DiscardedCapture, type DiscardReason } from './captures';\nimport type { SttEngine } from './stt';\nimport type { TtsEngine } from './tts';\nimport type { SatelliteState } from './protocol';\nimport { confirmationTone } from './tone';\n\n/** `VoiceAssistantEvent` (api.proto) — the subset we emit. */\nconst EVENT = {\n ERROR: 0,\n RUN_START: 1,\n RUN_END: 2,\n STT_START: 3,\n STT_END: 4,\n INTENT_START: 5,\n INTENT_END: 6,\n TTS_START: 7,\n TTS_END: 8,\n WAKE_WORD_END: 10,\n STT_VAD_START: 11,\n STT_VAD_END: 12,\n} as const;\n\n/** `SubscribeVoiceAssistantRequest.flags`: audio over the API socket instead of a UDP side channel. */\nconst SUBSCRIBE_API_AUDIO = 1;\n/** ESPHome voice satellites always capture at 16 kHz mono 16-bit. */\nconst MIC_SAMPLE_RATE = 16000;\n/**\n * Leading audio to keep out of the end-of-speech analysis. These devices acknowledge the wake word\n * with a chirp through their own speaker and hear it back on their own microphone, far louder than\n * the speech that follows. Without this the chirp alone satisfies the detector's speech test — so\n * `sawSpeech` stops meaning \"somebody said something\" and a false wake is billed to STT — and it\n * drags the noise floor up with it.\n *\n * Measured over four captures from a ThirdReality Voice & Music Assistant (RMS per 50 ms, remarkably\n * repeatable across all four):\n *\n * ms 0 50 100 150 200 250 300 350 400 450 500 550 600\n * rms ~20 ~900 ~11k ~19k ~14k ~1.3k ~990 ~780 ~610 ~370 ~330 ~165 ~180\n *\n * so the chirp is still above the gate at 500 ms and only clears it around 550–600. 600 ms is the\n * smallest value that rejects a chirp-only wake while still detecting the speech in every one of the\n * four captures, with no change to when the utterance closes. Only the analysis skips it: STT gets the audio\n * from 400 ms before the detected speech (`speechAudio.ts`), so a speaker who starts inside this window loses\n * nothing but a late gate open.\n */\nconst WAKE_CHIRP_MS = 600;\n/** Default API port of an ESPHome device. */\nconst DEFAULT_PORT = 6053;\n/** Keepalive interval; two missed replies count as a dead link. */\nconst PING_INTERVAL_MS = 20_000;\n/** Wait between reconnect attempts. Devices reboot, and a Wi-Fi speaker drops off now and then. */\nconst RECONNECT_MS = 10_000;\n/** Give up on a pipeline that produced no audio at all (device wedged mid-stream). */\nconst PIPELINE_TIMEOUT_MS = 30_000;\n/** How long we wait for the device to report that it finished playing before forcing it back to idle. */\nconst PLAYBACK_TIMEOUT_MS = 60_000;\n/**\n * Default lowest RMS that counts as speech (the noise floor can only raise the gate above it). Fits the\n * ThirdReality speaker; quieter microphones get their own value per device ({@link EsphomeDevice.speechLevel}).\n */\nexport const DEFAULT_SPEECH_LEVEL = 250;\n/**\n * Close the microphone when nobody has started speaking this long after the wake word. Without it a false wake\n * kept the stream open for the full 12 s cap: on a ThirdReality speaker with a custom wake word that was ten\n * times in one night, each 12.6 s of an open mic (and of music ducked, if any played).\n */\nconst NO_SPEECH_MS = 5000;\n/** The same after a follow-up question re-opened the mic: the user may need a moment to think. */\nconst NO_SPEECH_FOLLOW_UP_MS = 8000;\n/** Silence that ends an utterance when the configuration leaves it empty. */\nconst DEFAULT_SILENCE_MS = 900;\n/**\n * After this much speech a pause may be {@link LONG_PAUSE_FACTOR} times as long before the utterance ends: whoever\n * talks that long is dictating a request and pauses to think, while \"Licht an\" should still close quickly. Field\n * report 2026-11-03: \"Я хочу, чтоб ты создал задачу, чтобы утром говорить мне…\" was cut off right there.\n */\nconst LONG_REQUEST_MS = 2500;\nconst LONG_PAUSE_FACTOR = 1.5;\n/**\n * Sound needed before a loud moment counts as speech. On vitanova (2026-11-03) a single 100 ms sound at RMS 197\n * after a false wake opened the gate (threshold 150), and Whisper made \"и все просят.\" of the amplified silence\n * around it. The shortest real answer, \"да\", lasts about 250 ms.\n */\nconst MIN_SPEECH_MS = 200;\n/**\n * Close the utterance when the device stops sending audio without ending the stream. Seen on a ThirdReality\n * speaker: the audio stopped after 2.7 s, and the satellite showed \"listening\" for the 30 s of\n * {@link PIPELINE_TIMEOUT_MS}. A device streams every few tens of ms while the mic is open.\n */\nconst STREAM_STALL_MS = 2000;\n/** The same before the first audio arrives: a device needs a moment to open the microphone. */\nconst STREAM_START_MS = 5000;\n/** How often a running capture checks for a stalled stream. */\nconst STALL_CHECK_MS = 250;\n/** Silence threshold as a share of the speech threshold — keeps the default pair 250/150. */\nconst SILENCE_SHARE = 0.6;\n/**\n * The firmware answers an ERROR event with a stop request of its own (`signal_stop_`). One arriving this soon after\n * our error belongs to it and needs no reply — the run is already over.\n */\nconst ERROR_ECHO_MS = 2000;\n/**\n * What ends a run that produced no request. Home Assistant sends the same code when the speech recognition finds no\n * text, and the Voice PE firmware deliberately plays no error sound for it.\n */\nconst NO_TEXT_ERROR = { code: 'stt-no-text-recognized', message: 'No text recognized' };\n/**\n * A dropped utterance whose loudest frame reached this share of the speech threshold was probably a voice\n * that was too quiet, not an empty room — worth telling the user where to lower the threshold.\n */\nconst QUIET_VOICE_SHARE = 0.4;\n/**\n * Event entity of a satellite with a screen: the user answered the open question by touch, event type `yes` or `no`.\n * Pressing it is the same as saying \"yes\"/\"no\" into the open microphone — no speech recognition to get it wrong\n * (a German \"Ja\" came back as \"Я\" once).\n */\nconst CONFIRM_ENTITY = 'confirm_answer';\n/** Select entity of a satellite with a screen: the language of the date and the hints it shows. */\nconst DISPLAY_LANGUAGE_ENTITY = 'display_language';\n/**\n * After a reply that asks something: how long, beyond the reply's own length, the question stays open — the next\n * pipeline the device starts answers it, and so does a yes/no button press. Answering it (by voice or button) closes\n * it earlier. The wake word phrase cannot tell a follow-up from a new request: ESPHome sends the phrase of the last\n * wake word with every request, the follow-up microphone included (field report 2026-11-05).\n */\nconst QUESTION_OPEN_MS = 30_000;\n/**\n * A button press still answers the question this long after the follow-up microphone closed: the firmware may stop\n * the microphone on the press before it reports which button it was.\n */\nconst CONFIRM_GRACE_MS = 3000;\n/**\n * After a button answer: a follow-up microphone the device opens this soon was asked for by the question the button\n * already answered, and is closed at once (unless our reply asked something again).\n */\nconst IGNORE_FOLLOW_UP_MS = 15_000;\n/**\n * Dialog mode: nobody spoke for this much audio — the detector starts over on the audio that keeps coming (no new pipeline,\n * the device does not notice), so its noise floor, its limits and the memory of the recording stay those of a request.\n */\nconst DIALOG_WINDOW_MS = 10_000;\n/** Dialog mode: the longest request. */\nconst DIALOG_MAX_SPEECH_MS = 20_000;\n/** Dialog mode ends by itself when nothing was said for this long. */\nexport const DIALOG_IDLE_MS = 5 * 60_000;\n/** How often the dialog mode checks whether it ran idle. */\nconst DIALOG_CHECK_MS = 5000;\n/**\n * Dialog mode, nothing recognised (a cough, the TV): a reply of this much silence ends the run and makes the device\n * open its microphone again — an ESPHome device does that only after a reply has played.\n */\nconst DIALOG_PAUSE_MS = 250;\n\n/** \"Yes\" and \"no\" as a button answer is passed on: the words of the satellite's language, which pi-agent also takes. */\nconst YES_NO: Record<string, [yes: string, no: string]> = {\n en: ['Yes', 'No'],\n de: ['Ja', 'Nein'],\n ru: ['Да', 'Нет'],\n pt: ['Sim', 'Não'],\n nl: ['Ja', 'Nee'],\n fr: ['Oui', 'Non'],\n it: ['Sì', 'No'],\n es: ['Sí', 'No'],\n pl: ['Tak', 'Nie'],\n uk: ['Так', 'Ні'],\n zh: ['是', '不'],\n};\n\n/** The word a yes/no button stands for in `language` (ISO 639-1, `zh-cn` too); English for an unknown one. */\nexport function yesNoWord(language: string, yes: boolean): string {\n const base = (language || 'en').trim().toLowerCase().split(/[-_]/)[0];\n return (YES_NO[base] ?? YES_NO.en)[yes ? 0 : 1];\n}\n\n/** The event type of a {@link CONFIRM_ENTITY} as yes (true) or no (false); null for anything else. */\nexport function confirmAnswerOf(eventType: unknown): boolean | null {\n const type = typeof eventType === 'string' ? eventType.trim().toLowerCase() : '';\n if (type === 'yes' || type === 'confirm') {\n return true;\n }\n if (type === 'no' || type === 'cancel') {\n return false;\n }\n return null;\n}\n\n/**\n * Names of the adapter's languages in that language, for a display-language select. `Intl.DisplayNames` covers the\n * rest, but a Node.js built with only English ICU data knows no \"Deutsch\" or \"Русский\".\n */\nconst NATIVE_LANGUAGE_NAMES: Record<string, string> = {\n en: 'english',\n de: 'deutsch',\n ru: 'русский',\n pt: 'português',\n nl: 'nederlands',\n fr: 'français',\n it: 'italiano',\n es: 'español',\n pl: 'polski',\n uk: 'українська',\n zh: '中文',\n};\n\n/**\n * The option of a display-language select that means `language`: its name in that language (\"Deutsch\"), in English\n * (\"German\") or its code (\"de\", \"de-DE\"), case ignored. Null when the device offers none of them.\n */\nexport function displayLanguageOption(options: string[], language: string): string | null {\n const code = (language || '').trim().toLowerCase();\n const base = code.split(/[-_]/)[0];\n if (!base) {\n return null;\n }\n const names = new Set<string>([code, base]);\n if (NATIVE_LANGUAGE_NAMES[base]) {\n names.add(NATIVE_LANGUAGE_NAMES[base]);\n }\n for (const locale of [base, 'en']) {\n try {\n const name = new Intl.DisplayNames([locale], { type: 'language' }).of(base);\n if (name) {\n names.add(name.toLocaleLowerCase(locale));\n }\n } catch {\n /* not a language code Intl knows */\n }\n }\n const norm = (option: string): string => option.trim().toLocaleLowerCase();\n return (\n options.find(o => names.has(norm(o))) ??\n options.find(o => norm(o).split(/[-_]/)[0] === base && /^[a-z]{2,3}([-_][a-z0-9]+)?$/.test(norm(o))) ??\n null\n );\n}\n\n/** The configured speech threshold of a device, or 0 for the default. Table cells may arrive as strings. */\nexport function speechLevelOf(device: EsphomeDevice): number {\n const level = Math.round(Number(device.speechLevel));\n return Number.isFinite(level) && level > 0 ? level : 0;\n}\n\n/** How a configured device is identified: `ip`, or `ip:port` when it does not use the default port. */\nexport function esphomeAddress(device: Pick<EsphomeDevice, 'ip' | 'port'>): string {\n const ip = (device.ip || '').trim().toLowerCase();\n const port = Number(device.port) || DEFAULT_PORT;\n return port === DEFAULT_PORT ? ip : `${ip}:${port}`;\n}\n\nexport interface EsphomeDevice {\n /** Host name or IP of the satellite. */\n ip: string;\n /** API port; empty/0 → 6053. */\n port?: number | string;\n /** API password, if one is configured on the device. */\n password?: string;\n /** Room this satellite belongs to (drives `satellites.<room>.*` and the answer context). */\n room?: string;\n /**\n * Lowest RMS that counts as speech on this device (empty/0 → {@link DEFAULT_SPEECH_LEVEL}). Microphone\n * levels differ a lot: a ThirdReality speaker hears normal speech at RMS 350–470, a phone running a\n * satellite app at under 200, so one fixed floor cannot fit both.\n */\n speechLevel?: number | string | null;\n}\n\nexport interface EsphomeSatellitesOptions {\n devices: EsphomeDevice[];\n /** ISO-639-1 language hint for STT/TTS ('' = auto/provider default). */\n language: string;\n stt: SttEngine;\n tts: TtsEngine;\n /**\n * Produce the assistant reply for a transcribed utterance. `audioMs` is the length of the recording,\n * `vad` what the voice activity detection made of it (both for the request journal). An answer given with the\n * device's yes/no button ({@link CONFIRM_ENTITY}) comes as the yes or no word, with `button` and no recording.\n */\n answer: (\n question: string,\n ctx: {\n device: string;\n room: string;\n /** Wake word of the recording; '' = the mic was re-opened for a follow-up; absent for a button. */\n wakeWord?: string;\n sttMs?: number;\n audioMs?: number;\n vad?: VadReport;\n button?: 'yes' | 'no';\n },\n ) => Promise<string>;\n /** The reply was synthesised: how long that took and how long it plays (for the request journal). */\n onSpoken?: (device: string, info: { ms: number; audioMs: number }) => void;\n /** Optional STT vocabulary hints (device/room names) to bias recognition; re-read per utterance. */\n getHints?: () => string[] | Promise<string[]>;\n /** Where spoken replies are published for the device to fetch. */\n media: MediaHost;\n /**\n * Host the device should call back on. Empty → the local address of our socket to that device,\n * which is automatically the right interface on a multi-homed host.\n */\n mediaHost?: string;\n /** Silence that ends an utterance, in ms ('' / 0 → the detector default). */\n silenceMs?: number;\n log: ioBroker.Logger;\n /**\n * Notified on every satellite state transition (idle/listening/processing/speaking/offline). `host` is the\n * configured address (`ip`, or `ip:port` for another port than 6053), so the adapter can tell which table row\n * a satellite belongs to.\n */\n onStatus?: (device: string, room: string, state: SatelliteState | 'offline', host: string) => void;\n /**\n * Writes replies as MP3 or Opus, for a media player that takes nothing else (ffmpeg in the adapter). Without it\n * such a device gets FLAC or WAV if it lists one of them, and a warning otherwise.\n */\n encodeAudio?: ExternalEncoder;\n /** Notified with the device's wake-word configuration, on connect and after every change. */\n onWakeWords?: (device: string, room: string, config: WakeWordConfig) => void;\n /** Notified once per connect with everything the device exposes besides the voice pipeline. */\n onEntities?: (device: string, room: string, entities: EsphomeEntity[]) => void;\n /** Notified whenever one of those entities changes (and once per entity right after connecting). */\n onEntityState?: (device: string, room: string, entity: EsphomeEntity) => void;\n /** True when the reply asks something back, so the device should re-open its mic without a wake word. */\n expectsFollowUp?: (answer: string, device: string) => boolean;\n /**\n * A recording that never became a request: dropped as silence, or returned empty by the speech recognition.\n * For diagnosis (the adapter stores it when asked to); absent → nothing is kept.\n */\n onDiscarded?: (capture: DiscardedCapture) => void;\n /**\n * The dialog mode of a satellite changed — also by itself: the device was stopped, went offline, nothing was said\n * for {@link DIALOG_IDLE_MS}, or its pipeline failed.\n */\n onDialog?: (device: string, room: string, on: boolean, reason: DialogChange) => void;\n /**\n * Custom wake words to offer the devices, re-read for every configuration request. The device lists\n * them next to its own and downloads one (from the media server) only when it is selected.\n */\n externalWakeWords?: () => ExternalWakeWordOffer[];\n}\n\n/** Why the dialog mode of a satellite changed. */\nexport type DialogChange = 'command' | 'idle' | 'stop' | 'offline' | 'error';\n\n/** A custom wake word as offered to the devices; the files are on the media server under `path`. */\nexport interface ExternalWakeWordOffer {\n id: string;\n phrase: string;\n languages: string[];\n /** Size of the `.tflite` in bytes. */\n size: number;\n /** SHA-256 of the `.tflite`, lower-case hex. */\n sha256: string;\n /** URL path of the JSON config, e.g. `/wakeword/hey_hannah_1a2b3c4d.json`; the model sits next to it. */\n path: string;\n}\n\n/** What a device reports about its wake words: what the firmware ships plus the custom ones we offered. */\nexport interface WakeWordConfig {\n /** Ids currently listening, e.g. `['okay_nabu']`. */\n active: string[];\n /** Every wake word the device can use, with the spoken phrase and the languages it was trained on. */\n available: { id: string; phrase: string; languages: string[] }[];\n /** How many may listen at once — 2 on the ThirdReality speaker, which has a sensitivity per slot. */\n max: number;\n}\n\n/** `VoiceAssistantTimerEvent` in api.proto. */\nexport const TIMER_EVENT = { started: 0, updated: 1, cancelled: 2, finished: 3 } as const;\n\n/** One assistant timer, as the device wants to hear about it. */\nexport interface TimerEvent {\n type: keyof typeof TIMER_EVENT;\n id: string;\n name: string;\n totalSeconds: number;\n secondsLeft: number;\n /** False once it has finished or been cancelled — the device clears its ring on that. */\n active: boolean;\n}\n\n/** The slice of `MediaServer` this module needs (kept narrow so tests can pass a stub). */\nexport interface MediaHost {\n port: number;\n publish(body: Buffer, contentType?: string, ttlMs?: number): string;\n}\n\n/**\n * All configured ESPHome satellites. Owns one connection per device and offers the same surface the\n * adapter already uses for the UDP server: `devices()` and `announce()`.\n */\nexport class EsphomeSatellites {\n private readonly connections: EsphomeConnection[] = [];\n\n constructor(private readonly opts: EsphomeSatellitesOptions) {}\n\n async start(): Promise<void> {\n for (const device of this.opts.devices) {\n if (!device.ip?.trim()) {\n continue;\n }\n const connection = new EsphomeConnection(device, this.opts);\n this.connections.push(connection);\n connection.start();\n }\n if (!this.connections.length) {\n this.opts.log.warn('ESPHome satellites enabled, but no device addresses are configured.');\n }\n return Promise.resolve();\n }\n\n async stop(): Promise<void> {\n await Promise.all(this.connections.map(c => c.stop()));\n this.connections.length = 0;\n }\n\n /** Device names of the satellites currently connected. */\n devices(): string[] {\n return this.connections.filter(c => c.online).map(c => c.deviceName);\n }\n\n /** Wake-word configuration of one connected satellite, or null if it is unknown/offline. */\n wakeWords(device: string): WakeWordConfig | null {\n return this.connections.find(c => c.online && c.deviceName === device)?.wakeWordConfig ?? null;\n }\n\n /**\n * Choose which wake words listen on one satellite. Ids come from {@link WakeWordConfig.available};\n * the device stores the selection itself, so it survives a restart of the adapter.\n */\n setWakeWords(device: string, ids: string[]): boolean {\n const target = this.connections.find(c => c.online && c.deviceName === device);\n if (!target) {\n return false;\n }\n target.setWakeWords(ids);\n return true;\n }\n\n /**\n * Offer the current custom wake words to every connected satellite again — after one was uploaded\n * or deleted. Each device answers with its new configuration (→ `onWakeWords`).\n */\n refreshWakeWords(): number {\n const online = this.connections.filter(c => c.online);\n online.forEach(c => c.requestWakeWordConfig());\n return online.length;\n }\n\n /** Everything one satellite exposes besides the voice pipeline (gain, noise suppression, …). */\n entities(device: string): EsphomeEntity[] {\n return this.connections.find(c => c.online && c.deviceName === device)?.entities.list() ?? [];\n }\n\n /**\n * Write one of those entities. Returns false when the satellite is offline, the entity is unknown\n * or read-only, or the value is not one the device accepts.\n */\n setEntity(device: string, objectId: string, value: unknown): boolean {\n const target = this.connections.find(c => c.online && c.deviceName === device);\n return target ? target.setEntity(objectId, value) : false;\n }\n\n /**\n * Absolute URL of a path on our media server (a live stream) with a host `device` can reach — the local end of\n * its connection unless a media host is configured. null when it is offline.\n */\n mediaUrl(device: string, path: string): string | null {\n const target = this.connections.find(c => c.online && c.deviceName === device);\n return target ? target.mediaUrl(path) : null;\n }\n\n /**\n * Switch the dialog mode of one satellite: after every reply it listens again without a wake word. Switched on\n * while the satellite is idle, `open` is played and the microphone opens after it (a request in progress re-opens\n * it with its reply). False when the satellite is not connected.\n */\n setDialog(device: string, on: boolean, open?: { pcm: Buffer; sampleRate: number }): boolean {\n const target = this.connections.find(c => c.online && c.deviceName === device);\n if (!target) {\n return false;\n }\n target.setDialog(on, 'command', open);\n return true;\n }\n\n /** Whether a satellite is in dialog mode. */\n dialog(device: string): boolean {\n return !!this.connections.find(c => c.online && c.deviceName === device)?.dialog;\n }\n\n /**\n * Mirror an assistant timer onto the satellites so they can show it on their own LED ring and ring\n * it themselves. `device` null broadcasts. Returns how many devices were told.\n */\n timerEvent(device: string | null, event: TimerEvent): number {\n const targets = this.connections.filter(c => c.online && (!device || c.deviceName === device));\n targets.forEach(c => c.sendTimerEvent(event));\n return targets.length;\n }\n\n /**\n * Play a ready PCM buffer on one satellite (by device name) or all of them. Returns how many\n * devices it was handed to.\n *\n * With `startConversation` the device opens its microphone as soon as the clip has played, without\n * a wake word — that is how a question gets its answer (see `PendingQuestions`).\n */\n async announce(device: string | null, pcm: Buffer, sampleRate: number, startConversation = false): Promise<number> {\n const targets = this.connections.filter(c => c.online && (!device || c.deviceName === device));\n if (!targets.length) {\n return 0;\n }\n await Promise.all(\n targets.map(c =>\n c\n .announce(pcm, sampleRate, startConversation)\n .catch(e => this.opts.log.warn(`announce to ${c.deviceName} failed: ${(e as Error).message}`)),\n ),\n );\n return targets.length;\n }\n}\n\n/** State of the utterance currently being captured. */\ninterface Capture {\n chunks: Buffer[];\n detector: SpeechDetector;\n conversationId: string;\n /** Wake word that opened this capture; '' when the mic was re-opened for a follow-up/question. */\n wakeWord: string;\n /** The mic was re-opened for a reply that asked something: a yes/no button press answers it too. */\n answersQuestion: boolean;\n timer: NodeJS.Timeout;\n /** Watches for a device that stops sending audio without ending the stream. */\n stallCheck: NodeJS.Timeout;\n startedAt: number;\n /** When the last audio arrived; 0 = none yet. */\n lastAudioAt: number;\n closed: boolean;\n /** Opened in dialog mode: while nobody speaks, the detector starts over instead of ending the run. */\n dialog: boolean;\n}\n\n/** One satellite: socket lifecycle, handshake, and the voice pipeline. */\nclass EsphomeConnection {\n /** Device name as reported by the device; falls back to its address until the handshake answers. */\n deviceName: string;\n online = false;\n /** Last wake-word configuration the device reported; null until the handshake answers. */\n wakeWordConfig: WakeWordConfig | null = null;\n /**\n * One entry per configuration request in flight, in send order (the device answers each one, in\n * order): the ids a preceding `SetConfiguration` asked for, or null. The read-back is the only\n * failure signal the device gives.\n */\n private configChecks: (string[] | null)[] = [];\n /** Everything else the device exposes — rebuilt from scratch on every reconnect. */\n readonly entities = new EntityRegistry();\n\n private readonly host: string;\n private readonly port: number;\n private readonly room: string;\n\n private socket: net.Socket | null = null;\n private rx: Bytes = Buffer.alloc(0);\n private pingTimer: NodeJS.Timeout | null = null;\n private reconnectTimer: NodeJS.Timeout | null = null;\n private missedPings = 0;\n private stopping = false;\n private capture: Capture | null = null;\n private playbackTimer: NodeJS.Timeout | null = null;\n private readonly password: string;\n /** Configured speech threshold, 0 = {@link DEFAULT_SPEECH_LEVEL}. */\n private readonly speechLevel: number;\n /** `ip`, or `ip:port` for another port than the default — how the adapter recognises the table row. */\n private readonly address: string;\n /** The device's friendly name, for entities without a name of their own. */\n private friendlyName = '';\n /**\n * Number of the current pipeline run. A run whose number is no longer current was ended — the device asked to\n * stop, started over, or went away — and whatever STT, answer or TTS is still in flight for it stays silent.\n */\n private run = 0;\n /** From RUN_START until we sent RUN_END: the device waits for that RUN_END. */\n private runOpen = false;\n /** When we last sent an ERROR event (see {@link ERROR_ECHO_MS}). */\n private errorSentAt = 0;\n /** The reply format last reported in the log, to log it again only when it changes. */\n private loggedFormat = '';\n /**\n * The last reply asked something (`continue_conversation`, or an announcement with `start_conversation`): until\n * when the next request of the device, or a yes/no button press, answers it. 0 = no open question.\n */\n private questionUntil = 0;\n /** After a button answer: until when a follow-up microphone is the stale one of the answered question. */\n private ignoreFollowUpUntil = 0;\n /** When a yes/no button press last answered a question. */\n private buttonAt = 0;\n /** When the device last asked to stop (`VoiceAssistantRequest{start:false}`). */\n private stoppedAt = 0;\n /** The display language was compared with ours since the last connect. */\n private displayLanguageChecked = false;\n /** Dialog mode: every reply opens the microphone again, see {@link setDialog}. */\n private dialogOn = false;\n /** Dialog mode: when something was last recognised (or the mode was switched on). */\n private dialogHeardAt = 0;\n private dialogTimer: NodeJS.Timeout | null = null;\n\n constructor(\n device: EsphomeDevice,\n private readonly opts: EsphomeSatellitesOptions,\n ) {\n this.host = device.ip.trim();\n this.port = Number(device.port) || DEFAULT_PORT;\n this.room = (device.room || '').trim();\n this.password = device.password || '';\n this.speechLevel = speechLevelOf(device);\n this.address = esphomeAddress(device);\n this.deviceName = this.host;\n }\n\n // ── lifecycle ───────────────────────────────────────────────────────────────────────────────────\n\n start(): void {\n this.connect();\n }\n\n async stop(): Promise<void> {\n this.stopping = true;\n this.clearTimers();\n this.abortCapture();\n const socket = this.socket;\n this.socket = null;\n if (socket) {\n try {\n socket.write(encode(new pb.DisconnectRequest()));\n } catch {\n /* socket already gone — nothing to say goodbye on */\n }\n socket.destroy();\n }\n this.setOffline();\n return Promise.resolve();\n }\n\n private connect(): void {\n if (this.stopping) {\n return;\n }\n this.rx = Buffer.alloc(0);\n this.missedPings = 0;\n // The device re-announces everything after a reconnect, and the keys are not stable across\n // reboots, so starting from a clean slate is the only safe option.\n this.entities.clear();\n this.configChecks = [];\n this.displayLanguageChecked = false;\n\n const socket = net.createConnection({ host: this.host, port: this.port }, () => {\n this.opts.log.debug(`ESPHome ${this.host}:${this.port} connected`);\n this.handshake();\n });\n this.socket = socket;\n socket.setNoDelay(true);\n\n socket.on('data', data => this.onData(data));\n socket.on('error', e => {\n // A satellite that is switched off is normal, so this is not an error-level event.\n this.opts.log.debug(`ESPHome ${this.host}: ${e.message}`);\n });\n socket.on('close', () => {\n if (this.socket === socket) {\n this.socket = null;\n this.onDisconnected();\n }\n });\n }\n\n private onDisconnected(): void {\n this.clearTimers();\n this.abortCapture();\n // A reply still being worked out must not land on the next connection, in the middle of another run.\n this.run++;\n this.runOpen = false;\n this.questionUntil = 0;\n this.ignoreFollowUpUntil = 0;\n this.setDialog(false, 'offline');\n if (this.online) {\n this.opts.log.info(`ESPHome satellite offline: ${this.deviceName}`);\n }\n this.setOffline();\n this.scheduleReconnect();\n }\n\n private scheduleReconnect(): void {\n if (this.stopping || this.reconnectTimer) {\n return;\n }\n this.reconnectTimer = setTimeout(() => {\n this.reconnectTimer = null;\n this.connect();\n }, RECONNECT_MS);\n this.reconnectTimer.unref();\n }\n\n private clearTimers(): void {\n if (this.pingTimer) {\n clearInterval(this.pingTimer);\n this.pingTimer = null;\n }\n if (this.reconnectTimer) {\n clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n if (this.playbackTimer) {\n clearTimeout(this.playbackTimer);\n this.playbackTimer = null;\n }\n if (this.dialogTimer) {\n clearInterval(this.dialogTimer);\n this.dialogTimer = null;\n }\n }\n\n private setOffline(): void {\n if (this.online) {\n this.online = false;\n this.opts.onStatus?.(this.deviceName, this.room, 'offline', this.address);\n }\n }\n\n private status(state: SatelliteState): void {\n this.opts.onStatus?.(this.deviceName, this.room, state, this.address);\n }\n\n // ── protocol plumbing ───────────────────────────────────────────────────────────────────────────\n\n private send(message: PbMessage): void {\n const socket = this.socket;\n if (!socket || socket.destroyed) {\n return;\n }\n try {\n socket.write(encode(message));\n } catch (e) {\n this.opts.log.debug(`ESPHome ${this.deviceName}: send failed — ${(e as Error).message}`);\n }\n }\n\n private onData(data: Buffer): void {\n this.rx = this.rx.length ? Buffer.concat([this.rx, data]) : data;\n let frames;\n try {\n ({ frames, rest: this.rx } = decode(this.rx));\n } catch (e) {\n this.opts.log.error(`ESPHome ${this.deviceName}: ${(e as Error).message}`);\n this.socket?.destroy();\n return;\n }\n for (const frame of frames) {\n if (frame.error) {\n this.opts.log.debug(`ESPHome ${this.deviceName}: cannot parse ${frame.name}`);\n continue;\n }\n if (!frame.name || !frame.message) {\n continue; // unknown id — already skipped by its declared length\n }\n try {\n this.onMessage(frame.name, frame.message);\n } catch (e) {\n this.opts.log.warn(\n `ESPHome ${this.deviceName}: ${frame.name} handler failed — ${(e as Error).message}`,\n );\n }\n }\n }\n\n private handshake(): void {\n const hello = new pb.HelloRequest();\n hello.setClientInfo('ioBroker.assistant');\n hello.setApiVersionMajor(1);\n hello.setApiVersionMinor(10);\n this.send(hello);\n\n const auth = new pb.AuthenticationRequest();\n auth.setPassword(this.password);\n this.send(auth);\n\n this.send(new pb.DeviceInfoRequest());\n // Ask for the entity announcements *before* subscribing to their states: a state message whose\n // entity we have not seen yet has nothing to attach to and is dropped.\n this.send(new pb.ListEntitiesRequest());\n this.send(new pb.SubscribeStatesRequest());\n\n const subscribe = new pb.SubscribeVoiceAssistantRequest();\n subscribe.setSubscribe(true);\n subscribe.setFlags(SUBSCRIBE_API_AUDIO);\n this.send(subscribe);\n\n this.requestWakeWordConfig();\n\n this.pingTimer = setInterval(() => {\n if (++this.missedPings > 2) {\n this.opts.log.info(`ESPHome ${this.deviceName}: no reply to keepalive — reconnecting`);\n this.socket?.destroy();\n return;\n }\n this.send(new pb.PingRequest());\n }, PING_INTERVAL_MS);\n this.pingTimer.unref();\n }\n\n private onMessage(name: string, message: unknown): void {\n switch (name) {\n case 'HelloResponse': {\n const hello = message as HelloResponse;\n this.opts.log.debug(\n `ESPHome ${this.host}: ${hello.getServerInfo()} (API ${hello.getApiVersionMajor()}.${hello.getApiVersionMinor()})`,\n );\n return;\n }\n\n case 'AuthenticationResponse':\n if ((message as AuthenticationResponse).getInvalidPassword()) {\n this.opts.log.error(\n `ESPHome ${this.host}: API password rejected — check the device's password in the settings.`,\n );\n this.socket?.destroy();\n }\n return;\n\n case 'DeviceInfoResponse': {\n const info = message as DeviceInfoResponse;\n this.deviceName = info.getName() || this.host;\n this.friendlyName = info.getFriendlyName?.() || info.getName() || '';\n this.online = true;\n this.opts.log.info(\n `ESPHome satellite online: ${this.deviceName} (${info.getModel()}) @ ${this.host}${this.room ? `, room ${this.room}` : ''}`,\n );\n this.status('idle');\n return;\n }\n\n case 'VoiceAssistantConfigurationResponse': {\n const config = message as VoiceAssistantConfigurationResponse;\n // A custom wake word the device already downloaded is listed twice: once from its own\n // model folder and once from our offer.\n const seen = new Set<string>();\n this.wakeWordConfig = {\n active: config.getActiveWakeWordsList(),\n available: config\n .getAvailableWakeWordsList()\n .map(w => ({\n id: w.getId(),\n phrase: w.getWakeWord(),\n languages: w.getTrainedLanguagesList(),\n }))\n .filter(w => !seen.has(w.id) && !!seen.add(w.id)),\n max: config.getMaxActiveWakeWords(),\n };\n const active = this.wakeWordConfig.active.join(', ') || '(none active)';\n const available = this.wakeWordConfig.available.map(w => w.id);\n this.opts.log.info(\n `ESPHome ${this.deviceName}: wake words ${active}${available.length ? ` (available: ${available.join(', ')})` : ''}`,\n );\n const requested = this.configChecks.shift();\n const missing = requested?.filter(id => !this.wakeWordConfig?.active.includes(id)) ?? [];\n if (missing.length) {\n // The device answers a model it cannot fetch or load with silence, not an error.\n this.opts.log.warn(\n `ESPHome ${this.deviceName}: could not activate wake word(s) ${missing.join(', ')}. ` +\n `For an uploaded wake word the device must reach ${this.mediaUrl('/')} and the model ` +\n `must be a microWakeWord .tflite.`,\n );\n }\n this.opts.onWakeWords?.(this.deviceName, this.room, this.wakeWordConfig);\n return;\n }\n\n case 'VoiceAssistantRequest':\n this.onPipelineRequest(message as VoiceAssistantRequestMsg);\n return;\n\n case 'VoiceAssistantAudio':\n this.onAudio(message as VoiceAssistantAudio);\n return;\n\n case 'VoiceAssistantAnnounceFinished':\n if (this.playbackTimer) {\n clearTimeout(this.playbackTimer);\n this.playbackTimer = null;\n }\n this.opts.log.debug(\n `ESPHome ${this.deviceName}: playback finished (success=${(message as VoiceAssistantAnnounceFinished).getSuccess()})`,\n );\n this.status('idle');\n return;\n\n case 'PingRequest':\n this.send(new pb.PingResponse());\n return;\n\n case 'PingResponse':\n this.missedPings = 0;\n return;\n\n case 'GetTimeRequest': {\n // The device has no RTC and syncs its clock from us — its timer ring depends on it.\n const time = new pb.GetTimeResponse();\n time.setEpochSeconds(Math.floor(Date.now() / 1000));\n this.send(time);\n return;\n }\n\n case 'DisconnectRequest':\n this.send(new pb.DisconnectResponse());\n this.socket?.destroy();\n return;\n\n case 'ListEntitiesDoneResponse': {\n const list = this.entities.list();\n if (list.length) {\n this.opts.log.debug(\n `ESPHome ${this.deviceName}: ${list.length} entities — ${list.map(e => e.objectId).join(', ')}`,\n );\n }\n this.opts.onEntities?.(this.deviceName, this.room, list);\n return;\n }\n\n default:\n if (isListEntityMessage(name)) {\n this.entities.addFromAnnouncement(name, message, this.friendlyName);\n } else if (isEntityStateMessage(name)) {\n const entity = this.entities.applyState(name, message);\n if (entity) {\n this.opts.onEntityState?.(this.deviceName, this.room, entity);\n this.onEntityChange(entity);\n }\n }\n return;\n }\n }\n\n /** Entities of a satellite with a screen that take part in the conversation (see {@link CONFIRM_ENTITY}). */\n private onEntityChange(entity: EsphomeEntity): void {\n if (entity.objectId === CONFIRM_ENTITY && entity.kind === 'event') {\n this.onConfirmButton(entity.value);\n } else if (entity.objectId === DISPLAY_LANGUAGE_ENTITY && entity.kind === 'select') {\n // Once per connect, with the state the device reports on subscribing: a language the user picks on the\n // device afterwards stays until the next connect (a change of the voice language restarts the adapter).\n if (!this.displayLanguageChecked) {\n this.displayLanguageChecked = true;\n this.syncDisplayLanguage(entity);\n }\n }\n }\n\n /** Show the device's screen in the voice language, if it offers that language. */\n private syncDisplayLanguage(entity: EsphomeEntity): void {\n const language = this.opts.language;\n if (!language) {\n return;\n }\n const option = displayLanguageOption(entity.options ?? [], language);\n if (!option) {\n this.opts.log.debug(\n `ESPHome ${this.deviceName}: ${DISPLAY_LANGUAGE_ENTITY} has no option for \"${language}\" ` +\n `(${(entity.options ?? []).join(', ')})`,\n );\n return;\n }\n if (entity.value === option) {\n return;\n }\n const shown = typeof entity.value === 'string' ? entity.value : '?';\n this.opts.log.info(`ESPHome ${this.deviceName}: display language ${shown} → ${option}`);\n this.setEntity(DISPLAY_LANGUAGE_ENTITY, option);\n }\n\n /** Whether a yes/no button press now answers a question the last reply asked. */\n private questionOpen(): boolean {\n return !!this.capture?.answersQuestion || Date.now() < this.questionUntil;\n }\n\n /**\n * The user pressed yes or no on the device's screen. While a reply waits for an answer that is the answer: the\n * microphone opened for it is closed, the yes or no word goes on as the user's reply (pi-agent decides its\n * confirmation on it like on a spoken one), and the reply to that is announced on this device.\n */\n private onConfirmButton(eventType: unknown): void {\n const yes = confirmAnswerOf(eventType);\n if (yes === null) {\n this.opts.log.debug(\n `ESPHome ${this.deviceName}: ${CONFIRM_ENTITY} \"${String(eventType)}\" — not yes/no, ignored`,\n );\n return;\n }\n if (!this.questionOpen()) {\n this.opts.log.debug(\n `ESPHome ${this.deviceName}: ${CONFIRM_ENTITY} \"${yes ? 'yes' : 'no'}\" without an open question — ignored`,\n );\n return;\n }\n this.questionUntil = 0;\n // Pressed while the question still played: the device may open the microphone for it afterwards. Not if the\n // microphone is open already (our RUN_END closes it for good), and not if the device just stopped its\n // conversation itself — the firmware does that on the press, which also drops its continue flag.\n const micStillComes = !this.capture && Date.now() - this.stoppedAt >= CONFIRM_GRACE_MS;\n if (this.capture) {\n // A RUN_END while the microphone streams stops it and puts the device back to idle — without the error\n // display an empty recognition would end with.\n this.abortCapture();\n this.event(EVENT.RUN_END);\n }\n // Whatever is still in flight for the question stays silent; so does the follow-up microphone the device may\n // still open for it.\n const run = ++this.run;\n this.buttonAt = Date.now();\n this.ignoreFollowUpUntil = micStillComes ? Date.now() + IGNORE_FOLLOW_UP_MS : 0;\n void this.answerButton(yes, run);\n }\n\n /** Pass a button answer on and announce the reply (see {@link onConfirmButton}). */\n private async answerButton(yes: boolean, run: number): Promise<void> {\n const text = yesNoWord(this.opts.language, yes);\n this.opts.log.info(`ESPHome ${this.deviceName}: answered \"${text}\" with the button`);\n this.status('processing');\n try {\n const answer = (\n await this.opts.answer(text, { device: this.deviceName, room: this.room, button: yes ? 'yes' : 'no' })\n ).trim();\n if (run !== this.run) {\n return;\n }\n if (!answer) {\n this.status('idle');\n return;\n }\n const followUp = this.opts.expectsFollowUp?.(answer, this.deviceName) === true;\n const ttsStart = Date.now();\n const { pcm, sampleRate } = await this.opts.tts.synthesize(answer, this.opts.language);\n if (run !== this.run) {\n return;\n }\n this.opts.onSpoken?.(this.deviceName, {\n ms: Date.now() - ttsStart,\n audioMs: (pcm.length / 2 / sampleRate) * 1000,\n });\n await this.announce(pcm, sampleRate, followUp, answer);\n } catch (e) {\n this.opts.log.warn(`ESPHome ${this.deviceName}: answer to the button failed — ${(e as Error).message}`);\n if (run === this.run) {\n this.status('idle');\n }\n }\n }\n\n /** Write one of the device's entities. See {@link EsphomeSatellites.setEntity}. */\n setEntity(objectId: string, value: unknown): boolean {\n const message = this.entities.command(objectId, value);\n if (!message) {\n const entity = this.entities.get(objectId);\n const known = this.entities\n .list()\n .map(e => e.objectId)\n .join(', ');\n const options = entity?.options\n ? ` (one of: ${entity.options.join(', ')})`\n : entity?.kind === 'text'\n ? ` (${entity.minLength || 0}–${entity.maxLength ?? '∞'} bytes${entity.pattern ? `, pattern ${entity.pattern}` : ''})`\n : '';\n this.opts.log.warn(\n entity\n ? `ESPHome ${this.deviceName}: ${JSON.stringify(value)} is not a value \"${objectId}\" accepts${options}`\n : `ESPHome ${this.deviceName}: no entity \"${objectId}\" (have: ${known})`,\n );\n return false;\n }\n this.send(message);\n this.opts.log.debug(`ESPHome ${this.deviceName}: ${objectId} := ${JSON.stringify(value)}`);\n return true;\n }\n\n /** Push one assistant timer to the device so it can show and ring it itself. */\n sendTimerEvent(event: TimerEvent): void {\n const message = new pb.VoiceAssistantTimerEventResponse();\n message.setEventType(TIMER_EVENT[event.type]);\n message.setTimerId(event.id);\n message.setName(event.name);\n message.setTotalSeconds(Math.max(0, Math.round(event.totalSeconds)));\n message.setSecondsLeft(Math.max(0, Math.round(event.secondsLeft)));\n message.setIsActive(event.active);\n this.send(message);\n }\n\n // ── voice pipeline ──────────────────────────────────────────────────────────────────────────────\n\n private onPipelineRequest(request: VoiceAssistantRequestMsg): void {\n if (!request.getStart()) {\n this.onStopRequest();\n return;\n }\n if (this.capture) {\n this.opts.log.debug(`ESPHome ${this.deviceName}: pipeline already running — ignoring wake`);\n return;\n }\n const phrase = request.getWakeWordPhrase();\n if (Date.now() < this.ignoreFollowUpUntil) {\n // The microphone for the question a button already answered: close it at once. In this state the device\n // takes a RUN_END as \"stop the microphone\" and goes back to idle.\n this.ignoreFollowUpUntil = 0;\n this.opts.log.debug(`ESPHome ${this.deviceName}: follow-up of a question answered by button — closing it`);\n this.event(EVENT.RUN_END);\n return;\n }\n if (this.runOpen) {\n // The device started over while the last request was still being answered: that answer is not\n // wanted any more, and its events would land in the middle of the new run.\n this.opts.log.debug(`ESPHome ${this.deviceName}: new wake while answering — dropping the old reply`);\n }\n this.run++;\n // While a question is open the next request answers it. The phrase says nothing here: the follow-up\n // microphone carries the last wake word too. Should the user really have said the wake word, the utterance\n // is still the next one after the question — which is what pi-agent and askUser take as the answer anyway.\n const answersQuestion = Date.now() < this.questionUntil;\n // In dialog mode every microphone is the next turn: the phrase is the stale one of the last wake word.\n const dialog = this.dialogOn;\n const followUp = answersQuestion || !phrase || dialog;\n\n this.opts.log.debug(\n `ESPHome ${this.deviceName}: ${\n answersQuestion\n ? 'answer to the question'\n : dialog\n ? 'dialog'\n : followUp\n ? 'follow-up'\n : `wake \"${phrase}\"`\n }`,\n );\n\n const response = new pb.VoiceAssistantResponse();\n response.setPort(0); // 0 = stream the audio over this socket\n response.setError(false);\n this.send(response);\n\n const stallCheck = setInterval(() => this.checkStall(), STALL_CHECK_MS);\n stallCheck.unref();\n\n this.capture = {\n chunks: [],\n detector: this.speechDetector(followUp, dialog, WAKE_CHIRP_MS),\n conversationId: request.getConversationId(),\n wakeWord: followUp ? '' : phrase,\n answersQuestion,\n timer: this.pipelineTimer(dialog),\n stallCheck,\n startedAt: Date.now(),\n lastAudioAt: 0,\n closed: false,\n dialog,\n };\n\n this.status('listening');\n this.event(EVENT.RUN_START);\n if (!followUp) {\n this.event(EVENT.WAKE_WORD_END, { wake_word_phrase: phrase });\n }\n this.event(EVENT.STT_START);\n this.event(EVENT.STT_VAD_START);\n }\n\n /**\n * End-of-speech detection for one recording. `skipMs`: the wake chirp at its start.\n *\n * Microphone gain differs wildly between these devices, so fixed RMS levels do not travel: the levels are derived\n * from the room, once the chirp is out of the way. In dialog mode nobody may speak for a while — there the window\n * starts over (see {@link onAudio}) instead of the run ending, and a request may take longer.\n */\n private speechDetector(followUp: boolean, dialog: boolean, skipMs: number): SpeechDetector {\n const silenceMs = this.opts.silenceMs || DEFAULT_SILENCE_MS;\n return new SpeechDetector({\n sampleRate: MIC_SAMPLE_RATE,\n silenceMs,\n longSilenceMs: Math.round(silenceMs * LONG_PAUSE_FACTOR),\n longAfterMs: LONG_REQUEST_MS,\n skipMs,\n adaptive: true,\n startTimeoutMs: dialog ? 0 : followUp ? NO_SPEECH_FOLLOW_UP_MS : NO_SPEECH_MS,\n maxMs: dialog ? DIALOG_WINDOW_MS + DIALOG_MAX_SPEECH_MS : undefined,\n minStartLevel: this.speechLevel || DEFAULT_SPEECH_LEVEL,\n minEndLevel: Math.round((this.speechLevel || DEFAULT_SPEECH_LEVEL) * SILENCE_SHARE),\n minSpeechMs: MIN_SPEECH_MS,\n });\n }\n\n /** Last resort for a recording that never ends; in dialog mode per window. */\n private pipelineTimer(dialog: boolean): NodeJS.Timeout {\n const ms = dialog ? DIALOG_WINDOW_MS + DIALOG_MAX_SPEECH_MS + 5000 : PIPELINE_TIMEOUT_MS;\n const timer = setTimeout(() => {\n this.opts.log.warn(`ESPHome ${this.deviceName}: no end of speech within ${ms} ms`);\n void this.finishCapture('pipeline-timeout');\n }, ms);\n timer.unref();\n return timer;\n }\n\n /**\n * Dialog mode on or off. On: every reply asks the device to open its microphone again (`continue_conversation`),\n * and while nobody speaks the recording just goes on. Switched on while nothing runs, `open` is played as an\n * announcement that opens the microphone. Off: a microphone that hears nothing is closed now; a request being\n * answered closes it with its reply.\n */\n setDialog(on: boolean, reason: DialogChange, open?: { pcm: Buffer; sampleRate: number }): void {\n if (this.dialogOn === on) {\n return;\n }\n this.dialogOn = on;\n this.dialogHeardAt = Date.now();\n if (this.dialogTimer) {\n clearInterval(this.dialogTimer);\n this.dialogTimer = null;\n }\n const why =\n reason === 'idle'\n ? ` (nothing said for ${DIALOG_IDLE_MS / 60_000} min)`\n : reason === 'stop'\n ? ' (the device was stopped)'\n : reason === 'offline'\n ? ' (offline)'\n : reason === 'error'\n ? ' (the voice pipeline failed)'\n : '';\n this.opts.log.info(`ESPHome ${this.deviceName}: dialog mode ${on ? 'on' : 'off'}${why}`);\n this.opts.onDialog?.(this.deviceName, this.room, on, reason);\n if (on) {\n this.dialogTimer = setInterval(() => this.checkDialogIdle(), DIALOG_CHECK_MS);\n this.dialogTimer.unref();\n if (open && this.online && !this.capture && !this.runOpen) {\n void this.announce(open.pcm, open.sampleRate, true, '', false).catch(e =>\n this.opts.log.warn(\n `ESPHome ${this.deviceName}: opening the microphone failed — ${(e as Error).message}`,\n ),\n );\n }\n return;\n }\n const capture = this.capture;\n if (capture?.dialog && !capture.detector.hearing) {\n void this.finishCapture('no-speech'); // nobody talks: close the microphone now\n }\n }\n\n get dialog(): boolean {\n return this.dialogOn;\n }\n\n /** Dialog mode: switch it off when nothing was said for a long time — but not while somebody speaks or is answered. */\n private checkDialogIdle(): void {\n if (!this.dialogOn || Date.now() - this.dialogHeardAt < DIALOG_IDLE_MS) {\n return;\n }\n const capture = this.capture;\n if (capture ? capture.detector.hearing : this.runOpen) {\n return;\n }\n this.setDialog(false, 'idle');\n }\n\n /**\n * The device asks to end the conversation (`VoiceAssistantRequest{start:false}`): a button, or the wake word\n * said again while a request is running — that is how ESPHome's voice_assistant stops. While it waits for an\n * answer, the firmware leaves that state only on our RUN_END; without one it stays \"in the conversation\", and\n * every further wake word just sends another stop (field report 2026-11-03).\n */\n private onStopRequest(): void {\n this.stoppedAt = Date.now();\n const running = !!this.capture || this.runOpen;\n if (!running && Date.now() - this.buttonAt < CONFIRM_GRACE_MS) {\n // A device with yes/no buttons reports the press and then stops its conversation itself: the button\n // answer ended our run already, and its reply is on the way — nothing to end, nothing to drop. With the\n // stop the device dropped its continue flag too, so no microphone opens for the answered question.\n this.ignoreFollowUpUntil = 0;\n this.opts.log.debug(`ESPHome ${this.deviceName}: the device ended the conversation after the button`);\n return;\n }\n // A device with yes/no buttons may also stop the microphone on the press before it reports which button it\n // was (state messages can be batched): the question stays open a moment longer for that report.\n this.questionUntil = this.questionOpen() ? Math.max(this.questionUntil, Date.now() + CONFIRM_GRACE_MS) : 0;\n this.abortCapture();\n if (Date.now() - this.errorSentAt >= ERROR_ECHO_MS) {\n // Stopping the device ends the dialog, too (a reply in progress is dropped below, so it re-opens nothing)\n this.setDialog(false, 'stop');\n }\n if (running) {\n this.run++; // whatever is still being answered stays silent\n this.opts.log.debug(`ESPHome ${this.deviceName}: the device ended the conversation`);\n this.event(EVENT.RUN_END);\n this.status('idle');\n return;\n }\n if (Date.now() - this.errorSentAt < ERROR_ECHO_MS) {\n return; // the device's own reaction to our ERROR event\n }\n // Nothing is open on our side, but the device still thinks so (it missed a RUN_END): end it there too.\n this.opts.log.debug(`ESPHome ${this.deviceName}: stop outside a conversation — ending it on the device`);\n this.event(EVENT.RUN_END);\n }\n\n private onAudio(audio: VoiceAssistantAudio): void {\n const capture = this.capture;\n if (!capture || capture.closed) {\n return;\n }\n const chunk = Buffer.from(audio.getData_asU8());\n if (chunk.length) {\n capture.lastAudioAt = Date.now();\n capture.chunks.push(chunk);\n const end = capture.detector.push(chunk);\n if (end) {\n void this.finishCapture(end);\n return;\n }\n if (capture.dialog && !capture.detector.hearing && capture.detector.analysedMs >= DIALOG_WINDOW_MS) {\n this.nextDialogWindow(capture);\n }\n }\n if (audio.getEnd()) {\n void this.finishCapture('stream');\n }\n }\n\n /**\n * Dialog mode, nobody spoke during a window: forget it and start a new one on the audio that keeps coming. Only\n * while nothing is heard, so a word that just began is not cut.\n */\n private nextDialogWindow(capture: Capture): void {\n capture.chunks = [];\n capture.detector = this.speechDetector(true, true, 0);\n clearTimeout(capture.timer);\n capture.timer = this.pipelineTimer(true);\n }\n\n /** End a capture whose device stopped sending audio without ending the stream. */\n private checkStall(): void {\n const capture = this.capture;\n if (!capture || capture.closed) {\n return;\n }\n const now = Date.now();\n const quietMs = capture.lastAudioAt ? now - capture.lastAudioAt : now - capture.startedAt;\n if (quietMs < (capture.lastAudioAt ? STREAM_STALL_MS : STREAM_START_MS)) {\n return;\n }\n const audioMs = Math.round(capture.chunks.reduce((sum, c) => sum + c.length, 0) / 2 / (MIC_SAMPLE_RATE / 1000));\n this.opts.log.info(\n `ESPHome ${this.deviceName}: the device ${\n capture.lastAudioAt ? `stopped sending audio after ${(audioMs / 1000).toFixed(2)} s` : 'sent no audio'\n } without ending the stream — closing the utterance after ${(quietMs / 1000).toFixed(1)} s of nothing`,\n );\n void this.finishCapture('stall');\n }\n\n /** Hand a recording that never became a request to {@link EsphomeSatellitesOptions.onDiscarded}. */\n private discard(capture: Capture, pcm: Bytes, reason: DiscardReason, vad: VadReport): void {\n if (!this.opts.onDiscarded || !pcm.length) {\n return;\n }\n try {\n this.opts.onDiscarded({\n device: this.deviceName,\n room: this.room,\n wakeWord: capture.wakeWord,\n reason,\n pcm,\n sampleRate: MIC_SAMPLE_RATE,\n // The store writes its own level profile next to it.\n vad: { ...vad, levels: undefined },\n });\n } catch (e) {\n this.opts.log.debug(`ESPHome ${this.deviceName}: keeping the recording failed — ${(e as Error).message}`);\n }\n }\n\n /** Stop the mic stream and run STT → answer → TTS for what was captured. */\n private async finishCapture(end: CaptureEnd): Promise<void> {\n const capture = this.capture;\n if (!capture || capture.closed) {\n return;\n }\n capture.closed = true;\n this.capture = null;\n clearTimeout(capture.timer);\n clearInterval(capture.stallCheck);\n const run = this.run;\n /** False once the run was ended elsewhere — then nothing more may be sent for it. */\n const current = (): boolean => {\n if (run === this.run) {\n return true;\n }\n this.opts.log.debug(`ESPHome ${this.deviceName}: conversation ended meanwhile — dropping the reply`);\n return false;\n };\n\n // Send this first: the device streams until it sees it.\n this.event(EVENT.STT_VAD_END);\n\n const pcm = Buffer.concat(capture.chunks);\n const seconds = pcm.length / 2 / MIC_SAMPLE_RATE;\n const vad: VadReport = { ...capture.detector.report(), end };\n const startedAt =\n vad.speechStartMs !== undefined ? `, speech from ${(vad.speechStartMs / 1000).toFixed(2)} s` : '';\n const endedBy = vad.end === 'speech-end' ? `ended after ${vad.silenceMs} ms of silence` : `ended by ${vad.end}`;\n this.opts.log.debug(\n `ESPHome ${this.deviceName}: captured ${seconds.toFixed(2)} s ` +\n `(peak RMS ${vad.peak}, noise floor ${vad.noiseFloor}, speech/silence gate ${vad.startLevel}/${vad.endLevel}` +\n `${startedAt}, ${endedBy})`,\n );\n\n if (capture.answersQuestion) {\n // Spoken: that is the answer, a button press now would be a second one. Silent: the buttons still answer\n // for a moment, as the screen may still show them.\n this.questionUntil = capture.detector.sawSpeech\n ? 0\n : Math.max(this.questionUntil, Date.now() + CONFIRM_GRACE_MS);\n }\n\n if (!pcm.length || !capture.detector.sawSpeech) {\n const loudest = Math.round(capture.detector.analysedPeak);\n const gate = Math.round(capture.detector.startLevel);\n if (capture.detector.longestSoundMs > 0) {\n // Something crossed the gate, but too briefly for a word: a click, a knock, a cough.\n this.opts.log.debug(\n `ESPHome ${this.deviceName}: only a short sound (${capture.detector.longestSoundMs} ms, ` +\n `RMS ${loudest}) — too short for speech (${MIN_SPEECH_MS} ms), dropping the utterance`,\n );\n } else if (pcm.length && loudest >= gate * QUIET_VOICE_SHARE) {\n // Not an empty room: something came close to the gate. Typically a microphone that is quieter\n // than the default threshold expects (a phone) — say where to change it.\n this.opts.log.info(\n `ESPHome ${this.deviceName}: dropped the utterance — the loudest sound (RMS ${loudest}) stayed ` +\n `below the speech threshold ${gate}. If somebody spoke, lower \"Speech threshold\" for this ` +\n `device in the ESPHome satellites table (Voice tab), e.g. to ${Math.max(\n 30,\n Math.round((loudest * 0.6) / 10) * 10,\n )}.`,\n );\n } else {\n this.opts.log.debug(\n `ESPHome ${this.deviceName}: nothing but silence${\n end === 'no-speech' ? ' (nobody started speaking)' : ''\n } — dropping the utterance`,\n );\n }\n if (capture.dialog && this.dialogOn && (end === 'timeout' || end === 'speech-end')) {\n // a long noise in dialog mode: listen on\n this.event(EVENT.INTENT_END, { continue_conversation: '1' });\n await this.reopenDialog(run);\n return;\n }\n if (!capture.dialog) {\n this.discard(capture, pcm, end === 'no-speech' ? 'no-speech' : 'silence', vad);\n }\n this.endWithoutRequest();\n if (capture.dialog) {\n // the device ended or stopped the stream itself: it does not want to listen any more\n this.setDialog(false, 'stop');\n }\n return;\n }\n\n this.status('processing');\n try {\n const hints = this.opts.getHints ? await this.opts.getHints() : undefined;\n if (!current()) {\n return;\n }\n const speech = prepareForStt(pcm, MIC_SAMPLE_RATE, { startMs: vad.speechStartMs, endLevel: vad.endLevel });\n vad.stt = { fromMs: speech.fromMs, toMs: speech.toMs, gain: speech.gain };\n this.opts.log.debug(\n `ESPHome ${this.deviceName}: speech recognition gets ${(speech.fromMs / 1000).toFixed(2)}–` +\n `${(speech.toMs / 1000).toFixed(2)} s${speech.gain > 1 ? `, amplified ×${speech.gain}` : ''}`,\n );\n const sttStart = Date.now();\n const text = (\n await this.opts.stt.transcribe(speech.pcm, MIC_SAMPLE_RATE, this.opts.language, hints)\n ).trim();\n const sttMs = Date.now() - sttStart;\n if (!current()) {\n return;\n }\n if (!text) {\n // Speech was heard, so the user waits for an answer: say why none comes. Typically a word in another\n // language than the STT listens in (a German \"Ja\" to a Russian STT comes back empty).\n this.opts.log.info(\n `Voice Q (${this.deviceName}): (empty) — speech recognition returned no text for ${seconds.toFixed(1)} s of audio`,\n );\n this.discard(capture, pcm, 'empty-stt', vad);\n if (capture.answersQuestion) {\n this.questionUntil = Math.max(this.questionUntil, Date.now() + CONFIRM_GRACE_MS);\n }\n if (capture.dialog && this.dialogOn) {\n // a cough, the TV: listen on, without a word about it\n this.event(EVENT.INTENT_END, { continue_conversation: '1' });\n await this.reopenDialog(run);\n return;\n }\n // No STT_END without text — like Home Assistant, which reports this case as an error only.\n this.endWithoutRequest();\n return;\n }\n if (capture.dialog) {\n this.dialogHeardAt = Date.now();\n }\n this.event(EVENT.STT_END, { text });\n\n this.event(EVENT.INTENT_START);\n const answer = (\n await this.opts.answer(text, {\n device: this.deviceName,\n room: this.room,\n wakeWord: capture.wakeWord,\n sttMs,\n audioMs: Math.round(seconds * 1000),\n // Numbers only, no audio: shows where a request was cut off without keeping recordings.\n vad: { ...vad, levels: levelProfile(pcm, MIC_SAMPLE_RATE) },\n })\n ).trim();\n if (!current()) {\n return;\n }\n const followUp = !!answer && this.opts.expectsFollowUp?.(answer, this.deviceName) === true;\n // Always say it, \"0\" included: ESPHome keeps the flag of the last INTENT_END that carried it, so after\n // one question every later reply re-opened the microphone (field report 2026-11-04). Home Assistant\n // sends \"0\" just the same. In dialog mode (switched on or off by this very request, too) always \"1\".\n const conversation = { continue_conversation: followUp || this.dialogOn ? '1' : '0' };\n this.event(EVENT.INTENT_END, conversation);\n\n if (!answer) {\n if (this.dialogOn) {\n // A command done without words (the confirmation tone instead): the tone is the reply here, after\n // it the device listens again. The adapter does not play it itself in dialog mode.\n const tone = confirmationTone();\n await this.reopenDialog(run, tone.pcm, tone.sampleRate);\n return;\n }\n this.event(EVENT.RUN_END);\n this.status('idle');\n return;\n }\n\n const ttsStart = Date.now();\n const { pcm: ttsPcm, sampleRate } = await this.opts.tts.synthesize(answer, this.opts.language);\n if (!current()) {\n return;\n }\n this.opts.onSpoken?.(this.deviceName, {\n ms: Date.now() - ttsStart,\n audioMs: (ttsPcm.length / 2 / sampleRate) * 1000,\n });\n const url = await this.publish(ttsPcm, sampleRate);\n if (!current()) {\n return;\n }\n\n this.status('speaking');\n this.event(EVENT.TTS_START, { text: answer });\n this.event(EVENT.TTS_END, { url });\n // linux-voice-assistant reads the flag here (ignoring \"0\"), ESPHome at INTENT_END\n this.event(EVENT.RUN_END, conversation);\n this.questionUntil = followUp ? Date.now() + (ttsPcm.length / 2 / sampleRate) * 1000 + QUESTION_OPEN_MS : 0;\n this.armPlaybackTimeout();\n } catch (e) {\n const reason = (e as Error).message;\n this.opts.log.error(`ESPHome ${this.deviceName}: voice pipeline failed — ${reason}`);\n if (run !== this.run) {\n return; // the conversation is over already — nothing to tell the device\n }\n // Without this the device stays ducked and its LED keeps spinning.\n this.event(EVENT.ERROR, { code: 'pipeline-failed', message: reason });\n this.event(EVENT.RUN_END);\n this.status('idle');\n this.setDialog(false, 'error');\n }\n }\n\n /**\n * Dialog mode: end the run with a reply that only makes the device listen again — silence when nothing was\n * recognised, else the given clip. ESPHome opens the microphone after a reply has played when the INTENT_END\n * (sent by the caller) said so; linux-voice-assistant reads the flag in RUN_END.\n */\n private async reopenDialog(run: number, pcm?: Buffer, sampleRate = MIC_SAMPLE_RATE): Promise<void> {\n const clip = pcm ?? Buffer.alloc(Math.round((MIC_SAMPLE_RATE * DIALOG_PAUSE_MS) / 1000) * 2);\n try {\n const url = await this.publish(clip, sampleRate);\n if (run !== this.run) {\n return;\n }\n this.status('speaking');\n this.event(EVENT.TTS_START, { text: '' });\n this.event(EVENT.TTS_END, { url });\n this.event(EVENT.RUN_END, { continue_conversation: '1' });\n this.armPlaybackTimeout();\n } catch (e) {\n this.opts.log.warn(`ESPHome ${this.deviceName}: dialog cannot go on — ${(e as Error).message}`);\n if (run === this.run) {\n this.endWithoutRequest();\n this.setDialog(false, 'error');\n }\n }\n }\n\n /**\n * End a run that produced no request. A RUN_END right after STT_VAD_END gets lost: the firmware is still stopping\n * its microphone then, ignores RUN_END in that state, and afterwards waits for an answer that never comes — the\n * satellite stays in the conversation (field report 2026-11-03). An ERROR event puts it back to idle in any state,\n * so it goes first, with the code Home Assistant uses for this case.\n */\n private endWithoutRequest(): void {\n this.event(EVENT.ERROR, NO_TEXT_ERROR);\n this.event(EVENT.RUN_END);\n this.status('idle');\n }\n\n /**\n * Select which wake words listen on this device. Unknown ids are dropped and the list is trimmed\n * to what the firmware allows, because the device answers a rejected list with silence rather than\n * an error — better to send something valid and report what we changed.\n *\n * The device persists the selection and echoes it back in a `VoiceAssistantConfigurationResponse`,\n * so we ask for one instead of assuming the write took.\n */\n setWakeWords(ids: string[]): void {\n const known = this.wakeWordConfig?.available.map(w => w.id) ?? [];\n const wanted = [...new Set(ids.map(i => i.trim()).filter(Boolean))];\n const unknown = wanted.filter(i => !known.includes(i));\n if (unknown.length) {\n this.opts.log.warn(\n `ESPHome ${this.deviceName}: unknown wake word(s) ${unknown.join(', ')} — ignored. ` +\n `Available: ${known.join(', ') || '(none reported)'}`,\n );\n }\n let valid = wanted.filter(i => known.includes(i));\n const max = this.wakeWordConfig?.max || 0;\n if (max > 0 && valid.length > max) {\n this.opts.log.warn(\n `ESPHome ${this.deviceName}: device allows ${max} active wake word(s), keeping ${valid\n .slice(0, max)\n .join(', ')}`,\n );\n valid = valid.slice(0, max);\n }\n\n const message = new pb.VoiceAssistantSetConfiguration();\n message.setActiveWakeWordsList(valid);\n this.send(message);\n this.opts.log.info(`ESPHome ${this.deviceName}: wake words set to ${valid.join(', ') || '(none)'}`);\n // Read back, so the reported state is the device's and not our guess. The device resolves a\n // custom wake word (and downloads it) while handling the SetConfiguration, so this answer\n // already tells whether that worked.\n this.requestWakeWordConfig(valid);\n }\n\n /**\n * Ask the device for its wake-word configuration. The request always carries the current custom\n * wake words: the firmware replaces its list of offered models with every request, so one sent\n * without them would make an uploaded wake word vanish from the device until the next offer.\n *\n * @param check ids a SetConfiguration just asked for — warned about if the answer lacks them\n */\n requestWakeWordConfig(check: string[] | null = null): void {\n const request = new pb.VoiceAssistantConfigurationRequest();\n const offers = this.opts.externalWakeWords?.() ?? [];\n request.setExternalWakeWordsList(\n offers.map(offer => {\n const w = new pb.VoiceAssistantExternalWakeWord();\n w.setId(offer.id);\n w.setWakeWord(offer.phrase);\n w.setTrainedLanguagesList(offer.languages);\n w.setModelType('micro');\n w.setModelSize(offer.size);\n w.setModelHash(offer.sha256);\n w.setUrl(this.mediaUrl(offer.path));\n return w;\n }),\n );\n // A device that never answers must not let this grow without bound.\n if (this.configChecks.length < 16) {\n this.configChecks.push(check);\n }\n this.send(request);\n }\n\n /** Drop a half-finished capture (device went away, or told us to stop). */\n private abortCapture(): void {\n const capture = this.capture;\n if (!capture) {\n return;\n }\n this.capture = null;\n capture.closed = true;\n clearTimeout(capture.timer);\n clearInterval(capture.stallCheck);\n }\n\n // ── announcements ───────────────────────────────────────────────────────────────────────────────\n\n /**\n * Speak a ready PCM buffer on this device (timers, alarms, `tts.text`, jingles). With\n * `startConversation` the microphone opens once the clip has played, to catch the answer to a question.\n */\n async announce(\n pcm: Buffer,\n sampleRate: number,\n startConversation = false,\n text = '',\n question = true,\n ): Promise<void> {\n if (!this.online || !pcm.length) {\n return;\n }\n const request = new pb.VoiceAssistantAnnounceRequest();\n request.setMediaId(await this.publish(pcm, sampleRate));\n // What a device with a screen shows while it plays (its on_tts_start)\n request.setText(text);\n request.setPreannounceMediaId('');\n // Needs feature flag 32 (START_CONVERSATION); on a device without it the clip still plays and\n // only the microphone stays shut, so there is nothing to guard here.\n request.setStartConversation(startConversation);\n if (startConversation) {\n // The microphone the device opens after it is wanted; for a question a button press answers it, too\n this.ignoreFollowUpUntil = 0;\n if (question) {\n this.questionUntil = Date.now() + (pcm.length / 2 / sampleRate) * 1000 + QUESTION_OPEN_MS;\n }\n }\n this.status('speaking');\n this.send(request);\n this.armPlaybackTimeout();\n }\n\n /** The format replies should have on this device, from what its media player announced. */\n private replyFormat(): ReplyFormat {\n const formats = this.entities\n .list()\n .filter(e => e.kind === 'mediaPlayer')\n .flatMap(e => e.formats ?? []);\n return chooseReplyFormat(formats, !!this.opts.encodeAudio);\n }\n\n /**\n * Publish PCM on the media server, in the format the device plays, and build the URL it should fetch.\n *\n * The host matters: on a multi-homed ioBroker machine the device can usually only reach one of the\n * addresses, and the local end of *this* socket is by definition one it can talk to.\n */\n private async publish(pcm: Buffer, sampleRate: number): Promise<string> {\n let format = this.replyFormat();\n let encoded: { body: Buffer; contentType: string };\n try {\n encoded = await encodeReply(pcm, sampleRate, format, this.opts.encodeAudio);\n } catch (e) {\n // MP3/Opus need ffmpeg. Without it a native format is the only chance, whether the device lists it or not.\n const fallback: ReplyFormat = { ...format, codec: 'flac', source: `${format.source}, FLAC as fallback` };\n this.opts.log.warn(\n `ESPHome ${this.deviceName}: cannot write the reply as ${format.codec.toUpperCase()} ` +\n `(${(e as Error).message}) — sending FLAC, which the device may not play. Install ffmpeg.`,\n );\n format = fallback;\n encoded = await encodeReply(pcm, sampleRate, format);\n }\n const key = `${format.codec}/${format.sampleRate}/${format.channels}`;\n if (key !== this.loggedFormat) {\n this.loggedFormat = key;\n const what = !format.source\n ? 'WAV (the device lists no formats)'\n : `${format.codec.toUpperCase()}${format.sampleRate ? ` ${format.sampleRate} Hz` : ''}` +\n `${format.channels === 2 ? ' stereo' : ''} (device: ${format.source})`;\n this.opts.log.info(`ESPHome ${this.deviceName}: spoken replies as ${what}`);\n }\n return this.mediaUrl(this.opts.media.publish(encoded.body, encoded.contentType));\n }\n\n /** Absolute URL of a path on the media server, with a host this device can reach. */\n mediaUrl(path: string): string {\n const local = (this.socket?.localAddress || '').replace(/^::ffff:/, '');\n const host = this.opts.mediaHost?.trim() || local || '127.0.0.1';\n // An IPv6 literal has to be bracketed in a URL.\n const authority = host.includes(':') ? `[${host}]` : host;\n return `http://${authority}:${this.opts.media.port}${path}`;\n }\n\n /** Fall back to `idle` if the device never reports that it finished playing. */\n private armPlaybackTimeout(): void {\n if (this.playbackTimer) {\n clearTimeout(this.playbackTimer);\n }\n this.playbackTimer = setTimeout(() => {\n this.playbackTimer = null;\n this.status('idle');\n }, PLAYBACK_TIMEOUT_MS);\n this.playbackTimer.unref();\n }\n\n private event(type: number, data?: Record<string, string>): void {\n if (type === EVENT.RUN_START) {\n this.runOpen = true;\n } else if (type === EVENT.RUN_END) {\n this.runOpen = false;\n } else if (type === EVENT.ERROR) {\n this.errorSentAt = Date.now();\n }\n const message = new pb.VoiceAssistantEventResponse();\n message.setEventType(type);\n const items: VoiceAssistantEventData[] = [];\n for (const [name, value] of Object.entries(data || {})) {\n const item = new pb.VoiceAssistantEventData();\n item.setName(name);\n item.setValue(value);\n items.push(item);\n }\n message.setDataList(items);\n this.send(message);\n }\n}\n"]}
1
+ {"version":3,"file":"esphome.js","sourceRoot":"","sources":["../../../src/lib/voice/esphome.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgOA,8BAGC;AAGD,0CASC;AAwBD,sDA0BC;AAGD,sCAGC;AAGD,wCAIC;AA9SD;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,8CAAgC;AAChC,iDAawB;AACxB,uDAAkH;AAClH,+BAAoF;AACpF,+CAA8C;AAC9C,+CAAuG;AACvG,yCAAqF;AAIrF,iCAA0C;AAE1C,8DAA8D;AAC9D,MAAM,KAAK,GAAG;IACV,KAAK,EAAE,CAAC;IACR,SAAS,EAAE,CAAC;IACZ,OAAO,EAAE,CAAC;IACV,SAAS,EAAE,CAAC;IACZ,O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C,KAAK,EAAE,CAAC;YAC9B,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QAClC,CAAC;QACD,MAAM,OAAO,GAAG,IAAI,iBAAE,CAAC,2BAA2B,EAAE,CAAC;QACrD,OAAO,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;QAC3B,MAAM,KAAK,GAA8B,EAAE,CAAC;QAC5C,KAAK,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,IAAI,IAAI,EAAE,CAAC,EAAE,CAAC;YACrD,MAAM,IAAI,GAAG,IAAI,iBAAE,CAAC,uBAAuB,EAAE,CAAC;YAC9C,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;YACnB,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;YACrB,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACrB,CAAC;QACD,OAAO,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;QAC3B,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACvB,CAAC;CACJ","sourcesContent":["/**\n * ESPHome voice satellites — the fourth transport, next to the UDP server (`voiceServer.ts`) and the\n * Wyoming endpoint (`wyoming.ts`).\n *\n * Unlike those two, this one is a **client**: an ESPHome voice satellite is a *server* that waits on\n * TCP 6053 for the home-automation controller to connect and drive it. We therefore dial out to each\n * configured device and play the role Home Assistant normally plays. That covers the ThirdReality\n * Voice & Music Assistant (Dev Edition), the Home Assistant Voice PE and any box running\n * OHF-Voice/linux-voice-assistant.\n *\n * Flow for one utterance (verified against the firmware's `src/satellite/Satellite.cpp`):\n *\n * device → VoiceAssistantRequest{start, wake_word_phrase} wake word fired on the device\n * we → VoiceAssistantResponse{port:0} 0 = audio over the API, no UDP\n * we → RUN_START, WAKE_WORD_END, STT_START, STT_VAD_START\n * device → VoiceAssistantAudio … 16 kHz mono s16le, *until told to stop*\n * we → STT_VAD_END ← the device has no VAD of its own\n * we → STT_END{text}, INTENT_START, INTENT_END, TTS_START{text}, TTS_END{url}, RUN_END\n * device → fetches the URL over HTTP, plays it, VoiceAssistantAnnounceFinished\n *\n * Two consequences shape this file: end-of-speech detection is ours (`vad.ts`), and the spoken reply\n * has to be reachable over HTTP (`mediaServer.ts`) rather than streamed down the socket.\n *\n * The first one also makes the **dialog mode** possible ({@link EsphomeConnection.setDialog}): the device streams as\n * long as we do not end the utterance, so while nobody speaks the detector just starts over, and every reply asks the\n * device to open its microphone again (`continue_conversation`). Talking goes on without a wake word until the mode\n * is switched off, the device is stopped, or nobody said anything for {@link DIALOG_IDLE_MS}.\n */\nimport * as net from 'node:net';\nimport {\n pb,\n encode,\n decode,\n type PbMessage,\n type AuthenticationResponse,\n type DeviceInfoResponse,\n type HelloResponse,\n type VoiceAssistantAnnounceFinished,\n type VoiceAssistantAudio,\n type VoiceAssistantConfigurationResponse,\n type VoiceAssistantEventData,\n type VoiceAssistantRequestMsg,\n} from './esphomeProto';\nimport { EntityRegistry, isEntityStateMessage, isListEntityMessage, type EsphomeEntity } from './esphomeEntities';\nimport { SpeechDetector, type CaptureEnd, type Bytes, type VadReport } from './vad';\nimport { prepareForStt } from './speechAudio';\nimport { chooseReplyFormat, encodeReply, type ExternalEncoder, type ReplyFormat } from './replyFormat';\nimport { levelProfile, type DiscardedCapture, type DiscardReason } from './captures';\nimport type { SttEngine } from './stt';\nimport type { TtsEngine } from './tts';\nimport type { SatelliteState } from './protocol';\nimport { confirmationTone } from './tone';\n\n/** `VoiceAssistantEvent` (api.proto) — the subset we emit. */\nconst EVENT = {\n ERROR: 0,\n RUN_START: 1,\n RUN_END: 2,\n STT_START: 3,\n STT_END: 4,\n INTENT_START: 5,\n INTENT_END: 6,\n TTS_START: 7,\n TTS_END: 8,\n WAKE_WORD_END: 10,\n STT_VAD_START: 11,\n STT_VAD_END: 12,\n} as const;\n\n/** `SubscribeVoiceAssistantRequest.flags`: audio over the API socket instead of a UDP side channel. */\nconst SUBSCRIBE_API_AUDIO = 1;\n/** ESPHome voice satellites always capture at 16 kHz mono 16-bit. */\nconst MIC_SAMPLE_RATE = 16000;\n/**\n * Leading audio to keep out of the end-of-speech analysis. These devices acknowledge the wake word\n * with a chirp through their own speaker and hear it back on their own microphone, far louder than\n * the speech that follows. Without this the chirp alone satisfies the detector's speech test — so\n * `sawSpeech` stops meaning \"somebody said something\" and a false wake is billed to STT — and it\n * drags the noise floor up with it.\n *\n * Measured over four captures from a ThirdReality Voice & Music Assistant (RMS per 50 ms, remarkably\n * repeatable across all four):\n *\n * ms 0 50 100 150 200 250 300 350 400 450 500 550 600\n * rms ~20 ~900 ~11k ~19k ~14k ~1.3k ~990 ~780 ~610 ~370 ~330 ~165 ~180\n *\n * so the chirp is still above the gate at 500 ms and only clears it around 550–600. 600 ms is the\n * smallest value that rejects a chirp-only wake while still detecting the speech in every one of the\n * four captures, with no change to when the utterance closes. Only the analysis skips it: STT gets the audio\n * from 400 ms before the detected speech (`speechAudio.ts`), so a speaker who starts inside this window loses\n * nothing but a late gate open.\n */\nconst WAKE_CHIRP_MS = 600;\n/** Default API port of an ESPHome device. */\nconst DEFAULT_PORT = 6053;\n/** Keepalive interval; two missed replies count as a dead link. */\nconst PING_INTERVAL_MS = 20_000;\n/** Wait between reconnect attempts. Devices reboot, and a Wi-Fi speaker drops off now and then. */\nconst RECONNECT_MS = 10_000;\n/** Give up on a pipeline that produced no audio at all (device wedged mid-stream). */\nconst PIPELINE_TIMEOUT_MS = 30_000;\n/** How long we wait for the device to report that it finished playing before forcing it back to idle. */\nconst PLAYBACK_TIMEOUT_MS = 60_000;\n/**\n * Default lowest RMS that counts as speech (the noise floor can only raise the gate above it). Fits the\n * ThirdReality speaker; quieter microphones get their own value per device ({@link EsphomeDevice.speechLevel}).\n */\nexport const DEFAULT_SPEECH_LEVEL = 250;\n/**\n * Close the microphone when nobody has started speaking this long after the wake word. Without it a false wake\n * kept the stream open for the full 12 s cap: on a ThirdReality speaker with a custom wake word that was ten\n * times in one night, each 12.6 s of an open mic (and of music ducked, if any played).\n */\nconst NO_SPEECH_MS = 5000;\n/** The same after a follow-up question re-opened the mic: the user may need a moment to think. */\nconst NO_SPEECH_FOLLOW_UP_MS = 8000;\n/** Silence that ends an utterance when the configuration leaves it empty. */\nconst DEFAULT_SILENCE_MS = 900;\n/**\n * After this much speech a pause may be {@link LONG_PAUSE_FACTOR} times as long before the utterance ends: whoever\n * talks that long is dictating a request and pauses to think, while \"Licht an\" should still close quickly. Field\n * report 2026-11-03: \"Я хочу, чтоб ты создал задачу, чтобы утром говорить мне…\" was cut off right there.\n */\nconst LONG_REQUEST_MS = 2500;\nconst LONG_PAUSE_FACTOR = 1.5;\n/**\n * Sound needed before a loud moment counts as speech. On vitanova (2026-11-03) a single 100 ms sound at RMS 197\n * after a false wake opened the gate (threshold 150), and Whisper made \"и все просят.\" of the amplified silence\n * around it. The shortest real answer, \"да\", lasts about 250 ms.\n */\nconst MIN_SPEECH_MS = 200;\n/**\n * Close the utterance when the device stops sending audio without ending the stream. Seen on a ThirdReality\n * speaker: the audio stopped after 2.7 s, and the satellite showed \"listening\" for the 30 s of\n * {@link PIPELINE_TIMEOUT_MS}. A device streams every few tens of ms while the mic is open.\n */\nconst STREAM_STALL_MS = 2000;\n/** The same before the first audio arrives: a device needs a moment to open the microphone. */\nconst STREAM_START_MS = 5000;\n/** How often a running capture checks for a stalled stream. */\nconst STALL_CHECK_MS = 250;\n/** Silence threshold as a share of the speech threshold — keeps the default pair 250/150. */\nconst SILENCE_SHARE = 0.6;\n/**\n * The firmware answers an ERROR event with a stop request of its own (`signal_stop_`). One arriving this soon after\n * our error belongs to it and needs no reply — the run is already over.\n */\nconst ERROR_ECHO_MS = 2000;\n/**\n * What ends a run that produced no request. Home Assistant sends the same code when the speech recognition finds no\n * text, and the Voice PE firmware deliberately plays no error sound for it.\n */\nconst NO_TEXT_ERROR = { code: 'stt-no-text-recognized', message: 'No text recognized' };\n/**\n * A dropped utterance whose loudest frame reached this share of the speech threshold was probably a voice\n * that was too quiet, not an empty room — worth telling the user where to lower the threshold.\n */\nconst QUIET_VOICE_SHARE = 0.4;\n/**\n * Event entity of a satellite with a screen: the user answered the open question by touch, event type `yes` or `no`.\n * Pressing it is the same as saying \"yes\"/\"no\" into the open microphone — no speech recognition to get it wrong\n * (a German \"Ja\" came back as \"Я\" once).\n */\nconst CONFIRM_ENTITY = 'confirm_answer';\n/** Select entity of a satellite with a screen: the language of the date and the hints it shows. */\nconst DISPLAY_LANGUAGE_ENTITY = 'display_language';\n/**\n * After a reply that asks something: how long, beyond the reply's own length, the question stays open — the next\n * pipeline the device starts answers it, and so does a yes/no button press. Answering it (by voice or button) closes\n * it earlier. The wake word phrase cannot tell a follow-up from a new request: ESPHome sends the phrase of the last\n * wake word with every request, the follow-up microphone included (field report 2026-11-05).\n */\nconst QUESTION_OPEN_MS = 30_000;\n/**\n * A button press still answers the question this long after the follow-up microphone closed: the firmware may stop\n * the microphone on the press before it reports which button it was.\n */\nconst CONFIRM_GRACE_MS = 3000;\n/**\n * After a button answer: a follow-up microphone the device opens this soon was asked for by the question the button\n * already answered, and is closed at once (unless our reply asked something again).\n */\nconst IGNORE_FOLLOW_UP_MS = 15_000;\n/**\n * Dialog mode: nobody spoke for this much audio — the detector starts over on the audio that keeps coming (no new pipeline,\n * the device does not notice), so its noise floor, its limits and the memory of the recording stay those of a request.\n */\nconst DIALOG_WINDOW_MS = 10_000;\n/** Dialog mode: the longest request. */\nconst DIALOG_MAX_SPEECH_MS = 20_000;\n/** Dialog mode ends by itself when nothing was said for this long. */\nexport const DIALOG_IDLE_MS = 5 * 60_000;\n/** How often the dialog mode checks whether it ran idle. */\nconst DIALOG_CHECK_MS = 5000;\n/**\n * Dialog mode, nothing recognised (a cough, the TV): a reply of this much silence ends the run and makes the device\n * open its microphone again — an ESPHome device does that only after a reply has played.\n */\nconst DIALOG_PAUSE_MS = 250;\n/**\n * Dialog mode: once its reply has played, the device opens the microphone again by itself (ThirdReality after its\n * \"continue conversation delay\", 0.5 s by default). Nothing within this time: it does not listen, and the mode goes off\n * — its stop word or a tap ended the reply, or it lost the flag.\n */\nconst DIALOG_REOPEN_MS = 6000;\n/** A reply that ended this much earlier than its length was cut on the device. */\nconst REPLY_CUT_MS = 500;\n\n/** \"Yes\" and \"no\" as a button answer is passed on: the words of the satellite's language, which pi-agent also takes. */\nconst YES_NO: Record<string, [yes: string, no: string]> = {\n en: ['Yes', 'No'],\n de: ['Ja', 'Nein'],\n ru: ['Да', 'Нет'],\n pt: ['Sim', 'Não'],\n nl: ['Ja', 'Nee'],\n fr: ['Oui', 'Non'],\n it: ['Sì', 'No'],\n es: ['Sí', 'No'],\n pl: ['Tak', 'Nie'],\n uk: ['Так', 'Ні'],\n zh: ['是', '不'],\n};\n\n/** The word a yes/no button stands for in `language` (ISO 639-1, `zh-cn` too); English for an unknown one. */\nexport function yesNoWord(language: string, yes: boolean): string {\n const base = (language || 'en').trim().toLowerCase().split(/[-_]/)[0];\n return (YES_NO[base] ?? YES_NO.en)[yes ? 0 : 1];\n}\n\n/** The event type of a {@link CONFIRM_ENTITY} as yes (true) or no (false); null for anything else. */\nexport function confirmAnswerOf(eventType: unknown): boolean | null {\n const type = typeof eventType === 'string' ? eventType.trim().toLowerCase() : '';\n if (type === 'yes' || type === 'confirm') {\n return true;\n }\n if (type === 'no' || type === 'cancel') {\n return false;\n }\n return null;\n}\n\n/**\n * Names of the adapter's languages in that language, for a display-language select. `Intl.DisplayNames` covers the\n * rest, but a Node.js built with only English ICU data knows no \"Deutsch\" or \"Русский\".\n */\nconst NATIVE_LANGUAGE_NAMES: Record<string, string> = {\n en: 'english',\n de: 'deutsch',\n ru: 'русский',\n pt: 'português',\n nl: 'nederlands',\n fr: 'français',\n it: 'italiano',\n es: 'español',\n pl: 'polski',\n uk: 'українська',\n zh: '中文',\n};\n\n/**\n * The option of a display-language select that means `language`: its name in that language (\"Deutsch\"), in English\n * (\"German\") or its code (\"de\", \"de-DE\"), case ignored. Null when the device offers none of them.\n */\nexport function displayLanguageOption(options: string[], language: string): string | null {\n const code = (language || '').trim().toLowerCase();\n const base = code.split(/[-_]/)[0];\n if (!base) {\n return null;\n }\n const names = new Set<string>([code, base]);\n if (NATIVE_LANGUAGE_NAMES[base]) {\n names.add(NATIVE_LANGUAGE_NAMES[base]);\n }\n for (const locale of [base, 'en']) {\n try {\n const name = new Intl.DisplayNames([locale], { type: 'language' }).of(base);\n if (name) {\n names.add(name.toLocaleLowerCase(locale));\n }\n } catch {\n /* not a language code Intl knows */\n }\n }\n const norm = (option: string): string => option.trim().toLocaleLowerCase();\n return (\n options.find(o => names.has(norm(o))) ??\n options.find(o => norm(o).split(/[-_]/)[0] === base && /^[a-z]{2,3}([-_][a-z0-9]+)?$/.test(norm(o))) ??\n null\n );\n}\n\n/** The configured speech threshold of a device, or 0 for the default. Table cells may arrive as strings. */\nexport function speechLevelOf(device: EsphomeDevice): number {\n const level = Math.round(Number(device.speechLevel));\n return Number.isFinite(level) && level > 0 ? level : 0;\n}\n\n/** How a configured device is identified: `ip`, or `ip:port` when it does not use the default port. */\nexport function esphomeAddress(device: Pick<EsphomeDevice, 'ip' | 'port'>): string {\n const ip = (device.ip || '').trim().toLowerCase();\n const port = Number(device.port) || DEFAULT_PORT;\n return port === DEFAULT_PORT ? ip : `${ip}:${port}`;\n}\n\nexport interface EsphomeDevice {\n /** Host name or IP of the satellite. */\n ip: string;\n /** API port; empty/0 → 6053. */\n port?: number | string;\n /** API password, if one is configured on the device. */\n password?: string;\n /** Room this satellite belongs to (drives `satellites.<room>.*` and the answer context). */\n room?: string;\n /**\n * Lowest RMS that counts as speech on this device (empty/0 → {@link DEFAULT_SPEECH_LEVEL}). Microphone\n * levels differ a lot: a ThirdReality speaker hears normal speech at RMS 350–470, a phone running a\n * satellite app at under 200, so one fixed floor cannot fit both.\n */\n speechLevel?: number | string | null;\n}\n\nexport interface EsphomeSatellitesOptions {\n devices: EsphomeDevice[];\n /** ISO-639-1 language hint for STT/TTS ('' = auto/provider default). */\n language: string;\n stt: SttEngine;\n tts: TtsEngine;\n /**\n * Produce the assistant reply for a transcribed utterance. `audioMs` is the length of the recording,\n * `vad` what the voice activity detection made of it (both for the request journal). An answer given with the\n * device's yes/no button ({@link CONFIRM_ENTITY}) comes as the yes or no word, with `button` and no recording.\n */\n answer: (\n question: string,\n ctx: {\n device: string;\n room: string;\n /** Wake word of the recording; '' = the mic was re-opened for a follow-up; absent for a button. */\n wakeWord?: string;\n sttMs?: number;\n audioMs?: number;\n vad?: VadReport;\n button?: 'yes' | 'no';\n },\n ) => Promise<string>;\n /** The reply was synthesised: how long that took and how long it plays (for the request journal). */\n onSpoken?: (device: string, info: { ms: number; audioMs: number }) => void;\n /** Optional STT vocabulary hints (device/room names) to bias recognition; re-read per utterance. */\n getHints?: () => string[] | Promise<string[]>;\n /** Where spoken replies are published for the device to fetch. */\n media: MediaHost;\n /**\n * Host the device should call back on. Empty → the local address of our socket to that device,\n * which is automatically the right interface on a multi-homed host.\n */\n mediaHost?: string;\n /** Silence that ends an utterance, in ms ('' / 0 → the detector default). */\n silenceMs?: number;\n log: ioBroker.Logger;\n /**\n * Notified on every satellite state transition (idle/listening/processing/speaking/offline). `host` is the\n * configured address (`ip`, or `ip:port` for another port than 6053), so the adapter can tell which table row\n * a satellite belongs to.\n */\n onStatus?: (device: string, room: string, state: SatelliteState | 'offline', host: string) => void;\n /**\n * Writes replies as MP3 or Opus, for a media player that takes nothing else (ffmpeg in the adapter). Without it\n * such a device gets FLAC or WAV if it lists one of them, and a warning otherwise.\n */\n encodeAudio?: ExternalEncoder;\n /** Notified with the device's wake-word configuration, on connect and after every change. */\n onWakeWords?: (device: string, room: string, config: WakeWordConfig) => void;\n /** Notified once per connect with everything the device exposes besides the voice pipeline. */\n onEntities?: (device: string, room: string, entities: EsphomeEntity[]) => void;\n /** Notified whenever one of those entities changes (and once per entity right after connecting). */\n onEntityState?: (device: string, room: string, entity: EsphomeEntity) => void;\n /** True when the reply asks something back, so the device should re-open its mic without a wake word. */\n expectsFollowUp?: (answer: string, device: string) => boolean;\n /**\n * A recording that never became a request: dropped as silence, or returned empty by the speech recognition.\n * For diagnosis (the adapter stores it when asked to); absent → nothing is kept.\n */\n onDiscarded?: (capture: DiscardedCapture) => void;\n /**\n * The dialog mode of a satellite changed — also by itself: the device was stopped, went offline, nothing was said\n * for {@link DIALOG_IDLE_MS}, or its pipeline failed.\n */\n onDialog?: (device: string, room: string, on: boolean, reason: DialogChange) => void;\n /**\n * Custom wake words to offer the devices, re-read for every configuration request. The device lists\n * them next to its own and downloads one (from the media server) only when it is selected.\n */\n externalWakeWords?: () => ExternalWakeWordOffer[];\n}\n\n/** Why the dialog mode of a satellite changed. */\nexport type DialogChange = 'command' | 'idle' | 'stop' | 'no-listen' | 'offline' | 'error';\n\n/** A custom wake word as offered to the devices; the files are on the media server under `path`. */\nexport interface ExternalWakeWordOffer {\n id: string;\n phrase: string;\n languages: string[];\n /** Size of the `.tflite` in bytes. */\n size: number;\n /** SHA-256 of the `.tflite`, lower-case hex. */\n sha256: string;\n /** URL path of the JSON config, e.g. `/wakeword/hey_hannah_1a2b3c4d.json`; the model sits next to it. */\n path: string;\n}\n\n/** What a device reports about its wake words: what the firmware ships plus the custom ones we offered. */\nexport interface WakeWordConfig {\n /** Ids currently listening, e.g. `['okay_nabu']`. */\n active: string[];\n /** Every wake word the device can use, with the spoken phrase and the languages it was trained on. */\n available: { id: string; phrase: string; languages: string[] }[];\n /** How many may listen at once — 2 on the ThirdReality speaker, which has a sensitivity per slot. */\n max: number;\n}\n\n/** `VoiceAssistantTimerEvent` in api.proto. */\nexport const TIMER_EVENT = { started: 0, updated: 1, cancelled: 2, finished: 3 } as const;\n\n/** One assistant timer, as the device wants to hear about it. */\nexport interface TimerEvent {\n type: keyof typeof TIMER_EVENT;\n id: string;\n name: string;\n totalSeconds: number;\n secondsLeft: number;\n /** False once it has finished or been cancelled — the device clears its ring on that. */\n active: boolean;\n}\n\n/** The slice of `MediaServer` this module needs (kept narrow so tests can pass a stub). */\nexport interface MediaHost {\n port: number;\n publish(body: Buffer, contentType?: string, ttlMs?: number): string;\n}\n\n/**\n * All configured ESPHome satellites. Owns one connection per device and offers the same surface the\n * adapter already uses for the UDP server: `devices()` and `announce()`.\n */\nexport class EsphomeSatellites {\n private readonly connections: EsphomeConnection[] = [];\n\n constructor(private readonly opts: EsphomeSatellitesOptions) {}\n\n async start(): Promise<void> {\n for (const device of this.opts.devices) {\n if (!device.ip?.trim()) {\n continue;\n }\n const connection = new EsphomeConnection(device, this.opts);\n this.connections.push(connection);\n connection.start();\n }\n if (!this.connections.length) {\n this.opts.log.warn('ESPHome satellites enabled, but no device addresses are configured.');\n }\n return Promise.resolve();\n }\n\n async stop(): Promise<void> {\n await Promise.all(this.connections.map(c => c.stop()));\n this.connections.length = 0;\n }\n\n /** Device names of the satellites currently connected. */\n devices(): string[] {\n return this.connections.filter(c => c.online).map(c => c.deviceName);\n }\n\n /** Wake-word configuration of one connected satellite, or null if it is unknown/offline. */\n wakeWords(device: string): WakeWordConfig | null {\n return this.connections.find(c => c.online && c.deviceName === device)?.wakeWordConfig ?? null;\n }\n\n /**\n * Choose which wake words listen on one satellite. Ids come from {@link WakeWordConfig.available};\n * the device stores the selection itself, so it survives a restart of the adapter.\n */\n setWakeWords(device: string, ids: string[]): boolean {\n const target = this.connections.find(c => c.online && c.deviceName === device);\n if (!target) {\n return false;\n }\n target.setWakeWords(ids);\n return true;\n }\n\n /**\n * Offer the current custom wake words to every connected satellite again — after one was uploaded\n * or deleted. Each device answers with its new configuration (→ `onWakeWords`).\n */\n refreshWakeWords(): number {\n const online = this.connections.filter(c => c.online);\n online.forEach(c => c.requestWakeWordConfig());\n return online.length;\n }\n\n /** Everything one satellite exposes besides the voice pipeline (gain, noise suppression, …). */\n entities(device: string): EsphomeEntity[] {\n return this.connections.find(c => c.online && c.deviceName === device)?.entities.list() ?? [];\n }\n\n /**\n * Write one of those entities. Returns false when the satellite is offline, the entity is unknown\n * or read-only, or the value is not one the device accepts.\n */\n setEntity(device: string, objectId: string, value: unknown): boolean {\n const target = this.connections.find(c => c.online && c.deviceName === device);\n return target ? target.setEntity(objectId, value) : false;\n }\n\n /**\n * Absolute URL of a path on our media server (a live stream) with a host `device` can reach — the local end of\n * its connection unless a media host is configured. null when it is offline.\n */\n mediaUrl(device: string, path: string): string | null {\n const target = this.connections.find(c => c.online && c.deviceName === device);\n return target ? target.mediaUrl(path) : null;\n }\n\n /**\n * Switch the dialog mode of one satellite: after every reply it listens again without a wake word. Switched on\n * while the satellite is idle, `open` is played and the microphone opens after it (a request in progress re-opens\n * it with its reply). False when the satellite is not connected.\n */\n setDialog(device: string, on: boolean, open?: { pcm: Buffer; sampleRate: number }): boolean {\n const target = this.connections.find(c => c.online && c.deviceName === device);\n if (!target) {\n return false;\n }\n target.setDialog(on, 'command', open);\n return true;\n }\n\n /** Whether a satellite is in dialog mode. */\n dialog(device: string): boolean {\n return !!this.connections.find(c => c.online && c.deviceName === device)?.dialog;\n }\n\n /**\n * Mirror an assistant timer onto the satellites so they can show it on their own LED ring and ring\n * it themselves. `device` null broadcasts. Returns how many devices were told.\n */\n timerEvent(device: string | null, event: TimerEvent): number {\n const targets = this.connections.filter(c => c.online && (!device || c.deviceName === device));\n targets.forEach(c => c.sendTimerEvent(event));\n return targets.length;\n }\n\n /**\n * Play a ready PCM buffer on one satellite (by device name) or all of them. Returns how many\n * devices it was handed to.\n *\n * With `startConversation` the device opens its microphone as soon as the clip has played, without\n * a wake word — that is how a question gets its answer (see `PendingQuestions`).\n */\n async announce(device: string | null, pcm: Buffer, sampleRate: number, startConversation = false): Promise<number> {\n const targets = this.connections.filter(c => c.online && (!device || c.deviceName === device));\n if (!targets.length) {\n return 0;\n }\n await Promise.all(\n targets.map(c =>\n c\n .announce(pcm, sampleRate, startConversation)\n .catch(e => this.opts.log.warn(`announce to ${c.deviceName} failed: ${(e as Error).message}`)),\n ),\n );\n return targets.length;\n }\n}\n\n/** State of the utterance currently being captured. */\ninterface Capture {\n chunks: Buffer[];\n detector: SpeechDetector;\n conversationId: string;\n /** Wake word that opened this capture; '' when the mic was re-opened for a follow-up/question. */\n wakeWord: string;\n /** The mic was re-opened for a reply that asked something: a yes/no button press answers it too. */\n answersQuestion: boolean;\n timer: NodeJS.Timeout;\n /** Watches for a device that stops sending audio without ending the stream. */\n stallCheck: NodeJS.Timeout;\n startedAt: number;\n /** When the last audio arrived; 0 = none yet. */\n lastAudioAt: number;\n closed: boolean;\n /** Opened in dialog mode: while nobody speaks, the detector starts over instead of ending the run. */\n dialog: boolean;\n}\n\n/** One satellite: socket lifecycle, handshake, and the voice pipeline. */\nclass EsphomeConnection {\n /** Device name as reported by the device; falls back to its address until the handshake answers. */\n deviceName: string;\n online = false;\n /** Last wake-word configuration the device reported; null until the handshake answers. */\n wakeWordConfig: WakeWordConfig | null = null;\n /**\n * One entry per configuration request in flight, in send order (the device answers each one, in\n * order): the ids a preceding `SetConfiguration` asked for, or null. The read-back is the only\n * failure signal the device gives.\n */\n private configChecks: (string[] | null)[] = [];\n /** Everything else the device exposes — rebuilt from scratch on every reconnect. */\n readonly entities = new EntityRegistry();\n\n private readonly host: string;\n private readonly port: number;\n private readonly room: string;\n\n private socket: net.Socket | null = null;\n private rx: Bytes = Buffer.alloc(0);\n private pingTimer: NodeJS.Timeout | null = null;\n private reconnectTimer: NodeJS.Timeout | null = null;\n private missedPings = 0;\n private stopping = false;\n private capture: Capture | null = null;\n private playbackTimer: NodeJS.Timeout | null = null;\n private readonly password: string;\n /** Configured speech threshold, 0 = {@link DEFAULT_SPEECH_LEVEL}. */\n private readonly speechLevel: number;\n /** `ip`, or `ip:port` for another port than the default — how the adapter recognises the table row. */\n private readonly address: string;\n /** The device's friendly name, for entities without a name of their own. */\n private friendlyName = '';\n /**\n * Number of the current pipeline run. A run whose number is no longer current was ended — the device asked to\n * stop, started over, or went away — and whatever STT, answer or TTS is still in flight for it stays silent.\n */\n private run = 0;\n /** From RUN_START until we sent RUN_END: the device waits for that RUN_END. */\n private runOpen = false;\n /** When we last sent an ERROR event (see {@link ERROR_ECHO_MS}). */\n private errorSentAt = 0;\n /** The reply format last reported in the log, to log it again only when it changes. */\n private loggedFormat = '';\n /**\n * The last reply asked something (`continue_conversation`, or an announcement with `start_conversation`): until\n * when the next request of the device, or a yes/no button press, answers it. 0 = no open question.\n */\n private questionUntil = 0;\n /** After a button answer: until when a follow-up microphone is the stale one of the answered question. */\n private ignoreFollowUpUntil = 0;\n /** When a yes/no button press last answered a question. */\n private buttonAt = 0;\n /** When the device last asked to stop (`VoiceAssistantRequest{start:false}`). */\n private stoppedAt = 0;\n /** The display language was compared with ours since the last connect. */\n private displayLanguageChecked = false;\n /** Dialog mode: every reply opens the microphone again, see {@link setDialog}. */\n private dialogOn = false;\n /** Dialog mode: when something was last recognised (or the mode was switched on). */\n private dialogHeardAt = 0;\n private dialogTimer: NodeJS.Timeout | null = null;\n /** Dialog mode: when the last reply went out (0 = none pending) and how long it is. */\n private dialogReplyAt = 0;\n private dialogReplyMs = 0;\n /** Dialog mode: waits for the device to listen again after its reply, see {@link onReplyPlayed}. */\n private dialogReopenTimer: NodeJS.Timeout | null = null;\n\n constructor(\n device: EsphomeDevice,\n private readonly opts: EsphomeSatellitesOptions,\n ) {\n this.host = device.ip.trim();\n this.port = Number(device.port) || DEFAULT_PORT;\n this.room = (device.room || '').trim();\n this.password = device.password || '';\n this.speechLevel = speechLevelOf(device);\n this.address = esphomeAddress(device);\n this.deviceName = this.host;\n }\n\n // ── lifecycle ───────────────────────────────────────────────────────────────────────────────────\n\n start(): void {\n this.connect();\n }\n\n async stop(): Promise<void> {\n this.stopping = true;\n this.clearTimers();\n this.abortCapture();\n const socket = this.socket;\n this.socket = null;\n if (socket) {\n try {\n socket.write(encode(new pb.DisconnectRequest()));\n } catch {\n /* socket already gone — nothing to say goodbye on */\n }\n socket.destroy();\n }\n this.setOffline();\n return Promise.resolve();\n }\n\n private connect(): void {\n if (this.stopping) {\n return;\n }\n this.rx = Buffer.alloc(0);\n this.missedPings = 0;\n // The device re-announces everything after a reconnect, and the keys are not stable across\n // reboots, so starting from a clean slate is the only safe option.\n this.entities.clear();\n this.configChecks = [];\n this.displayLanguageChecked = false;\n\n const socket = net.createConnection({ host: this.host, port: this.port }, () => {\n this.opts.log.debug(`ESPHome ${this.host}:${this.port} connected`);\n this.handshake();\n });\n this.socket = socket;\n socket.setNoDelay(true);\n\n socket.on('data', data => this.onData(data));\n socket.on('error', e => {\n // A satellite that is switched off is normal, so this is not an error-level event.\n this.opts.log.debug(`ESPHome ${this.host}: ${e.message}`);\n });\n socket.on('close', () => {\n if (this.socket === socket) {\n this.socket = null;\n this.onDisconnected();\n }\n });\n }\n\n private onDisconnected(): void {\n this.clearTimers();\n this.abortCapture();\n // A reply still being worked out must not land on the next connection, in the middle of another run.\n this.run++;\n this.runOpen = false;\n this.questionUntil = 0;\n this.ignoreFollowUpUntil = 0;\n this.setDialog(false, 'offline');\n if (this.online) {\n this.opts.log.info(`ESPHome satellite offline: ${this.deviceName}`);\n }\n this.setOffline();\n this.scheduleReconnect();\n }\n\n private scheduleReconnect(): void {\n if (this.stopping || this.reconnectTimer) {\n return;\n }\n this.reconnectTimer = setTimeout(() => {\n this.reconnectTimer = null;\n this.connect();\n }, RECONNECT_MS);\n this.reconnectTimer.unref();\n }\n\n private clearTimers(): void {\n if (this.pingTimer) {\n clearInterval(this.pingTimer);\n this.pingTimer = null;\n }\n if (this.reconnectTimer) {\n clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n if (this.playbackTimer) {\n clearTimeout(this.playbackTimer);\n this.playbackTimer = null;\n }\n if (this.dialogTimer) {\n clearInterval(this.dialogTimer);\n this.dialogTimer = null;\n }\n this.cancelDialogReopen();\n }\n\n private setOffline(): void {\n if (this.online) {\n this.online = false;\n this.opts.onStatus?.(this.deviceName, this.room, 'offline', this.address);\n }\n }\n\n private status(state: SatelliteState): void {\n this.opts.onStatus?.(this.deviceName, this.room, state, this.address);\n }\n\n // ── protocol plumbing ───────────────────────────────────────────────────────────────────────────\n\n private send(message: PbMessage): void {\n const socket = this.socket;\n if (!socket || socket.destroyed) {\n return;\n }\n try {\n socket.write(encode(message));\n } catch (e) {\n this.opts.log.debug(`ESPHome ${this.deviceName}: send failed — ${(e as Error).message}`);\n }\n }\n\n private onData(data: Buffer): void {\n this.rx = this.rx.length ? Buffer.concat([this.rx, data]) : data;\n let frames;\n try {\n ({ frames, rest: this.rx } = decode(this.rx));\n } catch (e) {\n this.opts.log.error(`ESPHome ${this.deviceName}: ${(e as Error).message}`);\n this.socket?.destroy();\n return;\n }\n for (const frame of frames) {\n if (frame.error) {\n this.opts.log.debug(`ESPHome ${this.deviceName}: cannot parse ${frame.name}`);\n continue;\n }\n if (!frame.name || !frame.message) {\n continue; // unknown id — already skipped by its declared length\n }\n try {\n this.onMessage(frame.name, frame.message);\n } catch (e) {\n this.opts.log.warn(\n `ESPHome ${this.deviceName}: ${frame.name} handler failed — ${(e as Error).message}`,\n );\n }\n }\n }\n\n private handshake(): void {\n const hello = new pb.HelloRequest();\n hello.setClientInfo('ioBroker.assistant');\n hello.setApiVersionMajor(1);\n hello.setApiVersionMinor(10);\n this.send(hello);\n\n const auth = new pb.AuthenticationRequest();\n auth.setPassword(this.password);\n this.send(auth);\n\n this.send(new pb.DeviceInfoRequest());\n // Ask for the entity announcements *before* subscribing to their states: a state message whose\n // entity we have not seen yet has nothing to attach to and is dropped.\n this.send(new pb.ListEntitiesRequest());\n this.send(new pb.SubscribeStatesRequest());\n\n const subscribe = new pb.SubscribeVoiceAssistantRequest();\n subscribe.setSubscribe(true);\n subscribe.setFlags(SUBSCRIBE_API_AUDIO);\n this.send(subscribe);\n\n this.requestWakeWordConfig();\n\n this.pingTimer = setInterval(() => {\n if (++this.missedPings > 2) {\n this.opts.log.info(`ESPHome ${this.deviceName}: no reply to keepalive — reconnecting`);\n this.socket?.destroy();\n return;\n }\n this.send(new pb.PingRequest());\n }, PING_INTERVAL_MS);\n this.pingTimer.unref();\n }\n\n private onMessage(name: string, message: unknown): void {\n switch (name) {\n case 'HelloResponse': {\n const hello = message as HelloResponse;\n this.opts.log.debug(\n `ESPHome ${this.host}: ${hello.getServerInfo()} (API ${hello.getApiVersionMajor()}.${hello.getApiVersionMinor()})`,\n );\n return;\n }\n\n case 'AuthenticationResponse':\n if ((message as AuthenticationResponse).getInvalidPassword()) {\n this.opts.log.error(\n `ESPHome ${this.host}: API password rejected — check the device's password in the settings.`,\n );\n this.socket?.destroy();\n }\n return;\n\n case 'DeviceInfoResponse': {\n const info = message as DeviceInfoResponse;\n this.deviceName = info.getName() || this.host;\n this.friendlyName = info.getFriendlyName?.() || info.getName() || '';\n this.online = true;\n this.opts.log.info(\n `ESPHome satellite online: ${this.deviceName} (${info.getModel()}) @ ${this.host}${this.room ? `, room ${this.room}` : ''}`,\n );\n this.status('idle');\n return;\n }\n\n case 'VoiceAssistantConfigurationResponse': {\n const config = message as VoiceAssistantConfigurationResponse;\n // A custom wake word the device already downloaded is listed twice: once from its own\n // model folder and once from our offer.\n const seen = new Set<string>();\n this.wakeWordConfig = {\n active: config.getActiveWakeWordsList(),\n available: config\n .getAvailableWakeWordsList()\n .map(w => ({\n id: w.getId(),\n phrase: w.getWakeWord(),\n languages: w.getTrainedLanguagesList(),\n }))\n .filter(w => !seen.has(w.id) && !!seen.add(w.id)),\n max: config.getMaxActiveWakeWords(),\n };\n const active = this.wakeWordConfig.active.join(', ') || '(none active)';\n const available = this.wakeWordConfig.available.map(w => w.id);\n this.opts.log.info(\n `ESPHome ${this.deviceName}: wake words ${active}${available.length ? ` (available: ${available.join(', ')})` : ''}`,\n );\n const requested = this.configChecks.shift();\n const missing = requested?.filter(id => !this.wakeWordConfig?.active.includes(id)) ?? [];\n if (missing.length) {\n // The device answers a model it cannot fetch or load with silence, not an error.\n this.opts.log.warn(\n `ESPHome ${this.deviceName}: could not activate wake word(s) ${missing.join(', ')}. ` +\n `For an uploaded wake word the device must reach ${this.mediaUrl('/')} and the model ` +\n `must be a microWakeWord .tflite.`,\n );\n }\n this.opts.onWakeWords?.(this.deviceName, this.room, this.wakeWordConfig);\n return;\n }\n\n case 'VoiceAssistantRequest':\n this.onPipelineRequest(message as VoiceAssistantRequestMsg);\n return;\n\n case 'VoiceAssistantAudio':\n this.onAudio(message as VoiceAssistantAudio);\n return;\n\n case 'VoiceAssistantAnnounceFinished':\n if (this.playbackTimer) {\n clearTimeout(this.playbackTimer);\n this.playbackTimer = null;\n }\n this.opts.log.debug(\n `ESPHome ${this.deviceName}: playback finished (success=${(message as VoiceAssistantAnnounceFinished).getSuccess()})`,\n );\n this.status('idle');\n this.onReplyPlayed();\n return;\n\n case 'PingRequest':\n this.send(new pb.PingResponse());\n return;\n\n case 'PingResponse':\n this.missedPings = 0;\n return;\n\n case 'GetTimeRequest': {\n // The device has no RTC and syncs its clock from us — its timer ring depends on it.\n const time = new pb.GetTimeResponse();\n time.setEpochSeconds(Math.floor(Date.now() / 1000));\n this.send(time);\n return;\n }\n\n case 'DisconnectRequest':\n this.send(new pb.DisconnectResponse());\n this.socket?.destroy();\n return;\n\n case 'ListEntitiesDoneResponse': {\n const list = this.entities.list();\n if (list.length) {\n this.opts.log.debug(\n `ESPHome ${this.deviceName}: ${list.length} entities — ${list.map(e => e.objectId).join(', ')}`,\n );\n }\n this.opts.onEntities?.(this.deviceName, this.room, list);\n return;\n }\n\n default:\n if (isListEntityMessage(name)) {\n this.entities.addFromAnnouncement(name, message, this.friendlyName);\n } else if (isEntityStateMessage(name)) {\n const entity = this.entities.applyState(name, message);\n if (entity) {\n this.opts.onEntityState?.(this.deviceName, this.room, entity);\n this.onEntityChange(entity);\n }\n }\n return;\n }\n }\n\n /** Entities of a satellite with a screen that take part in the conversation (see {@link CONFIRM_ENTITY}). */\n private onEntityChange(entity: EsphomeEntity): void {\n if (entity.objectId === CONFIRM_ENTITY && entity.kind === 'event') {\n this.onConfirmButton(entity.value);\n } else if (entity.objectId === DISPLAY_LANGUAGE_ENTITY && entity.kind === 'select') {\n // Once per connect, with the state the device reports on subscribing: a language the user picks on the\n // device afterwards stays until the next connect (a change of the voice language restarts the adapter).\n if (!this.displayLanguageChecked) {\n this.displayLanguageChecked = true;\n this.syncDisplayLanguage(entity);\n }\n }\n }\n\n /** Show the device's screen in the voice language, if it offers that language. */\n private syncDisplayLanguage(entity: EsphomeEntity): void {\n const language = this.opts.language;\n if (!language) {\n return;\n }\n const option = displayLanguageOption(entity.options ?? [], language);\n if (!option) {\n this.opts.log.debug(\n `ESPHome ${this.deviceName}: ${DISPLAY_LANGUAGE_ENTITY} has no option for \"${language}\" ` +\n `(${(entity.options ?? []).join(', ')})`,\n );\n return;\n }\n if (entity.value === option) {\n return;\n }\n const shown = typeof entity.value === 'string' ? entity.value : '?';\n this.opts.log.info(`ESPHome ${this.deviceName}: display language ${shown} → ${option}`);\n this.setEntity(DISPLAY_LANGUAGE_ENTITY, option);\n }\n\n /** Whether a yes/no button press now answers a question the last reply asked. */\n private questionOpen(): boolean {\n return !!this.capture?.answersQuestion || Date.now() < this.questionUntil;\n }\n\n /**\n * The user pressed yes or no on the device's screen. While a reply waits for an answer that is the answer: the\n * microphone opened for it is closed, the yes or no word goes on as the user's reply (pi-agent decides its\n * confirmation on it like on a spoken one), and the reply to that is announced on this device.\n */\n private onConfirmButton(eventType: unknown): void {\n const yes = confirmAnswerOf(eventType);\n if (yes === null) {\n this.opts.log.debug(\n `ESPHome ${this.deviceName}: ${CONFIRM_ENTITY} \"${String(eventType)}\" — not yes/no, ignored`,\n );\n return;\n }\n if (!this.questionOpen()) {\n this.opts.log.debug(\n `ESPHome ${this.deviceName}: ${CONFIRM_ENTITY} \"${yes ? 'yes' : 'no'}\" without an open question — ignored`,\n );\n return;\n }\n this.questionUntil = 0;\n // Pressed while the question still played: the device may open the microphone for it afterwards. Not if the\n // microphone is open already (our RUN_END closes it for good), and not if the device just stopped its\n // conversation itself — the firmware does that on the press, which also drops its continue flag.\n const micStillComes = !this.capture && Date.now() - this.stoppedAt >= CONFIRM_GRACE_MS;\n if (this.capture) {\n // A RUN_END while the microphone streams stops it and puts the device back to idle — without the error\n // display an empty recognition would end with.\n this.abortCapture();\n this.event(EVENT.RUN_END);\n }\n // Whatever is still in flight for the question stays silent; so does the follow-up microphone the device may\n // still open for it.\n const run = ++this.run;\n this.buttonAt = Date.now();\n this.ignoreFollowUpUntil = micStillComes ? Date.now() + IGNORE_FOLLOW_UP_MS : 0;\n void this.answerButton(yes, run);\n }\n\n /** Pass a button answer on and announce the reply (see {@link onConfirmButton}). */\n private async answerButton(yes: boolean, run: number): Promise<void> {\n const text = yesNoWord(this.opts.language, yes);\n this.opts.log.info(`ESPHome ${this.deviceName}: answered \"${text}\" with the button`);\n this.status('processing');\n try {\n const answer = (\n await this.opts.answer(text, { device: this.deviceName, room: this.room, button: yes ? 'yes' : 'no' })\n ).trim();\n if (run !== this.run) {\n return;\n }\n if (!answer) {\n this.status('idle');\n return;\n }\n const followUp = this.opts.expectsFollowUp?.(answer, this.deviceName) === true;\n const ttsStart = Date.now();\n const { pcm, sampleRate } = await this.opts.tts.synthesize(answer, this.opts.language);\n if (run !== this.run) {\n return;\n }\n this.opts.onSpoken?.(this.deviceName, {\n ms: Date.now() - ttsStart,\n audioMs: (pcm.length / 2 / sampleRate) * 1000,\n });\n await this.announce(pcm, sampleRate, followUp, answer);\n } catch (e) {\n this.opts.log.warn(`ESPHome ${this.deviceName}: answer to the button failed — ${(e as Error).message}`);\n if (run === this.run) {\n this.status('idle');\n }\n }\n }\n\n /** Write one of the device's entities. See {@link EsphomeSatellites.setEntity}. */\n setEntity(objectId: string, value: unknown): boolean {\n const message = this.entities.command(objectId, value);\n if (!message) {\n const entity = this.entities.get(objectId);\n const known = this.entities\n .list()\n .map(e => e.objectId)\n .join(', ');\n const options = entity?.options\n ? ` (one of: ${entity.options.join(', ')})`\n : entity?.kind === 'text'\n ? ` (${entity.minLength || 0}–${entity.maxLength ?? '∞'} bytes${entity.pattern ? `, pattern ${entity.pattern}` : ''})`\n : '';\n this.opts.log.warn(\n entity\n ? `ESPHome ${this.deviceName}: ${JSON.stringify(value)} is not a value \"${objectId}\" accepts${options}`\n : `ESPHome ${this.deviceName}: no entity \"${objectId}\" (have: ${known})`,\n );\n return false;\n }\n this.send(message);\n this.opts.log.debug(`ESPHome ${this.deviceName}: ${objectId} := ${JSON.stringify(value)}`);\n return true;\n }\n\n /** Push one assistant timer to the device so it can show and ring it itself. */\n sendTimerEvent(event: TimerEvent): void {\n const message = new pb.VoiceAssistantTimerEventResponse();\n message.setEventType(TIMER_EVENT[event.type]);\n message.setTimerId(event.id);\n message.setName(event.name);\n message.setTotalSeconds(Math.max(0, Math.round(event.totalSeconds)));\n message.setSecondsLeft(Math.max(0, Math.round(event.secondsLeft)));\n message.setIsActive(event.active);\n this.send(message);\n }\n\n // ── voice pipeline ──────────────────────────────────────────────────────────────────────────────\n\n private onPipelineRequest(request: VoiceAssistantRequestMsg): void {\n if (!request.getStart()) {\n this.onStopRequest();\n return;\n }\n if (this.capture) {\n this.opts.log.debug(`ESPHome ${this.deviceName}: pipeline already running — ignoring wake`);\n return;\n }\n this.cancelDialogReopen();\n const phrase = request.getWakeWordPhrase();\n if (Date.now() < this.ignoreFollowUpUntil) {\n // The microphone for the question a button already answered: close it at once. In this state the device\n // takes a RUN_END as \"stop the microphone\" and goes back to idle.\n this.ignoreFollowUpUntil = 0;\n this.opts.log.debug(`ESPHome ${this.deviceName}: follow-up of a question answered by button — closing it`);\n this.event(EVENT.RUN_END);\n return;\n }\n if (this.runOpen) {\n // The device started over while the last request was still being answered: that answer is not\n // wanted any more, and its events would land in the middle of the new run.\n this.opts.log.debug(`ESPHome ${this.deviceName}: new wake while answering — dropping the old reply`);\n }\n this.run++;\n // While a question is open the next request answers it. The phrase says nothing here: the follow-up\n // microphone carries the last wake word too. Should the user really have said the wake word, the utterance\n // is still the next one after the question — which is what pi-agent and askUser take as the answer anyway.\n const answersQuestion = Date.now() < this.questionUntil;\n // In dialog mode every microphone is the next turn: the phrase is the stale one of the last wake word.\n const dialog = this.dialogOn;\n const followUp = answersQuestion || !phrase || dialog;\n\n this.opts.log.debug(\n `ESPHome ${this.deviceName}: ${\n answersQuestion\n ? 'answer to the question'\n : dialog\n ? 'dialog'\n : followUp\n ? 'follow-up'\n : `wake \"${phrase}\"`\n }`,\n );\n\n const response = new pb.VoiceAssistantResponse();\n response.setPort(0); // 0 = stream the audio over this socket\n response.setError(false);\n this.send(response);\n\n const stallCheck = setInterval(() => this.checkStall(), STALL_CHECK_MS);\n stallCheck.unref();\n\n this.capture = {\n chunks: [],\n detector: this.speechDetector(followUp, dialog, WAKE_CHIRP_MS),\n conversationId: request.getConversationId(),\n wakeWord: followUp ? '' : phrase,\n answersQuestion,\n timer: this.pipelineTimer(dialog),\n stallCheck,\n startedAt: Date.now(),\n lastAudioAt: 0,\n closed: false,\n dialog,\n };\n\n this.status('listening');\n this.event(EVENT.RUN_START);\n if (!followUp) {\n this.event(EVENT.WAKE_WORD_END, { wake_word_phrase: phrase });\n }\n this.event(EVENT.STT_START);\n this.event(EVENT.STT_VAD_START);\n }\n\n /**\n * End-of-speech detection for one recording. `skipMs`: the wake chirp at its start.\n *\n * Microphone gain differs wildly between these devices, so fixed RMS levels do not travel: the levels are derived\n * from the room, once the chirp is out of the way. In dialog mode nobody may speak for a while — there the window\n * starts over (see {@link onAudio}) instead of the run ending, and a request may take longer.\n */\n private speechDetector(followUp: boolean, dialog: boolean, skipMs: number): SpeechDetector {\n const silenceMs = this.opts.silenceMs || DEFAULT_SILENCE_MS;\n return new SpeechDetector({\n sampleRate: MIC_SAMPLE_RATE,\n silenceMs,\n longSilenceMs: Math.round(silenceMs * LONG_PAUSE_FACTOR),\n longAfterMs: LONG_REQUEST_MS,\n skipMs,\n adaptive: true,\n startTimeoutMs: dialog ? 0 : followUp ? NO_SPEECH_FOLLOW_UP_MS : NO_SPEECH_MS,\n maxMs: dialog ? DIALOG_WINDOW_MS + DIALOG_MAX_SPEECH_MS : undefined,\n minStartLevel: this.speechLevel || DEFAULT_SPEECH_LEVEL,\n minEndLevel: Math.round((this.speechLevel || DEFAULT_SPEECH_LEVEL) * SILENCE_SHARE),\n minSpeechMs: MIN_SPEECH_MS,\n });\n }\n\n /** Last resort for a recording that never ends; in dialog mode per window. */\n private pipelineTimer(dialog: boolean): NodeJS.Timeout {\n const ms = dialog ? DIALOG_WINDOW_MS + DIALOG_MAX_SPEECH_MS + 5000 : PIPELINE_TIMEOUT_MS;\n const timer = setTimeout(() => {\n this.opts.log.warn(`ESPHome ${this.deviceName}: no end of speech within ${ms} ms`);\n void this.finishCapture('pipeline-timeout');\n }, ms);\n timer.unref();\n return timer;\n }\n\n /**\n * Dialog mode on or off. On: every reply asks the device to open its microphone again (`continue_conversation`),\n * and while nobody speaks the recording just goes on. Switched on while nothing runs, `open` is played as an\n * announcement that opens the microphone. Off: a microphone that hears nothing is closed now; a request being\n * answered closes it with its reply.\n */\n setDialog(on: boolean, reason: DialogChange, open?: { pcm: Buffer; sampleRate: number }): void {\n if (this.dialogOn === on) {\n return;\n }\n this.dialogOn = on;\n this.dialogHeardAt = Date.now();\n this.dialogReplyAt = 0;\n this.cancelDialogReopen();\n if (this.dialogTimer) {\n clearInterval(this.dialogTimer);\n this.dialogTimer = null;\n }\n const why =\n reason === 'idle'\n ? ` (nothing said for ${DIALOG_IDLE_MS / 60_000} min)`\n : reason === 'stop'\n ? ' (the device was stopped)'\n : reason === 'no-listen'\n ? ' (the device did not listen again after the reply)'\n : reason === 'offline'\n ? ' (offline)'\n : reason === 'error'\n ? ' (the voice pipeline failed)'\n : '';\n this.opts.log.info(`ESPHome ${this.deviceName}: dialog mode ${on ? 'on' : 'off'}${why}`);\n this.opts.onDialog?.(this.deviceName, this.room, on, reason);\n if (on) {\n this.dialogTimer = setInterval(() => this.checkDialogIdle(), DIALOG_CHECK_MS);\n this.dialogTimer.unref();\n if (open && this.online && !this.capture && !this.runOpen) {\n this.noteDialogReply((open.pcm.length / 2 / open.sampleRate) * 1000);\n void this.announce(open.pcm, open.sampleRate, true, '', false).catch(e =>\n this.opts.log.warn(\n `ESPHome ${this.deviceName}: opening the microphone failed — ${(e as Error).message}`,\n ),\n );\n }\n return;\n }\n const capture = this.capture;\n if (capture?.dialog && !capture.detector.hearing) {\n void this.finishCapture('no-speech'); // nobody talks: close the microphone now\n }\n }\n\n get dialog(): boolean {\n return this.dialogOn;\n }\n\n /** Dialog mode: switch it off when nothing was said for a long time — but not while somebody speaks or is answered. */\n private checkDialogIdle(): void {\n if (!this.dialogOn || Date.now() - this.dialogHeardAt < DIALOG_IDLE_MS) {\n return;\n }\n const capture = this.capture;\n if (capture ? capture.detector.hearing : this.runOpen) {\n return;\n }\n this.setDialog(false, 'idle');\n }\n\n /** Dialog mode: a reply went out after which the device should listen again. */\n private noteDialogReply(ms: number): void {\n if (this.dialogOn) {\n this.dialogReplyAt = Date.now();\n this.dialogReplyMs = ms;\n }\n }\n\n /**\n * Dialog mode: the device reports that its reply has played (or was stopped). It should open the microphone again\n * now; one that does not — its stop word or a tap ended the reply, or it dropped the conversation flag — would\n * leave the mode on while nobody listens. A wake word during the reply starts a new run in time and keeps it.\n */\n private onReplyPlayed(): void {\n if (!this.dialogOn || !this.dialogReplyAt || this.capture) {\n return;\n }\n const playedMs = Date.now() - this.dialogReplyAt;\n const replyMs = this.dialogReplyMs;\n this.dialogReplyAt = 0;\n this.cancelDialogReopen();\n this.dialogReopenTimer = setTimeout(() => {\n this.dialogReopenTimer = null;\n if (!this.dialogOn || this.capture || this.runOpen) {\n return;\n }\n const s = (ms: number): string => (ms / 1000).toFixed(1);\n this.opts.log.info(\n playedMs + REPLY_CUT_MS < replyMs\n ? `ESPHome ${this.deviceName}: the device stopped the reply after ${s(playedMs)} of ${s(replyMs)} s ` +\n `(its stop word, a tap or its wake word) and does not listen again`\n : `ESPHome ${this.deviceName}: the device played the reply but did not open its microphone again`,\n );\n this.setDialog(false, 'no-listen');\n }, DIALOG_REOPEN_MS);\n this.dialogReopenTimer.unref();\n }\n\n private cancelDialogReopen(): void {\n if (this.dialogReopenTimer) {\n clearTimeout(this.dialogReopenTimer);\n this.dialogReopenTimer = null;\n }\n }\n\n /**\n * The device asks to end the conversation (`VoiceAssistantRequest{start:false}`): a button, or the wake word\n * said again while a request is running — that is how ESPHome's voice_assistant stops. While it waits for an\n * answer, the firmware leaves that state only on our RUN_END; without one it stays \"in the conversation\", and\n * every further wake word just sends another stop (field report 2026-11-03).\n */\n private onStopRequest(): void {\n this.stoppedAt = Date.now();\n const running = !!this.capture || this.runOpen;\n if (!running && Date.now() - this.buttonAt < CONFIRM_GRACE_MS) {\n // A device with yes/no buttons reports the press and then stops its conversation itself: the button\n // answer ended our run already, and its reply is on the way — nothing to end, nothing to drop. With the\n // stop the device dropped its continue flag too, so no microphone opens for the answered question.\n this.ignoreFollowUpUntil = 0;\n this.opts.log.debug(`ESPHome ${this.deviceName}: the device ended the conversation after the button`);\n return;\n }\n // A device with yes/no buttons may also stop the microphone on the press before it reports which button it\n // was (state messages can be batched): the question stays open a moment longer for that report.\n this.questionUntil = this.questionOpen() ? Math.max(this.questionUntil, Date.now() + CONFIRM_GRACE_MS) : 0;\n this.abortCapture();\n if (Date.now() - this.errorSentAt >= ERROR_ECHO_MS) {\n // Stopping the device ends the dialog, too (a reply in progress is dropped below, so it re-opens nothing)\n this.setDialog(false, 'stop');\n }\n if (running) {\n this.run++; // whatever is still being answered stays silent\n this.opts.log.debug(`ESPHome ${this.deviceName}: the device ended the conversation`);\n this.event(EVENT.RUN_END);\n this.status('idle');\n return;\n }\n if (Date.now() - this.errorSentAt < ERROR_ECHO_MS) {\n return; // the device's own reaction to our ERROR event\n }\n // Nothing is open on our side, but the device still thinks so (it missed a RUN_END): end it there too.\n this.opts.log.debug(`ESPHome ${this.deviceName}: stop outside a conversation — ending it on the device`);\n this.event(EVENT.RUN_END);\n }\n\n private onAudio(audio: VoiceAssistantAudio): void {\n const capture = this.capture;\n if (!capture || capture.closed) {\n return;\n }\n const chunk = Buffer.from(audio.getData_asU8());\n if (chunk.length) {\n capture.lastAudioAt = Date.now();\n capture.chunks.push(chunk);\n const end = capture.detector.push(chunk);\n if (end) {\n void this.finishCapture(end);\n return;\n }\n if (capture.dialog && !capture.detector.hearing && capture.detector.analysedMs >= DIALOG_WINDOW_MS) {\n this.nextDialogWindow(capture);\n }\n }\n if (audio.getEnd()) {\n void this.finishCapture('stream');\n }\n }\n\n /**\n * Dialog mode, nobody spoke during a window: forget it and start a new one on the audio that keeps coming. Only\n * while nothing is heard, so a word that just began is not cut.\n */\n private nextDialogWindow(capture: Capture): void {\n capture.chunks = [];\n capture.detector = this.speechDetector(true, true, 0);\n clearTimeout(capture.timer);\n capture.timer = this.pipelineTimer(true);\n }\n\n /** End a capture whose device stopped sending audio without ending the stream. */\n private checkStall(): void {\n const capture = this.capture;\n if (!capture || capture.closed) {\n return;\n }\n const now = Date.now();\n const quietMs = capture.lastAudioAt ? now - capture.lastAudioAt : now - capture.startedAt;\n if (quietMs < (capture.lastAudioAt ? STREAM_STALL_MS : STREAM_START_MS)) {\n return;\n }\n const audioMs = Math.round(capture.chunks.reduce((sum, c) => sum + c.length, 0) / 2 / (MIC_SAMPLE_RATE / 1000));\n this.opts.log.info(\n `ESPHome ${this.deviceName}: the device ${\n capture.lastAudioAt ? `stopped sending audio after ${(audioMs / 1000).toFixed(2)} s` : 'sent no audio'\n } without ending the stream — closing the utterance after ${(quietMs / 1000).toFixed(1)} s of nothing`,\n );\n void this.finishCapture('stall');\n }\n\n /** Hand a recording that never became a request to {@link EsphomeSatellitesOptions.onDiscarded}. */\n private discard(capture: Capture, pcm: Bytes, reason: DiscardReason, vad: VadReport): void {\n if (!this.opts.onDiscarded || !pcm.length) {\n return;\n }\n try {\n this.opts.onDiscarded({\n device: this.deviceName,\n room: this.room,\n wakeWord: capture.wakeWord,\n reason,\n pcm,\n sampleRate: MIC_SAMPLE_RATE,\n // The store writes its own level profile next to it.\n vad: { ...vad, levels: undefined },\n });\n } catch (e) {\n this.opts.log.debug(`ESPHome ${this.deviceName}: keeping the recording failed — ${(e as Error).message}`);\n }\n }\n\n /** Stop the mic stream and run STT → answer → TTS for what was captured. */\n private async finishCapture(end: CaptureEnd): Promise<void> {\n const capture = this.capture;\n if (!capture || capture.closed) {\n return;\n }\n capture.closed = true;\n this.capture = null;\n clearTimeout(capture.timer);\n clearInterval(capture.stallCheck);\n const run = this.run;\n /** False once the run was ended elsewhere — then nothing more may be sent for it. */\n const current = (): boolean => {\n if (run === this.run) {\n return true;\n }\n this.opts.log.debug(`ESPHome ${this.deviceName}: conversation ended meanwhile — dropping the reply`);\n return false;\n };\n\n // Send this first: the device streams until it sees it.\n this.event(EVENT.STT_VAD_END);\n\n const pcm = Buffer.concat(capture.chunks);\n const seconds = pcm.length / 2 / MIC_SAMPLE_RATE;\n const vad: VadReport = { ...capture.detector.report(), end };\n const startedAt =\n vad.speechStartMs !== undefined ? `, speech from ${(vad.speechStartMs / 1000).toFixed(2)} s` : '';\n const endedBy = vad.end === 'speech-end' ? `ended after ${vad.silenceMs} ms of silence` : `ended by ${vad.end}`;\n this.opts.log.debug(\n `ESPHome ${this.deviceName}: captured ${seconds.toFixed(2)} s ` +\n `(peak RMS ${vad.peak}, noise floor ${vad.noiseFloor}, speech/silence gate ${vad.startLevel}/${vad.endLevel}` +\n `${startedAt}, ${endedBy})`,\n );\n\n if (capture.answersQuestion) {\n // Spoken: that is the answer, a button press now would be a second one. Silent: the buttons still answer\n // for a moment, as the screen may still show them.\n this.questionUntil = capture.detector.sawSpeech\n ? 0\n : Math.max(this.questionUntil, Date.now() + CONFIRM_GRACE_MS);\n }\n\n if (!pcm.length || !capture.detector.sawSpeech) {\n const loudest = Math.round(capture.detector.analysedPeak);\n const gate = Math.round(capture.detector.startLevel);\n if (capture.detector.longestSoundMs > 0) {\n // Something crossed the gate, but too briefly for a word: a click, a knock, a cough.\n this.opts.log.debug(\n `ESPHome ${this.deviceName}: only a short sound (${capture.detector.longestSoundMs} ms, ` +\n `RMS ${loudest}) — too short for speech (${MIN_SPEECH_MS} ms), dropping the utterance`,\n );\n } else if (pcm.length && loudest >= gate * QUIET_VOICE_SHARE) {\n // Not an empty room: something came close to the gate. Typically a microphone that is quieter\n // than the default threshold expects (a phone) — say where to change it.\n this.opts.log.info(\n `ESPHome ${this.deviceName}: dropped the utterance — the loudest sound (RMS ${loudest}) stayed ` +\n `below the speech threshold ${gate}. If somebody spoke, lower \"Speech threshold\" for this ` +\n `device in the ESPHome satellites table (Voice tab), e.g. to ${Math.max(\n 30,\n Math.round((loudest * 0.6) / 10) * 10,\n )}.`,\n );\n } else {\n this.opts.log.debug(\n `ESPHome ${this.deviceName}: nothing but silence${\n end === 'no-speech' ? ' (nobody started speaking)' : ''\n } — dropping the utterance`,\n );\n }\n if (capture.dialog && this.dialogOn && (end === 'timeout' || end === 'speech-end')) {\n // a long noise in dialog mode: listen on\n this.event(EVENT.INTENT_END, { continue_conversation: '1' });\n await this.reopenDialog(run);\n return;\n }\n if (!capture.dialog) {\n this.discard(capture, pcm, end === 'no-speech' ? 'no-speech' : 'silence', vad);\n }\n this.endWithoutRequest();\n if (capture.dialog) {\n // the device ended or stopped the stream itself: it does not want to listen any more\n this.setDialog(false, 'stop');\n }\n return;\n }\n\n this.status('processing');\n try {\n const hints = this.opts.getHints ? await this.opts.getHints() : undefined;\n if (!current()) {\n return;\n }\n const speech = prepareForStt(pcm, MIC_SAMPLE_RATE, { startMs: vad.speechStartMs, endLevel: vad.endLevel });\n vad.stt = { fromMs: speech.fromMs, toMs: speech.toMs, gain: speech.gain };\n this.opts.log.debug(\n `ESPHome ${this.deviceName}: speech recognition gets ${(speech.fromMs / 1000).toFixed(2)}–` +\n `${(speech.toMs / 1000).toFixed(2)} s${speech.gain > 1 ? `, amplified ×${speech.gain}` : ''}`,\n );\n const sttStart = Date.now();\n const text = (\n await this.opts.stt.transcribe(speech.pcm, MIC_SAMPLE_RATE, this.opts.language, hints)\n ).trim();\n const sttMs = Date.now() - sttStart;\n if (!current()) {\n return;\n }\n if (!text) {\n // Speech was heard, so the user waits for an answer: say why none comes. Typically a word in another\n // language than the STT listens in (a German \"Ja\" to a Russian STT comes back empty).\n this.opts.log.info(\n `Voice Q (${this.deviceName}): (empty) — speech recognition returned no text for ${seconds.toFixed(1)} s of audio`,\n );\n this.discard(capture, pcm, 'empty-stt', vad);\n if (capture.answersQuestion) {\n this.questionUntil = Math.max(this.questionUntil, Date.now() + CONFIRM_GRACE_MS);\n }\n if (capture.dialog && this.dialogOn) {\n // a cough, the TV: listen on, without a word about it\n this.event(EVENT.INTENT_END, { continue_conversation: '1' });\n await this.reopenDialog(run);\n return;\n }\n // No STT_END without text — like Home Assistant, which reports this case as an error only.\n this.endWithoutRequest();\n return;\n }\n if (capture.dialog) {\n this.dialogHeardAt = Date.now();\n }\n this.event(EVENT.STT_END, { text });\n\n this.event(EVENT.INTENT_START);\n const answer = (\n await this.opts.answer(text, {\n device: this.deviceName,\n room: this.room,\n wakeWord: capture.wakeWord,\n sttMs,\n audioMs: Math.round(seconds * 1000),\n // Numbers only, no audio: shows where a request was cut off without keeping recordings.\n vad: { ...vad, levels: levelProfile(pcm, MIC_SAMPLE_RATE) },\n })\n ).trim();\n if (!current()) {\n return;\n }\n const followUp = !!answer && this.opts.expectsFollowUp?.(answer, this.deviceName) === true;\n // Always say it, \"0\" included: ESPHome keeps the flag of the last INTENT_END that carried it, so after\n // one question every later reply re-opened the microphone (field report 2026-11-04). Home Assistant\n // sends \"0\" just the same. In dialog mode (switched on or off by this very request, too) always \"1\".\n const conversation = { continue_conversation: followUp || this.dialogOn ? '1' : '0' };\n this.event(EVENT.INTENT_END, conversation);\n\n if (!answer) {\n if (this.dialogOn) {\n // A command done without words (the confirmation tone instead): the tone is the reply here, after\n // it the device listens again. The adapter does not play it itself in dialog mode.\n const tone = confirmationTone();\n await this.reopenDialog(run, tone.pcm, tone.sampleRate);\n return;\n }\n this.event(EVENT.RUN_END);\n this.status('idle');\n return;\n }\n\n const ttsStart = Date.now();\n const { pcm: ttsPcm, sampleRate } = await this.opts.tts.synthesize(answer, this.opts.language);\n if (!current()) {\n return;\n }\n this.opts.onSpoken?.(this.deviceName, {\n ms: Date.now() - ttsStart,\n audioMs: (ttsPcm.length / 2 / sampleRate) * 1000,\n });\n const url = await this.publish(ttsPcm, sampleRate);\n if (!current()) {\n return;\n }\n\n this.status('speaking');\n this.event(EVENT.TTS_START, { text: answer });\n this.event(EVENT.TTS_END, { url });\n // linux-voice-assistant reads the flag here (ignoring \"0\"), ESPHome at INTENT_END\n this.event(EVENT.RUN_END, conversation);\n this.noteDialogReply((ttsPcm.length / 2 / sampleRate) * 1000);\n this.questionUntil = followUp ? Date.now() + (ttsPcm.length / 2 / sampleRate) * 1000 + QUESTION_OPEN_MS : 0;\n this.armPlaybackTimeout();\n } catch (e) {\n const reason = (e as Error).message;\n this.opts.log.error(`ESPHome ${this.deviceName}: voice pipeline failed — ${reason}`);\n if (run !== this.run) {\n return; // the conversation is over already — nothing to tell the device\n }\n // Without this the device stays ducked and its LED keeps spinning.\n this.event(EVENT.ERROR, { code: 'pipeline-failed', message: reason });\n this.event(EVENT.RUN_END);\n this.status('idle');\n this.setDialog(false, 'error');\n }\n }\n\n /**\n * Dialog mode: end the run with a reply that only makes the device listen again — silence when nothing was\n * recognised, else the given clip. ESPHome opens the microphone after a reply has played when the INTENT_END\n * (sent by the caller) said so; linux-voice-assistant reads the flag in RUN_END.\n */\n private async reopenDialog(run: number, pcm?: Buffer, sampleRate = MIC_SAMPLE_RATE): Promise<void> {\n const clip = pcm ?? Buffer.alloc(Math.round((MIC_SAMPLE_RATE * DIALOG_PAUSE_MS) / 1000) * 2);\n try {\n const url = await this.publish(clip, sampleRate);\n if (run !== this.run) {\n return;\n }\n this.status('speaking');\n this.event(EVENT.TTS_START, { text: '' });\n this.event(EVENT.TTS_END, { url });\n this.event(EVENT.RUN_END, { continue_conversation: '1' });\n this.noteDialogReply((clip.length / 2 / sampleRate) * 1000);\n this.armPlaybackTimeout();\n } catch (e) {\n this.opts.log.warn(`ESPHome ${this.deviceName}: dialog cannot go on — ${(e as Error).message}`);\n if (run === this.run) {\n this.endWithoutRequest();\n this.setDialog(false, 'error');\n }\n }\n }\n\n /**\n * End a run that produced no request. A RUN_END right after STT_VAD_END gets lost: the firmware is still stopping\n * its microphone then, ignores RUN_END in that state, and afterwards waits for an answer that never comes — the\n * satellite stays in the conversation (field report 2026-11-03). An ERROR event puts it back to idle in any state,\n * so it goes first, with the code Home Assistant uses for this case.\n */\n private endWithoutRequest(): void {\n this.event(EVENT.ERROR, NO_TEXT_ERROR);\n this.event(EVENT.RUN_END);\n this.status('idle');\n }\n\n /**\n * Select which wake words listen on this device. Unknown ids are dropped and the list is trimmed\n * to what the firmware allows, because the device answers a rejected list with silence rather than\n * an error — better to send something valid and report what we changed.\n *\n * The device persists the selection and echoes it back in a `VoiceAssistantConfigurationResponse`,\n * so we ask for one instead of assuming the write took.\n */\n setWakeWords(ids: string[]): void {\n const known = this.wakeWordConfig?.available.map(w => w.id) ?? [];\n const wanted = [...new Set(ids.map(i => i.trim()).filter(Boolean))];\n const unknown = wanted.filter(i => !known.includes(i));\n if (unknown.length) {\n this.opts.log.warn(\n `ESPHome ${this.deviceName}: unknown wake word(s) ${unknown.join(', ')} — ignored. ` +\n `Available: ${known.join(', ') || '(none reported)'}`,\n );\n }\n let valid = wanted.filter(i => known.includes(i));\n const max = this.wakeWordConfig?.max || 0;\n if (max > 0 && valid.length > max) {\n this.opts.log.warn(\n `ESPHome ${this.deviceName}: device allows ${max} active wake word(s), keeping ${valid\n .slice(0, max)\n .join(', ')}`,\n );\n valid = valid.slice(0, max);\n }\n\n const message = new pb.VoiceAssistantSetConfiguration();\n message.setActiveWakeWordsList(valid);\n this.send(message);\n this.opts.log.info(`ESPHome ${this.deviceName}: wake words set to ${valid.join(', ') || '(none)'}`);\n // Read back, so the reported state is the device's and not our guess. The device resolves a\n // custom wake word (and downloads it) while handling the SetConfiguration, so this answer\n // already tells whether that worked.\n this.requestWakeWordConfig(valid);\n }\n\n /**\n * Ask the device for its wake-word configuration. The request always carries the current custom\n * wake words: the firmware replaces its list of offered models with every request, so one sent\n * without them would make an uploaded wake word vanish from the device until the next offer.\n *\n * @param check ids a SetConfiguration just asked for — warned about if the answer lacks them\n */\n requestWakeWordConfig(check: string[] | null = null): void {\n const request = new pb.VoiceAssistantConfigurationRequest();\n const offers = this.opts.externalWakeWords?.() ?? [];\n request.setExternalWakeWordsList(\n offers.map(offer => {\n const w = new pb.VoiceAssistantExternalWakeWord();\n w.setId(offer.id);\n w.setWakeWord(offer.phrase);\n w.setTrainedLanguagesList(offer.languages);\n w.setModelType('micro');\n w.setModelSize(offer.size);\n w.setModelHash(offer.sha256);\n w.setUrl(this.mediaUrl(offer.path));\n return w;\n }),\n );\n // A device that never answers must not let this grow without bound.\n if (this.configChecks.length < 16) {\n this.configChecks.push(check);\n }\n this.send(request);\n }\n\n /** Drop a half-finished capture (device went away, or told us to stop). */\n private abortCapture(): void {\n const capture = this.capture;\n if (!capture) {\n return;\n }\n this.capture = null;\n capture.closed = true;\n clearTimeout(capture.timer);\n clearInterval(capture.stallCheck);\n }\n\n // ── announcements ───────────────────────────────────────────────────────────────────────────────\n\n /**\n * Speak a ready PCM buffer on this device (timers, alarms, `tts.text`, jingles). With\n * `startConversation` the microphone opens once the clip has played, to catch the answer to a question.\n */\n async announce(\n pcm: Buffer,\n sampleRate: number,\n startConversation = false,\n text = '',\n question = true,\n ): Promise<void> {\n if (!this.online || !pcm.length) {\n return;\n }\n const request = new pb.VoiceAssistantAnnounceRequest();\n request.setMediaId(await this.publish(pcm, sampleRate));\n // What a device with a screen shows while it plays (its on_tts_start)\n request.setText(text);\n request.setPreannounceMediaId('');\n // Needs feature flag 32 (START_CONVERSATION); on a device without it the clip still plays and\n // only the microphone stays shut, so there is nothing to guard here.\n request.setStartConversation(startConversation);\n if (startConversation) {\n // The microphone the device opens after it is wanted; for a question a button press answers it, too\n this.ignoreFollowUpUntil = 0;\n if (question) {\n this.questionUntil = Date.now() + (pcm.length / 2 / sampleRate) * 1000 + QUESTION_OPEN_MS;\n }\n }\n this.status('speaking');\n this.send(request);\n this.armPlaybackTimeout();\n }\n\n /** The format replies should have on this device, from what its media player announced. */\n private replyFormat(): ReplyFormat {\n const formats = this.entities\n .list()\n .filter(e => e.kind === 'mediaPlayer')\n .flatMap(e => e.formats ?? []);\n return chooseReplyFormat(formats, !!this.opts.encodeAudio);\n }\n\n /**\n * Publish PCM on the media server, in the format the device plays, and build the URL it should fetch.\n *\n * The host matters: on a multi-homed ioBroker machine the device can usually only reach one of the\n * addresses, and the local end of *this* socket is by definition one it can talk to.\n */\n private async publish(pcm: Buffer, sampleRate: number): Promise<string> {\n let format = this.replyFormat();\n let encoded: { body: Buffer; contentType: string };\n try {\n encoded = await encodeReply(pcm, sampleRate, format, this.opts.encodeAudio);\n } catch (e) {\n // MP3/Opus need ffmpeg. Without it a native format is the only chance, whether the device lists it or not.\n const fallback: ReplyFormat = { ...format, codec: 'flac', source: `${format.source}, FLAC as fallback` };\n this.opts.log.warn(\n `ESPHome ${this.deviceName}: cannot write the reply as ${format.codec.toUpperCase()} ` +\n `(${(e as Error).message}) — sending FLAC, which the device may not play. Install ffmpeg.`,\n );\n format = fallback;\n encoded = await encodeReply(pcm, sampleRate, format);\n }\n const key = `${format.codec}/${format.sampleRate}/${format.channels}`;\n if (key !== this.loggedFormat) {\n this.loggedFormat = key;\n const what = !format.source\n ? 'WAV (the device lists no formats)'\n : `${format.codec.toUpperCase()}${format.sampleRate ? ` ${format.sampleRate} Hz` : ''}` +\n `${format.channels === 2 ? ' stereo' : ''} (device: ${format.source})`;\n this.opts.log.info(`ESPHome ${this.deviceName}: spoken replies as ${what}`);\n }\n return this.mediaUrl(this.opts.media.publish(encoded.body, encoded.contentType));\n }\n\n /** Absolute URL of a path on the media server, with a host this device can reach. */\n mediaUrl(path: string): string {\n const local = (this.socket?.localAddress || '').replace(/^::ffff:/, '');\n const host = this.opts.mediaHost?.trim() || local || '127.0.0.1';\n // An IPv6 literal has to be bracketed in a URL.\n const authority = host.includes(':') ? `[${host}]` : host;\n return `http://${authority}:${this.opts.media.port}${path}`;\n }\n\n /** Fall back to `idle` if the device never reports that it finished playing. */\n private armPlaybackTimeout(): void {\n if (this.playbackTimer) {\n clearTimeout(this.playbackTimer);\n }\n this.playbackTimer = setTimeout(() => {\n this.playbackTimer = null;\n this.status('idle');\n }, PLAYBACK_TIMEOUT_MS);\n this.playbackTimer.unref();\n }\n\n private event(type: number, data?: Record<string, string>): void {\n if (type === EVENT.RUN_START) {\n this.runOpen = true;\n } else if (type === EVENT.RUN_END) {\n this.runOpen = false;\n } else if (type === EVENT.ERROR) {\n this.errorSentAt = Date.now();\n }\n const message = new pb.VoiceAssistantEventResponse();\n message.setEventType(type);\n const items: VoiceAssistantEventData[] = [];\n for (const [name, value] of Object.entries(data || {})) {\n const item = new pb.VoiceAssistantEventData();\n item.setName(name);\n item.setValue(value);\n items.push(item);\n }\n message.setDataList(items);\n this.send(message);\n }\n}\n"]}
package/io-package.json CHANGED
@@ -1,8 +1,21 @@
1
1
  {
2
2
  "common": {
3
3
  "name": "assistant",
4
- "version": "1.4.13",
4
+ "version": "1.4.14",
5
5
  "news": {
6
+ "1.4.14": {
7
+ "en": "ESPHome satellites, dialog mode: a satellite that does not listen again after an answer (it stopped the answer itself — stop word, tap) ends the mode instead of leaving it on while nobody listens; the log says how much of the answer was played",
8
+ "de": "ESPHome-Satelliten, Dialogmodus: Ein Satellit, der nach einer Antwort nicht mehr zuhört (stoppt die Antwort selbst — Wort, Tippen) beendet den Modus, statt ihn an zu lassen, solange niemand zuhört; das Protokoll sagt, wie viel von der Antwort abgespielt wurde",
9
+ "ru": "Спутники EspHome, диалоговый режим: спутник, который после ответа больше не слушает (он сам остановил ответ — остановите слово, нажмите), завершает режим, а не оставит его включенным, пока никто не слушает; в журнале указано, какая часть ответа была воспроизведена",
10
+ "pt": "Satélites ESPHome, modo de diálogo: um satélite que não escuta novamente após uma resposta (parou a resposta) encerra o modo em vez de deixá-lo ligado enquanto ninguém escuta; o log diz quanto da resposta foi reproduzida",
11
+ "nl": "ESPhome-satellieten, dialoogmodus: een satelliet die na een antwoord niet meer luistert (hij heeft het antwoord zelf gestopt — stopwoord, tik) beëindigt de modus in plaats van hem aan te laten staan terwijl niemand luistert; in het logboek staat hoeveel van het antwoord is afgespeeld",
12
+ "fr": "Satellites ESPhome, mode dialogue : un satellite qui n'écoute plus après une réponse (il arrête la réponse elle-même, arrête le mot, tape) met fin au mode au lieu de le laisser allumé alors que personne n'écoute ; le journal indique la durée de la réponse",
13
+ "it": "Satelliti ESPhome, modalità dialogo: un satellite che non ascolta più una risposta (interrompe la risposta stessa — stop word, tap) termina la modalità invece di lasciarla accesa mentre nessuno ascolta; il registro indica la quantità di risposta",
14
+ "es": "Satélites ESPhome, modo de diálogo: un satélite que no vuelve a escuchar después de la respuesta (detiene la respuesta en sí, detiene la palabra, toca) termina el modo en lugar de dejarlo encendido mientras nadie escucha; el registro dice qué parte de la respuesta se ha reproducido",
15
+ "pl": "Satelity eSphome, tryb dialogowy: satelita, który nie słucha ponownie po odpowiedzi (zatrzymał samą odpowiedź — zatrzymaj słowo, dotknij) kończy tryb zamiast pozostawiać go włączonym, gdy nikt nie słucha; dziennik mówi, ile odpowiedzi została odtworzona",
16
+ "uk": "Супутники ESPHome, діалоговий режим: супутник, який не слухає знову після відповіді (він сам зупинив відповідь - зупиніть слово, торкніться), закінчує режим замість того, щоб залишити його увімкненим, поки ніхто не слухає; журнал говорить, скільки відповіді було відтворено",
17
+ "zh-cn": "espHome 卫星,对话模式:一颗卫星在答案后不再收听(它本身停止答案 — 停言,点击)会结束该模式,而不是在没人听的时候将其保持开启状态;日志显示答案中有多少已播放"
18
+ },
6
19
  "1.4.13": {
7
20
  "en": "If fullcalendar is installed, it must be 3.1.0 or later (the version with the event API that commands for later use)\nDevices renamed in the device list keep their room, type and all their states again (`@iobroker/mcp-server` 1.9.2): before, such a device lost its room, so \"the light in the kitchen\" was not understood, and a light lost the switch next to its level\nDevices in a room hidden from the smart home (iot, `smartName: false`) are no longer listed without a room\nThe AI sees what each state of a device is (switch, level, read-only) and that the level alone does not switch a device on\nThe AI (cloud model and pi-agent) is told to answer in the language of the question\nVideos: `ask` also takes `video: { url }` with an `iobdisk://` URL - the video stays on the disk of the sender's host (js-controller 8.0+) and can be read from any host. `{ adapter, path }` of the file storage still works. Telegram sends the URL",
8
21
  "de": "Wenn Fullcalendar installiert ist, muss es 3.1.0 oder höher sein (die Event-API zur späteren Nutzung)\nGeräte, die in der Geräteliste umbenannt wurden, behalten Raum, Typ und Status (`@iobroker /mcp-server` 1.9.2): vorher verlor ein Gerät seinen Raum, also wurde „das Licht in der Küche“ nicht verstanden, und ein Licht verlor den Schalter neben dem Level\nGeräte in einem Smart-Home-Raum (IoT, `SmartName: false`) werden nicht mehr ohne Raum gelistet\nDie KI sieht den Zustand eines Geräts (Schalter, Level, schreibgeschützt) und das Level allein schaltet es nicht ein\nDie KI (Cloud-Modell und Pi-Agent) soll in der Sprache der Frage antworten\nVideos: `ask` nimmt auch `video: {url} `mit einer `iobdisk: //` URL auf — das Video bleibt auf der Festplatte des Absenders (js-controller 8.0+) und kann von jedem Host gelesen werden. Telegram sendet die URL",
@@ -80,19 +93,6 @@
80
93
  "pl": "Satelity ESPhome: podmiot aktualizacji oprogramowania układowego otrzymuje przycisk „sprawdź” („kontrolki. <update>.check`), co sprawia, że urządzenie szuka nowej wersji teraz, zamiast przy następnym uruchomieniu lub 6-godzinnej kontroli\nSatelity ESPhome: elementy `tekstowe' są odzwierciedlone jako stany zapisywalne (etykiety i jednostki satelity z ekranem można ustawić za pomocą ioBroker). Wartości poza długością lub wzorem urządzenia są odrzucane z ostrzeżeniem; tekst hasła nie jest odzwierciedlany\nDokumenty: opcjonalne elementy satelity z ekranem (`confirm_answer`, `display_language`, `text`)",
81
94
  "uk": "Супутники ESPHome: об'єкт оновлення мікропрограми отримує кнопку «перевірити» (`елементи керування. <update>.check`), що змушує пристрій шукати нову версію зараз, а не при наступному завантаженні або 6-годинній перевірці\nСупутники ESPHome: `text` сутності віддзеркалюються як записуються стани (мітки та одиниці супутника з екраном можна встановити з IObroker). Значення за межами довжини або шаблону пристрою відхиляються з попередженням; текст пароля не відображається\nДокументи: необов'язкові об'єкти супутника з екраном (`confirm_answer`, `display_language`, `text`)",
82
95
  "zh-cn": "espHome 卫星:固件更新实体获得 “检查” 按钮(“控件”。<update>.check`) 这使设备现在正在寻找新版本,而不是在下次启动或 6 小时检查时寻找新版本\nESPhome 卫星:“文本” 实体被镜像为可写状态(带屏幕的卫星的标签和单位可以通过 ioBroker 设置)。超出设备长度或图案的值将被拒绝并显示警告;密码文本未镜像\n文档:带屏幕的卫星的可选实体(`confirm_answer`、`display_language`、`文本`)"
83
- },
84
- "1.4.7": {
85
- "en": "Voice messages: `ask` also takes a recording (`audio` as base64 plus `format`, e.g. `ogg`) instead of text. It is recognised with the speech recognition of the Voice tab and answered like a text question; the reply carries the recognised text as `heard`. Telegram uses it for voice messages\nPath to ffmpeg can be set on the Voice tab (empty = from the search path), with a button that checks it\nHosts without ffmpeg: \"Download ffmpeg\" on the Voice tab fetches a static build of ffmpeg-static (20-30 MB, checked against a fixed SHA-256) into the data directory of the instance; it is used while no path is entered\nPictures: `ask` takes `images` (base64 JPEG/PNG/GIF/WebP, at most 4) and passes them to the cloud model (OpenAI-compatible, Anthropic, pi-agent); without a text the question is \"What is in this picture?\". Rules and the local model are skipped for them. Telegram uses it for photos\nVideos: `ask` takes a reference `video: { adapter, path }` into the file storage (never the content). Videos are not looked at yet: without a question the answer says so, with one the model is told\nESPHome: after a reply that asked something, every later reply re-opened the microphone. The firmware keeps `continue_conversation` until it is told \"0\", so every reply now says it, like Home Assistant does\nSatellites only listen again after a reply that asks something: a [[LISTEN]] marker (pi-agent's confirmations) or a question mark at the end. A question mark in the middle of a reply no longer opens the microphone\nESPHome satellites with a screen: yes/no buttons (event `confirm_answer`) answer the open question like a spoken \"yes\"/\"no\" - the microphone closes, the reply is announced on that satellite. A select `display_language` is set to the voice language when the satellite connects",
86
- "de": "Sprachnachrichten: `ask` nimmt statt Text auch Aufnahme (`Audio` als Base64 plus `Format`, z. B. `ogg`). Es wird von der Spracherkennung im Sprach-Tab erkannt und wie eine Textfrage beantwortet; die Antwort enthält den Text „gehört“. Telegram nutzt es für Sprachnachrichten\nDer Pfad zu ffmpeg kann auf dem Tab Voice (leer = aus dem Suchpfad) gesetzt werden.\nHosts ohne ffmpeg: „Download ffmpeg“ im Tab Voice ruft eine statische Version von ffmpeg-static (20-30 MB, geprüft mit SHA-256) in das Datenverzeichnis der Instanz ab; wird ohne Pfadangabe verwendet\nBilder: `ask` nimmt Bilder (base64 JPEG/PNG/GIF/Webp, maximal 4) und übergibt sie an das Cloud-Modell (OpenAI-kompatibel, Anthropic, Pi-Agent); ohne Text lautet die Frage „Was ist auf dem Bild?“. Regeln und das lokale Modell entfallen. Telegram nutzt es für Fotos\nVideos: `ask` nimmt eine Referenz `video: {adapter, path} `in den Speicher (nie den Inhalt). Videos sind noch nicht angeschaut: ohne Frage sagt die Antwort ja, bei einem wird das Model\nESPhome: Nach einer Antwort mit einer Frage öffnete jede weitere Antwort das Mikrofon. Die Firmware fährt fort, bis „0\" angezeigt wird, also sagt es jetzt jede Antwort, wie Home Assistant\nSatelliten hören erst wieder zu, wenn sie etwas fragen: [[ZUHÖREN]] -Zeichen (Bestätigung des Pi-Agenten) oder Fragezeichen am Ende. Ein Fragezeichen in der Antwort öffnet das Mikro nicht mehr\nESPHome-Satelliten mit Bildschirm: Ja/Nein-Tasten (Event `confirm_answer`) beantworten offene Fragen wie „Ja“ /\"Nein“ — das Mikrofon schließt sich, die Antwort wird am Satelliten angekündigt. A select `display_language` ist die Sprachsprache, wenn der Satellit kommt",
87
- "ru": "Голосовые сообщения: `ask` также принимает запись (`audio` в формате base64 плюс `format`, например `ogg`) вместо текста. Оно распознается с помощью функции распознавания речи на вкладке «Голос» и отвечает на него как на текстовый вопрос; в ответе распознанный текст считается «услышанным». Telegram использует его для голосовых сообщений\nПуть к ffmpeg можно задать на вкладке Voice (пусто = из пути поиска) с помощью кнопки, которая его проверяет\nХосты без ffmpeg: при нажатии кнопки «Загрузить ffmpeg» на вкладке «Голос» статическая сборка ffmpeg-static (20-30 МБ, в сравнении с фиксированным значением SHA-256) загружается в каталог данных экземпляра; она используется, когда путь не указан\nИзображения: `ask` берет «изображения» (base64 JPEG/PNG/GIF/WebP, максимум 4) и передает их в облачную модель (совместимую с OpenAI, Anthropic, pi-agent); без текста вопрос: «Что на этой картинке?». Правила и локальная модель для них пропущены. Telegram использует его для фотографий\nВидео: `ask` помещает ссылку `video: {adapter, path} `в файловое хранилище (а не содержимое). Видеоролики пока не просматриваются: без вопросов ответ говорит сам за себя, по одному из них модель рассказывается\neSpHome: после ответа на какой-то вопрос каждый последующий ответ снова открывал микрофон. Прошивка сохраняет «continue_conversation» до тех пор, пока не будет указано «0», поэтому теперь в каждом ответе так же, как и в Home Assistant\nСпутники снова слушают только после ответа с вопросом: маркером [[LISTEN]] (подтверждения pi-agent) или вопросительным знаком в конце. Значок вопроса в середине ответа больше не открывает микрофон\nСпутники EspHome с экраном: кнопки «да/нет» (событие `confirm_answer`) отвечают на открытый вопрос так же, как и произнесенное «да»/«нет» — микрофон закрывается, ответ объявляется на этом спутнике. При подключении спутника выбранный язык `display_language` выбирается на язык голоса",
88
- "pt": "Mensagens de voz: `ask` também grava (`audio` em base64 mais `format`, e.g. `ogg`) em vez de texto. É reconhecida com o reconhecimento de fala na guia Voz e respondida como uma pergunta de texto; a resposta leva o texto reconhecido como “ouvido”. O Telegram o usa para mensagens de voz\nO caminho para ffmpeg pode ser definido na aba Voz (vazio = da busca), com um botão\nHosts sem ffmpeg: “Baixar ffmpeg” na guia Voice busca uma versão estática de ffmpeg-static (20 a 30 MB, comparada a um SHA-256 fixo) no diretório de dados da instância; é usada sem inserir caminho\nImagens: `ask` pega `images` (base64 JPEG/PNG/GIF/WebP, no máximo 4) e as passa para o modelo de nuvem (OpenAI, Anthropic, pi-agent); sem texto, a pergunta é “O que há nesta foto?”. Eles ignoram as regras e o modelo local. Telegram usa para fotos\nVídeos: `ask` leva a referência `video: {adapter, path} `para o arquivo (nunca o conteúdo). Os vídeos ainda não foram vistos: sem dúvida, a resposta diz: com um, a modelo diz\nESPHome: após uma resposta que perguntava algo, cada resposta reabria o microfone. O firmware continua conversando até ouvir “0\", então toda resposta agora diz isso, como o Home Assistant.\nOs satélites só escutam novamente após uma resposta que pergunta algo: um marcador (confirmações do agente pi) ou uma interrogação no final. Uma interrogação no meio da resposta não abre mais o microfone\nOs satélites ESPHome com tela: botões sim/não (evento `confirm_answer`) respondem à pergunta aberta como um “sim” /\"não” falado - o microfone fecha e a resposta é anunciada no satélite. Um `display_language` é definido para o idioma de voz quando o satélite se conecta",
89
- "nl": "Spraakberichten: voor `ask` is ook een opname nodig (`audio` als base64 plus `formaat`, bijvoorbeeld `ogg`) in plaats van tekst. Het wordt herkend met de spraakherkenning op het tabblad Spraak en beantwoord als een tekstvraag; het antwoord bevat de herkende tekst als „gehoord”. Telegram gebruikt het voor spraakberichten\nHet pad naar ffmpeg kan worden ingesteld op het tabblad Spraak (leeg = van het zoekpad), met een knop die het controleert\nHosts zonder ffmpeg: „Download ffmpeg” op het tabblad Voice haalt een statische versie van ffmpeg-static (20-30 MB, vergeleken met een vaste SHA-256) op naar de gegevensmap van de instantie; deze wordt gebruikt zonder dat er een pad is ingevoerd\nAfbeeldingen: `ask` neemt `beelden` (base64 JPEG/PNG/GIF/WebP, maximaal 4) en geeft deze door aan het cloudmodel (compatibel met OpenAI, Anthropic, pi-agent); zonder tekst is de vraag „Wat staat er op deze foto?”. Regels en het lokale model worden voor hen overgeslagen. Telegram gebruikt het voor foto's\nVideo's: `ask` neemt een referentie `video: {adapter, path} `mee naar de bestandsopslag (nooit de inhoud). De video's zijn nog niet bekeken: zonder een vraag is het antwoord ja, bij één wordt het model verteld\nESPhome: na een antwoord waarin iets werd gevraagd, werd bij elk antwoord later de microfoon opnieuw geopend. De firmware bewaart `continue_conversation` tot er „0\" wordt verteld, dus elk antwoord zegt het nu, zoals Home Assistant dat doet\nSatellieten luisteren pas weer na een antwoord waarin iets wordt gevraagd: een [[LISTEN]] -markering (de bevestigingen van de pi-agent) of een vraagteken aan het einde. Een vraagteken in het midden van een antwoord opent de microfoon niet langer\nESPhome-satellieten met een scherm: ja/nee-knoppen (gebeurtenis `confirm_answer`) beantwoorden de open vraag als een gesproken „ja” /\"nee” - de microfoon wordt gesloten, het antwoord wordt aangekondigd op die satelliet. Een geselecteerde `display_language` is ingesteld op de stemtaal wanneer de satelliet verbinding maakt",
90
- "fr": "Messages vocaux : `ask` enregistre également (`audio` en base64 plus `format`, par exemple `ogg`) au lieu du texte. La reconnaissance vocale de l'onglet Voix y est traitée comme une question textuelle ; le texte reconnu comme « entendu » apparaît sur la réponse. Telegram l'utilise pour les messages vocaux\nLe chemin vers ffmpeg peut être défini dans l'onglet Voice (vide = depuis le chemin de recherche)\nHôtes sans ffmpeg : « Download ffmpeg » de l'onglet Voice récupère une version statique de ffmpeg-static (20 à 30 Mo, comparé à un SHA-256 fixe) dans le répertoire de données de l'instance ; il est utilisé sans chemin\nPhotos : `ask` prend des « images » (base64 JPEG/PNG/GIF/WebP, au plus 4) et les transmet au modèle cloud (compatible OpenAI, Anthropic, pi-agent) ; sans texte, la question est « Qu'y a-t-il sur cette photo ? ». Les règles et le modèle local leur sont ignorés. Telegram l'utilise pour les photos\nVidéos : `ask` place la référence « video : {adapter, path} » dans le stockage (jamais le contenu). Les vidéos ne sont pas encore regardées : la réponse est claire, avec une, le mannequin\nESPhome : après une réponse qui demandait quelque chose, le micro a été rouvert à chaque réponse. Le firmware conserve « continue_conversation » jusqu'à ce qu'on lui donne « 0 », donc chaque réponse le dit, comme Home Assistant\nLes satellites ne réécoutent qu'après une réponse demandant quelque chose : un marqueur [[LISTEN]] (confirmation de l'agent PI) ou un point d'interrogation à la fin. Un point d'interrogation au milieu d'une réponse n'ouvre plus le micro\nSatellites ESPhome avec écran : les boutons oui/non (event « confirm_answer ») répondent à la question ouverte comme un « oui » /un « non ». Le micro se ferme, la réponse est annoncée sur ce satellite. Un select « display_language » est réglé sur la langue de la voix lorsque le satellite se connecte",
91
- "it": "Messaggi vocali: `ask` registra anche (`audio` in base64 più `format`, es. `ogg`) anziché testo. Viene riconosciuta con il riconoscimento vocale della scheda Voce e risponde come una domanda testuale; il testo è «sentito». Telegram lo usa per i messaggi vocali\nIl percorso di ffmpeg è impostato nella scheda Voce (vuota = ricerca), con un pulsante\nHost senza ffmpeg: «Scarica ffmpeg» nella scheda Voice recupera una build statica di ffmpeg-static (20-30 MB, confrontata con un SHA-256 fisso) nella cartella dati dell'istanza; è usata senza percorso\nFoto: `ask` prende `immagini` (base64 JPEG/PNG/GIF/WebP, al massimo 4) e le passa al modello cloud (compatibile con OpenAI, Anthropic, pi-agent); senza testo la domanda è «Cosa c'è nella foto?». Le regole e il modello locale sono saltati. Telegram lo usa per le foto\nVideo: `ask` inserisce un riferimento `video: {adapter, path} `nel file (mai il contenuto). I video non sono ancora visti: senza una domanda la risposta, con una la modella\nESPHome: dopo una domanda, ogni risposta successiva riapre il microfono. Il firmware continua a parlare finché non dice «0\", quindi ora ogni risposta lo dice, come Home Assistant\nI satelliti riascoltano solo dopo una risposta che chiede qualcosa: un [[LISTEN]] (conferme di pi-agent) o un punto interrogativo alla fine. Un punto a metà risposta non apre più il microfono\nSatelliti ESPhome con schermo: i pulsanti sì/no (evento `confirm_answer`) rispondono alla domanda aperta con un «sì» /\"no»: il microfono si chiude, la risposta è annunciata. La lingua vocale selezionata è `display_language` quando il satellite si connette",
92
- "es": "Mensajes de voz: `ask` también graba (`audio` en base64 más `formato`, p. ej., `ogg`) en lugar de texto. Se reconoce con el reconocimiento de voz de la pestaña Voz y se responde como una pregunta de texto; la respuesta incluye el texto reconocido como «oído». Telegram lo usa para mensajes de voz\nLa ruta a ffmpeg se puede fijar en la pestaña Voz (vacía = en la ruta de búsqueda), con un botón que la marca\nHosts sin ffmpeg: «Descargar ffmpeg» en la pestaña Voz busca una versión estática de ffmpeg-static (de 20 a 30 MB, comparada con un SHA-256 fijo) en el directorio de datos de la instancia; se usa sin introducir ninguna ruta\nImágenes: `ask` toma `imágenes` (base64 JPEG/PNG/GIF/WebP, como máximo 4) y las pasa al modelo de nube (compatible con OpenAI, Anthropic, pi-agent); sin texto, la pregunta es «¿Qué hay en esta imagen?». Se saltan las reglas y el modelo local. Telegram lo usa para fotos\nVídeos: `ask` lleva la referencia `video: {adapter, path} `al almacenamiento de archivos (nunca al contenido). Los vídeos aún no se ven: sin duda, la respuesta lo dice, con uno, le dicen a la modelo\nESPhome: Tras una respuesta en la que se preguntaba algo, cada vez que respondía volvía a abrir el micrófono. El firmware mantiene «continuar la conversación» hasta que se le diga «0», así que ahora todas las respuestas lo dicen, como Home Assistant\nLos satélites solo vuelven a escuchar después de una respuesta que diga algo: un marcador (confirmaciones del agente pi) o un signo de interrogación al final. Un signo de interrogación en mitad de la respuesta ya no abre el micrófono\nSatélites ESPhome con pantalla: los botones sí/no (evento `confirm_answer`) responden a la pregunta abierta como un «sí» /\"no» hablado: el micrófono se cierra y la respuesta se anuncia en ese satélite. Seleccione `display_language` como idioma de voz cuando el satélite se conecta",
93
- "pl": "Wiadomości głosowe: `ask` pobiera również nagranie (`audio` jako base64 plus `format`, np. `ogg`) zamiast tekstu. Jest rozpoznawany za pomocą rozpoznawania mowy na karcie Głos i odpowiada jak pytanie tekstowe; odpowiedź zawiera rozpoznany tekst jako „słyszany”. Telegram używa go do wiadomości głosowych\nŚcieżkę do ffmpeg można ustawić na karcie Głos (pusta = ze ścieżki wyszukiwania), za pomocą przycisku, który ją sprawdza\nHosty bez ffmpeg: „Pobierz ffmpeg” na karcie Głos pobiera statyczną kompilację ffmpeg-static (20-30 MB, zaznaczoną na podstawie stałego SHA-256) do katalogu danych instancji; jest używany, gdy nie jest wprowadzana ścieżka\nZdjęcia: `ask` pobiera „obrazy” (base64 JPEG/PNG/GIF/WebP, najwyżej 4) i przekazuje je do modelu chmury (kompatybilny z OpenAI, Anthropic, pi-agent); bez tekstu pytanie brzmi „Co jest na tym zdjęciu?”. Zasady i model lokalny są dla nich pomijane. Telegram używa go do zdjęć\nFilmy: `ask` pobiera odniesienie `video: {adapter, path} `do magazynu plików (nigdy treści). Filmy nie są jeszcze oglądane: bez pytania odpowiedź tak mówi, z jednym model jest powiedziany\nESPhome: po odpowiedzi, w której o coś pytano, każda późniejsza odpowiedź ponownie otwierała mikrofon. Oprogramowanie układowe utrzymuje „continue_conversation”, dopóki nie zostanie powiedziane „0”, więc każda odpowiedź mówi to teraz, tak jak robi to Home Assistant\nSatelity słuchają ponownie dopiero po odpowiedzi, która o coś pyta: znacznik [[LISTEN]] (potwierdzenia agenta pi-agenta) lub znak zapytania na końcu. Znak zapytania w środku odpowiedzi nie otwiera już mikrofonu\nSatelity ESPhome z ekranem: przyciski tak/nie (zdarzenie `confirm_answer`) odpowiadają na otwarte pytanie jak wypowiedziane „tak” /\"nie” - mikrofon zamyka się, odpowiedź jest ogłaszana na tym satelicie. Wybierz `display_language` jest ustawiony na język głosu, gdy satelita łączy się",
94
- "uk": "Голосові повідомлення: `ask` також приймає запис (`audio` як base64 плюс `format`, наприклад `ogg`) замість тексту. Він розпізнається за допомогою розпізнавання мовлення на вкладці Голос і відповідає як текстове запитання; відповідь містить розпізнаний текст як «почутий». Telegram використовує його для голосових повідомлень\nШляху до ffmpeg можна встановити на вкладці Голос (порожній = з шляху пошуку), за допомогою кнопки, яка перевіряє його\nХости без ffmpeg: «Завантажити ffmpeg» на вкладці Голос отримує статичну збірку ffmpeg-static (20-30 Мб, перевірено проти фіксованого SHA-256) у каталог даних екземпляра; він використовується, коли шлях не вводиться\nЗображення: `ask` бере `зображення` (base64 JPEG/PNG/GIF/WebP, максимум 4) і передає їх у хмарну модель (OpenAI-сумісна, антропна, pi-агент); без тексту питання «Що на цій картині?». Правила і локальна модель для них пропускаються. Telegram використовує його для фотографій\nВідео: `ask` переносить посилання `video: {adapter, path} `у сховище файлів (ніколи не вміст). Відео поки не дивляться: без питання відповідь говорить так, з одним розповідається модель\nESPHome: після відповіді, яка щось запитала, кожна пізніша відповідь знову відкриває мікрофон. Прошивка зберігає `continue_conversation`, доки їй не буде сказано «0», тому кожна відповідь тепер говорить це, як це робить домашній помічник\nСупутники знову слухають лише після відповіді, яка щось запитує: маркер [[LISTEN]] (підтвердження pi-агента) або знак питання в кінці. Знак питання посередині відповіді більше не відкриває мікрофон\nСупутники ESPHome з екраном: кнопки так/ні (подія `confirm_answer`) відповідають на відкрите запитання, як вимовлене «так» /\"ні» - мікрофон закривається, відповідь оголошується на цьому супутнику. Вибір `display_language` встановлюється на мову голосу, коли супутник підключається",
95
- "zh-cn": "语音消息:“ask” 还使用录音(“音频” 作为 base64 加上 “格式”,例如 “ogg”)而不是文本。它可通过 “语音” 选项卡的语音识别进行识别,并像文字问题一样回答;回复中识别出的文本为 “已听到”。Telegram 用它来发送语音消息\n可以在 “语音” 选项卡上设置 ffmpeg 的路径(空 = 来自搜索路径),使用一个按钮来检查路径\n没有 ffmpeg 的主机:“语音” 选项卡上的 “下载 ffmpeg” 会将 ffmpeg-static 的静态版本(20-30 MB,对照固定的 SHA-256 进行检查)提取到实例的数据目录中;在未输入路径时使用\n图片:`ask`取`图像`(base64 JPEG/PNG/GIF/WebP,最多4张)并将其传递给云端模型(兼容 OpenAI、Anthropic、pi-agent);如果没有文字,问题是 “这张照片里有什么?”。它们会跳过规则和局部模型。Telegram 用它拍照\n视频:`ask`将引用 `video: {适配器,路径} `存入文件存储(而不是内容)。视频还没有被看过:没有问题,答案就是这样,其中一个是模特被告知的\nespHome:在回复询问某事之后,每当以后的回复都会重新打开麦克风。固件会保持 “continue_conversation” 直到被告知 “0”,所以现在每个回复都会像家庭助理一样说出来\n卫星只有在回复后才会再次收听:[[LISTEN]] 标记(pi-agent 的确认)或末尾的问号。回复中间的问号不会再打开麦克风\n带有屏幕的 espHome 卫星:是/否按钮(事件 “confirm_answer”)像口头说 “是”/“否” 一样回答悬而未决的问题 —— 麦克风关闭,回复将在该卫星上公布。卫星连接时,选择的 “display_language” 设置为语音语言"
96
96
  }
97
97
  },
98
98
  "titleLang": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "iobroker.assistant",
3
- "version": "1.4.13",
3
+ "version": "1.4.14",
4
4
  "description": "LLM assistant for ioBroker — ask about and control any state via an LLM with tool-calling",
5
5
  "author": "ioBroker",
6
6
  "license": "MIT",