C#蓝牙开发-使用GATT进行蓝牙通信

GATT和经典蓝牙通信的区别,两个BLE设备可以通过GATT实现通信,不需要进行配对,直接连接和通信, 并且设备发现是通过广播发现设备,搜索设备在毫秒级。

1. 创建和初始化GATT服务, 创建一个GATT服务,并且创建了一个Characteristic,设备连接到这个服务之后,通过在Characteristic上进行读写操作,来实现通信

public GattServiceProvider ServiceProvider = null;
GattLocalCharacteristic LocalCharacteristic = null; 

public async Task<bool> InitGattServer()
        {
            if (ServiceProvider != null) return true;

             
            GattServiceProviderResult serviceResult = await GattServiceProvider.CreateAsync(Guid.Parse("0000FD89-0000-1000-8000-00805F9B34FB"));
            if (serviceResult.Error != BluetoothError.Success)
            { 
                Console.WriteLine("初始化GATT服务失:"+ serviceResult.Error);
                return false;
            }
            //  throw new Exception("Create GattService Error:" + serviceResult.Error);

            // 特征 1
            var characteristic1 = await serviceResult.ServiceProvider.Service.CreateCharacteristicAsync(Guid.Parse("00000002-0000-1000-8000-00805F9B34FB"), GattCharacteristicParameters);
            if (characteristic1.Error != BluetoothError.Success)
            {
                Console.WriteLine("初始化GATT服务失:" + serviceResult.Error);
                return false;
            }

            // 特征 2
            //var characteristic2 = await serviceResult.ServiceProvider.Service.CreateCharacteristicAsync("uuid", "GattCharacteristicParameters");
            //if (characteristic2.Error != BluetoothError.Success)
            //{
            //    return false;
            //}

            ServiceProvider = serviceResult.ServiceProvider;
            ServiceProvider.AdvertisementStatusChanged += ServiceProvider_AdvertisementStatusChanged;

            LocalCharacteristic = characteristic1.Characteristic;
            LocalCharacteristic.WriteRequested += OnWriteRequested;
            LocalCharacteristic.ReadRequested += OnReadRequested; 
            Console.WriteLine("GATT服务初始化完成!");
            return true;
        }

2. 将创建的GATT服务广播出去

 public async Task Start()
        { 
            var dataWriter = new DataWriter();
            dataWriter.WriteBytes(new byte[] { 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05 });
            GattServiceProviderAdvertisingParameters advParameters = new GattServiceProviderAdvertisingParameters
            {
                IsConnectable = true,
                IsDiscoverable = true,
                ServiceData = dataWriter.DetachBuffer()
            }; 
            ServiceProvider.StartAdvertising(advParameters);
        }

3. 客户端通过监听这个广播,然后通过广播与这个GATT服务建立连接,广播监听方式参考前面的文章

4. 建立连接之后,获取到这个GATT服务的Characteristic,一个GATT服务可能会有多个Characteristic,可以通过Characteristic的UUID(创建的时候设置的)区分不同的Characteristic,然后对特征进行读写

5. Characteristic写请求-->可以理解为客户端发送数据给服务端

private async void OnWriteRequested(GattLocalCharacteristic sender, GattWriteRequestedEventArgs args)
        {

            using (args.GetDeferral())
            {
                GattWriteRequest request = await args.GetRequestAsync();
                if (request == null)
                {
                    return ;
                }
                var data = new byte[request.Value.Length];
                using (var reader = DataReader.FromBuffer(request.Value))
                {
                    reader.ReadBytes(data);
                }
                 
                Console.WriteLine("GATT写请求:"+ Encoding.Default.GetString(data));

                if (request.Option == GattWriteOption.WriteWithResponse)
                {
                    request.Respond();
                }
            }
        }

6. GATT读请求---> 服务端发送数据到客户端

 private async void OnReadRequested(GattLocalCharacteristic sender, GattReadRequestedEventArgs args)
        {
            Console.WriteLine("GATT写请求");
        }

 ===============================

DEMO: https://download.csdn.net/download/A244108451/87818165

demo包含源码,bin目录下有已经编译好的exe, 如果要测试,可以使用两台笔记本电脑,一台作为服务端,一台作为客户端。

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值