Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
* Bluetooth programming with Windows sockets - https://docs.microsoft.com/en-us/windows/win32/bluetooth/bluetooth-programming-with-windows-sockets
114 changes: 97 additions & 17 deletions WindowsBtWithEsp32/WindowsBtWithEsp32/WindowsBtWithEsp32.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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 <stdlib.h>
#include <stdio.h>
#include <Winsock2.h>
#include <Ws2bth.h>
#include <BluetoothAPIs.h>
#include <iostream>
#include <string>
#include <vector>
#include <chrono>

BTH_ADDR esp32BtAddress;
SOCKADDR_BTH btSocketAddress;
Expand Down Expand Up @@ -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)
{
Expand All @@ -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: " <<message << std::endl;

if (send_reply != "-")
{
sendMessageToEsp32(send_reply); // send message to unblock the ESP32 from waiting on a message from the PC.
}
delete[] buffer; //make sure to clean up things on the heap made with "new"
return message;
}

//returns <nrOfMessages, nrOfSeconds> 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");
Expand All @@ -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;
}
5 changes: 5 additions & 0 deletions firmware/Bluetooth_serial_test/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
.pio
.vscode/.browse.c_cpp.db*
.vscode/c_cpp_properties.json
.vscode/launch.json
.vscode/ipch
7 changes: 7 additions & 0 deletions firmware/Bluetooth_serial_test/.vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
// See http://go.microsoft.com/fwlink/?LinkId=827846
// for the documentation about the extensions.json format
"recommendations": [
"platformio.platformio-ide"
]
}
39 changes: 39 additions & 0 deletions firmware/Bluetooth_serial_test/include/README
Original file line number Diff line number Diff line change
@@ -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
46 changes: 46 additions & 0 deletions firmware/Bluetooth_serial_test/lib/README
Original file line number Diff line number Diff line change
@@ -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 <Foo.h>
#include <Bar.h>

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
14 changes: 14 additions & 0 deletions firmware/Bluetooth_serial_test/platformio.ini
Original file line number Diff line number Diff line change
@@ -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
25 changes: 25 additions & 0 deletions firmware/Bluetooth_serial_test/src/main.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
#include <Arduino.h>
#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.
}
11 changes: 11 additions & 0 deletions firmware/Bluetooth_serial_test/test/README
Original file line number Diff line number Diff line change
@@ -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