diff --git a/csharp_package/brainflow/brainflow/board_controller_library.cs b/csharp_package/brainflow/brainflow/board_controller_library.cs index ca545b3aa..7ab6429a4 100644 --- a/csharp_package/brainflow/brainflow/board_controller_library.cs +++ b/csharp_package/brainflow/brainflow/board_controller_library.cs @@ -115,7 +115,9 @@ public enum BoardIds AAVAA_V3_BOARD = 53, EXPLORE_PLUS_8_CHAN_BOARD = 54, EXPLORE_PLUS_32_CHAN_BOARD = 55, - PIEEG_BOARD = 56 + PIEEG_BOARD = 56, + SYNCHRONI_3_CHANNELS_BOARD = 57, + SYNCHRONI_8_CHANNELS_BOARD = 58 }; diff --git a/java_package/brainflow/src/main/java/brainflow/BoardIds.java b/java_package/brainflow/src/main/java/brainflow/BoardIds.java index 6377c20af..2a21d3aca 100644 --- a/java_package/brainflow/src/main/java/brainflow/BoardIds.java +++ b/java_package/brainflow/src/main/java/brainflow/BoardIds.java @@ -65,7 +65,9 @@ public enum BoardIds AAVAA_V3_BOARD(53), EXPLORE_PLUS_8_CHAN_BOARD(54), EXPLORE_PLUS_32_CHAN_BOARD(55), - PIEEG_BOARD(56); + PIEEG_BOARD(56), + SYNCHRONI_3_CHANNELS_BOARD(57), + SYNCHRONI_8_CHANNELS_BOARD(58); private final int board_id; private static final Map bi_map = new HashMap (); diff --git a/julia_package/brainflow/src/board_shim.jl b/julia_package/brainflow/src/board_shim.jl index c21b94c83..d3dc4911b 100644 --- a/julia_package/brainflow/src/board_shim.jl +++ b/julia_package/brainflow/src/board_shim.jl @@ -61,6 +61,8 @@ export BrainFlowInputParams EXPLORE_PLUS_8_CHAN_BOARD = 54 EXPLORE_PLUS_32_CHAN_BOARD = 55 PIEEG_BOARD = 56 + SYNCHRONI_3_CHANNELS_BOARD = 57 + SYNCHRONI_8_CHANNELS_BOARD = 58 end diff --git a/matlab_package/brainflow/BoardIds.m b/matlab_package/brainflow/BoardIds.m index ceb601a86..69c655a6f 100644 --- a/matlab_package/brainflow/BoardIds.m +++ b/matlab_package/brainflow/BoardIds.m @@ -59,5 +59,7 @@ EXPLORE_PLUS_8_CHAN_BOARD(54) EXPLORE_PLUS_32_CHAN_BOARD(55) PIEEG_BOARD(56) + SYNCHRONI_3_CHANNELS_BOARD(57) + SYNCHRONI_8_CHANNELS_BOARD(58) end end \ No newline at end of file diff --git a/nodejs_package/brainflow/brainflow.types.ts b/nodejs_package/brainflow/brainflow.types.ts index c95ec7d1c..ed219d902 100644 --- a/nodejs_package/brainflow/brainflow.types.ts +++ b/nodejs_package/brainflow/brainflow.types.ts @@ -68,7 +68,9 @@ export enum BoardIds { ANT_NEURO_EE_511_BOARD = 51, EXPLORE_PLUS_8_CHAN_BOARD = 54, EXPLORE_PLUS_32_CHAN_BOARD = 55, - PIEEG_BOARD = 56 + PIEEG_BOARD = 56, + SYNCHRONI_3_CHANNELS_BOARD = 57, + SYNCHRONI_8_CHANNELS_BOARD = 58 } export enum IpProtocolTypes { diff --git a/python_package/brainflow/board_shim.py b/python_package/brainflow/board_shim.py index ced6ec9d5..34ca5c5e4 100644 --- a/python_package/brainflow/board_shim.py +++ b/python_package/brainflow/board_shim.py @@ -74,6 +74,8 @@ class BoardIds(enum.IntEnum): EXPLORE_PLUS_8_CHAN_BOARD = 54 #: EXPLORE_PLUS_32_CHAN_BOARD = 55 #: PIEEG_BOARD = 56 #: + SYNCHRONI_3_CHANNELS_BOARD = 57 #: + SYNCHRONI_8_CHANNELS_BOARD = 58 #: class IpProtocolTypes(enum.IntEnum): diff --git a/src/board_controller/board_controller.cpp b/src/board_controller/board_controller.cpp index 623499463..0b0c172c1 100644 --- a/src/board_controller/board_controller.cpp +++ b/src/board_controller/board_controller.cpp @@ -52,6 +52,7 @@ #include "pieeg_board.h" #include "playback_file_board.h" #include "streaming_board.h" +#include "synchroni_board.h" #include "synthetic_board.h" #include "unicorn_board.h" @@ -281,6 +282,12 @@ int prepare_session (int board_id, const char *json_brainflow_input_params) case BoardIds::PIEEG_BOARD: board = std::shared_ptr (new PIEEGBoard (board_id, params)); break; + case BoardIds::SYNCHRONI_3_CHANNELS_BOARD: + board = std::shared_ptr (new SynchroniBoard (board_id, params)); + break; + case BoardIds::SYNCHRONI_8_CHANNELS_BOARD: + board = std::shared_ptr (new SynchroniBoard (board_id, params)); + break; default: return (int)BrainFlowExitCodes::UNSUPPORTED_BOARD_ERROR; } diff --git a/src/board_controller/brainflow_boards.cpp b/src/board_controller/brainflow_boards.cpp index 22d5c91f4..543f4e074 100644 --- a/src/board_controller/brainflow_boards.cpp +++ b/src/board_controller/brainflow_boards.cpp @@ -74,7 +74,9 @@ BrainFlowBoards::BrainFlowBoards() {"53", json::object()}, {"54", json::object()}, {"55", json::object()}, - {"56", json::object()} + {"56", json::object()}, + {"57", json::object()}, + {"58", json::object()} } }}; @@ -1095,6 +1097,27 @@ BrainFlowBoards::BrainFlowBoards() {"eeg_channels", {1, 2, 3, 4, 5, 6, 7, 8}}, {"eeg_names", "Fp1,Fp2,C3,C4,P7,P8,O1,O2"} }; + // TODO update: + brainflow_boards_json["boards"]["57"]["default"] = { + {"name", "Synchroni3Channels"}, + {"sampling_rate", 250}, + {"package_num_channel", 0}, + {"timestamp_channel", 4}, + {"marker_channel", 5}, + {"num_rows", 6}, + {"eeg_channels", {1, 2}}, + {"ecg_channels", {3}} + }; + brainflow_boards_json["boards"]["58"]["default"] = { + {"name", "Synchroni8Channels"}, + {"sampling_rate", 250}, + {"package_num_channel", 0}, + {"timestamp_channel", 9}, + {"marker_channel", 10}, + {"num_rows", 11}, + {"eeg_channels", {1, 2, 3, 4, 5, 6, 7}}, + {"ecg_channels", {8}} + }; } BrainFlowBoards boards_struct; diff --git a/src/board_controller/build.cmake b/src/board_controller/build.cmake index aeeedbaa7..7baa52189 100644 --- a/src/board_controller/build.cmake +++ b/src/board_controller/build.cmake @@ -85,6 +85,7 @@ SET (BOARD_CONTROLLER_SRC ${CMAKE_CURRENT_SOURCE_DIR}/src/board_controller/ntl/ntl_wifi.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/board_controller/aavaa/aavaa_v3.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/board_controller/pieeg/pieeg_board.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/src/board_controller/synchroni/synchroni_board.cpp ) include (${CMAKE_CURRENT_SOURCE_DIR}/src/board_controller/ant_neuro/build.cmake) @@ -142,6 +143,7 @@ target_include_directories ( ${CMAKE_CURRENT_SOURCE_DIR}/src/board_controller/ntl/inc ${CMAKE_CURRENT_SOURCE_DIR}/src/board_controller/aavaa/inc ${CMAKE_CURRENT_SOURCE_DIR}/src/board_controller/pieeg/inc + ${CMAKE_CURRENT_SOURCE_DIR}/src/board_controller/synchroni/inc ) target_compile_definitions(${BOARD_CONTROLLER_NAME} PRIVATE NOMINMAX BRAINFLOW_VERSION=${BRAINFLOW_VERSION}) diff --git a/src/board_controller/synchroni/inc/synchroni_board.h b/src/board_controller/synchroni/inc/synchroni_board.h new file mode 100644 index 000000000..bde041f5b --- /dev/null +++ b/src/board_controller/synchroni/inc/synchroni_board.h @@ -0,0 +1,36 @@ +#include +#include +#include + +#include "ble_lib_board.h" +#include "board.h" +#include "board_controller.h" + +class SynchroniBoard : public BLELibBoard +{ + +public: + SynchroniBoard (int board_id, struct BrainFlowInputParams params); + ~SynchroniBoard (); + + int prepare_session (); + int start_stream (int buffer_size, const char *streamer_params); + int stop_stream (); + int release_session (); + int config_board (std::string config, std::string &response); + int config_board (std::string config); + + void adapter_1_on_scan_found (simpleble_adapter_t adapter, simpleble_peripheral_t peripheral); + void read_data ( + simpleble_uuid_t service, simpleble_uuid_t characteristic, uint8_t *data, size_t size); + +protected: + volatile simpleble_adapter_t synchroni_board_adapter; + volatile simpleble_peripheral_t synchroni_board_peripheral; + bool initialized; + bool is_streaming; + std::mutex m; + std::condition_variable cv; + std::pair notified_characteristics; + std::pair write_characteristics; +}; diff --git a/src/board_controller/synchroni/synchroni_board.cpp b/src/board_controller/synchroni/synchroni_board.cpp new file mode 100644 index 000000000..fb5204ad3 --- /dev/null +++ b/src/board_controller/synchroni/synchroni_board.cpp @@ -0,0 +1,380 @@ +#include + +#include "synchroni_board.h" + +#include "custom_cast.h" +#include "get_dll_dir.h" +#include "timestamp.h" + +#define SYNCHRONI_WRITE_CHAR "0000fe41-8e22-4541-9d4c-21edae82ed19" +#define SYNCHRONI_NOTIFY_CHAR "0000fe42-8e22-4541-9d4c-21edae82ed19" + + +static void synchroni_board_adapter_1_on_scan_found ( + simpleble_adapter_t adapter, simpleble_peripheral_t peripheral, void *board) +{ + ((SynchroniBoard *)(board))->adapter_1_on_scan_found (adapter, peripheral); +} + +static void synchroni_board_read_notifications (simpleble_uuid_t service, + simpleble_uuid_t characteristic, uint8_t *data, size_t size, void *board) +{ + ((SynchroniBoard *)(board))->read_data (service, characteristic, data, size); +} + +SynchroniBoard::SynchroniBoard (int board_id, struct BrainFlowInputParams params) + : BLELibBoard (board_id, params) +{ + initialized = false; + synchroni_board_adapter = NULL; + synchroni_board_peripheral = NULL; + is_streaming = false; +} + +SynchroniBoard::~SynchroniBoard () +{ + skip_logs = true; + release_session (); +} + +int SynchroniBoard::prepare_session () +{ + if (initialized) + { + safe_logger (spdlog::level::info, "Session is already prepared"); + return (int)BrainFlowExitCodes::STATUS_OK; + } + if (params.timeout < 1) + { + params.timeout = 5; + } + safe_logger (spdlog::level::info, "Use timeout for discovery: {}", params.timeout); + if (!init_dll_loader ()) + { + safe_logger (spdlog::level::err, "Failed to init dll_loader"); + return (int)BrainFlowExitCodes::GENERAL_ERROR; + } + size_t adapter_count = simpleble_adapter_get_count (); + if (adapter_count == 0) + { + safe_logger (spdlog::level::err, "No BLE adapters found"); + return (int)BrainFlowExitCodes::UNABLE_TO_OPEN_PORT_ERROR; + } + + synchroni_board_adapter = simpleble_adapter_get_handle (0); + if (synchroni_board_adapter == NULL) + { + safe_logger (spdlog::level::err, "Adapter is NULL"); + return (int)BrainFlowExitCodes::UNABLE_TO_OPEN_PORT_ERROR; + } + + simpleble_adapter_set_callback_on_scan_found ( + synchroni_board_adapter, ::synchroni_board_adapter_1_on_scan_found, (void *)this); + + if (!simpleble_adapter_is_bluetooth_enabled ()) + { + safe_logger (spdlog::level::warn, "Probably bluetooth is disabled."); + // dont throw an exception because of this + // https://github.com/OpenBluetoothToolbox/SimpleBLE/issues/115 + } + + simpleble_adapter_scan_start (synchroni_board_adapter); + int res = (int)BrainFlowExitCodes::STATUS_OK; + std::unique_lock lk (m); + auto sec = std::chrono::seconds (1); + if (cv.wait_for ( + lk, params.timeout * sec, [this] { return this->synchroni_board_peripheral != NULL; })) + { + safe_logger (spdlog::level::info, "Found SynchroniBoard device"); + } + else + { + safe_logger (spdlog::level::err, "Failed to find SynchroniBoard Device"); + res = (int)BrainFlowExitCodes::BOARD_NOT_READY_ERROR; + } + simpleble_adapter_scan_stop (synchroni_board_adapter); + if (res == (int)BrainFlowExitCodes::STATUS_OK) + { + // for safety + for (int i = 0; i < 3; i++) + { + if (simpleble_peripheral_connect (synchroni_board_peripheral) == SIMPLEBLE_SUCCESS) + { + safe_logger (spdlog::level::info, "Connected to SynchroniBoard Device"); + res = (int)BrainFlowExitCodes::STATUS_OK; + + break; + } + else + { + safe_logger ( + spdlog::level::warn, "Failed to connect to SynchroniBoard Device: {}/3", i); + res = (int)BrainFlowExitCodes::BOARD_NOT_READY_ERROR; +#ifdef _WIN32 + Sleep (1000); +#else + sleep (1); +#endif + } + } + } + else + { +// https://github.com/OpenBluetoothToolbox/SimpleBLE/issues/26#issuecomment-955606799 +#ifdef __linux__ + usleep (1000000); +#endif + } + + bool control_characteristics_found = false; + + if (res == (int)BrainFlowExitCodes::STATUS_OK) + { + size_t services_count = simpleble_peripheral_services_count (synchroni_board_peripheral); + for (size_t i = 0; i < services_count; i++) + { + simpleble_service_t service; + if (simpleble_peripheral_services_get (synchroni_board_peripheral, i, &service) != + SIMPLEBLE_SUCCESS) + { + safe_logger (spdlog::level::err, "failed to get service"); + res = (int)BrainFlowExitCodes::BOARD_NOT_READY_ERROR; + } + + safe_logger (spdlog::level::trace, "found servce {}", service.uuid.value); + for (size_t j = 0; j < service.characteristic_count; j++) + { + safe_logger (spdlog::level::trace, "found characteristic {}", + service.characteristics[j].uuid.value); + + if (strcmp (service.characteristics[j].uuid.value, + SYNCHRONI_WRITE_CHAR) == 0) // Write Characteristics + { + write_characteristics = std::pair ( + service.uuid, service.characteristics[j].uuid); + control_characteristics_found = true; + safe_logger (spdlog::level::info, "found control characteristic"); + } + if (strcmp (service.characteristics[j].uuid.value, + SYNCHRONI_NOTIFY_CHAR) == 0) // Notification Characteristics + { + if (simpleble_peripheral_notify (synchroni_board_peripheral, service.uuid, + service.characteristics[j].uuid, ::synchroni_board_read_notifications, + (void *)this) == SIMPLEBLE_SUCCESS) + { + + notified_characteristics = std::pair ( + service.uuid, service.characteristics[j].uuid); + } + else + { + safe_logger (spdlog::level::err, "Failed to notify for {} {}", + service.uuid.value, service.characteristics[j].uuid.value); + res = (int)BrainFlowExitCodes::GENERAL_ERROR; + } + } + } + } + } + + if ((res == (int)BrainFlowExitCodes::STATUS_OK) && (control_characteristics_found)) + { + initialized = true; + } + else + { + release_session (); + } + return res; +} + +int SynchroniBoard::start_stream (int buffer_size, const char *streamer_params) +{ + if (!initialized) + { + return (int)BrainFlowExitCodes::BOARD_NOT_CREATED_ERROR; + } + int res = prepare_for_acquisition (buffer_size, streamer_params); + + if (res == (int)BrainFlowExitCodes::STATUS_OK) + { + // todo send smth to enable streaming + res = config_board (""); + } + if (res == (int)BrainFlowExitCodes::STATUS_OK) + { + is_streaming = true; + } + + return res; +} + +int SynchroniBoard::stop_stream () +{ + if (synchroni_board_peripheral == NULL) + { + return (int)BrainFlowExitCodes::BOARD_NOT_CREATED_ERROR; + } + int res = (int)BrainFlowExitCodes::STATUS_OK; + if (is_streaming) + { + // todo send smth to stop streaming + res = config_board (""); + } + else + { + res = (int)BrainFlowExitCodes::STREAM_ALREADY_RUN_ERROR; + } + is_streaming = false; + return res; +} + +int SynchroniBoard::release_session () +{ + if (initialized) + { + // repeat it multiple times, failure here may lead to a crash + for (int i = 0; i < 2; i++) + { + stop_stream (); + // need to wait for notifications to stop triggered before unsubscribing, otherwise + // macos fails inside simpleble with timeout +#ifdef _WIN32 + Sleep (2000); +#else + sleep (2); +#endif + if (simpleble_peripheral_unsubscribe (synchroni_board_peripheral, + notified_characteristics.first, + notified_characteristics.second) != SIMPLEBLE_SUCCESS) + { + safe_logger (spdlog::level::err, "failed to unsubscribe for {} {}", + notified_characteristics.first.value, notified_characteristics.second.value); + } + else + { + break; + } + } + free_packages (); + initialized = false; + } + if (synchroni_board_peripheral != NULL) + { + bool is_connected = false; + if (simpleble_peripheral_is_connected (synchroni_board_peripheral, &is_connected) == + SIMPLEBLE_SUCCESS) + { + if (is_connected) + { + simpleble_peripheral_disconnect (synchroni_board_peripheral); + } + } + simpleble_peripheral_release_handle (synchroni_board_peripheral); + synchroni_board_peripheral = NULL; + } + if (synchroni_board_adapter != NULL) + { + simpleble_adapter_release_handle (synchroni_board_adapter); + synchroni_board_adapter = NULL; + } + + return (int)BrainFlowExitCodes::STATUS_OK; +} + +int SynchroniBoard::config_board (std::string config, std::string &response) +{ + return config_board (config); +} + +int SynchroniBoard::config_board (std::string config) +{ + if (!initialized) + { + return (int)BrainFlowExitCodes::BOARD_NOT_CREATED_ERROR; + } + + uint8_t *command = new uint8_t[config.size ()]; + memcpy (command, config.c_str (), config.size ()); + if (simpleble_peripheral_write_command (synchroni_board_peripheral, write_characteristics.first, + write_characteristics.second, command, config.size ()) != SIMPLEBLE_SUCCESS) + { + safe_logger (spdlog::level::err, "failed to send command {} to device", config.c_str ()); + delete[] command; + return (int)BrainFlowExitCodes::BOARD_WRITE_ERROR; + } + delete[] command; + return (int)BrainFlowExitCodes::STATUS_OK; +} + +void SynchroniBoard::adapter_1_on_scan_found ( + simpleble_adapter_t adapter, simpleble_peripheral_t peripheral) +{ + char *peripheral_identified = simpleble_peripheral_identifier (peripheral); + char *peripheral_address = simpleble_peripheral_address (peripheral); + simpleble_manufacturer_data_t manufacturer_data; + bool found = false; + + + size_t data_count = simpleble_peripheral_manufacturer_data_count (peripheral); + for (size_t i = 0; i < data_count; i++) + { + if (simpleble_peripheral_manufacturer_data_get (peripheral, i, &manufacturer_data) == + SIMPLEBLE_SUCCESS) + { + safe_logger (spdlog::level::info, "id: {}", manufacturer_data.manufacturer_id); + for (size_t j = 0; j < manufacturer_data.data_length; j++) + { + safe_logger (spdlog::level::info, "data: {} {}", j, manufacturer_data.data[j]); + } + } + } + if (!params.mac_address.empty ()) + { + if (strcmp (peripheral_address, params.mac_address.c_str ()) == 0) + { + found = true; + } + } + else + { + if (!params.serial_number.empty ()) + { + if (strcmp (peripheral_identified, params.serial_number.c_str ()) == 0) + { + found = true; + } + } + else + { + if (strncmp (peripheral_identified, "BA_FLEX", 7) == 0) + { + found = true; + } + } + } + + safe_logger (spdlog::level::trace, "address {}", peripheral_address); + simpleble_free (peripheral_address); + safe_logger (spdlog::level::trace, "identifier {}", peripheral_identified); + simpleble_free (peripheral_identified); + + if (found) + { + { + std::lock_guard lk (m); + synchroni_board_peripheral = peripheral; + } + cv.notify_one (); + } + else + { + simpleble_peripheral_release_handle (peripheral); + } +} + +void SynchroniBoard::read_data ( + simpleble_uuid_t service, simpleble_uuid_t characteristic, uint8_t *data, size_t size) +{ + // todo implement +} diff --git a/src/utils/inc/brainflow_constants.h b/src/utils/inc/brainflow_constants.h index 26034af5b..85b764bb6 100644 --- a/src/utils/inc/brainflow_constants.h +++ b/src/utils/inc/brainflow_constants.h @@ -88,9 +88,11 @@ enum class BoardIds : int EXPLORE_PLUS_8_CHAN_BOARD = 54, EXPLORE_PLUS_32_CHAN_BOARD = 55, PIEEG_BOARD = 56, + SYNCHRONI_3_CHANNELS_BOARD = 57, + SYNCHRONI_8_CHANNELS_BOARD = 58, // use it to iterate FIRST = PLAYBACK_FILE_BOARD, - LAST = PIEEG_BOARD + LAST = SYNCHRONI_8_CHANNELS_BOARD }; enum class IpProtocolTypes : int diff --git a/third_party/SimpleBLE/.github/FUNDING.yml b/third_party/SimpleBLE/.github/FUNDING.yml new file mode 100644 index 000000000..f6ab0f4d8 --- /dev/null +++ b/third_party/SimpleBLE/.github/FUNDING.yml @@ -0,0 +1,13 @@ +# These are supported funding model platforms + +github: [kdewald] # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/third_party/SimpleBLE/.github/workflows/ci_build_examples.yml b/third_party/SimpleBLE/.github/workflows/ci_build_examples.yml index 8794effc7..9dc285e75 100644 --- a/third_party/SimpleBLE/.github/workflows/ci_build_examples.yml +++ b/third_party/SimpleBLE/.github/workflows/ci_build_examples.yml @@ -6,59 +6,40 @@ jobs: # ------------------------------------------------------------ build-windows: - runs-on: ${{ matrix.os }} - - strategy: - fail-fast: false - max-parallel: 4 - matrix: - os: [windows-2019] - # For windows-2022, the generator is for "Visual Studio 17 2022" + runs-on: windows-2022 steps: - name: Clone Repository uses: actions/checkout@v3 - name: Add msbuild to PATH - uses: microsoft/setup-msbuild@v1.0.2 - - name: Compile Examples for Windows + uses: microsoft/setup-msbuild@v1.1 + - name: Compile Examples run: | - cmake -B %GITHUB_WORKSPACE%\build_simpleble_examples -G "Visual Studio 16 2019" -DCMAKE_SYSTEM_VERSION=10.0.22000.0 -S %GITHUB_WORKSPACE%/examples/simpleble - cmake --build %GITHUB_WORKSPACE%\build_simpleble_examples --config Release --parallel 4 + cmake -B %GITHUB_WORKSPACE%\build -G "Visual Studio 17 2022" -DCMAKE_SYSTEM_VERSION=10.0.22000.0 -S %GITHUB_WORKSPACE%/examples/simpleble + cmake --build %GITHUB_WORKSPACE%\build --config Release --parallel 4 shell: cmd # ------------------------------------------------------------ build-macos: - runs-on: ${{ matrix.os }} - - strategy: - fail-fast: false - max-parallel: 4 - matrix: - os: [macos-11.0] + runs-on: macos-12 steps: - name: Clone Repository uses: actions/checkout@v3 - name: Setup Cmake - uses: jwlawson/actions-setup-cmake@v1.12 + uses: jwlawson/actions-setup-cmake@v1.13 with: - cmake-version: '3.21.x' - - name: Compile Examples for MacOS + cmake-version: '3.21' + - name: Compile Examples run: | - cmake -B $GITHUB_WORKSPACE/build_simpleble_examples -DCMAKE_BUILD_TYPE=Release -S $GITHUB_WORKSPACE/examples/simpleble - cmake --build $GITHUB_WORKSPACE/build_simpleble_examples --config Release --parallel 4 + cmake -B $GITHUB_WORKSPACE/build -DCMAKE_BUILD_TYPE=Release -S $GITHUB_WORKSPACE/examples/simpleble + cmake --build $GITHUB_WORKSPACE/build --config Release --parallel 4 # ------------------------------------------------------------ build-linux: - runs-on: ${{ matrix.os }} - - strategy: - fail-fast: false - max-parallel: 4 - matrix: - os: [ubuntu-20.04] + runs-on: ubuntu-22.04 steps: - name: Clone Repository @@ -70,9 +51,9 @@ jobs: env: DEBIAN_FRONTEND: noninteractive - name: Setup Cmake - uses: jwlawson/actions-setup-cmake@v1.12 + uses: jwlawson/actions-setup-cmake@v1.13 with: - cmake-version: '3.21.x' + cmake-version: '3.21' - name: Compile SimpleBLE Examples for Ubuntu run: | cmake -B $GITHUB_WORKSPACE/build_simpleble_examples -DCMAKE_BUILD_TYPE=Release -S $GITHUB_WORKSPACE/examples/simpleble @@ -84,4 +65,4 @@ jobs: - name: Compile SimpleDBus Examples for Ubuntu run: | cmake -B $GITHUB_WORKSPACE/build_simpledbus_examples -DCMAKE_BUILD_TYPE=Release -S $GITHUB_WORKSPACE/examples/simpledbus - cmake --build $GITHUB_WORKSPACE/build_simpledbus_examples --config Release --parallel 4 \ No newline at end of file + cmake --build $GITHUB_WORKSPACE/build_simpledbus_examples --config Release --parallel 4 diff --git a/third_party/SimpleBLE/.github/workflows/ci_build_lib.yml b/third_party/SimpleBLE/.github/workflows/ci_build_lib.yml deleted file mode 100644 index bcfc26fea..000000000 --- a/third_party/SimpleBLE/.github/workflows/ci_build_lib.yml +++ /dev/null @@ -1,115 +0,0 @@ -name: CI Build Libs - -on: [push, pull_request] - -jobs: - - # ------------------------------------------------------------ - build-windows: - runs-on: ${{ matrix.os }} - - strategy: - fail-fast: false - max-parallel: 4 - matrix: - os: [windows-2019] - # For windows-2022, the generator is for "Visual Studio 17 2022" - - steps: - - name: Clone Repository - uses: actions/checkout@v3 - - name: Add msbuild to PATH - uses: microsoft/setup-msbuild@v1.0.2 - - name: Compile SimpleBLE for Windows x86 - Windows SDK 10.0.19041.0 - run: | - cmake -B %GITHUB_WORKSPACE%\build32_19041 -G "Visual Studio 16 2019" -A Win32 -DCMAKE_SYSTEM_VERSION=10.0.19041.0 -S %GITHUB_WORKSPACE%/simpleble - cmake --build %GITHUB_WORKSPACE%\build32_19041 --config Release --parallel 4 - cmake --install %GITHUB_WORKSPACE%\build32_19041 --prefix %GITHUB_WORKSPACE%\build32_19041\install - shell: cmd - - name: Compile SimpleBLE for Windows x64 - Windows SDK 10.0.19041.0 - run: | - cmake -B %GITHUB_WORKSPACE%\build64_19041 -G "Visual Studio 16 2019" -A x64 -DCMAKE_SYSTEM_VERSION=10.0.19401.0 -S %GITHUB_WORKSPACE%/simpleble - cmake --build %GITHUB_WORKSPACE%\build64_19041 --config Release --parallel 4 - cmake --install %GITHUB_WORKSPACE%\build64_19041 --prefix %GITHUB_WORKSPACE%\build64_19041\install - shell: cmd - - name: Compile SimpleBLE for Windows x86 - Windows SDK 10.0.22000.0 - run: | - cmake -B %GITHUB_WORKSPACE%\build32 -G "Visual Studio 16 2019" -A Win32 -DCMAKE_SYSTEM_VERSION=10.0.22000.0 -S %GITHUB_WORKSPACE%/simpleble - cmake --build %GITHUB_WORKSPACE%\build32 --config Release --parallel 4 - cmake --install %GITHUB_WORKSPACE%\build32 --prefix %GITHUB_WORKSPACE%\build32\install - shell: cmd - - name: Compile SimpleBLE for Windows x64 - Windows SDK 10.0.22000.0 - run: | - cmake -B %GITHUB_WORKSPACE%\build64 -G "Visual Studio 16 2019" -A x64 -DCMAKE_SYSTEM_VERSION=10.0.22000.0 -S %GITHUB_WORKSPACE%/simpleble - cmake --build %GITHUB_WORKSPACE%\build64 --config Release --parallel 4 - cmake --install %GITHUB_WORKSPACE%\build64 --prefix %GITHUB_WORKSPACE%\build64\install - shell: cmd - - # ------------------------------------------------------------ - - build-macos: - runs-on: ${{ matrix.os }} - - strategy: - fail-fast: false - max-parallel: 4 - matrix: - os: [macos-11.0] - - steps: - - name: Clone Repository - uses: actions/checkout@v3 - - name: Setup Cmake - uses: jwlawson/actions-setup-cmake@v1.12 - with: - cmake-version: '3.21.x' - - name: Compile SimpleBLE for MacOS arm64 - run: | - cmake -B $GITHUB_WORKSPACE/build_arm64 -DCMAKE_OSX_ARCHITECTURES="arm64" -DCMAKE_BUILD_TYPE=Release -S $GITHUB_WORKSPACE/simpleble - cmake --build $GITHUB_WORKSPACE/build_arm64 --config Release --parallel 4 - cmake --install $GITHUB_WORKSPACE/build_arm64 --prefix $GITHUB_WORKSPACE/build_arm64/install - - name: Compile SimpleBLE for MacOS x86 - run: | - cmake -B $GITHUB_WORKSPACE/build_x86 -DCMAKE_OSX_ARCHITECTURES="x86_64" -DCMAKE_BUILD_TYPE=Release -S $GITHUB_WORKSPACE/simpleble - cmake --build $GITHUB_WORKSPACE/build_x86 --config Release --parallel 4 - cmake --install $GITHUB_WORKSPACE/build_x86 --prefix $GITHUB_WORKSPACE/build_x86/install - - # ------------------------------------------------------------ - - build-linux: - runs-on: ${{ matrix.os }} - - strategy: - fail-fast: false - max-parallel: 4 - matrix: - os: [ubuntu-20.04] - - steps: - - name: Clone Repository - uses: actions/checkout@v3 - - name: Install Dependencies - run: | - sudo -H apt-get update -y - sudo -H apt-get install -y libdbus-1-dev - env: - DEBIAN_FRONTEND: noninteractive - - name: Setup Cmake - uses: jwlawson/actions-setup-cmake@v1.12 - with: - cmake-version: '3.21.x' - - name: Compile SimpleBLE for Ubuntu - run: | - cmake -B $GITHUB_WORKSPACE/build_simpleble -DCMAKE_BUILD_TYPE=Release -S $GITHUB_WORKSPACE/simpleble - cmake --build $GITHUB_WORKSPACE/build_simpleble --config Release --parallel 4 - cmake --install $GITHUB_WORKSPACE/build_simpleble --prefix $GITHUB_WORKSPACE/build_simpleble/install - - name: Compile SimpleBluez for Ubuntu - run: | - cmake -B $GITHUB_WORKSPACE/build_simplebluez -DCMAKE_BUILD_TYPE=Release -S $GITHUB_WORKSPACE/simplebluez - cmake --build $GITHUB_WORKSPACE/build_simplebluez --config Release --parallel 4 - cmake --install $GITHUB_WORKSPACE/build_simplebluez --prefix $GITHUB_WORKSPACE/build_simplebluez/install - - name: Compile SimpleDBus for Ubuntu - run: | - cmake -B $GITHUB_WORKSPACE/build_simpledbus -DCMAKE_BUILD_TYPE=Release -S $GITHUB_WORKSPACE/simpledbus - cmake --build $GITHUB_WORKSPACE/build_simpledbus --config Release --parallel 4 - cmake --install $GITHUB_WORKSPACE/build_simpledbus --prefix $GITHUB_WORKSPACE/build_simpledbus/install diff --git a/third_party/SimpleBLE/.github/workflows/ci_cpp_release.yml b/third_party/SimpleBLE/.github/workflows/ci_cpp_release.yml new file mode 100644 index 000000000..b47c441b5 --- /dev/null +++ b/third_party/SimpleBLE/.github/workflows/ci_cpp_release.yml @@ -0,0 +1,205 @@ +name: Cpp Release + +on: + release: + types: [published] + workflow_dispatch: + inputs: + tag: + description: "The tag to upload artifacts" + required: true + +jobs: + + # ------------------------------------------------------------ + + cpp-release-linux: + runs-on: ubuntu-latest + + strategy: + fail-fast: false + max-parallel: 4 + matrix: + options: [ + {container: dockcross/linux-x64, target: linux-x64}, + {container: dockcross/linux-x86, target: linux-x86}, + {container: dockcross/linux-armv6-lts, target: linux-armv6}, + ] + type: [shared, static] + + container: + image: ${{ matrix.options.container }} + steps: + - name: Clone repository + uses: actions/checkout@v3 + env: + TAG: ${{ inputs.tag || github.ref }} + with: + ref: ${{ env.TAG }} + + - name: Build Expat + run: | + git clone https://github.com/libexpat/libexpat.git /tmp/libexpat + cd /tmp/libexpat/expat + + cmake -B /tmb/expat/build -S /tmp/libexpat/expat -DEXPAT_BUILD_DOCS=OFF -DEXPAT_BUILD_EXAMPLES=OFF -DEXPAT_BUILD_TESTS=OFF + cmake --build /tmb/expat/build --config Release --parallel 4 + cmake --install /tmb/expat/build --prefix /tmp/expat/install + + - name: Build DBus + run: | + git clone https://gitlab.freedesktop.org/dbus/dbus.git /tmp/dbus + + export CMAKE_PREFIX_PATH=/tmp/expat/install:$CMAKE_PREFIX_PATH + + cmake -B /tmb/dbus/build -S /tmp/dbus -DDBUS_SESSION_SOCKET_DIR=/usr/local/var/run/dbus/system_bus_socket -DDBUS_BUILD_TESTS=OFF + cmake --build /tmb/dbus/build --config Release --parallel 4 + cmake --install /tmb/dbus/build --prefix /tmp/dbus/install + + - name: Build SimpleBLE + run: | + GITHUB_WORKSPACE=$(pwd) + + if [ "${{ matrix.type }}" = "shared" ]; then + BUILD_SHARED_LIBS=ON + else + BUILD_SHARED_LIBS=OFF + fi + + export CMAKE_PREFIX_PATH=/tmp/dbus/install:$CMAKE_PREFIX_PATH + + cmake -B $GITHUB_WORKSPACE/build_simpleble -DCMAKE_BUILD_TYPE=Release -S $GITHUB_WORKSPACE/simpleble -DBUILD_SHARED_LIBS=$BUILD_SHARED_LIBS + cmake --build $GITHUB_WORKSPACE/build_simpleble --config Release --parallel 4 + cmake --install $GITHUB_WORKSPACE/build_simpleble --prefix $GITHUB_WORKSPACE/build_simpleble/install + + mkdir -p $GITHUB_WORKSPACE/artifacts + zip -r $GITHUB_WORKSPACE/artifacts/simpleble_${{ matrix.type }}_${{ matrix.options.target }}.zip $GITHUB_WORKSPACE/build_simpleble/install + + - name: Upload binaries to job + uses: actions/upload-artifact@v3 + with: + name: simpleble_${{ matrix.type }}_${{ matrix.options.target }} + path: artifacts/simpleble_${{ matrix.type }}_${{ matrix.options.target }}.zip + + - name: Upload binaries to release + uses: svenstaro/upload-release-action@v2 + env: + TAG: ${{ inputs.tag || github.ref }} + with: + file: ${{ github.workspace }}/artifacts/**/* + tag: ${{ env.TAG }} + overwrite: true + file_glob: true + + # ------------------------------------------------------------ + + cpp-release-windows: + runs-on: windows-2022 + + strategy: + fail-fast: false + max-parallel: 4 + matrix: + arch: [Win32, x64] + type: [shared, static] + + steps: + - name: Clone repository + uses: actions/checkout@v3 + env: + TAG: ${{ inputs.tag || github.ref }} + with: + ref: ${{ env.TAG }} + + - name: Add msbuild to PATH + uses: microsoft/setup-msbuild@v1.1 + + - name: Compile SimpleBLE + shell: cmd + run: | + + if "${{ matrix.type }}" == "shared" ( + set BUILD_SHARED_LIBS=ON + ) else ( + set BUILD_SHARED_LIBS=OFF + ) + + cmake -B %GITHUB_WORKSPACE%\build -G "Visual Studio 17 2022" -A ${{ matrix.arch }} -DCMAKE_SYSTEM_VERSION="10.0.19041.0" -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=%BUILD_SHARED_LIBS% -S %GITHUB_WORKSPACE%/simpleble + cmake --build %GITHUB_WORKSPACE%\build --config Release --parallel 4 + cmake --install %GITHUB_WORKSPACE%\build --prefix %GITHUB_WORKSPACE%\build\install + + mkdir -p $GITHUB_WORKSPACE\artifacts + 7z a -tzip %GITHUB_WORKSPACE%\artifacts\simpleble_${{ matrix.type }}_windows-${{ matrix.arch }}.zip %GITHUB_WORKSPACE%\build\install + + - name: Upload binaries to job + uses: actions/upload-artifact@v3 + with: + name: simpleble_${{ matrix.type }}_windows-${{ matrix.arch }} + path: artifacts/simpleble_${{ matrix.type }}_windows-${{ matrix.arch }}.zip + + - name: Upload binaries to release + uses: svenstaro/upload-release-action@v2 + env: + TAG: ${{ inputs.tag || github.ref }} + with: + file: ${{ github.workspace }}/artifacts/**/* + tag: ${{ env.TAG }} + overwrite: true + file_glob: true + + # ------------------------------------------------------------ + + cpp-release-macos: + runs-on: macos-12 + + strategy: + fail-fast: false + max-parallel: 4 + matrix: + arch: [arm64, x86_64] + type: [shared, static] + + steps: + - name: Clone repository + uses: actions/checkout@v3 + env: + TAG: ${{ inputs.tag || github.ref }} + with: + ref: ${{ env.TAG }} + + - name: Setup CMake + uses: jwlawson/actions-setup-cmake@v1.13 + with: + cmake-version: '3.21' + + - name: Compile SimpleBLE + run: | + + if [ "${{ matrix.type }}" = "shared" ]; then + BUILD_SHARED_LIBS=ON + else + BUILD_SHARED_LIBS=OFF + fi + + cmake -B $GITHUB_WORKSPACE/build -DCMAKE_OSX_ARCHITECTURES="${{ matrix.arch }}" -DCMAKE_BUILD_TYPE=Release -S $GITHUB_WORKSPACE/simpleble -DBUILD_SHARED_LIBS=$BUILD_SHARED_LIBS + cmake --build $GITHUB_WORKSPACE/build --config Release --parallel 4 + cmake --install $GITHUB_WORKSPACE/build --prefix $GITHUB_WORKSPACE/build/install + + mkdir -p $GITHUB_WORKSPACE/artifacts + zip -r $GITHUB_WORKSPACE/artifacts/simpleble_${{ matrix.type }}_macos-${{ matrix.arch }}.zip $GITHUB_WORKSPACE/build/install + + - name: Upload binaries to job + uses: actions/upload-artifact@v3 + with: + name: simpleble_${{ matrix.type }}_macos-${{ matrix.arch }} + path: artifacts/simpleble_${{ matrix.type }}_macos-${{ matrix.arch }}.zip + + - name: Upload binaries to release + uses: svenstaro/upload-release-action@v2 + env: + TAG: ${{ inputs.tag || github.ref }} + with: + file: ${{ github.workspace }}/artifacts/**/* + tag: ${{ env.TAG }} + overwrite: true + file_glob: true diff --git a/third_party/SimpleBLE/.github/workflows/ci_cpp_release_test.yml b/third_party/SimpleBLE/.github/workflows/ci_cpp_release_test.yml new file mode 100644 index 000000000..2d4edbb2a --- /dev/null +++ b/third_party/SimpleBLE/.github/workflows/ci_cpp_release_test.yml @@ -0,0 +1,163 @@ +name: Cpp Release Test + +on: + # push: + # pull_request: + workflow_dispatch: + +jobs: + # ------------------------------------------------------------ + + cpp-release-linux: + runs-on: ubuntu-latest + + strategy: + fail-fast: false + max-parallel: 4 + matrix: + library: [ + {lib: simpledbus, name: SimpleDBus}, + {lib: simplebluez, name: SimpleBluez}, + {lib: simpleble, name: SimpleBLE}, + ] + options: [ + {container: dockcross/linux-x64, target: linux-x64}, + {container: dockcross/linux-x86, target: linux-x86}, + {container: dockcross/linux-armv6-lts, target: linux-armv6}, + ] + type: [shared, static] + + container: + image: ${{ matrix.options.container }} + steps: + - name: Clone repository + uses: actions/checkout@v3 + + - name: Build Expat + run: | + git clone https://github.com/libexpat/libexpat.git /tmp/libexpat + cd /tmp/libexpat/expat + + cmake -B /tmb/expat/build -S /tmp/libexpat/expat -DEXPAT_BUILD_DOCS=OFF -DEXPAT_BUILD_EXAMPLES=OFF -DEXPAT_BUILD_TESTS=OFF + cmake --build /tmb/expat/build --config Release --parallel 4 + cmake --install /tmb/expat/build --prefix /tmp/expat/install + + - name: Build DBus + run: | + git clone https://gitlab.freedesktop.org/dbus/dbus.git /tmp/dbus + + export CMAKE_PREFIX_PATH=/tmp/expat/install:$CMAKE_PREFIX_PATH + + cmake -B /tmb/dbus/build -S /tmp/dbus -DDBUS_SESSION_SOCKET_DIR=/usr/local/var/run/dbus/system_bus_socket -DDBUS_BUILD_TESTS=OFF + cmake --build /tmb/dbus/build --config Release --parallel 4 + cmake --install /tmb/dbus/build --prefix /tmp/dbus/install + + - name: Build ${{ matrix.library.name }} + run: | + GITHUB_WORKSPACE=$(pwd) + + if [ "${{ matrix.type }}" = "shared" ]; then + BUILD_SHARED_LIBS=ON + else + BUILD_SHARED_LIBS=OFF + fi + + export CMAKE_PREFIX_PATH=/tmp/dbus/install:$CMAKE_PREFIX_PATH + + cmake -B $GITHUB_WORKSPACE/build_${{ matrix.library.lib }} -DCMAKE_BUILD_TYPE=Release -S $GITHUB_WORKSPACE/${{ matrix.library.lib }} -DBUILD_SHARED_LIBS=$BUILD_SHARED_LIBS + cmake --build $GITHUB_WORKSPACE/build_${{ matrix.library.lib }} --config Release --parallel 4 + cmake --install $GITHUB_WORKSPACE/build_${{ matrix.library.lib }} --prefix $GITHUB_WORKSPACE/build_${{ matrix.library.lib }}/install + + mkdir -p $GITHUB_WORKSPACE/artifacts + zip -r $GITHUB_WORKSPACE/artifacts/${{ matrix.library.lib }}_${{ matrix.type }}_${{ matrix.options.target }}.zip $GITHUB_WORKSPACE/build_${{ matrix.library.lib }}/install + + - name: Upload binaries to job + uses: actions/upload-artifact@v3 + with: + name: ${{ matrix.library.lib }}_${{ matrix.type }}_${{ matrix.options.target }} + path: artifacts/${{ matrix.library.lib }}_${{ matrix.type }}_${{ matrix.options.target }}.zip + + # ------------------------------------------------------------ + + cpp-release-windows: + runs-on: windows-2022 + + strategy: + fail-fast: false + max-parallel: 4 + matrix: + arch: [Win32, x64] + type: [shared, static] + + steps: + - name: Clone repository + uses: actions/checkout@v3 + + - name: Add msbuild to PATH + uses: microsoft/setup-msbuild@v1.1 + + - name: Compile SimpleBLE + shell: cmd + run: | + + if "${{ matrix.type }}" == "shared" ( + set BUILD_SHARED_LIBS=ON + ) else ( + set BUILD_SHARED_LIBS=OFF + ) + + cmake -B %GITHUB_WORKSPACE%\build -G "Visual Studio 17 2022" -A ${{ matrix.arch }} -DCMAKE_SYSTEM_VERSION="10.0.19041.0" -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=%BUILD_SHARED_LIBS% -S %GITHUB_WORKSPACE%/simpleble + cmake --build %GITHUB_WORKSPACE%\build --config Release --parallel 4 + cmake --install %GITHUB_WORKSPACE%\build --prefix %GITHUB_WORKSPACE%\build\install + + mkdir -p $GITHUB_WORKSPACE\artifacts + 7z a -tzip %GITHUB_WORKSPACE%\artifacts\simpleble_${{ matrix.type }}_windows-${{ matrix.arch }}.zip %GITHUB_WORKSPACE%\build\install + + - name: Upload binaries to job + uses: actions/upload-artifact@v3 + with: + name: simpleble_${{ matrix.type }}_windows-${{ matrix.arch }} + path: artifacts/simpleble_${{ matrix.type }}_windows-${{ matrix.arch }}.zip + + # ------------------------------------------------------------ + + cpp-release-macos: + runs-on: macos-12 + + strategy: + fail-fast: false + max-parallel: 4 + matrix: + arch: [arm64, x86_64] + type: [shared, static] + + steps: + - name: Clone repository + uses: actions/checkout@v3 + + - name: Setup CMake + uses: jwlawson/actions-setup-cmake@v1.13 + with: + cmake-version: '3.21' + + - name: Compile SimpleBLE + run: | + + if [ "${{ matrix.type }}" = "shared" ]; then + BUILD_SHARED_LIBS=ON + else + BUILD_SHARED_LIBS=OFF + fi + + cmake -B $GITHUB_WORKSPACE/build -DCMAKE_OSX_ARCHITECTURES="${{ matrix.arch }}" -DCMAKE_BUILD_TYPE=Release -S $GITHUB_WORKSPACE/simpleble -DBUILD_SHARED_LIBS=$BUILD_SHARED_LIBS + cmake --build $GITHUB_WORKSPACE/build --config Release --parallel 4 + cmake --install $GITHUB_WORKSPACE/build --prefix $GITHUB_WORKSPACE/build/install + + mkdir -p $GITHUB_WORKSPACE/artifacts + zip -r $GITHUB_WORKSPACE/artifacts/simpleble_${{ matrix.type }}_macos-${{ matrix.arch }}.zip $GITHUB_WORKSPACE/build/install + + - name: Upload binaries to job + uses: actions/upload-artifact@v3 + with: + name: simpleble_${{ matrix.type }}_macos-${{ matrix.arch }} + path: artifacts/simpleble_${{ matrix.type }}_macos-${{ matrix.arch }}.zip diff --git a/third_party/SimpleBLE/.github/workflows/ci_docs.yml b/third_party/SimpleBLE/.github/workflows/ci_docs.yml index e541a2332..fd14509c4 100644 --- a/third_party/SimpleBLE/.github/workflows/ci_docs.yml +++ b/third_party/SimpleBLE/.github/workflows/ci_docs.yml @@ -4,7 +4,7 @@ on: [push, pull_request] jobs: build-docs: - runs-on: ubuntu-latest + runs-on: ubuntu-22.04 steps: - name: Checkout @@ -15,10 +15,10 @@ jobs: sudo -H apt-get update -y sudo -H apt-get install -y doxygen libdbus-1-dev - - name: Set up Python 3.9 - uses: actions/setup-python@v2 + - name: Set up Python + uses: actions/setup-python@v4 with: - python-version: 3.9 + python-version: 3.11 cache: "pip" - name: Install dependencies @@ -29,7 +29,7 @@ jobs: run: make html - name: Upload artifacts - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v3 with: path: docs/_build/* name: docs diff --git a/third_party/SimpleBLE/.github/workflows/ci_lint.yml b/third_party/SimpleBLE/.github/workflows/ci_lint.yml index de89e5af9..fd0be0cf6 100644 --- a/third_party/SimpleBLE/.github/workflows/ci_lint.yml +++ b/third_party/SimpleBLE/.github/workflows/ci_lint.yml @@ -4,7 +4,7 @@ on: [push, pull_request] jobs: clang-format: - runs-on: ubuntu-latest + runs-on: ubuntu-22.04 steps: - name: Checkout @@ -19,7 +19,7 @@ jobs: inplace: False cppcheck: - runs-on: ubuntu-latest + runs-on: ubuntu-22.04 steps: - name: Checkout @@ -39,7 +39,7 @@ jobs: run: cppcheck-htmlreport --title=SimpleBLE --file=cppcheck_res.xml --report-dir=report - name: Upload Report if: ${{ failure() }} - uses: actions/upload-artifact@v1 + uses: actions/upload-artifact@v3 with: name: report path: report diff --git a/third_party/SimpleBLE/.github/workflows/ci_py_release.yml b/third_party/SimpleBLE/.github/workflows/ci_py_release.yml new file mode 100644 index 000000000..2adf92412 --- /dev/null +++ b/third_party/SimpleBLE/.github/workflows/ci_py_release.yml @@ -0,0 +1,133 @@ +name: PyPI Release + +on: + release: + types: [published] + workflow_dispatch: + inputs: + tag: + description: "The tag to upload artifacts" + required: false + +jobs: + build_sdist: + runs-on: ubuntu-22.04 + + steps: + - name: Checkout + uses: actions/checkout@v3 + env: + TAG: ${{ inputs.tag || github.ref }} + with: + ref: ${{ env.TAG }} + + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: 3.11 + cache: "pip" + + - name: Build source distribution + run: | + pip3 install build twine + python3 -m build --sdist + + - name: Upload files + uses: actions/upload-artifact@v3 + with: + name: simplepyble + path: dist/*.tar.gz + + - name: Check packages + run: twine check dist/*.tar.gz + + - name: Publish packages + run: twine upload --skip-existing dist/*.tar.gz --verbose + env: + TWINE_USERNAME: ${{ secrets.PYPI_USER }} + TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }} + + - name: Upload source to release + uses: svenstaro/upload-release-action@v2 + if: inputs.tag != '' && inputs.tag != null + env: + TAG: ${{ inputs.tag }} + with: + file: dist/*.tar.gz + tag: ${{ env.TAG }} + overwrite: true + file_glob: true + + build_wheels: + runs-on: ${{ matrix.options.os }} + + strategy: + matrix: + options: [ + {os: ubuntu-22.04, arch: x86_64}, + {os: ubuntu-22.04, arch: i686}, + {os: ubuntu-22.04, arch: aarch64}, + {os: windows-2022, arch: AMD64}, + {os: windows-2022, arch: x86}, + {os: macos-12 , arch: x86_64}, + {os: macos-12 , arch: universal2}, + {os: macos-12 , arch: arm64}, + ] + + steps: + - name: Clone repository + uses: actions/checkout@v3 + env: + TAG: ${{ inputs.tag || github.ref }} + with: + ref: ${{ env.TAG }} + + - name: Set up QEMU + if: runner.os == 'Linux' + uses: docker/setup-qemu-action@v2 + with: + platforms: arm64 + + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: 3.11 + cache: "pip" + + - name: Install dependencies + run: pip install -r simplepyble/requirements.txt + + - name: Build wheel + uses: pypa/cibuildwheel@v2.16.5 + env: + CIBW_BEFORE_ALL_LINUX: "yum update -y && yum group install -y \"Development Tools\" && yum install -y dbus-devel" + CIBW_ARCHS_LINUX: ${{ matrix.options.arch }} + CIBW_ARCHS_MACOS: ${{ matrix.options.arch }} + CIBW_ARCHS_WINDOWS: ${{ matrix.options.arch }} + CIBW_SKIP: "*musllinux_* pp*" + + - name: Upload wheels to job + uses: actions/upload-artifact@v3 + with: + name: simpleble-wheels + path: wheelhouse/*.whl + + - name: Check Packages + run: twine check wheelhouse/*.whl + + - name: Upload wheels to release + uses: svenstaro/upload-release-action@v2 + if: inputs.tag != '' && inputs.tag != null + env: + TAG: ${{ inputs.tag }} + with: + file: wheelhouse/*.whl + tag: ${{ env.TAG }} + overwrite: true + file_glob: true + + - name: Publish packages + run: twine upload --skip-existing wheelhouse/*.whl --verbose + env: + TWINE_USERNAME: ${{ secrets.PYPI_USER }} + TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }} diff --git a/third_party/SimpleBLE/.github/workflows/ci_py_release_test.yml b/third_party/SimpleBLE/.github/workflows/ci_py_release_test.yml new file mode 100644 index 000000000..e3c6d45b5 --- /dev/null +++ b/third_party/SimpleBLE/.github/workflows/ci_py_release_test.yml @@ -0,0 +1,98 @@ +name: PyPI Test Release + +on: + # push: + # pull_request: + workflow_dispatch: + +jobs: + build_sdist: + runs-on: ubuntu-22.04 + + steps: + - name: Checkout + uses: actions/checkout@v3 + + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: 3.11 + cache: "pip" + + - name: Build source distribution + run: | + pip3 install build twine + python3 -m build --sdist + + - name: Upload files + uses: actions/upload-artifact@v3 + with: + name: simplepyble + path: dist/*.tar.gz + + - name: Check packages + run: twine check dist/*.tar.gz + + - name: Publish packages + if: ${{ env.HAS_TWINE_USERNAME == 'true' }} + run: | + twine upload --repository testpypi --skip-existing dist/*.tar.gz --verbose + env: + HAS_TWINE_USERNAME: ${{ secrets.TEST_PYPI_USER != '' }} + TWINE_USERNAME: ${{ secrets.TEST_PYPI_USER }} + TWINE_PASSWORD: ${{ secrets.TEST_PYPI_PASSWORD }} + + build_wheels: + runs-on: ${{ matrix.os }} + + strategy: + matrix: + os: [ubuntu-22.04 , windows-2022, macos-12] + + steps: + - name: Checkout + uses: actions/checkout@v3 + + - name: Set up QEMU + if: runner.os == 'Linux' + uses: docker/setup-qemu-action@v2 + with: + platforms: arm64 + + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: 3.11 + cache: "pip" + + - name: Install dependencies + run: pip install -r simplepyble/requirements.txt + + - name: Build wheel + uses: pypa/cibuildwheel@v2.16.5 + env: + CIBW_BUILD: cp39-* # Only build for Python 3.9 + CIBW_BUILD_VERBOSITY: 3 + CIBW_BEFORE_ALL_LINUX: "yum update -y && yum group install -y \"Development Tools\" && yum install -y dbus-devel" + CIBW_ARCHS_LINUX: x86_64 i686 aarch64 + CIBW_ARCHS_MACOS: x86_64 universal2 arm64 + CIBW_ARCHS_WINDOWS: AMD64 x86 + CIBW_SKIP: "*musllinux_* pp*" + + - name: Upload wheels + uses: actions/upload-artifact@v3 + with: + name: simpleble-wheels + path: wheelhouse/*.whl + + - name: Check Packages + run: twine check wheelhouse/*.whl + + - name: Publish packages + if: ${{ env.HAS_TWINE_USERNAME == 'true' }} + run: | + twine upload --repository testpypi --skip-existing wheelhouse/*.whl --verbose + env: + HAS_TWINE_USERNAME: ${{ secrets.TEST_PYPI_USER != '' }} + TWINE_USERNAME: ${{ secrets.TEST_PYPI_USER }} + TWINE_PASSWORD: ${{ secrets.TEST_PYPI_PASSWORD }} diff --git a/third_party/SimpleBLE/.github/workflows/ci_release.yml b/third_party/SimpleBLE/.github/workflows/ci_release.yml deleted file mode 100644 index dca6e3769..000000000 --- a/third_party/SimpleBLE/.github/workflows/ci_release.yml +++ /dev/null @@ -1,57 +0,0 @@ -name: PyPI Release - -on: - workflow_dispatch: - -jobs: - build_wheels: - strategy: - matrix: - os: [ubuntu-20.04 , windows-2019, macos-11] - runs-on: ${{ matrix.os }} - name: Build wheels on ${{ matrix.os }} - - steps: - - name: Checkout - uses: actions/checkout@v3 - - - name: Set up QEMU - if: runner.os == 'Linux' - uses: docker/setup-qemu-action@v1 - with: - platforms: arm64 - - - name: Set up Python 3.9 - uses: actions/setup-python@v2 - with: - python-version: 3.9 - cache: "pip" - - - name: Install dependencies - run: pip install -r simplepyble/requirements.txt - - - name: Build wheel - uses: pypa/cibuildwheel@v2.9.0 - env: - CIBW_BEFORE_ALL_LINUX: "yum update -y && yum group install -y \"Development Tools\" && yum install -y dbus-devel" - CIBW_ARCHS_LINUX: x86_64 i686 aarch64 - CIBW_ARCHS_MACOS: x86_64 universal2 arm64 - CIBW_ARCHS_WINDOWS: AMD64 x86 - CIBW_SKIP: "*musllinux_* pp*" - with: - package-dir: simplepyble - - - name: Upload wheels - uses: actions/upload-artifact@v1 - with: - name: simpleble-wheels - path: wheelhouse - - - name: Check Packages - run: twine check wheelhouse/*.whl - - - name: Publish packages - run: twine upload wheelhouse/*.whl --verbose - env: - TWINE_USERNAME: ${{ secrets.PYPI_USER }} - TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }} diff --git a/third_party/SimpleBLE/.github/workflows/ci_release_test.yml b/third_party/SimpleBLE/.github/workflows/ci_release_test.yml deleted file mode 100644 index e9ee22645..000000000 --- a/third_party/SimpleBLE/.github/workflows/ci_release_test.yml +++ /dev/null @@ -1,58 +0,0 @@ -name: PyPI Test Release - -on: [push, pull_request] - -jobs: - build_wheels: - strategy: - matrix: - os: [ubuntu-20.04 , windows-2019, macos-11] - runs-on: ${{ matrix.os }} - name: Build wheels on ${{ matrix.os }} - - steps: - - name: Checkout - uses: actions/checkout@v3 - - - name: Set up QEMU - if: runner.os == 'Linux' - uses: docker/setup-qemu-action@v1 - with: - platforms: arm64 - - - name: Set up Python 3.9 - uses: actions/setup-python@v2 - with: - python-version: 3.9 - cache: "pip" - - - name: Install dependencies - run: pip install -r simplepyble/requirements.txt - - - name: Build wheel - uses: pypa/cibuildwheel@v2.9.0 - env: - CIBW_BUILD: cp39-* # Only build for Python 3.9 - CIBW_BUILD_VERBOSITY: 3 - CIBW_BEFORE_ALL_LINUX: "yum update -y && yum group install -y \"Development Tools\" && yum install -y dbus-devel" - CIBW_ARCHS_LINUX: x86_64 - CIBW_ARCHS_MACOS: arm64 - CIBW_ARCHS_WINDOWS: AMD64 - CIBW_SKIP: "*musllinux_* pp*" - with: - package-dir: simplepyble - - - name: Upload wheels - uses: actions/upload-artifact@v1 - with: - name: simpleble-wheels - path: wheelhouse - - - name: Check Packages - run: twine check wheelhouse/*.whl - - - name: Publish packages - run: twine upload --repository testpypi --skip-existing wheelhouse/*.whl --verbose - env: - TWINE_USERNAME: ${{ secrets.TEST_PYPI_USER }} - TWINE_PASSWORD: ${{ secrets.TEST_PYPI_PASSWORD }} diff --git a/third_party/SimpleBLE/.github/workflows/ci_rust_build.yml b/third_party/SimpleBLE/.github/workflows/ci_rust_build.yml new file mode 100644 index 000000000..474072835 --- /dev/null +++ b/third_party/SimpleBLE/.github/workflows/ci_rust_build.yml @@ -0,0 +1,74 @@ +name: Rust Build + +on: [push, pull_request] + +jobs: + + # ------------------------------------------------------------ + # build-windows: + # runs-on: windows-2022 + + # strategy: + # fail-fast: false + # max-parallel: 4 + # matrix: + # arch: [Win32, x64] + # sdk: ["10.0.19041.0", "10.0.22000.0"] + + # steps: + # - name: Clone Repository + # uses: actions/checkout@v3 + + + # ------------------------------------------------------------ + + build-macos: + runs-on: ${{ matrix.os }} + + strategy: + fail-fast: false + max-parallel: 4 + matrix: + os: [macos-11, macos-12] + arch: [arm64, x86_64] + + steps: + - name: Clone Repository + uses: actions/checkout@v3 + - name: Install CMake + uses: jwlawson/actions-setup-cmake@v1.13 + with: + cmake-version: '3.21' + - name: Install Rust + uses: dtolnay/rust-toolchain@stable + - name: Compile SimpleBLE + run: cargo build + + # ------------------------------------------------------------ + + build-linux: + runs-on: ${{ matrix.os }} + + strategy: + fail-fast: false + max-parallel: 4 + matrix: + os: [ubuntu-20.04, ubuntu-22.04] + + steps: + - name: Clone Repository + uses: actions/checkout@v3 + - name: Install Dependencies + run: | + sudo -H apt-get update -y + sudo -H apt-get install -y libdbus-1-dev + env: + DEBIAN_FRONTEND: noninteractive + - name: Install CMake + uses: jwlawson/actions-setup-cmake@v1.13 + with: + cmake-version: '3.21' + - name: Install Rust + uses: dtolnay/rust-toolchain@stable + - name: Compile SimpleBLE + run: cargo build diff --git a/third_party/SimpleBLE/.github/workflows/ci_test.yml b/third_party/SimpleBLE/.github/workflows/ci_test.yml index c977b7dc4..6cef17acf 100644 --- a/third_party/SimpleBLE/.github/workflows/ci_test.yml +++ b/third_party/SimpleBLE/.github/workflows/ci_test.yml @@ -6,19 +6,13 @@ jobs: # ------------------------------------------------------------ test-windows: - runs-on: ${{ matrix.os }} - - strategy: - fail-fast: false - max-parallel: 4 - matrix: - os: [windows-2019] + runs-on: windows-2022 steps: - name: Clone Repository uses: actions/checkout@v3 - name: Add msbuild to PATH - uses: microsoft/setup-msbuild@v1.0.2 + uses: microsoft/setup-msbuild@v1.1 - name: Clone and build GTest run: | git clone https://github.com/google/googletest @@ -29,7 +23,7 @@ jobs: shell: cmd - name: Compile Tests for Windows x86 run: | - cmake -B %GITHUB_WORKSPACE%\build_test -G "Visual Studio 16 2019" -DCMAKE_SYSTEM_VERSION=10.0.22000.0 -DGTEST_ROOT=%GITHUB_WORKSPACE%\googletest\install -S %GITHUB_WORKSPACE%/simpleble -DSIMPLEBLE_TEST=ON + cmake -B %GITHUB_WORKSPACE%\build_test -G "Visual Studio 17 2022" -DCMAKE_SYSTEM_VERSION=10.0.22000.0 -DGTEST_ROOT=%GITHUB_WORKSPACE%\googletest\install -S %GITHUB_WORKSPACE%/simpleble -DSIMPLEBLE_TEST=ON cmake --build %GITHUB_WORKSPACE%\build_test --config Release --parallel 4 %GITHUB_WORKSPACE%\build_test\bin\Release\simpleble_test.exe shell: cmd @@ -37,21 +31,15 @@ jobs: # ------------------------------------------------------------ test-macos: - runs-on: ${{ matrix.os }} - - strategy: - fail-fast: false - max-parallel: 4 - matrix: - os: [macos-11.0] + runs-on: macos-12 steps: - name: Clone Repository uses: actions/checkout@v3 - name: Setup Cmake - uses: jwlawson/actions-setup-cmake@v1.12 + uses: jwlawson/actions-setup-cmake@v1.13 with: - cmake-version: '3.21.x' + cmake-version: '3.21' - name: Clone and build GTest run: | git clone https://github.com/google/googletest @@ -68,13 +56,7 @@ jobs: # ------------------------------------------------------------ test-linux: - runs-on: ${{ matrix.os }} - - strategy: - fail-fast: false - max-parallel: 4 - matrix: - os: [ubuntu-20.04] + runs-on: ubuntu-22.04 steps: - name: Clone Repository @@ -90,9 +72,9 @@ jobs: run: | echo "DBUS_SESSION_BUS_ADDRESS=$(dbus-daemon --config-file=/usr/share/dbus-1/session.conf --print-address --fork | cut -d, -f1)" >> $GITHUB_ENV - name: Setup Cmake - uses: jwlawson/actions-setup-cmake@v1.12 + uses: jwlawson/actions-setup-cmake@v1.13 with: - cmake-version: '3.21.x' + cmake-version: '3.21' - name: Clone and build GTest run: | git clone https://github.com/google/googletest @@ -149,16 +131,16 @@ jobs: # ------------------------------------------------------------ test-python: - runs-on: "ubuntu-20.04" + runs-on: ubuntu-22.04 steps: - name: Checkout uses: actions/checkout@v3 - - name: Set up Python 3.9 - uses: actions/setup-python@v2 + - name: Set up Python + uses: actions/setup-python@v4 with: - python-version: 3.9 + python-version: 3.11 cache: "pip" - name: Install dependencies @@ -166,8 +148,7 @@ jobs: - name: Install SimplePyBLE with Plain flavor run: python setup.py install --plain - working-directory: ./simplepyble - name: Run PyTest run: pytest - working-directory: ./simplepyble/test \ No newline at end of file + working-directory: ./simplepyble/test diff --git a/third_party/SimpleBLE/.gitignore b/third_party/SimpleBLE/.gitignore index b3c94aecc..8c6f07f0e 100644 --- a/third_party/SimpleBLE/.gitignore +++ b/third_party/SimpleBLE/.gitignore @@ -3,11 +3,13 @@ .DS_Store _build _doxygen +_skbuild /build_* -simplepyble/build -simplepyble/dist +/dist __pycache__ *.egg-info wheelhouse + +target diff --git a/third_party/SimpleBLE/.readthedocs.yaml b/third_party/SimpleBLE/.readthedocs.yaml index e013786ea..311ed90b9 100644 --- a/third_party/SimpleBLE/.readthedocs.yaml +++ b/third_party/SimpleBLE/.readthedocs.yaml @@ -21,7 +21,7 @@ build: post_install: - echo "Command run at 'post_install' step" # NOTE: Apparently sphinx_rtfd_theme==1.0.0 is not compatible with Sphinx 5.2 - - pip install breathe==4.34.0 sphinx_rtd_theme==1.0.0 sphinx==5.1.1 + - pip install breathe==4.34.0 sphinx_rtd_theme==1.0.0 sphinx==5.1.1 sphinxcontrib-mermaid==0.9.2 pre_build: - echo "Command run at 'pre_build' step" post_build: diff --git a/third_party/SimpleBLE/CONTRIBUTING.md b/third_party/SimpleBLE/CONTRIBUTING.md new file mode 100644 index 000000000..7cf014549 --- /dev/null +++ b/third_party/SimpleBLE/CONTRIBUTING.md @@ -0,0 +1,45 @@ +# Contributing to SimpleBLE + +This document outlines the process for contributing to the project and provides some guidelines to ensure a smooth collaboration. + +## Contributor License Agreement + +Before we can accept your contribution, you must sign our Contributor License Agreement (CLA). This agreement ensures that the project has the necessary rights to use and distribute your contributions. + +- If you are contributing as an individual, please sign the Individual CLA. +- If you are contributing on behalf of your employer, please have your employer sign the Corporate CLA. + + + +**Please note:** We cannot accept any contributions without a signed CLA. + +## Coding Guidelines + +- Follow the existing code style and conventions used in the project. +- Write clear, readable, and well-documented code. +- Include unit tests for new features or bug fixes where applicable. +- Ensure your code works on all supported platforms (Linux, Windows, macOS, iOS, and Android). + +## Submitting a Pull Request + +1. Ensure you have signed the CLA before submitting your pull request. +2. Provide a clear and detailed description of your changes in the pull request. +3. Reference any related issues in your pull request description. +4. Be prepared to make changes if requested by the maintainers. + +## Reporting Issues + +- Use the GitHub issue tracker to report bugs or suggest features. +- Before creating a new issue, please check if a similar issue already exists. +- Provide as much detail as possible, including steps to reproduce for bugs. + +## Community Guidelines + +- Be respectful and considerate in all interactions. +- Help others if you can. + +## Questions? + +If you have any questions about contributing, feel free to open an issue or contact the team directly. + +Thank you for contributing to SimpleBLE! Your efforts help make this project better for everyone. \ No newline at end of file diff --git a/third_party/SimpleBLE/Cargo.lock b/third_party/SimpleBLE/Cargo.lock new file mode 100644 index 000000000..06cd8f8ec --- /dev/null +++ b/third_party/SimpleBLE/Cargo.lock @@ -0,0 +1,183 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "cc" +version = "1.0.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50d30906286121d95be3d479533b458f87493b30a4b5f79a607db8f5d11aa91f" + +[[package]] +name = "cmake" +version = "0.1.49" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db34956e100b30725f2eb215f90d4871051239535632f84fea3bc92722c66b7c" +dependencies = [ + "cc", +] + +[[package]] +name = "codespan-reporting" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3538270d33cc669650c4b093848450d380def10c331d38c768e34cac80576e6e" +dependencies = [ + "termcolor", + "unicode-width", +] + +[[package]] +name = "cxx" +version = "1.0.89" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc831ee6a32dd495436e317595e639a587aa9907bef96fe6e6abc290ab6204e9" +dependencies = [ + "cc", + "cxxbridge-flags", + "cxxbridge-macro", + "link-cplusplus", +] + +[[package]] +name = "cxx-build" +version = "1.0.89" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94331d54f1b1a8895cd81049f7eaaaef9d05a7dcb4d1fd08bf3ff0806246789d" +dependencies = [ + "cc", + "codespan-reporting", + "once_cell", + "proc-macro2", + "quote", + "scratch", + "syn", +] + +[[package]] +name = "cxxbridge-flags" +version = "1.0.89" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48dcd35ba14ca9b40d6e4b4b39961f23d835dbb8eed74565ded361d93e1feb8a" + +[[package]] +name = "cxxbridge-macro" +version = "1.0.89" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81bbeb29798b407ccd82a3324ade1a7286e0d29851475990b612670f6f5124d2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "link-cplusplus" +version = "1.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecd207c9c713c34f95a097a5b029ac2ce6010530c7b49d7fea24d977dede04f5" +dependencies = [ + "cc", +] + +[[package]] +name = "once_cell" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f61fba1741ea2b3d6a1e3178721804bb716a68a6aeba1149b5d52e3d464ea66" + +[[package]] +name = "proc-macro2" +version = "1.0.50" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ef7d57beacfaf2d8aee5937dab7b7f28de3cb8b1828479bb5de2a7106f2bae2" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8856d8364d252a14d474036ea1358d63c9e6965c8e5c1885c18f73d70bff9c7b" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "scratch" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddccb15bcce173023b3fedd9436f882a0739b8dfb45e4f6b6002bee5929f61b2" + +[[package]] +name = "simplersble" +version = "0.8.0" +dependencies = [ + "cmake", + "cxx", + "cxx-build", +] + +[[package]] +name = "syn" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f4064b5b16e03ae50984a5a8ed5d4f8803e6bc1fd170a3cda91a1be4b18e3f5" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "termcolor" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be55cf8942feac5c765c2c993422806843c9a9a45d4d5c407ad6dd2ea95eb9b6" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "unicode-ident" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84a22b9f218b40614adcb3f4ff08b703773ad44fa9423e4e0d346d5db86e4ebc" + +[[package]] +name = "unicode-width" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0edd1e5b14653f783770bce4a4dabb4a5108a5370a5f5d8cfe8710c361f6c8b" + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" +dependencies = [ + "winapi", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/third_party/SimpleBLE/Cargo.toml b/third_party/SimpleBLE/Cargo.toml new file mode 100644 index 000000000..420afaae0 --- /dev/null +++ b/third_party/SimpleBLE/Cargo.toml @@ -0,0 +1,31 @@ +[package] +edition = "2021" + +name = "simplersble" +version = "0.8.0" +license = "GPL-3.0-only" +description = "The all-in-one Bluetooth library that makes it easy to add wireless connectivity to your projects." +readme = "simplersble/README.md" +repository = "https://github.com/OpenBluetoothToolbox/SimpleBLE" + +include = [ + "/VERSION", + "/cmake", + "/simpleble", + "/simplebluez", + "/simpledbus", + "/simplersble", +] + +build = "simplersble/build.rs" +links = "simpleble" + +[lib] +path = "simplersble/src/lib.rs" + +[dependencies] +cxx = "1.0" + +[build-dependencies] +cmake = "0.1" +cxx-build = "1.0" diff --git a/third_party/SimpleBLE/LICENSE.md b/third_party/SimpleBLE/LICENSE.md index b45662d88..60a363217 100644 --- a/third_party/SimpleBLE/LICENSE.md +++ b/third_party/SimpleBLE/LICENSE.md @@ -1,21 +1,425 @@ -MIT License - -Copyright (c) 2021-2022 Kevin Dewald - -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. +# SimpleBLE License + +Since February 15th 2024, SimpleBLE is now available under the GNU General Public License +version 3 (GPLv3), with the option for a commercial license without the GPLv3 restrictions +available for a fee. + +**You can find more information on pricing and commercial terms of service at www.simpleble.org** + +To enquire about a commercial license, please contact us at ``contact at simpleble dot org``. + +Likewise, if you are using SimpleBLE in an open-source project and would like to request +a free commercial license or if you have any other questions, please reach out at ``contact at simpleble dot org``. + +------------------------------------------------------------------------------- + +# SimpleBLE Commercial License Agreement + +Version 1.2 - 2024-06-28 + +Copyright © 2024 - THE CALIFORNIA OPEN SOURCE COMPANY LLC + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +## TERMS AND CONDITIONS + +### 0. Definitions + +- **"Licensed Technology"** shall mean the software, documentation, code, materials, and any other intellectual property specified in Appendix A as provided by the Licensor to the Licensee under this Agreement, as well as any updates, modifications, or improvements thereto made by either the Licensor or the Licensee. + +- **"Licensor"** shall mean the individual, corporation, or other legal entity that owns or controls the intellectual property rights in the Licensed Technology and grants the Licensee a license to use the Licensed Technology under the terms and conditions of this Agreement. + +- **"Licensee"** shall mean the individual, corporation, or other legal entity that is granted a license to use the Licensed Technology under the terms and conditions of this Agreement. + +- **"Parties"** shall mean the Licensor and the Licensee collectively, and "Party" shall mean either the Licensor or the Licensee individually, as the context requires. + +- **"Affiliate"** shall mean, with respect to a Party, any entity that directly or indirectly controls, is controlled by, or is under common control with such Party. For purposes of this definition, "control" means the power to direct or cause the direction of the management and policies of an entity, whether through the ownership of voting securities, by contract, or otherwise. + +- **"Employee"** shall mean any individual who is employed by either Party or any of its Affiliates on a full-time, part-time, or temporary basis, and who is subject to the direction and control of the employing Party or Affiliate with respect to the time, place, and manner of their work. The term "Employee" shall not include Contractors. + +- **"Contractor"** shall mean any individual or entity that is not an Employee of either Party or any of its Affiliates, but is engaged by a Party or its Affiliate to perform services on their behalf. Contractors may include, but are not limited to, consultants, advisors, or outsourced service providers. + +- **"Intellectual Property Rights"** means any form of protection afforded anywhere in the world by law to inventions, works, designs, software, trade secrets, confidential information, know-how and other proprietary information and data, including without limitation patents (including re-issues, divisions, continuations and extensions thereof), copyrights, database rights, registered and not-registered design rights, utility models, mask works, as well as applications for any such rights. + +- **"Application"** shall mean a product, service, or solution developed by the Licensee that incorporates the Licensed Technology and adds primary and substantial functionality, features, or improvements that are distinct from those provided by the Licensed Technology itself. An Application must have a clear and distinctive goal that goes beyond merely serving as a wrapper, modification, or adaptation of the Licensed Technology. + +- **"Derivative Work"** shall mean any modification, adaptation, translation, improvement, enhancement, or other work based on or derived from the Licensed Technology that does not add primary and substantial functionality, features, or improvements distinct from those provided by the Licensed Technology itself. This includes, without limitation, any product, service, or solution that integrates, incorporates, bundles, wraps, interfaces with, or adapts the Licensed Technology without significantly changing or enhancing its original functionality, features, or purpose. + +- **"Documentation"** shall mean any user manuals, technical manuals, specifications, or other written materials provided by the Licensor that describe the features, functions, or operation of the Licensed Technology. + +- **"Feedback"** shall mean any suggestions, comments, ideas, or other information provided by the Licensee to the Licensor regarding the Licensed Technology, including but not limited to bug reports, feature requests, and performance evaluations. + +- **"Compatible Open-Source Licenses"** shall mean open-source software licenses allowing for the free use, modification, and distribution of the Licensed Technology, without imposing conflicting or additional restrictions. The only valid licenses are: (a) MIT License (b) Apache License 2.0 (c) BSD 3-Clause "New" or "Revised" License. + +- **"Non-Compatible Open-Source Licenses"** shall mean any license terms that are inconsistent with or conflict with the terms of this Agreement, including but not limited to the GNU General Public License (GPL), Lesser GPL (LGPL), or the Creative Commons Attribution-ShareAlike License. + +- **"Fees"** shall mean the amounts payable by the Licensee to the Licensor in consideration for the rights and licenses granted under this Agreement. + +- **"Term"** shall mean the duration of this Agreement, as specified in Appendix A, commencing on the Effective Date and continuing until the expiration or termination of this Agreement in accordance with its terms. + +- **"Effective Date"** shall mean the date on which this Agreement comes into force, as specified in Appendix A or as determined by the mutual execution of this Agreement by both parties. + +- **"Force Majeure Event"** shall have the meaning set forth in Section 13. + +- **"End User"** shall mean any individual, corporation, or other legal entity that is not a party to this Agreement, but obtains and uses the Application developed by the Licensee, either under the terms of a Compatible License or through a commercial arrangement with the Licensee. + +### 1. Object of the Agreement + +1.1 The primary purpose of this Agreement is to delineate the terms under which the Licensor grants the Licensee specific rights pertaining to the use of the Licensed Technology. It is explicitly stated and understood that this Agreement does not grant any rights, privileges, or licenses to any third parties not explicitly mentioned herein. + +1.2 Under the terms outlined in this Agreement, contingent upon the Licensee's timely payment of Fees as specified in Appendix A, and strict adherence to all other terms and conditions herein, the Licensor grants the Licensee a worldwide, non-exclusive, non-sublicensable, and non-transferable license to use or modify the Licensed Technology, for the sole purposes of creating Application based on the Licensed Technology for and marketing, promoting, licensing, maintaining and supporting such Applications to/for End-User,, subject to the limitations and restrictions set forth in this Agreement. + +1.3 All rights bestowed upon the Licensee under this Agreement are conferred solely through licensing and not by sale. These rights are also circumscribed and governed by the terms of this Agreement. This Agreement does not grant any license or other rights in any intellectual property other than the Licensed Technology. No license or rights will arise under this Agreement by implication, estoppel, or any other means. Any attempt at sublicensing that contradicts the terms of this Agreement will be deemed invalid and without effect. + +1.4 The effective period of this Agreement commences both Parties signing this Agreement and the subsequent payment of the Fee by the Licensee. This initiation is contingent upon these dual conditions being met, marking the start of the Term as indicated in Appendix A and continuing for the Term as indicated in Appendix A. Following the conclusion of this Term, the Agreement may be subject to renewal, based on mutual consent of both Parties and contingent upon the Licensee's payment of any applicable renewal fees, as well as their continued compliance with the terms set forth herein. + +1.5 The Licensee acknowledges and agrees that any use of the Licensed Technology or any Derivative Work by the Licensee outside the scope of this Agreement shall constitute a material breach of this Agreement and may result in the immediate termination of the license granted herein. The Licensee shall promptly notify the Licensor of any unauthorized use or disclosure of the Licensed Technology and take reasonable steps to prevent further breach of this Agreement. + +### 2. Intellectual Property + +2.1 The Licensor retains all right, title, and interest, including all Intellectual Property Rights, in and to the Licensed Technology. This Agreement does not grant the Licensee any ownership rights in the Licensed Technology, but only the limited license rights expressly set forth herein. The Licensed Technology is protected by copyright laws, international copyright treaties, and other Intellectual Property Laws and treaties. Any unauthorized copying, modification, distribution, or use of the Licensed Technology is strictly prohibited and may subject the Licensee to legal action. + +2.2 The Licensee shall own the Intellectual Property Rights in any Application developed by the Licensee, excluding the Licensed Technology and any Derivative Works. The Licensee is hereby granted the privilege to alter, adapt, and modify the Licensed Technology as necessary to meet specific requirements or objectives. Any Derivative Work based on or derived from the Licensed Technology shall be owned by the Licensor and considered part of the Licensed Technology, subject to the terms and conditions of this Agreement. The Licensee shall have no ownership rights in Derivative Works. + +2.3 End Users may use, modify, and distribute the Application in accordance with the terms of the applicable Compatible License or commercial agreement, with the licensee, but shall have no rights to the Licensed Technology except as expressly granted in this Agreement. + +### 3. Fees and Taxes + +3.1 The Licensee shall pay the Licensor the fees specified in Appendix A (the "Fees") in accordance with the payment terms set forth therein. If the Licensee fails to pay the Fees within the agreed payment term, the Licensee shall owe Late Payment Charges as specified in Appendix A. + +3.2 All Fees are non-refundable, and the Licensor shall have no obligation to refund any Fees paid by the Licensee, except as expressly provided in this Agreement. The Licensee shall not be entitled for any reason to any set-off, counter-claim, abatement, or other similar deduction to withhold payment of any amount due to the Licensor. + +3.3 All Fees are exclusive of any applicable taxes, levies, or duties, including but not limited to value-added tax, sales tax, or withholding tax. The Licensee shall be responsible for paying all such taxes, levies, or duties associated with the Fees, except for those based on the Licensor's income. + +3.4 If the Licensor is required to pay or collect any such taxes, levies, or duties on behalf of the Licensee, the amount payable by the Licensee shall be increased to the extent necessary to ensure that the Licensor receives a sum equal to the Fees it would have received had no such deduction or withholding been required. The Licensor shall provide the Licensee with appropriate tax invoices or receipts evidencing the payment of any such taxes, levies, or duties. The Licensee shall furnish the Licensor with any relevant tax exemption certificates or other documentation required to minimize or eliminate any applicable taxes, levies, or duties. + +### 4. General Provisions + +4.1 **Entire Agreement.** This Agreement, together with Appendix A, collectively forms the complete and exclusive terms of the arrangement between the Parties. It supersedes all prior or contemporaneous discussions, representations, contracts, including but not limited to previous License Agreements and similar agreements, as well as proposals, whether written or oral, concerning the subject matters herein. + +4.2 **Severability.** In the event any portion of this Agreement is deemed invalid or unenforceable, such portion shall not limit or otherwise modify or affect any other portion of this Agreement Without limiting the generality of the foregoing, if the scope of any provision contained in this Agreement is too broad to permit enforcement to its fullest extent, such covenant shall be enforced to the maximum extent permitted by law, and the Parties hereby agree that such scope may be judicially modified accordingly. + +4.3 **Modification Waiver.** This Agreement is furnished 'as-is' and no amendments to its terms are permissible. The failure of either Party to enforce any provision of this Agreement may not be deemed a waiver of that or any other provision of this Agreement. + +4.4 **Marketing.** Licensee agrees that the Licensor may use the Licensee's name, trade name, and trademark in the Licensor's marketing materials and on its website, solely for the purpose of identifying the Licensee as a customer of the Licensor. Such use shall be in accordance with the Licensee's brand guidelines and shall not imply any endorsement or affiliation beyond the scope of this Agreement. The Licensor shall promptly cease any such use upon written request from the Licensee. + +4.5 **Compliance with Applicable Laws.** In the course of employing the Licensed Technology pursuant to this Agreement, the Licensee shall ensure compliance with all relevant laws and regulations. The Licensee is prohibited from engaging in the renting, leasing, or similar disposal of the Licensed Technology in any manner that contradicts this Agreement. Additionally, the Licensee must refrain from any misappropriation or unauthorized utilization of other products or services offered by the Licensor. + +4.6 **Trademarks.** The Licensee shall not remove or alter any copyright, trademark, or other proprietary rights notice(s) contained in any portion of the Licensed Technology. Applications must add primary and substantial functionality to the Licensed Technology so as not to compete with the Licensed Technology. + +4.7 **Prohibited Activities.** The Licensee shall not use the Licensed Technology for any unlawful purpose, including without limitation the infringement of any third party's Intellectual Property Right or other proprietary rights. The Licensee agrees that it shall not claim any right to or license (except for the license granted pursuant to Section 1.2 above) with respect to the Licensed Technology nor shall the Licensee contest or assist in contesting the Licensor's right, title and interest in and to such the Licensed Technology. Further, the Licensee shall not partake in activities that contribute to or support claims, whether made by the Licensee or any third party, alleging that the Licensed Technology infringes on any patents. The sale of the Licensed Technology or the establishment of a security interest over it is strictly prohibited. Moreover, the distribution of any product, inclusive of the Licensed Technology, shall be conducted strictly in accordance with the permissions explicitly granted by this Agreement. + +4.8 **Assignment.** The Licensee is barred from assigning or transferring any rights, benefits, or obligations under this Agreement, unless such transfer is part of the sale of its relevant business or assets, or is done with the Licensor's prior written consent, which is not to be unreasonably withheld or delayed. In contrast, the Licensor retains the unencumbered right to assign or transfer any of its rights, benefits, or obligations under this Agreement. + +4.9 **Injunctive Relief.** The Licensee hereby acknowledges that unauthorized disclosure and/or use of any of the Licensed Technology could cause irreparable harm and significant injury to the Licensor that may be difficult to ascertain. Accordingly, the Licensee agrees that, in addition to any other rights and remedies it may have, the Licensor will have the right to seek immediate injunctive relief to enforce the obligations under this Agreement without the necessity of posting a bond or any other security. + +4.10 **No Representation.** The Licensee shall not represent itself as an agent of the Licensor for any purpose, nor give any condition or warranty or make any representation on the Licensor's behalf or commit the Licensor to any contracts. Further, the Licensee shall not make any representations, warranties, guarantees or other commitments with respect to the specifications, features or capabilities of the Licensed Technology or otherwise incur any liability on behalf of the Licensor in any circumstances. + +4.11 **Audits.** The Licensor has the right to audit the Licensee compliance with its obligations under this Agreement. The Licensee shall provide to the Licensor and its personnel, auditors and inspectors such assistance, access and co-operation as they may need and reasonably require. + +4.12 **Cumulative Remedies.** Any remedies specified in this Agreement are cumulative and are not intended to be exclusive of any other remedies to which the Licensor may be entitled at law or equity in case of any breach or threatened breach by the Licensee of any provision of this Agreement, unless such remedies are specifically limited or excluded by the terms of any provision of this Agreement. + +4.13 **Survival.** Certain provisions of this Agreement are designed to outlast its termination. These provisions, due to their inherent nature or as specifically indicated, will continue to be valid and enforceable even after the termination of this Agreement. + +### 5. Feedback and Updates + +5.1 The Licensee hereby grants to the Licensor the unrestricted right to freely utilize and disclose any Feedback that the Licensee provides concerning the Licensed Technology. The Licensee acknowledges and agrees that all Feedback may be employed by the Licensor for any purpose, whether commercial, developmental, or otherwise, without any obligation for acknowledgment, compensation, or other consideration to the Licensee. This includes, but is not limited to, the right to develop, copy, publish, modify, enhance, or otherwise make improvements to the Licensed Technology, at the sole discretion of the Licensor. The Licensee recognizes that all Feedback shall be considered non-confidential and the Licensor is free to use such Feedback without any restriction or obligation of confidentiality. + +5.2 During the Term, the Licensor may develop and release updates, upgrades, or new versions of the Licensed Technology. The Licensee shall have the right to receive and use such updates, upgrades, or new versions, subject to the terms and conditions of this Agreement. + +5.3 The Licensee's right to receive and use updates, upgrades, or new versions shall continue until the termination of this Agreement, as outlined in Section 8. Upon termination, the Licensee shall have no further right to receive any updates, upgrades, or new versions of the Licensed Technology. + +5.4 All updates, upgrades, or new versions of the Licensed Technology provided to the Licensee shall be considered part of the Licensed Technology and subject to the terms and conditions of this Agreement, unless otherwise specified by the Licensor in writing. + +5.5 Notwithstanding the Licensee's right to receive updates, upgrades, or new versions, the Licensor is under no obligation to develop or release any such updates, upgrades, or new versions. The development and release of updates, upgrades, or new versions shall be at the sole discretion of the Licensor. + +### 6. End User Rights and Obligations + +6.1 End Users who obtain the Application, either under a Compatible Open-Source License or through a commercial arrangement with the Licensee, may use, modify, and distribute the Application, subject to the terms and conditions of the applicable Compatible Open-Source License or commercial agreement. However, End Users shall have no right to use, modify, or distribute the Licensed Technology, or any part thereof, except as incorporated in the Application and subject to the terms and conditions of this Agreement. + +6.2 The Licensee shall include a prominent notice in the Application's documentation, user interface, and source code, stating the following: + +``` +IMPORTANT NOTICE: This Application is built upon the [Licensed Technology Name], which is owned by [Licensor Name] and used under license. As an End User of this Application, you are prohibited from using, modifying, or distributing the [Licensed Technology Name], or any part thereof, except as incorporated in this Application. Specifically, you may not: + +a) Extract, isolate, or separate the [Licensed Technology Name] from this Application; +b) Use the [Licensed Technology Name] for any purpose other than as part of this Application; +c) Modify, adapt or translate the [Licensed Technology Name]; +d) Create any Derivative Works based on the [Licensed Technology Name]; +e) Distribute, sublicense, rent, lease, lend, or transfer the [Licensed Technology Name] to any third party; +f) Reverse engineer, decompile, disassemble, or attempt to derive the source code of the [Licensed Technology Name]; +g) Remove, obscure, or alter any copyright, trademark, or other proprietary rights notices contained within the [Licensed Technology Name]. + +Your use of this Application is subject to your compliance with these restrictions. If you have any questions about these terms, please contact [Licensee Name]. +``` + +The Licensee shall include a copy of this notice in all copies or substantial portions of the Application. + +6.3 End Users must comply with all applicable laws, regulations, and third-party rights when using, modifying, or distributing the Application. + +6.4 The Licensee shall indemnify, defend, and hold harmless the Licensor from and against any claims, damages, liabilities, costs, and expenses arising out of or in connection with any use of the Application by End Users, including any use that breaches the terms and conditions of this Agreement. + +### 7. Use of Non-Compatible Open-Source Licenses + +In adherence to the terms of this Agreement, the Licensee is expressly prohibited from, and shall not permit any third party or End User to, integrate, distribute, or otherwise utilize the Licensed Technology in conjunction with any code, software, or content that is subject to a license incompatible with the terms of this Agreement, hereafter referred to as "Non-Compatible Open-Source Licenses". Such prohibitive action includes, but is not limited to, any combination or use that would necessitate, either directly or indirectly, that the Licensed Technology be subject or conform to any licensing terms other than those explicitly set forth in this Agreement. + +### 8. Termination + +8.1 This Agreement may be terminated without cause by either Party upon written notice to the other Party, provided such notice period is no less than three (3) months. + +8.2 Either Party may terminate this Agreement with immediate effect, if the other Party commits a material breach of the terms of this Agreement and has not remedied such breach upon the non-breaching Party's written notice within a reasonable timeframe, which shall be no less than thirty (30) days). + +8.3 The Licensor may also immediately terminate this Agreement upon written notice to the Licensee if the Licensee becomes bankrupt, insolvent, enters into liquidation, or undergoes debt restructuring. + +### 9. Rights and Duties upon Termination + +9.1 Upon termination of this Agreement, the Licensee's rights to use or modify the Licensed Technology, and to create Derivative Works based on the Licensed Technology, shall immediately cease, except as provided in Section 9.2. + +9.2 In the event that this Agreement is terminated by either Party without cause pursuant to Section 8.1, or by the Licensor due to the Licensee's bankruptcy, insolvency, liquidation, or debt restructuring pursuant to Section 8.3, or upon the conclusion of the Term as specified in Section 1.4, the Licensee shall retain the right to continue using the Licensed Technology, limited to the version in use immediately prior to the termination date, solely for the purpose of maintaining and supporting existing Applications. The Licensee shall have no right to receive any updates, modifications, or improvements to the Licensed Technology made by the Licensor after the termination date. + +9.3 In the event that this Agreement is terminated by either Party due to a material breach by the other Party pursuant to Section 8.2, the Licensee's right to continue using the Licensed Technology as described in Section 9.2 shall not apply, and all rights granted to the Licensee under this Agreement shall immediately terminate. + +9.4 Expiry or termination of this Agreement shall not relieve the Licensee of its obligation to pay any Fees accrued or payable to the Licensor prior to the effective date of termination, and the Licensee shall pay to the Licensor all such Fees within 30 days from the effective date of termination. + +9.5 The Licensee acknowledges and agrees that, following the termination of this Agreement, it shall remain bound by its obligations under this Agreement with respect to any use of the Licensed Technology, including in Applications already distributed, and shall ensure that such use remains in compliance with the terms of this Agreement. + +### 10. Notices + +Any notice given by one Party to the other shall be deemed properly given and deemed received if specifically acknowledged by the receiving Party in writing. Additionally, any notice issued by the Licensor to the Licensee using the email address provided by the Licensee to the Licensor will be effective from the moment it was sent. Each communication and document made or delivered by one Party to the other Party pursuant to this Agreement shall be in the language specified in Appendix A. + +### 11. Warranty Disclaimers + +THE LICENSED TECHNOLOGY, INCLUDING ALL SOFTWARE, DOCUMENTATION, INFORMATION, CONTENT, MATERIALS, CODE, AND RELATED SERVICES, ARE PROVIDED BY THE LICENSOR ON AN "AS IS" AND "AS AVAILABLE" BASIS. THE LICENSOR AND ITS AFFILIATES HEREBY DISCLAIM ALL WARRANTIES, WHETHER EXPRESS, IMPLIED, STATUTORY, OR OTHERWISE. SPECIFICALLY, THE LICENSOR AND ITS AFFILIATES MAKE NO REPRESENTATIONS OR WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, REGARDING THE LICENSED TECHNOLOGY, INCLUDING BUT NOT LIMITED TO IMPLIED OR STATUTORY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, NON-INFRINGEMENT OF INTELLECTUAL PROPERTY OR OTHER PROPRIETARY RIGHTS, AND ALL WARRANTIES ARISING FROM COURSE OF DEALING, USAGE, OR TRADE PRACTICE. THE LICENSOR AND ITS AFFILIATES DO NOT WARRANT THAT THE LICENSED TECHNOLOGY, OR ANY PRODUCTS OR RESULTS OF THE USE THEREOF, WILL MEET LICENSEE'S OR ANY OTHER PERSON'S REQUIREMENTS, OPERATE WITHOUT INTERRUPTION, ACHIEVE ANY INTENDED RESULT, BE COMPATIBLE OR WORK WITH ANY SOFTWARE, SYSTEM, OR OTHER SERVICES, OR BE SECURE, ACCURATE, COMPLETE, FREE OF HARMFUL CODE, OR ERROR-FREE AT THE TIME OF THIS AGREEMENT OR AT ANY TIME IN THE FUTURE. FURTHER, THE LICENSOR AND ITS AFFILIATES DO NOT WARRANT THAT THE LICENSED TECHNOLOGY IS FREE OF VIRUSES OR OTHER HARMFUL COMPONENTS. THE PARTIES ACKNOWLEDGE AND AGREE THAT THE FOREGOING WARRANTY DISCLAIMERS ARE AN ESSENTIAL ELEMENT IN SETTING CONSIDERATION UNDER THIS AGREEMENT. + +### 12. Limitation of Liability + +TO THE FULL EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSOR WILL NOT BE LIABLE FOR ANY LOST PROFITS, LOSS OF SAVINGS, LOSS OR CORRUPTION OF DATA, LOSS OR INTERRUPTION OF BUSINESS, LOSS OF GOODWILL OR REPUTATION, CLAIMS MADE BY ANY END-USER OR ANY OTHER THIRD PARTY, OR ANY OTHER INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL, OR PUNITIVE COSTS, DAMAGES, OR EXPENSES OF ANY KIND ARISING UNDER OR IN CONNECTION WITH THIS AGREEMENT. FURTHER, THE LICENSOR'S AGGREGATE LIABILITY UNDER THIS AGREEMENT SHALL NOT EXCEED THE TOTAL AMOUNTS PAID (IF ANY) TO THE LICENSOR UNDER THIS AGREEMENT DURING THE TWELVE (12) MONTHS IMMEDIATELY PRECEDING THE EVENTS GIVING RISE TO THE LIABILITY. SEEKING DAMAGES AS LIMITED BY THIS SECTION SHALL BE THE SOLE AND EXCLUSIVE REMEDY TO THE LICENSEE FOR ANY ACT OR OMISSION OF THE LICENSOR. THESE LIMITATIONS OF LIABILITY AND EXCLUSIONS OF POTENTIAL DAMAGES WERE AN ESSENTIAL ELEMENT IN SETTING CONSIDERATION UNDER THIS AGREEMENT. + +### 13. Force Majeure + +Neither Party shall be liable to the other for any delay or non-performance of its obligations hereunder in the event and to the extent that such delay or non-performance is due to an event beyond a Party's reasonable control and without the fault or negligence of such Party. Such causes may include, but are not limited to, any God, terrorist attack, destruction of all available copies of the Licensed Technology, governmental actions such as changes in law or embargoes, cyberattacks including but not limited to significant DDoS attacks or other cybersecurity breaches that disrupt services, critical infrastructure failure involving essential utilities including but not limited to electricity or internet services, but in every case the failure to perform must be beyond the control and without the fault or negligence of the affected Party and cannot be avoided or circumvented by such party ("Force Majeure Event"). In the occurrence of any such event, the affected Party shall notify the other Party as soon as reasonably possible and shall use all reasonable endeavors to mitigate the effects of the Force Majeure Event. If the Force Majeure Event results in a delay or non-performance of a Party for a period of three (3) months or longer, then either Party shall have the right to terminate this Agreement with immediate effect without any liability (except for the obligations of payment arising prior to the Force Majeure Event) towards the other Party. + +### 14. Indemnification + +Under this Agreement, the Licensee agrees to indemnify, defend, and hold harmless the Licensor, its officers, directors, employees, agents, affiliates, successors, and assigns from any liabilities, damages, judgments, awards, losses, costs, expenses, including reasonable attorney and expert witness fees, arising out of or in connection with any third-party claims, suits, actions, or proceedings. This indemnity covers claims resulting from the Licensee's breach of this Agreement, negligence, willful misconduct, use of the Licensed Technology, or related to the Licensee's products. Excluded from this indemnification are claims alleging that the Licensee's authorized use of unmodified Licensed Technology provided by the Licensor infringes any patent, trademark, or copyright. The Licensor reserves the right, at its option and sole discretion, to assume full control of the defense of such claims with legal counsel of its choice. The Licensee is not permitted to enter into any third-party agreement that would affect the Licensor's rights, constitute an admission of fault by the Licensor, or bind the Licensor in any manner, without the Licensor's prior written consent. The Licensee must promptly notify the Licensor in writing of any claims brought against the Licensor for which indemnification or defense is sought, thereby enabling the Licensor to manage legal strategies and potential settlements effectively. For the avoidance of doubt, the Licensor does not have any obligation to defend the Licensee or any End-User against such claim and therefore such defense shall be up to the Licensor's sole discretion. If the Licensor decides to not defend a claim for infringement of Intellectual Property Rights, the Licensee may defend itself through counsel of its own choice and at its own expense. The Licensor shall have no liability for any costs, expenses, losses or damages incurred by the Licensee or any of its End-Users in the event of such claim. + +### 15. Governing Law and Jurisdiction + +The Licensor and the Licensee hereby mutually concur that the governance and interpretation of this Agreement shall be in strict accordance with the legal statutes and principles as stipulated in Appendix A. + +### 16. Dispute Resolution + +16.1 It is explicitly agreed that any dispute, controversy, or claim that may arise out of, or in connection with, this contract, inclusive of, but not limited to, its formation, interpretation, breach, or termination, and the arbitrability of the claims posited therein, shall be definitively resolved through arbitration. This arbitration shall be conducted in full alignment with the JAMS International Arbitration Rules. + +16.2 Furthermore, the arbitral tribunal shall be comprised of a sole arbitrator. The venue for such arbitration proceedings shall be as delineated in Appendix A of this Agreement. Moreover, the proceedings of the arbitration shall be conducted in the language specified within Appendix A. It is hereby declared that the award rendered by the said arbitrator shall be binding and enforceable, and judgment thereon may be entered in any court of competent jurisdiction. + +### 17. Confidentiality + +17.1 During the term of this Agreement and thereafter until Confidential Information becomes subject to one or more of the exceptions set forth in Section 17.3, each Party shall maintain strict confidentiality regarding the other Party's Confidential Information. "Confidential Information" shall include, but is not limited to, the Licensed Technology, trade secrets, business plans, strategies, customer information, and any other proprietary or sensitive information disclosed by one Party to the other. + +17.2 Each Party agrees to use the Confidential Information solely for the purposes of exercising its rights and fulfilling its obligations under this Agreement. The receiving Party shall not disclose or permit access to Confidential Information to any third party, except to its Employees, Contractors, or agents who need to know such information for the purposes of this Agreement and who are bound by confidentiality obligations no less protective than those set forth herein. + +17.3 The confidentiality obligations shall not apply to information that: (a) is or becomes publicly available through no fault of the receiving Party; (b) was known to the receiving Party prior to disclosure; (c) is independently developed by the receiving Party without use of or reference to the Confidential Information; or (d) is required to be disclosed by law or court order, provided that the receiving Party gives prompt notice to the disclosing Party to enable it to seek a protective order. + +------------------------------------------------------------------------------- + +# GNU General Public License version 3 + +**Preamble** + +The GNU General Public License is a free, copyleft license for software and other kinds of works. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program–to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. + +To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. + +For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. + +Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. + +For the developers’ and authors’ protection, the GPL clearly explains that there is no warranty for this free software. For both users’ and authors’ sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. + +Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users’ freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. + +Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. + +The precise terms and conditions for copying, distribution and modification follow. + +**TERMS AND CONDITIONS** +**0. Definitions.** + +“This License” refers to version 3 of the GNU General Public License. + +“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. + +“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations. + +To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work. + +A “covered work” means either the unmodified Program or a work based on the Program. + +To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. + +To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. + +**1. Source Code.** + +The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work. + +A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. + +The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. + +The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work’s System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +**2. Basic Permissions.** + +All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. + +**3. Protecting Users’ Legal Rights From Anti-Circumvention Law.** + +No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work’s users, your or third parties’ legal rights to forbid circumvention of technological measures. + +**4. Conveying Verbatim Copies.** + +You may convey verbatim copies of the Program’s source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. + +**5. Conveying Modified Source Versions.** + +You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: + +- a) The work must carry prominent notices stating that you modified it, and giving a relevant date. +- b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”. +- c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. +- d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. + +A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation’s users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. + +**6. Conveying Non-Source Forms.** + +You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: + +- a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. +- b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. +- c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. +- d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. +- e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. + +A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. + +“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). + +The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. + +**7. Additional Terms.** + +“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: + +- a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or +- b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or +- c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or +- d) Limiting the use for publicity purposes of names of licensors or authors of the material; or +- e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or +- f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. + +All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. + +**8. Termination.** + +You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. + +**9. Acceptance Not Required for Having Copies.** + +You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. + +**10. Automatic Licensing of Downstream Recipients.** + +Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. + +An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party’s predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. + +**11. Patents.** + +A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor’s “contributor version”. + +A contributor’s “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor’s essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. + +In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient’s use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. + +A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. + +**12. No Surrender of Others’ Freedom.** + +If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. + +**13. Use with the GNU Affero General Public License.** + +Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. + +**14. Revised Versions of this License.** + +The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy’s public statement of acceptance of a version permanently authorizes you to choose that version for the Program. + +Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. + +**15. Disclaimer of Warranty.** + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +**16. Limitation of Liability.** + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +**17. Interpretation of Sections 15 and 16.** + +If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. \ No newline at end of file diff --git a/third_party/SimpleBLE/MANIFEST.in b/third_party/SimpleBLE/MANIFEST.in new file mode 100644 index 000000000..dd35566cb --- /dev/null +++ b/third_party/SimpleBLE/MANIFEST.in @@ -0,0 +1,178 @@ +include LICENSE.md +include VERSION +include cmake/epilogue.cmake +include cmake/find/FindDBus1.cmake +include cmake/find/Findfmt.cmake +include cmake/parse_version.cmake +include cmake/prelude.cmake +include pyproject.toml +include setup.py +include simpleble/CMakeLists.txt +include simpleble/cmake/simpleble.pc.in +include simpleble/include/simpleble/Adapter.h +include simpleble/include/simpleble/AdapterSafe.h +include simpleble/include/simpleble/Characteristic.h +include simpleble/include/simpleble/Descriptor.h +include simpleble/include/simpleble/Exceptions.h +include simpleble/include/simpleble/Logging.h +include simpleble/include/simpleble/Peripheral.h +include simpleble/include/simpleble/PeripheralSafe.h +include simpleble/include/simpleble/Service.h +include simpleble/include/simpleble/SimpleBLE.h +include simpleble/include/simpleble/Types.h +include simpleble/include/simpleble/Utils.h +include simpleble/include/simpleble_c/adapter.h +include simpleble/include/simpleble_c/logging.h +include simpleble/include/simpleble_c/peripheral.h +include simpleble/include/simpleble_c/simpleble.h +include simpleble/include/simpleble_c/types.h +include simpleble/include/simpleble_c/utils.h +include simpleble/src/CommonUtils.h +include simpleble/src/Exceptions.cpp +include simpleble/src/Logging.cpp +include simpleble/src/LoggingInternal.h +include simpleble/src/Utils.cpp +include simpleble/src/backends/common/AdapterBaseTypes.h +include simpleble/src/backends/common/CharacteristicBase.cpp +include simpleble/src/backends/common/CharacteristicBase.h +include simpleble/src/backends/common/DescriptorBase.cpp +include simpleble/src/backends/common/DescriptorBase.h +include simpleble/src/backends/common/ServiceBase.cpp +include simpleble/src/backends/common/ServiceBase.h +include simpleble/src/backends/linux/AdapterBase.cpp +include simpleble/src/backends/linux/AdapterBase.h +include simpleble/src/backends/linux/Bluez.cpp +include simpleble/src/backends/linux/Bluez.h +include simpleble/src/backends/linux/PeripheralBase.cpp +include simpleble/src/backends/linux/PeripheralBase.h +include simpleble/src/backends/macos/AdapterBase.h +include simpleble/src/backends/macos/AdapterBase.mm +include simpleble/src/backends/macos/AdapterBaseMacOS.h +include simpleble/src/backends/macos/AdapterBaseMacOS.mm +include simpleble/src/backends/macos/PeripheralBase.h +include simpleble/src/backends/macos/PeripheralBase.mm +include simpleble/src/backends/macos/PeripheralBaseMacOS.h +include simpleble/src/backends/macos/PeripheralBaseMacOS.mm +include simpleble/src/backends/macos/Utils.h +include simpleble/src/backends/macos/Utils.mm +include simpleble/src/backends/plain/AdapterBase.cpp +include simpleble/src/backends/plain/AdapterBase.h +include simpleble/src/backends/plain/PeripheralBase.cpp +include simpleble/src/backends/plain/PeripheralBase.h +include simpleble/src/backends/windows/AdapterBase.cpp +include simpleble/src/backends/windows/AdapterBase.h +include simpleble/src/backends/windows/PeripheralBase.cpp +include simpleble/src/backends/windows/PeripheralBase.h +include simpleble/src/backends/windows/Utils.cpp +include simpleble/src/backends/windows/Utils.h +include simpleble/src/builders/AdapterBuilder.cpp +include simpleble/src/builders/AdapterBuilder.h +include simpleble/src/builders/CharacteristicBuilder.cpp +include simpleble/src/builders/CharacteristicBuilder.h +include simpleble/src/builders/DescriptorBuilder.cpp +include simpleble/src/builders/DescriptorBuilder.h +include simpleble/src/builders/PeripheralBuilder.cpp +include simpleble/src/builders/PeripheralBuilder.h +include simpleble/src/builders/ServiceBuilder.cpp +include simpleble/src/builders/ServiceBuilder.h +include simpleble/src/external/kvn_safe_callback.hpp +include simpleble/src/external/logfwd.hpp +include simpleble/src/frontends/base/Adapter.cpp +include simpleble/src/frontends/base/Characteristic.cpp +include simpleble/src/frontends/base/Descriptor.cpp +include simpleble/src/frontends/base/Peripheral.cpp +include simpleble/src/frontends/base/Service.cpp +include simpleble/src/frontends/safe/AdapterSafe.cpp +include simpleble/src/frontends/safe/PeripheralSafe.cpp +include simpleble/src_c/adapter.cpp +include simpleble/src_c/logging.cpp +include simpleble/src_c/peripheral.cpp +include simpleble/src_c/simpleble.cpp +include simpleble/src_c/utils.cpp +include simplebluez/CMakeLists.txt +include simplebluez/cmake/simplebluez.pc.in +include simplebluez/include/simplebluez/Adapter.h +include simplebluez/include/simplebluez/Agent.h +include simplebluez/include/simplebluez/Bluez.h +include simplebluez/include/simplebluez/Characteristic.h +include simplebluez/include/simplebluez/Descriptor.h +include simplebluez/include/simplebluez/Device.h +include simplebluez/include/simplebluez/Exceptions.h +include simplebluez/include/simplebluez/ProxyOrg.h +include simplebluez/include/simplebluez/ProxyOrgBluez.h +include simplebluez/include/simplebluez/Service.h +include simplebluez/include/simplebluez/Types.h +include simplebluez/include/simplebluez/interfaces/Adapter1.h +include simplebluez/include/simplebluez/interfaces/Agent1.h +include simplebluez/include/simplebluez/interfaces/AgentManager1.h +include simplebluez/include/simplebluez/interfaces/Battery1.h +include simplebluez/include/simplebluez/interfaces/Device1.h +include simplebluez/include/simplebluez/interfaces/GattCharacteristic1.h +include simplebluez/include/simplebluez/interfaces/GattDescriptor1.h +include simplebluez/include/simplebluez/interfaces/GattService1.h +include simplebluez/src/Adapter.cpp +include simplebluez/src/Agent.cpp +include simplebluez/src/Bluez.cpp +include simplebluez/src/Characteristic.cpp +include simplebluez/src/Descriptor.cpp +include simplebluez/src/Device.cpp +include simplebluez/src/Exceptions.cpp +include simplebluez/src/Logging.cpp +include simplebluez/src/Logging.h +include simplebluez/src/ProxyOrg.cpp +include simplebluez/src/ProxyOrgBluez.cpp +include simplebluez/src/Service.cpp +include simplebluez/src/interfaces/Adapter1.cpp +include simplebluez/src/interfaces/Agent1.cpp +include simplebluez/src/interfaces/AgentManager1.cpp +include simplebluez/src/interfaces/Battery1.cpp +include simplebluez/src/interfaces/Device1.cpp +include simplebluez/src/interfaces/GattCharacteristic1.cpp +include simplebluez/src/interfaces/GattDescriptor1.cpp +include simplebluez/src/interfaces/GattService1.cpp +include simpledbus/CMakeLists.txt +include simpledbus/cmake/simpledbus.pc.in +include simpledbus/include/simpledbus/advanced/Interface.h +include simpledbus/include/simpledbus/advanced/Proxy.h +include simpledbus/include/simpledbus/base/Connection.h +include simpledbus/include/simpledbus/base/Exceptions.h +include simpledbus/include/simpledbus/base/Holder.h +include simpledbus/include/simpledbus/base/Message.h +include simpledbus/include/simpledbus/base/Path.h +include simpledbus/include/simpledbus/external/kvn_safe_callback.hpp +include simpledbus/include/simpledbus/external/logfwd.hpp +include simpledbus/include/simpledbus/interfaces/ObjectManager.h +include simpledbus/src/advanced/Interface.cpp +include simpledbus/src/advanced/Proxy.cpp +include simpledbus/src/base/Connection.cpp +include simpledbus/src/base/Exceptions.cpp +include simpledbus/src/base/Holder.cpp +include simpledbus/src/base/Logging.cpp +include simpledbus/src/base/Logging.h +include simpledbus/src/base/Message.cpp +include simpledbus/src/base/Path.cpp +include simpledbus/src/interfaces/ObjectManager.cpp +include simplepyble/CMakeLists.txt +include simplepyble/README.rst +include simplepyble/requirements.txt +include simplepyble/src/main.cpp +include simplepyble/src/simplepyble/__init__.py +include simplepyble/src/wrap_adapter.cpp +include simplepyble/src/wrap_characteristic.cpp +include simplepyble/src/wrap_descriptor.cpp +include simplepyble/src/wrap_peripheral.cpp +include simplepyble/src/wrap_service.cpp +include simplepyble/src/wrap_types.cpp +prune .github +prune docs +prune examples +prune simpleble/test +prune simplebluez/test +prune simpledbus/test +prune simplersble +prune utils +exclude MANIFEST.in +exclude .clang-format +exclude .gitignore +exclude .readthedocs.yaml +exclude README.rst diff --git a/third_party/SimpleBLE/README.rst b/third_party/SimpleBLE/README.rst index 3262fefce..7022d14ad 100644 --- a/third_party/SimpleBLE/README.rst +++ b/third_party/SimpleBLE/README.rst @@ -9,16 +9,19 @@ Overview -------- The SimpleBLE project aims to provide fully cross-platform BLE libraries and bindings -for Python and C++, designed for simplicity and ease of use with a licencing scheme -chosen to be friendly towards commercial use. All specific operating system quirks -are handled internally to provide a consistent behavior across all platforms. The -libraries also provide first-class support for vendorization of all third-party -dependencies, allowing for easy integration into existing projects. +for C++, Python, Rust and other languages, designed for simplicity and ease of use. +All specific operating system quirks are handled internally to provide a consistent behavior +and API across all platforms. The libraries also provide first-class support for vendorization +of all third-party dependencies, allowing for easy integration into existing projects. -This repository offers the source code for the following related libraries: +**NOTICE: Since February 20, 2024 the license terms of SimpleBLE have changed. Please make sure to read and understand the details below.** + +Below you'll find a list of components that are part of SimpleBLE: * **SimpleBLE:** C++ cross-platform BLE library. -* **SimplePyBLE:** Python bindings for SimpleBLE. See `SimplePyBLE`_ PyPI page for more details. +* **SimplePyBLE:** Python bindings for SimpleBLE. See the `SimplePyBLE`_ PyPI page for more details. +* **SimpleDroidBLE:** Android-specific package following the SimpleBLE API. (Still in Alpha, more to come) +* **SimpleRsBLE:** Rust bindings for SimpleBLE (LEGACY - Big refactor coming soon). See the `SimpleRsBLE`_ Crates.io page for more details. * **SimpleBluez:** C++ abstraction layer for BlueZ over DBus. (Linux only) * **SimpleDBus:** C++ wrapper for libdbus-1 with convenience classes to handle DBus object hierarchies effectively. (Linux only) @@ -26,25 +29,43 @@ If you want to use SimpleBLE and need help. **Please do not hesitate to reach ou * Visit our `ReadTheDocs`_ page. * Join our `Discord`_ server. -* Contact me: ``kevin at dewald dot me`` (Dedicated consulting services available) - -Are you using SimpleBLE on your own project and would like to see it featured here? -Reach out and I'll add a link to it below! +* Contact us: ``contact at simpleble dot org`` +* Visit our `website`_ for more information. Supported platforms ------------------- -=========== ============= =================================== ===== -Windows Linux MacOS iOS -=========== ============= =================================== ===== -Windows 10+ Ubuntu 20.04+ 10.15+ (except 12.0, 12.1 and 12.2) 15.0+ -=========== ============= =================================== ===== + +.. list-table:: + :header-rows: 1 + + * - Platform + - Versions + - Notes + * - Windows + - Windows 10+ + - • WSL does not support Bluetooth. + • Only a single adapter is supported by the OS backend. + * - Linux + - Ubuntu 20.04+ + - • Other distros using Bluez as their Bluetooth backend should work. + * - MacOS + - 10.15+ (Catalina and newer) + - • MacOS 12.0, 12.1, and 12.2 have a bug where the adapter won't return any peripherals after scanning. + • Only a single adapter is supported by the OS backend. + * - iOS + - 15.0+ + - • Older versions of iOS might work but haven't been formally tested. + * - Android (Alpha) + - API 31+ + - • Older APIs are missing certain features of the JVM API that are required by SimpleBLE. Projects using SimpleBLE ------------------------ Don't forget to check out the following projects using SimpleBLE: -* `GDSimpleBLE`_ * `BrainFlow`_ +* `InsideBlue`_ +* `NodeWebBluetooth`_ Contributing ------------ @@ -52,16 +73,71 @@ Pull requests are welcome. For major changes, please open an issue first to disc what you would like to change. License -------- +======= + +Since February 15th 2024, SimpleBLE is now available under the GNU General Public License +version 3 (GPLv3), with the option for a commercial license without the GPLv3 restrictions +available for a fee. + +**You can find more information on pricing and commercial terms of service on our `website`_.** + +For further enquiries, please contact us at ``contact at simpleble dot org``. + +Licensing FAQ +------------- + +I'm already using SimpleBLE. What happens to my project? +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Please reach out at ``contact at simpleble dot org`` and we can discuss the specifics of your +situation. It is my intention to make this transition as smooth as possible for existing users, +and I'm open to finding a solution that works for everyone. -All components within this project that have not been bundled from -external creators, are licensed under the terms of the `MIT Licence`_. +If you are using SimpleBLE in an open-source project and would like to request +a free commercial license or if you have any other questions, do not hesitate to reach out. + +Why are you making this change? +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +So far, SimpleBLE has been a labor of passion with over 4000 hours invested in multiple iterations. +The decision to transition SimpleBLE to a dual-licensing model is mainly driven by the kind +of products that have been built around it, in particular around notable names in the medical +and industrial sectors, which has been both surprising and encouraging. Providing robust support for +these diverse and critical use cases is a resource-intensive endeavor which can't be achieved on +goodwill alone, especially so when the underlying APIs are also evolving and life having its own +plans. By introducing a commercial license, we're opening a pathway to dedicate more resources to +enhance SimpleBLE. Some of the things on the roadmap include: + +- Bindings into more languages and frameworks. +- Hardware-in-the-loop test infrastructure. +- Offering bounties and revenue sharing with other developers who contribute. +- Providing more comprehensive documentation and tutorials. + +Despite this transition, We remain firmly committed to the open-source philosophy. SimpleBLE was grown +a lot thanks to the feedback of the open-source community, and that foundation will always be a part +of the project. The GPLv3 license option ensures continued accessibility for open-source projects, +and we pledge to actively contribute to and collaborate with the community whenever possible. + +Ultimately, the success of SimpleBLE has been fueled by its open nature, and we believe this +dual-licensing model strengthens that success by enabling both community-driven growth and +targeted enhancements that benefit everyone. + +What does the GPLv3 license imply for my commercial project? +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +The GPLv3 license ensures that end users have the freedom to run, study, share, and modify the software. +It requires that any modified versions of SimpleBLE, or any software incorporating it, also be +distributed under the GPLv3. Essentially, if your project incorporates SimpleBLE and is distributed, +the entire codebase must be open-source under the GPLv3. + +You can find the full text of the GPLv3 license at https://www.gnu.org/licenses/gpl-3.0.html. .. Links +.. _website: https://simpleble.org + .. _SimplePyBLE: https://pypi.org/project/simplepyble/ -.. _MIT Licence: https://github.com/OpenBluetoothToolbox/SimpleBLE/blob/main/LICENCE.md +.. _SimpleRsBLE: https://crates.io/crates/simplersble .. _Discord: https://discord.gg/N9HqNEcvP3 @@ -73,4 +149,6 @@ external creators, are licensed under the terms of the `MIT Licence`_. .. Other projects using SimpleBLE .. _GDSimpleBLE: https://github.com/jferdelyi/GDSimpleBLE -.. _BrainFlow: https://github.com/brainflow-dev/brainflow \ No newline at end of file +.. _BrainFlow: https://github.com/brainflow-dev/brainflow +.. _InsideBlue: https://github.com/eriklins/InsideBlue-BLE-Tool +.. _NodeWebBluetooth: https://github.com/thegecko/webbluetooth diff --git a/third_party/SimpleBLE/VERSION b/third_party/SimpleBLE/VERSION index a918a2aa1..a3df0a695 100644 --- a/third_party/SimpleBLE/VERSION +++ b/third_party/SimpleBLE/VERSION @@ -1 +1 @@ -0.6.0 +0.8.0 diff --git a/third_party/SimpleBLE/cmake/find/FindDBus1.cmake b/third_party/SimpleBLE/cmake/find/FindDBus1.cmake index f005458bd..b61b16310 100644 --- a/third_party/SimpleBLE/cmake/find/FindDBus1.cmake +++ b/third_party/SimpleBLE/cmake/find/FindDBus1.cmake @@ -17,10 +17,4 @@ if(NOT DBus1_FOUND) set(DBus1_FOUND ${PC_DBUS_FOUND}) - # get_cmake_property(_variableNames VARIABLES) - # list (SORT _variableNames) - # foreach (_variableName ${_variableNames}) - # message(STATUS "${_variableName}=${${_variableName}}") - # endforeach() - endif() diff --git a/third_party/SimpleBLE/cmake/find/Findfmt.cmake b/third_party/SimpleBLE/cmake/find/Findfmt.cmake index ed053dff6..3385f3558 100644 --- a/third_party/SimpleBLE/cmake/find/Findfmt.cmake +++ b/third_party/SimpleBLE/cmake/find/Findfmt.cmake @@ -10,7 +10,7 @@ if(LIBFMT_VENDORIZE) set(LIBFMT_GIT_REPOSITORY "https://github.com/fmtlib/fmt.git") endif() if(NOT LIBFMT_GIT_TAG) - set(LIBFMT_GIT_TAG "b6f4ceaed0a0a24ccf575fab6c56dd50ccf6f1a9") # v8.1.1 + set(LIBFMT_GIT_TAG "a33701196adfad74917046096bf5a2aa0ab0bb50") # v9.1.0 endif() if(NOT LIBFMT_LOCAL_PATH) diff --git a/third_party/SimpleBLE/docs/Doxyfile b/third_party/SimpleBLE/docs/Doxyfile index c01742bb7..0e99c25bc 100644 --- a/third_party/SimpleBLE/docs/Doxyfile +++ b/third_party/SimpleBLE/docs/Doxyfile @@ -908,7 +908,7 @@ WARN_LOGFILE = # spaces. See also FILE_PATTERNS and EXTENSION_MAPPING # Note: If this tag is empty the current directory is searched. -INPUT = ../simpleble/include +INPUT = ../simpleble/include ../external/include # This tag can be used to specify the character encoding of the source files # that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses diff --git a/third_party/SimpleBLE/docs/changelog.rst b/third_party/SimpleBLE/docs/changelog.rst index 20f103783..32ac24827 100644 --- a/third_party/SimpleBLE/docs/changelog.rst +++ b/third_party/SimpleBLE/docs/changelog.rst @@ -5,7 +5,77 @@ All notable changes to this project will be documented in this file. The format is based on `Keep a Changelog`_, and this project adheres to `Semantic Versioning`_. -[0.6.0] - 2022-XX-XX +[0.8.0] - XXXX-XX-XX +-------------------- + +**Added** + +- (Android) Alpha preview of Android support. +- (SimpleDBus) Added templated version of creation and getter functions for Holder class. *(Thanks lorsi96!)* + +**Changed** + +- Implemented standalone ByteArray class derived from `kvn::bytearray`. *(Thanks tlifschitz!)* +- **API CHANGE**: Notify and Indicate callback in C bindings now receive the peripheral handle as the first argument. + +**Fixed** + +- (SimpleBluez) Fixed improper handling of non `org.Bluez.Service1` objects within a `org.bluez.Device1` object. *(Thanks Kober Engineering!)* +- (MacOS) Fixed incorrect storage and retrieval with standard Bluetooth UUIDs inside the peripheral class. *(Thanks TellowKrinkle!)* +- (Python) Fixed incorrect handling of the GIL in certain functions. *(Thanks nomenquis and Medra AI!)* + + +[0.7.X] +-------------------- + +This entire series is dedicated to reviewing and updating the license terms of the project. + + +[0.7.0] - 2024-02-15 +-------------------- + +**Added** + +- Function to query the version of SimpleBLE at runtime. +- (Python) Missing API from SimpleBLE::Characteristic. + +**Changed** + +- (MacOS) Main adapter address is now hardcoded to allow caching based on adapter address. *(Thanks BlissChapman!)* +- (Python) Release GIL when calling ``Peripheral.write_request`` and ``Peripheral.write_command``. +- (MacOS) Rewrote the entire backend. +- (MacOS) OperationFailed exception now contains the error message provided by the OS. + +**Fixed** + +- (MacOS) Remove unnecessary timeout during service discovery. *(Thanks BlissChapman!)* +- (MacOS) Return correct list of devices when scanning. *(Thanks roozmahdavian!)* +- (MacOS) Remove unnecessary timeout during characteristic notification. *(Thanks BlissChapman!)* +- (MacOS) Remove unnecessary timeout during operations on characteristics. +- (Windows) Failed connection attempt would not trigger an exception. *(Thanks eriklins!)* +- (Linux) Use correct UUIDs for advertized services. *(Thanks Symbitic!)* + + +[0.6.1] - 2023-03-14 +-------------------- + +**Added** + +- (Python) Generate source distribution packages. +- (SimpleDBus) Proxy objects keep track of their existence on the DBus object tree. + +**Changed** + +- Bluetooth enabled check was moved into the frontend modules. *(Thanks felixdollack!)* +- (Windows) Use the standard C++ exception handling model. *(Thanks TheFrankyJoe!)* + +**Fixed** + +- CI artifacts for non-standard architectures are now properly built. +- (SimpleBluez) Fixed incorrect handling of invalidated children objects. + + +[0.6.0] - 2023-02-23 -------------------- **Added** @@ -14,22 +84,48 @@ The format is based on `Keep a Changelog`_, and this project adheres to `Semanti - Support for advertized services. - Support for GATT Characteristic properties. - Retrieve the MTU value of an established connection. *(Thanks Marco Cruz!)* +- Peripheral addresses can now be queried for their type. *(Thanks camm73!)* +- Tx Power is decoded from advertising data if available. *(Thanks camm73!)* +- Logger now provides default functions to log to a file or to stdout. +- Support for exposing advertized service data. *(Thanks Symbitic!)* +- (Rust) Preliminary implementation of Rust bindings. - (Windows) Logging of WinRT initialization behavior. - (SimpleBluez) Support for GATT characteristic flags. - (SimpleBluez) Support for GATT characteristic MTUs. *(Thanks Marco Cruz!)* - (SimpleBluez) Support for advertized services. +- (SimpleBluez) Mechanism to select the default DBus bus type during compilation-time. *(Thanks MrMinos!)* **Changed** +- Debug, MinSizeRel and RelWithDebInfo targets now contain their appropriate suffix. *(Thanks kutij!)* +- **API CHANGE**: Log level convention changed from uppercase to capitalizing the first letter. +- Updated ``libfmt`` dependency to version 9.1.0. +- Unused ``libfmt`` targets removed from the build process. - (MacOS) More explicit exception messages. - (MacOS) 16-bit UUIDs are now presented in their 128-bit form. +- (MacOS) Adapter address now swapped for a random UUID. *(Thanks nothingisdead!)* +- (Windows) Reinitialize the WinRT backend if a single-threaded apartment is detected. *(Thanks jferdelyi!)* +- (Windows) Callbacks for indications and notifications are now swapped if one already exists. **Fixed** - Incorrect handling of services and characteristics in the Python examples. *(Thanks Carl-CWX!)* +- Minor potential race condition in the safe callback. +- Compilation-time log levels were not being set correctly. *(Thanks chen3496!)* +- Missing function definition in C-bindings. *(Thanks eriklins!)* +- (Linux) Peripheral would still issue callbacks after deletion. - (MacOS) Increased priority of the dispatch queue to prevent jitter in the incoming data. +- (MacOS) Incorrect listing of advertized services. *(Thanks eriklins & Symbitic!)* - (Windows) Missing peripheral identifier data. *(Thanks eriklins!)* -- (Windows) Multiple initialization of the WinRT backend. +- (Windows) Multiple initializations of the WinRT backend. +- (Windows) Incorrect initialization of the WinRT backend. *(Thanks ChatGPT & Andrey1994!)* +- (Windows) Scan callbacks would continue after scan stopped. +- (Windows) Disconnecting would prevent the user from connecting again. *(Thanks klaff, felixdollack & lairdrt!)* +- (Windows) Uncleared callbacks when unsubscribe is called. +- (Windows) Incorrect handling of non-english locale by MSVC. *(Thanks felixdollack!)* +- (Windows) Disconnection callback would not be triggered on a manual disconnect. *(Thanks crashtua!)* +- (Python) Type returned by ``simplepyble.get_operating_system()`` was not defined. +- (SimpleBluez) Incorrect attempt to operate on an uninitialized DBus connection. *(Thanks jacobbreen25!)* [0.5.0] - 2022-09-25 @@ -102,8 +198,8 @@ The format is based on `Keep a Changelog`_, and this project adheres to `Semanti - Updated Linux implementation to use SimpleBluez v0.5.0. - Added support for Windows SDK 10.0.22000.0 -- Updated libfmt to version 8.1.1. -- Cleaned up dependency management for libfmt and SimpleBluez. +- Updated ``libfmt`` to version 8.1.1. +- Cleaned up dependency management for ``libfmt`` and SimpleBluez. - ``Adapter::get_paired_peripherals`` will return an empty list on Windows and MacOS. - (Linux) **(Experimental)** Exceptions thrown inside the Bluez async thread are now caught to prevent lockups. - ``NotConnected`` exception will be thrown instead of ``OperationFailed`` when peripheral not connected. diff --git a/third_party/SimpleBLE/docs/conf.py b/third_party/SimpleBLE/docs/conf.py index 63c640f68..dcb3b5d72 100644 --- a/third_party/SimpleBLE/docs/conf.py +++ b/third_party/SimpleBLE/docs/conf.py @@ -36,6 +36,7 @@ "sphinx.ext.autodoc", "sphinx.ext.autosummary", "sphinx.ext.napoleon", + 'sphinxcontrib.mermaid', 'breathe' ] @@ -65,6 +66,8 @@ html_static_path = ['_static'] # -- Extension configuration ------------------------------------------------- -breathe_projects = { 'simpleble': '_doxygen/xml' } +breathe_projects = { 'simpleble': '_doxygen/xml', + 'external': '_doxygen/xml' + } autosummary_generate = True diff --git a/third_party/SimpleBLE/docs/extras.rst b/third_party/SimpleBLE/docs/extras.rst index 839da736d..e028efabc 100644 --- a/third_party/SimpleBLE/docs/extras.rst +++ b/third_party/SimpleBLE/docs/extras.rst @@ -1,11 +1,14 @@ -====================== +Extras +====== + Building documentation -====================== +---------------------- + To build documentation for the projects in this repository, you first need to install Sphynx, using the following commands: :: - pip3 install sphinx sphinx_rtd_theme + pip3 install -r docs/requirements.txt Once all dependencies have been installed, HTML documentation can be built by calling the following commands: :: @@ -13,19 +16,25 @@ by calling the following commands: :: cd /docs make html - -================= Release checklist -================= +----------------- Before releasing a new version of the project, the following steps should be performed: +#. Ensure content parity between all readmes and the documentation. + + - ``README.rst`` + - ``LICENSE.md`` + - ``simplepyble/README.rst`` + - ``simplersble/README.md`` + #. Review/update the version number in the following files: - ``VERSION`` + - ``Cargo.toml`` - ``docs/changelog.rst`` - - ``simplepyble/setup.py`` + - ``setup.py`` (Add or remove the ``.devX`` suffix as needed.) #. Commit the changes to the repository. @@ -37,8 +46,14 @@ performed: #. Run the CI job to build and upload the package to PyPI. +#. Run the CI job to build and upload the artifacts to GitHub. + +#. Perform a manual release of the Rust crate to crates.io. + - ``cargo publish`` (Ensure that the version number in ``Cargo.toml`` is correct.) + #. Advance the version number in the following files: - ``VERSION`` + - ``Cargo.toml`` - ``docs/changelog.rst`` - - ``simplepyble/setup.py`` + - ``setup.py`` (Add or remove the ``.devX`` suffix as needed.) diff --git a/third_party/SimpleBLE/docs/index.rst b/third_party/SimpleBLE/docs/index.rst index 4355ea019..36f7a0df9 100644 --- a/third_party/SimpleBLE/docs/index.rst +++ b/third_party/SimpleBLE/docs/index.rst @@ -1,5 +1,5 @@ SimpleBLE -========== +========= The ultimate fully-fledged cross-platform library and bindings for Bluetooth Low Energy (BLE). @@ -15,6 +15,7 @@ Table of Contents :caption: General overview + licensing_faq changelog extras @@ -34,6 +35,12 @@ Table of Contents simplepyble/usage simplepyble/api +.. toctree:: + :maxdepth: 2 + :caption: SimpleDroidBLE + + simpledroidble/usage + .. toctree:: :maxdepth: 2 :caption: SimpleBluez diff --git a/third_party/SimpleBLE/docs/licensing_faq.rst b/third_party/SimpleBLE/docs/licensing_faq.rst new file mode 100644 index 000000000..3194d0f0d --- /dev/null +++ b/third_party/SimpleBLE/docs/licensing_faq.rst @@ -0,0 +1,1387 @@ + +License +======= + +Since February 15th 2024, SimpleBLE is now available under the GNU General Public License +version 3 (GPLv3), with the option for a commercial license without the GPLv3 restrictions +available for a fee. You can find more information on pricing and commercial terms of service +on our `website`_. + +For further enquiries, please contact us at ``contact at simpleble dot org``. + +Likewise, if you are using SimpleBLE in an open-source project and would +like to request a free commercial license or if you have any other +questions, please reach out at ``contact at simpleble dot org``. + +Licensing FAQ +------------- + +I'm already using SimpleBLE. What happens to my project? +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Please reach out at ``contact at simpleble dot org`` and we can discuss the specifics of your +situation. It is my intention to make this transition as smooth as possible for existing users, +and I'm open to finding a solution that works for everyone. + +If you are using SimpleBLE in an open-source project and would like to request +a free commercial license or if you have any other questions, do not hesitate to reach out. + +Why are you making this change? +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +So far, SimpleBLE has been a labor of passion with over 4000 hours invested in multiple iterations. +The decision to transition SimpleBLE to a dual-licensing model is mainly driven by the kind +of products that have been built around it, in particular around notable names in the medical +and industrial sectors, which has been both surprising and encouraging. Providing robust support for +these diverse and critical use cases is a resource-intensive endeavor which can't be achieved on +goodwill alone, especially so when the underlying APIs are also evolving and life having its own +plans. By introducing a commercial license, we're opening a pathway to dedicate more resources to +enhance SimpleBLE. Some of the things on the roadmap include: + +- Bindings into more languages and frameworks. +- Hardware-in-the-loop test infrastructure. +- Offering bounties and revenue sharing with other developers who contribute. +- Providing more comprehensive documentation and tutorials. + +Despite this transition, We remain firmly committed to the open-source philosophy. SimpleBLE was grown +a lot thanks to the feedback of the open-source community, and that foundation will always be a part +of the project. The GPLv3 license option ensures continued accessibility for open-source projects, +and we pledge to actively contribute to and collaborate with the community whenever possible. + +Ultimately, the success of SimpleBLE has been fueled by its open nature, and we believe this +dual-licensing model strengthens that success by enabling both community-driven growth and +targeted enhancements that benefit everyone. + +What does the GPLv3 license imply for my commercial project? +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +The GPLv3 license ensures that end users have the freedom to run, study, share, and modify the software. +It requires that any modified versions of SimpleBLE, or any software incorporating it, also be +distributed under the GPLv3. Essentially, if your project incorporates SimpleBLE and is distributed, +the entire codebase must be open-source under the GPLv3. + +You can find the full text of the GPLv3 license at https://www.gnu.org/licenses/gpl-3.0.html. + + +-------------- + +SimpleBLE Commercial License Agreement +-------------------------------------- + +Version 1.2 - 2024-06-28 + +Copyright © 2024 - THE CALIFORNIA OPEN SOURCE COMPANY LLC + +Everyone is permitted to copy and distribute verbatim copies of this +license document, but changing it is not allowed. + +0. Definitions +^^^^^^^^^^^^^^ + +- **“Licensed Technology”** shall mean the software, documentation, + code, materials, and any other intellectual property specified in + Appendix A as provided by the Licensor to the Licensee under this + Agreement, as well as any updates, modifications, or improvements + thereto made by either the Licensor or the Licensee. + +- **“Licensor”** shall mean the individual, corporation, or other legal + entity that owns or controls the intellectual property rights in the + Licensed Technology and grants the Licensee a license to use the + Licensed Technology under the terms and conditions of this Agreement. + +- **“Licensee”** shall mean the individual, corporation, or other legal + entity that is granted a license to use the Licensed Technology under + the terms and conditions of this Agreement. + +- **“Parties”** shall mean the Licensor and the Licensee collectively, + and “Party” shall mean either the Licensor or the Licensee + individually, as the context requires. + +- **“Affiliate”** shall mean, with respect to a Party, any entity that + directly or indirectly controls, is controlled by, or is under common + control with such Party. For purposes of this definition, “control” + means the power to direct or cause the direction of the management + and policies of an entity, whether through the ownership of voting + securities, by contract, or otherwise. + +- **“Employee”** shall mean any individual who is employed by either + Party or any of its Affiliates on a full-time, part-time, or + temporary basis, and who is subject to the direction and control of + the employing Party or Affiliate with respect to the time, place, and + manner of their work. The term “Employee” shall not include + Contractors. + +- **“Contractor”** shall mean any individual or entity that is not an + Employee of either Party or any of its Affiliates, but is engaged by + a Party or its Affiliate to perform services on their behalf. + Contractors may include, but are not limited to, consultants, + advisors, or outsourced service providers. + +- **“Intellectual Property Rights”** means any form of protection + afforded anywhere in the world by law to inventions, works, designs, + software, trade secrets, confidential information, know-how and other + proprietary information and data, including without limitation + patents (including re-issues, divisions, continuations and extensions + thereof), copyrights, database rights, registered and not-registered + design rights, utility models, mask works, as well as applications + for any such rights. + +- **“Application”** shall mean a product, service, or solution + developed by the Licensee that incorporates the Licensed Technology + and adds primary and substantial functionality, features, or + improvements that are distinct from those provided by the Licensed + Technology itself. An Application must have a clear and distinctive + goal that goes beyond merely serving as a wrapper, modification, or + adaptation of the Licensed Technology. + +- **“Derivative Work”** shall mean any modification, adaptation, + translation, improvement, enhancement, or other work based on or + derived from the Licensed Technology that does not add primary and + substantial functionality, features, or improvements distinct from + those provided by the Licensed Technology itself. This includes, + without limitation, any product, service, or solution that + integrates, incorporates, bundles, wraps, interfaces with, or adapts + the Licensed Technology without significantly changing or enhancing + its original functionality, features, or purpose. + +- **“Documentation”** shall mean any user manuals, technical manuals, + specifications, or other written materials provided by the Licensor + that describe the features, functions, or operation of the Licensed + Technology. + +- **“Feedback”** shall mean any suggestions, comments, ideas, or other + information provided by the Licensee to the Licensor regarding the + Licensed Technology, including but not limited to bug reports, + feature requests, and performance evaluations. + +- **“Compatible Open-Source Licenses”** shall mean open-source software + licenses allowing for the free use, modification, and distribution of + the Licensed Technology, without imposing conflicting or additional + restrictions. The only valid licenses are: (a) MIT License (b) Apache + License 2.0 (c) BSD 3-Clause “New” or “Revised” License. + +- **“Non-Compatible Open-Source Licenses”** shall mean any license + terms that are inconsistent with or conflict with the terms of this + Agreement, including but not limited to the GNU General Public + License (GPL), Lesser GPL (LGPL), or the Creative Commons + Attribution-ShareAlike License. + +- **“Fees”** shall mean the amounts payable by the Licensee to the + Licensor in consideration for the rights and licenses granted under + this Agreement. + +- **“Term”** shall mean the duration of this Agreement, as specified in + Appendix A, commencing on the Effective Date and continuing until the + expiration or termination of this Agreement in accordance with its + terms. + +- **“Effective Date”** shall mean the date on which this Agreement + comes into force, as specified in Appendix A or as determined by the + mutual execution of this Agreement by both parties. + +- **“Force Majeure Event”** shall have the meaning set forth in Section + 13. + +- **“End User”** shall mean any individual, corporation, or other legal + entity that is not a party to this Agreement, but obtains and uses + the Application developed by the Licensee, either under the terms of + a Compatible License or through a commercial arrangement with the + Licensee. + +1. Object of the Agreement +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +1.1 The primary purpose of this Agreement is to delineate the terms +under which the Licensor grants the Licensee specific rights pertaining +to the use of the Licensed Technology. It is explicitly stated and +understood that this Agreement does not grant any rights, privileges, or +licenses to any third parties not explicitly mentioned herein. + +1.2 Under the terms outlined in this Agreement, contingent upon the +Licensee’s timely payment of Fees as specified in Appendix A, and strict +adherence to all other terms and conditions herein, the Licensor grants +the Licensee a worldwide, non-exclusive, non-sublicensable, and +non-transferable license to use or modify the Licensed Technology, for +the sole purposes of creating Application based on the Licensed +Technology for and marketing, promoting, licensing, maintaining and +supporting such Applications to/for End-User,, subject to the +limitations and restrictions set forth in this Agreement. + +1.3 All rights bestowed upon the Licensee under this Agreement are +conferred solely through licensing and not by sale. These rights are +also circumscribed and governed by the terms of this Agreement. This +Agreement does not grant any license or other rights in any intellectual +property other than the Licensed Technology. No license or rights will +arise under this Agreement by implication, estoppel, or any other means. +Any attempt at sublicensing that contradicts the terms of this Agreement +will be deemed invalid and without effect. + +1.4 The effective period of this Agreement commences both Parties +signing this Agreement and the subsequent payment of the Fee by the +Licensee. This initiation is contingent upon these dual conditions being +met, marking the start of the Term as indicated in Appendix A and +continuing for the Term as indicated in Appendix A. Following the +conclusion of this Term, the Agreement may be subject to renewal, based +on mutual consent of both Parties and contingent upon the Licensee’s +payment of any applicable renewal fees, as well as their continued +compliance with the terms set forth herein. + +1.5 The Licensee acknowledges and agrees that any use of the Licensed +Technology or any Derivative Work by the Licensee outside the scope of +this Agreement shall constitute a material breach of this Agreement and +may result in the immediate termination of the license granted herein. +The Licensee shall promptly notify the Licensor of any unauthorized use +or disclosure of the Licensed Technology and take reasonable steps to +prevent further breach of this Agreement. + +2. Intellectual Property +^^^^^^^^^^^^^^^^^^^^^^^^ + +2.1 The Licensor retains all right, title, and interest, including all +Intellectual Property Rights, in and to the Licensed Technology. This +Agreement does not grant the Licensee any ownership rights in the +Licensed Technology, but only the limited license rights expressly set +forth herein. The Licensed Technology is protected by copyright laws, +international copyright treaties, and other Intellectual Property Laws +and treaties. Any unauthorized copying, modification, distribution, or +use of the Licensed Technology is strictly prohibited and may subject +the Licensee to legal action. + +2.2 The Licensee shall own the Intellectual Property Rights in any +Application developed by the Licensee, excluding the Licensed Technology +and any Derivative Works. The Licensee is hereby granted the privilege +to alter, adapt, and modify the Licensed Technology as necessary to meet +specific requirements or objectives. Any Derivative Work based on or +derived from the Licensed Technology shall be owned by the Licensor and +considered part of the Licensed Technology, subject to the terms and +conditions of this Agreement. The Licensee shall have no ownership +rights in Derivative Works. + +2.3 End Users may use, modify, and distribute the Application in +accordance with the terms of the applicable Compatible License or +commercial agreement, with the licensee, but shall have no rights to the +Licensed Technology except as expressly granted in this Agreement. + +3. Fees and Taxes +^^^^^^^^^^^^^^^^^ + +3.1 The Licensee shall pay the Licensor the fees specified in Appendix A +(the “Fees”) in accordance with the payment terms set forth therein. If +the Licensee fails to pay the Fees within the agreed payment term, the +Licensee shall owe Late Payment Charges as specified in Appendix A. + +3.2 All Fees are non-refundable, and the Licensor shall have no +obligation to refund any Fees paid by the Licensee, except as expressly +provided in this Agreement. The Licensee shall not be entitled for any +reason to any set-off, counter-claim, abatement, or other similar +deduction to withhold payment of any amount due to the Licensor. + +3.3 All Fees are exclusive of any applicable taxes, levies, or duties, +including but not limited to value-added tax, sales tax, or withholding +tax. The Licensee shall be responsible for paying all such taxes, +levies, or duties associated with the Fees, except for those based on +the Licensor’s income. + +3.4 If the Licensor is required to pay or collect any such taxes, +levies, or duties on behalf of the Licensee, the amount payable by the +Licensee shall be increased to the extent necessary to ensure that the +Licensor receives a sum equal to the Fees it would have received had no +such deduction or withholding been required. The Licensor shall provide +the Licensee with appropriate tax invoices or receipts evidencing the +payment of any such taxes, levies, or duties. The Licensee shall furnish +the Licensor with any relevant tax exemption certificates or other +documentation required to minimize or eliminate any applicable taxes, +levies, or duties. + +4. General Provisions +^^^^^^^^^^^^^^^^^^^^^ + +4.1 **Entire Agreement.** This Agreement, together with Appendix A, +collectively forms the complete and exclusive terms of the arrangement +between the Parties. It supersedes all prior or contemporaneous +discussions, representations, contracts, including but not limited to +previous License Agreements and similar agreements, as well as +proposals, whether written or oral, concerning the subject matters +herein. + +4.2 **Severability.** In the event any portion of this Agreement is +deemed invalid or unenforceable, such portion shall not limit or +otherwise modify or affect any other portion of this Agreement Without +limiting the generality of the foregoing, if the scope of any provision +contained in this Agreement is too broad to permit enforcement to its +fullest extent, such covenant shall be enforced to the maximum extent +permitted by law, and the Parties hereby agree that such scope may be +judicially modified accordingly. + +4.3 **Modification Waiver.** This Agreement is furnished ‘as-is’ and no +amendments to its terms are permissible. The failure of either Party to +enforce any provision of this Agreement may not be deemed a waiver of +that or any other provision of this Agreement. + +4.4 **Marketing.** Licensee agrees that the Licensor may use the +Licensee’s name, trade name, and trademark in the Licensor’s marketing +materials and on its website, solely for the purpose of identifying the +Licensee as a customer of the Licensor. Such use shall be in accordance +with the Licensee’s brand guidelines and shall not imply any endorsement +or affiliation beyond the scope of this Agreement. The Licensor shall +promptly cease any such use upon written request from the Licensee. + +4.5 **Compliance with Applicable Laws.** In the course of employing the +Licensed Technology pursuant to this Agreement, the Licensee shall +ensure compliance with all relevant laws and regulations. The Licensee +is prohibited from engaging in the renting, leasing, or similar disposal +of the Licensed Technology in any manner that contradicts this +Agreement. Additionally, the Licensee must refrain from any +misappropriation or unauthorized utilization of other products or +services offered by the Licensor. + +4.6 **Trademarks.** The Licensee shall not remove or alter any +copyright, trademark, or other proprietary rights notice(s) contained in +any portion of the Licensed Technology. Applications must add primary +and substantial functionality to the Licensed Technology so as not to +compete with the Licensed Technology. + +4.7 **Prohibited Activities.** The Licensee shall not use the Licensed +Technology for any unlawful purpose, including without limitation the +infringement of any third party’s Intellectual Property Right or other +proprietary rights. The Licensee agrees that it shall not claim any +right to or license (except for the license granted pursuant to Section +1.2 above) with respect to the Licensed Technology nor shall the +Licensee contest or assist in contesting the Licensor’s right, title and +interest in and to such the Licensed Technology. Further, the Licensee +shall not partake in activities that contribute to or support claims, +whether made by the Licensee or any third party, alleging that the +Licensed Technology infringes on any patents. The sale of the Licensed +Technology or the establishment of a security interest over it is +strictly prohibited. Moreover, the distribution of any product, +inclusive of the Licensed Technology, shall be conducted strictly in +accordance with the permissions explicitly granted by this Agreement. + +4.8 **Assignment.** The Licensee is barred from assigning or +transferring any rights, benefits, or obligations under this Agreement, +unless such transfer is part of the sale of its relevant business or +assets, or is done with the Licensor’s prior written consent, which is +not to be unreasonably withheld or delayed. In contrast, the Licensor +retains the unencumbered right to assign or transfer any of its rights, +benefits, or obligations under this Agreement. + +4.9 **Injunctive Relief.** The Licensee hereby acknowledges that +unauthorized disclosure and/or use of any of the Licensed Technology +could cause irreparable harm and significant injury to the Licensor that +may be difficult to ascertain. Accordingly, the Licensee agrees that, in +addition to any other rights and remedies it may have, the Licensor will +have the right to seek immediate injunctive relief to enforce the +obligations under this Agreement without the necessity of posting a bond +or any other security. + +4.10 **No Representation.** The Licensee shall not represent itself as +an agent of the Licensor for any purpose, nor give any condition or +warranty or make any representation on the Licensor’s behalf or commit +the Licensor to any contracts. Further, the Licensee shall not make any +representations, warranties, guarantees or other commitments with +respect to the specifications, features or capabilities of the Licensed +Technology or otherwise incur any liability on behalf of the Licensor in +any circumstances. + +4.11 **Audits.** The Licensor has the right to audit the Licensee +compliance with its obligations under this Agreement. The Licensee shall +provide to the Licensor and its personnel, auditors and inspectors such +assistance, access and co-operation as they may need and reasonably +require. + +4.12 **Cumulative Remedies.** Any remedies specified in this Agreement +are cumulative and are not intended to be exclusive of any other +remedies to which the Licensor may be entitled at law or equity in case +of any breach or threatened breach by the Licensee of any provision of +this Agreement, unless such remedies are specifically limited or +excluded by the terms of any provision of this Agreement. + +4.13 **Survival.** Certain provisions of this Agreement are designed to +outlast its termination. These provisions, due to their inherent nature +or as specifically indicated, will continue to be valid and enforceable +even after the termination of this Agreement. + +5. Feedback and Updates +^^^^^^^^^^^^^^^^^^^^^^^ + +5.1 The Licensee hereby grants to the Licensor the unrestricted right to +freely utilize and disclose any Feedback that the Licensee provides +concerning the Licensed Technology. The Licensee acknowledges and agrees +that all Feedback may be employed by the Licensor for any purpose, +whether commercial, developmental, or otherwise, without any obligation +for acknowledgment, compensation, or other consideration to the +Licensee. This includes, but is not limited to, the right to develop, +copy, publish, modify, enhance, or otherwise make improvements to the +Licensed Technology, at the sole discretion of the Licensor. The +Licensee recognizes that all Feedback shall be considered +non-confidential and the Licensor is free to use such Feedback without +any restriction or obligation of confidentiality. + +5.2 During the Term, the Licensor may develop and release updates, +upgrades, or new versions of the Licensed Technology. The Licensee shall +have the right to receive and use such updates, upgrades, or new +versions, subject to the terms and conditions of this Agreement. + +5.3 The Licensee’s right to receive and use updates, upgrades, or new +versions shall continue until the termination of this Agreement, as +outlined in Section 8. Upon termination, the Licensee shall have no +further right to receive any updates, upgrades, or new versions of the +Licensed Technology. + +5.4 All updates, upgrades, or new versions of the Licensed Technology +provided to the Licensee shall be considered part of the Licensed +Technology and subject to the terms and conditions of this Agreement, +unless otherwise specified by the Licensor in writing. + +5.5 Notwithstanding the Licensee’s right to receive updates, upgrades, +or new versions, the Licensor is under no obligation to develop or +release any such updates, upgrades, or new versions. The development and +release of updates, upgrades, or new versions shall be at the sole +discretion of the Licensor. + +6. End User Rights and Obligations +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +6.1 End Users who obtain the Application, either under a Compatible +Open-Source License or through a commercial arrangement with the +Licensee, may use, modify, and distribute the Application, subject to +the terms and conditions of the applicable Compatible Open-Source +License or commercial agreement. However, End Users shall have no right +to use, modify, or distribute the Licensed Technology, or any part +thereof, except as incorporated in the Application and subject to the +terms and conditions of this Agreement. + +6.2 The Licensee shall include a prominent notice in the Application’s +documentation, user interface, and source code, stating the following: + +:: + + IMPORTANT NOTICE: This Application is built upon the [Licensed Technology Name], which is owned by [Licensor Name] and used under license. As an End User of this Application, you are prohibited from using, modifying, or distributing the [Licensed Technology Name], or any part thereof, except as incorporated in this Application. Specifically, you may not: + + a) Extract, isolate, or separate the [Licensed Technology Name] from this Application; + b) Use the [Licensed Technology Name] for any purpose other than as part of this Application; + c) Modify, adapt or translate the [Licensed Technology Name]; + d) Create any Derivative Works based on the [Licensed Technology Name]; + e) Distribute, sublicense, rent, lease, lend, or transfer the [Licensed Technology Name] to any third party; + f) Reverse engineer, decompile, disassemble, or attempt to derive the source code of the [Licensed Technology Name]; + g) Remove, obscure, or alter any copyright, trademark, or other proprietary rights notices contained within the [Licensed Technology Name]. + + Your use of this Application is subject to your compliance with these restrictions. If you have any questions about these terms, please contact [Licensee Name]. + +The Licensee shall include a copy of this notice in all copies or +substantial portions of the Application. + +6.3 End Users must comply with all applicable laws, regulations, and +third-party rights when using, modifying, or distributing the +Application. + +6.4 The Licensee shall indemnify, defend, and hold harmless the Licensor +from and against any claims, damages, liabilities, costs, and expenses +arising out of or in connection with any use of the Application by End +Users, including any use that breaches the terms and conditions of this +Agreement. + +7. Use of Non-Compatible Open-Source Licenses +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +In adherence to the terms of this Agreement, the Licensee is expressly +prohibited from, and shall not permit any third party or End User to, +integrate, distribute, or otherwise utilize the Licensed Technology in +conjunction with any code, software, or content that is subject to a +license incompatible with the terms of this Agreement, hereafter +referred to as “Non-Compatible Open-Source Licenses”. Such prohibitive +action includes, but is not limited to, any combination or use that +would necessitate, either directly or indirectly, that the Licensed +Technology be subject or conform to any licensing terms other than those +explicitly set forth in this Agreement. + +8. Termination +^^^^^^^^^^^^^^ + +8.1 This Agreement may be terminated without cause by either Party upon +written notice to the other Party, provided such notice period is no +less than three (3) months. + +8.2 Either Party may terminate this Agreement with immediate effect, if +the other Party commits a material breach of the terms of this Agreement +and has not remedied such breach upon the non-breaching Party’s written +notice within a reasonable timeframe, which shall be no less than thirty +(30) days). + +8.3 The Licensor may also immediately terminate this Agreement upon +written notice to the Licensee if the Licensee becomes bankrupt, +insolvent, enters into liquidation, or undergoes debt restructuring. + +9. Rights and Duties upon Termination +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +9.1 Upon termination of this Agreement, the Licensee’s rights to use or +modify the Licensed Technology, and to create Derivative Works based on +the Licensed Technology, shall immediately cease, except as provided in +Section 9.2. + +9.2 In the event that this Agreement is terminated by either Party +without cause pursuant to Section 8.1, or by the Licensor due to the +Licensee’s bankruptcy, insolvency, liquidation, or debt restructuring +pursuant to Section 8.3, or upon the conclusion of the Term as specified +in Section 1.4, the Licensee shall retain the right to continue using +the Licensed Technology, limited to the version in use immediately prior +to the termination date, solely for the purpose of maintaining and +supporting existing Applications. The Licensee shall have no right to +receive any updates, modifications, or improvements to the Licensed +Technology made by the Licensor after the termination date. + +9.3 In the event that this Agreement is terminated by either Party due +to a material breach by the other Party pursuant to Section 8.2, the +Licensee’s right to continue using the Licensed Technology as described +in Section 9.2 shall not apply, and all rights granted to the Licensee +under this Agreement shall immediately terminate. + +9.4 Expiry or termination of this Agreement shall not relieve the +Licensee of its obligation to pay any Fees accrued or payable to the +Licensor prior to the effective date of termination, and the Licensee +shall pay to the Licensor all such Fees within 30 days from the +effective date of termination. + +9.5 The Licensee acknowledges and agrees that, following the termination +of this Agreement, it shall remain bound by its obligations under this +Agreement with respect to any use of the Licensed Technology, including +in Applications already distributed, and shall ensure that such use +remains in compliance with the terms of this Agreement. + +10. Notices +^^^^^^^^^^^ + +Any notice given by one Party to the other shall be deemed properly +given and deemed received if specifically acknowledged by the receiving +Party in writing. Additionally, any notice issued by the Licensor to the +Licensee using the email address provided by the Licensee to the +Licensor will be effective from the moment it was sent. Each +communication and document made or delivered by one Party to the other +Party pursuant to this Agreement shall be in the language specified in +Appendix A. + +11. Warranty Disclaimers +^^^^^^^^^^^^^^^^^^^^^^^^ + +THE LICENSED TECHNOLOGY, INCLUDING ALL SOFTWARE, DOCUMENTATION, +INFORMATION, CONTENT, MATERIALS, CODE, AND RELATED SERVICES, ARE +PROVIDED BY THE LICENSOR ON AN “AS IS” AND “AS AVAILABLE” BASIS. THE +LICENSOR AND ITS AFFILIATES HEREBY DISCLAIM ALL WARRANTIES, WHETHER +EXPRESS, IMPLIED, STATUTORY, OR OTHERWISE. SPECIFICALLY, THE LICENSOR +AND ITS AFFILIATES MAKE NO REPRESENTATIONS OR WARRANTIES OF ANY KIND, +EXPRESS OR IMPLIED, REGARDING THE LICENSED TECHNOLOGY, INCLUDING BUT NOT +LIMITED TO IMPLIED OR STATUTORY WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE, TITLE, NON-INFRINGEMENT OF INTELLECTUAL +PROPERTY OR OTHER PROPRIETARY RIGHTS, AND ALL WARRANTIES ARISING FROM +COURSE OF DEALING, USAGE, OR TRADE PRACTICE. THE LICENSOR AND ITS +AFFILIATES DO NOT WARRANT THAT THE LICENSED TECHNOLOGY, OR ANY PRODUCTS +OR RESULTS OF THE USE THEREOF, WILL MEET LICENSEE’S OR ANY OTHER +PERSON’S REQUIREMENTS, OPERATE WITHOUT INTERRUPTION, ACHIEVE ANY +INTENDED RESULT, BE COMPATIBLE OR WORK WITH ANY SOFTWARE, SYSTEM, OR +OTHER SERVICES, OR BE SECURE, ACCURATE, COMPLETE, FREE OF HARMFUL CODE, +OR ERROR-FREE AT THE TIME OF THIS AGREEMENT OR AT ANY TIME IN THE +FUTURE. FURTHER, THE LICENSOR AND ITS AFFILIATES DO NOT WARRANT THAT THE +LICENSED TECHNOLOGY IS FREE OF VIRUSES OR OTHER HARMFUL COMPONENTS. THE +PARTIES ACKNOWLEDGE AND AGREE THAT THE FOREGOING WARRANTY DISCLAIMERS +ARE AN ESSENTIAL ELEMENT IN SETTING CONSIDERATION UNDER THIS AGREEMENT. + +12. Limitation of Liability +^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +TO THE FULL EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSOR WILL NOT BE +LIABLE FOR ANY LOST PROFITS, LOSS OF SAVINGS, LOSS OR CORRUPTION OF +DATA, LOSS OR INTERRUPTION OF BUSINESS, LOSS OF GOODWILL OR REPUTATION, +CLAIMS MADE BY ANY END-USER OR ANY OTHER THIRD PARTY, OR ANY OTHER +INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL, OR PUNITIVE COSTS, +DAMAGES, OR EXPENSES OF ANY KIND ARISING UNDER OR IN CONNECTION WITH +THIS AGREEMENT. FURTHER, THE LICENSOR’S AGGREGATE LIABILITY UNDER THIS +AGREEMENT SHALL NOT EXCEED THE TOTAL AMOUNTS PAID (IF ANY) TO THE +LICENSOR UNDER THIS AGREEMENT DURING THE TWELVE (12) MONTHS IMMEDIATELY +PRECEDING THE EVENTS GIVING RISE TO THE LIABILITY. SEEKING DAMAGES AS +LIMITED BY THIS SECTION SHALL BE THE SOLE AND EXCLUSIVE REMEDY TO THE +LICENSEE FOR ANY ACT OR OMISSION OF THE LICENSOR. THESE LIMITATIONS OF +LIABILITY AND EXCLUSIONS OF POTENTIAL DAMAGES WERE AN ESSENTIAL ELEMENT +IN SETTING CONSIDERATION UNDER THIS AGREEMENT. + +13. Force Majeure +^^^^^^^^^^^^^^^^^ + +Neither Party shall be liable to the other for any delay or +non-performance of its obligations hereunder in the event and to the +extent that such delay or non-performance is due to an event beyond a +Party’s reasonable control and without the fault or negligence of such +Party. Such causes may include, but are not limited to, any God, +terrorist attack, destruction of all available copies of the Licensed +Technology, governmental actions such as changes in law or embargoes, +cyberattacks including but not limited to significant DDoS attacks or +other cybersecurity breaches that disrupt services, critical +infrastructure failure involving essential utilities including but not +limited to electricity or internet services, but in every case the +failure to perform must be beyond the control and without the fault or +negligence of the affected Party and cannot be avoided or circumvented +by such party (“Force Majeure Event”). In the occurrence of any such +event, the affected Party shall notify the other Party as soon as +reasonably possible and shall use all reasonable endeavors to mitigate +the effects of the Force Majeure Event. If the Force Majeure Event +results in a delay or non-performance of a Party for a period of three +(3) months or longer, then either Party shall have the right to +terminate this Agreement with immediate effect without any liability +(except for the obligations of payment arising prior to the Force +Majeure Event) towards the other Party. + +14. Indemnification +^^^^^^^^^^^^^^^^^^^ + +Under this Agreement, the Licensee agrees to indemnify, defend, and hold +harmless the Licensor, its officers, directors, employees, agents, +affiliates, successors, and assigns from any liabilities, damages, +judgments, awards, losses, costs, expenses, including reasonable +attorney and expert witness fees, arising out of or in connection with +any third-party claims, suits, actions, or proceedings. This indemnity +covers claims resulting from the Licensee’s breach of this Agreement, +negligence, willful misconduct, use of the Licensed Technology, or +related to the Licensee’s products. Excluded from this indemnification +are claims alleging that the Licensee’s authorized use of unmodified +Licensed Technology provided by the Licensor infringes any patent, +trademark, or copyright. The Licensor reserves the right, at its option +and sole discretion, to assume full control of the defense of such +claims with legal counsel of its choice. The Licensee is not permitted +to enter into any third-party agreement that would affect the Licensor’s +rights, constitute an admission of fault by the Licensor, or bind the +Licensor in any manner, without the Licensor’s prior written consent. +The Licensee must promptly notify the Licensor in writing of any claims +brought against the Licensor for which indemnification or defense is +sought, thereby enabling the Licensor to manage legal strategies and +potential settlements effectively. For the avoidance of doubt, the +Licensor does not have any obligation to defend the Licensee or any +End-User against such claim and therefore such defense shall be up to +the Licensor’s sole discretion. If the Licensor decides to not defend a +claim for infringement of Intellectual Property Rights, the Licensee may +defend itself through counsel of its own choice and at its own expense. +The Licensor shall have no liability for any costs, expenses, losses or +damages incurred by the Licensee or any of its End-Users in the event of +such claim. + +15. Governing Law and Jurisdiction +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The Licensor and the Licensee hereby mutually concur that the governance +and interpretation of this Agreement shall be in strict accordance with +the legal statutes and principles as stipulated in Appendix A. + +16. Dispute Resolution +^^^^^^^^^^^^^^^^^^^^^^ + +16.1 It is explicitly agreed that any dispute, controversy, or claim +that may arise out of, or in connection with, this contract, inclusive +of, but not limited to, its formation, interpretation, breach, or +termination, and the arbitrability of the claims posited therein, shall +be definitively resolved through arbitration. This arbitration shall be +conducted in full alignment with the JAMS International Arbitration +Rules. + +16.2 Furthermore, the arbitral tribunal shall be comprised of a sole +arbitrator. The venue for such arbitration proceedings shall be as +delineated in Appendix A of this Agreement. Moreover, the proceedings of +the arbitration shall be conducted in the language specified within +Appendix A. It is hereby declared that the award rendered by the said +arbitrator shall be binding and enforceable, and judgment thereon may be +entered in any court of competent jurisdiction. + +17. Confidentiality +^^^^^^^^^^^^^^^^^^^ + +17.1 During the term of this Agreement and thereafter until Confidential +Information becomes subject to one or more of the exceptions set forth +in Section 17.3, each Party shall maintain strict confidentiality +regarding the other Party’s Confidential Information. “Confidential +Information” shall include, but is not limited to, the Licensed +Technology, trade secrets, business plans, strategies, customer +information, and any other proprietary or sensitive information +disclosed by one Party to the other. + +17.2 Each Party agrees to use the Confidential Information solely for +the purposes of exercising its rights and fulfilling its obligations +under this Agreement. The receiving Party shall not disclose or permit +access to Confidential Information to any third party, except to its +Employees, Contractors, or agents who need to know such information for +the purposes of this Agreement and who are bound by confidentiality +obligations no less protective than those set forth herein. + +17.3 The confidentiality obligations shall not apply to information +that: (a) is or becomes publicly available through no fault of the +receiving Party; (b) was known to the receiving Party prior to +disclosure; (c) is independently developed by the receiving Party +without use of or reference to the Confidential Information; or (d) is +required to be disclosed by law or court order, provided that the +receiving Party gives prompt notice to the disclosing Party to enable it +to seek a protective order. + +-------------- + +GNU General Public License version 3 +------------------------------------ + +Preamble +^^^^^^^^ + +The GNU General Public License is a free, copyleft license for software +and other kinds of works. + +The licenses for most software and other practical works are designed to +take away your freedom to share and change the works. By contrast, the +GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program–to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + +When we speak of free software, we are referring to freedom, not price. +Our General Public Licenses are designed to make sure that you have the +freedom to distribute copies of free software (and charge for them if +you wish), that you receive source code or can get it if you want it, +that you can change the software or use pieces of it in new free +programs, and that you know you can do these things. + +To protect your rights, we need to prevent others from denying you these +rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + +For example, if you distribute copies of such a program, whether gratis +or for a fee, you must pass on to the recipients the same freedoms that +you received. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + +Developers that use the GNU GPL protect your rights with two steps: (1) +assert copyright on the software, and (2) offer you this License giving +you legal permission to copy, distribute and/or modify it. + +For the developers’ and authors’ protection, the GPL clearly explains +that there is no warranty for this free software. For both users’ and +authors’ sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + +Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of protecting +users’ freedom to change the software. The systematic pattern of such +abuse occurs in the area of products for individuals to use, which is +precisely where it is most unacceptable. Therefore, we have designed +this version of the GPL to prohibit the practice for those products. If +such problems arise substantially in other domains, we stand ready to +extend this provision to those domains in future versions of the GPL, as +needed to protect the freedom of users. + +Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + +The precise terms and conditions for copying, distribution and +modification follow. + +**TERMS AND CONDITIONS** + +0. Definitions. +^^^^^^^^^^^^^^^ + +“This License” refers to version 3 of the GNU General Public License. + +“Copyright” also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + +“The Program” refers to any copyrightable work licensed under this +License. Each licensee is addressed as “you”. “Licensees” and +“recipients” may be individuals or organizations. + +To “modify” a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a “modified version” of the +earlier work or a work “based on” the earlier work. + +A “covered work” means either the unmodified Program or a work based on +the Program. + +To “propagate” a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + +To “convey” a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays “Appropriate Legal Notices” to +the extent that it includes a convenient and prominently visible feature +that (1) displays an appropriate copyright notice, and (2) tells the +user that there is no warranty for the work (except to the extent that +warranties are provided), that licensees may convey the work under this +License, and how to view a copy of this License. If the interface +presents a list of user commands or options, such as a menu, a prominent +item in the list meets this criterion. + +1. Source Code. +^^^^^^^^^^^^^^^ + +The “source code” for a work means the preferred form of the work for +making modifications to it. “Object code” means any non-source form of a +work. + +A “Standard Interface” means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that is +widely used among developers working in that language. + +The “System Libraries” of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that Major +Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A “Major +Component”, in this context, means a major essential component (kernel, +window system, and so on) of the specific operating system (if any) on +which the executable work runs, or a compiler used to produce the work, +or an object code interpreter used to run it. + +The “Corresponding Source” for a work in object code form means all the +source code needed to generate, install, and (for an executable work) +run the object code and to modify the work, including scripts to control +those activities. However, it does not include the work’s System +Libraries, or general-purpose tools or generally available free programs +which are used unmodified in performing those activities but which are +not part of the work. For example, Corresponding Source includes +interface definition files associated with source files for the work, +and the source code for shared libraries and dynamically linked +subprograms that the work is specifically designed to require, such as +by intimate data communication or control flow between those subprograms +and other parts of the work. + +The Corresponding Source need not include anything that users can +regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same +work. + +2. Basic Permissions. +^^^^^^^^^^^^^^^^^^^^^ + +All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, +without conditions so long as your license otherwise remains in force. +You may convey covered works to others for the sole purpose of having +them make modifications exclusively for you, or provide you with +facilities for running those works, provided that you comply with the +terms of this License in conveying all material for which you do not +control copyright. Those thus making or running the covered works for +you must do so exclusively on your behalf, under your direction and +control, on terms that prohibit them from making any copies of your +copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the +conditions stated below. Sublicensing is not allowed; section 10 makes +it unnecessary. + +3. Protecting Users’ Legal Rights From Anti-Circumvention Law. +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article 11 +of the WIPO copyright treaty adopted on 20 December 1996, or similar +laws prohibiting or restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to the +covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work’s +users, your or third parties’ legal rights to forbid circumvention of +technological measures. + +4. Conveying Verbatim Copies. +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +You may convey verbatim copies of the Program’s source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; keep +intact all notices stating that this License and any non-permissive +terms added in accord with section 7 apply to the code; keep intact all +notices of the absence of any warranty; and give all recipients a copy +of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and +you may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the terms +of section 4, provided that you also meet all of these conditions: + +- + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + +- + + b) The work must carry prominent notices stating that it is released + under this License and any conditions added under section 7. This + requirement modifies the requirement in section 4 to “keep intact + all notices”. + +- + + c) You must license the entire work, as a whole, under this License + to anyone who comes into possession of a copy. This License will + therefore apply, along with any applicable section 7 additional + terms, to the whole of the work, and all its parts, regardless of + how they are packaged. This License gives no permission to license + the work in any other way, but it does not invalidate such + permission if you have separately received it. + +- + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + +A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, and +which are not combined with it such as to form a larger program, in or +on a volume of a storage or distribution medium, is called an +“aggregate” if the compilation and its resulting copyright are not used +to limit the access or legal rights of the compilation’s users beyond +what the individual works permit. Inclusion of a covered work in an +aggregate does not cause this License to apply to the other parts of the +aggregate. + +6. Conveying Non-Source Forms. +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +You may convey a covered work in object code form under the terms of +sections 4 and 5, provided that you also convey the machine-readable +Corresponding Source under the terms of this License, in one of these +ways: + +- + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + +- + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the Corresponding + Source from a network server at no charge. + +- + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + +- + + d) Convey the object code by offering access from a designated place + (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + +- + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be included +in conveying the object code work. + +A “User Product” is either (1) a “consumer product”, which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for +incorporation into a dwelling. In determining whether a product is a +consumer product, doubtful cases shall be resolved in favor of coverage. +For a particular product received by a particular user, “normally used” +refers to a typical or common use of that class of product, regardless +of the status of the particular user or of the way in which the +particular user actually uses, or expects or is expected to use, the +product. A product is a consumer product regardless of whether the +product has substantial commercial, industrial or non-consumer uses, +unless such uses represent the only significant mode of use of the +product. + +“Installation Information” for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product +from a modified version of its Corresponding Source. The information +must suffice to ensure that the continued functioning of the modified +object code is in no case prevented or interfered with solely because +modification has been made. + +If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied by +the Installation Information. But this requirement does not apply if +neither you nor any third party retains the ability to install modified +object code on the User Product (for example, the work has been +installed in ROM). + +The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in +accord with this section must be in a format that is publicly documented +(and with an implementation available to the public in source code +form), and must require no special password or key for unpacking, +reading or copying. + +7. Additional Terms. +^^^^^^^^^^^^^^^^^^^^ + +“Additional permissions” are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by this +License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove +any additional permissions from that copy, or from any part of it. +(Additional permissions may be written to require their own removal in +certain cases when you modify the work.) You may place additional +permissions on material, added by you to a covered work, for which you +have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders +of that material) supplement the terms of this License with terms: + +- + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + +- + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + +- + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + +- + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + +- + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + +- + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions + of it) with contractual assumptions of liability to the recipient, + for any liability that these contractual assumptions directly + impose on those licensors and authors. + +All other non-permissive additional terms are considered “further +restrictions” within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains a +further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms of +that license document, provided that the further restriction does not +survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must +place, in the relevant source files, a statement of the additional terms +that apply to those files, or a notice indicating where to find the +applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; the above +requirements apply either way. + +8. Termination. +^^^^^^^^^^^^^^^ + +You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + +However, if you cease all violation of this License, then your license +from a particular copyright holder is reinstated (a) provisionally, +unless and until the copyright holder explicitly and finally terminates +your license, and (b) permanently, if the copyright holder fails to +notify you of the violation by some reasonable means prior to 60 days +after the cessation. + +Moreover, your license from a particular copyright holder is reinstated +permanently if the copyright holder notifies you of the violation by +some reasonable means, this is the first time you have received notice +of violation of this License (for any work) from that copyright holder, +and you cure the violation prior to 30 days after your receipt of the +notice. + +Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + +9. Acceptance Not Required for Having Copies. +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +You are not required to accept this License in order to receive or run a +copy of the Program. Ancillary propagation of a covered work occurring +solely as a consequence of using peer-to-peer transmission to receive a +copy likewise does not require acceptance. However, nothing other than +this License grants you permission to propagate or modify any covered +work. These actions infringe copyright if you do not accept this +License. Therefore, by modifying or propagating a covered work, you +indicate your acceptance of this License to do so. + +10. Automatic Licensing of Downstream Recipients. +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + +An “entity transaction” is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered work +results from an entity transaction, each party to that transaction who +receives a copy of the work also receives whatever licenses to the work +the party’s predecessor in interest had or could give under the previous +paragraph, plus a right to possession of the Corresponding Source of the +work from the predecessor in interest, if the predecessor has it or can +get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may not +impose a license fee, royalty, or other charge for exercise of rights +granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that any +patent claim is infringed by making, using, selling, offering for sale, +or importing the Program or any portion of it. + +11. Patents. +^^^^^^^^^^^^ + +A “contributor” is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The work +thus licensed is called the contributor’s “contributor version”. + +A contributor’s “essential patent claims” are all patent claims owned or +controlled by the contributor, whether already acquired or hereafter +acquired, that would be infringed by some manner, permitted by this +License, of making, using, or selling its contributor version, but do +not include claims that would be infringed only as a consequence of +further modification of the contributor version. For purposes of this +definition, “control” includes the right to grant patent sublicenses in +a manner consistent with the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor’s essential patent claims, to make, +use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + +In the following three paragraphs, a “patent license” is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To “grant” such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and +the Corresponding Source of the work is not available for anyone to +copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. “Knowingly relying” means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient’s use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify or +convey a specific copy of the covered work, then the patent license you +grant is automatically extended to all recipients of the covered work +and works based on it. + +A patent license is “discriminatory” if it does not include within the +scope of its coverage, prohibits the exercise of, or is conditioned on +the non-exercise of one or more of the rights that are specifically +granted under this License. You may not convey a covered work if you are +a party to an arrangement with a third party that is in the business of +distributing software, under which you make payment to the third party +based on the extent of your activity of conveying the work, and under +which the third party grants, to any of the parties who would receive +the covered work from you, a discriminatory patent license (a) in +connection with copies of the covered work conveyed by you (or copies +made from those copies), or (b) primarily for and in connection with +specific products or compilations that contain the covered work, unless +you entered into that arrangement, or that patent license was granted, +prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any +implied license or other defenses to infringement that may otherwise be +available to you under applicable patent law. + +12. No Surrender of Others’ Freedom. +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not convey it at all. For example, if you agree to terms that +obligate you to collect a royalty for further conveying from those to +whom you convey the Program, the only way you could satisfy both those +terms and this License would be to refrain entirely from conveying the +Program. + +13. Use with the GNU Affero General Public License. +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Notwithstanding any other provision of this License, you have permission +to link or combine any covered work with a work licensed under version 3 +of the GNU Affero General Public License into a single combined work, +and to convey the resulting work. The terms of this License will +continue to apply to the part which is the covered work, but the special +requirements of the GNU Affero General Public License, section 13, +concerning interaction through a network will apply to the combination +as such. + +14. Revised Versions of this License. +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies that a certain numbered version of the GNU General Public +License “or any later version” applies to it, you have the option of +following the terms and conditions either of that numbered version or of +any later version published by the Free Software Foundation. If the +Program does not specify a version number of the GNU General Public +License, you may choose any version ever published by the Free Software +Foundation. + +If the Program specifies that a proxy can decide which future versions +of the GNU General Public License can be used, that proxy’s public +statement of acceptance of a version permanently authorizes you to +choose that version for the Program. + +Later license versions may give you additional or different permissions. +However, no additional obligations are imposed on any author or +copyright holder as a result of your choosing to follow a later version. + +15. Disclaimer of Warranty. +^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT +WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF +THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR +CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES +ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT +NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES +SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE +WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN +ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +If the disclaimer of warranty and limitation of liability provided above +cannot be given local legal effect according to their terms, reviewing +courts shall apply local law that most closely approximates an absolute +waiver of all civil liability in connection with the Program, unless a +warranty or assumption of liability accompanies a copy of the Program in +return for a fee. + +.. Links + +.. _website: https://simpleble.org \ No newline at end of file diff --git a/third_party/SimpleBLE/docs/overview.rst b/third_party/SimpleBLE/docs/overview.rst index e779c1ba4..684a1fe97 100644 --- a/third_party/SimpleBLE/docs/overview.rst +++ b/third_party/SimpleBLE/docs/overview.rst @@ -2,11 +2,12 @@ Overview -------- The SimpleBLE project aims to provide fully cross-platform BLE libraries and bindings -for Python and C++, designed for simplicity and ease of use with a licencing scheme -chosen to be friendly towards commercial use. All specific operating system quirks -are handled internally to provide a consistent behavior across all platforms. The -libraries also provide first-class support for vendorization of all third-party -dependencies, allowing for easy integration into existing projects. +for C++, Python, Rust and other languages, designed for simplicity and ease of use. +All specific operating system quirks are handled internally to provide a consistent behavior +and API across all platforms. The libraries also provide first-class support for vendorization +of all third-party dependencies, allowing for easy integration into existing projects. + +**NOTICE: Since February 20, 2024 the license terms of SimpleBLE have changed. Please make sure to read and understand the new licensing scheme.** This repository offers the source code for the following related libraries: @@ -19,50 +20,61 @@ If you want to use SimpleBLE and need help. **Please do not hesitate to reach ou * Visit our `ReadTheDocs`_ page. * Join our `Discord`_ server. -* Contact me: ``kevin at dewald dot me`` (Dedicated consulting services available) - -Are you using SimpleBLE on your own project and would like to see it featured here? -Reach out and I'll add a link to it below! +* Contact us: ``contact at simpleble dot org`` +* Visit our `website`_ for more information. Supported platforms -------------------- -=========== ============= =================================== ===== -Windows Linux MacOS iOS -=========== ============= =================================== ===== -Windows 10+ Ubuntu 20.04+ 10.15+ (except 12.0, 12.1 and 12.2) 15.0+ -=========== ============= =================================== ===== +^^^^^^^^^^^^^^^^^^^ -Projects using SimpleBLE ------------------------- -Don't forget to check out the following projects using SimpleBLE: +Windows +""""""" +* **Supported Versions:** Windows 10 and newer +* **Notes:** -* `GDSimpleBLE`_ -* `BrainFlow`_ + - WSL does not support Bluetooth. + - Only a single adapter is supported by the OS backend. -Contributing ------------- -Pull requests are welcome. For major changes, please open an issue first to discuss -what you would like to change. +Linux +""""" +* **Supported Distributions:** Ubuntu 20.04 and newer +* **Notes:** -License -------- + - While Ubuntu is our primary supported distribution, the software may work on other major distributions using Bluez as their Bluetooth backend. -All components within this project that have not been bundled from -external creators, are licensed under the terms of the `MIT Licence`_. +MacOS +""""" +* **Supported Versions:** 10.15 (Catalina) and newer +* **Exceptions:** MacOS 12.0, 12.1, and 12.2 have a bug where the adapter won't return any peripherals after scanning. +* **Notes:** -.. Links + - Only a single adapter is supported by the OS backend. -.. _SimplePyBLE: https://pypi.org/project/simplepyble/ +iOS +""" +* **Supported Versions:** iOS 15.0 and newer +* **Notes:** -.. _MIT Licence: https://github.com/OpenBluetoothToolbox/SimpleBLE/blob/main/LICENCE.md + - Older versions of iOS might work but haven't been formally tested. -.. _fmtlib: https://github.com/fmtlib/fmt +Android +""""""" +* **Supported Versions:** API 31 and newer +* **Notes:** -.. _Discord: https://discord.gg/N9HqNEcvP3 + - Capabilities are still in an alpha stage, but should be good enough for initial testing. + - Older APIs are missing certain features of the JVM API that are required by SimpleBLE +.. Links + +.. _website: https://simpleble.org +.. _SimplePyBLE: https://pypi.org/project/simplepyble/ +.. _SimpleRsBLE: https://crates.io/crates/simplersble +.. _Discord: https://discord.gg/N9HqNEcvP3 .. _ReadTheDocs: https://simpleble.readthedocs.io/en/latest/ .. Other projects using SimpleBLE .. _GDSimpleBLE: https://github.com/jferdelyi/GDSimpleBLE -.. _BrainFlow: https://github.com/brainflow-dev/brainflow \ No newline at end of file +.. _BrainFlow: https://github.com/brainflow-dev/brainflow +.. _InsideBlue: https://github.com/eriklins/InsideBlue-BLE-Tool +.. _NodeWebBluetooth: https://github.com/thegecko/webbluetooth diff --git a/third_party/SimpleBLE/docs/requirements.txt b/third_party/SimpleBLE/docs/requirements.txt index eb4d45367..df91dccaa 100644 --- a/third_party/SimpleBLE/docs/requirements.txt +++ b/third_party/SimpleBLE/docs/requirements.txt @@ -1,3 +1,4 @@ sphinx==5.1.1 sphinx_rtd_theme==1.0.0 breathe==4.34.0 +sphinxcontrib-mermaid==0.9.2 \ No newline at end of file diff --git a/third_party/SimpleBLE/docs/simpleble/api.rst b/third_party/SimpleBLE/docs/simpleble/api.rst index f4f06d65c..1bff51a46 100644 --- a/third_party/SimpleBLE/docs/simpleble/api.rst +++ b/third_party/SimpleBLE/docs/simpleble/api.rst @@ -34,6 +34,9 @@ Standard API :members: :undoc-members: +.. doxygentypedef:: SimpleBLE::ByteArray + :project: simpleble + Safe API ======== @@ -55,3 +58,11 @@ C API .. doxygenfile:: peripheral.h :project: simpleble + +External API +============ + +.. doxygenclass:: kvn::bytearray + :project: external + :members: + :undoc-members: diff --git a/third_party/SimpleBLE/docs/simpleble/faq.rst b/third_party/SimpleBLE/docs/simpleble/faq.rst index 944a7de10..5f669f74d 100644 --- a/third_party/SimpleBLE/docs/simpleble/faq.rst +++ b/third_party/SimpleBLE/docs/simpleble/faq.rst @@ -13,6 +13,13 @@ UUID is not persistent across reboots, so you should not use it to identify a peripheral. Instead, you should use the name of the peripheral, which is persistent across reboots. +**I get a "Bluetooth not enabled" warning on Windows, despite Bluetooth being enabled.** + +This is a known issue when running a version of SimpleBLE built for a 32-bit architecture +on a 64-bit Windows machine. The issue is that the underlying Windows API will not allow +us to query the state of the Bluetooth adapter when running in 32-bit mode. The solution +is to consume a 64-bit version of SimpleBLE instead. + **What is the purpose behind the plain interface?** Building SimpleBLE with the plain-flavored interface allows you to use a version of the diff --git a/third_party/SimpleBLE/docs/simpleble/tutorial.rst b/third_party/SimpleBLE/docs/simpleble/tutorial.rst index 40638943d..0ae5026f1 100644 --- a/third_party/SimpleBLE/docs/simpleble/tutorial.rst +++ b/third_party/SimpleBLE/docs/simpleble/tutorial.rst @@ -233,18 +233,16 @@ Layers and their responsibilities .. _scan (cpp): https://github.com/OpenBluetoothToolbox/SimpleBLE/blob/main/examples/simpleble/cpp/scan/scan.cpp -.. _scan (c): https://github.com/OpenBluetoothToolbox/SimpleBLE/blob/main/examples/simpleble/c/scan/scan.c - .. _connect (cpp): https://github.com/OpenBluetoothToolbox/SimpleBLE/blob/main/examples/simpleble/cpp/connect/connect.cpp .. _connect_safe (cpp): https://github.com/OpenBluetoothToolbox/SimpleBLE/blob/main/examples/simpleble/cpp/connect_safe/connect_safe.cpp -.. _connect (c): https://github.com/OpenBluetoothToolbox/SimpleBLE/blob/main/examples/simpleble/c/connect/connect.c - .. _read: https://github.com/OpenBluetoothToolbox/SimpleBLE/blob/main/examples/simpleble/cpp/read/read.cpp .. _write: https://github.com/OpenBluetoothToolbox/SimpleBLE/blob/main/examples/simpleble/cpp/write/write.cpp .. _notify (cpp): https://github.com/OpenBluetoothToolbox/SimpleBLE/blob/main/examples/simpleble/cpp/notify/notify.cpp -.. _notify (c): https://github.com/OpenBluetoothToolbox/SimpleBLE/blob/main/examples/simpleble/c/notify/notify.c +.. _connect (c): https://github.com/OpenBluetoothToolbox/SimpleBLE/blob/main/examples/simpleble/c/connect.c +.. _scan (c): https://github.com/OpenBluetoothToolbox/SimpleBLE/blob/main/examples/simpleble/c/scan.c +.. _notify (c): https://github.com/OpenBluetoothToolbox/SimpleBLE/blob/main/examples/simpleble/c/notify.c diff --git a/third_party/SimpleBLE/docs/simpleble/usage.rst b/third_party/SimpleBLE/docs/simpleble/usage.rst index 6cd520819..3bcf04b82 100644 --- a/third_party/SimpleBLE/docs/simpleble/usage.rst +++ b/third_party/SimpleBLE/docs/simpleble/usage.rst @@ -6,32 +6,105 @@ SimpleBLE works on Windows, Linux, MacOS and iOS. Please follow the instructions to build and run SimpleBLE in your specific environment. -Building and Installing the Library (Source) -============================================ +System Requirements +=================== When building SimpleBLE from source, you will need some dependencies based on your current operating system. -**Linux** :: +**NOTE:** WSL does not support Bluetooth. + +General Requirements +-------------------- + + - `CMake`_ (Version 3.21 or higher) + +Linux +----- + +APT-based Distros +~~~~~~~~~~~~~~~~~ + + - `libdbus-1-dev` (install via ``sudo apt install libdbus-1-dev``) + +RPM-based Distros +~~~~~~~~~~~~~~~~~ + + - `dbus-devel` + - On Fedora, install via ``sudo dnf install dbus-devel`` + - On CentOS, install via ``sudo yum install dbus-devel`` + +Windows +------- + + - `Windows SDK` (Version 10.0.19041.0 or higher) + +MacOS +----- + + - `Xcode Command Line Tools` (install via ``xcode-select --install``) + +Android +------- + + - `Android Studio` + - `Android NDK` (Version 25 or higher. Older versions might work but haven't been thoroughly tested.) + + +Building and Installing SimpleBLE (Source) +============================================ + +Compiling the library is done using `CMake`_ and relies heavily on plenty of CMake +functionality. It is strongly suggested that you get familiarized with CMake before +blindly following the instructions below. + + +Building SimpleBLE +------------------ + +You can use the following commands to build SimpleBLE: :: - sudo apt install libdbus-1-dev + cmake -S -B build_simpleble + cmake --build build_simpleble -j7 -**Windows** :: +Note that if you want to modify the build configuration, you can do so by passing +additional arguments to the ``cmake`` command. For example, to build a shared library +set the ``BUILD_SHARED_LIBS`` CMake variable to ``TRUE`` :: - `Windows SDK `_ (Version 10.0.19041.0 or higher) + cmake -S -B build_simpleble -DBUILD_SHARED_LIBS=TRUE -The included CMake build script can be used to build SimpleBLE. -CMake is freely available for download from https://www.cmake.org/download/. :: +To build a plain-flavored version of the library, set the ``SIMPLEBLE_PLAIN`` CMake +variable to ``TRUE`` :: - cd - mkdir build && cd build - cmake .. -DSIMPLEBLE_LOG_LEVEL=[VERBOSE|DEBUG|INFO|WARNING|ERROR|FATAL] - cmake --build . -j7 - sudo cmake --install . + cmake -S -B build_simpleble -DSIMPLEBLE_PLAIN=TRUE -To build a shared library set the ``BUILD_SHARED_LIBS`` CMake variable to ``TRUE`` :: +To modify the log level, set the ``SIMPLEBLE_LOG_LEVEL`` CMake variable to one of the +following values: ``VERBOSE``, ``DEBUG``, ``INFO``, ``WARN``, ``ERROR``, ``FATAL`` :: - cmake -DBUILD_SHARED_LIBS=TRUE ... + cmake -S -B build_simpleble -DSIMPLEBLE_LOG_LEVEL=DEBUG + +**(Linux only)** To force the usage of the DBus session bus, enable the ``SIMPLEBLE_USE_SESSION_DBUS`` flag :: + + cmake -S -B build_simplebluez -DSIMPLEBLE_USE_SESSION_DBUS=TRUE + +Installing SimpleBLE +-------------------- + +To install SimpleBLE, you can use the following commands: :: + + cmake --install build_simpleble + +Note that if you want to modify the installation configuration, you can do so by passing +additional arguments to the ``cmake`` command. For example, to install the library to +a specific location, set the ``CMAKE_INSTALL_PREFIX`` CMake variable to the desired +location :: + + cmake --install build_simpleble --prefix /usr/local + +Note that on Linux and MacOS, you will need to run the ``cmake --install`` command +with ``sudo`` privileges. :: + + sudo cmake --install build_simpleble Usage with CMake (Installed) @@ -42,6 +115,9 @@ Once SimpleBLE has been installed, it can be consumed from within CMake:: find_package(simpleble REQUIRED CONFIG) target_link_libraries( simpleble::simpleble) +Note that this example assumes that SimpleBLE has been installed to a location +that is part of the default CMake module path. + Usage with CMake (Local) ============================= @@ -102,32 +178,47 @@ the following CMake options available: - ``LIBFMT_GIT_REPOSITORY``: The git repository to use for fmtlib. - - ``LIBFMT_GIT_TAG``: The git tag to use for fmtlib. *(Default: v8.1.1)* + - ``LIBFMT_GIT_TAG``: The git tag to use for fmtlib. *(Default: v9.1.0)* - ``LIBFMT_LOCAL_PATH``: The local path to use for fmtlib. *(Default: None)* -Build Examples -============== +Usage alongside native code in Android +====================================== -Use the following instructions to build the provided SimpleBLE examples: :: +When using SimpleBLE alongside native code in Android, you must include a small +Android dependency module that includes some necessary bridge classes used by SimpleBLE. +This is required because the Android JVM doesn't allow programatic definition of +derived classes, which forces us to bring these definitions in externally. + +To include this dependency module, add the following to your `settings.gradle` file: + +```groovy +includeBuild("path/to/simpleble/src/backends/android/simpleble-bridge") { + dependencySubstitution { + substitute module("org.simpleble.android.bridge:simpleble-bridge") with project(":") + } +} +``` + +```kotlin +includeBuild("path/to/simpleble/src/backends/android/simpleble-bridge") { + dependencySubstitution { + substitute(module("org.simpleble.android.bridge:simpleble-bridge")).using(project(":")) + } +} +``` - cd - mkdir build && cd build - cmake -DSIMPLEBLE_LOCAL=ON ../examples/simpleble - cmake --build . -j7 +**NOTE:** We will provide Maven packages in the future. -Plain-flavored Build -==================== +Build Examples +============== -Use the following instructions to build SimpleBLE with the plain-flavored API: :: +Use the following instructions to build the provided SimpleBLE examples: :: - cd - mkdir build && cd build - cmake .. -DSIMPLEBLE_PLAIN=ON - cmake --build . -j7 - sudo cmake --install . + cmake -S /examples/simpleble -B build_simpleble_examples -DSIMPLEBLE_LOCAL=ON + cmake --build build_simpleble_examples -j7 Testing @@ -145,11 +236,9 @@ Unit Tests To run the unit tests, run the following command: :: - cd - mkdir build && cd build - cmake .. -DCMAKE_BUILD_TYPE=Debug -DSIMPLEBLE_TEST=ON - cmake --build . -j7 - ./bin/simpleble_test + cmake -S -B build_simpleble_test -DSIMPLEBLE_TEST=ON + cmake --build build_simpleble_test -j7 + ./build_simpleble_test/bin/simpleble_test Address Sanitizer Tests @@ -157,11 +246,9 @@ Address Sanitizer Tests To run the address sanitizer tests, run the following command: :: - cd - mkdir build && cd build - cmake .. -DCMAKE_BUILD_TYPE=Debug -DSIMPLEBLE_SANITIZE=Address -DSIMPLEBLE_TEST=ON - cmake --build . -j7 - PYTHONMALLOC=malloc ./bin/simpleble_test + cmake -S -B build_simpleble_test -DSIMPLEBLE_SANITIZE=Address -DSIMPLEBLE_TEST=ON + cmake --build build_simpleble_test -j7 + PYTHONMALLOC=malloc ./build_simpleble_test/bin/simpleble_test It's important for ``PYTHONMALLOC`` to be set to ``malloc``, otherwise the tests will fail due to Python's memory allocator from triggering false positives. @@ -172,15 +259,17 @@ Thread Sanitizer Tests To run the thread sanitizer tests, run the following command: :: - cd - mkdir build && cd build - cmake .. -DCMAKE_BUILD_TYPE=Debug -DSIMPLEBLE_SANITIZE=Thread -DSIMPLEBLE_TEST=ON - cmake --build . -j7 - ./bin/simpleble_test + cmake -S -B build_simpleble_test -DSIMPLEBLE_SANITIZE=Thread -DSIMPLEBLE_TEST=ON + cmake --build build_simpleble_test -j7 + ./build_simpleble_test/bin/simpleble_test .. Links +.. _CMake: https://cmake.org/ + +.. _Windows SDK: https://developer.microsoft.com/en-us/windows/downloads/windows-10-sdk + .. _cmake-init-fetchcontent: https://github.com/friendlyanon/cmake-init-fetchcontent .. _fmtlib: https://github.com/fmtlib/fmt diff --git a/third_party/SimpleBLE/docs/simplebluez/usage.rst b/third_party/SimpleBLE/docs/simplebluez/usage.rst index 98a23d562..25e5aac5b 100644 --- a/third_party/SimpleBLE/docs/simplebluez/usage.rst +++ b/third_party/SimpleBLE/docs/simplebluez/usage.rst @@ -2,27 +2,85 @@ Usage ===== -SimpleBluez should work on any Linux environment supporting DBus. To install -the necessary dependencies on Debian-based systems, use the following command: :: +SimpleBluez should work on any Linux environment supporting DBus and Bluez. +Please follow the instructions below to build and run SimpleBluez in your specific environment. - sudo apt install libdbus-1-dev +System Requirements +=================== + +When building SimpleBluez from source, you will need some dependencies based on your +current operating system. + +General Requirements +-------------------- + + - `CMake`_ (Version 3.21 or higher) + +Linux +----- + +APT-based Distros +~~~~~~~~~~~~~~~~~ + + - `libdbus-1-dev` (install via ``sudo apt install libdbus-1-dev``) + +RPM-based Distros +~~~~~~~~~~~~~~~~~ + + - `dbus-devel` + - On Fedora, install via ``sudo dnf install dbus-devel`` + - On CentOS, install via ``sudo yum install dbus-devel`` Building and Installing the Library (Source) ============================================ -The included CMake build script can be used to build SimpleBluez. -CMake is freely available for download from https://www.cmake.org/download/. :: +Compiling the library is done using `CMake`_ and relies heavily on plenty of CMake +functionality. It is strongly suggested that you get familiarized with CMake before +blindly following the instructions below. + + +Building SimpleBluez +-------------------- + +You can use the following commands to build SimpleBluez: :: + + cmake -S -B build_simplebluez + cmake --build build_simplebluez -j7 - cd - mkdir build && cd build - cmake .. -DSIMPLEBLUEZ_LOG_LEVEL=[VERBOSE|DEBUG|INFO|WARNING|ERROR|FATAL] - cmake --build . -j7 - sudo cmake --install . +Note that if you want to modify the build configuration, you can do so by passing +additional arguments to the ``cmake`` command. For example, to build a shared library +set the ``BUILD_SHARED_LIBS`` CMake variable to ``TRUE`` :: -To build a shared library set the ``BUILD_SHARED_LIBS`` CMake variable to ``TRUE`` :: + cmake -S -B build_simplebluez -DBUILD_SHARED_LIBS=TRUE - cmake -DBUILD_SHARED_LIBS=TRUE ... +To modify the log level, set the ``SIMPLEBLUEZ_LOG_LEVEL`` CMake variable to one of the +following values: ``VERBOSE``, ``DEBUG``, ``INFO``, ``WARN``, ``ERROR``, ``FATAL`` :: + + cmake -S -B build_simplebluez -DSIMPLEBLUEZ_LOG_LEVEL=DEBUG + +To force the usage of the DBus session bus, enable the ``SIMPLEBLUEZ_USE_SESSION_DBUS`` flag :: + + cmake -S -B build_simplebluez -DSIMPLEBLUEZ_USE_SESSION_DBUS=TRUE + +Installing SimpleBluez +---------------------- + +To install SimpleBluez, you can use the following commands: :: + + cmake --install build_simplebluez + +Note that if you want to modify the installation configuration, you can do so by passing +additional arguments to the ``cmake`` command. For example, to install the library to +a specific location, set the ``CMAKE_INSTALL_PREFIX`` CMake variable to the desired +location :: + + cmake --install build_simplebluez --prefix /usr/local + +Note that on Linux and MacOS, you will need to run the ``cmake --install`` command +with ``sudo`` privileges. :: + + sudo cmake --install build_simplebluez Usage with CMake (Installed) @@ -103,10 +161,8 @@ Build Examples Use the following instructions to build the provided SimpleBluez examples: :: - cd - mkdir build && cd build - cmake -DSIMPLEBLUEZ_LOCAL=ON ../examples/simplebluez - cmake --build . -j7 + cmake -S /examples/simplebluez -B build_simplebluez_examples -DSIMPLEBLUEZ_LOCAL=ON + cmake --build build_simplebluez_examples -j7 Testing @@ -124,11 +180,9 @@ Unit Tests To run the unit tests, run the following command: :: - cd - mkdir build && cd build - cmake .. -DCMAKE_BUILD_TYPE=Debug -DSIMPLEBLUEZ_TEST=ON - cmake --build . -j7 - ./bin/simplebluez_test + cmake -S -B build_simplebluez_test -DSIMPLEBLUEZ_TEST=ON + cmake --build build_simplebluez_test -j7 + ./build_simplebluez_test/bin/simplebluez_test Address Sanitizer Tests @@ -136,11 +190,9 @@ Address Sanitizer Tests To run the address sanitizer tests, run the following command: :: - cd - mkdir build && cd build - cmake .. -DCMAKE_BUILD_TYPE=Debug -DSIMPLEBLUEZ_SANITIZE=Address -DSIMPLEBLUEZ_TEST=ON - cmake --build . -j7 - PYTHONMALLOC=malloc ./bin/simplebluez_test + cmake -S -B build_simplebluez_test -DSIMPLEBLUEZ_SANITIZE=Address -DSIMPLEBLUEZ_TEST=ON + cmake --build build_simplebluez_test -j7 + PYTHONMALLOC=malloc ./build_simplebluez_test/bin/simplebluez_test It's important for ``PYTHONMALLOC`` to be set to ``malloc``, otherwise the tests will fail due to Python's memory allocator from triggering false positives. @@ -151,15 +203,15 @@ Thread Sanitizer Tests To run the thread sanitizer tests, run the following command: :: - cd - mkdir build && cd build - cmake .. -DCMAKE_BUILD_TYPE=Debug -DSIMPLEBLUEZ_SANITIZE=Thread -DSIMPLEBLUEZ_TEST=ON - cmake --build . -j7 - ./bin/simplebluez_test + cmake -S -B build_simplebluez_test -DSIMPLEBLUEZ_SANITIZE=Thread -DSIMPLEBLUEZ_TEST=ON + cmake --build build_simplebluez_test -j7 + ./build_simplebluez_test/bin/simplebluez_test .. Links +.. _CMake: https://cmake.org/ + .. _cmake-init-fetchcontent: https://github.com/friendlyanon/cmake-init-fetchcontent .. _fmtlib: https://github.com/fmtlib/fmt diff --git a/third_party/SimpleBLE/docs/simpledbus/usage.rst b/third_party/SimpleBLE/docs/simpledbus/usage.rst index 5e7e04fcf..41c35a3a3 100644 --- a/third_party/SimpleBLE/docs/simpledbus/usage.rst +++ b/third_party/SimpleBLE/docs/simpledbus/usage.rst @@ -2,27 +2,85 @@ Usage ===== -SimpleDBus should work on any Linux environment supporting DBus. To install -the necessary dependencies on Debian-based systems, use the following command: :: +SimpleDBus should work on any Linux environment supporting DBus. +Please follow the instructions below to build and run SimpleDBus in your specific environment. - sudo apt install libdbus-1-dev +System Requirements +=================== + +When building SimpleDBus from source, you will need some dependencies based on your +current operating system. + +General Requirements +-------------------- + + - `CMake`_ (Version 3.21 or higher) + +Linux +----- + +APT-based Distros +~~~~~~~~~~~~~~~~~ + + - `libdbus-1-dev` (install via ``sudo apt install libdbus-1-dev``) + +RPM-based Distros +~~~~~~~~~~~~~~~~~ + + - `dbus-devel` + - On Fedora, install via ``sudo dnf install dbus-devel`` + - On CentOS, install via ``sudo yum install dbus-devel`` Building and Installing the Library (Source) ============================================ -The included CMake build script can be used to build SimpleDBus. -CMake is freely available for download from https://www.cmake.org/download/. :: +Compiling the library is done using `CMake`_ and relies heavily on plenty of CMake +functionality. It is strongly suggested that you get familiarized with CMake before +blindly following the instructions below. + + +Building SimpleDBus +------------------- + +You can use the following commands to build SimpleDBus: :: + + cmake -S -B build_simpledbus + cmake --build build_simpledbus -j7 - cd - mkdir build && cd build - cmake .. -DSIMPLEDBUS_LOG_LEVEL=[VERBOSE|DEBUG|INFO|WARNING|ERROR|FATAL] - cmake --build . -j7 - sudo cmake --install . +Note that if you want to modify the build configuration, you can do so by passing +additional arguments to the ``cmake`` command. For example, to build a shared library +set the ``BUILD_SHARED_LIBS`` CMake variable to ``TRUE`` :: -To build a shared library set the ``BUILD_SHARED_LIBS`` CMake variable to ``TRUE`` :: + cmake -S -B build_simpledbus -DBUILD_SHARED_LIBS=TRUE - cmake -DBUILD_SHARED_LIBS=TRUE ... +To modify the log level, set the ``SIMPLEDBUS_LOG_LEVEL`` CMake variable to one of the +following values: ``VERBOSE``, ``DEBUG``, ``INFO``, ``WARN``, ``ERROR``, ``FATAL`` :: + + cmake -S -B build_simpledbus -DSIMPLEDBUS_LOG_LEVEL=DEBUG + +To force the usage of the DBus session bus, enable the ``SIMPLEDBUS_USE_SESSION_DBUS`` flag :: + + cmake -S -B build_simpledbus -DSIMPLEDBUS_USE_SESSION_DBUS=TRUE + +Installing SimpleDBus +---------------------- + +To install SimpleDBus, you can use the following commands: :: + + cmake --install build_simpledbus + +Note that if you want to modify the installation configuration, you can do so by passing +additional arguments to the ``cmake`` command. For example, to install the library to +a specific location, set the ``CMAKE_INSTALL_PREFIX`` CMake variable to the desired +location :: + + cmake --install build_simpledbus --prefix /usr/local + +Note that on Linux and MacOS, you will need to run the ``cmake --install`` command +with ``sudo`` privileges. :: + + sudo cmake --install build_simpledbus Usage with CMake (Installed) @@ -103,10 +161,8 @@ Build Examples Use the following instructions to build the provided SimpleDBus examples: :: - cd - mkdir build && cd build - cmake -DSIMPLEDBUS_LOCAL=ON ../examples/simpledbus - cmake --build . -j7 + cmake -S /examples/simpledbus -B build_simpledbus_examples -DSIMPLEDBUS_LOCAL=ON + cmake --build build_simpledbus_examples -j7 Testing @@ -124,11 +180,9 @@ Unit Tests To run the unit tests, run the following command: :: - cd - mkdir build && cd build - cmake .. -DCMAKE_BUILD_TYPE=Debug -DSIMPLEDBUS_TEST=ON - cmake --build . -j7 - ./bin/simpledbus_test + cmake -S -B build_simpledbus_test -DSIMPLEDBUS_TEST=ON + cmake --build build_simpledbus_test -j7 + ./build_simpledbus_test/bin/simpledbus_test Address Sanitizer Tests @@ -136,11 +190,9 @@ Address Sanitizer Tests To run the address sanitizer tests, run the following command: :: - cd - mkdir build && cd build - cmake .. -DCMAKE_BUILD_TYPE=Debug -DSIMPLEDBUS_SANITIZE=Address -DSIMPLEDBUS_TEST=ON - cmake --build . -j7 - PYTHONMALLOC=malloc ./bin/simpledbus_test + cmake -S -B build_simpledbus_test -DSIMPLEDBUS_SANITIZE=Address -DSIMPLEDBUS_TEST=ON + cmake --build build_simpledbus_test -j7 + PYTHONMALLOC=malloc ./build_simpledbus_test/bin/simpledbus_test It's important for ``PYTHONMALLOC`` to be set to ``malloc``, otherwise the tests will fail due to Python's memory allocator from triggering false positives. @@ -151,15 +203,15 @@ Thread Sanitizer Tests To run the thread sanitizer tests, run the following command: :: - cd - mkdir build && cd build - cmake .. -DCMAKE_BUILD_TYPE=Debug -DSIMPLEDBUS_SANITIZE=Thread -DSIMPLEDBUS_TEST=ON - cmake --build . -j7 - ./bin/simpledbus_test + cmake -S -B build_simpledbus_test -DSIMPLEDBUS_SANITIZE=Thread -DSIMPLEDBUS_TEST=ON + cmake --build build_simpledbus_test -j7 + ./build_simpledbus_test/bin/simpledbus_test .. Links +.. _CMake: https://cmake.org/ + .. _cmake-init-fetchcontent: https://github.com/friendlyanon/cmake-init-fetchcontent .. _fmtlib: https://github.com/fmtlib/fmt diff --git a/third_party/SimpleBLE/docs/simpledroidble/usage.rst b/third_party/SimpleBLE/docs/simpledroidble/usage.rst new file mode 100644 index 000000000..a2fabd159 --- /dev/null +++ b/third_party/SimpleBLE/docs/simpledroidble/usage.rst @@ -0,0 +1,47 @@ +===== +Usage +===== + +SimpleDroidBLE is an Android-specific package that provides an API similar to +SimpleBLE, using modern Kotlin idiomatic code. + +This code is currently under active development and some features are not yet +implemented or their API might change, but should be enough to help you get +started. + +Consuming Locally +================= + +If you want to use SimpleDroidBLE as part of your project from a local copy, +you can do so by adding the following to your `settings.gradle` or `settings.gradle.kts`file. +Make sure this include is before your `include(":app")` statement. + +```groovy +includeBuild("path/to/simpledroidble") { + dependencySubstitution { + substitute module("org.simpleble.android:simpledroidble") with project(":simpledroidble") + } +} + +```kotlin +includeBuild("path/to/simpledroidble") { + dependencySubstitution { + substitute(module("org.simpleble.android:simpledroidble")).using(project(":simpledroidble")) + } +} +``` + +Then, inside your `build.gradle` or `build.gradle.kts` file, you can add the +following dependency: + +```groovy +dependencies { + implementation "org.simpleble.android:simpledroidble" +} +``` + +```kotlin +dependencies { + implementation("org.simpleble.android:simpledroidble") +} +``` \ No newline at end of file diff --git a/third_party/SimpleBLE/examples/simpleble-android/.gitignore b/third_party/SimpleBLE/examples/simpleble-android/.gitignore new file mode 100644 index 000000000..aa724b770 --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble-android/.gitignore @@ -0,0 +1,15 @@ +*.iml +.gradle +/local.properties +/.idea/caches +/.idea/libraries +/.idea/modules.xml +/.idea/workspace.xml +/.idea/navEditor.xml +/.idea/assetWizardSettings.xml +.DS_Store +/build +/captures +.externalNativeBuild +.cxx +local.properties diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/.gitignore b/third_party/SimpleBLE/examples/simpleble-android/app/.gitignore new file mode 100644 index 000000000..42afabfd2 --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble-android/app/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/build.gradle.kts b/third_party/SimpleBLE/examples/simpleble-android/app/build.gradle.kts new file mode 100644 index 000000000..bbd7cd103 --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble-android/app/build.gradle.kts @@ -0,0 +1,60 @@ +plugins { + alias(libs.plugins.androidApplication) + alias(libs.plugins.jetbrainsKotlinAndroid) +} + +android { + namespace = "org.simpleble.examples.android" + compileSdk = 34 + + defaultConfig { + applicationId = "org.simpleble.examples.android" + minSdk = 31 + targetSdk = 34 + versionCode = 1 + versionName = "1.0" + + } + + buildTypes { + release { + isMinifyEnabled = false + proguardFiles( + getDefaultProguardFile("proguard-android-optimize.txt"), + "proguard-rules.pro" + ) + } + } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + } + kotlinOptions { + jvmTarget = "1.8" + } + buildFeatures { + viewBinding = true + compose = true + } + composeOptions { + kotlinCompilerExtensionVersion = "1.5.11" + } +} + +dependencies { + + implementation(libs.androidx.core.ktx) + implementation(libs.androidx.appcompat) + implementation(libs.material) + + implementation(libs.ui) + implementation(libs.ui.tooling) + implementation(libs.ui.tooling.preview) + implementation(libs.foundation) + implementation(libs.material) + implementation(libs.activity.ktx) + implementation(libs.activity.compose) + + //noinspection UseTomlInstead + implementation("org.simpleble.android:simpledroidble") +} \ No newline at end of file diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/proguard-rules.pro b/third_party/SimpleBLE/examples/simpleble-android/app/proguard-rules.pro new file mode 100644 index 000000000..481bb4348 --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble-android/app/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile \ No newline at end of file diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/src/main/AndroidManifest.xml b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/AndroidManifest.xml new file mode 100644 index 000000000..ecf0890c9 --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/AndroidManifest.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/src/main/java/org/simpleble/examples/android/SimpleBleAndroidExample.kt b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/java/org/simpleble/examples/android/SimpleBleAndroidExample.kt new file mode 100644 index 000000000..58038de5d --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/java/org/simpleble/examples/android/SimpleBleAndroidExample.kt @@ -0,0 +1,17 @@ +package org.simpleble.examples.android + +import android.app.Application +import android.util.Log + +class SimpleBleAndroidExample : Application() { + + override fun onCreate() { + Log.d("SimpleBleAndroidExample", "onCreate()") + super.onCreate() + } + + override fun onTerminate() { + Log.d("SimpleBleAndroidExample", "onTerminate()") + super.onTerminate() + } +} \ No newline at end of file diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/src/main/java/org/simpleble/examples/android/activities/MainActivity.kt b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/java/org/simpleble/examples/android/activities/MainActivity.kt new file mode 100644 index 000000000..48a9b2e6c --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/java/org/simpleble/examples/android/activities/MainActivity.kt @@ -0,0 +1,136 @@ +package org.simpleble.examples.android.activities; + +import android.Manifest +import android.annotation.SuppressLint +import android.content.pm.PackageManager +import android.os.Build +import android.os.Bundle +import android.util.Log +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.padding +import androidx.compose.material.BottomNavigation +import androidx.compose.material.BottomNavigationItem +import androidx.compose.material.Button +import androidx.compose.material.Icon +import androidx.compose.material.MaterialTheme +import androidx.compose.material.Scaffold +import androidx.compose.material.Surface +import androidx.compose.material.Text +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.AccountBox +import androidx.compose.material.icons.filled.Info +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.core.app.ActivityCompat +import org.simpleble.android.Adapter +import org.simpleble.android.SimpleDroidBle +import org.simpleble.examples.android.viewmodels.BluetoothViewModel +import org.simpleble.examples.android.views.ConnectContent +import org.simpleble.examples.android.views.ListAdaptersContent +import org.simpleble.examples.android.views.NotifyContent +import org.simpleble.examples.android.views.ReadContent +import org.simpleble.examples.android.views.ScanContent +import java.lang.ref.WeakReference + +class MainActivity : ComponentActivity() { + private val bluetoothHasPermissions = mutableStateOf(false) + private val bluetoothViewModel = BluetoothViewModel() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + // Set the activity reference for SimpleDroidBle. This is required for requesting permissions. + // NOTE: This is a bit of a hacky way to do this, but it's the only way to do it for now. + SimpleDroidBle.contextReference = WeakReference(this) + bluetoothHasPermissions.value = SimpleDroidBle.hasPermissions + + setContent { + MaterialTheme { + Surface { + if (bluetoothHasPermissions.value) { + ExampleView(bluetoothViewModel) + } else { + Column { + Button(onClick = { SimpleDroidBle.requestPermissions() }) { + Text("Request Bluetooth Permissions") + } + Text("Bluetooth permissions are required to use this app") + Text("Please grant the permissions and restart the app") + } + } + } + } + } + } + + override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults) + SimpleDroidBle.handleOnRequestPermissionsResult(requestCode, permissions, grantResults) + bluetoothHasPermissions.value = SimpleDroidBle.hasPermissions + } +} + + + +@Composable +fun ExampleView(bluetoothViewModel: BluetoothViewModel) { + var selectedTab by remember { mutableIntStateOf(0) } + + Scaffold( + bottomBar = { + BottomNavigation { + BottomNavigationItem( + label = { Text("Adapter") }, + icon = { Icon(Icons.Default.Info, contentDescription = null) }, + selected = selectedTab == 0, + onClick = { selectedTab = 0 } + ) + BottomNavigationItem( + label = { Text("Scan") }, + icon = { Icon(Icons.Default.AccountBox, contentDescription = null) }, + selected = selectedTab == 1, + onClick = { selectedTab = 1 } + ) + BottomNavigationItem( + label = { Text("Connect") }, + icon = { Icon(Icons.Default.AccountBox, contentDescription = null) }, + selected = selectedTab == 2, + onClick = { selectedTab = 2 } + ) + BottomNavigationItem( + label = { Text("Read") }, + icon = { Icon(Icons.Default.AccountBox, contentDescription = null) }, + selected = selectedTab == 3, + onClick = { selectedTab = 3 } + ) + BottomNavigationItem( + label = { Text("Notify") }, + icon = { Icon(Icons.Default.AccountBox, contentDescription = null) }, + selected = selectedTab == 4, + onClick = { selectedTab = 4 } + ) + } + } + ) { innerPadding -> + Column( + modifier = Modifier.padding(innerPadding) + ) { + when (selectedTab) { + 0 -> ListAdaptersContent() + 1 -> ScanContent(bluetoothViewModel) + 2 -> ConnectContent(bluetoothViewModel) + 3 -> ReadContent(bluetoothViewModel) + 4 -> NotifyContent(bluetoothViewModel) + else -> ListAdaptersContent() // Default + } + } + } +} + diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/src/main/java/org/simpleble/examples/android/viewmodels/BluetoothViewModel.kt b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/java/org/simpleble/examples/android/viewmodels/BluetoothViewModel.kt new file mode 100644 index 000000000..d05ede182 --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/java/org/simpleble/examples/android/viewmodels/BluetoothViewModel.kt @@ -0,0 +1,16 @@ +package org.simpleble.examples.android.viewmodels + +import androidx.compose.runtime.mutableStateOf +import androidx.lifecycle.ViewModel +import org.simpleble.android.Adapter + +class BluetoothViewModel : ViewModel() { + private lateinit var _adapter: Adapter + val adapter: Adapter + get() { + if (!::_adapter.isInitialized) { + _adapter = Adapter.getAdapters()[0] + } + return _adapter + } +} \ No newline at end of file diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/src/main/java/org/simpleble/examples/android/views/ConnectContent.kt b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/java/org/simpleble/examples/android/views/ConnectContent.kt new file mode 100644 index 000000000..c64bde9ca --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/java/org/simpleble/examples/android/views/ConnectContent.kt @@ -0,0 +1,230 @@ +package org.simpleble.examples.android.views + +import android.util.Log +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.material.Button +import androidx.compose.material.MaterialTheme +import androidx.compose.material.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.launch +import org.simpleble.android.Adapter +import org.simpleble.android.BluetoothUUID +import org.simpleble.android.Peripheral +import org.simpleble.examples.android.viewmodels.BluetoothViewModel + + +@Composable +fun ConnectContent(bluetoothViewModel: BluetoothViewModel) { + var scanResults by remember { mutableStateOf(emptyList()) } + var isScanning by remember { mutableStateOf(false) } + + var selectedDevice by remember { mutableStateOf(null) } + var isConnected by remember { mutableStateOf(false) } + var mtu by remember { mutableStateOf(0) } + + LaunchedEffect(Unit, selectedDevice) { + CoroutineScope(Dispatchers.Main).launch { + bluetoothViewModel.adapter.onScanActive.collect { + isScanning = it + } + } + + CoroutineScope(Dispatchers.Main).launch { + bluetoothViewModel.adapter.onScanFound.collect { + Log.d("SimpleBLE", "Found device: ${it.identifier} [${it.address}] ${it.rssi} dBm") + scanResults = scanResults + it + } + } + + + selectedDevice?.let { peripheral -> + CoroutineScope(Dispatchers.Main).launch { + peripheral.onConnectionActive.collectLatest { active -> + isConnected = active + + mtu = if (active) { + peripheral.mtu + } else { + 0 + } + } + } + + CoroutineScope(Dispatchers.Main).launch { + peripheral.onConnected.collectLatest { + Log.d("SimpleBLE", "Connected to ${peripheral.identifier} [${peripheral.address}]") + } + } + + CoroutineScope(Dispatchers.Main).launch { + peripheral.onDisconnected.collectLatest { + Log.d("SimpleBLE", "Disconnected from ${peripheral.identifier} [${peripheral.address}]") + } + } + } + + + } + + + + Column( + modifier = Modifier.fillMaxSize(), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center + ) { + if (isScanning) { + Text( + text = "Scanning...", + style = MaterialTheme.typography.h6, + modifier = Modifier.padding(16.dp) + ) + } + + Button( + onClick = { + if (!isScanning) { + CoroutineScope(Dispatchers.Main).launch { + scanResults = emptyList() + bluetoothViewModel.adapter.scanStart() + } + } else { + CoroutineScope(Dispatchers.Main).launch { + bluetoothViewModel.adapter.scanStop() + } + } + }, + modifier = Modifier.padding(16.dp) + ) { + Text(text = if (isScanning) "Stop Scan" else "Start Scan") + } + + selectedDevice?.let { peripheral -> + Text( + text = "Connecting to ${peripheral.identifier} [${peripheral.address}]", + style = MaterialTheme.typography.body1, + modifier = Modifier.padding(16.dp) + ) + + Button( + onClick = { + + if (!isConnected) { + CoroutineScope(Dispatchers.Main).launch { + peripheral.connect() + } + } else { + CoroutineScope(Dispatchers.Main).launch { + peripheral.disconnect() + } + } + }, + modifier = Modifier.padding(16.dp) + ) { + Text(text = if (isConnected) "Disconnect" else "Connect") + } + + if (isConnected) { + Text( + text = "Successfully connected.", + style = MaterialTheme.typography.body1, + modifier = Modifier.padding(16.dp) + ) + + Text( + text = "MTU: ${peripheral.mtu}", + style = MaterialTheme.typography.body1, + modifier = Modifier.padding(16.dp) + ) + + LazyColumn( + modifier = Modifier.fillMaxWidth(), + contentPadding = PaddingValues(8.dp) + ) { + items(peripheral.services().withIndex().toList()) { (index, service) -> + Text( + text = "Service: ${service.uuid}", + style = MaterialTheme.typography.body1, + modifier = Modifier.padding(16.dp) + ) + + service.characteristics.forEach { characteristic -> + Text( + text = "Characteristic: ${characteristic.uuid}", + style = MaterialTheme.typography.body2, + modifier = Modifier.padding(start = 32.dp) + ) + +// Text( +// text = "Capabilities: ${characteristic.capabilities.joinToString(", ")}", +// style = MaterialTheme.typography.body2, +// modifier = Modifier.padding(start = 32.dp) +// ) + + characteristic.descriptors.forEach { descriptor -> + Text( + text = "Descriptor: ${descriptor.uuid}", + style = MaterialTheme.typography.body2, + modifier = Modifier.padding(start = 48.dp) + ) + } + } + } + } + } + } + + if (scanResults.isNotEmpty()) { + Text( + text = "The following devices were found:", + style = MaterialTheme.typography.h6, + modifier = Modifier.padding(16.dp) + ) + + LazyColumn( + modifier = Modifier.fillMaxWidth(), + contentPadding = PaddingValues(8.dp) + ) { + items(scanResults.withIndex().toList()) { (index, peripheral) -> + Text( + text = "[$index] ${peripheral.identifier} [${peripheral.address}]", + style = MaterialTheme.typography.body1, + modifier = Modifier + .padding(8.dp) + .clickable { + selectedDevice = peripheral + } + ) + } + } + } else { + Text( + text = "No devices found.", + style = MaterialTheme.typography.body1, + modifier = Modifier.padding(16.dp) + ) + } + + + } +} \ No newline at end of file diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/src/main/java/org/simpleble/examples/android/views/ListAdaptersContent.kt b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/java/org/simpleble/examples/android/views/ListAdaptersContent.kt new file mode 100644 index 000000000..01dadc3a8 --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/java/org/simpleble/examples/android/views/ListAdaptersContent.kt @@ -0,0 +1,88 @@ +package org.simpleble.examples.android.views + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.material.MaterialTheme +import androidx.compose.material.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import org.simpleble.android.Adapter +import org.simpleble.android.SimpleDroidBle + + +@Composable +fun ListAdaptersContent() { + var simpleBleVersion by remember { mutableStateOf("") } + var bluetoothEnabled by remember { mutableStateOf(false) } + var adapterList by remember { mutableStateOf(emptyList()) } + + LaunchedEffect(Unit) { + simpleBleVersion = SimpleDroidBle.getVersion() + bluetoothEnabled = Adapter.isBluetoothEnabled() + adapterList = Adapter.getAdapters() + } + + Column( + modifier = Modifier.fillMaxSize(), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center + ) { + Text( + text = "Using SimpleBLE version: $simpleBleVersion", + style = MaterialTheme.typography.h6, + textAlign = TextAlign.Center, + modifier = Modifier.padding(16.dp) + ) + + Text( + text = "Bluetooth enabled: $bluetoothEnabled", + style = MaterialTheme.typography.h6, + textAlign = TextAlign.Center, + modifier = Modifier.padding(16.dp) + ) + + if (adapterList.isEmpty()) { + Text( + text = "No adapter found", + style = MaterialTheme.typography.h6, + textAlign = TextAlign.Center, + modifier = Modifier.padding(16.dp) + ) + } else { + Text( + text = "Adapters:", + style = MaterialTheme.typography.h6, + textAlign = TextAlign.Center, + modifier = Modifier.padding(16.dp) + ) + + LazyColumn( + modifier = Modifier.fillMaxWidth(), + contentPadding = PaddingValues(16.dp) + ) { + items(adapterList) { adapter -> + Text( + text = "Adapter: ${adapter.identifier} [${adapter.address}]", + style = MaterialTheme.typography.body1, + modifier = Modifier.padding(8.dp) + ) + } + } + } + } +} \ No newline at end of file diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/src/main/java/org/simpleble/examples/android/views/NotifyContent.kt b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/java/org/simpleble/examples/android/views/NotifyContent.kt new file mode 100644 index 000000000..a7d7ec309 --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/java/org/simpleble/examples/android/views/NotifyContent.kt @@ -0,0 +1,254 @@ +package org.simpleble.examples.android.views + +import android.util.Log +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.material.Button +import androidx.compose.material.MaterialTheme +import androidx.compose.material.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.TextUnit +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.launch +import org.simpleble.android.BluetoothUUID +import org.simpleble.android.Peripheral +import org.simpleble.examples.android.viewmodels.BluetoothViewModel + +@Composable +fun NotifyContent(bluetoothViewModel: BluetoothViewModel) { + var scanResults by remember { mutableStateOf(emptyList()) } + var isScanning by remember { mutableStateOf(false) } + + var selectedDevice by remember { mutableStateOf(null) } + var isConnected by remember { mutableStateOf(false) } + + var servicescharacteristics by remember { mutableStateOf(emptyList>()) } + var selectedServiceCharacteristic by remember { mutableStateOf?>(null) } + var receivedData by remember { mutableStateOf(null) } + + LaunchedEffect(Unit, selectedDevice) { + CoroutineScope(Dispatchers.Main).launch { + bluetoothViewModel.adapter.onScanActive.collect { + Log.d("SimpleBLE", "Scan active: $it") + isScanning = it + } + } + + CoroutineScope(Dispatchers.Main).launch { + bluetoothViewModel.adapter.onScanFound.collect { + Log.d("SimpleBLE", "Found device: ${it.identifier} [${it.address}] ${it.rssi} dBm") + scanResults = scanResults + it + } + } + + selectedDevice?.let { peripheral -> + CoroutineScope(Dispatchers.Main).launch { + peripheral.onConnectionActive.collectLatest { active -> + isConnected = active + } + } + + CoroutineScope(Dispatchers.Main).launch { + peripheral.onConnected.collectLatest { + Log.d("SimpleBLE", "Connected to ${peripheral.identifier} [${peripheral.address}]") + + servicescharacteristics = peripheral.services().flatMap { service -> + service.characteristics.map { characteristic -> + Log.d("SimpleBLE", "Service: ${service.uuid} Characteristic: ${characteristic.uuid} [Notify: ${characteristic.canNotify} Indicate: ${characteristic.canIndicate} Read: ${characteristic.canRead} WriteCommand: ${characteristic.canWriteCommand} WriteRequest: ${characteristic.canWriteRequest}]") + Pair(BluetoothUUID(service.uuid), BluetoothUUID(characteristic.uuid)) + } + } + } + } + + CoroutineScope(Dispatchers.Main).launch { + peripheral.onDisconnected.collectLatest { + Log.d("SimpleBLE", "Disconnected from ${peripheral.identifier} [${peripheral.address}]") + + servicescharacteristics = emptyList() + selectedServiceCharacteristic = null + receivedData = null + } + } + } + } + + Column( + modifier = Modifier.fillMaxSize(), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center + ) { + if (isScanning) { + Text( + text = "Scanning...", + style = MaterialTheme.typography.h6, + modifier = Modifier.padding(16.dp) + ) + } + + Button( + onClick = { + if (!isScanning) { + CoroutineScope(Dispatchers.Main).launch { + scanResults = emptyList() + bluetoothViewModel.adapter.scanStart() + } + } else { + CoroutineScope(Dispatchers.Main).launch { + bluetoothViewModel.adapter.scanStop() + } + } + }, + modifier = Modifier.padding(16.dp) + ) { + Text(text = if (isScanning) "Stop Scan" else "Start Scan") + } + + + selectedDevice?.let { peripheral -> + Text( + text = "Connecting to ${peripheral.identifier} [${peripheral.address}]", + style = MaterialTheme.typography.body1, + modifier = Modifier.padding(16.dp) + ) + + Button( + onClick = { + if (!isConnected) { + CoroutineScope(Dispatchers.Main).launch { + peripheral.connect() + } + } else { + CoroutineScope(Dispatchers.Main).launch { + peripheral.disconnect() + } + } + }, + modifier = Modifier.padding(16.dp) + ) { + Text(text = if (isConnected) "Disconnect" else "Connect") + } + + if (isConnected) { + Text( + text = "Successfully connected, printing services and characteristics..", + style = MaterialTheme.typography.body1, + modifier = Modifier.padding(16.dp) + ) + + selectedServiceCharacteristic?.let { servicecharacteristic -> + Button( + onClick = { + CoroutineScope(Dispatchers.Main).launch { + peripheral.notify(servicecharacteristic.first, servicecharacteristic.second).collect { it -> + val hexString = it.joinToString(separator = " ") { "%02x".format(it) } + Log.d("SimpleBLE", "Received notification: $hexString") + } + } + CoroutineScope(Dispatchers.Main).launch { + delay(10000) + peripheral.unsubscribe(servicecharacteristic.first, servicecharacteristic.second) + } + }, + modifier = Modifier.padding(16.dp) + ) { + Text(text = "Subscribe to Notifications") + } + + Button( + onClick = { + CoroutineScope(Dispatchers.Main).launch { + peripheral.read(servicecharacteristic.first, servicecharacteristic.second) + } + }, + modifier = Modifier.padding(16.dp) + ) { + Text(text = "Read") + } + + receivedData?.let { data -> + Text( + text = "Received: ${data.joinToString(separator = " ") { "%02x".format(it) }}", + style = MaterialTheme.typography.body1, + modifier = Modifier.padding(16.dp) + ) + } + } + + LazyColumn( + modifier = Modifier.fillMaxWidth(), + contentPadding = PaddingValues(16.dp) + ) { + items(servicescharacteristics.withIndex().toList()) { (index, characteristic) -> + Text( + text = "[$index] ${characteristic.first} ${characteristic.second}", + style = TextStyle( + fontWeight = FontWeight.Normal, + fontSize = 8.sp, + lineHeight = 12.sp, + letterSpacing = 0.5.sp + ), + modifier = Modifier + .padding(8.dp) + .clickable { + selectedServiceCharacteristic = characteristic + } + ) + } + } + } + } + + if (scanResults.isNotEmpty()) { + Text( + text = "The following devices were found:", + style = MaterialTheme.typography.h6, + modifier = Modifier.padding(16.dp) + ) + + LazyColumn( + modifier = Modifier.fillMaxWidth(), + contentPadding = PaddingValues(16.dp) + ) { + items(scanResults.withIndex().toList()) { (index, peripheral) -> + Text( + text = "[$index] ${peripheral.identifier} [${peripheral.address}]", + style = MaterialTheme.typography.body1, + modifier = Modifier + .padding(8.dp) + .clickable { + selectedDevice = peripheral + } + ) + } + } + } else { + Text( + text = "No devices found.", + style = MaterialTheme.typography.body1, + modifier = Modifier.padding(16.dp) + ) + } + } +} \ No newline at end of file diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/src/main/java/org/simpleble/examples/android/views/ReadContent.kt b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/java/org/simpleble/examples/android/views/ReadContent.kt new file mode 100644 index 000000000..aeceb9ff7 --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/java/org/simpleble/examples/android/views/ReadContent.kt @@ -0,0 +1,197 @@ +package org.simpleble.examples.android.views + +import android.util.Log +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.material.Button +import androidx.compose.material.MaterialTheme +import androidx.compose.material.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import org.simpleble.android.Adapter +import org.simpleble.android.BluetoothUUID +import org.simpleble.android.Peripheral +import org.simpleble.examples.android.viewmodels.BluetoothViewModel + +@Composable +fun ReadContent(bluetoothViewModel: BluetoothViewModel) { + var scanResults by remember { mutableStateOf(emptyList()) } + var isScanning by remember { mutableStateOf(false) } + var selectedDevice by remember { mutableStateOf(null) } + var isConnected by remember { mutableStateOf(false) } + var characteristics by remember { mutableStateOf(emptyList>()) } + var selectedCharacteristic by remember { mutableStateOf?>(null) } + var characteristicContent by remember { mutableStateOf(null) } + + LaunchedEffect(Unit) { + CoroutineScope(Dispatchers.Main).launch { + bluetoothViewModel.adapter.onScanActive.collect { + Log.d("SimpleBLE", "Scan active: $it") + isScanning = it + } + } + + CoroutineScope(Dispatchers.Main).launch { + bluetoothViewModel.adapter.onScanFound.collect { + Log.d("SimpleBLE", "Found device: ${it.identifier} [${it.address}] ${it.rssi} dBm") + scanResults = scanResults + it + } + } + } + + Column( + modifier = Modifier.fillMaxSize(), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center + ) { + Button( + onClick = { + if (!isScanning) { + CoroutineScope(Dispatchers.Main).launch { + scanResults = emptyList() + bluetoothViewModel.adapter.scanFor(5000) + } + } + }, + modifier = Modifier.padding(16.dp) + ) { + Text(text = if (isScanning) "Scanning..." else "Start Scan") + } + + if (scanResults.isNotEmpty()) { + Text( + text = "The following devices were found:", + style = MaterialTheme.typography.h6, + modifier = Modifier.padding(16.dp) + ) + + LazyColumn( + modifier = Modifier.fillMaxWidth(), + contentPadding = PaddingValues(16.dp) + ) { + items(scanResults.withIndex().toList()) { (index, peripheral) -> + Text( + text = "[$index] ${peripheral.identifier} [${peripheral.address}]", + style = MaterialTheme.typography.body1, + modifier = Modifier + .padding(8.dp) + .clickable { + selectedDevice = peripheral + } + ) + } + } + } else { + Text( + text = "No devices found.", + style = MaterialTheme.typography.body1, + modifier = Modifier.padding(16.dp) + ) + } + + selectedDevice?.let { peripheral -> + Text( + text = "Connecting to ${peripheral.identifier} [${peripheral.address}]", + style = MaterialTheme.typography.body1, + modifier = Modifier.padding(16.dp) + ) + + Button( + onClick = { + if (!isConnected) { + CoroutineScope(Dispatchers.Main).launch { + peripheral.connect() + isConnected = true + +// characteristics = peripheral.services.flatMap { service -> +// service.characteristics.map { characteristic -> +// Pair(service.uuid, characteristic.uuid) +// } +// } + } + } else { + CoroutineScope(Dispatchers.Main).launch { + peripheral.disconnect() + isConnected = false + characteristics = emptyList() + selectedCharacteristic = null + characteristicContent = null + } + } + }, + modifier = Modifier.padding(16.dp) + ) { + Text(text = if (isConnected) "Disconnect" else "Connect") + } + + if (isConnected) { + Text( + text = "Successfully connected, printing services and characteristics..", + style = MaterialTheme.typography.body1, + modifier = Modifier.padding(16.dp) + ) + + LazyColumn( + modifier = Modifier.fillMaxWidth(), + contentPadding = PaddingValues(16.dp) + ) { + items(characteristics.withIndex().toList()) { (index, characteristic) -> + Text( + text = "[$index] ${characteristic.first} ${characteristic.second}", + style = MaterialTheme.typography.body1, + modifier = Modifier + .padding(8.dp) + .clickable { + selectedCharacteristic = characteristic + } + ) + } + } + + selectedCharacteristic?.let { characteristic -> + Button( + onClick = { + CoroutineScope(Dispatchers.Main).launch { + repeat(5) { + val content = peripheral.read(characteristic.first, characteristic.second) + characteristicContent = content + Log.d("SimpleBLE", "Characteristic content: ${content.joinToString(separator = " ") { "%02x".format(it) }}") + delay(1000) + } + } + }, + modifier = Modifier.padding(16.dp) + ) { + Text(text = "Read Characteristic") + } + + characteristicContent?.let { content -> + Text( + text = "Characteristic content: ${content.joinToString(separator = " ") { "%02x".format(it) }}", + style = MaterialTheme.typography.body1, + modifier = Modifier.padding(16.dp) + ) + } + } + } + } + } +} \ No newline at end of file diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/src/main/java/org/simpleble/examples/android/views/ScanContent.kt b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/java/org/simpleble/examples/android/views/ScanContent.kt new file mode 100644 index 000000000..3253ce16c --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/java/org/simpleble/examples/android/views/ScanContent.kt @@ -0,0 +1,154 @@ +package org.simpleble.examples.android.views + +import android.util.Log +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.material.Button +import androidx.compose.material.MaterialTheme +import androidx.compose.material.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import org.simpleble.android.Adapter +import org.simpleble.android.Peripheral +import org.simpleble.examples.android.viewmodels.BluetoothViewModel + + +@Composable +fun ScanContent(bluetoothViewModel: BluetoothViewModel) { + var scanActive by remember { mutableStateOf(false) } + var scanResults by remember { mutableStateOf(emptyList()) } + + LaunchedEffect(Unit) { + CoroutineScope(Dispatchers.Main).launch { + bluetoothViewModel.adapter.onScanStart.collect { + Log.d("SimpleBLE", "Scan started.") + } + } + + CoroutineScope(Dispatchers.Main).launch { + bluetoothViewModel.adapter.onScanStop.collect { + Log.d("SimpleBLE", "Scan stopped.") + } + } + + CoroutineScope(Dispatchers.Main).launch { + bluetoothViewModel.adapter.onScanActive.collect { + Log.d("SimpleBLE", "Scan active: $it") + scanActive = it + } + } + + CoroutineScope(Dispatchers.Main).launch { + bluetoothViewModel.adapter.onScanFound.collect { + Log.d("SimpleBLE", "Found device: ${it.identifier} [${it.address}] ${it.rssi} dBm ${it.hashCode()}") + scanResults = scanResults + it + } + } + + CoroutineScope(Dispatchers.Main).launch { + bluetoothViewModel.adapter.onScanUpdated.collect { + Log.d("SimpleBLE", "Updated device: ${it.identifier} [${it.address}] ${it.rssi} dBm ${it.hashCode()}") + } + } + } + + Column( + modifier = Modifier.fillMaxSize(), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center + ) { + Button( + onClick = { + if (!bluetoothViewModel.adapter.scanIsActive) { + CoroutineScope(Dispatchers.Main).launch { + scanResults = emptyList() + bluetoothViewModel.adapter.scanFor(5000) + } + } + }, + modifier = Modifier.padding(16.dp) + ) { + Text(text = if (scanActive) "Scanning..." else "Start Scan") + } + + if (scanResults.isNotEmpty()) { + Text( + text = "The following devices were found:", + style = MaterialTheme.typography.h6, + modifier = Modifier.padding(16.dp) + ) + + LazyColumn( + modifier = Modifier.fillMaxWidth(), + contentPadding = PaddingValues(16.dp) + ) { + items(scanResults.withIndex().toList()) { (index, peripheral) -> + val connectableString = if (peripheral.isConnectable) "Connectable" else "Non-Connectable" + Text( + text = "[$index] ${peripheral.identifier} [${peripheral.address}] ${peripheral.rssi} dBm $connectableString", + style = MaterialTheme.typography.body1, + modifier = Modifier.padding(8.dp) + ) + Text( + text = "Tx Power: ${peripheral.txPower} dBm", + style = MaterialTheme.typography.body2, + modifier = Modifier.padding(start = 16.dp) + ) + Text( + text = "Address Type: ${peripheral.addressType}", + style = MaterialTheme.typography.body2, + modifier = Modifier.padding(start = 16.dp) + ) + +// peripheral.services.forEach { service -> +// Text( +// text = "Service UUID: ${service.uuid}", +// style = MaterialTheme.typography.body2, +// modifier = Modifier.padding(start = 16.dp) +// ) +// Text( +// text = "Service data: ${service.data}", +// style = MaterialTheme.typography.body2, +// modifier = Modifier.padding(start = 16.dp) +// ) +// } +// +// peripheral.manufacturerData.forEach { (manufacturerId, data) -> +// Text( +// text = "Manufacturer ID: $manufacturerId", +// style = MaterialTheme.typography.body2, +// modifier = Modifier.padding(start = 16.dp) +// ) +// Text( +// text = "Manufacturer data: $data", +// style = MaterialTheme.typography.body2, +// modifier = Modifier.padding(start = 16.dp) +// ) +// } + } + } + } else { + Text( + text = "No devices found.", + style = MaterialTheme.typography.body1, + modifier = Modifier.padding(16.dp) + ) + } + } +} \ No newline at end of file diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/drawable/ic_dashboard_black_24dp.xml b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/drawable/ic_dashboard_black_24dp.xml new file mode 100644 index 000000000..46fc8deec --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/drawable/ic_dashboard_black_24dp.xml @@ -0,0 +1,9 @@ + + + diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/drawable/ic_home_black_24dp.xml b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/drawable/ic_home_black_24dp.xml new file mode 100644 index 000000000..f8bb0b556 --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/drawable/ic_home_black_24dp.xml @@ -0,0 +1,9 @@ + + + diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/drawable/ic_launcher_background.xml b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/drawable/ic_launcher_background.xml new file mode 100644 index 000000000..07d5da9cb --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/drawable/ic_launcher_foreground.xml b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/drawable/ic_launcher_foreground.xml new file mode 100644 index 000000000..2b068d114 --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/drawable/ic_launcher_foreground.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/drawable/ic_notifications_black_24dp.xml b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/drawable/ic_notifications_black_24dp.xml new file mode 100644 index 000000000..78b75c39b --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/drawable/ic_notifications_black_24dp.xml @@ -0,0 +1,9 @@ + + + diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/layout/activity_main.xml b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/layout/activity_main.xml new file mode 100644 index 000000000..06ea6cae2 --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/layout/activity_main.xml @@ -0,0 +1,33 @@ + + + + + + + + \ No newline at end of file diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/layout/fragment_dashboard.xml b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/layout/fragment_dashboard.xml new file mode 100644 index 000000000..166ab0e9e --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/layout/fragment_dashboard.xml @@ -0,0 +1,22 @@ + + + + + \ No newline at end of file diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/layout/fragment_home.xml b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/layout/fragment_home.xml new file mode 100644 index 000000000..f3d9b08ff --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/layout/fragment_home.xml @@ -0,0 +1,22 @@ + + + + + \ No newline at end of file diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/layout/fragment_notifications.xml b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/layout/fragment_notifications.xml new file mode 100644 index 000000000..d41793572 --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/layout/fragment_notifications.xml @@ -0,0 +1,22 @@ + + + + + \ No newline at end of file diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/menu/bottom_nav_menu.xml b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/menu/bottom_nav_menu.xml new file mode 100644 index 000000000..fb6d040b9 --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/menu/bottom_nav_menu.xml @@ -0,0 +1,19 @@ + + + + + + + + + + \ No newline at end of file diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/mipmap-anydpi/ic_launcher.xml b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/mipmap-anydpi/ic_launcher.xml new file mode 100644 index 000000000..6f3b755bf --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/mipmap-anydpi/ic_launcher.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/mipmap-anydpi/ic_launcher_round.xml b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/mipmap-anydpi/ic_launcher_round.xml new file mode 100644 index 000000000..6f3b755bf --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/mipmap-anydpi/ic_launcher_round.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/mipmap-hdpi/ic_launcher.webp b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/mipmap-hdpi/ic_launcher.webp new file mode 100644 index 000000000..c209e78ec Binary files /dev/null and b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/mipmap-hdpi/ic_launcher.webp differ diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/mipmap-hdpi/ic_launcher_round.webp b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/mipmap-hdpi/ic_launcher_round.webp new file mode 100644 index 000000000..b2dfe3d1b Binary files /dev/null and b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/mipmap-hdpi/ic_launcher_round.webp differ diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/mipmap-mdpi/ic_launcher.webp b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/mipmap-mdpi/ic_launcher.webp new file mode 100644 index 000000000..4f0f1d64e Binary files /dev/null and b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/mipmap-mdpi/ic_launcher.webp differ diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/mipmap-mdpi/ic_launcher_round.webp b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/mipmap-mdpi/ic_launcher_round.webp new file mode 100644 index 000000000..62b611da0 Binary files /dev/null and b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/mipmap-mdpi/ic_launcher_round.webp differ diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/mipmap-xhdpi/ic_launcher.webp b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/mipmap-xhdpi/ic_launcher.webp new file mode 100644 index 000000000..948a3070f Binary files /dev/null and b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/mipmap-xhdpi/ic_launcher.webp differ diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/mipmap-xhdpi/ic_launcher_round.webp b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/mipmap-xhdpi/ic_launcher_round.webp new file mode 100644 index 000000000..1b9a6956b Binary files /dev/null and b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/mipmap-xhdpi/ic_launcher_round.webp differ diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/mipmap-xxhdpi/ic_launcher.webp b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/mipmap-xxhdpi/ic_launcher.webp new file mode 100644 index 000000000..28d4b77f9 Binary files /dev/null and b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/mipmap-xxhdpi/ic_launcher.webp differ diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/mipmap-xxhdpi/ic_launcher_round.webp b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/mipmap-xxhdpi/ic_launcher_round.webp new file mode 100644 index 000000000..9287f5083 Binary files /dev/null and b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/mipmap-xxhdpi/ic_launcher_round.webp differ diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/mipmap-xxxhdpi/ic_launcher.webp b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/mipmap-xxxhdpi/ic_launcher.webp new file mode 100644 index 000000000..aa7d6427e Binary files /dev/null and b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/mipmap-xxxhdpi/ic_launcher.webp differ diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/mipmap-xxxhdpi/ic_launcher_round.webp b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/mipmap-xxxhdpi/ic_launcher_round.webp new file mode 100644 index 000000000..9126ae37c Binary files /dev/null and b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/mipmap-xxxhdpi/ic_launcher_round.webp differ diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/navigation/mobile_navigation.xml b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/navigation/mobile_navigation.xml new file mode 100644 index 000000000..b82e5ff58 --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/navigation/mobile_navigation.xml @@ -0,0 +1,25 @@ + + + + + + + + + \ No newline at end of file diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/values-night/themes.xml b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/values-night/themes.xml new file mode 100644 index 000000000..8acd8e17c --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/values-night/themes.xml @@ -0,0 +1,16 @@ + + + + \ No newline at end of file diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/values/colors.xml b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/values/colors.xml new file mode 100644 index 000000000..f8c6127d3 --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/values/colors.xml @@ -0,0 +1,10 @@ + + + #FFBB86FC + #FF6200EE + #FF3700B3 + #FF03DAC5 + #FF018786 + #FF000000 + #FFFFFFFF + \ No newline at end of file diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/values/dimens.xml b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/values/dimens.xml new file mode 100644 index 000000000..e00c2dd14 --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/values/dimens.xml @@ -0,0 +1,5 @@ + + + 16dp + 16dp + \ No newline at end of file diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/values/strings.xml b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/values/strings.xml new file mode 100644 index 000000000..423362190 --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/values/strings.xml @@ -0,0 +1,6 @@ + + SimpleBLE Example + Home + Dashboard + Notifications + \ No newline at end of file diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/values/themes.xml b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/values/themes.xml new file mode 100644 index 000000000..3545288e1 --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/values/themes.xml @@ -0,0 +1,16 @@ + + + + \ No newline at end of file diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/xml/backup_rules.xml b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/xml/backup_rules.xml new file mode 100644 index 000000000..fa0f996d2 --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/xml/backup_rules.xml @@ -0,0 +1,13 @@ + + + + \ No newline at end of file diff --git a/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/xml/data_extraction_rules.xml b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/xml/data_extraction_rules.xml new file mode 100644 index 000000000..9ee9997b0 --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble-android/app/src/main/res_legacy/xml/data_extraction_rules.xml @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/third_party/SimpleBLE/examples/simpleble-android/build.gradle.kts b/third_party/SimpleBLE/examples/simpleble-android/build.gradle.kts new file mode 100644 index 000000000..a0985efc8 --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble-android/build.gradle.kts @@ -0,0 +1,5 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. +plugins { + alias(libs.plugins.androidApplication) apply false + alias(libs.plugins.jetbrainsKotlinAndroid) apply false +} \ No newline at end of file diff --git a/third_party/SimpleBLE/examples/simpleble-android/gradle.properties b/third_party/SimpleBLE/examples/simpleble-android/gradle.properties new file mode 100644 index 000000000..20e2a0152 --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble-android/gradle.properties @@ -0,0 +1,23 @@ +# Project-wide Gradle settings. +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. For more details, visit +# https://developer.android.com/r/tools/gradle-multi-project-decoupled-projects +# org.gradle.parallel=true +# AndroidX package structure to make it clearer which packages are bundled with the +# Android operating system, and which are packaged with your app's APK +# https://developer.android.com/topic/libraries/support-library/androidx-rn +android.useAndroidX=true +# Kotlin code style for this project: "official" or "obsolete": +kotlin.code.style=official +# Enables namespacing of each library's R class so that its R class includes only the +# resources declared in the library itself and none from the library's dependencies, +# thereby reducing the size of the R class for that library +android.nonTransitiveRClass=true \ No newline at end of file diff --git a/third_party/SimpleBLE/examples/simpleble-android/gradle/libs.versions.toml b/third_party/SimpleBLE/examples/simpleble-android/gradle/libs.versions.toml new file mode 100644 index 000000000..59aa62cc3 --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble-android/gradle/libs.versions.toml @@ -0,0 +1,29 @@ +[versions] +agp = "8.3.1" +kotlin = "1.9.23" +coreKtx = "1.12.0" +appcompat = "1.6.1" + +ui = "1.6.4" +foundation = "1.6.4" +material = "1.6.4" +activity-ktx = "1.8.2" +activity-compose = "1.8.2" + +[libraries] +androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" } +androidx-appcompat = { group = "androidx.appcompat", name = "appcompat", version.ref = "appcompat" } + +ui = { module = "androidx.compose.ui:ui", version.ref = "ui" } +ui-tooling = { module = "androidx.compose.ui:ui-tooling", version.ref = "ui" } +ui-tooling-preview = { module = "androidx.compose.ui:ui-tooling-preview", version.ref = "ui" } +foundation = { module = "androidx.compose.foundation:foundation", version.ref = "foundation" } +material = { module = "androidx.compose.material:material", version.ref = "material" } +activity-ktx = { module = "androidx.activity:activity-ktx", version.ref = "activity-ktx" } +activity-compose = { module = "androidx.activity:activity-compose", version.ref = "activity-compose" } + +[plugins] +androidApplication = { id = "com.android.application", version.ref = "agp" } +androidLibrary = { id = "com.android.library", version.ref = "agp" } +jetbrainsKotlinAndroid = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" } + diff --git a/third_party/SimpleBLE/examples/simpleble-android/gradle/wrapper/gradle-wrapper.jar b/third_party/SimpleBLE/examples/simpleble-android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..e708b1c02 Binary files /dev/null and b/third_party/SimpleBLE/examples/simpleble-android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/third_party/SimpleBLE/examples/simpleble-android/gradle/wrapper/gradle-wrapper.properties b/third_party/SimpleBLE/examples/simpleble-android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..7dc5fdd11 --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble-android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Sat Apr 27 08:22:16 PDT 2024 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/third_party/SimpleBLE/examples/simpleble-android/gradlew b/third_party/SimpleBLE/examples/simpleble-android/gradlew new file mode 100644 index 000000000..4f906e0c8 --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble-android/gradlew @@ -0,0 +1,185 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/third_party/SimpleBLE/examples/simpleble-android/gradlew.bat b/third_party/SimpleBLE/examples/simpleble-android/gradlew.bat new file mode 100644 index 000000000..107acd32c --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble-android/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/third_party/SimpleBLE/examples/simpleble-android/settings.gradle.kts b/third_party/SimpleBLE/examples/simpleble-android/settings.gradle.kts new file mode 100644 index 000000000..34e8a92b8 --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble-android/settings.gradle.kts @@ -0,0 +1,30 @@ +pluginManagement { + repositories { + google { + content { + includeGroupByRegex("com\\.android.*") + includeGroupByRegex("com\\.google.*") + includeGroupByRegex("androidx.*") + } + } + mavenCentral() + gradlePluginPortal() + } +} +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + } +} + +rootProject.name = "SimpleBLE Example" + +// NOTE: This is somewhat of a hack to consume simpledroidble directly from the source code +includeBuild("../../simpledroidble") { + dependencySubstitution { + substitute(module("org.simpleble.android:simpledroidble")).using(project(":simpledroidble")) + } +} +include(":app") \ No newline at end of file diff --git a/third_party/SimpleBLE/examples/simpleble/CMakeLists.txt b/third_party/SimpleBLE/examples/simpleble/CMakeLists.txt index 280d444cb..389e3d864 100644 --- a/third_party/SimpleBLE/examples/simpleble/CMakeLists.txt +++ b/third_party/SimpleBLE/examples/simpleble/CMakeLists.txt @@ -12,20 +12,28 @@ option(SIMPLEBLE_LOCAL "Use local SimpleBLE" ON) if (SIMPLEBLE_LOCAL) add_subdirectory(${CMAKE_CURRENT_LIST_DIR}/../../simpleble ${CMAKE_BINARY_DIR}/simpleble) else() + cmake_policy(SET CMP0144 OLD) # NOTE: This broke on older versions of CMake find_package(simpleble CONFIG REQUIRED) endif() # C++ add_subdirectory(cpp/list_adapters) +add_subdirectory(cpp/list_adapters_safe) add_subdirectory(cpp/scan) add_subdirectory(cpp/connect) add_subdirectory(cpp/connect_safe) +add_subdirectory(cpp/multiconnect) add_subdirectory(cpp/read) add_subdirectory(cpp/write) add_subdirectory(cpp/notify) add_subdirectory(cpp/notify_multi) # C -add_subdirectory(c/notify) -add_subdirectory(c/connect) -add_subdirectory(c/scan) +add_executable(example_connect_c c/connect.c) +target_link_libraries(example_connect_c simpleble::simpleble-c) + +add_executable(example_notify_c c/notify.c) +target_link_libraries(example_notify_c simpleble::simpleble-c) + +add_executable(example_scan_c c/scan.c) +target_link_libraries(example_scan_c simpleble::simpleble-c) diff --git a/third_party/SimpleBLE/examples/simpleble/c/connect/connect.c b/third_party/SimpleBLE/examples/simpleble/c/connect.c similarity index 100% rename from third_party/SimpleBLE/examples/simpleble/c/connect/connect.c rename to third_party/SimpleBLE/examples/simpleble/c/connect.c diff --git a/third_party/SimpleBLE/examples/simpleble/c/connect/CMakeLists.txt b/third_party/SimpleBLE/examples/simpleble/c/connect/CMakeLists.txt deleted file mode 100644 index 86add84cc..000000000 --- a/third_party/SimpleBLE/examples/simpleble/c/connect/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -cmake_minimum_required(VERSION 3.21) - -project(EXAMPLE_CONNECT_C) - -message("-- [INFO] Building Example") -add_executable(example_connect_c connect.c) -target_link_libraries(example_connect_c simpleble::simpleble-c) diff --git a/third_party/SimpleBLE/examples/simpleble/c/notify/notify.c b/third_party/SimpleBLE/examples/simpleble/c/notify.c similarity index 94% rename from third_party/SimpleBLE/examples/simpleble/c/notify/notify.c rename to third_party/SimpleBLE/examples/simpleble/c/notify.c index 300afb458..6fd7c4f84 100644 --- a/third_party/SimpleBLE/examples/simpleble/c/notify/notify.c +++ b/third_party/SimpleBLE/examples/simpleble/c/notify.c @@ -30,8 +30,8 @@ static void clean_on_exit(void); static void adapter_on_scan_start(simpleble_adapter_t adapter, void* userdata); static void adapter_on_scan_stop(simpleble_adapter_t adapter, void* userdata); static void adapter_on_scan_found(simpleble_adapter_t adapter, simpleble_peripheral_t peripheral, void* userdata); -static void peripheral_on_notify(simpleble_uuid_t service, simpleble_uuid_t characteristic, const uint8_t* data, - size_t data_length, void* userdata); +static void peripheral_on_notify(simpleble_peripheral_t handle, simpleble_uuid_t service, simpleble_uuid_t characteristic, + const uint8_t* data, size_t data_length, void* userdata); static service_characteristic_t characteristic_list[SERVICES_LIST_SIZE] = {0}; static simpleble_peripheral_t peripheral_list[PERIPHERAL_LIST_SIZE] = {0}; @@ -205,8 +205,8 @@ static void adapter_on_scan_found(simpleble_adapter_t adapter, simpleble_periphe simpleble_free(peripheral_address); } -static void peripheral_on_notify(simpleble_uuid_t service, simpleble_uuid_t characteristic, const uint8_t* data, - size_t data_length, void* userdata) { +static void peripheral_on_notify(simpleble_peripheral_t handle, simpleble_uuid_t service, simpleble_uuid_t characteristic, + const uint8_t* data, size_t data_length, void* userdata) { printf("Received: "); for (size_t i = 0; i < data_length; i++) { printf("%02X ", data[i]); diff --git a/third_party/SimpleBLE/examples/simpleble/c/notify/CMakeLists.txt b/third_party/SimpleBLE/examples/simpleble/c/notify/CMakeLists.txt deleted file mode 100644 index 7509a2b95..000000000 --- a/third_party/SimpleBLE/examples/simpleble/c/notify/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -cmake_minimum_required(VERSION 3.21) - -project(EXAMPLE_NOTIFY_C) - -message("-- [INFO] Building Example") -add_executable(example_notify_c notify.c) -target_link_libraries(example_notify_c simpleble::simpleble-c) diff --git a/third_party/SimpleBLE/examples/simpleble/c/scan/scan.c b/third_party/SimpleBLE/examples/simpleble/c/scan.c similarity index 63% rename from third_party/SimpleBLE/examples/simpleble/c/scan/scan.c rename to third_party/SimpleBLE/examples/simpleble/c/scan.c index 5626631d2..7d7f9a970 100644 --- a/third_party/SimpleBLE/examples/simpleble/c/scan/scan.c +++ b/third_party/SimpleBLE/examples/simpleble/c/scan.c @@ -10,6 +10,20 @@ #include "simpleble_c/simpleble.h" +static void print_buffer_hex(uint8_t* buf, size_t len, bool newline) { + for (size_t i = 0; i < len; i++) { + printf("%02X", buf[i]); + + if (i < (len - 1)) { + printf(" "); + } + } + + if (newline) { + printf("\n"); + } +} + static void adapter_on_scan_start(simpleble_adapter_t adapter, void* userdata); static void adapter_on_scan_stop(simpleble_adapter_t adapter, void* userdata); static void adapter_on_scan_found(simpleble_adapter_t adapter, simpleble_peripheral_t peripheral, void* userdata); @@ -43,6 +57,46 @@ int main() { // internal peripheral took longer to stop than anticipated. SLEEP_SEC(1); + size_t peripheral_count = simpleble_adapter_scan_get_results_count(adapter); + for (size_t peripheral_index = 0; peripheral_index < peripheral_count; peripheral_index++) { + simpleble_peripheral_t peripheral = simpleble_adapter_scan_get_results_handle(adapter, peripheral_index); + + char* peripheral_identifier = simpleble_peripheral_identifier(peripheral); + char* peripheral_address = simpleble_peripheral_address(peripheral); + + bool peripheral_connectable = false; + simpleble_peripheral_is_connectable(peripheral, &peripheral_connectable); + + int16_t peripheral_rssi = simpleble_peripheral_rssi(peripheral); + + printf("[%zu] %s [%s] %d dBm %s\n", peripheral_index, peripheral_identifier, peripheral_address, + peripheral_rssi, peripheral_connectable ? "Connectable" : "Non-Connectable"); + + size_t services_count = simpleble_peripheral_services_count(peripheral); + for (size_t service_index = 0; service_index < services_count; service_index++) { + simpleble_service_t service; + simpleble_peripheral_services_get(peripheral, service_index, &service); + + printf(" Service UUID: %s\n", service.uuid.value); + printf(" Service data: "); + print_buffer_hex(service.data, service.data_length, true); + } + + size_t manufacturer_data_count = simpleble_peripheral_manufacturer_data_count(peripheral); + for (size_t manuf_data_index = 0; manuf_data_index < manufacturer_data_count; manuf_data_index++) { + simpleble_manufacturer_data_t manuf_data; + simpleble_peripheral_manufacturer_data_get(peripheral, manuf_data_index, &manuf_data); + printf(" Manufacturer ID: %04X\n", manuf_data.manufacturer_id); + printf(" Manufacturer data: "); + print_buffer_hex(manuf_data.data, manuf_data.data_length, true); + } + + // Let's not forget to release the associated handles and memory + simpleble_peripheral_release_handle(peripheral); + simpleble_free(peripheral_address); + simpleble_free(peripheral_identifier); + } + // Let's not forget to release the associated handle. simpleble_adapter_release_handle(adapter); diff --git a/third_party/SimpleBLE/examples/simpleble/c/scan/CMakeLists.txt b/third_party/SimpleBLE/examples/simpleble/c/scan/CMakeLists.txt deleted file mode 100644 index bbd7bc5f2..000000000 --- a/third_party/SimpleBLE/examples/simpleble/c/scan/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -cmake_minimum_required(VERSION 3.21) - -project(EXAMPLE_SCAN_C) - -message("-- [INFO] Building Example") -add_executable(example_scan_c scan.c) -target_link_libraries(example_scan_c simpleble::simpleble-c) diff --git a/third_party/SimpleBLE/examples/simpleble/cpp/common/utils.cpp b/third_party/SimpleBLE/examples/simpleble/cpp/common/utils.cpp index 4304cd389..1173e213d 100644 --- a/third_party/SimpleBLE/examples/simpleble/cpp/common/utils.cpp +++ b/third_party/SimpleBLE/examples/simpleble/cpp/common/utils.cpp @@ -3,13 +3,6 @@ #include #include -void Utils::print_byte_array(const SimpleBLE::ByteArray& bytes) { - for (auto b : bytes) { - std::cout << std::hex << std::setfill('0') << std::setw(2) << (uint32_t)((uint8_t)b) << " "; - } - std::cout << std::endl; -} - std::optional Utils::getUserInputInt(const std::string& line, std::size_t max) { std::size_t ret; diff --git a/third_party/SimpleBLE/examples/simpleble/cpp/common/utils.hpp b/third_party/SimpleBLE/examples/simpleble/cpp/common/utils.hpp index ba84bea74..b9ccda754 100644 --- a/third_party/SimpleBLE/examples/simpleble/cpp/common/utils.hpp +++ b/third_party/SimpleBLE/examples/simpleble/cpp/common/utils.hpp @@ -22,10 +22,6 @@ std::optional getAdapter(); */ std::optional getUserInputInt(const std::string& line, std::size_t max); -/** - * @brief Pretty print a ByteArray - */ -void print_byte_array(const SimpleBLE::ByteArray& bytes); } // namespace Utils #endif diff --git a/third_party/SimpleBLE/examples/simpleble/cpp/connect/connect.cpp b/third_party/SimpleBLE/examples/simpleble/cpp/connect/connect.cpp index 5f1fa4d43..92ca530af 100644 --- a/third_party/SimpleBLE/examples/simpleble/cpp/connect/connect.cpp +++ b/third_party/SimpleBLE/examples/simpleble/cpp/connect/connect.cpp @@ -16,14 +16,19 @@ int main() { std::vector peripherals; - adapter.set_callback_on_scan_found([&](SimpleBLE::Peripheral peripheral) { peripherals.push_back(peripheral); }); + adapter.set_callback_on_scan_found([&](SimpleBLE::Peripheral peripheral) { + std::cout << "Found device: " << peripheral.identifier() << " [" << peripheral.address() << "]" << std::endl; + if (peripheral.is_connectable()) { + peripherals.push_back(peripheral); + } + }); adapter.set_callback_on_scan_start([]() { std::cout << "Scan started." << std::endl; }); adapter.set_callback_on_scan_stop([]() { std::cout << "Scan stopped." << std::endl; }); // Scan for 5 seconds and return. adapter.scan_for(5000); - std::cout << "The following devices were found:" << std::endl; + std::cout << "The following connectable devices were found:" << std::endl; for (size_t i = 0; i < peripherals.size(); i++) { std::cout << "[" << i << "] " << peripherals[i].identifier() << " [" << peripherals[i].address() << "]" << std::endl; diff --git a/third_party/SimpleBLE/examples/simpleble/cpp/connect_safe/connect_safe.cpp b/third_party/SimpleBLE/examples/simpleble/cpp/connect_safe/connect_safe.cpp index 965a6c989..a08e41d2c 100644 --- a/third_party/SimpleBLE/examples/simpleble/cpp/connect_safe/connect_safe.cpp +++ b/third_party/SimpleBLE/examples/simpleble/cpp/connect_safe/connect_safe.cpp @@ -9,7 +9,7 @@ int main() { auto adapter_list = SimpleBLE::Safe::Adapter::get_adapters(); if (!adapter_list.has_value()) { - std::cout << "Failed to " << std::endl; + std::cout << "Failed to list adapters" << std::endl; return EXIT_FAILURE; } diff --git a/third_party/SimpleBLE/examples/simpleble/cpp/list_adapters/list_adapters.cpp b/third_party/SimpleBLE/examples/simpleble/cpp/list_adapters/list_adapters.cpp index 33d9c1f9e..acfec00c6 100644 --- a/third_party/SimpleBLE/examples/simpleble/cpp/list_adapters/list_adapters.cpp +++ b/third_party/SimpleBLE/examples/simpleble/cpp/list_adapters/list_adapters.cpp @@ -1,8 +1,10 @@ #include #include "simpleble/Adapter.h" +#include "simpleble/Utils.h" int main() { + std::cout << "Using SimpleBLE version: " << SimpleBLE::get_simpleble_version() << std::endl; std::cout << "Bluetooth enabled: " << SimpleBLE::Adapter::bluetooth_enabled() << std::endl; auto adapter_list = SimpleBLE::Adapter::get_adapters(); @@ -14,8 +16,6 @@ int main() { for (auto& adapter : adapter_list) { std::cout << "Adapter: " << adapter.identifier() << " [" << adapter.address() << "]" << std::endl; - - adapter.underlying(); } return EXIT_SUCCESS; diff --git a/third_party/SimpleBLE/examples/simpleble/cpp/list_adapters_safe/CMakeLists.txt b/third_party/SimpleBLE/examples/simpleble/cpp/list_adapters_safe/CMakeLists.txt new file mode 100644 index 000000000..0b19c189e --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble/cpp/list_adapters_safe/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 3.21) + +project(EXAMPLE_LIST_ADAPTERS_SAFE) + +message("-- [INFO] Building Example") + +add_executable(example_list_adapters_safe + list_adapters_safe.cpp +) + +target_link_libraries(example_list_adapters_safe simpleble::simpleble) diff --git a/third_party/SimpleBLE/examples/simpleble/cpp/list_adapters_safe/list_adapters_safe.cpp b/third_party/SimpleBLE/examples/simpleble/cpp/list_adapters_safe/list_adapters_safe.cpp new file mode 100644 index 000000000..ca6a0399e --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble/cpp/list_adapters_safe/list_adapters_safe.cpp @@ -0,0 +1,33 @@ +#include + +#include "simpleble/AdapterSafe.h" + +int main() { + auto bluetooth_enabled = SimpleBLE::Safe::Adapter::bluetooth_enabled(); + + if (!bluetooth_enabled.has_value()) { + std::cout << "Failed to determine Bluetooth status" << std::endl; + return EXIT_FAILURE; + } + + std::cout << "Bluetooth enabled: " << bluetooth_enabled.value() << std::endl; + + auto adapter_list = SimpleBLE::Safe::Adapter::get_adapters(); + + if (!adapter_list.has_value()) { + std::cout << "Failed to list adapters" << std::endl; + return EXIT_FAILURE; + } + + if (adapter_list->empty()) { + std::cout << "No adapter found" << std::endl; + return EXIT_FAILURE; + } + + for (auto& adapter : *adapter_list) { + std::cout << "Adapter: " << adapter.identifier().value() << " [" << adapter.address().value() << "]" + << std::endl; + } + + return EXIT_SUCCESS; +} diff --git a/third_party/SimpleBLE/examples/simpleble/cpp/multiconnect/CMakeLists.txt b/third_party/SimpleBLE/examples/simpleble/cpp/multiconnect/CMakeLists.txt new file mode 100644 index 000000000..c49cfcc4a --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble/cpp/multiconnect/CMakeLists.txt @@ -0,0 +1,12 @@ +cmake_minimum_required(VERSION 3.21) + +project(EXAMPLE_MULTICONNECT) + +message("-- [INFO] Building Example") + +add_executable(example_multiconnect + multiconnect.cpp + ../common/utils.cpp +) + +target_link_libraries(example_multiconnect simpleble::simpleble) diff --git a/third_party/SimpleBLE/examples/simpleble/cpp/multiconnect/multiconnect.cpp b/third_party/SimpleBLE/examples/simpleble/cpp/multiconnect/multiconnect.cpp new file mode 100644 index 000000000..5da268993 --- /dev/null +++ b/third_party/SimpleBLE/examples/simpleble/cpp/multiconnect/multiconnect.cpp @@ -0,0 +1,60 @@ +#include +#include +#include +#include + +#include "../common/utils.hpp" + +#include "simpleble/SimpleBLE.h" + +using namespace std::chrono_literals; + +int main() { + auto adapter_optional = Utils::getAdapter(); + + if (!adapter_optional.has_value()) { + return EXIT_FAILURE; + } + + auto adapter = adapter_optional.value(); + + std::vector peripherals; + + adapter.set_callback_on_scan_found([&](SimpleBLE::Peripheral peripheral) { peripherals.push_back(peripheral); }); + + // Scan for 5 seconds and return. + adapter.scan_for(5000); + + std::cout << "The following devices were found:" << std::endl; + for (size_t i = 0; i < peripherals.size(); i++) { + std::cout << "[" << i << "] " << peripherals[i].identifier() << " [" << peripherals[i].address() << "]" + << std::endl; + } + + auto selection = Utils::getUserInputInt("Please select a device to connect to", peripherals.size() - 1); + if (!selection.has_value()) { + return EXIT_FAILURE; + } + + auto peripheral = peripherals[selection.value()]; + peripheral.set_callback_on_connected([]() { std::cout << "Connected callback triggered" << std::endl; }); + peripheral.set_callback_on_disconnected([]() { std::cout << "Disconnected callback triggered" << std::endl; }); + + std::cout << "Connecting to " << peripheral.identifier() << " [" << peripheral.address() << "]" << std::endl; + + for (size_t i = 0; i < 5; i++) { + try { + peripheral.connect(); + std::cout << "Successfully connected." << std::endl; + std::this_thread::sleep_for(2s); + + peripheral.disconnect(); + std::cout << "Successfully disconnected." << std::endl; + } catch (const std::exception& ex) { + std::cout << "Failed at " << i << " with: " << ex.what() << std::endl; + throw; + } + } + + return EXIT_SUCCESS; +} diff --git a/third_party/SimpleBLE/examples/simpleble/cpp/notify/notify.cpp b/third_party/SimpleBLE/examples/simpleble/cpp/notify/notify.cpp index 8937e1f13..8fa10cf24 100644 --- a/third_party/SimpleBLE/examples/simpleble/cpp/notify/notify.cpp +++ b/third_party/SimpleBLE/examples/simpleble/cpp/notify/notify.cpp @@ -23,7 +23,9 @@ int main() { adapter.set_callback_on_scan_found([&](SimpleBLE::Peripheral peripheral) { std::cout << "Found device: " << peripheral.identifier() << " [" << peripheral.address() << "]" << std::endl; - peripherals.push_back(peripheral); + if (peripheral.is_connectable()) { + peripherals.push_back(peripheral); + } }); adapter.set_callback_on_scan_start([]() { std::cout << "Scan started." << std::endl; }); @@ -68,10 +70,8 @@ int main() { } // Subscribe to the characteristic. - peripheral.notify(uuids[selection.value()].first, uuids[selection.value()].second, [&](SimpleBLE::ByteArray bytes) { - std::cout << "Received: "; - Utils::print_byte_array(bytes); - }); + peripheral.notify(uuids[selection.value()].first, uuids[selection.value()].second, + [&](SimpleBLE::ByteArray bytes) { std::cout << "Received: " << bytes << std::endl; }); std::this_thread::sleep_for(5s); diff --git a/third_party/SimpleBLE/examples/simpleble/cpp/notify_multi/notify_multi.cpp b/third_party/SimpleBLE/examples/simpleble/cpp/notify_multi/notify_multi.cpp index 88258e0ff..dfe366507 100644 --- a/third_party/SimpleBLE/examples/simpleble/cpp/notify_multi/notify_multi.cpp +++ b/third_party/SimpleBLE/examples/simpleble/cpp/notify_multi/notify_multi.cpp @@ -81,8 +81,7 @@ int main() { peripherals[iter].notify(uuids[selection.value()].first, uuids[selection.value()].second, [&, iter](SimpleBLE::ByteArray bytes) { if (print_allowed) { - std::cout << "Peripheral " << iter << " received: "; - Utils::print_byte_array(bytes); + std::cout << "Peripheral " << iter << " received: " << bytes << std::endl; } }); } diff --git a/third_party/SimpleBLE/examples/simpleble/cpp/read/read.cpp b/third_party/SimpleBLE/examples/simpleble/cpp/read/read.cpp index 14aa576fd..3406d856d 100644 --- a/third_party/SimpleBLE/examples/simpleble/cpp/read/read.cpp +++ b/third_party/SimpleBLE/examples/simpleble/cpp/read/read.cpp @@ -22,7 +22,9 @@ int main() { adapter.set_callback_on_scan_found([&](SimpleBLE::Peripheral peripheral) { std::cout << "Found device: " << peripheral.identifier() << " [" << peripheral.address() << "]" << std::endl; - peripherals.push_back(peripheral); + if (peripheral.is_connectable()) { + peripherals.push_back(peripheral); + } }); adapter.set_callback_on_scan_start([]() { std::cout << "Scan started." << std::endl; }); @@ -70,8 +72,7 @@ int main() { // Attempt to read the characteristic 5 times in 5 seconds. for (size_t i = 0; i < 5; i++) { SimpleBLE::ByteArray rx_data = peripheral.read(uuids[selection.value()].first, uuids[selection.value()].second); - std::cout << "Characteristic content is: "; - Utils::print_byte_array(rx_data); + std::cout << "Characteristic content is: " << rx_data << std::endl; std::this_thread::sleep_for(1s); } diff --git a/third_party/SimpleBLE/examples/simpleble/cpp/scan/scan.cpp b/third_party/SimpleBLE/examples/simpleble/cpp/scan/scan.cpp index d4fb30a22..baae68ffc 100644 --- a/third_party/SimpleBLE/examples/simpleble/cpp/scan/scan.cpp +++ b/third_party/SimpleBLE/examples/simpleble/cpp/scan/scan.cpp @@ -26,7 +26,9 @@ int main() { }); adapter.set_callback_on_scan_start([]() { std::cout << "Scan started." << std::endl; }); + adapter.set_callback_on_scan_stop([]() { std::cout << "Scan stopped." << std::endl; }); + // Scan for 5 seconds. adapter.scan_for(5000); @@ -36,20 +38,24 @@ int main() { std::cout << "The following devices were found:" << std::endl; for (size_t i = 0; i < peripherals.size(); i++) { std::string connectable_string = peripherals[i].is_connectable() ? "Connectable" : "Non-Connectable"; - std::string peripheral_string = peripherals[i].identifier() + " [" + peripherals[i].address() + "]"; + std::string peripheral_string = peripherals[i].identifier() + " [" + peripherals[i].address() + "] " + + std::to_string(peripherals[i].rssi()) + " dBm"; std::cout << "[" << i << "] " << peripheral_string << " " << connectable_string << std::endl; + std::cout << " Tx Power: " << std::dec << peripherals[i].tx_power() << " dBm" << std::endl; + std::cout << " Address Type: " << peripherals[i].address_type() << std::endl; + std::vector services = peripherals[i].services(); for (auto& service : services) { - std::cout << " Service: " << service.uuid() << std::endl; + std::cout << " Service UUID: " << service.uuid() << std::endl; + std::cout << " Service data: " << service.data() << std::endl; } std::map manufacturer_data = peripherals[i].manufacturer_data(); for (auto& [manufacturer_id, data] : manufacturer_data) { std::cout << " Manufacturer ID: " << manufacturer_id << std::endl; - std::cout << " Manufacturer data: "; - Utils::print_byte_array(data); + std::cout << " Manufacturer data: " << data << std::endl; } } return EXIT_SUCCESS; diff --git a/third_party/SimpleBLE/examples/simpleble/cpp/write/write.cpp b/third_party/SimpleBLE/examples/simpleble/cpp/write/write.cpp index 443c4eacd..2c3b9394e 100644 --- a/third_party/SimpleBLE/examples/simpleble/cpp/write/write.cpp +++ b/third_party/SimpleBLE/examples/simpleble/cpp/write/write.cpp @@ -19,7 +19,9 @@ int main() { adapter.set_callback_on_scan_found([&](SimpleBLE::Peripheral peripheral) { std::cout << "Found device: " << peripheral.identifier() << " [" << peripheral.address() << "]" << std::endl; - peripherals.push_back(peripheral); + if (peripheral.is_connectable()) { + peripherals.push_back(peripheral); + } }); adapter.set_callback_on_scan_start([]() { std::cout << "Scan started." << std::endl; }); @@ -67,10 +69,12 @@ int main() { return EXIT_FAILURE; } + SimpleBLE::ByteArray bytes = SimpleBLE::ByteArray::fromHex(contents); + // NOTE: Alternatively, `write_command` can be used to write to a characteristic too. // `write_request` is for unacknowledged writes. // `write_command` is for acknowledged writes. - peripheral.write_request(uuids[selection.value()].first, uuids[selection.value()].second, contents); + peripheral.write_request(uuids[selection.value()].first, uuids[selection.value()].second, bytes); peripheral.disconnect(); return EXIT_SUCCESS; diff --git a/third_party/SimpleBLE/examples/simplebluez/scan/scan.cpp b/third_party/SimpleBLE/examples/simplebluez/scan/scan.cpp index 322ba659d..be45bf8d7 100644 --- a/third_party/SimpleBLE/examples/simplebluez/scan/scan.cpp +++ b/third_party/SimpleBLE/examples/simplebluez/scan/scan.cpp @@ -53,7 +53,9 @@ int main(int argc, char* argv[]) { adapter->set_on_device_updated([](std::shared_ptr device) { std::cout << "Update received for " << device->address() << std::endl; std::cout << "\tName " << device->name() << std::endl; + std::cout << "\tAddress Type " << device->address_type() << std::endl; std::cout << "\tRSSI " << std::dec << device->rssi() << std::endl; + std::cout << "\tTxPower " << std::dec << device->tx_power() << std::endl; auto manufacturer_data = device->manufacturer_data(); for (auto& [manufacturer_id, value_array] : manufacturer_data) { std::cout << "\tManuf ID 0x" << std::setfill('0') << std::setw(4) << std::hex << (int)manufacturer_id; diff --git a/third_party/SimpleBLE/examples/simplepyble/connect.py b/third_party/SimpleBLE/examples/simplepyble/connect.py index 78ef3e515..9cad11d18 100644 --- a/third_party/SimpleBLE/examples/simplepyble/connect.py +++ b/third_party/SimpleBLE/examples/simplepyble/connect.py @@ -42,4 +42,7 @@ for characteristic in service.characteristics(): print(f" Characteristic: {characteristic.uuid()}") + capabilities = " ".join(characteristic.capabilities()) + print(f" Capabilities: {capabilities}") + peripheral.disconnect() diff --git a/third_party/SimpleBLE/examples/simplepyble/list_adapters.py b/third_party/SimpleBLE/examples/simplepyble/list_adapters.py index 595b0573d..f7bf14246 100644 --- a/third_party/SimpleBLE/examples/simplepyble/list_adapters.py +++ b/third_party/SimpleBLE/examples/simplepyble/list_adapters.py @@ -1,6 +1,8 @@ import simplepyble if __name__ == "__main__": + print(f"Running on {simplepyble.get_operating_system()}") + adapters = simplepyble.Adapter.get_adapters() if len(adapters) == 0: diff --git a/third_party/SimpleBLE/examples/simplepyble/scan.py b/third_party/SimpleBLE/examples/simplepyble/scan.py index e152ad968..8c7a2c3eb 100644 --- a/third_party/SimpleBLE/examples/simplepyble/scan.py +++ b/third_party/SimpleBLE/examples/simplepyble/scan.py @@ -28,8 +28,15 @@ for peripheral in peripherals: connectable_str = "Connectable" if peripheral.is_connectable() else "Non-Connectable" print(f"{peripheral.identifier()} [{peripheral.address()}] - {connectable_str}") + print(f' Address Type: {peripheral.address_type()}') + print(f' Tx Power: {peripheral.tx_power()} dBm') manufacturer_data = peripheral.manufacturer_data() for manufacturer_id, value in manufacturer_data.items(): print(f" Manufacturer ID: {manufacturer_id}") print(f" Manufacturer data: {value}") + + services = peripheral.services() + for service in services: + print(f" Service UUID: {service.uuid()}") + print(f" Service data: {service.data()}") diff --git a/third_party/SimpleBLE/examples/simplersble/Cargo.lock b/third_party/SimpleBLE/examples/simplersble/Cargo.lock new file mode 100644 index 000000000..e4ac13503 --- /dev/null +++ b/third_party/SimpleBLE/examples/simplersble/Cargo.lock @@ -0,0 +1,190 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "cc" +version = "1.0.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50d30906286121d95be3d479533b458f87493b30a4b5f79a607db8f5d11aa91f" + +[[package]] +name = "cmake" +version = "0.1.49" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db34956e100b30725f2eb215f90d4871051239535632f84fea3bc92722c66b7c" +dependencies = [ + "cc", +] + +[[package]] +name = "codespan-reporting" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3538270d33cc669650c4b093848450d380def10c331d38c768e34cac80576e6e" +dependencies = [ + "termcolor", + "unicode-width", +] + +[[package]] +name = "cxx" +version = "1.0.89" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc831ee6a32dd495436e317595e639a587aa9907bef96fe6e6abc290ab6204e9" +dependencies = [ + "cc", + "cxxbridge-flags", + "cxxbridge-macro", + "link-cplusplus", +] + +[[package]] +name = "cxx-build" +version = "1.0.89" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94331d54f1b1a8895cd81049f7eaaaef9d05a7dcb4d1fd08bf3ff0806246789d" +dependencies = [ + "cc", + "codespan-reporting", + "once_cell", + "proc-macro2", + "quote", + "scratch", + "syn", +] + +[[package]] +name = "cxxbridge-flags" +version = "1.0.89" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48dcd35ba14ca9b40d6e4b4b39961f23d835dbb8eed74565ded361d93e1feb8a" + +[[package]] +name = "cxxbridge-macro" +version = "1.0.89" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81bbeb29798b407ccd82a3324ade1a7286e0d29851475990b612670f6f5124d2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "link-cplusplus" +version = "1.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecd207c9c713c34f95a097a5b029ac2ce6010530c7b49d7fea24d977dede04f5" +dependencies = [ + "cc", +] + +[[package]] +name = "once_cell" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f61fba1741ea2b3d6a1e3178721804bb716a68a6aeba1149b5d52e3d464ea66" + +[[package]] +name = "proc-macro2" +version = "1.0.50" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ef7d57beacfaf2d8aee5937dab7b7f28de3cb8b1828479bb5de2a7106f2bae2" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8856d8364d252a14d474036ea1358d63c9e6965c8e5c1885c18f73d70bff9c7b" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "scratch" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddccb15bcce173023b3fedd9436f882a0739b8dfb45e4f6b6002bee5929f61b2" + +[[package]] +name = "simplersble" +version = "0.6.0" +dependencies = [ + "cmake", + "cxx", + "cxx-build", +] + +[[package]] +name = "simplersble-examples" +version = "0.0.0" +dependencies = [ + "simplersble", +] + +[[package]] +name = "syn" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f4064b5b16e03ae50984a5a8ed5d4f8803e6bc1fd170a3cda91a1be4b18e3f5" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "termcolor" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be55cf8942feac5c765c2c993422806843c9a9a45d4d5c407ad6dd2ea95eb9b6" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "unicode-ident" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84a22b9f218b40614adcb3f4ff08b703773ad44fa9423e4e0d346d5db86e4ebc" + +[[package]] +name = "unicode-width" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0edd1e5b14653f783770bce4a4dabb4a5108a5370a5f5d8cfe8710c361f6c8b" + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" +dependencies = [ + "winapi", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/third_party/SimpleBLE/examples/simplersble/Cargo.toml b/third_party/SimpleBLE/examples/simplersble/Cargo.toml new file mode 100644 index 000000000..fd9a57907 --- /dev/null +++ b/third_party/SimpleBLE/examples/simplersble/Cargo.toml @@ -0,0 +1,19 @@ +[package] +edition = "2021" +name = "simplersble-examples" +version = "0.0.0" + +[[bin]] +name = "list_adapters" + +[[bin]] +name = "scan" + +[[bin]] +name = "connect" + +[[bin]] +name = "notify" + +[dependencies] +simplersble = { path = "../.." } \ No newline at end of file diff --git a/third_party/SimpleBLE/external/include/external/kvn_bytearray.h b/third_party/SimpleBLE/external/include/external/kvn_bytearray.h new file mode 100644 index 000000000..ac1fa991d --- /dev/null +++ b/third_party/SimpleBLE/external/include/external/kvn_bytearray.h @@ -0,0 +1,200 @@ +#ifndef KVN_BYTEARRAY_H +#define KVN_BYTEARRAY_H + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace kvn { + +/** + * @class bytearray + * @brief A class to handle byte arrays and their conversion from/to hex strings. + */ +class bytearray { + public: + /** + * @brief Default constructor. + */ + bytearray() = default; + + /** + * @brief Constructs byte array from a vector of uint8_t. + * @param vec A vector of uint8_t. + */ + bytearray(const std::vector& vec) : data_(vec) {} + + /** + * @brief Constructs byte array from a raw pointer and size. + * @param ptr A pointer to uint8_t data. + * @param size The size of the data. + */ + bytearray(const uint8_t* ptr, size_t size) : data_(ptr, ptr + size) {} + + /** + * @brief Constructs byte array from a std::string. + * @param byteArr A string containing byte data. + */ + bytearray(const std::string& byteArr) : data_(byteArr.begin(), byteArr.end()) {} + + /** + * @brief Constructs byte array from a C-style string and size. + * @param byteArr A C-style string. + * @param size The size of the string. + */ + bytearray(const char* byteArr, size_t size) : bytearray(std::string(byteArr, size)) {} + + /** + * @brief Constructs byte array from a C-style string. + * @param byteArr A C-style string. + */ + bytearray(const char* byteArr) : bytearray(std::string(byteArr)) {} + + /** + * @brief Creates a ByteArray from a hex string. + * + * Case is ignored and the string may have a '0x' hex prefix or not. + * + * @param hexStr A string containing hex data. + * @return A ByteArray object. + * @throws std::invalid_argument If the hex string contains non-hexadecimal characters. + * @throws std::length_error If the hex string length is not even. + */ + static bytearray fromHex(const std::string& hexStr) { + std::string cleanString(hexStr); + + // Check and skip the '0x' prefix if present + if (cleanString.size() >= 2 && cleanString.substr(0, 2) == "0x") { + cleanString = cleanString.substr(2); + } + + size_t size = cleanString.size(); + if (size % 2 != 0) { + throw std::length_error("Hex string length must be even."); + } + + bytearray byteArray; + byteArray.data_.reserve(size / 2); + + for (size_t i = 0; i < size; i += 2) { + uint8_t byte = static_cast(std::stoi(cleanString.substr(i, 2), nullptr, 16)); + byteArray.data_.push_back(byte); + } + + return byteArray; + } + + /** + * @overload + */ + static bytearray fromHex(const char* byteArr) { return fromHex(std::string(byteArr)); } + + /** + * @overload + */ + static bytearray fromHex(const char* byteArr, size_t size) { return fromHex(std::string(byteArr, size)); } + + /** + * @brief Converts the byte array to a lowercase hex string without '0x' prefix. + * @param spacing Whether to include spaces between bytes. + * + * @return A hex string representation of the byte array. + */ + std::string toHex(bool spacing = false) const { + std::ostringstream oss; + for (auto byte : data_) { + oss << std::hex << std::setw(2) << std::setfill('0') << static_cast(byte); + if (spacing) { + oss << " "; + } + } + return oss.str(); + } + + /** + * @brief Slices the byte array from a specified start index to an end index. + * + * This method creates a new byte array containing bytes from the specified range. + * The start index is inclusive, while the end index is exclusive. + * + * @param start The starting index from which to begin slicing. + * @param end The ending index up to which to slice (exclusive). + * @return byte array A new byte array containing the sliced segment. + * @throws std::out_of_range If the start index is greater than the end index or if the end index is out of bounds. + */ + bytearray slice(size_t start, size_t end) const { + if (start > end || end > data_.size()) { + throw std::out_of_range("Invalid slice range"); + } + return bytearray(std::vector(data_.begin() + start, data_.begin() + end)); + } + + /** + * @brief Slices the byte array from a specified start index to the end of the array. + * + * This method creates a new byte array containing all bytes from the specified start index to the end of the + * byte array. + * + * @param start The starting index from which to begin slicing. + * @return byte array A new byte array containing the sliced segment from the start index to the end. + * @throws std::out_of_range If the start index is out of the bounds of the byte array. + */ + bytearray slice_from(size_t start) const { return slice(start, data_.size()); } + + /** + * @brief Slices the byte array from the beginning to a specified end index. + * + * This method creates a new byte array containing all bytes from the beginning of the byte array to the specified + * end index. + * + * @param end The ending index up to which to slice (exclusive). + * @return byte array A new byte array containing the sliced segment from the beginning to the end index. + * @throws std::out_of_range If the end index is out of the bounds of the byte array. + */ + bytearray slice_to(size_t end) const { return slice(0, end); } + + /** + * @brief Overloaded stream insertion operator for byte array. + * @param os The output stream. + * @param byteArray The byte array object. + * @return The output stream. + */ + friend std::ostream& operator<<(std::ostream& os, const bytearray& byteArray) { + os << byteArray.toHex(true); + return os; + } + + /** + * @brief Conversion operator to convert byte array to std::string. + * + * @note This is provided to support code that relies on byte array + * being representd as a string. + * @return String containing the raw bytes of the byte array + */ + operator std::string() const { return std::string(data_.begin(), data_.end()); } + + //! @cond Doxygen_Suppress + // Expose vector-like functionality + size_t size() const { return data_.size(); } + const uint8_t* data() const { return data_.data(); } + bool empty() const { return data_.empty(); } + void clear() { data_.clear(); } + uint8_t& operator[](size_t index) { return data_[index]; } + const uint8_t& operator[](size_t index) const { return data_[index]; } + void push_back(uint8_t byte) { data_.push_back(byte); } + auto begin() const { return data_.begin(); } + auto end() const { return data_.end(); } + //! @endcond + + private: + std::vector data_; +}; + +} // namespace kvn + +#endif // KVN_BYTEARRAY_H \ No newline at end of file diff --git a/third_party/SimpleBLE/simplepyble/pyproject.toml b/third_party/SimpleBLE/pyproject.toml similarity index 55% rename from third_party/SimpleBLE/simplepyble/pyproject.toml rename to third_party/SimpleBLE/pyproject.toml index 0d8138c90..33ef92d8f 100644 --- a/third_party/SimpleBLE/simplepyble/pyproject.toml +++ b/third_party/SimpleBLE/pyproject.toml @@ -1,8 +1,8 @@ [build-system] requires = [ - "setuptools", - "wheel", - "ninja", + "setuptools>=42", + "scikit-build", + "ninja; platform_system!='Windows'", "cmake>=3.21", "pybind11", ] diff --git a/third_party/SimpleBLE/simplepyble/setup.py b/third_party/SimpleBLE/setup.py similarity index 54% rename from third_party/SimpleBLE/simplepyble/setup.py rename to third_party/SimpleBLE/setup.py index 2dd35991a..db3ca3d9a 100644 --- a/third_party/SimpleBLE/simplepyble/setup.py +++ b/third_party/SimpleBLE/setup.py @@ -1,30 +1,45 @@ +import argparse +import os import pathlib import sys -import setuptools -import argparse + +import pybind11 +import skbuild + + +def exclude_unnecessary_files(cmake_manifest): + def is_necessary(name): + is_necessary = ( + name.endswith(".so") + or name.endswith(".dylib") + or name.endswith("py") + or name.endswith("pyd") + ) + print(f"Parsing file: {name} - {is_necessary}") + return is_necessary + + return list(filter(is_necessary, cmake_manifest)) + argparser = argparse.ArgumentParser(add_help=False) -argparser.add_argument('--plain', help='Use Plain SimpleBLE', required=False, action='store_true') +argparser.add_argument( + "--plain", help="Use Plain SimpleBLE", required=False, action="store_true" +) args, unknown = argparser.parse_known_args() sys.argv = [sys.argv[0]] + unknown -here = pathlib.Path(__file__).parent.resolve() -root = here.parent.resolve() - -# Include our vendorized copy of cmake-build-extension, at least until -# https://github.com/diegoferigo/cmake-build-extension/pull/35 is merged. -sys.path.insert(0, str(here)) -import cmake_build_extension +root = pathlib.Path(__file__).parent.resolve() # Generate the version string # TODO: Make the dev portion smarter by looking at tags. version_str = (root / "VERSION").read_text(encoding="utf-8").strip() -version_str += ".dev0" # ! Ensure it matches the intended release version! +version_str += ".dev0" # ! Ensure it matches the intended release version! # Get the long description from the README file -long_description = (here / "README.rst").read_text(encoding="utf-8") +long_description = (root / "simplepyble" / "README.rst").read_text(encoding="utf-8") cmake_options = [] +cmake_options.append(f"-Dpybind11_DIR={pybind11.get_cmake_dir()}") if sys.platform == "win32": cmake_options.append("-DCMAKE_SYSTEM_VERSION=10.0.19041.0") elif sys.platform.startswith("darwin"): @@ -35,9 +50,12 @@ if args.plain: cmake_options.append("-DSIMPLEBLE_PLAIN=ON") +if 'PIWHEELS_BUILD' in os.environ: + cmake_options.append("-DLIBFMT_VENDORIZE=OFF") + # The information here can also be placed in setup.cfg - better separation of # logic and declaration, and simpler if you include description/version in a file. -setuptools.setup( +skbuild.setup( name="simplepyble", version=version_str, author="Kevin Dewald", @@ -45,34 +63,27 @@ url="https://github.com/OpenBluetoothToolbox/SimpleBLE", description="The ultimate fully-fledged cross-platform BLE library, designed for simplicity and ease of use.", long_description=long_description, - long_description_content_type='text/x-rst', - ext_modules=[ - cmake_build_extension.CMakeExtension( - name="simplepyble", - disable_editable=True, - source_dir=here, - cmake_depends_on=["pybind11"], - cmake_configure_options=cmake_options, - cmake_generator=None, - ) - ], - cmdclass={ - "build_ext": cmake_build_extension.BuildExtension - }, - zip_safe=False, - install_requires=[ - "wheel", + long_description_content_type="text/x-rst", + packages=["simplepyble"], + package_dir={"": "simplepyble/src"}, + cmake_source_dir="simplepyble", + cmake_args=cmake_options, + cmake_process_manifest_hook=exclude_unnecessary_files, + cmake_install_dir="simplepyble/src/simplepyble", + setup_requires=[ + "setuptools>=42", + "scikit-build", + "ninja; platform_system!='Windows'", + "cmake>=3.21", "pybind11", - "ninja" - ], - test_requires=[ - "pytest", ], + install_requires=[], extras_require={}, platforms="Windows, macOS, Linux", python_requires=">=3.7", classifiers=[ - "License :: OSI Approved :: MIT License", + "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", + "License :: Other/Proprietary License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", diff --git a/third_party/SimpleBLE/simpleble/CMakeLists.txt b/third_party/SimpleBLE/simpleble/CMakeLists.txt index ad8a70fca..3f205d313 100644 --- a/third_party/SimpleBLE/simpleble/CMakeLists.txt +++ b/third_party/SimpleBLE/simpleble/CMakeLists.txt @@ -2,25 +2,30 @@ cmake_minimum_required(VERSION 3.21) include(${CMAKE_CURRENT_SOURCE_DIR}/../cmake/prelude.cmake) -project(SimpleBLE VERSION 0.1 LANGUAGES CXX) +project( + simpleble + VERSION ${SIMPLEBLE_VERSION} + DESCRIPTION "The ultimate fully-fledged cross-platform library for Bluetooth Low Energy (BLE)." + HOMEPAGE_URL "https://github.com/OpenBluetoothToolbox/SimpleBLE" + LANGUAGES CXX +) -if(APPLE) +if (APPLE) SET(SIMPLEBLE-C simpleble-c) SET(FILE_NAME "libsimpleble-c.dylib") -elseif(UNIX) +elseif (UNIX) SET(SIMPLEBLE-C simpleble-c) SET(FILE_NAME "libsimpleble-c.so") -else() - if(CMAKE_SIZEOF_VOID_P EQUAL 8) +else () + if(CMAKE_SIZEOF_VOID_P EQUAL 8) SET(SIMPLEBLE-C simpleble-c) SET(FILE_NAME "simpleble-c.dll") else(CMAKE_SIZEOF_VOID_P EQUAL 8) SET(SIMPLEBLE-C simpleble-c32) SET(FILE_NAME "simpleble-c32.dll") endif(CMAKE_SIZEOF_VOID_P EQUAL 8) -endif(APPLE) +endif (APPLE) -# Run prelude script to set up environment include(${CMAKE_CURRENT_SOURCE_DIR}/../cmake/epilogue.cmake) include(GenerateExportHeader) @@ -29,6 +34,14 @@ include(GNUInstallDirs) option(SIMPLEBLE_PLAIN "Use plain version of SimpleBLE" OFF) add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/../../fmt ${CMAKE_CURRENT_BINARY_DIR}/libfmt) +#if(NOT TARGET fmt::fmt-header-only) +# option(LIBFMT_VENDORIZE "Enable vendorized libfmt" ON) +# find_package(fmt REQUIRED) + +# if(TARGET fmt) +# set_target_properties(fmt PROPERTIES EXCLUDE_FROM_ALL TRUE) +# endif() +#endif() if(SIMPLEBLE_TEST) message(STATUS "Building tests requires plain version of SimpleBLE") @@ -41,7 +54,8 @@ set(SIMPLEBLE_PRIVATE_INCLUDES ${CMAKE_CURRENT_SOURCE_DIR}/src/builders ${CMAKE_CURRENT_SOURCE_DIR}/src/external ${CMAKE_CURRENT_SOURCE_DIR}/src/backends/common - ${CMAKE_CURRENT_SOURCE_DIR}/src/frontends/safe) + ${CMAKE_CURRENT_SOURCE_DIR}/src/frontends/safe + ${CMAKE_CURRENT_SOURCE_DIR}/../external/include) set(SIMPLEBLE_SRC ${CMAKE_CURRENT_SOURCE_DIR}/src/frontends/base/Adapter.cpp @@ -71,12 +85,16 @@ set(SIMPLEBLE_C_SRC ${CMAKE_CURRENT_SOURCE_DIR}/src_c/simpleble.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src_c/adapter.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src_c/peripheral.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/src_c/utils.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/src_c/logging.cpp) + ${CMAKE_CURRENT_SOURCE_DIR}/src_c/logging.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/src_c/utils.cpp) # Define targets add_library(simpleble ${SIMPLEBLE_SRC}) -add_library(${SIMPLEBLE-C} SHARED ${SIMPLEBLE_C_SRC}) +# BrainFlow: convert to shared library +add_library(${SIMPLEBLE-C} SHARED ${SIMPLEBLE_C_SRC}) + +add_library(simpleble::simpleble ALIAS simpleble) +add_library(simpleble::simpleble-c ALIAS ${SIMPLEBLE-C}) set_target_properties(simpleble PROPERTIES CXX_VISIBILITY_PRESET hidden @@ -88,7 +106,11 @@ set_target_properties(simpleble PROPERTIES VERSION "${PROJECT_VERSION}" SOVERSION "${PROJECT_VERSION_MAJOR}" EXPORT_NAME simpleble - OUTPUT_NAME simpleble) + OUTPUT_NAME simpleble + RELEASE_POSTFIX "" + RELWITHDEBINFO_POSTFIX "-relwithdebinfo" + MINSIZEREL_POSTFIX "-minsizerel" + DEBUG_POSTFIX "-debug") set_target_properties(${SIMPLEBLE-C} PROPERTIES C_VISIBILITY_PRESET hidden @@ -100,13 +122,22 @@ set_target_properties(${SIMPLEBLE-C} PROPERTIES DEFINE_SYMBOL simpleble_EXPORTS # Use the same symbol as simpleble ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/../../../compiled LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/../../../compiled - RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/../../../compiled) - -generate_export_header( - simpleble - BASE_NAME simpleble - EXPORT_FILE_NAME export/simpleble/export.h -) + RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/../../../compiled + VERSION "${PROJECT_VERSION}" + SOVERSION "${PROJECT_VERSION_MAJOR}" + EXPORT_NAME ${SIMPLEBLE-C} + OUTPUT_NAME ${SIMPLEBLE-C} + RELEASE_POSTFIX "" + RELWITHDEBINFO_POSTFIX "-relwithdebinfo" + MINSIZEREL_POSTFIX "-minsizerel" + DEBUG_POSTFIX "-debug") + +# BrainFlow, no need for header +#generate_export_header( +# simpleble +# BASE_NAME simpleble +# EXPORT_FILE_NAME export/simpleble/export.h +#) # Configure include directories target_include_directories(simpleble PRIVATE ${SIMPLEBLE_PRIVATE_INCLUDES}) @@ -114,6 +145,7 @@ target_include_directories(${SIMPLEBLE-C} PRIVATE ${SIMPLEBLE_PRIVATE_INCLUDES}) target_include_directories(simpleble INTERFACE $ + $ $) target_include_directories(${SIMPLEBLE-C} INTERFACE $ @@ -128,14 +160,16 @@ target_include_directories(${SIMPLEBLE-C} SYSTEM PUBLIC # Configure linked libraries target_link_libraries(simpleble PRIVATE $) target_link_libraries(${SIMPLEBLE-C} PRIVATE $) -target_link_libraries(${SIMPLEBLE-C} PRIVATE simpleble) +target_link_libraries(${SIMPLEBLE-C} PRIVATE simpleble::simpleble) + +append_sanitize_options("${SIMPLEBLE_SANITIZE}") if(NOT SIMPLEBLE_LOG_LEVEL) -set(SIMPLEBLE_LOG_LEVEL "INFO") + set(SIMPLEBLE_LOG_LEVEL "INFO") endif() -list(APPEND PRIVATE_COMPILE_DEFINITIONS SIMPLEBLE_LOG_LEVEL=SIMPLEBLE_LOG_LEVEL_${SIMPLEBLE_LOG_LEVEL}) -append_sanitize_options("${SIMPLEBLE_SANITIZE}") +list(APPEND PRIVATE_COMPILE_DEFINITIONS SIMPLEBLE_LOG_LEVEL=SIMPLEBLE_LOG_LEVEL_${SIMPLEBLE_LOG_LEVEL}) +list(APPEND PRIVATE_COMPILE_DEFINITIONS SIMPLEBLE_VERSION="${PROJECT_VERSION}") # Detect the operating system and load the necessary dependencies if(SIMPLEBLE_PLAIN) @@ -164,6 +198,10 @@ elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux") list(APPEND PRIVATE_COMPILE_DEFINITIONS SIMPLEDBUS_LOG_LEVEL=${SIMPLEDBUS_LOG_LEVEL}) list(APPEND PRIVATE_COMPILE_DEFINITIONS SIMPLEBLUEZ_LOG_LEVEL=${SIMPLEBLUEZ_LOG_LEVEL}) + if(SIMPLEBLE_USE_SESSION_DBUS) + list(APPEND PRIVATE_COMPILE_DEFINITIONS SIMPLEBLUEZ_USE_SESSION_DBUS) + endif() + target_sources(simpleble PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/backends/linux/AdapterBase.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/backends/linux/PeripheralBase.cpp @@ -211,6 +249,7 @@ elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux") ${CMAKE_CURRENT_SOURCE_DIR}/../simpledbus/include ${CMAKE_CURRENT_SOURCE_DIR}/src/backends/linux) + set_property(TARGET simpleble PROPERTY INSTALL_RPATH $ORIGIN) set_property(TARGET ${SIMPLEBLE-C} PROPERTY INSTALL_RPATH $ORIGIN) elseif (CMAKE_SYSTEM_NAME STREQUAL "Windows") @@ -226,8 +265,12 @@ elseif (CMAKE_SYSTEM_NAME STREQUAL "Windows") # /D_USE_MATH_DEFINES -> Specifies that the math.h header file should be included. list(APPEND PRIVATE_COMPILE_DEFINITIONS "/D_USE_MATH_DEFINES") + # /utf-8 -> Set source and executable character sets to utf-8. https://learn.microsoft.com/en-us/cpp/build/reference/utf-8-set-source-and-executable-character-sets-to-utf-8 + list(APPEND PRIVATE_COMPILE_OPTIONS "/utf-8") # /Gd -> Use __cdecl as the default calling convention. https://docs.microsoft.com/en-us/cpp/cpp/cdecl list(APPEND PRIVATE_COMPILE_OPTIONS "/Gd") + # /EHsc -> Use the standard C++ exception handling model. https://learn.microsoft.com/en-us/cpp/build/reference/eh-exception-handling-model + list(APPEND PRIVATE_COMPILE_OPTIONS "/EHsc") # /WX -> Treats all warnings as errors. list(APPEND PRIVATE_COMPILE_OPTIONS "/WX") # /W1 -> Use the lowest level of warnings, as there are some unsafe functions that MSVC doesn't like. @@ -235,7 +278,8 @@ elseif (CMAKE_SYSTEM_NAME STREQUAL "Windows") list(APPEND PRIVATE_COMPILE_OPTIONS "/W1") endif() - target_include_directories(simpleble PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/backends/windows) + target_include_directories(simpleble PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/src/backends/windows) target_sources(simpleble PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/backends/windows/AdapterBase.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/backends/windows/PeripheralBase.cpp @@ -247,7 +291,8 @@ elseif(CMAKE_SYSTEM_NAME STREQUAL "Darwin" OR CMAKE_SYSTEM_NAME STREQUAL "iOS") list(APPEND PRIVATE_COMPILE_OPTIONS -fobjc-arc) target_link_libraries(simpleble PUBLIC "-framework Foundation" "-framework CoreBluetooth" ObjC) - target_include_directories(simpleble PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/backends/macos) + target_include_directories(simpleble PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/src/backends/macos) target_sources(simpleble PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/backends/macos/Utils.mm ${CMAKE_CURRENT_SOURCE_DIR}/src/backends/macos/AdapterBase.mm @@ -255,10 +300,44 @@ elseif(CMAKE_SYSTEM_NAME STREQUAL "Darwin" OR CMAKE_SYSTEM_NAME STREQUAL "iOS") ${CMAKE_CURRENT_SOURCE_DIR}/src/backends/macos/PeripheralBase.mm ${CMAKE_CURRENT_SOURCE_DIR}/src/backends/macos/PeripheralBaseMacOS.mm) + set_property(TARGET simpleble PROPERTY INSTALL_RPATH @loader_path) set_property(TARGET ${SIMPLEBLE-C} PROPERTY INSTALL_RPATH @loader_path) -else() - message(FATAL_ERROR "-- [ERROR] UNSUPPORTED SYSTEM: ${CMAKE_HOST_SYSTEM_NAME} ${CMAKE_SYSTEM_NAME}") +elseif(CMAKE_SYSTEM_NAME STREQUAL "Android") + message(STATUS "Configuring for Android") + + # Set the include directories for the Android NDK headers and other necessary directories + include_directories(${ANDROID_NDK}/sysroot/usr/include) + include_directories(${CMAKE_CURRENT_SOURCE_DIR}/src/backends/android) + + # Add any necessary compile definitions or options for Android + add_compile_options(-DANDROID -D__ANDROID_API__=${ANDROID_NATIVE_API_LEVEL}) + + # Specify the source files for the Android backend + # NOTE: These files have been commented out and replaced by the PLAIN version in order to develop the Android wrapper code. + target_include_directories(simpleble PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/src/backends/android) + target_sources(simpleble PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/src/backends/android/AdapterBase.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/src/backends/android/PeripheralBase.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/src/backends/android/android/BluetoothDevice.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/src/backends/android/android/BluetoothGatt.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/src/backends/android/android/BluetoothGattService.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/src/backends/android/android/BluetoothGattCharacteristic.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/src/backends/android/android/BluetoothGattDescriptor.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/src/backends/android/android/UUID.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/src/backends/android/android/ScanResult.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/src/backends/android/bridge/BluetoothGattCallback.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/src/backends/android/bridge/ScanCallback.cpp + ) + + target_include_directories(simpleble PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/src/backends/plain) + + target_link_libraries(simpleble PUBLIC + android + nativehelper + log) endif() apply_build_options(simpleble @@ -273,6 +352,42 @@ apply_build_options(${SIMPLEBLE-C} "${PRIVATE_LINK_OPTIONS}" "${PUBLIC_LINK_OPTIONS}") +configure_file(${CMAKE_CURRENT_SOURCE_DIR}/cmake/simpleble.pc.in + ${CMAKE_CURRENT_BINARY_DIR}/simpleble.pc @ONLY) + +# BrainFlow does not install simpleble +#install( +# TARGETS simpleble ${SIMPLEBLE-C} +# EXPORT simpleble-config +# ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} +# LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} +# RUNTIME DESTINATION ${CMAKE_INSTALL_LIBDIR}) # BrainFlow output to libdir + +#install( +# EXPORT simpleble-config +# NAMESPACE simpleble:: +# DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/simpleble) + +#install( +# DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/include/simpleble/ +# DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/simpleble) + +#install( +# DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/../external/include/ +# DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/simpleble) + +#install( +# DIRECTORY ${PROJECT_BINARY_DIR}/export/simpleble/ +# DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/simpleble) + +#install( +# DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/include/simpleble_c/ +# DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/simpleble_c) + +#install( +# FILES ${CMAKE_CURRENT_BINARY_DIR}/simpleble.pc +# DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig) + if(SIMPLEBLE_TEST) message(STATUS "Building Tests") find_package(GTest REQUIRED) @@ -280,6 +395,7 @@ if(SIMPLEBLE_TEST) add_executable(simpleble_test ${CMAKE_CURRENT_SOURCE_DIR}/test/src/main.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test/src/test_utils.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/test/src/test_bytearray.cpp ) set_target_properties(simpleble_test PROPERTIES @@ -289,11 +405,12 @@ if(SIMPLEBLE_TEST) POSITION_INDEPENDENT_CODE ON WINDOWS_EXPORT_ALL_SYMBOLS ON) - target_link_libraries(simpleble_test PRIVATE simpleble GTest::gtest) + target_link_libraries(simpleble_test PRIVATE simpleble::simpleble GTest::gtest) endif() + if (MSVC) - add_custom_command (TARGET ${SIMPLEBLE-C} POST_BUILD + add_custom_command(TARGET ${SIMPLEBLE-C} POST_BUILD COMMAND "${CMAKE_COMMAND}" -E copy_if_different "${CMAKE_CURRENT_SOURCE_DIR}/../../../compiled/$/${FILE_NAME}" "${CMAKE_CURRENT_SOURCE_DIR}/../../../python_package/brainflow/lib/${FILE_NAME}" COMMAND "${CMAKE_COMMAND}" -E copy_if_different "${CMAKE_CURRENT_SOURCE_DIR}/../../../compiled/$/${FILE_NAME}" "${CMAKE_CURRENT_SOURCE_DIR}/../../../java_package/brainflow/src/main/resources/${FILE_NAME}" COMMAND "${CMAKE_COMMAND}" -E copy_if_different "${CMAKE_CURRENT_SOURCE_DIR}/../../../compiled/$/${FILE_NAME}" "${CMAKE_CURRENT_SOURCE_DIR}/../../../csharp_package/brainflow/brainflow/lib/${FILE_NAME}" @@ -304,7 +421,7 @@ if (MSVC) ) endif (MSVC) if (UNIX AND NOT ANDROID) - add_custom_command (TARGET ${SIMPLEBLE-C} POST_BUILD + add_custom_command(TARGET ${SIMPLEBLE-C} POST_BUILD COMMAND "${CMAKE_COMMAND}" -E copy_if_different "${CMAKE_CURRENT_SOURCE_DIR}/../../../compiled/${FILE_NAME}" "${CMAKE_CURRENT_SOURCE_DIR}/../../../python_package/brainflow/lib/${FILE_NAME}" COMMAND "${CMAKE_COMMAND}" -E copy_if_different "${CMAKE_CURRENT_SOURCE_DIR}/../../../compiled/${FILE_NAME}" "${CMAKE_CURRENT_SOURCE_DIR}/../../../julia_package/brainflow/lib/${FILE_NAME}" COMMAND "${CMAKE_COMMAND}" -E copy_if_different "${CMAKE_CURRENT_SOURCE_DIR}/../../../compiled/${FILE_NAME}" "${CMAKE_CURRENT_SOURCE_DIR}/../../../java_package/brainflow/src/main/resources/${FILE_NAME}" @@ -316,16 +433,16 @@ if (UNIX AND NOT ANDROID) endif (UNIX AND NOT ANDROID) if (MSVC) - install ( + install( FILES ${CMAKE_CURRENT_SOURCE_DIR}/../../../compiled/$/${FILE_NAME} DESTINATION lib ) endif (MSVC) if (UNIX AND NOT ANDROID) - install ( + install( FILES ${CMAKE_CURRENT_SOURCE_DIR}/../../../compiled/${FILE_NAME} DESTINATION lib ) -endif (UNIX AND NOT ANDROID) +endif (UNIX AND NOT ANDROID) \ No newline at end of file diff --git a/third_party/SimpleBLE/simpleble/include/simpleble/Adapter.h b/third_party/SimpleBLE/simpleble/include/simpleble/Adapter.h index 9575e01af..f8ddfe8da 100644 --- a/third_party/SimpleBLE/simpleble/include/simpleble/Adapter.h +++ b/third_party/SimpleBLE/simpleble/include/simpleble/Adapter.h @@ -5,8 +5,6 @@ #include #include -#include - #include #include #include @@ -15,7 +13,7 @@ namespace SimpleBLE { class AdapterBase; -class SIMPLEBLE_EXPORT Adapter { +class Adapter { public: Adapter() = default; virtual ~Adapter() = default; diff --git a/third_party/SimpleBLE/simpleble/include/simpleble/AdapterSafe.h b/third_party/SimpleBLE/simpleble/include/simpleble/AdapterSafe.h index 00a2a59ce..8e766e5bf 100644 --- a/third_party/SimpleBLE/simpleble/include/simpleble/AdapterSafe.h +++ b/third_party/SimpleBLE/simpleble/include/simpleble/AdapterSafe.h @@ -1,7 +1,5 @@ #pragma once -#include - #include #include @@ -9,7 +7,7 @@ namespace SimpleBLE { namespace Safe { -class SIMPLEBLE_EXPORT Adapter : public SimpleBLE::Adapter { +class Adapter : public SimpleBLE::Adapter { public: Adapter(SimpleBLE::Adapter& adapter); virtual ~Adapter() = default; diff --git a/third_party/SimpleBLE/simpleble/include/simpleble/Characteristic.h b/third_party/SimpleBLE/simpleble/include/simpleble/Characteristic.h index e9692322e..da60b9812 100644 --- a/third_party/SimpleBLE/simpleble/include/simpleble/Characteristic.h +++ b/third_party/SimpleBLE/simpleble/include/simpleble/Characteristic.h @@ -2,8 +2,6 @@ #include -#include - #include #include #include @@ -12,7 +10,7 @@ namespace SimpleBLE { class CharacteristicBase; -class SIMPLEBLE_EXPORT Characteristic { +class Characteristic { public: Characteristic() = default; virtual ~Characteristic() = default; diff --git a/third_party/SimpleBLE/simpleble/include/simpleble/Descriptor.h b/third_party/SimpleBLE/simpleble/include/simpleble/Descriptor.h index 5fd1cff20..65e0f8a7d 100644 --- a/third_party/SimpleBLE/simpleble/include/simpleble/Descriptor.h +++ b/third_party/SimpleBLE/simpleble/include/simpleble/Descriptor.h @@ -2,8 +2,6 @@ #include -#include - #include #include @@ -11,7 +9,7 @@ namespace SimpleBLE { class DescriptorBase; -class SIMPLEBLE_EXPORT Descriptor { +class Descriptor { public: Descriptor() = default; virtual ~Descriptor() = default; diff --git a/third_party/SimpleBLE/simpleble/include/simpleble/Exceptions.h b/third_party/SimpleBLE/simpleble/include/simpleble/Exceptions.h index b20d6047f..6ddfc3550 100644 --- a/third_party/SimpleBLE/simpleble/include/simpleble/Exceptions.h +++ b/third_party/SimpleBLE/simpleble/include/simpleble/Exceptions.h @@ -3,66 +3,64 @@ #include #include -#include - #include "Types.h" namespace SimpleBLE { namespace Exception { -class SIMPLEBLE_EXPORT BaseException : public std::runtime_error { +class BaseException : public std::runtime_error { public: BaseException(const std::string& __arg) : std::runtime_error(__arg) {} }; -class SIMPLEBLE_EXPORT NotInitialized : public BaseException { +class NotInitialized : public BaseException { public: NotInitialized(); }; -class SIMPLEBLE_EXPORT NotConnected : public BaseException { +class NotConnected : public BaseException { public: NotConnected(); }; -class SIMPLEBLE_EXPORT InvalidReference : public BaseException { +class InvalidReference : public BaseException { public: InvalidReference(); }; -class SIMPLEBLE_EXPORT ServiceNotFound : public BaseException { +class ServiceNotFound : public BaseException { public: ServiceNotFound(BluetoothUUID uuid); }; -class SIMPLEBLE_EXPORT CharacteristicNotFound : public BaseException { +class CharacteristicNotFound : public BaseException { public: CharacteristicNotFound(BluetoothUUID uuid); }; -class SIMPLEBLE_EXPORT DescriptorNotFound : public BaseException { +class DescriptorNotFound : public BaseException { public: DescriptorNotFound(BluetoothUUID uuid); }; -class SIMPLEBLE_EXPORT OperationNotSupported : public BaseException { +class OperationNotSupported : public BaseException { public: OperationNotSupported(); }; -class SIMPLEBLE_EXPORT OperationFailed : public BaseException { +class OperationFailed : public BaseException { public: OperationFailed(); OperationFailed(const std::string& err_msg); }; -class SIMPLEBLE_EXPORT WinRTException : public BaseException { +class WinRTException : public BaseException { public: WinRTException(int32_t err_code, const std::string& err_msg); }; -class SIMPLEBLE_EXPORT CoreBluetoothException : public BaseException { +class CoreBluetoothException : public BaseException { public: CoreBluetoothException(const std::string& err_msg); }; diff --git a/third_party/SimpleBLE/simpleble/include/simpleble/Logging.h b/third_party/SimpleBLE/simpleble/include/simpleble/Logging.h index 84a3f7c93..e517657fe 100644 --- a/third_party/SimpleBLE/simpleble/include/simpleble/Logging.h +++ b/third_party/SimpleBLE/simpleble/include/simpleble/Logging.h @@ -5,8 +5,6 @@ #include #include -#include - namespace SimpleBLE { namespace Logging { @@ -25,7 +23,7 @@ enum Level : int { using Callback = std::function; // clang-format on -class SIMPLEBLE_EXPORT Logger { +class Logger { public: static Logger* get(); diff --git a/third_party/SimpleBLE/simpleble/include/simpleble/Peripheral.h b/third_party/SimpleBLE/simpleble/include/simpleble/Peripheral.h index 594627aaa..3917c997b 100644 --- a/third_party/SimpleBLE/simpleble/include/simpleble/Peripheral.h +++ b/third_party/SimpleBLE/simpleble/include/simpleble/Peripheral.h @@ -7,8 +7,6 @@ #include #include -#include - #include #include #include @@ -17,7 +15,7 @@ namespace SimpleBLE { class PeripheralBase; -class SIMPLEBLE_EXPORT Peripheral { +class Peripheral { public: Peripheral() = default; virtual ~Peripheral() = default; diff --git a/third_party/SimpleBLE/simpleble/include/simpleble/PeripheralSafe.h b/third_party/SimpleBLE/simpleble/include/simpleble/PeripheralSafe.h index 1a6f86e9e..6d40ced85 100644 --- a/third_party/SimpleBLE/simpleble/include/simpleble/PeripheralSafe.h +++ b/third_party/SimpleBLE/simpleble/include/simpleble/PeripheralSafe.h @@ -2,8 +2,6 @@ #include -#include - #include #include @@ -11,7 +9,7 @@ namespace SimpleBLE { namespace Safe { -class SIMPLEBLE_EXPORT Peripheral : public SimpleBLE::Peripheral { +class Peripheral : public SimpleBLE::Peripheral { public: Peripheral(SimpleBLE::Peripheral& peripheral); virtual ~Peripheral() = default; diff --git a/third_party/SimpleBLE/simpleble/include/simpleble/Service.h b/third_party/SimpleBLE/simpleble/include/simpleble/Service.h index 32f0230e9..09bcea04a 100644 --- a/third_party/SimpleBLE/simpleble/include/simpleble/Service.h +++ b/third_party/SimpleBLE/simpleble/include/simpleble/Service.h @@ -3,8 +3,6 @@ #include #include -#include - #include #include #include "simpleble/Characteristic.h" @@ -13,7 +11,7 @@ namespace SimpleBLE { class ServiceBase; -class SIMPLEBLE_EXPORT Service { +class Service { public: Service() = default; virtual ~Service() = default; diff --git a/third_party/SimpleBLE/simpleble/include/simpleble/Types.h b/third_party/SimpleBLE/simpleble/include/simpleble/Types.h index fe67c08b9..e68efdb92 100644 --- a/third_party/SimpleBLE/simpleble/include/simpleble/Types.h +++ b/third_party/SimpleBLE/simpleble/include/simpleble/Types.h @@ -3,6 +3,12 @@ #include #include #include +#include "external/kvn_bytearray.h" + +/** + * @file Types.h + * @brief Defines types and enumerations used throughout the SimpleBLE library. + */ namespace SimpleBLE { @@ -12,9 +18,11 @@ using BluetoothAddress = std::string; // returns the same string, but provides a homogeneous interface. using BluetoothUUID = std::string; -// IDEA: Extend ByteArray to be constructed by a vector of bytes -// and pointers to uint8_t. -using ByteArray = std::string; +/** + * @typedef ByteArray + * @brief Represents a byte array using kvn::bytearray from the external library. + */ +using ByteArray = kvn::bytearray; enum class OperatingSystem { WINDOWS, @@ -22,6 +30,7 @@ enum class OperatingSystem { LINUX, }; +// TODO: Add to_string functions for all enums. enum BluetoothAddressType : int32_t { PUBLIC = 0, RANDOM = 1, UNSPECIFIED = 2 }; } // namespace SimpleBLE diff --git a/third_party/SimpleBLE/simpleble/include/simpleble/Utils.h b/third_party/SimpleBLE/simpleble/include/simpleble/Utils.h index f270b7f8e..889e6fad7 100644 --- a/third_party/SimpleBLE/simpleble/include/simpleble/Utils.h +++ b/third_party/SimpleBLE/simpleble/include/simpleble/Utils.h @@ -1,13 +1,11 @@ #pragma once -#include - #include namespace SimpleBLE { -OperatingSystem SIMPLEBLE_EXPORT get_operating_system(); +OperatingSystem get_operating_system(); -std::string SIMPLEBLE_EXPORT get_simpleble_version(); +std::string get_simpleble_version(); } // namespace SimpleBLE diff --git a/third_party/SimpleBLE/simpleble/include/simpleble_c/adapter.h b/third_party/SimpleBLE/simpleble/include/simpleble_c/adapter.h index a479c74c1..c47bea816 100644 --- a/third_party/SimpleBLE/simpleble/include/simpleble_c/adapter.h +++ b/third_party/SimpleBLE/simpleble/include/simpleble_c/adapter.h @@ -4,8 +4,6 @@ #include #include -#include - #include #ifdef _WIN32 diff --git a/third_party/SimpleBLE/simpleble/include/simpleble_c/logging.h b/third_party/SimpleBLE/simpleble/include/simpleble_c/logging.h index 0cee8ab00..de2b57bb5 100644 --- a/third_party/SimpleBLE/simpleble/include/simpleble_c/logging.h +++ b/third_party/SimpleBLE/simpleble/include/simpleble_c/logging.h @@ -2,8 +2,6 @@ #include -#include - #ifdef _WIN32 #define SHARED_EXPORT __declspec(dllexport) #define CALLING_CONVENTION __cdecl diff --git a/third_party/SimpleBLE/simpleble/include/simpleble_c/peripheral.h b/third_party/SimpleBLE/simpleble/include/simpleble_c/peripheral.h index e20c3574f..8372681d3 100644 --- a/third_party/SimpleBLE/simpleble/include/simpleble_c/peripheral.h +++ b/third_party/SimpleBLE/simpleble/include/simpleble_c/peripheral.h @@ -4,8 +4,6 @@ #include #include -#include - #include #ifdef _WIN32 @@ -228,11 +226,11 @@ SHARED_EXPORT simpleble_err_t CALLING_CONVENTION simpleble_peripheral_write_comm * @param callback * @return simpleble_err_t */ -SHARED_EXPORT simpleble_err_t CALLING_CONVENTION -simpleble_peripheral_notify(simpleble_peripheral_t handle, simpleble_uuid_t service, simpleble_uuid_t characteristic, - void (*callback)(simpleble_uuid_t service, simpleble_uuid_t characteristic, - const uint8_t* data, size_t data_length, void* userdata), - void* userdata); +SHARED_EXPORT simpleble_err_t CALLING_CONVENTION simpleble_peripheral_notify( + simpleble_peripheral_t handle, simpleble_uuid_t service, simpleble_uuid_t characteristic, + void (*callback)(simpleble_peripheral_t handle, simpleble_uuid_t service, simpleble_uuid_t characteristic, + const uint8_t* data, size_t data_length, void* userdata), + void* userdata); /** * @brief @@ -243,11 +241,11 @@ simpleble_peripheral_notify(simpleble_peripheral_t handle, simpleble_uuid_t serv * @param callback * @return simpleble_err_t */ -SHARED_EXPORT simpleble_err_t CALLING_CONVENTION -simpleble_peripheral_indicate(simpleble_peripheral_t handle, simpleble_uuid_t service, simpleble_uuid_t characteristic, - void (*callback)(simpleble_uuid_t service, simpleble_uuid_t characteristic, - const uint8_t* data, size_t data_length, void* userdata), - void* userdata); +SHARED_EXPORT simpleble_err_t CALLING_CONVENTION simpleble_peripheral_indicate( + simpleble_peripheral_t handle, simpleble_uuid_t service, simpleble_uuid_t characteristic, + void (*callback)(simpleble_peripheral_t handle, simpleble_uuid_t service, simpleble_uuid_t characteristic, + const uint8_t* data, size_t data_length, void* userdata), + void* userdata); /** * @brief diff --git a/third_party/SimpleBLE/simpleble/include/simpleble_c/simpleble.h b/third_party/SimpleBLE/simpleble/include/simpleble_c/simpleble.h index 626e4263a..8f3692f4d 100644 --- a/third_party/SimpleBLE/simpleble/include/simpleble_c/simpleble.h +++ b/third_party/SimpleBLE/simpleble/include/simpleble_c/simpleble.h @@ -1,6 +1,5 @@ #pragma once -#include #include #include diff --git a/third_party/SimpleBLE/simpleble/include/simpleble_c/utils.h b/third_party/SimpleBLE/simpleble/include/simpleble_c/utils.h index e72864e2a..ea598a5d7 100644 --- a/third_party/SimpleBLE/simpleble/include/simpleble_c/utils.h +++ b/third_party/SimpleBLE/simpleble/include/simpleble_c/utils.h @@ -1,7 +1,5 @@ #pragma once -#include - #include #ifdef _WIN32 diff --git a/third_party/SimpleBLE/simpleble/src/Utils.cpp b/third_party/SimpleBLE/simpleble/src/Utils.cpp index c6a45319c..45e2a5b23 100644 --- a/third_party/SimpleBLE/simpleble/src/Utils.cpp +++ b/third_party/SimpleBLE/simpleble/src/Utils.cpp @@ -12,6 +12,6 @@ OperatingSystem get_operating_system() { #endif } -std::string get_simpleble_version() { return "0.6.1"; } +std::string get_simpleble_version() { return SIMPLEBLE_VERSION; } } // namespace SimpleBLE \ No newline at end of file diff --git a/third_party/SimpleBLE/simpleble/src/backends/android/AdapterBase.cpp b/third_party/SimpleBLE/simpleble/src/backends/android/AdapterBase.cpp new file mode 100644 index 000000000..4b2da7414 --- /dev/null +++ b/third_party/SimpleBLE/simpleble/src/backends/android/AdapterBase.cpp @@ -0,0 +1,167 @@ +#include "AdapterBase.h" +#include "CommonUtils.h" +#include "PeripheralBase.h" +#include "PeripheralBuilder.h" + +#include +#include +#include +#include +#include +#include + +using namespace SimpleBLE; + +JNI::Class AdapterBase::_btAdapterCls; +JNI::Class AdapterBase::_btScanResultCls; + +JNI::Object AdapterBase::_btAdapter; +JNI::Object AdapterBase::_btScanner; + +void AdapterBase::initialize() { + JNI::Env env; + + // Check if the BluetoothAdapter class has been loaded + if (_btAdapterCls.get() == nullptr) { + _btAdapterCls = env.find_class("android/bluetooth/BluetoothAdapter"); + } + + if (_btScanResultCls.get() == nullptr) { + _btScanResultCls = env.find_class("android/bluetooth/le/ScanResult"); + } + + if (_btAdapter.get() == nullptr) { + _btAdapter = _btAdapterCls.call_static_method( "getDefaultAdapter", "()Landroid/bluetooth/BluetoothAdapter;"); + } + + if (_btScanner.get() == nullptr) { + _btScanner = _btAdapter.call_object_method("getBluetoothLeScanner", "()Landroid/bluetooth/le/BluetoothLeScanner;"); + } + +} + +std::vector> AdapterBase::get_adapters() { + initialize(); + + // Create an instance of AdapterBase and add it to the vector + std::shared_ptr adapter = std::make_shared(); + std::vector> adapters; + adapters.push_back(adapter); + + return adapters; +} + +bool AdapterBase::bluetooth_enabled() { + initialize(); + + bool isEnabled = _btAdapter.call_boolean_method("isEnabled", "()Z"); + int bluetoothState = _btAdapter.call_int_method("getState", "()I"); + __android_log_write(ANDROID_LOG_INFO, "SimpleBLE", fmt::format("Bluetooth state: {}", bluetoothState).c_str()); + + return isEnabled; //bluetoothState == 12; +} + +AdapterBase::AdapterBase() { + _btScanCallback.set_callback_onScanResult([this](Android::ScanResult scan_result) { + std::string address = scan_result.getDevice().getAddress(); + + if (this->peripherals_.count(address) == 0) { + // If the incoming peripheral has never been seen before, create and save a reference to it. + auto base_peripheral = std::make_shared(scan_result); + this->peripherals_.insert(std::make_pair(address, base_peripheral)); + } + + // Update the received advertising data. + auto base_peripheral = this->peripherals_.at(address); + base_peripheral->update_advertising_data(scan_result); + + // Convert the base object into an external-facing Peripheral object + PeripheralBuilder peripheral_builder(base_peripheral); + + // Check if the device has been seen before, to forward the correct call to the user. + if (this->seen_peripherals_.count(address) == 0) { + // Store it in our table of seen peripherals + this->seen_peripherals_.insert(std::make_pair(address, base_peripheral)); + SAFE_CALLBACK_CALL(this->callback_on_scan_found_, peripheral_builder); + } else { + SAFE_CALLBACK_CALL(this->callback_on_scan_updated_, peripheral_builder); + } + }); + +} + +AdapterBase::~AdapterBase() { + +} + +void* AdapterBase::underlying() const { return nullptr; } + +std::string AdapterBase::identifier() { + return _btAdapter.call_string_method("getName", "()Ljava/lang/String;"); +} + +BluetoothAddress AdapterBase::address() { + return BluetoothAddress(_btAdapter.call_string_method("getAddress", "()Ljava/lang/String;")); +} + +void AdapterBase::scan_start() { + seen_peripherals_.clear(); + _btScanner.call_void_method("startScan", "(Landroid/bluetooth/le/ScanCallback;)V", _btScanCallback.get()); + scanning_ = true; + SAFE_CALLBACK_CALL(this->callback_on_scan_start_); +} + +void AdapterBase::scan_stop() { + _btScanner.call_void_method("stopScan", "(Landroid/bluetooth/le/ScanCallback;)V", _btScanCallback.get()); + scanning_ = false; + SAFE_CALLBACK_CALL(this->callback_on_scan_stop_); +} + +void AdapterBase::scan_for(int timeout_ms) { + scan_start(); + std::this_thread::sleep_for(std::chrono::milliseconds(timeout_ms)); + scan_stop(); +} + +bool AdapterBase::scan_is_active() { return scanning_; } + +std::vector AdapterBase::scan_get_results() { + return std::vector(); +} + +std::vector AdapterBase::get_paired_peripherals() { + return std::vector(); +} + +void AdapterBase::set_callback_on_scan_start(std::function on_scan_start) { + if (on_scan_start) { + callback_on_scan_start_.load(on_scan_start); + } else { + callback_on_scan_start_.unload(); + } +} + +void AdapterBase::set_callback_on_scan_stop(std::function on_scan_stop) { + if (on_scan_stop) { + callback_on_scan_stop_.load(on_scan_stop); + } else { + callback_on_scan_stop_.unload(); + } +} + +void AdapterBase::set_callback_on_scan_updated(std::function on_scan_updated) { + if (on_scan_updated) { + callback_on_scan_updated_.load(on_scan_updated); + } else { + callback_on_scan_updated_.unload(); + } +} + +void AdapterBase::set_callback_on_scan_found(std::function on_scan_found) { + if (on_scan_found) { + callback_on_scan_found_.load(on_scan_found); + } else { + callback_on_scan_found_.unload(); + } +} + diff --git a/third_party/SimpleBLE/simpleble/src/backends/android/AdapterBase.h b/third_party/SimpleBLE/simpleble/src/backends/android/AdapterBase.h new file mode 100644 index 000000000..10b9d1f94 --- /dev/null +++ b/third_party/SimpleBLE/simpleble/src/backends/android/AdapterBase.h @@ -0,0 +1,86 @@ +#pragma once + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +#include "jni/Common.hpp" +#include "bridge/ScanCallback.h" + +namespace SimpleBLE { + +class AdapterBase { + public: + AdapterBase(); + virtual ~AdapterBase(); + + void* underlying() const; + + std::string identifier(); + BluetoothAddress address(); + + void scan_start(); + void scan_stop(); + void scan_for(int timeout_ms); + bool scan_is_active(); + std::vector scan_get_results(); + + void set_callback_on_scan_start(std::function on_scan_start); + void set_callback_on_scan_stop(std::function on_scan_stop); + void set_callback_on_scan_updated(std::function on_scan_updated); + void set_callback_on_scan_found(std::function on_scan_found); + + std::vector get_paired_peripherals(); + + static bool bluetooth_enabled(); + static std::vector> get_adapters(); + + // NOTE: The following methods have been made public to allow the JNI layer to call them, but + // should not be called directly by the user. + + void onScanResultCallback(JNIEnv *env, jobject thiz, jint callback_type, jobject result); + void onBatchScanResultsCallback(JNIEnv *env, jobject thiz, jobject results); + void onScanFailedCallback(JNIEnv *env, jobject thiz, jint error_code); + + //static std::map _scanCallbackMap; + + private: + // NOTE: The correct way to request a BluetoothAdapter is to go though the BluetoothManager, + // as described in https://developer.android.com/reference/android/bluetooth/BluetoothManager#getAdapter() + // However, for simplicity, we are using a direct call to BluetoothAdapter.getDefaultAdapter() which is + // deprecated in API 31 but still works. We'll need to implement a backend bypass to get a Context + // object and call getSystemService(Context.BLUETOOTH_SERVICE) to get the BluetoothManager. + + void static initialize(); + // NOTE: Android BluetoothAdapter and BluetoothScanner classes are singletons, so we can use a static instance. + static JNI::Class _btAdapterCls; + static JNI::Class _btScanCallbackCls; + static JNI::Class _btScanResultCls; + static JNI::Object _btAdapter; + static JNI::Object _btScanner; + + Android::Bridge::ScanCallback _btScanCallback; + + std::map> peripherals_; + std::map> seen_peripherals_; + + kvn::safe_callback callback_on_scan_start_; + kvn::safe_callback callback_on_scan_stop_; + kvn::safe_callback callback_on_scan_updated_; + kvn::safe_callback callback_on_scan_found_; + + std::atomic scanning_{false}; + + +}; + +} // namespace SimpleBLE diff --git a/third_party/SimpleBLE/simpleble/src/backends/android/PeripheralBase.cpp b/third_party/SimpleBLE/simpleble/src/backends/android/PeripheralBase.cpp new file mode 100644 index 000000000..48a8774e6 --- /dev/null +++ b/third_party/SimpleBLE/simpleble/src/backends/android/PeripheralBase.cpp @@ -0,0 +1,312 @@ +#include "PeripheralBase.h" + +#include "CharacteristicBuilder.h" +#include "DescriptorBuilder.h" +#include "ServiceBuilder.h" + +#include +#include +#include "CommonUtils.h" +#include "LoggingInternal.h" + +#include + +using namespace SimpleBLE; +using namespace std::chrono_literals; + +PeripheralBase::PeripheralBase(Android::ScanResult scan_result) : _device(scan_result.getDevice()) { + _btGattCallback.set_callback_onConnectionStateChange([this](bool connected) { + // If a connection has been established, request service discovery. + if (connected) { + _gatt.discoverServices(); + } else { + // TODO: Whatever cleanup is necessary when disconnected. + __android_log_write(ANDROID_LOG_INFO, "SimpleBLE", "Disconnected from device"); + SAFE_CALLBACK_CALL(callback_on_disconnected_); + } + }); + + _btGattCallback.set_callback_onServicesDiscovered([this]() { + _services = _gatt.getServices(); + + // Notify the user that the connection has been established once services have been discovered. + SAFE_CALLBACK_CALL(callback_on_connected_); + }); +} + +PeripheralBase::~PeripheralBase() {} + +void PeripheralBase::update_advertising_data(Android::ScanResult scan_result) {} + +void* PeripheralBase::underlying() const { return nullptr; } + +std::string PeripheralBase::identifier() { return _device.getName(); } + +BluetoothAddress PeripheralBase::address() { return BluetoothAddress(_device.getAddress()); } + +BluetoothAddressType PeripheralBase::address_type() { return BluetoothAddressType::UNSPECIFIED; } + +int16_t PeripheralBase::rssi() { return 0; } + +int16_t PeripheralBase::tx_power() { return 0; } + +uint16_t PeripheralBase::mtu() { return _btGattCallback.mtu; } + +void PeripheralBase::connect() { _gatt = _device.connectGatt(false, _btGattCallback); } + +void PeripheralBase::disconnect() { _gatt.disconnect(); } + +bool PeripheralBase::is_connected() { return _btGattCallback.connected && _btGattCallback.services_discovered; } + +bool PeripheralBase::is_connectable() { return false; } + +bool PeripheralBase::is_paired() { return false; } + +void PeripheralBase::unpair() {} + +std::vector PeripheralBase::services() { + std::vector service_list; + for (auto service : _services) { + // Build the list of characteristics for the service. + std::vector characteristic_list; + for (auto characteristic : service.getCharacteristics()) { + // Build the list of descriptors for the characteristic. + std::vector descriptor_list; + for (auto descriptor : characteristic.getDescriptors()) { + descriptor_list.push_back(DescriptorBuilder(descriptor.getUuid())); + } + + int flags = characteristic.getProperties(); + + bool can_read = flags & Android::BluetoothGattCharacteristic::PROPERTY_READ; + bool can_write_request = flags & Android::BluetoothGattCharacteristic::PROPERTY_WRITE; + bool can_write_command = flags & Android::BluetoothGattCharacteristic::PROPERTY_WRITE_NO_RESPONSE; + bool can_notify = flags & Android::BluetoothGattCharacteristic::PROPERTY_NOTIFY; + bool can_indicate = flags & Android::BluetoothGattCharacteristic::PROPERTY_INDICATE; + + characteristic_list.push_back(CharacteristicBuilder(characteristic.getUuid(), descriptor_list, can_read, + can_write_request, can_write_command, can_notify, + can_indicate)); + } + + service_list.push_back(ServiceBuilder(service.getUuid(), characteristic_list)); + } + + return service_list; +} + +std::vector PeripheralBase::advertised_services() { return std::vector(); } + +std::map PeripheralBase::manufacturer_data() { return std::map(); } + +ByteArray PeripheralBase::read(BluetoothUUID const& service, BluetoothUUID const& characteristic) { + auto msg = "Reading characteristic " + characteristic; + __android_log_write(ANDROID_LOG_INFO, "SimpleBLE", msg.c_str()); + + auto characteristic_obj = _fetch_characteristic(service, characteristic); + + _btGattCallback.set_flag_characteristicReadPending(characteristic_obj.getObject()); + if (!_gatt.readCharacteristic(characteristic_obj)) { + throw SimpleBLE::Exception::OperationFailed("Failed to read characteristic " + characteristic); + } + + auto value = _btGattCallback.wait_flag_characteristicReadPending(characteristic_obj.getObject()); + return ByteArray(value.begin(), value.end()); +} + +void PeripheralBase::write_request(BluetoothUUID const& service, BluetoothUUID const& characteristic, + ByteArray const& data) { + auto msg = "Writing request to characteristic " + characteristic; + __android_log_write(ANDROID_LOG_INFO, "SimpleBLE", msg.c_str()); + + auto characteristic_obj = _fetch_characteristic(service, characteristic); + + characteristic_obj.setWriteType(Android::BluetoothGattCharacteristic::WRITE_TYPE_DEFAULT); + characteristic_obj.setValue(std::vector(data.begin(), data.end())); + + _btGattCallback.set_flag_characteristicWritePending(characteristic_obj.getObject()); + if (!_gatt.writeCharacteristic(characteristic_obj)) { + throw SimpleBLE::Exception::OperationFailed("Failed to write characteristic " + characteristic); + } + _btGattCallback.wait_flag_characteristicWritePending(characteristic_obj.getObject()); +} + +void PeripheralBase::write_command(BluetoothUUID const& service, BluetoothUUID const& characteristic, + ByteArray const& data) { + auto msg = "Writing command to characteristic " + characteristic; + __android_log_write(ANDROID_LOG_INFO, "SimpleBLE", msg.c_str()); + + auto characteristic_obj = _fetch_characteristic(service, characteristic); + + characteristic_obj.setWriteType(Android::BluetoothGattCharacteristic::WRITE_TYPE_NO_RESPONSE); + characteristic_obj.setValue(std::vector(data.begin(), data.end())); + + _btGattCallback.set_flag_characteristicWritePending(characteristic_obj.getObject()); + if (!_gatt.writeCharacteristic(characteristic_obj)) { + throw SimpleBLE::Exception::OperationFailed("Failed to write characteristic " + characteristic); + } + _btGattCallback.wait_flag_characteristicWritePending(characteristic_obj.getObject()); +} + +void PeripheralBase::notify(BluetoothUUID const& service, BluetoothUUID const& characteristic, + std::function callback) { + auto msg = "Subscribing to characteristic " + characteristic; + __android_log_write(ANDROID_LOG_INFO, "SimpleBLE", msg.c_str()); + + auto characteristic_obj = _fetch_characteristic(service, characteristic); + auto descriptor_obj = _fetch_descriptor(service, characteristic, + Android::BluetoothGattDescriptor::CLIENT_CHARACTERISTIC_CONFIG); + + _btGattCallback.set_callback_onCharacteristicChanged(characteristic_obj.getObject(), + [callback](std::vector data) { + ByteArray payload(data.begin(), data.end()); + callback(payload); + }); + bool success = _gatt.setCharacteristicNotification(characteristic_obj, true); + if (!success) { + throw SimpleBLE::Exception::OperationFailed("Failed to subscribe to characteristic " + characteristic); + } + + _btGattCallback.set_flag_descriptorWritePending(descriptor_obj.getObject().get()); + descriptor_obj.setValue(Android::BluetoothGattDescriptor::ENABLE_NOTIFICATION_VALUE); + if (!_gatt.writeDescriptor(descriptor_obj)) { + throw SimpleBLE::Exception::OperationFailed("Failed to write descriptor for characteristic " + characteristic); + } + _btGattCallback.wait_flag_descriptorWritePending(descriptor_obj.getObject().get()); +} + +void PeripheralBase::indicate(BluetoothUUID const& service, BluetoothUUID const& characteristic, + std::function callback) { + auto msg = "Subscribing to characteristic " + characteristic; + __android_log_write(ANDROID_LOG_INFO, "SimpleBLE", msg.c_str()); + + auto characteristic_obj = _fetch_characteristic(service, characteristic); + auto descriptor_obj = _fetch_descriptor(service, characteristic, + Android::BluetoothGattDescriptor::CLIENT_CHARACTERISTIC_CONFIG); + + _btGattCallback.set_callback_onCharacteristicChanged(characteristic_obj.getObject(), + [callback](std::vector data) { + ByteArray payload(data.begin(), data.end()); + callback(payload); + }); + bool success = _gatt.setCharacteristicNotification(characteristic_obj, true); + if (!success) { + throw SimpleBLE::Exception::OperationFailed("Failed to subscribe to characteristic " + characteristic); + } + + _btGattCallback.set_flag_descriptorWritePending(descriptor_obj.getObject().get()); + descriptor_obj.setValue(Android::BluetoothGattDescriptor::ENABLE_INDICATION_VALUE); + if (!_gatt.writeDescriptor(descriptor_obj)) { + throw SimpleBLE::Exception::OperationFailed("Failed to write descriptor for characteristic " + characteristic); + } + _btGattCallback.wait_flag_descriptorWritePending(descriptor_obj.getObject().get()); +} + +void PeripheralBase::unsubscribe(BluetoothUUID const& service, BluetoothUUID const& characteristic) { + auto msg = "Unsubscribing from characteristic " + characteristic; + __android_log_write(ANDROID_LOG_INFO, "SimpleBLE", msg.c_str()); + + auto characteristic_obj = _fetch_characteristic(service, characteristic); + auto descriptor_obj = _fetch_descriptor(service, characteristic, + Android::BluetoothGattDescriptor::CLIENT_CHARACTERISTIC_CONFIG); + + _btGattCallback.set_flag_descriptorWritePending(descriptor_obj.getObject().get()); + descriptor_obj.setValue(Android::BluetoothGattDescriptor::DISABLE_NOTIFICATION_VALUE); + if (!_gatt.writeDescriptor(descriptor_obj)) { + throw SimpleBLE::Exception::OperationFailed("Failed to write descriptor for characteristic " + characteristic); + } + _btGattCallback.wait_flag_descriptorWritePending(descriptor_obj.getObject().get()); + + _btGattCallback.clear_callback_onCharacteristicChanged(characteristic_obj.getObject()); + bool success = _gatt.setCharacteristicNotification(characteristic_obj, true); + if (!success) { + throw SimpleBLE::Exception::OperationFailed("Failed to subscribe to characteristic " + characteristic); + } +} + +ByteArray PeripheralBase::read(BluetoothUUID const& service, BluetoothUUID const& characteristic, + BluetoothUUID const& descriptor) { + auto msg = "Reading descriptor " + descriptor; + __android_log_write(ANDROID_LOG_INFO, "SimpleBLE", msg.c_str()); + + auto descriptor_obj = _fetch_descriptor(service, characteristic, descriptor); + + _btGattCallback.set_flag_descriptorReadPending(descriptor_obj.getObject().get()); + if (!_gatt.readDescriptor(descriptor_obj)) { + throw SimpleBLE::Exception::OperationFailed("Failed to read descriptor " + descriptor); + } + + auto value = _btGattCallback.wait_flag_descriptorReadPending(descriptor_obj.getObject().get()); + return ByteArray(value.begin(), value.end()); +} + +void PeripheralBase::write(BluetoothUUID const& service, BluetoothUUID const& characteristic, + BluetoothUUID const& descriptor, ByteArray const& data) { + auto msg = "Writing descriptor " + descriptor; + __android_log_write(ANDROID_LOG_INFO, "SimpleBLE", msg.c_str()); + + auto descriptor_obj = _fetch_descriptor(service, characteristic, descriptor); + + _btGattCallback.set_flag_descriptorWritePending(descriptor_obj.getObject().get()); + descriptor_obj.setValue(std::vector(data.begin(), data.end())); + if (!_gatt.writeDescriptor(descriptor_obj)) { + throw SimpleBLE::Exception::OperationFailed("Failed to write descriptor " + descriptor); + } + _btGattCallback.wait_flag_descriptorWritePending(descriptor_obj.getObject().get()); +} + +void PeripheralBase::set_callback_on_connected(std::function on_connected) { + if (on_connected) { + callback_on_connected_.load(std::move(on_connected)); + } else { + callback_on_connected_.unload(); + } +} + +void PeripheralBase::set_callback_on_disconnected(std::function on_disconnected) { + if (on_disconnected) { + callback_on_disconnected_.load(std::move(on_disconnected)); + } else { + callback_on_disconnected_.unload(); + } +} + +// NOTE: This approach to retrieve the characteristic and descriptor objects is not ideal, as it involves +// iterating on Java objects and returning a copy of the desired object. This will be improved in the future +// if performance becomes a bottleneck. +Android::BluetoothGattCharacteristic PeripheralBase::_fetch_characteristic(const BluetoothUUID& service_uuid, + const BluetoothUUID& characteristic_uuid) { + for (auto& service : _services) { + if (service.getUuid() == service_uuid) { + for (auto& characteristic : service.getCharacteristics()) { + if (characteristic.getUuid() == characteristic_uuid) { + return characteristic; + } + throw SimpleBLE::Exception::CharacteristicNotFound(characteristic_uuid); + } + } + } + + throw SimpleBLE::Exception::ServiceNotFound(service_uuid); +} + +Android::BluetoothGattDescriptor PeripheralBase::_fetch_descriptor(const BluetoothUUID& service_uuid, + const BluetoothUUID& characteristic_uuid, + const BluetoothUUID& descriptor_uuid) { + for (auto& service : _services) { + if (service.getUuid() == service_uuid) { + for (auto& characteristic : service.getCharacteristics()) { + if (characteristic.getUuid() == characteristic_uuid) { + for (auto& descriptor : characteristic.getDescriptors()) { + if (descriptor.getUuid() == descriptor_uuid) { + return descriptor; + } + throw SimpleBLE::Exception::DescriptorNotFound(descriptor_uuid); + } + } + throw SimpleBLE::Exception::CharacteristicNotFound(characteristic_uuid); + } + } + } + throw SimpleBLE::Exception::ServiceNotFound(service_uuid); +} \ No newline at end of file diff --git a/third_party/SimpleBLE/simpleble/src/backends/android/PeripheralBase.h b/third_party/SimpleBLE/simpleble/src/backends/android/PeripheralBase.h new file mode 100644 index 000000000..3a6564e00 --- /dev/null +++ b/third_party/SimpleBLE/simpleble/src/backends/android/PeripheralBase.h @@ -0,0 +1,74 @@ +#pragma once + +#include +#include +#include + +#include +#include + +#include + +namespace SimpleBLE { + +class PeripheralBase { + public: + PeripheralBase(Android::ScanResult scan_result); + virtual ~PeripheralBase(); + + void* underlying() const; + + std::string identifier(); + BluetoothAddress address(); + BluetoothAddressType address_type(); + int16_t rssi(); + int16_t tx_power(); + uint16_t mtu(); + + void connect(); + void disconnect(); + bool is_connected(); + bool is_connectable(); + bool is_paired(); + void unpair(); + + std::vector services(); + std::vector advertised_services(); + std::map manufacturer_data(); + + // clang-format off + ByteArray read(BluetoothUUID const& service, BluetoothUUID const& characteristic); + void write_request(BluetoothUUID const& service, BluetoothUUID const& characteristic, ByteArray const& data); + void write_command(BluetoothUUID const& service, BluetoothUUID const& characteristic, ByteArray const& data); + void notify(BluetoothUUID const& service, BluetoothUUID const& characteristic, std::function callback); + void indicate(BluetoothUUID const& service, BluetoothUUID const& characteristic, std::function callback); + void unsubscribe(BluetoothUUID const& service, BluetoothUUID const& characteristic); + + ByteArray read(BluetoothUUID const& service, BluetoothUUID const& characteristic, BluetoothUUID const& descriptor); + void write(BluetoothUUID const& service, BluetoothUUID const& characteristic, BluetoothUUID const& descriptor, ByteArray const& data); + // clang-format on + + void set_callback_on_connected(std::function on_connected); + void set_callback_on_disconnected(std::function on_disconnected); + + void update_advertising_data(Android::ScanResult scan_result); + + private: + + Android::Bridge::BluetoothGattCallback _btGattCallback; + Android::BluetoothDevice _device; + Android::BluetoothGatt _gatt; + std::vector _services; + + kvn::safe_callback callback_on_connected_; + kvn::safe_callback callback_on_disconnected_; + + Android::BluetoothGattCharacteristic _fetch_characteristic(const BluetoothUUID& service_uuid, + const BluetoothUUID& characteristic_uuid); + Android::BluetoothGattDescriptor _fetch_descriptor(const BluetoothUUID& service_uuid, + const BluetoothUUID& characteristic_uuid, + const BluetoothUUID& descriptor_uuid); + +}; + +} // namespace SimpleBLE diff --git a/third_party/SimpleBLE/simpleble/src/backends/android/android/BluetoothDevice.cpp b/third_party/SimpleBLE/simpleble/src/backends/android/android/BluetoothDevice.cpp new file mode 100644 index 000000000..d29d2cae3 --- /dev/null +++ b/third_party/SimpleBLE/simpleble/src/backends/android/android/BluetoothDevice.cpp @@ -0,0 +1,46 @@ +#include "BluetoothDevice.h" + +namespace SimpleBLE { +namespace Android { + +JNI::Class BluetoothDevice::_cls; +jmethodID BluetoothDevice::_method_getAddress; +jmethodID BluetoothDevice::_method_getName; +jmethodID BluetoothDevice::_method_connectGatt; + +void BluetoothDevice::initialize() { + JNI::Env env; + + if (_cls.get() == nullptr) { + _cls = env.find_class("android/bluetooth/BluetoothDevice"); + } + + if (!_method_getAddress) { + _method_getAddress = env->GetMethodID(_cls.get(), "getAddress", "()Ljava/lang/String;"); + } + + if (!_method_getName) { + _method_getName = env->GetMethodID(_cls.get(), "getName", "()Ljava/lang/String;"); + } + + if (!_method_connectGatt) { + _method_connectGatt = env->GetMethodID( + _cls.get(), "connectGatt", + "(Landroid/content/Context;ZLandroid/bluetooth/BluetoothGattCallback;)Landroid/bluetooth/BluetoothGatt;"); + } +} + +BluetoothDevice::BluetoothDevice(JNI::Object obj) : _obj(obj) { + initialize(); +}; + +std::string BluetoothDevice::getAddress() { return _obj.call_string_method(_method_getAddress); } + +std::string BluetoothDevice::getName() { return _obj.call_string_method(_method_getName); } + +BluetoothGatt BluetoothDevice::connectGatt(bool autoConnect, Bridge::BluetoothGattCallback& callback) { + return BluetoothGatt(_obj.call_object_method(_method_connectGatt, nullptr, autoConnect, callback.get())); +} + +} // namespace Android +} // namespace SimpleBLE diff --git a/third_party/SimpleBLE/simpleble/src/backends/android/android/BluetoothDevice.h b/third_party/SimpleBLE/simpleble/src/backends/android/android/BluetoothDevice.h new file mode 100644 index 000000000..b38fc6c02 --- /dev/null +++ b/third_party/SimpleBLE/simpleble/src/backends/android/android/BluetoothDevice.h @@ -0,0 +1,33 @@ +#pragma once + +#include "BluetoothGatt.h" + +#include "jni/Common.hpp" +#include "bridge/BluetoothGattCallback.h" + +namespace SimpleBLE { +namespace Android { + +class BluetoothDevice { +public: + BluetoothDevice(JNI::Object obj); + + std::string getAddress(); + std::string getName(); + + BluetoothGatt connectGatt(bool autoConnect, Bridge::BluetoothGattCallback& callback); + +private: + static JNI::Class _cls; + static jmethodID _method_getAddress; + static jmethodID _method_getName; + static jmethodID _method_connectGatt; + + static void initialize(); + + JNI::Object _obj; + +}; + +} // namespace Android +} // namespace SimpleBLE diff --git a/third_party/SimpleBLE/simpleble/src/backends/android/android/BluetoothGatt.cpp b/third_party/SimpleBLE/simpleble/src/backends/android/android/BluetoothGatt.cpp new file mode 100644 index 000000000..2fefc5c75 --- /dev/null +++ b/third_party/SimpleBLE/simpleble/src/backends/android/android/BluetoothGatt.cpp @@ -0,0 +1,146 @@ +#include "BluetoothGatt.h" +#include +#include + +namespace SimpleBLE { +namespace Android { + +JNI::Class BluetoothGatt::_cls; +jmethodID BluetoothGatt::_method_close = nullptr; +jmethodID BluetoothGatt::_method_connect = nullptr; +jmethodID BluetoothGatt::_method_disconnect = nullptr; +jmethodID BluetoothGatt::_method_discoverServices = nullptr; +jmethodID BluetoothGatt::_method_readCharacteristic = nullptr; +jmethodID BluetoothGatt::_method_readDescriptor = nullptr; +jmethodID BluetoothGatt::_method_setCharacteristicNotification = nullptr; +jmethodID BluetoothGatt::_method_writeCharacteristic = nullptr; +jmethodID BluetoothGatt::_method_writeDescriptor = nullptr; + +void BluetoothGatt::initialize() { + JNI::Env env; + + if (_cls.get() == nullptr) { + _cls = env.find_class("android/bluetooth/BluetoothGatt"); + } + + if (!_method_close) { + _method_close = env->GetMethodID(_cls.get(), "close", "()V"); + } + + if (!_method_connect) { + _method_connect = env->GetMethodID(_cls.get(), "connect", "()Z"); + } + + if (!_method_disconnect) { + _method_disconnect = env->GetMethodID(_cls.get(), "disconnect", "()V"); + } + + if (!_method_discoverServices) { + _method_discoverServices = env->GetMethodID(_cls.get(), "discoverServices", "()Z"); + } + + if (!_method_readCharacteristic) { + _method_readCharacteristic = env->GetMethodID(_cls.get(), "readCharacteristic", + "(Landroid/bluetooth/BluetoothGattCharacteristic;)Z"); + } + + if (!_method_readDescriptor) { + _method_readDescriptor = env->GetMethodID(_cls.get(), "readDescriptor", + "(Landroid/bluetooth/BluetoothGattDescriptor;)Z"); + } + + if (!_method_setCharacteristicNotification) { + _method_setCharacteristicNotification = env->GetMethodID(_cls.get(), "setCharacteristicNotification", + "(Landroid/bluetooth/BluetoothGattCharacteristic;Z)Z"); + } + + if (!_method_writeCharacteristic) { + _method_writeCharacteristic = env->GetMethodID(_cls.get(), "writeCharacteristic", + "(Landroid/bluetooth/BluetoothGattCharacteristic;)Z"); + } + + if (!_method_writeDescriptor) { + _method_writeDescriptor = env->GetMethodID(_cls.get(), "writeDescriptor", + "(Landroid/bluetooth/BluetoothGattDescriptor;)Z"); + } +} + +BluetoothGatt::BluetoothGatt() { initialize(); } + +BluetoothGatt::BluetoothGatt(JNI::Object obj) : BluetoothGatt() { _obj = obj; } + +void BluetoothGatt::close() { + if (!_obj) return; + + _obj.call_void_method(_method_close); +} + +bool BluetoothGatt::connect() { + if (!_obj) return false; + + return _obj.call_boolean_method(_method_connect); +} + +void BluetoothGatt::disconnect() { + if (!_obj) return; + + _obj.call_void_method(_method_disconnect); +} + +bool BluetoothGatt::discoverServices() { + if (!_obj) return false; + + return _obj.call_boolean_method(_method_discoverServices); +} + +std::vector BluetoothGatt::getServices() { + if (!_obj) return std::vector(); + + JNI::Object services = _obj.call_object_method("getServices", "()Ljava/util/List;"); + if (!services) return std::vector(); + + // TODO: We should create a List class type and cache method IDs. + std::vector result; + JNI::Object iterator = services.call_object_method("iterator", "()Ljava/util/Iterator;"); + while (iterator.call_boolean_method("hasNext", "()Z")) { + JNI::Object service = iterator.call_object_method("next", "()Ljava/lang/Object;"); + + if (!service) continue; + result.push_back(BluetoothGattService(service)); + } + + return result; +} + +bool BluetoothGatt::readCharacteristic(BluetoothGattCharacteristic characteristic) { + if (!_obj) return false; + + return _obj.call_boolean_method(_method_readCharacteristic, characteristic.getObject().get()); +} + +bool BluetoothGatt::readDescriptor(BluetoothGattDescriptor descriptor) { + if (!_obj) return false; + + return _obj.call_boolean_method(_method_readDescriptor, descriptor.getObject().get()); +} + +bool BluetoothGatt::setCharacteristicNotification(BluetoothGattCharacteristic characteristic, bool enable) { + if (!_obj) return false; + + return _obj.call_boolean_method(_method_setCharacteristicNotification, characteristic.getObject().get(), enable); +} + +bool BluetoothGatt::writeCharacteristic(BluetoothGattCharacteristic characteristic) { + if (!_obj) return false; + + return _obj.call_boolean_method(_method_writeCharacteristic, characteristic.getObject().get()); +} + +bool BluetoothGatt::writeDescriptor(BluetoothGattDescriptor descriptor) { + if (!_obj) return false; + + return _obj.call_boolean_method(_method_writeDescriptor, descriptor.getObject().get()); +} + +} // namespace Android +} // namespace SimpleBLE diff --git a/third_party/SimpleBLE/simpleble/src/backends/android/android/BluetoothGatt.h b/third_party/SimpleBLE/simpleble/src/backends/android/android/BluetoothGatt.h new file mode 100644 index 000000000..5fbeabc82 --- /dev/null +++ b/third_party/SimpleBLE/simpleble/src/backends/android/android/BluetoothGatt.h @@ -0,0 +1,64 @@ +#pragma once + +#include "BluetoothGattService.h" +#include "jni/Common.hpp" + +#include +#include + +namespace SimpleBLE { +namespace Android { + +class BluetoothGatt { + public: + BluetoothGatt(); + BluetoothGatt(JNI::Object obj); + + void close(); + bool connect(); + void disconnect(); + bool discoverServices(); + std::vector getServices(); + + // void abortReliableWrite(BluetoothDevice mDevice); + // void abortReliableWrite(); + // bool beginReliableWrite(); + // bool executeReliableWrite(); + // std::list getConnectedDevices(); + // int getConnectionState(BluetoothDevice device); + // BluetoothDevice getDevice(); + // std::list getDevicesMatchingConnectionStates(std::vector& states); + // BluetoothGattService getService(UUID uuid); + // std::list getServices(); + bool readCharacteristic(BluetoothGattCharacteristic characteristic); + bool readDescriptor(BluetoothGattDescriptor descriptor); + // void readPhy(); + // bool readRemoteRssi(); + // bool requestConnectionPriority(int connectionPriority); + // bool requestMtu(int mtu); + bool setCharacteristicNotification(BluetoothGattCharacteristic characteristic, bool enable); + // void setPreferredPhy(int txPhy, int rxPhy, int phyOptions); + bool writeCharacteristic(BluetoothGattCharacteristic characteristic); + // int writeCharacteristic(BluetoothGattCharacteristic characteristic, std::vector& value, int writeType); + bool writeDescriptor(BluetoothGattDescriptor descriptor); + // int writeDescriptor(BluetoothGattDescriptor descriptor, std::vector& value); + + private: + static JNI::Class _cls; + static jmethodID _method_close; + static jmethodID _method_connect; + static jmethodID _method_disconnect; + static jmethodID _method_discoverServices; + static jmethodID _method_readCharacteristic; + static jmethodID _method_readDescriptor; + static jmethodID _method_setCharacteristicNotification; + static jmethodID _method_writeCharacteristic; + static jmethodID _method_writeDescriptor; + + static void initialize(); + + JNI::Object _obj; +}; + +} // namespace Android +} // namespace SimpleBLE diff --git a/third_party/SimpleBLE/simpleble/src/backends/android/android/BluetoothGattCharacteristic.cpp b/third_party/SimpleBLE/simpleble/src/backends/android/android/BluetoothGattCharacteristic.cpp new file mode 100644 index 000000000..697e1515c --- /dev/null +++ b/third_party/SimpleBLE/simpleble/src/backends/android/android/BluetoothGattCharacteristic.cpp @@ -0,0 +1,144 @@ +// +// Created by Kevin Dewald on 5/17/24. +// + +#include "BluetoothGattCharacteristic.h" +#include "UUID.h" +#include "jni/Types.h" + +namespace SimpleBLE { +namespace Android { + +JNI::Class BluetoothGattCharacteristic::_cls; +jmethodID BluetoothGattCharacteristic::_method_addDescriptor = nullptr; +jmethodID BluetoothGattCharacteristic::_method_getDescriptor = nullptr; +jmethodID BluetoothGattCharacteristic::_method_getDescriptors = nullptr; +jmethodID BluetoothGattCharacteristic::_method_getInstanceId = nullptr; +jmethodID BluetoothGattCharacteristic::_method_getPermissions = nullptr; +jmethodID BluetoothGattCharacteristic::_method_getProperties = nullptr; +jmethodID BluetoothGattCharacteristic::_method_getService = nullptr; +jmethodID BluetoothGattCharacteristic::_method_getUuid = nullptr; +jmethodID BluetoothGattCharacteristic::_method_getWriteType = nullptr; +jmethodID BluetoothGattCharacteristic::_method_setWriteType = nullptr; +jmethodID BluetoothGattCharacteristic::_method_setValue = nullptr; + +void BluetoothGattCharacteristic::initialize() { + JNI::Env env; + + if (_cls.get() == nullptr) { + _cls = env.find_class("android/bluetooth/BluetoothGattCharacteristic"); + } + + if (!_method_addDescriptor) { + _method_addDescriptor = env->GetMethodID(_cls.get(), "addDescriptor", + "(Landroid/bluetooth/BluetoothGattDescriptor;)Z"); + } + + if (!_method_getDescriptor) { + _method_getDescriptor = env->GetMethodID(_cls.get(), "getDescriptor", + "(Ljava/util/UUID;)Landroid/bluetooth/BluetoothGattDescriptor;"); + } + + if (!_method_getDescriptors) { + _method_getDescriptors = env->GetMethodID(_cls.get(), "getDescriptors", "()Ljava/util/List;"); + } + + if (!_method_getInstanceId) { + _method_getInstanceId = env->GetMethodID(_cls.get(), "getInstanceId", "()I"); + } + + if (!_method_getPermissions) { + _method_getPermissions = env->GetMethodID(_cls.get(), "getPermissions", "()I"); + } + + if (!_method_getProperties) { + _method_getProperties = env->GetMethodID(_cls.get(), "getProperties", "()I"); + } + + if (!_method_getService) { + _method_getService = env->GetMethodID(_cls.get(), "getService", "()Landroid/bluetooth/BluetoothGattService;"); + } + + if (!_method_getUuid) { + _method_getUuid = env->GetMethodID(_cls.get(), "getUuid", "()Ljava/util/UUID;"); + } + + if (!_method_getWriteType) { + _method_getWriteType = env->GetMethodID(_cls.get(), "getWriteType", "()I"); + } + + if (!_method_setWriteType) { + _method_setWriteType = env->GetMethodID(_cls.get(), "setWriteType", "(I)V"); + } + + if (!_method_setValue) { + _method_setValue = env->GetMethodID(_cls.get(), "setValue", "([B)Z"); + } +} + +BluetoothGattCharacteristic::BluetoothGattCharacteristic() { initialize(); } + +BluetoothGattCharacteristic::BluetoothGattCharacteristic(JNI::Object obj) : BluetoothGattCharacteristic() { + _obj = obj; +} + +// bool BluetoothGattCharacteristic::addDescriptor(BluetoothGattDescriptor descriptor) { +// return _obj.call_boolean_method(_method_addDescriptor, descriptor.getObject()); +// } +// +// BluetoothGattDescriptor BluetoothGattCharacteristic::getDescriptor(std::string uuid) { +// JNI::Env env; +// JNI::Object descObj = _obj.call_object_method(_method_getDescriptor, env->NewStringUTF(uuid.c_str())); +// return BluetoothGattDescriptor(descObj); +// } +// +std::vector BluetoothGattCharacteristic::getDescriptors() { + if (!_obj) return std::vector(); + + JNI::Object descriptors = _obj.call_object_method(_method_getDescriptors); + if (!descriptors) return std::vector(); + + std::vector result; + JNI::Object iterator = descriptors.call_object_method("iterator", "()Ljava/util/Iterator;"); + while (iterator.call_boolean_method("hasNext", "()Z")) { + JNI::Object descriptor = iterator.call_object_method("next", "()Ljava/lang/Object;"); + + if (!descriptor) continue; + result.push_back(BluetoothGattDescriptor(descriptor)); + } + + return result; +} + +int BluetoothGattCharacteristic::getInstanceId() { return _obj.call_int_method(_method_getInstanceId); } + +int BluetoothGattCharacteristic::getPermissions() { return _obj.call_int_method(_method_getPermissions); } + +int BluetoothGattCharacteristic::getProperties() { return _obj.call_int_method(_method_getProperties); } + +std::string BluetoothGattCharacteristic::getUuid() { + if (!_obj) return ""; + + JNI::Object uuidObj = _obj.call_object_method(_method_getUuid); + if (!uuidObj) return ""; + + return UUID(uuidObj).toString(); +} + +int BluetoothGattCharacteristic::getWriteType() { return _obj.call_int_method(_method_getWriteType); } + +void BluetoothGattCharacteristic::setWriteType(int writeType) { + _obj.call_void_method(_method_setWriteType, writeType); +} + +bool BluetoothGattCharacteristic::setValue(const std::vector& value) { + JNI::Env env; + jbyteArray array = JNI::Types::toJByteArray(value); + + bool result = _obj.call_boolean_method(_method_setValue, array); + env->DeleteLocalRef(array); + return result; +} + +} // namespace Android +} // namespace SimpleBLE \ No newline at end of file diff --git a/third_party/SimpleBLE/simpleble/src/backends/android/android/BluetoothGattCharacteristic.h b/third_party/SimpleBLE/simpleble/src/backends/android/android/BluetoothGattCharacteristic.h new file mode 100644 index 000000000..507db989e --- /dev/null +++ b/third_party/SimpleBLE/simpleble/src/backends/android/android/BluetoothGattCharacteristic.h @@ -0,0 +1,57 @@ +#pragma once + +#include +#include +#include "BluetoothGattDescriptor.h" +#include "jni/Common.hpp" + +namespace SimpleBLE { +namespace Android { + +class BluetoothGattCharacteristic { + public: + BluetoothGattCharacteristic(); + BluetoothGattCharacteristic(JNI::Object obj); + + // bool addDescriptor(BluetoothGattDescriptor descriptor); + // BluetoothGattDescriptor getDescriptor(std::string uuid); + std::vector getDescriptors(); + int getInstanceId(); + int getPermissions(); + int getProperties(); + std::string getUuid(); + int getWriteType(); + void setWriteType(int writeType); + bool setValue(const std::vector& value); + + JNI::Object getObject() const { return _obj; } + + static const int PROPERTY_INDICATE = 0x00000020; + static const int PROPERTY_NOTIFY = 0x00000010; + static const int PROPERTY_READ = 0x00000002; + static const int PROPERTY_WRITE = 0x00000008; + static const int PROPERTY_WRITE_NO_RESPONSE = 0x00000004; + + static const int WRITE_TYPE_DEFAULT = 2; + static const int WRITE_TYPE_NO_RESPONSE = 1; + + private: + JNI::Object _obj; + static JNI::Class _cls; + static jmethodID _method_addDescriptor; + static jmethodID _method_getDescriptor; + static jmethodID _method_getDescriptors; + static jmethodID _method_getInstanceId; + static jmethodID _method_getPermissions; + static jmethodID _method_getProperties; + static jmethodID _method_getService; + static jmethodID _method_getUuid; + static jmethodID _method_getWriteType; + static jmethodID _method_setWriteType; + static jmethodID _method_setValue; + + void initialize(); +}; + +} // namespace Android +} // namespace SimpleBLE diff --git a/third_party/SimpleBLE/simpleble/src/backends/android/android/BluetoothGattDescriptor.cpp b/third_party/SimpleBLE/simpleble/src/backends/android/android/BluetoothGattDescriptor.cpp new file mode 100644 index 000000000..0274c77e5 --- /dev/null +++ b/third_party/SimpleBLE/simpleble/src/backends/android/android/BluetoothGattDescriptor.cpp @@ -0,0 +1,70 @@ +#include "BluetoothGattDescriptor.h" +#include "UUID.h" + +namespace SimpleBLE { +namespace Android { + +JNI::Class BluetoothGattDescriptor::_cls; +jmethodID BluetoothGattDescriptor::_method_getUuid = nullptr; +jmethodID BluetoothGattDescriptor::_method_getValue = nullptr; +jmethodID BluetoothGattDescriptor::_method_setValue = nullptr; + +const std::string BluetoothGattDescriptor::CLIENT_CHARACTERISTIC_CONFIG = "00002902-0000-1000-8000-00805f9b34fb"; +const std::vector BluetoothGattDescriptor::DISABLE_NOTIFICATION_VALUE = {0x00, 0x00}; +const std::vector BluetoothGattDescriptor::ENABLE_NOTIFICATION_VALUE = {0x01, 0x00}; +const std::vector BluetoothGattDescriptor::ENABLE_INDICATION_VALUE = {0x02, 0x00}; + +void BluetoothGattDescriptor::initialize() { + JNI::Env env; + + if (_cls.get() == nullptr) { + _cls = env.find_class("android/bluetooth/BluetoothGattDescriptor"); + } + + if (!_method_getUuid) { + _method_getUuid = env->GetMethodID(_cls.get(), "getUuid", "()Ljava/util/UUID;"); + } + + if (!_method_getValue) { + _method_getValue = env->GetMethodID(_cls.get(), "getValue", "()[B"); + } + + if (!_method_setValue) { + _method_setValue = env->GetMethodID(_cls.get(), "setValue", "([B)Z"); + } +} + +BluetoothGattDescriptor::BluetoothGattDescriptor() { initialize(); } + +BluetoothGattDescriptor::BluetoothGattDescriptor(JNI::Object obj) : BluetoothGattDescriptor() { _obj = obj; } + +std::string BluetoothGattDescriptor::getUuid() { + if (!_obj) return ""; + + JNI::Object uuidObj = _obj.call_object_method(_method_getUuid); + if (!uuidObj) return ""; + + return UUID(uuidObj).toString(); +} + +std::vector BluetoothGattDescriptor::getValue() { + if (!_obj) return {}; + + return _obj.call_byte_array_method(_method_getValue); +} + +bool BluetoothGattDescriptor::setValue(const std::vector &value) { + if (!_obj) return false; + + JNI::Env env; + jbyteArray jbyteArray_obj = env->NewByteArray(value.size()); + env->SetByteArrayRegion(jbyteArray_obj, 0, value.size(), reinterpret_cast(value.data())); + + bool result = _obj.call_boolean_method(_method_setValue, jbyteArray_obj); + + env->DeleteLocalRef(jbyteArray_obj); + return result; +} + +} // namespace Android +} // namespace SimpleBLE \ No newline at end of file diff --git a/third_party/SimpleBLE/simpleble/src/backends/android/android/BluetoothGattDescriptor.h b/third_party/SimpleBLE/simpleble/src/backends/android/android/BluetoothGattDescriptor.h new file mode 100644 index 000000000..73eb7c074 --- /dev/null +++ b/third_party/SimpleBLE/simpleble/src/backends/android/android/BluetoothGattDescriptor.h @@ -0,0 +1,39 @@ +#pragma once + +#include +#include +#include "jni/Common.hpp" + +namespace SimpleBLE { +namespace Android { + +class BluetoothGattDescriptor { + public: + BluetoothGattDescriptor(); + BluetoothGattDescriptor(JNI::Object obj); + + std::string getUuid(); + + std::vector getValue(); + bool setValue(const std::vector& value); + + JNI::Object getObject() const { return _obj; } + + static const std::string CLIENT_CHARACTERISTIC_CONFIG; + static const std::vector DISABLE_NOTIFICATION_VALUE; + static const std::vector ENABLE_NOTIFICATION_VALUE; + static const std::vector ENABLE_INDICATION_VALUE; + + + private: + JNI::Object _obj; + static JNI::Class _cls; + static jmethodID _method_getUuid; + static jmethodID _method_getValue; + static jmethodID _method_setValue; + + void initialize(); +}; + +} // namespace Android +} // namespace SimpleBLE diff --git a/third_party/SimpleBLE/simpleble/src/backends/android/android/BluetoothGattService.cpp b/third_party/SimpleBLE/simpleble/src/backends/android/android/BluetoothGattService.cpp new file mode 100644 index 000000000..f50b32b64 --- /dev/null +++ b/third_party/SimpleBLE/simpleble/src/backends/android/android/BluetoothGattService.cpp @@ -0,0 +1,122 @@ +// +// Created by Kevin Dewald on 5/17/24. +// + +#include "BluetoothGattService.h" +#include "UUID.h" + +namespace SimpleBLE { +namespace Android { + +JNI::Class BluetoothGattService::_cls; +jmethodID BluetoothGattService::_method_addCharacteristic = nullptr; +jmethodID BluetoothGattService::_method_addService = nullptr; +jmethodID BluetoothGattService::_method_getCharacteristic = nullptr; +jmethodID BluetoothGattService::_method_getCharacteristics = nullptr; +jmethodID BluetoothGattService::_method_getIncludedServices = nullptr; +jmethodID BluetoothGattService::_method_getInstanceId = nullptr; +jmethodID BluetoothGattService::_method_getType = nullptr; +jmethodID BluetoothGattService::_method_getUuid = nullptr; + +void BluetoothGattService::initialize() { + JNI::Env env; + + if (_cls.get() == nullptr) { + _cls = env.find_class("android/bluetooth/BluetoothGattService"); + } + + if (!_method_addCharacteristic) { + _method_addCharacteristic = env->GetMethodID(_cls.get(), "addCharacteristic", + "(Landroid/bluetooth/BluetoothGattCharacteristic;)Z"); + } + + if (!_method_addService) { + _method_addService = env->GetMethodID(_cls.get(), "addService", "(Landroid/bluetooth/BluetoothGattService;)Z"); + } + + if (!_method_getCharacteristic) { + _method_getCharacteristic = env->GetMethodID( + _cls.get(), "getCharacteristic", "(Ljava/util/UUID;)Landroid/bluetooth/BluetoothGattCharacteristic;"); + } + + if (!_method_getCharacteristics) { + _method_getCharacteristics = env->GetMethodID(_cls.get(), "getCharacteristics", "()Ljava/util/List;"); + } + + if (!_method_getIncludedServices) { + _method_getIncludedServices = env->GetMethodID(_cls.get(), "getIncludedServices", "()Ljava/util/List;"); + } + + if (!_method_getInstanceId) { + _method_getInstanceId = env->GetMethodID(_cls.get(), "getInstanceId", "()I"); + } + + if (!_method_getType) { + _method_getType = env->GetMethodID(_cls.get(), "getType", "()I"); + } + + if (!_method_getUuid) { + _method_getUuid = env->GetMethodID(_cls.get(), "getUuid", "()Ljava/util/UUID;"); + } +} + +BluetoothGattService::BluetoothGattService() { initialize(); } + + +BluetoothGattService::BluetoothGattService(JNI::Object obj) : BluetoothGattService() { + _obj = obj; +} + +//bool BluetoothGattService::addCharacteristic(BluetoothGattCharacteristic characteristic) { +// return _obj.call_boolean_method(_method_addCharacteristic, characteristic.getObject()); +//} +// +//bool BluetoothGattService::addService(BluetoothGattService service) { +// return _obj.call_boolean_method(_method_addService, service.getObject()); +//} +// +//BluetoothGattCharacteristic BluetoothGattService::getCharacteristic(std::string uuid) { +// JNI::Env env; +// JNI::Object charObj = _obj.call_object_method(_method_getCharacteristic, env->NewStringUTF(uuid.c_str())); +// return BluetoothGattCharacteristic(charObj); +//} +// +std::vector BluetoothGattService::getCharacteristics() { + if (!_obj) return std::vector(); + + JNI::Object characteristics = _obj.call_object_method(_method_getCharacteristics); + if (!characteristics) return std::vector(); + + std::vector result; + JNI::Object iterator = characteristics.call_object_method("iterator", "()Ljava/util/Iterator;"); + while (iterator.call_boolean_method("hasNext", "()Z")) { + JNI::Object characteristic = iterator.call_object_method("next", "()Ljava/lang/Object;"); + + if (!characteristic) continue; + result.push_back(BluetoothGattCharacteristic(characteristic)); + } + + return result; +} +// +//std::vector BluetoothGattService::getIncludedServices() { +// JNI::Env env; +// JNI::Object listObj = _obj.call_object_method(_method_getIncludedServices); +// return JNI::convert_list(listObj); +//} + +int BluetoothGattService::getInstanceId() { return _obj.call_int_method(_method_getInstanceId); } + +int BluetoothGattService::getType() { return _obj.call_int_method(_method_getType); } + +std::string BluetoothGattService::getUuid() { + if (!_obj) return ""; + + JNI::Object uuidObj = _obj.call_object_method(_method_getUuid); + if (!uuidObj) return ""; + + return UUID(uuidObj).toString(); +} + +} // namespace Android +} // namespace SimpleBLE \ No newline at end of file diff --git a/third_party/SimpleBLE/simpleble/src/backends/android/android/BluetoothGattService.h b/third_party/SimpleBLE/simpleble/src/backends/android/android/BluetoothGattService.h new file mode 100644 index 000000000..aa3a844b8 --- /dev/null +++ b/third_party/SimpleBLE/simpleble/src/backends/android/android/BluetoothGattService.h @@ -0,0 +1,43 @@ +#pragma once + +#include +#include +#include "BluetoothGattCharacteristic.h" +#include "jni/Common.hpp" + +namespace SimpleBLE { +namespace Android { + +class BluetoothGattService { + public: + BluetoothGattService(); + BluetoothGattService(JNI::Object obj); + +// bool addCharacteristic(BluetoothGattCharacteristic characteristic); +// bool addService(BluetoothGattService service); +// BluetoothGattCharacteristic getCharacteristic(std::string uuid); + std::vector getCharacteristics(); +// std::vector getIncludedServices(); + int getInstanceId(); + int getType(); + std::string getUuid(); + + JNI::Object getObject() const { return _obj; } + + private: + JNI::Object _obj; + static JNI::Class _cls; + static jmethodID _method_addCharacteristic; + static jmethodID _method_addService; + static jmethodID _method_getCharacteristic; + static jmethodID _method_getCharacteristics; + static jmethodID _method_getIncludedServices; + static jmethodID _method_getInstanceId; + static jmethodID _method_getType; + static jmethodID _method_getUuid; + + void initialize(); +}; + +} // namespace Android +} // namespace SimpleBLE diff --git a/third_party/SimpleBLE/simpleble/src/backends/android/android/ScanResult.cpp b/third_party/SimpleBLE/simpleble/src/backends/android/android/ScanResult.cpp new file mode 100644 index 000000000..e4f125dc2 --- /dev/null +++ b/third_party/SimpleBLE/simpleble/src/backends/android/android/ScanResult.cpp @@ -0,0 +1,29 @@ + +#include "ScanResult.h" + +namespace SimpleBLE { +namespace Android { + +JNI::Class ScanResult::_cls; + +void ScanResult::initialize() { + JNI::Env env; + + if (_cls.get() == nullptr) { + _cls = env.find_class("android/bluetooth/le/ScanResult"); + } +} + +ScanResult::ScanResult(jobject j_scan_result) { + initialize(); + _obj = JNI::Object(j_scan_result, _cls.get()); +}; + +BluetoothDevice ScanResult::getDevice() { + return BluetoothDevice(_obj.call_object_method("getDevice", "()Landroid/bluetooth/BluetoothDevice;")); +} + +std::string ScanResult::toString() { return _obj.call_string_method("toString", "()Ljava/lang/String;"); } + +} // namespace Android +} // namespace SimpleBLE \ No newline at end of file diff --git a/third_party/SimpleBLE/simpleble/src/backends/android/android/ScanResult.h b/third_party/SimpleBLE/simpleble/src/backends/android/android/ScanResult.h new file mode 100644 index 000000000..9d32d90f5 --- /dev/null +++ b/third_party/SimpleBLE/simpleble/src/backends/android/android/ScanResult.h @@ -0,0 +1,25 @@ +#pragma once + +#include "jni/Common.hpp" + +#include "BluetoothDevice.h" + +namespace SimpleBLE { +namespace Android { + +class ScanResult { + public: + ScanResult(jobject j_scan_result); + + BluetoothDevice getDevice(); + std::string toString(); + + private: + static JNI::Class _cls; + static void initialize(); + + JNI::Object _obj; +}; + +} // namespace Android +} // namespace SimpleBLE diff --git a/third_party/SimpleBLE/simpleble/src/backends/android/android/UUID.cpp b/third_party/SimpleBLE/simpleble/src/backends/android/android/UUID.cpp new file mode 100644 index 000000000..36083b076 --- /dev/null +++ b/third_party/SimpleBLE/simpleble/src/backends/android/android/UUID.cpp @@ -0,0 +1,34 @@ +#include "UUID.h" + +namespace SimpleBLE { + namespace Android { + + JNI::Class UUID::_cls; + jmethodID UUID::_method_toString = nullptr; + + void UUID::initialize() { + JNI::Env env; + + if (_cls.get() == nullptr) { + _cls = env.find_class("java/util/UUID"); + } + + if (!_method_toString) { + _method_toString = env->GetMethodID(_cls.get(), "toString", "()Ljava/lang/String;"); + } + } + + UUID::UUID() { initialize(); } + + UUID::UUID(JNI::Object obj) : UUID() { + _obj = obj; + } + + std::string UUID::toString() { + if (!_obj) return ""; + + return _obj.call_string_method(_method_toString); + } + + } // Android +} // SimpleBLE \ No newline at end of file diff --git a/third_party/SimpleBLE/simpleble/src/backends/android/android/UUID.h b/third_party/SimpleBLE/simpleble/src/backends/android/android/UUID.h new file mode 100644 index 000000000..8b601bddd --- /dev/null +++ b/third_party/SimpleBLE/simpleble/src/backends/android/android/UUID.h @@ -0,0 +1,25 @@ +#pragma once + +#include "jni/Common.hpp" + +namespace SimpleBLE { + namespace Android { + + class UUID { + public: + UUID(); + UUID(JNI::Object obj); + + std::string toString(); + + private: + static JNI::Class _cls; + static jmethodID _method_toString; + + static void initialize(); + + JNI::Object _obj; + }; + + } // Android +} // SimpleBLE diff --git a/third_party/SimpleBLE/simpleble/src/backends/android/bridge/BluetoothGattCallback.cpp b/third_party/SimpleBLE/simpleble/src/backends/android/bridge/BluetoothGattCallback.cpp new file mode 100644 index 000000000..a977cf69f --- /dev/null +++ b/third_party/SimpleBLE/simpleble/src/backends/android/bridge/BluetoothGattCallback.cpp @@ -0,0 +1,410 @@ +#include "BluetoothGattCallback.h" +#include + +#include +#include +#include + +namespace SimpleBLE { +namespace Android { +namespace Bridge { + +JNI::Class BluetoothGattCallback::_cls; +std::map BluetoothGattCallback::_map; + +void BluetoothGattCallback::initialize() { + JNI::Env env; + + if (_cls.get() == nullptr) { + _cls = env.find_class("org/simpleble/android/bridge/BluetoothGattCallback"); + } +} + +BluetoothGattCallback::BluetoothGattCallback() : connected(false), mtu(UINT16_MAX) { + initialize(); + + _obj = _cls.call_constructor("()V"); + _map[_obj.get()] = this; +} + +BluetoothGattCallback::~BluetoothGattCallback() { _map.erase(_obj.get()); } + +void BluetoothGattCallback::set_callback_onConnectionStateChange(std::function callback) { + if (callback) { + _callback_onConnectionStateChange.load(callback); + } else { + _callback_onConnectionStateChange.unload(); + } +} + +void BluetoothGattCallback::set_callback_onServicesDiscovered(std::function callback) { + if (callback) { + _callback_onServicesDiscovered.load(callback); + } else { + _callback_onServicesDiscovered.unload(); + } +} + +void BluetoothGattCallback::set_callback_onCharacteristicChanged(JNI::Object characteristic, + std::function)> callback) { + if (callback) { + _callback_onCharacteristicChanged[characteristic].load(callback); + } else { + _callback_onCharacteristicChanged[characteristic].unload(); + } +} + +void BluetoothGattCallback::clear_callback_onCharacteristicChanged(JNI::Object characteristic) { + _callback_onCharacteristicChanged[characteristic].unload(); +} + +void BluetoothGattCallback::set_flag_characteristicWritePending(JNI::Object characteristic) { + auto& flag_data = _flag_characteristicWritePending[characteristic]; + + std::lock_guard lock(flag_data.mtx); + flag_data.flag = true; +} + +void BluetoothGattCallback::clear_flag_characteristicWritePending(JNI::Object characteristic) { + auto& flag_data = _flag_characteristicWritePending[characteristic]; + { + std::lock_guard lock(flag_data.mtx); + flag_data.flag = false; + } + flag_data.cv.notify_all(); +} + +void BluetoothGattCallback::wait_flag_characteristicWritePending(JNI::Object characteristic) { + auto& flag_data = _flag_characteristicWritePending[characteristic]; + std::unique_lock lock(flag_data.mtx); + flag_data.cv.wait_for(lock, std::chrono::seconds(5), [&flag_data] { return !flag_data.flag; }); + + if (flag_data.flag) { + // TODO CLEANUP + throw std::runtime_error("Failed to write characteristic"); + } + + // TODO CLEANUP +} + +void BluetoothGattCallback::set_flag_characteristicReadPending(JNI::Object characteristic) { + auto& flag_data = _flag_characteristicReadPending[characteristic]; + + std::lock_guard lock(flag_data.mtx); + flag_data.flag = true; +} + +void BluetoothGattCallback::clear_flag_characteristicReadPending(JNI::Object characteristic, + std::vector value) { + auto& flag_data = _flag_characteristicReadPending[characteristic]; + { + std::lock_guard lock(flag_data.mtx); + flag_data.flag = false; + flag_data.value = value; + } + flag_data.cv.notify_all(); +} + +std::vector BluetoothGattCallback::wait_flag_characteristicReadPending(JNI::Object characteristic) { + auto& flag_data = _flag_characteristicReadPending[characteristic]; + std::unique_lock lock(flag_data.mtx); + flag_data.cv.wait_for(lock, std::chrono::seconds(5), [&flag_data] { return !flag_data.flag; }); + + if (flag_data.flag) { + // TODO CLEANUP + throw std::runtime_error("Failed to read characteristic"); + } + + return flag_data.value; +} + +void BluetoothGattCallback::set_flag_descriptorWritePending(JNI::Object descriptor) { + auto& flag_data = _flag_descriptorWritePending[descriptor]; + + std::lock_guard lock(flag_data.mtx); + flag_data.flag = true; +} + +void BluetoothGattCallback::clear_flag_descriptorWritePending(JNI::Object descriptor) { + auto& flag_data = _flag_descriptorWritePending[descriptor]; + { + std::lock_guard lock(flag_data.mtx); + flag_data.flag = false; + } + flag_data.cv.notify_all(); +} + +void BluetoothGattCallback::wait_flag_descriptorWritePending(JNI::Object descriptor) { + auto& flag_data = _flag_descriptorWritePending[descriptor]; + std::unique_lock lock(flag_data.mtx); + flag_data.cv.wait_for(lock, std::chrono::seconds(5), [&flag_data] { return !flag_data.flag; }); + + if (flag_data.flag) { + // TODO CLEANUP + throw std::runtime_error("Failed to write descriptor"); + } + + // TODO CLEANUP +} + +void BluetoothGattCallback::set_flag_descriptorReadPending(JNI::Object descriptor) { + auto& flag_data = _flag_descriptorWritePending[descriptor]; + + std::lock_guard lock(flag_data.mtx); + flag_data.flag = true; +} + +void BluetoothGattCallback::clear_flag_descriptorReadPending(JNI::Object descriptor, std::vector value) { + auto& flag_data = _flag_descriptorWritePending[descriptor]; + { + std::lock_guard lock(flag_data.mtx); + flag_data.flag = false; + flag_data.value = value; + } + flag_data.cv.notify_all(); +} + +std::vector BluetoothGattCallback::wait_flag_descriptorReadPending(JNI::Object descriptor) { + auto& flag_data = _flag_descriptorWritePending[descriptor]; + std::unique_lock lock(flag_data.mtx); + flag_data.cv.wait_for(lock, std::chrono::seconds(5), [&flag_data] { return !flag_data.flag; }); + + if (flag_data.flag) { + // TODO CLEANUP + throw std::runtime_error("Failed to read descriptor"); + } + + return flag_data.value; +} + +void BluetoothGattCallback::jni_onConnectionStateChangeCallback(JNIEnv* env, jobject thiz, jobject gatt, jint status, + jint new_state) { + auto msg = fmt::format("onConnectionStateChangeCallback status: {} new_state: {}", status, new_state); + __android_log_write(ANDROID_LOG_INFO, "SimpleBLE", msg.c_str()); + + auto it = BluetoothGattCallback::_map.find(thiz); + if (it == BluetoothGattCallback::_map.end()) { + // TODO: Throw an exception + return; + } + + BluetoothGattCallback* obj = it->second; + const bool connected = new_state == 2; + obj->connected = connected; + SAFE_CALLBACK_CALL(obj->_callback_onConnectionStateChange, connected); +} + +void BluetoothGattCallback::jni_onServicesDiscoveredCallback(JNIEnv* env, jobject thiz, jobject gatt, jint status) { + auto msg = "onServicesDiscoveredCallback"; + __android_log_write(ANDROID_LOG_INFO, "SimpleBLE", msg); + + auto it = BluetoothGattCallback::_map.find(thiz); + if (it == BluetoothGattCallback::_map.end()) { + // TODO: Throw an exception + return; + } + + BluetoothGattCallback* obj = it->second; + obj->services_discovered = true; + SAFE_CALLBACK_CALL(obj->_callback_onServicesDiscovered); +} + +void BluetoothGattCallback::jni_onServiceChangedCallback(JNIEnv* env, jobject thiz, jobject gatt) { + // NOTE: If this one gets triggered we're kinda screwed. + auto msg = "onServiceChangedCallback"; + __android_log_write(ANDROID_LOG_INFO, "SimpleBLE", msg); + + auto it = BluetoothGattCallback::_map.find(thiz); + if (it == BluetoothGattCallback::_map.end()) { + // TODO: Throw an exception + return; + } +} + +void BluetoothGattCallback::jni_onCharacteristicChangedCallback(JNIEnv* env, jobject thiz, jobject gatt, + jobject characteristic, jbyteArray value) { + auto msg = "onCharacteristicChangedCallback"; + __android_log_write(ANDROID_LOG_INFO, "SimpleBLE", msg); + + auto it = BluetoothGattCallback::_map.find(thiz); + if (it == BluetoothGattCallback::_map.end()) { + // TODO: Throw an exception + return; + } + + BluetoothGattCallback* obj = it->second; + auto& callback = obj->_callback_onCharacteristicChanged[characteristic]; + if (callback) { + std::vector data = JNI::Types::fromJByteArray(value); + SAFE_CALLBACK_CALL(callback, data); + } +} + +void BluetoothGattCallback::jni_onCharacteristicReadCallback(JNIEnv* env, jobject thiz, jobject gatt, + jobject characteristic, jbyteArray value, jint status) { + auto msg = "onCharacteristicReadCallback"; + __android_log_write(ANDROID_LOG_INFO, "SimpleBLE", msg); + + auto it = BluetoothGattCallback::_map.find(thiz); + if (it == BluetoothGattCallback::_map.end()) { + // TODO: Throw an exception + return; + } + + BluetoothGattCallback* obj = it->second; + obj->clear_flag_characteristicReadPending(characteristic, JNI::Types::fromJByteArray(value)); +} + +void BluetoothGattCallback::jni_onCharacteristicWriteCallback(JNIEnv* env, jobject thiz, jobject gatt, + jobject characteristic, jint status) { + auto msg = "onCharacteristicWriteCallback"; + __android_log_write(ANDROID_LOG_INFO, "SimpleBLE", msg); + + auto it = BluetoothGattCallback::_map.find(thiz); + if (it == BluetoothGattCallback::_map.end()) { + // TODO: Throw an exception + return; + } + + BluetoothGattCallback* obj = it->second; + obj->clear_flag_characteristicWritePending(characteristic); +} + +void BluetoothGattCallback::jni_onDescriptorReadCallback(JNIEnv* env, jobject thiz, jobject gatt, jobject descriptor, + jbyteArray value, jint status) { + auto msg = "onDescriptorReadCallback"; + __android_log_write(ANDROID_LOG_INFO, "SimpleBLE", msg); + + auto it = BluetoothGattCallback::_map.find(thiz); + if (it == BluetoothGattCallback::_map.end()) { + // TODO: Throw an exception + return; + } + + BluetoothGattCallback* obj = it->second; + obj->clear_flag_descriptorReadPending(descriptor, JNI::Types::fromJByteArray(value)); +} + +void BluetoothGattCallback::jni_onDescriptorWriteCallback(JNIEnv* env, jobject thiz, jobject gatt, jobject descriptor, + jint status) { + auto msg = "onDescriptorWriteCallback"; + __android_log_write(ANDROID_LOG_INFO, "SimpleBLE", msg); + + auto it = BluetoothGattCallback::_map.find(thiz); + if (it == BluetoothGattCallback::_map.end()) { + // TODO: Throw an exception + return; + } + + BluetoothGattCallback* obj = it->second; + obj->clear_flag_descriptorWritePending(descriptor); +} + +void BluetoothGattCallback::jni_onMtuChangedCallback(JNIEnv* env, jobject thiz, jobject gatt, jint mtu, jint status) { + auto msg = "onMtuChangedCallback"; + __android_log_write(ANDROID_LOG_INFO, "SimpleBLE", msg); + + auto it = BluetoothGattCallback::_map.find(thiz); + if (it != BluetoothGattCallback::_map.end()) { + BluetoothGattCallback* obj = it->second; + obj->mtu = mtu; + } else { + // TODO: Throw an exception + } +} + +void BluetoothGattCallback::jni_onPhyReadCallback(JNIEnv* env, jobject thiz, jobject gatt, jint tx_phy, jint rx_phy, + jint status) { + auto msg = "onPhyReadCallback"; + __android_log_write(ANDROID_LOG_INFO, "SimpleBLE", msg); +} + +void BluetoothGattCallback::jni_onPhyUpdateCallback(JNIEnv* env, jobject thiz, jobject gatt, jint tx_phy, jint rx_phy, + jint status) { + auto msg = "onPhyUpdateCallback"; + __android_log_write(ANDROID_LOG_INFO, "SimpleBLE", msg); +} + +void BluetoothGattCallback::jni_onReadRemoteRssiCallback(JNIEnv* env, jobject thiz, jobject gatt, jint rssi, + jint status) { + auto msg = "onReadRemoteRssiCallback"; + __android_log_write(ANDROID_LOG_INFO, "SimpleBLE", msg); +} + +void BluetoothGattCallback::jni_onReliableWriteCompletedCallback(JNIEnv* env, jobject thiz, jobject gatt, jint status) { + auto msg = "onReliableWriteCompletedCallback"; + __android_log_write(ANDROID_LOG_INFO, "SimpleBLE", msg); +} + +} // namespace Bridge +} // namespace Android +} // namespace SimpleBLE + +extern "C" { +// clang-format off +JNIEXPORT void JNICALL Java_org_simpleble_android_bridge_BluetoothGattCallback_onCharacteristicChangedCallback( + JNIEnv* env, jobject thiz, jobject gatt, jobject characteristic, jbyteArray value) { + SimpleBLE::Android::Bridge::BluetoothGattCallback::jni_onCharacteristicChangedCallback(env, thiz, gatt, characteristic, value); +} + +JNIEXPORT void JNICALL Java_org_simpleble_android_bridge_BluetoothGattCallback_onCharacteristicReadCallback( + JNIEnv* env, jobject thiz, jobject gatt, jobject characteristic, jbyteArray value, jint status) { + SimpleBLE::Android::Bridge::BluetoothGattCallback::jni_onCharacteristicReadCallback(env, thiz, gatt, characteristic, value, status); +} + +JNIEXPORT void JNICALL Java_org_simpleble_android_bridge_BluetoothGattCallback_onCharacteristicWriteCallback( + JNIEnv* env, jobject thiz, jobject gatt, jobject characteristic, jint status) { + SimpleBLE::Android::Bridge::BluetoothGattCallback::jni_onCharacteristicWriteCallback(env, thiz, gatt, characteristic, status); +} + +JNIEXPORT void JNICALL Java_org_simpleble_android_bridge_BluetoothGattCallback_onConnectionStateChangeCallback( + JNIEnv* env, jobject thiz, jobject gatt, jint status, jint new_state) { + SimpleBLE::Android::Bridge::BluetoothGattCallback::jni_onConnectionStateChangeCallback(env, thiz, gatt, status, new_state); +} + +JNIEXPORT void JNICALL Java_org_simpleble_android_bridge_BluetoothGattCallback_onDescriptorReadCallback( + JNIEnv* env, jobject thiz, jobject gatt, jobject descriptor, jbyteArray value, jint status) { + SimpleBLE::Android::Bridge::BluetoothGattCallback::jni_onDescriptorReadCallback(env, thiz, gatt, descriptor, value, status); +} + +JNIEXPORT void JNICALL Java_org_simpleble_android_bridge_BluetoothGattCallback_onDescriptorWriteCallback( + JNIEnv* env, jobject thiz, jobject gatt, jobject descriptor, jint status) { + SimpleBLE::Android::Bridge::BluetoothGattCallback::jni_onDescriptorWriteCallback(env, thiz, gatt, descriptor, status); +} + +JNIEXPORT void JNICALL Java_org_simpleble_android_bridge_BluetoothGattCallback_onMtuChangedCallback( + JNIEnv* env, jobject thiz, jobject gatt, jint mtu, jint status) { + SimpleBLE::Android::Bridge::BluetoothGattCallback::jni_onMtuChangedCallback(env, thiz, gatt, mtu, status); +} + +JNIEXPORT void JNICALL Java_org_simpleble_android_bridge_BluetoothGattCallback_onPhyReadCallback( + JNIEnv* env, jobject thiz, jobject gatt, jint tx_phy, jint rx_phy, jint status) { + SimpleBLE::Android::Bridge::BluetoothGattCallback::jni_onPhyReadCallback(env, thiz, gatt, tx_phy, rx_phy, status); +} + +JNIEXPORT void JNICALL Java_org_simpleble_android_bridge_BluetoothGattCallback_onPhyUpdateCallback( + JNIEnv* env, jobject thiz, jobject gatt, jint tx_phy, jint rx_phy, jint status) { + SimpleBLE::Android::Bridge::BluetoothGattCallback::jni_onPhyUpdateCallback(env, thiz, gatt, tx_phy, rx_phy, status); +} + +JNIEXPORT void JNICALL Java_org_simpleble_android_bridge_BluetoothGattCallback_onReadRemoteRssiCallback( + JNIEnv* env, jobject thiz, jobject gatt, jint rssi, jint status) { + SimpleBLE::Android::Bridge::BluetoothGattCallback::jni_onReadRemoteRssiCallback(env, thiz, gatt, rssi, status); +} + +JNIEXPORT void JNICALL Java_org_simpleble_android_bridge_BluetoothGattCallback_onReliableWriteCompletedCallback( + JNIEnv* env, jobject thiz, jobject gatt, jint status) { + SimpleBLE::Android::Bridge::BluetoothGattCallback::jni_onReliableWriteCompletedCallback(env, thiz, gatt, status); +} + +JNIEXPORT void JNICALL Java_org_simpleble_android_bridge_BluetoothGattCallback_onServiceChangedCallback( + JNIEnv* env, jobject thiz, jobject gatt) { + SimpleBLE::Android::Bridge::BluetoothGattCallback::jni_onServiceChangedCallback(env, thiz, gatt); +} + +JNIEXPORT void JNICALL Java_org_simpleble_android_bridge_BluetoothGattCallback_onServicesDiscoveredCallback( + JNIEnv* env, jobject thiz, jobject gatt, jint status) { + SimpleBLE::Android::Bridge::BluetoothGattCallback::jni_onServicesDiscoveredCallback(env, thiz, gatt, status); +} +// clang-format on +} // extern "C" \ No newline at end of file diff --git a/third_party/SimpleBLE/simpleble/src/backends/android/bridge/BluetoothGattCallback.h b/third_party/SimpleBLE/simpleble/src/backends/android/bridge/BluetoothGattCallback.h new file mode 100644 index 000000000..ffad0e4a3 --- /dev/null +++ b/third_party/SimpleBLE/simpleble/src/backends/android/bridge/BluetoothGattCallback.h @@ -0,0 +1,95 @@ +#pragma once + +#include +#include +#include +#include +#include +#include "jni/Common.hpp" + +namespace SimpleBLE { +namespace Android { +namespace Bridge { + +class BluetoothGattCallback { + public: + BluetoothGattCallback(); + virtual ~BluetoothGattCallback(); + jobject get() { return _obj.get(); } // TODO: Remove once nothing uses this + + void set_callback_onConnectionStateChange(std::function callback); + void set_callback_onServicesDiscovered(std::function callback); + + void set_callback_onCharacteristicChanged(JNI::Object characteristic, + std::function value)> callback); + void clear_callback_onCharacteristicChanged(JNI::Object characteristic); + + void set_flag_characteristicWritePending(JNI::Object characteristic); + void clear_flag_characteristicWritePending(JNI::Object characteristic); + void wait_flag_characteristicWritePending(JNI::Object characteristic); + + void set_flag_characteristicReadPending(JNI::Object characteristic); + void clear_flag_characteristicReadPending(JNI::Object characteristic, std::vector value); + std::vector wait_flag_characteristicReadPending(JNI::Object characteristic); + + void set_flag_descriptorWritePending(JNI::Object descriptor); + void clear_flag_descriptorWritePending(JNI::Object descriptor); + void wait_flag_descriptorWritePending(JNI::Object descriptor); + + void set_flag_descriptorReadPending(JNI::Object descriptor); + void clear_flag_descriptorReadPending(JNI::Object descriptor, std::vector value); + std::vector wait_flag_descriptorReadPending(JNI::Object descriptor); + + bool connected; + bool services_discovered; + uint16_t mtu; + + // Not for public use + // clang-format off + static void jni_onConnectionStateChangeCallback(JNIEnv *env, jobject thiz, jobject gatt, jint status, jint new_state); + static void jni_onServicesDiscoveredCallback(JNIEnv *env, jobject thiz, jobject gatt, jint status); + static void jni_onServiceChangedCallback(JNIEnv *env, jobject thiz, jobject gatt); + + static void jni_onCharacteristicChangedCallback(JNIEnv *env, jobject thiz, jobject gatt, jobject characteristic, jbyteArray value); + static void jni_onCharacteristicReadCallback(JNIEnv *env, jobject thiz, jobject gatt, jobject characteristic, jbyteArray value, jint status); + static void jni_onCharacteristicWriteCallback(JNIEnv *env, jobject thiz, jobject gatt, jobject characteristic, jint status); + + static void jni_onDescriptorReadCallback(JNIEnv *env, jobject thiz, jobject gatt, jobject descriptor, jbyteArray value, jint status); + static void jni_onDescriptorWriteCallback(JNIEnv *env, jobject thiz, jobject gatt, jobject descriptor, jint status); + + static void jni_onMtuChangedCallback(JNIEnv *env, jobject thiz, jobject gatt, jint mtu, jint status); + static void jni_onPhyReadCallback(JNIEnv *env, jobject thiz, jobject gatt, jint txPhy, jint rxPhy, jint status); + static void jni_onPhyUpdateCallback(JNIEnv *env, jobject thiz, jobject gatt, jint txPhy, jint rxPhy, jint status); + static void jni_onReadRemoteRssiCallback(JNIEnv *env, jobject thiz, jobject gatt, jint rssi, jint status); + static void jni_onReliableWriteCompletedCallback(JNIEnv *env, jobject thiz, jobject gatt, jint status); + // clang-format on + + private: + struct FlagData { + bool flag; + std::condition_variable cv; + std::mutex mtx; + std::vector value; + }; + + static JNI::Class _cls; + static std::map _map; + static void initialize(); + + JNI::Object _obj; + + kvn::safe_callback _callback_onConnectionStateChange; + kvn::safe_callback _callback_onServicesDiscovered; + + std::map)>, JNI::JniObjectComparator> + _callback_onCharacteristicChanged; + + std::map _flag_characteristicWritePending; + std::map _flag_characteristicReadPending; + std::map _flag_descriptorWritePending; + std::map _flag_descriptorReadPending; +}; + +} // namespace Bridge +} // namespace Android +} // namespace SimpleBLE \ No newline at end of file diff --git a/third_party/SimpleBLE/simpleble/src/backends/android/bridge/ScanCallback.cpp b/third_party/SimpleBLE/simpleble/src/backends/android/bridge/ScanCallback.cpp new file mode 100644 index 000000000..4b65f4de8 --- /dev/null +++ b/third_party/SimpleBLE/simpleble/src/backends/android/bridge/ScanCallback.cpp @@ -0,0 +1,98 @@ +#include +#include +#include +#include "ScanCallback.h" + +namespace SimpleBLE { +namespace Android { +namespace Bridge { + +JNI::Class ScanCallback::_cls; +std::map ScanCallback::_map; + +void ScanCallback::initialize() { + JNI::Env env; + + if (_cls.get() == nullptr) { + _cls = env.find_class("org/simpleble/android/bridge/ScanCallback"); + } +} + +ScanCallback::ScanCallback() { + initialize(); + + _obj = _cls.call_constructor("()V"); + _map[_obj.get()] = this; +} + +ScanCallback::~ScanCallback() { + _map.erase(_obj.get()); +} + +void ScanCallback::set_callback_onScanResult(std::function callback) { + if (callback) { + _callback_onScanResult.load(callback); + } else { + _callback_onScanResult.unload(); + } +} + +void ScanCallback::set_callback_onBatchScanResults(std::function callback) { + if (callback) { + _callback_onBatchScanResults.load(callback); + } else { + _callback_onBatchScanResults.unload(); + } +} + +void ScanCallback::set_callback_onScanFailed(std::function callback) { + if (callback) { + _callback_onScanFailed.load(callback); + } else { + _callback_onScanFailed.unload(); + } +} + +void ScanCallback::jni_onScanResultCallback(JNIEnv *env, jobject thiz, jint callback_type, jobject j_scan_result) { + auto it = ScanCallback::_map.find(thiz); + if (it != ScanCallback::_map.end()) { + ScanCallback* obj = it->second; + Android::ScanResult scan_result(j_scan_result); + + auto msg = fmt::format("onScanResultCallback: {}", scan_result.toString()); + __android_log_write(ANDROID_LOG_INFO, "SimpleBLE", msg.c_str()); + + SAFE_CALLBACK_CALL(obj->_callback_onScanResult, scan_result); + } else { + // TODO: Throw an exception + } +} + +void ScanCallback::jni_onBatchScanResultsCallback(JNIEnv *env, jobject thiz, jobject results) { + __android_log_write(ANDROID_LOG_INFO, "SimpleBLE", "onBatchScanResultsCallback"); + // TODO: Implement +} + +void ScanCallback::jni_onScanFailedCallback(JNIEnv *env, jobject thiz, jint error_code) { + __android_log_write(ANDROID_LOG_INFO, "SimpleBLE", "onScanFailedCallback"); + // TODO: Implement +} + +} // namespace Bridge +} // namespace Android +} // namespace SimpleBLE + +extern "C" { +// clang-format off +JNIEXPORT void JNICALL Java_org_simpleble_android_bridge_ScanCallback_onScanResultCallback(JNIEnv *env, jobject thiz, jint callback_type, jobject result) { + SimpleBLE::Android::Bridge::ScanCallback::jni_onScanResultCallback(env, thiz, callback_type, result); +} + +JNIEXPORT void JNICALL Java_org_simpleble_android_bridge_ScanCallback_onScanFailedCallback(JNIEnv *env, jobject thiz, jint error_code) { + SimpleBLE::Android::Bridge::ScanCallback::jni_onScanFailedCallback(env, thiz, error_code); +} +JNIEXPORT void JNICALL Java_org_simpleble_android_bridge_ScanCallback_onBatchScanResultsCallback(JNIEnv *env, jobject thiz, jobject results) { + SimpleBLE::Android::Bridge::ScanCallback::jni_onBatchScanResultsCallback(env, thiz, results); +} +// clang-format on +} \ No newline at end of file diff --git a/third_party/SimpleBLE/simpleble/src/backends/android/bridge/ScanCallback.h b/third_party/SimpleBLE/simpleble/src/backends/android/bridge/ScanCallback.h new file mode 100644 index 000000000..2738e72e8 --- /dev/null +++ b/third_party/SimpleBLE/simpleble/src/backends/android/bridge/ScanCallback.h @@ -0,0 +1,41 @@ +#pragma once + +#include "jni/Common.hpp" +#include +#include "android/ScanResult.h" +#include + +namespace SimpleBLE { +namespace Android { +namespace Bridge { + +class ScanCallback { + public: + ScanCallback(); + virtual ~ScanCallback(); + jobject get() { return _obj.get(); } // TODO: Remove once nothing uses this + + void set_callback_onScanResult(std::function callback); + void set_callback_onBatchScanResults(std::function callback); + void set_callback_onScanFailed(std::function callback); + + // Not for public use + static void jni_onScanResultCallback(JNIEnv *env, jobject thiz, jint callback_type, jobject result); + static void jni_onBatchScanResultsCallback(JNIEnv *env, jobject thiz, jobject results); + static void jni_onScanFailedCallback(JNIEnv *env, jobject thiz, jint error_code); + + private: + static JNI::Class _cls; + static std::map _map; + static void initialize(); + + JNI::Object _obj; + + kvn::safe_callback _callback_onScanResult; + kvn::safe_callback _callback_onBatchScanResults; + kvn::safe_callback _callback_onScanFailed; +}; + +} // namespace Bridge +} // namespace Android +} // namespace SimpleBLE \ No newline at end of file diff --git a/third_party/SimpleBLE/simpleble/src/backends/android/jni/Common.hpp b/third_party/SimpleBLE/simpleble/src/backends/android/jni/Common.hpp new file mode 100644 index 000000000..0ef6c7757 --- /dev/null +++ b/third_party/SimpleBLE/simpleble/src/backends/android/jni/Common.hpp @@ -0,0 +1,321 @@ +#pragma once + +#include +#include +#include +#include + +#include "GlobalRef.hpp" +#include "VM.hpp" + +namespace SimpleBLE { +namespace JNI { + +// Forward declarations +class Class; + +class Object { + public: + Object() = default; + + Object(jobject obj) : _obj(obj) { + JNIEnv* env = VM::env(); + _cls = env->GetObjectClass(obj); + } + + Object(jobject obj, jclass cls) : _obj(obj), _cls(cls) {} + + jobject get() const { return _obj.get(); } + + explicit operator bool() const { + return _obj.get() != nullptr; + } + + jmethodID get_method(const char* name, const char* signature) { + JNIEnv* env = VM::env(); + return env->GetMethodID(_cls.get(), name, signature); + } + + template + Object call_object_method(jmethodID method, Args&&... args) { + JNIEnv* env = VM::env(); + jobject result = env->CallObjectMethod(_obj.get(), method, std::forward(args)...); + jclass resultClass = env->GetObjectClass(result); + return Object(result, resultClass); + } + + template + void call_void_method(jmethodID method, Args&&... args) { + JNIEnv* env = VM::env(); + env->CallVoidMethod(_obj.get(), method, std::forward(args)...); + } + + template + bool call_boolean_method(jmethodID method, Args&&... args) { + JNIEnv* env = VM::env(); + jboolean result = env->CallBooleanMethod(_obj.get(), method, std::forward(args)...); + return result; + } + + template + int call_int_method(jmethodID method, Args&&... args) { + JNIEnv* env = VM::env(); + jint result = env->CallIntMethod(_obj.get(), method, std::forward(args)...); + return result; + } + + template + std::string call_string_method(jmethodID method, Args&&... args) { + JNIEnv* env = VM::env(); + jstring jstr = (jstring)env->CallObjectMethod(_obj.get(), method, std::forward(args)...); + + if (jstr == nullptr) { + return ""; + } + + const char* c_str = env->GetStringUTFChars(jstr, nullptr); + std::string result(c_str); + env->ReleaseStringUTFChars(jstr, c_str); + return result; + } + + template + std::vector call_byte_array_method(jmethodID method, Args&&... args) { + JNIEnv* env = VM::env(); + jbyteArray jarr = (jbyteArray)env->CallObjectMethod(_obj.get(), method, std::forward(args)...); + + if (jarr == nullptr) { + return {}; + } + + jsize len = env->GetArrayLength(jarr); + jbyte* arr = env->GetByteArrayElements(jarr, nullptr); + + std::vector result(arr, arr + len); + + env->ReleaseByteArrayElements(jarr, arr, JNI_ABORT); + return result; + } + + + + template + Object call_object_method(const char* name, const char* signature, Args&&... args) { + JNIEnv* env = VM::env(); + + jmethodID method = env->GetMethodID(_cls.get(), name, signature); + jobject result = env->CallObjectMethod(_obj.get(), method, std::forward(args)...); + + jclass resultClass = env->GetObjectClass(result); + + return Object(result, resultClass); + } + + template + void call_void_method(const char* name, const char* signature, Args&&... args) { + JNIEnv* env = VM::env(); + + jmethodID method = env->GetMethodID(_cls.get(), name, signature); + env->CallVoidMethod(_obj.get(), method, std::forward(args)...); + } + + template + bool call_boolean_method(const char* name, const char* signature, Args&&... args) { + JNIEnv* env = VM::env(); + + jmethodID method = env->GetMethodID(_cls.get(), name, signature); + jboolean result = env->CallBooleanMethod(_obj.get(), method, std::forward(args)...); + + return result; + } + + template + int call_int_method(const char* name, const char* signature, Args&&... args) { + JNIEnv* env = VM::env(); + + jmethodID method = env->GetMethodID(_cls.get(), name, signature); + jint result = env->CallIntMethod(_obj.get(), method, std::forward(args)...); + + return result; + } + + template + std::string call_string_method(const char* name, const char* signature, Args&&... args) { + JNIEnv* env = VM::env(); + + jmethodID method = env->GetMethodID(_cls.get(), name, signature); + jstring jstr = (jstring)env->CallObjectMethod(_obj.get(), method, std::forward(args)...); + + if (jstr == nullptr) { + return ""; + } + + const char* c_str = env->GetStringUTFChars(jstr, nullptr); + std::string result(c_str); + env->ReleaseStringUTFChars(jstr, c_str); + return result; + } + + template + std::vector call_byte_array_method(const char* name, const char* signature, Args&&... args) { + JNIEnv* env = VM::env(); + + jmethodID method = env->GetMethodID(_cls.get(), name, signature); + jbyteArray jarr = (jbyteArray)env->CallObjectMethod(_obj.get(), method, std::forward(args)...); + + if (jarr == nullptr) { + return {}; + } + + jsize len = env->GetArrayLength(jarr); + jbyte* arr = env->GetByteArrayElements(jarr, nullptr); + + std::vector result(arr, arr + len); + + env->ReleaseByteArrayElements(jarr, arr, JNI_ABORT); + return result; + } + + private: + GlobalRef _obj; + GlobalRef _cls; +}; + +class Class { + public: + Class() = default; + Class(jclass cls) : _cls(cls) {} + + jclass get() { return _cls.get(); } + + template + Object call_static_method(const char* name, const char* signature, Args&&... args) { + JNIEnv* env = VM::env(); + + jmethodID method = env->GetStaticMethodID(_cls.get(), name, signature); + jobject obj = env->CallStaticObjectMethod(_cls.get(), method, std::forward(args)...); + + return Object(obj, _cls.get()); + } + + template + Object call_constructor(const char* signature, Args&&... args) { + JNIEnv* env = VM::env(); + + jmethodID method = env->GetMethodID(_cls.get(), "", signature); + jobject obj = env->NewObject(_cls.get(), method, std::forward(args)...); + + return Object(obj, _cls.get()); + } + + void register_natives(const JNINativeMethod* methods, int nMethods) { + JNIEnv* env = VM::env(); + env->RegisterNatives(_cls.get(), methods, nMethods); + } + + private: + GlobalRef _cls; +}; + +class Env { +public: + Env() { _env = VM::env(); } + virtual ~Env() = default; + Env(Env& other) = delete; // Remove the copy constructor + void operator=(const Env&) = delete; // Remove the copy assignment + + JNIEnv* operator->() { return _env; } + + Class find_class(const std::string& name) { + jclass jcls = _env->FindClass(name.c_str()); + if (jcls == nullptr) { + throw std::runtime_error("Failed to find class: " + name); + } + Class cls(jcls); + _env->DeleteLocalRef(jcls); + return cls; + } + +private: + JNIEnv* _env = nullptr; +}; + +// TODO: Move these to their own namespace + +struct JObjectComparator { + bool operator()(const jobject& lhs, const jobject& rhs) const { + if (lhs == nullptr && rhs == nullptr) { + return false; // Both are null, considered equal + } + if (lhs == nullptr) { + return true; // lhs is null, rhs is not null, lhs < rhs + } + if (rhs == nullptr) { + return false; // rhs is null, lhs is not null, lhs > rhs + } + + JNIEnv* env = VM::env(); + if (env->IsSameObject(lhs, rhs)) { + return false; // Both objects are the same + } + + // Use hashCode method to establish a consistent ordering + // TODO: Cache all references statically for this class! + jclass objectClass = env->FindClass("java/lang/Object"); + jmethodID hashCodeMethod = env->GetMethodID(objectClass, "hashCode", "()I"); + + const jobject lhsObject = lhs; + const jobject rhsObject = rhs; + + jint lhsHashCode = env->CallIntMethod(lhsObject, hashCodeMethod); + jint rhsHashCode = env->CallIntMethod(rhsObject, hashCodeMethod); + + return lhsHashCode < rhsHashCode; + + // Use a unique identifier or a pointer value as the final comparison for non-equal objects + return lhs < rhs; // This can still be used for consistent ordering + } +}; + +struct JniObjectComparator { + bool operator()(const Object& lhs, const Object& rhs) const { + // Handle null object comparisons + if (!lhs && !rhs) { + return false; // Both are null, considered equal + } + if (!lhs) { + return true; // lhs is null, rhs is not, lhs < rhs + } + if (!rhs) { + return false; // rhs is null, lhs is not, lhs > rhs + } + + JNIEnv* env = VM::env(); + + // Access the underlying jobject handles from Object instances + jobject lhsObject = lhs.get(); + jobject rhsObject = rhs.get(); + + // Check if both jobject handles refer to the same object + if (env->IsSameObject(lhsObject, rhsObject)) { + return false; // Both objects are the same + } + + // Use hashCode method to establish a consistent ordering + jclass objectClass = env->FindClass("java/lang/Object"); + jmethodID hashCodeMethod = env->GetMethodID(objectClass, "hashCode", "()I"); + + jint lhsHashCode = env->CallIntMethod(lhsObject, hashCodeMethod); + jint rhsHashCode = env->CallIntMethod(rhsObject, hashCodeMethod); + + if (lhsHashCode != rhsHashCode) { + return lhsHashCode < rhsHashCode; // Use hash code for initial comparison + } + + // Use a direct pointer comparison as a fallback for objects with identical hash codes + return lhsObject < rhsObject; // This comparison is consistent within the same execution + } +}; + +} // namespace JNI +} // namespace SimpleBLE diff --git a/third_party/SimpleBLE/simpleble/src/backends/android/jni/GlobalRef.hpp b/third_party/SimpleBLE/simpleble/src/backends/android/jni/GlobalRef.hpp new file mode 100644 index 000000000..5e528778b --- /dev/null +++ b/third_party/SimpleBLE/simpleble/src/backends/android/jni/GlobalRef.hpp @@ -0,0 +1,49 @@ +#pragma once + +#include + +#include "VM.hpp" + +namespace SimpleBLE { +namespace JNI { + +template +class GlobalRef { + public: + GlobalRef() = default; + + GlobalRef(T obj) {_obj = (T) VM::env()->NewGlobalRef(obj);} + + GlobalRef(const GlobalRef& other) { + // Custom copy constructor + _obj = (T) VM::env()->NewGlobalRef(other._obj); + } + + GlobalRef& operator=(const GlobalRef& other) { + // Custom copy assignment + if (this != &other) { + if (_obj != nullptr) { + VM::env()->DeleteGlobalRef(_obj); + } + _obj = (T) VM::env()->NewGlobalRef(other._obj); + } + return *this; + } + + ~GlobalRef() { + if (_obj != nullptr) { + VM::env()->DeleteGlobalRef(_obj); + _obj = nullptr; + } + } + + T* operator->() const { return &_obj; } + + T get() const { return _obj; } + + protected: + T _obj = nullptr; +}; + +} // namespace JNI +} // namespace SimpleBLE \ No newline at end of file diff --git a/third_party/SimpleBLE/simpleble/src/backends/android/jni/Types.h b/third_party/SimpleBLE/simpleble/src/backends/android/jni/Types.h new file mode 100644 index 000000000..b499c704b --- /dev/null +++ b/third_party/SimpleBLE/simpleble/src/backends/android/jni/Types.h @@ -0,0 +1,28 @@ +#pragma once + +#include +#include +#include "Common.hpp" + +namespace SimpleBLE { + namespace JNI { + namespace Types { + // TODO: Review the inline approach some time in the future. + inline jbyteArray toJByteArray(const std::vector& data) { + JNI::Env env; + jbyteArray array = env->NewByteArray(data.size()); + env->SetByteArrayRegion(array, 0, data.size(), (jbyte*) data.data()); + return array; + } + + inline std::vector fromJByteArray(jbyteArray array) { + JNI::Env env; + jsize length = env->GetArrayLength(array); + std::vector data(length); + env->GetByteArrayRegion(array, 0, length, (jbyte*) data.data()); + return data; + } + } + + } // namespace JNI +} \ No newline at end of file diff --git a/third_party/SimpleBLE/simpleble/src/backends/android/jni/VM.hpp b/third_party/SimpleBLE/simpleble/src/backends/android/jni/VM.hpp new file mode 100644 index 000000000..2c718413e --- /dev/null +++ b/third_party/SimpleBLE/simpleble/src/backends/android/jni/VM.hpp @@ -0,0 +1,46 @@ +#pragma once + +#include + +#include + +namespace SimpleBLE { +namespace JNI { + +// Generic class to handle the Java Virtual Machine (JVM) +class VM { + public: + static JavaVM* jvm() { + static std::mutex get_mutex; // Static mutex to ensure thread safety when accessing the logger + std::scoped_lock lock(get_mutex); // Unlock the mutex on function return + static VM instance; // Static instance of the logger to ensure proper lifecycle management + + if (instance._jvm == nullptr) { + jsize count; + if (JNI_GetCreatedJavaVMs(&instance._jvm, 1, &count) != JNI_OK || count == 0) { + throw std::runtime_error("Failed to get the Java Virtual Machine"); + } + } + return instance._jvm; + } + + static JNIEnv* env() { + JNIEnv* env = nullptr; + JavaVM* jvm = VM::jvm(); + if (jvm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6) != JNI_OK) { + throw std::runtime_error("Failed to get the JNIEnv"); + } + return env; + } + + private: + VM() = default; + virtual ~VM() = default; + VM(VM& other) = delete; // Remove the copy constructor + void operator=(const VM&) = delete; // Remove the copy assignment + + JavaVM* _jvm = nullptr; +}; + +} // namespace JNI +} // namespace SimpleBLE \ No newline at end of file diff --git a/third_party/SimpleBLE/simpleble/src/backends/android/simpleble-bridge/.gitignore b/third_party/SimpleBLE/simpleble/src/backends/android/simpleble-bridge/.gitignore new file mode 100644 index 000000000..aa724b770 --- /dev/null +++ b/third_party/SimpleBLE/simpleble/src/backends/android/simpleble-bridge/.gitignore @@ -0,0 +1,15 @@ +*.iml +.gradle +/local.properties +/.idea/caches +/.idea/libraries +/.idea/modules.xml +/.idea/workspace.xml +/.idea/navEditor.xml +/.idea/assetWizardSettings.xml +.DS_Store +/build +/captures +.externalNativeBuild +.cxx +local.properties diff --git a/third_party/SimpleBLE/simpleble/src/backends/android/simpleble-bridge/build.gradle.kts b/third_party/SimpleBLE/simpleble/src/backends/android/simpleble-bridge/build.gradle.kts new file mode 100644 index 000000000..9fd04ac00 --- /dev/null +++ b/third_party/SimpleBLE/simpleble/src/backends/android/simpleble-bridge/build.gradle.kts @@ -0,0 +1,17 @@ +plugins { + id("com.android.library") version "8.3.1" +} + +android { + namespace = "org.simpleble.android.bridge" + compileSdk = 34 + + defaultConfig { + minSdk = 31 + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + } +} diff --git a/third_party/SimpleBLE/simpleble/src/backends/android/simpleble-bridge/gradle/wrapper/gradle-wrapper.jar b/third_party/SimpleBLE/simpleble/src/backends/android/simpleble-bridge/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..033e24c4c Binary files /dev/null and b/third_party/SimpleBLE/simpleble/src/backends/android/simpleble-bridge/gradle/wrapper/gradle-wrapper.jar differ diff --git a/third_party/SimpleBLE/simpleble/src/backends/android/simpleble-bridge/gradle/wrapper/gradle-wrapper.properties b/third_party/SimpleBLE/simpleble/src/backends/android/simpleble-bridge/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..016e7baaf --- /dev/null +++ b/third_party/SimpleBLE/simpleble/src/backends/android/simpleble-bridge/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,8 @@ +#Sat Apr 27 07:27:16 PDT 2024 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/third_party/SimpleBLE/simpleble/src/backends/android/simpleble-bridge/gradlew b/third_party/SimpleBLE/simpleble/src/backends/android/simpleble-bridge/gradlew new file mode 100644 index 000000000..fcb6fca14 --- /dev/null +++ b/third_party/SimpleBLE/simpleble/src/backends/android/simpleble-bridge/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/third_party/SimpleBLE/simpleble/src/backends/android/simpleble-bridge/gradlew.bat b/third_party/SimpleBLE/simpleble/src/backends/android/simpleble-bridge/gradlew.bat new file mode 100644 index 000000000..93e3f59f1 --- /dev/null +++ b/third_party/SimpleBLE/simpleble/src/backends/android/simpleble-bridge/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/third_party/SimpleBLE/simpleble/src/backends/android/simpleble-bridge/settings.gradle.kts b/third_party/SimpleBLE/simpleble/src/backends/android/simpleble-bridge/settings.gradle.kts new file mode 100644 index 000000000..3a35432e1 --- /dev/null +++ b/third_party/SimpleBLE/simpleble/src/backends/android/simpleble-bridge/settings.gradle.kts @@ -0,0 +1,22 @@ +pluginManagement { + repositories { + google { + content { + includeGroupByRegex("com\\.android.*") + includeGroupByRegex("com\\.google.*") + includeGroupByRegex("androidx.*") + } + } + mavenCentral() + gradlePluginPortal() + } +} +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + } +} + +rootProject.name = "simpleble-bridge" diff --git a/third_party/SimpleBLE/simpleble/src/backends/android/simpleble-bridge/src/main/AndroidManifest.xml b/third_party/SimpleBLE/simpleble/src/backends/android/simpleble-bridge/src/main/AndroidManifest.xml new file mode 100644 index 000000000..0e0cf2a6c --- /dev/null +++ b/third_party/SimpleBLE/simpleble/src/backends/android/simpleble-bridge/src/main/AndroidManifest.xml @@ -0,0 +1,9 @@ + + + + + + + \ No newline at end of file diff --git a/third_party/SimpleBLE/simpleble/src/backends/android/simpleble-bridge/src/main/java/org/simpleble/android/bridge/BluetoothGattCallback.java b/third_party/SimpleBLE/simpleble/src/backends/android/simpleble-bridge/src/main/java/org/simpleble/android/bridge/BluetoothGattCallback.java new file mode 100644 index 000000000..87e84f7bb --- /dev/null +++ b/third_party/SimpleBLE/simpleble/src/backends/android/simpleble-bridge/src/main/java/org/simpleble/android/bridge/BluetoothGattCallback.java @@ -0,0 +1,141 @@ +package org.simpleble.android.bridge; + +import android.bluetooth.BluetoothGatt; +import android.bluetooth.BluetoothGattCharacteristic; +import android.bluetooth.BluetoothGattDescriptor; +import android.util.Log; + +public class BluetoothGattCallback extends android.bluetooth.BluetoothGattCallback { + + public BluetoothGattCallback() {} + + @Override + public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { + // NOTE: This method has been deprecated on API 33, but we're still using API 31, so we need to support this. + super.onCharacteristicChanged(gatt, characteristic); + onCharacteristicChangedCallback(gatt, characteristic, characteristic.getValue()); + } + + @Override + public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, byte[] value) { + // NOTE: This method is only available from API 33 onwards. + super.onCharacteristicChanged(gatt, characteristic, value); + onCharacteristicChangedCallback(gatt, characteristic, value); + } + + @Override + public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { + // NOTE: This method has been deprecated on API 33, but we're still using API 31, so we need to support this. + super.onCharacteristicRead(gatt, characteristic, status); + onCharacteristicReadCallback(gatt, characteristic, characteristic.getValue(), status); + } + + @Override + public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, byte[] value, int status) { + // NOTE: This method is only available from API 33 onwards. + super.onCharacteristicRead(gatt, characteristic, value, status); + onCharacteristicReadCallback(gatt, characteristic, value, status); + } + + @Override + public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { + super.onCharacteristicWrite(gatt, characteristic, status); + onCharacteristicWriteCallback(gatt, characteristic, status); + } + + @Override + public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { + super.onConnectionStateChange(gatt, status, newState); + onConnectionStateChangeCallback(gatt, status, newState); + } + + // NOTE: This method is only available from API 33 onwards + @Override + public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) { + // NOTE: This method has been deprecated on API 33, but we're still using API 31, so we need to support this. + super.onDescriptorRead(gatt, descriptor, status); + onDescriptorReadCallback(gatt, descriptor, descriptor.getValue(), status); + } + + @Override + public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status, byte[] value) { + // NOTE: This method is only available from API 33 onwards. + super.onDescriptorRead(gatt, descriptor, status, value); + onDescriptorReadCallback(gatt, descriptor, value, status); + } + + @Override + public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) { + super.onDescriptorWrite(gatt, descriptor, status); + onDescriptorWriteCallback(gatt, descriptor, status); + } + + @Override + public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) { + super.onMtuChanged(gatt, mtu, status); + onMtuChangedCallback(gatt, mtu, status); + } + + @Override + public void onPhyRead(BluetoothGatt gatt, int txPhy, int rxPhy, int status) { + super.onPhyRead(gatt, txPhy, rxPhy, status); + onPhyReadCallback(gatt, txPhy, rxPhy, status); + } + + @Override + public void onPhyUpdate(BluetoothGatt gatt, int txPhy, int rxPhy, int status) { + super.onPhyUpdate(gatt, txPhy, rxPhy, status); + onPhyUpdateCallback(gatt, txPhy, rxPhy, status); + } + + @Override + public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) { + super.onReadRemoteRssi(gatt, rssi, status); + onReadRemoteRssiCallback(gatt, rssi, status); + } + + @Override + public void onReliableWriteCompleted(BluetoothGatt gatt, int status) { + super.onReliableWriteCompleted(gatt, status); + onReliableWriteCompletedCallback(gatt, status); + } + + @Override + public void onServiceChanged(BluetoothGatt gatt) { + super.onServiceChanged(gatt); + onServiceChangedCallback(gatt); + } + + @Override + public void onServicesDiscovered(BluetoothGatt gatt, int status) { + super.onServicesDiscovered(gatt, status); + onServicesDiscoveredCallback(gatt, status); + } + + private native void onCharacteristicChangedCallback(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, byte[] value); + + private native void onCharacteristicReadCallback(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, byte[] value, int status); + + private native void onCharacteristicWriteCallback(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status); + + private native void onConnectionStateChangeCallback(BluetoothGatt gatt, int status, int newState); + + private native void onDescriptorReadCallback(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, byte[] value, int status); + + private native void onDescriptorWriteCallback(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status); + + private native void onMtuChangedCallback(BluetoothGatt gatt, int mtu, int status); + + private native void onPhyReadCallback(BluetoothGatt gatt, int txPhy, int rxPhy, int status); + + private native void onPhyUpdateCallback(BluetoothGatt gatt, int txPhy, int rxPhy, int status); + + private native void onReadRemoteRssiCallback(BluetoothGatt gatt, int rssi, int status); + + private native void onReliableWriteCompletedCallback(BluetoothGatt gatt, int status); + + private native void onServiceChangedCallback(BluetoothGatt gatt); + + private native void onServicesDiscoveredCallback(BluetoothGatt gatt, int status); +} + diff --git a/third_party/SimpleBLE/simpleble/src/backends/android/simpleble-bridge/src/main/java/org/simpleble/android/bridge/ScanCallback.java b/third_party/SimpleBLE/simpleble/src/backends/android/simpleble-bridge/src/main/java/org/simpleble/android/bridge/ScanCallback.java new file mode 100644 index 000000000..8db9817bd --- /dev/null +++ b/third_party/SimpleBLE/simpleble/src/backends/android/simpleble-bridge/src/main/java/org/simpleble/android/bridge/ScanCallback.java @@ -0,0 +1,36 @@ +package org.simpleble.android.bridge; + +import android.bluetooth.le.ScanResult; + +import java.util.List; +import android.util.Log; + +public class ScanCallback extends android.bluetooth.le.ScanCallback { + + public ScanCallback() {} + + @Override + public void onScanResult(int callbackType, ScanResult result) { + super.onScanResult(callbackType, result); + onScanResultCallback(callbackType, result); + } + + @Override + public void onBatchScanResults(List results) { + super.onBatchScanResults(results); + onBatchScanResultsCallback(results); + } + + @Override + public void onScanFailed(int errorCode) { + super.onScanFailed(errorCode); + onScanFailedCallback(errorCode); + } + + private native void onScanResultCallback(int callbackType, android.bluetooth.le.ScanResult result); + + private native void onScanFailedCallback(int errorCode); + + private native void onBatchScanResultsCallback(List results); + +} diff --git a/third_party/SimpleBLE/simpleble/src/backends/linux/AdapterBase.cpp b/third_party/SimpleBLE/simpleble/src/backends/linux/AdapterBase.cpp index 3b9bf32aa..cba3035bc 100644 --- a/third_party/SimpleBLE/simpleble/src/backends/linux/AdapterBase.cpp +++ b/third_party/SimpleBLE/simpleble/src/backends/linux/AdapterBase.cpp @@ -71,6 +71,9 @@ void AdapterBase::scan_start() { // Start scanning and notify the user. adapter_->discovery_start(); + + // TODO: Does a discovery filter need to be set? + SAFE_CALLBACK_CALL(this->callback_on_scan_start_); is_scanning_ = true; } diff --git a/third_party/SimpleBLE/simpleble/src/backends/linux/PeripheralBase.cpp b/third_party/SimpleBLE/simpleble/src/backends/linux/PeripheralBase.cpp index d8f511f16..e6917e6be 100644 --- a/third_party/SimpleBLE/simpleble/src/backends/linux/PeripheralBase.cpp +++ b/third_party/SimpleBLE/simpleble/src/backends/linux/PeripheralBase.cpp @@ -171,22 +171,14 @@ std::vector PeripheralBase::services() { std::vector PeripheralBase::advertised_services() { std::vector service_list; - for (auto& [service_uuid, value_array] : device_->service_data()) { - service_list.push_back( - ServiceBuilder(service_uuid, ByteArray((const char*)value_array.data(), value_array.size()))); + for (auto& service_uuid : device_->uuids()) { + service_list.push_back(ServiceBuilder(service_uuid)); } return service_list; } -std::map PeripheralBase::manufacturer_data() { - std::map manufacturer_data; - for (auto& [manufacturer_id, value_array] : device_->manufacturer_data()) { - manufacturer_data[manufacturer_id] = ByteArray((const char*)value_array.data(), value_array.size()); - } - - return manufacturer_data; -} +std::map PeripheralBase::manufacturer_data() { return device_->manufacturer_data(); } ByteArray PeripheralBase::read(BluetoothUUID const& service, BluetoothUUID const& characteristic) { // Check if the user is attempting to read the battery service/characteristic and if so, diff --git a/third_party/SimpleBLE/simpleble/src/backends/macos/PeripheralBase.mm b/third_party/SimpleBLE/simpleble/src/backends/macos/PeripheralBase.mm index 5577dc0d1..1c9301ea5 100644 --- a/third_party/SimpleBLE/simpleble/src/backends/macos/PeripheralBase.mm +++ b/third_party/SimpleBLE/simpleble/src/backends/macos/PeripheralBase.mm @@ -126,22 +126,22 @@ return [internal read:service_uuid characteristic_uuid:characteristic_uuid]; } -void PeripheralBase::write_request(BluetoothUUID const& service, BluetoothUUID const& characteristic, ByteArray const& data) { +void PeripheralBase::write_request(BluetoothUUID const& service, BluetoothUUID const& characteristic, ByteArray const& byte_array) { PeripheralBaseMacOS* internal = (__bridge PeripheralBaseMacOS*)opaque_internal_; NSString* service_uuid = [NSString stringWithCString:service.c_str() encoding:NSString.defaultCStringEncoding]; NSString* characteristic_uuid = [NSString stringWithCString:characteristic.c_str() encoding:NSString.defaultCStringEncoding]; - NSData* payload = [NSData dataWithBytes:(void*)data.c_str() length:data.size()]; + NSData* payload = [NSData dataWithBytes:(void*)byte_array.data() length:byte_array.size()]; [internal writeRequest:service_uuid characteristic_uuid:characteristic_uuid payload:payload]; } -void PeripheralBase::write_command(BluetoothUUID const& service, BluetoothUUID const& characteristic, ByteArray const& data) { +void PeripheralBase::write_command(BluetoothUUID const& service, BluetoothUUID const& characteristic, ByteArray const& byte_array) { PeripheralBaseMacOS* internal = (__bridge PeripheralBaseMacOS*)opaque_internal_; NSString* service_uuid = [NSString stringWithCString:service.c_str() encoding:NSString.defaultCStringEncoding]; NSString* characteristic_uuid = [NSString stringWithCString:characteristic.c_str() encoding:NSString.defaultCStringEncoding]; - NSData* payload = [NSData dataWithBytes:(void*)data.c_str() length:data.size()]; + NSData* payload = [NSData dataWithBytes:(void*)byte_array.data() length:byte_array.size()]; [internal writeCommand:service_uuid characteristic_uuid:characteristic_uuid payload:payload]; } @@ -183,13 +183,13 @@ } void PeripheralBase::write(BluetoothUUID const& service, BluetoothUUID const& characteristic, BluetoothUUID const& descriptor, - ByteArray const& data) { + ByteArray const& byte_array) { PeripheralBaseMacOS* internal = (__bridge PeripheralBaseMacOS*)opaque_internal_; NSString* service_uuid = [NSString stringWithCString:service.c_str() encoding:NSString.defaultCStringEncoding]; NSString* characteristic_uuid = [NSString stringWithCString:characteristic.c_str() encoding:NSString.defaultCStringEncoding]; NSString* descriptor_uuid = [NSString stringWithCString:descriptor.c_str() encoding:NSString.defaultCStringEncoding]; - NSData* payload = [NSData dataWithBytes:(void*)data.c_str() length:data.size()]; + NSData* payload = [NSData dataWithBytes:(void*)byte_array.data() length:byte_array.size()]; [internal write:service_uuid characteristic_uuid:characteristic_uuid descriptor_uuid:descriptor_uuid payload:payload]; } diff --git a/third_party/SimpleBLE/simpleble/src/backends/macos/PeripheralBaseMacOS.mm b/third_party/SimpleBLE/simpleble/src/backends/macos/PeripheralBaseMacOS.mm index a4262fd72..1fc66fcfa 100644 --- a/third_party/SimpleBLE/simpleble/src/backends/macos/PeripheralBaseMacOS.mm +++ b/third_party/SimpleBLE/simpleble/src/backends/macos/PeripheralBaseMacOS.mm @@ -213,12 +213,12 @@ - (void)connect { for (CBDescriptor* descriptor in characteristic.descriptors) { @synchronized(self) { [characteristicExtras.descriptorExtras setObject:[[DescriptorExtras alloc] init] - forKey:[[descriptor.UUID UUIDString] lowercaseString]]; + forKey:uuidToString(descriptor.UUID)]; } } @synchronized(self) { - [self.characteristicExtras setObject:characteristicExtras forKey:[[characteristic.UUID UUIDString] lowercaseString]]; + [self.characteristicExtras setObject:characteristicExtras forKey:uuidToString(characteristic.UUID)]; } } } @@ -627,7 +627,7 @@ - (void)peripheral:(CBPeripheral*)peripheral } - (void)peripheral:(CBPeripheral*)peripheral didUpdateValueForCharacteristic:(CBCharacteristic*)characteristic error:(NSError*)error { - CharacteristicExtras* characteristicExtras = [self.characteristicExtras objectForKey:[[characteristic.UUID UUIDString] lowercaseString]]; + CharacteristicExtras* characteristicExtras = [self.characteristicExtras objectForKey:uuidToString(characteristic.UUID)]; if (characteristic.isNotifying) { // If the characteristic is notifying, just save the value and trigger the callback. @@ -651,7 +651,7 @@ - (void)peripheral:(CBPeripheral*)peripheral didUpdateValueForCharacteristic:(CB } - (void)peripheral:(CBPeripheral*)peripheral didWriteValueForCharacteristic:(CBCharacteristic*)characteristic error:(NSError*)error { - CharacteristicExtras* characteristicExtras = [self.characteristicExtras objectForKey:[[characteristic.UUID UUIDString] lowercaseString]]; + CharacteristicExtras* characteristicExtras = [self.characteristicExtras objectForKey:uuidToString(characteristic.UUID)]; BleTask* task = characteristicExtras.task; @synchronized(self) { @@ -663,7 +663,7 @@ - (void)peripheral:(CBPeripheral*)peripheral didWriteValueForCharacteristic:(CBC - (void)peripheral:(CBPeripheral*)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic*)characteristic error:(NSError*)error { - CharacteristicExtras* characteristicExtras = [self.characteristicExtras objectForKey:[[characteristic.UUID UUIDString] lowercaseString]]; + CharacteristicExtras* characteristicExtras = [self.characteristicExtras objectForKey:uuidToString(characteristic.UUID)]; BleTask* task = characteristicExtras.task; @synchronized(self) { @@ -677,8 +677,8 @@ - (void)peripheralIsReadyToSendWriteWithoutResponse:(CBPeripheral*)peripheral { } - (void)peripheral:(CBPeripheral*)peripheral didUpdateValueForDescriptor:(CBDescriptor*)descriptor error:(NSError*)error { - CharacteristicExtras* characteristicExtras = [self.characteristicExtras objectForKey:[[descriptor.characteristic.UUID UUIDString] lowercaseString]]; - DescriptorExtras* descriptorExtras = [characteristicExtras.descriptorExtras objectForKey:[[descriptor.UUID UUIDString] lowercaseString]]; + CharacteristicExtras* characteristicExtras = [self.characteristicExtras objectForKey:uuidToString(descriptor.characteristic.UUID)]; + DescriptorExtras* descriptorExtras = [characteristicExtras.descriptorExtras objectForKey:uuidToString(descriptor.UUID)]; BleTask* task = descriptorExtras.task; @synchronized(self) { @@ -688,8 +688,8 @@ - (void)peripheral:(CBPeripheral*)peripheral didUpdateValueForDescriptor:(CBDesc } - (void)peripheral:(CBPeripheral*)peripheral didWriteValueForDescriptor:(CBDescriptor*)descriptor error:(NSError*)error { - CharacteristicExtras* characteristicExtras = [self.characteristicExtras objectForKey:[[descriptor.characteristic.UUID UUIDString] lowercaseString]]; - DescriptorExtras* descriptorExtras = [characteristicExtras.descriptorExtras objectForKey:[[descriptor.UUID UUIDString] lowercaseString]]; + CharacteristicExtras* characteristicExtras = [self.characteristicExtras objectForKey:uuidToString(descriptor.characteristic.UUID)]; + DescriptorExtras* descriptorExtras = [characteristicExtras.descriptorExtras objectForKey:uuidToString(descriptor.UUID)]; BleTask* task = descriptorExtras.task; @synchronized(self) { diff --git a/third_party/SimpleBLE/simpleble/src/backends/macos/Utils.h b/third_party/SimpleBLE/simpleble/src/backends/macos/Utils.h index 2773cd776..65c49caf2 100644 --- a/third_party/SimpleBLE/simpleble/src/backends/macos/Utils.h +++ b/third_party/SimpleBLE/simpleble/src/backends/macos/Utils.h @@ -6,3 +6,4 @@ #include SimpleBLE::BluetoothUUID uuidToSimpleBLE(CBUUID* uuid); +NSString* uuidToString(CBUUID* uuid); diff --git a/third_party/SimpleBLE/simpleble/src/backends/macos/Utils.mm b/third_party/SimpleBLE/simpleble/src/backends/macos/Utils.mm index 90485f181..d6ceb1825 100644 --- a/third_party/SimpleBLE/simpleble/src/backends/macos/Utils.mm +++ b/third_party/SimpleBLE/simpleble/src/backends/macos/Utils.mm @@ -11,3 +11,13 @@ return uuid_raw; } } + +NSString* uuidToString(CBUUID* uuid) { + NSString* uuidString = [[uuid UUIDString] lowercaseString]; + + if ([uuidString length] == 4) { + return [NSString stringWithFormat:@"0000%@-0000-1000-8000-00805f9b34fb", uuidString]; + } else { + return uuidString; + } +} diff --git a/third_party/SimpleBLE/simpleble/src/backends/plain/PeripheralBase.cpp b/third_party/SimpleBLE/simpleble/src/backends/plain/PeripheralBase.cpp index 479f8886c..69627180f 100644 --- a/third_party/SimpleBLE/simpleble/src/backends/plain/PeripheralBase.cpp +++ b/third_party/SimpleBLE/simpleble/src/backends/plain/PeripheralBase.cpp @@ -70,7 +70,7 @@ std::vector PeripheralBase::services() { std::vector PeripheralBase::advertised_services() { return {}; } -std::map PeripheralBase::manufacturer_data() { return {}; } +std::map PeripheralBase::manufacturer_data() { return {{0x004C, "test"}}; } ByteArray PeripheralBase::read(BluetoothUUID const& service, BluetoothUUID const& characteristic) { return {}; } @@ -81,12 +81,55 @@ void PeripheralBase::write_command(BluetoothUUID const& service, BluetoothUUID c ByteArray const& data) {} void PeripheralBase::notify(BluetoothUUID const& service, BluetoothUUID const& characteristic, - std::function callback) {} + std::function callback) { + if (callback) { + callback_mutex_.lock(); + callbacks_[{service, characteristic}] = std::move(callback); + callback_mutex_.unlock(); + + task_runner_.dispatch( + [this, service, characteristic]() -> std::optional { + std::lock_guard lock(callback_mutex_); + auto it = this->callbacks_.find({service, characteristic}); + + if (it == this->callbacks_.end()) { + return std::nullopt; + } + + it->second("Hello from notify"); + return 1s; + }, + 1s); + } +} void PeripheralBase::indicate(BluetoothUUID const& service, BluetoothUUID const& characteristic, - std::function callback) {} + std::function callback) { + if (callback) { + callback_mutex_.lock(); + callbacks_[{service, characteristic}] = std::move(callback); + callback_mutex_.unlock(); + + task_runner_.dispatch( + [this, service, characteristic]() -> std::optional { + std::lock_guard lock(callback_mutex_); + auto it = this->callbacks_.find({service, characteristic}); + + if (it == this->callbacks_.end()) { + return std::nullopt; + } + + it->second("Hello from notify"); + return 1s; + }, + 1s); + } +} -void PeripheralBase::unsubscribe(BluetoothUUID const& service, BluetoothUUID const& characteristic) {} +void PeripheralBase::unsubscribe(BluetoothUUID const& service, BluetoothUUID const& characteristic) { + std::lock_guard lock(callback_mutex_); + callbacks_.erase({service, characteristic}); +} ByteArray PeripheralBase::read(BluetoothUUID const& service, BluetoothUUID const& characteristic, BluetoothUUID const& descriptor) { diff --git a/third_party/SimpleBLE/simpleble/src/backends/plain/PeripheralBase.h b/third_party/SimpleBLE/simpleble/src/backends/plain/PeripheralBase.h index 434e79c9c..e19a1ad87 100644 --- a/third_party/SimpleBLE/simpleble/src/backends/plain/PeripheralBase.h +++ b/third_party/SimpleBLE/simpleble/src/backends/plain/PeripheralBase.h @@ -5,11 +5,13 @@ #include #include +#include #include #include #include #include +#include namespace SimpleBLE { @@ -59,6 +61,12 @@ class PeripheralBase { kvn::safe_callback callback_on_connected_; kvn::safe_callback callback_on_disconnected_; + + std::mutex callback_mutex_; + std::map, std::function> callbacks_; + + TaskRunner task_runner_; + }; } // namespace SimpleBLE diff --git a/third_party/SimpleBLE/simpleble/src/backends/windows/AdapterBase.cpp b/third_party/SimpleBLE/simpleble/src/backends/windows/AdapterBase.cpp index 7bd3951da..8296914f7 100644 --- a/third_party/SimpleBLE/simpleble/src/backends/windows/AdapterBase.cpp +++ b/third_party/SimpleBLE/simpleble/src/backends/windows/AdapterBase.cpp @@ -99,7 +99,7 @@ AdapterBase::AdapterBase(std::string device_id) (uint8_t)section_data_buffer[5], (uint8_t)section_data_buffer[4], (uint8_t)section_data_buffer[3], (uint8_t)section_data_buffer[2], (uint8_t)section_data_buffer[1], (uint8_t)section_data_buffer[0]); - service_data = section_data_buffer.substr(16); + service_data = section_data_buffer.slice_from(16); } else if (section.DataType() == @@ -107,12 +107,12 @@ AdapterBase::AdapterBase(std::string device_id) service_uuid = fmt::format("{:02x}{:02x}{:02x}{:02x}-0000-1000-8000-00805f9b34fb", (uint8_t)section_data_buffer[3], (uint8_t)section_data_buffer[2], (uint8_t)section_data_buffer[1], (uint8_t)section_data_buffer[0]); - service_data = section_data_buffer.substr(4); + service_data = section_data_buffer.slice_from(4); } else if (section.DataType() == Advertisement::BluetoothLEAdvertisementDataTypes::ServiceData16BitUuids()) { service_uuid = fmt::format("0000{:02x}{:02x}-0000-1000-8000-00805f9b34fb", (uint8_t)section_data_buffer[1], (uint8_t)section_data_buffer[0]); - service_data = section_data_buffer.substr(2); + service_data = section_data_buffer.slice_from(2); } else { continue; } diff --git a/third_party/SimpleBLE/simpleble/src/backends/windows/PeripheralBase.h b/third_party/SimpleBLE/simpleble/src/backends/windows/PeripheralBase.h index 030ce8493..c13bef7db 100644 --- a/third_party/SimpleBLE/simpleble/src/backends/windows/PeripheralBase.h +++ b/third_party/SimpleBLE/simpleble/src/backends/windows/PeripheralBase.h @@ -77,6 +77,8 @@ class PeripheralBase { void set_callback_on_connected(std::function on_connected); void set_callback_on_disconnected(std::function on_disconnected); + // Internal methods not exposed to the user. + void update_advertising_data(advertising_data_t advertising_data); private: diff --git a/third_party/SimpleBLE/simpleble/src/external/TaskRunner.hpp b/third_party/SimpleBLE/simpleble/src/external/TaskRunner.hpp new file mode 100644 index 000000000..e3475122f --- /dev/null +++ b/third_party/SimpleBLE/simpleble/src/external/TaskRunner.hpp @@ -0,0 +1,99 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +class TaskRunner { + private: + using Clock = std::chrono::steady_clock; + using TimePoint = Clock::time_point; + using Duration = Clock::duration; + using Task = std::function()>; + + struct ScheduledTask { + TimePoint executionTime; + Task task; + + bool operator>(const ScheduledTask& other) const { return executionTime > other.executionTime; } + }; + + std::priority_queue, std::greater> taskQueue; + std::mutex taskQueueMutex; + std::condition_variable taskQueueCV; + bool running = false; + std::thread workerThread; + + public: + TaskRunner() = default; + + ~TaskRunner() { stop(); } + + void start() { + if (!running) { + running = true; + workerThread = std::thread(&TaskRunner::workerLoop, this); + } + } + + void stop() { + if (running) { + { + std::unique_lock lock(taskQueueMutex); + running = false; + taskQueueCV.notify_one(); + } + workerThread.join(); + } + } + + void dispatch(Task task, Duration delay) { + TimePoint executionTime = Clock::now() + delay; + { + std::unique_lock lock(taskQueueMutex); + taskQueue.push({executionTime, std::move(task)}); + taskQueueCV.notify_one(); + } + if (!running) { + start(); + } + } + + private: + void workerLoop() { + while (true) { + std::unique_lock lock(taskQueueMutex); + taskQueueCV.wait(lock, [this] { return !running || !taskQueue.empty(); }); + + if (!running) { + break; + } + + if (taskQueue.empty()) { + continue; + } + + // NOTE: If a new task is added to the queue with a shorter delay than the current top task, the worker thread + // will not wake up until the top task's execution time is reached. This is not ideal, but it's good enough for + // this simple implementation. + + auto now = Clock::now(); + if (taskQueue.top().executionTime > now) { + taskQueueCV.wait_until(lock, taskQueue.top().executionTime); + } + + auto task = std::move(taskQueue.top().task); + taskQueue.pop(); + lock.unlock(); + + auto result = task(); + if (result.has_value()) { + dispatch(std::move(task), *result); + } + } + } +}; \ No newline at end of file diff --git a/third_party/SimpleBLE/simpleble/src/external/ThreadRunner.h b/third_party/SimpleBLE/simpleble/src/external/ThreadRunner.h new file mode 100644 index 000000000..b4f1c6a2b --- /dev/null +++ b/third_party/SimpleBLE/simpleble/src/external/ThreadRunner.h @@ -0,0 +1,54 @@ +#pragma once + +#include +#include +#include +#include +#include + +class ThreadRunner { +public: + ThreadRunner() : _stop(false) { + _thread = std::thread(&ThreadRunner::threadFunc, this); + } + + ~ThreadRunner() { + { + std::unique_lock lock(_mutex); + _stop = true; + _cv.notify_one(); + } + _thread.join(); + } + + void enqueue(std::function func) { + { + std::unique_lock lock(_mutex); + _queue.push(std::move(func)); + _cv.notify_one(); + } + } + +private: + void threadFunc() { + while (true) { + std::function func; + { + std::unique_lock lock(_mutex); + _cv.wait(lock, [this] { return _stop || !_queue.empty(); }); + if (_stop && _queue.empty()) { + return; + } + func = std::move(_queue.front()); + _queue.pop(); + } + func(); + } + } + + std::thread _thread; + std::mutex _mutex; + std::condition_variable _cv; + std::queue> _queue; + bool _stop; +}; diff --git a/third_party/SimpleBLE/simpleble/src_c/peripheral.cpp b/third_party/SimpleBLE/simpleble/src_c/peripheral.cpp index dcd8fb1f0..4995f3ba1 100644 --- a/third_party/SimpleBLE/simpleble/src_c/peripheral.cpp +++ b/third_party/SimpleBLE/simpleble/src_c/peripheral.cpp @@ -279,7 +279,7 @@ simpleble_err_t simpleble_peripheral_read(simpleble_peripheral_t handle, simpleb *data_length = read_data.value().size(); *data = static_cast(malloc(*data_length)); - memcpy(*data, read_data.value().c_str(), *data_length); + memcpy(*data, read_data.value().data(), *data_length); return SIMPLEBLE_SUCCESS; } @@ -318,7 +318,7 @@ simpleble_err_t simpleble_peripheral_write_command(simpleble_peripheral_t handle simpleble_err_t simpleble_peripheral_notify( simpleble_peripheral_t handle, simpleble_uuid_t service, simpleble_uuid_t characteristic, - void (*callback)(simpleble_uuid_t, simpleble_uuid_t, const uint8_t*, size_t, void*), void* userdata) { + void (*callback)(simpleble_peripheral_t,simpleble_uuid_t, simpleble_uuid_t, const uint8_t*, size_t, void*), void* userdata) { if (handle == nullptr || callback == nullptr) { return SIMPLEBLE_FAILURE; } @@ -327,7 +327,7 @@ simpleble_err_t simpleble_peripheral_notify( bool success = peripheral->notify(SimpleBLE::BluetoothUUID(service.value), SimpleBLE::BluetoothUUID(characteristic.value), [=](SimpleBLE::ByteArray data) { - callback(service, characteristic, (const uint8_t*)data.data(), data.size(), + callback(handle, service, characteristic, (const uint8_t*)data.data(), data.size(), userdata); }); @@ -336,7 +336,7 @@ simpleble_err_t simpleble_peripheral_notify( simpleble_err_t simpleble_peripheral_indicate( simpleble_peripheral_t handle, simpleble_uuid_t service, simpleble_uuid_t characteristic, - void (*callback)(simpleble_uuid_t, simpleble_uuid_t, const uint8_t*, size_t, void*), void* userdata) { + void (*callback)(simpleble_peripheral_t,simpleble_uuid_t, simpleble_uuid_t, const uint8_t*, size_t, void*), void* userdata) { if (handle == nullptr || callback == nullptr) { return SIMPLEBLE_FAILURE; } @@ -345,7 +345,7 @@ simpleble_err_t simpleble_peripheral_indicate( bool success = peripheral->indicate(SimpleBLE::BluetoothUUID(service.value), SimpleBLE::BluetoothUUID(characteristic.value), [=](SimpleBLE::ByteArray data) { - callback(service, characteristic, (const uint8_t*)data.data(), data.size(), + callback(handle, service, characteristic, (const uint8_t*)data.data(), data.size(), userdata); }); @@ -390,7 +390,7 @@ simpleble_err_t simpleble_peripheral_read_descriptor(simpleble_peripheral_t hand *data_length = read_data.value().size(); *data = static_cast(malloc(*data_length)); - memcpy(*data, read_data.value().c_str(), *data_length); + memcpy(*data, read_data.value().data(), *data_length); return SIMPLEBLE_SUCCESS; } diff --git a/third_party/SimpleBLE/simpleble/src_c/utils.cpp b/third_party/SimpleBLE/simpleble/src_c/utils.cpp index 5198eb523..89c5acbf9 100644 --- a/third_party/SimpleBLE/simpleble/src_c/utils.cpp +++ b/third_party/SimpleBLE/simpleble/src_c/utils.cpp @@ -12,4 +12,4 @@ simpleble_os_t simpleble_get_operating_system() { #endif } -const char* simpleble_get_version() { return "0.6.1"; } +const char* simpleble_get_version() { return SIMPLEBLE_VERSION; } diff --git a/third_party/SimpleBLE/simpleble/test/src/test_bytearray.cpp b/third_party/SimpleBLE/simpleble/test/src/test_bytearray.cpp new file mode 100644 index 000000000..6bcfd8647 --- /dev/null +++ b/third_party/SimpleBLE/simpleble/test/src/test_bytearray.cpp @@ -0,0 +1,246 @@ +#include +#include "external/kvn_bytearray.h" + +using namespace kvn; + +TEST(ByteArrayTest, DefaultConstructor) { + bytearray byteArray; + EXPECT_EQ(byteArray.size(), 0); +} + +TEST(ByteArrayTest, VectorConstructor) { + std::vector vec = {1, 2, 3, 4}; + bytearray byteArray(vec); + EXPECT_EQ(byteArray.size(), 4); + EXPECT_EQ(byteArray[0], 1); + EXPECT_EQ(byteArray[1], 2); + EXPECT_EQ(byteArray[2], 3); + EXPECT_EQ(byteArray[3], 4); +} + +TEST(ByteArrayTest, PointerConstructor) { + uint8_t data[] = {1, 2, 3, 4}; + bytearray byteArray(data, 4); + EXPECT_EQ(byteArray.size(), 4); + EXPECT_EQ(byteArray[0], 1); + EXPECT_EQ(byteArray[1], 2); + EXPECT_EQ(byteArray[2], 3); + EXPECT_EQ(byteArray[3], 4); +} + +TEST(ByteArrayTest, StringConstructor) { + std::string str = "Hello"; + bytearray byteArray(str); + EXPECT_EQ(byteArray.size(), 5); + EXPECT_EQ(byteArray[0], 'H'); + EXPECT_EQ(byteArray[1], 'e'); + EXPECT_EQ(byteArray[2], 'l'); + EXPECT_EQ(byteArray[3], 'l'); + EXPECT_EQ(byteArray[4], 'o'); +} + +TEST(ByteArrayTest, CharArrayConstructor) { + const char str[] = {'H', 'e', 'l', 'l', 'o'}; + bytearray byteArray(str, 5); + EXPECT_EQ(byteArray.size(), 5); + EXPECT_EQ(byteArray[0], 'H'); + EXPECT_EQ(byteArray[1], 'e'); + EXPECT_EQ(byteArray[2], 'l'); + EXPECT_EQ(byteArray[3], 'l'); + EXPECT_EQ(byteArray[4], 'o'); +} + +TEST(ByteArrayTest, CStringConstructor) { + const char* str = "Hello"; + bytearray byteArray(str); + EXPECT_EQ(byteArray.size(), 5); + EXPECT_EQ(byteArray[0], 'H'); + EXPECT_EQ(byteArray[1], 'e'); + EXPECT_EQ(byteArray[2], 'l'); + EXPECT_EQ(byteArray[3], 'l'); + EXPECT_EQ(byteArray[4], 'o'); +} + +TEST(ByteArrayTest, FromHexValid) { + bytearray byteArray = bytearray::fromHex("48656c6C6f"); + EXPECT_EQ(byteArray.size(), 5); + EXPECT_EQ(byteArray[0], 'H'); + EXPECT_EQ(byteArray[1], 'e'); + EXPECT_EQ(byteArray[2], 'l'); + EXPECT_EQ(byteArray[3], 'l'); + EXPECT_EQ(byteArray[4], 'o'); +} + +TEST(ByteArrayTest, FromHexValidWithPrefix) { + bytearray byteArray = bytearray::fromHex("0x48656c6C6f"); + EXPECT_EQ(byteArray.size(), 5); + EXPECT_EQ(byteArray[0], 'H'); + EXPECT_EQ(byteArray[1], 'e'); + EXPECT_EQ(byteArray[2], 'l'); + EXPECT_EQ(byteArray[3], 'l'); + EXPECT_EQ(byteArray[4], 'o'); +} + +TEST(ByteArrayTest, FromHexInvalid) { + EXPECT_THROW(bytearray::fromHex("123"), std::length_error); + EXPECT_THROW(bytearray::fromHex("G123"), std::invalid_argument); +} + +TEST(ByteArrayTest, ToHex) { + bytearray byteArray("Hello"); + EXPECT_EQ(byteArray.toHex(), "48656c6c6f"); + EXPECT_EQ(byteArray.toHex(true), "48 65 6c 6c 6f "); +} + +TEST(ByteArrayTest, StingConversion) { + bytearray byteArray = bytearray::fromHex("48656c6C6f"); + std::string str = static_cast(byteArray); + EXPECT_EQ(str, "Hello"); +} + +TEST(ByteArrayTest, StreamOperator) { + bytearray byteArray("Hello"); + std::ostringstream oss; + oss << byteArray; + EXPECT_EQ(oss.str(), "48 65 6c 6c 6f "); +} + +TEST(ByteArrayTest, DefaultConstructor_Empty) { + bytearray byteArray; + EXPECT_TRUE(byteArray.empty()); +} + +TEST(ByteArrayTest, PushBackIncreasesSize) { + bytearray byteArray; + byteArray.push_back(0x01); + EXPECT_EQ(1, byteArray.size()); + byteArray.push_back(0x02); + EXPECT_EQ(2, byteArray.size()); +} + +TEST(ByteArrayTest, ClearEmptiesArray) { + bytearray byteArray; + byteArray.push_back(0x01); + byteArray.push_back(0x02); + byteArray.clear(); + EXPECT_TRUE(byteArray.empty()); +} + +TEST(ByteArrayTest, IndexOperatorAccessesCorrectElement) { + bytearray byteArray; + byteArray.push_back(0x01); + byteArray.push_back(0x02); + EXPECT_EQ(0x01, byteArray[0]); + EXPECT_EQ(0x02, byteArray[1]); +} + +TEST(ByteArrayTest, DataPointerIsValid) { + bytearray byteArray; + byteArray.push_back(0x01); + byteArray.push_back(0x02); + const uint8_t* data_ptr = byteArray.data(); + ASSERT_NE(nullptr, data_ptr); + EXPECT_EQ(0x01, data_ptr[0]); + EXPECT_EQ(0x02, data_ptr[1]); +} + +TEST(ByteArrayTest, BeginEndIterators) { + bytearray byteArray; + byteArray.push_back(0x01); + byteArray.push_back(0x02); + auto it = byteArray.begin(); + EXPECT_EQ(0x01, *it); + ++it; + EXPECT_EQ(0x02, *it); + ++it; + EXPECT_EQ(byteArray.end(), it); +} + +TEST(ByteArrayTest, ConstIndexOperatorAccessesCorrectElement) { + bytearray byteArray; + byteArray.push_back(0x01); + byteArray.push_back(0x02); + const bytearray constByteArray = byteArray; + EXPECT_EQ(0x01, constByteArray[0]); + EXPECT_EQ(0x02, constByteArray[1]); +} + +TEST(ByteArrayTest, SliceValidRange) { + std::vector vec = {1, 2, 3, 4, 5}; + bytearray byteArray(vec); + bytearray slicedArray = byteArray.slice(1, 3); + + ASSERT_EQ(slicedArray.size(), 2); + EXPECT_EQ(slicedArray[0], 0x02); + EXPECT_EQ(slicedArray[1], 0x03); +} + +TEST(ByteArrayTest, SliceFullRange) { + std::vector vec = {1, 2, 3, 4, 5}; + bytearray byteArray(vec); + bytearray slicedArray = byteArray.slice(0, byteArray.size()); + + ASSERT_EQ(slicedArray.size(), byteArray.size()); + EXPECT_EQ(slicedArray[0], 0x01); + EXPECT_EQ(slicedArray[4], 0x05); +} + +TEST(ByteArrayTest, SliceSingleElement) { + std::vector vec = {1, 2, 3, 4, 5}; + bytearray byteArray(vec); + bytearray slicedArray = byteArray.slice(2, 3); + + ASSERT_EQ(slicedArray.size(), 1); + EXPECT_EQ(slicedArray[0], 0x03); +} + +TEST(ByteArrayTest, SliceOutOfRange) { + std::vector vec = {1, 2, 3, 4, 5}; + bytearray byteArray(vec); + + EXPECT_THROW(byteArray.slice(1, 6), std::out_of_range); + EXPECT_THROW(byteArray.slice(6, 7), std::out_of_range); +} + +TEST(ByteArrayTest, SliceInvalidRange) { + std::vector vec = {1, 2, 3, 4, 5}; + bytearray byteArray(vec); + + EXPECT_THROW(byteArray.slice(3, 2), std::out_of_range); +} + +TEST(ByteArrayTest, SliceFromIndexToEnd) { + std::vector vec = {1, 2, 3, 4, 5}; + bytearray byteArray(vec); + bytearray slicedArray = byteArray.slice_from(2); + + ASSERT_EQ(slicedArray.size(), 3); + EXPECT_EQ(slicedArray[0], 0x03); + EXPECT_EQ(slicedArray[1], 0x04); + EXPECT_EQ(slicedArray[2], 0x05); +} + +TEST(ByteArrayTest, SliceFromBeginningToIndex) { + std::vector vec = {1, 2, 3, 4, 5}; + bytearray byteArray(vec); + bytearray slicedArray = byteArray.slice_to(3); + + ASSERT_EQ(slicedArray.size(), 3); + EXPECT_EQ(slicedArray[0], 0x01); + EXPECT_EQ(slicedArray[1], 0x02); + EXPECT_EQ(slicedArray[2], 0x03); +} + +TEST(ByteArrayTest, SliceFromIndexToEndOutOfRange) { + std::vector vec = {1, 2, 3, 4, 5}; + bytearray byteArray(vec); + + EXPECT_THROW(byteArray.slice_from(6), std::out_of_range); +} + +TEST(ByteArrayTest, SliceFromBeginningToIndexOutOfRange) { + std::vector vec = {1, 2, 3, 4, 5}; + bytearray byteArray(vec); + + EXPECT_THROW(byteArray.slice_to(6), std::out_of_range); +} diff --git a/third_party/SimpleBLE/simplebluez/CMakeLists.txt b/third_party/SimpleBLE/simplebluez/CMakeLists.txt index 7a2847a0d..53cd80d83 100644 --- a/third_party/SimpleBLE/simplebluez/CMakeLists.txt +++ b/third_party/SimpleBLE/simplebluez/CMakeLists.txt @@ -1,5 +1,10 @@ cmake_minimum_required(VERSION 3.21) +# Only allow Linux builds +if(NOT CMAKE_HOST_SYSTEM_NAME STREQUAL "Linux") + message(FATAL_ERROR "-- [ERROR] UNSUPPORTED SYSTEM: '${CMAKE_HOST_SYSTEM_NAME}'. SimpleBluez can only be built on Linux.") +endif() + include(${CMAKE_CURRENT_SOURCE_DIR}/../cmake/prelude.cmake) project( @@ -16,6 +21,8 @@ include(${CMAKE_CURRENT_SOURCE_DIR}/../cmake/epilogue.cmake) option(LIBFMT_VENDORIZE "Enable vendorized libfmt" ON) find_package(fmt REQUIRED) +set_target_properties(fmt PROPERTIES EXCLUDE_FROM_ALL TRUE) + find_package(DBus1 REQUIRED) if(NOT DEFINED SIMPLEDBUS_SANITIZE AND DEFINED SIMPLEBLUEZ_SANITIZE) @@ -33,7 +40,8 @@ endif() set(SIMPLEBLUEZ_INCLUDE ${CMAKE_CURRENT_SOURCE_DIR}/include - ${CMAKE_CURRENT_SOURCE_DIR}/../simpledbus/include) + ${CMAKE_CURRENT_SOURCE_DIR}/../simpledbus/include + ${CMAKE_CURRENT_SOURCE_DIR}/../external/include) set(SIMPLEBLUEZ_SRC ${CMAKE_CURRENT_SOURCE_DIR}/src/ProxyOrg.cpp @@ -86,12 +94,17 @@ set_target_properties( list(APPEND PRIVATE_COMPILE_DEFINITIONS SIMPLEDBUS_LOG_LEVEL=${SIMPLEDBUS_LOG_LEVEL}) list(APPEND PRIVATE_COMPILE_DEFINITIONS SIMPLEBLUEZ_LOG_LEVEL=${SIMPLEBLUEZ_LOG_LEVEL}) +if(SIMPLEBLUEZ_USE_SESSION_DBUS) + list(APPEND PRIVATE_COMPILE_DEFINITIONS SIMPLEBLUEZ_USE_SESSION_DBUS) +endif() + target_link_libraries(simplebluez PUBLIC ${DBus1_LIBRARIES}) target_link_libraries(simplebluez PRIVATE $) target_include_directories(simplebluez PRIVATE ${SIMPLEBLUEZ_INCLUDE}) target_include_directories(simplebluez INTERFACE $ + $ $ $ $ @@ -126,6 +139,10 @@ install( DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/include/simplebluez/ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/simplebluez) +install( + DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/../external/include/ + DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/simplebluez) + install( DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/../simpledbus/include/simpledbus/ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/simpledbus) diff --git a/third_party/SimpleBLE/simplebluez/include/simplebluez/Device.h b/third_party/SimpleBLE/simplebluez/include/simplebluez/Device.h index 3cb9e3bf2..6f640f497 100644 --- a/third_party/SimpleBLE/simplebluez/include/simplebluez/Device.h +++ b/third_party/SimpleBLE/simplebluez/include/simplebluez/Device.h @@ -20,6 +20,7 @@ class Device : public SimpleDBus::Proxy { // ----- PROPERTIES ----- std::vector> services(); + std::vector uuids(); std::string address(); std::string address_type(); @@ -28,8 +29,8 @@ class Device : public SimpleDBus::Proxy { int16_t rssi(); int16_t tx_power(); - std::map> manufacturer_data(); - std::map> service_data(); + std::map manufacturer_data(); + std::map service_data(); bool paired(); bool connected(); diff --git a/third_party/SimpleBLE/simplebluez/include/simplebluez/Types.h b/third_party/SimpleBLE/simplebluez/include/simplebluez/Types.h index 346600291..acd1400a4 100644 --- a/third_party/SimpleBLE/simplebluez/include/simplebluez/Types.h +++ b/third_party/SimpleBLE/simplebluez/include/simplebluez/Types.h @@ -1,9 +1,9 @@ #pragma once -#include +#include "external/kvn_bytearray.h" namespace SimpleBluez { -typedef std::string ByteArray; +using ByteArray = kvn::bytearray; } diff --git a/third_party/SimpleBLE/simplebluez/include/simplebluez/interfaces/Device1.h b/third_party/SimpleBLE/simplebluez/include/simplebluez/interfaces/Device1.h index 1192536c6..8f9310a83 100644 --- a/third_party/SimpleBLE/simplebluez/include/simplebluez/interfaces/Device1.h +++ b/third_party/SimpleBLE/simplebluez/include/simplebluez/interfaces/Device1.h @@ -5,6 +5,8 @@ #include +#include "simplebluez/Types.h" + namespace SimpleBluez { class Device1 : public SimpleDBus::Interface { @@ -26,8 +28,9 @@ class Device1 : public SimpleDBus::Interface { std::string AddressType(); std::string Alias(); std::string Name(); - std::map> ManufacturerData(bool refresh = true); - std::map> ServiceData(bool refresh = true); + std::vector UUIDs(); + std::map ManufacturerData(bool refresh = true); + std::map ServiceData(bool refresh = true); bool Paired(bool refresh = true); bool Connected(bool refresh = true); bool ServicesResolved(bool refresh = true); @@ -47,8 +50,8 @@ class Device1 : public SimpleDBus::Interface { std::string _address_type; bool _connected; bool _services_resolved; - std::map> _manufacturer_data; - std::map> _service_data; + std::map _manufacturer_data; + std::map _service_data; }; } // namespace SimpleBluez diff --git a/third_party/SimpleBLE/simplebluez/src/Device.cpp b/third_party/SimpleBLE/simplebluez/src/Device.cpp index e03957c55..ce0f40cfe 100644 --- a/third_party/SimpleBLE/simplebluez/src/Device.cpp +++ b/third_party/SimpleBLE/simplebluez/src/Device.cpp @@ -2,6 +2,8 @@ #include #include +#include + using namespace SimpleBluez; Device::Device(std::shared_ptr conn, const std::string& bus_name, const std::string& path) @@ -10,8 +12,14 @@ Device::Device(std::shared_ptr conn, const std::string& Device::~Device() {} std::shared_ptr Device::path_create(const std::string& path) { - auto child = std::make_shared(_conn, _bus_name, path); - return std::static_pointer_cast(child); + const std::string next_child = SimpleDBus::Path::next_child_strip(_path, path); + + if (next_child.find("service") == 0) { + auto child = std::make_shared(_conn, _bus_name, path); + return std::static_pointer_cast(child); + } else { + return std::make_shared(_conn, _bus_name, path); + } } std::shared_ptr Device::interfaces_create(const std::string& interface_name) { @@ -33,7 +41,9 @@ std::shared_ptr Device::battery1() { return std::dynamic_pointer_cast(interface_get("org.bluez.Battery1")); } -std::vector> Device::services() { return children_casted(); } +std::vector> Device::services() { + return children_casted_with_prefix("service"); +} std::shared_ptr Device::get_service(const std::string& uuid) { auto services_all = services(); @@ -73,9 +83,11 @@ int16_t Device::rssi() { return device1()->RSSI(); } int16_t Device::tx_power() { return device1()->TxPower(); } -std::map> Device::manufacturer_data() { return device1()->ManufacturerData(); } +std::vector Device::uuids() { return device1()->UUIDs(); } + +std::map Device::manufacturer_data() { return device1()->ManufacturerData(); } -std::map> Device::service_data() { return device1()->ServiceData(); } +std::map Device::service_data() { return device1()->ServiceData(); } bool Device::paired() { return device1()->Paired(); } diff --git a/third_party/SimpleBLE/simplebluez/src/interfaces/Device1.cpp b/third_party/SimpleBLE/simplebluez/src/interfaces/Device1.cpp index 5f54f845a..0a5033b2f 100644 --- a/third_party/SimpleBLE/simplebluez/src/interfaces/Device1.cpp +++ b/third_party/SimpleBLE/simplebluez/src/interfaces/Device1.cpp @@ -62,7 +62,18 @@ std::string Device1::Name() { return _properties["Name"].get_string(); } -std::map> Device1::ManufacturerData(bool refresh) { +std::vector Device1::UUIDs() { + std::scoped_lock lock(_property_update_mutex); + + std::vector uuids; + for (SimpleDBus::Holder& uuid : _properties["UUIDs"].get_array()) { + uuids.push_back(uuid.get_string()); + } + + return uuids; +} + +std::map Device1::ManufacturerData(bool refresh) { if (refresh) { property_refresh("ManufacturerData"); } @@ -72,7 +83,7 @@ std::map> Device1::ManufacturerData(bool refresh) return _manufacturer_data; } -std::map> Device1::ServiceData(bool refresh) { +std::map Device1::ServiceData(bool refresh) { if (refresh) { property_refresh("ServiceData"); } @@ -125,7 +136,7 @@ void Device1::property_changed(std::string option_name) { std::map manuf_data = _properties["ManufacturerData"].get_dict_uint16(); // Loop through all received keys and store them. for (auto& [key, value_array] : manuf_data) { - std::vector raw_manuf_data; + ByteArray raw_manuf_data; for (auto& elem : value_array.get_array()) { raw_manuf_data.push_back(elem.get_byte()); } @@ -138,7 +149,7 @@ void Device1::property_changed(std::string option_name) { std::map service_data = _properties["ServiceData"].get_dict_string(); // Loop through all received keys and store them. for (auto& [key, value_array] : service_data) { - std::vector raw_service_data; + ByteArray raw_service_data; for (auto& elem : value_array.get_array()) { raw_service_data.push_back(elem.get_byte()); } diff --git a/third_party/SimpleBLE/simpledbus/CMakeLists.txt b/third_party/SimpleBLE/simpledbus/CMakeLists.txt index eb2ebeebd..8cf127a4a 100644 --- a/third_party/SimpleBLE/simpledbus/CMakeLists.txt +++ b/third_party/SimpleBLE/simpledbus/CMakeLists.txt @@ -1,5 +1,10 @@ cmake_minimum_required(VERSION 3.21) +# Only allow Linux builds +if(NOT CMAKE_HOST_SYSTEM_NAME STREQUAL "Linux") + message(FATAL_ERROR "-- [ERROR] UNSUPPORTED SYSTEM: '${CMAKE_HOST_SYSTEM_NAME}'. SimpleDBus can only be built on Linux.") +endif() + include(${CMAKE_CURRENT_SOURCE_DIR}/../cmake/prelude.cmake) project( @@ -16,6 +21,8 @@ include(${CMAKE_CURRENT_SOURCE_DIR}/../cmake/epilogue.cmake) option(LIBFMT_VENDORIZE "Enable vendorized libfmt" ON) find_package(fmt REQUIRED) +set_target_properties(fmt PROPERTIES EXCLUDE_FROM_ALL TRUE) + find_package(DBus1 REQUIRED) # Load all variables that would eventually need to be exposed to downstream projects @@ -109,6 +116,7 @@ if(SIMPLEDBUS_TEST) ${CMAKE_CURRENT_SOURCE_DIR}/test/src/test_message.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test/src/test_proxy_interfaces.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test/src/test_proxy_children.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/test/src/test_proxy_lifetime.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test/src/test_path.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test/src/helpers/PythonRunner.cpp) diff --git a/third_party/SimpleBLE/simpledbus/include/simpledbus/advanced/Proxy.h b/third_party/SimpleBLE/simpledbus/include/simpledbus/advanced/Proxy.h index e9c91e0cf..b0872b033 100644 --- a/third_party/SimpleBLE/simpledbus/include/simpledbus/advanced/Proxy.h +++ b/third_party/SimpleBLE/simpledbus/include/simpledbus/advanced/Proxy.h @@ -2,6 +2,7 @@ #include #include +#include #include #include @@ -63,6 +64,19 @@ class Proxy { return result; } + template + std::vector> children_casted_with_prefix(const std::string& prefix) { + std::vector> result; + std::scoped_lock lock(_child_access_mutex); + for (auto& [path, child] : _children) { + const std::string next_child = SimpleDBus::Path::next_child_strip(_path, path); + if (next_child.find(prefix) == 0) { + result.push_back(std::dynamic_pointer_cast(child)); + } + } + return result; + } + protected: bool _valid; std::string _path; diff --git a/third_party/SimpleBLE/simpledbus/include/simpledbus/base/Holder.h b/third_party/SimpleBLE/simpledbus/include/simpledbus/base/Holder.h index 177c0ea67..83c4d3817 100644 --- a/third_party/SimpleBLE/simpledbus/include/simpledbus/base/Holder.h +++ b/third_party/SimpleBLE/simpledbus/include/simpledbus/base/Holder.h @@ -8,6 +8,28 @@ namespace SimpleDBus { +class ObjectPath { + public: + ObjectPath(const std::string& path) : path(path) {} + ObjectPath(const char* path) : path(path) {} + operator std::string() const { return path; } + bool operator<(const ObjectPath& other) const { return path < other.path; } + + private: + std::string path; +}; + +class Signature { + public: + Signature(const std::string& signature) : signature(signature) {} + Signature(const char* signature) : signature(signature) {} + operator std::string() const { return signature; } + bool operator<(const Signature& other) const { return signature < other.signature; } + + private: + std::string signature; +}; + class Holder; class Holder { @@ -40,6 +62,7 @@ class Holder { std::string represent(); std::string signature(); + // TODO: Deprecate these functions in favor of templated version. static Holder create_boolean(bool value); static Holder create_byte(uint8_t value); static Holder create_int16(int16_t value); @@ -50,12 +73,14 @@ class Holder { static Holder create_uint64(uint64_t value); static Holder create_double(double value); static Holder create_string(const std::string& str); - static Holder create_object_path(const std::string& str); - static Holder create_signature(const std::string& str); + static Holder create_object_path(const ObjectPath& path); + static Holder create_signature(const Signature& signature); static Holder create_array(); static Holder create_dict(); std::any get_contents() const; + + // TODO: Deprecate these functions in favor of templated version. bool get_boolean() const; uint8_t get_byte() const; int16_t get_int16() const; @@ -83,6 +108,16 @@ class Holder { void dict_append(Type key_type, std::any key, Holder value); void array_append(Holder holder); + // Template speciallizations. + template + static Holder create(); + + template + static Holder create(T value); + + template + T get() const; + private: Type _type = NONE; diff --git a/third_party/SimpleBLE/simpledbus/include/simpledbus/base/Path.h b/third_party/SimpleBLE/simpledbus/include/simpledbus/base/Path.h index 549f3ffcb..450ab80f4 100644 --- a/third_party/SimpleBLE/simpledbus/include/simpledbus/base/Path.h +++ b/third_party/SimpleBLE/simpledbus/include/simpledbus/base/Path.h @@ -18,6 +18,7 @@ class Path { static bool is_parent(const std::string& base, const std::string& path); static std::string next_child(const std::string& base, const std::string& path); + static std::string next_child_strip(const std::string& base, const std::string& path); }; } // namespace SimpleDBus diff --git a/third_party/SimpleBLE/simpledbus/src/base/Holder.cpp b/third_party/SimpleBLE/simpledbus/src/base/Holder.cpp index 24af1344a..d2cfc6558 100644 --- a/third_party/SimpleBLE/simpledbus/src/base/Holder.cpp +++ b/third_party/SimpleBLE/simpledbus/src/base/Holder.cpp @@ -416,16 +416,16 @@ Holder Holder::create_string(const std::string& str) { h.holder_string = str; return h; } -Holder Holder::create_object_path(const std::string& str) { +Holder Holder::create_object_path(const ObjectPath& path) { Holder h; h._type = OBJ_PATH; - h.holder_string = str; + h.holder_string = path; return h; } -Holder Holder::create_signature(const std::string& str) { +Holder Holder::create_signature(const Signature& signature) { Holder h; h._type = SIGNATURE; - h.holder_string = str; + h.holder_string = signature; return h; } Holder Holder::create_array() { @@ -441,6 +441,76 @@ Holder Holder::create_dict() { return h; } +template <> +Holder Holder::create(bool value) { + return create_boolean(value); +} + +template <> +Holder Holder::create(uint8_t value) { + return create_byte(value); +} + +template <> +Holder Holder::create(int16_t value) { + return create_int16(value); +} + +template <> +Holder Holder::create(uint16_t value) { + return create_uint16(value); +} + +template <> +Holder Holder::create(int32_t value) { + return create_int32(value); +} + +template <> +Holder Holder::create(uint32_t value) { + return create_uint32(value); +} + +template <> +Holder Holder::create(int64_t value) { + return create_int64(value); +} + +template <> +Holder Holder::create(uint64_t value) { + return create_uint64(value); +} + +template <> +Holder Holder::create(double value) { + return create_double(value); +} + +template <> +Holder Holder::create(const std::string& value) { + return create_string(value); +} + +template <> +Holder Holder::create(const ObjectPath& value) { + return create_object_path(value); +} + +template <> +Holder Holder::create(const Signature& value) { + return create_signature(value); +} + +template <> +Holder Holder::create>() { + return create_array(); +} + +template <> +Holder Holder::create>() { + return create_dict(); +} + std::any Holder::get_contents() const { // Only return the contents for simple types switch (_type) { @@ -519,6 +589,123 @@ std::map Holder::get_dict_object_path() const { return _get std::map Holder::get_dict_signature() const { return _get_dict(SIGNATURE); } +template <> +bool Holder::get() const { + return get_boolean(); +} + +template <> +uint8_t Holder::get() const { + return get_byte(); +} + +template <> +int16_t Holder::get() const { + return get_int16(); +} + +template <> +uint16_t Holder::get() const { + return get_uint16(); +} + +template <> +int32_t Holder::get() const { + return get_int32(); +} + +template <> +uint32_t Holder::get() const { + return get_uint32(); +} + +template <> +int64_t Holder::get() const { + return get_int64(); +} + +template <> +uint64_t Holder::get() const { + return get_uint64(); +} + +template <> +double Holder::get() const { + return get_double(); +} + +template <> +std::string Holder::get() const { + return get_string(); +} + +template <> +std::vector Holder::get() const { + return get_array(); +} + +template <> +std::map Holder::get() const { + return get_dict_uint8(); +} + +template <> +std::map Holder::get() const { + return get_dict_uint16(); +} + +template <> +std::map Holder::get() const { + return get_dict_uint32(); +} + +template <> +std::map Holder::get() const { + return get_dict_uint64(); +} + +template <> +std::map Holder::get() const { + return get_dict_int16(); +} + +template <> +std::map Holder::get() const { + return get_dict_int32(); +} + +template <> +std::map Holder::get() const { + return get_dict_int64(); +} + +template <> +std::map Holder::get() const { + return get_dict_string(); +} + +template <> +std::map Holder::get() const { + std::map output; + for (auto& [key_type_internal, key, value] : holder_dict) { + if (key_type_internal == OBJ_PATH) { + output[ObjectPath(std::any_cast(key))] = value; + } + } + return output; +} + +template <> +std::map Holder::get() const { + std::map output; + for (auto& [key_type_internal, key, value] : holder_dict) { + if (key_type_internal == SIGNATURE) { + output[Signature(std::any_cast(key))] = value; + } + } + return output; +} + void Holder::array_append(Holder holder) { holder_array.push_back(holder); } void Holder::dict_append(Type key_type, std::any key, Holder value) { diff --git a/third_party/SimpleBLE/simpledbus/src/base/Path.cpp b/third_party/SimpleBLE/simpledbus/src/base/Path.cpp index 4082fc90c..4e231683e 100644 --- a/third_party/SimpleBLE/simpledbus/src/base/Path.cpp +++ b/third_party/SimpleBLE/simpledbus/src/base/Path.cpp @@ -121,4 +121,9 @@ std::string Path::next_child(const std::string& base, const std::string& path) { return fetch_elements(path, count_elements(base) + 1); } +std::string Path::next_child_strip(const std::string& base, const std::string& path) { + const std::string child = next_child(base, path); + return child.substr(base.length() + 1); +} + } // namespace SimpleDBus diff --git a/third_party/SimpleBLE/simpledroidble/.gitignore b/third_party/SimpleBLE/simpledroidble/.gitignore new file mode 100644 index 000000000..aa724b770 --- /dev/null +++ b/third_party/SimpleBLE/simpledroidble/.gitignore @@ -0,0 +1,15 @@ +*.iml +.gradle +/local.properties +/.idea/caches +/.idea/libraries +/.idea/modules.xml +/.idea/workspace.xml +/.idea/navEditor.xml +/.idea/assetWizardSettings.xml +.DS_Store +/build +/captures +.externalNativeBuild +.cxx +local.properties diff --git a/third_party/SimpleBLE/simpledroidble/build.gradle.kts b/third_party/SimpleBLE/simpledroidble/build.gradle.kts new file mode 100644 index 000000000..001c1b800 --- /dev/null +++ b/third_party/SimpleBLE/simpledroidble/build.gradle.kts @@ -0,0 +1,5 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. +plugins { + alias(libs.plugins.jetbrainsKotlinAndroid) apply false + alias(libs.plugins.androidLibrary) apply false +} \ No newline at end of file diff --git a/third_party/SimpleBLE/simpledroidble/gradle.properties b/third_party/SimpleBLE/simpledroidble/gradle.properties new file mode 100644 index 000000000..20e2a0152 --- /dev/null +++ b/third_party/SimpleBLE/simpledroidble/gradle.properties @@ -0,0 +1,23 @@ +# Project-wide Gradle settings. +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. For more details, visit +# https://developer.android.com/r/tools/gradle-multi-project-decoupled-projects +# org.gradle.parallel=true +# AndroidX package structure to make it clearer which packages are bundled with the +# Android operating system, and which are packaged with your app's APK +# https://developer.android.com/topic/libraries/support-library/androidx-rn +android.useAndroidX=true +# Kotlin code style for this project: "official" or "obsolete": +kotlin.code.style=official +# Enables namespacing of each library's R class so that its R class includes only the +# resources declared in the library itself and none from the library's dependencies, +# thereby reducing the size of the R class for that library +android.nonTransitiveRClass=true \ No newline at end of file diff --git a/third_party/SimpleBLE/simpledroidble/gradle/libs.versions.toml b/third_party/SimpleBLE/simpledroidble/gradle/libs.versions.toml new file mode 100644 index 000000000..612a7bd0b --- /dev/null +++ b/third_party/SimpleBLE/simpledroidble/gradle/libs.versions.toml @@ -0,0 +1,15 @@ +[versions] +agp = "8.3.1" +kotlin = "1.9.23" +coreKtx = "1.12.0" +appcompat = "1.6.1" +material = "1.11.0" + +[libraries] +androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" } +androidx-appcompat = { group = "androidx.appcompat", name = "appcompat", version.ref = "appcompat" } +material = { group = "com.google.android.material", name = "material", version.ref = "material" } + +[plugins] +jetbrainsKotlinAndroid = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" } +androidLibrary = { id = "com.android.library", version.ref = "agp" } \ No newline at end of file diff --git a/third_party/SimpleBLE/simpledroidble/gradle/wrapper/gradle-wrapper.jar b/third_party/SimpleBLE/simpledroidble/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..e708b1c02 Binary files /dev/null and b/third_party/SimpleBLE/simpledroidble/gradle/wrapper/gradle-wrapper.jar differ diff --git a/third_party/SimpleBLE/simpledroidble/gradle/wrapper/gradle-wrapper.properties b/third_party/SimpleBLE/simpledroidble/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..48f2233cc --- /dev/null +++ b/third_party/SimpleBLE/simpledroidble/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue Apr 02 22:24:45 PDT 2024 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/third_party/SimpleBLE/simpledroidble/gradlew b/third_party/SimpleBLE/simpledroidble/gradlew new file mode 100644 index 000000000..4f906e0c8 --- /dev/null +++ b/third_party/SimpleBLE/simpledroidble/gradlew @@ -0,0 +1,185 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/third_party/SimpleBLE/simpledroidble/gradlew.bat b/third_party/SimpleBLE/simpledroidble/gradlew.bat new file mode 100644 index 000000000..107acd32c --- /dev/null +++ b/third_party/SimpleBLE/simpledroidble/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/third_party/SimpleBLE/simpledroidble/settings.gradle.kts b/third_party/SimpleBLE/simpledroidble/settings.gradle.kts new file mode 100644 index 000000000..eb11b9c51 --- /dev/null +++ b/third_party/SimpleBLE/simpledroidble/settings.gradle.kts @@ -0,0 +1,29 @@ +pluginManagement { + repositories { + google { + content { + includeGroupByRegex("com\\.android.*") + includeGroupByRegex("com\\.google.*") + includeGroupByRegex("androidx.*") + } + } + mavenCentral() + gradlePluginPortal() + } +} +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + } +} + +rootProject.name = "SimpleDroidBle" + +includeBuild("../simpleble/src/backends/android/simpleble-bridge") { + dependencySubstitution { + substitute(module("org.simpleble.android.bridge:simpleble-bridge")).using(project(":")) + } +} +include(":simpledroidble") diff --git a/third_party/SimpleBLE/simpledroidble/simpledroidble/.gitignore b/third_party/SimpleBLE/simpledroidble/simpledroidble/.gitignore new file mode 100644 index 000000000..42afabfd2 --- /dev/null +++ b/third_party/SimpleBLE/simpledroidble/simpledroidble/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/third_party/SimpleBLE/simpledroidble/simpledroidble/build.gradle.kts b/third_party/SimpleBLE/simpledroidble/simpledroidble/build.gradle.kts new file mode 100644 index 000000000..6b98e4965 --- /dev/null +++ b/third_party/SimpleBLE/simpledroidble/simpledroidble/build.gradle.kts @@ -0,0 +1,52 @@ +plugins { + alias(libs.plugins.androidLibrary) + alias(libs.plugins.jetbrainsKotlinAndroid) +} + +android { + namespace = "org.simpleble.android" + compileSdk = 34 + + defaultConfig { + minSdk = 31 + + consumerProguardFiles("consumer-rules.pro") + externalNativeBuild { + cmake { + cppFlags("") + } + } + } + + buildTypes { + release { + isMinifyEnabled = false + proguardFiles( + getDefaultProguardFile("proguard-android-optimize.txt"), + "proguard-rules.pro" + ) + } + } + externalNativeBuild { + cmake { + path("src/main/cpp/CMakeLists.txt") + version = "3.22.1" + } + } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + } + kotlinOptions { + jvmTarget = "1.8" + } +} + +dependencies { + implementation(libs.androidx.core.ktx) + implementation(libs.androidx.appcompat) + implementation(libs.material) + + //noinspection UseTomlInstead + implementation("org.simpleble.android.bridge:simpleble-bridge") +} \ No newline at end of file diff --git a/third_party/SimpleBLE/simpledroidble/simpledroidble/consumer-rules.pro b/third_party/SimpleBLE/simpledroidble/simpledroidble/consumer-rules.pro new file mode 100644 index 000000000..e69de29bb diff --git a/third_party/SimpleBLE/simpledroidble/simpledroidble/proguard-rules.pro b/third_party/SimpleBLE/simpledroidble/simpledroidble/proguard-rules.pro new file mode 100644 index 000000000..481bb4348 --- /dev/null +++ b/third_party/SimpleBLE/simpledroidble/simpledroidble/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile \ No newline at end of file diff --git a/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/AndroidManifest.xml b/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/AndroidManifest.xml new file mode 100644 index 000000000..eae847973 --- /dev/null +++ b/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/AndroidManifest.xml @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/cpp/CMakeLists.txt b/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/cpp/CMakeLists.txt new file mode 100644 index 000000000..c5ee0fdc3 --- /dev/null +++ b/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/cpp/CMakeLists.txt @@ -0,0 +1,48 @@ +cmake_minimum_required(VERSION 3.21) + +set(PROJECT_ROOT_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../../../../..) + +include(${PROJECT_ROOT_DIR}/cmake/prelude.cmake) + +project( + "simpleble-jni" + VERSION ${SIMPLEBLE_VERSION} + LANGUAGES CXX +) + +include(${PROJECT_ROOT_DIR}/cmake/epilogue.cmake) + +set(BUILD_SHARED_LIBS OFF) +add_subdirectory(${PROJECT_ROOT_DIR}/simpleble ${CMAKE_BINARY_DIR}/simpleble) +set(BUILD_SHARED_LIBS ON) + +if(NOT TARGET fmt::fmt-header-only) + option(LIBFMT_VENDORIZE "Enable vendorized libfmt" ON) + find_package(fmt REQUIRED) + + if(TARGET fmt) + set_target_properties(fmt PROPERTIES EXCLUDE_FROM_ALL TRUE) + endif() +endif() + +add_library( + ${CMAKE_PROJECT_NAME} SHARED + simpleble_android.cpp + android_utils.cpp +) + +set_target_properties( + ${CMAKE_PROJECT_NAME} PROPERTIES + CXX_STANDARD 17 + CXX_STANDARD_REQUIRED YES + CXX_EXTENSIONS NO +) + +target_include_directories( + ${CMAKE_PROJECT_NAME} PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR} +) + +target_link_libraries(${CMAKE_PROJECT_NAME} + android log simpleble::simpleble fmt::fmt-header-only +) \ No newline at end of file diff --git a/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/cpp/ThreadRunner.h b/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/cpp/ThreadRunner.h new file mode 100644 index 000000000..3ab402222 --- /dev/null +++ b/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/cpp/ThreadRunner.h @@ -0,0 +1,91 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include "android_utils.h" +#include +#include + +class ThreadRunner { +public: + ThreadRunner() : _stop(false), _jvm(nullptr) {} + + ~ThreadRunner() { + { + std::unique_lock lock(_mutex); + _stop = true; + _cv.notify_one(); + } + if (_thread && _thread->joinable()) { + _thread->join(); + } + } + + void set_jvm(JavaVM *jvm) { + _jvm = jvm; + } + + void enqueue(std::function func) { + { + std::unique_lock lock(_mutex); + if (!_thread) { + // Thread is lazily started upon the first task enqueue + _thread.emplace(&ThreadRunner::threadFunc, this); + } + _queue.push(std::move(func)); + } + _cv.notify_one(); + } + +private: + void threadFunc() { + if (!_jvm) { + log_error("No JVM provided"); + return; + } + + // Attach the thread to the JVM + JNIEnv *env; + jint result = _jvm->AttachCurrentThread(&env, NULL); + if (result != JNI_OK) { + log_error("Failed to attach thread"); + return; + } + + // Run the thread loop + while (true) { + std::function func; + + // Retrieve and execute the next task + { + std::unique_lock lock(_mutex); + _cv.wait(lock, [this] { return _stop || !_queue.empty(); }); + if (_stop && _queue.empty()) { + break; + } + func = std::move(_queue.front()); + _queue.pop(); + } + + try { + func(); + } catch (const std::exception &e) { + log_error(fmt::format("Exception in thread: {}", e.what())); + } + } + + // Detach the thread from the JVM + _jvm->DetachCurrentThread(); + } + + JavaVM *_jvm; + std::optional _thread; + std::mutex _mutex; + std::condition_variable _cv; + std::queue> _queue; + bool _stop; +}; diff --git a/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/cpp/android_utils.cpp b/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/cpp/android_utils.cpp new file mode 100644 index 000000000..8982f2530 --- /dev/null +++ b/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/cpp/android_utils.cpp @@ -0,0 +1,64 @@ +#include "android_utils.h" + +#include +#include + +void log_error(const std::string& msg) { + __android_log_write(ANDROID_LOG_ERROR, "SimpleBLE", msg.c_str()); +} +void log_info(const std::string& msg) { + __android_log_write(ANDROID_LOG_INFO, "SimpleBLE", msg.c_str()); +} +void log_debug(const std::string& msg) { + __android_log_write(ANDROID_LOG_DEBUG, "SimpleBLE", msg.c_str()); +} + +jstring to_jstring(JNIEnv* env, const std::string& str){ + return env->NewStringUTF(str.c_str()); +} + +std::string from_jstring(JNIEnv* env, jstring str){ + const char* c_str = env->GetStringUTFChars(str, nullptr); + std::string result(c_str); + env->ReleaseStringUTFChars(str, c_str); + return result; +} + +jbyteArray to_jbyteArray(JNIEnv* env, const std::string& data) { + jbyteArray result = env->NewByteArray(data.size()); + env->SetByteArrayRegion(result, 0, data.size(), reinterpret_cast(data.data())); + + jsize length = env->GetArrayLength(result); + jbyte* bytes = env->GetByteArrayElements(result, NULL); + + std::string arrayOut = "Array: "; + for (jsize i = 0; i < length; i++) { + arrayOut += fmt::format("{:02x} ", bytes[i]); + } + log_debug(arrayOut); + + env->ReleaseByteArrayElements(result, bytes, JNI_ABORT); + + + return result; +} + +jobject jarraylist_new(JNIEnv* env) { + jclass arrayListClass = env->FindClass("java/util/ArrayList"); + jmethodID arrayListConstructor = env->GetMethodID(arrayListClass, "", "()V"); + jobject arrayList = env->NewObject(arrayListClass, arrayListConstructor); + return arrayList; +} + +void jarraylist_add(JNIEnv* env, jobject arrayList, jobject element) { + jclass arrayListClass = env->GetObjectClass(arrayList); + jmethodID arrayListAdd = env->GetMethodID(arrayListClass, "add", "(Ljava/lang/Object;)Z"); + env->CallBooleanMethod(arrayList, arrayListAdd, element); +} + +void throw_exception(JNIEnv* env, const std::string& msg) { + log_error(fmt::format("Throwing exception: {}", msg)); + + jclass Exception = env->FindClass("java/lang/Exception"); + env->ThrowNew(Exception, msg.c_str()); +} \ No newline at end of file diff --git a/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/cpp/android_utils.h b/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/cpp/android_utils.h new file mode 100644 index 000000000..d8565bda2 --- /dev/null +++ b/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/cpp/android_utils.h @@ -0,0 +1,18 @@ +#pragma once + +#include +#include + +void log_error(const std::string& msg); +void log_info(const std::string& msg); +void log_debug(const std::string& msg); + +jstring to_jstring(JNIEnv* env, const std::string& str); +std::string from_jstring(JNIEnv* env, jstring str); + +jbyteArray to_jbyteArray(JNIEnv* env, const std::string& data); + +jobject jarraylist_new(JNIEnv* env); +void jarraylist_add(JNIEnv* env, jobject arrayList, jobject element); + +void throw_exception(JNIEnv* env, const std::string& msg); \ No newline at end of file diff --git a/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/cpp/simpleble_android.cpp b/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/cpp/simpleble_android.cpp new file mode 100644 index 000000000..f213c4e49 --- /dev/null +++ b/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/cpp/simpleble_android.cpp @@ -0,0 +1,784 @@ +#include +#include + +#include "android_utils.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include "ThreadRunner.h" + +// TODO: Switch to using regular SimpleBLE classes with try/catch blocks. + +static std::map cached_adapters; +static std::map> cached_adapter_callbacks; + +static std::map> cached_peripherals; +static std::map>> cached_peripheral_callbacks; +static std::map>> cached_peripheral_data_callbacks; +static ThreadRunner threadRunner; +static JavaVM *jvm; + +JNIEnv* get_env() { + JNIEnv *env; + jvm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6); + return env; +} + +JNIEXPORT jint JNI_OnLoad(JavaVM *vm, void *reserved) { + jvm = vm; + threadRunner.set_jvm(vm); + +// // Find your class. JNI_OnLoad is called from the correct class loader context for this to work. +// jclass c = env->FindClass("com/example/app/package/MyClass"); +// if (c == nullptr) return JNI_ERR; + + SimpleBLE::Logging::Logger::get()->set_callback( + [](SimpleBLE::Logging::Level level, const std::string& module, const std::string& file, uint32_t line, const std::string& function, const std::string& message) { + std::string log_message = fmt::format("[{}] {}:{}:{}: {}", module, file, line, function, message); + log_info(log_message); + } + ); + + return JNI_VERSION_1_6; +} + +extern "C" +JNIEXPORT void JNICALL +Java_org_simpleble_android_Adapter_nativeAdapterRegister(JNIEnv *env, jobject thiz, jlong adapter_id, jobject callback) { + // TODO: IDEA. We could store the callback object whenever the scan starts and then remove it when the scan stops, + // to avoid having extra references lying around. + + // Create a weak global reference to the Java callback object + jweak weakCallbackRef = env->NewWeakGlobalRef(callback); + + // Store the weak reference in the cached_adapter_callbacks map + cached_adapter_callbacks[adapter_id].push_back(weakCallbackRef); + + // Retrieve the adapter from the cached_adapters map + auto adapter = cached_adapters.at(adapter_id); + + // TODO: Remove any invalid objects before adding new ones. + + adapter.set_callback_on_scan_start([adapter_id](){ + threadRunner.enqueue([adapter_id](){ + JNIEnv *env = get_env(); + + // Retrieve the weak references from the cached_adapter_callbacks map + std::vector weakCallbackRefs = cached_adapter_callbacks[adapter_id]; + + // Iterate over the weak references + for (jweak weakCallbackRef : weakCallbackRefs) { + + // Check if the weak reference is still valid + if (env->IsSameObject(weakCallbackRef, nullptr) == JNI_FALSE) { + // Retrieve the strong reference from the weak reference + jobject callbackRef = env->NewLocalRef(weakCallbackRef); + + // Find the Java class and method to invoke + // TODO: We should cache the class and method IDs + jclass callbackClass = env->GetObjectClass(callbackRef); + jmethodID onScanStartMethod = env->GetMethodID(callbackClass, "onScanStart", "()V"); + + // Invoke the Java callback method + env->CallVoidMethod(callbackRef, onScanStartMethod); + + // Delete the local reference + env->DeleteLocalRef(callbackRef); + } + } + }); + }); + + adapter.set_callback_on_scan_stop([adapter_id](){ + threadRunner.enqueue([adapter_id](){ + JNIEnv *env = get_env(); + + // Retrieve the weak references from the cached_adapter_callbacks map + std::vector weakCallbackRefs = cached_adapter_callbacks[adapter_id]; + + // Iterate over the weak references + for (jweak weakCallbackRef : weakCallbackRefs) { + // Check if the weak reference is still valid + if (env->IsSameObject(weakCallbackRef, nullptr) == JNI_FALSE) { + // Retrieve the strong reference from the weak reference + jobject callbackRef = env->NewLocalRef(weakCallbackRef); + + // Find the Java class and method to invoke + // TODO: We should cache the class and method IDs + jclass callbackClass = env->GetObjectClass(callbackRef); + jmethodID onScanStopMethod = env->GetMethodID(callbackClass, "onScanStop", "()V"); + + // Invoke the Java callback method + env->CallVoidMethod(callbackRef, onScanStopMethod); + + // Delete the local reference + env->DeleteLocalRef(callbackRef); + } + } + }); + }); + + adapter.set_callback_on_scan_found([adapter_id](SimpleBLE::Safe::Peripheral peripheral){ + size_t peripheral_hash = std::hash{}(peripheral.address().value_or("UNKNOWN")); + + // Add to the cache if it doesn't exist + if (cached_peripherals[adapter_id].count(peripheral_hash) == 0) { + cached_peripherals[adapter_id].insert({peripheral_hash, peripheral}); + } + + threadRunner.enqueue([adapter_id, peripheral_hash](){ + JNIEnv *env = get_env(); + + // Retrieve the weak references from the cached_adapter_callbacks map + std::vector weakCallbackRefs = cached_adapter_callbacks[adapter_id]; + + // Iterate over the weak references + for (jweak weakCallbackRef : weakCallbackRefs) { + // Check if the weak reference is still valid + if (env->IsSameObject(weakCallbackRef, nullptr) == JNI_FALSE) { + + // Retrieve the strong reference from the weak reference + jobject callbackRef = env->NewLocalRef(weakCallbackRef); + + // Find the Java class and method to invoke + // TODO: We should cache the class and method IDs + jclass callbackClass = env->GetObjectClass(callbackRef); + jmethodID onScanFoundMethod = env->GetMethodID(callbackClass, "onScanFound","(J)V"); + + // Invoke the Java callback method + env->CallVoidMethod(callbackRef, onScanFoundMethod, peripheral_hash); + + // Delete the local reference + env->DeleteLocalRef(callbackRef); + + } + } + }); + }); + + adapter.set_callback_on_scan_updated([adapter_id](SimpleBLE::Safe::Peripheral peripheral){ + size_t peripheral_hash = std::hash{}(peripheral.address().value_or("UNKNOWN")); + + // Add to the cache if it doesn't exist + if (cached_peripherals[adapter_id].count(peripheral_hash) == 0) { + cached_peripherals[adapter_id].insert({peripheral_hash, peripheral}); + } + + threadRunner.enqueue([adapter_id, peripheral_hash](){ + JNIEnv *env = get_env(); + + // Retrieve the weak references from the cached_adapter_callbacks map + std::vector weakCallbackRefs = cached_adapter_callbacks[adapter_id]; + + // Iterate over the weak references + for (jweak weakCallbackRef : weakCallbackRefs) { + // Check if the weak reference is still valid + if (env->IsSameObject(weakCallbackRef, nullptr) == JNI_FALSE) { + + // Retrieve the strong reference from the weak reference + jobject callbackRef = env->NewLocalRef(weakCallbackRef); + + // Find the Java class and method to invoke + // TODO: We should cache the class and method IDs + jclass callbackClass = env->GetObjectClass(callbackRef); + jmethodID onScanFoundMethod = env->GetMethodID(callbackClass, "onScanUpdated", "(J)V"); + + // Invoke the Java callback method + env->CallVoidMethod(callbackRef, onScanFoundMethod, peripheral_hash); + + // Delete the local reference + env->DeleteLocalRef(callbackRef); + + } + } + }); + }); +} + +extern "C" +JNIEXPORT jboolean JNICALL +Java_org_simpleble_android_Adapter_00024Companion_nativeIsBluetoothEnabled(JNIEnv *env, jobject thiz) { + return SimpleBLE::Safe::Adapter::bluetooth_enabled().value_or(false); +} + +extern "C" JNIEXPORT jlongArray JNICALL Java_org_simpleble_android_Adapter_nativeGetAdapters(JNIEnv *env, jclass clazz) { + auto adapters = SimpleBLE::Safe::Adapter::get_adapters(); + + // If an error occurred, return an empty list. + if (!adapters.has_value()) return env->NewLongArray(0); + + // Go over the results, cache whatever doesn't exist and return the full list. + jsize j_adapter_index = 0; + jlongArray j_adapter_result = env->NewLongArray(static_cast(adapters.value().size())); + for (auto &adapter: adapters.value()) { + size_t adapter_hash = std::hash{}(adapter.identifier().value_or("UNKNOWN")); + + // Add to the cache if it doesn't exist + if (cached_adapters.count(adapter_hash) == 0) { + cached_adapters.insert({adapter_hash, adapter}); + } + + // Add to the results + jlong j_adapter_hash = adapter_hash; + env->SetLongArrayRegion(j_adapter_result, j_adapter_index, 1, &j_adapter_hash); + j_adapter_index++; + + } + + return j_adapter_result; +} + +extern "C" JNIEXPORT jstring JNICALL Java_org_simpleble_android_Adapter_nativeAdapterIdentifier(JNIEnv *env, jobject thiz, jlong adapter_id) { + auto adapter = cached_adapters.at(adapter_id); + // TODO: Should throw exception in case of failure. + return to_jstring(env, adapter.identifier().value_or("Unknown")); +} + +extern "C" JNIEXPORT jstring JNICALL Java_org_simpleble_android_Adapter_nativeAdapterAddress(JNIEnv *env, jobject thiz, jlong adapter_id) { + auto adapter = cached_adapters.at(adapter_id); + // TODO: Should throw exception in case of failure. + return to_jstring(env, adapter.address().value_or("Unknown")); +} + +extern "C" JNIEXPORT void JNICALL Java_org_simpleble_android_Adapter_nativeAdapterScanStart(JNIEnv *env, jobject thiz, jlong adapter_id) { + auto adapter = cached_adapters.at(adapter_id); + bool success = adapter.scan_start(); + + if (!success) { + throw_exception(env, "Failed to start scan"); + } +} + +extern "C" JNIEXPORT void JNICALL Java_org_simpleble_android_Adapter_nativeAdapterScanStop(JNIEnv *env, jobject thiz, jlong adapter_id) { + auto adapter = cached_adapters.at(adapter_id); + bool success = adapter.scan_stop(); + + if (!success) { + throw_exception(env, "Failed to stop scan"); + } +} + +extern "C" JNIEXPORT void JNICALL Java_org_simpleble_android_Adapter_nativeAdapterScanFor(JNIEnv *env, jobject thiz, jlong adapter_id, jint timeout) { + auto adapter = cached_adapters.at(adapter_id); + bool success = adapter.scan_for(timeout); + + if (!success) { + throw_exception(env, "Failed to scan for"); + } +} + +extern "C" JNIEXPORT jboolean JNICALL Java_org_simpleble_android_Adapter_nativeAdapterScanIsActive(JNIEnv *env, jobject thiz, jlong adapter_id) { + auto adapter = cached_adapters.at(adapter_id); + // TODO: Should throw exception in case of failure. + return adapter.scan_is_active().value_or(false); +} + +extern "C" JNIEXPORT jlongArray JNICALL Java_org_simpleble_android_Adapter_nativeAdapterScanGetResults(JNIEnv *env, jobject thiz, jlong adapter_id) { + auto adapter = cached_adapters.at(adapter_id); + + auto peripherals = adapter.scan_get_results(); + + // If an error occurred, return an empty list. + if (!peripherals.has_value()) return env->NewLongArray(0); + + jsize j_peripheral_index = 0; + jlongArray j_peripheral_result = env->NewLongArray(static_cast(peripherals.value().size())); + for (auto &peripheral: peripherals.value()) { + size_t peripheral_hash = std::hash{}(peripheral.address().value_or("UNKNOWN")); + + // Add to the cache if it doesn't exist + if (cached_peripherals[adapter_id].count(peripheral_hash) == 0) { + cached_peripherals[adapter_id].insert({peripheral_hash, peripheral}); + } + + // Add to the results + jlong j_peripheral_hash = peripheral_hash; + env->SetLongArrayRegion(j_peripheral_result, j_peripheral_index, 1, &j_peripheral_hash); + j_peripheral_index++; + } + + return j_peripheral_result; +} + +// PERIPHERAL + +extern "C" +JNIEXPORT void JNICALL +Java_org_simpleble_android_Peripheral_nativePeripheralRegister(JNIEnv *env, jobject thiz, + jlong adapter_id, jlong peripheral_id, jobject callback) { +// TODO: IDEA. We could store the callback object whenever the scan starts and then remove it when the scan stops, + // to avoid having extra references lying around. + + // Create a weak global reference to the Java callback object + jweak weakCallbackRef = env->NewWeakGlobalRef(callback); + + // Store the weak reference in the cached_adapter_callbacks map + cached_peripheral_callbacks[adapter_id][peripheral_id].push_back(weakCallbackRef); + + auto peripheral = cached_peripherals[adapter_id].at(peripheral_id); + + // TODO: Remove any invalid objects before adding new ones. + + peripheral.set_callback_on_connected([adapter_id, peripheral_id](){ + threadRunner.enqueue([adapter_id, peripheral_id](){ + JNIEnv *env = get_env(); + + // Retrieve the weak references from the cached_adapter_callbacks map + std::vector weakCallbackRefs = cached_peripheral_callbacks[adapter_id][peripheral_id]; + + // Iterate over the weak references + for (jweak weakCallbackRef : weakCallbackRefs) { + + // Check if the weak reference is still valid + if (env->IsSameObject(weakCallbackRef, nullptr) == JNI_FALSE) { + // Retrieve the strong reference from the weak reference + jobject callbackRef = env->NewLocalRef(weakCallbackRef); + + // Find the Java class and method to invoke + // TODO: We should cache the class and method IDs + jclass callbackClass = env->GetObjectClass(callbackRef); + jmethodID onConnectedMethod = env->GetMethodID(callbackClass, "onConnected", "()V"); + + // Invoke the Java callback method + env->CallVoidMethod(callbackRef, onConnectedMethod); + + // Delete the local reference + env->DeleteLocalRef(callbackRef); + } + } + }); + }); + + peripheral.set_callback_on_disconnected([adapter_id, peripheral_id](){ + threadRunner.enqueue([adapter_id, peripheral_id](){ + JNIEnv *env = get_env(); + + // Retrieve the weak references from the cached_adapter_callbacks map + std::vector weakCallbackRefs = cached_peripheral_callbacks[adapter_id][peripheral_id]; + + // Iterate over the weak references + for (jweak weakCallbackRef : weakCallbackRefs) { + + // Check if the weak reference is still valid + if (env->IsSameObject(weakCallbackRef, nullptr) == JNI_FALSE) { + // Retrieve the strong reference from the weak reference + jobject callbackRef = env->NewLocalRef(weakCallbackRef); + + // Find the Java class and method to invoke + // TODO: We should cache the class and method IDs + jclass callbackClass = env->GetObjectClass(callbackRef); + jmethodID onConnectedMethod = env->GetMethodID(callbackClass, "onDisconnected", "()V"); + + // Invoke the Java callback method + env->CallVoidMethod(callbackRef, onConnectedMethod); + + // Delete the local reference + env->DeleteLocalRef(callbackRef); + } + } + }); + }); +} + +extern "C" +JNIEXPORT jstring JNICALL +Java_org_simpleble_android_Peripheral_nativePeripheralIdentifier(JNIEnv *env, jobject thiz, + jlong adapter_id, + jlong peripheral_id) { + auto& peripheral = cached_peripherals[adapter_id].at(peripheral_id); + return to_jstring(env, peripheral.identifier().value_or("Unknown")); +} + +extern "C" +JNIEXPORT jstring JNICALL +Java_org_simpleble_android_Peripheral_nativePeripheralAddress(JNIEnv *env, jobject thiz, + jlong adapter_id, jlong peripheral_id) { + auto& peripheral = cached_peripherals[adapter_id].at(peripheral_id); + return to_jstring(env, peripheral.address().value_or("Unknown")); +} + +extern "C" +JNIEXPORT jint JNICALL +Java_org_simpleble_android_Peripheral_nativePeripheralAddressType(JNIEnv *env, jobject thiz, + jlong adapter_id, + jlong peripheral_id) { + auto& peripheral = cached_peripherals[adapter_id].at(peripheral_id); + return peripheral.address_type().value_or(SimpleBLE::BluetoothAddressType::UNSPECIFIED); +} + +extern "C" +JNIEXPORT jint JNICALL +Java_org_simpleble_android_Peripheral_nativePeripheralRssi(JNIEnv *env, jobject thiz, + jlong adapter_id, jlong peripheral_id) { + auto& peripheral = cached_peripherals[adapter_id].at(peripheral_id); + return peripheral.rssi().value_or(INT16_MIN); +} + +extern "C" +JNIEXPORT jint JNICALL +Java_org_simpleble_android_Peripheral_nativePeripheralTxPower(JNIEnv *env, jobject thiz, + jlong adapter_id, jlong peripheral_id) { + auto& peripheral = cached_peripherals[adapter_id].at(peripheral_id); + return peripheral.tx_power().value_or(INT16_MIN); +} + +extern "C" +JNIEXPORT jint JNICALL +Java_org_simpleble_android_Peripheral_nativePeripheralMtu(JNIEnv *env, jobject thiz, + jlong adapter_id, jlong peripheral_id) { + auto& peripheral = cached_peripherals[adapter_id].at(peripheral_id); + return peripheral.mtu().value_or(UINT16_MAX); +} + +extern "C" +JNIEXPORT void JNICALL +Java_org_simpleble_android_Peripheral_nativePeripheralConnect(JNIEnv *env, jobject thiz, + jlong adapter_id, jlong peripheral_id) { + auto peripheral = cached_peripherals[adapter_id].at(peripheral_id); + + bool success = peripheral.connect(); + if (!success) { + throw_exception(env, "Failed to connect"); + } +} + +extern "C" +JNIEXPORT void JNICALL +Java_org_simpleble_android_Peripheral_nativePeripheralDisconnect(JNIEnv *env, jobject thiz, + jlong adapter_id, + jlong peripheral_id) { + auto& peripheral = cached_peripherals[adapter_id].at(peripheral_id); + peripheral.disconnect(); +} + +extern "C" +JNIEXPORT void JNICALL +Java_org_simpleble_android_Peripheral_nativePeripheralNotify(JNIEnv *env, jobject thiz, + jlong adapter_id, jlong peripheral_id, + jstring j_service, + jstring j_characteristic, + jobject callback) { + + std::string service = from_jstring(env, j_service); + std::string characteristic = from_jstring(env, j_characteristic); + std::string service_characteristic = service + "_" + characteristic; + size_t service_characteristic_hash = std::hash{}(service_characteristic); + + jobject callbackRef = env->NewGlobalRef(callback); + // TODO: Check if there is a callback already registered for this service_characteristic_hash + cached_peripheral_data_callbacks[adapter_id][peripheral_id].insert({service_characteristic_hash, callbackRef}); + + auto peripheral = cached_peripherals[adapter_id].at(peripheral_id); + bool success = peripheral.notify(service, characteristic, [adapter_id, peripheral_id, service_characteristic_hash](SimpleBLE::ByteArray payload){ + + std::string payload_contents; + for (int i = 0; i < payload.size(); i++) { + payload_contents += fmt::format("{:02X}", (int)(payload[i])); + } + + log_info("Received payload: " + payload_contents); + + threadRunner.enqueue([adapter_id, peripheral_id, service_characteristic_hash, payload]() { + JNIEnv *env = get_env(); + + // Retrieve the weak references from the cached_adapter_callbacks map + jobject callbackRef = cached_peripheral_data_callbacks[adapter_id][peripheral_id].at(service_characteristic_hash); + jbyteArray j_payload = to_jbyteArray(env, payload); + + // TODO: We should cache the class and method IDs + jclass callbackClass = env->GetObjectClass(callbackRef); + jmethodID onDataReceivedMethod = env->GetMethodID(callbackClass, "onDataReceived", "([B)V"); + + // Invoke the Java callback method + env->CallVoidMethod(callbackRef, onDataReceivedMethod, j_payload); + + }); + }); + + if (!success) { + throw_exception(env, "Failed to notify"); + } +} + + +extern "C" +JNIEXPORT void JNICALL +Java_org_simpleble_android_Peripheral_nativePeripheralIndicate(JNIEnv *env, jobject thiz, + jlong adapter_id, jlong peripheral_id, + jstring j_service, + jstring j_characteristic, + jobject callback) { + + std::string service = from_jstring(env, j_service); + std::string characteristic = from_jstring(env, j_characteristic); + std::string service_characteristic = service + "_" + characteristic; + size_t service_characteristic_hash = std::hash{}(service_characteristic); + + jobject callbackRef = env->NewGlobalRef(callback); + // TODO: Check if there is a callback already registered for this service_characteristic_hash + cached_peripheral_data_callbacks[adapter_id][peripheral_id].insert({service_characteristic_hash, callbackRef}); + + auto peripheral = cached_peripherals[adapter_id].at(peripheral_id); + bool success = peripheral.indicate(service, characteristic, [adapter_id, peripheral_id, service_characteristic_hash](SimpleBLE::ByteArray payload){ + + std::string payload_contents; + for (int i = 0; i < payload.size(); i++) { + payload_contents += fmt::format("{:02X}", (int)(payload[i])); + } + + log_info("Received payload: " + payload_contents); + + threadRunner.enqueue([adapter_id, peripheral_id, service_characteristic_hash, payload]() { + JNIEnv *env = get_env(); + + // Retrieve the weak references from the cached_adapter_callbacks map + jobject callbackRef = cached_peripheral_data_callbacks[adapter_id][peripheral_id].at(service_characteristic_hash); + jbyteArray j_payload = to_jbyteArray(env, payload); + + // TODO: We should cache the class and method IDs + jclass callbackClass = env->GetObjectClass(callbackRef); + jmethodID onDataReceivedMethod = env->GetMethodID(callbackClass, "onDataReceived", "([B)V"); + + // Invoke the Java callback method + env->CallVoidMethod(callbackRef, onDataReceivedMethod, j_payload); + + }); + }); + + if (!success) { + throw_exception(env, "Failed to notify"); + } +} +extern "C" +JNIEXPORT void JNICALL +Java_org_simpleble_android_Peripheral_nativePeripheralUnsubscribe(JNIEnv *env, jobject thiz, + jlong adapter_id, + jlong peripheral_id, + jstring j_service, + jstring j_characteristic) { + std::string service = from_jstring(env, j_service); + std::string characteristic = from_jstring(env, j_characteristic); + std::string service_characteristic = service + "_" + characteristic; + size_t service_characteristic_hash = std::hash{}(service_characteristic); + + auto peripheral = cached_peripherals[adapter_id].at(peripheral_id); + bool success = peripheral.unsubscribe(service, characteristic); + + if (!success) { + throw_exception(env, "Failed to unsubscribe"); + } + + jobject callbackRef = cached_peripheral_data_callbacks[adapter_id][peripheral_id].at(service_characteristic_hash); + + // TODO: Should some check be done here to see if the callbackRef is still valid? + env->DeleteGlobalRef(callbackRef); + cached_peripheral_data_callbacks[adapter_id][peripheral_id].erase(service_characteristic_hash); +} + +extern "C" +JNIEXPORT jboolean JNICALL +Java_org_simpleble_android_Peripheral_nativePeripheralIsConnected(JNIEnv *env, jobject thiz, + jlong adapter_id, + jlong instance_id) { + auto& peripheral = cached_peripherals[adapter_id].at(instance_id); + return peripheral.is_connected().value_or(false); +} + +extern "C" +JNIEXPORT jboolean JNICALL +Java_org_simpleble_android_Peripheral_nativePeripheralIsConnectable(JNIEnv *env, jobject thiz, + jlong adapter_id, + jlong instance_id) { + auto& peripheral = cached_peripherals[adapter_id].at(instance_id); + return peripheral.is_connectable().value_or(false); +} + +extern "C" +JNIEXPORT jboolean JNICALL +Java_org_simpleble_android_Peripheral_nativePeripheralIsPaired(JNIEnv *env, jobject thiz, + jlong adapter_id, + jlong instance_id) { + auto& peripheral = cached_peripherals[adapter_id].at(instance_id); + return peripheral.is_paired().value_or(false); +} + +extern "C" +JNIEXPORT void JNICALL +Java_org_simpleble_android_Peripheral_nativePeripheralUnpair(JNIEnv *env, jobject thiz, + jlong adapter_id, jlong instance_id) { + auto& peripheral = cached_peripherals[adapter_id].at(instance_id); + peripheral.unpair(); +} + +extern "C" +JNIEXPORT jobject JNICALL +Java_org_simpleble_android_Peripheral_nativePeripheralServices(JNIEnv* env, jobject thiz, + jlong adapter_id, + jlong peripheral_id) { + auto& peripheral = cached_peripherals[adapter_id].at(peripheral_id); + auto services = peripheral.services().value_or(std::vector{}); + + jclass serviceClass = env->FindClass("org/simpleble/android/Service"); + jclass characteristicClass = env->FindClass("org/simpleble/android/Characteristic"); + jclass descriptorClass = env->FindClass("org/simpleble/android/Descriptor"); + + jmethodID serviceConstructor = env->GetMethodID(serviceClass, "", "(Ljava/lang/String;Ljava/util/List;)V"); + jmethodID characteristicConstructor = env->GetMethodID(characteristicClass, "", "(Ljava/lang/String;Ljava/util/List;ZZZZZ)V"); + jmethodID descriptorConstructor = env->GetMethodID(descriptorClass, "", "(Ljava/lang/String;)V"); + + jobject serviceArray = jarraylist_new(env); + + for (auto service : services) { + jstring serviceUUID = to_jstring(env, service.uuid()); + jobject charList = jarraylist_new(env); + + for (auto characteristic : service.characteristics()) { + jstring charUUID = to_jstring(env, characteristic.uuid()); + jobject descList = jarraylist_new(env); + + for (auto descriptor : characteristic.descriptors()) { + jstring descUUID = to_jstring(env, descriptor.uuid()); + jobject jDescriptor = env->NewObject(descriptorClass, descriptorConstructor, descUUID); + jarraylist_add(env, descList, jDescriptor); + } + + jobject jCharacteristic = env->NewObject(characteristicClass, characteristicConstructor, + charUUID, descList, + characteristic.can_read(), + characteristic.can_write_request(), + characteristic.can_write_command(), + characteristic.can_notify(), + characteristic.can_indicate()); + jarraylist_add(env, charList, jCharacteristic); + } + + jobject jService = env->NewObject(serviceClass, serviceConstructor, serviceUUID, charList); + jarraylist_add(env, serviceArray, jService); + } + + return serviceArray; +} + +// Utility function to create a new HashMap and return it +jobject NewHashMap(JNIEnv* env) { + jclass hashMapClass = env->FindClass("java/util/HashMap"); + if (hashMapClass == nullptr) { + return nullptr; // Class not found + } + jmethodID hashMapConstructor = env->GetMethodID(hashMapClass, "", "()V"); + if (hashMapConstructor == nullptr) { + return nullptr; // Constructor method not found + } + jobject hashMap = env->NewObject(hashMapClass, hashMapConstructor); + return hashMap; +} + +// Utility function to add an entry to a HashMap +void HashMapPut(JNIEnv* env, jobject hashMap, jobject key, jobject value) { + jclass hashMapClass = env->GetObjectClass(hashMap); + if (hashMapClass == nullptr) { + return; // Class not found + } + jmethodID hashMapPut = env->GetMethodID(hashMapClass, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"); + if (hashMapPut == nullptr) { + return; // Method not found + } + env->CallObjectMethod(hashMap, hashMapPut, key, value); +} + + +// Convert a C++ int to a Java Integer +jobject to_jInteger(JNIEnv* env, jint value) { + jclass integerClass = env->FindClass("java/lang/Integer"); + if (!integerClass) return nullptr; // Class not found + + jmethodID integerConstructor = env->GetMethodID(integerClass, "", "(I)V"); + if (!integerConstructor) return nullptr; // Constructor method not found + + jobject integerObject = env->NewObject(integerClass, integerConstructor, value); + return integerObject; +} + +// JNI function implementation +extern "C" +JNIEXPORT jobject JNICALL +Java_org_simpleble_android_Peripheral_nativePeripheralManufacturerData(JNIEnv* env, jobject thiz, jlong adapter_id, jlong instance_id) { + auto& peripheral = cached_peripherals[adapter_id].at(instance_id); + auto manufacturer_data = peripheral.manufacturer_data().value(); + + jobject hashMap = NewHashMap(env); + if (!hashMap) return nullptr; // Error creating HashMap + + for (const auto& data : manufacturer_data) { + jobject key = to_jInteger(env, static_cast(data.first)); + jbyteArray value = to_jbyteArray(env, data.second); + + HashMapPut(env, hashMap, key, value); + + env->DeleteLocalRef(key); + env->DeleteLocalRef(value); + } + + return hashMap; +} + +extern "C" +JNIEXPORT jbyteArray JNICALL +Java_org_simpleble_android_Peripheral_nativePeripheralRead(JNIEnv *env, jobject thiz, + jlong adapter_id, jlong peripheral_id, + jstring j_service, + jstring j_characteristic) { + std::string service = from_jstring(env, j_service); + std::string characteristic = from_jstring(env, j_characteristic); + + auto peripheral = cached_peripherals[adapter_id].at(peripheral_id); + SimpleBLE::ByteArray result = peripheral.read(service, characteristic).value_or(""); + + return to_jbyteArray(env, result); +} +extern "C" +JNIEXPORT void JNICALL +Java_org_simpleble_android_Peripheral_nativePeripheralWriteRequest(JNIEnv *env, jobject thiz, + jlong adapter_id, + jlong instance_id, + jstring service, + jstring characteristic, + jbyteArray data) { + // TODO: implement nativePeripheralWriteRequest() +} +extern "C" +JNIEXPORT void JNICALL +Java_org_simpleble_android_Peripheral_nativePeripheralWriteCommand(JNIEnv *env, jobject thiz, + jlong adapter_id, + jlong instance_id, + jstring service, + jstring characteristic, + jbyteArray data) { + // TODO: implement nativePeripheralWriteCommand() +} +extern "C" +JNIEXPORT jbyteArray JNICALL +Java_org_simpleble_android_Peripheral_nativePeripheralDescriptorRead(JNIEnv *env, jobject thiz, + jlong adapter_id, + jlong instance_id, + jstring service, + jstring characteristic, + jstring descriptor) { + // TODO: implement nativePeripheralDescriptorRead() +} +extern "C" +JNIEXPORT void JNICALL +Java_org_simpleble_android_Peripheral_nativePeripheralDescriptorWrite(JNIEnv *env, jobject thiz, + jlong adapter_id, + jlong instance_id, + jstring service, + jstring characteristic, + jstring descriptor, + jbyteArray data) { + // TODO: implement nativePeripheralDescriptorWrite() +} diff --git a/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/java/org/simpleble/android/Adapter.kt b/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/java/org/simpleble/android/Adapter.kt new file mode 100644 index 000000000..8318df47b --- /dev/null +++ b/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/java/org/simpleble/android/Adapter.kt @@ -0,0 +1,162 @@ +package org.simpleble.android + +import android.annotation.SuppressLint +import android.util.Log +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.channels.BufferOverflow +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +class Adapter private constructor(newInstanceId: Long) { + private val _onScanStart = MutableSharedFlow() + private val _onScanStop = MutableSharedFlow() + private val _onScanActive = MutableSharedFlow() + private val _onScanUpdated = MutableSharedFlow() + private val _onScanFound = MutableSharedFlow() + + private var instanceId: Long = newInstanceId + + private val callbacks = object : Callback { + override fun onScanStart() { + CoroutineScope(Dispatchers.Main).launch { + _onScanStart.emit(Unit) + } + CoroutineScope(Dispatchers.Main).launch { + _onScanActive.emit(true) + } + } + + override fun onScanStop() { + CoroutineScope(Dispatchers.Main).launch { + _onScanStop.emit(Unit) + } + CoroutineScope(Dispatchers.Main).launch { + _onScanActive.emit(false) + } + } + + override fun onScanUpdated(peripheralId: Long) { + CoroutineScope(Dispatchers.Main).launch { + _onScanUpdated.emit(Peripheral(instanceId, peripheralId)) + } + } + + override fun onScanFound(peripheralId: Long) { + CoroutineScope(Dispatchers.Main).launch { + _onScanFound.emit(Peripheral(instanceId, peripheralId)) + } + } + } + + init { + Log.d("SimpleBLE", "Adapter ${this.hashCode()}.init") + nativeAdapterRegister(instanceId, callbacks) + } + + val identifier: String get() { + return nativeAdapterIdentifier(instanceId) ?: "" + } + + val address: BluetoothAddress get() { + return BluetoothAddress(nativeAdapterAddress(instanceId) ?: "") + } + + fun scanStart() { + nativeAdapterScanStart(instanceId) + } + + fun scanStop() { + nativeAdapterScanStop(instanceId) + } + + suspend fun scanFor(timeoutMs: Int) { + withContext(Dispatchers.IO) { + nativeAdapterScanFor(instanceId, timeoutMs) + } + } + + val scanIsActive: Boolean get() { + return nativeAdapterScanIsActive(instanceId) + } + + fun scanGetResults(): List { + return nativeAdapterScanGetResults(instanceId).map { Peripheral(instanceId, it) } + } + + val onScanStart get() = _onScanStart + + val onScanStop get() = _onScanStop + + val onScanActive get() = _onScanActive + + val onScanUpdated get() = _onScanUpdated + + val onScanFound get() = _onScanFound + + fun getPairedPeripherals(): List { + // TODO: Implement + return emptyList() + } + + companion object { + + @JvmStatic + fun isBluetoothEnabled(): Boolean { + return nativeIsBluetoothEnabled() + } + + @JvmStatic + fun getAdapters(): List { +// if (SimpleDroidBle.permissionsGranted.not()) { +// return emptyList() +// } + + val nativeAdapterIds = nativeGetAdapters() + val adapters = ArrayList() + + for (nativeAdapterId in nativeAdapterIds) { + adapters.add(Adapter(nativeAdapterId)) + } + + return adapters + } + + @JvmStatic + private external fun nativeGetAdapters(): LongArray + + private external fun nativeIsBluetoothEnabled(): Boolean + } + + // ---------------------------------------------------------------------------- + + private external fun nativeAdapterRegister(adapterId: Long, callback: Callback) + + private external fun nativeAdapterIdentifier(adapterId: Long): String? + + private external fun nativeAdapterAddress(adapterId: Long): String? + + private external fun nativeAdapterScanStart(adapterId: Long) + + private external fun nativeAdapterScanStop(adapterId: Long) + + private external fun nativeAdapterScanFor(adapterId: Long, timeout: Int) + + private external fun nativeAdapterScanIsActive(adapterId: Long): Boolean + + private external fun nativeAdapterScanGetResults(adapterId: Long) : LongArray + + // TODO: Implement + private external fun nativeAdapterGetPairedPeripherals(adapterId: Long): LongArray + + // ---------------------------------------------------------------------------- + + private interface Callback { + fun onScanStart() + fun onScanStop() + fun onScanUpdated(peripheralId: Long) + fun onScanFound(peripheralId: Long) + } + +} diff --git a/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/java/org/simpleble/android/BluetoothAddress.kt b/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/java/org/simpleble/android/BluetoothAddress.kt new file mode 100644 index 000000000..cd530052f --- /dev/null +++ b/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/java/org/simpleble/android/BluetoothAddress.kt @@ -0,0 +1,7 @@ +package org.simpleble.android + +class BluetoothAddress(private val address: String) { + override fun toString(): String { + return address + } +} diff --git a/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/java/org/simpleble/android/BluetoothAddressType.kt b/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/java/org/simpleble/android/BluetoothAddressType.kt new file mode 100644 index 000000000..13a2837f7 --- /dev/null +++ b/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/java/org/simpleble/android/BluetoothAddressType.kt @@ -0,0 +1,21 @@ +package org.simpleble.android + +enum class BluetoothAddressType(val value: Int) { + PUBLIC(0), + RANDOM(1), + UNSPECIFIED(2); + + override fun toString(): String { + return when (this) { + PUBLIC -> "Public" + RANDOM -> "Random" + UNSPECIFIED -> "Unspecified" + } + } + + companion object { + fun fromInt(value: Int): BluetoothAddressType { + return values().find { it.value == value } ?: UNSPECIFIED + } + } +} \ No newline at end of file diff --git a/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/java/org/simpleble/android/BluetoothUUID.kt b/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/java/org/simpleble/android/BluetoothUUID.kt new file mode 100644 index 000000000..2058cf9a2 --- /dev/null +++ b/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/java/org/simpleble/android/BluetoothUUID.kt @@ -0,0 +1,7 @@ +package org.simpleble.android + +class BluetoothUUID(private val uuid: String) { + override fun toString(): String { + return uuid + } +} \ No newline at end of file diff --git a/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/java/org/simpleble/android/Characteristic.kt b/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/java/org/simpleble/android/Characteristic.kt new file mode 100644 index 000000000..31509b424 --- /dev/null +++ b/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/java/org/simpleble/android/Characteristic.kt @@ -0,0 +1,11 @@ +package org.simpleble.android + +class Characteristic( + val uuid: String, + val descriptors: List, + val canRead: Boolean, + val canWriteRequest: Boolean, + val canWriteCommand: Boolean, + val canNotify: Boolean, + val canIndicate: Boolean +) \ No newline at end of file diff --git a/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/java/org/simpleble/android/Descriptor.kt b/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/java/org/simpleble/android/Descriptor.kt new file mode 100644 index 000000000..37b7acc15 --- /dev/null +++ b/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/java/org/simpleble/android/Descriptor.kt @@ -0,0 +1,3 @@ +package org.simpleble.android + +class Descriptor(val uuid: String) \ No newline at end of file diff --git a/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/java/org/simpleble/android/Peripheral.kt b/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/java/org/simpleble/android/Peripheral.kt new file mode 100644 index 000000000..7552b23c8 --- /dev/null +++ b/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/java/org/simpleble/android/Peripheral.kt @@ -0,0 +1,284 @@ +package org.simpleble.android + +import android.util.Log +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +class Peripheral internal constructor(newAdapterId: Long, newInstanceId: Long) { + + private var instanceId: Long = newInstanceId + private var adapterId: Long = newAdapterId + + private val _onConnected = MutableSharedFlow() + private val _onConnectionActive = MutableSharedFlow() + private val _onDisconnected = MutableSharedFlow() + + private val callbacks = object : Callback { + override fun onConnected() { + CoroutineScope(Dispatchers.Main).launch { + _onConnected.emit(Unit) + } + CoroutineScope(Dispatchers.Main).launch { + _onConnectionActive.emit(true) + } + } + + override fun onDisconnected() { + CoroutineScope(Dispatchers.Main).launch { + _onDisconnected.emit(Unit) + } + CoroutineScope(Dispatchers.Main).launch { + _onConnectionActive.emit(false) + } + } + } + + init { + Log.d("SimpleBLE", "Peripheral ${this.hashCode()}.init") + nativePeripheralRegister(adapterId, instanceId, callbacks) + } + + val identifier: String get() { + return nativePeripheralIdentifier(adapterId, instanceId) ?: "" + } + + val address: BluetoothAddress get() { + return BluetoothAddress(nativePeripheralAddress(adapterId, instanceId) ?: "") + } + + val addressType: BluetoothAddressType get() { + return BluetoothAddressType.fromInt(nativePeripheralAddressType(adapterId, instanceId)) + } + + val rssi: Int get() { + return nativePeripheralRssi(adapterId, instanceId) + } + + val txPower: Int get() { + return nativePeripheralTxPower(adapterId, instanceId) + } + + val mtu: Int get() { + return nativePeripheralMtu(adapterId, instanceId) + } + + suspend fun connect() { + withContext(Dispatchers.IO) { + nativePeripheralConnect(adapterId, instanceId) + } + } + + suspend fun disconnect() { + withContext(Dispatchers.IO) { + nativePeripheralDisconnect(adapterId, instanceId) + } + } + + val isConnected: Boolean get() { + return nativePeripheralIsConnected(adapterId, instanceId) + } + + val isConnectable: Boolean get() { + return nativePeripheralIsConnectable(adapterId, instanceId) + } + + val isPaired: Boolean get() { + return nativePeripheralIsPaired(adapterId, instanceId) + } + + fun unpair() { + nativePeripheralUnpair(adapterId, instanceId) + } + + fun services(): List { + return nativePeripheralServices(adapterId, instanceId) + } + + fun manufacturerData(): Map { + return nativePeripheralManufacturerData(adapterId, instanceId) + } + + fun read(service: BluetoothUUID, characteristic: BluetoothUUID): ByteArray { + return nativePeripheralRead(adapterId, instanceId, service.toString(), characteristic.toString()) + } + + fun writeRequest(service: BluetoothUUID, characteristic: BluetoothUUID, data: ByteArray) { + // TODO: Implement + } + + fun writeCommand(service: BluetoothUUID, characteristic: BluetoothUUID, data: ByteArray) { + // TODO: Implement + } + + fun notify( + service: BluetoothUUID, + characteristic: BluetoothUUID + ): MutableSharedFlow { + val payloadFlow = MutableSharedFlow() + val dataCallback = object : DataCallback { + override fun onDataReceived(data: ByteArray) { + CoroutineScope(Dispatchers.Main).launch { + payloadFlow.emit(data) + } + } + } + + nativePeripheralNotify(adapterId, instanceId, service.toString(), characteristic.toString(), dataCallback) + return payloadFlow + } + + fun indicate( + service: BluetoothUUID, + characteristic: BluetoothUUID + ): MutableSharedFlow { + val payloadFlow = MutableSharedFlow() + val dataCallback = object : DataCallback { + override fun onDataReceived(data: ByteArray) { + CoroutineScope(Dispatchers.Main).launch { + payloadFlow.emit(data) + } + } + } + + nativePeripheralIndicate(adapterId, instanceId, service.toString(), characteristic.toString(), dataCallback) + return payloadFlow + } + + fun unsubscribe(service: BluetoothUUID, characteristic: BluetoothUUID) { + nativePeripheralUnsubscribe(adapterId, instanceId, service.toString(), characteristic.toString()) + } + + fun read( + service: BluetoothUUID, + characteristic: BluetoothUUID, + descriptor: BluetoothUUID + ): ByteArray { + // TODO: Implement + return ByteArray(0) + } + + fun write( + service: BluetoothUUID, + characteristic: BluetoothUUID, + descriptor: BluetoothUUID, + data: ByteArray + ) { + // TODO: Implement + } + + val onConnected get() = _onConnected + + val onDisconnected get() = _onDisconnected + + val onConnectionActive get() = _onConnectionActive + + /// ---------------------------------------------------------------------------- + + private external fun nativePeripheralRegister(adapterId: Long, instanceId: Long, callback: Callback) + + private external fun nativePeripheralIdentifier(adapterId: Long, instanceId: Long): String? + + private external fun nativePeripheralAddress(adapterId: Long, instanceId: Long): String? + + private external fun nativePeripheralAddressType(adapterId: Long, instanceId: Long): Int + + private external fun nativePeripheralRssi(adapterId: Long, instanceId: Long): Int + + private external fun nativePeripheralTxPower(adapterId: Long, instanceId: Long): Int + + private external fun nativePeripheralMtu(adapterId: Long, instanceId: Long): Int + + private external fun nativePeripheralConnect(adapterId: Long, instanceId: Long) + + private external fun nativePeripheralDisconnect(adapterId: Long, instanceId: Long) + + private external fun nativePeripheralIsConnected(adapterId: Long, instanceId: Long): Boolean + + private external fun nativePeripheralIsConnectable(adapterId: Long, instanceId: Long): Boolean + + private external fun nativePeripheralIsPaired(adapterId: Long, instanceId: Long): Boolean + + private external fun nativePeripheralUnpair(adapterId: Long, instanceId: Long) + + private external fun nativePeripheralServices(adapterId: Long, instanceId: Long): List + + private external fun nativePeripheralManufacturerData(adapterId: Long, instanceId: Long): Map + + private external fun nativePeripheralRead( + adapterId: Long, + instanceId: Long, + service: String, + characteristic: String + ): ByteArray + + private external fun nativePeripheralWriteRequest( + adapterId: Long, + instanceId: Long, + service: String, + characteristic: String, + data: ByteArray + ) + + private external fun nativePeripheralWriteCommand( + adapterId: Long, + instanceId: Long, + service: String, + characteristic: String, + data: ByteArray + ) + + private external fun nativePeripheralNotify( + adapterId: Long, + instanceId: Long, + service: String, + characteristic: String, + dataCallback: DataCallback + ) + + private external fun nativePeripheralIndicate( + adapterId: Long, + instanceId: Long, + service: String, + characteristic: String, + dataCallback: DataCallback + ) + + private external fun nativePeripheralUnsubscribe( + adapterId: Long, + instanceId: Long, + service: String, + characteristic: String) + + private external fun nativePeripheralDescriptorRead( + adapterId: Long, + instanceId: Long, + service: String, + characteristic: String, + descriptor: String + ): ByteArray + + private external fun nativePeripheralDescriptorWrite( + adapterId: Long, + instanceId: Long, + service: String, + characteristic: String, + descriptor: String, + data: ByteArray + ) + + // ---------------------------------------------------------------------------- + + private interface DataCallback { + fun onDataReceived(data: ByteArray) + } + + + private interface Callback { + fun onConnected() + fun onDisconnected() + } + +} \ No newline at end of file diff --git a/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/java/org/simpleble/android/Service.kt b/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/java/org/simpleble/android/Service.kt new file mode 100644 index 000000000..ce64bd36b --- /dev/null +++ b/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/java/org/simpleble/android/Service.kt @@ -0,0 +1,6 @@ +package org.simpleble.android + +class Service( + val uuid: String, + val characteristics: List +) \ No newline at end of file diff --git a/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/java/org/simpleble/android/SimpleDroidBle.kt b/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/java/org/simpleble/android/SimpleDroidBle.kt new file mode 100644 index 000000000..c69fb96f9 --- /dev/null +++ b/third_party/SimpleBLE/simpledroidble/simpledroidble/src/main/java/org/simpleble/android/SimpleDroidBle.kt @@ -0,0 +1,101 @@ +package org.simpleble.android + +import android.Manifest +import android.app.Activity +import android.content.Context +import android.content.pm.PackageManager +import android.util.Log +import androidx.core.app.ActivityCompat +import androidx.core.content.ContextCompat +import java.lang.ref.WeakReference + +class SimpleDroidBle { + companion object { + + lateinit var contextReference: WeakReference + private val context: Context + get() { + return contextReference.get() + ?: throw IllegalStateException("PermissionsManager: Permissions requested outside activity!") + } + private var hasPermissionBluetooth: Boolean = false + private var hasPermissionBluetoothAdmin: Boolean = false + private var hasPermissionBluetoothConnect: Boolean = false + private var hasPermissionBluetoothScan: Boolean = false + + val hasPermissions: Boolean + get() { + hasPermissionBluetooth = isPermissionGranted(Manifest.permission.BLUETOOTH) + hasPermissionBluetoothAdmin = isPermissionGranted(Manifest.permission.BLUETOOTH_ADMIN) + hasPermissionBluetoothConnect = isPermissionGranted(Manifest.permission.BLUETOOTH_CONNECT) + hasPermissionBluetoothScan = isPermissionGranted(Manifest.permission.BLUETOOTH_SCAN) + + return hasPermissionBluetooth && + hasPermissionBluetoothAdmin && + hasPermissionBluetoothConnect && + hasPermissionBluetoothScan + } + + init { + System.loadLibrary("simpleble-jni") + } + + fun requestPermissions() { + if (!hasPermissions) { + ActivityCompat.requestPermissions( + context as Activity, + arrayOf( + Manifest.permission.BLUETOOTH, + Manifest.permission.BLUETOOTH_ADMIN, + Manifest.permission.BLUETOOTH_CONNECT, + Manifest.permission.BLUETOOTH_SCAN + ), + 1 + ) + } + } + + fun handleOnRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) { + if (requestCode != 1) return + + val length = permissions.size + if (length != grantResults.size) { + Log.e("PermissionsManager", "Permissions and grant results are not the same size!") + return + } + + for (i in 0 until length) { + val permission = permissions[i] + val grantResult = grantResults[i] + when (permission) { + Manifest.permission.BLUETOOTH -> { + hasPermissionBluetooth = grantResult == PackageManager.PERMISSION_GRANTED + } + Manifest.permission.BLUETOOTH_ADMIN -> { + hasPermissionBluetoothAdmin = grantResult == PackageManager.PERMISSION_GRANTED + } + Manifest.permission.BLUETOOTH_CONNECT -> { + hasPermissionBluetoothConnect = grantResult == PackageManager.PERMISSION_GRANTED + } + Manifest.permission.BLUETOOTH_SCAN -> { + hasPermissionBluetoothScan = grantResult == PackageManager.PERMISSION_GRANTED + } + } + } + } + + + @JvmStatic + fun getVersion(): String { + return "1.0.0" + } + + private fun isPermissionGranted(permission: String): Boolean { + return ContextCompat.checkSelfPermission( + context, + permission + ) == PackageManager.PERMISSION_GRANTED + } + + } +} \ No newline at end of file diff --git a/third_party/SimpleBLE/simplepyble/CMakeLists.txt b/third_party/SimpleBLE/simplepyble/CMakeLists.txt index 6b93fd5ae..9b12ca584 100644 --- a/third_party/SimpleBLE/simplepyble/CMakeLists.txt +++ b/third_party/SimpleBLE/simplepyble/CMakeLists.txt @@ -8,30 +8,33 @@ set(CMAKE_CXX_EXTENSIONS NO) project(simplepyble) +include(GNUInstallDirs) + include(${CMAKE_CURRENT_LIST_DIR}/../cmake/epilogue.cmake) find_package(pybind11 REQUIRED) add_subdirectory(${CMAKE_CURRENT_LIST_DIR}/../simpleble ${CMAKE_BINARY_DIR}/simpleble) pybind11_add_module( - simplepyble + _simplepyble src/main.cpp src/wrap_adapter.cpp src/wrap_peripheral.cpp src/wrap_service.cpp src/wrap_characteristic.cpp src/wrap_descriptor.cpp + src/wrap_types.cpp ) -target_link_libraries(simplepyble PRIVATE simpleble::simpleble) -target_compile_definitions(simplepyble PRIVATE "-DSIMPLEPYBLE_VERSION=\"${SIMPLEPYBLE_VERSION}\"") +target_link_libraries(_simplepyble PRIVATE simpleble::simpleble) +target_compile_definitions(_simplepyble PRIVATE "-DSIMPLEPYBLE_VERSION=\"${SIMPLEPYBLE_VERSION}\"") set_target_properties( - simplepyble PROPERTIES + _simplepyble PROPERTIES CXX_STANDARD 17 ) install( - TARGETS simplepyble - LIBRARY DESTINATION "./" # Library needs to be installed at the provided path on CMAKE_INSTALL_PREFIX + TARGETS _simplepyble + DESTINATION . ) diff --git a/third_party/SimpleBLE/simplepyble/README.rst b/third_party/SimpleBLE/simplepyble/README.rst index e51dffd3d..6437939c1 100644 --- a/third_party/SimpleBLE/simplepyble/README.rst +++ b/third_party/SimpleBLE/simplepyble/README.rst @@ -29,6 +29,8 @@ Windows Linux MacOS iOS Windows 10+ Ubuntu 20.04+ 10.15+ (except 12.0, 12.1 and 12.2) 15.0+ =========== ============= =================================== ===== +**NOTE:** WSL does not support Bluetooth. + Installation ------------ @@ -45,10 +47,18 @@ Pull requests are welcome. For major changes, please open an issue first to disc what you would like to change. License -------- +======= + +Since February 15th 2024, SimpleBLE is now available under the GNU General Public License +version 3 (GPLv3), with the option for a commercial license without the GPLv3 restrictions +available for a fee. + +**More information on pricing and commercial terms of service will be available soon.** -All components within this project that have not been bundled from -external creators, are licensed under the terms of the `MIT Licence`_. +To enquire about a commercial license, please contact us at ``contact at simpleble dot org``. + +Likewise, if you are using SimpleBLE in an open-source project and would like to request +a free commercial license or if you have any other questions, please reach out at ``contact at simpleble dot org``. .. Links @@ -58,8 +68,6 @@ external creators, are licensed under the terms of the `MIT Licence`_. .. _code examples: https://github.com/OpenBluetoothToolbox/SimpleBLE/tree/main/examples/simplepyble -.. _MIT Licence: https://github.com/OpenBluetoothToolbox/SimpleBLE/blob/main/LICENCE.md - .. _Discord: https://discord.gg/N9HqNEcvP3 .. _ReadTheDocs: https://simpleble.readthedocs.io/en/latest/ @@ -69,3 +77,8 @@ external creators, are licensed under the terms of the `MIT Licence`_. .. |PyPI Licence| image:: https://img.shields.io/pypi/l/simplepyble +.. Other projects using SimpleBLE + +.. _BrainFlow: https://github.com/brainflow-dev/brainflow +.. _InsideBlue: https://github.com/eriklins/InsideBlue-BLE-Tool +.. _NodeWebBluetooth: https://github.com/thegecko/webbluetooth diff --git a/third_party/SimpleBLE/simplepyble/cmake_build_extension/__init__.py b/third_party/SimpleBLE/simplepyble/cmake_build_extension/__init__.py deleted file mode 100644 index 58361eebe..000000000 --- a/third_party/SimpleBLE/simplepyble/cmake_build_extension/__init__.py +++ /dev/null @@ -1,49 +0,0 @@ -import os -from contextlib import contextmanager -from pathlib import Path - -from . import build_ext_option, sdist_command -from .build_extension import BuildExtension -from .cmake_extension import CMakeExtension -from .sdist_command import GitSdistFolder, GitSdistTree - - -@contextmanager -def build_extension_env(): - """ - Creates a context in which build extensions can be imported. - - It fixes a change of behaviour of Python >= 3.8 in Windows: - https://docs.python.org/3/whatsnew/3.8.html#bpo-36085-whatsnew - - Other related resources: - - - https://stackoverflow.com/a/23805306 - - https://www.mail-archive.com/dev@subversion.apache.org/msg40414.html - - Example: - - .. code-block:: python - - from cmake_build_extension import build_extension_env - - with build_extension_env(): - from . import bindings - """ - - cookies = [] - - # Windows and Python >= 3.8 - if hasattr(os, "add_dll_directory"): - - for path in os.environ.get("PATH", "").split(os.pathsep): - - if path and Path(path).is_absolute() and Path(path).is_dir(): - cookies.append(os.add_dll_directory(path)) - - try: - yield - - finally: - for cookie in cookies: - cookie.close() \ No newline at end of file diff --git a/third_party/SimpleBLE/simplepyble/cmake_build_extension/build_ext_option.py b/third_party/SimpleBLE/simplepyble/cmake_build_extension/build_ext_option.py deleted file mode 100644 index 8ee4c42c9..000000000 --- a/third_party/SimpleBLE/simplepyble/cmake_build_extension/build_ext_option.py +++ /dev/null @@ -1,55 +0,0 @@ -from typing import NamedTuple - -from setuptools.command.build_ext import build_ext - - -class BuildExtOption(NamedTuple): - """ - NamedTuple that stores the metadata of a custom build_ext option. - - Example: - - The following option: - - BuildExtOption(variable="define", short="D", help="New compiler define") - - is displayed as follows: - - $ python setup.py build_ext --help - ... - Options for 'BuildExtension' command: - ... - --define (-D) New compiler define - ... - """ - - variable: str - short: str - help: str = "" - - -def add_new_build_ext_option(option: BuildExtOption, override: bool = True): - """ - Workaround to add an existing option shown in python setup.py build_ext -h. - - Args: - option: The new option to add. - override: Delete the option if it already exists. - """ - - if override: - # Remove from the existing build_ext.user_options the option to override - build_ext.user_options = [ - o for o in build_ext.user_options if o[1] is not option.short - ] - else: - # Just check if the option already exists, and raise if it does - for o in build_ext.user_options: - if o[1] == option.short: - raise ValueError(f"Short option '{o[1]}' already exists") - - # The long variable name must finish with =, here we append it - option = option._replace(variable=f"{option.variable}=") - - # Add the new option - build_ext.user_options.append(tuple(option)) \ No newline at end of file diff --git a/third_party/SimpleBLE/simplepyble/cmake_build_extension/build_extension.py b/third_party/SimpleBLE/simplepyble/cmake_build_extension/build_extension.py deleted file mode 100644 index d5c07e88c..000000000 --- a/third_party/SimpleBLE/simplepyble/cmake_build_extension/build_extension.py +++ /dev/null @@ -1,281 +0,0 @@ -import importlib.util -import os -import platform -import shutil -import subprocess -from pathlib import Path - -from setuptools.command.build_ext import build_ext - -from .build_ext_option import BuildExtOption, add_new_build_ext_option -from .cmake_extension import CMakeExtension - -# These options are listed in `python setup.py build_ext -h` -custom_options = [ - BuildExtOption( - variable="define", - short="D", - help="Create or update CMake cache " "(example: '-DBAR=b;FOO=f')", - ), - BuildExtOption( - variable="component", - short="C", - help="Install only a specific CMake component (example: '-Cbindings')", - ), - BuildExtOption( - variable="no-cmake-extension", - short="K", - help="Disable a CMakeExtension module (examples: '-Kall', '-Kbar', '-Kbar;foo')", - ), -] - -for o in custom_options: - add_new_build_ext_option(option=o, override=True) - - -class BuildExtension(build_ext): - """ - Setuptools build extension handler. - It processes all the extensions listed in the 'ext_modules' entry. - """ - - def initialize_options(self): - - # Initialize base class - build_ext.initialize_options(self) - - # Initialize the '--define' custom option, overriding the pre-existing one. - # Originally, it was aimed to pass C preprocessor definitions, but instead we - # use it to pass custom configuration options to CMake. - self.define = None - - # Initialize the '--component' custom option. - # It overrides the content of the cmake_component option of CMakeExtension. - self.component = None - - def finalize_options(self): - - # Parse the custom CMake options and store them in a new attribute - defines = [] if self.define is None else self.define.split(";") - self.cmake_defines = [f"-D{define}" for define in defines] - - # Call base class - build_ext.finalize_options(self) - - def run(self) -> None: - # Check that CMake is installed - if shutil.which("cmake") is None: - raise RuntimeError("Required command 'cmake' not found") - - # Check that Ninja is installed - if shutil.which("ninja") is None: - raise RuntimeError("Required command 'ninja' not found") - - for ext in self.extensions: - self.build_extension(ext) - - def __get_msvc_arch(self) -> str: - if self.plat_name == "win32": - return "Win32" - elif self.plat_name == "win-amd64": - return "x64" - elif self.plat_name == "win-arm32": - return "ARM" - elif self.plat_name == "win-arm64": - return "ARM64" - else: - raise RuntimeError(f"Unsupported platform: {platform}") - - def build_extension(self, ext: CMakeExtension) -> None: - """ - Build a CMakeExtension object. - - Args: - ext: The CMakeExtension object to build. - """ - - if self.inplace and ext.disable_editable: - print(f"Editable install recognized. Extension '{ext.name}' disabled.") - return - - # Export CMAKE_PREFIX_PATH of all the dependencies - for pkg in ext.cmake_depends_on: - - try: - importlib.import_module(pkg) - except ImportError: - raise ValueError(f"Failed to import '{pkg}'") - - init = importlib.util.find_spec(pkg).origin - BuildExtension.extend_cmake_prefix_path(path=str(Path(init).parent)) - - # The ext_dir directory can be thought as a temporary site-package folder. - # - # Case 1: regular installation. - # ext_dir is the folder that gets compressed to make the wheel archive. When - # installed, the archive is extracted in the active site-package directory. - # Case 2: editable installation. - # ext_dir is the in-source folder containing the Python packages. In this case, - # the CMake project is installed in-source. - ext_dir = Path(self.get_ext_fullpath(ext.name)).parent.absolute() - cmake_install_prefix = ext_dir / ext.install_prefix - - # Initialize the CMake configuration arguments - configure_args = [] - - # Select the appropriate generator and accompanying settings - if ext.cmake_generator is not None: - configure_args += [f"-G \"{ext.cmake_generator}\""] - - if ext.cmake_generator == "Ninja": - # Fix #26: https://github.com/diegoferigo/cmake-build-extension/issues/26 - configure_args += [f"-DCMAKE_MAKE_PROGRAM={shutil.which('ninja')}"] - - # CMake configure arguments - configure_args += [ - f"-DCMAKE_BUILD_TYPE={ext.cmake_build_type}", - f"-DCMAKE_INSTALL_PREFIX:PATH={cmake_install_prefix}", - ] - - # Extend the configure arguments with those passed from the extension - configure_args += ext.cmake_configure_options - - # CMake build arguments - build_args = ["--config", ext.cmake_build_type] - - if platform.system() == "Windows": - - configure_args += [f"-A {self.__get_msvc_arch()}"] - - elif platform.system() in {"Linux", "Darwin"}: - - configure_args += [] - - else: - raise RuntimeError(f"Unsupported '{platform.system()}' platform") - - # Parse the optional CMake options. They can be passed as: - # - # python setup.py build_ext -D"BAR=Foo;VAR=TRUE" - # python setup.py bdist_wheel build_ext -D"BAR=Foo;VAR=TRUE" - # python setup.py install build_ext -D"BAR=Foo;VAR=TRUE" - # python setup.py install -e build_ext -D"BAR=Foo;VAR=TRUE" - # pip install --global-option="build_ext" --global-option="-DBAR=Foo;VAR=TRUE" . - # - configure_args += self.cmake_defines - - # Get the absolute path to the build folder - build_folder = str(Path(".").absolute() / f"{self.build_temp}_{ext.name}") - - # Make sure that the build folder exists - Path(build_folder).mkdir(exist_ok=True, parents=True) - - # 1. Compose CMake configure command - configure_command = [ - "cmake", - "-S", - ext.source_dir, - "-B", - build_folder, - ] + configure_args - - # 2. Compose CMake build command - build_command = ["cmake", "--build", build_folder] + build_args - - # 3. Compose CMake install command - install_command = ["cmake", "--install", build_folder] - - # If the cmake_component option of the CMakeExtension is used, install just - # the specified component. - if self.component is None and ext.cmake_component is not None: - install_command.extend(["--component", ext.cmake_component]) - - # Instead, if the `--component` command line option is used, install just - # the specified component. This has higher priority than what specified in - # the CMakeExtension. - if self.component is not None: - install_command.extend(["--component", self.component]) - - print("") - print("==> Configuring:") - print(f"$ {' '.join(configure_command)}") - subprocess.check_call(configure_command) - print("") - print("==> Building:") - print(f"$ {' '.join(build_command)}") - subprocess.check_call(build_command) - print("") - print("==> Installing:") - print(f"$ {' '.join(install_command)}") - subprocess.check_call(install_command) - print("") - - # Write content to the top-level __init__.py - if ext.write_top_level_init is not None: - with open(file=cmake_install_prefix / "__init__.py", mode="w") as f: - f.write(ext.write_top_level_init) - - # Write content to the bin/__main__.py magic file to expose binaries - if len(ext.expose_binaries) > 0: - bin_dirs = {str(Path(d).parents[0]) for d in ext.expose_binaries} - - import inspect - - main_py = inspect.cleandoc( - f""" - from pathlib import Path - import subprocess - import sys - - def main(): - - binary_name = Path(sys.argv[0]).name - prefix = Path(__file__).parent.parent - bin_dirs = {str(bin_dirs)} - - binary_path = "" - - for dir in bin_dirs: - path = prefix / Path(dir) / binary_name - if path.is_file(): - binary_path = str(path) - break - - path = Path(str(path) + ".exe") - if path.is_file(): - binary_path = str(path) - break - - if not Path(binary_path).is_file(): - name = binary_path if binary_path != "" else binary_name - raise RuntimeError(f"Failed to find binary: {{ name }}") - - sys.argv[0] = binary_path - - result = subprocess.run(args=sys.argv, capture_output=False) - exit(result.returncode) - - if __name__ == "__main__" and len(sys.argv) > 1: - sys.argv = sys.argv[1:] - main()""" - ) - - bin_folder = cmake_install_prefix / "bin" - Path(bin_folder).mkdir(exist_ok=True, parents=True) - with open(file=bin_folder / "__main__.py", mode="w") as f: - f.write(main_py) - - @staticmethod - def extend_cmake_prefix_path(path: str) -> None: - - abs_path = Path(path).absolute() - - if not abs_path.exists(): - raise ValueError(f"Path {abs_path} does not exist") - - if "CMAKE_PREFIX_PATH" in os.environ: - os.environ[ - "CMAKE_PREFIX_PATH" - ] = f"{str(path)}:{os.environ['CMAKE_PREFIX_PATH']}" - else: - os.environ["CMAKE_PREFIX_PATH"] = str(path) diff --git a/third_party/SimpleBLE/simplepyble/cmake_build_extension/cmake_extension.py b/third_party/SimpleBLE/simplepyble/cmake_build_extension/cmake_extension.py deleted file mode 100644 index 248e1a021..000000000 --- a/third_party/SimpleBLE/simplepyble/cmake_build_extension/cmake_extension.py +++ /dev/null @@ -1,58 +0,0 @@ -from pathlib import Path -from typing import List - -from setuptools import Extension - - -class CMakeExtension(Extension): - """ - Custom setuptools extension that configures a CMake project. - - Args: - name: The name of the extension. - install_prefix: The path relative to the site-package directory where the CMake - project is installed (typically the name of the Python package). - disable_editable: Skip this extension in editable mode. - write_top_level_init: Create a new top-level ``__init__.py`` file in the install - prefix and write content. - cmake_configure_options: List of additional CMake configure options (-DBAR=FOO). - source_dir: The location of the main CMakeLists.txt. - cmake_build_type: The default build type of the CMake project. - cmake_component: The name of component to install. Defaults to all components. - cmake_depends_on: List of dependency packages containing required CMake projects. - expose_binaries: List of binary paths to expose, relative to top-level directory. - """ - - def __init__( - self, - name: str, - install_prefix: str = "", - disable_editable: bool = False, - write_top_level_init: str = None, - cmake_configure_options: List[str] = (), - source_dir: str = str(Path(".").absolute()), - cmake_build_type: str = "Release", - cmake_component: str = None, - cmake_depends_on: List[str] = (), - expose_binaries: List[str] = (), - cmake_generator: str = "Ninja", - ): - - super().__init__(name=name, sources=[]) - - if not Path(source_dir).is_absolute(): - source_dir = str(Path(".").absolute() / source_dir) - - if not Path(source_dir).absolute().is_dir(): - raise ValueError(f"Directory '{source_dir}' does not exist") - - self.install_prefix = install_prefix - self.cmake_build_type = cmake_build_type - self.disable_editable = disable_editable - self.write_top_level_init = write_top_level_init - self.cmake_depends_on = cmake_depends_on - self.source_dir = str(Path(source_dir).absolute()) - self.cmake_configure_options = cmake_configure_options - self.cmake_component = cmake_component - self.expose_binaries = expose_binaries - self.cmake_generator = cmake_generator diff --git a/third_party/SimpleBLE/simplepyble/cmake_build_extension/sdist_command.py b/third_party/SimpleBLE/simplepyble/cmake_build_extension/sdist_command.py deleted file mode 100644 index 5f7738d32..000000000 --- a/third_party/SimpleBLE/simplepyble/cmake_build_extension/sdist_command.py +++ /dev/null @@ -1,145 +0,0 @@ -import abc -import os -from pathlib import Path -from shutil import copy2 -from typing import Generator, List - -import setuptools.command.sdist - - -class GitSdistABC(abc.ABC, setuptools.command.sdist.sdist): - """ - This class defines a custom command to build source distribution. It covers the case - where projects store the setup.cfg file in a subfolder and are git repositories. - - The problem in this setup is that only the subfolder by default is packaged - in the sdist, resulting in a archive that only contains part of the whole repo. - """ - - def make_release_tree(self, base_dir, files) -> None: - """ - This method is the responsible of building the list of files that are included - in the source distribution. - - These files (that could be the entire git tree) are copied in the subfolder - before creating the archive, resulting in a source distribution like if the - setup.cfg would be part of the top-level folder. - - This method prepares the egg metadata for the source distribution and allows - specifying a list of files that are copied in the location of the setup.cfg. - """ - - import setuptools_scm.integration - - # Build the setuptools_scm configuration, containing useful info for the sdist - config: setuptools_scm.integration.Configuration = ( - setuptools_scm.integration.Configuration.from_file( - dist_name=self.distribution.metadata.name - ) - ) - - # Get the root of the git repository - repo_root = config.absolute_root - - if not Path(repo_root).exists() or not Path(repo_root).is_dir(): - raise RuntimeError(f"Failed to find a git repo in {repo_root}") - - # Prepare the release tree by calling the original method - super(GitSdistABC, self).make_release_tree(base_dir=base_dir, files=files) - - # Collect all the files and copy them in the subfolder containing setup.cfg - for file in self.get_sdist_files(repo_root=repo_root): - - src = Path(file) - dst = Path(base_dir) / Path(file).relative_to(repo_root) - - # Make sure that the parent directory of the destination exists - dst.absolute().parent.mkdir(parents=True, exist_ok=True) - - print(f"{Path(file).relative_to(repo_root)} -> {dst}") - copy2(src=src, dst=dst) - - # Create the updated list of files included in the sdist - all_files_gen = Path(base_dir).glob(pattern="**/*") - all_files = [str(f.relative_to(base_dir)) for f in all_files_gen] - - # Find the SOURCES.txt file - sources_txt_list = list(Path(base_dir).glob(pattern=f"*.egg-info/SOURCES.txt")) - assert len(sources_txt_list) == 1 - - # Update the SOURCES.txt files with the real content of the sdist - os.unlink(sources_txt_list[0]) - with open(file=sources_txt_list[0], mode="w") as f: - f.write("\n".join([str(f) for f in all_files])) - - @staticmethod - @abc.abstractmethod - def get_sdist_files(repo_root: str) -> List[Path]: - """ - Return all files that will be included in the source distribution. - - Note: the egg metadata are included by default, there's not need to specify them. - - Args: - repo_root: The path to the root of the git repository. - - Returns: - The list of files to include in the source distribution. - """ - - -class GitSdistTree(GitSdistABC): - """ - This class defines a custom command to build source distribution. It covers the case - where projects store the setup.cfg file in a subfolder and are git repositories. - - The problem in this setup is that only the subfolder by default is packaged - in the sdist, resulting in a archive that only contains part of the whole repo. - - In particular, this class copies all the files that are part of the last git commit. - Any uncommitted or staged files are ignored and are not part of the sdist. - """ - - @staticmethod - def get_sdist_files(repo_root: str) -> List[Path]: - - import git - - # Create the git Repo object - git_repo = git.Repo(path=repo_root) - - # Get all the files of the git repo recursively - def list_paths( - tree: git.Tree, path: Path = Path(".") - ) -> Generator[Path, None, None]: - - for blob in tree.blobs: - yield path / blob.name - - for tree in tree.trees: - yield from list_paths(tree=tree, path=path / tree.name) - - # Return the list of absolute paths to all the git repo files - return list(list_paths(tree=git_repo.commit().tree, path=Path(repo_root))) - - -class GitSdistFolder(GitSdistABC): - """ - This class defines a custom command to build source distribution. It covers the case - where projects store the setup.cfg file in a subfolder and are git repositories. - - The problem in this setup is that only the subfolder by default is packaged - in the sdist, resulting in a archive that only contains part of the whole repo. - - In particular, this class copies all the files that are part of the git folder. - It includes also all uncommitted and staged files. - """ - - @staticmethod - def get_sdist_files(repo_root: str) -> List[Path]: - - # Create the list of files of the git folder - all_files_gen = Path(repo_root).glob(pattern="**/*") - - # Return the list of absolute paths to all the git folder files (also uncommited) - return [f for f in all_files_gen if not f.is_dir() and ".git" not in f.parts] \ No newline at end of file diff --git a/third_party/SimpleBLE/simplepyble/requirements.txt b/third_party/SimpleBLE/simplepyble/requirements.txt index e3142d4c2..4efdab7d9 100644 --- a/third_party/SimpleBLE/simplepyble/requirements.txt +++ b/third_party/SimpleBLE/simplepyble/requirements.txt @@ -1,7 +1,10 @@ twine +build +auditwheel wheel -ninja +ninja; platform_system!='Windows' pytest pybind11 -setuptools -cibuildwheel==2.9 +scikit-build +cmake>=3.21 +setuptools>=42 diff --git a/third_party/SimpleBLE/simplepyble/src/main.cpp b/third_party/SimpleBLE/simplepyble/src/main.cpp index f1694ac9a..e2a48ec91 100644 --- a/third_party/SimpleBLE/simplepyble/src/main.cpp +++ b/third_party/SimpleBLE/simplepyble/src/main.cpp @@ -13,13 +13,14 @@ namespace py = pybind11; +void wrap_types(py::module& m); void wrap_descriptor(py::module& m); void wrap_characteristic(py::module& m); void wrap_service(py::module& m); void wrap_peripheral(py::module& m); void wrap_adapter(py::module& m); -PYBIND11_MODULE(simplepyble, m) { +PYBIND11_MODULE(_simplepyble, m) { m.attr("__version__") = SIMPLEPYBLE_VERSION; // m.doc() = R"pbdoc( @@ -39,6 +40,11 @@ PYBIND11_MODULE(simplepyble, m) { Returns the currently-running operating system. )pbdoc"); + m.def("get_simpleble_version", &SimpleBLE::get_simpleble_version, R"pbdoc( + Returns the version of SimpleBLE. + )pbdoc"); + + wrap_types(m); wrap_descriptor(m); wrap_characteristic(m); wrap_service(m); diff --git a/third_party/SimpleBLE/simplepyble/src/simplepyble/__init__.py b/third_party/SimpleBLE/simplepyble/src/simplepyble/__init__.py new file mode 100644 index 000000000..fddd3147d --- /dev/null +++ b/third_party/SimpleBLE/simplepyble/src/simplepyble/__init__.py @@ -0,0 +1 @@ +from ._simplepyble import * diff --git a/third_party/SimpleBLE/simplepyble/src/wrap_characteristic.cpp b/third_party/SimpleBLE/simplepyble/src/wrap_characteristic.cpp index 8c1c932f2..411b45bcb 100644 --- a/third_party/SimpleBLE/simplepyble/src/wrap_characteristic.cpp +++ b/third_party/SimpleBLE/simplepyble/src/wrap_characteristic.cpp @@ -18,9 +18,39 @@ constexpr auto kDocsCharacteristicDescriptors = R"pbdoc( Descriptors of the characteristic )pbdoc"; +constexpr auto kDocsCharacteristicCapabilities = R"pbdoc( + Capabilities of the characteristic +)pbdoc"; + +constexpr auto kDocsCharacteristicCanRead = R"pbdoc( + Whether the characteristic can be read +)pbdoc"; + +constexpr auto kDocsCharacteristicCanWriteRequest = R"pbdoc( + Whether the characteristic can be written with a request +)pbdoc"; + +constexpr auto kDocsCharacteristicCanWriteCommand = R"pbdoc( + Whether the characteristic can be written with a command +)pbdoc"; + +constexpr auto kDocsCharacteristicCanNotify = R"pbdoc( + Whether the characteristic can be notified +)pbdoc"; + +constexpr auto kDocsCharacteristicCanIndicate = R"pbdoc( + Whether the characteristic can be indicated +)pbdoc"; + void wrap_characteristic(py::module& m) { // TODO: Add __str__ and __repr__ methods py::class_(m, "Characteristic", kDocsCharacteristic) .def("uuid", &SimpleBLE::Characteristic::uuid, kDocsCharacteristicUuid) - .def("descriptors", &SimpleBLE::Characteristic::descriptors, kDocsCharacteristicDescriptors); + .def("descriptors", &SimpleBLE::Characteristic::descriptors, kDocsCharacteristicDescriptors) + .def("capabilities", &SimpleBLE::Characteristic::capabilities, kDocsCharacteristicCapabilities) + .def("can_read", &SimpleBLE::Characteristic::can_read, kDocsCharacteristicCanRead) + .def("can_write_request", &SimpleBLE::Characteristic::can_write_request, kDocsCharacteristicCanWriteRequest) + .def("can_write_command", &SimpleBLE::Characteristic::can_write_command, kDocsCharacteristicCanWriteCommand) + .def("can_notify", &SimpleBLE::Characteristic::can_notify, kDocsCharacteristicCanNotify) + .def("can_indicate", &SimpleBLE::Characteristic::can_indicate, kDocsCharacteristicCanIndicate); } diff --git a/third_party/SimpleBLE/simplepyble/src/wrap_peripheral.cpp b/third_party/SimpleBLE/simplepyble/src/wrap_peripheral.cpp index cdbb15f02..af6595398 100644 --- a/third_party/SimpleBLE/simplepyble/src/wrap_peripheral.cpp +++ b/third_party/SimpleBLE/simplepyble/src/wrap_peripheral.cpp @@ -22,10 +22,22 @@ constexpr auto kDocsPeripheralAddress = R"pbdoc( Address of the peripheral )pbdoc"; +constexpr auto kDocsPeripheralAddressType = R"pbdoc( + Address Type of the peripheral +)pbdoc"; + constexpr auto kDocsPeripheralRSSI = R"pbdoc( RSSI of the peripheral )pbdoc"; +constexpr auto kDocsPeripheralTxPower = R"pbdoc( + Transit Power of the peripheral in dBm +)pbdoc"; + +constexpr auto kDocsPeripheralMtu = R"pbdoc( + Get the negotiated MTU value +)pbdoc"; + constexpr auto kDocsPeripheralConnect = R"pbdoc( Connect to the peripheral )pbdoc"; @@ -98,13 +110,18 @@ constexpr auto kDocsPeripheralSetCallbackOnDisconnected = R"pbdoc( Set callback on disconnected )pbdoc"; +// clang-format off + void wrap_peripheral(py::module& m) { // TODO: Add __str__ and __repr__ methods py::class_(m, "Peripheral", kDocsPeripheral) .def("initialized", &SimpleBLE::Peripheral::initialized, kDocsPeripheralInitialized) .def("identifier", &SimpleBLE::Peripheral::identifier, kDocsPeripheralIdentifier) .def("address", &SimpleBLE::Peripheral::address, kDocsPeripheralAddress) + .def("address_type", &SimpleBLE::Peripheral::address_type, kDocsPeripheralAddressType) .def("rssi", &SimpleBLE::Peripheral::rssi, kDocsPeripheralRSSI) + .def("tx_power", &SimpleBLE::Peripheral::tx_power, kDocsPeripheralTxPower) + .def("mtu", &SimpleBLE::Peripheral::mtu, kDocsPeripheralMtu) .def("connect", &SimpleBLE::Peripheral::connect, py::call_guard(), kDocsPeripheralConnect) .def("disconnect", &SimpleBLE::Peripheral::disconnect, kDocsPeripheralDisconnect) @@ -132,40 +149,53 @@ void wrap_peripheral(py::module& m) { .def( "write_request", [](SimpleBLE::Peripheral& p, std::string service, std::string characteristic, py::bytes payload) { - p.write_request(service, characteristic, payload); + // Note py::bytes implicitly converts to std::string + SimpleBLE::ByteArray cpp_payload(payload); + py::gil_scoped_release release; + p.write_request(service, characteristic, cpp_payload); }, kDocsPeripheralWriteRequest) .def( "write_command", [](SimpleBLE::Peripheral& p, std::string service, std::string characteristic, py::bytes payload) { - p.write_command(service, characteristic, payload); + // Note py::bytes implicitly converts to std::string + SimpleBLE::ByteArray cpp_payload(payload); + py::gil_scoped_release release; + p.write_command(service, characteristic, cpp_payload); }, kDocsPeripheralWriteCommand) .def( "notify", - [](SimpleBLE::Peripheral& p, std::string service, std::string characteristic, - std::function cb) { - p.notify(service, characteristic, [cb](SimpleBLE::ByteArray payload) { cb(py::bytes(payload)); }); + [](SimpleBLE::Peripheral& p, std::string service, std::string characteristic, std::function cb) { + p.notify(service, characteristic, [cb](SimpleBLE::ByteArray payload) { + py::gil_scoped_acquire gil; + cb(py::bytes(payload)); + }); }, kDocsPeripheralNotify) .def( "indicate", - [](SimpleBLE::Peripheral& p, std::string service, std::string characteristic, - std::function cb) { - p.indicate(service, characteristic, [cb](SimpleBLE::ByteArray payload) { cb(py::bytes(payload)); }); + [](SimpleBLE::Peripheral& p, std::string service, std::string characteristic, std::function cb) { + p.indicate(service, characteristic, [cb](SimpleBLE::ByteArray payload) { + py::gil_scoped_acquire gil; + cb(py::bytes(payload)); + }); }, kDocsPeripheralIndicate) .def("unsubscribe", &SimpleBLE::Peripheral::unsubscribe, kDocsPeripheralUnsubscribe) .def( "descriptor_read", - [](SimpleBLE::Peripheral& p, std::string const& service, std::string const& characteristic, - std::string const& descriptor) { return py::bytes(p.read(service, characteristic, descriptor)); }, + [](SimpleBLE::Peripheral& p, std::string const& service, std::string const& characteristic, std::string const& descriptor) { + return py::bytes(p.read(service, characteristic, descriptor)); + }, kDocsPeripheralDescriptorRead) .def( "descriptor_write", - [](SimpleBLE::Peripheral& p, std::string service, std::string characteristic, std::string const& descriptor, - py::bytes payload) { p.write(service, characteristic, descriptor, payload); }, + [](SimpleBLE::Peripheral& p, std::string service, std::string characteristic, std::string const& descriptor, py::bytes payload) { + // Note py::bytes implicitly converts to std::string + p.write(service, characteristic, descriptor, SimpleBLE::ByteArray(payload)); + }, kDocsPeripheralDescriptorWrite) .def("set_callback_on_connected", &SimpleBLE::Peripheral::set_callback_on_connected, py::keep_alive<1, 2>(), @@ -173,3 +203,5 @@ void wrap_peripheral(py::module& m) { .def("set_callback_on_disconnected", &SimpleBLE::Peripheral::set_callback_on_disconnected, py::keep_alive<1, 2>(), kDocsPeripheralSetCallbackOnDisconnected); } + +// clang-format on \ No newline at end of file diff --git a/third_party/SimpleBLE/simplepyble/src/wrap_service.cpp b/third_party/SimpleBLE/simplepyble/src/wrap_service.cpp index 81dab82c9..b5d4afe61 100644 --- a/third_party/SimpleBLE/simplepyble/src/wrap_service.cpp +++ b/third_party/SimpleBLE/simplepyble/src/wrap_service.cpp @@ -14,6 +14,10 @@ constexpr auto kDocsServiceUuid = R"pbdoc( UUID of the service )pbdoc"; +constexpr auto kDocsServiceData = R"pbdoc( + Advertised service data +)pbdoc"; + constexpr auto kDocsServiceCharacteristics = R"pbdoc( Characteristics of the service )pbdoc"; @@ -22,5 +26,7 @@ void wrap_service(py::module& m) { // TODO: Add __str__ and __repr__ methods py::class_(m, "Service", kDocsService) .def("uuid", &SimpleBLE::Service::uuid, kDocsServiceUuid) + .def( + "data", [](SimpleBLE::Service& s) { return py::bytes(s.data()); }, kDocsServiceData) .def("characteristics", &SimpleBLE::Service::characteristics, kDocsServiceCharacteristics); } diff --git a/third_party/SimpleBLE/simplepyble/src/wrap_types.cpp b/third_party/SimpleBLE/simplepyble/src/wrap_types.cpp new file mode 100644 index 000000000..93f8b3c23 --- /dev/null +++ b/third_party/SimpleBLE/simplepyble/src/wrap_types.cpp @@ -0,0 +1,21 @@ +#include +#include +#include + +#include "simpleble/Types.h" + +namespace py = pybind11; + +void wrap_types(py::module& m) { + py::enum_(m, "OperatingSystem") + .value("WINDOWS", SimpleBLE::OperatingSystem::WINDOWS) + .value("MACOS", SimpleBLE::OperatingSystem::MACOS) + .value("LINUX", SimpleBLE::OperatingSystem::LINUX) + .export_values(); + + py::enum_(m, "BluetoothAddressType") + .value("PUBLIC", SimpleBLE::BluetoothAddressType::PUBLIC) + .value("RANDOM", SimpleBLE::BluetoothAddressType::RANDOM) + .value("UNSPECIFIED", SimpleBLE::BluetoothAddressType::UNSPECIFIED) + .export_values(); +} diff --git a/third_party/SimpleBLE/simplersble/README.md b/third_party/SimpleBLE/simplersble/README.md new file mode 100644 index 000000000..013873611 --- /dev/null +++ b/third_party/SimpleBLE/simplersble/README.md @@ -0,0 +1,53 @@ +# SimpleRsBLE + +The ultimate fully-fledged cross-platform library and bindings for Bluetooth Low Energy (BLE). + +## Overview + +The [SimpleBLE](https://github.com/OpenBluetoothToolbox/SimpleBLE/) project aims to provide +fully cross-platform BLE libraries and bindings, designed for simplicity and ease of use +with a licencing scheme chosen to be friendly towards commercial use. All specific operating +system quirks are handled internally to provide a consistent behavior across all platforms. +The libraries also provide first-class support for vendorization of all third-party +dependencies, allowing for easy integration into existing projects. + +If you want to use SimpleRsBLE and need help. **Please do not hesitate to reach out!** + +- Join our [Discord](https://discord.gg/N9HqNEcvP3) server. +- Contact me: `kevin at dewald dot me` + +## Supported platforms + +- Windows: Windows 10+ +- Linux: Ubuntu 20.04+ +- MacOS: 10.15+ (except 12.0, 12.1, and 12.2) +- iOS: 15.0+ + +## Usage + +You can add SimpleRsBLE to your project by adding the following lines to your `Cargo.toml`: + +```toml +[dependencies] +simplersble = "0.6.0" +``` + +Please review our [code examples](https://github.com/OpenBluetoothToolbox/SimpleBLE/tree/main/examples/simplersble/src/bin) +on GitHub for more information on how to use SimpleRsBLE. + +## Contributing + +Pull requests are welcome. For major changes, please open an issue first to discuss +what you would like to change. + +# License + +Since February 15th 2024, SimpleBLE is now available under the GNU General Public License +version 3 (GPLv3), with the option for a commercial license without the GPLv3 restrictions +available for a fee. (More information on pricing and commercial terms of service will be +available soon.) + +To enquire about a commercial license, please contact us at `contact at simpleble dot org`. + +Likewise, if you are using SimpleBLE in an open-source project and would like to request +a free commercial license or if you have any other questions, please reach out at `contact at simpleble dot org`. diff --git a/third_party/SimpleBLE/simplersble/build.rs b/third_party/SimpleBLE/simplersble/build.rs new file mode 100644 index 000000000..64c2b3151 --- /dev/null +++ b/third_party/SimpleBLE/simplersble/build.rs @@ -0,0 +1,62 @@ +use cmake; +use cxx_build; +use std::env; +use std::path::Path; + +fn compile_simpleble() { + let build_debug = env::var("DEBUG").unwrap() == "true"; + if build_debug { println!("cargo:warning=Building in DEBUG mode"); } + + let cargo_manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap(); + let simplersble_source_path = Path::new(&cargo_manifest_dir).join("simplersble"); + + println!("cargo:warning=CWD: {}", env::current_dir().unwrap().display()); + println!("cargo:warning=ENV: {} - {}", "OUT_DIR", env::var("OUT_DIR").unwrap()); + println!("cargo:warning=ENV: {} - {}", "CARGO_MANIFEST_DIR", env::var("CARGO_MANIFEST_DIR").unwrap()); + println!("cargo:warning=ENV: {} - {}", "CARGO_PKG_NAME", env::var("CARGO_PKG_NAME").unwrap()); + println!("cargo:warning=ENV: {} - {}", "CARGO_PKG_VERSION", env::var("CARGO_PKG_VERSION").unwrap()); + + // The simpleble library name depends if we're building in debug more or not. + let simpleble_library_name = if build_debug {"simpleble-debug"} else {"simpleble"}; + let simpleble_build_dest = cmake::Config::new("simpleble").build(); + let simpleble_include_path = Path::new(&simpleble_build_dest).join("include"); + + cxx_build::CFG.exported_header_dirs.push(&simpleble_include_path); + cxx_build::CFG.exported_header_dirs.push(&simplersble_source_path); + + println!("cargo:rustc-link-search=native={}/lib", simpleble_build_dest.display()); + println!("cargo:rustc-link-lib=static={}", simpleble_library_name); + + let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap(); + match target_os.as_str() { + "macos" => { + println!("cargo:rustc-link-lib=framework=Foundation"); + println!("cargo:rustc-link-lib=framework=CoreBluetooth"); + }, + "windows" => {}, + "linux" => { + println!("cargo:rustc-link-lib=dbus-1"); + }, + &_ => panic!("Unexpected target OS") + } +} + +fn main() { + // TODO: Add all files that would trigger a rerun + println!("cargo:rerun-if-changed=build.rs"); + println!("cargo:rerun-if-changed=src/lib.rs"); + println!("cargo:rerun-if-changed=src/bindings/Bindings.hpp"); + println!("cargo:rerun-if-changed=src/bindings/Bindings.cpp"); + + compile_simpleble(); + + if std::env::var("DOCS_RS").is_ok() { + println!("cargo:warning=Building DOCS"); + } + + // Build the bindings + cxx_build::bridge("simplersble/src/lib.rs") + .file("simplersble/src/bindings/Bindings.cpp") + .flag_if_supported("-std=c++17") + .compile("simpleble_bindings"); +} diff --git a/third_party/SimpleBLE/simplersble/src/bindings/Bindings.cpp b/third_party/SimpleBLE/simplersble/src/bindings/Bindings.cpp new file mode 100644 index 000000000..762260989 --- /dev/null +++ b/third_party/SimpleBLE/simplersble/src/bindings/Bindings.cpp @@ -0,0 +1,328 @@ +#include "Bindings.hpp" +#include + +#include "simplersble/simplersble/src/lib.rs.h" + +rust::Vec Bindings::RustyAdapter_get_adapters() { + rust::Vec result; + + for (auto& adapter : SimpleBLE::Adapter::get_adapters()) { + Bindings::RustyAdapterWrapper wrapper; + wrapper.internal = std::make_unique(adapter); + result.push_back(std::move(wrapper)); + } + + return result; +} + +bool Bindings::RustyAdapter_bluetooth_enabled() { return SimpleBLE::Adapter::bluetooth_enabled(); } + +// Adapter Bindings + +void Bindings::RustyAdapter::link(SimpleRsBLE::Adapter& target) const { + // Time to explain the weird shenanigan we're doing here: + // The TL;DR is that we're making the Adapter(Rust) and the RustyAdapter(C++) + // point to each other in a safe way. + // To achieve this, the Adapter(Rust) owns a RustyAdapter(C++) via a UniquePtr, + // which ensures that calls will always be made to a valid C++ object. + // We now give the RustyAdapter(C++) a pointer back to the Adapter(Rust), + // so that callbacks can be forwarded back to the Rust domain. + // In order to ensure that the Adapter(Rust) is always valid (given + // that Rust is keen on moving stuff around) the object is created as a + // Pin> + + // `_adapter` is a pointer to a pointer, allowing us to manipulate the contents within const functions. + *_adapter = ⌖ // THIS LINE IS SUPER IMPORTANT + + _internal->set_callback_on_scan_start([this]() { + SimpleRsBLE::Adapter* p_adapter = *this->_adapter; + if (p_adapter == nullptr) return; + + p_adapter->on_callback_scan_start(); + }); + + _internal->set_callback_on_scan_stop([this]() { + SimpleRsBLE::Adapter* p_adapter = *this->_adapter; + if (p_adapter == nullptr) return; + + p_adapter->on_callback_scan_stop(); + }); + + _internal->set_callback_on_scan_found([this](SimpleBLE::Peripheral peripheral) { + SimpleRsBLE::Adapter* p_adapter = *this->_adapter; + if (p_adapter == nullptr) return; + + Bindings::RustyPeripheralWrapper wrapper; + wrapper.internal = std::make_unique(peripheral); + p_adapter->on_callback_scan_found(wrapper); + }); + + _internal->set_callback_on_scan_updated([this](SimpleBLE::Peripheral peripheral) { + SimpleRsBLE::Adapter* p_adapter = *this->_adapter; + if (p_adapter == nullptr) return; + + Bindings::RustyPeripheralWrapper wrapper; + wrapper.internal = std::make_unique(peripheral); + p_adapter->on_callback_scan_updated(wrapper); + }); +} + +void Bindings::RustyAdapter::unlink() const { + // `_adapter` is a pointer to a pointer. + *_adapter = nullptr; +} + +rust::String Bindings::RustyAdapter::identifier() const { return rust::String(_internal->identifier()); } + +rust::String Bindings::RustyAdapter::address() const { return rust::String(_internal->address()); } + +void Bindings::RustyAdapter::scan_start() const { _internal->scan_start(); } + +void Bindings::RustyAdapter::scan_stop() const { _internal->scan_stop(); } + +void Bindings::RustyAdapter::scan_for(int32_t timeout_ms) const { _internal->scan_for(timeout_ms); } + +bool Bindings::RustyAdapter::scan_is_active() const { return _internal->scan_is_active(); } + +rust::Vec Bindings::RustyAdapter::scan_get_results() const { + rust::Vec result; + + for (auto& peripheral : _internal->scan_get_results()) { + Bindings::RustyPeripheralWrapper wrapper; + wrapper.internal = std::make_unique(peripheral); + result.push_back(std::move(wrapper)); + } + + return result; +} + +rust::Vec Bindings::RustyAdapter::get_paired_peripherals() const { + rust::Vec result; + + for (auto& peripheral : _internal->get_paired_peripherals()) { + Bindings::RustyPeripheralWrapper wrapper; + wrapper.internal = std::make_unique(peripheral); + result.push_back(std::move(wrapper)); + } + + return result; +} + +// Peripheral Bindings + +void Bindings::RustyPeripheral::link(SimpleRsBLE::Peripheral& target) const { + // Time to explain the weird shenanigan we're doing here: + // The TL;DR is that we're making the Peripheral(Rust) and the RustyPeripheral(C++) + // point to each other in a safe way. + // To achieve this, the Peripheral(Rust) owns a RustyPeripheral(C++) via a UniquePtr, + // which ensures that calls will always be made to a valid C++ object. + // We now give the RustyPeripheral(C++) a pointer back to the Peripheral(Rust), + // so that callbacks can be forwarded back to the Rust domain. + // In order to ensure that the Peripheral(Rust) is always valid (given + // that Rust is keen on moving stuff around) the object is created as a + // Pin> + + // `_peripheral` is a pointer to a pointer, allowing us to manipulate the contents within const functions. + *_peripheral = ⌖ // THIS LINE IS SUPER IMPORTANT + + _internal->set_callback_on_connected([this]() { + SimpleRsBLE::Peripheral* p_peripheral = *this->_peripheral; + if (p_peripheral == nullptr) return; + + p_peripheral->on_callback_connected(); + }); + + _internal->set_callback_on_disconnected([this]() { + SimpleRsBLE::Peripheral* p_peripheral = *this->_peripheral; + if (p_peripheral == nullptr) return; + + p_peripheral->on_callback_disconnected(); + }); +} + +void Bindings::RustyPeripheral::unlink() const { + // `_peripheral` is a pointer to a pointer. + *_peripheral = nullptr; +} + +rust::String Bindings::RustyPeripheral::identifier() const { return rust::String(_internal->identifier()); } + +rust::String Bindings::RustyPeripheral::address() const { return rust::String(_internal->address()); } + +SimpleBLE::BluetoothAddressType Bindings::RustyPeripheral::address_type() const { return _internal->address_type(); } + +int16_t Bindings::RustyPeripheral::rssi() const { return _internal->rssi(); } + +int16_t Bindings::RustyPeripheral::tx_power() const { return _internal->tx_power(); } + +uint16_t Bindings::RustyPeripheral::mtu() const { return _internal->mtu(); } + +void Bindings::RustyPeripheral::connect() const { _internal->connect(); } + +void Bindings::RustyPeripheral::disconnect() const { _internal->disconnect(); } + +bool Bindings::RustyPeripheral::is_connected() const { return _internal->is_connected(); } + +bool Bindings::RustyPeripheral::is_connectable() const { return _internal->is_connectable(); } + +bool Bindings::RustyPeripheral::is_paired() const { return _internal->is_paired(); } + +void Bindings::RustyPeripheral::unpair() const { _internal->unpair(); } + +rust::Vec Bindings::RustyPeripheral::services() const { + rust::Vec result; + + for (auto& service : _internal->services()) { + Bindings::RustyServiceWrapper wrapper; + wrapper.internal = std::make_unique(service); + result.push_back(std::move(wrapper)); + } + + return result; +} + +rust::Vec Bindings::RustyPeripheral::manufacturer_data() const { + rust::Vec result; + + for (auto& manufacturer_data : _internal->manufacturer_data()) { + Bindings::RustyManufacturerDataWrapper wrapper; + wrapper.company_id = manufacturer_data.first; + + for (auto& byte : manufacturer_data.second) { + wrapper.data.push_back(byte); + } + + result.push_back(std::move(wrapper)); + } + + return result; +} + +rust::Vec Bindings::RustyPeripheral::read(rust::String const& service, + rust::String const& characteristic) const { + std::string read_result = _internal->read(std::string(service), std::string(characteristic)); + + rust::Vec result; + for (auto& byte : read_result) { + result.push_back(byte); + } + + return result; +} + +void Bindings::RustyPeripheral::write_request(rust::String const& service_rs, rust::String const& characteristic_rs, + rust::Vec const& data) const { + std::string service(service_rs); + std::string characteristic(characteristic_rs); + std::string data_vec((char*)data.data(), data.size()); + + _internal->write_request(service, characteristic, data_vec); +} + +void Bindings::RustyPeripheral::write_command(rust::String const& service_rs, rust::String const& characteristic_rs, + rust::Vec const& data) const { + std::string service(service_rs); + std::string characteristic(characteristic_rs); + std::string data_vec((char*)data.data(), data.size()); + + _internal->write_command(service, characteristic, data_vec); +} + +void Bindings::RustyPeripheral::notify(rust::String const& service_rs, rust::String const& characteristic_rs) const { + std::string service(service_rs); + std::string characteristic(characteristic_rs); + + _internal->notify(service, characteristic, [this, service_rs, characteristic_rs](std::string data) { + SimpleRsBLE::Peripheral* p_peripheral = *this->_peripheral; + if (p_peripheral == nullptr) return; + + rust::Vec data_vec; + for (auto& byte : data) { + data_vec.push_back(byte); + } + + p_peripheral->on_callback_characteristic_updated(service_rs, characteristic_rs, data_vec); + }); +} + +void Bindings::RustyPeripheral::indicate(rust::String const& service_rs, rust::String const& characteristic_rs) const { + std::string service(service_rs); + std::string characteristic(characteristic_rs); + + _internal->indicate(service, characteristic, [this, service_rs, characteristic_rs](std::string data) { + SimpleRsBLE::Peripheral* p_peripheral = *this->_peripheral; + if (p_peripheral == nullptr) return; + + rust::Vec data_vec; + for (auto& byte : data) { + data_vec.push_back(byte); + } + + p_peripheral->on_callback_characteristic_updated(service_rs, characteristic_rs, data_vec); + }); +} + +void Bindings::RustyPeripheral::unsubscribe(rust::String const& service_rs, + rust::String const& characteristic_rs) const { + std::string service(service_rs); + std::string characteristic(characteristic_rs); + + _internal->unsubscribe(service, characteristic); +} + +rust::Vec Bindings::RustyPeripheral::read_descriptor(rust::String const& service, + rust::String const& characteristic, + rust::String const& descriptor) const { + std::string read_result = _internal->read(std::string(service), std::string(characteristic), + std::string(descriptor)); + + rust::Vec result; + for (auto& byte : read_result) { + result.push_back(byte); + } + + return result; +} + +void Bindings::RustyPeripheral::write_descriptor(rust::String const& service, rust::String const& characteristic, + rust::String const& descriptor, rust::Vec const& data) const { + _internal->write(std::string(service), std::string(characteristic), std::string(descriptor), + std::string((char*)data.data(), data.size())); +} + +// Service Bindings + +rust::Vec Bindings::RustyService::data() const { + rust::Vec result; + for (auto& byte : _internal->data()) { + result.push_back(byte); + } + + return result; +} + +rust::Vec Bindings::RustyService::characteristics() const { + rust::Vec result; + + for (auto& characteristic : _internal->characteristics()) { + Bindings::RustyCharacteristicWrapper wrapper; + wrapper.internal = std::make_unique(characteristic); + result.push_back(std::move(wrapper)); + } + + return result; +} + +// Characteristic Bindings + +rust::Vec Bindings::RustyCharacteristic::descriptors() const { + rust::Vec result; + + for (auto& descriptor : _internal->descriptors()) { + Bindings::RustyDescriptorWrapper wrapper; + wrapper.internal = std::make_unique(descriptor); + result.push_back(std::move(wrapper)); + } + + return result; +} diff --git a/third_party/SimpleBLE/simplersble/src/bindings/Bindings.hpp b/third_party/SimpleBLE/simplersble/src/bindings/Bindings.hpp new file mode 100644 index 000000000..cdc5d7449 --- /dev/null +++ b/third_party/SimpleBLE/simplersble/src/bindings/Bindings.hpp @@ -0,0 +1,177 @@ +#pragma once + +#include "rust/cxx.h" +#include "simpleble/Adapter.h" +#include "simpleble/Peripheral.h" + +#include +#include +#include + +namespace SimpleRsBLE { + +struct Adapter; +struct Peripheral; + +}; // namespace SimpleRsBLE + +namespace Bindings { + +struct RustyAdapterWrapper; +struct RustyPeripheralWrapper; +struct RustyServiceWrapper; +struct RustyCharacteristicWrapper; +struct RustyDescriptorWrapper; +struct RustyManufacturerDataWrapper; + +rust::Vec RustyAdapter_get_adapters(); +bool RustyAdapter_bluetooth_enabled(); + +class RustyAdapter : private SimpleBLE::Adapter { + public: + RustyAdapter() = default; + virtual ~RustyAdapter() { _internal.reset(); } + + RustyAdapter(SimpleBLE::Adapter adapter) + : _internal(new SimpleBLE::Adapter(adapter)), _adapter(std::make_unique()){}; + + void link(SimpleRsBLE::Adapter& target) const; + void unlink() const; + + rust::String identifier() const; + rust::String address() const; + + void scan_start() const; + void scan_stop() const; + void scan_for(int32_t timeout_ms) const; + bool scan_is_active() const; + rust::Vec scan_get_results() const; + + rust::Vec get_paired_peripherals() const; + + private: + // NOTE: All internal properties need to be handled as pointers, + // allowing the calls to RustyAdapter to always be const. + // This might require us to store pointers to pointers, so it's + // important to be careful when handling these. + std::unique_ptr _internal; + std::unique_ptr _adapter; +}; + +class RustyPeripheral : private SimpleBLE::Peripheral { + public: + RustyPeripheral() = default; + virtual ~RustyPeripheral() { _internal.reset(); } + + RustyPeripheral(SimpleBLE::Peripheral peripheral) + : _internal(new SimpleBLE::Peripheral(peripheral)), _peripheral(std::make_unique()) {} + + void link(SimpleRsBLE::Peripheral& target) const; + void unlink() const; + + rust::String identifier() const; + rust::String address() const; + SimpleBLE::BluetoothAddressType address_type() const; + int16_t rssi() const; + + int16_t tx_power() const; + uint16_t mtu() const; + + void connect() const; + void disconnect() const; + bool is_connected() const; + bool is_connectable() const; + bool is_paired() const; + void unpair() const; + + rust::Vec services() const; + rust::Vec manufacturer_data() const; + + rust::Vec read(rust::String const& service, rust::String const& characteristic) const; + void write_request(rust::String const& service, rust::String const& characteristic, + rust::Vec const& data) const; + void write_command(rust::String const& service, rust::String const& characteristic, + rust::Vec const& data) const; + void notify(rust::String const& service, rust::String const& characteristic) const; + void indicate(rust::String const& service, rust::String const& characteristic) const; + void unsubscribe(rust::String const& service, rust::String const& characteristic) const; + + rust::Vec read_descriptor(rust::String const& service, rust::String const& characteristic, + rust::String const& descriptor) const; + void write_descriptor(rust::String const& service, rust::String const& characteristic, + rust::String const& descriptor, rust::Vec const& data) const; + + private: + // NOTE: All internal properties need to be handled as pointers, + // allowing the calls to RustyPeripheral to always be const. + // This might require us to store pointers to pointers, so it's + // important to be careful when handling these. + std::unique_ptr _internal; + std::unique_ptr _peripheral; +}; + +class RustyService : private SimpleBLE::Service { + public: + RustyService() = default; + virtual ~RustyService() = default; + + RustyService(SimpleBLE::Service service) : _internal(new SimpleBLE::Service(service)) {} + + rust::String uuid() const { return rust::String(_internal->uuid()); } + + rust::Vec data() const; + + rust::Vec characteristics() const; + + private: + // NOTE: All internal properties need to be handled as pointers, + // allowing the calls to RustyService to always be const. + // This might require us to store pointers to pointers, so it's + // important to be careful when handling these. + std::shared_ptr _internal; +}; + +class RustyCharacteristic : private SimpleBLE::Characteristic { + public: + RustyCharacteristic() = default; + virtual ~RustyCharacteristic() = default; + + RustyCharacteristic(SimpleBLE::Characteristic characteristic) + : _internal(new SimpleBLE::Characteristic(characteristic)) {} + + rust::String uuid() const { return rust::String(_internal->uuid()); } + + rust::Vec descriptors() const; + + bool can_read() const { return _internal->can_read(); } + bool can_write_request() const { return _internal->can_write_request(); } + bool can_write_command() const { return _internal->can_write_command(); } + bool can_notify() const { return _internal->can_notify(); } + bool can_indicate() const { return _internal->can_indicate(); } + + private: + // NOTE: All internal properties need to be handled as pointers, + // allowing the calls to RustyCharacteristic to always be const. + // This might require us to store pointers to pointers, so it's + // important to be careful when handling these. + std::shared_ptr _internal; +}; + +class RustyDescriptor : private SimpleBLE::Descriptor { + public: + RustyDescriptor() = default; + virtual ~RustyDescriptor() = default; + + RustyDescriptor(SimpleBLE::Descriptor descriptor) : _internal(new SimpleBLE::Descriptor(descriptor)) {} + + rust::String uuid() const { return rust::String(_internal->uuid()); } + + private: + // NOTE: All internal properties need to be handled as pointers, + // allowing the calls to RustyDescriptor to always be const. + // This might require us to store pointers to pointers, so it's + // important to be careful when handling these. + std::shared_ptr _internal; +}; + +}; // namespace Bindings diff --git a/third_party/SimpleBLE/simplersble/src/lib.rs b/third_party/SimpleBLE/simplersble/src/lib.rs new file mode 100644 index 000000000..87e48a805 --- /dev/null +++ b/third_party/SimpleBLE/simplersble/src/lib.rs @@ -0,0 +1,854 @@ +use std::collections::HashMap; +use std::fmt; +use std::mem; +use std::pin::Pin; + +#[cxx::bridge] +mod ffi { + + #[namespace = "Bindings"] + struct RustyAdapterWrapper { + internal: UniquePtr, + } + + #[namespace = "Bindings"] + struct RustyPeripheralWrapper { + internal: UniquePtr, + } + + #[namespace = "Bindings"] + struct RustyServiceWrapper { + internal: UniquePtr, + } + + #[namespace = "Bindings"] + struct RustyCharacteristicWrapper { + internal: UniquePtr, + } + + #[namespace = "Bindings"] + struct RustyDescriptorWrapper { + internal: UniquePtr, + } + + #[namespace = "Bindings"] + struct RustyManufacturerDataWrapper { + company_id: u16, + data: Vec, + } + + #[namespace = "SimpleBLE"] + #[repr(i32)] + enum BluetoothAddressType { + PUBLIC, + RANDOM, + UNSPECIFIED, + } + + #[namespace = "SimpleRsBLE"] + extern "Rust" { + type Adapter; + + fn on_callback_scan_start(self: &mut Adapter); + fn on_callback_scan_stop(self: &mut Adapter); + fn on_callback_scan_updated(self: &mut Adapter, peripheral: &mut RustyPeripheralWrapper); + fn on_callback_scan_found(self: &mut Adapter, peripheral: &mut RustyPeripheralWrapper); + + type Peripheral; + + fn on_callback_connected(self: &mut Peripheral); + fn on_callback_disconnected(self: &mut Peripheral); + fn on_callback_characteristic_updated( + self: &mut Peripheral, + service: &String, + Characteristic: &String, + data: &Vec, + ); + } + + unsafe extern "C++" { + include!("src/bindings/Bindings.hpp"); + + #[namespace = "SimpleBLE"] + type BluetoothAddressType; + + #[namespace = "Bindings"] + type RustyAdapter; + + #[namespace = "Bindings"] + type RustyPeripheral; + + #[namespace = "Bindings"] + type RustyService; + + #[namespace = "Bindings"] + type RustyCharacteristic; + + #[namespace = "Bindings"] + type RustyDescriptor; + + // Common functions + + #[namespace = "Bindings"] + fn RustyAdapter_bluetooth_enabled() -> Result; + + #[namespace = "Bindings"] + fn RustyAdapter_get_adapters() -> Result>; + + // RustyAdapter functions + + fn link(self: &RustyAdapter, target: Pin<&mut Adapter>) -> Result<()>; + fn unlink(self: &RustyAdapter) -> Result<()>; + + fn identifier(self: &RustyAdapter) -> Result; + fn address(self: &RustyAdapter) -> Result; + + fn scan_start(self: &RustyAdapter) -> Result<()>; + fn scan_stop(self: &RustyAdapter) -> Result<()>; + fn scan_for(self: &RustyAdapter, timeout_ms: i32) -> Result<()>; + fn scan_is_active(self: &RustyAdapter) -> Result; + fn scan_get_results(self: &RustyAdapter) -> Result>; + + fn get_paired_peripherals(self: &RustyAdapter) -> Result>; + + // RustyPeripheral functions + + fn link(self: &RustyPeripheral, target: Pin<&mut Peripheral>) -> Result<()>; + fn unlink(self: &RustyPeripheral) -> Result<()>; + + fn identifier(self: &RustyPeripheral) -> Result; + fn address(self: &RustyPeripheral) -> Result; + fn address_type(self: &RustyPeripheral) -> Result; + fn rssi(self: &RustyPeripheral) -> Result; + + fn tx_power(self: &RustyPeripheral) -> Result; + fn mtu(self: &RustyPeripheral) -> Result; + + fn connect(self: &RustyPeripheral) -> Result<()>; + fn disconnect(self: &RustyPeripheral) -> Result<()>; + fn is_connected(self: &RustyPeripheral) -> Result; + fn is_connectable(self: &RustyPeripheral) -> Result; + fn is_paired(self: &RustyPeripheral) -> Result; + fn unpair(self: &RustyPeripheral) -> Result<()>; + + fn services(self: &RustyPeripheral) -> Result>; + fn manufacturer_data(self: &RustyPeripheral) -> Result>; + + fn read( + self: &RustyPeripheral, + service: &String, + characteristic: &String, + ) -> Result>; + fn write_request( + self: &RustyPeripheral, + service: &String, + characteristic: &String, + data: &Vec, + ) -> Result<()>; + fn write_command( + self: &RustyPeripheral, + service: &String, + characteristic: &String, + data: &Vec, + ) -> Result<()>; + fn notify(self: &RustyPeripheral, service: &String, characteristic: &String) -> Result<()>; + fn indicate( + self: &RustyPeripheral, + service: &String, + characteristic: &String, + ) -> Result<()>; + fn unsubscribe( + self: &RustyPeripheral, + service: &String, + characteristic: &String, + ) -> Result<()>; + + fn read_descriptor( + self: &RustyPeripheral, + service: &String, + characteristic: &String, + descriptor: &String, + ) -> Result>; + fn write_descriptor( + self: &RustyPeripheral, + service: &String, + characteristic: &String, + descriptor: &String, + data: &Vec, + ) -> Result<()>; + + // RustyService functions + + fn uuid(self: &RustyService) -> String; + fn data(self: &RustyService) -> Vec; + fn characteristics(self: &RustyService) -> Vec; + + // RustyCharacteristic functions + + fn uuid(self: &RustyCharacteristic) -> String; + fn descriptors(self: &RustyCharacteristic) -> Vec; + + fn can_read(self: &RustyCharacteristic) -> bool; + fn can_write_request(self: &RustyCharacteristic) -> bool; + fn can_write_command(self: &RustyCharacteristic) -> bool; + fn can_notify(self: &RustyCharacteristic) -> bool; + fn can_indicate(self: &RustyCharacteristic) -> bool; + + // RustyDescriptor functions + + fn uuid(self: &RustyDescriptor) -> String; + } +} + +#[derive(Debug, Clone)] +pub struct Error { + msg: String, +} + +#[derive(Debug)] +pub enum BluetoothAddressType { + Public, + Random, + Unspecified, +} + +#[derive(Debug)] +pub enum CharacteristicCapability { + Read, + WriteRequest, + WriteCommand, + Notify, + Indicate, +} + +pub struct Adapter { + internal: cxx::UniquePtr, + on_scan_start: Box, + on_scan_stop: Box, + on_scan_found: Box>) + Send + Sync + 'static>, + on_scan_updated: Box>) + Send + Sync + 'static>, +} + +pub struct Peripheral { + internal: cxx::UniquePtr, + + on_connected: Box, + on_disconnected: Box, + + on_characteristic_update_map: HashMap) + Send + Sync + 'static>>, +} + +pub struct Service { + internal: cxx::UniquePtr, +} + +pub struct Characteristic { + internal: cxx::UniquePtr, +} + +pub struct Descriptor { + internal: cxx::UniquePtr, +} + +impl Adapter { + pub fn bluetooth_enabled() -> Result { + ffi::RustyAdapter_bluetooth_enabled().map_err(|e| Error { + msg: e.what().to_string(), + }) + } + + pub fn get_adapters() -> Result>>, Error> { + let mut raw_adapter_list = ffi::RustyAdapter_get_adapters().map_err(|e| Error { + msg: e.what().to_string(), + })?; + + let mut adapters = Vec::>>::new(); + for adapter_wrapper in raw_adapter_list.iter_mut() { + adapters.push(Adapter::new(adapter_wrapper)); + } + Ok(adapters) + } + + fn new(wrapper: &mut ffi::RustyAdapterWrapper) -> Pin> { + let this = Self { + internal: cxx::UniquePtr::::null(), + on_scan_start: Box::new(|| {}), + on_scan_stop: Box::new(|| {}), + on_scan_found: Box::new(|_| {}), + on_scan_updated: Box::new(|_| {}), + }; + + // Pin the object to guarantee that its location in memory is + // fixed throughout the lifetime of the application + let mut this_boxed = Box::pin(this); + + // Link `this` to the RustyAdapter + wrapper.internal.link(this_boxed.as_mut()).unwrap(); + + // Copy the RustyAdapter pointer into `this` + mem::swap(&mut this_boxed.internal, &mut wrapper.internal); + + return this_boxed; + } + + pub fn identifier(&self) -> Result { + self.internal.identifier().map_err(|e| Error { + msg: e.what().to_string(), + }) + } + + pub fn address(&self) -> Result { + self.internal.address().map_err(|e| Error { + msg: e.what().to_string(), + }) + } + + pub fn scan_start(&self) -> Result<(), Error> { + self.internal.scan_start().map_err(|e| Error { + msg: e.what().to_string(), + }) + } + + pub fn scan_stop(&self) -> Result<(), Error> { + self.internal.scan_stop().map_err(|e| Error { + msg: e.what().to_string(), + }) + } + + pub fn scan_for(&self, timeout_ms: i32) -> Result<(), Error> { + self.internal.scan_for(timeout_ms).map_err(|e| Error { + msg: e.what().to_string(), + }) + } + + pub fn scan_is_active(&self) -> Result { + self.internal.scan_is_active().map_err(|e| Error { + msg: e.what().to_string(), + }) + } + + pub fn scan_get_results(&self) -> Result>>, Error> { + let mut raw_peripheral_list = self.internal.scan_get_results().map_err(|e| Error { + msg: e.what().to_string(), + })?; + + let mut peripherals = Vec::>>::new(); + for peripheral_wrapper in raw_peripheral_list.iter_mut() { + peripherals.push(Peripheral::new(peripheral_wrapper)); + } + + return Ok(peripherals); + } + + pub fn get_paired_peripherals(&self) -> Result>>, Error> { + let mut raw_peripheral_list = + self.internal.get_paired_peripherals().map_err(|e| Error { + msg: e.what().to_string(), + })?; + + let mut peripherals = Vec::>>::new(); + for peripheral_wrapper in raw_peripheral_list.iter_mut() { + peripherals.push(Peripheral::new(peripheral_wrapper)); + } + + return Ok(peripherals); + } + + pub fn set_callback_on_scan_start(&mut self, cb: Box) { + self.on_scan_start = cb; + } + + pub fn set_callback_on_scan_stop(&mut self, cb: Box) { + self.on_scan_stop = cb; + } + + pub fn set_callback_on_scan_updated( + &mut self, + cb: Box>) + Send + Sync + 'static>, + ) { + self.on_scan_updated = cb; + } + + pub fn set_callback_on_scan_found( + &mut self, + cb: Box>) + Send + Sync + 'static>, + ) { + self.on_scan_found = cb; + } + + fn on_callback_scan_start(&self) { + (self.on_scan_start)(); + } + + fn on_callback_scan_stop(&self) { + (self.on_scan_stop)(); + } + + fn on_callback_scan_updated(&self, peripheral: &mut ffi::RustyPeripheralWrapper) { + (self.on_scan_updated)(Peripheral::new(peripheral)); + } + + fn on_callback_scan_found(&self, peripheral: &mut ffi::RustyPeripheralWrapper) { + (self.on_scan_found)(Peripheral::new(peripheral)); + } +} + +impl Peripheral { + fn new(wrapper: &mut ffi::RustyPeripheralWrapper) -> Pin> { + let this = Self { + internal: cxx::UniquePtr::::null(), + on_connected: Box::new(|| {}), + on_disconnected: Box::new(|| {}), + on_characteristic_update_map: HashMap::new(), + }; + + // Pin the object to guarantee that its location in memory is + // fixed throughout the lifetime of the application + let mut this_boxed = Box::pin(this); + + // Link `this` to the RustyPeripheral + wrapper.internal.link(this_boxed.as_mut()).unwrap(); + + // Copy the RustyPeripheral pointer into `this` + mem::swap(&mut this_boxed.internal, &mut wrapper.internal); + + return this_boxed; + } + + pub fn identifier(&self) -> Result { + self.internal.identifier().map_err(|e| Error { + msg: e.what().to_string(), + }) + } + + pub fn address(&self) -> Result { + self.internal.address().map_err(|e| Error { + msg: e.what().to_string(), + }) + } + + pub fn address_type(&self) -> Result { + let address_type = self.internal.address_type().map_err(|e| Error { + msg: e.what().to_string(), + })?; + + return match address_type { + ffi::BluetoothAddressType::PUBLIC => Ok(BluetoothAddressType::Public), + ffi::BluetoothAddressType::RANDOM => Ok(BluetoothAddressType::Random), + ffi::BluetoothAddressType::UNSPECIFIED => Ok(BluetoothAddressType::Unspecified), + _ => Ok(BluetoothAddressType::Unspecified), + }; + } + + pub fn rssi(&self) -> Result { + self.internal.rssi().map_err(|e| Error { + msg: e.what().to_string(), + }) + } + + pub fn tx_power(&self) -> Result { + self.internal.tx_power().map_err(|e| Error { + msg: e.what().to_string(), + }) + } + + pub fn mtu(&self) -> Result { + self.internal.mtu().map_err(|e| Error { + msg: e.what().to_string(), + }) + } + + pub fn connect(&self) -> Result<(), Error> { + self.internal.connect().map_err(|e| Error { + msg: e.what().to_string(), + }) + } + + pub fn disconnect(&self) -> Result<(), Error> { + self.internal.disconnect().map_err(|e| Error { + msg: e.what().to_string(), + }) + } + + pub fn is_connected(&self) -> Result { + self.internal.is_connected().map_err(|e| Error { + msg: e.what().to_string(), + }) + } + + pub fn is_connectable(&self) -> Result { + self.internal.is_connectable().map_err(|e| Error { + msg: e.what().to_string(), + }) + } + + pub fn is_paired(&self) -> Result { + self.internal.is_paired().map_err(|e| Error { + msg: e.what().to_string(), + }) + } + + pub fn unpair(&self) -> Result<(), Error> { + self.internal.unpair().map_err(|e| Error { + msg: e.what().to_string(), + }) + } + + pub fn services(&self) -> Result>>, Error> { + let mut raw_services = self.internal.services().map_err(|e| Error { + msg: e.what().to_string(), + })?; + + let mut services = Vec::>>::new(); + for service_wrapper in raw_services.iter_mut() { + services.push(Service::new(service_wrapper)); + } + + Ok(services) + } + + pub fn manufacturer_data(&self) -> Result>, Error> { + let raw_manufacturer_data = self.internal.manufacturer_data().map_err(|e| Error { + msg: e.what().to_string(), + })?; + + let mut manufacturer_data = HashMap::>::new(); + for raw_manuf_data in raw_manufacturer_data.iter() { + manufacturer_data.insert(raw_manuf_data.company_id, raw_manuf_data.data.clone()); + } + + Ok(manufacturer_data) + } + + pub fn read(&self, service: &String, characteristic: &String) -> Result, Error> { + self.internal + .read(service, characteristic) + .map_err(|e| Error { + msg: e.what().to_string(), + }) + } + + pub fn write_request( + &self, + service: &String, + characteristic: &String, + data: &Vec, + ) -> Result<(), Error> { + self.internal + .write_request(service, characteristic, data) + .map_err(|e| Error { + msg: e.what().to_string(), + }) + } + + pub fn write_command( + &self, + service: &String, + characteristic: &String, + data: &Vec, + ) -> Result<(), Error> { + self.internal + .write_command(service, characteristic, data) + .map_err(|e| Error { + msg: e.what().to_string(), + }) + } + + pub fn notify( + &mut self, + service: &String, + characteristic: &String, + cb: Box) + Send + Sync + 'static>, + ) -> Result<(), Error> { + // Make a string joining the service and characteristic, then save it in the map + let key = format!("{}{}", service, characteristic); + self.on_characteristic_update_map.insert(key, cb); + + self.internal + .notify(service, characteristic) + .map_err(|e| Error { + msg: e.what().to_string(), + }) + } + + pub fn indicate( + &mut self, + service: &String, + characteristic: &String, + cb: Box) + Send + Sync + 'static>, + ) -> Result<(), Error> { + // Make a string joining the service and characteristic, then save it in the map + let key = format!("{}{}", service, characteristic); + self.on_characteristic_update_map.insert(key, cb); + + self.internal + .indicate(service, characteristic) + .map_err(|e| Error { + msg: e.what().to_string(), + }) + } + + pub fn unsubscribe(&mut self, service: &String, characteristic: &String) -> Result<(), Error> { + // Make a string joining the service and characteristic, then remove it from the map + let key = format!("{}{}", service, characteristic); + self.on_characteristic_update_map.remove(&key); + + self.internal + .unsubscribe(service, characteristic) + .map_err(|e| Error { + msg: e.what().to_string(), + }) + } + + pub fn descriptor_read( + &self, + service: &String, + characteristic: &String, + descriptor: &String, + ) -> Result, Error> { + self.internal + .read_descriptor(service, characteristic, descriptor) + .map_err(|e| Error { + msg: e.what().to_string(), + }) + } + + pub fn descriptor_write( + &self, + service: &String, + characteristic: &String, + descriptor: &String, + data: &Vec, + ) -> Result<(), Error> { + self.internal + .write_descriptor(service, characteristic, descriptor, data) + .map_err(|e| Error { + msg: e.what().to_string(), + }) + } + + pub fn set_callback_on_connected(&mut self, cb: Box) { + self.on_connected = cb; + } + + pub fn set_callback_on_disconnected(&mut self, cb: Box) { + self.on_disconnected = cb; + } + + fn on_callback_connected(&self) { + (self.on_connected)(); + } + + fn on_callback_disconnected(&self) { + (self.on_disconnected)(); + } + + fn on_callback_characteristic_updated( + &self, + service: &String, + characteristic: &String, + data: &Vec, + ) { + // Make a string joining the service and characteristic, then look up the callback and call it. + let key = format!("{}{}", service, characteristic); + + if let Some(cb) = self.on_characteristic_update_map.get(&key) { + (cb)(data.clone()); + } + } +} + +impl Service { + fn new(wrapper: &mut ffi::RustyServiceWrapper) -> Pin> { + let this = Self { + internal: cxx::UniquePtr::::null(), + }; + + // Pin the object to guarantee that its location in memory is + // fixed throughout the lifetime of the application + let mut this_boxed = Box::pin(this); + + // Copy the RustyService pointer into `this` + mem::swap(&mut this_boxed.internal, &mut wrapper.internal); + + return this_boxed; + } + + pub fn uuid(&self) -> String { + return self.internal.uuid(); + } + + pub fn data(&self) -> Vec { + return self.internal.data(); + } + + pub fn characteristics(&self) -> Vec>> { + let mut characteristics = Vec::>>::new(); + + for characteristic_wrapper in self.internal.characteristics().iter_mut() { + characteristics.push(Characteristic::new(characteristic_wrapper)); + } + + return characteristics; + } +} + +impl Characteristic { + fn new(wrapper: &mut ffi::RustyCharacteristicWrapper) -> Pin> { + let this = Self { + internal: cxx::UniquePtr::::null(), + }; + + // Pin the object to guarantee that its location in memory is + // fixed throughout the lifetime of the application + let mut this_boxed = Box::pin(this); + + // Copy the RustyCharacteristic pointer into `this` + mem::swap(&mut this_boxed.internal, &mut wrapper.internal); + + return this_boxed; + } + + pub fn uuid(&self) -> String { + return self.internal.uuid(); + } + + pub fn descriptors(&self) -> Vec>> { + let mut descriptors = Vec::>>::new(); + + for descriptor_wrapper in self.internal.descriptors().iter_mut() { + descriptors.push(Descriptor::new(descriptor_wrapper)); + } + + return descriptors; + } + + pub fn capabilities(&self) -> Vec { + let mut capabilities = Vec::::new(); + + if self.internal.can_read() { + capabilities.push(CharacteristicCapability::Read); + } + + if self.internal.can_write_request() { + capabilities.push(CharacteristicCapability::WriteRequest); + } + + if self.internal.can_write_command() { + capabilities.push(CharacteristicCapability::WriteCommand); + } + + if self.internal.can_notify() { + capabilities.push(CharacteristicCapability::Notify); + } + + if self.internal.can_indicate() { + capabilities.push(CharacteristicCapability::Indicate); + } + + return capabilities; + } + + pub fn can_read(&self) -> bool { + return self.internal.can_read(); + } + + pub fn can_write_request(&self) -> bool { + return self.internal.can_write_request(); + } + + pub fn can_write_command(&self) -> bool { + return self.internal.can_write_command(); + } + + pub fn can_notify(&self) -> bool { + return self.internal.can_notify(); + } + + pub fn can_indicate(&self) -> bool { + return self.internal.can_indicate(); + } +} + +impl Descriptor { + fn new(wrapper: &mut ffi::RustyDescriptorWrapper) -> Pin> { + let this = Self { + internal: cxx::UniquePtr::::null(), + }; + + // Pin the object to guarantee that its location in memory is + // fixed throughout the lifetime of the application + let mut this_boxed = Box::pin(this); + + // Copy the RustyDescriptor pointer into `this` + mem::swap(&mut this_boxed.internal, &mut wrapper.internal); + + return this_boxed; + } + + pub fn uuid(&self) -> String { + return self.internal.uuid(); + } +} + +unsafe impl Sync for Adapter {} + +unsafe impl Sync for Peripheral {} + +unsafe impl Sync for Service {} + +unsafe impl Sync for Characteristic {} + +unsafe impl Sync for Descriptor {} + +unsafe impl Send for Adapter {} + +unsafe impl Send for Peripheral {} + +unsafe impl Send for Service {} + +unsafe impl Send for Characteristic {} + +unsafe impl Send for Descriptor {} + +impl std::error::Error for Error {} + +impl fmt::Display for BluetoothAddressType { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + BluetoothAddressType::Public => write!(f, "Public"), + BluetoothAddressType::Random => write!(f, "Random"), + BluetoothAddressType::Unspecified => write!(f, "Unspecified"), + } + } +} + +impl fmt::Display for CharacteristicCapability { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + CharacteristicCapability::Read => write!(f, "Read"), + CharacteristicCapability::WriteRequest => write!(f, "WriteRequest"), + CharacteristicCapability::WriteCommand => write!(f, "WriteCommand"), + CharacteristicCapability::Notify => write!(f, "Notify"), + CharacteristicCapability::Indicate => write!(f, "Indicate"), + } + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "SimpleBLE error: {}", self.msg) + } +} + +impl Drop for Adapter { + fn drop(&mut self) { + self.internal.unlink().unwrap(); + } +} + +impl Drop for Peripheral { + fn drop(&mut self) { + self.internal.unlink().unwrap(); + } +} diff --git a/third_party/SimpleBLE/utils/build_android.sh b/third_party/SimpleBLE/utils/build_android.sh new file mode 100644 index 000000000..f2f07c6c3 --- /dev/null +++ b/third_party/SimpleBLE/utils/build_android.sh @@ -0,0 +1,104 @@ +#!/usr/bin/env bash + +# Some portions of this file where inspired from: +# https://medium.com/@Drew_Stokes/bash-argument-parsing-54f3b81a6a8f + +# If the current script is running in MacOS, print a warning +if [[ "$OSTYPE" == "darwin"* ]]; then + + # Define the realpath function, as MacOs doesn't have it + realpath() { + OURPWD=$PWD + cd "$(dirname "$1")" + LINK=$(readlink "$(basename "$1")") + while [ "$LINK" ]; do + cd "$(dirname "$LINK")" + LINK=$(readlink "$(basename "$1")") + done + REALPATH="$PWD/$(basename "$1")" + cd "$OURPWD" + echo "$REALPATH" + } +fi + +# Parse incoming arguments +PARAMS="" +while (( "$#" )); do + case "$1" in + -c|--clean) + FLAG_CLEAN=0 + shift + ;; + -e|--examples) + FLAG_EXAMPLE=0 + shift + ;; + -d|--deploy) + FLAG_DEPLOY=0 + shift + ;; + -r|--run) + FLAG_RUN=$2 + shift + shift + ;; + -*|--*=) # unsupported flags + echo "Error: Unsupported flag $1" >&2 + exit 1 + ;; + *) # preserve positional arguments + PARAMS="$PARAMS $1" + shift + ;; + esac +done + +# Set positional arguments in their proper place +eval set -- "$PARAMS" + +# Base path definitions +PROJECT_ROOT=$(realpath $(dirname `realpath $0`)/..) +SOURCE_PATH=$PROJECT_ROOT/simpleble +BUILD_PATH=$PROJECT_ROOT/build_simpleble_android +INSTALL_PATH=$BUILD_PATH/install + +EXAMPLE_BUILD_PATH=$PROJECT_ROOT/build_simpleble_android_examples +EXAMPLE_SOURCE_PATH=$PROJECT_ROOT/examples/simpleble + +# If FLAG_CLEAN is set, clean the build directory +if [[ ! -z "$FLAG_CLEAN" ]]; then + rm -rf $BUILD_PATH + rm -rf $EXAMPLE_BUILD_PATH +fi + +# Check if the ANDROID_NDK_HOME environment variable is set +if [ -z "$ANDROID_NDK_HOME" ]; then + echo "The ANDROID_NDK_HOME environment variable is not set. Please set it to the path of your Android NDK installation." + exit 1 +fi + +# These are some hardcoded variables used for my test process. You can change them to fit your needs. +ANDROID_ARCH_ABI="armeabi-v7a" +ANDROID_API=21 +# NOTE: Also look at ANDROID_STL_TYPE +ANDROID_ARGS="-DCMAKE_SYSTEM_NAME=Android -DCMAKE_ANDROID_NDK=$ANDROID_NDK_HOME -DCMAKE_ANDROID_ARCH_ABI=$ANDROID_ARCH_ABI -DCMAKE_ANDROID_API=$ANDROID_API" + +cmake -H$SOURCE_PATH -B $BUILD_PATH $ANDROID_ARGS +cmake --build $BUILD_PATH -j7 +cmake --install $BUILD_PATH --prefix "${INSTALL_PATH}" + +if [[ ! -z "$FLAG_EXAMPLE" ]]; then + cmake -H$EXAMPLE_SOURCE_PATH -B $EXAMPLE_BUILD_PATH $ANDROID_ARGS + cmake --build $EXAMPLE_BUILD_PATH -j7 + + if [[ ! -z "$FLAG_DEPLOY" ]]; then + adb shell rm -rf /data/local/tmp/simpleble + adb shell mkdir /data/local/tmp/simpleble + adb push $EXAMPLE_BUILD_PATH/bin/* /data/local/tmp/simpleble + adb shell chmod +x /data/local/tmp/simpleble/* + fi + + if [[ ! -z "$FLAG_RUN" ]]; then + adb shell /data/local/tmp/simpleble/$FLAG_RUN + fi +fi \ No newline at end of file diff --git a/third_party/SimpleBLE/utils/build_docs.sh b/third_party/SimpleBLE/utils/build_docs.sh new file mode 100644 index 000000000..bb2cdc823 --- /dev/null +++ b/third_party/SimpleBLE/utils/build_docs.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash + +# pip3 install sphinx-autobuild +# sphinx-autobuild docs build_docs/html \ No newline at end of file diff --git a/third_party/SimpleBLE/utils/build_lib.sh b/third_party/SimpleBLE/utils/build_lib.sh index ade1c1c3a..b46450edb 100644 --- a/third_party/SimpleBLE/utils/build_lib.sh +++ b/third_party/SimpleBLE/utils/build_lib.sh @@ -30,6 +30,10 @@ while (( "$#" )); do FLAG_CLEAN=0 shift ;; + -d|--debug) + FLAG_DEBUG=0 + shift + ;; -s|--shared) FLAG_SHARED=0 shift @@ -126,7 +130,11 @@ if [[ ! -z "$FLAG_CLEAN" ]]; then rm -rf $EXAMPLE_BUILD_PATH fi -cmake -H$SOURCE_PATH -B $BUILD_PATH $BUILD_TEST_ARG $BUILD_SANITIZE_ADDRESS_ARG $BUILD_SANITIZE_THREAD_ARG $BUILD_SHARED_ARG $BUILD_PLAIN $EXTRA_BUILD_ARGS +if [[ ! -z "$FLAG_DEBUG" ]]; then + DEBUG_ARG="-DCMAKE_BUILD_TYPE=Debug" +fi + +cmake $DEBUG_ARG -H$SOURCE_PATH -B $BUILD_PATH $BUILD_TEST_ARG $BUILD_SANITIZE_ADDRESS_ARG $BUILD_SANITIZE_THREAD_ARG $BUILD_SHARED_ARG $BUILD_PLAIN $EXTRA_BUILD_ARGS cmake --build $BUILD_PATH -j7 cmake --install $BUILD_PATH --prefix "${INSTALL_PATH}" @@ -138,6 +146,6 @@ else fi if [[ ! -z "$FLAG_EXAMPLE" ]]; then - cmake -H$EXAMPLE_SOURCE_PATH -B $EXAMPLE_BUILD_PATH $BUILD_EXAMPLE_ARGS $BUILD_SHARED_ARG + cmake $DEBUG_ARG -H$EXAMPLE_SOURCE_PATH -B $EXAMPLE_BUILD_PATH $BUILD_EXAMPLE_ARGS $BUILD_SHARED_ARG cmake --build $EXAMPLE_BUILD_PATH -j7 fi diff --git a/third_party/SimpleBLE/utils/clean_workflows.py b/third_party/SimpleBLE/utils/clean_workflows.py new file mode 100644 index 000000000..93789ca28 --- /dev/null +++ b/third_party/SimpleBLE/utils/clean_workflows.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python3 +import argparse +import json +import os +import urllib.parse +import urllib.request + +API_BASE_URL = "https://api.github.com" +REQUEST_ACCEPT_VERSION = "application/vnd.github.v3+json" +REQUEST_USER_AGENT = "magnetikonline/remove-workflow-run" + + +def github_request( + auth_token, path, method=None, parameter_collection=None, parse_response=True +): + # build base request URL/headers + request_url = f"{API_BASE_URL}/{path}" + header_collection = { + "Accept": REQUEST_ACCEPT_VERSION, + "Authorization": f"token {auth_token}", + "User-Agent": REQUEST_USER_AGENT, + } + + if method is None: + # GET method + if parameter_collection is not None: + request_url = ( + f"{request_url}?{urllib.parse.urlencode(parameter_collection)}" + ) + + request = urllib.request.Request(headers=header_collection, url=request_url) + else: + # POST/PATCH/PUT/DELETE method + request = urllib.request.Request( + headers=header_collection, method=method, url=request_url + ) + + response = urllib.request.urlopen(request) + response_data = {} + if parse_response: + response_data = json.load(response) + + response.close() + + return response_data + + +def workflow_run_list(auth_token, owner_repo_name, workflow_id): + request_page = 1 + while True: + data = github_request( + auth_token, + f"repos/{owner_repo_name}/actions/workflows/{urllib.parse.quote(workflow_id)}/runs", + parameter_collection={"page": request_page}, + ) + + run_list = data["workflow_runs"] + if len(run_list) < 1: + # no more items + break + + for item in run_list: + print(f"Found run ID: {item['id']}") + yield item["id"] + + # move to next page + request_page += 1 + + +def workflow_run_delete(auth_token, owner_repo_name, run_id): + github_request( + auth_token, + f"repos/{owner_repo_name}/actions/runs/{run_id}", + method="DELETE", + parse_response=False, + ) + + +def main(): + # fetch GitHub access token + auth_token = os.environ["AUTH_TOKEN"] + + # fetch requested repository and workflow ID to remove prior runs from + parser = argparse.ArgumentParser() + parser.add_argument("--repository-name", required=True) + parser.add_argument("--workflow-id", required=True) + arg_list = parser.parse_args() + + # fetch run id list from repository workflow + run_id_list = list( + workflow_run_list(auth_token, arg_list.repository_name, arg_list.workflow_id) + ) + + for run_id in run_id_list: + print(f"Deleting run ID: {run_id}") + workflow_run_delete(auth_token, arg_list.repository_name, run_id) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/third_party/SimpleBLE/utils/format.sh b/third_party/SimpleBLE/utils/format.sh new file mode 100644 index 000000000..4a8c3ebc5 --- /dev/null +++ b/third_party/SimpleBLE/utils/format.sh @@ -0,0 +1,75 @@ +#!/usr/bin/env bash + +# Script to run clang-format locally and print differences using colordiff +# only for files that have changes. +# +# Dry run: +# >./format.sh +# +# Apply changes: +# >./format.sh apply + + +CLANG_FORMAT="clang-format" + +# Check if colordiff is installed +if ! command -v colordiff &> /dev/null; then + echo "colordiff is required but not installed. Please install it and run the script again." + exit 1 +fi + + +APPLY=false +# Check if the 'apply' argument is provided +if [ -n "$1" ]; then + if [ "$1" == "apply" ]; then + APPLY=true + else + # If the first argument is not 'apply', print usage and exit + echo "Invalid argument. Usage:" + echo "format.sh apply" + exit 1 + fi +fi + + +if [ "$1" == "apply" ]; then + APPLY=true +fi + +# Run clang-format and print differences only for files that have changes +echo "Running clang-format..." + +# Excluded paths +EXCLUDED_PATHS=( + "./simplepyble/*" + "*CMakeFiles*" + "*_deps*" + "*build*" + "*external*" +) + +FIND_CMD="find . -type f \( -name \"*.h\" -o -name \"*.hpp\" -o -name \"*.cpp\" -o -name \"*.c\" \)" +for path in "${EXCLUDED_PATHS[@]}"; do + FIND_CMD+=" ! -path \"$path\"" +done + +# Find all relevant source files, excluding specified paths, and process each file +eval "$FIND_CMD" | while read -r file; do + + # Get the differences between the original file and the formatted file + diff_output=$($CLANG_FORMAT "$file" | diff -u "$file" - | colordiff) + + # If differences are found, print the file name and the differences + if [ -n "$diff_output" ]; then + if [ "$APPLY" == true ]; then + $CLANG_FORMAT -i "$file" + echo "Applied changes to $file" + else + echo "Differences found in $file:" + echo "$diff_output" + fi + fi +done + +echo "Format completed."