c/c++ windows ble 蓝牙

1 篇文章 1 订阅
1 篇文章 0 订阅

前言:

在使用c/c++ 通过winrt 操作ble蓝牙之前,本身采用了qt的ble蓝牙库去操作,但是最后发现qt的ble只能使用在msvc+qt中使用,其他的使用的时候就会在扫描的时候没有反应,最终又只能在比较了解ble的同事帮助之下去研究 微软的使用c/c++ 通过winrt 操作ble蓝牙,另外如果不用通过广播过滤设备可以使用第三方库 WCHBleLib_MultiOS 或者是BleWinrtDll ,如果想多深入了解的话也可以参考微软写的demo BluetoothLE,关于微软操作ble接口说明文档地址是bluetoothleadvertisement

注意事项:

1.使用该方式的时候c++的版本要设置为 c++17

2.引用的头文件为:

#include <windows.h>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <mutex> 
#include <winrt/Windows.Foundation.h>
#include <winrt/Windows.Foundation.Collections.h> 
#include <winrt/Windows.Devices.Bluetooth.h>
#include <winrt/Windows.Devices.Enumeration.h>
#include <winrt/Windows.Devices.Bluetooth.Advertisement.h>
#include <winrt/Windows.Devices.Bluetooth.GenericAttributeProfile.h>
#include <winrt/Windows.Storage.Streams.h>
#include <winrt/Windows.Foundation.Collections.h>
#include <winrt/Windows.Devices.Radios.h>
#include <winrt/Windows.Web.Syndication.h>
#include <windows.devices.bluetooth.h>
#include <windows.foundation.h>
#include<coroutine>
using namespace winrt;
using namespace Windows::Devices::Bluetooth;
using namespace Windows::Devices::Bluetooth::Advertisement;
using namespace Windows::Devices::Bluetooth::GenericAttributeProfile;
using namespace winrt::Windows::Devices::Radios;
using namespace Windows::Foundation;
#pragma comment(lib, "windowsapp")
#pragma comment(lib, "WindowsApp.lib")
using namespace std;

1.获取电脑是否支持ble蓝牙和蓝牙是否打开

bool BLEIsLowEnergySupported() {

    auto getadapter_op = Windows::Devices::Bluetooth::BluetoothAdapter::GetDefaultAsync();
    auto adapter = getadapter_op.get();
    auto  supported = adapter.IsLowEnergySupported(); // 获取windows电脑是否支持ble
    if (supported == false) return false;
    auto async = adapter.GetRadioAsync(); //获取本地蓝牙信息
    auto radio = async.get();
    auto t = radio.State(); // 获取电脑蓝牙状态 0未知,1打开,2关闭,3硬件关闭或禁用
    if (t != winrt::Windows::Devices::Radios::RadioState::On) {
        return false;
    }
    return  true;
}

LPWSTRT 与char 互转

LPWSTR ConvertCharToLPWSTR(char* szString, WCHAR* addrchar)
{
    int dwLen = strlen(szString) + 1;
    int nwLen = MultiByteToWideChar(CP_ACP, 0, szString, dwLen, NULL, 0);//算出合适的长度
    MultiByteToWideChar(CP_ACP, 0, szString, dwLen, addrchar, nwLen);
    return addrchar;
}


unsigned char* ConvertLPWSTRToChar(LPCTSTR widestr, unsigned char* addrchar)
{
    int num = WideCharToMultiByte(CP_OEMCP, NULL, widestr, -1, NULL, 0, NULL, FALSE);
    WideCharToMultiByte(CP_OEMCP, NULL, widestr, -1, (char*)addrchar, num, NULL, FALSE);
    return addrchar;
}


 

2.扫描ble蓝牙

void Scanblebackfun(BluetoothLEAdvertisementWatcher w, BluetoothLEAdvertisementReceivedEventArgs e) // 扫描到的ble蓝牙设备通过此回调方式返回{
    if (e.AdvertisementType() == BluetoothLEAdvertisementType::ConnectableUndirected)
    {
        uint64_t address = e.BluetoothAddress(); //获取蓝牙地址,建议不用转字符串太麻烦
        auto Rssi = e.RawSignalStrengthInDBm(); //获取蓝牙信号强度


        //保存有效地址
        BluetoothLEDevice dev = BluetoothLEDevice::FromBluetoothAddressAsync(address).get();
        int cid = 0;
        auto id = dev.BluetoothDeviceId(); //获取蓝牙唯一id
        auto name = dev.Name(); //获取蓝牙名称

        char ID[50] = {0};
        char Name[50] = {0};
        ConvertLPWSTRToChar(id.Id().c_str(), (unsigned char*)ID);
		ConvertLPWSTRToChar(name.c_str(), (unsigned char*)Name);

        auto advertisement = e.Advertisement();  //获取蓝牙广播

        auto serviceUuids = advertisement.ServiceUuids(); //获取广播的服务器的uuid
        auto view = serviceUuids.GetView();
        bool Isfindguid = false;
        for (size_t i = 0; i < view.Size(); i++)
        {
            auto guid = view.GetAt(i);
            if (guid.Data1 == 0xf801 ) { //获取自己需要的广播

                Isfindguid = true;
            }
        }

        dev.Close();

        if (Isfindguid == false) return;
}

void ScanBLEDevice(int timeout) {
    BluetoothLEAdvertisementWatcher m_btWatcher;
    m_btWatcher.ScanningMode(BluetoothLEScanningMode::Passive); //扫描所有此时没有连接的蓝牙
    m_btWatcher.Received(Scanblebackfun); // 注册扫描到的蓝牙回调
    Pens.clear();
    m_btWatcher.Start(); //开始扫描
    Sleep(timeout);
    m_btWatcher.Stop();//结束扫描
}

3.连接蓝牙获取服务和特征

void Characteristic_ValueChanged(GattCharacteristic const& characteristic, GattValueChangedEventArgs args){//订阅回传的数据


}
BLEHandle ConnectBLEDevice(char * id) {
    WCHAR ID[255] = { 0 };
    ConvertCharToLPWSTR(id, ID);
    hstring hst(ID);
    auto device =  BluetoothLEDevice::FromIdAsync(hst).get();
    auto result =  device.GetGattServicesAsync(BluetoothCacheMode::Uncached).get();//连接蓝牙服务
    auto services = result.Services();

    for (size_t i = 0; i < services.Size(); i++)
    {
        auto service = services.GetAt(i);
        auto uuid = service.Uuid(); //获取服务uuid
        auto charact = service.GetCharacteristicsAsync().get();
        auto characts = charact.Characteristics();
        for (size_t j = 0; j < characts.Size(); j++)
        {
            auto charact = characts.GetAt(j);
            auto uuid = charact.Uuid(); //获取子服务的uuid
            auto GAttpro = charact.CharacteristicProperties(); //获取每个子服务特征值
            if (GAttpro == GattCharacteristicProperties::Notify) {                 charact.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue::Notify);//注册订阅
                charact.ValueChanged(auto_revoke, &Characteristic_ValueChanged); //设置订阅数据回传的回调
            }

            if (GAttpro == GattCharacteristicProperties::Write) {
                //写入数据
                unsigned char* buff = "123456";
                unsigned int lenght = 6;
                winrt::Windows::Storage::Streams::DataWriter writer;
                writer.WriteBytes(array_view<uint8_t const>(buff, buff + lenght));
                winrt::Windows::Storage::Streams::IBuffer buffer = writer.DetachBuffer();
                charact.WriteValueAsync(buffer);
            }

            if (GAttpro == GattCharacteristicProperties::Read) {
                
            }


            if (GAttpro == (GattCharacteristicProperties::Write | GattCharacteristicProperties::WriteWithoutResponse)) {
               
            }

            if (GAttpro == (GattCharacteristicProperties::Notify | GattCharacteristicProperties::Write)) {
             
            }

            if (GAttpro == (GattCharacteristicProperties::Notify | GattCharacteristicProperties::Read)) {
                
            }

            if (GAttpro == (GattCharacteristicProperties::Write | GattCharacteristicProperties::Read)) {
                
            }
            return;
        }
    }

}

  • 10
    点赞
  • 52
    收藏
    觉得还不错? 一键收藏
  • 12
    评论
C BLE蓝牙开发是指使用C语言进行蓝牙低功耗(Bluetooth Low Energy,简称BLE)设备开发的过程。BLE蓝牙技术被广泛应用于各种智能设备,包括智能手表、智能手机、健康监测设备等。使用C语言进行BLE蓝牙开发具有以下几个重要的方面。 首先,在C BLE蓝牙开发中,开发者需要了解蓝牙通信协议和BLE协议栈。蓝牙协议规定了通信的标准和数据格式,而BLE协议栈是处理BLE通信的软件层次。C语言可以提供底层的控制和操作,实现与BLE协议栈的交互。 其次,C BLE蓝牙开发需要使用特定的蓝牙开发工具和SDK(软件开发工具包)。开发者可以使用C语言编写代码,通过SDK提供的接口实现与蓝牙设备的连接、数据传输和控制等功能。这些工具和SDK通常由蓝牙芯片厂商提供,开发者可以根据具体的硬件平台选择适合的工具和SDK。 此外,C语言具有高效性和跨平台的特点,在蓝牙开发中也有广泛的应用。通过使用C语言编写的代码,开发者可以利用底层硬件的资源和功能,提高系统的性能和响应速度。同时,C语言也可以在不同的操作系统和开发环境下进行编译和运行,使得BLE蓝牙开发具有更好的灵活性和可移植性。 综上所述,C BLE蓝牙开发是一种使用C语言进行蓝牙低功耗设备开发的方法。它需要对蓝牙通信协议和BLE协议栈有一定的了解,同时使用特定的蓝牙开发工具和SDK进行开发C语言的高效性和跨平台特性使得BLE蓝牙开发更加灵活和可移植。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值