0% found this document useful (0 votes)
19 views9 pages

Bluetooth Device Connection Guide

This C++ program initializes Winsock and lists available Bluetooth devices, allowing the user to connect to a selected device. It includes functionality for pairing with the device, connecting via RFCOMM, and sending formatted ESC/POS commands to a Bluetooth printer. The program handles errors and ensures proper cleanup of resources before exiting.

Uploaded by

02113 Emon
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views9 pages

Bluetooth Device Connection Guide

This C++ program initializes Winsock and lists available Bluetooth devices, allowing the user to connect to a selected device. It includes functionality for pairing with the device, connecting via RFCOMM, and sending formatted ESC/POS commands to a Bluetooth printer. The program handles errors and ensures proper cleanup of resources before exiting.

Uploaded by

02113 Emon
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

#include <winsock2.

h>

#include <ws2bth.h>

#include <bluetoothapis.h>

#include <iostream>

#include <vector>

#include <string>

#include <windows.h>

#pragma comment(lib, "Ws2_32.lib") // For Winsock functions

#pragma comment(lib, "[Link]") // For Bluetooth functions

//Bluetooth device structure

struct BluetoothDevice {

std::wstring name;

BLUETOOTH_ADDRESS address;

SOCKADDR_BTH addr_bth;

};

//Winsock initialization

void InitializeWinsock() {

WSADATA wsaData;

if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {

std::cerr << "Winsock initialization failed.\n";

exit(1);

}
//Listing Bluetooth devices

void ListBluetoothDevices(std::vector<BluetoothDevice>& devices) {

HANDLE hRadio;

BLUETOOTH_FIND_RADIO_PARAMS radioParams = {
sizeof(BLUETOOTH_FIND_RADIO_PARAMS) };

HBLUETOOTH_RADIO_FIND hFindRadio = BluetoothFindFirstRadio(&radioParams, &hRadio);

if (!hFindRadio || !hRadio) {

std::cerr << "No Bluetooth radio found.\n";

return;

// Device searching logic...

BLUETOOTH_DEVICE_SEARCH_PARAMS searchParams = { 0 };

[Link] = sizeof(searchParams);

[Link] = hRadio;

[Link] = TRUE;

[Link] = FALSE;

[Link] = TRUE;

[Link] = TRUE; // Include unknown devices

[Link] = TRUE; // Actively scan

[Link] = 4; // ~7.68 seconds scan

//Device info Retrieval

BLUETOOTH_DEVICE_INFO deviceInfo = { 0 };

[Link] = sizeof(deviceInfo);

HBLUETOOTH_DEVICE_FIND hFind = BluetoothFindFirstDevice(&searchParams, &deviceInfo);


if (!hFind) {

std::cerr << "No Bluetooth devices found.\n";

return;

//Processing found devices

int index = 0;

do {

BluetoothDevice dev;

[Link] = [Link];

[Link] = [Link];

dev.addr_bth.addressFamily = AF_BTH;

dev.addr_bth.btAddr = ((uint64_t)[Link][5] << 40) |

((uint64_t)[Link][4] << 32) |

((uint64_t)[Link][3] << 24) |

((uint64_t)[Link][2] << 16) |

((uint64_t)[Link][1] << 8) |

(uint64_t)[Link][0];

dev.addr_bth.port = 1; // RFCOMM port

devices.push_back(dev);

std::wcout << L"[" << index++ << L"] " << [Link] << L" - ";

printf("%02X:%02X:%02X:%02X:%02X:%02X\n",

[Link][5], [Link][4],

[Link][3], [Link][2],

[Link][1], [Link][0]);
} while (BluetoothFindNextDevice(hFind, &deviceInfo));

BluetoothFindDeviceClose(hFind);

CloseHandle(hRadio);

bool IsDevicePaired(const BLUETOOTH_ADDRESS& address) {

BLUETOOTH_DEVICE_INFO deviceInfo = { 0 };

[Link] = sizeof(deviceInfo);

[Link] = address;

if (BluetoothGetDeviceInfo(NULL, &deviceInfo) == ERROR_SUCCESS) {

return [Link]; // ✅ this is what actually tells if it's paired

return false;

//Pairing with the device

bool PairWithDevice(BLUETOOTH_ADDRESS address) {

BLUETOOTH_DEVICE_INFO deviceInfo = { 0 };

[Link] = sizeof(deviceInfo);

[Link] = address;

DWORD result = BluetoothAuthenticateDeviceEx(NULL, NULL, &deviceInfo, NULL,


MITMProtectionNotRequired);

if (result == ERROR_SUCCESS) {

return true; // 🔄 Removed extra message


}

else {

std::wcerr << L"Pairing failed with error code: " << result << L"\n";

return false;

//Connecting to the device

SOCKET ConnectToDevice(const BluetoothDevice& device) {

SOCKET sock = socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM);

if (sock == INVALID_SOCKET) {

std::cerr << "Failed to create socket.\n";

return INVALID_SOCKET;

if (connect(sock, (SOCKADDR*)&device.addr_bth, sizeof(device.addr_bth)) == SOCKET_ERROR)


{

std::cerr << "Failed to connect to Bluetooth device.\n";

closesocket(sock);

return INVALID_SOCKET;

return sock;

//Sending data to the device

void SendData(SOCKET sock, const std::string& data) {

int result = send(sock, data.c_str(), [Link](), 0);


if (result == SOCKET_ERROR) {

std::cerr << "Failed to send data.\n";

else {

std::cout << "Data sent successfully.\n";

//Main function

int main() {

std::vector<BluetoothDevice> devices;

// Initialize Winsock

InitializeWinsock();

// List available Bluetooth devices

std::cout << "Scanning for Bluetooth devices...\n";

ListBluetoothDevices(devices);

// Handle no devices found

if ([Link]()) {

std::cout << "No devices found.\n";

WSACleanup();

return 1;
}

// User selects a device

int choice;

std::cout << "\nEnter the number of the device you want to connect to: ";

std::cin >> choice;

// Check if the device is valid

if (choice < 0 || choice >= [Link]()) {

std::cout << "Invalid selection.\n";

WSACleanup();

return 1;

if (IsDevicePaired(devices[choice].address)) {

std::wcout << L"Paired already.\n";

else {

std::wcout << L"Attempting to pair...\n";

if (PairWithDevice(devices[choice].address)) {

std::wcout << L"Paired successfully.\n";

else {

std::wcerr << L"Failed to pair.\n";

WSACleanup();

return 1;

}
}

// Connect to the selected device

SOCKET sock = ConnectToDevice(devices[choice]);

if (sock == INVALID_SOCKET) {

WSACleanup();

return 1;

// Get user input and send data

std::string userInput;

std::cout << "Enter message to print: ";

std::[Link]();

std::getline(std::cin, userInput);

// ESC/POS command to reset printer and print

std::string escposCmd;

escposCmd += "\x1B\x40"; // Initialize printer

escposCmd += "\x1B\x61\x01"; // Center alignment

escposCmd += userInput; // User input text

escposCmd += "\n\n"; // New lines

escposCmd += "\x1D\x56\x42\x10"; // Partial cut (or adjust for your printer)

// Send properly formatted ESC/POS command

SendData(sock, escposCmd);

// Clean up
closesocket(sock);

WSACleanup();

return 0;

You might also like