xref: /btstack/example/gatt_counter.c (revision db88441f671cf9b797d1a7638cc0e38d13db6ac0)
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__ "gatt_counter.c"
39 
40 // *****************************************************************************
41 /* EXAMPLE_START(gatt_counter): GATT Server - Heartbeat Counter over GATT
42  *
43  * @text All newer operating systems provide GATT Client functionality.
44  * The LE Counter examples demonstrates how to specify a minimal GATT Database
45  * with a custom GATT Service and a custom Characteristic that sends periodic
46  * notifications.
47  */
48  // *****************************************************************************
49 
50 #include <stdint.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.h>
54 
55 #include "gatt_counter.h"
56 #include "btstack.h"
57 #include "ble/gatt-service/battery_service_server.h"
58 
59 #define HEARTBEAT_PERIOD_MS 1000
60 
61 /* @section Main Application Setup
62  *
63  * @text Listing MainConfiguration shows main application code.
64  * It initializes L2CAP, the Security Manager and configures the ATT Server with the pre-compiled
65  * ATT Database generated from $le_counter.gatt$.
66  * Additionally, it enables the Battery Service Server with the current battery level.
67  * Finally, it configures the advertisements
68  * and the heartbeat handler and boots the Bluetooth stack.
69  * In this example, the Advertisement contains the Flags attribute and the device name.
70  * The flag 0x06 indicates: LE General Discoverable Mode and BR/EDR not supported.
71  */
72 
73 /* LISTING_START(MainConfiguration): Init L2CAP SM ATT Server and start heartbeat timer */
74 static int  le_notification_enabled;
75 static btstack_timer_source_t heartbeat;
76 static btstack_packet_callback_registration_t hci_event_callback_registration;
77 static hci_con_handle_t con_handle;
78 static uint8_t battery = 100;
79 
80 #ifdef ENABLE_GATT_OVER_CLASSIC
81 static uint8_t gatt_service_buffer[70];
82 #endif
83 
84 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
85 static uint16_t att_read_callback(hci_con_handle_t con_handle, uint16_t att_handle, uint16_t offset, uint8_t * buffer, uint16_t buffer_size);
86 static int att_write_callback(hci_con_handle_t con_handle, uint16_t att_handle, uint16_t transaction_mode, uint16_t offset, uint8_t *buffer, uint16_t buffer_size);
87 static void  heartbeat_handler(struct btstack_timer_source *ts);
88 static void beat(void);
89 
90 // Flags general discoverable, BR/EDR supported (== not supported flag not set) when ENABLE_GATT_OVER_CLASSIC is enabled
91 #ifdef ENABLE_GATT_OVER_CLASSIC
92 #define APP_AD_FLAGS 0x02
93 #else
94 #define APP_AD_FLAGS 0x06
95 #endif
96 
97 const uint8_t adv_data[] = {
98     // Flags general discoverable
99     0x02, BLUETOOTH_DATA_TYPE_FLAGS, APP_AD_FLAGS,
100     // Name
101     0x0b, BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME, 'L', 'E', ' ', 'C', 'o', 'u', 'n', 't', 'e', 'r',
102     // Incomplete List of 16-bit Service Class UUIDs -- FF10 - only valid for testing!
103     0x03, BLUETOOTH_DATA_TYPE_INCOMPLETE_LIST_OF_16_BIT_SERVICE_CLASS_UUIDS, 0x10, 0xff,
104 };
105 const uint8_t adv_data_len = sizeof(adv_data);
106 
107 static void le_counter_setup(void){
108 
109     l2cap_init();
110 
111     // setup SM: Display only
112     sm_init();
113 
114 #ifdef ENABLE_GATT_OVER_CLASSIC
115     // init SDP, create record for GATT and register with SDP
116     sdp_init();
117     memset(gatt_service_buffer, 0, sizeof(gatt_service_buffer));
118     gatt_create_sdp_record(gatt_service_buffer, sdp_create_service_record_handle(), ATT_SERVICE_GATT_SERVICE_START_HANDLE, ATT_SERVICE_GATT_SERVICE_END_HANDLE);
119     btstack_assert(de_get_len( gatt_service_buffer) <= sizeof(gatt_service_buffer));
120     sdp_register_service(gatt_service_buffer);
121 
122     // configure Classic GAP
123     gap_set_local_name("GATT Counter BR/EDR 00:00:00:00:00:00");
124     gap_ssp_set_io_capability(SSP_IO_CAPABILITY_DISPLAY_YES_NO);
125     gap_discoverable_control(1);
126 #endif
127 
128     // setup ATT server
129     att_server_init(profile_data, att_read_callback, att_write_callback);
130 
131     // setup battery service
132     battery_service_server_init(battery);
133 
134     // setup advertisements
135     uint16_t adv_int_min = 0x0030;
136     uint16_t adv_int_max = 0x0030;
137     uint8_t adv_type = 0;
138     bd_addr_t null_addr;
139     memset(null_addr, 0, 6);
140     gap_advertisements_set_params(adv_int_min, adv_int_max, adv_type, 0, null_addr, 0x07, 0x00);
141     gap_advertisements_set_data(adv_data_len, (uint8_t*) adv_data);
142     gap_advertisements_enable(1);
143 
144     // register for HCI events
145     hci_event_callback_registration.callback = &packet_handler;
146     hci_add_event_handler(&hci_event_callback_registration);
147 
148     // register for ATT event
149     att_server_register_packet_handler(packet_handler);
150 
151     // set one-shot timer
152     heartbeat.process = &heartbeat_handler;
153     btstack_run_loop_set_timer(&heartbeat, HEARTBEAT_PERIOD_MS);
154     btstack_run_loop_add_timer(&heartbeat);
155 
156     // beat once
157     beat();
158 }
159 /* LISTING_END */
160 
161 /*
162  * @section Heartbeat Handler
163  *
164  * @text The heartbeat handler updates the value of the single Characteristic provided in this example,
165  * and request a ATT_EVENT_CAN_SEND_NOW to send a notification if enabled see Listing heartbeat.
166  */
167 
168  /* LISTING_START(heartbeat): Hearbeat Handler */
169 static int  counter = 0;
170 static char counter_string[30];
171 static int  counter_string_len;
172 
173 static void beat(void){
174     counter++;
175     counter_string_len = snprintf(counter_string, sizeof(counter_string), "BTstack counter %04u", counter);
176     puts(counter_string);
177 }
178 
179 static void heartbeat_handler(struct btstack_timer_source *ts){
180     if (le_notification_enabled) {
181         beat();
182         att_server_request_can_send_now_event(con_handle);
183     }
184 
185     // simulate battery drain
186     battery--;
187     if (battery < 50) {
188         battery = 100;
189     }
190     battery_service_server_set_battery_value(battery);
191 
192     btstack_run_loop_set_timer(ts, HEARTBEAT_PERIOD_MS);
193     btstack_run_loop_add_timer(ts);
194 }
195 /* LISTING_END */
196 
197 /*
198  * @section Packet Handler
199  *
200  * @text The packet handler is used to:
201  *        - stop the counter after a disconnect
202  *        - send a notification when the requested ATT_EVENT_CAN_SEND_NOW is received
203  */
204 
205 /* LISTING_START(packetHandler): Packet Handler */
206 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
207     UNUSED(channel);
208     UNUSED(size);
209 
210     if (packet_type != HCI_EVENT_PACKET) return;
211 
212     switch (hci_event_packet_get_type(packet)) {
213         case HCI_EVENT_DISCONNECTION_COMPLETE:
214             le_notification_enabled = 0;
215             break;
216         case ATT_EVENT_CAN_SEND_NOW:
217             att_server_notify(con_handle, ATT_CHARACTERISTIC_0000FF11_0000_1000_8000_00805F9B34FB_01_VALUE_HANDLE, (uint8_t*) counter_string, counter_string_len);
218             break;
219         default:
220             break;
221     }
222 }
223 
224 /* LISTING_END */
225 
226 /*
227  * @section ATT Read
228  *
229  * @text The ATT Server handles all reads to constant data. For dynamic data like the custom characteristic, the registered
230  * att_read_callback is called. To handle long characteristics and long reads, the att_read_callback is first called
231  * with buffer == NULL, to request the total value length. Then it will be called again requesting a chunk of the value.
232  * See Listing attRead.
233  */
234 
235 /* LISTING_START(attRead): ATT Read */
236 
237 // ATT Client Read Callback for Dynamic Data
238 // - if buffer == NULL, don't copy data, just return size of value
239 // - if buffer != NULL, copy data and return number bytes copied
240 // @param offset defines start of attribute value
241 static uint16_t att_read_callback(hci_con_handle_t connection_handle, uint16_t att_handle, uint16_t offset, uint8_t * buffer, uint16_t buffer_size){
242     UNUSED(connection_handle);
243 
244     if (att_handle == ATT_CHARACTERISTIC_0000FF11_0000_1000_8000_00805F9B34FB_01_VALUE_HANDLE){
245         return att_read_callback_handle_blob((const uint8_t *)counter_string, counter_string_len, offset, buffer, buffer_size);
246     }
247     return 0;
248 }
249 /* LISTING_END */
250 
251 
252 /*
253  * @section ATT Write
254  *
255  * @text The only valid ATT writes in this example are to the Client Characteristic Configuration, which configures notification
256  * and indication and to the the Characteristic Value.
257  * If the ATT handle matches the client configuration handle, the new configuration value is stored and used
258  * in the heartbeat handler to decide if a new value should be sent.
259  * If the ATT handle matches the characteristic value handle, we print the write as hexdump
260  * See Listing attWrite.
261  */
262 
263 /* LISTING_START(attWrite): ATT Write */
264 static int att_write_callback(hci_con_handle_t connection_handle, uint16_t att_handle, uint16_t transaction_mode, uint16_t offset, uint8_t *buffer, uint16_t buffer_size){
265     switch (att_handle){
266         case ATT_CHARACTERISTIC_0000FF11_0000_1000_8000_00805F9B34FB_01_CLIENT_CONFIGURATION_HANDLE:
267             le_notification_enabled = little_endian_read_16(buffer, 0) == GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_NOTIFICATION;
268             con_handle = connection_handle;
269             break;
270         case ATT_CHARACTERISTIC_0000FF11_0000_1000_8000_00805F9B34FB_01_VALUE_HANDLE:
271             printf("Write: transaction mode %u, offset %u, data (%u bytes): ", transaction_mode, offset, buffer_size);
272             printf_hexdump(buffer, buffer_size);
273             break;
274         default:
275             break;
276     }
277     return 0;
278 }
279 /* LISTING_END */
280 
281 int btstack_main(void);
282 int btstack_main(void)
283 {
284     le_counter_setup();
285 
286     // turn on!
287 	hci_power_control(HCI_POWER_ON);
288 
289     return 0;
290 }
291 /* EXAMPLE_END */
292