Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for external bluetooth devices #535

Open
wants to merge 17 commits into
base: master
Choose a base branch
from
Open
63 changes: 63 additions & 0 deletions third_party/open-bp-cpp/.gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
###############################################################################
# Set default behavior to automatically normalize line endings.
###############################################################################
* text=auto

###############################################################################
# Set default behavior for command prompt diff.
#
# This is need for earlier builds of msysgit that does not have it on by
# default for csharp files.
# Note: This is only used by command line
###############################################################################
#*.cs diff=csharp

###############################################################################
# Set the merge driver for project and solution files
#
# Merging from the command prompt will add diff markers to the files if there
# are conflicts (Merging from VS is not affected by the settings below, in VS
# the diff markers are never inserted). Diff markers may cause the following
# file extensions to fail to load in VS. An alternative would be to treat
# these files as binary and thus will always conflict and require user
# intervention with every merge. To do so, just uncomment the entries below
###############################################################################
#*.sln merge=binary
#*.csproj merge=binary
#*.vbproj merge=binary
#*.vcxproj merge=binary
#*.vcproj merge=binary
#*.dbproj merge=binary
#*.fsproj merge=binary
#*.lsproj merge=binary
#*.wixproj merge=binary
#*.modelproj merge=binary
#*.sqlproj merge=binary
#*.wwaproj merge=binary

###############################################################################
# behavior for image files
#
# image files are treated as binary by default.
###############################################################################
#*.jpg binary
#*.png binary
#*.gif binary

###############################################################################
# diff behavior for common document formats
#
# Convert binary document formats to text before diffing them. This feature
# is only available from the command line. Turn it on by uncommenting the
# entries below.
###############################################################################
#*.doc diff=astextplain
#*.DOC diff=astextplain
#*.docx diff=astextplain
#*.DOCX diff=astextplain
#*.dot diff=astextplain
#*.DOT diff=astextplain
#*.pdf diff=astextplain
#*.PDF diff=astextplain
#*.rtf diff=astextplain
#*.RTF diff=astextplain
40 changes: 40 additions & 0 deletions third_party/open-bp-cpp/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# Prerequisites
*.d

# Compiled Object files
*.slo
*.lo
*.o
*.obj

# Precompiled Headers
*.gch
*.pch

# Compiled Dynamic libraries
*.so
*.dylib
*.dll

# Fortran module files
*.mod
*.smod

# Compiled Static libraries
*.lai
*.la
*.a
*.lib

# Executables
*.exe
*.out
*.app
/.vs
/out/build/x64-debug
/CMakeFiles
/_3rdParty
/CMakeCache.txt
/cmake_install.cmake
/Makefile
/buttplugCpp
33 changes: 33 additions & 0 deletions third_party/open-bp-cpp/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# CMakeList.txt : CMake project for buttplugCpp, include source and define
# project specific logic here.
#
cmake_minimum_required (VERSION 3.8)

# Enable Hot Reload for MSVC compilers if supported.
if (POLICY CMP0141)
cmake_policy(SET CMP0141 NEW)
set(CMAKE_MSVC_DEBUG_INFORMATION_FORMAT "$<IF:$<AND:$<C_COMPILER_ID:MSVC>,$<CXX_COMPILER_ID:MSVC>>,$<$<CONFIG:Debug,RelWithDebInfo>:EditAndContinue>,$<$<CONFIG:Debug,RelWithDebInfo>:ProgramDatabase>>")
endif()

project(buttplugCpp)

# Add source to this project's executable.

file(GLOB SRC_FILES
"src/*.cpp"
"include/*.h"
"include/*.hpp"
)

add_library(buttplugCpp STATIC ${SRC_FILES})

set(USE_ZLIB FALSE)
add_subdirectory(third_party/IXWebSocket)

find_package(Threads REQUIRED)
target_link_libraries(buttplugCpp PUBLIC ixwebsocket::ixwebsocket Threads::Threads)

if (CMAKE_VERSION VERSION_GREATER 3.12)
set_property(TARGET buttplugCpp PROPERTY CXX_STANDARD 11)
endif()
# TODO: Add tests and install targets if needed.
61 changes: 61 additions & 0 deletions third_party/open-bp-cpp/CMakePresets.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
{
"version": 3,
"configurePresets": [
{
"name": "windows-base",
"hidden": true,
"generator": "Ninja",
"binaryDir": "${sourceDir}/out/build/${presetName}",
"installDir": "${sourceDir}/out/install/${presetName}",
"cacheVariables": {
"CMAKE_C_COMPILER": "cl.exe",
"CMAKE_CXX_COMPILER": "cl.exe"
},
"condition": {
"type": "equals",
"lhs": "${hostSystemName}",
"rhs": "Windows"
}
},
{
"name": "x64-debug",
"displayName": "x64 Debug",
"inherits": "windows-base",
"architecture": {
"value": "x64",
"strategy": "external"
},
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Debug"
}
},
{
"name": "x64-release",
"displayName": "x64 Release",
"inherits": "x64-debug",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Release"
}
},
{
"name": "x86-debug",
"displayName": "x86 Debug",
"inherits": "windows-base",
"architecture": {
"value": "x86",
"strategy": "external"
},
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Debug"
}
},
{
"name": "x86-release",
"displayName": "x86 Release",
"inherits": "x86-debug",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Release"
}
}
]
}
17 changes: 17 additions & 0 deletions third_party/open-bp-cpp/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# buttplugCpp
## How to use
I made this project in Visual Studio 2022, but it uses CMake. I currently am struggling to get a proper library CMake going, so simply include the src and include directories in your project and add them with:
```
file(GLOB SRC_FILES
"src/*.cpp"
"include/*.h"
)

target_sources(buttplugCpp PUBLIC
${SRC_FILES}
)
```
in your CMake file. Also make sure to build IXWebSockets (without zlib, unless you want to deal with getting it working with CMake). Nlohmann Json dependency is handled by Hunter, so make sure you have Hunter in your project too. I provide an example CMake file which makes the example program in example directory.

## More info
Currently this library was tested (not very extensively) with Linux and Windows. The C++ version is C++11. This library and its documentation is still WIP.
42 changes: 42 additions & 0 deletions third_party/open-bp-cpp/example/buttplugCpp.cpp
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I got 100x improvement from this commit.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how did you bench btw

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Omfg... We're making history here 😭

Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// buttplugCpp.cpp : Defines the entry point for the application.
//

#include "buttplugCpp.h"
#include <cstdio>

void callbackFunction(const mhl::Messages msg) {
switch (msg.messageType) {
case mhl::MessageTypes::DeviceList: std::printf("Device List callback\n"); break;
case mhl::MessageTypes::DeviceAdded: std::printf("Device List callback\n"); break;
case mhl::MessageTypes::ServerInfo: std::printf("Server info callback\n"); break;
case mhl::MessageTypes::DeviceRemoved: std::printf("Device Removed callback\n"); break;
case mhl::MessageTypes::SensorReading: std::printf("Sensor reading callback\n"); break;
default: printf("Unknown message")
}
}

int main()
{
std::string url = "ws://127.0.0.1";
std::cout << "\n";
Client client(url, 12345, "test.txt");
client.connect(callbackFunction);
client.requestDeviceList();
client.startScan();
while (1) {
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
client.stopScan();
break;
}
//std::vector<DeviceClass> myDevices = client.getDevices();
//client.sendScalar(myDevices[0], 0.5);
//client.sendScalar(myDevices[1], 0.5);
//client.sensorSubscribe(myDevices[0], 0);
//std::this_thread::sleep_for(std::chrono::milliseconds(20000));
//client.sensorUnsubscribe(myDevices[0], 0);
//client.stopAllDevices();
std::this_thread::sleep_for(std::chrono::milliseconds(2000));

return 0;
}

9 changes: 9 additions & 0 deletions third_party/open-bp-cpp/example/buttplugCpp.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// buttplugCpp.h : Include file for standard system include files,
// or project specific include files.

#pragma once

#include <iostream>
#include "../include/buttplugclient.h"

// TODO: Reference additional headers your program requires here.
110 changes: 110 additions & 0 deletions third_party/open-bp-cpp/include/buttplugclient.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
#include <string>
#include <functional>
#include <iostream>
#include <atomic>
#include <sstream>
#include <queue>

#include <IXWebSocket.h>
#ifdef _WIN32
#include <IXNetSystem.h>
#endif
#include "messageHandler.h"
#include "log.h"

typedef msg::SensorReading SensorClass;

// Helper class to store devices and access them outside of the library.
class DeviceClass {
public:
std::string deviceName;
std::string displayName;
std::vector<std::string> commandTypes;
std::vector<std::string> sensorTypes;
unsigned int deviceID;
};

// Main client class
class Client {
public:
// Constructor which initialized websockets for Windows. Add an IFDEF depending on compilation OS for portability.
Client(std::string url, unsigned int port) {
#ifdef _WIN32
ix::initNetSystem();
#endif
lUrl = url;
lPort = port;
}
Client(std::string url, unsigned int port, std::string logfile) {
#ifdef _WIN32
ix::initNetSystem();
#endif
lUrl = url;
lPort = port;
logging = 1;
if (!logfile.empty()) logInfo.init(logfile);
else logInfo.init("log.txt");
}
~Client() {
#ifdef _WIN32
ix::uninitNetSystem();
#endif
}

int connect(void (*callFunc)(const mhl::Messages));
// Atomic variables to store connection status. Can be accessed outside library too since atomic.
std::atomic<int> wsConnected{0};
std::atomic<int> isConnecting{0};
std::atomic<int> clientConnected{0};
// Condition variables for the atomics, we want C++11 support
std::condition_variable condClient;
std::condition_variable condWs;

// Public functions that send requests to server.
void startScan();
void stopScan();
void requestDeviceList();
void stopDevice(DeviceClass dev);
void stopAllDevices();
void sendScalar(DeviceClass dev, double str);
void sensorRead(DeviceClass dev, int senIndex);
void sensorSubscribe(DeviceClass dev, int senIndex);
void sensorUnsubscribe(DeviceClass dev, int senIndex);

// Mutex blocked function which grabs the currently connected devices and sensor reads.
std::vector<DeviceClass> getDevices();
SensorClass getSensors();
private:
// URL variables for the websocket.
std::string FullUrl;
std::string lUrl;
unsigned int lPort;

int logging = 0;
Logger logInfo;

ix::WebSocket webSocket;

// Message handler class, which takes messages, parses them and makes them to classes.
mhl::Messages messageHandler;

// Queue variable for passing received messages from server.
std::queue<std::string> q;
// Condition variabel to wait for received messages in the queue.
std::condition_variable cond;
// Mutex to ensure no race conditions.
std::mutex msgMx;
// Callback function for when a message is received and handled.
std::function<void(const mhl::Messages&)> messageCallback;

// Device and sensor class vector which is grabbed outside of the library.
std::vector<DeviceClass> devices;
SensorClass sensorData;

void connectServer();
void callbackFunction(const ix::WebSocketMessagePtr& msg);
void messageHandling();
void sendMessage(json msg, mhl::MessageTypes mType);
void updateDevices();
int findDevice(DeviceClass dev);
};
Loading