简体   繁体   English

C# - 蓝牙编程

[英]C# - Bluetooth programming

In my program, I send a command to a device and it sends some data back.在我的程序中,我向设备发送一个命令,然后它会发回一些数据。 Whenever the data is available, the following event handler gets invoked.只要数据可用,就会调用以下事件处理程序。

private void notify_change(GattCharacteristic sender, GattValueChangedEventArgs args)
{
    lock (this._dataRec)
    {
        notCounter++;
        byte[] bArray = new byte[args.CharacteristicValue.Length];
                DataReader.FromBuffer(args.CharacteristicValue).ReadBytes(bArray);                
                dataQ.Enqueue(Encoding.ASCII.GetString(bArray));
                Monitor.Pulse(this._dataRec);
    }
}

Sometimes, I noticed that this gets called before previous data has been read (or something like that; from the list of commands, data seems to be missing).有时,我注意到在读取以前的数据之前调用它(或类似的东西;从命令列表中,数据似乎丢失了)。 Looks like the buffer gets overwritten whenever the function is invoked.看起来每当调用函数时缓冲区都会被覆盖。 Is there a way to add data to the buffer rather than overwriting it?有没有办法将数据添加到缓冲区而不是覆盖它?

In my program, I send a command to a device and it sends some data back.在我的程序中,我向设备发送一个命令,然后它会发回一些数据。

Since you are trigger response by your calls, be sure that you don't make buffer overflow on device side.由于您是通过调用触发响应,因此请确保不要在设备端造成缓冲区溢出。 Minimal theoretical gap between two packets is 7.5ms but in practice it is about 20-30ms.两个数据包之间的最小理论间隔为 7.5 毫秒,但实际上约为 20-30 毫秒。 So if you are sending in a loop, your device will lost (overwrite) packets if gap is less than your HW setup can handle.因此,如果您在循环中发送,如果间隙小于您的硬件设置可以处理的,您的设备将丢失(覆盖)数据包。

The GATT protocol has two options to receive unsolicited information. GATT 协议有两个选项来接收未经请求的信息。 They are notifications and indications.它们是通知和指示。 notifications are one with out acknowledgement from the receiver where as indications require an acknowledgment from the receiver.通知是一种没有接收器确认的通知,其中指示需要接收器的确认。 so you probably need indications and if this is not an option you need to ensure that the data is copied before the next notification.所以您可能需要指示,如果这不是一个选项,您需要确保在下一次通知之前复制数据。

see the following from the Bluetooth specification.请参阅蓝牙规范中的以下内容。 在此处输入图片说明

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM