heart_rate.dart 14 KB

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