wizlight 0.1.0-beta.1

Async client for Philips WiZ smart bulbs over the local UDP protocol, plus the wizlight CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
//! Typed protocol methods and the pilot builder against the mock bulb.

mod common;

use std::time::Duration;

use common::mock_bulb::{MockBulb, Personality};
use serde_json::{Value, json};
use wizlight::protocol::{
    BulbClass, Channel, Derivation, Devices, Dimming, Kelvin, KelvinRange, PULSE_SCENE_ID,
    PilotBuilder, PulseDelta, PulseParams, Ratio, Scene, SceneId, Speed,
};
use wizlight::{Bulb, Error, RetryPolicy};

async fn connect(bulb: &MockBulb) -> Bulb {
    Bulb::connect_to(bulb.addr()).await.expect("bind socket")
}

/// The last datagram the bulb received, parsed.
///
/// Compared as JSON rather than as bytes: key order is not part of the
/// protocol, and pinning it would mean forcing `serde_json/preserve_order` on
/// every crate in a consumer's build. See the note in `Cargo.toml`.
fn last_request(bulb: &MockBulb) -> Value {
    let raw = bulb.requests().last().cloned().expect("a request was sent");
    serde_json::from_str(&raw).expect("requests are JSON")
}

#[tokio::test]
async fn get_pilot_returns_typed_state() {
    let bulb = MockBulb::start().await;
    let client = connect(&bulb).await;

    let pilot = client.get_pilot().await.expect("get_pilot");
    assert_eq!(pilot.mac.as_deref(), Some(bulb.mac()));
    assert_eq!(pilot.state, Some(true));
    assert_eq!(pilot.temp, Some(2700));
    assert_eq!(pilot.dimming, Some(100));
}

#[tokio::test]
async fn set_pilot_rgb_round_trips_and_matches_wire_format() {
    let bulb = MockBulb::start().await;
    let client = connect(&bulb).await;

    let builder = PilotBuilder::new()
        .rgb(Channel::new(255), Channel::new(80), Channel::new(0))
        .dimming(Dimming::new(40).unwrap());

    client.set_pilot(&builder).await.expect("set_pilot");
    assert_eq!(
        last_request(&bulb),
        json!({
            "method": "setPilot",
            "params": {"r": 255, "g": 80, "b": 0, "dimming": 40},
        })
    );

    let pilot = client.get_pilot().await.expect("get_pilot");
    assert_eq!(pilot.rgb(), Some((255, 80, 0)));
    assert_eq!(pilot.dimming, Some(40));
    assert_eq!(pilot.state, Some(true));
    assert!(pilot.temp.is_none());
}

#[tokio::test]
async fn set_pilot_rgbw_puts_the_white_channel_on_the_wire() {
    let bulb = MockBulb::start().await;
    let client = connect(&bulb).await;

    let builder = PilotBuilder::new().rgbw(
        Channel::new(10),
        Channel::new(20),
        Channel::new(30),
        Channel::new(40),
    );
    client.set_pilot(&builder).await.expect("set_pilot");

    assert_eq!(
        last_request(&bulb),
        json!({
            "method": "setPilot",
            "params": {"r": 10, "g": 20, "b": 30, "w": 40},
        })
    );

    let pilot = client.get_pilot().await.expect("get_pilot");
    assert_eq!(pilot.rgbw(), Some((10, 20, 30, 40)));
}

#[tokio::test]
async fn set_state_uses_the_set_state_method() {
    let bulb = MockBulb::start().await;
    let client = connect(&bulb).await;

    let builder = PilotBuilder::new().temp(Kelvin::new(4000).unwrap());
    client.set_state(&builder).await.expect("set_state");

    assert_eq!(
        last_request(&bulb),
        json!({"method": "setState", "params": {"temp": 4000}})
    );
    let pilot = client.get_pilot().await.expect("get_pilot");
    assert_eq!(pilot.temp, Some(4000));
    assert!(pilot.r.is_none());
}

#[tokio::test]
async fn scene_and_speed_round_trip() {
    let bulb = MockBulb::start().await;
    let client = connect(&bulb).await;

    let builder = PilotBuilder::new()
        .scene(SceneId::new(4).unwrap())
        .speed(Speed::new(100).unwrap());
    client.set_pilot(&builder).await.expect("set_pilot");

    let pilot = client.get_pilot().await.expect("get_pilot");
    assert_eq!(pilot.scene_id, Some(4));
    assert_eq!(pilot.speed, Some(100));
    assert!(pilot.temp.is_none());
    assert!(pilot.r.is_none());
}

#[tokio::test]
async fn ratio_and_devices_reach_a_dual_head_bulb() {
    let bulb = MockBulb::builder()
        .personality(Personality::dual_head())
        .start()
        .await;
    let client = connect(&bulb).await;

    let builder = PilotBuilder::new()
        .state(true)
        .ratio(Ratio::new(75).unwrap())
        .devices(Devices::new(2).unwrap());
    client.set_pilot(&builder).await.expect("set_pilot");

    assert_eq!(
        last_request(&bulb),
        json!({
            "method": "setPilot",
            "params": {"state": true, "ratio": 75, "devices": 2},
        })
    );

    let pilot = client.get_pilot().await.expect("get_pilot");
    assert_eq!(pilot.ratio, Some(75));
    assert_eq!(pilot.devices, Some(2));
}

#[tokio::test]
async fn a_dimmable_white_bulb_takes_dimming_and_reports_its_range() {
    let bulb = MockBulb::builder()
        .personality(Personality::dimmable_white())
        .start()
        .await;
    let client = connect(&bulb).await;

    let system = client.get_system_config().await.expect("system");
    assert_eq!(system.module_name.as_deref(), Some("ESP06_SHDW9_01"));

    client
        .set_pilot(&PilotBuilder::new().dimming(Dimming::new(25).unwrap()))
        .await
        .expect("set_pilot");
    assert_eq!(client.get_pilot().await.unwrap().dimming, Some(25));

    // No getModelConfig on 1.11.7, so the range comes from getUserConfig.
    assert_eq!(
        client.kelvin_range().await.expect("range"),
        Some(KelvinRange::new(2700, 6500))
    );
}

#[tokio::test]
async fn colour_modes_are_mutually_exclusive_on_the_bulb() {
    let bulb = MockBulb::start().await;
    let client = connect(&bulb).await;

    client
        .set_pilot(&PilotBuilder::new().rgb(Channel::new(10), Channel::new(20), Channel::new(30)))
        .await
        .unwrap();
    client
        .set_pilot(&PilotBuilder::new().temp(Kelvin::new(3000).unwrap()))
        .await
        .unwrap();

    let pilot = client.get_pilot().await.unwrap();
    assert_eq!(pilot.temp, Some(3000));
    assert!(pilot.r.is_none());
    assert_eq!(pilot.scene_id, Some(0));
}

#[tokio::test]
async fn a_conflicting_builder_never_reaches_the_wire() {
    let bulb = MockBulb::start().await;
    let client = connect(&bulb).await;

    let err = client
        .set_pilot(
            &PilotBuilder::new()
                .rgb(Channel::new(10), Channel::new(20), Channel::new(30))
                .temp(Kelvin::new(3000).unwrap()),
        )
        .await
        .expect_err("colour and temp together");
    assert!(matches!(err, Error::InvalidParam { .. }), "{err}");
    assert!(bulb.requests().is_empty());
}

#[tokio::test]
async fn empty_builder_is_rejected_before_the_wire() {
    let bulb = MockBulb::start().await;
    let client = connect(&bulb).await;

    let err = client
        .set_pilot(&PilotBuilder::new())
        .await
        .expect_err("empty builder");
    assert!(matches!(err, Error::InvalidParam { .. }));
    assert!(bulb.requests().is_empty());
}

#[tokio::test]
async fn system_model_and_user_config_parse() {
    let bulb = MockBulb::start().await;
    let client = connect(&bulb).await;

    let system = client.get_system_config().await.expect("system");
    assert_eq!(system.module_name.as_deref(), Some("ESP25_SHRGB_01"));
    assert_eq!(system.fw_version.as_deref(), Some("1.38.0"));
    assert_eq!(system.mac.as_deref(), Some(bulb.mac()));

    let model = client.get_model_config().await.expect("model");
    assert_eq!(model.kelvin_range(), Some(KelvinRange::new(2200, 6500)));
    assert_eq!(model.wcr, Some(80));

    let user = client.get_user_config().await.expect("user");
    assert_eq!(user.dft_dim, Some(100));
}

#[tokio::test]
async fn kelvin_range_uses_model_config_when_present() {
    let bulb = MockBulb::start().await;
    let client = connect(&bulb).await;
    assert_eq!(
        client.kelvin_range().await.expect("range"),
        Some(KelvinRange::new(2200, 6500))
    );
}

#[tokio::test]
async fn kelvin_range_reads_a_legacy_model_config() {
    // ESP01_SHRGB_03 has getModelConfig but none of the fields 1.38.0 added,
    // and no getUserConfig at all — so the range has to come from the former.
    let bulb = MockBulb::builder()
        .personality(Personality::rgb_legacy())
        .start()
        .await;
    let client = connect(&bulb).await;

    assert!(matches!(
        client.get_user_config().await,
        Err(Error::NotSupported { .. })
    ));
    assert_eq!(
        client.kelvin_range().await.expect("range"),
        Some(KelvinRange::new(2200, 6500))
    );
}

#[tokio::test]
async fn kelvin_range_falls_back_to_user_config() {
    let bulb = MockBulb::builder()
        .personality(Personality::tunable_white())
        .start()
        .await;
    let client = connect(&bulb).await;

    let err = client
        .get_model_config()
        .await
        .expect_err("no model config");
    assert!(matches!(err, Error::NotSupported { .. }));

    assert_eq!(
        client.kelvin_range().await.expect("range"),
        Some(KelvinRange::new(2700, 6500))
    );
}

#[tokio::test]
async fn bulb_type_describes_the_measured_hardware() {
    // ESP25_SHRGB_01 on 1.38.0. Its getSystemConfig carries neither `drvConf`
    // nor `typeId`, so everything but the module name comes from
    // getModelConfig: `nowc`, `wcr` and the `cctRange` of 2200-6500.
    let bulb = MockBulb::start().await;
    let client = connect(&bulb).await;

    let bulb_type = client.bulb_type().await.expect("bulb type");
    assert_eq!(bulb_type.class, BulbClass::Rgb);
    assert_eq!(bulb_type.derivation, Derivation::ModuleName);
    assert_eq!(
        bulb_type.module_name.as_ref().map(ToString::to_string),
        Some("ESP25_SHRGB_01".to_owned())
    );
    assert_eq!(bulb_type.fw_version.as_deref(), Some("1.38.0"));
    assert_eq!(bulb_type.kelvin_range, Some(KelvinRange::new(2200, 6500)));
    assert_eq!(bulb_type.white_channels, Some(1));
    assert_eq!(bulb_type.white_to_color_ratio, Some(80));
    assert_eq!(bulb_type.fan_speed_range, None);

    let features = bulb_type.features;
    assert!(features.color && features.color_tmp && features.effect && features.brightness);
    assert!(!features.dual_head && !features.fan);
}

#[tokio::test]
async fn bulb_type_reads_white_channels_from_drv_conf_on_old_firmware() {
    // ESP14_SHTW1C_01 on 1.18.0: no getModelConfig, so `nowc` and `wcr` are
    // only available as the two entries of `drvConf`, and the Kelvin range
    // only from getUserConfig.
    let bulb = MockBulb::builder()
        .personality(Personality::tunable_white())
        .start()
        .await;
    let bulb_type = connect(&bulb).await.bulb_type().await.expect("bulb type");

    assert_eq!(bulb_type.class, BulbClass::Tw);
    assert_eq!(bulb_type.kelvin_range, Some(KelvinRange::new(2700, 6500)));
    assert_eq!(bulb_type.white_channels, Some(1));
    assert_eq!(bulb_type.white_to_color_ratio, Some(20));
    assert!(!bulb_type.features.color && bulb_type.features.color_tmp);
}

#[tokio::test]
async fn bulb_type_of_a_dual_head_bulb_reports_two_heads() {
    let bulb = MockBulb::builder()
        .personality(Personality::dual_head())
        .start()
        .await;
    let bulb_type = connect(&bulb).await.bulb_type().await.expect("bulb type");

    assert_eq!(bulb_type.class, BulbClass::Rgb);
    assert!(bulb_type.features.dual_head);
    // `nowc` from getModelConfig wins over the `drvConf` of [30, 1] that the
    // same bulb's getSystemConfig still carries.
    assert_eq!(bulb_type.white_channels, Some(2));
    assert_eq!(bulb_type.white_to_color_ratio, Some(20));
}

#[tokio::test]
async fn a_socket_has_nothing_to_dim() {
    let bulb = MockBulb::builder()
        .personality(Personality::socket())
        .start()
        .await;
    let bulb_type = connect(&bulb).await.bulb_type().await.expect("bulb type");

    assert_eq!(bulb_type.class, BulbClass::Socket);
    let features = bulb_type.features;
    assert!(!features.brightness && !features.color && !features.color_tmp && !features.effect);
}

#[tokio::test]
async fn a_fan_reports_its_speed_range() {
    let bulb = MockBulb::builder()
        .personality(Personality::fan())
        .start()
        .await;
    let bulb_type = connect(&bulb).await.bulb_type().await.expect("bulb type");

    assert_eq!(bulb_type.class, BulbClass::FanDim);
    assert_eq!(bulb_type.fan_speed_range, Some(6));
    // A single-temperature light: the range is four copies of one value.
    assert_eq!(bulb_type.kelvin_range, Some(KelvinRange::new(2700, 2700)));
    assert!(bulb_type.features.fan && bulb_type.features.brightness);
    assert!(!bulb_type.features.effect && !bulb_type.features.color_tmp);
}

#[tokio::test]
async fn firmware_too_old_for_a_module_name_falls_back_to_its_type_id() {
    // 1.8.0 reports no moduleName at all, so the class comes from `typeId: 0`
    // and the white channel count from `drvConf: [20, 1]`.
    let bulb = MockBulb::builder()
        .personality(Personality::firmware_1_8_0())
        .start()
        .await;
    let bulb_type = connect(&bulb).await.bulb_type().await.expect("bulb type");

    assert_eq!(bulb_type.class, BulbClass::Dw);
    assert_eq!(bulb_type.derivation, Derivation::KnownTypeId(0));
    assert_eq!(bulb_type.module_name, None);
    assert_eq!(bulb_type.white_channels, Some(1));
    assert_eq!(bulb_type.white_to_color_ratio, Some(20));
    assert!(bulb_type.features.brightness && bulb_type.features.effect);

    // `pywizlight` reports no range for this fixture, because it reads
    // `extRange` and `cctRange` only while 1.8.0 sends `whiteRange`. Reading
    // the range the bulb did send is a deliberate difference: a reported
    // range beats no range at all.
    assert_eq!(bulb_type.kelvin_range, Some(KelvinRange::new(2700, 2700)));
}

#[tokio::test]
async fn a_bulb_that_cannot_describe_itself_says_so() {
    // Neither a moduleName nor a typeId, and then a module name with no
    // identifier token in it. Both are refused rather than guessed at.
    for system_config in [
        r#"{"method":"getSystemConfig","env":"pro","result":{"mac":"9877d5230f0a","fwVersion":"1.38.0"}}"#,
        r#"{"method":"getSystemConfig","env":"pro","result":{"mac":"9877d5230f0a","moduleName":"INVALID","fwVersion":"1.38.0"}}"#,
    ] {
        let bulb = MockBulb::builder()
            .personality(Personality::rgb().with_system_config(system_config))
            .start()
            .await;
        let err = connect(&bulb)
            .await
            .bulb_type()
            .await
            .expect_err("nothing to go on");
        assert!(matches!(err, Error::UnknownModel { .. }), "{err}");
    }
}

#[tokio::test]
async fn a_colour_bulb_that_reports_no_kelvin_range_is_an_error() {
    // A getModelConfig with no `cctRange` and no getUserConfig to fall back
    // on. An RGB bulb whose usable range is unknown cannot be given a colour
    // temperature safely, so this is refused rather than guessed.
    let bulb = MockBulb::builder()
        .personality(Personality::rgb_legacy().with_model_config(
            r#"{"method":"getModelConfig","env":"pro","result":{"ps":1,"wcr":30,"nowc":1}}"#,
        ))
        .start()
        .await;
    let client = connect(&bulb).await;

    assert_eq!(client.kelvin_range().await.expect("no range"), None);
    let err = client.bulb_type().await.expect_err("no kelvin range");
    assert!(
        err.to_string().contains("must report a Kelvin range"),
        "{err}"
    );
}

/// The scene list a bulb offers follows its class, which is the whole reason
/// the table is keyed on class rather than on model.
#[tokio::test]
async fn the_scene_list_follows_the_bulb_s_class() {
    let cases = [
        (Personality::rgb(), BulbClass::Rgb, 39),
        (Personality::tunable_white(), BulbClass::Tw, 17),
        (Personality::dimmable_white(), BulbClass::Dw, 11),
        // Nothing to run a light mode on.
        (Personality::socket(), BulbClass::Socket, 0),
        (Personality::fan(), BulbClass::FanDim, 0),
    ];

    for (personality, class, expected) in cases {
        let name = personality.module_name;
        let bulb = MockBulb::builder().personality(personality).start().await;
        let scenes = connect(&bulb).await.scenes().await.expect("scenes");
        assert_eq!(scenes.len(), expected, "{name}");
        // Whatever the class, a listed scene has to be one it can play.
        assert!(
            scenes.iter().all(|scene| scene.available_for(class)),
            "{name}"
        );
    }
}

/// Every scene is addressable end to end: it goes out as its id, and the bulb
/// reports the same id back for the crate to name again.
#[tokio::test]
async fn every_scene_round_trips_through_a_bulb() {
    let bulb = MockBulb::start().await;
    let client = connect(&bulb).await;

    for scene in Scene::all() {
        client
            .set_pilot(&PilotBuilder::new().scene(scene.id()))
            .await
            .unwrap_or_else(|err| panic!("{scene} was refused: {err}"));
        assert_eq!(
            last_request(&bulb),
            json!({"method": "setPilot", "params": {"sceneId": scene.id().get()}}),
        );

        let pilot = client.get_pilot().await.expect("get_pilot");
        assert_eq!(pilot.scene_id, Some(scene.id().get()));
        assert_eq!(pilot.scene(), Some(*scene));
    }
}

#[tokio::test]
async fn get_power_is_answered_by_this_model() {
    let bulb = MockBulb::start().await;
    let client = connect(&bulb).await;

    let power = client.get_power().await.expect("power");
    assert_eq!(power.power, 0);
}

#[tokio::test]
async fn reboot_is_refused_by_the_hardware_and_says_so() {
    // Measured on ESP25_SHRGB_01 fw 1.38.0: `reboot` comes back -32600
    // Invalid Request and the bulb does not reboot. Not -32601, so the
    // firmware knows the method and declines it. The harness answers the same
    // way, and this test exists so nobody "fixes" it back to success.
    let bulb = MockBulb::start().await;
    let client = connect(&bulb).await;

    let err = client
        .reboot()
        .await
        .expect_err("the hardware refuses reboot");
    assert!(
        matches!(&err, Error::Device { code: -32600, method, .. } if method == "reboot"),
        "{err}"
    );
    // A refusal must not be mistaken for the silence that fire-and-forget
    // forgives.
    assert!(!matches!(err, Error::Timeout { .. }));

    let sent: Vec<Value> = bulb
        .requests()
        .iter()
        .map(|r| serde_json::from_str(r).expect("requests are JSON"))
        .collect();
    assert!(sent.contains(&json!({"method": "reboot", "params": {}})));
}

#[tokio::test]
async fn reset_is_assumed_to_behave_like_reboot() {
    // Untested on hardware, and staying that way: measuring a factory reset
    // costs a re-paired bulb.
    let bulb = MockBulb::start().await;
    let client = connect(&bulb).await;

    let err = client.reset().await.expect_err("assumed refused");
    assert!(matches!(err, Error::Device { code: -32600, .. }), "{err}");
}

#[tokio::test]
async fn silence_is_still_forgiven_for_reboot_and_reset() {
    // The other half of fire-and-forget: a bulb that really did reboot has an
    // obvious reason not to answer. The socket stays bound but unread so no
    // concurrent test can claim the supposedly silent address and answer.
    let silent = std::net::UdpSocket::bind("127.0.0.1:0").expect("bind");
    let dead = silent.local_addr().expect("local_addr");
    let client = Bulb::connect_to(dead)
        .await
        .expect("bind socket")
        .with_policy(RetryPolicy {
            attempts: 1,
            attempt_timeout: Duration::from_millis(50),
            min_interval: Duration::from_millis(1),
        });

    client
        .reboot()
        .await
        .expect("a silent reboot is still a reboot");
    client
        .reset()
        .await
        .expect("a silent reset is still a reset");

    // A read, by contrast, has nothing to return and must still time out.
    assert!(matches!(
        client.get_pilot().await,
        Err(Error::Timeout { .. })
    ));
}

#[tokio::test]
async fn get_power_missing_on_legacy_personalities() {
    let bulb = MockBulb::builder()
        .personality(Personality::rgb_legacy())
        .start()
        .await;
    let client = connect(&bulb).await;

    let err = client.get_power().await.expect_err("no power");
    assert!(matches!(err, Error::NotSupported { .. }));
}

#[tokio::test]
async fn socket_personality_reports_power() {
    let bulb = MockBulb::builder()
        .personality(Personality::socket())
        .start()
        .await;
    let client = connect(&bulb).await;
    assert_eq!(client.get_power().await.unwrap().power, 1_065_385);
}

#[tokio::test]
async fn pilot_survives_missing_optional_fields() {
    let bulb = MockBulb::builder()
        .pilot(json!({
            "mac": "aabbccddeeff",
            "state": false,
            "dimming": 10
        }))
        .start()
        .await;
    let client = connect(&bulb).await;
    let pilot = client.get_pilot().await.unwrap();
    assert_eq!(pilot.state, Some(false));
    assert_eq!(pilot.dimming, Some(10));
    assert!(pilot.temp.is_none());
    assert!(pilot.r.is_none());
    assert!(pilot.scene_id.is_none());
}

#[tokio::test]
async fn pulse_sends_typed_request_reports_effect_and_restores_prior_mode() {
    let bulb = MockBulb::start().await;
    let client = connect(&bulb).await;

    // Client-side validation rejects delta=0, delta outside -100..=100, and duration=0
    // before touching the socket.
    for (delta, duration) in [(0, 150), (-101, 150), (101, 150), (-50, 0)] {
        let err = client.pulse(delta, duration).await.unwrap_err();
        assert!(matches!(err, Error::InvalidParam { .. }), "{err}");
    }
    assert!(bulb.requests().is_empty());

    assert_eq!(PulseDelta::new(-80).unwrap().get(), -80);
    assert_eq!(
        serde_json::to_value(PulseParams::new(-80, 50).unwrap().request().unwrap()).unwrap(),
        json!({"method": "pulse", "params": {"delta": -80, "duration": 50}})
    );

    client.pulse(-80, 50).await.expect("pulse succeeds");
    assert_eq!(
        last_request(&bulb),
        json!({"method": "pulse", "params": {"delta": -80, "duration": 50}})
    );

    let during = client.get_pilot().await.expect("get_pilot during pulse");
    assert_eq!(during.scene_id, Some(PULSE_SCENE_ID));
    assert_eq!(during.effect.as_deref(), Some("pulse"));
    assert!(during.is_pulsing());

    tokio::time::sleep(Duration::from_millis(140)).await;
    let after = client.get_pilot().await.expect("get_pilot after pulse");
    assert_eq!(after.scene_id, Some(11));
    assert_eq!(after.temp, Some(2700));
    assert_eq!(after.effect, None);
    assert!(!after.is_pulsing());
}

#[tokio::test]
async fn a_reported_dimming_the_builder_would_refuse_still_parses() {
    let bulb = MockBulb::builder()
        .pilot(json!({"mac": "aabbccddeeff", "state": false, "dimming": 0}))
        .start()
        .await;
    let client = connect(&bulb).await;
    assert_eq!(client.get_pilot().await.unwrap().dimming, Some(0));
    assert!(Dimming::new(0).is_err());
}