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