diff options
103 files changed, 353 insertions, 14174 deletions
diff --git a/CMakeLists.txt b/CMakeLists.txt index 28c81700..5dd5a710 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -9,13 +9,6 @@ endif() FIND_PACKAGE (Threads REQUIRED) -if(NOT SKIP_TINYB) - FIND_PACKAGE (PkgConfig REQUIRED) - PKG_CHECK_MODULES (GLIB2 REQUIRED glib-2.0>=2.40) - PKG_CHECK_MODULES (GIO REQUIRED gio-2.0>=2.40) - PKG_CHECK_MODULES (GIO-UNIX REQUIRED gio-unix-2.0>=2.40) -endif() - # set(CMAKE_MESSAGE_LOG_LEVEL DEBUG) include(jaulib/JaulibSetup.cmake) @@ -30,11 +23,6 @@ set (direct_bt_VERSION_MINOR ${VERSION_MINOR}) set (direct_bt_VERSION_PATCH ${VERSION_PATCH}) set (direct_bt_VERSION_STRING "${direct_bt_VERSION_MAJOR}.${direct_bt_VERSION_MINOR}.${direct_bt_VERSION_PATCH}") -set (tinyb_VERSION_MAJOR ${VERSION_MAJOR}) -set (tinyb_VERSION_MINOR ${VERSION_MINOR}) -set (tinyb_VERSION_PATCH ${VERSION_PATCH}) -set (tinyb_VERSION_STRING "${tinyb_VERSION_MAJOR}.${tinyb_VERSION_MINOR}.${tinyb_VERSION_PATCH}") - set (CMAKE_SWIG_FLAGS "") set (direct_bt_DOCS_DIR documentation) @@ -46,16 +34,11 @@ add_subdirectory (jaulib) add_subdirectory (src/direct_bt) -if(NOT SKIP_TINYB) - add_subdirectory (src/tinyb) -endif() - option (BUILDJAVA "Build Java API." OFF) IF(BUILDJAVA) configure_file (${CMAKE_CURRENT_SOURCE_DIR}/java/manifest.txt.in ${CMAKE_CURRENT_BINARY_DIR}/java/manifest.txt) configure_file (${CMAKE_CURRENT_SOURCE_DIR}/java_fat/manifest-fat.txt.in ${CMAKE_CURRENT_BINARY_DIR}/java_fat/manifest-fat.txt) - configure_file (${CMAKE_CURRENT_SOURCE_DIR}/java_fat/manifest-fat2.txt.in ${CMAKE_CURRENT_BINARY_DIR}/java_fat/manifest-fat2.txt) add_subdirectory (java) add_subdirectory (java_fat) ENDIF(BUILDJAVA) @@ -70,7 +53,7 @@ if (DOXYGEN_FOUND) COMMAND ${CMAKE_COMMAND} -E make_directory ${direct_bt_DOCS_DIR} COMMAND ${DOXYGEN_EXECUTABLE} ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile.cpp.out COMMAND ${DOXYGEN_EXECUTABLE} ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile.java.out - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/api/tinyb/*.hpp ${CMAKE_CURRENT_SOURCE_DIR}/api/direct_bt/*.hpp ${CMAKE_CURRENT_SOURCE_DIR}/java/org/direct_bt/*.java ${CMAKE_CURRENT_SOURCE_DIR}/java/tinyb/dbus/*java ${CMAKE_CURRENT_SOURCE_DIR}/java/jau/direct_bt/*java + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/api/direct_bt/*.hpp ${CMAKE_CURRENT_SOURCE_DIR}/java/org/direct_bt/*.java ${CMAKE_CURRENT_SOURCE_DIR}/java/jau/direct_bt/*java WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} COMMENT "Generating API documentation with Doxygen" VERBATIM ) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 974ed5dc..2284b7f2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,7 +1,7 @@ -Contributing to TinyB {#contributing} -====================== +Contributing to *Direct-BT* {#contributing} +=========================== -TinyB / Direct-BT is an opensource project and we are actively looking for people to help +*Direct-BT* is an opensource project and we are actively looking for people to help with: - Contributions to functionality, extensions of API @@ -61,7 +61,7 @@ we assume the following SPDX-License-Identifier should be declared: ... -This documentation of our usage is certainly a better than GOOG's approach: +This documentation of our usage is certainly better than GOOG's approach: <https://android.googlesource.com/platform/system/bluetooth/+/eclair-release/bluez-clean-headers/bluetooth?autodive=0/>, which removes all authorship and origin. @@ -1,5 +1,7 @@ # Direct-BT LE and BREDR Library +[Original document location](https://jausoft.com/cgit/direct_bt.git/about/). + ## Git Repository This project's canonical repositories is hosted on [Gothel Software](https://jausoft.com/cgit/direct_bt.git/). @@ -7,20 +9,7 @@ This project's canonical repositories is hosted on [Gothel Software](https://jau This project aims to create a clean, modern and easy to use API for [Bluetooth LE and BREDR](https://www.bluetooth.com/specifications/bluetooth-core-specification/), fully accessible through C++, Java and other languages. - -## Version 2 -Starting with version 2.1.0, the *TinyB* Java API has been refactored -to support all new features of its new *Direct-BT* implementation. - -Starting with version 2.2.0, the Java API has changed -to clarify semantics, further support *Direct-BT* -and to favor a shortened naming convention, -e.g. *BluetoothManager* to *BTManager*, *BluetoothGattCharacteristic* to *BTGattChar* etc. - -As of today, the Java API comprises two implementations, *Direct-BT* (complete) and *TinyB* (incomplete). - - -## Direct-BT +## Overview *Direct-BT* provides direct [Bluetooth LE and BREDR](https://www.bluetooth.com/specifications/bluetooth-core-specification/) programming, offering robust high-performance support for embedded & desktop with zero overhead via C++ and Java. @@ -57,6 +46,8 @@ Some more elaboration on the implementation and its status > exposing BTSecurityLevel and SMPIOCapability setup per connection > and providing *automatic security mode negotiation*. > +> BLE slave periphal and GATT server support is underway. +> > BREDR support is planned and prepared for. > @@ -65,7 +56,36 @@ To support other platforms than Linux/BlueZ, we will have to * add specialization for each new platform using their non-platform-agnostic features. -### Direct-BT System Preparations +## Supported Platforms +The following **platforms** are tested and hence supported + +**Debian 10 Buster (GNU/Linux)** + +- amd64 (validated, Generic) +- arm64 (validated, Raspberry Pi 3+ and 4) +- arm32 (validated, Raspberry Pi 3+ and 4) + +**Debian 11 Bullseye (GNU/Linux)** + +- amd64 (validated, Generic) +- arm64 (should work, Raspberry Pi 3+ and 4) +- arm32 (should work, Raspberry Pi 3+ and 4) + +The following **Bluetooth Adapter** were tested + +* Bluetooth 4.0 + - Intel Bluemoon Bluetooth Adapter + - CSR Bluetooth Adapter (CSR8510,..) + - Raspberry Pi Bluetooth Adapter (BCM43455 on 3+, 4) + +* Bluetooth 5.0 + - Intel AX200 Bluetooth 5.0 (Wi-Fi 6 802.11ax (2.4Gbps) + BT 5.0) + - Realtek Bluetooth 5.0 (`RTK_BT_5.0`) + + +## Using *Direct-BT* Applications + +### System Preparations Since *Direct-BT* is not using a 3rd party Bluetooth client library or daemon/service, they should be disabled to allow operation without any interference. @@ -78,7 +98,7 @@ systemctl disable bluetooth systemctl mask bluetooth ``` -### Required Permissions for Direct-BT Applications +### Required Permissions for *Direct-BT* Applications Since *Direct-BT* requires root permissions to certain Bluetooth network device facilities, non-root user require to be granted such permissions. @@ -127,7 +147,7 @@ Notable here is that *capsh* needs to be invoked by root to hand over the capabi and to pass over the *cap_net_raw,cap_net_admin+eip* via *--addamb=...* it also needs *cap_setpcap,cap_setuid,cap_setgid+ep* beforehand. -#### Examples +### Launch Examples The *capsh* method (default), *setcap* and *root* method is being utilized in @@ -137,54 +157,12 @@ The *capsh* method (default), *setcap* and *root* method is being utilized in See *Examples* below ... -### Sponsorship - -*Direct-BT* is the new implementation as provided by [Zafena ICT](https://ict.zafena.se) and [Gothel Software](https://jausoft.com/). - -If you like to utilize *Direct-BT* in a commercial setting, -please contact us to setup a potential support contract. - - -## TinyB -*TinyB* exposes the BLE GATT API for C++, Java and other languages, using *BlueZ* over DBus. - -*TinyB* does not expose the BREDR API. - -*TinyB* is exposed via the following native libraries -- *libtinyb.so* for the core C++ implementation. -- *libjavatinyb.so* for the Java binding. - -*TinyB* is the original implementation of the TinyB project by Intel. - -*TinyB* does not cover all API functionality anymore: Event driven adapter, device and GATT handling -nor SMP Secure Connections. - - -## TinyB and Direct-BT -Pre version 2.0.0 D-Bus implementation details of the Java[tm] classes -of package *tinyb* has been moved to *tinyb.dbus*. -The *tinyb.jar* jar file has been renamed to *direct_bt.jar*, avoiding conflicts. - -Offering the fat jar *direct_bt-fat.jar*, bootstrapping its contained native libraries. -This functionality is provided by the merged-in `jaulib` package. - -General interfaces matching the [Bluetooth Specification](https://www.bluetooth.com/specifications/bluetooth-core-specification/) -were created in package *org.direct_bt*. Direct-BT's C++ API and implementation -contains detailed references to the official specification. - -*org.direct_bt.BTFactory* provides a factory to instantiate the initial root -*org.direct_bt.BTManager*, either using *Direct-BT* or *Tiny-B* (D-Bus) implementation. - -*TinyB*'s C++ namespace and implementation kept mostly unchanged. - -The new Java interface has changed. Package renamed from *org.tinyb* to *org.direct_bt* -and most names have been shortened, -e.g. *BluetoothManager* to *BTManager*, *BluetoothGattCharacteristic* to *BTGattChar* etc. - -*since 2.x* version tags have been added to the Java interface specification for clarity. +## Programming with *Direct-BT* +### API +Exposed API closely follows and references the [Bluetooth Specification](https://www.bluetooth.com/specifications/bluetooth-core-specification/). -## API Documentation +#### API Documentation Up to date API documentation can be found: * [API Overview](https://jausoft.com/projects/direct_bt/build/documentation/cpp/html/namespacedirect__bt.html#details) (C++) @@ -199,7 +177,12 @@ and the [same in the Java API](https://jausoft.com/projects/direct_bt/build/docu A guide for getting started with *Direct-BT* on C++ and Java may follow up. -## Examples +#### Java Specifics +*org.direct_bt.BTFactory* provides a factory to instantiate the initial root +*org.direct_bt.BTManager*, using the *Direct-BT* implementation. + + +### Examples *Direct-BT* [C++ examples](https://jausoft.com/projects/direct_bt/build/documentation/cpp/html/examples.html) are available, [dbt_scanner10.cpp](https://jausoft.com/projects/direct_bt/build/documentation/cpp/html/dbt_scanner10_8cpp-example.html) demonstrates the event driven and multithreading workflow. @@ -208,60 +191,14 @@ demonstrates the event driven and multithreading workflow. are availble, [DBTScanner10.java](https://jausoft.com/projects/direct_bt/build/documentation/java/html/DBTScanner10_8java-example.html) demonstrates the event driven and multithreading workflow - matching *dbt_scanner10.cpp*. -A guide for getting started with *TinyB* on Java is available from Intel: -https://software.intel.com/en-us/java-for-bluetooth-le-apps. - -The hellotinyb example uses a [TI Sensor Tag](http://www.ti.com/ww/en/wireless_connectivity/sensortag2015/?INTC=SensorTag&HQS=sensortag) -from which it reads the ambient temperature. You have to pass the MAC address -of the Sensor Tag as a first parameter to the program. - - -## Supported Platforms -The following **platforms** are tested and hence supported - -**Debian 10 Buster (GNU/Linux)** - -- amd64 (validated, Generic) -- arm64 (validated, Raspberry Pi 3+ and 4) -- arm32 (validated, Raspberry Pi 3+ and 4) - -**Debian 11 Bullseye (GNU/Linux)** -- amd64 (validated, Generic) -- arm64 (should work, Raspberry Pi 3+ and 4) -- arm32 (should work, Raspberry Pi 3+ and 4) - -The following **Bluetooth Adapter** were tested - -* Bluetooth 4.0 - - Intel Bluemoon Bluetooth Adapter - - CSR Bluetooth Adapter (CSR8510,..) - - Raspberry Pi Bluetooth Adapter (BCM43455 on 3+, 4) - -* Bluetooth 5.0 - - Intel AX200 Bluetooth 5.0 (Wi-Fi 6 802.11ax (2.4Gbps) + BT 5.0) - - Realtek Bluetooth 5.0 (`RTK_BT_5.0`) - - -## Build Status -*Will be updated* - - -## Building Binaries +## Building *Direct-BT* The project requires CMake 3.13+ for building and a Java JDK >= 11. This project also uses the [Jau Library](https://jausoft.com/cgit/jaulib.git/about/) as a git submodule, which has been extracted earlier from this project to better encapsulation and allow general use. -*TinyB* requires GLib/GIO 2.40+. It also -requires *BlueZ* with GATT profile activated, which is currently experimental (as -of *BlueZ* 5.37), so you might have to run bluetoothd with the -E flag. For -example, on a system with systemd (Fedora, poky, etc.) edit the -bluetooth.service file (usually found in /usr/lib/systemd/system/ or -/lib/systemd/system) and append -E to ExecStart line, restart the daemon with -systemctl restart bluetooth. - *Direct-BT* does not require GLib/GIO nor shall the *BlueZ* userspace service *bluetoothd* be active for best experience. @@ -279,7 +216,6 @@ Installing build dependencies on Debian (10 or 11): apt install git apt install build-essential g++ gcc libc-dev libpthread-stubs0-dev apt install libunwind8 libunwind-dev -apt install libglib2.0 libglib2.0-0 libglib2.0-dev apt install openjdk-11-jdk openjdk-11-jre junit4 apt install cmake cmake-extras extra-cmake-modules pkg-config apt install doxygen graphviz @@ -289,7 +225,7 @@ For a generic build use: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.sh} CPU_COUNT=`getconf _NPROCESSORS_ONLN` -git clone --recurse-submodules https://jausoft.com/cgit/direct_bt.git +git clone --recurse-submodules git://jausoft.com/srv/scm/direct_bt.git cd direct_bt mkdir build cd build @@ -355,12 +291,6 @@ To build Java bindings: -DBUILDJAVA=ON ~~~~~~~~~~~~~ -To not build the *TinyB* implementation: - -~~~~~~~~~~~~~ --DSKIP_TINYB=ON -~~~~~~~~~~~~~ - To build examples: ~~~~~~~~~~~~~ @@ -373,11 +303,48 @@ To build documentation run: make doc ~~~~~~~~~~~~~ +## Build Status +*Will be updated* + + +## Support & Sponsorship + +*Direct-BT* is the new implementation as provided by [Gothel Software](https://jausoft.com/) and [Zafena ICT](https://ict.zafena.se). + +If you like to utilize *Direct-BT* in a commercial setting, +please contact [Gothel Software](https://jausoft.com/) to setup a potential support contract. + +## Common issues +If you have any issues, please go through the [Troubleshooting Guide](TROUBLESHOOTING.md). + +If the solution is not there, please search for an existing issue in our [Bugzilla DB](https://jausoft.com/bugzilla/describecomponents.cgi?product=Direct-BT), +please [contact us](https://jausoft.com/) for a new bugzilla account via email to Sven Gothel <[email protected]>. + + +## Contributing to *Direct-BT* +You shall agree to Developer Certificate of Origin and Sign-off your code, +using a real name and e-mail address. + +Please check the [Contribution](CONTRIBUTING.md) document for more details. + +## Historical Notes + +### *TinyB* Removal since version 2.3 +Starting with version 2.3, the previously refactored *TinyB* has been removed completely. + +Motivation was lack of detailed Bluetooth support, inclusive increasing diversion with *Direct-BT*. +Furthermore, work is underway for `BLE slave periphal and GATT server` support and its mapping to *BlueZ D-Bus* is questionable +and would be resource intensive. + ## Changes **2.3.0 *Direct-BT* Maturity (Bluetooth LE)** * TODO +**2.3.00** + +* Removal of *TinyB* + **2.2.14** * Bluetooth 5.0 Support @@ -472,15 +439,3 @@ were created in package *org.tinyb*. * Added asynchronous methods for discovering BluetoothObjects -## Common issues -If you have any issues, please go through the [Troubleshooting Guide](TROUBLESHOOTING.md). - -If the solution is not there, please search for an existing issue in our [Bugzilla DB](https://jausoft.com/bugzilla/describecomponents.cgi?product=Direct-BT), -please [contact us](https://jausoft.com/) for a new bugzilla account via email to Sven Gothel <[email protected]>. - - -## Contributing to TinyB / Direct-BT -You shall agree to Developer Certificate of Origin and Sign-off your code, -using a real name and e-mail address. - -Please check the [Contribution](CONTRIBUTING.md) document for more details. diff --git a/TROUBLESHOOTING.md b/TROUBLESHOOTING.md index b5852083..12e1e42e 100644 --- a/TROUBLESHOOTING.md +++ b/TROUBLESHOOTING.md @@ -1,27 +1,24 @@ -Solving common issues with Direct-BT and TinyB {#troubleshooting} +Solving common issues with Direct-BT {#troubleshooting} ============================================== -TinyB -===== +Direct-BT +========= -If you are having issues with TinyB, please follow these steps to resolve common issues: +If you are having issues with *Direct-BT*, please follow these steps to resolve common issues: 1. Make sure bluetooth is not blocked. On most systems you can do this with ``` rfkill unblock bluetooth ```. -2. Make sure blueoothd daemon is started: ``` ps -eF | grep bluetoothd ``` or ``` ps | grep bluetoothd ``` if your ps command does not support parameters (such as BusyBox based systems). This command should a line containing bluetoothd. +2. Make sure blueoothd daemon is **not** started: +``` +systemctl stop bluetooth +systemctl disable bluetooth +systemctl mask bluetooth +``` - If the bluetooth daemon is not started, you should run ```systemctl start bluetooth.service``` on systems using systemd, or the equivalent for your distro. - -3. Make sure you are running bluetoothd with the -E flag. It should be visible when running the commands in 1. If it is not present, you need to add it in ``` /lib/systemd/system/bluetooth.service ``` or the equivalent on your system. - -3. Make sure that your DBus policy permits users to access BlueZ GATT interfaces. The following lines should be present in ``` /etc/dbus-1/system.d/bluetooth.conf ``` under ``` <policy context="default"> ```: - ``` - <allow send_interface="org.bluez.GattService1"/> - <allow send_interface="org.bluez.GattCharacteristic1"/> - <allow send_interface="org.bluez.GattDescriptor1"/> - ``` - -4. Make sure your kernel supports Bluetooth. This is sometimes hard to verify, here are some ways on how to do this: +3. Make sure your kernel supports Bluetooth. This is sometimes hard to verify, here are some ways on how to do this: * ``` lsmod | grep bluetooth ``` should return a line containing bluetooth, if not, try ``` modprobe bluetooth ``` or ``` insmod bluetooth ``` * ``` /proc/config ``` or ``` /proc/config.gz ``` or ``` /boot/config ``` should contain ``` CONFIG_BT=y ``` or ``` CONFIG_BT=m ``` and ``` CONFIG_BT_LE=y ```. If ``` CONFIG_BT=m ``` is enabled, make sure to load your module using ``` modprobe bluetooth ``` or ``` insmod bluetooth ``` * ``` rfkill list ``` should show at least a line containing bluetooth, and it should not be blocked, if it is, see step 1. + +4. If all fails, contact please contact [Gothel Software](https://jausoft.com/) for support. + Support contracts for your project may also be available. diff --git a/api/direct_bt/BTGattChar.hpp b/api/direct_bt/BTGattChar.hpp index f3aa7ff1..44dd48b3 100644 --- a/api/direct_bt/BTGattChar.hpp +++ b/api/direct_bt/BTGattChar.hpp @@ -84,14 +84,15 @@ namespace direct_bt { public: /** BT Core Spec v5.2: Vol 3, Part G GATT: 3.3.1.1 Characteristic Properties */ enum PropertyBitVal : uint8_t { - Broadcast = 0x01, - Read = 0x02, - WriteNoAck = 0x04, - WriteWithAck = 0x08, - Notify = 0x10, - Indicate = 0x20, - AuthSignedWrite = 0x40, - ExtProps = 0x80 + NONE = 0, + Broadcast = (1 << 0), + Read = (1 << 1), + WriteNoAck = (1 << 2), + WriteWithAck = (1 << 3), + Notify = (1 << 4), + Indicate = (1 << 5), + AuthSignedWrite = (1 << 6), + ExtProps = (1 << 7) }; /** * Returns string values as defined in <https://git.kernel.org/pub/scm/bluetooth/bluez.git/tree/doc/gatt-api.txt> diff --git a/api/tinyb.hpp b/api/tinyb.hpp deleted file mode 100644 index 568824d2..00000000 --- a/api/tinyb.hpp +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Author: Petre Eftime <[email protected]> - * Copyright (c) 2015 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#pragma once -#include "tinyb/BluetoothObject.hpp" -#include "tinyb/BluetoothManager.hpp" -#include "tinyb/BluetoothAdapter.hpp" -#include "tinyb/BluetoothDevice.hpp" -#include "tinyb/BluetoothGattService.hpp" -#include "tinyb/BluetoothGattCharacteristic.hpp" -#include "tinyb/BluetoothGattDescriptor.hpp" -#include "tinyb/BluetoothUUID.hpp" diff --git a/api/tinyb/BluetoothAdapter.hpp b/api/tinyb/BluetoothAdapter.hpp deleted file mode 100644 index 2f5b2d9d..00000000 --- a/api/tinyb/BluetoothAdapter.hpp +++ /dev/null @@ -1,338 +0,0 @@ -/* - * Author: Petre Eftime <[email protected]> - * Copyright (c) 2015 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#pragma once -#include "BluetoothObject.hpp" -#include "BluetoothManager.hpp" -#include "BluetoothUUID.hpp" -#include <vector> - -/* Forward declaration of types */ -struct _Object; -typedef struct _Object Object; -struct _Adapter1; -typedef struct _Adapter1 Adapter1; - -/** - * TinyB exposes the BLE GATT API for C++, Java and other languages, using BlueZ - * over DBus and alternative implementations. - * - * TinyB aims to create clean, modern and easy to use Bluetooth LE API. - */ -namespace tinyb { - -/** - * Provides access to Bluetooth adapters. Follows the BlueZ adapter API - * available at: http://git.kernel.org/cgit/bluetooth/bluez.git/tree/doc/adapter-api.txt - */ -class BluetoothAdapter: public BluetoothObject -{ - -friend class BluetoothManager; -friend class BluetoothEventManager; -friend class BluetoothDevice; -friend class BluetoothNotificationHandler; - -private: - Adapter1 *object; - -protected: - BluetoothAdapter(Adapter1 *object); - - static std::unique_ptr<BluetoothAdapter> make(Object *object, - BluetoothType type = BluetoothType::ADAPTER, - std::string *name = nullptr, - std::string *identifier = nullptr, - BluetoothObject *parent = nullptr); - - std::function<void(bool)> powered_callback; - std::function<void(bool)> discoverable_callback; - std::function<void(bool)> pairable_callback; - std::function<void(bool)> discovering_callback; - -public: - - static std::string java_class() { - return std::string(JAVA_DBUS_PACKAGE "/DBusAdapter"); - } - static BluetoothType class_type() { return BluetoothType::ADAPTER; } - - virtual std::string get_java_class() const; - virtual std::string get_class_name() const; - virtual std::string get_object_path() const; - virtual BluetoothType get_bluetooth_type() const; - - BluetoothAdapter(const BluetoothAdapter &object); - ~BluetoothAdapter(); - virtual BluetoothAdapter *clone() const; - - std::unique_ptr<BluetoothDevice> find(std::string *name, - std::string *identifier, - std::chrono::milliseconds timeout = std::chrono::milliseconds::zero()) - { - - BluetoothManager *manager = BluetoothManager::get_bluetooth_manager(); - return manager->find<BluetoothDevice>(name, identifier, this, timeout); - } - - /* D-Bus method calls: */ - - /** Removes a device from the list of devices available on this adapter. - * @param[in] arg_device The path of the device on DBus - * @return TRUE if device was successfully removed - */ - bool remove_device ( - const std::string &arg_device - ); - - /** Turns on device discovery if it is disabled. - * @return TRUE if discovery was successfully enabled - */ - bool start_discovery ( - ); - - /** Turns off device discovery if it is enabled. - * @return TRUE if discovery was successfully disabled - */ - bool stop_discovery ( - ); - - /** Sets the device discovery filter for the caller. If all fields are empty, - * filter is removed. - * @param uuids Vector of UUIDs to filter on - * @param rssi RSSI low bounded threshold - * @param pathloss Pathloss threshold value - * @param transport Type of scan to run - */ - bool set_discovery_filter (std::vector<BluetoothUUID> uuids, - int16_t rssi, uint16_t pathloss, const TransportType &transport); - - /** Returns a list of BluetoothDevices visible from this adapter. - * @return A list of BluetoothDevices visible on this adapter, - * NULL if an error occurred - */ - std::vector<std::unique_ptr<BluetoothDevice>> get_devices ( - ); - - /* D-Bus property accessors: */ - /** Returns the hardware address of this adapter. - * @return The hardware address of this adapter. - */ - std::string get_address (); - - /** Returns the system name of this adapter. - * @return The system name of this adapter. - */ - std::string get_name (); - - /** Returns the friendly name of this adapter. - * @return The friendly name of this adapter. - */ - std::string get_alias (); - - /** Sets the friendly name of this adapter. - */ - void set_alias (const std::string &value); - - /** Returns the Bluetooth class of the adapter. - * @return The Bluetooth class of the adapter. - */ - unsigned int get_class (); - - /** Returns the power state the adapter. - * @return The power state of the adapter. - */ - bool get_powered (); - - /** Sets the power state the adapter. - */ - void set_powered (bool value); - - /** - * Enables notifications for changes of the powered status of the adapter - * and triggers the callback when the value changes. - * Uninstalls the previous powered callback, if any was installed. - * @param callback A function of the form void(BluetoothAdapter&, bool, void *), where - * BluetoothAdapter& is the adapter for which the callback was set, bool will contain the - * new value of the powered property and void * contains optional, user set data - * @param userdata The data which will be delivered to the callback when it is triggered. - * Memory must be managed by user. - */ - void enable_powered_notifications( - std::function<void(BluetoothAdapter &adapter, bool powered, void *userdata)> callback, - void *userdata); - /** - * Enables notifications for changes of the powered status of the adapter - * and triggers the callback when the value changes. - * Uninstalls the previous powered callback, if any was installed. - * @param callback A function of the form void(bool), where - * bool will contain the new value of the powered property - */ - void enable_powered_notifications(std::function<void(bool powered)> callback); - /** - * Disables notifications for changes of the powered status of the adapter - * and uninstalls any callback. - */ - void disable_powered_notifications(); - - /** Returns the discoverable state the adapter. - * @return The discoverable state of the adapter. - */ - bool get_discoverable (); - - /** Sets the discoverable state the adapter. - */ - void set_discoverable (bool value); - - /** - * Enables notifications for changes of the discoverable status of the adapter - * and triggers the callback when the value changes. - * Uninstalls the previous discoverable callback, if any was installed. - * @param callback A function of the form void(BluetoothAdapter&, bool, void *), where - * BluetoothAdapter& is the adapter for which the callback was set, bool will contain the - * new value of the discoverable property and void * contains optional, user set data - * @param userdata The data which will be delivered to the callback when it is triggered. - * Memory must be managed by user. - */ - void enable_discoverable_notifications( - std::function<void(BluetoothAdapter &adapter, bool discoverable, void *userdata)> callback, - void *userdata); - /** - * Enables notifications for changes of the discoverable status of the adapter - * and triggers the callback when the value changes. - * Uninstalls the previous discoverable callback, if any was installed. - * @param callback A function of the form void(bool), where - * bool will contain the new value of the discoverable property - */ - void enable_discoverable_notifications(std::function<void(bool discoverable)> callback); - /** - * Disables notifications for changes of the discoverable status of the adapter and uninstalls any callback; - */ - void disable_discoverable_notifications(); - - - /** Returns the discoverable timeout the adapter. - * @return The discoverable timeout of the adapter. - */ - unsigned int get_discoverable_timeout (); - - /** Sets the discoverable timeout the adapter. A value of 0 disables - * the timeout. - */ - void set_discoverable_timeout (unsigned int value); - - /** Returns the pairable state the adapter. - * @return The pairable state of the adapter. - */ - bool get_pairable (); - - /** Sets the discoverable state the adapter. - */ - void set_pairable (bool value); - - /** - * Enables notifications for changes of the pairable status of the adapter - * and triggers the callback when the value changes. - * Uninstalls the previous pairable callback, if any was installed. - * @param callback A function of the form void(BluetoothAdapter&, bool, void *), where - * BluetoothAdapter& is the adapter for which the callback was set, bool will contain the - * new value of the pairable property and void * contains optional, user set data - * @param userdata The data which will be delivered to the callback when it is triggered. - * Memory must be managed by user. - */ - void enable_pairable_notifications( - std::function<void(BluetoothAdapter &adapter, bool pairable, void *userdata)> callback, - void *userdata); - /** - * Enables notifications for changes of the pairable status of the adapter - * and triggers the callback when the value changes. - * Uninstalls the previous pairable callback, if any was installed. - * @param callback A function of the form void(bool), where - * bool will contain the new value of the pairable property - */ - void enable_pairable_notifications(std::function<void(bool pairable)> callback); - /** - * Disables notifications for changes of the pairable status of the adapter and uninstalls any callback; - */ - void disable_pairable_notifications(); - - /** Returns the timeout in seconds after which pairable state turns off - * automatically, 0 means never. - * @return The pairable timeout of the adapter. - */ - unsigned int get_pairable_timeout (); - - /** Sets the timeout after which pairable state turns off automatically, 0 means never. - */ - void set_pairable_timeout (unsigned int value); - - /** Returns the discovering state the adapter. It can be modified through - * start_discovery/stop_discovery functions. - * @return The discovering state of the adapter. - */ - bool get_discovering (); - - /** - * Enables notifications for changes of the discovering status of the adapter - * and triggers the callback when the value changes. - * Uninstalls the previous discovering callback, if any was installed. - * @param callback A function of the form void(BluetoothAdapter&, bool, void *), where - * BluetoothAdapter& is the adapter for which the callback was set, bool will contain the - * new value of the discovering property and void * contains optional, user set data - * @param userdata The data which will be delivered to the callback when it is triggered. - * Memory must be managed by user. - */ - void enable_discovering_notifications( - std::function<void(BluetoothAdapter &adapter, bool discovering, void *userdata)> callback, - void *userdata); - /** - * Enables notifications for changes of the discovering status of the adapter - * and triggers the callback when the value changes. - * Uninstalls the previous discovering callback, if any was installed. - * @param callback A function of the form void(bool), where - * bool will contain the new value of the discovering property - */ - void enable_discovering_notifications(std::function<void(bool discovering)> callback); - /** - * Disables notifications for changes of the discovering status of the adapter and uninstalls any callback; - */ - void disable_discovering_notifications(); - - /** Returns the UUIDs of the adapter. - * @return Array containing the UUIDs of the adapter, ends with NULL. - */ - std::vector<std::string> get_uuids (); - - /** Returns the local ID of the adapter. - * @return The local ID of the adapter. - */ - std::unique_ptr<std::string> get_modalias (); - - std::unique_ptr<BluetoothDevice> connect_device ( - const std::string &arg_address, const std::string &arg_address_type); - -}; - -} /* namespace tinyb */ - diff --git a/api/tinyb/BluetoothDevice.hpp b/api/tinyb/BluetoothDevice.hpp deleted file mode 100644 index 72e1b834..00000000 --- a/api/tinyb/BluetoothDevice.hpp +++ /dev/null @@ -1,501 +0,0 @@ -/* - * Author: Petre Eftime <[email protected]> - * Copyright (c) 2015 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#pragma once -#include "BluetoothObject.hpp" -#include "BluetoothAdapter.hpp" -#include "BluetoothGattService.hpp" -#include "BluetoothManager.hpp" -#include <cstdint> -#include <vector> -#include <functional> -#include <map> - -/* Forward declaration of types */ -struct _Object; -typedef struct _Object Object; -struct _Device1; -typedef struct _Device1 Device1; - -/** - * Provides access to Bluetooth devices. Follows the BlueZ adapter API - * available at: http://git.kernel.org/cgit/bluetooth/bluez.git/tree/doc/device-api.txt - */ -class tinyb::BluetoothDevice: public BluetoothObject -{ - -friend class tinyb::BluetoothManager; -friend class tinyb::BluetoothEventManager; -friend class tinyb::BluetoothAdapter; -friend class tinyb::BluetoothGattService; -friend class tinyb::BluetoothNotificationHandler; - -private: - Device1 *object; - -protected: - BluetoothDevice(Device1 *object); - - static std::unique_ptr<BluetoothDevice> make(Object *object, - BluetoothType type = BluetoothType::DEVICE, - std::string *name = nullptr, - std::string *identifier = nullptr, - BluetoothObject *parent = nullptr); - - std::function<void(int16_t)> rssi_callback; - std::function<void(bool)> trusted_callback; - std::function<void(bool)> paired_callback; - std::function<void(bool)> connected_callback; - std::function<void(bool)> blocked_callback; - std::function<void(std::map<uint16_t, std::vector<uint8_t>> &)> mfg_callback; - std::function<void(std::map<std::string, std::vector<uint8_t>> &)> service_callback; - std::function<void(bool)> services_resolved_callback; - -public: - - static std::string java_class() { - return std::string(JAVA_DBUS_PACKAGE "/DBusDevice"); - } - static BluetoothType class_type() { return BluetoothType::DEVICE; } - - virtual std::string get_java_class() const; - virtual std::string get_class_name() const; - virtual std::string get_object_path() const; - virtual BluetoothType get_bluetooth_type() const; - - BluetoothDevice(const BluetoothDevice &object); - ~BluetoothDevice(); - virtual BluetoothDevice *clone() const; - - std::unique_ptr<BluetoothGattService> find( - std::string *identifier, - std::chrono::milliseconds timeout = std::chrono::milliseconds::zero()) - { - - BluetoothManager *manager = BluetoothManager::get_bluetooth_manager(); - return manager->find<BluetoothGattService>(nullptr, identifier, this, timeout); - } - - /* D-Bus method calls: */ - - /** The connection to this device is removed, removing all connected - * profiles. - * @return TRUE if the device disconnected - */ - bool disconnect ( - ); - - /** An asynchronous connection to this device is initiated, - * connecting each profile flagged as auto-connectable. - */ - void connect_async_start (); - - /** Completion of the initiated asynchronous connection. - */ - bool connect_async_finish (); - - /** A connection to this device is established, connecting each profile - * flagged as auto-connectable. - * @return TRUE if the device connected - */ - bool connect ( - ); - - /** Connects a specific profile available on the device, given by UUID - * @param arg_UUID The UUID of the profile to be connected - * @return TRUE if the profile connected successfully - */ - bool connect_profile ( - const std::string &arg_UUID - ); - - /** Disconnects a specific profile available on the device, given by UUID - * @param arg_UUID The UUID of the profile to be disconnected - * @return TRUE if the profile disconnected successfully - */ - bool disconnect_profile ( - const std::string &arg_UUID - ); - - /** A connection to this device is established, and the device is then - * paired. - * @return TRUE if the device connected and paired - */ - bool pair ( - ); - - /** Remove the current device (like an unpair). - * @return true if the device has been removed from the system. - */ - bool remove_device( - ); - - /** Cancels an initiated pairing operation - * @return TRUE if the paring is cancelled successfully - */ - bool cancel_pairing ( - ); - - /** Returns a list of BluetoothGattServices available on this device. - * @return A list of BluetoothGattServices available on this device, - * NULL if an error occurred - */ - std::vector<std::unique_ptr<BluetoothGattService>> get_services ( - ); - - /* D-Bus property accessors: */ - /** Returns the hardware address of this device. - * @return The hardware address of this device. - */ - std::string get_address (); - - /** Returns the remote friendly name of this device. - * @return The remote friendly name of this device, or NULL if not set. - */ - std::string get_name (); - - /** Returns an alternative friendly name of this device. - * @return The alternative friendly name of this device, or NULL if not set. - */ - std::string get_alias (); - - /** Sets an alternative friendly name of this device. - */ - void set_alias (const std::string &value); - - /** Returns the Bluetooth class of the device. - * @return The Bluetooth class of the device. - */ - unsigned int get_class (); - - /** Returns the appearance of the device, as found by GAP service. - * @return The appearance of the device, as found by GAP service. - */ - uint16_t get_appearance (); - - /** Returns the proposed icon name of the device. - * @return The proposed icon name, or NULL if not set. - */ - std::unique_ptr<std::string> get_icon (); - - /** Returns the paired state the device. - * @return The paired state of the device. - */ - bool get_paired (); - - /** - * Enables notifications for changes of the paired status of the device - * and triggers the callback when the value changes. - * Uninstalls the previous paired callback, if any was installed. - * @param callback A function of the form void(BluetoothDevice&, bool, void *), where - * BluetoothDevice& is the device for which the callback was set, bool will contain the - * new value of the paired property and void * contains optional, user set data - * @param userdata The data which will be delivered to the callback when it is triggered. - * Memory must be managed by user. - */ - void enable_paired_notifications( - std::function<void(BluetoothDevice &device, bool paired, void *userdata)> callback, - void *userdata); - /** - * Enables notifications for changes of the paired status of the device - * and triggers the callback when the value changes. - * Uninstalls the previous paired callback, if any was installed. - * @param callback A function of the form void(bool), where - * bool will contain the new value of the paired property - */ - void enable_paired_notifications( - std::function<void(bool paired)> callback); - /** - * Disables notifications for changes of the paired status of the device - * and uninstalls any callback. - */ - void disable_paired_notifications(); - - /** Returns the trusted state the device. - * @return The trusted state of the device. - */ - bool get_trusted (); - - /** Sets the trusted state the device. - */ - void set_trusted (bool value); - - /** - * Enables notifications for changes of the trusted status of the device - * and triggers the callback when the value changes. - * Uninstalls the previous trusted callback, if any was installed. - * @param callback A function of the form void(BluetoothDevice&, bool, void *), where - * BluetoothDevice& is the device for which the callback was set, bool will contain the - * new value of the trusted property and void * contains optional, user set data - * @param userdata The data which will be delivered to the callback when it is triggered. - * Memory must be managed by user. - */ - void enable_trusted_notifications( - std::function<void(BluetoothDevice &device, bool trusted, void *userdata)> callback, - void *userdata); - /** - * Enables notifications for changes of the trusted status of the device - * and triggers the callback when the value changes. - * Uninstalls the previous trusted callback, if any was installed. - * @param callback A function of the form void(bool), where - * bool will contain the new value of the trusted property - */ - void enable_trusted_notifications( - std::function<void(bool trusted)> callback); - /** - * Disables notifications for changes of the trusted status of the device - * and uninstalls any callback. - */ - void disable_trusted_notifications(); - - /** Returns the blocked state the device. - * @return The blocked state of the device. - */ - bool get_blocked (); - - /** Sets the blocked state the device. - */ - void set_blocked (bool value); - - /** - * Enables notifications for changes of the blocked status of the device - * and triggers the callback when the value changes. - * Uninstalls the previous blocked callback, if any was installed. - * @param callback A function of the form void(BluetoothDevice&, bool, void *), where - * BluetoothDevice& is the device for which the callback was set, bool will contain the - * new value of the blocked property and void * contains optional, user set data - * @param userdata The data which will be delivered to the callback when it is triggered. - * Memory must be managed by user. - */ - void enable_blocked_notifications( - std::function<void(BluetoothDevice &device, bool blocked, void *userdata)> callback, - void *userdata); - /** - * Enables notifications for changes of the blocked status of the device - * and triggers the callback when the value changes. - * Uninstalls the previous blocked callback, if any was installed. - * @param callback A function of the form void(bool), where - * bool will contain the new value of the blocked property - */ - void enable_blocked_notifications( - std::function<void(bool blocked)> callback); - /** - * Disables notifications for changes of the blocked status of the device - * and uninstalls any callback. - */ - void disable_blocked_notifications(); - - /** Returns if device uses only pre-Bluetooth 2.1 pairing mechanism. - * @return True if device uses only pre-Bluetooth 2.1 pairing mechanism. - */ - bool get_legacy_pairing (); - - /** Returns the Received Signal Strength Indicator of the device (0 means unknown). - * @return The Received Signal Strength Indicator of the device (0 means unknown). - */ - int16_t get_rssi (); - - - /** - * Enables notifications for changes of the RSSI value of the device - * and triggers the callback when the value changes. - * Uninstalls the previous RSSI callback, if any was installed. - * @param callback A function of the form void(BluetoothDevice&, int16_t, void *), where - * BluetoothDevice& is the device for which the callback was set, bool will contain the - * new value of the RSSI property and void * contains optional, user set data - * @param userdata The data which will be delivered to the callback when it is triggered. - * Memory must be managed by user. - */ - void enable_rssi_notifications( - std::function<void(BluetoothDevice &device, int16_t rssi, void *userdata)> callback, - void *userdata = nullptr); - /** - * Enables notifications for changes of the RSSI value of the device - * and triggers the callback when the value changes. - * Uninstalls the previous RSSI callback, if any was installed. - * @param callback A function of the form void(int16_t), where - * bool will contain the new value of the RSSI property - */ - void enable_rssi_notifications( - std::function<void(int16_t rssi)> callback); - /** - * Disables notifications for changes of the RSSI value of the device - * and uninstalls any callback. - */ - void disable_rssi_notifications(); - - /** Returns the connected state of the device. - * @return The connected state of the device. - */ - bool get_connected (); - - /** - * Enables notifications for changes of the connected status of the device - * and triggers the callback when the value changes. - * Uninstalls the previous connected callback, if any was installed. - * @param callback A function of the form void(BluetoothDevice&, bool, void *), where - * BluetoothDevice& is the device for which the callback was set, bool will contain the - * new value of the connected property and void * contains optional, user set data - * @param userdata The data which will be delivered to the callback when it is triggered. - * Memory must be managed by user. - */ - void enable_connected_notifications( - std::function<void(BluetoothDevice &device, bool connected, void *userdata)> callback, - void *userdata); - /** - * Enables notifications for changes of the connected status of the device - * and triggers the callback when the value changes. - * Uninstalls the previous connected callback, if any was installed. - * @param callback A function of the form void(bool), where - * bool will contain the new value of the connected property - */ - void enable_connected_notifications( - std::function<void(bool connected)> callback); - /** - * Disables notifications for changes of the connected status of the device - * and uninstalls any callback. - */ - void disable_connected_notifications(); - - /** Returns the UUIDs of the device. - * @return Array containing the UUIDs of the device, ends with NULL. - */ - std::vector<std::string> get_uuids (); - - /** Returns the local ID of the adapter, or nullptr. - * @return The local ID of the adapter, or nullptr. - */ - std::unique_ptr<std::string> get_modalias (); - - /** Returns the adapter on which this device was discovered or - * connected. - * @return The adapter. - */ - BluetoothAdapter get_adapter (); - - /** Returns a map containing manufacturer specific advertisement data. - * An entry has a uint16_t key and an array of bytes. - * @return manufacturer specific advertisement data. - */ - std::map<uint16_t, std::vector<uint8_t>> get_manufacturer_data(); - /** - * Enables notifications for changes of the manufacturer data of the device - * and triggers the callback when the value changes. - * Uninstalls the previous connected callback, if any was installed. - * @param callback A function of the form void(BluetoothDevice&, bool, void *), where - * BluetoothDevice& is the device for which the callback was set, bool will contain the - * new value of the connected property and void * contains optional, user set data - * @param userdata The data which will be delivered to the callback when it is triggered. - * Memory must be managed by user. - */ - void enable_manufacturer_data_notifications( - std::function<void(BluetoothDevice &device, std::map<uint16_t, std::vector<uint8_t>> &mfgdata, void *userdata)> callback, - void *userdata); - /** - * Enables notifications for changes in the manufacturer data of the device - * and triggers the callback when the value changes. - * Uninstalls the previous connected callback, if any was installed. - * @param callback A function of the form void(bool), where - * bool will contain the new value of the connected property - */ - void enable_manufacturer_data_notifications( - std::function<void(std::map<uint16_t, std::vector<uint8_t>> &mfgdata)> callback); - /** - * Disables notifications for changes in the manufacturer data of the device - * and uninstalls any callback. - */ - void disable_manufacturer_data_notifications(); - - - /** Returns a map containing service advertisement data. - * An entry has a UUID string key and an array of bytes. - * @return service advertisement data. - */ - std::map<std::string, std::vector<uint8_t>> get_service_data(); - /** - * Enables notifications for changes of the service data of the device - * and triggers the callback when the value changes. - * Uninstalls the previous connected callback, if any was installed. - * @param callback A function of the form void(BluetoothDevice&, bool, void *), where - * BluetoothDevice& is the device for which the callback was set, bool will contain the - * new value of the connected property and void * contains optional, user set data - * @param userdata The data which will be delivered to the callback when it is triggered. - * Memory must be managed by user. - */ - void enable_service_data_notifications( - std::function<void(BluetoothDevice &device, std::map<std::string, std::vector<uint8_t>> &servicedata, void *userdata)> callback, - void *userdata); - /** - * Enables notifications for changes in the manufacturer data of the device - * and triggers the callback when the value changes. - * Uninstalls the previous connected callback, if any was installed. - * @param callback A function of the form void(bool), where - * bool will contain the new value of the connected property - */ - void enable_service_data_notifications( - std::function<void(std::map<std::string, std::vector<uint8_t>> &servicedata)> callback); - /** - * Disables notifications for changes in the service data of the device - * and uninstalls any callback. - */ - void disable_service_data_notifications(); - - /** Returns the transmission power level (0 means unknown). - * @return the transmission power level (0 means unknown). - */ - int16_t get_tx_power (); - - /** Returns true if service discovery has ended. - * @return true if the service discovery has ended. - */ - bool get_services_resolved (); - /** - * Enables notifications for changes of the services resolved status of the device - * and triggers the callback when the value changes. - * Uninstalls the previous services resolved callback, if any was installed. - * @param callback A function of the form void(BluetoothDevice&, bool, void *), where - * BluetoothDevice& is the device for which the callback was set, bool will contain the - * new value of the services resolved property and void * contains optional, user set data - * @param userdata The data which will be delivered to the callback when it is triggered. - * Memory must be managed by user. - */ - void enable_services_resolved_notifications( - std::function<void(BluetoothDevice &device, bool services_resolved, void *userdata)> callback, - void *userdata); - /** - * Enables notifications for changes of the services resolved status of the device - * and triggers the callback when the value changes. - * Uninstalls the previous services resolved callback, if any was installed. - * @param callback A function of the form void(bool), where - * bool will contain the new value of the services resolved property - */ - void enable_services_resolved_notifications( - std::function<void(bool connec)> callback); - /** - * Disables notifications for changes of the services resolved status of the device - * and uninstalls any callback. - */ - void disable_services_resolved_notifications(); - -}; diff --git a/api/tinyb/BluetoothEvent.hpp b/api/tinyb/BluetoothEvent.hpp deleted file mode 100644 index 9435c02a..00000000 --- a/api/tinyb/BluetoothEvent.hpp +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Author: Petre Eftime <[email protected]> - * Copyright (c) 2015 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#include <string> -#include <condition_variable> -#include <atomic> -#include <functional> -#include "BluetoothObject.hpp" -#pragma once - -using namespace tinyb; - -typedef std::function<void (BluetoothObject &, void *)> BluetoothCallback; - -class tinyb::BluetoothEvent { -private: - std::string *name; - std::string *identifier; - BluetoothObject *parent; - BluetoothType type; - bool execute_once; - BluetoothCallback cb; - void *data; - bool canceled; - -class BluetoothConditionVariable { - - friend class BluetoothEvent; - - std::condition_variable cv; - std::mutex lock; - BluetoothObject *result; - std::atomic_bool triggered; - std::atomic_uint waiting; - - BluetoothConditionVariable() : cv(), lock() { - result = nullptr; - waiting = 0; - triggered = false; - } - - BluetoothObject *wait() { - if (result != nullptr) - return result; - - if (!triggered) { - std::unique_lock<std::mutex> lk(lock); - waiting++; - cv.wait(lk); - waiting--; - } - - return result; - } - - BluetoothObject *wait_for(std::chrono::milliseconds timeout) { - if (result != nullptr) - return result; - - if (!triggered) { - waiting++; - std::unique_lock<std::mutex> lk(lock); - cv.wait_for(lk, timeout); - waiting--; - } - - return result; - } - - void notify() { - triggered = true; - while (waiting != 0) - cv.notify_all(); - } - - ~BluetoothConditionVariable() { - notify(); - } -}; - - -BluetoothConditionVariable cv; - -static void generic_callback(BluetoothObject &object, void *data); -public: - - BluetoothEvent(BluetoothType type, std::string *name, std::string *identifier, - BluetoothObject *parent, bool execute_once = true, - BluetoothCallback cb = nullptr, void *data = NULL); - ~BluetoothEvent(); - - BluetoothType get_type() const { - return type; - } - - std::string *get_name() const { - return name; - } - - std::string *get_identifier() const { - return identifier; - } - - BluetoothObject *get_parent() const { - return parent; - } - - bool execute_callback(BluetoothObject &object); - bool has_callback() { - return (cb != NULL); - } - - BluetoothObject *get_result() { - return cv.result; - } - - void cancel(); - - void wait(std::chrono::milliseconds timeout = std::chrono::milliseconds::zero()); - - bool operator==(BluetoothEvent const &other); -}; diff --git a/api/tinyb/BluetoothException.hpp b/api/tinyb/BluetoothException.hpp deleted file mode 100644 index 3f723454..00000000 --- a/api/tinyb/BluetoothException.hpp +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Author: Petre Eftime <[email protected]> - * Copyright (c) 2016 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#pragma once -#include <stdexcept> -#include <iostream> - -namespace tinyb { - - class BluetoothException: public std::runtime_error { - - public: - explicit BluetoothException(const std::string &msg): std::runtime_error(msg) { - } - - explicit BluetoothException(const char *msg): std::runtime_error(msg) { - } - - virtual ~BluetoothException() throw() { - } - - virtual const char* what() const throw() { - return std::runtime_error::what(); - } - }; - -} diff --git a/api/tinyb/BluetoothGattCharacteristic.hpp b/api/tinyb/BluetoothGattCharacteristic.hpp deleted file mode 100644 index 52e91c90..00000000 --- a/api/tinyb/BluetoothGattCharacteristic.hpp +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Author: Petre Eftime <[email protected]> - * Copyright (c) 2015 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#pragma once -#include "BluetoothObject.hpp" -#include "BluetoothManager.hpp" -#include "BluetoothGattDescriptor.hpp" -#include <string> -#include <vector> -#include <functional> - -/* Forward declaration of types */ -struct _Object; -typedef struct _Object Object; -struct _GattCharacteristic1; -typedef struct _GattCharacteristic1 GattCharacteristic1; - - -/** - * Provides access to Bluetooth GATT characteristic. Follows the BlueZ adapter API - * available at: http://git.kernel.org/cgit/bluetooth/bluez.git/tree/doc/gatt-api.txt - */ -class tinyb::BluetoothGattCharacteristic: public BluetoothObject -{ - -friend class tinyb::BluetoothGattService; -friend class tinyb::BluetoothGattDescriptor; -friend class tinyb::BluetoothManager; -friend class tinyb::BluetoothEventManager; -friend class BluetoothNotificationHandler; - -private: - GattCharacteristic1 *object; - -protected: - BluetoothGattCharacteristic(GattCharacteristic1 *object); - - static std::unique_ptr<BluetoothGattCharacteristic> make(Object *object, - BluetoothType type = BluetoothType::GATT_CHARACTERISTIC, - std::string *name = nullptr, - std::string *identifier = nullptr, - BluetoothObject *parent = nullptr); - - std::function<void(std::vector<unsigned char> &)> value_changed_callback; - - bool start_notify (); - bool stop_notify (); - -public: - - static std::string java_class() { - return std::string(JAVA_DBUS_PACKAGE "/DBusGattCharacteristic"); - } - static BluetoothType class_type() { return BluetoothType::GATT_CHARACTERISTIC; } - - virtual std::string get_java_class() const; - virtual std::string get_class_name() const ; - virtual std::string get_object_path() const; - virtual BluetoothType get_bluetooth_type() const; - - BluetoothGattCharacteristic(const BluetoothGattCharacteristic &object); - ~BluetoothGattCharacteristic(); - virtual BluetoothGattCharacteristic *clone() const; - - std::unique_ptr<BluetoothGattDescriptor> find( - std::string *identifier, - std::chrono::milliseconds timeout = std::chrono::milliseconds::zero()) - { - - BluetoothManager *manager = BluetoothManager::get_bluetooth_manager(); - return manager->find<BluetoothGattDescriptor>(nullptr, identifier, this, timeout); - } - - /* D-Bus method calls: */ - /** Reads the value of this characteristic. - * @return A std::vector<unsgined char> containing the value of this characteristic. - */ - std::vector<unsigned char> read_value ( - uint16_t offset = 0 - ); - - /** Writes the value of this characteristic. - * @param[in] arg_value The data as vector<uchar> - * to be written packed in a GBytes struct - * @return TRUE if value was written succesfully - */ - bool write_value (const std::vector<unsigned char> &arg_value, uint16_t offset = 0); - - /** - * Enables notifications (including at BLE level) for changes of the - * value of the characteristic and triggers the callback when the - * value changes. - * Uninstalls the previous value callback, if any was installed. - * @param callback A function of the form - * void(BluetoothGattCharacteristic&, std::vector<unsigned char> &, void *), where - * BluetoothGattCharacteristic& is the adapter for which the callback was - * set, bool will contain the new value of the powered property and void * - * contains optional, user set data - * @param userdata The data which will be delivered to the callback when it is triggered. - * Memory must be managed by user. - */ - bool enable_value_notifications( - std::function<void(BluetoothGattCharacteristic &characteristic, std::vector<unsigned char> &value,void *userdata)> callback, - void *user_data); - /** - * Enables notifications (including at BLE level) for changes of the - * value of the characteristic and triggers the callback when the - * value changes. - * Uninstalls the previous powered callback, if any was installed. - * @param callback A function of the form void(std::vector<unsigned char> &), where - * std::vector<unsigned char>& will contain the new value - */ - bool enable_value_notifications( - std::function<void(std::vector<unsigned char> &value)> callback); - /** - * Disables notifications for changes of the value of the characteristic - * and uninstalls any callback (including BLE level). - */ - bool disable_value_notifications(); - - /* D-Bus property accessors: */ - /** Get the UUID of this characteristic. - * @return The 128 byte UUID of this characteristic, NULL if an error occurred - */ - std::string get_uuid (); - - /** Returns the service to which this characteristic belongs to. - * @return The service. - */ - BluetoothGattService get_service (); - - /** Returns the cached value of this characteristic, if any. - * @return The cached value of this characteristic. - */ - std::vector<unsigned char> get_value (); - - /** Returns true if notification for changes of this characteristic are - * activated. - * @return True if notificatios are activated. - */ - bool get_notifying (); - - /** Returns the flags this characterstic has. - * @return A list of flags for this characteristic. - */ - std::vector<std::string> get_flags (); - - /** Returns a list of BluetoothGattDescriptors this characteristic exposes. - * @return A list of BluetoothGattDescriptors exposed by this characteristic - * NULL if an error occurred - */ - std::vector<std::unique_ptr<BluetoothGattDescriptor>> get_descriptors (); - -}; diff --git a/api/tinyb/BluetoothGattDescriptor.hpp b/api/tinyb/BluetoothGattDescriptor.hpp deleted file mode 100644 index 4e973dca..00000000 --- a/api/tinyb/BluetoothGattDescriptor.hpp +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Author: Petre Eftime <[email protected]> - * Copyright (c) 2015 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#pragma once -#include "BluetoothObject.hpp" -#include <vector> -#include <functional> - -/* Forward declaration of types */ -struct _Object; -typedef struct _Object Object; -struct _GattDescriptor1; -typedef struct _GattDescriptor1 GattDescriptor1; - -/** - * Provides access to Bluetooth GATT descriptor. Follows the BlueZ adapter API - * available at: http://git.kernel.org/cgit/bluetooth/bluez.git/tree/doc/gatt-api.txt - */ -class tinyb::BluetoothGattDescriptor: public BluetoothObject -{ - -friend class tinyb::BluetoothGattCharacteristic; -friend class tinyb::BluetoothManager; -friend class tinyb::BluetoothEventManager; -friend class tinyb::BluetoothNotificationHandler; - -private: - GattDescriptor1 *object; - - -protected: - BluetoothGattDescriptor(GattDescriptor1 *object); - - static std::unique_ptr<BluetoothGattDescriptor> make(Object *object, - BluetoothType type = BluetoothType::GATT_DESCRIPTOR, - std::string *name = nullptr, - std::string *identifier = nullptr, - BluetoothObject *parent = nullptr); - - std::function<void(std::vector<unsigned char> &)> value_changed_callback; - -public: - - static std::string java_class() { - return std::string(JAVA_DBUS_PACKAGE "/DBusGattDescriptor"); - } - static BluetoothType class_type() { return BluetoothType::GATT_DESCRIPTOR; } - - virtual std::string get_java_class() const; - virtual std::string get_class_name() const; - virtual std::string get_object_path() const; - virtual BluetoothType get_bluetooth_type() const; - - BluetoothGattDescriptor(const BluetoothGattDescriptor &object); - ~BluetoothGattDescriptor(); - virtual BluetoothGattDescriptor *clone() const; - - /* D-Bus method calls: */ - /** Reads the value of this descriptor - * @return A vector<uchar> containing data from this descriptor - */ - std::vector<unsigned char> read_value ( - uint16_t offset = 0 - ); - - /** Writes the value of this descriptor. - * @param[in] arg_value The data as vector<uchar> - * to be written packed in a GBytes struct - * @return TRUE if value was written succesfully - */ - bool write_value ( - const std::vector<unsigned char> &arg_value, - uint16_t offset = 0 - ); - - /** - * Enables notifications for changes of the value of the descriptor and - * triggers the callback when the value changes. - * Uninstalls the previous value callback, if any was installed. - * @param callback A function of the form - * void(BluetoothGattDescriptor &, std::vector<unsigned char> &, void *), where - * BluetoothGattDescriptor& is the adapter for which the callback was - * set, vector<unsigned char>& will contain the new value of the powered property and void* - * contains optional, user set data - * @param userdata The data which will be delivered to the callback when it is triggered. - * Memory of this parameter must be managed by user. - */ - bool enable_value_notifications( - std::function<void(BluetoothGattDescriptor &descriptor, std::vector<unsigned char> &value,void *userdata)> callback, - void *user_data); - /** - * Enables notifications (including at BLE level) for changes of the - * value of the characteristic and triggers the callback when the - * value changes. - * Uninstalls the previous powered callback, if any was installed. - * @param callback A function of the form void(std::vector<unsigned char> &), where - * std::vector<unsigned char>& will contain the new value - */ - bool enable_value_notifications( - std::function<void(std::vector<unsigned char> &value)> callback); - bool disable_value_notifications(); - - /* D-Bus property accessors: */ - /** Get the UUID of this descriptor. - * @return The 128 byte UUID of this descriptor, NULL if an error occurred - */ - std::string get_uuid (); - - /** Returns the characteristic to which this descriptor belongs to. - * @return The characteristic. - */ - BluetoothGattCharacteristic get_characteristic (); - - /** Returns the cached value of this descriptor, if any. - * @return The cached value of this descriptor. - */ - std::vector<unsigned char> get_value (); - -}; diff --git a/api/tinyb/BluetoothGattService.hpp b/api/tinyb/BluetoothGattService.hpp deleted file mode 100644 index bcc1e525..00000000 --- a/api/tinyb/BluetoothGattService.hpp +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Author: Petre Eftime <[email protected]> - * Copyright (c) 2015 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#pragma once -#include "BluetoothObject.hpp" -#include "BluetoothManager.hpp" -#include "BluetoothGattCharacteristic.hpp" -#include <vector> - -/* Forward declaration of types */ -struct _Object; -typedef struct _Object Object; -struct _GattService1; -typedef struct _GattService1 GattService1; - -/** - * Provides access to Bluetooth GATT characteristic. Follows the BlueZ adapter API - * available at: http://git.kernel.org/cgit/bluetooth/bluez.git/tree/doc/gatt-api.txt - */ -class tinyb::BluetoothGattService: public BluetoothObject -{ - -friend class tinyb::BluetoothManager; -friend class tinyb::BluetoothEventManager; -friend class tinyb::BluetoothDevice; -friend class tinyb::BluetoothGattCharacteristic; - -private: - GattService1 *object; - -protected: - BluetoothGattService(GattService1 *object); - - static std::unique_ptr<BluetoothGattService> make(Object *object, - BluetoothType type = BluetoothType::GATT_SERVICE, - std::string *name = nullptr, - std::string *identifier = nullptr, - BluetoothObject *parent = nullptr); - -public: - - static std::string java_class() { - return std::string(JAVA_DBUS_PACKAGE "/DBusGattService"); - } - static BluetoothType class_type() { return BluetoothType::GATT_SERVICE; } - - virtual std::string get_java_class() const; - virtual std::string get_class_name() const; - virtual std::string get_object_path() const; - virtual BluetoothType get_bluetooth_type() const; - - BluetoothGattService(const BluetoothGattService &object); - ~BluetoothGattService(); - virtual BluetoothGattService *clone() const; - - std::unique_ptr<BluetoothGattCharacteristic> find( - std::string *identifier, - std::chrono::milliseconds timeout = std::chrono::milliseconds::zero()) - { - - BluetoothManager *manager = BluetoothManager::get_bluetooth_manager(); - return manager->find<BluetoothGattCharacteristic>(nullptr, identifier, this, timeout); - } - - /* D-Bus property accessors: */ - - /** Get the UUID of this service - * @return The 128 byte UUID of this service, NULL if an error occurred - */ - std::string get_uuid (); - - /** Returns the device to which this service belongs to. - * @return The device. - */ - BluetoothDevice get_device (); - - /** Returns true if this service is a primary service, false if secondary. - * @return true if this service is a primary service, false if secondary. - */ - bool get_primary (); - - /** Returns a list of BluetoothGattCharacteristics this service exposes. - * @return A list of BluetoothGattCharacteristics exposed by this service - */ - std::vector<std::unique_ptr<BluetoothGattCharacteristic>> get_characteristics (); - -}; diff --git a/api/tinyb/BluetoothManager.hpp b/api/tinyb/BluetoothManager.hpp deleted file mode 100644 index 3210f966..00000000 --- a/api/tinyb/BluetoothManager.hpp +++ /dev/null @@ -1,257 +0,0 @@ -/* - * Author: Petre Eftime <[email protected]> - * Copyright (c) 2015 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#pragma once -#include "BluetoothObject.hpp" -#include "BluetoothEvent.hpp" -#include <vector> -#include <list> - -#include <jau/cpp_lang_util.hpp> - -class tinyb::BluetoothManager: public BluetoothObject -{ -friend class BluetoothAdapter; -friend class BluetoothDevice; -friend class BluetoothGattService; -friend class BluetoothGattCharacteristic; -friend class BluetoothGattDescriptor; -friend class BluetoothEventManager; - -private: - std::unique_ptr<BluetoothAdapter> default_adapter; - static BluetoothManager *bluetooth_manager; - std::list<std::shared_ptr<BluetoothEvent>> event_list; - - BluetoothManager(); - BluetoothManager(const BluetoothManager &object); - -protected: - - void handle_event(BluetoothType type, std::string *name, - std::string *identifier, BluetoothObject *parent, BluetoothObject &object); - -public: - - static std::string java_class() { - return std::string(JAVA_DBUS_PACKAGE "/DBusManager"); - } - - static std::string get_api_version(); - static std::string get_library_version(); - - virtual std::string get_java_class() const; - virtual std::string get_class_name() const; - virtual std::string get_object_path() const; - virtual BluetoothType get_bluetooth_type() const; - - ~BluetoothManager(); - /** Returns an instance of BluetoothManager, to be used instead of constructor. - * @return An initialized BluetoothManager instance. - */ - static BluetoothManager *get_bluetooth_manager(); - - /** Add event to checked against events generated by BlueZ. If an the event - * matches an incoming event its' callback will be triggered. Events can be - * the addition of a new Device, GattService, GattCharacteristic, etc. */ - void add_event(std::shared_ptr<BluetoothEvent> &event) { - event_list.push_back(event); - } - - /** Remove event to checked against events generated by BlueZ. - */ - void remove_event(std::shared_ptr<BluetoothEvent> &event) { - event_list.remove(event); - } - - void remove_event(BluetoothEvent &event) { - for(auto it = event_list.begin(); it != event_list.end(); ++it) { - if ((*it).get() == &event) { - event_list.remove(*it); - break; - } - } - } - - - /** Find a BluetoothObject of type T. If parameters name, identifier and - * parent are not null, the returned object will have to match them. - * It will first check for existing objects. It will not turn on discovery - * or connect to devices. - * @parameter name optionally specify the name of the object you are - * waiting for (for Adapter or Device) - * @parameter identifier optionally specify the identifier of the object you are - * waiting for (UUID for GattService, GattCharacteristic or GattDescriptor, address - * for Adapter or Device) - * @parameter parent optionally specify the parent of the object you are - * waiting for - * @parameter timeout the function will return after timeout time, a - * value of zero means wait forever. If object is not found during this time null will be returned. - * @return An object matching the name, identifier, parent or null if not found before - * timeout expires or event is canceled. - */ - template<class T> - std::unique_ptr<T> find(std::string *name, - std::string* identifier, BluetoothObject *parent, - std::chrono::milliseconds timeout = std::chrono::milliseconds::zero()) - { -#if defined(__cxx_rtti_available__) - std::unique_ptr<BluetoothObject> obj = find(T::class_type(), name, identifier, parent, timeout); - T *t = dynamic_cast<T *>(obj.release()); - return std::unique_ptr<T>(t); -#else - (void)name; - (void) identifier; - (void) parent; - (void) timeout; - return std::unique_ptr<T>(nullptr); -#endif - } - - /** Find a BluetoothObject of a type matching type. If parameters name, - * identifier and parent are not null, the returned object will have to - * match them. - * It will first check for existing objects. It will not turn on discovery - * or connect to devices. - * @parameter type specify the type of the object you are - * waiting for, NONE means anything. - * @parameter name optionally specify the name of the object you are - * waiting for (for Adapter or Device) - * @parameter identifier optionally specify the identifier of the object you are - * waiting for (UUID for GattService, GattCharacteristic or GattDescriptor, address - * for Adapter or Device) - * @parameter parent optionally specify the parent of the object you are - * waiting for - * @parameter timeout the function will return after timeout time, a - * value of zero means wait forever. If object is not found during this time null will be returned. - * @return An object matching the name, identifier, parent or null if not found before - * timeout expires or event is canceled. - */ - std::unique_ptr<BluetoothObject> find(BluetoothType type, std::string *name, - std::string* identifier, BluetoothObject *parent, - std::chrono::milliseconds timeout = std::chrono::milliseconds::zero()); - - /** Find a BluetoothObject of a type matching type. If parameters name, - * identifier and parent are not null, the found object will have to - * match them. The callback cb will be triggered when a match is made. - * Only new objects will trigger the callback. - * @parameter type specify the type of the object you are - * waiting for, NONE means anything. - * @parameter name optionally specify the name of the object you are - * waiting for (for Adapter or Device) - * @parameter identifier optionally specify the identifier of the object you are - * waiting for (UUID for GattService, GattCharacteristic or GattDescriptor, address - * for Adapter or Device) - * @parameter parent optionally specify the parent of the object you are - * waiting for - * @parameter timeout the function will return after timeout time, a - * value of zero means wait forever. If object is not found during this time null will be returned. - * @return It returns the BluetoothEvent generated by this function, allowing to manage the parameters or cancel the event. - */ - std::weak_ptr<BluetoothEvent> find(BluetoothType type, std::string *name, - std::string* identifier, BluetoothObject *parent, BluetoothCallback cb, - bool execute_once = true, - std::chrono::milliseconds timeout = std::chrono::milliseconds::zero()); - - /** Return a BluetoothObject of a type matching type. If parameters name, - * identifier and parent are not null, the returned object will have to - * match them. Only objects which are already in the system will be returned. - * @parameter type specify the type of the object you are - * waiting for, NONE means anything. - * @parameter name optionally specify the name of the object you are - * waiting for (for Adapter or Device) - * @parameter identifier optionally specify the identifier of the object you are - * waiting for (UUID for GattService, GattCharacteristic or GattDescriptor, address - * for Adapter or Device) - * @parameter parent optionally specify the parent of the object you are - * waiting for - * @return An object matching the name, identifier, parent or null if not found. - */ - std::unique_ptr<BluetoothObject> get_object(BluetoothType type, - std::string *name, std::string *identifier, BluetoothObject *parent); - - /** Return a vector of BluetoothObject of a type matching type. If parameters name, - * identifier and parent are not null, the returned object will have to - * match them. Only objects which are already in the system will be returned. - * @parameter type specify the type of the object you are - * waiting for, NONE means anything. - * @parameter name optionally specify the name of the object you are - * waiting for (for Adapter or Device) - * @parameter identifier optionally specify the identifier of the object you are - * waiting for (UUID for GattService, GattCharacteristic or GattDescriptor, address - * for Adapter or Device) - * @parameter parent optionally specify the parent of the object you are - * waiting for - * @return A vector of object matching the name, identifier, parent. - */ - std::vector<std::unique_ptr<BluetoothObject>> get_objects( - BluetoothType type = BluetoothType::NONE, - std::string *name = nullptr, std::string *identifier = nullptr, - BluetoothObject *parent = nullptr); - - /** Returns a list of BluetoothAdapters available in the system - * @return A list of BluetoothAdapters available in the system - */ - std::vector<std::unique_ptr<BluetoothAdapter>> get_adapters( - ); - - /** Returns a list of discovered BluetoothDevices - * @return A list of discovered BluetoothDevices - */ - std::vector<std::unique_ptr<BluetoothDevice>> get_devices( - ); - - /** Returns a list of available BluetoothGattServices - * @return A list of available BluetoothGattServices - */ - std::vector<std::unique_ptr<BluetoothGattService>> get_services( - ); - - /** Sets a default adapter to use for discovery. - * @return TRUE if the device was set - */ - bool set_default_adapter( - BluetoothAdapter &adapter - ); - - std::unique_ptr<BluetoothAdapter> get_default_adapter(); - - /** Turns on device discovery on the default adapter if it is disabled. - * @return TRUE if discovery was successfully enabled - */ - bool start_discovery( - ); - - /** Turns off device discovery on the default adapter if it is enabled. - * @return TRUE if discovery was successfully disabled - */ - bool stop_discovery( - ); - - /** Returns if the discovers is running or not. - * @return TRUE if discovery is running - */ - bool get_discovering( - ); -}; diff --git a/api/tinyb/BluetoothObject.hpp b/api/tinyb/BluetoothObject.hpp deleted file mode 100644 index f262b98c..00000000 --- a/api/tinyb/BluetoothObject.hpp +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Author: Petre Eftime <[email protected]> - * Copyright (c) 2015 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#pragma once -#include <memory> -#include <mutex> -#include <atomic> - -#define JAVA_MAIN_PACKAGE "org/direct_bt" -#define JAVA_DBUS_PACKAGE "tinyb/dbus" - -namespace tinyb { -enum class BluetoothType { - NONE, - ADAPTER, - DEVICE, - GATT_SERVICE, - GATT_CHARACTERISTIC, - GATT_DESCRIPTOR -}; - enum class TransportType { - AUTO, - BREDR, - LE - }; - - class BluetoothEvent; - class BluetoothEventManager; - class BluetoothObject; - class BluetoothManager; - class BluetoothAdapter; - class BluetoothDevice; - class BluetoothDeviceChangeHandler; - class BluetoothGattService; - class BluetoothGattCharacteristic; - class BluetoothNotificationHandler; - class BluetoothGattDescriptor; - class BluetoothException; - class BluetoothUUID; -} - - -class tinyb::BluetoothObject -{ -protected: - std::mutex lk; - std::atomic_bool valid; - - bool lock() { - if (valid) { - lk.lock(); - return true; - } else { - return false; - } - } - - void unlock() { - lk.unlock(); - } - -public: - static BluetoothType class_type() { return BluetoothType::NONE; } - - static std::string java_class() { - return std::string(JAVA_DBUS_PACKAGE "/DBusObject"); - } - - /** Returns the complete Java class of this object - * @return A std::string containing the java class of this object - */ - virtual std::string get_java_class() const; - - /** Returns the class name of this object - * @return A std::string containing the class name of this object - */ - virtual std::string get_class_name() const; - - /** Returns the DBus object path of this object - * @return A std::string containing the DBus object path of this object - */ - virtual std::string get_object_path() const; - - /** Returns the BluetoothType of this object - * @return The BluetoothType of this object - */ - virtual BluetoothType get_bluetooth_type() const; - - virtual ~BluetoothObject() { }; - - - /** Returns a raw pointer to a clone of the object - * @return A raw pointer to a clone of the object - */ - virtual BluetoothObject *clone() const; - - /** Returns true if this object and the other point to the same DBus Object - * @return True if this object and the other point to the same DBus Object - */ - virtual bool operator==(const BluetoothObject &other) const; - virtual bool operator!=(const BluetoothObject &other) const; -}; diff --git a/api/tinyb/BluetoothUUID.hpp b/api/tinyb/BluetoothUUID.hpp deleted file mode 100644 index 452a9a5d..00000000 --- a/api/tinyb/BluetoothUUID.hpp +++ /dev/null @@ -1,27 +0,0 @@ -#pragma once -#include<cstdint> -#include<string> -#include "BluetoothObject.hpp" - -class tinyb::BluetoothUUID { -private: - uint64_t uuid[2]; - -public: - BluetoothUUID(const BluetoothUUID &other); - BluetoothUUID(const std::string &uuid); - BluetoothUUID(const char uuid[]); - - bool operator==(const BluetoothUUID &other); - bool operator==(const std::string &str); - bool operator==(const char str[]); - - BluetoothUUID operator=(const BluetoothUUID &other); - BluetoothUUID operator=(const std::string &other); - BluetoothUUID operator=(const char str[]); - - std::string get_string(); - std::string get_short_string(); - uint32_t get_short(); - bool is_short(); -}; diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index 61ac730b..b24ce212 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -3,47 +3,6 @@ include_directories( ${PROJECT_SOURCE_DIR}/api ) -#include_directories( -# ${PROJECT_SOURCE_DIR}/api -# ${direct_bt_LIB_INCLUDE_DIRS} -# ${tinyb_LIB_INCLUDE_DIRS} -# ${GLIB2_INCLUDE_DIRS} -# ${GIO_INCLUDE_DIRS} -# ${GIO-UNIX_INCLUDE_DIRS} -#) - -if(NOT SKIP_TINYB) - - add_executable (hellotinyb tinyb/hellotinyb.cpp) - target_link_libraries (hellotinyb tinyb) - add_dependencies(hellotinyb tinyb) - - add_executable (checkinit tinyb/checkinit.cpp) - target_link_libraries (checkinit tinyb) - add_dependencies(checkinit tinyb) - - add_executable (asynctinyb tinyb/asynctinyb.cpp) - target_link_libraries (asynctinyb tinyb) - add_dependencies(asynctinyb tinyb) - - add_executable (esstinyb tinyb/esstinyb.cpp) - target_link_libraries (esstinyb tinyb) - add_dependencies(esstinyb tinyb) - - add_executable (notifications tinyb/notifications.cpp) - target_link_libraries (notifications tinyb) - add_dependencies(notifications tinyb) - - add_executable (uuid tinyb/uuid.cpp) - target_link_libraries (uuid tinyb) - add_dependencies(uuid tinyb) - - add_executable (list_mfg tinyb/list_mfg.cpp) - target_link_libraries (list_mfg tinyb) - add_dependencies(list_mfg tinyb) - -endif() - add_executable (dbt_scanner00 direct_bt_scanner00/dbt_scanner00.cpp) target_link_libraries (dbt_scanner00 direct_bt) add_dependencies(dbt_scanner00 direct_bt) diff --git a/examples/java/AsyncTinyB.java b/examples/java/AsyncTinyB.java deleted file mode 100644 index 58fcff9d..00000000 --- a/examples/java/AsyncTinyB.java +++ /dev/null @@ -1,185 +0,0 @@ -import java.util.concurrent.locks.*; - -import org.direct_bt.BTDevice; -import org.direct_bt.BTException; -import org.direct_bt.BTFactory; -import org.direct_bt.BTGattChar; -import org.direct_bt.BTGattService; -import org.direct_bt.BTManager; -import org.direct_bt.HCIStatusCode; - -import java.lang.reflect.InvocationTargetException; -import java.util.concurrent.TimeUnit; - -public class AsyncTinyB { - // private static final float SCALE_LSB = 0.03125f; - static boolean running = true; - - static void printDevice(final BTDevice device) { - System.out.print("Address = " + device.getAddressAndType()); - System.out.print(" Name = " + device.getName()); - System.out.print(" Connected = " + device.getConnected()); - System.out.println(); - } - - static float convertCelsius(final int raw) { - return raw / 128f; - } - - /* - * This program connects to a TI SensorTag 2.0 and reads the temperature characteristic exposed by the device over - * Bluetooth Low Energy. The parameter provided to the program should be the MAC address of the device. - * - * A wiki describing the sensor is found here: http://processors.wiki.ti.com/index.php/CC2650_SensorTag_User's_Guide - * - * The API used in this example is based on TinyB v0.3, which only supports polling, but v0.4 will introduce a - * simplied API for discovering devices and services. - */ - public static void main(final String[] args) throws InterruptedException { - - if (args.length < 1) { - System.err.println("Run with <device_address> argument"); - System.exit(-1); - } - - /* - * To start looking of the device, we first must initialize the TinyB library. The way of interacting with the - * library is through the BluetoothManager. There can be only one BluetoothManager at one time, and the - * reference to it is obtained through the getBluetoothManager method. - */ - final BTManager manager; - try { - manager = BTFactory.getDBusBTManager(); - } catch (BTException | NoSuchMethodException | SecurityException - | IllegalAccessException | IllegalArgumentException - | InvocationTargetException | ClassNotFoundException e) { - System.err.println("Failed to initialized "+BTFactory.DBusImplementationID); - throw new RuntimeException(e); - } - - /* - * The manager will try to initialize a BluetoothAdapter if any adapter is present in the system. To initialize - * discovery we can call startDiscovery, which will put the default adapter in discovery mode. - */ - @SuppressWarnings("deprecation") - final boolean discoveryStarted = manager.startDiscovery(); - - System.out.println("The discovery started: " + (discoveryStarted ? "true" : "false")); - - /* - * After discovery is started, new devices will be detected. We can find the device we are interested in - * through the manager's find method. - */ - final BTDevice sensor = manager.find(null, args[0], null, 10000); - - /* - * After we find the device we can stop looking for other devices. - */ - try { - manager.stopDiscovery(); - } catch (final BTException e) { - System.err.println("Discovery could not be stopped right now"); - } - - if (sensor == null) { - System.err.println("No sensor found with the provided address."); - System.exit(-1); - } - - System.out.print("Found device: "); - printDevice(sensor); - - if ( HCIStatusCode.SUCCESS == sensor.connect() ) - System.out.println("Sensor with the provided address connected"); - else { - System.out.println("Could not connect device."); - System.exit(-1); - } - - final Lock lock = new ReentrantLock(); - final Condition cv = lock.newCondition(); - - Runtime.getRuntime().addShutdownHook(new Thread() { - @Override - public void run() { - running = false; - lock.lock(); - try { - cv.signalAll(); - } finally { - lock.unlock(); - } - } - }); - - /* - * Our device should expose a temperature service, which has a UUID we can find out from the data sheet. The service - * description of the SensorTag can be found here: - * http://processors.wiki.ti.com/images/a/a8/BLE_SensorTag_GATT_Server.pdf. The service we are looking for has the - * short UUID AA00 which we insert into the TI Base UUID: f000XXXX-0451-4000-b000-000000000000 - */ - final BTGattService tempService = sensor.find( "f000aa00-0451-4000-b000-000000000000"); - - if (tempService == null) { - System.err.println("This device does not have the temperature service we are looking for."); - sensor.disconnect(); - System.exit(-1); - } - System.out.println("Found service " + tempService.getUUID()); - - final BTGattChar tempValue = tempService.find("f000aa01-0451-4000-b000-000000000000"); - final BTGattChar tempConfig = tempService.find("f000aa02-0451-4000-b000-000000000000"); - final BTGattChar tempPeriod = tempService.find("f000aa03-0451-4000-b000-000000000000"); - - if (tempValue == null || tempConfig == null || tempPeriod == null) { - System.err.println("Could not find the correct characteristics."); - sensor.disconnect(); - System.exit(-1); - } - - System.out.println("Found the temperature characteristics"); - - /* - * Turn on the Temperature Service by writing 1 in the configuration characteristic, as mentioned in the PDF - * mentioned above. We could also modify the update interval, by writing in the period characteristic, but the - * default 1s is good enough for our purposes. - */ - final byte[] config = { 0x01 }; - tempConfig.writeValue(config, false /* withResponse */); - - /* - * Each second read the value characteristic and display it in a human readable format. - */ - while (running) { - final byte[] tempRaw = tempValue.readValue(); - System.out.print("Temp raw = {"); - for (final byte b : tempRaw) { - System.out.print(String.format("%02x,", b)); - } - System.out.print("}"); - - /* - * The temperature service returns the data in an encoded format which can be found in the wiki. Convert the - * raw temperature format to celsius and print it. Conversion for object temperature depends on ambient - * according to wiki, but assume result is good enough for our purposes without conversion. - */ - final int objectTempRaw = (tempRaw[0] & 0xff) | (tempRaw[1] << 8); - final int ambientTempRaw = (tempRaw[2] & 0xff) | (tempRaw[3] << 8); - - final float objectTempCelsius = convertCelsius(objectTempRaw); - final float ambientTempCelsius = convertCelsius(ambientTempRaw); - - System.out.println( - String.format(" Temp: Object = %fC, Ambient = %fC", objectTempCelsius, ambientTempCelsius)); - - lock.lock(); - try { - cv.await(1, TimeUnit.SECONDS); - } finally { - lock.unlock(); - } - } - sensor.disconnect(); - - } -} diff --git a/examples/java/CMakeLists.txt b/examples/java/CMakeLists.txt index 6a5e0139..ce5fbc59 100644 --- a/examples/java/CMakeLists.txt +++ b/examples/java/CMakeLists.txt @@ -2,48 +2,6 @@ find_package(Java REQUIRED) include(UseJava) -add_jar(HelloTinyB SOURCES HelloTinyB.java INCLUDE_JARS direct_bt_jar ENTRY_POINT HelloTinyB) -add_custom_command(TARGET HelloTinyB - POST_BUILD - COMMAND cp "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_FILES_DIRECTORY}/HelloTinyB.dir/HelloTinyB.class" "${CMAKE_CURRENT_BINARY_DIR}" -) -add_dependencies(HelloTinyB direct_bt_jar) - -add_jar(AsyncTinyB SOURCES AsyncTinyB.java INCLUDE_JARS direct_bt_jar ENTRY_POINT AsyncTinyB) -add_custom_command(TARGET AsyncTinyB - POST_BUILD - COMMAND cp "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_FILES_DIRECTORY}/AsyncTinyB.dir/AsyncTinyB.class" "${CMAKE_CURRENT_BINARY_DIR}" -) -add_dependencies(AsyncTinyB direct_bt_jar) - -add_jar(Notification SOURCES Notification.java INCLUDE_JARS direct_bt_jar ENTRY_POINT Notification) -add_custom_command(TARGET Notification - POST_BUILD - COMMAND cp "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_FILES_DIRECTORY}/Notification.dir/Notification.class" "${CMAKE_CURRENT_BINARY_DIR}" -) -add_dependencies(Notification direct_bt_jar) - -add_jar(ScannerTinyB00 SOURCES ScannerTinyB00.java INCLUDE_JARS direct_bt_jar ENTRY_POINT Notification) -add_custom_command(TARGET ScannerTinyB00 - POST_BUILD - COMMAND cp "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_FILES_DIRECTORY}/ScannerTinyB00.dir/ScannerTinyB00.class" "${CMAKE_CURRENT_BINARY_DIR}" -) -add_dependencies(ScannerTinyB00 direct_bt_jar) - -add_jar(ScannerTinyB01 SOURCES ScannerTinyB01.java INCLUDE_JARS direct_bt_jar ENTRY_POINT Notification) -add_custom_command(TARGET ScannerTinyB01 - POST_BUILD - COMMAND cp "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_FILES_DIRECTORY}/ScannerTinyB01.dir/ScannerTinyB01.class" "${CMAKE_CURRENT_BINARY_DIR}" -) -add_dependencies(ScannerTinyB01 direct_bt_jar) - -add_jar(ScannerTinyB02 SOURCES ScannerTinyB02.java INCLUDE_JARS direct_bt_jar ENTRY_POINT Notification) -add_custom_command(TARGET ScannerTinyB02 - POST_BUILD - COMMAND cp "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_FILES_DIRECTORY}/ScannerTinyB02.dir/ScannerTinyB02.class" "${CMAKE_CURRENT_BINARY_DIR}" -) -add_dependencies(ScannerTinyB02 direct_bt_jar) - add_jar(DBTScanner10 SOURCES DBTScanner10.java INCLUDE_JARS direct_bt_jar ENTRY_POINT Notification) add_custom_command(TARGET DBTScanner10 POST_BUILD diff --git a/examples/java/DBTScanner10.java b/examples/java/DBTScanner10.java index 8d022ca2..a118820d 100644 --- a/examples/java/DBTScanner10.java +++ b/examples/java/DBTScanner10.java @@ -47,12 +47,12 @@ import org.direct_bt.BTGattChar; import org.direct_bt.BTGattDesc; import org.direct_bt.BTGattService; import org.direct_bt.BTManager; -import org.direct_bt.BTNotification; import org.direct_bt.BTSecurityRegistry; import org.direct_bt.BTType; import org.direct_bt.BTUtils; import org.direct_bt.EIRDataTypeSet; import org.direct_bt.EUI48; +import org.direct_bt.GattCharPropertySet; import org.direct_bt.BTGattCharListener; import org.direct_bt.HCIStatusCode; import org.direct_bt.HCIWhitelistConnectType; @@ -134,7 +134,7 @@ public class DBTScanner10 { } } - final AdapterStatusListener statusListener = new AdapterStatusListener() { + class MyAdapterStatusListener extends AdapterStatusListener { @Override public void adapterSettingsChanged(final BTAdapter adapter, final AdapterSettings oldmask, final AdapterSettings newmask, final AdapterSettings changedmask, final long timestamp) { @@ -520,8 +520,8 @@ public class DBTScanner10 { printf(" [%02d.%02d] Characteristic: UUID %s\n", i, j, serviceChar.getUUID()); printf(" [%02d.%02d] %s\n", i, j, serviceChar.toString()); } - final List<String> properties = Arrays.asList(serviceChar.getFlags()); - if( properties.contains("read") ) { + final GattCharPropertySet properties = serviceChar.getProperties(); + if( properties.isSet(GattCharPropertySet.Type.Read) ) { final byte[] value = serviceChar.readValue(); final String svalue = BTUtils.decodeUTF8String(value, 0, value.length); if( !QUIET ) { @@ -646,7 +646,7 @@ public class DBTScanner10 { private boolean initAdapter(final BTAdapter adapter) { // Even if adapter is not yet powered, listen to it and act when it gets powered-on - adapter.addStatusListener(statusListener); + adapter.addStatusListener(new MyAdapterStatusListener() ); // Flush discovered devices after registering our status listener. // This avoids discovered devices before we have registered! adapter.removeDiscoveredDevices(); @@ -656,14 +656,6 @@ public class DBTScanner10 { return false; } - adapter.enableDiscoverableNotifications(new BooleanNotification("Discoverable", timestamp_t0)); - - adapter.enableDiscoveringNotifications(new BooleanNotification("Discovering", timestamp_t0)); - - adapter.enablePairableNotifications(new BooleanNotification("Pairable", timestamp_t0)); - - adapter.enablePoweredNotifications(new BooleanNotification("Powered", timestamp_t0)); - if( USE_WHITELIST ) { for(final Iterator<BDAddressAndType> wliter = whitelist.iterator(); wliter.hasNext(); ) { final BDAddressAndType addr = wliter.next(); @@ -891,31 +883,4 @@ public class DBTScanner10 { } test.runTest(manager); } - - static class BooleanNotification implements BTNotification<Boolean> { - private final long t0; - private final String name; - private boolean v; - - public BooleanNotification(final String name, final long t0) { - this.t0 = t0; - this.name = name; - this.v = false; - } - - @Override - public void run(final Boolean v) { - synchronized(this) { - final long t1 = BTUtils.currentTimeMillis(); - this.v = v.booleanValue(); - System.out.println("###### "+name+": "+v+" in td "+(t1-t0)+" ms!"); - this.notifyAll(); - } - } - public boolean getValue() { - synchronized(this) { - return v; - } - } - } } diff --git a/examples/java/HelloTinyB.java b/examples/java/HelloTinyB.java deleted file mode 100644 index 54e991a7..00000000 --- a/examples/java/HelloTinyB.java +++ /dev/null @@ -1,247 +0,0 @@ -import java.lang.reflect.InvocationTargetException; -import java.util.List; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.Condition; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -import org.direct_bt.BDAddressAndType; -import org.direct_bt.BDAddressType; -import org.direct_bt.BTDevice; -import org.direct_bt.BTException; -import org.direct_bt.BTFactory; -import org.direct_bt.BTGattChar; -import org.direct_bt.BTGattService; -import org.direct_bt.BTManager; -import org.direct_bt.EUI48; -import org.direct_bt.HCIStatusCode; - -public class HelloTinyB { - static boolean running = true; - - static void printDevice(final BTDevice device) { - System.out.print("Address = " + device.getAddressAndType()); - System.out.print(" Name = " + device.getName()); - System.out.print(" Connected = " + device.getConnected()); - System.out.println(); - } - - static float convertCelsius(final int raw) { - return raw / 128f; - } - - /* - * After discovery is started, new devices will be detected. We can get a list of all devices through the manager's - * getDevices method. We can the look through the list of devices to find the device with the MAC which we provided - * as a parameter. We continue looking until we find it, or we try 15 times (1 minutes). - */ - static BTDevice getDevice(final BTManager manager, final BDAddressAndType addressAndType) throws InterruptedException { - BTDevice sensor = null; - for (int i = 0; (i < 15) && running; ++i) { - final List<BTDevice> list = manager.getDevices(); - if (list == null) - return null; - - for (final BTDevice device : list) { - printDevice(device); - /* - * Here we check if the address matches. - */ - if (device.getAddressAndType().matches(addressAndType)) { - sensor = device; - } - } - - if (sensor != null) { - return sensor; - } - Thread.sleep(4000); - } - return null; - } - - /* - * Our device should expose a temperature service, which has a UUID we can find out from the data sheet. The service - * description of the SensorTag can be found here: - * http://processors.wiki.ti.com/images/a/a8/BLE_SensorTag_GATT_Server.pdf. The service we are looking for has the - * short UUID AA00 which we insert into the TI Base UUID: f000XXXX-0451-4000-b000-000000000000 - */ - static BTGattService getService(final BTDevice device, final String UUID) throws InterruptedException { - System.out.println("Services exposed by device:"); - BTGattService tempService = null; - List<BTGattService> bluetoothServices = null; - do { - bluetoothServices = device.getServices(); - if (bluetoothServices == null) - return null; - - for (final BTGattService service : bluetoothServices) { - System.out.println("UUID: " + service.getUUID()); - if (service.getUUID().equals(UUID)) - tempService = service; - } - Thread.sleep(4000); - } while (bluetoothServices.isEmpty() && running); - return tempService; - } - - static BTGattChar getCharacteristic(final BTGattService service, final String UUID) { - final List<BTGattChar> characteristics = service.getChars(); - if (characteristics == null) - return null; - - for (final BTGattChar characteristic : characteristics) { - if (characteristic.getUUID().equals(UUID)) - return characteristic; - } - return null; - } - - /* - * This program connects to a TI SensorTag 2.0 and reads the temperature characteristic exposed by the device over - * Bluetooth Low Energy. The parameter provided to the program should be the MAC address of the device. - * - * A wiki describing the sensor is found here: http://processors.wiki.ti.com/index.php/CC2650_SensorTag_User's_Guide - * - * The API used in this example is based on TinyB v0.3, which only supports polling, but v0.4 will introduce a - * simplied API for discovering devices and services. - */ - public static void main(final String[] args) throws InterruptedException { - - if (args.length < 1) { - System.err.println("Run with <device_address> argument"); - System.exit(-1); - } - - /* - * To start looking of the device, we first must initialize the TinyB library. The way of interacting with the - * library is through the BluetoothManager. There can be only one BluetoothManager at one time, and the - * reference to it is obtained through the getBluetoothManager method. - */ - final BTManager manager; - try { - manager = BTFactory.getDBusBTManager(); - } catch (BTException | NoSuchMethodException | SecurityException - | IllegalAccessException | IllegalArgumentException - | InvocationTargetException | ClassNotFoundException e) { - System.err.println("Failed to initialized "+BTFactory.DBusImplementationID); - throw new RuntimeException(e); - } - - /* - * The manager will try to initialize a BluetoothAdapter if any adapter is present in the system. To initialize - * discovery we can call startDiscovery, which will put the default adapter in discovery mode. - */ - @SuppressWarnings("deprecation") - final boolean discoveryStarted = manager.startDiscovery(); - - System.out.println("The discovery started: " + (discoveryStarted ? "true" : "false")); - final BTDevice sensor = getDevice(manager, new BDAddressAndType(new EUI48(args[0]), BDAddressType.BDADDR_UNDEFINED)); - - /* - * After we find the device we can stop looking for other devices. - */ - try { - manager.stopDiscovery(); - } catch (final BTException e) { - System.err.println("Discovery could not be stopped."); - } - - if (sensor == null) { - System.err.println("No sensor found with the provided address."); - System.exit(-1); - } - - System.out.print("Found device: "); - printDevice(sensor); - - if ( HCIStatusCode.SUCCESS == sensor.connect() ) - System.out.println("Sensor with the provided address connected"); - else { - System.out.println("Could not connect device."); - System.exit(-1); - } - - final Lock lock = new ReentrantLock(); - final Condition cv = lock.newCondition(); - - Runtime.getRuntime().addShutdownHook(new Thread() { - @Override - public void run() { - running = false; - lock.lock(); - try { - cv.signalAll(); - } finally { - lock.unlock(); - } - - } - }); - - - final BTGattService tempService = getService(sensor, "f000aa00-0451-4000-b000-000000000000"); - - if (tempService == null) { - System.err.println("This device does not have the temperature service we are looking for."); - sensor.disconnect(); - System.exit(-1); - } - System.out.println("Found service " + tempService.getUUID()); - - final BTGattChar tempValue = getCharacteristic(tempService, "f000aa01-0451-4000-b000-000000000000"); - final BTGattChar tempConfig = getCharacteristic(tempService, "f000aa02-0451-4000-b000-000000000000"); - final BTGattChar tempPeriod = getCharacteristic(tempService, "f000aa03-0451-4000-b000-000000000000"); - - if (tempValue == null || tempConfig == null || tempPeriod == null) { - System.err.println("Could not find the correct characteristics."); - sensor.disconnect(); - System.exit(-1); - } - - System.out.println("Found the temperature characteristics"); - - /* - * Turn on the Temperature Service by writing 1 in the configuration characteristic, as mentioned in the PDF - * mentioned above. We could also modify the update interval, by writing in the period characteristic, but the - * default 1s is good enough for our purposes. - */ - final byte[] config = { 0x01 }; - tempConfig.writeValue(config, false /* withResponse */); - - /* - * Each second read the value characteristic and display it in a human readable format. - */ - while (running) { - final byte[] tempRaw = tempValue.readValue(); - System.out.print("Temp raw = {"); - for (final byte b : tempRaw) { - System.out.print(String.format("%02x,", b)); - } - System.out.print("}"); - - /* - * The temperature service returns the data in an encoded format which can be found in the wiki. Convert the - * raw temperature format to celsius and print it. Conversion for object temperature depends on ambient - * according to wiki, but assume result is good enough for our purposes without conversion. - */ - final int objectTempRaw = (tempRaw[0] & 0xff) | (tempRaw[1] << 8); - final int ambientTempRaw = (tempRaw[2] & 0xff) | (tempRaw[3] << 8); - - final float objectTempCelsius = convertCelsius(objectTempRaw); - final float ambientTempCelsius = convertCelsius(ambientTempRaw); - - System.out.println( - String.format(" Temp: Object = %fC, Ambient = %fC", objectTempCelsius, ambientTempCelsius)); - - lock.lock(); - try { - cv.await(1, TimeUnit.SECONDS); - } finally { - lock.unlock(); - } - } - sensor.disconnect(); - - } -} diff --git a/examples/java/Notification.java b/examples/java/Notification.java deleted file mode 100644 index b7cbe80d..00000000 --- a/examples/java/Notification.java +++ /dev/null @@ -1,226 +0,0 @@ -/* - * Author: Petre Eftime <[email protected]> - * Copyright (c) 2016 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -import java.lang.reflect.InvocationTargetException; -import java.util.concurrent.locks.Condition; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -import org.direct_bt.BTDevice; -import org.direct_bt.BTException; -import org.direct_bt.BTFactory; -import org.direct_bt.BTGattChar; -import org.direct_bt.BTGattService; -import org.direct_bt.BTManager; -import org.direct_bt.BTNotification; -import org.direct_bt.HCIStatusCode; - -class ValueNotification implements BTNotification<byte[]> { - - @Override - public void run(final byte[] tempRaw) { - System.out.print("Temp raw = {"); - for (final byte b : tempRaw) { - System.out.print(String.format("%02x,", b)); - } - System.out.print("}"); - - /* - * The temperature service returns the data in an encoded format which can be found in the wiki. Convert the - * raw temperature format to celsius and print it. Conversion for object temperature depends on ambient - * according to wiki, but assume result is good enough for our purposes without conversion. - */ - final int objectTempRaw = (tempRaw[0] & 0xff) | (tempRaw[1] << 8); - final int ambientTempRaw = (tempRaw[2] & 0xff) | (tempRaw[3] << 8); - - final float objectTempCelsius = Notification.convertCelsius(objectTempRaw); - final float ambientTempCelsius = Notification.convertCelsius(ambientTempRaw); - - System.out.println( - String.format(" Temp: Object = %fC, Ambient = %fC", objectTempCelsius, ambientTempCelsius)); - - - } - -} - -class ConnectedNotification implements BTNotification<Boolean> { - - @Override - public void run(final Boolean connected) { - System.out.println("Connected"); - } - -} - -public class Notification { - // private static final float SCALE_LSB = 0.03125f; - static boolean running = true; - - static void printDevice(final BTDevice device) { - System.out.print("Address = " + device.getAddressAndType()); - System.out.print(" Name = " + device.getName()); - System.out.print(" Connected = " + device.getConnected()); - System.out.println(); - } - - static float convertCelsius(final int raw) { - return raw / 128f; - } - - /* - * This program connects to a TI SensorTag 2.0 and reads the temperature characteristic exposed by the device over - * Bluetooth Low Energy. The parameter provided to the program should be the MAC address of the device. - * - * A wiki describing the sensor is found here: http://processors.wiki.ti.com/index.php/CC2650_SensorTag_User's_Guide - * - * The API used in this example is based on TinyB v0.3, which only supports polling, but v0.4 will introduce a - * simplied API for discovering devices and services. - */ - public static void main(final String[] args) throws InterruptedException { - - if (args.length < 1) { - System.err.println("Run with <device_address> argument"); - System.exit(-1); - } - - /* - * To start looking of the device, we first must initialize the TinyB library. The way of interacting with the - * library is through the BluetoothManager. There can be only one BluetoothManager at one time, and the - * reference to it is obtained through the getBluetoothManager method. - */ - final BTManager manager; - try { - manager = BTFactory.getDBusBTManager(); - } catch (BTException | NoSuchMethodException | SecurityException - | IllegalAccessException | IllegalArgumentException - | InvocationTargetException | ClassNotFoundException e) { - System.err.println("Failed to initialized "+BTFactory.DBusImplementationID); - throw new RuntimeException(e); - } - - /* - * The manager will try to initialize a BluetoothAdapter if any adapter is present in the system. To initialize - * discovery we can call startDiscovery, which will put the default adapter in discovery mode. - */ - @SuppressWarnings("deprecation") - final boolean discoveryStarted = manager.startDiscovery(); - - System.out.println("The discovery started: " + (discoveryStarted ? "true" : "false")); - - /* - * After discovery is started, new devices will be detected. We can find the device we are interested in - * through the manager's find method. - */ - final BTDevice sensor = manager.find(null, args[0], null, 10000); - - if (sensor == null) { - System.err.println("No sensor found with the provided address."); - System.exit(-1); - } - - sensor.enableConnectedNotifications(new ConnectedNotification()); - - System.out.print("Found device: "); - printDevice(sensor); - - if ( HCIStatusCode.SUCCESS == sensor.connect() ) - System.out.println("Sensor with the provided address connected"); - else { - System.out.println("Could not connect device."); - System.exit(-1); - } - - /* - * After we find the device we can stop looking for other devices. - */ - //manager.stopDiscovery(); - - final Lock lock = new ReentrantLock(); - final Condition cv = lock.newCondition(); - - Runtime.getRuntime().addShutdownHook(new Thread() { - @Override - public void run() { - running = false; - lock.lock(); - try { - cv.signalAll(); - } finally { - lock.unlock(); - } - } - }); - - /* - * Our device should expose a temperature service, which has a UUID we can find out from the data sheet. The service - * description of the SensorTag can be found here: - * http://processors.wiki.ti.com/images/a/a8/BLE_SensorTag_GATT_Server.pdf. The service we are looking for has the - * short UUID AA00 which we insert into the TI Base UUID: f000XXXX-0451-4000-b000-000000000000 - */ - final BTGattService tempService = sensor.find( "f000aa00-0451-4000-b000-000000000000"); - - if (tempService == null) { - System.err.println("This device does not have the temperature service we are looking for."); - sensor.disconnect(); - System.exit(-1); - } - System.out.println("Found service " + tempService.getUUID()); - - final BTGattChar tempValue = tempService.find("f000aa01-0451-4000-b000-000000000000"); - final BTGattChar tempConfig = tempService.find("f000aa02-0451-4000-b000-000000000000"); - final BTGattChar tempPeriod = tempService.find("f000aa03-0451-4000-b000-000000000000"); - - if (tempValue == null || tempConfig == null || tempPeriod == null) { - System.err.println("Could not find the correct characteristics."); - sensor.disconnect(); - System.exit(-1); - } - - System.out.println("Found the temperature characteristics"); - - /* - * Turn on the Temperature Service by writing 1 in the configuration characteristic, as mentioned in the PDF - * mentioned above. We could also modify the update interval, by writing in the period characteristic, but the - * default 1s is good enough for our purposes. - */ - final byte[] config = { 0x01 }; - tempConfig.writeValue(config, false /* withResponse */); - - final byte[] period = { 100 }; - tempPeriod.writeValue(period, false /* withResponse */); - - tempValue.enableValueNotifications(new ValueNotification()); - - lock.lock(); - try { - while(running) - cv.await(); - } finally { - lock.unlock(); - } - sensor.disconnect(); - - } -} diff --git a/examples/java/ScannerTinyB00.java b/examples/java/ScannerTinyB00.java deleted file mode 100644 index e3956740..00000000 --- a/examples/java/ScannerTinyB00.java +++ /dev/null @@ -1,310 +0,0 @@ -/** - * Author: Sven Gothel <[email protected]> - * Copyright (c) 2020 Gothel Software e.K. - * Copyright (c) 2020 ZAFENA AB - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -import java.lang.reflect.InvocationTargetException; -import java.util.Iterator; -import java.util.List; - -import org.direct_bt.BDAddressAndType; -import org.direct_bt.BDAddressType; -import org.direct_bt.BTAdapter; -import org.direct_bt.BTDevice; -import org.direct_bt.BTException; -import org.direct_bt.BTFactory; -import org.direct_bt.BTGattChar; -import org.direct_bt.BTGattDesc; -import org.direct_bt.BTGattService; -import org.direct_bt.BTManager; -import org.direct_bt.BTNotification; -import org.direct_bt.BTUtils; -import org.direct_bt.EUI48; -import org.direct_bt.HCIStatusCode; - -/** - * This Java scanner example is a TinyB backward compatible and not fully event driven. - * It simply polls found devices and shows certain results. - * <p> - * This example does not represent the recommended utilization of Direct-BT. - * </p> - */ -public class ScannerTinyB00 { - static { - System.setProperty("org.tinyb.verbose", "true"); - } - /** 60,000 milliseconds */ - static long TO_DISCOVER = 60000; - - public static void main(final String[] args) throws InterruptedException { - String bluetoothManagerClazzName = BTFactory.DirectBTImplementationID.BluetoothManagerClassName; - int dev_id = 0; // default - BDAddressAndType mac = null; - int mode = 0; - boolean forever = false; - - for(int i=0; i< args.length; i++) { - final String arg = args[i]; - - if( arg.equals("-dev_id") && args.length > (i+1) ) { - dev_id = Integer.valueOf(args[++i]).intValue(); - } else if( arg.equals("-mac") ) { - mac = new BDAddressAndType(new EUI48(args[++i]), BDAddressType.BDADDR_LE_PUBLIC); - } else if( arg.equals("-mode") ) { - mode = Integer.valueOf(args[++i]).intValue(); - } else if( arg.equals("-bluetoothManager") && args.length > (i+1) ) { - bluetoothManagerClazzName = args[++i]; - } else if( arg.equals("-forever") ) { - forever = true; - } - } - // Enable BluetoothGattCharacteristic value cache and notification compatibility using direct_bt. - System.setProperty("direct_bt.tinyb.characteristic.compat", "true"); - - System.err.println("BluetoothManager "+bluetoothManagerClazzName); - System.err.println("dev_id "+dev_id); - System.err.println("device: "+mac); - System.err.println("mode "+mode); - - if ( null == mac ) { - System.err.println("Run with '-mac <device_address> [-mode <mode>] [-bluetoothManager <BluetoothManager-Implementation-Class-Name>]'"); - System.exit(-1); - } - - final boolean useAdapter = mode/10 > 0; - mode = mode %10; - - final boolean isDirectBT; - final BTManager manager; - { - BTManager _manager = null; - final BTFactory.ImplementationIdentifier implID = BTFactory.getImplementationIdentifier(bluetoothManagerClazzName); - if( null == implID ) { - System.err.println("Unable to find BluetoothManager "+bluetoothManagerClazzName); - System.exit(-1); - } - isDirectBT = BTFactory.DirectBTImplementationID.equals(implID); - System.err.println("Using BluetoothManager "+bluetoothManagerClazzName); - System.err.println("Using Implementation "+implID+", isDirectBT "+isDirectBT); - try { - _manager = BTFactory.getBTManager( implID ); - } catch (BTException | NoSuchMethodException | SecurityException - | IllegalAccessException | IllegalArgumentException - | InvocationTargetException | ClassNotFoundException e) { - System.err.println("Unable to instantiate BluetoothManager via "+implID); - e.printStackTrace(); - System.exit(-1); - } - manager = _manager; - } - final BTAdapter adapter; - { - final List<BTAdapter> adapters = manager.getAdapters(); - for(int i=0; i < adapters.size(); i++) { - System.err.println("Adapter["+i+"]: "+adapters.get(i)); - } - if( adapters.size() <= dev_id ) { - System.err.println("No adapter dev_id "+dev_id+" available, adapter count "+adapters.size()); - System.exit(-1); - } - adapter = adapters.get(dev_id); - if( !adapter.isPowered() ) { - System.err.println("Adapter not enabled: device "+adapter.getName()+", address "+adapter.getAddressAndType()+": "+adapter.toString()); - System.exit(-1); - } - } - - do { - final long t0 = System.currentTimeMillis();; - - if( useAdapter ) { - adapter.removeDiscoveredDevices(); - } - final HCIStatusCode discoveryStatus = useAdapter ? adapter.startDiscovery(true, false) : manager.startDiscovery(true, false); - - System.err.println("The discovery started: " + discoveryStatus + " for mac "+mac+", mode "+mode+", useAdapter "+useAdapter); - BTDevice sensor = null; - - if( 0 == mode ) { - if( useAdapter ) { - sensor = adapter.find(null, mac, TO_DISCOVER); - } else { - sensor = manager.find(null, mac.toString(), null, TO_DISCOVER); - } - } else { - boolean timeout = false; - while( null == sensor && !timeout ) { - final List<BTDevice> devices = useAdapter ? adapter.getDiscoveredDevices() : manager.getDevices(); - for(final Iterator<BTDevice> id = devices.iterator(); id.hasNext() && !timeout; ) { - final BTDevice d = id.next(); - if(d.getAddressAndType().equals(mac)) { - sensor = d; - break; - } - final long tn = System.currentTimeMillis(); - timeout = ( tn - t0 ) > TO_DISCOVER; - } - } - } - final long t1 = System.currentTimeMillis(); - if (sensor == null) { - System.err.println("No sensor found within "+(t1-t0)+" ms"); - System.exit(-1); - } - System.err.println("Found device in "+(t1-t0)+" ms: "); - printDevice(sensor); - - adapter.stopDiscovery(); - - final BooleanNotification connectedNotification = new BooleanNotification("Connected", t1); - final BooleanNotification servicesResolvedNotification = new BooleanNotification("ServicesResolved", t1); - sensor.enableConnectedNotifications(connectedNotification); - sensor.enableServicesResolvedNotifications(servicesResolvedNotification); - - final long t2; - final HCIStatusCode res; - if ( ( res = sensor.connect() ) == HCIStatusCode.SUCCESS ) { - t2 = System.currentTimeMillis(); - System.err.println("Sensor connect command in "+(t2-t1)+" ms"); - System.err.println("Sensor connectedNotification: "+connectedNotification.getValue()); - } else { - t2=0; - System.out.println("Connect command failed, res "+res); - System.exit(-1); - } - - synchronized( servicesResolvedNotification ) { - while( !servicesResolvedNotification.getValue() ) { - final long tn = System.currentTimeMillis(); - if( tn - t2 > 20000 ) { - break; // 20s TO - } - servicesResolvedNotification.wait(); - } - } - final long t3; - if ( servicesResolvedNotification.getValue() ) { - t3 = System.currentTimeMillis(); - System.err.println("Sensor servicesResolved in "+(t3-t2)+" ms, total "+(t3-t1)+" ms"); - } else { - t3=0; - System.out.println("Sensor service not resolved: "+(t3-t2)+" ms, total "+(t3-t1)+" ms"); - System.exit(-1); - } - - final List<BTGattService> allBluetoothServices = sensor.getServices(); - if (allBluetoothServices.isEmpty()) { - System.err.println("No BluetoothGattService found!"); - System.exit(1); - } - printAllServiceInfo(allBluetoothServices); - - sensor.disconnect(); - sensor.remove(); - } while( forever ); - } - private static void printDevice(final BTDevice device) { - System.err.println("Address = " + device.getAddressAndType()); - System.err.println(" Name = " + device.getName()); - System.err.println(" Connected = " + device.getConnected()); - System.err.println(); - } - private static void printAllServiceInfo(final List<BTGattService> allBluetoothServices) { - try { - for (final BTGattService service : allBluetoothServices) { - System.err.println("Service UUID: " + service.getUUID()); - final List<BTGattChar> v = service.getChars(); - for (final BTGattChar c : v) { - System.err.println(" Characteristic UUID: " + c.getUUID()); - - final List<BTGattDesc> descriptors = c.getDescriptors(); - - for (final BTGattDesc d : descriptors) { - System.err.println(" Descriptor UUID: " + d.getUUID()); - } - if (c.getUUID().contains("2a29-")) { - final byte[] tempRaw = c.readValue(); - System.err.println(" Manufacturer: " + new String(tempRaw)); - } - - if (c.getUUID().contains("2a28-")) { - final byte[] tempRaw = c.readValue(); - System.err.println(" Software: " + new String(tempRaw)); - } - - if (c.getUUID().contains("2a27-")) { - final byte[] tempRaw = c.readValue(); - System.err.println(" Hardware: " + new String(tempRaw)); - } - - if (c.getUUID().contains("2a26-")) { - final byte[] tempRaw = c.readValue(); - System.err.println(" Firmware: " + new String(tempRaw)); - } - - if (c.getUUID().contains("2a25-")) { - final byte[] tempRaw = c.readValue(); - System.err.println(" Serial: " + new String(tempRaw)); - } - - if (c.getUUID().contains("2a24-")) { - final byte[] tempRaw = c.readValue(); - System.err.println(" Model: " + new String(tempRaw)); - } - - if (c.getUUID().contains("2a23-")) { - final byte[] tempRaw = c.readValue(); - System.err.println(" System ID: " + BTUtils.bytesHexString(tempRaw, 0, -1, true)); - } - } - } - } catch (final RuntimeException e) { - } - } - static class BooleanNotification implements BTNotification<Boolean> { - private final long t0; - private final String name; - private boolean v; - - public BooleanNotification(final String name, final long t0) { - this.t0 = t0; - this.name = name; - this.v = false; - } - - @Override - public void run(final Boolean v) { - synchronized(this) { - final long t1 = System.currentTimeMillis(); - this.v = v.booleanValue(); - System.out.println("#### "+name+": "+v+" in td "+(t1-t0)+" ms!"); - this.notifyAll(); - } - } - public boolean getValue() { - synchronized(this) { - return v; - } - } - } -} diff --git a/examples/java/ScannerTinyB01.java b/examples/java/ScannerTinyB01.java deleted file mode 100644 index 50855a67..00000000 --- a/examples/java/ScannerTinyB01.java +++ /dev/null @@ -1,452 +0,0 @@ -/** - * Author: Sven Gothel <[email protected]> - * Copyright (c) 2020 Gothel Software e.K. - * Copyright (c) 2020 ZAFENA AB - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; - -import org.direct_bt.AdapterSettings; -import org.direct_bt.AdapterStatusListener; -import org.direct_bt.BDAddressAndType; -import org.direct_bt.BDAddressType; -import org.direct_bt.BTAdapter; -import org.direct_bt.BTDevice; -import org.direct_bt.BTException; -import org.direct_bt.BTFactory; -import org.direct_bt.BTGattChar; -import org.direct_bt.BTGattService; -import org.direct_bt.BTManager; -import org.direct_bt.BTNotification; -import org.direct_bt.BTType; -import org.direct_bt.BTUtils; -import org.direct_bt.EIRDataTypeSet; -import org.direct_bt.EUI48; -import org.direct_bt.BTGattCharListener; -import org.direct_bt.HCIStatusCode; -import org.direct_bt.ScanType; - -/** - * This Java scanner example is a TinyB backward compatible and not fully event driven. - * It simply polls found devices and shows certain results. - * However, the AdapterStatusListener is attached if supported. - * <p> - * This example does not represent the recommended utilization of Direct-BT. - * </p> - */ -public class ScannerTinyB01 { - static { - System.setProperty("org.tinyb.verbose", "true"); - } - /** 10,000 milliseconds */ - static long TO_DISCOVER = 10000; - - /** 20000 milliseconds */ - static long TO_CONNECT_AND_RESOLVE = 20000; - - static BDAddressAndType waitForDevice = BDAddressAndType.ANY_DEVICE; - static List<String> characteristicList = new ArrayList<String>(); - - public static void main(final String[] args) throws InterruptedException { - final boolean waitForEnter=false; - long t0_discovery = TO_DISCOVER; - String bluetoothManagerClazzName = BTFactory.DirectBTImplementationID.BluetoothManagerClassName; - int dev_id = 0; // default - int mode = 0; - int max_loops = 1; - boolean forever = false; - { - for(int i=0; i< args.length; i++) { - final String arg = args[i]; - - if( arg.equals("-dev_id") && args.length > (i+1) ) { - dev_id = Integer.valueOf(args[++i]).intValue(); - } else if( arg.equals("-mac") && args.length > (i+1) ) { - waitForDevice = new BDAddressAndType(new EUI48(args[++i]), BDAddressType.BDADDR_LE_PUBLIC); - } else if( arg.equals("-char") && args.length > (i+1) ) { - characteristicList.add(args[++i]); - } else if( arg.equals("-mode") && args.length > (i+1) ) { - mode = Integer.valueOf(args[++i]).intValue(); - } else if( arg.equals("-bluetoothManager") && args.length > (i+1) ) { - bluetoothManagerClazzName = args[++i]; - } else if( arg.equals("-t0_discovery") && args.length > (i+1) ) { - t0_discovery = Long.valueOf(args[++i]).longValue(); - } else if( arg.equals("-forever") ) { - forever = true; - } else if( arg.equals("-loops") && args.length > (i+1) ) { - max_loops = Integer.valueOf(args[++i]).intValue(); - } - } - - System.err.println("Run with '[-dev_id <adapter-index>] [-mac <device_address>] (-char <uuid>)* [-mode <mode>] [-bluetoothManager <BluetoothManager-Implementation-Class-Name>]'"); - } - // Enable BluetoothGattCharacteristic value cache and notification compatibility using direct_bt. - System.setProperty("direct_bt.tinyb.characteristic.compat", "true"); - - System.err.println("BluetoothManager "+bluetoothManagerClazzName); - System.err.println("dev_id "+dev_id); - System.err.println("waitForDevice: "+waitForDevice); - System.err.println("characteristicList: "+Arrays.toString(characteristicList.toArray())); - System.err.println("mode "+mode); - - if( waitForEnter ) { - System.err.println("Press ENTER to continue\n"); - try{ System.in.read(); - } catch(final Exception e) { } - } - - final boolean isDirectBT; - final BTManager manager; - { - BTManager _manager = null; - final BTFactory.ImplementationIdentifier implID = BTFactory.getImplementationIdentifier(bluetoothManagerClazzName); - if( null == implID ) { - System.err.println("Unable to find BluetoothManager "+bluetoothManagerClazzName); - System.exit(-1); - } - isDirectBT = BTFactory.DirectBTImplementationID.equals(implID); - System.err.println("Using BluetoothManager "+bluetoothManagerClazzName); - System.err.println("Using Implementation "+implID+", isDirectBT "+isDirectBT); - try { - _manager = BTFactory.getBTManager( implID ); - } catch (BTException | NoSuchMethodException | SecurityException - | IllegalAccessException | IllegalArgumentException - | InvocationTargetException | ClassNotFoundException e) { - System.err.println("Unable to instantiate BluetoothManager via "+implID); - e.printStackTrace(); - System.exit(-1); - } - manager = _manager; - } - final BTAdapter adapter; - { - final List<BTAdapter> adapters = manager.getAdapters(); - for(int i=0; i < adapters.size(); i++) { - System.err.println("Adapter["+i+"]: "+adapters.get(i)); - } - if( adapters.size() <= dev_id ) { - System.err.println("No adapter dev_id "+dev_id+" available, adapter count "+adapters.size()); - System.exit(-1); - } - adapter = adapters.get(dev_id); - if( !adapter.isPowered() ) { - System.err.println("Adapter not enabled: device "+adapter.getName()+", address "+adapter.getAddressAndType()+": "+adapter.toString()); - System.exit(-1); - } - } - - final BTDevice[] matchingDiscoveredDeviceBucket = { null }; - - final AdapterStatusListener statusListener = new AdapterStatusListener() { - @Override - public void adapterSettingsChanged(final BTAdapter adapter, final AdapterSettings oldmask, - final AdapterSettings newmask, final AdapterSettings changedmask, final long timestamp) { - System.err.println("****** SETTINGS: "+oldmask+" -> "+newmask+", changed "+changedmask); - System.err.println("Status Adapter:"); - System.err.println(adapter.toString()); - } - - @Override - public void discoveringChanged(final BTAdapter adapter, final ScanType currentMeta, final ScanType changedType, final boolean changedEnabled, final boolean keepAlive, final long timestamp) { - System.err.println("****** DISCOVERING: meta "+currentMeta+", changed["+changedType+", enabled "+changedEnabled+", keepAlive "+keepAlive+"] on "+adapter); - System.err.println("Status Adapter:"); - System.err.println(adapter.toString()); - } - - @Override - public boolean deviceFound(final BTDevice device, final long timestamp) { - final boolean matches = BDAddressAndType.ANY_DEVICE.matches(waitForDevice) || device.getAddressAndType().matches(waitForDevice); - System.err.println("****** FOUND__: "+device.toString()+" - match "+matches); - System.err.println("Status Adapter:"); - System.err.println(device.getAdapter().toString()); - - if( matches ) { - synchronized(matchingDiscoveredDeviceBucket) { - matchingDiscoveredDeviceBucket[0] = device; - matchingDiscoveredDeviceBucket.notifyAll(); - } - return true; - } else { - return false; - } - } - - @Override - public void deviceUpdated(final BTDevice device, final EIRDataTypeSet updateMask, final long timestamp) { - final boolean matches = BDAddressAndType.ANY_DEVICE.matches(waitForDevice) || device.getAddressAndType().equals(waitForDevice); - System.err.println("****** UPDATED: "+updateMask+" of "+device+" - match "+matches); - } - - @Override - public void deviceConnected(final BTDevice device, final short handle, final long timestamp) { - final boolean matches = BDAddressAndType.ANY_DEVICE.matches(waitForDevice) || device.getAddressAndType().equals(waitForDevice); - System.err.println("****** CONNECTED: "+device+" - matches "+matches); - } - - @Override - public void deviceDisconnected(final BTDevice device, final HCIStatusCode reason, final short handle, final long timestamp) { - System.err.println("****** DISCONNECTED: Reason "+reason+", old handle 0x"+Integer.toHexString(handle)+": "+device+" on "+device.getAdapter()); - } - - @Override - public String toString() { - return "AdapterStatusListener[user, per-adapter]"; - } - }; - adapter.addStatusListener(statusListener); - - final long timestamp_t0 = BTUtils.currentTimeMillis(); - - adapter.enableDiscoverableNotifications(new BooleanNotification("Discoverable", timestamp_t0)); - - adapter.enableDiscoveringNotifications(new BooleanNotification("Discovering", timestamp_t0)); - - adapter.enablePairableNotifications(new BooleanNotification("Pairable", timestamp_t0)); - - adapter.enablePoweredNotifications(new BooleanNotification("Powered", timestamp_t0)); - - int loop = 0; - try { - while( forever || loop < max_loops ) { - loop++; - System.err.println("****** Loop "+loop); - - final long t0 = BTUtils.currentTimeMillis(); - - final HCIStatusCode discoveryStatus = adapter.startDiscovery(true, false); - - System.err.println("The discovery started: " + discoveryStatus + " for mac "+waitForDevice+", mode "+mode); - if( HCIStatusCode.SUCCESS != discoveryStatus ) { - break; - } - BTDevice sensor = null; - - if( 0 == mode ) { - synchronized(matchingDiscoveredDeviceBucket) { - boolean timeout = false; - while( !timeout && null == matchingDiscoveredDeviceBucket[0] ) { - matchingDiscoveredDeviceBucket.wait(t0_discovery); - final long tn = BTUtils.currentTimeMillis(); - timeout = ( tn - t0 ) > t0_discovery; - } - sensor = matchingDiscoveredDeviceBucket[0]; - matchingDiscoveredDeviceBucket[0] = null; - } - } else if( 1 == mode ) { - boolean timeout = false; - while( null == sensor && !timeout ) { - sensor = adapter.find(null, waitForDevice, t0_discovery); - if( null == sensor ) { - final long tn = BTUtils.currentTimeMillis(); - timeout = ( tn - t0 ) > t0_discovery; - Thread.sleep(60); - } - } - } else { - boolean timeout = false; - while( null == sensor && !timeout ) { - final List<BTDevice> devices = adapter.getDiscoveredDevices(); - for(final Iterator<BTDevice> id = devices.iterator(); id.hasNext() && !timeout; ) { - final BTDevice d = id.next(); - if( BDAddressAndType.ANY_DEVICE.matches(waitForDevice) || d.getAddressAndType().equals(waitForDevice) ) { - sensor = d; - break; - } - } - if( null == sensor ) { - final long tn = BTUtils.currentTimeMillis(); - timeout = ( tn - t0 ) > t0_discovery; - Thread.sleep(60); - } - } - } - final long t1 = BTUtils.currentTimeMillis(); - if (sensor == null) { - System.err.println("No sensor found within "+(t1-t0)+" ms"); - continue; // forever loop - } - System.err.println("Found device in "+(t1-t0)+" ms: "); - printDevice(sensor); - - adapter.stopDiscovery(); - - final BooleanNotification connectedNotification = new BooleanNotification("Connected", t1); - final BooleanNotification servicesResolvedNotification = new BooleanNotification("ServicesResolved", t1); - sensor.enableConnectedNotifications(connectedNotification); - sensor.enableServicesResolvedNotifications(servicesResolvedNotification); - - final long t2 = BTUtils.currentTimeMillis(); - final long t3; - HCIStatusCode res; - if ( ( res = sensor.connect() ) == HCIStatusCode.SUCCESS ) { - t3 = BTUtils.currentTimeMillis(); - System.err.println("Sensor connect issued: "+(t3-t2)+" ms, total "+(t3-t0)+" ms"); - System.err.println("Sensor connectedNotification: "+connectedNotification.getValue()); - } else { - t3 = BTUtils.currentTimeMillis(); - System.out.println("connect command failed, res "+res+": "+(t3-t2)+" ms, total "+(t3-t0)+" ms"); - // we tolerate the failed immediate connect, as it might happen at a later time - } - - synchronized( servicesResolvedNotification ) { - while( !servicesResolvedNotification.getValue() ) { - final long tn = BTUtils.currentTimeMillis(); - if( tn - t3 > TO_CONNECT_AND_RESOLVE ) { - break; - } - servicesResolvedNotification.wait(100); - } - } - final long t4; - if ( servicesResolvedNotification.getValue() ) { - t4 = BTUtils.currentTimeMillis(); - System.err.println("Sensor servicesResolved: "+(t4-t3)+" ms, total "+(t4-t0)+" ms"); - } else { - t4 = BTUtils.currentTimeMillis(); - System.out.println("Sensor service not resolved: "+(t4-t3)+" ms, total "+(t4-t0)+" ms"); - System.exit(-1); - } - - final List<BTGattService> primServices = sensor.getServices(); - if ( null == primServices || primServices.isEmpty() ) { - System.err.println("No BluetoothGattService found!"); - } else { - { - for(final String characteristic : characteristicList) { - final BTGattChar char0 = (BTGattChar) - manager.find(BTType.GATT_CHARACTERISTIC, null, characteristic, null, 1000); - final BTGattChar char1 = (BTGattChar) - manager.find(BTType.GATT_CHARACTERISTIC, null, characteristic, sensor.getAdapter(), 1000); - final BTGattChar char2 = (BTGattChar) - manager.find(BTType.GATT_CHARACTERISTIC, null, characteristic, sensor, 1000); - System.err.println("Char UUID "+characteristic); - System.err.println(" over manager: "+char0); - System.err.println(" over adapter: "+char1); - System.err.println(" over device : "+char2); - } - } - - final BTGattCharListener myCharacteristicListener = new BTGattCharListener(null) { - @Override - public void notificationReceived(final BTGattChar charDecl, - final byte[] value, final long timestamp) { - System.err.println("****** GATT notificationReceived: "+charDecl+ - ", value "+BTUtils.bytesHexString(value, 0, -1, true)); - } - - @Override - public void indicationReceived(final BTGattChar charDecl, - final byte[] value, final long timestamp, final boolean confirmationSent) { - System.err.println("****** GATT indicationReceived: "+charDecl+ - ", value "+BTUtils.bytesHexString(value, 0, -1, true)); - } - }; - final boolean addedCharacteristicListenerRes = - BTGattService.addCharListenerToAll(sensor, primServices, myCharacteristicListener); - System.err.println("Added GATTCharacteristicListener: "+addedCharacteristicListenerRes); - - int i=0, j=0; - for(final Iterator<BTGattService> srvIter = primServices.iterator(); srvIter.hasNext(); i++) { - final BTGattService primService = srvIter.next(); - System.err.printf(" [%02d] Service %s\n", i, primService.toString()); - System.err.printf(" [%02d] Service Characteristics\n", i); - final List<BTGattChar> serviceCharacteristics = primService.getChars(); - for(final Iterator<BTGattChar> charIter = serviceCharacteristics.iterator(); charIter.hasNext(); j++) { - final BTGattChar serviceChar = charIter.next(); - System.err.printf(" [%02d.%02d] Decla: %s\n", i, j, serviceChar.toString()); - final List<String> properties = Arrays.asList(serviceChar.getFlags()); - if( properties.contains("read") ) { - try { - final byte[] value = serviceChar.readValue(); - final String svalue = BTUtils.decodeUTF8String(value, 0, value.length); - System.err.printf(" [%02d.%02d] Value: %s ('%s')\n", - i, j, BTUtils.bytesHexString(value, 0, -1, true), svalue); - } catch( final Exception ex) { - System.err.println("Caught "+ex.getMessage()); - ex.printStackTrace(); - } - } - } - } - Thread.sleep(1000); // FIXME: Wait for notifications - - final boolean remRes = BTGattService.removeCharListenerFromAll(sensor, primServices, myCharacteristicListener); - System.err.println("Removed GATTCharacteristicListener: "+remRes); - } - sensor.disconnect(); - System.err.println("ScannerTinyB01 04 ...: "+adapter); - } - } catch (final Throwable t) { - System.err.println("Caught: "+t.getMessage()); - t.printStackTrace(); - } - - System.err.println("ScannerTinyB01 02 clear listener etc .. "); - adapter.removeStatusListener(statusListener); - adapter.disableDiscoverableNotifications(); - adapter.disableDiscoveringNotifications(); - adapter.disablePairableNotifications(); - adapter.disablePoweredNotifications(); - - System.err.println("ScannerTinyB01 03 close: "+adapter); - adapter.close(); - System.err.println("ScannerTinyB01 04"); - manager.shutdown(); - System.err.println("ScannerTinyB01 XX"); - } - private static void printDevice(final BTDevice device) { - System.err.println("Address = " + device.getAddressAndType()); - System.err.println(" Name = " + device.getName()); - System.err.println(" Connected = " + device.getConnected()); - System.err.println(); - } - static class BooleanNotification implements BTNotification<Boolean> { - private final long t0; - private final String name; - private boolean v; - - public BooleanNotification(final String name, final long t0) { - this.t0 = t0; - this.name = name; - this.v = false; - } - - @Override - public void run(final Boolean v) { - synchronized(this) { - final long t1 = BTUtils.currentTimeMillis(); - this.v = v.booleanValue(); - System.out.println("###### "+name+": "+v+" in td "+(t1-t0)+" ms!"); - this.notifyAll(); - } - } - public boolean getValue() { - synchronized(this) { - return v; - } - } - } -} diff --git a/examples/java/ScannerTinyB02.java b/examples/java/ScannerTinyB02.java deleted file mode 100644 index cdbbd2dd..00000000 --- a/examples/java/ScannerTinyB02.java +++ /dev/null @@ -1,390 +0,0 @@ -/** - * Author: Sven Gothel <[email protected]> - * Copyright (c) 2020 Gothel Software e.K. - * Copyright (c) 2020 ZAFENA AB - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -import java.lang.reflect.InvocationTargetException; -import java.util.Iterator; -import java.util.List; - -import org.direct_bt.AdapterSettings; -import org.direct_bt.AdapterStatusListener; -import org.direct_bt.BDAddressAndType; -import org.direct_bt.BDAddressType; -import org.direct_bt.BTAdapter; -import org.direct_bt.BTDevice; -import org.direct_bt.BTException; -import org.direct_bt.BTFactory; -import org.direct_bt.BTManager; -import org.direct_bt.BTNotification; -import org.direct_bt.BTUtils; -import org.direct_bt.EIRDataTypeSet; -import org.direct_bt.EUI48; -import org.direct_bt.HCIStatusCode; -import org.direct_bt.ScanType; - -/** - * Test and debugging application for certain situation. - * <p> - * Code will in 'in flux' and is not intended as an example. - * </p> - */ -public class ScannerTinyB02 { - static { - System.setProperty("org.tinyb.verbose", "true"); - } - /** 10,000 milliseconds */ - static long TO_DISCOVER = 10000; - - /** 300 milliseconds */ - static long TO_CONNECT = 300; - - static BDAddressAndType waitForDevice = BDAddressAndType.ANY_DEVICE; - - public static void main(final String[] args) throws InterruptedException { - final boolean waitForEnter=false; - long t0_discovery = TO_DISCOVER; - int factory = 0; - int dev_id = 0; // default - int mode = 3; - int max_loops = 5; - boolean forever = false; - { - for(int i=0; i< args.length; i++) { - final String arg = args[i]; - - if( arg.equals("-dev_id") && args.length > (i+1) ) { - dev_id = Integer.valueOf(args[++i]).intValue(); - } else if( arg.equals("-mac") && args.length > (i+1) ) { - waitForDevice = new BDAddressAndType(new EUI48(args[++i]), BDAddressType.BDADDR_LE_PUBLIC); - } else if( arg.equals("-mode") && args.length > (i+1) ) { - mode = Integer.valueOf(args[++i]).intValue(); - } else if( arg.equals("-factory") && args.length > (i+1) ) { - factory = Integer.valueOf(args[++i]).intValue(); - } else if( arg.equals("-t0_discovery") && args.length > (i+1) ) { - t0_discovery = Long.valueOf(args[++i]).longValue(); - } else if( arg.equals("-forever") ) { - forever = true; - } else if( arg.equals("-loops") && args.length > (i+1) ) { - max_loops = Integer.valueOf(args[++i]).intValue(); - } - } - - System.err.println("Run with '[-dev_id <adapter-index>] [-mac <device_address>] [-mode <mode>] [-factory <BluetoothManager-Factory-Implementation-Class>]'"); - } - - System.err.println("dev_id "+dev_id); - System.err.println("waitForDevice: "+waitForDevice); - - if( waitForEnter ) { - System.err.println("Press ENTER to continue\n"); - try{ System.in.read(); - } catch(final Exception e) { } - } - - final BTFactory.ImplementationIdentifier implID = 0 == factory ? BTFactory.DirectBTImplementationID : BTFactory.DBusImplementationID; - final BTManager manager; - { - BTManager _manager = null; - try { - _manager = BTFactory.getBTManager( implID ); - } catch (BTException | NoSuchMethodException | SecurityException - | IllegalAccessException | IllegalArgumentException - | InvocationTargetException | ClassNotFoundException e) { - System.err.println("Unable to instantiate BluetoothManager via "+implID); - e.printStackTrace(); - System.exit(-1); - } - manager = _manager; - } - final BTAdapter adapter; - { - final List<BTAdapter> adapters = manager.getAdapters(); - for(int i=0; i < adapters.size(); i++) { - System.err.println("Adapter["+i+"]: "+adapters.get(i)); - } - if( adapters.size() <= dev_id ) { - System.err.println("No adapter dev_id "+dev_id+" available, adapter count "+adapters.size()); - System.exit(-1); - } - adapter = adapters.get(dev_id); - if( !adapter.isPowered() ) { - System.err.println("Adapter not enabled: device "+adapter.getName()+", address "+adapter.getAddressAndType()+": "+adapter.toString()); - System.exit(-1); - } - } - - final BTDevice[] matchingDiscoveredDeviceBucket = { null }; - - final AdapterStatusListener statusListener = new AdapterStatusListener() { - @Override - public void adapterSettingsChanged(final BTAdapter adapter, final AdapterSettings oldmask, - final AdapterSettings newmask, final AdapterSettings changedmask, final long timestamp) { - System.err.println("****** SETTINGS: "+oldmask+" -> "+newmask+", changed "+changedmask); - System.err.println("Status Adapter:"); - System.err.println(adapter.toString()); - } - - @Override - public void discoveringChanged(final BTAdapter adapter, final ScanType currentMeta, final ScanType changedType, final boolean changedEnabled, final boolean keepAlive, final long timestamp) { - System.err.println("****** DISCOVERING: meta "+currentMeta+", changed["+changedType+", enabled "+changedEnabled+", keepAlive "+keepAlive+"] on "+adapter); - System.err.println("Status Adapter:"); - System.err.println(adapter.toString()); - } - - @Override - public boolean deviceFound(final BTDevice device, final long timestamp) { - final boolean matches = BDAddressAndType.ANY_DEVICE.matches(waitForDevice) || device.getAddressAndType().equals(waitForDevice); - System.err.println("****** FOUND__: "+device.toString()+" - match "+matches); - System.err.println("Status Adapter:"); - System.err.println(device.getAdapter().toString()); - - if( matches ) { - synchronized(matchingDiscoveredDeviceBucket) { - matchingDiscoveredDeviceBucket[0] = device; - matchingDiscoveredDeviceBucket.notifyAll(); - } - return true; - } else { - return false; - } - } - - @Override - public void deviceUpdated(final BTDevice device, final EIRDataTypeSet updateMask, final long timestamp) { - final boolean matches = BDAddressAndType .ANY_DEVICE.matches(waitForDevice) || device.getAddressAndType().equals(waitForDevice); - System.err.println("****** UPDATED: "+updateMask+" of "+device+" - match "+matches); - } - - @Override - public void deviceConnected(final BTDevice device, final short handle, final long timestamp) { - final boolean matches = BDAddressAndType .ANY_DEVICE.matches(waitForDevice) || device.getAddressAndType().equals(waitForDevice); - System.err.println("****** CONNECTED: "+device+" - matches "+matches); - } - - @Override - public void deviceDisconnected(final BTDevice device, final HCIStatusCode reason, final short handle, final long timestamp) { - System.err.println("****** DISCONNECTED: Reason "+reason+", old handle 0x"+Integer.toHexString(handle)+": "+device+" on "+device.getAdapter()); - } - - @Override - public String toString() { - return "AdapterStatusListener[user, per-adapter]"; - } - }; - adapter.addStatusListener(statusListener); - - final long timestamp_t0 = BTUtils.currentTimeMillis(); - - adapter.enableDiscoverableNotifications(new BooleanNotification("Discoverable", timestamp_t0)); - - adapter.enableDiscoveringNotifications(new BooleanNotification("Discovering", timestamp_t0)); - - adapter.enablePairableNotifications(new BooleanNotification("Pairable", timestamp_t0)); - - adapter.enablePoweredNotifications(new BooleanNotification("Powered", timestamp_t0)); - - int loop = 0; - try { - while( forever || loop < max_loops ) { - loop++; - System.err.println("****** Loop "+loop); - - final long t0 = BTUtils.currentTimeMillis(); - - final boolean discoveryStarted = true; // adapter.startDiscovery(true); - { - final Thread lalaTask = new Thread( new Runnable() { - @Override - public void run() { - adapter.startDiscovery(true, false); - } - }, "lala"); - lalaTask.setDaemon(true); // detach thread - lalaTask.start(); - } - - System.err.println("The discovery started: " + (discoveryStarted ? "true" : "false") + " for mac "+waitForDevice+", mode "+mode); - if( !discoveryStarted ) { - break; - } - BTDevice sensor = null; - - if( 0 == mode ) { - synchronized(matchingDiscoveredDeviceBucket) { - boolean timeout = false; - while( !timeout && null == matchingDiscoveredDeviceBucket[0] ) { - matchingDiscoveredDeviceBucket.wait(t0_discovery); - final long tn = BTUtils.currentTimeMillis(); - timeout = ( tn - t0 ) > t0_discovery; - } - sensor = matchingDiscoveredDeviceBucket[0]; - matchingDiscoveredDeviceBucket[0] = null; - } - } else if( 1 == mode ) { - sensor = adapter.find(null, waitForDevice, t0_discovery); - } else { - boolean timeout = false; - while( null == sensor && !timeout ) { - final List<BTDevice> devices = adapter.getDiscoveredDevices(); - int i=0; - for(final Iterator<BTDevice> id = devices.iterator(); id.hasNext() && !timeout; ) { - final BTDevice d = id.next(); - final boolean match = BDAddressAndType .ANY_DEVICE.matches(waitForDevice) || d.getAddressAndType().equals(waitForDevice); - System.err.println("****** Has "+i+"/"+devices.size()+": match "+match+": "+d.toString()); - i++; - if( match ) { - sensor = d; - break; - } - } - if( null == sensor ) { - final long tn = BTUtils.currentTimeMillis(); - timeout = ( tn - t0 ) > t0_discovery; - System.err.print("."); - Thread.sleep(60); - } - } - } - final long t1 = BTUtils.currentTimeMillis(); - if (sensor == null) { - System.err.println("No sensor found within "+(t1-t0)+" ms"); - continue; // forever loop - } - System.err.println("Found device in "+(t1-t0)+" ms: "); - printDevice(sensor); - - // adapter.stopDiscovery(); - { - final Thread lalaTask = new Thread( new Runnable() { - @Override - public void run() { - adapter.stopDiscovery(); - } - }, "lala"); - lalaTask.setDaemon(true); // detach thread - lalaTask.start(); - } - - final BooleanNotification connectedNotification = new BooleanNotification("Connected", t1); - final BooleanNotification servicesResolvedNotification = new BooleanNotification("ServicesResolved", t1); - sensor.enableConnectedNotifications(connectedNotification); - sensor.enableServicesResolvedNotifications(servicesResolvedNotification); - - final long t2 = BTUtils.currentTimeMillis(); - final long t3; - HCIStatusCode res; - if ( (res = sensor.connect() ) == HCIStatusCode.SUCCESS ) { - t3 = BTUtils.currentTimeMillis(); - System.err.println("Sensor connect issued: "+(t3-t2)+" ms, total "+(t3-t0)+" ms"); - System.err.println("Sensor connectedNotification: "+connectedNotification.getValue()); - } else { - t3 = BTUtils.currentTimeMillis(); - System.out.println("connect command failed, res "+res+": "+(t3-t2)+" ms, total "+(t3-t0)+" ms"); - // we tolerate the failed immediate connect, as it might happen at a later time - } - - synchronized( servicesResolvedNotification ) { - while( !servicesResolvedNotification.getValue() ) { - final long tn = BTUtils.currentTimeMillis(); - if( tn - t3 > TO_CONNECT ) { - break; - } - servicesResolvedNotification.wait(100); - } - } - final long t4; - if ( servicesResolvedNotification.getValue() ) { - t4 = BTUtils.currentTimeMillis(); - System.err.println("Sensor servicesResolved: "+(t4-t3)+" ms, total "+(t4-t0)+" ms"); - } else { - t4 = BTUtils.currentTimeMillis(); - System.out.println("Could not connect device: "+(t4-t3)+" ms, total "+(t4-t0)+" ms"); - // System.exit(-1); - } - - final BTDevice _sensor = sensor; - final Thread lalaTask = new Thread( new Runnable() { - @Override - public void run() { - _sensor.disconnect(); - } - }, "lala"); - lalaTask.setDaemon(true); // detach thread - lalaTask.start(); - - // Thread.sleep(60); - // sensor.connect(); - continue; - } - } catch (final Throwable t) { - System.err.println("Caught: "+t.getMessage()); - t.printStackTrace(); - } - - System.err.println("ScannerTinyB01 02 clear listener etc .. "); - adapter.removeStatusListener(statusListener); - adapter.disableDiscoverableNotifications(); - adapter.disableDiscoveringNotifications(); - adapter.disablePairableNotifications(); - adapter.disablePoweredNotifications(); - - System.err.println("ScannerTinyB01 03 close: "+adapter); - adapter.close(); - System.err.println("ScannerTinyB01 04"); - manager.shutdown(); - System.err.println("ScannerTinyB01 XX"); - } - private static void printDevice(final BTDevice device) { - System.err.println("Address = " + device.getAddressAndType()); - System.err.println(" Name = " + device.getName()); - System.err.println(" Connected = " + device.getConnected()); - System.err.println(); - } - static class BooleanNotification implements BTNotification<Boolean> { - private final long t0; - private final String name; - private boolean v; - - public BooleanNotification(final String name, final long t0) { - this.t0 = t0; - this.name = name; - this.v = false; - } - - @Override - public void run(final Boolean v) { - synchronized(this) { - final long t1 = BTUtils.currentTimeMillis(); - this.v = v.booleanValue(); - System.out.println("###### "+name+": "+v+" in td "+(t1-t0)+" ms!"); - this.notifyAll(); - } - } - public boolean getValue() { - synchronized(this) { - return v; - } - } - } -} diff --git a/examples/tinyb/TinyBTest01.cpp b/examples/tinyb/TinyBTest01.cpp deleted file mode 100644 index c50ad776..00000000 --- a/examples/tinyb/TinyBTest01.cpp +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Author: Petre Eftime <[email protected]> - * Copyright (c) 2016 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#include <tinyb.hpp> - -#include <vector> -#include <iostream> -#include <thread> -#include <csignal> -#include <condition_variable> - -using namespace tinyb; - -int main(int argc, char **argv) -{ - if (argc < 2) { - std::cerr << "Run as: " << argv[0] << " <device_address>" << std::endl; - exit(1); - } - - BluetoothManager *manager = nullptr; - try { - manager = BluetoothManager::get_bluetooth_manager(); - } catch(const std::runtime_error& e) { - std::cerr << "Error while initializing libtinyb: " << e.what() << std::endl; - exit(1); - } - - /* Start the discovery of devices */ - bool ret = manager->start_discovery(); - std::cout << "Started = " << (ret ? "true" : "false") << std::endl; - - std::unique_ptr<BluetoothGattService> temperature_service; - - std::string device_mac(argv[1]); - auto sensor_tag = manager->find<BluetoothDevice>(nullptr, &device_mac, nullptr, std::chrono::seconds(10)); - if (sensor_tag == nullptr) { - std::cout << "Device not found" << std::endl; - return 1; - } - sensor_tag->enable_connected_notifications([] (BluetoothDevice &d, bool connected, void *usedata) - { if (connected) std::cout << "Connected " << d.get_name() << std::endl; }, NULL); - - if (sensor_tag != nullptr) { - /* Connect to the device and get the list of services exposed by it */ - sensor_tag->connect(); - std::string service_uuid("f000aa00-0451-4000-b000-000000000000"); - std::cout << "Waiting for service " << service_uuid << "to be discovered" << std::endl; - temperature_service = sensor_tag->find(&service_uuid); - } else { - ret = manager->stop_discovery(); - std::cerr << "SensorTag not found after 30 seconds, exiting" << std::endl; - return 1; - } - - /* Stop the discovery (the device was found or timeout was over) */ - ret = manager->stop_discovery(); - std::cout << "Stopped = " << (ret ? "true" : "false") << std::endl; - - auto value_uuid = std::string("f000aa01-0451-4000-b000-000000000000"); - auto temp_value = temperature_service->find(&value_uuid); - - auto config_uuid = std::string("f000aa02-0451-4000-b000-000000000000"); - auto temp_config = temperature_service->find(&config_uuid); - - auto period_uuid = std::string("f000aa03-0451-4000-b000-000000000000"); - auto temp_period = temperature_service->find(&period_uuid); - - /* Activate the temperature measurements */ - std::vector<unsigned char> config_on {0x01}; - temp_config->write_value(config_on); - temp_period->write_value({100}); - temp_value->enable_value_notifications(data_callback, nullptr); - - std::mutex m; - std::unique_lock<std::mutex> lock(m); - - std::signal(SIGINT, signal_handler); - - cv.wait(lock); - - /* Disconnect from the device */ - if (sensor_tag != nullptr) - sensor_tag->disconnect(); -} diff --git a/examples/tinyb/asynctinyb.cpp b/examples/tinyb/asynctinyb.cpp deleted file mode 100644 index f2d5756c..00000000 --- a/examples/tinyb/asynctinyb.cpp +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Author: Petre Eftime <[email protected]> - * Copyright (c) 2015 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#include <tinyb.hpp> - -#include <vector> -#include <iostream> -#include <thread> -#include <atomic> -#include <csignal> - -using namespace tinyb; - - - -/** Converts a raw temperature read from the sensor to a Celsius value. - * @param[in] raw_temp The temperature read from the sensor (two bytes) - * @return The Celsius value of the temperature - */ -static float celsius_temp(uint16_t raw_temp) -{ - const float SCALE_LSB = 0.03125; - return ((float)(raw_temp >> 2)) * SCALE_LSB; -} - -std::atomic<bool> running(true); - -void signal_handler(int signum) -{ - if (signum == SIGINT) { - running = false; - } -} - -/** This program reads the temperature from a - * TI Sensor Tag(http://www.ti.com/ww/en/wireless_connectivity/sensortag2015/?INTC=SensorTag&HQS=sensortag) - * Pass the MAC address of the sensor as the first parameter of the program. - */ -int main(int argc, char **argv) -{ - if (argc < 2) { - std::cerr << "Run as: " << argv[0] << " <device_address>" << std::endl; - exit(1); - } - - BluetoothManager *manager = nullptr; - try { - manager = BluetoothManager::get_bluetooth_manager(); - } catch(const std::runtime_error& e) { - std::cerr << "Error while initializing libtinyb: " << e.what() << std::endl; - exit(1); - } - - /* Start the discovery of devices */ - bool ret = manager->start_discovery(); - std::cout << "Started = " << (ret ? "true" : "false") << std::endl; - - std::unique_ptr<BluetoothGattService> temperature_service; - - std::string device_mac(argv[1]); - auto sensor_tag = manager->find<BluetoothDevice>(nullptr, &device_mac, nullptr, std::chrono::seconds(10)); - if (sensor_tag == nullptr) { - std::cout << "Device not found" << std::endl; - return 1; - } - - if (sensor_tag == nullptr) { - ret = manager->stop_discovery(); - std::cerr << "SensorTag not found after 30 seconds, exiting" << std::endl; - return 1; - } - - /* Connect to the device and get the list of services exposed by it */ - sensor_tag->connect(); - std::string service_uuid("f000aa00-0451-4000-b000-000000000000"); - std::cout << "Waiting for service " << service_uuid << " to be discovered" << std::endl; - temperature_service = sensor_tag->find(&service_uuid); - - /* Stop the discovery (the device was found or timeout was over) */ - ret = manager->stop_discovery(); - std::cout << "Stopped = " << (ret ? "true" : "false") << std::endl; - - auto value_uuid = std::string("f000aa01-0451-4000-b000-000000000000"); - auto temp_value = temperature_service->find(&value_uuid); - - auto config_uuid = std::string("f000aa02-0451-4000-b000-000000000000"); - auto temp_config = temperature_service->find(&config_uuid); - - auto period_uuid = std::string("f000aa03-0451-4000-b000-000000000000"); - auto temp_period = temperature_service->find(&period_uuid); - - /* Activate the temperature measurements */ - try { - std::vector<unsigned char> config_on {0x01}; - temp_config->write_value(config_on); - std::signal(SIGINT, signal_handler); - } catch (std::exception &e) { - std::cout << "Error: " << e.what() << std::endl; - running = false; - } - - while (running) { - /* Read temperature data and display it */ - try { - std::vector<unsigned char> response = temp_value->read_value(); - unsigned char *data; - unsigned int size = response.size(); - if (size > 0) { - data = response.data(); - - std::cout << "Raw data=["; - for (unsigned i = 0; i < response.size(); i++) - std::cout << std::hex << static_cast<int>(data[i]) << ", "; - std::cout << "] "; - - uint16_t ambient_temp, object_temp; - object_temp = data[0] | (data[1] << 8); - ambient_temp = data[2] | (data[3] << 8); - - std::cout << "Ambient temp: " << celsius_temp(ambient_temp) << "C "; - std::cout << "Object temp: " << celsius_temp(object_temp) << "C "; - std::cout << std::endl; - } - - std::this_thread::sleep_for(std::chrono::seconds(1)); - - } catch (std::exception &e) { - std::cout << "Error: " << e.what() << std::endl; - break; - } - } - - /* Disconnect from the device */ - try { - sensor_tag->disconnect(); - } catch (std::exception &e) { - std::cout << "Error: " << e.what() << std::endl; - } - return 0; -} diff --git a/examples/tinyb/checkinit.cpp b/examples/tinyb/checkinit.cpp deleted file mode 100644 index e437ff4a..00000000 --- a/examples/tinyb/checkinit.cpp +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Author: Petre Eftime <[email protected]> - * Copyright (c) 2015 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#include <tinyb.hpp> -#include <iostream> - -using namespace tinyb; - -int main(int argc, char **argv) -{ - (void)argc; - (void)argv; - try { - BluetoothManager *manager = BluetoothManager::get_bluetooth_manager(); - (void)manager; - } catch(const std::runtime_error& e) { - std::cout << "Expected error: " << e.what() << std::endl; - return 1; - } - - std::cout << "Initialization was succesful." << std::endl; - return 0; -} diff --git a/examples/tinyb/esstinyb.cpp b/examples/tinyb/esstinyb.cpp deleted file mode 100644 index 9aa302cc..00000000 --- a/examples/tinyb/esstinyb.cpp +++ /dev/null @@ -1,209 +0,0 @@ -/* - * Author: Henry Bruce <[email protected]> - * Copyright (c) 2016 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -/* - * This sample looks for a device that implements the Environmental Sensing - * Service and supports temperatures notifications. It then starts notfication - * updates and displays samples until CRTL+C is hit. - * Sample has been tested with the following devices: - * - Zephyr Environmental Sensing Profile sample running on Arduino 101 - */ - -#include <tinyb.hpp> -#include <tinyb/BluetoothException.hpp> -#include <jau/basic_types.hpp> -#include <vector> -#include <algorithm> -#include <iostream> -#include <iomanip> -#include <thread> -#include <csignal> -#include <condition_variable> - -using namespace tinyb; - -#define BT_MEAS_INTERVAL_INDEX 6 - -struct es_measurement { - uint16_t reserved; - uint8_t sampling_func; - uint32_t meas_period; - uint32_t update_interval; - uint8_t application; - uint8_t meas_uncertainty; -}; - - -const std::string BT_UUID_ESS = "0000181a-0000-1000-8000-00805f9b34fb"; -const std::string BT_UUID_CUD = "00002901-0000-1000-8000-00805f9b34fb"; -const std::string BT_UUID_TEMPERATURE = "00002a6e-0000-1000-8000-00805f9b34fb"; -const std::string BT_UUID_MEASUREMENT = "0000290c-0000-1000-8000-00805f9b34fb"; -const std::string BT_NOFITY_FLAG = "notify"; - -std::condition_variable cv; - - -static void signal_handler(int signum) -{ - if (signum == SIGINT) { - cv.notify_all(); - } -} - - -static void wait_ctrl_c() -{ - std::mutex m; - std::unique_lock<std::mutex> lock(m); - std::signal(SIGINT, signal_handler); - cv.wait(lock); -} - - -void data_callback(BluetoothGattCharacteristic &c, std::vector<unsigned char> &data, void *userdata) -{ - (void)c; - (void)userdata; - // unsigned char *data_c; - unsigned int size = data.size(); - if (size == 2) { - jau::packed_t<int16_t>* raw_data = reinterpret_cast<jau::packed_t<int16_t>*>( data.data() ); - // int16_t* raw_data = reinterpret_cast<int16_t*>(data.data()); - std::cout << "Raw data = " << std::hex << std::setfill('0') << std::setw(4) << raw_data->store << ". "; - uint16_t temp = (raw_data->store + 50) / 100; - std::cout << "Temperature = " << std::dec << temp << "C " << std::endl; - } -} - - -/** This program reads the temperature from a device running the Environmental Sensing Senvice. - */ -int main(int argc, char **argv) -{ - (void)argc; - (void)argv; - BluetoothManager *manager = nullptr; - try { - manager = BluetoothManager::get_bluetooth_manager(); - } catch(const std::runtime_error& e) { - std::cerr << "Error while initializing libtinyb: " << e.what() << std::endl; - exit(1); - } - - std::unique_ptr<BluetoothAdapter> adapter = manager->get_default_adapter(); - BluetoothDevice *ess_device = NULL; - - // Start the discovery of devices */ - bool ret = manager->start_discovery(); - if (!ret) { - std::cout << "Failed to start discovery" << std::endl; - return 1; - } - std::cout << "Discovering BLE devices"; - size_t num_devices = 0; - bool no_new_devices = false; - std::vector<std::unique_ptr<BluetoothDevice>> list_devices; - while (ess_device == NULL && !no_new_devices) { - list_devices = manager->get_devices(); - std::cout << "." << std::flush; - if (list_devices.size() > 0 && list_devices.size() == num_devices) - no_new_devices = true; - num_devices = list_devices.size(); - - // Look for active ESS device - for (auto it = list_devices.begin(); it != list_devices.end(); ++it) { - if ((*it)->get_rssi() != 0) { - auto list_uuids = (*it)->get_uuids(); - for (auto uuit = list_uuids.begin(); uuit != list_uuids.end(); ++uuit) { - if (*(uuit) == BT_UUID_ESS) { - ess_device = (*it).release(); - break; - } - } - } - } - - if (ess_device == NULL) - std::this_thread::sleep_for(std::chrono::seconds(4)); - } - ret = manager->stop_discovery(); - std::cout << std::endl; - - // Now try to connect - if (ess_device != NULL) { - std::cout << "Connecting to " << ess_device->get_name() << " with addr " << ess_device->get_address() << std::flush; - try { - if (ess_device->connect()) { - std::cout << ". Connected" << std::endl; - } - else - std::cout << ". Failed" << std::endl; - } catch (BluetoothException& e) { - std::cout << std::endl << e.what() << std::endl; - return 1; - } - } else { - std::cout << "ESS device not found." << std::endl; - delete ess_device; - return 1; - } - - if (!ess_device->get_connected()) { - delete ess_device; - return 1; - } - - std::cout << "Getting environmental service" << std::endl; - std::unique_ptr<BluetoothGattService> environmental_service = ess_device->find(const_cast<std::string*>(&BT_UUID_ESS)); - std::cout << "Getting temperature characteristic" << std::endl; - std::unique_ptr<BluetoothGattCharacteristic> temp_characteristic = environmental_service->find(const_cast<std::string*>(&BT_UUID_TEMPERATURE)); - - std::vector<std::string> list_flags = temp_characteristic->get_flags(); - if (std::find(list_flags.begin(), list_flags.end(), BT_NOFITY_FLAG) != list_flags.end()) { - std::unique_ptr<BluetoothGattDescriptor> meas = temp_characteristic->find(const_cast<std::string*>(&BT_UUID_MEASUREMENT)); - std::unique_ptr<BluetoothGattDescriptor> cud = temp_characteristic->find(const_cast<std::string*>(&BT_UUID_CUD)); - std::vector<unsigned char> name_bytes = cud->read_value(); - std::string name(reinterpret_cast<char *>(name_bytes.data()), name_bytes.size()); - std::cout << "Sensor name is '" << name << "'" << std::endl; - std::vector<unsigned char> meas_bytes = meas->read_value(); - int notification_interval = meas_bytes[BT_MEAS_INTERVAL_INDEX]; - std::cout << "Temperature notification interval = " << notification_interval << " secs" << std::endl; - std::cout << "Starting temperature notifications. " << std::endl; - temp_characteristic->enable_value_notifications(data_callback, nullptr); - wait_ctrl_c(); - temp_characteristic->disable_value_notifications(); - } else { - std::cout << "Sensor does not support notifications" << std::endl; - } - - /* Disconnect from the device */ - std::cout << "Disconnecting" << std::endl; - try { - ess_device->disconnect(); - delete ess_device; - } catch (std::exception &e) { - std::cout << "Error: " << e.what() << std::endl; - } - return 0; -} diff --git a/examples/tinyb/hellotinyb.cpp b/examples/tinyb/hellotinyb.cpp deleted file mode 100644 index 49886195..00000000 --- a/examples/tinyb/hellotinyb.cpp +++ /dev/null @@ -1,214 +0,0 @@ -/* - * Author: Petre Eftime <[email protected]> - * Copyright (c) 2015 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#include <tinyb.hpp> - -#include <vector> -#include <iostream> -#include <thread> -#include <atomic> -#include <csignal> - -using namespace tinyb; - -/** Converts a raw temperature read from the sensor to a Celsius value. - * @param[in] raw_temp The temperature read from the sensor (two bytes) - * @return The Celsius value of the temperature - */ -static float celsius_temp(uint16_t raw_temp) -{ - const float SCALE_LSB = 0.03125; - return ((float)(raw_temp >> 2)) * SCALE_LSB; -} - - -std::atomic<bool> running(true); - -void signal_handler(int signum) -{ - if (signum == SIGINT) { - running = false; - } -} - -/** This program reads the temperature from a - * TI Sensor Tag(http://www.ti.com/ww/en/wireless_connectivity/sensortag2015/?INTC=SensorTag&HQS=sensortag) - * Pass the MAC address of the sensor as the first parameter of the program. - */ -int main(int argc, char **argv) -{ - if (argc < 2) { - std::cerr << "Run as: " << argv[0] << " <device_address>" << std::endl; - exit(1); - } - - BluetoothManager *manager = nullptr; - try { - manager = BluetoothManager::get_bluetooth_manager(); - } catch(const std::runtime_error& e) { - std::cerr << "Error while initializing libtinyb: " << e.what() << std::endl; - exit(1); - } - - /* Start the discovery of devices */ - bool ret = manager->start_discovery(); - std::cout << "Started = " << (ret ? "true" : "false") << std::endl; - - BluetoothDevice *sensor_tag = NULL; - BluetoothGattService *temperature_service = NULL; - - for (int i = 0; i < 15; ++i) { - std::cout << "Discovered devices: " << std::endl; - /* Get the list of devices */ - auto list = manager->get_devices(); - - for (auto it = list.begin(); it != list.end(); ++it) { - - std::cout << "Class = " << (*it)->get_class_name() << " "; - std::cout << "Path = " << (*it)->get_object_path() << " "; - std::cout << "Name = " << (*it)->get_name() << " "; - std::cout << "Connected = " << (*it)->get_connected() << " "; - std::cout << std::endl; - - /* Search for the device with the address given as a parameter to the program */ - if ((*it)->get_address() == argv[1]) - sensor_tag = (*it).release(); - } - - /* Free the list of devices and stop if the device was found */ - if (sensor_tag != nullptr) - break; - /* If not, wait and try again */ - std::this_thread::sleep_for(std::chrono::seconds(4)); - std::cout << std::endl; - } - - /* Stop the discovery (the device was found or number of tries ran out */ - ret = manager->stop_discovery(); - std::cout << "Stopped = " << (ret ? "true" : "false") << std::endl; - - if (sensor_tag == nullptr) { - std::cout << "Could not find device " << argv[1] << std::endl; - return 1; - } - - /* Connect to the device and get the list of services exposed by it */ - sensor_tag->connect(); - std::cout << "Discovered services: " << std::endl; - while (true) { - /* Wait for the device to come online */ - std::this_thread::sleep_for(std::chrono::seconds(4)); - - auto list = sensor_tag->get_services(); - if (list.empty()) - continue; - - for (auto it = list.begin(); it != list.end(); ++it) { - std::cout << "Class = " << (*it)->get_class_name() << " "; - std::cout << "Path = " << (*it)->get_object_path() << " "; - std::cout << "UUID = " << (*it)->get_uuid() << " "; - std::cout << "Device = " << (*it)->get_device().get_object_path() << " "; - std::cout << std::endl; - - /* Search for the temperature service, by UUID */ - if ((*it)->get_uuid() == "f000aa00-0451-4000-b000-000000000000") - temperature_service = (*it).release(); - } - break; - } - - if (temperature_service == nullptr) { - std::cout << "Could not find service f000aa00-0451-4000-b000-000000000000" << std::endl; - return 1; - } - - BluetoothGattCharacteristic *temp_value = nullptr; - BluetoothGattCharacteristic *temp_config = nullptr; - BluetoothGattCharacteristic *temp_period = nullptr; - - /* If there is a temperature service on the device with the given UUID, - * get it's characteristics, by UUID again */ - auto list = temperature_service->get_characteristics(); - std::cout << "Discovered characteristics: " << std::endl; - for (auto it = list.begin(); it != list.end(); ++it) { - - std::cout << "Class = " << (*it)->get_class_name() << " "; - std::cout << "Path = " << (*it)->get_object_path() << " "; - std::cout << "UUID = " << (*it)->get_uuid() << " "; - std::cout << "Service = " << (*it)->get_service().get_object_path() << " "; - std::cout << std::endl; - - if ((*it)->get_uuid() == "f000aa01-0451-4000-b000-000000000000") - temp_value = (*it).release(); - else if ((*it)->get_uuid() =="f000aa02-0451-4000-b000-000000000000") - temp_config = (*it).release(); - else if ((*it)->get_uuid() == "f000aa03-0451-4000-b000-000000000000") - temp_period = (*it).release(); - } - - if (temp_config == nullptr || temp_value == nullptr || temp_period == nullptr) { - std::cout << "Could not find characteristics." << std::endl; - return 1; - } - - /* Activate the temperature measurements */ - try { - std::vector<unsigned char> config_on {0x01}; - temp_config->write_value(config_on); - while (running) { - /* Read temperature data and display it */ - std::vector<unsigned char> response = temp_value->read_value(); - unsigned char *data; - unsigned int size = response.size(); - if (size > 0) { - data = response.data(); - - std::cout << "Raw data=["; - for (unsigned i = 0; i < response.size(); i++) - std::cout << std::hex << static_cast<int>(data[i]) << ", "; - std::cout << "] "; - - uint16_t ambient_temp, object_temp; - object_temp = data[0] | (data[1] << 8); - ambient_temp = data[2] | (data[3] << 8); - - std::cout << "Ambient temp: " << celsius_temp(ambient_temp) << "C "; - std::cout << "Object temp: " << celsius_temp(object_temp) << "C "; - std::cout << std::endl; - } - - std::this_thread::sleep_for(std::chrono::seconds(1)); - } - } catch (std::exception &e) { - std::cout << "Error: " << e.what() << std::endl; - } - - /* Disconnect from the device */ - try { - sensor_tag->disconnect(); - } catch (std::exception &e) { - std::cout << "Error: " << e.what() << std::endl; - } - return 0; -} diff --git a/examples/tinyb/list_mfg.cpp b/examples/tinyb/list_mfg.cpp deleted file mode 100644 index d978aa0a..00000000 --- a/examples/tinyb/list_mfg.cpp +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Author: Petre Eftime <[email protected]> - * Copyright (c) 2015 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#include <tinyb.hpp> - -#include <vector> -#include <iostream> -#include <thread> -#include <atomic> -#include <csignal> - -using namespace tinyb; - -/** Converts a raw temperature read from the sensor to a Celsius value. - * @param[in] raw_temp The temperature read from the sensor (two bytes) - * @return The Celsius value of the temperature - */ -float celsius_temp(uint16_t raw_temp) -{ - const float SCALE_LSB = 0.03125; - return ((float)(raw_temp >> 2)) * SCALE_LSB; -} - - -std::atomic<bool> running(true); - -void signal_handler(int signum) -{ - if (signum == SIGINT) { - running = false; - } -} - -/** This program reads the temperature from a - * TI Sensor Tag(http://www.ti.com/ww/en/wireless_connectivity/sensortag2015/?INTC=SensorTag&HQS=sensortag) - * Pass the MAC address of the sensor as the first parameter of the program. - */ -int main(int argc, char **argv) -{ - (void)argc; // FIXME - (void)argv; // FIXME - - BluetoothManager *manager = nullptr; - try { - manager = BluetoothManager::get_bluetooth_manager(); - } catch(const std::runtime_error& e) { - std::cerr << "Error while initializing libtinyb: " << e.what() << std::endl; - exit(1); - } - - /* Start the discovery of devices */ - bool ret = manager->start_discovery(); - std::cout << "Started = " << (ret ? "true" : "false") << std::endl; - - BluetoothDevice *sensor_tag = NULL; - BluetoothGattService *temperature_service = NULL; - - (void)sensor_tag; // FIXME - (void)temperature_service; // FIXME - - for (;;) { - std::cout << "Discovered devices: " << std::endl; - /* Get the list of devices */ - auto list = manager->get_devices(); - - for (auto it = list.begin(); it != list.end(); ++it) { - - std::cout << "Class = " << (*it)->get_class_name() << " "; - std::cout << "Path = " << (*it)->get_object_path() << " "; - std::cout << "Name = " << (*it)->get_name() << " "; - std::cout << "Connected = " << (*it)->get_connected() << " "; - std::cout << std::endl; - - auto mfg = (*it)->get_manufacturer_data(); - - if (!mfg.empty()) { - std::cout << "MFG" << std::endl; - for(auto it2: mfg) { - std::cout << "\t" << it2.first << " = [ "; - for (auto arr_it: it2.second) { - std::cout << (int) arr_it << ", "; - } - std::cout << "]" << std::endl; - } - } - - auto service_data = (*it)->get_service_data(); - - if (!service_data.empty()) { - std::cout << "Service Data" << std::endl; - for(auto it2: service_data) { - std::cout << "\t" << it2.first << " = [ "; - for (auto arr_it: it2.second) { - std::cout << (int) arr_it << ", "; - } - std::cout << "]" << std::endl; - } - } - - } - - /* If not, wait and try again */ - std::this_thread::sleep_for(std::chrono::seconds(4)); - std::cout << std::endl; - } -} diff --git a/examples/tinyb/notifications.cpp b/examples/tinyb/notifications.cpp deleted file mode 100644 index 52290ffc..00000000 --- a/examples/tinyb/notifications.cpp +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Author: Petre Eftime <[email protected]> - * Copyright (c) 2016 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#include <tinyb.hpp> - -#include <vector> -#include <iostream> -#include <thread> -#include <csignal> -#include <condition_variable> - -using namespace tinyb; - -std::condition_variable cv; - -/** Converts a raw temperature read from the sensor to a Celsius value. - * @param[in] raw_temp The temperature read from the sensor (two bytes) - * @return The Celsius value of the temperature - */ -static float celsius_temp(uint16_t raw_temp) -{ - const float SCALE_LSB = 0.03125; - return ((float)(raw_temp >> 2)) * SCALE_LSB; -} - -void data_callback(BluetoothGattCharacteristic &c, std::vector<unsigned char> &data, void *userdata) -{ - (void)c; - (void)userdata; - /* Read temperature data and display it */ - unsigned char *data_c; - unsigned int size = data.size(); - if (size > 0) { - data_c = data.data(); - - std::cout << "Raw data=["; - for (unsigned i = 0; i < size; i++) - std::cout << std::hex << static_cast<int>(data_c[i]) << ", "; - std::cout << "] "; - - uint16_t ambient_temp, object_temp; - object_temp = data_c[0] | (data_c[1] << 8); - ambient_temp = data_c[2] | (data_c[3] << 8); - - std::cout << "Ambient temp: " << celsius_temp(ambient_temp) << "C "; - std::cout << "Object temp: " << celsius_temp(object_temp) << "C "; - std::cout << std::endl; - } -} - -void signal_handler(int signum) -{ - if (signum == SIGINT) { - cv.notify_all(); - } -} - -/** This program reads the temperature from a - * TI Sensor Tag(http://www.ti.com/ww/en/wireless_connectivity/sensortag2015/?INTC=SensorTag&HQS=sensortag) - * Pass the MAC address of the sensor as the first parameter of the program. - */ -int main(int argc, char **argv) -{ - if (argc < 2) { - std::cerr << "Run as: " << argv[0] << " <device_address>" << std::endl; - exit(1); - } - - BluetoothManager *manager = nullptr; - try { - manager = BluetoothManager::get_bluetooth_manager(); - } catch(const std::runtime_error& e) { - std::cerr << "Error while initializing libtinyb: " << e.what() << std::endl; - exit(1); - } - - /* Start the discovery of devices */ - bool ret = manager->start_discovery(); - std::cout << "Started = " << (ret ? "true" : "false") << std::endl; - - std::unique_ptr<BluetoothGattService> temperature_service; - - std::string device_mac(argv[1]); - auto sensor_tag = manager->find<BluetoothDevice>(nullptr, &device_mac, nullptr, std::chrono::seconds(10)); - if (sensor_tag == nullptr) { - std::cout << "Device not found" << std::endl; - return 1; - } - sensor_tag->enable_connected_notifications([] (BluetoothDevice &d, bool connected, void *userdata) - { (void)userdata; if (connected) std::cout << "Connected " << d.get_name() << std::endl; }, NULL); - - if (sensor_tag != nullptr) { - /* Connect to the device and get the list of services exposed by it */ - sensor_tag->connect(); - std::string service_uuid("f000aa00-0451-4000-b000-000000000000"); - std::cout << "Waiting for service " << service_uuid << "to be discovered" << std::endl; - temperature_service = sensor_tag->find(&service_uuid); - } else { - ret = manager->stop_discovery(); - std::cerr << "SensorTag not found after 30 seconds, exiting" << std::endl; - return 1; - } - - /* Stop the discovery (the device was found or timeout was over) */ - ret = manager->stop_discovery(); - std::cout << "Stopped = " << (ret ? "true" : "false") << std::endl; - - auto value_uuid = std::string("f000aa01-0451-4000-b000-000000000000"); - auto temp_value = temperature_service->find(&value_uuid); - - auto config_uuid = std::string("f000aa02-0451-4000-b000-000000000000"); - auto temp_config = temperature_service->find(&config_uuid); - - auto period_uuid = std::string("f000aa03-0451-4000-b000-000000000000"); - auto temp_period = temperature_service->find(&period_uuid); - - /* Activate the temperature measurements */ - std::vector<unsigned char> config_on {0x01}; - temp_config->write_value(config_on); - temp_period->write_value({100}); - temp_value->enable_value_notifications(data_callback, nullptr); - - std::mutex m; - std::unique_lock<std::mutex> lock(m); - - std::signal(SIGINT, signal_handler); - - cv.wait(lock); - - /* Disconnect from the device */ - if (sensor_tag != nullptr) - sensor_tag->disconnect(); -} diff --git a/examples/tinyb/uuid.cpp b/examples/tinyb/uuid.cpp deleted file mode 100644 index db5452bb..00000000 --- a/examples/tinyb/uuid.cpp +++ /dev/null @@ -1,69 +0,0 @@ -#include<string> -#include<string.h> -#include<cstdlib> -#include<iostream> -#include<stdio.h> -#include<iomanip> -#include<stdint.h> -#include <tinyb.hpp> - -using namespace tinyb; - -int main(int argc, char **argv) { - - if( argc <= 2 ) { - exit(1); - } - std::string uuid_string(argv[1]); - - std::cout << uuid_string << std::endl; -/* - uint64_t uuid[2]; - if (uuid_string.size() == 4 || uuid_string.size() == 8) { - // 16bit UUID - uuid[0] = strtoul(uuid_string.c_str(), NULL, 16) << 32 | 0x00001000UL; - uuid[1] = (0x80000080ULL << 32) | 0x5f9b34fbUL; - } else if (uuid_string.size() == 36) { - // 128bit UUID - char u[37]; - strcpy(u, uuid_string.c_str()); - - if (u[9] == '-') { - u[9] = ' '; - uuid[0] = strtoul(u + 0, NULL, 16) << 32; - } else - return 1; - if (u[13] == '-') { - u[13] = ' '; - uuid[0] = uuid[0] | strtoul(u + 10, NULL, 16) << 16; - } else - return 1; - if (u[17] == '-') { - u[17] = ' '; - uuid[0] = uuid[0] | strtoul(u + 14, NULL, 16); - } else - return 1; - - if (u[21] == '-') { - u[21] = ' '; - uuid[1] = strtoul(u + 18, NULL, 16) << 48; - } else - return 1; - uuid[1] = uuid[1] | strtoul(u + 22, NULL, 16); - } else - return 1; - - printf("%08lx-%04lx-%04lx-%04lx-%012lx\n", - (uuid[0] >> 32), - ((uuid[0] >> 16) & 0xFFFFULL), - (uuid[0] & 0xFFFFULL), - (uuid[1] >> 48), - (uuid[1] & ~(0xFFFFULL << 48))); -*/ - BluetoothUUID uuid1(uuid_string); - BluetoothUUID uuid2(argv[1]); - - std::cout << uuid1.get_string() << " " << uuid2.get_string() << std::endl; - - return 0; -} diff --git a/java/CMakeLists.txt b/java/CMakeLists.txt index 51257d38..c88e9f08 100644 --- a/java/CMakeLists.txt +++ b/java/CMakeLists.txt @@ -36,6 +36,3 @@ install (FILES ${direct_bt_jar_file} DESTINATION ${CMAKE_INSTALL_LIBDIR}/../lib/ add_subdirectory (jni/direct_bt) -if(NOT SKIP_TINYB) - add_subdirectory (jni/tinyb) -endif() diff --git a/java/jau/direct_bt/DBTAdapter.java b/java/jau/direct_bt/DBTAdapter.java index 18907a9e..994a2539 100644 --- a/java/jau/direct_bt/DBTAdapter.java +++ b/java/jau/direct_bt/DBTAdapter.java @@ -27,10 +27,8 @@ package jau.direct_bt; import java.lang.ref.WeakReference; import java.util.ArrayList; -import java.util.Collections; import java.util.Iterator; import java.util.List; -import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; @@ -46,7 +44,6 @@ import org.direct_bt.BTGattChar; import org.direct_bt.BTGattDesc; import org.direct_bt.BTGattService; import org.direct_bt.BTManager; -import org.direct_bt.BTNotification; import org.direct_bt.BTObject; import org.direct_bt.BTType; import org.direct_bt.BTUtils; @@ -57,7 +54,6 @@ import org.direct_bt.HCIWhitelistConnectType; import org.direct_bt.PairingMode; import org.direct_bt.SMPPairingState; import org.direct_bt.ScanType; -import org.direct_bt.TransportType; public class DBTAdapter extends DBTObject implements BTAdapter { @@ -80,19 +76,13 @@ public class DBTAdapter extends DBTObject implements BTAdapter private final Object discoveryLock = new Object(); private final Object discoveredDevicesLock = new Object(); - private final Object userCallbackLock = new Object(); private final AtomicBoolean isClosing = new AtomicBoolean(false); private final AtomicBoolean powered_state = new AtomicBoolean(false); // AdapterSettings - private BTNotification<Boolean> userPairableNotificationCB = null; private final AtomicBoolean isDiscoverable = new AtomicBoolean(false); // AdapterSettings - private BTNotification<Boolean> userDiscoverableNotificationCB = null; - private final AtomicBoolean isPairable = new AtomicBoolean(false); // AdapterSettings - private BTNotification<Boolean> userPoweredNotificationCB = null; private final AtomicReference<ScanType> currentMetaScanType = new AtomicReference<ScanType>(ScanType.NONE); // AdapterStatusListener and powerdOff - private BTNotification<Boolean> userDiscoveringNotificationCB = null; private final List<WeakReference<BTDevice>> discoveredDevices = new ArrayList<WeakReference<BTDevice>>(); @@ -123,10 +113,6 @@ public class DBTAdapter extends DBTObject implements BTAdapter } // mute all listener first removeAllStatusListener(); - disableDiscoverableNotifications(); - disableDiscoveringNotifications(); - disablePairableNotifications(); - disablePoweredNotifications(); stopDiscovery(); @@ -170,12 +156,6 @@ public class DBTAdapter extends DBTObject implements BTAdapter public BDAddressAndType getVisibleAddressAndType() { return visibleAddressAndType; } @Override - public EUI48 getAddress() { return addressAndType.address; } - - @Override - public String getAddressString() { return addressAndType.address.toString(); } - - @Override public String getName() { return name; } @Override @@ -228,108 +208,14 @@ public class DBTAdapter extends DBTObject implements BTAdapter /* Unsupported */ @Override - public long getBluetoothClass() { throw new UnsupportedOperationException(); } // FIXME - - @Override - public final BTAdapter clone() { throw new UnsupportedOperationException(); } // FIXME - - @Override - public String getInterfaceName() { throw new UnsupportedOperationException(); } // FIXME - - @Override - public long getDiscoverableTimeout() { throw new UnsupportedOperationException(); } // FIXME - - @Override - public boolean setDiscoverableTimout(final long value) { return false; } // FIXME - - @Override - public long getPairableTimeout() { throw new UnsupportedOperationException(); } // FIXME - - @Override - public boolean setPairableTimeout(final long value) { return false; } // FIXME - - @Override - public String getModalias() { throw new UnsupportedOperationException(); } // FIXME - - @Override - public String[] getUUIDs() { throw new UnsupportedOperationException(); } // FIXME - - - /* Java callbacks */ - - @Override - public void enablePoweredNotifications(final BTNotification<Boolean> callback) { - synchronized(userCallbackLock) { - userPoweredNotificationCB = callback; - } - } - - @Override - public void disablePoweredNotifications() { - synchronized(userCallbackLock) { - userPoweredNotificationCB = null; - } - } - - @Override public boolean getDiscoverable() { return isDiscoverable.get(); } @Override - public void enableDiscoverableNotifications(final BTNotification<Boolean> callback) { - synchronized(userCallbackLock) { - userDiscoverableNotificationCB = callback; - } - } - - @Override - public void disableDiscoverableNotifications() { - synchronized(userCallbackLock) { - userDiscoverableNotificationCB = null; - } - } - - @Override public final ScanType getCurrentScanType() { return currentMetaScanType.get(); } @Override - public final boolean getDiscovering() { - return ScanType.NONE != currentMetaScanType.get(); - } - - @Override - public final void enableDiscoveringNotifications(final BTNotification<Boolean> callback) { - synchronized(userCallbackLock) { - userDiscoveringNotificationCB = callback; - } - } - - @Override - public final void disableDiscoveringNotifications() { - synchronized(userCallbackLock) { - userDiscoveringNotificationCB = null; - } - } - - @Override - public final boolean getPairable() { return isPairable.get(); } - - @Override - public void enablePairableNotifications(final BTNotification<Boolean> callback) { - synchronized(userCallbackLock) { - userPairableNotificationCB = callback; - } - } - - @Override - public void disablePairableNotifications() { - synchronized(userCallbackLock) { - userPairableNotificationCB = null; - } - } - - @Override public String toString() { if( !isValid() ) { return "Adapter" + "\u271D" + "["+addressAndType+", '"+name+"', id "+dev_id+"]"; @@ -390,13 +276,6 @@ public class DBTAdapter extends DBTObject implements BTAdapter @Override protected native void deleteImpl(long nativeInstance); - /* discovery */ - - @Override - public boolean startDiscovery() throws BTException { - return HCIStatusCode.SUCCESS == startDiscovery(true, false); - } - @Override public HCIStatusCode startDiscovery(final boolean keepAlive, final boolean le_scan_active) throws BTException { return startDiscovery(keepAlive, le_scan_active, (short)24, (short)24, (byte)0); @@ -543,22 +422,6 @@ public class DBTAdapter extends DBTObject implements BTAdapter public native int removeAllStatusListener(); @Override - public void setDiscoveryFilter(final List<UUID> uuids, final int rssi, final int pathloss, final TransportType transportType) { - final List<String> uuidsFmt = new ArrayList<>(uuids.size()); - for (final UUID uuid : uuids) { - uuidsFmt.add(uuid.toString()); - } - setDiscoveryFilter(uuidsFmt, rssi, pathloss, transportType.ordinal()); - } - - @SuppressWarnings("unchecked") - public void setRssiDiscoveryFilter(final int rssi) { - setDiscoveryFilter(Collections.EMPTY_LIST, rssi, 0, TransportType.AUTO); - } - - private native void setDiscoveryFilter(List<String> uuids, int rssi, int pathloss, int transportType); - - @Override public final void printDeviceLists() { printDeviceListsImpl(); List<WeakReference<BTDevice>> _discoveredDevices; @@ -598,7 +461,6 @@ public class DBTAdapter extends DBTObject implements BTAdapter if( initialSetting ) { powered_state.set( newmask.isSet(AdapterSettings.SettingType.POWERED) ); isDiscoverable.set( newmask.isSet(AdapterSettings.SettingType.DISCOVERABLE) ); - isPairable.set( newmask.isSet(AdapterSettings.SettingType.BONDABLE) ); return; } if( changedmask.isSet(AdapterSettings.SettingType.POWERED) ) { @@ -607,31 +469,11 @@ public class DBTAdapter extends DBTObject implements BTAdapter if( !_isPowered ) { poweredOff(); } - synchronized(userCallbackLock) { - if( null != userPoweredNotificationCB ) { - userPoweredNotificationCB.run(_isPowered); - } - } } } if( changedmask.isSet(AdapterSettings.SettingType.DISCOVERABLE) ) { final boolean _isDiscoverable = newmask.isSet(AdapterSettings.SettingType.DISCOVERABLE); if( isDiscoverable.compareAndSet(!_isDiscoverable, _isDiscoverable) ) { - synchronized(userCallbackLock) { - if( null != userDiscoverableNotificationCB ) { - userDiscoverableNotificationCB.run( _isDiscoverable ); - } - } - } - } - if( changedmask.isSet(AdapterSettings.SettingType.BONDABLE) ) { - final boolean _isPairable = newmask.isSet(AdapterSettings.SettingType.BONDABLE); - if( isPairable.compareAndSet(!_isPairable, _isPairable) ) { - synchronized(userCallbackLock) { - if( null != userPairableNotificationCB ) { - userPairableNotificationCB.run( _isPairable ); - } - } } } } @@ -641,16 +483,7 @@ public class DBTAdapter extends DBTObject implements BTAdapter System.err.println("Adapter.StatusListener.DISCOVERING: meta "+currentMeta+", changed["+changedType+", enabled "+changedEnabled+", keepAlive "+keepAlive+"] on "+adapter); } // meta ignores changes on temp disabled discovery - final boolean has_le_changed = currentMetaScanType.get().hasScanType(ScanType.LE) != currentMeta.hasScanType(ScanType.LE); currentMetaScanType.set(currentMeta); - - if( changedType.hasScanType(ScanType.LE) && has_le_changed ) { - synchronized(userCallbackLock) { - if( null != userDiscoveringNotificationCB ) { - userDiscoveringNotificationCB.run(changedEnabled); - } - } - } } @Override public boolean deviceFound(final BTDevice device, final long timestamp) { @@ -765,13 +598,13 @@ public class DBTAdapter extends DBTObject implements BTAdapter if( ( anyType || deviceType ) ) { if( null != name && null != identifier && device.getName().equals(name) && - device.getAddressString().equals(identifier) + device.getAddressAndType().address.toString().equals(identifier) ) { return device; } if( null != identifier && - device.getAddressString().equals(identifier) + device.getAddressAndType().address.toString().equals(identifier) ) { return device; diff --git a/java/jau/direct_bt/DBTDevice.java b/java/jau/direct_bt/DBTDevice.java index d4dd9629..ab0fc189 100644 --- a/java/jau/direct_bt/DBTDevice.java +++ b/java/jau/direct_bt/DBTDevice.java @@ -40,7 +40,6 @@ import org.direct_bt.BTException; import org.direct_bt.BTGattChar; import org.direct_bt.BTGattDesc; import org.direct_bt.BTGattService; -import org.direct_bt.BTNotification; import org.direct_bt.BTObject; import org.direct_bt.BTType; import org.direct_bt.BTUtils; @@ -72,76 +71,22 @@ public class DBTDevice extends DBTObject implements BTDevice private final AtomicBoolean isClosing = new AtomicBoolean(false); - private final Object userCallbackLock = new Object(); - - private final long blockedNotificationRef = 0; - private BTNotification<Boolean> userBlockedNotificationsCB = null; - private final AtomicBoolean isBlocked = new AtomicBoolean(false); - - private final long pairedNotificationRef = 0; - private BTNotification<Boolean> userPairedNotificationsCB = null; - private final AtomicBoolean isPaired = new AtomicBoolean(false); - - private final long trustedNotificationRef = 0; - private BTNotification<Boolean> userTrustedNotificationsCB = null; - private final AtomicBoolean isTrusted = new AtomicBoolean(false); - - private BTNotification<Boolean> userConnectedNotificationsCB = null; private final AtomicBoolean isConnected = new AtomicBoolean(false); - private BTNotification<Short> userRSSINotificationsCB = null; - private BTNotification<Map<Short, byte[]> > userManufDataNotificationsCB = null; - private BTNotification<Boolean> userServicesResolvedNotificationsCB = null; - private final AtomicBoolean servicesResolved = new AtomicBoolean(false); - private short appearance = 0; - final AdapterStatusListener statusListener = new AdapterStatusListener() { @Override public void deviceUpdated(final BTDevice device, final EIRDataTypeSet updateMask, final long timestamp) { - final boolean rssiUpdated = updateMask.isSet( EIRDataTypeSet.DataType.RSSI ); - final boolean mdUpdated = updateMask.isSet( EIRDataTypeSet.DataType.MANUF_DATA ); - if( rssiUpdated || mdUpdated ) { - synchronized(userCallbackLock) { - if( rssiUpdated && null != userRSSINotificationsCB ) { - userRSSINotificationsCB.run(getRSSI()); - } - if( mdUpdated && null != userManufDataNotificationsCB ) { - userManufDataNotificationsCB.run(getManufacturerData()); - } - } - } } @Override public void deviceConnected(final BTDevice device, final short handle, final long timestamp) { if( isConnected.compareAndSet(false, true) ) { - synchronized(userCallbackLock) { - if( null != userConnectedNotificationsCB ) { - userConnectedNotificationsCB.run(Boolean.TRUE); - } - if( servicesResolved.compareAndSet(false, true) ) { - if( null != userServicesResolvedNotificationsCB ) { - userServicesResolvedNotificationsCB.run(Boolean.TRUE); - } - } - } + // nop } } @Override public void deviceDisconnected(final BTDevice device, final HCIStatusCode reason, final short handle, final long timestamp) { - devicePaired(false); - if( isConnected.compareAndSet(true, false) ) { clearServiceCache(); - synchronized(userCallbackLock) { - if( servicesResolved.compareAndSet(true, false) ) { - if( null != userServicesResolvedNotificationsCB ) { - userServicesResolvedNotificationsCB.run(Boolean.FALSE); - } - } - if( null != userConnectedNotificationsCB ) { - userConnectedNotificationsCB.run(Boolean.FALSE); - } - } } } @@ -151,59 +96,6 @@ public class DBTDevice extends DBTObject implements BTDevice } }; - final private BTNotification<Boolean> blockedNotificationsCB = new BTNotification<Boolean>() { - @Override - public void run(final Boolean value) { - if( DEBUG ) { - System.err.println("Device.BlockedNotification: "+isBlocked+" -> "+value+" on "+DBTDevice.this.toString()); - } - final boolean _isBlocked = value.booleanValue(); - if( isBlocked.compareAndSet(!_isBlocked, _isBlocked) ) { - synchronized(userCallbackLock) { - if( null != userBlockedNotificationsCB ) { - userBlockedNotificationsCB.run(value); - } - } - } - } - }; - - final private void devicePaired(final boolean _isPaired) { - if( DEBUG ) { - System.err.println("Device.PairedNotification: "+isPaired+" -> "+_isPaired+" on "+DBTDevice.this.toString()); - } - if( isPaired.compareAndSet(!_isPaired, _isPaired) ) { - synchronized(userCallbackLock) { - if( null != userPairedNotificationsCB ) { - userPairedNotificationsCB.run(_isPaired); - } - } - } - } - final private BTNotification<Boolean> pairedNotificationsCB = new BTNotification<Boolean>() { - @Override - public void run(final Boolean value) { - devicePaired( value.booleanValue() ); - } - }; - - final private BTNotification<Boolean> trustedNotificationsCB = new BTNotification<Boolean>() { - @Override - public void run(final Boolean value) { - if( DEBUG ) { - System.err.println("Device.TrustedNotification: "+isTrusted+" -> "+value+" on "+DBTDevice.this.toString()); - } - final boolean _isTrusted = value.booleanValue(); - if( isTrusted.compareAndSet(!_isTrusted, _isTrusted) ) { - synchronized(userCallbackLock) { - if( null != userTrustedNotificationsCB ) { - userTrustedNotificationsCB.run(value); - } - } - } - } - }; - /* pp */ DBTDevice(final long nativeInstance, final DBTAdapter adptr, final byte byteAddress[/*6*/], final byte byteAddressType, @@ -220,11 +112,8 @@ public class DBTDevice extends DBTObject implements BTDevice ts_last_update = ts_creation; hciConnHandle = 0; name_cached = name; - appearance = 0; initImpl(); addStatusListener(statusListener); // associated events and lifecycle with this device - enableBlockedNotificationsImpl(blockedNotificationsCB); - enablePairedNotificationsImpl(pairedNotificationsCB); // FIXME enableTrustedNotificationsImpl(trustedNotificationsCB); } @@ -236,19 +125,6 @@ public class DBTDevice extends DBTObject implements BTDevice if( !isClosing.compareAndSet(false, true) ) { return; } - disableConnectedNotifications(); - disableRSSINotifications(); - disableManufacturerDataNotifications(); - disableServicesResolvedNotifications(); - - disableBlockedNotifications(); - disableBlockedNotificationsImpl(); - disablePairedNotifications(); - disablePairedNotificationsImpl(); - disableServiceDataNotifications(); - disableTrustedNotifications(); - // FIXME disableTrustedNotificationsImpl(); - clearServiceCache(); final DBTAdapter a = getAdapter(); @@ -285,9 +161,6 @@ public class DBTDevice extends DBTObject implements BTDevice public DBTAdapter getAdapter() { return wbr_adapter.get(); } @Override - public String getAddressString() { return addressAndType.address.toString(); } - - @Override public BDAddressAndType getAddressAndType() { return addressAndType; } @Override @@ -317,31 +190,6 @@ public class DBTDevice extends DBTObject implements BTDevice return find(UUID, 0); } - /* Unsupported */ - - @Override - public final boolean pair() throws BTException { - return false; - } - - @Override - public int getBluetoothClass() { throw new UnsupportedOperationException(); } // FIXME - - @Override - public final BTDevice clone() { throw new UnsupportedOperationException(); } // FIXME - - @Override - public String getAlias() { return null; } // FIXME - - @Override - public void setAlias(final String value) { throw new UnsupportedOperationException(); } // FIXME - - @Override - public final boolean cancelPairing() throws BTException { - // FIXME: Not supporter (yet) - return false; - } - /* internal */ private native void initImpl(); @@ -359,19 +207,6 @@ public class DBTDevice extends DBTObject implements BTDevice } @Override - public final void enableConnectedNotifications(final BTNotification<Boolean> callback) { - synchronized(userCallbackLock) { - userConnectedNotificationsCB = callback; - } - } - @Override - public final void disableConnectedNotifications() { - synchronized(userCallbackLock) { - userConnectedNotificationsCB = null; - } - } - - @Override public final boolean getConnected() { return isConnected.get(); } @Override @@ -539,135 +374,6 @@ public class DBTDevice extends DBTObject implements BTDevice } private native byte getPairingStateImpl(); - /* DBT Java callbacks */ - - @Override - public final void enableRSSINotifications(final BTNotification<Short> callback) { - synchronized(userCallbackLock) { - userRSSINotificationsCB = callback; - } - } - - @Override - public final void disableRSSINotifications() { - synchronized(userCallbackLock) { - userRSSINotificationsCB = null; - } - } - - - @Override - public final void enableManufacturerDataNotifications(final BTNotification<Map<Short, byte[]> > callback) { - synchronized(userCallbackLock) { - userManufDataNotificationsCB = callback; - } - } - - @Override - public final void disableManufacturerDataNotifications() { - synchronized(userCallbackLock) { - userManufDataNotificationsCB = null; - } - } - - - @Override - public final void enableServicesResolvedNotifications(final BTNotification<Boolean> callback) { - synchronized(userCallbackLock) { - userServicesResolvedNotificationsCB = callback; - } - } - - @Override - public void disableServicesResolvedNotifications() { - synchronized(userCallbackLock) { - userServicesResolvedNotificationsCB = null; - } - } - - @Override - public boolean getServicesResolved () { return servicesResolved.get(); } - - @Override - public short getAppearance() { return appearance; } - - @Override - public void enableBlockedNotifications(final BTNotification<Boolean> callback) { - synchronized(userCallbackLock) { - userBlockedNotificationsCB = callback; - } - } - @Override - public void disableBlockedNotifications() { - synchronized(userCallbackLock) { - userBlockedNotificationsCB = null; - } - } - @Override - public boolean getBlocked() { return isBlocked.get(); } - - @Override - public void setBlocked(final boolean value) { - setBlockedImpl(value); - } - - @Override - public void enableServiceDataNotifications(final BTNotification<Map<String, byte[]> > callback) { - // FIXME: Isn't this BTGattChar data notification/indication? Then map it or drop! - } - - @Override - public Map<String, byte[]> getServiceData() { - return null; // FIXME - } - - @Override - public void disableServiceDataNotifications() { - // FIXME - } - - @Override - public void enablePairedNotifications(final BTNotification<Boolean> callback) { - synchronized(userCallbackLock) { - userPairedNotificationsCB = callback; - } - } - - @Override - public void disablePairedNotifications() { - synchronized(userCallbackLock) { - userPairedNotificationsCB = null; - } - } - - @Override - public final boolean getPaired() { return isPaired.get(); } - - @Override - public void enableTrustedNotifications(final BTNotification<Boolean> callback) { - synchronized(userCallbackLock) { - userTrustedNotificationsCB = callback; - } - } - - @Override - public void disableTrustedNotifications() { - synchronized(userCallbackLock) { - userTrustedNotificationsCB = null; - } - } - - @Override - public boolean getTrusted() { return isTrusted.get(); } - - @Override - public void setTrusted(final boolean value) { - setTrustedImpl(value); - } - - @Override - public native boolean getLegacyPairing(); - @Override public final String toString() { if( !isValid() ) { @@ -677,35 +383,8 @@ public class DBTDevice extends DBTObject implements BTDevice } return toStringImpl(); } - - /* DBT native callbacks */ - private native String toStringImpl(); - private native void enableBlockedNotificationsImpl(BTNotification<Boolean> callback); - private native void disableBlockedNotificationsImpl(); - private native void setBlockedImpl(final boolean value); - - // Note that this is only called natively for unpaired, i.e. paired:=false. Using deviceConnected for paired:=true. - private native void enablePairedNotificationsImpl(BTNotification<Boolean> callback); - private native void disablePairedNotificationsImpl(); - - /** - * FIXME: How to implement trusted ? - * - private native void enableTrustedNotificationsImpl(BluetoothNotification<Boolean> callback); - private native void disableTrustedNotificationsImpl(); - */ - private native void setTrustedImpl(boolean value); - - /* DBT native method calls: */ - - @Override - public native boolean connectProfile(String arg_UUID) throws BTException; - - @Override - public native boolean disconnectProfile(String arg_UUID) throws BTException; - /** * {@inheritDoc} */ @@ -760,18 +439,9 @@ public class DBTDevice extends DBTObject implements BTDevice /* property accessors: */ @Override - public native String getIcon(); - - @Override public native short getRSSI(); @Override - public native String[] getUUIDs(); - - @Override - public native String getModalias(); - - @Override public native Map<Short, byte[]> getManufacturerData(); @Override diff --git a/java/jau/direct_bt/DBTEvent.java b/java/jau/direct_bt/DBTEvent.java deleted file mode 100644 index bd176944..00000000 --- a/java/jau/direct_bt/DBTEvent.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Author: Sven Gothel <[email protected]> - * Copyright (c) 2020 Gothel Software e.K. - * Copyright (c) 2020 ZAFENA AB - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package jau.direct_bt; - -import org.direct_bt.BTCallback; -import org.direct_bt.BTEvent; -import org.direct_bt.BTType; - -public class DBTEvent implements BTEvent -{ - private long nativeInstance; - - @Override - public native BTType getType(); - @Override - public native String getName(); - @Override - public native String getIdentifier(); - @Override - public native boolean executeCallback(); - @Override - public native boolean hasCallback(); - - private native void init(BTType type, String name, String identifier, - DBTObject parent, BTCallback cb, Object data); - private native void delete(); - - public DBTEvent(final BTType type, final String name, final String identifier, - final DBTObject parent, final BTCallback cb, final Object data) - { - init(type, name, identifier, parent, cb, data); - } - - @Override - protected void finalize() - { - delete(); - } -} diff --git a/java/jau/direct_bt/DBTGattChar.java b/java/jau/direct_bt/DBTGattChar.java index b3ec3222..e3fd00a3 100644 --- a/java/jau/direct_bt/DBTGattChar.java +++ b/java/jau/direct_bt/DBTGattChar.java @@ -26,18 +26,16 @@ package jau.direct_bt; import java.lang.ref.WeakReference; -import java.util.Arrays; import java.util.List; import org.direct_bt.BTException; -import org.direct_bt.BTFactory; import org.direct_bt.BTGattChar; import org.direct_bt.BTGattDesc; import org.direct_bt.BTGattService; -import org.direct_bt.BTNotification; import org.direct_bt.BTObject; import org.direct_bt.BTType; import org.direct_bt.BTUtils; +import org.direct_bt.GattCharPropertySet; import org.direct_bt.BTGattCharListener; public class DBTGattChar extends DBTObject implements BTGattChar @@ -55,10 +53,7 @@ public class DBTGattChar extends DBTObject implements BTGattChar */ private final short handle; - /* Characteristics Property */ - private final String[] properties; - private final boolean hasNotify; - private final boolean hasIndicate; + private final GattCharPropertySet properties; /* Characteristics Value Type UUID */ private final String value_type_uuid; @@ -76,97 +71,45 @@ public class DBTGattChar extends DBTObject implements BTGattChar /* pp */ final List<BTGattDesc> descriptorList; - private final boolean supCharValueCacheNotification; - boolean enabledNotifyState = false; boolean enabledIndicateState = false; - private byte[] cachedValue = null; - private BTNotification<byte[]> valueNotificationCB = null; - - private boolean updateCachedValue(final byte[] value, final boolean notify) { - boolean valueChanged = false; - if( null == cachedValue || cachedValue.length != value.length ) { - cachedValue = new byte[value.length]; - valueChanged = true; - } else if( !Arrays.equals(value, cachedValue) ) { - valueChanged = true; - } - if( valueChanged ) { - System.arraycopy(value, 0, cachedValue, 0, value.length); - if( notify && null != valueNotificationCB ) { - valueNotificationCB.run(cachedValue); - } - } - return valueChanged; - } - /* pp */ DBTGattChar(final long nativeInstance, final DBTGattService service, - final short handle, final String[] properties, - final boolean hasNotify, final boolean hasIndicate, - final String value_type_uuid, final short value_handle, - final int clientCharacteristicsConfigIndex) + final short handle, final GattCharPropertySet properties, + final String value_type_uuid, final short value_handle, + final int clientCharacteristicsConfigIndex) { super(nativeInstance, handle /* hash */); this.wbr_service = new WeakReference<DBTGattService>(service); this.handle = handle; this.properties = properties; - this.hasNotify = hasNotify; - this.hasIndicate = hasIndicate; this.value_type_uuid = value_type_uuid; this.value_handle = value_handle; this.clientCharacteristicsConfigIndex = clientCharacteristicsConfigIndex; this.descriptorList = getDescriptorsImpl(); - this.supCharValueCacheNotification = DBTManager.getManager().getSettings().isCharValueCacheNotificationSupported(); - - if( ( BTFactory.DEBUG || supCharValueCacheNotification ) && - ( hasNotify || hasIndicate ) - ) - { - // This characteristicListener serves TinyB 'enableValueNotification(..)' and 'getValue()' (cached value) - // backwards compatibility only! - final Listener characteristicListener = new Listener() { - @Override - public void notificationReceived(final BTGattChar charDecl, final byte[] value, final long timestamp) { - final DBTGattChar cd = (DBTGattChar)charDecl; - if( !cd.equals(DBTGattChar.this) ) { - throw new InternalError("Filtered GATTCharacteristicListener.notificationReceived: Wrong Characteristic: Got "+charDecl+ - ", expected "+DBTGattChar.this.toString()); - } - final boolean valueChanged; - if( supCharValueCacheNotification ) { - valueChanged = updateCachedValue(value, true); - } else { - valueChanged = true; - } - if( DEBUG ) { + + if( DEBUG ) { + final boolean hasNotify = properties.isSet(GattCharPropertySet.Type.Notify); + final boolean hasIndicate = properties.isSet(GattCharPropertySet.Type.Indicate); + + if( hasNotify || hasIndicate ) { + final Listener characteristicListener = new Listener() { + @Override + public void notificationReceived(final BTGattChar charDecl, final byte[] value, final long timestamp) { System.err.println("GATTCharacteristicListener.notificationReceived: "+charDecl+ - ", value[changed "+valueChanged+", len "+value.length+": "+BTUtils.bytesHexString(value, 0, -1, true)+"]"); - } - } - @Override - public void indicationReceived(final BTGattChar charDecl, final byte[] value, final long timestamp, - final boolean confirmationSent) { - final DBTGattChar cd = (DBTGattChar)charDecl; - if( !cd.equals(DBTGattChar.this) ) { - throw new InternalError("Filtered GATTCharacteristicListener.indicationReceived: Wrong Characteristic: Got "+charDecl+ - ", expected "+DBTGattChar.this.toString()); + ", value[len "+value.length+": "+BTUtils.bytesHexString(value, 0, -1, true)+"]"); } - final boolean valueChanged; - if( supCharValueCacheNotification ) { - valueChanged = updateCachedValue(value, true); - } else { - valueChanged = true; - } - if( DEBUG ) { + @Override + public void indicationReceived(final BTGattChar charDecl, final byte[] value, final long timestamp, + final boolean confirmationSent) { System.err.println("GATTCharacteristicListener.indicationReceived: "+charDecl+ - ", value[changed "+valueChanged+", len "+value.length+": "+BTUtils.bytesHexString(value, 0, -1, true)+ + ", value[len "+value.length+": "+BTUtils.bytesHexString(value, 0, -1, true)+ "], confirmationSent "+confirmationSent); } - } - }; - this.addCharListener(characteristicListener); // silent, don't enable native GATT ourselves + }; + this.addCharListener(characteristicListener); // silent, don't enable native GATT ourselves + } } } @@ -218,29 +161,23 @@ public class DBTGattChar extends DBTObject implements BTGattChar public final BTGattService getService() { return wbr_service.get(); } @Override - public final String[] getFlags() { return properties; } + public final boolean getNotifying(final boolean enabledState[/*2*/]) { + enabledState[0] = enabledNotifyState; + enabledState[1] = enabledIndicateState; + return enabledNotifyState || enabledIndicateState; + } @Override - public final byte[] getValue() { return cachedValue; } + public final GattCharPropertySet getProperties() { return properties; } @Override public final byte[] readValue() throws BTException { - if( supCharValueCacheNotification ) { - final byte[] value = readValueImpl(); - updateCachedValue(value, true); - return cachedValue; - } else { - return readValueImpl(); - } + return readValueImpl(); } @Override public final boolean writeValue(final byte[] value, final boolean withResponse) throws BTException { - final boolean res = writeValueImpl(value, withResponse); - if( supCharValueCacheNotification && res ) { - updateCachedValue(value, false); - } - return res; + return writeValueImpl(value, withResponse); } @Override @@ -250,6 +187,9 @@ public class DBTGattChar extends DBTObject implements BTGattChar public final synchronized boolean configNotificationIndication(final boolean enableNotification, final boolean enableIndication, final boolean enabledState[/*2*/]) throws IllegalStateException { + final boolean hasNotify = properties.isSet(GattCharPropertySet.Type.Notify); + final boolean hasIndicate = properties.isSet(GattCharPropertySet.Type.Indicate); + if( hasNotify || hasIndicate ) { final boolean resEnableNotification = hasNotify && enableNotification; final boolean resEnableIndication = hasIndicate && enableIndication; @@ -268,16 +208,18 @@ public class DBTGattChar extends DBTObject implements BTGattChar } final boolean res = configNotificationIndicationImpl(enableNotification, enableIndication, enabledState); + if( !res ) { + enabledState[0] = false; + enabledState[1] = false; + } if( DEBUG ) { System.err.printf("GATTCharacteristic.configNotificationIndication: res %b, notification[shall %b, has %b: %b -> %b], indication[shall %b, has %b: %b -> %b]\n", res, - enableNotification, hasNotify, enabledNotifyState, resEnableNotification, - enableIndication, hasIndicate, enabledIndicateState, resEnableIndication); - } - if( res ) { - enabledNotifyState = resEnableNotification; - enabledIndicateState = resEnableIndication; + enableNotification, hasNotify, enabledNotifyState, enabledState[0], + enableIndication, hasIndicate, enabledIndicateState, enabledState[1]); } + enabledNotifyState = enabledState[0]; + enabledIndicateState = enabledState[1]; return res; } else { enabledState[0] = false; @@ -295,8 +237,8 @@ public class DBTGattChar extends DBTObject implements BTGattChar public boolean enableNotificationOrIndication(final boolean enabledState[/*2*/]) throws IllegalStateException { - final boolean enableNotification = hasNotify; - final boolean enableIndication = !enableNotification && hasIndicate; + final boolean enableNotification = properties.isSet(GattCharPropertySet.Type.Notify); + final boolean enableIndication = !enableNotification && properties.isSet(GattCharPropertySet.Type.Indicate); return configNotificationIndication(enableNotification, enableIndication, enabledState); } @@ -341,28 +283,12 @@ public class DBTGattChar extends DBTObject implements BTGattChar if( disableIndicationNotification ) { configNotificationIndication(false /* enableNotification */, false /* enableIndication */, new boolean[2]); } - valueNotificationCB = null; return getService().getDevice().removeAllAssociatedCharListener(this); } @Override - public final synchronized void enableValueNotifications(final BTNotification<byte[]> callback) { - if( !configNotificationIndication(true /* enableNotification */, true /* enableIndication */, new boolean[2]) ) { - valueNotificationCB = null; - } else { - valueNotificationCB = callback; - } - } - - @Override public final synchronized void disableValueNotifications() { configNotificationIndication(false /* enableNotification */, false /* enableIndication */, new boolean[2]); - valueNotificationCB = null; - } - - @Override - public final boolean getNotifying() { - return null != valueNotificationCB; } /** diff --git a/java/jau/direct_bt/DBTGattDesc.java b/java/jau/direct_bt/DBTGattDesc.java index 7c080e39..a9ead765 100644 --- a/java/jau/direct_bt/DBTGattDesc.java +++ b/java/jau/direct_bt/DBTGattDesc.java @@ -30,7 +30,6 @@ import java.util.Arrays; import org.direct_bt.BTException; import org.direct_bt.BTGattDesc; -import org.direct_bt.BTNotification; import org.direct_bt.BTType; public class DBTGattDesc extends DBTObject implements BTGattDesc @@ -50,23 +49,12 @@ public class DBTGattDesc extends DBTObject implements BTGattDesc private final short handle; private byte[] cachedValue; - private BTNotification<byte[]> valueNotificationCB = null; - private boolean updateCachedValue(final byte[] value, final boolean notify) { - boolean valueChanged = false; + private void updateCachedValue(final byte[] value) { if( null == cachedValue || cachedValue.length != value.length ) { cachedValue = new byte[value.length]; - valueChanged = true; - } else if( !Arrays.equals(value, cachedValue) ) { - valueChanged = true; } - if( valueChanged ) { - System.arraycopy(value, 0, cachedValue, 0, value.length); - if( notify && null != valueNotificationCB ) { - valueNotificationCB.run(cachedValue); - } - } - return valueChanged; + System.arraycopy(value, 0, cachedValue, 0, value.length); } /* pp */ DBTGattDesc(final long nativeInstance, final DBTGattChar characteristic, @@ -84,7 +72,6 @@ public class DBTGattDesc extends DBTObject implements BTGattDesc if( !isValid() ) { return; } - disableValueNotifications(); super.close(); } @@ -119,7 +106,7 @@ public class DBTGattDesc extends DBTObject implements BTGattDesc @Override public final byte[] readValue() { final byte[] value = readValueImpl(); - updateCachedValue(value, true); + updateCachedValue(value); return cachedValue; } @@ -127,21 +114,11 @@ public class DBTGattDesc extends DBTObject implements BTGattDesc public final boolean writeValue(final byte[] value) throws BTException { final boolean res = writeValueImpl(value); if( res ) { - updateCachedValue(value, false); + updateCachedValue(value); } return res; } - @Override - public final synchronized void enableValueNotifications(final BTNotification<byte[]> callback) { - valueNotificationCB = callback; - } - - @Override - public final synchronized void disableValueNotifications() { - valueNotificationCB = null; - } - /** * Characteristic Descriptor Handle * <p> diff --git a/java/jau/direct_bt/DBTManager.java b/java/jau/direct_bt/DBTManager.java index f2ca6746..9a943a8d 100644 --- a/java/jau/direct_bt/DBTManager.java +++ b/java/jau/direct_bt/DBTManager.java @@ -45,6 +45,7 @@ import org.direct_bt.BTManager; import org.direct_bt.BTObject; import org.direct_bt.BTType; import org.direct_bt.HCIStatusCode; +import org.direct_bt.ScanType; public class DBTManager implements BTManager { @@ -142,7 +143,7 @@ public class DBTManager implements BTManager * Enables or disables uuid128_t consolidation * for native uuid16_t and uuid32_t values before string conversion. * <p> - * Default is {@code true}, as this represent compatibility with original TinyB D-Bus behavior. + * Default is {@code true}. * </p> * <p> * If desired, this value should be set once before the first call of {@link #getManager()}! @@ -173,38 +174,6 @@ public class DBTManager implements BTManager } @Override - public <T extends BTObject> T find(final String name, final String identifier, final BTObject parent, final long timeoutMS) { - // Due to generic type erasure, we cannot determine the matching BluetoothType for the return parameter, - // hence this orig TinyB API method is rather misleading than useful. - throw new UnsupportedOperationException("Generic return type 'find' won't be implemented."); - // return (T) find(BluetoothType.NONE, name, identifier, parent, timeoutMS); - } - - @Override - public <T extends BTObject> T find(final String name, final String identifier, final BTObject parent) { - // Due to generic type erasure, we cannot determine the matching BluetoothType for the return parameter, - // hence this orig TinyB API method is rather misleading than useful. - throw new UnsupportedOperationException("Generic return type 'find' won't be implemented."); - // return (T) find(BluetoothType.NONE, name, identifier, parent, 0); - } - - @Override - public BTObject getObject(final BTType type, final String name, - final String identifier, final BTObject parent) { - return getObject(type.ordinal(), name, identifier, parent); - } - private BTObject getObject(final int type, final String name, final String identifier, final BTObject parent) - { throw new UnsupportedOperationException(); } // FIXME - - @Override - public List<BTObject> getObjects(final BTType type, final String name, - final String identifier, final BTObject parent) { - return getObjects(type.ordinal(), name, identifier, parent); - } - private List<BTObject> getObjects(final int type, final String name, final String identifier, final BTObject parent) - { throw new UnsupportedOperationException(); } // FIXME - - @Override public List<BTAdapter> getAdapters() { return new ArrayList<BTAdapter>(adapters); } @Override @@ -269,9 +238,6 @@ public class DBTManager implements BTManager } @Override - public boolean startDiscovery() throws BTException { return HCIStatusCode.SUCCESS == startDiscovery(true, false); } - - @Override public HCIStatusCode startDiscovery(final boolean keepAlive, final boolean le_scan_active) throws BTException { return getDefaultAdapter().startDiscovery(keepAlive, le_scan_active); } @@ -279,9 +245,10 @@ public class DBTManager implements BTManager @Override public HCIStatusCode stopDiscovery() throws BTException { return getDefaultAdapter().stopDiscovery(); } - @SuppressWarnings("deprecation") @Override - public boolean getDiscovering() throws BTException { return getDefaultAdapter().getDiscovering(); } + public final ScanType getCurrentScanType() { + return getDefaultAdapter().getCurrentScanType(); + } @Override public final void addChangedAdapterSetListener(final ChangedAdapterSetListener l) { @@ -413,27 +380,14 @@ public class DBTManager implements BTManager } catch (final BTException be) { be.printStackTrace(); } - final boolean supCharValCacheNotify; - { - final String v = System.getProperty("jau.direct_bt.characteristic.compat", "false"); - supCharValCacheNotify = Boolean.valueOf(v); - } settings = new Settings() { @Override public final boolean isDirectBT() { return true; } @Override - public boolean isTinyB() { - return false; - } - @Override - public boolean isCharValueCacheNotificationSupported() { - return supCharValCacheNotify; - } - @Override public String toString() { - return "Settings[dbt true, tinyb false, charValueCacheNotify "+isCharValueCacheNotificationSupported()+"]"; + return "Settings[dbt true]"; } }; } @@ -516,13 +470,13 @@ public class DBTManager implements BTManager if( ( anyType || adapterType ) ) { if( null != name && null != identifier && adapter.getName().equals(name) && - adapter.getAddressString().equals(identifier) + adapter.getAddressAndType().address.toString().equals(identifier) ) { return adapter; } if( null != identifier && - adapter.getAddressString().equals(identifier) + adapter.getAddressAndType().address.toString().equals(identifier) ) { return adapter; diff --git a/java/jni/direct_bt/CMakeLists.txt b/java/jni/direct_bt/CMakeLists.txt index 92f83970..3952d63a 100644 --- a/java/jni/direct_bt/CMakeLists.txt +++ b/java/jni/direct_bt/CMakeLists.txt @@ -28,7 +28,6 @@ set (direct_bt_JNI_SRCS ${PROJECT_SOURCE_DIR}/java/jni/direct_bt/helper_dbt.cxx ${PROJECT_SOURCE_DIR}/java/jni/direct_bt/DBTAdapter.cxx ${PROJECT_SOURCE_DIR}/java/jni/direct_bt/DBTDevice.cxx - ${PROJECT_SOURCE_DIR}/java/jni/direct_bt/DBTEvent.cxx ${PROJECT_SOURCE_DIR}/java/jni/direct_bt/DBTGattChar.cxx ${PROJECT_SOURCE_DIR}/java/jni/direct_bt/DBTGattDesc.cxx ${PROJECT_SOURCE_DIR}/java/jni/direct_bt/DBTGattService.cxx diff --git a/java/jni/direct_bt/DBTAdapter.cxx b/java/jni/direct_bt/DBTAdapter.cxx index 0b19145e..5fceee87 100644 --- a/java/jni/direct_bt/DBTAdapter.cxx +++ b/java/jni/direct_bt/DBTAdapter.cxx @@ -62,8 +62,6 @@ static const std::string _deviceDisconnectedMethodArgs("(Lorg/direct_bt/BTDevice class JNIAdapterStatusListener : public AdapterStatusListener { private: /** - package org.tinyb; - public abstract class AdapterStatusListener { private long nativeInstance; @@ -503,7 +501,7 @@ jboolean Java_jau_direct_1bt_DBTAdapter_addStatusListenerImpl(JNIEnv *env, jobje { JNIAdapterStatusListener * pre = jau::getInstanceUnchecked<JNIAdapterStatusListener>(env, statusListener); if( nullptr != pre ) { - WARN_PRINT("JNIAdapterStatusListener::addStatusListener: statusListener's nativeInstance not null, already in use"); + throw jau::IllegalStateException("JNIAdapterStatusListener::addStatusListener: statusListener's nativeInstance not null, already in use", E_FILE_LINE); return false; } } @@ -549,7 +547,6 @@ jboolean Java_jau_direct_1bt_DBTAdapter_addStatusListenerImpl(JNIEnv *env, jobje jau::clearInstance(env, statusListener); rethrow_and_raise_java_exception(env); } - ERR_PRINT("JNIAdapterStatusListener::addStatusListener: FAILED XX"); return JNI_FALSE; } @@ -955,16 +952,6 @@ jboolean Java_jau_direct_1bt_DBTAdapter_setPairable(JNIEnv *env, jobject obj, jb return JNI_FALSE; } -void Java_jau_direct_1bt_DBTAdapter_setDiscoveryFilter(JNIEnv *env, jobject obj, jobject juuids, jint rssi, jint pathloss, jint transportType) { - // List<String> uuids - (void)env; - (void)obj; - (void)juuids; - (void)rssi; - (void)pathloss; - (void)transportType; -} - void Java_jau_direct_1bt_DBTAdapter_printDeviceListsImpl(JNIEnv *env, jobject obj) { try { BTAdapter *adapter = jau::getJavaUplinkObject<BTAdapter>(env, obj); diff --git a/java/jni/direct_bt/DBTDevice.cxx b/java/jni/direct_bt/DBTDevice.cxx index 1ca51fe5..13d965f4 100644 --- a/java/jni/direct_bt/DBTDevice.cxx +++ b/java/jni/direct_bt/DBTDevice.cxx @@ -44,8 +44,6 @@ static const std::string _indicationReceivedMethodArgs("(Lorg/direct_bt/BTGattCh class JNIGattCharListener : public BTGattCharListener { private: /** - package org.tinyb; - public abstract class BTGattCharListener { long nativeInstance; @@ -639,8 +637,6 @@ jobject Java_jau_direct_1bt_DBTDevice_getServicesImpl(JNIEnv *env, jobject obj) if( services.size() > 0 ) { std::shared_ptr<GattGenericAccessSvc> ga = device->getGattGenericAccess(); if( nullptr != ga ) { - env->SetShortField(obj, getField(env, obj, "appearance", "S"), static_cast<jshort>(ga->appearance)); - java_exception_check_and_throw(env, E_FILE_LINE); DBG_PRINT("BTDevice.getServices(): GenericAccess: %s", ga->toString().c_str()); } } else { @@ -693,54 +689,6 @@ jboolean Java_jau_direct_1bt_DBTDevice_pingGATTImpl(JNIEnv *env, jobject obj) return JNI_FALSE; } -jstring Java_jau_direct_1bt_DBTDevice_getIcon(JNIEnv *env, jobject obj) -{ - try { - BTDevice *device = getJavaUplinkObject<BTDevice>(env, obj); - JavaGlobalObj::check(device->getJavaObject(), E_FILE_LINE); - return nullptr; // FIXME - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; // FIXME; -} - -void Java_jau_direct_1bt_DBTDevice_setTrustedImpl(JNIEnv *env, jobject obj, jboolean value) -{ - try { - BTDevice *device = getJavaUplinkObject<BTDevice>(env, obj); - JavaGlobalObj::check(device->getJavaObject(), E_FILE_LINE); - (void)value; - // FIXME - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - -void Java_jau_direct_1bt_DBTDevice_setBlockedImpl(JNIEnv *env, jobject obj, jboolean value) -{ - try { - BTDevice *device = getJavaUplinkObject<BTDevice>(env, obj); - JavaGlobalObj::check(device->getJavaObject(), E_FILE_LINE); - (void)value; - // FIXME - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - -jboolean JNICALL Java_jau_direct_1bt_DBTDevice_getLegacyPairing(JNIEnv *env, jobject obj) -{ - try { - BTDevice *device = getJavaUplinkObject<BTDevice>(env, obj); - JavaGlobalObj::check(device->getJavaObject(), E_FILE_LINE); - return JNI_FALSE; // FIXME - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return JNI_FALSE; -} - jshort Java_jau_direct_1bt_DBTDevice_getRSSI(JNIEnv *env, jobject obj) { try { @@ -753,31 +701,6 @@ jshort Java_jau_direct_1bt_DBTDevice_getRSSI(JNIEnv *env, jobject obj) return 0; } - -jobjectArray Java_jau_direct_1bt_DBTDevice_getUUIDs(JNIEnv *env, jobject obj) -{ - try { - BTDevice *device = getJavaUplinkObject<BTDevice>(env, obj); - JavaGlobalObj::check(device->getJavaObject(), E_FILE_LINE); - return nullptr; // FIXME - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -jstring Java_jau_direct_1bt_DBTDevice_getModalias(JNIEnv *env, jobject obj) -{ - try { - BTDevice *device = getJavaUplinkObject<BTDevice>(env, obj); - JavaGlobalObj::check(device->getJavaObject(), E_FILE_LINE); - return nullptr; // FIXME - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - jobject Java_jau_direct_1bt_DBTDevice_getManufacturerData(JNIEnv *env, jobject obj) { try { @@ -827,6 +750,10 @@ jshort Java_jau_direct_1bt_DBTDevice_getTxPower(JNIEnv *env, jobject obj) return 0; } +#if 0 +// +// Leave below code 'in' disabled, as an example of how to bind Java callback functions to C++ callback functions ad-hoc. + // // BooleanDeviceCBContext // @@ -866,99 +793,8 @@ typedef std::shared_ptr<BooleanDeviceCBContext> BooleanDeviceCBContextRef; // -// Blocked -// - -static void disableBlockedNotifications(JNIEnv *env, jobject obj, BTManager &mgmt) -{ - InvocationFunc<bool, const MgmtEvent&> * funcptr = - getObjectRef<InvocationFunc<bool, const MgmtEvent&>>(env, obj, "blockedNotificationRef"); - if( nullptr != funcptr ) { - FunctionDef<bool, const MgmtEvent&> funcDef( funcptr ); - funcptr = nullptr; - setObjectRef(env, obj, funcptr, "blockedNotificationRef"); // clear java ref - int count; - if( 1 != ( count = mgmt.removeMgmtEventCallback(MgmtEvent::Opcode::DEVICE_BLOCKED, funcDef) ) ) { - throw InternalError(std::string("removeMgmtEventCallback of ")+funcDef.toString()+" not 1 but "+std::to_string(count), E_FILE_LINE); - } - if( 1 != ( count = mgmt.removeMgmtEventCallback(MgmtEvent::Opcode::DEVICE_UNBLOCKED, funcDef) ) ) { - throw InternalError(std::string("removeMgmtEventCallback of ")+funcDef.toString()+" not 1 but "+std::to_string(count), E_FILE_LINE); - } - } -} -void Java_jau_direct_1bt_DBTDevice_disableBlockedNotificationsImpl(JNIEnv *env, jobject obj) -{ - try { - BTDevice *device = getJavaUplinkObject<BTDevice>(env, obj); - JavaGlobalObj::check(device->getJavaObject(), E_FILE_LINE); - BTManager & mgmt = device->getAdapter().getManager(); - - disableBlockedNotifications(env, obj, mgmt); - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} -void Java_jau_direct_1bt_DBTDevice_enableBlockedNotificationsImpl(JNIEnv *env, jobject obj, jobject javaCallback) -{ - try { - BTDevice *device= getJavaUplinkObject<BTDevice>(env, obj); - JavaGlobalObj::check(device->getJavaObject(), E_FILE_LINE); - BTAdapter & adapter = device->getAdapter(); - BTManager & mgmt = adapter.getManager(); - - disableBlockedNotifications(env, obj, mgmt); - - bool(*nativeCallback)(BooleanDeviceCBContextRef&, const MgmtEvent&) = - [](BooleanDeviceCBContextRef& ctx_ref, const MgmtEvent& e)->bool { - bool isBlocked = false; - if( MgmtEvent::Opcode::DEVICE_BLOCKED == e.getOpcode() ) { - const MgmtEvtDeviceBlocked &event = *static_cast<const MgmtEvtDeviceBlocked *>(&e); - if( event.getAddress() != ctx_ref->addressAndType.address || event.getAddressType() != ctx_ref->addressAndType.type ) { - return false; // not this device - } - isBlocked = true; - } else if( MgmtEvent::Opcode::DEVICE_UNBLOCKED == e.getOpcode() ) { - const MgmtEvtDeviceUnblocked &event = *static_cast<const MgmtEvtDeviceUnblocked *>(&e); - if( event.getAddress() != ctx_ref->addressAndType.address || event.getAddressType() != ctx_ref->addressAndType.type ) { - return false; // not this device - } - isBlocked = false; - } else { - return false; // oops - } - - jobject result = jni_env->NewObject(ctx_ref->boolean_cls_ref.getClass(), ctx_ref->boolean_ctor, isBlocked ? JNI_TRUE : JNI_FALSE); - jni_env->CallVoidMethod(*(ctx_ref->javaCallback_ref), ctx_ref->mRun, result); - jni_env->DeleteLocalRef(result); - return true; - }; - jclass notification = search_class(*jni_env, javaCallback); - jmethodID mRun = search_method(*jni_env, notification, "run", "(Ljava/lang/Object;)V", false); - java_exception_check_and_throw(env, E_FILE_LINE); - jni_env->DeleteLocalRef(notification); - - jclass boolean_cls = search_class(*jni_env, "java/lang/Boolean"); - jmethodID boolean_ctor = search_method(*jni_env, boolean_cls, "<init>", "(Z)V", false); - java_exception_check_and_throw(env, E_FILE_LINE); - - BooleanDeviceCBContextRef ctx_ref = std::make_shared<BooleanDeviceCBContext>( - device->getAddressAndType(), JNIGlobalRef(javaCallback), mRun, JNIGlobalRef(boolean_cls), boolean_ctor ); - jni_env->DeleteLocalRef(boolean_cls); - - // move BooleanDeviceCBContextRef into CaptureInvocationFunc and operator== includes javaCallback comparison - FunctionDef<bool, const MgmtEvent&> funcDef = bindCaptureFunc(ctx_ref, nativeCallback); - setObjectRef(env, obj, funcDef.cloneFunction(), "blockedNotificationRef"); // set java ref - mgmt.addMgmtEventCallback(adapter.dev_id, MgmtEvent::Opcode::DEVICE_BLOCKED, funcDef); - mgmt.addMgmtEventCallback(adapter.dev_id, MgmtEvent::Opcode::DEVICE_UNBLOCKED, funcDef); - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - -// // Paired // - static void disablePairedNotifications(JNIEnv *env, jobject obj, BTManager &mgmt) { InvocationFunc<bool, const MgmtEvent&> * funcptr = @@ -1028,3 +864,4 @@ void Java_jau_direct_1bt_DBTDevice_enablePairedNotificationsImpl(JNIEnv *env, jo rethrow_and_raise_java_exception(env); } } +#endif diff --git a/java/jni/direct_bt/DBTEvent.cxx b/java/jni/direct_bt/DBTEvent.cxx deleted file mode 100644 index 39dd4cf4..00000000 --- a/java/jni/direct_bt/DBTEvent.cxx +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Author: Sven Gothel <[email protected]> - * Copyright (c) 2020 Gothel Software e.K. - * Copyright (c) 2020 ZAFENA AB - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#include "jau_direct_bt_DBTEvent.h" - -jobject Java_jau_direct_1bt_DBTEvent_getType(JNIEnv *env, jobject obj) -{ - (void)env; - (void)obj; - - return NULL; -} - -jstring Java_jau_direct_1bt_DBTEvent_getName(JNIEnv *env, jobject obj) -{ - (void)env; - (void)obj; - - return NULL; -} - -jstring Java_jau_direct_1bt_DBTEvent_getIdentifier(JNIEnv *env, jobject obj) -{ - (void)env; - (void)obj; - - return NULL; -} - -jboolean Java_jau_direct_1bt_DBTEvent_executeCallback(JNIEnv *env, jobject obj) -{ - (void)env; - (void)obj; - - return JNI_FALSE; -} - -jboolean Java_jau_direct_1bt_DBTEvent_hasCallback(JNIEnv *env, jobject obj) -{ - (void)env; - (void)obj; - - return JNI_FALSE; -} - -void Java_jau_direct_1bt_DBTEvent_init(JNIEnv *env, jobject obj, jobject type, jstring name, - jstring identifier, jobject parent, jobject callback, - jobject arg_data) -{ - (void)env; - (void)obj; - (void)type; - (void)name; - (void)identifier; - (void)parent; - (void)callback; - (void)arg_data; -} - -void Java_jau_direct_1bt_DBTEvent_delete(JNIEnv *env, jobject obj) -{ - (void)env; - (void)obj; -} - diff --git a/java/jni/direct_bt/DBTGattService.cxx b/java/jni/direct_bt/DBTGattService.cxx index 085ef1a1..43539077 100644 --- a/java/jni/direct_bt/DBTGattService.cxx +++ b/java/jni/direct_bt/DBTGattService.cxx @@ -60,7 +60,9 @@ void Java_jau_direct_1bt_DBTGattService_deleteImpl(JNIEnv *env, jobject obj, jlo } } -static const std::string _characteristicClazzCtorArgs("(JLjau/direct_bt/DBTGattService;S[Ljava/lang/String;ZZLjava/lang/String;SI)V"); +static const std::string _characteristicClazzCtorArgs("(JLjau/direct_bt/DBTGattService;SLorg/direct_bt/GattCharPropertySet;Ljava/lang/String;SI)V"); +static const std::string _gattCharPropSetClassName("org/direct_bt/GattCharPropertySet"); +static const std::string _gattCharPropSetClazzCtorArgs("(B)V"); jobject Java_jau_direct_1bt_DBTGattService_getCharsImpl(JNIEnv *env, jobject obj) { try { @@ -69,57 +71,60 @@ jobject Java_jau_direct_1bt_DBTGattService_getCharsImpl(JNIEnv *env, jobject obj jau::darray<std::shared_ptr<BTGattChar>> & characteristics = service->characteristicList; - // BTGattChar(final long nativeInstance, final BTGattService service, - // final short handle, final String[] properties, - // final boolean hasNotify, final boolean hasIndicate, - // final String value_type_uuid, final short value_handle, - // final int clientCharacteristicsConfigIndex) - + jclass gattCharPropSetClazz; + jmethodID gattCharPropSetClazzCtor; + // gattCharPropSetClazzRef, gattCharPropSetClazzCtor + { + gattCharPropSetClazz = jau::search_class(env, _gattCharPropSetClassName.c_str()); + jau::java_exception_check_and_throw(env, E_FILE_LINE); + if( nullptr == gattCharPropSetClazz ) { + throw jau::InternalError("BTDevice::java_class not found: "+_gattCharPropSetClassName, E_FILE_LINE); + } + } + gattCharPropSetClazzCtor = jau::search_method(env, gattCharPropSetClazz, "<init>", _gattCharPropSetClazzCtorArgs.c_str(), false); + jau::java_exception_check_and_throw(env, E_FILE_LINE); + if( nullptr == gattCharPropSetClazzCtor ) { + throw jau::InternalError("GattCharPropertySet ctor not found: "+_gattCharPropSetClassName+".<init>"+_gattCharPropSetClazzCtorArgs, E_FILE_LINE); + } + + /** + DBTGattChar(final long nativeInstance, final DBTGattService service, + final short handle, final GattCharPropertySet properties, + final String value_type_uuid, final short value_handle, + final int clientCharacteristicsConfigIndex) + */ std::function<jobject(JNIEnv*, jclass, jmethodID, BTGattChar *)> ctor_char = - [](JNIEnv *env_, jclass clazz, jmethodID clazz_ctor, BTGattChar *characteristic)->jobject { + [&gattCharPropSetClazz, &gattCharPropSetClazzCtor](JNIEnv *env_, jclass clazz, jmethodID clazz_ctor, BTGattChar *characteristic)->jobject { // prepare adapter ctor std::shared_ptr<BTGattService> _service = characteristic->getServiceChecked(); JavaGlobalObj::check(_service->getJavaObject(), E_FILE_LINE); jobject jservice = JavaGlobalObj::GetObject(_service->getJavaObject()); - jau::darray<std::unique_ptr<std::string>> props = BTGattChar::getPropertiesStringList(characteristic->properties); - size_t props_size = props.size(); - - jobjectArray jproperties; - { - jclass string_class = search_class(env_, "java/lang/String"); - jproperties = env_->NewObjectArray((jsize)props_size, string_class, 0); - java_exception_check_and_throw(env_, E_FILE_LINE); - env_->DeleteLocalRef(string_class); - } - for (size_t i = 0; i < props_size; ++i) { - jobject elem = from_string_to_jstring(env_, *props[i].get()); - env_->SetObjectArrayElement(jproperties, (jsize)i, elem); - env_->DeleteLocalRef(elem); - } + jobject jGattCharPropSet = env_->NewObject(gattCharPropSetClazz, gattCharPropSetClazzCtor, (jbyte)characteristic->properties); + jau::java_exception_check_and_throw(env_, E_FILE_LINE); + JNIGlobalRef::check(jGattCharPropSet, E_FILE_LINE); java_exception_check_and_throw(env_, E_FILE_LINE); - const bool hasNotify = characteristic->hasProperties(BTGattChar::PropertyBitVal::Notify); - const bool hasIndicate = characteristic->hasProperties(BTGattChar::PropertyBitVal::Indicate); - const jstring uuid = from_string_to_jstring(env_, directBTJNISettings.getUnifyUUID128Bit() ? characteristic->value_type->toUUID128String() : characteristic->value_type->toString()); java_exception_check_and_throw(env_, E_FILE_LINE); jobject jcharVal = env_->NewObject(clazz, clazz_ctor, (jlong)characteristic, jservice, - characteristic->handle, jproperties, hasNotify, hasIndicate, + characteristic->handle, jGattCharPropSet, uuid, characteristic->value_handle, characteristic->clientCharConfigIndex); java_exception_check_and_throw(env_, E_FILE_LINE); JNIGlobalRef::check(jcharVal, E_FILE_LINE); std::shared_ptr<JavaAnon> jCharRef = characteristic->getJavaObject(); // GlobalRef JavaGlobalObj::check(jCharRef, E_FILE_LINE); - env_->DeleteLocalRef(jproperties); + env_->DeleteLocalRef(jGattCharPropSet); env_->DeleteLocalRef(jcharVal); return JavaGlobalObj::GetObject(jCharRef); }; - return convert_vector_sharedptr_to_jarraylist<jau::darray<std::shared_ptr<BTGattChar>>, BTGattChar>( + jobject jres = convert_vector_sharedptr_to_jarraylist<jau::darray<std::shared_ptr<BTGattChar>>, BTGattChar>( env, characteristics, _characteristicClazzCtorArgs.c_str(), ctor_char); + env->DeleteLocalRef(gattCharPropSetClazz); + return jres; } catch(...) { rethrow_and_raise_java_exception(env); } diff --git a/java/jni/direct_bt/helper_dbt.hpp b/java/jni/direct_bt/helper_dbt.hpp index 584e842d..8c7a45b5 100644 --- a/java/jni/direct_bt/helper_dbt.hpp +++ b/java/jni/direct_bt/helper_dbt.hpp @@ -41,7 +41,7 @@ namespace direct_bt { * Enables or disables uuid128_t consolidation * for native uuid16_t and uuid32_t values before string conversion. * <p> - * Default is {@code true}, as this represent compatibility with original TinyB D-Bus behavior. + * Default is {@code true}. * </p> */ bool getUnifyUUID128Bit() { return unifyUUID128Bit; } diff --git a/java/jni/helper_base.cxx b/java/jni/helper_base.cxx index c08c9280..84a6e4c2 100644 --- a/java/jni/helper_base.cxx +++ b/java/jni/helper_base.cxx @@ -50,10 +50,6 @@ void raise_java_exception(JNIEnv *env, const direct_bt::BTException &e, const ch jau::print_native_caught_exception_fwd2java(e, file, line); env->ThrowNew(env->FindClass("org/direct_bt/BTException"), e.what()); } -void raise_java_exception(JNIEnv *env, const tinyb::BluetoothException &e, const char* file, int line) { - jau::print_native_caught_exception_fwd2java(e, file, line); - env->ThrowNew(env->FindClass("org/direct_bt/BTException"), e.what()); -} static std::string _unknown_exception_type_msg("Unknown exception type"); @@ -80,8 +76,6 @@ void rethrow_and_raise_java_exception_impl(JNIEnv *env, const char* file, int li jau::raise_java_exception(env, e, file, line); } catch (const direct_bt::BTException &e) { raise_java_exception(env, e, file, line); - } catch (const tinyb::BluetoothException &e) { - raise_java_exception(env, e, file, line); } catch (const jau::RuntimeException &e) { jau::raise_java_exception(env, e, file, line); } catch (const std::runtime_error &e) { diff --git a/java/jni/helper_base.hpp b/java/jni/helper_base.hpp index 05293108..2e678236 100644 --- a/java/jni/helper_base.hpp +++ b/java/jni/helper_base.hpp @@ -37,12 +37,10 @@ #include <jau/jni/helper_jni.hpp> #include "direct_bt/BTTypes0.hpp" -#include "tinyb/BluetoothException.hpp" jobject get_bluetooth_type(JNIEnv *env, const char *field_name); void raise_java_exception(JNIEnv *env, const direct_bt::BTException &e, const char* file, int line); -void raise_java_exception(JNIEnv *env, const tinyb::BluetoothException &e, const char* file, int line); /** * Re-throw current exception and raise respective java exception diff --git a/java/jni/tinyb/CMakeLists.txt b/java/jni/tinyb/CMakeLists.txt deleted file mode 100644 index 0e98beb3..00000000 --- a/java/jni/tinyb/CMakeLists.txt +++ /dev/null @@ -1,64 +0,0 @@ -find_package(JNI REQUIRED) - -if (JNI_FOUND) - message (STATUS "JNI_INCLUDE_DIRS=${JNI_INCLUDE_DIRS}") - message (STATUS "JNI_LIBRARIES=${JNI_LIBRARIES}") -endif (JNI_FOUND) - -set (tinyb_LIB_INCLUDE_DIRS - ${PROJECT_SOURCE_DIR}/jaulib/include - ${PROJECT_SOURCE_DIR}/api - ${PROJECT_SOURCE_DIR}/api/direct_bt - ${PROJECT_SOURCE_DIR}/api/tinyb - ${PROJECT_SOURCE_DIR}/include - ${PROJECT_SOURCE_DIR}/java/jni -) - -include_directories( - ${JNI_INCLUDE_DIRS} - ${tinyb_LIB_INCLUDE_DIRS} - ${JNI_HEADER_PATH} -) - -set (tinyb_JNI_SRCS - ${PROJECT_SOURCE_DIR}/jaulib/java_jni/jni/jni_mem.cxx - ${PROJECT_SOURCE_DIR}/jaulib/java_jni/jni/helper_jni.cxx - ${PROJECT_SOURCE_DIR}/jaulib/src/basic_types.cpp - ${PROJECT_SOURCE_DIR}/java/jni/helper_base.cxx - ${PROJECT_SOURCE_DIR}/java/jni/BTFactory.cxx - ${PROJECT_SOURCE_DIR}/java/jni/BTUtils.cxx - ${PROJECT_SOURCE_DIR}/java/jni/tinyb/helper_tinyb.cxx - ${PROJECT_SOURCE_DIR}/java/jni/tinyb/DBusAdapter.cxx - ${PROJECT_SOURCE_DIR}/java/jni/tinyb/DBusDevice.cxx - ${PROJECT_SOURCE_DIR}/java/jni/tinyb/DBusEvent.cxx - ${PROJECT_SOURCE_DIR}/java/jni/tinyb/DBusGattCharacteristic.cxx - ${PROJECT_SOURCE_DIR}/java/jni/tinyb/DBusGattDescriptor.cxx - ${PROJECT_SOURCE_DIR}/java/jni/tinyb/DBusGattService.cxx - ${PROJECT_SOURCE_DIR}/java/jni/tinyb/DBusManager.cxx - ${PROJECT_SOURCE_DIR}/java/jni/tinyb/DBusObject.cxx -) - -set (CMAKE_SHARED_LINKER_FLAGS "-Wl,--as-needed") - -add_library (javatinyb SHARED ${tinyb_JNI_SRCS}) -target_link_libraries(javatinyb ${JNI_LIBRARIES} tinyb) - -if(USE_STRIP) -add_custom_command(TARGET javatinyb POST_BUILD - COMMAND ${STRIP} ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_SHARED_LIBRARY_PREFIX}javatinyb${CMAKE_SHARED_LIBRARY_SUFFIX}.${tinyb_VERSION_STRING} - COMMENT "stripping javatinyb" - VERBATIM - ) -endif(USE_STRIP) - -set_target_properties( - javatinyb - PROPERTIES - SOVERSION ${tinyb_VERSION_MAJOR} - VERSION ${tinyb_VERSION_STRING} -) - -install(TARGETS javatinyb LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}) - -add_dependencies(javatinyb tinyb direct_bt_jar) - diff --git a/java/jni/tinyb/DBusAdapter.cxx b/java/jni/tinyb/DBusAdapter.cxx deleted file mode 100644 index 531a046e..00000000 --- a/java/jni/tinyb/DBusAdapter.cxx +++ /dev/null @@ -1,594 +0,0 @@ -/* - * Author: Andrei Vasiliu <[email protected]> - * Copyright (c) 2016 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#include "tinyb/BluetoothAdapter.hpp" -#include "tinyb/BluetoothDevice.hpp" -#include "tinyb/BluetoothObject.hpp" - -#include "tinyb_dbus_DBusAdapter.h" - -#include "helper_tinyb.hpp" - -using namespace tinyb; -using namespace jau; - -jobject Java_tinyb_dbus_DBusAdapter_getBluetoothType(JNIEnv *env, jobject obj) -{ - try { - (void)obj; - - return get_bluetooth_type(env, "ADAPTER"); - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -jobject Java_tinyb_dbus_DBusAdapter_clone(JNIEnv *env, jobject obj) -{ - try { - return generic_clone<BluetoothAdapter>(env, obj); - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -jboolean Java_tinyb_dbus_DBusAdapter_startDiscovery(JNIEnv *env, jobject obj) -{ - try { - BluetoothAdapter *obj_adapter = getInstance<BluetoothAdapter>(env, obj); - - return obj_adapter->start_discovery() ? JNI_TRUE : JNI_FALSE; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return JNI_FALSE; -} - -jboolean Java_tinyb_dbus_DBusAdapter_stopDiscoveryImpl(JNIEnv *env, jobject obj) -{ - try { - BluetoothAdapter *obj_adapter = getInstance<BluetoothAdapter>(env, obj); - - return obj_adapter->stop_discovery() ? JNI_TRUE : JNI_FALSE; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return JNI_FALSE; -} - -jobject Java_tinyb_dbus_DBusAdapter_getDiscoveredDevices(JNIEnv *env, jobject obj) -{ - try { - BluetoothAdapter *obj_adapter = getInstance<BluetoothAdapter>(env, obj); - std::vector<std::unique_ptr<BluetoothDevice>> array = obj_adapter->get_devices(); - jobject result = convert_vector_uniqueptr_to_jarraylist<std::vector<std::unique_ptr<BluetoothDevice>>, BluetoothDevice>( - env, array, "(J)V"); - - return result; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -jint Java_tinyb_dbus_DBusAdapter_removeDiscoveredDevices(JNIEnv *env, jobject obj) -{ - try { - BluetoothAdapter *obj_adapter = getInstance<BluetoothAdapter>(env, obj); - std::vector<std::unique_ptr<tinyb::BluetoothDevice>> array = obj_adapter->get_devices(); - - for (unsigned int i =0;i<array.size();i++) { - std::unique_ptr<tinyb::BluetoothDevice> *obj_device = &array.at(i); - std::string path = obj_device->get()->get_object_path(); - // printf("PATH:%s\n", path.c_str()); - // fflush(stdout); - obj_adapter->remove_device(path.c_str()); - - } - return array.size(); - - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return 0; -} - -jstring Java_tinyb_dbus_DBusAdapter_getAddressString(JNIEnv *env, jobject obj) -{ - try { - BluetoothAdapter *obj_adapter = getInstance<BluetoothAdapter>(env, obj); - std::string address = obj_adapter->get_address(); - - return env->NewStringUTF((const char *)address.c_str()); - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -jstring Java_tinyb_dbus_DBusAdapter_getName(JNIEnv *env, jobject obj) -{ - try { - BluetoothAdapter *obj_adapter = getInstance<BluetoothAdapter>(env, obj); - std::string name = obj_adapter->get_name(); - - return env->NewStringUTF((const char *)name.c_str()); - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -jstring Java_tinyb_dbus_DBusAdapter_getAlias(JNIEnv *env, jobject obj) -{ - try { - BluetoothAdapter *obj_adapter = getInstance<BluetoothAdapter>(env, obj); - std::string alias = obj_adapter->get_alias(); - - return env->NewStringUTF((const char *)alias.c_str()); - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -void Java_tinyb_dbus_DBusAdapter_setAlias(JNIEnv *env, jobject obj, jstring str) -{ - try { - BluetoothAdapter *obj_adapter = getInstance<BluetoothAdapter>(env, obj); - - const std::string string_to_write = from_jstring_to_string(env, str); - - obj_adapter->set_alias(string_to_write); - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - -jlong Java_tinyb_dbus_DBusAdapter_getBluetoothClass(JNIEnv *env, jobject obj) -{ - try { - BluetoothAdapter *obj_adapter = getInstance<BluetoothAdapter>(env, obj); - - return (jlong)obj_adapter->get_class(); - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return 0; -} - -jboolean Java_tinyb_dbus_DBusAdapter_getPoweredState(JNIEnv *env, jobject obj) -{ - try { - BluetoothAdapter *obj_adapter = getInstance<BluetoothAdapter>(env, obj); - - return obj_adapter->get_powered() ? JNI_TRUE : JNI_FALSE; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return JNI_FALSE; -} - -jboolean Java_tinyb_dbus_DBusAdapter_setPowered(JNIEnv *env, jobject obj, jboolean val) -{ - try { - BluetoothAdapter *obj_adapter = getInstance<BluetoothAdapter>(env, obj); - - bool val_to_write = from_jboolean_to_bool(val); - obj_adapter->set_powered(val_to_write); - return JNI_TRUE; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return JNI_FALSE; -} - -void Java_tinyb_dbus_DBusAdapter_enablePoweredNotifications(JNIEnv *env, jobject obj, jobject callback) -{ - try { - BluetoothAdapter *obj_adapter = - getInstance<BluetoothAdapter>(env, obj); - std::shared_ptr<JNIGlobalRef> callback_ptr(new JNIGlobalRef(callback)); - obj_adapter->enable_powered_notifications([ callback_ptr ] (bool v) - { - jclass notification = search_class(*jni_env, **callback_ptr); - jmethodID method = search_method(*jni_env, notification, "run", "(Ljava/lang/Object;)V", false); - jni_env->DeleteLocalRef(notification); - - jclass boolean_cls = search_class(*jni_env, "java/lang/Boolean"); - jmethodID constructor = search_method(*jni_env, boolean_cls, "<init>", "(Z)V", false); - - jobject result = jni_env->NewObject(boolean_cls, constructor, v ? JNI_TRUE : JNI_FALSE); - jni_env->DeleteLocalRef(boolean_cls); - - jni_env->CallVoidMethod(**callback_ptr, method, result); - jni_env->DeleteLocalRef(result); - - }); - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - -void Java_tinyb_dbus_DBusAdapter_disablePoweredNotifications(JNIEnv *env, jobject obj) -{ - try { - BluetoothAdapter *obj_adapter = - getInstance<BluetoothAdapter>(env, obj); - obj_adapter->disable_powered_notifications(); - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - -jboolean Java_tinyb_dbus_DBusAdapter_getDiscoverable(JNIEnv *env, jobject obj) -{ - try { - BluetoothAdapter *obj_adapter = getInstance<BluetoothAdapter>(env, obj); - - return obj_adapter->get_discoverable() ? JNI_TRUE : JNI_FALSE; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return JNI_FALSE; -} - -jboolean Java_tinyb_dbus_DBusAdapter_setDiscoverable(JNIEnv *env, jobject obj, jboolean val) -{ - try { - BluetoothAdapter *obj_adapter = getInstance<BluetoothAdapter>(env, obj); - - bool val_to_write = from_jboolean_to_bool(val); - obj_adapter->set_discoverable(val_to_write); - return JNI_TRUE; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return JNI_FALSE; -} - -void Java_tinyb_dbus_DBusAdapter_enableDiscoverableNotifications(JNIEnv *env, jobject obj, jobject callback) -{ - try { - BluetoothAdapter *obj_adapter = - getInstance<BluetoothAdapter>(env, obj); - std::shared_ptr<JNIGlobalRef> callback_ptr(new JNIGlobalRef(callback)); - obj_adapter->enable_discoverable_notifications([ callback_ptr ] (bool v) - { - jclass notification = search_class(*jni_env, **callback_ptr); - jmethodID method = search_method(*jni_env, notification, "run", "(Ljava/lang/Object;)V", false); - jni_env->DeleteLocalRef(notification); - - jclass boolean_cls = search_class(*jni_env, "java/lang/Boolean"); - jmethodID constructor = search_method(*jni_env, boolean_cls, "<init>", "(Z)V", false); - - jobject result = jni_env->NewObject(boolean_cls, constructor, v ? JNI_TRUE : JNI_FALSE); - jni_env->DeleteLocalRef(boolean_cls); - - jni_env->CallVoidMethod(**callback_ptr, method, result); - jni_env->DeleteLocalRef(result); - - }); - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - -void Java_tinyb_dbus_DBusAdapter_disableDiscoverableNotifications(JNIEnv *env, jobject obj) -{ - try { - BluetoothAdapter *obj_adapter = - getInstance<BluetoothAdapter>(env, obj); - obj_adapter->disable_discoverable_notifications(); - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - -jlong Java_tinyb_dbus_DBusAdapter_getDiscoverableTimeout(JNIEnv *env, jobject obj) -{ - try { - BluetoothAdapter *obj_adapter = getInstance<BluetoothAdapter>(env, obj); - - return (jlong)obj_adapter->get_discoverable_timeout(); - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return 0; -} - -jboolean Java_tinyb_dbus_DBusAdapter_setDiscoverableTimout(JNIEnv *env, jobject obj, jlong timeout) -{ - try { - BluetoothAdapter *obj_adapter = getInstance<BluetoothAdapter>(env, obj); - - if (timeout < 0) - { - throw std::invalid_argument("timeout argument is negative\n"); - } - obj_adapter->set_discoverable_timeout((unsigned int)timeout); - return JNI_TRUE; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return JNI_FALSE; -} - -jboolean Java_tinyb_dbus_DBusAdapter_getPairable(JNIEnv *env, jobject obj) -{ - try { - BluetoothAdapter *obj_adapter = getInstance<BluetoothAdapter>(env, obj); - - return obj_adapter->get_pairable() ? JNI_TRUE : JNI_FALSE; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return JNI_FALSE; -} - -void Java_tinyb_dbus_DBusAdapter_enablePairableNotifications(JNIEnv *env, jobject obj, jobject callback) -{ - try { - BluetoothAdapter *obj_adapter = - getInstance<BluetoothAdapter>(env, obj); - std::shared_ptr<JNIGlobalRef> callback_ptr(new JNIGlobalRef(callback)); - obj_adapter->enable_pairable_notifications([ callback_ptr ] (bool v) - { - jclass notification = search_class(*jni_env, **callback_ptr); - jmethodID method = search_method(*jni_env, notification, "run", "(Ljava/lang/Object;)V", false); - jni_env->DeleteLocalRef(notification); - - jclass boolean_cls = search_class(*jni_env, "java/lang/Boolean"); - jmethodID constructor = search_method(*jni_env, boolean_cls, "<init>", "(Z)V", false); - - jobject result = jni_env->NewObject(boolean_cls, constructor, v ? JNI_TRUE : JNI_FALSE); - jni_env->DeleteLocalRef(boolean_cls); - - jni_env->CallVoidMethod(**callback_ptr, method, result); - jni_env->DeleteLocalRef(result); - - }); - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - -void Java_tinyb_dbus_DBusAdapter_disablePairableNotifications(JNIEnv *env, jobject obj) -{ - try { - BluetoothAdapter *obj_adapter = - getInstance<BluetoothAdapter>(env, obj); - obj_adapter->disable_pairable_notifications(); - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - -jboolean Java_tinyb_dbus_DBusAdapter_setPairable(JNIEnv *env, jobject obj, jboolean val) -{ - try { - BluetoothAdapter *obj_adapter = getInstance<BluetoothAdapter>(env, obj); - - bool val_to_write = from_jboolean_to_bool(val); - obj_adapter->set_pairable(val_to_write); - return JNI_TRUE; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return JNI_FALSE; -} - -jlong Java_tinyb_dbus_DBusAdapter_getPairableTimeout(JNIEnv *env, jobject obj) -{ - try { - BluetoothAdapter *obj_adapter = getInstance<BluetoothAdapter>(env, obj); - - return (jlong)obj_adapter->get_pairable_timeout(); - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return 0; -} - -jboolean Java_tinyb_dbus_DBusAdapter_setPairableTimeout(JNIEnv *env, jobject obj, jlong timeout) -{ - try { - BluetoothAdapter *obj_adapter = getInstance<BluetoothAdapter>(env, obj); - - if (timeout < 0) - { - throw std::invalid_argument("timeout argument is negative\n"); - } - obj_adapter->set_pairable_timeout((unsigned int)timeout); - return JNI_TRUE; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return JNI_FALSE; -} - -jboolean Java_tinyb_dbus_DBusAdapter_getDiscovering(JNIEnv *env, jobject obj) -{ - try { - BluetoothAdapter *obj_adapter = getInstance<BluetoothAdapter>(env, obj); - - return obj_adapter->get_discovering() ? JNI_TRUE : JNI_FALSE; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return JNI_FALSE; -} - -void Java_tinyb_dbus_DBusAdapter_enableDiscoveringNotifications(JNIEnv *env, jobject obj, jobject callback) -{ - try { - BluetoothAdapter *obj_adapter = - getInstance<BluetoothAdapter>(env, obj); - std::shared_ptr<JNIGlobalRef> callback_ptr(new JNIGlobalRef(callback)); - obj_adapter->enable_discovering_notifications([ callback_ptr ] (bool v) - { - jclass notification = search_class(*jni_env, **callback_ptr); - jmethodID method = search_method(*jni_env, notification, "run", "(Ljava/lang/Object;)V", false); - jni_env->DeleteLocalRef(notification); - - jclass boolean_cls = search_class(*jni_env, "java/lang/Boolean"); - jmethodID constructor = search_method(*jni_env, boolean_cls, "<init>", "(Z)V", false); - - jobject result = jni_env->NewObject(boolean_cls, constructor, v ? JNI_TRUE : JNI_FALSE); - jni_env->DeleteLocalRef(boolean_cls); - - jni_env->CallVoidMethod(**callback_ptr, method, result); - jni_env->DeleteLocalRef(result); - - }); - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - -void Java_tinyb_dbus_DBusAdapter_disableDiscoveringNotifications(JNIEnv *env, jobject obj) -{ - try { - BluetoothAdapter *obj_adapter = - getInstance<BluetoothAdapter>(env, obj); - obj_adapter->disable_discovering_notifications(); - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - -jobjectArray Java_tinyb_dbus_DBusAdapter_getUUIDs(JNIEnv *env, jobject obj) -{ - try { - BluetoothAdapter *obj_adapter = getInstance<BluetoothAdapter>(env, obj); - std::vector<std::string> uuids = obj_adapter->get_uuids(); - unsigned int uuids_size = uuids.size(); - - jclass string_class = search_class(env, "Ljava/lang/String;"); - jobjectArray result = env->NewObjectArray(uuids_size, string_class, 0); - if (!result) - { - throw std::bad_alloc(); - } - - for (unsigned int i = 0; i < uuids_size; ++i) - { - std::string str_elem = uuids.at(i); - jobject elem = env->NewStringUTF((const char *)str_elem.c_str()); - env->SetObjectArrayElement(result, i, elem); - } - - return result; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -jstring Java_tinyb_dbus_DBusAdapter_getModalias(JNIEnv *env, jobject obj) -{ - try { - BluetoothAdapter *obj_adapter = getInstance<BluetoothAdapter>(env, obj); - std::unique_ptr<std::string> modalias = obj_adapter->get_modalias(); - if(modalias == nullptr) - return nullptr; - - return env->NewStringUTF((const char *)modalias->c_str()); - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -void Java_tinyb_dbus_DBusAdapter_delete(JNIEnv *env, jobject obj) -{ - try { - BluetoothAdapter *adapter = getInstance<BluetoothAdapter>(env, obj); - delete adapter; - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - -void Java_tinyb_dbus_DBusAdapter_setDiscoveryFilter(JNIEnv *env, jobject obj, jobject uuids, jint rssi, jint pathloss, jint transportType) -{ - try { - BluetoothAdapter *obj_adapter = getInstance<BluetoothAdapter>(env, obj); - - jclass cList = env->FindClass("java/util/List"); - - jmethodID mSize = env->GetMethodID(cList, "size", "()I"); - jmethodID mGet = env->GetMethodID(cList, "get", "(I)Ljava/lang/Object;"); - - jint size = env->CallIntMethod(uuids, mSize); - std::vector<BluetoothUUID> native_uuids; - - for (jint i = 0; i < size; i++) { - jstring strObj = (jstring) env->CallObjectMethod(uuids, mGet, i); - const char * chr = env->GetStringUTFChars(strObj, NULL); - BluetoothUUID uuid(chr); - native_uuids.push_back(uuid); - env->ReleaseStringUTFChars(strObj, chr); - } - - TransportType t_type = from_int_to_transport_type((int) transportType); - - obj_adapter->set_discovery_filter(native_uuids, (int16_t) rssi, (uint16_t) pathloss, t_type); - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - -jobject Java_tinyb_dbus_DBusAdapter_connectDeviceImpl(JNIEnv *env, jobject obj, jstring jaddress, jstring jaddressType) -{ - try { - BluetoothAdapter *obj_adapter = getInstance<BluetoothAdapter>(env, obj); - - const std::string address = from_jstring_to_string(env, jaddress); - const std::string addressType = from_jstring_to_string(env, jaddressType); - - fprintf(stderr, "connectDeviceJ.0\n"); fflush(stderr); - std::unique_ptr<tinyb::BluetoothDevice> b_device = obj_adapter->connect_device(address, addressType); - fprintf(stderr, "connectDeviceJ.1\n"); fflush(stderr); - - BluetoothDevice *b_device_naked = b_device.release(); - fprintf(stderr, "connectDeviceJ.2\n"); fflush(stderr); - if (!b_device_naked) - { - return nullptr; - } - jclass clazz = search_class(env, *b_device_naked); - jmethodID clazz_ctor = search_method(env, clazz, "<init>", "(J)V", false); - - jobject result = env->NewObject(clazz, clazz_ctor, (jlong)b_device_naked); - fprintf(stderr, "connectDeviceJ.X\n"); fflush(stderr); - return result; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return NULL; -} - diff --git a/java/jni/tinyb/DBusDevice.cxx b/java/jni/tinyb/DBusDevice.cxx deleted file mode 100644 index aa5c804d..00000000 --- a/java/jni/tinyb/DBusDevice.cxx +++ /dev/null @@ -1,883 +0,0 @@ -/* - * Author: Andrei Vasiliu <[email protected]> - * Copyright (c) 2016 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#include "tinyb/BluetoothAdapter.hpp" -#include "tinyb/BluetoothDevice.hpp" -#include "tinyb/BluetoothGattService.hpp" -#include "tinyb/BluetoothObject.hpp" - -#include "tinyb_dbus_DBusDevice.h" - -#include "helper_tinyb.hpp" - -using namespace tinyb; -using namespace jau; - -jobject Java_tinyb_dbus_DBusDevice_getBluetoothType(JNIEnv *env, jobject obj) -{ - try { - (void)obj; - - return get_bluetooth_type(env, "DEVICE"); - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -jobject Java_tinyb_dbus_DBusDevice_clone(JNIEnv *env, jobject obj) -{ - try { - return generic_clone<BluetoothDevice>(env, obj); - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -jboolean Java_tinyb_dbus_DBusDevice_disconnectImpl(JNIEnv *env, jobject obj) -{ - try { - BluetoothDevice *obj_device = getInstance<BluetoothDevice>(env, obj); - - return obj_device->disconnect() ? JNI_TRUE : JNI_FALSE; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return JNI_FALSE; -} - -void Java_tinyb_dbus_DBusDevice_connectAsyncStart(JNIEnv *env, jobject obj) -{ - try { - BluetoothDevice *obj_device = getInstance<BluetoothDevice>(env, obj); - - obj_device->connect_async_start(); - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - -jboolean Java_tinyb_dbus_DBusDevice_connectAsyncFinish(JNIEnv *env, jobject obj) -{ - try { - BluetoothDevice *obj_device = getInstance<BluetoothDevice>(env, obj); - - return obj_device->connect_async_finish() ? JNI_TRUE : JNI_FALSE; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return JNI_FALSE; -} - -jboolean Java_tinyb_dbus_DBusDevice_connectImpl(JNIEnv *env, jobject obj) -{ - try { - BluetoothDevice *obj_device = getInstance<BluetoothDevice>(env, obj); - - return obj_device->connect() ? JNI_TRUE : JNI_FALSE; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return JNI_FALSE; -} - -jboolean Java_tinyb_dbus_DBusDevice_connectProfile(JNIEnv *env, jobject obj, jstring str) -{ - try { - BluetoothDevice *obj_device = getInstance<BluetoothDevice>(env, obj); - - const std::string string_to_write = from_jstring_to_string(env, str); - - return obj_device->connect_profile(string_to_write) ? JNI_TRUE : JNI_FALSE; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return JNI_FALSE; -} - -jboolean Java_tinyb_dbus_DBusDevice_disconnectProfile(JNIEnv *env, jobject obj, jstring str) -{ - try { - BluetoothDevice *obj_device = getInstance<BluetoothDevice>(env, obj); - - const std::string string_to_write = from_jstring_to_string(env, str); - - return obj_device->disconnect_profile(string_to_write) ? JNI_TRUE : JNI_FALSE; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return JNI_FALSE; -} - -jboolean Java_tinyb_dbus_DBusDevice_pair(JNIEnv *env, jobject obj) -{ - try { - BluetoothDevice *obj_device = getInstance<BluetoothDevice>(env, obj); - - return obj_device->pair() ? JNI_TRUE : JNI_FALSE; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return JNI_FALSE; -} - -jboolean Java_tinyb_dbus_DBusDevice_remove(JNIEnv *env, jobject obj) -{ - try { - BluetoothDevice *obj_device = getInstance<BluetoothDevice>(env, obj); - - return obj_device->remove_device() ? JNI_TRUE : JNI_FALSE; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return JNI_FALSE; -} - -jboolean Java_tinyb_dbus_DBusDevice_cancelPairing(JNIEnv *env, jobject obj) -{ - try { - BluetoothDevice *obj_device = getInstance<BluetoothDevice>(env, obj); - - return obj_device->cancel_pairing() ? JNI_TRUE : JNI_FALSE; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return JNI_FALSE; -} - -jobject Java_tinyb_dbus_DBusDevice_getServices(JNIEnv *env, jobject obj) -{ - try { - BluetoothDevice *obj_device = getInstance<BluetoothDevice>(env, obj); - std::vector<std::unique_ptr<BluetoothGattService>> array = obj_device->get_services(); - jobject result = convert_vector_uniqueptr_to_jarraylist<std::vector<std::unique_ptr<BluetoothGattService>>, BluetoothGattService>( - env, array, "(J)V"); - - return result; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -jstring Java_tinyb_dbus_DBusDevice_getAddressString(JNIEnv *env, jobject obj) -{ - try { - BluetoothDevice *obj_device = getInstance<BluetoothDevice>(env, obj); - std::string address = obj_device->get_address(); - - return env->NewStringUTF((const char *)address.c_str()); - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -jstring Java_tinyb_dbus_DBusDevice_getName(JNIEnv *env, jobject obj) -{ - try { - BluetoothDevice *obj_device = getInstance<BluetoothDevice>(env, obj); - std::string name = obj_device->get_name(); - - return env->NewStringUTF((const char *)name.c_str()); - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -jstring Java_tinyb_dbus_DBusDevice_getAlias(JNIEnv *env, jobject obj) -{ - try { - BluetoothDevice *obj_device = getInstance<BluetoothDevice>(env, obj); - std::string alias = obj_device->get_alias(); - - return env->NewStringUTF((const char *)alias.c_str()); - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -void Java_tinyb_dbus_DBusDevice_setAlias(JNIEnv *env, jobject obj, jstring str) -{ - try { - BluetoothDevice *obj_device = getInstance<BluetoothDevice>(env, obj); - - const std::string string_to_write = from_jstring_to_string(env, str); - - obj_device->set_alias(string_to_write); - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - -jint Java_tinyb_dbus_DBusDevice_getBluetoothClass(JNIEnv *env, jobject obj) -{ - try { - BluetoothDevice *obj_device = getInstance<BluetoothDevice>(env, obj); - - return (jlong)obj_device->get_class(); - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return 0; -} - -jshort Java_tinyb_dbus_DBusDevice_getAppearance(JNIEnv *env, jobject obj) -{ - try { - BluetoothDevice *obj_device = getInstance<BluetoothDevice>(env, obj); - - return (jshort)obj_device->get_appearance(); - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return 0; -} - -jstring Java_tinyb_dbus_DBusDevice_getIcon(JNIEnv *env, jobject obj) -{ - try { - BluetoothDevice *obj_device = getInstance<BluetoothDevice>(env, obj); - std::unique_ptr<std::string> icon = obj_device->get_icon(); - if (icon == nullptr) - return nullptr; - - return env->NewStringUTF((const char *)icon->c_str()); - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -jboolean Java_tinyb_dbus_DBusDevice_getPaired(JNIEnv *env, jobject obj) -{ - try { - BluetoothDevice *obj_device = getInstance<BluetoothDevice>(env, obj); - - return obj_device->get_paired() ? JNI_TRUE : JNI_FALSE; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return JNI_FALSE; -} - -void Java_tinyb_dbus_DBusDevice_enablePairedNotifications(JNIEnv *env, jobject obj, jobject callback) -{ - try { - BluetoothDevice *obj_device = - getInstance<BluetoothDevice>(env, obj); - std::shared_ptr<JNIGlobalRef> callback_ptr(new JNIGlobalRef(callback)); - obj_device->enable_paired_notifications([ callback_ptr ] (bool v) - { - jclass notification = search_class(*jni_env, **callback_ptr); - jmethodID method = search_method(*jni_env, notification, "run", "(Ljava/lang/Object;)V", false); - jni_env->DeleteLocalRef(notification); - - jclass boolean_cls = search_class(*jni_env, "java/lang/Boolean"); - jmethodID constructor = search_method(*jni_env, boolean_cls, "<init>", "(Z)V", false); - - jobject result = jni_env->NewObject(boolean_cls, constructor, v ? JNI_TRUE : JNI_FALSE); - jni_env->DeleteLocalRef(boolean_cls); - - jni_env->CallVoidMethod(**callback_ptr, method, result); - jni_env->DeleteLocalRef(result); - - }); - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - -void Java_tinyb_dbus_DBusDevice_disablePairedNotifications(JNIEnv *env, jobject obj) -{ - try { - BluetoothDevice *obj_device = - getInstance<BluetoothDevice>(env, obj); - obj_device->disable_paired_notifications(); - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - -jboolean Java_tinyb_dbus_DBusDevice_getTrusted(JNIEnv *env, jobject obj) -{ - try { - BluetoothDevice *obj_device = getInstance<BluetoothDevice>(env, obj); - - return obj_device->get_trusted() ? JNI_TRUE : JNI_FALSE; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return JNI_FALSE; -} - -void Java_tinyb_dbus_DBusDevice_setTrusted(JNIEnv *env, jobject obj, jboolean val) -{ - try { - BluetoothDevice *obj_device = getInstance<BluetoothDevice>(env, obj); - - bool val_to_write = from_jboolean_to_bool(val); - obj_device->set_trusted(val_to_write); - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - -void Java_tinyb_dbus_DBusDevice_enableTrustedNotifications(JNIEnv *env, jobject obj, jobject callback) -{ - try { - BluetoothDevice *obj_device = - getInstance<BluetoothDevice>(env, obj); - std::shared_ptr<JNIGlobalRef> callback_ptr(new JNIGlobalRef(callback)); - obj_device->enable_trusted_notifications([ callback_ptr ] (bool v) - { - jclass notification = search_class(*jni_env, **callback_ptr); - jmethodID method = search_method(*jni_env, notification, "run", "(Ljava/lang/Object;)V", false); - jni_env->DeleteLocalRef(notification); - - jclass boolean_cls = search_class(*jni_env, "java/lang/Boolean"); - jmethodID constructor = search_method(*jni_env, boolean_cls, "<init>", "(Z)V", false); - - jobject result = jni_env->NewObject(boolean_cls, constructor, v ? JNI_TRUE : JNI_FALSE); - jni_env->DeleteLocalRef(boolean_cls); - - jni_env->CallVoidMethod(**callback_ptr, method, result); - jni_env->DeleteLocalRef(result); - - }); - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - -void Java_tinyb_dbus_DBusDevice_disableTrustedNotifications(JNIEnv *env, jobject obj) -{ - try { - BluetoothDevice *obj_device = - getInstance<BluetoothDevice>(env, obj); - obj_device->disable_trusted_notifications(); - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - -jboolean Java_tinyb_dbus_DBusDevice_getBlocked(JNIEnv *env, jobject obj) -{ - try { - BluetoothDevice *obj_device = getInstance<BluetoothDevice>(env, obj); - - return obj_device->get_blocked() ? JNI_TRUE : JNI_FALSE; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return JNI_FALSE; -} - -void Java_tinyb_dbus_DBusDevice_setBlocked(JNIEnv *env, jobject obj, jboolean val) -{ - try { - BluetoothDevice *obj_device = getInstance<BluetoothDevice>(env, obj); - - bool val_to_write = from_jboolean_to_bool(val); - obj_device->set_blocked(val_to_write); - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - -void Java_tinyb_dbus_DBusDevice_enableBlockedNotifications(JNIEnv *env, jobject obj, jobject callback) -{ - try { - BluetoothDevice *obj_device = - getInstance<BluetoothDevice>(env, obj); - std::shared_ptr<JNIGlobalRef> callback_ptr(new JNIGlobalRef(callback)); - obj_device->enable_blocked_notifications([ callback_ptr ] (bool v) - { - jclass notification = search_class(*jni_env, **callback_ptr); - jmethodID method = search_method(*jni_env, notification, "run", "(Ljava/lang/Object;)V", false); - jni_env->DeleteLocalRef(notification); - - jclass boolean_cls = search_class(*jni_env, "java/lang/Boolean"); - jmethodID constructor = search_method(*jni_env, boolean_cls, "<init>", "(Z)V", false); - - jobject result = jni_env->NewObject(boolean_cls, constructor, v ? JNI_TRUE : JNI_FALSE); - jni_env->DeleteLocalRef(boolean_cls); - - jni_env->CallVoidMethod(**callback_ptr, method, result); - jni_env->DeleteLocalRef(result); - - }); - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - -void Java_tinyb_dbus_DBusDevice_disableBlockedNotifications(JNIEnv *env, jobject obj) -{ - try { - BluetoothDevice *obj_device = - getInstance<BluetoothDevice>(env, obj); - obj_device->disable_blocked_notifications(); - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - -jboolean Java_tinyb_dbus_DBusDevice_getLegacyPairing(JNIEnv *env, jobject obj) -{ - try { - BluetoothDevice *obj_device = getInstance<BluetoothDevice>(env, obj); - - return obj_device->get_legacy_pairing() ? JNI_TRUE : JNI_FALSE; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return JNI_FALSE; -} - -jshort Java_tinyb_dbus_DBusDevice_getRSSI(JNIEnv *env, jobject obj) -{ - try { - BluetoothDevice *obj_device = getInstance<BluetoothDevice>(env, obj); - - return (jshort)obj_device->get_rssi(); - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return 0; -} - -void Java_tinyb_dbus_DBusDevice_enableRSSINotifications(JNIEnv *env, jobject obj, jobject callback) -{ - try { - BluetoothDevice *obj_device = - getInstance<BluetoothDevice>(env, obj); - std::shared_ptr<JNIGlobalRef> callback_ptr(new JNIGlobalRef(callback)); - obj_device->enable_rssi_notifications([ callback_ptr ] (int16_t v) - { - jclass notification = search_class(*jni_env, **callback_ptr); - jmethodID method = search_method(*jni_env, notification, "run", "(Ljava/lang/Object;)V", false); - jni_env->DeleteLocalRef(notification); - - jclass short_cls = search_class(*jni_env, "java/lang/Short"); - jmethodID constructor = search_method(*jni_env, short_cls, "<init>", "(S)V", false); - - jobject result = jni_env->NewObject(short_cls, constructor, (jshort) v); - jni_env->DeleteLocalRef(short_cls); - - jni_env->CallVoidMethod(**callback_ptr, method, result); - jni_env->DeleteLocalRef(result); - - }); - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - -void Java_tinyb_dbus_DBusDevice_disableRSSINotifications(JNIEnv *env, jobject obj) -{ - try { - BluetoothDevice *obj_device = - getInstance<BluetoothDevice>(env, obj); - obj_device->disable_rssi_notifications(); - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - -jboolean Java_tinyb_dbus_DBusDevice_getConnected(JNIEnv *env, jobject obj) -{ - try { - BluetoothDevice *obj_device = getInstance<BluetoothDevice>(env, obj); - - return obj_device->get_connected() ? JNI_TRUE : JNI_FALSE; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return JNI_FALSE; -} - -void Java_tinyb_dbus_DBusDevice_enableConnectedNotifications(JNIEnv *env, jobject obj, jobject callback) -{ - try { - BluetoothDevice *obj_device = - getInstance<BluetoothDevice>(env, obj); - std::shared_ptr<JNIGlobalRef> callback_ptr(new JNIGlobalRef(callback)); - obj_device->enable_connected_notifications([ callback_ptr ] (bool v) - { - jclass notification = search_class(*jni_env, **callback_ptr); - jmethodID method = search_method(*jni_env, notification, "run", "(Ljava/lang/Object;)V", false); - jni_env->DeleteLocalRef(notification); - - jclass boolean_cls = search_class(*jni_env, "java/lang/Boolean"); - jmethodID constructor = search_method(*jni_env, boolean_cls, "<init>", "(Z)V", false); - - jobject result = jni_env->NewObject(boolean_cls, constructor, v ? JNI_TRUE : JNI_FALSE); - jni_env->DeleteLocalRef(boolean_cls); - - jni_env->CallVoidMethod(**callback_ptr, method, result); - jni_env->DeleteLocalRef(result); - - }); - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - -void Java_tinyb_dbus_DBusDevice_disableConnectedNotifications(JNIEnv *env, jobject obj) -{ - try { - BluetoothDevice *obj_device = - getInstance<BluetoothDevice>(env, obj); - obj_device->disable_connected_notifications(); - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - -jobjectArray Java_tinyb_dbus_DBusDevice_getUUIDs(JNIEnv *env, jobject obj) -{ - try { - BluetoothDevice *obj_device = getInstance<BluetoothDevice>(env, obj); - std::vector<std::string> uuids = obj_device->get_uuids(); - unsigned int uuids_size = uuids.size(); - - jclass string_class = search_class(env, "Ljava/lang/String;"); - jobjectArray result = env->NewObjectArray(uuids_size, string_class, 0); - - for (unsigned int i = 0; i < uuids_size; ++i) - { - std::string str_elem = uuids.at(i); - jobject elem = env->NewStringUTF((const char *)str_elem.c_str()); - env->SetObjectArrayElement(result, i, elem); - } - - return result; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -jstring Java_tinyb_dbus_DBusDevice_getModalias(JNIEnv *env, jobject obj) -{ - try { - BluetoothDevice *obj_device = getInstance<BluetoothDevice>(env, obj); - std::unique_ptr<std::string> modalias = obj_device->get_modalias(); - if (modalias == nullptr) - return nullptr; - - return env->NewStringUTF((const char *)modalias->c_str()); - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -jobject Java_tinyb_dbus_DBusDevice_getAdapter(JNIEnv *env, jobject obj) -{ - try { - BluetoothDevice *obj_device = getInstance<BluetoothDevice>(env, obj); - BluetoothAdapter *obj_adapter = obj_device->get_adapter().clone(); - - jclass b_adapter_class = search_class(env, *obj_adapter); - jmethodID b_adapter_ctor = search_method(env, b_adapter_class, "<init>", - "(J)V", false); - jobject result = env->NewObject(b_adapter_class, b_adapter_ctor, (jlong)obj_adapter); - if (!result) - { - throw std::bad_alloc(); - } - - return result; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -jobject Java_tinyb_dbus_DBusDevice_getManufacturerData(JNIEnv *env, jobject obj) -{ - try { - BluetoothDevice *obj_device = getInstance<BluetoothDevice>(env, obj); - auto mdata = obj_device->get_manufacturer_data(); - - jclass map_cls = search_class(env, "java/util/HashMap"); - jmethodID map_ctor = search_method(env, map_cls, "<init>", - "(I)V", false); - jmethodID map_put = search_method(env, map_cls, "put", - "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;", - false); - - jclass short_cls = search_class(env, "java/lang/Short"); - jmethodID short_ctor = search_method(env, short_cls, "<init>", - "(S)V", false); - - jobject result = env->NewObject(map_cls, map_ctor, mdata.size()); - - for (auto it: mdata) { - jbyteArray arr = env->NewByteArray(it.second.size()); - env->SetByteArrayRegion(arr, 0, it.second.size(), (const jbyte *)it.second.data()); - jobject key = env->NewObject(short_cls, short_ctor, it.first); - env->CallObjectMethod(result, map_put, key, arr); - - env->DeleteLocalRef(arr); - env->DeleteLocalRef(key); - } - - if (!result) - { - throw std::bad_alloc(); - } - - return result; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -void Java_tinyb_dbus_DBusDevice_enableManufacturerDataNotifications(JNIEnv *env, jobject obj, jobject callback) -{ - try { - BluetoothDevice *obj_device = - getInstance<BluetoothDevice>(env, obj); - std::shared_ptr<JNIGlobalRef> callback_ptr(new JNIGlobalRef(callback)); - obj_device->enable_manufacturer_data_notifications([ callback_ptr ] (std::map<uint16_t, std::vector<uint8_t>> v) - { - jclass notification = search_class(*jni_env, **callback_ptr); - jmethodID method = search_method(*jni_env, notification, "run", "(Ljava/lang/Object;)V", false); - jni_env->DeleteLocalRef(notification); - - jclass map_cls = search_class(*jni_env, "java/util/HashMap"); - jmethodID map_ctor = search_method(*jni_env, map_cls, "<init>", - "(I)V", false); - jmethodID map_put = search_method(*jni_env, map_cls, "put", - "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;", - false); - - jclass short_cls = search_class(*jni_env, "java/lang/Short"); - jmethodID short_ctor = search_method(*jni_env, short_cls, "<init>", - "(S)V", false); - - jobject result = jni_env->NewObject(map_cls, map_ctor, v.size()); - jni_env->DeleteLocalRef(map_cls); - for (auto it: v) { - jbyteArray arr = jni_env->NewByteArray(it.second.size()); - jni_env->SetByteArrayRegion(arr, 0, it.second.size(), (const jbyte *)it.second.data()); - jobject key = jni_env->NewObject(short_cls, short_ctor, it.first); - jni_env->CallObjectMethod(result, map_put, key, arr); - - jni_env->DeleteLocalRef(arr); - jni_env->DeleteLocalRef(key); - } - - jni_env->CallVoidMethod(**callback_ptr, method, result); - jni_env->DeleteLocalRef(result); - jni_env->DeleteLocalRef(short_cls); - - }); - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - -void Java_tinyb_dbus_DBusDevice_disableManufacturerDataNotifications(JNIEnv *env, jobject obj) -{ - try { - BluetoothDevice *obj_device = - getInstance<BluetoothDevice>(env, obj); - obj_device->disable_service_data_notifications(); - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - -jobject Java_tinyb_dbus_DBusDevice_getServiceData(JNIEnv *env, jobject obj) -{ - try { - BluetoothDevice *obj_device = getInstance<BluetoothDevice>(env, obj); - auto mdata = obj_device->get_service_data(); - - jclass map_cls = search_class(env, "java/util/HashMap"); - jmethodID map_ctor = search_method(env, map_cls, "<init>", - "(I)V", false); - jmethodID map_put = search_method(env, map_cls, "put", - "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;", - false); - - jobject result = env->NewObject(map_cls, map_ctor, mdata.size()); - - for (auto it: mdata) { - jbyteArray arr = env->NewByteArray(it.second.size()); - env->SetByteArrayRegion(arr, 0, it.second.size(), (const jbyte *)it.second.data()); - jobject key = env->NewStringUTF(it.first.c_str()); - env->CallObjectMethod(result, map_put, key, arr); - - env->DeleteLocalRef(arr); - env->DeleteLocalRef(key); - } - - if (!result) - { - throw std::bad_alloc(); - } - - return result; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -void Java_tinyb_dbus_DBusDevice_enableServiceDataNotifications(JNIEnv *env, jobject obj, jobject callback) -{ - try { - BluetoothDevice *obj_device = - getInstance<BluetoothDevice>(env, obj); - std::shared_ptr<JNIGlobalRef> callback_ptr(new JNIGlobalRef(callback)); - obj_device->enable_service_data_notifications([ callback_ptr ] (std::map<std::string, std::vector<uint8_t>> v) - { - jclass notification = search_class(*jni_env, **callback_ptr); - jmethodID method = search_method(*jni_env, notification, "run", "(Ljava/lang/Object;)V", false); - jni_env->DeleteLocalRef(notification); - - jclass map_cls = search_class(*jni_env, "java/util/HashMap"); - jmethodID map_ctor = search_method(*jni_env, map_cls, "<init>", - "(I)V", false); - jmethodID map_put = search_method(*jni_env, map_cls, "put", - "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;", - false); - - jobject result = jni_env->NewObject(map_cls, map_ctor, v.size()); - jni_env->DeleteLocalRef(map_cls); - - for (auto it: v) { - jbyteArray arr = jni_env->NewByteArray(it.second.size()); - jni_env->SetByteArrayRegion(arr, 0, it.second.size(), (const jbyte *)it.second.data()); - jobject key = jni_env->NewStringUTF(it.first.c_str()); - jni_env->CallObjectMethod(result, map_put, key, arr); - - jni_env->DeleteLocalRef(arr); - jni_env->DeleteLocalRef(key); - } - - jni_env->CallVoidMethod(**callback_ptr, method, result); - jni_env->DeleteLocalRef(result); - }); - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - -void Java_tinyb_dbus_DBusDevice_disableServiceDataNotifications(JNIEnv *env, jobject obj) -{ - try { - BluetoothDevice *obj_device = - getInstance<BluetoothDevice>(env, obj); - obj_device->disable_service_data_notifications(); - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - - - -jshort Java_tinyb_dbus_DBusDevice_getTxPower(JNIEnv *env, jobject obj) -{ - try { - BluetoothDevice *obj_device = getInstance<BluetoothDevice>(env, obj); - - return (jshort)obj_device->get_tx_power(); - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return 0; -} - -jboolean Java_tinyb_dbus_DBusDevice_getServicesResolved(JNIEnv *env, jobject obj) -{ - try { - BluetoothDevice *obj_device = getInstance<BluetoothDevice>(env, obj); - - return obj_device->get_services_resolved() ? JNI_TRUE : JNI_FALSE; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return JNI_FALSE; -} - -void Java_tinyb_dbus_DBusDevice_enableServicesResolvedNotifications(JNIEnv *env, jobject obj, jobject callback) -{ - try { - BluetoothDevice *obj_device = - getInstance<BluetoothDevice>(env, obj); - std::shared_ptr<JNIGlobalRef> callback_ptr(new JNIGlobalRef(callback)); - obj_device->enable_services_resolved_notifications([ callback_ptr ] (bool v) - { - jclass notification = search_class(*jni_env, **callback_ptr); - jmethodID method = search_method(*jni_env, notification, "run", "(Ljava/lang/Object;)V", false); - jni_env->DeleteLocalRef(notification); - - jclass boolean_cls = search_class(*jni_env, "java/lang/Boolean"); - jmethodID constructor = search_method(*jni_env, boolean_cls, "<init>", "(Z)V", false); - - jobject result = jni_env->NewObject(boolean_cls, constructor, v ? JNI_TRUE : JNI_FALSE); - jni_env->DeleteLocalRef(boolean_cls); - - jni_env->CallVoidMethod(**callback_ptr, method, result); - jni_env->DeleteLocalRef(result); - - }); - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - -void Java_tinyb_dbus_DBusDevice_disableServicesResolvedNotifications(JNIEnv *env, jobject obj) -{ - try { - BluetoothDevice *obj_device = - getInstance<BluetoothDevice>(env, obj); - obj_device->disable_services_resolved_notifications(); - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - - - -void Java_tinyb_dbus_DBusDevice_delete(JNIEnv *env, jobject obj) -{ - try { - BluetoothDevice *b_device = getInstance<BluetoothDevice>(env, obj); - delete b_device; - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - diff --git a/java/jni/tinyb/DBusEvent.cxx b/java/jni/tinyb/DBusEvent.cxx deleted file mode 100644 index 14b6431c..00000000 --- a/java/jni/tinyb/DBusEvent.cxx +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Author: Andrei Vasiliu <[email protected]> - * Copyright (c) 2016 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#include "tinyb_dbus_DBusEvent.h" - -jobject Java_tinyb_dbus_DBusEvent_getType(JNIEnv *env, jobject obj) -{ - (void)env; - (void)obj; - - return NULL; -} - -jstring Java_tinyb_dbus_DBusEvent_getName(JNIEnv *env, jobject obj) -{ - (void)env; - (void)obj; - - return NULL; -} - -jstring Java_tinyb_dbus_DBusEvent_getIdentifier(JNIEnv *env, jobject obj) -{ - (void)env; - (void)obj; - - return NULL; -} - -jboolean Java_tinyb_dbus_DBusEvent_executeCallback(JNIEnv *env, jobject obj) -{ - (void)env; - (void)obj; - - return JNI_FALSE; -} - -jboolean Java_tinyb_dbus_DBusEvent_hasCallback(JNIEnv *env, jobject obj) -{ - (void)env; - (void)obj; - - return JNI_FALSE; -} - -void Java_tinyb_dbus_DBusEvent_init(JNIEnv *env, jobject obj, jobject type, jstring name, - jstring identifier, jobject parent, jobject callback, - jobject arg_data) -{ - (void)env; - (void)obj; - (void)type; - (void)name; - (void)identifier; - (void)parent; - (void)callback; - (void)arg_data; -} - -void Java_tinyb_dbus_DBusEvent_delete(JNIEnv *env, jobject obj) -{ - (void)env; - (void)obj; -} - diff --git a/java/jni/tinyb/DBusGattCharacteristic.cxx b/java/jni/tinyb/DBusGattCharacteristic.cxx deleted file mode 100644 index 0becc560..00000000 --- a/java/jni/tinyb/DBusGattCharacteristic.cxx +++ /dev/null @@ -1,255 +0,0 @@ -/* - * Author: Andrei Vasiliu <[email protected]> - * Copyright (c) 2016 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#include "tinyb/BluetoothGattCharacteristic.hpp" -#include "tinyb/BluetoothGattDescriptor.hpp" -#include "tinyb/BluetoothGattService.hpp" -#include "tinyb/BluetoothObject.hpp" - -#include "tinyb_dbus_DBusGattCharacteristic.h" - -#include "helper_tinyb.hpp" - -using namespace tinyb; -using namespace jau; - -jobject Java_tinyb_dbus_DBusGattCharacteristic_getBluetoothType(JNIEnv *env, jobject obj) -{ - try { - (void)obj; - - return get_bluetooth_type(env, "GATT_CHARACTERISTIC"); - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -jobject Java_tinyb_dbus_DBusGattCharacteristic_clone(JNIEnv *env, jobject obj) -{ - try { - return generic_clone<BluetoothGattCharacteristic>(env, obj); - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -jbyteArray Java_tinyb_dbus_DBusGattCharacteristic_readValue(JNIEnv *env, jobject obj) -{ - try { - BluetoothGattCharacteristic *obj_gatt_char = - getInstance<BluetoothGattCharacteristic>(env, obj); - std::vector<unsigned char> array = obj_gatt_char->read_value(); - unsigned int array_size = array.size(); - - jbyteArray result = env->NewByteArray((jsize)array_size); - env->SetByteArrayRegion(result, 0, (jsize)array_size, (const jbyte *)&array[0]); - - return result; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -jboolean Java_tinyb_dbus_DBusGattCharacteristic_writeValue(JNIEnv *env, jobject obj, jbyteArray argValue) -{ - try { - if (!argValue) - { - throw std::invalid_argument("byte array is null"); - return JNI_FALSE; - } - - BluetoothGattCharacteristic *obj_gatt_char = - getInstance<BluetoothGattCharacteristic>(env, obj); - - jboolean is_copy = false; - jbyte *native_array = env->GetByteArrayElements(argValue, &is_copy); - jsize native_array_length = env->GetArrayLength(argValue); - - std::vector<unsigned char> array(native_array, native_array + native_array_length); - - return obj_gatt_char->write_value(array) ? JNI_TRUE : JNI_FALSE; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return JNI_FALSE; -} - -void Java_tinyb_dbus_DBusGattCharacteristic_enableValueNotifications(JNIEnv *env, jobject obj, jobject callback) -{ - try { - BluetoothGattCharacteristic *obj_gatt_char = - getInstance<BluetoothGattCharacteristic>(env, obj); - std::shared_ptr<JNIGlobalRef> callback_ptr(new JNIGlobalRef(callback)); - obj_gatt_char->enable_value_notifications([ callback_ptr ] (std::vector<unsigned char> &v) - { - jclass notification = search_class(*jni_env, **callback_ptr); - jmethodID method = search_method(*jni_env, notification, "run", "(Ljava/lang/Object;)V", false); - jni_env->DeleteLocalRef(notification); - unsigned int size = v.size(); - - jbyteArray result = jni_env->NewByteArray((jsize)size); - jni_env->SetByteArrayRegion(result, 0, (jsize)size, (const jbyte *)&v[0]); - - jni_env->CallVoidMethod(**callback_ptr, method, result); - jni_env->DeleteLocalRef(result); - - }); - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - -void Java_tinyb_dbus_DBusGattCharacteristic_disableValueNotifications(JNIEnv *env, jobject obj) -{ - try { - BluetoothGattCharacteristic *obj_gatt_char = - getInstance<BluetoothGattCharacteristic>(env, obj); - obj_gatt_char->disable_value_notifications(); - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - -jstring Java_tinyb_dbus_DBusGattCharacteristic_getUUID(JNIEnv *env, jobject obj) -{ - try { - BluetoothGattCharacteristic *obj_gatt_char = - getInstance<BluetoothGattCharacteristic>(env, obj); - std::string uuid = obj_gatt_char->get_uuid(); - - return env->NewStringUTF((const char *)uuid.c_str()); - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -jobject Java_tinyb_dbus_DBusGattCharacteristic_getService(JNIEnv *env, jobject obj) -{ - try { - BluetoothGattCharacteristic *obj_gatt_char = - getInstance<BluetoothGattCharacteristic>(env, obj); - BluetoothGattService *obj_gatt_serv = obj_gatt_char->get_service().clone(); - - jclass b_gatt_serv_class = search_class(env, *obj_gatt_serv); - jmethodID b_gatt_serv_ctor = search_method(env, b_gatt_serv_class, "<init>", - "(J)V", false); - jobject result = env->NewObject(b_gatt_serv_class, b_gatt_serv_ctor, (jlong)obj_gatt_serv); - if (result == NULL) - { - throw std::runtime_error("cannot create instance of class\n"); - } - - return result; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -jbyteArray Java_tinyb_dbus_DBusGattCharacteristic_getValue(JNIEnv *env, jobject obj) -{ - try { - BluetoothGattCharacteristic *obj_gatt_char = - getInstance<BluetoothGattCharacteristic>(env, obj); - std::vector<unsigned char> array = obj_gatt_char->get_value(); - unsigned int array_size = array.size(); - - jbyteArray result = env->NewByteArray((jsize)array_size); - env->SetByteArrayRegion(result, 0, (jsize)array_size, (const jbyte *)&array[0]); - - return result; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -jboolean Java_tinyb_dbus_DBusGattCharacteristic_getNotifying(JNIEnv *env, jobject obj) -{ - try { - BluetoothGattCharacteristic *obj_gatt_char = - getInstance<BluetoothGattCharacteristic>(env, obj); - return obj_gatt_char->get_notifying() ? JNI_TRUE : JNI_FALSE; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return JNI_FALSE; -} - -jobjectArray Java_tinyb_dbus_DBusGattCharacteristic_getFlags(JNIEnv *env, jobject obj) -{ - try { - BluetoothGattCharacteristic *obj_gatt_char = - getInstance<BluetoothGattCharacteristic>(env, obj); - std::vector<std::string> flags = obj_gatt_char->get_flags(); - unsigned int flags_size = flags.size(); - - jclass string_class = search_class(env, "Ljava/lang/String;"); - jobjectArray result = env->NewObjectArray(flags_size, string_class, 0); - - for (unsigned int i = 0; i < flags_size; ++i) - { - std::string str_elem = flags.at(i); - jobject elem = env->NewStringUTF((const char *)str_elem.c_str()); - env->SetObjectArrayElement(result, i, elem); - } - - return result; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -jobject Java_tinyb_dbus_DBusGattCharacteristic_getDescriptors(JNIEnv *env, jobject obj) -{ - try { - BluetoothGattCharacteristic *obj_gatt_char = - getInstance<BluetoothGattCharacteristic>(env, obj); - std::vector<std::unique_ptr<BluetoothGattDescriptor>> array = obj_gatt_char->get_descriptors(); - - jobject result = convert_vector_uniqueptr_to_jarraylist<std::vector<std::unique_ptr<BluetoothGattDescriptor>>, BluetoothGattDescriptor>( - env, array, "(J)V"); - return result; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -void Java_tinyb_dbus_DBusGattCharacteristic_delete(JNIEnv *env, jobject obj) -{ - try { - BluetoothGattCharacteristic *obj_gatt_char = - getInstance<BluetoothGattCharacteristic>(env, obj); - delete obj_gatt_char; - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} diff --git a/java/jni/tinyb/DBusGattDescriptor.cxx b/java/jni/tinyb/DBusGattDescriptor.cxx deleted file mode 100644 index a1cc7606..00000000 --- a/java/jni/tinyb/DBusGattDescriptor.cxx +++ /dev/null @@ -1,197 +0,0 @@ -/* - * Author: Andrei Vasiliu <[email protected]> - * Copyright (c) 2016 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#include "tinyb/BluetoothGattCharacteristic.hpp" -#include "tinyb/BluetoothGattDescriptor.hpp" -#include "tinyb/BluetoothObject.hpp" - -#include "tinyb_dbus_DBusGattDescriptor.h" - -#include "helper_tinyb.hpp" - -using namespace tinyb; -using namespace jau; - -jobject Java_tinyb_dbus_DBusGattDescriptor_getBluetoothType(JNIEnv *env, jobject obj) -{ - try { - (void)obj; - - return get_bluetooth_type(env, "GATT_DESCRIPTOR"); - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -jobject Java_tinyb_dbus_DBusGattDescriptor_clone(JNIEnv *env, jobject obj) -{ - try { - return generic_clone<BluetoothGattDescriptor>(env, obj); - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -jbyteArray Java_tinyb_dbus_DBusGattDescriptor_readValue(JNIEnv *env, jobject obj) -{ - try { - BluetoothGattDescriptor *obj_gatt_desc = getInstance<BluetoothGattDescriptor>(env, obj); - std::vector<unsigned char> array = obj_gatt_desc->read_value(); - unsigned int array_size = array.size(); - - jbyteArray result = env->NewByteArray((jsize)array_size); - env->SetByteArrayRegion(result, 0, (jsize)array_size, (const jbyte *)&array[0]); - - return result; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -jboolean Java_tinyb_dbus_DBusGattDescriptor_writeValue(JNIEnv *env, jobject obj, jbyteArray argValue) -{ - try { - if (!argValue) - { - throw std::invalid_argument("byte array is null"); - } - - BluetoothGattDescriptor *obj_gatt_desc = getInstance<BluetoothGattDescriptor>(env, obj); - - jboolean is_copy = false; - jbyte *native_array = env->GetByteArrayElements(argValue, &is_copy); - jsize native_array_length = env->GetArrayLength(argValue); - - std::vector<unsigned char> array(native_array, native_array + native_array_length); - - return obj_gatt_desc->write_value(array) ? JNI_TRUE : JNI_FALSE; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return JNI_FALSE; -} - -jstring Java_tinyb_dbus_DBusGattDescriptor_getUUID(JNIEnv *env, jobject obj) -{ - try { - BluetoothGattDescriptor *obj_gatt_desc = getInstance<BluetoothGattDescriptor>(env, obj); - std::string uuid = obj_gatt_desc->get_uuid(); - - return env->NewStringUTF((const char *)uuid.c_str()); - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -jobject Java_tinyb_dbus_DBusGattDescriptor_getCharacteristic(JNIEnv *env, jobject obj) -{ - try { - BluetoothGattDescriptor *obj_gatt_desc = getInstance<BluetoothGattDescriptor>(env, obj); - BluetoothGattCharacteristic *obj_gatt_char = obj_gatt_desc->get_characteristic().clone(); - - jclass b_gatt_char_class = search_class(env, *obj_gatt_char); - jmethodID b_gatt_char_ctor = search_method(env, b_gatt_char_class, "<init>", - "(J)V", false); - jobject result = env->NewObject(b_gatt_char_class, b_gatt_char_ctor, (jlong)obj_gatt_char); - if (result == NULL) - { - throw std::runtime_error("cannot create instance of class\n"); - } - - return result; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -jbyteArray Java_tinyb_dbus_DBusGattDescriptor_getValue(JNIEnv *env, jobject obj) -{ - try { - BluetoothGattDescriptor *obj_gatt_desc = getInstance<BluetoothGattDescriptor>(env, obj); - std::vector<unsigned char> array = obj_gatt_desc->get_value(); - unsigned int array_size = array.size(); - - jbyteArray result = env->NewByteArray((jsize)array_size); - env->SetByteArrayRegion(result, 0, (jsize)array_size, (const jbyte *)&array[0]); - - return result; - - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -void Java_tinyb_dbus_DBusGattDescriptor_enableValueNotifications(JNIEnv *env, jobject obj, jobject callback) -{ - try { - BluetoothGattDescriptor *obj_gatt_desc = - getInstance<BluetoothGattDescriptor>(env, obj); - std::shared_ptr<JNIGlobalRef> callback_ptr(new JNIGlobalRef(callback)); - obj_gatt_desc->enable_value_notifications([ callback_ptr ] (std::vector<unsigned char> &v) - { - jclass notification = search_class(*jni_env, **callback_ptr); - jmethodID method = search_method(*jni_env, notification, "run", "(Ljava/lang/Object;)V", false); - jni_env->DeleteLocalRef(notification); - unsigned int size = v.size(); - - jbyteArray result = jni_env->NewByteArray((jsize)size); - jni_env->SetByteArrayRegion(result, 0, (jsize)size, (const jbyte *)&v[0]); - - jni_env->CallVoidMethod(**callback_ptr, method, result); - jni_env->DeleteLocalRef(result); - - }); - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - -void Java_tinyb_dbus_DBusGattDescriptor_disableValueNotifications(JNIEnv *env, jobject obj) -{ - try { - BluetoothGattDescriptor *obj_gatt_desc = - getInstance<BluetoothGattDescriptor>(env, obj); - obj_gatt_desc->disable_value_notifications(); - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - - -void Java_tinyb_dbus_DBusGattDescriptor_delete(JNIEnv *env, jobject obj) -{ - try { - BluetoothGattDescriptor *obj_gatt_desc = getInstance<BluetoothGattDescriptor>(env, obj); - delete obj_gatt_desc; - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - diff --git a/java/jni/tinyb/DBusGattService.cxx b/java/jni/tinyb/DBusGattService.cxx deleted file mode 100644 index f621df2d..00000000 --- a/java/jni/tinyb/DBusGattService.cxx +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Author: Andrei Vasiliu <[email protected]> - * Copyright (c) 2016 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#include "tinyb/BluetoothDevice.hpp" -#include "tinyb/BluetoothGattService.hpp" -#include "tinyb/BluetoothGattCharacteristic.hpp" -#include "tinyb/BluetoothObject.hpp" - -#include "tinyb_dbus_DBusGattService.h" - -#include "helper_tinyb.hpp" - -using namespace tinyb; -using namespace jau; - -jobject Java_tinyb_dbus_DBusGattService_getBluetoothType(JNIEnv *env, jobject obj) -{ - try { - (void)obj; - - return get_bluetooth_type(env, "GATT_SERVICE"); - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -jobject Java_tinyb_dbus_DBusGattService_clone(JNIEnv *env, jobject obj) -{ - try { - return generic_clone<BluetoothGattService>(env, obj); - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -jstring Java_tinyb_dbus_DBusGattService_getUUID(JNIEnv *env, jobject obj) -{ - try { - BluetoothGattService *obj_gatt_serv = getInstance<BluetoothGattService>(env, obj); - std::string uuid = obj_gatt_serv->get_uuid(); - - return env->NewStringUTF((const char *)uuid.c_str()); - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -jobject Java_tinyb_dbus_DBusGattService_getDevice(JNIEnv *env, jobject obj) -{ - try { - BluetoothGattService *obj_gatt_serv = getInstance<BluetoothGattService>(env, obj); - BluetoothDevice *obj_device = obj_gatt_serv->get_device().clone(); - - jclass b_device_class = search_class(env, *obj_device); - jmethodID b_device_ctor = search_method(env, b_device_class, "<init>", - "(J)V", false); - jobject result = env->NewObject(b_device_class, b_device_ctor, (jlong)obj_device); - if (result == NULL) - { - throw std::runtime_error("cannot create instance of class\n"); - } - - return result; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -jboolean Java_tinyb_dbus_DBusGattService_getPrimary(JNIEnv *env, jobject obj) -{ - try { - BluetoothGattService *obj_gatt_serv = getInstance<BluetoothGattService>(env, obj); - - return obj_gatt_serv->get_primary() ? JNI_TRUE : JNI_FALSE; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return JNI_FALSE; -} - -jobject Java_tinyb_dbus_DBusGattService_getChars(JNIEnv *env, jobject obj) -{ - try { - BluetoothGattService *obj_gatt_serv = getInstance<BluetoothGattService>(env, obj); - std::vector<std::unique_ptr<BluetoothGattCharacteristic>> array = - obj_gatt_serv->get_characteristics(); - jobject result = convert_vector_uniqueptr_to_jarraylist<std::vector<std::unique_ptr<BluetoothGattCharacteristic>>, BluetoothGattCharacteristic>( - env, array, "(J)V"); - return result; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -void Java_tinyb_dbus_DBusGattService_delete(JNIEnv *env, jobject obj) -{ - try { - BluetoothGattService *obj_gatt_serv = getInstance<BluetoothGattService>(env, obj); - delete obj_gatt_serv; - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - diff --git a/java/jni/tinyb/DBusManager.cxx b/java/jni/tinyb/DBusManager.cxx deleted file mode 100644 index e3abf7ba..00000000 --- a/java/jni/tinyb/DBusManager.cxx +++ /dev/null @@ -1,352 +0,0 @@ -/* - * Author: Andrei Vasiliu <[email protected]> - * Copyright (c) 2016 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#include "tinyb/BluetoothAdapter.hpp" -#include "tinyb/BluetoothDevice.hpp" -#include "tinyb/BluetoothGattService.hpp" -#include "tinyb/BluetoothManager.hpp" - -#include "tinyb_dbus_DBusManager.h" - -#include "helper_tinyb.hpp" - -using namespace tinyb; -using namespace jau; - -jobject Java_tinyb_dbus_DBusManager_getBluetoothType(JNIEnv *env, jobject obj) -{ - try { - (void)obj; - - return get_bluetooth_type(env, "NONE"); - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -static void getObject_setter(JNIEnv *env, - jstring name, std::string **name_to_write, - jstring identifier, std::string **identifier_to_write, - jobject parent, BluetoothObject **b_parent) -{ - try { - if (!parent) - { - *b_parent = nullptr; - } - else - { - *b_parent = getInstance<BluetoothObject>(env, parent); - } - - if (!name) - { - *name_to_write = nullptr; - } - else - { - *name_to_write = new std::string(from_jstring_to_string(env, name)); - } - - if (!identifier) - { - *identifier_to_write = nullptr; - } - else - { - *identifier_to_write = new std::string(from_jstring_to_string(env, identifier)); - } - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - -static void getObject_cleaner(std::string *name_to_write, std::string *identifier_to_write) -{ - if (name_to_write != nullptr) - delete name_to_write; - - if (identifier_to_write != nullptr) - delete identifier_to_write; -} - -jobject Java_tinyb_dbus_DBusManager_find(JNIEnv *env, jobject obj, jint type, - jstring name, jstring identifier, jobject parent, - jlong milliseconds) -{ - try { - BluetoothManager *manager = getInstance<BluetoothManager>(env, obj); - BluetoothObject *b_parent; - BluetoothType b_type; - std::string *name_to_write; - std::string *identifier_to_write; - - getObject_setter(env, - name, &name_to_write, - identifier, &identifier_to_write, - parent, &b_parent); - - b_type = from_int_to_btype((int)type); - std::unique_ptr<BluetoothObject> b_object = manager->find(b_type, name_to_write, - identifier_to_write, - b_parent, - std::chrono::milliseconds(milliseconds)); - getObject_cleaner(name_to_write, identifier_to_write); - - BluetoothObject *b_object_naked = b_object.release(); - if (!b_object_naked) - { - return nullptr; - } - jclass clazz = search_class(env, *b_object_naked); - jmethodID clazz_ctor = search_method(env, clazz, "<init>", "(J)V", false); - - jobject result = env->NewObject(clazz, clazz_ctor, (jlong)b_object_naked); - - return result; - - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - - -jobject Java_tinyb_dbus_DBusManager_getObject(JNIEnv *env, jobject obj, jint type, - jstring name, jstring identifier, jobject parent) -{ - try { - BluetoothManager *manager = getInstance<BluetoothManager>(env, obj); - BluetoothObject *b_parent; - BluetoothType b_type; - std::string *name_to_write; - std::string *identifier_to_write; - - getObject_setter(env, - name, &name_to_write, - identifier, &identifier_to_write, - parent, &b_parent); - - b_type = from_int_to_btype((int)type); - std::unique_ptr<BluetoothObject> b_object = manager->get_object(b_type, name_to_write, - identifier_to_write, - b_parent); - getObject_cleaner(name_to_write, identifier_to_write); - - BluetoothObject *b_object_naked = b_object.release(); - if (!b_object_naked) - { - return nullptr; - } - jclass clazz = search_class(env, *b_object_naked); - jmethodID clazz_ctor = search_method(env, clazz, "<init>", "(J)V", false); - - jobject result = env->NewObject(clazz, clazz_ctor, (jlong)b_object_naked); - return result; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -jobject Java_tinyb_dbus_DBusManager_getObjects(JNIEnv *env, jobject obj, jint type, - jstring name, jstring identifier, jobject parent) -{ - try { - BluetoothManager *manager = getInstance<BluetoothManager>(env, obj); - BluetoothObject *b_parent; - BluetoothType b_type; - std::string *name_to_write; - std::string *identifier_to_write; - - getObject_setter(env, - name, &name_to_write, - identifier, &identifier_to_write, - parent, &b_parent); - - b_type = from_int_to_btype((int)type); - std::vector<std::unique_ptr<BluetoothObject>> array = manager->get_objects(b_type, - name_to_write, - identifier_to_write, - b_parent); - getObject_cleaner(name_to_write, identifier_to_write); - jobject result = convert_vector_uniqueptr_to_jarraylist<std::vector<std::unique_ptr<BluetoothObject>>, BluetoothObject>( - env, array, "(J)V"); - return result; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -jobject Java_tinyb_dbus_DBusManager_getAdapters(JNIEnv *env, jobject obj) -{ - try { - BluetoothManager *manager = getInstance<BluetoothManager>(env, obj); - - std::vector<std::unique_ptr<BluetoothAdapter>> array = manager->get_adapters(); - jobject result = convert_vector_uniqueptr_to_jarraylist<std::vector<std::unique_ptr<BluetoothAdapter>>, BluetoothAdapter>( - env, array, "(J)V"); - return result; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -jobject Java_tinyb_dbus_DBusManager_getDevices(JNIEnv *env, jobject obj) -{ - try { - BluetoothManager *manager = getInstance<BluetoothManager>(env, obj); - - std::vector<std::unique_ptr<BluetoothDevice>> array = manager->get_devices(); - jobject result = convert_vector_uniqueptr_to_jarraylist<std::vector<std::unique_ptr<BluetoothDevice>>, BluetoothDevice>( - env, array, "(J)V"); - return result; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -jobject Java_tinyb_dbus_DBusManager_getServices(JNIEnv *env, jobject obj) -{ - try { - BluetoothManager *manager = getInstance<BluetoothManager>(env, obj); - - std::vector<std::unique_ptr<BluetoothGattService>> array = manager->get_services(); - jobject result = convert_vector_uniqueptr_to_jarraylist<std::vector<std::unique_ptr<BluetoothGattService>>, BluetoothGattService>( - env, array, "(J)V"); - return result; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} - -jboolean Java_tinyb_dbus_DBusManager_setDefaultAdapter(JNIEnv *env, jobject obj, jobject adapter) -{ - try { - if (adapter == nullptr) - throw std::invalid_argument("adapter argument is null\n"); - - BluetoothManager *manager = getInstance<BluetoothManager>(env, obj); - BluetoothAdapter *b_adapter = getInstance<BluetoothAdapter>(env, adapter); - - return manager->set_default_adapter(*b_adapter); - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return JNI_FALSE; -} - -jobject Java_tinyb_dbus_DBusManager_getDefaultAdapter(JNIEnv *env, jobject obj) -{ - try { - BluetoothManager *manager = getInstance<BluetoothManager>(env, obj); - - std::unique_ptr<tinyb::BluetoothAdapter> b_adapter = manager->get_default_adapter(); - BluetoothAdapter *b_adapter_naked = b_adapter.release(); - if (!b_adapter_naked) - { - return nullptr; - } - jclass clazz = search_class(env, *b_adapter_naked); - jmethodID clazz_ctor = search_method(env, clazz, "<init>", "(J)V", false); - - jobject result = env->NewObject(clazz, clazz_ctor, (jlong)b_adapter_naked); - return result; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return NULL; -} - -jboolean Java_tinyb_dbus_DBusManager_startDiscovery(JNIEnv *env, jobject obj) -{ - try { - BluetoothManager *manager = getInstance<BluetoothManager>(env, obj); - return manager->start_discovery() ? JNI_TRUE : JNI_FALSE; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return JNI_FALSE; -} - -jboolean Java_tinyb_dbus_DBusManager_stopDiscoveryImpl(JNIEnv *env, jobject obj) -{ - try { - BluetoothManager *manager = getInstance<BluetoothManager>(env, obj); - return manager->start_discovery() ? JNI_TRUE : JNI_FALSE; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return JNI_FALSE; -} - -jboolean Java_tinyb_dbus_DBusManager_getDiscovering(JNIEnv *env, jobject obj) -{ - try { - BluetoothManager *manager = getInstance<BluetoothManager>(env, obj); - return manager->get_discovering() ? JNI_TRUE : JNI_FALSE; - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return JNI_FALSE; -} - -void Java_tinyb_dbus_DBusManager_init(JNIEnv *env, jobject obj) -{ - try { - BluetoothManager *manager = BluetoothManager::get_bluetooth_manager(); - setInstance<BluetoothManager>(env, obj, manager); - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - -void Java_tinyb_dbus_DBusManager_delete(JNIEnv *env, jobject obj) -{ - try { - BluetoothManager *manager = getInstance<BluetoothManager>(env, obj); - (void) manager; - // delete manager; // Should not be called! - } catch(...) { - rethrow_and_raise_java_exception(env); - } -} - -jstring Java_tinyb_dbus_DBusManager_getNativeAPIVersion(JNIEnv *env, jclass clazz) -{ - try { - (void) clazz; - - BluetoothManager *manager = BluetoothManager::get_bluetooth_manager(); - return env->NewStringUTF(manager->get_api_version().c_str()); - } catch(...) { - rethrow_and_raise_java_exception(env); - } - return nullptr; -} diff --git a/java/jni/tinyb/DBusObject.cxx b/java/jni/tinyb/DBusObject.cxx deleted file mode 100644 index 1ab749f6..00000000 --- a/java/jni/tinyb/DBusObject.cxx +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Author: Andrei Vasiliu <[email protected]> - * Copyright (c) 2016 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#include "tinyb/BluetoothObject.hpp" - -#include "tinyb_dbus_DBusObject.h" - -#include "helper_tinyb.hpp" - -using namespace tinyb; -using namespace jau; - -jobject Java_tinyb_dbus_DBusObject_getBluetoothType(JNIEnv *env, jobject obj) -{ - (void)obj; - - return get_bluetooth_type(env, "NONE"); -} - -jobject Java_tinyb_dbus_DBusObject_clone(JNIEnv *env, jobject obj) -{ - return generic_clone<BluetoothObject>(env, obj); -} - -void Java_tinyb_dbus_DBusObject_delete(JNIEnv *env, jobject obj) -{ - BluetoothObject *obj_b = getInstance<BluetoothObject>(env, obj); - - delete obj_b; -} - -jboolean Java_tinyb_dbus_DBusObject_operatorEqual(JNIEnv *env, jobject obj, jobject other) -{ - if (!other) - { - return JNI_FALSE; - } - BluetoothObject *obj_b = getInstance<BluetoothObject>(env, obj); - BluetoothObject *obj_other = getInstance<BluetoothObject>(env, other); - - return (*obj_b) == (*obj_other); -} - -jstring Java_tinyb_dbus_DBusObject_getObjectPath(JNIEnv *env, jobject obj) -{ - BluetoothObject *obj_b = getInstance<BluetoothObject>(env, obj); - - return env->NewStringUTF(obj_b->get_object_path().c_str()); -} - diff --git a/java/jni/tinyb/helper_tinyb.cxx b/java/jni/tinyb/helper_tinyb.cxx deleted file mode 100644 index 8777f024..00000000 --- a/java/jni/tinyb/helper_tinyb.cxx +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Author: Andrei Vasiliu <[email protected]> - * Copyright (c) 2016 Intel Corporation. - * - * Author: Sven Gothel <[email protected]> - * Copyright (c) 2020 Gothel Software e.K. - * Copyright (c) 2020 ZAFENA AB - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#include <jni.h> -#include <memory> -#include <stdexcept> -#include <vector> - -#include "helper_tinyb.hpp" - -using namespace tinyb; - -jclass tinyb::search_class(JNIEnv *env, BluetoothObject &object) -{ - return jau::search_class(env, object.get_java_class().c_str()); -} - -BluetoothType tinyb::from_int_to_btype(int type) -{ - BluetoothType result = BluetoothType::NONE; - - switch (type) - { - case 0: - result = BluetoothType::NONE; - break; - - case 1: - result = BluetoothType::ADAPTER; - break; - - case 2: - result = BluetoothType::DEVICE; - break; - - case 3: - result = BluetoothType::GATT_SERVICE; - break; - - case 4: - result = BluetoothType::GATT_CHARACTERISTIC; - break; - - case 5: - result = BluetoothType::GATT_CHARACTERISTIC; - break; - - default: - result = BluetoothType::NONE; - break; - } - - return result; -} - -TransportType tinyb::from_int_to_transport_type(int type) -{ - TransportType result = TransportType::AUTO; - - switch (type) - { - case 0: - result = TransportType::AUTO; - break; - - case 1: - result = TransportType::BREDR; - break; - - case 2: - result = TransportType::LE; - break; - - default: - result = TransportType::AUTO; - break; - } - - return result; -} - -void tinyb::raise_java_bluetooth_exception(JNIEnv *env, BluetoothException &e) -{ - env->ThrowNew(env->FindClass("org/direct_bt/BTException"), e.what()); -} - diff --git a/java/jni/tinyb/helper_tinyb.hpp b/java/jni/tinyb/helper_tinyb.hpp deleted file mode 100644 index cdfad29c..00000000 --- a/java/jni/tinyb/helper_tinyb.hpp +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Author: Andrei Vasiliu <[email protected]> - * Copyright (c) 2016 Intel Corporation. - * - * Author: Sven Gothel <[email protected]> - * Copyright (c) 2020 Gothel Software e.K. - * Copyright (c) 2020 ZAFENA AB - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#pragma once - -#include "helper_base.hpp" - -#include "tinyb/BluetoothObject.hpp" -#include "tinyb/BluetoothException.hpp" - -namespace tinyb { - - jclass search_class(JNIEnv *env, BluetoothObject &object); - BluetoothType from_int_to_btype(int type); - TransportType from_int_to_transport_type(int type); - - void raise_java_bluetooth_exception(JNIEnv *env, BluetoothException &e); - -} // namespace tinyb diff --git a/java/manifest.txt.in b/java/manifest.txt.in index 96b2abe3..c1ae4024 100644 --- a/java/manifest.txt.in +++ b/java/manifest.txt.in @@ -12,7 +12,7 @@ Package-Version: @VERSION_SHORT@ Specification-Title: Direct-BT Specification-Vendor: Gothel Software Specification-Version: @VERSION_API@ -Implementation-Title: Direct-BT (optionally with TinyB) +Implementation-Title: Direct-BT Implementation-Vendor: Gothel Software Implementation-Version: @VERSION@ Implementation-Commit: @VERSION_SHA1@ @@ -26,9 +26,6 @@ Main-Class: org.direct_bt.BTFactory Name: org/direct_bt/ Sealed: true -Name: tinyb/dbus/ -Sealed: true - Name: jau/direct_bt/ Sealed: true diff --git a/java/org/direct_bt/BDAddressType.java b/java/org/direct_bt/BDAddressType.java index 320a5686..674e41e6 100644 --- a/java/org/direct_bt/BDAddressType.java +++ b/java/org/direct_bt/BDAddressType.java @@ -83,7 +83,7 @@ public enum BDAddressType { /** * Maps the specified name to a constant of {@link BDAddressType}. * <p> - * According to BlueZ's D-Bus protocol, which is also followed by TinyB, + * According to BlueZ's D-Bus protocol, * the following mappings are valid: * <ul> * <li>"{@code public}" -> {@link #BDADDR_LE_PUBLIC}</li> diff --git a/java/org/direct_bt/BTAdapter.java b/java/org/direct_bt/BTAdapter.java index 62efb83d..7464a026 100644 --- a/java/org/direct_bt/BTAdapter.java +++ b/java/org/direct_bt/BTAdapter.java @@ -39,9 +39,6 @@ import java.util.UUID; */ public interface BTAdapter extends BTObject { - @Override - public BTAdapter clone(); - /** * Returns the used singleton {@link BTManager} instance, used to create this adapter. */ @@ -79,7 +76,6 @@ public interface BTAdapter extends BTObject /** * Returns true, if the adapter's device is already whitelisted. * @since 2.0.0 - * @implNote not implemented in {@code tinyb.dbus} */ public boolean isDeviceWhitelisted(final BDAddressAndType addressAndType); @@ -104,7 +100,6 @@ public interface BTAdapter extends BTObject * * @see #addDeviceToWhitelist(String, BDAddressType, HCIWhitelistConnectType) * @since 2.0.0 - * @implNote not implemented in {@code tinyb.dbus} */ public boolean addDeviceToWhitelist(final BDAddressAndType addressAndType, final HCIWhitelistConnectType ctype, @@ -128,7 +123,6 @@ public interface BTAdapter extends BTObject * * @see #addDeviceToWhitelist(String, BDAddressType, HCIWhitelistConnectType, short, short, short, short) * @since 2.0.0 - * @implNote not implemented in {@code tinyb.dbus} */ public boolean addDeviceToWhitelist(final BDAddressAndType addressAndType, final HCIWhitelistConnectType ctype); @@ -137,18 +131,10 @@ public interface BTAdapter extends BTObject /** * Remove the given device from the adapter's autoconnect whitelist. * @since 2.0.0 - * @implNote not implemented in {@code tinyb.dbus} */ public boolean removeDeviceFromWhitelist(final BDAddressAndType addressAndType); - /** Turns on device discovery if it is disabled. - * @return TRUE if discovery was successfully enabled - * @deprecated since 2.0.0, use {@link #startDiscovery(boolean)}. - */ - @Deprecated - public boolean startDiscovery() throws BTException; - /** * Turns on device discovery if it is disabled. * <p> @@ -179,7 +165,6 @@ public interface BTAdapter extends BTObject * @throws BTException * @since 2.0.0 * @since 2.2.8 - * @implNote {@code keepAlive} not implemented in {@code tinyb.dbus} * @see #startDiscovery(boolean, boolean, int, int, byte) * @see #getDiscovering() */ @@ -195,7 +180,6 @@ public interface BTAdapter extends BTObject * @return {@link HCIStatusCode#SUCCESS} if successful, otherwise the {@link HCIStatusCode} error state * @throws BTException * @since 2.2.8 - * @implNote not implemented in {@code tinyb.dbus} * @see #startDiscovery(boolean, boolean) * @see #getDiscovering() */ @@ -231,7 +215,6 @@ public interface BTAdapter extends BTObject * Discards matching discovered devices. * @return {@code true} if found and removed, otherwise false. * @since 2.2.0 - * @implNote not implemented in {@code tinyb.dbus} */ public boolean removeDiscoveredDevice(final BDAddressAndType addressAndType); @@ -260,25 +243,6 @@ public interface BTAdapter extends BTObject */ BDAddressAndType getVisibleAddressAndType(); - /** - * Returns the hardware address of this adapter. - * @return The hardware address of this adapter. - * @implNote Changed to EUI48 since version 2.2.0 - * @since 2.2.0 - * @deprecated Use {@link #getAddressAndType()} and {@link #getVisibleAddressAndType()} - */ - @Deprecated - EUI48 getAddress(); - - /** - * Returns the hardware address of this adapter in its string representation. - * @return The hardware address of this adapter as a string. - * @since 2.2.0 - * @deprecated Use {@link #getAddress()} - */ - @Deprecated - String getAddressString(); - /** Returns the system name of this adapter. * @return The system name of this adapter. */ @@ -291,7 +255,6 @@ public interface BTAdapter extends BTObject * but may change after its destruction. * </p> * @since 2.0.0 - * @implNote Not implemented on {@code tinyb.dbus} */ public int getDevID(); @@ -304,12 +267,6 @@ public interface BTAdapter extends BTObject */ public void setAlias(String value); - /** Returns the Bluetooth class of the adapter. - * @return The Bluetooth class of the adapter. - */ - public long getBluetoothClass(); - - /** * Returns whether the adapter is valid, plugged in and powered. * @return true if {@link #isValid()}, HCI channel open and {@link AdapterSettings.SettingType#POWERED POWERED} state is set. @@ -351,21 +308,6 @@ public interface BTAdapter extends BTObject public boolean getPoweredState(); /** - * Enables notifications for the powered property and calls run function of the - * BluetoothNotification object. - * @param callback A BluetoothNotification<Boolean> object. Its run function will be called - * when a notification is issued. The run function will deliver the new value of the powered - * property. - */ - public void enablePoweredNotifications(BTNotification<Boolean> callback); - - /** - * Disables notifications of the powered property and unregisters the callback - * object passed through the corresponding enable method. - */ - public void disablePoweredNotifications(); - - /** * Sets the power state the adapter. * @apiNote return value boolean since 2.0.0 * @since 2.0.0 @@ -383,7 +325,6 @@ public interface BTAdapter extends BTObject * BT Core Spec v5.2: Vol 4, Part E HCI: 7.3.2 Reset command * </pre> * @since 2.0.0 - * @implNote not implemented in {@code tinyb.dbus} */ public HCIStatusCode reset(); @@ -393,39 +334,12 @@ public interface BTAdapter extends BTObject public boolean getDiscoverable(); /** - * Enables notifications for the discoverable property and calls run function of the - * BluetoothNotification object. - * @param callback A BluetoothNotification<Boolean> object. Its run function will be called - * when a notification is issued. The run function will deliver the new value of the discoverable - * property. - */ - public void enableDiscoverableNotifications(BTNotification<Boolean> callback); - /** - * Disables notifications of the discoverable property and unregisters the callback - * object passed through the corresponding enable method. - */ - public void disableDiscoverableNotifications(); - - /** * Sets the discoverable state the adapter. * @apiNote return value boolean since 2.0.0 * @since 2.0.0 */ public boolean setDiscoverable(boolean value); - /** Returns the discoverable timeout the adapter. - * @return The discoverable timeout of the adapter. - */ - public long getDiscoverableTimeout(); - - /** - * Sets the discoverable timeout the adapter. A value of 0 disables - * the timeout. - * @apiNote return value boolean since 2.0.0 - * @since 2.0.0 - */ - public boolean setDiscoverableTimout(long value); - /** * This method connects to device without need of * performing General Discovery. Connection mechanism is @@ -452,26 +366,6 @@ public interface BTAdapter extends BTObject */ public BTDevice connectDevice(BDAddressAndType addressAndType); - /** Returns the pairable state the adapter. - * @return The pairable state of the adapter. - */ - public boolean getPairable(); - - /** - * Enables notifications for the pairable property and calls run function of the - * BluetoothNotification object. - * @param callback A BluetoothNotification<Boolean> object. Its run function will be called - * when a notification is issued. The run function will deliver the new value of the pairable - * property. - */ - public void enablePairableNotifications(BTNotification<Boolean> callback); - - /** - * Disables notifications of the pairable property and unregisters the callback - * object passed through the corresponding enable method. - */ - public void disablePairableNotifications(); - /** * Sets the discoverable state the adapter. * @apiNote return value boolean since 2.0.0 @@ -479,24 +373,11 @@ public interface BTAdapter extends BTObject */ public boolean setPairable(boolean value); - /** Returns the timeout in seconds after which pairable state turns off - * automatically, 0 means never. - * @return The pairable timeout of the adapter. - */ - public long getPairableTimeout(); - - /** - * Sets the timeout after which pairable state turns off automatically, 0 means never. - * @apiNote return value boolean since 2.0.0 - * @since 2.0.0 - */ - public boolean setPairableTimeout(long value); - /** * Returns the current meta discovering {@link ScanType}. - * It can be modified through {@link #startDiscovery(boolean)} and {@link #stopDiscovery()}. + * It can be modified through {@link #startDiscovery(boolean, boolean)} and {@link #stopDiscovery()}. * <p> - * Note that if {@link #startDiscovery(boolean)} has been issued with keepAlive==true, + * Note that if {@link #startDiscovery(boolean, boolean)} has been issued with keepAlive==true, * the meta {@link ScanType} will still keep the desired {@link ScanType} enabled * even if it has been temporarily disabled. * </p> @@ -507,18 +388,6 @@ public interface BTAdapter extends BTObject public ScanType getCurrentScanType(); /** - * Returns the meta discovering state (of the adapter). - * It can be modified through - * start_discovery/stop_discovery functions. - * @return The discovering state of the adapter. - * @deprecated since 2.0.0, use {@link #getCurrentScanType()}. - * @see #getCurrentScanType() - * @see #startDiscovery(boolean) - */ - @Deprecated - public boolean getDiscovering(); - - /** * Add the given {@link AdapterStatusListener} to the list if not already present. * <p> * In case the {@link AdapterStatusListener}'s lifecycle and event delivery @@ -534,7 +403,6 @@ public interface BTAdapter extends BTObject * @param listener A {@link AdapterStatusListener} instance * @return true if the given listener is not element of the list and has been newly added, otherwise false. * @since 2.3.0 - * @implNote not implemented in {@code tinyb.dbus} * @see {@link BTDevice#addStatusListener(AdapterStatusListener)} * @see {@link #removeStatusListener(AdapterStatusListener)} * @see {@link #removeAllStatusListener()} @@ -546,7 +414,6 @@ public interface BTAdapter extends BTObject * @param listener A {@link AdapterStatusListener} instance * @return true if the given listener is an element of the list and has been removed, otherwise false. * @since 2.0.0 - * @implNote not implemented in {@code tinyb.dbus} */ public boolean removeStatusListener(final AdapterStatusListener l); @@ -554,62 +421,10 @@ public interface BTAdapter extends BTObject * Remove all {@link AdapterStatusListener} from the list. * @return number of removed listener. * @since 2.0.0 - * @implNote not implemented in {@code tinyb.dbus} */ public int removeAllStatusListener(); /** - * Enables notifications for the discovering property and calls run function of the - * BluetoothNotification object. - * @param callback A BluetoothNotification<Boolean> object. Its run function will be called - * when a notification is issued. The run function will deliver the new value of the discovering - * property. - */ - public void enableDiscoveringNotifications(BTNotification<Boolean> callback); - - /** - * Disables notifications of the discovering property and unregisters the discovering - * object passed through the corresponding enable method. - */ - public void disableDiscoveringNotifications(); - - /** Returns the UUIDs of the adapter. - * @return Array containing the UUIDs of the adapter, ends with NULL. - */ - public String[] getUUIDs(); - - /** Returns the local ID of the adapter. - * @return The local ID of the adapter. - */ - public String getModalias(); - - /** This method sets the device discovery filter for the caller. When this method is called - * with no filter parameter, filter is removed. - * <p> - * When a remote device is found that advertises any UUID from UUIDs, it will be reported if: - * <ul><li>Pathloss and RSSI are both empty.</li> - * <li>only Pathloss param is set, device advertise TX pwer, and computed pathloss is less than Pathloss param.</li> - * <li>only RSSI param is set, and received RSSI is higher than RSSI param.</li> - * </ul> - * <p> - * If one or more discovery filters have been set, the RSSI delta-threshold, - * that is imposed by StartDiscovery by default, will not be applied. - * <p> - * If "auto" transport is requested, scan will use LE, BREDR, or both, depending on what's - * currently enabled on the controller. - * - * @param uuids a list of device UUIDs - * @param rssi a rssi value - * @param pathloss a pathloss value - */ - public void setDiscoveryFilter(List<UUID> uuids, int rssi, int pathloss, TransportType transportType); - - /** Returns the interface name of the adapter. - * @return The interface name of the adapter. - */ - public String getInterfaceName(); - - /** * Print the internally maintained BTDevice lists to stderr: * - sharedDevices * - connectedDevice @@ -618,7 +433,6 @@ public interface BTAdapter extends BTObject * * This is intended as a debug facility. * @since 2.3.0 - * @implNote not implemented in {@code tinyb.dbus} */ public void printDeviceLists(); diff --git a/java/org/direct_bt/BTCallback.java b/java/org/direct_bt/BTCallback.java deleted file mode 100644 index 86b3f542..00000000 --- a/java/org/direct_bt/BTCallback.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Author: Andrei Vasiliu <[email protected]> - * Copyright (c) 2016 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.direct_bt; - -import tinyb.dbus.DBusObject; - -public abstract class BTCallback implements Runnable -{ - protected DBusObject bObj; - - /* - * public void run() is missing because it will be implemented - * in children classes - */ -} diff --git a/java/org/direct_bt/BTDevice.java b/java/org/direct_bt/BTDevice.java index ed2b7f98..70cfdba8 100644 --- a/java/org/direct_bt/BTDevice.java +++ b/java/org/direct_bt/BTDevice.java @@ -40,9 +40,6 @@ import java.util.Map; */ public interface BTDevice extends BTObject { - @Override - public BTDevice clone(); - /** Find a BluetoothGattService. If parameter UUID is not null, * the returned object will have to match it. * It will first check for existing objects. It will not turn on discovery @@ -85,7 +82,6 @@ public interface BTDevice extends BTObject * {@link AdapterStatusListener} {@code device*} methods. Pass {@code null} for no filtering. * @return true if the given listener is not element of the list and has been newly added, otherwise false. * @since 2.3.0 - * @implNote not implemented in {@code tinyb.dbus} * @see {@link BTDevice#addStatusListener(AdapterStatusListener, BTDevice)} * @see {@link #removeStatusListener(AdapterStatusListener)} * @see {@link #removeAllStatusListener()} @@ -97,7 +93,6 @@ public interface BTDevice extends BTObject * @param listener A {@link AdapterStatusListener} instance * @return true if the given listener is an element of the list and has been removed, otherwise false. * @since 2.3.0 - * @implNote not implemented in {@code tinyb.dbus} */ public boolean removeStatusListener(final AdapterStatusListener l); @@ -150,7 +145,6 @@ public interface BTDevice extends BTObject * The device is tracked by the managing adapter. * </p> * <p> - * {@code tinyb.dbus}: A connection to this device is established, connecting each profile * flagged as auto-connectable. * </p> * @return {@link HCIStatusCode#SUCCESS} if the command has been accepted, otherwise {@link HCIStatusCode} may disclose reason for rejection. @@ -197,32 +191,17 @@ public interface BTDevice extends BTObject * @return {@link HCIStatusCode#SUCCESS} if the command has been accepted, otherwise {@link HCIStatusCode} may disclose reason for rejection. * @see BTUtils#getHCIConnSupervisorTimeout(int, int, int, int) * @see #connect() - * @since 2.1.0 change API, i.e. return value from boolean to HCIStatusCode in favor of <i>direct_bt</i> - * @implNote not implemented in {@code tinyb.dbus} */ HCIStatusCode connectLE(final short le_scan_interval, final short le_scan_window, final short conn_interval_min, final short conn_interval_max, final short conn_latency, final short supervision_timeout); - /** Connects a specific profile available on the device, given by UUID - * @param arg_UUID The UUID of the profile to be connected - * @return TRUE if the profile connected successfully - */ - boolean connectProfile(String arg_UUID) throws BTException; - - /** Disconnects a specific profile available on the device, given by UUID - * @param arg_UUID The UUID of the profile to be disconnected - * @return TRUE if the profile disconnected successfully - */ - boolean disconnectProfile(String arg_UUID) throws BTException; - /** * Returns the available {@link SMPKeyMask.KeyType} {@link SMPKeyMask} for the responder (LL slave) or initiator (LL master). * @param responder if true, queries the responder (LL slave) key, otherwise the initiator (LL master) key. * @return {@link SMPKeyMask.KeyType} {@link SMPKeyMask} result * @since 2.2.0 - * @implNote not implemented in {@code tinyb.dbus} */ SMPKeyMask getAvailableSMPKeys(final boolean responder); @@ -233,7 +212,6 @@ public interface BTDevice extends BTObject * @see {@link SMPPairingState#COMPLETED} * @see {@link AdapterStatusListener#deviceReady(BTDevice, long)} * @since 2.2.0 - * @implNote not implemented in {@code tinyb.dbus} */ SMPLongTermKeyInfo getLongTermKeyInfo(final boolean responder); @@ -245,7 +223,6 @@ public interface BTDevice extends BTObject * @param ltk the pre-paired encryption LTK * @return {@link HCIStatusCode#SUCCESS} if successful, otherwise the appropriate error code. * @since 2.2.0 - * @implNote not implemented in {@code tinyb.dbus} */ HCIStatusCode setLongTermKeyInfo(final SMPLongTermKeyInfo ltk); @@ -256,22 +233,10 @@ public interface BTDevice extends BTObject * @see {@link SMPPairingState#COMPLETED} * @see {@link AdapterStatusListener#deviceReady(BTDevice, long)} * @since 2.2.0 - * @implNote not implemented in {@code tinyb.dbus} */ SMPSignatureResolvingKeyInfo getSignatureResolvingKeyInfo(final boolean responder); /** - * A secure connection to this device is established, and the device is then paired. - * <p> - * For direct_bt use {@link #setConnSecurity(BTSecurityLevel, SMPIOCapability) setConnSecurity(..) or its variants} - * and {@link #connectLE(short, short, short, short, short, short) connectLE(..)}. - * </p> - * @return TRUE if the device connected and paired - * @implNote not implemented in {@code jau.direct_bt} - */ - boolean pair() throws BTException; - - /** * Unpairs this device from the adapter while staying connected. * <p> * All keys will be cleared within the adapter and host implementation.<br> @@ -281,7 +246,6 @@ public interface BTDevice extends BTObject * </p> * @return {@link HCIStatusCode#SUCCESS} or an appropriate error status. * @since 2.1.0 - * @implNote not implemented in {@code tinyb.dbus} */ HCIStatusCode unpair(); @@ -303,7 +267,6 @@ public interface BTDevice extends BTObject * @param sec_level {@link BTSecurityLevel} to be applied, {@link BTSecurityLevel#UNSET} will be ignored and method fails. * @return * @since 2.1.0 - * @implNote not implemented in {@code tinyb.dbus} * @see BTSecurityLevel * @see SMPIOCapability * @see #getConnSecurityLevel() @@ -317,7 +280,6 @@ public interface BTDevice extends BTObject /** * Return the {@link BTSecurityLevel}, determined when the connection is established. * @since 2.1.0 - * @implNote not implemented in {@code tinyb.dbus} * @see BTSecurityLevel * @see SMPIOCapability * @see #setConnSecurityLevel(BTSecurityLevel) @@ -337,7 +299,6 @@ public interface BTDevice extends BTObject * </p> * @param io_cap {@link SMPIOCapability} to be applied, {@link SMPIOCapability#UNSET} will be ignored and method fails. * @since 2.1.0 - * @implNote not implemented in {@code tinyb.dbus} * @see BTSecurityLevel * @see SMPIOCapability * @see #setConnSecurityLevel(BTSecurityLevel) @@ -351,7 +312,6 @@ public interface BTDevice extends BTObject /** * Return the {@link SMPIOCapability} value, determined when the connection is established. * @since 2.1.0 - * @implNote not implemented in {@code tinyb.dbus} * @see BTSecurityLevel * @see SMPIOCapability * @see #setConnSecurityLevel(BTSecurityLevel) @@ -374,7 +334,6 @@ public interface BTDevice extends BTObject * @param sec_level {@link BTSecurityLevel} to be applied. * @param io_cap {@link SMPIOCapability} to be applied. * @since 2.1.0 - * @implNote not implemented in {@code tinyb.dbus} * @see BTSecurityLevel * @see SMPIOCapability * @see #setConnSecurityLevel(BTSecurityLevel) @@ -411,7 +370,6 @@ public interface BTDevice extends BTObject * @param sec_level {@link BTSecurityLevel} to be applied. * @param io_cap {@link SMPIOCapability} to be applied. * @since 2.1.0 - * @implNote not implemented in {@code tinyb.dbus} * @see BTSecurityLevel * @see SMPIOCapability * @see #setConnSecurityLevel(BTSecurityLevel) @@ -449,7 +407,6 @@ public interface BTDevice extends BTObject * </p> * @param auth_io_cap user {@link SMPIOCapability} choice for negotiation * @since 2.2.0 - * @implNote not implemented in {@code tinyb.dbus} * @see #isConnSecurityAutoEnabled() * @see BTSecurityLevel * @see SMPIOCapability @@ -460,7 +417,6 @@ public interface BTDevice extends BTObject * Returns true if automatic security negotiation has been enabled via {@link #setConnSecurityAuto(SMPIOCapability)}, * otherwise false. * @since 2.2.0 - * @implNote not implemented in {@code tinyb.dbus} * @see #setConnSecurityAuto(SMPIOCapability) */ boolean isConnSecurityAutoEnabled(); @@ -485,7 +441,6 @@ public interface BTDevice extends BTObject * @see #getPairingMode() * @see #getPairingState() * @since 2.1.0 - * @implNote not implemented in {@code tinyb.dbus} */ HCIStatusCode setPairingPasskey(final int passkey); @@ -512,7 +467,6 @@ public interface BTDevice extends BTObject * @see #getPairingMode() * @see #getPairingState() * @since 2.1.0 - * @implNote not implemented in {@code tinyb.dbus} */ HCIStatusCode setPairingPasskeyNegative(); @@ -536,7 +490,6 @@ public interface BTDevice extends BTObject * @see #getPairingMode() * @see #getPairingState() * @since 2.1.0 - * @implNote not implemented in {@code tinyb.dbus} */ HCIStatusCode setPairingNumericComparison(final boolean equal); @@ -563,7 +516,6 @@ public interface BTDevice extends BTObject * @see #getPairingMode() * @see #getPairingState() * @since 2.1.0 - * @implNote not implemented in {@code tinyb.dbus} */ PairingMode getPairingMode(); @@ -580,7 +532,6 @@ public interface BTDevice extends BTObject * @see #getPairingMode() * @see #getPairingState() * @since 2.1.0 - * @implNote not implemented in {@code tinyb.dbus} */ SMPPairingState getPairingState(); @@ -623,11 +574,6 @@ public interface BTDevice extends BTObject */ public boolean isValid(); - /** Cancels an initiated pairing operation - * @return TRUE if the paring is cancelled successfully - */ - boolean cancelPairing() throws BTException; - /** Returns a list of BluetoothGattServices available on this device. * @return A list of BluetoothGattServices available on this device, * NULL if an error occurred @@ -648,7 +594,6 @@ public interface BTDevice extends BTObject * </p> * @return {@code true} if successful or not implemented, otherwise false in case no GATT services exists or is not connected.. * @since 2.0.0 - * @implNote not implemented in {@code tinyb.dbus}. */ boolean pingGATT(); @@ -667,7 +612,6 @@ public interface BTDevice extends BTObject * * @see BTUtils#currentTimeMillis() * @since 2.0.0 - * @implNote not implemented in {@code tinyb.dbus}, returns {@link #getCreationTimestamp()} */ long getLastDiscoveryTimestamp(); @@ -677,148 +621,25 @@ public interface BTDevice extends BTObject * * @see BTUtils#currentTimeMillis() * @since 2.0.0 - * @implNote not implemented in {@code tinyb.dbus}, returns {@link #getCreationTimestamp()} */ long getLastUpdateTimestamp(); /** * Returns the unique device {@link EUI48} address and {@link BDAddressType} type. * @since 2.2.0 - * @implNote not fully implemented in {@code tinyb.dbus}, uses {@link BDAddressType#BDADDR_LE_PUBLIC} */ BDAddressAndType getAddressAndType(); - /** - * Returns the hardware address of this device in its string representation. - * @return The hardware address of this device as a string. - * @since 2.2.0 - * @deprecated Use {@link #getAddressAndType()} - */ - @Deprecated - String getAddressString(); - /** Returns the remote friendly name of this device. * @return The remote friendly name of this device, or NULL if not set. */ String getName(); - /** Returns an alternative friendly name of this device. - * @return The alternative friendly name of this device, or NULL if not set. - */ - String getAlias(); - - /** Sets an alternative friendly name of this device. - */ - void setAlias(String value); - - /** Returns the Bluetooth class of the device. - * @return The Bluetooth class of the device. - */ - int getBluetoothClass(); - - /** Returns the appearance of the device, as found by GAP service. - * @return The appearance of the device, as found by GAP service. - */ - short getAppearance(); - - /** Returns the proposed icon name of the device. - * @return The proposed icon name, or NULL if not set. - */ - String getIcon(); - - /** Returns the paired state the device. - * @return The paired state of the device. - */ - boolean getPaired(); - - /** - * Enables notifications for the paired property and calls run function of the - * BluetoothNotification object. - * @param callback A BluetoothNotification<Boolean> object. Its run function will be called - * when a notification is issued. The run function will deliver the new value of the paired - * property. - */ - void enablePairedNotifications(BTNotification<Boolean> callback); - - /** - * Disables notifications of the paired property and unregisters the callback - * object passed through the corresponding enable method. - */ - void disablePairedNotifications(); - - /** Returns the trusted state the device. - * @return The trusted state of the device. - */ - boolean getTrusted(); - - /** - * Enables notifications for the trusted property and calls run function of the - * BluetoothNotification object. - * @param callback A BluetoothNotification<Boolean> object. Its run function will be called - * when a notification is issued. The run function will deliver the new value of the trusted - * property. - */ - void enableTrustedNotifications(BTNotification<Boolean> callback); - - /** - * Disables notifications of the trusted property and unregisters the callback - * object passed through the corresponding enable method. - */ - void disableTrustedNotifications(); - - /** Sets the trusted state the device. - */ - void setTrusted(boolean value); - - /** Returns the blocked state the device. - * @return The blocked state of the device. - */ - boolean getBlocked(); - - /** - * Enables notifications for the blocked property and calls run function of the - * BluetoothNotification object. - * @param callback A BluetoothNotification<Boolean> object. Its run function will be called - * when a notification is issued. The run function will deliver the new value of the blocked - * property. - */ - void enableBlockedNotifications(BTNotification<Boolean> callback); - - /** - * Disables notifications of the blocked property and unregisters the callback - * object passed through the corresponding enable method. - */ - void disableBlockedNotifications(); - - /** Sets the blocked state the device. - */ - void setBlocked(boolean value); - - /** Returns if device uses only pre-Bluetooth 2.1 pairing mechanism. - * @return True if device uses only pre-Bluetooth 2.1 pairing mechanism. - */ - boolean getLegacyPairing(); - /** Returns the Received Signal Strength Indicator of the device. * @return The Received Signal Strength Indicator of the device. */ short getRSSI(); - /** - * Enables notifications for the RSSI property and calls run function of the - * BluetoothNotification object. - * @param callback A BluetoothNotification<Short> object. Its run function will be called - * when a notification is issued. The run function will deliver the new value of the RSSI - * property. - */ - void enableRSSINotifications(BTNotification<Short> callback); - - /** - * Disables notifications of the RSSI property and unregisters the callback - * object passed through the corresponding enable method. - */ - void disableRSSINotifications(); - /** Returns the connected state of the device. * @return The connected state of the device. */ @@ -827,35 +648,9 @@ public interface BTDevice extends BTObject /** * Return the HCI connection handle to the LE or BREDR peer, zero if not connected. * @since 2.1.0 - * @implNote not implemented in {@code tinyb.dbus} */ short getConnectionHandle(); - /** - * Enables notifications for the connected property and calls run function of the - * BluetoothNotification object. - * @param callback A BluetoothNotification<Boolean> object. Its run function will be called - * when a notification is issued. The run function will deliver the new value of the connected - * property. - */ - void enableConnectedNotifications(BTNotification<Boolean> callback); - - /** - * Disables notifications of the connected property and unregisters the callback - * object passed through the corresponding enable method. - */ - void disableConnectedNotifications(); - - /** Returns the UUIDs of the device. - * @return Array containing the UUIDs of the device, ends with NULL. - */ - String[] getUUIDs(); - - /** Returns the local ID of the adapter. - * @return The local ID of the adapter. - */ - String getModalias(); - /** Returns the adapter on which this device was discovered or * connected. * @return The adapter. @@ -868,70 +663,11 @@ public interface BTDevice extends BTObject */ Map<Short, byte[]> getManufacturerData(); - /** - * Enables notifications for the manufacturer data property and calls run function of the - * BluetoothNotification object. - * @param callback A BluetoothNotification<Map<Short, byte[]> > object. Its run function will be called - * when a notification is issued. The run function will deliver the new value of the manufacturer data - * property. - */ - void enableManufacturerDataNotifications( - BTNotification<Map<Short, byte[]>> callback); - - /** - * Disables notifications of the manufacturer data property and unregisters the callback - * object passed through the corresponding enable method. - */ - void disableManufacturerDataNotifications(); - - /** Returns a map containing service advertisement data. - * An entry has a UUID string key and an array of bytes. - * @return service advertisement data. - */ - Map<String, byte[]> getServiceData(); - - /** - * Enables notifications for the service data property and calls run function of the - * BluetoothNotification object. - * @param callback A BluetoothNotification<Map<String, byte[]> > object. Its run function will be called - * when a notification is issued. The run function will deliver the new value of the service data - * property. - */ - void enableServiceDataNotifications( - BTNotification<Map<String, byte[]>> callback); - - /** - * Disables notifications of the service data property and unregisters the callback - * object passed through the corresponding enable method. - */ - void disableServiceDataNotifications(); - /** Returns the transmission power level (0 means unknown). * @return the transmission power level (0 means unknown). */ short getTxPower(); - /** Returns true if service discovery has ended. - * @return true if the service discovery has ended. - */ - boolean getServicesResolved(); - - /** - * Enables notifications for the services resolved property and calls run function of the - * BluetoothNotification object. - * @param callback A BluetoothNotification<Boolean> object. Its run function will be called - * when a notification is issued. The run function will deliver the new value of the services resolved - * property. - */ - void enableServicesResolvedNotifications( - BTNotification<Boolean> callback); - - /** - * Disables notifications of the services resolved property and unregisters the callback - * object passed through the corresponding enable method. - */ - void disableServicesResolvedNotifications(); - /** * Add the given {@link BTGattCharListener} to the listener list if not already present. * <p> @@ -946,7 +682,6 @@ public interface BTDevice extends BTObject * @see BTGattChar#configNotificationIndication(boolean, boolean, boolean[]) * @see BTGattChar#enableNotificationOrIndication(boolean[]) * @since 2.0.0 - * @implNote not implemented in {@code tinyb.dbus} */ public boolean addCharListener(final BTGattCharListener listener) throws IllegalStateException; @@ -959,7 +694,6 @@ public interface BTDevice extends BTObject * @param listener A {@link BTGattCharListener} instance * @return true if the given listener is an element of the list and has been removed, otherwise false. * @since 2.0.0 - * @implNote not implemented in {@code tinyb.dbus} */ public boolean removeCharListener(final BTGattCharListener l); @@ -972,7 +706,6 @@ public interface BTDevice extends BTObject * @param associatedCharacteristic the match criteria to remove any BTGattCharListener from the list * @return number of removed listener. * @since 2.0.0 - * @implNote not implemented in {@code tinyb.dbus} */ public int removeAllAssociatedCharListener(final BTGattChar associatedCharacteristic); @@ -980,7 +713,6 @@ public interface BTDevice extends BTObject * Remove all {@link BTGattCharListener} from the list. * @return number of removed listener. * @since 2.0.0 - * @implNote not implemented in {@code tinyb.dbus} */ public int removeAllCharListener(); } diff --git a/java/org/direct_bt/BTEvent.java b/java/org/direct_bt/BTEvent.java deleted file mode 100644 index 12cf5f9e..00000000 --- a/java/org/direct_bt/BTEvent.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Author: Sven Gothel <[email protected]> - * Copyright (c) 2020 Gothel Software e.K. - * Copyright (c) 2020 ZAFENA AB - * - * Author: Andrei Vasiliu <[email protected]> - * Copyright (c) 2016 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.direct_bt; - -public interface BTEvent -{ - public BTType getType(); - public String getName(); - public String getIdentifier(); - public boolean executeCallback(); - public boolean hasCallback(); - -} diff --git a/java/org/direct_bt/BTFactory.java b/java/org/direct_bt/BTFactory.java index 585b630c..93f01b87 100644 --- a/java/org/direct_bt/BTFactory.java +++ b/java/org/direct_bt/BTFactory.java @@ -109,14 +109,6 @@ public class BTFactory { } /** - * {@link ImplementationIdentifier} for D-Bus implementation: {@value} - * <p> - * This value is exposed for convenience, user implementations are welcome. - * </p> - */ - public static final ImplementationIdentifier DBusImplementationID = new ImplementationIdentifier("tinyb.dbus.DBusManager", "tinyb", "javatinyb"); - - /** * {@link ImplementationIdentifier} for direct_bt implementation: {@value} * <p> * This value is exposed for convenience, user implementations are welcome. @@ -160,7 +152,6 @@ public class BTFactory { * System property {@code org.direct_bt.btmode}, string, default {@code DUAL} {@link BTMode#DUAL}. * </p> * @since 2.0.0 - * @implNote not implemented in tinyb.dbus. */ public static final BTMode DEFAULT_BTMODE; @@ -197,7 +188,6 @@ public class BTFactory { DEFAULT_BTMODE = btMode; } implIDs.add(DirectBTImplementationID); - implIDs.add(DBusImplementationID); boolean isJaulibAvail = false; try { @@ -290,7 +280,7 @@ public class BTFactory { // Map all Java properties '[org.]direct_bt.*' and 'direct_bt.*' to native environment. try { if( DEBUG ) { - System.err.println("BlootoothFactory: Mapping '[org.|jau.]direct_bt.*' and 'tinyb.*' properties to native environment"); + System.err.println("BlootoothFactory: Mapping '[org.|jau.]direct_bt.*' properties to native environment"); } final Properties props = AccessController.doPrivileged(new PrivilegedAction<Properties>() { @Override @@ -302,7 +292,7 @@ public class BTFactory { while (enums.hasMoreElements()) { final String key = (String) enums.nextElement(); if( key.startsWith("org.direct_bt.") || key.startsWith("jau.direct_bt.") || - key.startsWith("direct_bt.") || key.startsWith("tinyb.") ) + key.startsWith("direct_bt.") ) { final String value = props.getProperty(key); if( DEBUG ) { @@ -472,29 +462,6 @@ public class BTFactory { } /** - * Returns an initialized BluetoothManager instance using a D-Bus implementation. - * <p> - * Issues {@link #getBTManager(ImplementationIdentifier)} using {@link #DBusImplementationID}. - * </p> - * <p> - * The chosen implementation can't be changed within a running implementation, an exception is thrown if tried. - * </p> - * @throws BTException - * @throws NoSuchMethodException - * @throws SecurityException - * @throws IllegalAccessException - * @throws IllegalArgumentException - * @throws InvocationTargetException - * @throws ClassNotFoundException - */ - public static synchronized BTManager getDBusBTManager() - throws BTException, NoSuchMethodException, SecurityException, - IllegalAccessException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException - { - return getBTManager(DBusImplementationID); - } - - /** * Returns an initialized BluetoothManager instance using the DirectBT implementation. * <p> * Issues {@link #getBTManager(ImplementationIdentifier)} using {@link #DirectBTImplementationID}. @@ -624,19 +591,3 @@ public class BTFactory { * </p> */ -/** \example ScannerTinyB00.java - * This Java scanner example is a TinyB backward compatible and not fully event driven. - * It simply polls found devices and shows certain results. - * <p> - * This example does not represent the recommended utilization of Direct-BT. - * </p> - */ - -/** \example ScannerTinyB01.java - * This Java scanner example is a TinyB backward compatible and not fully event driven. - * It simply polls found devices and shows certain results. - * However, the AdapterStatusListener is attached if supported. - * <p> - * This example does not represent the recommended utilization of Direct-BT. - * </p> - */ diff --git a/java/org/direct_bt/BTGattChar.java b/java/org/direct_bt/BTGattChar.java index 078fbd0f..3f5f0e5d 100644 --- a/java/org/direct_bt/BTGattChar.java +++ b/java/org/direct_bt/BTGattChar.java @@ -77,9 +77,6 @@ public interface BTGattChar extends BTObject final boolean confirmationSent); }; - @Override - public BTGattChar clone(); - /** Find a BluetoothGattDescriptor. If parameter UUID is not null, * the returned object will have to match it. * It will first check for existing objects. It will not turn on discovery @@ -137,7 +134,6 @@ public interface BTGattChar extends BTObject * and the {@link BTDevice}'s GATTHandler is null, i.e. not connected * @see #enableNotificationOrIndication(boolean[]) * @since 2.0.0 - * @implNote not implemented in tinyb.dbus */ public boolean configNotificationIndication(final boolean enableNotification, final boolean enableIndication, final boolean enabledState[/*2*/]) throws IllegalStateException; @@ -163,7 +159,6 @@ public interface BTGattChar extends BTObject * and the {@link BTDevice}'s GATTHandler is null, i.e. not connected * @see #configNotificationIndication(boolean, boolean, boolean[]) * @since 2.0.0 - * @implNote not implemented in tinyb.dbus */ public boolean enableNotificationOrIndication(final boolean enabledState[/*2*/]) throws IllegalStateException; @@ -190,7 +185,6 @@ public interface BTGattChar extends BTObject * @see #removeCharListener(Listener, boolean) * @see #removeAllAssociatedCharListener(boolean) * @since 2.0.0 - * @implNote not implemented in tinyb.dbus */ public boolean addCharListener(final Listener listener) throws IllegalStateException; @@ -221,7 +215,6 @@ public interface BTGattChar extends BTObject * @see #removeCharListener(Listener, boolean) * @see #removeAllAssociatedCharListener(boolean) * @since 2.0.0 - * @implNote not implemented in tinyb.dbus */ public boolean addCharListener(final Listener listener, final boolean enabledState[/*2*/]) throws IllegalStateException; @@ -244,23 +237,10 @@ public interface BTGattChar extends BTObject * @see #addCharListener(Listener, boolean[]) * @see #removeCharListener(Listener, boolean) * @since 2.0.0 - * @implNote not implemented in tinyb.dbus */ public int removeAllAssociatedCharListener(final boolean disableIndicationNotification); /** - * Sets the given value BluetoothNotification to have its run function - * receive the enabled notification and/or indication sent. - * <p> - * Enables notification and/or indication for this characteristic at BLE level. - * </p. - * @param callback A BluetoothNotification<byte[]> object. Its run function will be called - * when a notification is issued. The run function will deliver the new value of the value - * property. - */ - public void enableValueNotifications(BTNotification<byte[]> callback); - - /** * Disables notifications of the value and unregisters the callback object * passed through the corresponding enable method. It disables notifcations * at BLE level for this characteristic. @@ -280,7 +260,6 @@ public interface BTGattChar extends BTObject * @return TRUE if value was written successfully * @since 2.0.0 * @implNote {@code withResponse} parameter has been added since 2.0.0 - * @implNote tinyb.dbus does not support {@code withResponse = true} */ public boolean writeValue(byte[] argValue, boolean withResponse) throws BTException; @@ -296,31 +275,19 @@ public interface BTGattChar extends BTObject */ public BTGattService getService(); - /** Returns the cached value of this characteristic, if any. - * @return The cached value of this characteristic. + /** Returns true if notification for changes of this characteristic are activated. + * @param enabledState array of size 2, storage for the current enabled state for notification and indication. + * @return True if either notification or indication is enabled */ - public byte[] getValue(); - - /** Returns true if notification for changes of this characteristic are - * activated. - * @return True if notificatios are activated. - */ - public boolean getNotifying(); + public boolean getNotifying(final boolean enabledState[/*2*/]); /** - * Returns the flags this characterstic has. - * <p> - * These flags are actually the BT Core Spec v5.2: Vol 3, Part G GATT: 3.3.1.1 Characteristic Properties - * </p> + * Returns the properties of this characteristic. * <p> - * Returns string values as defined in <https://git.kernel.org/pub/scm/bluetooth/bluez.git/tree/doc/gatt-api.txt> - * <pre> - * org.bluez.GattCharacteristic1 :: array{string} Flags [read-only] - * </pre> + * BT Core Spec v5.2: Vol 3, Part G GATT: 3.3.1.1 Characteristic Properties * </p> - * @return A list of flags for this characteristic. */ - public String[] getFlags(); + public GattCharPropertySet getProperties(); /** Returns a list of BluetoothGattDescriptors this characteristic exposes. * @return A list of BluetoothGattDescriptors exposed by this characteristic diff --git a/java/org/direct_bt/BTGattDesc.java b/java/org/direct_bt/BTGattDesc.java index 23ee5352..5318a262 100644 --- a/java/org/direct_bt/BTGattDesc.java +++ b/java/org/direct_bt/BTGattDesc.java @@ -36,11 +36,6 @@ package org.direct_bt; */ public interface BTGattDesc extends BTObject { - @Override - public BTGattDesc clone(); - - /* D-Bus method calls: */ - /** Reads the value of this descriptor * @return A vector<uchar> containing data from this descriptor */ @@ -53,22 +48,6 @@ public interface BTGattDesc extends BTObject */ public boolean writeValue(byte[] argValue) throws BTException; - /** - * Enables notifications for the value and calls run function of the BluetoothNotification - * object. - * @param callback A BluetoothNotification<byte[]> object. Its run function will be called - * when a notification is issued. The run function will deliver the new value of the value - * property. - */ - public void enableValueNotifications(BTNotification<byte[]> callback); - /** - * Disables notifications of the value and unregisters the callback object - * passed through the corresponding enable method. - */ - public void disableValueNotifications(); - - /* D-Bus property accessors: */ - /** Get the UUID of this descriptor. * @return The 128 byte UUID of this descriptor, NULL if an error occurred */ diff --git a/java/org/direct_bt/BTGattService.java b/java/org/direct_bt/BTGattService.java index 4822d71c..c944f95b 100644 --- a/java/org/direct_bt/BTGattService.java +++ b/java/org/direct_bt/BTGattService.java @@ -39,9 +39,6 @@ import java.util.List; */ public interface BTGattService extends BTObject { - @Override - public BTGattService clone(); - /** Find a BTGattChar. If parameter UUID is not null, * the returned object will have to match it. * It will first check for existing objects. It will not turn on discovery @@ -98,7 +95,6 @@ public interface BTGattService extends BTObject * @throws IllegalArgumentException if listener's {@link BTGattCharListener#getAssociatedChar() associated characteristic} * is not null. * @since 2.0.0 - * @implNote not implemented in tinyb.dbus * @see BTGattChar#enableNotificationOrIndication(boolean[]) * @see BTDevice#addCharListener(BTGattCharListener, BTGattChar) */ @@ -126,7 +122,6 @@ public interface BTGattService extends BTObject * @param listener {@link BTGattCharListener} to remove from the {@link BTDevice}. * @return true if successful, otherwise false * @since 2.0.0 - * @implNote not implemented in tinyb.dbus * @see BTGattChar#configNotificationIndication(boolean, boolean, boolean[]) * @see BTDevice#removeCharListener(BTGattCharListener) */ @@ -146,7 +141,6 @@ public interface BTGattService extends BTObject * Removes all {@link BTGattCharListener} from the {@link BTDevice}. * @return count of removed {@link BTGattCharListener} * @since 2.0.0 - * @implNote not implemented in tinyb.dbus * @see BTGattChar#configNotificationIndication(boolean, boolean, boolean[]) * @see BTDevice#removeAllCharListener() */ diff --git a/java/org/direct_bt/BTManager.java b/java/org/direct_bt/BTManager.java index 2fd4291c..120ef7c8 100644 --- a/java/org/direct_bt/BTManager.java +++ b/java/org/direct_bt/BTManager.java @@ -46,31 +46,6 @@ public interface BTManager */ boolean isDirectBT(); - /** - * Returns true if underlying implementation is TinyB. - */ - boolean isTinyB(); - - /** - * Returns whether {@link BTGattChar} API: {@link BTGattChar#getValue() value cache} and - * {@link BTGattChar#enableValueNotifications(BluetoothNotification) value notification} - * is supported. - * <p> - * This is enabled using {@link #isTinyB() TinyB}, but disabled by default using {@link #isDirectBT() Direct-BT}. - * </p> - * <p> - * If using {@link #isDirectBT() Direct-BT}, user are encouraged to - * {@link BTGattChar#addCharListener(BTGattCharListener, boolean[]) utilize BTGattCharListener} - * to handle value notifications when they occur w/o caching. - * </p> - * <p> - * If using {@link #isDirectBT() Direct-BT}, users can enable this TinyB compatibility - * by setting the System property {@code jau.direct_bt.characteristic.compat} to {@code true}. - * It defaults to {@code false}, i.e. disabled. - * </p> - */ - boolean isCharValueCacheNotificationSupported(); - @Override String toString(); } @@ -88,7 +63,6 @@ public interface BTManager * allowing the user to perform complex operations. * </p> * @since 2.0.0 - * @implNote Not implemented on tinyb.dbus * @see BTManager#addChangedAdapterSetListener(ChangedAdapterSetListener) * @see BTManager#removeChangedAdapterSetListener(ChangedAdapterSetListener) */ @@ -155,73 +129,6 @@ public interface BTManager */ public BTObject find(BTType type, String name, String identifier, BTObject parent); - /** Find a BluetoothObject of type T. If parameters name, identifier and - * parent are not null, the returned object will have to match them. - * It will first check for existing objects. It will not turn on discovery - * or connect to devices. - * @parameter name optionally specify the name of the object you are - * waiting for (for Adapter or Device) - * @parameter identifier optionally specify the identifier of the object you are - * waiting for (UUID for GattService, GattCharacteristic or GattDescriptor, address - * for Adapter or Device) - * @parameter parent optionally specify the parent of the object you are - * waiting for - * @parameter timeoutMS the function will return after timeout time in milliseconds, a - * value of zero means wait forever. If object is not found during this time null will be returned. - * @return An object matching the name, identifier, parent or null if not found before - * timeout expires or event is canceled. - */ - public <T extends BTObject> T find(String name, String identifier, BTObject parent, long timeoutMS); - - /** Find a BluetoothObject of type T. If parameters name, identifier and - * parent are not null, the returned object will have to match them. - * It will first check for existing objects. It will not turn on discovery - * or connect to devices. - * @parameter name optionally specify the name of the object you are - * waiting for (for Adapter or Device) - * @parameter identifier optionally specify the identifier of the object you are - * waiting for (UUID for GattService, GattCharacteristic or GattDescriptor, address - * for Adapter or Device) - * @parameter parent optionally specify the parent of the object you are - * waiting for - * @return An object matching the name, identifier and parent. - */ - public <T extends BTObject> T find(String name, String identifier, BTObject parent); - - /** Return a BluetoothObject of a type matching type. If parameters name, - * identifier and parent are not null, the returned object will have to - * match them. Only objects which are already in the system will be returned. - * @parameter type specify the type of the object you are - * waiting for, NONE means anything. - * @parameter name optionally specify the name of the object you are - * waiting for (for Adapter or Device) - * @parameter identifier optionally specify the identifier of the object you are - * waiting for (UUID for GattService, GattCharacteristic or GattDescriptor, address - * for Adapter or Device) - * @parameter parent optionally specify the parent of the object you are - * waiting for - * @return An object matching the name, identifier, parent or null if not found. - */ - public BTObject getObject(BTType type, String name, - String identifier, BTObject parent); - - /** Return a List of BluetoothObject of a type matching type. If parameters name, - * identifier and parent are not null, the returned object will have to - * match them. Only objects which are already in the system will be returned. - * @parameter type specify the type of the object you are - * waiting for, NONE means anything. - * @parameter name optionally specify the name of the object you are - * waiting for (for Adapter or Device) - * @parameter identifier optionally specify the identifier of the object you are - * waiting for (UUID for GattService, GattCharacteristic or GattDescriptor, address - * for Adapter or Device) - * @parameter parent optionally specify the parent of the object you are - * waiting for - * @return A vector of object matching the name, identifier, parent. - */ - public List<BTObject> getObjects(BTType type, String name, - String identifier, BTObject parent); - /** Returns a list of BluetoothAdapters available in the system * @return A list of BluetoothAdapters available in the system */ @@ -235,7 +142,6 @@ public interface BTManager * </p> * @param dev_id the internal temporary adapter device id * @since 2.0.0 - * @implNote Not implemented on tinyb.dbus */ public BTAdapter getAdapter(final int dev_id); @@ -259,23 +165,13 @@ public interface BTManager /** * Gets the default adapter to use for discovery. * <p> - * {@code jau.direct_bt}: The default adapter is either the first {@link BTAdapter#isPowered() powered} {@link BTAdapter}, + * The default adapter is either the first {@link BTAdapter#isPowered() powered} {@link BTAdapter}, * or function returns nullptr if none is enabled. * </p> - * <p> - * <i>tinyb.dbus</i>: System default is the last detected adapter at initialization. - * </p> * @return the used default adapter */ public BTAdapter getDefaultAdapter(); - /** Turns on device discovery on the default adapter if it is disabled. - * @return TRUE if discovery was successfully enabled - * @deprecated since 2.0.0, use {@link #startDiscovery(boolean)}. - */ - @Deprecated - public boolean startDiscovery() throws BTException; - /** * Turns on device discovery on the default adapter if it is disabled. * @param keepAlive if {@code true}, indicates that discovery shall be restarted @@ -288,7 +184,6 @@ public interface BTManager * @throws BTException * @since 2.0.0 * @since 2.2.8 - * @implNote {@code keepAlive} not implemented in tinyb.dbus */ public HCIStatusCode startDiscovery(final boolean keepAlive, final boolean le_scan_active) throws BTException; @@ -300,10 +195,14 @@ public interface BTManager */ public HCIStatusCode stopDiscovery() throws BTException; - /** Returns if the discovers is running or not. - * @return TRUE if discovery is running - */ - public boolean getDiscovering() throws BTException; + /** + * Returns the current meta discovering {@link ScanType} of the {@link #getDefaultAdapter()} + * via {@link BTAdapter#getCurrentScanType()}. + * @see BTAdapter#getCurrentScanType() + * @see #getDefaultAdapter() + * @since 2.3 + */ + public ScanType getCurrentScanType(); /** * Add the given {@link ChangedAdapterSetListener} to this manager. @@ -316,7 +215,6 @@ public interface BTManager * allowing the user to perform complex operations. * </p> * @since 2.0.0 - * @implNote Not implemented on tinyb.dbus */ void addChangedAdapterSetListener(final ChangedAdapterSetListener l); @@ -325,7 +223,6 @@ public interface BTManager * @param l the to be removed element * @return the number of removed elements * @since 2.0.0 - * @implNote Not implemented on tinyb.dbus */ int removeChangedAdapterSetListener(final ChangedAdapterSetListener l); diff --git a/java/org/direct_bt/BTNotification.java b/java/org/direct_bt/BTNotification.java deleted file mode 100644 index 961008f7..00000000 --- a/java/org/direct_bt/BTNotification.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Author: Petre Eftime <[email protected]> - * Copyright (c) 2016 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.direct_bt; - -/** - * This interface is used by notifications. - * Implement a class inheriting BluetoothNotification and pass an object of that type - * to the enable*Notifications function. When a notification of that type is received, - * the run function of the class will be called. - */ -public interface BTNotification<T> { - public void run(T value); -} diff --git a/java/org/direct_bt/BTObject.java b/java/org/direct_bt/BTObject.java index 05821e48..2c44ad4a 100644 --- a/java/org/direct_bt/BTObject.java +++ b/java/org/direct_bt/BTObject.java @@ -27,18 +27,13 @@ */ package org.direct_bt; -public interface BTObject extends Cloneable, AutoCloseable +public interface BTObject extends AutoCloseable { /** Returns the BluetoothType of this object * @return The BluetoothType of this object */ public BTType getBluetoothType(); - /** Returns a clone of the BluetoothObject - * @return A clone of the BluetoothObject - */ - public BTObject clone(); - @Override public boolean equals(Object obj); diff --git a/java/org/direct_bt/GattCharPropertySet.java b/java/org/direct_bt/GattCharPropertySet.java new file mode 100644 index 00000000..df89ddb1 --- /dev/null +++ b/java/org/direct_bt/GattCharPropertySet.java @@ -0,0 +1,106 @@ +/** + * Author: Sven Gothel <[email protected]> + * Copyright (c) 2020 Gothel Software e.K. + * Copyright (c) 2020 ZAFENA AB + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +package org.direct_bt; + +/** + * Bit mask of GATT Characteristic Properties + * <pre> + * BT Core Spec v5.2: Vol 3, Part G GATT: 3.3.1.1 Characteristic Properties + * </pre> + * + * @since 2.3 + */ +public class GattCharPropertySet { + + /** + * BT Core Spec v5.2: Vol 3, Part G GATT: 3.3.1.1 Characteristic Properties + * + * @since 2.3 + */ + public enum Type { + NONE ( 0), + Broadcast (1 << 0), + Read (1 << 1), + WriteNoAck (1 << 2), + WriteWithAck (1 << 3), + Notify (1 << 4), + Indicate (1 << 5), + AuthSignedWrite (1 << 6), + ExtProps (1 << 7); + + Type(final int v) { value = (byte)v; } + public final byte value; + } + + public byte mask; + + public GattCharPropertySet(final byte v) { + mask = v; + } + + public boolean isSet(final Type bit) { return 0 != ( mask & bit.value ); } + public void set(final Type bit) { mask = (byte) ( mask | bit.value ); } + + @Override + public String toString() { + int count = 0; + final StringBuilder out = new StringBuilder(); + if( isSet(Type.Broadcast) ) { + out.append(Type.Broadcast.name()); count++; + } + if( isSet(Type.Read) ) { + out.append(Type.Read.name()); count++; + } + if( isSet(Type.WriteNoAck) ) { + if( 0 < count ) { out.append(", "); } + out.append(Type.WriteNoAck.name()); count++; + } + if( isSet(Type.WriteWithAck) ) { + if( 0 < count ) { out.append(", "); } + out.append(Type.WriteWithAck.name()); count++; + } + if( isSet(Type.Notify) ) { + if( 0 < count ) { out.append(", "); } + out.append(Type.Notify.name()); count++; + } + if( isSet(Type.Indicate) ) { + if( 0 < count ) { out.append(", "); } + out.append(Type.Indicate.name()); count++; + } + if( isSet(Type.AuthSignedWrite) ) { + if( 0 < count ) { out.append(", "); } + out.append(Type.AuthSignedWrite.name()); count++; + } + if( isSet(Type.ExtProps) ) { + if( 0 < count ) { out.append(", "); } + out.append(Type.ExtProps.name()); count++; + } + if( 1 < count ) { + out.insert(0, "["); + out.append("]"); + } + return out.toString(); + } +} diff --git a/java/org/direct_bt/ObjectArgCallback.java b/java/org/direct_bt/ObjectArgCallback.java deleted file mode 100644 index 36430f8a..00000000 --- a/java/org/direct_bt/ObjectArgCallback.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Author: Andrei Vasiliu <[email protected]> - * Copyright (c) 2016 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.direct_bt; - -import tinyb.dbus.DBusObject; - -public class ObjectArgCallback extends BTCallback -{ - @SuppressWarnings("unused") - private final Object callbackArg; - - public ObjectArgCallback(final DBusObject bObj, final Object callbackArg) - { - this.bObj = bObj; - this.callbackArg = callbackArg; - } - - @Override - public void run() - { - } -} diff --git a/java/org/direct_bt/ObjectArrayArgCallback.java b/java/org/direct_bt/ObjectArrayArgCallback.java deleted file mode 100644 index 8fb196b4..00000000 --- a/java/org/direct_bt/ObjectArrayArgCallback.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Author: Andrei Vasiliu <[email protected]> - * Copyright (c) 2016 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.direct_bt; - -import tinyb.dbus.DBusObject; - -public class ObjectArrayArgCallback extends BTCallback -{ - @SuppressWarnings("unused") - private final Object[] callbackArg; - - public ObjectArrayArgCallback(final DBusObject bObj, final Object[] callbackArg) - { - this.bObj = bObj; - this.callbackArg = callbackArg; - } - - @Override - public void run() - { - } -} diff --git a/java/org/direct_bt/TransportType.java b/java/org/direct_bt/TransportType.java deleted file mode 100644 index d97c28dd..00000000 --- a/java/org/direct_bt/TransportType.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.direct_bt; - -/** - * TransportType determines type of bluetooth scan. - */ -public enum TransportType { - /** - * interleaved scan - */ - AUTO, - /** - * BR/EDR inquiry - */ - BREDR, - /** - * LE scan only - */ - LE -} diff --git a/java/tinyb/dbus/DBusAdapter.java b/java/tinyb/dbus/DBusAdapter.java deleted file mode 100644 index 72b16712..00000000 --- a/java/tinyb/dbus/DBusAdapter.java +++ /dev/null @@ -1,301 +0,0 @@ -/** - * Author: Sven Gothel <[email protected]> - * Copyright (c) 2020 Gothel Software e.K. - * Copyright (c) 2020 ZAFENA AB - * - * Author: Andrei Vasiliu <[email protected]> - * Copyright (c) 2016 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package tinyb.dbus; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.UUID; - -import org.direct_bt.AdapterStatusListener; -import org.direct_bt.BDAddressAndType; -import org.direct_bt.BDAddressType; -import org.direct_bt.BTAdapter; -import org.direct_bt.BTDevice; -import org.direct_bt.BTException; -import org.direct_bt.BTManager; -import org.direct_bt.BTNotification; -import org.direct_bt.BTType; -import org.direct_bt.EUI48; -import org.direct_bt.HCIStatusCode; -import org.direct_bt.HCIWhitelistConnectType; -import org.direct_bt.ScanType; -import org.direct_bt.TransportType; - -public class DBusAdapter extends DBusObject implements BTAdapter -{ - @Override - public native BTType getBluetoothType(); - - @Override - public native BTAdapter clone(); - - static BTType class_type() { return BTType.ADAPTER; } - - @Override - public BTDevice find(final String name, final BDAddressAndType addressAndType, final long timeoutMS) { - final BTManager manager = DBusManager.getManager(); - return (BTDevice) manager.find(BTType.DEVICE, name, addressAndType.address.toString(), this, timeoutMS); - } - - @Override - public BTDevice find(final String name, final BDAddressAndType addressAndType) { - return find(name, addressAndType, 0); - } - - @Override - public boolean isPowered() { return isValid() && getPoweredState(); } - - @Override - public final boolean isSuspended() { return isValid() && !getPoweredState(); } - - @Override - public final boolean isValid() { return super.isValid(); } - - @Override - public boolean isDeviceWhitelisted(final BDAddressAndType addressAndType) { - return false; // FIXME - } - - @Override - public boolean addDeviceToWhitelist(final BDAddressAndType addressAndType, - final HCIWhitelistConnectType ctype, - final short min_interval, final short max_interval, - final short latency, final short timeout) { - return false; // FIXME - } - - @Override - public boolean addDeviceToWhitelist(final BDAddressAndType addressAndType, - final HCIWhitelistConnectType ctype) { - return false; // FIXME - } - - @Override - public boolean removeDeviceFromWhitelist(final BDAddressAndType addressAndType) { - return false; // FIXME - } - - @Override - public final BTManager getManager() { return DBusManager.getManager(); } - - /* D-Bus method calls: */ - - @Override - @Deprecated - public native boolean startDiscovery() throws BTException; - - @Override - public synchronized HCIStatusCode startDiscovery(final boolean keepAlive, final boolean le_scan_active) throws BTException { - return startDiscovery() ? HCIStatusCode.SUCCESS : HCIStatusCode.INTERNAL_FAILURE; // FIXME keepAlive, le_scan_active - } - @Override - public HCIStatusCode startDiscovery(final boolean keepAlive, final boolean le_scan_active, - final short le_scan_interval, final short le_scan_window, - final byte filter_policy) throws BTException { - return startDiscovery() ? HCIStatusCode.SUCCESS : HCIStatusCode.INTERNAL_FAILURE; // FIXME keepAlive, le_scan_active, ... - } - - @Override - public HCIStatusCode stopDiscovery() throws BTException { - return stopDiscoveryImpl() ? HCIStatusCode.SUCCESS : HCIStatusCode.INTERNAL_FAILURE; - } - private native boolean stopDiscoveryImpl() throws BTException; - - @Override - public native List<BTDevice> getDiscoveredDevices(); - - @Override - public native int removeDiscoveredDevices() throws BTException; - - @Override - public boolean removeDiscoveredDevice(final BDAddressAndType addressAndType) { - return false; // FIXME - } - - /* D-Bus property accessors: */ - - @Override - public native String getAddressString(); - - @Override - public EUI48 getAddress() { return new EUI48(getAddressString()); } - - @Override - public BDAddressAndType getAddressAndType() { return new BDAddressAndType(getAddress(), BDAddressType.BDADDR_LE_PUBLIC); } - - @Override - public BDAddressAndType getVisibleAddressAndType() { return getAddressAndType(); } - - @Override - public native String getName(); - - @Override - public int getDevID() { return 0; } // FIXME - - @Override - public native String getAlias(); - - @Override - public native void setAlias(String value); - - @Override - public native long getBluetoothClass(); - - @Override - public native boolean getPoweredState(); - - @Override - public native void enablePoweredNotifications(BTNotification<Boolean> callback); - - @Override - public native void disablePoweredNotifications(); - - @Override - public native boolean setPowered(boolean value); - - @Override - public final HCIStatusCode reset() { return HCIStatusCode.INTERNAL_FAILURE; } - - @Override - public native boolean getDiscoverable(); - - @Override - public native void enableDiscoverableNotifications(BTNotification<Boolean> callback); - - @Override - public native void disableDiscoverableNotifications(); - - @Override - public native boolean setDiscoverable(boolean value); - - @Override - public native long getDiscoverableTimeout(); - - @Override - public native boolean setDiscoverableTimout(long value); - - @Override - public BTDevice connectDevice(final BDAddressAndType addressAndType) { - return connectDeviceImpl(addressAndType.address.toString(), addressAndType.type.toDbusString()); - } - private native BTDevice connectDeviceImpl(String address, String addressType); - - @Override - public native boolean getPairable(); - - @Override - public native void enablePairableNotifications(BTNotification<Boolean> callback); - - @Override - public native void disablePairableNotifications(); - - @Override - public native boolean setPairable(boolean value); - - @Override - public native long getPairableTimeout(); - - @Override - public native boolean setPairableTimeout(long value); - - @Override - public final ScanType getCurrentScanType() { - return getDiscovering() ? ScanType.LE : ScanType.NONE; - } - @Override - public native boolean getDiscovering(); - - @Override - public boolean addStatusListener(final AdapterStatusListener l) { - return false; // FIXME - } - - @Override - public boolean removeStatusListener(final AdapterStatusListener l) { - return false; // FIXME - } - - @Override - public int removeAllStatusListener() { - return 0; // FIXME - } - - @Override - public native void enableDiscoveringNotifications(BTNotification<Boolean> callback); - - @Override - public native void disableDiscoveringNotifications(); - - @Override - public native String[] getUUIDs(); - - @Override - public native String getModalias(); - - @Override - public void setDiscoveryFilter(final List<UUID> uuids, final int rssi, final int pathloss, final TransportType transportType) { - final List<String> uuidsFmt = new ArrayList<>(uuids.size()); - for (final UUID uuid : uuids) { - uuidsFmt.add(uuid.toString()); - } - setDiscoveryFilter(uuidsFmt, rssi, pathloss, transportType.ordinal()); - } - - @SuppressWarnings("unchecked") - public void setRssiDiscoveryFilter(final int rssi) { - setDiscoveryFilter(Collections.EMPTY_LIST, rssi, 0, TransportType.AUTO); - } - - @Override - public String getInterfaceName() { - final String[] path = getObjectPath().split("/"); - return path[path.length-1]; - } - - private native void delete(); - - private native void setDiscoveryFilter(List<String> uuids, int rssi, int pathloss, int transportType); - - private DBusAdapter(final long instance) - { - super(instance); - } - - @Override - public String toString() { - return "Adapter["+getAddress()+", '"+getName()+"']"; - } - - @Override - public final void printDeviceLists() { - // FIXME - } -} diff --git a/java/tinyb/dbus/DBusBluetoothException.java b/java/tinyb/dbus/DBusBluetoothException.java deleted file mode 100644 index b2630dfd..00000000 --- a/java/tinyb/dbus/DBusBluetoothException.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Author: Sven Gothel <[email protected]> - * Copyright (c) 2020 Gothel Software e.K. - * Copyright (c) 2020 ZAFENA AB - * - * Author: Petre Eftime <[email protected]> - * Copyright (c) 2016 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package tinyb.dbus; - -import org.direct_bt.BTException; - -@SuppressWarnings("serial") -public class DBusBluetoothException extends BTException { - DBusBluetoothException(final String msg) { - super(msg); - } -} diff --git a/java/tinyb/dbus/DBusDevice.java b/java/tinyb/dbus/DBusDevice.java deleted file mode 100644 index 3241788d..00000000 --- a/java/tinyb/dbus/DBusDevice.java +++ /dev/null @@ -1,352 +0,0 @@ -/** - * Author: Sven Gothel <[email protected]> - * Copyright (c) 2020 Gothel Software e.K. - * Copyright (c) 2020 ZAFENA AB - * - * Author: Andrei Vasiliu <[email protected]> - * Copyright (c) 2016 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package tinyb.dbus; - -import java.util.List; -import java.util.Map; - -import org.direct_bt.AdapterStatusListener; -import org.direct_bt.BDAddressAndType; -import org.direct_bt.BDAddressType; -import org.direct_bt.BTSecurityLevel; -import org.direct_bt.BTDevice; -import org.direct_bt.BTException; -import org.direct_bt.BTGattChar; -import org.direct_bt.BTGattService; -import org.direct_bt.BTManager; -import org.direct_bt.BTNotification; -import org.direct_bt.BTType; -import org.direct_bt.BTUtils; -import org.direct_bt.EUI48; -import org.direct_bt.BTGattCharListener; -import org.direct_bt.HCIStatusCode; -import org.direct_bt.PairingMode; -import org.direct_bt.SMPIOCapability; -import org.direct_bt.SMPKeyMask; -import org.direct_bt.SMPLongTermKeyInfo; -import org.direct_bt.SMPPairingState; -import org.direct_bt.SMPSignatureResolvingKeyInfo; - -public class DBusDevice extends DBusObject implements BTDevice -{ - @Override - public final long getCreationTimestamp() { return ts_creation; } - - @Override - public final long getLastDiscoveryTimestamp() { return ts_creation; } // FIXME - - @Override - public final long getLastUpdateTimestamp() { return ts_creation; } // FIXME - - @Override - public native BTType getBluetoothType(); - @Override - public native DBusDevice clone(); - - static BTType class_type() { return BTType.DEVICE; } - - @Override - public BTGattService find(final String UUID, final long timeoutMS) { - final BTManager manager = DBusManager.getManager(); - return (BTGattService) manager.find(BTType.GATT_SERVICE, - null, UUID, this, timeoutMS); - } - - @Override - public BTGattService find(final String UUID) { - return find(UUID, 0); - } - - /* D-Bus method calls: */ - - @Override - public final boolean addStatusListener(final AdapterStatusListener l) { - return false; // FIXME - } - - @Override - public boolean removeStatusListener(final AdapterStatusListener l) { - return false; // FIXME - } - - @Override - public final HCIStatusCode disconnect() throws BTException { - return disconnectImpl() ? HCIStatusCode.SUCCESS : HCIStatusCode.UNSPECIFIED_ERROR ; - } - private native boolean disconnectImpl() throws BTException; - - - @Override - public final HCIStatusCode connect() throws BTException { - return connectImpl() ? HCIStatusCode.SUCCESS : HCIStatusCode.UNSPECIFIED_ERROR ; - } - private native boolean connectImpl() throws BTException; - - @Override - public HCIStatusCode connectLE(final short interval, final short window, - final short min_interval, final short max_interval, - final short latency, final short timeout) { - return connect(); // FIXME connection params ... - } - - @Override - public native boolean connectProfile(String arg_UUID) throws BTException; - - @Override - public native boolean disconnectProfile(String arg_UUID) throws BTException; - - @Override - public final SMPKeyMask getAvailableSMPKeys(final boolean responder) { return new SMPKeyMask(); } - - @Override - public final SMPLongTermKeyInfo getLongTermKeyInfo(final boolean responder) { return new SMPLongTermKeyInfo(); } // FIXME - - @Override - public final HCIStatusCode setLongTermKeyInfo(final SMPLongTermKeyInfo ltk) { return HCIStatusCode.NOT_SUPPORTED; } // FIXME - - @Override - public final SMPSignatureResolvingKeyInfo getSignatureResolvingKeyInfo(final boolean responder) { return new SMPSignatureResolvingKeyInfo(); } // FIXME - - @Override - public native boolean pair() throws BTException; - - @Override - public final HCIStatusCode unpair() { return HCIStatusCode.NOT_SUPPORTED; } // FIXME - - @Override - public final boolean setConnSecurityLevel(final BTSecurityLevel sec_level) { return false; } // FIXME - - @Override - public final BTSecurityLevel getConnSecurityLevel() { return BTSecurityLevel.UNSET; } // FIXME - - @Override - public final boolean setConnIOCapability(final SMPIOCapability io_cap) { return false; } // FIXME - - @Override - public final SMPIOCapability getConnIOCapability() { return SMPIOCapability.UNSET; } // FIXME - - @Override - public final boolean setConnSecurity(final BTSecurityLevel sec_level, final SMPIOCapability io_cap) { return false; } // FIXME - - @Override - public final boolean setConnSecurityBest(final BTSecurityLevel sec_level, final SMPIOCapability io_cap) { return false; } // FIXME - - @Override - public final boolean setConnSecurityAuto(final SMPIOCapability iocap_auto) { return false; } // FIXME - - @Override - public final boolean isConnSecurityAutoEnabled() { return false; } // FIXME - - @Override - public HCIStatusCode setPairingPasskey(final int passkey) { return HCIStatusCode.INTERNAL_FAILURE; } - - @Override - public HCIStatusCode setPairingPasskeyNegative() { return HCIStatusCode.INTERNAL_FAILURE; } - - @Override - public HCIStatusCode setPairingNumericComparison(final boolean equal) { return HCIStatusCode.INTERNAL_FAILURE; } - - @Override - public PairingMode getPairingMode() { return PairingMode.NONE; } - - @Override - public SMPPairingState getPairingState() { return SMPPairingState.NONE; } - - @Override - public native boolean remove() throws BTException; - - @Override - public final boolean isValid() { return super.isValid(); } - - @Override - public native boolean cancelPairing() throws BTException; - - @Override - public native List<BTGattService> getServices(); - - @Override - public boolean pingGATT() { return true; } // FIXME - - /* D-Bus property accessors: */ - - @Override - public BDAddressAndType getAddressAndType() { return new BDAddressAndType(new EUI48(getAddressString()), BDAddressType.BDADDR_LE_PUBLIC /* FIXME */); } - - @Override - public native String getAddressString(); - - @Override - public native String getName(); - - @Override - public native String getAlias(); - - @Override - public native void setAlias(String value); - - @Override - public native int getBluetoothClass(); - - @Override - public native short getAppearance(); - - @Override - public native String getIcon(); - - @Override - public native boolean getPaired(); - - @Override - public native void enablePairedNotifications(BTNotification<Boolean> callback); - - @Override - public native void disablePairedNotifications(); - - @Override - public native boolean getTrusted(); - - @Override - public native void enableTrustedNotifications(BTNotification<Boolean> callback); - - @Override - public native void disableTrustedNotifications(); - - @Override - public native void setTrusted(boolean value); - - @Override - public native boolean getBlocked(); - - @Override - public native void enableBlockedNotifications(BTNotification<Boolean> callback); - - @Override - public native void disableBlockedNotifications(); - - @Override - public native void setBlocked(boolean value); - - @Override - public native boolean getLegacyPairing(); - - @Override - public native short getRSSI(); - - @Override - public native void enableRSSINotifications(BTNotification<Short> callback); - - @Override - public native void disableRSSINotifications(); - - @Override - public native boolean getConnected(); - - @Override - public final short getConnectionHandle() { return 0; /* FIXME */ } - - @Override - public native void enableConnectedNotifications(BTNotification<Boolean> callback); - - @Override - public native void disableConnectedNotifications(); - - @Override - public native String[] getUUIDs(); - - @Override - public native String getModalias(); - - @Override - public native DBusAdapter getAdapter(); - - @Override - public native Map<Short, byte[]> getManufacturerData(); - - @Override - public native void enableManufacturerDataNotifications(BTNotification<Map<Short, byte[]> > callback); - - @Override - public native void disableManufacturerDataNotifications(); - - - @Override - public native Map<String, byte[]> getServiceData(); - - @Override - public native void enableServiceDataNotifications(BTNotification<Map<String, byte[]> > callback); - - @Override - public native void disableServiceDataNotifications(); - - @Override - public native short getTxPower (); - - @Override - public native boolean getServicesResolved (); - - @Override - public native void enableServicesResolvedNotifications(BTNotification<Boolean> callback); - - @Override - public native void disableServicesResolvedNotifications(); - - @Override - public boolean addCharListener(final BTGattCharListener listener) { - return false; // FIXME - } - - @Override - public boolean removeCharListener(final BTGattCharListener l) { - return false; // FIXME - } - - @Override - public int removeAllAssociatedCharListener(final BTGattChar associatedCharacteristic) { - return 0; // FIXME - } - - @Override - public int removeAllCharListener() { - return 0; // FIXME - } - - private native void delete(); - - private DBusDevice(final long instance) - { - super(instance); - ts_creation = BTUtils.currentTimeMillis(); - } - final long ts_creation; - - @Override - public String toString() { - return "Device[address"+getAddressAndType()+", '"+getName()+"']"; - } -} diff --git a/java/tinyb/dbus/DBusEvent.java b/java/tinyb/dbus/DBusEvent.java deleted file mode 100644 index ddc080bc..00000000 --- a/java/tinyb/dbus/DBusEvent.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Author: Andrei Vasiliu <[email protected]> - * Copyright (c) 2016 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package tinyb.dbus; - -import org.direct_bt.BTCallback; -import org.direct_bt.BTEvent; -import org.direct_bt.BTType; - -public class DBusEvent implements BTEvent -{ - private long nativeInstance; - - @Override - public native BTType getType(); - @Override - public native String getName(); - @Override - public native String getIdentifier(); - @Override - public native boolean executeCallback(); - @Override - public native boolean hasCallback(); - - private native void init(BTType type, String name, String identifier, - DBusObject parent, BTCallback cb, Object data); - private native void delete(); - - public DBusEvent(final BTType type, final String name, final String identifier, - final DBusObject parent, final BTCallback cb, final Object data) - { - init(type, name, identifier, parent, cb, data); - } - - @Override - protected void finalize() - { - delete(); - } -} diff --git a/java/tinyb/dbus/DBusGattCharacteristic.java b/java/tinyb/dbus/DBusGattCharacteristic.java deleted file mode 100644 index d37e1713..00000000 --- a/java/tinyb/dbus/DBusGattCharacteristic.java +++ /dev/null @@ -1,142 +0,0 @@ -/** - * Author: Sven Gothel <[email protected]> - * Copyright (c) 2020 Gothel Software e.K. - * Copyright (c) 2020 ZAFENA AB - * - * Author: Andrei Vasiliu <[email protected]> - * Copyright (c) 2016 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package tinyb.dbus; - -import java.util.List; - -import org.direct_bt.BTException; -import org.direct_bt.BTGattChar; -import org.direct_bt.BTGattDesc; -import org.direct_bt.BTGattService; -import org.direct_bt.BTManager; -import org.direct_bt.BTNotification; -import org.direct_bt.BTType; - -public class DBusGattCharacteristic extends DBusObject implements BTGattChar -{ - @Override - public native BTType getBluetoothType(); - @Override - public native DBusGattCharacteristic clone(); - - static BTType class_type() { return BTType.GATT_CHARACTERISTIC; } - - @Override - public BTGattDesc find(final String UUID, final long timeoutMS) { - final BTManager manager = DBusManager.getManager(); - return (BTGattDesc) manager.find(BTType.GATT_DESCRIPTOR, - null, UUID, this, timeoutMS); - } - - @Override - public BTGattDesc find(final String UUID) { - return find(UUID, 0); - } - - /* D-Bus method calls: */ - - @Override - public native byte[] readValue() throws BTException; - - @Override - public native void enableValueNotifications(BTNotification<byte[]> callback); - - @Override - public native void disableValueNotifications(); - - @Override - public boolean writeValue(final byte[] argValue, final boolean withResponse) throws BTException { - if( withResponse ) { - throw new DBusBluetoothException("writeValue with response not yet supported"); - } - return writeValueImpl(argValue); - } - private native boolean writeValueImpl(byte[] argValue) throws BTException; - - /* D-Bus property accessors: */ - - @Override - public native String getUUID(); - - @Override - public native BTGattService getService(); - - @Override - public native byte[] getValue(); - - @Override - public native boolean getNotifying(); - - @Override - public native String[] getFlags(); - - @Override - public native List<BTGattDesc> getDescriptors(); - - private native void init(DBusGattCharacteristic obj); - - private native void delete(); - - private DBusGattCharacteristic(final long instance) - { - super(instance); - } - - @Override - public boolean addCharListener(final Listener listener) { - return false; // FIXME - } - @Override - public boolean configNotificationIndication(final boolean enableNotification, final boolean enableIndication, final boolean[] enabledState) - throws IllegalStateException - { - return false; // FIXME - } - @Override - public boolean enableNotificationOrIndication(final boolean[] enabledState) - throws IllegalStateException - { - return false; // FIXME - } - @Override - public boolean addCharListener(final Listener listener, final boolean[] enabledState) - throws IllegalStateException - { - return false; // FIXME - } - @Override - public int removeAllAssociatedCharListener(final boolean disableIndicationNotification) { - return 0; // FIXME - } - - @Override - public String toString() { - return "Characteristic[uuid "+getUUID()+"]"; - } -} diff --git a/java/tinyb/dbus/DBusGattDescriptor.java b/java/tinyb/dbus/DBusGattDescriptor.java deleted file mode 100644 index f1741dba..00000000 --- a/java/tinyb/dbus/DBusGattDescriptor.java +++ /dev/null @@ -1,81 +0,0 @@ -/** - * Author: Sven Gothel <[email protected]> - * Copyright (c) 2020 Gothel Software e.K. - * Copyright (c) 2020 ZAFENA AB - * - * Author: Andrei Vasiliu <[email protected]> - * Copyright (c) 2016 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package tinyb.dbus; - -import org.direct_bt.BTException; -import org.direct_bt.BTGattDesc; -import org.direct_bt.BTNotification; -import org.direct_bt.BTType; - -public class DBusGattDescriptor extends DBusObject implements BTGattDesc -{ - @Override - public native BTType getBluetoothType(); - @Override - public native BTGattDesc clone(); - - static BTType class_type() { return BTType.GATT_DESCRIPTOR; } - - /* D-Bus method calls: */ - - @Override - public native byte[] readValue(); - - @Override - public native boolean writeValue(byte[] argValue) throws BTException; - - @Override - public native void enableValueNotifications(BTNotification<byte[]> callback); - - @Override - public native void disableValueNotifications(); - - /* D-Bus property accessors: */ - - @Override - public native String getUUID(); - - @Override - public native DBusGattCharacteristic getCharacteristic(); - - @Override - public native byte[] getValue(); - - private native void delete(); - - private DBusGattDescriptor(final long instance) - { - super(instance); - } - - @Override - public String toString() { - return "Descriptor[uuid "+getUUID()+"]"; - } -} diff --git a/java/tinyb/dbus/DBusGattService.java b/java/tinyb/dbus/DBusGattService.java deleted file mode 100644 index feb24e65..00000000 --- a/java/tinyb/dbus/DBusGattService.java +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Author: Sven Gothel <[email protected]> - * Copyright (c) 2020 Gothel Software e.K. - * Copyright (c) 2020 ZAFENA AB - * - * Author: Andrei Vasiliu <[email protected]> - * Copyright (c) 2016 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package tinyb.dbus; - -import java.util.List; - -import org.direct_bt.BTGattChar; -import org.direct_bt.BTGattService; -import org.direct_bt.BTManager; -import org.direct_bt.BTType; - -public class DBusGattService extends DBusObject implements BTGattService -{ - @Override - public native BTType getBluetoothType(); - - @Override - public native BTGattService clone(); - - static BTType class_type() { return BTType.GATT_SERVICE; } - - @Override - public BTGattChar find(final String UUID, final long timeoutMS) { - final BTManager manager = DBusManager.getManager(); - return (DBusGattCharacteristic) manager.find(BTType.GATT_CHARACTERISTIC, - null, UUID, this, timeoutMS); - } - - @Override - public BTGattChar find(final String UUID) { - return find(UUID, 0); - } - - /* D-Bus property accessors: */ - - @Override - public native String getUUID(); - - @Override - public native DBusDevice getDevice(); - - @Override - public native boolean getPrimary(); - - @Override - public native List<BTGattChar> getChars(); - - private native void delete(); - - private DBusGattService(final long instance) - { - super(instance); - } - - @Override - public String toString() { - return "Service[uuid "+getUUID()+"]"; - } -} diff --git a/java/tinyb/dbus/DBusManager.java b/java/tinyb/dbus/DBusManager.java deleted file mode 100644 index b8057cae..00000000 --- a/java/tinyb/dbus/DBusManager.java +++ /dev/null @@ -1,183 +0,0 @@ -/** - * Author: Sven Gothel <[email protected]> - * Copyright (c) 2020 Gothel Software e.K. - * Copyright (c) 2020 ZAFENA AB - * - * Author: Andrei Vasiliu <[email protected]> - * Copyright (c) 2016 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package tinyb.dbus; - -import java.util.List; - -import org.direct_bt.BTAdapter; -import org.direct_bt.BTDevice; -import org.direct_bt.BTException; -import org.direct_bt.BTGattService; -import org.direct_bt.BTManager; -import org.direct_bt.BTObject; -import org.direct_bt.BTType; -import org.direct_bt.HCIStatusCode; -import org.direct_bt.BTManager.ChangedAdapterSetListener; - -public class DBusManager implements BTManager -{ - private long nativeInstance; - private final Settings settings; - - private native static String getNativeAPIVersion(); - - public native BTType getBluetoothType(); - - private native DBusObject find(int type, String name, String identifier, BTObject parent, long milliseconds); - - @Override - public final Settings getSettings() { - return settings; - } - - @Override - public DBusObject find(final BTType type, final String name, final String identifier, final BTObject parent, final long timeoutMS) { - return find(type.ordinal(), name, identifier, parent, timeoutMS); - } - - @Override - public DBusObject find(final BTType type, final String name, final String identifier, final BTObject parent) { - return find(type, name, identifier, parent, 0); - } - - @SuppressWarnings("unchecked") - @Override - public <T extends BTObject> T find(final String name, final String identifier, final BTObject parent, final long timeoutMS) { - return (T) find(DBusObject.class_type().ordinal(), name, identifier, parent, timeoutMS); - } - - @SuppressWarnings("unchecked") - @Override - public <T extends BTObject> T find(final String name, final String identifier, final BTObject parent) { - return (T) find(name, identifier, parent, 0); - } - - @Override - public BTObject getObject(final BTType type, final String name, - final String identifier, final BTObject parent) { - return getObject(type.ordinal(), name, identifier, parent); - } - private native BTObject getObject(int type, String name, String identifier, BTObject parent); - - @Override - public List<BTObject> getObjects(final BTType type, final String name, - final String identifier, final BTObject parent) { - return getObjects(type.ordinal(), name, identifier, parent); - } - private native List<BTObject> getObjects(int type, String name, String identifier, BTObject parent); - - @Override - public native List<BTAdapter> getAdapters(); - - @Override - public BTAdapter getAdapter(final int dev_id) { return null; } // FIXME - - @Override - public native List<BTDevice> getDevices(); - - @Override - public native List<BTGattService> getServices(); - - @Override - public native boolean setDefaultAdapter(BTAdapter adapter); - - @Override - public native BTAdapter getDefaultAdapter(); - - @Override - public native boolean startDiscovery() throws BTException; - - @Override - public HCIStatusCode startDiscovery(final boolean keepAlive, final boolean le_scan_active) throws BTException { - return startDiscovery() ? HCIStatusCode.SUCCESS : HCIStatusCode.INTERNAL_FAILURE; // FIXME keepAlive, le_scan_active - } - - @Override - public HCIStatusCode stopDiscovery() throws BTException { - return stopDiscoveryImpl() ? HCIStatusCode.SUCCESS : HCIStatusCode.INTERNAL_FAILURE; - } - private native boolean stopDiscoveryImpl() throws BTException; - - @Override - public native boolean getDiscovering() throws BTException; - - private native void init() throws BTException; - private native void delete(); - private DBusManager() - { - init(); - settings = new Settings() { - @Override - public final boolean isDirectBT() { - return false; - } - @Override - public boolean isTinyB() { - return true; - } - @Override - public boolean isCharValueCacheNotificationSupported() { - return true; - } - @Override - public String toString() { - return "Settings[dbt false, tinyb true, charValueCacheNotify "+isCharValueCacheNotificationSupported()+"]"; - } - }; - System.err.println("DBusManager: Using "+settings.toString()); - } - - /** Returns an instance of BluetoothManager, to be used instead of constructor. - * @return An initialized BluetoothManager instance. - */ - public static synchronized BTManager getManager() throws RuntimeException, BTException { - return LazySingletonHolder.singleton; - } - /** Initialize-On-Demand Holder Class, similar to C++11's "Magic Statics". */ - private static class LazySingletonHolder { - private static final DBusManager singleton = new DBusManager(); - } - - @Override - protected void finalize() - { - delete(); - } - - @Override - public void shutdown() { - delete(); - } - - @Override - public final void addChangedAdapterSetListener(final ChangedAdapterSetListener l) {} // FIXME - - @Override - public final int removeChangedAdapterSetListener(final ChangedAdapterSetListener l) { return 0; } // FIXME -} diff --git a/java/tinyb/dbus/DBusObject.java b/java/tinyb/dbus/DBusObject.java deleted file mode 100644 index f28ba858..00000000 --- a/java/tinyb/dbus/DBusObject.java +++ /dev/null @@ -1,92 +0,0 @@ -/** - * Author: Sven Gothel <[email protected]> - * Copyright (c) 2020 Gothel Software e.K. - * Copyright (c) 2020 ZAFENA AB - * - * Author: Andrei Vasiliu <[email protected]> - * Copyright (c) 2016 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package tinyb.dbus; - -import org.direct_bt.BTFactory; -import org.direct_bt.BTObject; -import org.direct_bt.BTType; - -public class DBusObject implements BTObject -{ - protected long nativeInstance; - private boolean isValid; - - static { - BTFactory.checkInitialized(); - } - - static BTType class_type() { return BTType.NONE; } - - @Override - public native BTType getBluetoothType(); - - @Override - public native BTObject clone(); - - private native void delete(); - private native boolean operatorEqual(DBusObject obj); - - protected DBusObject(final long instance) - { - nativeInstance = instance; - isValid = true; - } - - @Override - protected void finalize() - { - close(); - } - - @Override - public boolean equals(final Object obj) - { - if (obj == null || !(obj instanceof DBusObject)) - return false; - return operatorEqual((DBusObject)obj); - } - - protected native String getObjectPath(); - - @Override - public int hashCode() { - final String objectPath = getObjectPath(); - return objectPath.hashCode(); - } - - protected synchronized boolean isValid() { return isValid; } - - @Override - public synchronized void close() { - if (!isValid) - return; - isValid = false; - delete(); - } -} diff --git a/java_fat/CMakeLists.txt b/java_fat/CMakeLists.txt index f29b6b09..c09c97b2 100644 --- a/java_fat/CMakeLists.txt +++ b/java_fat/CMakeLists.txt @@ -11,10 +11,9 @@ # set(direct_bt_jar_file ${CMAKE_CURRENT_BINARY_DIR}/direct_bt.jar CACHE FILEPATH "direct_bt jar file" FORCE) set(direct_bt_fat_jar_file ${CMAKE_CURRENT_BINARY_DIR}/direct_bt-fat.jar CACHE FILEPATH "direct_bt fat jar file" FORCE) -set(direct_bt_fat2_jar_file ${CMAKE_CURRENT_BINARY_DIR}/direct_bt-fat2.jar CACHE FILEPATH "direct_bt fat2 jar file" FORCE) set(direct_bt_java_src_file ${CMAKE_CURRENT_BINARY_DIR}/direct_bt-java-src.zip CACHE FILEPATH "direct_bt java source file" FORCE) -add_custom_command (OUTPUT ${direct_bt_fat_jar_file} ${direct_bt_fat2_jar_file} ${direct_bt_java_src_file} +add_custom_command (OUTPUT ${direct_bt_fat_jar_file} ${direct_bt_java_src_file} WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} COMMAND ${CMAKE_COMMAND} -D_srcdir=${CMAKE_CURRENT_BINARY_DIR}/../src/direct_bt @@ -32,28 +31,7 @@ add_custom_command (OUTPUT ${direct_bt_fat_jar_file} ${direct_bt_fat2_jar_file} -D _dstdir:PATH='${CMAKE_CURRENT_BINARY_DIR}/temp' -D _archives:FILEPATH="${jaulib_fat_jar_file}" -P ${CMAKE_CURRENT_SOURCE_DIR}/../cmake/modules/ExtractArchiveList.cmake - COMMAND ${JAR} - --create --file ${direct_bt_fat2_jar_file} - --manifest ${CMAKE_CURRENT_BINARY_DIR}/manifest-fat2.txt - -C ${CMAKE_CURRENT_BINARY_DIR}/temp/ jau - -C ${CMAKE_CURRENT_BINARY_DIR}/temp/ org - -C ${CMAKE_CURRENT_BINARY_DIR}/temp/ natives - -C ${CMAKE_CURRENT_BINARY_DIR}/../java/${CMAKE_FILES_DIRECTORY}/direct_bt_jar.dir/ jau - -C ${CMAKE_CURRENT_BINARY_DIR}/../java/${CMAKE_FILES_DIRECTORY}/direct_bt_jar.dir/ org - -C ${CMAKE_CURRENT_BINARY_DIR}/ natives - COMMAND ${CMAKE_COMMAND} - -D_srcdir=${CMAKE_CURRENT_BINARY_DIR}/../src/tinyb - -D_dstdir=${CMAKE_CURRENT_BINARY_DIR}/natives/${OS_AND_ARCH} - -D_srcbasename=${CMAKE_SHARED_LIBRARY_PREFIX}tinyb${CMAKE_SHARED_LIBRARY_SUFFIX}.${tinyb_VERSION_STRING} - -D_dstbasename=${CMAKE_SHARED_LIBRARY_PREFIX}tinyb${CMAKE_SHARED_LIBRARY_SUFFIX} - -P ${CMAKE_CURRENT_SOURCE_DIR}/../cmake/modules/FileCopyS2D.cmake - COMMAND ${CMAKE_COMMAND} - -D_srcdir=${CMAKE_CURRENT_BINARY_DIR}/../java/jni/tinyb - -D_dstdir=${CMAKE_CURRENT_BINARY_DIR}/natives/${OS_AND_ARCH} - -D_srcbasename=${CMAKE_SHARED_LIBRARY_PREFIX}javatinyb${CMAKE_SHARED_LIBRARY_SUFFIX}.${tinyb_VERSION_STRING} - -D_dstbasename=${CMAKE_SHARED_LIBRARY_PREFIX}javatinyb${CMAKE_SHARED_LIBRARY_SUFFIX} - -P ${CMAKE_CURRENT_SOURCE_DIR}/../cmake/modules/FileCopyS2D.cmake COMMAND ${JAR} --create --file ${direct_bt_fat_jar_file} --manifest ${CMAKE_CURRENT_BINARY_DIR}/manifest-fat.txt @@ -62,7 +40,6 @@ add_custom_command (OUTPUT ${direct_bt_fat_jar_file} ${direct_bt_fat2_jar_file} -C ${CMAKE_CURRENT_BINARY_DIR}/temp/ natives -C ${CMAKE_CURRENT_BINARY_DIR}/../java/${CMAKE_FILES_DIRECTORY}/direct_bt_jar.dir/ jau -C ${CMAKE_CURRENT_BINARY_DIR}/../java/${CMAKE_FILES_DIRECTORY}/direct_bt_jar.dir/ org - -C ${CMAKE_CURRENT_BINARY_DIR}/../java/${CMAKE_FILES_DIRECTORY}/direct_bt_jar.dir/ tinyb -C ${CMAKE_CURRENT_BINARY_DIR}/ natives COMMAND ${JAR} @@ -70,18 +47,17 @@ add_custom_command (OUTPUT ${direct_bt_fat_jar_file} ${direct_bt_fat2_jar_file} --no-manifest -C ${CMAKE_CURRENT_SOURCE_DIR}/../java jau -C ${CMAKE_CURRENT_SOURCE_DIR}/../java org - -C ${CMAKE_CURRENT_SOURCE_DIR}/../java tinyb - DEPENDS jaulib_fat_jar direct_bt tinyb direct_bt_jar javadirect_bt javatinyb + DEPENDS jaulib_fat_jar direct_bt direct_bt_jar javadirect_bt COMMENT "producing direct_bt [fat] jar files and its java source zip" VERBATIM ) add_custom_target (direct_bt_fat_jar ALL - DEPENDS ${direct_bt_fat_jar_file} ${direct_bt_fat2_jar_file} ${direct_bt_java_src_file} + DEPENDS ${direct_bt_fat_jar_file} ${direct_bt_java_src_file} ) -add_dependencies(direct_bt_fat_jar jaulib_fat_jar direct_bt tinyb direct_bt_jar javadirect_bt javatinyb) +add_dependencies(direct_bt_fat_jar jaulib_fat_jar direct_bt direct_bt_jar javadirect_bt) -install (FILES ${direct_bt_fat_jar_file} ${direct_bt_fat2_jar_file} ${direct_bt_java_src_file} DESTINATION ${CMAKE_INSTALL_LIBDIR}/../lib/java) +install (FILES ${direct_bt_fat_jar_file} ${direct_bt_java_src_file} DESTINATION ${CMAKE_INSTALL_LIBDIR}/../lib/java) diff --git a/java_fat/manifest-fat.txt.in b/java_fat/manifest-fat.txt.in index 2293195b..5ec719ed 100644 --- a/java_fat/manifest-fat.txt.in +++ b/java_fat/manifest-fat.txt.in @@ -12,7 +12,7 @@ Package-Version: @VERSION_SHORT@ Specification-Title: Direct-BT Jaulib Fat Specification-Vendor: Gothel Software Specification-Version: @VERSION_API@ -Implementation-Title: Direct-BT Jaulib Fat (w/ TinyB) +Implementation-Title: Direct-BT Jaulib Fat Implementation-Vendor: Gothel Software Implementation-Version: @VERSION@ Implementation-Commit: @VERSION_SHA1@ @@ -38,9 +38,6 @@ Sealed: true Name: org/direct_bt/ Sealed: true -Name: tinyb/dbus/ -Sealed: true - Name: jau/direct_bt/ Sealed: true diff --git a/java_fat/manifest-fat2.txt.in b/java_fat/manifest-fat2.txt.in deleted file mode 100644 index 70ba4dc2..00000000 --- a/java_fat/manifest-fat2.txt.in +++ /dev/null @@ -1,43 +0,0 @@ -Manifest-Version: 1.0 -Bundle-Date: @BUILD_TSTAMP@ -Bundle-ManifestVersion: 2 -Bundle-Name: org.direct_bt -Bundle-SymbolicName: org.direct_bt -Bundle-Version: @VERSION_SHORT@ -Export-Package: org.direct_bt -Require-Capability: osgi.ee;filter:="(&(osgi.ee=JavaSE)(version=1.9))" -Package-Title: org.direct_bt -Package-Vendor: Gothel Software -Package-Version: @VERSION_SHORT@ -Specification-Title: Direct-BT Jaulib Fat -Specification-Vendor: Gothel Software -Specification-Version: @VERSION_API@ -Implementation-Title: Direct-BT Jaulib Fat (ex TinyB) -Implementation-Vendor: Gothel Software -Implementation-Version: @VERSION@ -Implementation-Commit: @VERSION_SHA1@ -Implementation-URL: http://www.jausoft.com/ -Extension-Name: org.direct_bt -Trusted-Library: true -Permissions: all-permissions -Application-Library-Allowable-Codebase: * -Main-Class: org.direct_bt.BTFactory - -Name: org/jau -Sealed: true - -Name: jau/util -Sealed: true - -Name: jau/sys -Sealed: true - -Name: jau/pkg -Sealed: true - -Name: org/direct_bt/ -Sealed: true - -Name: jau/direct_bt/ -Sealed: true - diff --git a/scripts/build.sh b/scripts/build.sh index 6d77c211..6468ffe1 100644 --- a/scripts/build.sh +++ b/scripts/build.sh @@ -43,7 +43,6 @@ buildit() { # cmake $CLANG_ARGS -DCMAKE_INSTALL_PREFIX=$rootdir/dist-$archabi -DBUILDJAVA=ON -DBUILDEXAMPLES=ON -DBUILD_TESTING=ON -DDEBUG=ON -DINSTRUMENTATION=ON .. # cmake $CLANG_ARGS -DCMAKE_INSTALL_PREFIX=$rootdir/dist-$archabi -DBUILDJAVA=ON -DBUILDEXAMPLES=ON -DBUILD_TESTING=ON -DDEBUG=ON -DINSTRUMENTATION_UNDEFINED=ON .. # cmake $CLANG_ARGS -DCMAKE_INSTALL_PREFIX=$rootdir/dist-$archabi -DBUILDJAVA=ON -DBUILDEXAMPLES=ON -DBUILD_TESTING=ON -DDEBUG=ON -DINSTRUMENTATION_THREAD=ON .. - # cmake $CLANG_ARGS -DCMAKE_INSTALL_PREFIX=$rootdir/dist-$archabi -DBUILDJAVA=ON -DBUILDEXAMPLES=ON -DBUILD_TESTING=ON -DSKIP_TINYB=ON .. make -j $CPU_COUNT install test if [ $? -eq 0 ] ; then echo "BUILD SUCCESS $bname $archabi" diff --git a/src/tinyb/BluetoothAdapter.cpp b/src/tinyb/BluetoothAdapter.cpp deleted file mode 100644 index c8ea3fbd..00000000 --- a/src/tinyb/BluetoothAdapter.cpp +++ /dev/null @@ -1,461 +0,0 @@ -/* - * Author: Petre Eftime <[email protected]> - * Copyright (c) 2015 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#include "orgbluez-dbus.h" -#include "tinyb_utils.hpp" -#include "BluetoothNotificationHandler.hpp" -#include "BluetoothAdapter.hpp" -#include "BluetoothDevice.hpp" -#include "BluetoothManager.hpp" -#include "BluetoothException.hpp" - -using namespace tinyb; - -void BluetoothNotificationHandler::on_properties_changed_adapter(GDBusProxy *proxy, GVariant *changed_properties, GStrv invalidated_properties, gpointer userdata) { - (void) proxy; - (void) invalidated_properties; - - auto c = static_cast<BluetoothAdapter*>(userdata); - - if (!c->lock()) - return; - - if(g_variant_n_children(changed_properties) > 0) { - GVariantIter *iter = NULL; - - GVariant *value; - const gchar *key; - g_variant_get(changed_properties, "a{sv}", &iter); - while (iter != nullptr && g_variant_iter_loop(iter, "{&sv}", &key, &value)) { - auto powered_callback = c->powered_callback; - if (powered_callback != nullptr && g_ascii_strncasecmp(key, "powered", 8) == 0) { - bool new_value; - g_variant_get(value, "b", &new_value); - powered_callback(new_value); - continue; - } - auto discoverable_callback = c->discoverable_callback; - if (discoverable_callback != nullptr && g_ascii_strncasecmp(key, "discoverable", 13) == 0) { - bool new_value; - g_variant_get(value, "b", &new_value); - discoverable_callback(new_value); - continue; - } - auto pairable_callback = c->pairable_callback; - if (pairable_callback != nullptr && g_ascii_strncasecmp(key, "pairable", 9) == 0) { - bool new_value; - g_variant_get(value, "b", &new_value); - pairable_callback(new_value); - continue; - } - auto discovering_callback = c->discovering_callback; - if (discovering_callback != nullptr && g_ascii_strncasecmp(key, "discovering", 12) == 0) { - bool new_value; - g_variant_get(value, "b", &new_value); - discovering_callback(new_value); - continue; - } - } - g_variant_iter_free (iter); - } - - c->unlock(); -} - -std::string BluetoothAdapter::get_class_name() const -{ - return std::string("BluetoothAdapter"); -} - -std::string BluetoothAdapter::get_java_class() const -{ - return std::string(JAVA_DBUS_PACKAGE "/DBusAdapter"); -} - -std::string BluetoothAdapter::get_object_path() const -{ - return std::string(g_dbus_proxy_get_object_path(G_DBUS_PROXY(object))); -} - -BluetoothType BluetoothAdapter::get_bluetooth_type() const -{ - return BluetoothType::ADAPTER; -} - -BluetoothAdapter::BluetoothAdapter(Adapter1 *object_) -{ - this->object = object_; - g_object_ref(object_); - - g_signal_connect(G_DBUS_PROXY(object_), "g-properties-changed", - G_CALLBACK(BluetoothNotificationHandler::on_properties_changed_adapter), this); - valid = true; -} - -BluetoothAdapter::BluetoothAdapter(const BluetoothAdapter &object_) -{ - BluetoothAdapter(object_.object); -} - -BluetoothAdapter *BluetoothAdapter::clone() const -{ - return new BluetoothAdapter(object); -} - -BluetoothAdapter::~BluetoothAdapter() -{ - valid = false; - g_signal_handlers_disconnect_by_data(object, this); - lk.lock(); - - g_object_unref(object); -} - -std::unique_ptr<BluetoothAdapter> BluetoothAdapter::make(Object *object, - BluetoothType type, std::string *name, std::string *identifier, - BluetoothObject *parent) -{ - Adapter1 *adapter; - if((type == BluetoothType::NONE || type == BluetoothType::ADAPTER) && - (adapter = object_get_adapter1(object)) != NULL) { - - std::unique_ptr<BluetoothAdapter> p(new BluetoothAdapter(adapter)); - g_object_unref(adapter); - - if ((name == nullptr || *name == p->get_name()) && - (identifier == nullptr || *identifier == p->get_address()) && - (parent == nullptr)) - return p; - } - - return std::unique_ptr<BluetoothAdapter>(); -} - -std::vector<std::unique_ptr<BluetoothDevice>> BluetoothAdapter::get_devices() -{ - std::vector<std::unique_ptr<BluetoothDevice>> vector; - GList *l, *objects = g_dbus_object_manager_get_objects(gdbus_manager); - - for (l = objects; l != NULL; l = l->next) { - Object *object2 = OBJECT(l->data); - - auto p = BluetoothDevice::make(object2, - BluetoothType::DEVICE, NULL, NULL, this); - if (p != nullptr) - vector.push_back(std::move(p)); - } - g_list_free_full(objects, g_object_unref); - - return vector; -} - -/* D-Bus method calls: */ -bool BluetoothAdapter::start_discovery () -{ - GError *error = NULL; - if (get_discovering() == true) - return true; - bool result = adapter1_call_start_discovery_sync( - object, - NULL, - &error - ); - handle_error(error); - return result; -} - -bool BluetoothAdapter::stop_discovery () -{ - GError *error = NULL; - if (get_discovering() == false) - return true; - bool result = adapter1_call_stop_discovery_sync( - object, - NULL, - &error - ); - handle_error(error); - return result; -} - -bool BluetoothAdapter::remove_device ( - const std::string &arg_device) -{ - GError *error = NULL; - bool result = adapter1_call_remove_device_sync( - object, - arg_device.c_str(), - NULL, - &error - ); - handle_error(error); - return result; -} - -bool BluetoothAdapter::set_discovery_filter (std::vector<BluetoothUUID> uuids, - int16_t rssi, uint16_t pathloss, const TransportType &transport) -{ - GError *error = NULL; - bool result = true; - GVariantDict dict; - g_variant_dict_init(&dict, NULL); - - if (uuids.size() > 0) - { - GVariantBuilder *builder = g_variant_builder_new(G_VARIANT_TYPE("a(s)")); - - for (std::vector<BluetoothUUID>::iterator i = uuids.begin(); i != uuids.end(); ++i) - g_variant_builder_add(builder, "(s)", (*i).get_string().c_str()); - - GVariant *uuids_variant = g_variant_new("a(s)", builder); - g_variant_builder_unref(builder); - g_variant_dict_insert_value(&dict, "UUIDs", uuids_variant); - } - - if (rssi != 0) - g_variant_dict_insert_value(&dict, "RSSI", g_variant_new_int16(rssi)); - - if (pathloss != 0) - g_variant_dict_insert_value(&dict, "Pathloss", g_variant_new_uint16(pathloss)); - - std::string transport_str; - - if (transport == TransportType::AUTO) - transport_str = "auto"; - else if (transport == TransportType::BREDR) - transport_str = "bredr"; - else if (transport == TransportType::LE) - transport_str = "le"; - - if (!transport_str.empty()) - g_variant_dict_insert_value(&dict, "Transport", g_variant_new_string(transport_str.c_str())); - - GVariant *variant = g_variant_dict_end(&dict); - - result = adapter1_call_set_discovery_filter_sync( - object, - variant, - NULL, - &error - ); - - handle_error(error); - return result; -} - -/* D-Bus property accessors: */ -std::string BluetoothAdapter::get_address () -{ - return std::string(adapter1_get_address (object)); -} - -std::string BluetoothAdapter::get_name () -{ - return std::string(adapter1_get_name (object)); -} - -std::string BluetoothAdapter::get_alias () -{ - return std::string(adapter1_get_alias (object)); -} - -void BluetoothAdapter::set_alias (const std::string &value) -{ - adapter1_set_alias (object, value.c_str()); -} - -unsigned int BluetoothAdapter::get_class () -{ - return adapter1_get_class (object); -} - -bool BluetoothAdapter::get_powered () -{ - return adapter1_get_powered (object); -} - -void BluetoothAdapter::enable_powered_notifications( - std::function<void(BluetoothAdapter &adapter, bool powered, void *userdata)> callback, - void *userdata) { - powered_callback = std::bind(callback, std::ref(*this), std::placeholders::_1, userdata); -} -void BluetoothAdapter::enable_powered_notifications(std::function<void(bool powered)> callback) { - powered_callback = callback; -} -void BluetoothAdapter::disable_powered_notifications() { - powered_callback = nullptr; -} - -void BluetoothAdapter::set_powered (bool value) -{ - if (get_powered() != value) - adapter1_set_powered (object, value); -} - -bool BluetoothAdapter::get_discoverable () -{ - return adapter1_get_discoverable (object); -} - -void BluetoothAdapter::set_discoverable (bool value) -{ - adapter1_set_discoverable (object, value); -} - -void BluetoothAdapter::enable_discoverable_notifications( - std::function<void(BluetoothAdapter &adapter, bool discoverable, void *userdata)> callback, - void *userdata) { - discoverable_callback = std::bind(callback, std::ref(*this), std::placeholders::_1, userdata); -} -void BluetoothAdapter::enable_discoverable_notifications(std::function<void(bool discoverable)> callback) { - discoverable_callback = callback; -} -void BluetoothAdapter::disable_discoverable_notifications() { - discoverable_callback = nullptr; -} - -unsigned int BluetoothAdapter::get_discoverable_timeout () -{ - return adapter1_get_discoverable_timeout (object); -} - -void BluetoothAdapter::set_discoverable_timeout (unsigned int value) -{ - adapter1_set_discoverable_timeout (object, value); -} - -bool BluetoothAdapter::get_pairable () -{ - return adapter1_get_pairable (object); -} - -void BluetoothAdapter::enable_pairable_notifications( - std::function<void(BluetoothAdapter &adapter, bool pairable, void *userdata)> callback, - void *userdata) { - pairable_callback = std::bind(callback, std::ref(*this), std::placeholders::_1, userdata); -} -void BluetoothAdapter::enable_pairable_notifications(std::function<void(bool pairable)> callback) { - pairable_callback = callback; -} -void BluetoothAdapter::disable_pairable_notifications() { - pairable_callback = nullptr; -} - -void BluetoothAdapter::set_pairable (bool value) -{ - adapter1_set_pairable (object, value); -} - -unsigned int BluetoothAdapter::get_pairable_timeout () -{ - return adapter1_get_pairable_timeout (object); -} - -void BluetoothAdapter::set_pairable_timeout (unsigned int value) -{ - adapter1_set_pairable_timeout (object, value); -} - -bool BluetoothAdapter::get_discovering () -{ - return adapter1_get_discovering (object); -} - -void BluetoothAdapter::enable_discovering_notifications( - std::function<void(BluetoothAdapter &adapter, bool discovering, void *userdata)> callback, - void *userdata) { - discovering_callback = std::bind(callback, std::ref(*this), std::placeholders::_1, userdata); -} -void BluetoothAdapter::enable_discovering_notifications(std::function<void(bool discovering)> callback) { - discovering_callback = callback; -} -void BluetoothAdapter::disable_discovering_notifications() { - discovering_callback = nullptr; -} - -std::vector<std::string> BluetoothAdapter::get_uuids () -{ - const char * const *uuids_c = adapter1_get_uuids (object); - std::vector<std::string> uuids; - for (int i = 0; uuids_c[i] != NULL ;i++) - uuids.push_back(std::string(uuids_c[i])); - return uuids; -} - -std::unique_ptr<std::string> BluetoothAdapter::get_modalias () -{ - const gchar *modalias= adapter1_get_modalias (object); - if (modalias == nullptr) - return std::unique_ptr<std::string>(); - return std::unique_ptr<std::string>(new std::string(modalias)); -} - -std::unique_ptr<BluetoothDevice> BluetoothAdapter::connect_device ( - const std::string &arg_address, const std::string &arg_address_type) -{ - bool result = true; - GError *error = NULL; - GVariantDict dict; - gchar *object_path = nullptr; - - g_variant_dict_init(&dict, NULL); - g_variant_dict_insert_value(&dict, "Address", g_variant_new_string(arg_address.c_str())); - g_variant_dict_insert_value(&dict, "AddressType", g_variant_new_string(arg_address_type.c_str())); - GVariant *variant = g_variant_dict_end(&dict); - - result = adapter1_call_connect_device_sync( - object, - variant, - &object_path, - NULL, - &error - ); - handle_error(error); - - if( result && nullptr != object_path ) { - - Device1 *device = device1_proxy_new_for_bus_sync( - G_BUS_TYPE_SYSTEM, - G_DBUS_PROXY_FLAGS_NONE, - "org.bluez", - object_path, - NULL, - &error); - g_free(object_path); - handle_error(error); - - if (device == nullptr) { - std::string error_msg("Error occured while instantiating device: "); - error_msg += error->message; - g_error_free(error); - throw BluetoothException(error_msg); - } - std::unique_ptr<BluetoothDevice> p(new BluetoothDevice(device)); - g_object_unref(device); - return p; - } - g_free(object_path); - return std::unique_ptr<BluetoothDevice>(); -} - diff --git a/src/tinyb/BluetoothDevice.cpp b/src/tinyb/BluetoothDevice.cpp deleted file mode 100644 index f8160a7d..00000000 --- a/src/tinyb/BluetoothDevice.cpp +++ /dev/null @@ -1,644 +0,0 @@ -/* - * Author: Petre Eftime <[email protected]> - * Copyright (c) 2015 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#include "orgbluez-dbus.h" -#include "tinyb_utils.hpp" -#include "BluetoothNotificationHandler.hpp" -#include "BluetoothDevice.hpp" -#include "BluetoothGattService.hpp" -#include "BluetoothManager.hpp" -#include "BluetoothException.hpp" - -using namespace tinyb; - -void BluetoothNotificationHandler::on_properties_changed_device(GDBusProxy *proxy, GVariant *changed_properties, GStrv invalidated_properties, gpointer userdata) { - (void) proxy; - (void) invalidated_properties; - - auto c = static_cast<BluetoothDevice*>(userdata); - - if (!c->lock()) - return; - - if(g_variant_n_children(changed_properties) > 0) { - GVariantIter *iter = NULL; - - GVariant *value; - const gchar *key; - g_variant_get(changed_properties, "a{sv}", &iter); - while (iter != nullptr && g_variant_iter_loop(iter, "{&sv}", &key, &value)) { - auto rssi_callback = c->rssi_callback; - if (rssi_callback != nullptr && g_ascii_strncasecmp(key, "rssi", 5) == 0) { - int16_t new_value; - g_variant_get(value, "n", &new_value); - rssi_callback(new_value); - continue; - } - auto blocked_callback = c->blocked_callback; - if (blocked_callback != nullptr && g_ascii_strncasecmp(key, "blocked", 8) == 0) { - bool new_value; - g_variant_get(value, "b", &new_value); - blocked_callback(new_value); - continue; - } - auto trusted_callback = c->trusted_callback; - if (trusted_callback != nullptr && g_ascii_strncasecmp(key, "trusted", 8) == 0) { - bool new_value; - g_variant_get(value, "b", &new_value); - trusted_callback(new_value); - continue; - } - auto paired_callback = c->paired_callback; - if (paired_callback != nullptr && g_ascii_strncasecmp(key, "paired", 7) == 0) { - bool new_value; - g_variant_get(value, "b", &new_value); - paired_callback(new_value); - continue; - } - auto connected_callback = c->connected_callback; - if (connected_callback != nullptr && g_ascii_strncasecmp(key, "connected", 10) == 0) { - bool new_value; - g_variant_get(value, "b", &new_value); - connected_callback(new_value); - continue; - } - auto mfg_callback = c->mfg_callback; - if (mfg_callback != nullptr && g_ascii_strncasecmp(key, "manufacturerdata", 16) == 0) { - std::map<uint16_t, std::vector<uint8_t>> new_value; - - GVariantIter *iter_; - g_variant_get (value, "a{qv}", &iter_); - - GVariant *array; - uint16_t key_; - uint8_t val; - - while (g_variant_iter_loop(iter_, "{qv}", &key_, &array)) { - GVariantIter it_array; - g_variant_iter_init(&it_array, array); - while(g_variant_iter_loop(&it_array, "y", &val)) { - new_value[key_].push_back(val); - } - } - - g_variant_iter_free(iter_); - mfg_callback(new_value); - continue; - } - auto service_callback = c->service_callback; - if (service_callback != nullptr && g_ascii_strncasecmp(key, "servicedata", 11) == 0) { - std::map<std::string, std::vector<uint8_t>> new_value; - - GVariantIter *iter_; - g_variant_get (value, "a{sv}", &iter_); - - GVariant *array; - const char* key_; - uint8_t val; - - while (g_variant_iter_loop(iter_, "{sv}", &key_, &array)) { - GVariantIter it_array; - g_variant_iter_init(&it_array, array); - while(g_variant_iter_loop(&it_array, "y", &val)) { - new_value[key_].push_back(val); - } - } - - g_variant_iter_free(iter_); - service_callback(new_value); - continue; - } - auto services_resolved_callback = c->services_resolved_callback; - if (services_resolved_callback != nullptr && g_ascii_strncasecmp(key, "servicesresolved", 16) == 0) { - bool new_value; - g_variant_get(value, "b", &new_value); - services_resolved_callback(new_value); - continue; - } - } - g_variant_iter_free (iter); - } - - c->unlock(); -} - -std::string BluetoothDevice::get_class_name() const -{ - return std::string("BluetoothDevice"); -} - -std::string BluetoothDevice::get_java_class() const -{ - return std::string(JAVA_DBUS_PACKAGE "/DBusDevice"); -} - -std::string BluetoothDevice::get_object_path() const -{ - return std::string(g_dbus_proxy_get_object_path(G_DBUS_PROXY(object))); -} - -BluetoothType BluetoothDevice::get_bluetooth_type() const -{ - return BluetoothType::DEVICE; -} - -BluetoothDevice::BluetoothDevice(Device1 *object_) -{ - this->object = object_; - g_object_ref(object_); - - g_signal_connect(G_DBUS_PROXY(object_), "g-properties-changed", - G_CALLBACK(BluetoothNotificationHandler::on_properties_changed_device), this); - valid = true; -} - -BluetoothDevice::BluetoothDevice(const BluetoothDevice &object_) -{ - BluetoothDevice(object_.object); -} - -BluetoothDevice::~BluetoothDevice() -{ - valid = false; - g_signal_handlers_disconnect_by_data(object, this); - lk.lock(); - - g_object_unref(object); -} - -std::unique_ptr<BluetoothDevice> BluetoothDevice::make(Object *object, - BluetoothType type, std::string *name, std::string *identifier, - BluetoothObject *parent) -{ - Device1 *device; - if((type == BluetoothType::NONE || type == BluetoothType::DEVICE) && - (device = object_get_device1(object)) != NULL) { - - std::unique_ptr<BluetoothDevice> p(new BluetoothDevice(device)); - g_object_unref(device); - - if ((name == nullptr || *name == p->get_name()) && - (identifier == nullptr || *identifier == p->get_address()) && - (parent == nullptr || *parent == p->get_adapter())) - return p; - } - - return std::unique_ptr<BluetoothDevice>(); -} - -BluetoothDevice *BluetoothDevice::clone() const -{ - return new BluetoothDevice(object); -} - -std::vector<std::unique_ptr<BluetoothGattService>> BluetoothDevice::get_services() -{ - std::vector<std::unique_ptr<BluetoothGattService>> vector; - GList *l, *objects = g_dbus_object_manager_get_objects(gdbus_manager); - - for (l = objects; l != NULL; l = l->next) { - Object *object2 = OBJECT(l->data); - - auto p = BluetoothGattService::make(object2, - BluetoothType::GATT_SERVICE, NULL, NULL, this); - if (p != nullptr) - vector.push_back(std::move(p)); - } - g_list_free_full(objects, g_object_unref); - - return vector; -} - -/* D-Bus method calls: */ -bool BluetoothDevice::disconnect () -{ - GError *error = NULL; - bool result; - result = device1_call_disconnect_sync( - object, - NULL, - &error - ); - handle_error(error); - return result; -} - -void BluetoothDevice::connect_async_start () -{ - device1_call_connect ( - object, // Device1 *proxy, - NULL, // GCancellable *cancellable, - NULL, // GAsyncReadyCallback callback, - NULL // gpointer user_data) - ); -} - -bool BluetoothDevice::connect_async_finish () -{ - GError *error = NULL; - bool result; - result = device1_call_connect_finish ( - object, // Device1 *proxy, - NULL, // GAsyncResult *res, - &error // GError **error) - ); - handle_error(error); - return result; -} - -bool BluetoothDevice::connect () -{ - GError *error = NULL; - bool result; - result = device1_call_connect_sync( - object, - NULL, - &error - ); - handle_error(error); - return result; -} - -bool BluetoothDevice::connect_profile ( - const std::string &arg_UUID) -{ - GError *error = NULL; - bool result; - result = device1_call_connect_profile_sync( - object, - arg_UUID.c_str(), - NULL, - &error - ); - handle_error(error); - return result; -} - -bool BluetoothDevice::disconnect_profile ( - const std::string &arg_UUID) -{ - GError *error = NULL; - bool result; - result = device1_call_disconnect_profile_sync( - object, - arg_UUID.c_str(), - NULL, - &error - ); - handle_error(error); - return result; -} - -bool BluetoothDevice::pair () -{ - GError *error = NULL; - bool result; - result = device1_call_pair_sync( - object, - NULL, - &error - ); - handle_error(error); - return result; -} - -// Remove the device (like an unpair) -bool BluetoothDevice::remove_device(){ - BluetoothAdapter ba = get_adapter(); - return ba.remove_device(get_object_path()); -} - -bool BluetoothDevice::cancel_pairing () -{ - GError *error = NULL; - bool result; - result = device1_call_cancel_pairing_sync( - object, - NULL, - &error - ); - handle_error(error); - return result; -} - - - -/* D-Bus property accessors: */ -std::string BluetoothDevice::get_address () -{ - return std::string(device1_get_address (object)); -} - -std::string BluetoothDevice::get_name () -{ - const gchar *name = device1_get_name(object); - if (name == nullptr) - return std::string(device1_get_alias(object)); - return std::string(name); -} - -std::string BluetoothDevice::get_alias () -{ - return device1_get_alias (object); -} - -void BluetoothDevice::set_alias (const std::string &value) -{ - device1_set_alias (object, value.c_str()); -} - -unsigned int BluetoothDevice::get_class () -{ - return device1_get_class (object); -} - -uint16_t BluetoothDevice::get_appearance () -{ - return device1_get_appearance (object); -} - -std::unique_ptr<std::string> BluetoothDevice::get_icon () -{ - const gchar *icon = device1_get_icon (object); - if (icon == nullptr) - return std::unique_ptr<std::string>(); - return std::unique_ptr<std::string>(new std::string(icon)); -} - -bool BluetoothDevice::get_paired () -{ - return device1_get_paired (object); -} - -void BluetoothDevice::enable_paired_notifications( - std::function<void(BluetoothDevice &, bool, void *)> callback, - void *userdata) { - paired_callback = std::bind(callback, std::ref(*this), std::placeholders::_1, userdata); -} -void BluetoothDevice::enable_paired_notifications( - std::function<void(bool)> callback) { - paired_callback = callback; -} -void BluetoothDevice::disable_paired_notifications() { - paired_callback = nullptr; -} - -bool BluetoothDevice::get_trusted () -{ - return device1_get_trusted (object); -} - -void BluetoothDevice::set_trusted (bool value) -{ - device1_set_trusted (object, value); -} - -void BluetoothDevice::enable_trusted_notifications( - std::function<void(BluetoothDevice &, bool, void *)> callback, - void *userdata) { - trusted_callback = std::bind(callback, std::ref(*this), std::placeholders::_1, userdata); -} -void BluetoothDevice::enable_trusted_notifications( - std::function<void(bool)> callback) { - trusted_callback = callback; -} -void BluetoothDevice::disable_trusted_notifications() { - trusted_callback = nullptr; -} - -bool BluetoothDevice::get_blocked () -{ - return device1_get_blocked (object); -} - -void BluetoothDevice::set_blocked (bool value) -{ - device1_set_blocked (object, value); -} - -void BluetoothDevice::enable_blocked_notifications( - std::function<void(BluetoothDevice &, bool, void *)> callback, - void *userdata) { - blocked_callback = std::bind(callback, std::ref(*this), std::placeholders::_1, userdata); -} -void BluetoothDevice::enable_blocked_notifications( - std::function<void(bool)> callback) { - blocked_callback = callback; -} -void BluetoothDevice::disable_blocked_notifications() { - blocked_callback = nullptr; -} - -bool BluetoothDevice::get_legacy_pairing () -{ - return device1_get_legacy_pairing (object); -} - -int16_t BluetoothDevice::get_rssi () -{ - return device1_get_rssi (object); -} - -void BluetoothDevice::enable_rssi_notifications( - std::function<void(BluetoothDevice &, int16_t, void *)> callback, - void *userdata) { - rssi_callback = std::bind(callback, std::ref(*this), std::placeholders::_1, userdata); -} -void BluetoothDevice::enable_rssi_notifications( - std::function<void(int16_t)> callback) { - rssi_callback = callback; -} -void BluetoothDevice::disable_rssi_notifications() { - rssi_callback = nullptr; -} - -bool BluetoothDevice::get_connected () -{ - return device1_get_connected (object); -} - -void BluetoothDevice::enable_connected_notifications( - std::function<void(BluetoothDevice &, bool, void *)> callback, - void *userdata) { - connected_callback = std::bind(callback, std::ref(*this), std::placeholders::_1, userdata); -} -void BluetoothDevice::enable_connected_notifications( - std::function<void(bool)> callback) { - connected_callback = callback; -} -void BluetoothDevice::disable_connected_notifications() { - connected_callback = nullptr; -} - -std::vector<std::string> BluetoothDevice::get_uuids () -{ - - const char * const *uuids_c = device1_get_uuids (object); - std::vector<std::string> uuids; - for (int i = 0; uuids_c[i] != NULL ;i++) - uuids.push_back(std::string(uuids_c[i])); - return uuids; -} - -std::unique_ptr<std::string> BluetoothDevice::get_modalias () -{ - const gchar *modalias= device1_get_modalias (object); - if (modalias == nullptr) - return std::unique_ptr<std::string>(); - return std::unique_ptr<std::string>(new std::string(modalias)); -} - -BluetoothAdapter BluetoothDevice::get_adapter () -{ - GError *error = NULL; - - Adapter1 *adapter = adapter1_proxy_new_for_bus_sync( - G_BUS_TYPE_SYSTEM, - G_DBUS_PROXY_FLAGS_NONE, - "org.bluez", - device1_get_adapter (object), - NULL, - &error); - - if (adapter == NULL) { - std::string error_msg("Error occured while instantiating adapter: "); - error_msg += error->message; - g_error_free(error); - throw BluetoothException(error_msg); - } - - auto res = BluetoothAdapter(adapter); - g_object_unref(adapter); - return res; -} - -std::map<uint16_t, std::vector<uint8_t>> BluetoothDevice::get_manufacturer_data() -{ - std::map<uint16_t, std::vector<uint8_t>> m_data; - GVariant *v = device1_dup_manufacturer_data (object); - - if (v == nullptr) - return m_data; - - GVariantIter *iter; - g_variant_get (v, "a{qv}", &iter); - - GVariant *array; - uint16_t key; - uint8_t val; - - while (g_variant_iter_loop(iter, "{qv}", &key, &array)) { - - GVariantIter it_array; - g_variant_iter_init(&it_array, array); - while(g_variant_iter_loop(&it_array, "y", &val)) { - m_data[key].push_back(val); - } - } - - g_variant_iter_free(iter); - g_variant_unref(v); - - return m_data; -} - -void BluetoothDevice::enable_manufacturer_data_notifications( - std::function<void(BluetoothDevice &, std::map<uint16_t, std::vector<uint8_t>> &, void *)> callback, - void *userdata) { - mfg_callback = std::bind(callback, std::ref(*this), std::placeholders::_1, userdata); -} -void BluetoothDevice::enable_manufacturer_data_notifications( - std::function<void(std::map<uint16_t, std::vector<uint8_t>> &)> callback) { - mfg_callback = callback; -} -void BluetoothDevice::disable_manufacturer_data_notifications() { - mfg_callback = nullptr; -} - -std::map<std::string, std::vector<uint8_t>> BluetoothDevice::get_service_data() -{ - std::map<std::string, std::vector<uint8_t>> m_data; - GVariant *v = device1_dup_service_data (object); - - if (v == nullptr) - return m_data; - - GVariantIter *iter; - g_variant_get (v, "a{sv}", &iter); - - GVariant *array; - const char* key; - uint8_t val; - - while (g_variant_iter_loop(iter, "{sv}", &key, &array)) { - - GVariantIter it_array; - g_variant_iter_init(&it_array, array); - while(g_variant_iter_loop(&it_array, "y", &val)) { - m_data[key].push_back(val); - } - } - - g_variant_iter_free(iter); - g_variant_unref(v); - - return m_data; -} - -void BluetoothDevice::enable_service_data_notifications( - std::function<void(BluetoothDevice &, std::map<std::string, std::vector<uint8_t>> &, void *)> callback, - void *userdata) { - service_callback = std::bind(callback, std::ref(*this), std::placeholders::_1, userdata); -} -void BluetoothDevice::enable_service_data_notifications( - std::function<void(std::map<std::string, std::vector<uint8_t>> &)> callback) { - service_callback = callback; -} -void BluetoothDevice::disable_service_data_notifications() { - service_callback = nullptr; -} - -int16_t BluetoothDevice::get_tx_power () -{ - return device1_get_tx_power (object); -} - -bool BluetoothDevice::get_services_resolved () -{ - return device1_get_services_resolved (object); -} - -void BluetoothDevice::enable_services_resolved_notifications( - std::function<void(BluetoothDevice &, bool, void *)> callback, - void *userdata) { - services_resolved_callback = std::bind(callback, std::ref(*this), std::placeholders::_1, userdata); -} -void BluetoothDevice::enable_services_resolved_notifications( - std::function<void(bool)> callback) { - services_resolved_callback = callback; -} -void BluetoothDevice::disable_services_resolved_notifications() { - services_resolved_callback = nullptr; -} - diff --git a/src/tinyb/BluetoothEvent.cpp b/src/tinyb/BluetoothEvent.cpp deleted file mode 100644 index a92fa851..00000000 --- a/src/tinyb/BluetoothEvent.cpp +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Author: Petre Eftime <[email protected]> - * Copyright (c) 2016 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#include "orgbluez-dbus.h" -#include "BluetoothEvent.hpp" -#include "BluetoothManager.hpp" - -void BluetoothEvent::generic_callback(BluetoothObject &object, void *data) -{ - - if (data == nullptr) - return; - - BluetoothConditionVariable *generic_data = static_cast<BluetoothConditionVariable *>(data); - - generic_data->result = object.clone(); - generic_data->notify(); -} - -BluetoothEvent::BluetoothEvent(BluetoothType type_, std::string *name_, - std::string *identifier_, BluetoothObject *parent_, bool execute_once_, - BluetoothCallback cb_, void *data_) -{ - canceled = false; - this->type = type_; - if (name_ != nullptr) - this->name = new std::string(*name_); - else - this->name = nullptr; - - if (identifier_ != nullptr) - this->identifier = new std::string(*identifier_); - else - this->identifier = nullptr; - - if (parent_ != nullptr) - this->parent = parent_->clone(); - else - this->parent = nullptr; - - this->execute_once = execute_once_; - - if (cb_ == nullptr) { - this->data = static_cast<void *>(&cv); - this->cb = generic_callback; - } - else { - this->cb = cb_; - this->data = data_; - } -} - -bool BluetoothEvent::execute_callback(BluetoothObject &object) -{ - if (has_callback()) { - cb(object, data); - cv.notify(); - return execute_once; - } - - return true; -} - -void BluetoothEvent::wait(std::chrono::milliseconds timeout) -{ - if (!canceled && execute_once == true) { - if (timeout == std::chrono::milliseconds::zero()) - cv.wait(); - else - cv.wait_for(timeout); - } -} - -void BluetoothEvent::cancel() -{ - BluetoothManager *manager = BluetoothManager::get_bluetooth_manager(); - manager->remove_event(*this); - - cv.notify(); -} - -BluetoothEvent::~BluetoothEvent() -{ - if (name != nullptr) - delete name; - if (identifier != nullptr) - delete identifier; - if (parent != nullptr) - delete parent; -} diff --git a/src/tinyb/BluetoothGattCharacteristic.cpp b/src/tinyb/BluetoothGattCharacteristic.cpp deleted file mode 100644 index b051cba6..00000000 --- a/src/tinyb/BluetoothGattCharacteristic.cpp +++ /dev/null @@ -1,325 +0,0 @@ -/* - * Author: Petre Eftime <[email protected]> - * Copyright (c) 2015 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#include "orgbluez-dbus.h" -#include "tinyb_utils.hpp" -#include "BluetoothNotificationHandler.hpp" -#include "BluetoothGattCharacteristic.hpp" -#include "BluetoothGattService.hpp" -#include "BluetoothGattDescriptor.hpp" -#include "BluetoothException.hpp" - -using namespace tinyb; - -void BluetoothNotificationHandler::on_properties_changed_characteristic(GDBusProxy *proxy, GVariant *changed_properties, GStrv invalidated_properties, gpointer userdata) { - (void) proxy; - (void) invalidated_properties; - auto c = static_cast<BluetoothGattCharacteristic*>(userdata); - - if(g_variant_n_children(changed_properties) > 0) { - GVariantIter *iter = NULL; - - GVariant *value; - const gchar *key; - g_variant_get(changed_properties, "a{sv}", &iter); - while (iter != nullptr && g_variant_iter_loop(iter, "{&sv}", &key, &value)) { - auto value_callback = c->value_changed_callback; - if (value_callback != nullptr && g_ascii_strncasecmp(key, "value", 5) == 0) { - std::vector<unsigned char> new_value = from_iter_to_vector(value); - value_callback(new_value); - } - } - g_variant_iter_free (iter); - } -} - -std::string BluetoothGattCharacteristic::get_class_name() const -{ - return std::string("BluetoothGattCharacteristic"); -} - -std::string BluetoothGattCharacteristic::get_java_class() const -{ - return std::string(JAVA_DBUS_PACKAGE "/DBusGattCharacteristic"); -} - -std::string BluetoothGattCharacteristic::get_object_path() const -{ - return std::string(g_dbus_proxy_get_object_path(G_DBUS_PROXY(object))); -} - -BluetoothType BluetoothGattCharacteristic::get_bluetooth_type() const -{ - return BluetoothType::GATT_CHARACTERISTIC; -} - -BluetoothGattCharacteristic::BluetoothGattCharacteristic(GattCharacteristic1 *object_) -{ - this->object = object_; - g_object_ref(object_); - - g_signal_connect(G_DBUS_PROXY(object_), "g-properties-changed", - G_CALLBACK(BluetoothNotificationHandler::on_properties_changed_characteristic), this); -} - -BluetoothGattCharacteristic::BluetoothGattCharacteristic(const BluetoothGattCharacteristic &object_) -{ - BluetoothGattCharacteristic(object_.object); - -} - -BluetoothGattCharacteristic::~BluetoothGattCharacteristic() -{ - g_signal_handlers_disconnect_by_data(object, this); - g_object_unref(object); -} - -BluetoothGattCharacteristic *BluetoothGattCharacteristic::clone() const -{ - return new BluetoothGattCharacteristic(object); -} - -std::unique_ptr<BluetoothGattCharacteristic> BluetoothGattCharacteristic::make( - Object *object, BluetoothType type, std::string *name, - std::string *identifier, BluetoothObject *parent) -{ - GattCharacteristic1 *characteristic; - if((type == BluetoothType::NONE || type == BluetoothType::GATT_CHARACTERISTIC) && - (characteristic = object_get_gatt_characteristic1(object)) != NULL) { - - std::unique_ptr<BluetoothGattCharacteristic> p( - new BluetoothGattCharacteristic(characteristic)); - g_object_unref(characteristic); - - if ((name == nullptr) && - (identifier == nullptr || *identifier == p->get_uuid()) && - (parent == nullptr || *parent == p->get_service())) - return p; - } - - return std::unique_ptr<BluetoothGattCharacteristic>(); -} - -/* D-Bus method calls: */ -std::vector<unsigned char> BluetoothGattCharacteristic::read_value (uint16_t offset) -{ - GError *error = NULL; - GVariant *result_variant; - - GVariantDict dict; - g_variant_dict_init(&dict, NULL); - - if (offset != 0) - g_variant_dict_insert_value(&dict, "offset", g_variant_new_uint16(offset)); - - GVariant *variant = g_variant_dict_end(&dict); - - gatt_characteristic1_call_read_value_sync( - object, - variant, - &result_variant, - NULL, - &error - ); - - handle_error(error); - - GBytes *result_gbytes = g_variant_get_data_as_bytes(result_variant); - std::vector<unsigned char> result = from_gbytes_to_vector(result_gbytes); - - /* free the gbytes array */ - g_bytes_unref(result_gbytes); - - return result; -} - -bool BluetoothGattCharacteristic::write_value ( - const std::vector<unsigned char> &arg_value, uint16_t offset) -{ - GError *error = NULL; - bool result = true; - - gboolean trusted = true; - GBytes *arg_value_gbytes = from_vector_to_gbytes(arg_value); - GVariant *value = g_variant_new_from_bytes( - G_VARIANT_TYPE_BYTESTRING, arg_value_gbytes, trusted); - - GVariantDict dict; - g_variant_dict_init(&dict, NULL); - - if (offset != 0) - g_variant_dict_insert_value(&dict, "offset", g_variant_new_uint16(offset)); - - GVariant *variant = g_variant_dict_end(&dict); - - result = gatt_characteristic1_call_write_value_sync( - object, - value, - variant, - NULL, - &error - ); - - /* freeing the GBytes allocated inside from_vector_to_gbytes function */ - g_bytes_unref(arg_value_gbytes); - - handle_error(error); - - return result; -} - -bool BluetoothGattCharacteristic::enable_value_notifications( - std::function<void(BluetoothGattCharacteristic &, std::vector<unsigned char> &,void *)> callback, - void *userdata) -{ - value_changed_callback = std::bind(callback, std::ref(*this), std::placeholders::_1, userdata); - start_notify(); - return true; -} - -bool BluetoothGattCharacteristic::enable_value_notifications( - std::function<void(std::vector<unsigned char> &)> callback) -{ - value_changed_callback = callback; - start_notify(); - return true; -} - -bool BluetoothGattCharacteristic::disable_value_notifications() -{ - stop_notify(); - value_changed_callback = nullptr; - return true; -} - - -bool BluetoothGattCharacteristic::start_notify () -{ - GError *error = NULL; - bool result; - result = gatt_characteristic1_call_start_notify_sync( - object, - NULL, - &error - ); - - handle_error(error); - return result; -} - -bool BluetoothGattCharacteristic::stop_notify () -{ - GError *error = NULL; - bool result; - result = gatt_characteristic1_call_stop_notify_sync( - object, - NULL, - &error - ); - handle_error(error); - return result; -} - -/* D-Bus property accessors: */ -std::string BluetoothGattCharacteristic::get_uuid () -{ - return std::string(gatt_characteristic1_get_uuid (object)); -} - -BluetoothGattService BluetoothGattCharacteristic::get_service () -{ - GError *error = NULL; - - GattService1 *service = gatt_service1_proxy_new_for_bus_sync( - G_BUS_TYPE_SYSTEM, - G_DBUS_PROXY_FLAGS_NONE, - "org.bluez", - gatt_characteristic1_get_service (object), - NULL, - &error); - - if (service == nullptr) { - std::string error_msg("Error occured while instantiating service: "); - error_msg += error->message; - g_error_free(error); - throw BluetoothException(error_msg); - } - - auto res = BluetoothGattService(service); - g_object_unref(service); - return res; -} - -std::vector<unsigned char> BluetoothGattCharacteristic::get_value () -{ - GVariant *value_variant = gatt_characteristic1_get_value (object); - GBytes *value_gbytes = g_variant_get_data_as_bytes(value_variant); - std::vector<unsigned char> result; - - try { - result = from_gbytes_to_vector(value_gbytes); - } catch (std::exception &e) { - g_bytes_unref(value_gbytes); - throw e; - } - - g_bytes_unref(value_gbytes); - - return result; -} - -bool BluetoothGattCharacteristic::get_notifying () -{ - return gatt_characteristic1_get_notifying (object); -} - -std::vector<std::string> BluetoothGattCharacteristic::get_flags () -{ - const char * const *flags_c = gatt_characteristic1_get_flags (object); - std::vector<std::string> flags; - for (int i = 0; flags_c[i] != NULL ;i++) - flags.push_back(std::string(flags_c[i])); - return flags; - -} - -std::vector<std::unique_ptr<BluetoothGattDescriptor>> BluetoothGattCharacteristic::get_descriptors () -{ - std::vector<std::unique_ptr<BluetoothGattDescriptor>> vector; - GList *l, *objects = g_dbus_object_manager_get_objects(gdbus_manager); - - for (l = objects; l != NULL; l = l->next) { - Object *object2 = OBJECT(l->data); - - auto p = BluetoothGattDescriptor::make(object2, - BluetoothType::GATT_DESCRIPTOR, NULL, NULL, this); - if (p != nullptr) - vector.push_back(std::move(p)); - } - g_list_free_full(objects, g_object_unref); - - return vector; -} - - diff --git a/src/tinyb/BluetoothGattDescriptor.cpp b/src/tinyb/BluetoothGattDescriptor.cpp deleted file mode 100644 index 48217114..00000000 --- a/src/tinyb/BluetoothGattDescriptor.cpp +++ /dev/null @@ -1,245 +0,0 @@ -/* - * Author: Petre Eftime <[email protected]> - * Copyright (c) 2015 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#include "orgbluez-dbus.h" -#include "tinyb_utils.hpp" -#include "BluetoothNotificationHandler.hpp" -#include "BluetoothGattDescriptor.hpp" -#include "BluetoothGattCharacteristic.hpp" -#include "BluetoothException.hpp" - -using namespace tinyb; - -void BluetoothNotificationHandler::on_properties_changed_descriptor(GDBusProxy *proxy, GVariant *changed_properties, GStrv invalidated_properties, gpointer userdata) { - (void) proxy; - (void) invalidated_properties; - auto c = static_cast<BluetoothGattDescriptor*>(userdata); - - if(g_variant_n_children(changed_properties) > 0) { - GVariantIter *iter = NULL; - - GVariant *value; - const gchar *key; - g_variant_get(changed_properties, "a{sv}", &iter); - while (iter != nullptr && g_variant_iter_loop(iter, "{&sv}", &key, &value)) { - auto value_callback = c->value_changed_callback; - if (value_callback != nullptr && g_ascii_strncasecmp(key, "value", 5) == 0) { - std::vector<unsigned char> new_value = from_iter_to_vector(value); - value_callback(new_value); - } - } - g_variant_iter_free (iter); - } -} - -std::string BluetoothGattDescriptor::get_class_name() const -{ - return std::string("BluetoothGattDescriptor"); -} - -std::string BluetoothGattDescriptor::get_java_class() const -{ - return std::string(JAVA_DBUS_PACKAGE "/DBusGattDescriptor"); -} - -std::string BluetoothGattDescriptor::get_object_path() const -{ - return std::string(g_dbus_proxy_get_object_path(G_DBUS_PROXY(object))); -} - -BluetoothType BluetoothGattDescriptor::get_bluetooth_type() const -{ - return BluetoothType::GATT_DESCRIPTOR; -} - -BluetoothGattDescriptor::BluetoothGattDescriptor(GattDescriptor1 *object_) -{ - this->object = object_; - g_object_ref(object_); - - g_signal_connect(G_DBUS_PROXY(object_), "g-properties-changed", - G_CALLBACK(BluetoothNotificationHandler::on_properties_changed_descriptor), this); - valid = true; -} - -BluetoothGattDescriptor::BluetoothGattDescriptor(const BluetoothGattDescriptor &object_) -{ - BluetoothGattDescriptor(object_.object); -} - -BluetoothGattDescriptor::~BluetoothGattDescriptor() -{ - valid = false; - g_signal_handlers_disconnect_by_data(object, this); - lk.lock(); - - g_object_unref(object); -} - -std::unique_ptr<BluetoothGattDescriptor> BluetoothGattDescriptor::make( - Object *object, BluetoothType type, std::string *name, - std::string *identifier, BluetoothObject *parent) -{ - GattDescriptor1 *descriptor; - if((type == BluetoothType::NONE || type == BluetoothType::GATT_DESCRIPTOR) && - (descriptor = object_get_gatt_descriptor1(object)) != NULL) { - - std::unique_ptr<BluetoothGattDescriptor> p( - new BluetoothGattDescriptor(descriptor)); - g_object_unref(descriptor); - - if ((name == nullptr) && - (identifier == nullptr || *identifier == p->get_uuid()) && - (parent == nullptr || *parent == p->get_characteristic())) - return p; - } - - return std::unique_ptr<BluetoothGattDescriptor>(); -} - - - -BluetoothGattDescriptor *BluetoothGattDescriptor::clone() const -{ - return new BluetoothGattDescriptor(object); -} - -/* D-Bus method calls: */ -std::vector<unsigned char> BluetoothGattDescriptor::read_value (uint16_t offset) -{ - GError *error = NULL; - gchar *result_chars; - - GVariantDict dict; - g_variant_dict_init(&dict, NULL); - - if (offset != 0) - g_variant_dict_insert_value(&dict, "offset", g_variant_new_uint16(offset)); - - GVariant *variant = g_variant_dict_end(&dict); - - gatt_descriptor1_call_read_value_sync( - object, - variant, - &result_chars, - NULL, - &error - ); - handle_error(error); - - std::vector<unsigned char> result = from_chars_to_vector(result_chars); - - g_free(result_chars); - - return result; -} - -bool BluetoothGattDescriptor::write_value ( - const std::vector<unsigned char> &arg_value, uint16_t offset) -{ - GError *error = NULL; - bool result; - - gchar *arg_value_chars = const_cast<gchar*>(reinterpret_cast<const gchar*>(arg_value.data())); - - GVariantDict dict; - g_variant_dict_init(&dict, NULL); - - if (offset != 0) - g_variant_dict_insert_value(&dict, "offset", g_variant_new_uint16(offset)); - - GVariant *variant = g_variant_dict_end(&dict); - - result = gatt_descriptor1_call_write_value_sync( - object, - arg_value_chars, - variant, - NULL, - &error - ); - handle_error(error); - - return result; -} - -bool BluetoothGattDescriptor::enable_value_notifications( - std::function<void(BluetoothGattDescriptor &, std::vector<unsigned char> &,void *)> callback, - void *userdata) -{ - value_changed_callback = std::bind(callback, std::ref(*this), std::placeholders::_1, userdata); - return true; -} - -bool BluetoothGattDescriptor::enable_value_notifications( - std::function<void(std::vector<unsigned char> &)> callback) -{ - value_changed_callback = callback; - return true; -} - -bool BluetoothGattDescriptor::disable_value_notifications() -{ - value_changed_callback = nullptr; - return true; -} - -/* D-Bus property accessors: */ -std::string BluetoothGattDescriptor::get_uuid () -{ - return std::string(gatt_descriptor1_get_uuid (object)); -} - -BluetoothGattCharacteristic BluetoothGattDescriptor::get_characteristic () -{ - GError *error = NULL; - - GattCharacteristic1* characteristic = gatt_characteristic1_proxy_new_for_bus_sync( - G_BUS_TYPE_SYSTEM, - G_DBUS_PROXY_FLAGS_NONE, - "org.bluez", - gatt_descriptor1_get_characteristic (object), - NULL, - &error); - - if (characteristic == NULL) { - std::string error_msg("Error occured while instantiating characteristic: "); - error_msg += error->message; - g_error_free(error); - throw BluetoothException(error_msg); - } - - auto res = BluetoothGattCharacteristic(characteristic); - g_object_unref(characteristic); - return res; -} - -std::vector<unsigned char> BluetoothGattDescriptor::get_value () -{ - gchar *value_chars = const_cast<gchar *>(gatt_descriptor1_get_value (object)); - std::vector<unsigned char> result; - - result = from_chars_to_vector(value_chars); - - return result; -} diff --git a/src/tinyb/BluetoothGattService.cpp b/src/tinyb/BluetoothGattService.cpp deleted file mode 100644 index 0897ef4c..00000000 --- a/src/tinyb/BluetoothGattService.cpp +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Author: Petre Eftime <[email protected]> - * Copyright (c) 2015 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#include "orgbluez-dbus.h" -#include "tinyb_utils.hpp" -#include "BluetoothGattService.hpp" -#include "BluetoothGattCharacteristic.hpp" -#include "BluetoothDevice.hpp" -#include "BluetoothException.hpp" - -using namespace tinyb; - -std::string BluetoothGattService::get_class_name() const -{ - return std::string("BluetoothGattService"); -} - -std::string BluetoothGattService::get_java_class() const -{ - return std::string(JAVA_DBUS_PACKAGE "/DBusGattService"); -} - -std::string BluetoothGattService::get_object_path() const -{ - return std::string(g_dbus_proxy_get_object_path(G_DBUS_PROXY(object))); -} - -BluetoothType BluetoothGattService::get_bluetooth_type() const -{ - return BluetoothType::GATT_SERVICE; -} - -BluetoothGattService::BluetoothGattService(GattService1 *object_) -{ - this->object = object_; - g_object_ref(object_); -} - -BluetoothGattService::BluetoothGattService(const BluetoothGattService &object_) -{ - BluetoothGattService(object_.object); -} - -BluetoothGattService::~BluetoothGattService() -{ - g_object_unref(object); -} - -std::unique_ptr<BluetoothGattService> BluetoothGattService::make( - Object *object, BluetoothType type, std::string *name, - std::string *identifier, BluetoothObject *parent) -{ - GattService1 *service; - if((type == BluetoothType::NONE || type == BluetoothType::GATT_SERVICE) && - (service = object_get_gatt_service1(object)) != NULL) { - - std::unique_ptr<BluetoothGattService> p( - new BluetoothGattService(service)); - g_object_unref(service); - - if ((name == nullptr) && - (identifier == nullptr || *identifier == p->get_uuid()) && - (parent == nullptr || *parent == p->get_device())) - return p; - } - - return std::unique_ptr<BluetoothGattService>(); -} - -BluetoothGattService *BluetoothGattService::clone() const -{ - return new BluetoothGattService(object); -} - -/* D-Bus property accessors: */ -std::string BluetoothGattService::get_uuid () -{ - return std::string(gatt_service1_get_uuid (object)); -} - -BluetoothDevice BluetoothGattService::get_device () -{ - GError *error = NULL; - - Device1 *device = device1_proxy_new_for_bus_sync( - G_BUS_TYPE_SYSTEM, - G_DBUS_PROXY_FLAGS_NONE, - "org.bluez", - gatt_service1_get_device (object), - NULL, - &error); - - if (device == nullptr) { - std::string error_msg("Error occured while instantiating device: "); - error_msg += error->message; - g_error_free(error); - throw BluetoothException(error_msg); - } - - auto res = BluetoothDevice(device); - g_object_unref(device); - return res; -} - -bool BluetoothGattService::get_primary () -{ - return gatt_service1_get_primary (object); -} - -std::vector<std::unique_ptr<BluetoothGattCharacteristic>> BluetoothGattService::get_characteristics () -{ - std::vector<std::unique_ptr<BluetoothGattCharacteristic>> vector; - GList *l, *objects = g_dbus_object_manager_get_objects(gdbus_manager); - - for (l = objects; l != NULL; l = l->next) { - Object *object2 = OBJECT(l->data); - - auto p = BluetoothGattCharacteristic::make(object2, - BluetoothType::GATT_CHARACTERISTIC, NULL, NULL, this); - if (p != nullptr) - vector.push_back(std::move(p)); - } - g_list_free_full(objects, g_object_unref); - - return vector; -} - diff --git a/src/tinyb/BluetoothManager.cpp b/src/tinyb/BluetoothManager.cpp deleted file mode 100644 index d4637308..00000000 --- a/src/tinyb/BluetoothManager.cpp +++ /dev/null @@ -1,420 +0,0 @@ -/* - * Author: Petre Eftime <[email protected]> - * Copyright (c) 2015 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#include "orgbluez-dbus.h" -#include "BluetoothManager.hpp" -#include "BluetoothAdapter.hpp" -#include "BluetoothDevice.hpp" -#include "BluetoothGattService.hpp" -#include "BluetoothGattCharacteristic.hpp" -#include "BluetoothGattDescriptor.hpp" -#include "BluetoothEvent.hpp" -#include "BluetoothException.hpp" -#include "version.h" - -#include <cassert> - -using namespace tinyb; - -class tinyb::BluetoothEventManager { -public: - static void on_interface_added (GDBusObject *object, - GDBusInterface *interface, gpointer user_data) { - (void) object; - (void) user_data; - - GDBusInterfaceInfo *info = g_dbus_interface_get_info(interface); - BluetoothType type = BluetoothType::NONE; - BluetoothManager *manager = BluetoothManager::get_bluetooth_manager(); - - /* Unknown interface, ignore */ - if (info == NULL) - return; - - if(IS_GATT_SERVICE1_PROXY(interface)) { - type = BluetoothType::GATT_SERVICE; - auto obj = new BluetoothGattService(GATT_SERVICE1(interface)); - auto uuid = obj->get_uuid(); - auto parent = obj->get_device(); - manager->handle_event(type, nullptr, &uuid, &parent, *obj); - } - else if(IS_GATT_CHARACTERISTIC1_PROXY(interface)) { - type = BluetoothType::GATT_CHARACTERISTIC; - auto obj = new BluetoothGattCharacteristic(GATT_CHARACTERISTIC1(interface)); - auto uuid = obj->get_uuid(); - auto parent = obj->get_service(); - manager->handle_event(type, nullptr, &uuid, &parent, *obj); - } - else if(IS_GATT_DESCRIPTOR1_PROXY(interface)) { - type = BluetoothType::GATT_DESCRIPTOR; - auto obj = new BluetoothGattDescriptor(GATT_DESCRIPTOR1(interface)); - auto uuid = obj->get_uuid(); - auto parent = obj->get_characteristic(); - manager->handle_event(type, nullptr, &uuid, &parent, *obj); - } - else if(IS_DEVICE1_PROXY(interface)) { - type = BluetoothType::DEVICE; - auto obj = new BluetoothDevice(DEVICE1(interface)); - auto name = obj->get_name(); - auto uuid = obj->get_address(); - auto parent = obj->get_adapter(); - manager->handle_event(type, &name, &uuid, &parent, *obj); - } - else if(IS_ADAPTER1_PROXY(interface)) { - type = BluetoothType::ADAPTER; - auto obj = new BluetoothAdapter(ADAPTER1(interface)); - auto name = obj->get_name(); - auto uuid = obj->get_address(); - manager->handle_event(type, &name, &uuid, nullptr, *obj); - } - } - - static void on_object_added (GDBusObjectManager *manager, - GDBusObject *object, gpointer user_data) { - (void) manager; - - GList *l, *interfaces = g_dbus_object_get_interfaces(object); - - for(l = interfaces; l != NULL; l = l->next) - on_interface_added(object, (GDBusInterface *)l->data, user_data); - - g_list_free_full(interfaces, g_object_unref); - } -}; - -GDBusObjectManager *gdbus_manager = NULL; -GMainContext *manager_context = NULL; -GThread *manager_thread = NULL; - -std::string BluetoothManager::get_class_name() const -{ - return std::string("BluetoothManager"); -} - -std::string BluetoothManager::get_java_class() const -{ - return std::string(JAVA_DBUS_PACKAGE "/DBusManager"); -} - -std::string BluetoothManager::get_object_path() const -{ - return std::string("/"); -} - -BluetoothType BluetoothManager::get_bluetooth_type() const -{ - return BluetoothType::NONE; -} - -std::string BluetoothManager::get_api_version() { - return std::string(gVERSION_API); -} - -std::string BluetoothManager::get_library_version() { - return std::string(gVERSION_SHORT); -} - -std::unique_ptr<BluetoothObject> BluetoothManager::get_object( - BluetoothType type, std::string *name, std::string *identifier, - BluetoothObject *parent) -{ - auto list = get_objects(type, name, identifier, parent); - if (list.empty()) - return std::unique_ptr<BluetoothObject>(); - return std::move(list.front()); -} - -std::vector<std::unique_ptr<BluetoothObject>> BluetoothManager::get_objects( - BluetoothType type, std::string *name, std::string *identifier, - BluetoothObject *parent) -{ - std::vector<std::unique_ptr<BluetoothObject>> vector; - GList *l, *objects = g_dbus_object_manager_get_objects(gdbus_manager); - - for (l = objects; l != NULL; l = l->next) { - Object *object = OBJECT(l->data); - - auto p_service = BluetoothGattService::make(object, type, name, identifier, parent); - if (p_service != nullptr) - vector.push_back(std::move(p_service)); - - auto p_characteristic = BluetoothGattCharacteristic::make(object, type, name, identifier, parent); - if (p_characteristic != nullptr) - vector.push_back(std::move(p_characteristic)); - - auto p_descriptor = BluetoothGattDescriptor::make(object, type, name, identifier, parent); - if (p_descriptor != nullptr) - vector.push_back(std::move(p_descriptor)); - - auto p_device = BluetoothDevice::make(object, type, name, identifier, parent); - if (p_device != nullptr) - vector.push_back(std::move(p_device)); - - auto p_adapter = BluetoothAdapter::make(object, type, name, identifier, parent); - if (p_adapter != nullptr) - vector.push_back(std::move(p_adapter)); - } - g_list_free_full(objects, g_object_unref); - return vector; -} - -std::unique_ptr<BluetoothObject> BluetoothManager::find(BluetoothType type, - std::string *name, std::string* identifier, BluetoothObject *parent, - std::chrono::milliseconds timeout) -{ - std::shared_ptr<BluetoothEvent> event(new BluetoothEvent(type, name, - identifier, parent)); - add_event(event); - - auto object = get_object(type, name, identifier, parent); - - if (object == nullptr) { - event->wait(timeout); - object = std::unique_ptr<BluetoothObject>(event->get_result()); - } - - event->cancel(); - return object; -} - -std::weak_ptr<BluetoothEvent> BluetoothManager::find(BluetoothType type, - std::string *name, std::string* identifier, BluetoothObject *parent, - BluetoothCallback cb, bool execute_once, - std::chrono::milliseconds timeout) -{ - (void)cb; - (void)execute_once; - (void)timeout; - - std::shared_ptr<BluetoothEvent> event(new BluetoothEvent(type, name, - identifier, parent)); - add_event(event); - return std::weak_ptr<BluetoothEvent>(event); -} - -void BluetoothManager::handle_event(BluetoothType type, std::string *name, - std::string *identifier, BluetoothObject *parent, BluetoothObject &object) -{ - for (auto it = event_list.begin(); - it != event_list.end();) { - if ((*it)->get_type() != BluetoothType::NONE && ((*it)->get_type()) != type) { - ++it; - continue; /* this event does not match */ - } - if ((*it)->get_name() != NULL) - if (name == NULL || *((*it)->get_name()) != *name) { - ++it; - continue; /* this event does not match */ - } - if ((*it)->get_identifier() != NULL) - if (identifier == NULL || *((*it)->get_identifier()) != *identifier) { - ++it; - continue; /* this event does not match */ - } - if ((*it)->get_parent() != NULL) - if (parent == NULL || *((*it)->get_parent()) != *parent) { - ++it; - continue; /* this event does not match */ - } - /* The event matches, execute and see if it needs to reexecute */ - if ((*it)->execute_callback(object)) - it = event_list.erase(it); - else - ++it; - } -} - -static gpointer init_manager_thread(void *data) -{ - GMainLoop *loop; - GDBusObjectManager *_gdbus_manager = (GDBusObjectManager *) data; - - g_main_context_push_thread_default(manager_context); - - loop = g_main_loop_new(manager_context, FALSE); - - g_signal_connect(_gdbus_manager, - "interface-added", - G_CALLBACK(BluetoothEventManager::on_interface_added), - NULL); - - g_signal_connect(_gdbus_manager, - "object-added", - G_CALLBACK(BluetoothEventManager::on_object_added), - NULL); - - g_main_context_pop_thread_default(manager_context); - - g_main_loop_run(loop); - - return NULL; -} - -BluetoothManager::BluetoothManager() : event_list() -{ - GError *error = NULL; - GList *objects, *l; - - manager_context = g_main_context_new (); - g_main_context_push_thread_default(manager_context); - - gdbus_manager = object_manager_client_new_for_bus_sync( - G_BUS_TYPE_SYSTEM, - G_DBUS_OBJECT_MANAGER_CLIENT_FLAGS_NONE, - "org.bluez", - "/", - NULL, /* GCancellable */ - &error); - - if (gdbus_manager == nullptr) { - std::string error_str("Error getting object manager client: "); - error_str += error->message; - g_error_free(error); - throw std::runtime_error(error_str); - } - - g_main_context_pop_thread_default(manager_context); - - manager_thread = g_thread_new("BluetoothManager-Thread", init_manager_thread, gdbus_manager); - - objects = g_dbus_object_manager_get_objects(gdbus_manager); - - default_adapter = nullptr; - for (l = objects; l != NULL; l = l->next) { - Object *object = (Object *) l->data; - Adapter1 *adapter = object_get_adapter1(object); - if (adapter != NULL) { - default_adapter = std::unique_ptr<BluetoothAdapter>(new BluetoothAdapter(adapter)); - g_object_unref(adapter); - break; - } - } - g_list_free_full(objects, g_object_unref); - - if (default_adapter == nullptr) { - throw BluetoothException("No adapter installed or not recognized by system"); - } -} - -BluetoothManager *BluetoothManager::get_bluetooth_manager() -{ - static BluetoothManager bluetooth_manager_; - return &bluetooth_manager_; -} - -BluetoothManager::BluetoothManager(const BluetoothManager &) -{ - /* Should not be called */ -} - -BluetoothManager::~BluetoothManager() -{ - /* Should not be called */ -} - -std::vector<std::unique_ptr<BluetoothAdapter>> BluetoothManager::get_adapters() -{ - std::vector<std::unique_ptr<BluetoothAdapter>> vector; - GList *l, *objects = g_dbus_object_manager_get_objects(gdbus_manager); - - for (l = objects; l != NULL; l = l->next) { - Object *object = OBJECT(l->data); - - auto p = BluetoothAdapter::make(object); - if (p != nullptr) - vector.push_back(std::move(p)); - } - g_list_free_full(objects, g_object_unref); - - return vector; -} - -std::vector<std::unique_ptr<BluetoothDevice>> BluetoothManager::get_devices() -{ - std::vector<std::unique_ptr<BluetoothDevice>> vector; - GList *l, *objects = g_dbus_object_manager_get_objects(gdbus_manager); - - for (l = objects; l != NULL; l = l->next) { - Object *object = OBJECT(l->data); - - auto p = BluetoothDevice::make(object); - if (p != nullptr) - vector.push_back(std::move(p)); - } - g_list_free_full(objects, g_object_unref); - - return vector; -} - -std::vector<std::unique_ptr<BluetoothGattService>> BluetoothManager::get_services() -{ - std::vector<std::unique_ptr<BluetoothGattService>> vector; - GList *l, *objects = g_dbus_object_manager_get_objects(gdbus_manager); - - for (l = objects; l != NULL; l = l->next) { - Object *object = OBJECT(l->data); - - auto p = BluetoothGattService::make(object); - if (p != nullptr) - vector.push_back(std::move(p)); - } - g_list_free_full(objects, g_object_unref); - - return vector; -} - -bool BluetoothManager::set_default_adapter(BluetoothAdapter &adapter) -{ - default_adapter = std::unique_ptr<BluetoothAdapter>(adapter.clone()); - return true; -} - -std::unique_ptr<BluetoothAdapter> BluetoothManager::get_default_adapter() -{ - return std::unique_ptr<BluetoothAdapter>(default_adapter->clone()); -} - -bool BluetoothManager::start_discovery() -{ - if (default_adapter != nullptr) - return default_adapter->start_discovery(); - else - return false; -} - -bool BluetoothManager::stop_discovery() -{ - if (default_adapter != NULL) - return default_adapter->stop_discovery(); - else - return false; -} - -bool BluetoothManager::get_discovering() -{ - if (default_adapter != NULL) - return default_adapter->get_discovering(); - else - return false; -} diff --git a/src/tinyb/BluetoothObject.cpp b/src/tinyb/BluetoothObject.cpp deleted file mode 100644 index 2e8ddaf4..00000000 --- a/src/tinyb/BluetoothObject.cpp +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Author: Petre Eftime <[email protected]> - * Copyright (c) 2015 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#include "BluetoothObject.hpp" -#include <glib.h> - -using namespace tinyb; - -std::string BluetoothObject::get_java_class() const -{ - return std::string(JAVA_DBUS_PACKAGE "/DBusObject"); -} - -std::string BluetoothObject::get_class_name() const -{ - return std::string("BluetoothObject"); -} - -std::string BluetoothObject::get_object_path() const -{ - return std::string(); -} - -BluetoothType BluetoothObject::get_bluetooth_type() const -{ - return BluetoothType::NONE; -} - -BluetoothObject *BluetoothObject::clone() const -{ - return NULL; -} - -bool BluetoothObject::operator==(const BluetoothObject &other) const -{ - return (this->get_bluetooth_type() == other.get_bluetooth_type()) - && (this->get_object_path() == other.get_object_path()); -} - -bool BluetoothObject::operator!=(const BluetoothObject &other) const -{ - return !(*this == other); -} diff --git a/src/tinyb/BluetoothUUID.cpp b/src/tinyb/BluetoothUUID.cpp deleted file mode 100644 index 6d25e19e..00000000 --- a/src/tinyb/BluetoothUUID.cpp +++ /dev/null @@ -1,94 +0,0 @@ -#include "BluetoothUUID.hpp" - -#include <cinttypes> -#include <cstring> -#include <iostream> - -using namespace tinyb; - -BluetoothUUID::BluetoothUUID(const BluetoothUUID &other) { - uuid[0] = other.uuid[0]; - uuid[1] = other.uuid[1]; -} - -BluetoothUUID::BluetoothUUID(const char str[]) { - int len = strlen(str); - const char *err_msg = "UUID does not have a valid format"; - - if (len == 4 || len == 8) { - /* 16bit or 32bit UUID: number + base UUID */ - const uint64_t strval = strtoul(str, NULL, 16); - uuid[0] = strval << 32 | 0x00001000ULL; - uuid[1] = 0x800000805f9b34fbULL; - } else if (len == 36) { - /* 128bit UUID */ - char u[37]; - strcpy(u, str); - - if (u[8] == '-') { - u[8] = ' '; - const uint64_t uval = strtoul(u + 0, NULL, 16); - uuid[0] = uval << 32; - } else { - throw std::invalid_argument(err_msg); - } - if (u[13] == '-') { - u[13] = ' '; - uuid[0] = uuid[0] | strtoul(u + 9, NULL, 16) << 16; - } else throw std::invalid_argument(err_msg); - if (u[18] == '-') { - u[18] = ' '; - uuid[0] = uuid[0] | strtoul(u + 14, NULL, 16); - } else throw std::invalid_argument(err_msg); - - if (u[23] == '-') { - u[23] = ' '; - const uint64_t uval = strtoul(u + 19, NULL, 16); - uuid[1] = uval << 48; - } else throw std::invalid_argument(err_msg); - - uuid[1] = uuid[1] | strtoul(u + 24, NULL, 16); - } else throw std::invalid_argument(err_msg); -} - -BluetoothUUID::BluetoothUUID(const std::string &str) : BluetoothUUID(str.c_str()) {} - -std::string BluetoothUUID::get_string() -{ - char u[37]; - snprintf(u, 37, "%08" PRIx64 "-%04" PRIx64 "-%04" PRIx64 "-%04" PRIx64 "-%012" PRIx64, - (uint64_t)(uuid[0] >> 32), - (uint64_t)((uuid[0] >> 16) & 0xFFFFULL), - (uint64_t)(uuid[0] & 0xFFFFULL), - (uint64_t)(uuid[1] >> 48), - (uint64_t)(uuid[1] & ~(0xFFFFULL << 48))); - return std::string(u); -} - -std::string BluetoothUUID::get_short_string() -{ - char u[12]; - if (is_short()) { - uint32_t suuid = get_short(); - if ( ( suuid & 0xFFFF ) == suuid ) - snprintf(u, sizeof(u), "%04ux", suuid); - else - snprintf(u, sizeof(u), "%08ux", suuid); - return std::string(u); - } else { - return get_string(); - } -} - -uint32_t BluetoothUUID::get_short() { - if (is_short()) - return uuid[0] >> 32; - return 0; -} - -bool BluetoothUUID::is_short() -{ - if ( ( uuid[1] == 0x800000805f9b34fbULL ) && uuid[0] & ( 0xffffffffULL == 0x00001000ULL ) ) - return true; - return false; -} diff --git a/src/tinyb/CMakeLists.txt b/src/tinyb/CMakeLists.txt deleted file mode 100644 index d87a1aab..00000000 --- a/src/tinyb/CMakeLists.txt +++ /dev/null @@ -1,88 +0,0 @@ -set (tinyb_LIB_INCLUDE_DIRS - ${PROJECT_SOURCE_DIR}/jaulib/include - ${PROJECT_SOURCE_DIR}/api - ${PROJECT_SOURCE_DIR}/api/tinyb - ${PROJECT_SOURCE_DIR}/include -) - -include_directories( - ${tinyb_LIB_INCLUDE_DIRS} - ${GLIB2_INCLUDE_DIRS} - ${GIO_INCLUDE_DIRS} - ${GIO-UNIX_INCLUDE_DIRS} - ${CMAKE_CURRENT_BINARY_DIR} -) - -set (tinyb_LIB_SRCS - ${PROJECT_SOURCE_DIR}/jaulib/src/dfa_utf8_decode.cpp - ${PROJECT_SOURCE_DIR}/jaulib/src/environment.cpp - ${PROJECT_SOURCE_DIR}/jaulib/src/debug.cpp - ${PROJECT_SOURCE_DIR}/jaulib/src/basic_types.cpp - ${PROJECT_SOURCE_DIR}/src/tinyb/BluetoothObject.cpp - ${PROJECT_SOURCE_DIR}/src/tinyb/BluetoothEvent.cpp - ${PROJECT_SOURCE_DIR}/src/tinyb/BluetoothManager.cpp - ${PROJECT_SOURCE_DIR}/src/tinyb/BluetoothAdapter.cpp - ${PROJECT_SOURCE_DIR}/src/tinyb/BluetoothDevice.cpp - ${PROJECT_SOURCE_DIR}/src/tinyb/BluetoothGattService.cpp - ${PROJECT_SOURCE_DIR}/src/tinyb/BluetoothGattCharacteristic.cpp - ${PROJECT_SOURCE_DIR}/src/tinyb/BluetoothGattDescriptor.cpp - ${PROJECT_SOURCE_DIR}/src/tinyb/BluetoothUUID.cpp - ${PROJECT_SOURCE_DIR}/src/tinyb/tinyb_utils.cpp -# autogenerated files - ${CMAKE_CURRENT_BINARY_DIR}/../version.c - ${CMAKE_CURRENT_BINARY_DIR}/orgbluez-dbus.c -) - -set (tinyb_LIB_GLOB_HEADERS - ${PROJECT_SOURCE_DIR}/api/tinyb.hpp -) - -find_program(GDBUS_CODEGEN NAMES gdbus-codegen) -if (NOT GDBUS_CODEGEN) - message(FATAL_ERROR "gdbus-codegen not found") -else () - message(STATUS "gdbus-codegen found") -endif () - -add_custom_command(OUTPUT orgbluez-dbus.c orgbluez-dbus.h - COMMAND ${GDBUS_CODEGEN} - --interface-prefix org.bluez - --generate-c-code orgbluez-dbus - --c-generate-object-manager ${PROJECT_SOURCE_DIR}/src/tinyb/org.bluez.xml - DEPENDS ${PROJECT_SOURCE_DIR}/src/tinyb/org.bluez.xml - COMMENT "Generating dbus code from org.bluez.xml") - -add_library (tinyb SHARED ${tinyb_LIB_SRCS}) -target_link_libraries ( - tinyb - unwind - ${CMAKE_THREAD_LIBS_INIT} - ${GLIB2_LIBRARIES} - ${GIO_LIBRARIES} -) - -if(USE_STRIP) -add_custom_command(TARGET tinyb POST_BUILD - COMMAND ${STRIP} ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_SHARED_LIBRARY_PREFIX}tinyb${CMAKE_SHARED_LIBRARY_SUFFIX}.${tinyb_VERSION_STRING} - COMMENT "stripping tinyb" - VERBATIM - ) -endif(USE_STRIP) - -set_target_properties( - tinyb - PROPERTIES - SOVERSION ${tinyb_VERSION_MAJOR} - VERSION ${tinyb_VERSION_STRING} -) -install (FILES ${tinyb_LIB_GLOB_HEADERS} DESTINATION include/) -install (DIRECTORY ${PROJECT_SOURCE_DIR}/api/tinyb/ DESTINATION include/tinyb) - -macro (tinyb_CREATE_INSTALL_PKGCONFIG generated_file install_location) - configure_file (${generated_file}.cmake ${CMAKE_CURRENT_BINARY_DIR}/${generated_file} @ONLY) - install (FILES ${CMAKE_CURRENT_BINARY_DIR}/${generated_file} DESTINATION ${install_location}) -endmacro (tinyb_CREATE_INSTALL_PKGCONFIG) -tinyb_create_install_pkgconfig (tinyb.pc lib${LIB_SUFFIX}/pkgconfig) - -install(TARGETS tinyb LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}) - diff --git a/src/tinyb/org.bluez.xml b/src/tinyb/org.bluez.xml deleted file mode 100644 index da200c6b..00000000 --- a/src/tinyb/org.bluez.xml +++ /dev/null @@ -1,195 +0,0 @@ -<?xml version="1.0"?> -<!-- -Author: Petre Eftime <[email protected]> -Copyright (c) 2015 Intel Corporation. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - -Author: Sven Gothel <[email protected]> -Copyright (c) 2020 Gothel Software e.K. - -Permission / License unchanged BSD style. - ---> -<node> - <interface name="org.bluez.Adapter1"> - <method name="StartDiscovery"/> - <method name="StopDiscovery"/> - <method name="RemoveDevice"> - <arg name="device" type="o" direction="in"/> - </method> - <method name="SetDiscoveryFilter"> - <arg name="filter" type="a{sv}" direction="in"/> - </method> - <method name="ConnectDevice"> - <arg name="value" type="o" direction="out"/> - <arg name="properties" type="a{sv}" direction="in"/> - </method> - <property name="Address" type="s" access="read"/> - <property name="Name" type="s" access="read"/> - <property name="Alias" type="s" access="readwrite"/> - <property name="Class" type="u" access="read"/> - <property name="Powered" type="b" access="readwrite"/> - <property name="Discoverable" type="b" access="readwrite"/> - <property name="DiscoverableTimeout" type="u" access="readwrite"/> - <property name="Pairable" type="b" access="readwrite"/> - <property name="PairableTimeout" type="u" access="readwrite"/> - <property name="Discovering" type="b" access="read"/> - <property name="UUIDs" type="as" access="read"/> - <property name="Modalias" type="s" access="read"/> - </interface> - - <interface name="org.bluez.Device1"> - <method name="Disconnect"/> - <method name="Connect"/> - <method name="ConnectProfile"> - <arg name="UUID" type="s" direction="in"/> - </method> - <method name="DisconnectProfile"> - <arg name="UUID" type="s" direction="in"/> - </method> - <method name="Pair"/> - <method name="CancelPairing"/> - <property name="Address" type="s" access="read"/> - <property name="Name" type="s" access="read"/> - <property name="Alias" type="s" access="readwrite"/> - <property name="Class" type="u" access="read"/> - <property name="Appearance" type="q" access="read"/> - <property name="Icon" type="s" access="read"/> - <property name="Paired" type="b" access="read"/> - <property name="Trusted" type="b" access="readwrite"/> - <property name="Blocked" type="b" access="readwrite"/> - <property name="LegacyPairing" type="b" access="read"/> - <property name="RSSI" type="n" access="read"/> - <property name="Connected" type="b" access="read"/> - <property name="UUIDs" type="as" access="read"/> - <property name="Modalias" type="s" access="read"/> - <property name="Adapter" type="o" access="read"/> - <property name="ManufacturerData" type="a{qv}" access="read"/> - <property name="ServiceData" type="a{sv}" access="read"/> - <property name="TxPower" type="n" access="read"/> - <property name="ServicesResolved" type="b" access="read"/> - </interface> - - <interface name="org.bluez.GattService1"> - <property name="UUID" type="s" access="read"/> - <property name="Device" type="o" access="read"/> - <property name="Primary" type="b" access="read"/> - <property name="Characteristics" type="ao" access="read"/> - </interface> - - <interface name="org.bluez.GattCharacteristic1"> - <method name="ReadValue"> - <arg name="value" type="ay" direction="out"> - <annotation name="org.gtk.GDBus.C.ForceGVariant" value="true"/> - </arg> - <arg name="options" type="a{sv}" direction="in"/> - </method> - <method name="WriteValue"> - <arg name="value" type="ay" byte_arrays="True" direction="in"> - <annotation name="org.gtk.GDBus.C.ForceGVariant" value="true"/> - </arg> - <arg name="options" type="a{sv}" direction="in"/> - </method> - <method name="StartNotify"/> - <method name="StopNotify"/> - <property name="UUID" type="s" access="read"/> - <property name="Service" type="o" access="read"/> - <property name="Value" type="ay" access="read"> - <annotation name="org.gtk.GDBus.C.ForceGVariant" value="true"/> - </property> - <property name="Notifying" type="b" access="read"/> - <property name="Flags" type="as" access="read"/> - <property name="Descriptors" type="ao" access="read"/> - </interface> - - <interface name="org.bluez.GattDescriptor1"> - <method name="ReadValue"> - <arg name="value" type="ay" direction="out"/> - <arg name="options" type="a{sv}" direction="in"/> - </method> - <method name="WriteValue"> - <arg name="value" type="ay" direction="in"/> - <arg name="options" type="a{sv}" direction="in"/> - </method> - <property name="UUID" type="s" access="read"/> - <property name="Characteristic" type="o" access="read"/> - <property name="Value" type="ay" access="read"/> - </interface> - - <interface name="org.bluez.LEAdvertisement1"> - <method name="Release"> - <annotation name="org.freedesktop.DBus.Method.NoReply" value="true"/> - </method> - <annotation name="org.freedesktop.DBus.Properties.PropertiesChanged" value="const"/> - <property name="Type" type="s" access="read"/> - <property name="ServiceUUIDs" type="as" access="read"/> - <property name="ManufacturerData" type="a{sv}" access="read"/> - <property name="SolicitUUIDs" type="as" access="read"/> - <property name="ServiceData" type="a{sv}" access="read"/> - <property name="IncludeTxPower" type="b" access="read"/> - </interface> - - <interface name="org.bluez.AgentManager1"> - <method name="RegisterAgent"> - <arg name="agent" type="o" direction="in" /> - <arg name="capability" type="s" direction="in" /> - </method> - <method name="UnregisterAgent"> - <arg name="agent" type="o" direction="in" /> - </method> - <method name="RequestDefaultAgent"> - <arg name="agent" type="o" direction="in" /> - </method> - </interface> - - <interface name="org.bluez.Agent1"> - <method name="Release"/> - <method name="RequestPinCode"> - <arg name="pincode" type="s" direction="out" /> - <arg name="device" type="o" direction="in" /> - </method> - <method name="DisplayPinCode"> - <arg name="device" type="o" direction="in" /> - <arg name="pincode" type="s" direction="in" /> - </method> - <method name="RequestPasskey"> - <arg name="passkey" type="u" direction="out" /> - <arg name="device" type="o" direction="in" /> - </method> - <method name="DisplayPasskey"> - <arg name="device" type="o" direction="in" /> - <arg name="passkey" type="u" direction="in" /> - <arg name="entered" type="q" direction="in" /> - </method> - <method name="RequestConfirmation"> - <arg name="device" type="o" direction="in" /> - <arg name="passkey" type="u" direction="in" /> - </method> - <method name="RequestAuthorization"> - <arg name="device" type="o" direction="in" /> - </method> - <method name="AuthorizeService"> - <arg name="device" type="o" direction="in" /> - <arg name="uuid" type="s" direction="in" /> - </method> - <method name="Cancel"/> - </interface> - -</node> diff --git a/src/tinyb/tinyb.pc.cmake b/src/tinyb/tinyb.pc.cmake deleted file mode 100644 index 1c9fbaf8..00000000 --- a/src/tinyb/tinyb.pc.cmake +++ /dev/null @@ -1,11 +0,0 @@ -prefix=@CMAKE_INSTALL_PREFIX@ -exec_prefix=${prefix} -libdir=${exec_prefix}/lib@LIB_SUFFIX@ -includedir=${prefix}/include - -Name: tinyb -Description: Tiny BLE library -Version: @tinyb_VERSION_STRING@ - -Libs: -L${libdir} -ltinyb -Cflags: -I${includedir} diff --git a/src/tinyb/tinyb_utils.cpp b/src/tinyb/tinyb_utils.cpp deleted file mode 100644 index 89c76b81..00000000 --- a/src/tinyb/tinyb_utils.cpp +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Author: Andrei Vasiliu <[email protected]> - * Copyright (c) 2015 Intel Corporation. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#include "tinyb_utils.hpp" -#include "BluetoothException.hpp" - -std::vector<unsigned char> tinyb::from_chars_to_vector(const gchar *chars) -{ - std::vector<unsigned char>::size_type chars_size = strlen((const char*)chars); - - if (chars_size == 0) - throw std::runtime_error("Trying to read empty value"); - - std::vector<unsigned char> result(chars, chars + chars_size); - - return result; -} - -std::vector<unsigned char> tinyb::from_gbytes_to_vector(const GBytes *bytes) -{ - gsize result_size; - const unsigned char *aux_array = (const unsigned char *)g_bytes_get_data(const_cast<GBytes *>(bytes), &result_size); - - if (aux_array == nullptr || result_size == 0) - throw std::runtime_error("Trying to read empty value"); - - std::vector<unsigned char> result(result_size); - std::copy(aux_array, aux_array + result_size, result.begin()); - - return result; -} - -/* it allocates memory - the result that is being returned is from heap */ -GBytes *tinyb::from_vector_to_gbytes(const std::vector<unsigned char>& vector) -{ - unsigned int vector_size = vector.size(); - const unsigned char *vector_content = vector.data(); - - GBytes *result = g_bytes_new(vector_content, vector_size); - if (result == nullptr) - throw std::bad_alloc(); - - return result; -} - -std::vector<unsigned char> tinyb::from_iter_to_vector(GVariant *iter) -{ - GVariantIter *value_iter; - guchar value_byte; - - g_variant_get (iter, - "ay", - &value_iter); - - if (value_iter == nullptr) - throw std::invalid_argument("GVariant should be a container of an array of bytes"); - - std::vector<unsigned char> value; - while (g_variant_iter_loop(value_iter, "y", &value_byte)) { - value.push_back(value_byte); - } - - g_variant_iter_free(value_iter); - return value; -} - -void tinyb::handle_error(GError *error) -{ - if (error != nullptr) { - BluetoothException e(error->message); - g_error_free(error); - throw e; - } -} |