From 3c89fd52679c8ccebceb30294a4bd815b51ede19 Mon Sep 17 00:00:00 2001 From: Dimitri Sokolyuk Date: Mon, 5 Dec 2016 11:22:26 +0100 Subject: Import Drive SDK --- drive-sdk/.gitignore | 5 + drive-sdk/CMakeLists.txt | 31 + drive-sdk/LICENSE | 201 + drive-sdk/README.md | 69 + drive-sdk/cmake/modules/FindGLIB2.cmake | 235 + drive-sdk/cmake/modules/FindReadline.cmake | 35 + .../cmake/modules/MacroOutOfSourceBuild.cmake | 13 + drive-sdk/cmake/modules/TargetDistclean.cmake | 28 + drive-sdk/deps/bzle/.gitignore | 5 + drive-sdk/deps/bzle/CMakeLists.txt | 15 + drive-sdk/deps/bzle/COPYING | 340 ++ drive-sdk/deps/bzle/README.md | 25 + .../deps/bzle/cmake/modules/COPYING-CMAKE-MODULES | 23 + drive-sdk/deps/bzle/cmake/modules/FindGLIB2.cmake | 235 + .../bzle/cmake/modules/MacroOutOfSourceBuild.cmake | 13 + .../deps/bzle/include/bzle/bluetooth/bluetooth.h | 399 ++ drive-sdk/deps/bzle/include/bzle/bluetooth/btio.h | 95 + drive-sdk/deps/bzle/include/bzle/bluetooth/hci.h | 2418 ++++++++++ .../deps/bzle/include/bzle/bluetooth/hci_lib.h | 235 + drive-sdk/deps/bzle/include/bzle/bluetooth/l2cap.h | 279 ++ drive-sdk/deps/bzle/include/bzle/bluetooth/sco.h | 62 + drive-sdk/deps/bzle/include/bzle/bluetooth/sdp.h | 534 +++ .../deps/bzle/include/bzle/bluetooth/sdp_lib.h | 634 +++ drive-sdk/deps/bzle/include/bzle/bluetooth/uuid.h | 140 + drive-sdk/deps/bzle/include/bzle/gatt/att.h | 286 ++ drive-sdk/deps/bzle/include/bzle/gatt/gatt.h | 115 + drive-sdk/deps/bzle/include/bzle/gatt/gattrib.h | 79 + drive-sdk/deps/bzle/include/bzle/gatt/utils.h | 33 + drive-sdk/deps/bzle/src/CMakeLists.txt | 23 + drive-sdk/deps/bzle/src/att.c | 1165 +++++ drive-sdk/deps/bzle/src/bluetooth.c | 867 ++++ drive-sdk/deps/bzle/src/btio.c | 1186 +++++ drive-sdk/deps/bzle/src/gatt.c | 929 ++++ drive-sdk/deps/bzle/src/gattrib.c | 763 +++ drive-sdk/deps/bzle/src/hci.c | 2929 ++++++++++++ drive-sdk/deps/bzle/src/log.c | 146 + drive-sdk/deps/bzle/src/log.h | 59 + drive-sdk/deps/bzle/src/sdp.c | 4940 ++++++++++++++++++++ drive-sdk/deps/bzle/src/utils.c | 120 + drive-sdk/deps/bzle/src/uuid.c | 278 ++ drive-sdk/deps/bzle/tools/CMakeLists.txt | 21 + drive-sdk/deps/bzle/tools/csr.c | 2853 +++++++++++ drive-sdk/deps/bzle/tools/csr.h | 553 +++ drive-sdk/deps/bzle/tools/hciconfig.c | 2050 ++++++++ drive-sdk/deps/bzle/tools/textfile.c | 475 ++ drive-sdk/deps/bzle/tools/textfile.h | 34 + drive-sdk/examples/CMakeLists.txt | 2 + drive-sdk/examples/README.md | 25 + drive-sdk/examples/vehicle-scan/.gitignore | 3 + drive-sdk/examples/vehicle-scan/CMakeLists.txt | 22 + drive-sdk/examples/vehicle-scan/README.md | 13 + drive-sdk/examples/vehicle-scan/uthash.h | 948 ++++ drive-sdk/examples/vehicle-scan/vehicle-scan.c | 471 ++ drive-sdk/examples/vehicle-tool/.gitignore | 4 + drive-sdk/examples/vehicle-tool/CMakeLists.txt | 31 + drive-sdk/examples/vehicle-tool/display.c | 64 + drive-sdk/examples/vehicle-tool/display.h | 32 + drive-sdk/examples/vehicle-tool/vehicle_cmd.c | 1155 +++++ drive-sdk/examples/vehicle-tool/vehicle_tool.c | 172 + drive-sdk/include/ankidrive.h | 26 + drive-sdk/include/ankidrive/advertisement.h | 145 + drive-sdk/include/ankidrive/common.h | 48 + drive-sdk/include/ankidrive/protocol.h | 559 +++ drive-sdk/include/ankidrive/uuid.h | 50 + drive-sdk/include/ankidrive/vehicle_gatt_profile.h | 30 + drive-sdk/include/ankidrive/version.h | 25 + drive-sdk/src/CMakeLists.txt | 22 + drive-sdk/src/advertisement.c | 148 + drive-sdk/src/advertisement.h | 145 + drive-sdk/src/anki_util.c | 62 + drive-sdk/src/anki_util.h | 29 + drive-sdk/src/common.h | 48 + drive-sdk/src/eir.c | 54 + drive-sdk/src/eir.h | 56 + drive-sdk/src/protocol.c | 246 + drive-sdk/src/protocol.h | 559 +++ drive-sdk/src/uuid.c | 25 + drive-sdk/src/uuid.h | 50 + drive-sdk/src/vehicle_gatt_profile.h | 30 + drive-sdk/test/CMakeLists.txt | 18 + drive-sdk/test/adv_data.h | 39 + drive-sdk/test/anki_greatest.h | 54 + drive-sdk/test/greatest.h | 591 +++ drive-sdk/test/test_ble_advertisement.c | 75 + drive-sdk/test/test_protocol.c | 243 + drive-sdk/test/test_suite.c | 36 + drive-sdk/test/test_vehicle_advertisement.c | 96 + 87 files changed, 32424 insertions(+) create mode 100644 drive-sdk/.gitignore create mode 100644 drive-sdk/CMakeLists.txt create mode 100644 drive-sdk/LICENSE create mode 100644 drive-sdk/README.md create mode 100644 drive-sdk/cmake/modules/FindGLIB2.cmake create mode 100644 drive-sdk/cmake/modules/FindReadline.cmake create mode 100644 drive-sdk/cmake/modules/MacroOutOfSourceBuild.cmake create mode 100644 drive-sdk/cmake/modules/TargetDistclean.cmake create mode 100644 drive-sdk/deps/bzle/.gitignore create mode 100644 drive-sdk/deps/bzle/CMakeLists.txt create mode 100644 drive-sdk/deps/bzle/COPYING create mode 100644 drive-sdk/deps/bzle/README.md create mode 100644 drive-sdk/deps/bzle/cmake/modules/COPYING-CMAKE-MODULES create mode 100644 drive-sdk/deps/bzle/cmake/modules/FindGLIB2.cmake create mode 100644 drive-sdk/deps/bzle/cmake/modules/MacroOutOfSourceBuild.cmake create mode 100644 drive-sdk/deps/bzle/include/bzle/bluetooth/bluetooth.h create mode 100644 drive-sdk/deps/bzle/include/bzle/bluetooth/btio.h create mode 100644 drive-sdk/deps/bzle/include/bzle/bluetooth/hci.h create mode 100644 drive-sdk/deps/bzle/include/bzle/bluetooth/hci_lib.h create mode 100644 drive-sdk/deps/bzle/include/bzle/bluetooth/l2cap.h create mode 100644 drive-sdk/deps/bzle/include/bzle/bluetooth/sco.h create mode 100644 drive-sdk/deps/bzle/include/bzle/bluetooth/sdp.h create mode 100644 drive-sdk/deps/bzle/include/bzle/bluetooth/sdp_lib.h create mode 100644 drive-sdk/deps/bzle/include/bzle/bluetooth/uuid.h create mode 100644 drive-sdk/deps/bzle/include/bzle/gatt/att.h create mode 100644 drive-sdk/deps/bzle/include/bzle/gatt/gatt.h create mode 100644 drive-sdk/deps/bzle/include/bzle/gatt/gattrib.h create mode 100644 drive-sdk/deps/bzle/include/bzle/gatt/utils.h create mode 100644 drive-sdk/deps/bzle/src/CMakeLists.txt create mode 100644 drive-sdk/deps/bzle/src/att.c create mode 100644 drive-sdk/deps/bzle/src/bluetooth.c create mode 100644 drive-sdk/deps/bzle/src/btio.c create mode 100644 drive-sdk/deps/bzle/src/gatt.c create mode 100644 drive-sdk/deps/bzle/src/gattrib.c create mode 100644 drive-sdk/deps/bzle/src/hci.c create mode 100644 drive-sdk/deps/bzle/src/log.c create mode 100644 drive-sdk/deps/bzle/src/log.h create mode 100644 drive-sdk/deps/bzle/src/sdp.c create mode 100644 drive-sdk/deps/bzle/src/utils.c create mode 100644 drive-sdk/deps/bzle/src/uuid.c create mode 100644 drive-sdk/deps/bzle/tools/CMakeLists.txt create mode 100644 drive-sdk/deps/bzle/tools/csr.c create mode 100644 drive-sdk/deps/bzle/tools/csr.h create mode 100644 drive-sdk/deps/bzle/tools/hciconfig.c create mode 100644 drive-sdk/deps/bzle/tools/textfile.c create mode 100644 drive-sdk/deps/bzle/tools/textfile.h create mode 100755 drive-sdk/examples/CMakeLists.txt create mode 100644 drive-sdk/examples/README.md create mode 100644 drive-sdk/examples/vehicle-scan/.gitignore create mode 100755 drive-sdk/examples/vehicle-scan/CMakeLists.txt create mode 100644 drive-sdk/examples/vehicle-scan/README.md create mode 100644 drive-sdk/examples/vehicle-scan/uthash.h create mode 100644 drive-sdk/examples/vehicle-scan/vehicle-scan.c create mode 100644 drive-sdk/examples/vehicle-tool/.gitignore create mode 100755 drive-sdk/examples/vehicle-tool/CMakeLists.txt create mode 100644 drive-sdk/examples/vehicle-tool/display.c create mode 100644 drive-sdk/examples/vehicle-tool/display.h create mode 100644 drive-sdk/examples/vehicle-tool/vehicle_cmd.c create mode 100644 drive-sdk/examples/vehicle-tool/vehicle_tool.c create mode 100644 drive-sdk/include/ankidrive.h create mode 100644 drive-sdk/include/ankidrive/advertisement.h create mode 100644 drive-sdk/include/ankidrive/common.h create mode 100644 drive-sdk/include/ankidrive/protocol.h create mode 100644 drive-sdk/include/ankidrive/uuid.h create mode 100644 drive-sdk/include/ankidrive/vehicle_gatt_profile.h create mode 100644 drive-sdk/include/ankidrive/version.h create mode 100644 drive-sdk/src/CMakeLists.txt create mode 100644 drive-sdk/src/advertisement.c create mode 100644 drive-sdk/src/advertisement.h create mode 100644 drive-sdk/src/anki_util.c create mode 100644 drive-sdk/src/anki_util.h create mode 100644 drive-sdk/src/common.h create mode 100644 drive-sdk/src/eir.c create mode 100644 drive-sdk/src/eir.h create mode 100644 drive-sdk/src/protocol.c create mode 100644 drive-sdk/src/protocol.h create mode 100644 drive-sdk/src/uuid.c create mode 100644 drive-sdk/src/uuid.h create mode 100644 drive-sdk/src/vehicle_gatt_profile.h create mode 100644 drive-sdk/test/CMakeLists.txt create mode 100644 drive-sdk/test/adv_data.h create mode 100644 drive-sdk/test/anki_greatest.h create mode 100644 drive-sdk/test/greatest.h create mode 100644 drive-sdk/test/test_ble_advertisement.c create mode 100644 drive-sdk/test/test_protocol.c create mode 100644 drive-sdk/test/test_suite.c create mode 100644 drive-sdk/test/test_vehicle_advertisement.c diff --git a/drive-sdk/.gitignore b/drive-sdk/.gitignore new file mode 100644 index 0000000..740f2b9 --- /dev/null +++ b/drive-sdk/.gitignore @@ -0,0 +1,5 @@ +build/ +*.o + +*~ +*.swp diff --git a/drive-sdk/CMakeLists.txt b/drive-sdk/CMakeLists.txt new file mode 100644 index 0000000..1f0df49 --- /dev/null +++ b/drive-sdk/CMakeLists.txt @@ -0,0 +1,31 @@ +cmake_minimum_required(VERSION 2.8) + +project(drivekit) + +set(CMAKE_MODULE_PATH ${drivekit_SOURCE_DIR}/cmake/modules ${CMAKE_MODULE_PATH}) + +# Set the default install path to be './build/dist' +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX ${PROJECT_BINARY_DIR}/dist CACHE PATH "drive-sdk install prefix" FORCE) +endif(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + +OPTION( BUILD_EXAMPLES "Build example apps" OFF ) + +SET (CMAKE_C_FLAGS "-Wall -std=c99") +include(MacroOutOfSourceBuild) +include(TargetDistclean) + +macro_ensure_out_of_source_build("${PROJECT_NAME} requires an out of source build.") + +add_subdirectory(src) +add_subdirectory(test) + +install(DIRECTORY include/ankidrive DESTINATION include) + +if (BUILD_EXAMPLES) + add_subdirectory(deps/bzle) + add_subdirectory(examples) +endif () + +# CTest is flaky - Create a target to run our test suite directly +add_custom_target(test COMMAND ${PROJECT_BINARY_DIR}/test/Test) diff --git a/drive-sdk/LICENSE b/drive-sdk/LICENSE new file mode 100644 index 0000000..11069ed --- /dev/null +++ b/drive-sdk/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/drive-sdk/README.md b/drive-sdk/README.md new file mode 100644 index 0000000..3590e15 --- /dev/null +++ b/drive-sdk/README.md @@ -0,0 +1,69 @@ +Anki Drive SDK +============== + +The Anki Drive SDK is a C implementation of the message protocols and data parsing routines necessary for communicating with Anki Drive vehicles. + +The Anki Drive SDK is licensed under the Apache 2.0 license. Projects in the `examples` folder are released under separate licenses. + +- web: http://anki.github.io/drive-sdk +- StackOverflow Tag: anki-drive-sdk +- Issues: [GitHub Issues](https://github.com/anki/drive-sdk/issues) +- Guides: [Getting Started on Ubuntu][ubuntu-getting-started], [Programming Guide][] +- Mailing list: [Anki-Dev Google Group](https://groups.google.com/a/anki.com/forum/#!forum/anki-dev) + +[Programming Guide]: http://anki.github.io/drive-sdk/docs/programming-guide + + +Features +======== + +The initial release of the SDK has the minimal number of functions required to use the message protocol and parse information sent by vehicles. + +* Parse vehicle info from Bluetooth LE `LOCAL_NAME` and `MANUFACTURER_DATA` advertisement data. +* Create messages to send commands to vehicles. +* Parse vehicle response messages. + +The initial version provides a limited subset of the message protocol. +We hope to expand available messages and functionality in the future, once we can do so in a safe and stable way. + +Optional dependencies +===================== + +* Building the example programs for linux requires [glib2][] and [libreadline][]. + See the guide to [Getting Started on Ubuntu][ubuntu-getting-started] for more info. + +[ubuntu-getting-started]: https://github.com/anki/drive-sdk/wiki/Getting-Started-on-Ubuntu +[glib2]: http://www.gtk.org/ +[libreadline]: http://cnswww.cns.cwru.edu/php/chet/readline/rltop.html + +Building the SDK +================ + +The Anki Drive SDK builds cleanly on Mac OS X and most linux distributions. +The SDK builds the `libankidrive` library, with public headers available in `include`. + +The SDK is built using `CMake 2.8` () on all platforms. + + $ mkdir -p build && cd build + + # build & test library + $ cmake .. + $ make + $ make test + + # build library + examples (examples currently require Linux) + $ cmake .. -DBUILD_EXAMPLES=ON + $ make + $ make test + $ make install + # install creates a build/dist/bin folder containing executables + + +### Run Unit Tests + + $ cd build + $ cmake .. + $ make + $ make test + + diff --git a/drive-sdk/cmake/modules/FindGLIB2.cmake b/drive-sdk/cmake/modules/FindGLIB2.cmake new file mode 100644 index 0000000..87bf6ec --- /dev/null +++ b/drive-sdk/cmake/modules/FindGLIB2.cmake @@ -0,0 +1,235 @@ +# - Try to find GLib2 +# Once done this will define +# +# GLIB2_FOUND - system has GLib2 +# GLIB2_INCLUDE_DIRS - the GLib2 include directory +# GLIB2_LIBRARIES - Link these to use GLib2 +# +# HAVE_GLIB_GREGEX_H glib has gregex.h header and +# supports g_regex_match_simple +# +# Copyright (c) 2006 Andreas Schneider +# Copyright (c) 2006 Philippe Bernery +# Copyright (c) 2007 Daniel Gollub +# Copyright (c) 2007 Alban Browaeys +# Copyright (c) 2008 Michael Bell +# Copyright (c) 2008-2009 Bjoern Ricks +# +# Redistribution and use is allowed according to the terms of the New +# BSD license. +# For details see the accompanying COPYING-CMAKE-SCRIPTS file. +# + + +IF (GLIB2_LIBRARIES AND GLIB2_INCLUDE_DIRS ) + # in cache already + SET(GLIB2_FOUND TRUE) +ELSE (GLIB2_LIBRARIES AND GLIB2_INCLUDE_DIRS ) + + INCLUDE(FindPkgConfig) + + ## Glib + IF ( GLIB2_FIND_REQUIRED ) + SET( _pkgconfig_REQUIRED "REQUIRED" ) + ELSE ( GLIB2_FIND_REQUIRED ) + SET( _pkgconfig_REQUIRED "" ) + ENDIF ( GLIB2_FIND_REQUIRED ) + + IF ( GLIB2_MIN_VERSION ) + PKG_SEARCH_MODULE( GLIB2 ${_pkgconfig_REQUIRED} glib-2.0>=${GLIB2_MIN_VERSION} ) + ELSE ( GLIB2_MIN_VERSION ) + PKG_SEARCH_MODULE( GLIB2 ${_pkgconfig_REQUIRED} glib-2.0 ) + ENDIF ( GLIB2_MIN_VERSION ) + IF ( PKG_CONFIG_FOUND ) + IF ( GLIB2_FOUND ) + SET ( GLIB2_CORE_FOUND TRUE ) + ELSE ( GLIB2_FOUND ) + SET ( GLIB2_CORE_FOUND FALSE ) + ENDIF ( GLIB2_FOUND ) + ENDIF ( PKG_CONFIG_FOUND ) + + # Look for glib2 include dir and libraries w/o pkgconfig + IF ( NOT GLIB2_FOUND AND NOT PKG_CONFIG_FOUND ) + FIND_PATH( + _glibconfig_include_DIR + NAMES + glibconfig.h + PATHS + /opt/gnome/lib64 + /opt/gnome/lib + /opt/lib/ + /opt/local/lib + /sw/lib/ + /usr/lib64 + /usr/lib + /usr/local/include + ${CMAKE_LIBRARY_PATH} + PATH_SUFFIXES + glib-2.0/include + ) + + FIND_PATH( + _glib2_include_DIR + NAMES + glib.h + PATHS + /opt/gnome/include + /opt/local/include + /sw/include + /usr/include + /usr/local/include + PATH_SUFFIXES + glib-2.0 + ) + + #MESSAGE(STATUS "Glib headers: ${_glib2_include_DIR}") + + FIND_LIBRARY( + _glib2_link_DIR + NAMES + glib-2.0 + glib + PATHS + /opt/gnome/lib + /opt/local/lib + /sw/lib + /usr/lib + /usr/local/lib + ) + IF ( _glib2_include_DIR AND _glib2_link_DIR ) + SET ( _glib2_FOUND TRUE ) + ENDIF ( _glib2_include_DIR AND _glib2_link_DIR ) + + + IF ( _glib2_FOUND ) + SET ( GLIB2_INCLUDE_DIRS ${_glib2_include_DIR} ${_glibconfig_include_DIR} ) + SET ( GLIB2_LIBRARIES ${_glib2_link_DIR} ) + SET ( GLIB2_CORE_FOUND TRUE ) + ELSE ( _glib2_FOUND ) + SET ( GLIB2_CORE_FOUND FALSE ) + ENDIF ( _glib2_FOUND ) + + # Handle dependencies + # libintl + IF ( NOT LIBINTL_FOUND ) + FIND_PATH(LIBINTL_INCLUDE_DIR + NAMES + libintl.h + PATHS + /opt/gnome/include + /opt/local/include + /sw/include + /usr/include + /usr/local/include + ) + + FIND_LIBRARY(LIBINTL_LIBRARY + NAMES + intl + PATHS + /opt/gnome/lib + /opt/local/lib + /sw/lib + /usr/local/lib + /usr/lib + ) + + IF (LIBINTL_LIBRARY AND LIBINTL_INCLUDE_DIR) + SET (LIBINTL_FOUND TRUE) + ENDIF (LIBINTL_LIBRARY AND LIBINTL_INCLUDE_DIR) + ENDIF ( NOT LIBINTL_FOUND ) + + # libiconv + IF ( NOT LIBICONV_FOUND ) + FIND_PATH(LIBICONV_INCLUDE_DIR + NAMES + iconv.h + PATHS + /opt/gnome/include + /opt/local/include + /opt/local/include + /sw/include + /sw/include + /usr/local/include + /usr/include + PATH_SUFFIXES + glib-2.0 + ) + + FIND_LIBRARY(LIBICONV_LIBRARY + NAMES + iconv + PATHS + /opt/gnome/lib + /opt/local/lib + /sw/lib + /usr/lib + /usr/local/lib + ) + + IF (LIBICONV_LIBRARY AND LIBICONV_INCLUDE_DIR) + SET (LIBICONV_FOUND TRUE) + ENDIF (LIBICONV_LIBRARY AND LIBICONV_INCLUDE_DIR) + ENDIF ( NOT LIBICONV_FOUND ) + + IF (LIBINTL_FOUND) + SET (GLIB2_LIBRARIES ${GLIB2_LIBRARIES} ${LIBINTL_LIBRARY}) + SET (GLIB2_INCLUDE_DIRS ${GLIB2_INCLUDE_DIRS} ${LIBINTL_INCLUDE_DIR}) + ENDIF (LIBINTL_FOUND) + + IF (LIBICONV_FOUND) + SET (GLIB2_LIBRARIES ${GLIB2_LIBRARIES} ${LIBICONV_LIBRARY}) + SET (GLIB2_INCLUDE_DIRS ${GLIB2_INCLUDE_DIRS} ${LIBICONV_INCLUDE_DIR}) + ENDIF (LIBICONV_FOUND) + + ENDIF ( NOT GLIB2_FOUND AND NOT PKG_CONFIG_FOUND ) + ## + + IF (GLIB2_CORE_FOUND AND GLIB2_INCLUDE_DIRS AND GLIB2_LIBRARIES) + SET (GLIB2_FOUND TRUE) + ENDIF (GLIB2_CORE_FOUND AND GLIB2_INCLUDE_DIRS AND GLIB2_LIBRARIES) + + IF (GLIB2_FOUND) + IF (NOT GLIB2_FIND_QUIETLY) + MESSAGE (STATUS "Found GLib2: ${GLIB2_LIBRARIES} ${GLIB2_INCLUDE_DIRS}") + ENDIF (NOT GLIB2_FIND_QUIETLY) + ELSE (GLIB2_FOUND) + IF (GLIB2_FIND_REQUIRED) + MESSAGE (SEND_ERROR "Could not find GLib2") + ENDIF (GLIB2_FIND_REQUIRED) + ENDIF (GLIB2_FOUND) + + # show the GLIB2_INCLUDE_DIRS and GLIB2_LIBRARIES variables only in the advanced view + MARK_AS_ADVANCED(GLIB2_INCLUDE_DIRS GLIB2_LIBRARIES) + MARK_AS_ADVANCED(LIBICONV_INCLUDE_DIR LIBICONV_LIBRARY) + MARK_AS_ADVANCED(LIBINTL_INCLUDE_DIR LIBINTL_LIBRARY) + +ENDIF (GLIB2_LIBRARIES AND GLIB2_INCLUDE_DIRS) + +IF ( WIN32 ) + # include libiconv for win32 + IF ( NOT LIBICONV_FOUND ) + FIND_PATH(LIBICONV_INCLUDE_DIR iconv.h PATH_SUFFIXES glib-2.0) + + FIND_LIBRARY(LIBICONV_LIBRARY NAMES iconv) + + IF (LIBICONV_LIBRARY AND LIBICONV_INCLUDE_DIR) + SET (LIBICONV_FOUND TRUE) + ENDIF (LIBICONV_LIBRARY AND LIBICONV_INCLUDE_DIR) + ENDIF ( NOT LIBICONV_FOUND ) + IF (LIBICONV_FOUND) + SET (GLIB2_LIBRARIES ${GLIB2_LIBRARIES} ${LIBICONV_LIBRARY}) + SET (GLIB2_INCLUDE_DIRS ${GLIB2_INCLUDE_DIRS} ${LIBICONV_INCLUDE_DIR}) + ENDIF (LIBICONV_FOUND) +ENDIF ( WIN32 ) + +IF ( GLIB2_FOUND ) + # Check if system has a newer version of glib + # which supports g_regex_match_simple + INCLUDE( CheckIncludeFiles ) + SET( CMAKE_REQUIRED_INCLUDES ${GLIB2_INCLUDE_DIRS} ) + CHECK_INCLUDE_FILES ( glib/gregex.h HAVE_GLIB_GREGEX_H ) + CHECK_INCLUDE_FILES ( glib/gchecksum.h HAVE_GLIB_GCHECKSUM_H ) + # Reset CMAKE_REQUIRED_INCLUDES + SET( CMAKE_REQUIRED_INCLUDES "" ) +ENDIF( GLIB2_FOUND ) diff --git a/drive-sdk/cmake/modules/FindReadline.cmake b/drive-sdk/cmake/modules/FindReadline.cmake new file mode 100644 index 0000000..7d1601f --- /dev/null +++ b/drive-sdk/cmake/modules/FindReadline.cmake @@ -0,0 +1,35 @@ +# Try to find Readline library and header. +# This file sets the following variables: +# +# READLINE_INCLUDE_DIR, where to find readline.h, etc. +# READLINE_LIBRARIES, the libraries to link against +# READLINE_FOUND, If false, do not try to use Readline. +# +# Also defined, but not for general use are: +# READLINE_LIBRARY, the full path to the Readline library. +# READLINE_INCLUDE_PATH, for CMake backward compatibility + +FIND_PATH(READLINE_INCLUDE_DIR readline.h + PATHS /usr/local/include + /usr/include + PATH_SUFFIXES readline +) + +FIND_LIBRARY(READLINE_LIBRARY readline + /usr/lib + /usr/local/lib +) + +# handle the QUIETLY and REQUIRED arguments and set READLINE_FOUND to TRUE if +# all listed variables are TRUE +INCLUDE(FindPackageHandleStandardArgs) +FIND_PACKAGE_HANDLE_STANDARD_ARGS(READLINE DEFAULT_MSG READLINE_LIBRARY READLINE_INCLUDE_DIR) + +IF(READLINE_FOUND) + SET(READLINE_LIBRARIES ${READLINE_LIBRARY}) +ENDIF(READLINE_FOUND) + +MARK_AS_ADVANCED( + READLINE_INCLUDE_DIR + READLINE_LIBRARY +) diff --git a/drive-sdk/cmake/modules/MacroOutOfSourceBuild.cmake b/drive-sdk/cmake/modules/MacroOutOfSourceBuild.cmake new file mode 100644 index 0000000..c2b1121 --- /dev/null +++ b/drive-sdk/cmake/modules/MacroOutOfSourceBuild.cmake @@ -0,0 +1,13 @@ +# Ensures that we do an out of source build + +MACRO(MACRO_ENSURE_OUT_OF_SOURCE_BUILD MSG) + STRING(COMPARE EQUAL "${CMAKE_SOURCE_DIR}" +"${CMAKE_BINARY_DIR}" insource) + GET_FILENAME_COMPONENT(PARENTDIR ${CMAKE_SOURCE_DIR} PATH) + STRING(COMPARE EQUAL "${CMAKE_SOURCE_DIR}" +"${PARENTDIR}" insourcesubdir) + IF(insource OR insourcesubdir) + MESSAGE(FATAL_ERROR "${MSG}") + ENDIF(insource OR insourcesubdir) +ENDMACRO(MACRO_ENSURE_OUT_OF_SOURCE_BUILD) + diff --git a/drive-sdk/cmake/modules/TargetDistclean.cmake b/drive-sdk/cmake/modules/TargetDistclean.cmake new file mode 100644 index 0000000..ddd738c --- /dev/null +++ b/drive-sdk/cmake/modules/TargetDistclean.cmake @@ -0,0 +1,28 @@ +# http://www.cmake.org/pipermail/cmake/2003-June/003953.html +# add custom target distclean +# cleans and removes cmake generated files etc. +# Jan Woetzel 04/2003 +# + +IF (UNIX) + ADD_CUSTOM_TARGET (distclean @echo cleaning for source distribution) + SET(DISTCLEANED + cmake.depends + cmake.check_depends + CMakeCache.txt + cmake.check_cache + *.cmake + Makefile + core core.* + gmon.out + *~ + ) + + ADD_CUSTOM_COMMAND( + DEPENDS clean + COMMENT "distribution clean" + COMMAND rm + ARGS -Rf CMakeTmp ${DISTCLEANED} + TARGET distclean + ) +ENDIF(UNIX) diff --git a/drive-sdk/deps/bzle/.gitignore b/drive-sdk/deps/bzle/.gitignore new file mode 100644 index 0000000..740f2b9 --- /dev/null +++ b/drive-sdk/deps/bzle/.gitignore @@ -0,0 +1,5 @@ +build/ +*.o + +*~ +*.swp diff --git a/drive-sdk/deps/bzle/CMakeLists.txt b/drive-sdk/deps/bzle/CMakeLists.txt new file mode 100644 index 0000000..dad1137 --- /dev/null +++ b/drive-sdk/deps/bzle/CMakeLists.txt @@ -0,0 +1,15 @@ +cmake_minimum_required(VERSION 2.8) + +project(bzle) + +set(CMAKE_MODULE_PATH ${bzle_SOURCE_DIR}/cmake/modules ${CMAKE_MODULE_PATH}) + +SET (CMAKE_C_FLAGS "-Wall") +include(MacroOutOfSourceBuild) + +macro_ensure_out_of_source_build("${PROJECT_NAME} requires an out of source build.") + +add_subdirectory(src) +add_subdirectory(tools) + +install(DIRECTORY include/bzle DESTINATION include) diff --git a/drive-sdk/deps/bzle/COPYING b/drive-sdk/deps/bzle/COPYING new file mode 100644 index 0000000..6d45519 --- /dev/null +++ b/drive-sdk/deps/bzle/COPYING @@ -0,0 +1,340 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Library General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General +Public License instead of this License. diff --git a/drive-sdk/deps/bzle/README.md b/drive-sdk/deps/bzle/README.md new file mode 100644 index 0000000..0b6d281 --- /dev/null +++ b/drive-sdk/deps/bzle/README.md @@ -0,0 +1,25 @@ +# libbzle + +This is a minimal library consisting of code from [BlueZ 5.15][bluez] that is required for Bluetooth LE. +The Anki Drive SDK only requires the C interface to access Bluetooth LE methods supported by the Linux kernel. +This small package simplifies the build procedure, but eliminating the requirement to install dependencies and build the entire BlueZ 5.x package. + +[bluez]: http://www.bluez.org/ + +## Build + +``` +mkdir build +cd build +cmake .. +make +``` + +## Products + +- `libbzle.a`: Static library. +- `include/bzle`: Public header files for Bluetooth LE and GATT functions. +- `hciconfig`: The `hciconfig` tool distributed with the BlueZ package. +This tool allows users to configure Bluetooth USB dongles. + + diff --git a/drive-sdk/deps/bzle/cmake/modules/COPYING-CMAKE-MODULES b/drive-sdk/deps/bzle/cmake/modules/COPYING-CMAKE-MODULES new file mode 100644 index 0000000..d99eefb --- /dev/null +++ b/drive-sdk/deps/bzle/cmake/modules/COPYING-CMAKE-MODULES @@ -0,0 +1,23 @@ +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +1. Redistributions of source code must retain the copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. The name of the author may not be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR +IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + diff --git a/drive-sdk/deps/bzle/cmake/modules/FindGLIB2.cmake b/drive-sdk/deps/bzle/cmake/modules/FindGLIB2.cmake new file mode 100644 index 0000000..87bf6ec --- /dev/null +++ b/drive-sdk/deps/bzle/cmake/modules/FindGLIB2.cmake @@ -0,0 +1,235 @@ +# - Try to find GLib2 +# Once done this will define +# +# GLIB2_FOUND - system has GLib2 +# GLIB2_INCLUDE_DIRS - the GLib2 include directory +# GLIB2_LIBRARIES - Link these to use GLib2 +# +# HAVE_GLIB_GREGEX_H glib has gregex.h header and +# supports g_regex_match_simple +# +# Copyright (c) 2006 Andreas Schneider +# Copyright (c) 2006 Philippe Bernery +# Copyright (c) 2007 Daniel Gollub +# Copyright (c) 2007 Alban Browaeys +# Copyright (c) 2008 Michael Bell +# Copyright (c) 2008-2009 Bjoern Ricks +# +# Redistribution and use is allowed according to the terms of the New +# BSD license. +# For details see the accompanying COPYING-CMAKE-SCRIPTS file. +# + + +IF (GLIB2_LIBRARIES AND GLIB2_INCLUDE_DIRS ) + # in cache already + SET(GLIB2_FOUND TRUE) +ELSE (GLIB2_LIBRARIES AND GLIB2_INCLUDE_DIRS ) + + INCLUDE(FindPkgConfig) + + ## Glib + IF ( GLIB2_FIND_REQUIRED ) + SET( _pkgconfig_REQUIRED "REQUIRED" ) + ELSE ( GLIB2_FIND_REQUIRED ) + SET( _pkgconfig_REQUIRED "" ) + ENDIF ( GLIB2_FIND_REQUIRED ) + + IF ( GLIB2_MIN_VERSION ) + PKG_SEARCH_MODULE( GLIB2 ${_pkgconfig_REQUIRED} glib-2.0>=${GLIB2_MIN_VERSION} ) + ELSE ( GLIB2_MIN_VERSION ) + PKG_SEARCH_MODULE( GLIB2 ${_pkgconfig_REQUIRED} glib-2.0 ) + ENDIF ( GLIB2_MIN_VERSION ) + IF ( PKG_CONFIG_FOUND ) + IF ( GLIB2_FOUND ) + SET ( GLIB2_CORE_FOUND TRUE ) + ELSE ( GLIB2_FOUND ) + SET ( GLIB2_CORE_FOUND FALSE ) + ENDIF ( GLIB2_FOUND ) + ENDIF ( PKG_CONFIG_FOUND ) + + # Look for glib2 include dir and libraries w/o pkgconfig + IF ( NOT GLIB2_FOUND AND NOT PKG_CONFIG_FOUND ) + FIND_PATH( + _glibconfig_include_DIR + NAMES + glibconfig.h + PATHS + /opt/gnome/lib64 + /opt/gnome/lib + /opt/lib/ + /opt/local/lib + /sw/lib/ + /usr/lib64 + /usr/lib + /usr/local/include + ${CMAKE_LIBRARY_PATH} + PATH_SUFFIXES + glib-2.0/include + ) + + FIND_PATH( + _glib2_include_DIR + NAMES + glib.h + PATHS + /opt/gnome/include + /opt/local/include + /sw/include + /usr/include + /usr/local/include + PATH_SUFFIXES + glib-2.0 + ) + + #MESSAGE(STATUS "Glib headers: ${_glib2_include_DIR}") + + FIND_LIBRARY( + _glib2_link_DIR + NAMES + glib-2.0 + glib + PATHS + /opt/gnome/lib + /opt/local/lib + /sw/lib + /usr/lib + /usr/local/lib + ) + IF ( _glib2_include_DIR AND _glib2_link_DIR ) + SET ( _glib2_FOUND TRUE ) + ENDIF ( _glib2_include_DIR AND _glib2_link_DIR ) + + + IF ( _glib2_FOUND ) + SET ( GLIB2_INCLUDE_DIRS ${_glib2_include_DIR} ${_glibconfig_include_DIR} ) + SET ( GLIB2_LIBRARIES ${_glib2_link_DIR} ) + SET ( GLIB2_CORE_FOUND TRUE ) + ELSE ( _glib2_FOUND ) + SET ( GLIB2_CORE_FOUND FALSE ) + ENDIF ( _glib2_FOUND ) + + # Handle dependencies + # libintl + IF ( NOT LIBINTL_FOUND ) + FIND_PATH(LIBINTL_INCLUDE_DIR + NAMES + libintl.h + PATHS + /opt/gnome/include + /opt/local/include + /sw/include + /usr/include + /usr/local/include + ) + + FIND_LIBRARY(LIBINTL_LIBRARY + NAMES + intl + PATHS + /opt/gnome/lib + /opt/local/lib + /sw/lib + /usr/local/lib + /usr/lib + ) + + IF (LIBINTL_LIBRARY AND LIBINTL_INCLUDE_DIR) + SET (LIBINTL_FOUND TRUE) + ENDIF (LIBINTL_LIBRARY AND LIBINTL_INCLUDE_DIR) + ENDIF ( NOT LIBINTL_FOUND ) + + # libiconv + IF ( NOT LIBICONV_FOUND ) + FIND_PATH(LIBICONV_INCLUDE_DIR + NAMES + iconv.h + PATHS + /opt/gnome/include + /opt/local/include + /opt/local/include + /sw/include + /sw/include + /usr/local/include + /usr/include + PATH_SUFFIXES + glib-2.0 + ) + + FIND_LIBRARY(LIBICONV_LIBRARY + NAMES + iconv + PATHS + /opt/gnome/lib + /opt/local/lib + /sw/lib + /usr/lib + /usr/local/lib + ) + + IF (LIBICONV_LIBRARY AND LIBICONV_INCLUDE_DIR) + SET (LIBICONV_FOUND TRUE) + ENDIF (LIBICONV_LIBRARY AND LIBICONV_INCLUDE_DIR) + ENDIF ( NOT LIBICONV_FOUND ) + + IF (LIBINTL_FOUND) + SET (GLIB2_LIBRARIES ${GLIB2_LIBRARIES} ${LIBINTL_LIBRARY}) + SET (GLIB2_INCLUDE_DIRS ${GLIB2_INCLUDE_DIRS} ${LIBINTL_INCLUDE_DIR}) + ENDIF (LIBINTL_FOUND) + + IF (LIBICONV_FOUND) + SET (GLIB2_LIBRARIES ${GLIB2_LIBRARIES} ${LIBICONV_LIBRARY}) + SET (GLIB2_INCLUDE_DIRS ${GLIB2_INCLUDE_DIRS} ${LIBICONV_INCLUDE_DIR}) + ENDIF (LIBICONV_FOUND) + + ENDIF ( NOT GLIB2_FOUND AND NOT PKG_CONFIG_FOUND ) + ## + + IF (GLIB2_CORE_FOUND AND GLIB2_INCLUDE_DIRS AND GLIB2_LIBRARIES) + SET (GLIB2_FOUND TRUE) + ENDIF (GLIB2_CORE_FOUND AND GLIB2_INCLUDE_DIRS AND GLIB2_LIBRARIES) + + IF (GLIB2_FOUND) + IF (NOT GLIB2_FIND_QUIETLY) + MESSAGE (STATUS "Found GLib2: ${GLIB2_LIBRARIES} ${GLIB2_INCLUDE_DIRS}") + ENDIF (NOT GLIB2_FIND_QUIETLY) + ELSE (GLIB2_FOUND) + IF (GLIB2_FIND_REQUIRED) + MESSAGE (SEND_ERROR "Could not find GLib2") + ENDIF (GLIB2_FIND_REQUIRED) + ENDIF (GLIB2_FOUND) + + # show the GLIB2_INCLUDE_DIRS and GLIB2_LIBRARIES variables only in the advanced view + MARK_AS_ADVANCED(GLIB2_INCLUDE_DIRS GLIB2_LIBRARIES) + MARK_AS_ADVANCED(LIBICONV_INCLUDE_DIR LIBICONV_LIBRARY) + MARK_AS_ADVANCED(LIBINTL_INCLUDE_DIR LIBINTL_LIBRARY) + +ENDIF (GLIB2_LIBRARIES AND GLIB2_INCLUDE_DIRS) + +IF ( WIN32 ) + # include libiconv for win32 + IF ( NOT LIBICONV_FOUND ) + FIND_PATH(LIBICONV_INCLUDE_DIR iconv.h PATH_SUFFIXES glib-2.0) + + FIND_LIBRARY(LIBICONV_LIBRARY NAMES iconv) + + IF (LIBICONV_LIBRARY AND LIBICONV_INCLUDE_DIR) + SET (LIBICONV_FOUND TRUE) + ENDIF (LIBICONV_LIBRARY AND LIBICONV_INCLUDE_DIR) + ENDIF ( NOT LIBICONV_FOUND ) + IF (LIBICONV_FOUND) + SET (GLIB2_LIBRARIES ${GLIB2_LIBRARIES} ${LIBICONV_LIBRARY}) + SET (GLIB2_INCLUDE_DIRS ${GLIB2_INCLUDE_DIRS} ${LIBICONV_INCLUDE_DIR}) + ENDIF (LIBICONV_FOUND) +ENDIF ( WIN32 ) + +IF ( GLIB2_FOUND ) + # Check if system has a newer version of glib + # which supports g_regex_match_simple + INCLUDE( CheckIncludeFiles ) + SET( CMAKE_REQUIRED_INCLUDES ${GLIB2_INCLUDE_DIRS} ) + CHECK_INCLUDE_FILES ( glib/gregex.h HAVE_GLIB_GREGEX_H ) + CHECK_INCLUDE_FILES ( glib/gchecksum.h HAVE_GLIB_GCHECKSUM_H ) + # Reset CMAKE_REQUIRED_INCLUDES + SET( CMAKE_REQUIRED_INCLUDES "" ) +ENDIF( GLIB2_FOUND ) diff --git a/drive-sdk/deps/bzle/cmake/modules/MacroOutOfSourceBuild.cmake b/drive-sdk/deps/bzle/cmake/modules/MacroOutOfSourceBuild.cmake new file mode 100644 index 0000000..c2b1121 --- /dev/null +++ b/drive-sdk/deps/bzle/cmake/modules/MacroOutOfSourceBuild.cmake @@ -0,0 +1,13 @@ +# Ensures that we do an out of source build + +MACRO(MACRO_ENSURE_OUT_OF_SOURCE_BUILD MSG) + STRING(COMPARE EQUAL "${CMAKE_SOURCE_DIR}" +"${CMAKE_BINARY_DIR}" insource) + GET_FILENAME_COMPONENT(PARENTDIR ${CMAKE_SOURCE_DIR} PATH) + STRING(COMPARE EQUAL "${CMAKE_SOURCE_DIR}" +"${PARENTDIR}" insourcesubdir) + IF(insource OR insourcesubdir) + MESSAGE(FATAL_ERROR "${MSG}") + ENDIF(insource OR insourcesubdir) +ENDMACRO(MACRO_ENSURE_OUT_OF_SOURCE_BUILD) + diff --git a/drive-sdk/deps/bzle/include/bzle/bluetooth/bluetooth.h b/drive-sdk/deps/bzle/include/bzle/bluetooth/bluetooth.h new file mode 100644 index 0000000..61c1f9a --- /dev/null +++ b/drive-sdk/deps/bzle/include/bzle/bluetooth/bluetooth.h @@ -0,0 +1,399 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2000-2001 Qualcomm Incorporated + * Copyright (C) 2002-2003 Maxim Krasnyansky + * Copyright (C) 2002-2010 Marcel Holtmann + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifndef __BLUETOOTH_H +#define __BLUETOOTH_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include +#include +#include +#include + +#ifndef AF_BLUETOOTH +#define AF_BLUETOOTH 31 +#define PF_BLUETOOTH AF_BLUETOOTH +#endif + +#define BTPROTO_L2CAP 0 +#define BTPROTO_HCI 1 +#define BTPROTO_SCO 2 +#define BTPROTO_RFCOMM 3 +#define BTPROTO_BNEP 4 +#define BTPROTO_CMTP 5 +#define BTPROTO_HIDP 6 +#define BTPROTO_AVDTP 7 + +#define SOL_HCI 0 +#define SOL_L2CAP 6 +#define SOL_SCO 17 +#define SOL_RFCOMM 18 + +#ifndef SOL_BLUETOOTH +#define SOL_BLUETOOTH 274 +#endif + +#define BT_SECURITY 4 +struct bt_security { + uint8_t level; + uint8_t key_size; +}; +#define BT_SECURITY_SDP 0 +#define BT_SECURITY_LOW 1 +#define BT_SECURITY_MEDIUM 2 +#define BT_SECURITY_HIGH 3 + +#define BT_DEFER_SETUP 7 + +#define BT_FLUSHABLE 8 + +#define BT_FLUSHABLE_OFF 0 +#define BT_FLUSHABLE_ON 1 + +#define BT_POWER 9 +struct bt_power { + uint8_t force_active; +}; +#define BT_POWER_FORCE_ACTIVE_OFF 0 +#define BT_POWER_FORCE_ACTIVE_ON 1 + +#define BT_CHANNEL_POLICY 10 + +/* BR/EDR only (default policy) + * AMP controllers cannot be used. + * Channel move requests from the remote device are denied. + * If the L2CAP channel is currently using AMP, move the channel to BR/EDR. + */ +#define BT_CHANNEL_POLICY_BREDR_ONLY 0 + +/* BR/EDR Preferred + * Allow use of AMP controllers. + * If the L2CAP channel is currently on AMP, move it to BR/EDR. + * Channel move requests from the remote device are allowed. + */ +#define BT_CHANNEL_POLICY_BREDR_PREFERRED 1 + +/* AMP Preferred + * Allow use of AMP controllers + * If the L2CAP channel is currently on BR/EDR and AMP controller + * resources are available, initiate a channel move to AMP. + * Channel move requests from the remote device are allowed. + * If the L2CAP socket has not been connected yet, try to create + * and configure the channel directly on an AMP controller rather + * than BR/EDR. + */ +#define BT_CHANNEL_POLICY_AMP_PREFERRED 2 + +#define BT_VOICE 11 +struct bt_voice { + uint16_t setting; +}; + +#define BT_SNDMTU 12 +#define BT_RCVMTU 13 + +#define BT_VOICE_TRANSPARENT 0x0003 +#define BT_VOICE_CVSD_16BIT 0x0060 + +/* Connection and socket states */ +enum { + BT_CONNECTED = 1, /* Equal to TCP_ESTABLISHED to make net code happy */ + BT_OPEN, + BT_BOUND, + BT_LISTEN, + BT_CONNECT, + BT_CONNECT2, + BT_CONFIG, + BT_DISCONN, + BT_CLOSED +}; + +/* Byte order conversions */ +#if __BYTE_ORDER == __LITTLE_ENDIAN +#define htobs(d) (d) +#define htobl(d) (d) +#define htobll(d) (d) +#define btohs(d) (d) +#define btohl(d) (d) +#define btohll(d) (d) +#elif __BYTE_ORDER == __BIG_ENDIAN +#define htobs(d) bswap_16(d) +#define htobl(d) bswap_32(d) +#define htobll(d) bswap_64(d) +#define btohs(d) bswap_16(d) +#define btohl(d) bswap_32(d) +#define btohll(d) bswap_64(d) +#else +#error "Unknown byte order" +#endif + +/* Bluetooth unaligned access */ +#define bt_get_unaligned(ptr) \ +({ \ + struct __attribute__((packed)) { \ + typeof(*(ptr)) __v; \ + } *__p = (typeof(__p)) (ptr); \ + __p->__v; \ +}) + +#define bt_put_unaligned(val, ptr) \ +do { \ + struct __attribute__((packed)) { \ + typeof(*(ptr)) __v; \ + } *__p = (typeof(__p)) (ptr); \ + __p->__v = (val); \ +} while(0) + +#if __BYTE_ORDER == __LITTLE_ENDIAN +static inline uint64_t bt_get_le64(const void *ptr) +{ + return bt_get_unaligned((const uint64_t *) ptr); +} + +static inline uint64_t bt_get_be64(const void *ptr) +{ + return bswap_64(bt_get_unaligned((const uint64_t *) ptr)); +} + +static inline uint32_t bt_get_le32(const void *ptr) +{ + return bt_get_unaligned((const uint32_t *) ptr); +} + +static inline uint32_t bt_get_be32(const void *ptr) +{ + return bswap_32(bt_get_unaligned((const uint32_t *) ptr)); +} + +static inline uint16_t bt_get_le16(const void *ptr) +{ + return bt_get_unaligned((const uint16_t *) ptr); +} + +static inline uint16_t bt_get_be16(const void *ptr) +{ + return bswap_16(bt_get_unaligned((const uint16_t *) ptr)); +} + +static inline void bt_put_le64(uint64_t val, const void *ptr) +{ + bt_put_unaligned(val, (uint64_t *) ptr); +} + +static inline void bt_put_be64(uint64_t val, const void *ptr) +{ + bt_put_unaligned(bswap_64(val), (uint64_t *) ptr); +} + +static inline void bt_put_le32(uint32_t val, const void *ptr) +{ + bt_put_unaligned(val, (uint32_t *) ptr); +} + +static inline void bt_put_be32(uint32_t val, const void *ptr) +{ + bt_put_unaligned(bswap_32(val), (uint32_t *) ptr); +} + +static inline void bt_put_le16(uint16_t val, const void *ptr) +{ + bt_put_unaligned(val, (uint16_t *) ptr); +} + +static inline void bt_put_be16(uint16_t val, const void *ptr) +{ + bt_put_unaligned(bswap_16(val), (uint16_t *) ptr); +} + +#elif __BYTE_ORDER == __BIG_ENDIAN +static inline uint64_t bt_get_le64(const void *ptr) +{ + return bswap_64(bt_get_unaligned((const uint64_t *) ptr)); +} + +static inline uint64_t bt_get_be64(const void *ptr) +{ + return bt_get_unaligned((const uint64_t *) ptr); +} + +static inline uint32_t bt_get_le32(const void *ptr) +{ + return bswap_32(bt_get_unaligned((const uint32_t *) ptr)); +} + +static inline uint32_t bt_get_be32(const void *ptr) +{ + return bt_get_unaligned((const uint32_t *) ptr); +} + +static inline uint16_t bt_get_le16(const void *ptr) +{ + return bswap_16(bt_get_unaligned((const uint16_t *) ptr)); +} + +static inline uint16_t bt_get_be16(const void *ptr) +{ + return bt_get_unaligned((const uint16_t *) ptr); +} + +static inline void bt_put_le64(uint64_t val, const void *ptr) +{ + bt_put_unaligned(bswap_64(val), (uint64_t *) ptr); +} + +static inline void bt_put_be64(uint64_t val, const void *ptr) +{ + bt_put_unaligned(val, (uint64_t *) ptr); +} + +static inline void bt_put_le32(uint32_t val, const void *ptr) +{ + bt_put_unaligned(bswap_32(val), (uint32_t *) ptr); +} + +static inline void bt_put_be32(uint32_t val, const void *ptr) +{ + bt_put_unaligned(val, (uint32_t *) ptr); +} + +static inline void bt_put_le16(uint16_t val, const void *ptr) +{ + bt_put_unaligned(bswap_16(val), (uint16_t *) ptr); +} + +static inline void bt_put_be16(uint16_t val, const void *ptr) +{ + bt_put_unaligned(val, (uint16_t *) ptr); +} +#else +#error "Unknown byte order" +#endif + +/* BD Address */ +typedef struct { + uint8_t b[6]; +} __attribute__((packed)) bdaddr_t; + +/* BD Address type */ +#define BDADDR_BREDR 0x00 +#define BDADDR_LE_PUBLIC 0x01 +#define BDADDR_LE_RANDOM 0x02 + +#define BDADDR_ANY (&(bdaddr_t) {{0, 0, 0, 0, 0, 0}}) +#define BDADDR_ALL (&(bdaddr_t) {{0xff, 0xff, 0xff, 0xff, 0xff, 0xff}}) +#define BDADDR_LOCAL (&(bdaddr_t) {{0, 0, 0, 0xff, 0xff, 0xff}}) + +/* Copy, swap, convert BD Address */ +static inline int bacmp(const bdaddr_t *ba1, const bdaddr_t *ba2) +{ + return memcmp(ba1, ba2, sizeof(bdaddr_t)); +} +static inline void bacpy(bdaddr_t *dst, const bdaddr_t *src) +{ + memcpy(dst, src, sizeof(bdaddr_t)); +} + +void baswap(bdaddr_t *dst, const bdaddr_t *src); +bdaddr_t *strtoba(const char *str); +char *batostr(const bdaddr_t *ba); +int ba2str(const bdaddr_t *ba, char *str); +int str2ba(const char *str, bdaddr_t *ba); +int ba2oui(const bdaddr_t *ba, char *oui); +int bachk(const char *str); + +int baprintf(const char *format, ...); +int bafprintf(FILE *stream, const char *format, ...); +int basprintf(char *str, const char *format, ...); +int basnprintf(char *str, size_t size, const char *format, ...); + +void *bt_malloc(size_t size); +void bt_free(void *ptr); + +int bt_error(uint16_t code); +const char *bt_compidtostr(int id); + +typedef struct { + uint8_t data[16]; +} uint128_t; + +#if __BYTE_ORDER == __BIG_ENDIAN + +#define ntoh64(x) (x) + +static inline void ntoh128(const uint128_t *src, uint128_t *dst) +{ + memcpy(dst, src, sizeof(uint128_t)); +} + +static inline void btoh128(const uint128_t *src, uint128_t *dst) +{ + int i; + + for (i = 0; i < 16; i++) + dst->data[15 - i] = src->data[i]; +} + +#else + +static inline uint64_t ntoh64(uint64_t n) +{ + uint64_t h; + uint64_t tmp = ntohl(n & 0x00000000ffffffff); + + h = ntohl(n >> 32); + h |= tmp << 32; + + return h; +} + +static inline void ntoh128(const uint128_t *src, uint128_t *dst) +{ + int i; + + for (i = 0; i < 16; i++) + dst->data[15 - i] = src->data[i]; +} + +static inline void btoh128(const uint128_t *src, uint128_t *dst) +{ + memcpy(dst, src, sizeof(uint128_t)); +} + +#endif + +#define hton64(x) ntoh64(x) +#define hton128(x, y) ntoh128(x, y) +#define htob128(x, y) btoh128(x, y) + +#ifdef __cplusplus +} +#endif + +#endif /* __BLUETOOTH_H */ diff --git a/drive-sdk/deps/bzle/include/bzle/bluetooth/btio.h b/drive-sdk/deps/bzle/include/bzle/bluetooth/btio.h new file mode 100644 index 0000000..2dce9f0 --- /dev/null +++ b/drive-sdk/deps/bzle/include/bzle/bluetooth/btio.h @@ -0,0 +1,95 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2009-2010 Marcel Holtmann + * Copyright (C) 2009-2010 Nokia Corporation + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ +#ifndef BT_IO_H +#define BT_IO_H + +#include + +#define BT_IO_ERROR bt_io_error_quark() + +GQuark bt_io_error_quark(void); + +typedef enum { + BT_IO_OPT_INVALID = 0, + BT_IO_OPT_SOURCE, + BT_IO_OPT_SOURCE_BDADDR, + BT_IO_OPT_SOURCE_TYPE, + BT_IO_OPT_DEST, + BT_IO_OPT_DEST_BDADDR, + BT_IO_OPT_DEST_TYPE, + BT_IO_OPT_DEFER_TIMEOUT, + BT_IO_OPT_SEC_LEVEL, + BT_IO_OPT_KEY_SIZE, + BT_IO_OPT_CHANNEL, + BT_IO_OPT_SOURCE_CHANNEL, + BT_IO_OPT_DEST_CHANNEL, + BT_IO_OPT_PSM, + BT_IO_OPT_CID, + BT_IO_OPT_MTU, + BT_IO_OPT_OMTU, + BT_IO_OPT_IMTU, + BT_IO_OPT_MASTER, + BT_IO_OPT_HANDLE, + BT_IO_OPT_CLASS, + BT_IO_OPT_MODE, + BT_IO_OPT_FLUSHABLE, + BT_IO_OPT_PRIORITY, + BT_IO_OPT_VOICE, +} BtIOOption; + +typedef enum { + BT_IO_SEC_SDP = 0, + BT_IO_SEC_LOW, + BT_IO_SEC_MEDIUM, + BT_IO_SEC_HIGH, +} BtIOSecLevel; + +typedef enum { + BT_IO_MODE_BASIC = 0, + BT_IO_MODE_RETRANS, + BT_IO_MODE_FLOWCTL, + BT_IO_MODE_ERTM, + BT_IO_MODE_STREAMING +} BtIOMode; + +typedef void (*BtIOConfirm)(GIOChannel *io, gpointer user_data); + +typedef void (*BtIOConnect)(GIOChannel *io, GError *err, gpointer user_data); + +gboolean bt_io_accept(GIOChannel *io, BtIOConnect connect, gpointer user_data, + GDestroyNotify destroy, GError **err); + +gboolean bt_io_set(GIOChannel *io, GError **err, BtIOOption opt1, ...); + +gboolean bt_io_get(GIOChannel *io, GError **err, BtIOOption opt1, ...); + +GIOChannel *bt_io_connect(BtIOConnect connect, gpointer user_data, + GDestroyNotify destroy, GError **gerr, + BtIOOption opt1, ...); + +GIOChannel *bt_io_listen(BtIOConnect connect, BtIOConfirm confirm, + gpointer user_data, GDestroyNotify destroy, + GError **err, BtIOOption opt1, ...); + +#endif diff --git a/drive-sdk/deps/bzle/include/bzle/bluetooth/hci.h b/drive-sdk/deps/bzle/include/bzle/bluetooth/hci.h new file mode 100644 index 0000000..0c94829 --- /dev/null +++ b/drive-sdk/deps/bzle/include/bzle/bluetooth/hci.h @@ -0,0 +1,2418 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2000-2001 Qualcomm Incorporated + * Copyright (C) 2002-2003 Maxim Krasnyansky + * Copyright (C) 2002-2010 Marcel Holtmann + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifndef __HCI_H +#define __HCI_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define HCI_MAX_DEV 16 + +#define HCI_MAX_ACL_SIZE (1492 + 4) +#define HCI_MAX_SCO_SIZE 255 +#define HCI_MAX_EVENT_SIZE 260 +#define HCI_MAX_FRAME_SIZE (HCI_MAX_ACL_SIZE + 4) + +/* HCI dev events */ +#define HCI_DEV_REG 1 +#define HCI_DEV_UNREG 2 +#define HCI_DEV_UP 3 +#define HCI_DEV_DOWN 4 +#define HCI_DEV_SUSPEND 5 +#define HCI_DEV_RESUME 6 + +/* HCI bus types */ +#define HCI_VIRTUAL 0 +#define HCI_USB 1 +#define HCI_PCCARD 2 +#define HCI_UART 3 +#define HCI_RS232 4 +#define HCI_PCI 5 +#define HCI_SDIO 6 + +/* HCI controller types */ +#define HCI_BREDR 0x00 +#define HCI_AMP 0x01 + +/* HCI device flags */ +enum { + HCI_UP, + HCI_INIT, + HCI_RUNNING, + + HCI_PSCAN, + HCI_ISCAN, + HCI_AUTH, + HCI_ENCRYPT, + HCI_INQUIRY, + + HCI_RAW, +}; + +/* LE address type */ +enum { + LE_PUBLIC_ADDRESS = 0x00, + LE_RANDOM_ADDRESS = 0x01 +}; + +/* HCI ioctl defines */ +#define HCIDEVUP _IOW('H', 201, int) +#define HCIDEVDOWN _IOW('H', 202, int) +#define HCIDEVRESET _IOW('H', 203, int) +#define HCIDEVRESTAT _IOW('H', 204, int) + +#define HCIGETDEVLIST _IOR('H', 210, int) +#define HCIGETDEVINFO _IOR('H', 211, int) +#define HCIGETCONNLIST _IOR('H', 212, int) +#define HCIGETCONNINFO _IOR('H', 213, int) +#define HCIGETAUTHINFO _IOR('H', 215, int) + +#define HCISETRAW _IOW('H', 220, int) +#define HCISETSCAN _IOW('H', 221, int) +#define HCISETAUTH _IOW('H', 222, int) +#define HCISETENCRYPT _IOW('H', 223, int) +#define HCISETPTYPE _IOW('H', 224, int) +#define HCISETLINKPOL _IOW('H', 225, int) +#define HCISETLINKMODE _IOW('H', 226, int) +#define HCISETACLMTU _IOW('H', 227, int) +#define HCISETSCOMTU _IOW('H', 228, int) + +#define HCIBLOCKADDR _IOW('H', 230, int) +#define HCIUNBLOCKADDR _IOW('H', 231, int) + +#define HCIINQUIRY _IOR('H', 240, int) + +#ifndef __NO_HCI_DEFS + +/* HCI Packet types */ +#define HCI_COMMAND_PKT 0x01 +#define HCI_ACLDATA_PKT 0x02 +#define HCI_SCODATA_PKT 0x03 +#define HCI_EVENT_PKT 0x04 +#define HCI_VENDOR_PKT 0xff + +/* HCI Packet types */ +#define HCI_2DH1 0x0002 +#define HCI_3DH1 0x0004 +#define HCI_DM1 0x0008 +#define HCI_DH1 0x0010 +#define HCI_2DH3 0x0100 +#define HCI_3DH3 0x0200 +#define HCI_DM3 0x0400 +#define HCI_DH3 0x0800 +#define HCI_2DH5 0x1000 +#define HCI_3DH5 0x2000 +#define HCI_DM5 0x4000 +#define HCI_DH5 0x8000 + +#define HCI_HV1 0x0020 +#define HCI_HV2 0x0040 +#define HCI_HV3 0x0080 + +#define HCI_EV3 0x0008 +#define HCI_EV4 0x0010 +#define HCI_EV5 0x0020 +#define HCI_2EV3 0x0040 +#define HCI_3EV3 0x0080 +#define HCI_2EV5 0x0100 +#define HCI_3EV5 0x0200 + +#define SCO_PTYPE_MASK (HCI_HV1 | HCI_HV2 | HCI_HV3) +#define ACL_PTYPE_MASK (HCI_DM1 | HCI_DH1 | HCI_DM3 | HCI_DH3 | HCI_DM5 | HCI_DH5) + +/* HCI Error codes */ +#define HCI_UNKNOWN_COMMAND 0x01 +#define HCI_NO_CONNECTION 0x02 +#define HCI_HARDWARE_FAILURE 0x03 +#define HCI_PAGE_TIMEOUT 0x04 +#define HCI_AUTHENTICATION_FAILURE 0x05 +#define HCI_PIN_OR_KEY_MISSING 0x06 +#define HCI_MEMORY_FULL 0x07 +#define HCI_CONNECTION_TIMEOUT 0x08 +#define HCI_MAX_NUMBER_OF_CONNECTIONS 0x09 +#define HCI_MAX_NUMBER_OF_SCO_CONNECTIONS 0x0a +#define HCI_ACL_CONNECTION_EXISTS 0x0b +#define HCI_COMMAND_DISALLOWED 0x0c +#define HCI_REJECTED_LIMITED_RESOURCES 0x0d +#define HCI_REJECTED_SECURITY 0x0e +#define HCI_REJECTED_PERSONAL 0x0f +#define HCI_HOST_TIMEOUT 0x10 +#define HCI_UNSUPPORTED_FEATURE 0x11 +#define HCI_INVALID_PARAMETERS 0x12 +#define HCI_OE_USER_ENDED_CONNECTION 0x13 +#define HCI_OE_LOW_RESOURCES 0x14 +#define HCI_OE_POWER_OFF 0x15 +#define HCI_CONNECTION_TERMINATED 0x16 +#define HCI_REPEATED_ATTEMPTS 0x17 +#define HCI_PAIRING_NOT_ALLOWED 0x18 +#define HCI_UNKNOWN_LMP_PDU 0x19 +#define HCI_UNSUPPORTED_REMOTE_FEATURE 0x1a +#define HCI_SCO_OFFSET_REJECTED 0x1b +#define HCI_SCO_INTERVAL_REJECTED 0x1c +#define HCI_AIR_MODE_REJECTED 0x1d +#define HCI_INVALID_LMP_PARAMETERS 0x1e +#define HCI_UNSPECIFIED_ERROR 0x1f +#define HCI_UNSUPPORTED_LMP_PARAMETER_VALUE 0x20 +#define HCI_ROLE_CHANGE_NOT_ALLOWED 0x21 +#define HCI_LMP_RESPONSE_TIMEOUT 0x22 +#define HCI_LMP_ERROR_TRANSACTION_COLLISION 0x23 +#define HCI_LMP_PDU_NOT_ALLOWED 0x24 +#define HCI_ENCRYPTION_MODE_NOT_ACCEPTED 0x25 +#define HCI_UNIT_LINK_KEY_USED 0x26 +#define HCI_QOS_NOT_SUPPORTED 0x27 +#define HCI_INSTANT_PASSED 0x28 +#define HCI_PAIRING_NOT_SUPPORTED 0x29 +#define HCI_TRANSACTION_COLLISION 0x2a +#define HCI_QOS_UNACCEPTABLE_PARAMETER 0x2c +#define HCI_QOS_REJECTED 0x2d +#define HCI_CLASSIFICATION_NOT_SUPPORTED 0x2e +#define HCI_INSUFFICIENT_SECURITY 0x2f +#define HCI_PARAMETER_OUT_OF_RANGE 0x30 +#define HCI_ROLE_SWITCH_PENDING 0x32 +#define HCI_SLOT_VIOLATION 0x34 +#define HCI_ROLE_SWITCH_FAILED 0x35 +#define HCI_EIR_TOO_LARGE 0x36 +#define HCI_SIMPLE_PAIRING_NOT_SUPPORTED 0x37 +#define HCI_HOST_BUSY_PAIRING 0x38 + +/* ACL flags */ +#define ACL_START_NO_FLUSH 0x00 +#define ACL_CONT 0x01 +#define ACL_START 0x02 +#define ACL_ACTIVE_BCAST 0x04 +#define ACL_PICO_BCAST 0x08 + +/* Baseband links */ +#define SCO_LINK 0x00 +#define ACL_LINK 0x01 +#define ESCO_LINK 0x02 + +/* LMP features */ +#define LMP_3SLOT 0x01 +#define LMP_5SLOT 0x02 +#define LMP_ENCRYPT 0x04 +#define LMP_SOFFSET 0x08 +#define LMP_TACCURACY 0x10 +#define LMP_RSWITCH 0x20 +#define LMP_HOLD 0x40 +#define LMP_SNIFF 0x80 + +#define LMP_PARK 0x01 +#define LMP_RSSI 0x02 +#define LMP_QUALITY 0x04 +#define LMP_SCO 0x08 +#define LMP_HV2 0x10 +#define LMP_HV3 0x20 +#define LMP_ULAW 0x40 +#define LMP_ALAW 0x80 + +#define LMP_CVSD 0x01 +#define LMP_PSCHEME 0x02 +#define LMP_PCONTROL 0x04 +#define LMP_TRSP_SCO 0x08 +#define LMP_BCAST_ENC 0x80 + +#define LMP_EDR_ACL_2M 0x02 +#define LMP_EDR_ACL_3M 0x04 +#define LMP_ENH_ISCAN 0x08 +#define LMP_ILACE_ISCAN 0x10 +#define LMP_ILACE_PSCAN 0x20 +#define LMP_RSSI_INQ 0x40 +#define LMP_ESCO 0x80 + +#define LMP_EV4 0x01 +#define LMP_EV5 0x02 +#define LMP_AFH_CAP_SLV 0x08 +#define LMP_AFH_CLS_SLV 0x10 +#define LMP_NO_BREDR 0x20 +#define LMP_LE 0x40 +#define LMP_EDR_3SLOT 0x80 + +#define LMP_EDR_5SLOT 0x01 +#define LMP_SNIFF_SUBR 0x02 +#define LMP_PAUSE_ENC 0x04 +#define LMP_AFH_CAP_MST 0x08 +#define LMP_AFH_CLS_MST 0x10 +#define LMP_EDR_ESCO_2M 0x20 +#define LMP_EDR_ESCO_3M 0x40 +#define LMP_EDR_3S_ESCO 0x80 + +#define LMP_EXT_INQ 0x01 +#define LMP_LE_BREDR 0x02 +#define LMP_SIMPLE_PAIR 0x08 +#define LMP_ENCAPS_PDU 0x10 +#define LMP_ERR_DAT_REP 0x20 +#define LMP_NFLUSH_PKTS 0x40 + +#define LMP_LSTO 0x01 +#define LMP_INQ_TX_PWR 0x02 +#define LMP_EPC 0x04 +#define LMP_EXT_FEAT 0x80 + +/* Extended LMP features */ +#define LMP_HOST_SSP 0x01 +#define LMP_HOST_LE 0x02 +#define LMP_HOST_LE_BREDR 0x04 + +/* Link policies */ +#define HCI_LP_RSWITCH 0x0001 +#define HCI_LP_HOLD 0x0002 +#define HCI_LP_SNIFF 0x0004 +#define HCI_LP_PARK 0x0008 + +/* Link mode */ +#define HCI_LM_ACCEPT 0x8000 +#define HCI_LM_MASTER 0x0001 +#define HCI_LM_AUTH 0x0002 +#define HCI_LM_ENCRYPT 0x0004 +#define HCI_LM_TRUSTED 0x0008 +#define HCI_LM_RELIABLE 0x0010 +#define HCI_LM_SECURE 0x0020 + +/* Link Key types */ +#define HCI_LK_COMBINATION 0x00 +#define HCI_LK_LOCAL_UNIT 0x01 +#define HCI_LK_REMOTE_UNIT 0x02 +#define HCI_LK_DEBUG_COMBINATION 0x03 +#define HCI_LK_UNAUTH_COMBINATION 0x04 +#define HCI_LK_AUTH_COMBINATION 0x05 +#define HCI_LK_CHANGED_COMBINATION 0x06 +#define HCI_LK_INVALID 0xFF + +/* ----- HCI Commands ----- */ + +/* Link Control */ +#define OGF_LINK_CTL 0x01 + +#define OCF_INQUIRY 0x0001 +typedef struct { + uint8_t lap[3]; + uint8_t length; /* 1.28s units */ + uint8_t num_rsp; +} __attribute__ ((packed)) inquiry_cp; +#define INQUIRY_CP_SIZE 5 + +typedef struct { + uint8_t status; + bdaddr_t bdaddr; +} __attribute__ ((packed)) status_bdaddr_rp; +#define STATUS_BDADDR_RP_SIZE 7 + +#define OCF_INQUIRY_CANCEL 0x0002 + +#define OCF_PERIODIC_INQUIRY 0x0003 +typedef struct { + uint16_t max_period; /* 1.28s units */ + uint16_t min_period; /* 1.28s units */ + uint8_t lap[3]; + uint8_t length; /* 1.28s units */ + uint8_t num_rsp; +} __attribute__ ((packed)) periodic_inquiry_cp; +#define PERIODIC_INQUIRY_CP_SIZE 9 + +#define OCF_EXIT_PERIODIC_INQUIRY 0x0004 + +#define OCF_CREATE_CONN 0x0005 +typedef struct { + bdaddr_t bdaddr; + uint16_t pkt_type; + uint8_t pscan_rep_mode; + uint8_t pscan_mode; + uint16_t clock_offset; + uint8_t role_switch; +} __attribute__ ((packed)) create_conn_cp; +#define CREATE_CONN_CP_SIZE 13 + +#define OCF_DISCONNECT 0x0006 +typedef struct { + uint16_t handle; + uint8_t reason; +} __attribute__ ((packed)) disconnect_cp; +#define DISCONNECT_CP_SIZE 3 + +#define OCF_ADD_SCO 0x0007 +typedef struct { + uint16_t handle; + uint16_t pkt_type; +} __attribute__ ((packed)) add_sco_cp; +#define ADD_SCO_CP_SIZE 4 + +#define OCF_CREATE_CONN_CANCEL 0x0008 +typedef struct { + bdaddr_t bdaddr; +} __attribute__ ((packed)) create_conn_cancel_cp; +#define CREATE_CONN_CANCEL_CP_SIZE 6 + +#define OCF_ACCEPT_CONN_REQ 0x0009 +typedef struct { + bdaddr_t bdaddr; + uint8_t role; +} __attribute__ ((packed)) accept_conn_req_cp; +#define ACCEPT_CONN_REQ_CP_SIZE 7 + +#define OCF_REJECT_CONN_REQ 0x000A +typedef struct { + bdaddr_t bdaddr; + uint8_t reason; +} __attribute__ ((packed)) reject_conn_req_cp; +#define REJECT_CONN_REQ_CP_SIZE 7 + +#define OCF_LINK_KEY_REPLY 0x000B +typedef struct { + bdaddr_t bdaddr; + uint8_t link_key[16]; +} __attribute__ ((packed)) link_key_reply_cp; +#define LINK_KEY_REPLY_CP_SIZE 22 + +#define OCF_LINK_KEY_NEG_REPLY 0x000C + +#define OCF_PIN_CODE_REPLY 0x000D +typedef struct { + bdaddr_t bdaddr; + uint8_t pin_len; + uint8_t pin_code[16]; +} __attribute__ ((packed)) pin_code_reply_cp; +#define PIN_CODE_REPLY_CP_SIZE 23 + +#define OCF_PIN_CODE_NEG_REPLY 0x000E + +#define OCF_SET_CONN_PTYPE 0x000F +typedef struct { + uint16_t handle; + uint16_t pkt_type; +} __attribute__ ((packed)) set_conn_ptype_cp; +#define SET_CONN_PTYPE_CP_SIZE 4 + +#define OCF_AUTH_REQUESTED 0x0011 +typedef struct { + uint16_t handle; +} __attribute__ ((packed)) auth_requested_cp; +#define AUTH_REQUESTED_CP_SIZE 2 + +#define OCF_SET_CONN_ENCRYPT 0x0013 +typedef struct { + uint16_t handle; + uint8_t encrypt; +} __attribute__ ((packed)) set_conn_encrypt_cp; +#define SET_CONN_ENCRYPT_CP_SIZE 3 + +#define OCF_CHANGE_CONN_LINK_KEY 0x0015 +typedef struct { + uint16_t handle; +} __attribute__ ((packed)) change_conn_link_key_cp; +#define CHANGE_CONN_LINK_KEY_CP_SIZE 2 + +#define OCF_MASTER_LINK_KEY 0x0017 +typedef struct { + uint8_t key_flag; +} __attribute__ ((packed)) master_link_key_cp; +#define MASTER_LINK_KEY_CP_SIZE 1 + +#define OCF_REMOTE_NAME_REQ 0x0019 +typedef struct { + bdaddr_t bdaddr; + uint8_t pscan_rep_mode; + uint8_t pscan_mode; + uint16_t clock_offset; +} __attribute__ ((packed)) remote_name_req_cp; +#define REMOTE_NAME_REQ_CP_SIZE 10 + +#define OCF_REMOTE_NAME_REQ_CANCEL 0x001A +typedef struct { + bdaddr_t bdaddr; +} __attribute__ ((packed)) remote_name_req_cancel_cp; +#define REMOTE_NAME_REQ_CANCEL_CP_SIZE 6 + +#define OCF_READ_REMOTE_FEATURES 0x001B +typedef struct { + uint16_t handle; +} __attribute__ ((packed)) read_remote_features_cp; +#define READ_REMOTE_FEATURES_CP_SIZE 2 + +#define OCF_READ_REMOTE_EXT_FEATURES 0x001C +typedef struct { + uint16_t handle; + uint8_t page_num; +} __attribute__ ((packed)) read_remote_ext_features_cp; +#define READ_REMOTE_EXT_FEATURES_CP_SIZE 3 + +#define OCF_READ_REMOTE_VERSION 0x001D +typedef struct { + uint16_t handle; +} __attribute__ ((packed)) read_remote_version_cp; +#define READ_REMOTE_VERSION_CP_SIZE 2 + +#define OCF_READ_CLOCK_OFFSET 0x001F +typedef struct { + uint16_t handle; +} __attribute__ ((packed)) read_clock_offset_cp; +#define READ_CLOCK_OFFSET_CP_SIZE 2 + +#define OCF_READ_LMP_HANDLE 0x0020 + +#define OCF_SETUP_SYNC_CONN 0x0028 +typedef struct { + uint16_t handle; + uint32_t tx_bandwith; + uint32_t rx_bandwith; + uint16_t max_latency; + uint16_t voice_setting; + uint8_t retrans_effort; + uint16_t pkt_type; +} __attribute__ ((packed)) setup_sync_conn_cp; +#define SETUP_SYNC_CONN_CP_SIZE 17 + +#define OCF_ACCEPT_SYNC_CONN_REQ 0x0029 +typedef struct { + bdaddr_t bdaddr; + uint32_t tx_bandwith; + uint32_t rx_bandwith; + uint16_t max_latency; + uint16_t voice_setting; + uint8_t retrans_effort; + uint16_t pkt_type; +} __attribute__ ((packed)) accept_sync_conn_req_cp; +#define ACCEPT_SYNC_CONN_REQ_CP_SIZE 21 + +#define OCF_REJECT_SYNC_CONN_REQ 0x002A +typedef struct { + bdaddr_t bdaddr; + uint8_t reason; +} __attribute__ ((packed)) reject_sync_conn_req_cp; +#define REJECT_SYNC_CONN_REQ_CP_SIZE 7 + +#define OCF_IO_CAPABILITY_REPLY 0x002B +typedef struct { + bdaddr_t bdaddr; + uint8_t capability; + uint8_t oob_data; + uint8_t authentication; +} __attribute__ ((packed)) io_capability_reply_cp; +#define IO_CAPABILITY_REPLY_CP_SIZE 9 + +#define OCF_USER_CONFIRM_REPLY 0x002C +typedef struct { + bdaddr_t bdaddr; +} __attribute__ ((packed)) user_confirm_reply_cp; +#define USER_CONFIRM_REPLY_CP_SIZE 6 + +#define OCF_USER_CONFIRM_NEG_REPLY 0x002D + +#define OCF_USER_PASSKEY_REPLY 0x002E +typedef struct { + bdaddr_t bdaddr; + uint32_t passkey; +} __attribute__ ((packed)) user_passkey_reply_cp; +#define USER_PASSKEY_REPLY_CP_SIZE 10 + +#define OCF_USER_PASSKEY_NEG_REPLY 0x002F + +#define OCF_REMOTE_OOB_DATA_REPLY 0x0030 +typedef struct { + bdaddr_t bdaddr; + uint8_t hash[16]; + uint8_t randomizer[16]; +} __attribute__ ((packed)) remote_oob_data_reply_cp; +#define REMOTE_OOB_DATA_REPLY_CP_SIZE 38 + +#define OCF_REMOTE_OOB_DATA_NEG_REPLY 0x0033 + +#define OCF_IO_CAPABILITY_NEG_REPLY 0x0034 +typedef struct { + bdaddr_t bdaddr; + uint8_t reason; +} __attribute__ ((packed)) io_capability_neg_reply_cp; +#define IO_CAPABILITY_NEG_REPLY_CP_SIZE 7 + +#define OCF_CREATE_PHYSICAL_LINK 0x0035 +typedef struct { + uint8_t handle; + uint8_t key_length; + uint8_t key_type; + uint8_t key[32]; +} __attribute__ ((packed)) create_physical_link_cp; +#define CREATE_PHYSICAL_LINK_CP_SIZE 35 + +#define OCF_ACCEPT_PHYSICAL_LINK 0x0036 +typedef struct { + uint8_t handle; + uint8_t key_length; + uint8_t key_type; + uint8_t key[32]; +} __attribute__ ((packed)) accept_physical_link_cp; +#define ACCEPT_PHYSICAL_LINK_CP_SIZE 35 + +#define OCF_DISCONNECT_PHYSICAL_LINK 0x0037 +typedef struct { + uint8_t handle; + uint8_t reason; +} __attribute__ ((packed)) disconnect_physical_link_cp; +#define DISCONNECT_PHYSICAL_LINK_CP_SIZE 2 + +#define OCF_CREATE_LOGICAL_LINK 0x0038 +typedef struct { + uint8_t handle; + uint8_t tx_flow[16]; + uint8_t rx_flow[16]; +} __attribute__ ((packed)) create_logical_link_cp; +#define CREATE_LOGICAL_LINK_CP_SIZE 33 + +#define OCF_ACCEPT_LOGICAL_LINK 0x0039 + +#define OCF_DISCONNECT_LOGICAL_LINK 0x003A +typedef struct { + uint16_t handle; +} __attribute__ ((packed)) disconnect_logical_link_cp; +#define DISCONNECT_LOGICAL_LINK_CP_SIZE 2 + +#define OCF_LOGICAL_LINK_CANCEL 0x003B +typedef struct { + uint8_t handle; + uint8_t tx_flow_id; +} __attribute__ ((packed)) cancel_logical_link_cp; +#define LOGICAL_LINK_CANCEL_CP_SIZE 2 +typedef struct { + uint8_t status; + uint8_t handle; + uint8_t tx_flow_id; +} __attribute__ ((packed)) cancel_logical_link_rp; +#define LOGICAL_LINK_CANCEL_RP_SIZE 3 + +#define OCF_FLOW_SPEC_MODIFY 0x003C + +/* Link Policy */ +#define OGF_LINK_POLICY 0x02 + +#define OCF_HOLD_MODE 0x0001 +typedef struct { + uint16_t handle; + uint16_t max_interval; + uint16_t min_interval; +} __attribute__ ((packed)) hold_mode_cp; +#define HOLD_MODE_CP_SIZE 6 + +#define OCF_SNIFF_MODE 0x0003 +typedef struct { + uint16_t handle; + uint16_t max_interval; + uint16_t min_interval; + uint16_t attempt; + uint16_t timeout; +} __attribute__ ((packed)) sniff_mode_cp; +#define SNIFF_MODE_CP_SIZE 10 + +#define OCF_EXIT_SNIFF_MODE 0x0004 +typedef struct { + uint16_t handle; +} __attribute__ ((packed)) exit_sniff_mode_cp; +#define EXIT_SNIFF_MODE_CP_SIZE 2 + +#define OCF_PARK_MODE 0x0005 +typedef struct { + uint16_t handle; + uint16_t max_interval; + uint16_t min_interval; +} __attribute__ ((packed)) park_mode_cp; +#define PARK_MODE_CP_SIZE 6 + +#define OCF_EXIT_PARK_MODE 0x0006 +typedef struct { + uint16_t handle; +} __attribute__ ((packed)) exit_park_mode_cp; +#define EXIT_PARK_MODE_CP_SIZE 2 + +#define OCF_QOS_SETUP 0x0007 +typedef struct { + uint8_t service_type; /* 1 = best effort */ + uint32_t token_rate; /* Byte per seconds */ + uint32_t peak_bandwidth; /* Byte per seconds */ + uint32_t latency; /* Microseconds */ + uint32_t delay_variation; /* Microseconds */ +} __attribute__ ((packed)) hci_qos; +#define HCI_QOS_CP_SIZE 17 +typedef struct { + uint16_t handle; + uint8_t flags; /* Reserved */ + hci_qos qos; +} __attribute__ ((packed)) qos_setup_cp; +#define QOS_SETUP_CP_SIZE (3 + HCI_QOS_CP_SIZE) + +#define OCF_ROLE_DISCOVERY 0x0009 +typedef struct { + uint16_t handle; +} __attribute__ ((packed)) role_discovery_cp; +#define ROLE_DISCOVERY_CP_SIZE 2 +typedef struct { + uint8_t status; + uint16_t handle; + uint8_t role; +} __attribute__ ((packed)) role_discovery_rp; +#define ROLE_DISCOVERY_RP_SIZE 4 + +#define OCF_SWITCH_ROLE 0x000B +typedef struct { + bdaddr_t bdaddr; + uint8_t role; +} __attribute__ ((packed)) switch_role_cp; +#define SWITCH_ROLE_CP_SIZE 7 + +#define OCF_READ_LINK_POLICY 0x000C +typedef struct { + uint16_t handle; +} __attribute__ ((packed)) read_link_policy_cp; +#define READ_LINK_POLICY_CP_SIZE 2 +typedef struct { + uint8_t status; + uint16_t handle; + uint16_t policy; +} __attribute__ ((packed)) read_link_policy_rp; +#define READ_LINK_POLICY_RP_SIZE 5 + +#define OCF_WRITE_LINK_POLICY 0x000D +typedef struct { + uint16_t handle; + uint16_t policy; +} __attribute__ ((packed)) write_link_policy_cp; +#define WRITE_LINK_POLICY_CP_SIZE 4 +typedef struct { + uint8_t status; + uint16_t handle; +} __attribute__ ((packed)) write_link_policy_rp; +#define WRITE_LINK_POLICY_RP_SIZE 3 + +#define OCF_READ_DEFAULT_LINK_POLICY 0x000E + +#define OCF_WRITE_DEFAULT_LINK_POLICY 0x000F + +#define OCF_FLOW_SPECIFICATION 0x0010 + +#define OCF_SNIFF_SUBRATING 0x0011 +typedef struct { + uint16_t handle; + uint16_t max_latency; + uint16_t min_remote_timeout; + uint16_t min_local_timeout; +} __attribute__ ((packed)) sniff_subrating_cp; +#define SNIFF_SUBRATING_CP_SIZE 8 + +/* Host Controller and Baseband */ +#define OGF_HOST_CTL 0x03 + +#define OCF_SET_EVENT_MASK 0x0001 +typedef struct { + uint8_t mask[8]; +} __attribute__ ((packed)) set_event_mask_cp; +#define SET_EVENT_MASK_CP_SIZE 8 + +#define OCF_RESET 0x0003 + +#define OCF_SET_EVENT_FLT 0x0005 +typedef struct { + uint8_t flt_type; + uint8_t cond_type; + uint8_t condition[0]; +} __attribute__ ((packed)) set_event_flt_cp; +#define SET_EVENT_FLT_CP_SIZE 2 + +/* Filter types */ +#define FLT_CLEAR_ALL 0x00 +#define FLT_INQ_RESULT 0x01 +#define FLT_CONN_SETUP 0x02 +/* INQ_RESULT Condition types */ +#define INQ_RESULT_RETURN_ALL 0x00 +#define INQ_RESULT_RETURN_CLASS 0x01 +#define INQ_RESULT_RETURN_BDADDR 0x02 +/* CONN_SETUP Condition types */ +#define CONN_SETUP_ALLOW_ALL 0x00 +#define CONN_SETUP_ALLOW_CLASS 0x01 +#define CONN_SETUP_ALLOW_BDADDR 0x02 +/* CONN_SETUP Conditions */ +#define CONN_SETUP_AUTO_OFF 0x01 +#define CONN_SETUP_AUTO_ON 0x02 + +#define OCF_FLUSH 0x0008 + +#define OCF_READ_PIN_TYPE 0x0009 +typedef struct { + uint8_t status; + uint8_t pin_type; +} __attribute__ ((packed)) read_pin_type_rp; +#define READ_PIN_TYPE_RP_SIZE 2 + +#define OCF_WRITE_PIN_TYPE 0x000A +typedef struct { + uint8_t pin_type; +} __attribute__ ((packed)) write_pin_type_cp; +#define WRITE_PIN_TYPE_CP_SIZE 1 + +#define OCF_CREATE_NEW_UNIT_KEY 0x000B + +#define OCF_READ_STORED_LINK_KEY 0x000D +typedef struct { + bdaddr_t bdaddr; + uint8_t read_all; +} __attribute__ ((packed)) read_stored_link_key_cp; +#define READ_STORED_LINK_KEY_CP_SIZE 7 +typedef struct { + uint8_t status; + uint16_t max_keys; + uint16_t num_keys; +} __attribute__ ((packed)) read_stored_link_key_rp; +#define READ_STORED_LINK_KEY_RP_SIZE 5 + +#define OCF_WRITE_STORED_LINK_KEY 0x0011 +typedef struct { + uint8_t num_keys; + /* variable length part */ +} __attribute__ ((packed)) write_stored_link_key_cp; +#define WRITE_STORED_LINK_KEY_CP_SIZE 1 +typedef struct { + uint8_t status; + uint8_t num_keys; +} __attribute__ ((packed)) write_stored_link_key_rp; +#define READ_WRITE_LINK_KEY_RP_SIZE 2 + +#define OCF_DELETE_STORED_LINK_KEY 0x0012 +typedef struct { + bdaddr_t bdaddr; + uint8_t delete_all; +} __attribute__ ((packed)) delete_stored_link_key_cp; +#define DELETE_STORED_LINK_KEY_CP_SIZE 7 +typedef struct { + uint8_t status; + uint16_t num_keys; +} __attribute__ ((packed)) delete_stored_link_key_rp; +#define DELETE_STORED_LINK_KEY_RP_SIZE 3 + +#define HCI_MAX_NAME_LENGTH 248 + +#define OCF_CHANGE_LOCAL_NAME 0x0013 +typedef struct { + uint8_t name[HCI_MAX_NAME_LENGTH]; +} __attribute__ ((packed)) change_local_name_cp; +#define CHANGE_LOCAL_NAME_CP_SIZE 248 + +#define OCF_READ_LOCAL_NAME 0x0014 +typedef struct { + uint8_t status; + uint8_t name[HCI_MAX_NAME_LENGTH]; +} __attribute__ ((packed)) read_local_name_rp; +#define READ_LOCAL_NAME_RP_SIZE 249 + +#define OCF_READ_CONN_ACCEPT_TIMEOUT 0x0015 +typedef struct { + uint8_t status; + uint16_t timeout; +} __attribute__ ((packed)) read_conn_accept_timeout_rp; +#define READ_CONN_ACCEPT_TIMEOUT_RP_SIZE 3 + +#define OCF_WRITE_CONN_ACCEPT_TIMEOUT 0x0016 +typedef struct { + uint16_t timeout; +} __attribute__ ((packed)) write_conn_accept_timeout_cp; +#define WRITE_CONN_ACCEPT_TIMEOUT_CP_SIZE 2 + +#define OCF_READ_PAGE_TIMEOUT 0x0017 +typedef struct { + uint8_t status; + uint16_t timeout; +} __attribute__ ((packed)) read_page_timeout_rp; +#define READ_PAGE_TIMEOUT_RP_SIZE 3 + +#define OCF_WRITE_PAGE_TIMEOUT 0x0018 +typedef struct { + uint16_t timeout; +} __attribute__ ((packed)) write_page_timeout_cp; +#define WRITE_PAGE_TIMEOUT_CP_SIZE 2 + +#define OCF_READ_SCAN_ENABLE 0x0019 +typedef struct { + uint8_t status; + uint8_t enable; +} __attribute__ ((packed)) read_scan_enable_rp; +#define READ_SCAN_ENABLE_RP_SIZE 2 + +#define OCF_WRITE_SCAN_ENABLE 0x001A + #define SCAN_DISABLED 0x00 + #define SCAN_INQUIRY 0x01 + #define SCAN_PAGE 0x02 + +#define OCF_READ_PAGE_ACTIVITY 0x001B +typedef struct { + uint8_t status; + uint16_t interval; + uint16_t window; +} __attribute__ ((packed)) read_page_activity_rp; +#define READ_PAGE_ACTIVITY_RP_SIZE 5 + +#define OCF_WRITE_PAGE_ACTIVITY 0x001C +typedef struct { + uint16_t interval; + uint16_t window; +} __attribute__ ((packed)) write_page_activity_cp; +#define WRITE_PAGE_ACTIVITY_CP_SIZE 4 + +#define OCF_READ_INQ_ACTIVITY 0x001D +typedef struct { + uint8_t status; + uint16_t interval; + uint16_t window; +} __attribute__ ((packed)) read_inq_activity_rp; +#define READ_INQ_ACTIVITY_RP_SIZE 5 + +#define OCF_WRITE_INQ_ACTIVITY 0x001E +typedef struct { + uint16_t interval; + uint16_t window; +} __attribute__ ((packed)) write_inq_activity_cp; +#define WRITE_INQ_ACTIVITY_CP_SIZE 4 + +#define OCF_READ_AUTH_ENABLE 0x001F + +#define OCF_WRITE_AUTH_ENABLE 0x0020 + #define AUTH_DISABLED 0x00 + #define AUTH_ENABLED 0x01 + +#define OCF_READ_ENCRYPT_MODE 0x0021 + +#define OCF_WRITE_ENCRYPT_MODE 0x0022 + #define ENCRYPT_DISABLED 0x00 + #define ENCRYPT_P2P 0x01 + #define ENCRYPT_BOTH 0x02 + +#define OCF_READ_CLASS_OF_DEV 0x0023 +typedef struct { + uint8_t status; + uint8_t dev_class[3]; +} __attribute__ ((packed)) read_class_of_dev_rp; +#define READ_CLASS_OF_DEV_RP_SIZE 4 + +#define OCF_WRITE_CLASS_OF_DEV 0x0024 +typedef struct { + uint8_t dev_class[3]; +} __attribute__ ((packed)) write_class_of_dev_cp; +#define WRITE_CLASS_OF_DEV_CP_SIZE 3 + +#define OCF_READ_VOICE_SETTING 0x0025 +typedef struct { + uint8_t status; + uint16_t voice_setting; +} __attribute__ ((packed)) read_voice_setting_rp; +#define READ_VOICE_SETTING_RP_SIZE 3 + +#define OCF_WRITE_VOICE_SETTING 0x0026 +typedef struct { + uint16_t voice_setting; +} __attribute__ ((packed)) write_voice_setting_cp; +#define WRITE_VOICE_SETTING_CP_SIZE 2 + +#define OCF_READ_AUTOMATIC_FLUSH_TIMEOUT 0x0027 + +#define OCF_WRITE_AUTOMATIC_FLUSH_TIMEOUT 0x0028 + +#define OCF_READ_NUM_BROADCAST_RETRANS 0x0029 + +#define OCF_WRITE_NUM_BROADCAST_RETRANS 0x002A + +#define OCF_READ_HOLD_MODE_ACTIVITY 0x002B + +#define OCF_WRITE_HOLD_MODE_ACTIVITY 0x002C + +#define OCF_READ_TRANSMIT_POWER_LEVEL 0x002D +typedef struct { + uint16_t handle; + uint8_t type; +} __attribute__ ((packed)) read_transmit_power_level_cp; +#define READ_TRANSMIT_POWER_LEVEL_CP_SIZE 3 +typedef struct { + uint8_t status; + uint16_t handle; + int8_t level; +} __attribute__ ((packed)) read_transmit_power_level_rp; +#define READ_TRANSMIT_POWER_LEVEL_RP_SIZE 4 + +#define OCF_READ_SYNC_FLOW_ENABLE 0x002E + +#define OCF_WRITE_SYNC_FLOW_ENABLE 0x002F + +#define OCF_SET_CONTROLLER_TO_HOST_FC 0x0031 + +#define OCF_HOST_BUFFER_SIZE 0x0033 +typedef struct { + uint16_t acl_mtu; + uint8_t sco_mtu; + uint16_t acl_max_pkt; + uint16_t sco_max_pkt; +} __attribute__ ((packed)) host_buffer_size_cp; +#define HOST_BUFFER_SIZE_CP_SIZE 7 + +#define OCF_HOST_NUM_COMP_PKTS 0x0035 +typedef struct { + uint8_t num_hndl; + /* variable length part */ +} __attribute__ ((packed)) host_num_comp_pkts_cp; +#define HOST_NUM_COMP_PKTS_CP_SIZE 1 + +#define OCF_READ_LINK_SUPERVISION_TIMEOUT 0x0036 +typedef struct { + uint8_t status; + uint16_t handle; + uint16_t timeout; +} __attribute__ ((packed)) read_link_supervision_timeout_rp; +#define READ_LINK_SUPERVISION_TIMEOUT_RP_SIZE 5 + +#define OCF_WRITE_LINK_SUPERVISION_TIMEOUT 0x0037 +typedef struct { + uint16_t handle; + uint16_t timeout; +} __attribute__ ((packed)) write_link_supervision_timeout_cp; +#define WRITE_LINK_SUPERVISION_TIMEOUT_CP_SIZE 4 +typedef struct { + uint8_t status; + uint16_t handle; +} __attribute__ ((packed)) write_link_supervision_timeout_rp; +#define WRITE_LINK_SUPERVISION_TIMEOUT_RP_SIZE 3 + +#define OCF_READ_NUM_SUPPORTED_IAC 0x0038 + +#define MAX_IAC_LAP 0x40 +#define OCF_READ_CURRENT_IAC_LAP 0x0039 +typedef struct { + uint8_t status; + uint8_t num_current_iac; + uint8_t lap[MAX_IAC_LAP][3]; +} __attribute__ ((packed)) read_current_iac_lap_rp; +#define READ_CURRENT_IAC_LAP_RP_SIZE 2+3*MAX_IAC_LAP + +#define OCF_WRITE_CURRENT_IAC_LAP 0x003A +typedef struct { + uint8_t num_current_iac; + uint8_t lap[MAX_IAC_LAP][3]; +} __attribute__ ((packed)) write_current_iac_lap_cp; +#define WRITE_CURRENT_IAC_LAP_CP_SIZE 1+3*MAX_IAC_LAP + +#define OCF_READ_PAGE_SCAN_PERIOD_MODE 0x003B + +#define OCF_WRITE_PAGE_SCAN_PERIOD_MODE 0x003C + +#define OCF_READ_PAGE_SCAN_MODE 0x003D + +#define OCF_WRITE_PAGE_SCAN_MODE 0x003E + +#define OCF_SET_AFH_CLASSIFICATION 0x003F +typedef struct { + uint8_t map[10]; +} __attribute__ ((packed)) set_afh_classification_cp; +#define SET_AFH_CLASSIFICATION_CP_SIZE 10 +typedef struct { + uint8_t status; +} __attribute__ ((packed)) set_afh_classification_rp; +#define SET_AFH_CLASSIFICATION_RP_SIZE 1 + +#define OCF_READ_INQUIRY_SCAN_TYPE 0x0042 +typedef struct { + uint8_t status; + uint8_t type; +} __attribute__ ((packed)) read_inquiry_scan_type_rp; +#define READ_INQUIRY_SCAN_TYPE_RP_SIZE 2 + +#define OCF_WRITE_INQUIRY_SCAN_TYPE 0x0043 +typedef struct { + uint8_t type; +} __attribute__ ((packed)) write_inquiry_scan_type_cp; +#define WRITE_INQUIRY_SCAN_TYPE_CP_SIZE 1 +typedef struct { + uint8_t status; +} __attribute__ ((packed)) write_inquiry_scan_type_rp; +#define WRITE_INQUIRY_SCAN_TYPE_RP_SIZE 1 + +#define OCF_READ_INQUIRY_MODE 0x0044 +typedef struct { + uint8_t status; + uint8_t mode; +} __attribute__ ((packed)) read_inquiry_mode_rp; +#define READ_INQUIRY_MODE_RP_SIZE 2 + +#define OCF_WRITE_INQUIRY_MODE 0x0045 +typedef struct { + uint8_t mode; +} __attribute__ ((packed)) write_inquiry_mode_cp; +#define WRITE_INQUIRY_MODE_CP_SIZE 1 +typedef struct { + uint8_t status; +} __attribute__ ((packed)) write_inquiry_mode_rp; +#define WRITE_INQUIRY_MODE_RP_SIZE 1 + +#define OCF_READ_PAGE_SCAN_TYPE 0x0046 + +#define OCF_WRITE_PAGE_SCAN_TYPE 0x0047 + #define PAGE_SCAN_TYPE_STANDARD 0x00 + #define PAGE_SCAN_TYPE_INTERLACED 0x01 + +#define OCF_READ_AFH_MODE 0x0048 +typedef struct { + uint8_t status; + uint8_t mode; +} __attribute__ ((packed)) read_afh_mode_rp; +#define READ_AFH_MODE_RP_SIZE 2 + +#define OCF_WRITE_AFH_MODE 0x0049 +typedef struct { + uint8_t mode; +} __attribute__ ((packed)) write_afh_mode_cp; +#define WRITE_AFH_MODE_CP_SIZE 1 +typedef struct { + uint8_t status; +} __attribute__ ((packed)) write_afh_mode_rp; +#define WRITE_AFH_MODE_RP_SIZE 1 + +#define HCI_MAX_EIR_LENGTH 240 + +#define OCF_READ_EXT_INQUIRY_RESPONSE 0x0051 +typedef struct { + uint8_t status; + uint8_t fec; + uint8_t data[HCI_MAX_EIR_LENGTH]; +} __attribute__ ((packed)) read_ext_inquiry_response_rp; +#define READ_EXT_INQUIRY_RESPONSE_RP_SIZE 242 + +#define OCF_WRITE_EXT_INQUIRY_RESPONSE 0x0052 +typedef struct { + uint8_t fec; + uint8_t data[HCI_MAX_EIR_LENGTH]; +} __attribute__ ((packed)) write_ext_inquiry_response_cp; +#define WRITE_EXT_INQUIRY_RESPONSE_CP_SIZE 241 +typedef struct { + uint8_t status; +} __attribute__ ((packed)) write_ext_inquiry_response_rp; +#define WRITE_EXT_INQUIRY_RESPONSE_RP_SIZE 1 + +#define OCF_REFRESH_ENCRYPTION_KEY 0x0053 +typedef struct { + uint16_t handle; +} __attribute__ ((packed)) refresh_encryption_key_cp; +#define REFRESH_ENCRYPTION_KEY_CP_SIZE 2 +typedef struct { + uint8_t status; +} __attribute__ ((packed)) refresh_encryption_key_rp; +#define REFRESH_ENCRYPTION_KEY_RP_SIZE 1 + +#define OCF_READ_SIMPLE_PAIRING_MODE 0x0055 +typedef struct { + uint8_t status; + uint8_t mode; +} __attribute__ ((packed)) read_simple_pairing_mode_rp; +#define READ_SIMPLE_PAIRING_MODE_RP_SIZE 2 + +#define OCF_WRITE_SIMPLE_PAIRING_MODE 0x0056 +typedef struct { + uint8_t mode; +} __attribute__ ((packed)) write_simple_pairing_mode_cp; +#define WRITE_SIMPLE_PAIRING_MODE_CP_SIZE 1 +typedef struct { + uint8_t status; +} __attribute__ ((packed)) write_simple_pairing_mode_rp; +#define WRITE_SIMPLE_PAIRING_MODE_RP_SIZE 1 + +#define OCF_READ_LOCAL_OOB_DATA 0x0057 +typedef struct { + uint8_t status; + uint8_t hash[16]; + uint8_t randomizer[16]; +} __attribute__ ((packed)) read_local_oob_data_rp; +#define READ_LOCAL_OOB_DATA_RP_SIZE 33 + +#define OCF_READ_INQ_RESPONSE_TX_POWER_LEVEL 0x0058 +typedef struct { + uint8_t status; + int8_t level; +} __attribute__ ((packed)) read_inq_response_tx_power_level_rp; +#define READ_INQ_RESPONSE_TX_POWER_LEVEL_RP_SIZE 2 + +#define OCF_READ_INQUIRY_TRANSMIT_POWER_LEVEL 0x0058 +typedef struct { + uint8_t status; + int8_t level; +} __attribute__ ((packed)) read_inquiry_transmit_power_level_rp; +#define READ_INQUIRY_TRANSMIT_POWER_LEVEL_RP_SIZE 2 + +#define OCF_WRITE_INQUIRY_TRANSMIT_POWER_LEVEL 0x0059 +typedef struct { + int8_t level; +} __attribute__ ((packed)) write_inquiry_transmit_power_level_cp; +#define WRITE_INQUIRY_TRANSMIT_POWER_LEVEL_CP_SIZE 1 +typedef struct { + uint8_t status; +} __attribute__ ((packed)) write_inquiry_transmit_power_level_rp; +#define WRITE_INQUIRY_TRANSMIT_POWER_LEVEL_RP_SIZE 1 + +#define OCF_READ_DEFAULT_ERROR_DATA_REPORTING 0x005A +typedef struct { + uint8_t status; + uint8_t reporting; +} __attribute__ ((packed)) read_default_error_data_reporting_rp; +#define READ_DEFAULT_ERROR_DATA_REPORTING_RP_SIZE 2 + +#define OCF_WRITE_DEFAULT_ERROR_DATA_REPORTING 0x005B +typedef struct { + uint8_t reporting; +} __attribute__ ((packed)) write_default_error_data_reporting_cp; +#define WRITE_DEFAULT_ERROR_DATA_REPORTING_CP_SIZE 1 +typedef struct { + uint8_t status; +} __attribute__ ((packed)) write_default_error_data_reporting_rp; +#define WRITE_DEFAULT_ERROR_DATA_REPORTING_RP_SIZE 1 + +#define OCF_ENHANCED_FLUSH 0x005F +typedef struct { + uint16_t handle; + uint8_t type; +} __attribute__ ((packed)) enhanced_flush_cp; +#define ENHANCED_FLUSH_CP_SIZE 3 + +#define OCF_SEND_KEYPRESS_NOTIFY 0x0060 +typedef struct { + bdaddr_t bdaddr; + uint8_t type; +} __attribute__ ((packed)) send_keypress_notify_cp; +#define SEND_KEYPRESS_NOTIFY_CP_SIZE 7 +typedef struct { + uint8_t status; +} __attribute__ ((packed)) send_keypress_notify_rp; +#define SEND_KEYPRESS_NOTIFY_RP_SIZE 1 + +#define OCF_READ_LOGICAL_LINK_ACCEPT_TIMEOUT 0x0061 +typedef struct { + uint8_t status; + uint16_t timeout; +} __attribute__ ((packed)) read_log_link_accept_timeout_rp; +#define READ_LOGICAL_LINK_ACCEPT_TIMEOUT_RP_SIZE 3 + +#define OCF_WRITE_LOGICAL_LINK_ACCEPT_TIMEOUT 0x0062 +typedef struct { + uint16_t timeout; +} __attribute__ ((packed)) write_log_link_accept_timeout_cp; +#define WRITE_LOGICAL_LINK_ACCEPT_TIMEOUT_CP_SIZE 2 + +#define OCF_SET_EVENT_MASK_PAGE_2 0x0063 + +#define OCF_READ_LOCATION_DATA 0x0064 + +#define OCF_WRITE_LOCATION_DATA 0x0065 + +#define OCF_READ_FLOW_CONTROL_MODE 0x0066 + +#define OCF_WRITE_FLOW_CONTROL_MODE 0x0067 + +#define OCF_READ_ENHANCED_TRANSMIT_POWER_LEVEL 0x0068 +typedef struct { + uint8_t status; + uint16_t handle; + int8_t level_gfsk; + int8_t level_dqpsk; + int8_t level_8dpsk; +} __attribute__ ((packed)) read_enhanced_transmit_power_level_rp; +#define READ_ENHANCED_TRANSMIT_POWER_LEVEL_RP_SIZE 6 + +#define OCF_READ_BEST_EFFORT_FLUSH_TIMEOUT 0x0069 +typedef struct { + uint8_t status; + uint32_t timeout; +} __attribute__ ((packed)) read_best_effort_flush_timeout_rp; +#define READ_BEST_EFFORT_FLUSH_TIMEOUT_RP_SIZE 5 + +#define OCF_WRITE_BEST_EFFORT_FLUSH_TIMEOUT 0x006A +typedef struct { + uint16_t handle; + uint32_t timeout; +} __attribute__ ((packed)) write_best_effort_flush_timeout_cp; +#define WRITE_BEST_EFFORT_FLUSH_TIMEOUT_CP_SIZE 6 +typedef struct { + uint8_t status; +} __attribute__ ((packed)) write_best_effort_flush_timeout_rp; +#define WRITE_BEST_EFFORT_FLUSH_TIMEOUT_RP_SIZE 1 + +#define OCF_READ_LE_HOST_SUPPORTED 0x006C +typedef struct { + uint8_t status; + uint8_t le; + uint8_t simul; +} __attribute__ ((packed)) read_le_host_supported_rp; +#define READ_LE_HOST_SUPPORTED_RP_SIZE 3 + +#define OCF_WRITE_LE_HOST_SUPPORTED 0x006D +typedef struct { + uint8_t le; + uint8_t simul; +} __attribute__ ((packed)) write_le_host_supported_cp; +#define WRITE_LE_HOST_SUPPORTED_CP_SIZE 2 + +/* Informational Parameters */ +#define OGF_INFO_PARAM 0x04 + +#define OCF_READ_LOCAL_VERSION 0x0001 +typedef struct { + uint8_t status; + uint8_t hci_ver; + uint16_t hci_rev; + uint8_t lmp_ver; + uint16_t manufacturer; + uint16_t lmp_subver; +} __attribute__ ((packed)) read_local_version_rp; +#define READ_LOCAL_VERSION_RP_SIZE 9 + +#define OCF_READ_LOCAL_COMMANDS 0x0002 +typedef struct { + uint8_t status; + uint8_t commands[64]; +} __attribute__ ((packed)) read_local_commands_rp; +#define READ_LOCAL_COMMANDS_RP_SIZE 65 + +#define OCF_READ_LOCAL_FEATURES 0x0003 +typedef struct { + uint8_t status; + uint8_t features[8]; +} __attribute__ ((packed)) read_local_features_rp; +#define READ_LOCAL_FEATURES_RP_SIZE 9 + +#define OCF_READ_LOCAL_EXT_FEATURES 0x0004 +typedef struct { + uint8_t page_num; +} __attribute__ ((packed)) read_local_ext_features_cp; +#define READ_LOCAL_EXT_FEATURES_CP_SIZE 1 +typedef struct { + uint8_t status; + uint8_t page_num; + uint8_t max_page_num; + uint8_t features[8]; +} __attribute__ ((packed)) read_local_ext_features_rp; +#define READ_LOCAL_EXT_FEATURES_RP_SIZE 11 + +#define OCF_READ_BUFFER_SIZE 0x0005 +typedef struct { + uint8_t status; + uint16_t acl_mtu; + uint8_t sco_mtu; + uint16_t acl_max_pkt; + uint16_t sco_max_pkt; +} __attribute__ ((packed)) read_buffer_size_rp; +#define READ_BUFFER_SIZE_RP_SIZE 8 + +#define OCF_READ_COUNTRY_CODE 0x0007 + +#define OCF_READ_BD_ADDR 0x0009 +typedef struct { + uint8_t status; + bdaddr_t bdaddr; +} __attribute__ ((packed)) read_bd_addr_rp; +#define READ_BD_ADDR_RP_SIZE 7 + +#define OCF_READ_DATA_BLOCK_SIZE 0x000A +typedef struct { + uint8_t status; + uint16_t max_acl_len; + uint16_t data_block_len; + uint16_t num_blocks; +} __attribute__ ((packed)) read_data_block_size_rp; + +/* Status params */ +#define OGF_STATUS_PARAM 0x05 + +#define OCF_READ_FAILED_CONTACT_COUNTER 0x0001 +typedef struct { + uint8_t status; + uint16_t handle; + uint8_t counter; +} __attribute__ ((packed)) read_failed_contact_counter_rp; +#define READ_FAILED_CONTACT_COUNTER_RP_SIZE 4 + +#define OCF_RESET_FAILED_CONTACT_COUNTER 0x0002 +typedef struct { + uint8_t status; + uint16_t handle; +} __attribute__ ((packed)) reset_failed_contact_counter_rp; +#define RESET_FAILED_CONTACT_COUNTER_RP_SIZE 3 + +#define OCF_READ_LINK_QUALITY 0x0003 +typedef struct { + uint8_t status; + uint16_t handle; + uint8_t link_quality; +} __attribute__ ((packed)) read_link_quality_rp; +#define READ_LINK_QUALITY_RP_SIZE 4 + +#define OCF_READ_RSSI 0x0005 +typedef struct { + uint8_t status; + uint16_t handle; + int8_t rssi; +} __attribute__ ((packed)) read_rssi_rp; +#define READ_RSSI_RP_SIZE 4 + +#define OCF_READ_AFH_MAP 0x0006 +typedef struct { + uint8_t status; + uint16_t handle; + uint8_t mode; + uint8_t map[10]; +} __attribute__ ((packed)) read_afh_map_rp; +#define READ_AFH_MAP_RP_SIZE 14 + +#define OCF_READ_CLOCK 0x0007 +typedef struct { + uint16_t handle; + uint8_t which_clock; +} __attribute__ ((packed)) read_clock_cp; +#define READ_CLOCK_CP_SIZE 3 +typedef struct { + uint8_t status; + uint16_t handle; + uint32_t clock; + uint16_t accuracy; +} __attribute__ ((packed)) read_clock_rp; +#define READ_CLOCK_RP_SIZE 9 + +#define OCF_READ_LOCAL_AMP_INFO 0x0009 +typedef struct { + uint8_t status; + uint8_t amp_status; + uint32_t total_bandwidth; + uint32_t max_guaranteed_bandwidth; + uint32_t min_latency; + uint32_t max_pdu_size; + uint8_t controller_type; + uint16_t pal_caps; + uint16_t max_amp_assoc_length; + uint32_t max_flush_timeout; + uint32_t best_effort_flush_timeout; +} __attribute__ ((packed)) read_local_amp_info_rp; +#define READ_LOCAL_AMP_INFO_RP_SIZE 31 + +#define OCF_READ_LOCAL_AMP_ASSOC 0x000A +typedef struct { + uint8_t handle; + uint16_t length_so_far; + uint16_t assoc_length; +} __attribute__ ((packed)) read_local_amp_assoc_cp; +#define READ_LOCAL_AMP_ASSOC_CP_SIZE 5 +typedef struct { + uint8_t status; + uint8_t handle; + uint16_t length; + uint8_t fragment[HCI_MAX_NAME_LENGTH]; +} __attribute__ ((packed)) read_local_amp_assoc_rp; +#define READ_LOCAL_AMP_ASSOC_RP_SIZE 252 + +#define OCF_WRITE_REMOTE_AMP_ASSOC 0x000B +typedef struct { + uint8_t handle; + uint16_t length_so_far; + uint16_t remaining_length; + uint8_t fragment[HCI_MAX_NAME_LENGTH]; +} __attribute__ ((packed)) write_remote_amp_assoc_cp; +#define WRITE_REMOTE_AMP_ASSOC_CP_SIZE 253 +typedef struct { + uint8_t status; + uint8_t handle; +} __attribute__ ((packed)) write_remote_amp_assoc_rp; +#define WRITE_REMOTE_AMP_ASSOC_RP_SIZE 2 + +/* Testing commands */ +#define OGF_TESTING_CMD 0x3e + +#define OCF_READ_LOOPBACK_MODE 0x0001 + +#define OCF_WRITE_LOOPBACK_MODE 0x0002 + +#define OCF_ENABLE_DEVICE_UNDER_TEST_MODE 0x0003 + +#define OCF_WRITE_SIMPLE_PAIRING_DEBUG_MODE 0x0004 +typedef struct { + uint8_t mode; +} __attribute__ ((packed)) write_simple_pairing_debug_mode_cp; +#define WRITE_SIMPLE_PAIRING_DEBUG_MODE_CP_SIZE 1 +typedef struct { + uint8_t status; +} __attribute__ ((packed)) write_simple_pairing_debug_mode_rp; +#define WRITE_SIMPLE_PAIRING_DEBUG_MODE_RP_SIZE 1 + +/* LE commands */ +#define OGF_LE_CTL 0x08 + +#define OCF_LE_SET_EVENT_MASK 0x0001 +typedef struct { + uint8_t mask[8]; +} __attribute__ ((packed)) le_set_event_mask_cp; +#define LE_SET_EVENT_MASK_CP_SIZE 8 + +#define OCF_LE_READ_BUFFER_SIZE 0x0002 +typedef struct { + uint8_t status; + uint16_t pkt_len; + uint8_t max_pkt; +} __attribute__ ((packed)) le_read_buffer_size_rp; +#define LE_READ_BUFFER_SIZE_RP_SIZE 4 + +#define OCF_LE_READ_LOCAL_SUPPORTED_FEATURES 0x0003 +typedef struct { + uint8_t status; + uint8_t features[8]; +} __attribute__ ((packed)) le_read_local_supported_features_rp; +#define LE_READ_LOCAL_SUPPORTED_FEATURES_RP_SIZE 9 + +#define OCF_LE_SET_RANDOM_ADDRESS 0x0005 +typedef struct { + bdaddr_t bdaddr; +} __attribute__ ((packed)) le_set_random_address_cp; +#define LE_SET_RANDOM_ADDRESS_CP_SIZE 6 + +#define OCF_LE_SET_ADVERTISING_PARAMETERS 0x0006 +typedef struct { + uint16_t min_interval; + uint16_t max_interval; + uint8_t advtype; + uint8_t own_bdaddr_type; + uint8_t direct_bdaddr_type; + bdaddr_t direct_bdaddr; + uint8_t chan_map; + uint8_t filter; +} __attribute__ ((packed)) le_set_advertising_parameters_cp; +#define LE_SET_ADVERTISING_PARAMETERS_CP_SIZE 15 + +#define OCF_LE_READ_ADVERTISING_CHANNEL_TX_POWER 0x0007 +typedef struct { + uint8_t status; + int8_t level; +} __attribute__ ((packed)) le_read_advertising_channel_tx_power_rp; +#define LE_READ_ADVERTISING_CHANNEL_TX_POWER_RP_SIZE 2 + +#define OCF_LE_SET_ADVERTISING_DATA 0x0008 +typedef struct { + uint8_t length; + uint8_t data[31]; +} __attribute__ ((packed)) le_set_advertising_data_cp; +#define LE_SET_ADVERTISING_DATA_CP_SIZE 32 + +#define OCF_LE_SET_SCAN_RESPONSE_DATA 0x0009 +typedef struct { + uint8_t length; + uint8_t data[31]; +} __attribute__ ((packed)) le_set_scan_response_data_cp; +#define LE_SET_SCAN_RESPONSE_DATA_CP_SIZE 32 + +#define OCF_LE_SET_ADVERTISE_ENABLE 0x000A +typedef struct { + uint8_t enable; +} __attribute__ ((packed)) le_set_advertise_enable_cp; +#define LE_SET_ADVERTISE_ENABLE_CP_SIZE 1 + +#define OCF_LE_SET_SCAN_PARAMETERS 0x000B +typedef struct { + uint8_t type; + uint16_t interval; + uint16_t window; + uint8_t own_bdaddr_type; + uint8_t filter; +} __attribute__ ((packed)) le_set_scan_parameters_cp; +#define LE_SET_SCAN_PARAMETERS_CP_SIZE 7 + +#define OCF_LE_SET_SCAN_ENABLE 0x000C +typedef struct { + uint8_t enable; + uint8_t filter_dup; +} __attribute__ ((packed)) le_set_scan_enable_cp; +#define LE_SET_SCAN_ENABLE_CP_SIZE 2 + +#define OCF_LE_CREATE_CONN 0x000D +typedef struct { + uint16_t interval; + uint16_t window; + uint8_t initiator_filter; + uint8_t peer_bdaddr_type; + bdaddr_t peer_bdaddr; + uint8_t own_bdaddr_type; + uint16_t min_interval; + uint16_t max_interval; + uint16_t latency; + uint16_t supervision_timeout; + uint16_t min_ce_length; + uint16_t max_ce_length; +} __attribute__ ((packed)) le_create_connection_cp; +#define LE_CREATE_CONN_CP_SIZE 25 + +#define OCF_LE_CREATE_CONN_CANCEL 0x000E + +#define OCF_LE_READ_WHITE_LIST_SIZE 0x000F +typedef struct { + uint8_t status; + uint8_t size; +} __attribute__ ((packed)) le_read_white_list_size_rp; +#define LE_READ_WHITE_LIST_SIZE_RP_SIZE 2 + +#define OCF_LE_CLEAR_WHITE_LIST 0x0010 + +#define OCF_LE_ADD_DEVICE_TO_WHITE_LIST 0x0011 +typedef struct { + uint8_t bdaddr_type; + bdaddr_t bdaddr; +} __attribute__ ((packed)) le_add_device_to_white_list_cp; +#define LE_ADD_DEVICE_TO_WHITE_LIST_CP_SIZE 7 + +#define OCF_LE_REMOVE_DEVICE_FROM_WHITE_LIST 0x0012 +typedef struct { + uint8_t bdaddr_type; + bdaddr_t bdaddr; +} __attribute__ ((packed)) le_remove_device_from_white_list_cp; +#define LE_REMOVE_DEVICE_FROM_WHITE_LIST_CP_SIZE 7 + +#define OCF_LE_CONN_UPDATE 0x0013 +typedef struct { + uint16_t handle; + uint16_t min_interval; + uint16_t max_interval; + uint16_t latency; + uint16_t supervision_timeout; + uint16_t min_ce_length; + uint16_t max_ce_length; +} __attribute__ ((packed)) le_connection_update_cp; +#define LE_CONN_UPDATE_CP_SIZE 14 + +#define OCF_LE_SET_HOST_CHANNEL_CLASSIFICATION 0x0014 +typedef struct { + uint8_t map[5]; +} __attribute__ ((packed)) le_set_host_channel_classification_cp; +#define LE_SET_HOST_CHANNEL_CLASSIFICATION_CP_SIZE 5 + +#define OCF_LE_READ_CHANNEL_MAP 0x0015 +typedef struct { + uint16_t handle; +} __attribute__ ((packed)) le_read_channel_map_cp; +#define LE_READ_CHANNEL_MAP_CP_SIZE 2 +typedef struct { + uint8_t status; + uint16_t handle; + uint8_t map[5]; +} __attribute__ ((packed)) le_read_channel_map_rp; +#define LE_READ_CHANNEL_MAP_RP_SIZE 8 + +#define OCF_LE_READ_REMOTE_USED_FEATURES 0x0016 +typedef struct { + uint16_t handle; +} __attribute__ ((packed)) le_read_remote_used_features_cp; +#define LE_READ_REMOTE_USED_FEATURES_CP_SIZE 2 + +#define OCF_LE_ENCRYPT 0x0017 +typedef struct { + uint8_t key[16]; + uint8_t plaintext[16]; +} __attribute__ ((packed)) le_encrypt_cp; +#define LE_ENCRYPT_CP_SIZE 32 +typedef struct { + uint8_t status; + uint8_t data[16]; +} __attribute__ ((packed)) le_encrypt_rp; +#define LE_ENCRYPT_RP_SIZE 17 + +#define OCF_LE_RAND 0x0018 +typedef struct { + uint8_t status; + uint64_t random; +} __attribute__ ((packed)) le_rand_rp; +#define LE_RAND_RP_SIZE 9 + +#define OCF_LE_START_ENCRYPTION 0x0019 +typedef struct { + uint16_t handle; + uint64_t random; + uint16_t diversifier; + uint8_t key[16]; +} __attribute__ ((packed)) le_start_encryption_cp; +#define LE_START_ENCRYPTION_CP_SIZE 28 + +#define OCF_LE_LTK_REPLY 0x001A +typedef struct { + uint16_t handle; + uint8_t key[16]; +} __attribute__ ((packed)) le_ltk_reply_cp; +#define LE_LTK_REPLY_CP_SIZE 18 +typedef struct { + uint8_t status; + uint16_t handle; +} __attribute__ ((packed)) le_ltk_reply_rp; +#define LE_LTK_REPLY_RP_SIZE 3 + +#define OCF_LE_LTK_NEG_REPLY 0x001B +typedef struct { + uint16_t handle; +} __attribute__ ((packed)) le_ltk_neg_reply_cp; +#define LE_LTK_NEG_REPLY_CP_SIZE 2 +typedef struct { + uint8_t status; + uint16_t handle; +} __attribute__ ((packed)) le_ltk_neg_reply_rp; +#define LE_LTK_NEG_REPLY_RP_SIZE 3 + +#define OCF_LE_READ_SUPPORTED_STATES 0x001C +typedef struct { + uint8_t status; + uint64_t states; +} __attribute__ ((packed)) le_read_supported_states_rp; +#define LE_READ_SUPPORTED_STATES_RP_SIZE 9 + +#define OCF_LE_RECEIVER_TEST 0x001D +typedef struct { + uint8_t frequency; +} __attribute__ ((packed)) le_receiver_test_cp; +#define LE_RECEIVER_TEST_CP_SIZE 1 + +#define OCF_LE_TRANSMITTER_TEST 0x001E +typedef struct { + uint8_t frequency; + uint8_t length; + uint8_t payload; +} __attribute__ ((packed)) le_transmitter_test_cp; +#define LE_TRANSMITTER_TEST_CP_SIZE 3 + +#define OCF_LE_TEST_END 0x001F +typedef struct { + uint8_t status; + uint16_t num_pkts; +} __attribute__ ((packed)) le_test_end_rp; +#define LE_TEST_END_RP_SIZE 3 + +/* Vendor specific commands */ +#define OGF_VENDOR_CMD 0x3f + +/* ---- HCI Events ---- */ + +#define EVT_INQUIRY_COMPLETE 0x01 + +#define EVT_INQUIRY_RESULT 0x02 +typedef struct { + bdaddr_t bdaddr; + uint8_t pscan_rep_mode; + uint8_t pscan_period_mode; + uint8_t pscan_mode; + uint8_t dev_class[3]; + uint16_t clock_offset; +} __attribute__ ((packed)) inquiry_info; +#define INQUIRY_INFO_SIZE 14 + +#define EVT_CONN_COMPLETE 0x03 +typedef struct { + uint8_t status; + uint16_t handle; + bdaddr_t bdaddr; + uint8_t link_type; + uint8_t encr_mode; +} __attribute__ ((packed)) evt_conn_complete; +#define EVT_CONN_COMPLETE_SIZE 11 + +#define EVT_CONN_REQUEST 0x04 +typedef struct { + bdaddr_t bdaddr; + uint8_t dev_class[3]; + uint8_t link_type; +} __attribute__ ((packed)) evt_conn_request; +#define EVT_CONN_REQUEST_SIZE 10 + +#define EVT_DISCONN_COMPLETE 0x05 +typedef struct { + uint8_t status; + uint16_t handle; + uint8_t reason; +} __attribute__ ((packed)) evt_disconn_complete; +#define EVT_DISCONN_COMPLETE_SIZE 4 + +#define EVT_AUTH_COMPLETE 0x06 +typedef struct { + uint8_t status; + uint16_t handle; +} __attribute__ ((packed)) evt_auth_complete; +#define EVT_AUTH_COMPLETE_SIZE 3 + +#define EVT_REMOTE_NAME_REQ_COMPLETE 0x07 +typedef struct { + uint8_t status; + bdaddr_t bdaddr; + uint8_t name[HCI_MAX_NAME_LENGTH]; +} __attribute__ ((packed)) evt_remote_name_req_complete; +#define EVT_REMOTE_NAME_REQ_COMPLETE_SIZE 255 + +#define EVT_ENCRYPT_CHANGE 0x08 +typedef struct { + uint8_t status; + uint16_t handle; + uint8_t encrypt; +} __attribute__ ((packed)) evt_encrypt_change; +#define EVT_ENCRYPT_CHANGE_SIZE 4 + +#define EVT_CHANGE_CONN_LINK_KEY_COMPLETE 0x09 +typedef struct { + uint8_t status; + uint16_t handle; +} __attribute__ ((packed)) evt_change_conn_link_key_complete; +#define EVT_CHANGE_CONN_LINK_KEY_COMPLETE_SIZE 3 + +#define EVT_MASTER_LINK_KEY_COMPLETE 0x0A +typedef struct { + uint8_t status; + uint16_t handle; + uint8_t key_flag; +} __attribute__ ((packed)) evt_master_link_key_complete; +#define EVT_MASTER_LINK_KEY_COMPLETE_SIZE 4 + +#define EVT_READ_REMOTE_FEATURES_COMPLETE 0x0B +typedef struct { + uint8_t status; + uint16_t handle; + uint8_t features[8]; +} __attribute__ ((packed)) evt_read_remote_features_complete; +#define EVT_READ_REMOTE_FEATURES_COMPLETE_SIZE 11 + +#define EVT_READ_REMOTE_VERSION_COMPLETE 0x0C +typedef struct { + uint8_t status; + uint16_t handle; + uint8_t lmp_ver; + uint16_t manufacturer; + uint16_t lmp_subver; +} __attribute__ ((packed)) evt_read_remote_version_complete; +#define EVT_READ_REMOTE_VERSION_COMPLETE_SIZE 8 + +#define EVT_QOS_SETUP_COMPLETE 0x0D +typedef struct { + uint8_t status; + uint16_t handle; + uint8_t flags; /* Reserved */ + hci_qos qos; +} __attribute__ ((packed)) evt_qos_setup_complete; +#define EVT_QOS_SETUP_COMPLETE_SIZE (4 + HCI_QOS_CP_SIZE) + +#define EVT_CMD_COMPLETE 0x0E +typedef struct { + uint8_t ncmd; + uint16_t opcode; +} __attribute__ ((packed)) evt_cmd_complete; +#define EVT_CMD_COMPLETE_SIZE 3 + +#define EVT_CMD_STATUS 0x0F +typedef struct { + uint8_t status; + uint8_t ncmd; + uint16_t opcode; +} __attribute__ ((packed)) evt_cmd_status; +#define EVT_CMD_STATUS_SIZE 4 + +#define EVT_HARDWARE_ERROR 0x10 +typedef struct { + uint8_t code; +} __attribute__ ((packed)) evt_hardware_error; +#define EVT_HARDWARE_ERROR_SIZE 1 + +#define EVT_FLUSH_OCCURRED 0x11 +typedef struct { + uint16_t handle; +} __attribute__ ((packed)) evt_flush_occured; +#define EVT_FLUSH_OCCURRED_SIZE 2 + +#define EVT_ROLE_CHANGE 0x12 +typedef struct { + uint8_t status; + bdaddr_t bdaddr; + uint8_t role; +} __attribute__ ((packed)) evt_role_change; +#define EVT_ROLE_CHANGE_SIZE 8 + +#define EVT_NUM_COMP_PKTS 0x13 +typedef struct { + uint8_t num_hndl; + /* variable length part */ +} __attribute__ ((packed)) evt_num_comp_pkts; +#define EVT_NUM_COMP_PKTS_SIZE 1 + +#define EVT_MODE_CHANGE 0x14 +typedef struct { + uint8_t status; + uint16_t handle; + uint8_t mode; + uint16_t interval; +} __attribute__ ((packed)) evt_mode_change; +#define EVT_MODE_CHANGE_SIZE 6 + +#define EVT_RETURN_LINK_KEYS 0x15 +typedef struct { + uint8_t num_keys; + /* variable length part */ +} __attribute__ ((packed)) evt_return_link_keys; +#define EVT_RETURN_LINK_KEYS_SIZE 1 + +#define EVT_PIN_CODE_REQ 0x16 +typedef struct { + bdaddr_t bdaddr; +} __attribute__ ((packed)) evt_pin_code_req; +#define EVT_PIN_CODE_REQ_SIZE 6 + +#define EVT_LINK_KEY_REQ 0x17 +typedef struct { + bdaddr_t bdaddr; +} __attribute__ ((packed)) evt_link_key_req; +#define EVT_LINK_KEY_REQ_SIZE 6 + +#define EVT_LINK_KEY_NOTIFY 0x18 +typedef struct { + bdaddr_t bdaddr; + uint8_t link_key[16]; + uint8_t key_type; +} __attribute__ ((packed)) evt_link_key_notify; +#define EVT_LINK_KEY_NOTIFY_SIZE 23 + +#define EVT_LOOPBACK_COMMAND 0x19 + +#define EVT_DATA_BUFFER_OVERFLOW 0x1A +typedef struct { + uint8_t link_type; +} __attribute__ ((packed)) evt_data_buffer_overflow; +#define EVT_DATA_BUFFER_OVERFLOW_SIZE 1 + +#define EVT_MAX_SLOTS_CHANGE 0x1B +typedef struct { + uint16_t handle; + uint8_t max_slots; +} __attribute__ ((packed)) evt_max_slots_change; +#define EVT_MAX_SLOTS_CHANGE_SIZE 3 + +#define EVT_READ_CLOCK_OFFSET_COMPLETE 0x1C +typedef struct { + uint8_t status; + uint16_t handle; + uint16_t clock_offset; +} __attribute__ ((packed)) evt_read_clock_offset_complete; +#define EVT_READ_CLOCK_OFFSET_COMPLETE_SIZE 5 + +#define EVT_CONN_PTYPE_CHANGED 0x1D +typedef struct { + uint8_t status; + uint16_t handle; + uint16_t ptype; +} __attribute__ ((packed)) evt_conn_ptype_changed; +#define EVT_CONN_PTYPE_CHANGED_SIZE 5 + +#define EVT_QOS_VIOLATION 0x1E +typedef struct { + uint16_t handle; +} __attribute__ ((packed)) evt_qos_violation; +#define EVT_QOS_VIOLATION_SIZE 2 + +#define EVT_PSCAN_REP_MODE_CHANGE 0x20 +typedef struct { + bdaddr_t bdaddr; + uint8_t pscan_rep_mode; +} __attribute__ ((packed)) evt_pscan_rep_mode_change; +#define EVT_PSCAN_REP_MODE_CHANGE_SIZE 7 + +#define EVT_FLOW_SPEC_COMPLETE 0x21 +typedef struct { + uint8_t status; + uint16_t handle; + uint8_t flags; + uint8_t direction; + hci_qos qos; +} __attribute__ ((packed)) evt_flow_spec_complete; +#define EVT_FLOW_SPEC_COMPLETE_SIZE (5 + HCI_QOS_CP_SIZE) + +#define EVT_INQUIRY_RESULT_WITH_RSSI 0x22 +typedef struct { + bdaddr_t bdaddr; + uint8_t pscan_rep_mode; + uint8_t pscan_period_mode; + uint8_t dev_class[3]; + uint16_t clock_offset; + int8_t rssi; +} __attribute__ ((packed)) inquiry_info_with_rssi; +#define INQUIRY_INFO_WITH_RSSI_SIZE 14 +typedef struct { + bdaddr_t bdaddr; + uint8_t pscan_rep_mode; + uint8_t pscan_period_mode; + uint8_t pscan_mode; + uint8_t dev_class[3]; + uint16_t clock_offset; + int8_t rssi; +} __attribute__ ((packed)) inquiry_info_with_rssi_and_pscan_mode; +#define INQUIRY_INFO_WITH_RSSI_AND_PSCAN_MODE_SIZE 15 + +#define EVT_READ_REMOTE_EXT_FEATURES_COMPLETE 0x23 +typedef struct { + uint8_t status; + uint16_t handle; + uint8_t page_num; + uint8_t max_page_num; + uint8_t features[8]; +} __attribute__ ((packed)) evt_read_remote_ext_features_complete; +#define EVT_READ_REMOTE_EXT_FEATURES_COMPLETE_SIZE 13 + +#define EVT_SYNC_CONN_COMPLETE 0x2C +typedef struct { + uint8_t status; + uint16_t handle; + bdaddr_t bdaddr; + uint8_t link_type; + uint8_t trans_interval; + uint8_t retrans_window; + uint16_t rx_pkt_len; + uint16_t tx_pkt_len; + uint8_t air_mode; +} __attribute__ ((packed)) evt_sync_conn_complete; +#define EVT_SYNC_CONN_COMPLETE_SIZE 17 + +#define EVT_SYNC_CONN_CHANGED 0x2D +typedef struct { + uint8_t status; + uint16_t handle; + uint8_t trans_interval; + uint8_t retrans_window; + uint16_t rx_pkt_len; + uint16_t tx_pkt_len; +} __attribute__ ((packed)) evt_sync_conn_changed; +#define EVT_SYNC_CONN_CHANGED_SIZE 9 + +#define EVT_SNIFF_SUBRATING 0x2E +typedef struct { + uint8_t status; + uint16_t handle; + uint16_t max_tx_latency; + uint16_t max_rx_latency; + uint16_t min_remote_timeout; + uint16_t min_local_timeout; +} __attribute__ ((packed)) evt_sniff_subrating; +#define EVT_SNIFF_SUBRATING_SIZE 11 + +#define EVT_EXTENDED_INQUIRY_RESULT 0x2F +typedef struct { + bdaddr_t bdaddr; + uint8_t pscan_rep_mode; + uint8_t pscan_period_mode; + uint8_t dev_class[3]; + uint16_t clock_offset; + int8_t rssi; + uint8_t data[HCI_MAX_EIR_LENGTH]; +} __attribute__ ((packed)) extended_inquiry_info; +#define EXTENDED_INQUIRY_INFO_SIZE 254 + +#define EVT_ENCRYPTION_KEY_REFRESH_COMPLETE 0x30 +typedef struct { + uint8_t status; + uint16_t handle; +} __attribute__ ((packed)) evt_encryption_key_refresh_complete; +#define EVT_ENCRYPTION_KEY_REFRESH_COMPLETE_SIZE 3 + +#define EVT_IO_CAPABILITY_REQUEST 0x31 +typedef struct { + bdaddr_t bdaddr; +} __attribute__ ((packed)) evt_io_capability_request; +#define EVT_IO_CAPABILITY_REQUEST_SIZE 6 + +#define EVT_IO_CAPABILITY_RESPONSE 0x32 +typedef struct { + bdaddr_t bdaddr; + uint8_t capability; + uint8_t oob_data; + uint8_t authentication; +} __attribute__ ((packed)) evt_io_capability_response; +#define EVT_IO_CAPABILITY_RESPONSE_SIZE 9 + +#define EVT_USER_CONFIRM_REQUEST 0x33 +typedef struct { + bdaddr_t bdaddr; + uint32_t passkey; +} __attribute__ ((packed)) evt_user_confirm_request; +#define EVT_USER_CONFIRM_REQUEST_SIZE 10 + +#define EVT_USER_PASSKEY_REQUEST 0x34 +typedef struct { + bdaddr_t bdaddr; +} __attribute__ ((packed)) evt_user_passkey_request; +#define EVT_USER_PASSKEY_REQUEST_SIZE 6 + +#define EVT_REMOTE_OOB_DATA_REQUEST 0x35 +typedef struct { + bdaddr_t bdaddr; +} __attribute__ ((packed)) evt_remote_oob_data_request; +#define EVT_REMOTE_OOB_DATA_REQUEST_SIZE 6 + +#define EVT_SIMPLE_PAIRING_COMPLETE 0x36 +typedef struct { + uint8_t status; + bdaddr_t bdaddr; +} __attribute__ ((packed)) evt_simple_pairing_complete; +#define EVT_SIMPLE_PAIRING_COMPLETE_SIZE 7 + +#define EVT_LINK_SUPERVISION_TIMEOUT_CHANGED 0x38 +typedef struct { + uint16_t handle; + uint16_t timeout; +} __attribute__ ((packed)) evt_link_supervision_timeout_changed; +#define EVT_LINK_SUPERVISION_TIMEOUT_CHANGED_SIZE 4 + +#define EVT_ENHANCED_FLUSH_COMPLETE 0x39 +typedef struct { + uint16_t handle; +} __attribute__ ((packed)) evt_enhanced_flush_complete; +#define EVT_ENHANCED_FLUSH_COMPLETE_SIZE 2 + +#define EVT_USER_PASSKEY_NOTIFY 0x3B +typedef struct { + bdaddr_t bdaddr; + uint32_t passkey; +} __attribute__ ((packed)) evt_user_passkey_notify; +#define EVT_USER_PASSKEY_NOTIFY_SIZE 10 + +#define EVT_KEYPRESS_NOTIFY 0x3C +typedef struct { + bdaddr_t bdaddr; + uint8_t type; +} __attribute__ ((packed)) evt_keypress_notify; +#define EVT_KEYPRESS_NOTIFY_SIZE 7 + +#define EVT_REMOTE_HOST_FEATURES_NOTIFY 0x3D +typedef struct { + bdaddr_t bdaddr; + uint8_t features[8]; +} __attribute__ ((packed)) evt_remote_host_features_notify; +#define EVT_REMOTE_HOST_FEATURES_NOTIFY_SIZE 14 + +#define EVT_LE_META_EVENT 0x3E +typedef struct { + uint8_t subevent; + uint8_t data[0]; +} __attribute__ ((packed)) evt_le_meta_event; +#define EVT_LE_META_EVENT_SIZE 1 + +#define EVT_LE_CONN_COMPLETE 0x01 +typedef struct { + uint8_t status; + uint16_t handle; + uint8_t role; + uint8_t peer_bdaddr_type; + bdaddr_t peer_bdaddr; + uint16_t interval; + uint16_t latency; + uint16_t supervision_timeout; + uint8_t master_clock_accuracy; +} __attribute__ ((packed)) evt_le_connection_complete; +#define EVT_LE_CONN_COMPLETE_SIZE 18 + +#define EVT_LE_ADVERTISING_REPORT 0x02 +typedef struct { + uint8_t evt_type; + uint8_t bdaddr_type; + bdaddr_t bdaddr; + uint8_t length; + uint8_t data[0]; +} __attribute__ ((packed)) le_advertising_info; +#define LE_ADVERTISING_INFO_SIZE 9 + +#define EVT_LE_CONN_UPDATE_COMPLETE 0x03 +typedef struct { + uint8_t status; + uint16_t handle; + uint16_t interval; + uint16_t latency; + uint16_t supervision_timeout; +} __attribute__ ((packed)) evt_le_connection_update_complete; +#define EVT_LE_CONN_UPDATE_COMPLETE_SIZE 9 + +#define EVT_LE_READ_REMOTE_USED_FEATURES_COMPLETE 0x04 +typedef struct { + uint8_t status; + uint16_t handle; + uint8_t features[8]; +} __attribute__ ((packed)) evt_le_read_remote_used_features_complete; +#define EVT_LE_READ_REMOTE_USED_FEATURES_COMPLETE_SIZE 11 + +#define EVT_LE_LTK_REQUEST 0x05 +typedef struct { + uint16_t handle; + uint64_t random; + uint16_t diversifier; +} __attribute__ ((packed)) evt_le_long_term_key_request; +#define EVT_LE_LTK_REQUEST_SIZE 12 + +#define EVT_PHYSICAL_LINK_COMPLETE 0x40 +typedef struct { + uint8_t status; + uint8_t handle; +} __attribute__ ((packed)) evt_physical_link_complete; +#define EVT_PHYSICAL_LINK_COMPLETE_SIZE 2 + +#define EVT_CHANNEL_SELECTED 0x41 + +#define EVT_DISCONNECT_PHYSICAL_LINK_COMPLETE 0x42 +typedef struct { + uint8_t status; + uint8_t handle; + uint8_t reason; +} __attribute__ ((packed)) evt_disconn_physical_link_complete; +#define EVT_DISCONNECT_PHYSICAL_LINK_COMPLETE_SIZE 3 + +#define EVT_PHYSICAL_LINK_LOSS_EARLY_WARNING 0x43 +typedef struct { + uint8_t handle; + uint8_t reason; +} __attribute__ ((packed)) evt_physical_link_loss_warning; +#define EVT_PHYSICAL_LINK_LOSS_WARNING_SIZE 2 + +#define EVT_PHYSICAL_LINK_RECOVERY 0x44 +typedef struct { + uint8_t handle; +} __attribute__ ((packed)) evt_physical_link_recovery; +#define EVT_PHYSICAL_LINK_RECOVERY_SIZE 1 + +#define EVT_LOGICAL_LINK_COMPLETE 0x45 +typedef struct { + uint8_t status; + uint16_t log_handle; + uint8_t handle; + uint8_t tx_flow_id; +} __attribute__ ((packed)) evt_logical_link_complete; +#define EVT_LOGICAL_LINK_COMPLETE_SIZE 5 + +#define EVT_DISCONNECT_LOGICAL_LINK_COMPLETE 0x46 + +#define EVT_FLOW_SPEC_MODIFY_COMPLETE 0x47 +typedef struct { + uint8_t status; + uint16_t handle; +} __attribute__ ((packed)) evt_flow_spec_modify_complete; +#define EVT_FLOW_SPEC_MODIFY_COMPLETE_SIZE 3 + +#define EVT_NUMBER_COMPLETED_BLOCKS 0x48 +typedef struct { + uint16_t handle; + uint16_t num_cmplt_pkts; + uint16_t num_cmplt_blks; +} __attribute__ ((packed)) cmplt_handle; +typedef struct { + uint16_t total_num_blocks; + uint8_t num_handles; + cmplt_handle handles[0]; +} __attribute__ ((packed)) evt_num_completed_blocks; + +#define EVT_AMP_STATUS_CHANGE 0x4D +typedef struct { + uint8_t status; + uint8_t amp_status; +} __attribute__ ((packed)) evt_amp_status_change; +#define EVT_AMP_STATUS_CHANGE_SIZE 2 + +#define EVT_TESTING 0xFE + +#define EVT_VENDOR 0xFF + +/* Internal events generated by BlueZ stack */ +#define EVT_STACK_INTERNAL 0xFD +typedef struct { + uint16_t type; + uint8_t data[0]; +} __attribute__ ((packed)) evt_stack_internal; +#define EVT_STACK_INTERNAL_SIZE 2 + +#define EVT_SI_DEVICE 0x01 +typedef struct { + uint16_t event; + uint16_t dev_id; +} __attribute__ ((packed)) evt_si_device; +#define EVT_SI_DEVICE_SIZE 4 + +/* -------- HCI Packet structures -------- */ +#define HCI_TYPE_LEN 1 + +typedef struct { + uint16_t opcode; /* OCF & OGF */ + uint8_t plen; +} __attribute__ ((packed)) hci_command_hdr; +#define HCI_COMMAND_HDR_SIZE 3 + +typedef struct { + uint8_t evt; + uint8_t plen; +} __attribute__ ((packed)) hci_event_hdr; +#define HCI_EVENT_HDR_SIZE 2 + +typedef struct { + uint16_t handle; /* Handle & Flags(PB, BC) */ + uint16_t dlen; +} __attribute__ ((packed)) hci_acl_hdr; +#define HCI_ACL_HDR_SIZE 4 + +typedef struct { + uint16_t handle; + uint8_t dlen; +} __attribute__ ((packed)) hci_sco_hdr; +#define HCI_SCO_HDR_SIZE 3 + +typedef struct { + uint16_t device; + uint16_t type; + uint16_t plen; +} __attribute__ ((packed)) hci_msg_hdr; +#define HCI_MSG_HDR_SIZE 6 + +/* Command opcode pack/unpack */ +#define cmd_opcode_pack(ogf, ocf) (uint16_t)((ocf & 0x03ff)|(ogf << 10)) +#define cmd_opcode_ogf(op) (op >> 10) +#define cmd_opcode_ocf(op) (op & 0x03ff) + +/* ACL handle and flags pack/unpack */ +#define acl_handle_pack(h, f) (uint16_t)((h & 0x0fff)|(f << 12)) +#define acl_handle(h) (h & 0x0fff) +#define acl_flags(h) (h >> 12) + +#endif /* _NO_HCI_DEFS */ + +/* HCI Socket options */ +#define HCI_DATA_DIR 1 +#define HCI_FILTER 2 +#define HCI_TIME_STAMP 3 + +/* HCI CMSG flags */ +#define HCI_CMSG_DIR 0x0001 +#define HCI_CMSG_TSTAMP 0x0002 + +struct sockaddr_hci { + sa_family_t hci_family; + unsigned short hci_dev; + unsigned short hci_channel; +}; +#define HCI_DEV_NONE 0xffff + +#define HCI_CHANNEL_RAW 0 +#define HCI_CHANNEL_USER 1 +#define HCI_CHANNEL_MONITOR 2 +#define HCI_CHANNEL_CONTROL 3 + +struct hci_filter { + uint32_t type_mask; + uint32_t event_mask[2]; + uint16_t opcode; +}; + +#define HCI_FLT_TYPE_BITS 31 +#define HCI_FLT_EVENT_BITS 63 +#define HCI_FLT_OGF_BITS 63 +#define HCI_FLT_OCF_BITS 127 + +/* Ioctl requests structures */ +struct hci_dev_stats { + uint32_t err_rx; + uint32_t err_tx; + uint32_t cmd_tx; + uint32_t evt_rx; + uint32_t acl_tx; + uint32_t acl_rx; + uint32_t sco_tx; + uint32_t sco_rx; + uint32_t byte_rx; + uint32_t byte_tx; +}; + +struct hci_dev_info { + uint16_t dev_id; + char name[8]; + + bdaddr_t bdaddr; + + uint32_t flags; + uint8_t type; + + uint8_t features[8]; + + uint32_t pkt_type; + uint32_t link_policy; + uint32_t link_mode; + + uint16_t acl_mtu; + uint16_t acl_pkts; + uint16_t sco_mtu; + uint16_t sco_pkts; + + struct hci_dev_stats stat; +}; + +struct hci_conn_info { + uint16_t handle; + bdaddr_t bdaddr; + uint8_t type; + uint8_t out; + uint16_t state; + uint32_t link_mode; +}; + +struct hci_dev_req { + uint16_t dev_id; + uint32_t dev_opt; +}; + +struct hci_dev_list_req { + uint16_t dev_num; + struct hci_dev_req dev_req[0]; /* hci_dev_req structures */ +}; + +struct hci_conn_list_req { + uint16_t dev_id; + uint16_t conn_num; + struct hci_conn_info conn_info[0]; +}; + +struct hci_conn_info_req { + bdaddr_t bdaddr; + uint8_t type; + struct hci_conn_info conn_info[0]; +}; + +struct hci_auth_info_req { + bdaddr_t bdaddr; + uint8_t type; +}; + +struct hci_inquiry_req { + uint16_t dev_id; + uint16_t flags; + uint8_t lap[3]; + uint8_t length; + uint8_t num_rsp; +}; +#define IREQ_CACHE_FLUSH 0x0001 + +#ifdef __cplusplus +} +#endif + +#endif /* __HCI_H */ diff --git a/drive-sdk/deps/bzle/include/bzle/bluetooth/hci_lib.h b/drive-sdk/deps/bzle/include/bzle/bluetooth/hci_lib.h new file mode 100644 index 0000000..50744c3 --- /dev/null +++ b/drive-sdk/deps/bzle/include/bzle/bluetooth/hci_lib.h @@ -0,0 +1,235 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2000-2001 Qualcomm Incorporated + * Copyright (C) 2002-2003 Maxim Krasnyansky + * Copyright (C) 2002-2010 Marcel Holtmann + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifndef __HCI_LIB_H +#define __HCI_LIB_H + +#ifdef __cplusplus +extern "C" { +#endif + +struct hci_request { + uint16_t ogf; + uint16_t ocf; + int event; + void *cparam; + int clen; + void *rparam; + int rlen; +}; + +struct hci_version { + uint16_t manufacturer; + uint8_t hci_ver; + uint16_t hci_rev; + uint8_t lmp_ver; + uint16_t lmp_subver; +}; + +int hci_open_dev(int dev_id); +int hci_close_dev(int dd); +int hci_send_cmd(int dd, uint16_t ogf, uint16_t ocf, uint8_t plen, void *param); +int hci_send_req(int dd, struct hci_request *req, int timeout); + +int hci_create_connection(int dd, const bdaddr_t *bdaddr, uint16_t ptype, uint16_t clkoffset, uint8_t rswitch, uint16_t *handle, int to); +int hci_disconnect(int dd, uint16_t handle, uint8_t reason, int to); + +int hci_inquiry(int dev_id, int len, int num_rsp, const uint8_t *lap, inquiry_info **ii, long flags); +int hci_devinfo(int dev_id, struct hci_dev_info *di); +int hci_devba(int dev_id, bdaddr_t *bdaddr); +int hci_devid(const char *str); + +int hci_read_local_name(int dd, int len, char *name, int to); +int hci_write_local_name(int dd, const char *name, int to); +int hci_read_remote_name(int dd, const bdaddr_t *bdaddr, int len, char *name, int to); +int hci_read_remote_name_with_clock_offset(int dd, const bdaddr_t *bdaddr, uint8_t pscan_rep_mode, uint16_t clkoffset, int len, char *name, int to); +int hci_read_remote_name_cancel(int dd, const bdaddr_t *bdaddr, int to); +int hci_read_remote_version(int dd, uint16_t handle, struct hci_version *ver, int to); +int hci_read_remote_features(int dd, uint16_t handle, uint8_t *features, int to); +int hci_read_remote_ext_features(int dd, uint16_t handle, uint8_t page, uint8_t *max_page, uint8_t *features, int to); +int hci_read_clock_offset(int dd, uint16_t handle, uint16_t *clkoffset, int to); +int hci_read_local_version(int dd, struct hci_version *ver, int to); +int hci_read_local_commands(int dd, uint8_t *commands, int to); +int hci_read_local_features(int dd, uint8_t *features, int to); +int hci_read_local_ext_features(int dd, uint8_t page, uint8_t *max_page, uint8_t *features, int to); +int hci_read_bd_addr(int dd, bdaddr_t *bdaddr, int to); +int hci_read_class_of_dev(int dd, uint8_t *cls, int to); +int hci_write_class_of_dev(int dd, uint32_t cls, int to); +int hci_read_voice_setting(int dd, uint16_t *vs, int to); +int hci_write_voice_setting(int dd, uint16_t vs, int to); +int hci_read_current_iac_lap(int dd, uint8_t *num_iac, uint8_t *lap, int to); +int hci_write_current_iac_lap(int dd, uint8_t num_iac, uint8_t *lap, int to); +int hci_read_stored_link_key(int dd, bdaddr_t *bdaddr, uint8_t all, int to); +int hci_write_stored_link_key(int dd, bdaddr_t *bdaddr, uint8_t *key, int to); +int hci_delete_stored_link_key(int dd, bdaddr_t *bdaddr, uint8_t all, int to); +int hci_authenticate_link(int dd, uint16_t handle, int to); +int hci_encrypt_link(int dd, uint16_t handle, uint8_t encrypt, int to); +int hci_change_link_key(int dd, uint16_t handle, int to); +int hci_switch_role(int dd, bdaddr_t *bdaddr, uint8_t role, int to); +int hci_park_mode(int dd, uint16_t handle, uint16_t max_interval, uint16_t min_interval, int to); +int hci_exit_park_mode(int dd, uint16_t handle, int to); +int hci_read_inquiry_scan_type(int dd, uint8_t *type, int to); +int hci_write_inquiry_scan_type(int dd, uint8_t type, int to); +int hci_read_inquiry_mode(int dd, uint8_t *mode, int to); +int hci_write_inquiry_mode(int dd, uint8_t mode, int to); +int hci_read_afh_mode(int dd, uint8_t *mode, int to); +int hci_write_afh_mode(int dd, uint8_t mode, int to); +int hci_read_ext_inquiry_response(int dd, uint8_t *fec, uint8_t *data, int to); +int hci_write_ext_inquiry_response(int dd, uint8_t fec, uint8_t *data, int to); +int hci_read_simple_pairing_mode(int dd, uint8_t *mode, int to); +int hci_write_simple_pairing_mode(int dd, uint8_t mode, int to); +int hci_read_local_oob_data(int dd, uint8_t *hash, uint8_t *randomizer, int to); +int hci_read_inq_response_tx_power_level(int dd, int8_t *level, int to); +int hci_read_inquiry_transmit_power_level(int dd, int8_t *level, int to); +int hci_write_inquiry_transmit_power_level(int dd, int8_t level, int to); +int hci_read_transmit_power_level(int dd, uint16_t handle, uint8_t type, int8_t *level, int to); +int hci_read_link_policy(int dd, uint16_t handle, uint16_t *policy, int to); +int hci_write_link_policy(int dd, uint16_t handle, uint16_t policy, int to); +int hci_read_link_supervision_timeout(int dd, uint16_t handle, uint16_t *timeout, int to); +int hci_write_link_supervision_timeout(int dd, uint16_t handle, uint16_t timeout, int to); +int hci_set_afh_classification(int dd, uint8_t *map, int to); +int hci_read_link_quality(int dd, uint16_t handle, uint8_t *link_quality, int to); +int hci_read_rssi(int dd, uint16_t handle, int8_t *rssi, int to); +int hci_read_afh_map(int dd, uint16_t handle, uint8_t *mode, uint8_t *map, int to); +int hci_read_clock(int dd, uint16_t handle, uint8_t which, uint32_t *clock, uint16_t *accuracy, int to); + +int hci_le_set_scan_enable(int dev_id, uint8_t enable, uint8_t filter_dup, int to); +int hci_le_set_scan_parameters(int dev_id, uint8_t type, uint16_t interval, + uint16_t window, uint8_t own_type, + uint8_t filter, int to); +int hci_le_set_advertise_enable(int dev_id, uint8_t enable, int to); +int hci_le_create_conn(int dd, uint16_t interval, uint16_t window, + uint8_t initiator_filter, uint8_t peer_bdaddr_type, + bdaddr_t peer_bdaddr, uint8_t own_bdaddr_type, + uint16_t min_interval, uint16_t max_interval, + uint16_t latency, uint16_t supervision_timeout, + uint16_t min_ce_length, uint16_t max_ce_length, + uint16_t *handle, int to); + +int hci_le_conn_update(int dd, uint16_t handle, uint16_t min_interval, + uint16_t max_interval, uint16_t latency, + uint16_t supervision_timeout, int to); +int hci_le_add_white_list(int dd, const bdaddr_t *bdaddr, uint8_t type, int to); +int hci_le_rm_white_list(int dd, const bdaddr_t *bdaddr, uint8_t type, int to); +int hci_le_read_white_list_size(int dd, uint8_t *size, int to); +int hci_le_clear_white_list(int dd, int to); +int hci_for_each_dev(int flag, int(*func)(int dd, int dev_id, long arg), long arg); +int hci_get_route(bdaddr_t *bdaddr); + +char *hci_bustostr(int bus); +char *hci_typetostr(int type); +char *hci_dtypetostr(int type); +char *hci_dflagstostr(uint32_t flags); +char *hci_ptypetostr(unsigned int ptype); +int hci_strtoptype(char *str, unsigned int *val); +char *hci_scoptypetostr(unsigned int ptype); +int hci_strtoscoptype(char *str, unsigned int *val); +char *hci_lptostr(unsigned int ptype); +int hci_strtolp(char *str, unsigned int *val); +char *hci_lmtostr(unsigned int ptype); +int hci_strtolm(char *str, unsigned int *val); + +char *hci_cmdtostr(unsigned int cmd); +char *hci_commandstostr(uint8_t *commands, char *pref, int width); + +char *hci_vertostr(unsigned int ver); +int hci_strtover(char *str, unsigned int *ver); +char *lmp_vertostr(unsigned int ver); +int lmp_strtover(char *str, unsigned int *ver); +char *pal_vertostr(unsigned int ver); +int pal_strtover(char *str, unsigned int *ver); + +char *lmp_featurestostr(uint8_t *features, char *pref, int width); + +static inline void hci_set_bit(int nr, void *addr) +{ + *((uint32_t *) addr + (nr >> 5)) |= (1 << (nr & 31)); +} + +static inline void hci_clear_bit(int nr, void *addr) +{ + *((uint32_t *) addr + (nr >> 5)) &= ~(1 << (nr & 31)); +} + +static inline int hci_test_bit(int nr, void *addr) +{ + return *((uint32_t *) addr + (nr >> 5)) & (1 << (nr & 31)); +} + +/* HCI filter tools */ +static inline void hci_filter_clear(struct hci_filter *f) +{ + memset(f, 0, sizeof(*f)); +} +static inline void hci_filter_set_ptype(int t, struct hci_filter *f) +{ + hci_set_bit((t == HCI_VENDOR_PKT) ? 0 : (t & HCI_FLT_TYPE_BITS), &f->type_mask); +} +static inline void hci_filter_clear_ptype(int t, struct hci_filter *f) +{ + hci_clear_bit((t == HCI_VENDOR_PKT) ? 0 : (t & HCI_FLT_TYPE_BITS), &f->type_mask); +} +static inline int hci_filter_test_ptype(int t, struct hci_filter *f) +{ + return hci_test_bit((t == HCI_VENDOR_PKT) ? 0 : (t & HCI_FLT_TYPE_BITS), &f->type_mask); +} +static inline void hci_filter_all_ptypes(struct hci_filter *f) +{ + memset((void *) &f->type_mask, 0xff, sizeof(f->type_mask)); +} +static inline void hci_filter_set_event(int e, struct hci_filter *f) +{ + hci_set_bit((e & HCI_FLT_EVENT_BITS), &f->event_mask); +} +static inline void hci_filter_clear_event(int e, struct hci_filter *f) +{ + hci_clear_bit((e & HCI_FLT_EVENT_BITS), &f->event_mask); +} +static inline int hci_filter_test_event(int e, struct hci_filter *f) +{ + return hci_test_bit((e & HCI_FLT_EVENT_BITS), &f->event_mask); +} +static inline void hci_filter_all_events(struct hci_filter *f) +{ + memset((void *) f->event_mask, 0xff, sizeof(f->event_mask)); +} +static inline void hci_filter_set_opcode(int opcode, struct hci_filter *f) +{ + f->opcode = opcode; +} +static inline void hci_filter_clear_opcode(struct hci_filter *f) +{ + f->opcode = 0; +} +static inline int hci_filter_test_opcode(int opcode, struct hci_filter *f) +{ + return (f->opcode == opcode); +} + +#ifdef __cplusplus +} +#endif + +#endif /* __HCI_LIB_H */ diff --git a/drive-sdk/deps/bzle/include/bzle/bluetooth/l2cap.h b/drive-sdk/deps/bzle/include/bzle/bluetooth/l2cap.h new file mode 100644 index 0000000..5ce94c4 --- /dev/null +++ b/drive-sdk/deps/bzle/include/bzle/bluetooth/l2cap.h @@ -0,0 +1,279 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2000-2001 Qualcomm Incorporated + * Copyright (C) 2002-2003 Maxim Krasnyansky + * Copyright (C) 2002-2010 Marcel Holtmann + * Copyright (c) 2012 Code Aurora Forum. All rights reserved. + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifndef __L2CAP_H +#define __L2CAP_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +/* L2CAP defaults */ +#define L2CAP_DEFAULT_MTU 672 +#define L2CAP_DEFAULT_FLUSH_TO 0xFFFF + +/* L2CAP socket address */ +struct sockaddr_l2 { + sa_family_t l2_family; + unsigned short l2_psm; + bdaddr_t l2_bdaddr; + unsigned short l2_cid; + uint8_t l2_bdaddr_type; +}; + +/* L2CAP socket options */ +#define L2CAP_OPTIONS 0x01 +struct l2cap_options { + uint16_t omtu; + uint16_t imtu; + uint16_t flush_to; + uint8_t mode; + uint8_t fcs; + uint8_t max_tx; + uint16_t txwin_size; +}; + +#define L2CAP_CONNINFO 0x02 +struct l2cap_conninfo { + uint16_t hci_handle; + uint8_t dev_class[3]; +}; + +#define L2CAP_LM 0x03 +#define L2CAP_LM_MASTER 0x0001 +#define L2CAP_LM_AUTH 0x0002 +#define L2CAP_LM_ENCRYPT 0x0004 +#define L2CAP_LM_TRUSTED 0x0008 +#define L2CAP_LM_RELIABLE 0x0010 +#define L2CAP_LM_SECURE 0x0020 + +/* L2CAP command codes */ +#define L2CAP_COMMAND_REJ 0x01 +#define L2CAP_CONN_REQ 0x02 +#define L2CAP_CONN_RSP 0x03 +#define L2CAP_CONF_REQ 0x04 +#define L2CAP_CONF_RSP 0x05 +#define L2CAP_DISCONN_REQ 0x06 +#define L2CAP_DISCONN_RSP 0x07 +#define L2CAP_ECHO_REQ 0x08 +#define L2CAP_ECHO_RSP 0x09 +#define L2CAP_INFO_REQ 0x0a +#define L2CAP_INFO_RSP 0x0b +#define L2CAP_CREATE_REQ 0x0c +#define L2CAP_CREATE_RSP 0x0d +#define L2CAP_MOVE_REQ 0x0e +#define L2CAP_MOVE_RSP 0x0f +#define L2CAP_MOVE_CFM 0x10 +#define L2CAP_MOVE_CFM_RSP 0x11 + +/* L2CAP extended feature mask */ +#define L2CAP_FEAT_FLOWCTL 0x00000001 +#define L2CAP_FEAT_RETRANS 0x00000002 +#define L2CAP_FEAT_BIDIR_QOS 0x00000004 +#define L2CAP_FEAT_ERTM 0x00000008 +#define L2CAP_FEAT_STREAMING 0x00000010 +#define L2CAP_FEAT_FCS 0x00000020 +#define L2CAP_FEAT_EXT_FLOW 0x00000040 +#define L2CAP_FEAT_FIXED_CHAN 0x00000080 +#define L2CAP_FEAT_EXT_WINDOW 0x00000100 +#define L2CAP_FEAT_UCD 0x00000200 + +/* L2CAP fixed channels */ +#define L2CAP_FC_L2CAP 0x02 +#define L2CAP_FC_CONNLESS 0x04 +#define L2CAP_FC_A2MP 0x08 + +/* L2CAP structures */ +typedef struct { + uint16_t len; + uint16_t cid; +} __attribute__ ((packed)) l2cap_hdr; +#define L2CAP_HDR_SIZE 4 + +typedef struct { + uint8_t code; + uint8_t ident; + uint16_t len; +} __attribute__ ((packed)) l2cap_cmd_hdr; +#define L2CAP_CMD_HDR_SIZE 4 + +typedef struct { + uint16_t reason; +} __attribute__ ((packed)) l2cap_cmd_rej; +#define L2CAP_CMD_REJ_SIZE 2 + +typedef struct { + uint16_t psm; + uint16_t scid; +} __attribute__ ((packed)) l2cap_conn_req; +#define L2CAP_CONN_REQ_SIZE 4 + +typedef struct { + uint16_t dcid; + uint16_t scid; + uint16_t result; + uint16_t status; +} __attribute__ ((packed)) l2cap_conn_rsp; +#define L2CAP_CONN_RSP_SIZE 8 + +/* connect result */ +#define L2CAP_CR_SUCCESS 0x0000 +#define L2CAP_CR_PEND 0x0001 +#define L2CAP_CR_BAD_PSM 0x0002 +#define L2CAP_CR_SEC_BLOCK 0x0003 +#define L2CAP_CR_NO_MEM 0x0004 + +/* connect status */ +#define L2CAP_CS_NO_INFO 0x0000 +#define L2CAP_CS_AUTHEN_PEND 0x0001 +#define L2CAP_CS_AUTHOR_PEND 0x0002 + +typedef struct { + uint16_t dcid; + uint16_t flags; + uint8_t data[0]; +} __attribute__ ((packed)) l2cap_conf_req; +#define L2CAP_CONF_REQ_SIZE 4 + +typedef struct { + uint16_t scid; + uint16_t flags; + uint16_t result; + uint8_t data[0]; +} __attribute__ ((packed)) l2cap_conf_rsp; +#define L2CAP_CONF_RSP_SIZE 6 + +#define L2CAP_CONF_SUCCESS 0x0000 +#define L2CAP_CONF_UNACCEPT 0x0001 +#define L2CAP_CONF_REJECT 0x0002 +#define L2CAP_CONF_UNKNOWN 0x0003 +#define L2CAP_CONF_PENDING 0x0004 +#define L2CAP_CONF_EFS_REJECT 0x0005 + +typedef struct { + uint8_t type; + uint8_t len; + uint8_t val[0]; +} __attribute__ ((packed)) l2cap_conf_opt; +#define L2CAP_CONF_OPT_SIZE 2 + +#define L2CAP_CONF_MTU 0x01 +#define L2CAP_CONF_FLUSH_TO 0x02 +#define L2CAP_CONF_QOS 0x03 +#define L2CAP_CONF_RFC 0x04 +#define L2CAP_CONF_FCS 0x05 +#define L2CAP_CONF_EFS 0x06 +#define L2CAP_CONF_EWS 0x07 + +#define L2CAP_CONF_MAX_SIZE 22 + +#define L2CAP_MODE_BASIC 0x00 +#define L2CAP_MODE_RETRANS 0x01 +#define L2CAP_MODE_FLOWCTL 0x02 +#define L2CAP_MODE_ERTM 0x03 +#define L2CAP_MODE_STREAMING 0x04 + +#define L2CAP_SERVTYPE_NOTRAFFIC 0x00 +#define L2CAP_SERVTYPE_BESTEFFORT 0x01 +#define L2CAP_SERVTYPE_GUARANTEED 0x02 + +typedef struct { + uint16_t dcid; + uint16_t scid; +} __attribute__ ((packed)) l2cap_disconn_req; +#define L2CAP_DISCONN_REQ_SIZE 4 + +typedef struct { + uint16_t dcid; + uint16_t scid; +} __attribute__ ((packed)) l2cap_disconn_rsp; +#define L2CAP_DISCONN_RSP_SIZE 4 + +typedef struct { + uint16_t type; +} __attribute__ ((packed)) l2cap_info_req; +#define L2CAP_INFO_REQ_SIZE 2 + +typedef struct { + uint16_t type; + uint16_t result; + uint8_t data[0]; +} __attribute__ ((packed)) l2cap_info_rsp; +#define L2CAP_INFO_RSP_SIZE 4 + +/* info type */ +#define L2CAP_IT_CL_MTU 0x0001 +#define L2CAP_IT_FEAT_MASK 0x0002 + +/* info result */ +#define L2CAP_IR_SUCCESS 0x0000 +#define L2CAP_IR_NOTSUPP 0x0001 + +typedef struct { + uint16_t psm; + uint16_t scid; + uint8_t id; +} __attribute__ ((packed)) l2cap_create_req; +#define L2CAP_CREATE_REQ_SIZE 5 + +typedef struct { + uint16_t dcid; + uint16_t scid; + uint16_t result; + uint16_t status; +} __attribute__ ((packed)) l2cap_create_rsp; +#define L2CAP_CREATE_RSP_SIZE 8 + +typedef struct { + uint16_t icid; + uint8_t id; +} __attribute__ ((packed)) l2cap_move_req; +#define L2CAP_MOVE_REQ_SIZE 3 + +typedef struct { + uint16_t icid; + uint16_t result; +} __attribute__ ((packed)) l2cap_move_rsp; +#define L2CAP_MOVE_RSP_SIZE 4 + +typedef struct { + uint16_t icid; + uint16_t result; +} __attribute__ ((packed)) l2cap_move_cfm; +#define L2CAP_MOVE_CFM_SIZE 4 + +typedef struct { + uint16_t icid; +} __attribute__ ((packed)) l2cap_move_cfm_rsp; +#define L2CAP_MOVE_CFM_RSP_SIZE 2 + +#ifdef __cplusplus +} +#endif + +#endif /* __L2CAP_H */ diff --git a/drive-sdk/deps/bzle/include/bzle/bluetooth/sco.h b/drive-sdk/deps/bzle/include/bzle/bluetooth/sco.h new file mode 100644 index 0000000..75336a5 --- /dev/null +++ b/drive-sdk/deps/bzle/include/bzle/bluetooth/sco.h @@ -0,0 +1,62 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2002-2003 Maxim Krasnyansky + * Copyright (C) 2002-2010 Marcel Holtmann + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifndef __SCO_H +#define __SCO_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* SCO defaults */ +#define SCO_DEFAULT_MTU 500 +#define SCO_DEFAULT_FLUSH_TO 0xFFFF + +#define SCO_CONN_TIMEOUT (HZ * 40) +#define SCO_DISCONN_TIMEOUT (HZ * 2) +#define SCO_CONN_IDLE_TIMEOUT (HZ * 60) + +/* SCO socket address */ +struct sockaddr_sco { + sa_family_t sco_family; + bdaddr_t sco_bdaddr; +}; + +/* set/get sockopt defines */ +#define SCO_OPTIONS 0x01 +struct sco_options { + uint16_t mtu; +}; + +#define SCO_CONNINFO 0x02 +struct sco_conninfo { + uint16_t hci_handle; + uint8_t dev_class[3]; +}; + +#ifdef __cplusplus +} +#endif + +#endif /* __SCO_H */ diff --git a/drive-sdk/deps/bzle/include/bzle/bluetooth/sdp.h b/drive-sdk/deps/bzle/include/bzle/bluetooth/sdp.h new file mode 100644 index 0000000..a0108cb --- /dev/null +++ b/drive-sdk/deps/bzle/include/bzle/bluetooth/sdp.h @@ -0,0 +1,534 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2001-2002 Nokia Corporation + * Copyright (C) 2002-2003 Maxim Krasnyansky + * Copyright (C) 2002-2010 Marcel Holtmann + * Copyright (C) 2002-2003 Stephen Crane + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifndef __SDP_H +#define __SDP_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include "bluetooth.h" + +#define SDP_UNIX_PATH "/var/run/sdp" +#define SDP_RESPONSE_TIMEOUT 20 +#define SDP_REQ_BUFFER_SIZE 2048 +#define SDP_RSP_BUFFER_SIZE 65535 +#define SDP_PDU_CHUNK_SIZE 1024 + +/* + * All definitions are based on Bluetooth Assigned Numbers + * of the Bluetooth Specification + */ +#define SDP_PSM 0x0001 + +/* + * Protocol UUIDs + */ +#define SDP_UUID 0x0001 +#define UDP_UUID 0x0002 +#define RFCOMM_UUID 0x0003 +#define TCP_UUID 0x0004 +#define TCS_BIN_UUID 0x0005 +#define TCS_AT_UUID 0x0006 +#define ATT_UUID 0x0007 +#define OBEX_UUID 0x0008 +#define IP_UUID 0x0009 +#define FTP_UUID 0x000a +#define HTTP_UUID 0x000c +#define WSP_UUID 0x000e +#define BNEP_UUID 0x000f +#define UPNP_UUID 0x0010 +#define HIDP_UUID 0x0011 +#define HCRP_CTRL_UUID 0x0012 +#define HCRP_DATA_UUID 0x0014 +#define HCRP_NOTE_UUID 0x0016 +#define AVCTP_UUID 0x0017 +#define AVDTP_UUID 0x0019 +#define CMTP_UUID 0x001b +#define UDI_UUID 0x001d +#define MCAP_CTRL_UUID 0x001e +#define MCAP_DATA_UUID 0x001f +#define L2CAP_UUID 0x0100 + +/* + * Service class identifiers of standard services and service groups + */ +#define SDP_SERVER_SVCLASS_ID 0x1000 +#define BROWSE_GRP_DESC_SVCLASS_ID 0x1001 +#define PUBLIC_BROWSE_GROUP 0x1002 +#define SERIAL_PORT_SVCLASS_ID 0x1101 +#define LAN_ACCESS_SVCLASS_ID 0x1102 +#define DIALUP_NET_SVCLASS_ID 0x1103 +#define IRMC_SYNC_SVCLASS_ID 0x1104 +#define OBEX_OBJPUSH_SVCLASS_ID 0x1105 +#define OBEX_FILETRANS_SVCLASS_ID 0x1106 +#define IRMC_SYNC_CMD_SVCLASS_ID 0x1107 +#define HEADSET_SVCLASS_ID 0x1108 +#define CORDLESS_TELEPHONY_SVCLASS_ID 0x1109 +#define AUDIO_SOURCE_SVCLASS_ID 0x110a +#define AUDIO_SINK_SVCLASS_ID 0x110b +#define AV_REMOTE_TARGET_SVCLASS_ID 0x110c +#define ADVANCED_AUDIO_SVCLASS_ID 0x110d +#define AV_REMOTE_SVCLASS_ID 0x110e +#define AV_REMOTE_CONTROLLER_SVCLASS_ID 0x110f +#define INTERCOM_SVCLASS_ID 0x1110 +#define FAX_SVCLASS_ID 0x1111 +#define HEADSET_AGW_SVCLASS_ID 0x1112 +#define WAP_SVCLASS_ID 0x1113 +#define WAP_CLIENT_SVCLASS_ID 0x1114 +#define PANU_SVCLASS_ID 0x1115 +#define NAP_SVCLASS_ID 0x1116 +#define GN_SVCLASS_ID 0x1117 +#define DIRECT_PRINTING_SVCLASS_ID 0x1118 +#define REFERENCE_PRINTING_SVCLASS_ID 0x1119 +#define IMAGING_SVCLASS_ID 0x111a +#define IMAGING_RESPONDER_SVCLASS_ID 0x111b +#define IMAGING_ARCHIVE_SVCLASS_ID 0x111c +#define IMAGING_REFOBJS_SVCLASS_ID 0x111d +#define HANDSFREE_SVCLASS_ID 0x111e +#define HANDSFREE_AGW_SVCLASS_ID 0x111f +#define DIRECT_PRT_REFOBJS_SVCLASS_ID 0x1120 +#define REFLECTED_UI_SVCLASS_ID 0x1121 +#define BASIC_PRINTING_SVCLASS_ID 0x1122 +#define PRINTING_STATUS_SVCLASS_ID 0x1123 +#define HID_SVCLASS_ID 0x1124 +#define HCR_SVCLASS_ID 0x1125 +#define HCR_PRINT_SVCLASS_ID 0x1126 +#define HCR_SCAN_SVCLASS_ID 0x1127 +#define CIP_SVCLASS_ID 0x1128 +#define VIDEO_CONF_GW_SVCLASS_ID 0x1129 +#define UDI_MT_SVCLASS_ID 0x112a +#define UDI_TA_SVCLASS_ID 0x112b +#define AV_SVCLASS_ID 0x112c +#define SAP_SVCLASS_ID 0x112d +#define PBAP_PCE_SVCLASS_ID 0x112e +#define PBAP_PSE_SVCLASS_ID 0x112f +#define PBAP_SVCLASS_ID 0x1130 +#define MAP_MSE_SVCLASS_ID 0x1132 +#define MAP_MCE_SVCLASS_ID 0x1133 +#define MAP_SVCLASS_ID 0x1134 +#define GNSS_SVCLASS_ID 0x1135 +#define GNSS_SERVER_SVCLASS_ID 0x1136 +#define PNP_INFO_SVCLASS_ID 0x1200 +#define GENERIC_NETWORKING_SVCLASS_ID 0x1201 +#define GENERIC_FILETRANS_SVCLASS_ID 0x1202 +#define GENERIC_AUDIO_SVCLASS_ID 0x1203 +#define GENERIC_TELEPHONY_SVCLASS_ID 0x1204 +#define UPNP_SVCLASS_ID 0x1205 +#define UPNP_IP_SVCLASS_ID 0x1206 +#define UPNP_PAN_SVCLASS_ID 0x1300 +#define UPNP_LAP_SVCLASS_ID 0x1301 +#define UPNP_L2CAP_SVCLASS_ID 0x1302 +#define VIDEO_SOURCE_SVCLASS_ID 0x1303 +#define VIDEO_SINK_SVCLASS_ID 0x1304 +#define VIDEO_DISTRIBUTION_SVCLASS_ID 0x1305 +#define HDP_SVCLASS_ID 0x1400 +#define HDP_SOURCE_SVCLASS_ID 0x1401 +#define HDP_SINK_SVCLASS_ID 0x1402 +#define GENERIC_ACCESS_SVCLASS_ID 0x1800 +#define GENERIC_ATTRIB_SVCLASS_ID 0x1801 +#define APPLE_AGENT_SVCLASS_ID 0x2112 + +/* + * Standard profile descriptor identifiers; note these + * may be identical to some of the service classes defined above + */ +#define SDP_SERVER_PROFILE_ID SDP_SERVER_SVCLASS_ID +#define BROWSE_GRP_DESC_PROFILE_ID BROWSE_GRP_DESC_SVCLASS_ID +#define SERIAL_PORT_PROFILE_ID SERIAL_PORT_SVCLASS_ID +#define LAN_ACCESS_PROFILE_ID LAN_ACCESS_SVCLASS_ID +#define DIALUP_NET_PROFILE_ID DIALUP_NET_SVCLASS_ID +#define IRMC_SYNC_PROFILE_ID IRMC_SYNC_SVCLASS_ID +#define OBEX_OBJPUSH_PROFILE_ID OBEX_OBJPUSH_SVCLASS_ID +#define OBEX_FILETRANS_PROFILE_ID OBEX_FILETRANS_SVCLASS_ID +#define IRMC_SYNC_CMD_PROFILE_ID IRMC_SYNC_CMD_SVCLASS_ID +#define HEADSET_PROFILE_ID HEADSET_SVCLASS_ID +#define CORDLESS_TELEPHONY_PROFILE_ID CORDLESS_TELEPHONY_SVCLASS_ID +#define AUDIO_SOURCE_PROFILE_ID AUDIO_SOURCE_SVCLASS_ID +#define AUDIO_SINK_PROFILE_ID AUDIO_SINK_SVCLASS_ID +#define AV_REMOTE_TARGET_PROFILE_ID AV_REMOTE_TARGET_SVCLASS_ID +#define ADVANCED_AUDIO_PROFILE_ID ADVANCED_AUDIO_SVCLASS_ID +#define AV_REMOTE_PROFILE_ID AV_REMOTE_SVCLASS_ID +#define VIDEO_CONF_PROFILE_ID VIDEO_CONF_SVCLASS_ID +#define INTERCOM_PROFILE_ID INTERCOM_SVCLASS_ID +#define FAX_PROFILE_ID FAX_SVCLASS_ID +#define HEADSET_AGW_PROFILE_ID HEADSET_AGW_SVCLASS_ID +#define WAP_PROFILE_ID WAP_SVCLASS_ID +#define WAP_CLIENT_PROFILE_ID WAP_CLIENT_SVCLASS_ID +#define PANU_PROFILE_ID PANU_SVCLASS_ID +#define NAP_PROFILE_ID NAP_SVCLASS_ID +#define GN_PROFILE_ID GN_SVCLASS_ID +#define DIRECT_PRINTING_PROFILE_ID DIRECT_PRINTING_SVCLASS_ID +#define REFERENCE_PRINTING_PROFILE_ID REFERENCE_PRINTING_SVCLASS_ID +#define IMAGING_PROFILE_ID IMAGING_SVCLASS_ID +#define IMAGING_RESPONDER_PROFILE_ID IMAGING_RESPONDER_SVCLASS_ID +#define IMAGING_ARCHIVE_PROFILE_ID IMAGING_ARCHIVE_SVCLASS_ID +#define IMAGING_REFOBJS_PROFILE_ID IMAGING_REFOBJS_SVCLASS_ID +#define HANDSFREE_PROFILE_ID HANDSFREE_SVCLASS_ID +#define HANDSFREE_AGW_PROFILE_ID HANDSFREE_AGW_SVCLASS_ID +#define DIRECT_PRT_REFOBJS_PROFILE_ID DIRECT_PRT_REFOBJS_SVCLASS_ID +#define REFLECTED_UI_PROFILE_ID REFLECTED_UI_SVCLASS_ID +#define BASIC_PRINTING_PROFILE_ID BASIC_PRINTING_SVCLASS_ID +#define PRINTING_STATUS_PROFILE_ID PRINTING_STATUS_SVCLASS_ID +#define HID_PROFILE_ID HID_SVCLASS_ID +#define HCR_PROFILE_ID HCR_SCAN_SVCLASS_ID +#define HCR_PRINT_PROFILE_ID HCR_PRINT_SVCLASS_ID +#define HCR_SCAN_PROFILE_ID HCR_SCAN_SVCLASS_ID +#define CIP_PROFILE_ID CIP_SVCLASS_ID +#define VIDEO_CONF_GW_PROFILE_ID VIDEO_CONF_GW_SVCLASS_ID +#define UDI_MT_PROFILE_ID UDI_MT_SVCLASS_ID +#define UDI_TA_PROFILE_ID UDI_TA_SVCLASS_ID +#define AV_PROFILE_ID AV_SVCLASS_ID +#define SAP_PROFILE_ID SAP_SVCLASS_ID +#define PBAP_PCE_PROFILE_ID PBAP_PCE_SVCLASS_ID +#define PBAP_PSE_PROFILE_ID PBAP_PSE_SVCLASS_ID +#define PBAP_PROFILE_ID PBAP_SVCLASS_ID +#define MAP_PROFILE_ID MAP_SVCLASS_ID +#define PNP_INFO_PROFILE_ID PNP_INFO_SVCLASS_ID +#define GENERIC_NETWORKING_PROFILE_ID GENERIC_NETWORKING_SVCLASS_ID +#define GENERIC_FILETRANS_PROFILE_ID GENERIC_FILETRANS_SVCLASS_ID +#define GENERIC_AUDIO_PROFILE_ID GENERIC_AUDIO_SVCLASS_ID +#define GENERIC_TELEPHONY_PROFILE_ID GENERIC_TELEPHONY_SVCLASS_ID +#define UPNP_PROFILE_ID UPNP_SVCLASS_ID +#define UPNP_IP_PROFILE_ID UPNP_IP_SVCLASS_ID +#define UPNP_PAN_PROFILE_ID UPNP_PAN_SVCLASS_ID +#define UPNP_LAP_PROFILE_ID UPNP_LAP_SVCLASS_ID +#define UPNP_L2CAP_PROFILE_ID UPNP_L2CAP_SVCLASS_ID +#define VIDEO_SOURCE_PROFILE_ID VIDEO_SOURCE_SVCLASS_ID +#define VIDEO_SINK_PROFILE_ID VIDEO_SINK_SVCLASS_ID +#define VIDEO_DISTRIBUTION_PROFILE_ID VIDEO_DISTRIBUTION_SVCLASS_ID +#define HDP_PROFILE_ID HDP_SVCLASS_ID +#define HDP_SOURCE_PROFILE_ID HDP_SOURCE_SVCLASS_ID +#define HDP_SINK_PROFILE_ID HDP_SINK_SVCLASS_ID +#define GENERIC_ACCESS_PROFILE_ID GENERIC_ACCESS_SVCLASS_ID +#define GENERIC_ATTRIB_PROFILE_ID GENERIC_ATTRIB_SVCLASS_ID +#define APPLE_AGENT_PROFILE_ID APPLE_AGENT_SVCLASS_ID + +/* + * Compatibility macros for the old MDP acronym + */ +#define MDP_SVCLASS_ID HDP_SVCLASS_ID +#define MDP_SOURCE_SVCLASS_ID HDP_SOURCE_SVCLASS_ID +#define MDP_SINK_SVCLASS_ID HDP_SINK_SVCLASS_ID +#define MDP_PROFILE_ID HDP_PROFILE_ID +#define MDP_SOURCE_PROFILE_ID HDP_SOURCE_PROFILE_ID +#define MDP_SINK_PROFILE_ID HDP_SINK_PROFILE_ID + +/* + * Attribute identifier codes + */ +#define SDP_SERVER_RECORD_HANDLE 0x0000 + +/* + * Possible values for attribute-id are listed below. + * See SDP Spec, section "Service Attribute Definitions" for more details. + */ +#define SDP_ATTR_RECORD_HANDLE 0x0000 +#define SDP_ATTR_SVCLASS_ID_LIST 0x0001 +#define SDP_ATTR_RECORD_STATE 0x0002 +#define SDP_ATTR_SERVICE_ID 0x0003 +#define SDP_ATTR_PROTO_DESC_LIST 0x0004 +#define SDP_ATTR_BROWSE_GRP_LIST 0x0005 +#define SDP_ATTR_LANG_BASE_ATTR_ID_LIST 0x0006 +#define SDP_ATTR_SVCINFO_TTL 0x0007 +#define SDP_ATTR_SERVICE_AVAILABILITY 0x0008 +#define SDP_ATTR_PFILE_DESC_LIST 0x0009 +#define SDP_ATTR_DOC_URL 0x000a +#define SDP_ATTR_CLNT_EXEC_URL 0x000b +#define SDP_ATTR_ICON_URL 0x000c +#define SDP_ATTR_ADD_PROTO_DESC_LIST 0x000d + +#define SDP_ATTR_GROUP_ID 0x0200 +#define SDP_ATTR_IP_SUBNET 0x0200 +#define SDP_ATTR_VERSION_NUM_LIST 0x0200 +#define SDP_ATTR_SUPPORTED_FEATURES_LIST 0x0200 +#define SDP_ATTR_GOEP_L2CAP_PSM 0x0200 +#define SDP_ATTR_SVCDB_STATE 0x0201 + +#define SDP_ATTR_SERVICE_VERSION 0x0300 +#define SDP_ATTR_EXTERNAL_NETWORK 0x0301 +#define SDP_ATTR_SUPPORTED_DATA_STORES_LIST 0x0301 +#define SDP_ATTR_DATA_EXCHANGE_SPEC 0x0301 +#define SDP_ATTR_NETWORK 0x0301 +#define SDP_ATTR_FAX_CLASS1_SUPPORT 0x0302 +#define SDP_ATTR_REMOTE_AUDIO_VOLUME_CONTROL 0x0302 +#define SDP_ATTR_MCAP_SUPPORTED_PROCEDURES 0x0302 +#define SDP_ATTR_FAX_CLASS20_SUPPORT 0x0303 +#define SDP_ATTR_SUPPORTED_FORMATS_LIST 0x0303 +#define SDP_ATTR_FAX_CLASS2_SUPPORT 0x0304 +#define SDP_ATTR_AUDIO_FEEDBACK_SUPPORT 0x0305 +#define SDP_ATTR_NETWORK_ADDRESS 0x0306 +#define SDP_ATTR_WAP_GATEWAY 0x0307 +#define SDP_ATTR_HOMEPAGE_URL 0x0308 +#define SDP_ATTR_WAP_STACK_TYPE 0x0309 +#define SDP_ATTR_SECURITY_DESC 0x030a +#define SDP_ATTR_NET_ACCESS_TYPE 0x030b +#define SDP_ATTR_MAX_NET_ACCESSRATE 0x030c +#define SDP_ATTR_IP4_SUBNET 0x030d +#define SDP_ATTR_IP6_SUBNET 0x030e +#define SDP_ATTR_SUPPORTED_CAPABILITIES 0x0310 +#define SDP_ATTR_SUPPORTED_FEATURES 0x0311 +#define SDP_ATTR_SUPPORTED_FUNCTIONS 0x0312 +#define SDP_ATTR_TOTAL_IMAGING_DATA_CAPACITY 0x0313 +#define SDP_ATTR_SUPPORTED_REPOSITORIES 0x0314 +#define SDP_ATTR_MAS_INSTANCE_ID 0x0315 +#define SDP_ATTR_SUPPORTED_MESSAGE_TYPES 0x0316 + +#define SDP_ATTR_SPECIFICATION_ID 0x0200 +#define SDP_ATTR_VENDOR_ID 0x0201 +#define SDP_ATTR_PRODUCT_ID 0x0202 +#define SDP_ATTR_VERSION 0x0203 +#define SDP_ATTR_PRIMARY_RECORD 0x0204 +#define SDP_ATTR_VENDOR_ID_SOURCE 0x0205 + +#define SDP_ATTR_HID_DEVICE_RELEASE_NUMBER 0x0200 +#define SDP_ATTR_HID_PARSER_VERSION 0x0201 +#define SDP_ATTR_HID_DEVICE_SUBCLASS 0x0202 +#define SDP_ATTR_HID_COUNTRY_CODE 0x0203 +#define SDP_ATTR_HID_VIRTUAL_CABLE 0x0204 +#define SDP_ATTR_HID_RECONNECT_INITIATE 0x0205 +#define SDP_ATTR_HID_DESCRIPTOR_LIST 0x0206 +#define SDP_ATTR_HID_LANG_ID_BASE_LIST 0x0207 +#define SDP_ATTR_HID_SDP_DISABLE 0x0208 +#define SDP_ATTR_HID_BATTERY_POWER 0x0209 +#define SDP_ATTR_HID_REMOTE_WAKEUP 0x020a +#define SDP_ATTR_HID_PROFILE_VERSION 0x020b +#define SDP_ATTR_HID_SUPERVISION_TIMEOUT 0x020c +#define SDP_ATTR_HID_NORMALLY_CONNECTABLE 0x020d +#define SDP_ATTR_HID_BOOT_DEVICE 0x020e + +/* + * These identifiers are based on the SDP spec stating that + * "base attribute id of the primary (universal) language must be 0x0100" + * + * Other languages should have their own offset; e.g.: + * #define XXXLangBase yyyy + * #define AttrServiceName_XXX 0x0000+XXXLangBase + */ +#define SDP_PRIMARY_LANG_BASE 0x0100 + +#define SDP_ATTR_SVCNAME_PRIMARY 0x0000 + SDP_PRIMARY_LANG_BASE +#define SDP_ATTR_SVCDESC_PRIMARY 0x0001 + SDP_PRIMARY_LANG_BASE +#define SDP_ATTR_PROVNAME_PRIMARY 0x0002 + SDP_PRIMARY_LANG_BASE + +/* + * The Data representation in SDP PDUs (pps 339, 340 of BT SDP Spec) + * These are the exact data type+size descriptor values + * that go into the PDU buffer. + * + * The datatype (leading 5bits) + size descriptor (last 3 bits) + * is 8 bits. The size descriptor is critical to extract the + * right number of bytes for the data value from the PDU. + * + * For most basic types, the datatype+size descriptor is + * straightforward. However for constructed types and strings, + * the size of the data is in the next "n" bytes following the + * 8 bits (datatype+size) descriptor. Exactly what the "n" is + * specified in the 3 bits of the data size descriptor. + * + * TextString and URLString can be of size 2^{8, 16, 32} bytes + * DataSequence and DataSequenceAlternates can be of size 2^{8, 16, 32} + * The size are computed post-facto in the API and are not known apriori + */ +#define SDP_DATA_NIL 0x00 +#define SDP_UINT8 0x08 +#define SDP_UINT16 0x09 +#define SDP_UINT32 0x0A +#define SDP_UINT64 0x0B +#define SDP_UINT128 0x0C +#define SDP_INT8 0x10 +#define SDP_INT16 0x11 +#define SDP_INT32 0x12 +#define SDP_INT64 0x13 +#define SDP_INT128 0x14 +#define SDP_UUID_UNSPEC 0x18 +#define SDP_UUID16 0x19 +#define SDP_UUID32 0x1A +#define SDP_UUID128 0x1C +#define SDP_TEXT_STR_UNSPEC 0x20 +#define SDP_TEXT_STR8 0x25 +#define SDP_TEXT_STR16 0x26 +#define SDP_TEXT_STR32 0x27 +#define SDP_BOOL 0x28 +#define SDP_SEQ_UNSPEC 0x30 +#define SDP_SEQ8 0x35 +#define SDP_SEQ16 0x36 +#define SDP_SEQ32 0x37 +#define SDP_ALT_UNSPEC 0x38 +#define SDP_ALT8 0x3D +#define SDP_ALT16 0x3E +#define SDP_ALT32 0x3F +#define SDP_URL_STR_UNSPEC 0x40 +#define SDP_URL_STR8 0x45 +#define SDP_URL_STR16 0x46 +#define SDP_URL_STR32 0x47 + +/* + * The PDU identifiers of SDP packets between client and server + */ +#define SDP_ERROR_RSP 0x01 +#define SDP_SVC_SEARCH_REQ 0x02 +#define SDP_SVC_SEARCH_RSP 0x03 +#define SDP_SVC_ATTR_REQ 0x04 +#define SDP_SVC_ATTR_RSP 0x05 +#define SDP_SVC_SEARCH_ATTR_REQ 0x06 +#define SDP_SVC_SEARCH_ATTR_RSP 0x07 + +/* + * Some additions to support service registration. + * These are outside the scope of the Bluetooth specification + */ +#define SDP_SVC_REGISTER_REQ 0x75 +#define SDP_SVC_REGISTER_RSP 0x76 +#define SDP_SVC_UPDATE_REQ 0x77 +#define SDP_SVC_UPDATE_RSP 0x78 +#define SDP_SVC_REMOVE_REQ 0x79 +#define SDP_SVC_REMOVE_RSP 0x80 + +/* + * SDP Error codes + */ +#define SDP_INVALID_VERSION 0x0001 +#define SDP_INVALID_RECORD_HANDLE 0x0002 +#define SDP_INVALID_SYNTAX 0x0003 +#define SDP_INVALID_PDU_SIZE 0x0004 +#define SDP_INVALID_CSTATE 0x0005 + +/* + * SDP PDU + */ +typedef struct { + uint8_t pdu_id; + uint16_t tid; + uint16_t plen; +} __attribute__ ((packed)) sdp_pdu_hdr_t; + +/* + * Common definitions for attributes in the SDP. + * Should the type of any of these change, you need only make a change here. + */ + +typedef struct { + uint8_t type; + union { + uint16_t uuid16; + uint32_t uuid32; + uint128_t uuid128; + } value; +} uuid_t; + +#define SDP_IS_UUID(x) ((x) == SDP_UUID16 || (x) == SDP_UUID32 || \ + (x) == SDP_UUID128) +#define SDP_IS_ALT(x) ((x) == SDP_ALT8 || (x) == SDP_ALT16 || (x) == SDP_ALT32) +#define SDP_IS_SEQ(x) ((x) == SDP_SEQ8 || (x) == SDP_SEQ16 || (x) == SDP_SEQ32) +#define SDP_IS_TEXT_STR(x) ((x) == SDP_TEXT_STR8 || (x) == SDP_TEXT_STR16 || \ + (x) == SDP_TEXT_STR32) + +typedef struct _sdp_list sdp_list_t; +struct _sdp_list { + sdp_list_t *next; + void *data; +}; + +/* + * User-visible strings can be in many languages + * in addition to the universal language. + * + * Language meta-data includes language code in ISO639 + * followed by the encoding format. The third field in this + * structure is the attribute offset for the language. + * User-visible strings in the specified language can be + * obtained at this offset. + */ +typedef struct { + uint16_t code_ISO639; + uint16_t encoding; + uint16_t base_offset; +} sdp_lang_attr_t; + +/* + * Profile descriptor is the Bluetooth profile metadata. If a + * service conforms to a well-known profile, then its profile + * identifier (UUID) is an attribute of the service. In addition, + * if the profile has a version number it is specified here. + */ +typedef struct { + uuid_t uuid; + uint16_t version; +} sdp_profile_desc_t; + +typedef struct { + uint8_t major; + uint8_t minor; +} sdp_version_t; + +typedef struct { + uint8_t *data; + uint32_t data_size; + uint32_t buf_size; +} sdp_buf_t; + +typedef struct { + uint32_t handle; + + /* Search pattern: a sequence of all UUIDs seen in this record */ + sdp_list_t *pattern; + sdp_list_t *attrlist; + + /* Main service class for Extended Inquiry Response */ + uuid_t svclass; +} sdp_record_t; + +typedef struct sdp_data_struct sdp_data_t; +struct sdp_data_struct { + uint8_t dtd; + uint16_t attrId; + union { + int8_t int8; + int16_t int16; + int32_t int32; + int64_t int64; + uint128_t int128; + uint8_t uint8; + uint16_t uint16; + uint32_t uint32; + uint64_t uint64; + uint128_t uint128; + uuid_t uuid; + char *str; + sdp_data_t *dataseq; + } val; + sdp_data_t *next; + int unitSize; +}; + +#ifdef __cplusplus +} +#endif + +#endif /* __SDP_H */ diff --git a/drive-sdk/deps/bzle/include/bzle/bluetooth/sdp_lib.h b/drive-sdk/deps/bzle/include/bzle/bluetooth/sdp_lib.h new file mode 100644 index 0000000..b3d7d51 --- /dev/null +++ b/drive-sdk/deps/bzle/include/bzle/bluetooth/sdp_lib.h @@ -0,0 +1,634 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2001-2002 Nokia Corporation + * Copyright (C) 2002-2003 Maxim Krasnyansky + * Copyright (C) 2002-2010 Marcel Holtmann + * Copyright (C) 2002-2003 Stephen Crane + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifndef __SDP_LIB_H +#define __SDP_LIB_H + +#include +#include "bluetooth.h" +#include "hci.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * SDP lists + */ +typedef void(*sdp_list_func_t)(void *, void *); +typedef void(*sdp_free_func_t)(void *); +typedef int (*sdp_comp_func_t)(const void *, const void *); + +sdp_list_t *sdp_list_append(sdp_list_t *list, void *d); +sdp_list_t *sdp_list_remove(sdp_list_t *list, void *d); +sdp_list_t *sdp_list_insert_sorted(sdp_list_t *list, void *data, sdp_comp_func_t f); +void sdp_list_free(sdp_list_t *list, sdp_free_func_t f); + +static inline int sdp_list_len(const sdp_list_t *list) +{ + int n = 0; + for (; list; list = list->next) + n++; + return n; +} + +static inline sdp_list_t *sdp_list_find(sdp_list_t *list, void *u, sdp_comp_func_t f) +{ + for (; list; list = list->next) + if (f(list->data, u) == 0) + return list; + return NULL; +} + +static inline void sdp_list_foreach(sdp_list_t *list, sdp_list_func_t f, void *u) +{ + for (; list; list = list->next) + f(list->data, u); +} + +/* + * Values of the flags parameter to sdp_record_register + */ +#define SDP_RECORD_PERSIST 0x01 +#define SDP_DEVICE_RECORD 0x02 + +/* + * Values of the flags parameter to sdp_connect + */ +#define SDP_RETRY_IF_BUSY 0x01 +#define SDP_WAIT_ON_CLOSE 0x02 +#define SDP_NON_BLOCKING 0x04 +#define SDP_LARGE_MTU 0x08 + +/* + * a session with an SDP server + */ +typedef struct { + int sock; + int state; + int local; + int flags; + uint16_t tid; /* Current transaction ID */ + void *priv; +} sdp_session_t; + +typedef enum { + /* + * Attributes are specified as individual elements + */ + SDP_ATTR_REQ_INDIVIDUAL = 1, + /* + * Attributes are specified as a range + */ + SDP_ATTR_REQ_RANGE +} sdp_attrreq_type_t; + +/* + * When the pdu_id(type) is a sdp error response, check the status value + * to figure out the error reason. For status values 0x0001-0x0006 check + * Bluetooth SPEC. If the status is 0xffff, call sdp_get_error function + * to get the real reason: + * - wrong transaction ID(EPROTO) + * - wrong PDU id or(EPROTO) + * - I/O error + */ +typedef void sdp_callback_t(uint8_t type, uint16_t status, uint8_t *rsp, size_t size, void *udata); + +/* + * create an L2CAP connection to a Bluetooth device + * + * INPUT: + * + * bdaddr_t *src: + * Address of the local device to use to make the connection + * (or BDADDR_ANY) + * + * bdaddr_t *dst: + * Address of the SDP server device + */ +sdp_session_t *sdp_connect(const bdaddr_t *src, const bdaddr_t *dst, uint32_t flags); +int sdp_close(sdp_session_t *session); +int sdp_get_socket(const sdp_session_t *session); + +/* + * SDP transaction: functions for asynchronous search. + */ +sdp_session_t *sdp_create(int sk, uint32_t flags); +int sdp_get_error(sdp_session_t *session); +int sdp_process(sdp_session_t *session); +int sdp_set_notify(sdp_session_t *session, sdp_callback_t *func, void *udata); + +int sdp_service_search_async(sdp_session_t *session, const sdp_list_t *search, uint16_t max_rec_num); +int sdp_service_attr_async(sdp_session_t *session, uint32_t handle, sdp_attrreq_type_t reqtype, const sdp_list_t *attrid_list); +int sdp_service_search_attr_async(sdp_session_t *session, const sdp_list_t *search, sdp_attrreq_type_t reqtype, const sdp_list_t *attrid_list); + +uint16_t sdp_gen_tid(sdp_session_t *session); + +/* + * find all devices in the piconet + */ +int sdp_general_inquiry(inquiry_info *ii, int dev_num, int duration, uint8_t *found); + +/* flexible extraction of basic attributes - Jean II */ +int sdp_get_int_attr(const sdp_record_t *rec, uint16_t attr, int *value); +int sdp_get_string_attr(const sdp_record_t *rec, uint16_t attr, char *value, int valuelen); + +/* + * Basic sdp data functions + */ +sdp_data_t *sdp_data_alloc(uint8_t dtd, const void *value); +sdp_data_t *sdp_data_alloc_with_length(uint8_t dtd, const void *value, uint32_t length); +void sdp_data_free(sdp_data_t *data); +sdp_data_t *sdp_data_get(const sdp_record_t *rec, uint16_t attr_id); + +sdp_data_t *sdp_seq_alloc(void **dtds, void **values, int len); +sdp_data_t *sdp_seq_alloc_with_length(void **dtds, void **values, int *length, int len); +sdp_data_t *sdp_seq_append(sdp_data_t *seq, sdp_data_t *data); + +int sdp_attr_add(sdp_record_t *rec, uint16_t attr, sdp_data_t *data); +void sdp_attr_remove(sdp_record_t *rec, uint16_t attr); +void sdp_attr_replace(sdp_record_t *rec, uint16_t attr, sdp_data_t *data); +int sdp_set_uuidseq_attr(sdp_record_t *rec, uint16_t attr, sdp_list_t *seq); +int sdp_get_uuidseq_attr(const sdp_record_t *rec, uint16_t attr, sdp_list_t **seqp); + +/* + * NOTE that none of the functions below will update the SDP server, + * unless the {register, update}sdp_record_t() function is invoked. + * All functions which return an integer value, return 0 on success + * or -1 on failure. + */ + +/* + * Create an attribute and add it to the service record's attribute list. + * This consists of the data type descriptor of the attribute, + * the value of the attribute and the attribute identifier. + */ +int sdp_attr_add_new(sdp_record_t *rec, uint16_t attr, uint8_t dtd, const void *p); + +/* + * Set the information attributes of the service record. + * The set of attributes comprises service name, description + * and provider name + */ +void sdp_set_info_attr(sdp_record_t *rec, const char *name, const char *prov, const char *desc); + +/* + * Set the ServiceClassID attribute to the sequence specified by seq. + * Note that the identifiers need to be in sorted order from the most + * specific to the most generic service class that this service + * conforms to. + */ +static inline int sdp_set_service_classes(sdp_record_t *rec, sdp_list_t *seq) +{ + return sdp_set_uuidseq_attr(rec, SDP_ATTR_SVCLASS_ID_LIST, seq); +} + +/* + * Get the service classes to which the service conforms. + * + * When set, the list contains elements of ServiceClassIdentifer(uint16_t) + * ordered from most specific to most generic + */ +static inline int sdp_get_service_classes(const sdp_record_t *rec, sdp_list_t **seqp) +{ + return sdp_get_uuidseq_attr(rec, SDP_ATTR_SVCLASS_ID_LIST, seqp); +} + +/* + * Set the BrowseGroupList attribute to the list specified by seq. + * + * A service can belong to one or more service groups + * and the list comprises such group identifiers (UUIDs) + */ +static inline int sdp_set_browse_groups(sdp_record_t *rec, sdp_list_t *seq) +{ + return sdp_set_uuidseq_attr(rec, SDP_ATTR_BROWSE_GRP_LIST, seq); +} + +/* + * Set the access protocols of the record to those specified in proto + */ +int sdp_set_access_protos(sdp_record_t *rec, const sdp_list_t *proto); + +/* + * Set the additional access protocols of the record to those specified in proto + */ +int sdp_set_add_access_protos(sdp_record_t *rec, const sdp_list_t *proto); + +/* + * Get protocol port (i.e. PSM for L2CAP, Channel for RFCOMM) + */ +int sdp_get_proto_port(const sdp_list_t *list, int proto); + +/* + * Get protocol descriptor. + */ +sdp_data_t *sdp_get_proto_desc(sdp_list_t *list, int proto); + +/* + * Set the LanguageBase attributes to the values specified in list + * (a linked list of sdp_lang_attr_t objects, one for each language in + * which user-visible attributes are present). + */ +int sdp_set_lang_attr(sdp_record_t *rec, const sdp_list_t *list); + +/* + * Set the ServiceInfoTimeToLive attribute of the service. + * This is the number of seconds that this record is guaranteed + * not to change after being obtained by a client. + */ +static inline int sdp_set_service_ttl(sdp_record_t *rec, uint32_t ttl) +{ + return sdp_attr_add_new(rec, SDP_ATTR_SVCINFO_TTL, SDP_UINT32, &ttl); +} + +/* + * Set the ServiceRecordState attribute of a service. This is + * guaranteed to change if there is any kind of modification to + * the record. + */ +static inline int sdp_set_record_state(sdp_record_t *rec, uint32_t state) +{ + return sdp_attr_add_new(rec, SDP_ATTR_RECORD_STATE, SDP_UINT32, &state); +} + +/* + * Set the ServiceID attribute of a service. + */ +void sdp_set_service_id(sdp_record_t *rec, uuid_t uuid); + +/* + * Set the GroupID attribute of a service + */ +void sdp_set_group_id(sdp_record_t *rec, uuid_t grouuuid); + +/* + * Set the ServiceAvailability attribute of a service. + * + * Note that this represents the relative availability + * of the service: 0x00 means completely unavailable; + * 0xFF means maximum availability. + */ +static inline int sdp_set_service_avail(sdp_record_t *rec, uint8_t avail) +{ + return sdp_attr_add_new(rec, SDP_ATTR_SERVICE_AVAILABILITY, SDP_UINT8, &avail); +} + +/* + * Set the profile descriptor list attribute of a record. + * + * Each element in the list is an object of type + * sdp_profile_desc_t which is a definition of the + * Bluetooth profile that this service conforms to. + */ +int sdp_set_profile_descs(sdp_record_t *rec, const sdp_list_t *desc); + +/* + * Set URL attributes of a record. + * + * ClientExecutableURL: a URL to a client's platform specific (WinCE, + * PalmOS) executable code that can be used to access this service. + * + * DocumentationURL: a URL pointing to service documentation + * + * IconURL: a URL to an icon that can be used to represent this service. + * + * Note: pass NULL for any URLs that you don't want to set or remove + */ +void sdp_set_url_attr(sdp_record_t *rec, const char *clientExecURL, const char *docURL, const char *iconURL); + +/* + * a service search request. + * + * INPUT : + * + * sdp_list_t *search + * list containing elements of the search + * pattern. Each entry in the list is a UUID + * of the service to be searched + * + * uint16_t max_rec_num + * An integer specifying the maximum number of + * entries that the client can handle in the response. + * + * OUTPUT : + * + * int return value + * 0 + * The request completed successfully. This does not + * mean the requested services were found + * -1 + * The request completed unsuccessfully + * + * sdp_list_t *rsp_list + * This variable is set on a successful return if there are + * non-zero service handles. It is a singly linked list of + * service record handles (uint16_t) + */ +int sdp_service_search_req(sdp_session_t *session, const sdp_list_t *search, uint16_t max_rec_num, sdp_list_t **rsp_list); + +/* + * a service attribute request. + * + * INPUT : + * + * uint32_t handle + * The handle of the service for which the attribute(s) are + * requested + * + * sdp_attrreq_type_t reqtype + * Attribute identifiers are 16 bit unsigned integers specified + * in one of 2 ways described below : + * SDP_ATTR_REQ_INDIVIDUAL - 16bit individual identifiers + * They are the actual attribute identifiers in ascending order + * + * SDP_ATTR_REQ_RANGE - 32bit identifier range + * The high-order 16bits is the start of range + * the low-order 16bits are the end of range + * 0x0000 to 0xFFFF gets all attributes + * + * sdp_list_t *attrid_list + * Singly linked list containing attribute identifiers desired. + * Every element is either a uint16_t(attrSpec = SDP_ATTR_REQ_INDIVIDUAL) + * or a uint32_t(attrSpec=SDP_ATTR_REQ_RANGE) + * + * OUTPUT : + * int return value + * 0 + * The request completed successfully. This does not + * mean the requested services were found + * -1 + * The request completed unsuccessfully due to a timeout + */ +sdp_record_t *sdp_service_attr_req(sdp_session_t *session, uint32_t handle, sdp_attrreq_type_t reqtype, const sdp_list_t *attrid_list); + +/* + * This is a service search request combined with the service + * attribute request. First a service class match is done and + * for matching service, requested attributes are extracted + * + * INPUT : + * + * sdp_list_t *search + * Singly linked list containing elements of the search + * pattern. Each entry in the list is a UUID(DataTypeSDP_UUID16) + * of the service to be searched + * + * AttributeSpecification attrSpec + * Attribute identifiers are 16 bit unsigned integers specified + * in one of 2 ways described below : + * SDP_ATTR_REQ_INDIVIDUAL - 16bit individual identifiers + * They are the actual attribute identifiers in ascending order + * + * SDP_ATTR_REQ_RANGE - 32bit identifier range + * The high-order 16bits is the start of range + * the low-order 16bits are the end of range + * 0x0000 to 0xFFFF gets all attributes + * + * sdp_list_t *attrid_list + * Singly linked list containing attribute identifiers desired. + * Every element is either a uint16_t(attrSpec = SDP_ATTR_REQ_INDIVIDUAL) + * or a uint32_t(attrSpec=SDP_ATTR_REQ_RANGE) + * + * OUTPUT : + * int return value + * 0 + * The request completed successfully. This does not + * mean the requested services were found + * -1 + * The request completed unsuccessfully due to a timeout + * + * sdp_list_t *rsp_list + * This variable is set on a successful return to point to + * service(s) found. Each element of this list is of type + * sdp_record_t *. + */ +int sdp_service_search_attr_req(sdp_session_t *session, const sdp_list_t *search, sdp_attrreq_type_t reqtype, const sdp_list_t *attrid_list, sdp_list_t **rsp_list); + +/* + * Allocate/free a service record and its attributes + */ +sdp_record_t *sdp_record_alloc(void); +void sdp_record_free(sdp_record_t *rec); + +/* + * Register a service record. + * + * Note: It is the responsbility of the Service Provider to create the + * record first and set its attributes using setXXX() methods. + * + * The service provider must then call sdp_record_register() to make + * the service record visible to SDP clients. This function returns 0 + * on success or -1 on failure (and sets errno). + */ +int sdp_device_record_register_binary(sdp_session_t *session, bdaddr_t *device, uint8_t *data, uint32_t size, uint8_t flags, uint32_t *handle); +int sdp_device_record_register(sdp_session_t *session, bdaddr_t *device, sdp_record_t *rec, uint8_t flags); +int sdp_record_register(sdp_session_t *session, sdp_record_t *rec, uint8_t flags); + +/* + * Unregister a service record. + */ +int sdp_device_record_unregister_binary(sdp_session_t *session, bdaddr_t *device, uint32_t handle); +int sdp_device_record_unregister(sdp_session_t *session, bdaddr_t *device, sdp_record_t *rec); +int sdp_record_unregister(sdp_session_t *session, sdp_record_t *rec); + +/* + * Update an existing service record. (Calling this function + * before a previous call to sdp_record_register() will result + * in an error.) + */ +int sdp_device_record_update_binary(sdp_session_t *session, bdaddr_t *device, uint32_t handle, uint8_t *data, uint32_t size); +int sdp_device_record_update(sdp_session_t *session, bdaddr_t *device, const sdp_record_t *rec); +int sdp_record_update(sdp_session_t *sess, const sdp_record_t *rec); + +void sdp_record_print(const sdp_record_t *rec); + +/* + * UUID functions + */ +uuid_t *sdp_uuid16_create(uuid_t *uuid, uint16_t data); +uuid_t *sdp_uuid32_create(uuid_t *uuid, uint32_t data); +uuid_t *sdp_uuid128_create(uuid_t *uuid, const void *data); +int sdp_uuid16_cmp(const void *p1, const void *p2); +int sdp_uuid128_cmp(const void *p1, const void *p2); +int sdp_uuid_cmp(const void *p1, const void *p2); +uuid_t *sdp_uuid_to_uuid128(const uuid_t *uuid); +void sdp_uuid16_to_uuid128(uuid_t *uuid128, const uuid_t *uuid16); +void sdp_uuid32_to_uuid128(uuid_t *uuid128, const uuid_t *uuid32); +int sdp_uuid128_to_uuid(uuid_t *uuid); +int sdp_uuid_to_proto(uuid_t *uuid); +int sdp_uuid_extract(const uint8_t *buffer, int bufsize, uuid_t *uuid, int *scanned); +void sdp_uuid_print(const uuid_t *uuid); + +#define MAX_LEN_UUID_STR 37 +#define MAX_LEN_PROTOCOL_UUID_STR 8 +#define MAX_LEN_SERVICECLASS_UUID_STR 28 +#define MAX_LEN_PROFILEDESCRIPTOR_UUID_STR 28 + +int sdp_uuid2strn(const uuid_t *uuid, char *str, size_t n); +int sdp_proto_uuid2strn(const uuid_t *uuid, char *str, size_t n); +int sdp_svclass_uuid2strn(const uuid_t *uuid, char *str, size_t n); +int sdp_profile_uuid2strn(const uuid_t *uuid, char *str, size_t n); + +/* + * In all the sdp_get_XXX(handle, XXX *xxx) functions below, + * the XXX * is set to point to the value, should it exist + * and 0 is returned. If the value does not exist, -1 is + * returned and errno set to ENODATA. + * + * In all the methods below, the memory management rules are + * simple. Don't free anything! The pointer returned, in the + * case of constructed types, is a pointer to the contents + * of the sdp_record_t. + */ + +/* + * Get the access protocols from the service record + */ +int sdp_get_access_protos(const sdp_record_t *rec, sdp_list_t **protos); + +/* + * Get the additional access protocols from the service record + */ +int sdp_get_add_access_protos(const sdp_record_t *rec, sdp_list_t **protos); + +/* + * Extract the list of browse groups to which the service belongs. + * When set, seqp contains elements of GroupID (uint16_t) + */ +static inline int sdp_get_browse_groups(const sdp_record_t *rec, sdp_list_t **seqp) +{ + return sdp_get_uuidseq_attr(rec, SDP_ATTR_BROWSE_GRP_LIST, seqp); +} + +/* + * Extract language attribute meta-data of the service record. + * For each language in the service record, LangSeq has a struct of type + * sdp_lang_attr_t. + */ +int sdp_get_lang_attr(const sdp_record_t *rec, sdp_list_t **langSeq); + +/* + * Extract the Bluetooth profile descriptor sequence from a record. + * Each element in the list is of type sdp_profile_desc_t + * which contains the UUID of the profile and its version number + * (encoded as major and minor in the high-order 8bits + * and low-order 8bits respectively of the uint16_t) + */ +int sdp_get_profile_descs(const sdp_record_t *rec, sdp_list_t **profDesc); + +/* + * Extract SDP server version numbers + * + * Note: that this is an attribute of the SDP server only and + * contains a list of uint16_t each of which represent the + * major and minor SDP version numbers supported by this server + */ +int sdp_get_server_ver(const sdp_record_t *rec, sdp_list_t **pVnumList); + +int sdp_get_service_id(const sdp_record_t *rec, uuid_t *uuid); +int sdp_get_group_id(const sdp_record_t *rec, uuid_t *uuid); +int sdp_get_record_state(const sdp_record_t *rec, uint32_t *svcRecState); +int sdp_get_service_avail(const sdp_record_t *rec, uint8_t *svcAvail); +int sdp_get_service_ttl(const sdp_record_t *rec, uint32_t *svcTTLInfo); +int sdp_get_database_state(const sdp_record_t *rec, uint32_t *svcDBState); + +static inline int sdp_get_service_name(const sdp_record_t *rec, char *str, int len) +{ + return sdp_get_string_attr(rec, SDP_ATTR_SVCNAME_PRIMARY, str, len); +} + +static inline int sdp_get_service_desc(const sdp_record_t *rec, char *str, int len) +{ + return sdp_get_string_attr(rec, SDP_ATTR_SVCDESC_PRIMARY, str, len); +} + +static inline int sdp_get_provider_name(const sdp_record_t *rec, char *str, int len) +{ + return sdp_get_string_attr(rec, SDP_ATTR_PROVNAME_PRIMARY, str, len); +} + +static inline int sdp_get_doc_url(const sdp_record_t *rec, char *str, int len) +{ + return sdp_get_string_attr(rec, SDP_ATTR_DOC_URL, str, len); +} + +static inline int sdp_get_clnt_exec_url(const sdp_record_t *rec, char *str, int len) +{ + return sdp_get_string_attr(rec, SDP_ATTR_CLNT_EXEC_URL, str, len); +} + +static inline int sdp_get_icon_url(const sdp_record_t *rec, char *str, int len) +{ + return sdp_get_string_attr(rec, SDP_ATTR_ICON_URL, str, len); +} + +/* + * Set the supported features + * sf should be a list of list with each feature data + * Returns 0 on success -1 on fail + */ +int sdp_set_supp_feat(sdp_record_t *rec, const sdp_list_t *sf); + +/* + * Get the supported features + * seqp is set to a list of list with each feature data + * Returns 0 on success, if an error occurred -1 is returned and errno is set + */ +int sdp_get_supp_feat(const sdp_record_t *rec, sdp_list_t **seqp); + +sdp_record_t *sdp_extract_pdu(const uint8_t *pdata, int bufsize, int *scanned); +sdp_record_t *sdp_copy_record(sdp_record_t *rec); + +void sdp_data_print(sdp_data_t *data); +void sdp_print_service_attr(sdp_list_t *alist); + +int sdp_attrid_comp_func(const void *key1, const void *key2); + +void sdp_set_seq_len(uint8_t *ptr, uint32_t length); +void sdp_set_attrid(sdp_buf_t *pdu, uint16_t id); +void sdp_append_to_pdu(sdp_buf_t *dst, sdp_data_t *d); +void sdp_append_to_buf(sdp_buf_t *dst, uint8_t *data, uint32_t len); + +int sdp_gen_pdu(sdp_buf_t *pdu, sdp_data_t *data); +int sdp_gen_record_pdu(const sdp_record_t *rec, sdp_buf_t *pdu); + +int sdp_extract_seqtype(const uint8_t *buf, int bufsize, uint8_t *dtdp, int *size); + +sdp_data_t *sdp_extract_attr(const uint8_t *pdata, int bufsize, int *extractedLength, sdp_record_t *rec); + +void sdp_pattern_add_uuid(sdp_record_t *rec, uuid_t *uuid); +void sdp_pattern_add_uuidseq(sdp_record_t *rec, sdp_list_t *seq); + +int sdp_send_req_w4_rsp(sdp_session_t *session, uint8_t *req, uint8_t *rsp, uint32_t reqsize, uint32_t *rspsize); + +void sdp_add_lang_attr(sdp_record_t *rec); + +#ifdef __cplusplus +} +#endif + +#endif /* __SDP_LIB_H */ diff --git a/drive-sdk/deps/bzle/include/bzle/bluetooth/uuid.h b/drive-sdk/deps/bzle/include/bzle/bluetooth/uuid.h new file mode 100644 index 0000000..28d8caa --- /dev/null +++ b/drive-sdk/deps/bzle/include/bzle/bluetooth/uuid.h @@ -0,0 +1,140 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2011 Nokia Corporation + * Copyright (C) 2011 Marcel Holtmann + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifndef __BLUETOOTH_UUID_H +#define __BLUETOOTH_UUID_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include "bluetooth.h" + +#define GENERIC_AUDIO_UUID "00001203-0000-1000-8000-00805f9b34fb" + +#define HSP_HS_UUID "00001108-0000-1000-8000-00805f9b34fb" +#define HSP_AG_UUID "00001112-0000-1000-8000-00805f9b34fb" + +#define HFP_HS_UUID "0000111e-0000-1000-8000-00805f9b34fb" +#define HFP_AG_UUID "0000111f-0000-1000-8000-00805f9b34fb" + +#define ADVANCED_AUDIO_UUID "0000110d-0000-1000-8000-00805f9b34fb" + +#define A2DP_SOURCE_UUID "0000110a-0000-1000-8000-00805f9b34fb" +#define A2DP_SINK_UUID "0000110b-0000-1000-8000-00805f9b34fb" + +#define AVRCP_REMOTE_UUID "0000110e-0000-1000-8000-00805f9b34fb" +#define AVRCP_TARGET_UUID "0000110c-0000-1000-8000-00805f9b34fb" + +#define PANU_UUID "00001115-0000-1000-8000-00805f9b34fb" +#define NAP_UUID "00001116-0000-1000-8000-00805f9b34fb" +#define GN_UUID "00001117-0000-1000-8000-00805f9b34fb" +#define BNEP_SVC_UUID "0000000f-0000-1000-8000-00805f9b34fb" + +#define PNPID_UUID "00002a50-0000-1000-8000-00805f9b34fb" +#define DEVICE_INFORMATION_UUID "0000180a-0000-1000-8000-00805f9b34fb" + +#define GATT_UUID "00001801-0000-1000-8000-00805f9b34fb" +#define IMMEDIATE_ALERT_UUID "00001802-0000-1000-8000-00805f9b34fb" +#define LINK_LOSS_UUID "00001803-0000-1000-8000-00805f9b34fb" +#define TX_POWER_UUID "00001804-0000-1000-8000-00805f9b34fb" + +#define SAP_UUID "0000112D-0000-1000-8000-00805f9b34fb" + +#define HEART_RATE_UUID "0000180d-0000-1000-8000-00805f9b34fb" +#define HEART_RATE_MEASUREMENT_UUID "00002a37-0000-1000-8000-00805f9b34fb" +#define BODY_SENSOR_LOCATION_UUID "00002a38-0000-1000-8000-00805f9b34fb" +#define HEART_RATE_CONTROL_POINT_UUID "00002a39-0000-1000-8000-00805f9b34fb" + +#define HEALTH_THERMOMETER_UUID "00001809-0000-1000-8000-00805f9b34fb" +#define TEMPERATURE_MEASUREMENT_UUID "00002a1c-0000-1000-8000-00805f9b34fb" +#define TEMPERATURE_TYPE_UUID "00002a1d-0000-1000-8000-00805f9b34fb" +#define INTERMEDIATE_TEMPERATURE_UUID "00002a1e-0000-1000-8000-00805f9b34fb" +#define MEASUREMENT_INTERVAL_UUID "00002a21-0000-1000-8000-00805f9b34fb" + +#define CYCLING_SC_UUID "00001816-0000-1000-8000-00805f9b34fb" +#define CSC_MEASUREMENT_UUID "00002a5b-0000-1000-8000-00805f9b34fb" +#define CSC_FEATURE_UUID "00002a5c-0000-1000-8000-00805f9b34fb" +#define SENSOR_LOCATION_UUID "00002a5d-0000-1000-8000-00805f9b34fb" +#define SC_CONTROL_POINT_UUID "00002a55-0000-1000-8000-00805f9b34fb" + +#define RFCOMM_UUID_STR "00000003-0000-1000-8000-00805f9b34fb" + +#define HDP_UUID "00001400-0000-1000-8000-00805f9b34fb" +#define HDP_SOURCE_UUID "00001401-0000-1000-8000-00805f9b34fb" +#define HDP_SINK_UUID "00001402-0000-1000-8000-00805f9b34fb" + +#define HID_UUID "00001124-0000-1000-8000-00805f9b34fb" + +#define DUN_GW_UUID "00001103-0000-1000-8000-00805f9b34fb" + +#define GAP_UUID "00001800-0000-1000-8000-00805f9b34fb" +#define PNP_UUID "00001200-0000-1000-8000-00805f9b34fb" + +#define SPP_UUID "00001101-0000-1000-8000-00805f9b34fb" + +#define OBEX_SYNC_UUID "00001104-0000-1000-8000-00805f9b34fb" +#define OBEX_OPP_UUID "00001105-0000-1000-8000-00805f9b34fb" +#define OBEX_FTP_UUID "00001106-0000-1000-8000-00805f9b34fb" +#define OBEX_PCE_UUID "0000112e-0000-1000-8000-00805f9b34fb" +#define OBEX_PSE_UUID "0000112f-0000-1000-8000-00805f9b34fb" +#define OBEX_PBAP_UUID "00001130-0000-1000-8000-00805f9b34fb" +#define OBEX_MAS_UUID "00001132-0000-1000-8000-00805f9b34fb" +#define OBEX_MNS_UUID "00001133-0000-1000-8000-00805f9b34fb" +#define OBEX_MAP_UUID "00001134-0000-1000-8000-00805f9b34fb" + +typedef struct { + enum { + BT_UUID_UNSPEC = 0, + BT_UUID16 = 16, + BT_UUID32 = 32, + BT_UUID128 = 128, + } type; + union { + uint16_t u16; + uint32_t u32; + uint128_t u128; + } value; +} bt_uuid_t; + +int bt_uuid_strcmp(const void *a, const void *b); + +int bt_uuid16_create(bt_uuid_t *btuuid, uint16_t value); +int bt_uuid32_create(bt_uuid_t *btuuid, uint32_t value); +int bt_uuid128_create(bt_uuid_t *btuuid, uint128_t value); + +int bt_uuid_cmp(const bt_uuid_t *uuid1, const bt_uuid_t *uuid2); +void bt_uuid_to_uuid128(const bt_uuid_t *src, bt_uuid_t *dst); + +#define MAX_LEN_UUID_STR 37 + +int bt_uuid_to_string(const bt_uuid_t *uuid, char *str, size_t n); +int bt_string_to_uuid(bt_uuid_t *uuid, const char *string); + +#ifdef __cplusplus +} +#endif + +#endif /* __BLUETOOTH_UUID_H */ diff --git a/drive-sdk/deps/bzle/include/bzle/gatt/att.h b/drive-sdk/deps/bzle/include/bzle/gatt/att.h new file mode 100644 index 0000000..28bc944 --- /dev/null +++ b/drive-sdk/deps/bzle/include/bzle/gatt/att.h @@ -0,0 +1,286 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2010 Nokia Corporation + * Copyright (C) 2010 Marcel Holtmann + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +/* Attribute Protocol Opcodes */ +#define ATT_OP_ERROR 0x01 +#define ATT_OP_MTU_REQ 0x02 +#define ATT_OP_MTU_RESP 0x03 +#define ATT_OP_FIND_INFO_REQ 0x04 +#define ATT_OP_FIND_INFO_RESP 0x05 +#define ATT_OP_FIND_BY_TYPE_REQ 0x06 +#define ATT_OP_FIND_BY_TYPE_RESP 0x07 +#define ATT_OP_READ_BY_TYPE_REQ 0x08 +#define ATT_OP_READ_BY_TYPE_RESP 0x09 +#define ATT_OP_READ_REQ 0x0A +#define ATT_OP_READ_RESP 0x0B +#define ATT_OP_READ_BLOB_REQ 0x0C +#define ATT_OP_READ_BLOB_RESP 0x0D +#define ATT_OP_READ_MULTI_REQ 0x0E +#define ATT_OP_READ_MULTI_RESP 0x0F +#define ATT_OP_READ_BY_GROUP_REQ 0x10 +#define ATT_OP_READ_BY_GROUP_RESP 0x11 +#define ATT_OP_WRITE_REQ 0x12 +#define ATT_OP_WRITE_RESP 0x13 +#define ATT_OP_WRITE_CMD 0x52 +#define ATT_OP_PREP_WRITE_REQ 0x16 +#define ATT_OP_PREP_WRITE_RESP 0x17 +#define ATT_OP_EXEC_WRITE_REQ 0x18 +#define ATT_OP_EXEC_WRITE_RESP 0x19 +#define ATT_OP_HANDLE_NOTIFY 0x1B +#define ATT_OP_HANDLE_IND 0x1D +#define ATT_OP_HANDLE_CNF 0x1E +#define ATT_OP_SIGNED_WRITE_CMD 0xD2 + +/* Error codes for Error response PDU */ +#define ATT_ECODE_INVALID_HANDLE 0x01 +#define ATT_ECODE_READ_NOT_PERM 0x02 +#define ATT_ECODE_WRITE_NOT_PERM 0x03 +#define ATT_ECODE_INVALID_PDU 0x04 +#define ATT_ECODE_AUTHENTICATION 0x05 +#define ATT_ECODE_REQ_NOT_SUPP 0x06 +#define ATT_ECODE_INVALID_OFFSET 0x07 +#define ATT_ECODE_AUTHORIZATION 0x08 +#define ATT_ECODE_PREP_QUEUE_FULL 0x09 +#define ATT_ECODE_ATTR_NOT_FOUND 0x0A +#define ATT_ECODE_ATTR_NOT_LONG 0x0B +#define ATT_ECODE_INSUFF_ENCR_KEY_SIZE 0x0C +#define ATT_ECODE_INVAL_ATTR_VALUE_LEN 0x0D +#define ATT_ECODE_UNLIKELY 0x0E +#define ATT_ECODE_INSUFF_ENC 0x0F +#define ATT_ECODE_UNSUPP_GRP_TYPE 0x10 +#define ATT_ECODE_INSUFF_RESOURCES 0x11 +/* Application error */ +#define ATT_ECODE_IO 0x80 +#define ATT_ECODE_TIMEOUT 0x81 +#define ATT_ECODE_ABORTED 0x82 + +/* Characteristic Property bit field */ +#define ATT_CHAR_PROPER_BROADCAST 0x01 +#define ATT_CHAR_PROPER_READ 0x02 +#define ATT_CHAR_PROPER_WRITE_WITHOUT_RESP 0x04 +#define ATT_CHAR_PROPER_WRITE 0x08 +#define ATT_CHAR_PROPER_NOTIFY 0x10 +#define ATT_CHAR_PROPER_INDICATE 0x20 +#define ATT_CHAR_PROPER_AUTH 0x40 +#define ATT_CHAR_PROPER_EXT_PROPER 0x80 + +#define ATT_MAX_VALUE_LEN 512 +#define ATT_DEFAULT_L2CAP_MTU 48 +#define ATT_DEFAULT_LE_MTU 23 + +#define ATT_CID 4 +#define ATT_PSM 31 + +/* Flags for Execute Write Request Operation */ +#define ATT_CANCEL_ALL_PREP_WRITES 0x00 +#define ATT_WRITE_ALL_PREP_WRITES 0x01 + +/* Find Information Response Formats */ +#define ATT_FIND_INFO_RESP_FMT_16BIT 0x01 +#define ATT_FIND_INFO_RESP_FMT_128BIT 0x02 + +struct att_data_list { + uint16_t num; + uint16_t len; + uint8_t **data; +}; + +struct att_range { + uint16_t start; + uint16_t end; +}; + +/* These functions do byte conversion */ +static inline uint8_t att_get_u8(const void *ptr) +{ + const uint8_t *u8_ptr = ptr; + return bt_get_unaligned(u8_ptr); +} + +static inline uint16_t att_get_u16(const void *ptr) +{ + const uint16_t *u16_ptr = ptr; + return btohs(bt_get_unaligned(u16_ptr)); +} + +static inline uint32_t att_get_u32(const void *ptr) +{ + const uint32_t *u32_ptr = ptr; + return btohl(bt_get_unaligned(u32_ptr)); +} + +static inline uint128_t att_get_u128(const void *ptr) +{ + const uint128_t *u128_ptr = ptr; + uint128_t dst; + + btoh128(u128_ptr, &dst); + + return dst; +} + +static inline void att_put_u8(uint8_t src, void *dst) +{ + bt_put_unaligned(src, (uint8_t *) dst); +} + +static inline void att_put_u16(uint16_t src, void *dst) +{ + bt_put_unaligned(htobs(src), (uint16_t *) dst); +} + +static inline void att_put_u32(uint32_t src, void *dst) +{ + bt_put_unaligned(htobl(src), (uint32_t *) dst); +} + +static inline void att_put_u128(uint128_t src, void *dst) +{ + uint128_t *d128 = dst; + + htob128(&src, d128); +} + +static inline void att_put_uuid16(bt_uuid_t src, void *dst) +{ + att_put_u16(src.value.u16, dst); +} + +static inline void att_put_uuid128(bt_uuid_t src, void *dst) +{ + att_put_u128(src.value.u128, dst); +} + +static inline void att_put_uuid(bt_uuid_t src, void *dst) +{ + if (src.type == BT_UUID16) + att_put_uuid16(src, dst); + else + att_put_uuid128(src, dst); +} + +static inline bt_uuid_t att_get_uuid16(const void *ptr) +{ + bt_uuid_t uuid; + + bt_uuid16_create(&uuid, att_get_u16(ptr)); + + return uuid; +} + +static inline bt_uuid_t att_get_uuid128(const void *ptr) +{ + bt_uuid_t uuid; + uint128_t value; + + value = att_get_u128(ptr); + bt_uuid128_create(&uuid, value); + + return uuid; +} + +struct att_data_list *att_data_list_alloc(uint16_t num, uint16_t len); +void att_data_list_free(struct att_data_list *list); + +const char *att_ecode2str(uint8_t status); +uint16_t enc_read_by_grp_req(uint16_t start, uint16_t end, bt_uuid_t *uuid, + uint8_t *pdu, size_t len); +uint16_t dec_read_by_grp_req(const uint8_t *pdu, size_t len, uint16_t *start, + uint16_t *end, bt_uuid_t *uuid); +uint16_t enc_read_by_grp_resp(struct att_data_list *list, uint8_t *pdu, + size_t len); +uint16_t enc_find_by_type_req(uint16_t start, uint16_t end, bt_uuid_t *uuid, + const uint8_t *value, size_t vlen, uint8_t *pdu, + size_t len); +uint16_t dec_find_by_type_req(const uint8_t *pdu, size_t len, uint16_t *start, + uint16_t *end, bt_uuid_t *uuid, uint8_t *value, size_t *vlen); +uint16_t enc_find_by_type_resp(GSList *ranges, uint8_t *pdu, size_t len); +GSList *dec_find_by_type_resp(const uint8_t *pdu, size_t len); +struct att_data_list *dec_read_by_grp_resp(const uint8_t *pdu, size_t len); +uint16_t enc_read_by_type_req(uint16_t start, uint16_t end, bt_uuid_t *uuid, + uint8_t *pdu, size_t len); +uint16_t dec_read_by_type_req(const uint8_t *pdu, size_t len, uint16_t *start, + uint16_t *end, bt_uuid_t *uuid); +uint16_t enc_read_by_type_resp(struct att_data_list *list, uint8_t *pdu, + size_t len); +uint16_t enc_write_cmd(uint16_t handle, const uint8_t *value, size_t vlen, + uint8_t *pdu, size_t len); +uint16_t dec_write_cmd(const uint8_t *pdu, size_t len, uint16_t *handle, + uint8_t *value, size_t *vlen); +struct att_data_list *dec_read_by_type_resp(const uint8_t *pdu, size_t len); +uint16_t enc_write_req(uint16_t handle, const uint8_t *value, size_t vlen, + uint8_t *pdu, size_t len); +uint16_t dec_write_req(const uint8_t *pdu, size_t len, uint16_t *handle, + uint8_t *value, size_t *vlen); +uint16_t enc_write_resp(uint8_t *pdu); +uint16_t dec_write_resp(const uint8_t *pdu, size_t len); +uint16_t enc_read_req(uint16_t handle, uint8_t *pdu, size_t len); +uint16_t enc_read_blob_req(uint16_t handle, uint16_t offset, uint8_t *pdu, + size_t len); +uint16_t dec_read_req(const uint8_t *pdu, size_t len, uint16_t *handle); +uint16_t dec_read_blob_req(const uint8_t *pdu, size_t len, uint16_t *handle, + uint16_t *offset); +uint16_t enc_read_resp(uint8_t *value, size_t vlen, uint8_t *pdu, size_t len); +uint16_t enc_read_blob_resp(uint8_t *value, size_t vlen, uint16_t offset, + uint8_t *pdu, size_t len); +ssize_t dec_read_resp(const uint8_t *pdu, size_t len, uint8_t *value, + size_t vlen); +uint16_t enc_error_resp(uint8_t opcode, uint16_t handle, uint8_t status, + uint8_t *pdu, size_t len); +uint16_t enc_find_info_req(uint16_t start, uint16_t end, uint8_t *pdu, + size_t len); +uint16_t dec_find_info_req(const uint8_t *pdu, size_t len, uint16_t *start, + uint16_t *end); +uint16_t enc_find_info_resp(uint8_t format, struct att_data_list *list, + uint8_t *pdu, size_t len); +struct att_data_list *dec_find_info_resp(const uint8_t *pdu, size_t len, + uint8_t *format); +uint16_t enc_notification(uint16_t handle, uint8_t *value, size_t vlen, + uint8_t *pdu, size_t len); +uint16_t enc_indication(uint16_t handle, uint8_t *value, size_t vlen, + uint8_t *pdu, size_t len); +uint16_t dec_indication(const uint8_t *pdu, size_t len, uint16_t *handle, + uint8_t *value, size_t vlen); +uint16_t enc_confirmation(uint8_t *pdu, size_t len); + +uint16_t enc_mtu_req(uint16_t mtu, uint8_t *pdu, size_t len); +uint16_t dec_mtu_req(const uint8_t *pdu, size_t len, uint16_t *mtu); +uint16_t enc_mtu_resp(uint16_t mtu, uint8_t *pdu, size_t len); +uint16_t dec_mtu_resp(const uint8_t *pdu, size_t len, uint16_t *mtu); + +uint16_t enc_prep_write_req(uint16_t handle, uint16_t offset, + const uint8_t *value, size_t vlen, + uint8_t *pdu, size_t len); +uint16_t dec_prep_write_req(const uint8_t *pdu, size_t len, uint16_t *handle, + uint16_t *offset, uint8_t *value, size_t *vlen); +uint16_t enc_prep_write_resp(uint16_t handle, uint16_t offset, + const uint8_t *value, size_t vlen, + uint8_t *pdu, size_t len); +uint16_t dec_prep_write_resp(const uint8_t *pdu, size_t len, uint16_t *handle, + uint16_t *offset, uint8_t *value, + size_t *vlen); +uint16_t enc_exec_write_req(uint8_t flags, uint8_t *pdu, size_t len); +uint16_t dec_exec_write_req(const uint8_t *pdu, size_t len, uint8_t *flags); +uint16_t enc_exec_write_resp(uint8_t *pdu); +uint16_t dec_exec_write_resp(const uint8_t *pdu, size_t len); diff --git a/drive-sdk/deps/bzle/include/bzle/gatt/gatt.h b/drive-sdk/deps/bzle/include/bzle/gatt/gatt.h new file mode 100644 index 0000000..56d8780 --- /dev/null +++ b/drive-sdk/deps/bzle/include/bzle/gatt/gatt.h @@ -0,0 +1,115 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2010 Nokia Corporation + * Copyright (C) 2010 Marcel Holtmann + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifndef __GATT_H +#define __GATT_H + +#include + +/* GATT Profile Attribute types */ +#define GATT_PRIM_SVC_UUID 0x2800 +#define GATT_SND_SVC_UUID 0x2801 +#define GATT_INCLUDE_UUID 0x2802 +#define GATT_CHARAC_UUID 0x2803 + +/* GATT Characteristic Types */ +#define GATT_CHARAC_DEVICE_NAME 0x2A00 +#define GATT_CHARAC_APPEARANCE 0x2A01 +#define GATT_CHARAC_PERIPHERAL_PRIV_FLAG 0x2A02 +#define GATT_CHARAC_RECONNECTION_ADDRESS 0x2A03 +#define GATT_CHARAC_PERIPHERAL_PREF_CONN 0x2A04 +#define GATT_CHARAC_SERVICE_CHANGED 0x2A05 + +/* GATT Characteristic Descriptors */ +#define GATT_CHARAC_EXT_PROPER_UUID 0x2900 +#define GATT_CHARAC_USER_DESC_UUID 0x2901 +#define GATT_CLIENT_CHARAC_CFG_UUID 0x2902 +#define GATT_SERVER_CHARAC_CFG_UUID 0x2903 +#define GATT_CHARAC_FMT_UUID 0x2904 +#define GATT_CHARAC_AGREG_FMT_UUID 0x2905 +#define GATT_CHARAC_VALID_RANGE_UUID 0x2906 +#define GATT_EXTERNAL_REPORT_REFERENCE 0x2907 +#define GATT_REPORT_REFERENCE 0x2908 + +/* Client Characteristic Configuration bit field */ +#define GATT_CLIENT_CHARAC_CFG_NOTIF_BIT 0x0001 +#define GATT_CLIENT_CHARAC_CFG_IND_BIT 0x0002 + +typedef void (*gatt_cb_t) (uint8_t status, GSList *l, void *user_data); + +struct gatt_primary { + char uuid[MAX_LEN_UUID_STR + 1]; + gboolean changed; + struct att_range range; +}; + +struct gatt_included { + char uuid[MAX_LEN_UUID_STR + 1]; + uint16_t handle; + struct att_range range; +}; + +struct gatt_char { + char uuid[MAX_LEN_UUID_STR + 1]; + uint16_t handle; + uint8_t properties; + uint16_t value_handle; +}; + +guint gatt_discover_primary(GAttrib *attrib, bt_uuid_t *uuid, gatt_cb_t func, + gpointer user_data); + +unsigned int gatt_find_included(GAttrib *attrib, uint16_t start, uint16_t end, + gatt_cb_t func, gpointer user_data); + +guint gatt_discover_char(GAttrib *attrib, uint16_t start, uint16_t end, + bt_uuid_t *uuid, gatt_cb_t func, + gpointer user_data); + +guint gatt_read_char(GAttrib *attrib, uint16_t handle, GAttribResultFunc func, + gpointer user_data); + +guint gatt_write_char(GAttrib *attrib, uint16_t handle, uint8_t *value, + size_t vlen, GAttribResultFunc func, + gpointer user_data); + +guint gatt_discover_char_desc(GAttrib *attrib, uint16_t start, uint16_t end, + GAttribResultFunc func, gpointer user_data); + +guint gatt_write_cmd(GAttrib *attrib, uint16_t handle, uint8_t *value, int vlen, + GDestroyNotify notify, gpointer user_data); + +guint gatt_read_char_by_uuid(GAttrib *attrib, uint16_t start, uint16_t end, + bt_uuid_t *uuid, GAttribResultFunc func, + gpointer user_data); + +guint gatt_exchange_mtu(GAttrib *attrib, uint16_t mtu, GAttribResultFunc func, + gpointer user_data); + +gboolean gatt_parse_record(const sdp_record_t *rec, + uuid_t *prim_uuid, uint16_t *psm, + uint16_t *start, uint16_t *end); + + +#endif diff --git a/drive-sdk/deps/bzle/include/bzle/gatt/gattrib.h b/drive-sdk/deps/bzle/include/bzle/gatt/gattrib.h new file mode 100644 index 0000000..3fe92c7 --- /dev/null +++ b/drive-sdk/deps/bzle/include/bzle/gatt/gattrib.h @@ -0,0 +1,79 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2010 Nokia Corporation + * Copyright (C) 2010 Marcel Holtmann + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ +#ifndef __GATTRIB_H +#define __GATTRIB_H + +#ifdef __cplusplus +extern "C" { +#endif + +#define GATTRIB_ALL_EVENTS 0xFF +#define GATTRIB_ALL_REQS 0xFE +#define GATTRIB_ALL_HANDLES 0x0000 + +struct _GAttrib; +typedef struct _GAttrib GAttrib; + +typedef void (*GAttribResultFunc) (guint8 status, const guint8 *pdu, + guint16 len, gpointer user_data); +typedef void (*GAttribDisconnectFunc)(gpointer user_data); +typedef void (*GAttribDebugFunc)(const char *str, gpointer user_data); +typedef void (*GAttribNotifyFunc)(const guint8 *pdu, guint16 len, + gpointer user_data); + +GAttrib *g_attrib_new(GIOChannel *io); +GAttrib *g_attrib_ref(GAttrib *attrib); +void g_attrib_unref(GAttrib *attrib); + +GIOChannel *g_attrib_get_channel(GAttrib *attrib); + +gboolean g_attrib_set_destroy_function(GAttrib *attrib, + GDestroyNotify destroy, gpointer user_data); + +guint g_attrib_send(GAttrib *attrib, guint id, const guint8 *pdu, guint16 len, + GAttribResultFunc func, gpointer user_data, + GDestroyNotify notify); + +gboolean g_attrib_cancel(GAttrib *attrib, guint id); +gboolean g_attrib_cancel_all(GAttrib *attrib); + +gboolean g_attrib_set_debug(GAttrib *attrib, + GAttribDebugFunc func, gpointer user_data); + +guint g_attrib_register(GAttrib *attrib, guint8 opcode, guint16 handle, + GAttribNotifyFunc func, gpointer user_data, + GDestroyNotify notify); + +gboolean g_attrib_is_encrypted(GAttrib *attrib); + +uint8_t *g_attrib_get_buffer(GAttrib *attrib, size_t *len); +gboolean g_attrib_set_mtu(GAttrib *attrib, int mtu); + +gboolean g_attrib_unregister(GAttrib *attrib, guint id); +gboolean g_attrib_unregister_all(GAttrib *attrib); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/drive-sdk/deps/bzle/include/bzle/gatt/utils.h b/drive-sdk/deps/bzle/include/bzle/gatt/utils.h new file mode 100644 index 0000000..301f0a9 --- /dev/null +++ b/drive-sdk/deps/bzle/include/bzle/gatt/utils.h @@ -0,0 +1,33 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2011 Nokia Corporation + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifndef __UTILS_H__ +#define __UTILS_H__ + +GIOChannel *gatt_connect(const char *src, const char *dst, + const char *dst_type, const char *sec_level, + int psm, int mtu, BtIOConnect connect_cb, + GError **gerr); +size_t gatt_attr_data_from_string(const char *str, uint8_t **data); + +#endif // __UTILS_H__ diff --git a/drive-sdk/deps/bzle/src/CMakeLists.txt b/drive-sdk/deps/bzle/src/CMakeLists.txt new file mode 100644 index 0000000..a6f101a --- /dev/null +++ b/drive-sdk/deps/bzle/src/CMakeLists.txt @@ -0,0 +1,23 @@ +# Include the directory itself as a path to include directories +set(CMAKE_INCLUDE_CURRENT_DIR ON) + +include(FindGLIB2) + +include_directories( + ${bzle_SOURCE_DIR}/include + ${GLIB2_INCLUDE_DIRS} +) + +set(bzle_SOURCES +att.c bluetooth.c btio.c gatt.c gattrib.c hci.c log.h log.c sdp.c utils.c uuid.c +) + +add_library(bzle ${bzle_SOURCES}) +target_link_libraries(bzle + ${GLIB2_LIBRARIES} + ) + +install(TARGETS bzle + LIBRARY DESTINATION lib + ARCHIVE DESTINATION lib +) diff --git a/drive-sdk/deps/bzle/src/att.c b/drive-sdk/deps/bzle/src/att.c new file mode 100644 index 0000000..802c9c8 --- /dev/null +++ b/drive-sdk/deps/bzle/src/att.c @@ -0,0 +1,1165 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2010 Nokia Corporation + * Copyright (C) 2010 Marcel Holtmann + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include +#include + +#include + +#include + +#include +#include + +const char *att_ecode2str(uint8_t status) +{ + switch (status) { + case ATT_ECODE_INVALID_HANDLE: + return "Invalid handle"; + case ATT_ECODE_READ_NOT_PERM: + return "Attribute can't be read"; + case ATT_ECODE_WRITE_NOT_PERM: + return "Attribute can't be written"; + case ATT_ECODE_INVALID_PDU: + return "Attribute PDU was invalid"; + case ATT_ECODE_AUTHENTICATION: + return "Attribute requires authentication before read/write"; + case ATT_ECODE_REQ_NOT_SUPP: + return "Server doesn't support the request received"; + case ATT_ECODE_INVALID_OFFSET: + return "Offset past the end of the attribute"; + case ATT_ECODE_AUTHORIZATION: + return "Attribute requires authorization before read/write"; + case ATT_ECODE_PREP_QUEUE_FULL: + return "Too many prepare writes have been queued"; + case ATT_ECODE_ATTR_NOT_FOUND: + return "No attribute found within the given range"; + case ATT_ECODE_ATTR_NOT_LONG: + return "Attribute can't be read/written using Read Blob Req"; + case ATT_ECODE_INSUFF_ENCR_KEY_SIZE: + return "Encryption Key Size is insufficient"; + case ATT_ECODE_INVAL_ATTR_VALUE_LEN: + return "Attribute value length is invalid"; + case ATT_ECODE_UNLIKELY: + return "Request attribute has encountered an unlikely error"; + case ATT_ECODE_INSUFF_ENC: + return "Encryption required before read/write"; + case ATT_ECODE_UNSUPP_GRP_TYPE: + return "Attribute type is not a supported grouping attribute"; + case ATT_ECODE_INSUFF_RESOURCES: + return "Insufficient Resources to complete the request"; + case ATT_ECODE_IO: + return "Internal application error: I/O"; + case ATT_ECODE_TIMEOUT: + return "A timeout occured"; + case ATT_ECODE_ABORTED: + return "The operation was aborted"; + default: + return "Unexpected error code"; + } +} + +void att_data_list_free(struct att_data_list *list) +{ + if (list == NULL) + return; + + if (list->data) { + int i; + for (i = 0; i < list->num; i++) + g_free(list->data[i]); + } + + g_free(list->data); + g_free(list); +} + +struct att_data_list *att_data_list_alloc(uint16_t num, uint16_t len) +{ + struct att_data_list *list; + int i; + + if (len > UINT8_MAX) + return NULL; + + list = g_new0(struct att_data_list, 1); + list->len = len; + list->num = num; + + list->data = g_malloc0(sizeof(uint8_t *) * num); + + for (i = 0; i < num; i++) + list->data[i] = g_malloc0(sizeof(uint8_t) * len); + + return list; +} + +uint16_t enc_read_by_grp_req(uint16_t start, uint16_t end, bt_uuid_t *uuid, + uint8_t *pdu, size_t len) +{ + uint16_t uuid_len; + + if (!uuid) + return 0; + + if (uuid->type == BT_UUID16) + uuid_len = 2; + else if (uuid->type == BT_UUID128) + uuid_len = 16; + else + return 0; + + /* Attribute Opcode (1 octet) */ + pdu[0] = ATT_OP_READ_BY_GROUP_REQ; + /* Starting Handle (2 octets) */ + att_put_u16(start, &pdu[1]); + /* Ending Handle (2 octets) */ + att_put_u16(end, &pdu[3]); + /* Attribute Group Type (2 or 16 octet UUID) */ + att_put_uuid(*uuid, &pdu[5]); + + return 5 + uuid_len; +} + +uint16_t dec_read_by_grp_req(const uint8_t *pdu, size_t len, uint16_t *start, + uint16_t *end, bt_uuid_t *uuid) +{ + const size_t min_len = sizeof(pdu[0]) + sizeof(*start) + sizeof(*end); + + if (pdu == NULL) + return 0; + + if (start == NULL || end == NULL || uuid == NULL) + return 0; + + if (pdu[0] != ATT_OP_READ_BY_GROUP_REQ) + return 0; + + if (len != (min_len + 2) && len != (min_len + 16)) + return 0; + + *start = att_get_u16(&pdu[1]); + *end = att_get_u16(&pdu[3]); + if (len == min_len + 2) + *uuid = att_get_uuid16(&pdu[5]); + else + *uuid = att_get_uuid128(&pdu[5]); + + return len; +} + +uint16_t enc_read_by_grp_resp(struct att_data_list *list, uint8_t *pdu, + size_t len) +{ + int i; + uint16_t w; + uint8_t *ptr; + + if (list == NULL) + return 0; + + if (len < list->len + sizeof(uint8_t) * 2) + return 0; + + pdu[0] = ATT_OP_READ_BY_GROUP_RESP; + pdu[1] = list->len; + + ptr = &pdu[2]; + + for (i = 0, w = 2; i < list->num && w + list->len <= len; i++) { + memcpy(ptr, list->data[i], list->len); + ptr += list->len; + w += list->len; + } + + return w; +} + +struct att_data_list *dec_read_by_grp_resp(const uint8_t *pdu, size_t len) +{ + struct att_data_list *list; + const uint8_t *ptr; + uint16_t elen, num; + int i; + + if (pdu[0] != ATT_OP_READ_BY_GROUP_RESP) + return NULL; + + /* PDU must contain at least: + * - Attribute Opcode (1 octet) + * - Length (1 octet) + * - Attribute Data List (at least one entry): + * - Attribute Handle (2 octets) + * - End Group Handle (2 octets) + * - Attribute Value (at least 1 octet) */ + if (len < 7) + return NULL; + + elen = pdu[1]; + /* Minimum Attribute Data List size */ + if (elen < 5) + return NULL; + + /* Reject incomplete Attribute Data List */ + if ((len - 2) % elen) + return NULL; + + num = (len - 2) / elen; + list = att_data_list_alloc(num, elen); + if (list == NULL) + return NULL; + + ptr = &pdu[2]; + + for (i = 0; i < num; i++) { + memcpy(list->data[i], ptr, list->len); + ptr += list->len; + } + + return list; +} + +uint16_t enc_find_by_type_req(uint16_t start, uint16_t end, bt_uuid_t *uuid, + const uint8_t *value, size_t vlen, + uint8_t *pdu, size_t len) +{ + uint16_t min_len = sizeof(pdu[0]) + sizeof(start) + sizeof(end) + + sizeof(uint16_t); + + if (pdu == NULL) + return 0; + + if (!uuid) + return 0; + + if (uuid->type != BT_UUID16) + return 0; + + if (vlen > len - min_len) + vlen = len - min_len; + + pdu[0] = ATT_OP_FIND_BY_TYPE_REQ; + att_put_u16(start, &pdu[1]); + att_put_u16(end, &pdu[3]); + att_put_uuid16(*uuid, &pdu[5]); + + if (vlen > 0) { + memcpy(&pdu[7], value, vlen); + return min_len + vlen; + } + + return min_len; +} + +uint16_t dec_find_by_type_req(const uint8_t *pdu, size_t len, uint16_t *start, + uint16_t *end, bt_uuid_t *uuid, + uint8_t *value, size_t *vlen) +{ + if (pdu == NULL) + return 0; + + if (len < 7) + return 0; + + /* Attribute Opcode (1 octet) */ + if (pdu[0] != ATT_OP_FIND_BY_TYPE_REQ) + return 0; + + /* First requested handle number (2 octets) */ + *start = att_get_u16(&pdu[1]); + /* Last requested handle number (2 octets) */ + *end = att_get_u16(&pdu[3]); + /* 16-bit UUID to find (2 octets) */ + *uuid = att_get_uuid16(&pdu[5]); + + /* Attribute value to find */ + *vlen = len - 7; + if (*vlen > 0) + memcpy(value, pdu + 7, *vlen); + + return len; +} + +uint16_t enc_find_by_type_resp(GSList *matches, uint8_t *pdu, size_t len) +{ + GSList *l; + uint16_t offset; + + if (!pdu) + return 0; + + pdu[0] = ATT_OP_FIND_BY_TYPE_RESP; + + for (l = matches, offset = 1; + l && len >= (offset + sizeof(uint16_t) * 2); + l = l->next, offset += sizeof(uint16_t) * 2) { + struct att_range *range = l->data; + + att_put_u16(range->start, &pdu[offset]); + att_put_u16(range->end, &pdu[offset + 2]); + } + + return offset; +} + +GSList *dec_find_by_type_resp(const uint8_t *pdu, size_t len) +{ + struct att_range *range; + GSList *matches; + off_t offset; + + /* PDU should contain at least: + * - Attribute Opcode (1 octet) + * - Handles Information List (at least one entry): + * - Found Attribute Handle (2 octets) + * - Group End Handle (2 octets) */ + if (pdu == NULL || len < 5) + return NULL; + + if (pdu[0] != ATT_OP_FIND_BY_TYPE_RESP) + return NULL; + + /* Reject incomplete Handles Information List */ + if ((len - 1) % 4) + return NULL; + + for (offset = 1, matches = NULL; + len >= (offset + sizeof(uint16_t) * 2); + offset += sizeof(uint16_t) * 2) { + range = g_new0(struct att_range, 1); + range->start = att_get_u16(&pdu[offset]); + range->end = att_get_u16(&pdu[offset + 2]); + + matches = g_slist_append(matches, range); + } + + return matches; +} + +uint16_t enc_read_by_type_req(uint16_t start, uint16_t end, bt_uuid_t *uuid, + uint8_t *pdu, size_t len) +{ + uint16_t uuid_len; + + if (!uuid) + return 0; + + if (uuid->type == BT_UUID16) + uuid_len = 2; + else if (uuid->type == BT_UUID128) + uuid_len = 16; + else + return 0; + + /* Attribute Opcode (1 octet) */ + pdu[0] = ATT_OP_READ_BY_TYPE_REQ; + /* Starting Handle (2 octets) */ + att_put_u16(start, &pdu[1]); + /* Ending Handle (2 octets) */ + att_put_u16(end, &pdu[3]); + /* Attribute Type (2 or 16 octet UUID) */ + att_put_uuid(*uuid, &pdu[5]); + + return 5 + uuid_len; +} + +uint16_t dec_read_by_type_req(const uint8_t *pdu, size_t len, uint16_t *start, + uint16_t *end, bt_uuid_t *uuid) +{ + const size_t min_len = sizeof(pdu[0]) + sizeof(*start) + sizeof(*end); + + if (pdu == NULL) + return 0; + + if (start == NULL || end == NULL || uuid == NULL) + return 0; + + if (len != (min_len + 2) && len != (min_len + 16)) + return 0; + + if (pdu[0] != ATT_OP_READ_BY_TYPE_REQ) + return 0; + + *start = att_get_u16(&pdu[1]); + *end = att_get_u16(&pdu[3]); + + if (len == min_len + 2) + *uuid = att_get_uuid16(&pdu[5]); + else + *uuid = att_get_uuid128(&pdu[5]); + + return len; +} + +uint16_t enc_read_by_type_resp(struct att_data_list *list, uint8_t *pdu, + size_t len) +{ + uint8_t *ptr; + size_t i, w, l; + + if (list == NULL) + return 0; + + if (pdu == NULL) + return 0; + + l = MIN(len - 2, list->len); + + pdu[0] = ATT_OP_READ_BY_TYPE_RESP; + pdu[1] = l; + ptr = &pdu[2]; + + for (i = 0, w = 2; i < list->num && w + l <= len; i++) { + memcpy(ptr, list->data[i], l); + ptr += l; + w += l; + } + + return w; +} + +struct att_data_list *dec_read_by_type_resp(const uint8_t *pdu, size_t len) +{ + struct att_data_list *list; + const uint8_t *ptr; + uint16_t elen, num; + int i; + + if (pdu[0] != ATT_OP_READ_BY_TYPE_RESP) + return NULL; + + /* PDU must contain at least: + * - Attribute Opcode (1 octet) + * - Length (1 octet) + * - Attribute Data List (at least one entry): + * - Attribute Handle (2 octets) + * - Attribute Value (at least 1 octet) */ + if (len < 5) + return NULL; + + elen = pdu[1]; + /* Minimum Attribute Data List size */ + if (elen < 3) + return NULL; + + /* Reject incomplete Attribute Data List */ + if ((len - 2) % elen) + return NULL; + + num = (len - 2) / elen; + list = att_data_list_alloc(num, elen); + if (list == NULL) + return NULL; + + ptr = &pdu[2]; + + for (i = 0; i < num; i++) { + memcpy(list->data[i], ptr, list->len); + ptr += list->len; + } + + return list; +} + +uint16_t enc_write_cmd(uint16_t handle, const uint8_t *value, size_t vlen, + uint8_t *pdu, size_t len) +{ + const uint16_t min_len = sizeof(pdu[0]) + sizeof(handle); + + if (pdu == NULL) + return 0; + + if (vlen > len - min_len) + vlen = len - min_len; + + pdu[0] = ATT_OP_WRITE_CMD; + att_put_u16(handle, &pdu[1]); + + if (vlen > 0) { + memcpy(&pdu[3], value, vlen); + return min_len + vlen; + } + + return min_len; +} + +uint16_t dec_write_cmd(const uint8_t *pdu, size_t len, uint16_t *handle, + uint8_t *value, size_t *vlen) +{ + const uint16_t min_len = sizeof(pdu[0]) + sizeof(*handle); + + if (pdu == NULL) + return 0; + + if (value == NULL || vlen == NULL || handle == NULL) + return 0; + + if (len < min_len) + return 0; + + if (pdu[0] != ATT_OP_WRITE_CMD) + return 0; + + *handle = att_get_u16(&pdu[1]); + memcpy(value, pdu + min_len, len - min_len); + *vlen = len - min_len; + + return len; +} + +uint16_t enc_write_req(uint16_t handle, const uint8_t *value, size_t vlen, + uint8_t *pdu, size_t len) +{ + const uint16_t min_len = sizeof(pdu[0]) + sizeof(handle); + + if (pdu == NULL) + return 0; + + if (vlen > len - min_len) + vlen = len - min_len; + + pdu[0] = ATT_OP_WRITE_REQ; + att_put_u16(handle, &pdu[1]); + + if (vlen > 0) { + memcpy(&pdu[3], value, vlen); + return min_len + vlen; + } + + return min_len; +} + +uint16_t dec_write_req(const uint8_t *pdu, size_t len, uint16_t *handle, + uint8_t *value, size_t *vlen) +{ + const uint16_t min_len = sizeof(pdu[0]) + sizeof(*handle); + + if (pdu == NULL) + return 0; + + if (value == NULL || vlen == NULL || handle == NULL) + return 0; + + if (len < min_len) + return 0; + + if (pdu[0] != ATT_OP_WRITE_REQ) + return 0; + + *handle = att_get_u16(&pdu[1]); + *vlen = len - min_len; + if (*vlen > 0) + memcpy(value, pdu + min_len, *vlen); + + return len; +} + +uint16_t enc_write_resp(uint8_t *pdu) +{ + if (pdu == NULL) + return 0; + + pdu[0] = ATT_OP_WRITE_RESP; + + return sizeof(pdu[0]); +} + +uint16_t dec_write_resp(const uint8_t *pdu, size_t len) +{ + if (pdu == NULL) + return 0; + + if (pdu[0] != ATT_OP_WRITE_RESP) + return 0; + + return len; +} + +uint16_t enc_read_req(uint16_t handle, uint8_t *pdu, size_t len) +{ + if (pdu == NULL) + return 0; + + /* Attribute Opcode (1 octet) */ + pdu[0] = ATT_OP_READ_REQ; + /* Attribute Handle (2 octets) */ + att_put_u16(handle, &pdu[1]); + + return 3; +} + +uint16_t enc_read_blob_req(uint16_t handle, uint16_t offset, uint8_t *pdu, + size_t len) +{ + if (pdu == NULL) + return 0; + + /* Attribute Opcode (1 octet) */ + pdu[0] = ATT_OP_READ_BLOB_REQ; + /* Attribute Handle (2 octets) */ + att_put_u16(handle, &pdu[1]); + /* Value Offset (2 octets) */ + att_put_u16(offset, &pdu[3]); + + return 5; +} + +uint16_t dec_read_req(const uint8_t *pdu, size_t len, uint16_t *handle) +{ + const uint16_t min_len = sizeof(pdu[0]) + sizeof(*handle); + + if (pdu == NULL) + return 0; + + if (handle == NULL) + return 0; + + if (len < min_len) + return 0; + + if (pdu[0] != ATT_OP_READ_REQ) + return 0; + + *handle = att_get_u16(&pdu[1]); + + return min_len; +} + +uint16_t dec_read_blob_req(const uint8_t *pdu, size_t len, uint16_t *handle, + uint16_t *offset) +{ + const uint16_t min_len = sizeof(pdu[0]) + sizeof(*handle) + + sizeof(*offset); + + if (pdu == NULL) + return 0; + + if (handle == NULL) + return 0; + + if (offset == NULL) + return 0; + + if (len < min_len) + return 0; + + if (pdu[0] != ATT_OP_READ_BLOB_REQ) + return 0; + + *handle = att_get_u16(&pdu[1]); + *offset = att_get_u16(&pdu[3]); + + return min_len; +} + +uint16_t enc_read_resp(uint8_t *value, size_t vlen, uint8_t *pdu, size_t len) +{ + if (pdu == NULL) + return 0; + + /* If the attribute value length is longer than the allowed PDU size, + * send only the octets that fit on the PDU. The remaining octets can + * be requested using the Read Blob Request. */ + if (vlen > len - 1) + vlen = len - 1; + + pdu[0] = ATT_OP_READ_RESP; + + memcpy(pdu + 1, value, vlen); + + return vlen + 1; +} + +uint16_t enc_read_blob_resp(uint8_t *value, size_t vlen, uint16_t offset, + uint8_t *pdu, size_t len) +{ + if (pdu == NULL) + return 0; + + vlen -= offset; + if (vlen > len - 1) + vlen = len - 1; + + pdu[0] = ATT_OP_READ_BLOB_RESP; + + memcpy(pdu + 1, &value[offset], vlen); + + return vlen + 1; +} + +ssize_t dec_read_resp(const uint8_t *pdu, size_t len, uint8_t *value, + size_t vlen) +{ + if (pdu == NULL) + return -EINVAL; + + if (pdu[0] != ATT_OP_READ_RESP) + return -EINVAL; + + if (value == NULL) + return len - 1; + + if (vlen < (len - 1)) + return -ENOBUFS; + + memcpy(value, pdu + 1, len - 1); + + return len - 1; +} + +uint16_t enc_error_resp(uint8_t opcode, uint16_t handle, uint8_t status, + uint8_t *pdu, size_t len) +{ + /* Attribute Opcode (1 octet) */ + pdu[0] = ATT_OP_ERROR; + /* Request Opcode In Error (1 octet) */ + pdu[1] = opcode; + /* Attribute Handle In Error (2 octets) */ + att_put_u16(handle, &pdu[2]); + /* Error Code (1 octet) */ + pdu[4] = status; + + return 5; +} + +uint16_t enc_find_info_req(uint16_t start, uint16_t end, uint8_t *pdu, + size_t len) +{ + if (pdu == NULL) + return 0; + + /* Attribute Opcode (1 octet) */ + pdu[0] = ATT_OP_FIND_INFO_REQ; + /* Starting Handle (2 octets) */ + att_put_u16(start, &pdu[1]); + /* Ending Handle (2 octets) */ + att_put_u16(end, &pdu[3]); + + return 5; +} + +uint16_t dec_find_info_req(const uint8_t *pdu, size_t len, uint16_t *start, + uint16_t *end) +{ + const uint16_t min_len = sizeof(pdu[0]) + sizeof(*start) + sizeof(*end); + + if (pdu == NULL) + return 0; + + if (len < min_len) + return 0; + + if (start == NULL || end == NULL) + return 0; + + if (pdu[0] != ATT_OP_FIND_INFO_REQ) + return 0; + + *start = att_get_u16(&pdu[1]); + *end = att_get_u16(&pdu[3]); + + return min_len; +} + +uint16_t enc_find_info_resp(uint8_t format, struct att_data_list *list, + uint8_t *pdu, size_t len) +{ + uint8_t *ptr; + size_t i, w; + + if (pdu == NULL) + return 0; + + if (list == NULL) + return 0; + + if (len < list->len + sizeof(uint8_t) * 2) + return 0; + + pdu[0] = ATT_OP_FIND_INFO_RESP; + pdu[1] = format; + ptr = (void *) &pdu[2]; + + for (i = 0, w = 2; i < list->num && w + list->len <= len; i++) { + memcpy(ptr, list->data[i], list->len); + ptr += list->len; + w += list->len; + } + + return w; +} + +struct att_data_list *dec_find_info_resp(const uint8_t *pdu, size_t len, + uint8_t *format) +{ + struct att_data_list *list; + uint8_t *ptr; + uint16_t elen, num; + int i; + + if (pdu == NULL) + return 0; + + if (format == NULL) + return 0; + + if (pdu[0] != ATT_OP_FIND_INFO_RESP) + return 0; + + *format = pdu[1]; + elen = sizeof(pdu[0]) + sizeof(*format); + if (*format == 0x01) + elen += 2; + else if (*format == 0x02) + elen += 16; + + num = (len - 2) / elen; + + ptr = (void *) &pdu[2]; + + list = att_data_list_alloc(num, elen); + if (list == NULL) + return NULL; + + for (i = 0; i < num; i++) { + memcpy(list->data[i], ptr, list->len); + ptr += list->len; + } + + return list; +} + +uint16_t enc_notification(uint16_t handle, uint8_t *value, size_t vlen, + uint8_t *pdu, size_t len) +{ + const uint16_t min_len = sizeof(pdu[0]) + sizeof(uint16_t); + + if (pdu == NULL) + return 0; + + if (len < (vlen + min_len)) + return 0; + + pdu[0] = ATT_OP_HANDLE_NOTIFY; + att_put_u16(handle, &pdu[1]); + memcpy(&pdu[3], value, vlen); + + return vlen + min_len; +} + +uint16_t enc_indication(uint16_t handle, uint8_t *value, size_t vlen, + uint8_t *pdu, size_t len) +{ + const uint16_t min_len = sizeof(pdu[0]) + sizeof(uint16_t); + + if (pdu == NULL) + return 0; + + if (len < (vlen + min_len)) + return 0; + + pdu[0] = ATT_OP_HANDLE_IND; + att_put_u16(handle, &pdu[1]); + memcpy(&pdu[3], value, vlen); + + return vlen + min_len; +} + +uint16_t dec_indication(const uint8_t *pdu, size_t len, uint16_t *handle, + uint8_t *value, size_t vlen) +{ + const uint16_t min_len = sizeof(pdu[0]) + sizeof(uint16_t); + uint16_t dlen; + + if (pdu == NULL) + return 0; + + if (pdu[0] != ATT_OP_HANDLE_IND) + return 0; + + if (len < min_len) + return 0; + + dlen = MIN(len - min_len, vlen); + + if (handle) + *handle = att_get_u16(&pdu[1]); + + memcpy(value, &pdu[3], dlen); + + return dlen; +} + +uint16_t enc_confirmation(uint8_t *pdu, size_t len) +{ + if (pdu == NULL) + return 0; + + /* Attribute Opcode (1 octet) */ + pdu[0] = ATT_OP_HANDLE_CNF; + + return 1; +} + +uint16_t enc_mtu_req(uint16_t mtu, uint8_t *pdu, size_t len) +{ + if (pdu == NULL) + return 0; + + /* Attribute Opcode (1 octet) */ + pdu[0] = ATT_OP_MTU_REQ; + /* Client Rx MTU (2 octets) */ + att_put_u16(mtu, &pdu[1]); + + return 3; +} + +uint16_t dec_mtu_req(const uint8_t *pdu, size_t len, uint16_t *mtu) +{ + const uint16_t min_len = sizeof(pdu[0]) + sizeof(*mtu); + + if (pdu == NULL) + return 0; + + if (mtu == NULL) + return 0; + + if (len < min_len) + return 0; + + if (pdu[0] != ATT_OP_MTU_REQ) + return 0; + + *mtu = att_get_u16(&pdu[1]); + + return min_len; +} + +uint16_t enc_mtu_resp(uint16_t mtu, uint8_t *pdu, size_t len) +{ + if (pdu == NULL) + return 0; + + /* Attribute Opcode (1 octet) */ + pdu[0] = ATT_OP_MTU_RESP; + /* Server Rx MTU (2 octets) */ + att_put_u16(mtu, &pdu[1]); + + return 3; +} + +uint16_t dec_mtu_resp(const uint8_t *pdu, size_t len, uint16_t *mtu) +{ + const uint16_t min_len = sizeof(pdu[0]) + sizeof(*mtu); + + if (pdu == NULL) + return 0; + + if (mtu == NULL) + return 0; + + if (len < min_len) + return 0; + + if (pdu[0] != ATT_OP_MTU_RESP) + return 0; + + *mtu = att_get_u16(&pdu[1]); + + return min_len; +} + +uint16_t enc_prep_write_req(uint16_t handle, uint16_t offset, + const uint8_t *value, size_t vlen, + uint8_t *pdu, size_t len) +{ + const uint16_t min_len = sizeof(pdu[0]) + sizeof(handle) + + sizeof(offset); + + if (pdu == NULL) + return 0; + + if (vlen > len - min_len) + vlen = len - min_len; + + pdu[0] = ATT_OP_PREP_WRITE_REQ; + att_put_u16(handle, &pdu[1]); + att_put_u16(offset, &pdu[3]); + + if (vlen > 0) { + memcpy(&pdu[5], value, vlen); + return min_len + vlen; + } + + return min_len; +} + +uint16_t dec_prep_write_req(const uint8_t *pdu, size_t len, uint16_t *handle, + uint16_t *offset, uint8_t *value, size_t *vlen) +{ + const uint16_t min_len = sizeof(pdu[0]) + sizeof(*handle) + + sizeof(*offset); + + if (pdu == NULL) + return 0; + + if (handle == NULL || offset == NULL || value == NULL || vlen == NULL) + return 0; + + if (len < min_len) + return 0; + + if (pdu[0] != ATT_OP_PREP_WRITE_REQ) + return 0; + + *handle = att_get_u16(&pdu[1]); + *offset = att_get_u16(&pdu[3]); + + *vlen = len - min_len; + if (*vlen > 0) + memcpy(value, pdu + min_len, *vlen); + + return len; +} + +uint16_t enc_prep_write_resp(uint16_t handle, uint16_t offset, + const uint8_t *value, size_t vlen, + uint8_t *pdu, size_t len) +{ + const uint16_t min_len = sizeof(pdu[0]) + sizeof(handle) + + sizeof(offset); + + if (pdu == NULL) + return 0; + + if (vlen > len - min_len) + vlen = len - min_len; + + pdu[0] = ATT_OP_PREP_WRITE_RESP; + att_put_u16(handle, &pdu[1]); + att_put_u16(offset, &pdu[3]); + + if (vlen > 0) { + memcpy(&pdu[5], value, vlen); + return min_len + vlen; + } + + return min_len; +} + +uint16_t dec_prep_write_resp(const uint8_t *pdu, size_t len, uint16_t *handle, + uint16_t *offset, uint8_t *value, size_t *vlen) +{ + const uint16_t min_len = sizeof(pdu[0]) + sizeof(*handle) + + sizeof(*offset); + + if (pdu == NULL) + return 0; + + if (handle == NULL || offset == NULL || value == NULL || vlen == NULL) + return 0; + + if (len < min_len) + return 0; + + if (pdu[0] != ATT_OP_PREP_WRITE_REQ) + return 0; + + *handle = att_get_u16(&pdu[1]); + *offset = att_get_u16(&pdu[3]); + *vlen = len - min_len; + if (*vlen > 0) + memcpy(value, pdu + min_len, *vlen); + + return len; +} + +uint16_t enc_exec_write_req(uint8_t flags, uint8_t *pdu, size_t len) +{ + if (pdu == NULL) + return 0; + + if (flags > 1) + return 0; + + /* Attribute Opcode (1 octet) */ + pdu[0] = ATT_OP_EXEC_WRITE_REQ; + /* Flags (1 octet) */ + pdu[1] = flags; + + return 2; +} + +uint16_t dec_exec_write_req(const uint8_t *pdu, size_t len, uint8_t *flags) +{ + const uint16_t min_len = sizeof(pdu[0]) + sizeof(*flags); + + if (pdu == NULL) + return 0; + + if (flags == NULL) + return 0; + + if (len < min_len) + return 0; + + if (pdu[0] != ATT_OP_EXEC_WRITE_REQ) + return 0; + + *flags = pdu[1]; + + return min_len; +} + +uint16_t enc_exec_write_resp(uint8_t *pdu) +{ + if (pdu == NULL) + return 0; + + /* Attribute Opcode (1 octet) */ + pdu[0] = ATT_OP_EXEC_WRITE_RESP; + + return 1; +} + +uint16_t dec_exec_write_resp(const uint8_t *pdu, size_t len) +{ + const uint16_t min_len = sizeof(pdu[0]); + + if (pdu == NULL) + return 0; + + if (len < min_len) + return 0; + + if (pdu[0] != ATT_OP_EXEC_WRITE_RESP) + return 0; + + return len; +} diff --git a/drive-sdk/deps/bzle/src/bluetooth.c b/drive-sdk/deps/bzle/src/bluetooth.c new file mode 100644 index 0000000..af80c79 --- /dev/null +++ b/drive-sdk/deps/bzle/src/bluetooth.c @@ -0,0 +1,867 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2000-2001 Qualcomm Incorporated + * Copyright (C) 2002-2003 Maxim Krasnyansky + * Copyright (C) 2002-2010 Marcel Holtmann + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +void baswap(bdaddr_t *dst, const bdaddr_t *src) +{ + register unsigned char *d = (unsigned char *) dst; + register const unsigned char *s = (const unsigned char *) src; + register int i; + + for (i = 0; i < 6; i++) + d[i] = s[5-i]; +} + +char *batostr(const bdaddr_t *ba) +{ + char *str = bt_malloc(18); + if (!str) + return NULL; + + sprintf(str, "%2.2X:%2.2X:%2.2X:%2.2X:%2.2X:%2.2X", + ba->b[0], ba->b[1], ba->b[2], + ba->b[3], ba->b[4], ba->b[5]); + + return str; +} + +bdaddr_t *strtoba(const char *str) +{ + bdaddr_t b; + bdaddr_t *ba = bt_malloc(sizeof(*ba)); + + if (ba) { + str2ba(str, &b); + baswap(ba, &b); + } + + return ba; +} + +int ba2str(const bdaddr_t *ba, char *str) +{ + return sprintf(str, "%2.2X:%2.2X:%2.2X:%2.2X:%2.2X:%2.2X", + ba->b[5], ba->b[4], ba->b[3], ba->b[2], ba->b[1], ba->b[0]); +} + +int str2ba(const char *str, bdaddr_t *ba) +{ + int i; + + if (bachk(str) < 0) { + memset(ba, 0, sizeof(*ba)); + return -1; + } + + for (i = 5; i >= 0; i--, str += 3) + ba->b[i] = strtol(str, NULL, 16); + + return 0; +} + +int ba2oui(const bdaddr_t *ba, char *str) +{ + return sprintf(str, "%2.2X-%2.2X-%2.2X", ba->b[5], ba->b[4], ba->b[3]); +} + +int bachk(const char *str) +{ + if (!str) + return -1; + + if (strlen(str) != 17) + return -1; + + while (*str) { + if (!isxdigit(*str++)) + return -1; + + if (!isxdigit(*str++)) + return -1; + + if (*str == 0) + break; + + if (*str++ != ':') + return -1; + } + + return 0; +} + +int baprintf(const char *format, ...) +{ + va_list ap; + int len; + + va_start(ap, format); + len = vprintf(format, ap); + va_end(ap); + + return len; +} + +int bafprintf(FILE *stream, const char *format, ...) +{ + va_list ap; + int len; + + va_start(ap, format); + len = vfprintf(stream, format, ap); + va_end(ap); + + return len; +} + +int basprintf(char *str, const char *format, ...) +{ + va_list ap; + int len; + + va_start(ap, format); + len = vsnprintf(str, (~0U) >> 1, format, ap); + va_end(ap); + + return len; +} + +int basnprintf(char *str, size_t size, const char *format, ...) +{ + va_list ap; + int len; + + va_start(ap, format); + len = vsnprintf(str, size, format, ap); + va_end(ap); + + return len; +} + +void *bt_malloc(size_t size) +{ + return malloc(size); +} + +void bt_free(void *ptr) +{ + free(ptr); +} + +/* Bluetooth error codes to Unix errno mapping */ +int bt_error(uint16_t code) +{ + switch (code) { + case 0: + return 0; + case HCI_UNKNOWN_COMMAND: + return EBADRQC; + case HCI_NO_CONNECTION: + return ENOTCONN; + case HCI_HARDWARE_FAILURE: + return EIO; + case HCI_PAGE_TIMEOUT: + return EHOSTDOWN; + case HCI_AUTHENTICATION_FAILURE: + return EACCES; + case HCI_PIN_OR_KEY_MISSING: + return EINVAL; + case HCI_MEMORY_FULL: + return ENOMEM; + case HCI_CONNECTION_TIMEOUT: + return ETIMEDOUT; + case HCI_MAX_NUMBER_OF_CONNECTIONS: + case HCI_MAX_NUMBER_OF_SCO_CONNECTIONS: + return EMLINK; + case HCI_ACL_CONNECTION_EXISTS: + return EALREADY; + case HCI_COMMAND_DISALLOWED: + case HCI_TRANSACTION_COLLISION: + case HCI_ROLE_SWITCH_PENDING: + return EBUSY; + case HCI_REJECTED_LIMITED_RESOURCES: + case HCI_REJECTED_PERSONAL: + case HCI_QOS_REJECTED: + return ECONNREFUSED; + case HCI_HOST_TIMEOUT: + return ETIMEDOUT; + case HCI_UNSUPPORTED_FEATURE: + case HCI_QOS_NOT_SUPPORTED: + case HCI_PAIRING_NOT_SUPPORTED: + case HCI_CLASSIFICATION_NOT_SUPPORTED: + case HCI_UNSUPPORTED_LMP_PARAMETER_VALUE: + case HCI_PARAMETER_OUT_OF_RANGE: + case HCI_QOS_UNACCEPTABLE_PARAMETER: + return EOPNOTSUPP; + case HCI_INVALID_PARAMETERS: + case HCI_SLOT_VIOLATION: + return EINVAL; + case HCI_OE_USER_ENDED_CONNECTION: + case HCI_OE_LOW_RESOURCES: + case HCI_OE_POWER_OFF: + return ECONNRESET; + case HCI_CONNECTION_TERMINATED: + return ECONNABORTED; + case HCI_REPEATED_ATTEMPTS: + return ELOOP; + case HCI_REJECTED_SECURITY: + case HCI_PAIRING_NOT_ALLOWED: + case HCI_INSUFFICIENT_SECURITY: + return EACCES; + case HCI_UNSUPPORTED_REMOTE_FEATURE: + return EPROTONOSUPPORT; + case HCI_SCO_OFFSET_REJECTED: + return ECONNREFUSED; + case HCI_UNKNOWN_LMP_PDU: + case HCI_INVALID_LMP_PARAMETERS: + case HCI_LMP_ERROR_TRANSACTION_COLLISION: + case HCI_LMP_PDU_NOT_ALLOWED: + case HCI_ENCRYPTION_MODE_NOT_ACCEPTED: + return EPROTO; + default: + return ENOSYS; + } +} + +const char *bt_compidtostr(int compid) +{ + switch (compid) { + case 0: + return "Ericsson Technology Licensing"; + case 1: + return "Nokia Mobile Phones"; + case 2: + return "Intel Corp."; + case 3: + return "IBM Corp."; + case 4: + return "Toshiba Corp."; + case 5: + return "3Com"; + case 6: + return "Microsoft"; + case 7: + return "Lucent"; + case 8: + return "Motorola"; + case 9: + return "Infineon Technologies AG"; + case 10: + return "Cambridge Silicon Radio"; + case 11: + return "Silicon Wave"; + case 12: + return "Digianswer A/S"; + case 13: + return "Texas Instruments Inc."; + case 14: + return "Ceva, Inc. (formerly Parthus Technologies, Inc.)"; + case 15: + return "Broadcom Corporation"; + case 16: + return "Mitel Semiconductor"; + case 17: + return "Widcomm, Inc"; + case 18: + return "Zeevo, Inc."; + case 19: + return "Atmel Corporation"; + case 20: + return "Mitsubishi Electric Corporation"; + case 21: + return "RTX Telecom A/S"; + case 22: + return "KC Technology Inc."; + case 23: + return "NewLogic"; + case 24: + return "Transilica, Inc."; + case 25: + return "Rohde & Schwarz GmbH & Co. KG"; + case 26: + return "TTPCom Limited"; + case 27: + return "Signia Technologies, Inc."; + case 28: + return "Conexant Systems Inc."; + case 29: + return "Qualcomm"; + case 30: + return "Inventel"; + case 31: + return "AVM Berlin"; + case 32: + return "BandSpeed, Inc."; + case 33: + return "Mansella Ltd"; + case 34: + return "NEC Corporation"; + case 35: + return "WavePlus Technology Co., Ltd."; + case 36: + return "Alcatel"; + case 37: + return "Philips Semiconductors"; + case 38: + return "C Technologies"; + case 39: + return "Open Interface"; + case 40: + return "R F Micro Devices"; + case 41: + return "Hitachi Ltd"; + case 42: + return "Symbol Technologies, Inc."; + case 43: + return "Tenovis"; + case 44: + return "Macronix International Co. Ltd."; + case 45: + return "GCT Semiconductor"; + case 46: + return "Norwood Systems"; + case 47: + return "MewTel Technology Inc."; + case 48: + return "ST Microelectronics"; + case 49: + return "Synopsis"; + case 50: + return "Red-M (Communications) Ltd"; + case 51: + return "Commil Ltd"; + case 52: + return "Computer Access Technology Corporation (CATC)"; + case 53: + return "Eclipse (HQ Espana) S.L."; + case 54: + return "Renesas Technology Corp."; + case 55: + return "Mobilian Corporation"; + case 56: + return "Terax"; + case 57: + return "Integrated System Solution Corp."; + case 58: + return "Matsushita Electric Industrial Co., Ltd."; + case 59: + return "Gennum Corporation"; + case 60: + return "Research In Motion"; + case 61: + return "IPextreme, Inc."; + case 62: + return "Systems and Chips, Inc."; + case 63: + return "Bluetooth SIG, Inc."; + case 64: + return "Seiko Epson Corporation"; + case 65: + return "Integrated Silicon Solution Taiwan, Inc."; + case 66: + return "CONWISE Technology Corporation Ltd"; + case 67: + return "PARROT SA"; + case 68: + return "Socket Mobile"; + case 69: + return "Atheros Communications, Inc."; + case 70: + return "MediaTek, Inc."; + case 71: + return "Bluegiga"; + case 72: + return "Marvell Technology Group Ltd."; + case 73: + return "3DSP Corporation"; + case 74: + return "Accel Semiconductor Ltd."; + case 75: + return "Continental Automotive Systems"; + case 76: + return "Apple, Inc."; + case 77: + return "Staccato Communications, Inc."; + case 78: + return "Avago Technologies"; + case 79: + return "APT Licensing Ltd."; + case 80: + return "SiRF Technology"; + case 81: + return "Tzero Technologies, Inc."; + case 82: + return "J&M Corporation"; + case 83: + return "Free2move AB"; + case 84: + return "3DiJoy Corporation"; + case 85: + return "Plantronics, Inc."; + case 86: + return "Sony Ericsson Mobile Communications"; + case 87: + return "Harman International Industries, Inc."; + case 88: + return "Vizio, Inc."; + case 89: + return "Nordic Semiconductor ASA"; + case 90: + return "EM Microelectronic-Marin SA"; + case 91: + return "Ralink Technology Corporation"; + case 92: + return "Belkin International, Inc."; + case 93: + return "Realtek Semiconductor Corporation"; + case 94: + return "Stonestreet One, LLC"; + case 95: + return "Wicentric, Inc."; + case 96: + return "RivieraWaves S.A.S"; + case 97: + return "RDA Microelectronics"; + case 98: + return "Gibson Guitars"; + case 99: + return "MiCommand Inc."; + case 100: + return "Band XI International, LLC"; + case 101: + return "Hewlett-Packard Company"; + case 102: + return "9Solutions Oy"; + case 103: + return "GN Netcom A/S"; + case 104: + return "General Motors"; + case 105: + return "A&D Engineering, Inc."; + case 106: + return "MindTree Ltd."; + case 107: + return "Polar Electro OY"; + case 108: + return "Beautiful Enterprise Co., Ltd."; + case 109: + return "BriarTek, Inc."; + case 110: + return "Summit Data Communications, Inc."; + case 111: + return "Sound ID"; + case 112: + return "Monster, LLC"; + case 113: + return "connectBlue AB"; + case 114: + return "ShangHai Super Smart Electronics Co. Ltd."; + case 115: + return "Group Sense Ltd."; + case 116: + return "Zomm, LLC"; + case 117: + return "Samsung Electronics Co. Ltd."; + case 118: + return "Creative Technology Ltd."; + case 119: + return "Laird Technologies"; + case 120: + return "Nike, Inc."; + case 121: + return "lesswire AG"; + case 122: + return "MStar Semiconductor, Inc."; + case 123: + return "Hanlynn Technologies"; + case 124: + return "A & R Cambridge"; + case 125: + return "Seers Technology Co. Ltd"; + case 126: + return "Sports Tracking Technologies Ltd."; + case 127: + return "Autonet Mobile"; + case 128: + return "DeLorme Publishing Company, Inc."; + case 129: + return "WuXi Vimicro"; + case 130: + return "Sennheiser Communications A/S"; + case 131: + return "TimeKeeping Systems, Inc."; + case 132: + return "Ludus Helsinki Ltd."; + case 133: + return "BlueRadios, Inc."; + case 134: + return "equinox AG"; + case 135: + return "Garmin International, Inc."; + case 136: + return "Ecotest"; + case 137: + return "GN ReSound A/S"; + case 138: + return "Jawbone"; + case 139: + return "Topcorn Positioning Systems, LLC"; + case 140: + return "Qualcomm Retail Solutions, Inc. (formerly Qualcomm Labs, Inc.)"; + case 141: + return "Zscan Software"; + case 142: + return "Quintic Corp."; + case 143: + return "Stollman E+V GmbH"; + case 144: + return "Funai Electric Co., Ltd."; + case 145: + return "Advanced PANMOBIL Systems GmbH & Co. KG"; + case 146: + return "ThinkOptics, Inc."; + case 147: + return "Universal Electronics, Inc."; + case 148: + return "Airoha Technology Corp."; + case 149: + return "NEC Lighting, Ltd."; + case 150: + return "ODM Technology, Inc."; + case 151: + return "ConnecteDevice Ltd."; + case 152: + return "zer01.tv GmbH"; + case 153: + return "i.Tech Dynamic Global Distribution Ltd."; + case 154: + return "Alpwise"; + case 155: + return "Jiangsu Toppower Automotive Electronics Co., Ltd."; + case 156: + return "Colorfy, Inc."; + case 157: + return "Geoforce Inc."; + case 158: + return "Bose Corporation"; + case 159: + return "Suunto Oy"; + case 160: + return "Kensington Computer Products Group"; + case 161: + return "SR-Medizinelektronik"; + case 162: + return "Vertu Corporation Limited"; + case 163: + return "Meta Watch Ltd."; + case 164: + return "LINAK A/S"; + case 165: + return "OTL Dynamics LLC"; + case 166: + return "Panda Ocean Inc."; + case 167: + return "Visteon Corporation"; + case 168: + return "ARP Devices Limited"; + case 169: + return "Magneti Marelli S.p.A"; + case 170: + return "CAEN RFID srl"; + case 171: + return "Ingenieur-Systemgruppe Zahn GmbH"; + case 172: + return "Green Throttle Games"; + case 173: + return "Peter Systemtechnik GmbH"; + case 174: + return "Omegawave Oy"; + case 175: + return "Cinetix"; + case 176: + return "Passif Semiconductor Corp"; + case 177: + return "Saris Cycling Group, Inc"; + case 178: + return "Bekey A/S"; + case 179: + return "Clarinox Technologies Pty. Ltd."; + case 180: + return "BDE Technology Co., Ltd."; + case 181: + return "Swirl Networks"; + case 182: + return "Meso international"; + case 183: + return "TreLab Ltd"; + case 184: + return "Qualcomm Innovation Center, Inc. (QuIC)"; + case 185: + return "Johnson Controls, Inc."; + case 186: + return "Starkey Laboratories Inc."; + case 187: + return "S-Power Electronics Limited"; + case 188: + return "Ace Sensor Inc"; + case 189: + return "Aplix Corporation"; + case 190: + return "AAMP of America"; + case 191: + return "Stalmart Technology Limited"; + case 192: + return "AMICCOM Electronics Corporation"; + case 193: + return "Shenzhen Excelsecu Data Technology Co.,Ltd"; + case 194: + return "Geneq Inc."; + case 195: + return "adidas AG"; + case 196: + return "LG Electronics"; + case 197: + return "Onset Computer Corporation"; + case 198: + return "Selfly BV"; + case 199: + return "Quuppa Oy."; + case 200: + return "GeLo Inc"; + case 201: + return "Evluma"; + case 202: + return "MC10"; + case 203: + return "Binauric SE"; + case 204: + return "Beats Electronics"; + case 205: + return "Microchip Technology Inc."; + case 206: + return "Elgato Systems GmbH"; + case 207: + return "ARCHOS SA"; + case 208: + return "Dexcom, Inc."; + case 209: + return "Polar Electro Europe B.V."; + case 210: + return "Dialog Semiconductor B.V."; + case 211: + return "Taixingbang Technology (HK) Co,. LTD."; + case 212: + return "Kawantech"; + case 213: + return "Austco Communication Systems"; + case 214: + return "Timex Group USA, Inc."; + case 215: + return "Qualcomm Technologies, Inc."; + case 216: + return "Qualcomm Connected Experiences, Inc."; + case 217: + return "Voyetra Turtle Beach"; + case 218: + return "txtr GmbH"; + case 219: + return "Biosentronics"; + case 220: + return "Procter & Gamble"; + case 221: + return "Hosiden Corporation"; + case 222: + return "Muzik LLC"; + case 223: + return "Misfit Wearables Corp"; + case 224: + return "Google"; + case 225: + return "Danlers Ltd"; + case 226: + return "Semilink Inc"; + case 227: + return "inMusic Brands, Inc"; + case 228: + return "L.S. Research Inc."; + case 229: + return "Eden Software Consultants Ltd."; + case 230: + return "Freshtemp"; + case 231: + return "KS Technologies"; + case 232: + return "ACTS Technologies"; + case 233: + return "Vtrack Systems"; + case 234: + return "Nielsen-Kellerman Company"; + case 235: + return "Server Technology, Inc."; + case 236: + return "BioResearch Associates"; + case 237: + return "Jolly Logic, LLC"; + case 238: + return "Above Average Outcomes, Inc."; + case 239: + return "Bitsplitters GmbH"; + case 240: + return "PayPal, Inc."; + case 241: + return "Witron Technology Limited"; + case 242: + return "Morse Project Inc."; + case 243: + return "Kent Displays Inc."; + case 244: + return "Nautilus Inc."; + case 245: + return "Smartifier Oy"; + case 246: + return "Elcometer Limited"; + case 247: + return "VSN Technologies Inc."; + case 248: + return "AceUni Corp., Ltd."; + case 249: + return "StickNFind"; + case 250: + return "Crystal Code AB"; + case 251: + return "KOUKAAM a.s."; + case 252: + return "Delphi Corporation"; + case 253: + return "ValenceTech Limited"; + case 254: + return "Reserved"; + case 255: + return "Typo Products, LLC"; + case 256: + return "TomTom International BV"; + case 257: + return "Fugoo, Inc"; + case 258: + return "Keiser Corporation"; + case 259: + return "Bang & Olufsen A/S"; + case 260: + return "PLUS Locations Systems Pty Ltd"; + case 261: + return "Ubiquitous Computing Technology Corporation"; + case 262: + return "Innovative Yachtter Solutions"; + case 263: + return "William Demant Holding A/S"; + case 264: + return "Chicony Electronics Co., Ltd."; + case 265: + return "Atus BV"; + case 266: + return "Codegate Ltd."; + case 267: + return "ERi, Inc."; + case 268: + return "Transducers Direct, LLC"; + case 269: + return "Fujitsu Ten Limited"; + case 270: + return "Audi AG"; + case 271: + return "HiSilicon Technologies Co., Ltd."; + case 272: + return "Nippon Seiki Co., Ltd."; + case 273: + return "Steelseries ApS"; + case 274: + return "vyzybl Inc."; + case 275: + return "Openbrain Technologies, Co., Ltd."; + case 276: + return "Xensr"; + case 277: + return "e.solutions"; + case 278: + return "1OAK Technologies"; + case 279: + return "Wimoto Technologies Inc"; + case 280: + return "Radius Networks, Inc."; + case 281: + return "Wize Technology Co., Ltd."; + case 282: + return "Qualcomm Labs, Inc."; + case 283: + return "Aruba Networks"; + case 284: + return "Baidu"; + case 285: + return "Arendi AG"; + case 286: + return "Skoda Auto a.s."; + case 287: + return "Volkswagon AG"; + case 288: + return "Porsche AG"; + case 289: + return "Sino Wealth Electronic Ltd."; + case 290: + return "AirTurn, Inc."; + case 291: + return "Kinsa, Inc."; + case 292: + return "HID Global"; + case 293: + return "SEAT es"; + case 294: + return "Promethean Ltd."; + case 295: + return "Salutica Allied Solutions"; + case 296: + return "GPSI Group Pty Ltd"; + case 297: + return "Nimble Devices Oy"; + case 298: + return "Changzhou Yongse Infotech Co., Ltd"; + case 65535: + return "internal use"; + default: + return "not assigned"; + } +} diff --git a/drive-sdk/deps/bzle/src/btio.c b/drive-sdk/deps/bzle/src/btio.c new file mode 100644 index 0000000..6ad7e7a --- /dev/null +++ b/drive-sdk/deps/bzle/src/btio.c @@ -0,0 +1,1186 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2009-2010 Marcel Holtmann + * Copyright (C) 2009-2010 Nokia Corporation + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +/* + * Remove support for RF_COMM and SCO communication types, + * since these are not used by Bluetooth LE. + * + * 01-Mar-2014 Brian Chapados + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include + +#include + +#ifndef BT_FLUSHABLE +#define BT_FLUSHABLE 8 +#endif + +#define ERROR_FAILED(gerr, str, err) \ + g_set_error(gerr, BT_IO_ERROR, err, \ + str ": %s (%d)", strerror(err), err) + +#define DEFAULT_DEFER_TIMEOUT 30 + +typedef enum { + BT_IO_L2CAP, + BT_IO_RFCOMM, + BT_IO_SCO, + BT_IO_INVALID, +} BtIOType; + +struct set_opts { + bdaddr_t src; + bdaddr_t dst; + BtIOType type; + uint8_t src_type; + uint8_t dst_type; + int defer; + int sec_level; + uint8_t channel; + uint16_t psm; + uint16_t cid; + uint16_t mtu; + uint16_t imtu; + uint16_t omtu; + int master; + uint8_t mode; + int flushable; + uint32_t priority; + uint16_t voice; +}; + +struct connect { + BtIOConnect connect; + gpointer user_data; + GDestroyNotify destroy; +}; + +struct accept { + BtIOConnect connect; + gpointer user_data; + GDestroyNotify destroy; +}; + +struct server { + BtIOConnect connect; + BtIOConfirm confirm; + gpointer user_data; + GDestroyNotify destroy; +}; + +static BtIOType bt_io_get_type(GIOChannel *io, GError **gerr) +{ + int sk = g_io_channel_unix_get_fd(io); + int domain, proto, err; + socklen_t len; + + domain = 0; + len = sizeof(domain); + err = getsockopt(sk, SOL_SOCKET, SO_DOMAIN, &domain, &len); + if (err < 0) { + ERROR_FAILED(gerr, "getsockopt(SO_DOMAIN)", errno); + return BT_IO_INVALID; + } + + if (domain != AF_BLUETOOTH) { + g_set_error(gerr, BT_IO_ERROR, EINVAL, + "BtIO socket domain not AF_BLUETOOTH"); + return BT_IO_INVALID; + } + + proto = 0; + len = sizeof(proto); + err = getsockopt(sk, SOL_SOCKET, SO_PROTOCOL, &proto, &len); + if (err < 0) { + ERROR_FAILED(gerr, "getsockopt(SO_PROTOCOL)", errno); + return BT_IO_INVALID; + } + + switch (proto) { + case BTPROTO_RFCOMM: + return BT_IO_RFCOMM; + case BTPROTO_SCO: + return BT_IO_SCO; + case BTPROTO_L2CAP: + return BT_IO_L2CAP; + default: + g_set_error(gerr, BT_IO_ERROR, EINVAL, + "Unknown BtIO socket type"); + return BT_IO_INVALID; + } +} + +static void server_remove(struct server *server) +{ + if (server->destroy) + server->destroy(server->user_data); + g_free(server); +} + +static void connect_remove(struct connect *conn) +{ + if (conn->destroy) + conn->destroy(conn->user_data); + g_free(conn); +} + +static void accept_remove(struct accept *accept) +{ + if (accept->destroy) + accept->destroy(accept->user_data); + g_free(accept); +} + +static gboolean check_nval(GIOChannel *io) +{ + struct pollfd fds; + + memset(&fds, 0, sizeof(fds)); + fds.fd = g_io_channel_unix_get_fd(io); + fds.events = POLLNVAL; + + if (poll(&fds, 1, 0) > 0 && (fds.revents & POLLNVAL)) + return TRUE; + + return FALSE; +} + +static gboolean accept_cb(GIOChannel *io, GIOCondition cond, + gpointer user_data) +{ + struct accept *accept = user_data; + GError *gerr = NULL; + + /* If the user aborted this accept attempt */ + if ((cond & G_IO_NVAL) || check_nval(io)) + return FALSE; + + if (cond & (G_IO_HUP | G_IO_ERR)) { + int err, sk_err, sock = g_io_channel_unix_get_fd(io); + socklen_t len = sizeof(sk_err); + + if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &sk_err, &len) < 0) + err = -errno; + else + err = -sk_err; + + if (err < 0) + ERROR_FAILED(&gerr, "HUP or ERR on socket", -err); + } + + accept->connect(io, gerr, accept->user_data); + + g_clear_error(&gerr); + + return FALSE; +} + +static gboolean connect_cb(GIOChannel *io, GIOCondition cond, + gpointer user_data) +{ + struct connect *conn = user_data; + GError *gerr = NULL; + int err, sk_err, sock; + socklen_t len = sizeof(sk_err); + + /* If the user aborted this connect attempt */ + if ((cond & G_IO_NVAL) || check_nval(io)) + return FALSE; + + sock = g_io_channel_unix_get_fd(io); + + if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &sk_err, &len) < 0) + err = -errno; + else + err = -sk_err; + + if (err < 0) + ERROR_FAILED(&gerr, "connect error", -err); + + conn->connect(io, gerr, conn->user_data); + + g_clear_error(&gerr); + + return FALSE; +} + +static gboolean server_cb(GIOChannel *io, GIOCondition cond, + gpointer user_data) +{ + struct server *server = user_data; + int srv_sock, cli_sock; + GIOChannel *cli_io; + + /* If the user closed the server */ + if ((cond & G_IO_NVAL) || check_nval(io)) + return FALSE; + + srv_sock = g_io_channel_unix_get_fd(io); + + cli_sock = accept(srv_sock, NULL, NULL); + if (cli_sock < 0) + return TRUE; + + cli_io = g_io_channel_unix_new(cli_sock); + + g_io_channel_set_close_on_unref(cli_io, TRUE); + g_io_channel_set_flags(cli_io, G_IO_FLAG_NONBLOCK, NULL); + + if (server->confirm) + server->confirm(cli_io, server->user_data); + else + server->connect(cli_io, NULL, server->user_data); + + g_io_channel_unref(cli_io); + + return TRUE; +} + +static void server_add(GIOChannel *io, BtIOConnect connect, + BtIOConfirm confirm, gpointer user_data, + GDestroyNotify destroy) +{ + struct server *server; + GIOCondition cond; + + server = g_new0(struct server, 1); + server->connect = connect; + server->confirm = confirm; + server->user_data = user_data; + server->destroy = destroy; + + cond = G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL; + g_io_add_watch_full(io, G_PRIORITY_DEFAULT, cond, server_cb, server, + (GDestroyNotify) server_remove); +} + +static void connect_add(GIOChannel *io, BtIOConnect connect, + gpointer user_data, GDestroyNotify destroy) +{ + struct connect *conn; + GIOCondition cond; + + conn = g_new0(struct connect, 1); + conn->connect = connect; + conn->user_data = user_data; + conn->destroy = destroy; + + cond = G_IO_OUT | G_IO_ERR | G_IO_HUP | G_IO_NVAL; + g_io_add_watch_full(io, G_PRIORITY_DEFAULT, cond, connect_cb, conn, + (GDestroyNotify) connect_remove); +} + +static void accept_add(GIOChannel *io, BtIOConnect connect, gpointer user_data, + GDestroyNotify destroy) +{ + struct accept *accept; + GIOCondition cond; + + accept = g_new0(struct accept, 1); + accept->connect = connect; + accept->user_data = user_data; + accept->destroy = destroy; + + cond = G_IO_OUT | G_IO_ERR | G_IO_HUP | G_IO_NVAL; + g_io_add_watch_full(io, G_PRIORITY_DEFAULT, cond, accept_cb, accept, + (GDestroyNotify) accept_remove); +} + +static int l2cap_bind(int sock, const bdaddr_t *src, uint8_t src_type, + uint16_t psm, uint16_t cid, GError **err) +{ + struct sockaddr_l2 addr; + + memset(&addr, 0, sizeof(addr)); + addr.l2_family = AF_BLUETOOTH; + bacpy(&addr.l2_bdaddr, src); + + if (cid) + addr.l2_cid = htobs(cid); + else + addr.l2_psm = htobs(psm); + + addr.l2_bdaddr_type = src_type; + + if (bind(sock, (struct sockaddr *) &addr, sizeof(addr)) < 0) { + int error = -errno; + ERROR_FAILED(err, "l2cap_bind", errno); + return error; + } + + return 0; +} + +static int l2cap_connect(int sock, const bdaddr_t *dst, uint8_t dst_type, + uint16_t psm, uint16_t cid) +{ + int err; + struct sockaddr_l2 addr; + + memset(&addr, 0, sizeof(addr)); + addr.l2_family = AF_BLUETOOTH; + bacpy(&addr.l2_bdaddr, dst); + if (cid) + addr.l2_cid = htobs(cid); + else + addr.l2_psm = htobs(psm); + + addr.l2_bdaddr_type = dst_type; + + err = connect(sock, (struct sockaddr *) &addr, sizeof(addr)); + if (err < 0 && !(errno == EAGAIN || errno == EINPROGRESS)) + return -errno; + + return 0; +} + +static int l2cap_set_master(int sock, int master) +{ + int flags; + socklen_t len; + + len = sizeof(flags); + if (getsockopt(sock, SOL_L2CAP, L2CAP_LM, &flags, &len) < 0) + return -errno; + + if (master) { + if (flags & L2CAP_LM_MASTER) + return 0; + flags |= L2CAP_LM_MASTER; + } else { + if (!(flags & L2CAP_LM_MASTER)) + return 0; + flags &= ~L2CAP_LM_MASTER; + } + + if (setsockopt(sock, SOL_L2CAP, L2CAP_LM, &flags, sizeof(flags)) < 0) + return -errno; + + return 0; +} + +static int l2cap_set_lm(int sock, int level) +{ + int lm_map[] = { + 0, + L2CAP_LM_AUTH, + L2CAP_LM_AUTH | L2CAP_LM_ENCRYPT, + L2CAP_LM_AUTH | L2CAP_LM_ENCRYPT | L2CAP_LM_SECURE, + }, opt = lm_map[level]; + + if (setsockopt(sock, SOL_L2CAP, L2CAP_LM, &opt, sizeof(opt)) < 0) + return -errno; + + return 0; +} + +static gboolean set_sec_level(int sock, BtIOType type, int level, GError **err) +{ + struct bt_security sec; + int ret; + + if (level < BT_SECURITY_LOW || level > BT_SECURITY_HIGH) { + g_set_error(err, BT_IO_ERROR, EINVAL, + "Valid security level range is %d-%d", + BT_SECURITY_LOW, BT_SECURITY_HIGH); + return FALSE; + } + + memset(&sec, 0, sizeof(sec)); + sec.level = level; + + if (setsockopt(sock, SOL_BLUETOOTH, BT_SECURITY, &sec, + sizeof(sec)) == 0) + return TRUE; + + if (errno != ENOPROTOOPT) { + ERROR_FAILED(err, "setsockopt(BT_SECURITY)", errno); + return FALSE; + } + + if (type == BT_IO_L2CAP) { + ERROR_FAILED(err, "unsupported type for Bluetooth LE", EPERM); + return FALSE; + } + ret = l2cap_set_lm(sock, level); + + if (ret < 0) { + ERROR_FAILED(err, "setsockopt(LM)", -ret); + return FALSE; + } + + return TRUE; +} + +static int l2cap_get_lm(int sock, int *sec_level) +{ + int opt; + socklen_t len; + + len = sizeof(opt); + if (getsockopt(sock, SOL_L2CAP, L2CAP_LM, &opt, &len) < 0) + return -errno; + + *sec_level = 0; + + if (opt & L2CAP_LM_AUTH) + *sec_level = BT_SECURITY_LOW; + if (opt & L2CAP_LM_ENCRYPT) + *sec_level = BT_SECURITY_MEDIUM; + if (opt & L2CAP_LM_SECURE) + *sec_level = BT_SECURITY_HIGH; + + return 0; +} + +static gboolean get_sec_level(int sock, BtIOType type, int *level, + GError **err) +{ + struct bt_security sec; + socklen_t len; + int ret; + + memset(&sec, 0, sizeof(sec)); + len = sizeof(sec); + if (getsockopt(sock, SOL_BLUETOOTH, BT_SECURITY, &sec, &len) == 0) { + *level = sec.level; + return TRUE; + } + + if (errno != ENOPROTOOPT) { + ERROR_FAILED(err, "getsockopt(BT_SECURITY)", errno); + return FALSE; + } + + if (type == BT_IO_L2CAP) { + ERROR_FAILED(err, "unsupported type for Bluetooth LE", EPERM); + return FALSE; + } + ret = l2cap_get_lm(sock, level); + + if (ret < 0) { + ERROR_FAILED(err, "getsockopt(LM)", -ret); + return FALSE; + } + + return TRUE; +} + +static int l2cap_set_flushable(int sock, gboolean flushable) +{ + int f; + + f = flushable; + if (setsockopt(sock, SOL_BLUETOOTH, BT_FLUSHABLE, &f, sizeof(f)) < 0) + return -errno; + + return 0; +} + +static int set_priority(int sock, uint32_t prio) +{ + if (setsockopt(sock, SOL_SOCKET, SO_PRIORITY, &prio, sizeof(prio)) < 0) + return -errno; + + return 0; +} + +static gboolean get_key_size(int sock, int *size, GError **err) +{ + struct bt_security sec; + socklen_t len; + + memset(&sec, 0, sizeof(sec)); + len = sizeof(sec); + if (getsockopt(sock, SOL_BLUETOOTH, BT_SECURITY, &sec, &len) == 0) { + *size = sec.key_size; + return TRUE; + } + + return FALSE; +} + +static gboolean set_l2opts(int sock, uint16_t imtu, uint16_t omtu, + uint8_t mode, GError **err) +{ + struct l2cap_options l2o; + socklen_t len; + + memset(&l2o, 0, sizeof(l2o)); + len = sizeof(l2o); + if (getsockopt(sock, SOL_L2CAP, L2CAP_OPTIONS, &l2o, &len) < 0) { + ERROR_FAILED(err, "getsockopt(L2CAP_OPTIONS)", errno); + return FALSE; + } + + if (imtu) + l2o.imtu = imtu; + if (omtu) + l2o.omtu = omtu; + if (mode) + l2o.mode = mode; + + if (setsockopt(sock, SOL_L2CAP, L2CAP_OPTIONS, &l2o, sizeof(l2o)) < 0) { + ERROR_FAILED(err, "setsockopt(L2CAP_OPTIONS)", errno); + return FALSE; + } + + return TRUE; +} + +static gboolean set_le_imtu(int sock, uint16_t imtu, GError **err) +{ + if (setsockopt(sock, SOL_BLUETOOTH, BT_RCVMTU, &imtu, + sizeof(imtu)) < 0) { + ERROR_FAILED(err, "setsockopt(BT_RCVMTU)", errno); + return FALSE; + } + + return TRUE; +} + +static gboolean l2cap_set(int sock, uint8_t src_type, int sec_level, + uint16_t imtu, uint16_t omtu, uint8_t mode, + int master, int flushable, uint32_t priority, + GError **err) +{ + if (imtu || omtu || mode) { + gboolean ret; + + if (src_type == BDADDR_BREDR) + ret = set_l2opts(sock, imtu, omtu, mode, err); + else + ret = set_le_imtu(sock, imtu, err); + + if (!ret) + return ret; + } + + if (master >= 0 && l2cap_set_master(sock, master) < 0) { + ERROR_FAILED(err, "l2cap_set_master", errno); + return FALSE; + } + + if (flushable >= 0 && l2cap_set_flushable(sock, flushable) < 0) { + ERROR_FAILED(err, "l2cap_set_flushable", errno); + return FALSE; + } + + if (priority > 0 && set_priority(sock, priority) < 0) { + ERROR_FAILED(err, "set_priority", errno); + return FALSE; + } + + if (sec_level && !set_sec_level(sock, BT_IO_L2CAP, sec_level, err)) + return FALSE; + + return TRUE; +} + +static gboolean parse_set_opts(struct set_opts *opts, GError **err, + BtIOOption opt1, va_list args) +{ + BtIOOption opt = opt1; + const char *str; + + memset(opts, 0, sizeof(*opts)); + + /* Set defaults */ + opts->type = BT_IO_L2CAP; + opts->defer = DEFAULT_DEFER_TIMEOUT; + opts->master = -1; + opts->mode = L2CAP_MODE_BASIC; + opts->flushable = -1; + opts->priority = 0; + opts->src_type = BDADDR_BREDR; + opts->dst_type = BDADDR_BREDR; + + while (opt != BT_IO_OPT_INVALID) { + switch (opt) { + case BT_IO_OPT_SOURCE: + str = va_arg(args, const char *); + str2ba(str, &opts->src); + break; + case BT_IO_OPT_SOURCE_BDADDR: + bacpy(&opts->src, va_arg(args, const bdaddr_t *)); + break; + case BT_IO_OPT_SOURCE_TYPE: + opts->src_type = va_arg(args, int); + break; + case BT_IO_OPT_DEST: + str2ba(va_arg(args, const char *), &opts->dst); + break; + case BT_IO_OPT_DEST_BDADDR: + bacpy(&opts->dst, va_arg(args, const bdaddr_t *)); + break; + case BT_IO_OPT_DEST_TYPE: + opts->dst_type = va_arg(args, int); + break; + case BT_IO_OPT_DEFER_TIMEOUT: + opts->defer = va_arg(args, int); + break; + case BT_IO_OPT_SEC_LEVEL: + opts->sec_level = va_arg(args, int); + break; + case BT_IO_OPT_CHANNEL: + opts->type = BT_IO_RFCOMM; + opts->channel = va_arg(args, int); + break; + case BT_IO_OPT_PSM: + opts->type = BT_IO_L2CAP; + opts->psm = va_arg(args, int); + break; + case BT_IO_OPT_CID: + opts->type = BT_IO_L2CAP; + opts->cid = va_arg(args, int); + break; + case BT_IO_OPT_MTU: + opts->mtu = va_arg(args, int); + opts->imtu = opts->mtu; + opts->omtu = opts->mtu; + break; + case BT_IO_OPT_OMTU: + opts->omtu = va_arg(args, int); + if (!opts->mtu) + opts->mtu = opts->omtu; + break; + case BT_IO_OPT_IMTU: + opts->imtu = va_arg(args, int); + if (!opts->mtu) + opts->mtu = opts->imtu; + break; + case BT_IO_OPT_MASTER: + opts->master = va_arg(args, gboolean); + break; + case BT_IO_OPT_MODE: + opts->mode = va_arg(args, int); + break; + case BT_IO_OPT_FLUSHABLE: + opts->flushable = va_arg(args, gboolean); + break; + case BT_IO_OPT_PRIORITY: + opts->priority = va_arg(args, int); + break; + case BT_IO_OPT_VOICE: + opts->voice = va_arg(args, int); + break; + default: + g_set_error(err, BT_IO_ERROR, EINVAL, + "Unknown option %d", opt); + return FALSE; + } + + opt = va_arg(args, int); + } + + return TRUE; +} + +static gboolean get_peers(int sock, struct sockaddr *src, struct sockaddr *dst, + socklen_t len, GError **err) +{ + socklen_t olen; + + memset(src, 0, len); + olen = len; + if (getsockname(sock, src, &olen) < 0) { + ERROR_FAILED(err, "getsockname", errno); + return FALSE; + } + + memset(dst, 0, len); + olen = len; + if (getpeername(sock, dst, &olen) < 0) { + ERROR_FAILED(err, "getpeername", errno); + return FALSE; + } + + return TRUE; +} + +static int l2cap_get_info(int sock, uint16_t *handle, uint8_t *dev_class) +{ + struct l2cap_conninfo info; + socklen_t len; + + len = sizeof(info); + if (getsockopt(sock, SOL_L2CAP, L2CAP_CONNINFO, &info, &len) < 0) + return -errno; + + if (handle) + *handle = info.hci_handle; + + if (dev_class) + memcpy(dev_class, info.dev_class, 3); + + return 0; +} + +static int l2cap_get_flushable(int sock, gboolean *flushable) +{ + int f; + socklen_t len; + + f = 0; + len = sizeof(f); + if (getsockopt(sock, SOL_BLUETOOTH, BT_FLUSHABLE, &f, &len) < 0) + return -errno; + + if (f) + *flushable = TRUE; + else + *flushable = FALSE; + + return 0; +} + +static int get_priority(int sock, uint32_t *prio) +{ + socklen_t len; + + len = sizeof(*prio); + if (getsockopt(sock, SOL_SOCKET, SO_PRIORITY, prio, &len) < 0) + return -errno; + + return 0; +} + +static gboolean l2cap_get(int sock, GError **err, BtIOOption opt1, + va_list args) +{ + BtIOOption opt = opt1; + struct sockaddr_l2 src, dst; + struct l2cap_options l2o; + int flags; + uint8_t dev_class[3]; + uint16_t handle; + socklen_t len; + gboolean flushable = FALSE; + uint32_t priority; + + if (!get_peers(sock, (struct sockaddr *) &src, + (struct sockaddr *) &dst, sizeof(src), err)) + return FALSE; + + memset(&l2o, 0, sizeof(l2o)); + + if (src.l2_bdaddr_type != BDADDR_BREDR) { + len = sizeof(l2o.imtu); + if (getsockopt(sock, SOL_BLUETOOTH, BT_RCVMTU, + &l2o.imtu, &len) == 0) + goto parse_opts; + + /* Non-LE CoC enabled kernels will return one of these + * in which case we need to fall back to L2CAP_OPTIONS. + */ + if (errno != EPROTONOSUPPORT && errno != ENOPROTOOPT) { + ERROR_FAILED(err, "getsockopt(BT_RCVMTU)", errno); + return FALSE; + } + } + + len = sizeof(l2o); + if (getsockopt(sock, SOL_L2CAP, L2CAP_OPTIONS, &l2o, &len) < 0) { + ERROR_FAILED(err, "getsockopt(L2CAP_OPTIONS)", errno); + return FALSE; + } + +parse_opts: + while (opt != BT_IO_OPT_INVALID) { + switch (opt) { + case BT_IO_OPT_SOURCE: + ba2str(&src.l2_bdaddr, va_arg(args, char *)); + break; + case BT_IO_OPT_SOURCE_BDADDR: + bacpy(va_arg(args, bdaddr_t *), &src.l2_bdaddr); + break; + case BT_IO_OPT_DEST: + ba2str(&dst.l2_bdaddr, va_arg(args, char *)); + break; + case BT_IO_OPT_DEST_BDADDR: + bacpy(va_arg(args, bdaddr_t *), &dst.l2_bdaddr); + break; + case BT_IO_OPT_DEST_TYPE: + *(va_arg(args, uint8_t *)) = dst.l2_bdaddr_type; + break; + case BT_IO_OPT_DEFER_TIMEOUT: + len = sizeof(int); + if (getsockopt(sock, SOL_BLUETOOTH, BT_DEFER_SETUP, + va_arg(args, int *), &len) < 0) { + ERROR_FAILED(err, "getsockopt(DEFER_SETUP)", + errno); + return FALSE; + } + break; + case BT_IO_OPT_SEC_LEVEL: + if (!get_sec_level(sock, BT_IO_L2CAP, + va_arg(args, int *), err)) + return FALSE; + break; + case BT_IO_OPT_KEY_SIZE: + if (!get_key_size(sock, va_arg(args, int *), err)) + return FALSE; + break; + case BT_IO_OPT_PSM: + *(va_arg(args, uint16_t *)) = src.l2_psm ? + btohs(src.l2_psm) : btohs(dst.l2_psm); + break; + case BT_IO_OPT_CID: + *(va_arg(args, uint16_t *)) = src.l2_cid ? + btohs(src.l2_cid) : btohs(dst.l2_cid); + break; + case BT_IO_OPT_OMTU: + if (src.l2_bdaddr_type == BDADDR_BREDR) { + *(va_arg(args, uint16_t *)) = l2o.omtu; + break; + } + + if (getsockopt(sock, SOL_BLUETOOTH, BT_SNDMTU, + &l2o.omtu, &len) < 0) { + ERROR_FAILED(err, "getsockopt(BT_RCVMTU)", + errno); + return FALSE; + } + + *(va_arg(args, uint16_t *)) = l2o.omtu; + break; + case BT_IO_OPT_IMTU: + *(va_arg(args, uint16_t *)) = l2o.imtu; + break; + case BT_IO_OPT_MASTER: + len = sizeof(flags); + if (getsockopt(sock, SOL_L2CAP, L2CAP_LM, &flags, + &len) < 0) { + ERROR_FAILED(err, "getsockopt(L2CAP_LM)", + errno); + return FALSE; + } + *(va_arg(args, gboolean *)) = + (flags & L2CAP_LM_MASTER) ? TRUE : FALSE; + break; + case BT_IO_OPT_HANDLE: + if (l2cap_get_info(sock, &handle, dev_class) < 0) { + ERROR_FAILED(err, "L2CAP_CONNINFO", errno); + return FALSE; + } + *(va_arg(args, uint16_t *)) = handle; + break; + case BT_IO_OPT_CLASS: + if (l2cap_get_info(sock, &handle, dev_class) < 0) { + ERROR_FAILED(err, "L2CAP_CONNINFO", errno); + return FALSE; + } + memcpy(va_arg(args, uint8_t *), dev_class, 3); + break; + case BT_IO_OPT_MODE: + *(va_arg(args, uint8_t *)) = l2o.mode; + break; + case BT_IO_OPT_FLUSHABLE: + if (l2cap_get_flushable(sock, &flushable) < 0) { + ERROR_FAILED(err, "get_flushable", errno); + return FALSE; + } + *(va_arg(args, gboolean *)) = flushable; + break; + case BT_IO_OPT_PRIORITY: + if (get_priority(sock, &priority) < 0) { + ERROR_FAILED(err, "get_priority", errno); + return FALSE; + } + *(va_arg(args, uint32_t *)) = priority; + break; + default: + g_set_error(err, BT_IO_ERROR, EINVAL, + "Unknown option %d", opt); + return FALSE; + } + + opt = va_arg(args, int); + } + + return TRUE; +} + +static gboolean get_valist(GIOChannel *io, BtIOType type, GError **err, + BtIOOption opt1, va_list args) +{ + int sock; + + sock = g_io_channel_unix_get_fd(io); + + switch (type) { + case BT_IO_L2CAP: + return l2cap_get(sock, err, opt1, args); + case BT_IO_SCO: + case BT_IO_RFCOMM: + g_set_error(err, BT_IO_ERROR, EINVAL, + "Unsupported BtIO type %d for Bluetooth LE", type); + return FALSE; + default: + g_set_error(err, BT_IO_ERROR, EINVAL, + "Unknown BtIO type %d", type); + return FALSE; + } +} + +gboolean bt_io_accept(GIOChannel *io, BtIOConnect connect, gpointer user_data, + GDestroyNotify destroy, GError **err) +{ + int sock; + char c; + struct pollfd pfd; + + sock = g_io_channel_unix_get_fd(io); + + memset(&pfd, 0, sizeof(pfd)); + pfd.fd = sock; + pfd.events = POLLOUT; + + if (poll(&pfd, 1, 0) < 0) { + ERROR_FAILED(err, "poll", errno); + return FALSE; + } + + if (!(pfd.revents & POLLOUT)) { + if (read(sock, &c, 1) < 0) { + ERROR_FAILED(err, "read", errno); + return FALSE; + } + } + + accept_add(io, connect, user_data, destroy); + + return TRUE; +} + +gboolean bt_io_set(GIOChannel *io, GError **err, BtIOOption opt1, ...) +{ + va_list args; + gboolean ret; + struct set_opts opts; + int sock; + BtIOType type; + + va_start(args, opt1); + ret = parse_set_opts(&opts, err, opt1, args); + va_end(args); + + if (!ret) + return ret; + + type = bt_io_get_type(io, err); + if (type == BT_IO_INVALID) + return FALSE; + + sock = g_io_channel_unix_get_fd(io); + + switch (type) { + case BT_IO_L2CAP: + return l2cap_set(sock, opts.src_type, opts.sec_level, opts.imtu, + opts.omtu, opts.mode, opts.master, + opts.flushable, opts.priority, err); + case BT_IO_SCO: + case BT_IO_RFCOMM: + g_set_error(err, BT_IO_ERROR, EINVAL, + "Unsupported BtIO type %d for Bluetooth LE", type); + return FALSE; + default: + g_set_error(err, BT_IO_ERROR, EINVAL, + "Unknown BtIO type %d", type); + return FALSE; + } + +} + +gboolean bt_io_get(GIOChannel *io, GError **err, BtIOOption opt1, ...) +{ + va_list args; + gboolean ret; + BtIOType type; + + type = bt_io_get_type(io, err); + if (type == BT_IO_INVALID) + return FALSE; + + va_start(args, opt1); + ret = get_valist(io, type, err, opt1, args); + va_end(args); + + return ret; +} + +static GIOChannel *create_io(gboolean server, struct set_opts *opts, + GError **err) +{ + int sock; + GIOChannel *io; + + switch (opts->type) { + case BT_IO_L2CAP: + sock = socket(PF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_L2CAP); + if (sock < 0) { + ERROR_FAILED(err, "socket(SEQPACKET, L2CAP)", errno); + return NULL; + } + if (l2cap_bind(sock, &opts->src, opts->src_type, + server ? opts->psm : 0, opts->cid, err) < 0) + goto failed; + if (!l2cap_set(sock, opts->src_type, opts->sec_level, + opts->imtu, opts->omtu, opts->mode, + opts->master, opts->flushable, opts->priority, + err)) + goto failed; + break; + case BT_IO_SCO: + case BT_IO_RFCOMM: + g_set_error(err, BT_IO_ERROR, EINVAL, + "Unsupported BtIO type %d for Bluetooth LE", opts->type); + return NULL; + default: + g_set_error(err, BT_IO_ERROR, EINVAL, + "Unknown BtIO type %d", opts->type); + return NULL; + } + + io = g_io_channel_unix_new(sock); + + g_io_channel_set_close_on_unref(io, TRUE); + g_io_channel_set_flags(io, G_IO_FLAG_NONBLOCK, NULL); + + return io; + +failed: + close(sock); + + return NULL; +} + +GIOChannel *bt_io_connect(BtIOConnect connect, gpointer user_data, + GDestroyNotify destroy, GError **gerr, + BtIOOption opt1, ...) +{ + GIOChannel *io; + va_list args; + struct set_opts opts; + int err, sock; + gboolean ret; + + va_start(args, opt1); + ret = parse_set_opts(&opts, gerr, opt1, args); + va_end(args); + + if (ret == FALSE) + return NULL; + + io = create_io(FALSE, &opts, gerr); + if (io == NULL) + return NULL; + + sock = g_io_channel_unix_get_fd(io); + + switch (opts.type) { + case BT_IO_L2CAP: + err = l2cap_connect(sock, &opts.dst, opts.dst_type, + opts.psm, opts.cid); + break; + case BT_IO_SCO: + case BT_IO_RFCOMM: + g_set_error(gerr, BT_IO_ERROR, EINVAL, + "Unsupported BtIO type %d for Bluetooth LE", opts.type); + return NULL; + default: + g_set_error(gerr, BT_IO_ERROR, EINVAL, + "Unknown BtIO type %d", opts.type); + return NULL; + } + + if (err < 0) { + ERROR_FAILED(gerr, "connect", -err); + g_io_channel_unref(io); + return NULL; + } + + connect_add(io, connect, user_data, destroy); + + return io; +} + +GIOChannel *bt_io_listen(BtIOConnect connect, BtIOConfirm confirm, + gpointer user_data, GDestroyNotify destroy, + GError **err, BtIOOption opt1, ...) +{ + GIOChannel *io; + va_list args; + struct set_opts opts; + int sock; + gboolean ret; + + va_start(args, opt1); + ret = parse_set_opts(&opts, err, opt1, args); + va_end(args); + + if (ret == FALSE) + return NULL; + + io = create_io(TRUE, &opts, err); + if (io == NULL) + return NULL; + + sock = g_io_channel_unix_get_fd(io); + + if (confirm) + setsockopt(sock, SOL_BLUETOOTH, BT_DEFER_SETUP, &opts.defer, + sizeof(opts.defer)); + + if (listen(sock, 5) < 0) { + ERROR_FAILED(err, "listen", errno); + g_io_channel_unref(io); + return NULL; + } + + server_add(io, connect, confirm, user_data, destroy); + + return io; +} + +GQuark bt_io_error_quark(void) +{ + return g_quark_from_static_string("bt-io-error-quark"); +} diff --git a/drive-sdk/deps/bzle/src/gatt.c b/drive-sdk/deps/bzle/src/gatt.c new file mode 100644 index 0000000..3c0fab0 --- /dev/null +++ b/drive-sdk/deps/bzle/src/gatt.c @@ -0,0 +1,929 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2010 Nokia Corporation + * Copyright (C) 2010 Marcel Holtmann + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +struct discover_primary { + GAttrib *attrib; + bt_uuid_t uuid; + GSList *primaries; + gatt_cb_t cb; + void *user_data; +}; + +/* Used for the Included Services Discovery (ISD) procedure */ +struct included_discovery { + GAttrib *attrib; + int refs; + int err; + uint16_t end_handle; + GSList *includes; + gatt_cb_t cb; + void *user_data; +}; + +struct included_uuid_query { + struct included_discovery *isd; + struct gatt_included *included; +}; + +struct discover_char { + GAttrib *attrib; + bt_uuid_t *uuid; + uint16_t end; + GSList *characteristics; + gatt_cb_t cb; + void *user_data; +}; + +static void discover_primary_free(struct discover_primary *dp) +{ + g_slist_free(dp->primaries); + g_attrib_unref(dp->attrib); + g_free(dp); +} + +static struct included_discovery *isd_ref(struct included_discovery *isd) +{ + __sync_fetch_and_add(&isd->refs, 1); + + return isd; +} + +static void isd_unref(struct included_discovery *isd) +{ + if (__sync_sub_and_fetch(&isd->refs, 1) > 0) + return; + + if (isd->err) + isd->cb(isd->err, NULL, isd->user_data); + else + isd->cb(isd->err, isd->includes, isd->user_data); + + g_slist_free_full(isd->includes, g_free); + g_attrib_unref(isd->attrib); + g_free(isd); +} + +static void discover_char_free(struct discover_char *dc) +{ + g_slist_free_full(dc->characteristics, g_free); + g_attrib_unref(dc->attrib); + g_free(dc->uuid); + g_free(dc); +} + +static guint16 encode_discover_primary(uint16_t start, uint16_t end, + bt_uuid_t *uuid, uint8_t *pdu, size_t len) +{ + bt_uuid_t prim; + guint16 plen; + + bt_uuid16_create(&prim, GATT_PRIM_SVC_UUID); + + if (uuid == NULL) { + /* Discover all primary services */ + plen = enc_read_by_grp_req(start, end, &prim, pdu, len); + } else { + uint16_t u16; + uint128_t u128; + const void *value; + size_t vlen; + + /* Discover primary service by service UUID */ + + if (uuid->type == BT_UUID16) { + u16 = htobs(uuid->value.u16); + value = &u16; + vlen = sizeof(u16); + } else { + htob128(&uuid->value.u128, &u128); + value = &u128; + vlen = sizeof(u128); + } + + plen = enc_find_by_type_req(start, end, &prim, value, vlen, + pdu, len); + } + + return plen; +} + +static void primary_by_uuid_cb(guint8 status, const guint8 *ipdu, + guint16 iplen, gpointer user_data) + +{ + struct discover_primary *dp = user_data; + GSList *ranges, *last; + struct att_range *range; + uint8_t *buf; + guint16 oplen; + int err = 0; + size_t buflen; + + if (status) { + err = status == ATT_ECODE_ATTR_NOT_FOUND ? 0 : status; + goto done; + } + + ranges = dec_find_by_type_resp(ipdu, iplen); + if (ranges == NULL) + goto done; + + dp->primaries = g_slist_concat(dp->primaries, ranges); + + last = g_slist_last(ranges); + range = last->data; + + if (range->end == 0xffff) + goto done; + + buf = g_attrib_get_buffer(dp->attrib, &buflen); + oplen = encode_discover_primary(range->end + 1, 0xffff, &dp->uuid, + buf, buflen); + + if (oplen == 0) + goto done; + + g_attrib_send(dp->attrib, 0, buf, oplen, primary_by_uuid_cb, dp, NULL); + return; + +done: + dp->cb(err, dp->primaries, dp->user_data); + discover_primary_free(dp); +} + +static void primary_all_cb(guint8 status, const guint8 *ipdu, guint16 iplen, + gpointer user_data) +{ + struct discover_primary *dp = user_data; + struct att_data_list *list; + unsigned int i, err; + uint16_t start, end; + + if (status) { + err = status == ATT_ECODE_ATTR_NOT_FOUND ? 0 : status; + goto done; + } + + list = dec_read_by_grp_resp(ipdu, iplen); + if (list == NULL) { + err = ATT_ECODE_IO; + goto done; + } + + for (i = 0, end = 0; i < list->num; i++) { + const uint8_t *data = list->data[i]; + struct gatt_primary *primary; + bt_uuid_t uuid; + + start = att_get_u16(&data[0]); + end = att_get_u16(&data[2]); + + if (list->len == 6) { + bt_uuid_t uuid16 = att_get_uuid16(&data[4]); + bt_uuid_to_uuid128(&uuid16, &uuid); + } else if (list->len == 20) { + uuid = att_get_uuid128(&data[4]); + } else { + /* Skipping invalid data */ + continue; + } + + primary = g_try_new0(struct gatt_primary, 1); + if (!primary) { + att_data_list_free(list); + err = ATT_ECODE_INSUFF_RESOURCES; + goto done; + } + primary->range.start = start; + primary->range.end = end; + bt_uuid_to_string(&uuid, primary->uuid, sizeof(primary->uuid)); + dp->primaries = g_slist_append(dp->primaries, primary); + } + + att_data_list_free(list); + err = 0; + + if (end != 0xffff) { + size_t buflen; + uint8_t *buf = g_attrib_get_buffer(dp->attrib, &buflen); + guint16 oplen = encode_discover_primary(end + 1, 0xffff, NULL, + buf, buflen); + + g_attrib_send(dp->attrib, 0, buf, oplen, primary_all_cb, + dp, NULL); + + return; + } + +done: + dp->cb(err, dp->primaries, dp->user_data); + discover_primary_free(dp); +} + +guint gatt_discover_primary(GAttrib *attrib, bt_uuid_t *uuid, gatt_cb_t func, + gpointer user_data) +{ + struct discover_primary *dp; + size_t buflen; + uint8_t *buf = g_attrib_get_buffer(attrib, &buflen); + GAttribResultFunc cb; + guint16 plen; + + plen = encode_discover_primary(0x0001, 0xffff, uuid, buf, buflen); + if (plen == 0) + return 0; + + dp = g_try_new0(struct discover_primary, 1); + if (dp == NULL) + return 0; + + dp->attrib = g_attrib_ref(attrib); + dp->cb = func; + dp->user_data = user_data; + + if (uuid) { + dp->uuid = *uuid; + cb = primary_by_uuid_cb; + } else + cb = primary_all_cb; + + return g_attrib_send(attrib, 0, buf, plen, cb, dp, NULL); +} + +static void resolve_included_uuid_cb(uint8_t status, const uint8_t *pdu, + uint16_t len, gpointer user_data) +{ + struct included_uuid_query *query = user_data; + struct included_discovery *isd = query->isd; + struct gatt_included *incl = query->included; + unsigned int err = status; + bt_uuid_t uuid; + size_t buflen; + uint8_t *buf; + + if (err) + goto done; + + buf = g_attrib_get_buffer(isd->attrib, &buflen); + if (dec_read_resp(pdu, len, buf, buflen) != 16) { + err = ATT_ECODE_IO; + goto done; + } + + uuid = att_get_uuid128(buf); + bt_uuid_to_string(&uuid, incl->uuid, sizeof(incl->uuid)); + isd->includes = g_slist_append(isd->includes, incl); + +done: + if (err) + g_free(incl); + + if (isd->err == 0) + isd->err = err; + + isd_unref(isd); + + g_free(query); +} + +static guint resolve_included_uuid(struct included_discovery *isd, + struct gatt_included *incl) +{ + struct included_uuid_query *query; + size_t buflen; + uint8_t *buf = g_attrib_get_buffer(isd->attrib, &buflen); + guint16 oplen = enc_read_req(incl->range.start, buf, buflen); + + query = g_new0(struct included_uuid_query, 1); + query->isd = isd_ref(isd); + query->included = incl; + + return g_attrib_send(isd->attrib, 0, buf, oplen, + resolve_included_uuid_cb, query, NULL); +} + +static struct gatt_included *included_from_buf(const uint8_t *buf, gsize len) +{ + struct gatt_included *incl = g_new0(struct gatt_included, 1); + + incl->handle = att_get_u16(&buf[0]); + incl->range.start = att_get_u16(&buf[2]); + incl->range.end = att_get_u16(&buf[4]); + + if (len == 8) { + bt_uuid_t uuid128; + bt_uuid_t uuid16 = att_get_uuid16(&buf[6]); + + bt_uuid_to_uuid128(&uuid16, &uuid128); + bt_uuid_to_string(&uuid128, incl->uuid, sizeof(incl->uuid)); + } + + return incl; +} + +static void find_included_cb(uint8_t status, const uint8_t *pdu, uint16_t len, + gpointer user_data); + +static guint find_included(struct included_discovery *isd, uint16_t start) +{ + bt_uuid_t uuid; + size_t buflen; + uint8_t *buf = g_attrib_get_buffer(isd->attrib, &buflen); + guint16 oplen; + + bt_uuid16_create(&uuid, GATT_INCLUDE_UUID); + oplen = enc_read_by_type_req(start, isd->end_handle, &uuid, + buf, buflen); + + return g_attrib_send(isd->attrib, 0, buf, oplen, find_included_cb, + isd_ref(isd), (GDestroyNotify) isd_unref); +} + +static void find_included_cb(uint8_t status, const uint8_t *pdu, uint16_t len, + gpointer user_data) +{ + struct included_discovery *isd = user_data; + uint16_t last_handle = isd->end_handle; + unsigned int err = status; + struct att_data_list *list; + int i; + + if (err == ATT_ECODE_ATTR_NOT_FOUND) + err = 0; + + if (status) + goto done; + + list = dec_read_by_type_resp(pdu, len); + if (list == NULL) { + err = ATT_ECODE_IO; + goto done; + } + + if (list->len != 6 && list->len != 8) { + err = ATT_ECODE_IO; + att_data_list_free(list); + goto done; + } + + for (i = 0; i < list->num; i++) { + struct gatt_included *incl; + + incl = included_from_buf(list->data[i], list->len); + last_handle = incl->handle; + + /* 128 bit UUID, needs resolving */ + if (list->len == 6) { + resolve_included_uuid(isd, incl); + continue; + } + + isd->includes = g_slist_append(isd->includes, incl); + } + + att_data_list_free(list); + + if (last_handle < isd->end_handle) + find_included(isd, last_handle + 1); + +done: + if (isd->err == 0) + isd->err = err; +} + +unsigned int gatt_find_included(GAttrib *attrib, uint16_t start, uint16_t end, + gatt_cb_t func, gpointer user_data) +{ + struct included_discovery *isd; + + isd = g_new0(struct included_discovery, 1); + isd->attrib = g_attrib_ref(attrib); + isd->end_handle = end; + isd->cb = func; + isd->user_data = user_data; + + return find_included(isd, start); +} + +static void char_discovered_cb(guint8 status, const guint8 *ipdu, guint16 iplen, + gpointer user_data) +{ + struct discover_char *dc = user_data; + struct att_data_list *list; + unsigned int i, err = ATT_ECODE_ATTR_NOT_FOUND; + uint16_t last = 0; + + if (status) { + err = status; + goto done; + } + + list = dec_read_by_type_resp(ipdu, iplen); + if (list == NULL) { + err = ATT_ECODE_IO; + goto done; + } + + for (i = 0; i < list->num; i++) { + uint8_t *value = list->data[i]; + struct gatt_char *chars; + bt_uuid_t uuid; + + last = att_get_u16(value); + + if (list->len == 7) { + bt_uuid_t uuid16 = att_get_uuid16(&value[5]); + bt_uuid_to_uuid128(&uuid16, &uuid); + } else + uuid = att_get_uuid128(&value[5]); + + if (dc->uuid && bt_uuid_cmp(dc->uuid, &uuid)) + continue; + + chars = g_try_new0(struct gatt_char, 1); + if (!chars) { + err = ATT_ECODE_INSUFF_RESOURCES; + goto done; + } + + chars->handle = last; + chars->properties = value[2]; + chars->value_handle = att_get_u16(&value[3]); + bt_uuid_to_string(&uuid, chars->uuid, sizeof(chars->uuid)); + dc->characteristics = g_slist_append(dc->characteristics, + chars); + } + + att_data_list_free(list); + + if (last != 0 && (last + 1 < dc->end)) { + bt_uuid_t uuid; + guint16 oplen; + size_t buflen; + uint8_t *buf; + + buf = g_attrib_get_buffer(dc->attrib, &buflen); + + bt_uuid16_create(&uuid, GATT_CHARAC_UUID); + + oplen = enc_read_by_type_req(last + 1, dc->end, &uuid, buf, + buflen); + + if (oplen == 0) + return; + + g_attrib_send(dc->attrib, 0, buf, oplen, char_discovered_cb, + dc, NULL); + + return; + } + +done: + err = (dc->characteristics ? 0 : err); + + dc->cb(err, dc->characteristics, dc->user_data); + discover_char_free(dc); +} + +guint gatt_discover_char(GAttrib *attrib, uint16_t start, uint16_t end, + bt_uuid_t *uuid, gatt_cb_t func, + gpointer user_data) +{ + size_t buflen; + uint8_t *buf = g_attrib_get_buffer(attrib, &buflen); + struct discover_char *dc; + bt_uuid_t type_uuid; + guint16 plen; + + bt_uuid16_create(&type_uuid, GATT_CHARAC_UUID); + + plen = enc_read_by_type_req(start, end, &type_uuid, buf, buflen); + if (plen == 0) + return 0; + + dc = g_try_new0(struct discover_char, 1); + if (dc == NULL) + return 0; + + dc->attrib = g_attrib_ref(attrib); + dc->cb = func; + dc->user_data = user_data; + dc->end = end; + dc->uuid = g_memdup(uuid, sizeof(bt_uuid_t)); + + return g_attrib_send(attrib, 0, buf, plen, char_discovered_cb, + dc, NULL); +} + +guint gatt_read_char_by_uuid(GAttrib *attrib, uint16_t start, uint16_t end, + bt_uuid_t *uuid, GAttribResultFunc func, + gpointer user_data) +{ + size_t buflen; + uint8_t *buf = g_attrib_get_buffer(attrib, &buflen); + guint16 plen; + + plen = enc_read_by_type_req(start, end, uuid, buf, buflen); + if (plen == 0) + return 0; + + return g_attrib_send(attrib, 0, buf, plen, func, user_data, NULL); +} + +struct read_long_data { + GAttrib *attrib; + GAttribResultFunc func; + gpointer user_data; + guint8 *buffer; + guint16 size; + guint16 handle; + guint id; + int ref; +}; + +static void read_long_destroy(gpointer user_data) +{ + struct read_long_data *long_read = user_data; + + if (__sync_sub_and_fetch(&long_read->ref, 1) > 0) + return; + + if (long_read->buffer != NULL) + g_free(long_read->buffer); + + g_free(long_read); +} + +static void read_blob_helper(guint8 status, const guint8 *rpdu, guint16 rlen, + gpointer user_data) +{ + struct read_long_data *long_read = user_data; + uint8_t *buf; + size_t buflen; + guint8 *tmp; + guint16 plen; + guint id; + + if (status != 0 || rlen == 1) { + status = 0; + goto done; + } + + tmp = g_try_realloc(long_read->buffer, long_read->size + rlen - 1); + + if (tmp == NULL) { + status = ATT_ECODE_INSUFF_RESOURCES; + goto done; + } + + memcpy(&tmp[long_read->size], &rpdu[1], rlen - 1); + long_read->buffer = tmp; + long_read->size += rlen - 1; + + buf = g_attrib_get_buffer(long_read->attrib, &buflen); + if (rlen < buflen) + goto done; + + plen = enc_read_blob_req(long_read->handle, long_read->size - 1, + buf, buflen); + id = g_attrib_send(long_read->attrib, long_read->id, buf, plen, + read_blob_helper, long_read, read_long_destroy); + + if (id != 0) { + __sync_fetch_and_add(&long_read->ref, 1); + return; + } + + status = ATT_ECODE_IO; + +done: + long_read->func(status, long_read->buffer, long_read->size, + long_read->user_data); +} + +static void read_char_helper(guint8 status, const guint8 *rpdu, + guint16 rlen, gpointer user_data) +{ + struct read_long_data *long_read = user_data; + size_t buflen; + uint8_t *buf = g_attrib_get_buffer(long_read->attrib, &buflen); + guint16 plen; + guint id; + + if (status != 0 || rlen < buflen) + goto done; + + long_read->buffer = g_malloc(rlen); + if (long_read->buffer == NULL) { + status = ATT_ECODE_INSUFF_RESOURCES; + goto done; + } + + memcpy(long_read->buffer, rpdu, rlen); + long_read->size = rlen; + + plen = enc_read_blob_req(long_read->handle, rlen - 1, buf, buflen); + + id = g_attrib_send(long_read->attrib, long_read->id, buf, plen, + read_blob_helper, long_read, read_long_destroy); + if (id != 0) { + __sync_fetch_and_add(&long_read->ref, 1); + return; + } + + status = ATT_ECODE_IO; + +done: + long_read->func(status, rpdu, rlen, long_read->user_data); +} + +guint gatt_read_char(GAttrib *attrib, uint16_t handle, GAttribResultFunc func, + gpointer user_data) +{ + uint8_t *buf; + size_t buflen; + guint16 plen; + guint id; + struct read_long_data *long_read; + + long_read = g_try_new0(struct read_long_data, 1); + + if (long_read == NULL) + return 0; + + long_read->attrib = attrib; + long_read->func = func; + long_read->user_data = user_data; + long_read->handle = handle; + + buf = g_attrib_get_buffer(attrib, &buflen); + plen = enc_read_req(handle, buf, buflen); + id = g_attrib_send(attrib, 0, buf, plen, read_char_helper, + long_read, read_long_destroy); + if (id == 0) + g_free(long_read); + else { + __sync_fetch_and_add(&long_read->ref, 1); + long_read->id = id; + } + + return id; +} + +struct write_long_data { + GAttrib *attrib; + GAttribResultFunc func; + gpointer user_data; + guint16 handle; + uint16_t offset; + uint8_t *value; + size_t vlen; +}; + +static guint execute_write(GAttrib *attrib, uint8_t flags, + GAttribResultFunc func, gpointer user_data) +{ + uint8_t *buf; + size_t buflen; + guint16 plen; + + buf = g_attrib_get_buffer(attrib, &buflen); + plen = enc_exec_write_req(flags, buf, buflen); + if (plen == 0) + return 0; + + return g_attrib_send(attrib, 0, buf, plen, func, user_data, NULL); +} + +static guint prepare_write(struct write_long_data *long_write); + +static void prepare_write_cb(guint8 status, const guint8 *rpdu, guint16 rlen, + gpointer user_data) +{ + struct write_long_data *long_write = user_data; + + if (status != 0) { + long_write->func(status, rpdu, rlen, long_write->user_data); + return; + } + + /* Skip Prepare Write Response PDU header (5 bytes) */ + long_write->offset += rlen - 5; + + if (long_write->offset == long_write->vlen) { + execute_write(long_write->attrib, ATT_WRITE_ALL_PREP_WRITES, + long_write->func, long_write->user_data); + g_free(long_write->value); + g_free(long_write); + + return; + } + + prepare_write(long_write); +} + +static guint prepare_write(struct write_long_data *long_write) +{ + GAttrib *attrib = long_write->attrib; + uint16_t handle = long_write->handle; + uint16_t offset = long_write->offset; + uint8_t *buf, *value = long_write->value + offset; + size_t buflen, vlen = long_write->vlen - offset; + guint16 plen; + + buf = g_attrib_get_buffer(attrib, &buflen); + + plen = enc_prep_write_req(handle, offset, value, vlen, buf, buflen); + if (plen == 0) + return 0; + + return g_attrib_send(attrib, 0, buf, plen, prepare_write_cb, long_write, + NULL); +} + +guint gatt_write_char(GAttrib *attrib, uint16_t handle, uint8_t *value, + size_t vlen, GAttribResultFunc func, gpointer user_data) +{ + uint8_t *buf; + size_t buflen; + struct write_long_data *long_write; + + buf = g_attrib_get_buffer(attrib, &buflen); + + /* Use Write Request if payload fits on a single transfer, including 3 + * bytes for the header. */ + if (vlen <= buflen - 3) { + uint16_t plen; + + plen = enc_write_req(handle, value, vlen, buf, buflen); + if (plen == 0) + return 0; + + return g_attrib_send(attrib, 0, buf, plen, func, user_data, + NULL); + } + + /* Write Long Characteristic Values */ + long_write = g_try_new0(struct write_long_data, 1); + if (long_write == NULL) + return 0; + + long_write->attrib = attrib; + long_write->func = func; + long_write->user_data = user_data; + long_write->handle = handle; + long_write->value = g_memdup(value, vlen); + long_write->vlen = vlen; + + return prepare_write(long_write); +} + +guint gatt_exchange_mtu(GAttrib *attrib, uint16_t mtu, GAttribResultFunc func, + gpointer user_data) +{ + uint8_t *buf; + size_t buflen; + guint16 plen; + + buf = g_attrib_get_buffer(attrib, &buflen); + plen = enc_mtu_req(mtu, buf, buflen); + return g_attrib_send(attrib, 0, buf, plen, func, user_data, NULL); +} + +guint gatt_discover_char_desc(GAttrib *attrib, uint16_t start, uint16_t end, + GAttribResultFunc func, gpointer user_data) +{ + uint8_t *buf; + size_t buflen; + guint16 plen; + + buf = g_attrib_get_buffer(attrib, &buflen); + plen = enc_find_info_req(start, end, buf, buflen); + if (plen == 0) + return 0; + + return g_attrib_send(attrib, 0, buf, plen, func, user_data, NULL); +} + +guint gatt_write_cmd(GAttrib *attrib, uint16_t handle, uint8_t *value, int vlen, + GDestroyNotify notify, gpointer user_data) +{ + uint8_t *buf; + size_t buflen; + guint16 plen; + + buf = g_attrib_get_buffer(attrib, &buflen); + plen = enc_write_cmd(handle, value, vlen, buf, buflen); + return g_attrib_send(attrib, 0, buf, plen, NULL, user_data, notify); +} + +static sdp_data_t *proto_seq_find(sdp_list_t *proto_list) +{ + sdp_list_t *list; + uuid_t proto; + + sdp_uuid16_create(&proto, ATT_UUID); + + for (list = proto_list; list; list = list->next) { + sdp_list_t *p; + for (p = list->data; p; p = p->next) { + sdp_data_t *seq = p->data; + if (seq && seq->dtd == SDP_UUID16 && + sdp_uuid16_cmp(&proto, &seq->val.uuid) == 0) + return seq->next; + } + } + + return NULL; +} + +static gboolean parse_proto_params(sdp_list_t *proto_list, uint16_t *psm, + uint16_t *start, uint16_t *end) +{ + sdp_data_t *seq1, *seq2; + + if (psm) + *psm = sdp_get_proto_port(proto_list, L2CAP_UUID); + + /* Getting start and end handle */ + seq1 = proto_seq_find(proto_list); + if (!seq1 || seq1->dtd != SDP_UINT16) + return FALSE; + + seq2 = seq1->next; + if (!seq2 || seq2->dtd != SDP_UINT16) + return FALSE; + + if (start) + *start = seq1->val.uint16; + + if (end) + *end = seq2->val.uint16; + + return TRUE; +} + +gboolean gatt_parse_record(const sdp_record_t *rec, + uuid_t *prim_uuid, uint16_t *psm, + uint16_t *start, uint16_t *end) +{ + sdp_list_t *list; + uuid_t uuid; + gboolean ret; + + if (sdp_get_service_classes(rec, &list) < 0) + return FALSE; + + memcpy(&uuid, list->data, sizeof(uuid)); + sdp_list_free(list, free); + + if (sdp_get_access_protos(rec, &list) < 0) + return FALSE; + + ret = parse_proto_params(list, psm, start, end); + + sdp_list_foreach(list, (sdp_list_func_t) sdp_list_free, NULL); + sdp_list_free(list, NULL); + + /* FIXME: replace by bt_uuid_t after uuid_t/sdp code cleanup */ + if (ret && prim_uuid) + memcpy(prim_uuid, &uuid, sizeof(uuid_t)); + + return ret; +} diff --git a/drive-sdk/deps/bzle/src/gattrib.c b/drive-sdk/deps/bzle/src/gattrib.c new file mode 100644 index 0000000..f865956 --- /dev/null +++ b/drive-sdk/deps/bzle/src/gattrib.c @@ -0,0 +1,763 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2010 Nokia Corporation + * Copyright (C) 2010 Marcel Holtmann + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include +#include +#include + +#include + +#include + +#include +#include +#include +#include + +#include "log.h" + +#define GATT_TIMEOUT 30 + +struct _GAttrib { + GIOChannel *io; + int refs; + uint8_t *buf; + size_t buflen; + guint read_watch; + guint write_watch; + guint timeout_watch; + GQueue *requests; + GQueue *responses; + GSList *events; + guint next_cmd_id; + GDestroyNotify destroy; + gpointer destroy_user_data; + bool stale; +}; + +struct command { + guint id; + guint8 opcode; + guint8 *pdu; + guint16 len; + guint8 expected; + bool sent; + GAttribResultFunc func; + gpointer user_data; + GDestroyNotify notify; +}; + +struct event { + guint id; + guint8 expected; + guint16 handle; + GAttribNotifyFunc func; + gpointer user_data; + GDestroyNotify notify; +}; + +static guint8 opcode2expected(guint8 opcode) +{ + switch (opcode) { + case ATT_OP_MTU_REQ: + return ATT_OP_MTU_RESP; + + case ATT_OP_FIND_INFO_REQ: + return ATT_OP_FIND_INFO_RESP; + + case ATT_OP_FIND_BY_TYPE_REQ: + return ATT_OP_FIND_BY_TYPE_RESP; + + case ATT_OP_READ_BY_TYPE_REQ: + return ATT_OP_READ_BY_TYPE_RESP; + + case ATT_OP_READ_REQ: + return ATT_OP_READ_RESP; + + case ATT_OP_READ_BLOB_REQ: + return ATT_OP_READ_BLOB_RESP; + + case ATT_OP_READ_MULTI_REQ: + return ATT_OP_READ_MULTI_RESP; + + case ATT_OP_READ_BY_GROUP_REQ: + return ATT_OP_READ_BY_GROUP_RESP; + + case ATT_OP_WRITE_REQ: + return ATT_OP_WRITE_RESP; + + case ATT_OP_PREP_WRITE_REQ: + return ATT_OP_PREP_WRITE_RESP; + + case ATT_OP_EXEC_WRITE_REQ: + return ATT_OP_EXEC_WRITE_RESP; + + case ATT_OP_HANDLE_IND: + return ATT_OP_HANDLE_CNF; + } + + return 0; +} + +static bool is_response(guint8 opcode) +{ + switch (opcode) { + case ATT_OP_ERROR: + case ATT_OP_MTU_RESP: + case ATT_OP_FIND_INFO_RESP: + case ATT_OP_FIND_BY_TYPE_RESP: + case ATT_OP_READ_BY_TYPE_RESP: + case ATT_OP_READ_RESP: + case ATT_OP_READ_BLOB_RESP: + case ATT_OP_READ_MULTI_RESP: + case ATT_OP_READ_BY_GROUP_RESP: + case ATT_OP_WRITE_RESP: + case ATT_OP_PREP_WRITE_RESP: + case ATT_OP_EXEC_WRITE_RESP: + case ATT_OP_HANDLE_CNF: + return true; + } + + return false; +} + +GAttrib *g_attrib_ref(GAttrib *attrib) +{ + int refs; + + if (!attrib) + return NULL; + + refs = __sync_add_and_fetch(&attrib->refs, 1); + + DBG("%p: ref=%d", attrib, refs); + + return attrib; +} + +static void command_destroy(struct command *cmd) +{ + if (cmd->notify) + cmd->notify(cmd->user_data); + + g_free(cmd->pdu); + g_free(cmd); +} + +static void event_destroy(struct event *evt) +{ + if (evt->notify) + evt->notify(evt->user_data); + + g_free(evt); +} + +static void attrib_destroy(GAttrib *attrib) +{ + GSList *l; + struct command *c; + + while ((c = g_queue_pop_head(attrib->requests))) + command_destroy(c); + + while ((c = g_queue_pop_head(attrib->responses))) + command_destroy(c); + + g_queue_free(attrib->requests); + attrib->requests = NULL; + + g_queue_free(attrib->responses); + attrib->responses = NULL; + + for (l = attrib->events; l; l = l->next) + event_destroy(l->data); + + g_slist_free(attrib->events); + attrib->events = NULL; + + if (attrib->timeout_watch > 0) + g_source_remove(attrib->timeout_watch); + + if (attrib->write_watch > 0) + g_source_remove(attrib->write_watch); + + if (attrib->read_watch > 0) + g_source_remove(attrib->read_watch); + + if (attrib->io) + g_io_channel_unref(attrib->io); + + g_free(attrib->buf); + + if (attrib->destroy) + attrib->destroy(attrib->destroy_user_data); + + g_free(attrib); +} + +void g_attrib_unref(GAttrib *attrib) +{ + int refs; + + if (!attrib) + return; + + refs = __sync_sub_and_fetch(&attrib->refs, 1); + + DBG("%p: ref=%d", attrib, refs); + + if (refs > 0) + return; + + attrib_destroy(attrib); +} + +GIOChannel *g_attrib_get_channel(GAttrib *attrib) +{ + if (!attrib) + return NULL; + + return attrib->io; +} + +gboolean g_attrib_set_destroy_function(GAttrib *attrib, + GDestroyNotify destroy, gpointer user_data) +{ + if (attrib == NULL) + return FALSE; + + attrib->destroy = destroy; + attrib->destroy_user_data = user_data; + + return TRUE; +} + +static gboolean disconnect_timeout(gpointer data) +{ + struct _GAttrib *attrib = data; + struct command *c; + + g_attrib_ref(attrib); + + c = g_queue_pop_head(attrib->requests); + if (c == NULL) + goto done; + + if (c->func) + c->func(ATT_ECODE_TIMEOUT, NULL, 0, c->user_data); + + command_destroy(c); + + while ((c = g_queue_pop_head(attrib->requests))) { + if (c->func) + c->func(ATT_ECODE_ABORTED, NULL, 0, c->user_data); + command_destroy(c); + } + +done: + attrib->stale = true; + + g_attrib_unref(attrib); + + return FALSE; +} + +static gboolean can_write_data(GIOChannel *io, GIOCondition cond, + gpointer data) +{ + struct _GAttrib *attrib = data; + struct command *cmd; + GError *gerr = NULL; + gsize len; + GIOStatus iostat; + GQueue *queue; + + if (attrib->stale) + return FALSE; + + if (cond & (G_IO_HUP | G_IO_ERR | G_IO_NVAL)) + return FALSE; + + queue = attrib->responses; + cmd = g_queue_peek_head(queue); + if (cmd == NULL) { + queue = attrib->requests; + cmd = g_queue_peek_head(queue); + } + if (cmd == NULL) + return FALSE; + + /* + * Verify that we didn't already send this command. This can only + * happen with elementes from attrib->requests. + */ + if (cmd->sent) + return FALSE; + + iostat = g_io_channel_write_chars(io, (char *) cmd->pdu, cmd->len, + &len, &gerr); + if (iostat != G_IO_STATUS_NORMAL) { + if (gerr) { + error("%s", gerr->message); + g_error_free(gerr); + } + + return FALSE; + } + + if (cmd->expected == 0) { + g_queue_pop_head(queue); + command_destroy(cmd); + + return TRUE; + } + + cmd->sent = true; + + if (attrib->timeout_watch == 0) + attrib->timeout_watch = g_timeout_add_seconds(GATT_TIMEOUT, + disconnect_timeout, attrib); + + return FALSE; +} + +static void destroy_sender(gpointer data) +{ + struct _GAttrib *attrib = data; + + attrib->write_watch = 0; + g_attrib_unref(attrib); +} + +static void wake_up_sender(struct _GAttrib *attrib) +{ + if (attrib->write_watch > 0) + return; + + attrib = g_attrib_ref(attrib); + attrib->write_watch = g_io_add_watch_full(attrib->io, + G_PRIORITY_DEFAULT, G_IO_OUT, + can_write_data, attrib, destroy_sender); +} + +static bool match_event(struct event *evt, const uint8_t *pdu, gsize len) +{ + guint16 handle; + + if (evt->expected == GATTRIB_ALL_EVENTS) + return true; + + if (!is_response(pdu[0]) && evt->expected == GATTRIB_ALL_REQS) + return true; + + if (evt->expected == pdu[0] && evt->handle == GATTRIB_ALL_HANDLES) + return true; + + if (len < 3) + return false; + + handle = att_get_u16(&pdu[1]); + + if (evt->expected == pdu[0] && evt->handle == handle) + return true; + + return false; +} + +static gboolean received_data(GIOChannel *io, GIOCondition cond, gpointer data) +{ + struct _GAttrib *attrib = data; + struct command *cmd = NULL; + GSList *l; + uint8_t buf[512], status; + gsize len; + GIOStatus iostat; + + if (attrib->stale) + return FALSE; + + if (cond & (G_IO_HUP | G_IO_ERR | G_IO_NVAL)) { + attrib->read_watch = 0; + return FALSE; + } + + memset(buf, 0, sizeof(buf)); + + iostat = g_io_channel_read_chars(io, (char *) buf, sizeof(buf), + &len, NULL); + if (iostat != G_IO_STATUS_NORMAL) { + status = ATT_ECODE_IO; + goto done; + } + + for (l = attrib->events; l; l = l->next) { + struct event *evt = l->data; + + if (match_event(evt, buf, len)) + evt->func(buf, len, evt->user_data); + } + + if (!is_response(buf[0])) + return TRUE; + + if (attrib->timeout_watch > 0) { + g_source_remove(attrib->timeout_watch); + attrib->timeout_watch = 0; + } + + cmd = g_queue_pop_head(attrib->requests); + if (cmd == NULL) { + /* Keep the watch if we have events to report */ + return attrib->events != NULL; + } + + if (buf[0] == ATT_OP_ERROR) { + status = buf[4]; + goto done; + } + + if (cmd->expected != buf[0]) { + status = ATT_ECODE_IO; + goto done; + } + + status = 0; + +done: + if (!g_queue_is_empty(attrib->requests) || + !g_queue_is_empty(attrib->responses)) + wake_up_sender(attrib); + + if (cmd) { + if (cmd->func) + cmd->func(status, buf, len, cmd->user_data); + + command_destroy(cmd); + } + + return TRUE; +} + +GAttrib *g_attrib_new(GIOChannel *io) +{ + struct _GAttrib *attrib; + uint16_t imtu; + uint16_t att_mtu; + uint16_t cid; + GError *gerr = NULL; + + g_io_channel_set_encoding(io, NULL, NULL); + g_io_channel_set_buffered(io, FALSE); + + bt_io_get(io, &gerr, BT_IO_OPT_IMTU, &imtu, + BT_IO_OPT_CID, &cid, BT_IO_OPT_INVALID); + if (gerr) { + error("%s", gerr->message); + g_error_free(gerr); + return NULL; + } + + attrib = g_try_new0(struct _GAttrib, 1); + if (attrib == NULL) + return NULL; + + att_mtu = (cid == ATT_CID) ? ATT_DEFAULT_LE_MTU : imtu; + + attrib->buf = g_malloc0(att_mtu); + attrib->buflen = att_mtu; + + attrib->io = g_io_channel_ref(io); + attrib->requests = g_queue_new(); + attrib->responses = g_queue_new(); + + attrib->read_watch = g_io_add_watch(attrib->io, + G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_NVAL, + received_data, attrib); + + return g_attrib_ref(attrib); +} + +guint g_attrib_send(GAttrib *attrib, guint id, const guint8 *pdu, guint16 len, + GAttribResultFunc func, gpointer user_data, + GDestroyNotify notify) +{ + struct command *c; + GQueue *queue; + uint8_t opcode; + + if (attrib->stale) + return 0; + + c = g_try_new0(struct command, 1); + if (c == NULL) + return 0; + + opcode = pdu[0]; + + c->opcode = opcode; + c->expected = opcode2expected(opcode); + c->pdu = g_malloc(len); + memcpy(c->pdu, pdu, len); + c->len = len; + c->func = func; + c->user_data = user_data; + c->notify = notify; + + if (is_response(opcode)) + queue = attrib->responses; + else + queue = attrib->requests; + + if (id) { + c->id = id; + if (!is_response(opcode)) + g_queue_push_head(queue, c); + else + /* Don't re-order responses even if an ID is given */ + g_queue_push_tail(queue, c); + } else { + c->id = ++attrib->next_cmd_id; + g_queue_push_tail(queue, c); + } + + /* + * If a command was added to the queue and it was empty before, wake up + * the sender. If the sender was already woken up by the second queue, + * wake_up_sender will just return. + */ + if (g_queue_get_length(queue) == 1) + wake_up_sender(attrib); + + return c->id; +} + +static int command_cmp_by_id(gconstpointer a, gconstpointer b) +{ + const struct command *cmd = a; + guint id = GPOINTER_TO_UINT(b); + + return cmd->id - id; +} + +gboolean g_attrib_cancel(GAttrib *attrib, guint id) +{ + GList *l = NULL; + struct command *cmd; + GQueue *queue; + + if (attrib == NULL) + return FALSE; + + queue = attrib->requests; + if (queue) + l = g_queue_find_custom(queue, GUINT_TO_POINTER(id), + command_cmp_by_id); + if (l == NULL) { + queue = attrib->responses; + if (!queue) + return FALSE; + l = g_queue_find_custom(queue, GUINT_TO_POINTER(id), + command_cmp_by_id); + } + + if (l == NULL) + return FALSE; + + cmd = l->data; + + if (cmd == g_queue_peek_head(queue) && cmd->sent) + cmd->func = NULL; + else { + g_queue_remove(queue, cmd); + command_destroy(cmd); + } + + return TRUE; +} + +static gboolean cancel_all_per_queue(GQueue *queue) +{ + struct command *c, *head = NULL; + gboolean first = TRUE; + + if (queue == NULL) + return FALSE; + + while ((c = g_queue_pop_head(queue))) { + if (first && c->sent) { + /* If the command was sent ignore its callback ... */ + c->func = NULL; + head = c; + continue; + } + + first = FALSE; + command_destroy(c); + } + + if (head) { + /* ... and put it back in the queue */ + g_queue_push_head(queue, head); + } + + return TRUE; +} + +gboolean g_attrib_cancel_all(GAttrib *attrib) +{ + gboolean ret; + + if (attrib == NULL) + return FALSE; + + ret = cancel_all_per_queue(attrib->requests); + ret = cancel_all_per_queue(attrib->responses) && ret; + + return ret; +} + +gboolean g_attrib_set_debug(GAttrib *attrib, + GAttribDebugFunc func, gpointer user_data) +{ + return TRUE; +} + +uint8_t *g_attrib_get_buffer(GAttrib *attrib, size_t *len) +{ + if (len == NULL) + return NULL; + + *len = attrib->buflen; + + return attrib->buf; +} + +gboolean g_attrib_set_mtu(GAttrib *attrib, int mtu) +{ + if (mtu < ATT_DEFAULT_LE_MTU) + return FALSE; + + attrib->buf = g_realloc(attrib->buf, mtu); + + attrib->buflen = mtu; + + return TRUE; +} + +guint g_attrib_register(GAttrib *attrib, guint8 opcode, guint16 handle, + GAttribNotifyFunc func, gpointer user_data, + GDestroyNotify notify) +{ + static guint next_evt_id = 0; + struct event *event; + + event = g_try_new0(struct event, 1); + if (event == NULL) + return 0; + + event->expected = opcode; + event->handle = handle; + event->func = func; + event->user_data = user_data; + event->notify = notify; + event->id = ++next_evt_id; + + attrib->events = g_slist_append(attrib->events, event); + + return event->id; +} + +static int event_cmp_by_id(gconstpointer a, gconstpointer b) +{ + const struct event *evt = a; + guint id = GPOINTER_TO_UINT(b); + + return evt->id - id; +} + +gboolean g_attrib_is_encrypted(GAttrib *attrib) +{ + BtIOSecLevel sec_level; + + if (!bt_io_get(attrib->io, NULL, + BT_IO_OPT_SEC_LEVEL, &sec_level, + BT_IO_OPT_INVALID)) + return FALSE; + + return sec_level > BT_IO_SEC_LOW; +} + +gboolean g_attrib_unregister(GAttrib *attrib, guint id) +{ + struct event *evt; + GSList *l; + + if (id == 0) { + warn("%s: invalid id", __func__); + return FALSE; + } + + l = g_slist_find_custom(attrib->events, GUINT_TO_POINTER(id), + event_cmp_by_id); + if (l == NULL) + return FALSE; + + evt = l->data; + + attrib->events = g_slist_remove(attrib->events, evt); + + if (evt->notify) + evt->notify(evt->user_data); + + g_free(evt); + + return TRUE; +} + +gboolean g_attrib_unregister_all(GAttrib *attrib) +{ + GSList *l; + + if (attrib->events == NULL) + return FALSE; + + for (l = attrib->events; l; l = l->next) { + struct event *evt = l->data; + + if (evt->notify) + evt->notify(evt->user_data); + + g_free(evt); + } + + g_slist_free(attrib->events); + attrib->events = NULL; + + return TRUE; +} diff --git a/drive-sdk/deps/bzle/src/hci.c b/drive-sdk/deps/bzle/src/hci.c new file mode 100644 index 0000000..3579bfd --- /dev/null +++ b/drive-sdk/deps/bzle/src/hci.c @@ -0,0 +1,2929 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2000-2001 Qualcomm Incorporated + * Copyright (C) 2002-2003 Maxim Krasnyansky + * Copyright (C) 2002-2010 Marcel Holtmann + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#ifndef MIN +#define MIN(x, y) ((x) < (y) ? (x) : (y)) +#endif + +typedef struct { + char *str; + unsigned int val; +} hci_map; + +static char *hci_bit2str(hci_map *m, unsigned int val) +{ + char *str = malloc(120); + char *ptr = str; + + if (!str) + return NULL; + + *ptr = 0; + while (m->str) { + if ((unsigned int) m->val & val) + ptr += sprintf(ptr, "%s ", m->str); + m++; + } + return str; +} + +static int hci_str2bit(hci_map *map, char *str, unsigned int *val) +{ + char *t, *ptr; + hci_map *m; + int set; + + if (!str || !(str = ptr = strdup(str))) + return 0; + + *val = set = 0; + + while ((t = strsep(&ptr, ","))) { + for (m = map; m->str; m++) { + if (!strcasecmp(m->str, t)) { + *val |= (unsigned int) m->val; + set = 1; + } + } + } + free(str); + + return set; +} + +static char *hci_uint2str(hci_map *m, unsigned int val) +{ + char *str = malloc(50); + char *ptr = str; + + if (!str) + return NULL; + + *ptr = 0; + while (m->str) { + if ((unsigned int) m->val == val) { + ptr += sprintf(ptr, "%s", m->str); + break; + } + m++; + } + return str; +} + +static int hci_str2uint(hci_map *map, char *str, unsigned int *val) +{ + char *t, *ptr; + hci_map *m; + int set = 0; + + if (!str) + return 0; + + str = ptr = strdup(str); + + while ((t = strsep(&ptr, ","))) { + for (m = map; m->str; m++) { + if (!strcasecmp(m->str,t)) { + *val = (unsigned int) m->val; + set = 1; + break; + } + } + } + free(str); + + return set; +} + +char *hci_bustostr(int bus) +{ + switch (bus) { + case HCI_VIRTUAL: + return "VIRTUAL"; + case HCI_USB: + return "USB"; + case HCI_PCCARD: + return "PCCARD"; + case HCI_UART: + return "UART"; + case HCI_RS232: + return "RS232"; + case HCI_PCI: + return "PCI"; + case HCI_SDIO: + return "SDIO"; + default: + return "UNKNOWN"; + } +} + +char *hci_dtypetostr(int type) +{ + return hci_bustostr(type & 0x0f); +} + +char *hci_typetostr(int type) +{ + switch (type) { + case HCI_BREDR: + return "BR/EDR"; + case HCI_AMP: + return "AMP"; + default: + return "UNKNOWN"; + } +} + +/* HCI dev flags mapping */ +static hci_map dev_flags_map[] = { + { "UP", HCI_UP }, + { "INIT", HCI_INIT }, + { "RUNNING", HCI_RUNNING }, + { "RAW", HCI_RAW }, + { "PSCAN", HCI_PSCAN }, + { "ISCAN", HCI_ISCAN }, + { "INQUIRY", HCI_INQUIRY }, + { "AUTH", HCI_AUTH }, + { "ENCRYPT", HCI_ENCRYPT }, + { NULL } +}; + +char *hci_dflagstostr(uint32_t flags) +{ + char *str = bt_malloc(50); + char *ptr = str; + hci_map *m = dev_flags_map; + + if (!str) + return NULL; + + *ptr = 0; + + if (!hci_test_bit(HCI_UP, &flags)) + ptr += sprintf(ptr, "DOWN "); + + while (m->str) { + if (hci_test_bit(m->val, &flags)) + ptr += sprintf(ptr, "%s ", m->str); + m++; + } + return str; +} + +/* HCI packet type mapping */ +static hci_map pkt_type_map[] = { + { "DM1", HCI_DM1 }, + { "DM3", HCI_DM3 }, + { "DM5", HCI_DM5 }, + { "DH1", HCI_DH1 }, + { "DH3", HCI_DH3 }, + { "DH5", HCI_DH5 }, + { "HV1", HCI_HV1 }, + { "HV2", HCI_HV2 }, + { "HV3", HCI_HV3 }, + { "2-DH1", HCI_2DH1 }, + { "2-DH3", HCI_2DH3 }, + { "2-DH5", HCI_2DH5 }, + { "3-DH1", HCI_3DH1 }, + { "3-DH3", HCI_3DH3 }, + { "3-DH5", HCI_3DH5 }, + { NULL } +}; + +static hci_map sco_ptype_map[] = { + { "HV1", 0x0001 }, + { "HV2", 0x0002 }, + { "HV3", 0x0004 }, + { "EV3", HCI_EV3 }, + { "EV4", HCI_EV4 }, + { "EV5", HCI_EV5 }, + { "2-EV3", HCI_2EV3 }, + { "2-EV5", HCI_2EV5 }, + { "3-EV3", HCI_3EV3 }, + { "3-EV5", HCI_3EV5 }, + { NULL } +}; + +char *hci_ptypetostr(unsigned int ptype) +{ + return hci_bit2str(pkt_type_map, ptype); +} + +int hci_strtoptype(char *str, unsigned int *val) +{ + return hci_str2bit(pkt_type_map, str, val); +} + +char *hci_scoptypetostr(unsigned int ptype) +{ + return hci_bit2str(sco_ptype_map, ptype); +} + +int hci_strtoscoptype(char *str, unsigned int *val) +{ + return hci_str2bit(sco_ptype_map, str, val); +} + +/* Link policy mapping */ +static hci_map link_policy_map[] = { + { "NONE", 0 }, + { "RSWITCH", HCI_LP_RSWITCH }, + { "HOLD", HCI_LP_HOLD }, + { "SNIFF", HCI_LP_SNIFF }, + { "PARK", HCI_LP_PARK }, + { NULL } +}; + +char *hci_lptostr(unsigned int lp) +{ + return hci_bit2str(link_policy_map, lp); +} + +int hci_strtolp(char *str, unsigned int *val) +{ + return hci_str2bit(link_policy_map, str, val); +} + +/* Link mode mapping */ +static hci_map link_mode_map[] = { + { "NONE", 0 }, + { "ACCEPT", HCI_LM_ACCEPT }, + { "MASTER", HCI_LM_MASTER }, + { "AUTH", HCI_LM_AUTH }, + { "ENCRYPT", HCI_LM_ENCRYPT }, + { "TRUSTED", HCI_LM_TRUSTED }, + { "RELIABLE", HCI_LM_RELIABLE }, + { "SECURE", HCI_LM_SECURE }, + { NULL } +}; + +char *hci_lmtostr(unsigned int lm) +{ + char *s, *str = bt_malloc(50); + if (!str) + return NULL; + + *str = 0; + if (!(lm & HCI_LM_MASTER)) + strcpy(str, "SLAVE "); + + s = hci_bit2str(link_mode_map, lm); + if (!s) { + bt_free(str); + return NULL; + } + + strcat(str, s); + free(s); + return str; +} + +int hci_strtolm(char *str, unsigned int *val) +{ + return hci_str2bit(link_mode_map, str, val); +} + +/* Command mapping */ +static hci_map commands_map[] = { + { "Inquiry", 0 }, + { "Inquiry Cancel", 1 }, + { "Periodic Inquiry Mode", 2 }, + { "Exit Periodic Inquiry Mode", 3 }, + { "Create Connection", 4 }, + { "Disconnect", 5 }, + { "Add SCO Connection", 6 }, + { "Cancel Create Connection", 7 }, + + { "Accept Connection Request", 8 }, + { "Reject Connection Request", 9 }, + { "Link Key Request Reply", 10 }, + { "Link Key Request Negative Reply", 11 }, + { "PIN Code Request Reply", 12 }, + { "PIN Code Request Negative Reply", 13 }, + { "Change Connection Packet Type", 14 }, + { "Authentication Requested", 15 }, + + { "Set Connection Encryption", 16 }, + { "Change Connection Link Key", 17 }, + { "Master Link Key", 18 }, + { "Remote Name Request", 19 }, + { "Cancel Remote Name Request", 20 }, + { "Read Remote Supported Features", 21 }, + { "Read Remote Extended Features", 22 }, + { "Read Remote Version Information", 23 }, + + { "Read Clock Offset", 24 }, + { "Read LMP Handle", 25 }, + { "Reserved", 26 }, + { "Reserved", 27 }, + { "Reserved", 28 }, + { "Reserved", 29 }, + { "Reserved", 30 }, + { "Reserved", 31 }, + + { "Reserved", 32 }, + { "Hold Mode", 33 }, + { "Sniff Mode", 34 }, + { "Exit Sniff Mode", 35 }, + { "Park State", 36 }, + { "Exit Park State", 37 }, + { "QoS Setup", 38 }, + { "Role Discovery", 39 }, + + { "Switch Role", 40 }, + { "Read Link Policy Settings", 41 }, + { "Write Link Policy Settings", 42 }, + { "Read Default Link Policy Settings", 43 }, + { "Write Default Link Policy Settings", 44 }, + { "Flow Specification", 45 }, + { "Set Event Mask", 46 }, + { "Reset", 47 }, + + { "Set Event Filter", 48 }, + { "Flush", 49 }, + { "Read PIN Type", 50 }, + { "Write PIN Type", 51 }, + { "Create New Unit Key", 52 }, + { "Read Stored Link Key", 53 }, + { "Write Stored Link Key", 54 }, + { "Delete Stored Link Key", 55 }, + + { "Write Local Name", 56 }, + { "Read Local Name", 57 }, + { "Read Connection Accept Timeout", 58 }, + { "Write Connection Accept Timeout", 59 }, + { "Read Page Timeout", 60 }, + { "Write Page Timeout", 61 }, + { "Read Scan Enable", 62 }, + { "Write Scan Enable", 63 }, + + { "Read Page Scan Activity", 64 }, + { "Write Page Scan Activity", 65 }, + { "Read Inquiry Scan Activity", 66 }, + { "Write Inquiry Scan Activity", 67 }, + { "Read Authentication Enable", 68 }, + { "Write Authentication Enable", 69 }, + { "Read Encryption Mode", 70 }, + { "Write Encryption Mode", 71 }, + + { "Read Class Of Device", 72 }, + { "Write Class Of Device", 73 }, + { "Read Voice Setting", 74 }, + { "Write Voice Setting", 75 }, + { "Read Automatic Flush Timeout", 76 }, + { "Write Automatic Flush Timeout", 77 }, + { "Read Num Broadcast Retransmissions", 78 }, + { "Write Num Broadcast Retransmissions", 79 }, + + { "Read Hold Mode Activity", 80 }, + { "Write Hold Mode Activity", 81 }, + { "Read Transmit Power Level", 82 }, + { "Read Synchronous Flow Control Enable", 83 }, + { "Write Synchronous Flow Control Enable", 84 }, + { "Set Host Controller To Host Flow Control", 85 }, + { "Host Buffer Size", 86 }, + { "Host Number Of Completed Packets", 87 }, + + { "Read Link Supervision Timeout", 88 }, + { "Write Link Supervision Timeout", 89 }, + { "Read Number of Supported IAC", 90 }, + { "Read Current IAC LAP", 91 }, + { "Write Current IAC LAP", 92 }, + { "Read Page Scan Period Mode", 93 }, + { "Write Page Scan Period Mode", 94 }, + { "Read Page Scan Mode", 95 }, + + { "Write Page Scan Mode", 96 }, + { "Set AFH Channel Classification", 97 }, + { "Reserved", 98 }, + { "Reserved", 99 }, + { "Read Inquiry Scan Type", 100 }, + { "Write Inquiry Scan Type", 101 }, + { "Read Inquiry Mode", 102 }, + { "Write Inquiry Mode", 103 }, + + { "Read Page Scan Type", 104 }, + { "Write Page Scan Type", 105 }, + { "Read AFH Channel Assessment Mode", 106 }, + { "Write AFH Channel Assessment Mode", 107 }, + { "Reserved", 108 }, + { "Reserved", 109 }, + { "Reserved", 110 }, + { "Reserved", 111 }, + + { "Reserved", 112 }, + { "Reserved", 113 }, + { "Reserved", 114 }, + { "Read Local Version Information", 115 }, + { "Read Local Supported Commands", 116 }, + { "Read Local Supported Features", 117 }, + { "Read Local Extended Features", 118 }, + { "Read Buffer Size", 119 }, + + { "Read Country Code", 120 }, + { "Read BD ADDR", 121 }, + { "Read Failed Contact Counter", 122 }, + { "Reset Failed Contact Counter", 123 }, + { "Get Link Quality", 124 }, + { "Read RSSI", 125 }, + { "Read AFH Channel Map", 126 }, + { "Read BD Clock", 127 }, + + { "Read Loopback Mode", 128 }, + { "Write Loopback Mode", 129 }, + { "Enable Device Under Test Mode", 130 }, + { "Setup Synchronous Connection", 131 }, + { "Accept Synchronous Connection", 132 }, + { "Reject Synchronous Connection", 133 }, + { "Reserved", 134 }, + { "Reserved", 135 }, + + { "Read Extended Inquiry Response", 136 }, + { "Write Extended Inquiry Response", 137 }, + { "Refresh Encryption Key", 138 }, + { "Reserved", 139 }, + { "Sniff Subrating", 140 }, + { "Read Simple Pairing Mode", 141 }, + { "Write Simple Pairing Mode", 142 }, + { "Read Local OOB Data", 143 }, + + { "Read Inquiry Response Transmit Power Level", 144 }, + { "Write Inquiry Transmit Power Level", 145 }, + { "Read Default Erroneous Data Reporting", 146 }, + { "Write Default Erroneous Data Reporting", 147 }, + { "Reserved", 148 }, + { "Reserved", 149 }, + { "Reserved", 150 }, + { "IO Capability Request Reply", 151 }, + + { "User Confirmation Request Reply", 152 }, + { "User Confirmation Request Negative Reply", 153 }, + { "User Passkey Request Reply", 154 }, + { "User Passkey Request Negative Reply", 155 }, + { "Remote OOB Data Request Reply", 156 }, + { "Write Simple Pairing Debug Mode", 157 }, + { "Enhanced Flush", 158 }, + { "Remote OOB Data Request Negative Reply", 159 }, + + { "Reserved", 160 }, + { "Reserved", 161 }, + { "Send Keypress Notification", 162 }, + { "IO Capability Request Negative Reply", 163 }, + { "Read Encryption Key Size", 164 }, + { "Reserved", 165 }, + { "Reserved", 166 }, + { "Reserved", 167 }, + + { "Create Physical Link", 168 }, + { "Accept Physical Link", 169 }, + { "Disconnect Physical Link", 170 }, + { "Create Logical Link", 171 }, + { "Accept Logical Link", 172 }, + { "Disconnect Logical Link", 173 }, + { "Logical Link Cancel", 174 }, + { "Flow Specification Modify", 175 }, + + { "Read Logical Link Accept Timeout", 176 }, + { "Write Logical Link Accept Timeout", 177 }, + { "Set Event Mask Page 2", 178 }, + { "Read Location Data", 179 }, + { "Write Location Data", 180 }, + { "Read Local AMP Info", 181 }, + { "Read Local AMP_ASSOC", 182 }, + { "Write Remote AMP_ASSOC", 183 }, + + { "Read Flow Control Mode", 184 }, + { "Write Flow Control Mode", 185 }, + { "Read Data Block Size", 186 }, + { "Reserved", 187 }, + { "Reserved", 188 }, + { "Enable AMP Receiver Reports", 189 }, + { "AMP Test End", 190 }, + { "AMP Test Command", 191 }, + + { "Read Enhanced Transmit Power Level", 192 }, + { "Reserved", 193 }, + { "Read Best Effort Flush Timeout", 194 }, + { "Write Best Effort Flush Timeout", 195 }, + { "Short Range Mode", 196 }, + { "Read LE Host Support", 197 }, + { "Write LE Host Support", 198 }, + { "Reserved", 199 }, + + { "LE Set Event Mask", 200 }, + { "LE Read Buffer Size", 201 }, + { "LE Read Local Supported Features", 202 }, + { "Reserved", 203 }, + { "LE Set Random Address", 204 }, + { "LE Set Advertising Parameters", 205 }, + { "LE Read Advertising Channel TX Power", 206 }, + { "LE Set Advertising Data", 207 }, + + { "LE Set Scan Response Data", 208 }, + { "LE Set Advertise Enable", 209 }, + { "LE Set Scan Parameters", 210 }, + { "LE Set Scan Enable", 211 }, + { "LE Create Connection", 212 }, + { "LE Create Connection Cancel", 213 }, + { "LE Read White List Size", 214 }, + { "LE Clear White List", 215 }, + + { "LE Add Device To White List", 216 }, + { "LE Remove Device From White List", 217 }, + { "LE Connection Update", 218 }, + { "LE Set Host Channel Classification", 219 }, + { "LE Read Channel Map", 220 }, + { "LE Read Remote Used Features", 221 }, + { "LE Encrypt", 222 }, + { "LE Rand", 223 }, + + { "LE Start Encryption", 224 }, + { "LE Long Term Key Request Reply", 225 }, + { "LE Long Term Key Request Negative Reply", 226 }, + { "LE Read Supported States", 227 }, + { "LE Receiver Test", 228 }, + { "LE Transmitter Test", 229 }, + { "LE Test End", 230 }, + { "Reserved", 231 }, + + { NULL } +}; + +char *hci_cmdtostr(unsigned int cmd) +{ + return hci_uint2str(commands_map, cmd); +} + +char *hci_commandstostr(uint8_t *commands, char *pref, int width) +{ + unsigned int maxwidth = width - 3; + hci_map *m; + char *off, *ptr, *str; + int size = 10; + + m = commands_map; + + while (m->str) { + if (commands[m->val / 8] & (1 << (m->val % 8))) + size += strlen(m->str) + (pref ? strlen(pref) : 0) + 3; + m++; + } + + str = bt_malloc(size); + if (!str) + return NULL; + + ptr = str; *ptr = '\0'; + + if (pref) + ptr += sprintf(ptr, "%s", pref); + + off = ptr; + + m = commands_map; + + while (m->str) { + if (commands[m->val / 8] & (1 << (m->val % 8))) { + if (strlen(off) + strlen(m->str) > maxwidth) { + ptr += sprintf(ptr, "\n%s", pref ? pref : ""); + off = ptr; + } + ptr += sprintf(ptr, "'%s' ", m->str); + } + m++; + } + + return str; +} + +/* Version mapping */ +static hci_map ver_map[] = { + { "1.0b", 0x00 }, + { "1.1", 0x01 }, + { "1.2", 0x02 }, + { "2.0", 0x03 }, + { "2.1", 0x04 }, + { "3.0", 0x05 }, + { "4.0", 0x06 }, + { "4.1", 0x07 }, + { NULL } +}; + +char *hci_vertostr(unsigned int ver) +{ + return hci_uint2str(ver_map, ver); +} + +int hci_strtover(char *str, unsigned int *ver) +{ + return hci_str2uint(ver_map, str, ver); +} + +char *lmp_vertostr(unsigned int ver) +{ + return hci_uint2str(ver_map, ver); +} + +int lmp_strtover(char *str, unsigned int *ver) +{ + return hci_str2uint(ver_map, str, ver); +} + +static hci_map pal_map[] = { + { "3.0", 0x01 }, + { NULL } +}; + +char *pal_vertostr(unsigned int ver) +{ + return hci_uint2str(pal_map, ver); +} + +int pal_strtover(char *str, unsigned int *ver) +{ + return hci_str2uint(pal_map, str, ver); +} + +/* LMP features mapping */ +static hci_map lmp_features_map[8][9] = { + { /* Byte 0 */ + { "<3-slot packets>", LMP_3SLOT }, /* Bit 0 */ + { "<5-slot packets>", LMP_5SLOT }, /* Bit 1 */ + { "", LMP_ENCRYPT }, /* Bit 2 */ + { "", LMP_SOFFSET }, /* Bit 3 */ + { "", LMP_TACCURACY }, /* Bit 4 */ + { "", LMP_RSWITCH }, /* Bit 5 */ + { "", LMP_HOLD }, /* Bit 6 */ + { "", LMP_SNIFF }, /* Bit 7 */ + { NULL } + }, + { /* Byte 1 */ + { "", LMP_PARK }, /* Bit 0 */ + { "", LMP_RSSI }, /* Bit 1 */ + { "", LMP_QUALITY }, /* Bit 2 */ + { "", LMP_SCO }, /* Bit 3 */ + { "", LMP_HV2 }, /* Bit 4 */ + { "", LMP_HV3 }, /* Bit 5 */ + { "", LMP_ULAW }, /* Bit 6 */ + { "", LMP_ALAW }, /* Bit 7 */ + { NULL } + }, + { /* Byte 2 */ + { "", LMP_CVSD }, /* Bit 0 */ + { "", LMP_PSCHEME }, /* Bit 1 */ + { "", LMP_PCONTROL }, /* Bit 2 */ + { "", LMP_TRSP_SCO }, /* Bit 3 */ + { "",LMP_BCAST_ENC }, /* Bit 7 */ + { NULL } + }, + { /* Byte 3 */ + { "", 0x01 }, /* Bit 0 */ + { "", LMP_EDR_ACL_2M }, /* Bit 1 */ + { "", LMP_EDR_ACL_3M }, /* Bit 2 */ + { "", LMP_ENH_ISCAN }, /* Bit 3 */ + { "", LMP_ILACE_ISCAN }, /* Bit 4 */ + { "", LMP_ILACE_PSCAN }, /* Bit 5 */ + { "",LMP_RSSI_INQ }, /* Bit 6 */ + { "", LMP_ESCO }, /* Bit 7 */ + { NULL } + }, + { /* Byte 4 */ + { "", LMP_EV4 }, /* Bit 0 */ + { "", LMP_EV5 }, /* Bit 1 */ + { "", 0x04 }, /* Bit 2 */ + { "", LMP_AFH_CAP_SLV }, /* Bit 3 */ + { "", LMP_AFH_CLS_SLV }, /* Bit 4 */ + { "
", LMP_NO_BREDR }, /* Bit 5 */ + { "", LMP_LE }, /* Bit 6 */ + { "<3-slot EDR ACL>", LMP_EDR_3SLOT }, /* Bit 7 */ + { NULL } + }, + { /* Byte 5 */ + { "<5-slot EDR ACL>", LMP_EDR_5SLOT }, /* Bit 0 */ + { "", LMP_SNIFF_SUBR }, /* Bit 1 */ + { "", LMP_PAUSE_ENC }, /* Bit 2 */ + { "", LMP_AFH_CAP_MST }, /* Bit 3 */ + { "",LMP_AFH_CLS_MST }, /* Bit 4 */ + { "", LMP_EDR_ESCO_2M }, /* Bit 5 */ + { "", LMP_EDR_ESCO_3M }, /* Bit 6 */ + { "<3-slot EDR eSCO>", LMP_EDR_3S_ESCO }, /* Bit 7 */ + { NULL } + }, + { /* Byte 6 */ + { "", LMP_EXT_INQ }, /* Bit 0 */ + { "", LMP_LE_BREDR }, /* Bit 1 */ + { "", 0x04 }, /* Bit 2 */ + { "", LMP_SIMPLE_PAIR }, /* Bit 3 */ + { "", LMP_ENCAPS_PDU }, /* Bit 4 */ + { "", LMP_ERR_DAT_REP }, /* Bit 5 */ + { "", LMP_NFLUSH_PKTS }, /* Bit 6 */ + { "", 0x80 }, /* Bit 7 */ + { NULL } + }, + { /* Byte 7 */ + { "", LMP_LSTO }, /* Bit 1 */ + { "", LMP_INQ_TX_PWR }, /* Bit 1 */ + { "", LMP_EPC }, /* Bit 2 */ + { "", 0x08 }, /* Bit 3 */ + { "", 0x10 }, /* Bit 4 */ + { "", 0x20 }, /* Bit 5 */ + { "", 0x40 }, /* Bit 6 */ + { "",LMP_EXT_FEAT }, /* Bit 7 */ + { NULL } + }, +}; + +char *lmp_featurestostr(uint8_t *features, char *pref, int width) +{ + unsigned int maxwidth = width - 1; + char *off, *ptr, *str; + int i, size = 10; + + for (i = 0; i < 8; i++) { + hci_map *m = lmp_features_map[i]; + + while (m->str) { + if (m->val & features[i]) + size += strlen(m->str) + + (pref ? strlen(pref) : 0) + 1; + m++; + } + } + + str = bt_malloc(size); + if (!str) + return NULL; + + ptr = str; *ptr = '\0'; + + if (pref) + ptr += sprintf(ptr, "%s", pref); + + off = ptr; + + for (i = 0; i < 8; i++) { + hci_map *m = lmp_features_map[i]; + + while (m->str) { + if (m->val & features[i]) { + if (strlen(off) + strlen(m->str) > maxwidth) { + ptr += sprintf(ptr, "\n%s", + pref ? pref : ""); + off = ptr; + } + ptr += sprintf(ptr, "%s ", m->str); + } + m++; + } + } + + return str; +} + +/* HCI functions that do not require open device */ +int hci_for_each_dev(int flag, int (*func)(int dd, int dev_id, long arg), + long arg) +{ + struct hci_dev_list_req *dl; + struct hci_dev_req *dr; + int dev_id = -1; + int i, sk, err = 0; + + sk = socket(AF_BLUETOOTH, SOCK_RAW | SOCK_CLOEXEC, BTPROTO_HCI); + if (sk < 0) + return -1; + + dl = malloc(HCI_MAX_DEV * sizeof(*dr) + sizeof(*dl)); + if (!dl) { + err = errno; + goto done; + } + + memset(dl, 0, HCI_MAX_DEV * sizeof(*dr) + sizeof(*dl)); + + dl->dev_num = HCI_MAX_DEV; + dr = dl->dev_req; + + if (ioctl(sk, HCIGETDEVLIST, (void *) dl) < 0) { + err = errno; + goto free; + } + + for (i = 0; i < dl->dev_num; i++, dr++) { + if (hci_test_bit(flag, &dr->dev_opt)) + if (!func || func(sk, dr->dev_id, arg)) { + dev_id = dr->dev_id; + break; + } + } + + if (dev_id < 0) + err = ENODEV; + +free: + free(dl); + +done: + close(sk); + errno = err; + + return dev_id; +} + +static int __other_bdaddr(int dd, int dev_id, long arg) +{ + struct hci_dev_info di = { .dev_id = dev_id }; + + if (ioctl(dd, HCIGETDEVINFO, (void *) &di)) + return 0; + + if (hci_test_bit(HCI_RAW, &di.flags)) + return 0; + + return bacmp((bdaddr_t *) arg, &di.bdaddr); +} + +static int __same_bdaddr(int dd, int dev_id, long arg) +{ + struct hci_dev_info di = { .dev_id = dev_id }; + + if (ioctl(dd, HCIGETDEVINFO, (void *) &di)) + return 0; + + return !bacmp((bdaddr_t *) arg, &di.bdaddr); +} + +int hci_get_route(bdaddr_t *bdaddr) +{ + return hci_for_each_dev(HCI_UP, __other_bdaddr, + (long) (bdaddr ? bdaddr : BDADDR_ANY)); +} + +int hci_devid(const char *str) +{ + bdaddr_t ba; + int id = -1; + + if (!strncmp(str, "hci", 3) && strlen(str) >= 4) { + id = atoi(str + 3); + if (hci_devba(id, &ba) < 0) + return -1; + } else { + errno = ENODEV; + str2ba(str, &ba); + id = hci_for_each_dev(HCI_UP, __same_bdaddr, (long) &ba); + } + + return id; +} + +int hci_devinfo(int dev_id, struct hci_dev_info *di) +{ + int dd, err, ret; + + dd = socket(AF_BLUETOOTH, SOCK_RAW | SOCK_CLOEXEC, BTPROTO_HCI); + if (dd < 0) + return dd; + + memset(di, 0, sizeof(struct hci_dev_info)); + + di->dev_id = dev_id; + ret = ioctl(dd, HCIGETDEVINFO, (void *) di); + + err = errno; + close(dd); + errno = err; + + return ret; +} + +int hci_devba(int dev_id, bdaddr_t *bdaddr) +{ + struct hci_dev_info di; + + memset(&di, 0, sizeof(di)); + + if (hci_devinfo(dev_id, &di)) + return -1; + + if (!hci_test_bit(HCI_UP, &di.flags)) { + errno = ENETDOWN; + return -1; + } + + bacpy(bdaddr, &di.bdaddr); + + return 0; +} + +int hci_inquiry(int dev_id, int len, int nrsp, const uint8_t *lap, + inquiry_info **ii, long flags) +{ + struct hci_inquiry_req *ir; + uint8_t num_rsp = nrsp; + void *buf; + int dd, size, err, ret = -1; + + if (nrsp <= 0) { + num_rsp = 0; + nrsp = 255; + } + + if (dev_id < 0) { + dev_id = hci_get_route(NULL); + if (dev_id < 0) { + errno = ENODEV; + return -1; + } + } + + dd = socket(AF_BLUETOOTH, SOCK_RAW | SOCK_CLOEXEC, BTPROTO_HCI); + if (dd < 0) + return dd; + + buf = malloc(sizeof(*ir) + (sizeof(inquiry_info) * (nrsp))); + if (!buf) + goto done; + + ir = buf; + ir->dev_id = dev_id; + ir->num_rsp = num_rsp; + ir->length = len; + ir->flags = flags; + + if (lap) { + memcpy(ir->lap, lap, 3); + } else { + ir->lap[0] = 0x33; + ir->lap[1] = 0x8b; + ir->lap[2] = 0x9e; + } + + ret = ioctl(dd, HCIINQUIRY, (unsigned long) buf); + if (ret < 0) + goto free; + + size = sizeof(inquiry_info) * ir->num_rsp; + + if (!*ii) + *ii = malloc(size); + + if (*ii) { + memcpy((void *) *ii, buf + sizeof(*ir), size); + ret = ir->num_rsp; + } else + ret = -1; + +free: + free(buf); + +done: + err = errno; + close(dd); + errno = err; + + return ret; +} + +/* Open HCI device. + * Returns device descriptor (dd). */ +int hci_open_dev(int dev_id) +{ + struct sockaddr_hci a; + int dd, err; + + /* Create HCI socket */ + dd = socket(AF_BLUETOOTH, SOCK_RAW | SOCK_CLOEXEC, BTPROTO_HCI); + if (dd < 0) + return dd; + + /* Bind socket to the HCI device */ + memset(&a, 0, sizeof(a)); + a.hci_family = AF_BLUETOOTH; + a.hci_dev = dev_id; + if (bind(dd, (struct sockaddr *) &a, sizeof(a)) < 0) + goto failed; + + return dd; + +failed: + err = errno; + close(dd); + errno = err; + + return -1; +} + +int hci_close_dev(int dd) +{ + return close(dd); +} + +/* HCI functions that require open device + * dd - Device descriptor returned by hci_open_dev. */ + +int hci_send_cmd(int dd, uint16_t ogf, uint16_t ocf, uint8_t plen, void *param) +{ + uint8_t type = HCI_COMMAND_PKT; + hci_command_hdr hc; + struct iovec iv[3]; + int ivn; + + hc.opcode = htobs(cmd_opcode_pack(ogf, ocf)); + hc.plen= plen; + + iv[0].iov_base = &type; + iv[0].iov_len = 1; + iv[1].iov_base = &hc; + iv[1].iov_len = HCI_COMMAND_HDR_SIZE; + ivn = 2; + + if (plen) { + iv[2].iov_base = param; + iv[2].iov_len = plen; + ivn = 3; + } + + while (writev(dd, iv, ivn) < 0) { + if (errno == EAGAIN || errno == EINTR) + continue; + return -1; + } + return 0; +} + +int hci_send_req(int dd, struct hci_request *r, int to) +{ + unsigned char buf[HCI_MAX_EVENT_SIZE], *ptr; + uint16_t opcode = htobs(cmd_opcode_pack(r->ogf, r->ocf)); + struct hci_filter nf, of; + socklen_t olen; + hci_event_hdr *hdr; + int err, try; + + olen = sizeof(of); + if (getsockopt(dd, SOL_HCI, HCI_FILTER, &of, &olen) < 0) + return -1; + + hci_filter_clear(&nf); + hci_filter_set_ptype(HCI_EVENT_PKT, &nf); + hci_filter_set_event(EVT_CMD_STATUS, &nf); + hci_filter_set_event(EVT_CMD_COMPLETE, &nf); + hci_filter_set_event(EVT_LE_META_EVENT, &nf); + hci_filter_set_event(r->event, &nf); + hci_filter_set_opcode(opcode, &nf); + if (setsockopt(dd, SOL_HCI, HCI_FILTER, &nf, sizeof(nf)) < 0) + return -1; + + if (hci_send_cmd(dd, r->ogf, r->ocf, r->clen, r->cparam) < 0) + goto failed; + + try = 10; + while (try--) { + evt_cmd_complete *cc; + evt_cmd_status *cs; + evt_remote_name_req_complete *rn; + evt_le_meta_event *me; + remote_name_req_cp *cp; + int len; + + if (to) { + struct pollfd p; + int n; + + p.fd = dd; p.events = POLLIN; + while ((n = poll(&p, 1, to)) < 0) { + if (errno == EAGAIN || errno == EINTR) + continue; + goto failed; + } + + if (!n) { + errno = ETIMEDOUT; + goto failed; + } + + to -= 10; + if (to < 0) + to = 0; + + } + + while ((len = read(dd, buf, sizeof(buf))) < 0) { + if (errno == EAGAIN || errno == EINTR) + continue; + goto failed; + } + + hdr = (void *) (buf + 1); + ptr = buf + (1 + HCI_EVENT_HDR_SIZE); + len -= (1 + HCI_EVENT_HDR_SIZE); + + switch (hdr->evt) { + case EVT_CMD_STATUS: + cs = (void *) ptr; + + if (cs->opcode != opcode) + continue; + + if (r->event != EVT_CMD_STATUS) { + if (cs->status) { + errno = EIO; + goto failed; + } + break; + } + + r->rlen = MIN(len, r->rlen); + memcpy(r->rparam, ptr, r->rlen); + goto done; + + case EVT_CMD_COMPLETE: + cc = (void *) ptr; + + if (cc->opcode != opcode) + continue; + + ptr += EVT_CMD_COMPLETE_SIZE; + len -= EVT_CMD_COMPLETE_SIZE; + + r->rlen = MIN(len, r->rlen); + memcpy(r->rparam, ptr, r->rlen); + goto done; + + case EVT_REMOTE_NAME_REQ_COMPLETE: + if (hdr->evt != r->event) + break; + + rn = (void *) ptr; + cp = r->cparam; + + if (bacmp(&rn->bdaddr, &cp->bdaddr)) + continue; + + r->rlen = MIN(len, r->rlen); + memcpy(r->rparam, ptr, r->rlen); + goto done; + + case EVT_LE_META_EVENT: + me = (void *) ptr; + + if (me->subevent != r->event) + continue; + + len -= 1; + r->rlen = MIN(len, r->rlen); + memcpy(r->rparam, me->data, r->rlen); + goto done; + + default: + if (hdr->evt != r->event) + break; + + r->rlen = MIN(len, r->rlen); + memcpy(r->rparam, ptr, r->rlen); + goto done; + } + } + errno = ETIMEDOUT; + +failed: + err = errno; + setsockopt(dd, SOL_HCI, HCI_FILTER, &of, sizeof(of)); + errno = err; + return -1; + +done: + setsockopt(dd, SOL_HCI, HCI_FILTER, &of, sizeof(of)); + return 0; +} + +int hci_create_connection(int dd, const bdaddr_t *bdaddr, uint16_t ptype, + uint16_t clkoffset, uint8_t rswitch, + uint16_t *handle, int to) +{ + evt_conn_complete rp; + create_conn_cp cp; + struct hci_request rq; + + memset(&cp, 0, sizeof(cp)); + bacpy(&cp.bdaddr, bdaddr); + cp.pkt_type = ptype; + cp.pscan_rep_mode = 0x02; + cp.clock_offset = clkoffset; + cp.role_switch = rswitch; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_LINK_CTL; + rq.ocf = OCF_CREATE_CONN; + rq.event = EVT_CONN_COMPLETE; + rq.cparam = &cp; + rq.clen = CREATE_CONN_CP_SIZE; + rq.rparam = &rp; + rq.rlen = EVT_CONN_COMPLETE_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + *handle = rp.handle; + return 0; +} + +int hci_disconnect(int dd, uint16_t handle, uint8_t reason, int to) +{ + evt_disconn_complete rp; + disconnect_cp cp; + struct hci_request rq; + + memset(&cp, 0, sizeof(cp)); + cp.handle = handle; + cp.reason = reason; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_LINK_CTL; + rq.ocf = OCF_DISCONNECT; + rq.event = EVT_DISCONN_COMPLETE; + rq.cparam = &cp; + rq.clen = DISCONNECT_CP_SIZE; + rq.rparam = &rp; + rq.rlen = EVT_DISCONN_COMPLETE_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + return 0; +} + +int hci_le_add_white_list(int dd, const bdaddr_t *bdaddr, uint8_t type, int to) +{ + struct hci_request rq; + le_add_device_to_white_list_cp cp; + uint8_t status; + + memset(&cp, 0, sizeof(cp)); + cp.bdaddr_type = type; + bacpy(&cp.bdaddr, bdaddr); + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_LE_CTL; + rq.ocf = OCF_LE_ADD_DEVICE_TO_WHITE_LIST; + rq.cparam = &cp; + rq.clen = LE_ADD_DEVICE_TO_WHITE_LIST_CP_SIZE; + rq.rparam = &status; + rq.rlen = 1; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (status) { + errno = EIO; + return -1; + } + + return 0; +} + +int hci_le_rm_white_list(int dd, const bdaddr_t *bdaddr, uint8_t type, int to) +{ + struct hci_request rq; + le_remove_device_from_white_list_cp cp; + uint8_t status; + + memset(&cp, 0, sizeof(cp)); + cp.bdaddr_type = type; + bacpy(&cp.bdaddr, bdaddr); + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_LE_CTL; + rq.ocf = OCF_LE_REMOVE_DEVICE_FROM_WHITE_LIST; + rq.cparam = &cp; + rq.clen = LE_REMOVE_DEVICE_FROM_WHITE_LIST_CP_SIZE; + rq.rparam = &status; + rq.rlen = 1; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (status) { + errno = EIO; + return -1; + } + + return 0; +} + +int hci_le_read_white_list_size(int dd, uint8_t *size, int to) +{ + struct hci_request rq; + le_read_white_list_size_rp rp; + + memset(&rp, 0, sizeof(rp)); + memset(&rq, 0, sizeof(rq)); + + rq.ogf = OGF_LE_CTL; + rq.ocf = OCF_LE_READ_WHITE_LIST_SIZE; + rq.rparam = &rp; + rq.rlen = LE_READ_WHITE_LIST_SIZE_RP_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + if (size) + *size = rp.size; + + return 0; +} + +int hci_le_clear_white_list(int dd, int to) +{ + struct hci_request rq; + uint8_t status; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_LE_CTL; + rq.ocf = OCF_LE_CLEAR_WHITE_LIST; + rq.rparam = &status; + rq.rlen = 1; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (status) { + errno = EIO; + return -1; + } + + return 0; +} + +int hci_read_local_name(int dd, int len, char *name, int to) +{ + read_local_name_rp rp; + struct hci_request rq; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_HOST_CTL; + rq.ocf = OCF_READ_LOCAL_NAME; + rq.rparam = &rp; + rq.rlen = READ_LOCAL_NAME_RP_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + rp.name[247] = '\0'; + strncpy(name, (char *) rp.name, len); + return 0; +} + +int hci_write_local_name(int dd, const char *name, int to) +{ + change_local_name_cp cp; + struct hci_request rq; + + memset(&cp, 0, sizeof(cp)); + strncpy((char *) cp.name, name, sizeof(cp.name)); + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_HOST_CTL; + rq.ocf = OCF_CHANGE_LOCAL_NAME; + rq.cparam = &cp; + rq.clen = CHANGE_LOCAL_NAME_CP_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + return 0; +} + +int hci_read_remote_name_with_clock_offset(int dd, const bdaddr_t *bdaddr, + uint8_t pscan_rep_mode, + uint16_t clkoffset, + int len, char *name, int to) +{ + evt_remote_name_req_complete rn; + remote_name_req_cp cp; + struct hci_request rq; + + memset(&cp, 0, sizeof(cp)); + bacpy(&cp.bdaddr, bdaddr); + cp.pscan_rep_mode = pscan_rep_mode; + cp.clock_offset = clkoffset; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_LINK_CTL; + rq.ocf = OCF_REMOTE_NAME_REQ; + rq.cparam = &cp; + rq.clen = REMOTE_NAME_REQ_CP_SIZE; + rq.event = EVT_REMOTE_NAME_REQ_COMPLETE; + rq.rparam = &rn; + rq.rlen = EVT_REMOTE_NAME_REQ_COMPLETE_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rn.status) { + errno = EIO; + return -1; + } + + rn.name[247] = '\0'; + strncpy(name, (char *) rn.name, len); + return 0; +} + +int hci_read_remote_name(int dd, const bdaddr_t *bdaddr, int len, char *name, + int to) +{ + return hci_read_remote_name_with_clock_offset(dd, bdaddr, 0x02, 0x0000, + len, name, to); +} + +int hci_read_remote_name_cancel(int dd, const bdaddr_t *bdaddr, int to) +{ + remote_name_req_cancel_cp cp; + struct hci_request rq; + + memset(&cp, 0, sizeof(cp)); + bacpy(&cp.bdaddr, bdaddr); + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_LINK_CTL; + rq.ocf = OCF_REMOTE_NAME_REQ_CANCEL; + rq.cparam = &cp; + rq.clen = REMOTE_NAME_REQ_CANCEL_CP_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + return 0; +} + +int hci_read_remote_version(int dd, uint16_t handle, struct hci_version *ver, + int to) +{ + evt_read_remote_version_complete rp; + read_remote_version_cp cp; + struct hci_request rq; + + memset(&cp, 0, sizeof(cp)); + cp.handle = handle; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_LINK_CTL; + rq.ocf = OCF_READ_REMOTE_VERSION; + rq.event = EVT_READ_REMOTE_VERSION_COMPLETE; + rq.cparam = &cp; + rq.clen = READ_REMOTE_VERSION_CP_SIZE; + rq.rparam = &rp; + rq.rlen = EVT_READ_REMOTE_VERSION_COMPLETE_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + ver->manufacturer = btohs(rp.manufacturer); + ver->lmp_ver = rp.lmp_ver; + ver->lmp_subver = btohs(rp.lmp_subver); + return 0; +} + +int hci_read_remote_features(int dd, uint16_t handle, uint8_t *features, int to) +{ + evt_read_remote_features_complete rp; + read_remote_features_cp cp; + struct hci_request rq; + + memset(&cp, 0, sizeof(cp)); + cp.handle = handle; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_LINK_CTL; + rq.ocf = OCF_READ_REMOTE_FEATURES; + rq.event = EVT_READ_REMOTE_FEATURES_COMPLETE; + rq.cparam = &cp; + rq.clen = READ_REMOTE_FEATURES_CP_SIZE; + rq.rparam = &rp; + rq.rlen = EVT_READ_REMOTE_FEATURES_COMPLETE_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + if (features) + memcpy(features, rp.features, 8); + + return 0; +} + +int hci_read_remote_ext_features(int dd, uint16_t handle, uint8_t page, + uint8_t *max_page, uint8_t *features, + int to) +{ + evt_read_remote_ext_features_complete rp; + read_remote_ext_features_cp cp; + struct hci_request rq; + + memset(&cp, 0, sizeof(cp)); + cp.handle = handle; + cp.page_num = page; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_LINK_CTL; + rq.ocf = OCF_READ_REMOTE_EXT_FEATURES; + rq.event = EVT_READ_REMOTE_EXT_FEATURES_COMPLETE; + rq.cparam = &cp; + rq.clen = READ_REMOTE_EXT_FEATURES_CP_SIZE; + rq.rparam = &rp; + rq.rlen = EVT_READ_REMOTE_EXT_FEATURES_COMPLETE_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + if (max_page) + *max_page = rp.max_page_num; + + if (features) + memcpy(features, rp.features, 8); + + return 0; +} + +int hci_read_clock_offset(int dd, uint16_t handle, uint16_t *clkoffset, int to) +{ + evt_read_clock_offset_complete rp; + read_clock_offset_cp cp; + struct hci_request rq; + + memset(&cp, 0, sizeof(cp)); + cp.handle = handle; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_LINK_CTL; + rq.ocf = OCF_READ_CLOCK_OFFSET; + rq.event = EVT_READ_CLOCK_OFFSET_COMPLETE; + rq.cparam = &cp; + rq.clen = READ_CLOCK_OFFSET_CP_SIZE; + rq.rparam = &rp; + rq.rlen = EVT_READ_CLOCK_OFFSET_COMPLETE_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + *clkoffset = rp.clock_offset; + return 0; +} + +int hci_read_local_version(int dd, struct hci_version *ver, int to) +{ + read_local_version_rp rp; + struct hci_request rq; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_INFO_PARAM; + rq.ocf = OCF_READ_LOCAL_VERSION; + rq.rparam = &rp; + rq.rlen = READ_LOCAL_VERSION_RP_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + ver->manufacturer = btohs(rp.manufacturer); + ver->hci_ver = rp.hci_ver; + ver->hci_rev = btohs(rp.hci_rev); + ver->lmp_ver = rp.lmp_ver; + ver->lmp_subver = btohs(rp.lmp_subver); + return 0; +} + +int hci_read_local_commands(int dd, uint8_t *commands, int to) +{ + read_local_commands_rp rp; + struct hci_request rq; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_INFO_PARAM; + rq.ocf = OCF_READ_LOCAL_COMMANDS; + rq.rparam = &rp; + rq.rlen = READ_LOCAL_COMMANDS_RP_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + if (commands) + memcpy(commands, rp.commands, 64); + + return 0; +} + +int hci_read_local_features(int dd, uint8_t *features, int to) +{ + read_local_features_rp rp; + struct hci_request rq; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_INFO_PARAM; + rq.ocf = OCF_READ_LOCAL_FEATURES; + rq.rparam = &rp; + rq.rlen = READ_LOCAL_FEATURES_RP_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + if (features) + memcpy(features, rp.features, 8); + + return 0; +} + +int hci_read_local_ext_features(int dd, uint8_t page, uint8_t *max_page, + uint8_t *features, int to) +{ + read_local_ext_features_cp cp; + read_local_ext_features_rp rp; + struct hci_request rq; + + cp.page_num = page; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_INFO_PARAM; + rq.ocf = OCF_READ_LOCAL_EXT_FEATURES; + rq.cparam = &cp; + rq.clen = READ_LOCAL_EXT_FEATURES_CP_SIZE; + rq.rparam = &rp; + rq.rlen = READ_LOCAL_EXT_FEATURES_RP_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + if (max_page) + *max_page = rp.max_page_num; + + if (features) + memcpy(features, rp.features, 8); + + return 0; +} + +int hci_read_bd_addr(int dd, bdaddr_t *bdaddr, int to) +{ + read_bd_addr_rp rp; + struct hci_request rq; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_INFO_PARAM; + rq.ocf = OCF_READ_BD_ADDR; + rq.rparam = &rp; + rq.rlen = READ_BD_ADDR_RP_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + if (bdaddr) + bacpy(bdaddr, &rp.bdaddr); + + return 0; +} + +int hci_read_class_of_dev(int dd, uint8_t *cls, int to) +{ + read_class_of_dev_rp rp; + struct hci_request rq; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_HOST_CTL; + rq.ocf = OCF_READ_CLASS_OF_DEV; + rq.rparam = &rp; + rq.rlen = READ_CLASS_OF_DEV_RP_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + memcpy(cls, rp.dev_class, 3); + return 0; +} + +int hci_write_class_of_dev(int dd, uint32_t cls, int to) +{ + write_class_of_dev_cp cp; + struct hci_request rq; + + memset(&rq, 0, sizeof(rq)); + cp.dev_class[0] = cls & 0xff; + cp.dev_class[1] = (cls >> 8) & 0xff; + cp.dev_class[2] = (cls >> 16) & 0xff; + rq.ogf = OGF_HOST_CTL; + rq.ocf = OCF_WRITE_CLASS_OF_DEV; + rq.cparam = &cp; + rq.clen = WRITE_CLASS_OF_DEV_CP_SIZE; + return hci_send_req(dd, &rq, to); +} + +int hci_read_voice_setting(int dd, uint16_t *vs, int to) +{ + read_voice_setting_rp rp; + struct hci_request rq; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_HOST_CTL; + rq.ocf = OCF_READ_VOICE_SETTING; + rq.rparam = &rp; + rq.rlen = READ_VOICE_SETTING_RP_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + *vs = rp.voice_setting; + return 0; +} + +int hci_write_voice_setting(int dd, uint16_t vs, int to) +{ + write_voice_setting_cp cp; + struct hci_request rq; + + memset(&rq, 0, sizeof(rq)); + cp.voice_setting = vs; + rq.ogf = OGF_HOST_CTL; + rq.ocf = OCF_WRITE_VOICE_SETTING; + rq.cparam = &cp; + rq.clen = WRITE_VOICE_SETTING_CP_SIZE; + + return hci_send_req(dd, &rq, to); +} + +int hci_read_current_iac_lap(int dd, uint8_t *num_iac, uint8_t *lap, int to) +{ + read_current_iac_lap_rp rp; + struct hci_request rq; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_HOST_CTL; + rq.ocf = OCF_READ_CURRENT_IAC_LAP; + rq.rparam = &rp; + rq.rlen = READ_CURRENT_IAC_LAP_RP_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + *num_iac = rp.num_current_iac; + memcpy(lap, rp.lap, rp.num_current_iac * 3); + return 0; +} + +int hci_write_current_iac_lap(int dd, uint8_t num_iac, uint8_t *lap, int to) +{ + write_current_iac_lap_cp cp; + struct hci_request rq; + + memset(&cp, 0, sizeof(cp)); + cp.num_current_iac = num_iac; + memcpy(&cp.lap, lap, num_iac * 3); + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_HOST_CTL; + rq.ocf = OCF_WRITE_CURRENT_IAC_LAP; + rq.cparam = &cp; + rq.clen = num_iac * 3 + 1; + + return hci_send_req(dd, &rq, to); +} + +int hci_read_stored_link_key(int dd, bdaddr_t *bdaddr, uint8_t all, int to) +{ + read_stored_link_key_cp cp; + struct hci_request rq; + + memset(&cp, 0, sizeof(cp)); + bacpy(&cp.bdaddr, bdaddr); + cp.read_all = all; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_HOST_CTL; + rq.ocf = OCF_READ_STORED_LINK_KEY; + rq.cparam = &cp; + rq.clen = READ_STORED_LINK_KEY_CP_SIZE; + + return hci_send_req(dd, &rq, to); +} + +int hci_write_stored_link_key(int dd, bdaddr_t *bdaddr, uint8_t *key, int to) +{ + unsigned char cp[WRITE_STORED_LINK_KEY_CP_SIZE + 6 + 16]; + struct hci_request rq; + + memset(&cp, 0, sizeof(cp)); + cp[0] = 1; + bacpy((bdaddr_t *) (cp + 1), bdaddr); + memcpy(cp + 7, key, 16); + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_HOST_CTL; + rq.ocf = OCF_WRITE_STORED_LINK_KEY; + rq.cparam = &cp; + rq.clen = WRITE_STORED_LINK_KEY_CP_SIZE + 6 + 16; + + return hci_send_req(dd, &rq, to); +} + +int hci_delete_stored_link_key(int dd, bdaddr_t *bdaddr, uint8_t all, int to) +{ + delete_stored_link_key_cp cp; + struct hci_request rq; + + memset(&cp, 0, sizeof(cp)); + bacpy(&cp.bdaddr, bdaddr); + cp.delete_all = all; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_HOST_CTL; + rq.ocf = OCF_DELETE_STORED_LINK_KEY; + rq.cparam = &cp; + rq.clen = DELETE_STORED_LINK_KEY_CP_SIZE; + + return hci_send_req(dd, &rq, to); +} + +int hci_authenticate_link(int dd, uint16_t handle, int to) +{ + auth_requested_cp cp; + evt_auth_complete rp; + struct hci_request rq; + + cp.handle = handle; + + rq.ogf = OGF_LINK_CTL; + rq.ocf = OCF_AUTH_REQUESTED; + rq.event = EVT_AUTH_COMPLETE; + rq.cparam = &cp; + rq.clen = AUTH_REQUESTED_CP_SIZE; + rq.rparam = &rp; + rq.rlen = EVT_AUTH_COMPLETE_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + return 0; +} + +int hci_encrypt_link(int dd, uint16_t handle, uint8_t encrypt, int to) +{ + set_conn_encrypt_cp cp; + evt_encrypt_change rp; + struct hci_request rq; + + cp.handle = handle; + cp.encrypt = encrypt; + + rq.ogf = OGF_LINK_CTL; + rq.ocf = OCF_SET_CONN_ENCRYPT; + rq.event = EVT_ENCRYPT_CHANGE; + rq.cparam = &cp; + rq.clen = SET_CONN_ENCRYPT_CP_SIZE; + rq.rparam = &rp; + rq.rlen = EVT_ENCRYPT_CHANGE_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + return 0; +} + +int hci_change_link_key(int dd, uint16_t handle, int to) +{ + change_conn_link_key_cp cp; + evt_change_conn_link_key_complete rp; + struct hci_request rq; + + cp.handle = handle; + + rq.ogf = OGF_LINK_CTL; + rq.ocf = OCF_CHANGE_CONN_LINK_KEY; + rq.event = EVT_CHANGE_CONN_LINK_KEY_COMPLETE; + rq.cparam = &cp; + rq.clen = CHANGE_CONN_LINK_KEY_CP_SIZE; + rq.rparam = &rp; + rq.rlen = EVT_CHANGE_CONN_LINK_KEY_COMPLETE_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + return 0; +} + +int hci_switch_role(int dd, bdaddr_t *bdaddr, uint8_t role, int to) +{ + switch_role_cp cp; + evt_role_change rp; + struct hci_request rq; + + bacpy(&cp.bdaddr, bdaddr); + cp.role = role; + rq.ogf = OGF_LINK_POLICY; + rq.ocf = OCF_SWITCH_ROLE; + rq.cparam = &cp; + rq.clen = SWITCH_ROLE_CP_SIZE; + rq.rparam = &rp; + rq.rlen = EVT_ROLE_CHANGE_SIZE; + rq.event = EVT_ROLE_CHANGE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + return 0; +} + +int hci_park_mode(int dd, uint16_t handle, uint16_t max_interval, + uint16_t min_interval, int to) +{ + park_mode_cp cp; + evt_mode_change rp; + struct hci_request rq; + + memset(&cp, 0, sizeof (cp)); + cp.handle = handle; + cp.max_interval = max_interval; + cp.min_interval = min_interval; + + memset(&rq, 0, sizeof (rq)); + rq.ogf = OGF_LINK_POLICY; + rq.ocf = OCF_PARK_MODE; + rq.event = EVT_MODE_CHANGE; + rq.cparam = &cp; + rq.clen = PARK_MODE_CP_SIZE; + rq.rparam = &rp; + rq.rlen = EVT_MODE_CHANGE_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + return 0; +} + +int hci_exit_park_mode(int dd, uint16_t handle, int to) +{ + exit_park_mode_cp cp; + evt_mode_change rp; + struct hci_request rq; + + memset(&cp, 0, sizeof (cp)); + cp.handle = handle; + + memset (&rq, 0, sizeof (rq)); + rq.ogf = OGF_LINK_POLICY; + rq.ocf = OCF_EXIT_PARK_MODE; + rq.event = EVT_MODE_CHANGE; + rq.cparam = &cp; + rq.clen = EXIT_PARK_MODE_CP_SIZE; + rq.rparam = &rp; + rq.rlen = EVT_MODE_CHANGE_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + return 0; +} + +int hci_read_inquiry_scan_type(int dd, uint8_t *type, int to) +{ + read_inquiry_scan_type_rp rp; + struct hci_request rq; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_HOST_CTL; + rq.ocf = OCF_READ_INQUIRY_SCAN_TYPE; + rq.rparam = &rp; + rq.rlen = READ_INQUIRY_SCAN_TYPE_RP_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + *type = rp.type; + return 0; +} + +int hci_write_inquiry_scan_type(int dd, uint8_t type, int to) +{ + write_inquiry_scan_type_cp cp; + write_inquiry_scan_type_rp rp; + struct hci_request rq; + + memset(&cp, 0, sizeof(cp)); + cp.type = type; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_HOST_CTL; + rq.ocf = OCF_WRITE_INQUIRY_SCAN_TYPE; + rq.cparam = &cp; + rq.clen = WRITE_INQUIRY_SCAN_TYPE_CP_SIZE; + rq.rparam = &rp; + rq.rlen = WRITE_INQUIRY_SCAN_TYPE_RP_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + return 0; +} + +int hci_read_inquiry_mode(int dd, uint8_t *mode, int to) +{ + read_inquiry_mode_rp rp; + struct hci_request rq; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_HOST_CTL; + rq.ocf = OCF_READ_INQUIRY_MODE; + rq.rparam = &rp; + rq.rlen = READ_INQUIRY_MODE_RP_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + *mode = rp.mode; + return 0; +} + +int hci_write_inquiry_mode(int dd, uint8_t mode, int to) +{ + write_inquiry_mode_cp cp; + write_inquiry_mode_rp rp; + struct hci_request rq; + + memset(&cp, 0, sizeof(cp)); + cp.mode = mode; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_HOST_CTL; + rq.ocf = OCF_WRITE_INQUIRY_MODE; + rq.cparam = &cp; + rq.clen = WRITE_INQUIRY_MODE_CP_SIZE; + rq.rparam = &rp; + rq.rlen = WRITE_INQUIRY_MODE_RP_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + return 0; +} + +int hci_read_afh_mode(int dd, uint8_t *mode, int to) +{ + read_afh_mode_rp rp; + struct hci_request rq; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_HOST_CTL; + rq.ocf = OCF_READ_AFH_MODE; + rq.rparam = &rp; + rq.rlen = READ_AFH_MODE_RP_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + *mode = rp.mode; + return 0; +} + +int hci_write_afh_mode(int dd, uint8_t mode, int to) +{ + write_afh_mode_cp cp; + write_afh_mode_rp rp; + struct hci_request rq; + + memset(&cp, 0, sizeof(cp)); + cp.mode = mode; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_HOST_CTL; + rq.ocf = OCF_WRITE_AFH_MODE; + rq.cparam = &cp; + rq.clen = WRITE_AFH_MODE_CP_SIZE; + rq.rparam = &rp; + rq.rlen = WRITE_AFH_MODE_RP_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + return 0; +} + +int hci_read_ext_inquiry_response(int dd, uint8_t *fec, uint8_t *data, int to) +{ + read_ext_inquiry_response_rp rp; + struct hci_request rq; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_HOST_CTL; + rq.ocf = OCF_READ_EXT_INQUIRY_RESPONSE; + rq.rparam = &rp; + rq.rlen = READ_EXT_INQUIRY_RESPONSE_RP_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + *fec = rp.fec; + memcpy(data, rp.data, HCI_MAX_EIR_LENGTH); + + return 0; +} + +int hci_write_ext_inquiry_response(int dd, uint8_t fec, uint8_t *data, int to) +{ + write_ext_inquiry_response_cp cp; + write_ext_inquiry_response_rp rp; + struct hci_request rq; + + memset(&cp, 0, sizeof(cp)); + cp.fec = fec; + memcpy(cp.data, data, HCI_MAX_EIR_LENGTH); + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_HOST_CTL; + rq.ocf = OCF_WRITE_EXT_INQUIRY_RESPONSE; + rq.cparam = &cp; + rq.clen = WRITE_EXT_INQUIRY_RESPONSE_CP_SIZE; + rq.rparam = &rp; + rq.rlen = WRITE_EXT_INQUIRY_RESPONSE_RP_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + return 0; +} + +int hci_read_simple_pairing_mode(int dd, uint8_t *mode, int to) +{ + read_simple_pairing_mode_rp rp; + struct hci_request rq; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_HOST_CTL; + rq.ocf = OCF_READ_SIMPLE_PAIRING_MODE; + rq.rparam = &rp; + rq.rlen = READ_SIMPLE_PAIRING_MODE_RP_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + *mode = rp.mode; + return 0; +} + +int hci_write_simple_pairing_mode(int dd, uint8_t mode, int to) +{ + write_simple_pairing_mode_cp cp; + write_simple_pairing_mode_rp rp; + struct hci_request rq; + + memset(&cp, 0, sizeof(cp)); + cp.mode = mode; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_HOST_CTL; + rq.ocf = OCF_WRITE_SIMPLE_PAIRING_MODE; + rq.cparam = &cp; + rq.clen = WRITE_SIMPLE_PAIRING_MODE_CP_SIZE; + rq.rparam = &rp; + rq.rlen = WRITE_SIMPLE_PAIRING_MODE_RP_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + return 0; +} + +int hci_read_local_oob_data(int dd, uint8_t *hash, uint8_t *randomizer, int to) +{ + read_local_oob_data_rp rp; + struct hci_request rq; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_HOST_CTL; + rq.ocf = OCF_READ_LOCAL_OOB_DATA; + rq.rparam = &rp; + rq.rlen = READ_LOCAL_OOB_DATA_RP_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + memcpy(hash, rp.hash, 16); + memcpy(randomizer, rp.randomizer, 16); + return 0; +} + +int hci_read_inq_response_tx_power_level(int dd, int8_t *level, int to) +{ + read_inq_response_tx_power_level_rp rp; + struct hci_request rq; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_HOST_CTL; + rq.ocf = OCF_READ_INQ_RESPONSE_TX_POWER_LEVEL; + rq.rparam = &rp; + rq.rlen = READ_INQ_RESPONSE_TX_POWER_LEVEL_RP_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + *level = rp.level; + return 0; +} + +int hci_read_inquiry_transmit_power_level(int dd, int8_t *level, int to) +{ + return hci_read_inq_response_tx_power_level(dd, level, to); +} + +int hci_write_inquiry_transmit_power_level(int dd, int8_t level, int to) +{ + write_inquiry_transmit_power_level_cp cp; + write_inquiry_transmit_power_level_rp rp; + struct hci_request rq; + + memset(&cp, 0, sizeof(cp)); + cp.level = level; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_HOST_CTL; + rq.ocf = OCF_WRITE_INQUIRY_TRANSMIT_POWER_LEVEL; + rq.cparam = &cp; + rq.clen = WRITE_INQUIRY_TRANSMIT_POWER_LEVEL_CP_SIZE; + rq.rparam = &rp; + rq.rlen = WRITE_INQUIRY_TRANSMIT_POWER_LEVEL_RP_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + return 0; +} + +int hci_read_transmit_power_level(int dd, uint16_t handle, uint8_t type, + int8_t *level, int to) +{ + read_transmit_power_level_cp cp; + read_transmit_power_level_rp rp; + struct hci_request rq; + + memset(&cp, 0, sizeof(cp)); + cp.handle = handle; + cp.type = type; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_HOST_CTL; + rq.ocf = OCF_READ_TRANSMIT_POWER_LEVEL; + rq.cparam = &cp; + rq.clen = READ_TRANSMIT_POWER_LEVEL_CP_SIZE; + rq.rparam = &rp; + rq.rlen = READ_TRANSMIT_POWER_LEVEL_RP_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + *level = rp.level; + return 0; +} + +int hci_read_link_policy(int dd, uint16_t handle, uint16_t *policy, int to) +{ + read_link_policy_rp rp; + struct hci_request rq; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_LINK_POLICY; + rq.ocf = OCF_READ_LINK_POLICY; + rq.cparam = &handle; + rq.clen = 2; + rq.rparam = &rp; + rq.rlen = READ_LINK_POLICY_RP_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + *policy = rp.policy; + return 0; +} + +int hci_write_link_policy(int dd, uint16_t handle, uint16_t policy, int to) +{ + write_link_policy_cp cp; + write_link_policy_rp rp; + struct hci_request rq; + + memset(&cp, 0, sizeof(cp)); + cp.handle = handle; + cp.policy = policy; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_LINK_POLICY; + rq.ocf = OCF_WRITE_LINK_POLICY; + rq.cparam = &cp; + rq.clen = WRITE_LINK_POLICY_CP_SIZE; + rq.rparam = &rp; + rq.rlen = WRITE_LINK_POLICY_RP_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + return 0; +} + +int hci_read_link_supervision_timeout(int dd, uint16_t handle, + uint16_t *timeout, int to) +{ + read_link_supervision_timeout_rp rp; + struct hci_request rq; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_HOST_CTL; + rq.ocf = OCF_READ_LINK_SUPERVISION_TIMEOUT; + rq.cparam = &handle; + rq.clen = 2; + rq.rparam = &rp; + rq.rlen = READ_LINK_SUPERVISION_TIMEOUT_RP_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + *timeout = rp.timeout; + return 0; +} + +int hci_write_link_supervision_timeout(int dd, uint16_t handle, + uint16_t timeout, int to) +{ + write_link_supervision_timeout_cp cp; + write_link_supervision_timeout_rp rp; + struct hci_request rq; + + memset(&cp, 0, sizeof(cp)); + cp.handle = handle; + cp.timeout = timeout; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_HOST_CTL; + rq.ocf = OCF_WRITE_LINK_SUPERVISION_TIMEOUT; + rq.cparam = &cp; + rq.clen = WRITE_LINK_SUPERVISION_TIMEOUT_CP_SIZE; + rq.rparam = &rp; + rq.rlen = WRITE_LINK_SUPERVISION_TIMEOUT_RP_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + return 0; +} + +int hci_set_afh_classification(int dd, uint8_t *map, int to) +{ + set_afh_classification_cp cp; + set_afh_classification_rp rp; + struct hci_request rq; + + memset(&cp, 0, sizeof(cp)); + memcpy(cp.map, map, 10); + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_HOST_CTL; + rq.ocf = OCF_SET_AFH_CLASSIFICATION; + rq.cparam = &cp; + rq.clen = SET_AFH_CLASSIFICATION_CP_SIZE; + rq.rparam = &rp; + rq.rlen = SET_AFH_CLASSIFICATION_RP_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + return 0; +} + +int hci_read_link_quality(int dd, uint16_t handle, uint8_t *link_quality, + int to) +{ + read_link_quality_rp rp; + struct hci_request rq; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_STATUS_PARAM; + rq.ocf = OCF_READ_LINK_QUALITY; + rq.cparam = &handle; + rq.clen = 2; + rq.rparam = &rp; + rq.rlen = READ_LINK_QUALITY_RP_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + *link_quality = rp.link_quality; + return 0; +} + +int hci_read_rssi(int dd, uint16_t handle, int8_t *rssi, int to) +{ + read_rssi_rp rp; + struct hci_request rq; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_STATUS_PARAM; + rq.ocf = OCF_READ_RSSI; + rq.cparam = &handle; + rq.clen = 2; + rq.rparam = &rp; + rq.rlen = READ_RSSI_RP_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + *rssi = rp.rssi; + return 0; +} + +int hci_read_afh_map(int dd, uint16_t handle, uint8_t *mode, uint8_t *map, + int to) +{ + read_afh_map_rp rp; + struct hci_request rq; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_STATUS_PARAM; + rq.ocf = OCF_READ_AFH_MAP; + rq.cparam = &handle; + rq.clen = 2; + rq.rparam = &rp; + rq.rlen = READ_AFH_MAP_RP_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + *mode = rp.mode; + memcpy(map, rp.map, 10); + return 0; +} + +int hci_read_clock(int dd, uint16_t handle, uint8_t which, uint32_t *clock, + uint16_t *accuracy, int to) +{ + read_clock_cp cp; + read_clock_rp rp; + struct hci_request rq; + + memset(&cp, 0, sizeof(cp)); + cp.handle = handle; + cp.which_clock = which; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_STATUS_PARAM; + rq.ocf = OCF_READ_CLOCK; + rq.cparam = &cp; + rq.clen = READ_CLOCK_CP_SIZE; + rq.rparam = &rp; + rq.rlen = READ_CLOCK_RP_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (rp.status) { + errno = EIO; + return -1; + } + + *clock = rp.clock; + *accuracy = rp.accuracy; + return 0; +} + +int hci_le_set_scan_enable(int dd, uint8_t enable, uint8_t filter_dup, int to) +{ + struct hci_request rq; + le_set_scan_enable_cp scan_cp; + uint8_t status; + + memset(&scan_cp, 0, sizeof(scan_cp)); + scan_cp.enable = enable; + scan_cp.filter_dup = filter_dup; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_LE_CTL; + rq.ocf = OCF_LE_SET_SCAN_ENABLE; + rq.cparam = &scan_cp; + rq.clen = LE_SET_SCAN_ENABLE_CP_SIZE; + rq.rparam = &status; + rq.rlen = 1; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (status) { + errno = EIO; + return -1; + } + + return 0; +} + +int hci_le_set_scan_parameters(int dd, uint8_t type, + uint16_t interval, uint16_t window, + uint8_t own_type, uint8_t filter, int to) +{ + struct hci_request rq; + le_set_scan_parameters_cp param_cp; + uint8_t status; + + memset(¶m_cp, 0, sizeof(param_cp)); + param_cp.type = type; + param_cp.interval = interval; + param_cp.window = window; + param_cp.own_bdaddr_type = own_type; + param_cp.filter = filter; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_LE_CTL; + rq.ocf = OCF_LE_SET_SCAN_PARAMETERS; + rq.cparam = ¶m_cp; + rq.clen = LE_SET_SCAN_PARAMETERS_CP_SIZE; + rq.rparam = &status; + rq.rlen = 1; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (status) { + errno = EIO; + return -1; + } + + return 0; +} + +int hci_le_set_advertise_enable(int dd, uint8_t enable, int to) +{ + struct hci_request rq; + le_set_advertise_enable_cp adv_cp; + uint8_t status; + + memset(&adv_cp, 0, sizeof(adv_cp)); + adv_cp.enable = enable; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_LE_CTL; + rq.ocf = OCF_LE_SET_ADVERTISE_ENABLE; + rq.cparam = &adv_cp; + rq.clen = LE_SET_ADVERTISE_ENABLE_CP_SIZE; + rq.rparam = &status; + rq.rlen = 1; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (status) { + errno = EIO; + return -1; + } + + return 0; +} + +int hci_le_create_conn(int dd, uint16_t interval, uint16_t window, + uint8_t initiator_filter, uint8_t peer_bdaddr_type, + bdaddr_t peer_bdaddr, uint8_t own_bdaddr_type, + uint16_t min_interval, uint16_t max_interval, + uint16_t latency, uint16_t supervision_timeout, + uint16_t min_ce_length, uint16_t max_ce_length, + uint16_t *handle, int to) +{ + struct hci_request rq; + le_create_connection_cp create_conn_cp; + evt_le_connection_complete conn_complete_rp; + + memset(&create_conn_cp, 0, sizeof(create_conn_cp)); + create_conn_cp.interval = interval; + create_conn_cp.window = window; + create_conn_cp.initiator_filter = initiator_filter; + create_conn_cp.peer_bdaddr_type = peer_bdaddr_type; + create_conn_cp.peer_bdaddr = peer_bdaddr; + create_conn_cp.own_bdaddr_type = own_bdaddr_type; + create_conn_cp.min_interval = min_interval; + create_conn_cp.max_interval = max_interval; + create_conn_cp.latency = latency; + create_conn_cp.supervision_timeout = supervision_timeout; + create_conn_cp.min_ce_length = min_ce_length; + create_conn_cp.max_ce_length = max_ce_length; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_LE_CTL; + rq.ocf = OCF_LE_CREATE_CONN; + rq.event = EVT_LE_CONN_COMPLETE; + rq.cparam = &create_conn_cp; + rq.clen = LE_CREATE_CONN_CP_SIZE; + rq.rparam = &conn_complete_rp; + rq.rlen = EVT_CONN_COMPLETE_SIZE; + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (conn_complete_rp.status) { + errno = EIO; + return -1; + } + + if (handle) + *handle = conn_complete_rp.handle; + + return 0; +} + +int hci_le_conn_update(int dd, uint16_t handle, uint16_t min_interval, + uint16_t max_interval, uint16_t latency, + uint16_t supervision_timeout, int to) +{ + evt_le_connection_update_complete evt; + le_connection_update_cp cp; + struct hci_request rq; + + memset(&cp, 0, sizeof(cp)); + cp.handle = handle; + cp.min_interval = min_interval; + cp.max_interval = max_interval; + cp.latency = latency; + cp.supervision_timeout = supervision_timeout; + cp.min_ce_length = htobs(0x0001); + cp.max_ce_length = htobs(0x0001); + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_LE_CTL; + rq.ocf = OCF_LE_CONN_UPDATE; + rq.cparam = &cp; + rq.clen = LE_CONN_UPDATE_CP_SIZE; + rq.event = EVT_LE_CONN_UPDATE_COMPLETE; + rq.rparam = &evt; + rq.rlen = sizeof(evt); + + if (hci_send_req(dd, &rq, to) < 0) + return -1; + + if (evt.status) { + errno = EIO; + return -1; + } + + return 0; +} diff --git a/drive-sdk/deps/bzle/src/log.c b/drive-sdk/deps/bzle/src/log.c new file mode 100644 index 0000000..19b3450 --- /dev/null +++ b/drive-sdk/deps/bzle/src/log.c @@ -0,0 +1,146 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2004-2010 Marcel Holtmann + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include +#include + +#include + +#include "log.h" + +#define VERSION "5.15" + +void info(const char *format, ...) +{ + va_list ap; + + va_start(ap, format); + + vsyslog(LOG_INFO, format, ap); + + va_end(ap); +} + +void warn(const char *format, ...) +{ + va_list ap; + + va_start(ap, format); + + vsyslog(LOG_WARNING, format, ap); + + va_end(ap); +} + +void error(const char *format, ...) +{ + va_list ap; + + va_start(ap, format); + + vsyslog(LOG_ERR, format, ap); + + va_end(ap); +} + +void btd_debug(const char *format, ...) +{ + va_list ap; + + va_start(ap, format); + + vsyslog(LOG_DEBUG, format, ap); + + va_end(ap); +} + +extern struct btd_debug_desc __start___debug[]; +extern struct btd_debug_desc __stop___debug[]; + +static char **enabled = NULL; + +static gboolean is_enabled(struct btd_debug_desc *desc) +{ + int i; + + if (enabled == NULL) + return 0; + + for (i = 0; enabled[i] != NULL; i++) + if (desc->file != NULL && g_pattern_match_simple(enabled[i], + desc->file) == TRUE) + return 1; + + return 0; +} + +void __btd_enable_debug(struct btd_debug_desc *start, + struct btd_debug_desc *stop) +{ + struct btd_debug_desc *desc; + + if (start == NULL || stop == NULL) + return; + + for (desc = start; desc < stop; desc++) { + if (is_enabled(desc)) + desc->flags |= BTD_DEBUG_FLAG_PRINT; + } +} + +void __btd_toggle_debug(void) +{ + struct btd_debug_desc *desc; + + for (desc = __start___debug; desc < __stop___debug; desc++) + desc->flags |= BTD_DEBUG_FLAG_PRINT; +} + +void __btd_log_init(const char *debug, int detach) +{ + int option = LOG_NDELAY | LOG_PID; + + if (debug != NULL) + enabled = g_strsplit_set(debug, ":, ", 0); + + __btd_enable_debug(__start___debug, __stop___debug); + + if (!detach) + option |= LOG_PERROR; + + openlog("bluetoothd", option, LOG_DAEMON); + + syslog(LOG_INFO, "Bluetooth daemon %s", VERSION); +} + +void __btd_log_cleanup(void) +{ + closelog(); + + g_strfreev(enabled); +} diff --git a/drive-sdk/deps/bzle/src/log.h b/drive-sdk/deps/bzle/src/log.h new file mode 100644 index 0000000..bf9eac2 --- /dev/null +++ b/drive-sdk/deps/bzle/src/log.h @@ -0,0 +1,59 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2004-2010 Marcel Holtmann + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +void info(const char *format, ...) __attribute__((format(printf, 1, 2))); +void warn(const char *format, ...) __attribute__((format(printf, 1, 2))); +void error(const char *format, ...) __attribute__((format(printf, 1, 2))); + +void btd_debug(const char *format, ...) __attribute__((format(printf, 1, 2))); + +void __btd_log_init(const char *debug, int detach); +void __btd_log_cleanup(void); +void __btd_toggle_debug(void); + +struct btd_debug_desc { + const char *file; +#define BTD_DEBUG_FLAG_DEFAULT (0) +#define BTD_DEBUG_FLAG_PRINT (1 << 0) + unsigned int flags; +} __attribute__((aligned(8))); + +void __btd_enable_debug(struct btd_debug_desc *start, + struct btd_debug_desc *stop); + +/** + * DBG: + * @fmt: format string + * @arg...: list of arguments + * + * Simple macro around btd_debug() which also include the function + * name it is called in. + */ +#define DBG(fmt, arg...) do { \ + static struct btd_debug_desc __btd_debug_desc \ + __attribute__((used, section("__debug"), aligned(8))) = { \ + .file = __FILE__, .flags = BTD_DEBUG_FLAG_DEFAULT, \ + }; \ + if (__btd_debug_desc.flags & BTD_DEBUG_FLAG_PRINT) \ + btd_debug("%s:%s() " fmt, __FILE__, __func__ , ## arg); \ +} while (0) diff --git a/drive-sdk/deps/bzle/src/sdp.c b/drive-sdk/deps/bzle/src/sdp.c new file mode 100644 index 0000000..1b0939e --- /dev/null +++ b/drive-sdk/deps/bzle/src/sdp.c @@ -0,0 +1,4940 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2001-2002 Nokia Corporation + * Copyright (C) 2002-2003 Maxim Krasnyansky + * Copyright (C) 2002-2010 Marcel Holtmann + * Copyright (C) 2002-2003 Stephen Crane + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#define SDPINF(fmt, arg...) syslog(LOG_INFO, fmt "\n", ## arg) +#define SDPERR(fmt, arg...) syslog(LOG_ERR, "%s: " fmt "\n", __func__ , ## arg) + +#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0])) + +#ifdef SDP_DEBUG +#define SDPDBG(fmt, arg...) syslog(LOG_DEBUG, "%s: " fmt "\n", __func__ , ## arg) +#else +#define SDPDBG(fmt...) +#endif + +static uint128_t bluetooth_base_uuid = { + .data = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, + 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB } +}; + +#define SDP_MAX_ATTR_LEN 65535 + +/* match MTU used by RFCOMM */ +#define SDP_LARGE_L2CAP_MTU 1013 + +static sdp_data_t *sdp_copy_seq(sdp_data_t *data); +static int sdp_attr_add_new_with_length(sdp_record_t *rec, + uint16_t attr, uint8_t dtd, const void *value, uint32_t len); +static int sdp_gen_buffer(sdp_buf_t *buf, sdp_data_t *d); + +/* Message structure. */ +struct tupla { + int index; + char *str; +}; + +static struct tupla Protocol[] = { + { SDP_UUID, "SDP" }, + { UDP_UUID, "UDP" }, + { RFCOMM_UUID, "RFCOMM" }, + { TCP_UUID, "TCP" }, + { TCS_BIN_UUID, "TCS-BIN" }, + { TCS_AT_UUID, "TCS-AT" }, + { OBEX_UUID, "OBEX" }, + { IP_UUID, "IP" }, + { FTP_UUID, "FTP" }, + { HTTP_UUID, "HTTP" }, + { WSP_UUID, "WSP" }, + { BNEP_UUID, "BNEP" }, + { UPNP_UUID, "UPNP" }, + { HIDP_UUID, "HIDP" }, + { HCRP_CTRL_UUID, "HCRP-Ctrl" }, + { HCRP_DATA_UUID, "HCRP-Data" }, + { HCRP_NOTE_UUID, "HCRP-Notify" }, + { AVCTP_UUID, "AVCTP" }, + { AVDTP_UUID, "AVDTP" }, + { CMTP_UUID, "CMTP" }, + { UDI_UUID, "UDI" }, + { MCAP_CTRL_UUID, "MCAP-Ctrl" }, + { MCAP_DATA_UUID, "MCAP-Data" }, + { L2CAP_UUID, "L2CAP" }, + { ATT_UUID, "ATT" }, + { 0 } +}; + +static struct tupla ServiceClass[] = { + { SDP_SERVER_SVCLASS_ID, "SDP Server" }, + { BROWSE_GRP_DESC_SVCLASS_ID, "Browse Group Descriptor" }, + { PUBLIC_BROWSE_GROUP, "Public Browse Group" }, + { SERIAL_PORT_SVCLASS_ID, "Serial Port" }, + { LAN_ACCESS_SVCLASS_ID, "LAN Access Using PPP" }, + { DIALUP_NET_SVCLASS_ID, "Dialup Networking" }, + { IRMC_SYNC_SVCLASS_ID, "IrMC Sync" }, + { OBEX_OBJPUSH_SVCLASS_ID, "OBEX Object Push" }, + { OBEX_FILETRANS_SVCLASS_ID, "OBEX File Transfer" }, + { IRMC_SYNC_CMD_SVCLASS_ID, "IrMC Sync Command" }, + { HEADSET_SVCLASS_ID, "Headset" }, + { CORDLESS_TELEPHONY_SVCLASS_ID, "Cordless Telephony" }, + { AUDIO_SOURCE_SVCLASS_ID, "Audio Source" }, + { AUDIO_SINK_SVCLASS_ID, "Audio Sink" }, + { AV_REMOTE_TARGET_SVCLASS_ID, "AV Remote Target" }, + { ADVANCED_AUDIO_SVCLASS_ID, "Advanced Audio" }, + { AV_REMOTE_SVCLASS_ID, "AV Remote" }, + { AV_REMOTE_CONTROLLER_SVCLASS_ID, "AV Remote Controller" }, + { INTERCOM_SVCLASS_ID, "Intercom" }, + { FAX_SVCLASS_ID, "Fax" }, + { HEADSET_AGW_SVCLASS_ID, "Headset Audio Gateway" }, + { WAP_SVCLASS_ID, "WAP" }, + { WAP_CLIENT_SVCLASS_ID, "WAP Client" }, + { PANU_SVCLASS_ID, "PAN User" }, + { NAP_SVCLASS_ID, "Network Access Point" }, + { GN_SVCLASS_ID, "PAN Group Network" }, + { DIRECT_PRINTING_SVCLASS_ID, "Direct Printing" }, + { REFERENCE_PRINTING_SVCLASS_ID, "Reference Printing" }, + { IMAGING_SVCLASS_ID, "Imaging" }, + { IMAGING_RESPONDER_SVCLASS_ID, "Imaging Responder" }, + { IMAGING_ARCHIVE_SVCLASS_ID, "Imaging Automatic Archive" }, + { IMAGING_REFOBJS_SVCLASS_ID, "Imaging Referenced Objects" }, + { HANDSFREE_SVCLASS_ID, "Handsfree" }, + { HANDSFREE_AGW_SVCLASS_ID, "Handsfree Audio Gateway" }, + { DIRECT_PRT_REFOBJS_SVCLASS_ID, "Direct Printing Ref. Objects" }, + { REFLECTED_UI_SVCLASS_ID, "Reflected UI" }, + { BASIC_PRINTING_SVCLASS_ID, "Basic Printing" }, + { PRINTING_STATUS_SVCLASS_ID, "Printing Status" }, + { HID_SVCLASS_ID, "Human Interface Device" }, + { HCR_SVCLASS_ID, "Hardcopy Cable Replacement" }, + { HCR_PRINT_SVCLASS_ID, "HCR Print" }, + { HCR_SCAN_SVCLASS_ID, "HCR Scan" }, + { CIP_SVCLASS_ID, "Common ISDN Access" }, + { VIDEO_CONF_GW_SVCLASS_ID, "Video Conferencing Gateway" }, + { UDI_MT_SVCLASS_ID, "UDI MT" }, + { UDI_TA_SVCLASS_ID, "UDI TA" }, + { AV_SVCLASS_ID, "Audio/Video" }, + { SAP_SVCLASS_ID, "SIM Access" }, + { PBAP_PCE_SVCLASS_ID, "Phonebook Access - PCE" }, + { PBAP_PSE_SVCLASS_ID, "Phonebook Access - PSE" }, + { PBAP_SVCLASS_ID, "Phonebook Access" }, + { MAP_MSE_SVCLASS_ID, "Message Access - MAS" }, + { MAP_MCE_SVCLASS_ID, "Message Access - MNS" }, + { MAP_SVCLASS_ID, "Message Access" }, + { PNP_INFO_SVCLASS_ID, "PnP Information" }, + { GENERIC_NETWORKING_SVCLASS_ID, "Generic Networking" }, + { GENERIC_FILETRANS_SVCLASS_ID, "Generic File Transfer" }, + { GENERIC_AUDIO_SVCLASS_ID, "Generic Audio" }, + { GENERIC_TELEPHONY_SVCLASS_ID, "Generic Telephony" }, + { UPNP_SVCLASS_ID, "UPnP" }, + { UPNP_IP_SVCLASS_ID, "UPnP IP" }, + { UPNP_PAN_SVCLASS_ID, "UPnP PAN" }, + { UPNP_LAP_SVCLASS_ID, "UPnP LAP" }, + { UPNP_L2CAP_SVCLASS_ID, "UPnP L2CAP" }, + { VIDEO_SOURCE_SVCLASS_ID, "Video Source" }, + { VIDEO_SINK_SVCLASS_ID, "Video Sink" }, + { VIDEO_DISTRIBUTION_SVCLASS_ID, "Video Distribution" }, + { HDP_SVCLASS_ID, "HDP" }, + { HDP_SOURCE_SVCLASS_ID, "HDP Source" }, + { HDP_SINK_SVCLASS_ID, "HDP Sink" }, + { GENERIC_ACCESS_SVCLASS_ID, "Generic Access" }, + { GENERIC_ATTRIB_SVCLASS_ID, "Generic Attribute" }, + { APPLE_AGENT_SVCLASS_ID, "Apple Agent" }, + { 0 } +}; + +#define Profile ServiceClass + +static char *string_lookup(struct tupla *pt0, int index) +{ + struct tupla *pt; + + for (pt = pt0; pt->index; pt++) + if (pt->index == index) + return pt->str; + + return ""; +} + +static char *string_lookup_uuid(struct tupla *pt0, const uuid_t *uuid) +{ + uuid_t tmp_uuid; + + memcpy(&tmp_uuid, uuid, sizeof(tmp_uuid)); + + if (sdp_uuid128_to_uuid(&tmp_uuid)) { + switch (tmp_uuid.type) { + case SDP_UUID16: + return string_lookup(pt0, tmp_uuid.value.uuid16); + case SDP_UUID32: + return string_lookup(pt0, tmp_uuid.value.uuid32); + } + } + + return ""; +} + +/* + * Prints into a string the Protocol UUID + * coping a maximum of n characters. + */ +static int uuid2str(struct tupla *message, const uuid_t *uuid, char *str, size_t n) +{ + char *str2; + + if (!uuid) { + snprintf(str, n, "NULL"); + return -2; + } + + switch (uuid->type) { + case SDP_UUID16: + str2 = string_lookup(message, uuid->value.uuid16); + snprintf(str, n, "%s", str2); + break; + case SDP_UUID32: + str2 = string_lookup(message, uuid->value.uuid32); + snprintf(str, n, "%s", str2); + break; + case SDP_UUID128: + str2 = string_lookup_uuid(message, uuid); + snprintf(str, n, "%s", str2); + break; + default: + snprintf(str, n, "Type of UUID (%x) unknown.", uuid->type); + return -1; + } + + return 0; +} + +int sdp_proto_uuid2strn(const uuid_t *uuid, char *str, size_t n) +{ + return uuid2str(Protocol, uuid, str, n); +} + +int sdp_svclass_uuid2strn(const uuid_t *uuid, char *str, size_t n) +{ + return uuid2str(ServiceClass, uuid, str, n); +} + +int sdp_profile_uuid2strn(const uuid_t *uuid, char *str, size_t n) +{ + return uuid2str(Profile, uuid, str, n); +} + +/* + * convert the UUID to string, copying a maximum of n characters. + */ +int sdp_uuid2strn(const uuid_t *uuid, char *str, size_t n) +{ + if (!uuid) { + snprintf(str, n, "NULL"); + return -2; + } + switch (uuid->type) { + case SDP_UUID16: + snprintf(str, n, "%.4x", uuid->value.uuid16); + break; + case SDP_UUID32: + snprintf(str, n, "%.8x", uuid->value.uuid32); + break; + case SDP_UUID128:{ + unsigned int data0; + unsigned short data1; + unsigned short data2; + unsigned short data3; + unsigned int data4; + unsigned short data5; + + memcpy(&data0, &uuid->value.uuid128.data[0], 4); + memcpy(&data1, &uuid->value.uuid128.data[4], 2); + memcpy(&data2, &uuid->value.uuid128.data[6], 2); + memcpy(&data3, &uuid->value.uuid128.data[8], 2); + memcpy(&data4, &uuid->value.uuid128.data[10], 4); + memcpy(&data5, &uuid->value.uuid128.data[14], 2); + + snprintf(str, n, "%.8x-%.4x-%.4x-%.4x-%.8x%.4x", + ntohl(data0), ntohs(data1), + ntohs(data2), ntohs(data3), + ntohl(data4), ntohs(data5)); + } + break; + default: + snprintf(str, n, "Type of UUID (%x) unknown.", uuid->type); + return -1; /* Enum type of UUID not set */ + } + return 0; +} + +#ifdef SDP_DEBUG +/* + * Function prints the UUID in hex as per defined syntax - + * + * 4bytes-2bytes-2bytes-2bytes-6bytes + * + * There is some ugly code, including hardcoding, but + * that is just the way it is converting 16 and 32 bit + * UUIDs to 128 bit as defined in the SDP doc + */ +void sdp_uuid_print(const uuid_t *uuid) +{ + if (uuid == NULL) { + SDPERR("Null passed to print UUID"); + return; + } + if (uuid->type == SDP_UUID16) { + SDPDBG(" uint16_t : 0x%.4x", uuid->value.uuid16); + } else if (uuid->type == SDP_UUID32) { + SDPDBG(" uint32_t : 0x%.8x", uuid->value.uuid32); + } else if (uuid->type == SDP_UUID128) { + unsigned int data0; + unsigned short data1; + unsigned short data2; + unsigned short data3; + unsigned int data4; + unsigned short data5; + + memcpy(&data0, &uuid->value.uuid128.data[0], 4); + memcpy(&data1, &uuid->value.uuid128.data[4], 2); + memcpy(&data2, &uuid->value.uuid128.data[6], 2); + memcpy(&data3, &uuid->value.uuid128.data[8], 2); + memcpy(&data4, &uuid->value.uuid128.data[10], 4); + memcpy(&data5, &uuid->value.uuid128.data[14], 2); + + SDPDBG(" uint128_t : 0x%.8x-%.4x-%.4x-%.4x-%.8x%.4x", + ntohl(data0), ntohs(data1), ntohs(data2), + ntohs(data3), ntohl(data4), ntohs(data5)); + } else + SDPERR("Enum type of UUID not set"); +} +#endif + +sdp_data_t *sdp_data_alloc_with_length(uint8_t dtd, const void *value, + uint32_t length) +{ + sdp_data_t *seq; + sdp_data_t *d = malloc(sizeof(sdp_data_t)); + + if (!d) + return NULL; + + memset(d, 0, sizeof(sdp_data_t)); + d->dtd = dtd; + d->unitSize = sizeof(uint8_t); + + switch (dtd) { + case SDP_DATA_NIL: + break; + case SDP_UINT8: + d->val.uint8 = *(uint8_t *) value; + d->unitSize += sizeof(uint8_t); + break; + case SDP_INT8: + case SDP_BOOL: + d->val.int8 = *(int8_t *) value; + d->unitSize += sizeof(int8_t); + break; + case SDP_UINT16: + d->val.uint16 = bt_get_unaligned((uint16_t *) value); + d->unitSize += sizeof(uint16_t); + break; + case SDP_INT16: + d->val.int16 = bt_get_unaligned((int16_t *) value); + d->unitSize += sizeof(int16_t); + break; + case SDP_UINT32: + d->val.uint32 = bt_get_unaligned((uint32_t *) value); + d->unitSize += sizeof(uint32_t); + break; + case SDP_INT32: + d->val.int32 = bt_get_unaligned((int32_t *) value); + d->unitSize += sizeof(int32_t); + break; + case SDP_INT64: + d->val.int64 = bt_get_unaligned((int64_t *) value); + d->unitSize += sizeof(int64_t); + break; + case SDP_UINT64: + d->val.uint64 = bt_get_unaligned((uint64_t *) value); + d->unitSize += sizeof(uint64_t); + break; + case SDP_UINT128: + memcpy(&d->val.uint128.data, value, sizeof(uint128_t)); + d->unitSize += sizeof(uint128_t); + break; + case SDP_INT128: + memcpy(&d->val.int128.data, value, sizeof(uint128_t)); + d->unitSize += sizeof(uint128_t); + break; + case SDP_UUID16: + sdp_uuid16_create(&d->val.uuid, bt_get_unaligned((uint16_t *) value)); + d->unitSize += sizeof(uint16_t); + break; + case SDP_UUID32: + sdp_uuid32_create(&d->val.uuid, bt_get_unaligned((uint32_t *) value)); + d->unitSize += sizeof(uint32_t); + break; + case SDP_UUID128: + sdp_uuid128_create(&d->val.uuid, value); + d->unitSize += sizeof(uint128_t); + break; + case SDP_URL_STR8: + case SDP_URL_STR16: + case SDP_TEXT_STR8: + case SDP_TEXT_STR16: + if (!value) { + free(d); + return NULL; + } + + d->unitSize += length; + if (length <= USHRT_MAX) { + d->val.str = malloc(length); + if (!d->val.str) { + free(d); + return NULL; + } + + memcpy(d->val.str, value, length); + } else { + SDPERR("Strings of size > USHRT_MAX not supported"); + free(d); + d = NULL; + } + break; + case SDP_URL_STR32: + case SDP_TEXT_STR32: + SDPERR("Strings of size > USHRT_MAX not supported"); + break; + case SDP_ALT8: + case SDP_ALT16: + case SDP_ALT32: + case SDP_SEQ8: + case SDP_SEQ16: + case SDP_SEQ32: + if (dtd == SDP_ALT8 || dtd == SDP_SEQ8) + d->unitSize += sizeof(uint8_t); + else if (dtd == SDP_ALT16 || dtd == SDP_SEQ16) + d->unitSize += sizeof(uint16_t); + else if (dtd == SDP_ALT32 || dtd == SDP_SEQ32) + d->unitSize += sizeof(uint32_t); + seq = (sdp_data_t *)value; + d->val.dataseq = seq; + for (; seq; seq = seq->next) + d->unitSize += seq->unitSize; + break; + default: + free(d); + d = NULL; + } + + return d; +} + +sdp_data_t *sdp_data_alloc(uint8_t dtd, const void *value) +{ + uint32_t length; + + switch (dtd) { + case SDP_URL_STR8: + case SDP_URL_STR16: + case SDP_TEXT_STR8: + case SDP_TEXT_STR16: + if (!value) + return NULL; + + length = strlen((char *) value); + break; + default: + length = 0; + break; + } + + return sdp_data_alloc_with_length(dtd, value, length); +} + +sdp_data_t *sdp_seq_append(sdp_data_t *seq, sdp_data_t *d) +{ + if (seq) { + sdp_data_t *p; + for (p = seq; p->next; p = p->next); + p->next = d; + } else + seq = d; + d->next = NULL; + return seq; +} + +sdp_data_t *sdp_seq_alloc_with_length(void **dtds, void **values, int *length, + int len) +{ + sdp_data_t *curr = NULL, *seq = NULL; + int i; + + for (i = 0; i < len; i++) { + sdp_data_t *data; + int8_t dtd = *(uint8_t *) dtds[i]; + + if (dtd >= SDP_SEQ8 && dtd <= SDP_ALT32) + data = (sdp_data_t *) values[i]; + else + data = sdp_data_alloc_with_length(dtd, values[i], length[i]); + + if (!data) + return NULL; + + if (curr) + curr->next = data; + else + seq = data; + + curr = data; + } + + return sdp_data_alloc(SDP_SEQ8, seq); +} + +sdp_data_t *sdp_seq_alloc(void **dtds, void **values, int len) +{ + sdp_data_t *curr = NULL, *seq = NULL; + int i; + + for (i = 0; i < len; i++) { + sdp_data_t *data; + uint8_t dtd = *(uint8_t *) dtds[i]; + + if (dtd >= SDP_SEQ8 && dtd <= SDP_ALT32) + data = (sdp_data_t *) values[i]; + else + data = sdp_data_alloc(dtd, values[i]); + + if (!data) + return NULL; + + if (curr) + curr->next = data; + else + seq = data; + + curr = data; + } + + return sdp_data_alloc(SDP_SEQ8, seq); +} + +static void extract_svclass_uuid(sdp_data_t *data, uuid_t *uuid) +{ + sdp_data_t *d; + + if (!data || !SDP_IS_SEQ(data->dtd)) + return; + + d = data->val.dataseq; + if (!d) + return; + + if (d->dtd < SDP_UUID16 || d->dtd > SDP_UUID128) + return; + + *uuid = d->val.uuid; +} + +int sdp_attr_add(sdp_record_t *rec, uint16_t attr, sdp_data_t *d) +{ + sdp_data_t *p = sdp_data_get(rec, attr); + + if (p) + return -1; + + d->attrId = attr; + rec->attrlist = sdp_list_insert_sorted(rec->attrlist, d, sdp_attrid_comp_func); + + if (attr == SDP_ATTR_SVCLASS_ID_LIST) + extract_svclass_uuid(d, &rec->svclass); + + return 0; +} + +void sdp_attr_remove(sdp_record_t *rec, uint16_t attr) +{ + sdp_data_t *d = sdp_data_get(rec, attr); + + if (d) + rec->attrlist = sdp_list_remove(rec->attrlist, d); + + if (attr == SDP_ATTR_SVCLASS_ID_LIST) + memset(&rec->svclass, 0, sizeof(rec->svclass)); +} + +void sdp_set_seq_len(uint8_t *ptr, uint32_t length) +{ + uint8_t dtd = *ptr++; + + switch (dtd) { + case SDP_SEQ8: + case SDP_ALT8: + case SDP_TEXT_STR8: + case SDP_URL_STR8: + *ptr = (uint8_t) length; + break; + case SDP_SEQ16: + case SDP_ALT16: + case SDP_TEXT_STR16: + case SDP_URL_STR16: + bt_put_be16(length, ptr); + break; + case SDP_SEQ32: + case SDP_ALT32: + case SDP_TEXT_STR32: + case SDP_URL_STR32: + bt_put_be32(length, ptr); + break; + } +} + +static int sdp_get_data_type_size(uint8_t dtd) +{ + int size = sizeof(uint8_t); + + switch (dtd) { + case SDP_SEQ8: + case SDP_TEXT_STR8: + case SDP_URL_STR8: + case SDP_ALT8: + size += sizeof(uint8_t); + break; + case SDP_SEQ16: + case SDP_TEXT_STR16: + case SDP_URL_STR16: + case SDP_ALT16: + size += sizeof(uint16_t); + break; + case SDP_SEQ32: + case SDP_TEXT_STR32: + case SDP_URL_STR32: + case SDP_ALT32: + size += sizeof(uint32_t); + break; + } + + return size; +} + +void sdp_set_attrid(sdp_buf_t *buf, uint16_t attr) +{ + uint8_t *p = buf->data; + + /* data type for attr */ + *p++ = SDP_UINT16; + buf->data_size = sizeof(uint8_t); + bt_put_be16(attr, p); + buf->data_size += sizeof(uint16_t); +} + +static int get_data_size(sdp_buf_t *buf, sdp_data_t *sdpdata) +{ + sdp_data_t *d; + int n = 0; + + for (d = sdpdata->val.dataseq; d; d = d->next) { + if (buf->data) + n += sdp_gen_pdu(buf, d); + else + n += sdp_gen_buffer(buf, d); + } + + return n; +} + +static int sdp_get_data_size(sdp_buf_t *buf, sdp_data_t *d) +{ + uint32_t data_size = 0; + uint8_t dtd = d->dtd; + + switch (dtd) { + case SDP_DATA_NIL: + break; + case SDP_UINT8: + data_size = sizeof(uint8_t); + break; + case SDP_UINT16: + data_size = sizeof(uint16_t); + break; + case SDP_UINT32: + data_size = sizeof(uint32_t); + break; + case SDP_UINT64: + data_size = sizeof(uint64_t); + break; + case SDP_UINT128: + data_size = sizeof(uint128_t); + break; + case SDP_INT8: + case SDP_BOOL: + data_size = sizeof(int8_t); + break; + case SDP_INT16: + data_size = sizeof(int16_t); + break; + case SDP_INT32: + data_size = sizeof(int32_t); + break; + case SDP_INT64: + data_size = sizeof(int64_t); + break; + case SDP_INT128: + data_size = sizeof(uint128_t); + break; + case SDP_TEXT_STR8: + case SDP_TEXT_STR16: + case SDP_TEXT_STR32: + case SDP_URL_STR8: + case SDP_URL_STR16: + case SDP_URL_STR32: + data_size = d->unitSize - sizeof(uint8_t); + break; + case SDP_SEQ8: + case SDP_SEQ16: + case SDP_SEQ32: + data_size = get_data_size(buf, d); + break; + case SDP_ALT8: + case SDP_ALT16: + case SDP_ALT32: + data_size = get_data_size(buf, d); + break; + case SDP_UUID16: + data_size = sizeof(uint16_t); + break; + case SDP_UUID32: + data_size = sizeof(uint32_t); + break; + case SDP_UUID128: + data_size = sizeof(uint128_t); + break; + default: + break; + } + + return data_size; +} + +static int sdp_gen_buffer(sdp_buf_t *buf, sdp_data_t *d) +{ + int orig = buf->buf_size; + + if (buf->buf_size == 0 && d->dtd == 0) { + /* create initial sequence */ + buf->buf_size += sizeof(uint8_t); + + /* reserve space for sequence size */ + buf->buf_size += sizeof(uint8_t); + } + + /* attribute length */ + buf->buf_size += sizeof(uint8_t) + sizeof(uint16_t); + + buf->buf_size += sdp_get_data_type_size(d->dtd); + buf->buf_size += sdp_get_data_size(buf, d); + + if (buf->buf_size > UCHAR_MAX && d->dtd == SDP_SEQ8) + buf->buf_size += sizeof(uint8_t); + + return buf->buf_size - orig; +} + +int sdp_gen_pdu(sdp_buf_t *buf, sdp_data_t *d) +{ + uint32_t pdu_size, data_size; + unsigned char *src = NULL, is_seq = 0, is_alt = 0; + uint16_t u16; + uint32_t u32; + uint64_t u64; + uint128_t u128; + uint8_t *seqp = buf->data + buf->data_size; + uint32_t orig_data_size = buf->data_size; + +recalculate: + pdu_size = sdp_get_data_type_size(d->dtd); + buf->data_size += pdu_size; + + data_size = sdp_get_data_size(buf, d); + if (data_size > UCHAR_MAX && d->dtd == SDP_SEQ8) { + buf->data_size = orig_data_size; + d->dtd = SDP_SEQ16; + goto recalculate; + } + + *seqp = d->dtd; + + switch (d->dtd) { + case SDP_DATA_NIL: + break; + case SDP_UINT8: + src = &d->val.uint8; + break; + case SDP_UINT16: + u16 = htons(d->val.uint16); + src = (unsigned char *) &u16; + break; + case SDP_UINT32: + u32 = htonl(d->val.uint32); + src = (unsigned char *) &u32; + break; + case SDP_UINT64: + u64 = hton64(d->val.uint64); + src = (unsigned char *) &u64; + break; + case SDP_UINT128: + hton128(&d->val.uint128, &u128); + src = (unsigned char *) &u128; + break; + case SDP_INT8: + case SDP_BOOL: + src = (unsigned char *) &d->val.int8; + break; + case SDP_INT16: + u16 = htons(d->val.int16); + src = (unsigned char *) &u16; + break; + case SDP_INT32: + u32 = htonl(d->val.int32); + src = (unsigned char *) &u32; + break; + case SDP_INT64: + u64 = hton64(d->val.int64); + src = (unsigned char *) &u64; + break; + case SDP_INT128: + hton128(&d->val.int128, &u128); + src = (unsigned char *) &u128; + break; + case SDP_TEXT_STR8: + case SDP_TEXT_STR16: + case SDP_TEXT_STR32: + case SDP_URL_STR8: + case SDP_URL_STR16: + case SDP_URL_STR32: + src = (unsigned char *) d->val.str; + sdp_set_seq_len(seqp, data_size); + break; + case SDP_SEQ8: + case SDP_SEQ16: + case SDP_SEQ32: + is_seq = 1; + sdp_set_seq_len(seqp, data_size); + break; + case SDP_ALT8: + case SDP_ALT16: + case SDP_ALT32: + is_alt = 1; + sdp_set_seq_len(seqp, data_size); + break; + case SDP_UUID16: + u16 = htons(d->val.uuid.value.uuid16); + src = (unsigned char *) &u16; + break; + case SDP_UUID32: + u32 = htonl(d->val.uuid.value.uuid32); + src = (unsigned char *) &u32; + break; + case SDP_UUID128: + src = (unsigned char *) &d->val.uuid.value.uuid128; + break; + default: + break; + } + + if (!is_seq && !is_alt) { + if (src && buf->buf_size >= buf->data_size + data_size) { + memcpy(buf->data + buf->data_size, src, data_size); + buf->data_size += data_size; + } else if (d->dtd != SDP_DATA_NIL) { + SDPDBG("Gen PDU : Can't copy from invalid source or dest"); + } + } + + pdu_size += data_size; + + return pdu_size; +} + +static void sdp_attr_pdu(void *value, void *udata) +{ + sdp_append_to_pdu((sdp_buf_t *)udata, (sdp_data_t *)value); +} + +static void sdp_attr_size(void *value, void *udata) +{ + sdp_gen_buffer((sdp_buf_t *)udata, (sdp_data_t *)value); +} + +int sdp_gen_record_pdu(const sdp_record_t *rec, sdp_buf_t *buf) +{ + memset(buf, 0, sizeof(sdp_buf_t)); + sdp_list_foreach(rec->attrlist, sdp_attr_size, buf); + + buf->data = malloc(buf->buf_size); + if (!buf->data) + return -ENOMEM; + buf->data_size = 0; + memset(buf->data, 0, buf->buf_size); + + sdp_list_foreach(rec->attrlist, sdp_attr_pdu, buf); + + return 0; +} + +void sdp_attr_replace(sdp_record_t *rec, uint16_t attr, sdp_data_t *d) +{ + sdp_data_t *p = sdp_data_get(rec, attr); + + if (p) { + rec->attrlist = sdp_list_remove(rec->attrlist, p); + sdp_data_free(p); + } + + d->attrId = attr; + rec->attrlist = sdp_list_insert_sorted(rec->attrlist, d, sdp_attrid_comp_func); + + if (attr == SDP_ATTR_SVCLASS_ID_LIST) + extract_svclass_uuid(d, &rec->svclass); +} + +int sdp_attrid_comp_func(const void *key1, const void *key2) +{ + const sdp_data_t *d1 = (const sdp_data_t *)key1; + const sdp_data_t *d2 = (const sdp_data_t *)key2; + + if (d1 && d2) + return d1->attrId - d2->attrId; + return 0; +} + +static void data_seq_free(sdp_data_t *seq) +{ + sdp_data_t *d = seq->val.dataseq; + + while (d) { + sdp_data_t *next = d->next; + sdp_data_free(d); + d = next; + } +} + +void sdp_data_free(sdp_data_t *d) +{ + switch (d->dtd) { + case SDP_SEQ8: + case SDP_SEQ16: + case SDP_SEQ32: + data_seq_free(d); + break; + case SDP_URL_STR8: + case SDP_URL_STR16: + case SDP_URL_STR32: + case SDP_TEXT_STR8: + case SDP_TEXT_STR16: + case SDP_TEXT_STR32: + free(d->val.str); + break; + } + free(d); +} + +int sdp_uuid_extract(const uint8_t *p, int bufsize, uuid_t *uuid, int *scanned) +{ + uint8_t type; + + if (bufsize < (int) sizeof(uint8_t)) { + SDPERR("Unexpected end of packet"); + return -1; + } + + type = *(const uint8_t *) p; + + if (!SDP_IS_UUID(type)) { + SDPERR("Unknown data type : %d expecting a svc UUID", type); + return -1; + } + p += sizeof(uint8_t); + *scanned += sizeof(uint8_t); + bufsize -= sizeof(uint8_t); + if (type == SDP_UUID16) { + if (bufsize < (int) sizeof(uint16_t)) { + SDPERR("Not enough room for 16-bit UUID"); + return -1; + } + sdp_uuid16_create(uuid, bt_get_be16(p)); + *scanned += sizeof(uint16_t); + } else if (type == SDP_UUID32) { + if (bufsize < (int) sizeof(uint32_t)) { + SDPERR("Not enough room for 32-bit UUID"); + return -1; + } + sdp_uuid32_create(uuid, bt_get_be32(p)); + *scanned += sizeof(uint32_t); + } else { + if (bufsize < (int) sizeof(uint128_t)) { + SDPERR("Not enough room for 128-bit UUID"); + return -1; + } + sdp_uuid128_create(uuid, p); + *scanned += sizeof(uint128_t); + } + return 0; +} + +static sdp_data_t *extract_int(const void *p, int bufsize, int *len) +{ + sdp_data_t *d; + + if (bufsize < (int) sizeof(uint8_t)) { + SDPERR("Unexpected end of packet"); + return NULL; + } + + d = malloc(sizeof(sdp_data_t)); + if (!d) + return NULL; + + SDPDBG("Extracting integer"); + memset(d, 0, sizeof(sdp_data_t)); + d->dtd = *(uint8_t *) p; + p += sizeof(uint8_t); + *len += sizeof(uint8_t); + bufsize -= sizeof(uint8_t); + + switch (d->dtd) { + case SDP_DATA_NIL: + break; + case SDP_BOOL: + case SDP_INT8: + case SDP_UINT8: + if (bufsize < (int) sizeof(uint8_t)) { + SDPERR("Unexpected end of packet"); + free(d); + return NULL; + } + *len += sizeof(uint8_t); + d->val.uint8 = *(uint8_t *) p; + break; + case SDP_INT16: + case SDP_UINT16: + if (bufsize < (int) sizeof(uint16_t)) { + SDPERR("Unexpected end of packet"); + free(d); + return NULL; + } + *len += sizeof(uint16_t); + d->val.uint16 = bt_get_be16(p); + break; + case SDP_INT32: + case SDP_UINT32: + if (bufsize < (int) sizeof(uint32_t)) { + SDPERR("Unexpected end of packet"); + free(d); + return NULL; + } + *len += sizeof(uint32_t); + d->val.uint32 = bt_get_be32(p); + break; + case SDP_INT64: + case SDP_UINT64: + if (bufsize < (int) sizeof(uint64_t)) { + SDPERR("Unexpected end of packet"); + free(d); + return NULL; + } + *len += sizeof(uint64_t); + d->val.uint64 = bt_get_be64(p); + break; + case SDP_INT128: + case SDP_UINT128: + if (bufsize < (int) sizeof(uint128_t)) { + SDPERR("Unexpected end of packet"); + free(d); + return NULL; + } + *len += sizeof(uint128_t); + ntoh128((uint128_t *) p, &d->val.uint128); + break; + default: + free(d); + d = NULL; + } + return d; +} + +static sdp_data_t *extract_uuid(const uint8_t *p, int bufsize, int *len, + sdp_record_t *rec) +{ + sdp_data_t *d = malloc(sizeof(sdp_data_t)); + + if (!d) + return NULL; + + SDPDBG("Extracting UUID"); + memset(d, 0, sizeof(sdp_data_t)); + if (sdp_uuid_extract(p, bufsize, &d->val.uuid, len) < 0) { + free(d); + return NULL; + } + d->dtd = *p; + if (rec) + sdp_pattern_add_uuid(rec, &d->val.uuid); + return d; +} + +/* + * Extract strings from the PDU (could be service description and similar info) + */ +static sdp_data_t *extract_str(const void *p, int bufsize, int *len) +{ + char *s; + int n; + sdp_data_t *d; + + if (bufsize < (int) sizeof(uint8_t)) { + SDPERR("Unexpected end of packet"); + return NULL; + } + + d = malloc(sizeof(sdp_data_t)); + if (!d) + return NULL; + + memset(d, 0, sizeof(sdp_data_t)); + d->dtd = *(uint8_t *) p; + p += sizeof(uint8_t); + *len += sizeof(uint8_t); + bufsize -= sizeof(uint8_t); + + switch (d->dtd) { + case SDP_TEXT_STR8: + case SDP_URL_STR8: + if (bufsize < (int) sizeof(uint8_t)) { + SDPERR("Unexpected end of packet"); + free(d); + return NULL; + } + n = *(uint8_t *) p; + p += sizeof(uint8_t); + *len += sizeof(uint8_t); + bufsize -= sizeof(uint8_t); + break; + case SDP_TEXT_STR16: + case SDP_URL_STR16: + if (bufsize < (int) sizeof(uint16_t)) { + SDPERR("Unexpected end of packet"); + free(d); + return NULL; + } + n = bt_get_be16(p); + p += sizeof(uint16_t); + *len += sizeof(uint16_t); + bufsize -= sizeof(uint16_t); + break; + default: + SDPERR("Sizeof text string > UINT16_MAX"); + free(d); + return NULL; + } + + if (bufsize < n) { + SDPERR("String too long to fit in packet"); + free(d); + return NULL; + } + + s = malloc(n + 1); + if (!s) { + SDPERR("Not enough memory for incoming string"); + free(d); + return NULL; + } + memset(s, 0, n + 1); + memcpy(s, p, n); + + *len += n; + + SDPDBG("Len : %d", n); + SDPDBG("Str : %s", s); + + d->val.str = s; + d->unitSize = n + sizeof(uint8_t); + return d; +} + +/* + * Extract the sequence type and its length, and return offset into buf + * or 0 on failure. + */ +int sdp_extract_seqtype(const uint8_t *buf, int bufsize, uint8_t *dtdp, int *size) +{ + uint8_t dtd; + int scanned = sizeof(uint8_t); + + if (bufsize < (int) sizeof(uint8_t)) { + SDPERR("Unexpected end of packet"); + return 0; + } + + dtd = *(uint8_t *) buf; + buf += sizeof(uint8_t); + bufsize -= sizeof(uint8_t); + *dtdp = dtd; + switch (dtd) { + case SDP_SEQ8: + case SDP_ALT8: + if (bufsize < (int) sizeof(uint8_t)) { + SDPERR("Unexpected end of packet"); + return 0; + } + *size = *(uint8_t *) buf; + scanned += sizeof(uint8_t); + break; + case SDP_SEQ16: + case SDP_ALT16: + if (bufsize < (int) sizeof(uint16_t)) { + SDPERR("Unexpected end of packet"); + return 0; + } + *size = bt_get_be16(buf); + scanned += sizeof(uint16_t); + break; + case SDP_SEQ32: + case SDP_ALT32: + if (bufsize < (int) sizeof(uint32_t)) { + SDPERR("Unexpected end of packet"); + return 0; + } + *size = bt_get_be32(buf); + scanned += sizeof(uint32_t); + break; + default: + SDPERR("Unknown sequence type, aborting"); + return 0; + } + return scanned; +} + +static sdp_data_t *extract_seq(const void *p, int bufsize, int *len, + sdp_record_t *rec) +{ + int seqlen, n = 0; + sdp_data_t *curr, *prev; + sdp_data_t *d = malloc(sizeof(sdp_data_t)); + + if (!d) + return NULL; + + SDPDBG("Extracting SEQ"); + memset(d, 0, sizeof(sdp_data_t)); + *len = sdp_extract_seqtype(p, bufsize, &d->dtd, &seqlen); + SDPDBG("Sequence Type : 0x%x length : 0x%x", d->dtd, seqlen); + + if (*len == 0) + return d; + + if (*len > bufsize) { + SDPERR("Packet not big enough to hold sequence."); + free(d); + return NULL; + } + + p += *len; + bufsize -= *len; + prev = NULL; + while (n < seqlen) { + int attrlen = 0; + curr = sdp_extract_attr(p, bufsize, &attrlen, rec); + if (curr == NULL) + break; + + if (prev) + prev->next = curr; + else + d->val.dataseq = curr; + prev = curr; + p += attrlen; + n += attrlen; + bufsize -= attrlen; + + SDPDBG("Extracted: %d SequenceLength: %d", n, seqlen); + } + + *len += n; + return d; +} + +sdp_data_t *sdp_extract_attr(const uint8_t *p, int bufsize, int *size, + sdp_record_t *rec) +{ + sdp_data_t *elem; + int n = 0; + uint8_t dtd; + + if (bufsize < (int) sizeof(uint8_t)) { + SDPERR("Unexpected end of packet"); + return NULL; + } + + dtd = *(const uint8_t *)p; + + SDPDBG("extract_attr: dtd=0x%x", dtd); + switch (dtd) { + case SDP_DATA_NIL: + case SDP_BOOL: + case SDP_UINT8: + case SDP_UINT16: + case SDP_UINT32: + case SDP_UINT64: + case SDP_UINT128: + case SDP_INT8: + case SDP_INT16: + case SDP_INT32: + case SDP_INT64: + case SDP_INT128: + elem = extract_int(p, bufsize, &n); + break; + case SDP_UUID16: + case SDP_UUID32: + case SDP_UUID128: + elem = extract_uuid(p, bufsize, &n, rec); + break; + case SDP_TEXT_STR8: + case SDP_TEXT_STR16: + case SDP_TEXT_STR32: + case SDP_URL_STR8: + case SDP_URL_STR16: + case SDP_URL_STR32: + elem = extract_str(p, bufsize, &n); + break; + case SDP_SEQ8: + case SDP_SEQ16: + case SDP_SEQ32: + case SDP_ALT8: + case SDP_ALT16: + case SDP_ALT32: + elem = extract_seq(p, bufsize, &n, rec); + break; + default: + SDPERR("Unknown data descriptor : 0x%x terminating", dtd); + return NULL; + } + *size += n; + return elem; +} + +#ifdef SDP_DEBUG +static void attr_print_func(void *value, void *userData) +{ + sdp_data_t *d = (sdp_data_t *)value; + + SDPDBG("====================================="); + SDPDBG("ATTRIBUTE IDENTIFIER : 0x%x", d->attrId); + SDPDBG("ATTRIBUTE VALUE PTR : %p", value); + if (d) + sdp_data_print(d); + else + SDPDBG("NULL value"); + SDPDBG("====================================="); +} + +void sdp_print_service_attr(sdp_list_t *svcAttrList) +{ + SDPDBG("Printing service attr list %p", svcAttrList); + sdp_list_foreach(svcAttrList, attr_print_func, NULL); + SDPDBG("Printed service attr list %p", svcAttrList); +} +#endif + +sdp_record_t *sdp_extract_pdu(const uint8_t *buf, int bufsize, int *scanned) +{ + int extracted = 0, seqlen = 0; + uint8_t dtd; + uint16_t attr; + sdp_record_t *rec = sdp_record_alloc(); + const uint8_t *p = buf; + + *scanned = sdp_extract_seqtype(buf, bufsize, &dtd, &seqlen); + p += *scanned; + bufsize -= *scanned; + rec->attrlist = NULL; + + while (extracted < seqlen && bufsize > 0) { + int n = sizeof(uint8_t), attrlen = 0; + sdp_data_t *data = NULL; + + SDPDBG("Extract PDU, sequenceLength: %d localExtractedLength: %d", + seqlen, extracted); + + if (bufsize < n + (int) sizeof(uint16_t)) { + SDPERR("Unexpected end of packet"); + break; + } + + dtd = *(uint8_t *) p; + attr = bt_get_be16(p + n); + n += sizeof(uint16_t); + + SDPDBG("DTD of attrId : %d Attr id : 0x%x ", dtd, attr); + + data = sdp_extract_attr(p + n, bufsize - n, &attrlen, rec); + + SDPDBG("Attr id : 0x%x attrValueLength : %d", attr, attrlen); + + n += attrlen; + if (data == NULL) { + SDPDBG("Terminating extraction of attributes"); + break; + } + + if (attr == SDP_ATTR_RECORD_HANDLE) + rec->handle = data->val.uint32; + + if (attr == SDP_ATTR_SVCLASS_ID_LIST) + extract_svclass_uuid(data, &rec->svclass); + + extracted += n; + p += n; + bufsize -= n; + sdp_attr_replace(rec, attr, data); + + SDPDBG("Extract PDU, seqLength: %d localExtractedLength: %d", + seqlen, extracted); + } +#ifdef SDP_DEBUG + SDPDBG("Successful extracting of Svc Rec attributes"); + sdp_print_service_attr(rec->attrlist); +#endif + *scanned += seqlen; + return rec; +} + +static void sdp_copy_pattern(void *value, void *udata) +{ + uuid_t *uuid = value; + sdp_record_t *rec = udata; + + sdp_pattern_add_uuid(rec, uuid); +} + +static void *sdp_data_value(sdp_data_t *data, uint32_t *len) +{ + void *val = NULL; + + switch (data->dtd) { + case SDP_DATA_NIL: + break; + case SDP_UINT8: + val = &data->val.uint8; + break; + case SDP_INT8: + case SDP_BOOL: + val = &data->val.int8; + break; + case SDP_UINT16: + val = &data->val.uint16; + break; + case SDP_INT16: + val = &data->val.int16; + break; + case SDP_UINT32: + val = &data->val.uint32; + break; + case SDP_INT32: + val = &data->val.int32; + break; + case SDP_INT64: + val = &data->val.int64; + break; + case SDP_UINT64: + val = &data->val.uint64; + break; + case SDP_UINT128: + val = &data->val.uint128; + break; + case SDP_INT128: + val = &data->val.int128; + break; + case SDP_UUID16: + val = &data->val.uuid.value.uuid16; + break; + case SDP_UUID32: + val = &data->val.uuid.value.uuid32; + break; + case SDP_UUID128: + val = &data->val.uuid.value.uuid128; + break; + case SDP_URL_STR8: + case SDP_URL_STR16: + case SDP_TEXT_STR8: + case SDP_TEXT_STR16: + case SDP_URL_STR32: + case SDP_TEXT_STR32: + val = data->val.str; + if (len) + *len = data->unitSize - 1; + break; + case SDP_ALT8: + case SDP_ALT16: + case SDP_ALT32: + case SDP_SEQ8: + case SDP_SEQ16: + case SDP_SEQ32: + val = sdp_copy_seq(data->val.dataseq); + break; + } + + return val; +} + +static sdp_data_t *sdp_copy_seq(sdp_data_t *data) +{ + sdp_data_t *tmp, *seq = NULL, *cur = NULL; + + for (tmp = data; tmp; tmp = tmp->next) { + sdp_data_t *datatmp; + void *value; + + value = sdp_data_value(tmp, NULL); + datatmp = sdp_data_alloc_with_length(tmp->dtd, value, + tmp->unitSize); + + if (cur) + cur->next = datatmp; + else + seq = datatmp; + + cur = datatmp; + } + + return seq; +} + +static void sdp_copy_attrlist(void *value, void *udata) +{ + sdp_data_t *data = value; + sdp_record_t *rec = udata; + void *val; + uint32_t len = 0; + + val = sdp_data_value(data, &len); + + if (!len) + sdp_attr_add_new(rec, data->attrId, data->dtd, val); + else + sdp_attr_add_new_with_length(rec, data->attrId, + data->dtd, val, len); +} + +sdp_record_t *sdp_copy_record(sdp_record_t *rec) +{ + sdp_record_t *cpy; + + cpy = sdp_record_alloc(); + + cpy->handle = rec->handle; + + sdp_list_foreach(rec->pattern, sdp_copy_pattern, cpy); + sdp_list_foreach(rec->attrlist, sdp_copy_attrlist, cpy); + + cpy->svclass = rec->svclass; + + return cpy; +} + +#ifdef SDP_DEBUG +static void print_dataseq(sdp_data_t *p) +{ + sdp_data_t *d; + + for (d = p; d; d = d->next) + sdp_data_print(d); +} +#endif + +void sdp_record_print(const sdp_record_t *rec) +{ + sdp_data_t *d = sdp_data_get(rec, SDP_ATTR_SVCNAME_PRIMARY); + if (d && SDP_IS_TEXT_STR(d->dtd)) + printf("Service Name: %.*s\n", d->unitSize, d->val.str); + d = sdp_data_get(rec, SDP_ATTR_SVCDESC_PRIMARY); + if (d && SDP_IS_TEXT_STR(d->dtd)) + printf("Service Description: %.*s\n", d->unitSize, d->val.str); + d = sdp_data_get(rec, SDP_ATTR_PROVNAME_PRIMARY); + if (d && SDP_IS_TEXT_STR(d->dtd)) + printf("Service Provider: %.*s\n", d->unitSize, d->val.str); +} + +#ifdef SDP_DEBUG +void sdp_data_print(sdp_data_t *d) +{ + switch (d->dtd) { + case SDP_DATA_NIL: + SDPDBG("NIL"); + break; + case SDP_BOOL: + case SDP_UINT8: + case SDP_UINT16: + case SDP_UINT32: + case SDP_UINT64: + case SDP_UINT128: + case SDP_INT8: + case SDP_INT16: + case SDP_INT32: + case SDP_INT64: + case SDP_INT128: + SDPDBG("Integer : 0x%x", d->val.uint32); + break; + case SDP_UUID16: + case SDP_UUID32: + case SDP_UUID128: + SDPDBG("UUID"); + sdp_uuid_print(&d->val.uuid); + break; + case SDP_TEXT_STR8: + case SDP_TEXT_STR16: + case SDP_TEXT_STR32: + SDPDBG("Text : %s", d->val.str); + break; + case SDP_URL_STR8: + case SDP_URL_STR16: + case SDP_URL_STR32: + SDPDBG("URL : %s", d->val.str); + break; + case SDP_SEQ8: + case SDP_SEQ16: + case SDP_SEQ32: + print_dataseq(d->val.dataseq); + break; + case SDP_ALT8: + case SDP_ALT16: + case SDP_ALT32: + SDPDBG("Data Sequence Alternates"); + print_dataseq(d->val.dataseq); + break; + } +} +#endif + +sdp_data_t *sdp_data_get(const sdp_record_t *rec, uint16_t attrId) +{ + if (rec->attrlist) { + sdp_data_t sdpTemplate; + sdp_list_t *p; + + sdpTemplate.attrId = attrId; + p = sdp_list_find(rec->attrlist, &sdpTemplate, sdp_attrid_comp_func); + if (p) + return p->data; + } + return NULL; +} + +static int sdp_send_req(sdp_session_t *session, uint8_t *buf, uint32_t size) +{ + uint32_t sent = 0; + + while (sent < size) { + int n = send(session->sock, buf + sent, size - sent, 0); + if (n < 0) + return -1; + sent += n; + } + return 0; +} + +static int sdp_read_rsp(sdp_session_t *session, uint8_t *buf, uint32_t size) +{ + fd_set readFds; + struct timeval timeout = { SDP_RESPONSE_TIMEOUT, 0 }; + + FD_ZERO(&readFds); + FD_SET(session->sock, &readFds); + SDPDBG("Waiting for response"); + if (select(session->sock + 1, &readFds, NULL, NULL, &timeout) == 0) { + SDPERR("Client timed out"); + errno = ETIMEDOUT; + return -1; + } + return recv(session->sock, buf, size, 0); +} + +/* + * generic send request, wait for response method. + */ +int sdp_send_req_w4_rsp(sdp_session_t *session, uint8_t *reqbuf, + uint8_t *rspbuf, uint32_t reqsize, uint32_t *rspsize) +{ + int n; + sdp_pdu_hdr_t *reqhdr = (sdp_pdu_hdr_t *) reqbuf; + sdp_pdu_hdr_t *rsphdr = (sdp_pdu_hdr_t *) rspbuf; + + SDPDBG(""); + if (0 > sdp_send_req(session, reqbuf, reqsize)) { + SDPERR("Error sending data:%m"); + return -1; + } + n = sdp_read_rsp(session, rspbuf, SDP_RSP_BUFFER_SIZE); + if (0 > n) + return -1; + SDPDBG("Read : %d", n); + if (n == 0 || reqhdr->tid != rsphdr->tid) { + errno = EPROTO; + return -1; + } + *rspsize = n; + return 0; +} + +/* + * singly-linked lists (after openobex implementation) + */ +sdp_list_t *sdp_list_append(sdp_list_t *p, void *d) +{ + sdp_list_t *q, *n = malloc(sizeof(sdp_list_t)); + + if (!n) + return NULL; + + n->data = d; + n->next = 0; + + if (!p) + return n; + + for (q = p; q->next; q = q->next); + q->next = n; + + return p; +} + +sdp_list_t *sdp_list_remove(sdp_list_t *list, void *d) +{ + sdp_list_t *p, *q; + + for (q = 0, p = list; p; q = p, p = p->next) + if (p->data == d) { + if (q) + q->next = p->next; + else + list = p->next; + free(p); + break; + } + + return list; +} + +sdp_list_t *sdp_list_insert_sorted(sdp_list_t *list, void *d, + sdp_comp_func_t f) +{ + sdp_list_t *q, *p, *n; + + n = malloc(sizeof(sdp_list_t)); + if (!n) + return NULL; + n->data = d; + for (q = 0, p = list; p; q = p, p = p->next) + if (f(p->data, d) >= 0) + break; + /* insert between q and p; if !q insert at head */ + if (q) + q->next = n; + else + list = n; + n->next = p; + return list; +} + +/* + * Every element of the list points to things which need + * to be free()'d. This method frees the list's contents + */ +void sdp_list_free(sdp_list_t *list, sdp_free_func_t f) +{ + sdp_list_t *next; + while (list) { + next = list->next; + if (f) + f(list->data); + free(list); + list = next; + } +} + +static inline int __find_port(sdp_data_t *seq, int proto) +{ + if (!seq || !seq->next) + return 0; + + if (SDP_IS_UUID(seq->dtd) && sdp_uuid_to_proto(&seq->val.uuid) == proto) { + seq = seq->next; + switch (seq->dtd) { + case SDP_UINT8: + return seq->val.uint8; + case SDP_UINT16: + return seq->val.uint16; + } + } + return 0; +} + +int sdp_get_proto_port(const sdp_list_t *list, int proto) +{ + if (proto != L2CAP_UUID && proto != RFCOMM_UUID) { + errno = EINVAL; + return -1; + } + + for (; list; list = list->next) { + sdp_list_t *p; + for (p = list->data; p; p = p->next) { + sdp_data_t *seq = p->data; + int port = __find_port(seq, proto); + if (port) + return port; + } + } + return 0; +} + +sdp_data_t *sdp_get_proto_desc(sdp_list_t *list, int proto) +{ + for (; list; list = list->next) { + sdp_list_t *p; + for (p = list->data; p; p = p->next) { + sdp_data_t *seq = p->data; + if (SDP_IS_UUID(seq->dtd) && + sdp_uuid_to_proto(&seq->val.uuid) == proto) + return seq->next; + } + } + return NULL; +} + +static int sdp_get_proto_descs(uint16_t attr_id, const sdp_record_t *rec, + sdp_list_t **pap) +{ + sdp_data_t *pdlist, *curr; + sdp_list_t *ap = NULL; + + pdlist = sdp_data_get(rec, attr_id); + if (pdlist == NULL) { + errno = ENODATA; + return -1; + } + + SDPDBG("Attribute value type: 0x%02x", pdlist->dtd); + + if (attr_id == SDP_ATTR_ADD_PROTO_DESC_LIST) { + if (!SDP_IS_SEQ(pdlist->dtd)) { + errno = EINVAL; + return -1; + } + pdlist = pdlist->val.dataseq; + } + + for (; pdlist; pdlist = pdlist->next) { + sdp_list_t *pds = NULL; + + if (!SDP_IS_SEQ(pdlist->dtd) && !SDP_IS_ALT(pdlist->dtd)) + goto failed; + + for (curr = pdlist->val.dataseq; curr; curr = curr->next) { + if (!SDP_IS_SEQ(curr->dtd)) { + sdp_list_free(pds, NULL); + goto failed; + } + pds = sdp_list_append(pds, curr->val.dataseq); + } + + ap = sdp_list_append(ap, pds); + } + + *pap = ap; + + return 0; + +failed: + sdp_list_foreach(ap, (sdp_list_func_t) sdp_list_free, NULL); + sdp_list_free(ap, NULL); + errno = EINVAL; + + return -1; +} + +int sdp_get_access_protos(const sdp_record_t *rec, sdp_list_t **pap) +{ + return sdp_get_proto_descs(SDP_ATTR_PROTO_DESC_LIST, rec, pap); +} + +int sdp_get_add_access_protos(const sdp_record_t *rec, sdp_list_t **pap) +{ + return sdp_get_proto_descs(SDP_ATTR_ADD_PROTO_DESC_LIST, rec, pap); +} + +int sdp_get_uuidseq_attr(const sdp_record_t *rec, uint16_t attr, + sdp_list_t **seqp) +{ + sdp_data_t *sdpdata = sdp_data_get(rec, attr); + + *seqp = NULL; + if (sdpdata && SDP_IS_SEQ(sdpdata->dtd)) { + sdp_data_t *d; + for (d = sdpdata->val.dataseq; d; d = d->next) { + uuid_t *u; + if (d->dtd < SDP_UUID16 || d->dtd > SDP_UUID128) { + errno = EINVAL; + goto fail; + } + + u = malloc(sizeof(uuid_t)); + if (!u) + goto fail; + + *u = d->val.uuid; + *seqp = sdp_list_append(*seqp, u); + } + return 0; + } +fail: + sdp_list_free(*seqp, free); + *seqp = NULL; + return -1; +} + +int sdp_set_uuidseq_attr(sdp_record_t *rec, uint16_t aid, sdp_list_t *seq) +{ + int status = 0, i, len; + void **dtds, **values; + uint8_t uuid16 = SDP_UUID16; + uint8_t uuid32 = SDP_UUID32; + uint8_t uuid128 = SDP_UUID128; + sdp_list_t *p; + + len = sdp_list_len(seq); + if (!seq || len == 0) + return -1; + dtds = malloc(len * sizeof(void *)); + if (!dtds) + return -1; + + values = malloc(len * sizeof(void *)); + if (!values) { + free(dtds); + return -1; + } + + for (p = seq, i = 0; i < len; i++, p = p->next) { + uuid_t *uuid = p->data; + if (uuid) + switch (uuid->type) { + case SDP_UUID16: + dtds[i] = &uuid16; + values[i] = &uuid->value.uuid16; + break; + case SDP_UUID32: + dtds[i] = &uuid32; + values[i] = &uuid->value.uuid32; + break; + case SDP_UUID128: + dtds[i] = &uuid128; + values[i] = &uuid->value.uuid128; + break; + default: + status = -1; + break; + } + else { + status = -1; + break; + } + } + if (status == 0) { + sdp_data_t *data = sdp_seq_alloc(dtds, values, len); + sdp_attr_replace(rec, aid, data); + sdp_pattern_add_uuidseq(rec, seq); + } + free(dtds); + free(values); + return status; +} + +int sdp_get_lang_attr(const sdp_record_t *rec, sdp_list_t **langSeq) +{ + sdp_lang_attr_t *lang; + sdp_data_t *sdpdata, *curr_data; + + *langSeq = NULL; + sdpdata = sdp_data_get(rec, SDP_ATTR_LANG_BASE_ATTR_ID_LIST); + if (sdpdata == NULL) { + errno = ENODATA; + return -1; + } + + if (!SDP_IS_SEQ(sdpdata->dtd)) + goto invalid; + curr_data = sdpdata->val.dataseq; + + while (curr_data) { + sdp_data_t *pCode, *pEncoding, *pOffset; + + pCode = curr_data; + if (pCode->dtd != SDP_UINT16) + goto invalid; + + /* LanguageBaseAttributeIDList entries are always grouped as + * triplets */ + if (!pCode->next || !pCode->next->next) + goto invalid; + + pEncoding = pCode->next; + if (pEncoding->dtd != SDP_UINT16) + goto invalid; + + pOffset = pEncoding->next; + if (pOffset->dtd != SDP_UINT16) + goto invalid; + + lang = malloc(sizeof(sdp_lang_attr_t)); + if (!lang) { + sdp_list_free(*langSeq, free); + *langSeq = NULL; + return -1; + } + lang->code_ISO639 = pCode->val.uint16; + lang->encoding = pEncoding->val.uint16; + lang->base_offset = pOffset->val.uint16; + SDPDBG("code_ISO639 : 0x%02x", lang->code_ISO639); + SDPDBG("encoding : 0x%02x", lang->encoding); + SDPDBG("base_offfset : 0x%02x", lang->base_offset); + *langSeq = sdp_list_append(*langSeq, lang); + + curr_data = pOffset->next; + } + + return 0; + +invalid: + sdp_list_free(*langSeq, free); + *langSeq = NULL; + errno = EINVAL; + + return -1; +} + +int sdp_get_profile_descs(const sdp_record_t *rec, sdp_list_t **profDescSeq) +{ + sdp_profile_desc_t *profDesc; + sdp_data_t *sdpdata, *seq; + + *profDescSeq = NULL; + sdpdata = sdp_data_get(rec, SDP_ATTR_PFILE_DESC_LIST); + if (sdpdata == NULL) { + errno = ENODATA; + return -1; + } + + if (!SDP_IS_SEQ(sdpdata->dtd) || sdpdata->val.dataseq == NULL) + goto invalid; + + for (seq = sdpdata->val.dataseq; seq; seq = seq->next) { + uuid_t *uuid = NULL; + uint16_t version = 0x100; + + if (SDP_IS_UUID(seq->dtd)) { + /* Mac OS X 10.7.3 and old Samsung phones do not comply + * to the SDP specification for + * BluetoothProfileDescriptorList. This workaround + * allows to properly parse UUID/version from SDP + * record published by these systems. */ + sdp_data_t *next = seq->next; + uuid = &seq->val.uuid; + if (next && next->dtd == SDP_UINT16) { + version = next->val.uint16; + seq = next; + } + } else if (SDP_IS_SEQ(seq->dtd)) { + sdp_data_t *puuid, *pVnum; + + puuid = seq->val.dataseq; + if (puuid == NULL || !SDP_IS_UUID(puuid->dtd)) + goto invalid; + + uuid = &puuid->val.uuid; + + pVnum = puuid->next; + if (pVnum == NULL || pVnum->dtd != SDP_UINT16) + goto invalid; + + version = pVnum->val.uint16; + } else + goto invalid; + + if (uuid != NULL) { + profDesc = malloc(sizeof(sdp_profile_desc_t)); + if (!profDesc) { + sdp_list_free(*profDescSeq, free); + *profDescSeq = NULL; + return -1; + } + profDesc->uuid = *uuid; + profDesc->version = version; +#ifdef SDP_DEBUG + sdp_uuid_print(&profDesc->uuid); + SDPDBG("Vnum : 0x%04x", profDesc->version); +#endif + *profDescSeq = sdp_list_append(*profDescSeq, profDesc); + } + } + return 0; + +invalid: + sdp_list_free(*profDescSeq, free); + *profDescSeq = NULL; + errno = EINVAL; + + return -1; +} + +int sdp_get_server_ver(const sdp_record_t *rec, sdp_list_t **u16) +{ + sdp_data_t *d, *curr; + + *u16 = NULL; + d = sdp_data_get(rec, SDP_ATTR_VERSION_NUM_LIST); + if (d == NULL) { + errno = ENODATA; + return -1; + } + + if (!SDP_IS_SEQ(d->dtd) || d->val.dataseq == NULL) + goto invalid; + + for (curr = d->val.dataseq; curr; curr = curr->next) { + if (curr->dtd != SDP_UINT16) + goto invalid; + *u16 = sdp_list_append(*u16, &curr->val.uint16); + } + + return 0; + +invalid: + sdp_list_free(*u16, NULL); + *u16 = NULL; + errno = EINVAL; + + return -1; +} + +/* flexible extraction of basic attributes - Jean II */ +/* How do we expect caller to extract predefined data sequences? */ +int sdp_get_int_attr(const sdp_record_t *rec, uint16_t attrid, int *value) +{ + sdp_data_t *sdpdata = sdp_data_get(rec, attrid); + + if (sdpdata) + /* Verify that it is what the caller expects */ + if (sdpdata->dtd == SDP_BOOL || sdpdata->dtd == SDP_UINT8 || + sdpdata->dtd == SDP_UINT16 || sdpdata->dtd == SDP_UINT32 || + sdpdata->dtd == SDP_INT8 || sdpdata->dtd == SDP_INT16 || + sdpdata->dtd == SDP_INT32) { + *value = sdpdata->val.uint32; + return 0; + } + errno = EINVAL; + return -1; +} + +int sdp_get_string_attr(const sdp_record_t *rec, uint16_t attrid, char *value, + int valuelen) +{ + sdp_data_t *sdpdata = sdp_data_get(rec, attrid); + if (sdpdata) + /* Verify that it is what the caller expects */ + if (SDP_IS_TEXT_STR(sdpdata->dtd)) + if ((int) strlen(sdpdata->val.str) < valuelen) { + strcpy(value, sdpdata->val.str); + return 0; + } + errno = EINVAL; + return -1; +} + +#define get_basic_attr(attrID, pAttrValue, fieldName) \ + sdp_data_t *data = sdp_data_get(rec, attrID); \ + if (data) { \ + *pAttrValue = data->val.fieldName; \ + return 0; \ + } \ + errno = EINVAL; \ + return -1; + +int sdp_get_service_id(const sdp_record_t *rec, uuid_t *uuid) +{ + get_basic_attr(SDP_ATTR_SERVICE_ID, uuid, uuid); +} + +int sdp_get_group_id(const sdp_record_t *rec, uuid_t *uuid) +{ + get_basic_attr(SDP_ATTR_GROUP_ID, uuid, uuid); +} + +int sdp_get_record_state(const sdp_record_t *rec, uint32_t *svcRecState) +{ + get_basic_attr(SDP_ATTR_RECORD_STATE, svcRecState, uint32); +} + +int sdp_get_service_avail(const sdp_record_t *rec, uint8_t *svcAvail) +{ + get_basic_attr(SDP_ATTR_SERVICE_AVAILABILITY, svcAvail, uint8); +} + +int sdp_get_service_ttl(const sdp_record_t *rec, uint32_t *svcTTLInfo) +{ + get_basic_attr(SDP_ATTR_SVCINFO_TTL, svcTTLInfo, uint32); +} + +int sdp_get_database_state(const sdp_record_t *rec, uint32_t *svcDBState) +{ + get_basic_attr(SDP_ATTR_SVCDB_STATE, svcDBState, uint32); +} + +/* + * NOTE that none of the setXXX() functions below will + * actually update the SDP server, unless the + * {register, update}sdp_record_t() function is invoked. + */ + +int sdp_attr_add_new(sdp_record_t *rec, uint16_t attr, uint8_t dtd, + const void *value) +{ + sdp_data_t *d = sdp_data_alloc(dtd, value); + if (d) { + sdp_attr_replace(rec, attr, d); + return 0; + } + return -1; +} + +static int sdp_attr_add_new_with_length(sdp_record_t *rec, + uint16_t attr, uint8_t dtd, const void *value, uint32_t len) +{ + sdp_data_t *d; + + d = sdp_data_alloc_with_length(dtd, value, len); + if (!d) + return -1; + + sdp_attr_replace(rec, attr, d); + + return 0; +} + +/* + * Set the information attributes of the service + * pointed to by rec. The attributes are + * service name, description and provider name + */ +void sdp_set_info_attr(sdp_record_t *rec, const char *name, const char *prov, + const char *desc) +{ + if (name) + sdp_attr_add_new(rec, SDP_ATTR_SVCNAME_PRIMARY, + SDP_TEXT_STR8, name); + if (prov) + sdp_attr_add_new(rec, SDP_ATTR_PROVNAME_PRIMARY, + SDP_TEXT_STR8, prov); + if (desc) + sdp_attr_add_new(rec, SDP_ATTR_SVCDESC_PRIMARY, + SDP_TEXT_STR8, desc); +} + +static sdp_data_t *access_proto_to_dataseq(sdp_record_t *rec, sdp_list_t *proto) +{ + sdp_data_t *seq = NULL; + void *dtds[10], *values[10]; + void **seqDTDs, **seqs; + int i, seqlen; + sdp_list_t *p; + + seqlen = sdp_list_len(proto); + seqDTDs = malloc(seqlen * sizeof(void *)); + if (!seqDTDs) + return NULL; + + seqs = malloc(seqlen * sizeof(void *)); + if (!seqs) { + free(seqDTDs); + return NULL; + } + + for (i = 0, p = proto; p; p = p->next, i++) { + sdp_list_t *elt = p->data; + sdp_data_t *s; + uuid_t *uuid = NULL; + unsigned int pslen = 0; + for (; elt && pslen < ARRAY_SIZE(dtds); elt = elt->next, pslen++) { + sdp_data_t *d = elt->data; + dtds[pslen] = &d->dtd; + switch (d->dtd) { + case SDP_UUID16: + uuid = (uuid_t *) d; + values[pslen] = &uuid->value.uuid16; + break; + case SDP_UUID32: + uuid = (uuid_t *) d; + values[pslen] = &uuid->value.uuid32; + break; + case SDP_UUID128: + uuid = (uuid_t *) d; + values[pslen] = &uuid->value.uuid128; + break; + case SDP_UINT8: + values[pslen] = &d->val.uint8; + break; + case SDP_UINT16: + values[pslen] = &d->val.uint16; + break; + case SDP_SEQ8: + case SDP_SEQ16: + case SDP_SEQ32: + values[pslen] = d; + break; + /* FIXME: more */ + } + } + s = sdp_seq_alloc(dtds, values, pslen); + if (s) { + seqDTDs[i] = &s->dtd; + seqs[i] = s; + if (uuid) + sdp_pattern_add_uuid(rec, uuid); + } + } + seq = sdp_seq_alloc(seqDTDs, seqs, seqlen); + free(seqDTDs); + free(seqs); + return seq; +} + +/* + * sets the access protocols of the service specified + * to the value specified in "access_proto" + * + * Note that if there are alternate mechanisms by + * which the service is accessed, then they should + * be specified as sequences + * + * Using a value of NULL for accessProtocols has + * effect of removing this attribute (if previously set) + * + * This function replaces the existing sdp_access_proto_t + * structure (if any) with the new one specified. + * + * returns 0 if successful or -1 if there is a failure. + */ +int sdp_set_access_protos(sdp_record_t *rec, const sdp_list_t *ap) +{ + const sdp_list_t *p; + sdp_data_t *protos = NULL; + + for (p = ap; p; p = p->next) { + sdp_data_t *seq = access_proto_to_dataseq(rec, p->data); + protos = sdp_seq_append(protos, seq); + } + + sdp_attr_add(rec, SDP_ATTR_PROTO_DESC_LIST, protos); + + return 0; +} + +int sdp_set_add_access_protos(sdp_record_t *rec, const sdp_list_t *ap) +{ + const sdp_list_t *p; + sdp_data_t *protos = NULL; + + for (p = ap; p; p = p->next) { + sdp_data_t *seq = access_proto_to_dataseq(rec, p->data); + protos = sdp_seq_append(protos, seq); + } + + sdp_attr_add(rec, SDP_ATTR_ADD_PROTO_DESC_LIST, + protos ? sdp_data_alloc(SDP_SEQ8, protos) : NULL); + + return 0; +} + +/* + * set the "LanguageBase" attributes of the service record + * record to the value specified in "langAttrList". + * + * "langAttrList" is a linked list of "sdp_lang_attr_t" + * objects, one for each language in which user visible + * attributes are present in the service record. + * + * Using a value of NULL for langAttrList has + * effect of removing this attribute (if previously set) + * + * This function replaces the exisiting sdp_lang_attr_t + * structure (if any) with the new one specified. + * + * returns 0 if successful or -1 if there is a failure. + */ +int sdp_set_lang_attr(sdp_record_t *rec, const sdp_list_t *seq) +{ + uint8_t uint16 = SDP_UINT16; + int status = 0, i = 0, seqlen = sdp_list_len(seq); + void **dtds, **values; + const sdp_list_t *p; + + dtds = malloc(3 * seqlen * sizeof(void *)); + if (!dtds) + return -1; + + values = malloc(3 * seqlen * sizeof(void *)); + if (!values) { + free(dtds); + return -1; + } + + for (p = seq; p; p = p->next) { + sdp_lang_attr_t *lang = p->data; + if (!lang) { + status = -1; + break; + } + dtds[i] = &uint16; + values[i] = &lang->code_ISO639; + i++; + dtds[i] = &uint16; + values[i] = &lang->encoding; + i++; + dtds[i] = &uint16; + values[i] = &lang->base_offset; + i++; + } + if (status == 0) { + sdp_data_t *seq = sdp_seq_alloc(dtds, values, 3 * seqlen); + sdp_attr_add(rec, SDP_ATTR_LANG_BASE_ATTR_ID_LIST, seq); + } + free(dtds); + free(values); + return status; +} + +/* + * set the "ServiceID" attribute of the service. + * + * This is the UUID of the service. + * + * returns 0 if successful or -1 if there is a failure. + */ +void sdp_set_service_id(sdp_record_t *rec, uuid_t uuid) +{ + switch (uuid.type) { + case SDP_UUID16: + sdp_attr_add_new(rec, SDP_ATTR_SERVICE_ID, SDP_UUID16, + &uuid.value.uuid16); + break; + case SDP_UUID32: + sdp_attr_add_new(rec, SDP_ATTR_SERVICE_ID, SDP_UUID32, + &uuid.value.uuid32); + break; + case SDP_UUID128: + sdp_attr_add_new(rec, SDP_ATTR_SERVICE_ID, SDP_UUID128, + &uuid.value.uuid128); + break; + } + sdp_pattern_add_uuid(rec, &uuid); +} + +/* + * set the GroupID attribute of the service record defining a group. + * + * This is the UUID of the group. + * + * returns 0 if successful or -1 if there is a failure. + */ +void sdp_set_group_id(sdp_record_t *rec, uuid_t uuid) +{ + switch (uuid.type) { + case SDP_UUID16: + sdp_attr_add_new(rec, SDP_ATTR_GROUP_ID, SDP_UUID16, + &uuid.value.uuid16); + break; + case SDP_UUID32: + sdp_attr_add_new(rec, SDP_ATTR_GROUP_ID, SDP_UUID32, + &uuid.value.uuid32); + break; + case SDP_UUID128: + sdp_attr_add_new(rec, SDP_ATTR_GROUP_ID, SDP_UUID128, + &uuid.value.uuid128); + break; + } + sdp_pattern_add_uuid(rec, &uuid); +} + +/* + * set the ProfileDescriptorList attribute of the service record + * pointed to by record to the value specified in "profileDesc". + * + * Each element in the list is an object of type + * sdp_profile_desc_t which is a definition of the + * Bluetooth profile that this service conforms to. + * + * Using a value of NULL for profileDesc has + * effect of removing this attribute (if previously set) + * + * This function replaces the exisiting ProfileDescriptorList + * structure (if any) with the new one specified. + * + * returns 0 if successful or -1 if there is a failure. + */ +int sdp_set_profile_descs(sdp_record_t *rec, const sdp_list_t *profiles) +{ + int status = 0; + uint8_t uuid16 = SDP_UUID16; + uint8_t uuid32 = SDP_UUID32; + uint8_t uuid128 = SDP_UUID128; + uint8_t uint16 = SDP_UINT16; + int i = 0, seqlen = sdp_list_len(profiles); + void **seqDTDs, **seqs; + const sdp_list_t *p; + sdp_data_t *pAPSeq; + + seqDTDs = malloc(seqlen * sizeof(void *)); + if (!seqDTDs) + return -1; + + seqs = malloc(seqlen * sizeof(void *)); + if (!seqs) { + free(seqDTDs); + return -1; + } + + for (p = profiles; p; p = p->next) { + sdp_data_t *seq; + void *dtds[2], *values[2]; + sdp_profile_desc_t *profile = p->data; + if (!profile) { + status = -1; + goto end; + } + switch (profile->uuid.type) { + case SDP_UUID16: + dtds[0] = &uuid16; + values[0] = &profile->uuid.value.uuid16; + break; + case SDP_UUID32: + dtds[0] = &uuid32; + values[0] = &profile->uuid.value.uuid32; + break; + case SDP_UUID128: + dtds[0] = &uuid128; + values[0] = &profile->uuid.value.uuid128; + break; + default: + status = -1; + goto end; + } + dtds[1] = &uint16; + values[1] = &profile->version; + seq = sdp_seq_alloc(dtds, values, 2); + + if (seq == NULL) { + status = -1; + goto end; + } + + seqDTDs[i] = &seq->dtd; + seqs[i] = seq; + sdp_pattern_add_uuid(rec, &profile->uuid); + i++; + } + + pAPSeq = sdp_seq_alloc(seqDTDs, seqs, seqlen); + sdp_attr_add(rec, SDP_ATTR_PFILE_DESC_LIST, pAPSeq); +end: + free(seqDTDs); + free(seqs); + return status; +} + +/* + * sets various URL attributes of the service + * pointed to by record. The URL include + * + * client: a URL to the client's + * platform specific (WinCE, PalmOS) executable + * code that can be used to access this service. + * + * doc: a URL pointing to service documentation + * + * icon: a URL to an icon that can be used to represent + * this service. + * + * Note that you need to pass NULL for any URLs + * that you don't want to set or remove + */ +void sdp_set_url_attr(sdp_record_t *rec, const char *client, const char *doc, + const char *icon) +{ + sdp_attr_add_new(rec, SDP_ATTR_CLNT_EXEC_URL, SDP_URL_STR8, client); + sdp_attr_add_new(rec, SDP_ATTR_DOC_URL, SDP_URL_STR8, doc); + sdp_attr_add_new(rec, SDP_ATTR_ICON_URL, SDP_URL_STR8, icon); +} + +uuid_t *sdp_uuid16_create(uuid_t *u, uint16_t val) +{ + memset(u, 0, sizeof(uuid_t)); + u->type = SDP_UUID16; + u->value.uuid16 = val; + return u; +} + +uuid_t *sdp_uuid32_create(uuid_t *u, uint32_t val) +{ + memset(u, 0, sizeof(uuid_t)); + u->type = SDP_UUID32; + u->value.uuid32 = val; + return u; +} + +uuid_t *sdp_uuid128_create(uuid_t *u, const void *val) +{ + memset(u, 0, sizeof(uuid_t)); + u->type = SDP_UUID128; + memcpy(&u->value.uuid128, val, sizeof(uint128_t)); + return u; +} + +/* + * UUID comparison function + * returns 0 if uuidValue1 == uuidValue2 else -1 + */ +int sdp_uuid_cmp(const void *p1, const void *p2) +{ + uuid_t *u1 = sdp_uuid_to_uuid128(p1); + uuid_t *u2 = sdp_uuid_to_uuid128(p2); + int ret; + + ret = sdp_uuid128_cmp(u1, u2); + + bt_free(u1); + bt_free(u2); + + return ret; +} + +/* + * UUID comparison function + * returns 0 if uuidValue1 == uuidValue2 else -1 + */ +int sdp_uuid16_cmp(const void *p1, const void *p2) +{ + const uuid_t *u1 = p1; + const uuid_t *u2 = p2; + return memcmp(&u1->value.uuid16, &u2->value.uuid16, sizeof(uint16_t)); +} + +/* + * UUID comparison function + * returns 0 if uuidValue1 == uuidValue2 else -1 + */ +int sdp_uuid128_cmp(const void *p1, const void *p2) +{ + const uuid_t *u1 = p1; + const uuid_t *u2 = p2; + return memcmp(&u1->value.uuid128, &u2->value.uuid128, sizeof(uint128_t)); +} + +/* + * 128 to 16 bit and 32 to 16 bit UUID conversion functions + * yet to be implemented. Note that the input is in NBO in + * both 32 and 128 bit UUIDs and conversion is needed + */ +void sdp_uuid16_to_uuid128(uuid_t *uuid128, const uuid_t *uuid16) +{ + /* + * We have a 16 bit value, which needs to be added to + * bytes 3 and 4 (at indices 2 and 3) of the Bluetooth base + */ + unsigned short data1; + + /* allocate a 128bit UUID and init to the Bluetooth base UUID */ + uuid128->value.uuid128 = bluetooth_base_uuid; + uuid128->type = SDP_UUID128; + + /* extract bytes 2 and 3 of 128bit BT base UUID */ + memcpy(&data1, &bluetooth_base_uuid.data[2], 2); + + /* add the given UUID (16 bits) */ + data1 += htons(uuid16->value.uuid16); + + /* set bytes 2 and 3 of the 128 bit value */ + memcpy(&uuid128->value.uuid128.data[2], &data1, 2); +} + +void sdp_uuid32_to_uuid128(uuid_t *uuid128, const uuid_t *uuid32) +{ + /* + * We have a 32 bit value, which needs to be added to + * bytes 1->4 (at indices 0 thru 3) of the Bluetooth base + */ + unsigned int data0; + + /* allocate a 128bit UUID and init to the Bluetooth base UUID */ + uuid128->value.uuid128 = bluetooth_base_uuid; + uuid128->type = SDP_UUID128; + + /* extract first 4 bytes */ + memcpy(&data0, &bluetooth_base_uuid.data[0], 4); + + /* add the given UUID (32bits) */ + data0 += htonl(uuid32->value.uuid32); + + /* set the 4 bytes of the 128 bit value */ + memcpy(&uuid128->value.uuid128.data[0], &data0, 4); +} + +uuid_t *sdp_uuid_to_uuid128(const uuid_t *uuid) +{ + uuid_t *uuid128 = bt_malloc(sizeof(uuid_t)); + + if (!uuid128) + return NULL; + + memset(uuid128, 0, sizeof(uuid_t)); + switch (uuid->type) { + case SDP_UUID128: + *uuid128 = *uuid; + break; + case SDP_UUID32: + sdp_uuid32_to_uuid128(uuid128, uuid); + break; + case SDP_UUID16: + sdp_uuid16_to_uuid128(uuid128, uuid); + break; + } + return uuid128; +} + +/* + * converts a 128-bit uuid to a 16/32-bit one if possible + * returns true if uuid contains a 16/32-bit UUID at exit + */ +int sdp_uuid128_to_uuid(uuid_t *uuid) +{ + uint128_t *b = &bluetooth_base_uuid; + uint128_t *u = &uuid->value.uuid128; + uint32_t data; + unsigned int i; + + if (uuid->type != SDP_UUID128) + return 1; + + for (i = 4; i < sizeof(b->data); i++) + if (b->data[i] != u->data[i]) + return 0; + + memcpy(&data, u->data, 4); + data = htonl(data); + if (data <= 0xffff) { + uuid->type = SDP_UUID16; + uuid->value.uuid16 = (uint16_t) data; + } else { + uuid->type = SDP_UUID32; + uuid->value.uuid32 = data; + } + return 1; +} + +/* + * convert a UUID to the 16-bit short-form + */ +int sdp_uuid_to_proto(uuid_t *uuid) +{ + uuid_t u = *uuid; + if (sdp_uuid128_to_uuid(&u)) { + switch (u.type) { + case SDP_UUID16: + return u.value.uuid16; + case SDP_UUID32: + return u.value.uuid32; + } + } + return 0; +} + +/* + * This function appends data to the PDU buffer "dst" from source "src". + * The data length is also computed and set. + * Should the PDU length exceed 2^8, then sequence type is + * set accordingly and the data is memmove()'d. + */ +void sdp_append_to_buf(sdp_buf_t *dst, uint8_t *data, uint32_t len) +{ + uint8_t *p = dst->data; + uint8_t dtd = *p; + + SDPDBG("Append src size: %d", len); + SDPDBG("Append dst size: %d", dst->data_size); + SDPDBG("Dst buffer size: %d", dst->buf_size); + if (dst->data_size == 0 && dtd == 0) { + /* create initial sequence */ + *p = SDP_SEQ8; + dst->data_size += sizeof(uint8_t); + /* reserve space for sequence size */ + dst->data_size += sizeof(uint8_t); + } + + memcpy(dst->data + dst->data_size, data, len); + dst->data_size += len; + + dtd = *(uint8_t *) dst->data; + if (dst->data_size > UCHAR_MAX && dtd == SDP_SEQ8) { + short offset = sizeof(uint8_t) + sizeof(uint8_t); + memmove(dst->data + offset + 1, dst->data + offset, + dst->data_size - offset); + *p = SDP_SEQ16; + dst->data_size += 1; + } + dtd = *(uint8_t *) p; + p += sizeof(uint8_t); + switch (dtd) { + case SDP_SEQ8: + *(uint8_t *) p = dst->data_size - sizeof(uint8_t) - sizeof(uint8_t); + break; + case SDP_SEQ16: + bt_put_be16(dst->data_size - sizeof(uint8_t) - sizeof(uint16_t), p); + break; + case SDP_SEQ32: + bt_put_be32(dst->data_size - sizeof(uint8_t) - sizeof(uint32_t), p); + break; + } +} + +void sdp_append_to_pdu(sdp_buf_t *pdu, sdp_data_t *d) +{ + sdp_buf_t append; + + memset(&append, 0, sizeof(sdp_buf_t)); + sdp_gen_buffer(&append, d); + append.data = malloc(append.buf_size); + if (!append.data) + return; + + sdp_set_attrid(&append, d->attrId); + sdp_gen_pdu(&append, d); + sdp_append_to_buf(pdu, append.data, append.data_size); + free(append.data); +} + +/* + * Registers an sdp record. + * + * It is incorrect to call this method on a record that + * has been already registered with the server. + * + * Returns zero on success, otherwise -1 (and sets errno). + */ +int sdp_device_record_register_binary(sdp_session_t *session, bdaddr_t *device, uint8_t *data, uint32_t size, uint8_t flags, uint32_t *handle) +{ + uint8_t *req, *rsp, *p; + uint32_t reqsize, rspsize; + sdp_pdu_hdr_t *reqhdr, *rsphdr; + int status; + + SDPDBG(""); + + if (!session->local) { + errno = EREMOTE; + return -1; + } + req = malloc(SDP_REQ_BUFFER_SIZE); + rsp = malloc(SDP_RSP_BUFFER_SIZE); + if (req == NULL || rsp == NULL) { + status = -1; + errno = ENOMEM; + goto end; + } + + reqhdr = (sdp_pdu_hdr_t *)req; + reqhdr->pdu_id = SDP_SVC_REGISTER_REQ; + reqhdr->tid = htons(sdp_gen_tid(session)); + reqsize = sizeof(sdp_pdu_hdr_t) + 1; + p = req + sizeof(sdp_pdu_hdr_t); + + if (bacmp(device, BDADDR_ANY)) { + *p++ = flags | SDP_DEVICE_RECORD; + bacpy((bdaddr_t *) p, device); + p += sizeof(bdaddr_t); + reqsize += sizeof(bdaddr_t); + } else + *p++ = flags; + + memcpy(p, data, size); + reqsize += size; + reqhdr->plen = htons(reqsize - sizeof(sdp_pdu_hdr_t)); + + status = sdp_send_req_w4_rsp(session, req, rsp, reqsize, &rspsize); + if (status < 0) + goto end; + + if (rspsize < sizeof(sdp_pdu_hdr_t)) { + SDPERR("Unexpected end of packet"); + errno = EPROTO; + status = -1; + goto end; + } + + rsphdr = (sdp_pdu_hdr_t *) rsp; + p = rsp + sizeof(sdp_pdu_hdr_t); + + if (rsphdr->pdu_id == SDP_ERROR_RSP) { + /* Invalid service record */ + errno = EINVAL; + status = -1; + } else if (rsphdr->pdu_id != SDP_SVC_REGISTER_RSP) { + errno = EPROTO; + status = -1; + } else { + if (rspsize < sizeof(sdp_pdu_hdr_t) + sizeof(uint32_t)) { + SDPERR("Unexpected end of packet"); + errno = EPROTO; + status = -1; + goto end; + } + if (handle) + *handle = bt_get_be32(p); + } + +end: + free(req); + free(rsp); + + return status; +} + +int sdp_device_record_register(sdp_session_t *session, bdaddr_t *device, sdp_record_t *rec, uint8_t flags) +{ + sdp_buf_t pdu; + uint32_t handle; + int err; + + SDPDBG(""); + + if (rec->handle && rec->handle != 0xffffffff) { + uint32_t handle = rec->handle; + sdp_data_t *data = sdp_data_alloc(SDP_UINT32, &handle); + sdp_attr_replace(rec, SDP_ATTR_RECORD_HANDLE, data); + } + + if (sdp_gen_record_pdu(rec, &pdu) < 0) { + errno = ENOMEM; + return -1; + } + + err = sdp_device_record_register_binary(session, device, + pdu.data, pdu.data_size, flags, &handle); + + free(pdu.data); + + if (err == 0) { + sdp_data_t *data = sdp_data_alloc(SDP_UINT32, &handle); + rec->handle = handle; + sdp_attr_replace(rec, SDP_ATTR_RECORD_HANDLE, data); + } + + return err; +} + +int sdp_record_register(sdp_session_t *session, sdp_record_t *rec, uint8_t flags) +{ + return sdp_device_record_register(session, BDADDR_ANY, rec, flags); +} + +/* + * unregister a service record + */ +int sdp_device_record_unregister_binary(sdp_session_t *session, bdaddr_t *device, uint32_t handle) +{ + uint8_t *reqbuf, *rspbuf, *p; + uint32_t reqsize = 0, rspsize = 0; + sdp_pdu_hdr_t *reqhdr, *rsphdr; + int status; + + SDPDBG(""); + + if (handle == SDP_SERVER_RECORD_HANDLE) { + errno = EINVAL; + return -1; + } + + if (!session->local) { + errno = EREMOTE; + return -1; + } + + reqbuf = malloc(SDP_REQ_BUFFER_SIZE); + rspbuf = malloc(SDP_RSP_BUFFER_SIZE); + if (!reqbuf || !rspbuf) { + errno = ENOMEM; + status = -1; + goto end; + } + reqhdr = (sdp_pdu_hdr_t *) reqbuf; + reqhdr->pdu_id = SDP_SVC_REMOVE_REQ; + reqhdr->tid = htons(sdp_gen_tid(session)); + + p = reqbuf + sizeof(sdp_pdu_hdr_t); + reqsize = sizeof(sdp_pdu_hdr_t); + bt_put_be32(handle, p); + reqsize += sizeof(uint32_t); + + reqhdr->plen = htons(reqsize - sizeof(sdp_pdu_hdr_t)); + status = sdp_send_req_w4_rsp(session, reqbuf, rspbuf, reqsize, &rspsize); + if (status < 0) + goto end; + + if (rspsize < sizeof(sdp_pdu_hdr_t) + sizeof(uint16_t)) { + SDPERR("Unexpected end of packet"); + errno = EPROTO; + status = -1; + goto end; + } + + rsphdr = (sdp_pdu_hdr_t *) rspbuf; + p = rspbuf + sizeof(sdp_pdu_hdr_t); + + if (rsphdr->pdu_id == SDP_ERROR_RSP) { + /* For this case the status always is invalid record handle */ + errno = EINVAL; + status = -1; + } else if (rsphdr->pdu_id != SDP_SVC_REMOVE_RSP) { + errno = EPROTO; + status = -1; + } else { + uint16_t tmp; + + memcpy(&tmp, p, sizeof(tmp)); + + status = tmp; + } +end: + free(reqbuf); + free(rspbuf); + + return status; +} + +int sdp_device_record_unregister(sdp_session_t *session, bdaddr_t *device, sdp_record_t *rec) +{ + int err; + + err = sdp_device_record_unregister_binary(session, device, rec->handle); + if (err == 0) + sdp_record_free(rec); + + return err; +} + +int sdp_record_unregister(sdp_session_t *session, sdp_record_t *rec) +{ + return sdp_device_record_unregister(session, BDADDR_ANY, rec); +} + +/* + * modify an existing service record + */ +int sdp_device_record_update_binary(sdp_session_t *session, bdaddr_t *device, uint32_t handle, uint8_t *data, uint32_t size) +{ + return -1; +} + +int sdp_device_record_update(sdp_session_t *session, bdaddr_t *device, const sdp_record_t *rec) +{ + uint8_t *reqbuf, *rspbuf, *p; + uint32_t reqsize, rspsize; + sdp_pdu_hdr_t *reqhdr, *rsphdr; + uint32_t handle; + sdp_buf_t pdu; + int status; + + SDPDBG(""); + + handle = rec->handle; + + if (handle == SDP_SERVER_RECORD_HANDLE) { + errno = EINVAL; + return -1; + } + if (!session->local) { + errno = EREMOTE; + return -1; + } + reqbuf = malloc(SDP_REQ_BUFFER_SIZE); + rspbuf = malloc(SDP_RSP_BUFFER_SIZE); + if (!reqbuf || !rspbuf) { + errno = ENOMEM; + status = -1; + goto end; + } + reqhdr = (sdp_pdu_hdr_t *) reqbuf; + reqhdr->pdu_id = SDP_SVC_UPDATE_REQ; + reqhdr->tid = htons(sdp_gen_tid(session)); + + p = reqbuf + sizeof(sdp_pdu_hdr_t); + reqsize = sizeof(sdp_pdu_hdr_t); + + bt_put_be32(handle, p); + reqsize += sizeof(uint32_t); + p += sizeof(uint32_t); + + if (sdp_gen_record_pdu(rec, &pdu) < 0) { + errno = ENOMEM; + status = -1; + goto end; + } + memcpy(p, pdu.data, pdu.data_size); + reqsize += pdu.data_size; + free(pdu.data); + + reqhdr->plen = htons(reqsize - sizeof(sdp_pdu_hdr_t)); + status = sdp_send_req_w4_rsp(session, reqbuf, rspbuf, reqsize, &rspsize); + if (status < 0) + goto end; + + if (rspsize < sizeof(sdp_pdu_hdr_t) + sizeof(uint16_t)) { + SDPERR("Unexpected end of packet"); + errno = EPROTO; + status = -1; + goto end; + } + + SDPDBG("Send req status : %d", status); + + rsphdr = (sdp_pdu_hdr_t *) rspbuf; + p = rspbuf + sizeof(sdp_pdu_hdr_t); + + if (rsphdr->pdu_id == SDP_ERROR_RSP) { + /* The status can be invalid sintax or invalid record handle */ + errno = EINVAL; + status = -1; + } else if (rsphdr->pdu_id != SDP_SVC_UPDATE_RSP) { + errno = EPROTO; + status = -1; + } else { + uint16_t tmp; + + memcpy(&tmp, p, sizeof(tmp)); + + status = tmp; + } +end: + free(reqbuf); + free(rspbuf); + return status; +} + +int sdp_record_update(sdp_session_t *session, const sdp_record_t *rec) +{ + return sdp_device_record_update(session, BDADDR_ANY, rec); +} + +sdp_record_t *sdp_record_alloc(void) +{ + sdp_record_t *rec = malloc(sizeof(sdp_record_t)); + + if (!rec) + return NULL; + + memset(rec, 0, sizeof(sdp_record_t)); + rec->handle = 0xffffffff; + return rec; +} + +/* + * Free the contents of a service record + */ +void sdp_record_free(sdp_record_t *rec) +{ + sdp_list_free(rec->attrlist, (sdp_free_func_t) sdp_data_free); + sdp_list_free(rec->pattern, free); + free(rec); +} + +void sdp_pattern_add_uuid(sdp_record_t *rec, uuid_t *uuid) +{ + uuid_t *uuid128 = sdp_uuid_to_uuid128(uuid); + + SDPDBG("Elements in target pattern : %d", sdp_list_len(rec->pattern)); + SDPDBG("Trying to add : 0x%lx", (unsigned long) uuid128); + + if (sdp_list_find(rec->pattern, uuid128, sdp_uuid128_cmp) == NULL) + rec->pattern = sdp_list_insert_sorted(rec->pattern, uuid128, sdp_uuid128_cmp); + else + bt_free(uuid128); + + SDPDBG("Elements in target pattern : %d", sdp_list_len(rec->pattern)); +} + +void sdp_pattern_add_uuidseq(sdp_record_t *rec, sdp_list_t *seq) +{ + for (; seq; seq = seq->next) { + uuid_t *uuid = (uuid_t *)seq->data; + sdp_pattern_add_uuid(rec, uuid); + } +} + +/* + * Extract a sequence of service record handles from a PDU buffer + * and add the entries to a sdp_list_t. Note that the service record + * handles are not in "data element sequence" form, but just like + * an array of service handles + */ +static void extract_record_handle_seq(uint8_t *pdu, int bufsize, sdp_list_t **seq, int count, unsigned int *scanned) +{ + sdp_list_t *pSeq = *seq; + uint8_t *pdata = pdu; + int n; + + for (n = 0; n < count; n++) { + uint32_t *pSvcRec; + if (bufsize < (int) sizeof(uint32_t)) { + SDPERR("Unexpected end of packet"); + break; + } + pSvcRec = malloc(sizeof(uint32_t)); + if (!pSvcRec) + break; + *pSvcRec = bt_get_be32(pdata); + pSeq = sdp_list_append(pSeq, pSvcRec); + pdata += sizeof(uint32_t); + *scanned += sizeof(uint32_t); + bufsize -= sizeof(uint32_t); + } + *seq = pSeq; +} +/* + * Generate the attribute sequence pdu form + * from sdp_list_t elements. Return length of attr seq + */ +static int gen_dataseq_pdu(uint8_t *dst, const sdp_list_t *seq, uint8_t dtd) +{ + sdp_data_t *dataseq; + void **types, **values; + sdp_buf_t buf; + int i, seqlen = sdp_list_len(seq); + + /* Fill up the value and the dtd arrays */ + SDPDBG(""); + + SDPDBG("Seq length : %d", seqlen); + + types = malloc(seqlen * sizeof(void *)); + if (!types) + return -ENOMEM; + + values = malloc(seqlen * sizeof(void *)); + if (!values) { + free(types); + return -ENOMEM; + } + + for (i = 0; i < seqlen; i++) { + void *data = seq->data; + types[i] = &dtd; + if (SDP_IS_UUID(dtd)) + data = &((uuid_t *)data)->value; + values[i] = data; + seq = seq->next; + } + + dataseq = sdp_seq_alloc(types, values, seqlen); + if (!dataseq) { + free(types); + free(values); + return -ENOMEM; + } + + memset(&buf, 0, sizeof(sdp_buf_t)); + sdp_gen_buffer(&buf, dataseq); + buf.data = malloc(buf.buf_size); + + if (!buf.data) { + sdp_data_free(dataseq); + free(types); + free(values); + return -ENOMEM; + } + + SDPDBG("Data Seq : 0x%p", seq); + seqlen = sdp_gen_pdu(&buf, dataseq); + SDPDBG("Copying : %d", buf.data_size); + memcpy(dst, buf.data, buf.data_size); + + sdp_data_free(dataseq); + + free(types); + free(values); + free(buf.data); + return seqlen; +} + +static int gen_searchseq_pdu(uint8_t *dst, const sdp_list_t *seq) +{ + uuid_t *uuid = seq->data; + return gen_dataseq_pdu(dst, seq, uuid->type); +} + +static int gen_attridseq_pdu(uint8_t *dst, const sdp_list_t *seq, uint8_t dataType) +{ + return gen_dataseq_pdu(dst, seq, dataType); +} + +typedef struct { + uint8_t length; + unsigned char data[16]; +} __attribute__ ((packed)) sdp_cstate_t; + +static int copy_cstate(uint8_t *pdata, int pdata_len, const sdp_cstate_t *cstate) +{ + if (cstate) { + uint8_t len = cstate->length; + if (len >= pdata_len) { + SDPERR("Continuation state size exceeds internal buffer"); + len = pdata_len - 1; + } + *pdata++ = len; + memcpy(pdata, cstate->data, len); + return len + 1; + } + *pdata = 0; + return 1; +} + +/* + * This is a service search request. + * + * INPUT : + * + * sdp_list_t *search + * Singly linked list containing elements of the search + * pattern. Each entry in the list is a UUID (DataTypeSDP_UUID16) + * of the service to be searched + * + * uint16_t max_rec_num + * A 16 bit integer which tells the service, the maximum + * entries that the client can handle in the response. The + * server is obliged not to return > max_rec_num entries + * + * OUTPUT : + * + * int return value + * 0: + * The request completed successfully. This does not + * mean the requested services were found + * -1: + * On any failure and sets errno + * + * sdp_list_t **rsp_list + * This variable is set on a successful return if there are + * non-zero service handles. It is a singly linked list of + * service record handles (uint16_t) + */ +int sdp_service_search_req(sdp_session_t *session, const sdp_list_t *search, + uint16_t max_rec_num, sdp_list_t **rsp) +{ + int status = 0; + uint32_t reqsize = 0, _reqsize; + uint32_t rspsize = 0, rsplen; + int seqlen = 0; + int rec_count; + unsigned scanned, pdata_len; + uint8_t *pdata, *_pdata; + uint8_t *reqbuf, *rspbuf; + sdp_pdu_hdr_t *reqhdr, *rsphdr; + sdp_cstate_t *cstate = NULL; + + reqbuf = malloc(SDP_REQ_BUFFER_SIZE); + rspbuf = malloc(SDP_RSP_BUFFER_SIZE); + if (!reqbuf || !rspbuf) { + errno = ENOMEM; + status = -1; + goto end; + } + reqhdr = (sdp_pdu_hdr_t *) reqbuf; + reqhdr->pdu_id = SDP_SVC_SEARCH_REQ; + pdata = reqbuf + sizeof(sdp_pdu_hdr_t); + reqsize = sizeof(sdp_pdu_hdr_t); + + /* add service class IDs for search */ + seqlen = gen_searchseq_pdu(pdata, search); + + SDPDBG("Data seq added : %d", seqlen); + + /* set the length and increment the pointer */ + reqsize += seqlen; + pdata += seqlen; + + /* specify the maximum svc rec count that client expects */ + bt_put_be16(max_rec_num, pdata); + reqsize += sizeof(uint16_t); + pdata += sizeof(uint16_t); + + _reqsize = reqsize; + _pdata = pdata; + *rsp = NULL; + + do { + /* Add continuation state or NULL (first time) */ + reqsize = _reqsize + copy_cstate(_pdata, + SDP_REQ_BUFFER_SIZE - _reqsize, cstate); + + /* Set the request header's param length */ + reqhdr->plen = htons(reqsize - sizeof(sdp_pdu_hdr_t)); + + reqhdr->tid = htons(sdp_gen_tid(session)); + /* + * Send the request, wait for response and if + * no error, set the appropriate values and return + */ + status = sdp_send_req_w4_rsp(session, reqbuf, rspbuf, reqsize, &rspsize); + if (status < 0) + goto end; + + if (rspsize < sizeof(sdp_pdu_hdr_t)) { + SDPERR("Unexpected end of packet"); + status = -1; + goto end; + } + + rsphdr = (sdp_pdu_hdr_t *) rspbuf; + rsplen = ntohs(rsphdr->plen); + + if (rsphdr->pdu_id == SDP_ERROR_RSP) { + SDPDBG("Status : 0x%x", rsphdr->pdu_id); + status = -1; + goto end; + } + scanned = 0; + pdata = rspbuf + sizeof(sdp_pdu_hdr_t); + pdata_len = rspsize - sizeof(sdp_pdu_hdr_t); + + if (pdata_len < sizeof(uint16_t) + sizeof(uint16_t)) { + SDPERR("Unexpected end of packet"); + status = -1; + goto end; + } + + /* net service record match count */ + pdata += sizeof(uint16_t); + scanned += sizeof(uint16_t); + pdata_len -= sizeof(uint16_t); + rec_count = bt_get_be16(pdata); + pdata += sizeof(uint16_t); + scanned += sizeof(uint16_t); + pdata_len -= sizeof(uint16_t); + + SDPDBG("Current svc count: %d", rec_count); + SDPDBG("ResponseLength: %d", rsplen); + + if (!rec_count) { + status = -1; + goto end; + } + extract_record_handle_seq(pdata, pdata_len, rsp, rec_count, &scanned); + SDPDBG("BytesScanned : %d", scanned); + + if (rsplen > scanned) { + uint8_t cstate_len; + + if (rspsize < sizeof(sdp_pdu_hdr_t) + scanned + sizeof(uint8_t)) { + SDPERR("Unexpected end of packet: continuation state data missing"); + status = -1; + goto end; + } + + pdata = rspbuf + sizeof(sdp_pdu_hdr_t) + scanned; + cstate_len = *(uint8_t *) pdata; + if (cstate_len > 0) { + cstate = (sdp_cstate_t *)pdata; + SDPDBG("Cont state length: %d", cstate_len); + } else + cstate = NULL; + } + } while (cstate); + +end: + free(reqbuf); + free(rspbuf); + + return status; +} + +/* + * This is a service attribute request. + * + * INPUT : + * + * uint32_t handle + * The handle of the service for which the attribute(s) are + * requested + * + * sdp_attrreq_type_t reqtype + * Attribute identifiers are 16 bit unsigned integers specified + * in one of 2 ways described below : + * SDP_ATTR_REQ_INDIVIDUAL - 16bit individual identifiers + * They are the actual attribute identifiers in ascending order + * + * SDP_ATTR_REQ_RANGE - 32bit identifier range + * The high-order 16bits is the start of range + * the low-order 16bits are the end of range + * 0x0000 to 0xFFFF gets all attributes + * + * sdp_list_t *attrid + * Singly linked list containing attribute identifiers desired. + * Every element is either a uint16_t(attrSpec = SDP_ATTR_REQ_INDIVIDUAL) + * or a uint32_t(attrSpec=SDP_ATTR_REQ_RANGE) + * + * OUTPUT : + * return sdp_record_t * + * 0: + * On any error and sets errno + * !0: + * The service record + */ +sdp_record_t *sdp_service_attr_req(sdp_session_t *session, uint32_t handle, + sdp_attrreq_type_t reqtype, const sdp_list_t *attrids) +{ + uint32_t reqsize = 0, _reqsize; + uint32_t rspsize = 0, rsp_count; + int attr_list_len = 0; + int seqlen = 0; + unsigned int pdata_len; + uint8_t *pdata, *_pdata; + uint8_t *reqbuf, *rspbuf; + sdp_pdu_hdr_t *reqhdr, *rsphdr; + sdp_cstate_t *cstate = NULL; + uint8_t cstate_len = 0; + sdp_buf_t rsp_concat_buf; + sdp_record_t *rec = 0; + + if (reqtype != SDP_ATTR_REQ_INDIVIDUAL && reqtype != SDP_ATTR_REQ_RANGE) { + errno = EINVAL; + return NULL; + } + + memset(&rsp_concat_buf, 0, sizeof(sdp_buf_t)); + + reqbuf = malloc(SDP_REQ_BUFFER_SIZE); + rspbuf = malloc(SDP_RSP_BUFFER_SIZE); + if (!reqbuf || !rspbuf) { + errno = ENOMEM; + goto end; + } + reqhdr = (sdp_pdu_hdr_t *) reqbuf; + reqhdr->pdu_id = SDP_SVC_ATTR_REQ; + + pdata = reqbuf + sizeof(sdp_pdu_hdr_t); + reqsize = sizeof(sdp_pdu_hdr_t); + + /* add the service record handle */ + bt_put_be32(handle, pdata); + reqsize += sizeof(uint32_t); + pdata += sizeof(uint32_t); + + /* specify the response limit */ + bt_put_be16(65535, pdata); + reqsize += sizeof(uint16_t); + pdata += sizeof(uint16_t); + + /* get attr seq PDU form */ + seqlen = gen_attridseq_pdu(pdata, attrids, + reqtype == SDP_ATTR_REQ_INDIVIDUAL? SDP_UINT16 : SDP_UINT32); + if (seqlen == -1) { + errno = EINVAL; + goto end; + } + pdata += seqlen; + reqsize += seqlen; + SDPDBG("Attr list length : %d", seqlen); + + /* save before Continuation State */ + _pdata = pdata; + _reqsize = reqsize; + + do { + int status; + + /* add NULL continuation state */ + reqsize = _reqsize + copy_cstate(_pdata, + SDP_REQ_BUFFER_SIZE - _reqsize, cstate); + + /* set the request header's param length */ + reqhdr->tid = htons(sdp_gen_tid(session)); + reqhdr->plen = htons(reqsize - sizeof(sdp_pdu_hdr_t)); + + status = sdp_send_req_w4_rsp(session, reqbuf, rspbuf, reqsize, &rspsize); + if (status < 0) + goto end; + + if (rspsize < sizeof(sdp_pdu_hdr_t)) { + SDPERR("Unexpected end of packet"); + goto end; + } + + rsphdr = (sdp_pdu_hdr_t *) rspbuf; + if (rsphdr->pdu_id == SDP_ERROR_RSP) { + SDPDBG("PDU ID : 0x%x", rsphdr->pdu_id); + goto end; + } + pdata = rspbuf + sizeof(sdp_pdu_hdr_t); + pdata_len = rspsize - sizeof(sdp_pdu_hdr_t); + + if (pdata_len < sizeof(uint16_t)) { + SDPERR("Unexpected end of packet"); + goto end; + } + + rsp_count = bt_get_be16(pdata); + attr_list_len += rsp_count; + pdata += sizeof(uint16_t); + pdata_len -= sizeof(uint16_t); + + /* + * if continuation state set need to re-issue request before + * parsing + */ + if (pdata_len < rsp_count + sizeof(uint8_t)) { + SDPERR("Unexpected end of packet: continuation state data missing"); + goto end; + } + cstate_len = *(uint8_t *) (pdata + rsp_count); + + SDPDBG("Response id : %d", rsphdr->pdu_id); + SDPDBG("Attrlist byte count : %d", rsp_count); + SDPDBG("sdp_cstate_t length : %d", cstate_len); + + /* + * a split response: concatenate intermediate responses + * and the last one (which has cstate_len == 0) + */ + if (cstate_len > 0 || rsp_concat_buf.data_size != 0) { + uint8_t *targetPtr = NULL; + + cstate = cstate_len > 0 ? (sdp_cstate_t *) (pdata + rsp_count) : 0; + + /* build concatenated response buffer */ + rsp_concat_buf.data = realloc(rsp_concat_buf.data, rsp_concat_buf.data_size + rsp_count); + rsp_concat_buf.buf_size = rsp_concat_buf.data_size + rsp_count; + targetPtr = rsp_concat_buf.data + rsp_concat_buf.data_size; + memcpy(targetPtr, pdata, rsp_count); + rsp_concat_buf.data_size += rsp_count; + } + } while (cstate); + + if (attr_list_len > 0) { + int scanned = 0; + if (rsp_concat_buf.data_size != 0) { + pdata = rsp_concat_buf.data; + pdata_len = rsp_concat_buf.data_size; + } + rec = sdp_extract_pdu(pdata, pdata_len, &scanned); + } + +end: + free(reqbuf); + free(rsp_concat_buf.data); + free(rspbuf); + return rec; +} + +/* + * SDP transaction structure for asynchronous search + */ +struct sdp_transaction { + sdp_callback_t *cb; /* called when the transaction finishes */ + void *udata; /* client user data */ + uint8_t *reqbuf; /* pointer to request PDU */ + sdp_buf_t rsp_concat_buf; + uint32_t reqsize; /* without cstate */ + int err; /* ZERO if success or the errno if failed */ +}; + +/* + * Creates a new sdp session for asynchronous search + * INPUT: + * int sk + * non-blocking L2CAP socket + * + * RETURN: + * sdp_session_t * + * NULL - On memory allocation failure + */ +sdp_session_t *sdp_create(int sk, uint32_t flags) +{ + sdp_session_t *session; + struct sdp_transaction *t; + + session = malloc(sizeof(sdp_session_t)); + if (!session) { + errno = ENOMEM; + return NULL; + } + memset(session, 0, sizeof(*session)); + + session->flags = flags; + session->sock = sk; + + t = malloc(sizeof(struct sdp_transaction)); + if (!t) { + errno = ENOMEM; + free(session); + return NULL; + } + memset(t, 0, sizeof(*t)); + + session->priv = t; + + return session; +} + +/* + * Sets the callback function/user data used to notify the application + * that the asynchronous transaction finished. This function must be + * called before request an asynchronous search. + * + * INPUT: + * sdp_session_t *session + * Current sdp session to be handled + * sdp_callback_t *cb + * callback to be called when the transaction finishes + * void *udata + * user data passed to callback + * RETURN: + * 0 - Success + * -1 - Failure + */ +int sdp_set_notify(sdp_session_t *session, sdp_callback_t *func, void *udata) +{ + struct sdp_transaction *t; + + if (!session || !session->priv) + return -1; + + t = session->priv; + t->cb = func; + t->udata = udata; + + return 0; +} + +/* + * This function starts an asynchronous service search request. + * The incoming and outgoing data are stored in the transaction structure + * buffers. When there is incoming data the sdp_process function must be + * called to get the data and handle the continuation state. + * + * INPUT : + * sdp_session_t *session + * Current sdp session to be handled + * + * sdp_list_t *search + * Singly linked list containing elements of the search + * pattern. Each entry in the list is a UUID (DataTypeSDP_UUID16) + * of the service to be searched + * + * uint16_t max_rec_num + * A 16 bit integer which tells the service, the maximum + * entries that the client can handle in the response. The + * server is obliged not to return > max_rec_num entries + * + * OUTPUT : + * + * int return value + * 0 - if the request has been sent properly + * -1 - On any failure and sets errno + */ + +int sdp_service_search_async(sdp_session_t *session, const sdp_list_t *search, uint16_t max_rec_num) +{ + struct sdp_transaction *t; + sdp_pdu_hdr_t *reqhdr; + uint8_t *pdata; + int cstate_len, seqlen = 0; + + if (!session || !session->priv) + return -1; + + t = session->priv; + + /* clean possible allocated buffer */ + free(t->rsp_concat_buf.data); + memset(&t->rsp_concat_buf, 0, sizeof(sdp_buf_t)); + + if (!t->reqbuf) { + t->reqbuf = malloc(SDP_REQ_BUFFER_SIZE); + if (!t->reqbuf) { + t->err = ENOMEM; + goto end; + } + } + memset(t->reqbuf, 0, SDP_REQ_BUFFER_SIZE); + + reqhdr = (sdp_pdu_hdr_t *) t->reqbuf; + reqhdr->tid = htons(sdp_gen_tid(session)); + reqhdr->pdu_id = SDP_SVC_SEARCH_REQ; + + /* generate PDU */ + pdata = t->reqbuf + sizeof(sdp_pdu_hdr_t); + t->reqsize = sizeof(sdp_pdu_hdr_t); + + /* add service class IDs for search */ + seqlen = gen_searchseq_pdu(pdata, search); + + SDPDBG("Data seq added : %d", seqlen); + + /* now set the length and increment the pointer */ + t->reqsize += seqlen; + pdata += seqlen; + + bt_put_be16(max_rec_num, pdata); + t->reqsize += sizeof(uint16_t); + pdata += sizeof(uint16_t); + + /* set the request header's param length */ + cstate_len = copy_cstate(pdata, SDP_REQ_BUFFER_SIZE - t->reqsize, NULL); + reqhdr->plen = htons((t->reqsize + cstate_len) - sizeof(sdp_pdu_hdr_t)); + + if (sdp_send_req(session, t->reqbuf, t->reqsize + cstate_len) < 0) { + SDPERR("Error sendind data:%m"); + t->err = errno; + goto end; + } + + return 0; +end: + + free(t->reqbuf); + t->reqbuf = NULL; + + return -1; +} + +/* + * This function starts an asynchronous service attribute request. + * The incoming and outgoing data are stored in the transaction structure + * buffers. When there is incoming data the sdp_process function must be + * called to get the data and handle the continuation state. + * + * INPUT : + * sdp_session_t *session + * Current sdp session to be handled + * + * uint32_t handle + * The handle of the service for which the attribute(s) are + * requested + * + * sdp_attrreq_type_t reqtype + * Attribute identifiers are 16 bit unsigned integers specified + * in one of 2 ways described below : + * SDP_ATTR_REQ_INDIVIDUAL - 16bit individual identifiers + * They are the actual attribute identifiers in ascending order + * + * SDP_ATTR_REQ_RANGE - 32bit identifier range + * The high-order 16bits is the start of range + * the low-order 16bits are the end of range + * 0x0000 to 0xFFFF gets all attributes + * + * sdp_list_t *attrid_list + * Singly linked list containing attribute identifiers desired. + * Every element is either a uint16_t(attrSpec = SDP_ATTR_REQ_INDIVIDUAL) + * or a uint32_t(attrSpec=SDP_ATTR_REQ_RANGE) + * + * OUTPUT : + * int return value + * 0 - if the request has been sent properly + * -1 - On any failure and sets errno + */ + +int sdp_service_attr_async(sdp_session_t *session, uint32_t handle, sdp_attrreq_type_t reqtype, const sdp_list_t *attrid_list) +{ + struct sdp_transaction *t; + sdp_pdu_hdr_t *reqhdr; + uint8_t *pdata; + int cstate_len, seqlen = 0; + + if (!session || !session->priv) + return -1; + + t = session->priv; + + /* clean possible allocated buffer */ + free(t->rsp_concat_buf.data); + memset(&t->rsp_concat_buf, 0, sizeof(sdp_buf_t)); + + if (!t->reqbuf) { + t->reqbuf = malloc(SDP_REQ_BUFFER_SIZE); + if (!t->reqbuf) { + t->err = ENOMEM; + goto end; + } + } + memset(t->reqbuf, 0, SDP_REQ_BUFFER_SIZE); + + reqhdr = (sdp_pdu_hdr_t *) t->reqbuf; + reqhdr->tid = htons(sdp_gen_tid(session)); + reqhdr->pdu_id = SDP_SVC_ATTR_REQ; + + /* generate PDU */ + pdata = t->reqbuf + sizeof(sdp_pdu_hdr_t); + t->reqsize = sizeof(sdp_pdu_hdr_t); + + /* add the service record handle */ + bt_put_be32(handle, pdata); + t->reqsize += sizeof(uint32_t); + pdata += sizeof(uint32_t); + + /* specify the response limit */ + bt_put_be16(65535, pdata); + t->reqsize += sizeof(uint16_t); + pdata += sizeof(uint16_t); + + /* get attr seq PDU form */ + seqlen = gen_attridseq_pdu(pdata, attrid_list, + reqtype == SDP_ATTR_REQ_INDIVIDUAL? SDP_UINT16 : SDP_UINT32); + if (seqlen == -1) { + t->err = EINVAL; + goto end; + } + + /* now set the length and increment the pointer */ + t->reqsize += seqlen; + pdata += seqlen; + SDPDBG("Attr list length : %d", seqlen); + + /* set the request header's param length */ + cstate_len = copy_cstate(pdata, SDP_REQ_BUFFER_SIZE - t->reqsize, NULL); + reqhdr->plen = htons((t->reqsize + cstate_len) - sizeof(sdp_pdu_hdr_t)); + + if (sdp_send_req(session, t->reqbuf, t->reqsize + cstate_len) < 0) { + SDPERR("Error sendind data:%m"); + t->err = errno; + goto end; + } + + return 0; +end: + + free(t->reqbuf); + t->reqbuf = NULL; + + return -1; +} + +/* + * This function starts an asynchronous service search attributes. + * It is a service search request combined with attribute request. The incoming + * and outgoing data are stored in the transaction structure buffers. When there + * is incoming data the sdp_process function must be called to get the data + * and handle the continuation state. + * + * INPUT: + * sdp_session_t *session + * Current sdp session to be handled + * + * sdp_list_t *search + * Singly linked list containing elements of the search + * pattern. Each entry in the list is a UUID(DataTypeSDP_UUID16) + * of the service to be searched + * + * AttributeSpecification attrSpec + * Attribute identifiers are 16 bit unsigned integers specified + * in one of 2 ways described below : + * SDP_ATTR_REQ_INDIVIDUAL - 16bit individual identifiers + * They are the actual attribute identifiers in ascending order + * + * SDP_ATTR_REQ_RANGE - 32bit identifier range + * The high-order 16bits is the start of range + * the low-order 16bits are the end of range + * 0x0000 to 0xFFFF gets all attributes + * + * sdp_list_t *attrid_list + * Singly linked list containing attribute identifiers desired. + * Every element is either a uint16_t(attrSpec = SDP_ATTR_REQ_INDIVIDUAL) + * or a uint32_t(attrSpec=SDP_ATTR_REQ_RANGE) + * + + * RETURN: + * 0 - if the request has been sent properly + * -1 - On any failure + */ +int sdp_service_search_attr_async(sdp_session_t *session, const sdp_list_t *search, sdp_attrreq_type_t reqtype, const sdp_list_t *attrid_list) +{ + struct sdp_transaction *t; + sdp_pdu_hdr_t *reqhdr; + uint8_t *pdata; + int cstate_len, seqlen = 0; + + if (!session || !session->priv) + return -1; + + t = session->priv; + + /* clean possible allocated buffer */ + free(t->rsp_concat_buf.data); + memset(&t->rsp_concat_buf, 0, sizeof(sdp_buf_t)); + + if (!t->reqbuf) { + t->reqbuf = malloc(SDP_REQ_BUFFER_SIZE); + if (!t->reqbuf) { + t->err = ENOMEM; + goto end; + } + } + memset(t->reqbuf, 0, SDP_REQ_BUFFER_SIZE); + + reqhdr = (sdp_pdu_hdr_t *) t->reqbuf; + reqhdr->tid = htons(sdp_gen_tid(session)); + reqhdr->pdu_id = SDP_SVC_SEARCH_ATTR_REQ; + + /* generate PDU */ + pdata = t->reqbuf + sizeof(sdp_pdu_hdr_t); + t->reqsize = sizeof(sdp_pdu_hdr_t); + + /* add service class IDs for search */ + seqlen = gen_searchseq_pdu(pdata, search); + + SDPDBG("Data seq added : %d", seqlen); + + /* now set the length and increment the pointer */ + t->reqsize += seqlen; + pdata += seqlen; + + bt_put_be16(SDP_MAX_ATTR_LEN, pdata); + t->reqsize += sizeof(uint16_t); + pdata += sizeof(uint16_t); + + SDPDBG("Max attr byte count : %d", SDP_MAX_ATTR_LEN); + + /* get attr seq PDU form */ + seqlen = gen_attridseq_pdu(pdata, attrid_list, + reqtype == SDP_ATTR_REQ_INDIVIDUAL ? SDP_UINT16 : SDP_UINT32); + if (seqlen == -1) { + t->err = EINVAL; + goto end; + } + + pdata += seqlen; + SDPDBG("Attr list length : %d", seqlen); + t->reqsize += seqlen; + + /* set the request header's param length */ + cstate_len = copy_cstate(pdata, SDP_REQ_BUFFER_SIZE - t->reqsize, NULL); + reqhdr->plen = htons((t->reqsize + cstate_len) - sizeof(sdp_pdu_hdr_t)); + + if (sdp_send_req(session, t->reqbuf, t->reqsize + cstate_len) < 0) { + SDPERR("Error sendind data:%m"); + t->err = errno; + goto end; + } + + return 0; +end: + + free(t->reqbuf); + t->reqbuf = NULL; + + return -1; +} + +/* + * Function used to get the error reason after sdp_callback_t function has been called + * and the status is 0xffff or if sdp_service_{search, attr, search_attr}_async returns -1. + * It indicates that an error NOT related to SDP_ErrorResponse happened. Get errno directly + * is not safe because multiple transactions can be triggered. + * This function must be used with asynchronous sdp functions only. + * + * INPUT: + * sdp_session_t *session + * Current sdp session to be handled + * RETURN: + * 0 = No error in the current transaction + * -1 - if the session is invalid + * positive value - the errno value + * + */ +int sdp_get_error(sdp_session_t *session) +{ + struct sdp_transaction *t; + + if (!session || !session->priv) { + SDPERR("Invalid session"); + return -1; + } + + t = session->priv; + + return t->err; +} + +/* + * Receive the incoming SDP PDU. This function must be called when there is data + * available to be read. On continuation state, the original request (with a new + * transaction ID) and the continuation state data will be appended in the initial PDU. + * If an error happens or the transaction finishes the callback function will be called. + * + * INPUT: + * sdp_session_t *session + * Current sdp session to be handled + * RETURN: + * 0 - if the transaction is on continuation state + * -1 - On any failure or the transaction finished + */ +int sdp_process(sdp_session_t *session) +{ + struct sdp_transaction *t; + sdp_pdu_hdr_t *reqhdr, *rsphdr; + sdp_cstate_t *pcstate; + uint8_t *pdata, *rspbuf, *targetPtr; + int rsp_count, err = -1; + size_t size = 0; + int n, plen; + uint16_t status = 0xffff; + uint8_t pdu_id = 0x00; + + if (!session || !session->priv) { + SDPERR("Invalid session"); + return -1; + } + + rspbuf = malloc(SDP_RSP_BUFFER_SIZE); + if (!rspbuf) { + SDPERR("Response buffer alloc failure:%m (%d)", errno); + return -1; + } + + memset(rspbuf, 0, SDP_RSP_BUFFER_SIZE); + + t = session->priv; + reqhdr = (sdp_pdu_hdr_t *)t->reqbuf; + rsphdr = (sdp_pdu_hdr_t *)rspbuf; + + pdata = rspbuf + sizeof(sdp_pdu_hdr_t); + + n = sdp_read_rsp(session, rspbuf, SDP_RSP_BUFFER_SIZE); + if (n < 0) { + SDPERR("Read response:%m (%d)", errno); + t->err = errno; + goto end; + } + + if (n == 0 || reqhdr->tid != rsphdr->tid || + (n != (int) (ntohs(rsphdr->plen) + sizeof(sdp_pdu_hdr_t)))) { + t->err = EPROTO; + SDPERR("Protocol error."); + goto end; + } + + pdu_id = rsphdr->pdu_id; + switch (rsphdr->pdu_id) { + uint8_t *ssr_pdata; + uint16_t tsrc, csrc; + case SDP_SVC_SEARCH_RSP: + /* + * TSRC: Total Service Record Count (2 bytes) + * CSRC: Current Service Record Count (2 bytes) + */ + ssr_pdata = pdata; + tsrc = bt_get_be16(ssr_pdata); + ssr_pdata += sizeof(uint16_t); + csrc = bt_get_be16(ssr_pdata); + + /* csrc should never be larger than tsrc */ + if (csrc > tsrc) { + t->err = EPROTO; + SDPERR("Protocol error: wrong current service record count value."); + goto end; + } + + SDPDBG("Total svc count: %d", tsrc); + SDPDBG("Current svc count: %d", csrc); + + /* parameter length without continuation state */ + plen = sizeof(tsrc) + sizeof(csrc) + csrc * 4; + + if (t->rsp_concat_buf.data_size == 0) { + /* first fragment */ + rsp_count = sizeof(tsrc) + sizeof(csrc) + csrc * 4; + } else if (t->rsp_concat_buf.data_size >= sizeof(uint16_t) * 2) { + /* point to the first csrc */ + uint8_t *pcsrc = t->rsp_concat_buf.data + 2; + uint16_t tcsrc, tcsrc2; + + /* FIXME: update the interface later. csrc doesn't need be passed to clients */ + + pdata += sizeof(uint16_t); /* point to csrc */ + + /* the first csrc contains the sum of partial csrc responses */ + memcpy(&tcsrc, pcsrc, sizeof(tcsrc)); + memcpy(&tcsrc2, pdata, sizeof(tcsrc2)); + tcsrc += tcsrc2; + memcpy(pcsrc, &tcsrc, sizeof(tcsrc)); + + pdata += sizeof(uint16_t); /* point to the first handle */ + rsp_count = csrc * 4; + } else { + t->err = EPROTO; + SDPERR("Protocol error: invalid PDU size"); + status = SDP_INVALID_PDU_SIZE; + goto end; + } + status = 0x0000; + break; + case SDP_SVC_ATTR_RSP: + case SDP_SVC_SEARCH_ATTR_RSP: + rsp_count = bt_get_be16(pdata); + SDPDBG("Attrlist byte count : %d", rsp_count); + + /* Valid range for rsp_count is 0x0002-0xFFFF */ + if (t->rsp_concat_buf.data_size == 0 && rsp_count < 0x0002) { + t->err = EPROTO; + SDPERR("Protocol error: invalid AttrList size"); + status = SDP_INVALID_PDU_SIZE; + goto end; + } + + /* + * Number of bytes in the AttributeLists parameter(without + * continuation state) + AttributeListsByteCount field size. + */ + plen = sizeof(uint16_t) + rsp_count; + + pdata += sizeof(uint16_t); /* points to attribute list */ + status = 0x0000; + break; + case SDP_ERROR_RSP: + status = bt_get_be16(pdata); + size = ntohs(rsphdr->plen); + + goto end; + default: + t->err = EPROTO; + SDPERR("Illegal PDU ID: 0x%x", rsphdr->pdu_id); + goto end; + } + + /* Out of bound check before using rsp_count as offset for + * continuation state, which has at least a one byte size + * field. + */ + if ((n - (int) sizeof(sdp_pdu_hdr_t)) < plen + 1) { + t->err = EPROTO; + SDPERR("Protocol error: invalid PDU size"); + status = SDP_INVALID_PDU_SIZE; + goto end; + } + + pcstate = (sdp_cstate_t *) (pdata + rsp_count); + + SDPDBG("Cstate length : %d", pcstate->length); + + /* + * Check out of bound. Continuation state must have at least + * 1 byte: ZERO to indicate that it is not a partial response. + */ + if ((n - (int) sizeof(sdp_pdu_hdr_t)) != (plen + pcstate->length + 1)) { + t->err = EPROTO; + SDPERR("Protocol error: wrong PDU size."); + status = 0xffff; + goto end; + } + + /* + * This is a split response, need to concatenate intermediate + * responses and the last one which will have cstate length == 0 + */ + t->rsp_concat_buf.data = realloc(t->rsp_concat_buf.data, t->rsp_concat_buf.data_size + rsp_count); + targetPtr = t->rsp_concat_buf.data + t->rsp_concat_buf.data_size; + t->rsp_concat_buf.buf_size = t->rsp_concat_buf.data_size + rsp_count; + memcpy(targetPtr, pdata, rsp_count); + t->rsp_concat_buf.data_size += rsp_count; + + if (pcstate->length > 0) { + int reqsize, cstate_len; + + reqhdr->tid = htons(sdp_gen_tid(session)); + + /* add continuation state */ + cstate_len = copy_cstate(t->reqbuf + t->reqsize, + SDP_REQ_BUFFER_SIZE - t->reqsize, pcstate); + + reqsize = t->reqsize + cstate_len; + + /* set the request header's param length */ + reqhdr->plen = htons(reqsize - sizeof(sdp_pdu_hdr_t)); + + if (sdp_send_req(session, t->reqbuf, reqsize) < 0) { + SDPERR("Error sendind data:%m(%d)", errno); + status = 0xffff; + t->err = errno; + goto end; + } + err = 0; + } + +end: + if (err) { + if (t->rsp_concat_buf.data_size != 0) { + pdata = t->rsp_concat_buf.data; + size = t->rsp_concat_buf.data_size; + } + if (t->cb) + t->cb(pdu_id, status, pdata, size, t->udata); + } + + free(rspbuf); + + return err; +} + +/* + * This is a service search request combined with the service + * attribute request. First a service class match is done and + * for matching service, requested attributes are extracted + * + * INPUT : + * + * sdp_list_t *search + * Singly linked list containing elements of the search + * pattern. Each entry in the list is a UUID(DataTypeSDP_UUID16) + * of the service to be searched + * + * AttributeSpecification attrSpec + * Attribute identifiers are 16 bit unsigned integers specified + * in one of 2 ways described below : + * SDP_ATTR_REQ_INDIVIDUAL - 16bit individual identifiers + * They are the actual attribute identifiers in ascending order + * + * SDP_ATTR_REQ_RANGE - 32bit identifier range + * The high-order 16bits is the start of range + * the low-order 16bits are the end of range + * 0x0000 to 0xFFFF gets all attributes + * + * sdp_list_t *attrids + * Singly linked list containing attribute identifiers desired. + * Every element is either a uint16_t(attrSpec = SDP_ATTR_REQ_INDIVIDUAL) + * or a uint32_t(attrSpec=SDP_ATTR_REQ_RANGE) + * + * OUTPUT : + * int return value + * 0: + * The request completed successfully. This does not + * mean the requested services were found + * -1: + * On any error and sets errno + * + * sdp_list_t **rsp + * This variable is set on a successful return to point to + * service(s) found. Each element of this list is of type + * sdp_record_t* (of the services which matched the search list) + */ +int sdp_service_search_attr_req(sdp_session_t *session, const sdp_list_t *search, sdp_attrreq_type_t reqtype, const sdp_list_t *attrids, sdp_list_t **rsp) +{ + int status = 0; + uint32_t reqsize = 0, _reqsize; + uint32_t rspsize = 0; + int seqlen = 0, attr_list_len = 0; + int rsp_count = 0, cstate_len = 0; + unsigned int pdata_len; + uint8_t *pdata, *_pdata; + uint8_t *reqbuf, *rspbuf; + sdp_pdu_hdr_t *reqhdr, *rsphdr; + uint8_t dataType; + sdp_list_t *rec_list = NULL; + sdp_buf_t rsp_concat_buf; + sdp_cstate_t *cstate = NULL; + + if (reqtype != SDP_ATTR_REQ_INDIVIDUAL && reqtype != SDP_ATTR_REQ_RANGE) { + errno = EINVAL; + return -1; + } + + memset(&rsp_concat_buf, 0, sizeof(sdp_buf_t)); + + reqbuf = malloc(SDP_REQ_BUFFER_SIZE); + rspbuf = malloc(SDP_RSP_BUFFER_SIZE); + if (!reqbuf || !rspbuf) { + errno = ENOMEM; + status = -1; + goto end; + } + + reqhdr = (sdp_pdu_hdr_t *) reqbuf; + reqhdr->pdu_id = SDP_SVC_SEARCH_ATTR_REQ; + + /* generate PDU */ + pdata = reqbuf + sizeof(sdp_pdu_hdr_t); + reqsize = sizeof(sdp_pdu_hdr_t); + + /* add service class IDs for search */ + seqlen = gen_searchseq_pdu(pdata, search); + if (seqlen < 0) { + errno = EINVAL; + status = -1; + goto end; + } + + SDPDBG("Data seq added : %d", seqlen); + + /* now set the length and increment the pointer */ + reqsize += seqlen; + pdata += seqlen; + + bt_put_be16(SDP_MAX_ATTR_LEN, pdata); + reqsize += sizeof(uint16_t); + pdata += sizeof(uint16_t); + + SDPDBG("Max attr byte count : %d", SDP_MAX_ATTR_LEN); + + /* get attr seq PDU form */ + seqlen = gen_attridseq_pdu(pdata, attrids, + reqtype == SDP_ATTR_REQ_INDIVIDUAL ? SDP_UINT16 : SDP_UINT32); + if (seqlen == -1) { + errno = EINVAL; + status = -1; + goto end; + } + pdata += seqlen; + SDPDBG("Attr list length : %d", seqlen); + reqsize += seqlen; + *rsp = 0; + + /* save before Continuation State */ + _pdata = pdata; + _reqsize = reqsize; + + do { + reqhdr->tid = htons(sdp_gen_tid(session)); + + /* add continuation state (can be null) */ + reqsize = _reqsize + copy_cstate(_pdata, + SDP_REQ_BUFFER_SIZE - _reqsize, cstate); + + /* set the request header's param length */ + reqhdr->plen = htons(reqsize - sizeof(sdp_pdu_hdr_t)); + rsphdr = (sdp_pdu_hdr_t *) rspbuf; + status = sdp_send_req_w4_rsp(session, reqbuf, rspbuf, reqsize, &rspsize); + if (rspsize < sizeof(sdp_pdu_hdr_t)) { + SDPERR("Unexpected end of packet"); + status = -1; + goto end; + } + + if (status < 0) { + SDPDBG("Status : 0x%x", rsphdr->pdu_id); + goto end; + } + + if (rsphdr->pdu_id == SDP_ERROR_RSP) { + status = -1; + goto end; + } + + pdata = rspbuf + sizeof(sdp_pdu_hdr_t); + pdata_len = rspsize - sizeof(sdp_pdu_hdr_t); + + if (pdata_len < sizeof(uint16_t)) { + SDPERR("Unexpected end of packet"); + status = -1; + goto end; + } + + rsp_count = bt_get_be16(pdata); + attr_list_len += rsp_count; + pdata += sizeof(uint16_t); /* pdata points to attribute list */ + pdata_len -= sizeof(uint16_t); + + if (pdata_len < rsp_count + sizeof(uint8_t)) { + SDPERR("Unexpected end of packet: continuation state data missing"); + status = -1; + goto end; + } + + cstate_len = *(uint8_t *) (pdata + rsp_count); + + SDPDBG("Attrlist byte count : %d", attr_list_len); + SDPDBG("Response byte count : %d", rsp_count); + SDPDBG("Cstate length : %d", cstate_len); + /* + * This is a split response, need to concatenate intermediate + * responses and the last one which will have cstate_len == 0 + */ + if (cstate_len > 0 || rsp_concat_buf.data_size != 0) { + uint8_t *targetPtr = NULL; + + cstate = cstate_len > 0 ? (sdp_cstate_t *) (pdata + rsp_count) : 0; + + /* build concatenated response buffer */ + rsp_concat_buf.data = realloc(rsp_concat_buf.data, rsp_concat_buf.data_size + rsp_count); + targetPtr = rsp_concat_buf.data + rsp_concat_buf.data_size; + rsp_concat_buf.buf_size = rsp_concat_buf.data_size + rsp_count; + memcpy(targetPtr, pdata, rsp_count); + rsp_concat_buf.data_size += rsp_count; + } + } while (cstate); + + if (attr_list_len > 0) { + int scanned = 0; + + if (rsp_concat_buf.data_size != 0) { + pdata = rsp_concat_buf.data; + pdata_len = rsp_concat_buf.data_size; + } + + /* + * Response is a sequence of sequence(s) for one or + * more data element sequence(s) representing services + * for which attributes are returned + */ + scanned = sdp_extract_seqtype(pdata, pdata_len, &dataType, &seqlen); + + SDPDBG("Bytes scanned : %d", scanned); + SDPDBG("Seq length : %d", seqlen); + + if (scanned && seqlen) { + pdata += scanned; + pdata_len -= scanned; + do { + int recsize = 0; + sdp_record_t *rec = sdp_extract_pdu(pdata, pdata_len, &recsize); + if (rec == NULL) { + SDPERR("SVC REC is null"); + status = -1; + goto end; + } + if (!recsize) { + sdp_record_free(rec); + break; + } + scanned += recsize; + pdata += recsize; + pdata_len -= recsize; + + SDPDBG("Loc seq length : %d", recsize); + SDPDBG("Svc Rec Handle : 0x%x", rec->handle); + SDPDBG("Bytes scanned : %d", scanned); + SDPDBG("Attrlist byte count : %d", attr_list_len); + rec_list = sdp_list_append(rec_list, rec); + } while (scanned < attr_list_len && pdata_len > 0); + + SDPDBG("Successful scan of service attr lists"); + *rsp = rec_list; + } + } +end: + free(rsp_concat_buf.data); + free(reqbuf); + free(rspbuf); + return status; +} + +/* + * Find devices in the piconet. + */ +int sdp_general_inquiry(inquiry_info *ii, int num_dev, int duration, uint8_t *found) +{ + int n = hci_inquiry(-1, 10, num_dev, NULL, &ii, 0); + if (n < 0) { + SDPERR("Inquiry failed:%m"); + return -1; + } + *found = n; + return 0; +} + +int sdp_close(sdp_session_t *session) +{ + struct sdp_transaction *t; + int ret; + + if (!session) + return -1; + + ret = close(session->sock); + + t = session->priv; + + if (t) { + free(t->reqbuf); + + free(t->rsp_concat_buf.data); + + free(t); + } + free(session); + return ret; +} + +static inline int sdp_is_local(const bdaddr_t *device) +{ + return memcmp(device, BDADDR_LOCAL, sizeof(bdaddr_t)) == 0; +} + +static int sdp_connect_local(sdp_session_t *session) +{ + struct sockaddr_un sa; + + session->sock = socket(PF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); + if (session->sock < 0) + return -1; + session->local = 1; + + sa.sun_family = AF_UNIX; + strcpy(sa.sun_path, SDP_UNIX_PATH); + + return connect(session->sock, (struct sockaddr *) &sa, sizeof(sa)); +} + +static int set_l2cap_mtu(int sk, uint16_t mtu) +{ + struct l2cap_options l2o; + socklen_t len; + + memset(&l2o, 0, sizeof(l2o)); + len = sizeof(l2o); + + if (getsockopt(sk, SOL_L2CAP, L2CAP_OPTIONS, &l2o, &len) < 0) + return -1; + + l2o.imtu = mtu; + l2o.omtu = mtu; + + if (setsockopt(sk, SOL_L2CAP, L2CAP_OPTIONS, &l2o, sizeof(l2o)) < 0) + return -1; + + return 0; +} + +static int sdp_connect_l2cap(const bdaddr_t *src, + const bdaddr_t *dst, sdp_session_t *session) +{ + uint32_t flags = session->flags; + struct sockaddr_l2 sa; + int sk; + int sockflags = SOCK_SEQPACKET | SOCK_CLOEXEC; + + if (flags & SDP_NON_BLOCKING) + sockflags |= SOCK_NONBLOCK; + + session->sock = socket(PF_BLUETOOTH, sockflags, BTPROTO_L2CAP); + if (session->sock < 0) + return -1; + session->local = 0; + + sk = session->sock; + + memset(&sa, 0, sizeof(sa)); + + sa.l2_family = AF_BLUETOOTH; + sa.l2_psm = 0; + + if (bacmp(src, BDADDR_ANY)) { + sa.l2_bdaddr = *src; + if (bind(sk, (struct sockaddr *) &sa, sizeof(sa)) < 0) + return -1; + } + + if (flags & SDP_WAIT_ON_CLOSE) { + struct linger l = { .l_onoff = 1, .l_linger = 1 }; + setsockopt(sk, SOL_SOCKET, SO_LINGER, &l, sizeof(l)); + } + + if ((flags & SDP_LARGE_MTU) && + set_l2cap_mtu(sk, SDP_LARGE_L2CAP_MTU) < 0) + return -1; + + sa.l2_psm = htobs(SDP_PSM); + sa.l2_bdaddr = *dst; + + do { + int ret = connect(sk, (struct sockaddr *) &sa, sizeof(sa)); + if (!ret) + return 0; + if (ret < 0 && (flags & SDP_NON_BLOCKING) && + (errno == EAGAIN || errno == EINPROGRESS)) + return 0; + } while (errno == EBUSY && (flags & SDP_RETRY_IF_BUSY)); + + return -1; +} + +sdp_session_t *sdp_connect(const bdaddr_t *src, + const bdaddr_t *dst, uint32_t flags) +{ + sdp_session_t *session; + int err; + + if ((flags & SDP_RETRY_IF_BUSY) && (flags & SDP_NON_BLOCKING)) { + errno = EINVAL; + return NULL; + } + + session = sdp_create(-1, flags); + if (!session) + return NULL; + + if (sdp_is_local(dst)) { + if (sdp_connect_local(session) < 0) + goto fail; + } else { + if (sdp_connect_l2cap(src, dst, session) < 0) + goto fail; + } + + return session; + +fail: + err = errno; + if (session->sock >= 0) + close(session->sock); + free(session->priv); + free(session); + errno = err; + + return NULL; +} + +int sdp_get_socket(const sdp_session_t *session) +{ + return session->sock; +} + +uint16_t sdp_gen_tid(sdp_session_t *session) +{ + return session->tid++; +} + +/* + * Set the supported features + */ +int sdp_set_supp_feat(sdp_record_t *rec, const sdp_list_t *sf) +{ + const sdp_list_t *p, *r; + sdp_data_t *feat, *seq_feat; + int seqlen, i; + void **seqDTDs, **seqVals; + + seqlen = sdp_list_len(sf); + seqDTDs = malloc(seqlen * sizeof(void *)); + if (!seqDTDs) + return -1; + seqVals = malloc(seqlen * sizeof(void *)); + if (!seqVals) { + free(seqDTDs); + return -1; + } + + for (p = sf, i = 0; p; p = p->next, i++) { + int plen, j; + void **dtds, **vals; + int *lengths; + + plen = sdp_list_len(p->data); + dtds = malloc(plen * sizeof(void *)); + if (!dtds) + goto fail; + vals = malloc(plen * sizeof(void *)); + if (!vals) { + free(dtds); + goto fail; + } + lengths = malloc(plen * sizeof(int)); + if (!lengths) { + free(dtds); + free(vals); + goto fail; + } + for (r = p->data, j = 0; r; r = r->next, j++) { + sdp_data_t *data = (sdp_data_t *) r->data; + dtds[j] = &data->dtd; + switch (data->dtd) { + case SDP_URL_STR8: + case SDP_URL_STR16: + case SDP_TEXT_STR8: + case SDP_TEXT_STR16: + vals[j] = data->val.str; + lengths[j] = data->unitSize - sizeof(uint8_t); + break; + case SDP_ALT8: + case SDP_ALT16: + case SDP_ALT32: + case SDP_SEQ8: + case SDP_SEQ16: + case SDP_SEQ32: + vals[j] = data->val.dataseq; + lengths[j] = 0; + break; + default: + vals[j] = &data->val; + lengths[j] = 0; + break; + } + } + feat = sdp_seq_alloc_with_length(dtds, vals, lengths, plen); + free(dtds); + free(vals); + free(lengths); + if (!feat) + goto fail; + seqDTDs[i] = &feat->dtd; + seqVals[i] = feat; + } + seq_feat = sdp_seq_alloc(seqDTDs, seqVals, seqlen); + if (!seq_feat) + goto fail; + sdp_attr_replace(rec, SDP_ATTR_SUPPORTED_FEATURES_LIST, seq_feat); + + free(seqVals); + free(seqDTDs); + return 0; + +fail: + free(seqVals); + free(seqDTDs); + return -1; +} + +/* + * Get the supported features + * If an error occurred -1 is returned and errno is set + */ +int sdp_get_supp_feat(const sdp_record_t *rec, sdp_list_t **seqp) +{ + sdp_data_t *sdpdata, *d; + sdp_list_t *tseq; + tseq = NULL; + + sdpdata = sdp_data_get(rec, SDP_ATTR_SUPPORTED_FEATURES_LIST); + + if (!sdpdata || !SDP_IS_SEQ(sdpdata->dtd)) + return sdp_get_uuidseq_attr(rec, + SDP_ATTR_SUPPORTED_FEATURES_LIST, seqp); + + for (d = sdpdata->val.dataseq; d; d = d->next) { + sdp_data_t *dd; + sdp_list_t *subseq; + + if (!SDP_IS_SEQ(d->dtd)) + goto fail; + + subseq = NULL; + + for (dd = d->val.dataseq; dd; dd = dd->next) { + sdp_data_t *data; + void *val; + int length; + + switch (dd->dtd) { + case SDP_URL_STR8: + case SDP_URL_STR16: + case SDP_TEXT_STR8: + case SDP_TEXT_STR16: + val = dd->val.str; + length = dd->unitSize - sizeof(uint8_t); + break; + case SDP_UINT8: + case SDP_UINT16: + val = &dd->val; + length = 0; + break; + default: + goto fail; + } + + data = sdp_data_alloc_with_length(dd->dtd, val, length); + if (data) + subseq = sdp_list_append(subseq, data); + } + tseq = sdp_list_append(tseq, subseq); + } + *seqp = tseq; + return 0; + +fail: + while (tseq) { + sdp_list_t * next; + + next = tseq->next; + sdp_list_free(tseq, free); + tseq = next; + } + errno = EINVAL; + return -1; +} + +void sdp_add_lang_attr(sdp_record_t *rec) +{ + sdp_lang_attr_t base_lang; + sdp_list_t *langs; + + base_lang.code_ISO639 = (0x65 << 8) | 0x6e; + base_lang.encoding = 106; + base_lang.base_offset = SDP_PRIMARY_LANG_BASE; + + langs = sdp_list_append(0, &base_lang); + sdp_set_lang_attr(rec, langs); + sdp_list_free(langs, NULL); +} diff --git a/drive-sdk/deps/bzle/src/utils.c b/drive-sdk/deps/bzle/src/utils.c new file mode 100644 index 0000000..db1f5a0 --- /dev/null +++ b/drive-sdk/deps/bzle/src/utils.c @@ -0,0 +1,120 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2011 Nokia Corporation + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +GIOChannel *gatt_connect(const char *src, const char *dst, + const char *dst_type, const char *sec_level, + int psm, int mtu, BtIOConnect connect_cb, + GError **gerr) +{ + GIOChannel *chan; + bdaddr_t sba, dba; + uint8_t dest_type; + GError *tmp_err = NULL; + BtIOSecLevel sec; + + str2ba(dst, &dba); + + /* Local adapter */ + if (src != NULL) { + if (!strncmp(src, "hci", 3)) + hci_devba(atoi(src + 3), &sba); + else + str2ba(src, &sba); + } else + bacpy(&sba, BDADDR_ANY); + + /* Not used for BR/EDR */ + if (strcmp(dst_type, "random") == 0) + dest_type = BDADDR_LE_RANDOM; + else + dest_type = BDADDR_LE_PUBLIC; + + if (strcmp(sec_level, "medium") == 0) + sec = BT_IO_SEC_MEDIUM; + else if (strcmp(sec_level, "high") == 0) + sec = BT_IO_SEC_HIGH; + else + sec = BT_IO_SEC_LOW; + + if (psm == 0) + chan = bt_io_connect(connect_cb, NULL, NULL, &tmp_err, + BT_IO_OPT_SOURCE_BDADDR, &sba, + BT_IO_OPT_SOURCE_TYPE, BDADDR_LE_PUBLIC, + BT_IO_OPT_DEST_BDADDR, &dba, + BT_IO_OPT_DEST_TYPE, dest_type, + BT_IO_OPT_CID, ATT_CID, + BT_IO_OPT_SEC_LEVEL, sec, + BT_IO_OPT_INVALID); + else + chan = bt_io_connect(connect_cb, NULL, NULL, &tmp_err, + BT_IO_OPT_SOURCE_BDADDR, &sba, + BT_IO_OPT_DEST_BDADDR, &dba, + BT_IO_OPT_PSM, psm, + BT_IO_OPT_IMTU, mtu, + BT_IO_OPT_SEC_LEVEL, sec, + BT_IO_OPT_INVALID); + + if (tmp_err) { + g_propagate_error(gerr, tmp_err); + return NULL; + } + + return chan; +} + +size_t gatt_attr_data_from_string(const char *str, uint8_t **data) +{ + char tmp[3]; + size_t size, i; + + size = strlen(str) / 2; + *data = g_try_malloc0(size); + if (*data == NULL) + return 0; + + tmp[2] = '\0'; + for (i = 0; i < size; i++) { + memcpy(tmp, str + (i * 2), 2); + (*data)[i] = (uint8_t) strtol(tmp, NULL, 16); + } + + return size; +} diff --git a/drive-sdk/deps/bzle/src/uuid.c b/drive-sdk/deps/bzle/src/uuid.c new file mode 100644 index 0000000..08278be --- /dev/null +++ b/drive-sdk/deps/bzle/src/uuid.c @@ -0,0 +1,278 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2011 Nokia Corporation + * Copyright (C) 2011 Marcel Holtmann + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include +#include + +#include + +#if __BYTE_ORDER == __BIG_ENDIAN +static uint128_t bluetooth_base_uuid = { + .data = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, + 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB } +}; + +#define BASE_UUID16_OFFSET 2 +#define BASE_UUID32_OFFSET 0 + +#else +static uint128_t bluetooth_base_uuid = { + .data = { 0xFB, 0x34, 0x9B, 0x5F, 0x80, 0x00, 0x00, 0x80, + 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } +}; + +#define BASE_UUID16_OFFSET 12 +#define BASE_UUID32_OFFSET BASE_UUID16_OFFSET + +#endif + +static void bt_uuid16_to_uuid128(const bt_uuid_t *src, bt_uuid_t *dst) +{ + dst->value.u128 = bluetooth_base_uuid; + dst->type = BT_UUID128; + + memcpy(&dst->value.u128.data[BASE_UUID16_OFFSET], + &src->value.u16, sizeof(src->value.u16)); +} + +static void bt_uuid32_to_uuid128(const bt_uuid_t *src, bt_uuid_t *dst) +{ + dst->value.u128 = bluetooth_base_uuid; + dst->type = BT_UUID128; + + memcpy(&dst->value.u128.data[BASE_UUID32_OFFSET], + &src->value.u32, sizeof(src->value.u32)); +} + +void bt_uuid_to_uuid128(const bt_uuid_t *src, bt_uuid_t *dst) +{ + switch (src->type) { + case BT_UUID128: + *dst = *src; + break; + case BT_UUID32: + bt_uuid32_to_uuid128(src, dst); + break; + case BT_UUID16: + bt_uuid16_to_uuid128(src, dst); + break; + default: + break; + } +} + +static int bt_uuid128_cmp(const bt_uuid_t *u1, const bt_uuid_t *u2) +{ + return memcmp(&u1->value.u128, &u2->value.u128, sizeof(uint128_t)); +} + +int bt_uuid16_create(bt_uuid_t *btuuid, uint16_t value) +{ + memset(btuuid, 0, sizeof(bt_uuid_t)); + btuuid->type = BT_UUID16; + btuuid->value.u16 = value; + + return 0; +} + +int bt_uuid32_create(bt_uuid_t *btuuid, uint32_t value) +{ + memset(btuuid, 0, sizeof(bt_uuid_t)); + btuuid->type = BT_UUID32; + btuuid->value.u32 = value; + + return 0; +} + +int bt_uuid128_create(bt_uuid_t *btuuid, uint128_t value) +{ + memset(btuuid, 0, sizeof(bt_uuid_t)); + btuuid->type = BT_UUID128; + btuuid->value.u128 = value; + + return 0; +} + +int bt_uuid_cmp(const bt_uuid_t *uuid1, const bt_uuid_t *uuid2) +{ + bt_uuid_t u1, u2; + + bt_uuid_to_uuid128(uuid1, &u1); + bt_uuid_to_uuid128(uuid2, &u2); + + return bt_uuid128_cmp(&u1, &u2); +} + +/* + * convert the UUID to string, copying a maximum of n characters. + */ +int bt_uuid_to_string(const bt_uuid_t *uuid, char *str, size_t n) +{ + if (!uuid) { + snprintf(str, n, "NULL"); + return -EINVAL; + } + + switch (uuid->type) { + case BT_UUID16: + snprintf(str, n, "%.4x", uuid->value.u16); + break; + case BT_UUID32: + snprintf(str, n, "%.8x", uuid->value.u32); + break; + case BT_UUID128: { + unsigned int data0; + unsigned short data1; + unsigned short data2; + unsigned short data3; + unsigned int data4; + unsigned short data5; + + uint128_t nvalue; + const uint8_t *data = (uint8_t *) &nvalue; + + hton128(&uuid->value.u128, &nvalue); + + memcpy(&data0, &data[0], 4); + memcpy(&data1, &data[4], 2); + memcpy(&data2, &data[6], 2); + memcpy(&data3, &data[8], 2); + memcpy(&data4, &data[10], 4); + memcpy(&data5, &data[14], 2); + + snprintf(str, n, "%.8x-%.4x-%.4x-%.4x-%.8x%.4x", + ntohl(data0), ntohs(data1), + ntohs(data2), ntohs(data3), + ntohl(data4), ntohs(data5)); + } + break; + default: + snprintf(str, n, "Type of UUID (%x) unknown.", uuid->type); + return -EINVAL; /* Enum type of UUID not set */ + } + + return 0; +} + +static inline int is_uuid128(const char *string) +{ + return (strlen(string) == 36 && + string[8] == '-' && + string[13] == '-' && + string[18] == '-' && + string[23] == '-'); +} + +static inline int is_uuid32(const char *string) +{ + return (strlen(string) == 8 || strlen(string) == 10); +} + +static inline int is_uuid16(const char *string) +{ + return (strlen(string) == 4 || strlen(string) == 6); +} + +static int bt_string_to_uuid16(bt_uuid_t *uuid, const char *string) +{ + uint16_t u16; + char *endptr = NULL; + + u16 = strtol(string, &endptr, 16); + if (endptr && *endptr == '\0') { + bt_uuid16_create(uuid, u16); + return 0; + } + + return -EINVAL; +} + +static int bt_string_to_uuid32(bt_uuid_t *uuid, const char *string) +{ + uint32_t u32; + char *endptr = NULL; + + u32 = strtol(string, &endptr, 16); + if (endptr && *endptr == '\0') { + bt_uuid32_create(uuid, u32); + return 0; + } + + return -EINVAL; +} + +static int bt_string_to_uuid128(bt_uuid_t *uuid, const char *string) +{ + uint32_t data0, data4; + uint16_t data1, data2, data3, data5; + uint128_t n128, u128; + uint8_t *val = (uint8_t *) &n128; + + if (sscanf(string, "%08x-%04hx-%04hx-%04hx-%08x%04hx", + &data0, &data1, &data2, + &data3, &data4, &data5) != 6) + return -EINVAL; + + data0 = htonl(data0); + data1 = htons(data1); + data2 = htons(data2); + data3 = htons(data3); + data4 = htonl(data4); + data5 = htons(data5); + + memcpy(&val[0], &data0, 4); + memcpy(&val[4], &data1, 2); + memcpy(&val[6], &data2, 2); + memcpy(&val[8], &data3, 2); + memcpy(&val[10], &data4, 4); + memcpy(&val[14], &data5, 2); + + ntoh128(&n128, &u128); + + bt_uuid128_create(uuid, u128); + + return 0; +} + +int bt_string_to_uuid(bt_uuid_t *uuid, const char *string) +{ + if (is_uuid128(string)) + return bt_string_to_uuid128(uuid, string); + else if (is_uuid32(string)) + return bt_string_to_uuid32(uuid, string); + else if (is_uuid16(string)) + return bt_string_to_uuid16(uuid, string); + + return -EINVAL; +} + +int bt_uuid_strcmp(const void *a, const void *b) +{ + return strcasecmp(a, b); +} diff --git a/drive-sdk/deps/bzle/tools/CMakeLists.txt b/drive-sdk/deps/bzle/tools/CMakeLists.txt new file mode 100644 index 0000000..aca0e1d --- /dev/null +++ b/drive-sdk/deps/bzle/tools/CMakeLists.txt @@ -0,0 +1,21 @@ +# Include the directory itself as a path to include directories +set(CMAKE_INCLUDE_CURRENT_DIR ON) + + +include_directories( + ${bzle_SOURCE_DIR}/include + ) + + +set(hciconfig_SOURCES +csr.h csr.c hciconfig.c textfile.c textfile.h +) + +add_executable(hciconfig ${hciconfig_SOURCES}) +target_link_libraries(hciconfig + bzle + ) + +install(TARGETS hciconfig + RUNTIME DESTINATION bin +) diff --git a/drive-sdk/deps/bzle/tools/csr.c b/drive-sdk/deps/bzle/tools/csr.c new file mode 100644 index 0000000..defeb9f --- /dev/null +++ b/drive-sdk/deps/bzle/tools/csr.c @@ -0,0 +1,2853 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2003-2010 Marcel Holtmann + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "csr.h" + +struct psr_data { + uint16_t pskey; + uint8_t *value; + uint8_t size; + struct psr_data *next; +}; + +static struct psr_data *head = NULL, *tail = NULL; + +static struct { + uint16_t id; + char *str; +} csr_map[] = { + { 66, "HCI 9.8" }, + { 97, "HCI 10.3" }, + { 101, "HCI 10.5" }, + { 111, "HCI 11.0" }, + { 112, "HCI 11.1" }, + { 114, "HCI 11.2" }, + { 115, "HCI 11.3" }, + { 117, "HCI 12.0" }, + { 119, "HCI 12.1" }, + { 133, "HCI 12.2" }, + { 134, "HCI 12.3" }, + { 162, "HCI 12.4" }, + { 165, "HCI 12.5" }, + { 169, "HCI 12.6" }, + { 188, "HCI 12.7" }, + { 218, "HCI 12.8" }, + { 283, "HCI 12.9" }, + { 203, "HCI 13.2" }, + { 204, "HCI 13.2" }, + { 210, "HCI 13.3" }, + { 211, "HCI 13.3" }, + { 213, "HCI 13.4" }, + { 214, "HCI 13.4" }, + { 225, "HCI 13.5" }, + { 226, "HCI 13.5" }, + { 237, "HCI 13.6" }, + { 238, "HCI 13.6" }, + { 242, "HCI 14.0" }, + { 243, "HCI 14.0" }, + { 244, "HCI 14.0" }, + { 245, "HCI 14.0" }, + { 254, "HCI 13.7" }, + { 255, "HCI 13.7" }, + { 264, "HCI 14.1" }, + { 265, "HCI 14.1" }, + { 267, "HCI 14.2" }, + { 268, "HCI 14.2" }, + { 272, "HCI 14.3" }, + { 273, "HCI 14.3" }, + { 274, "HCI 13.8" }, + { 275, "HCI 13.8" }, + { 286, "HCI 13.9" }, + { 287, "HCI 13.9" }, + { 309, "HCI 13.10" }, + { 310, "HCI 13.10" }, + { 313, "HCI 14.4" }, + { 314, "HCI 14.4" }, + { 323, "HCI 14.5" }, + { 324, "HCI 14.5" }, + { 336, "HCI 14.6" }, + { 337, "HCI 14.6" }, + { 351, "HCI 13.11" }, + { 352, "HCI 13.11" }, + { 362, "HCI 15.0" }, + { 363, "HCI 15.0" }, + { 364, "HCI 15.0" }, + { 365, "HCI 15.0" }, + { 373, "HCI 14.7" }, + { 374, "HCI 14.7" }, + { 379, "HCI 15.1" }, + { 380, "HCI 15.1" }, + { 381, "HCI 15.1" }, + { 382, "HCI 15.1" }, + { 392, "HCI 15.2" }, + { 393, "HCI 15.2" }, + { 394, "HCI 15.2" }, + { 395, "HCI 15.2" }, + { 436, "HCI 16.0" }, + { 437, "HCI 16.0" }, + { 438, "HCI 16.0" }, + { 439, "HCI 16.0" }, + { 443, "HCI 15.3" }, + { 444, "HCI 15.3" }, + { 465, "HCI 16.1" }, + { 466, "HCI 16.1" }, + { 467, "HCI 16.1" }, + { 468, "HCI 16.1" }, + { 487, "HCI 14.8" }, + { 488, "HCI 14.8" }, + { 492, "HCI 16.2" }, + { 493, "HCI 16.2" }, + { 495, "HCI 16.2" }, + { 496, "HCI 16.2" }, + { 502, "HCI 16.1.1" }, + { 503, "HCI 16.1.1" }, + { 504, "HCI 16.1.1" }, + { 505, "HCI 16.1.1" }, + { 506, "HCI 16.1.2" }, + { 507, "HCI 16.1.2" }, + { 508, "HCI 16.1.2" }, + { 509, "HCI 16.1.2" }, + { 516, "HCI 16.3" }, + { 517, "HCI 16.3" }, + { 518, "HCI 16.3" }, + { 519, "HCI 16.3" }, + { 523, "HCI 16.4" }, + { 524, "HCI 16.4" }, + { 525, "HCI 16.4" }, + { 526, "HCI 16.4" }, + { 553, "HCI 15.3" }, + { 554, "HCI 15.3" }, + { 562, "HCI 16.5" }, + { 563, "HCI 16.5" }, + { 564, "HCI 16.5" }, + { 565, "HCI 16.5" }, + { 593, "HCI 17.0" }, + { 594, "HCI 17.0" }, + { 595, "HCI 17.0" }, + { 599, "HCI 17.0" }, + { 600, "HCI 17.0" }, + { 608, "HCI 13.10.1" }, + { 609, "HCI 13.10.1" }, + { 613, "HCI 17.1" }, + { 614, "HCI 17.1" }, + { 615, "HCI 17.1" }, + { 616, "HCI 17.1" }, + { 618, "HCI 17.1" }, + { 624, "HCI 17.2" }, + { 625, "HCI 17.2" }, + { 626, "HCI 17.2" }, + { 627, "HCI 17.2" }, + { 637, "HCI 16.6" }, + { 638, "HCI 16.6" }, + { 639, "HCI 16.6" }, + { 640, "HCI 16.6" }, + { 642, "HCI 13.10.2" }, + { 643, "HCI 13.10.2" }, + { 644, "HCI 13.10.3" }, + { 645, "HCI 13.10.3" }, + { 668, "HCI 13.10.4" }, + { 669, "HCI 13.10.4" }, + { 681, "HCI 16.7" }, + { 682, "HCI 16.7" }, + { 683, "HCI 16.7" }, + { 684, "HCI 16.7" }, + { 704, "HCI 16.8" }, + { 718, "HCI 16.4.1" }, + { 719, "HCI 16.4.1" }, + { 720, "HCI 16.4.1" }, + { 721, "HCI 16.4.1" }, + { 722, "HCI 16.7.1" }, + { 723, "HCI 16.7.1" }, + { 724, "HCI 16.7.1" }, + { 725, "HCI 16.7.1" }, + { 731, "HCI 16.7.2" }, + { 732, "HCI 16.7.2" }, + { 733, "HCI 16.7.2" }, + { 734, "HCI 16.7.2" }, + { 735, "HCI 16.4.2" }, + { 736, "HCI 16.4.2" }, + { 737, "HCI 16.4.2" }, + { 738, "HCI 16.4.2" }, + { 750, "HCI 16.7.3" }, + { 751, "HCI 16.7.3" }, + { 752, "HCI 16.7.3" }, + { 753, "HCI 16.7.3" }, + { 760, "HCI 16.7.4" }, + { 761, "HCI 16.7.4" }, + { 762, "HCI 16.7.4" }, + { 763, "HCI 16.7.4" }, + { 770, "HCI 16.9" }, + { 771, "HCI 16.9" }, + { 772, "HCI 16.9" }, + { 773, "HCI 16.9" }, + { 774, "HCI 17.3" }, + { 775, "HCI 17.3" }, + { 776, "HCI 17.3" }, + { 777, "HCI 17.3" }, + { 781, "HCI 16.7.5" }, + { 786, "HCI 16.10" }, + { 787, "HCI 16.10" }, + { 788, "HCI 16.10" }, + { 789, "HCI 16.10" }, + { 791, "HCI 16.4.3" }, + { 792, "HCI 16.4.3" }, + { 793, "HCI 16.4.3" }, + { 794, "HCI 16.4.3" }, + { 798, "HCI 16.11" }, + { 799, "HCI 16.11" }, + { 800, "HCI 16.11" }, + { 801, "HCI 16.11" }, + { 806, "HCI 16.7.5" }, + { 807, "HCI 16.12" }, + { 808, "HCI 16.12" }, + { 809, "HCI 16.12" }, + { 810, "HCI 16.12" }, + { 817, "HCI 16.13" }, + { 818, "HCI 16.13" }, + { 819, "HCI 16.13" }, + { 820, "HCI 16.13" }, + { 823, "HCI 13.10.5" }, + { 824, "HCI 13.10.5" }, + { 826, "HCI 16.14" }, + { 827, "HCI 16.14" }, + { 828, "HCI 16.14" }, + { 829, "HCI 16.14" }, + { 843, "HCI 17.3.1" }, + { 856, "HCI 17.3.2" }, + { 857, "HCI 17.3.2" }, + { 858, "HCI 17.3.2" }, + { 1120, "HCI 17.11" }, + { 1168, "HCI 18.1" }, + { 1169, "HCI 18.1" }, + { 1241, "HCI 18.x" }, + { 1298, "HCI 18.2" }, + { 1354, "HCI 18.2" }, + { 1392, "HCI 18.2" }, + { 1393, "HCI 18.2" }, + { 1501, "HCI 18.2" }, + { 1503, "HCI 18.2" }, + { 1504, "HCI 18.2" }, + { 1505, "HCI 18.2" }, + { 1506, "HCI 18.2" }, + { 1520, "HCI 18.2" }, + { 1586, "HCI 18.2" }, + { 1591, "HCI 18.2" }, + { 1592, "HCI 18.2" }, + { 1593, "HCI 18.2.1" }, + { 1733, "HCI 18.3" }, + { 1734, "HCI 18.3" }, + { 1735, "HCI 18.3" }, + { 1737, "HCI 18.3" }, + { 1915, "HCI 19.2" }, + { 1916, "HCI 19.2" }, + { 1958, "HCI 19.2" }, + { 1981, "Unified 20a" }, + { 1982, "Unified 20a" }, + { 1989, "HCI 18.4" }, + { 2062, "Unified 20a1" }, + { 2063, "Unified 20a1" }, + { 2067, "Unified 18f" }, + { 2068, "Unified 18f" }, + { 2243, "Unified 18e" }, + { 2244, "Unified 18e" }, + { 2258, "Unified 20d" }, + { 2259, "Unified 20d" }, + { 2361, "Unified 20e" }, + { 2362, "Unified 20e" }, + { 2386, "Unified 21a" }, + { 2387, "Unified 21a" }, + { 2423, "Unified 21a" }, + { 2424, "Unified 21a" }, + { 2623, "Unified 21c" }, + { 2624, "Unified 21c" }, + { 2625, "Unified 21c" }, + { 2626, "Unified 21c" }, + { 2627, "Unified 21c" }, + { 2628, "Unified 21c" }, + { 2629, "Unified 21c" }, + { 2630, "Unified 21c" }, + { 2631, "Unified 21c" }, + { 2632, "Unified 21c" }, + { 2633, "Unified 21c" }, + { 2634, "Unified 21c" }, + { 2635, "Unified 21c" }, + { 2636, "Unified 21c" }, + { 2649, "Unified 21c" }, + { 2650, "Unified 21c" }, + { 2651, "Unified 21c" }, + { 2652, "Unified 21c" }, + { 2653, "Unified 21c" }, + { 2654, "Unified 21c" }, + { 2655, "Unified 21c" }, + { 2656, "Unified 21c" }, + { 2658, "Unified 21c" }, + { 3057, "Unified 21d" }, + { 3058, "Unified 21d" }, + { 3059, "Unified 21d" }, + { 3060, "Unified 21d" }, + { 3062, "Unified 21d" }, + { 3063, "Unified 21d" }, + { 3064, "Unified 21d" }, + { 3164, "Unified 21e" }, + { 3413, "Unified 21f" }, + { 3414, "Unified 21f" }, + { 3415, "Unified 21f" }, + { 3424, "Unified 21f" }, + { 3454, "Unified 21f" }, + { 3684, "Unified 21f" }, + { 3764, "Unified 21f" }, + { 4276, "Unified 22b" }, + { 4277, "Unified 22b" }, + { 4279, "Unified 22b" }, + { 4281, "Unified 22b" }, + { 4282, "Unified 22b" }, + { 4283, "Unified 22b" }, + { 4284, "Unified 22b" }, + { 4285, "Unified 22b" }, + { 4289, "Unified 22b" }, + { 4290, "Unified 22b" }, + { 4291, "Unified 22b" }, + { 4292, "Unified 22b" }, + { 4293, "Unified 22b" }, + { 4294, "Unified 22b" }, + { 4295, "Unified 22b" }, + { 4363, "Unified 22c" }, + { 4373, "Unified 22c" }, + { 4374, "Unified 22c" }, + { 4532, "Unified 22d" }, + { 4533, "Unified 22d" }, + { 4698, "Unified 23c" }, + { 4839, "Unified 23c" }, + { 4841, "Unified 23c" }, + { 4866, "Unified 23c" }, + { 4867, "Unified 23c" }, + { 4868, "Unified 23c" }, + { 4869, "Unified 23c" }, + { 4870, "Unified 23c" }, + { 4871, "Unified 23c" }, + { 4872, "Unified 23c" }, + { 4874, "Unified 23c" }, + { 4875, "Unified 23c" }, + { 4876, "Unified 23c" }, + { 4877, "Unified 23c" }, + { 2526, "Marcel 1 (2005-09-26)" }, + { 2543, "Marcel 2 (2005-09-28)" }, + { 2622, "Marcel 3 (2005-10-27)" }, + { 3326, "Marcel 4 (2006-06-16)" }, + { 3612, "Marcel 5 (2006-10-24)" }, + { 4509, "Marcel 6 (2007-06-11)" }, + { 5417, "Marcel 7 (2008-08-26)" }, + { 195, "Sniff 1 (2001-11-27)" }, + { 220, "Sniff 2 (2002-01-03)" }, + { 269, "Sniff 3 (2002-02-22)" }, + { 270, "Sniff 4 (2002-02-26)" }, + { 284, "Sniff 5 (2002-03-12)" }, + { 292, "Sniff 6 (2002-03-20)" }, + { 305, "Sniff 7 (2002-04-12)" }, + { 306, "Sniff 8 (2002-04-12)" }, + { 343, "Sniff 9 (2002-05-02)" }, + { 346, "Sniff 10 (2002-05-03)" }, + { 355, "Sniff 11 (2002-05-16)" }, + { 256, "Sniff 11 (2002-05-16)" }, + { 390, "Sniff 12 (2002-06-26)" }, + { 450, "Sniff 13 (2002-08-16)" }, + { 451, "Sniff 13 (2002-08-16)" }, + { 533, "Sniff 14 (2002-10-11)" }, + { 580, "Sniff 15 (2002-11-14)" }, + { 623, "Sniff 16 (2002-12-12)" }, + { 678, "Sniff 17 (2003-01-29)" }, + { 847, "Sniff 18 (2003-04-17)" }, + { 876, "Sniff 19 (2003-06-10)" }, + { 997, "Sniff 22 (2003-09-05)" }, + { 1027, "Sniff 23 (2003-10-03)" }, + { 1029, "Sniff 24 (2003-10-03)" }, + { 1112, "Sniff 25 (2003-12-03)" }, + { 1113, "Sniff 25 (2003-12-03)" }, + { 1133, "Sniff 26 (2003-12-18)" }, + { 1134, "Sniff 26 (2003-12-18)" }, + { 1223, "Sniff 27 (2004-03-08)" }, + { 1224, "Sniff 27 (2004-03-08)" }, + { 1319, "Sniff 31 (2004-04-22)" }, + { 1320, "Sniff 31 (2004-04-22)" }, + { 1427, "Sniff 34 (2004-06-16)" }, + { 1508, "Sniff 35 (2004-07-19)" }, + { 1509, "Sniff 35 (2004-07-19)" }, + { 1587, "Sniff 36 (2004-08-18)" }, + { 1588, "Sniff 36 (2004-08-18)" }, + { 1641, "Sniff 37 (2004-09-16)" }, + { 1642, "Sniff 37 (2004-09-16)" }, + { 1699, "Sniff 38 (2004-10-07)" }, + { 1700, "Sniff 38 (2004-10-07)" }, + { 1752, "Sniff 39 (2004-11-02)" }, + { 1753, "Sniff 39 (2004-11-02)" }, + { 1759, "Sniff 40 (2004-11-03)" }, + { 1760, "Sniff 40 (2004-11-03)" }, + { 1761, "Sniff 40 (2004-11-03)" }, + { 2009, "Sniff 41 (2005-04-06)" }, + { 2010, "Sniff 41 (2005-04-06)" }, + { 2011, "Sniff 41 (2005-04-06)" }, + { 2016, "Sniff 42 (2005-04-11)" }, + { 2017, "Sniff 42 (2005-04-11)" }, + { 2018, "Sniff 42 (2005-04-11)" }, + { 2023, "Sniff 43 (2005-04-14)" }, + { 2024, "Sniff 43 (2005-04-14)" }, + { 2025, "Sniff 43 (2005-04-14)" }, + { 2032, "Sniff 44 (2005-04-18)" }, + { 2033, "Sniff 44 (2005-04-18)" }, + { 2034, "Sniff 44 (2005-04-18)" }, + { 2288, "Sniff 45 (2005-07-08)" }, + { 2289, "Sniff 45 (2005-07-08)" }, + { 2290, "Sniff 45 (2005-07-08)" }, + { 2388, "Sniff 46 (2005-08-17)" }, + { 2389, "Sniff 46 (2005-08-17)" }, + { 2390, "Sniff 46 (2005-08-17)" }, + { 2869, "Sniff 47 (2006-02-15)" }, + { 2870, "Sniff 47 (2006-02-15)" }, + { 2871, "Sniff 47 (2006-02-15)" }, + { 3214, "Sniff 48 (2006-05-16)" }, + { 3215, "Sniff 48 (2006-05-16)" }, + { 3216, "Sniff 48 (2006-05-16)" }, + { 3356, "Sniff 49 (2006-07-17)" }, + { 3529, "Sniff 50 (2006-09-21)" }, + { 3546, "Sniff 51 (2006-09-29)" }, + { 3683, "Sniff 52 (2006-11-03)" }, + { 0, } +}; + +char *csr_builddeftostr(uint16_t def) +{ + switch (def) { + case 0x0000: + return "NONE"; + case 0x0001: + return "CHIP_BASE_BC01"; + case 0x0002: + return "CHIP_BASE_BC02"; + case 0x0003: + return "CHIP_BC01B"; + case 0x0004: + return "CHIP_BC02_EXTERNAL"; + case 0x0005: + return "BUILD_HCI"; + case 0x0006: + return "BUILD_RFCOMM"; + case 0x0007: + return "BT_VER_1_1"; + case 0x0008: + return "TRANSPORT_ALL"; + case 0x0009: + return "TRANSPORT_BCSP"; + case 0x000a: + return "TRANSPORT_H4"; + case 0x000b: + return "TRANSPORT_USB"; + case 0x000c: + return "MAX_CRYPT_KEY_LEN_56"; + case 0x000d: + return "MAX_CRYPT_KEY_LEN_128"; + case 0x000e: + return "TRANSPORT_USER"; + case 0x000f: + return "CHIP_BC02_KATO"; + case 0x0010: + return "TRANSPORT_NONE"; + case 0x0012: + return "REQUIRE_8MBIT"; + case 0x0013: + return "RADIOTEST"; + case 0x0014: + return "RADIOTEST_LITE"; + case 0x0015: + return "INSTALL_FLASH"; + case 0x0016: + return "INSTALL_EEPROM"; + case 0x0017: + return "INSTALL_COMBO_DOT11"; + case 0x0018: + return "LOWPOWER_TX"; + case 0x0019: + return "TRANSPORT_TWUTL"; + case 0x001a: + return "COMPILER_GCC"; + case 0x001b: + return "CHIP_BC02_CLOUSEAU"; + case 0x001c: + return "CHIP_BC02_TOULOUSE"; + case 0x001d: + return "CHIP_BASE_BC3"; + case 0x001e: + return "CHIP_BC3_NICKNACK"; + case 0x001f: + return "CHIP_BC3_KALIMBA"; + case 0x0020: + return "INSTALL_HCI_MODULE"; + case 0x0021: + return "INSTALL_L2CAP_MODULE"; + case 0x0022: + return "INSTALL_DM_MODULE"; + case 0x0023: + return "INSTALL_SDP_MODULE"; + case 0x0024: + return "INSTALL_RFCOMM_MODULE"; + case 0x0025: + return "INSTALL_HIDIO_MODULE"; + case 0x0026: + return "INSTALL_PAN_MODULE"; + case 0x0027: + return "INSTALL_IPV4_MODULE"; + case 0x0028: + return "INSTALL_IPV6_MODULE"; + case 0x0029: + return "INSTALL_TCP_MODULE"; + case 0x002a: + return "BT_VER_1_2"; + case 0x002b: + return "INSTALL_UDP_MODULE"; + case 0x002c: + return "REQUIRE_0_WAIT_STATES"; + case 0x002d: + return "CHIP_BC3_PADDYWACK"; + case 0x002e: + return "CHIP_BC4_COYOTE"; + case 0x002f: + return "CHIP_BC4_ODDJOB"; + case 0x0030: + return "TRANSPORT_H4DS"; + case 0x0031: + return "CHIP_BASE_BC4"; + default: + return "UNKNOWN"; + } +} + +char *csr_buildidtostr(uint16_t id) +{ + static char str[12]; + int i; + + for (i = 0; csr_map[i].id; i++) + if (csr_map[i].id == id) + return csr_map[i].str; + + snprintf(str, 11, "Build %d", id); + return str; +} + +char *csr_chipvertostr(uint16_t ver, uint16_t rev) +{ + switch (ver) { + case 0x00: + return "BlueCore01a"; + case 0x01: + switch (rev) { + case 0x64: + return "BlueCore01b (ES)"; + case 0x65: + default: + return "BlueCore01b"; + } + case 0x02: + switch (rev) { + case 0x89: + return "BlueCore02-External (ES2)"; + case 0x8a: + return "BlueCore02-External"; + case 0x28: + return "BlueCore02-ROM/Audio/Flash"; + default: + return "BlueCore02"; + } + case 0x03: + switch (rev) { + case 0x43: + return "BlueCore3-MM"; + case 0x15: + return "BlueCore3-ROM"; + case 0xe2: + return "BlueCore3-Flash"; + case 0x26: + return "BlueCore4-External"; + case 0x30: + return "BlueCore4-ROM"; + default: + return "BlueCore3 or BlueCore4"; + } + default: + return "Unknown"; + } +} + +char *csr_pskeytostr(uint16_t pskey) +{ + switch (pskey) { + case CSR_PSKEY_BDADDR: + return "Bluetooth address"; + case CSR_PSKEY_COUNTRYCODE: + return "Country code"; + case CSR_PSKEY_CLASSOFDEVICE: + return "Class of device"; + case CSR_PSKEY_DEVICE_DRIFT: + return "Device drift"; + case CSR_PSKEY_DEVICE_JITTER: + return "Device jitter"; + case CSR_PSKEY_MAX_ACLS: + return "Maximum ACL links"; + case CSR_PSKEY_MAX_SCOS: + return "Maximum SCO links"; + case CSR_PSKEY_MAX_REMOTE_MASTERS: + return "Maximum remote masters"; + case CSR_PSKEY_ENABLE_MASTERY_WITH_SLAVERY: + return "Support master and slave roles simultaneously"; + case CSR_PSKEY_H_HC_FC_MAX_ACL_PKT_LEN: + return "Maximum HCI ACL packet length"; + case CSR_PSKEY_H_HC_FC_MAX_SCO_PKT_LEN: + return "Maximum HCI SCO packet length"; + case CSR_PSKEY_H_HC_FC_MAX_ACL_PKTS: + return "Maximum number of HCI ACL packets"; + case CSR_PSKEY_H_HC_FC_MAX_SCO_PKTS: + return "Maximum number of HCI SCO packets"; + case CSR_PSKEY_LC_FC_BUFFER_LOW_WATER_MARK: + return "Flow control low water mark"; + case CSR_PSKEY_LC_MAX_TX_POWER: + return "Maximum transmit power"; + case CSR_PSKEY_TX_GAIN_RAMP: + return "Transmit gain ramp rate"; + case CSR_PSKEY_LC_POWER_TABLE: + return "Radio power table"; + case CSR_PSKEY_LC_PEER_POWER_PERIOD: + return "Peer transmit power control interval"; + case CSR_PSKEY_LC_FC_POOLS_LOW_WATER_MARK: + return "Flow control pool low water mark"; + case CSR_PSKEY_LC_DEFAULT_TX_POWER: + return "Default transmit power"; + case CSR_PSKEY_LC_RSSI_GOLDEN_RANGE: + return "RSSI at bottom of golden receive range"; + case CSR_PSKEY_LC_COMBO_DISABLE_PIO_MASK: + return "Combo: PIO lines and logic to disable transmit"; + case CSR_PSKEY_LC_COMBO_PRIORITY_PIO_MASK: + return "Combo: priority activity PIO lines and logic"; + case CSR_PSKEY_LC_COMBO_DOT11_CHANNEL_PIO_BASE: + return "Combo: 802.11b channel number base PIO line"; + case CSR_PSKEY_LC_COMBO_DOT11_BLOCK_CHANNELS: + return "Combo: channels to block either side of 802.11b"; + case CSR_PSKEY_LC_MAX_TX_POWER_NO_RSSI: + return "Maximum transmit power when peer has no RSSI"; + case CSR_PSKEY_LC_CONNECTION_RX_WINDOW: + return "Receive window size during connections"; + case CSR_PSKEY_LC_COMBO_DOT11_TX_PROTECTION_MODE: + return "Combo: which TX packets shall we protect"; + case CSR_PSKEY_LC_ENHANCED_POWER_TABLE: + return "Radio power table"; + case CSR_PSKEY_LC_WIDEBAND_RSSI_CONFIG: + return "RSSI configuration for use with wideband RSSI"; + case CSR_PSKEY_LC_COMBO_DOT11_PRIORITY_LEAD: + return "Combo: How much notice will we give the Combo Card"; + case CSR_PSKEY_BT_CLOCK_INIT: + return "Initial value of Bluetooth clock"; + case CSR_PSKEY_TX_MR_MOD_DELAY: + return "TX Mod delay"; + case CSR_PSKEY_RX_MR_SYNC_TIMING: + return "RX MR Sync Timing"; + case CSR_PSKEY_RX_MR_SYNC_CONFIG: + return "RX MR Sync Configuration"; + case CSR_PSKEY_LC_LOST_SYNC_SLOTS: + return "Time in ms for lost sync in low power modes"; + case CSR_PSKEY_RX_MR_SAMP_CONFIG: + return "RX MR Sync Configuration"; + case CSR_PSKEY_AGC_HYST_LEVELS: + return "AGC hysteresis levels"; + case CSR_PSKEY_RX_LEVEL_LOW_SIGNAL: + return "ANA_RX_LVL at low signal strengths"; + case CSR_PSKEY_AGC_IQ_LVL_VALUES: + return "ANA_IQ_LVL values for AGC algorithmn"; + case CSR_PSKEY_MR_FTRIM_OFFSET_12DB: + return "ANA_RX_FTRIM offset when using 12 dB IF atten "; + case CSR_PSKEY_MR_FTRIM_OFFSET_6DB: + return "ANA_RX_FTRIM offset when using 6 dB IF atten "; + case CSR_PSKEY_NO_CAL_ON_BOOT: + return "Do not calibrate radio on boot"; + case CSR_PSKEY_RSSI_HI_TARGET: + return "RSSI high target"; + case CSR_PSKEY_PREFERRED_MIN_ATTENUATION: + return "Preferred minimum attenuator setting"; + case CSR_PSKEY_LC_COMBO_DOT11_PRIORITY_OVERRIDE: + return "Combo: Treat all packets as high priority"; + case CSR_PSKEY_LC_MULTISLOT_HOLDOFF: + return "Time till single slot packets are used for resync"; + case CSR_PSKEY_FREE_KEY_PIGEON_HOLE: + return "Link key store bitfield"; + case CSR_PSKEY_LINK_KEY_BD_ADDR0: + return "Bluetooth address + link key 0"; + case CSR_PSKEY_LINK_KEY_BD_ADDR1: + return "Bluetooth address + link key 1"; + case CSR_PSKEY_LINK_KEY_BD_ADDR2: + return "Bluetooth address + link key 2"; + case CSR_PSKEY_LINK_KEY_BD_ADDR3: + return "Bluetooth address + link key 3"; + case CSR_PSKEY_LINK_KEY_BD_ADDR4: + return "Bluetooth address + link key 4"; + case CSR_PSKEY_LINK_KEY_BD_ADDR5: + return "Bluetooth address + link key 5"; + case CSR_PSKEY_LINK_KEY_BD_ADDR6: + return "Bluetooth address + link key 6"; + case CSR_PSKEY_LINK_KEY_BD_ADDR7: + return "Bluetooth address + link key 7"; + case CSR_PSKEY_LINK_KEY_BD_ADDR8: + return "Bluetooth address + link key 8"; + case CSR_PSKEY_LINK_KEY_BD_ADDR9: + return "Bluetooth address + link key 9"; + case CSR_PSKEY_LINK_KEY_BD_ADDR10: + return "Bluetooth address + link key 10"; + case CSR_PSKEY_LINK_KEY_BD_ADDR11: + return "Bluetooth address + link key 11"; + case CSR_PSKEY_LINK_KEY_BD_ADDR12: + return "Bluetooth address + link key 12"; + case CSR_PSKEY_LINK_KEY_BD_ADDR13: + return "Bluetooth address + link key 13"; + case CSR_PSKEY_LINK_KEY_BD_ADDR14: + return "Bluetooth address + link key 14"; + case CSR_PSKEY_LINK_KEY_BD_ADDR15: + return "Bluetooth address + link key 15"; + case CSR_PSKEY_ENC_KEY_LMIN: + return "Minimum encryption key length"; + case CSR_PSKEY_ENC_KEY_LMAX: + return "Maximum encryption key length"; + case CSR_PSKEY_LOCAL_SUPPORTED_FEATURES: + return "Local supported features block"; + case CSR_PSKEY_LM_USE_UNIT_KEY: + return "Allow use of unit key for authentication?"; + case CSR_PSKEY_HCI_NOP_DISABLE: + return "Disable the HCI Command_Status event on boot"; + case CSR_PSKEY_LM_MAX_EVENT_FILTERS: + return "Maximum number of event filters"; + case CSR_PSKEY_LM_USE_ENC_MODE_BROADCAST: + return "Allow LM to use enc_mode=2"; + case CSR_PSKEY_LM_TEST_SEND_ACCEPTED_TWICE: + return "LM sends two LMP_accepted messages in test mode"; + case CSR_PSKEY_LM_MAX_PAGE_HOLD_TIME: + return "Maximum time we hold a device around page"; + case CSR_PSKEY_AFH_ADAPTATION_RESPONSE_TIME: + return "LM period for AFH adaption"; + case CSR_PSKEY_AFH_OPTIONS: + return "Options to configure AFH"; + case CSR_PSKEY_AFH_RSSI_RUN_PERIOD: + return "AFH RSSI reading period"; + case CSR_PSKEY_AFH_REENABLE_CHANNEL_TIME: + return "AFH good channel adding time"; + case CSR_PSKEY_NO_DROP_ON_ACR_MS_FAIL: + return "Complete link if acr barge-in role switch refused"; + case CSR_PSKEY_MAX_PRIVATE_KEYS: + return "Max private link keys stored"; + case CSR_PSKEY_PRIVATE_LINK_KEY_BD_ADDR0: + return "Bluetooth address + link key 0"; + case CSR_PSKEY_PRIVATE_LINK_KEY_BD_ADDR1: + return "Bluetooth address + link key 1"; + case CSR_PSKEY_PRIVATE_LINK_KEY_BD_ADDR2: + return "Bluetooth address + link key 2"; + case CSR_PSKEY_PRIVATE_LINK_KEY_BD_ADDR3: + return "Bluetooth address + link key 3"; + case CSR_PSKEY_PRIVATE_LINK_KEY_BD_ADDR4: + return "Bluetooth address + link key 4"; + case CSR_PSKEY_PRIVATE_LINK_KEY_BD_ADDR5: + return "Bluetooth address + link key 5"; + case CSR_PSKEY_PRIVATE_LINK_KEY_BD_ADDR6: + return "Bluetooth address + link key 6"; + case CSR_PSKEY_PRIVATE_LINK_KEY_BD_ADDR7: + return "Bluetooth address + link key 7"; + case CSR_PSKEY_LOCAL_SUPPORTED_COMMANDS: + return "Local supported commands"; + case CSR_PSKEY_LM_MAX_ABSENCE_INDEX: + return "Maximum absence index allowed"; + case CSR_PSKEY_DEVICE_NAME: + return "Local device's \"user friendly\" name"; + case CSR_PSKEY_AFH_RSSI_THRESHOLD: + return "AFH RSSI threshold"; + case CSR_PSKEY_LM_CASUAL_SCAN_INTERVAL: + return "Scan interval in slots for casual scanning"; + case CSR_PSKEY_AFH_MIN_MAP_CHANGE: + return "The minimum amount to change an AFH map by"; + case CSR_PSKEY_AFH_RSSI_LP_RUN_PERIOD: + return "AFH RSSI reading period when in low power mode"; + case CSR_PSKEY_HCI_LMP_LOCAL_VERSION: + return "The HCI and LMP version reported locally"; + case CSR_PSKEY_LMP_REMOTE_VERSION: + return "The LMP version reported remotely"; + case CSR_PSKEY_HOLD_ERROR_MESSAGE_NUMBER: + return "Maximum number of queued HCI Hardware Error Events"; + case CSR_PSKEY_DFU_ATTRIBUTES: + return "DFU attributes"; + case CSR_PSKEY_DFU_DETACH_TO: + return "DFU detach timeout"; + case CSR_PSKEY_DFU_TRANSFER_SIZE: + return "DFU transfer size"; + case CSR_PSKEY_DFU_ENABLE: + return "DFU enable"; + case CSR_PSKEY_DFU_LIN_REG_ENABLE: + return "Linear Regulator enabled at boot in DFU mode"; + case CSR_PSKEY_DFUENC_VMAPP_PK_MODULUS_MSB: + return "DFU encryption VM application public key MSB"; + case CSR_PSKEY_DFUENC_VMAPP_PK_MODULUS_LSB: + return "DFU encryption VM application public key LSB"; + case CSR_PSKEY_DFUENC_VMAPP_PK_M_DASH: + return "DFU encryption VM application M dash"; + case CSR_PSKEY_DFUENC_VMAPP_PK_R2N_MSB: + return "DFU encryption VM application public key R2N MSB"; + case CSR_PSKEY_DFUENC_VMAPP_PK_R2N_LSB: + return "DFU encryption VM application public key R2N LSB"; + case CSR_PSKEY_BCSP_LM_PS_BLOCK: + return "BCSP link establishment block"; + case CSR_PSKEY_HOSTIO_FC_PS_BLOCK: + return "HCI flow control block"; + case CSR_PSKEY_HOSTIO_PROTOCOL_INFO0: + return "Host transport channel 0 settings (BCSP ACK)"; + case CSR_PSKEY_HOSTIO_PROTOCOL_INFO1: + return "Host transport channel 1 settings (BCSP-LE)"; + case CSR_PSKEY_HOSTIO_PROTOCOL_INFO2: + return "Host transport channel 2 settings (BCCMD)"; + case CSR_PSKEY_HOSTIO_PROTOCOL_INFO3: + return "Host transport channel 3 settings (HQ)"; + case CSR_PSKEY_HOSTIO_PROTOCOL_INFO4: + return "Host transport channel 4 settings (DM)"; + case CSR_PSKEY_HOSTIO_PROTOCOL_INFO5: + return "Host transport channel 5 settings (HCI CMD/EVT)"; + case CSR_PSKEY_HOSTIO_PROTOCOL_INFO6: + return "Host transport channel 6 settings (HCI ACL)"; + case CSR_PSKEY_HOSTIO_PROTOCOL_INFO7: + return "Host transport channel 7 settings (HCI SCO)"; + case CSR_PSKEY_HOSTIO_PROTOCOL_INFO8: + return "Host transport channel 8 settings (L2CAP)"; + case CSR_PSKEY_HOSTIO_PROTOCOL_INFO9: + return "Host transport channel 9 settings (RFCOMM)"; + case CSR_PSKEY_HOSTIO_PROTOCOL_INFO10: + return "Host transport channel 10 settings (SDP)"; + case CSR_PSKEY_HOSTIO_PROTOCOL_INFO11: + return "Host transport channel 11 settings (TEST)"; + case CSR_PSKEY_HOSTIO_PROTOCOL_INFO12: + return "Host transport channel 12 settings (DFU)"; + case CSR_PSKEY_HOSTIO_PROTOCOL_INFO13: + return "Host transport channel 13 settings (VM)"; + case CSR_PSKEY_HOSTIO_PROTOCOL_INFO14: + return "Host transport channel 14 settings"; + case CSR_PSKEY_HOSTIO_PROTOCOL_INFO15: + return "Host transport channel 15 settings"; + case CSR_PSKEY_HOSTIO_UART_RESET_TIMEOUT: + return "UART reset counter timeout"; + case CSR_PSKEY_HOSTIO_USE_HCI_EXTN: + return "Use hci_extn to route non-hci channels"; + case CSR_PSKEY_HOSTIO_USE_HCI_EXTN_CCFC: + return "Use command-complete flow control for hci_extn"; + case CSR_PSKEY_HOSTIO_HCI_EXTN_PAYLOAD_SIZE: + return "Maximum hci_extn payload size"; + case CSR_PSKEY_BCSP_LM_CNF_CNT_LIMIT: + return "BCSP link establishment conf message count"; + case CSR_PSKEY_HOSTIO_MAP_SCO_PCM: + return "Map SCO over PCM"; + case CSR_PSKEY_HOSTIO_AWKWARD_PCM_SYNC: + return "PCM interface synchronisation is difficult"; + case CSR_PSKEY_HOSTIO_BREAK_POLL_PERIOD: + return "Break poll period (microseconds)"; + case CSR_PSKEY_HOSTIO_MIN_UART_HCI_SCO_SIZE: + return "Minimum SCO packet size sent to host over UART HCI"; + case CSR_PSKEY_HOSTIO_MAP_SCO_CODEC: + return "Map SCO over the built-in codec"; + case CSR_PSKEY_PCM_CVSD_TX_HI_FREQ_BOOST: + return "High frequency boost for PCM when transmitting CVSD"; + case CSR_PSKEY_PCM_CVSD_RX_HI_FREQ_BOOST: + return "High frequency boost for PCM when receiving CVSD"; + case CSR_PSKEY_PCM_CONFIG32: + return "PCM interface settings bitfields"; + case CSR_PSKEY_USE_OLD_BCSP_LE: + return "Use the old version of BCSP link establishment"; + case CSR_PSKEY_PCM_CVSD_USE_NEW_FILTER: + return "CVSD uses the new filter if available"; + case CSR_PSKEY_PCM_FORMAT: + return "PCM data format"; + case CSR_PSKEY_CODEC_OUT_GAIN: + return "Audio output gain when using built-in codec"; + case CSR_PSKEY_CODEC_IN_GAIN: + return "Audio input gain when using built-in codec"; + case CSR_PSKEY_CODEC_PIO: + return "PIO to enable when built-in codec is enabled"; + case CSR_PSKEY_PCM_LOW_JITTER_CONFIG: + return "PCM interface settings for low jitter master mode"; + case CSR_PSKEY_HOSTIO_SCO_PCM_THRESHOLDS: + return "Thresholds for SCO PCM buffers"; + case CSR_PSKEY_HOSTIO_SCO_HCI_THRESHOLDS: + return "Thresholds for SCO HCI buffers"; + case CSR_PSKEY_HOSTIO_MAP_SCO_PCM_SLOT: + return "Route SCO data to specified slot in pcm frame"; + case CSR_PSKEY_UART_BAUDRATE: + return "UART Baud rate"; + case CSR_PSKEY_UART_CONFIG_BCSP: + return "UART configuration when using BCSP"; + case CSR_PSKEY_UART_CONFIG_H4: + return "UART configuration when using H4"; + case CSR_PSKEY_UART_CONFIG_H5: + return "UART configuration when using H5"; + case CSR_PSKEY_UART_CONFIG_USR: + return "UART configuration when under VM control"; + case CSR_PSKEY_UART_TX_CRCS: + return "Use CRCs for BCSP or H5"; + case CSR_PSKEY_UART_ACK_TIMEOUT: + return "Acknowledgement timeout for BCSP and H5"; + case CSR_PSKEY_UART_TX_MAX_ATTEMPTS: + return "Max times to send reliable BCSP or H5 message"; + case CSR_PSKEY_UART_TX_WINDOW_SIZE: + return "Transmit window size for BCSP and H5"; + case CSR_PSKEY_UART_HOST_WAKE: + return "UART host wakeup"; + case CSR_PSKEY_HOSTIO_THROTTLE_TIMEOUT: + return "Host interface performance control."; + case CSR_PSKEY_PCM_ALWAYS_ENABLE: + return "PCM port is always enable when chip is running"; + case CSR_PSKEY_UART_HOST_WAKE_SIGNAL: + return "Signal to use for uart host wakeup protocol"; + case CSR_PSKEY_UART_CONFIG_H4DS: + return "UART configuration when using H4DS"; + case CSR_PSKEY_H4DS_WAKE_DURATION: + return "How long to spend waking the host when using H4DS"; + case CSR_PSKEY_H4DS_MAXWU: + return "Maximum number of H4DS Wake-Up messages to send"; + case CSR_PSKEY_H4DS_LE_TIMER_PERIOD: + return "H4DS Link Establishment Tsync and Tconf period"; + case CSR_PSKEY_H4DS_TWU_TIMER_PERIOD: + return "H4DS Twu timer period"; + case CSR_PSKEY_H4DS_UART_IDLE_TIMER_PERIOD: + return "H4DS Tuart_idle timer period"; + case CSR_PSKEY_ANA_FTRIM: + return "Crystal frequency trim"; + case CSR_PSKEY_WD_TIMEOUT: + return "Watchdog timeout (microseconds)"; + case CSR_PSKEY_WD_PERIOD: + return "Watchdog period (microseconds)"; + case CSR_PSKEY_HOST_INTERFACE: + return "Host interface"; + case CSR_PSKEY_HQ_HOST_TIMEOUT: + return "HQ host command timeout"; + case CSR_PSKEY_HQ_ACTIVE: + return "Enable host query task?"; + case CSR_PSKEY_BCCMD_SECURITY_ACTIVE: + return "Enable configuration security"; + case CSR_PSKEY_ANA_FREQ: + return "Crystal frequency"; + case CSR_PSKEY_PIO_PROTECT_MASK: + return "Access to PIO pins"; + case CSR_PSKEY_PMALLOC_SIZES: + return "pmalloc sizes array"; + case CSR_PSKEY_UART_BAUD_RATE: + return "UART Baud rate (pre 18)"; + case CSR_PSKEY_UART_CONFIG: + return "UART configuration bitfield"; + case CSR_PSKEY_STUB: + return "Stub"; + case CSR_PSKEY_TXRX_PIO_CONTROL: + return "TX and RX PIO control"; + case CSR_PSKEY_ANA_RX_LEVEL: + return "ANA_RX_LVL register initial value"; + case CSR_PSKEY_ANA_RX_FTRIM: + return "ANA_RX_FTRIM register initial value"; + case CSR_PSKEY_PSBC_DATA_VERSION: + return "Persistent store version"; + case CSR_PSKEY_PCM0_ATTENUATION: + return "Volume control on PCM channel 0"; + case CSR_PSKEY_LO_LVL_MAX: + return "Maximum value of LO level control register"; + case CSR_PSKEY_LO_ADC_AMPL_MIN: + return "Minimum value of the LO amplitude measured on the ADC"; + case CSR_PSKEY_LO_ADC_AMPL_MAX: + return "Maximum value of the LO amplitude measured on the ADC"; + case CSR_PSKEY_IQ_TRIM_CHANNEL: + return "IQ calibration channel"; + case CSR_PSKEY_IQ_TRIM_GAIN: + return "IQ calibration gain"; + case CSR_PSKEY_IQ_TRIM_ENABLE: + return "IQ calibration enable"; + case CSR_PSKEY_TX_OFFSET_HALF_MHZ: + return "Transmit offset"; + case CSR_PSKEY_GBL_MISC_ENABLES: + return "Global miscellaneous hardware enables"; + case CSR_PSKEY_UART_SLEEP_TIMEOUT: + return "Time in ms to deep sleep if nothing received"; + case CSR_PSKEY_DEEP_SLEEP_STATE: + return "Deep sleep state usage"; + case CSR_PSKEY_IQ_ENABLE_PHASE_TRIM: + return "IQ phase enable"; + case CSR_PSKEY_HCI_HANDLE_FREEZE_PERIOD: + return "Time for which HCI handle is frozen after link removal"; + case CSR_PSKEY_MAX_FROZEN_HCI_HANDLES: + return "Maximum number of frozen HCI handles"; + case CSR_PSKEY_PAGETABLE_DESTRUCTION_DELAY: + return "Delay from freezing buf handle to deleting page table"; + case CSR_PSKEY_IQ_TRIM_PIO_SETTINGS: + return "IQ PIO settings"; + case CSR_PSKEY_USE_EXTERNAL_CLOCK: + return "Device uses an external clock"; + case CSR_PSKEY_DEEP_SLEEP_WAKE_CTS: + return "Exit deep sleep on CTS line activity"; + case CSR_PSKEY_FC_HC2H_FLUSH_DELAY: + return "Delay from disconnect to flushing HC->H FC tokens"; + case CSR_PSKEY_RX_HIGHSIDE: + return "Disable the HIGHSIDE bit in ANA_CONFIG"; + case CSR_PSKEY_TX_PRE_LVL: + return "TX pre-amplifier level"; + case CSR_PSKEY_RX_SINGLE_ENDED: + return "RX single ended"; + case CSR_PSKEY_TX_FILTER_CONFIG: + return "TX filter configuration"; + case CSR_PSKEY_CLOCK_REQUEST_ENABLE: + return "External clock request enable"; + case CSR_PSKEY_RX_MIN_ATTEN: + return "Minimum attenuation allowed for receiver"; + case CSR_PSKEY_XTAL_TARGET_AMPLITUDE: + return "Crystal target amplitude"; + case CSR_PSKEY_PCM_MIN_CPU_CLOCK: + return "Minimum CPU clock speed with PCM port running"; + case CSR_PSKEY_HOST_INTERFACE_PIO_USB: + return "USB host interface selection PIO line"; + case CSR_PSKEY_CPU_IDLE_MODE: + return "CPU idle mode when radio is active"; + case CSR_PSKEY_DEEP_SLEEP_CLEAR_RTS: + return "Deep sleep clears the UART RTS line"; + case CSR_PSKEY_RF_RESONANCE_TRIM: + return "Frequency trim for IQ and LNA resonant circuits"; + case CSR_PSKEY_DEEP_SLEEP_PIO_WAKE: + return "PIO line to wake the chip from deep sleep"; + case CSR_PSKEY_DRAIN_BORE_TIMERS: + return "Energy consumption measurement settings"; + case CSR_PSKEY_DRAIN_TX_POWER_BASE: + return "Energy consumption measurement settings"; + case CSR_PSKEY_MODULE_ID: + return "Module serial number"; + case CSR_PSKEY_MODULE_DESIGN: + return "Module design ID"; + case CSR_PSKEY_MODULE_SECURITY_CODE: + return "Module security code"; + case CSR_PSKEY_VM_DISABLE: + return "VM disable"; + case CSR_PSKEY_MOD_MANUF0: + return "Module manufactuer data 0"; + case CSR_PSKEY_MOD_MANUF1: + return "Module manufactuer data 1"; + case CSR_PSKEY_MOD_MANUF2: + return "Module manufactuer data 2"; + case CSR_PSKEY_MOD_MANUF3: + return "Module manufactuer data 3"; + case CSR_PSKEY_MOD_MANUF4: + return "Module manufactuer data 4"; + case CSR_PSKEY_MOD_MANUF5: + return "Module manufactuer data 5"; + case CSR_PSKEY_MOD_MANUF6: + return "Module manufactuer data 6"; + case CSR_PSKEY_MOD_MANUF7: + return "Module manufactuer data 7"; + case CSR_PSKEY_MOD_MANUF8: + return "Module manufactuer data 8"; + case CSR_PSKEY_MOD_MANUF9: + return "Module manufactuer data 9"; + case CSR_PSKEY_DUT_VM_DISABLE: + return "VM disable when entering radiotest modes"; + case CSR_PSKEY_USR0: + return "User configuration data 0"; + case CSR_PSKEY_USR1: + return "User configuration data 1"; + case CSR_PSKEY_USR2: + return "User configuration data 2"; + case CSR_PSKEY_USR3: + return "User configuration data 3"; + case CSR_PSKEY_USR4: + return "User configuration data 4"; + case CSR_PSKEY_USR5: + return "User configuration data 5"; + case CSR_PSKEY_USR6: + return "User configuration data 6"; + case CSR_PSKEY_USR7: + return "User configuration data 7"; + case CSR_PSKEY_USR8: + return "User configuration data 8"; + case CSR_PSKEY_USR9: + return "User configuration data 9"; + case CSR_PSKEY_USR10: + return "User configuration data 10"; + case CSR_PSKEY_USR11: + return "User configuration data 11"; + case CSR_PSKEY_USR12: + return "User configuration data 12"; + case CSR_PSKEY_USR13: + return "User configuration data 13"; + case CSR_PSKEY_USR14: + return "User configuration data 14"; + case CSR_PSKEY_USR15: + return "User configuration data 15"; + case CSR_PSKEY_USR16: + return "User configuration data 16"; + case CSR_PSKEY_USR17: + return "User configuration data 17"; + case CSR_PSKEY_USR18: + return "User configuration data 18"; + case CSR_PSKEY_USR19: + return "User configuration data 19"; + case CSR_PSKEY_USR20: + return "User configuration data 20"; + case CSR_PSKEY_USR21: + return "User configuration data 21"; + case CSR_PSKEY_USR22: + return "User configuration data 22"; + case CSR_PSKEY_USR23: + return "User configuration data 23"; + case CSR_PSKEY_USR24: + return "User configuration data 24"; + case CSR_PSKEY_USR25: + return "User configuration data 25"; + case CSR_PSKEY_USR26: + return "User configuration data 26"; + case CSR_PSKEY_USR27: + return "User configuration data 27"; + case CSR_PSKEY_USR28: + return "User configuration data 28"; + case CSR_PSKEY_USR29: + return "User configuration data 29"; + case CSR_PSKEY_USR30: + return "User configuration data 30"; + case CSR_PSKEY_USR31: + return "User configuration data 31"; + case CSR_PSKEY_USR32: + return "User configuration data 32"; + case CSR_PSKEY_USR33: + return "User configuration data 33"; + case CSR_PSKEY_USR34: + return "User configuration data 34"; + case CSR_PSKEY_USR35: + return "User configuration data 35"; + case CSR_PSKEY_USR36: + return "User configuration data 36"; + case CSR_PSKEY_USR37: + return "User configuration data 37"; + case CSR_PSKEY_USR38: + return "User configuration data 38"; + case CSR_PSKEY_USR39: + return "User configuration data 39"; + case CSR_PSKEY_USR40: + return "User configuration data 40"; + case CSR_PSKEY_USR41: + return "User configuration data 41"; + case CSR_PSKEY_USR42: + return "User configuration data 42"; + case CSR_PSKEY_USR43: + return "User configuration data 43"; + case CSR_PSKEY_USR44: + return "User configuration data 44"; + case CSR_PSKEY_USR45: + return "User configuration data 45"; + case CSR_PSKEY_USR46: + return "User configuration data 46"; + case CSR_PSKEY_USR47: + return "User configuration data 47"; + case CSR_PSKEY_USR48: + return "User configuration data 48"; + case CSR_PSKEY_USR49: + return "User configuration data 49"; + case CSR_PSKEY_USB_VERSION: + return "USB specification version number"; + case CSR_PSKEY_USB_DEVICE_CLASS_CODES: + return "USB device class codes"; + case CSR_PSKEY_USB_VENDOR_ID: + return "USB vendor identifier"; + case CSR_PSKEY_USB_PRODUCT_ID: + return "USB product identifier"; + case CSR_PSKEY_USB_MANUF_STRING: + return "USB manufacturer string"; + case CSR_PSKEY_USB_PRODUCT_STRING: + return "USB product string"; + case CSR_PSKEY_USB_SERIAL_NUMBER_STRING: + return "USB serial number string"; + case CSR_PSKEY_USB_CONFIG_STRING: + return "USB configuration string"; + case CSR_PSKEY_USB_ATTRIBUTES: + return "USB attributes bitmap"; + case CSR_PSKEY_USB_MAX_POWER: + return "USB device maximum power consumption"; + case CSR_PSKEY_USB_BT_IF_CLASS_CODES: + return "USB Bluetooth interface class codes"; + case CSR_PSKEY_USB_LANGID: + return "USB language strings supported"; + case CSR_PSKEY_USB_DFU_CLASS_CODES: + return "USB DFU class codes block"; + case CSR_PSKEY_USB_DFU_PRODUCT_ID: + return "USB DFU product ID"; + case CSR_PSKEY_USB_PIO_DETACH: + return "USB detach/attach PIO line"; + case CSR_PSKEY_USB_PIO_WAKEUP: + return "USB wakeup PIO line"; + case CSR_PSKEY_USB_PIO_PULLUP: + return "USB D+ pullup PIO line"; + case CSR_PSKEY_USB_PIO_VBUS: + return "USB VBus detection PIO Line"; + case CSR_PSKEY_USB_PIO_WAKE_TIMEOUT: + return "Timeout for assertion of USB PIO wake signal"; + case CSR_PSKEY_USB_PIO_RESUME: + return "PIO signal used in place of bus resume"; + case CSR_PSKEY_USB_BT_SCO_IF_CLASS_CODES: + return "USB Bluetooth SCO interface class codes"; + case CSR_PSKEY_USB_SUSPEND_PIO_LEVEL: + return "USB PIO levels to set when suspended"; + case CSR_PSKEY_USB_SUSPEND_PIO_DIR: + return "USB PIO I/O directions to set when suspended"; + case CSR_PSKEY_USB_SUSPEND_PIO_MASK: + return "USB PIO lines to be set forcibly in suspend"; + case CSR_PSKEY_USB_ENDPOINT_0_MAX_PACKET_SIZE: + return "The maxmimum packet size for USB endpoint 0"; + case CSR_PSKEY_USB_CONFIG: + return "USB config params for new chips (>bc2)"; + case CSR_PSKEY_RADIOTEST_ATTEN_INIT: + return "Radio test initial attenuator"; + case CSR_PSKEY_RADIOTEST_FIRST_TRIM_TIME: + return "IQ first calibration period in test"; + case CSR_PSKEY_RADIOTEST_SUBSEQUENT_TRIM_TIME: + return "IQ subsequent calibration period in test"; + case CSR_PSKEY_RADIOTEST_LO_LVL_TRIM_ENABLE: + return "LO_LVL calibration enable"; + case CSR_PSKEY_RADIOTEST_DISABLE_MODULATION: + return "Disable modulation during radiotest transmissions"; + case CSR_PSKEY_RFCOMM_FCON_THRESHOLD: + return "RFCOMM aggregate flow control on threshold"; + case CSR_PSKEY_RFCOMM_FCOFF_THRESHOLD: + return "RFCOMM aggregate flow control off threshold"; + case CSR_PSKEY_IPV6_STATIC_ADDR: + return "Static IPv6 address"; + case CSR_PSKEY_IPV4_STATIC_ADDR: + return "Static IPv4 address"; + case CSR_PSKEY_IPV6_STATIC_PREFIX_LEN: + return "Static IPv6 prefix length"; + case CSR_PSKEY_IPV6_STATIC_ROUTER_ADDR: + return "Static IPv6 router address"; + case CSR_PSKEY_IPV4_STATIC_SUBNET_MASK: + return "Static IPv4 subnet mask"; + case CSR_PSKEY_IPV4_STATIC_ROUTER_ADDR: + return "Static IPv4 router address"; + case CSR_PSKEY_MDNS_NAME: + return "Multicast DNS name"; + case CSR_PSKEY_FIXED_PIN: + return "Fixed PIN"; + case CSR_PSKEY_MDNS_PORT: + return "Multicast DNS port"; + case CSR_PSKEY_MDNS_TTL: + return "Multicast DNS TTL"; + case CSR_PSKEY_MDNS_IPV4_ADDR: + return "Multicast DNS IPv4 address"; + case CSR_PSKEY_ARP_CACHE_TIMEOUT: + return "ARP cache timeout"; + case CSR_PSKEY_HFP_POWER_TABLE: + return "HFP power table"; + case CSR_PSKEY_DRAIN_BORE_TIMER_COUNTERS: + return "Energy consumption estimation timer counters"; + case CSR_PSKEY_DRAIN_BORE_COUNTERS: + return "Energy consumption estimation counters"; + case CSR_PSKEY_LOOP_FILTER_TRIM: + return "Trim value to optimise loop filter"; + case CSR_PSKEY_DRAIN_BORE_CURRENT_PEAK: + return "Energy consumption estimation current peak"; + case CSR_PSKEY_VM_E2_CACHE_LIMIT: + return "Maximum RAM for caching EEPROM VM application"; + case CSR_PSKEY_FORCE_16MHZ_REF_PIO: + return "PIO line to force 16 MHz reference to be assumed"; + case CSR_PSKEY_CDMA_LO_REF_LIMITS: + return "Local oscillator frequency reference limits for CDMA"; + case CSR_PSKEY_CDMA_LO_ERROR_LIMITS: + return "Local oscillator frequency error limits for CDMA"; + case CSR_PSKEY_CLOCK_STARTUP_DELAY: + return "Clock startup delay in milliseconds"; + case CSR_PSKEY_DEEP_SLEEP_CORRECTION_FACTOR: + return "Deep sleep clock correction factor"; + case CSR_PSKEY_TEMPERATURE_CALIBRATION: + return "Temperature in deg C for a given internal setting"; + case CSR_PSKEY_TEMPERATURE_VS_DELTA_INTERNAL_PA: + return "Temperature for given internal PA adjustment"; + case CSR_PSKEY_TEMPERATURE_VS_DELTA_TX_PRE_LVL: + return "Temperature for a given TX_PRE_LVL adjustment"; + case CSR_PSKEY_TEMPERATURE_VS_DELTA_TX_BB: + return "Temperature for a given TX_BB adjustment"; + case CSR_PSKEY_TEMPERATURE_VS_DELTA_ANA_FTRIM: + return "Temperature for given crystal trim adjustment"; + case CSR_PSKEY_TEST_DELTA_OFFSET: + return "Frequency offset applied to synthesiser in test mode"; + case CSR_PSKEY_RX_DYNAMIC_LVL_OFFSET: + return "Receiver dynamic level offset depending on channel"; + case CSR_PSKEY_TEST_FORCE_OFFSET: + return "Force use of exact value in PSKEY_TEST_DELTA_OFFSET"; + case CSR_PSKEY_RF_TRAP_BAD_DIVISION_RATIOS: + return "Trap bad division ratios in radio frequency tables"; + case CSR_PSKEY_RADIOTEST_CDMA_LO_REF_LIMITS: + return "LO frequency reference limits for CDMA in radiotest"; + case CSR_PSKEY_INITIAL_BOOTMODE: + return "Initial device bootmode"; + case CSR_PSKEY_ONCHIP_HCI_CLIENT: + return "HCI traffic routed internally"; + case CSR_PSKEY_RX_ATTEN_BACKOFF: + return "Receiver attenuation back-off"; + case CSR_PSKEY_RX_ATTEN_UPDATE_RATE: + return "Receiver attenuation update rate"; + case CSR_PSKEY_SYNTH_TXRX_THRESHOLDS: + return "Local oscillator tuning voltage limits for tx and rx"; + case CSR_PSKEY_MIN_WAIT_STATES: + return "Flash wait state indicator"; + case CSR_PSKEY_RSSI_CORRECTION: + return "RSSI correction factor."; + case CSR_PSKEY_SCHED_THROTTLE_TIMEOUT: + return "Scheduler performance control."; + case CSR_PSKEY_DEEP_SLEEP_USE_EXTERNAL_CLOCK: + return "Deep sleep uses external 32 kHz clock source"; + case CSR_PSKEY_TRIM_RADIO_FILTERS: + return "Trim rx and tx radio filters if true."; + case CSR_PSKEY_TRANSMIT_OFFSET: + return "Transmit offset in units of 62.5 kHz"; + case CSR_PSKEY_USB_VM_CONTROL: + return "VM application will supply USB descriptors"; + case CSR_PSKEY_MR_ANA_RX_FTRIM: + return "Medium rate value for the ANA_RX_FTRIM register"; + case CSR_PSKEY_I2C_CONFIG: + return "I2C configuration"; + case CSR_PSKEY_IQ_LVL_RX: + return "IQ demand level for reception"; + case CSR_PSKEY_MR_TX_FILTER_CONFIG: + return "TX filter configuration used for enhanced data rate"; + case CSR_PSKEY_MR_TX_CONFIG2: + return "TX filter configuration used for enhanced data rate"; + case CSR_PSKEY_USB_DONT_RESET_BOOTMODE_ON_HOST_RESET: + return "Don't reset bootmode if USB host resets"; + case CSR_PSKEY_LC_USE_THROTTLING: + return "Adjust packet selection on packet error rate"; + case CSR_PSKEY_CHARGER_TRIM: + return "Trim value for the current charger"; + case CSR_PSKEY_CLOCK_REQUEST_FEATURES: + return "Clock request is tristated if enabled"; + case CSR_PSKEY_TRANSMIT_OFFSET_CLASS1: + return "Transmit offset / 62.5 kHz for class 1 radios"; + case CSR_PSKEY_TX_AVOID_PA_CLASS1_PIO: + return "PIO line asserted in class1 operation to avoid PA"; + case CSR_PSKEY_MR_PIO_CONFIG: + return "PIO line asserted in class1 operation to avoid PA"; + case CSR_PSKEY_UART_CONFIG2: + return "The UART Sampling point"; + case CSR_PSKEY_CLASS1_IQ_LVL: + return "IQ demand level for class 1 power level"; + case CSR_PSKEY_CLASS1_TX_CONFIG2: + return "TX filter configuration used for class 1 tx power"; + case CSR_PSKEY_TEMPERATURE_VS_DELTA_INTERNAL_PA_CLASS1: + return "Temperature for given internal PA adjustment"; + case CSR_PSKEY_TEMPERATURE_VS_DELTA_EXTERNAL_PA_CLASS1: + return "Temperature for given internal PA adjustment"; + case CSR_PSKEY_TEMPERATURE_VS_DELTA_TX_PRE_LVL_MR: + return "Temperature adjustment for TX_PRE_LVL in EDR"; + case CSR_PSKEY_TEMPERATURE_VS_DELTA_TX_BB_MR_HEADER: + return "Temperature for a given TX_BB in EDR header"; + case CSR_PSKEY_TEMPERATURE_VS_DELTA_TX_BB_MR_PAYLOAD: + return "Temperature for a given TX_BB in EDR payload"; + case CSR_PSKEY_RX_MR_EQ_TAPS: + return "Adjust receiver configuration for EDR"; + case CSR_PSKEY_TX_PRE_LVL_CLASS1: + return "TX pre-amplifier level in class 1 operation"; + case CSR_PSKEY_ANALOGUE_ATTENUATOR: + return "TX analogue attenuator setting"; + case CSR_PSKEY_MR_RX_FILTER_TRIM: + return "Trim for receiver used in EDR."; + case CSR_PSKEY_MR_RX_FILTER_RESPONSE: + return "Filter response for receiver used in EDR."; + case CSR_PSKEY_PIO_WAKEUP_STATE: + return "PIO deep sleep wake up state "; + case CSR_PSKEY_MR_TX_IF_ATTEN_OFF_TEMP: + return "TX IF atten off temperature when using EDR."; + case CSR_PSKEY_LO_DIV_LATCH_BYPASS: + return "Bypass latch for LO dividers"; + case CSR_PSKEY_LO_VCO_STANDBY: + return "Use standby mode for the LO VCO"; + case CSR_PSKEY_SLOW_CLOCK_FILTER_SHIFT: + return "Slow clock sampling filter constant"; + case CSR_PSKEY_SLOW_CLOCK_FILTER_DIVIDER: + return "Slow clock filter fractional threshold"; + case CSR_PSKEY_USB_ATTRIBUTES_POWER: + return "USB self powered"; + case CSR_PSKEY_USB_ATTRIBUTES_WAKEUP: + return "USB responds to wake-up"; + case CSR_PSKEY_DFU_ATTRIBUTES_MANIFESTATION_TOLERANT: + return "DFU manifestation tolerant"; + case CSR_PSKEY_DFU_ATTRIBUTES_CAN_UPLOAD: + return "DFU can upload"; + case CSR_PSKEY_DFU_ATTRIBUTES_CAN_DOWNLOAD: + return "DFU can download"; + case CSR_PSKEY_UART_CONFIG_STOP_BITS: + return "UART: stop bits"; + case CSR_PSKEY_UART_CONFIG_PARITY_BIT: + return "UART: parity bit"; + case CSR_PSKEY_UART_CONFIG_FLOW_CTRL_EN: + return "UART: hardware flow control"; + case CSR_PSKEY_UART_CONFIG_RTS_AUTO_EN: + return "UART: RTS auto-enabled"; + case CSR_PSKEY_UART_CONFIG_RTS: + return "UART: RTS asserted"; + case CSR_PSKEY_UART_CONFIG_TX_ZERO_EN: + return "UART: TX zero enable"; + case CSR_PSKEY_UART_CONFIG_NON_BCSP_EN: + return "UART: enable BCSP-specific hardware"; + case CSR_PSKEY_UART_CONFIG_RX_RATE_DELAY: + return "UART: RX rate delay"; + case CSR_PSKEY_UART_SEQ_TIMEOUT: + return "UART: BCSP ack timeout"; + case CSR_PSKEY_UART_SEQ_RETRIES: + return "UART: retry limit in sequencing layer"; + case CSR_PSKEY_UART_SEQ_WINSIZE: + return "UART: BCSP transmit window size"; + case CSR_PSKEY_UART_USE_CRC_ON_TX: + return "UART: use BCSP CRCs"; + case CSR_PSKEY_UART_HOST_INITIAL_STATE: + return "UART: initial host state"; + case CSR_PSKEY_UART_HOST_ATTENTION_SPAN: + return "UART: host attention span"; + case CSR_PSKEY_UART_HOST_WAKEUP_TIME: + return "UART: host wakeup time"; + case CSR_PSKEY_UART_HOST_WAKEUP_WAIT: + return "UART: host wakeup wait"; + case CSR_PSKEY_BCSP_LM_MODE: + return "BCSP link establishment mode"; + case CSR_PSKEY_BCSP_LM_SYNC_RETRIES: + return "BCSP link establishment sync retries"; + case CSR_PSKEY_BCSP_LM_TSHY: + return "BCSP link establishment Tshy"; + case CSR_PSKEY_UART_DFU_CONFIG_STOP_BITS: + return "DFU mode UART: stop bits"; + case CSR_PSKEY_UART_DFU_CONFIG_PARITY_BIT: + return "DFU mode UART: parity bit"; + case CSR_PSKEY_UART_DFU_CONFIG_FLOW_CTRL_EN: + return "DFU mode UART: hardware flow control"; + case CSR_PSKEY_UART_DFU_CONFIG_RTS_AUTO_EN: + return "DFU mode UART: RTS auto-enabled"; + case CSR_PSKEY_UART_DFU_CONFIG_RTS: + return "DFU mode UART: RTS asserted"; + case CSR_PSKEY_UART_DFU_CONFIG_TX_ZERO_EN: + return "DFU mode UART: TX zero enable"; + case CSR_PSKEY_UART_DFU_CONFIG_NON_BCSP_EN: + return "DFU mode UART: enable BCSP-specific hardware"; + case CSR_PSKEY_UART_DFU_CONFIG_RX_RATE_DELAY: + return "DFU mode UART: RX rate delay"; + case CSR_PSKEY_AMUX_AIO0: + return "Multiplexer for AIO 0"; + case CSR_PSKEY_AMUX_AIO1: + return "Multiplexer for AIO 1"; + case CSR_PSKEY_AMUX_AIO2: + return "Multiplexer for AIO 2"; + case CSR_PSKEY_AMUX_AIO3: + return "Multiplexer for AIO 3"; + case CSR_PSKEY_LOCAL_NAME_SIMPLIFIED: + return "Local Name (simplified)"; + case CSR_PSKEY_EXTENDED_STUB: + return "Extended stub"; + default: + return "Unknown"; + } +} + +char *csr_pskeytoval(uint16_t pskey) +{ + switch (pskey) { + case CSR_PSKEY_BDADDR: + return "BDADDR"; + case CSR_PSKEY_COUNTRYCODE: + return "COUNTRYCODE"; + case CSR_PSKEY_CLASSOFDEVICE: + return "CLASSOFDEVICE"; + case CSR_PSKEY_DEVICE_DRIFT: + return "DEVICE_DRIFT"; + case CSR_PSKEY_DEVICE_JITTER: + return "DEVICE_JITTER"; + case CSR_PSKEY_MAX_ACLS: + return "MAX_ACLS"; + case CSR_PSKEY_MAX_SCOS: + return "MAX_SCOS"; + case CSR_PSKEY_MAX_REMOTE_MASTERS: + return "MAX_REMOTE_MASTERS"; + case CSR_PSKEY_ENABLE_MASTERY_WITH_SLAVERY: + return "ENABLE_MASTERY_WITH_SLAVERY"; + case CSR_PSKEY_H_HC_FC_MAX_ACL_PKT_LEN: + return "H_HC_FC_MAX_ACL_PKT_LEN"; + case CSR_PSKEY_H_HC_FC_MAX_SCO_PKT_LEN: + return "H_HC_FC_MAX_SCO_PKT_LEN"; + case CSR_PSKEY_H_HC_FC_MAX_ACL_PKTS: + return "H_HC_FC_MAX_ACL_PKTS"; + case CSR_PSKEY_H_HC_FC_MAX_SCO_PKTS: + return "H_HC_FC_MAX_SCO_PKTS"; + case CSR_PSKEY_LC_FC_BUFFER_LOW_WATER_MARK: + return "LC_FC_BUFFER_LOW_WATER_MARK"; + case CSR_PSKEY_LC_MAX_TX_POWER: + return "LC_MAX_TX_POWER"; + case CSR_PSKEY_TX_GAIN_RAMP: + return "TX_GAIN_RAMP"; + case CSR_PSKEY_LC_POWER_TABLE: + return "LC_POWER_TABLE"; + case CSR_PSKEY_LC_PEER_POWER_PERIOD: + return "LC_PEER_POWER_PERIOD"; + case CSR_PSKEY_LC_FC_POOLS_LOW_WATER_MARK: + return "LC_FC_POOLS_LOW_WATER_MARK"; + case CSR_PSKEY_LC_DEFAULT_TX_POWER: + return "LC_DEFAULT_TX_POWER"; + case CSR_PSKEY_LC_RSSI_GOLDEN_RANGE: + return "LC_RSSI_GOLDEN_RANGE"; + case CSR_PSKEY_LC_COMBO_DISABLE_PIO_MASK: + return "LC_COMBO_DISABLE_PIO_MASK"; + case CSR_PSKEY_LC_COMBO_PRIORITY_PIO_MASK: + return "LC_COMBO_PRIORITY_PIO_MASK"; + case CSR_PSKEY_LC_COMBO_DOT11_CHANNEL_PIO_BASE: + return "LC_COMBO_DOT11_CHANNEL_PIO_BASE"; + case CSR_PSKEY_LC_COMBO_DOT11_BLOCK_CHANNELS: + return "LC_COMBO_DOT11_BLOCK_CHANNELS"; + case CSR_PSKEY_LC_MAX_TX_POWER_NO_RSSI: + return "LC_MAX_TX_POWER_NO_RSSI"; + case CSR_PSKEY_LC_CONNECTION_RX_WINDOW: + return "LC_CONNECTION_RX_WINDOW"; + case CSR_PSKEY_LC_COMBO_DOT11_TX_PROTECTION_MODE: + return "LC_COMBO_DOT11_TX_PROTECTION_MODE"; + case CSR_PSKEY_LC_ENHANCED_POWER_TABLE: + return "LC_ENHANCED_POWER_TABLE"; + case CSR_PSKEY_LC_WIDEBAND_RSSI_CONFIG: + return "LC_WIDEBAND_RSSI_CONFIG"; + case CSR_PSKEY_LC_COMBO_DOT11_PRIORITY_LEAD: + return "LC_COMBO_DOT11_PRIORITY_LEAD"; + case CSR_PSKEY_BT_CLOCK_INIT: + return "BT_CLOCK_INIT"; + case CSR_PSKEY_TX_MR_MOD_DELAY: + return "TX_MR_MOD_DELAY"; + case CSR_PSKEY_RX_MR_SYNC_TIMING: + return "RX_MR_SYNC_TIMING"; + case CSR_PSKEY_RX_MR_SYNC_CONFIG: + return "RX_MR_SYNC_CONFIG"; + case CSR_PSKEY_LC_LOST_SYNC_SLOTS: + return "LC_LOST_SYNC_SLOTS"; + case CSR_PSKEY_RX_MR_SAMP_CONFIG: + return "RX_MR_SAMP_CONFIG"; + case CSR_PSKEY_AGC_HYST_LEVELS: + return "AGC_HYST_LEVELS"; + case CSR_PSKEY_RX_LEVEL_LOW_SIGNAL: + return "RX_LEVEL_LOW_SIGNAL"; + case CSR_PSKEY_AGC_IQ_LVL_VALUES: + return "AGC_IQ_LVL_VALUES"; + case CSR_PSKEY_MR_FTRIM_OFFSET_12DB: + return "MR_FTRIM_OFFSET_12DB"; + case CSR_PSKEY_MR_FTRIM_OFFSET_6DB: + return "MR_FTRIM_OFFSET_6DB"; + case CSR_PSKEY_NO_CAL_ON_BOOT: + return "NO_CAL_ON_BOOT"; + case CSR_PSKEY_RSSI_HI_TARGET: + return "RSSI_HI_TARGET"; + case CSR_PSKEY_PREFERRED_MIN_ATTENUATION: + return "PREFERRED_MIN_ATTENUATION"; + case CSR_PSKEY_LC_COMBO_DOT11_PRIORITY_OVERRIDE: + return "LC_COMBO_DOT11_PRIORITY_OVERRIDE"; + case CSR_PSKEY_LC_MULTISLOT_HOLDOFF: + return "LC_MULTISLOT_HOLDOFF"; + case CSR_PSKEY_FREE_KEY_PIGEON_HOLE: + return "FREE_KEY_PIGEON_HOLE"; + case CSR_PSKEY_LINK_KEY_BD_ADDR0: + return "LINK_KEY_BD_ADDR0"; + case CSR_PSKEY_LINK_KEY_BD_ADDR1: + return "LINK_KEY_BD_ADDR1"; + case CSR_PSKEY_LINK_KEY_BD_ADDR2: + return "LINK_KEY_BD_ADDR2"; + case CSR_PSKEY_LINK_KEY_BD_ADDR3: + return "LINK_KEY_BD_ADDR3"; + case CSR_PSKEY_LINK_KEY_BD_ADDR4: + return "LINK_KEY_BD_ADDR4"; + case CSR_PSKEY_LINK_KEY_BD_ADDR5: + return "LINK_KEY_BD_ADDR5"; + case CSR_PSKEY_LINK_KEY_BD_ADDR6: + return "LINK_KEY_BD_ADDR6"; + case CSR_PSKEY_LINK_KEY_BD_ADDR7: + return "LINK_KEY_BD_ADDR7"; + case CSR_PSKEY_LINK_KEY_BD_ADDR8: + return "LINK_KEY_BD_ADDR8"; + case CSR_PSKEY_LINK_KEY_BD_ADDR9: + return "LINK_KEY_BD_ADDR9"; + case CSR_PSKEY_LINK_KEY_BD_ADDR10: + return "LINK_KEY_BD_ADDR10"; + case CSR_PSKEY_LINK_KEY_BD_ADDR11: + return "LINK_KEY_BD_ADDR11"; + case CSR_PSKEY_LINK_KEY_BD_ADDR12: + return "LINK_KEY_BD_ADDR12"; + case CSR_PSKEY_LINK_KEY_BD_ADDR13: + return "LINK_KEY_BD_ADDR13"; + case CSR_PSKEY_LINK_KEY_BD_ADDR14: + return "LINK_KEY_BD_ADDR14"; + case CSR_PSKEY_LINK_KEY_BD_ADDR15: + return "LINK_KEY_BD_ADDR15"; + case CSR_PSKEY_ENC_KEY_LMIN: + return "ENC_KEY_LMIN"; + case CSR_PSKEY_ENC_KEY_LMAX: + return "ENC_KEY_LMAX"; + case CSR_PSKEY_LOCAL_SUPPORTED_FEATURES: + return "LOCAL_SUPPORTED_FEATURES"; + case CSR_PSKEY_LM_USE_UNIT_KEY: + return "LM_USE_UNIT_KEY"; + case CSR_PSKEY_HCI_NOP_DISABLE: + return "HCI_NOP_DISABLE"; + case CSR_PSKEY_LM_MAX_EVENT_FILTERS: + return "LM_MAX_EVENT_FILTERS"; + case CSR_PSKEY_LM_USE_ENC_MODE_BROADCAST: + return "LM_USE_ENC_MODE_BROADCAST"; + case CSR_PSKEY_LM_TEST_SEND_ACCEPTED_TWICE: + return "LM_TEST_SEND_ACCEPTED_TWICE"; + case CSR_PSKEY_LM_MAX_PAGE_HOLD_TIME: + return "LM_MAX_PAGE_HOLD_TIME"; + case CSR_PSKEY_AFH_ADAPTATION_RESPONSE_TIME: + return "AFH_ADAPTATION_RESPONSE_TIME"; + case CSR_PSKEY_AFH_OPTIONS: + return "AFH_OPTIONS"; + case CSR_PSKEY_AFH_RSSI_RUN_PERIOD: + return "AFH_RSSI_RUN_PERIOD"; + case CSR_PSKEY_AFH_REENABLE_CHANNEL_TIME: + return "AFH_REENABLE_CHANNEL_TIME"; + case CSR_PSKEY_NO_DROP_ON_ACR_MS_FAIL: + return "NO_DROP_ON_ACR_MS_FAIL"; + case CSR_PSKEY_MAX_PRIVATE_KEYS: + return "MAX_PRIVATE_KEYS"; + case CSR_PSKEY_PRIVATE_LINK_KEY_BD_ADDR0: + return "PRIVATE_LINK_KEY_BD_ADDR0"; + case CSR_PSKEY_PRIVATE_LINK_KEY_BD_ADDR1: + return "PRIVATE_LINK_KEY_BD_ADDR1"; + case CSR_PSKEY_PRIVATE_LINK_KEY_BD_ADDR2: + return "PRIVATE_LINK_KEY_BD_ADDR2"; + case CSR_PSKEY_PRIVATE_LINK_KEY_BD_ADDR3: + return "PRIVATE_LINK_KEY_BD_ADDR3"; + case CSR_PSKEY_PRIVATE_LINK_KEY_BD_ADDR4: + return "PRIVATE_LINK_KEY_BD_ADDR4"; + case CSR_PSKEY_PRIVATE_LINK_KEY_BD_ADDR5: + return "PRIVATE_LINK_KEY_BD_ADDR5"; + case CSR_PSKEY_PRIVATE_LINK_KEY_BD_ADDR6: + return "PRIVATE_LINK_KEY_BD_ADDR6"; + case CSR_PSKEY_PRIVATE_LINK_KEY_BD_ADDR7: + return "PRIVATE_LINK_KEY_BD_ADDR7"; + case CSR_PSKEY_LOCAL_SUPPORTED_COMMANDS: + return "LOCAL_SUPPORTED_COMMANDS"; + case CSR_PSKEY_LM_MAX_ABSENCE_INDEX: + return "LM_MAX_ABSENCE_INDEX"; + case CSR_PSKEY_DEVICE_NAME: + return "DEVICE_NAME"; + case CSR_PSKEY_AFH_RSSI_THRESHOLD: + return "AFH_RSSI_THRESHOLD"; + case CSR_PSKEY_LM_CASUAL_SCAN_INTERVAL: + return "LM_CASUAL_SCAN_INTERVAL"; + case CSR_PSKEY_AFH_MIN_MAP_CHANGE: + return "AFH_MIN_MAP_CHANGE"; + case CSR_PSKEY_AFH_RSSI_LP_RUN_PERIOD: + return "AFH_RSSI_LP_RUN_PERIOD"; + case CSR_PSKEY_HCI_LMP_LOCAL_VERSION: + return "HCI_LMP_LOCAL_VERSION"; + case CSR_PSKEY_LMP_REMOTE_VERSION: + return "LMP_REMOTE_VERSION"; + case CSR_PSKEY_HOLD_ERROR_MESSAGE_NUMBER: + return "HOLD_ERROR_MESSAGE_NUMBER"; + case CSR_PSKEY_DFU_ATTRIBUTES: + return "DFU_ATTRIBUTES"; + case CSR_PSKEY_DFU_DETACH_TO: + return "DFU_DETACH_TO"; + case CSR_PSKEY_DFU_TRANSFER_SIZE: + return "DFU_TRANSFER_SIZE"; + case CSR_PSKEY_DFU_ENABLE: + return "DFU_ENABLE"; + case CSR_PSKEY_DFU_LIN_REG_ENABLE: + return "DFU_LIN_REG_ENABLE"; + case CSR_PSKEY_DFUENC_VMAPP_PK_MODULUS_MSB: + return "DFUENC_VMAPP_PK_MODULUS_MSB"; + case CSR_PSKEY_DFUENC_VMAPP_PK_MODULUS_LSB: + return "DFUENC_VMAPP_PK_MODULUS_LSB"; + case CSR_PSKEY_DFUENC_VMAPP_PK_M_DASH: + return "DFUENC_VMAPP_PK_M_DASH"; + case CSR_PSKEY_DFUENC_VMAPP_PK_R2N_MSB: + return "DFUENC_VMAPP_PK_R2N_MSB"; + case CSR_PSKEY_DFUENC_VMAPP_PK_R2N_LSB: + return "DFUENC_VMAPP_PK_R2N_LSB"; + case CSR_PSKEY_BCSP_LM_PS_BLOCK: + return "BCSP_LM_PS_BLOCK"; + case CSR_PSKEY_HOSTIO_FC_PS_BLOCK: + return "HOSTIO_FC_PS_BLOCK"; + case CSR_PSKEY_HOSTIO_PROTOCOL_INFO0: + return "HOSTIO_PROTOCOL_INFO0"; + case CSR_PSKEY_HOSTIO_PROTOCOL_INFO1: + return "HOSTIO_PROTOCOL_INFO1"; + case CSR_PSKEY_HOSTIO_PROTOCOL_INFO2: + return "HOSTIO_PROTOCOL_INFO2"; + case CSR_PSKEY_HOSTIO_PROTOCOL_INFO3: + return "HOSTIO_PROTOCOL_INFO3"; + case CSR_PSKEY_HOSTIO_PROTOCOL_INFO4: + return "HOSTIO_PROTOCOL_INFO4"; + case CSR_PSKEY_HOSTIO_PROTOCOL_INFO5: + return "HOSTIO_PROTOCOL_INFO5"; + case CSR_PSKEY_HOSTIO_PROTOCOL_INFO6: + return "HOSTIO_PROTOCOL_INFO6"; + case CSR_PSKEY_HOSTIO_PROTOCOL_INFO7: + return "HOSTIO_PROTOCOL_INFO7"; + case CSR_PSKEY_HOSTIO_PROTOCOL_INFO8: + return "HOSTIO_PROTOCOL_INFO8"; + case CSR_PSKEY_HOSTIO_PROTOCOL_INFO9: + return "HOSTIO_PROTOCOL_INFO9"; + case CSR_PSKEY_HOSTIO_PROTOCOL_INFO10: + return "HOSTIO_PROTOCOL_INFO10"; + case CSR_PSKEY_HOSTIO_PROTOCOL_INFO11: + return "HOSTIO_PROTOCOL_INFO11"; + case CSR_PSKEY_HOSTIO_PROTOCOL_INFO12: + return "HOSTIO_PROTOCOL_INFO12"; + case CSR_PSKEY_HOSTIO_PROTOCOL_INFO13: + return "HOSTIO_PROTOCOL_INFO13"; + case CSR_PSKEY_HOSTIO_PROTOCOL_INFO14: + return "HOSTIO_PROTOCOL_INFO14"; + case CSR_PSKEY_HOSTIO_PROTOCOL_INFO15: + return "HOSTIO_PROTOCOL_INFO15"; + case CSR_PSKEY_HOSTIO_UART_RESET_TIMEOUT: + return "HOSTIO_UART_RESET_TIMEOUT"; + case CSR_PSKEY_HOSTIO_USE_HCI_EXTN: + return "HOSTIO_USE_HCI_EXTN"; + case CSR_PSKEY_HOSTIO_USE_HCI_EXTN_CCFC: + return "HOSTIO_USE_HCI_EXTN_CCFC"; + case CSR_PSKEY_HOSTIO_HCI_EXTN_PAYLOAD_SIZE: + return "HOSTIO_HCI_EXTN_PAYLOAD_SIZE"; + case CSR_PSKEY_BCSP_LM_CNF_CNT_LIMIT: + return "BCSP_LM_CNF_CNT_LIMIT"; + case CSR_PSKEY_HOSTIO_MAP_SCO_PCM: + return "HOSTIO_MAP_SCO_PCM"; + case CSR_PSKEY_HOSTIO_AWKWARD_PCM_SYNC: + return "HOSTIO_AWKWARD_PCM_SYNC"; + case CSR_PSKEY_HOSTIO_BREAK_POLL_PERIOD: + return "HOSTIO_BREAK_POLL_PERIOD"; + case CSR_PSKEY_HOSTIO_MIN_UART_HCI_SCO_SIZE: + return "HOSTIO_MIN_UART_HCI_SCO_SIZE"; + case CSR_PSKEY_HOSTIO_MAP_SCO_CODEC: + return "HOSTIO_MAP_SCO_CODEC"; + case CSR_PSKEY_PCM_CVSD_TX_HI_FREQ_BOOST: + return "PCM_CVSD_TX_HI_FREQ_BOOST"; + case CSR_PSKEY_PCM_CVSD_RX_HI_FREQ_BOOST: + return "PCM_CVSD_RX_HI_FREQ_BOOST"; + case CSR_PSKEY_PCM_CONFIG32: + return "PCM_CONFIG32"; + case CSR_PSKEY_USE_OLD_BCSP_LE: + return "USE_OLD_BCSP_LE"; + case CSR_PSKEY_PCM_CVSD_USE_NEW_FILTER: + return "PCM_CVSD_USE_NEW_FILTER"; + case CSR_PSKEY_PCM_FORMAT: + return "PCM_FORMAT"; + case CSR_PSKEY_CODEC_OUT_GAIN: + return "CODEC_OUT_GAIN"; + case CSR_PSKEY_CODEC_IN_GAIN: + return "CODEC_IN_GAIN"; + case CSR_PSKEY_CODEC_PIO: + return "CODEC_PIO"; + case CSR_PSKEY_PCM_LOW_JITTER_CONFIG: + return "PCM_LOW_JITTER_CONFIG"; + case CSR_PSKEY_HOSTIO_SCO_PCM_THRESHOLDS: + return "HOSTIO_SCO_PCM_THRESHOLDS"; + case CSR_PSKEY_HOSTIO_SCO_HCI_THRESHOLDS: + return "HOSTIO_SCO_HCI_THRESHOLDS"; + case CSR_PSKEY_HOSTIO_MAP_SCO_PCM_SLOT: + return "HOSTIO_MAP_SCO_PCM_SLOT"; + case CSR_PSKEY_UART_BAUDRATE: + return "UART_BAUDRATE"; + case CSR_PSKEY_UART_CONFIG_BCSP: + return "UART_CONFIG_BCSP"; + case CSR_PSKEY_UART_CONFIG_H4: + return "UART_CONFIG_H4"; + case CSR_PSKEY_UART_CONFIG_H5: + return "UART_CONFIG_H5"; + case CSR_PSKEY_UART_CONFIG_USR: + return "UART_CONFIG_USR"; + case CSR_PSKEY_UART_TX_CRCS: + return "UART_TX_CRCS"; + case CSR_PSKEY_UART_ACK_TIMEOUT: + return "UART_ACK_TIMEOUT"; + case CSR_PSKEY_UART_TX_MAX_ATTEMPTS: + return "UART_TX_MAX_ATTEMPTS"; + case CSR_PSKEY_UART_TX_WINDOW_SIZE: + return "UART_TX_WINDOW_SIZE"; + case CSR_PSKEY_UART_HOST_WAKE: + return "UART_HOST_WAKE"; + case CSR_PSKEY_HOSTIO_THROTTLE_TIMEOUT: + return "HOSTIO_THROTTLE_TIMEOUT"; + case CSR_PSKEY_PCM_ALWAYS_ENABLE: + return "PCM_ALWAYS_ENABLE"; + case CSR_PSKEY_UART_HOST_WAKE_SIGNAL: + return "UART_HOST_WAKE_SIGNAL"; + case CSR_PSKEY_UART_CONFIG_H4DS: + return "UART_CONFIG_H4DS"; + case CSR_PSKEY_H4DS_WAKE_DURATION: + return "H4DS_WAKE_DURATION"; + case CSR_PSKEY_H4DS_MAXWU: + return "H4DS_MAXWU"; + case CSR_PSKEY_H4DS_LE_TIMER_PERIOD: + return "H4DS_LE_TIMER_PERIOD"; + case CSR_PSKEY_H4DS_TWU_TIMER_PERIOD: + return "H4DS_TWU_TIMER_PERIOD"; + case CSR_PSKEY_H4DS_UART_IDLE_TIMER_PERIOD: + return "H4DS_UART_IDLE_TIMER_PERIOD"; + case CSR_PSKEY_ANA_FTRIM: + return "ANA_FTRIM"; + case CSR_PSKEY_WD_TIMEOUT: + return "WD_TIMEOUT"; + case CSR_PSKEY_WD_PERIOD: + return "WD_PERIOD"; + case CSR_PSKEY_HOST_INTERFACE: + return "HOST_INTERFACE"; + case CSR_PSKEY_HQ_HOST_TIMEOUT: + return "HQ_HOST_TIMEOUT"; + case CSR_PSKEY_HQ_ACTIVE: + return "HQ_ACTIVE"; + case CSR_PSKEY_BCCMD_SECURITY_ACTIVE: + return "BCCMD_SECURITY_ACTIVE"; + case CSR_PSKEY_ANA_FREQ: + return "ANA_FREQ"; + case CSR_PSKEY_PIO_PROTECT_MASK: + return "PIO_PROTECT_MASK"; + case CSR_PSKEY_PMALLOC_SIZES: + return "PMALLOC_SIZES"; + case CSR_PSKEY_UART_BAUD_RATE: + return "UART_BAUD_RATE"; + case CSR_PSKEY_UART_CONFIG: + return "UART_CONFIG"; + case CSR_PSKEY_STUB: + return "STUB"; + case CSR_PSKEY_TXRX_PIO_CONTROL: + return "TXRX_PIO_CONTROL"; + case CSR_PSKEY_ANA_RX_LEVEL: + return "ANA_RX_LEVEL"; + case CSR_PSKEY_ANA_RX_FTRIM: + return "ANA_RX_FTRIM"; + case CSR_PSKEY_PSBC_DATA_VERSION: + return "PSBC_DATA_VERSION"; + case CSR_PSKEY_PCM0_ATTENUATION: + return "PCM0_ATTENUATION"; + case CSR_PSKEY_LO_LVL_MAX: + return "LO_LVL_MAX"; + case CSR_PSKEY_LO_ADC_AMPL_MIN: + return "LO_ADC_AMPL_MIN"; + case CSR_PSKEY_LO_ADC_AMPL_MAX: + return "LO_ADC_AMPL_MAX"; + case CSR_PSKEY_IQ_TRIM_CHANNEL: + return "IQ_TRIM_CHANNEL"; + case CSR_PSKEY_IQ_TRIM_GAIN: + return "IQ_TRIM_GAIN"; + case CSR_PSKEY_IQ_TRIM_ENABLE: + return "IQ_TRIM_ENABLE"; + case CSR_PSKEY_TX_OFFSET_HALF_MHZ: + return "TX_OFFSET_HALF_MHZ"; + case CSR_PSKEY_GBL_MISC_ENABLES: + return "GBL_MISC_ENABLES"; + case CSR_PSKEY_UART_SLEEP_TIMEOUT: + return "UART_SLEEP_TIMEOUT"; + case CSR_PSKEY_DEEP_SLEEP_STATE: + return "DEEP_SLEEP_STATE"; + case CSR_PSKEY_IQ_ENABLE_PHASE_TRIM: + return "IQ_ENABLE_PHASE_TRIM"; + case CSR_PSKEY_HCI_HANDLE_FREEZE_PERIOD: + return "HCI_HANDLE_FREEZE_PERIOD"; + case CSR_PSKEY_MAX_FROZEN_HCI_HANDLES: + return "MAX_FROZEN_HCI_HANDLES"; + case CSR_PSKEY_PAGETABLE_DESTRUCTION_DELAY: + return "PAGETABLE_DESTRUCTION_DELAY"; + case CSR_PSKEY_IQ_TRIM_PIO_SETTINGS: + return "IQ_TRIM_PIO_SETTINGS"; + case CSR_PSKEY_USE_EXTERNAL_CLOCK: + return "USE_EXTERNAL_CLOCK"; + case CSR_PSKEY_DEEP_SLEEP_WAKE_CTS: + return "DEEP_SLEEP_WAKE_CTS"; + case CSR_PSKEY_FC_HC2H_FLUSH_DELAY: + return "FC_HC2H_FLUSH_DELAY"; + case CSR_PSKEY_RX_HIGHSIDE: + return "RX_HIGHSIDE"; + case CSR_PSKEY_TX_PRE_LVL: + return "TX_PRE_LVL"; + case CSR_PSKEY_RX_SINGLE_ENDED: + return "RX_SINGLE_ENDED"; + case CSR_PSKEY_TX_FILTER_CONFIG: + return "TX_FILTER_CONFIG"; + case CSR_PSKEY_CLOCK_REQUEST_ENABLE: + return "CLOCK_REQUEST_ENABLE"; + case CSR_PSKEY_RX_MIN_ATTEN: + return "RX_MIN_ATTEN"; + case CSR_PSKEY_XTAL_TARGET_AMPLITUDE: + return "XTAL_TARGET_AMPLITUDE"; + case CSR_PSKEY_PCM_MIN_CPU_CLOCK: + return "PCM_MIN_CPU_CLOCK"; + case CSR_PSKEY_HOST_INTERFACE_PIO_USB: + return "HOST_INTERFACE_PIO_USB"; + case CSR_PSKEY_CPU_IDLE_MODE: + return "CPU_IDLE_MODE"; + case CSR_PSKEY_DEEP_SLEEP_CLEAR_RTS: + return "DEEP_SLEEP_CLEAR_RTS"; + case CSR_PSKEY_RF_RESONANCE_TRIM: + return "RF_RESONANCE_TRIM"; + case CSR_PSKEY_DEEP_SLEEP_PIO_WAKE: + return "DEEP_SLEEP_PIO_WAKE"; + case CSR_PSKEY_DRAIN_BORE_TIMERS: + return "DRAIN_BORE_TIMERS"; + case CSR_PSKEY_DRAIN_TX_POWER_BASE: + return "DRAIN_TX_POWER_BASE"; + case CSR_PSKEY_MODULE_ID: + return "MODULE_ID"; + case CSR_PSKEY_MODULE_DESIGN: + return "MODULE_DESIGN"; + case CSR_PSKEY_MODULE_SECURITY_CODE: + return "MODULE_SECURITY_CODE"; + case CSR_PSKEY_VM_DISABLE: + return "VM_DISABLE"; + case CSR_PSKEY_MOD_MANUF0: + return "MOD_MANUF0"; + case CSR_PSKEY_MOD_MANUF1: + return "MOD_MANUF1"; + case CSR_PSKEY_MOD_MANUF2: + return "MOD_MANUF2"; + case CSR_PSKEY_MOD_MANUF3: + return "MOD_MANUF3"; + case CSR_PSKEY_MOD_MANUF4: + return "MOD_MANUF4"; + case CSR_PSKEY_MOD_MANUF5: + return "MOD_MANUF5"; + case CSR_PSKEY_MOD_MANUF6: + return "MOD_MANUF6"; + case CSR_PSKEY_MOD_MANUF7: + return "MOD_MANUF7"; + case CSR_PSKEY_MOD_MANUF8: + return "MOD_MANUF8"; + case CSR_PSKEY_MOD_MANUF9: + return "MOD_MANUF9"; + case CSR_PSKEY_DUT_VM_DISABLE: + return "DUT_VM_DISABLE"; + case CSR_PSKEY_USR0: + return "USR0"; + case CSR_PSKEY_USR1: + return "USR1"; + case CSR_PSKEY_USR2: + return "USR2"; + case CSR_PSKEY_USR3: + return "USR3"; + case CSR_PSKEY_USR4: + return "USR4"; + case CSR_PSKEY_USR5: + return "USR5"; + case CSR_PSKEY_USR6: + return "USR6"; + case CSR_PSKEY_USR7: + return "USR7"; + case CSR_PSKEY_USR8: + return "USR8"; + case CSR_PSKEY_USR9: + return "USR9"; + case CSR_PSKEY_USR10: + return "USR10"; + case CSR_PSKEY_USR11: + return "USR11"; + case CSR_PSKEY_USR12: + return "USR12"; + case CSR_PSKEY_USR13: + return "USR13"; + case CSR_PSKEY_USR14: + return "USR14"; + case CSR_PSKEY_USR15: + return "USR15"; + case CSR_PSKEY_USR16: + return "USR16"; + case CSR_PSKEY_USR17: + return "USR17"; + case CSR_PSKEY_USR18: + return "USR18"; + case CSR_PSKEY_USR19: + return "USR19"; + case CSR_PSKEY_USR20: + return "USR20"; + case CSR_PSKEY_USR21: + return "USR21"; + case CSR_PSKEY_USR22: + return "USR22"; + case CSR_PSKEY_USR23: + return "USR23"; + case CSR_PSKEY_USR24: + return "USR24"; + case CSR_PSKEY_USR25: + return "USR25"; + case CSR_PSKEY_USR26: + return "USR26"; + case CSR_PSKEY_USR27: + return "USR27"; + case CSR_PSKEY_USR28: + return "USR28"; + case CSR_PSKEY_USR29: + return "USR29"; + case CSR_PSKEY_USR30: + return "USR30"; + case CSR_PSKEY_USR31: + return "USR31"; + case CSR_PSKEY_USR32: + return "USR32"; + case CSR_PSKEY_USR33: + return "USR33"; + case CSR_PSKEY_USR34: + return "USR34"; + case CSR_PSKEY_USR35: + return "USR35"; + case CSR_PSKEY_USR36: + return "USR36"; + case CSR_PSKEY_USR37: + return "USR37"; + case CSR_PSKEY_USR38: + return "USR38"; + case CSR_PSKEY_USR39: + return "USR39"; + case CSR_PSKEY_USR40: + return "USR40"; + case CSR_PSKEY_USR41: + return "USR41"; + case CSR_PSKEY_USR42: + return "USR42"; + case CSR_PSKEY_USR43: + return "USR43"; + case CSR_PSKEY_USR44: + return "USR44"; + case CSR_PSKEY_USR45: + return "USR45"; + case CSR_PSKEY_USR46: + return "USR46"; + case CSR_PSKEY_USR47: + return "USR47"; + case CSR_PSKEY_USR48: + return "USR48"; + case CSR_PSKEY_USR49: + return "USR49"; + case CSR_PSKEY_USB_VERSION: + return "USB_VERSION"; + case CSR_PSKEY_USB_DEVICE_CLASS_CODES: + return "USB_DEVICE_CLASS_CODES"; + case CSR_PSKEY_USB_VENDOR_ID: + return "USB_VENDOR_ID"; + case CSR_PSKEY_USB_PRODUCT_ID: + return "USB_PRODUCT_ID"; + case CSR_PSKEY_USB_MANUF_STRING: + return "USB_MANUF_STRING"; + case CSR_PSKEY_USB_PRODUCT_STRING: + return "USB_PRODUCT_STRING"; + case CSR_PSKEY_USB_SERIAL_NUMBER_STRING: + return "USB_SERIAL_NUMBER_STRING"; + case CSR_PSKEY_USB_CONFIG_STRING: + return "USB_CONFIG_STRING"; + case CSR_PSKEY_USB_ATTRIBUTES: + return "USB_ATTRIBUTES"; + case CSR_PSKEY_USB_MAX_POWER: + return "USB_MAX_POWER"; + case CSR_PSKEY_USB_BT_IF_CLASS_CODES: + return "USB_BT_IF_CLASS_CODES"; + case CSR_PSKEY_USB_LANGID: + return "USB_LANGID"; + case CSR_PSKEY_USB_DFU_CLASS_CODES: + return "USB_DFU_CLASS_CODES"; + case CSR_PSKEY_USB_DFU_PRODUCT_ID: + return "USB_DFU_PRODUCT_ID"; + case CSR_PSKEY_USB_PIO_DETACH: + return "USB_PIO_DETACH"; + case CSR_PSKEY_USB_PIO_WAKEUP: + return "USB_PIO_WAKEUP"; + case CSR_PSKEY_USB_PIO_PULLUP: + return "USB_PIO_PULLUP"; + case CSR_PSKEY_USB_PIO_VBUS: + return "USB_PIO_VBUS"; + case CSR_PSKEY_USB_PIO_WAKE_TIMEOUT: + return "USB_PIO_WAKE_TIMEOUT"; + case CSR_PSKEY_USB_PIO_RESUME: + return "USB_PIO_RESUME"; + case CSR_PSKEY_USB_BT_SCO_IF_CLASS_CODES: + return "USB_BT_SCO_IF_CLASS_CODES"; + case CSR_PSKEY_USB_SUSPEND_PIO_LEVEL: + return "USB_SUSPEND_PIO_LEVEL"; + case CSR_PSKEY_USB_SUSPEND_PIO_DIR: + return "USB_SUSPEND_PIO_DIR"; + case CSR_PSKEY_USB_SUSPEND_PIO_MASK: + return "USB_SUSPEND_PIO_MASK"; + case CSR_PSKEY_USB_ENDPOINT_0_MAX_PACKET_SIZE: + return "USB_ENDPOINT_0_MAX_PACKET_SIZE"; + case CSR_PSKEY_USB_CONFIG: + return "USB_CONFIG"; + case CSR_PSKEY_RADIOTEST_ATTEN_INIT: + return "RADIOTEST_ATTEN_INIT"; + case CSR_PSKEY_RADIOTEST_FIRST_TRIM_TIME: + return "RADIOTEST_FIRST_TRIM_TIME"; + case CSR_PSKEY_RADIOTEST_SUBSEQUENT_TRIM_TIME: + return "RADIOTEST_SUBSEQUENT_TRIM_TIME"; + case CSR_PSKEY_RADIOTEST_LO_LVL_TRIM_ENABLE: + return "RADIOTEST_LO_LVL_TRIM_ENABLE"; + case CSR_PSKEY_RADIOTEST_DISABLE_MODULATION: + return "RADIOTEST_DISABLE_MODULATION"; + case CSR_PSKEY_RFCOMM_FCON_THRESHOLD: + return "RFCOMM_FCON_THRESHOLD"; + case CSR_PSKEY_RFCOMM_FCOFF_THRESHOLD: + return "RFCOMM_FCOFF_THRESHOLD"; + case CSR_PSKEY_IPV6_STATIC_ADDR: + return "IPV6_STATIC_ADDR"; + case CSR_PSKEY_IPV4_STATIC_ADDR: + return "IPV4_STATIC_ADDR"; + case CSR_PSKEY_IPV6_STATIC_PREFIX_LEN: + return "IPV6_STATIC_PREFIX_LEN"; + case CSR_PSKEY_IPV6_STATIC_ROUTER_ADDR: + return "IPV6_STATIC_ROUTER_ADDR"; + case CSR_PSKEY_IPV4_STATIC_SUBNET_MASK: + return "IPV4_STATIC_SUBNET_MASK"; + case CSR_PSKEY_IPV4_STATIC_ROUTER_ADDR: + return "IPV4_STATIC_ROUTER_ADDR"; + case CSR_PSKEY_MDNS_NAME: + return "MDNS_NAME"; + case CSR_PSKEY_FIXED_PIN: + return "FIXED_PIN"; + case CSR_PSKEY_MDNS_PORT: + return "MDNS_PORT"; + case CSR_PSKEY_MDNS_TTL: + return "MDNS_TTL"; + case CSR_PSKEY_MDNS_IPV4_ADDR: + return "MDNS_IPV4_ADDR"; + case CSR_PSKEY_ARP_CACHE_TIMEOUT: + return "ARP_CACHE_TIMEOUT"; + case CSR_PSKEY_HFP_POWER_TABLE: + return "HFP_POWER_TABLE"; + case CSR_PSKEY_DRAIN_BORE_TIMER_COUNTERS: + return "DRAIN_BORE_TIMER_COUNTERS"; + case CSR_PSKEY_DRAIN_BORE_COUNTERS: + return "DRAIN_BORE_COUNTERS"; + case CSR_PSKEY_LOOP_FILTER_TRIM: + return "LOOP_FILTER_TRIM"; + case CSR_PSKEY_DRAIN_BORE_CURRENT_PEAK: + return "DRAIN_BORE_CURRENT_PEAK"; + case CSR_PSKEY_VM_E2_CACHE_LIMIT: + return "VM_E2_CACHE_LIMIT"; + case CSR_PSKEY_FORCE_16MHZ_REF_PIO: + return "FORCE_16MHZ_REF_PIO"; + case CSR_PSKEY_CDMA_LO_REF_LIMITS: + return "CDMA_LO_REF_LIMITS"; + case CSR_PSKEY_CDMA_LO_ERROR_LIMITS: + return "CDMA_LO_ERROR_LIMITS"; + case CSR_PSKEY_CLOCK_STARTUP_DELAY: + return "CLOCK_STARTUP_DELAY"; + case CSR_PSKEY_DEEP_SLEEP_CORRECTION_FACTOR: + return "DEEP_SLEEP_CORRECTION_FACTOR"; + case CSR_PSKEY_TEMPERATURE_CALIBRATION: + return "TEMPERATURE_CALIBRATION"; + case CSR_PSKEY_TEMPERATURE_VS_DELTA_INTERNAL_PA: + return "TEMPERATURE_VS_DELTA_INTERNAL_PA"; + case CSR_PSKEY_TEMPERATURE_VS_DELTA_TX_PRE_LVL: + return "TEMPERATURE_VS_DELTA_TX_PRE_LVL"; + case CSR_PSKEY_TEMPERATURE_VS_DELTA_TX_BB: + return "TEMPERATURE_VS_DELTA_TX_BB"; + case CSR_PSKEY_TEMPERATURE_VS_DELTA_ANA_FTRIM: + return "TEMPERATURE_VS_DELTA_ANA_FTRIM"; + case CSR_PSKEY_TEST_DELTA_OFFSET: + return "TEST_DELTA_OFFSET"; + case CSR_PSKEY_RX_DYNAMIC_LVL_OFFSET: + return "RX_DYNAMIC_LVL_OFFSET"; + case CSR_PSKEY_TEST_FORCE_OFFSET: + return "TEST_FORCE_OFFSET"; + case CSR_PSKEY_RF_TRAP_BAD_DIVISION_RATIOS: + return "RF_TRAP_BAD_DIVISION_RATIOS"; + case CSR_PSKEY_RADIOTEST_CDMA_LO_REF_LIMITS: + return "RADIOTEST_CDMA_LO_REF_LIMITS"; + case CSR_PSKEY_INITIAL_BOOTMODE: + return "INITIAL_BOOTMODE"; + case CSR_PSKEY_ONCHIP_HCI_CLIENT: + return "ONCHIP_HCI_CLIENT"; + case CSR_PSKEY_RX_ATTEN_BACKOFF: + return "RX_ATTEN_BACKOFF"; + case CSR_PSKEY_RX_ATTEN_UPDATE_RATE: + return "RX_ATTEN_UPDATE_RATE"; + case CSR_PSKEY_SYNTH_TXRX_THRESHOLDS: + return "SYNTH_TXRX_THRESHOLDS"; + case CSR_PSKEY_MIN_WAIT_STATES: + return "MIN_WAIT_STATES"; + case CSR_PSKEY_RSSI_CORRECTION: + return "RSSI_CORRECTION"; + case CSR_PSKEY_SCHED_THROTTLE_TIMEOUT: + return "SCHED_THROTTLE_TIMEOUT"; + case CSR_PSKEY_DEEP_SLEEP_USE_EXTERNAL_CLOCK: + return "DEEP_SLEEP_USE_EXTERNAL_CLOCK"; + case CSR_PSKEY_TRIM_RADIO_FILTERS: + return "TRIM_RADIO_FILTERS"; + case CSR_PSKEY_TRANSMIT_OFFSET: + return "TRANSMIT_OFFSET"; + case CSR_PSKEY_USB_VM_CONTROL: + return "USB_VM_CONTROL"; + case CSR_PSKEY_MR_ANA_RX_FTRIM: + return "MR_ANA_RX_FTRIM"; + case CSR_PSKEY_I2C_CONFIG: + return "I2C_CONFIG"; + case CSR_PSKEY_IQ_LVL_RX: + return "IQ_LVL_RX"; + case CSR_PSKEY_MR_TX_FILTER_CONFIG: + return "MR_TX_FILTER_CONFIG"; + case CSR_PSKEY_MR_TX_CONFIG2: + return "MR_TX_CONFIG2"; + case CSR_PSKEY_USB_DONT_RESET_BOOTMODE_ON_HOST_RESET: + return "USB_DONT_RESET_BOOTMODE_ON_HOST_RESET"; + case CSR_PSKEY_LC_USE_THROTTLING: + return "LC_USE_THROTTLING"; + case CSR_PSKEY_CHARGER_TRIM: + return "CHARGER_TRIM"; + case CSR_PSKEY_CLOCK_REQUEST_FEATURES: + return "CLOCK_REQUEST_FEATURES"; + case CSR_PSKEY_TRANSMIT_OFFSET_CLASS1: + return "TRANSMIT_OFFSET_CLASS1"; + case CSR_PSKEY_TX_AVOID_PA_CLASS1_PIO: + return "TX_AVOID_PA_CLASS1_PIO"; + case CSR_PSKEY_MR_PIO_CONFIG: + return "MR_PIO_CONFIG"; + case CSR_PSKEY_UART_CONFIG2: + return "UART_CONFIG2"; + case CSR_PSKEY_CLASS1_IQ_LVL: + return "CLASS1_IQ_LVL"; + case CSR_PSKEY_CLASS1_TX_CONFIG2: + return "CLASS1_TX_CONFIG2"; + case CSR_PSKEY_TEMPERATURE_VS_DELTA_INTERNAL_PA_CLASS1: + return "TEMPERATURE_VS_DELTA_INTERNAL_PA_CLASS1"; + case CSR_PSKEY_TEMPERATURE_VS_DELTA_EXTERNAL_PA_CLASS1: + return "TEMPERATURE_VS_DELTA_EXTERNAL_PA_CLASS1"; + case CSR_PSKEY_TEMPERATURE_VS_DELTA_TX_PRE_LVL_MR: + return "TEMPERATURE_VS_DELTA_TX_PRE_LVL_MR"; + case CSR_PSKEY_TEMPERATURE_VS_DELTA_TX_BB_MR_HEADER: + return "TEMPERATURE_VS_DELTA_TX_BB_MR_HEADER"; + case CSR_PSKEY_TEMPERATURE_VS_DELTA_TX_BB_MR_PAYLOAD: + return "TEMPERATURE_VS_DELTA_TX_BB_MR_PAYLOAD"; + case CSR_PSKEY_RX_MR_EQ_TAPS: + return "RX_MR_EQ_TAPS"; + case CSR_PSKEY_TX_PRE_LVL_CLASS1: + return "TX_PRE_LVL_CLASS1"; + case CSR_PSKEY_ANALOGUE_ATTENUATOR: + return "ANALOGUE_ATTENUATOR"; + case CSR_PSKEY_MR_RX_FILTER_TRIM: + return "MR_RX_FILTER_TRIM"; + case CSR_PSKEY_MR_RX_FILTER_RESPONSE: + return "MR_RX_FILTER_RESPONSE"; + case CSR_PSKEY_PIO_WAKEUP_STATE: + return "PIO_WAKEUP_STATE"; + case CSR_PSKEY_MR_TX_IF_ATTEN_OFF_TEMP: + return "MR_TX_IF_ATTEN_OFF_TEMP"; + case CSR_PSKEY_LO_DIV_LATCH_BYPASS: + return "LO_DIV_LATCH_BYPASS"; + case CSR_PSKEY_LO_VCO_STANDBY: + return "LO_VCO_STANDBY"; + case CSR_PSKEY_SLOW_CLOCK_FILTER_SHIFT: + return "SLOW_CLOCK_FILTER_SHIFT"; + case CSR_PSKEY_SLOW_CLOCK_FILTER_DIVIDER: + return "SLOW_CLOCK_FILTER_DIVIDER"; + case CSR_PSKEY_USB_ATTRIBUTES_POWER: + return "USB_ATTRIBUTES_POWER"; + case CSR_PSKEY_USB_ATTRIBUTES_WAKEUP: + return "USB_ATTRIBUTES_WAKEUP"; + case CSR_PSKEY_DFU_ATTRIBUTES_MANIFESTATION_TOLERANT: + return "DFU_ATTRIBUTES_MANIFESTATION_TOLERANT"; + case CSR_PSKEY_DFU_ATTRIBUTES_CAN_UPLOAD: + return "DFU_ATTRIBUTES_CAN_UPLOAD"; + case CSR_PSKEY_DFU_ATTRIBUTES_CAN_DOWNLOAD: + return "DFU_ATTRIBUTES_CAN_DOWNLOAD"; + case CSR_PSKEY_UART_CONFIG_STOP_BITS: + return "UART_CONFIG_STOP_BITS"; + case CSR_PSKEY_UART_CONFIG_PARITY_BIT: + return "UART_CONFIG_PARITY_BIT"; + case CSR_PSKEY_UART_CONFIG_FLOW_CTRL_EN: + return "UART_CONFIG_FLOW_CTRL_EN"; + case CSR_PSKEY_UART_CONFIG_RTS_AUTO_EN: + return "UART_CONFIG_RTS_AUTO_EN"; + case CSR_PSKEY_UART_CONFIG_RTS: + return "UART_CONFIG_RTS"; + case CSR_PSKEY_UART_CONFIG_TX_ZERO_EN: + return "UART_CONFIG_TX_ZERO_EN"; + case CSR_PSKEY_UART_CONFIG_NON_BCSP_EN: + return "UART_CONFIG_NON_BCSP_EN"; + case CSR_PSKEY_UART_CONFIG_RX_RATE_DELAY: + return "UART_CONFIG_RX_RATE_DELAY"; + case CSR_PSKEY_UART_SEQ_TIMEOUT: + return "UART_SEQ_TIMEOUT"; + case CSR_PSKEY_UART_SEQ_RETRIES: + return "UART_SEQ_RETRIES"; + case CSR_PSKEY_UART_SEQ_WINSIZE: + return "UART_SEQ_WINSIZE"; + case CSR_PSKEY_UART_USE_CRC_ON_TX: + return "UART_USE_CRC_ON_TX"; + case CSR_PSKEY_UART_HOST_INITIAL_STATE: + return "UART_HOST_INITIAL_STATE"; + case CSR_PSKEY_UART_HOST_ATTENTION_SPAN: + return "UART_HOST_ATTENTION_SPAN"; + case CSR_PSKEY_UART_HOST_WAKEUP_TIME: + return "UART_HOST_WAKEUP_TIME"; + case CSR_PSKEY_UART_HOST_WAKEUP_WAIT: + return "UART_HOST_WAKEUP_WAIT"; + case CSR_PSKEY_BCSP_LM_MODE: + return "BCSP_LM_MODE"; + case CSR_PSKEY_BCSP_LM_SYNC_RETRIES: + return "BCSP_LM_SYNC_RETRIES"; + case CSR_PSKEY_BCSP_LM_TSHY: + return "BCSP_LM_TSHY"; + case CSR_PSKEY_UART_DFU_CONFIG_STOP_BITS: + return "UART_DFU_CONFIG_STOP_BITS"; + case CSR_PSKEY_UART_DFU_CONFIG_PARITY_BIT: + return "UART_DFU_CONFIG_PARITY_BIT"; + case CSR_PSKEY_UART_DFU_CONFIG_FLOW_CTRL_EN: + return "UART_DFU_CONFIG_FLOW_CTRL_EN"; + case CSR_PSKEY_UART_DFU_CONFIG_RTS_AUTO_EN: + return "UART_DFU_CONFIG_RTS_AUTO_EN"; + case CSR_PSKEY_UART_DFU_CONFIG_RTS: + return "UART_DFU_CONFIG_RTS"; + case CSR_PSKEY_UART_DFU_CONFIG_TX_ZERO_EN: + return "UART_DFU_CONFIG_TX_ZERO_EN"; + case CSR_PSKEY_UART_DFU_CONFIG_NON_BCSP_EN: + return "UART_DFU_CONFIG_NON_BCSP_EN"; + case CSR_PSKEY_UART_DFU_CONFIG_RX_RATE_DELAY: + return "UART_DFU_CONFIG_RX_RATE_DELAY"; + case CSR_PSKEY_AMUX_AIO0: + return "AMUX_AIO0"; + case CSR_PSKEY_AMUX_AIO1: + return "AMUX_AIO1"; + case CSR_PSKEY_AMUX_AIO2: + return "AMUX_AIO2"; + case CSR_PSKEY_AMUX_AIO3: + return "AMUX_AIO3"; + case CSR_PSKEY_LOCAL_NAME_SIMPLIFIED: + return "LOCAL_NAME_SIMPLIFIED"; + case CSR_PSKEY_EXTENDED_STUB: + return "EXTENDED_STUB"; + default: + return "UNKNOWN"; + } +} + +int csr_write_varid_valueless(int dd, uint16_t seqnum, uint16_t varid) +{ + unsigned char cmd[] = { 0x02, 0x00, 0x09, 0x00, + seqnum & 0xff, seqnum >> 8, varid & 0xff, varid >> 8, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; + + unsigned char cp[254], rp[254]; + struct hci_request rq; + + memset(&cp, 0, sizeof(cp)); + cp[0] = 0xc2; + memcpy(cp + 1, cmd, sizeof(cmd)); + + switch (varid) { + case CSR_VARID_COLD_RESET: + case CSR_VARID_WARM_RESET: + case CSR_VARID_COLD_HALT: + case CSR_VARID_WARM_HALT: + return hci_send_cmd(dd, OGF_VENDOR_CMD, 0x00, sizeof(cmd) + 1, cp); + } + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_VENDOR_CMD; + rq.ocf = 0x00; + rq.event = EVT_VENDOR; + rq.cparam = cp; + rq.clen = sizeof(cmd) + 1; + rq.rparam = rp; + rq.rlen = sizeof(rp); + + if (hci_send_req(dd, &rq, 2000) < 0) + return -1; + + if (rp[0] != 0xc2) { + errno = EIO; + return -1; + } + + if ((rp[9] + (rp[10] << 8)) != 0) { + errno = ENXIO; + return -1; + } + + return 0; +} + +int csr_write_varid_complex(int dd, uint16_t seqnum, uint16_t varid, uint8_t *value, uint16_t length) +{ + unsigned char cmd[] = { 0x02, 0x00, ((length / 2) + 5) & 0xff, ((length / 2) + 5) >> 8, + seqnum & 0xff, seqnum >> 8, varid & 0xff, varid >> 8, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; + + unsigned char cp[254], rp[254]; + struct hci_request rq; + + memset(&cp, 0, sizeof(cp)); + cp[0] = 0xc2; + memcpy(cp + 1, cmd, sizeof(cmd)); + memcpy(cp + 11, value, length); + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_VENDOR_CMD; + rq.ocf = 0x00; + rq.event = EVT_VENDOR; + rq.cparam = cp; + rq.clen = sizeof(cmd) + length + 1; + rq.rparam = rp; + rq.rlen = sizeof(rp); + + if (hci_send_req(dd, &rq, 2000) < 0) + return -1; + + if (rp[0] != 0xc2) { + errno = EIO; + return -1; + } + + if ((rp[9] + (rp[10] << 8)) != 0) { + errno = ENXIO; + return -1; + } + + return 0; +} + +int csr_read_varid_complex(int dd, uint16_t seqnum, uint16_t varid, uint8_t *value, uint16_t length) +{ + unsigned char cmd[] = { 0x00, 0x00, ((length / 2) + 5) & 0xff, ((length / 2) + 5) >> 8, + seqnum & 0xff, seqnum >> 8, varid & 0xff, varid >> 8, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; + + unsigned char cp[254], rp[254]; + struct hci_request rq; + + memset(&cp, 0, sizeof(cp)); + cp[0] = 0xc2; + memcpy(cp + 1, cmd, sizeof(cmd)); + memcpy(cp + 11, value, length); + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_VENDOR_CMD; + rq.ocf = 0x00; + rq.event = EVT_VENDOR; + rq.cparam = cp; + rq.clen = sizeof(cmd) + length + 1; + rq.rparam = rp; + rq.rlen = sizeof(rp); + + if (hci_send_req(dd, &rq, 2000) < 0) + return -1; + + if (rp[0] != 0xc2) { + errno = EIO; + return -1; + } + + if ((rp[9] + (rp[10] << 8)) != 0) { + errno = ENXIO; + return -1; + } + + memcpy(value, rp + 11, length); + + return 0; +} + +int csr_read_varid_uint16(int dd, uint16_t seqnum, uint16_t varid, uint16_t *value) +{ + unsigned char cmd[] = { 0x00, 0x00, 0x09, 0x00, + seqnum & 0xff, seqnum >> 8, varid & 0xff, varid >> 8, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; + + unsigned char cp[254], rp[254]; + struct hci_request rq; + + memset(&cp, 0, sizeof(cp)); + cp[0] = 0xc2; + memcpy(cp + 1, cmd, sizeof(cmd)); + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_VENDOR_CMD; + rq.ocf = 0x00; + rq.event = EVT_VENDOR; + rq.cparam = cp; + rq.clen = sizeof(cmd) + 1; + rq.rparam = rp; + rq.rlen = sizeof(rp); + + if (hci_send_req(dd, &rq, 2000) < 0) + return -1; + + if (rp[0] != 0xc2) { + errno = EIO; + return -1; + } + + if ((rp[9] + (rp[10] << 8)) != 0) { + errno = ENXIO; + return -1; + } + + *value = rp[11] + (rp[12] << 8); + + return 0; +} + +int csr_read_varid_uint32(int dd, uint16_t seqnum, uint16_t varid, uint32_t *value) +{ + unsigned char cmd[] = { 0x00, 0x00, 0x09, 0x00, + seqnum & 0xff, seqnum >> 8, varid & 0xff, varid >> 8, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; + + unsigned char cp[254], rp[254]; + struct hci_request rq; + + memset(&cp, 0, sizeof(cp)); + cp[0] = 0xc2; + memcpy(cp + 1, cmd, sizeof(cmd)); + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_VENDOR_CMD; + rq.ocf = 0x00; + rq.event = EVT_VENDOR; + rq.cparam = cp; + rq.clen = sizeof(cmd) + 1; + rq.rparam = rp; + rq.rlen = sizeof(rp); + + if (hci_send_req(dd, &rq, 2000) < 0) + return -1; + + if (rp[0] != 0xc2) { + errno = EIO; + return -1; + } + + if ((rp[9] + (rp[10] << 8)) != 0) { + errno = ENXIO; + return -1; + } + + *value = ((rp[11] + (rp[12] << 8)) << 16) + (rp[13] + (rp[14] << 8)); + + return 0; +} + +int csr_read_pskey_complex(int dd, uint16_t seqnum, uint16_t pskey, uint16_t stores, uint8_t *value, uint16_t length) +{ + unsigned char cmd[] = { 0x00, 0x00, ((length / 2) + 8) & 0xff, ((length / 2) + 8) >> 8, + seqnum & 0xff, seqnum >> 8, 0x03, 0x70, 0x00, 0x00, + pskey & 0xff, pskey >> 8, + (length / 2) & 0xff, (length / 2) >> 8, + stores & 0xff, stores >> 8, 0x00, 0x00 }; + + unsigned char cp[254], rp[254]; + struct hci_request rq; + + memset(&cp, 0, sizeof(cp)); + cp[0] = 0xc2; + memcpy(cp + 1, cmd, sizeof(cmd)); + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_VENDOR_CMD; + rq.ocf = 0x00; + rq.event = EVT_VENDOR; + rq.cparam = cp; + rq.clen = sizeof(cmd) + length - 1; + rq.rparam = rp; + rq.rlen = sizeof(rp); + + if (hci_send_req(dd, &rq, 2000) < 0) + return -1; + + if (rp[0] != 0xc2) { + errno = EIO; + return -1; + } + + if ((rp[9] + (rp[10] << 8)) != 0) { + errno = ENXIO; + return -1; + } + + memcpy(value, rp + 17, length); + + return 0; +} + +int csr_write_pskey_complex(int dd, uint16_t seqnum, uint16_t pskey, uint16_t stores, uint8_t *value, uint16_t length) +{ + unsigned char cmd[] = { 0x02, 0x00, ((length / 2) + 8) & 0xff, ((length / 2) + 8) >> 8, + seqnum & 0xff, seqnum >> 8, 0x03, 0x70, 0x00, 0x00, + pskey & 0xff, pskey >> 8, + (length / 2) & 0xff, (length / 2) >> 8, + stores & 0xff, stores >> 8, 0x00, 0x00 }; + + unsigned char cp[254], rp[254]; + struct hci_request rq; + + memset(&cp, 0, sizeof(cp)); + cp[0] = 0xc2; + memcpy(cp + 1, cmd, sizeof(cmd)); + + memcpy(cp + 17, value, length); + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_VENDOR_CMD; + rq.ocf = 0x00; + rq.event = EVT_VENDOR; + rq.cparam = cp; + rq.clen = sizeof(cmd) + length - 1; + rq.rparam = rp; + rq.rlen = sizeof(rp); + + if (hci_send_req(dd, &rq, 2000) < 0) + return -1; + + if (rp[0] != 0xc2) { + errno = EIO; + return -1; + } + + if ((rp[9] + (rp[10] << 8)) != 0) { + errno = ENXIO; + return -1; + } + + return 0; +} + +int csr_read_pskey_uint16(int dd, uint16_t seqnum, uint16_t pskey, uint16_t stores, uint16_t *value) +{ + uint8_t array[2] = { 0x00, 0x00 }; + int err; + + err = csr_read_pskey_complex(dd, seqnum, pskey, stores, array, 2); + + *value = array[0] + (array[1] << 8); + + return err; +} + +int csr_write_pskey_uint16(int dd, uint16_t seqnum, uint16_t pskey, uint16_t stores, uint16_t value) +{ + uint8_t array[2] = { value & 0xff, value >> 8 }; + + return csr_write_pskey_complex(dd, seqnum, pskey, stores, array, 2); +} + +int csr_read_pskey_uint32(int dd, uint16_t seqnum, uint16_t pskey, uint16_t stores, uint32_t *value) +{ + uint8_t array[4] = { 0x00, 0x00, 0x00, 0x00 }; + int err; + + err = csr_read_pskey_complex(dd, seqnum, pskey, stores, array, 4); + + *value = ((array[0] + (array[1] << 8)) << 16) + + (array[2] + (array[3] << 8)); + + return err; +} + +int csr_write_pskey_uint32(int dd, uint16_t seqnum, uint16_t pskey, uint16_t stores, uint32_t value) +{ + uint8_t array[4] = { (value & 0xff0000) >> 16, value >> 24, + value & 0xff, (value & 0xff00) >> 8 }; + + return csr_write_pskey_complex(dd, seqnum, pskey, stores, array, 4); +} + +int psr_put(uint16_t pskey, uint8_t *value, uint16_t size) +{ + struct psr_data *item; + + item = malloc(sizeof(*item)); + if (!item) + return -ENOMEM; + + item->pskey = pskey; + + if (size > 0) { + item->value = malloc(size); + if (!item->value) { + free(item); + return -ENOMEM; + } + + memcpy(item->value, value, size); + item->size = size; + } else { + item->value = NULL; + item->size = 0; + } + + item->next = NULL; + + if (!head) + head = item; + else + tail->next = item; + + tail = item; + + return 0; +} + +int psr_get(uint16_t *pskey, uint8_t *value, uint16_t *size) +{ + struct psr_data *item = head; + + if (!head) + return -ENOENT; + + *pskey = item->pskey; + + if (item->value) { + if (value && item->size > 0) + memcpy(value, item->value, item->size); + free(item->value); + *size = item->size; + } else + *size = 0; + + if (head == tail) + tail = NULL; + + head = head->next; + free(item); + + return 0; +} + +static int parse_line(char *str) +{ + uint8_t array[256]; + uint16_t value, pskey, length = 0; + char *off, *end; + + pskey = strtol(str + 1, NULL, 16); + off = strstr(str, "=") + 1; + if (!off) + return -EIO; + + while (1) { + value = strtol(off, &end, 16); + if (value == 0 && off == end) + break; + + array[length++] = value & 0xff; + array[length++] = value >> 8; + + if (*end == '\0') + break; + + off = end + 1; + } + + return psr_put(pskey, array, length); +} + +int psr_read(const char *filename) +{ + struct stat st; + char *str, *map, *off, *end; + int fd, err = 0; + + fd = open(filename, O_RDONLY); + if (fd < 0) + return fd; + + if (fstat(fd, &st) < 0) { + err = -errno; + goto close; + } + + map = mmap(0, st.st_size, PROT_READ, MAP_SHARED, fd, 0); + if (!map || map == MAP_FAILED) { + err = -errno; + goto close; + } + + off = map; + + while (1) { + if (*off == '\r' || *off == '\n') { + off++; + continue; + } + + end = strpbrk(off, "\r\n"); + if (!end) + break; + + str = malloc(end - off + 1); + if (!str) + break; + + memset(str, 0, end - off + 1); + strncpy(str, off, end - off); + if (*str == '&') + parse_line(str); + + free(str); + off = end + 1; + } + + munmap(map, st.st_size); + +close: + close(fd); + + return err; +} + +int psr_print(void) +{ + uint8_t array[256]; + uint16_t pskey, length; + char *str, val[7]; + int i; + + while (1) { + if (psr_get(&pskey, array, &length) < 0) + break; + + str = csr_pskeytoval(pskey); + if (!strcasecmp(str, "UNKNOWN")) { + sprintf(val, "0x%04x", pskey); + str = NULL; + } + + printf("// %s%s\n&%04x =", str ? "PSKEY_" : "", + str ? str : val, pskey); + for (i = 0; i < length / 2; i++) + printf(" %02x%02x", array[i * 2 + 1], array[i * 2]); + printf("\n"); + } + + return 0; +} diff --git a/drive-sdk/deps/bzle/tools/csr.h b/drive-sdk/deps/bzle/tools/csr.h new file mode 100644 index 0000000..8b94d7b --- /dev/null +++ b/drive-sdk/deps/bzle/tools/csr.h @@ -0,0 +1,553 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2003-2010 Marcel Holtmann + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#include +#include + +#define CSR_VARID_PS_CLR_ALL 0x000b /* valueless */ +#define CSR_VARID_PS_FACTORY_SET 0x000c /* valueless */ +#define CSR_VARID_PS_CLR_ALL_STORES 0x082d /* uint16 */ +#define CSR_VARID_BC01_STATUS 0x2801 /* uint16 */ +#define CSR_VARID_BUILDID 0x2819 /* uint16 */ +#define CSR_VARID_CHIPVER 0x281a /* uint16 */ +#define CSR_VARID_CHIPREV 0x281b /* uint16 */ +#define CSR_VARID_INTERFACE_VERSION 0x2825 /* uint16 */ +#define CSR_VARID_RAND 0x282a /* uint16 */ +#define CSR_VARID_MAX_CRYPT_KEY_LENGTH 0x282c /* uint16 */ +#define CSR_VARID_CHIPANAREV 0x2836 /* uint16 */ +#define CSR_VARID_BUILDID_LOADER 0x2838 /* uint16 */ +#define CSR_VARID_BT_CLOCK 0x2c00 /* uint32 */ +#define CSR_VARID_PS_NEXT 0x3005 /* complex */ +#define CSR_VARID_PS_SIZE 0x3006 /* complex */ +#define CSR_VARID_CRYPT_KEY_LENGTH 0x3008 /* complex */ +#define CSR_VARID_PICONET_INSTANCE 0x3009 /* complex */ +#define CSR_VARID_GET_CLR_EVT 0x300a /* complex */ +#define CSR_VARID_GET_NEXT_BUILDDEF 0x300b /* complex */ +#define CSR_VARID_PS_MEMORY_TYPE 0x3012 /* complex */ +#define CSR_VARID_READ_BUILD_NAME 0x301c /* complex */ +#define CSR_VARID_COLD_RESET 0x4001 /* valueless */ +#define CSR_VARID_WARM_RESET 0x4002 /* valueless */ +#define CSR_VARID_COLD_HALT 0x4003 /* valueless */ +#define CSR_VARID_WARM_HALT 0x4004 /* valueless */ +#define CSR_VARID_INIT_BT_STACK 0x4005 /* valueless */ +#define CSR_VARID_ACTIVATE_BT_STACK 0x4006 /* valueless */ +#define CSR_VARID_ENABLE_TX 0x4007 /* valueless */ +#define CSR_VARID_DISABLE_TX 0x4008 /* valueless */ +#define CSR_VARID_RECAL 0x4009 /* valueless */ +#define CSR_VARID_PS_FACTORY_RESTORE 0x400d /* valueless */ +#define CSR_VARID_PS_FACTORY_RESTORE_ALL 0x400e /* valueless */ +#define CSR_VARID_PS_DEFRAG_RESET 0x400f /* valueless */ +#define CSR_VARID_KILL_VM_APPLICATION 0x4010 /* valueless */ +#define CSR_VARID_HOPPING_ON 0x4011 /* valueless */ +#define CSR_VARID_CANCEL_PAGE 0x4012 /* valueless */ +#define CSR_VARID_PS_CLR 0x4818 /* uint16 */ +#define CSR_VARID_MAP_SCO_PCM 0x481c /* uint16 */ +#define CSR_VARID_SINGLE_CHAN 0x482e /* uint16 */ +#define CSR_VARID_RADIOTEST 0x5004 /* complex */ +#define CSR_VARID_PS_CLR_STORES 0x500c /* complex */ +#define CSR_VARID_NO_VARIABLE 0x6000 /* valueless */ +#define CSR_VARID_CONFIG_UART 0x6802 /* uint16 */ +#define CSR_VARID_PANIC_ARG 0x6805 /* uint16 */ +#define CSR_VARID_FAULT_ARG 0x6806 /* uint16 */ +#define CSR_VARID_MAX_TX_POWER 0x6827 /* int8 */ +#define CSR_VARID_DEFAULT_TX_POWER 0x682b /* int8 */ +#define CSR_VARID_PS 0x7003 /* complex */ + +#define CSR_PSKEY_BDADDR 0x0001 /* bdaddr / uint16[] = { 0x00A5A5, 0x5b, 0x0002 } */ +#define CSR_PSKEY_COUNTRYCODE 0x0002 /* uint16 */ +#define CSR_PSKEY_CLASSOFDEVICE 0x0003 /* bdcod */ +#define CSR_PSKEY_DEVICE_DRIFT 0x0004 /* uint16 */ +#define CSR_PSKEY_DEVICE_JITTER 0x0005 /* uint16 */ +#define CSR_PSKEY_MAX_ACLS 0x000d /* uint16 */ +#define CSR_PSKEY_MAX_SCOS 0x000e /* uint16 */ +#define CSR_PSKEY_MAX_REMOTE_MASTERS 0x000f /* uint16 */ +#define CSR_PSKEY_ENABLE_MASTERY_WITH_SLAVERY 0x0010 /* bool */ +#define CSR_PSKEY_H_HC_FC_MAX_ACL_PKT_LEN 0x0011 /* uint16 */ +#define CSR_PSKEY_H_HC_FC_MAX_SCO_PKT_LEN 0x0012 /* uint8 */ +#define CSR_PSKEY_H_HC_FC_MAX_ACL_PKTS 0x0013 /* uint16 */ +#define CSR_PSKEY_H_HC_FC_MAX_SCO_PKTS 0x0014 /* uint16 */ +#define CSR_PSKEY_LC_FC_BUFFER_LOW_WATER_MARK 0x0015 /* lc_fc_lwm */ +#define CSR_PSKEY_LC_MAX_TX_POWER 0x0017 /* int16 */ +#define CSR_PSKEY_TX_GAIN_RAMP 0x001d /* uint16 */ +#define CSR_PSKEY_LC_POWER_TABLE 0x001e /* power_setting[] */ +#define CSR_PSKEY_LC_PEER_POWER_PERIOD 0x001f /* TIME */ +#define CSR_PSKEY_LC_FC_POOLS_LOW_WATER_MARK 0x0020 /* lc_fc_lwm */ +#define CSR_PSKEY_LC_DEFAULT_TX_POWER 0x0021 /* int16 */ +#define CSR_PSKEY_LC_RSSI_GOLDEN_RANGE 0x0022 /* uint8 */ +#define CSR_PSKEY_LC_COMBO_DISABLE_PIO_MASK 0x0028 /* uint16[] */ +#define CSR_PSKEY_LC_COMBO_PRIORITY_PIO_MASK 0x0029 /* uint16[] */ +#define CSR_PSKEY_LC_COMBO_DOT11_CHANNEL_PIO_BASE 0x002a /* uint16 */ +#define CSR_PSKEY_LC_COMBO_DOT11_BLOCK_CHANNELS 0x002b /* uint16 */ +#define CSR_PSKEY_LC_MAX_TX_POWER_NO_RSSI 0x002d /* int8 */ +#define CSR_PSKEY_LC_CONNECTION_RX_WINDOW 0x002e /* uint16 */ +#define CSR_PSKEY_LC_COMBO_DOT11_TX_PROTECTION_MODE 0x0030 /* uint16 */ +#define CSR_PSKEY_LC_ENHANCED_POWER_TABLE 0x0031 /* enhanced_power_setting[] */ +#define CSR_PSKEY_LC_WIDEBAND_RSSI_CONFIG 0x0032 /* wideband_rssi_config */ +#define CSR_PSKEY_LC_COMBO_DOT11_PRIORITY_LEAD 0x0033 /* uint16 */ +#define CSR_PSKEY_BT_CLOCK_INIT 0x0034 /* uint32 */ +#define CSR_PSKEY_TX_MR_MOD_DELAY 0x0038 /* uint8 */ +#define CSR_PSKEY_RX_MR_SYNC_TIMING 0x0039 /* uint16 */ +#define CSR_PSKEY_RX_MR_SYNC_CONFIG 0x003a /* uint16 */ +#define CSR_PSKEY_LC_LOST_SYNC_SLOTS 0x003b /* uint16 */ +#define CSR_PSKEY_RX_MR_SAMP_CONFIG 0x003c /* uint16 */ +#define CSR_PSKEY_AGC_HYST_LEVELS 0x003d /* agc_hyst_config */ +#define CSR_PSKEY_RX_LEVEL_LOW_SIGNAL 0x003e /* uint16 */ +#define CSR_PSKEY_AGC_IQ_LVL_VALUES 0x003f /* IQ_LVL_VAL[] */ +#define CSR_PSKEY_MR_FTRIM_OFFSET_12DB 0x0040 /* uint16 */ +#define CSR_PSKEY_MR_FTRIM_OFFSET_6DB 0x0041 /* uint16 */ +#define CSR_PSKEY_NO_CAL_ON_BOOT 0x0042 /* bool */ +#define CSR_PSKEY_RSSI_HI_TARGET 0x0043 /* uint8 */ +#define CSR_PSKEY_PREFERRED_MIN_ATTENUATION 0x0044 /* uint8 */ +#define CSR_PSKEY_LC_COMBO_DOT11_PRIORITY_OVERRIDE 0x0045 /* bool */ +#define CSR_PSKEY_LC_MULTISLOT_HOLDOFF 0x0047 /* TIME */ +#define CSR_PSKEY_FREE_KEY_PIGEON_HOLE 0x00c9 /* uint16 */ +#define CSR_PSKEY_LINK_KEY_BD_ADDR0 0x00ca /* LM_LINK_KEY_BD_ADDR_T */ +#define CSR_PSKEY_LINK_KEY_BD_ADDR1 0x00cb /* LM_LINK_KEY_BD_ADDR_T */ +#define CSR_PSKEY_LINK_KEY_BD_ADDR2 0x00cc /* LM_LINK_KEY_BD_ADDR_T */ +#define CSR_PSKEY_LINK_KEY_BD_ADDR3 0x00cd /* LM_LINK_KEY_BD_ADDR_T */ +#define CSR_PSKEY_LINK_KEY_BD_ADDR4 0x00ce /* LM_LINK_KEY_BD_ADDR_T */ +#define CSR_PSKEY_LINK_KEY_BD_ADDR5 0x00cf /* LM_LINK_KEY_BD_ADDR_T */ +#define CSR_PSKEY_LINK_KEY_BD_ADDR6 0x00d0 /* LM_LINK_KEY_BD_ADDR_T */ +#define CSR_PSKEY_LINK_KEY_BD_ADDR7 0x00d1 /* LM_LINK_KEY_BD_ADDR_T */ +#define CSR_PSKEY_LINK_KEY_BD_ADDR8 0x00d2 /* LM_LINK_KEY_BD_ADDR_T */ +#define CSR_PSKEY_LINK_KEY_BD_ADDR9 0x00d3 /* LM_LINK_KEY_BD_ADDR_T */ +#define CSR_PSKEY_LINK_KEY_BD_ADDR10 0x00d4 /* LM_LINK_KEY_BD_ADDR_T */ +#define CSR_PSKEY_LINK_KEY_BD_ADDR11 0x00d5 /* LM_LINK_KEY_BD_ADDR_T */ +#define CSR_PSKEY_LINK_KEY_BD_ADDR12 0x00d6 /* LM_LINK_KEY_BD_ADDR_T */ +#define CSR_PSKEY_LINK_KEY_BD_ADDR13 0x00d7 /* LM_LINK_KEY_BD_ADDR_T */ +#define CSR_PSKEY_LINK_KEY_BD_ADDR14 0x00d8 /* LM_LINK_KEY_BD_ADDR_T */ +#define CSR_PSKEY_LINK_KEY_BD_ADDR15 0x00d9 /* LM_LINK_KEY_BD_ADDR_T */ +#define CSR_PSKEY_ENC_KEY_LMIN 0x00da /* uint16 */ +#define CSR_PSKEY_ENC_KEY_LMAX 0x00db /* uint16 */ +#define CSR_PSKEY_LOCAL_SUPPORTED_FEATURES 0x00ef /* uint16[] = { 0xffff, 0xfe8f, 0xf99b, 0x8000 }*/ +#define CSR_PSKEY_LM_USE_UNIT_KEY 0x00f0 /* bool */ +#define CSR_PSKEY_HCI_NOP_DISABLE 0x00f2 /* bool */ +#define CSR_PSKEY_LM_MAX_EVENT_FILTERS 0x00f4 /* uint8 */ +#define CSR_PSKEY_LM_USE_ENC_MODE_BROADCAST 0x00f5 /* bool */ +#define CSR_PSKEY_LM_TEST_SEND_ACCEPTED_TWICE 0x00f6 /* bool */ +#define CSR_PSKEY_LM_MAX_PAGE_HOLD_TIME 0x00f7 /* uint16 */ +#define CSR_PSKEY_AFH_ADAPTATION_RESPONSE_TIME 0x00f8 /* uint16 */ +#define CSR_PSKEY_AFH_OPTIONS 0x00f9 /* uint16 */ +#define CSR_PSKEY_AFH_RSSI_RUN_PERIOD 0x00fa /* uint16 */ +#define CSR_PSKEY_AFH_REENABLE_CHANNEL_TIME 0x00fb /* uint16 */ +#define CSR_PSKEY_NO_DROP_ON_ACR_MS_FAIL 0x00fc /* bool */ +#define CSR_PSKEY_MAX_PRIVATE_KEYS 0x00fd /* uint8 */ +#define CSR_PSKEY_PRIVATE_LINK_KEY_BD_ADDR0 0x00fe /* LM_LINK_KEY_BD_ADDR_T */ +#define CSR_PSKEY_PRIVATE_LINK_KEY_BD_ADDR1 0x00ff /* LM_LINK_KEY_BD_ADDR_T */ +#define CSR_PSKEY_PRIVATE_LINK_KEY_BD_ADDR2 0x0100 /* LM_LINK_KEY_BD_ADDR_T */ +#define CSR_PSKEY_PRIVATE_LINK_KEY_BD_ADDR3 0x0101 /* LM_LINK_KEY_BD_ADDR_T */ +#define CSR_PSKEY_PRIVATE_LINK_KEY_BD_ADDR4 0x0102 /* LM_LINK_KEY_BD_ADDR_T */ +#define CSR_PSKEY_PRIVATE_LINK_KEY_BD_ADDR5 0x0103 /* LM_LINK_KEY_BD_ADDR_T */ +#define CSR_PSKEY_PRIVATE_LINK_KEY_BD_ADDR6 0x0104 /* LM_LINK_KEY_BD_ADDR_T */ +#define CSR_PSKEY_PRIVATE_LINK_KEY_BD_ADDR7 0x0105 /* LM_LINK_KEY_BD_ADDR_T */ +#define CSR_PSKEY_LOCAL_SUPPORTED_COMMANDS 0x0106 /* uint16[] = { 0xffff, 0x03ff, 0xfffe, 0xffff, 0xffff, 0xffff, 0x0ff3, 0xfff8, 0x003f } */ +#define CSR_PSKEY_LM_MAX_ABSENCE_INDEX 0x0107 /* uint8 */ +#define CSR_PSKEY_DEVICE_NAME 0x0108 /* uint16[] */ +#define CSR_PSKEY_AFH_RSSI_THRESHOLD 0x0109 /* uint16 */ +#define CSR_PSKEY_LM_CASUAL_SCAN_INTERVAL 0x010a /* uint16 */ +#define CSR_PSKEY_AFH_MIN_MAP_CHANGE 0x010b /* uint16[] */ +#define CSR_PSKEY_AFH_RSSI_LP_RUN_PERIOD 0x010c /* uint16 */ +#define CSR_PSKEY_HCI_LMP_LOCAL_VERSION 0x010d /* uint16 */ +#define CSR_PSKEY_LMP_REMOTE_VERSION 0x010e /* uint8 */ +#define CSR_PSKEY_HOLD_ERROR_MESSAGE_NUMBER 0x0113 /* uint16 */ +#define CSR_PSKEY_DFU_ATTRIBUTES 0x0136 /* uint8 */ +#define CSR_PSKEY_DFU_DETACH_TO 0x0137 /* uint16 */ +#define CSR_PSKEY_DFU_TRANSFER_SIZE 0x0138 /* uint16 */ +#define CSR_PSKEY_DFU_ENABLE 0x0139 /* bool */ +#define CSR_PSKEY_DFU_LIN_REG_ENABLE 0x013a /* bool */ +#define CSR_PSKEY_DFUENC_VMAPP_PK_MODULUS_MSB 0x015e /* uint16[] */ +#define CSR_PSKEY_DFUENC_VMAPP_PK_MODULUS_LSB 0x015f /* uint16[] */ +#define CSR_PSKEY_DFUENC_VMAPP_PK_M_DASH 0x0160 /* uint16 */ +#define CSR_PSKEY_DFUENC_VMAPP_PK_R2N_MSB 0x0161 /* uint16[] */ +#define CSR_PSKEY_DFUENC_VMAPP_PK_R2N_LSB 0x0162 /* uint16[] */ +#define CSR_PSKEY_BCSP_LM_PS_BLOCK 0x0192 /* BCSP_LM_PS_BLOCK */ +#define CSR_PSKEY_HOSTIO_FC_PS_BLOCK 0x0193 /* HOSTIO_FC_PS_BLOCK */ +#define CSR_PSKEY_HOSTIO_PROTOCOL_INFO0 0x0194 /* PROTOCOL_INFO */ +#define CSR_PSKEY_HOSTIO_PROTOCOL_INFO1 0x0195 /* PROTOCOL_INFO */ +#define CSR_PSKEY_HOSTIO_PROTOCOL_INFO2 0x0196 /* PROTOCOL_INFO */ +#define CSR_PSKEY_HOSTIO_PROTOCOL_INFO3 0x0197 /* PROTOCOL_INFO */ +#define CSR_PSKEY_HOSTIO_PROTOCOL_INFO4 0x0198 /* PROTOCOL_INFO */ +#define CSR_PSKEY_HOSTIO_PROTOCOL_INFO5 0x0199 /* PROTOCOL_INFO */ +#define CSR_PSKEY_HOSTIO_PROTOCOL_INFO6 0x019a /* PROTOCOL_INFO */ +#define CSR_PSKEY_HOSTIO_PROTOCOL_INFO7 0x019b /* PROTOCOL_INFO */ +#define CSR_PSKEY_HOSTIO_PROTOCOL_INFO8 0x019c /* PROTOCOL_INFO */ +#define CSR_PSKEY_HOSTIO_PROTOCOL_INFO9 0x019d /* PROTOCOL_INFO */ +#define CSR_PSKEY_HOSTIO_PROTOCOL_INFO10 0x019e /* PROTOCOL_INFO */ +#define CSR_PSKEY_HOSTIO_PROTOCOL_INFO11 0x019f /* PROTOCOL_INFO */ +#define CSR_PSKEY_HOSTIO_PROTOCOL_INFO12 0x01a0 /* PROTOCOL_INFO */ +#define CSR_PSKEY_HOSTIO_PROTOCOL_INFO13 0x01a1 /* PROTOCOL_INFO */ +#define CSR_PSKEY_HOSTIO_PROTOCOL_INFO14 0x01a2 /* PROTOCOL_INFO */ +#define CSR_PSKEY_HOSTIO_PROTOCOL_INFO15 0x01a3 /* PROTOCOL_INFO */ +#define CSR_PSKEY_HOSTIO_UART_RESET_TIMEOUT 0x01a4 /* TIME */ +#define CSR_PSKEY_HOSTIO_USE_HCI_EXTN 0x01a5 /* bool */ +#define CSR_PSKEY_HOSTIO_USE_HCI_EXTN_CCFC 0x01a6 /* bool */ +#define CSR_PSKEY_HOSTIO_HCI_EXTN_PAYLOAD_SIZE 0x01a7 /* uint16 */ +#define CSR_PSKEY_BCSP_LM_CNF_CNT_LIMIT 0x01aa /* uint16 */ +#define CSR_PSKEY_HOSTIO_MAP_SCO_PCM 0x01ab /* bool */ +#define CSR_PSKEY_HOSTIO_AWKWARD_PCM_SYNC 0x01ac /* bool */ +#define CSR_PSKEY_HOSTIO_BREAK_POLL_PERIOD 0x01ad /* TIME */ +#define CSR_PSKEY_HOSTIO_MIN_UART_HCI_SCO_SIZE 0x01ae /* uint16 */ +#define CSR_PSKEY_HOSTIO_MAP_SCO_CODEC 0x01b0 /* bool */ +#define CSR_PSKEY_PCM_CVSD_TX_HI_FREQ_BOOST 0x01b1 /* uint16 */ +#define CSR_PSKEY_PCM_CVSD_RX_HI_FREQ_BOOST 0x01b2 /* uint16 */ +#define CSR_PSKEY_PCM_CONFIG32 0x01b3 /* uint32 */ +#define CSR_PSKEY_USE_OLD_BCSP_LE 0x01b4 /* uint16 */ +#define CSR_PSKEY_PCM_CVSD_USE_NEW_FILTER 0x01b5 /* bool */ +#define CSR_PSKEY_PCM_FORMAT 0x01b6 /* uint16 */ +#define CSR_PSKEY_CODEC_OUT_GAIN 0x01b7 /* uint16 */ +#define CSR_PSKEY_CODEC_IN_GAIN 0x01b8 /* uint16 */ +#define CSR_PSKEY_CODEC_PIO 0x01b9 /* uint16 */ +#define CSR_PSKEY_PCM_LOW_JITTER_CONFIG 0x01ba /* uint32 */ +#define CSR_PSKEY_HOSTIO_SCO_PCM_THRESHOLDS 0x01bb /* uint16[] */ +#define CSR_PSKEY_HOSTIO_SCO_HCI_THRESHOLDS 0x01bc /* uint16[] */ +#define CSR_PSKEY_HOSTIO_MAP_SCO_PCM_SLOT 0x01bd /* uint16 */ +#define CSR_PSKEY_UART_BAUDRATE 0x01be /* uint16 */ +#define CSR_PSKEY_UART_CONFIG_BCSP 0x01bf /* uint16 */ +#define CSR_PSKEY_UART_CONFIG_H4 0x01c0 /* uint16 */ +#define CSR_PSKEY_UART_CONFIG_H5 0x01c1 /* uint16 */ +#define CSR_PSKEY_UART_CONFIG_USR 0x01c2 /* uint16 */ +#define CSR_PSKEY_UART_TX_CRCS 0x01c3 /* bool */ +#define CSR_PSKEY_UART_ACK_TIMEOUT 0x01c4 /* uint16 */ +#define CSR_PSKEY_UART_TX_MAX_ATTEMPTS 0x01c5 /* uint16 */ +#define CSR_PSKEY_UART_TX_WINDOW_SIZE 0x01c6 /* uint16 */ +#define CSR_PSKEY_UART_HOST_WAKE 0x01c7 /* uint16[] */ +#define CSR_PSKEY_HOSTIO_THROTTLE_TIMEOUT 0x01c8 /* TIME */ +#define CSR_PSKEY_PCM_ALWAYS_ENABLE 0x01c9 /* bool */ +#define CSR_PSKEY_UART_HOST_WAKE_SIGNAL 0x01ca /* uint16 */ +#define CSR_PSKEY_UART_CONFIG_H4DS 0x01cb /* uint16 */ +#define CSR_PSKEY_H4DS_WAKE_DURATION 0x01cc /* uint16 */ +#define CSR_PSKEY_H4DS_MAXWU 0x01cd /* uint16 */ +#define CSR_PSKEY_H4DS_LE_TIMER_PERIOD 0x01cf /* uint16 */ +#define CSR_PSKEY_H4DS_TWU_TIMER_PERIOD 0x01d0 /* uint16 */ +#define CSR_PSKEY_H4DS_UART_IDLE_TIMER_PERIOD 0x01d1 /* uint16 */ +#define CSR_PSKEY_ANA_FTRIM 0x01f6 /* uint16 */ +#define CSR_PSKEY_WD_TIMEOUT 0x01f7 /* TIME */ +#define CSR_PSKEY_WD_PERIOD 0x01f8 /* TIME */ +#define CSR_PSKEY_HOST_INTERFACE 0x01f9 /* phys_bus */ +#define CSR_PSKEY_HQ_HOST_TIMEOUT 0x01fb /* TIME */ +#define CSR_PSKEY_HQ_ACTIVE 0x01fc /* bool */ +#define CSR_PSKEY_BCCMD_SECURITY_ACTIVE 0x01fd /* bool */ +#define CSR_PSKEY_ANA_FREQ 0x01fe /* uint16 */ +#define CSR_PSKEY_PIO_PROTECT_MASK 0x0202 /* uint16 */ +#define CSR_PSKEY_PMALLOC_SIZES 0x0203 /* uint16[] */ +#define CSR_PSKEY_UART_BAUD_RATE 0x0204 /* uint16 */ +#define CSR_PSKEY_UART_CONFIG 0x0205 /* uint16 */ +#define CSR_PSKEY_STUB 0x0207 /* uint16 */ +#define CSR_PSKEY_TXRX_PIO_CONTROL 0x0209 /* uint16 */ +#define CSR_PSKEY_ANA_RX_LEVEL 0x020b /* uint16 */ +#define CSR_PSKEY_ANA_RX_FTRIM 0x020c /* uint16 */ +#define CSR_PSKEY_PSBC_DATA_VERSION 0x020d /* uint16 */ +#define CSR_PSKEY_PCM0_ATTENUATION 0x020f /* uint16 */ +#define CSR_PSKEY_LO_LVL_MAX 0x0211 /* uint16 */ +#define CSR_PSKEY_LO_ADC_AMPL_MIN 0x0212 /* uint16 */ +#define CSR_PSKEY_LO_ADC_AMPL_MAX 0x0213 /* uint16 */ +#define CSR_PSKEY_IQ_TRIM_CHANNEL 0x0214 /* uint16 */ +#define CSR_PSKEY_IQ_TRIM_GAIN 0x0215 /* uint16 */ +#define CSR_PSKEY_IQ_TRIM_ENABLE 0x0216 /* iq_trim_enable_flag */ +#define CSR_PSKEY_TX_OFFSET_HALF_MHZ 0x0217 /* int16 */ +#define CSR_PSKEY_GBL_MISC_ENABLES 0x0221 /* uint16 */ +#define CSR_PSKEY_UART_SLEEP_TIMEOUT 0x0222 /* uint16 */ +#define CSR_PSKEY_DEEP_SLEEP_STATE 0x0229 /* deep_sleep_state */ +#define CSR_PSKEY_IQ_ENABLE_PHASE_TRIM 0x022d /* bool */ +#define CSR_PSKEY_HCI_HANDLE_FREEZE_PERIOD 0x0237 /* TIME */ +#define CSR_PSKEY_MAX_FROZEN_HCI_HANDLES 0x0238 /* uint16 */ +#define CSR_PSKEY_PAGETABLE_DESTRUCTION_DELAY 0x0239 /* TIME */ +#define CSR_PSKEY_IQ_TRIM_PIO_SETTINGS 0x023a /* uint8 */ +#define CSR_PSKEY_USE_EXTERNAL_CLOCK 0x023b /* bool */ +#define CSR_PSKEY_DEEP_SLEEP_WAKE_CTS 0x023c /* uint16 */ +#define CSR_PSKEY_FC_HC2H_FLUSH_DELAY 0x023d /* TIME */ +#define CSR_PSKEY_RX_HIGHSIDE 0x023e /* bool */ +#define CSR_PSKEY_TX_PRE_LVL 0x0240 /* uint8 */ +#define CSR_PSKEY_RX_SINGLE_ENDED 0x0242 /* bool */ +#define CSR_PSKEY_TX_FILTER_CONFIG 0x0243 /* uint32 */ +#define CSR_PSKEY_CLOCK_REQUEST_ENABLE 0x0246 /* uint16 */ +#define CSR_PSKEY_RX_MIN_ATTEN 0x0249 /* uint16 */ +#define CSR_PSKEY_XTAL_TARGET_AMPLITUDE 0x024b /* uint8 */ +#define CSR_PSKEY_PCM_MIN_CPU_CLOCK 0x024d /* uint16 */ +#define CSR_PSKEY_HOST_INTERFACE_PIO_USB 0x0250 /* uint16 */ +#define CSR_PSKEY_CPU_IDLE_MODE 0x0251 /* cpu_idle_mode */ +#define CSR_PSKEY_DEEP_SLEEP_CLEAR_RTS 0x0252 /* bool */ +#define CSR_PSKEY_RF_RESONANCE_TRIM 0x0254 /* uint16 */ +#define CSR_PSKEY_DEEP_SLEEP_PIO_WAKE 0x0255 /* uint16 */ +#define CSR_PSKEY_DRAIN_BORE_TIMERS 0x0256 /* uint32[] */ +#define CSR_PSKEY_DRAIN_TX_POWER_BASE 0x0257 /* uint16 */ +#define CSR_PSKEY_MODULE_ID 0x0259 /* uint32 */ +#define CSR_PSKEY_MODULE_DESIGN 0x025a /* uint16 */ +#define CSR_PSKEY_MODULE_SECURITY_CODE 0x025c /* uint16[] */ +#define CSR_PSKEY_VM_DISABLE 0x025d /* bool */ +#define CSR_PSKEY_MOD_MANUF0 0x025e /* uint16[] */ +#define CSR_PSKEY_MOD_MANUF1 0x025f /* uint16[] */ +#define CSR_PSKEY_MOD_MANUF2 0x0260 /* uint16[] */ +#define CSR_PSKEY_MOD_MANUF3 0x0261 /* uint16[] */ +#define CSR_PSKEY_MOD_MANUF4 0x0262 /* uint16[] */ +#define CSR_PSKEY_MOD_MANUF5 0x0263 /* uint16[] */ +#define CSR_PSKEY_MOD_MANUF6 0x0264 /* uint16[] */ +#define CSR_PSKEY_MOD_MANUF7 0x0265 /* uint16[] */ +#define CSR_PSKEY_MOD_MANUF8 0x0266 /* uint16[] */ +#define CSR_PSKEY_MOD_MANUF9 0x0267 /* uint16[] */ +#define CSR_PSKEY_DUT_VM_DISABLE 0x0268 /* bool */ +#define CSR_PSKEY_USR0 0x028a /* uint16[] */ +#define CSR_PSKEY_USR1 0x028b /* uint16[] */ +#define CSR_PSKEY_USR2 0x028c /* uint16[] */ +#define CSR_PSKEY_USR3 0x028d /* uint16[] */ +#define CSR_PSKEY_USR4 0x028e /* uint16[] */ +#define CSR_PSKEY_USR5 0x028f /* uint16[] */ +#define CSR_PSKEY_USR6 0x0290 /* uint16[] */ +#define CSR_PSKEY_USR7 0x0291 /* uint16[] */ +#define CSR_PSKEY_USR8 0x0292 /* uint16[] */ +#define CSR_PSKEY_USR9 0x0293 /* uint16[] */ +#define CSR_PSKEY_USR10 0x0294 /* uint16[] */ +#define CSR_PSKEY_USR11 0x0295 /* uint16[] */ +#define CSR_PSKEY_USR12 0x0296 /* uint16[] */ +#define CSR_PSKEY_USR13 0x0297 /* uint16[] */ +#define CSR_PSKEY_USR14 0x0298 /* uint16[] */ +#define CSR_PSKEY_USR15 0x0299 /* uint16[] */ +#define CSR_PSKEY_USR16 0x029a /* uint16[] */ +#define CSR_PSKEY_USR17 0x029b /* uint16[] */ +#define CSR_PSKEY_USR18 0x029c /* uint16[] */ +#define CSR_PSKEY_USR19 0x029d /* uint16[] */ +#define CSR_PSKEY_USR20 0x029e /* uint16[] */ +#define CSR_PSKEY_USR21 0x029f /* uint16[] */ +#define CSR_PSKEY_USR22 0x02a0 /* uint16[] */ +#define CSR_PSKEY_USR23 0x02a1 /* uint16[] */ +#define CSR_PSKEY_USR24 0x02a2 /* uint16[] */ +#define CSR_PSKEY_USR25 0x02a3 /* uint16[] */ +#define CSR_PSKEY_USR26 0x02a4 /* uint16[] */ +#define CSR_PSKEY_USR27 0x02a5 /* uint16[] */ +#define CSR_PSKEY_USR28 0x02a6 /* uint16[] */ +#define CSR_PSKEY_USR29 0x02a7 /* uint16[] */ +#define CSR_PSKEY_USR30 0x02a8 /* uint16[] */ +#define CSR_PSKEY_USR31 0x02a9 /* uint16[] */ +#define CSR_PSKEY_USR32 0x02aa /* uint16[] */ +#define CSR_PSKEY_USR33 0x02ab /* uint16[] */ +#define CSR_PSKEY_USR34 0x02ac /* uint16[] */ +#define CSR_PSKEY_USR35 0x02ad /* uint16[] */ +#define CSR_PSKEY_USR36 0x02ae /* uint16[] */ +#define CSR_PSKEY_USR37 0x02af /* uint16[] */ +#define CSR_PSKEY_USR38 0x02b0 /* uint16[] */ +#define CSR_PSKEY_USR39 0x02b1 /* uint16[] */ +#define CSR_PSKEY_USR40 0x02b2 /* uint16[] */ +#define CSR_PSKEY_USR41 0x02b3 /* uint16[] */ +#define CSR_PSKEY_USR42 0x02b4 /* uint16[] */ +#define CSR_PSKEY_USR43 0x02b5 /* uint16[] */ +#define CSR_PSKEY_USR44 0x02b6 /* uint16[] */ +#define CSR_PSKEY_USR45 0x02b7 /* uint16[] */ +#define CSR_PSKEY_USR46 0x02b8 /* uint16[] */ +#define CSR_PSKEY_USR47 0x02b9 /* uint16[] */ +#define CSR_PSKEY_USR48 0x02ba /* uint16[] */ +#define CSR_PSKEY_USR49 0x02bb /* uint16[] */ +#define CSR_PSKEY_USB_VERSION 0x02bc /* uint16 */ +#define CSR_PSKEY_USB_DEVICE_CLASS_CODES 0x02bd /* usbclass */ +#define CSR_PSKEY_USB_VENDOR_ID 0x02be /* uint16 */ +#define CSR_PSKEY_USB_PRODUCT_ID 0x02bf /* uint16 */ +#define CSR_PSKEY_USB_MANUF_STRING 0x02c1 /* unicodestring */ +#define CSR_PSKEY_USB_PRODUCT_STRING 0x02c2 /* unicodestring */ +#define CSR_PSKEY_USB_SERIAL_NUMBER_STRING 0x02c3 /* unicodestring */ +#define CSR_PSKEY_USB_CONFIG_STRING 0x02c4 /* unicodestring */ +#define CSR_PSKEY_USB_ATTRIBUTES 0x02c5 /* uint8 */ +#define CSR_PSKEY_USB_MAX_POWER 0x02c6 /* uint16 */ +#define CSR_PSKEY_USB_BT_IF_CLASS_CODES 0x02c7 /* usbclass */ +#define CSR_PSKEY_USB_LANGID 0x02c9 /* uint16 */ +#define CSR_PSKEY_USB_DFU_CLASS_CODES 0x02ca /* usbclass */ +#define CSR_PSKEY_USB_DFU_PRODUCT_ID 0x02cb /* uint16 */ +#define CSR_PSKEY_USB_PIO_DETACH 0x02ce /* uint16 */ +#define CSR_PSKEY_USB_PIO_WAKEUP 0x02cf /* uint16 */ +#define CSR_PSKEY_USB_PIO_PULLUP 0x02d0 /* uint16 */ +#define CSR_PSKEY_USB_PIO_VBUS 0x02d1 /* uint16 */ +#define CSR_PSKEY_USB_PIO_WAKE_TIMEOUT 0x02d2 /* uint16 */ +#define CSR_PSKEY_USB_PIO_RESUME 0x02d3 /* uint16 */ +#define CSR_PSKEY_USB_BT_SCO_IF_CLASS_CODES 0x02d4 /* usbclass */ +#define CSR_PSKEY_USB_SUSPEND_PIO_LEVEL 0x02d5 /* uint16 */ +#define CSR_PSKEY_USB_SUSPEND_PIO_DIR 0x02d6 /* uint16 */ +#define CSR_PSKEY_USB_SUSPEND_PIO_MASK 0x02d7 /* uint16 */ +#define CSR_PSKEY_USB_ENDPOINT_0_MAX_PACKET_SIZE 0x02d8 /* uint8 */ +#define CSR_PSKEY_USB_CONFIG 0x02d9 /* uint16 */ +#define CSR_PSKEY_RADIOTEST_ATTEN_INIT 0x0320 /* uint16 */ +#define CSR_PSKEY_RADIOTEST_FIRST_TRIM_TIME 0x0326 /* TIME */ +#define CSR_PSKEY_RADIOTEST_SUBSEQUENT_TRIM_TIME 0x0327 /* TIME */ +#define CSR_PSKEY_RADIOTEST_LO_LVL_TRIM_ENABLE 0x0328 /* bool */ +#define CSR_PSKEY_RADIOTEST_DISABLE_MODULATION 0x032c /* bool */ +#define CSR_PSKEY_RFCOMM_FCON_THRESHOLD 0x0352 /* uint16 */ +#define CSR_PSKEY_RFCOMM_FCOFF_THRESHOLD 0x0353 /* uint16 */ +#define CSR_PSKEY_IPV6_STATIC_ADDR 0x0354 /* uint16[] */ +#define CSR_PSKEY_IPV4_STATIC_ADDR 0x0355 /* uint32 */ +#define CSR_PSKEY_IPV6_STATIC_PREFIX_LEN 0x0356 /* uint8 */ +#define CSR_PSKEY_IPV6_STATIC_ROUTER_ADDR 0x0357 /* uint16[] */ +#define CSR_PSKEY_IPV4_STATIC_SUBNET_MASK 0x0358 /* uint32 */ +#define CSR_PSKEY_IPV4_STATIC_ROUTER_ADDR 0x0359 /* uint32 */ +#define CSR_PSKEY_MDNS_NAME 0x035a /* char[] */ +#define CSR_PSKEY_FIXED_PIN 0x035b /* uint8[] */ +#define CSR_PSKEY_MDNS_PORT 0x035c /* uint16 */ +#define CSR_PSKEY_MDNS_TTL 0x035d /* uint8 */ +#define CSR_PSKEY_MDNS_IPV4_ADDR 0x035e /* uint32 */ +#define CSR_PSKEY_ARP_CACHE_TIMEOUT 0x035f /* uint16 */ +#define CSR_PSKEY_HFP_POWER_TABLE 0x0360 /* uint16[] */ +#define CSR_PSKEY_DRAIN_BORE_TIMER_COUNTERS 0x03e7 /* uint32[] */ +#define CSR_PSKEY_DRAIN_BORE_COUNTERS 0x03e6 /* uint32[] */ +#define CSR_PSKEY_LOOP_FILTER_TRIM 0x03e4 /* uint16 */ +#define CSR_PSKEY_DRAIN_BORE_CURRENT_PEAK 0x03e3 /* uint32[] */ +#define CSR_PSKEY_VM_E2_CACHE_LIMIT 0x03e2 /* uint16 */ +#define CSR_PSKEY_FORCE_16MHZ_REF_PIO 0x03e1 /* uint16 */ +#define CSR_PSKEY_CDMA_LO_REF_LIMITS 0x03df /* uint16 */ +#define CSR_PSKEY_CDMA_LO_ERROR_LIMITS 0x03de /* uint16 */ +#define CSR_PSKEY_CLOCK_STARTUP_DELAY 0x03dd /* uint16 */ +#define CSR_PSKEY_DEEP_SLEEP_CORRECTION_FACTOR 0x03dc /* int16 */ +#define CSR_PSKEY_TEMPERATURE_CALIBRATION 0x03db /* temperature_calibration */ +#define CSR_PSKEY_TEMPERATURE_VS_DELTA_INTERNAL_PA 0x03da /* temperature_calibration[] */ +#define CSR_PSKEY_TEMPERATURE_VS_DELTA_TX_PRE_LVL 0x03d9 /* temperature_calibration[] */ +#define CSR_PSKEY_TEMPERATURE_VS_DELTA_TX_BB 0x03d8 /* temperature_calibration[] */ +#define CSR_PSKEY_TEMPERATURE_VS_DELTA_ANA_FTRIM 0x03d7 /* temperature_calibration[] */ +#define CSR_PSKEY_TEST_DELTA_OFFSET 0x03d6 /* uint16 */ +#define CSR_PSKEY_RX_DYNAMIC_LVL_OFFSET 0x03d4 /* uint16 */ +#define CSR_PSKEY_TEST_FORCE_OFFSET 0x03d3 /* bool */ +#define CSR_PSKEY_RF_TRAP_BAD_DIVISION_RATIOS 0x03cf /* uint16 */ +#define CSR_PSKEY_RADIOTEST_CDMA_LO_REF_LIMITS 0x03ce /* uint16 */ +#define CSR_PSKEY_INITIAL_BOOTMODE 0x03cd /* int16 */ +#define CSR_PSKEY_ONCHIP_HCI_CLIENT 0x03cc /* bool */ +#define CSR_PSKEY_RX_ATTEN_BACKOFF 0x03ca /* uint16 */ +#define CSR_PSKEY_RX_ATTEN_UPDATE_RATE 0x03c9 /* uint16 */ +#define CSR_PSKEY_SYNTH_TXRX_THRESHOLDS 0x03c7 /* uint16 */ +#define CSR_PSKEY_MIN_WAIT_STATES 0x03c6 /* uint16 */ +#define CSR_PSKEY_RSSI_CORRECTION 0x03c5 /* int8 */ +#define CSR_PSKEY_SCHED_THROTTLE_TIMEOUT 0x03c4 /* TIME */ +#define CSR_PSKEY_DEEP_SLEEP_USE_EXTERNAL_CLOCK 0x03c3 /* bool */ +#define CSR_PSKEY_TRIM_RADIO_FILTERS 0x03c2 /* uint16 */ +#define CSR_PSKEY_TRANSMIT_OFFSET 0x03c1 /* int16 */ +#define CSR_PSKEY_USB_VM_CONTROL 0x03c0 /* bool */ +#define CSR_PSKEY_MR_ANA_RX_FTRIM 0x03bf /* uint16 */ +#define CSR_PSKEY_I2C_CONFIG 0x03be /* uint16 */ +#define CSR_PSKEY_IQ_LVL_RX 0x03bd /* uint16 */ +#define CSR_PSKEY_MR_TX_FILTER_CONFIG 0x03bb /* uint32 */ +#define CSR_PSKEY_MR_TX_CONFIG2 0x03ba /* uint16 */ +#define CSR_PSKEY_USB_DONT_RESET_BOOTMODE_ON_HOST_RESET 0x03b9 /* bool */ +#define CSR_PSKEY_LC_USE_THROTTLING 0x03b8 /* bool */ +#define CSR_PSKEY_CHARGER_TRIM 0x03b7 /* uint16 */ +#define CSR_PSKEY_CLOCK_REQUEST_FEATURES 0x03b6 /* uint16 */ +#define CSR_PSKEY_TRANSMIT_OFFSET_CLASS1 0x03b4 /* int16 */ +#define CSR_PSKEY_TX_AVOID_PA_CLASS1_PIO 0x03b3 /* uint16 */ +#define CSR_PSKEY_MR_PIO_CONFIG 0x03b2 /* uint16 */ +#define CSR_PSKEY_UART_CONFIG2 0x03b1 /* uint8 */ +#define CSR_PSKEY_CLASS1_IQ_LVL 0x03b0 /* uint16 */ +#define CSR_PSKEY_CLASS1_TX_CONFIG2 0x03af /* uint16 */ +#define CSR_PSKEY_TEMPERATURE_VS_DELTA_INTERNAL_PA_CLASS1 0x03ae /* temperature_calibration[] */ +#define CSR_PSKEY_TEMPERATURE_VS_DELTA_EXTERNAL_PA_CLASS1 0x03ad /* temperature_calibration[] */ +#define CSR_PSKEY_TEMPERATURE_VS_DELTA_TX_PRE_LVL_MR 0x03ac /* temperature_calibration[] */ +#define CSR_PSKEY_TEMPERATURE_VS_DELTA_TX_BB_MR_HEADER 0x03ab /* temperature_calibration[] */ +#define CSR_PSKEY_TEMPERATURE_VS_DELTA_TX_BB_MR_PAYLOAD 0x03aa /* temperature_calibration[] */ +#define CSR_PSKEY_RX_MR_EQ_TAPS 0x03a9 /* uint16[] */ +#define CSR_PSKEY_TX_PRE_LVL_CLASS1 0x03a8 /* uint8 */ +#define CSR_PSKEY_ANALOGUE_ATTENUATOR 0x03a7 /* bool */ +#define CSR_PSKEY_MR_RX_FILTER_TRIM 0x03a6 /* uint16 */ +#define CSR_PSKEY_MR_RX_FILTER_RESPONSE 0x03a5 /* int16[] */ +#define CSR_PSKEY_PIO_WAKEUP_STATE 0x039f /* uint16 */ +#define CSR_PSKEY_MR_TX_IF_ATTEN_OFF_TEMP 0x0394 /* int16 */ +#define CSR_PSKEY_LO_DIV_LATCH_BYPASS 0x0393 /* bool */ +#define CSR_PSKEY_LO_VCO_STANDBY 0x0392 /* bool */ +#define CSR_PSKEY_SLOW_CLOCK_FILTER_SHIFT 0x0391 /* uint16 */ +#define CSR_PSKEY_SLOW_CLOCK_FILTER_DIVIDER 0x0390 /* uint16 */ +#define CSR_PSKEY_USB_ATTRIBUTES_POWER 0x03f2 /* bool */ +#define CSR_PSKEY_USB_ATTRIBUTES_WAKEUP 0x03f3 /* bool */ +#define CSR_PSKEY_DFU_ATTRIBUTES_MANIFESTATION_TOLERANT 0x03f4 /* bool */ +#define CSR_PSKEY_DFU_ATTRIBUTES_CAN_UPLOAD 0x03f5 /* bool */ +#define CSR_PSKEY_DFU_ATTRIBUTES_CAN_DOWNLOAD 0x03f6 /* bool */ +#define CSR_PSKEY_UART_CONFIG_STOP_BITS 0x03fc /* bool */ +#define CSR_PSKEY_UART_CONFIG_PARITY_BIT 0x03fd /* uint16 */ +#define CSR_PSKEY_UART_CONFIG_FLOW_CTRL_EN 0x03fe /* bool */ +#define CSR_PSKEY_UART_CONFIG_RTS_AUTO_EN 0x03ff /* bool */ +#define CSR_PSKEY_UART_CONFIG_RTS 0x0400 /* bool */ +#define CSR_PSKEY_UART_CONFIG_TX_ZERO_EN 0x0401 /* bool */ +#define CSR_PSKEY_UART_CONFIG_NON_BCSP_EN 0x0402 /* bool */ +#define CSR_PSKEY_UART_CONFIG_RX_RATE_DELAY 0x0403 /* uint16 */ +#define CSR_PSKEY_UART_SEQ_TIMEOUT 0x0405 /* uint16 */ +#define CSR_PSKEY_UART_SEQ_RETRIES 0x0406 /* uint16 */ +#define CSR_PSKEY_UART_SEQ_WINSIZE 0x0407 /* uint16 */ +#define CSR_PSKEY_UART_USE_CRC_ON_TX 0x0408 /* bool */ +#define CSR_PSKEY_UART_HOST_INITIAL_STATE 0x0409 /* hwakeup_state */ +#define CSR_PSKEY_UART_HOST_ATTENTION_SPAN 0x040a /* uint16 */ +#define CSR_PSKEY_UART_HOST_WAKEUP_TIME 0x040b /* uint16 */ +#define CSR_PSKEY_UART_HOST_WAKEUP_WAIT 0x040c /* uint16 */ +#define CSR_PSKEY_BCSP_LM_MODE 0x0410 /* uint16 */ +#define CSR_PSKEY_BCSP_LM_SYNC_RETRIES 0x0411 /* uint16 */ +#define CSR_PSKEY_BCSP_LM_TSHY 0x0412 /* uint16 */ +#define CSR_PSKEY_UART_DFU_CONFIG_STOP_BITS 0x0417 /* bool */ +#define CSR_PSKEY_UART_DFU_CONFIG_PARITY_BIT 0x0418 /* uint16 */ +#define CSR_PSKEY_UART_DFU_CONFIG_FLOW_CTRL_EN 0x0419 /* bool */ +#define CSR_PSKEY_UART_DFU_CONFIG_RTS_AUTO_EN 0x041a /* bool */ +#define CSR_PSKEY_UART_DFU_CONFIG_RTS 0x041b /* bool */ +#define CSR_PSKEY_UART_DFU_CONFIG_TX_ZERO_EN 0x041c /* bool */ +#define CSR_PSKEY_UART_DFU_CONFIG_NON_BCSP_EN 0x041d /* bool */ +#define CSR_PSKEY_UART_DFU_CONFIG_RX_RATE_DELAY 0x041e /* uint16 */ +#define CSR_PSKEY_AMUX_AIO0 0x041f /* ana_amux_sel */ +#define CSR_PSKEY_AMUX_AIO1 0x0420 /* ana_amux_sel */ +#define CSR_PSKEY_AMUX_AIO2 0x0421 /* ana_amux_sel */ +#define CSR_PSKEY_AMUX_AIO3 0x0422 /* ana_amux_sel */ +#define CSR_PSKEY_LOCAL_NAME_SIMPLIFIED 0x0423 /* local_name_complete */ +#define CSR_PSKEY_EXTENDED_STUB 0x2001 /* uint16 */ + +char *csr_builddeftostr(uint16_t def); +char *csr_buildidtostr(uint16_t id); +char *csr_chipvertostr(uint16_t ver, uint16_t rev); +char *csr_pskeytostr(uint16_t pskey); +char *csr_pskeytoval(uint16_t pskey); + +int csr_open_hci(char *device); +int csr_read_hci(uint16_t varid, uint8_t *value, uint16_t length); +int csr_write_hci(uint16_t varid, uint8_t *value, uint16_t length); +void csr_close_hci(void); + +int csr_open_usb(char *device); +int csr_read_usb(uint16_t varid, uint8_t *value, uint16_t length); +int csr_write_usb(uint16_t varid, uint8_t *value, uint16_t length); +void csr_close_usb(void); + +int csr_open_bcsp(char *device, speed_t bcsp_rate); +int csr_read_bcsp(uint16_t varid, uint8_t *value, uint16_t length); +int csr_write_bcsp(uint16_t varid, uint8_t *value, uint16_t length); +void csr_close_bcsp(void); + +int csr_open_h4(char *device); +int csr_read_h4(uint16_t varid, uint8_t *value, uint16_t length); +int csr_write_h4(uint16_t varid, uint8_t *value, uint16_t length); +void csr_close_h4(void); + +int csr_open_3wire(char *device); +int csr_read_3wire(uint16_t varid, uint8_t *value, uint16_t length); +int csr_write_3wire(uint16_t varid, uint8_t *value, uint16_t length); +void csr_close_3wire(void); + +int csr_write_varid_valueless(int dd, uint16_t seqnum, uint16_t varid); +int csr_write_varid_complex(int dd, uint16_t seqnum, uint16_t varid, uint8_t *value, uint16_t length); +int csr_read_varid_complex(int dd, uint16_t seqnum, uint16_t varid, uint8_t *value, uint16_t length); +int csr_read_varid_uint16(int dd, uint16_t seqnum, uint16_t varid, uint16_t *value); +int csr_read_varid_uint32(int dd, uint16_t seqnum, uint16_t varid, uint32_t *value); +int csr_read_pskey_complex(int dd, uint16_t seqnum, uint16_t pskey, uint16_t stores, uint8_t *value, uint16_t length); +int csr_write_pskey_complex(int dd, uint16_t seqnum, uint16_t pskey, uint16_t stores, uint8_t *value, uint16_t length); +int csr_read_pskey_uint16(int dd, uint16_t seqnum, uint16_t pskey, uint16_t stores, uint16_t *value); +int csr_write_pskey_uint16(int dd, uint16_t seqnum, uint16_t pskey, uint16_t stores, uint16_t value); +int csr_read_pskey_uint32(int dd, uint16_t seqnum, uint16_t pskey, uint16_t stores, uint32_t *value); +int csr_write_pskey_uint32(int dd, uint16_t seqnum, uint16_t pskey, uint16_t stores, uint32_t value); + +int psr_put(uint16_t pskey, uint8_t *value, uint16_t size); +int psr_get(uint16_t *pskey, uint8_t *value, uint16_t *size); +int psr_read(const char *filename); +int psr_print(void); diff --git a/drive-sdk/deps/bzle/tools/hciconfig.c b/drive-sdk/deps/bzle/tools/hciconfig.c new file mode 100644 index 0000000..2ca4cba --- /dev/null +++ b/drive-sdk/deps/bzle/tools/hciconfig.c @@ -0,0 +1,2050 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2000-2001 Qualcomm Incorporated + * Copyright (C) 2002-2003 Maxim Krasnyansky + * Copyright (C) 2002-2010 Marcel Holtmann + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include "textfile.h" +#include "csr.h" + +static struct hci_dev_info di; +static int all; + +static void print_dev_hdr(struct hci_dev_info *di); +static void print_dev_info(int ctl, struct hci_dev_info *di); + +static void print_dev_list(int ctl, int flags) +{ + struct hci_dev_list_req *dl; + struct hci_dev_req *dr; + int i; + + if (!(dl = malloc(HCI_MAX_DEV * sizeof(struct hci_dev_req) + + sizeof(uint16_t)))) { + perror("Can't allocate memory"); + exit(1); + } + dl->dev_num = HCI_MAX_DEV; + dr = dl->dev_req; + + if (ioctl(ctl, HCIGETDEVLIST, (void *) dl) < 0) { + perror("Can't get device list"); + exit(1); + } + + for (i = 0; i< dl->dev_num; i++) { + di.dev_id = (dr+i)->dev_id; + if (ioctl(ctl, HCIGETDEVINFO, (void *) &di) < 0) + continue; + if (hci_test_bit(HCI_RAW, &di.flags) && + !bacmp(&di.bdaddr, BDADDR_ANY)) { + int dd = hci_open_dev(di.dev_id); + hci_read_bd_addr(dd, &di.bdaddr, 1000); + hci_close_dev(dd); + } + print_dev_info(ctl, &di); + } +} + +static void print_pkt_type(struct hci_dev_info *di) +{ + char *str; + str = hci_ptypetostr(di->pkt_type); + printf("\tPacket type: %s\n", str); + bt_free(str); +} + +static void print_link_policy(struct hci_dev_info *di) +{ + printf("\tLink policy: %s\n", hci_lptostr(di->link_policy)); +} + +static void print_link_mode(struct hci_dev_info *di) +{ + char *str; + str = hci_lmtostr(di->link_mode); + printf("\tLink mode: %s\n", str); + bt_free(str); +} + +static void print_dev_features(struct hci_dev_info *di, int format) +{ + printf("\tFeatures: 0x%2.2x 0x%2.2x 0x%2.2x 0x%2.2x " + "0x%2.2x 0x%2.2x 0x%2.2x 0x%2.2x\n", + di->features[0], di->features[1], di->features[2], + di->features[3], di->features[4], di->features[5], + di->features[6], di->features[7]); + + if (format) { + char *tmp = lmp_featurestostr(di->features, "\t\t", 63); + printf("%s\n", tmp); + bt_free(tmp); + } +} + +static void print_le_states(uint64_t states) +{ + int i; + const char *le_states[] = { + "Non-connectable Advertising State" , + "Scannable Advertising State", + "Connectable Advertising State", + "Directed Advertising State", + "Passive Scanning State", + "Active Scanning State", + "Initiating State/Connection State in Master Role", + "Connection State in the Slave Role", + "Non-connectable Advertising State and Passive Scanning State combination", + "Scannable Advertising State and Passive Scanning State combination", + "Connectable Advertising State and Passive Scanning State combination", + "Directed Advertising State and Passive Scanning State combination", + "Non-connectable Advertising State and Active Scanning State combination", + "Scannable Advertising State and Active Scanning State combination", + "Connectable Advertising State and Active Scanning State combination", + "Directed Advertising State and Active Scanning State combination", + "Non-connectable Advertising State and Initiating State combination", + "Scannable Advertising State and Initiating State combination", + "Non-connectable Advertising State and Master Role combination", + "Scannable Advertising State and Master Role combination", + "Non-connectable Advertising State and Slave Role combination", + "Scannable Advertising State and Slave Role combination", + "Passive Scanning State and Initiating State combination", + "Active Scanning State and Initiating State combination", + "Passive Scanning State and Master Role combination", + "Active Scanning State and Master Role combination", + "Passive Scanning State and Slave Role combination", + "Active Scanning State and Slave Role combination", + "Initiating State and Master Role combination/Master Role and Master Role combination", + NULL + }; + + printf("Supported link layer states:\n"); + for (i = 0; le_states[i]; i++) { + const char *status; + + status = states & (1 << i) ? "YES" : "NO "; + printf("\t%s %s\n", status, le_states[i]); + } +} + +static void cmd_rstat(int ctl, int hdev, char *opt) +{ + /* Reset HCI device stat counters */ + if (ioctl(ctl, HCIDEVRESTAT, hdev) < 0) { + fprintf(stderr, "Can't reset stats counters hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } +} + +static void cmd_scan(int ctl, int hdev, char *opt) +{ + struct hci_dev_req dr; + + dr.dev_id = hdev; + dr.dev_opt = SCAN_DISABLED; + if (!strcmp(opt, "iscan")) + dr.dev_opt = SCAN_INQUIRY; + else if (!strcmp(opt, "pscan")) + dr.dev_opt = SCAN_PAGE; + else if (!strcmp(opt, "piscan")) + dr.dev_opt = SCAN_PAGE | SCAN_INQUIRY; + + if (ioctl(ctl, HCISETSCAN, (unsigned long) &dr) < 0) { + fprintf(stderr, "Can't set scan mode on hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } +} + +static void cmd_le_addr(int ctl, int hdev, char *opt) +{ + struct hci_request rq; + le_set_random_address_cp cp; + uint8_t status; + int dd, err, ret; + + if (!opt) + return; + + if (hdev < 0) + hdev = hci_get_route(NULL); + + dd = hci_open_dev(hdev); + if (dd < 0) { + err = -errno; + fprintf(stderr, "Could not open device: %s(%d)\n", + strerror(-err), -err); + exit(1); + } + + memset(&cp, 0, sizeof(cp)); + + str2ba(opt, &cp.bdaddr); + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_LE_CTL; + rq.ocf = OCF_LE_SET_RANDOM_ADDRESS; + rq.cparam = &cp; + rq.clen = LE_SET_RANDOM_ADDRESS_CP_SIZE; + rq.rparam = &status; + rq.rlen = 1; + + ret = hci_send_req(dd, &rq, 1000); + if (status || ret < 0) { + err = -errno; + fprintf(stderr, "Can't set random address for hci%d: " + "%s (%d)\n", hdev, strerror(-err), -err); + } + + hci_close_dev(dd); +} + +static void cmd_le_adv(int ctl, int hdev, char *opt) +{ + struct hci_request rq; + le_set_advertise_enable_cp advertise_cp; + le_set_advertising_parameters_cp adv_params_cp; + uint8_t status; + int dd, ret; + + if (hdev < 0) + hdev = hci_get_route(NULL); + + dd = hci_open_dev(hdev); + if (dd < 0) { + perror("Could not open device"); + exit(1); + } + + memset(&adv_params_cp, 0, sizeof(adv_params_cp)); + adv_params_cp.min_interval = htobs(0x0800); + adv_params_cp.max_interval = htobs(0x0800); + if (opt) + adv_params_cp.advtype = atoi(opt); + adv_params_cp.chan_map = 7; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_LE_CTL; + rq.ocf = OCF_LE_SET_ADVERTISING_PARAMETERS; + rq.cparam = &adv_params_cp; + rq.clen = LE_SET_ADVERTISING_PARAMETERS_CP_SIZE; + rq.rparam = &status; + rq.rlen = 1; + + ret = hci_send_req(dd, &rq, 1000); + if (ret < 0) + goto done; + + memset(&advertise_cp, 0, sizeof(advertise_cp)); + advertise_cp.enable = 0x01; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_LE_CTL; + rq.ocf = OCF_LE_SET_ADVERTISE_ENABLE; + rq.cparam = &advertise_cp; + rq.clen = LE_SET_ADVERTISE_ENABLE_CP_SIZE; + rq.rparam = &status; + rq.rlen = 1; + + ret = hci_send_req(dd, &rq, 1000); + +done: + hci_close_dev(dd); + + if (ret < 0) { + fprintf(stderr, "Can't set advertise mode on hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + + if (status) { + fprintf(stderr, + "LE set advertise enable on hci%d returned status %d\n", + hdev, status); + exit(1); + } +} + +static void cmd_no_le_adv(int ctl, int hdev, char *opt) +{ + struct hci_request rq; + le_set_advertise_enable_cp advertise_cp; + uint8_t status; + int dd, ret; + + if (hdev < 0) + hdev = hci_get_route(NULL); + + dd = hci_open_dev(hdev); + if (dd < 0) { + perror("Could not open device"); + exit(1); + } + + memset(&advertise_cp, 0, sizeof(advertise_cp)); + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_LE_CTL; + rq.ocf = OCF_LE_SET_ADVERTISE_ENABLE; + rq.cparam = &advertise_cp; + rq.clen = LE_SET_ADVERTISE_ENABLE_CP_SIZE; + rq.rparam = &status; + rq.rlen = 1; + + ret = hci_send_req(dd, &rq, 1000); + + hci_close_dev(dd); + + if (ret < 0) { + fprintf(stderr, "Can't set advertise mode on hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + + if (status) { + fprintf(stderr, "LE set advertise enable on hci%d returned status %d\n", + hdev, status); + exit(1); + } +} + +static void cmd_le_states(int ctl, int hdev, char *opt) +{ + le_read_supported_states_rp rp; + struct hci_request rq; + int err, dd; + + if (hdev < 0) + hdev = hci_get_route(NULL); + + dd = hci_open_dev(hdev); + if (dd < 0) { + fprintf(stderr, "Can't open device hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + + memset(&rp, 0, sizeof(rp)); + memset(&rq, 0, sizeof(rq)); + + rq.ogf = OGF_LE_CTL; + rq.ocf = OCF_LE_READ_SUPPORTED_STATES; + rq.rparam = &rp; + rq.rlen = LE_READ_SUPPORTED_STATES_RP_SIZE; + + err = hci_send_req(dd, &rq, 1000); + + hci_close_dev(dd); + + if (err < 0) { + fprintf(stderr, "Can't read LE supported states on hci%d:" + " %s(%d)\n", hdev, strerror(errno), errno); + exit(1); + } + + if (rp.status) { + fprintf(stderr, "Read LE supported states on hci%d" + " returned status %d\n", hdev, rp.status); + exit(1); + } + + print_le_states(rp.states); +} + +static void cmd_iac(int ctl, int hdev, char *opt) +{ + int s = hci_open_dev(hdev); + + if (s < 0) { + fprintf(stderr, "Can't open device hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + if (opt) { + int l = strtoul(opt, 0, 16); + uint8_t lap[3]; + if (!strcasecmp(opt, "giac")) { + l = 0x9e8b33; + } else if (!strcasecmp(opt, "liac")) { + l = 0x9e8b00; + } else if (l < 0x9e8b00 || l > 0x9e8b3f) { + printf("Invalid access code 0x%x\n", l); + exit(1); + } + lap[0] = (l & 0xff); + lap[1] = (l >> 8) & 0xff; + lap[2] = (l >> 16) & 0xff; + if (hci_write_current_iac_lap(s, 1, lap, 1000) < 0) { + printf("Failed to set IAC on hci%d: %s\n", hdev, strerror(errno)); + exit(1); + } + } else { + uint8_t lap[3 * MAX_IAC_LAP]; + int i, j; + uint8_t n; + if (hci_read_current_iac_lap(s, &n, lap, 1000) < 0) { + printf("Failed to read IAC from hci%d: %s\n", hdev, strerror(errno)); + exit(1); + } + print_dev_hdr(&di); + printf("\tIAC: "); + for (i = 0; i < n; i++) { + printf("0x"); + for (j = 3; j--; ) + printf("%02x", lap[j + 3 * i]); + if (i < n - 1) + printf(", "); + } + printf("\n"); + } + close(s); +} + +static void cmd_auth(int ctl, int hdev, char *opt) +{ + struct hci_dev_req dr; + + dr.dev_id = hdev; + if (!strcmp(opt, "auth")) + dr.dev_opt = AUTH_ENABLED; + else + dr.dev_opt = AUTH_DISABLED; + + if (ioctl(ctl, HCISETAUTH, (unsigned long) &dr) < 0) { + fprintf(stderr, "Can't set auth on hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } +} + +static void cmd_encrypt(int ctl, int hdev, char *opt) +{ + struct hci_dev_req dr; + + dr.dev_id = hdev; + if (!strcmp(opt, "encrypt")) + dr.dev_opt = ENCRYPT_P2P; + else + dr.dev_opt = ENCRYPT_DISABLED; + + if (ioctl(ctl, HCISETENCRYPT, (unsigned long) &dr) < 0) { + fprintf(stderr, "Can't set encrypt on hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } +} + +static void cmd_up(int ctl, int hdev, char *opt) +{ + /* Start HCI device */ + if (ioctl(ctl, HCIDEVUP, hdev) < 0) { + if (errno == EALREADY) + return; + fprintf(stderr, "Can't init device hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } +} + +static void cmd_down(int ctl, int hdev, char *opt) +{ + /* Stop HCI device */ + if (ioctl(ctl, HCIDEVDOWN, hdev) < 0) { + fprintf(stderr, "Can't down device hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } +} + +static void cmd_reset(int ctl, int hdev, char *opt) +{ + /* Reset HCI device */ +#if 0 + if (ioctl(ctl, HCIDEVRESET, hdev) < 0 ){ + fprintf(stderr, "Reset failed for device hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } +#endif + cmd_down(ctl, hdev, "down"); + cmd_up(ctl, hdev, "up"); +} + +static void cmd_ptype(int ctl, int hdev, char *opt) +{ + struct hci_dev_req dr; + + dr.dev_id = hdev; + + if (hci_strtoptype(opt, &dr.dev_opt)) { + if (ioctl(ctl, HCISETPTYPE, (unsigned long) &dr) < 0) { + fprintf(stderr, "Can't set pkttype on hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + } else { + print_dev_hdr(&di); + print_pkt_type(&di); + } +} + +static void cmd_lp(int ctl, int hdev, char *opt) +{ + struct hci_dev_req dr; + + dr.dev_id = hdev; + + if (hci_strtolp(opt, &dr.dev_opt)) { + if (ioctl(ctl, HCISETLINKPOL, (unsigned long) &dr) < 0) { + fprintf(stderr, "Can't set link policy on hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + } else { + print_dev_hdr(&di); + print_link_policy(&di); + } +} + +static void cmd_lm(int ctl, int hdev, char *opt) +{ + struct hci_dev_req dr; + + dr.dev_id = hdev; + + if (hci_strtolm(opt, &dr.dev_opt)) { + if (ioctl(ctl, HCISETLINKMODE, (unsigned long) &dr) < 0) { + fprintf(stderr, "Can't set default link mode on hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + } else { + print_dev_hdr(&di); + print_link_mode(&di); + } +} + +static void cmd_aclmtu(int ctl, int hdev, char *opt) +{ + struct hci_dev_req dr = { .dev_id = hdev }; + uint16_t mtu, mpkt; + + if (!opt) + return; + + if (sscanf(opt, "%4hu:%4hu", &mtu, &mpkt) != 2) + return; + + dr.dev_opt = htobl(htobs(mpkt) | (htobs(mtu) << 16)); + + if (ioctl(ctl, HCISETACLMTU, (unsigned long) &dr) < 0) { + fprintf(stderr, "Can't set ACL mtu on hci%d: %s(%d)\n", + hdev, strerror(errno), errno); + exit(1); + } +} + +static void cmd_scomtu(int ctl, int hdev, char *opt) +{ + struct hci_dev_req dr = { .dev_id = hdev }; + uint16_t mtu, mpkt; + + if (!opt) + return; + + if (sscanf(opt, "%4hu:%4hu", &mtu, &mpkt) != 2) + return; + + dr.dev_opt = htobl(htobs(mpkt) | (htobs(mtu) << 16)); + + if (ioctl(ctl, HCISETSCOMTU, (unsigned long) &dr) < 0) { + fprintf(stderr, "Can't set SCO mtu on hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } +} + +static void cmd_features(int ctl, int hdev, char *opt) +{ + uint8_t features[8], max_page = 0; + char *tmp; + int i, dd; + + if (!(di.features[7] & LMP_EXT_FEAT)) { + print_dev_hdr(&di); + print_dev_features(&di, 1); + return; + } + + dd = hci_open_dev(hdev); + if (dd < 0) { + fprintf(stderr, "Can't open device hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + + if (hci_read_local_ext_features(dd, 0, &max_page, features, 1000) < 0) { + fprintf(stderr, "Can't read extended features hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + + print_dev_hdr(&di); + printf("\tFeatures%s: 0x%2.2x 0x%2.2x 0x%2.2x 0x%2.2x " + "0x%2.2x 0x%2.2x 0x%2.2x 0x%2.2x\n", + (max_page > 0) ? " page 0" : "", + features[0], features[1], features[2], features[3], + features[4], features[5], features[6], features[7]); + + tmp = lmp_featurestostr(di.features, "\t\t", 63); + printf("%s\n", tmp); + bt_free(tmp); + + for (i = 1; i <= max_page; i++) { + if (hci_read_local_ext_features(dd, i, NULL, + features, 1000) < 0) + continue; + + printf("\tFeatures page %d: 0x%2.2x 0x%2.2x 0x%2.2x 0x%2.2x " + "0x%2.2x 0x%2.2x 0x%2.2x 0x%2.2x\n", i, + features[0], features[1], features[2], features[3], + features[4], features[5], features[6], features[7]); + } + + hci_close_dev(dd); +} + +static void cmd_name(int ctl, int hdev, char *opt) +{ + int dd; + + dd = hci_open_dev(hdev); + if (dd < 0) { + fprintf(stderr, "Can't open device hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + + if (opt) { + if (hci_write_local_name(dd, opt, 2000) < 0) { + fprintf(stderr, "Can't change local name on hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + } else { + char name[249]; + int i; + + if (hci_read_local_name(dd, sizeof(name), name, 1000) < 0) { + fprintf(stderr, "Can't read local name on hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + + for (i = 0; i < 248 && name[i]; i++) { + if ((unsigned char) name[i] < 32 || name[i] == 127) + name[i] = '.'; + } + + name[248] = '\0'; + + print_dev_hdr(&di); + printf("\tName: '%s'\n", name); + } + + hci_close_dev(dd); +} + +/* + * see http://www.bluetooth.org/assigned-numbers/baseband.htm --- all + * strings are reproduced verbatim + */ +static char *get_minor_device_name(int major, int minor) +{ + switch (major) { + case 0: /* misc */ + return ""; + case 1: /* computer */ + switch (minor) { + case 0: + return "Uncategorized"; + case 1: + return "Desktop workstation"; + case 2: + return "Server"; + case 3: + return "Laptop"; + case 4: + return "Handheld"; + case 5: + return "Palm"; + case 6: + return "Wearable"; + } + break; + case 2: /* phone */ + switch (minor) { + case 0: + return "Uncategorized"; + case 1: + return "Cellular"; + case 2: + return "Cordless"; + case 3: + return "Smart phone"; + case 4: + return "Wired modem or voice gateway"; + case 5: + return "Common ISDN Access"; + case 6: + return "Sim Card Reader"; + } + break; + case 3: /* lan access */ + if (minor == 0) + return "Uncategorized"; + switch (minor / 8) { + case 0: + return "Fully available"; + case 1: + return "1-17% utilized"; + case 2: + return "17-33% utilized"; + case 3: + return "33-50% utilized"; + case 4: + return "50-67% utilized"; + case 5: + return "67-83% utilized"; + case 6: + return "83-99% utilized"; + case 7: + return "No service available"; + } + break; + case 4: /* audio/video */ + switch (minor) { + case 0: + return "Uncategorized"; + case 1: + return "Device conforms to the Headset profile"; + case 2: + return "Hands-free"; + /* 3 is reserved */ + case 4: + return "Microphone"; + case 5: + return "Loudspeaker"; + case 6: + return "Headphones"; + case 7: + return "Portable Audio"; + case 8: + return "Car Audio"; + case 9: + return "Set-top box"; + case 10: + return "HiFi Audio Device"; + case 11: + return "VCR"; + case 12: + return "Video Camera"; + case 13: + return "Camcorder"; + case 14: + return "Video Monitor"; + case 15: + return "Video Display and Loudspeaker"; + case 16: + return "Video Conferencing"; + /* 17 is reserved */ + case 18: + return "Gaming/Toy"; + } + break; + case 5: /* peripheral */ { + static char cls_str[48]; + + cls_str[0] = '\0'; + + switch (minor & 48) { + case 16: + strncpy(cls_str, "Keyboard", sizeof(cls_str)); + break; + case 32: + strncpy(cls_str, "Pointing device", sizeof(cls_str)); + break; + case 48: + strncpy(cls_str, "Combo keyboard/pointing device", sizeof(cls_str)); + break; + } + if ((minor & 15) && (strlen(cls_str) > 0)) + strcat(cls_str, "/"); + + switch (minor & 15) { + case 0: + break; + case 1: + strncat(cls_str, "Joystick", + sizeof(cls_str) - strlen(cls_str) - 1); + break; + case 2: + strncat(cls_str, "Gamepad", + sizeof(cls_str) - strlen(cls_str) - 1); + break; + case 3: + strncat(cls_str, "Remote control", + sizeof(cls_str) - strlen(cls_str) - 1); + break; + case 4: + strncat(cls_str, "Sensing device", + sizeof(cls_str) - strlen(cls_str) - 1); + break; + case 5: + strncat(cls_str, "Digitizer tablet", + sizeof(cls_str) - strlen(cls_str) - 1); + break; + case 6: + strncat(cls_str, "Card reader", + sizeof(cls_str) - strlen(cls_str) - 1); + break; + default: + strncat(cls_str, "(reserved)", + sizeof(cls_str) - strlen(cls_str) - 1); + break; + } + if (strlen(cls_str) > 0) + return cls_str; + } + case 6: /* imaging */ + if (minor & 4) + return "Display"; + if (minor & 8) + return "Camera"; + if (minor & 16) + return "Scanner"; + if (minor & 32) + return "Printer"; + break; + case 7: /* wearable */ + switch (minor) { + case 1: + return "Wrist Watch"; + case 2: + return "Pager"; + case 3: + return "Jacket"; + case 4: + return "Helmet"; + case 5: + return "Glasses"; + } + break; + case 8: /* toy */ + switch (minor) { + case 1: + return "Robot"; + case 2: + return "Vehicle"; + case 3: + return "Doll / Action Figure"; + case 4: + return "Controller"; + case 5: + return "Game"; + } + break; + case 63: /* uncategorised */ + return ""; + } + return "Unknown (reserved) minor device class"; +} + +static void cmd_class(int ctl, int hdev, char *opt) +{ + static const char *services[] = { "Positioning", + "Networking", + "Rendering", + "Capturing", + "Object Transfer", + "Audio", + "Telephony", + "Information" }; + static const char *major_devices[] = { "Miscellaneous", + "Computer", + "Phone", + "LAN Access", + "Audio/Video", + "Peripheral", + "Imaging", + "Uncategorized" }; + int s = hci_open_dev(hdev); + + if (s < 0) { + fprintf(stderr, "Can't open device hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + if (opt) { + uint32_t cod = strtoul(opt, NULL, 16); + if (hci_write_class_of_dev(s, cod, 2000) < 0) { + fprintf(stderr, "Can't write local class of device on hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + } else { + uint8_t cls[3]; + if (hci_read_class_of_dev(s, cls, 1000) < 0) { + fprintf(stderr, "Can't read class of device on hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + print_dev_hdr(&di); + printf("\tClass: 0x%02x%02x%02x\n", cls[2], cls[1], cls[0]); + printf("\tService Classes: "); + if (cls[2]) { + unsigned int i; + int first = 1; + for (i = 0; i < (sizeof(services) / sizeof(*services)); i++) + if (cls[2] & (1 << i)) { + if (!first) + printf(", "); + printf("%s", services[i]); + first = 0; + } + } else + printf("Unspecified"); + printf("\n\tDevice Class: "); + if ((cls[1] & 0x1f) >= sizeof(major_devices) / sizeof(*major_devices)) + printf("Invalid Device Class!\n"); + else + printf("%s, %s\n", major_devices[cls[1] & 0x1f], + get_minor_device_name(cls[1] & 0x1f, cls[0] >> 2)); + } +} + +static void cmd_voice(int ctl, int hdev, char *opt) +{ + static char *icf[] = { "Linear", + "u-Law", + "A-Law", + "Reserved" }; + + static char *idf[] = { "1's complement", + "2's complement", + "Sign-Magnitude", + "Reserved" }; + + static char *iss[] = { "8 bit", + "16 bit" }; + + static char *acf[] = { "CVSD", + "u-Law", + "A-Law", + "Reserved" }; + + int s = hci_open_dev(hdev); + + if (s < 0) { + fprintf(stderr, "Can't open device hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + if (opt) { + uint16_t vs = htobs(strtoul(opt, NULL, 16)); + if (hci_write_voice_setting(s, vs, 2000) < 0) { + fprintf(stderr, "Can't write voice setting on hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + } else { + uint16_t vs; + uint8_t ic; + if (hci_read_voice_setting(s, &vs, 1000) < 0) { + fprintf(stderr, "Can't read voice setting on hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + vs = htobs(vs); + ic = (vs & 0x0300) >> 8; + print_dev_hdr(&di); + printf("\tVoice setting: 0x%04x%s\n", vs, + ((vs & 0x03fc) == 0x0060) ? " (Default Condition)" : ""); + printf("\tInput Coding: %s\n", icf[ic]); + printf("\tInput Data Format: %s\n", idf[(vs & 0xc0) >> 6]); + + if (!ic) { + printf("\tInput Sample Size: %s\n", + iss[(vs & 0x20) >> 5]); + printf("\t# of bits padding at MSB: %d\n", + (vs & 0x1c) >> 2); + } + printf("\tAir Coding Format: %s\n", acf[vs & 0x03]); + } +} + +static void cmd_delkey(int ctl, int hdev, char *opt) +{ + bdaddr_t bdaddr; + uint8_t all; + int dd; + + if (!opt) + return; + + dd = hci_open_dev(hdev); + if (dd < 0) { + fprintf(stderr, "Can't open device hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + + if (!strcasecmp(opt, "all")) { + bacpy(&bdaddr, BDADDR_ANY); + all = 1; + } else { + str2ba(opt, &bdaddr); + all = 0; + } + + if (hci_delete_stored_link_key(dd, &bdaddr, all, 1000) < 0) { + fprintf(stderr, "Can't delete stored link key on hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + + hci_close_dev(dd); +} + +static void cmd_oob_data(int ctl, int hdev, char *opt) +{ + uint8_t hash[16], randomizer[16]; + int i, dd; + + dd = hci_open_dev(hdev); + if (dd < 0) { + fprintf(stderr, "Can't open device hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + + if (hci_read_local_oob_data(dd, hash, randomizer, 1000) < 0) { + fprintf(stderr, "Can't read local OOB data on hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + + print_dev_hdr(&di); + printf("\tOOB Hash: "); + for (i = 0; i < 16; i++) + printf(" %02x", hash[i]); + printf("\n\tRandomizer:"); + for (i = 0; i < 16; i++) + printf(" %02x", randomizer[i]); + printf("\n"); + + hci_close_dev(dd); +} + +static void cmd_commands(int ctl, int hdev, char *opt) +{ + uint8_t cmds[64]; + char *str; + int i, n, dd; + + dd = hci_open_dev(hdev); + if (dd < 0) { + fprintf(stderr, "Can't open device hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + + if (hci_read_local_commands(dd, cmds, 1000) < 0) { + fprintf(stderr, "Can't read support commands on hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + + print_dev_hdr(&di); + for (i = 0; i < 64; i++) { + if (!cmds[i]) + continue; + + printf("%s Octet %-2d = 0x%02x (Bit", + i ? "\t\t ": "\tCommands:", i, cmds[i]); + for (n = 0; n < 8; n++) + if (cmds[i] & (1 << n)) + printf(" %d", n); + printf(")\n"); + } + + str = hci_commandstostr(cmds, "\t", 71); + printf("%s\n", str); + bt_free(str); + + hci_close_dev(dd); +} + +static void cmd_version(int ctl, int hdev, char *opt) +{ + struct hci_version ver; + char *hciver, *lmpver; + int dd; + + dd = hci_open_dev(hdev); + if (dd < 0) { + fprintf(stderr, "Can't open device hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + + if (hci_read_local_version(dd, &ver, 1000) < 0) { + fprintf(stderr, "Can't read version info hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + + hciver = hci_vertostr(ver.hci_ver); + if (((di.type & 0x30) >> 4) == HCI_BREDR) + lmpver = lmp_vertostr(ver.lmp_ver); + else + lmpver = pal_vertostr(ver.lmp_ver); + + print_dev_hdr(&di); + printf("\tHCI Version: %s (0x%x) Revision: 0x%x\n" + "\t%s Version: %s (0x%x) Subversion: 0x%x\n" + "\tManufacturer: %s (%d)\n", + hciver ? hciver : "n/a", ver.hci_ver, ver.hci_rev, + (((di.type & 0x30) >> 4) == HCI_BREDR) ? "LMP" : "PAL", + lmpver ? lmpver : "n/a", ver.lmp_ver, ver.lmp_subver, + bt_compidtostr(ver.manufacturer), ver.manufacturer); + + if (hciver) + bt_free(hciver); + if (lmpver) + bt_free(lmpver); + + hci_close_dev(dd); +} + +static void cmd_inq_tpl(int ctl, int hdev, char *opt) +{ + int dd; + + dd = hci_open_dev(hdev); + if (dd < 0) { + fprintf(stderr, "Can't open device hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + + if (opt) { + int8_t level = atoi(opt); + + if (hci_write_inquiry_transmit_power_level(dd, level, 2000) < 0) { + fprintf(stderr, "Can't set inquiry transmit power level on hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + } else { + int8_t level; + + if (hci_read_inq_response_tx_power_level(dd, &level, 1000) < 0) { + fprintf(stderr, "Can't read inquiry transmit power level on hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + + print_dev_hdr(&di); + printf("\tInquiry transmit power level: %d\n", level); + } + + hci_close_dev(dd); +} + +static void cmd_inq_mode(int ctl, int hdev, char *opt) +{ + int dd; + + dd = hci_open_dev(hdev); + if (dd < 0) { + fprintf(stderr, "Can't open device hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + + if (opt) { + uint8_t mode = atoi(opt); + + if (hci_write_inquiry_mode(dd, mode, 2000) < 0) { + fprintf(stderr, "Can't set inquiry mode on hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + } else { + uint8_t mode; + + if (hci_read_inquiry_mode(dd, &mode, 1000) < 0) { + fprintf(stderr, "Can't read inquiry mode on hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + + print_dev_hdr(&di); + printf("\tInquiry mode: "); + switch (mode) { + case 0: + printf("Standard Inquiry\n"); + break; + case 1: + printf("Inquiry with RSSI\n"); + break; + case 2: + printf("Inquiry with RSSI or Extended Inquiry\n"); + break; + default: + printf("Unknown (0x%02x)\n", mode); + break; + } + } + + hci_close_dev(dd); +} + +static void cmd_inq_data(int ctl, int hdev, char *opt) +{ + int i, dd; + + dd = hci_open_dev(hdev); + if (dd < 0) { + fprintf(stderr, "Can't open device hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + + if (opt) { + uint8_t fec = 0, data[HCI_MAX_EIR_LENGTH]; + char tmp[3]; + int i, size; + + memset(data, 0, sizeof(data)); + + memset(tmp, 0, sizeof(tmp)); + size = (strlen(opt) + 1) / 2; + if (size > HCI_MAX_EIR_LENGTH) + size = HCI_MAX_EIR_LENGTH; + + for (i = 0; i < size; i++) { + memcpy(tmp, opt + (i * 2), 2); + data[i] = strtol(tmp, NULL, 16); + } + + if (hci_write_ext_inquiry_response(dd, fec, data, 2000) < 0) { + fprintf(stderr, "Can't set extended inquiry response on hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + } else { + uint8_t fec, data[HCI_MAX_EIR_LENGTH], len, type, *ptr; + char *str; + + if (hci_read_ext_inquiry_response(dd, &fec, data, 1000) < 0) { + fprintf(stderr, "Can't read extended inquiry response on hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + + print_dev_hdr(&di); + printf("\tFEC %s\n\t\t", fec ? "enabled" : "disabled"); + for (i = 0; i < HCI_MAX_EIR_LENGTH; i++) + printf("%02x%s%s", data[i], (i + 1) % 8 ? "" : " ", + (i + 1) % 16 ? " " : (i < 239 ? "\n\t\t" : "\n")); + + ptr = data; + while (*ptr) { + len = *ptr++; + type = *ptr++; + switch (type) { + case 0x01: + printf("\tFlags:"); + for (i = 0; i < len - 1; i++) + printf(" 0x%2.2x", *((uint8_t *) (ptr + i))); + printf("\n"); + break; + case 0x02: + case 0x03: + printf("\t%s service classes:", + type == 0x02 ? "Shortened" : "Complete"); + for (i = 0; i < (len - 1) / 2; i++) { + uint16_t val = bt_get_le16((ptr + (i * 2))); + printf(" 0x%4.4x", val); + } + printf("\n"); + break; + case 0x08: + case 0x09: + str = malloc(len); + if (str) { + snprintf(str, len, "%s", ptr); + for (i = 0; i < len - 1; i++) { + if ((unsigned char) str[i] < 32 || str[i] == 127) + str[i] = '.'; + } + printf("\t%s local name: \'%s\'\n", + type == 0x08 ? "Shortened" : "Complete", str); + free(str); + } + break; + case 0x0a: + printf("\tTX power level: %d\n", *((int8_t *) ptr)); + break; + case 0x10: + printf("\tDevice ID with %d bytes data\n", + len - 1); + break; + default: + printf("\tUnknown type 0x%02x with %d bytes data\n", + type, len - 1); + break; + } + + ptr += (len - 1); + } + + printf("\n"); + } + + hci_close_dev(dd); +} + +static void cmd_inq_type(int ctl, int hdev, char *opt) +{ + int dd; + + dd = hci_open_dev(hdev); + if (dd < 0) { + fprintf(stderr, "Can't open device hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + + if (opt) { + uint8_t type = atoi(opt); + + if (hci_write_inquiry_scan_type(dd, type, 2000) < 0) { + fprintf(stderr, "Can't set inquiry scan type on hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + } else { + uint8_t type; + + if (hci_read_inquiry_scan_type(dd, &type, 1000) < 0) { + fprintf(stderr, "Can't read inquiry scan type on hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + + print_dev_hdr(&di); + printf("\tInquiry scan type: %s\n", + type == 1 ? "Interlaced Inquiry Scan" : "Standard Inquiry Scan"); + } + + hci_close_dev(dd); +} + +static void cmd_inq_parms(int ctl, int hdev, char *opt) +{ + struct hci_request rq; + int s; + + if ((s = hci_open_dev(hdev)) < 0) { + fprintf(stderr, "Can't open device hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + + memset(&rq, 0, sizeof(rq)); + + if (opt) { + unsigned int window, interval; + write_inq_activity_cp cp; + + if (sscanf(opt,"%4u:%4u", &window, &interval) != 2) { + printf("Invalid argument format\n"); + exit(1); + } + + rq.ogf = OGF_HOST_CTL; + rq.ocf = OCF_WRITE_INQ_ACTIVITY; + rq.cparam = &cp; + rq.clen = WRITE_INQ_ACTIVITY_CP_SIZE; + + cp.window = htobs((uint16_t) window); + cp.interval = htobs((uint16_t) interval); + + if (window < 0x12 || window > 0x1000) + printf("Warning: inquiry window out of range!\n"); + + if (interval < 0x12 || interval > 0x1000) + printf("Warning: inquiry interval out of range!\n"); + + if (hci_send_req(s, &rq, 2000) < 0) { + fprintf(stderr, "Can't set inquiry parameters name on hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + } else { + uint16_t window, interval; + read_inq_activity_rp rp; + + rq.ogf = OGF_HOST_CTL; + rq.ocf = OCF_READ_INQ_ACTIVITY; + rq.rparam = &rp; + rq.rlen = READ_INQ_ACTIVITY_RP_SIZE; + + if (hci_send_req(s, &rq, 1000) < 0) { + fprintf(stderr, "Can't read inquiry parameters on hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + if (rp.status) { + printf("Read inquiry parameters on hci%d returned status %d\n", + hdev, rp.status); + exit(1); + } + print_dev_hdr(&di); + + window = btohs(rp.window); + interval = btohs(rp.interval); + printf("\tInquiry interval: %u slots (%.2f ms), window: %u slots (%.2f ms)\n", + interval, (float)interval * 0.625, window, (float)window * 0.625); + } +} + +static void cmd_page_parms(int ctl, int hdev, char *opt) +{ + struct hci_request rq; + int s; + + if ((s = hci_open_dev(hdev)) < 0) { + fprintf(stderr, "Can't open device hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + + memset(&rq, 0, sizeof(rq)); + + if (opt) { + unsigned int window, interval; + write_page_activity_cp cp; + + if (sscanf(opt,"%4u:%4u", &window, &interval) != 2) { + printf("Invalid argument format\n"); + exit(1); + } + + rq.ogf = OGF_HOST_CTL; + rq.ocf = OCF_WRITE_PAGE_ACTIVITY; + rq.cparam = &cp; + rq.clen = WRITE_PAGE_ACTIVITY_CP_SIZE; + + cp.window = htobs((uint16_t) window); + cp.interval = htobs((uint16_t) interval); + + if (window < 0x12 || window > 0x1000) + printf("Warning: page window out of range!\n"); + + if (interval < 0x12 || interval > 0x1000) + printf("Warning: page interval out of range!\n"); + + if (hci_send_req(s, &rq, 2000) < 0) { + fprintf(stderr, "Can't set page parameters name on hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + } else { + uint16_t window, interval; + read_page_activity_rp rp; + + rq.ogf = OGF_HOST_CTL; + rq.ocf = OCF_READ_PAGE_ACTIVITY; + rq.rparam = &rp; + rq.rlen = READ_PAGE_ACTIVITY_RP_SIZE; + + if (hci_send_req(s, &rq, 1000) < 0) { + fprintf(stderr, "Can't read page parameters on hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + if (rp.status) { + printf("Read page parameters on hci%d returned status %d\n", + hdev, rp.status); + exit(1); + } + print_dev_hdr(&di); + + window = btohs(rp.window); + interval = btohs(rp.interval); + printf("\tPage interval: %u slots (%.2f ms), " + "window: %u slots (%.2f ms)\n", + interval, (float)interval * 0.625, + window, (float)window * 0.625); + } +} + +static void cmd_page_to(int ctl, int hdev, char *opt) +{ + struct hci_request rq; + int s; + + if ((s = hci_open_dev(hdev)) < 0) { + fprintf(stderr, "Can't open device hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + + memset(&rq, 0, sizeof(rq)); + + if (opt) { + unsigned int timeout; + write_page_timeout_cp cp; + + if (sscanf(opt,"%5u", &timeout) != 1) { + printf("Invalid argument format\n"); + exit(1); + } + + rq.ogf = OGF_HOST_CTL; + rq.ocf = OCF_WRITE_PAGE_TIMEOUT; + rq.cparam = &cp; + rq.clen = WRITE_PAGE_TIMEOUT_CP_SIZE; + + cp.timeout = htobs((uint16_t) timeout); + + if (timeout < 0x01 || timeout > 0xFFFF) + printf("Warning: page timeout out of range!\n"); + + if (hci_send_req(s, &rq, 2000) < 0) { + fprintf(stderr, "Can't set page timeout on hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + } else { + uint16_t timeout; + read_page_timeout_rp rp; + + rq.ogf = OGF_HOST_CTL; + rq.ocf = OCF_READ_PAGE_TIMEOUT; + rq.rparam = &rp; + rq.rlen = READ_PAGE_TIMEOUT_RP_SIZE; + + if (hci_send_req(s, &rq, 1000) < 0) { + fprintf(stderr, "Can't read page timeout on hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + if (rp.status) { + printf("Read page timeout on hci%d returned status %d\n", + hdev, rp.status); + exit(1); + } + print_dev_hdr(&di); + + timeout = btohs(rp.timeout); + printf("\tPage timeout: %u slots (%.2f ms)\n", + timeout, (float)timeout * 0.625); + } +} + +static void cmd_afh_mode(int ctl, int hdev, char *opt) +{ + int dd; + + dd = hci_open_dev(hdev); + if (dd < 0) { + fprintf(stderr, "Can't open device hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + + if (opt) { + uint8_t mode = atoi(opt); + + if (hci_write_afh_mode(dd, mode, 2000) < 0) { + fprintf(stderr, "Can't set AFH mode on hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + } else { + uint8_t mode; + + if (hci_read_afh_mode(dd, &mode, 1000) < 0) { + fprintf(stderr, "Can't read AFH mode on hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + + print_dev_hdr(&di); + printf("\tAFH mode: %s\n", mode == 1 ? "Enabled" : "Disabled"); + } +} + +static void cmd_ssp_mode(int ctl, int hdev, char *opt) +{ + int dd; + + dd = hci_open_dev(hdev); + if (dd < 0) { + fprintf(stderr, "Can't open device hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + + if (opt) { + uint8_t mode = atoi(opt); + + if (hci_write_simple_pairing_mode(dd, mode, 2000) < 0) { + fprintf(stderr, "Can't set Simple Pairing mode on hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + } else { + uint8_t mode; + + if (hci_read_simple_pairing_mode(dd, &mode, 1000) < 0) { + fprintf(stderr, "Can't read Simple Pairing mode on hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + + print_dev_hdr(&di); + printf("\tSimple Pairing mode: %s\n", + mode == 1 ? "Enabled" : "Disabled"); + } +} + +static void print_rev_ericsson(int dd) +{ + struct hci_request rq; + unsigned char buf[102]; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_VENDOR_CMD; + rq.ocf = 0x000f; + rq.cparam = NULL; + rq.clen = 0; + rq.rparam = &buf; + rq.rlen = sizeof(buf); + + if (hci_send_req(dd, &rq, 1000) < 0) { + printf("\nCan't read revision info: %s (%d)\n", + strerror(errno), errno); + return; + } + + printf("\t%s\n", buf + 1); +} + +static void print_rev_csr(int dd, uint16_t rev) +{ + uint16_t buildid, chipver, chiprev, maxkeylen, mapsco; + + if (csr_read_varid_uint16(dd, 0, CSR_VARID_BUILDID, &buildid) < 0) { + printf("\t%s\n", csr_buildidtostr(rev)); + return; + } + + printf("\t%s\n", csr_buildidtostr(buildid)); + + if (!csr_read_varid_uint16(dd, 1, CSR_VARID_CHIPVER, &chipver)) { + if (csr_read_varid_uint16(dd, 2, CSR_VARID_CHIPREV, &chiprev) < 0) + chiprev = 0; + printf("\tChip version: %s\n", csr_chipvertostr(chipver, chiprev)); + } + + if (!csr_read_varid_uint16(dd, 3, CSR_VARID_MAX_CRYPT_KEY_LENGTH, &maxkeylen)) + printf("\tMax key size: %d bit\n", maxkeylen * 8); + + if (!csr_read_pskey_uint16(dd, 4, CSR_PSKEY_HOSTIO_MAP_SCO_PCM, 0x0000, &mapsco)) + printf("\tSCO mapping: %s\n", mapsco ? "PCM" : "HCI"); +} + +static void print_rev_digianswer(int dd) +{ + struct hci_request rq; + unsigned char req[] = { 0x07 }; + unsigned char buf[102]; + + memset(&rq, 0, sizeof(rq)); + rq.ogf = OGF_VENDOR_CMD; + rq.ocf = 0x000e; + rq.cparam = req; + rq.clen = sizeof(req); + rq.rparam = &buf; + rq.rlen = sizeof(buf); + + if (hci_send_req(dd, &rq, 1000) < 0) { + printf("\nCan't read revision info: %s (%d)\n", + strerror(errno), errno); + return; + } + + printf("\t%s\n", buf + 1); +} + +static void print_rev_broadcom(uint16_t hci_rev, uint16_t lmp_subver) +{ + printf("\tFirmware %d.%d / %d\n", + hci_rev & 0xff, lmp_subver >> 8, lmp_subver & 0xff); +} + +static void print_rev_avm(uint16_t hci_rev, uint16_t lmp_subver) +{ + if (lmp_subver == 0x01) + printf("\tFirmware 03.%d.%d\n", hci_rev >> 8, hci_rev & 0xff); + else + printf("\tUnknown type\n"); +} + +static void cmd_revision(int ctl, int hdev, char *opt) +{ + struct hci_version ver; + int dd; + + dd = hci_open_dev(hdev); + if (dd < 0) { + fprintf(stderr, "Can't open device hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + return; + } + + if (hci_read_local_version(dd, &ver, 1000) < 0) { + fprintf(stderr, "Can't read version info for hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + return; + } + + print_dev_hdr(&di); + switch (ver.manufacturer) { + case 0: + case 37: + case 48: + print_rev_ericsson(dd); + break; + case 10: + print_rev_csr(dd, ver.hci_rev); + break; + case 12: + print_rev_digianswer(dd); + break; + case 15: + print_rev_broadcom(ver.hci_rev, ver.lmp_subver); + break; + case 31: + print_rev_avm(ver.hci_rev, ver.lmp_subver); + break; + default: + printf("\tUnsupported manufacturer\n"); + break; + } + return; +} + +static void cmd_block(int ctl, int hdev, char *opt) +{ + bdaddr_t bdaddr; + int dd; + + if (!opt) + return; + + dd = hci_open_dev(hdev); + if (dd < 0) { + fprintf(stderr, "Can't open device hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + + str2ba(opt, &bdaddr); + + if (ioctl(dd, HCIBLOCKADDR, &bdaddr) < 0) { + perror("ioctl(HCIBLOCKADDR)"); + exit(1); + } + + hci_close_dev(dd); +} + +static void cmd_unblock(int ctl, int hdev, char *opt) +{ + bdaddr_t bdaddr; + int dd; + + if (!opt) + return; + + dd = hci_open_dev(hdev); + if (dd < 0) { + fprintf(stderr, "Can't open device hci%d: %s (%d)\n", + hdev, strerror(errno), errno); + exit(1); + } + + if (!strcasecmp(opt, "all")) + bacpy(&bdaddr, BDADDR_ANY); + else + str2ba(opt, &bdaddr); + + if (ioctl(dd, HCIUNBLOCKADDR, &bdaddr) < 0) { + perror("ioctl(HCIUNBLOCKADDR)"); + exit(1); + } + + hci_close_dev(dd); +} + +static void print_dev_hdr(struct hci_dev_info *di) +{ + static int hdr = -1; + char addr[18]; + + if (hdr == di->dev_id) + return; + hdr = di->dev_id; + + ba2str(&di->bdaddr, addr); + + printf("%s:\tType: %s Bus: %s\n", di->name, + hci_typetostr((di->type & 0x30) >> 4), + hci_bustostr(di->type & 0x0f)); + printf("\tBD Address: %s ACL MTU: %d:%d SCO MTU: %d:%d\n", + addr, di->acl_mtu, di->acl_pkts, + di->sco_mtu, di->sco_pkts); +} + +static void print_dev_info(int ctl, struct hci_dev_info *di) +{ + struct hci_dev_stats *st = &di->stat; + char *str; + + print_dev_hdr(di); + + str = hci_dflagstostr(di->flags); + printf("\t%s\n", str); + bt_free(str); + + printf("\tRX bytes:%d acl:%d sco:%d events:%d errors:%d\n", + st->byte_rx, st->acl_rx, st->sco_rx, st->evt_rx, st->err_rx); + + printf("\tTX bytes:%d acl:%d sco:%d commands:%d errors:%d\n", + st->byte_tx, st->acl_tx, st->sco_tx, st->cmd_tx, st->err_tx); + + if (all && !hci_test_bit(HCI_RAW, &di->flags)) { + print_dev_features(di, 0); + + if (((di->type & 0x30) >> 4) == HCI_BREDR) { + print_pkt_type(di); + print_link_policy(di); + print_link_mode(di); + + if (hci_test_bit(HCI_UP, &di->flags)) { + cmd_name(ctl, di->dev_id, NULL); + cmd_class(ctl, di->dev_id, NULL); + } + } + + if (hci_test_bit(HCI_UP, &di->flags)) + cmd_version(ctl, di->dev_id, NULL); + } + + printf("\n"); +} + +static struct { + char *cmd; + void (*func)(int ctl, int hdev, char *opt); + char *opt; + char *doc; +} command[] = { + { "up", cmd_up, 0, "Open and initialize HCI device" }, + { "down", cmd_down, 0, "Close HCI device" }, + { "reset", cmd_reset, 0, "Reset HCI device" }, + { "rstat", cmd_rstat, 0, "Reset statistic counters" }, + { "auth", cmd_auth, 0, "Enable Authentication" }, + { "noauth", cmd_auth, 0, "Disable Authentication" }, + { "encrypt", cmd_encrypt, 0, "Enable Encryption" }, + { "noencrypt", cmd_encrypt, 0, "Disable Encryption" }, + { "piscan", cmd_scan, 0, "Enable Page and Inquiry scan" }, + { "noscan", cmd_scan, 0, "Disable scan" }, + { "iscan", cmd_scan, 0, "Enable Inquiry scan" }, + { "pscan", cmd_scan, 0, "Enable Page scan" }, + { "ptype", cmd_ptype, "[type]", "Get/Set default packet type" }, + { "lm", cmd_lm, "[mode]", "Get/Set default link mode" }, + { "lp", cmd_lp, "[policy]", "Get/Set default link policy" }, + { "name", cmd_name, "[name]", "Get/Set local name" }, + { "class", cmd_class, "[class]", "Get/Set class of device" }, + { "voice", cmd_voice, "[voice]", "Get/Set voice setting" }, + { "iac", cmd_iac, "[iac]", "Get/Set inquiry access code" }, + { "inqtpl", cmd_inq_tpl, "[level]", "Get/Set inquiry transmit power level" }, + { "inqmode", cmd_inq_mode, "[mode]", "Get/Set inquiry mode" }, + { "inqdata", cmd_inq_data, "[data]", "Get/Set inquiry data" }, + { "inqtype", cmd_inq_type, "[type]", "Get/Set inquiry scan type" }, + { "inqparms", cmd_inq_parms, "[win:int]", "Get/Set inquiry scan window and interval" }, + { "pageparms", cmd_page_parms, "[win:int]", "Get/Set page scan window and interval" }, + { "pageto", cmd_page_to, "[to]", "Get/Set page timeout" }, + { "afhmode", cmd_afh_mode, "[mode]", "Get/Set AFH mode" }, + { "sspmode", cmd_ssp_mode, "[mode]", "Get/Set Simple Pairing Mode" }, + { "aclmtu", cmd_aclmtu, "", "Set ACL MTU and number of packets" }, + { "scomtu", cmd_scomtu, "", "Set SCO MTU and number of packets" }, + { "delkey", cmd_delkey, "", "Delete link key from the device" }, + { "oobdata", cmd_oob_data, 0, "Get local OOB data" }, + { "commands", cmd_commands, 0, "Display supported commands" }, + { "features", cmd_features, 0, "Display device features" }, + { "version", cmd_version, 0, "Display version information" }, + { "revision", cmd_revision, 0, "Display revision information" }, + { "block", cmd_block, "", "Add a device to the blacklist" }, + { "unblock", cmd_unblock, "", "Remove a device from the blacklist" }, + { "lerandaddr", cmd_le_addr, "", "Set LE Random Address" }, + { "leadv", cmd_le_adv, "[type]", "Enable LE advertising" + "\n\t\t\t0 - Connectable undirected advertising (default)" + "\n\t\t\t3 - Non connectable undirected advertising"}, + { "noleadv", cmd_no_le_adv, 0, "Disable LE advertising" }, + { "lestates", cmd_le_states, 0, "Display the supported LE states" }, + { NULL, NULL, 0 } +}; + +static void usage(void) +{ + int i; + + printf("hciconfig - HCI device configuration utility\n"); + printf("Usage:\n" + "\thciconfig\n" + "\thciconfig [-a] hciX [command ...]\n"); + printf("Commands:\n"); + for (i = 0; command[i].cmd; i++) + printf("\t%-10s %-8s\t%s\n", command[i].cmd, + command[i].opt ? command[i].opt : " ", + command[i].doc); +} + +static struct option main_options[] = { + { "help", 0, 0, 'h' }, + { "all", 0, 0, 'a' }, + { 0, 0, 0, 0 } +}; + +int main(int argc, char *argv[]) +{ + int opt, ctl, i, cmd = 0; + + while ((opt = getopt_long(argc, argv, "ah", main_options, NULL)) != -1) { + switch (opt) { + case 'a': + all = 1; + break; + + case 'h': + default: + usage(); + exit(0); + } + } + + argc -= optind; + argv += optind; + optind = 0; + + /* Open HCI socket */ + if ((ctl = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI)) < 0) { + perror("Can't open HCI socket."); + exit(1); + } + + if (argc < 1) { + print_dev_list(ctl, 0); + exit(0); + } + + di.dev_id = atoi(argv[0] + 3); + argc--; argv++; + + if (ioctl(ctl, HCIGETDEVINFO, (void *) &di)) { + perror("Can't get device info"); + exit(1); + } + + if (hci_test_bit(HCI_RAW, &di.flags) && + !bacmp(&di.bdaddr, BDADDR_ANY)) { + int dd = hci_open_dev(di.dev_id); + hci_read_bd_addr(dd, &di.bdaddr, 1000); + hci_close_dev(dd); + } + + while (argc > 0) { + for (i = 0; command[i].cmd; i++) { + if (strncmp(command[i].cmd, + *argv, strlen(command[i].cmd))) + continue; + + if (command[i].opt) { + argc--; argv++; + } + + command[i].func(ctl, di.dev_id, *argv); + cmd = 1; + break; + } + + if (command[i].cmd == 0) + fprintf(stderr, "Warning: unknown command - \"%s\"\n", + *argv); + + argc--; argv++; + } + + if (!cmd) + print_dev_info(ctl, &di); + + close(ctl); + return 0; +} diff --git a/drive-sdk/deps/bzle/tools/textfile.c b/drive-sdk/deps/bzle/tools/textfile.c new file mode 100644 index 0000000..7267f3a --- /dev/null +++ b/drive-sdk/deps/bzle/tools/textfile.c @@ -0,0 +1,475 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2004-2010 Marcel Holtmann + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "textfile.h" + +static int create_dirs(const char *filename, const mode_t mode) +{ + struct stat st; + char dir[PATH_MAX + 1], *prev, *next; + int err; + + err = stat(filename, &st); + if (!err && S_ISREG(st.st_mode)) + return 0; + + memset(dir, 0, PATH_MAX + 1); + strcat(dir, "/"); + + prev = strchr(filename, '/'); + + while (prev) { + next = strchr(prev + 1, '/'); + if (!next) + break; + + if (next - prev == 1) { + prev = next; + continue; + } + + strncat(dir, prev + 1, next - prev); + mkdir(dir, mode); + + prev = next; + } + + return 0; +} + +int create_file(const char *filename, const mode_t mode) +{ + int fd; + + create_dirs(filename, S_IRUSR | S_IWUSR | S_IXUSR); + + fd = open(filename, O_RDWR | O_CREAT, mode); + if (fd < 0) + return fd; + + close(fd); + + return 0; +} + +int create_name(char *buf, size_t size, const char *path, const char *address, const char *name) +{ + return snprintf(buf, size, "%s/%s/%s", path, address, name); +} + +static inline char *find_key(char *map, size_t size, const char *key, size_t len, int icase) +{ + char *ptr = map; + size_t ptrlen = size; + + while (ptrlen > len + 1) { + int cmp = (icase) ? strncasecmp(ptr, key, len) : strncmp(ptr, key, len); + if (cmp == 0) { + if (ptr == map && *(ptr + len) == ' ') + return ptr; + + if ((*(ptr - 1) == '\r' || *(ptr - 1) == '\n') && + *(ptr + len) == ' ') + return ptr; + } + + if (icase) { + char *p1 = memchr(ptr + 1, tolower(*key), ptrlen - 1); + char *p2 = memchr(ptr + 1, toupper(*key), ptrlen - 1); + + if (!p1) + ptr = p2; + else if (!p2) + ptr = p1; + else + ptr = (p1 < p2) ? p1 : p2; + } else + ptr = memchr(ptr + 1, *key, ptrlen - 1); + + if (!ptr) + return NULL; + + ptrlen = size - (ptr - map); + } + + return NULL; +} + +static inline int write_key_value(int fd, const char *key, const char *value) +{ + char *str; + size_t size; + int err = 0; + + size = strlen(key) + strlen(value) + 2; + + str = malloc(size + 1); + if (!str) + return ENOMEM; + + sprintf(str, "%s %s\n", key, value); + + if (write(fd, str, size) < 0) + err = -errno; + + free(str); + + return err; +} + +static char *strnpbrk(const char *s, ssize_t len, const char *accept) +{ + const char *p = s; + const char *end; + + end = s + len - 1; + + while (p <= end && *p) { + const char *a = accept; + + while (*a) { + if (*p == *a) + return (char *) p; + a++; + } + + p++; + } + + return NULL; +} + +static int write_key(const char *pathname, const char *key, const char *value, int icase) +{ + struct stat st; + char *map, *off, *end, *str; + off_t size; + size_t base; + int fd, len, err = 0; + + fd = open(pathname, O_RDWR); + if (fd < 0) + return -errno; + + if (flock(fd, LOCK_EX) < 0) { + err = -errno; + goto close; + } + + if (fstat(fd, &st) < 0) { + err = -errno; + goto unlock; + } + + size = st.st_size; + + if (!size) { + if (value) { + lseek(fd, size, SEEK_SET); + err = write_key_value(fd, key, value); + } + goto unlock; + } + + map = mmap(NULL, size, PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_LOCKED, fd, 0); + if (!map || map == MAP_FAILED) { + err = -errno; + goto unlock; + } + + len = strlen(key); + off = find_key(map, size, key, len, icase); + if (!off) { + munmap(map, size); + if (value) { + lseek(fd, size, SEEK_SET); + err = write_key_value(fd, key, value); + } + goto unlock; + } + + base = off - map; + + end = strnpbrk(off, size, "\r\n"); + if (!end) { + err = -EILSEQ; + goto unmap; + } + + if (value && ((ssize_t) strlen(value) == end - off - len - 1) && + !strncmp(off + len + 1, value, end - off - len - 1)) + goto unmap; + + len = strspn(end, "\r\n"); + end += len; + + len = size - (end - map); + if (!len) { + munmap(map, size); + if (ftruncate(fd, base) < 0) { + err = -errno; + goto unlock; + } + lseek(fd, base, SEEK_SET); + if (value) + err = write_key_value(fd, key, value); + + goto unlock; + } + + if (len < 0 || len > size) { + err = -EILSEQ; + goto unmap; + } + + str = malloc(len); + if (!str) { + err = -errno; + goto unmap; + } + + memcpy(str, end, len); + + munmap(map, size); + if (ftruncate(fd, base) < 0) { + err = -errno; + free(str); + goto unlock; + } + lseek(fd, base, SEEK_SET); + if (value) + err = write_key_value(fd, key, value); + + if (write(fd, str, len) < 0) + err = -errno; + + free(str); + + goto unlock; + +unmap: + munmap(map, size); + +unlock: + flock(fd, LOCK_UN); + +close: + fdatasync(fd); + + close(fd); + errno = -err; + + return err; +} + +static char *read_key(const char *pathname, const char *key, int icase) +{ + struct stat st; + char *map, *off, *end, *str = NULL; + off_t size; size_t len; + int fd, err = 0; + + fd = open(pathname, O_RDONLY); + if (fd < 0) + return NULL; + + if (flock(fd, LOCK_SH) < 0) { + err = -errno; + goto close; + } + + if (fstat(fd, &st) < 0) { + err = -errno; + goto unlock; + } + + size = st.st_size; + + map = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0); + if (!map || map == MAP_FAILED) { + err = -errno; + goto unlock; + } + + len = strlen(key); + off = find_key(map, size, key, len, icase); + if (!off) { + err = -EILSEQ; + goto unmap; + } + + end = strnpbrk(off, size - (off - map), "\r\n"); + if (!end) { + err = -EILSEQ; + goto unmap; + } + + str = malloc(end - off - len); + if (!str) { + err = -EILSEQ; + goto unmap; + } + + memset(str, 0, end - off - len); + strncpy(str, off + len + 1, end - off - len - 1); + +unmap: + munmap(map, size); + +unlock: + flock(fd, LOCK_UN); + +close: + close(fd); + errno = -err; + + return str; +} + +int textfile_put(const char *pathname, const char *key, const char *value) +{ + return write_key(pathname, key, value, 0); +} + +int textfile_del(const char *pathname, const char *key) +{ + return write_key(pathname, key, NULL, 0); +} + +char *textfile_get(const char *pathname, const char *key) +{ + return read_key(pathname, key, 0); +} + +int textfile_foreach(const char *pathname, textfile_cb func, void *data) +{ + struct stat st; + char *map, *off, *end, *key, *value; + off_t size; size_t len; + int fd, err = 0; + + fd = open(pathname, O_RDONLY); + if (fd < 0) + return -errno; + + if (flock(fd, LOCK_SH) < 0) { + err = -errno; + goto close; + } + + if (fstat(fd, &st) < 0) { + err = -errno; + goto unlock; + } + + size = st.st_size; + + map = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0); + if (!map || map == MAP_FAILED) { + err = -errno; + goto unlock; + } + + off = map; + + while (size - (off - map) > 0) { + end = strnpbrk(off, size - (off - map), " "); + if (!end) { + err = -EILSEQ; + break; + } + + len = end - off; + + key = malloc(len + 1); + if (!key) { + err = -errno; + break; + } + + memset(key, 0, len + 1); + memcpy(key, off, len); + + off = end + 1; + + if (size - (off - map) < 0) { + err = -EILSEQ; + free(key); + break; + } + + end = strnpbrk(off, size - (off - map), "\r\n"); + if (!end) { + err = -EILSEQ; + free(key); + break; + } + + len = end - off; + + value = malloc(len + 1); + if (!value) { + err = -errno; + free(key); + break; + } + + memset(value, 0, len + 1); + memcpy(value, off, len); + + func(key, value, data); + + free(key); + free(value); + + off = end + 1; + } + + munmap(map, size); + +unlock: + flock(fd, LOCK_UN); + +close: + close(fd); + errno = -err; + + return 0; +} diff --git a/drive-sdk/deps/bzle/tools/textfile.h b/drive-sdk/deps/bzle/tools/textfile.h new file mode 100644 index 0000000..f01629e --- /dev/null +++ b/drive-sdk/deps/bzle/tools/textfile.h @@ -0,0 +1,34 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2004-2010 Marcel Holtmann + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +int create_file(const char *filename, const mode_t mode); +int create_name(char *buf, size_t size, const char *path, + const char *address, const char *name); + +int textfile_put(const char *pathname, const char *key, const char *value); +int textfile_del(const char *pathname, const char *key); +char *textfile_get(const char *pathname, const char *key); + +typedef void (*textfile_cb) (char *key, char *value, void *data); + +int textfile_foreach(const char *pathname, textfile_cb func, void *data); diff --git a/drive-sdk/examples/CMakeLists.txt b/drive-sdk/examples/CMakeLists.txt new file mode 100755 index 0000000..90b1e68 --- /dev/null +++ b/drive-sdk/examples/CMakeLists.txt @@ -0,0 +1,2 @@ +add_subdirectory(vehicle-scan) +add_subdirectory(vehicle-tool) diff --git a/drive-sdk/examples/README.md b/drive-sdk/examples/README.md new file mode 100644 index 0000000..9f5e781 --- /dev/null +++ b/drive-sdk/examples/README.md @@ -0,0 +1,25 @@ +Anki Drive SDK Examples +======================= + +These examples show how to use the Anki Drive SDK to detect, display, connect to and control vehicles. + + +## vehicle-scan + +A linux command line utility to scan for Anki Drive vehicles using Bluetooth LE and display information advertised by vehicles. +This utility shows how to use the data parsing methods to extract vehicle information from Bluetooth LE advertising data packets. +`vehicle-scan` links to code distributed with the [bluez][] library and is licensed under the GNU Public License v3. + +## vehicle-tool + +An interactive command line shell for connecting and controlling Anki Drive vehicles. +This program demonstrates the Bluetooth LE connection procedure and shows how to interact use the message protocol to interact with vehicles. +`vehicle-tool` links to code distributed with the [bluez][] library and is licensed under the GNU Public License v3. + +[bluez]: http://www.bluez.org + +## Building and Running Examples + +For a detailed description of how to build and run the example programs, see the guide to [Getting Started on Ubuntu][ubuntu-getting-started]. + +[ubuntu-getting-started]: https://github.com/anki/drive-sdk/wiki/Getting-Started-on-Ubuntu diff --git a/drive-sdk/examples/vehicle-scan/.gitignore b/drive-sdk/examples/vehicle-scan/.gitignore new file mode 100644 index 0000000..c3a4afe --- /dev/null +++ b/drive-sdk/examples/vehicle-scan/.gitignore @@ -0,0 +1,3 @@ +.deps +.dirstamp +vehicle-scan diff --git a/drive-sdk/examples/vehicle-scan/CMakeLists.txt b/drive-sdk/examples/vehicle-scan/CMakeLists.txt new file mode 100755 index 0000000..f976cfb --- /dev/null +++ b/drive-sdk/examples/vehicle-scan/CMakeLists.txt @@ -0,0 +1,22 @@ +set(CMAKE_INCLUDE_CURRENT_DIR ON) + +SET (CMAKE_C_FLAGS "") + +include_directories(${drivekit_SOURCE_DIR}/include + ${bzle_SOURCE_DIR}/include + ) + +# Add sources +set(vehiclescan_SOURCES + vehicle-scan.c +) + +add_executable(vehicle-scan ${vehiclescan_SOURCES}) +target_link_libraries(vehicle-scan + ankidrive + bzle +) + +install(TARGETS vehicle-scan + RUNTIME DESTINATION bin +) diff --git a/drive-sdk/examples/vehicle-scan/README.md b/drive-sdk/examples/vehicle-scan/README.md new file mode 100644 index 0000000..9be8499 --- /dev/null +++ b/drive-sdk/examples/vehicle-scan/README.md @@ -0,0 +1,13 @@ +## Build + + make + +## Run + + # bring up bluetooth 4.0 driver + sudo hciconfig hci0 up + + # run scanning tool + sudo ./vehicle-scan + + # Ctrl+C to stop scanning diff --git a/drive-sdk/examples/vehicle-scan/uthash.h b/drive-sdk/examples/vehicle-scan/uthash.h new file mode 100644 index 0000000..b9bc7e9 --- /dev/null +++ b/drive-sdk/examples/vehicle-scan/uthash.h @@ -0,0 +1,948 @@ +/* +Copyright (c) 2003-2013, Troy D. Hanson http://troydhanson.github.com/uthash/ +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER +OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#ifndef UTHASH_H +#define UTHASH_H + +#include /* memcmp,strlen */ +#include /* ptrdiff_t */ +#include /* exit() */ + +/* These macros use decltype or the earlier __typeof GNU extension. + As decltype is only available in newer compilers (VS2010 or gcc 4.3+ + when compiling c++ source) this code uses whatever method is needed + or, for VS2008 where neither is available, uses casting workarounds. */ +#ifdef _MSC_VER /* MS compiler */ +#if _MSC_VER >= 1600 && defined(__cplusplus) /* VS2010 or newer in C++ mode */ +#define DECLTYPE(x) (decltype(x)) +#else /* VS2008 or older (or VS2010 in C mode) */ +#define NO_DECLTYPE +#define DECLTYPE(x) +#endif +#else /* GNU, Sun and other compilers */ +#define DECLTYPE(x) (__typeof(x)) +#endif + +#ifdef NO_DECLTYPE +#define DECLTYPE_ASSIGN(dst,src) \ +do { \ + char **_da_dst = (char**)(&(dst)); \ + *_da_dst = (char*)(src); \ +} while(0) +#else +#define DECLTYPE_ASSIGN(dst,src) \ +do { \ + (dst) = DECLTYPE(dst)(src); \ +} while(0) +#endif + +/* a number of the hash function use uint32_t which isn't defined on win32 */ +#ifdef _MSC_VER +typedef unsigned int uint32_t; +typedef unsigned char uint8_t; +#else +#include /* uint32_t */ +#endif + +#define UTHASH_VERSION 1.9.8 + +#ifndef uthash_fatal +#define uthash_fatal(msg) exit(-1) /* fatal error (out of memory,etc) */ +#endif +#ifndef uthash_malloc +#define uthash_malloc(sz) malloc(sz) /* malloc fcn */ +#endif +#ifndef uthash_free +#define uthash_free(ptr,sz) free(ptr) /* free fcn */ +#endif + +#ifndef uthash_noexpand_fyi +#define uthash_noexpand_fyi(tbl) /* can be defined to log noexpand */ +#endif +#ifndef uthash_expand_fyi +#define uthash_expand_fyi(tbl) /* can be defined to log expands */ +#endif + +/* initial number of buckets */ +#define HASH_INITIAL_NUM_BUCKETS 32 /* initial number of buckets */ +#define HASH_INITIAL_NUM_BUCKETS_LOG2 5 /* lg2 of initial number of buckets */ +#define HASH_BKT_CAPACITY_THRESH 10 /* expand when bucket count reaches */ + +/* calculate the element whose hash handle address is hhe */ +#define ELMT_FROM_HH(tbl,hhp) ((void*)(((char*)(hhp)) - ((tbl)->hho))) + +#define HASH_FIND(hh,head,keyptr,keylen,out) \ +do { \ + unsigned _hf_bkt,_hf_hashv; \ + out=NULL; \ + if (head) { \ + HASH_FCN(keyptr,keylen, (head)->hh.tbl->num_buckets, _hf_hashv, _hf_bkt); \ + if (HASH_BLOOM_TEST((head)->hh.tbl, _hf_hashv)) { \ + HASH_FIND_IN_BKT((head)->hh.tbl, hh, (head)->hh.tbl->buckets[ _hf_bkt ], \ + keyptr,keylen,out); \ + } \ + } \ +} while (0) + +#ifdef HASH_BLOOM +#define HASH_BLOOM_BITLEN (1ULL << HASH_BLOOM) +#define HASH_BLOOM_BYTELEN (HASH_BLOOM_BITLEN/8) + ((HASH_BLOOM_BITLEN%8) ? 1:0) +#define HASH_BLOOM_MAKE(tbl) \ +do { \ + (tbl)->bloom_nbits = HASH_BLOOM; \ + (tbl)->bloom_bv = (uint8_t*)uthash_malloc(HASH_BLOOM_BYTELEN); \ + if (!((tbl)->bloom_bv)) { uthash_fatal( "out of memory"); } \ + memset((tbl)->bloom_bv, 0, HASH_BLOOM_BYTELEN); \ + (tbl)->bloom_sig = HASH_BLOOM_SIGNATURE; \ +} while (0) + +#define HASH_BLOOM_FREE(tbl) \ +do { \ + uthash_free((tbl)->bloom_bv, HASH_BLOOM_BYTELEN); \ +} while (0) + +#define HASH_BLOOM_BITSET(bv,idx) (bv[(idx)/8] |= (1U << ((idx)%8))) +#define HASH_BLOOM_BITTEST(bv,idx) (bv[(idx)/8] & (1U << ((idx)%8))) + +#define HASH_BLOOM_ADD(tbl,hashv) \ + HASH_BLOOM_BITSET((tbl)->bloom_bv, (hashv & (uint32_t)((1ULL << (tbl)->bloom_nbits) - 1))) + +#define HASH_BLOOM_TEST(tbl,hashv) \ + HASH_BLOOM_BITTEST((tbl)->bloom_bv, (hashv & (uint32_t)((1ULL << (tbl)->bloom_nbits) - 1))) + +#else +#define HASH_BLOOM_MAKE(tbl) +#define HASH_BLOOM_FREE(tbl) +#define HASH_BLOOM_ADD(tbl,hashv) +#define HASH_BLOOM_TEST(tbl,hashv) (1) +#define HASH_BLOOM_BYTELEN 0 +#endif + +#define HASH_MAKE_TABLE(hh,head) \ +do { \ + (head)->hh.tbl = (UT_hash_table*)uthash_malloc( \ + sizeof(UT_hash_table)); \ + if (!((head)->hh.tbl)) { uthash_fatal( "out of memory"); } \ + memset((head)->hh.tbl, 0, sizeof(UT_hash_table)); \ + (head)->hh.tbl->tail = &((head)->hh); \ + (head)->hh.tbl->num_buckets = HASH_INITIAL_NUM_BUCKETS; \ + (head)->hh.tbl->log2_num_buckets = HASH_INITIAL_NUM_BUCKETS_LOG2; \ + (head)->hh.tbl->hho = (char*)(&(head)->hh) - (char*)(head); \ + (head)->hh.tbl->buckets = (UT_hash_bucket*)uthash_malloc( \ + HASH_INITIAL_NUM_BUCKETS*sizeof(struct UT_hash_bucket)); \ + if (! (head)->hh.tbl->buckets) { uthash_fatal( "out of memory"); } \ + memset((head)->hh.tbl->buckets, 0, \ + HASH_INITIAL_NUM_BUCKETS*sizeof(struct UT_hash_bucket)); \ + HASH_BLOOM_MAKE((head)->hh.tbl); \ + (head)->hh.tbl->signature = HASH_SIGNATURE; \ +} while(0) + +#define HASH_ADD(hh,head,fieldname,keylen_in,add) \ + HASH_ADD_KEYPTR(hh,head,&((add)->fieldname),keylen_in,add) + +#define HASH_REPLACE(hh,head,fieldname,keylen_in,add,replaced) \ +do { \ + replaced=NULL; \ + HASH_FIND(hh,head,&((add)->fieldname),keylen_in,replaced); \ + if (replaced!=NULL) { \ + HASH_DELETE(hh,head,replaced); \ + }; \ + HASH_ADD(hh,head,fieldname,keylen_in,add); \ +} while(0) + +#define HASH_ADD_KEYPTR(hh,head,keyptr,keylen_in,add) \ +do { \ + unsigned _ha_bkt; \ + (add)->hh.next = NULL; \ + (add)->hh.key = (char*)(keyptr); \ + (add)->hh.keylen = (unsigned)(keylen_in); \ + if (!(head)) { \ + head = (add); \ + (head)->hh.prev = NULL; \ + HASH_MAKE_TABLE(hh,head); \ + } else { \ + (head)->hh.tbl->tail->next = (add); \ + (add)->hh.prev = ELMT_FROM_HH((head)->hh.tbl, (head)->hh.tbl->tail); \ + (head)->hh.tbl->tail = &((add)->hh); \ + } \ + (head)->hh.tbl->num_items++; \ + (add)->hh.tbl = (head)->hh.tbl; \ + HASH_FCN(keyptr,keylen_in, (head)->hh.tbl->num_buckets, \ + (add)->hh.hashv, _ha_bkt); \ + HASH_ADD_TO_BKT((head)->hh.tbl->buckets[_ha_bkt],&(add)->hh); \ + HASH_BLOOM_ADD((head)->hh.tbl,(add)->hh.hashv); \ + HASH_EMIT_KEY(hh,head,keyptr,keylen_in); \ + HASH_FSCK(hh,head); \ +} while(0) + +#define HASH_TO_BKT( hashv, num_bkts, bkt ) \ +do { \ + bkt = ((hashv) & ((num_bkts) - 1)); \ +} while(0) + +/* delete "delptr" from the hash table. + * "the usual" patch-up process for the app-order doubly-linked-list. + * The use of _hd_hh_del below deserves special explanation. + * These used to be expressed using (delptr) but that led to a bug + * if someone used the same symbol for the head and deletee, like + * HASH_DELETE(hh,users,users); + * We want that to work, but by changing the head (users) below + * we were forfeiting our ability to further refer to the deletee (users) + * in the patch-up process. Solution: use scratch space to + * copy the deletee pointer, then the latter references are via that + * scratch pointer rather than through the repointed (users) symbol. + */ +#define HASH_DELETE(hh,head,delptr) \ +do { \ + unsigned _hd_bkt; \ + struct UT_hash_handle *_hd_hh_del; \ + if ( ((delptr)->hh.prev == NULL) && ((delptr)->hh.next == NULL) ) { \ + uthash_free((head)->hh.tbl->buckets, \ + (head)->hh.tbl->num_buckets*sizeof(struct UT_hash_bucket) ); \ + HASH_BLOOM_FREE((head)->hh.tbl); \ + uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ + head = NULL; \ + } else { \ + _hd_hh_del = &((delptr)->hh); \ + if ((delptr) == ELMT_FROM_HH((head)->hh.tbl,(head)->hh.tbl->tail)) { \ + (head)->hh.tbl->tail = \ + (UT_hash_handle*)((ptrdiff_t)((delptr)->hh.prev) + \ + (head)->hh.tbl->hho); \ + } \ + if ((delptr)->hh.prev) { \ + ((UT_hash_handle*)((ptrdiff_t)((delptr)->hh.prev) + \ + (head)->hh.tbl->hho))->next = (delptr)->hh.next; \ + } else { \ + DECLTYPE_ASSIGN(head,(delptr)->hh.next); \ + } \ + if (_hd_hh_del->next) { \ + ((UT_hash_handle*)((ptrdiff_t)_hd_hh_del->next + \ + (head)->hh.tbl->hho))->prev = \ + _hd_hh_del->prev; \ + } \ + HASH_TO_BKT( _hd_hh_del->hashv, (head)->hh.tbl->num_buckets, _hd_bkt); \ + HASH_DEL_IN_BKT(hh,(head)->hh.tbl->buckets[_hd_bkt], _hd_hh_del); \ + (head)->hh.tbl->num_items--; \ + } \ + HASH_FSCK(hh,head); \ +} while (0) + + +/* convenience forms of HASH_FIND/HASH_ADD/HASH_DEL */ +#define HASH_FIND_STR(head,findstr,out) \ + HASH_FIND(hh,head,findstr,strlen(findstr),out) +#define HASH_ADD_STR(head,strfield,add) \ + HASH_ADD(hh,head,strfield,strlen(add->strfield),add) +#define HASH_REPLACE_STR(head,strfield,add,replaced) \ + HASH_REPLACE(hh,head,strfield,strlen(add->strfield),add,replaced) +#define HASH_FIND_INT(head,findint,out) \ + HASH_FIND(hh,head,findint,sizeof(int),out) +#define HASH_ADD_INT(head,intfield,add) \ + HASH_ADD(hh,head,intfield,sizeof(int),add) +#define HASH_REPLACE_INT(head,intfield,add,replaced) \ + HASH_REPLACE(hh,head,intfield,sizeof(int),add,replaced) +#define HASH_FIND_PTR(head,findptr,out) \ + HASH_FIND(hh,head,findptr,sizeof(void *),out) +#define HASH_ADD_PTR(head,ptrfield,add) \ + HASH_ADD(hh,head,ptrfield,sizeof(void *),add) +#define HASH_REPLACE_PTR(head,ptrfield,add,replaced) \ + HASH_REPLACE(hh,head,ptrfield,sizeof(void *),add,replaced) +#define HASH_DEL(head,delptr) \ + HASH_DELETE(hh,head,delptr) + +/* HASH_FSCK checks hash integrity on every add/delete when HASH_DEBUG is defined. + * This is for uthash developer only; it compiles away if HASH_DEBUG isn't defined. + */ +#ifdef HASH_DEBUG +#define HASH_OOPS(...) do { fprintf(stderr,__VA_ARGS__); exit(-1); } while (0) +#define HASH_FSCK(hh,head) \ +do { \ + unsigned _bkt_i; \ + unsigned _count, _bkt_count; \ + char *_prev; \ + struct UT_hash_handle *_thh; \ + if (head) { \ + _count = 0; \ + for( _bkt_i = 0; _bkt_i < (head)->hh.tbl->num_buckets; _bkt_i++) { \ + _bkt_count = 0; \ + _thh = (head)->hh.tbl->buckets[_bkt_i].hh_head; \ + _prev = NULL; \ + while (_thh) { \ + if (_prev != (char*)(_thh->hh_prev)) { \ + HASH_OOPS("invalid hh_prev %p, actual %p\n", \ + _thh->hh_prev, _prev ); \ + } \ + _bkt_count++; \ + _prev = (char*)(_thh); \ + _thh = _thh->hh_next; \ + } \ + _count += _bkt_count; \ + if ((head)->hh.tbl->buckets[_bkt_i].count != _bkt_count) { \ + HASH_OOPS("invalid bucket count %d, actual %d\n", \ + (head)->hh.tbl->buckets[_bkt_i].count, _bkt_count); \ + } \ + } \ + if (_count != (head)->hh.tbl->num_items) { \ + HASH_OOPS("invalid hh item count %d, actual %d\n", \ + (head)->hh.tbl->num_items, _count ); \ + } \ + /* traverse hh in app order; check next/prev integrity, count */ \ + _count = 0; \ + _prev = NULL; \ + _thh = &(head)->hh; \ + while (_thh) { \ + _count++; \ + if (_prev !=(char*)(_thh->prev)) { \ + HASH_OOPS("invalid prev %p, actual %p\n", \ + _thh->prev, _prev ); \ + } \ + _prev = (char*)ELMT_FROM_HH((head)->hh.tbl, _thh); \ + _thh = ( _thh->next ? (UT_hash_handle*)((char*)(_thh->next) + \ + (head)->hh.tbl->hho) : NULL ); \ + } \ + if (_count != (head)->hh.tbl->num_items) { \ + HASH_OOPS("invalid app item count %d, actual %d\n", \ + (head)->hh.tbl->num_items, _count ); \ + } \ + } \ +} while (0) +#else +#define HASH_FSCK(hh,head) +#endif + +/* When compiled with -DHASH_EMIT_KEYS, length-prefixed keys are emitted to + * the descriptor to which this macro is defined for tuning the hash function. + * The app can #include to get the prototype for write(2). */ +#ifdef HASH_EMIT_KEYS +#define HASH_EMIT_KEY(hh,head,keyptr,fieldlen) \ +do { \ + unsigned _klen = fieldlen; \ + write(HASH_EMIT_KEYS, &_klen, sizeof(_klen)); \ + write(HASH_EMIT_KEYS, keyptr, fieldlen); \ +} while (0) +#else +#define HASH_EMIT_KEY(hh,head,keyptr,fieldlen) +#endif + +/* default to Jenkin's hash unless overridden e.g. DHASH_FUNCTION=HASH_SAX */ +#ifdef HASH_FUNCTION +#define HASH_FCN HASH_FUNCTION +#else +#define HASH_FCN HASH_JEN +#endif + +/* The Bernstein hash function, used in Perl prior to v5.6 */ +#define HASH_BER(key,keylen,num_bkts,hashv,bkt) \ +do { \ + unsigned _hb_keylen=keylen; \ + char *_hb_key=(char*)(key); \ + (hashv) = 0; \ + while (_hb_keylen--) { (hashv) = ((hashv) * 33) + *_hb_key++; } \ + bkt = (hashv) & (num_bkts-1); \ +} while (0) + + +/* SAX/FNV/OAT/JEN hash functions are macro variants of those listed at + * http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx */ +#define HASH_SAX(key,keylen,num_bkts,hashv,bkt) \ +do { \ + unsigned _sx_i; \ + char *_hs_key=(char*)(key); \ + hashv = 0; \ + for(_sx_i=0; _sx_i < keylen; _sx_i++) \ + hashv ^= (hashv << 5) + (hashv >> 2) + _hs_key[_sx_i]; \ + bkt = hashv & (num_bkts-1); \ +} while (0) + +#define HASH_FNV(key,keylen,num_bkts,hashv,bkt) \ +do { \ + unsigned _fn_i; \ + char *_hf_key=(char*)(key); \ + hashv = 2166136261UL; \ + for(_fn_i=0; _fn_i < keylen; _fn_i++) \ + hashv = (hashv * 16777619) ^ _hf_key[_fn_i]; \ + bkt = hashv & (num_bkts-1); \ +} while(0) + +#define HASH_OAT(key,keylen,num_bkts,hashv,bkt) \ +do { \ + unsigned _ho_i; \ + char *_ho_key=(char*)(key); \ + hashv = 0; \ + for(_ho_i=0; _ho_i < keylen; _ho_i++) { \ + hashv += _ho_key[_ho_i]; \ + hashv += (hashv << 10); \ + hashv ^= (hashv >> 6); \ + } \ + hashv += (hashv << 3); \ + hashv ^= (hashv >> 11); \ + hashv += (hashv << 15); \ + bkt = hashv & (num_bkts-1); \ +} while(0) + +#define HASH_JEN_MIX(a,b,c) \ +do { \ + a -= b; a -= c; a ^= ( c >> 13 ); \ + b -= c; b -= a; b ^= ( a << 8 ); \ + c -= a; c -= b; c ^= ( b >> 13 ); \ + a -= b; a -= c; a ^= ( c >> 12 ); \ + b -= c; b -= a; b ^= ( a << 16 ); \ + c -= a; c -= b; c ^= ( b >> 5 ); \ + a -= b; a -= c; a ^= ( c >> 3 ); \ + b -= c; b -= a; b ^= ( a << 10 ); \ + c -= a; c -= b; c ^= ( b >> 15 ); \ +} while (0) + +#define HASH_JEN(key,keylen,num_bkts,hashv,bkt) \ +do { \ + unsigned _hj_i,_hj_j,_hj_k; \ + unsigned char *_hj_key=(unsigned char*)(key); \ + hashv = 0xfeedbeef; \ + _hj_i = _hj_j = 0x9e3779b9; \ + _hj_k = (unsigned)(keylen); \ + while (_hj_k >= 12) { \ + _hj_i += (_hj_key[0] + ( (unsigned)_hj_key[1] << 8 ) \ + + ( (unsigned)_hj_key[2] << 16 ) \ + + ( (unsigned)_hj_key[3] << 24 ) ); \ + _hj_j += (_hj_key[4] + ( (unsigned)_hj_key[5] << 8 ) \ + + ( (unsigned)_hj_key[6] << 16 ) \ + + ( (unsigned)_hj_key[7] << 24 ) ); \ + hashv += (_hj_key[8] + ( (unsigned)_hj_key[9] << 8 ) \ + + ( (unsigned)_hj_key[10] << 16 ) \ + + ( (unsigned)_hj_key[11] << 24 ) ); \ + \ + HASH_JEN_MIX(_hj_i, _hj_j, hashv); \ + \ + _hj_key += 12; \ + _hj_k -= 12; \ + } \ + hashv += keylen; \ + switch ( _hj_k ) { \ + case 11: hashv += ( (unsigned)_hj_key[10] << 24 ); \ + case 10: hashv += ( (unsigned)_hj_key[9] << 16 ); \ + case 9: hashv += ( (unsigned)_hj_key[8] << 8 ); \ + case 8: _hj_j += ( (unsigned)_hj_key[7] << 24 ); \ + case 7: _hj_j += ( (unsigned)_hj_key[6] << 16 ); \ + case 6: _hj_j += ( (unsigned)_hj_key[5] << 8 ); \ + case 5: _hj_j += _hj_key[4]; \ + case 4: _hj_i += ( (unsigned)_hj_key[3] << 24 ); \ + case 3: _hj_i += ( (unsigned)_hj_key[2] << 16 ); \ + case 2: _hj_i += ( (unsigned)_hj_key[1] << 8 ); \ + case 1: _hj_i += _hj_key[0]; \ + } \ + HASH_JEN_MIX(_hj_i, _hj_j, hashv); \ + bkt = hashv & (num_bkts-1); \ +} while(0) + +/* The Paul Hsieh hash function */ +#undef get16bits +#if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__) \ + || defined(_MSC_VER) || defined (__BORLANDC__) || defined (__TURBOC__) +#define get16bits(d) (*((const uint16_t *) (d))) +#endif + +#if !defined (get16bits) +#define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8) \ + +(uint32_t)(((const uint8_t *)(d))[0]) ) +#endif +#define HASH_SFH(key,keylen,num_bkts,hashv,bkt) \ +do { \ + unsigned char *_sfh_key=(unsigned char*)(key); \ + uint32_t _sfh_tmp, _sfh_len = keylen; \ + \ + int _sfh_rem = _sfh_len & 3; \ + _sfh_len >>= 2; \ + hashv = 0xcafebabe; \ + \ + /* Main loop */ \ + for (;_sfh_len > 0; _sfh_len--) { \ + hashv += get16bits (_sfh_key); \ + _sfh_tmp = (uint32_t)(get16bits (_sfh_key+2)) << 11 ^ hashv; \ + hashv = (hashv << 16) ^ _sfh_tmp; \ + _sfh_key += 2*sizeof (uint16_t); \ + hashv += hashv >> 11; \ + } \ + \ + /* Handle end cases */ \ + switch (_sfh_rem) { \ + case 3: hashv += get16bits (_sfh_key); \ + hashv ^= hashv << 16; \ + hashv ^= (uint32_t)(_sfh_key[sizeof (uint16_t)] << 18); \ + hashv += hashv >> 11; \ + break; \ + case 2: hashv += get16bits (_sfh_key); \ + hashv ^= hashv << 11; \ + hashv += hashv >> 17; \ + break; \ + case 1: hashv += *_sfh_key; \ + hashv ^= hashv << 10; \ + hashv += hashv >> 1; \ + } \ + \ + /* Force "avalanching" of final 127 bits */ \ + hashv ^= hashv << 3; \ + hashv += hashv >> 5; \ + hashv ^= hashv << 4; \ + hashv += hashv >> 17; \ + hashv ^= hashv << 25; \ + hashv += hashv >> 6; \ + bkt = hashv & (num_bkts-1); \ +} while(0) + +#ifdef HASH_USING_NO_STRICT_ALIASING +/* The MurmurHash exploits some CPU's (x86,x86_64) tolerance for unaligned reads. + * For other types of CPU's (e.g. Sparc) an unaligned read causes a bus error. + * MurmurHash uses the faster approach only on CPU's where we know it's safe. + * + * Note the preprocessor built-in defines can be emitted using: + * + * gcc -m64 -dM -E - < /dev/null (on gcc) + * cc -## a.c (where a.c is a simple test file) (Sun Studio) + */ +#if (defined(__i386__) || defined(__x86_64__) || defined(_M_IX86)) +#define MUR_GETBLOCK(p,i) p[i] +#else /* non intel */ +#define MUR_PLUS0_ALIGNED(p) (((unsigned long)p & 0x3) == 0) +#define MUR_PLUS1_ALIGNED(p) (((unsigned long)p & 0x3) == 1) +#define MUR_PLUS2_ALIGNED(p) (((unsigned long)p & 0x3) == 2) +#define MUR_PLUS3_ALIGNED(p) (((unsigned long)p & 0x3) == 3) +#define WP(p) ((uint32_t*)((unsigned long)(p) & ~3UL)) +#if (defined(__BIG_ENDIAN__) || defined(SPARC) || defined(__ppc__) || defined(__ppc64__)) +#define MUR_THREE_ONE(p) ((((*WP(p))&0x00ffffff) << 8) | (((*(WP(p)+1))&0xff000000) >> 24)) +#define MUR_TWO_TWO(p) ((((*WP(p))&0x0000ffff) <<16) | (((*(WP(p)+1))&0xffff0000) >> 16)) +#define MUR_ONE_THREE(p) ((((*WP(p))&0x000000ff) <<24) | (((*(WP(p)+1))&0xffffff00) >> 8)) +#else /* assume little endian non-intel */ +#define MUR_THREE_ONE(p) ((((*WP(p))&0xffffff00) >> 8) | (((*(WP(p)+1))&0x000000ff) << 24)) +#define MUR_TWO_TWO(p) ((((*WP(p))&0xffff0000) >>16) | (((*(WP(p)+1))&0x0000ffff) << 16)) +#define MUR_ONE_THREE(p) ((((*WP(p))&0xff000000) >>24) | (((*(WP(p)+1))&0x00ffffff) << 8)) +#endif +#define MUR_GETBLOCK(p,i) (MUR_PLUS0_ALIGNED(p) ? ((p)[i]) : \ + (MUR_PLUS1_ALIGNED(p) ? MUR_THREE_ONE(p) : \ + (MUR_PLUS2_ALIGNED(p) ? MUR_TWO_TWO(p) : \ + MUR_ONE_THREE(p)))) +#endif +#define MUR_ROTL32(x,r) (((x) << (r)) | ((x) >> (32 - (r)))) +#define MUR_FMIX(_h) \ +do { \ + _h ^= _h >> 16; \ + _h *= 0x85ebca6b; \ + _h ^= _h >> 13; \ + _h *= 0xc2b2ae35l; \ + _h ^= _h >> 16; \ +} while(0) + +#define HASH_MUR(key,keylen,num_bkts,hashv,bkt) \ +do { \ + const uint8_t *_mur_data = (const uint8_t*)(key); \ + const int _mur_nblocks = (keylen) / 4; \ + uint32_t _mur_h1 = 0xf88D5353; \ + uint32_t _mur_c1 = 0xcc9e2d51; \ + uint32_t _mur_c2 = 0x1b873593; \ + uint32_t _mur_k1 = 0; \ + const uint8_t *_mur_tail; \ + const uint32_t *_mur_blocks = (const uint32_t*)(_mur_data+_mur_nblocks*4); \ + int _mur_i; \ + for(_mur_i = -_mur_nblocks; _mur_i; _mur_i++) { \ + _mur_k1 = MUR_GETBLOCK(_mur_blocks,_mur_i); \ + _mur_k1 *= _mur_c1; \ + _mur_k1 = MUR_ROTL32(_mur_k1,15); \ + _mur_k1 *= _mur_c2; \ + \ + _mur_h1 ^= _mur_k1; \ + _mur_h1 = MUR_ROTL32(_mur_h1,13); \ + _mur_h1 = _mur_h1*5+0xe6546b64; \ + } \ + _mur_tail = (const uint8_t*)(_mur_data + _mur_nblocks*4); \ + _mur_k1=0; \ + switch((keylen) & 3) { \ + case 3: _mur_k1 ^= _mur_tail[2] << 16; \ + case 2: _mur_k1 ^= _mur_tail[1] << 8; \ + case 1: _mur_k1 ^= _mur_tail[0]; \ + _mur_k1 *= _mur_c1; \ + _mur_k1 = MUR_ROTL32(_mur_k1,15); \ + _mur_k1 *= _mur_c2; \ + _mur_h1 ^= _mur_k1; \ + } \ + _mur_h1 ^= (keylen); \ + MUR_FMIX(_mur_h1); \ + hashv = _mur_h1; \ + bkt = hashv & (num_bkts-1); \ +} while(0) +#endif /* HASH_USING_NO_STRICT_ALIASING */ + +/* key comparison function; return 0 if keys equal */ +#define HASH_KEYCMP(a,b,len) memcmp(a,b,len) + +/* iterate over items in a known bucket to find desired item */ +#define HASH_FIND_IN_BKT(tbl,hh,head,keyptr,keylen_in,out) \ +do { \ + if (head.hh_head) DECLTYPE_ASSIGN(out,ELMT_FROM_HH(tbl,head.hh_head)); \ + else out=NULL; \ + while (out) { \ + if ((out)->hh.keylen == keylen_in) { \ + if ((HASH_KEYCMP((out)->hh.key,keyptr,keylen_in)) == 0) break; \ + } \ + if ((out)->hh.hh_next) DECLTYPE_ASSIGN(out,ELMT_FROM_HH(tbl,(out)->hh.hh_next)); \ + else out = NULL; \ + } \ +} while(0) + +/* add an item to a bucket */ +#define HASH_ADD_TO_BKT(head,addhh) \ +do { \ + head.count++; \ + (addhh)->hh_next = head.hh_head; \ + (addhh)->hh_prev = NULL; \ + if (head.hh_head) { (head).hh_head->hh_prev = (addhh); } \ + (head).hh_head=addhh; \ + if (head.count >= ((head.expand_mult+1) * HASH_BKT_CAPACITY_THRESH) \ + && (addhh)->tbl->noexpand != 1) { \ + HASH_EXPAND_BUCKETS((addhh)->tbl); \ + } \ +} while(0) + +/* remove an item from a given bucket */ +#define HASH_DEL_IN_BKT(hh,head,hh_del) \ + (head).count--; \ + if ((head).hh_head == hh_del) { \ + (head).hh_head = hh_del->hh_next; \ + } \ + if (hh_del->hh_prev) { \ + hh_del->hh_prev->hh_next = hh_del->hh_next; \ + } \ + if (hh_del->hh_next) { \ + hh_del->hh_next->hh_prev = hh_del->hh_prev; \ + } + +/* Bucket expansion has the effect of doubling the number of buckets + * and redistributing the items into the new buckets. Ideally the + * items will distribute more or less evenly into the new buckets + * (the extent to which this is true is a measure of the quality of + * the hash function as it applies to the key domain). + * + * With the items distributed into more buckets, the chain length + * (item count) in each bucket is reduced. Thus by expanding buckets + * the hash keeps a bound on the chain length. This bounded chain + * length is the essence of how a hash provides constant time lookup. + * + * The calculation of tbl->ideal_chain_maxlen below deserves some + * explanation. First, keep in mind that we're calculating the ideal + * maximum chain length based on the *new* (doubled) bucket count. + * In fractions this is just n/b (n=number of items,b=new num buckets). + * Since the ideal chain length is an integer, we want to calculate + * ceil(n/b). We don't depend on floating point arithmetic in this + * hash, so to calculate ceil(n/b) with integers we could write + * + * ceil(n/b) = (n/b) + ((n%b)?1:0) + * + * and in fact a previous version of this hash did just that. + * But now we have improved things a bit by recognizing that b is + * always a power of two. We keep its base 2 log handy (call it lb), + * so now we can write this with a bit shift and logical AND: + * + * ceil(n/b) = (n>>lb) + ( (n & (b-1)) ? 1:0) + * + */ +#define HASH_EXPAND_BUCKETS(tbl) \ +do { \ + unsigned _he_bkt; \ + unsigned _he_bkt_i; \ + struct UT_hash_handle *_he_thh, *_he_hh_nxt; \ + UT_hash_bucket *_he_new_buckets, *_he_newbkt; \ + _he_new_buckets = (UT_hash_bucket*)uthash_malloc( \ + 2 * tbl->num_buckets * sizeof(struct UT_hash_bucket)); \ + if (!_he_new_buckets) { uthash_fatal( "out of memory"); } \ + memset(_he_new_buckets, 0, \ + 2 * tbl->num_buckets * sizeof(struct UT_hash_bucket)); \ + tbl->ideal_chain_maxlen = \ + (tbl->num_items >> (tbl->log2_num_buckets+1)) + \ + ((tbl->num_items & ((tbl->num_buckets*2)-1)) ? 1 : 0); \ + tbl->nonideal_items = 0; \ + for(_he_bkt_i = 0; _he_bkt_i < tbl->num_buckets; _he_bkt_i++) \ + { \ + _he_thh = tbl->buckets[ _he_bkt_i ].hh_head; \ + while (_he_thh) { \ + _he_hh_nxt = _he_thh->hh_next; \ + HASH_TO_BKT( _he_thh->hashv, tbl->num_buckets*2, _he_bkt); \ + _he_newbkt = &(_he_new_buckets[ _he_bkt ]); \ + if (++(_he_newbkt->count) > tbl->ideal_chain_maxlen) { \ + tbl->nonideal_items++; \ + _he_newbkt->expand_mult = _he_newbkt->count / \ + tbl->ideal_chain_maxlen; \ + } \ + _he_thh->hh_prev = NULL; \ + _he_thh->hh_next = _he_newbkt->hh_head; \ + if (_he_newbkt->hh_head) _he_newbkt->hh_head->hh_prev = \ + _he_thh; \ + _he_newbkt->hh_head = _he_thh; \ + _he_thh = _he_hh_nxt; \ + } \ + } \ + uthash_free( tbl->buckets, tbl->num_buckets*sizeof(struct UT_hash_bucket) ); \ + tbl->num_buckets *= 2; \ + tbl->log2_num_buckets++; \ + tbl->buckets = _he_new_buckets; \ + tbl->ineff_expands = (tbl->nonideal_items > (tbl->num_items >> 1)) ? \ + (tbl->ineff_expands+1) : 0; \ + if (tbl->ineff_expands > 1) { \ + tbl->noexpand=1; \ + uthash_noexpand_fyi(tbl); \ + } \ + uthash_expand_fyi(tbl); \ +} while(0) + + +/* This is an adaptation of Simon Tatham's O(n log(n)) mergesort */ +/* Note that HASH_SORT assumes the hash handle name to be hh. + * HASH_SRT was added to allow the hash handle name to be passed in. */ +#define HASH_SORT(head,cmpfcn) HASH_SRT(hh,head,cmpfcn) +#define HASH_SRT(hh,head,cmpfcn) \ +do { \ + unsigned _hs_i; \ + unsigned _hs_looping,_hs_nmerges,_hs_insize,_hs_psize,_hs_qsize; \ + struct UT_hash_handle *_hs_p, *_hs_q, *_hs_e, *_hs_list, *_hs_tail; \ + if (head) { \ + _hs_insize = 1; \ + _hs_looping = 1; \ + _hs_list = &((head)->hh); \ + while (_hs_looping) { \ + _hs_p = _hs_list; \ + _hs_list = NULL; \ + _hs_tail = NULL; \ + _hs_nmerges = 0; \ + while (_hs_p) { \ + _hs_nmerges++; \ + _hs_q = _hs_p; \ + _hs_psize = 0; \ + for ( _hs_i = 0; _hs_i < _hs_insize; _hs_i++ ) { \ + _hs_psize++; \ + _hs_q = (UT_hash_handle*)((_hs_q->next) ? \ + ((void*)((char*)(_hs_q->next) + \ + (head)->hh.tbl->hho)) : NULL); \ + if (! (_hs_q) ) break; \ + } \ + _hs_qsize = _hs_insize; \ + while ((_hs_psize > 0) || ((_hs_qsize > 0) && _hs_q )) { \ + if (_hs_psize == 0) { \ + _hs_e = _hs_q; \ + _hs_q = (UT_hash_handle*)((_hs_q->next) ? \ + ((void*)((char*)(_hs_q->next) + \ + (head)->hh.tbl->hho)) : NULL); \ + _hs_qsize--; \ + } else if ( (_hs_qsize == 0) || !(_hs_q) ) { \ + _hs_e = _hs_p; \ + if (_hs_p){ \ + _hs_p = (UT_hash_handle*)((_hs_p->next) ? \ + ((void*)((char*)(_hs_p->next) + \ + (head)->hh.tbl->hho)) : NULL); \ + } \ + _hs_psize--; \ + } else if (( \ + cmpfcn(DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl,_hs_p)), \ + DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl,_hs_q))) \ + ) <= 0) { \ + _hs_e = _hs_p; \ + if (_hs_p){ \ + _hs_p = (UT_hash_handle*)((_hs_p->next) ? \ + ((void*)((char*)(_hs_p->next) + \ + (head)->hh.tbl->hho)) : NULL); \ + } \ + _hs_psize--; \ + } else { \ + _hs_e = _hs_q; \ + _hs_q = (UT_hash_handle*)((_hs_q->next) ? \ + ((void*)((char*)(_hs_q->next) + \ + (head)->hh.tbl->hho)) : NULL); \ + _hs_qsize--; \ + } \ + if ( _hs_tail ) { \ + _hs_tail->next = ((_hs_e) ? \ + ELMT_FROM_HH((head)->hh.tbl,_hs_e) : NULL); \ + } else { \ + _hs_list = _hs_e; \ + } \ + if (_hs_e) { \ + _hs_e->prev = ((_hs_tail) ? \ + ELMT_FROM_HH((head)->hh.tbl,_hs_tail) : NULL); \ + } \ + _hs_tail = _hs_e; \ + } \ + _hs_p = _hs_q; \ + } \ + if (_hs_tail){ \ + _hs_tail->next = NULL; \ + } \ + if ( _hs_nmerges <= 1 ) { \ + _hs_looping=0; \ + (head)->hh.tbl->tail = _hs_tail; \ + DECLTYPE_ASSIGN(head,ELMT_FROM_HH((head)->hh.tbl, _hs_list)); \ + } \ + _hs_insize *= 2; \ + } \ + HASH_FSCK(hh,head); \ + } \ +} while (0) + +/* This function selects items from one hash into another hash. + * The end result is that the selected items have dual presence + * in both hashes. There is no copy of the items made; rather + * they are added into the new hash through a secondary hash + * hash handle that must be present in the structure. */ +#define HASH_SELECT(hh_dst, dst, hh_src, src, cond) \ +do { \ + unsigned _src_bkt, _dst_bkt; \ + void *_last_elt=NULL, *_elt; \ + UT_hash_handle *_src_hh, *_dst_hh, *_last_elt_hh=NULL; \ + ptrdiff_t _dst_hho = ((char*)(&(dst)->hh_dst) - (char*)(dst)); \ + if (src) { \ + for(_src_bkt=0; _src_bkt < (src)->hh_src.tbl->num_buckets; _src_bkt++) { \ + for(_src_hh = (src)->hh_src.tbl->buckets[_src_bkt].hh_head; \ + _src_hh; \ + _src_hh = _src_hh->hh_next) { \ + _elt = ELMT_FROM_HH((src)->hh_src.tbl, _src_hh); \ + if (cond(_elt)) { \ + _dst_hh = (UT_hash_handle*)(((char*)_elt) + _dst_hho); \ + _dst_hh->key = _src_hh->key; \ + _dst_hh->keylen = _src_hh->keylen; \ + _dst_hh->hashv = _src_hh->hashv; \ + _dst_hh->prev = _last_elt; \ + _dst_hh->next = NULL; \ + if (_last_elt_hh) { _last_elt_hh->next = _elt; } \ + if (!dst) { \ + DECLTYPE_ASSIGN(dst,_elt); \ + HASH_MAKE_TABLE(hh_dst,dst); \ + } else { \ + _dst_hh->tbl = (dst)->hh_dst.tbl; \ + } \ + HASH_TO_BKT(_dst_hh->hashv, _dst_hh->tbl->num_buckets, _dst_bkt); \ + HASH_ADD_TO_BKT(_dst_hh->tbl->buckets[_dst_bkt],_dst_hh); \ + (dst)->hh_dst.tbl->num_items++; \ + _last_elt = _elt; \ + _last_elt_hh = _dst_hh; \ + } \ + } \ + } \ + } \ + HASH_FSCK(hh_dst,dst); \ +} while (0) + +#define HASH_CLEAR(hh,head) \ +do { \ + if (head) { \ + uthash_free((head)->hh.tbl->buckets, \ + (head)->hh.tbl->num_buckets*sizeof(struct UT_hash_bucket)); \ + HASH_BLOOM_FREE((head)->hh.tbl); \ + uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ + (head)=NULL; \ + } \ +} while(0) + +#define HASH_OVERHEAD(hh,head) \ + (size_t)((((head)->hh.tbl->num_items * sizeof(UT_hash_handle)) + \ + ((head)->hh.tbl->num_buckets * sizeof(UT_hash_bucket)) + \ + (sizeof(UT_hash_table)) + \ + (HASH_BLOOM_BYTELEN))) + +#ifdef NO_DECLTYPE +#define HASH_ITER(hh,head,el,tmp) \ +for((el)=(head), (*(char**)(&(tmp)))=(char*)((head)?(head)->hh.next:NULL); \ + el; (el)=(tmp),(*(char**)(&(tmp)))=(char*)((tmp)?(tmp)->hh.next:NULL)) +#else +#define HASH_ITER(hh,head,el,tmp) \ +for((el)=(head),(tmp)=DECLTYPE(el)((head)?(head)->hh.next:NULL); \ + el; (el)=(tmp),(tmp)=DECLTYPE(el)((tmp)?(tmp)->hh.next:NULL)) +#endif + +/* obtain a count of items in the hash */ +#define HASH_COUNT(head) HASH_CNT(hh,head) +#define HASH_CNT(hh,head) ((head)?((head)->hh.tbl->num_items):0) + +typedef struct UT_hash_bucket { + struct UT_hash_handle *hh_head; + unsigned count; + + /* expand_mult is normally set to 0. In this situation, the max chain length + * threshold is enforced at its default value, HASH_BKT_CAPACITY_THRESH. (If + * the bucket's chain exceeds this length, bucket expansion is triggered). + * However, setting expand_mult to a non-zero value delays bucket expansion + * (that would be triggered by additions to this particular bucket) + * until its chain length reaches a *multiple* of HASH_BKT_CAPACITY_THRESH. + * (The multiplier is simply expand_mult+1). The whole idea of this + * multiplier is to reduce bucket expansions, since they are expensive, in + * situations where we know that a particular bucket tends to be overused. + * It is better to let its chain length grow to a longer yet-still-bounded + * value, than to do an O(n) bucket expansion too often. + */ + unsigned expand_mult; + +} UT_hash_bucket; + +/* random signature used only to find hash tables in external analysis */ +#define HASH_SIGNATURE 0xa0111fe1 +#define HASH_BLOOM_SIGNATURE 0xb12220f2 + +typedef struct UT_hash_table { + UT_hash_bucket *buckets; + unsigned num_buckets, log2_num_buckets; + unsigned num_items; + struct UT_hash_handle *tail; /* tail hh in app order, for fast append */ + ptrdiff_t hho; /* hash handle offset (byte pos of hash handle in element */ + + /* in an ideal situation (all buckets used equally), no bucket would have + * more than ceil(#items/#buckets) items. that's the ideal chain length. */ + unsigned ideal_chain_maxlen; + + /* nonideal_items is the number of items in the hash whose chain position + * exceeds the ideal chain maxlen. these items pay the penalty for an uneven + * hash distribution; reaching them in a chain traversal takes >ideal steps */ + unsigned nonideal_items; + + /* ineffective expands occur when a bucket doubling was performed, but + * afterward, more than half the items in the hash had nonideal chain + * positions. If this happens on two consecutive expansions we inhibit any + * further expansion, as it's not helping; this happens when the hash + * function isn't a good fit for the key domain. When expansion is inhibited + * the hash will still work, albeit no longer in constant time. */ + unsigned ineff_expands, noexpand; + + uint32_t signature; /* used only to find hash tables in external analysis */ +#ifdef HASH_BLOOM + uint32_t bloom_sig; /* used only to test bloom exists in external analysis */ + uint8_t *bloom_bv; + char bloom_nbits; +#endif + +} UT_hash_table; + +typedef struct UT_hash_handle { + struct UT_hash_table *tbl; + void *prev; /* prev element in app order */ + void *next; /* next element in app order */ + struct UT_hash_handle *hh_prev; /* previous hh in bucket order */ + struct UT_hash_handle *hh_next; /* next hh in bucket order */ + void *key; /* ptr to enclosing struct's key */ + unsigned keylen; /* enclosing struct's key len */ + unsigned hashv; /* result of hash-fcn(key) */ +} UT_hash_handle; + +#endif /* UTHASH_H */ diff --git a/drive-sdk/examples/vehicle-scan/vehicle-scan.c b/drive-sdk/examples/vehicle-scan/vehicle-scan.c new file mode 100644 index 0000000..4ecc7e2 --- /dev/null +++ b/drive-sdk/examples/vehicle-scan/vehicle-scan.c @@ -0,0 +1,471 @@ +/* + * vehicle-scan.c + * + * drive-sdk - Anki Drive SDK + * + * Copyright (C) 2014 Anki, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + * Portions of this software are derived from BlueZ, a Bluetooth protocol stack for + * Linux. The license for BlueZ is included below. + */ + +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2000-2001 Qualcomm Incorporated + * Copyright (C) 2002-2003 Maxim Krasnyansky + * Copyright (C) 2002-2010 Marcel Holtmann + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define for_each_opt(opt, long, short) while ((opt=getopt_long(argc, argv, short ? short:"+", long, NULL)) != -1) + +#include +#include +#include + +#include "uthash.h" + +#include + +/* Unofficial value, might still change */ +#define LE_LINK 0x03 + +#define FLAGS_AD_TYPE 0x01 +#define FLAGS_LIMITED_MODE_BIT 0x01 +#define FLAGS_GENERAL_MODE_BIT 0x02 + +#define EIR_FLAGS 0x01 /* flags */ +#define EIR_UUID16_SOME 0x02 /* 16-bit UUID, more available */ +#define EIR_UUID16_ALL 0x03 /* 16-bit UUID, all listed */ +#define EIR_UUID32_SOME 0x04 /* 32-bit UUID, more available */ +#define EIR_UUID32_ALL 0x05 /* 32-bit UUID, all listed */ +#define EIR_UUID128_SOME 0x06 /* 128-bit UUID, more available */ +#define EIR_UUID128_ALL 0x07 /* 128-bit UUID, all listed */ +#define EIR_NAME_SHORT 0x08 /* shortened local name */ +#define EIR_NAME_COMPLETE 0x09 /* complete local name */ +#define EIR_TX_POWER 0x0A /* transmit power level */ +#define EIR_DEVICE_ID 0x10 /* device ID */ + +struct _vehicle { + bdaddr_t address; + anki_vehicle_adv_t adv; + uint8_t scan_complete; + UT_hash_handle hh; +}; +typedef struct _vehicle vehicle_t; + +static volatile int signal_received = 0; + +static void hex_dump(char *pref, int width, unsigned char *buf, int len) +{ + register int i,n; + + for (i = 0, n = 1; i < len; i++, n++) { + if (n == 1) + printf("%s", pref); + printf("%2.2X ", buf[i]); + if (n == width) { + printf("\n"); + n = 0; + } + } + if (i && n!=1) + printf("\n"); +} + +static struct option lescan_options[] = { + { "help", 0, 0, 'h' }, + { "privacy", 0, 0, 'p' }, + { "passive", 0, 0, 'P' }, + { "whitelist", 0, 0, 'w' }, + { "discovery", 1, 0, 'd' }, + { "duplicates", 0, 0, 'D' }, + { 0, 0, 0, 0 } +}; + +static const char *lescan_help = + "Usage:\n" + "\tlescan [--privacy] enable privacy\n" + "\tlescan [--passive] set scan type passive (default active)\n" + "\tlescan [--whitelist] scan for address in the whitelist only\n" + "\tlescan [--discovery=g|l] enable general or limited discovery" + "procedure\n" + "\tlescan [--duplicates] don't filter duplicates\n"; + +static void helper_arg(int min_num_arg, int max_num_arg, int *argc, + char ***argv, const char *usage) +{ + *argc -= optind; + /* too many arguments, but when "max_num_arg < min_num_arg" then no + limiting (prefer "max_num_arg=-1" to gen infinity) + */ + if ( (*argc > max_num_arg) && (max_num_arg >= min_num_arg ) ) { + fprintf(stderr, "%s: too many arguments (maximal: %i)\n", + *argv[0], max_num_arg); + printf("%s", usage); + exit(1); + } + + /* print usage */ + if (*argc < min_num_arg) { + fprintf(stderr, "%s: too few arguments (minimal: %i)\n", + *argv[0], min_num_arg); + printf("%s", usage); + exit(0); + } + + *argv += optind; +} + + +static void sigint_handler(int sig) +{ + signal_received = sig; +} + +static int read_flags(uint8_t *flags, const uint8_t *data, size_t size) +{ + size_t offset; + + if (!flags || !data) + return -EINVAL; + + offset = 0; + while (offset < size) { + uint8_t len = data[offset]; + uint8_t type; + + /* Check if it is the end of the significant part */ + if (len == 0) + break; + + if (len + offset > size) + break; + + type = data[offset + 1]; + + if (type == FLAGS_AD_TYPE) { + *flags = data[offset + 2]; + return 0; + } + + offset += 1 + len; + } + + return -ENOENT; +} + +static int check_report_filter(uint8_t procedure, le_advertising_info *info) +{ + uint8_t flags; + + /* If no discovery procedure is set, all reports are treat as valid */ + if (procedure == 0) + return 1; + + /* Read flags AD type value from the advertising report if it exists */ + if (read_flags(&flags, info->data, info->length)) + return 0; + + switch (procedure) { + case 'l': /* Limited Discovery Procedure */ + if (flags & FLAGS_LIMITED_MODE_BIT) + return 1; + break; + case 'g': /* General Discovery Procedure */ + if (flags & (FLAGS_LIMITED_MODE_BIT | FLAGS_GENERAL_MODE_BIT)) + return 1; + break; + default: + fprintf(stderr, "Unknown discovery procedure\n"); + } + + return 0; +} + +static void eir_parse_name(uint8_t *eir, size_t eir_len, + char *buf, size_t buf_len) +{ + size_t offset; + + offset = 0; + while (offset < eir_len) { + uint8_t field_len = eir[0]; + size_t name_len; + + /* Check for the end of EIR */ + if (field_len == 0) + break; + + if (offset + field_len > eir_len) + goto failed; + + printf("eir_type: %02x: ", eir[1]); + hex_dump("0x", 32, &eir[2], field_len-1); + + switch (eir[1]) { + case EIR_NAME_SHORT: + case EIR_NAME_COMPLETE: + name_len = field_len - 1; + if (name_len > buf_len) + goto failed; + + memcpy(buf, &eir[2], name_len); + return; + } + + offset += field_len + 1; + eir += field_len + 1; + } + +failed: + snprintf(buf, buf_len, "(unknown)"); +} + +vehicle_t *vehicles = NULL; + +static int print_advertising_devices(int dd, uint8_t filter_type) +{ + unsigned char buf[HCI_MAX_EVENT_SIZE], *ptr; + struct hci_filter nf, of; + struct sigaction sa; + socklen_t olen; + int len; + + olen = sizeof(of); + if (getsockopt(dd, SOL_HCI, HCI_FILTER, &of, &olen) < 0) { + printf("Could not get socket options\n"); + return -1; + } + + hci_filter_clear(&nf); + hci_filter_set_ptype(HCI_EVENT_PKT, &nf); + hci_filter_set_event(EVT_LE_META_EVENT, &nf); + + if (setsockopt(dd, SOL_HCI, HCI_FILTER, &nf, sizeof(nf)) < 0) { + printf("Could not set socket options\n"); + return -1; + } + + memset(&sa, 0, sizeof(sa)); + sa.sa_flags = SA_NOCLDSTOP; + sa.sa_handler = sigint_handler; + sigaction(SIGINT, &sa, NULL); + + while (1) { + evt_le_meta_event *meta; + le_advertising_info *info; + char addr[18]; + + while ((len = read(dd, buf, sizeof(buf))) < 0) { + if (errno == EINTR && signal_received == SIGINT) { + len = 0; + goto done; + } + + if (errno == EAGAIN || errno == EINTR) + continue; + goto done; + } + + ptr = buf + (1 + HCI_EVENT_HDR_SIZE); + len -= (1 + HCI_EVENT_HDR_SIZE); + + meta = (void *) ptr; + + if (meta->subevent != 0x02) + goto done; + + /* Ignoring multiple reports */ + info = (le_advertising_info *) (meta->data + 1); + if (check_report_filter(filter_type, info)) { + char name[30]; + + memset(name, 0, sizeof(name)); + + ba2str(&info->bdaddr, addr); + + vehicle_t vehicle; + vehicle_t *v = &vehicle; + + HASH_FIND(hh, vehicles, &info->bdaddr, sizeof(bdaddr_t), v); + if (v == NULL) { + v = (vehicle_t *)malloc(sizeof(vehicle_t)); + memset(&v->adv, 0, sizeof(anki_vehicle_adv_t)); + memcpy(&v->address, &info->bdaddr, sizeof(bdaddr_t)); + HASH_ADD(hh, vehicles, address, sizeof(bdaddr_t), v); + } + + int err = anki_vehicle_parse_adv_record(info->data, info->length, &v->adv); + + if (err == 0 && v->adv.mfg_data.identifier > 0 && v->adv.local_name.version > 0 && !v->scan_complete) { + v->scan_complete = 1; + printf("%s ", addr); + + const char *model = NULL; + switch(v->adv.mfg_data.model_id) { + case 1: + model = "Kourai"; + break; + case 2: + model = "Boson"; + break; + case 3: + model = "Rho"; + break; + case 4: + model = "Katal"; + break; + default: + model = "Unknown"; + break; + } + + printf("%s [v%04x] (%s %04x)\n", v->adv.local_name.name, v->adv.local_name.version & 0xffff, model, v->adv.mfg_data.identifier & 0xffff); + } + } + } + +done: + setsockopt(dd, SOL_HCI, HCI_FILTER, &of, sizeof(of)); + + if (len < 0) + return -1; + + return 0; +} + +static void cmd_lescan(int dev_id, int argc, char **argv) +{ + int err, opt, dd; + uint8_t own_type = 0x00; + uint8_t scan_type = 0x01; + uint8_t filter_type = 0; + uint8_t filter_policy = 0x00; + uint16_t interval = htobs(0x0010); + uint16_t window = htobs(0x0010); + uint8_t filter_dup = 1; + + for_each_opt(opt, lescan_options, NULL) { + switch (opt) { + case 'p': + own_type = 0x01; /* Random */ + break; + case 'P': + scan_type = 0x00; /* Passive */ + break; + case 'w': + filter_policy = 0x01; /* Whitelist */ + break; + case 'd': + filter_type = optarg[0]; + if (filter_type != 'g' && filter_type != 'l') { + fprintf(stderr, "Unknown discovery procedure\n"); + exit(1); + } + + interval = htobs(0x0012); + window = htobs(0x0012); + break; + case 'D': + filter_dup = 0x00; + break; + default: + printf("%s", lescan_help); + return; + } + } + helper_arg(0, 1, &argc, &argv, lescan_help); + + if (dev_id < 0) + dev_id = hci_get_route(NULL); + + dd = hci_open_dev(dev_id); + if (dd < 0) { + perror("Could not open device"); + exit(1); + exit(1); + } + + err = hci_le_set_scan_parameters(dd, scan_type, interval, window, + own_type, filter_policy, 2000); + if (err < 0) { + perror("Set scan parameters failed"); + exit(1); + } + + err = hci_le_set_scan_enable(dd, 0x01, filter_dup, 2000); + if (err < 0) { + perror("Enable scan failed"); + exit(1); + } + + printf("LE Scan ...\n"); + + err = print_advertising_devices(dd, filter_type); + if (err < 0) { + perror("Could not receive advertising events"); + exit(1); + } + + err = hci_le_set_scan_enable(dd, 0x00, filter_dup, 2000); + if (err < 0) { + fprintf(stderr, "Disable scan failed with error code: %d", err); + hci_close_dev(dd); + exit(1); + } + + hci_close_dev(dd); +} + +int main(int argc, char *argv[]) { + int opt, i, dev_id = -1; + + cmd_lescan(dev_id, argc, argv); + + return 0; +} diff --git a/drive-sdk/examples/vehicle-tool/.gitignore b/drive-sdk/examples/vehicle-tool/.gitignore new file mode 100644 index 0000000..61ceb70 --- /dev/null +++ b/drive-sdk/examples/vehicle-tool/.gitignore @@ -0,0 +1,4 @@ +.deps +.dirstamp +vehicle-tool + diff --git a/drive-sdk/examples/vehicle-tool/CMakeLists.txt b/drive-sdk/examples/vehicle-tool/CMakeLists.txt new file mode 100755 index 0000000..58a67d3 --- /dev/null +++ b/drive-sdk/examples/vehicle-tool/CMakeLists.txt @@ -0,0 +1,31 @@ +set(CMAKE_INCLUDE_CURRENT_DIR ON) + +SET (CMAKE_C_FLAGS "") + +include(FindGLIB2) +include(FindReadline) + +include_directories(${drivekit_SOURCE_DIR}/include + ${bzle_SOURCE_DIR}/include + ${GLIB2_INCLUDE_DIRS} + ${READLINE_INCLUDE_DIR} + ) + + +# Add sources +set(vehicleTool_SOURCES + vehicle_tool.c + vehicle_cmd.c + display.c +) + +add_executable(vehicle-tool ${vehicleTool_SOURCES}) +target_link_libraries(vehicle-tool + ankidrive + bzle + ${GLIB2_LIBRARIES} + ${READLINE_LIBRARY} +) +install(TARGETS vehicle-tool + RUNTIME DESTINATION bin +) diff --git a/drive-sdk/examples/vehicle-tool/display.c b/drive-sdk/examples/vehicle-tool/display.c new file mode 100644 index 0000000..bc891af --- /dev/null +++ b/drive-sdk/examples/vehicle-tool/display.c @@ -0,0 +1,64 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2012 Intel Corporation. All rights reserved. + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include +#include +#include +#include + +#include "display.h" + +void rl_printf(const char *fmt, ...) +{ + va_list args; + bool save_input; + char *saved_line; + int saved_point; + + save_input = !RL_ISSTATE(RL_STATE_DONE); + + if (save_input) { + saved_point = rl_point; + saved_line = rl_copy_text(0, rl_end); + rl_save_prompt(); + rl_replace_line("", 0); + rl_redisplay(); + } + + va_start(args, fmt); + vprintf(fmt, args); + va_end(args); + + if (save_input) { + rl_restore_prompt(); + rl_replace_line(saved_line, 0); + rl_point = saved_point; + rl_redisplay(); + free(saved_line); + } +} diff --git a/drive-sdk/examples/vehicle-tool/display.h b/drive-sdk/examples/vehicle-tool/display.h new file mode 100644 index 0000000..91a0be9 --- /dev/null +++ b/drive-sdk/examples/vehicle-tool/display.h @@ -0,0 +1,32 @@ +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2012 Intel Corporation. All rights reserved. + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#define COLOR_OFF "\x1B[0m" +#define COLOR_RED "\x1B[0;91m" +#define COLOR_GREEN "\x1B[0;92m" +#define COLOR_YELLOW "\x1B[0;93m" +#define COLOR_BLUE "\x1B[0;94m" +#define COLOR_BOLDGRAY "\x1B[1;30m" +#define COLOR_BOLDWHITE "\x1B[1;37m" + +void rl_printf(const char *fmt, ...) __attribute__((format(printf, 1, 2))); diff --git a/drive-sdk/examples/vehicle-tool/vehicle_cmd.c b/drive-sdk/examples/vehicle-tool/vehicle_cmd.c new file mode 100644 index 0000000..172a922 --- /dev/null +++ b/drive-sdk/examples/vehicle-tool/vehicle_cmd.c @@ -0,0 +1,1155 @@ +/* + * vehicle-tool + * + * Example vehicle control tool for Anki Drive SDK + * + * Copyright (C) 2014 Anki, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + * Portions of this software are derived from BlueZ, a Bluetooth protocol stack for + * Linux. The license for BlueZ is included below. + */ + +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2011 Nokia Corporation + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include "display.h" + +#include + +static GIOChannel *iochannel = NULL; +static GAttrib *attrib = NULL; +static GMainLoop *event_loop; +static GString *prompt; + +static char *opt_src = NULL; +static char *opt_dst = NULL; +static char *opt_dst_type = NULL; +static char *opt_sec_level = NULL; +static int opt_psm = 0; +static int opt_mtu = 0; +static int start; +static int end; + + +typedef struct anki_vehicle { + struct gatt_char read_char; + struct gatt_char write_char; +} anki_vehicle_t; + +static anki_vehicle_t vehicle; + +static char *effects_by_name[] = { "STEADY", "FADE", "THROB", "FLASH", "RANDOM", NULL }; +static uint8_t effect_invalid = 0xff; +static char *channels_by_name[] = { "RED", "TAIL", "BLUE", "GREEN", "FRONTL", "FRONTR", NULL }; +static uint8_t channel_invalid = 0xff; +static char* turn_types_by_name[] = { "NONE", "LEFT", "RIGHT", "UTURN", "UTURN_JUMP", NULL }; + +static void discover_services(void); +static void cmd_help(int argcp, char **argvp); + +static enum state { + STATE_DISCONNECTED, + STATE_CONNECTING, + STATE_CONNECTED +} conn_state; + +#define error(fmt, arg...) \ + rl_printf(COLOR_RED "Error: " COLOR_OFF fmt, ## arg) + +#define failed(fmt, arg...) \ + rl_printf(COLOR_RED "Command Failed: " COLOR_OFF fmt, ## arg) + +static char *get_prompt(void) +{ + if (conn_state == STATE_CONNECTED) + g_string_assign(prompt, COLOR_BLUE); + else + g_string_assign(prompt, ""); + + if (opt_dst) + g_string_append_printf(prompt, "[%17s]", opt_dst); + else + g_string_append_printf(prompt, "[%17s]", ""); + + if (conn_state == STATE_CONNECTED) + g_string_append(prompt, COLOR_OFF); + + if (opt_psm) + g_string_append(prompt, "[BR]"); + else + g_string_append(prompt, "[LE]"); + + g_string_append(prompt, "> "); + + return prompt->str; +} + + +static void set_state(enum state st) +{ + conn_state = st; + rl_set_prompt(get_prompt()); +} + +static void handle_vehicle_msg_response(const uint8_t *data, uint16_t len) +{ + if (len > sizeof(anki_vehicle_msg_t)) { + error("Invalid vehicle response\n"); + return; + } + + const anki_vehicle_msg_t *msg = (const anki_vehicle_msg_t *)data; + switch(msg->msg_id) { + case ANKI_VEHICLE_MSG_V2C_PING_RESPONSE: + { + rl_printf("[read] PING_RESPONSE\n"); + break; + } + case ANKI_VEHICLE_MSG_V2C_VERSION_RESPONSE: + { + const anki_vehicle_msg_version_response_t *m = (const anki_vehicle_msg_version_response_t *)msg; + rl_printf("[read] VERSION_RESPONSE: 0x%04x\n", m->version); + + break; + } + default: + // rl_printf("Received unhandled vehicle message of type 0x%02x\n", msg->msg_id); + break; + } +} + +static void events_handler(const uint8_t *pdu, uint16_t len, gpointer user_data) +{ + uint16_t handle = att_get_u16(&pdu[1]); + + if (pdu[0] == ATT_OP_HANDLE_NOTIFY) { + uint16_t handle = att_get_u16(&pdu[1]); + if (handle != vehicle.read_char.value_handle) { + error("Invalid vehicle read handle: 0x%04x\n", handle); + return; + } + const uint8_t *data = &pdu[3]; + const uint16_t datalen = len-3; + + handle_vehicle_msg_response(data, datalen); + return; + } +} + +static void connect_cb(GIOChannel *io, GError *err, gpointer user_data) +{ + if (err) { + set_state(STATE_DISCONNECTED); + error("%s\n", err->message); + return; + } + + attrib = g_attrib_new(iochannel); + g_attrib_register(attrib, ATT_OP_HANDLE_NOTIFY, GATTRIB_ALL_HANDLES, + events_handler, attrib, NULL); + g_attrib_register(attrib, ATT_OP_HANDLE_IND, GATTRIB_ALL_HANDLES, + events_handler, attrib, NULL); + set_state(STATE_CONNECTED); + rl_printf("Connection successful\n"); + + discover_services(); +} + +static void disconnect_io() +{ + if (conn_state == STATE_DISCONNECTED) + return; + + g_attrib_unref(attrib); + attrib = NULL; + opt_mtu = 0; + + g_io_channel_shutdown(iochannel, FALSE, NULL); + g_io_channel_unref(iochannel); + iochannel = NULL; + + set_state(STATE_DISCONNECTED); +} + +static void discover_char_cb(guint8 status, GSList *characteristics, gpointer user_data) +{ + GSList *l; + + if (status) { + error("Discover all characteristics failed: %s\n", + att_ecode2str(status)); + return; + } + + for (l = characteristics; l; l = l->next) { + struct gatt_char *chars = l->data; + + if (strncasecmp(chars->uuid, ANKI_STR_CHR_READ_UUID, strlen(ANKI_STR_CHR_READ_UUID)) == 0) { + memmove(&(vehicle.read_char), chars, sizeof(struct gatt_char)); + rl_printf("Anki Read Characteristic: %s ", chars->uuid); + rl_printf("[handle: 0x%04x, char properties: 0x%02x, char value " + "handle: 0x%04x]\n", chars->handle, + chars->properties, chars->value_handle); + } + + if (strncasecmp(chars->uuid, ANKI_STR_CHR_WRITE_UUID, strlen(ANKI_STR_CHR_WRITE_UUID)) == 0) { + memmove(&(vehicle.write_char), chars, sizeof(struct gatt_char)); + rl_printf("Anki Write Characteristic: %s ", chars->uuid); + rl_printf("[handle: 0x%04x, char properties: 0x%02x, char value " + "handle: 0x%04x]\n", chars->handle, + chars->properties, chars->value_handle); + } + } + + if (vehicle.read_char.handle > 0 && vehicle.write_char.handle > 0) { + // register for notifications when the vehicle sends data. + // We do this by setting the notification bit on the + // client configuration characteristic: + // see: + // https://developer.bluetooth.org/gatt/descriptors/Pages/DescriptorViewer.aspx?u=org.bluetooth.descriptor.gatt.client_characteristic_configuration.xml + uint8_t notify_cmd[] = { 0x01, 0x00 }; + gatt_write_cmd(attrib, vehicle.write_char.properties, notify_cmd, 2, NULL, NULL); + } +} + +static void char_read_cb(guint8 status, const guint8 *pdu, guint16 plen, + gpointer user_data) +{ + if (status != 0) { + error("Characteristic value/descriptor read failed: %s\n", + att_ecode2str(status)); + return; + } + + uint8_t value[plen]; + ssize_t vlen = dec_read_resp(pdu, plen, value, sizeof(value)); + if (vlen < 0) { + error("Protocol error\n"); + return; + } + + handle_vehicle_msg_response(value, vlen); +} + +static void cmd_exit(int argcp, char **argvp) +{ + rl_callback_handler_remove(); + g_main_loop_quit(event_loop); +} + +static gboolean channel_watcher(GIOChannel *chan, GIOCondition cond, + gpointer user_data) +{ + disconnect_io(); + + return FALSE; +} + +static void cmd_connect(int argcp, char **argvp) +{ + GError *gerr = NULL; + + if (conn_state != STATE_DISCONNECTED) + return; + + if (argcp > 1) { + g_free(opt_dst); + opt_dst = g_strdup(argvp[1]); + + g_free(opt_dst_type); + if (argcp > 2) + opt_dst_type = g_strdup(argvp[2]); + else + opt_dst_type = g_strdup("public"); + } + + if (opt_dst == NULL) { + error("Remote Bluetooth address required\n"); + return; + } + + rl_printf("Attempting to connect to %s\n", opt_dst); + set_state(STATE_CONNECTING); + iochannel = gatt_connect(opt_src, opt_dst, opt_dst_type, opt_sec_level, + opt_psm, opt_mtu, connect_cb, &gerr); + if (iochannel == NULL) { + set_state(STATE_DISCONNECTED); + error("%s\n", gerr->message); + g_error_free(gerr); + } else + g_io_add_watch(iochannel, G_IO_HUP, channel_watcher, NULL); +} + +static void cmd_disconnect(int argcp, char **argvp) +{ + disconnect_io(); +} + +// Discover Services +static void discover_services_cb(guint8 status, GSList *ranges, gpointer user_data) +{ + GSList *l; + + if (status) { + error("Discover primary services by UUID failed: %s\n", + att_ecode2str(status)); + return; + } + + if (ranges == NULL) { + error("No service UUID found\n"); + return; + } + + for (l = ranges; l; l = l->next) { + struct att_range *range = l->data; + rl_printf("Starting handle: 0x%04x Ending handle: 0x%04x\n", + range->start, range->end); + } + gatt_discover_char(attrib, 0x1, 0xffff, NULL, discover_char_cb, NULL); +} + + +static void discover_services(void) +{ + if (conn_state != STATE_CONNECTED) { + failed("Disconnected\n"); + return; + } + + bt_uuid_t uuid; + if (bt_string_to_uuid(&uuid, ANKI_STR_SERVICE_UUID) < 0) { + error("Error attempting to discover service for UUID: %s\n", ANKI_STR_SERVICE_UUID); + return; + } + + gatt_discover_primary(attrib, &uuid, discover_services_cb, NULL); +} + +static int strtohandle(const char *src) +{ + char *e; + int dst; + + errno = 0; + dst = strtoll(src, &e, 16); + if (errno != 0 || *e != '\0') + return -EINVAL; + + return dst; +} + +static void cmd_anki_vehicle_read(int argcp, char **argvp) +{ + if (conn_state != STATE_CONNECTED) { + failed("Disconnected\n"); + return; + } + + if (argcp < 1) { + error("Missing argument: handle\n"); + return; + } + + int handle = vehicle.read_char.value_handle; + if (handle < 0) { + error("Invalid handle: %s\n", argvp[1]); + return; + } + + gatt_read_char(attrib, handle, char_read_cb, attrib); +} + +static void char_write_req_cb(guint8 status, const guint8 *pdu, guint16 plen, + gpointer user_data) +{ + if (status != 0) { + error("Characteristic Write Request failed: " + "%s\n", att_ecode2str(status)); + return; + } + + if (!dec_write_resp(pdu, plen) && !dec_exec_write_resp(pdu, plen)) { + error("Protocol error\n"); + return; + } + + rl_printf("Characteristic value was written successfully\n"); +} + +static void cmd_anki_vehicle_write(int argcp, char **argvp) +{ + uint8_t *value; + size_t plen; + int handle; + + if (conn_state != STATE_CONNECTED) { + failed("Disconnected\n"); + return; + } + + if (argcp < 2) { + rl_printf("Usage: %s \n", argvp[0]); + return; + } + + handle = vehicle.write_char.value_handle; + + plen = gatt_attr_data_from_string(argvp[1], &value); + if (plen == 0) { + error("Invalid value\n"); + return; + } + + if (g_strcmp0("send-data-req", argvp[0]) == 0) + gatt_write_char(attrib, handle, value, plen, + char_write_req_cb, NULL); + else + gatt_write_cmd(attrib, handle, value, plen, NULL, NULL); + + g_free(value); +} + +static void cmd_anki_vehicle_disconnect(int argcp, char **argvp) +{ + uint8_t *value; + size_t plen; + int handle; + + if (conn_state != STATE_CONNECTED) { + failed("Disconnected\n"); + return; + } + + if (argcp < 1) { + rl_printf("Usage: %s\n", argvp[0]); + return; + } + + handle = vehicle.write_char.value_handle; + + anki_vehicle_msg_t msg; + plen = anki_vehicle_msg_disconnect(&msg); + value = (uint8_t *)&msg; + + gatt_write_char(attrib, handle, value, plen, + NULL, NULL); +} + +static void cmd_anki_vehicle_sdk_mode(int argcp, char **argvp) +{ + uint8_t *value; + size_t plen; + int handle; + + if (conn_state != STATE_CONNECTED) { + failed("Disconnected\n"); + return; + } + + if (argcp < 2) { + rl_printf("Usage: %s \n", argvp[0]); + return; + } + + handle = vehicle.write_char.value_handle; + + int arg = atoi(argvp[1]); + + anki_vehicle_msg_t msg; + plen = anki_vehicle_msg_set_sdk_mode(&msg, arg, ANKI_VEHICLE_SDK_OPTION_OVERRIDE_LOCALIZATION); + value = (uint8_t *)&msg; + + gatt_write_char(attrib, handle, value, plen, + NULL, NULL); +} + +static void cmd_anki_vehicle_ping(int argcp, char **argvp) +{ + uint8_t *value; + size_t plen; + int handle; + + if (conn_state != STATE_CONNECTED) { + failed("Disconnected\n"); + return; + } + + if (argcp < 1) { + rl_printf("Usage: %s\n", argvp[0]); + return; + } + + handle = vehicle.write_char.value_handle; + + anki_vehicle_msg_t msg; + plen = anki_vehicle_msg_ping(&msg); + value = (uint8_t *)&msg; + + gatt_write_char(attrib, handle, value, plen, NULL, NULL); +} + +static void cmd_anki_vehicle_get_version(int argcp, char **argvp) +{ + uint8_t *value; + size_t plen; + int handle; + + if (conn_state != STATE_CONNECTED) { + failed("Disconnected\n"); + return; + } + + if (argcp < 1) { + rl_printf("Usage: %s\n", argvp[0]); + return; + } + + handle = vehicle.write_char.value_handle; + + anki_vehicle_msg_t msg; + plen = anki_vehicle_msg_get_version(&msg); + value = (uint8_t *)&msg; + + gatt_write_char(attrib, handle, value, plen, NULL, NULL); +} + +static void cmd_anki_vehicle_set_speed(int argcp, char **argvp) +{ + uint8_t *value; + size_t plen; + int handle; + + if (conn_state != STATE_CONNECTED) { + failed("Disconnected\n"); + return; + } + + if (argcp < 2) { + rl_printf("Usage: %s \n", argvp[0]); + return; + } + + handle = vehicle.write_char.value_handle; + + int16_t speed = (int16_t)atoi(argvp[1]); + int16_t accel = 25000; + if (argcp > 2) { + accel = atoi(argvp[2]); + } + rl_printf("setting speed to %d (accel = %d)\n", speed, accel); + + anki_vehicle_msg_t msg; + plen = anki_vehicle_msg_set_speed(&msg, speed, accel); + value = (uint8_t *)&msg; + + gatt_write_char(attrib, handle, value, plen, + NULL, NULL); +} + +static void cmd_anki_vehicle_change_lane(int argcp, char **argvp) +{ + if (conn_state != STATE_CONNECTED) { + failed("Disconnected\n"); + return; + } + + if (argcp < 3) { + rl_printf("Usage: %s \n", argvp[0]); + return; + } + + int handle = vehicle.write_char.value_handle; + + int16_t hspeed = (int16_t)atoi(argvp[1]); + int16_t haccel = (int16_t)atoi(argvp[2]); + float offset = 1.0; + if (argcp > 3) { + offset = strtof(argvp[3], NULL); + } + rl_printf("changing lane at %d (accel = %d | offset = %1.2f)\n", hspeed, haccel, offset); + + anki_vehicle_msg_t msg; + size_t plen = anki_vehicle_msg_set_offset_from_road_center(&msg, 0.0); + gatt_write_char(attrib, handle, (uint8_t*)&msg, plen, NULL, NULL); + + anki_vehicle_msg_t lane_msg; + size_t lane_plen = anki_vehicle_msg_change_lane(&lane_msg, hspeed, haccel, offset); + gatt_write_char(attrib, handle, (uint8_t*)&lane_msg, lane_plen, NULL, NULL); +} + +anki_vehicle_light_channel_t get_channel_by_name(const char *name) +{ + uint8_t i; + uint8_t channel = channel_invalid; + + if (name == NULL) + return channel; + + uint8_t count = sizeof(channels_by_name)/sizeof(channels_by_name[0]); + for (i = 0; i < count; i++) { + uint8_t len = MAX(strlen(name), strlen(channels_by_name[i])); + if (strncmp(name, channels_by_name[i], len) == 0) { + channel = i; + break; + } + } + + return channel; +} + +anki_vehicle_light_effect_t get_effect_by_name(const char *name) +{ + uint8_t i; + uint8_t effect = channel_invalid; + + if (name == NULL) + return effect; + + uint8_t count = sizeof(effects_by_name)/sizeof(effects_by_name[0]); + for (i = 0; i < count; i++) { + if (strncmp(name, effects_by_name[i], sizeof(effects_by_name[i])) == 0) { + effect = i; + break; + } + } + + return effect; +} + +static void cmd_anki_vehicle_lights_pattern(int argcp, char **argvp) +{ + uint8_t *value; + size_t plen; + int handle; + + if (conn_state != STATE_CONNECTED) { + failed("Disconnected\n"); + return; + } + + if (argcp < 6) { + rl_printf("Usage: %s \n", argvp[0]); + rl_printf(" channels: RED, TAIL, BLUE, GREEN, FRONTL, FRONTR\n"); + rl_printf(" effects: STEADY, FADE, THROB, FLASH, RANDOM\n"); + return; + } + + handle = vehicle.write_char.value_handle; + + uint8_t channel = get_channel_by_name(argvp[1]); + if (channel == channel_invalid) { + rl_printf("Unrecognized channel: %s\n", argvp[1]); + return; + } + + uint8_t effect = get_effect_by_name(argvp[2]); + if (effect == effect_invalid) { + rl_printf("Unrecognized channel: %s\n", argvp[2]); + return; + } + + uint8_t start = atoi(argvp[3]); + uint8_t end = atoi(argvp[4]); + uint16_t cycles_per_min = atoi(argvp[5]); + + anki_vehicle_msg_t msg; + plen = anki_vehicle_msg_lights_pattern(&msg, channel, effect, start, end, cycles_per_min); + value = (uint8_t *)&msg; + + gatt_write_char(attrib, handle, value, plen, NULL, NULL); +} + +static void vehicle_set_rgb_lights(int handle, uint8_t effect, uint8_t start_red, uint8_t end_red, uint8_t start_green, uint8_t end_green, uint8_t start_blue, uint8_t end_blue, uint16_t cycles_per_min) +{ + anki_vehicle_msg_lights_pattern_t msg; + + anki_vehicle_light_config_t red_config; + anki_vehicle_light_config(&red_config, LIGHT_RED, effect, start_red, end_red, cycles_per_min); + anki_vehicle_msg_lights_pattern_append(&msg, &red_config); + + anki_vehicle_light_config_t green_config; + anki_vehicle_light_config(&green_config, LIGHT_GREEN, effect, start_green, end_green, cycles_per_min); + anki_vehicle_msg_lights_pattern_append(&msg, &green_config); + + anki_vehicle_light_config_t blue_config; + anki_vehicle_light_config(&blue_config, LIGHT_BLUE, effect, start_blue, end_blue, cycles_per_min); + anki_vehicle_msg_lights_pattern_append(&msg, &blue_config); + + uint8_t *value = (uint8_t *)&msg; + size_t plen = sizeof(msg); + + gatt_write_char(attrib, handle, value, plen, NULL, NULL); +} + +static void cmd_anki_vehicle_engine_lights(int argcp, char **argvp) +{ + + if (conn_state != STATE_CONNECTED) { + failed("Disconnected\n"); + return; + } + + if (argcp < 5) { + rl_printf("Usage: %s \n", argvp[0]); + rl_printf(" effects: STEADY, FADE, THROB, FLASH, RANDOM\n"); + return; + } + + float red = strtof(argvp[1], NULL); + uint8_t r = (uint8_t)(ANKI_VEHICLE_MAX_LIGHT_INTENSITY * red); + + float green = strtof(argvp[2], NULL); + uint8_t g = (uint8_t)(ANKI_VEHICLE_MAX_LIGHT_INTENSITY * green); + + float blue = strtof(argvp[3], NULL); + uint8_t b = (uint8_t)(ANKI_VEHICLE_MAX_LIGHT_INTENSITY * blue); + + uint8_t effect = get_effect_by_name(argvp[4]); + uint16_t cycles_per_min = atoi(argvp[5]); + + int handle = vehicle.write_char.value_handle; + rl_printf("%s: %u %u %u @ %u cycles/min\n", argvp[4], r, g, b, cycles_per_min); + + switch(effect) { + case EFFECT_RANDOM: + case EFFECT_STEADY: + vehicle_set_rgb_lights(handle, effect, r, r, g, g, b, b, 0); + break; + case EFFECT_FLASH: + case EFFECT_THROB: + vehicle_set_rgb_lights(handle, effect, 0, r, 0, g, 0, b, cycles_per_min); + break; + case EFFECT_FADE: + vehicle_set_rgb_lights(handle, effect, r, 0, g, 0, b, 0, cycles_per_min); + break; + } +} + +anki_vehicle_turn_type_t get_turn_type_by_name(const char *name) +{ + uint8_t i; + anki_vehicle_turn_type_t turn_type = VEHICLE_TURN_NONE; + + if (name == NULL) + return turn_type; + + uint8_t count = sizeof(turn_types_by_name)/sizeof(turn_types_by_name[0]); + for (i = 0; i < count; i++) { + if (strncmp(name, turn_types_by_name[i], sizeof(turn_types_by_name[i])) == 0) { + turn_type = (anki_vehicle_turn_type_t)i; + break; + } + } + + return turn_type; +} + +static void vehicle_turn(int handle, anki_vehicle_turn_type_t turn_type) +{ + anki_vehicle_msg_t msg; + size_t plen = anki_vehicle_msg_turn(&msg, turn_type, VEHICLE_TURN_TRIGGER_IMMEDIATE); + + uint8_t *value = (uint8_t *)&msg; + + gatt_write_char(attrib, handle, value, plen, NULL, NULL); +} + +static void cmd_anki_vehicle_turn(int argcp, char **argvp) +{ + if (conn_state != STATE_CONNECTED) { + failed("Disconnected\n"); + return; + } + + if (argcp < 2) { + rl_printf("Usage: %s \n", argvp[0]); + rl_printf(" turn type: UTURN, LEFT, RIGHT\n"); + return; + } + + + anki_vehicle_turn_type_t turn_type = get_turn_type_by_name(argvp[1]); + rl_printf("%s: %s (%u)\n", argvp[0], argvp[1], turn_type); + + int handle = vehicle.write_char.value_handle; + vehicle_turn(handle, turn_type); +} + +static void exchange_mtu_cb(guint8 status, const guint8 *pdu, guint16 plen, + gpointer user_data) +{ + uint16_t mtu; + + if (status != 0) { + error("Exchange MTU Request failed: %s\n", + att_ecode2str(status)); + return; + } + + if (!dec_mtu_resp(pdu, plen, &mtu)) { + error("Protocol error\n"); + return; + } + + mtu = MIN(mtu, opt_mtu); + /* Set new value for MTU in client */ + if (g_attrib_set_mtu(attrib, mtu)) + rl_printf("MTU was exchanged successfully: %d\n", mtu); + else + error("Error exchanging MTU\n"); +} + +static void cmd_mtu(int argcp, char **argvp) +{ + if (conn_state != STATE_CONNECTED) { + failed("Disconnected\n"); + return; + } + + if (opt_psm) { + failed("Operation is only available for LE transport.\n"); + return; + } + + if (argcp < 2) { + rl_printf("Usage: mtu \n"); + return; + } + + if (opt_mtu) { + failed("MTU exchange can only occur once per connection.\n"); + return; + } + + errno = 0; + opt_mtu = strtoll(argvp[1], NULL, 0); + if (errno != 0 || opt_mtu < ATT_DEFAULT_LE_MTU) { + error("Invalid value. Minimum MTU size is %d\n", + ATT_DEFAULT_LE_MTU); + return; + } + + gatt_exchange_mtu(attrib, opt_mtu, exchange_mtu_cb, NULL); +} + +static struct { + const char *cmd; + void (*func)(int argcp, char **argvp); + const char *params; + const char *desc; +} commands[] = { + { "help", cmd_help, "", + "Show this help"}, + { "exit", cmd_exit, "", + "Exit interactive mode" }, + { "quit", cmd_exit, "", + "Exit interactive mode" }, + { "connect", cmd_connect, "[address [address type]]", + "Connect to a remote device" }, + { "disconnect", cmd_disconnect, "", + "Disconnect from a remote device" }, + { "mtu", cmd_mtu, "", + "Exchange MTU for GATT/ATT" }, + { "sdk-mode", cmd_anki_vehicle_sdk_mode, "[on]", + "Set SDK Mode"}, + { "ping", cmd_anki_vehicle_ping, "", + "Send ping message to vehicle."}, + { "get-version", cmd_anki_vehicle_get_version, "", + "Request vehicle software version."}, + { "set-speed", cmd_anki_vehicle_set_speed, " ", + "Set vehicle Speed (mm/sec) with acceleration (mm/sec^2)"}, + { "change-lane", cmd_anki_vehicle_change_lane, " (right(+), left(-))", + "Change lanes at speed (mm/sec), accel (mm/sec^2) in the specified direction (offset)"}, + { "set-lights-pattern", cmd_anki_vehicle_lights_pattern, " ", + "Set lights pattern for vehicle LEDs."}, + { "set-engine-lights", cmd_anki_vehicle_engine_lights, " ", + "Set the pattern for the engine lights."}, + { "turn", cmd_anki_vehicle_turn, "", + "Execute a turn of type UTURN, LEFT, RIGHT"}, + { "vehicle-disconnect", cmd_anki_vehicle_disconnect, "", + "Request that the vehicle disconnect (often more reliable than disconnect)"}, + { "send-data-req", cmd_anki_vehicle_write, "", + "Write data to vehicle (Request response)" }, + { "send-data", cmd_anki_vehicle_write, "", + "Write data to vehicle (No response)" }, + { "read-data", cmd_anki_vehicle_read, "", + "Read last message from vehicle" }, + { NULL, NULL, NULL} +}; + +static void cmd_help(int argcp, char **argvp) +{ + int i; + + for (i = 0; commands[i].cmd; i++) + rl_printf("%-15s %-30s %s\n", commands[i].cmd, + commands[i].params, commands[i].desc); +} + +static void parse_line(char *line_read) +{ + char **argvp; + int argcp; + int i; + + if (line_read == NULL) { + rl_printf("\n"); + cmd_exit(0, NULL); + return; + } + + line_read = g_strstrip(line_read); + + if (*line_read == '\0') + goto done; + + add_history(line_read); + + if (g_shell_parse_argv(line_read, &argcp, &argvp, NULL) == FALSE) + goto done; + + for (i = 0; commands[i].cmd; i++) + if (strcasecmp(commands[i].cmd, argvp[0]) == 0) + break; + + if (commands[i].cmd) + commands[i].func(argcp, argvp); + else + error("%s: command not found\n", argvp[0]); + + g_strfreev(argvp); + +done: + free(line_read); +} + +static gboolean prompt_read(GIOChannel *chan, GIOCondition cond, + gpointer user_data) +{ + if (cond & (G_IO_HUP | G_IO_ERR | G_IO_NVAL)) { + g_io_channel_unref(chan); + return FALSE; + } + + rl_callback_read_char(); + + return TRUE; +} + +static char *completion_generator(const char *text, int state) +{ + static int index = 0, len = 0; + const char *cmd = NULL; + + if (state == 0) { + index = 0; + len = strlen(text); + } + + while ((cmd = commands[index].cmd) != NULL) { + index++; + if (strncmp(cmd, text, len) == 0) + return strdup(cmd); + } + + return NULL; +} + +static char **commands_completion(const char *text, int start, int end) +{ + if (start == 0) + return rl_completion_matches(text, &completion_generator); + else + return NULL; +} + +static guint setup_standard_input(void) +{ + GIOChannel *channel; + guint source; + + channel = g_io_channel_unix_new(fileno(stdin)); + + source = g_io_add_watch(channel, + G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_NVAL, + prompt_read, NULL); + + g_io_channel_unref(channel); + + return source; +} + +static gboolean signal_handler(GIOChannel *channel, GIOCondition condition, + gpointer user_data) +{ + static unsigned int __terminated = 0; + struct signalfd_siginfo si; + ssize_t result; + int fd; + + if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) { + g_main_loop_quit(event_loop); + return FALSE; + } + + fd = g_io_channel_unix_get_fd(channel); + + result = read(fd, &si, sizeof(si)); + if (result != sizeof(si)) + return FALSE; + + switch (si.ssi_signo) { + case SIGINT: + rl_replace_line("", 0); + rl_crlf(); + rl_on_new_line(); + rl_redisplay(); + break; + case SIGTERM: + if (__terminated == 0) { + rl_replace_line("", 0); + rl_crlf(); + g_main_loop_quit(event_loop); + } + + __terminated = 1; + break; + } + + return TRUE; +} + +static guint setup_signalfd(void) +{ + GIOChannel *channel; + guint source; + sigset_t mask; + int fd; + + sigemptyset(&mask); + sigaddset(&mask, SIGINT); + sigaddset(&mask, SIGTERM); + + if (sigprocmask(SIG_BLOCK, &mask, NULL) < 0) { + perror("Failed to set signal mask"); + return 0; + } + + fd = signalfd(-1, &mask, 0); + if (fd < 0) { + perror("Failed to create signal descriptor"); + return 0; + } + + channel = g_io_channel_unix_new(fd); + + g_io_channel_set_close_on_unref(channel, TRUE); + g_io_channel_set_encoding(channel, NULL, NULL); + g_io_channel_set_buffered(channel, FALSE); + + source = g_io_add_watch(channel, + G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_NVAL, + signal_handler, NULL); + + g_io_channel_unref(channel); + + return source; +} + +int interactive(const char *src, const char *dst, + const char *dst_type, int psm) +{ + guint input; + guint signal; + + opt_sec_level = g_strdup("low"); + + opt_src = g_strdup(src); + opt_dst = g_strdup(dst); + opt_dst_type = g_strdup(dst_type); + opt_psm = psm; + + prompt = g_string_new(NULL); + + event_loop = g_main_loop_new(NULL, FALSE); + + input = setup_standard_input(); + signal = setup_signalfd(); + + rl_attempted_completion_function = commands_completion; + rl_erase_empty_line = 1; + rl_callback_handler_install(get_prompt(), parse_line); + + g_main_loop_run(event_loop); + + rl_callback_handler_remove(); + cmd_disconnect(0, NULL); + g_source_remove(input); + g_source_remove(signal); + g_main_loop_unref(event_loop); + g_string_free(prompt, TRUE); + + g_free(opt_src); + g_free(opt_dst); + g_free(opt_sec_level); + + return 0; +} diff --git a/drive-sdk/examples/vehicle-tool/vehicle_tool.c b/drive-sdk/examples/vehicle-tool/vehicle_tool.c new file mode 100644 index 0000000..c5ff73e --- /dev/null +++ b/drive-sdk/examples/vehicle-tool/vehicle_tool.c @@ -0,0 +1,172 @@ +/* + * vehicle-tool + * + * Example vehicle control tool for Anki Drive SDK + * + * Copyright (C) 2014 Anki, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + * Portions of this software are derived from BlueZ, a Bluetooth protocol stack for + * Linux. The license for BlueZ is included below. + */ + +/* + * + * BlueZ - Bluetooth protocol stack for Linux + * + * Copyright (C) 2010 Nokia Corporation + * Copyright (C) 2010 Marcel Holtmann + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +static char *opt_src = NULL; +static char *opt_dst = NULL; +static char *opt_dst_type = NULL; +static char *opt_value = NULL; +static char *opt_sec_level = NULL; +static bt_uuid_t *opt_uuid = NULL; +static int opt_handle = -1; +static int opt_mtu = 0; +static int opt_psm = 0; +static GMainLoop *event_loop; +static gboolean got_error = FALSE; +static GSourceFunc operation; + +struct characteristic_data { + GAttrib *attrib; + uint16_t start; + uint16_t end; +}; + +static void events_handler(const uint8_t *pdu, uint16_t len, gpointer user_data) +{ + GAttrib *attrib = user_data; + uint8_t *opdu; + uint16_t handle, i, olen = 0; + size_t plen; + + handle = att_get_u16(&pdu[1]); + + switch (pdu[0]) { + case ATT_OP_HANDLE_NOTIFY: + g_print("Notification handle = 0x%04x value: ", handle); + break; + case ATT_OP_HANDLE_IND: + g_print("Indication handle = 0x%04x value: ", handle); + break; + default: + g_print("Invalid opcode\n"); + return; + } + + for (i = 3; i < len; i++) + g_print("%02x ", pdu[i]); + + g_print("\n"); + + if (pdu[0] == ATT_OP_HANDLE_NOTIFY) + return; + + opdu = g_attrib_get_buffer(attrib, &plen); + olen = enc_confirmation(opdu, plen); + + if (olen > 0) + g_attrib_send(attrib, 0, opdu, olen, NULL, NULL, NULL); +} + +static GOptionEntry options[] = { + { "adapter", 'i', 0, G_OPTION_ARG_STRING, &opt_src, + "Specify local adapter interface", "hciX" }, + { "device", 'b', 0, G_OPTION_ARG_STRING, &opt_dst, + "Specify remote Bluetooth address", "MAC" }, + { "addr-type", 't', 0, G_OPTION_ARG_STRING, &opt_dst_type, + "Set LE address type. Default: random", "[public | random]"}, + { "mtu", 'm', 0, G_OPTION_ARG_INT, &opt_mtu, + "Specify the MTU size", "MTU" }, + { "psm", 'p', 0, G_OPTION_ARG_INT, &opt_psm, + "Specify the PSM for GATT/ATT over BR/EDR", "PSM" }, + { "sec-level", 'l', 0, G_OPTION_ARG_STRING, &opt_sec_level, + "Set security level. Default: low", "[low | medium | high]"}, + { NULL }, +}; + +int main(int argc, char *argv[]) +{ + GOptionContext *context; + GOptionGroup *gatt_group, *params_group, *char_rw_group; + GError *gerr = NULL; + GIOChannel *chan; + + opt_dst_type = g_strdup("random"); + opt_sec_level = g_strdup("low"); + + context = g_option_context_new(NULL); + g_option_context_add_main_entries(context, options, NULL); + + if (!g_option_context_parse(context, &argc, &argv, &gerr)) { + g_printerr("%s\n", gerr->message); + g_clear_error(&gerr); + } + + interactive(opt_src, opt_dst, opt_dst_type, opt_psm); + +done: + g_option_context_free(context); + g_free(opt_src); + g_free(opt_dst); + g_free(opt_uuid); + g_free(opt_sec_level); + + if (got_error) + exit(EXIT_FAILURE); + else + exit(EXIT_SUCCESS); +} diff --git a/drive-sdk/include/ankidrive.h b/drive-sdk/include/ankidrive.h new file mode 100644 index 0000000..9cda11f --- /dev/null +++ b/drive-sdk/include/ankidrive.h @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2014 Anki, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_ankidrive_ankidrive_h +#define INCLUDE_ankidrive_ankidrive_h + +#include "ankidrive/version.h" +#include "ankidrive/uuid.h" +#include "ankidrive/advertisement.h" +#include "ankidrive/protocol.h" +#include "ankidrive/vehicle_gatt_profile.h" + +#endif diff --git a/drive-sdk/include/ankidrive/advertisement.h b/drive-sdk/include/ankidrive/advertisement.h new file mode 100644 index 0000000..9b192e2 --- /dev/null +++ b/drive-sdk/include/ankidrive/advertisement.h @@ -0,0 +1,145 @@ +/* + * Copyright (c) 2014 Anki, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_advertisement_h +#define INCLUDE_advertisement_h + +#include +#include "common.h" +#include "uuid.h" + +ANKI_BEGIN_DECL + +/** + * The state of a vehicle recorded in the advertising packet. + * + * - full_battery: The vehicle battery is fully charged + * - low_battery: The vehicle battery has a low charge and will die soon + * - on_charger: The vehicle is currently on the charger + */ +typedef struct anki_vehicle_adv_state { + uint8_t _reserved:4; + uint8_t full_battery:1; // 4: TRUE if Car has full battery + uint8_t low_battery:1; // 5: TRUE if Car has low battery + uint8_t on_charger:1; // 6: TRUE if Car is on Charger + uint8_t _unavailable:1; // 7: Cannot be used due to BTLE character set constraint +} anki_vehicle_adv_state_t; + +/** + * Vehicle information packed in the LOCAL_NAME string record + * of an advertising packet. + * + * - state: Current vehicle state. + * NOTE: Changes to the vehicle state will cause the LOCAL_NAME value + * to change. + * - version: Firmware version running on the vehicle + * - name: User-defined name in UTF-8 encoding + */ +typedef struct anki_vehicle_adv_info { + anki_vehicle_adv_state_t state; + uint16_t version; + uint8_t _reserved[5]; + unsigned char name[13]; // UTF8: 12 bytes + NULL. +} anki_vehicle_adv_info_t; + + +/** + * Vehicle hardware information encodeded in the MANUFACTURER_DATA + * record of an advertising packet. + * + * - identifier: Unique identifer for a physical vehicle + * - model_id: The model type of a vehicle + * - product_id: Value identifying the vehicle as Anki Drive hardware + */ +typedef struct anki_vehicle_adv_mfg { + uint32_t identifier; + uint8_t model_id; + uint8_t _reserved; + uint16_t product_id; +} anki_vehicle_adv_mfg_t; + + +/** + * Vehicle information present in Bluetooth LE advertising packets. + * + * flags: EIR / AD flags + * tx_power: transmission power + * mfg_data: parsed data from the MANUFACTURER_DATA bytes + * local_name: parsed data from the LOCAL_NAME string bytes + * service_id: Anki Vehicle UUID (128-bit) + */ +typedef struct anki_vehicle_adv { + uint8_t flags; + uint8_t tx_power; + anki_vehicle_adv_mfg_t mfg_data; + anki_vehicle_adv_info_t local_name; + uuid128_t service_id; +} anki_vehicle_adv_t; + +/** + * Test whether the scan record contains an Anki Drive vehicle service UUID. + * + * @param scan_data Bytes obtained by scanning vehicle advertising packets. + * @param scan_data_len Length of bytes in scan_data. + * + * @return 0 on failure, 1 on success. + */ +uint8_t anki_vehicle_adv_record_has_anki_uuid(const uint8_t *scan_data, const size_t scan_data_len); + + +/** + * Parse advertising data for an Anki Drive vehicle. + * + * @param scan_data Bytes obtained by scanning vehicle advertising packets. + * @param scan_data_len Length of bytes in scan_data. + * @param anki_vehicle_adv Pointer to a structure for storing accumulated information for a vehicle. + * Parsed scan data will overwrite matching record data in the struct. + * + * @return 0 on success, 1 on failure, + * 2 if the data is not anki drive + * 3 if unknown EIR data is encountered + * + * @discuss Pass NULL for anki_vehicle_adv in order to determine if this is an appropriate record. + * + * + */ +uint8_t anki_vehicle_parse_adv_record(const uint8_t *scan_data, const size_t scan_data_len, anki_vehicle_adv_t *anki_vehicle_adv); + +/** + * Parse MANUFACTERER_DATA record from a vehicle advertising packet. + * + * @param scan_data Bytes obtained by scanning vehicle advertising packets. + * @param scan_data_len Length of bytes in scan_data. + * @param mfg_data Pointer to a structure for storing parsed data. + * + * @return 0 on success, 1 on failure. + */ +uint8_t anki_vehicle_parse_mfg_data(const uint8_t *bytes, uint8_t len, anki_vehicle_adv_mfg_t *mfg_data); + +/** + * Parse LOCAL_NAME record from a vehicle advertising packet. + * + * @param scan_data Bytes obtained by scanning vehicle advertising packets. + * @param scan_data_len Length of bytes in scan_data. + * @param local_name Pointer to a structure for storing parsed data. + * + * @return 0 on success, 1 on failure. + */ +uint8_t anki_vehicle_parse_local_name(const uint8_t *bytes, uint8_t len, anki_vehicle_adv_info_t *local_name); + +ANKI_END_DECL + +#endif diff --git a/drive-sdk/include/ankidrive/common.h b/drive-sdk/include/ankidrive/common.h new file mode 100644 index 0000000..d946ceb --- /dev/null +++ b/drive-sdk/include/ankidrive/common.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2014 Anki, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_common_h +#define INCLUDE_common_h + +#ifdef __cplusplus +# define ANKI_BEGIN_DECL extern "C" { +# define ANKI_END_DECL } +#else + /** Start declarations in C mode */ +# define ANKI_BEGIN_DECL /* empty */ + /** End declarations in C mode */ +# define ANKI_END_DECL /* empty */ +#endif + +/** Declare a public function */ +#if __GNUC__ >= 4 +# define ANKI_EXTERN(type) extern \ + __attribute__((visibility("default"))) \ + type +#elif defined(_MSC_VER) +# define ANKI_EXTERN(type) __declspec(dllexport) type +#else +# define ANKI_EXTERN(type) extern type +#endif + +/** Declare a function as always inlined. */ +#if defined(_MSC_VER) +# define ANKI_INLINE(type) static __inline type +#else +# define ANKI_INLINE(type) static inline type +#endif + +#endif diff --git a/drive-sdk/include/ankidrive/protocol.h b/drive-sdk/include/ankidrive/protocol.h new file mode 100644 index 0000000..259960a --- /dev/null +++ b/drive-sdk/include/ankidrive/protocol.h @@ -0,0 +1,559 @@ +/* + * Copyright (c) 2014 Anki, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_protocol_h +#define INCLUDE_protocol_h + +#include + +#include "common.h" + +ANKI_BEGIN_DECL + +#define ANKI_VEHICLE_MSG_MAX_SIZE 20 +#define ANKI_VEHICLE_MSG_PAYLOAD_MAX_SIZE 18 +#define ANKI_VEHICLE_MSG_BASE_SIZE 1 + +/** Identifier for a vehicle message */ +enum { + // BLE Connections + ANKI_VEHICLE_MSG_C2V_DISCONNECT = 0x0d, + + // Ping request / response + ANKI_VEHICLE_MSG_C2V_PING_REQUEST = 0x16, + ANKI_VEHICLE_MSG_V2C_PING_RESPONSE = 0x17, + + // Messages for checking vehicle version info + ANKI_VEHICLE_MSG_C2V_VERSION_REQUEST = 0x18, + ANKI_VEHICLE_MSG_V2C_VERSION_RESPONSE = 0x19, + + // Battery level + ANKI_VEHICLE_MSG_C2V_BATTERY_LEVEL_REQUEST = 0x1a, + ANKI_VEHICLE_MSG_V2C_BATTERY_LEVEL_RESPONSE = 0x1b, + + // Lights + ANKI_VEHICLE_MSG_C2V_SET_LIGHTS = 0x1d, + + // Driving Commands + ANKI_VEHICLE_MSG_C2V_SET_SPEED = 0x24, + ANKI_VEHICLE_MSG_C2V_CHANGE_LANE = 0x25, + ANKI_VEHICLE_MSG_C2V_CANCEL_LANE_CHANGE = 0x26, + ANKI_VEHICLE_MSG_C2V_TURN = 0x32, + + // Vehicle position updates + ANKI_VEHICLE_MSG_V2C_LOCALIZATION_POSITION_UPDATE = 0x27, + ANKI_VEHICLE_MSG_V2C_LOCALIZATION_TRANSITION_UPDATE = 0x29, + ANKI_VEHICLE_MSG_V2C_LOCALIZATION_INTERSECTION_UPDATE = 0x2a, + ANKI_VEHICLE_MSG_V2C_VEHICLE_DELOCALIZED = 0x2b, + ANKI_VEHICLE_MSG_C2V_SET_OFFSET_FROM_ROAD_CENTER = 0x2c, + ANKI_VEHICLE_MSG_V2C_OFFSET_FROM_ROAD_CENTER_UPDATE = 0x2d, + + // Light Patterns + ANKI_VEHICLE_MSG_C2V_LIGHTS_PATTERN = 0x33, + + // Vehicle Configuration Parameters + ANKI_VEHICLE_MSG_C2V_SET_CONFIG_PARAMS = 0x45, + + // SDK Mode + ANKI_VEHICLE_MSG_C2V_SDK_MODE = 0x90, +}; + +#define ATTRIBUTE_PACKED __attribute__((packed)) + +/** + * Basic vehicle message. + * + * - size: Size in bytes of the msg_id plus payload + * - msg_id: Identifier for message + * - payload: Optional message data for parameters or response info. + * + */ +typedef struct anki_vehicle_msg { + uint8_t size; + uint8_t msg_id; + uint8_t payload[ANKI_VEHICLE_MSG_PAYLOAD_MAX_SIZE]; +} anki_vehicle_msg_t; + +typedef struct anki_vehicle_msg_version_response { + uint8_t size; + uint8_t msg_id; + uint16_t version; +} ATTRIBUTE_PACKED anki_vehicle_msg_version_response_t; +#define ANKI_VEHICLE_MSG_V2C_VERSION_RESPONSE_SIZE 3 + +typedef struct anki_vehicle_msg_battery_level_response { + uint8_t size; + uint8_t msg_id; + uint16_t battery_level; +} ATTRIBUTE_PACKED anki_vehicle_msg_battery_level_response_t; +#define ANKI_VEHICLE_MSG_V2C_BATTERY_LEVEL_RESPONSE_SIZE 3 + +#define ANKI_VEHICLE_SDK_OPTION_OVERRIDE_LOCALIZATION 0x1 +typedef struct anki_vehicle_msg_sdk_mode { + uint8_t size; + uint8_t msg_id; + uint8_t on; + uint8_t flags; +} ATTRIBUTE_PACKED anki_vehicle_msg_sdk_mode_t; +#define ANKI_VEHICLE_MSG_SDK_MODE_SIZE 3 + +typedef struct anki_vehicle_msg_set_speed { + uint8_t size; + uint8_t msg_id; + int16_t speed_mm_per_sec; // mm/sec + int16_t accel_mm_per_sec2; // mm/sec^2 + uint8_t respect_road_piece_speed_limit; +} ATTRIBUTE_PACKED anki_vehicle_msg_set_speed_t; +#define ANKI_VEHICLE_MSG_C2V_SET_SPEED_SIZE 6 + +typedef enum { + VEHICLE_TURN_NONE = 0, + VEHICLE_TURN_LEFT = 1, + VEHICLE_TURN_RIGHT = 2, + VEHICLE_TURN_UTURN = 3, + VEHICLE_TURN_UTURN_JUMP = 4, +} anki_vehicle_turn_type_t; + +typedef enum { + VEHICLE_TURN_TRIGGER_IMMEDIATE = 0, // Run immediately + VEHICLE_TURN_TRIGGER_INTERSECTION = 1, // Run at the next intersection +} anki_vehicle_turn_trigger_t; + +typedef struct anki_vehicle_msg_turn { + uint8_t size; + uint8_t msg_id; + uint8_t type; + uint8_t trigger; +} ATTRIBUTE_PACKED anki_vehicle_msg_turn_t; +#define ANKI_VEHICLE_MSG_C2V_TURN_SIZE 3 + +typedef struct anki_vehicle_msg_set_offset_from_road_center { + uint8_t size; + uint8_t msg_id; + float offset_mm; +} ATTRIBUTE_PACKED anki_vehicle_msg_set_offset_from_road_center_t; +#define ANKI_VEHICLE_MSG_C2V_SET_OFFSET_FROM_ROAD_CENTER_SIZE 5 + +typedef struct anki_vehicle_msg_change_lane { + uint8_t size; + uint8_t msg_id; + uint16_t horizontal_speed_mm_per_sec; + uint16_t horizontal_accel_mm_per_sec2; + float offset_from_road_center_mm; + uint8_t hop_intent; + uint8_t tag; +} ATTRIBUTE_PACKED anki_vehicle_msg_change_lane_t; +#define ANKI_VEHICLE_MSG_C2V_CHANGE_LANE_SIZE 11 + +// +// Bitwise masks applied to parsing_flags +// +// determine how many bits per code were read +#define PARSEFLAGS_MASK_NUM_BITS 0x0f + +// determine if the track has an inverted code scheme +#define PARSEFLAGS_MASK_INVERTED_COLOR 0x80 + +// determine if the the code has been reverse parsed +#define PARSEFLAGS_MASK_REVERSE_PARSING 0x40 + +// determine if the current driving dir is reversed +#define PARSEFLAGS_MASK_REVERSE_DRIVING 0x20 + +typedef struct anki_vehicle_msg_localization_position_update { + uint8_t size; + uint8_t msg_id; + uint8_t location_id; + uint8_t road_piece_id; + float offset_from_road_center_mm; + uint16_t speed_mm_per_sec; + uint8_t parsing_flags; + + /* ACK commands received */ + uint8_t last_recv_lane_change_cmd_id; + uint8_t last_exec_lane_change_cmd_id; + uint16_t last_desired_horizontal_speed_mm_per_sec; + uint16_t last_desired_speed_mm_per_sec; +} ATTRIBUTE_PACKED anki_vehicle_msg_localization_position_update_t; +#define ANKI_VEHICLE_MSG_V2C_LOCALIZATION_POSITION_UPDATE_SIZE 16 + +typedef enum anki_vehicle_driving_direction { + FORWARD = 0, + REVERSE = 1, +} anki_vehicle_driving_direction_t; + +typedef struct anki_vehicle_msg_localization_transition_update { + uint8_t size; + uint8_t msg_id; + uint8_t road_piece_idx; + uint8_t road_piece_idx_prev; + float offset_from_road_center_mm; + + uint8_t driving_direction; + + /* ACK commands received */ + uint8_t last_recv_lane_change_id; + uint8_t last_exec_lane_change_id; + uint16_t last_desired_horizontal_speed_mm_per_sec; + uint16_t last_desired_speed_mm_per_sec; + + /* track grade detection */ + uint8_t uphill_counter; + uint8_t downhill_counter; + + /* wheel displacement (cm) since last transition bar */ + uint8_t left_wheel_dist_cm; + uint8_t right_wheel_dist_cm; +} ATTRIBUTE_PACKED anki_vehicle_msg_localization_transition_update_t; +#define ANKI_VEHICLE_MSG_V2C_LOCALIZATION_TRANSITION_UPDATE_SIZE 18 + +typedef enum { + INTERSECTION_CODE_ENTRY_FIRST, + INTERSECTION_CODE_EXIT_FIRST, + INTERSECTION_CODE_ENTRY_SECOND, + INTERSECTION_CODE_EXIT_SECOND, +} anki_intersection_code_t; + +typedef struct anki_vehicle_msg_localization_intersection_update { + uint8_t size; + uint8_t msg_id; + uint8_t road_piece_idx; + float offset_from_road_center_mm; + + uint8_t driving_direction; + uint8_t intersection_code; + uint8_t intersection_turn; + uint8_t is_exiting; +} ATTRIBUTE_PACKED anki_vehicle_msg_localization_intersection_update_t; +#define ANKI_VEHICLE_MSG_V2C_LOCALIZATION_INTERSECTION_UPDATE_SIZE 10 + +typedef struct anki_vehicle_msg_offset_from_road_center_update { + uint8_t size; + uint8_t msg_id; + float offset_from_road_center_mm; + uint8_t lane_change_id; +} ATTRIBUTE_PACKED anki_vehicle_msg_offset_from_road_center_update_t; +#define ANKI_VEHICLE_MSG_V2C_OFFSET_FROM_ROAD_CENTER_UPDATE_SIZE 6 + +// Lights +// The bits in the simple light message (ANKI_VEHICLE_MSG_C2V_SET_LIGHTS) corresponding to +// each type of light. +#define LIGHT_HEADLIGHTS 0 +#define LIGHT_BRAKELIGHTS 1 +#define LIGHT_FRONTLIGHTS 2 +#define LIGHT_ENGINE 3 + +// Helper macros for parsing lights bits +#define LIGHT_ANKI_VEHICLE_MSG_IS_VALID(messageBits, LIGHT_ID) (((messageBits >> LIGHT_ID) & 1) == TRUE) +#define LIGHT_ANKI_VEHICLE_MSG_GET_VALUE(messageBits, LIGHT_ID) ((messageBits >> (4 + LIGHT_ANKI_VEHICLE_MSG_HEADLIGHTS) & 1)) + +typedef struct anki_vehicle_msg_set_lights { + uint8_t size; + uint8_t msg_id; + uint8_t light_mask; // Valid and value bits for lights (see above) +} ATTRIBUTE_PACKED anki_vehicle_msg_set_lights_t; +#define ANKI_VEHICLE_MSG_C2V_SET_LIGHTS_SIZE 2 + +#define ANKI_VEHICLE_MAX_LIGHT_INTENSITY 14 +#define ANKI_VEHICLE_MAX_LIGHT_TIME 11 + +// LED channel definitions - for RGB engine, front, and tail lights +typedef enum { + LIGHT_RED, + LIGHT_TAIL, + LIGHT_BLUE, + LIGHT_GREEN, + LIGHT_FRONTL, + LIGHT_FRONTR, + LIGHT_COUNT +} anki_vehicle_light_channel_t; + +// Below is a description of the various effects used in SetLight(...) +typedef enum { + EFFECT_STEADY, // Simply set the light intensity to 'start' value + EFFECT_FADE, // Fade intensity from 'start' to 'end' + EFFECT_THROB, // Fade intensity from 'start' to 'end' and back to 'start' + EFFECT_FLASH, // Turn on LED between time 'start' and time 'end' inclusive + EFFECT_RANDOM, // Flash the LED erratically - ignoring start/end + EFFECT_COUNT +} anki_vehicle_light_effect_t; + +typedef struct anki_vehicle_light_config { + uint8_t channel; + uint8_t effect; + uint8_t start; + uint8_t end; + uint8_t cycles_per_10_sec; +} ATTRIBUTE_PACKED anki_vehicle_light_config_t; + +#define LIGHT_CHANNEL_COUNT_MAX 3 +typedef struct anki_vehicle_msg_lights_pattern { + uint8_t size; + uint8_t msg_id; + uint8_t channel_count; + anki_vehicle_light_config_t channel_config[LIGHT_CHANNEL_COUNT_MAX]; +} ATTRIBUTE_PACKED anki_vehicle_msg_lights_pattern_t; +#define ANKI_VEHICLE_MSG_C2V_LIGHTS_PATTERN_SIZE 17 + +typedef enum anki_track_material { + TRACK_MATERIAL_PLASTIC, + TRACK_MATERIAL_VINYL, +} anki_track_material_t; + +#define SUPERCODE_NONE 0 +#define SUPERCODE_BOOST_JUMP 1 +#define SUPERCODE_ALL (SUPERCODE_BOOST_JUMP) + +typedef struct anki_vehicle_msg_set_config_params { + uint8_t size; + uint8_t msg_id; + uint8_t super_code_parse_mask; + uint8_t track_material; +} ATTRIBUTE_PACKED anki_vehicle_msg_set_config_params_t; +#define ANKI_VEHICLE_MSG_C2V_SET_CONFIG_PARAMS_SIZE 3 + +/** + * Create a message for setting the SDK mode. + * + * Note that in order to set the speed and change lanes in the current SDK, + * the ANKI_VEHICLE_SDK_OPTION_OVERRIDE_LOCALIZATION flag must be set + * when enabling the SDK mode. + * + * @param msg A pointer to the vehicle message struct to be written. + * @param on Whether to turn SDK mode on (1) or off (0). + * @param flags Option flags to specify vehicle behaviors while SDK mode is enabled. + * + * @return size of bytes written to msg + */ +uint8_t anki_vehicle_msg_set_sdk_mode(anki_vehicle_msg_t *msg, uint8_t on, uint8_t flags); + +/** + * Create a message for setting the vehicle speed. + * + * @param msg A pointer to the vehicle message struct to be written. + * @param speed_mm_per_sec The requested vehicle speed in mm/sec. + * @param accel_mm_per_sec2 The acceleration in mm/sec^2. + * + * @return size of bytes written to msg + */ +uint8_t anki_vehicle_msg_set_speed(anki_vehicle_msg_t *msg, + uint16_t speed_mm_per_sec, + uint16_t accel_mm_per_sec2); + +/** + * Create a message for setting vehicle's internal offset from road center. + * + * This value is stored internally in the vehicle and is used during a + * lane change request to determine the target location. In the current + * version of the SDK, this message is always sent to set the current offset + * to zero before a lane change message. This allows the lane change to control + * the relative horizontal movement of the vehicle + * + * @param msg A pointer to the vehicle message struct to be written. + * @param offset_mm The offset from the road center in mm. + * + * @return size of bytes written to msg + * + * @see anki_vehicle_msg_change_lane + */ +uint8_t anki_vehicle_msg_set_offset_from_road_center(anki_vehicle_msg_t *msg, float offset_mm); + +/** + * Create a message to change the lane of driving vehicle. + * + * The vehicle must be moving in order for this command to be + * executed. + * + * @param msg A pointer to the vehicle message struct to be written. + * @param horizontal_speed_mm_per_sec The horizontal speed at for the lane change in mm/sec. + * @param horizontal_accel_mm_per_sec The horizontal acceleration for the lane change in mm/sec. + * @param offset_from_center_mm The target offset from the road center in mm. + * + * @return size of bytes written to msg + */ +uint8_t anki_vehicle_msg_change_lane(anki_vehicle_msg_t *msg, + uint16_t horizontal_speed_mm_per_sec, + uint16_t horizontal_accel_mm_per_sec2, + float offset_from_center_mm); + +/** + * Create a message to set vehicle light directly using a mask. + * + * @param msg A pointer to the vehicle message struct to be written. + * @param mask Mask byte representing the desired lights. + * + * @return size of bytes written to msg + * + * @see anki_vehicle_msg_set_lights_t + */ +uint8_t anki_vehicle_msg_set_lights(anki_vehicle_msg_t *msg, uint8_t mask); + +/** + * Create a vehicle lights configuration. + * + * @param config A pointer to the light channel configuration. + * @param channel The target lights. See anki_vehicle_light_channel_t. + * @param effect The type of desired effect. See anki_vehicle_light_effect_t. + * @param start The starting intensity of the LED. + * @param end The end intensity of the LED. + * @param cycles_per_min The frequency repeated start->end transition phases (according to effect). + * + * @see anki_vehicle_light_channel_t, anki_vehicle_light_effect_t + */ +void anki_vehicle_light_config(anki_vehicle_light_config_t *config, + anki_vehicle_light_channel_t channel, + anki_vehicle_light_effect_t effect, + uint8_t start, + uint8_t end, + uint16_t cycles_per_min); + +/** + * Create a message to set a vehicle lights pattern. + * + * @param msg A pointer to the vehicle message struct to be written. + * @param channel The target lights. See anki_vehicle_light_channel_t. + * @param effect The type of desired effect. See anki_vehicle_light_effect_t. + * @param start The starting intensity of the LED. + * @param end The end intensity of the LED. + * @param cycles_per_min The frequency repeated start->end transition phases (according to effect). + * + * @return size of bytes written to msg + * + * @see anki_vehicle_light_channel_t, anki_vehicle_light_effect_t + */ +uint8_t anki_vehicle_msg_lights_pattern(anki_vehicle_msg_t *message, + anki_vehicle_light_channel_t channel, + anki_vehicle_light_effect_t effect, + uint8_t start, + uint8_t end, + uint16_t cycles_per_min); + +/** + * Create a message to set vehicle lights using light channel configurations. + * + * Up to 3 channel configurations can be added to a single lights_pattern message. + * + * @param message A pointer to the vehicle message struct to be written. + * @param config A pointer to the light channel config to append to the message. + * + * @return size of appended config object or zero if nothing was appended. + */ +uint8_t anki_vehicle_msg_lights_pattern_append(anki_vehicle_msg_lights_pattern_t* message, + anki_vehicle_light_config_t* config); + +/** + * Create a message to request that the vehicle disconnect. + * + * This is often a more reliable way to disconnect compared to closing + * the connection to a vehicle from the central. + * + * @param msg A pointer to the vehicle message struct to be written. + * + * @return size of bytes written to msg + */ +uint8_t anki_vehicle_msg_disconnect(anki_vehicle_msg_t *msg); + +/** + * Create a message to send the vehicle a ping request. + * + * This will cause the vehicle to response with a message of type + * ANKI_VEHICLE_MSG_V2C_PING_RESPONSE. + * + * @param msg A pointer to the vehicle message struct to be written. + * + * @return size of bytes written to msg + */ +uint8_t anki_vehicle_msg_ping(anki_vehicle_msg_t *msg); + +/** + * Create a message to request the vehicle firmware version. + * + * The vehicle will response with a anki_vehicle_msg_version_response_t message. + * + * @param msg A pointer to the vehicle message struct to be written. + * + * @return size of bytes written to msg + */ +uint8_t anki_vehicle_msg_get_version(anki_vehicle_msg_t *msg); + +/** + * Create a message to request the vehicle battery level. + * + * The vehicle will respond with a anki_vehicle_msg_battery_level_response_t + * message. + * + * @param msg A pointer to the vehicle message struct to be written. + * + * @return size of bytes written to msg + */ +uint8_t anki_vehicle_msg_get_battery_level(anki_vehicle_msg_t *msg); + +/** + * Create a message to cancel a requested lane change. + * + * @param msg A pointer to the vehicle message struct to be written. + * + * @return size of bytes written to msg + */ +uint8_t anki_vehicle_msg_cancel_lane_change(anki_vehicle_msg_t *msg); + +/** + * Create a message to request a turn. + * + * @param msg A pointer to the vehicle message struct to be written. + * @param type Enum value specifying the type of turn to execute. (see `see anki_vehicle_turn_type_t`) + * The default value is `VEHICLE_TURN_TYPE_NONE`, which is a no-op (no turn executed). + * @param trigger Enum value specifying when to execute the turn. (see `anki_vehicle_turn_trigger_t`) + * The only supported value is currently `VEHICLE_TURN_TRIGGER_IMMEDIATE`, + * which causes the turn to be executed immediately. + * + * @return size of bytes written to msg + */ +uint8_t anki_vehicle_msg_turn(anki_vehicle_msg_t *msg, + anki_vehicle_turn_type_t type, + anki_vehicle_turn_trigger_t trigger); + +/** + * Create a message to request a 180 degree turn. + * + * @param msg A pointer to the vehicle message struct to be written. + * + * @return size of bytes written to msg + */ +uint8_t anki_vehicle_msg_turn_180(anki_vehicle_msg_t *msg); + + +/** + * Create a message to set vehicle config parameters + * + * Specify parameters that modify scan-parsing or change the way that track codes are + * iterpreted. + * + * This message is experimental and may change in the future. + * + * @param msg A pointer to the vehicle message struct to be written. + * @param super_code_parse_mask Mask byte specifying super codes that should be parsed. + * @param track_material Enum value specifying the material on which codes are printed. + * + * @return size of bytes written to msg + */ +uint8_t anki_vehicle_msg_set_config_params(anki_vehicle_msg_t* msg, + uint8_t super_code_parse_mask, + anki_track_material_t track_material); + +ANKI_END_DECL + +#endif diff --git a/drive-sdk/include/ankidrive/uuid.h b/drive-sdk/include/ankidrive/uuid.h new file mode 100644 index 0000000..e93ca84 --- /dev/null +++ b/drive-sdk/include/ankidrive/uuid.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2014 Anki, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_uuid_h +#define INCLUDE_uuid_h + +#include + +#include "common.h" + +ANKI_BEGIN_DECL + +struct uuid128 { + uint8_t byte0; + uint8_t byte1; + uint8_t byte2; + uint8_t byte3; + uint8_t byte4; + uint8_t byte5; + uint8_t byte6; + uint8_t byte7; + uint8_t byte8; + uint8_t byte9; + uint8_t byte10; + uint8_t byte11; + uint8_t byte12; + uint8_t byte13; + uint8_t byte14; + uint8_t byte15; +}; +typedef struct uuid128 uuid128_t; + +int uuid128_cmp(const uuid128_t *a, const uuid128_t *b); + +ANKI_END_DECL + +#endif diff --git a/drive-sdk/include/ankidrive/vehicle_gatt_profile.h b/drive-sdk/include/ankidrive/vehicle_gatt_profile.h new file mode 100644 index 0000000..6ed0f25 --- /dev/null +++ b/drive-sdk/include/ankidrive/vehicle_gatt_profile.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2014 Anki, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_vehicle_gatt_profile_h +#define INCLUDE_vehicle_gatt_profile_h + +#define ANKI_STR_SERVICE_UUID "BE15BEEF-6186-407E-8381-0BD89C4D8DF4" +#define ANKI_SERVICE_UUID { 0xbe, 0x15, 0xbe, 0xef, 0x61, 0x68, 0x40, 0x7e, 0x83, 0x81, 0x0b, 0xd8, 0x9c, 0x4d, 0x8d, 0xf4 } +#define ANKI_SERVICE_UUID_LE { 0xf4, 0x8d, 0x4d, 0x9c, 0xd8, 0x0b, 0x81, 0x83, 0x7e, 0x40, 0x86, 0x61, 0xef, 0xbe, 0x15, 0xbe } + +#define ANKI_STR_CHR_READ_UUID "BE15BEE0-6186-407E-8381-0BD89C4D8DF4" +#define ANKI_CHR_READ_UUID { 0xbe, 0x15, 0xbe, 0xe0, 0x61, 0x68, 0x40, 0x7e, 0x83, 0x81, 0x0b, 0xd8, 0x9c, 0x4d, 0x8d, 0xf4 } + +#define ANKI_STR_CHR_WRITE_UUID "BE15BEE1-6186-407E-8381-0BD89C4D8DF4" +#define ANKI_CHR_WRITE_UUID { 0xbe, 0x15, 0xbe, 0xe1, 0x61, 0x68, 0x40, 0x7e, 0x83, 0x81, 0x0b, 0xd8, 0x9c, 0x4d, 0x8d, 0xf4 } + +#endif diff --git a/drive-sdk/include/ankidrive/version.h b/drive-sdk/include/ankidrive/version.h new file mode 100644 index 0000000..cb6390c --- /dev/null +++ b/drive-sdk/include/ankidrive/version.h @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2014 Anki, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_ankidrive_vehicle_h__ +#define INCLUDE_ankidrive_vehicle_h__ + +#define ANKIDRIVESDK_VERSION "0.3.0" +#define ANKIDRIVESDK_VER_MAJOR 0 +#define ANKIDRIVESDK_VER_MINOR 3 +#define ANKIDRIVESDK_VER_REVISION 0 + +#endif diff --git a/drive-sdk/src/CMakeLists.txt b/drive-sdk/src/CMakeLists.txt new file mode 100644 index 0000000..b326665 --- /dev/null +++ b/drive-sdk/src/CMakeLists.txt @@ -0,0 +1,22 @@ +# Include the directory itself as a path to include directories +set(CMAKE_INCLUDE_CURRENT_DIR ON) + +set(drivekit_SOURCES + eir.c eir.h + anki_util.c + advertisement.c advertisement.h + uuid.c uuid.h + protocol.c protocol.h +) + + +# For a large number of source files you can create it in a simpler way +# using file() function: +# file(GLOB drivekit_SOURCES *.cpp) + +add_library(ankidrive ${drivekit_SOURCES}) + +install(TARGETS ankidrive + LIBRARY DESTINATION lib + ARCHIVE DESTINATION lib +) diff --git a/drive-sdk/src/advertisement.c b/drive-sdk/src/advertisement.c new file mode 100644 index 0000000..e5cbfe9 --- /dev/null +++ b/drive-sdk/src/advertisement.c @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2014 Anki, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +#include "eir.h" +#include "advertisement.h" +#include "vehicle_gatt_profile.h" +#include "uuid.h" +#include "anki_util.h" + +#define VEHICLE_STATE_FULL_BATTERY (1 << 4) +#define VEHICLE_STATE_LOW_BATTERY (1 << 5) +#define VEHICLE_STATE_ON_CHARGER (1 << 6) +#define IS_VEHICLE_STATE_SET(state, flag) ( ((state) & (flag)) == (flag) ) + +int is_anki_vehicle_service_uuid(uuid128_t *a); + +uint8_t anki_vehicle_parse_adv_record(const uint8_t *scan_data, const size_t scan_data_len, anki_vehicle_adv_t *anki_vehicle_adv) +{ + // no data to parse + if (scan_data == NULL) + return 1; + + int i = 0; + while (i < scan_data_len) { + uint8_t len = scan_data[i++]; + if (len == 0) break; + + ble_adv_record_type_t type = scan_data[i]; + if (type == ADV_TYPE_INVALID) break; + + const uint8_t *data = &scan_data[i+1]; + uint8_t data_len = len - 1; + switch(type) { + case ADV_TYPE_INVALID: + return -1; + break; + case ADV_TYPE_FLAGS: + if (anki_vehicle_adv != NULL) + memmove(&anki_vehicle_adv->flags, data, data_len); + break; + case ADV_TYPE_UUID_128: + { + if ((data_len == sizeof(uuid128_t)) && + !is_anki_vehicle_service_uuid((uuid128_t*)data) ) + return 2; + + if (anki_vehicle_adv != NULL) { + memmove(&anki_vehicle_adv->service_id, data, data_len); + } else { + return 0; + } + break; + } + case ADV_TYPE_LOCAL_NAME: + if (anki_vehicle_adv != NULL) { + anki_vehicle_parse_local_name(data, data_len, &anki_vehicle_adv->local_name); + } + break; + case ADV_TYPE_TX_POWER: + if (anki_vehicle_adv != NULL) + memmove(&anki_vehicle_adv->tx_power, data, data_len); + break; + case ADV_TYPE_MANUFACTURER_DATA: + if (anki_vehicle_adv != NULL) { + anki_vehicle_parse_mfg_data(data, data_len, &anki_vehicle_adv->mfg_data); + } + break; + default: + return 3; + printf("\nunknown type: %d\n", type); + hexdump("data: ", 80, data, data_len); + break; + } + + i += len; + } + + return ((anki_vehicle_adv != NULL) && is_anki_vehicle_service_uuid(&anki_vehicle_adv->service_id)) ? 0 : 2; +} + +uint8_t anki_vehicle_adv_record_has_anki_uuid(const uint8_t *scan_data, const size_t scan_data_len) +{ + return (anki_vehicle_parse_adv_record(scan_data, scan_data_len, NULL) == 0); +} + +int is_anki_vehicle_service_uuid(uuid128_t *a) +{ + static const uint8_t ANKI_SERVICE_UUID_BYTES[16] = ANKI_SERVICE_UUID_LE; + return (uuid128_cmp(a, (uuid128_t *)ANKI_SERVICE_UUID_BYTES) == 0); +} + +uint8_t anki_vehicle_parse_mfg_data(const uint8_t *bytes, uint8_t len, anki_vehicle_adv_mfg_t *mfg_data) +{ + if (bytes == NULL || len != 8) return 1; + + // bytes stored on the vehicle in Big Endian order + // This assumes the host is little endian + + mfg_data->product_id = (bytes[1] | (bytes[0] << 8)); + mfg_data->_reserved = bytes[2]; + mfg_data->model_id = bytes[3]; + mfg_data->identifier = (bytes[7] | (bytes[6] << 8) | (bytes[5] << 16) | (bytes[4] << 24)); + + return 0; +} + +uint8_t anki_vehicle_parse_local_name(const uint8_t *bytes, uint8_t len, anki_vehicle_adv_info_t *local_name) +{ + if (len == 0) return 1; + + uint8_t state = (uint8_t)bytes[0] & 0xff; + local_name->state.full_battery = IS_VEHICLE_STATE_SET(state, VEHICLE_STATE_FULL_BATTERY); + local_name->state.low_battery = IS_VEHICLE_STATE_SET(state, VEHICLE_STATE_LOW_BATTERY); + local_name->state.on_charger = IS_VEHICLE_STATE_SET(state, VEHICLE_STATE_ON_CHARGER); + + if (len > 1) { + local_name->version = bytes[1]; + } + + if (len > 2) { + local_name->version |= (bytes[2] << 8); + } + + if (len > 8) { + uint8_t name_len = len - 8; + memset(local_name->name, 0, (sizeof local_name->name)); + memmove(local_name->name, &bytes[8], name_len); + } + + return 0; +} diff --git a/drive-sdk/src/advertisement.h b/drive-sdk/src/advertisement.h new file mode 100644 index 0000000..9b192e2 --- /dev/null +++ b/drive-sdk/src/advertisement.h @@ -0,0 +1,145 @@ +/* + * Copyright (c) 2014 Anki, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_advertisement_h +#define INCLUDE_advertisement_h + +#include +#include "common.h" +#include "uuid.h" + +ANKI_BEGIN_DECL + +/** + * The state of a vehicle recorded in the advertising packet. + * + * - full_battery: The vehicle battery is fully charged + * - low_battery: The vehicle battery has a low charge and will die soon + * - on_charger: The vehicle is currently on the charger + */ +typedef struct anki_vehicle_adv_state { + uint8_t _reserved:4; + uint8_t full_battery:1; // 4: TRUE if Car has full battery + uint8_t low_battery:1; // 5: TRUE if Car has low battery + uint8_t on_charger:1; // 6: TRUE if Car is on Charger + uint8_t _unavailable:1; // 7: Cannot be used due to BTLE character set constraint +} anki_vehicle_adv_state_t; + +/** + * Vehicle information packed in the LOCAL_NAME string record + * of an advertising packet. + * + * - state: Current vehicle state. + * NOTE: Changes to the vehicle state will cause the LOCAL_NAME value + * to change. + * - version: Firmware version running on the vehicle + * - name: User-defined name in UTF-8 encoding + */ +typedef struct anki_vehicle_adv_info { + anki_vehicle_adv_state_t state; + uint16_t version; + uint8_t _reserved[5]; + unsigned char name[13]; // UTF8: 12 bytes + NULL. +} anki_vehicle_adv_info_t; + + +/** + * Vehicle hardware information encodeded in the MANUFACTURER_DATA + * record of an advertising packet. + * + * - identifier: Unique identifer for a physical vehicle + * - model_id: The model type of a vehicle + * - product_id: Value identifying the vehicle as Anki Drive hardware + */ +typedef struct anki_vehicle_adv_mfg { + uint32_t identifier; + uint8_t model_id; + uint8_t _reserved; + uint16_t product_id; +} anki_vehicle_adv_mfg_t; + + +/** + * Vehicle information present in Bluetooth LE advertising packets. + * + * flags: EIR / AD flags + * tx_power: transmission power + * mfg_data: parsed data from the MANUFACTURER_DATA bytes + * local_name: parsed data from the LOCAL_NAME string bytes + * service_id: Anki Vehicle UUID (128-bit) + */ +typedef struct anki_vehicle_adv { + uint8_t flags; + uint8_t tx_power; + anki_vehicle_adv_mfg_t mfg_data; + anki_vehicle_adv_info_t local_name; + uuid128_t service_id; +} anki_vehicle_adv_t; + +/** + * Test whether the scan record contains an Anki Drive vehicle service UUID. + * + * @param scan_data Bytes obtained by scanning vehicle advertising packets. + * @param scan_data_len Length of bytes in scan_data. + * + * @return 0 on failure, 1 on success. + */ +uint8_t anki_vehicle_adv_record_has_anki_uuid(const uint8_t *scan_data, const size_t scan_data_len); + + +/** + * Parse advertising data for an Anki Drive vehicle. + * + * @param scan_data Bytes obtained by scanning vehicle advertising packets. + * @param scan_data_len Length of bytes in scan_data. + * @param anki_vehicle_adv Pointer to a structure for storing accumulated information for a vehicle. + * Parsed scan data will overwrite matching record data in the struct. + * + * @return 0 on success, 1 on failure, + * 2 if the data is not anki drive + * 3 if unknown EIR data is encountered + * + * @discuss Pass NULL for anki_vehicle_adv in order to determine if this is an appropriate record. + * + * + */ +uint8_t anki_vehicle_parse_adv_record(const uint8_t *scan_data, const size_t scan_data_len, anki_vehicle_adv_t *anki_vehicle_adv); + +/** + * Parse MANUFACTERER_DATA record from a vehicle advertising packet. + * + * @param scan_data Bytes obtained by scanning vehicle advertising packets. + * @param scan_data_len Length of bytes in scan_data. + * @param mfg_data Pointer to a structure for storing parsed data. + * + * @return 0 on success, 1 on failure. + */ +uint8_t anki_vehicle_parse_mfg_data(const uint8_t *bytes, uint8_t len, anki_vehicle_adv_mfg_t *mfg_data); + +/** + * Parse LOCAL_NAME record from a vehicle advertising packet. + * + * @param scan_data Bytes obtained by scanning vehicle advertising packets. + * @param scan_data_len Length of bytes in scan_data. + * @param local_name Pointer to a structure for storing parsed data. + * + * @return 0 on success, 1 on failure. + */ +uint8_t anki_vehicle_parse_local_name(const uint8_t *bytes, uint8_t len, anki_vehicle_adv_info_t *local_name); + +ANKI_END_DECL + +#endif diff --git a/drive-sdk/src/anki_util.c b/drive-sdk/src/anki_util.c new file mode 100644 index 0000000..24cb1dd --- /dev/null +++ b/drive-sdk/src/anki_util.c @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2014 Anki, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include + +void bytes_to_hex(const void *value, size_t len, char **output) { + const unsigned char *bytes = (const unsigned char *)value; + size_t bufferLen = len * 3 * sizeof(char); + char str[bufferLen]; + memset(str, 0, bufferLen); + + const char *hex = "0123456789ABCDEF"; + char *s = str; + + for (size_t i = 0; i < len-1; ++i ) { + *s++ = hex[(*bytes>>4)&0xF]; + *s++ = hex[(*bytes++)&0xF]; + *s++ = ' '; + } + *s++ = hex[(*bytes>>4)&0xF]; + *s++ = hex[(*bytes++)&0xF]; + *s++ = 0; + + if (output != NULL) + memmove(*output, str, bufferLen); +} + +void hexdump(const char *prefix, const size_t column_len, const void *value, size_t len) { + assert(prefix != NULL); + assert(column_len > 0); + int row_count = (len / column_len) + 1; + int i; + + size_t slen = column_len*3; + char* s = malloc(slen * sizeof(char)); + for (i = 0; i < row_count; ++i) { + memset(s, 0, slen); + bytes_to_hex(value, len, (char **)&s); + printf("%s %s\n", prefix, s); + } + free(s); +} + + diff --git a/drive-sdk/src/anki_util.h b/drive-sdk/src/anki_util.h new file mode 100644 index 0000000..8c46361 --- /dev/null +++ b/drive-sdk/src/anki_util.h @@ -0,0 +1,29 @@ + +/* + * Copyright (c) 2014 Anki, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_anki_util_h +#define INCLUDE_anki_util_h + +#include "common.h" + +ANKI_BEGIN_DECL + +void hexdump(const char *prefix, const size_t column_len, const void *value, size_t len); + +ANKI_END_DECL + +#endif diff --git a/drive-sdk/src/common.h b/drive-sdk/src/common.h new file mode 100644 index 0000000..d946ceb --- /dev/null +++ b/drive-sdk/src/common.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2014 Anki, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_common_h +#define INCLUDE_common_h + +#ifdef __cplusplus +# define ANKI_BEGIN_DECL extern "C" { +# define ANKI_END_DECL } +#else + /** Start declarations in C mode */ +# define ANKI_BEGIN_DECL /* empty */ + /** End declarations in C mode */ +# define ANKI_END_DECL /* empty */ +#endif + +/** Declare a public function */ +#if __GNUC__ >= 4 +# define ANKI_EXTERN(type) extern \ + __attribute__((visibility("default"))) \ + type +#elif defined(_MSC_VER) +# define ANKI_EXTERN(type) __declspec(dllexport) type +#else +# define ANKI_EXTERN(type) extern type +#endif + +/** Declare a function as always inlined. */ +#if defined(_MSC_VER) +# define ANKI_INLINE(type) static __inline type +#else +# define ANKI_INLINE(type) static inline type +#endif + +#endif diff --git a/drive-sdk/src/eir.c b/drive-sdk/src/eir.c new file mode 100644 index 0000000..1255bb4 --- /dev/null +++ b/drive-sdk/src/eir.c @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2014 Anki, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +#include "eir.h" + +int ble_adv_parse_scan(const uint8_t *data, const size_t data_len, size_t *record_count, ble_adv_record_t records[]) +{ + // no data to parse + if (data == NULL) + return 1; + + uint8_t record_index = 0; + int i = 0; + while (i < data_len) { + uint8_t len = data[i++]; + if (len == 0) break; + + ble_adv_record_type_t type = data[i]; + if (type == ADV_TYPE_INVALID) break; + + if (records != NULL) { + ble_adv_record_t *record = &records[record_index]; + record->type = type; + record->length = (len-1); + memmove(record->data, &data[i+1], len-1); + } + + record_index++; + i += len; + } + + if (record_count != NULL) { + *record_count = record_index; + } + + return 0; +} diff --git a/drive-sdk/src/eir.h b/drive-sdk/src/eir.h new file mode 100644 index 0000000..8f434bd --- /dev/null +++ b/drive-sdk/src/eir.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2014 Anki, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_eir_h +#define INCLUDE_eir_h + +#include +#include + +#include "common.h" + +ANKI_BEGIN_DECL + +#define BLE_ADV_RECORD_MAX_LEN 32 +struct ble_adv_record { + uint8_t type; + uint8_t length; + uint8_t data[30]; +}; +typedef struct ble_adv_record ble_adv_record_t; + +/* + * These Advertising Data types are required for parsing Anki Drive vehicle records. + * + * This is an incomplete list. + * See https://www.bluetooth.org/en-us/specification/assigned-numbers/generic-access-profile + * for all supported values + */ +enum ble_adv_record_type { + ADV_TYPE_INVALID = 0, + ADV_TYPE_FLAGS = 0x1, + ADV_TYPE_UUID_128 = 0x7, + ADV_TYPE_LOCAL_NAME = 0x9, + ADV_TYPE_TX_POWER = 0xa, + ADV_TYPE_MANUFACTURER_DATA = 0xff +}; +typedef uint8_t ble_adv_record_type_t; + +int ble_adv_parse_scan(const uint8_t *data, const size_t data_len, size_t *record_count, ble_adv_record_t records[]); + +ANKI_END_DECL + +#endif diff --git a/drive-sdk/src/protocol.c b/drive-sdk/src/protocol.c new file mode 100644 index 0000000..0c00133 --- /dev/null +++ b/drive-sdk/src/protocol.c @@ -0,0 +1,246 @@ +/* + * Copyright (c) 2014 Anki, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +#include "protocol.h" + +#define ANKI_VEHICLE_MSG_TYPE_SIZE 2 + +uint8_t anki_vehicle_msg_set_sdk_mode(anki_vehicle_msg_t *message, uint8_t on, uint8_t flags) +{ + assert(message != NULL); + + anki_vehicle_msg_sdk_mode_t *msg = (anki_vehicle_msg_sdk_mode_t *)message; + memset(msg, 0, sizeof(anki_vehicle_msg_sdk_mode_t)); + msg->size = ANKI_VEHICLE_MSG_SDK_MODE_SIZE; + msg->msg_id = ANKI_VEHICLE_MSG_C2V_SDK_MODE; + msg->on = on; + msg->flags = flags; + + return sizeof(anki_vehicle_msg_sdk_mode_t); +} + +uint8_t anki_vehicle_msg_set_speed(anki_vehicle_msg_t *message, uint16_t speed_mm_per_sec, uint16_t accel_mm_per_sec2) +{ + assert(message != NULL); + + anki_vehicle_msg_set_speed_t *msg = (anki_vehicle_msg_set_speed_t *)message; + memset(msg, 0, sizeof(anki_vehicle_msg_set_speed_t)); + msg->size = ANKI_VEHICLE_MSG_C2V_SET_SPEED_SIZE; + msg->msg_id = ANKI_VEHICLE_MSG_C2V_SET_SPEED; + msg->speed_mm_per_sec = speed_mm_per_sec; + msg->accel_mm_per_sec2 = accel_mm_per_sec2; + + return sizeof(anki_vehicle_msg_set_speed_t); +} + +uint8_t anki_vehicle_msg_set_offset_from_road_center(anki_vehicle_msg_t *msg, float offset_mm) +{ + assert(msg != NULL); + + anki_vehicle_msg_set_offset_from_road_center_t *m = (anki_vehicle_msg_set_offset_from_road_center_t *)msg; + memset(m, 0, sizeof(anki_vehicle_msg_set_offset_from_road_center_t)); + m->size = sizeof(anki_vehicle_msg_set_offset_from_road_center_t) - ANKI_VEHICLE_MSG_BASE_SIZE; + m->msg_id = ANKI_VEHICLE_MSG_C2V_SET_OFFSET_FROM_ROAD_CENTER; + m->offset_mm = offset_mm; + + return sizeof(anki_vehicle_msg_set_offset_from_road_center_t); +} + +uint8_t anki_vehicle_msg_change_lane(anki_vehicle_msg_t *message, + uint16_t horizontal_speed_mm_per_sec, + uint16_t horizontal_accel_mm_per_sec2, + float offset_from_center_mm) +{ + assert(message != NULL); + memset(message, 0, sizeof(anki_vehicle_msg_t)); + + anki_vehicle_msg_change_lane_t *msg = (anki_vehicle_msg_change_lane_t *)message; + msg->size = ANKI_VEHICLE_MSG_C2V_CHANGE_LANE_SIZE; + msg->msg_id = ANKI_VEHICLE_MSG_C2V_CHANGE_LANE; + msg->horizontal_speed_mm_per_sec = horizontal_speed_mm_per_sec; + msg->horizontal_accel_mm_per_sec2 = horizontal_accel_mm_per_sec2; + msg->offset_from_road_center_mm = offset_from_center_mm; + + return sizeof(anki_vehicle_msg_change_lane_t); +} + +uint8_t anki_vehicle_msg_set_lights(anki_vehicle_msg_t *message, uint8_t mask) +{ + assert(message != NULL); + + anki_vehicle_msg_set_lights_t *msg = (anki_vehicle_msg_set_lights_t *)message; + memset(msg, 0, sizeof(anki_vehicle_msg_set_lights_t)); + msg->size = ANKI_VEHICLE_MSG_C2V_SET_LIGHTS_SIZE; + msg->msg_id = ANKI_VEHICLE_MSG_C2V_SET_LIGHTS; + msg->light_mask = mask; + + return sizeof(anki_vehicle_msg_set_lights_t); +} + +void anki_vehicle_light_config(anki_vehicle_light_config_t *config, + anki_vehicle_light_channel_t channel, + anki_vehicle_light_effect_t effect, + uint8_t start, + uint8_t end, + uint16_t cycles_per_min) +{ + assert(config != NULL); + config->channel = channel; + config->effect = effect; + config->start = (start > ANKI_VEHICLE_MAX_LIGHT_INTENSITY) ? ANKI_VEHICLE_MAX_LIGHT_INTENSITY : start; + config->end = (end > ANKI_VEHICLE_MAX_LIGHT_INTENSITY) ? ANKI_VEHICLE_MAX_LIGHT_INTENSITY : end; + uint16_t cpm = cycles_per_min > ANKI_VEHICLE_MAX_LIGHT_TIME ? ANKI_VEHICLE_MAX_LIGHT_TIME : cycles_per_min; + config->cycles_per_10_sec = (uint8_t)(cpm / 6); +} + +uint8_t anki_vehicle_msg_lights_pattern_append(anki_vehicle_msg_lights_pattern_t* msg, + anki_vehicle_light_config_t* config) +{ + assert(msg != NULL); + assert(config != NULL); + + if ( (msg->msg_id != ANKI_VEHICLE_MSG_C2V_LIGHTS_PATTERN) + || (msg->size != ANKI_VEHICLE_MSG_C2V_LIGHTS_PATTERN_SIZE) + || (msg->channel_count == 0)) { + memset(msg, 0, sizeof(anki_vehicle_msg_lights_pattern_t)); + } + + uint8_t next_index = msg->channel_count; + if (next_index >= LIGHT_CHANNEL_COUNT_MAX) { + return 0; + } + + msg->size = ANKI_VEHICLE_MSG_C2V_LIGHTS_PATTERN_SIZE; + msg->msg_id = ANKI_VEHICLE_MSG_C2V_LIGHTS_PATTERN; + + anki_vehicle_light_config_t* target = &(msg->channel_config[next_index]); + const size_t len = sizeof(*config); + memmove(target, config, len); + (msg->channel_count)++; + + return len; +} + +/* +uint8_t anki_vehicle_msg_lights_pattern(anki_vehicle_msg_t *message, + anki_vehicle_light_config_t* config, + uint8_t count) +*/ +uint8_t anki_vehicle_msg_lights_pattern(anki_vehicle_msg_t* message, + anki_vehicle_light_channel_t channel, + anki_vehicle_light_effect_t effect, + uint8_t start, + uint8_t end, + uint16_t cycles_per_min) +{ + assert(message != NULL); + + anki_vehicle_msg_lights_pattern_t *msg = (anki_vehicle_msg_lights_pattern_t *)message; + memset(msg, 0, sizeof(anki_vehicle_msg_lights_pattern_t)); + msg->size = ANKI_VEHICLE_MSG_C2V_LIGHTS_PATTERN_SIZE; + msg->msg_id = ANKI_VEHICLE_MSG_C2V_LIGHTS_PATTERN; + + anki_vehicle_light_config_t config; + anki_vehicle_light_config(&config, channel, effect, start, end, cycles_per_min); + + const uint8_t len = anki_vehicle_msg_lights_pattern_append(msg, &config); + if (len == 0) { + return 0; + } + + return sizeof(*msg); +} + +uint8_t anki_vehicle_msg_disconnect(anki_vehicle_msg_t *msg) +{ + assert(msg != NULL); + msg->size = ANKI_VEHICLE_MSG_BASE_SIZE; + msg->msg_id = ANKI_VEHICLE_MSG_C2V_DISCONNECT; + return ANKI_VEHICLE_MSG_TYPE_SIZE; +} + +uint8_t anki_vehicle_msg_cancel_lane_change(anki_vehicle_msg_t *msg) +{ + assert(msg != NULL); + msg->size = ANKI_VEHICLE_MSG_BASE_SIZE; + msg->msg_id = ANKI_VEHICLE_MSG_C2V_CANCEL_LANE_CHANGE; + return ANKI_VEHICLE_MSG_TYPE_SIZE; +} + +uint8_t anki_vehicle_msg_turn(anki_vehicle_msg_t *msg, + anki_vehicle_turn_type_t type, + anki_vehicle_turn_trigger_t trigger) +{ + assert(msg != NULL); + + anki_vehicle_msg_turn_t *m = (anki_vehicle_msg_turn_t *)msg; + memset(m, 0, sizeof(anki_vehicle_msg_turn_t)); + m->size = ANKI_VEHICLE_MSG_C2V_TURN_SIZE; + m->msg_id = ANKI_VEHICLE_MSG_C2V_TURN; + m->type = (uint8_t)type; + m->trigger = (uint8_t)trigger; + + return sizeof(anki_vehicle_msg_turn_t); +} + +uint8_t anki_vehicle_msg_turn_180(anki_vehicle_msg_t *msg) +{ + return anki_vehicle_msg_turn(msg, VEHICLE_TURN_UTURN, VEHICLE_TURN_TRIGGER_IMMEDIATE); +} + +uint8_t anki_vehicle_msg_set_config_params(anki_vehicle_msg_t* msg, + uint8_t super_code_parse_mask, + anki_track_material_t track_material) +{ + assert(msg != NULL); + + anki_vehicle_msg_set_config_params_t* m = (anki_vehicle_msg_set_config_params_t*)msg; + memset(m, 0, sizeof(anki_vehicle_msg_set_config_params_t)); + m->size = ANKI_VEHICLE_MSG_C2V_SET_CONFIG_PARAMS_SIZE; + m->msg_id = ANKI_VEHICLE_MSG_C2V_SET_CONFIG_PARAMS; + m->super_code_parse_mask = super_code_parse_mask; + m->track_material = track_material; + + return sizeof(anki_vehicle_msg_set_config_params_t); +} + +uint8_t anki_vehicle_msg_ping(anki_vehicle_msg_t *msg) +{ + assert(msg != NULL); + msg->size = ANKI_VEHICLE_MSG_BASE_SIZE; + msg->msg_id = ANKI_VEHICLE_MSG_C2V_PING_REQUEST; + return ANKI_VEHICLE_MSG_TYPE_SIZE; +} + +uint8_t anki_vehicle_msg_get_version(anki_vehicle_msg_t *msg) +{ + assert(msg != NULL); + msg->size = ANKI_VEHICLE_MSG_BASE_SIZE; + msg->msg_id = ANKI_VEHICLE_MSG_C2V_VERSION_REQUEST; + return ANKI_VEHICLE_MSG_TYPE_SIZE; +} + +uint8_t anki_vehicle_msg_get_battery_level(anki_vehicle_msg_t *msg) +{ + assert(msg != NULL); + msg->size = ANKI_VEHICLE_MSG_BASE_SIZE; + msg->msg_id = ANKI_VEHICLE_MSG_C2V_BATTERY_LEVEL_REQUEST; + return ANKI_VEHICLE_MSG_TYPE_SIZE; +} diff --git a/drive-sdk/src/protocol.h b/drive-sdk/src/protocol.h new file mode 100644 index 0000000..259960a --- /dev/null +++ b/drive-sdk/src/protocol.h @@ -0,0 +1,559 @@ +/* + * Copyright (c) 2014 Anki, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_protocol_h +#define INCLUDE_protocol_h + +#include + +#include "common.h" + +ANKI_BEGIN_DECL + +#define ANKI_VEHICLE_MSG_MAX_SIZE 20 +#define ANKI_VEHICLE_MSG_PAYLOAD_MAX_SIZE 18 +#define ANKI_VEHICLE_MSG_BASE_SIZE 1 + +/** Identifier for a vehicle message */ +enum { + // BLE Connections + ANKI_VEHICLE_MSG_C2V_DISCONNECT = 0x0d, + + // Ping request / response + ANKI_VEHICLE_MSG_C2V_PING_REQUEST = 0x16, + ANKI_VEHICLE_MSG_V2C_PING_RESPONSE = 0x17, + + // Messages for checking vehicle version info + ANKI_VEHICLE_MSG_C2V_VERSION_REQUEST = 0x18, + ANKI_VEHICLE_MSG_V2C_VERSION_RESPONSE = 0x19, + + // Battery level + ANKI_VEHICLE_MSG_C2V_BATTERY_LEVEL_REQUEST = 0x1a, + ANKI_VEHICLE_MSG_V2C_BATTERY_LEVEL_RESPONSE = 0x1b, + + // Lights + ANKI_VEHICLE_MSG_C2V_SET_LIGHTS = 0x1d, + + // Driving Commands + ANKI_VEHICLE_MSG_C2V_SET_SPEED = 0x24, + ANKI_VEHICLE_MSG_C2V_CHANGE_LANE = 0x25, + ANKI_VEHICLE_MSG_C2V_CANCEL_LANE_CHANGE = 0x26, + ANKI_VEHICLE_MSG_C2V_TURN = 0x32, + + // Vehicle position updates + ANKI_VEHICLE_MSG_V2C_LOCALIZATION_POSITION_UPDATE = 0x27, + ANKI_VEHICLE_MSG_V2C_LOCALIZATION_TRANSITION_UPDATE = 0x29, + ANKI_VEHICLE_MSG_V2C_LOCALIZATION_INTERSECTION_UPDATE = 0x2a, + ANKI_VEHICLE_MSG_V2C_VEHICLE_DELOCALIZED = 0x2b, + ANKI_VEHICLE_MSG_C2V_SET_OFFSET_FROM_ROAD_CENTER = 0x2c, + ANKI_VEHICLE_MSG_V2C_OFFSET_FROM_ROAD_CENTER_UPDATE = 0x2d, + + // Light Patterns + ANKI_VEHICLE_MSG_C2V_LIGHTS_PATTERN = 0x33, + + // Vehicle Configuration Parameters + ANKI_VEHICLE_MSG_C2V_SET_CONFIG_PARAMS = 0x45, + + // SDK Mode + ANKI_VEHICLE_MSG_C2V_SDK_MODE = 0x90, +}; + +#define ATTRIBUTE_PACKED __attribute__((packed)) + +/** + * Basic vehicle message. + * + * - size: Size in bytes of the msg_id plus payload + * - msg_id: Identifier for message + * - payload: Optional message data for parameters or response info. + * + */ +typedef struct anki_vehicle_msg { + uint8_t size; + uint8_t msg_id; + uint8_t payload[ANKI_VEHICLE_MSG_PAYLOAD_MAX_SIZE]; +} anki_vehicle_msg_t; + +typedef struct anki_vehicle_msg_version_response { + uint8_t size; + uint8_t msg_id; + uint16_t version; +} ATTRIBUTE_PACKED anki_vehicle_msg_version_response_t; +#define ANKI_VEHICLE_MSG_V2C_VERSION_RESPONSE_SIZE 3 + +typedef struct anki_vehicle_msg_battery_level_response { + uint8_t size; + uint8_t msg_id; + uint16_t battery_level; +} ATTRIBUTE_PACKED anki_vehicle_msg_battery_level_response_t; +#define ANKI_VEHICLE_MSG_V2C_BATTERY_LEVEL_RESPONSE_SIZE 3 + +#define ANKI_VEHICLE_SDK_OPTION_OVERRIDE_LOCALIZATION 0x1 +typedef struct anki_vehicle_msg_sdk_mode { + uint8_t size; + uint8_t msg_id; + uint8_t on; + uint8_t flags; +} ATTRIBUTE_PACKED anki_vehicle_msg_sdk_mode_t; +#define ANKI_VEHICLE_MSG_SDK_MODE_SIZE 3 + +typedef struct anki_vehicle_msg_set_speed { + uint8_t size; + uint8_t msg_id; + int16_t speed_mm_per_sec; // mm/sec + int16_t accel_mm_per_sec2; // mm/sec^2 + uint8_t respect_road_piece_speed_limit; +} ATTRIBUTE_PACKED anki_vehicle_msg_set_speed_t; +#define ANKI_VEHICLE_MSG_C2V_SET_SPEED_SIZE 6 + +typedef enum { + VEHICLE_TURN_NONE = 0, + VEHICLE_TURN_LEFT = 1, + VEHICLE_TURN_RIGHT = 2, + VEHICLE_TURN_UTURN = 3, + VEHICLE_TURN_UTURN_JUMP = 4, +} anki_vehicle_turn_type_t; + +typedef enum { + VEHICLE_TURN_TRIGGER_IMMEDIATE = 0, // Run immediately + VEHICLE_TURN_TRIGGER_INTERSECTION = 1, // Run at the next intersection +} anki_vehicle_turn_trigger_t; + +typedef struct anki_vehicle_msg_turn { + uint8_t size; + uint8_t msg_id; + uint8_t type; + uint8_t trigger; +} ATTRIBUTE_PACKED anki_vehicle_msg_turn_t; +#define ANKI_VEHICLE_MSG_C2V_TURN_SIZE 3 + +typedef struct anki_vehicle_msg_set_offset_from_road_center { + uint8_t size; + uint8_t msg_id; + float offset_mm; +} ATTRIBUTE_PACKED anki_vehicle_msg_set_offset_from_road_center_t; +#define ANKI_VEHICLE_MSG_C2V_SET_OFFSET_FROM_ROAD_CENTER_SIZE 5 + +typedef struct anki_vehicle_msg_change_lane { + uint8_t size; + uint8_t msg_id; + uint16_t horizontal_speed_mm_per_sec; + uint16_t horizontal_accel_mm_per_sec2; + float offset_from_road_center_mm; + uint8_t hop_intent; + uint8_t tag; +} ATTRIBUTE_PACKED anki_vehicle_msg_change_lane_t; +#define ANKI_VEHICLE_MSG_C2V_CHANGE_LANE_SIZE 11 + +// +// Bitwise masks applied to parsing_flags +// +// determine how many bits per code were read +#define PARSEFLAGS_MASK_NUM_BITS 0x0f + +// determine if the track has an inverted code scheme +#define PARSEFLAGS_MASK_INVERTED_COLOR 0x80 + +// determine if the the code has been reverse parsed +#define PARSEFLAGS_MASK_REVERSE_PARSING 0x40 + +// determine if the current driving dir is reversed +#define PARSEFLAGS_MASK_REVERSE_DRIVING 0x20 + +typedef struct anki_vehicle_msg_localization_position_update { + uint8_t size; + uint8_t msg_id; + uint8_t location_id; + uint8_t road_piece_id; + float offset_from_road_center_mm; + uint16_t speed_mm_per_sec; + uint8_t parsing_flags; + + /* ACK commands received */ + uint8_t last_recv_lane_change_cmd_id; + uint8_t last_exec_lane_change_cmd_id; + uint16_t last_desired_horizontal_speed_mm_per_sec; + uint16_t last_desired_speed_mm_per_sec; +} ATTRIBUTE_PACKED anki_vehicle_msg_localization_position_update_t; +#define ANKI_VEHICLE_MSG_V2C_LOCALIZATION_POSITION_UPDATE_SIZE 16 + +typedef enum anki_vehicle_driving_direction { + FORWARD = 0, + REVERSE = 1, +} anki_vehicle_driving_direction_t; + +typedef struct anki_vehicle_msg_localization_transition_update { + uint8_t size; + uint8_t msg_id; + uint8_t road_piece_idx; + uint8_t road_piece_idx_prev; + float offset_from_road_center_mm; + + uint8_t driving_direction; + + /* ACK commands received */ + uint8_t last_recv_lane_change_id; + uint8_t last_exec_lane_change_id; + uint16_t last_desired_horizontal_speed_mm_per_sec; + uint16_t last_desired_speed_mm_per_sec; + + /* track grade detection */ + uint8_t uphill_counter; + uint8_t downhill_counter; + + /* wheel displacement (cm) since last transition bar */ + uint8_t left_wheel_dist_cm; + uint8_t right_wheel_dist_cm; +} ATTRIBUTE_PACKED anki_vehicle_msg_localization_transition_update_t; +#define ANKI_VEHICLE_MSG_V2C_LOCALIZATION_TRANSITION_UPDATE_SIZE 18 + +typedef enum { + INTERSECTION_CODE_ENTRY_FIRST, + INTERSECTION_CODE_EXIT_FIRST, + INTERSECTION_CODE_ENTRY_SECOND, + INTERSECTION_CODE_EXIT_SECOND, +} anki_intersection_code_t; + +typedef struct anki_vehicle_msg_localization_intersection_update { + uint8_t size; + uint8_t msg_id; + uint8_t road_piece_idx; + float offset_from_road_center_mm; + + uint8_t driving_direction; + uint8_t intersection_code; + uint8_t intersection_turn; + uint8_t is_exiting; +} ATTRIBUTE_PACKED anki_vehicle_msg_localization_intersection_update_t; +#define ANKI_VEHICLE_MSG_V2C_LOCALIZATION_INTERSECTION_UPDATE_SIZE 10 + +typedef struct anki_vehicle_msg_offset_from_road_center_update { + uint8_t size; + uint8_t msg_id; + float offset_from_road_center_mm; + uint8_t lane_change_id; +} ATTRIBUTE_PACKED anki_vehicle_msg_offset_from_road_center_update_t; +#define ANKI_VEHICLE_MSG_V2C_OFFSET_FROM_ROAD_CENTER_UPDATE_SIZE 6 + +// Lights +// The bits in the simple light message (ANKI_VEHICLE_MSG_C2V_SET_LIGHTS) corresponding to +// each type of light. +#define LIGHT_HEADLIGHTS 0 +#define LIGHT_BRAKELIGHTS 1 +#define LIGHT_FRONTLIGHTS 2 +#define LIGHT_ENGINE 3 + +// Helper macros for parsing lights bits +#define LIGHT_ANKI_VEHICLE_MSG_IS_VALID(messageBits, LIGHT_ID) (((messageBits >> LIGHT_ID) & 1) == TRUE) +#define LIGHT_ANKI_VEHICLE_MSG_GET_VALUE(messageBits, LIGHT_ID) ((messageBits >> (4 + LIGHT_ANKI_VEHICLE_MSG_HEADLIGHTS) & 1)) + +typedef struct anki_vehicle_msg_set_lights { + uint8_t size; + uint8_t msg_id; + uint8_t light_mask; // Valid and value bits for lights (see above) +} ATTRIBUTE_PACKED anki_vehicle_msg_set_lights_t; +#define ANKI_VEHICLE_MSG_C2V_SET_LIGHTS_SIZE 2 + +#define ANKI_VEHICLE_MAX_LIGHT_INTENSITY 14 +#define ANKI_VEHICLE_MAX_LIGHT_TIME 11 + +// LED channel definitions - for RGB engine, front, and tail lights +typedef enum { + LIGHT_RED, + LIGHT_TAIL, + LIGHT_BLUE, + LIGHT_GREEN, + LIGHT_FRONTL, + LIGHT_FRONTR, + LIGHT_COUNT +} anki_vehicle_light_channel_t; + +// Below is a description of the various effects used in SetLight(...) +typedef enum { + EFFECT_STEADY, // Simply set the light intensity to 'start' value + EFFECT_FADE, // Fade intensity from 'start' to 'end' + EFFECT_THROB, // Fade intensity from 'start' to 'end' and back to 'start' + EFFECT_FLASH, // Turn on LED between time 'start' and time 'end' inclusive + EFFECT_RANDOM, // Flash the LED erratically - ignoring start/end + EFFECT_COUNT +} anki_vehicle_light_effect_t; + +typedef struct anki_vehicle_light_config { + uint8_t channel; + uint8_t effect; + uint8_t start; + uint8_t end; + uint8_t cycles_per_10_sec; +} ATTRIBUTE_PACKED anki_vehicle_light_config_t; + +#define LIGHT_CHANNEL_COUNT_MAX 3 +typedef struct anki_vehicle_msg_lights_pattern { + uint8_t size; + uint8_t msg_id; + uint8_t channel_count; + anki_vehicle_light_config_t channel_config[LIGHT_CHANNEL_COUNT_MAX]; +} ATTRIBUTE_PACKED anki_vehicle_msg_lights_pattern_t; +#define ANKI_VEHICLE_MSG_C2V_LIGHTS_PATTERN_SIZE 17 + +typedef enum anki_track_material { + TRACK_MATERIAL_PLASTIC, + TRACK_MATERIAL_VINYL, +} anki_track_material_t; + +#define SUPERCODE_NONE 0 +#define SUPERCODE_BOOST_JUMP 1 +#define SUPERCODE_ALL (SUPERCODE_BOOST_JUMP) + +typedef struct anki_vehicle_msg_set_config_params { + uint8_t size; + uint8_t msg_id; + uint8_t super_code_parse_mask; + uint8_t track_material; +} ATTRIBUTE_PACKED anki_vehicle_msg_set_config_params_t; +#define ANKI_VEHICLE_MSG_C2V_SET_CONFIG_PARAMS_SIZE 3 + +/** + * Create a message for setting the SDK mode. + * + * Note that in order to set the speed and change lanes in the current SDK, + * the ANKI_VEHICLE_SDK_OPTION_OVERRIDE_LOCALIZATION flag must be set + * when enabling the SDK mode. + * + * @param msg A pointer to the vehicle message struct to be written. + * @param on Whether to turn SDK mode on (1) or off (0). + * @param flags Option flags to specify vehicle behaviors while SDK mode is enabled. + * + * @return size of bytes written to msg + */ +uint8_t anki_vehicle_msg_set_sdk_mode(anki_vehicle_msg_t *msg, uint8_t on, uint8_t flags); + +/** + * Create a message for setting the vehicle speed. + * + * @param msg A pointer to the vehicle message struct to be written. + * @param speed_mm_per_sec The requested vehicle speed in mm/sec. + * @param accel_mm_per_sec2 The acceleration in mm/sec^2. + * + * @return size of bytes written to msg + */ +uint8_t anki_vehicle_msg_set_speed(anki_vehicle_msg_t *msg, + uint16_t speed_mm_per_sec, + uint16_t accel_mm_per_sec2); + +/** + * Create a message for setting vehicle's internal offset from road center. + * + * This value is stored internally in the vehicle and is used during a + * lane change request to determine the target location. In the current + * version of the SDK, this message is always sent to set the current offset + * to zero before a lane change message. This allows the lane change to control + * the relative horizontal movement of the vehicle + * + * @param msg A pointer to the vehicle message struct to be written. + * @param offset_mm The offset from the road center in mm. + * + * @return size of bytes written to msg + * + * @see anki_vehicle_msg_change_lane + */ +uint8_t anki_vehicle_msg_set_offset_from_road_center(anki_vehicle_msg_t *msg, float offset_mm); + +/** + * Create a message to change the lane of driving vehicle. + * + * The vehicle must be moving in order for this command to be + * executed. + * + * @param msg A pointer to the vehicle message struct to be written. + * @param horizontal_speed_mm_per_sec The horizontal speed at for the lane change in mm/sec. + * @param horizontal_accel_mm_per_sec The horizontal acceleration for the lane change in mm/sec. + * @param offset_from_center_mm The target offset from the road center in mm. + * + * @return size of bytes written to msg + */ +uint8_t anki_vehicle_msg_change_lane(anki_vehicle_msg_t *msg, + uint16_t horizontal_speed_mm_per_sec, + uint16_t horizontal_accel_mm_per_sec2, + float offset_from_center_mm); + +/** + * Create a message to set vehicle light directly using a mask. + * + * @param msg A pointer to the vehicle message struct to be written. + * @param mask Mask byte representing the desired lights. + * + * @return size of bytes written to msg + * + * @see anki_vehicle_msg_set_lights_t + */ +uint8_t anki_vehicle_msg_set_lights(anki_vehicle_msg_t *msg, uint8_t mask); + +/** + * Create a vehicle lights configuration. + * + * @param config A pointer to the light channel configuration. + * @param channel The target lights. See anki_vehicle_light_channel_t. + * @param effect The type of desired effect. See anki_vehicle_light_effect_t. + * @param start The starting intensity of the LED. + * @param end The end intensity of the LED. + * @param cycles_per_min The frequency repeated start->end transition phases (according to effect). + * + * @see anki_vehicle_light_channel_t, anki_vehicle_light_effect_t + */ +void anki_vehicle_light_config(anki_vehicle_light_config_t *config, + anki_vehicle_light_channel_t channel, + anki_vehicle_light_effect_t effect, + uint8_t start, + uint8_t end, + uint16_t cycles_per_min); + +/** + * Create a message to set a vehicle lights pattern. + * + * @param msg A pointer to the vehicle message struct to be written. + * @param channel The target lights. See anki_vehicle_light_channel_t. + * @param effect The type of desired effect. See anki_vehicle_light_effect_t. + * @param start The starting intensity of the LED. + * @param end The end intensity of the LED. + * @param cycles_per_min The frequency repeated start->end transition phases (according to effect). + * + * @return size of bytes written to msg + * + * @see anki_vehicle_light_channel_t, anki_vehicle_light_effect_t + */ +uint8_t anki_vehicle_msg_lights_pattern(anki_vehicle_msg_t *message, + anki_vehicle_light_channel_t channel, + anki_vehicle_light_effect_t effect, + uint8_t start, + uint8_t end, + uint16_t cycles_per_min); + +/** + * Create a message to set vehicle lights using light channel configurations. + * + * Up to 3 channel configurations can be added to a single lights_pattern message. + * + * @param message A pointer to the vehicle message struct to be written. + * @param config A pointer to the light channel config to append to the message. + * + * @return size of appended config object or zero if nothing was appended. + */ +uint8_t anki_vehicle_msg_lights_pattern_append(anki_vehicle_msg_lights_pattern_t* message, + anki_vehicle_light_config_t* config); + +/** + * Create a message to request that the vehicle disconnect. + * + * This is often a more reliable way to disconnect compared to closing + * the connection to a vehicle from the central. + * + * @param msg A pointer to the vehicle message struct to be written. + * + * @return size of bytes written to msg + */ +uint8_t anki_vehicle_msg_disconnect(anki_vehicle_msg_t *msg); + +/** + * Create a message to send the vehicle a ping request. + * + * This will cause the vehicle to response with a message of type + * ANKI_VEHICLE_MSG_V2C_PING_RESPONSE. + * + * @param msg A pointer to the vehicle message struct to be written. + * + * @return size of bytes written to msg + */ +uint8_t anki_vehicle_msg_ping(anki_vehicle_msg_t *msg); + +/** + * Create a message to request the vehicle firmware version. + * + * The vehicle will response with a anki_vehicle_msg_version_response_t message. + * + * @param msg A pointer to the vehicle message struct to be written. + * + * @return size of bytes written to msg + */ +uint8_t anki_vehicle_msg_get_version(anki_vehicle_msg_t *msg); + +/** + * Create a message to request the vehicle battery level. + * + * The vehicle will respond with a anki_vehicle_msg_battery_level_response_t + * message. + * + * @param msg A pointer to the vehicle message struct to be written. + * + * @return size of bytes written to msg + */ +uint8_t anki_vehicle_msg_get_battery_level(anki_vehicle_msg_t *msg); + +/** + * Create a message to cancel a requested lane change. + * + * @param msg A pointer to the vehicle message struct to be written. + * + * @return size of bytes written to msg + */ +uint8_t anki_vehicle_msg_cancel_lane_change(anki_vehicle_msg_t *msg); + +/** + * Create a message to request a turn. + * + * @param msg A pointer to the vehicle message struct to be written. + * @param type Enum value specifying the type of turn to execute. (see `see anki_vehicle_turn_type_t`) + * The default value is `VEHICLE_TURN_TYPE_NONE`, which is a no-op (no turn executed). + * @param trigger Enum value specifying when to execute the turn. (see `anki_vehicle_turn_trigger_t`) + * The only supported value is currently `VEHICLE_TURN_TRIGGER_IMMEDIATE`, + * which causes the turn to be executed immediately. + * + * @return size of bytes written to msg + */ +uint8_t anki_vehicle_msg_turn(anki_vehicle_msg_t *msg, + anki_vehicle_turn_type_t type, + anki_vehicle_turn_trigger_t trigger); + +/** + * Create a message to request a 180 degree turn. + * + * @param msg A pointer to the vehicle message struct to be written. + * + * @return size of bytes written to msg + */ +uint8_t anki_vehicle_msg_turn_180(anki_vehicle_msg_t *msg); + + +/** + * Create a message to set vehicle config parameters + * + * Specify parameters that modify scan-parsing or change the way that track codes are + * iterpreted. + * + * This message is experimental and may change in the future. + * + * @param msg A pointer to the vehicle message struct to be written. + * @param super_code_parse_mask Mask byte specifying super codes that should be parsed. + * @param track_material Enum value specifying the material on which codes are printed. + * + * @return size of bytes written to msg + */ +uint8_t anki_vehicle_msg_set_config_params(anki_vehicle_msg_t* msg, + uint8_t super_code_parse_mask, + anki_track_material_t track_material); + +ANKI_END_DECL + +#endif diff --git a/drive-sdk/src/uuid.c b/drive-sdk/src/uuid.c new file mode 100644 index 0000000..b3ee649 --- /dev/null +++ b/drive-sdk/src/uuid.c @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2014 Anki, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include "uuid.h" + +int uuid128_cmp(const uuid128_t *a, const uuid128_t *b) +{ + return memcmp(a, b, sizeof(uuid128_t)); +} diff --git a/drive-sdk/src/uuid.h b/drive-sdk/src/uuid.h new file mode 100644 index 0000000..e93ca84 --- /dev/null +++ b/drive-sdk/src/uuid.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2014 Anki, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_uuid_h +#define INCLUDE_uuid_h + +#include + +#include "common.h" + +ANKI_BEGIN_DECL + +struct uuid128 { + uint8_t byte0; + uint8_t byte1; + uint8_t byte2; + uint8_t byte3; + uint8_t byte4; + uint8_t byte5; + uint8_t byte6; + uint8_t byte7; + uint8_t byte8; + uint8_t byte9; + uint8_t byte10; + uint8_t byte11; + uint8_t byte12; + uint8_t byte13; + uint8_t byte14; + uint8_t byte15; +}; +typedef struct uuid128 uuid128_t; + +int uuid128_cmp(const uuid128_t *a, const uuid128_t *b); + +ANKI_END_DECL + +#endif diff --git a/drive-sdk/src/vehicle_gatt_profile.h b/drive-sdk/src/vehicle_gatt_profile.h new file mode 100644 index 0000000..6ed0f25 --- /dev/null +++ b/drive-sdk/src/vehicle_gatt_profile.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2014 Anki, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_vehicle_gatt_profile_h +#define INCLUDE_vehicle_gatt_profile_h + +#define ANKI_STR_SERVICE_UUID "BE15BEEF-6186-407E-8381-0BD89C4D8DF4" +#define ANKI_SERVICE_UUID { 0xbe, 0x15, 0xbe, 0xef, 0x61, 0x68, 0x40, 0x7e, 0x83, 0x81, 0x0b, 0xd8, 0x9c, 0x4d, 0x8d, 0xf4 } +#define ANKI_SERVICE_UUID_LE { 0xf4, 0x8d, 0x4d, 0x9c, 0xd8, 0x0b, 0x81, 0x83, 0x7e, 0x40, 0x86, 0x61, 0xef, 0xbe, 0x15, 0xbe } + +#define ANKI_STR_CHR_READ_UUID "BE15BEE0-6186-407E-8381-0BD89C4D8DF4" +#define ANKI_CHR_READ_UUID { 0xbe, 0x15, 0xbe, 0xe0, 0x61, 0x68, 0x40, 0x7e, 0x83, 0x81, 0x0b, 0xd8, 0x9c, 0x4d, 0x8d, 0xf4 } + +#define ANKI_STR_CHR_WRITE_UUID "BE15BEE1-6186-407E-8381-0BD89C4D8DF4" +#define ANKI_CHR_WRITE_UUID { 0xbe, 0x15, 0xbe, 0xe1, 0x61, 0x68, 0x40, 0x7e, 0x83, 0x81, 0x0b, 0xd8, 0x9c, 0x4d, 0x8d, 0xf4 } + +#endif diff --git a/drive-sdk/test/CMakeLists.txt b/drive-sdk/test/CMakeLists.txt new file mode 100644 index 0000000..d1e1534 --- /dev/null +++ b/drive-sdk/test/CMakeLists.txt @@ -0,0 +1,18 @@ +set(CMAKE_INCLUDE_CURRENT_DIR ON) + +include_directories(${drivekit_SOURCE_DIR}/src + ) + +# Add sources +set(test_SOURCES greatest.h + anki_greatest.h + test_suite.c + test_ble_advertisement.c + test_vehicle_advertisement.c + test_protocol.c +) + +add_executable(Test ${test_SOURCES}) +target_link_libraries(Test + ankidrive + ) diff --git a/drive-sdk/test/adv_data.h b/drive-sdk/test/adv_data.h new file mode 100644 index 0000000..c5581be --- /dev/null +++ b/drive-sdk/test/adv_data.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2014 Anki, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ADV_DATA_H +#define ADV_DATA_H + +// scan data from Anki Drive vehicles +static uint8_t adv0_scan[] = { + 0x02, 0x01, 0x06, + 0x11, 0x07, 0xF4, 0x8D, 0x4D, 0x9C, 0xD8, 0x0B, 0x81, 0x83, 0x7E, 0x40, 0x86, 0x61, 0xEF, 0xBE, 0x15, 0xBE, + 0x09, 0xFF, 0xBE, 0xEF, 0x00, 0x01, 0x00, 0xE0, 0x0A, 0xA3 +}; +static uint8_t adv1_scan[] = { + 0x13, 0x09, 0x50, 0x20, 0x21, 0x01, 0x20, 0x20, 0x5A, 0x39, 0x41, 0x41, 0x33, 0x20, 0x54, 0x4F, 0x4D, 0x4D, 0x59, 0x00, + 0x02, 0x0A, 0x00 +}; + +// scan data from Ti SensorTag +static uint8_t st0_scan[] = { 0x02, 0x01, 0x05 }; +static uint8_t st1_scan[] = { + 0x0A, 0x09, 0x53, 0x65, 0x6E, 0x73, 0x6F, 0x72, 0x54, 0x61, 0x67, + 0x05, 0x12, 0x50, 0x00, 0x20, 0x03, + 0x02, 0x0A, 0x00 +}; + +#endif // ADV_DATA_H diff --git a/drive-sdk/test/anki_greatest.h b/drive-sdk/test/anki_greatest.h new file mode 100644 index 0000000..2d39a2b --- /dev/null +++ b/drive-sdk/test/anki_greatest.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2014 Anki, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INCLUDE_anki_greatest_h__ +#define INCLUDE_anki_greatest_h__ + +#define ANKI_GREATEST_HEX_DUMP(buffer, len) \ + do { \ + const uint8_t *b = (const uint8_t *)buffer; \ + int i; \ + for (i = 0; i < (len); ++i) { \ + fprintf(GREATEST_STDOUT, "%02x ", b[i]); \ + } \ + } while(0) + +#define ANKI_GREATEST_ASSERT_BYTES_EQm(MSG, EXP, GOT, LEN) \ + do { \ + const void *exp_s = (const void *)(EXP); \ + const void *got_s = (const void *)(GOT); \ + const size_t len_s = (const size_t)(LEN); \ + greatest_info.msg = MSG; \ + greatest_info.fail_file = __FILE__; \ + greatest_info.fail_line = __LINE__; \ + if (0 != memcmp(exp_s, got_s, len_s)) { \ + fprintf(GREATEST_STDOUT, "Expected:\n####\n"); \ + ANKI_GREATEST_HEX_DUMP(exp_s, len_s); \ + fprintf(GREATEST_STDOUT, "\n####\n"); \ + fprintf(GREATEST_STDOUT, "Got:\n####\n"); \ + ANKI_GREATEST_HEX_DUMP(got_s, len_s); \ + fprintf(GREATEST_STDOUT, "\n####\n"); \ + return -1; \ + } \ + greatest_info.msg = NULL; \ + } while (0) + +#define ANKI_GREATEST_ASSERT_BYTES_EQ(EXP, GOT, LEN) ANKI_GREATEST_ASSERT_BYTES_EQm(#EXP " != " #GOT, EXP, GOT, LEN) + +#define ASSERT_BYTES_EQm(MSG, EXP, GOT, LEN) ANKI_GREATEST_ASSERT_BYTES_EQm(MSG, EXP, GOT, LEN) +#define ASSERT_BYTES_EQ(EXP, GOT, LEN) ANKI_GREATEST_ASSERT_BYTES_EQ(EXP, GOT, LEN) + +#endif diff --git a/drive-sdk/test/greatest.h b/drive-sdk/test/greatest.h new file mode 100644 index 0000000..a92c642 --- /dev/null +++ b/drive-sdk/test/greatest.h @@ -0,0 +1,591 @@ +/* + * Copyright (c) 2011 Scott Vokes + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#ifndef GREATEST_H +#define GREATEST_H + +#define GREATEST_VERSION_MAJOR 0 +#define GREATEST_VERSION_MINOR 9 +#define GREATEST_VERSION_PATCH 3 + +/* A unit testing system for C, contained in 1 file. + * It doesn't use dynamic allocation or depend on anything + * beyond ANSI C89. */ + + +/********************************************************************* + * Minimal test runner template + *********************************************************************/ +#if 0 + +#include "greatest.h" + +TEST foo_should_foo() { + PASS(); +} + +static void setup_cb(void *data) { + printf("setup callback for each test case\n"); +} + +static void teardown_cb(void *data) { + printf("teardown callback for each test case\n"); +} + +SUITE(suite) { + /* Optional setup/teardown callbacks which will be run before/after + * every test case in the suite. + * Cleared when the suite finishes. */ + SET_SETUP(setup_cb, voidp_to_callback_data); + SET_TEARDOWN(teardown_cb, voidp_to_callback_data); + + RUN_TEST(foo_should_foo); +} + +/* Add all the definitions that need to be in the test runner's main file. */ +GREATEST_MAIN_DEFS(); + +int main(int argc, char **argv) { + GREATEST_MAIN_BEGIN(); /* command-line arguments, initialization. */ + RUN_SUITE(suite); + GREATEST_MAIN_END(); /* display results */ +} + +#endif +/*********************************************************************/ + + +#include +#include +#include +#include + + +/*********** + * Options * + ***********/ + +/* Default column width for non-verbose output. */ +#ifndef GREATEST_DEFAULT_WIDTH +#define GREATEST_DEFAULT_WIDTH 72 +#endif + +/* FILE *, for test logging. */ +#ifndef GREATEST_STDOUT +#define GREATEST_STDOUT stdout +#endif + +/* Remove GREATEST_ prefix from most commonly used symbols? */ +#ifndef GREATEST_USE_ABBREVS +#define GREATEST_USE_ABBREVS 1 +#endif + + +/********* + * Types * + *********/ + +/* Info for the current running suite. */ +typedef struct greatest_suite_info { + unsigned int tests_run; + unsigned int passed; + unsigned int failed; + unsigned int skipped; + + /* timers, pre/post running suite and individual tests */ + clock_t pre_suite; + clock_t post_suite; + clock_t pre_test; + clock_t post_test; +} greatest_suite_info; + +/* Type for a suite function. */ +typedef void (greatest_suite_cb)(void); + +/* Types for setup/teardown callbacks. If non-NULL, these will be run + * and passed the pointer to their additional data. */ +typedef void (greatest_setup_cb)(void *udata); +typedef void (greatest_teardown_cb)(void *udata); + +typedef enum { + GREATEST_FLAG_VERBOSE = 0x01, + GREATEST_FLAG_FIRST_FAIL = 0x02, + GREATEST_FLAG_LIST_ONLY = 0x04 +} GREATEST_FLAG; + +typedef struct greatest_run_info { + unsigned int flags; + unsigned int tests_run; /* total test count */ + + /* Overall pass/fail/skip counts. */ + unsigned int passed; + unsigned int failed; + unsigned int skipped; + + /* currently running test suite */ + greatest_suite_info suite; + + /* info to print about the most recent failure */ + const char *fail_file; + unsigned int fail_line; + const char *msg; + + /* current setup/teardown hooks and userdata */ + greatest_setup_cb *setup; + void *setup_udata; + greatest_teardown_cb *teardown; + void *teardown_udata; + + /* formatting info for ".....s...F"-style output */ + unsigned int col; + unsigned int width; + + /* only run a specific suite or test */ + char *suite_filter; + char *test_filter; + + /* overall timers */ + clock_t begin; + clock_t end; +} greatest_run_info; + +/* Global var for the current testing context. + * Initialized by GREATEST_MAIN_DEFS(). */ +extern greatest_run_info greatest_info; + + +/********************** + * Exported functions * + **********************/ + +void greatest_do_pass(const char *name); +void greatest_do_fail(const char *name); +void greatest_do_skip(const char *name); +int greatest_pre_test(const char *name); +void greatest_post_test(const char *name, int res); +void greatest_usage(const char *name); +void GREATEST_SET_SETUP_CB(greatest_setup_cb *cb, void *udata); +void GREATEST_SET_TEARDOWN_CB(greatest_teardown_cb *cb, void *udata); + + +/********** + * Macros * + **********/ + +/* Define a suite. */ +#define GREATEST_SUITE(NAME) void NAME(void) + +/* Start defining a test function. + * The arguments are not included, to allow parametric testing. */ +#define GREATEST_TEST static int + +/* Run a suite. */ +#define GREATEST_RUN_SUITE(S_NAME) greatest_run_suite(S_NAME, #S_NAME) + +/* Run a test in the current suite. */ +#define GREATEST_RUN_TEST(TEST) \ + do { \ + if (greatest_pre_test(#TEST) == 1) { \ + int res = TEST(); \ + greatest_post_test(#TEST, res); \ + } else if (GREATEST_LIST_ONLY()) { \ + fprintf(GREATEST_STDOUT, " %s\n", #TEST); \ + } \ + } while (0) + +/* Run a test in the current suite with one void* argument, + * which can be a pointer to a struct with multiple arguments. */ +#define GREATEST_RUN_TEST1(TEST, ENV) \ + do { \ + if (greatest_pre_test(#TEST) == 1) { \ + int res = TEST(ENV); \ + greatest_post_test(#TEST, res); \ + } else if (GREATEST_LIST_ONLY()) { \ + fprintf(GREATEST_STDOUT, " %s\n", #TEST); \ + } \ + } while (0) + +/* If __VA_ARGS__ (C99) is supported, allow parametric testing + * without needing to manually manage the argument struct. */ +#if __STDC_VERSION__ >= 19901L +#define GREATEST_RUN_TESTp(TEST, ...) \ + do { \ + if (greatest_pre_test(#TEST) == 1) { \ + int res = TEST(__VA_ARGS__); \ + greatest_post_test(#TEST, res); \ + } else if (GREATEST_LIST_ONLY()) { \ + fprintf(GREATEST_STDOUT, " %s\n", #TEST); \ + } \ + } while (0) +#endif + + +/* Check if the test runner is in verbose mode. */ +#define GREATEST_IS_VERBOSE() (greatest_info.flags & GREATEST_FLAG_VERBOSE) +#define GREATEST_LIST_ONLY() (greatest_info.flags & GREATEST_FLAG_LIST_ONLY) +#define GREATEST_FIRST_FAIL() (greatest_info.flags & GREATEST_FLAG_FIRST_FAIL) +#define GREATEST_FAILURE_ABORT() (greatest_info.suite.failed > 0 && GREATEST_FIRST_FAIL()) + +/* Message-less forms. */ +#define GREATEST_PASS() GREATEST_PASSm(NULL) +#define GREATEST_FAIL() GREATEST_FAILm(NULL) +#define GREATEST_SKIP() GREATEST_SKIPm(NULL) +#define GREATEST_ASSERT(COND) GREATEST_ASSERTm(#COND, COND) +#define GREATEST_ASSERT_FALSE(COND) GREATEST_ASSERT_FALSEm(#COND, COND) +#define GREATEST_ASSERT_EQ(EXP, GOT) GREATEST_ASSERT_EQm(#EXP " != " #GOT, EXP, GOT) +#define GREATEST_ASSERT_STR_EQ(EXP, GOT) GREATEST_ASSERT_STR_EQm(#EXP " != " #GOT, EXP, GOT) + +/* The following forms take an additional message argument first, + * to be displayed by the test runner. */ + +/* Fail if a condition is not true, with message. */ +#define GREATEST_ASSERTm(MSG, COND) \ + do { \ + greatest_info.msg = MSG; \ + greatest_info.fail_file = __FILE__; \ + greatest_info.fail_line = __LINE__; \ + if (!(COND)) return -1; \ + greatest_info.msg = NULL; \ + } while (0) + +#define GREATEST_ASSERT_FALSEm(MSG, COND) \ + do { \ + greatest_info.msg = MSG; \ + greatest_info.fail_file = __FILE__; \ + greatest_info.fail_line = __LINE__; \ + if ((COND)) return -1; \ + greatest_info.msg = NULL; \ + } while (0) + +#define GREATEST_ASSERT_EQm(MSG, EXP, GOT) \ + do { \ + greatest_info.msg = MSG; \ + greatest_info.fail_file = __FILE__; \ + greatest_info.fail_line = __LINE__; \ + if ((EXP) != (GOT)) return -1; \ + greatest_info.msg = NULL; \ + } while (0) + +#define GREATEST_ASSERT_STR_EQm(MSG, EXP, GOT) \ + do { \ + const char *exp_s = (EXP); \ + const char *got_s = (GOT); \ + greatest_info.msg = MSG; \ + greatest_info.fail_file = __FILE__; \ + greatest_info.fail_line = __LINE__; \ + if (0 != strcmp(exp_s, got_s)) { \ + fprintf(GREATEST_STDOUT, \ + "Expected:\n####\n%s\n####\n", exp_s); \ + fprintf(GREATEST_STDOUT, \ + "Got:\n####\n%s\n####\n", got_s); \ + return -1; \ + } \ + greatest_info.msg = NULL; \ + } while (0) + +#define GREATEST_PASSm(MSG) \ + do { \ + greatest_info.msg = MSG; \ + return 0; \ + } while (0) + +#define GREATEST_FAILm(MSG) \ + do { \ + greatest_info.fail_file = __FILE__; \ + greatest_info.fail_line = __LINE__; \ + greatest_info.msg = MSG; \ + return -1; \ + } while (0) + +#define GREATEST_SKIPm(MSG) \ + do { \ + greatest_info.msg = MSG; \ + return 1; \ + } while (0) + +#define GREATEST_SET_TIME(NAME) \ + NAME = clock(); \ + if (NAME == (clock_t) -1) { \ + fprintf(GREATEST_STDOUT, \ + "clock error: %s\n", #NAME); \ + exit(EXIT_FAILURE); \ + } + +#define GREATEST_CLOCK_DIFF(C1, C2) \ + fprintf(GREATEST_STDOUT, " (%lu ticks, %.3f sec)", \ + (long unsigned int) (C2) - (C1), \ + (double)((C2) - (C1)) / (1.0 * (double)CLOCKS_PER_SEC)) \ + +/* Include several function definitions in the main test file. */ +#define GREATEST_MAIN_DEFS() \ + \ +/* Is FILTER a subset of NAME? */ \ +static int greatest_name_match(const char *name, \ + const char *filter) { \ + size_t offset = 0; \ + size_t filter_len = strlen(filter); \ + while (name[offset] != '\0') { \ + if (name[offset] == filter[0]) { \ + if (0 == strncmp(&name[offset], filter, filter_len)) { \ + return 1; \ + } \ + } \ + offset++; \ + } \ + \ + return 0; \ +} \ + \ +int greatest_pre_test(const char *name) { \ + if (!GREATEST_LIST_ONLY() \ + && (!GREATEST_FIRST_FAIL() || greatest_info.suite.failed == 0) \ + && (greatest_info.test_filter == NULL || \ + greatest_name_match(name, greatest_info.test_filter))) { \ + GREATEST_SET_TIME(greatest_info.suite.pre_test); \ + if (greatest_info.setup) { \ + greatest_info.setup(greatest_info.setup_udata); \ + } \ + return 1; /* test should be run */ \ + } else { \ + return 0; /* skipped */ \ + } \ +} \ + \ +void greatest_post_test(const char *name, int res) { \ + GREATEST_SET_TIME(greatest_info.suite.post_test); \ + if (greatest_info.teardown) { \ + void *udata = greatest_info.teardown_udata; \ + greatest_info.teardown(udata); \ + } \ + \ + if (res < 0) { \ + greatest_do_fail(name); \ + } else if (res > 0) { \ + greatest_do_skip(name); \ + } else if (res == 0) { \ + greatest_do_pass(name); \ + } \ + greatest_info.suite.tests_run++; \ + greatest_info.col++; \ + if (GREATEST_IS_VERBOSE()) { \ + GREATEST_CLOCK_DIFF(greatest_info.suite.pre_test, \ + greatest_info.suite.post_test); \ + fprintf(GREATEST_STDOUT, "\n"); \ + } else if (greatest_info.col % greatest_info.width == 0) { \ + fprintf(GREATEST_STDOUT, "\n"); \ + greatest_info.col = 0; \ + } \ + if (GREATEST_STDOUT == stdout) fflush(stdout); \ +} \ + \ +static void greatest_run_suite(greatest_suite_cb *suite_cb, \ + const char *suite_name) { \ + if (greatest_info.suite_filter && \ + !greatest_name_match(suite_name, greatest_info.suite_filter)) \ + return; \ + if (GREATEST_FIRST_FAIL() && greatest_info.failed > 0) return; \ + greatest_info.suite.tests_run = 0; \ + greatest_info.suite.failed = 0; \ + greatest_info.suite.passed = 0; \ + greatest_info.suite.skipped = 0; \ + greatest_info.suite.pre_suite = 0; \ + greatest_info.suite.post_suite = 0; \ + greatest_info.suite.pre_test = 0; \ + greatest_info.suite.post_test = 0; \ + greatest_info.col = 0; \ + fprintf(GREATEST_STDOUT, "\n* Suite %s:\n", suite_name); \ + GREATEST_SET_TIME(greatest_info.suite.pre_suite); \ + suite_cb(); \ + GREATEST_SET_TIME(greatest_info.suite.post_suite); \ + if (greatest_info.suite.tests_run > 0) { \ + fprintf(GREATEST_STDOUT, \ + "\n%u tests - %u pass, %u fail, %u skipped", \ + greatest_info.suite.tests_run, \ + greatest_info.suite.passed, \ + greatest_info.suite.failed, \ + greatest_info.suite.skipped); \ + GREATEST_CLOCK_DIFF(greatest_info.suite.pre_suite, \ + greatest_info.suite.post_suite); \ + fprintf(GREATEST_STDOUT, "\n"); \ + } \ + greatest_info.setup = NULL; \ + greatest_info.setup_udata = NULL; \ + greatest_info.teardown = NULL; \ + greatest_info.teardown_udata = NULL; \ + greatest_info.passed += greatest_info.suite.passed; \ + greatest_info.failed += greatest_info.suite.failed; \ + greatest_info.skipped += greatest_info.suite.skipped; \ + greatest_info.tests_run += greatest_info.suite.tests_run; \ +} \ + \ +void greatest_do_pass(const char *name) { \ + if (GREATEST_IS_VERBOSE()) { \ + fprintf(GREATEST_STDOUT, "PASS %s: %s", \ + name, greatest_info.msg ? greatest_info.msg : ""); \ + } else { \ + fprintf(GREATEST_STDOUT, "."); \ + } \ + greatest_info.suite.passed++; \ +} \ + \ +void greatest_do_fail(const char *name) { \ + if (GREATEST_IS_VERBOSE()) { \ + fprintf(GREATEST_STDOUT, \ + "FAIL %s: %s (%s:%u)", \ + name, greatest_info.msg ? greatest_info.msg : "", \ + greatest_info.fail_file, greatest_info.fail_line); \ + } else { \ + fprintf(GREATEST_STDOUT, "F"); \ + /* add linebreak if in line of '.'s */ \ + if (greatest_info.col % greatest_info.width != 0) \ + fprintf(GREATEST_STDOUT, "\n"); \ + greatest_info.col = 0; \ + fprintf(GREATEST_STDOUT, "FAIL %s: %s (%s:%u)\n", \ + name, \ + greatest_info.msg ? greatest_info.msg : "", \ + greatest_info.fail_file, greatest_info.fail_line); \ + } \ + greatest_info.suite.failed++; \ +} \ + \ +void greatest_do_skip(const char *name) { \ + if (GREATEST_IS_VERBOSE()) { \ + fprintf(GREATEST_STDOUT, "SKIP %s: %s", \ + name, \ + greatest_info.msg ? \ + greatest_info.msg : "" ); \ + } else { \ + fprintf(GREATEST_STDOUT, "s"); \ + } \ + greatest_info.suite.skipped++; \ +} \ + \ +void greatest_usage(const char *name) { \ + fprintf(GREATEST_STDOUT, \ + "Usage: %s [-hlfv] [-s SUITE] [-t TEST]\n" \ + " -h print this Help\n" \ + " -l List suites and their tests, then exit\n" \ + " -f Stop runner after first failure\n" \ + " -v Verbose output\n" \ + " -s SUITE only run suite named SUITE\n" \ + " -t TEST only run test named TEST\n", \ + name); \ +} \ + \ +void GREATEST_SET_SETUP_CB(greatest_setup_cb *cb, void *udata) { \ + greatest_info.setup = cb; \ + greatest_info.setup_udata = udata; \ +} \ + \ +void GREATEST_SET_TEARDOWN_CB(greatest_teardown_cb *cb, \ + void *udata) { \ + greatest_info.teardown = cb; \ + greatest_info.teardown_udata = udata; \ +} \ + \ +greatest_run_info greatest_info + +/* Handle command-line arguments, etc. */ +#define GREATEST_MAIN_BEGIN() \ + do { \ + int i = 0; \ + memset(&greatest_info, 0, sizeof(greatest_info)); \ + if (greatest_info.width == 0) { \ + greatest_info.width = GREATEST_DEFAULT_WIDTH; \ + } \ + for (i = 1; i < argc; i++) { \ + if (0 == strcmp("-t", argv[i])) { \ + if (argc <= i + 1) { \ + greatest_usage(argv[0]); \ + exit(EXIT_FAILURE); \ + } \ + greatest_info.test_filter = argv[i+1]; \ + i++; \ + } else if (0 == strcmp("-s", argv[i])) { \ + if (argc <= i + 1) { \ + greatest_usage(argv[0]); \ + exit(EXIT_FAILURE); \ + } \ + greatest_info.suite_filter = argv[i+1]; \ + i++; \ + } else if (0 == strcmp("-f", argv[i])) { \ + greatest_info.flags |= GREATEST_FLAG_FIRST_FAIL; \ + } else if (0 == strcmp("-v", argv[i])) { \ + greatest_info.flags |= GREATEST_FLAG_VERBOSE; \ + } else if (0 == strcmp("-l", argv[i])) { \ + greatest_info.flags |= GREATEST_FLAG_LIST_ONLY; \ + } else if (0 == strcmp("-h", argv[i])) { \ + greatest_usage(argv[0]); \ + exit(EXIT_SUCCESS); \ + } else { \ + fprintf(GREATEST_STDOUT, \ + "Unknown argument '%s'\n", argv[i]); \ + greatest_usage(argv[0]); \ + exit(EXIT_FAILURE); \ + } \ + } \ + } while (0); \ + GREATEST_SET_TIME(greatest_info.begin) + +#define GREATEST_MAIN_END() \ + do { \ + if (!GREATEST_LIST_ONLY()) { \ + GREATEST_SET_TIME(greatest_info.end); \ + fprintf(GREATEST_STDOUT, \ + "\nTotal: %u tests", greatest_info.tests_run); \ + GREATEST_CLOCK_DIFF(greatest_info.begin, \ + greatest_info.end); \ + fprintf(GREATEST_STDOUT, "\n"); \ + fprintf(GREATEST_STDOUT, \ + "Pass: %u, fail: %u, skip: %u.\n", \ + greatest_info.passed, \ + greatest_info.failed, greatest_info.skipped); \ + } \ + return (greatest_info.failed > 0 \ + ? EXIT_FAILURE : EXIT_SUCCESS); \ + } while (0) + +/* Make abbreviations without the GREATEST_ prefix for the + * most commonly used symbols. */ +#if GREATEST_USE_ABBREVS +#define TEST GREATEST_TEST +#define SUITE GREATEST_SUITE +#define RUN_TEST GREATEST_RUN_TEST +#define RUN_TEST1 GREATEST_RUN_TEST1 +#define RUN_SUITE GREATEST_RUN_SUITE +#define ASSERT GREATEST_ASSERT +#define ASSERTm GREATEST_ASSERTm +#define ASSERT_FALSE GREATEST_ASSERT_FALSE +#define ASSERT_EQ GREATEST_ASSERT_EQ +#define ASSERT_STR_EQ GREATEST_ASSERT_STR_EQ +#define ASSERT_FALSEm GREATEST_ASSERT_FALSEm +#define ASSERT_EQm GREATEST_ASSERT_EQm +#define ASSERT_STR_EQm GREATEST_ASSERT_STR_EQm +#define PASS GREATEST_PASS +#define FAIL GREATEST_FAIL +#define SKIP GREATEST_SKIP +#define PASSm GREATEST_PASSm +#define FAILm GREATEST_FAILm +#define SKIPm GREATEST_SKIPm +#define SET_SETUP GREATEST_SET_SETUP_CB +#define SET_TEARDOWN GREATEST_SET_TEARDOWN_CB + +#if __STDC_VERSION__ >= 19901L +#endif /* C99 */ +#define RUN_TESTp GREATEST_RUN_TESTp +#endif /* USE_ABBREVS */ + +#endif diff --git a/drive-sdk/test/test_ble_advertisement.c b/drive-sdk/test/test_ble_advertisement.c new file mode 100644 index 0000000..b9e084e --- /dev/null +++ b/drive-sdk/test/test_ble_advertisement.c @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2014 Anki, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include "greatest.h" + +#include "eir.h" +#include "adv_data.h" + +SUITE(ble_advertisement); + +TEST ble_adv_parse_scan_record_count(void) { + size_t count = 0; + int err = 0; + + err = ble_adv_parse_scan(adv0_scan, sizeof(adv0_scan), &count, NULL); + ASSERT_EQ(err, 0); + ASSERT_EQ(count, 3); + + err = ble_adv_parse_scan(adv1_scan, sizeof(adv1_scan), &count, NULL); + ASSERT_EQ(err, 0); + ASSERT_EQ(count, 2); + + err = ble_adv_parse_scan(st0_scan, sizeof(st0_scan), &count, NULL); + ASSERT_EQ(err, 0); + ASSERT_EQ(count, 1); + + err = ble_adv_parse_scan(st1_scan, sizeof(st1_scan), &count, NULL); + ASSERT_EQ(err, 0); + ASSERT_EQ(count, 3); + + PASS(); +} + +TEST ble_adv_parse_scan_records(void) { + size_t count = 0; + int err = 0; + + err = ble_adv_parse_scan(adv0_scan, sizeof(adv0_scan), &count, NULL); + ASSERT_EQ(err, 0); + ASSERT_EQ(count, 3); + + ble_adv_record_t records[3]; + memset(records, 0, sizeof(ble_adv_record_t) * 3); + err = ble_adv_parse_scan(adv0_scan, sizeof(adv0_scan), &count, records); + + ble_adv_record_type_t expected_types[3] = { ADV_TYPE_FLAGS, ADV_TYPE_UUID_128, ADV_TYPE_MANUFACTURER_DATA }; + + int i = 0; + for (i = 0; i < count; ++i) { + ASSERT_EQ(records[i].type, expected_types[i]); + } + + PASS(); +} + +GREATEST_SUITE(ble_advertisement) { + RUN_TEST(ble_adv_parse_scan_record_count); + RUN_TEST(ble_adv_parse_scan_records); +} diff --git a/drive-sdk/test/test_protocol.c b/drive-sdk/test/test_protocol.c new file mode 100644 index 0000000..1bb2768 --- /dev/null +++ b/drive-sdk/test/test_protocol.c @@ -0,0 +1,243 @@ +/* + * Copyright (c) 2014 Anki, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +#include "greatest.h" +#include "anki_greatest.h" + +#include "protocol.h" +#include "anki_util.h" + +SUITE(vehicle_protocol); + +TEST test_struct_attribute_packed(void) { + ASSERT_EQ(sizeof(anki_vehicle_msg_sdk_mode_t), ANKI_VEHICLE_MSG_SDK_MODE_SIZE+ANKI_VEHICLE_MSG_BASE_SIZE); + PASS(); +} + +TEST test_set_sdk_mode(void) { + anki_vehicle_msg_t msg; + uint8_t size = anki_vehicle_msg_set_sdk_mode(&msg, 1, ANKI_VEHICLE_SDK_OPTION_OVERRIDE_LOCALIZATION); + ASSERT_EQ(size, 4); + + uint8_t expect[4] = { 0x03, 0x90, 0x01, 0x01 }; + ASSERT_BYTES_EQ(&msg, expect, 4); + PASS(); +} + +TEST test_set_speed(void) { + anki_vehicle_msg_t msg; + uint8_t size = anki_vehicle_msg_set_speed(&msg, 1000, 25000); + ASSERT_EQ(size, sizeof(anki_vehicle_msg_set_speed_t)); + + uint8_t expect[7] = { 0x06, 0x24, 0xe8, 0x03, 0xa8, 0x61, 0x00 }; + ASSERT_BYTES_EQ(&msg, expect, 7); + PASS(); +} + +TEST test_set_offset_from_center(void) { + anki_vehicle_msg_t msg; + memset(&msg, 0, sizeof(anki_vehicle_msg_t)); + uint8_t size = anki_vehicle_msg_set_offset_from_road_center(&msg, 0.0); + + ASSERT_EQ(size, sizeof(anki_vehicle_msg_set_offset_from_road_center_t)); + + uint8_t expect[6] = { 0x5, 0x2c, 0, 0, 0, 0 }; + ASSERT_BYTES_EQ(&msg, expect, 6); + PASS(); +} + +TEST test_change_lane(void) { + anki_vehicle_msg_t msg; + memset(&msg, 0, sizeof(anki_vehicle_msg_change_lane_t)); + uint8_t size = anki_vehicle_msg_change_lane(&msg, 1000, 10000, 20.f); + ASSERT_EQ(size, sizeof(anki_vehicle_msg_change_lane_t)); + + uint8_t expect[12] = { 0x0b, 0x25, 0xe8, 0x03, 0x10, 0x27, 0x00, 0x00, 0xa0, 0x41, 0, 0 }; + ASSERT_BYTES_EQ(&msg, expect, 12); + PASS(); +} + +TEST test_light_config(void) { + anki_vehicle_light_config_t config; + memset(&config, 0, sizeof(anki_vehicle_light_config_t)); + //uint8_t size = anki_vehicle_light_config(&config, LIGHT_RED, EFFECT_THROB, 0, 20, 5); + anki_vehicle_light_config(&config, LIGHT_RED, EFFECT_THROB, 0, 10, 10); + ASSERT(config.cycles_per_10_sec > 0); + + anki_vehicle_msg_lights_pattern_t msg; + memset(&msg, 0, sizeof(anki_vehicle_msg_lights_pattern_t)); + + const uint8_t size = anki_vehicle_msg_lights_pattern_append(&msg, &config); + ASSERT_EQ(size, sizeof(config)); + + ASSERT_EQ(msg.msg_id, ANKI_VEHICLE_MSG_C2V_LIGHTS_PATTERN); + ASSERT_EQ(msg.size, ANKI_VEHICLE_MSG_C2V_LIGHTS_PATTERN_SIZE); + ASSERT_EQ(msg.channel_count, 1); + ASSERT_BYTES_EQ(&(msg.channel_config[0]), &config, sizeof(config)); + + PASS(); +} + +// Regression test against a STEADY LIGHT_BLUE, max intensity +TEST test_lights_steady_blue(void) { + anki_vehicle_msg_lights_pattern_t msg; + memset(&msg, 0, sizeof(anki_vehicle_msg_lights_pattern_t)); + + uint8_t intensity = ANKI_VEHICLE_MAX_LIGHT_INTENSITY; + uint8_t cycles_per_min = 0; + + anki_vehicle_light_config_t config; + { + memset(&config, 0, sizeof(anki_vehicle_light_config_t)); + anki_vehicle_light_config(&config, LIGHT_RED, EFFECT_STEADY, 0, 0, cycles_per_min); + uint8_t append_size = anki_vehicle_msg_lights_pattern_append(&msg, &config); + ASSERT_EQ(append_size, sizeof(config)); + ASSERT_EQ(msg.channel_count, 1); + } + { + memset(&config, 0, sizeof(anki_vehicle_light_config_t)); + anki_vehicle_light_config(&config, LIGHT_GREEN, EFFECT_STEADY, 0, 0, cycles_per_min); + uint8_t append_size = anki_vehicle_msg_lights_pattern_append(&msg, &config); + ASSERT_EQ(append_size, sizeof(config)); + ASSERT_EQ(msg.channel_count, 2); + } + { + memset(&config, 0, sizeof(anki_vehicle_light_config_t)); + anki_vehicle_light_config(&config, LIGHT_BLUE, EFFECT_STEADY, intensity, intensity, cycles_per_min); + uint8_t append_size = anki_vehicle_msg_lights_pattern_append(&msg, &config); + ASSERT_EQ(append_size, sizeof(config)); + ASSERT_EQ(msg.channel_count, 3); + } + + uint8_t expected[18] = { + 0x11, 0x33, + 0x03, + 0x00, 0x00, 0x00, 0x00, 0x00, + 0x03, 0x00, 0x00, 0x00, 0x00, + 0x02, 0x00, 0x0e, 0x0e, 0x00 + }; + + ASSERT_BYTES_EQ(&msg, expected, sizeof(expected)); + PASS(); +} + +TEST test_turn_180(void) { + anki_vehicle_msg_t msg; + memset(&msg, 0, sizeof(anki_vehicle_msg_turn_t)); + + uint8_t size = anki_vehicle_msg_turn(&msg, VEHICLE_TURN_UTURN, VEHICLE_TURN_TRIGGER_IMMEDIATE); + ASSERT_EQ(size, sizeof(anki_vehicle_msg_turn_t)); + + uint8_t expect[4] = { ANKI_VEHICLE_MSG_C2V_TURN_SIZE, + ANKI_VEHICLE_MSG_C2V_TURN, + VEHICLE_TURN_UTURN, + VEHICLE_TURN_TRIGGER_IMMEDIATE }; + ASSERT_BYTES_EQ(&msg, expect, 4); + PASS(); +} + +TEST test_lights_pattern(void) { + anki_vehicle_msg_lights_pattern_t msg; + memset(&msg, 0, sizeof(anki_vehicle_msg_lights_pattern_t)); + + uint8_t intensity = ANKI_VEHICLE_MAX_LIGHT_INTENSITY; + uint8_t cycles_per_min = 6; + + anki_vehicle_light_config_t config; + { + memset(&config, 0, sizeof(anki_vehicle_light_config_t)); + anki_vehicle_light_config(&config, LIGHT_RED, EFFECT_THROB, 0, intensity, cycles_per_min); + uint8_t append_size = anki_vehicle_msg_lights_pattern_append(&msg, &config); + ASSERT_EQ(append_size, sizeof(config)); + ASSERT_EQ(msg.channel_count, 1); + } + { + memset(&config, 0, sizeof(anki_vehicle_light_config_t)); + anki_vehicle_light_config(&config, LIGHT_GREEN, EFFECT_THROB, 0, ANKI_VEHICLE_MAX_LIGHT_INTENSITY, cycles_per_min); + uint8_t append_size = anki_vehicle_msg_lights_pattern_append(&msg, &config); + ASSERT_EQ(append_size, sizeof(config)); + ASSERT_EQ(msg.channel_count, 2); + } + { + memset(&config, 0, sizeof(anki_vehicle_light_config_t)); + anki_vehicle_light_config(&config, LIGHT_BLUE, EFFECT_THROB, 0, ANKI_VEHICLE_MAX_LIGHT_INTENSITY, cycles_per_min); + uint8_t append_size = anki_vehicle_msg_lights_pattern_append(&msg, &config); + ASSERT_EQ(append_size, sizeof(config)); + ASSERT_EQ(msg.channel_count, 3); + } + + ASSERT_EQ(msg.msg_id, ANKI_VEHICLE_MSG_C2V_LIGHTS_PATTERN); + ASSERT_EQ(msg.size, ANKI_VEHICLE_MSG_C2V_LIGHTS_PATTERN_SIZE); + + ASSERT_EQ(msg.channel_config[0].channel, LIGHT_RED); + ASSERT_EQ(msg.channel_config[1].channel, LIGHT_GREEN); + ASSERT_EQ(msg.channel_config[2].channel, LIGHT_BLUE); + + PASS(); +} + +TEST test_disconnect(void) { + anki_vehicle_msg_t msg; + anki_vehicle_msg_disconnect(&msg); + + uint8_t expect[2] = { ANKI_VEHICLE_MSG_BASE_SIZE, ANKI_VEHICLE_MSG_C2V_DISCONNECT }; + ASSERT_BYTES_EQ(&msg, expect, 2); + + PASS(); +} + +TEST test_get_version(void) { + anki_vehicle_msg_t msg; + uint8_t size = anki_vehicle_msg_get_version(&msg); + + ASSERT_EQ(size, 2); + + uint8_t expect[2] = { ANKI_VEHICLE_MSG_BASE_SIZE, ANKI_VEHICLE_MSG_C2V_VERSION_REQUEST }; + ASSERT_BYTES_EQ(&msg, expect, sizeof(expect)); + + PASS(); +} + +TEST test_get_battery_level(void) { + anki_vehicle_msg_t msg; + uint8_t size = anki_vehicle_msg_get_battery_level(&msg); + + ASSERT_EQ(size, 2); + + uint8_t expect[2] = { ANKI_VEHICLE_MSG_BASE_SIZE, ANKI_VEHICLE_MSG_C2V_BATTERY_LEVEL_REQUEST }; + ASSERT_BYTES_EQ(&msg, expect, sizeof(expect)); + + PASS(); +} + +GREATEST_SUITE(vehicle_protocol) { + RUN_TEST(test_struct_attribute_packed); + RUN_TEST(test_set_sdk_mode); + RUN_TEST(test_set_speed); + RUN_TEST(test_set_offset_from_center); + RUN_TEST(test_change_lane); + RUN_TEST(test_light_config); + RUN_TEST(test_lights_pattern); + RUN_TEST(test_lights_steady_blue); + RUN_TEST(test_turn_180); + RUN_TEST(test_disconnect); + RUN_TEST(test_get_version); + RUN_TEST(test_get_battery_level); +} diff --git a/drive-sdk/test/test_suite.c b/drive-sdk/test/test_suite.c new file mode 100644 index 0000000..dd83bf5 --- /dev/null +++ b/drive-sdk/test/test_suite.c @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2014 Anki, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +#include "greatest.h" + +extern SUITE(ble_advertisement); +extern SUITE(vehicle_advertisement); +extern SUITE(vehicle_protocol); + +/* Add all the definitions that need to be in the test runner's main file. */ +GREATEST_MAIN_DEFS(); + +int main(int argc, char **argv) { + GREATEST_MAIN_BEGIN(); /* command-line arguments, initialization. */ + RUN_SUITE(ble_advertisement); + RUN_SUITE(vehicle_advertisement); + RUN_SUITE(vehicle_protocol); + GREATEST_MAIN_END(); /* display results */ +} diff --git a/drive-sdk/test/test_vehicle_advertisement.c b/drive-sdk/test/test_vehicle_advertisement.c new file mode 100644 index 0000000..c7ae364 --- /dev/null +++ b/drive-sdk/test/test_vehicle_advertisement.c @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2014 Anki, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include "greatest.h" + +#include "advertisement.h" +#include "adv_data.h" + +SUITE(vehicle_advertisement); + +TEST test_is_anki_vehicle(void) { + int is_anki = 0; + is_anki = anki_vehicle_adv_record_has_anki_uuid(adv0_scan, sizeof(adv0_scan)); + ASSERT_EQ(is_anki, 1); + + is_anki = anki_vehicle_adv_record_has_anki_uuid(adv1_scan, sizeof(adv1_scan)); + ASSERT_EQ(is_anki, 0); + + PASS(); +} + +TEST test_is_anki_vehicle_ignores_sensortag(void) { + int is_anki = 0; + is_anki = anki_vehicle_adv_record_has_anki_uuid(st0_scan, sizeof(st0_scan)); + ASSERT_EQ(is_anki, 0); + + is_anki = anki_vehicle_adv_record_has_anki_uuid(st1_scan, sizeof(st1_scan)); + ASSERT_EQ(is_anki, 0); + + PASS(); +} + +TEST test_anki_vehicle_parse_adv_record(void) { + anki_vehicle_adv_t adv; + + // parse first packet + uint8_t err = 0; + err = anki_vehicle_parse_adv_record(adv0_scan, sizeof(adv0_scan), &adv); + ASSERT_EQ(err, 0); + + err = anki_vehicle_parse_adv_record(adv1_scan, sizeof(adv1_scan), &adv); + ASSERT_EQ(err, 0); + + PASS(); +} + +TEST test_vehicle_parse_mfg_data(void) { + uint8_t data0[] = { 0xBE, 0xEF, 0x00, 0x01, 0x00, 0xE0, 0x0A, 0xA3 }; + anki_vehicle_adv_mfg_t mfg_data; + int err = anki_vehicle_parse_mfg_data(data0, 8, &mfg_data); + ASSERT_EQ(err, 0); + + ASSERT_EQ(mfg_data.product_id, 0xbeef); + ASSERT_EQ(mfg_data.model_id, 0x01); + ASSERT_EQ(mfg_data.identifier & 0xffff, 0x0aa3); + + PASS(); +} + +TEST test_vehicle_parse_local_name(void) { + uint8_t data0[] = { 0x50, 0x20, 0x21, 0x01, 0x20, 0x20, 0x5A, 0x39, 0x41, 0x41, 0x33, 0x20, 0x54, 0x4F, 0x4D, 0x4D, 0x59, 0x00 }; + anki_vehicle_adv_info_t info; + uint8_t err = anki_vehicle_parse_local_name(data0, sizeof(data0), &info); + ASSERT_EQ(err, 0); + ASSERT_EQ(info.state.full_battery, 1); + ASSERT_EQ(info.state.low_battery, 0); + ASSERT_EQ(info.state.on_charger, 1); + ASSERT_EQ(info.version, 0x2120); + ASSERT_STR_EQ((const char *)info.name, (const char *)&data0[8]); + + PASS(); +} + +GREATEST_SUITE(vehicle_advertisement) { + RUN_TEST(test_is_anki_vehicle); + RUN_TEST(test_is_anki_vehicle_ignores_sensortag); + RUN_TEST(test_anki_vehicle_parse_adv_record); + RUN_TEST(test_vehicle_parse_mfg_data); + RUN_TEST(test_vehicle_parse_local_name); +} -- cgit v1.2.3