huesmith 0.1.0

Hue-compatible Zigbee light library for ESP32-C6/H2 (ESP-IDF)
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
pub mod cluster;
pub mod command;
pub mod endpoint;
pub mod ffi;
pub mod reporting;
pub mod scene;
pub mod signal;

use huesmith_core::hue::device::{HueDeviceType, PROFILE_HA};
use huesmith_core::hue::identity::DeviceIdentity;
use huesmith_core::light::state::LightState;

use core::cell::RefCell;

/// Configuration passed from the builder to the Zigbee stack.
/// Created via `Box::leak` in `driver::launch` so it is `'static`.
pub(crate) struct Config {
    pub device_type: HueDeviceType,
    pub identity: &'static DeviceIdentity,
    /// Custom IEEE EUI-64 address. `None` → use chip efuse ID (unique per module).
    pub mac: Option<[u8; 8]>,
    pub channel: Option<u8>,
    pub endpoint_id: u8,
}

/// === CRITICAL SINGLE-TASKING ASSUMPTION ===
///
/// `LIGHT_STATE` uses `RefCell` wrapped in `static mut`. This is **only safe**
/// because all ZBOSS callbacks (action handler, BDB signal handler, etc.) are
/// invoked from the **same single FreeRTOS task** running `esp_zb_stack_main_loop()`.
///
/// If concurrency is ever added (a second task, ISR, or async) this MUST be
/// replaced with a proper synchronization mechanism (mutex, channel, or atomic).
static mut LIGHT_STATE: Option<RefCell<LightState>> = None;
/// Set once in `run` before the ZBOSS task starts; the single source for
/// endpoint id and device capabilities inside FFI callbacks (deriving them via
/// `HueDeviceType`'s methods instead of caching one bool static per flag).
static mut CONFIG: Option<&'static Config> = None;
static mut TRANSITION_ALARM_SCHEDULED: bool = false;
static mut IDENTIFY_ALARM_SCHEDULED: bool = false;

/// Shared accessor for the global light state.
///
/// SAFETY: relies on the single-tasking invariant documented above — every
/// caller runs on the same ZBOSS task, so the returned reference is never
/// aliased while a `borrow_mut` is live. It goes through a raw pointer
/// (`addr_of!`) rather than referencing the `static mut` directly, which keeps
/// it sound under the Rust 2024 `static_mut_refs` rule and confines the unsafe
/// static access to this one function. The reference is `'static` because
/// `LIGHT_STATE` is assigned once in `run` and never reassigned or dropped.
unsafe fn light_state() -> Option<&'static RefCell<LightState>> {
    (*core::ptr::addr_of!(LIGHT_STATE)).as_ref()
}

/// Shared accessor for the device configuration; same single-tasking and
/// assign-once reasoning as [`light_state`].
unsafe fn device_config() -> Option<&'static Config> {
    *core::ptr::addr_of!(CONFIG)
}

/// Initialize and run the Zigbee stack. This function never returns.
pub(crate) fn run(config: &'static Config, light_state: LightState, nvram_erase: bool) -> ! {
    let initial_on = light_state.on;
    let initial_level = light_state.brightness;

    // SAFETY: one-time initialization before the ZBOSS task starts — nothing
    // else can observe these statics yet (see single-tasking note above).
    unsafe {
        LIGHT_STATE = Some(RefCell::new(light_state));
        CONFIG = Some(config);
    }

    let mut platform_cfg: ffi::esp_zb_platform_config_t = unsafe { core::mem::zeroed() };
    platform_cfg.radio_config.radio_mode = ffi::RADIO_MODE_NATIVE;
    platform_cfg.host_config.host_connection_mode = ffi::HOST_CONNECTION_MODE_NONE;
    unsafe {
        let ret = ffi::esp_zb_platform_config(&platform_cfg);
        if ret != 0 {
            log::error!("esp_zb_platform_config failed: {ret} — radio may not come up");
        }
        ffi::esp_zb_nvram_erase_at_start(nvram_erase);
        ffi::esp_zb_io_buffer_size_set(254);
        ffi::esp_zb_scheduler_queue_size_set(254);
    }

    let zb_cfg = ffi::esp_zb_cfg_t {
        esp_zb_role: ffi::ZB_ROUTER,
        install_code_policy: false,
        nwk_cfg: ffi::esp_zb_nwk_cfg_t::zczr(10),
    };
    unsafe {
        ffi::esp_zb_init(&zb_cfg);
    }

    // Set custom MAC only when explicitly provided; otherwise let ZBOSS derive
    // the EUI-64 from the chip's efuse, which is unique per module.
    if let Some(mac) = config.mac {
        unsafe {
            ffi::esp_zb_set_long_address(mac.as_ptr());
        }
    }

    let mut mac_readback = [0u8; 8];
    unsafe {
        ffi::esp_zb_get_long_address(mac_readback.as_mut_ptr());
    }
    log::info!(
        "IEEE MAC: {:02X}:{:02X}:{:02X}:{:02X}:{:02X}:{:02X}:{:02X}:{:02X}",
        mac_readback[7],
        mac_readback[6],
        mac_readback[5],
        mac_readback[4],
        mac_readback[3],
        mac_readback[2],
        mac_readback[1],
        mac_readback[0],
    );

    log_struct_sizes();

    log::info!(
        "CONFIG: device={:?} identity={} {} endpoint={} channel={:?} custom_mac={}",
        config.device_type,
        config.identity.manufacturer_name,
        config.identity.model_identifier,
        config.endpoint_id,
        config.channel,
        config.mac.is_some(),
    );

    let channel_mask = config
        .channel
        .map(|ch| 1u32 << ch)
        .unwrap_or(ffi::ALL_CHANNELS_MASK);
    unsafe {
        ffi::esp_zb_set_primary_network_channel_set(channel_mask);
        ffi::esp_zb_enable_joining_to_distributed(true);
    }

    let mut tc_key: [u8; 16] = ffi::ZLL_TC_LINK_KEY;
    unsafe {
        ffi::esp_zb_secur_TC_standard_distributed_key_set(tc_key.as_mut_ptr());
    }

    let ep_list = unsafe { ffi::esp_zb_ep_list_create() };

    endpoint::EndpointBuilder::new(config.endpoint_id, config.device_type, config.identity)
        .profile_id(PROFILE_HA)
        .initial_on(initial_on)
        .initial_level(initial_level)
        .register(ep_list);

    unsafe {
        let ret = ffi::esp_zb_device_register(ep_list);
        if ret != 0 {
            log::error!("esp_zb_device_register failed: {ret} — device will not pair");
        }
    }

    verify_endpoint(config.endpoint_id, config.device_type);

    unsafe {
        // Configure reporting from the joined hook (after the network is up),
        // mirroring the sensor stack. Calling esp_zb_zcl_update_reporting_info
        // before esp_zb_start can fail because the ZCL reporting subsystem is
        // not initialised yet.
        signal::set_joined_hook(light_joined_hook);
        ffi::esp_zb_core_action_handler_register(Some(action_handler_cb));
    }
    scene::register_privilege_commands(config.endpoint_id);

    log::info!("Starting Zigbee stack...");
    unsafe {
        let ret = ffi::esp_zb_start(false);
        if ret != 0 {
            panic!("esp_zb_start failed: {}", ret);
        }
    }

    log::info!("Entering Zigbee main loop");
    unsafe {
        ffi::esp_zb_stack_main_loop();
    }
    unreachable!()
}

/// # Safety
///
/// Called by ZBOSS from the Zigbee stack task with a valid, non-null signal
/// pointer; must only ever be invoked by the C stack (the `#[no_mangle]` name
/// is the contract). Runs on the single ZBOSS task, upholding the
/// `LIGHT_STATE` invariant documented above.
#[no_mangle]
pub unsafe extern "C" fn esp_zb_app_signal_handler(signal_s: *mut ffi::esp_zb_app_signal_t) {
    // ZBOSS is contracted to pass a valid struct, but guard the two derefs
    // anyway: a null here would abort the whole device, and the cost is one
    // branch on a low-frequency lifecycle callback.
    if signal_s.is_null() {
        return;
    }
    // SAFETY: non-null per the check above; valid for the duration of the call.
    let sig = &*signal_s;
    if sig.p_app_signal.is_null() {
        return;
    }
    let sig_type = *sig.p_app_signal;
    let status = sig.esp_err_status;
    let bdb_signal = signal::BdbSignal::from_raw(sig_type, status);
    signal::handle_bdb_signal(bdb_signal);
}

/// Fires once the network is joined (steering success) or resumed after a
/// reboot. Sets up default attribute reporting now that the stack is live.
unsafe fn light_joined_hook() {
    if let Some(config) = device_config() {
        reporting::setup_default_reporting(config.endpoint_id, config.device_type);
    }
}

fn log_struct_sizes() {
    log::info!(
        "FFI sizes: cb_info={} set_attr_msg={} zcl_attr={} endpoint_cfg={}",
        core::mem::size_of::<ffi::esp_zb_device_cb_common_info_t>(),
        core::mem::size_of::<ffi::esp_zb_zcl_set_attr_value_message_t>(),
        core::mem::size_of::<ffi::esp_zb_zcl_attribute_t>(),
        core::mem::size_of::<ffi::esp_zb_endpoint_config_t>(),
    );
}

fn verify_endpoint(ep: u8, device_type: HueDeviceType) {
    let required: &[(u16, u16, &str)] = &[
        (
            ffi::CLUSTER_BASIC,
            ffi::ATTR_BASIC_ZCL_VERSION,
            "ZCLVersion",
        ),
        (
            ffi::CLUSTER_BASIC,
            ffi::ATTR_BASIC_MANUFACTURER_NAME,
            "ManufacturerName",
        ),
        (
            ffi::CLUSTER_BASIC,
            ffi::ATTR_BASIC_MODEL_IDENTIFIER,
            "ModelIdentifier",
        ),
        (ffi::CLUSTER_ON_OFF, ffi::ATTR_ON_OFF, "OnOff"),
    ];
    let level: &[(u16, u16, &str)] = &[(
        ffi::CLUSTER_LEVEL_CONTROL,
        ffi::ATTR_LEVEL_CURRENT_LEVEL,
        "CurrentLevel",
    )];
    let color: &[(u16, u16, &str)] = &[
        (
            ffi::CLUSTER_COLOR_CONTROL,
            ffi::ATTR_COLOR_TEMPERATURE_MIREDS,
            "ColorTempMireds",
        ),
        (
            ffi::CLUSTER_COLOR_CONTROL,
            ffi::ATTR_COLOR_CAPABILITIES,
            "ColorCapabilities",
        ),
    ];

    // Probe only the clusters this device type actually registers — an on/off
    // light has no Level Control, so probing it would warn on every boot.
    let level_checks = if device_type.has_level_control() {
        level.iter()
    } else {
        [].iter()
    };
    let color_checks = if device_type.has_color_control() {
        color.iter()
    } else {
        [].iter()
    };

    for &(cluster, attr, name) in required.iter().chain(level_checks).chain(color_checks) {
        let ptr = unsafe {
            ffi::esp_zb_zcl_get_attribute(ep, cluster, ffi::ZB_ZCL_CLUSTER_SERVER_ROLE, attr)
        };
        if ptr.is_null() {
            log::warn!(
                "VERIFY EP{}: cluster 0x{:04X} attr 0x{:04X} ({}) = NULL",
                ep,
                cluster,
                attr,
                name
            );
        }
    }
}

unsafe fn handle_identify_effect(message: *const core::ffi::c_void) {
    if message.is_null() {
        return;
    }
    // SAFETY: for IDENTIFY_EFFECT_CB_ID the stack passes a
    // esp_zb_zcl_identify_effect_message_t, valid for the duration of the callback.
    let msg = &*(message as *const ffi::esp_zb_zcl_identify_effect_message_t);
    log::info!(
        "TriggerEffect: effect=0x{:02X} variant=0x{:02X}",
        msg.effect_id,
        msg.effect_variant,
    );
    let cmd = huesmith_core::light::command::LightCommand::TriggerEffect {
        effect_id: msg.effect_id,
        variant: msg.effect_variant,
    };
    if let Some(state) = light_state() {
        state.borrow_mut().apply_command(&cmd);
    }
}

// SAFETY of the signature: callback_id is `esp_zb_core_action_callback_id_t`
// (a C enum = int-sized), so this must take u32 to match the registered
// function type exactly.
unsafe extern "C" fn action_handler_cb(callback_id: u32, message: *const core::ffi::c_void) -> i32 {
    match callback_id {
        ffi::ESP_ZB_CORE_SET_ATTR_VALUE_CB_ID => {
            handle_set_attribute(message);
        }
        ffi::ESP_ZB_CORE_IDENTIFY_EFFECT_CB_ID => {
            handle_identify_effect(message);
            schedule_identify_if_active();
        }
        ffi::ESP_ZB_CORE_SCENES_STORE_SCENE_CB_ID => {
            let has_color = device_config().is_some_and(|c| c.device_type.has_color_control());
            return scene::handle_store_scene(message, light_state(), has_color);
        }
        ffi::ESP_ZB_CORE_SCENES_RECALL_SCENE_CB_ID => {
            let has_color = device_config().is_some_and(|c| c.device_type.has_color_control());
            let ret = scene::handle_recall_scene(message, light_state(), has_color);
            schedule_transition_if_active();
            return ret;
        }
        ffi::ESP_ZB_CORE_CMD_PRIVILEGE_COMMAND_REQ_CB_ID => {
            return scene::handle_privilege_command(message);
        }
        _ => {
            log::debug!("Unhandled Zigbee action: 0x{:04X}", callback_id);
        }
    }
    0
}

unsafe fn schedule_transition_if_active() {
    if let Some(state) = light_state() {
        let state = state.borrow();
        let active = state.transition_active();
        let delay_ms = state.transition_step_interval_ms() as u32;
        drop(state);
        if active {
            ensure_transition_step_scheduled(delay_ms);
        }
    }
}

unsafe fn handle_set_attribute(message: *const core::ffi::c_void) {
    if message.is_null() {
        log::warn!("Set attribute: NULL message");
        return;
    }

    // SAFETY: for SET_ATTR_VALUE_CB_ID the stack passes a
    // esp_zb_zcl_set_attr_value_message_t, valid for the duration of the callback.
    let msg_ptr = message as *const ffi::esp_zb_zcl_set_attr_value_message_t;
    let msg = &*msg_ptr;

    let status = msg.info.status;
    let cluster = msg.info.cluster;
    let dst_ep = msg.info.dst_endpoint;
    let attr_id = msg.attribute.id;
    let attr_type = { msg.attribute.data.type_ };
    let attr_size = { msg.attribute.data.size };
    let attr_value = { msg.attribute.data.value };

    log::debug!(
        "SET_ATTR: ep={} cluster=0x{:04X} attr=0x{:04X} type=0x{:02X} size={} status={}",
        dst_ep,
        cluster,
        attr_id,
        attr_type,
        attr_size,
        status,
    );

    if status != ffi::ZCL_STATUS_SUCCESS as u32 {
        log::warn!("Set attribute failed: status {}", status);
        return;
    }

    if attr_value.is_null() {
        log::warn!("Set attribute: NULL value");
        return;
    }

    if let Some(cmd) =
        command::parse_set_attribute(cluster, attr_id, attr_size, attr_value as *const _)
    {
        log::info!("Command: {:?}", cmd);
        let is_identify = matches!(
            cmd,
            huesmith_core::light::command::LightCommand::Identify { .. }
        );
        if let Some(state) = light_state() {
            state.borrow_mut().apply_command(&cmd);
        }
        if is_identify {
            schedule_identify_if_active();
        } else {
            schedule_transition_if_active();
        }
    }
}

unsafe extern "C" fn transition_step_cb(_param: u8) {
    TRANSITION_ALARM_SCHEDULED = false;

    if let Some(state) = light_state() {
        let mut state = state.borrow_mut();
        let still_active = state.step_transition();
        let delay_ms = state.transition_step_interval_ms() as u32;
        drop(state);
        if still_active {
            ensure_transition_step_scheduled(delay_ms);
        }
    }
}

unsafe fn ensure_transition_step_scheduled(delay_ms: u32) {
    if TRANSITION_ALARM_SCHEDULED {
        return;
    }
    TRANSITION_ALARM_SCHEDULED = true;
    ffi::esp_zb_scheduler_alarm(transition_step_cb, 0, delay_ms.max(1));
}

unsafe extern "C" fn identify_step_cb(_param: u8) {
    IDENTIFY_ALARM_SCHEDULED = false;
    if let Some(state) = light_state() {
        let mut state = state.borrow_mut();
        let still_active = state.step_identify();
        drop(state);
        if still_active {
            schedule_identify_step();
        }
    }
}

unsafe fn schedule_identify_step() {
    if IDENTIFY_ALARM_SCHEDULED {
        return;
    }
    IDENTIFY_ALARM_SCHEDULED = true;
    ffi::esp_zb_scheduler_alarm(identify_step_cb, 0, 500); // 500 ms per half-cycle = 0.5 Hz
}

unsafe fn schedule_identify_if_active() {
    if let Some(state) = light_state() {
        let active = state.borrow().identify_active();
        if active {
            schedule_identify_step();
        }
    }
}