xref: /btstack/src/ble/gatt-service/ancs_client.c (revision c824d78c0a34df89b57d535abafcc7dacf30bb06)
1 /*
2  * Copyright (C) 2014 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BLUEKITCHEN
24  * GMBH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 #define BTSTACK_FILE__ "ancs_client.c"
39 
40 #include "btstack_config.h"
41 
42 #include <stdint.h>
43 #include <string.h>
44 
45 #include "ble/gatt-service/ancs_client.h"
46 
47 #include "ble/core.h"
48 #include "ble/gatt_client.h"
49 #include "ble/sm.h"
50 #include "btstack_debug.h"
51 #include "btstack_event.h"
52 #include "gap.h"
53 
54 // ancs_client.h Start
55 typedef enum ancs_chunk_parser_state {
56     W4_ATTRIBUTE_ID,
57     W4_ATTRIBUTE_LEN,
58     W4_ATTRIBUTE_COMPLETE,
59 } ancs_chunk_parser_state_t;
60 
61 typedef enum {
62     TC_IDLE,
63     TC_W4_ENCRYPTED_CONNECTION,
64     TC_W4_SERVICE_RESULT,
65     TC_W4_CHARACTERISTIC_RESULT,
66     TC_W4_DATA_SOURCE_SUBSCRIBED,
67     TC_W4_NOTIFICATION_SOURCE_SUBSCRIBED,
68     TC_SUBSCRIBED,
69     TC_W4_DISCONNECT
70 } tc_state_t;
71 
72 static uint32_t ancs_notification_uid;
73 static uint16_t gc_handle;
74 static gatt_client_notification_t ancs_notification_source_notification;
75 static gatt_client_notification_t ancs_data_source_notification;
76 static int ancs_service_found;
77 static gatt_client_service_t  ancs_service;
78 static gatt_client_characteristic_t ancs_notification_source_characteristic;
79 static gatt_client_characteristic_t ancs_control_point_characteristic;
80 static gatt_client_characteristic_t ancs_data_source_characteristic;
81 static int ancs_characteristcs;
82 static tc_state_t tc_state = TC_IDLE;
83 
84 static ancs_chunk_parser_state_t chunk_parser_state;
85 static uint8_t  ancs_notification_buffer[50];
86 static uint16_t ancs_bytes_received;
87 static uint16_t ancs_bytes_needed;
88 static uint8_t  ancs_attribute_id;
89 static uint16_t ancs_attribute_len;
90 
91 static btstack_packet_handler_t client_handler;
92 static btstack_packet_callback_registration_t hci_event_callback_registration;
93 
94 static void ancs_client_handle_gatt_client_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
95 
96 void ancs_client_register_callback(btstack_packet_handler_t handler){
97     client_handler = handler;
98 }
99 
100 static void notify_client_text(int event_type){
101     if (!client_handler) return;
102     uint8_t event[7 + sizeof(ancs_notification_buffer) + 1];
103     event[0] = HCI_EVENT_ANCS_META;
104     event[1] = 5u + ancs_attribute_len;
105     event[2] = event_type;
106     little_endian_store_16(event, 3, gc_handle);
107     little_endian_store_16(event, 5, ancs_attribute_id);
108     (void)memcpy(&event[7], ancs_notification_buffer, ancs_attribute_len);
109     // we're nice
110     event[7u+ancs_attribute_len] = 0u;
111     (*client_handler)(HCI_EVENT_PACKET, 0u, event, event[1u] + 2u);
112 }
113 
114 static void notify_client_simple(int event_type){
115     if (!client_handler) return;
116     uint8_t event[5];
117     event[0] = HCI_EVENT_ANCS_META;
118     event[1] = 3;
119     event[2] = event_type;
120     little_endian_store_16(event, 3, gc_handle);
121     (*client_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
122 }
123 
124 static void ancs_chunk_parser_init(void){
125     // skip comand id and notification uid
126     chunk_parser_state = W4_ATTRIBUTE_ID;
127     ancs_bytes_received = 0;
128     ancs_bytes_needed = 6;
129 }
130 
131 const char * ancs_client_attribute_name_for_id(int id){
132     static const char * ancs_attribute_names[] = {
133             "AppIdentifier",
134             "IDTitle",
135             "IDSubtitle",
136             "IDMessage",
137             "IDMessageSize",
138             "IDDate"
139     };
140 
141     static const uint16_t ANCS_ATTRIBUTE_NAMES_COUNT = sizeof(ancs_attribute_names) / sizeof(char *);
142 
143     if (id >= ANCS_ATTRIBUTE_NAMES_COUNT) return NULL;
144     return ancs_attribute_names[id];
145 }
146 
147 static void ancs_chunk_parser_handle_byte(uint8_t data){
148     ancs_notification_buffer[ancs_bytes_received++] = data;
149     if (ancs_bytes_received < ancs_bytes_needed) return;
150     switch (chunk_parser_state){
151         case W4_ATTRIBUTE_ID:
152             ancs_attribute_id   = ancs_notification_buffer[ancs_bytes_received-1u];
153             ancs_bytes_received = 0;
154             ancs_bytes_needed   = 2;
155             chunk_parser_state  = W4_ATTRIBUTE_LEN;
156             break;
157         case W4_ATTRIBUTE_LEN:
158             ancs_attribute_len  = little_endian_read_16(ancs_notification_buffer, ancs_bytes_received-2u);
159             ancs_bytes_received = 0;
160             ancs_bytes_needed   = ancs_attribute_len;
161             if (ancs_attribute_len == 0u) {
162                 ancs_bytes_needed   = 1;
163                 chunk_parser_state  = W4_ATTRIBUTE_ID;
164                 break;
165             }
166             chunk_parser_state  = W4_ATTRIBUTE_COMPLETE;
167             break;
168         case W4_ATTRIBUTE_COMPLETE:
169             ancs_notification_buffer[ancs_bytes_received] = 0;
170             notify_client_text(ANCS_SUBEVENT_CLIENT_NOTIFICATION);
171             ancs_bytes_received = 0;
172             ancs_bytes_needed   = 1;
173             chunk_parser_state  = W4_ATTRIBUTE_ID;
174             break;
175         default:
176             btstack_unreachable();
177             break;
178     }
179 }
180 
181 static void ancs_client_handle_notification(uint8_t * packet, uint16_t size){
182     UNUSED(size);
183 
184     uint16_t  value_handle = little_endian_read_16(packet, 4);
185     uint16_t  value_length = little_endian_read_16(packet, 6);
186     uint8_t * value = &packet[8];
187 
188     log_info("ANCS Notification, value handle %u", value_handle);
189 
190     if (value_handle == ancs_data_source_characteristic.value_handle){
191         int i;
192         for (i=0;i<value_length;i++) {
193             ancs_chunk_parser_handle_byte(value[i]);
194         }
195     } else if (value_handle == ancs_notification_source_characteristic.value_handle){
196         ancs_notification_uid = little_endian_read_32(value, 4);
197         log_info("Notification received: EventID %02x, EventFlags %02x, CategoryID %02x, CategoryCount %u, UID %04x",
198                  value[0], value[1], value[2], value[3], (int) ancs_notification_uid);
199         static uint8_t get_notification_attributes[] = {0, 0,0,0,0,  0,  1,32,0,  2,32,0, 3,32,0, 4, 5};
200         little_endian_store_32(get_notification_attributes, 1, ancs_notification_uid);
201         ancs_notification_uid = 0;
202         ancs_chunk_parser_init();
203         gatt_client_write_value_of_characteristic(ancs_client_handle_gatt_client_event, gc_handle, ancs_control_point_characteristic.value_handle,
204                                                   sizeof(get_notification_attributes), get_notification_attributes);
205     } else {
206         log_info("Unknown Source: ");
207         log_info_hexdump(value , value_length);
208     }
209 }
210 
211 static void ancs_client_handle_gatt_client_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
212 
213     UNUSED(packet_type);
214     UNUSED(channel);
215 
216     static const uint8_t ancs_notification_source_uuid[] = {0x9F,0xBF,0x12,0x0D,0x63,0x01,0x42,0xD9,0x8C,0x58,0x25,0xE6,0x99,0xA2,0x1D,0xBD};
217     static const uint8_t ancs_control_point_uuid[] =       {0x69,0xD1,0xD8,0xF3,0x45,0xE1,0x49,0xA8,0x98,0x21,0x9B,0xBD,0xFD,0xAA,0xD9,0xD9};
218     static const uint8_t ancs_data_source_uuid[] =         {0x22,0xEA,0xC6,0xE9,0x24,0xD6,0x4B,0xB5,0xBE,0x44,0xB3,0x6A,0xCE,0x7C,0x7B,0xFB};
219 
220     gatt_client_characteristic_t characteristic;
221 
222     switch(tc_state){
223         case TC_W4_SERVICE_RESULT:
224             switch(hci_event_packet_get_type(packet)){
225                 case GATT_EVENT_SERVICE_QUERY_RESULT:
226                     gatt_event_service_query_result_get_service(packet, &ancs_service);
227                     ancs_service_found = 1;
228                     break;
229                 case GATT_EVENT_QUERY_COMPLETE:
230                     if (!ancs_service_found){
231                         log_info("ANCS Service not found");
232                         tc_state = TC_IDLE;
233                         break;
234                     }
235                     tc_state = TC_W4_CHARACTERISTIC_RESULT;
236                     log_info("ANCS Client - Discover characteristics for ANCS SERVICE ");
237                     gatt_client_discover_characteristics_for_service(ancs_client_handle_gatt_client_event, gc_handle, &ancs_service);
238                     break;
239                 default:
240                     break;
241             }
242             break;
243 
244         case TC_W4_CHARACTERISTIC_RESULT:
245             switch(hci_event_packet_get_type(packet)){
246                 case GATT_EVENT_CHARACTERISTIC_QUERY_RESULT:
247                     gatt_event_characteristic_query_result_get_characteristic(packet, &characteristic);
248                     if (memcmp(characteristic.uuid128, ancs_notification_source_uuid, 16) == 0){
249                         log_info("ANCS Notification Source found, attribute handle %u", characteristic.value_handle);
250                         ancs_notification_source_characteristic = characteristic;
251                         ancs_characteristcs++;
252                         break;
253                     }
254                     if (memcmp(characteristic.uuid128, ancs_control_point_uuid, 16) == 0){
255                         log_info("ANCS Control Point found, attribute handle %u", characteristic.value_handle);
256                         ancs_control_point_characteristic = characteristic;
257                         ancs_characteristcs++;
258                         break;
259                     }
260                     if (memcmp(characteristic.uuid128, ancs_data_source_uuid, 16) == 0){
261                         log_info("ANCS Data Source found, attribute handle %u", characteristic.value_handle);
262                         ancs_data_source_characteristic = characteristic;
263                         ancs_characteristcs++;
264                         break;
265                     }
266                     break;
267                 case GATT_EVENT_QUERY_COMPLETE:
268                     log_info("ANCS Characteristcs count %u", ancs_characteristcs);
269                     tc_state = TC_W4_NOTIFICATION_SOURCE_SUBSCRIBED;
270                     gatt_client_listen_for_characteristic_value_updates(&ancs_notification_source_notification, &ancs_client_handle_gatt_client_event, gc_handle, &ancs_notification_source_characteristic);
271                     gatt_client_write_client_characteristic_configuration(ancs_client_handle_gatt_client_event, gc_handle, &ancs_notification_source_characteristic,
272                                                                           GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_NOTIFICATION);
273                     break;
274                 default:
275                     break;
276             }
277             break;
278         case TC_W4_NOTIFICATION_SOURCE_SUBSCRIBED:
279             switch(hci_event_packet_get_type(packet)){
280                 case GATT_EVENT_QUERY_COMPLETE:
281                     log_info("ANCS Notification Source subscribed");
282                     tc_state = TC_W4_DATA_SOURCE_SUBSCRIBED;
283                     gatt_client_listen_for_characteristic_value_updates(&ancs_data_source_notification, &ancs_client_handle_gatt_client_event, gc_handle, &ancs_data_source_characteristic);
284                     gatt_client_write_client_characteristic_configuration(ancs_client_handle_gatt_client_event, gc_handle, &ancs_data_source_characteristic,
285                                                                           GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_NOTIFICATION);
286                     break;
287                 default:
288                     break;
289             }
290             break;
291         case TC_W4_DATA_SOURCE_SUBSCRIBED:
292             switch(hci_event_packet_get_type(packet)){
293                 case GATT_EVENT_QUERY_COMPLETE:
294                     log_info("ANCS Data Source subscribed");
295                     tc_state = TC_SUBSCRIBED;
296                     notify_client_simple(ANCS_SUBEVENT_CLIENT_CONNECTED);
297                     break;
298                 default:
299                     break;
300             }
301             break;
302         case TC_SUBSCRIBED:
303             switch(hci_event_packet_get_type(packet)){
304                 case GATT_EVENT_NOTIFICATION:
305                 case GATT_EVENT_INDICATION:
306                     ancs_client_handle_notification(packet, size);
307                     break;
308                 default:
309                     break;
310             }
311             break;
312         default:
313             break;
314     }
315 }
316 
317 static void handle_hci_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
318 
319     UNUSED(packet_type); // ok: only hci events
320     UNUSED(channel);     // ok: there is no channel
321     UNUSED(size);        // ok: fixed format events read from HCI buffer
322 
323     static const uint8_t ancs_service_uuid[] =             {0x79,0x05,0xF4,0x31,0xB5,0xCE,0x4E,0x99,0xA4,0x0F,0x4B,0x1E,0x12,0x2D,0x00,0xD0};
324 
325     int connection_encrypted;
326 
327     // handle connect / disconncet events first
328     switch (hci_event_packet_get_type(packet)) {
329         case HCI_EVENT_LE_META:
330             switch (packet[2]) {
331                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
332                     gc_handle = hci_subevent_le_connection_complete_get_connection_handle(packet);
333                     log_info("Connection handle 0x%04x, request encryption", gc_handle);
334 
335                     // we need to be paired to enable notifications
336                     tc_state = TC_W4_ENCRYPTED_CONNECTION;
337                     ancs_service_found = false;
338                     sm_request_pairing(gc_handle);
339                     break;
340                 default:
341                     break;
342             }
343             return;
344 
345         case HCI_EVENT_ENCRYPTION_CHANGE:
346         case HCI_EVENT_ENCRYPTION_CHANGE_V2:
347             if (gc_handle != hci_event_encryption_change_get_connection_handle(packet)) return;
348             connection_encrypted = hci_event_encryption_change_get_encryption_enabled(packet);
349             log_info("Encryption state change: %u", connection_encrypted);
350             if (!connection_encrypted) return;
351             if (tc_state != TC_W4_ENCRYPTED_CONNECTION) return;
352 
353             // let's start
354             log_info("\nANCS Client - CONNECTED, discover ANCS service");
355             tc_state = TC_W4_SERVICE_RESULT;
356             gatt_client_discover_primary_services_by_uuid128(ancs_client_handle_gatt_client_event, gc_handle, ancs_service_uuid);
357             return;
358 
359         case HCI_EVENT_DISCONNECTION_COMPLETE:
360             if (hci_event_disconnection_complete_get_connection_handle(packet) != gc_handle) break;
361             if (tc_state == TC_SUBSCRIBED){
362                 notify_client_simple(ANCS_SUBEVENT_CLIENT_DISCONNECTED);
363             }
364             tc_state = TC_IDLE;
365             gc_handle = 0;
366             return;
367 
368         default:
369             break;
370     }
371 }
372 
373 void ancs_client_init(void){
374     hci_event_callback_registration.callback = &handle_hci_event;
375     hci_add_event_handler(&hci_event_callback_registration);
376 }
377 
378 // unit test only
379 #if defined __cplusplus
380 extern "C"
381 #endif
382 void ancs_client_set_invalid_parser_state(void);
383 void ancs_client_set_invalid_parser_state(void){
384     chunk_parser_state = (ancs_chunk_parser_state_t) 0x17;
385 }
386