xref: /btstack/src/btstack_util.h (revision 9fce1f717ee8d87d160efefd9380999dfd97a9fb)
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 /**
39  * @title General Utility Functions
40  *
41  */
42 
43 #ifndef BTSTACK_UTIL_H
44 #define BTSTACK_UTIL_H
45 
46 
47 #if defined __cplusplus
48 extern "C" {
49 #endif
50 
51 #include <stdint.h>
52 #include <string.h>
53 
54 #include "bluetooth.h"
55 #include "btstack_defines.h"
56 #include "btstack_linked_list.h"
57 
58 // hack: compilation with the android ndk causes an error as there's a reverse_64 macro
59 #ifdef reverse_64
60 #undef reverse_64
61 #endif
62 
63 // will be moved to daemon/btstack_device_name_db.h
64 
65 
66  /**
67   * @brief returns a value with number of lowest bits set to <1>
68   */
69 #define N_BITS(value) ((1<<value) - 1)
70 
71 /**
72  * @brief The device name type
73  */
74 #define DEVICE_NAME_LEN 248
75 typedef uint8_t device_name_t[DEVICE_NAME_LEN+1];
76 
77 /* API_START */
78 
79 /**
80  * @brief Minimum function for uint32_t
81  * @param a
82  * @param b
83  * @return value
84  */
85 uint32_t btstack_min(uint32_t a, uint32_t b);
86 
87 /**
88  * @brief Maximum function for uint32_t
89  * @param a
90  * @param b
91  * @return value
92  */
93 uint32_t btstack_max(uint32_t a, uint32_t b);
94 
95 /**
96  * @brief Calculate delta between two uint32_t points in time
97  * @return time_a - time_b - result > 0 if time_a is newer than time_b
98  */
99 int32_t btstack_time_delta(uint32_t time_a, uint32_t time_b);
100 
101 /**
102  * @brief Calculate delta between two uint16_t points in time
103  * @return time_a - time_b - result > 0 if time_a is newer than time_b
104  */
105 int16_t btstack_time16_delta(uint16_t time_a, uint16_t time_b);
106 
107 /**
108  * @brief Read 08/16/24/32 bit little endian value from buffer
109  * @param buffer
110  * @param position in buffer
111  * @return value
112  */
113 uint8_t  little_endian_read_08(const uint8_t * buffer, int position);
114 uint16_t little_endian_read_16(const uint8_t * buffer, int position);
115 uint32_t little_endian_read_24(const uint8_t * buffer, int position);
116 uint32_t little_endian_read_32(const uint8_t * buffer, int position);
117 
118 
119 /**
120  * @brief Write 08/16/32 bit little endian value into buffer
121  * @param buffer
122  * @param position in buffer
123  * @param value
124  */
125 void little_endian_store_08(uint8_t * buffer, uint16_t position, uint8_t value);
126 void little_endian_store_16(uint8_t * buffer, uint16_t position, uint16_t value);
127 void little_endian_store_24(uint8_t * buffer, uint16_t position, uint32_t value);
128 void little_endian_store_32(uint8_t * buffer, uint16_t position, uint32_t value);
129 
130 /**
131  * @brief Read 08/16/24/32 bit big endian value from buffer
132  * @param buffer
133  * @param position in buffer
134  * @return value
135  */
136 uint32_t big_endian_read_08(const uint8_t* buffer, int position);
137 uint32_t big_endian_read_16(const uint8_t * buffer, int position);
138 uint32_t big_endian_read_24(const uint8_t * buffer, int position);
139 uint32_t big_endian_read_32(const uint8_t * buffer, int position);
140 
141 /**
142  * @brief Write 08/16/32 bit big endian value into buffer
143  * @param buffer
144  * @param position in buffer
145  * @param value
146  */
147 void big_endian_store_08(uint8_t * buffer, uint16_t position, uint8_t value);
148 void big_endian_store_16(uint8_t * buffer, uint16_t position, uint16_t value);
149 void big_endian_store_24(uint8_t * buffer, uint16_t position, uint32_t value);
150 void big_endian_store_32(uint8_t * buffer, uint16_t position, uint32_t value);
151 
152 
153 /**
154  * @brief Swap bytes in 16 bit integer
155  */
156 static inline uint16_t btstack_flip_16(uint16_t value){
157     return (uint16_t)((value & 0xffu) << 8) | (value >> 8);
158 }
159 
160 /**
161  * @brief Check for big endian system
162  * @return 1 if on big endian
163  */
164 static inline int btstack_is_big_endian(void){
165 	uint16_t sample = 0x0100;
166 	return (int) *(uint8_t*) &sample;
167 }
168 
169 /**
170  * @brief Check for little endian system
171  * @return 1 if on little endian
172  */
173 static inline int btstack_is_little_endian(void){
174 	uint16_t sample = 0x0001;
175 	return (int) *(uint8_t*) &sample;
176 }
177 
178 /**
179  * @brief Copy from source to destination and reverse byte order
180  * @param src
181  * @param dest
182  * @param len
183  */
184 void reverse_bytes(const uint8_t * src, uint8_t * dest, int len);
185 
186 /**
187  * @brief Wrapper around reverse_bytes for common buffer sizes
188  * @param src
189  * @param dest
190  */
191 void reverse_24 (const uint8_t * src, uint8_t * dest);
192 void reverse_48 (const uint8_t * src, uint8_t * dest);
193 void reverse_56 (const uint8_t * src, uint8_t * dest);
194 void reverse_64 (const uint8_t * src, uint8_t * dest);
195 void reverse_128(const uint8_t * src, uint8_t * dest);
196 void reverse_256(const uint8_t * src, uint8_t * dest);
197 
198 void reverse_bd_addr(const bd_addr_t src, bd_addr_t dest);
199 
200 /**
201  * @brief Check if all bytes in buffer are zero
202  * @param buffer
203  * @param size
204  * @return true if all bytes is buffer are zero
205  */
206 bool btstack_is_null(const uint8_t * buffer, uint16_t size);
207 
208 /**
209  * @brief Check if all bytes in a bd_addr_t are zero
210  * @param addr
211  * @return true if all bytes in addr are zero
212  */
213 bool btstack_is_null_bd_addr( const bd_addr_t addr );
214 
215 /**
216  * @brief ASCII character for 4-bit nibble
217  * @return character
218  */
219 char char_for_nibble(uint8_t nibble);
220 
221 /**
222  * @brif 4-bit nibble from ASCII character
223  * @return value
224  */
225 int nibble_for_char(char c);
226 
227 /**
228  * @brief Compare two Bluetooth addresses
229  * @param a
230  * @param b
231  * @return 0 if equal
232  */
233 int bd_addr_cmp(const bd_addr_t a, const bd_addr_t b);
234 
235 /**
236  * @brief Copy Bluetooth address
237  * @param dest
238  * @param src
239  */
240 void bd_addr_copy(bd_addr_t dest, const bd_addr_t src);
241 
242 /**
243  * @brief Use printf to write hexdump as single line of data
244  */
245 void printf_hexdump(const void * data, int size);
246 
247 /**
248  * @brief Create human readable representation for UUID128
249  * @note uses fixed global buffer
250  * @return pointer to UUID128 string
251  */
252 char * uuid128_to_str(const uint8_t * uuid);
253 
254 /**
255  * @brief Create human readable represenationt of Bluetooth address
256  * @note uses fixed global buffer
257  * @param delimiter
258  * @return pointer to Bluetooth address string
259  */
260 char * bd_addr_to_str_with_delimiter(const bd_addr_t addr, char delimiter);
261 
262 /**
263  * @brief Create human readable represenationt of Bluetooth address
264  * @note uses fixed global buffer
265  * @return pointer to Bluetooth address string
266  */
267 char * bd_addr_to_str(const bd_addr_t addr);
268 
269 /**
270  * @brief Replace address placeholder '00:00:00:00:00:00' with Bluetooth address
271  * @param buffer
272  * @param size
273  * @param address
274  */
275 void btstack_replace_bd_addr_placeholder(uint8_t * buffer, uint16_t size, const bd_addr_t address);
276 
277 /**
278  * @brief Parse Bluetooth address
279  * @param address_string
280  * @param buffer for parsed address
281  * @return 1 if string was parsed successfully
282  */
283 int sscanf_bd_addr(const char * addr_string, bd_addr_t addr);
284 
285 /**
286  * @brief Constructs UUID128 from 16 or 32 bit UUID using Bluetooth base UUID
287  * @param uuid128 output buffer
288  * @param short_uuid
289  */
290 void uuid_add_bluetooth_prefix(uint8_t * uuid128, uint32_t short_uuid);
291 
292 /**
293  * @brief Checks if UUID128 has Bluetooth base UUID prefix
294  * @param uui128 to test
295  * @return true if it can be expressed as UUID32
296  */
297 bool uuid_has_bluetooth_prefix(const uint8_t * uuid128);
298 
299 /**
300  * @brief Parse unsigned number
301  * @param str to parse
302  * @return value
303  */
304 uint32_t btstack_atoi(const char * str);
305 
306 /**
307  * @brief Return number of digits of a uint32 number
308  * @param uint32_number
309  * @return num_digits
310  */
311 int string_len_for_uint32(uint32_t i);
312 
313 /**
314  * @brief Return number of set bits in a uint32 number
315  * @param uint32_number
316  * @return num_set_bits
317  */
318 int count_set_bits_uint32(uint32_t x);
319 
320 /**
321  * @brief Check CRC8 using ETSI TS 101 369 V6.3.0.
322  * @note Only used by RFCOMM
323  * @param data
324  * @param len
325  * @param check_sum
326  */
327 uint8_t btstack_crc8_check(uint8_t * data, uint16_t len, uint8_t check_sum);
328 
329 /**
330  * @brief Calculate CRC8 using ETSI TS 101 369 V6.3.0.
331  * @note Only used by RFCOMM
332  * @param data
333  * @param len
334  */
335 uint8_t btstack_crc8_calc(uint8_t * data, uint16_t len);
336 
337 
338 /**
339  * @brief Calculate the initial CRC32 value using ISO 3309 (HDLC), polynomial (normal) 0x04c11db7
340  * @note Used by OTS Service.
341  *
342  * @return  The initial crc value.
343  */
344 uint32_t btstack_crc32_init(void);
345 
346 /**
347  * @brief Update the CRC32 value with new data.
348  *
349  * @param crc      The current crc value.
350  * @param data     Pointer to a buffer of \a data_len bytes.
351  * @param data_len Number of bytes in the \a data buffer.
352  * @return             The updated crc value.
353  */
354 uint32_t btstack_crc32_update(uint32_t crc, const uint8_t * data, uint32_t data_len);
355 
356 /**
357  * @brief Calculate the final CRC32 value.
358  *
359  * @param crc  The current crc value.
360  * @return     The final crc value.
361  */
362 uint32_t btstack_crc32_finalize(uint32_t crc);
363 
364 /**
365  * @brief Get next cid
366  * @param current_cid
367  * @return next cid skiping 0
368  */
369 uint16_t btstack_next_cid_ignoring_zero(uint16_t current_cid);
370 
371 /**
372  * @brief Copy string (up to dst_size-1 characters) from src into dst buffer with terminating '\0'
373  * @note replaces strncpy + dst[dst_size-1] = '\0'
374  * @param dst
375  * @param dst_size
376  * @param src
377  * @retun bytes_copied including trailing 0
378  */
379 uint16_t btstack_strcpy(char * dst, uint16_t dst_size, const char * src);
380 
381 /**
382  * @brief Append src string to string in dst buffer with terminating '\0'
383  * @note max total string length will be dst_size-1 characters
384  * @param dst
385  * @param dst_size
386  * @param src
387  */
388 void btstack_strcat(char * dst, uint16_t dst_size, const char * src);
389 
390 /**
391  * @brief Calculated the number of characters that would get printed
392  * @note same as calling snprintf without a buffer
393  * @param format
394  * @param argsq
395  * @return number of characters, or negative value on error
396  */
397 int btstack_printf_strlen(const char * format, ...)
398 #ifdef __GNUC__
399 __attribute__ ((format (__printf__, 1, 2)))
400 #endif
401 ;
402 
403 
404 /**
405  * @brief Format string into buffer with '\0' and assert it is large enough
406  * @note same as calling snprintf and assert that the string was not truncated
407  * @param buffer
408  * @param size of buffer
409  * @param format
410  * @param argsq
411  * @return number of characters
412  */
413 uint16_t btstack_snprintf_assert_complete(char * buffer, size_t size, const char * format, ...)
414 #ifdef __GNUC__
415 __attribute__ ((format (__printf__, 3, 4)))
416 #endif
417 ;
418 
419 /**
420  * @brief Format string into buffer, truncated if necessary. Output string is '\0' terminated
421  * @note similar to calling snprintf but returns the length of the output string
422  * @param buffer
423  * @param size of buffer
424  * @param format
425  * @param argsq
426  * @return number of characters
427  */
428 uint16_t btstack_snprintf_best_effort(char * buffer, size_t size, const char * format, ...)
429 #ifdef __GNUC__
430 __attribute__ ((format (__printf__, 3, 4)))
431 #endif
432 ;
433 
434 /**
435  * Returns the number of leading 0-bits in x, starting at the most significant bit position.
436  * If x is 0, the result is undefined.
437  * @note maps to __builtin_clz for gcc and clang
438  * @param value
439  * @return number of leading 0-bits
440  */
441 uint8_t btstack_clz(uint32_t value);
442 
443 /**
444  * @brief Copy chunk of data into a virtual buffer backed by a physical buffer.
445  * Used to provide chunk of data of larger buffer that is constructed on the fly, e.g. serializing data struct
446  *
447  * For example, copy field2 to buffer, with buffer_offset = 11
448  *
449  *           field1  field2  field3     field4        field5  filed6
450  * struct:  -------|-------|----------|-------------|-------|--------------
451  * buffer:             ------------------
452  * result:             ----|
453  *
454  * When also copying field3 and field4 to buffer, with buffer_offset = 11
455  *
456  *           field1  field2  field3     field4        field5  filed6
457  * struct:  -------|-------|----------|-------------|-------|--------------
458  * buffer:             ------------------
459  * result:             ----|----------|--
460  *
461  * @param field_data
462  * @param field_len
463  * @param field_offset  position of field in complete data block
464  * @param buffer_data
465  * @param buffer_len
466  * @param buffer_offset position of buffer in complete data block
467  * @return bytes_copied number of bytes actually stored in buffer
468  */
469 uint16_t btstack_virtual_memcpy(
470     const uint8_t * field_data, uint16_t field_len, uint16_t field_offset,
471     uint8_t * buffer, uint16_t buffer_size, uint16_t buffer_offset);
472 
473 
474 /* API_END */
475 
476 #if defined __cplusplus
477 }
478 #endif
479 
480 #endif // BTSTACK_UTIL_H
481