diff --git a/README.md b/README.md index 314bf06..594292d 100644 --- a/README.md +++ b/README.md @@ -2,10 +2,22 @@ This repository is a sample on how to connect from a Windows 10 PC to an ESP32 via bluetooth and windows sockets. You should pair your PC with the ESP32 first. The console application will loop through the BT devices connected to the PC and find the ESP32, connect to it, send a message, and recieve a message. The Arduino.ino file should be loaded onto the ESP32. The Visual Studio project should be built (I used Visual Studio 2019). The actual source code is just contained in the .ino file and single .cpp file. The code should be simple to follow, unlike most of the examples and documentation I came across. +# Steps to build: +- Download the zip with the code (or clone it with git). +- Download [Visual Studio Community] (https://visualstudio.microsoft.com/downloads/) (tested with 2019). +- During that installation, you only need the Desktop development with C++. +- Download the [Arduino IDE](https://www.arduino.cc/en/software). +- Open the Arduino.ino file, and click Upload with your ESP32 plugged in. (Make sure you installed [ESP32 libraries first](https://randomnerdtutorials.com/installing-the-esp32-board-in-arduino-ide-windows-instructions/). +- Open the Bluetooth menu on your PC (you should have a dongle or Bluetooth integrated). Connect to Esp32Test. + +- Open the .sln file in WindowsBTWithEsp32 with Visual Studio Community. +- Click play (Local Windows Debugger). +- You should now receive messages via bluetooth in the terminal that opened: "Message from ESP32". + ## References * Helpful examples on getting connected devices - https://www.winsocketdotnetworkprogramming.com/winsock2programming/winsock2advancedotherprotocol4k.html * Bluetooth APIs - https://docs.microsoft.com/en-us/windows/win32/api/bluetoothapis/ * Microsoft example - https://github.com/microsoftarchive/msdn-code-gallery-microsoft/blob/master/Official%20Windows%20Platform%20Sample/Bluetooth%20connection%20sample/%5BC%2B%2B%5D-Bluetooth%20connection%20sample/C%2B%2B/bthcxn.cpp -* Bluetooth programming with Windows sockets - https://docs.microsoft.com/en-us/windows/win32/bluetooth/bluetooth-programming-with-windows-sockets \ No newline at end of file +* Bluetooth programming with Windows sockets - https://docs.microsoft.com/en-us/windows/win32/bluetooth/bluetooth-programming-with-windows-sockets diff --git a/WindowsBtWithEsp32/WindowsBtWithEsp32/WindowsBtWithEsp32.cpp b/WindowsBtWithEsp32/WindowsBtWithEsp32/WindowsBtWithEsp32.cpp index d4b8317..6b607e1 100644 --- a/WindowsBtWithEsp32/WindowsBtWithEsp32/WindowsBtWithEsp32.cpp +++ b/WindowsBtWithEsp32/WindowsBtWithEsp32/WindowsBtWithEsp32.cpp @@ -6,12 +6,18 @@ Microsoft example - https://github.com/microsoftarchive/msdn-code-gallery-micros Bluetooth programming with Windows sockets - https://docs.microsoft.com/en-us/windows/win32/bluetooth/bluetooth-programming-with-windows-sockets **/ +#pragma comment(lib, "Bthprops.lib") +#pragma comment(lib, "Ws2_32.lib") #include #include #include #include #include +#include +#include +#include +#include BTH_ADDR esp32BtAddress; SOCKADDR_BTH btSocketAddress; @@ -107,9 +113,8 @@ bool connectToEsp32() return true; } -bool sendMessageToEsp32() +bool sendMessageToEsp32(const char* message) { - const char* message = "Message from Windows\r\n"; int sendResult = send(btClientSocket, message, (int)strlen(message), 0); //send your message to the BT device if (sendResult == SOCKET_ERROR) { @@ -121,27 +126,96 @@ bool sendMessageToEsp32() return true; } -bool recieveMessageFromEsp32() +bool sendMessageToEsp32(std::string message) { - printf("Waiting to recieve a message\r\n"); - while (true) + const char* msg = message.c_str(); + return sendMessageToEsp32(msg); + +} + + +//receive a message and send a message back. +//to not send a message back use send_reply="-". (This will block the esp32 if it expects a message if you don't send anywhere else!) +//always terminate the reply with \n. \n will send the minimum info to not block the esp32. +std::string recieveStringMessageFromEsp32(std::string send_reply = "\n", bool debug = true) +{ + char* buffer = new char[50000]; + int nrReceivedBytes = recv(btClientSocket, buffer, 50000, 0); //if your socket is blocking, this will block until a message comes in + if (nrReceivedBytes < 0) { + delete[] buffer; //make sure to clean up things on the heap made with "new" + return ""; + } + + std::string message(buffer, nrReceivedBytes); + + if(debug) + std::cout << "Message recieved: " < measured. +//you can give up an expected message to see if your data is validated. MAKE SURE TO MATCH THE WHITESPACE (so terminate with \r\n). +void benchmarkMessagesPerSecond(std::string expectedMessage ="-", float measureXseconds = 10.0f ) +{ + clock_t start, time = 0; + start = clock(); + + int validMessagesCounter = 0; + int invalidMessagesCounter = 0; + + std::cout << "Benchmark started, wait " << measureXseconds << " seconds" << std::endl; + + if (expectedMessage != "-") { - char recievedMessage[512]; //make sure buffer is big enough for any messages your receiving - int recievedMessageLength = 512; - int recieveResult = recv(btClientSocket, recievedMessage, recievedMessageLength, 0); //if your socket is blocking, this will block until a - if (recieveResult < 0) //a message is recieved. If not, it will return right - { //away - continue; + while (time < measureXseconds) + { + std::string msg = recieveStringMessageFromEsp32("\n", false); + + if (msg == "") + { + // do nothing, no message was received in the time period + } + else if (msg == expectedMessage) + { + validMessagesCounter++; + } + else + { + invalidMessagesCounter++; + } + time = (clock() - start) / CLOCKS_PER_SEC; } - printf("Message recieved - \r\n"); - for (int i = 0; i < recieveResult; i++) + } + else + { + while (time < measureXseconds) { - printf("%c", recievedMessage[i]); + std::string msg = recieveStringMessageFromEsp32("\n", false); + if (msg == "") + { + // do nothing, no message was received in the time period + } + else + { + validMessagesCounter++; + } + time = (clock() - start) / CLOCKS_PER_SEC; } - printf("\r\n"); } + std::cout << "Benchmark completed" << std::endl; + std::cout << "Measured for " << time << " seconds" << std::endl; + std::cout << "Received " << validMessagesCounter << " valid messages and " << invalidMessagesCounter << " invalid messages" << std::endl; + std::cout << "Total: " << validMessagesCounter / time << " messages per second." << std::endl; } + + int main() { printf("Attempting to find paired ESP32 devices.\r\n"); @@ -157,10 +231,16 @@ int main() { return 0; } - if (!sendMessageToEsp32()) //send a message to the ESP32 + if (!sendMessageToEsp32("\n")) //send a message to the ESP32 { return 0; } - recieveMessageFromEsp32(); //receive messages from ESP32 + std::cout <<"Waiting to recieve a message\r\n"; + //while (true) + //{ + // recieveStringMessageFromEsp32(); //receive messages from ESP32 + //} + benchmarkMessagesPerSecond("<970,400,500-500,500,100-1,0>\r\n", 10); + return 0; } \ No newline at end of file diff --git a/firmware/Bluetooth_serial_test/.gitignore b/firmware/Bluetooth_serial_test/.gitignore new file mode 100644 index 0000000..89cc49c --- /dev/null +++ b/firmware/Bluetooth_serial_test/.gitignore @@ -0,0 +1,5 @@ +.pio +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/ipch diff --git a/firmware/Bluetooth_serial_test/.vscode/extensions.json b/firmware/Bluetooth_serial_test/.vscode/extensions.json new file mode 100644 index 0000000..e80666b --- /dev/null +++ b/firmware/Bluetooth_serial_test/.vscode/extensions.json @@ -0,0 +1,7 @@ +{ + // See http://go.microsoft.com/fwlink/?LinkId=827846 + // for the documentation about the extensions.json format + "recommendations": [ + "platformio.platformio-ide" + ] +} diff --git a/firmware/Bluetooth_serial_test/include/README b/firmware/Bluetooth_serial_test/include/README new file mode 100644 index 0000000..194dcd4 --- /dev/null +++ b/firmware/Bluetooth_serial_test/include/README @@ -0,0 +1,39 @@ + +This directory is intended for project header files. + +A header file is a file containing C declarations and macro definitions +to be shared between several project source files. You request the use of a +header file in your project source file (C, C++, etc) located in `src` folder +by including it, with the C preprocessing directive `#include'. + +```src/main.c + +#include "header.h" + +int main (void) +{ + ... +} +``` + +Including a header file produces the same results as copying the header file +into each source file that needs it. Such copying would be time-consuming +and error-prone. With a header file, the related declarations appear +in only one place. If they need to be changed, they can be changed in one +place, and programs that include the header file will automatically use the +new version when next recompiled. The header file eliminates the labor of +finding and changing all the copies as well as the risk that a failure to +find one copy will result in inconsistencies within a program. + +In C, the usual convention is to give header files names that end with `.h'. +It is most portable to use only letters, digits, dashes, and underscores in +header file names, and at most one dot. + +Read more about using header files in official GCC documentation: + +* Include Syntax +* Include Operation +* Once-Only Headers +* Computed Includes + +https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html diff --git a/firmware/Bluetooth_serial_test/lib/README b/firmware/Bluetooth_serial_test/lib/README new file mode 100644 index 0000000..6debab1 --- /dev/null +++ b/firmware/Bluetooth_serial_test/lib/README @@ -0,0 +1,46 @@ + +This directory is intended for project specific (private) libraries. +PlatformIO will compile them to static libraries and link into executable file. + +The source code of each library should be placed in a an own separate directory +("lib/your_library_name/[here are source files]"). + +For example, see a structure of the following two libraries `Foo` and `Bar`: + +|--lib +| | +| |--Bar +| | |--docs +| | |--examples +| | |--src +| | |- Bar.c +| | |- Bar.h +| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html +| | +| |--Foo +| | |- Foo.c +| | |- Foo.h +| | +| |- README --> THIS FILE +| +|- platformio.ini +|--src + |- main.c + +and a contents of `src/main.c`: +``` +#include +#include + +int main (void) +{ + ... +} + +``` + +PlatformIO Library Dependency Finder will find automatically dependent +libraries scanning project source files. + +More information about PlatformIO Library Dependency Finder +- https://docs.platformio.org/page/librarymanager/ldf.html diff --git a/firmware/Bluetooth_serial_test/platformio.ini b/firmware/Bluetooth_serial_test/platformio.ini new file mode 100644 index 0000000..2fedd0b --- /dev/null +++ b/firmware/Bluetooth_serial_test/platformio.ini @@ -0,0 +1,14 @@ +; PlatformIO Project Configuration File +; +; Build options: build flags, source filter +; Upload options: custom upload port, speed and extra flags +; Library options: dependencies, extra library storages +; Advanced options: extra scripting +; +; Please visit documentation for the other options and examples +; https://docs.platformio.org/page/projectconf.html + +[env:featheresp32] +platform = espressif32 +board = featheresp32 +framework = arduino diff --git a/firmware/Bluetooth_serial_test/src/main.cpp b/firmware/Bluetooth_serial_test/src/main.cpp new file mode 100644 index 0000000..b9ca389 --- /dev/null +++ b/firmware/Bluetooth_serial_test/src/main.cpp @@ -0,0 +1,25 @@ +#include +#include "BluetoothSerial.h" + +#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED) +#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it +#endif + +BluetoothSerial SerialBT; + +void setup() { + // put your setup code here, to run once: + Serial.begin(9600); + SerialBT.begin("ESP32test"); //Bluetooth device name + Serial.println("The device started, now you can pair it with bluetooth!"); +} + +void loop() { + if (SerialBT.available()) + { + String message = SerialBT.readStringUntil('\n'); + Serial.println(message); + SerialBT.println("<970,400,500-500,500,100-1,0>"); + } + // delay is only required if you do non-blocking or one way messages only. +} \ No newline at end of file diff --git a/firmware/Bluetooth_serial_test/test/README b/firmware/Bluetooth_serial_test/test/README new file mode 100644 index 0000000..b94d089 --- /dev/null +++ b/firmware/Bluetooth_serial_test/test/README @@ -0,0 +1,11 @@ + +This directory is intended for PlatformIO Unit Testing and project tests. + +Unit Testing is a software testing method by which individual units of +source code, sets of one or more MCU program modules together with associated +control data, usage procedures, and operating procedures, are tested to +determine whether they are fit for use. Unit testing finds problems early +in the development cycle. + +More information about PlatformIO Unit Testing: +- https://docs.platformio.org/page/plus/unit-testing.html