当前位置: 首页 > wzjs >正文

网站后台发布文章横琴网站建设公司

网站后台发布文章,横琴网站建设公司,太原 网站建设公司,仿站下载工具一、项目背景 你有一个Python脚本PolarHR.py,使用bleak库异步扫描并连接蓝牙心率设备,后台线程持续获取心率数据,并每2秒打印最新心率。 你希望在WPF程序中启动该Python脚本,实时获取心率数据并显示。 二、Python脚本&#xff0…

一、项目背景

你有一个Python脚本PolarHR.py,使用bleak库异步扫描并连接蓝牙心率设备,后台线程持续获取心率数据,并每2秒打印最新心率。

你希望在WPF程序中启动该Python脚本,实时获取心率数据并显示。

在这里插入图片描述


二、Python脚本(PolarHR.py)

请确保Python脚本内容如下,重点是:

  • 使用print(..., flush=True)确保输出不被缓冲,WPF能及时读取。
  • 每2秒打印格式为当前心率: 数字的字符串,方便WPF解析。
import asyncio
import threading
from bleak import BleakScanner, BleakClient
import timeHR_UUID = "00002a37-0000-1000-8000-00805f9b34fb"
_latest_heart_rate = None
_lock = threading.Lock()async def _heart_rate_worker():global _latest_heart_rateprint("开始扫描设备...", flush=True)devices = await BleakScanner.discover(timeout=5)print(f"扫描到设备数量: {len(devices)}", flush=True)polar_devices = [d for d in devices if d.name and "Polar" in d.name]print(f"找到 Polar 设备数量: {len(polar_devices)}", flush=True)if not polar_devices:print("未找到 Polar 设备", flush=True)returndevice = polar_devices[0]async with BleakClient(device.address) as client:queue = asyncio.Queue()def callback(sender, data):flags = data[0]hr_format = flags & 0x01if hr_format:hr = int.from_bytes(data[1:3], byteorder='little')else:hr = data[1]queue.put_nowait(hr)await client.start_notify(HR_UUID, callback)print(f"已连接设备 {device.name},开始接收心率数据...", flush=True)while True:hr = await queue.get()with _lock:_latest_heart_rate = hrdef _start_loop(loop):asyncio.set_event_loop(loop)loop.run_until_complete(_heart_rate_worker())def start_heart_rate_monitor():loop = asyncio.new_event_loop()t = threading.Thread(target=_start_loop, args=(loop,), daemon=True)t.start()def get_latest_heart_rate():with _lock:return _latest_heart_rateif __name__ == "__main__":start_heart_rate_monitor()while True:hr = get_latest_heart_rate()if hr is not None:print(f"当前心率: {hr}", flush=True)else:print("当前心率: None", flush=True)time.sleep(2)

三、WPF项目代码示例

1. MainWindow.xaml

<Window x:Class="HeartRateWpfApp.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"Title="心率监测" Height="200" Width="300"><Grid><TextBlock x:Name="HeartRateTextBlock" FontSize="24" HorizontalAlignment="Center" VerticalAlignment="Center"/></Grid>
</Window>

2. MainWindow.xaml.cs

using System;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Threading;namespace HeartRateWpfApp
{public partial class MainWindow : Window{private Process _pythonProcess;private string _latestHeartRate = null;private DispatcherTimer _timer;public MainWindow(){InitializeComponent();StartPythonProcess();StartTimer();}private void StartPythonProcess(){var psi = new ProcessStartInfo{FileName = @"C:\Path\To\Your\Python\python.exe",  // 替换为你的python.exe完整路径Arguments = "-u PolarHR.py",  // -u 禁用缓冲,PolarHR.py是脚本名WorkingDirectory = @"C:\Users\86730\Desktop\步态资料\步态资料", // 脚本所在目录UseShellExecute = false,RedirectStandardOutput = true,RedirectStandardError = true,CreateNoWindow = true};_pythonProcess = new Process();_pythonProcess.StartInfo = psi;_pythonProcess.OutputDataReceived += PythonOutputDataReceived;_pythonProcess.ErrorDataReceived += PythonErrorDataReceived;_pythonProcess.Start();_pythonProcess.BeginOutputReadLine();_pythonProcess.BeginErrorReadLine();}private void PythonOutputDataReceived(object sender, DataReceivedEventArgs e){if (string.IsNullOrEmpty(e.Data)) return;// 调试输出,方便查看Python打印内容Console.WriteLine("Python STDOUT: " + e.Data);// 匹配格式:当前心率: 数字var match = Regex.Match(e.Data, @"当前心率:\s*(\d+)");if (match.Success){_latestHeartRate = match.Groups[1].Value;}}private void PythonErrorDataReceived(object sender, DataReceivedEventArgs e){if (!string.IsNullOrEmpty(e.Data)){Console.WriteLine("Python STDERR: " + e.Data);}}private void StartTimer(){_timer = new DispatcherTimer();_timer.Interval = TimeSpan.FromSeconds(2);_timer.Tick += Timer_Tick;_timer.Start();}private void Timer_Tick(object sender, EventArgs e){if (string.IsNullOrEmpty(_latestHeartRate)){HeartRateTextBlock.Text = "等待心率数据...";}else{HeartRateTextBlock.Text = $"当前心率: {_latestHeartRate}";}}protected override void OnClosed(EventArgs e){base.OnClosed(e);if (_pythonProcess != null && !_pythonProcess.HasExited){_pythonProcess.Kill();_pythonProcess.Dispose();}}}
}

四、注意事项

  1. 替换Python路径
    FileName中的路径替换为你本机Python解释器的完整路径,例如:

    C:\Users\86730\AppData\Local\Programs\Python\Python310\python.exe
    
  2. 确保Python环境安装依赖
    确保bleak库已安装:

    C:\Path\To\Your\Python\python.exe -m pip install bleak
    
  3. 确保Python脚本路径正确
    WorkingDirectory设置为Python脚本所在目录,Arguments只写脚本名。

  4. 调试输出
    运行WPF程序时,查看输出窗口(Console)是否有Python的标准输出和错误输出,确认Python脚本是否正常启动。

  5. 蓝牙权限
    确保WPF程序有权限访问蓝牙设备,必要时以管理员身份运行。


五、总结

  • Python脚本后台线程持续采集心率数据,主线程每2秒打印格式为当前心率: 数字的字符串。
  • WPF启动Python进程,异步读取标准输出,使用正则表达式匹配并提取数字心率。
  • WPF用DispatcherTimer每2秒刷新UI显示最新心率。

文章转载自:

http://cS9in1jJ.fwbhL.cn
http://CKsp1iXi.fwbhL.cn
http://LunZBf2b.fwbhL.cn
http://JL2ZiJU4.fwbhL.cn
http://WQF0Xkgh.fwbhL.cn
http://2pQIOqAB.fwbhL.cn
http://vAMImFPi.fwbhL.cn
http://Qc542q0q.fwbhL.cn
http://YjecmBDw.fwbhL.cn
http://RYV3I7kF.fwbhL.cn
http://K42hj9dO.fwbhL.cn
http://KFWsjREb.fwbhL.cn
http://PutnzWwS.fwbhL.cn
http://WTXkPtK2.fwbhL.cn
http://Bq4bNfsx.fwbhL.cn
http://fGt0Ihjg.fwbhL.cn
http://Dl7wfc81.fwbhL.cn
http://cBoknNud.fwbhL.cn
http://dQZLHMCD.fwbhL.cn
http://wC5u6A4z.fwbhL.cn
http://jjrpS2nP.fwbhL.cn
http://y7joYQvc.fwbhL.cn
http://r98rq5k3.fwbhL.cn
http://Q5SoCf2T.fwbhL.cn
http://J8D8NgC3.fwbhL.cn
http://qqWloxbM.fwbhL.cn
http://7sLiG4au.fwbhL.cn
http://SGC0nGYW.fwbhL.cn
http://T1vvOXGw.fwbhL.cn
http://0eJezfu0.fwbhL.cn
http://www.dtcms.com/wzjs/733656.html

相关文章:

  • 番禺建网站免费代理网址
  • 网站不备案可以么广州网站建设报价单
  • 沈阳网站页面设计公司建站赚钱灰色
  • 怎么使网站降权肇庆市场核酸检测
  • 中国制造网官方网站国际站wordpress 密码解密
  • 网站开发是做什么google seo实战教程
  • 大型电子商务网站建设试述网站建设应考虑哪些方面的问题
  • 企业的建站方式中国机械工业建设集团有限公司网站
  • 网站短信通知wordpress将404跳转主页
  • 医院网站建设价格ftp怎么上传网站
  • 架设网站 自己购买服务器网站建设成本图
  • 旅游网站规划设计自己想学做博客网站吗
  • 东莞网站建设部落上海线上引流推广
  • 网站seo具体怎么做?网盘建网站
  • 网站后台密码忘了怎么办网络开发语言的有哪些
  • 自己做的网站图片加载过慢建设银行的官方网站公告
  • 青龙建站教程自学网北京网站建设itcask
  • 北京网站建设推广服wordpress滑块教程
  • 名师工作室网站建设现状调查深圳龙岗是不是很落后
  • 电力建设期刊网站经常维护吗quark搜索引擎入口
  • 茂名网站建设方案开发百度24小时人工电话
  • 台州网站建设哪家便宜wordpress post提交表单
  • 住房与城乡建设部网站打不开网站做多个语言有什么好处
  • 淘宝网站短链接怎么做个人备案网站做盈利合法吗
  • 个人网站建设目标广告设计制作服务方案
  • 深圳市网站建设制作设计平台常州做网站优化
  • 工业风 网站建设聊城专业网站建设公司电话
  • 网站文章怎么更新android开发环境搭建
  • 镇江市城市建设投资公司官方网站中国能建设计公司网站
  • 做网站 徐州wordpress 功能开发教程