in C+ win32 i want to send data to a Bluetooth BLE client
any easy example will help tank!
what i have for now BT detect and connect how to send data to my BT led??
help need
Code:#pragma warning (disable: 4068) #include <windows.h> #include <stdio.h> #include <tchar.h> #include <setupapi.h> #include <devguid.h> #include <regstr.h> #include <bthdef.h> #include <bluetoothleapis.h> #include <iostream> #include <sstream> #include <string> #include <locale> #pragma comment(lib, "SetupAPI") #pragma comment(lib, "BluetoothApis.lib") //#define MOSS_DEVICE_UUID "{88880001-b5a3-f393-e0a9-e50e24dc1234}" //#define MOSS_DEVICE_UUID "{00001800 - 0000 - 1000 - 8000 - 00805f9b34fb}" #define MOSS_DEVICE_UUID "{e0cbf06c-cd8b-4647-bb8a-263b43f0f974}" //{e0cbf06c-cd8b-4647-bb8a-263b43f0f974} namespace util { std::string to_narrow(const wchar_t* s, char def = '?', const std::locale& loc = std::locale()) { std::ostringstream stm; while (*s != L'\0') { stm << std::use_facet< std::ctype<wchar_t> >(loc).narrow(*s++, def); } return stm.str(); } } void CALLBACK HandleBLENotification(BTH_LE_GATT_EVENT_TYPE EventType, PVOID EventOutParameter, PVOID Context) { printf("notification obtained "); PBLUETOOTH_GATT_VALUE_CHANGED_EVENT ValueChangedEventParameters = (PBLUETOOTH_GATT_VALUE_CHANGED_EVENT)EventOutParameter; HRESULT hr; if (0 == ValueChangedEventParameters->CharacteristicValue->DataSize) { hr = E_FAIL; printf("datasize 0\n"); } else { printf("got value\n"); //for(int i=0; i<ValueChangedEventParameters->CharacteristicValue->DataSize;i++) { // printf("%0x",ValueChangedEventParameters->CharacteristicValue->Data[i]); //} // if the first bit is set, then the value is the next 2 bytes. If it is clear, the value is in the next byte //The Heart Rate Value Format bit (bit 0 of the Flags field) indicates if the data format of //the Heart Rate Measurement Value field is in a format of UINT8 or UINT16. //When the Heart Rate Value format is sent in a UINT8 format, the Heart Rate Value //Format bit shall be set to 0. When the Heart Rate Value format is sent in a UINT16 //format, the Heart Rate Value Format bit shall be set to 1 //from this PDF https://www.bluetooth.org/docman/handlers/downloaddoc.ashx?doc_id=239866 //unsigned heart_rate; //if (0x01 == (ValueChangedEventParameters->CharacteristicValue->Data[0] & 0x01)) { // heart_rate = ValueChangedEventParameters->CharacteristicValue->Data[1] * 256 + ValueChangedEventParameters->CharacteristicValue->Data[2]; //} //else { // heart_rate = ValueChangedEventParameters->CharacteristicValue->Data[1]; //} //printf("%d\n", heart_rate); } } // This function works to get a handle for a BLE device based on its GUID // Copied from http://social.msdn.microsoft.com/Forums/windowshardware/en-US/e5e1058d-5a64-4e60-b8e2-0ce327c13058/erroraccessdenied-error-when-trying-to-receive-data-from-bluetooth-low-energy-devices?forum=wdk // From https://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/bad452cb-4fc2-4a86-9b60-070b43577cc9/is-there-a-simple-example-desktop-programming-c-for-bluetooth-low-energy-devices?forum=wdk // Credits to Andrey_sh HANDLE GetBLEHandle(__in GUID AGuid) { HDEVINFO hDI; SP_DEVICE_INTERFACE_DATA did; SP_DEVINFO_DATA dd; GUID BluetoothInterfaceGUID = AGuid; HANDLE hComm = NULL; hDI = SetupDiGetClassDevs(&BluetoothInterfaceGUID, NULL, NULL, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT); if (hDI == INVALID_HANDLE_VALUE) return NULL; did.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA); dd.cbSize = sizeof(SP_DEVINFO_DATA); for (DWORD i = 0; SetupDiEnumDeviceInterfaces(hDI, NULL, &BluetoothInterfaceGUID, i, &did); i++) { SP_DEVICE_INTERFACE_DETAIL_DATA DeviceInterfaceDetailData; DeviceInterfaceDetailData.cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA); DWORD size = 0; if (!SetupDiGetDeviceInterfaceDetail(hDI, &did, NULL, 0, &size, 0)) { int err = GetLastError(); if (err == ERROR_NO_MORE_ITEMS) { printf("ERROR_NO_MORE_ITEM\n"); break; } PSP_DEVICE_INTERFACE_DETAIL_DATA pInterfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)GlobalAlloc(GPTR, size); pInterfaceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA); if (!SetupDiGetDeviceInterfaceDetail(hDI, &did, pInterfaceDetailData, size, &size, &dd)) { printf("SetupDiGet\n"); break; } hComm = CreateFile( pInterfaceDetailData->DevicePath, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); GlobalFree(pInterfaceDetailData); } } SetupDiDestroyDeviceInfoList(hDI); return hComm; } DWORD WriteValueToCharacteristic(__in const HANDLE deviceHandle, __in const CharacteristicData* pCharData, __in const UCHAR* writeBuffer, __in const USHORT bufferSize, __in const BOOL noResponse) { HRESULT hr; PBTH_LE_GATT_CHARACTERISTIC pCharacteristic = pCharData->pCharacteristic; USHORT charValueDataSize = 512; PBTH_LE_GATT_CHARACTERISTIC_VALUE pWriteValue = (PBTH_LE_GATT_CHARACTERISTIC_VALUE)HeapAlloc ( GetProcessHeap(), HEAP_ZERO_MEMORY, charValueDataSize + sizeof(BTH_LE_GATT_CHARACTERISTIC_VALUE) ); if (pWriteValue == NULL) { printf("Out of memory.\n"); return -1; } hr = BluetoothGATTGetCharacteristicValue ( deviceHandle, pCharacteristic, (ULONG)charValueDataSize, pWriteValue, NULL, BLUETOOTH_GATT_FLAG_FORCE_READ_FROM_DEVICE ); if (bufferSize > pWriteValue->DataSize) { if (pWriteValue->DataSize == 0) { pWriteValue->DataSize = bufferSize; } } // after the first write, DataSize stays as 3 //pWriteValue->DataSize here is 3, as expected //buffer size is also 3 memcpy(pWriteValue->Data, writeBuffer, bufferSize); ULONG flags = noResponse == TRUE ? BLUETOOTH_GATT_FLAG_WRITE_WITHOUT_RESPONSE : 0; hr = BluetoothGATTSetCharacteristicValue ( deviceHandle, pCharacteristic, pWriteValue, NULL, flags ); if (hr != S_OK) { printf("BluetoothGATTSetCharacteristicValue returned error %d\n", hr); HeapFree(GetProcessHeap(), 0, pWriteValue); return -1; } HeapFree(GetProcessHeap(), 0, pWriteValue); return ERROR_SUCCESS; } int ConnectBLEDevice() { // Step 1: find the BLE device handle from its GUID GUID AGuid; // GUID can be constructed from "{xxx....}" string using CLSID CLSIDFromString(TEXT(MOSS_DEVICE_UUID), &AGuid); // Get the handle HANDLE hLEDevice = GetBLEHandle(AGuid); // Step 2: Get a list of services that the device advertises // first send 0, NULL as the parameters to BluetoothGATTServices inorder to get the number of // services in serviceBufferCount USHORT serviceBufferCount = 0; HRESULT hr = BluetoothGATTGetServices( hLEDevice, 0, NULL, &serviceBufferCount, BLUETOOTH_GATT_FLAG_NONE); if (hr== ERROR_MORE_DATA) printf("ERROR_MORE_DATA\n"); if (hr == ERROR_ACCESS_DENIED) printf("ERROR_ACCESS_DENIED\n"); if (hr == ERROR_INVALID_PARAMETER) printf("ERROR_INVALID_PARAMETER\n"); if (hr == ERROR_INVALID_USER_BUFFER) printf("ERROR_INVALID_USER_BUFFER\n"); if (hr == ERROR_BAD_COMMAND) printf("ERROR_BAD_COMMAND\n"); if (hr == ERROR_NO_SYSTEM_RESOURCES) printf("ERROR_NO_SYSTEM_RESOURCES\n"); if (hr == S_OK) printf("S_OK\n"); BTH_LE_GATT_RELIABLE_WRITE_CONTEXT ReliableWriteContext = NULL; hr = BluetoothGATTBeginReliableWrite(hLEDevice, &ReliableWriteContext, BLUETOOTH_GATT_FLAG_NONE); if (SUCCEEDED(hr)) { PBTH_LE_GATT_CHARACTERISTIC parentCharacteristic; RtlZeroMemory(&newValue, (sizeof(newValue))); RtlZeroMemory(&parentCharacteristic, (sizeof(parentCharacteristic))); WriteValueToCharacteristic(hLEDevice, _in const CharacteristicData * pCharData, "xxx", 10, 0); // Set the new characteristic value hr = BluetoothGATTSetCharacteristicValue(hLEDevice, parentCharacteristic, &newValue, NULL, BLUETOOTH_GATT_FLAG_NONE); } if (NULL != ReliableWriteContext) { BluetoothGATTEndReliableWrite(hLEDevice, ReliableWriteContext, BLUETOOTH_GATT_FLAG_NONE); } // go into an inf loop that sleeps. you will ideally see notifications from the HR device while (1) { printf("sleep\n"); Sleep(1000); } CloseHandle(hLEDevice); if (GetLastError() != NO_ERROR && GetLastError() != ERROR_NO_MORE_ITEMS) { // Insert error handling here. return 1; } return 0; } int ScanBLEDevices() { HDEVINFO hDI; SP_DEVINFO_DATA did; DWORD i; // Create a HDEVINFO with all present devices. hDI = SetupDiGetClassDevs(&GUID_DEVCLASS_BLUETOOTH, NULL, NULL, DIGCF_PRESENT); if (hDI == INVALID_HANDLE_VALUE) { return 1; } // Enumerate through all devices in Set. did.cbSize = sizeof(SP_DEVINFO_DATA); for (i = 0; SetupDiEnumDeviceInfo(hDI, i, &did); i++) { bool hasError = false; DWORD nameData; LPTSTR nameBuffer = NULL; DWORD nameBufferSize = 0; while (!SetupDiGetDeviceRegistryProperty( hDI, &did, SPDRP_FRIENDLYNAME, &nameData, (PBYTE)nameBuffer, nameBufferSize, &nameBufferSize)) { if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) { if (nameBuffer) delete(nameBuffer); nameBuffer = new wchar_t[nameBufferSize * 2]; } else { hasError = true; break; } } DWORD addressData; LPTSTR addressBuffer = NULL; DWORD addressBufferSize = 0; while (!SetupDiGetDeviceRegistryProperty( hDI, &did, SPDRP_HARDWAREID, &addressData, (PBYTE)addressBuffer, addressBufferSize, &addressBufferSize)) { if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) { if (addressBuffer) delete(addressBuffer); addressBuffer = new wchar_t[addressBufferSize * 2]; } else { hasError = true; break; } } LPTSTR deviceIdBuffer = NULL; DWORD deviceIdBufferSize = 0; while (!SetupDiGetDeviceInstanceId( hDI, &did, deviceIdBuffer, deviceIdBufferSize, &deviceIdBufferSize)) { if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) { if (deviceIdBuffer) delete(deviceIdBuffer); deviceIdBuffer = new wchar_t[deviceIdBufferSize * 2]; } else { hasError = true; break; } } if (hasError) { continue; } std::string name = util::to_narrow(nameBuffer); std::string address = util::to_narrow(addressBuffer); std::string deviceId = util::to_narrow(deviceIdBuffer); std::cout << "Found " << name << " (" << deviceId << ")" << std::endl; } return 0; } int _tmain(int argc, _TCHAR* argv[]) { //wmic path win32_computersystemproduct get UUID //607C4600 - D7DA - 11DD - BBC7 - 2CFDA1E02528 int result = 0; ScanBLEDevices(); result = ConnectBLEDevice(); std::cin.get(); return result; }
+ Reply to Thread
Results 1 to 5 of 5
-
-
okay i doing it wrong here the new code
device is detected connected to ble send do okay no error -
here the code
Code:#include "pch.h" #pragma comment(lib, "oleaut32") #pragma comment(lib, "runtimeobject") #include <string> using namespace winrt; using namespace Windows::Foundation; using namespace winrt::Windows::Foundation; using namespace Windows::Storage::Streams; using namespace Windows::Devices::Bluetooth; using namespace Windows::Foundation::Collections; using namespace Windows::Devices::Bluetooth::Advertisement; using namespace Windows::Devices::Bluetooth::GenericAttributeProfile; std::wstring guidToString(GUID uuid) { std::wstring guid; WCHAR* wszUuid = NULL; if (::UuidToString(&uuid, (RPC_WSTR*) &wszUuid) == RPC_S_OK) { guid = wszUuid; ::RpcStringFree((RPC_WSTR*) &wszUuid); } return guid; } std::wstring advertisementTypeToString(BluetoothLEAdvertisementType advertisementType) { std::wstring ret; switch (advertisementType) { case BluetoothLEAdvertisementType::ConnectableUndirected: ret = L"ConnectableUndirected"; break; case BluetoothLEAdvertisementType::ConnectableDirected: ret = L"ConnectableDirected"; break; case BluetoothLEAdvertisementType::ScannableUndirected: ret = L"ScannableUndirected"; break; case BluetoothLEAdvertisementType::NonConnectableUndirected: ret = L"NonConnectableUndirected"; break; case BluetoothLEAdvertisementType::ScanResponse: ret = L"ScanResponse"; break; default: break; } return ret; } std::wstring bluetoothAddressTypeToString(BluetoothAddressType bluetoothAddressType) { std::wstring ret; switch (bluetoothAddressType) { case BluetoothAddressType::Public: ret = L"Public"; break; case BluetoothAddressType::Random: ret = L"Random"; break; case BluetoothAddressType::Unspecified: ret = L"Unspecified"; break; default: break; } return ret; } winrt::Windows::Foundation::IAsyncAction OpenDevice(unsigned long long deviceAddress) { auto device = co_await BluetoothLEDevice::FromBluetoothAddressAsync(deviceAddress); std::wcout << std::hex << "\tDevice Information: " << std::endl << "\tBluetoothAddress: [" << device.BluetoothAddress() << "]" << std::endl << "\tBluetoothAddressType: [" << bluetoothAddressTypeToString(device.BluetoothAddressType()) << "]" << std::endl << "\tConnectionStatus: [" << (device.ConnectionStatus() == BluetoothConnectionStatus::Connected ? "Connected" : "Disconnected") << "]" << std::endl << "\tDeviceId: [" << device.DeviceId().c_str() << "]" << std::endl << std::endl; //device.DeviceId().c_str(); auto services = co_await device.GetGattServicesAsync(); for (GenericAttributeProfile::GattDeviceService const & s : services.Services()) { std::wcout << std::hex << "\t\tService - Guid: [" << guidToString(s.Uuid()) << "]" << std::endl; auto characteristics = co_await s.GetCharacteristicsAsync(); for (GenericAttributeProfile::GattCharacteristic const & c : characteristics.Characteristics()) { std::wcout << std::hex << "\t\t\tCharacteristic - Guid: [" << guidToString(c.Uuid()) << "]" << std::endl; if (c.CharacteristicProperties() == GattCharacteristicProperties::Read) { auto readResult = co_await c.ReadValueAsync(); if (readResult.Status() == GattCommunicationStatus::Success) { std::wcout << "\t\t\tCharacteristic Data - Size: [" << readResult.Value().Length() << "]" << std::endl; DataReader reader = DataReader::FromBuffer(readResult.Value()); std::wcout << "\t\t\tCharacteristic Data - [" << reader.ReadString(readResult.Value().Length()).c_str() << "]" << std::endl; } } if (c.CharacteristicProperties() == GattCharacteristicProperties::Notify) { c.ValueChanged([](GattCharacteristic const& charateristic, GattValueChangedEventArgs const& args) { std::wcout << std::hex << "\t\tNotified GattCharacteristic - Guid: [" << guidToString(charateristic.Uuid()) << "]" << std::endl; DataReader reader = DataReader::FromBuffer(args.CharacteristicValue()); // Note this assumes value is string the characteristic type must be determined before reading // This can display junk or maybe blowup std::wcout << "\t\t\tCharacteristic Data - [" << reader.ReadString(args.CharacteristicValue().Length()).c_str() << "]" << std::endl; }); } } } auto uartService = services.Services().GetAt(3); auto txService = (co_await uartService.GetCharacteristicsAsync()).Characteristics().GetAt(0); auto rxService = (co_await uartService.GetCharacteristicsAsync()).Characteristics().GetAt(1); auto writer = Windows::Storage::Streams::DataWriter(); writer.WriteUInt16(0xFFF8U); //0x3B,0x24,0,0,0,0,0,0,0,0,0,0,0x5f ///## Power control //Example bytes `ON`: `00 04 80 00 00 0d 0e 0b 3b 23 00 00 00 00 00 00 00 32 00 00 90` //Example bytes `OFF`: `00 5b 80 00 00 0d 0e 0b 3b 24 00 00 00 00 00 00 00 32 00 00 91` auto status = co_await txService.WriteValueWithResultAsync(writer.DetachBuffer(), winrt::Windows::Devices::Bluetooth::GenericAttributeProfile::GattWriteOption::WriteWithoutResponse); if (status.Status() == GattCommunicationStatus::Success) { std::wcout << "Write OK"; } else { std::wcout << "Write Failed"; } device.Close(); } void scanble() { init_apartment(); std::atomic<unsigned long long> deviceAddress = 0; try { BluetoothLEAdvertisementWatcher watcher; //watcher.ScanningMode(BluetoothLEScanningMode::Active); watcher.ScanningMode(BluetoothLEScanningMode::Passive); watcher.Received([&](BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs eventArgs) { watcher.Stop(); std::string localName; std::wcout << "AdvertisementReceived:" << std::endl << "\tLocalName: [" << eventArgs.Advertisement().LocalName().c_str() << "]" << "\tAdvertisementType: [" << advertisementTypeToString(eventArgs.AdvertisementType()) << "]" << "\tBluetoothAddress: [0x" << std::hex << eventArgs.BluetoothAddress() << "]" << "\tRawSignalStrengthInDBm: [" << std::dec << eventArgs.RawSignalStrengthInDBm() << "]" << std::endl; if (eventArgs.AdvertisementType() == BluetoothLEAdvertisementType::ConnectableUndirected || eventArgs.AdvertisementType() == BluetoothLEAdvertisementType::ConnectableDirected) { for (GUID const& g : eventArgs.Advertisement().ServiceUuids()) std::wcout << "ServiceUUID: [" << guidToString(g) << "]" << std::endl; deviceAddress = eventArgs.BluetoothAddress(); } }); std::cout << "Waiting for device: "; watcher.Start(); int count = 0; while ((count++ < 10) && deviceAddress == 0) { std::this_thread::sleep_for(std::chrono::seconds(3)); std::cout << '.'; } std::cout << std::endl << "Finished waiting for device." << std::endl; if (deviceAddress != 0) { std::cout << "Device found." << std::endl; OpenDevice(deviceAddress).get(); } else { //watcher.Stop(); std::cout << "Device not found." << std::endl; } } catch (const std::exception& e) { std::cout << e.what() << std::endl; return ; } } int main() { scanble(); }
-
Running result
Code:LocalName: [LEDnetWF0200A32197AC] AdvertisementType: [ConnectableUndirected] BluetoothAddress: [0x865f02197ac] RawSignalStrengthInDBm: [-22] . Finished waiting for device. Device found. Device Information: BluetoothAddress: [865f02197ac] BluetoothAddressType: [Public] ConnectionStatus: [Disconnected] DeviceId: [BluetoothLE#BluetoothLE64:6e:69:8b:25:88-08:65:f0:21:97:ac] Service - Guid: [00001800-0000-1000-8000-00805f9b34fb] Characteristic - Guid: [00002a00-0000-1000-8000-00805f9b34fb] Characteristic Data - Size: [14] Characteristic Data - [LEDnetWF0200A32197AC] Characteristic - Guid: [00002a01-0000-1000-8000-00805f9b34fb] Characteristic Data - Size: [2] Characteristic Data - [] Characteristic - Guid: [00002a04-0000-1000-8000-00805f9b34fb] Characteristic Data - Size: [8] Characteristic Data - [] Service - Guid: [00001801-0000-1000-8000-00805f9b34fb] Characteristic - Guid: [00002a05-0000-1000-8000-00805f9b34fb] Service - Guid: [0000fe00-0000-1000-8000-00805f9b34fb] Characteristic - Guid: [0000ff22-0000-1000-8000-00805f9b34fb] Characteristic - Guid: [0000ff11-0000-1000-8000-00805f9b34fb] Service - Guid: [0000ffff-0000-1000-8000-00805f9b34fb] Characteristic - Guid: [0000ff02-0000-1000-8000-00805f9b34fb] Characteristic - Guid: [0000ff01-0000-1000-8000-00805f9b34fb] send data to device okay done
open led
// byte[] sendData={0x3B,0x23,0,0,0,0,0,0,0,0,0,0,0x5e}; byte[] sendData={0x71,0x23,0x0F, (byte) 0xa3};
close led byte[] sendData={0x3B,0x24,0,0,0,0,0,0,0,0,0,0,0x5f}; byte[] sendData={0x71,0x24,0x0F, (byte) 0xa4};
almost done just need to figure how to send this hex -
price 10- 20$ i put it in my wall and controll it with my pc in c, there a py code here work greate github ->https://github.com/8none1/zengge_lednetwf
crap led from aliexpress done with it!
next project...
video of what it look like...
https://www.youtube.com/watch?v=y4knuQ5rLrA
Similar Threads
-
Can someone recommend me a tv box without bluetooth and wifi to watch?
By Chemist116 in forum Newbie / General discussionsReplies: 18Last Post: 30th Jun 2022, 10:10 -
Will Bluetooth only deliver onboard sound?
By GLE3 in forum ComputerReplies: 2Last Post: 5th Apr 2021, 23:03 -
Use bluetooth speaker as visualiser
By therock003 in forum Newbie / General discussionsReplies: 9Last Post: 13th Aug 2020, 04:42 -
Can you recommend a product to me -- digital media player WITH BLUETOOTH
By True Colors in forum Newbie / General discussionsReplies: 6Last Post: 14th Dec 2018, 23:13 -
Can I add audio Bluetooth to Vizio TV?
By peggypwr1 in forum AudioReplies: 4Last Post: 19th Nov 2018, 01:01