homebridge-tsvesync 1.5.0 → 1.5.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.
@@ -0,0 +1,531 @@
1
+ import { API, CharacteristicValue, Logger } from 'homebridge';
2
+ import { VeSync } from 'tsvesync';
3
+ import { AirPurifierAccessory } from '../../accessories/air-purifier.accessory';
4
+ import { TSVESyncPlatform } from '../../platform';
5
+ import {
6
+ createMockInfoService,
7
+ createMockLogger,
8
+ createMockVeSync,
9
+ } from '../utils/test-helpers';
10
+
11
+ /**
12
+ * Regression tests for issue #42 - "Auto Mode not Engaging Correctly".
13
+ *
14
+ * HomeKit scenes and automations write Active, TargetAirPurifierState and
15
+ * RotationSpeed in a single HAP request, and HAP-NodeJS dispatches those
16
+ * writes concurrently. Because this accessory encodes sleep/manual/turbo into
17
+ * the RotationSpeed slider, every speed write is implicitly a mode write - so
18
+ * before the fix the speed handler raced with, and usually clobbered, an
19
+ * explicit AUTO written alongside it.
20
+ */
21
+ describe('AirPurifierAccessory batched HomeKit writes', () => {
22
+ interface Handlers {
23
+ get?: () => Promise<CharacteristicValue>;
24
+ set?: (value: CharacteristicValue) => Promise<void>;
25
+ }
26
+
27
+ const CHARACTERISTICS = [
28
+ 'Active', 'CurrentAirPurifierState', 'FilterChangeIndication', 'FilterLifeLevel',
29
+ 'Manufacturer', 'Model', 'Name', 'On', 'RotationSpeed', 'SerialNumber',
30
+ 'TargetAirPurifierState',
31
+ ];
32
+
33
+ function createHarness(options: { deviceType?: string; deviceStatus?: string; mode?: string } = {}) {
34
+ const {
35
+ deviceType = 'Core300S',
36
+ deviceStatus = 'off',
37
+ mode = 'manual',
38
+ } = options;
39
+
40
+ const logger = createMockLogger();
41
+ const Characteristic: Record<string, string> = {};
42
+ for (const c of CHARACTERISTICS) Characteristic[c] = c;
43
+
44
+ const mockAPI = {
45
+ hap: {
46
+ Characteristic,
47
+ Service: {
48
+ AccessoryInformation: 'AccessoryInformation',
49
+ AirPurifier: 'AirPurifier',
50
+ AirQualitySensor: 'AirQualitySensor',
51
+ FilterMaintenance: 'FilterMaintenance',
52
+ Switch: 'Switch',
53
+ },
54
+ uuid: { generate: jest.fn() },
55
+ },
56
+ platformAccessory: jest.fn(),
57
+ updatePlatformAccessories: jest.fn(),
58
+ } as unknown as jest.Mocked<API>;
59
+
60
+ const platform = new TSVESyncPlatform(logger as jest.Mocked<Logger>, {} as any, mockAPI);
61
+ (platform as any).api = mockAPI;
62
+ (platform as any).client = createMockVeSync() as jest.Mocked<VeSync>;
63
+
64
+ // Service mock that records the onSet/onGet handler per characteristic so
65
+ // the test can invoke them exactly the way HAP-NodeJS does.
66
+ const handlers: Record<string, Handlers> = {};
67
+ const chars = new Map<string, any>();
68
+ const getChar = (name: string) => {
69
+ if (!chars.has(name)) {
70
+ const stub: any = {
71
+ onSet: (fn: Handlers['set']) => { handlers[name] = { ...handlers[name], set: fn }; return stub; },
72
+ onGet: (fn: Handlers['get']) => { handlers[name] = { ...handlers[name], get: fn }; return stub; },
73
+ updateValue: () => stub,
74
+ setProps: (p: any) => { stub.props = p; return stub; },
75
+ };
76
+ chars.set(name, stub);
77
+ }
78
+ return chars.get(name);
79
+ };
80
+ const primaryService = {
81
+ getCharacteristic: jest.fn(getChar),
82
+ addCharacteristic: jest.fn(getChar),
83
+ setCharacteristic: jest.fn().mockReturnThis(),
84
+ testCharacteristic: jest.fn().mockReturnValue(true),
85
+ removeCharacteristic: jest.fn().mockReturnThis(),
86
+ setPrimaryService: jest.fn().mockReturnThis(),
87
+ updateCharacteristic: jest.fn().mockReturnThis(),
88
+ };
89
+
90
+ const accessory = {
91
+ context: {},
92
+ getService: jest.fn((service: any) => {
93
+ if (service === 'AccessoryInformation') return createMockInfoService();
94
+ if (service === 'AirPurifier') return primaryService;
95
+ return undefined;
96
+ }),
97
+ addService: jest.fn(() => primaryService),
98
+ removeService: jest.fn(),
99
+ };
100
+
101
+ const features = new Set(['fan_speed', 'filter_life', 'sleep_mode',
102
+ ...(deviceType === 'Core200S' ? [] : ['auto_mode'])]);
103
+
104
+ const device: any = {
105
+ connectionStatus: 'online',
106
+ details: { enabled: deviceStatus === 'on', filter_life: 80, mode, speed: 1 },
107
+ deviceName: 'Test Purifier',
108
+ deviceStatus,
109
+ deviceType,
110
+ enabled: deviceStatus === 'on',
111
+ filterLife: 80,
112
+ getDetails: jest.fn().mockResolvedValue(true),
113
+ getMaxFanSpeed: jest.fn().mockReturnValue(4),
114
+ hasFeature: jest.fn((feature: string) => features.has(feature)),
115
+ maxSpeed: 4,
116
+ uuid: 'test-purifier',
117
+ changeFanSpeed: jest.fn().mockResolvedValue(true),
118
+ setMode: jest.fn().mockResolvedValue(true),
119
+ autoMode: jest.fn().mockResolvedValue(true),
120
+ manualMode: jest.fn().mockResolvedValue(true),
121
+ sleepMode: jest.fn().mockResolvedValue(true),
122
+ turnOn: jest.fn().mockResolvedValue(true),
123
+ turnOff: jest.fn().mockResolvedValue(true),
124
+ };
125
+ // VeSyncFan exposes `mode` and `speed` as getter-only properties that read
126
+ // through to `details`. Model that exactly - a plain writable property would
127
+ // let the accessory "successfully" assign to them and hide real bugs.
128
+ Object.defineProperty(device, 'mode', { get: () => device.details.mode });
129
+ Object.defineProperty(device, 'speed', { get: () => device.details.speed });
130
+
131
+ device.autoMode.mockImplementation(async () => { device.details.mode = 'auto'; return true; });
132
+ device.manualMode.mockImplementation(async () => { device.details.mode = 'manual'; return true; });
133
+ device.sleepMode.mockImplementation(async () => { device.details.mode = 'sleep'; return true; });
134
+ device.turnOn.mockImplementation(async () => { device.deviceStatus = 'on'; device.enabled = true; return true; });
135
+ device.turnOff.mockImplementation(async () => { device.deviceStatus = 'off'; device.enabled = false; return true; });
136
+
137
+ new AirPurifierAccessory(platform, accessory as any, device);
138
+
139
+ /** Dispatch a batch the way HAP-NodeJS does: all writes concurrently. */
140
+ const writeBatch = (batch: Array<[string, number]>) =>
141
+ Promise.all(batch.map(([name, value]) => handlers[name].set!(value)));
142
+
143
+ return { device, handlers, primaryService, writeBatch, logger, chars };
144
+ }
145
+
146
+ // Core300S has three manual speeds (the library over-declares four), so with
147
+ // sleep on the first notch the slider is 0/25/50/75/100.
148
+ it('exposes a 25% step for the Core300S, with no dead top notch', () => {
149
+ const { chars } = createHarness();
150
+ expect(chars.get('RotationSpeed').props.minStep).toBe(25);
151
+ });
152
+
153
+ describe('an automation setting on + Auto', () => {
154
+ it('honours AUTO instead of the mode implied by a 60% slider', async () => {
155
+ const h = createHarness({ deviceStatus: 'off' });
156
+
157
+ await h.writeBatch([['Active', 1], ['TargetAirPurifierState', 1], ['RotationSpeed', 60]]);
158
+
159
+ expect(h.device.turnOn).toHaveBeenCalled();
160
+ expect(h.device.autoMode).toHaveBeenCalledTimes(1);
161
+ // The slider must not drag the device back into manual
162
+ expect(h.device.manualMode).not.toHaveBeenCalled();
163
+ expect(h.device.changeFanSpeed).not.toHaveBeenCalled();
164
+ expect(h.device.mode).toBe('auto');
165
+ });
166
+
167
+ it('honours AUTO instead of sleep for a 20% slider', async () => {
168
+ const h = createHarness({ deviceStatus: 'off' });
169
+
170
+ await h.writeBatch([['Active', 1], ['TargetAirPurifierState', 1], ['RotationSpeed', 20]]);
171
+
172
+ expect(h.device.autoMode).toHaveBeenCalledTimes(1);
173
+ expect(h.device.sleepMode).not.toHaveBeenCalled();
174
+ expect(h.device.mode).toBe('auto');
175
+ });
176
+
177
+ it('does not turn the device back off for a 0% slider', async () => {
178
+ const h = createHarness({ deviceStatus: 'off' });
179
+
180
+ await h.writeBatch([['Active', 1], ['TargetAirPurifierState', 1], ['RotationSpeed', 0]]);
181
+
182
+ expect(h.device.turnOn).toHaveBeenCalled();
183
+ expect(h.device.turnOff).not.toHaveBeenCalled();
184
+ expect(h.device.autoMode).toHaveBeenCalledTimes(1);
185
+ expect(h.device.deviceStatus).toBe('on');
186
+ expect(h.device.mode).toBe('auto');
187
+ });
188
+
189
+ it('produces the same result regardless of the order writes arrive in', async () => {
190
+ const h = createHarness({ deviceStatus: 'off' });
191
+
192
+ // Reverse order - the coalescer must not be order-sensitive
193
+ await h.writeBatch([['RotationSpeed', 60], ['TargetAirPurifierState', 1], ['Active', 1]]);
194
+
195
+ expect(h.device.mode).toBe('auto');
196
+ expect(h.device.changeFanSpeed).not.toHaveBeenCalled();
197
+ });
198
+ });
199
+
200
+ describe('behaviour preserved for single-characteristic writes', () => {
201
+ it('still treats a lone 0% slider as "turn off"', async () => {
202
+ const h = createHarness({ deviceStatus: 'on', mode: 'manual' });
203
+
204
+ await h.writeBatch([['RotationSpeed', 0]]);
205
+
206
+ expect(h.device.turnOff).toHaveBeenCalledTimes(1);
207
+ expect(h.device.deviceStatus).toBe('off');
208
+ });
209
+
210
+ it('still switches out of auto when only the slider is dragged', async () => {
211
+ const h = createHarness({ deviceStatus: 'on', mode: 'auto' });
212
+
213
+ await h.writeBatch([['RotationSpeed', 75]]);
214
+
215
+ expect(h.device.manualMode).toHaveBeenCalled();
216
+ expect(h.device.changeFanSpeed).toHaveBeenCalledWith(2);
217
+ });
218
+
219
+ it('still selects sleep for the first notch when only the slider is dragged', async () => {
220
+ const h = createHarness({ deviceStatus: 'on', mode: 'manual' });
221
+
222
+ await h.writeBatch([['RotationSpeed', 20]]);
223
+
224
+ expect(h.device.sleepMode).toHaveBeenCalledTimes(1);
225
+ expect(h.device.changeFanSpeed).not.toHaveBeenCalled();
226
+ });
227
+
228
+ it('still honours an explicit power off, ignoring everything else', async () => {
229
+ const h = createHarness({ deviceStatus: 'on', mode: 'auto' });
230
+
231
+ await h.writeBatch([['Active', 0], ['RotationSpeed', 60]]);
232
+
233
+ expect(h.device.turnOff).toHaveBeenCalledTimes(1);
234
+ expect(h.device.changeFanSpeed).not.toHaveBeenCalled();
235
+ expect(h.device.deviceStatus).toBe('off');
236
+ });
237
+
238
+ it('still reaches sleep via on + MANUAL + 20%, which HomeKit reports as MANUAL', async () => {
239
+ const h = createHarness({ deviceStatus: 'off' });
240
+
241
+ await h.writeBatch([['Active', 1], ['TargetAirPurifierState', 0], ['RotationSpeed', 20]]);
242
+
243
+ expect(h.device.sleepMode).toHaveBeenCalledTimes(1);
244
+ expect(h.device.mode).toBe('sleep');
245
+ });
246
+
247
+ it('still applies a speed for on + MANUAL + 60%', async () => {
248
+ const h = createHarness({ deviceStatus: 'off' });
249
+
250
+ await h.writeBatch([['Active', 1], ['TargetAirPurifierState', 0], ['RotationSpeed', 75]]);
251
+
252
+ expect(h.device.changeFanSpeed).toHaveBeenCalledWith(2);
253
+ expect(h.device.mode).toBe('manual');
254
+ });
255
+ });
256
+
257
+ /**
258
+ * The slider implicitly changes the mode, but the accessory used to leave
259
+ * TargetAirPurifierState untouched and set skipNextUpdate, so the Home app
260
+ * kept showing "Auto" while the device had actually moved to Manual. The
261
+ * poll that would have corrected it has a two minute floor.
262
+ */
263
+ describe('mode is reflected back to HomeKit immediately', () => {
264
+ const targetStateWrites = (service: any) =>
265
+ service.updateCharacteristic.mock.calls.filter((c: any[]) => c[0] === 'TargetAirPurifierState');
266
+
267
+ it('reports MANUAL as soon as a slider drag leaves auto', async () => {
268
+ const h = createHarness({ deviceStatus: 'on', mode: 'auto' });
269
+
270
+ await h.writeBatch([['RotationSpeed', 60]]);
271
+
272
+ expect(h.device.manualMode).toHaveBeenCalled();
273
+ expect(targetStateWrites(h.primaryService)).toContainEqual(['TargetAirPurifierState', 0]);
274
+ });
275
+
276
+ it('reports MANUAL as soon as a slider drag selects sleep', async () => {
277
+ const h = createHarness({ deviceStatus: 'on', mode: 'auto' });
278
+
279
+ await h.writeBatch([['RotationSpeed', 20]]);
280
+
281
+ expect(h.device.sleepMode).toHaveBeenCalled();
282
+ // HomeKit has no "sleep"; sleep is reported as MANUAL
283
+ expect(targetStateWrites(h.primaryService)).toContainEqual(['TargetAirPurifierState', 0]);
284
+ });
285
+
286
+ it('still reports AUTO after an explicit auto write', async () => {
287
+ const h = createHarness({ deviceStatus: 'off', mode: 'manual' });
288
+
289
+ await h.writeBatch([['Active', 1], ['TargetAirPurifierState', 1], ['RotationSpeed', 60]]);
290
+
291
+ const writes = targetStateWrites(h.primaryService);
292
+ expect(writes[writes.length - 1]).toEqual(['TargetAirPurifierState', 1]);
293
+ });
294
+
295
+ it('surfaces a failed mode change instead of pushing a speed anyway', async () => {
296
+ const h = createHarness({ deviceStatus: 'on', mode: 'auto' });
297
+ h.device.manualMode.mockResolvedValue(false);
298
+
299
+ await h.writeBatch([['RotationSpeed', 60]]);
300
+
301
+ // The speed must not be sent to a device still sitting in auto
302
+ expect(h.device.changeFanSpeed).not.toHaveBeenCalled();
303
+ expect(h.logger.error).toHaveBeenCalled();
304
+ });
305
+ });
306
+
307
+ /**
308
+ * VeSync is eventually consistent: for a few seconds after a mode change
309
+ * getDetails() still reports the previous mode. Without a guard that stale
310
+ * read flips the HomeKit tile straight back - observed in both directions,
311
+ * auto reverting to manual and a slider drag still showing auto.
312
+ */
313
+ describe('stale API reads must not undo a commanded mode', () => {
314
+ const targetStateWrites = (service: any) =>
315
+ service.updateCharacteristic.mock.calls.filter((c: any[]) => c[0] === 'TargetAirPurifierState');
316
+
317
+ it('keeps reporting AUTO while the API still says manual', async () => {
318
+ const h = createHarness({ deviceStatus: 'on', mode: 'manual' });
319
+ // Commanding auto succeeds, but the device keeps reporting the old mode
320
+ h.device.autoMode.mockImplementation(async () => true);
321
+
322
+ await h.writeBatch([['TargetAirPurifierState', 1]]);
323
+ expect(h.device.mode).toBe('manual'); // stale, as VeSync would report it
324
+
325
+ expect(await h.handlers.TargetAirPurifierState.get!()).toBe(1);
326
+ });
327
+
328
+ it('keeps reporting MANUAL while the API still says auto', async () => {
329
+ const h = createHarness({ deviceStatus: 'on', mode: 'auto' });
330
+ // The slider moves it to manual, but the device still reports auto
331
+ h.device.manualMode.mockImplementation(async () => true);
332
+
333
+ await h.writeBatch([['RotationSpeed', 60]]);
334
+
335
+ // A poll lands and overwrites the cache with a stale 'auto' from the API
336
+ h.device.details.mode = 'auto';
337
+
338
+ expect(await h.handlers.TargetAirPurifierState.get!()).toBe(0);
339
+ expect(targetStateWrites(h.primaryService)).toContainEqual(['TargetAirPurifierState', 0]);
340
+ });
341
+
342
+ it('a poll landing mid-flight does not flip the tile back', async () => {
343
+ const h = createHarness({ deviceStatus: 'on', mode: 'manual' });
344
+ h.device.autoMode.mockImplementation(async () => true);
345
+
346
+ await h.writeBatch([['TargetAirPurifierState', 1]]);
347
+ h.primaryService.updateCharacteristic.mockClear();
348
+
349
+ // Simulate the 2-minute poll arriving while VeSync still reports manual
350
+ await (h as any).instance?.updateDeviceSpecificStates?.(h.device);
351
+ const writes = targetStateWrites(h.primaryService);
352
+ if (writes.length) {
353
+ expect(writes[writes.length - 1]).toEqual(['TargetAirPurifierState', 1]);
354
+ }
355
+ expect(await h.handlers.TargetAirPurifierState.get!()).toBe(1);
356
+ });
357
+
358
+ it('stops overriding once the device catches up', async () => {
359
+ const h = createHarness({ deviceStatus: 'on', mode: 'manual' });
360
+ h.device.autoMode.mockImplementation(async () => true);
361
+
362
+ await h.writeBatch([['TargetAirPurifierState', 1]]);
363
+ expect(await h.handlers.TargetAirPurifierState.get!()).toBe(1);
364
+
365
+ // Device catches up, then is later changed to manual in the VeSync app
366
+ h.device.details.mode = 'auto';
367
+ expect(await h.handlers.TargetAirPurifierState.get!()).toBe(1);
368
+ h.device.details.mode = 'manual';
369
+ expect(await h.handlers.TargetAirPurifierState.get!()).toBe(0);
370
+ });
371
+
372
+ it('expires so an out-of-band change is not masked forever', async () => {
373
+ const h = createHarness({ deviceStatus: 'on', mode: 'manual' });
374
+ h.device.autoMode.mockImplementation(async () => true);
375
+
376
+ await h.writeBatch([['TargetAirPurifierState', 1]]);
377
+ expect(await h.handlers.TargetAirPurifierState.get!()).toBe(1);
378
+
379
+ // Advance past the 30s guard window
380
+ const realNow = Date.now;
381
+ Date.now = () => realNow() + 31000;
382
+ try {
383
+ expect(await h.handlers.TargetAirPurifierState.get!()).toBe(0);
384
+ } finally {
385
+ Date.now = realNow;
386
+ }
387
+ });
388
+ });
389
+
390
+ /**
391
+ * airBypass.changeFanSpeed() (the Core-series path) doesn't update the
392
+ * library's own cache, so device.speed stays stale until the next poll -
393
+ * which has a two minute floor. That made the slider snap back to the
394
+ * previously reported speed, and made sleep report a manual speed.
395
+ */
396
+ describe('readback after a speed change with a stale library cache', () => {
397
+ it('reports the speed we just set, not the stale cached one', async () => {
398
+ const h = createHarness({ deviceStatus: 'on', mode: 'manual' });
399
+ h.device.details.speed = 3; // stale value the library keeps reporting
400
+ h.device.changeFanSpeed.mockResolvedValue(true);
401
+
402
+ await h.writeBatch([['RotationSpeed', 50]]); // -> speed 1
403
+
404
+ expect(h.device.changeFanSpeed).toHaveBeenCalledWith(1);
405
+ // Without the write-through this reported the stale speed instead
406
+ expect(await h.handlers.RotationSpeed.get!()).toBe(50);
407
+ });
408
+
409
+ it('reports the sleep notch while the device is on and in sleep', async () => {
410
+ const h = createHarness({ deviceStatus: 'on', mode: 'manual' });
411
+ h.device.details.speed = 3; // stale
412
+
413
+ await h.writeBatch([['RotationSpeed', 25]]); // -> sleep
414
+
415
+ expect(h.device.sleepMode).toHaveBeenCalled();
416
+ // Previously fell through to the manual speed conversion instead
417
+ expect(await h.handlers.RotationSpeed.get!()).toBe(25);
418
+ });
419
+
420
+ it('reports 0 when the device is off', async () => {
421
+ const h = createHarness({ deviceStatus: 'off', mode: 'sleep' });
422
+ h.device.details.speed = 3;
423
+
424
+ expect(await h.handlers.RotationSpeed.get!()).toBe(0);
425
+ });
426
+ });
427
+
428
+ /**
429
+ * HomeKit caches characteristic metadata on the home hub. After an upgrade
430
+ * that changes minStep, a controller can keep sending values on the OLD grid
431
+ * for an unknown period - so upgrading users must still get the right speed,
432
+ * and must not see the slider fight them. This is the property that makes a
433
+ * minStep change safe to release.
434
+ */
435
+ describe('a controller using a stale slider grid', () => {
436
+ // Core300S: sleep + Low/Med/High, so the current grid is 25%.
437
+ // An un-refreshed controller still sends the old 20% grid.
438
+ const STALE_20_GRID: Array<[number, number | 'sleep']> = [
439
+ [20, 'sleep'],
440
+ [40, 1],
441
+ [60, 2],
442
+ [80, 3],
443
+ [100, 3],
444
+ ];
445
+
446
+ it.each(STALE_20_GRID)('maps a stale %i%% to the correct speed', async (pct, expected) => {
447
+ const h = createHarness({ deviceStatus: 'on', mode: 'manual' });
448
+
449
+ await h.writeBatch([['RotationSpeed', pct as number]]);
450
+
451
+ if (expected === 'sleep') {
452
+ expect(h.device.sleepMode).toHaveBeenCalled();
453
+ } else {
454
+ expect(h.device.changeFanSpeed).toHaveBeenCalledWith(expected);
455
+ }
456
+ });
457
+
458
+ it.each(STALE_20_GRID)('echoes a stale %i%% straight back, so the slider does not jump', async (pct) => {
459
+ const h = createHarness({ deviceStatus: 'on', mode: 'manual' });
460
+
461
+ await h.writeBatch([['RotationSpeed', pct as number]]);
462
+
463
+ expect(await h.handlers.RotationSpeed.get!()).toBe(pct);
464
+ const speedWrites = h.primaryService.updateCharacteristic.mock.calls
465
+ .filter((c: any[]) => c[0] === 'RotationSpeed');
466
+ expect(speedWrites[speedWrites.length - 1]).toEqual(['RotationSpeed', pct]);
467
+ });
468
+
469
+ it('is also correct on the current 25% grid', async () => {
470
+ for (const [pct, expected] of [[25, 'sleep'], [50, 1], [75, 2], [100, 3]] as const) {
471
+ const h = createHarness({ deviceStatus: 'on', mode: 'manual' });
472
+ await h.writeBatch([['RotationSpeed', pct as number]]);
473
+ if (expected === 'sleep') {
474
+ expect(h.device.sleepMode).toHaveBeenCalled();
475
+ } else {
476
+ expect(h.device.changeFanSpeed).toHaveBeenCalledWith(expected);
477
+ }
478
+ expect(await h.handlers.RotationSpeed.get!()).toBe(pct);
479
+ }
480
+ });
481
+ });
482
+
483
+ /**
484
+ * Dragging the slider produces a burst of writes spaced further apart than
485
+ * the coalesce window, so several batches are in flight at once. Their API
486
+ * calls must not interleave, or the device settles on whichever response
487
+ * lands last rather than the last value the user picked.
488
+ */
489
+ describe('bursts of writes are applied in order', () => {
490
+ it('does not interleave overlapping batches', async () => {
491
+ const h = createHarness({ deviceStatus: 'on', mode: 'manual' });
492
+
493
+ const inFlight: string[] = [];
494
+ const order: string[] = [];
495
+ let overlapped = false;
496
+ h.device.changeFanSpeed.mockImplementation(async (speed: number) => {
497
+ if (inFlight.length > 0) overlapped = true;
498
+ inFlight.push(`s${speed}`);
499
+ await new Promise(r => setTimeout(r, 40));
500
+ inFlight.pop();
501
+ order.push(`s${speed}`);
502
+ return true;
503
+ });
504
+
505
+ // Three drags, spaced beyond the 50ms coalesce window
506
+ const writes: Promise<unknown>[] = [];
507
+ for (const pct of [50, 75, 100]) {
508
+ writes.push(h.handlers.RotationSpeed.set!(pct));
509
+ await new Promise(r => setTimeout(r, 60));
510
+ }
511
+ await Promise.all(writes);
512
+
513
+ expect(overlapped).toBe(false);
514
+ expect(order).toEqual(['s1', 's2', 's3']);
515
+ // The device ends on the last value the user chose
516
+ expect(h.device.details.speed).toBe(3);
517
+ });
518
+ });
519
+
520
+ describe('Core200S', () => {
521
+ it('turns on without being turned straight back off by a 0% slider', async () => {
522
+ const h = createHarness({ deviceType: 'Core200S', deviceStatus: 'off' });
523
+
524
+ await h.writeBatch([['Active', 1], ['RotationSpeed', 0]]);
525
+
526
+ expect(h.device.turnOn).toHaveBeenCalled();
527
+ expect(h.device.turnOff).not.toHaveBeenCalled();
528
+ expect(h.device.deviceStatus).toBe('on');
529
+ });
530
+ });
531
+ });