esphome-ts 4.0.0 → 5.0.0

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
@@ -6,10 +6,10 @@ This is a client library for use with [esphome](https://esphome.io).
6
6
 
7
7
  ```typescript
8
8
  import { EspDevice, SwitchComponent } from 'esphome-ts';
9
- import { filter, tap } from 'rxjs/operators';
9
+ import { filter, tap } from 'rxjs';
10
10
 
11
11
  const device = new EspDevice('my_esp.local');
12
- device.discovery$
12
+ const subscription = device.discovery$
13
13
  .pipe(
14
14
  filter((value) => value),
15
15
  tap(() => {
@@ -20,6 +20,9 @@ device.discovery$
20
20
  }),
21
21
  )
22
22
  .subscribe();
23
+
24
+ // Call `subscription.unsubscribe()` to stop watching, and `device.terminate()`
25
+ // to tear the device down for good.
23
26
  ```
24
27
 
25
28
  `rxjs` (>= 7.8) is a peer dependency: install it next to the library (`npm install esphome-ts rxjs`).
@@ -39,13 +42,29 @@ deep imports such as the previously documented `esphome-ts/dist` no longer resol
39
42
  exports map. The legacy `Connection` class, the `isLightComponent` type guard and internal helpers
40
43
  (`decode`, `stateParser`, `convertNumbers`, `BytePositions`, …) are no longer exported; the public
41
44
  surface is `EspDevice` (with `InvalidPasswordError`), `Client`, `EspSocket`, `RxjsSocket`,
42
- `MessageTypes`, `ReadData`, the `isSwitchComponent` type guard, the `isTrue`/`isFalse` filters and
45
+ `MessageTypes`, `ReadData` (type), the `isSwitchComponent` type guard, the `isTrue`/`isFalse` filters and
43
46
  the component classes with their entity and state types. `EspDevice` now reconnects when a
44
- connection attempt fails, reports invalid passwords and undecodable frames on its new `error$`
45
- observable instead of stalling or crashing, and `Client.listEntities()` /
47
+ connection attempt fails, reports invalid passwords and undecodable discovery frames on its
48
+ new `error$` observable instead of stalling or crashing, and `Client.listEntities()` /
46
49
  `Client.subscribeStateChange()` emit `void` instead of a placeholder message. The
47
50
  generated protobuf layer now depends on `@bufbuild/protobuf` instead of `protobufjs`.
48
51
 
52
+ ## Upgrading to v5
53
+
54
+ v5 replaces the exported inheritance-based socket stack with the `Connection` seam:
55
+
56
+ - `RxjsSocket` is internal now — it became `TcpConnection` and is no longer exported.
57
+ - `EspSocket` no longer exposes `data$`, `send()`, `timeout$`, `close(force)` — use
58
+ `sendEspMessage` and `terminate()`.
59
+ - `reconnectOnTimeout`/`disconnectOnTimeout` are gone — an idle timeout always tears the
60
+ connection down, and reconnection stays driven by `EspDevice`.
61
+ - If you need a custom transport, inject your own `Connection` via `EspDevice`'s new options
62
+ parameter or via `EspSocket`'s config. The new `Connection` is an exported interface TYPE for
63
+ custom transports — unrelated to the legacy `Connection` class that v4 removed.
64
+ - ESPHome re-sends identical states; `state$` now de-duplicates them (shallow compare,
65
+ `Object.is` per field) and emits only on actual changes — subscribers no longer see phantom
66
+ re-emissions.
67
+
49
68
  ## Development
50
69
 
51
70
  The protobuf layer in `src/api/protobuf/` is generated from the `.proto` files alongside it. After changing a `.proto` file, regenerate with:
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { BinaryWriter, BinaryReader } from '@bufbuild/protobuf/wire';
2
- import { Observable, Subject, BehaviorSubject } from 'rxjs';
2
+ import { Observable, BehaviorSubject, Subject } from 'rxjs';
3
3
 
4
4
  /**
5
5
  * Message sent at the beginning of each connection
@@ -149,33 +149,32 @@ interface CommandInterface {
149
149
  sendEspMessage(type: MessageTypes, data: Uint8Array): void;
150
150
  }
151
151
 
152
- interface RxjsSocketConfiguration {
153
- reconnectOnTimeout?: boolean;
154
- timeout?: number;
155
- disconnectOnTimeout?: boolean;
156
- }
157
- declare class RxjsSocket {
158
- private readonly host;
159
- private readonly port;
160
- private socket?;
161
- private readonly config;
162
- private readonly data;
163
- readonly data$: Observable<Buffer>;
164
- private readonly connected;
165
- readonly connected$: Observable<boolean>;
166
- private readonly timeout;
167
- readonly timeout$: Observable<void>;
168
- protected readonly error: Subject<Error>;
169
- readonly error$: Observable<Error>;
170
- protected readonly terminate: Subject<void>;
171
- constructor(host: string, port: number, config?: RxjsSocketConfiguration);
152
+ /**
153
+ * Connection seam: the live path between the library and a device, along which
154
+ * frames travel as byte chunks. The TCP path is the production Connection; any
155
+ * implementation satisfying the same interface may substitute for it.
156
+ *
157
+ * Contract per member:
158
+ * - `open()`: repeatable — a no-op while a connect attempt is already in flight;
159
+ * otherwise a call with a live path tears it down and opens a fresh one.
160
+ * - `terminate()`: with a path or failed attempt open, tears it down and emits `false` on
161
+ * `connected$`; with nothing open it is a no-op — first or repeat call alike.
162
+ * - `connected$`: hot state stream that MUST emit its current value synchronously to every new
163
+ * subscriber (e.g. a BehaviorSubject seeded false pre-connect) — `EspDevice` drives its initial
164
+ * `open()` from the synchronous seed; a plain hot Subject or cold observable silently never
165
+ * connects. Never completes.
166
+ * - `chunks$`: hot, no emission while disconnected, never completes.
167
+ * - `error$`: hot, never completes — late errors after `terminate()` keep arriving.
168
+ */
169
+ interface Connection {
172
170
  open(): void;
173
- close(forceDestroy?: boolean): void;
171
+ terminate(): void;
174
172
  isConnected(): boolean;
175
- send(data: string | Uint8Array, encoding?: BufferEncoding): Observable<void>;
176
- private setupSocketEvents;
177
- private reconnect;
178
- private destroySocket;
173
+ readonly connected$: Observable<boolean>;
174
+ readonly chunks$: Observable<Buffer>;
175
+ readonly error$: Observable<unknown>;
176
+ /** Fire-and-forget. Silently drops when not connected. Write errors surface on error$. */
177
+ write(data: Uint8Array): void;
179
178
  }
180
179
 
181
180
  interface ReadData {
@@ -183,9 +182,22 @@ interface ReadData {
183
182
  payload: Uint8Array;
184
183
  }
185
184
 
186
- declare class EspSocket extends RxjsSocket implements CommandInterface {
185
+ interface EspSocketConfiguration {
186
+ /** Ignored when `connection` is set: idle-timeout teardown is owned by the injected adapter. */
187
+ timeout?: number;
188
+ connection?: Connection;
189
+ }
190
+ declare class EspSocket implements CommandInterface {
191
+ private readonly connection;
192
+ private readonly teardown;
193
+ private readonly errors;
194
+ readonly connected$: Observable<boolean>;
187
195
  readonly espData$: Observable<ReadData>;
188
- constructor(host: string, port: number, config?: RxjsSocketConfiguration);
196
+ readonly error$: Observable<unknown>;
197
+ constructor(host: string, port: number, config?: EspSocketConfiguration);
198
+ open(): void;
199
+ isConnected(): boolean;
200
+ terminate(): void;
189
201
  sendEspMessage(type: MessageTypes, payload: Uint8Array): void;
190
202
  }
191
203
 
@@ -287,8 +299,23 @@ declare class EspDevice {
287
299
  */
288
300
  readonly error$: Observable<unknown>;
289
301
  private readonly subscription;
302
+ private retrySubscription?;
303
+ private passwordRejected;
290
304
  readonly alive$: Observable<boolean>;
291
- constructor(host: string, password?: string, port?: number);
305
+ constructor(host: string, password?: string, port?: number,
306
+ /**
307
+ * An injected Connection owns its own liveness/idle teardown — the
308
+ * socket-level `PING_TIMEOUT` does not apply to it.
309
+ */
310
+ options?: {
311
+ connection?: Connection;
312
+ });
313
+ /**
314
+ * Provides the reconnect cadence used while the device is unreachable.
315
+ * Calling this again replaces the previously provided retry signal, so
316
+ * repeated calls cannot stack parallel reconnect loops. Providing a cadence
317
+ * is also the explicit opt-in re-arm after a password rejection.
318
+ */
292
319
  provideRetryObservable(retryWhen$: Observable<unknown>): void;
293
320
  terminate(): void;
294
321
  private parseListResponse;
@@ -376,4 +403,4 @@ declare class SensorComponent extends BaseComponent<SensorEntity, SensorStateEve
376
403
  get icon(): string;
377
404
  }
378
405
 
379
- export { BaseComponent, BinarySensorComponent, type BinarySensorEntity, type BinarySensorStateEvent, BinarySensorTypes, Client, type CommandInterface, type ComponentType, EspDevice, EspSocket, type Hsv, InvalidPasswordError, LightComponent, type LightEntity, type LightStateEvent, type ListEntity, MessageTypes, type ReadData, type Rgb, RxjsSocket, type RxjsSocketConfiguration, SensorComponent, type SensorEntity, type SensorStateEvent, type StateEvent, SwitchComponent, type SwitchStateEvent, isFalse, isSwitchComponent, isTrue };
406
+ export { BaseComponent, BinarySensorComponent, type BinarySensorEntity, type BinarySensorStateEvent, BinarySensorTypes, Client, type CommandInterface, type ComponentType, type Connection, EspDevice, EspSocket, type Hsv, InvalidPasswordError, LightComponent, type LightEntity, type LightStateEvent, type ListEntity, MessageTypes, type ReadData, type Rgb, SensorComponent, type SensorEntity, type SensorStateEvent, type StateEvent, SwitchComponent, type SwitchStateEvent, isFalse, isSwitchComponent, isTrue };
package/dist/index.js CHANGED
@@ -2410,181 +2410,204 @@ function isSet(value) {
2410
2410
  }
2411
2411
 
2412
2412
  // src/api/espSocket.ts
2413
- import { from } from "rxjs";
2414
- import { filter, mergeMap, switchMap, take as take2, takeUntil as takeUntil2, timeout } from "rxjs/operators";
2413
+ import {
2414
+ EMPTY,
2415
+ filter,
2416
+ from,
2417
+ merge,
2418
+ mergeMap,
2419
+ share,
2420
+ Subject as Subject2,
2421
+ switchMap,
2422
+ take as take2,
2423
+ takeUntil as takeUntil2,
2424
+ timeout
2425
+ } from "rxjs";
2415
2426
 
2416
2427
  // src/api/requestResponseMatching.ts
2417
- var MessageTypes = /* @__PURE__ */ ((MessageTypes4) => {
2418
- MessageTypes4[MessageTypes4["HelloRequest"] = 1] = "HelloRequest";
2419
- MessageTypes4[MessageTypes4["HelloResponse"] = 2] = "HelloResponse";
2420
- MessageTypes4[MessageTypes4["ConnectRequest"] = 3] = "ConnectRequest";
2421
- MessageTypes4[MessageTypes4["ConnectResponse"] = 4] = "ConnectResponse";
2422
- MessageTypes4[MessageTypes4["DisconnectRequest"] = 5] = "DisconnectRequest";
2423
- MessageTypes4[MessageTypes4["DisconnectResponse"] = 6] = "DisconnectResponse";
2424
- MessageTypes4[MessageTypes4["PingRequest"] = 7] = "PingRequest";
2425
- MessageTypes4[MessageTypes4["PingResponse"] = 8] = "PingResponse";
2426
- MessageTypes4[MessageTypes4["DeviceInfoRequest"] = 9] = "DeviceInfoRequest";
2427
- MessageTypes4[MessageTypes4["DeviceInfoResponse"] = 10] = "DeviceInfoResponse";
2428
- MessageTypes4[MessageTypes4["ListEntitiesRequest"] = 11] = "ListEntitiesRequest";
2429
- MessageTypes4[MessageTypes4["ListEntitiesBinarySensorResponse"] = 12] = "ListEntitiesBinarySensorResponse";
2430
- MessageTypes4[MessageTypes4["ListEntitiesCoverResponse"] = 13] = "ListEntitiesCoverResponse";
2431
- MessageTypes4[MessageTypes4["ListEntitiesFanResponse"] = 14] = "ListEntitiesFanResponse";
2432
- MessageTypes4[MessageTypes4["ListEntitiesLightResponse"] = 15] = "ListEntitiesLightResponse";
2433
- MessageTypes4[MessageTypes4["ListEntitiesSensorResponse"] = 16] = "ListEntitiesSensorResponse";
2434
- MessageTypes4[MessageTypes4["ListEntitiesSwitchResponse"] = 17] = "ListEntitiesSwitchResponse";
2435
- MessageTypes4[MessageTypes4["ListEntitiesTextSensorResponse"] = 18] = "ListEntitiesTextSensorResponse";
2436
- MessageTypes4[MessageTypes4["ListEntitiesDoneResponse"] = 19] = "ListEntitiesDoneResponse";
2437
- MessageTypes4[MessageTypes4["SubscribeStatesRequest"] = 20] = "SubscribeStatesRequest";
2438
- MessageTypes4[MessageTypes4["BinarySensorStateResponse"] = 21] = "BinarySensorStateResponse";
2439
- MessageTypes4[MessageTypes4["CoverStateResponse"] = 22] = "CoverStateResponse";
2440
- MessageTypes4[MessageTypes4["FanStateResponse"] = 23] = "FanStateResponse";
2441
- MessageTypes4[MessageTypes4["LightStateResponse"] = 24] = "LightStateResponse";
2442
- MessageTypes4[MessageTypes4["SensorStateResponse"] = 25] = "SensorStateResponse";
2443
- MessageTypes4[MessageTypes4["SwitchStateResponse"] = 26] = "SwitchStateResponse";
2444
- MessageTypes4[MessageTypes4["TextSensorStateResponse"] = 27] = "TextSensorStateResponse";
2445
- MessageTypes4[MessageTypes4["SubscribeLogsRequest"] = 28] = "SubscribeLogsRequest";
2446
- MessageTypes4[MessageTypes4["SubscribeLogsResponse"] = 29] = "SubscribeLogsResponse";
2447
- MessageTypes4[MessageTypes4["CoverCommandRequest"] = 30] = "CoverCommandRequest";
2448
- MessageTypes4[MessageTypes4["FanCommandRequest"] = 31] = "FanCommandRequest";
2449
- MessageTypes4[MessageTypes4["LightCommandRequest"] = 32] = "LightCommandRequest";
2450
- MessageTypes4[MessageTypes4["SwitchCommandRequest"] = 33] = "SwitchCommandRequest";
2451
- MessageTypes4[MessageTypes4["SubscribeHomeassistantServicesRequest"] = 34] = "SubscribeHomeassistantServicesRequest";
2452
- MessageTypes4[MessageTypes4["HomeassistantServiceResponse"] = 35] = "HomeassistantServiceResponse";
2453
- MessageTypes4[MessageTypes4["GetTimeRequest"] = 36] = "GetTimeRequest";
2454
- MessageTypes4[MessageTypes4["GetTimeResponse"] = 37] = "GetTimeResponse";
2455
- MessageTypes4[MessageTypes4["SubscribeHomeAssistantStatesRequest"] = 38] = "SubscribeHomeAssistantStatesRequest";
2456
- MessageTypes4[MessageTypes4["SubscribeHomeAssistantStateResponse"] = 39] = "SubscribeHomeAssistantStateResponse";
2457
- MessageTypes4[MessageTypes4["HomeAssistantStateResponse"] = 40] = "HomeAssistantStateResponse";
2458
- MessageTypes4[MessageTypes4["ListEntitiesServicesResponse"] = 41] = "ListEntitiesServicesResponse";
2459
- MessageTypes4[MessageTypes4["ExecuteServiceRequest"] = 42] = "ExecuteServiceRequest";
2460
- MessageTypes4[MessageTypes4["ListEntitiesCameraResponse"] = 43] = "ListEntitiesCameraResponse";
2461
- MessageTypes4[MessageTypes4["CameraImageResponse"] = 44] = "CameraImageResponse";
2462
- MessageTypes4[MessageTypes4["CameraImageRequest"] = 45] = "CameraImageRequest";
2463
- MessageTypes4[MessageTypes4["ListEntitiesClimateResponse"] = 46] = "ListEntitiesClimateResponse";
2464
- MessageTypes4[MessageTypes4["ClimateStateResponse"] = 47] = "ClimateStateResponse";
2465
- MessageTypes4[MessageTypes4["ClimateCommandRequest"] = 48] = "ClimateCommandRequest";
2466
- return MessageTypes4;
2428
+ var MessageTypes = /* @__PURE__ */ ((MessageTypes2) => {
2429
+ MessageTypes2[MessageTypes2["HelloRequest"] = 1] = "HelloRequest";
2430
+ MessageTypes2[MessageTypes2["HelloResponse"] = 2] = "HelloResponse";
2431
+ MessageTypes2[MessageTypes2["ConnectRequest"] = 3] = "ConnectRequest";
2432
+ MessageTypes2[MessageTypes2["ConnectResponse"] = 4] = "ConnectResponse";
2433
+ MessageTypes2[MessageTypes2["DisconnectRequest"] = 5] = "DisconnectRequest";
2434
+ MessageTypes2[MessageTypes2["DisconnectResponse"] = 6] = "DisconnectResponse";
2435
+ MessageTypes2[MessageTypes2["PingRequest"] = 7] = "PingRequest";
2436
+ MessageTypes2[MessageTypes2["PingResponse"] = 8] = "PingResponse";
2437
+ MessageTypes2[MessageTypes2["DeviceInfoRequest"] = 9] = "DeviceInfoRequest";
2438
+ MessageTypes2[MessageTypes2["DeviceInfoResponse"] = 10] = "DeviceInfoResponse";
2439
+ MessageTypes2[MessageTypes2["ListEntitiesRequest"] = 11] = "ListEntitiesRequest";
2440
+ MessageTypes2[MessageTypes2["ListEntitiesBinarySensorResponse"] = 12] = "ListEntitiesBinarySensorResponse";
2441
+ MessageTypes2[MessageTypes2["ListEntitiesCoverResponse"] = 13] = "ListEntitiesCoverResponse";
2442
+ MessageTypes2[MessageTypes2["ListEntitiesFanResponse"] = 14] = "ListEntitiesFanResponse";
2443
+ MessageTypes2[MessageTypes2["ListEntitiesLightResponse"] = 15] = "ListEntitiesLightResponse";
2444
+ MessageTypes2[MessageTypes2["ListEntitiesSensorResponse"] = 16] = "ListEntitiesSensorResponse";
2445
+ MessageTypes2[MessageTypes2["ListEntitiesSwitchResponse"] = 17] = "ListEntitiesSwitchResponse";
2446
+ MessageTypes2[MessageTypes2["ListEntitiesTextSensorResponse"] = 18] = "ListEntitiesTextSensorResponse";
2447
+ MessageTypes2[MessageTypes2["ListEntitiesDoneResponse"] = 19] = "ListEntitiesDoneResponse";
2448
+ MessageTypes2[MessageTypes2["SubscribeStatesRequest"] = 20] = "SubscribeStatesRequest";
2449
+ MessageTypes2[MessageTypes2["BinarySensorStateResponse"] = 21] = "BinarySensorStateResponse";
2450
+ MessageTypes2[MessageTypes2["CoverStateResponse"] = 22] = "CoverStateResponse";
2451
+ MessageTypes2[MessageTypes2["FanStateResponse"] = 23] = "FanStateResponse";
2452
+ MessageTypes2[MessageTypes2["LightStateResponse"] = 24] = "LightStateResponse";
2453
+ MessageTypes2[MessageTypes2["SensorStateResponse"] = 25] = "SensorStateResponse";
2454
+ MessageTypes2[MessageTypes2["SwitchStateResponse"] = 26] = "SwitchStateResponse";
2455
+ MessageTypes2[MessageTypes2["TextSensorStateResponse"] = 27] = "TextSensorStateResponse";
2456
+ MessageTypes2[MessageTypes2["SubscribeLogsRequest"] = 28] = "SubscribeLogsRequest";
2457
+ MessageTypes2[MessageTypes2["SubscribeLogsResponse"] = 29] = "SubscribeLogsResponse";
2458
+ MessageTypes2[MessageTypes2["CoverCommandRequest"] = 30] = "CoverCommandRequest";
2459
+ MessageTypes2[MessageTypes2["FanCommandRequest"] = 31] = "FanCommandRequest";
2460
+ MessageTypes2[MessageTypes2["LightCommandRequest"] = 32] = "LightCommandRequest";
2461
+ MessageTypes2[MessageTypes2["SwitchCommandRequest"] = 33] = "SwitchCommandRequest";
2462
+ MessageTypes2[MessageTypes2["SubscribeHomeassistantServicesRequest"] = 34] = "SubscribeHomeassistantServicesRequest";
2463
+ MessageTypes2[MessageTypes2["HomeassistantServiceResponse"] = 35] = "HomeassistantServiceResponse";
2464
+ MessageTypes2[MessageTypes2["GetTimeRequest"] = 36] = "GetTimeRequest";
2465
+ MessageTypes2[MessageTypes2["GetTimeResponse"] = 37] = "GetTimeResponse";
2466
+ MessageTypes2[MessageTypes2["SubscribeHomeAssistantStatesRequest"] = 38] = "SubscribeHomeAssistantStatesRequest";
2467
+ MessageTypes2[MessageTypes2["SubscribeHomeAssistantStateResponse"] = 39] = "SubscribeHomeAssistantStateResponse";
2468
+ MessageTypes2[MessageTypes2["HomeAssistantStateResponse"] = 40] = "HomeAssistantStateResponse";
2469
+ MessageTypes2[MessageTypes2["ListEntitiesServicesResponse"] = 41] = "ListEntitiesServicesResponse";
2470
+ MessageTypes2[MessageTypes2["ExecuteServiceRequest"] = 42] = "ExecuteServiceRequest";
2471
+ MessageTypes2[MessageTypes2["ListEntitiesCameraResponse"] = 43] = "ListEntitiesCameraResponse";
2472
+ MessageTypes2[MessageTypes2["CameraImageResponse"] = 44] = "CameraImageResponse";
2473
+ MessageTypes2[MessageTypes2["CameraImageRequest"] = 45] = "CameraImageRequest";
2474
+ MessageTypes2[MessageTypes2["ListEntitiesClimateResponse"] = 46] = "ListEntitiesClimateResponse";
2475
+ MessageTypes2[MessageTypes2["ClimateStateResponse"] = 47] = "ClimateStateResponse";
2476
+ MessageTypes2[MessageTypes2["ClimateCommandRequest"] = 48] = "ClimateCommandRequest";
2477
+ return MessageTypes2;
2467
2478
  })(MessageTypes || {});
2468
2479
 
2469
- // src/api/socket.ts
2480
+ // src/api/tcpConnection.ts
2470
2481
  import { Socket } from "net";
2471
- import { BehaviorSubject, fromEvent, Observable, Subject } from "rxjs";
2472
- import { take, takeUntil, tap } from "rxjs/operators";
2473
- var defaultConfig = {
2474
- reconnectOnTimeout: false,
2475
- disconnectOnTimeout: true
2476
- };
2477
- var RxjsSocket = class {
2482
+ import { BehaviorSubject, fromEvent, Subject, take, takeUntil, tap } from "rxjs";
2483
+ var TcpConnection = class {
2478
2484
  constructor(host, port, config) {
2479
2485
  this.host = host;
2480
2486
  this.port = port;
2481
- this.config = { ...defaultConfig, ...config };
2482
- this.data$ = this.data.asObservable();
2487
+ this.timeout = config?.timeout;
2488
+ this.chunks$ = this.chunks.asObservable();
2483
2489
  this.connected$ = this.connected.asObservable();
2484
- this.timeout$ = this.timeout.asObservable();
2485
2490
  this.error$ = this.error.asObservable();
2486
2491
  }
2487
2492
  host;
2488
2493
  port;
2489
2494
  socket;
2490
- config;
2495
+ timeout;
2491
2496
  // RxJS
2492
- data = new Subject();
2493
- data$;
2497
+ chunks = new Subject();
2498
+ chunks$;
2494
2499
  connected = new BehaviorSubject(false);
2495
2500
  connected$;
2496
- timeout = new Subject();
2497
- timeout$;
2498
2501
  error = new Subject();
2499
2502
  error$;
2500
- terminate = new Subject();
2503
+ // Internal teardown signal; ends the socket event subscriptions.
2504
+ teardown = new Subject();
2505
+ // Cancel closure for a pending graceful termination; invoked when a new
2506
+ // connection is opened to cancel it.
2507
+ pendingGracefulDestroy;
2501
2508
  open() {
2502
2509
  if (this.socket?.connecting) {
2503
2510
  return;
2504
2511
  }
2505
- this.close(true);
2512
+ this.teardownSocket();
2506
2513
  this.socket = new Socket();
2507
- if (this.config.timeout) {
2508
- this.socket.setTimeout(this.config.timeout);
2514
+ if (this.timeout) {
2515
+ this.socket.setTimeout(this.timeout);
2509
2516
  }
2510
2517
  this.setupSocketEvents();
2511
2518
  this.socket.connect(this.port, this.host);
2512
2519
  }
2513
- close(forceDestroy) {
2514
- if (!this.socket) {
2520
+ terminate() {
2521
+ if (!this.socket || this.pendingGracefulDestroy) {
2515
2522
  return;
2516
2523
  }
2517
2524
  this.connected.next(false);
2518
- this.terminate.next();
2525
+ this.teardown.next();
2519
2526
  this.socket.end();
2520
- if (forceDestroy) {
2521
- this.destroySocket();
2522
- }
2527
+ const socket = this.socket;
2528
+ let settled = false;
2529
+ const finish = () => {
2530
+ clearTimeout(safety);
2531
+ if (settled) {
2532
+ return;
2533
+ }
2534
+ settled = true;
2535
+ this.pendingGracefulDestroy = void 0;
2536
+ if (this.socket === socket) {
2537
+ this.destroySocket();
2538
+ }
2539
+ };
2540
+ const safety = setTimeout(finish, 250);
2541
+ safety.unref();
2542
+ socket.once("close", finish);
2543
+ const cancel = () => {
2544
+ settled = true;
2545
+ clearTimeout(safety);
2546
+ socket.removeListener("close", finish);
2547
+ this.pendingGracefulDestroy = void 0;
2548
+ };
2549
+ this.pendingGracefulDestroy = cancel;
2523
2550
  }
2524
2551
  isConnected() {
2525
2552
  return this.connected.getValue();
2526
2553
  }
2527
- send(data, encoding) {
2528
- return new Observable((subscriber) => {
2529
- if (this.connected.getValue() && this.socket) {
2530
- this.socket.write(data, encoding, (err) => {
2531
- if (err) {
2532
- subscriber.error(err);
2533
- return;
2534
- }
2535
- subscriber.next();
2536
- subscriber.complete();
2537
- });
2538
- return;
2554
+ // Fire-and-forget: a write while disconnected is silently dropped, a write
2555
+ // error is surfaced on error$ instead of escaping into Node's write-completion
2556
+ // context as an uncaught exception.
2557
+ write(data) {
2558
+ if (!this.isConnected() || !this.socket) {
2559
+ return;
2560
+ }
2561
+ this.socket.write(data, (err) => {
2562
+ if (err) {
2563
+ this.error.next(err);
2539
2564
  }
2540
- subscriber.next();
2541
- subscriber.complete();
2542
2565
  });
2543
2566
  }
2544
2567
  setupSocketEvents() {
2545
- if (!this.socket) {
2568
+ const socket = this.socket;
2569
+ if (!socket) {
2546
2570
  return;
2547
2571
  }
2548
- this.socket.on("error", (err) => this.error.next(err));
2549
- fromEvent(this.socket, "data").pipe(
2550
- tap((buffer) => this.data.next(buffer)),
2551
- takeUntil(this.terminate)
2572
+ socket.on("error", (err) => this.error.next(err));
2573
+ fromEvent(socket, "data").pipe(
2574
+ tap((buffer) => this.chunks.next(buffer)),
2575
+ takeUntil(this.teardown)
2552
2576
  ).subscribe();
2553
- fromEvent(this.socket, "connect").pipe(
2577
+ fromEvent(socket, "connect").pipe(
2554
2578
  take(1),
2555
2579
  tap(() => this.connected.next(true)),
2556
- takeUntil(this.terminate)
2580
+ takeUntil(this.teardown)
2557
2581
  ).subscribe();
2558
- fromEvent(this.socket, "close").pipe(
2582
+ fromEvent(socket, "close").pipe(
2559
2583
  take(1),
2560
2584
  tap(() => this.connected.next(false)),
2561
- takeUntil(this.terminate)
2585
+ takeUntil(this.teardown)
2562
2586
  ).subscribe();
2563
- fromEvent(this.socket, "end").pipe(
2587
+ fromEvent(socket, "end").pipe(
2564
2588
  take(1),
2565
2589
  tap(() => this.socket?.end()),
2566
2590
  tap(() => this.connected.next(false)),
2567
- takeUntil(this.terminate)
2591
+ takeUntil(this.teardown)
2568
2592
  ).subscribe();
2569
- if (this.config.timeout && this.config.timeout > 0) {
2570
- fromEvent(this.socket, "timeout").pipe(
2571
- tap(() => this.timeout.next()),
2593
+ if (this.timeout && this.timeout > 0) {
2594
+ fromEvent(socket, "timeout").pipe(
2572
2595
  tap(() => {
2573
- if (this.config.disconnectOnTimeout) {
2574
- this.destroySocket();
2575
- }
2576
- if (this.config.reconnectOnTimeout) {
2577
- this.reconnect();
2578
- }
2596
+ this.teardown.next();
2597
+ this.destroySocket();
2579
2598
  }),
2580
- takeUntil(this.terminate)
2599
+ takeUntil(this.teardown)
2581
2600
  ).subscribe();
2582
2601
  }
2583
2602
  }
2584
- reconnect() {
2585
- this.terminate.next();
2603
+ teardownSocket() {
2604
+ this.pendingGracefulDestroy?.();
2605
+ this.pendingGracefulDestroy = void 0;
2606
+ if (!this.socket) {
2607
+ return;
2608
+ }
2609
+ this.teardown.next();
2586
2610
  this.destroySocket();
2587
- this.open();
2588
2611
  }
2589
2612
  destroySocket() {
2590
2613
  this.socket?.destroy();
@@ -2640,39 +2663,61 @@ var isTrue = (val) => val === true;
2640
2663
  var isFalse = (val) => val === false;
2641
2664
 
2642
2665
  // src/api/espSocket.ts
2643
- var EspSocket = class extends RxjsSocket {
2666
+ var EspSocket = class {
2667
+ connection;
2668
+ teardown = new Subject2();
2669
+ errors = new Subject2();
2670
+ connected$;
2644
2671
  espData$;
2672
+ error$;
2645
2673
  constructor(host, port, config) {
2646
- super(host, port, config);
2647
- this.espData$ = this.connected$.pipe(
2674
+ this.connection = config?.connection ?? new TcpConnection(host, port, { timeout: config?.timeout });
2675
+ this.connected$ = this.connection.connected$;
2676
+ this.error$ = merge(this.errors, this.connection.error$);
2677
+ this.espData$ = this.connection.connected$.pipe(
2648
2678
  filter(isTrue),
2649
2679
  switchMap(() => {
2650
2680
  const frameParser = createFrameParser();
2651
- return this.data$.pipe(mergeMap((chunk) => from(frameParser.push(chunk))));
2652
- })
2681
+ return this.connection.chunks$.pipe(mergeMap((chunk) => from(frameParser.push(chunk))));
2682
+ }),
2683
+ share()
2653
2684
  );
2654
2685
  }
2686
+ open() {
2687
+ this.connection.open();
2688
+ }
2689
+ isConnected() {
2690
+ return this.connection.isConnected();
2691
+ }
2692
+ terminate() {
2693
+ this.teardown.next();
2694
+ this.connection.terminate();
2695
+ }
2655
2696
  sendEspMessage(type, payload) {
2656
- this.connected$.pipe(
2697
+ this.connection.connected$.pipe(
2657
2698
  timeout(5e3),
2658
2699
  filter(isTrue),
2659
2700
  take2(1),
2660
2701
  switchMap(() => {
2661
2702
  const final = encodeFrame(type, payload);
2662
- return this.send(final);
2703
+ this.connection.write(final);
2704
+ return EMPTY;
2663
2705
  }),
2664
- takeUntil2(this.terminate)
2706
+ // terminate() kills a pending send, but open() deliberately does
2707
+ // NOT: a command issued during a blip rides the reconnect within
2708
+ // its 5-second window — the commands are idempotent absolute-state
2709
+ // writes, so a ≤5s-old resend is safe.
2710
+ takeUntil2(this.teardown)
2665
2711
  ).subscribe({
2666
2712
  error: (error) => {
2667
- this.error.next(error instanceof Error ? error : new Error(String(error)));
2713
+ this.errors.next(error instanceof Error ? error : new Error(String(error)));
2668
2714
  }
2669
2715
  });
2670
2716
  }
2671
2717
  };
2672
2718
 
2673
2719
  // src/api/client.ts
2674
- import { of, Subscription } from "rxjs";
2675
- import { filter as filter2, map, take as take3, tap as tap2 } from "rxjs/operators";
2720
+ import { filter as filter2, map, of, Subscription, take as take3, tap as tap2 } from "rxjs";
2676
2721
  var Client = class {
2677
2722
  constructor(socket) {
2678
2723
  this.socket = socket;
@@ -2747,34 +2792,38 @@ var Client = class {
2747
2792
  }
2748
2793
  };
2749
2794
 
2750
- // src/api/espDevice.ts
2751
- import {
2752
- catchError,
2753
- distinctUntilChanged,
2754
- filter as filter5,
2755
- map as map2,
2756
- mapTo,
2757
- shareReplay,
2758
- switchMap as switchMap2,
2759
- take as take5,
2760
- takeUntil as takeUntil4,
2761
- tap as tap4,
2762
- timeout as timeout2
2763
- } from "rxjs/operators";
2764
-
2765
2795
  // src/api/helpers.ts
2766
- import "rxjs";
2767
- import { filter as filter4 } from "rxjs/operators";
2796
+ import { filter as filter4 } from "rxjs";
2768
2797
 
2769
2798
  // src/components/base.ts
2770
- import { BehaviorSubject as BehaviorSubject2, Subject as Subject2 } from "rxjs";
2771
- import { debounceTime, filter as filter3, take as take4, takeUntil as takeUntil3, tap as tap3 } from "rxjs/operators";
2799
+ import {
2800
+ BehaviorSubject as BehaviorSubject2,
2801
+ debounceTime,
2802
+ distinctUntilChanged,
2803
+ filter as filter3,
2804
+ Subject as Subject3,
2805
+ take as take4,
2806
+ takeUntil as takeUntil3,
2807
+ tap as tap3
2808
+ } from "rxjs";
2809
+ var shallowEqualStates = (previous, current) => {
2810
+ const previousKeys = Object.keys(previous);
2811
+ const currentKeys = Object.keys(current);
2812
+ return previousKeys.length === currentKeys.length && previousKeys.every((key) => Object.is(previous[key], current[key]));
2813
+ };
2772
2814
  var BaseComponent = class {
2773
2815
  constructor(listEntity, state, commandInterface) {
2774
2816
  this.listEntity = listEntity;
2775
2817
  this.commandInterface = commandInterface;
2776
2818
  this.commandInPipeline = new BehaviorSubject2(false);
2777
- this.state$ = this.state.pipe(filter3((state2) => state2 !== void 0));
2819
+ this.state$ = this.state.pipe(
2820
+ filter3((state2) => state2 !== void 0),
2821
+ // ESPHome re-sends identical states (e.g. a sensor polling a stable
2822
+ // reading): shallow-compare the flat state events so subscribers only
2823
+ // observe actual changes. Object.is is used per field so an identical
2824
+ // NaN-valued state also compares equal instead of re-emitting.
2825
+ distinctUntilChanged(shallowEqualStates)
2826
+ );
2778
2827
  this.provideStateObservable(state);
2779
2828
  this.commandInPipeline.pipe(
2780
2829
  debounceTime(30 * 1e3),
@@ -2787,9 +2836,9 @@ var BaseComponent = class {
2787
2836
  commandInterface;
2788
2837
  state = new BehaviorSubject2(void 0);
2789
2838
  state$;
2790
- terminatePreviousStateSubscription = new Subject2();
2839
+ terminatePreviousStateSubscription = new Subject3();
2791
2840
  commandInPipeline;
2792
- teardown = new Subject2();
2841
+ teardown = new Subject3();
2793
2842
  provideStateObservable(state$) {
2794
2843
  this.terminatePreviousStateSubscription.next();
2795
2844
  state$.pipe(
@@ -3184,7 +3233,26 @@ var stateResponses = /* @__PURE__ */ new Set([
3184
3233
  ]);
3185
3234
 
3186
3235
  // src/api/espDevice.ts
3187
- import { BehaviorSubject as BehaviorSubject3, concat, EMPTY, merge, of as of2, Subject as Subject3, Subscription as Subscription2, timer } from "rxjs";
3236
+ import {
3237
+ BehaviorSubject as BehaviorSubject3,
3238
+ concat,
3239
+ defer,
3240
+ distinctUntilChanged as distinctUntilChanged2,
3241
+ EMPTY as EMPTY2,
3242
+ filter as filter5,
3243
+ map as map2,
3244
+ merge as merge2,
3245
+ of as of2,
3246
+ retry,
3247
+ share as share2,
3248
+ shareReplay,
3249
+ Subject as Subject4,
3250
+ Subscription as Subscription2,
3251
+ switchMap as switchMap2,
3252
+ takeUntil as takeUntil4,
3253
+ tap as tap4,
3254
+ timer
3255
+ } from "rxjs";
3188
3256
  var PING_TIMEOUT = 90 * 1e3;
3189
3257
  var RETRY_DELAY = 1e3;
3190
3258
  var InvalidPasswordError = class extends Error {
@@ -3194,7 +3262,7 @@ var InvalidPasswordError = class extends Error {
3194
3262
  }
3195
3263
  };
3196
3264
  var EspDevice = class {
3197
- constructor(host, password = "", port = 6053) {
3265
+ constructor(host, password = "", port = 6053, options) {
3198
3266
  this.host = host;
3199
3267
  this.password = password;
3200
3268
  this.port = port;
@@ -3203,13 +3271,17 @@ var EspDevice = class {
3203
3271
  this.discovery$ = this.discovery.asObservable();
3204
3272
  this.error$ = this.errors.asObservable();
3205
3273
  this.socket = new EspSocket(host, port, {
3206
- timeout: PING_TIMEOUT
3274
+ timeout: PING_TIMEOUT,
3275
+ connection: options?.connection
3207
3276
  });
3208
3277
  this.client = new Client(this.socket);
3209
3278
  this.stateEvents$ = this.socket.espData$.pipe(
3210
3279
  filter5((data) => stateResponses.has(data.type)),
3211
3280
  map2((data) => stateParser(data)),
3212
- filter5((parsed) => !!parsed)
3281
+ filter5((parsed) => !!parsed),
3282
+ // One decode shared by all components: without this, every discovered
3283
+ // component re-runs the filter+decode chain for the same state frame.
3284
+ share2()
3213
3285
  );
3214
3286
  this.subscription.add(
3215
3287
  this.socket.espData$.pipe(
@@ -3228,55 +3300,63 @@ var EspDevice = class {
3228
3300
  );
3229
3301
  this.subscription.add(
3230
3302
  this.socket.connected$.pipe(
3231
- distinctUntilChanged(),
3303
+ distinctUntilChanged2(),
3232
3304
  tap4((connected) => {
3233
- if (!connected) {
3305
+ if (!connected && !this.passwordRejected) {
3234
3306
  this.socket.open();
3235
3307
  }
3236
3308
  }),
3237
- filter5(isTrue),
3238
- switchMap2(() => this.client.hello({ clientInfo: "esphome-ts" })),
3239
- switchMap2(() => this.client.connect({ password })),
3240
- map2((response) => {
3241
- if (response.invalidPassword) {
3242
- throw new InvalidPasswordError(this.host);
3243
- }
3244
- return response;
3245
- }),
3246
- switchMap2(() => this.client.deviceInfo()),
3247
- switchMap2(() => this.client.listEntities()),
3248
- switchMap2(() => this.client.subscribeStateChange()),
3249
- catchError((error, caught) => {
3250
- this.errors.next(error);
3251
- if (error instanceof InvalidPasswordError) {
3252
- return EMPTY;
3253
- }
3254
- return timer(RETRY_DELAY).pipe(switchMap2(() => caught));
3255
- })
3309
+ filter5((connected) => connected && !this.passwordRejected),
3310
+ switchMap2(
3311
+ () => (
3312
+ // defer() re-runs this factory on every retry:
3313
+ // Client.request() sends eagerly when called (not on
3314
+ // subscription), so without it a retried handshake
3315
+ // would never put a fresh HelloRequest on the wire —
3316
+ // and a real device only answers HelloRequest, never
3317
+ // speaks first.
3318
+ defer(() => this.client.hello({ clientInfo: "esphome-ts" })).pipe(
3319
+ switchMap2(() => this.client.connect({ password })),
3320
+ map2((response) => {
3321
+ if (response.invalidPassword) {
3322
+ throw new InvalidPasswordError(this.host);
3323
+ }
3324
+ return response;
3325
+ }),
3326
+ switchMap2(() => this.client.deviceInfo()),
3327
+ switchMap2(() => this.client.listEntities()),
3328
+ switchMap2(() => this.client.subscribeStateChange()),
3329
+ retry({
3330
+ delay: (error) => {
3331
+ this.errors.next(error);
3332
+ if (error instanceof InvalidPasswordError) {
3333
+ this.passwordRejected = true;
3334
+ this.socket.terminate();
3335
+ return EMPTY2;
3336
+ }
3337
+ return timer(RETRY_DELAY);
3338
+ }
3339
+ })
3340
+ )
3341
+ )
3342
+ )
3256
3343
  ).subscribe()
3257
3344
  );
3258
3345
  this.subscription.add(
3259
3346
  this.socket.error$.pipe(
3260
3347
  switchMap2(() => timer(RETRY_DELAY)),
3261
- filter5(() => !this.socket.isConnected())
3348
+ filter5(() => !this.passwordRejected && !this.socket.isConnected())
3262
3349
  ).subscribe(() => this.socket.open())
3263
3350
  );
3264
- this.alive$ = merge(
3351
+ this.alive$ = merge2(
3265
3352
  this.socket.connected$,
3266
- this.socket.espData$.pipe(
3267
- switchMap2(() => {
3268
- return concat(
3269
- of2(true),
3270
- this.socket.espData$.pipe(
3271
- mapTo(true),
3272
- timeout2(PING_TIMEOUT),
3273
- catchError(() => of2(false)),
3274
- take5(1)
3275
- )
3276
- );
3277
- })
3278
- )
3279
- ).pipe(distinctUntilChanged(), shareReplay(1));
3353
+ this.socket.espData$.pipe(switchMap2(() => concat(of2(true), timer(PING_TIMEOUT).pipe(map2(() => false)))))
3354
+ ).pipe(
3355
+ distinctUntilChanged2(),
3356
+ // refCount releases the watchdog source and its pending timer when
3357
+ // the last subscriber leaves, e.g. after terminate().
3358
+ shareReplay({ bufferSize: 1, refCount: true })
3359
+ );
3280
3360
  }
3281
3361
  host;
3282
3362
  password;
@@ -3288,7 +3368,7 @@ var EspDevice = class {
3288
3368
  components = {};
3289
3369
  discovery;
3290
3370
  discovery$;
3291
- errors = new Subject3();
3371
+ errors = new Subject4();
3292
3372
  /**
3293
3373
  * Device level failures: frames that could not be decoded and handshake
3294
3374
  * problems such as an `InvalidPasswordError`. Socket level errors are
@@ -3296,19 +3376,30 @@ var EspDevice = class {
3296
3376
  */
3297
3377
  error$;
3298
3378
  subscription;
3379
+ retrySubscription;
3380
+ // Latched when the device rejects the constructed password: terminal for
3381
+ // auto-reconnect until provideRetryObservable() explicitly re-arms it.
3382
+ passwordRejected = false;
3299
3383
  alive$;
3384
+ /**
3385
+ * Provides the reconnect cadence used while the device is unreachable.
3386
+ * Calling this again replaces the previously provided retry signal, so
3387
+ * repeated calls cannot stack parallel reconnect loops. Providing a cadence
3388
+ * is also the explicit opt-in re-arm after a password rejection.
3389
+ */
3300
3390
  provideRetryObservable(retryWhen$) {
3301
- this.subscription.add(
3302
- this.alive$.pipe(
3303
- filter5(isFalse),
3304
- switchMap2(
3305
- () => retryWhen$.pipe(
3306
- tap4(() => this.socket.open()),
3307
- takeUntil4(this.alive$.pipe(filter5(isTrue)))
3308
- )
3391
+ this.passwordRejected = false;
3392
+ this.retrySubscription?.unsubscribe();
3393
+ this.retrySubscription = this.alive$.pipe(
3394
+ filter5(isFalse),
3395
+ switchMap2(
3396
+ () => retryWhen$.pipe(
3397
+ tap4(() => this.socket.open()),
3398
+ takeUntil4(this.alive$.pipe(filter5(isTrue)))
3309
3399
  )
3310
- ).subscribe()
3311
- );
3400
+ )
3401
+ ).subscribe();
3402
+ this.subscription.add(this.retrySubscription);
3312
3403
  }
3313
3404
  terminate() {
3314
3405
  Object.values(this.components).forEach((component) => {
@@ -3317,7 +3408,7 @@ var EspDevice = class {
3317
3408
  this.client.terminate();
3318
3409
  this.subscription.unsubscribe();
3319
3410
  this.errors.complete();
3320
- this.socket.close(true);
3411
+ this.socket.terminate();
3321
3412
  }
3322
3413
  parseListResponse(data) {
3323
3414
  if (data.type === 19 /* ListEntitiesDoneResponse */) {
@@ -3346,7 +3437,6 @@ export {
3346
3437
  InvalidPasswordError,
3347
3438
  LightComponent,
3348
3439
  MessageTypes,
3349
- RxjsSocket,
3350
3440
  SensorComponent,
3351
3441
  SwitchComponent,
3352
3442
  isFalse,
package/package.json CHANGED
@@ -1,8 +1,9 @@
1
1
  {
2
2
  "name": "esphome-ts",
3
- "version": "4.0.0",
3
+ "version": "5.0.0",
4
4
  "description": "A TypeScript client for the Esphome Native API interface",
5
5
  "type": "module",
6
+ "sideEffects": false,
6
7
  "main": "dist/index.js",
7
8
  "types": "dist/index.d.ts",
8
9
  "exports": {