iobroker.assistant 1.4.11 → 1.4.13

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.
@@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.EsphomeSatellites = exports.TIMER_EVENT = exports.DEFAULT_SPEECH_LEVEL = void 0;
36
+ exports.EsphomeSatellites = exports.TIMER_EVENT = exports.DIALOG_IDLE_MS = exports.DEFAULT_SPEECH_LEVEL = void 0;
37
37
  exports.yesNoWord = yesNoWord;
38
38
  exports.confirmAnswerOf = confirmAnswerOf;
39
39
  exports.displayLanguageOption = displayLanguageOption;
@@ -61,6 +61,11 @@ exports.esphomeAddress = esphomeAddress;
61
61
  *
62
62
  * Two consequences shape this file: end-of-speech detection is ours (`vad.ts`), and the spoken reply
63
63
  * has to be reachable over HTTP (`mediaServer.ts`) rather than streamed down the socket.
64
+ *
65
+ * The first one also makes the **dialog mode** possible ({@link EsphomeConnection.setDialog}): the device streams as
66
+ * long as we do not end the utterance, so while nobody speaks the detector just starts over, and every reply asks the
67
+ * device to open its microphone again (`continue_conversation`). Talking goes on without a wake word until the mode
68
+ * is switched off, the device is stopped, or nobody said anything for {@link DIALOG_IDLE_MS}.
64
69
  */
65
70
  const net = __importStar(require("node:net"));
66
71
  const esphomeProto_1 = require("./esphomeProto");
@@ -69,6 +74,7 @@ const vad_1 = require("./vad");
69
74
  const speechAudio_1 = require("./speechAudio");
70
75
  const replyFormat_1 = require("./replyFormat");
71
76
  const captures_1 = require("./captures");
77
+ const tone_1 = require("./tone");
72
78
  /** `VoiceAssistantEvent` (api.proto) — the subset we emit. */
73
79
  const EVENT = {
74
80
  ERROR: 0,
@@ -198,6 +204,22 @@ const CONFIRM_GRACE_MS = 3000;
198
204
  * already answered, and is closed at once (unless our reply asked something again).
199
205
  */
200
206
  const IGNORE_FOLLOW_UP_MS = 15_000;
207
+ /**
208
+ * Dialog mode: nobody spoke for this much audio — the detector starts over on the audio that keeps coming (no new pipeline,
209
+ * the device does not notice), so its noise floor, its limits and the memory of the recording stay those of a request.
210
+ */
211
+ const DIALOG_WINDOW_MS = 10_000;
212
+ /** Dialog mode: the longest request. */
213
+ const DIALOG_MAX_SPEECH_MS = 20_000;
214
+ /** Dialog mode ends by itself when nothing was said for this long. */
215
+ exports.DIALOG_IDLE_MS = 5 * 60_000;
216
+ /** How often the dialog mode checks whether it ran idle. */
217
+ const DIALOG_CHECK_MS = 5000;
218
+ /**
219
+ * Dialog mode, nothing recognised (a cough, the TV): a reply of this much silence ends the run and makes the device
220
+ * open its microphone again — an ESPHome device does that only after a reply has played.
221
+ */
222
+ const DIALOG_PAUSE_MS = 250;
201
223
  /** "Yes" and "no" as a button answer is passed on: the words of the satellite's language, which pi-agent also takes. */
202
224
  const YES_NO = {
203
225
  en: ['Yes', 'No'],
@@ -365,6 +387,23 @@ class EsphomeSatellites {
365
387
  const target = this.connections.find(c => c.online && c.deviceName === device);
366
388
  return target ? target.mediaUrl(path) : null;
367
389
  }
390
+ /**
391
+ * Switch the dialog mode of one satellite: after every reply it listens again without a wake word. Switched on
392
+ * while the satellite is idle, `open` is played and the microphone opens after it (a request in progress re-opens
393
+ * it with its reply). False when the satellite is not connected.
394
+ */
395
+ setDialog(device, on, open) {
396
+ const target = this.connections.find(c => c.online && c.deviceName === device);
397
+ if (!target) {
398
+ return false;
399
+ }
400
+ target.setDialog(on, 'command', open);
401
+ return true;
402
+ }
403
+ /** Whether a satellite is in dialog mode. */
404
+ dialog(device) {
405
+ return !!this.connections.find(c => c.online && c.deviceName === device)?.dialog;
406
+ }
368
407
  /**
369
408
  * Mirror an assistant timer onto the satellites so they can show it on their own LED ring and ring
370
409
  * it themselves. `device` null broadcasts. Returns how many devices were told.
@@ -451,6 +490,11 @@ class EsphomeConnection {
451
490
  stoppedAt = 0;
452
491
  /** The display language was compared with ours since the last connect. */
453
492
  displayLanguageChecked = false;
493
+ /** Dialog mode: every reply opens the microphone again, see {@link setDialog}. */
494
+ dialogOn = false;
495
+ /** Dialog mode: when something was last recognised (or the mode was switched on). */
496
+ dialogHeardAt = 0;
497
+ dialogTimer = null;
454
498
  constructor(device, opts) {
455
499
  this.opts = opts;
456
500
  this.host = device.ip.trim();
@@ -520,6 +564,7 @@ class EsphomeConnection {
520
564
  this.runOpen = false;
521
565
  this.questionUntil = 0;
522
566
  this.ignoreFollowUpUntil = 0;
567
+ this.setDialog(false, 'offline');
523
568
  if (this.online) {
524
569
  this.opts.log.info(`ESPHome satellite offline: ${this.deviceName}`);
525
570
  }
@@ -549,6 +594,10 @@ class EsphomeConnection {
549
594
  clearTimeout(this.playbackTimer);
550
595
  this.playbackTimer = null;
551
596
  }
597
+ if (this.dialogTimer) {
598
+ clearInterval(this.dialogTimer);
599
+ this.dialogTimer = null;
600
+ }
552
601
  }
553
602
  setOffline() {
554
603
  if (this.online) {
@@ -900,44 +949,34 @@ class EsphomeConnection {
900
949
  // microphone carries the last wake word too. Should the user really have said the wake word, the utterance
901
950
  // is still the next one after the question — which is what pi-agent and askUser take as the answer anyway.
902
951
  const answersQuestion = Date.now() < this.questionUntil;
903
- const followUp = answersQuestion || !phrase;
904
- this.opts.log.debug(`ESPHome ${this.deviceName}: ${answersQuestion ? 'answer to the question' : followUp ? 'follow-up' : `wake "${phrase}"`}`);
952
+ // In dialog mode every microphone is the next turn: the phrase is the stale one of the last wake word.
953
+ const dialog = this.dialogOn;
954
+ const followUp = answersQuestion || !phrase || dialog;
955
+ this.opts.log.debug(`ESPHome ${this.deviceName}: ${answersQuestion
956
+ ? 'answer to the question'
957
+ : dialog
958
+ ? 'dialog'
959
+ : followUp
960
+ ? 'follow-up'
961
+ : `wake "${phrase}"`}`);
905
962
  const response = new esphomeProto_1.pb.VoiceAssistantResponse();
906
963
  response.setPort(0); // 0 = stream the audio over this socket
907
964
  response.setError(false);
908
965
  this.send(response);
909
- const timer = setTimeout(() => {
910
- this.opts.log.warn(`ESPHome ${this.deviceName}: no end of speech within ${PIPELINE_TIMEOUT_MS} ms`);
911
- void this.finishCapture('pipeline-timeout');
912
- }, PIPELINE_TIMEOUT_MS);
913
- timer.unref();
914
966
  const stallCheck = setInterval(() => this.checkStall(), STALL_CHECK_MS);
915
967
  stallCheck.unref();
916
- const silenceMs = this.opts.silenceMs || DEFAULT_SILENCE_MS;
917
968
  this.capture = {
918
969
  chunks: [],
919
- detector: new vad_1.SpeechDetector({
920
- sampleRate: MIC_SAMPLE_RATE,
921
- silenceMs,
922
- longSilenceMs: Math.round(silenceMs * LONG_PAUSE_FACTOR),
923
- longAfterMs: LONG_REQUEST_MS,
924
- // Microphone gain differs wildly between these devices, so fixed RMS levels do not
925
- // travel: derive them from the room instead, once the wake chirp is out of the way.
926
- skipMs: WAKE_CHIRP_MS,
927
- adaptive: true,
928
- startTimeoutMs: followUp ? NO_SPEECH_FOLLOW_UP_MS : NO_SPEECH_MS,
929
- minStartLevel: this.speechLevel || exports.DEFAULT_SPEECH_LEVEL,
930
- minEndLevel: Math.round((this.speechLevel || exports.DEFAULT_SPEECH_LEVEL) * SILENCE_SHARE),
931
- minSpeechMs: MIN_SPEECH_MS,
932
- }),
970
+ detector: this.speechDetector(followUp, dialog, WAKE_CHIRP_MS),
933
971
  conversationId: request.getConversationId(),
934
972
  wakeWord: followUp ? '' : phrase,
935
973
  answersQuestion,
936
- timer,
974
+ timer: this.pipelineTimer(dialog),
937
975
  stallCheck,
938
976
  startedAt: Date.now(),
939
977
  lastAudioAt: 0,
940
978
  closed: false,
979
+ dialog,
941
980
  };
942
981
  this.status('listening');
943
982
  this.event(EVENT.RUN_START);
@@ -947,6 +986,93 @@ class EsphomeConnection {
947
986
  this.event(EVENT.STT_START);
948
987
  this.event(EVENT.STT_VAD_START);
949
988
  }
989
+ /**
990
+ * End-of-speech detection for one recording. `skipMs`: the wake chirp at its start.
991
+ *
992
+ * Microphone gain differs wildly between these devices, so fixed RMS levels do not travel: the levels are derived
993
+ * from the room, once the chirp is out of the way. In dialog mode nobody may speak for a while — there the window
994
+ * starts over (see {@link onAudio}) instead of the run ending, and a request may take longer.
995
+ */
996
+ speechDetector(followUp, dialog, skipMs) {
997
+ const silenceMs = this.opts.silenceMs || DEFAULT_SILENCE_MS;
998
+ return new vad_1.SpeechDetector({
999
+ sampleRate: MIC_SAMPLE_RATE,
1000
+ silenceMs,
1001
+ longSilenceMs: Math.round(silenceMs * LONG_PAUSE_FACTOR),
1002
+ longAfterMs: LONG_REQUEST_MS,
1003
+ skipMs,
1004
+ adaptive: true,
1005
+ startTimeoutMs: dialog ? 0 : followUp ? NO_SPEECH_FOLLOW_UP_MS : NO_SPEECH_MS,
1006
+ maxMs: dialog ? DIALOG_WINDOW_MS + DIALOG_MAX_SPEECH_MS : undefined,
1007
+ minStartLevel: this.speechLevel || exports.DEFAULT_SPEECH_LEVEL,
1008
+ minEndLevel: Math.round((this.speechLevel || exports.DEFAULT_SPEECH_LEVEL) * SILENCE_SHARE),
1009
+ minSpeechMs: MIN_SPEECH_MS,
1010
+ });
1011
+ }
1012
+ /** Last resort for a recording that never ends; in dialog mode per window. */
1013
+ pipelineTimer(dialog) {
1014
+ const ms = dialog ? DIALOG_WINDOW_MS + DIALOG_MAX_SPEECH_MS + 5000 : PIPELINE_TIMEOUT_MS;
1015
+ const timer = setTimeout(() => {
1016
+ this.opts.log.warn(`ESPHome ${this.deviceName}: no end of speech within ${ms} ms`);
1017
+ void this.finishCapture('pipeline-timeout');
1018
+ }, ms);
1019
+ timer.unref();
1020
+ return timer;
1021
+ }
1022
+ /**
1023
+ * Dialog mode on or off. On: every reply asks the device to open its microphone again (`continue_conversation`),
1024
+ * and while nobody speaks the recording just goes on. Switched on while nothing runs, `open` is played as an
1025
+ * announcement that opens the microphone. Off: a microphone that hears nothing is closed now; a request being
1026
+ * answered closes it with its reply.
1027
+ */
1028
+ setDialog(on, reason, open) {
1029
+ if (this.dialogOn === on) {
1030
+ return;
1031
+ }
1032
+ this.dialogOn = on;
1033
+ this.dialogHeardAt = Date.now();
1034
+ if (this.dialogTimer) {
1035
+ clearInterval(this.dialogTimer);
1036
+ this.dialogTimer = null;
1037
+ }
1038
+ const why = reason === 'idle'
1039
+ ? ` (nothing said for ${exports.DIALOG_IDLE_MS / 60_000} min)`
1040
+ : reason === 'stop'
1041
+ ? ' (the device was stopped)'
1042
+ : reason === 'offline'
1043
+ ? ' (offline)'
1044
+ : reason === 'error'
1045
+ ? ' (the voice pipeline failed)'
1046
+ : '';
1047
+ this.opts.log.info(`ESPHome ${this.deviceName}: dialog mode ${on ? 'on' : 'off'}${why}`);
1048
+ this.opts.onDialog?.(this.deviceName, this.room, on, reason);
1049
+ if (on) {
1050
+ this.dialogTimer = setInterval(() => this.checkDialogIdle(), DIALOG_CHECK_MS);
1051
+ this.dialogTimer.unref();
1052
+ if (open && this.online && !this.capture && !this.runOpen) {
1053
+ 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
+ }
1055
+ return;
1056
+ }
1057
+ const capture = this.capture;
1058
+ if (capture?.dialog && !capture.detector.hearing) {
1059
+ void this.finishCapture('no-speech'); // nobody talks: close the microphone now
1060
+ }
1061
+ }
1062
+ get dialog() {
1063
+ return this.dialogOn;
1064
+ }
1065
+ /** Dialog mode: switch it off when nothing was said for a long time — but not while somebody speaks or is answered. */
1066
+ checkDialogIdle() {
1067
+ if (!this.dialogOn || Date.now() - this.dialogHeardAt < exports.DIALOG_IDLE_MS) {
1068
+ return;
1069
+ }
1070
+ const capture = this.capture;
1071
+ if (capture ? capture.detector.hearing : this.runOpen) {
1072
+ return;
1073
+ }
1074
+ this.setDialog(false, 'idle');
1075
+ }
950
1076
  /**
951
1077
  * The device asks to end the conversation (`VoiceAssistantRequest{start:false}`): a button, or the wake word
952
1078
  * said again while a request is running — that is how ESPHome's voice_assistant stops. While it waits for an
@@ -968,6 +1094,10 @@ class EsphomeConnection {
968
1094
  // was (state messages can be batched): the question stays open a moment longer for that report.
969
1095
  this.questionUntil = this.questionOpen() ? Math.max(this.questionUntil, Date.now() + CONFIRM_GRACE_MS) : 0;
970
1096
  this.abortCapture();
1097
+ if (Date.now() - this.errorSentAt >= ERROR_ECHO_MS) {
1098
+ // Stopping the device ends the dialog, too (a reply in progress is dropped below, so it re-opens nothing)
1099
+ this.setDialog(false, 'stop');
1100
+ }
971
1101
  if (running) {
972
1102
  this.run++; // whatever is still being answered stays silent
973
1103
  this.opts.log.debug(`ESPHome ${this.deviceName}: the device ended the conversation`);
@@ -996,11 +1126,24 @@ class EsphomeConnection {
996
1126
  void this.finishCapture(end);
997
1127
  return;
998
1128
  }
1129
+ if (capture.dialog && !capture.detector.hearing && capture.detector.analysedMs >= DIALOG_WINDOW_MS) {
1130
+ this.nextDialogWindow(capture);
1131
+ }
999
1132
  }
1000
1133
  if (audio.getEnd()) {
1001
1134
  void this.finishCapture('stream');
1002
1135
  }
1003
1136
  }
1137
+ /**
1138
+ * Dialog mode, nobody spoke during a window: forget it and start a new one on the audio that keeps coming. Only
1139
+ * while nothing is heard, so a word that just began is not cut.
1140
+ */
1141
+ nextDialogWindow(capture) {
1142
+ capture.chunks = [];
1143
+ capture.detector = this.speechDetector(true, true, 0);
1144
+ clearTimeout(capture.timer);
1145
+ capture.timer = this.pipelineTimer(true);
1146
+ }
1004
1147
  /** End a capture whose device stopped sending audio without ending the stream. */
1005
1148
  checkStall() {
1006
1149
  const capture = this.capture;
@@ -1091,8 +1234,20 @@ class EsphomeConnection {
1091
1234
  else {
1092
1235
  this.opts.log.debug(`ESPHome ${this.deviceName}: nothing but silence${end === 'no-speech' ? ' (nobody started speaking)' : ''} — dropping the utterance`);
1093
1236
  }
1094
- this.discard(capture, pcm, end === 'no-speech' ? 'no-speech' : 'silence', vad);
1237
+ if (capture.dialog && this.dialogOn && (end === 'timeout' || end === 'speech-end')) {
1238
+ // a long noise in dialog mode: listen on
1239
+ this.event(EVENT.INTENT_END, { continue_conversation: '1' });
1240
+ await this.reopenDialog(run);
1241
+ return;
1242
+ }
1243
+ if (!capture.dialog) {
1244
+ this.discard(capture, pcm, end === 'no-speech' ? 'no-speech' : 'silence', vad);
1245
+ }
1095
1246
  this.endWithoutRequest();
1247
+ if (capture.dialog) {
1248
+ // the device ended or stopped the stream itself: it does not want to listen any more
1249
+ this.setDialog(false, 'stop');
1250
+ }
1096
1251
  return;
1097
1252
  }
1098
1253
  this.status('processing');
@@ -1119,10 +1274,19 @@ class EsphomeConnection {
1119
1274
  if (capture.answersQuestion) {
1120
1275
  this.questionUntil = Math.max(this.questionUntil, Date.now() + CONFIRM_GRACE_MS);
1121
1276
  }
1277
+ if (capture.dialog && this.dialogOn) {
1278
+ // a cough, the TV: listen on, without a word about it
1279
+ this.event(EVENT.INTENT_END, { continue_conversation: '1' });
1280
+ await this.reopenDialog(run);
1281
+ return;
1282
+ }
1122
1283
  // No STT_END without text — like Home Assistant, which reports this case as an error only.
1123
1284
  this.endWithoutRequest();
1124
1285
  return;
1125
1286
  }
1287
+ if (capture.dialog) {
1288
+ this.dialogHeardAt = Date.now();
1289
+ }
1126
1290
  this.event(EVENT.STT_END, { text });
1127
1291
  this.event(EVENT.INTENT_START);
1128
1292
  const answer = (await this.opts.answer(text, {
@@ -1140,10 +1304,17 @@ class EsphomeConnection {
1140
1304
  const followUp = !!answer && this.opts.expectsFollowUp?.(answer, this.deviceName) === true;
1141
1305
  // Always say it, "0" included: ESPHome keeps the flag of the last INTENT_END that carried it, so after
1142
1306
  // one question every later reply re-opened the microphone (field report 2026-11-04). Home Assistant
1143
- // sends "0" just the same.
1144
- const conversation = { continue_conversation: followUp ? '1' : '0' };
1307
+ // sends "0" just the same. In dialog mode (switched on or off by this very request, too) always "1".
1308
+ const conversation = { continue_conversation: followUp || this.dialogOn ? '1' : '0' };
1145
1309
  this.event(EVENT.INTENT_END, conversation);
1146
1310
  if (!answer) {
1311
+ if (this.dialogOn) {
1312
+ // A command done without words (the confirmation tone instead): the tone is the reply here, after
1313
+ // it the device listens again. The adapter does not play it itself in dialog mode.
1314
+ const tone = (0, tone_1.confirmationTone)();
1315
+ await this.reopenDialog(run, tone.pcm, tone.sampleRate);
1316
+ return;
1317
+ }
1147
1318
  this.event(EVENT.RUN_END);
1148
1319
  this.status('idle');
1149
1320
  return;
@@ -1179,6 +1350,33 @@ class EsphomeConnection {
1179
1350
  this.event(EVENT.ERROR, { code: 'pipeline-failed', message: reason });
1180
1351
  this.event(EVENT.RUN_END);
1181
1352
  this.status('idle');
1353
+ this.setDialog(false, 'error');
1354
+ }
1355
+ }
1356
+ /**
1357
+ * Dialog mode: end the run with a reply that only makes the device listen again — silence when nothing was
1358
+ * recognised, else the given clip. ESPHome opens the microphone after a reply has played when the INTENT_END
1359
+ * (sent by the caller) said so; linux-voice-assistant reads the flag in RUN_END.
1360
+ */
1361
+ async reopenDialog(run, pcm, sampleRate = MIC_SAMPLE_RATE) {
1362
+ const clip = pcm ?? Buffer.alloc(Math.round((MIC_SAMPLE_RATE * DIALOG_PAUSE_MS) / 1000) * 2);
1363
+ try {
1364
+ const url = await this.publish(clip, sampleRate);
1365
+ if (run !== this.run) {
1366
+ return;
1367
+ }
1368
+ this.status('speaking');
1369
+ this.event(EVENT.TTS_START, { text: '' });
1370
+ this.event(EVENT.TTS_END, { url });
1371
+ this.event(EVENT.RUN_END, { continue_conversation: '1' });
1372
+ this.armPlaybackTimeout();
1373
+ }
1374
+ catch (e) {
1375
+ this.opts.log.warn(`ESPHome ${this.deviceName}: dialog cannot go on — ${e.message}`);
1376
+ if (run === this.run) {
1377
+ this.endWithoutRequest();
1378
+ this.setDialog(false, 'error');
1379
+ }
1182
1380
  }
1183
1381
  }
1184
1382
  /**
@@ -1268,7 +1466,7 @@ class EsphomeConnection {
1268
1466
  * Speak a ready PCM buffer on this device (timers, alarms, `tts.text`, jingles). With
1269
1467
  * `startConversation` the microphone opens once the clip has played, to catch the answer to a question.
1270
1468
  */
1271
- async announce(pcm, sampleRate, startConversation = false, text = '') {
1469
+ async announce(pcm, sampleRate, startConversation = false, text = '', question = true) {
1272
1470
  if (!this.online || !pcm.length) {
1273
1471
  return;
1274
1472
  }
@@ -1281,9 +1479,11 @@ class EsphomeConnection {
1281
1479
  // only the microphone stays shut, so there is nothing to guard here.
1282
1480
  request.setStartConversation(startConversation);
1283
1481
  if (startConversation) {
1284
- // A question: the microphone the device opens after it is wanted, and a button press answers it
1482
+ // The microphone the device opens after it is wanted; for a question a button press answers it, too
1285
1483
  this.ignoreFollowUpUntil = 0;
1286
- this.questionUntil = Date.now() + (pcm.length / 2 / sampleRate) * 1000 + QUESTION_OPEN_MS;
1484
+ if (question) {
1485
+ this.questionUntil = Date.now() + (pcm.length / 2 / sampleRate) * 1000 + QUESTION_OPEN_MS;
1486
+ }
1287
1487
  }
1288
1488
  this.status('speaking');
1289
1489
  this.send(request);