hello大家好呀O(∩_∩)O最近在做毕设 其中有个小功能要用到实时心率数据。查找网上的资料发现只有小米手环的实时心率数据导出但是没有华为手环的,我试了华为手环但是并不能行得通哈哈哈。现在分享一下华为手环实时心率数据导出的代码。
Step 1: 创建UWP项目
-
打开 Visual Studio → 点击 创建新项目 → 搜索 "空白应用(通用 Windows)" → 选择 C# 版本 → 命名项目(例如
HuaweiBandHRMonitor
)→ 点击 创建。 -
选择目标版本和最低版本(建议保持默认的Windows 10版本)。
Step 2: 添加界面控件(XAML文件)
文件名称和位置
-
文件:
MainPage.xaml
-
位置:项目根目录(自动生成)
-
tips: 你只需要更改
MainPage.xaml这个文件就行 不用自己建立 因为是自带的 如果没有这个文件 说明你的项目建立得不对 一定要是c#的空白应用!
-
代码:在MainPage.xaml中
更改为以下代码
<!-- MainPage.xaml -->
<Page
x:Class="HuaweiBandHRMonitor.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:HuaweiBandHRMonitor"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<StackPanel Padding="20">
<Button x:Name="StartScanButton"
Content="开始扫描设备"
Click="StartScanButton_Click"
Margin="0,10"/>
<TextBlock x:Name="DeviceStatusText"
Text="状态:等待扫描..."
Margin="0,10"/>
<TextBlock x:Name="HeartRateText"
Text="当前心率:-- BPM"
FontSize="24"
Margin="0,10"/>
</StackPanel>
</Page>
Step 3: 编写后台逻辑(C#代码)
文件名称和位置
-
文件:
MainPage.xaml.cs
(与XAML文件关联的后台代码) -
位置:项目根目录(自动生成)
代码:实现蓝牙扫描与数据监听
// MainPage.xaml.cs
using System;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.Devices.Enumeration;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace HuaweiBandHRMonitor
{
public sealed partial class MainPage : Page
{
// 定义蓝牙相关对象
private DeviceWatcher deviceWatcher;
private BluetoothLEDevice bleDevice;
private GattCharacteristic heartRateCharacteristic;
public MainPage()
{
this.InitializeComponent();
}
// 按钮点击事件:开始扫描设备
private void StartScanButton_Click(object sender, RoutedEventArgs e)
{
StartScanning();
DeviceStatusText.Text = "状态:扫描中...";
}
// 启动蓝牙设备扫描
private void StartScanning()
{
// 1. 定义过滤条件(仅BLE设备)
string aqsFilter = "(System.Devices.Aep.ProtocolId:=\"{bb7bb05e-5972-42b5-94fc-76eaa7084d49}\")";
// 2. 指定需要获取的设备属性
string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected" };
// 3. 创建设备监视器
deviceWatcher = DeviceInformation.CreateWatcher(
aqsFilter,
requestedProperties,
DeviceInformationKind.AssociationEndpoint
);
// 4. 注册设备发现事件
deviceWatcher.Added += DeviceWatcher_Added;
// 5. 启动扫描
deviceWatcher.Start();
}
// 发现设备时的回调
private async void DeviceWatcher_Added(DeviceWatcher sender, DeviceInformation deviceInfo)
{
// 筛选设备名称(根据手环实际名称调整)
if (deviceInfo.Name.Contains("HUAWEI Band 9"))//打开心率广播查看蓝牙名称 就是移动的那串名字
{
// 停止扫描
deviceWatcher.Stop();
// 通过设备ID获取蓝牙设备对象
bleDevice = await BluetoothLEDevice.FromIdAsync(deviceInfo.Id);
// 更新UI状态
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
DeviceStatusText.Text = $"已连接设备:{deviceInfo.Name}";
});
// 发现服务
await DiscoverServices();
}
}
// 发现服务
private async Task DiscoverServices()
{
// 获取所有服务
GattDeviceServicesResult result = await bleDevice.GetGattServicesAsync(BluetoothCacheMode.Uncached);
if (result.Status == GattCommunicationStatus.Success)
{
foreach (GattDeviceService service in result.Services)
{
// 查找心率服务(标准UUID:0x180D)
if (service.Uuid == GattServiceUuids.HeartRate)
{
await SubscribeToHeartRateCharacteristic(service);
}
}
}
}
// 订阅心率特征值
private async Task SubscribeToHeartRateCharacteristic(GattDeviceService service)
{
// 获取所有特征值
GattCharacteristicsResult characteristicsResult = await service.GetCharacteristicsAsync();
if (characteristicsResult.Status == GattCommunicationStatus.Success)
{
foreach (GattCharacteristic characteristic in characteristicsResult.Characteristics)
{
// 查找心率测量特征值(标准UUID:0x2A37)
if (characteristic.Uuid == GattCharacteristicUuids.HeartRateMeasurement)
{
heartRateCharacteristic = characteristic;
// 启用通知(Notify)
GattCommunicationStatus status =
await heartRateCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(
GattClientCharacteristicConfigurationDescriptorValue.Notify);
if (status == GattCommunicationStatus.Success)
{
// 注册数据变化事件
heartRateCharacteristic.ValueChanged += HeartRateCharacteristic_ValueChanged;
}
}
}
}
}
// 心率数据解析
private void HeartRateCharacteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
{
// 读取原始数据
var reader = Windows.Storage.Streams.DataReader.FromBuffer(args.CharacteristicValue);
byte[] data = new byte[reader.UnconsumedBufferLength];
reader.ReadBytes(data);
// 解析心率值
int heartRate = 0;
if (data.Length >= 2)
{
// 判断心率值占1字节还是2字节(根据协议标志位)
if ((data[0] & 0x01) == 0)
{
heartRate = data[1]; // 1字节
}
else
{
heartRate = (data[2] << 8) + data[1]; // 2字节
}
}
// 更新UI(必须在UI线程操作)
Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
HeartRateText.Text = $"当前心率:{heartRate} BPM";
});
}
}
}
Step 4: 配置权限
文件名称和位置
-
文件:
Package.appxmanifest
-
位置:项目根目录(自动生成)
操作步骤
-
双击打开
Package.appxmanifest
文件。 -
切换到 "功能" 选项卡。
-
勾选以下权限:
-
蓝牙
-
邻近感应(可选,但建议勾选)
-
Step 5: 运行与测试
硬件准备
-
确保电脑支持蓝牙4.0及以上。
-
打开华为手环9的 心率广播 功能:
-
进入手环设置 → 健康监测 → 开启心率广播。
-
调试步骤
-
在Visual Studio中按 F5 启动调试。
-
点击应用中的 "开始扫描设备" 按钮。
-
如果成功连接,界面会显示 "已连接设备:HUAWEI Band 9"。
-
手环实时心率会显示在下方文本框中。
常见问题解决
-
设备无法发现:
-
检查手环是否开启广播模式。
-
确保电脑蓝牙已开启并配对过手环。
-
-
权限错误:
-
确认
Package.appxmanifest
中已启用蓝牙权限。
-
-
数据解析错误:
-
在
HeartRateCharacteristic_ValueChanged
方法中添加断点,检查data
数组的原始值。
-
项目结构总结
复制
HuaweiBandHRMonitor/ ├── Package.appxmanifest # 应用配置和权限 ├── MainPage.xaml # 界面设计 ├── MainPage.xaml.cs # 后台逻辑 └── Properties/ # 项目属性(无需修改)
运行以后就能看见自己的心率啦: