diff --git a/docs/changelog_fw.md b/docs/changelog_fw.md index 80691ccac6..90191f783f 100644 --- a/docs/changelog_fw.md +++ b/docs/changelog_fw.md @@ -8,6 +8,19 @@ Please describe what you are working on, under ## Upcoming -------------------------------------------------------> +## Upcoming + +### Features + +- **Countdown timers** (`on_with_timed_off`) for relay endpoints. The ZCL command was already + accepted by the stack but ignored by the cluster callback, so the relay stayed on indefinitely. + `on_time` and `off_wait_time` are now honoured. Any local change cancels a pending countdown, + and a repeated `on_with_timed_off` re-arms it instead of cancelling it. + The longest countdown is 6553 s, the maximum the ZCL command can carry. + Implemented for Telink router builds; end device builds sleep between polls and the + system clock stops while they do, so the deadline could not be reached on time there. + The Silabs platform is not covered by this change. + ## 1.1.3 ### Features diff --git a/readme.md b/readme.md index 8a6361a3fa..468553fb0b 100644 --- a/readme.md +++ b/readme.md @@ -36,10 +36,10 @@ Users also consider this _the missing piece of a reliable smart home,_ because i - Multiple **reset options** (configurable multi-press count, on-board button) - **Wireless switches** (battery-powered remotes) - **Curtain modules** +- **Countdown timers** (`on_with_timed_off`) ### Work in progress - FW-level multi-press (double or triple click) - [progress](https://github.com/romasku/tuya-zigbee-switch/pull/380) -- Countdown timers (on_with_timed_off) - Inching (pulse relay output) - Scenes (send and receive) - Power monitoring - [progress](https://github.com/romasku/tuya-zigbee-switch/pull/314) diff --git a/src/app.c b/src/app.c index 20ea9c51f1..f07d76c221 100644 --- a/src/app.c +++ b/src/app.c @@ -9,6 +9,7 @@ #include "hal/zigbee_ota.h" #include "zigbee/battery_cluster.h" #include "zigbee/general_commands.h" +#include "zigbee/relay_cluster.h" #ifdef END_DEVICE #include "zigbee/poll_control_cluster.h" #endif @@ -56,6 +57,10 @@ void app_init(void) { static bool boot_announce_sent = false; void app_task() { +#ifdef HAL_HAS_TIMER_64 + relay_cluster_task(); +#endif + #ifdef END_DEVICE poll_control_cluster_update(); #endif diff --git a/src/hal/tick64.h b/src/hal/tick64.h new file mode 100644 index 0000000000..130cc0f98e --- /dev/null +++ b/src/hal/tick64.h @@ -0,0 +1,87 @@ +#ifndef _HAL_TICK64_H_ +#define _HAL_TICK64_H_ + +#include + +/** + * Wrap-safe millisecond counter for a 16 MHz free-running tick. + * + * clock_time() is a 32-bit counter clocked at 16 MHz, so it wraps every + * 2^32 / 16e6 = 268.435456 s. + * + * The old hal_millis() divided the raw tick by 16000 and tracked the wrap + * of that derived value. The derived value only spans 0..268435 ms, so the + * wrap counter was shifted left by 32 bits: every hardware wrap added + * 2^32 ms (~49.7 days) instead of the ~268 s that really elapsed. The + * result was not a millisecond timeline, and every deadline longer than + * one wrap was reached at the wrap boundary instead of at its deadline. + * + * The counter below advances by the elapsed tick delta instead. The delta + * is a plain uint32 subtraction, so it stays correct across the wrap. + * The sub-millisecond remainder is carried over, because a tick period is + * 268435.456 ms rather than a whole number of milliseconds. + * + * Only 32-bit division is used: the tc32 toolchain has no __udivdi3. + * + * Deadlines of any length compare correctly, up to the ZCL On With Timed + * Off maximum of 6553 s. + * + * The header is dependency-free so the firmware and the regression test + * compile the same code. + */ + +/** Ticks per millisecond for the 16 MHz system timer. */ +#define HAL_TICK64_TICKS_PER_MS 16000 + +/** State of the counter. */ +typedef struct { + uint32_t last; /**< raw tick seen on the previous read */ + uint32_t frac; /**< ticks carried over, always < HAL_TICK64_TICKS_PER_MS */ + uint64_t ms; /**< whole milliseconds since boot */ + uint8_t started; /**< set after the first read */ +} hal_tick64_state; + +/** Reset the state. Call once before the first use. */ +static inline void hal_tick64_init(hal_tick64_state *state) { + state->last = 0; + state->frac = 0; + state->ms = 0; + state->started = 0; +} + +/** + * Advance the counter to the given raw tick and return the elapsed + * milliseconds since boot. + * + * The first read establishes the origin from the tick itself, so the + * result is boot-relative from the start. Every later read adds the + * elapsed interval. + */ +static inline uint64_t hal_tick64_millis(hal_tick64_state *state, uint32_t now) { + if (!state->started) { + // First read: the raw tick already carries the time since boot. + state->started = 1; + state->last = now; + state->frac = now % HAL_TICK64_TICKS_PER_MS; + state->ms = now / HAL_TICK64_TICKS_PER_MS; + return state->ms; + } + + // Ticks since the previous read. Modulo 2^32 this is the true elapsed + // tick count even across a hardware wrap, as long as less than one tick + // period passes between reads. + uint32_t delta = now - state->last; + state->last = now; + + // Whole milliseconds in the delta, plus the carried remainder. + uint32_t whole = delta / HAL_TICK64_TICKS_PER_MS; + uint32_t rem = state->frac + (delta % HAL_TICK64_TICKS_PER_MS); + uint32_t carry = rem / HAL_TICK64_TICKS_PER_MS; + state->frac = rem % HAL_TICK64_TICKS_PER_MS; + + state->ms += (uint64_t)whole + (uint64_t)carry; + + return state->ms; +} + +#endif diff --git a/src/hal/timer.h b/src/hal/timer.h index 0228b4f917..d7afaa364d 100644 --- a/src/hal/timer.h +++ b/src/hal/timer.h @@ -6,7 +6,37 @@ /** * Get milliseconds elapsed since system initialization * @return Number of milliseconds since system started + * + * This is the low 32 bits of the true millisecond timeline, so it wraps + * every 2^32 ms (~49.7 days) and "now - then" differences are correct + * for any interval shorter than that. */ uint32_t hal_millis(); +/** + * Platforms with a 64-bit monotonic millisecond counter. The countdown + * timer needs one to compare a deadline against the current time. + * + * End device builds are excluded: they sleep between polls, and the + * system clock stops while they do, so a deadline could never be + * reached on time. + */ +#if !defined(END_DEVICE) && (defined(HAL_TELINK) || defined(HAL_STUB)) +#define HAL_HAS_TIMER_64 1 +#endif + +#ifdef HAL_HAS_TIMER_64 + +/** + * Monotonic 64-bit millisecond counter. Safe for any deadline comparison. + * + * The counter is derived from the raw hardware tick, so it advances by + * exactly one millisecond per millisecond of real time across the + * hardware counter's ~268 s wrap. Deadlines of any length (up to the + * ZCL On With Timed Off maximum of 6553 s) compare correctly. + */ +uint64_t hal_millis_64(void); + +#endif + #endif diff --git a/src/stub/commands.c b/src/stub/commands.c index b750011a81..c281078eeb 100644 --- a/src/stub/commands.c +++ b/src/stub/commands.c @@ -8,6 +8,7 @@ #include "stub/stub_app.h" #include "zigbee/consts.h" +#include "zigbee/relay_cluster.h" #include #include #include @@ -355,6 +356,12 @@ static int cmd_step_time(int argc, char **argv) { } stub_millis_step((uint64_t)step); io_res_ok("stepped_ms=%ld", step); +#ifdef HAL_HAS_TIMER_64 + // Re-evaluate the auto-off timers against the new time. + // Deliberately not stub_app_poll(): its network-steering branch would + // restart joining right after a test triggered a factory reset. + relay_cluster_task(); +#endif return 0; } diff --git a/src/stub/hal/timer.c b/src/stub/hal/timer.c index dca9c62ae3..6d77d54966 100644 --- a/src/stub/hal/timer.c +++ b/src/stub/hal/timer.c @@ -62,3 +62,21 @@ uint32_t hal_millis() { return result; } + +uint64_t hal_millis_64(void) { + // Monotonic 64-bit counter, never truncated like hal_millis(). + if (!initialized) { + stub_millis_init(); + } + if (time_frozen) { + return frozen_millis; + } + struct timeval current_time; + if (gettimeofday(¤t_time, NULL) != 0) { + io_log("TIMER", "Error: Failed to get current time"); + exit(1); + } + uint64_t current_ms = + (uint64_t)current_time.tv_sec * 1000 + current_time.tv_usec / 1000; + return current_ms - start_ms; +} diff --git a/src/telink/hal/timer.c b/src/telink/hal/timer.c index 150412623f..4d9b99c3d4 100644 --- a/src/telink/hal/timer.c +++ b/src/telink/hal/timer.c @@ -1,11 +1,23 @@ #include "hal/timer.h" +#include "hal/tick64.h" #pragma pack(push, 1) #include "tl_common.h" #pragma pack(pop) #include +// clock_time() is a 32-bit counter at 16 MHz: it wraps every 268.435456 s. +// hal_tick64_millis() counts the elapsed tick delta, so the value stays +// monotonic across that wrap. +static hal_tick64_state s_tick_state; + uint32_t hal_millis() { - // Convert system ticks directly to milliseconds - // clock_time() returns ticks at 16MHz, so divide by 16000 for milliseconds - return clock_time() / CLOCK_16M_SYS_TIMER_CLK_1MS; + // Low 32 bits of the true millisecond timeline, so it wraps every + // ~49.7 days and "now - then" differences stay correct. + return (uint32_t)hal_tick64_millis(&s_tick_state, clock_time()); +} + +uint64_t hal_millis_64(void) { + // Monotonic across the hardware tick wrap. Deadlines of any length + // compare correctly (the ZCL On With Timed Off maximum is 6553 s). + return hal_tick64_millis(&s_tick_state, clock_time()); } diff --git a/src/zigbee/relay_cluster.c b/src/zigbee/relay_cluster.c index 57386ddb84..afb2659221 100644 --- a/src/zigbee/relay_cluster.c +++ b/src/zigbee/relay_cluster.c @@ -4,6 +4,7 @@ #include "device_config/nvm_items.h" #include "hal/nvm.h" #include "hal/printf_selector.h" +#include "hal/timer.h" hal_zigbee_cmd_result_t relay_cluster_callback(zigbee_relay_cluster *cluster, uint8_t command_id, @@ -36,6 +37,11 @@ void relay_cluster_handle_startup_mode(zigbee_relay_cluster *cluster); void sync_indicator_led(zigbee_relay_cluster *cluster); +#ifdef HAL_HAS_TIMER_64 +void relay_cluster_task(void); + +#endif + zigbee_relay_cluster *relay_cluster_by_endpoint[10]; void relay_cluster_callback_attr_write_trampoline(uint8_t endpoint, @@ -61,6 +67,10 @@ void relay_cluster_add_to_endpoint(zigbee_relay_cluster *cluster, cluster->relay->callback_param = cluster; cluster->relay->on_change = (relay_callback_t)relay_cluster_on_relay_change; +#ifdef HAL_HAS_TIMER_64 + cluster->off_timer_active = 0; +#endif + relay_cluster_handle_startup_mode(cluster); sync_indicator_led(cluster); @@ -109,18 +119,68 @@ hal_zigbee_cmd_result_t relay_cluster_callback(zigbee_relay_cluster *cluster, switch (command_id) { case ZCL_CMD_ONOFF_ON: case ZCL_CMD_ON_WITH_RECALL_GLOBAL_SCENE: +#ifdef HAL_HAS_TIMER_64 + cluster->off_timer_active = 0; +#endif relay_cluster_on(cluster); break; case ZCL_CMD_ONOFF_OFF: case ZCL_CMD_OFF_WITH_EFFECT: +#ifdef HAL_HAS_TIMER_64 + cluster->off_timer_active = 0; +#endif relay_cluster_off(cluster); break; case ZCL_CMD_ONOFF_TOGGLE: +#ifdef HAL_HAS_TIMER_64 + cluster->off_timer_active = 0; +#endif relay_cluster_toggle(cluster); break; +#ifdef HAL_HAS_TIMER_64 + case ZCL_CMD_ON_WITH_TIMED_OFF: { + // Payload layout (little-endian): + // [0] onOffCtrl, [1..2] onTime, [3..4] offWaitTime + // onTime and offWaitTime are in units of 100 ms. + if (cmd_payload == NULL || cmd_payload_len < 5) { + return HAL_ZIGBEE_MALFORMED_COMMAND; + } + const uint8_t *p = (const uint8_t *)cmd_payload; + uint16_t on_time = (uint16_t)p[1] | ((uint16_t)p[2] << 8); + uint16_t off_wait_time = (uint16_t)p[3] | ((uint16_t)p[4] << 8); + cluster->off_timer_active = 0; + + // ZCL case (0,0): turn OFF now. + if (on_time == 0 && off_wait_time == 0) { + relay_cluster_off(cluster); + return HAL_ZIGBEE_CMD_PROCESSED; + } + if (on_time > 0) { + // offWaitTime takes precedence when set, otherwise onTime. + uint32_t delay_ms = off_wait_time > 0 + ? (uint32_t)off_wait_time * 100 + : (uint32_t)on_time * 100; + if (delay_ms < 100) { + delay_ms = 100; // 0.1 s = 1 spec unit + } + // Drive the relay first: the on_change callback it fires + // cancels any pending timer, and we arm the new one after it. + relay_cluster_on(cluster); + cluster->off_timer_deadline_ms = + hal_millis_64() + (uint64_t)delay_ms; + cluster->off_timer_active = 1; + return HAL_ZIGBEE_CMD_PROCESSED; + } + // ZCL case onTime=0, offWaitTime>0: stay OFF for offWaitTime. + // The "wait, then turn ON" half is not implemented. + relay_cluster_off(cluster); + return HAL_ZIGBEE_CMD_PROCESSED; + } +#endif + default: printf("Unknown OnOff command: %d\r\n", command_id); return HAL_ZIGBEE_CMD_SKIPPED; @@ -147,6 +207,9 @@ hal_zigbee_cmd_result_t relay_cluster_level_callback(zigbee_relay_cluster *clust return HAL_ZIGBEE_MALFORMED_COMMAND; } uint8_t level = *(uint8_t *)cmd_payload; +#ifdef HAL_HAS_TIMER_64 + cluster->off_timer_active = 0; +#endif if (level == 0) { relay_cluster_off(cluster); } else { @@ -198,6 +261,10 @@ void relay_cluster_toggle(zigbee_relay_cluster *cluster) { void relay_cluster_on_relay_change(zigbee_relay_cluster *cluster, uint8_t state) { +#ifdef HAL_HAS_TIMER_64 + // A local action (button) cancels a pending auto-off. + cluster->off_timer_active = 0; +#endif hal_zigbee_notify_attribute_changed(cluster->endpoint, ZCL_CLUSTER_ON_OFF, ZCL_ATTR_ONOFF); if (cluster->startup_mode == ZCL_START_UP_ONOFF_SET_ONOFF_TOGGLE || @@ -292,3 +359,25 @@ void relay_cluster_handle_startup_mode(zigbee_relay_cluster *cluster) { // Restore indicator LED state sync_indicator_led(cluster); } + +#ifdef HAL_HAS_TIMER_64 +// Fire any expired auto-off timer. Called from app_task() every loop. +// +// The deadline is compared against a 64-bit millisecond counter, so it +// stays correct across the ~268 s hardware tick wrap of hal_millis(). +void relay_cluster_task(void) { + const uint64_t now_ms = hal_millis_64(); + + for (int ep = 0; ep < 10; ep++) { + zigbee_relay_cluster *cluster = relay_cluster_by_endpoint[ep]; + if (cluster == NULL || cluster->off_timer_active == 0) { + continue; + } + if (now_ms >= cluster->off_timer_deadline_ms) { + cluster->off_timer_active = 0; + relay_cluster_off(cluster); + } + } +} + +#endif diff --git a/src/zigbee/relay_cluster.h b/src/zigbee/relay_cluster.h index d0967d4e6b..47a0a35e16 100644 --- a/src/zigbee/relay_cluster.h +++ b/src/zigbee/relay_cluster.h @@ -5,6 +5,7 @@ #include "base_components/relay.h" #include +#include "hal/timer.h" #include "hal/zigbee.h" typedef struct { @@ -16,6 +17,13 @@ typedef struct { relay_t * relay; led_t * indicator_led; uint8_t indicator_state; + +#ifdef HAL_HAS_TIMER_64 + // Auto-off timer (ZCL On With Timed Off). 0 = no timer, 1 = armed. + uint8_t off_timer_active; + // Deadline in the hal_millis_64() time domain. + uint64_t off_timer_deadline_ms; +#endif } zigbee_relay_cluster; void relay_cluster_add_to_endpoint(zigbee_relay_cluster *cluster, @@ -29,6 +37,12 @@ void relay_cluster_report(zigbee_relay_cluster *cluster); void update_relay_clusters(); +#ifdef HAL_HAS_TIMER_64 +// Fire any expired auto-off timer. Call from app_task(). +void relay_cluster_task(void); + +#endif + void relay_cluster_callback_attr_write_trampoline(uint8_t endpoint, uint16_t attribute_id); diff --git a/tests/test_relay_cluster_button_pairing.py b/tests/test_relay_cluster_button_pairing.py new file mode 100644 index 0000000000..cfb976a1cf --- /dev/null +++ b/tests/test_relay_cluster_button_pairing.py @@ -0,0 +1,235 @@ +"""Which button cancels which relay's timer when the wiring is crossed. + +The switch-to-relay pairing comes from two per-type counters in +``config_parser.c``: + + switch_clusters[n].relay_index = n + 1; (n = index of the Nth 'S' entry) + relay_clusters[m].relay = &relays[m]; (m = index of the Nth 'R' entry) + +So the Nth 'S' entry drives the Nth 'R' entry — in the ORDER OF +APPEARANCE WITHIN EACH TYPE, not in the order the entries sit in the +config string, and not by which pin is physically nearest. + +That is what makes a crossed wiring possible at all. A two-gang board +whose left button is wired to the right relay is expressed as + + SA0u;RB1;SA1u;RB0; + +— the 'R' entries are listed in the opposite order to the 'S' entries. +Switch 1 (pin A0) then drives relay 1 (pin B1, endpoint 3) and switch 2 +(pin A1) drives relay 2 (pin B0, endpoint 4). + +The rule for the timer is simple and does not change with the wiring: +**a button cancels the timer of the relay it drives, and of no other.** +The timer belongs to the relay endpoint; the button only reaches it +through the relay it is paired with. + +These tests pin both halves down: the pairing under a crossed wiring, +and the fact that the button cancels its own relay's timer while +leaving the other one armed. +""" + +import pytest + +from tests.client import StubProc +from tests.conftest import Device +from tests.zcl_consts import ( + ZCL_ATTR_ONOFF, + ZCL_ATTR_ONOFF_CONFIGURATION_SWITCH_ACTIONS, + ZCL_ATTR_ONOFF_CONFIGURATION_SWITCH_MODE, + ZCL_CLUSTER_ON_OFF, + ZCL_CLUSTER_ON_OFF_SWITCH_CONFIG, + ZCL_CMD_ON_WITH_TIMED_OFF, + ZCL_ONOFF_CONFIGURATION_SWITCH_ACTION_ONOFF, + ZCL_ONOFF_CONFIGURATION_SWITCH_TYPE_MOMENTARY, +) + + +def _payload(on_time: int, off_wait_time: int = 0) -> list[int]: + on_lo, on_hi = on_time & 0xFF, (on_time >> 8) & 0xFF + off_lo, off_hi = off_wait_time & 0xFF, (off_wait_time >> 8) & 0xFF + return [0x00, on_lo, on_hi, off_lo, off_hi] + + +def _on_with_timed_off(device: Device, ep: int, on_time: int) -> None: + device.call_zigbee_cmd( + ep, + ZCL_CLUSTER_ON_OFF, + ZCL_CMD_ON_WITH_TIMED_OFF, + payload_bytes=_payload(on_time), + ) + + +def _make_momentary(device: Device, switch_ep: int) -> None: + """A momentary switch whose press drives the relay ON. + + ONOFF action is used on purpose: it drives the relay without + changing its state, so the relay stays ON and a surviving timer + would switch it OFF at its deadline. + """ + device.write_zigbee_attr( + switch_ep, + ZCL_CLUSTER_ON_OFF_SWITCH_CONFIG, + ZCL_ATTR_ONOFF_CONFIGURATION_SWITCH_MODE, + ZCL_ONOFF_CONFIGURATION_SWITCH_TYPE_MOMENTARY, + ) + device.write_zigbee_attr( + switch_ep, + ZCL_CLUSTER_ON_OFF_SWITCH_CONFIG, + ZCL_ATTR_ONOFF_CONFIGURATION_SWITCH_ACTIONS, + ZCL_ONOFF_CONFIGURATION_SWITCH_ACTION_ONOFF, + ) + + +# Crossed wiring: switch 1 (pin A0) -> relay 1 (pin B1), switch 2 +# (pin A1) -> relay 2 (pin B0). The 'R' entries are in the opposite +# order to the 'S' entries. +CROSSED_CFG = "X;Y;SA0u;RB1;SA1u;RB0;" +# Straight wiring, for comparison: switch 1 -> relay on B0. +STRAIGHT_CFG = "X;Y;SA0u;RB0;SA1u;RB1;" + + +@pytest.fixture() +def crossed() -> Device: + with StubProc(device_config=CROSSED_CFG) as proc: + yield Device(proc) + + +@pytest.fixture() +def straight() -> Device: + with StubProc(device_config=STRAIGHT_CFG) as proc: + yield Device(proc) + + +# --- the pairing under a crossed wiring ---------------------------------- + + +def test_crossed_switch1_drives_relay1(crossed: Device) -> None: + """With the 'R' entries reversed, switch 1 drives the relay on pin B1. + + The relay endpoints follow the 'R' order, so the relay on pin B1 + is endpoint 3 and the one on pin B0 is endpoint 4. + """ + _make_momentary(crossed, 1) + _on_with_timed_off(crossed, 3, 100) # 10 s on endpoint 3 + assert crossed.get_gpio("B1") + assert not crossed.get_gpio("B0") + crossed.click_button("A0") + assert crossed.get_gpio("B1", refresh=True) + assert not crossed.get_gpio("B0", refresh=True), ( + "switch 1 drove the relay on B0 — the pairing is not by the " + "order of the 'R' entries" + ) + + +def test_crossed_switch2_drives_relay2(crossed: Device) -> None: + """Switch 2 drives the relay on pin B0, which is endpoint 4.""" + _make_momentary(crossed, 2) + _on_with_timed_off(crossed, 4, 100) # 10 s on endpoint 4 + assert crossed.get_gpio("B0") + crossed.click_button("A1") + assert crossed.get_gpio("B0", refresh=True) + assert not crossed.get_gpio("B1", refresh=True), ( + "switch 2 drove the relay on B1 — the pairing is not by the " + "order of the 'R' entries" + ) + + +def test_straight_switch1_drives_relay_on_b0(straight: Device) -> None: + """The straight wiring pairs switch 1 with the relay on pin B0.""" + _make_momentary(straight, 1) + _on_with_timed_off(straight, 3, 100) + assert straight.get_gpio("B0") + straight.click_button("A0") + assert straight.get_gpio("B0", refresh=True) + assert not straight.get_gpio("B1", refresh=True) + + +# --- which timer does the button cancel under a crossed wiring ------------ + + +def test_crossed_button1_cancels_relay1_timer(crossed: Device) -> None: + """Switch 1 cancels the timer of the relay it drives (endpoint 3).""" + _make_momentary(crossed, 1) + _on_with_timed_off(crossed, 3, 100) # 10 s + crossed.step_time(5_000) + crossed.click_button("A0") + crossed.step_time(6_000) # past the deadline + assert crossed.get_gpio("B1", refresh=True), ( + "switch 1 did not cancel the timer of the relay it drives" + ) + + +def test_crossed_button1_leaves_relay2_timer_running(crossed: Device) -> None: + """Switch 1 must not cancel the timer of the OTHER relay.""" + _make_momentary(crossed, 1) + _on_with_timed_off(crossed, 4, 100) # 10 s on the relay switch 1 does NOT drive + crossed.step_time(5_000) + crossed.click_button("A0") + crossed.step_time(6_000) + assert not crossed.get_gpio("B0", refresh=True), ( + "switch 1 cancelled the timer of the relay it does not drive" + ) + + +def test_crossed_button2_cancels_relay2_timer(crossed: Device) -> None: + """Switch 2 cancels the timer of the relay it drives (endpoint 4).""" + _make_momentary(crossed, 2) + _on_with_timed_off(crossed, 4, 100) # 10 s + crossed.step_time(5_000) + crossed.click_button("A1") + crossed.step_time(6_000) + assert crossed.get_gpio("B0", refresh=True), ( + "switch 2 did not cancel the timer of the relay it drives" + ) + + +def test_crossed_button2_leaves_relay1_timer_running(crossed: Device) -> None: + """Switch 2 must not cancel the timer of the OTHER relay.""" + _make_momentary(crossed, 2) + _on_with_timed_off(crossed, 3, 100) # 10 s on the relay switch 2 does NOT drive + crossed.step_time(5_000) + crossed.click_button("A1") + crossed.step_time(6_000) + assert not crossed.get_gpio("B1", refresh=True), ( + "switch 2 cancelled the timer of the relay it does not drive" + ) + + +def test_crossed_both_buttons_cancel_their_own_timers(crossed: Device) -> None: + """Each button cancels its own relay's timer, and the other timer + still fires.""" + _make_momentary(crossed, 1) + _make_momentary(crossed, 2) + _on_with_timed_off(crossed, 3, 100) # 10 s, relay on B1 + _on_with_timed_off(crossed, 4, 100) # 10 s, relay on B0 + + crossed.step_time(5_000) + crossed.click_button("A0") # cancels the relay on B1 + crossed.click_button("A1") # cancels the relay on B0 + + crossed.step_time(6_000) + assert crossed.get_gpio("B1", refresh=True) + assert crossed.get_gpio("B0", refresh=True), ( + "a button cancelled the timer of the relay it does not drive" + ) + + +def test_crossed_timers_are_per_relay_endpoint(crossed: Device) -> None: + """Under a crossed wiring the timers still belong to the relay + endpoints, so each one fires at its own deadline.""" + _make_momentary(crossed, 1) + _make_momentary(crossed, 2) + _on_with_timed_off(crossed, 3, 10) # 1 s, relay on B1 + _on_with_timed_off(crossed, 4, 40) # 4 s, relay on B0 + + crossed.step_time(1_500) + assert not crossed.get_gpio("B1", refresh=True), ( + "the relay on B1 did not switch off at its own 1 s deadline" + ) + assert crossed.get_gpio("B0", refresh=True) + + crossed.step_time(3_000) + assert not crossed.get_gpio("B0", refresh=True), ( + "the relay on B0 did not switch off at its own 4 s deadline" + ) diff --git a/tests/test_relay_cluster_on_with_timed_off.py b/tests/test_relay_cluster_on_with_timed_off.py new file mode 100644 index 0000000000..3d6b90e3fa --- /dev/null +++ b/tests/test_relay_cluster_on_with_timed_off.py @@ -0,0 +1,440 @@ +"""Tests for the OnOff cluster "On With Timed Off" command (ZCL 0x42). + +The stub REPL runs with time frozen by default; we use `step_time` to advance +the virtual clock so scheduled timers can fire deterministically. The stub's +`step_time` command also calls `app_task()` once after stepping, so the relay +cluster polling tick re-evaluates the deadline against the new time. +""" + +import pytest + +from tests.client import StubProc +from tests.conftest import Device +from tests.zcl_consts import ( + ZCL_ATTR_ONOFF, + ZCL_CLUSTER_LEVEL_CONTROL, + ZCL_CLUSTER_ON_OFF, + ZCL_CMD_LEVEL_MOVE_TO_LEVEL_WITH_ON_OFF, + ZCL_CMD_OFF_WITH_EFFECT, + ZCL_CMD_ONOFF_OFF, + ZCL_CMD_ONOFF_ON, + ZCL_CMD_ONOFF_TOGGLE, + ZCL_CMD_ON_WITH_RECALL_GLOBAL_SCENE, + ZCL_CMD_ON_WITH_TIMED_OFF, + ZCL_ONOFF_CONFIGURATION_RELAY_MODE_DETACHED, +) + + +# The 5-byte onWithTimedOff payload: [onOffCtrl, onTime_LO, onTime_HI, +# offWaitTime_LO, offWaitTime_HI]. The Telink SDK stores onTime as +# (pData[2]<<8)|pData[1] (LE), so byte[1] is the LO byte. The romasku +# code reads the bytes directly to avoid struct-cast layout drift +# between the x86_64 stub (where the bitfield union is 4 bytes) and +# tc32 (where it is 1 byte). +def _payload(on_time: int, off_wait_time: int) -> list[int]: + on_lo, on_hi = on_time & 0xFF, (on_time >> 8) & 0xFF + off_lo, off_hi = off_wait_time & 0xFF, (off_wait_time >> 8) & 0xFF + return [0x00, on_lo, on_hi, off_lo, off_hi] + + +@pytest.fixture() +def timed_off_device() -> Device: + # One button + one relay: switch_endpoint=1, relay_endpoint=2. + cfg = "X;Y;SA0u;RB0;" + with StubProc(device_config=cfg) as proc: + yield Device(proc) + + +@pytest.fixture() +def multi_relay_timed_off_device() -> Device: + # Two buttons + two relays: switch_eps=1,2; relay_eps=3,4. + cfg = "X;Y;SA0u;SA1u;RB0;RB1;" + with StubProc(device_config=cfg) as proc: + yield Device(proc) + + +def _on_with_timed_off( + device: Device, ep: int, on_time: int, off_wait_time: int +) -> None: + device.call_zigbee_cmd( + ep, + ZCL_CLUSTER_ON_OFF, + ZCL_CMD_ON_WITH_TIMED_OFF, + payload_bytes=_payload(on_time, off_wait_time), + ) + + +# --- plain ON/OFF/level — basic path, must not be broken by the timer --- + +def test_plain_on_turns_relay_on(timed_off_device: Device) -> None: + ep = 2 + timed_off_device.call_zigbee_cmd(ep, ZCL_CLUSTER_ON_OFF, ZCL_CMD_ONOFF_ON) + assert ( + timed_off_device.read_zigbee_attr(ep, ZCL_CLUSTER_ON_OFF, ZCL_ATTR_ONOFF) + == "1" + ) + assert timed_off_device.get_gpio("B0") + + +def test_plain_off_turns_relay_off(timed_off_device: Device) -> None: + ep = 2 + timed_off_device.call_zigbee_cmd(ep, ZCL_CLUSTER_ON_OFF, ZCL_CMD_ONOFF_ON) + assert timed_off_device.get_gpio("B0") + timed_off_device.call_zigbee_cmd(ep, ZCL_CLUSTER_ON_OFF, ZCL_CMD_ONOFF_OFF) + assert not timed_off_device.get_gpio("B0") + assert ( + timed_off_device.read_zigbee_attr(ep, ZCL_CLUSTER_ON_OFF, ZCL_ATTR_ONOFF) + == "0" + ) + + +def test_plain_on_cancels_pending_timer(timed_off_device: Device) -> None: + """A fresh ON while a previous auto-OFF timer is pending must cancel + that timer — the user expects "ON" to mean "stay on".""" + ep = 2 + _on_with_timed_off(timed_off_device, ep, on_time=10, off_wait_time=0) + assert timed_off_device.get_gpio("B0") + # Step partway through the 1s timer. + timed_off_device.step_time(500) + # Fresh ON cancels the pending auto-OFF. + timed_off_device.call_zigbee_cmd(ep, ZCL_CLUSTER_ON_OFF, ZCL_CMD_ONOFF_ON) + # Step past the original deadline. + timed_off_device.step_time(800) + assert timed_off_device.get_gpio("B0", refresh=True), ( + "Pending auto-OFF fired despite a fresh ON — cancel did not work" + ) + + +# --- onWithTimedOff happy path --- + +def test_on_with_timed_off_turns_relay_on_immediately( + timed_off_device: Device, +) -> None: + ep = 2 + _on_with_timed_off(timed_off_device, ep, on_time=10, off_wait_time=0) + assert ( + timed_off_device.read_zigbee_attr(ep, ZCL_CLUSTER_ON_OFF, ZCL_ATTR_ONOFF) + == "1" + ) + assert timed_off_device.get_gpio("B0") + + +def test_on_with_timed_off_turns_off_after_on_time( + timed_off_device: Device, +) -> None: + ep = 2 + _on_with_timed_off(timed_off_device, ep, on_time=10, off_wait_time=0) + # on_time = 10 -> 1.0s. Step past the boundary. + timed_off_device.step_time(1100) + assert ( + timed_off_device.read_zigbee_attr(ep, ZCL_CLUSTER_ON_OFF, ZCL_ATTR_ONOFF) + == "0" + ) + assert not timed_off_device.get_gpio("B0") + + +def test_on_with_timed_off_does_not_fire_before_on_time( + timed_off_device: Device, +) -> None: + ep = 2 + _on_with_timed_off(timed_off_device, ep, on_time=20, off_wait_time=0) + timed_off_device.step_time(500) # half of 2.0s + assert ( + timed_off_device.read_zigbee_attr(ep, ZCL_CLUSTER_ON_OFF, ZCL_ATTR_ONOFF) + == "1" + ) + assert timed_off_device.get_gpio("B0") + + +def test_on_with_timed_off_uses_off_wait_time_when_provided( + timed_off_device: Device, +) -> None: + """ZCL spec: if offWaitTime>0, the auto-OFF fires after offWaitTime, + not onTime.""" + ep = 2 + # onTime=10 (1.0s), offWaitTime=30 (3.0s) — auto-OFF must fire at 3.0s. + _on_with_timed_off(timed_off_device, ep, on_time=10, off_wait_time=30) + timed_off_device.step_time(2000) # past 1.0s, before 3.0s + assert timed_off_device.get_gpio("B0") + timed_off_device.step_time(1500) # total 3.5s + assert not timed_off_device.get_gpio("B0", refresh=True) + + +def test_on_with_timed_off_zero_both_turns_off( + timed_off_device: Device, +) -> None: + """ZCL spec: (onTime=0, offWaitTime=0) is a plain OFF.""" + ep = 2 + # Start ON + timed_off_device.call_zigbee_cmd(ep, ZCL_CLUSTER_ON_OFF, ZCL_CMD_ONOFF_ON) + assert timed_off_device.get_gpio("B0") + # (0,0) -> OFF now + _on_with_timed_off(timed_off_device, ep, on_time=0, off_wait_time=0) + assert not timed_off_device.get_gpio("B0", refresh=True) + + +def test_on_with_timed_off_only_off_wait_keeps_off( + timed_off_device: Device, +) -> None: + """(onTime=0, offWaitTime>0) — the romasku firmware implements this + as a plain OFF (the "wait then ON" half of the ZCL spec is not + implemented; Z2M does not exercise this case).""" + ep = 2 + timed_off_device.call_zigbee_cmd(ep, ZCL_CLUSTER_ON_OFF, ZCL_CMD_ONOFF_ON) + assert timed_off_device.get_gpio("B0") + _on_with_timed_off(timed_off_device, ep, on_time=0, off_wait_time=20) + assert not timed_off_device.get_gpio("B0", refresh=True) + # Stay off past the offWaitTime. + timed_off_device.step_time(2_500) + assert not timed_off_device.get_gpio("B0", refresh=True) + + +def test_on_with_timed_off_new_command_cancels_pending( + timed_off_device: Device, +) -> None: + """A second onWithTimedOff replaces the first. With onTime=0 in + the replacement it becomes a plain OFF.""" + ep = 2 + _on_with_timed_off(timed_off_device, ep, on_time=50, off_wait_time=0) + # Replacement with (0,0) — turns OFF now, cancels the 5s timer. + _on_with_timed_off(timed_off_device, ep, on_time=0, off_wait_time=0) + assert not timed_off_device.get_gpio("B0", refresh=True) + # Past the original deadline. + timed_off_device.step_time(5_500) + assert not timed_off_device.get_gpio("B0", refresh=True), ( + "Old timer fired after (0,0) replacement — the replacement did " + "not cancel the previous arming" + ) + + +def test_off_command_cancels_pending_timer(timed_off_device: Device) -> None: + """A manual OFF cancels any pending auto-OFF.""" + ep = 2 + _on_with_timed_off(timed_off_device, ep, on_time=20, off_wait_time=0) + timed_off_device.call_zigbee_cmd(ep, ZCL_CLUSTER_ON_OFF, ZCL_CMD_ONOFF_OFF) + # Past the original deadline. + timed_off_device.step_time(2_500) + assert not timed_off_device.get_gpio("B0", refresh=True) + # And another auto-OFF must be armable fresh. + _on_with_timed_off(timed_off_device, ep, on_time=10, off_wait_time=0) + timed_off_device.step_time(1_200) + assert not timed_off_device.get_gpio("B0", refresh=True) + + +def test_level_move_with_on_off_cancels_pending_timer( + timed_off_device: Device, +) -> None: + ep = 2 + _on_with_timed_off(timed_off_device, ep, on_time=50, off_wait_time=0) + # level=0 -> off, which should cancel the pending timer. + timed_off_device.call_zigbee_cmd( + ep, + ZCL_CLUSTER_LEVEL_CONTROL, + ZCL_CMD_LEVEL_MOVE_TO_LEVEL_WITH_ON_OFF, + payload_bytes=[0x00, 0x00, 0x00], # level=0, trans_time=0 + ) + assert not timed_off_device.get_gpio("B0", refresh=True) + timed_off_device.step_time(5_500) + assert not timed_off_device.get_gpio("B0", refresh=True), ( + "Auto-OFF fired after a manual level=0 — the level handler did " + "not cancel the pending timer" + ) + + +# --- regressions for the captured ZCL bugs --- + +def test_on_with_timed_off_fires_after_hal_millis_wraparound( + timed_off_device: Device, +) -> None: + """Regression: the deadline must survive the 32-bit hal_millis() + wraparound (the Telink 8258 16MHz hardware counter wraps every + ~268s; the stub mimics this with a 400s wrap). + + The romasku code now uses a 64-bit deadline (`hal_millis_64() + + delay_ms`) and a 64-bit comparison, so even if a 32-bit + `hal_millis()` cast would have shown the deadline "in the past", + the 64-bit timeline is monotonic and the timer fires at the right + time. + """ + ep = 2 + # Push the clock to 395s (just under the 400s wrap). hal_millis()=395_000, + # hal_millis_64()=395_000. + timed_off_device.step_time(395_000) + # 1s on-time. 64-bit deadline = 396_000. + _on_with_timed_off(timed_off_device, ep, on_time=10, off_wait_time=0) + # Step 10s. hal_millis_64()=405_000, hal_millis() mod 400_000 = 5_000. + timed_off_device.step_time(10_000) + # The timer must fire: 9s past the 1s deadline. + assert ( + timed_off_device.read_zigbee_attr(ep, ZCL_CLUSTER_ON_OFF, ZCL_ATTR_ONOFF) + == "0" + ), "relay should be OFF after deadline even though 32-bit hal_millis() wrapped" + assert not timed_off_device.get_gpio("B0") + + +def test_malformed_payload_returns_malformed_command( + timed_off_device: Device, +) -> None: + ep = 2 + # Short payload (< 5 bytes) -> MALFORMED, not PROCESSED. + res = timed_off_device.call_zigbee_cmd_raw( + ep, ZCL_CLUSTER_ON_OFF, ZCL_CMD_ON_WITH_TIMED_OFF, payload=bytes([0x01]) + ) + assert res.get("result") == "MALFORMED_COMMAND", res + + +def test_on_with_timed_off_uses_le_wire_layout( + timed_off_device: Device, +) -> None: + """Regression: onTime / offWaitTime are read as little-endian u16s + from cmd_payload[1..2] and [3..4]. Telink SDK stores onTime as + `(pData[2]<<8) | pData[1]`, so the LO byte is at cmd_payload[1]. + + If a future change flips to big-endian (or uses a struct cast that + gives a different layout on x86_64 vs tc32), this test sees the + auto-OFF fire at the wrong time and fails. + """ + ep = 2 + # LE 0x1234 onTime (= 4660 in 0.1s = 466.0s), 0 offWaitTime. + payload = [0x00, 0x34, 0x12, 0x00, 0x00] + timed_off_device.call_zigbee_cmd( + ep, ZCL_CLUSTER_ON_OFF, ZCL_CMD_ON_WITH_TIMED_OFF, + payload_bytes=payload, + ) + assert timed_off_device.get_gpio("B0") + # 460s into a 466s timer — must still be ON. + timed_off_device.step_time(460_000) + assert timed_off_device.get_gpio("B0", refresh=True), ( + "Auto-OFF fired too early — likely a byte-order bug, the " + "romasku code is reading onTime in the wrong order" + ) + # 7s later (467s total) — must be OFF. + timed_off_device.step_time(7_000) + assert not timed_off_device.get_gpio("B0", refresh=True), ( + "Auto-OFF did not fire at the deadline" + ) + + +# --- multi-relay independence --- + +def test_multi_relay_timers_are_independent( + multi_relay_timed_off_device: Device, +) -> None: + """A timer on relay A does not affect relay B.""" + ep_a, ep_b = 3, 4 + _on_with_timed_off(multi_relay_timed_off_device, ep_a, on_time=10, off_wait_time=0) + _on_with_timed_off(multi_relay_timed_off_device, ep_b, on_time=40, off_wait_time=0) + assert multi_relay_timed_off_device.get_gpio("B0") + assert multi_relay_timed_off_device.get_gpio("B1") + # Step past relay A's 1s deadline. A turns off, B stays on. + multi_relay_timed_off_device.step_time(1_500) + assert not multi_relay_timed_off_device.get_gpio("B0", refresh=True) + assert multi_relay_timed_off_device.get_gpio("B1", refresh=True) + # Step past relay B's 4s deadline. B turns off. + multi_relay_timed_off_device.step_time(3_000) + assert not multi_relay_timed_off_device.get_gpio("B1", refresh=True) + + +# --- detach mode (button does not affect the relay) --- + +def test_on_with_timed_off_works_with_detached_switch() -> None: + cfg = "X;Y;SA0u;RB0;" + with StubProc(device_config=cfg) as proc: + device = Device(proc) + device.zcl_switch_relay_mode_set( + 1, ZCL_ONOFF_CONFIGURATION_RELAY_MODE_DETACHED + ) + + relay_ep = 2 + _on_with_timed_off(device, relay_ep, on_time=10, off_wait_time=0) + assert device.get_gpio("B0") + # A physical button press in detach mode must not affect the + # relay or its timer. + device.click_button("A0") + assert device.get_gpio("B0") # still ON + # After 1s the timer must fire regardless of the button press. + device.step_time(1100) + assert not device.get_gpio("B0", refresh=True) + + +def test_physical_button_in_detach_mode_does_not_cancel_timer() -> None: + """In detach mode the button does not change the relay, so its + on_change callback does not fire — and the pending auto-OFF timer + must still run.""" + cfg = "X;Y;SA0u;RB0;" + with StubProc(device_config=cfg) as proc: + device = Device(proc) + device.zcl_switch_relay_mode_set( + 1, ZCL_ONOFF_CONFIGURATION_RELAY_MODE_DETACHED + ) + + relay_ep = 2 + _on_with_timed_off(device, relay_ep, on_time=10, off_wait_time=0) + # Press the button — in detach mode this must NOT affect the relay. + device.click_button("A0") + assert device.get_gpio("B0") + # And the timer must still fire at the deadline. + device.step_time(1100) + assert not device.get_gpio("B0", refresh=True) + + +# --- onWithTimedOff on a relay that is already ON --- + +def test_on_with_timed_off_works_when_relay_already_on( + timed_off_device: Device, +) -> None: + """Per ZCL spec, onWithTimedOff is the canonical "schedule an + auto-OFF on top of an already-ON relay" command — the controller + doesn't have to send a separate On. Sending it to a relay that's + already ON must schedule the auto-OFF without the relay on_change + callback cancelling the freshly installed timer (relay_on() is a + no-op on a relay that is already on, so on_change is not invoked). + """ + ep = 2 + timed_off_device.call_zigbee_cmd(ep, ZCL_CLUSTER_ON_OFF, ZCL_CMD_ONOFF_ON) + assert timed_off_device.get_gpio("B0") + + # onTime=50 (5s). The handler must (a) not toggle the relay, + # (b) install a fresh auto-OFF timer, (c) fire it at 5s. + _on_with_timed_off(timed_off_device, ep, on_time=50, off_wait_time=0) + + # Relay stays ON right after the command. + assert timed_off_device.get_gpio("B0", refresh=True) + # And is still ON at the halfway point. + timed_off_device.step_time(2_500) + assert timed_off_device.get_gpio("B0", refresh=True) + # And finally turns OFF at 5s. + timed_off_device.step_time(2_600) + assert not timed_off_device.get_gpio("B0", refresh=True) + + +def test_staggered_multi_relay_timers_both_fire( + multi_relay_timed_off_device: Device, +) -> None: + """A long countdown armed before a short one still fires. + + Mirror image of test_multi_relay_timers_are_independent, where the + shorter timer is armed first. Here the 10 s timer goes on relay A + first and the 5 s timer on relay B second, so the *shorter* deadline + is the one that passes first. Both must fire, independently. + """ + ep_long, ep_short = 3, 4 + _on_with_timed_off(multi_relay_timed_off_device, ep_long, on_time=100, off_wait_time=0) + _on_with_timed_off(multi_relay_timed_off_device, ep_short, on_time=50, off_wait_time=0) + assert multi_relay_timed_off_device.get_gpio("B0") + assert multi_relay_timed_off_device.get_gpio("B1") + + # Past the short deadline: only relay B turns off. + multi_relay_timed_off_device.step_time(6_000) + assert not multi_relay_timed_off_device.get_gpio("B1", refresh=True) + assert multi_relay_timed_off_device.get_gpio("B0", refresh=True) + + # Past the long deadline: relay A turns off too. + multi_relay_timed_off_device.step_time(5_000) + assert not multi_relay_timed_off_device.get_gpio("B0", refresh=True) + assert ( + multi_relay_timed_off_device.read_zigbee_attr( + ep_long, ZCL_CLUSTER_ON_OFF, ZCL_ATTR_ONOFF + ) + == "0" + ) diff --git a/tests/test_relay_cluster_timer_matrix.py b/tests/test_relay_cluster_timer_matrix.py new file mode 100644 index 0000000000..7d058723dd --- /dev/null +++ b/tests/test_relay_cluster_timer_matrix.py @@ -0,0 +1,480 @@ +"""The full cross-product of timer events. + +The individual reset paths are covered in +``test_relay_cluster_timer_reset.py`` and +``test_relay_cluster_button_pairing.py``. This file walks the +CROSS-PRODUCT of the dimensions that interact, because the interesting +bugs live in the combinations rather than in the single cases: + +* the event that arrives while a timer is pending +* the device shape (1, 2 or 3 relays) +* which endpoint the timer sits on +* the timer length relative to the hardware tick wrap (268.435456 s) + +Each event carries two facts: whether it CANCELS the pending timer, +and what it leaves the relay in. The matrix asserts both. The events +that do NOT cancel are just as important as the ones that do — a +non-cancelling event that silently cancelled a timer would be as much +a bug as a cancelling event that failed to. +""" + +import pytest + +from tests.client import StubProc +from tests.conftest import Device +from tests.zcl_consts import ( + ZCL_ATTR_ONOFF, + ZCL_ATTR_ONOFF_CONFIGURATION_SWITCH_ACTIONS, + ZCL_ATTR_ONOFF_CONFIGURATION_SWITCH_MODE, + ZCL_ATTR_ONOFF_CONFIGURATION_SWITCH_RELAY_MODE, + ZCL_CLUSTER_LEVEL_CONTROL, + ZCL_CLUSTER_ON_OFF, + ZCL_CLUSTER_ON_OFF_SWITCH_CONFIG, + ZCL_CMD_LEVEL_MOVE_TO_LEVEL_WITH_ON_OFF, + ZCL_CMD_OFF_WITH_EFFECT, + ZCL_CMD_ONOFF_OFF, + ZCL_CMD_ONOFF_ON, + ZCL_CMD_ONOFF_TOGGLE, + ZCL_CMD_ON_WITH_RECALL_GLOBAL_SCENE, + ZCL_CMD_ON_WITH_TIMED_OFF, + ZCL_ONOFF_CONFIGURATION_RELAY_MODE_DETACHED, + ZCL_ONOFF_CONFIGURATION_RELAY_MODE_LONG, + ZCL_ONOFF_CONFIGURATION_SWITCH_ACTION_ONOFF, + ZCL_ONOFF_CONFIGURATION_SWITCH_ACTION_TOGGLE_SIMPLE, + ZCL_ONOFF_CONFIGURATION_SWITCH_TYPE_MOMENTARY, +) + + +def _payload(on_time: int, off_wait_time: int = 0) -> list[int]: + on_lo, on_hi = on_time & 0xFF, (on_time >> 8) & 0xFF + off_lo, off_hi = off_wait_time & 0xFF, (off_wait_time >> 8) & 0xFF + return [0x00, on_lo, on_hi, off_lo, off_hi] + + +def _timed_off(device: Device, ep: int, on_time: int) -> None: + device.call_zigbee_cmd( + ep, + ZCL_CLUSTER_ON_OFF, + ZCL_CMD_ON_WITH_TIMED_OFF, + payload_bytes=_payload(on_time), + ) + + +def _make_momentary(device: Device, switch_ep: int, action: int) -> None: + device.write_zigbee_attr( + switch_ep, + ZCL_CLUSTER_ON_OFF_SWITCH_CONFIG, + ZCL_ATTR_ONOFF_CONFIGURATION_SWITCH_MODE, + ZCL_ONOFF_CONFIGURATION_SWITCH_TYPE_MOMENTARY, + ) + device.write_zigbee_attr( + switch_ep, + ZCL_CLUSTER_ON_OFF_SWITCH_CONFIG, + ZCL_ATTR_ONOFF_CONFIGURATION_SWITCH_ACTIONS, + action, + ) + + +# --- device shapes ------------------------------------------------------- +# +# One config per arity. "X;Y;" is the manufacturer/model prefix the +# stub expects; the entries after it are the switches and the relays. +ONE_RELAY = "X;Y;SA0u;RB0;" # switch ep1, relay ep2 +TWO_RELAYS = "X;Y;SA0u;RB0;SA1u;RB1;" # switches 1,2, relays 3,4 +THREE_RELAYS = "X;Y;SA0u;RB0;SA1u;RB1;SA2u;RB2;" # switches 1-3, relays 4-6 + + +def _button_pin(switch_ep: int) -> str: + return f"A{switch_ep - 1}" + + +# --- the events ---------------------------------------------------------- +# +# Each entry: (id, cancels_timer, relay_state_after, action, setup) +# +# relay_state_after is one of: +# "on" the relay ends up ON +# "off" the relay ends up OFF +# "toggled" the relay flipped (ON -> OFF, since the timer turned it on) +# +# cancels_timer is False for the events that do NOT drive the relay: +# writing the read-only onOff attribute, and a detached switch. Both +# must leave the pending timer running. + +def _ev_plain_on(d: Device, ep: int, switch_ep: int, action: int) -> None: + d.call_zigbee_cmd(ep, ZCL_CLUSTER_ON_OFF, ZCL_CMD_ONOFF_ON) + + +def _ev_plain_off(d: Device, ep: int, switch_ep: int, action: int) -> None: + d.call_zigbee_cmd(ep, ZCL_CLUSTER_ON_OFF, ZCL_CMD_ONOFF_OFF) + + +def _ev_toggle(d: Device, ep: int, switch_ep: int, action: int) -> None: + d.call_zigbee_cmd(ep, ZCL_CLUSTER_ON_OFF, ZCL_CMD_ONOFF_TOGGLE) + + +def _ev_off_with_effect(d: Device, ep: int, switch_ep: int, action: int) -> None: + d.call_zigbee_cmd( + ep, ZCL_CLUSTER_ON_OFF, ZCL_CMD_OFF_WITH_EFFECT, payload_bytes=[0x00] + ) + + +def _ev_on_with_recall(d: Device, ep: int, switch_ep: int, action: int) -> None: + d.call_zigbee_cmd( + ep, + ZCL_CLUSTER_ON_OFF, + ZCL_CMD_ON_WITH_RECALL_GLOBAL_SCENE, + payload_bytes=[0x00, 0x00, 0x00, 0x00], + ) + + +def _ev_level_zero(d: Device, ep: int, switch_ep: int, action: int) -> None: + d.call_zigbee_cmd( + ep, + ZCL_CLUSTER_LEVEL_CONTROL, + ZCL_CMD_LEVEL_MOVE_TO_LEVEL_WITH_ON_OFF, + payload_bytes=[0x00, 0x00, 0x00], + ) + + +def _ev_button(d: Device, ep: int, switch_ep: int, action: int) -> None: + d.click_button(_button_pin(switch_ep)) + + +def _ev_long_press(d: Device, ep: int, switch_ep: int, action: int) -> None: + d.long_click_button(_button_pin(switch_ep), duration_ms=1_000) + + +def _ev_attr_write(d: Device, ep: int, switch_ep: int, action: int) -> None: + d.write_zigbee_attr(ep, ZCL_CLUSTER_ON_OFF, ZCL_ATTR_ONOFF, 1) + + +EVENTS = [ + # id, cancels, relay after, action, setup, runner + ("plain_on", True, "on", + ZCL_ONOFF_CONFIGURATION_SWITCH_ACTION_ONOFF, None, _ev_plain_on), + ("plain_off", True, "off", + ZCL_ONOFF_CONFIGURATION_SWITCH_ACTION_ONOFF, None, _ev_plain_off), + ("toggle", True, "toggled", + ZCL_ONOFF_CONFIGURATION_SWITCH_ACTION_ONOFF, None, _ev_toggle), + ("off_with_effect", True, "off", + ZCL_ONOFF_CONFIGURATION_SWITCH_ACTION_ONOFF, None, _ev_off_with_effect), + ("on_with_recall", True, "on", + ZCL_ONOFF_CONFIGURATION_SWITCH_ACTION_ONOFF, None, _ev_on_with_recall), + ("level_zero", True, "off", + ZCL_ONOFF_CONFIGURATION_SWITCH_ACTION_ONOFF, None, _ev_level_zero), + ("button_onoff", True, "on", + ZCL_ONOFF_CONFIGURATION_SWITCH_ACTION_ONOFF, None, _ev_button), + ("button_toggle", True, "toggled", + ZCL_ONOFF_CONFIGURATION_SWITCH_ACTION_TOGGLE_SIMPLE, None, _ev_button), + ("long_press", True, "toggled", + ZCL_ONOFF_CONFIGURATION_SWITCH_ACTION_TOGGLE_SIMPLE, "long", _ev_long_press), + ("detached_button", False, "on", + ZCL_ONOFF_CONFIGURATION_SWITCH_ACTION_ONOFF, "detached", _ev_button), + ("attr_write", False, "on", + ZCL_ONOFF_CONFIGURATION_SWITCH_ACTION_ONOFF, None, _ev_attr_write), +] + +EVENT_IDS = [e[0] for e in EVENTS] + + +def _prepare(d: Device, switch_ep: int, action: int, setup: str | None) -> None: + _make_momentary(d, switch_ep, action) + if setup == "detached": + d.write_zigbee_attr( + switch_ep, + ZCL_CLUSTER_ON_OFF_SWITCH_CONFIG, + ZCL_ATTR_ONOFF_CONFIGURATION_SWITCH_RELAY_MODE, + ZCL_ONOFF_CONFIGURATION_RELAY_MODE_DETACHED, + ) + elif setup == "long": + d.write_zigbee_attr( + switch_ep, + ZCL_CLUSTER_ON_OFF_SWITCH_CONFIG, + ZCL_ATTR_ONOFF_CONFIGURATION_SWITCH_RELAY_MODE, + ZCL_ONOFF_CONFIGURATION_RELAY_MODE_LONG, + ) + + +def _relay_on(pin: str, state: str) -> bool: + """Whether the relay is expected to be ON after the event.""" + if state == "on": + return True + if state == "off": + return False + if state == "toggled": + return False # the timer had turned it ON, the event flipped it + raise AssertionError(state) + + +# --- the matrix ---------------------------------------------------------- + + +@pytest.mark.parametrize( + "event_id,cancels,state,action,setup,runner", + EVENTS, + ids=EVENT_IDS, +) +def test_event_matrix_single_relay( + event_id: str, cancels: bool, state: str, action: int, setup, runner +) -> None: + """Every event on a one-relay device, with the timer armed. + + After the event the relay must be in the expected state, and the + timer must have been cancelled (or, for the two non-cancelling + events, must still fire). + """ + with StubProc(device_config=ONE_RELAY) as proc: + d = Device(proc) + ep = 2 + _prepare(d, 1, action, setup) + + _timed_off(d, ep, 100) # 10 s + assert d.get_gpio("B0") + was_on = True + + d.step_time(5_000) + runner(d, ep, 1, action) + + expected_on = _relay_on("B0", state) + assert d.get_gpio("B0", refresh=True) == expected_on, ( + f"{event_id}: unexpected relay state right after the event" + ) + + # Past the deadline. + d.step_time(6_000) + if cancels: + if expected_on: + assert d.get_gpio("B0", refresh=True), ( + f"{event_id}: the auto-OFF fired — the event did not " + f"cancel the timer" + ) + else: + assert not d.get_gpio("B0", refresh=True) + else: + # The event does not drive the relay, so the timer must + # still fire. + assert not d.get_gpio("B0", refresh=True), ( + f"{event_id}: the timer was cancelled — this event does " + f"not drive the relay and must leave the timer alone" + ) + + +@pytest.mark.parametrize( + "event_id,cancels,state,action,setup,runner", + EVENTS, + ids=EVENT_IDS, +) +@pytest.mark.parametrize("relay_ep", [3, 4]) +def test_event_matrix_two_relays( + event_id: str, cancels: bool, state: str, action: int, setup, runner, + relay_ep: int, +) -> None: + """Every event on either relay of a two-relay device. + + The other relay keeps its own timer, which must still fire. + """ + with StubProc(device_config=TWO_RELAYS) as proc: + d = Device(proc) + other_ep = 4 if relay_ep == 3 else 3 + target_pin = "B0" if relay_ep == 3 else "B1" + other_pin = "B1" if relay_ep == 3 else "B0" + switch_ep = 1 if relay_ep == 3 else 2 + + _prepare(d, switch_ep, action, setup) + + _timed_off(d, relay_ep, 100) # 10 s on the target + _timed_off(d, other_ep, 100) # 10 s on the other + + d.step_time(5_000) + runner(d, relay_ep, switch_ep, action) + + expected_on = _relay_on(target_pin, state) + assert d.get_gpio(target_pin, refresh=True) == expected_on, ( + f"{event_id}: unexpected relay state right after the event" + ) + + d.step_time(6_000) # past both deadlines + if cancels and expected_on: + assert d.get_gpio(target_pin, refresh=True), ( + f"{event_id}: the auto-OFF fired on the target relay" + ) + elif not cancels: + assert not d.get_gpio(target_pin, refresh=True), ( + f"{event_id}: the timer was cancelled — this event does " + f"not drive the relay" + ) + else: + assert not d.get_gpio(target_pin, refresh=True) + + # The other relay's timer is untouched by this event. + assert not d.get_gpio(other_pin, refresh=True), ( + f"{event_id}: the other relay's timer did not fire" + ) + + +@pytest.mark.parametrize("relay_ep", [4, 5, 6]) +def test_every_endpoint_of_a_three_relay_device(relay_ep: int) -> None: + """Each of the three relays keeps its own timer and its own button.""" + with StubProc(device_config=THREE_RELAYS) as proc: + d = Device(proc) + pins = {4: "B0", 5: "B1", 6: "B2"} + other_eps = [e for e in (4, 5, 6) if e != relay_ep] + switch_ep = relay_ep - 3 + + _make_momentary(d, switch_ep, ZCL_ONOFF_CONFIGURATION_SWITCH_ACTION_ONOFF) + for ep in (4, 5, 6): + _timed_off(d, ep, 100) + + d.step_time(5_000) + d.click_button(_button_pin(switch_ep)) + + d.step_time(6_000) + assert d.get_gpio(pins[relay_ep], refresh=True), ( + "the relay's own button did not cancel its timer" + ) + for ep in other_eps: + assert not d.get_gpio(pins[ep], refresh=True), ( + f"the timer of relay {ep} was cancelled by another button" + ) + + +@pytest.mark.parametrize("relay_ep", [4, 5, 6]) +def test_every_endpoint_timers_fire_at_their_own_deadline(relay_ep: int) -> None: + """Three timers of different lengths each fire at their own moment.""" + with StubProc(device_config=THREE_RELAYS) as proc: + d = Device(proc) + pins = {4: "B0", 5: "B1", 6: "B2"} + lengths = {4: 10, 5: 20, 6: 30} # 1 s, 2 s, 3 s + for ep in (4, 5, 6): + _timed_off(d, ep, lengths[ep]) + + d.step_time(1_500) + assert not d.get_gpio(pins[4], refresh=True) + assert d.get_gpio(pins[5], refresh=True) + assert d.get_gpio(pins[6], refresh=True) + + d.step_time(1_000) + assert not d.get_gpio(pins[5], refresh=True) + assert d.get_gpio(pins[6], refresh=True) + + d.step_time(1_000) + assert not d.get_gpio(pins[6], refresh=True) + + +@pytest.mark.parametrize("on_time_units", [10, 100, 1000, 6000, 65534]) +def test_timer_lengths_across_the_tick_wrap(on_time_units: int) -> None: + """Timers of 1 s .. 6553 s all fire at their own deadline. + + 6553 s is the ZCL maximum and is longer than the 268 s + hardware tick wrap, which is exactly the case the old counter got + wrong. + """ + with StubProc(device_config=ONE_RELAY) as proc: + d = Device(proc) + ep = 2 + deadline_ms = on_time_units * 100 + _timed_off(d, ep, on_time_units) + assert d.get_gpio("B0") + # Just before the deadline: still ON. + d.step_time(deadline_ms - 500) + assert d.get_gpio("B0", refresh=True), ( + f"the timer of {on_time_units} units fired early" + ) + # Just past the deadline: OFF. + d.step_time(1_000) + assert not d.get_gpio("B0", refresh=True), ( + f"the timer of {on_time_units} units did not fire" + ) + + +@pytest.mark.parametrize("on_time_units", [10, 1000, 6000, 65534]) +def test_event_during_a_long_timer(on_time_units: int) -> None: + """A button cancels a long timer too, not just a short one. + + The long timers straddle the hardware tick wrap, which is where + the old counter broke. + """ + with StubProc(device_config=ONE_RELAY) as proc: + d = Device(proc) + ep = 2 + deadline_ms = on_time_units * 100 + _make_momentary(d, 1, ZCL_ONOFF_CONFIGURATION_SWITCH_ACTION_ONOFF) + _timed_off(d, ep, on_time_units) + d.step_time(deadline_ms // 2) + d.click_button("A0") + d.step_time(deadline_ms // 2 + 1_000) + assert d.get_gpio("B0", refresh=True), ( + f"the timer of {on_time_units} units survived the button press" + ) + + +@pytest.mark.parametrize("on_time_units", [100, 1000, 6000, 65534]) +def test_second_timer_replaces_a_long_timer(on_time_units: int) -> None: + """A second On With Timed Off replaces a long one cleanly. + + The replacement is LONGER, so the old deadline passes without the + relay switching off, and the new deadline switches it off later. + + Timeline: the first timer is armed at t=0 with deadline old_ms. + The replacement arrives at t=old_ms//2 and moves the deadline to + old_ms//2 + new_ms. + """ + with StubProc(device_config=ONE_RELAY) as proc: + d = Device(proc) + ep = 2 + old_ms = on_time_units * 100 + _timed_off(d, ep, on_time_units) + d.step_time(old_ms // 2) + # Replace with a longer timer, capped at the ZCL maximum. + new_units = min(on_time_units * 2, 65534) + new_ms = new_units * 100 + _timed_off(d, ep, new_units) + # The OLD deadline (old_ms from the start) must not fire. + # Stop just short of it. + d.step_time(old_ms // 2 - 500) + assert d.get_gpio("B0", refresh=True), ( + f"the replaced timer of {on_time_units} units still fired" + ) + # The NEW deadline is at old_ms//2 + new_ms; wait past it. + d.step_time(new_ms - old_ms // 2 + 1_000) + assert not d.get_gpio("B0", refresh=True), ( + "the replacement timer did not fire" + ) + + +@pytest.mark.parametrize("first,second", [(10, 40), (40, 10), (100, 200), + (200, 100), (65534, 10)]) +def test_replacement_in_both_directions(first: int, second: int) -> None: + """Replacing a timer with a shorter one and with a longer one.""" + with StubProc(device_config=ONE_RELAY) as proc: + d = Device(proc) + ep = 2 + _timed_off(d, ep, first) + d.step_time(1_000) + _timed_off(d, ep, second) + # The second deadline is 1 s + second. + d.step_time(second * 100 - 1_000 + 500) + assert d.get_gpio("B0", refresh=True), ( + f"the replacement by {second} fired too early" + ) + d.step_time(1_000) + assert not d.get_gpio("B0", refresh=True), ( + f"the replacement by {second} did not fire" + ) + + +@pytest.mark.parametrize("relay_ep", [2, 3, 4, 5, 6]) +def test_timer_after_the_relay_was_already_off(relay_ep: int) -> None: + """Arming a timer on an already-off relay still turns it on and + still fires.""" + cfg = {2: ONE_RELAY, 3: TWO_RELAYS, 4: THREE_RELAYS, + 5: THREE_RELAYS, 6: THREE_RELAYS}[relay_ep] + with StubProc(device_config=cfg) as proc: + d = Device(proc) + pin = {2: "B0", 3: "B0", 4: "B0", 5: "B1", 6: "B2"}[relay_ep] + assert not d.get_gpio(pin) + _timed_off(d, relay_ep, 100) + assert d.get_gpio(pin), "the timer did not turn the relay on" + d.step_time(10_500) + assert not d.get_gpio(pin, refresh=True) diff --git a/tests/test_relay_cluster_timer_reset.py b/tests/test_relay_cluster_timer_reset.py new file mode 100644 index 0000000000..e6f1628c3c --- /dev/null +++ b/tests/test_relay_cluster_timer_reset.py @@ -0,0 +1,636 @@ +"""Every path that can cancel or replace a pending auto-OFF timer. + +The ZCL "On With Timed Off" timer is per relay cluster (per endpoint). +This file walks each way the pending deadline can be cleared or moved +and asserts the relay ends up in the state the user would expect. + +The paths covered here: + +* plain ON / OFF / TOGGLE commands +* ON with recall global scene, OFF with effect +* level control move-to-level +* a second On With Timed Off (must REPLACE, not stack or cancel) +* the physical button (short press, long press) +* the button of the *other* endpoint (must not touch this timer) +* a plain attribute write (must not cancel) +* the timer firing on its own + +The stub REPL runs with time frozen by default; `step_time` advances the +virtual clock so deadlines can be evaluated deterministically. +""" + +import pytest + +from tests.client import StubProc +from tests.conftest import Device +from tests.zcl_consts import ( + ZCL_ATTR_ONOFF, + ZCL_ATTR_ONOFF_CONFIGURATION_SWITCH_ACTIONS, + ZCL_ATTR_ONOFF_CONFIGURATION_SWITCH_MODE, + ZCL_ATTR_ONOFF_CONFIGURATION_SWITCH_RELAY_MODE, + ZCL_CLUSTER_LEVEL_CONTROL, + ZCL_CLUSTER_ON_OFF, + ZCL_CLUSTER_ON_OFF_SWITCH_CONFIG, + ZCL_CMD_LEVEL_MOVE_TO_LEVEL_WITH_ON_OFF, + ZCL_CMD_OFF_WITH_EFFECT, + ZCL_CMD_ONOFF_OFF, + ZCL_CMD_ONOFF_ON, + ZCL_CMD_ONOFF_TOGGLE, + ZCL_CMD_ON_WITH_RECALL_GLOBAL_SCENE, + ZCL_CMD_ON_WITH_TIMED_OFF, + ZCL_ONOFF_CONFIGURATION_RELAY_MODE_DETACHED, + ZCL_ONOFF_CONFIGURATION_RELAY_MODE_LONG, + ZCL_ONOFF_CONFIGURATION_RELAY_MODE_SHORT, + ZCL_ONOFF_CONFIGURATION_SWITCH_ACTION_ONOFF, + ZCL_ONOFF_CONFIGURATION_SWITCH_ACTION_TOGGLE_SIMPLE, + ZCL_ONOFF_CONFIGURATION_SWITCH_TYPE_MOMENTARY, +) + + +def _payload(on_time: int, off_wait_time: int) -> list[int]: + """The 5-byte onWithTimedOff payload, little-endian onTime/offWaitTime.""" + on_lo, on_hi = on_time & 0xFF, (on_time >> 8) & 0xFF + off_lo, off_hi = off_wait_time & 0xFF, (off_wait_time >> 8) & 0xFF + return [0x00, on_lo, on_hi, off_lo, off_hi] + + +def _on_with_timed_off( + device: Device, ep: int, on_time: int, off_wait_time: int = 0 +) -> None: + device.call_zigbee_cmd( + ep, + ZCL_CLUSTER_ON_OFF, + ZCL_CMD_ON_WITH_TIMED_OFF, + payload_bytes=_payload(on_time, off_wait_time), + ) + + +def _onoff_reports(device: Device, ep: int) -> int: + """Count the onOff attribute reports seen so far on an endpoint. + + The stub's reader thread delivers the EVT lines asynchronously, so + an event emitted by a command may still be in flight when the + command's reply arrives. `status` is a round trip that lets the + reader catch up before the count is taken. + """ + device.status() + count = 0 + for e in device._events: + if e.kind != "zcl_attr_change": + continue + if int(e.payload["ep"]) != ep: + continue + if int(e.payload["cluster"], 16) != ZCL_CLUSTER_ON_OFF: + continue + if int(e.payload["attr"], 16) != ZCL_ATTR_ONOFF: + continue + count += 1 + return count + + +def _make_momentary(device: Device, switch_ep: int, action: int) -> None: + """Turn the switch into a momentary button with the given action. + + The device config defaults to TOGGLE switch type, where a press and + a release each drive the relay — two toggles for one click. A + momentary switch drives the relay once, on the release, which is + what a real push button does. + """ + device.write_zigbee_attr( + switch_ep, + ZCL_CLUSTER_ON_OFF_SWITCH_CONFIG, + ZCL_ATTR_ONOFF_CONFIGURATION_SWITCH_MODE, + ZCL_ONOFF_CONFIGURATION_SWITCH_TYPE_MOMENTARY, + ) + device.write_zigbee_attr( + switch_ep, + ZCL_CLUSTER_ON_OFF_SWITCH_CONFIG, + ZCL_ATTR_ONOFF_CONFIGURATION_SWITCH_ACTIONS, + action, + ) + + +@pytest.fixture() +def device() -> Device: + # One button + one relay: switch endpoint 1, relay endpoint 2. + cfg = "X;Y;SA0u;RB0;" + with StubProc(device_config=cfg) as proc: + yield Device(proc) + + +@pytest.fixture() +def two_relay_device() -> Device: + # Two buttons + two relays: switch_eps=1,2; relay_eps=3,4. + cfg = "X;Y;SA0u;SA1u;RB0;RB1;" + with StubProc(device_config=cfg) as proc: + yield Device(proc) + + +@pytest.fixture() +def three_relay_device() -> Device: + # Three buttons + three relays: switch_eps=1,2,3; relay_eps=4,5,6. + cfg = "X;Y;SA0u;SA1u;SA2u;RB0;RB1;RB2;" + with StubProc(device_config=cfg) as proc: + yield Device(proc) + + +# --- a single-channel device --------------------------------------------- +# +# The real single-channel boards (MODULE_AVATTO_A_TS0001) have one switch +# and one relay: config "4rbqgcuv;TS0001-AVB;BC2u;LD2i;SD3u;RC0;". +# The relay endpoint is 2 there. The two-channel boards +# (MODULE_AVATTO_TS0012) have two of each: "ljhbw1c9;TS0012-avatto; +# BB4u;LB5;SC0u;RC2;SC3u;RC4;" — switches on endpoints 1,2 and relays +# on endpoints 3,4. + + +def test_single_channel_device_timer_fires(device: Device) -> None: + """A one-relay device arms and fires its timer normally.""" + ep = 2 + _on_with_timed_off(device, ep, on_time=100) # 10 s + assert device.get_gpio("B0") + device.step_time(10_500) + assert not device.get_gpio("B0", refresh=True) + assert device.read_zigbee_attr(ep, ZCL_CLUSTER_ON_OFF, ZCL_ATTR_ONOFF) == "0" + + +def test_single_channel_device_button_cancels_timer(device: Device) -> None: + """On a one-relay device the button cancels the pending timer.""" + ep = 2 + _make_momentary(device, 1, ZCL_ONOFF_CONFIGURATION_SWITCH_ACTION_ONOFF) + _on_with_timed_off(device, ep, on_time=100) # 10 s + device.step_time(5_000) + device.click_button("A0") + device.step_time(6_000) + assert device.get_gpio("B0", refresh=True), ( + "auto-OFF fired after a button press on a single-channel device" + ) + + +# --- both channels of a two-channel device -------------------------------- + + +def test_both_channels_arm_and_fire_independently( + two_relay_device: Device, +) -> None: + """Both relays of a two-channel device run their own timer. + + Channel 1 gets a 1 s timer, channel 2 a 4 s one. Channel 1 must + switch off first and channel 2 later — each at its own deadline. + """ + ep_a, ep_b = 3, 4 + _on_with_timed_off(two_relay_device, ep_a, on_time=10) # 1 s + _on_with_timed_off(two_relay_device, ep_b, on_time=40) # 4 s + assert two_relay_device.get_gpio("B0") + assert two_relay_device.get_gpio("B1") + + two_relay_device.step_time(1_500) + assert not two_relay_device.get_gpio("B0", refresh=True), ( + "channel 1 did not switch off at its own 1 s deadline" + ) + assert two_relay_device.get_gpio("B1", refresh=True), ( + "channel 2 switched off early — it followed the other channel" + ) + + two_relay_device.step_time(3_000) + assert not two_relay_device.get_gpio("B1", refresh=True), ( + "channel 2 did not switch off at its own 4 s deadline" + ) + + +def test_channel1_button_cancels_only_channel1_timer( + two_relay_device: Device, +) -> None: + """The button of channel 1 cancels channel 1's timer and leaves + channel 2's timer running.""" + ep_a, ep_b = 3, 4 + _make_momentary( + two_relay_device, 1, ZCL_ONOFF_CONFIGURATION_SWITCH_ACTION_ONOFF + ) + _on_with_timed_off(two_relay_device, ep_a, on_time=100) # 10 s + _on_with_timed_off(two_relay_device, ep_b, on_time=100) # 10 s + + two_relay_device.step_time(5_000) + two_relay_device.click_button("A0") # channel 1's button + + two_relay_device.step_time(6_000) # past both deadlines + # Channel 1's timer was cancelled, so its relay is still ON. + assert two_relay_device.get_gpio("B0", refresh=True), ( + "channel 1's timer was not cancelled by its own button" + ) + # Channel 2's timer was untouched, so it fired. + assert not two_relay_device.get_gpio("B1", refresh=True), ( + "channel 2's timer was cancelled by the other channel's button" + ) + + +def test_detached_button_does_not_cancel_the_timer(device: Device) -> None: + """A detached switch does not drive the relay. + + The relay therefore keeps no trace of the button press, the pending + auto-OFF survives, and the relay still switches off on time. This + is the documented behaviour of the detach mode: the button is not + connected to the relay at all. + """ + ep = 2 + _make_momentary(device, 1, ZCL_ONOFF_CONFIGURATION_SWITCH_ACTION_ONOFF) + device.write_zigbee_attr( + 1, + ZCL_CLUSTER_ON_OFF_SWITCH_CONFIG, + ZCL_ATTR_ONOFF_CONFIGURATION_SWITCH_RELAY_MODE, + ZCL_ONOFF_CONFIGURATION_RELAY_MODE_DETACHED, + ) + _on_with_timed_off(device, ep, on_time=100) # 10 s + assert device.get_gpio("B0") + + device.click_button("A0") + # The relay did not move and the timer is still armed. + assert device.get_gpio("B0", refresh=True) + + device.step_time(10_500) + assert not device.get_gpio("B0", refresh=True), ( + "the timer did not fire — a detached button must not cancel it" + ) + + +def test_detached_button_of_channel1_leaves_channel2_timer_running( + two_relay_device: Device, +) -> None: + """A detached switch on channel 1 leaves both timers running.""" + ep_a, ep_b = 3, 4 + _make_momentary( + two_relay_device, 1, ZCL_ONOFF_CONFIGURATION_SWITCH_ACTION_ONOFF + ) + two_relay_device.write_zigbee_attr( + 1, + ZCL_CLUSTER_ON_OFF_SWITCH_CONFIG, + ZCL_ATTR_ONOFF_CONFIGURATION_SWITCH_RELAY_MODE, + ZCL_ONOFF_CONFIGURATION_RELAY_MODE_DETACHED, + ) + _on_with_timed_off(two_relay_device, ep_a, on_time=100) # 10 s + _on_with_timed_off(two_relay_device, ep_b, on_time=100) # 10 s + + two_relay_device.click_button("A0") + two_relay_device.step_time(10_500) + assert not two_relay_device.get_gpio("B0", refresh=True) + assert not two_relay_device.get_gpio("B1", refresh=True) + + +def test_three_channels_each_keep_their_own_timer( + three_relay_device: Device, +) -> None: + """A three-relay device keeps three independent timers.""" + ep_a, ep_b, ep_c = 4, 5, 6 + _on_with_timed_off(three_relay_device, ep_a, on_time=10) # 1 s + _on_with_timed_off(three_relay_device, ep_b, on_time=20) # 2 s + _on_with_timed_off(three_relay_device, ep_c, on_time=30) # 3 s + + three_relay_device.step_time(1_500) + assert not three_relay_device.get_gpio("B0", refresh=True) + assert three_relay_device.get_gpio("B1", refresh=True) + assert three_relay_device.get_gpio("B2", refresh=True) + + three_relay_device.step_time(1_000) + assert not three_relay_device.get_gpio("B1", refresh=True) + assert three_relay_device.get_gpio("B2", refresh=True) + + three_relay_device.step_time(1_000) + assert not three_relay_device.get_gpio("B2", refresh=True) + + +def test_cancel_on_one_channel_does_not_affect_the_others( + three_relay_device: Device, +) -> None: + """Cancelling one channel's timer leaves the other two armed.""" + ep_a, ep_b, ep_c = 4, 5, 6 + _on_with_timed_off(three_relay_device, ep_a, on_time=100) # 10 s + _on_with_timed_off(three_relay_device, ep_b, on_time=100) # 10 s + _on_with_timed_off(three_relay_device, ep_c, on_time=100) # 10 s + + three_relay_device.step_time(5_000) + # Cancel only channel 2. + three_relay_device.call_zigbee_cmd(ep_b, ZCL_CLUSTER_ON_OFF, ZCL_CMD_ONOFF_ON) + three_relay_device.step_time(6_000) + + assert not three_relay_device.get_gpio("B0", refresh=True), ( + "channel 1's timer did not fire" + ) + assert three_relay_device.get_gpio("B1", refresh=True), ( + "channel 2's timer was not cancelled" + ) + assert not three_relay_device.get_gpio("B2", refresh=True), ( + "channel 3's timer did not fire" + ) + + +# --- plain commands cancel the timer ------------------------------------- + + +def test_plain_on_cancels_pending_timer(device: Device) -> None: + """ON means "stay on" — the pending auto-OFF must be dropped.""" + ep = 2 + _on_with_timed_off(device, ep, on_time=100) # 10 s + device.step_time(5_000) + device.call_zigbee_cmd(ep, ZCL_CLUSTER_ON_OFF, ZCL_CMD_ONOFF_ON) + device.step_time(6_000) # past the original 10 s deadline + assert device.get_gpio("B0", refresh=True), ( + "auto-OFF fired after a plain ON — the timer was not cancelled" + ) + + +def test_plain_off_cancels_pending_timer(device: Device) -> None: + """OFF turns the relay off; the stale timer must not fire later.""" + ep = 2 + _on_with_timed_off(device, ep, on_time=100) # 10 s + device.step_time(5_000) + device.call_zigbee_cmd(ep, ZCL_CLUSTER_ON_OFF, ZCL_CMD_ONOFF_OFF) + assert not device.get_gpio("B0", refresh=True) + device.step_time(6_000) + assert not device.get_gpio("B0", refresh=True) + + +def test_toggle_command_cancels_pending_timer(device: Device) -> None: + """TOGGLE flips the relay and must cancel the pending auto-OFF.""" + ep = 2 + _on_with_timed_off(device, ep, on_time=100) # 10 s + device.step_time(5_000) + device.call_zigbee_cmd(ep, ZCL_CLUSTER_ON_OFF, ZCL_CMD_ONOFF_TOGGLE) + # The relay was ON, so the toggle turned it OFF. + assert not device.get_gpio("B0", refresh=True) + device.step_time(6_000) + assert not device.get_gpio("B0", refresh=True) + + +def test_off_with_effect_cancels_pending_timer(device: Device) -> None: + """OFF with effect (0x40) is an OFF — it cancels the timer.""" + ep = 2 + _on_with_timed_off(device, ep, on_time=100) # 10 s + device.step_time(5_000) + device.call_zigbee_cmd( + ep, ZCL_CLUSTER_ON_OFF, ZCL_CMD_OFF_WITH_EFFECT, payload_bytes=[0x00] + ) + assert not device.get_gpio("B0", refresh=True) + device.step_time(6_000) + assert not device.get_gpio("B0", refresh=True) + + +def test_on_with_recall_global_scene_cancels_pending_timer(device: Device) -> None: + """ON with recall global scene (0x41) is an ON — it cancels the timer.""" + ep = 2 + _on_with_timed_off(device, ep, on_time=100) # 10 s + device.step_time(5_000) + device.call_zigbee_cmd( + ep, + ZCL_CLUSTER_ON_OFF, + ZCL_CMD_ON_WITH_RECALL_GLOBAL_SCENE, + payload_bytes=[0x00, 0x00, 0x00, 0x00], + ) + assert device.get_gpio("B0", refresh=True) + device.step_time(6_000) + assert device.get_gpio("B0", refresh=True), ( + "auto-OFF fired after on-with-recall — the timer was not cancelled" + ) + + +def test_level_move_cancels_pending_timer(device: Device) -> None: + """Level control with on/off (level 0) cancels the timer.""" + ep = 2 + _on_with_timed_off(device, ep, on_time=100) # 10 s + device.step_time(5_000) + device.call_zigbee_cmd( + ep, + ZCL_CLUSTER_LEVEL_CONTROL, + ZCL_CMD_LEVEL_MOVE_TO_LEVEL_WITH_ON_OFF, + payload_bytes=[0x00, 0x00, 0x00], + ) + assert not device.get_gpio("B0", refresh=True) + device.step_time(6_000) + assert not device.get_gpio("B0", refresh=True) + + +def test_attribute_write_does_not_cancel_pending_timer(device: Device) -> None: + """Writing the onOff attribute is not a relay action — the timer stays.""" + ep = 2 + _on_with_timed_off(device, ep, on_time=100) # 10 s + device.write_zigbee_attr(ep, ZCL_CLUSTER_ON_OFF, ZCL_ATTR_ONOFF, 1) + device.step_time(10_500) + assert not device.get_gpio("B0", refresh=True), ( + "the timer did not fire — an attribute write must not cancel it" + ) + + +# --- a second On With Timed Off replaces the first ------------------------ + + +def test_second_timed_off_replaces_the_pending_deadline(device: Device) -> None: + """A second On With Timed Off must REPLACE the pending deadline, not + stack on top of it and not cancel it. + + The replacement starts counting from the moment it arrives. + """ + ep = 2 + _on_with_timed_off(device, ep, on_time=100) # 10 s + device.step_time(5_000) + # Replace with a 20 s timer. + _on_with_timed_off(device, ep, on_time=200) + # Past the FIRST deadline (10 s from the start) — still ON, because the + # second command moved the deadline to 5 + 20 = 25 s. + device.step_time(6_000) + assert device.get_gpio("B0", refresh=True), ( + "the first timer fired — the second command did not replace it" + ) + # Past the SECOND deadline (25 s from the start). + device.step_time(15_000) + assert not device.get_gpio("B0", refresh=True), ( + "the replacement timer did not fire at its own deadline" + ) + + +def test_second_timed_off_with_zero_turns_off_now(device: Device) -> None: + """A replacement of (0,0) is a plain OFF and cancels the old timer.""" + ep = 2 + _on_with_timed_off(device, ep, on_time=100) # 10 s + device.step_time(5_000) + _on_with_timed_off(device, ep, on_time=0, off_wait_time=0) + assert not device.get_gpio("B0", refresh=True) + device.step_time(6_000) + assert not device.get_gpio("B0", refresh=True) + + +def test_second_timed_off_keeps_relay_on(device: Device) -> None: + """Replacing the timer must not toggle the relay off and on again — + the relay stays ON across the replacement.""" + ep = 2 + _on_with_timed_off(device, ep, on_time=100) # 10 s + device.step_time(5_000) + _on_with_timed_off(device, ep, on_time=200) + assert device.get_gpio("B0", refresh=True) + assert device.read_zigbee_attr(ep, ZCL_CLUSTER_ON_OFF, ZCL_ATTR_ONOFF) == "1" + + +# --- the physical button --------------------------------------------------- + + +def test_physical_button_cancels_pending_timer(device: Device) -> None: + """A button press drives the relay, which cancels the pending auto-OFF. + + The ONOFF action is used deliberately: it drives the relay ON without + changing its state, so the relay stays ON. If the timer had survived, + it would switch the relay OFF at its deadline — which is exactly what + this test watches for. + """ + ep = 2 + _make_momentary(device, 1, ZCL_ONOFF_CONFIGURATION_SWITCH_ACTION_ONOFF) + _on_with_timed_off(device, ep, on_time=100) # 10 s + assert device.get_gpio("B0") + device.step_time(5_000) + device.click_button("A0") + # The press drove the relay ON again — the state did not change. + assert device.get_gpio("B0", refresh=True) + # Past the original deadline. The button cancelled the timer, so the + # relay must still be ON. + device.step_time(6_000) + assert device.get_gpio("B0", refresh=True), ( + "auto-OFF fired after a button press — the button did not cancel it" + ) + + +def test_physical_button_toggle_turns_the_relay_off(device: Device) -> None: + """With the toggle action a button press flips the relay.""" + ep = 2 + _make_momentary( + device, 1, ZCL_ONOFF_CONFIGURATION_SWITCH_ACTION_TOGGLE_SIMPLE + ) + _on_with_timed_off(device, ep, on_time=100) # 10 s + device.step_time(5_000) + device.click_button("A0") + assert not device.get_gpio("B0", refresh=True), ( + "the button did not toggle the relay" + ) + + +def test_physical_button_long_press_cancels_pending_timer(device: Device) -> None: + """A long press also drives the relay and cancels the timer. + + RELAY_MODE_LONG drives the relay with a toggle on the long press + itself. The relay therefore ends up OFF, which is indistinguishable + from the auto-OFF having fired. The proof that the timer was + cancelled is the report count: the timer firing would push a second + onOff report (the relay was already off, so no third). + """ + ep = 2 + _make_momentary(device, 1, ZCL_ONOFF_CONFIGURATION_SWITCH_ACTION_ONOFF) + device.write_zigbee_attr( + 1, + ZCL_CLUSTER_ON_OFF_SWITCH_CONFIG, + ZCL_ATTR_ONOFF_CONFIGURATION_SWITCH_RELAY_MODE, + ZCL_ONOFF_CONFIGURATION_RELAY_MODE_LONG, + ) + _on_with_timed_off(device, ep, on_time=100) # 10 s + device.step_time(5_000) + device.long_click_button("A0", duration_ms=1_000) + # The long press toggled the relay off. + assert not device.get_gpio("B0", refresh=True) + reports_after_press = _onoff_reports(device, ep) + # Past the original deadline. If the timer had survived, it would + # fire here and push another report. + device.step_time(6_000) + assert _onoff_reports(device, ep) == reports_after_press, ( + "the auto-OFF fired after a long press — the press did not cancel it" + ) + assert not device.get_gpio("B0", refresh=True) + + +def test_button_in_detached_mode_leaves_the_timer_running(device: Device) -> None: + """A detached switch does not drive the relay, so the timer survives.""" + ep = 2 + _make_momentary(device, 1, ZCL_ONOFF_CONFIGURATION_SWITCH_ACTION_ONOFF) + device.write_zigbee_attr( + 1, + ZCL_CLUSTER_ON_OFF_SWITCH_CONFIG, + ZCL_ATTR_ONOFF_CONFIGURATION_SWITCH_RELAY_MODE, + ZCL_ONOFF_CONFIGURATION_RELAY_MODE_DETACHED, + ) + _on_with_timed_off(device, ep, on_time=100) # 10 s + device.click_button("A0") + assert device.get_gpio("B0", refresh=True) + device.step_time(10_500) + assert not device.get_gpio("B0", refresh=True), ( + "the timer did not fire in detach mode" + ) + + +# --- cross-endpoint isolation -------------------------------------------- + + +def test_button_of_the_other_endpoint_does_not_cancel_this_timer( + two_relay_device: Device, +) -> None: + """Switch 2 drives relay 2 (endpoint 4). It must not touch the timer + that belongs to relay 1 (endpoint 3).""" + ep_a, ep_b = 3, 4 + _make_momentary( + two_relay_device, 2, ZCL_ONOFF_CONFIGURATION_SWITCH_ACTION_ONOFF + ) + _on_with_timed_off(two_relay_device, ep_a, on_time=100) # 10 s + two_relay_device.step_time(5_000) + # Press the button of the second relay. + two_relay_device.click_button("A1") + # Relay A's timer must still fire at its own deadline. + two_relay_device.step_time(6_000) + assert not two_relay_device.get_gpio("B0", refresh=True), ( + "the button of the other endpoint cancelled this relay's timer" + ) + + +def test_plain_on_on_the_other_endpoint_does_not_cancel_this_timer( + two_relay_device: Device, +) -> None: + """An ON command to relay B must not cancel relay A's timer.""" + ep_a, ep_b = 3, 4 + _on_with_timed_off(two_relay_device, ep_a, on_time=100) # 10 s + two_relay_device.step_time(5_000) + two_relay_device.call_zigbee_cmd(ep_b, ZCL_CLUSTER_ON_OFF, ZCL_CMD_ONOFF_ON) + two_relay_device.step_time(6_000) + assert not two_relay_device.get_gpio("B0", refresh=True), ( + "relay A's timer did not fire — the other endpoint's command broke it" + ) + + +def test_timed_off_on_the_other_endpoint_does_not_cancel_this_timer( + two_relay_device: Device, +) -> None: + """Arming a timer on relay B must not disturb relay A's timer.""" + ep_a, ep_b = 3, 4 + _on_with_timed_off(two_relay_device, ep_a, on_time=100) # 10 s + two_relay_device.step_time(5_000) + _on_with_timed_off(two_relay_device, ep_b, on_time=200) + two_relay_device.step_time(6_000) + assert not two_relay_device.get_gpio("B0", refresh=True), ( + "relay A's timer did not fire — the other endpoint's timer broke it" + ) + + +# --- the timer firing on its own ----------------------------------------- + + +def test_timer_fires_and_leaves_the_relay_off(device: Device) -> None: + """After the deadline the relay is OFF and stays OFF.""" + ep = 2 + _on_with_timed_off(device, ep, on_time=100) # 10 s + device.step_time(10_500) + assert not device.get_gpio("B0", refresh=True) + assert device.read_zigbee_attr(ep, ZCL_CLUSTER_ON_OFF, ZCL_ATTR_ONOFF) == "0" + + +def test_timer_can_be_rearmed_after_it_fired(device: Device) -> None: + """After the timer fired, a new On With Timed Off works again.""" + ep = 2 + _on_with_timed_off(device, ep, on_time=100) # 10 s + device.step_time(10_500) + assert not device.get_gpio("B0", refresh=True) + # Re-arm with a fresh timer. + _on_with_timed_off(device, ep, on_time=100) + assert device.get_gpio("B0", refresh=True) + device.step_time(10_500) + assert not device.get_gpio("B0", refresh=True) diff --git a/tests/test_tick64_timer.py b/tests/test_tick64_timer.py new file mode 100644 index 0000000000..a1c515537c --- /dev/null +++ b/tests/test_tick64_timer.py @@ -0,0 +1,340 @@ +"""Regression test for the Telink 64-bit tick/millisecond counter. + +The bug this covers +------------------ +``src/telink/hal/timer.c`` used to build its 64-bit value like this:: + + uint32_t now_lo = clock_time() / CLOCK_16M_SYS_TIMER_CLK_1MS; + if (s_millis_last_lo != 0 && now_lo < s_millis_last_lo) s_millis_overflows++; + s_millis_last_lo = now_lo; + return ((uint64_t)s_millis_overflows << 32) | (uint64_t)s_millis_last_lo; + +``clock_time()`` is a 32-bit counter at 16 MHz, so it wraps every +2^32 / 16e6 = 268.435456 s. The derived millisecond value does NOT have +a 32-bit range: it only spans 0..268435 ms before it restarts. Shifting +the wrap counter left by 32 bits therefore added 2^32 ms (~49.7 days) +per hardware wrap instead of the ~268 s that actually elapsed. + +The result was not a millisecond timeline. A deadline computed as +``hal_millis_64() + delay`` was compared against a counter that jumped +forward by 49.7 days at every wrap, so any timer longer than ~268 s +fired at the wrap boundary instead of at its deadline. + +Observed on real hardware (Shower Switch 0x05EC, ZCL On With Timed Off +with onTime=3000 == 300 s): + + command 11:16:58.852 -> OFF 11:18:06.884 (68 s instead of 300 s) + command 10:42:22.138 -> OFF 10:46:47 (265 s instead of 300 s) + +Both OFF timestamps land exactly on a hardware-wrap boundary. + +Why this test compiles C +------------------------ +The existing ``test_on_with_timed_off_fires_after_hal_millis_wraparound`` +exercises the *stub* timer (``src/stub/hal/timer.c``), which returns a +perfect 64-bit value and therefore cannot reproduce the production bug. +This test compiles ``src/hal/tick64.h`` -- the exact header the +firmware includes -- and drives it with a simulated tick, so the logic +under test is the logic that ships. + +The harness also carries the OLD formula, so the tests can assert that +the old behaviour really did fire early. If someone reverts the fix in +the shared header, these assertions flip and the suite goes red. +""" + +import os +import re +import subprocess +import textwrap + +import pytest + +TICK_HZ = 16_000_000 +TICKS_PER_MS = 16_000 +WRAP_TICKS = 2**32 +WRAP_MS = WRAP_TICKS / TICKS_PER_MS # 268.435456 s + +# The largest onTime/offWaitTime the ZCL On With Timed Off command can +# carry: a uint16 in tenths of a second with 0xffff reserved. +ZCL_MAX_TIMER_MS = 6553_400 + +REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +TICK64_HEADER = os.path.join(REPO_ROOT, "src", "hal", "tick64.h") + +# C harness: reads a script of elapsed milliseconds on stdin and prints +# +# for each sample, so both formulas can be compared in one run. +# +# The harness deliberately uses only 32-bit division, like the fix: the +# Telink tc32 toolchain has no __udivdi3, so a 64-bit division does not +# link. A 64-bit division in the shared header would break the build. +HARNESS = textwrap.dedent( + """ + #include "hal/tick64.h" + #include + + /* The pre-fix implementation, kept here as the behavioural reference + for the assertions below. */ + static uint32_t old_last_lo = 0; + static uint32_t old_overflows = 0; + + static uint64_t old_millis_64(uint32_t tick) { + uint32_t now_lo = tick / 16000; + if (old_last_lo != 0 && now_lo < old_last_lo) { + old_overflows++; + } + old_last_lo = now_lo; + return ((uint64_t)old_overflows << 32) | (uint64_t)old_last_lo; + } + + int main(void) { + hal_tick64_state state; + hal_tick64_init(&state); + + unsigned long long elapsed_ms; + while (scanf("%llu", &elapsed_ms) == 1) { + /* The hardware tick is free running at 16 MHz and wraps at + 2^32, so the tick seen at a given elapsed time is the + elapsed time modulo the wrap period. */ + uint32_t tick = (uint32_t)((elapsed_ms * 16000ULL) & 0xFFFFFFFFULL); + + printf("%llu %llu\\n", + (unsigned long long)hal_tick64_millis(&state, tick), + (unsigned long long)old_millis_64(tick)); + } + return 0; + } + """ +) + + +@pytest.fixture(scope="module") +def tick64_harness(tmp_path_factory): + """Compile the production tick64.h into a runnable helper.""" + tmp = tmp_path_factory.mktemp("tick64") + src = tmp / "harness.c" + src.write_text(HARNESS) + binary = tmp / "harness" + + result = subprocess.run( + [ + os.environ.get("CC", "cc"), + "-std=c99", + "-Wall", + "-Werror", + "-I", + os.path.join(REPO_ROOT, "src"), + str(src), + "-o", + str(binary), + ], + capture_output=True, + text=True, + ) + if result.returncode != 0: + pytest.fail(f"failed to compile tick64 harness:\n{result.stderr}") + return binary + + +def run_elapsed(harness, elapsed_ms_list): + """Feed elapsed times to the harness. + + Returns (new_millis, old_millis) lists. + """ + stdin = "\n".join(str(v) for v in elapsed_ms_list) + "\n" + result = subprocess.run( + [str(harness)], input=stdin, capture_output=True, text=True + ) + assert result.returncode == 0, result.stderr + + new, old = [], [] + for line in result.stdout.splitlines(): + if not line.strip(): + continue + n, o = line.split() + new.append(int(n)) + old.append(int(o)) + return new, old + + +def fire_after(series, elapsed_ms_list, delay_ms): + """Real elapsed time at which `series` first reaches its deadline. + + The deadline is armed at the first sample and is `delay_ms` later in + the counter's own units. Returns the elapsed time (not the counter + value) at which it was reached, or None. + + Measuring in elapsed time is the only meaningful metric here: the + old counter's units are not milliseconds across a wrap -- it jumps + by 2^32 ms -- so differences taken in its units are meaningless. + """ + target = series[0] + delay_ms + for value, elapsed in zip(series, elapsed_ms_list): + if value >= target: + return elapsed + return None + + +def test_tick64_header_exists(): + """The shared header the firmware includes must exist.""" + assert os.path.exists(TICK64_HEADER), TICK64_HEADER + + +def test_no_64bit_division_in_shared_header(): + """The header must not use 64-bit division. + + The Telink tc32 toolchain has no __udivdi3, so a 64-bit division + in shared code does not link -- the build fails with an undefined + reference. This catches the mistake before a container build does. + """ + source = open(TICK64_HEADER).read() + # Strip both comment styles so a mention in prose does not trip + # the check. + code = re.sub(r"/\*.*?\*/", "", source, flags=re.S) + code = "\n".join(line.split("//")[0] for line in code.splitlines()) + + assert "__udivdi3" not in code + + # The only division present must divide a 32-bit value. + assert "delta / HAL_TICK64_TICKS_PER_MS" in code, ( + "expected the 32-bit division of the tick delta" + ) + for line in code.splitlines(): + stripped = line.strip() + if not stripped or stripped.startswith("*"): + continue + if "/=" not in stripped: + continue + divisor = stripped.split("/=")[1].strip().rstrip(";").strip() + if divisor.startswith("UINT64") or divisor.startswith("u64"): + pytest.fail(f"64-bit division in shared header: {stripped}") + if divisor.isdigit() and int(divisor) > 0xFFFFFFFF: + pytest.fail(f"64-bit divisor literal in shared header: {stripped}") + + +def test_counter_tracks_elapsed_time_exactly(tick64_harness): + """Without a wrap the counter must equal the elapsed time exactly.""" + elapsed = list(range(0, 500)) + new, old = run_elapsed(tick64_harness, elapsed) + + assert new == elapsed + assert old == elapsed # the old formula agreed before the first wrap + + +def test_survives_single_wrap(tick64_harness): + """Across a hardware wrap the counter must keep following real time.""" + # 268.435456 s is where the 32-bit tick wraps. + wrap_at_ms = int(WRAP_MS) # 268435 + elapsed = list(range(wrap_at_ms - 500, wrap_at_ms + 500)) + + new, old = run_elapsed(tick64_harness, elapsed) + + # The new counter is a true millisecond timeline across the wrap. + assert new == elapsed, "counter diverged from real time across the wrap" + + # The old one is not: it jumps by ~49.7 days at the wrap. + jump = max(old[i + 1] - old[i] for i in range(len(old) - 1)) + assert jump > 40_000_000, ( + f"expected the old formula to jump by ~49.7 days at the wrap, got {jump} ms" + ) + + +def test_wrap_boundary_continuity(tick64_harness): + """The millisecond counter must not skip or repeat across the wrap.""" + wrap_at_ms = int(WRAP_MS) + elapsed = list(range(wrap_at_ms - 50, wrap_at_ms + 50)) + + new, _old = run_elapsed(tick64_harness, elapsed) + + for i in range(1, len(new)): + assert new[i] - new[i - 1] == 1, ( + f"step {i}: {new[i - 1]} -> {new[i]}, expected +1" + ) + + +def test_deadline_longer_than_wrap_is_reached_exactly(tick64_harness): + """A 300 s deadline must not fire early at the wrap boundary. + + This is the actual production failure: onTime=3000 (300 s) is + longer than the 268.435456 s hardware wrap, so the old code fired + the relay at the wrap instead of at the deadline. + """ + deadline_ms = 300_000 + + # Arm 5 s before a wrap: the old code would have fired ~5 s later. + arm_at_ms = int(WRAP_MS) - 5_000 + elapsed = list(range(arm_at_ms, arm_at_ms + deadline_ms + 10_000, 100)) + + new, old = run_elapsed(tick64_harness, elapsed) + + # --- new implementation: fires at the deadline --- + fired = fire_after(new, elapsed, deadline_ms) + assert fired is not None, "300 s deadline was never reached" + expected = arm_at_ms + deadline_ms + assert abs(fired - expected) <= 100, ( + f"300 s deadline fired at {fired} ms, expected ~{expected} ms" + ) + + # --- old implementation: fired early, at the wrap --- + old_fired = fire_after(old, elapsed, deadline_ms) + assert old_fired is not None + wrap_at = int(WRAP_MS) + assert old_fired < wrap_at + 10_000, ( + f"expected the old formula to fire at the wrap (~{wrap_at} ms), " + f"got {old_fired} ms" + ) + assert old_fired < expected - 200_000, ( + f"expected the old formula to fire far earlier than the deadline, " + f"got {old_fired} ms" + ) + + +def test_short_timer_is_unaffected_by_the_fix(tick64_harness): + """A 60 s timer keeps working, both before and after the fix.""" + deadline_ms = 60_000 + + # Arm well inside an epoch so no wrap falls inside the window. + arm_at_ms = 10_000 + elapsed = list(range(arm_at_ms, arm_at_ms + deadline_ms + 5_000, 100)) + + new, old = run_elapsed(tick64_harness, elapsed) + + for label, series in (("new", new), ("old", old)): + target = series[0] + deadline_ms + fired = next((m for m in series if m >= target), None) + assert fired is not None, f"{label}: 60 s deadline never reached" + assert fired - target <= 100, f"{label}: fired {fired - target} ms late" + + +def test_zcl_maximum_timer_is_reachable(tick64_harness): + """The ZCL On With Timed Off maximum (6553 s) must also work. + + 6553 s is the largest value the command can carry: onTime is a + uint16 in tenths of a second, so it tops out just below an hour + and a half. That is 24 hardware wraps, which the old code could + not survive at all. + """ + arm_at_ms = 1_000 + elapsed = list(range(arm_at_ms, arm_at_ms + ZCL_MAX_TIMER_MS + 10_000, 1_000)) + + new, old = run_elapsed(tick64_harness, elapsed) + + # --- new implementation --- + fired = fire_after(new, elapsed, ZCL_MAX_TIMER_MS) + assert fired is not None, "maximum ZCL timer was never reached" + expected = arm_at_ms + ZCL_MAX_TIMER_MS + assert abs(fired - expected) <= 1_000, ( + f"maximum timer fired at {fired} ms, expected ~{expected} ms" + ) + + # --- old implementation: gave up at the first wrap --- + old_fired = fire_after(old, elapsed, ZCL_MAX_TIMER_MS) + assert old_fired is not None + assert old_fired < int(WRAP_MS) + 10_000, ( + f"expected the old formula to give up at the first wrap, " + f"got {old_fired} ms" + ) + assert old_fired < expected - 6_000_000, ( + f"expected the old formula to fire far earlier than the deadline, " + f"got {old_fired} ms" + ) diff --git a/zigbee2mqtt/countdown_timer_example.js b/zigbee2mqtt/countdown_timer_example.js new file mode 100644 index 0000000000..7220cee714 --- /dev/null +++ b/zigbee2mqtt/countdown_timer_example.js @@ -0,0 +1,346 @@ +// Example Zigbee2MQTT external converter for the countdown timer. +// +// The firmware in this PR implements the ZCL On With Timed Off command +// (0x42) on relay endpoints. Stock zigbee-herdsman-converters turns an +// "on_time" payload into that command, but the generated converters do +// not expose the field, so it cannot be set from the UI. +// +// This file is an example for the four models the implementation covers: +// +// _TZ3000_ljhbw1c9 LZWSM16-2 TS0012-avatto +// _TZ3000_kpatq5pq LZWSM16-2 TS0012-AVB1 +// _TZ3000_mtnpt6ws ZWSM16-2 TS0002-AVB +// _TZ3000_4rbqgcuv ZWSM16-1 TS0001-AVB +// +// The timer was tested on the first two models; the other two build and +// are covered by the same code, but were not verified on hardware. +// +// Install it as an external converter and drop the built-in entry for +// the same model, so the two definitions do not overlap. +// +// Endpoint layout comes from the config_str in device_db.yaml: the switch +// clusters come first, then the relay clusters. +// +// TS0012-avatto ljhbw1c9;TS0012-avatto;BB4u;LB5;SC0u;RC2;SC3u;RC4; +// TS0012-AVB1 kpatq5pq;TS0012-AVB1;BB4u;LB5;SC0u;RC2;SC3u;RC4; +// switch 1,2 relay 3,4 +// TS0002-AVB mtnpt6ws;TS0002-AVB;BC2u;LD2i;SD3u;RC0;SD7u;RD4; +// switch 1,2 relay 3,4 +// TS0001-AVB 4rbqgcuv;TS0001-AVB;BC2u;LD2i;SD3u;RC0; +// switch 1 relay 2 + +const { + deviceEndpoints, + enumLookup, + text, + binary, + numeric, + onOff, +} = require("zigbee-herdsman-converters/lib/modernExtend"); +const exposes = require("zigbee-herdsman-converters/lib/exposes"); +const tz = require("zigbee-herdsman-converters/converters/toZigbee"); +const reporting = require("zigbee-herdsman-converters/lib/reporting"); +const constants = require("zigbee-herdsman-converters/lib/constants"); +const {assertString} = require("zigbee-herdsman-converters/lib/utils"); + +const {Numeric, access: ea} = exposes; + +// ====== romasku attributes (subset used by these models) ====== + +const romasku = { + pressAction: (name, endpointName) => + enumLookup({ + name, + endpointName, + access: "STATE_GET", + lookup: {released: 0, press: 1, long_press: 2}, + cluster: "genMultistateInput", + attribute: "presentValue", + description: "Action of the switch: 'released' / 'press' / 'long_press'", + entityCategory: "diagnostic", + }), + switchMode: (name, endpointName) => + enumLookup({ + name, + endpointName, + lookup: {toggle: 0, momentary: 1, momentary_nc: 2}, + cluster: "genOnOffSwitchCfg", + attribute: {ID: 0xff00, type: 0x30}, + description: "Select the type of switch connected to the device", + entityCategory: "config", + }), + switchAction: (name, endpointName) => + enumLookup({ + name, + endpointName, + lookup: { + on_off: 0, + off_on: 1, + toggle_simple: 2, + toggle_smart_sync: 3, + toggle_smart_opposite: 4, + }, + cluster: "genOnOffSwitchCfg", + attribute: {ID: 0x0010, type: 0x30}, + description: `Select how switch should work:\n|- on_off: physical position 1 = ON, position 2 = OFF\n|- off_on: positions swapped\n|- toggle_simple: any press TOGGLE the relay\n|- toggle_smart_sync: TOGGLE + send ON/OFF to keep binds in sync\n|- toggle_smart_opposite: TOGGLE + send OPPOSITE ON/OFF to binds`, + entityCategory: "config", + }), + relayMode: (name, endpointName) => + enumLookup({ + name, + endpointName, + lookup: {detached: 0, press_start: 1, short_press: 3, long_press: 2}, + cluster: "genOnOffSwitchCfg", + attribute: {ID: 0xff01, type: 0x30}, + description: "When to turn on/off internal relay", + entityCategory: "config", + }), + relayIndex: (name, endpointName, relayCnt) => + enumLookup({ + name, + endpointName, + lookup: Object.fromEntries( + Array.from({length: relayCnt || 2}, (_, i) => [`relay_${i + 1}`, i + 1]) + ), + cluster: "genOnOffSwitchCfg", + attribute: {ID: 0xff02, type: 0x20}, + description: "Which internal relay this switch triggers", + entityCategory: "config", + }), + bindedMode: (name, endpointName) => + enumLookup({ + name, + endpointName, + lookup: {press_start: 1, short_press: 3, long_press: 2}, + cluster: "genOnOffSwitchCfg", + attribute: {ID: 0xff05, type: 0x30}, + description: "When to send commands to bound devices", + entityCategory: "config", + }), + longPressDuration: (name, endpointName) => + numeric({ + name, + endpointNames: [endpointName], + cluster: "genOnOffSwitchCfg", + attribute: {ID: 0xff03, type: 0x21}, + description: "Threshold for long press (ms)", + valueMin: 0, + valueMax: 5000, + entityCategory: "config", + }), + levelMoveRate: (name, endpointName) => + numeric({ + name, + endpointNames: [endpointName], + cluster: "genOnOffSwitchCfg", + attribute: {ID: 0xff04, type: 0x20}, + description: "Level (dim) move rate in steps/ms", + valueMin: 1, + valueMax: 255, + entityCategory: "config", + }), + networkIndicator: (name, endpointName) => + binary({ + name, + endpointName, + valueOn: ["ON", 1], + valueOff: ["OFF", 0], + cluster: "genBasic", + attribute: {ID: 0xff01, type: 0x10}, + description: "State of the network indicator LED", + access: "ALL", + entityCategory: "config", + }), + multiPressResetCount: (name, endpointName) => + numeric({ + name, + endpointNames: [endpointName], + cluster: "genBasic", + attribute: {ID: 0xff02, type: 0x20}, + description: "Consecutive presses to trigger factory reset (0 = disabled)", + valueMin: 0, + valueMax: 255, + entityCategory: "config", + }), + deviceConfig: (name, endpointName) => + text({ + name, + endpointName, + access: "ALL", + cluster: "genBasic", + attribute: {ID: 0xff00, type: 0x44}, + description: "Current configuration of the device", + zigbeeCommandOptions: {timeout: 30_000}, + validate: assertString, + entityCategory: "config", + }), +}; + +// ====== on_time / off_wait_time in the UI ====== +// +// Stock tz.on_off already puts the right bytes on the wire. Only a +// write-only Numeric is needed here, so the field shows up in the UI. + +const countdownExposes = (endpointNames) => + endpointNames.map((endpointName) => + new Numeric("on_time", ea.SET) + .withUnit("s") + .withDescription("Seconds to stay ON before switching OFF. 0 = no timer.") + .withEndpoint(endpointName) + .withPreset("on", "on", "Turn ON with a countdown timer") + ); + +// ====== build the definition ====== + +const makeDefinition = ({zigbeeModel, model, description, icon, switchNames, relayNames, endpoints}) => { + // state and on_time need separate converters: Z2M drops a converter + // bound to endpoints when the payload key carries no endpoint + // qualifier, and logs "No converter available for 'on_time'". + const stateConverter = { + ...tz.on_off, + key: ["state"], + endpoints: relayNames, + }; + + const timerConverter = { + ...tz.on_off, + key: ["on_time", "off_wait_time"], + convertSet: async (entity, key, value, meta) => { + // A qualified state_ key was already handled by the + // state converter, which sends the command to that endpoint. + // Sending it again would re-arm the first relay's timer. + const qualifiedState = Object.keys(meta.message).find( + (k) => k.startsWith("state_") && relayNames.includes(k.substring("state_".length)) + ); + if (qualifiedState !== undefined) { + return; + } + + // A bare on_time carries no state, and tz.on_off rejects a + // missing one. Default to "on" so the timer branch is taken. + if (meta.message.state === undefined) { + meta.message.state = "on"; + } + return tz.on_off.convertSet(entity, key, value, meta); + }, + }; + + // modernExtend's onOff() provides the state and power_on_behavior + // exposes and the genOnOff reporting setup. Only its toZigbee list is + // replaced, to split state from the timer. + const onOffExtend = onOff({endpointNames: relayNames}); + onOffExtend.toZigbee = [stateConverter, timerConverter, tz.power_on_behavior]; + + return { + zigbeeModel, + model, + vendor: "Tuya-custom", + description, + icon, + + extend: [ + deviceEndpoints({endpoints}), + + onOffExtend, + + { + isModernExtend: true, + exposes: countdownExposes(relayNames), + }, + + // Configuration attributes, on the first switch endpoint. + romasku.deviceConfig("device_config", switchNames[0]), + romasku.multiPressResetCount("multi_press_reset_count", switchNames[0]), + romasku.networkIndicator("network_led", switchNames[0]), + + // Configuration of each physical switch + ...switchNames.flatMap((sw) => [ + romasku.pressAction(`${sw}_press_action`, sw), + romasku.switchMode(`${sw}_mode`, sw), + romasku.switchAction(`${sw}_action_mode`, sw), + romasku.relayMode(`${sw}_relay_mode`, sw), + romasku.relayIndex(`${sw}_relay_index`, sw, relayNames.length), + romasku.bindedMode(`${sw}_binded_mode`, sw), + romasku.longPressDuration(`${sw}_long_press_duration`, sw), + romasku.levelMoveRate(`${sw}_level_move_rate`, sw), + ]), + ], + + meta: {multiEndpoint: true}, + + configure: async (device, coordinatorEndpoint) => { + // Button press reports (genMultistateInput on the switch endpoints). + // onOff() above also does the genOnOff binding and reporting: it looks + // for endpoints by the genOnOff server cluster, and on the switch + // endpoints genOnOff is a client (is_server = 0 in + // src/zigbee/switch_cluster.c), so they are skipped. + for (const sw of switchNames) { + const endpoint = device.getEndpoint(endpoints[sw]); + await reporting.bind(endpoint, coordinatorEndpoint, ["genMultistateInput"]); + await endpoint.configureReporting("genMultistateInput", [ + { + attribute: {ID: 0x0055 /* presentValue */, type: 0x21}, + minimumReportInterval: 0, + maximumReportInterval: constants.repInterval.MAX, + reportableChange: 1, + }, + ]); + } + }, + + ota: true, + }; +}; + + +// ====== definitions ====== + +const twoRelayEndpoints = {switch_left: 1, switch_right: 2, relay_left: 3, relay_right: 4}; +const oneRelayEndpoints = {switch: 1, relay: 2}; + +module.exports = [ + makeDefinition({ + zigbeeModel: ["TS0012-avatto"], + model: "LZWSM16-2", + description: + "AVATTO LZWSM16-2 / TS0012 2-gang switch module, " + + "romasku/tuya-zigbee-switch firmware with countdown timer support.", + icon: "https://www.zigbee2mqtt.io/images/devices/LZWSM16-2.png", + switchNames: ["switch_left", "switch_right"], + relayNames: ["relay_left", "relay_right"], + endpoints: twoRelayEndpoints, + }), + makeDefinition({ + zigbeeModel: ["TS0012-AVB1"], + model: "LZWSM16-2", + description: + "AVATTO LZWSM16-2 / TS0012 2-gang switch module, " + + "romasku/tuya-zigbee-switch firmware with countdown timer support.", + icon: "https://www.zigbee2mqtt.io/images/devices/LZWSM16-2.png", + switchNames: ["switch_left", "switch_right"], + relayNames: ["relay_left", "relay_right"], + endpoints: twoRelayEndpoints, + }), + makeDefinition({ + zigbeeModel: ["TS0002-AVB"], + model: "ZWSM16-2", + description: + "AVATTO ZWSM16-2 / TS0002 2-gang switch module, " + + "romasku/tuya-zigbee-switch firmware with countdown timer support.", + icon: "https://www.zigbee2mqtt.io/images/devices/ZWSM16-2.png", + switchNames: ["switch_left", "switch_right"], + relayNames: ["relay_left", "relay_right"], + endpoints: twoRelayEndpoints, + }), + makeDefinition({ + zigbeeModel: ["TS0001-AVB"], + model: "ZWSM16-1", + description: + "AVATTO ZWSM16-1 / TS0001 1-gang switch module, " + + "romasku/tuya-zigbee-switch firmware with countdown timer support.", + icon: "https://www.zigbee2mqtt.io/images/devices/ZWSM16-1.png", + switchNames: ["switch"], + relayNames: ["relay"], + endpoints: oneRelayEndpoints, + }), +];