xref: /btstack/example/spp_counter.c (revision d39ea275a9252bb29596189a0f4f47579c7409b8)
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_counter.c"
39 
40 // *****************************************************************************
41 /* EXAMPLE_START(spp_counter): SPP Server - Heartbeat Counter over RFCOMM
42  *
43  * @text The Serial port profile (SPP) is widely used as it provides a serial
44  * port over Bluetooth. The SPP counter example demonstrates how to setup an SPP
45  * service, and provide a periodic timer over RFCOMM.
46  *
47  * @text Note: To test, please run the spp_counter example, and then pair from
48  * a remote device, and open the Virtual Serial Port.
49  */
50 // *****************************************************************************
51 
52 #include <inttypes.h>
53 #include <stdint.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <string.h>
57 
58 #include "btstack.h"
59 
60 #define RFCOMM_SERVER_CHANNEL 1
61 #define HEARTBEAT_PERIOD_MS 1000
62 
63 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
64 
65 static uint16_t rfcomm_channel_id;
66 static uint8_t  spp_service_buffer[150];
67 static btstack_packet_callback_registration_t hci_event_callback_registration;
68 
69 
70 /* @section SPP Service Setup
71  *s
72  * @text To provide an SPP service, the L2CAP, RFCOMM, and SDP protocol layers
73  * are required. After setting up an RFCOMM service with channel nubmer
74  * RFCOMM_SERVER_CHANNEL, an SDP record is created and registered with the SDP server.
75  * Example code for SPP service setup is
76  * provided in Listing SPPSetup. The SDP record created by function
77  * spp_create_sdp_record consists of a basic SPP definition that uses the provided
78  * RFCOMM channel ID and service name. For more details, please have a look at it
79  * in \path{src/sdp_util.c}.
80  * The SDP record is created on the fly in RAM and is deterministic.
81  * To preserve valuable RAM, the result could be stored as constant data inside the ROM.
82  */
83 
84 /* LISTING_START(SPPSetup): SPP service setup */
85 static void spp_service_setup(void){
86 
87     // register for HCI events
88     hci_event_callback_registration.callback = &packet_handler;
89     hci_add_event_handler(&hci_event_callback_registration);
90 
91     l2cap_init();
92 
93 #ifdef ENABLE_BLE
94     // Initialize LE Security Manager. Needed for cross-transport key derivation
95     sm_init();
96 #endif
97 
98     rfcomm_init();
99     rfcomm_register_service(packet_handler, RFCOMM_SERVER_CHANNEL, 0xffff);  // reserved channel, mtu limited by l2cap
100 
101     // init SDP, create record for SPP and register with SDP
102     sdp_init();
103     memset(spp_service_buffer, 0, sizeof(spp_service_buffer));
104     spp_create_sdp_record(spp_service_buffer, 0x10001, RFCOMM_SERVER_CHANNEL, "SPP Counter");
105     sdp_register_service(spp_service_buffer);
106     printf("SDP service record size: %u\n", de_get_len(spp_service_buffer));
107 }
108 /* LISTING_END */
109 
110 /* @section Periodic Timer Setup
111  *
112  * @text The heartbeat handler increases the real counter every second,
113  * and sends a text string with the counter value, as shown in Listing PeriodicCounter.
114  */
115 
116 /* LISTING_START(PeriodicCounter): Periodic Counter */
117 static btstack_timer_source_t heartbeat;
118 static char lineBuffer[30];
119 static void  heartbeat_handler(struct btstack_timer_source *ts){
120     static int counter = 0;
121 
122     if (rfcomm_channel_id){
123         snprintf(lineBuffer, sizeof(lineBuffer), "BTstack counter %04u\n", ++counter);
124         printf("%s", lineBuffer);
125 
126         rfcomm_request_can_send_now_event(rfcomm_channel_id);
127     }
128 
129     btstack_run_loop_set_timer(ts, HEARTBEAT_PERIOD_MS);
130     btstack_run_loop_add_timer(ts);
131 }
132 
133 static void one_shot_timer_setup(void){
134     // set one-shot timer
135     heartbeat.process = &heartbeat_handler;
136     btstack_run_loop_set_timer(&heartbeat, HEARTBEAT_PERIOD_MS);
137     btstack_run_loop_add_timer(&heartbeat);
138 }
139 /* LISTING_END */
140 
141 
142 /* @section Bluetooth Logic
143  * @text The Bluetooth logic is implemented within the
144  * packet handler, see Listing SppServerPacketHandler. In this example,
145  * the following events are passed sequentially:
146  * - BTSTACK_EVENT_STATE,
147  * - HCI_EVENT_PIN_CODE_REQUEST (Standard pairing) or
148  * - HCI_EVENT_USER_CONFIRMATION_REQUEST (Secure Simple Pairing),
149  * - RFCOMM_EVENT_INCOMING_CONNECTION,
150  * - RFCOMM_EVENT_CHANNEL_OPENED,
151 * - RFCOMM_EVETN_CAN_SEND_NOW, and
152  * - RFCOMM_EVENT_CHANNEL_CLOSED
153  */
154 
155 /* @text Upon receiving HCI_EVENT_PIN_CODE_REQUEST event, we need to handle
156  * authentication. Here, we use a fixed PIN code "0000".
157  *
158  * When HCI_EVENT_USER_CONFIRMATION_REQUEST is received, the user will be
159  * asked to accept the pairing request. If the IO capability is set to
160  * SSP_IO_CAPABILITY_DISPLAY_YES_NO, the request will be automatically accepted.
161  *
162  * The RFCOMM_EVENT_INCOMING_CONNECTION event indicates an incoming connection.
163  * Here, the connection is accepted. More logic is need, if you want to handle connections
164  * from multiple clients. The incoming RFCOMM connection event contains the RFCOMM
165  * channel number used during the SPP setup phase and the newly assigned RFCOMM
166  * channel ID that is used by all BTstack commands and events.
167  *
168  * If RFCOMM_EVENT_CHANNEL_OPENED event returns status greater then 0,
169  * then the channel establishment has failed (rare case, e.g., client crashes).
170  * On successful connection, the RFCOMM channel ID and MTU for this
171  * channel are made available to the heartbeat counter. After opening the RFCOMM channel,
172  * the communication between client and the application
173  * takes place. In this example, the timer handler increases the real counter every
174  * second.
175  *
176  * RFCOMM_EVENT_CAN_SEND_NOW indicates that it's possible to send an RFCOMM packet
177  * on the rfcomm_cid that is include
178 
179  */
180 
181 /* LISTING_START(SppServerPacketHandler): SPP Server - Heartbeat Counter over RFCOMM */
182 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
183     UNUSED(channel);
184 
185 /* LISTING_PAUSE */
186     bd_addr_t event_addr;
187     uint8_t   rfcomm_channel_nr;
188     uint16_t  mtu;
189     int i;
190 
191     switch (packet_type) {
192         case HCI_EVENT_PACKET:
193             switch (hci_event_packet_get_type(packet)) {
194 /* LISTING_RESUME */
195                 case HCI_EVENT_PIN_CODE_REQUEST:
196                     // inform about pin code request
197                     printf("Pin code request - using '0000'\n");
198                     hci_event_pin_code_request_get_bd_addr(packet, event_addr);
199                     gap_pin_code_response(event_addr, "0000");
200                     break;
201 
202                 case HCI_EVENT_USER_CONFIRMATION_REQUEST:
203                     // ssp: inform about user confirmation request
204                     printf("SSP User Confirmation Request with numeric value '%06"PRIu32"'\n", little_endian_read_32(packet, 8));
205                     printf("SSP User Confirmation Auto accept\n");
206                     break;
207 
208                 case RFCOMM_EVENT_INCOMING_CONNECTION:
209                     // data: event (8), len(8), address(48), channel (8), rfcomm_cid (16)
210                     rfcomm_event_incoming_connection_get_bd_addr(packet, event_addr);
211                     rfcomm_channel_nr = rfcomm_event_incoming_connection_get_server_channel(packet);
212                     rfcomm_channel_id = rfcomm_event_incoming_connection_get_rfcomm_cid(packet);
213                     printf("RFCOMM channel %u requested for %s\n", rfcomm_channel_nr, bd_addr_to_str(event_addr));
214                     rfcomm_accept_connection(rfcomm_channel_id);
215                     break;
216 
217                 case RFCOMM_EVENT_CHANNEL_OPENED:
218                     // data: event(8), len(8), status (8), address (48), server channel(8), rfcomm_cid(16), max frame size(16)
219                     if (rfcomm_event_channel_opened_get_status(packet)) {
220                         printf("RFCOMM channel open failed, status %u\n", rfcomm_event_channel_opened_get_status(packet));
221                     } else {
222                         rfcomm_channel_id = rfcomm_event_channel_opened_get_rfcomm_cid(packet);
223                         mtu = rfcomm_event_channel_opened_get_max_frame_size(packet);
224                         printf("RFCOMM channel open succeeded. New RFCOMM Channel ID %u, max frame size %u\n", rfcomm_channel_id, mtu);
225                     }
226                     break;
227                 case RFCOMM_EVENT_CAN_SEND_NOW:
228                     rfcomm_send(rfcomm_channel_id, (uint8_t*) lineBuffer, (uint16_t) strlen(lineBuffer));
229                     break;
230 
231 /* LISTING_PAUSE */
232                 case RFCOMM_EVENT_CHANNEL_CLOSED:
233                     printf("RFCOMM channel closed\n");
234                     rfcomm_channel_id = 0;
235                     break;
236 
237                 default:
238                     break;
239             }
240             break;
241 
242         case RFCOMM_DATA_PACKET:
243             printf("RCV: '");
244             for (i=0;i<size;i++){
245                 putchar(packet[i]);
246             }
247             printf("'\n");
248             break;
249 
250         default:
251             break;
252     }
253 /* LISTING_RESUME */
254 }
255 /* LISTING_END */
256 
257 int btstack_main(int argc, const char * argv[]);
258 int btstack_main(int argc, const char * argv[]){
259     (void)argc;
260     (void)argv;
261 
262     one_shot_timer_setup();
263     spp_service_setup();
264 
265     gap_discoverable_control(1);
266     gap_ssp_set_io_capability(SSP_IO_CAPABILITY_DISPLAY_YES_NO);
267     gap_set_local_name("SPP Counter 00:00:00:00:00:00");
268 
269     // turn on!
270     hci_power_control(HCI_POWER_ON);
271 
272     return 0;
273 }
274 /* EXAMPLE_END */
275 
276