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

Blue Printer Con

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)
21 views9 pages

Blue Printer Con

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
You are on page 1/ 9

#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, "Bthprops.lib") // 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 };

searchParams.dwSize = sizeof(searchParams);

searchParams.hRadio = hRadio;

searchParams.fReturnAuthenticated = TRUE;

searchParams.fReturnRemembered = FALSE;

searchParams.fReturnConnected = TRUE;

searchParams.fReturnUnknown = TRUE; // Include unknown devices

searchParams.fIssueInquiry = TRUE; // Actively scan

searchParams.cTimeoutMultiplier = 4; // ~7.68 seconds scan

//Device info Retrieval

BLUETOOTH_DEVICE_INFO deviceInfo = { 0 };

deviceInfo.dwSize = 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;

dev.name = deviceInfo.szName;

dev.address = deviceInfo.Address;

dev.addr_bth.addressFamily = AF_BTH;

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

((uint64_t)dev.address.rgBytes[4] << 32) |

((uint64_t)dev.address.rgBytes[3] << 24) |

((uint64_t)dev.address.rgBytes[2] << 16) |

((uint64_t)dev.address.rgBytes[1] << 8) |

(uint64_t)dev.address.rgBytes[0];

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

devices.push_back(dev);

std::wcout << L"[" << index++ << L"] " << deviceInfo.szName << L" - ";

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

deviceInfo.Address.rgBytes[5], deviceInfo.Address.rgBytes[4],

deviceInfo.Address.rgBytes[3], deviceInfo.Address.rgBytes[2],

deviceInfo.Address.rgBytes[1], deviceInfo.Address.rgBytes[0]);
} while (BluetoothFindNextDevice(hFind, &deviceInfo));

BluetoothFindDeviceClose(hFind);

CloseHandle(hRadio);

bool IsDevicePaired(const BLUETOOTH_ADDRESS& address) {

BLUETOOTH_DEVICE_INFO deviceInfo = { 0 };

deviceInfo.dwSize = sizeof(deviceInfo);

deviceInfo.Address = address;

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

return deviceInfo.fAuthenticated; // ✅ 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 };

deviceInfo.dwSize = sizeof(deviceInfo);

deviceInfo.Address = 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(), data.length(), 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 (devices.empty()) {

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 >= devices.size()) {

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::cin.ignore();

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