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