Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions docs/changelog_fw.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
5 changes: 5 additions & 0 deletions src/app.c
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
87 changes: 87 additions & 0 deletions src/hal/tick64.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
#ifndef _HAL_TICK64_H_
#define _HAL_TICK64_H_

#include <stdint.h>

/**
* 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
30 changes: 30 additions & 0 deletions src/hal/timer.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
7 changes: 7 additions & 0 deletions src/stub/commands.c
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

#include "stub/stub_app.h"
#include "zigbee/consts.h"
#include "zigbee/relay_cluster.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Expand Down Expand Up @@ -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;
}

Expand Down
18 changes: 18 additions & 0 deletions src/stub/hal/timer.c
Original file line number Diff line number Diff line change
Expand Up @@ -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(&current_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;
}
18 changes: 15 additions & 3 deletions src/telink/hal/timer.c
Original file line number Diff line number Diff line change
@@ -1,11 +1,23 @@
#include "hal/timer.h"
#include "hal/tick64.h"
#pragma pack(push, 1)
#include "tl_common.h"
#pragma pack(pop)
#include <stdint.h>

// 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());
}
89 changes: 89 additions & 0 deletions src/zigbee/relay_cluster.c
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand All @@ -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);

Expand Down Expand Up @@ -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;
Expand All @@ -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 {
Expand Down Expand Up @@ -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 ||
Expand Down Expand Up @@ -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
Loading