持续从心率监测器获取数据

时间:2017-11-15 10:11:52

标签: c# bluetooth uwp

我一直在研究一个从Polar H7 hrm读取一个人心率的项目。我已成功连接设备并获得程序在UI中显示为文本的心率。但是,有些情况下程序突然停止从设备输入。

我已经检查了设备与Win 10笔记本电脑的连接,发现它稳定,程序也没有例外。文本只是停止改变。

这是我写的代码:

public sealed partial class MainPage : Page
{   
    private GattDeviceService device;


    public MainPage()
    {
        this.InitializeComponent();

        init();
    }

    async void init()
    {
        var devices = await DeviceInformation.FindAllAsync(GattDeviceService.GetDeviceSelectorFromUuid(GattServiceUuids.HeartRate));
        Status.Text = devices.Count.ToString();
        device = await GattDeviceService.FromIdAsync(devices[0].Id);
        enableSensor();
    }

    private async void enableSensor()
    {
        IReadOnlyList<GattCharacteristic> characteristicList;

        characteristicList = device.GetAllCharacteristics();
        if (characteristicList != null)
        {
            GattCharacteristic characteristic = characteristicList[0];
            if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Notify))
            {
                characteristic.ValueChanged += SendNotif;
                await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);
            }
        }
    }

    async void SendNotif(GattCharacteristic sender, GattValueChangedEventArgs eventArgs)
    {
        if (eventArgs.CharacteristicValue.Length != 0) { 
            byte[] hrData = new byte[eventArgs.CharacteristicValue.Length];
            DataReader.FromBuffer(eventArgs.CharacteristicValue).ReadBytes(hrData);

            var hrValue = ProcessData(hrData);


            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                Status.Text = hrValue.ToString();

            });
        }

    }

    private int ProcessData(byte[] data)
    {
        // Heart Rate profile defined flag values
        const byte heartRateValueFormat = 0x01;

        byte currentOffset = 0;
        byte flags = data[currentOffset];
        bool isHeartRateValueSizeLong = ((flags & heartRateValueFormat) != 0);

        currentOffset++;

        ushort heartRateMeasurementValue;

        if (isHeartRateValueSizeLong)
        {
            heartRateMeasurementValue = (ushort)((data[currentOffset + 1] << 8) + data[currentOffset]);
            currentOffset += 2;
        }
        else
        {
            heartRateMeasurementValue = data[currentOffset];
        }

        return heartRateMeasurementValue;
    }
}

0 个答案:

没有答案
相关问题