heart_rate.dart 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  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/medical/widgets/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. 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. DeviceModel? device = await medicalController.getDevice(DeviceTypes.HEART);
  233. if (device == null) {
  234. connectStatus = WorkerStatus.unboundDevice;
  235. setState(() {});
  236. return;
  237. }
  238. heart =
  239. DeviceControllerManager(DeviceTypes.HEART, device.model, device.mac);
  240. worker = heart!.worker as HeartDeviceWorker;
  241. connectStatus = heart!.connectStatus;
  242. loadListeners();
  243. connect();
  244. }
  245. /// 尝试重连
  246. Future<void> tryReconnect() async {
  247. await disconnect();
  248. await connect();
  249. }
  250. Future<void> disconnect() async {
  251. await worker.disconnect();
  252. }
  253. Future<void> connect() async {
  254. await worker.connect();
  255. }
  256. @override
  257. void dispose() {
  258. heart?.dispose();
  259. heart = null;
  260. releaseListeners();
  261. disconnect();
  262. worker.dispose();
  263. super.dispose();
  264. }
  265. /// 重置数据以及心电图
  266. void resetEcgView() {
  267. try {
  268. EcgViewController ecgViewController = Get.find<EcgViewController>();
  269. ecgPoint = [];
  270. ecgViewController.reset();
  271. } catch (e) {
  272. logger.i('心率图测量失败:$e');
  273. }
  274. }
  275. /// 数据初始化
  276. Future<void> initData() async {
  277. // medicalController.readCachedRecord();
  278. if (medicalController.diagnosisDataValue['Heart'] == null) {
  279. medicalController.diagnosisDataValue['Heart'] = {};
  280. }
  281. if (medicalController.diagnosisDataValue['Heart']?['ECG_POINT'] != null) {
  282. String pointInfo =
  283. medicalController.diagnosisDataValue['Heart']?['ECG_POINT'] ?? '';
  284. if ((pointInfo.toString().startsWith('https://') ||
  285. pointInfo.toString().startsWith('http://')) &&
  286. kIsOnline) {
  287. final response = await http.get(Uri.parse(pointInfo));
  288. pointInfo = response.body;
  289. }
  290. initEcgData = jsonDecode(pointInfo).cast<int>();
  291. if (initEcgData != null &&
  292. initEcgData!.isNotEmpty &&
  293. initEcgData!.length < 125 * 30) {
  294. // print("数据不完整 ⭐⭐⭐⭐⭐⭐⭐");
  295. showResetButton = true;
  296. }
  297. } else {
  298. initEcgData = [];
  299. }
  300. setState(() {});
  301. }
  302. Future<void> initHeart() async {
  303. await initDevice();
  304. await initData();
  305. }
  306. @override
  307. void initState() {
  308. initHeart();
  309. super.initState();
  310. }
  311. void loadListeners() {
  312. worker.connectErrorEvent.addListener(_onConnectFail);
  313. worker.connectedEvent.addListener(_onConnectSuccess);
  314. worker.disconnectedEvent.addListener(_onDisconnected);
  315. worker.hrValueUpdateEvent.addListener(_onHrValueUpdate);
  316. worker.ecgValueUpdateEvent.addListener(_onEcgValueUpdate);
  317. worker.resultReceivedEvent.addListener(_onRCesultReceived);
  318. worker.errorEvent.addListener(_onError);
  319. }
  320. void releaseListeners() {
  321. worker.connectErrorEvent.removeListener(_onConnectFail);
  322. worker.connectedEvent.removeListener(_onConnectSuccess);
  323. worker.disconnectedEvent.removeListener(_onDisconnected);
  324. worker.hrValueUpdateEvent.removeListener(_onHrValueUpdate);
  325. worker.ecgValueUpdateEvent.removeListener(_onEcgValueUpdate);
  326. worker.resultReceivedEvent.removeListener(_onRCesultReceived);
  327. worker.errorEvent.removeListener(_onError);
  328. }
  329. /// 需要封装一下
  330. Widget _buildErrorButton() {
  331. return DeviceStatusPosition(
  332. deviceStatus: Row(
  333. children: [
  334. const Text(
  335. '请确认设备是否启动',
  336. style: TextStyle(fontSize: 24, color: Colors.red),
  337. ),
  338. IconButton(
  339. onPressed: () {
  340. tryReconnect();
  341. setState(() {
  342. connectStatus = WorkerStatus.connecting;
  343. isConnectFail = false;
  344. });
  345. },
  346. icon: const Icon(Icons.refresh),
  347. iconSize: 32,
  348. ),
  349. ],
  350. ),
  351. );
  352. }
  353. void _onConnectFail(sender, e) async {
  354. logger.i("设备连接失败:${worker.mac}");
  355. if (errorCount < 3) {
  356. errorCount++;
  357. await tryReconnect();
  358. } else {
  359. isConnectFail = true;
  360. }
  361. connectStatus = WorkerStatus.connectionFailed;
  362. setState(() {});
  363. }
  364. void _onConnectSuccess(sender, e) {
  365. logger.e('_HeartRateState ${worker.mac}, 设备连接成功');
  366. isConnectFail = false;
  367. errorCount = 0;
  368. connectStatus = WorkerStatus.connected;
  369. setState(() {});
  370. }
  371. /// 设备连接中断
  372. void _onDisconnected(sender, e) async {
  373. print('设备连接中断');
  374. logger.i("设备连接中断:${worker.mac}");
  375. await tryReconnect();
  376. errorCount = 0;
  377. connectStatus = WorkerStatus.disconnected;
  378. setState(() {});
  379. }
  380. // 心电图数据更新
  381. void _onEcgValueUpdate(_, List<int> e) {
  382. try {
  383. EcgViewController ecgViewController = Get.find<EcgViewController>();
  384. ecgPoint.addAll(e);
  385. if (ecgPoint.length > 125 * 3) {
  386. // 3s 后开始塞数据
  387. ecgViewController.addData(e);
  388. }
  389. } catch (e) {
  390. print(e);
  391. }
  392. }
  393. /// 更新心率
  394. void _onHrValueUpdate(_, int e) {
  395. if (_deviceError.isNotEmpty || _assess.isNotEmpty) {
  396. // 如果上次因错误而停止了,这里需要先重置
  397. _deviceError = '';
  398. _assess = '';
  399. resetEcgView();
  400. }
  401. setState(() {
  402. _heart = e.toString();
  403. showResetButton = false;
  404. });
  405. }
  406. void _onError(_, String e) {
  407. logger.i('心率更新失败:$e');
  408. _deviceError = e;
  409. resetEcgView();
  410. setState(() {});
  411. }
  412. /// 接收到最终结果
  413. void _onRCesultReceived(_, HeartExamResult e) async {
  414. logger.i('心率更新接收结果:${e.heartRate}');
  415. // print(ecgPoint.toString());
  416. // _heart = e.toString();
  417. _assess = e.analysis.first;
  418. _heart = e.heartRate.toString();
  419. medicalController.diagnosisDataValue['Heart']?['HEART'] =
  420. e.heartRate.toString();
  421. medicalController.diagnosisDataValue['Heart']?['ASSESS'] =
  422. dataConvertManager.heartRateConversion(int.parse(heartRate));
  423. await setEcgData();
  424. medicalController.saveCachedRecord();
  425. /// 判断数据是否完整
  426. if (ecgPoint.isNotEmpty && ecgPoint.length < 125 * 30) {
  427. // print("数据不完整 ⭐⭐⭐⭐⭐⭐⭐");
  428. showResetButton = true;
  429. }
  430. /// FIXME 解除下方注释
  431. // try {
  432. // medicalController.saveCachedRecord();
  433. // } catch (e) {
  434. // print(e);
  435. // }
  436. // print(medicalController.diagnosisDataValue);
  437. setState(() {});
  438. }
  439. /// 设置最终数据
  440. Future<void> setEcgData() async {
  441. EcgViewController ecgViewController = Get.find<EcgViewController>();
  442. medicalController.diagnosisDataValue['Heart']?['ECG'] =
  443. await ecgViewController.getFullDataImageBase64();
  444. medicalController.diagnosisDataValue['Heart']?['ECG_POINT'] =
  445. jsonEncode(ecgViewController.allPoints);
  446. }
  447. }