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