xref: /btstack/example/panu_demo.c (revision 9975f1a3b6852778da384fc279d83b10eda1cae1)
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__ "panu_demo.c"
39 
40 /*
41  * panu_demo.c
42  * Author: Ole Reinhardt <[email protected]>
43  */
44 
45 /* EXAMPLE_START(panu_demo): PANU Demo
46  *
47  * @text This example implements both a PANU client and a server. In server mode, it
48  * sets up a BNEP server and registers a PANU SDP record and waits for incoming connections.
49  * In client mode, it connects to a remote device, does an SDP Query to identify the PANU
50  * service and initiates a BNEP connection.
51  *
52  * Note: currently supported only on Linux and Mac.
53  */
54 
55 #include <stdio.h>
56 
57 #include "btstack_config.h"
58 #include "btstack.h"
59 
60 static int record_id = -1;
61 static uint16_t bnep_l2cap_psm      = 0;
62 static uint32_t bnep_remote_uuid    = 0;
63 static uint16_t bnep_version        = 0;
64 static uint16_t bnep_cid            = 0;
65 
66 static uint16_t sdp_bnep_l2cap_psm      = 0;
67 static uint16_t sdp_bnep_version        = 0;
68 static uint32_t sdp_bnep_remote_uuid    = 0;
69 
70 static uint8_t   attribute_value[1000];
71 static const unsigned int attribute_value_buffer_size = sizeof(attribute_value);
72 
73 // MBP 2016
74 static const char * remote_addr_string = "F4-0F-24-3B-1B-E1";
75 // Wiko Sunny static const char * remote_addr_string = "A0:4C:5B:0F:B2:42";
76 
77 static bd_addr_t remote_addr;
78 
79 static btstack_packet_callback_registration_t hci_event_callback_registration;
80 
81 // outgoing network packet
82 static const uint8_t * network_buffer;
83 static uint16_t network_buffer_len;
84 
85 /* @section Main application configuration
86  *
87  * @text In the application configuration, L2CAP and BNEP are initialized and a BNEP service, for server mode,
88  * is registered, before the Bluetooth stack gets started, as shown in Listing PanuSetup.
89  */
90 
91 /* LISTING_START(PanuSetup): Panu setup */
92 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
93 static void handle_sdp_client_query_result(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
94 static void network_send_packet_callback(const uint8_t * packet, uint16_t size);
95 
96 static void panu_setup(void){
97 
98     // Initialize L2CAP
99     l2cap_init();
100 
101     // Initialise BNEP
102     bnep_init();
103 
104     // Minimum L2CAP MTU for bnep is 1691 bytes
105     bnep_register_service(packet_handler, BLUETOOTH_SERVICE_CLASS_PANU, 1691);
106 
107     // Initialize network interface
108     btstack_network_init(&network_send_packet_callback);
109 
110     // register for HCI events
111     hci_event_callback_registration.callback = &packet_handler;
112     hci_add_event_handler(&hci_event_callback_registration);
113 }
114 /* LISTING_END */
115 
116 // PANU client routines
117 static void get_string_from_data_element(uint8_t * element, uint16_t buffer_size, char * buffer_data){
118     de_size_t de_size = de_get_size_type(element);
119     int pos     = de_get_header_size(element);
120     int len = 0;
121     switch (de_size){
122         case DE_SIZE_VAR_8:
123             len = element[1];
124             break;
125         case DE_SIZE_VAR_16:
126             len = big_endian_read_16(element, 1);
127             break;
128         default:
129             break;
130     }
131     uint16_t bytes_to_copy = btstack_min(buffer_size-1,len);
132     memcpy(buffer_data, &element[pos], bytes_to_copy);
133     buffer_data[bytes_to_copy] ='\0';
134 }
135 
136 
137 /* @section SDP parser callback
138  *
139  * @text The SDP parsers retrieves the BNEP PAN UUID as explained in
140  * Section [on SDP BNEP Query example](#sec:sdpbnepqueryExample}.
141  */
142 static void handle_sdp_client_record_complete(void){
143 
144     printf("SDP BNEP Record complete\n");
145 
146     // accept first entry or if we foudn a NAP and only have a PANU yet
147     if ((bnep_remote_uuid == 0) || (sdp_bnep_remote_uuid == BLUETOOTH_SERVICE_CLASS_NAP && bnep_remote_uuid == BLUETOOTH_SERVICE_CLASS_PANU)){
148         bnep_l2cap_psm   = sdp_bnep_l2cap_psm;
149         bnep_remote_uuid = sdp_bnep_remote_uuid;
150         bnep_version     = sdp_bnep_version;
151     }
152 }
153 
154 static void handle_sdp_client_query_result(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
155 
156     UNUSED(packet_type);
157     UNUSED(channel);
158     UNUSED(size);
159 
160     des_iterator_t des_list_it;
161     des_iterator_t prot_it;
162     char str[20];
163 
164     switch (hci_event_packet_get_type(packet)){
165         case SDP_EVENT_QUERY_ATTRIBUTE_VALUE:
166             // Handle new SDP record
167             if (sdp_event_query_attribute_byte_get_record_id(packet) != record_id) {
168                 handle_sdp_client_record_complete();
169                 // next record started
170                 record_id = sdp_event_query_attribute_byte_get_record_id(packet);
171                 printf("SDP Record: Nr: %d\n", record_id);
172             }
173 
174             if (sdp_event_query_attribute_byte_get_attribute_length(packet) <= attribute_value_buffer_size) {
175                 attribute_value[sdp_event_query_attribute_byte_get_data_offset(packet)] = sdp_event_query_attribute_byte_get_data(packet);
176 
177                 if ((uint16_t)(sdp_event_query_attribute_byte_get_data_offset(packet)+1) == sdp_event_query_attribute_byte_get_attribute_length(packet)) {
178 
179                     switch(sdp_event_query_attribute_byte_get_attribute_id(packet)) {
180                         case BLUETOOTH_ATTRIBUTE_SERVICE_CLASS_ID_LIST:
181                             if (de_get_element_type(attribute_value) != DE_DES) break;
182                             for (des_iterator_init(&des_list_it, attribute_value); des_iterator_has_more(&des_list_it); des_iterator_next(&des_list_it)) {
183                                 uint8_t * element = des_iterator_get_element(&des_list_it);
184                                 if (de_get_element_type(element) != DE_UUID) continue;
185                                 uint32_t uuid = de_get_uuid32(element);
186                                 switch (uuid){
187                                     case BLUETOOTH_SERVICE_CLASS_PANU:
188                                     case BLUETOOTH_SERVICE_CLASS_NAP:
189                                     case BLUETOOTH_SERVICE_CLASS_GN:
190                                         printf("SDP Attribute 0x%04x: BNEP PAN protocol UUID: %04x\n", sdp_event_query_attribute_byte_get_attribute_id(packet), uuid);
191                                         sdp_bnep_remote_uuid = uuid;
192                                         break;
193                                     default:
194                                         break;
195                                 }
196                             }
197                             break;
198                         case 0x0100:
199                         case 0x0101:
200                             get_string_from_data_element(attribute_value, sizeof(str), str);
201                             printf("SDP Attribute: 0x%04x: %s\n", sdp_event_query_attribute_byte_get_attribute_id(packet), str);
202                             free(str);
203                             break;
204                         case BLUETOOTH_ATTRIBUTE_PROTOCOL_DESCRIPTOR_LIST: {
205                                 printf("SDP Attribute: 0x%04x\n", sdp_event_query_attribute_byte_get_attribute_id(packet));
206 
207                                 for (des_iterator_init(&des_list_it, attribute_value); des_iterator_has_more(&des_list_it); des_iterator_next(&des_list_it)) {
208                                     uint8_t       *des_element;
209                                     uint8_t       *element;
210                                     uint32_t       uuid;
211 
212                                     if (des_iterator_get_type(&des_list_it) != DE_DES) continue;
213 
214                                     des_element = des_iterator_get_element(&des_list_it);
215                                     des_iterator_init(&prot_it, des_element);
216                                     element = des_iterator_get_element(&prot_it);
217 
218                                     if (!element) continue;
219                                     if (de_get_element_type(element) != DE_UUID) continue;
220 
221                                     uuid = de_get_uuid32(element);
222                                     des_iterator_next(&prot_it);
223                                     switch (uuid){
224                                         case BLUETOOTH_PROTOCOL_L2CAP:
225                                             if (!des_iterator_has_more(&prot_it)) continue;
226                                             de_element_get_uint16(des_iterator_get_element(&prot_it), &sdp_bnep_l2cap_psm);
227                                             break;
228                                         case BLUETOOTH_PROTOCOL_BNEP:
229                                             if (!des_iterator_has_more(&prot_it)) continue;
230                                             de_element_get_uint16(des_iterator_get_element(&prot_it), &sdp_bnep_version);
231                                             break;
232                                         default:
233                                             break;
234                                     }
235                                 }
236                                 printf("Summary: uuid 0x%04x, l2cap_psm 0x%04x, bnep_version 0x%04x\n", sdp_bnep_remote_uuid, sdp_bnep_l2cap_psm, sdp_bnep_version);
237 
238                             }
239                             break;
240                         default:
241                             break;
242                     }
243                 }
244             } else {
245                 fprintf(stderr, "SDP attribute value buffer size exceeded: available %d, required %d\n", attribute_value_buffer_size, sdp_event_query_attribute_byte_get_attribute_length(packet));
246             }
247             break;
248 
249         case SDP_EVENT_QUERY_COMPLETE:
250             handle_sdp_client_record_complete();
251             fprintf(stderr, "General query done with status %d, bnep psm %04x.\n", sdp_event_query_complete_get_status(packet), bnep_l2cap_psm);
252             if (bnep_l2cap_psm){
253                 /* Create BNEP connection */
254                 bnep_connect(packet_handler, remote_addr, bnep_l2cap_psm, BLUETOOTH_SERVICE_CLASS_PANU, bnep_remote_uuid);
255             } else {
256                 fprintf(stderr, "No BNEP service found\n");
257             }
258 
259             break;
260     }
261 }
262 
263 /*
264  * @section Packet Handler
265  *
266  * @text The packet handler responds to various HCI Events.
267  */
268 
269 /* LISTING_START(packetHandler): Packet Handler */
270 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)
271 {
272 /* LISTING_PAUSE */
273     UNUSED(channel);
274 
275     uint8_t   event;
276     bd_addr_t event_addr;
277     bd_addr_t local_addr;
278     uint16_t  uuid_source;
279     uint16_t  uuid_dest;
280     uint16_t  mtu;
281 
282     /* LISTING_RESUME */
283     switch (packet_type) {
284 		case HCI_EVENT_PACKET:
285             event = hci_event_packet_get_type(packet);
286             switch (event) {
287                 /* @text When BTSTACK_EVENT_STATE with state HCI_STATE_WORKING
288                  * is received and the example is started in client mode, the remote SDP BNEP query is started.
289                  */
290                 case BTSTACK_EVENT_STATE:
291                     if (btstack_event_state_get_state(packet) == HCI_STATE_WORKING){
292                         printf("Start SDP BNEP query for remote PAN Network Access Point (NAP).\n");
293                         sdp_client_query_uuid16(&handle_sdp_client_query_result, remote_addr, BLUETOOTH_SERVICE_CLASS_NAP);
294                     }
295                     break;
296 
297                 /* LISTING_PAUSE */
298                 case HCI_EVENT_PIN_CODE_REQUEST:
299 					// inform about pin code request
300                     printf("Pin code request - using '0000'\n");
301                     hci_event_pin_code_request_get_bd_addr(packet, event_addr);
302                     gap_pin_code_response(event_addr, "0000");
303 					break;
304 
305                 case HCI_EVENT_USER_CONFIRMATION_REQUEST:
306                     // inform about user confirmation request
307                     printf("SSP User Confirmation Request with numeric value '%06u'\n", little_endian_read_32(packet, 8));
308                     printf("SSP User Confirmation Auto accept\n");
309                     break;
310 
311                 /* LISTING_RESUME */
312 
313                 /* @text BNEP_EVENT_CHANNEL_OPENED is received after a BNEP connection was established or
314                  * or when the connection fails. The status field returns the error code.
315                  *
316                  * The TAP network interface is then configured. A data source is set up and registered with the
317                  * run loop to receive Ethernet packets from the TAP interface.
318                  *
319                  * The event contains both the source and destination UUIDs, as well as the MTU for this connection and
320                  * the BNEP Channel ID, which is used for sending Ethernet packets over BNEP.
321                  */
322 				case BNEP_EVENT_CHANNEL_OPENED:
323                     if (bnep_event_channel_opened_get_status(packet)) {
324                         printf("BNEP channel open failed, status %02x\n", bnep_event_channel_opened_get_status(packet));
325                     } else {
326                         bnep_cid    = bnep_event_channel_opened_get_bnep_cid(packet);
327                         uuid_source = bnep_event_channel_opened_get_source_uuid(packet);
328                         uuid_dest   = bnep_event_channel_opened_get_destination_uuid(packet);
329                         mtu         = bnep_event_channel_opened_get_mtu(packet);
330                         memcpy(&event_addr, &packet[11], sizeof(bd_addr_t));
331                         printf("BNEP connection open succeeded to %s source UUID 0x%04x dest UUID: 0x%04x, max frame size %u\n", bd_addr_to_str(event_addr), uuid_source, uuid_dest, mtu);
332                         /* Setup network interface */
333                         gap_local_bd_addr(local_addr);
334                         btstack_network_up(local_addr);
335                         printf("Network Interface %s activated\n", btstack_network_get_name());
336                     }
337 					break;
338 
339                 /* @text If there is a timeout during the connection setup, BNEP_EVENT_CHANNEL_TIMEOUT will be received
340                  * and the BNEP connection  will be closed
341                  */
342                 case BNEP_EVENT_CHANNEL_TIMEOUT:
343                     printf("BNEP channel timeout! Channel will be closed\n");
344                     break;
345 
346                 /* @text BNEP_EVENT_CHANNEL_CLOSED is received when the connection gets closed.
347                  */
348                 case BNEP_EVENT_CHANNEL_CLOSED:
349                     printf("BNEP channel closed\n");
350                     btstack_network_down();
351                     break;
352 
353                 /* @text BNEP_EVENT_CAN_SEND_NOW indicates that a new packet can be send. This triggers the send of a
354                  * stored network packet. The tap datas source can be enabled again
355                  */
356                 case BNEP_EVENT_CAN_SEND_NOW:
357                     if (network_buffer_len > 0) {
358                         bnep_send(bnep_cid, (uint8_t*) network_buffer, network_buffer_len);
359                         network_buffer_len = 0;
360                         btstack_network_packet_sent();
361                     }
362                     break;
363 
364                 default:
365                     break;
366             }
367             break;
368 
369         /* @text Ethernet packets from the remote device are received in the packet handler with type BNEP_DATA_PACKET.
370          * It is forwarded to the TAP interface.
371          */
372         case BNEP_DATA_PACKET:
373             // Write out the ethernet frame to the network interface
374             btstack_network_process_packet(packet, size);
375             break;
376 
377         default:
378             break;
379     }
380 }
381 /* LISTING_END */
382 
383 /*
384  * @section Network packet handler
385  *
386  * @text A pointer to the network packet is stored and a BNEP_EVENT_CAN_SEND_NOW requested
387  */
388 
389 /* LISTING_START(networkPacketHandler): Network Packet Handler */
390 static void network_send_packet_callback(const uint8_t * packet, uint16_t size){
391     network_buffer = packet;
392     network_buffer_len = size;
393     bnep_request_can_send_now_event(bnep_cid);
394 }
395 /* LISTING_END */
396 
397 int btstack_main(int argc, const char * argv[]);
398 int btstack_main(int argc, const char * argv[]){
399 
400     (void)argc;
401     (void)argv;
402 
403     panu_setup();
404 
405     // parse human readable Bluetooth address
406     sscanf_bd_addr(remote_addr_string, remote_addr);
407 
408     // Turn on the device
409     hci_power_control(HCI_POWER_ON);
410     return 0;
411 }
412 
413 /* EXAMPLE_END */
414 /* -*- Mode: C; indent-tabs-mode: nil; c-basic-offset: 4; tab-width: 4 -*-  */
415 
416