xref: /btstack/example/gatt_counter.c (revision f11fd9a990fedbf11b7c70e38b9da44019506e13)
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 MATTHIAS
24  * RINGWALD 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 le device db
112     le_device_db_init();
113 
114     // setup SM: Display only
115     sm_init();
116 
117 #ifdef ENABLE_GATT_OVER_CLASSIC
118     // init SDP, create record for GATT and register with SDP
119     sdp_init();
120     memset(gatt_service_buffer, 0, sizeof(gatt_service_buffer));
121     gatt_create_sdp_record(gatt_service_buffer, 0x10001, ATT_SERVICE_GATT_SERVICE_START_HANDLE, ATT_SERVICE_GATT_SERVICE_END_HANDLE);
122     sdp_register_service(gatt_service_buffer);
123     printf("SDP service record size: %u\n", de_get_len(gatt_service_buffer));
124 
125     // configure Classic GAP
126     gap_set_local_name("GATT Counter BR/EDR 00:00:00:00:00:00");
127     gap_ssp_set_io_capability(SSP_IO_CAPABILITY_DISPLAY_YES_NO);
128     gap_discoverable_control(1);
129 #endif
130 
131     // setup ATT server
132     att_server_init(profile_data, att_read_callback, att_write_callback);
133 
134     // setup battery service
135     battery_service_server_init(battery);
136 
137     // setup advertisements
138     uint16_t adv_int_min = 0x0030;
139     uint16_t adv_int_max = 0x0030;
140     uint8_t adv_type = 0;
141     bd_addr_t null_addr;
142     memset(null_addr, 0, 6);
143     gap_advertisements_set_params(adv_int_min, adv_int_max, adv_type, 0, null_addr, 0x07, 0x00);
144     gap_advertisements_set_data(adv_data_len, (uint8_t*) adv_data);
145     gap_advertisements_enable(1);
146 
147     // register for HCI events
148     hci_event_callback_registration.callback = &packet_handler;
149     hci_add_event_handler(&hci_event_callback_registration);
150 
151     // register for ATT event
152     att_server_register_packet_handler(packet_handler);
153 
154     // set one-shot timer
155     heartbeat.process = &heartbeat_handler;
156     btstack_run_loop_set_timer(&heartbeat, HEARTBEAT_PERIOD_MS);
157     btstack_run_loop_add_timer(&heartbeat);
158 
159     // beat once
160     beat();
161 }
162 /* LISTING_END */
163 
164 /*
165  * @section Heartbeat Handler
166  *
167  * @text The heartbeat handler updates the value of the single Characteristic provided in this example,
168  * and request a ATT_EVENT_CAN_SEND_NOW to send a notification if enabled see Listing heartbeat.
169  */
170 
171  /* LISTING_START(heartbeat): Hearbeat Handler */
172 static int  counter = 0;
173 static char counter_string[30];
174 static int  counter_string_len;
175 
176 static void beat(void){
177     counter++;
178     counter_string_len = sprintf(counter_string, "BTstack counter %04u", counter);
179     puts(counter_string);
180 }
181 
182 static void heartbeat_handler(struct btstack_timer_source *ts){
183     if (le_notification_enabled) {
184         beat();
185         att_server_request_can_send_now_event(con_handle);
186     }
187 
188     // simulate battery drain
189     battery--;
190     if (battery < 50) {
191         battery = 100;
192     }
193     battery_service_server_set_battery_value(battery);
194 
195     btstack_run_loop_set_timer(ts, HEARTBEAT_PERIOD_MS);
196     btstack_run_loop_add_timer(ts);
197 }
198 /* LISTING_END */
199 
200 /*
201  * @section Packet Handler
202  *
203  * @text The packet handler is used to:
204  *        - stop the counter after a disconnect
205  *        - send a notification when the requested ATT_EVENT_CAN_SEND_NOW is received
206  */
207 
208 /* LISTING_START(packetHandler): Packet Handler */
209 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
210     UNUSED(channel);
211     UNUSED(size);
212 
213     if (packet_type != HCI_EVENT_PACKET) return;
214 
215     switch (hci_event_packet_get_type(packet)) {
216         case HCI_EVENT_DISCONNECTION_COMPLETE:
217             le_notification_enabled = 0;
218             break;
219         case ATT_EVENT_CAN_SEND_NOW:
220             att_server_notify(con_handle, ATT_CHARACTERISTIC_0000FF11_0000_1000_8000_00805F9B34FB_01_VALUE_HANDLE, (uint8_t*) counter_string, counter_string_len);
221             break;
222         default:
223             break;
224     }
225 }
226 
227 /* LISTING_END */
228 
229 /*
230  * @section ATT Read
231  *
232  * @text The ATT Server handles all reads to constant data. For dynamic data like the custom characteristic, the registered
233  * att_read_callback is called. To handle long characteristics and long reads, the att_read_callback is first called
234  * with buffer == NULL, to request the total value length. Then it will be called again requesting a chunk of the value.
235  * See Listing attRead.
236  */
237 
238 /* LISTING_START(attRead): ATT Read */
239 
240 // ATT Client Read Callback for Dynamic Data
241 // - if buffer == NULL, don't copy data, just return size of value
242 // - if buffer != NULL, copy data and return number bytes copied
243 // @param offset defines start of attribute value
244 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){
245     UNUSED(connection_handle);
246 
247     if (att_handle == ATT_CHARACTERISTIC_0000FF11_0000_1000_8000_00805F9B34FB_01_VALUE_HANDLE){
248         return att_read_callback_handle_blob((const uint8_t *)counter_string, counter_string_len, offset, buffer, buffer_size);
249     }
250     return 0;
251 }
252 /* LISTING_END */
253 
254 
255 /*
256  * @section ATT Write
257  *
258  * @text The only valid ATT write in this example is to the Client Characteristic Configuration, which configures notification
259  * and indication. If the ATT handle matches the client configuration handle, the new configuration value is stored and used
260  * in the heartbeat handler to decide if a new value should be sent. 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     UNUSED(transaction_mode);
266     UNUSED(offset);
267     UNUSED(buffer_size);
268 
269     if (att_handle != ATT_CHARACTERISTIC_0000FF11_0000_1000_8000_00805F9B34FB_01_CLIENT_CONFIGURATION_HANDLE) return 0;
270     le_notification_enabled = little_endian_read_16(buffer, 0) == GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_NOTIFICATION;
271     con_handle = connection_handle;
272     return 0;
273 }
274 /* LISTING_END */
275 
276 int btstack_main(void);
277 int btstack_main(void)
278 {
279     le_counter_setup();
280 
281     // turn on!
282 	hci_power_control(HCI_POWER_ON);
283 
284     return 0;
285 }
286 /* EXAMPLE_END */
287