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