From 3bf7d40e1939fc51544dbc4453a9159c0b68c418 Mon Sep 17 00:00:00 2001 From: Aleksandr Khromykh Date: Wed, 8 Jan 2025 14:59:42 +0100 Subject: [PATCH] Bluetooth: Mesh: fix uptime to tai conversion inaccuracy Commit fixes uptime to tai inaccuracy conversion. Previous implementation did not take into account subseconds overflow that caused -1 second inaccuracy. Signed-off-by: Aleksandr Khromykh --- subsys/bluetooth/mesh/time_srv.c | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/subsys/bluetooth/mesh/time_srv.c b/subsys/bluetooth/mesh/time_srv.c index 4fbfada67c7a..549af6fe4438 100644 --- a/subsys/bluetooth/mesh/time_srv.c +++ b/subsys/bluetooth/mesh/time_srv.c @@ -36,20 +36,27 @@ static inline bool tai_is_unknown(const struct bt_mesh_time_tai *tai) return !tai->sec && !tai->subsec; } -static inline struct bt_mesh_time_tai -tai_at(const struct bt_mesh_time_srv *srv, int64_t uptime) +static inline struct bt_mesh_time_tai tai_at(const struct bt_mesh_time_srv *srv, int64_t uptime) { const struct bt_mesh_time_tai *sync = &srv->data.sync.status.tai; - int64_t steps = (SUBSEC_STEPS * (uptime - srv->data.sync.uptime)) / - MSEC_PER_SEC; + int64_t steps = (SUBSEC_STEPS * (uptime - srv->data.sync.uptime)) / MSEC_PER_SEC; + int64_t sec; + int64_t subsec; if (tai_is_unknown(sync)) { return *sync; } - return (struct bt_mesh_time_tai) { - .sec = sync->sec + (steps / SUBSEC_STEPS), - .subsec = sync->subsec + steps, + subsec = sync->subsec + steps; + sec = sync->sec + (subsec / SUBSEC_STEPS); + + if (subsec >= SUBSEC_STEPS) { + subsec %= SUBSEC_STEPS; + } + + return (struct bt_mesh_time_tai){ + .sec = sec, + .subsec = subsec, }; }