diff --git a/app/src/battery.c b/app/src/battery.c index c6466272082..e76797ef997 100644 --- a/app/src/battery.c +++ b/app/src/battery.c @@ -18,6 +18,8 @@ LOG_MODULE_DECLARE(zmk, CONFIG_ZMK_LOG_LEVEL); #include #include #include +#include +#include #include static uint8_t last_state_of_charge = 0; @@ -84,6 +86,10 @@ static void zmk_battery_timer(struct k_timer *timer) { K_TIMER_DEFINE(battery_timer, zmk_battery_timer, NULL); +static void zmk_battery_start_reporting() { + k_timer_start(&battery_timer, K_NO_WAIT, K_SECONDS(CONFIG_ZMK_BATTERY_REPORT_INTERVAL)); +} + static int zmk_battery_init(const struct device *_arg) { #if !DT_HAS_CHOSEN(zmk_battery) battery = device_get_binding("BATTERY"); @@ -100,9 +106,30 @@ static int zmk_battery_init(const struct device *_arg) { return -ENODEV; } - k_timer_start(&battery_timer, K_NO_WAIT, K_SECONDS(CONFIG_ZMK_BATTERY_REPORT_INTERVAL)); - + zmk_battery_start_reporting(); return 0; } +static int battery_event_listener(const zmk_event_t *eh) { + + if (as_zmk_activity_state_changed(eh)) { + switch (zmk_activity_get_state()) { + case ZMK_ACTIVITY_ACTIVE: + zmk_battery_start_reporting(); + return 0; + case ZMK_ACTIVITY_IDLE: + case ZMK_ACTIVITY_SLEEP: + k_timer_stop(&battery_timer); + return 0; + default: + break; + } + } + return -ENOTSUP; +} + +ZMK_LISTENER(battery, battery_event_listener); + +ZMK_SUBSCRIPTION(battery, zmk_activity_state_changed); + SYS_INIT(zmk_battery_init, APPLICATION, CONFIG_APPLICATION_INIT_PRIORITY);