esphome-ts 5.1.0 → 5.1.2

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/dist/index.d.ts CHANGED
@@ -245,6 +245,7 @@ interface CoverEntity extends ListEntity {
245
245
  assumedState: boolean;
246
246
  supportsPosition: boolean;
247
247
  supportsTilt: boolean;
248
+ supportsStop?: boolean;
248
249
  deviceClass: string;
249
250
  }
250
251
  interface LightEntity extends ListEntity {
@@ -309,6 +310,7 @@ declare class EspDevice {
309
310
  private readonly client;
310
311
  private readonly stateEvents$;
311
312
  deviceInfo?: DeviceInfoResponse;
313
+ private readonly apiVersion;
312
314
  readonly components: {
313
315
  [key: string]: BaseComponent;
314
316
  };
@@ -333,6 +335,12 @@ declare class EspDevice {
333
335
  options?: {
334
336
  connection?: Connection;
335
337
  });
338
+ private watchDeviceMessages;
339
+ private handleDeviceMessage;
340
+ private watchConnection;
341
+ private handshake;
342
+ private retryFailedConnections;
343
+ private createLivenessObservable;
336
344
  /**
337
345
  * Provides the reconnect cadence used while the device is unreachable.
338
346
  * Calling this again replaces the previously provided retry signal, so
@@ -389,7 +397,13 @@ declare class BinarySensorComponent extends BaseComponent<BinarySensorEntity, Bi
389
397
  get type(): ComponentType;
390
398
  }
391
399
 
400
+ interface ApiVersion {
401
+ major: number;
402
+ minor: number;
403
+ }
392
404
  declare class CoverComponent extends BaseComponent<CoverEntity, CoverStateEvent> {
405
+ private readonly apiVersion;
406
+ constructor(listEntity: CoverEntity, state: Observable<CoverStateEvent>, commandInterface: CommandInterface, apiVersion?: ApiVersion);
393
407
  open(): void;
394
408
  close(): void;
395
409
  stop(): void;
@@ -398,10 +412,12 @@ declare class CoverComponent extends BaseComponent<CoverEntity, CoverStateEvent>
398
412
  get type(): ComponentType;
399
413
  get assumedState(): boolean;
400
414
  get supportsPosition(): boolean;
415
+ get supportsStop(): boolean;
401
416
  get supportsTilt(): boolean;
402
417
  /**
403
- * Current position between 0 (closed) and 1 (open). Undefined until the
404
- * first state was received or when the cover does not support positions.
418
+ * Current position between 0 (closed) and 1 (open). This is feedback from
419
+ * the state response and is independent of position-control support. API
420
+ * versions before 1.1 do not report position values.
405
421
  */
406
422
  get position(): number | undefined;
407
423
  /**
@@ -410,15 +426,13 @@ declare class CoverComponent extends BaseComponent<CoverEntity, CoverStateEvent>
410
426
  */
411
427
  get tilt(): number | undefined;
412
428
  /**
413
- * Whether the cover is fully closed. Derived from the position field the
414
- * device always sends, exactly like aioesphomeapi derives is_closed
415
- * (position == 0). Undefined until the first state was received.
429
+ * Whether the cover is fully closed. API versions before 1.1 report this
430
+ * using the legacy state enum; newer versions report the position.
416
431
  */
417
432
  get isClosed(): boolean | undefined;
418
433
  /**
419
- * Whether the cover is fully open. Derived from the position field the
420
- * device always sends. Undefined until the first state was received; a
421
- * partially open cover is neither open nor closed.
434
+ * Whether the cover is fully open. Uses the legacy state before API 1.1
435
+ * and position thereafter; a partially open cover is neither open nor closed.
422
436
  */
423
437
  get isOpen(): boolean | undefined;
424
438
  /**
@@ -426,6 +440,8 @@ declare class CoverComponent extends BaseComponent<CoverEntity, CoverStateEvent>
426
440
  * received.
427
441
  */
428
442
  get operation(): CoverOperation | undefined;
443
+ private get usesLegacyProtocol();
444
+ private isApiVersionAtLeast;
429
445
  private sendCommand;
430
446
  }
431
447
 
package/dist/index.js CHANGED
@@ -1002,7 +1002,8 @@ function createBaseListEntitiesCoverResponse() {
1002
1002
  assumedState: false,
1003
1003
  supportsPosition: false,
1004
1004
  supportsTilt: false,
1005
- deviceClass: ""
1005
+ deviceClass: "",
1006
+ supportsStop: false
1006
1007
  };
1007
1008
  }
1008
1009
  var ListEntitiesCoverResponse = {
@@ -1031,6 +1032,9 @@ var ListEntitiesCoverResponse = {
1031
1032
  if (message.deviceClass !== "") {
1032
1033
  writer.uint32(66).string(message.deviceClass);
1033
1034
  }
1035
+ if (message.supportsStop !== false) {
1036
+ writer.uint32(96).bool(message.supportsStop);
1037
+ }
1034
1038
  return writer;
1035
1039
  },
1036
1040
  decode(input, length) {
@@ -1102,6 +1106,13 @@ var ListEntitiesCoverResponse = {
1102
1106
  message.deviceClass = reader.string();
1103
1107
  continue;
1104
1108
  }
1109
+ case 12: {
1110
+ if (tag !== 96) {
1111
+ break;
1112
+ }
1113
+ message.supportsStop = reader.bool();
1114
+ continue;
1115
+ }
1105
1116
  }
1106
1117
  if ((tag & 7) === 4 || tag === 0) {
1107
1118
  break;
@@ -1122,7 +1133,8 @@ var ListEntitiesCoverResponse = {
1122
1133
  assumedState: isSet(object.assumedState) ? globalThis.Boolean(object.assumedState) : isSet(object.assumed_state) ? globalThis.Boolean(object.assumed_state) : false,
1123
1134
  supportsPosition: isSet(object.supportsPosition) ? globalThis.Boolean(object.supportsPosition) : isSet(object.supports_position) ? globalThis.Boolean(object.supports_position) : false,
1124
1135
  supportsTilt: isSet(object.supportsTilt) ? globalThis.Boolean(object.supportsTilt) : isSet(object.supports_tilt) ? globalThis.Boolean(object.supports_tilt) : false,
1125
- deviceClass: isSet(object.deviceClass) ? globalThis.String(object.deviceClass) : isSet(object.device_class) ? globalThis.String(object.device_class) : ""
1136
+ deviceClass: isSet(object.deviceClass) ? globalThis.String(object.deviceClass) : isSet(object.device_class) ? globalThis.String(object.device_class) : "",
1137
+ supportsStop: isSet(object.supportsStop) ? globalThis.Boolean(object.supportsStop) : isSet(object.supports_stop) ? globalThis.Boolean(object.supports_stop) : false
1126
1138
  };
1127
1139
  },
1128
1140
  toJSON(message) {
@@ -1151,6 +1163,9 @@ var ListEntitiesCoverResponse = {
1151
1163
  if (message.deviceClass !== "") {
1152
1164
  obj.deviceClass = message.deviceClass;
1153
1165
  }
1166
+ if (message.supportsStop !== false) {
1167
+ obj.supportsStop = message.supportsStop;
1168
+ }
1154
1169
  return obj;
1155
1170
  },
1156
1171
  create(base) {
@@ -1166,6 +1181,7 @@ var ListEntitiesCoverResponse = {
1166
1181
  message.supportsPosition = object.supportsPosition ?? false;
1167
1182
  message.supportsTilt = object.supportsTilt ?? false;
1168
1183
  message.deviceClass = object.deviceClass ?? "";
1184
+ message.supportsStop = object.supportsStop ?? false;
1169
1185
  return message;
1170
1186
  }
1171
1187
  };
@@ -2806,7 +2822,6 @@ function isSet(value) {
2806
2822
 
2807
2823
  // src/api/espSocket.ts
2808
2824
  import {
2809
- EMPTY,
2810
2825
  filter,
2811
2826
  from,
2812
2827
  merge,
@@ -2816,6 +2831,7 @@ import {
2816
2831
  switchMap,
2817
2832
  take as take2,
2818
2833
  takeUntil as takeUntil2,
2834
+ tap as tap2,
2819
2835
  timeout
2820
2836
  } from "rxjs";
2821
2837
 
@@ -3012,22 +3028,62 @@ var TcpConnection = class {
3012
3028
  };
3013
3029
 
3014
3030
  // src/api/framer.ts
3031
+ var MAX_PAYLOAD_SIZE = 65535;
3032
+ var MAX_VARINT_BYTES = 5;
3033
+ var MAX_MESSAGE_TYPE = 65535;
3034
+ var encodeVarint = (value) => {
3035
+ const bytes = [];
3036
+ while (value >= 128) {
3037
+ bytes.push(value & 127 | 128);
3038
+ value = Math.floor(value / 128);
3039
+ }
3040
+ bytes.push(value);
3041
+ return bytes;
3042
+ };
3015
3043
  var encodeFrame = (type, payload) => {
3016
- if (payload.length > 255) {
3017
- throw new RangeError(`frame payload exceeds wire limit: ${payload.length} > 255 bytes`);
3044
+ const messageType = Number(type);
3045
+ if (payload.length > MAX_PAYLOAD_SIZE) {
3046
+ throw new RangeError(`frame payload exceeds wire limit: ${payload.length} > ${MAX_PAYLOAD_SIZE} bytes`);
3047
+ }
3048
+ if (!Number.isSafeInteger(messageType) || messageType < 0 || messageType > MAX_MESSAGE_TYPE) {
3049
+ throw new RangeError(`frame message type must be an unsigned 16-bit integer: ${messageType}`);
3018
3050
  }
3019
- const frame = new Uint8Array(3 + payload.length);
3051
+ const lengthBytes = encodeVarint(payload.length);
3052
+ const typeBytes = encodeVarint(messageType);
3053
+ const frame = new Uint8Array(1 + lengthBytes.length + typeBytes.length + payload.length);
3020
3054
  frame[0] = 0;
3021
- frame[1] = payload.length;
3022
- frame[2] = type;
3023
- frame.set(payload, 3);
3055
+ frame.set(lengthBytes, 1);
3056
+ frame.set(typeBytes, 1 + lengthBytes.length);
3057
+ frame.set(payload, 1 + lengthBytes.length + typeBytes.length);
3024
3058
  return frame;
3025
3059
  };
3060
+ var decodeVarint = (buffer, offset) => {
3061
+ let value = 0;
3062
+ let multiplier = 1;
3063
+ for (let index = 0; index < MAX_VARINT_BYTES; index++) {
3064
+ const position = offset + index;
3065
+ if (position >= buffer.length) {
3066
+ return { status: "incomplete" };
3067
+ }
3068
+ const byte = buffer[position];
3069
+ if (index === MAX_VARINT_BYTES - 1 && (byte & 240) !== 0) {
3070
+ return { status: "invalid" };
3071
+ }
3072
+ value += (byte & 127) * multiplier;
3073
+ if ((byte & 128) === 0) {
3074
+ return { status: "value", value, next: position + 1 };
3075
+ }
3076
+ multiplier *= 128;
3077
+ }
3078
+ return { status: "invalid" };
3079
+ };
3026
3080
  var createFrameParser = () => {
3027
3081
  let buffer = Buffer.alloc(0);
3028
3082
  return {
3029
3083
  push(chunk) {
3030
- buffer = Buffer.concat([buffer, chunk]);
3084
+ if (chunk.length > 0) {
3085
+ buffer = Buffer.concat([buffer, chunk]);
3086
+ }
3031
3087
  const frames = [];
3032
3088
  while (buffer.length > 0) {
3033
3089
  if (buffer[0] !== 0) {
@@ -3035,18 +3091,33 @@ var createFrameParser = () => {
3035
3091
  buffer = sync === -1 ? Buffer.alloc(0) : buffer.subarray(sync);
3036
3092
  continue;
3037
3093
  }
3038
- if (buffer.length < 3) {
3094
+ const length = decodeVarint(buffer, 1);
3095
+ if (length.status === "incomplete") {
3039
3096
  break;
3040
3097
  }
3041
- const total = 3 + buffer[1];
3042
- if (buffer.length < total) {
3098
+ if (length.status === "invalid" || length.value > MAX_PAYLOAD_SIZE) {
3099
+ const sync = buffer.indexOf(0, 1);
3100
+ buffer = sync === -1 ? Buffer.alloc(0) : buffer.subarray(sync);
3101
+ continue;
3102
+ }
3103
+ const type = decodeVarint(buffer, length.next);
3104
+ if (type.status === "incomplete") {
3105
+ break;
3106
+ }
3107
+ if (type.status === "invalid" || type.value > MAX_MESSAGE_TYPE) {
3108
+ const sync = buffer.indexOf(0, 1);
3109
+ buffer = sync === -1 ? Buffer.alloc(0) : buffer.subarray(sync);
3110
+ continue;
3111
+ }
3112
+ const end = type.next + length.value;
3113
+ if (buffer.length < end) {
3043
3114
  break;
3044
3115
  }
3045
3116
  frames.push({
3046
- type: buffer[2],
3047
- payload: new Uint8Array(buffer.subarray(3, total))
3117
+ type: type.value,
3118
+ payload: new Uint8Array(buffer.subarray(type.next, end))
3048
3119
  });
3049
- buffer = buffer.subarray(total);
3120
+ buffer = buffer.subarray(end);
3050
3121
  }
3051
3122
  return frames;
3052
3123
  }
@@ -3093,10 +3164,9 @@ var EspSocket = class {
3093
3164
  timeout(5e3),
3094
3165
  filter(isTrue),
3095
3166
  take2(1),
3096
- switchMap(() => {
3167
+ tap2(() => {
3097
3168
  const final = encodeFrame(type, payload);
3098
3169
  this.connection.write(final);
3099
- return EMPTY;
3100
3170
  }),
3101
3171
  // terminate() kills a pending send, but open() deliberately does
3102
3172
  // NOT: a command issued during a blip rides the reconnect within
@@ -3112,14 +3182,14 @@ var EspSocket = class {
3112
3182
  };
3113
3183
 
3114
3184
  // src/api/client.ts
3115
- import { filter as filter2, map, of, Subscription, take as take3, tap as tap2 } from "rxjs";
3185
+ import { filter as filter2, map, of, Subscription, take as take3, tap as tap3 } from "rxjs";
3116
3186
  var Client = class {
3117
3187
  constructor(socket) {
3118
3188
  this.socket = socket;
3119
3189
  this.subscription = new Subscription();
3120
3190
  this.subscription.add(
3121
3191
  this.socket.espData$.pipe(
3122
- tap2((data) => {
3192
+ tap3((data) => {
3123
3193
  if (data.type === 7 /* PingRequest */) {
3124
3194
  this.socket.sendEspMessage(8 /* PingResponse */, PingResponse.encode({}).finish());
3125
3195
  }
@@ -3199,7 +3269,7 @@ import {
3199
3269
  Subject as Subject3,
3200
3270
  take as take4,
3201
3271
  takeUntil as takeUntil3,
3202
- tap as tap3
3272
+ tap as tap4
3203
3273
  } from "rxjs";
3204
3274
  var shallowEqualStates = (previous, current) => {
3205
3275
  const previousKeys = Object.keys(previous);
@@ -3223,7 +3293,7 @@ var BaseComponent = class {
3223
3293
  this.commandInPipeline.pipe(
3224
3294
  debounceTime(30 * 1e3),
3225
3295
  filter3(isTrue),
3226
- tap3(() => this.commandInPipeline.next(false)),
3296
+ tap4(() => this.commandInPipeline.next(false)),
3227
3297
  takeUntil3(this.teardown)
3228
3298
  ).subscribe();
3229
3299
  }
@@ -3237,8 +3307,8 @@ var BaseComponent = class {
3237
3307
  provideStateObservable(state$) {
3238
3308
  this.terminatePreviousStateSubscription.next();
3239
3309
  state$.pipe(
3240
- tap3((state) => this.state.next(state)),
3241
- tap3(() => this.commandInPipeline.next(false)),
3310
+ tap4((state) => this.state.next(state)),
3311
+ tap4(() => this.commandInPipeline.next(false)),
3242
3312
  takeUntil3(this.terminatePreviousStateSubscription),
3243
3313
  takeUntil3(this.teardown)
3244
3314
  ).subscribe();
@@ -3262,7 +3332,7 @@ var BaseComponent = class {
3262
3332
  this.commandInPipeline.pipe(
3263
3333
  filter3((x) => !x || disableSerialise),
3264
3334
  take4(1),
3265
- tap3(() => {
3335
+ tap4(() => {
3266
3336
  this.commandInterface.sendEspMessage(type, dataFn());
3267
3337
  this.commandInPipeline.next(true);
3268
3338
  }),
@@ -3315,24 +3385,46 @@ var BinarySensorComponent = class extends BaseComponent {
3315
3385
  };
3316
3386
 
3317
3387
  // src/components/cover.ts
3388
+ import "rxjs";
3389
+ var DEFAULT_API_VERSION = { major: 1, minor: 8 };
3318
3390
  var CoverComponent = class extends BaseComponent {
3391
+ constructor(listEntity, state, commandInterface, apiVersion = DEFAULT_API_VERSION) {
3392
+ super(listEntity, state, commandInterface);
3393
+ this.apiVersion = apiVersion;
3394
+ }
3395
+ apiVersion;
3319
3396
  open() {
3320
- this.sendCommand({ position: 1 });
3397
+ if (this.usesLegacyProtocol) {
3398
+ this.sendCommand({ legacyCommand: 0 /* LEGACY_COVER_COMMAND_OPEN */ });
3399
+ } else {
3400
+ this.sendCommand({ position: 1 });
3401
+ }
3321
3402
  }
3322
3403
  close() {
3323
- this.sendCommand({ position: 0 });
3404
+ if (this.usesLegacyProtocol) {
3405
+ this.sendCommand({ legacyCommand: 1 /* LEGACY_COVER_COMMAND_CLOSE */ });
3406
+ } else {
3407
+ this.sendCommand({ position: 0 });
3408
+ }
3324
3409
  }
3325
3410
  stop() {
3326
- this.sendCommand({ stop: true });
3411
+ if (!this.supportsStop) {
3412
+ return;
3413
+ }
3414
+ if (this.usesLegacyProtocol) {
3415
+ this.sendCommand({ legacyCommand: 2 /* LEGACY_COVER_COMMAND_STOP */ });
3416
+ } else {
3417
+ this.sendCommand({ stop: true });
3418
+ }
3327
3419
  }
3328
3420
  setPosition(position) {
3329
- if (!this.supportsPosition) {
3421
+ if (this.usesLegacyProtocol || !this.supportsPosition) {
3330
3422
  return;
3331
3423
  }
3332
3424
  this.sendCommand({ position });
3333
3425
  }
3334
3426
  setTilt(tilt) {
3335
- if (!this.supportsTilt) {
3427
+ if (this.usesLegacyProtocol || !this.supportsTilt) {
3336
3428
  return;
3337
3429
  }
3338
3430
  this.sendCommand({ tilt });
@@ -3344,17 +3436,21 @@ var CoverComponent = class extends BaseComponent {
3344
3436
  return this.listEntity.assumedState;
3345
3437
  }
3346
3438
  get supportsPosition() {
3347
- return this.listEntity.supportsPosition;
3439
+ return this.isApiVersionAtLeast(1, 1) && this.listEntity.supportsPosition;
3440
+ }
3441
+ get supportsStop() {
3442
+ return !this.isApiVersionAtLeast(1, 8) || (this.listEntity.supportsStop ?? false);
3348
3443
  }
3349
3444
  get supportsTilt() {
3350
- return this.listEntity.supportsTilt;
3445
+ return this.isApiVersionAtLeast(1, 1) && this.listEntity.supportsTilt;
3351
3446
  }
3352
3447
  /**
3353
- * Current position between 0 (closed) and 1 (open). Undefined until the
3354
- * first state was received or when the cover does not support positions.
3448
+ * Current position between 0 (closed) and 1 (open). This is feedback from
3449
+ * the state response and is independent of position-control support. API
3450
+ * versions before 1.1 do not report position values.
3355
3451
  */
3356
3452
  get position() {
3357
- if (!this.supportsPosition) {
3453
+ if (this.usesLegacyProtocol) {
3358
3454
  return void 0;
3359
3455
  }
3360
3456
  return this.state.getValue()?.position;
@@ -3370,21 +3466,33 @@ var CoverComponent = class extends BaseComponent {
3370
3466
  return this.state.getValue()?.tilt;
3371
3467
  }
3372
3468
  /**
3373
- * Whether the cover is fully closed. Derived from the position field the
3374
- * device always sends, exactly like aioesphomeapi derives is_closed
3375
- * (position == 0). Undefined until the first state was received.
3469
+ * Whether the cover is fully closed. API versions before 1.1 report this
3470
+ * using the legacy state enum; newer versions report the position.
3376
3471
  */
3377
3472
  get isClosed() {
3378
- const position = this.state.getValue()?.position;
3473
+ const state = this.state.getValue();
3474
+ if (state === void 0) {
3475
+ return void 0;
3476
+ }
3477
+ if (this.usesLegacyProtocol) {
3478
+ return state.legacyState === 1 /* LEGACY_COVER_STATE_CLOSED */;
3479
+ }
3480
+ const position = state.position;
3379
3481
  return position === void 0 ? void 0 : position === 0;
3380
3482
  }
3381
3483
  /**
3382
- * Whether the cover is fully open. Derived from the position field the
3383
- * device always sends. Undefined until the first state was received; a
3384
- * partially open cover is neither open nor closed.
3484
+ * Whether the cover is fully open. Uses the legacy state before API 1.1
3485
+ * and position thereafter; a partially open cover is neither open nor closed.
3385
3486
  */
3386
3487
  get isOpen() {
3387
- const position = this.state.getValue()?.position;
3488
+ const state = this.state.getValue();
3489
+ if (state === void 0) {
3490
+ return void 0;
3491
+ }
3492
+ if (this.usesLegacyProtocol) {
3493
+ return state.legacyState === 0 /* LEGACY_COVER_STATE_OPEN */;
3494
+ }
3495
+ const position = state.position;
3388
3496
  return position === void 0 ? void 0 : position === 1;
3389
3497
  }
3390
3498
  /**
@@ -3394,18 +3502,21 @@ var CoverComponent = class extends BaseComponent {
3394
3502
  get operation() {
3395
3503
  return this.state.getValue()?.currentOperation;
3396
3504
  }
3505
+ get usesLegacyProtocol() {
3506
+ return !this.isApiVersionAtLeast(1, 1);
3507
+ }
3508
+ isApiVersionAtLeast(major, minor) {
3509
+ return this.apiVersion.major > major || this.apiVersion.major === major && this.apiVersion.minor >= minor;
3510
+ }
3397
3511
  sendCommand(command) {
3398
3512
  this.queueCommand(
3399
3513
  30 /* CoverCommandRequest */,
3400
3514
  () => CoverCommandRequest.encode({
3401
3515
  key: this.key,
3402
- // The legacy command fields are dead: Home Assistant last
3403
- // sent them to pre-2019 devices and firmware dropped their
3404
- // handling in 2025.8.0. Only the values below reach the
3405
- // wire; these two are wire-inert defaults that satisfy
3406
- // the generated message type.
3407
- hasLegacyCommand: false,
3408
- legacyCommand: 0 /* LEGACY_COVER_COMMAND_OPEN */,
3516
+ // API 1.0 predates position/stop commands; retain the
3517
+ // legacy enum command for those firmware versions.
3518
+ hasLegacyCommand: command.legacyCommand !== void 0,
3519
+ legacyCommand: command.legacyCommand ?? 0 /* LEGACY_COVER_COMMAND_OPEN */,
3409
3520
  hasPosition: command.position !== void 0,
3410
3521
  position: command.position ?? 0,
3411
3522
  hasTilt: command.tilt !== void 0,
@@ -3662,66 +3773,119 @@ var stateParser = (data) => {
3662
3773
  }
3663
3774
  return void 0;
3664
3775
  };
3665
- var createComponents = (data, stateEvents$, connection, knownComponents) => {
3776
+ var createComponents = (data, stateEvents$, connection, knownComponents, apiVersion = { major: 1, minor: 8 }) => {
3777
+ const identity = (objectId, key) => {
3778
+ const knownById = knownComponents instanceof Set ? void 0 : knownComponents;
3779
+ const knownIds = knownComponents instanceof Set ? knownComponents : void 0;
3780
+ if (knownById) {
3781
+ for (const [knownId, knownKey2] of knownById) {
3782
+ if (knownKey2 === key) {
3783
+ return {
3784
+ id: knownId,
3785
+ fallback: objectId.length === 0,
3786
+ known: true
3787
+ };
3788
+ }
3789
+ }
3790
+ }
3791
+ let fallback = objectId.length === 0;
3792
+ let id = fallback ? fallbackEntityId(key) : objectId;
3793
+ const knownKey = (candidate) => knownById?.get(candidate);
3794
+ const isKnown = (candidate) => knownById ? knownKey(candidate) === key : knownIds?.has(candidate) ?? false;
3795
+ if (knownById && knownById.has(id) && !isKnown(id)) {
3796
+ fallback = true;
3797
+ id = fallbackEntityId(key);
3798
+ let suffix = 1;
3799
+ const baseId = id;
3800
+ while (knownById.has(id)) id = `${baseId}_${suffix++}`;
3801
+ }
3802
+ return { id, fallback, known: isKnown(id) };
3803
+ };
3666
3804
  switch (data.type) {
3667
3805
  case 12 /* ListEntitiesBinarySensorResponse */: {
3668
3806
  const response = ListEntitiesBinarySensorResponse.decode(data.payload);
3669
3807
  const state$ = transformStates(stateEvents$, response);
3670
- return knownComponents.has(response.objectId) ? {
3671
- id: response.objectId,
3808
+ const entity = identity(response.objectId, response.key);
3809
+ return entity.known ? {
3810
+ id: entity.id,
3811
+ key: response.key,
3812
+ fallback: entity.fallback,
3672
3813
  state$
3673
3814
  } : {
3674
- id: response.objectId,
3815
+ id: entity.id,
3816
+ key: response.key,
3817
+ fallback: entity.fallback,
3675
3818
  component: new BinarySensorComponent(response, state$, emptyCommandInterface)
3676
3819
  };
3677
3820
  }
3678
3821
  case 13 /* ListEntitiesCoverResponse */: {
3679
3822
  const response = ListEntitiesCoverResponse.decode(data.payload);
3680
3823
  const state$ = transformStates(stateEvents$, response);
3681
- return knownComponents.has(response.objectId) ? {
3682
- id: response.objectId,
3824
+ const entity = identity(response.objectId, response.key);
3825
+ return entity.known ? {
3826
+ id: entity.id,
3827
+ key: response.key,
3828
+ fallback: entity.fallback,
3683
3829
  state$
3684
3830
  } : {
3685
- id: response.objectId,
3686
- component: new CoverComponent(response, state$, connection)
3831
+ id: entity.id,
3832
+ key: response.key,
3833
+ fallback: entity.fallback,
3834
+ component: new CoverComponent(response, state$, connection, apiVersion)
3687
3835
  };
3688
3836
  }
3689
3837
  case 17 /* ListEntitiesSwitchResponse */: {
3690
3838
  const response = ListEntitiesSwitchResponse.decode(data.payload);
3691
3839
  const state$ = transformStates(stateEvents$, response);
3692
- return knownComponents.has(response.objectId) ? {
3693
- id: response.objectId,
3840
+ const entity = identity(response.objectId, response.key);
3841
+ return entity.known ? {
3842
+ id: entity.id,
3843
+ key: response.key,
3844
+ fallback: entity.fallback,
3694
3845
  state$
3695
3846
  } : {
3696
- id: response.objectId,
3847
+ id: entity.id,
3848
+ key: response.key,
3849
+ fallback: entity.fallback,
3697
3850
  component: new SwitchComponent(response, state$, connection)
3698
3851
  };
3699
3852
  }
3700
3853
  case 15 /* ListEntitiesLightResponse */: {
3701
3854
  const response = ListEntitiesLightResponse.decode(data.payload);
3702
3855
  const state$ = transformStates(stateEvents$, response);
3703
- return knownComponents.has(response.objectId) ? {
3704
- id: response.objectId,
3856
+ const entity = identity(response.objectId, response.key);
3857
+ return entity.known ? {
3858
+ id: entity.id,
3859
+ key: response.key,
3860
+ fallback: entity.fallback,
3705
3861
  state$
3706
3862
  } : {
3707
- id: response.objectId,
3863
+ id: entity.id,
3864
+ key: response.key,
3865
+ fallback: entity.fallback,
3708
3866
  component: new LightComponent(response, state$, connection)
3709
3867
  };
3710
3868
  }
3711
3869
  case 16 /* ListEntitiesSensorResponse */: {
3712
3870
  const response = ListEntitiesSensorResponse.decode(data.payload);
3713
3871
  const state$ = transformStates(stateEvents$, response);
3714
- return knownComponents.has(response.objectId) ? {
3715
- id: response.objectId,
3872
+ const entity = identity(response.objectId, response.key);
3873
+ return entity.known ? {
3874
+ id: entity.id,
3875
+ key: response.key,
3876
+ fallback: entity.fallback,
3716
3877
  state$
3717
3878
  } : {
3718
- id: response.objectId,
3879
+ id: entity.id,
3880
+ key: response.key,
3881
+ fallback: entity.fallback,
3719
3882
  component: new SensorComponent(response, state$, emptyCommandInterface)
3720
3883
  };
3721
3884
  }
3722
3885
  }
3723
3886
  return { id: "" };
3724
3887
  };
3888
+ var fallbackEntityId = (key) => `__esphome_entity_key_${key}`;
3725
3889
  var emptyCommandInterface = {
3726
3890
  sendEspMessage: () => void 0
3727
3891
  };
@@ -3752,7 +3916,7 @@ import {
3752
3916
  concat,
3753
3917
  defer,
3754
3918
  distinctUntilChanged as distinctUntilChanged2,
3755
- EMPTY as EMPTY2,
3919
+ EMPTY,
3756
3920
  filter as filter5,
3757
3921
  map as map2,
3758
3922
  merge as merge2,
@@ -3764,7 +3928,7 @@ import {
3764
3928
  Subscription as Subscription2,
3765
3929
  switchMap as switchMap2,
3766
3930
  takeUntil as takeUntil4,
3767
- tap as tap4,
3931
+ tap as tap5,
3768
3932
  timer
3769
3933
  } from "rxjs";
3770
3934
  var PING_TIMEOUT = 90 * 1e3;
@@ -3797,80 +3961,10 @@ var EspDevice = class {
3797
3961
  // component re-runs the filter+decode chain for the same state frame.
3798
3962
  share2()
3799
3963
  );
3800
- this.subscription.add(
3801
- this.socket.espData$.pipe(
3802
- tap4((data) => {
3803
- try {
3804
- if (listResponses.has(data.type)) {
3805
- this.parseListResponse(data);
3806
- } else if (data.type === 10 /* DeviceInfoResponse */) {
3807
- this.deviceInfo = DeviceInfoResponse.decode(data.payload);
3808
- }
3809
- } catch (error) {
3810
- this.errors.next(error);
3811
- }
3812
- })
3813
- ).subscribe()
3814
- );
3815
- this.subscription.add(
3816
- this.socket.connected$.pipe(
3817
- distinctUntilChanged2(),
3818
- tap4((connected) => {
3819
- if (!connected && !this.passwordRejected) {
3820
- this.socket.open();
3821
- }
3822
- }),
3823
- filter5((connected) => connected && !this.passwordRejected),
3824
- switchMap2(
3825
- () => (
3826
- // defer() re-runs this factory on every retry:
3827
- // Client.request() sends eagerly when called (not on
3828
- // subscription), so without it a retried handshake
3829
- // would never put a fresh HelloRequest on the wire —
3830
- // and a real device only answers HelloRequest, never
3831
- // speaks first.
3832
- defer(() => this.client.hello({ clientInfo: "esphome-ts" })).pipe(
3833
- switchMap2(() => this.client.connect({ password })),
3834
- map2((response) => {
3835
- if (response.invalidPassword) {
3836
- throw new InvalidPasswordError(this.host);
3837
- }
3838
- return response;
3839
- }),
3840
- switchMap2(() => this.client.deviceInfo()),
3841
- switchMap2(() => this.client.listEntities()),
3842
- switchMap2(() => this.client.subscribeStateChange()),
3843
- retry({
3844
- delay: (error) => {
3845
- this.errors.next(error);
3846
- if (error instanceof InvalidPasswordError) {
3847
- this.passwordRejected = true;
3848
- this.socket.terminate();
3849
- return EMPTY2;
3850
- }
3851
- return timer(RETRY_DELAY);
3852
- }
3853
- })
3854
- )
3855
- )
3856
- )
3857
- ).subscribe()
3858
- );
3859
- this.subscription.add(
3860
- this.socket.error$.pipe(
3861
- switchMap2(() => timer(RETRY_DELAY)),
3862
- filter5(() => !this.passwordRejected && !this.socket.isConnected())
3863
- ).subscribe(() => this.socket.open())
3864
- );
3865
- this.alive$ = merge2(
3866
- this.socket.connected$,
3867
- this.socket.espData$.pipe(switchMap2(() => concat(of2(true), timer(PING_TIMEOUT).pipe(map2(() => false)))))
3868
- ).pipe(
3869
- distinctUntilChanged2(),
3870
- // refCount releases the watchdog source and its pending timer when
3871
- // the last subscriber leaves, e.g. after terminate().
3872
- shareReplay({ bufferSize: 1, refCount: true })
3873
- );
3964
+ this.watchDeviceMessages();
3965
+ this.watchConnection();
3966
+ this.retryFailedConnections();
3967
+ this.alive$ = this.createLivenessObservable();
3874
3968
  }
3875
3969
  host;
3876
3970
  password;
@@ -3879,6 +3973,10 @@ var EspDevice = class {
3879
3973
  client;
3880
3974
  stateEvents$;
3881
3975
  deviceInfo;
3976
+ // The HelloResponse selects the protocol version for each connection. Keep
3977
+ // one mutable per-device value so covers created on discovery and reused
3978
+ // after reconnects see the version negotiated on the latest handshake.
3979
+ apiVersion = { major: 0, minor: 0 };
3882
3980
  components = {};
3883
3981
  discovery;
3884
3982
  discovery$;
@@ -3895,6 +3993,80 @@ var EspDevice = class {
3895
3993
  // auto-reconnect until provideRetryObservable() explicitly re-arms it.
3896
3994
  passwordRejected = false;
3897
3995
  alive$;
3996
+ watchDeviceMessages() {
3997
+ this.subscription.add(this.socket.espData$.subscribe((data) => this.handleDeviceMessage(data)));
3998
+ }
3999
+ handleDeviceMessage(data) {
4000
+ try {
4001
+ if (listResponses.has(data.type)) {
4002
+ this.parseListResponse(data);
4003
+ } else if (data.type === 10 /* DeviceInfoResponse */) {
4004
+ this.deviceInfo = DeviceInfoResponse.decode(data.payload);
4005
+ } else if (data.type === 4 /* ConnectResponse */) {
4006
+ if (ConnectResponse.decode(data.payload).invalidPassword && !this.passwordRejected) {
4007
+ this.passwordRejected = true;
4008
+ this.errors.next(new InvalidPasswordError(this.host));
4009
+ this.socket.terminate();
4010
+ }
4011
+ }
4012
+ } catch (error) {
4013
+ this.errors.next(error);
4014
+ }
4015
+ }
4016
+ watchConnection() {
4017
+ this.subscription.add(
4018
+ this.socket.connected$.pipe(
4019
+ distinctUntilChanged2(),
4020
+ tap5((connected) => {
4021
+ if (!connected && !this.passwordRejected) {
4022
+ this.socket.open();
4023
+ }
4024
+ }),
4025
+ filter5((connected) => connected && !this.passwordRejected),
4026
+ // A new connection cancels the previous handshake and its retry timer.
4027
+ switchMap2(() => this.handshake())
4028
+ ).subscribe()
4029
+ );
4030
+ }
4031
+ handshake() {
4032
+ return defer(() => this.client.hello({ clientInfo: "esphome-ts" })).pipe(
4033
+ tap5((helloResponse) => {
4034
+ this.apiVersion.major = helloResponse.apiVersionMajor;
4035
+ this.apiVersion.minor = helloResponse.apiVersionMinor;
4036
+ }),
4037
+ switchMap2(() => {
4038
+ this.client.connect({ password: this.password });
4039
+ return this.passwordRejected ? EMPTY : this.client.deviceInfo();
4040
+ }),
4041
+ switchMap2(() => this.client.listEntities()),
4042
+ switchMap2(() => this.client.subscribeStateChange()),
4043
+ retry({
4044
+ delay: (error) => {
4045
+ this.errors.next(error);
4046
+ return timer(RETRY_DELAY);
4047
+ }
4048
+ })
4049
+ );
4050
+ }
4051
+ retryFailedConnections() {
4052
+ this.subscription.add(
4053
+ this.socket.error$.pipe(
4054
+ switchMap2(() => timer(RETRY_DELAY)),
4055
+ filter5(() => !this.passwordRejected && !this.socket.isConnected())
4056
+ ).subscribe(() => this.socket.open())
4057
+ );
4058
+ }
4059
+ createLivenessObservable() {
4060
+ const trafficLiveness$ = this.socket.espData$.pipe(
4061
+ switchMap2(() => concat(of2(true), timer(PING_TIMEOUT).pipe(map2(() => false))))
4062
+ );
4063
+ return merge2(this.socket.connected$, trafficLiveness$).pipe(
4064
+ distinctUntilChanged2(),
4065
+ // refCount releases the watchdog source and its pending timer when
4066
+ // the last subscriber leaves, e.g. after terminate().
4067
+ shareReplay({ bufferSize: 1, refCount: true })
4068
+ );
4069
+ }
3898
4070
  /**
3899
4071
  * Provides the reconnect cadence used while the device is unreachable.
3900
4072
  * Calling this again replaces the previously provided retry signal, so
@@ -3908,7 +4080,7 @@ var EspDevice = class {
3908
4080
  filter5(isFalse),
3909
4081
  switchMap2(
3910
4082
  () => retryWhen$.pipe(
3911
- tap4(() => this.socket.open()),
4083
+ tap5(() => this.socket.open()),
3912
4084
  takeUntil4(this.alive$.pipe(filter5(isTrue)))
3913
4085
  )
3914
4086
  )
@@ -3928,12 +4100,20 @@ var EspDevice = class {
3928
4100
  if (data.type === 19 /* ListEntitiesDoneResponse */) {
3929
4101
  this.discovery.next(true);
3930
4102
  } else {
3931
- const knownComponents = new Set(Object.keys(this.components));
3932
- const { id, component, state$ } = createComponents(data, this.stateEvents$, this.socket, knownComponents);
4103
+ const knownComponents = new Map(
4104
+ Object.entries(this.components).map(([id2, component2]) => [id2, component2.key])
4105
+ );
4106
+ const { id, component, state$ } = createComponents(
4107
+ data,
4108
+ this.stateEvents$,
4109
+ this.socket,
4110
+ knownComponents,
4111
+ this.apiVersion
4112
+ );
3933
4113
  if (component) {
3934
4114
  this.components[id] = this.components[id] ?? component;
3935
4115
  } else if (state$) {
3936
- this.components[id].provideStateObservable(state$);
4116
+ this.components[id]?.provideStateObservable(state$);
3937
4117
  }
3938
4118
  }
3939
4119
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "esphome-ts",
3
- "version": "5.1.0",
3
+ "version": "5.1.2",
4
4
  "description": "A TypeScript client for the Esphome Native API interface",
5
5
  "type": "module",
6
6
  "sideEffects": false,