heart_rate.dart 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. import 'dart:async';
  2. import 'dart:convert';
  3. import 'package:fis_common/logger/logger.dart';
  4. import 'package:flutter/material.dart';
  5. import 'package:get/get.dart';
  6. import 'package:vitalapp/architecture/app_parameters.dart';
  7. import 'package:vitalapp/global.dart';
  8. import 'package:vitalapp/managers/device_controller_manager.dart';
  9. import 'package:vitalapp/managers/interfaces/data_convert.dart';
  10. import 'package:vitalapp/managers/interfaces/models/device.dart';
  11. import 'package:vitalapp/pages/medical/widgets/exam_card.dart';
  12. import 'package:vitalapp/pages/medical/controller.dart';
  13. import 'package:vitalapp/pages/medical/models/worker.dart';
  14. import 'package:vitalapp/pages/medical/widgets/device_status.dart';
  15. import 'package:vitalapp/pages/medical/widgets/device_status_position.dart';
  16. import 'package:vitalapp/pages/medical/widgets/ecg_view/index.dart';
  17. import 'package:vitalapp/pages/medical/widgets/side_bar.dart';
  18. import 'package:vnote_device_plugin/consts/types.dart';
  19. import 'package:vnote_device_plugin/devices/heart.dart';
  20. import 'package:vnote_device_plugin/models/exams/heart.dart';
  21. import 'package:http/http.dart' as http;
  22. class HeartRate extends StatefulWidget {
  23. const HeartRate({
  24. super.key,
  25. });
  26. @override
  27. State<HeartRate> createState() => _HeartRateState();
  28. }
  29. class _HeartRateState extends State<HeartRate> {
  30. bool get isPureSoftwareMode => AppParameters.data.isPureSoftwareMode;
  31. final MedicalController medicalController = Get.find<MedicalController>();
  32. final IDataConvertManager dataConvertManager =
  33. Get.find<IDataConvertManager>();
  34. DeviceControllerManager? heart;
  35. late HeartDeviceWorker worker;
  36. WorkerStatus connectStatus = WorkerStatus.connecting;
  37. List<int> ecgPoint = [];
  38. int errorCount = 0;
  39. bool isConnectFail = false;
  40. late String _heart =
  41. medicalController.diagnosisDataValue['Heart']?['HEART']?.toString() ?? '';
  42. late String _assess =
  43. medicalController.diagnosisDataValue['Heart']?['ASSESS'] ?? '';
  44. late final heartRate =
  45. medicalController.diagnosisDataValue['Heart']?['HEART'] ?? 0;
  46. /// 是否显示重试按钮
  47. bool showResetButton = false;
  48. /// 初始时的心电初始数据
  49. List<int>? initEcgData;
  50. String _deviceError = '';
  51. @override
  52. Widget build(BuildContext context) {
  53. return Stack(
  54. children: [
  55. ExamCard(
  56. titleText: const SizedBox(),
  57. // bottomPadding: 10,
  58. content: Column(
  59. mainAxisAlignment: MainAxisAlignment.start,
  60. children: [
  61. Row(
  62. mainAxisAlignment: MainAxisAlignment.end,
  63. children: [
  64. const SideBar(
  65. title: '心率',
  66. value: '',
  67. unit: '',
  68. ),
  69. const Expanded(child: SizedBox()),
  70. Text(
  71. _heart.isEmpty ? '--' : _heart,
  72. style: const TextStyle(
  73. fontSize: 60,
  74. color: Colors.black,
  75. ),
  76. ),
  77. const Text(
  78. " bpm",
  79. style: TextStyle(fontSize: 25),
  80. ),
  81. const SizedBox(
  82. width: 15,
  83. )
  84. ],
  85. ),
  86. if (_deviceError.isNotEmpty)
  87. Row(
  88. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  89. crossAxisAlignment: CrossAxisAlignment.start,
  90. children: [
  91. Container(
  92. padding: const EdgeInsets.symmetric(
  93. horizontal: 30,
  94. ),
  95. child: const Text(
  96. '心率测量出错',
  97. style: TextStyle(
  98. fontSize: 25,
  99. ),
  100. ),
  101. ),
  102. Container(
  103. padding: const EdgeInsets.symmetric(
  104. horizontal: 50,
  105. ),
  106. child: Text(
  107. _deviceError,
  108. style: const TextStyle(
  109. fontSize: 24,
  110. ),
  111. ),
  112. ),
  113. ],
  114. ),
  115. if (_assess.isNotEmpty)
  116. Row(
  117. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  118. crossAxisAlignment: CrossAxisAlignment.start,
  119. children: [
  120. Container(
  121. padding: const EdgeInsets.symmetric(
  122. horizontal: 30,
  123. ),
  124. child: const Text(
  125. '心率评估',
  126. style: TextStyle(
  127. fontSize: 25,
  128. ),
  129. ),
  130. ),
  131. Container(
  132. padding: const EdgeInsets.only(
  133. right: 15,
  134. ),
  135. child: Text(
  136. dataConvertManager.heartRateConversion(
  137. int.parse(heartRate.toString())),
  138. style: const TextStyle(
  139. fontSize: 24,
  140. fontWeight: FontWeight.bold,
  141. ),
  142. ),
  143. ),
  144. ],
  145. ),
  146. const SizedBox(
  147. height: 10,
  148. ),
  149. SizedBox(
  150. height: 240,
  151. child: LayoutBuilder(builder: (context, constraints) {
  152. if (initEcgData == null) {
  153. return Container();
  154. } else {
  155. return EcgView(
  156. width: constraints.maxWidth,
  157. height: constraints.maxHeight,
  158. initData: initEcgData!,
  159. );
  160. }
  161. }),
  162. ),
  163. Container(
  164. // !! 这一层 Container 不能删 ,否则会引发 EcgView 的 controller 被异常删除
  165. child: _buildResetButton(),
  166. ),
  167. ],
  168. ),
  169. ),
  170. if (!isPureSoftwareMode) ...[
  171. if (!isConnectFail)
  172. DeviceStatusPosition(
  173. deviceStatus: DeviceStatus(connectStatus: connectStatus),
  174. )
  175. else
  176. _buildErrorButton(),
  177. ],
  178. ],
  179. );
  180. }
  181. // Widget _buildDebugButton() {
  182. // return Container(
  183. // child: Row(
  184. // children: [
  185. // const Text(
  186. // '测试============?',
  187. // style: TextStyle(color: Colors.grey, fontSize: 24),
  188. // ),
  189. // TextButton(
  190. // onPressed: () {
  191. // debugTest();
  192. // },
  193. // child: const Text(
  194. // '重试',
  195. // style: TextStyle(color: Colors.blue, fontSize: 24),
  196. // ),
  197. // ),
  198. // ],
  199. // ),
  200. // );
  201. // }
  202. Widget _buildResetButton() {
  203. if (!showResetButton) {
  204. return const SizedBox(
  205. height: 48,
  206. );
  207. }
  208. return Container(
  209. padding: const EdgeInsets.only(left: 30),
  210. child: Row(
  211. children: const [
  212. Text(
  213. '时长不足30S',
  214. style: TextStyle(color: Colors.grey, fontSize: 24),
  215. ),
  216. // TextButton(
  217. // onPressed: () {
  218. // ecgPoint = [];
  219. // resetEcgView();
  220. // setEcgData();
  221. // setState(() {
  222. // showResetButton = false;
  223. // });
  224. // },
  225. // child: const Text(
  226. // '重试',
  227. // style: TextStyle(color: Colors.blue, fontSize: 24),
  228. // ),
  229. // ),
  230. ],
  231. ),
  232. );
  233. }
  234. // 设备初始化
  235. Future<void> initDevice() async {
  236. DeviceModel? device = await medicalController.getDevice(DeviceTypes.HEART);
  237. if (device == null) {
  238. connectStatus = WorkerStatus.unboundDevice;
  239. setState(() {});
  240. return;
  241. }
  242. heart =
  243. DeviceControllerManager(DeviceTypes.HEART, device.model, device.mac);
  244. worker = heart!.worker as HeartDeviceWorker;
  245. connectStatus = heart!.connectStatus;
  246. loadListeners();
  247. connect();
  248. }
  249. /// 尝试重连
  250. Future<void> tryReconnect() async {
  251. await disconnect();
  252. await connect();
  253. }
  254. Future<void> disconnect() async {
  255. await worker.disconnect();
  256. }
  257. Future<void> connect() async {
  258. await worker.connect();
  259. }
  260. @override
  261. void dispose() {
  262. heart?.dispose();
  263. heart = null;
  264. releaseListeners();
  265. disconnect();
  266. worker.dispose();
  267. super.dispose();
  268. }
  269. /// 重置数据以及心电图
  270. void resetEcgView() {
  271. try {
  272. EcgViewController ecgViewController = Get.find<EcgViewController>();
  273. ecgPoint = [];
  274. ecgViewController.reset();
  275. } catch (e) {
  276. logger.i('心率图测量失败:$e');
  277. }
  278. }
  279. /// 数据初始化
  280. Future<void> initData() async {
  281. // medicalController.readCachedRecord();
  282. if (medicalController.diagnosisDataValue['Heart'] == null) {
  283. medicalController.diagnosisDataValue['Heart'] = {};
  284. }
  285. if (medicalController.diagnosisDataValue['Heart']?['ECG_POINT'] != null) {
  286. String pointInfo =
  287. medicalController.diagnosisDataValue['Heart']?['ECG_POINT'] ?? '';
  288. if ((pointInfo.toString().startsWith('https://') ||
  289. pointInfo.toString().startsWith('http://')) &&
  290. kIsOnline) {
  291. final response = await http.get(Uri.parse(pointInfo));
  292. pointInfo = response.body;
  293. }
  294. initEcgData = jsonDecode(pointInfo).cast<int>();
  295. if (initEcgData != null &&
  296. initEcgData!.isNotEmpty &&
  297. initEcgData!.length < 125 * 30) {
  298. // print("数据不完整 ⭐⭐⭐⭐⭐⭐⭐");
  299. showResetButton = true;
  300. }
  301. } else {
  302. initEcgData = [];
  303. }
  304. setState(() {});
  305. }
  306. Future<void> initHeart() async {
  307. await initDevice();
  308. await initData();
  309. }
  310. @override
  311. void initState() {
  312. initHeart();
  313. super.initState();
  314. }
  315. void loadListeners() {
  316. worker.connectErrorEvent.addListener(_onConnectFail);
  317. worker.connectedEvent.addListener(_onConnectSuccess);
  318. worker.disconnectedEvent.addListener(_onDisconnected);
  319. worker.hrValueUpdateEvent.addListener(_onHrValueUpdate);
  320. worker.ecgValueUpdateEvent.addListener(_onEcgValueUpdate);
  321. worker.resultReceivedEvent.addListener(_onRCesultReceived);
  322. worker.errorEvent.addListener(_onError);
  323. }
  324. void releaseListeners() {
  325. worker.connectErrorEvent.removeListener(_onConnectFail);
  326. worker.connectedEvent.removeListener(_onConnectSuccess);
  327. worker.disconnectedEvent.removeListener(_onDisconnected);
  328. worker.hrValueUpdateEvent.removeListener(_onHrValueUpdate);
  329. worker.ecgValueUpdateEvent.removeListener(_onEcgValueUpdate);
  330. worker.resultReceivedEvent.removeListener(_onRCesultReceived);
  331. worker.errorEvent.removeListener(_onError);
  332. }
  333. /// 需要封装一下
  334. Widget _buildErrorButton() {
  335. return DeviceStatusPosition(
  336. deviceStatus: Row(
  337. children: [
  338. const Text(
  339. '请确认设备是否启动',
  340. style: TextStyle(fontSize: 24, color: Colors.red),
  341. ),
  342. IconButton(
  343. onPressed: () {
  344. tryReconnect();
  345. setState(() {
  346. connectStatus = WorkerStatus.connecting;
  347. isConnectFail = false;
  348. });
  349. },
  350. icon: const Icon(Icons.refresh),
  351. iconSize: 32,
  352. ),
  353. ],
  354. ),
  355. );
  356. }
  357. void _onConnectFail(sender, e) async {
  358. logger.i("设备连接失败:${worker.mac}");
  359. if (errorCount < 3) {
  360. errorCount++;
  361. await tryReconnect();
  362. } else {
  363. isConnectFail = true;
  364. }
  365. connectStatus = WorkerStatus.connectionFailed;
  366. setState(() {});
  367. }
  368. void _onConnectSuccess(sender, e) {
  369. logger.e('_HeartRateState ${worker.mac}, 设备连接成功');
  370. isConnectFail = false;
  371. errorCount = 0;
  372. connectStatus = WorkerStatus.connected;
  373. setState(() {});
  374. }
  375. /// 设备连接中断
  376. void _onDisconnected(sender, e) async {
  377. print('设备连接中断');
  378. logger.i("设备连接中断:${worker.mac}");
  379. await tryReconnect();
  380. errorCount = 0;
  381. connectStatus = WorkerStatus.disconnected;
  382. setState(() {});
  383. }
  384. // 心电图数据更新
  385. void _onEcgValueUpdate(_, List<int> e) {
  386. try {
  387. EcgViewController ecgViewController = Get.find<EcgViewController>();
  388. ecgPoint.addAll(e);
  389. if (ecgPoint.length > 125 * 3) {
  390. // 3s 后开始塞数据
  391. ecgViewController.addData(e);
  392. }
  393. } catch (e) {
  394. print(e);
  395. }
  396. }
  397. /// 更新心率
  398. void _onHrValueUpdate(_, int e) {
  399. if (_deviceError.isNotEmpty || _assess.isNotEmpty) {
  400. // 如果上次因错误而停止了,这里需要先重置
  401. _deviceError = '';
  402. _assess = '';
  403. resetEcgView();
  404. }
  405. setState(() {
  406. _heart = e.toString();
  407. showResetButton = false;
  408. });
  409. }
  410. void _onError(_, String e) {
  411. logger.i('心率更新失败:$e');
  412. _deviceError = e;
  413. resetEcgView();
  414. setState(() {});
  415. }
  416. /// 接收到最终结果
  417. void _onRCesultReceived(_, HeartExamResult e) async {
  418. logger.i('心率更新接收结果:${e.heartRate}');
  419. // print(ecgPoint.toString());
  420. // _heart = e.toString();
  421. _assess = e.analysis.first;
  422. _heart = e.heartRate.toString();
  423. medicalController.diagnosisDataValue['Heart']?['HEART'] =
  424. e.heartRate.toString();
  425. medicalController.diagnosisDataValue['Heart']?['ASSESS'] =
  426. dataConvertManager.heartRateConversion(int.parse(heartRate));
  427. await setEcgData();
  428. medicalController.saveCachedRecord();
  429. /// 判断数据是否完整
  430. if (ecgPoint.isNotEmpty && ecgPoint.length < 125 * 30) {
  431. // print("数据不完整 ⭐⭐⭐⭐⭐⭐⭐");
  432. showResetButton = true;
  433. }
  434. /// FIXME 解除下方注释
  435. // try {
  436. // medicalController.saveCachedRecord();
  437. // } catch (e) {
  438. // print(e);
  439. // }
  440. // print(medicalController.diagnosisDataValue);
  441. setState(() {});
  442. }
  443. /// 设置最终数据
  444. Future<void> setEcgData() async {
  445. EcgViewController ecgViewController = Get.find<EcgViewController>();
  446. medicalController.diagnosisDataValue['Heart']?['ECG'] =
  447. await ecgViewController.getFullDataImageBase64();
  448. medicalController.diagnosisDataValue['Heart']?['ECG_POINT'] =
  449. jsonEncode(ecgViewController.allPoints);
  450. }
  451. }