xref: /btstack/example/spp_and_gatt_counter.c (revision 4930cef6e21e6da2d7571b9259c7f0fb8bed3d01)
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__ "spp_and_gatt_counter.c"
39 
40 // *****************************************************************************
41 /* EXAMPLE_START(spp_and_le_counter): Dual Mode - SPP and LE Counter
42  *
43  * @text The SPP and LE Counter example combines the Bluetooth Classic SPP Counter
44  * and the Bluetooth LE Counter into a single application.
45  *
46  * @text In this Section, we only point out the differences to the individual examples
47  * and how the stack is configured.
48  *
49  * @text Note: To test, please run the example, and then:
50  *    - for SPP pair from a remote device, and open the Virtual Serial Port,
51  *    - for LE use some GATT Explorer, e.g. LightBlue, BLExplr, to enable notifications.
52  */
53 // *****************************************************************************
54 
55 #include <stdint.h>
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <string.h>
59 #include <inttypes.h>
60 
61 #include "btstack.h"
62 #include "spp_and_gatt_counter.h"
63 
64 #define RFCOMM_SERVER_CHANNEL 1
65 #define HEARTBEAT_PERIOD_MS 1000
66 
67 static uint16_t  rfcomm_channel_id;
68 static uint8_t   spp_service_buffer[150];
69 static int       le_notification_enabled;
70 static hci_con_handle_t att_con_handle;
71 
72 // THE Couner
73 static btstack_timer_source_t heartbeat;
74 static int  counter = 0;
75 static char counter_string[30];
76 static int  counter_string_len;
77 
78 static btstack_packet_callback_registration_t hci_event_callback_registration;
79 
80 #ifdef ENABLE_GATT_OVER_CLASSIC
81 static uint8_t gatt_service_buffer[70];
82 #endif
83 
84 /*
85  * @section Advertisements
86  *
87  * @text The Flags attribute in the Advertisement Data indicates if a device is dual-mode or le-only.
88  */
89 /* LISTING_START(advertisements): Advertisement data: Flag 0x02 indicates dual-mode device */
90 const uint8_t adv_data[] = {
91     // Flags general discoverable
92     0x02, BLUETOOTH_DATA_TYPE_FLAGS, 0x02,
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 /* LISTING_END */
99 uint8_t adv_data_len = sizeof(adv_data);
100 
101 
102 /*
103  * @section Packet Handler
104  *
105  * @text The packet handler of the combined example is just the combination of the individual packet handlers.
106  */
107 
108 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
109     UNUSED(channel);
110 
111     bd_addr_t event_addr;
112     uint8_t   rfcomm_channel_nr;
113     uint16_t  mtu;
114     int i;
115 
116 	switch (packet_type) {
117 		case HCI_EVENT_PACKET:
118 			switch (hci_event_packet_get_type(packet)) {
119                 case HCI_EVENT_PIN_CODE_REQUEST:
120                     // inform about pin code request
121                     printf("Pin code request - using '0000'\n");
122                     hci_event_pin_code_request_get_bd_addr(packet, event_addr);
123                     gap_pin_code_response(event_addr, "0000");
124                     break;
125 
126                 case HCI_EVENT_USER_CONFIRMATION_REQUEST:
127                     // inform about user confirmation request
128                     printf("SSP User Confirmation Request with numeric value '%06"PRIu32"'\n", little_endian_read_32(packet, 8));
129                     printf("SSP User Confirmation Auto accept\n");
130                     break;
131 
132                 case HCI_EVENT_DISCONNECTION_COMPLETE:
133                     le_notification_enabled = 0;
134                     break;
135 
136                 case ATT_EVENT_CAN_SEND_NOW:
137                     att_server_notify(att_con_handle, ATT_CHARACTERISTIC_0000FF11_0000_1000_8000_00805F9B34FB_01_VALUE_HANDLE, (uint8_t*) counter_string, counter_string_len);
138                     break;
139 
140                 case RFCOMM_EVENT_INCOMING_CONNECTION:
141 					// data: event (8), len(8), address(48), channel (8), rfcomm_cid (16)
142                     rfcomm_event_incoming_connection_get_bd_addr(packet, event_addr);
143                     rfcomm_channel_nr = rfcomm_event_incoming_connection_get_server_channel(packet);
144                     rfcomm_channel_id = rfcomm_event_incoming_connection_get_rfcomm_cid(packet);
145                     printf("RFCOMM channel %u requested for %s\n", rfcomm_channel_nr, bd_addr_to_str(event_addr));
146                     rfcomm_accept_connection(rfcomm_channel_id);
147 					break;
148 
149 				case RFCOMM_EVENT_CHANNEL_OPENED:
150 					// data: event(8), len(8), status (8), address (48), server channel(8), rfcomm_cid(16), max frame size(16)
151 					if (rfcomm_event_channel_opened_get_status(packet)) {
152                         printf("RFCOMM channel open failed, status %u\n", rfcomm_event_channel_opened_get_status(packet));
153                     } else {
154                         rfcomm_channel_id = rfcomm_event_channel_opened_get_rfcomm_cid(packet);
155                         mtu = rfcomm_event_channel_opened_get_max_frame_size(packet);
156                         printf("RFCOMM channel open succeeded. New RFCOMM Channel ID %u, max frame size %u\n", rfcomm_channel_id, mtu);
157                     }
158 					break;
159 
160                 case RFCOMM_EVENT_CAN_SEND_NOW:
161                     rfcomm_send(rfcomm_channel_id, (uint8_t*) counter_string, counter_string_len);
162                     break;
163 
164                 case RFCOMM_EVENT_CHANNEL_CLOSED:
165                     printf("RFCOMM channel closed\n");
166                     rfcomm_channel_id = 0;
167                     break;
168 
169                 default:
170                     break;
171 			}
172             break;
173 
174         case RFCOMM_DATA_PACKET:
175             printf("RCV: '");
176             for (i=0;i<size;i++){
177                 putchar(packet[i]);
178             }
179             printf("'\n");
180             break;
181 
182         default:
183             break;
184 	}
185 }
186 
187 // ATT Client Read Callback for Dynamic Data
188 // - if buffer == NULL, don't copy data, just return size of value
189 // - if buffer != NULL, copy data and return number bytes copied
190 // @param offset defines start of attribute value
191 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){
192     UNUSED(con_handle);
193 
194     if (att_handle == ATT_CHARACTERISTIC_0000FF11_0000_1000_8000_00805F9B34FB_01_VALUE_HANDLE){
195         return att_read_callback_handle_blob((const uint8_t *)counter_string, counter_string_len, offset, buffer, buffer_size);
196     }
197     return 0;
198 }
199 
200 // write requests
201 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){
202     // ignore cancel sent for new connections
203     if (transaction_mode == ATT_TRANSACTION_MODE_CANCEL) return 0;
204     // find characteristic for handle
205     switch (att_handle){
206         case ATT_CHARACTERISTIC_0000FF11_0000_1000_8000_00805F9B34FB_01_CLIENT_CONFIGURATION_HANDLE:
207             le_notification_enabled = little_endian_read_16(buffer, 0) == GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_NOTIFICATION;
208             att_con_handle = con_handle;
209             return 0;
210         case ATT_CHARACTERISTIC_0000FF11_0000_1000_8000_00805F9B34FB_01_VALUE_HANDLE:
211             printf("Write on test characteristic: ");
212             printf_hexdump(buffer, buffer_size);
213             return 0;
214         default:
215             printf("WRITE Callback, handle %04x, mode %u, offset %u, data: ", con_handle, transaction_mode, offset);
216             printf_hexdump(buffer, buffer_size);
217             return 0;
218     }
219 }
220 
221 static void beat(void){
222     counter++;
223     counter_string_len = snprintf(counter_string, sizeof(counter_string), "BTstack counter %04u", counter);
224     puts(counter_string);
225 }
226 
227 /*
228  * @section Heartbeat Handler
229  *
230  * @text Similar to the packet handler, the heartbeat handler is the combination of the individual ones.
231  * After updating the counter, it requests an ATT_EVENT_CAN_SEND_NOW and/or RFCOMM_EVENT_CAN_SEND_NOW
232  */
233 
234  /* LISTING_START(heartbeat): Combined Heartbeat handler */
235 static void heartbeat_handler(struct btstack_timer_source *ts){
236 
237     if (rfcomm_channel_id || le_notification_enabled) {
238         beat();
239     }
240 
241     if (rfcomm_channel_id){
242         rfcomm_request_can_send_now_event(rfcomm_channel_id);
243     }
244 
245     if (le_notification_enabled) {
246         att_server_request_can_send_now_event(att_con_handle);
247     }
248 
249     btstack_run_loop_set_timer(ts, HEARTBEAT_PERIOD_MS);
250     btstack_run_loop_add_timer(ts);
251 }
252 /* LISTING_END */
253 
254 /*
255  * @section Main Application Setup
256  *
257  * @text As with the packet and the heartbeat handlers, the combined app setup contains the code from the individual example setups.
258  */
259 
260 /* LISTING_START(MainConfiguration): Init L2CAP RFCOMM SDO SM ATT Server and start heartbeat timer */
261 int btstack_main(void);
262 int btstack_main(void)
263 {
264     l2cap_init();
265 
266     rfcomm_init();
267     rfcomm_register_service(packet_handler, RFCOMM_SERVER_CHANNEL, 0xffff);
268 
269     // init SDP, create record for SPP and register with SDP
270     sdp_init();
271     memset(spp_service_buffer, 0, sizeof(spp_service_buffer));
272     spp_create_sdp_record(spp_service_buffer, 0x10001, RFCOMM_SERVER_CHANNEL, "SPP Counter");
273     sdp_register_service(spp_service_buffer);
274     printf("SDP service record size: %u\n", de_get_len(spp_service_buffer));
275 
276 #ifdef ENABLE_GATT_OVER_CLASSIC
277     // init SDP, create record for GATT and register with SDP
278     memset(gatt_service_buffer, 0, sizeof(gatt_service_buffer));
279     gatt_create_sdp_record(gatt_service_buffer, 0x10001, ATT_SERVICE_GATT_SERVICE_START_HANDLE, ATT_SERVICE_GATT_SERVICE_END_HANDLE);
280     sdp_register_service(gatt_service_buffer);
281     printf("SDP service record size: %u\n", de_get_len(gatt_service_buffer));
282 #endif
283 
284     gap_set_local_name("SPP and LE Counter 00:00:00:00:00:00");
285     gap_ssp_set_io_capability(SSP_IO_CAPABILITY_DISPLAY_YES_NO);
286     gap_discoverable_control(1);
287 
288     // setup SM: Display only
289     sm_init();
290 
291     // setup ATT server
292     att_server_init(profile_data, att_read_callback, att_write_callback);
293 
294     // register for HCI events
295     hci_event_callback_registration.callback = &packet_handler;
296     hci_add_event_handler(&hci_event_callback_registration);
297 
298     // register for ATT events
299     att_server_register_packet_handler(packet_handler);
300 
301     // setup advertisements
302     uint16_t adv_int_min = 0x0030;
303     uint16_t adv_int_max = 0x0030;
304     uint8_t adv_type = 0;
305     bd_addr_t null_addr;
306     memset(null_addr, 0, 6);
307     gap_advertisements_set_params(adv_int_min, adv_int_max, adv_type, 0, null_addr, 0x07, 0x00);
308     gap_advertisements_set_data(adv_data_len, (uint8_t*) adv_data);
309     gap_advertisements_enable(1);
310 
311     // set one-shot timer
312     heartbeat.process = &heartbeat_handler;
313     btstack_run_loop_set_timer(&heartbeat, HEARTBEAT_PERIOD_MS);
314     btstack_run_loop_add_timer(&heartbeat);
315 
316     // beat once
317     beat();
318 
319     // turn on!
320 	hci_power_control(HCI_POWER_ON);
321 
322     return 0;
323 }
324 /* LISTING_END */
325 /* EXAMPLE_END */
326