1+ #include <zephyr/sys/byteorder.h>
2+ #include <zephyr/logging/log.h>
3+ #include <zephyr/bluetooth/gatt.h>
4+
5+ #include "current_time_service.h"
6+
7+ LOG_MODULE_REGISTER (ZephyrWatch_CurrentTimeService , LOG_LEVEL_INF );
8+
9+
10+ /* Holds current time data. */
11+ static uint8_t m_current_time_data [10 ] = {
12+ 232U , // Year (2024) last byte
13+ 7U , // Year (2024) first byte
14+ 5U , // Month (May)
15+ 13U , // Day (13th)
16+ 23U , // Hours (23)
17+ 45U , // Minutes (45)
18+ 30U , // Seconds (30)
19+ 2U , // Day of week (Tuesday)
20+ 0U , // Fractions 256 part of 'Exact Time 256'
21+ 0U , // Adjust reason
22+ };
23+
24+ /* Current Time Service Declaration */
25+ static ssize_t m_time_write_callback (
26+ struct bt_conn * conn ,
27+ const struct bt_gatt_attr * attr ,
28+ const void * buf ,
29+ uint16_t len ,
30+ uint16_t offset ,
31+ uint8_t flags ) {
32+
33+ // Get the value of the attribute.
34+ uint8_t * value = attr -> user_data ;
35+
36+ // Check if the value written is valid.
37+ if (offset + len > sizeof (m_current_time_data )) {
38+ LOG_ERR ("Write request too long." );
39+ return BT_GATT_ERR (BT_ATT_ERR_INVALID_OFFSET );
40+ }
41+
42+ // Copy the new value into the m_current_time_data array (given as buffer).
43+ memcpy (value + offset , buf , len );
44+ LOG_INF ("Current time updated from the Bluetooth client." );
45+ return len ;
46+ }
47+
48+ /* Current Time Service Declaration */
49+ /*
50+ BT_GATT_SERVICE_DEFINE(cts_cvs,
51+ BT_GATT_PRIMARY_SERVICE(BT_UUID_CTS),
52+ BT_GATT_CHARACTERISTIC(
53+ BT_UUID_CTS_CURRENT_TIME,
54+ BT_GATT_CHRC_WRITE,
55+ BT_GATT_PERM_WRITE,
56+ NULL, m_time_write_callback, m_current_time_data),
57+ );
58+ */
59+
60+ /* API for the Current Time Service application layer consumers.
61+ * - get_current_time: Get the current time. Returns a struct with
62+ * proper key-value pairs for year, month, hours, minutes, and seconds.
63+ * - set_current_time: Set the current time. Takes a struct with
64+ * proper key-value pairs for year, month, hours, minutes, and seconds.
65+ */
66+
67+ struct current_time get_current_time (void ) {
68+ struct current_time time ;
69+ time .year = sys_le16_to_cpu (* (uint16_t * ) & m_current_time_data [0 ]);
70+ time .month = m_current_time_data [2 ];
71+ time .day = m_current_time_data [3 ];
72+ time .hours = m_current_time_data [4 ];
73+ time .minutes = m_current_time_data [5 ];
74+ time .seconds = m_current_time_data [6 ];
75+ return time ;
76+ }
77+
78+ void set_current_time (struct current_time time ) {
79+ * (uint16_t * ) & m_current_time_data [0 ] = sys_cpu_to_le16 (time .year );
80+ m_current_time_data [2 ] = time .month ;
81+ m_current_time_data [3 ] = time .day ;
82+ m_current_time_data [4 ] = time .hours ;
83+ m_current_time_data [5 ] = time .minutes ;
84+ m_current_time_data [6 ] = time .seconds ;
85+ }
0 commit comments