bluetooth.dart 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876
  1. import 'dart:async';
  2. import 'dart:convert';
  3. import 'dart:core';
  4. import 'dart:io';
  5. import 'dart:math';
  6. import 'dart:typed_data';
  7. import 'package:broadcast/broadcast.dart';
  8. import 'package:buffer/buffer.dart';
  9. import 'package:device_info/device_info.dart';
  10. import 'package:flutter/material.dart';
  11. import 'package:flutter_reactive_ble/flutter_reactive_ble.dart';
  12. import 'package:get_it/get_it.dart';
  13. import 'package:package_info/package_info.dart';
  14. import 'package:path_provider/path_provider.dart';
  15. import 'package:shared_preferences/shared_preferences.dart';
  16. import 'package:sport/application.dart';
  17. import 'package:sport/bean/hardware.dart';
  18. import 'package:sport/db/bluetooth_db.dart';
  19. import 'package:sport/db/step_db.dart';
  20. import 'package:sport/game/sdk_parse.dart';
  21. import 'package:sport/pages/my/dfu_update_page.dart';
  22. import 'package:sport/pages/web/game_log.dart';
  23. import 'package:sport/services/Converter.dart';
  24. import 'package:sport/services/api/inject_api.dart';
  25. import 'package:sport/services/api/rest_client.dart';
  26. import 'package:sport/utils/toast.dart';
  27. import 'package:sport/utils/version.dart';
  28. import 'package:sport/widgets/dialog/alert_dialog.dart';
  29. const BLE_CODE_0 = 0x00;
  30. const BLE_CODE_1 = 0x01;
  31. class BLE {
  32. BLE._();
  33. static const BLE_Client_T_MOTION = 0x04;
  34. static const BLE_Client_T_UPDATE = 0xA1;
  35. static const BLE_Client_T_GAMEMODE = 0xA2;
  36. static const BLE_Client_T_CONNET_R = 0xA3;
  37. static const BLE_Client_T_SHOCK = 0xA4;
  38. static const BLE_Client_T_REALTIMESTEP = 0xA5;
  39. static const BLE_Client_T_DFU = 0xA6;
  40. static const BLE_Client_T_CHARGE = 0xA7;
  41. static const BLE_Client_T_LIGHTING = 0xAC;
  42. static const BLE_Client_T_ERR = 0xAD;
  43. static const BLE_Client_T_CONNECT_CONFIRM = 0xB0;
  44. }
  45. class BLE_UPDATE {
  46. BLE_UPDATE._();
  47. static const BASIC = 0x00;
  48. static const DATA = 0x01;
  49. static const STEP = 0x02;
  50. static const STEP_DELETE = 0x03;
  51. }
  52. const BLE_UUID = "6e400001-b5a3-f393-e0a9-e50e24dcca9e";
  53. class Bluetooth with InjectApi, GameLog {
  54. static final String PREF_KEY = "SHOES";
  55. static final String PREF_KEY_NAME = "SHOES_NAME";
  56. factory Bluetooth() => _getInstance();
  57. static Bluetooth? _instance;
  58. // 获取对象
  59. static Bluetooth _getInstance() {
  60. if (_instance == null) {
  61. // 使用私有的构造方法来创建对象
  62. _instance = Bluetooth._internal();
  63. }
  64. return _instance!;
  65. }
  66. Bluetooth._internal() {
  67. //初始化(设置一些默认的)...
  68. }
  69. final List<StreamSubscription<dynamic>> _streamSubscriptions = <StreamSubscription<dynamic>>[];
  70. void addSubscription(StreamSubscription<dynamic> streamSubscription) {
  71. _streamSubscriptions.add(streamSubscription);
  72. }
  73. disposeSubscription() async {
  74. timerConnected?.cancel();
  75. characteristicWrite = null;
  76. characteristicNotify = null;
  77. if(_streamSubscriptions.isNotEmpty) {
  78. try {
  79. for (StreamSubscription<dynamic> subscription in _streamSubscriptions) {
  80. await subscription.cancel();
  81. }
  82. } catch (e) {
  83. print(e);
  84. }
  85. }
  86. _streamSubscriptions.clear();
  87. }
  88. // ignore: close_sinks
  89. final StreamController<bool> _queryController = StreamController.broadcast();
  90. Stream<bool> get queryStream => _queryController.stream;
  91. // ignore: close_sinks
  92. final StreamController<Uint8List> _dataController = StreamController.broadcast();
  93. Stream<Uint8List> get dataStream => _dataController.stream;
  94. // ignore: close_sinks
  95. final StreamController<int> _connectRightController = StreamController.broadcast();
  96. Stream<int> get connectRightStream => _connectRightController.stream;
  97. // ignore: close_sinks
  98. final StreamController<bool> _dfuController = StreamController.broadcast();
  99. Stream<bool> get dfuStream => _dfuController.stream;
  100. // ignore: close_sinks
  101. final StreamController<int> _sdkCmdController = StreamController.broadcast();
  102. Stream<int> get sdkCmdStream => _sdkCmdController.stream;
  103. // ignore: close_sinks
  104. final StreamController<List<int>> _sdkMotionController = StreamController.broadcast();
  105. Stream<List<int>> get sdkMotionStream => _sdkMotionController.stream;
  106. // ignore: close_sinks
  107. final StreamController<String> _sdkMotionDataController = StreamController.broadcast();
  108. Stream<String> get sdkMotionDataStream => _sdkMotionDataController.stream;
  109. final ValueNotifier<DiscoveredDevice?> deviceNotifier = ValueNotifier<DiscoveredDevice?>(null);
  110. final ValueNotifier<String> deviceNameNotifier = ValueNotifier<String>("");
  111. final ValueNotifier<Map> infoNotifier = ValueNotifier<Map>({});
  112. final ValueNotifier<String> versionNotifier = ValueNotifier<String>("");
  113. final ValueNotifier<Map> dataNotifier = ValueNotifier<Map>({});
  114. final ValueNotifier<int> electricityNotifier = ValueNotifier<int>(0);
  115. final ValueNotifier<int> stepNotifier = ValueNotifier<int>(0);
  116. final ValueNotifier<int> stepTotalNotifier = ValueNotifier<int>(0);
  117. final ValueNotifier<int> stepTotalTestNotifier = ValueNotifier<int>(0);
  118. final ValueNotifier<int> actionNotifier = ValueNotifier<int>(0);
  119. final ValueNotifier<List<int>> byteNotifier = ValueNotifier<List<int>>([]);
  120. final ValueNotifier<int> vibrateNotifier = ValueNotifier<int>(400);
  121. final ValueNotifier<List<int>> stepRealtimeNotifier = ValueNotifier<List<int>>([]);
  122. final ValueNotifier<bool> stepRealtimePageNotifier = ValueNotifier<bool>(false);
  123. final ValueNotifier<Hardware?> verNotifier = ValueNotifier(null);
  124. final ValueNotifier<Map<int, int>> stateNotifier = ValueNotifier({1: 0, 0: 0});
  125. final ValueNotifier<bool> h5gameRNotifier = ValueNotifier<bool>(false);
  126. final ValueNotifier<bool> deviceWriteNotifier = ValueNotifier<bool>(false);
  127. final ValueNotifier<bool> deviceReadNotifier = ValueNotifier<bool>(false);
  128. final ValueNotifier<bool> deviceReadNotifyNotifier = ValueNotifier<bool>(false);
  129. final ValueNotifier<int> rssiNotifier = ValueNotifier<int>(0);
  130. final ValueNotifier<Map<String, int>> timeUseNotifier = ValueNotifier<Map<String, int>>({});
  131. DiscoveredDevice? _connectingDevice;
  132. bool _listen = false;
  133. bool _online = false;
  134. bool _uploadLoged = false;
  135. bool _connecting = false;
  136. bool _scanning = false;
  137. String? _deviceId;
  138. int heartbeat = 0;
  139. PartInfo? _partInfo;
  140. Completer<bool>? _completerStep;
  141. Completer<bool>? _completerStepDel;
  142. Completer<bool>? _completerSetupDeviceVer;
  143. Completer<bool>? _completerConnected;
  144. QualifiedCharacteristic? characteristicWrite, characteristicNotify;
  145. StreamSubscription? statusStream, connectRight;
  146. late FlutterReactiveBle flutterReactiveBle;
  147. Timer? stepRealTimeTimer;
  148. Timer? gameModeTimer;
  149. Timer? timerConnected;
  150. Timer? rssiTimer;
  151. Timer? disconnectTimer;
  152. Timer? tryConnectTimer;
  153. int disconnectTimes = 0;
  154. DateTime? startTime;
  155. List<int> timeUse = [];
  156. int testDfu = 0;
  157. int _isRightError = 0;
  158. bool get isConnected => _online;
  159. bool get isNotReady => isDebugShoe ? false : !(_online == true && electricityNotifier.value > 0);
  160. bool get isRightError => _isRightError != 1;
  161. String? get deviceId => _deviceId;
  162. DiscoveredDevice? get device => _connectingDevice;
  163. late BuildContext _context;
  164. bool _showChargeDialog = false;
  165. DateTime? electricityTime;
  166. late SDKApi sdk;
  167. resetData() {
  168. stepNotifier.value = 0;
  169. stepTotalNotifier.value = 0;
  170. actionNotifier.value = 0;
  171. }
  172. bool _dfu = false;
  173. set dfu(bool dfu) {
  174. _dfu = dfu;
  175. }
  176. Future<String> _saveDevice(DiscoveredDevice device) async {
  177. var prefs = await SharedPreferences.getInstance();
  178. prefs.setString(PREF_KEY, device.id);
  179. prefs.setString(PREF_KEY_NAME, device.name);
  180. return device.id;
  181. }
  182. clearDevice({bool deleteStep = false}) async {
  183. var prefs = await SharedPreferences.getInstance();
  184. prefs.remove(PREF_KEY);
  185. prefs.remove(PREF_KEY_NAME);
  186. // if (deleteStep == true) {
  187. // var db = StepDB();
  188. // db.deleteAll();
  189. // }
  190. startTime = null;
  191. await disconnectDevice("清空设备", clearGatt: true, click: true);
  192. }
  193. Future<String?> getHistoryDevice() async {
  194. var prefs = await SharedPreferences.getInstance();
  195. return prefs.getString(PREF_KEY);
  196. }
  197. init(BuildContext context) async {
  198. this._connecting = false;
  199. statusStream?.cancel();
  200. connectRight?.cancel();
  201. flutterReactiveBle = FlutterReactiveBle();
  202. flutterReactiveBle.logLevel = inProduction ? LogLevel.none : LogLevel.verbose;
  203. statusStream = flutterReactiveBle.statusStream.listen((state) {
  204. print("bluetooth -- instance state $state");
  205. if (state == BleStatus.ready) {
  206. autoConnect();
  207. } else if (state == BleStatus.unknown) {
  208. } else if (state == BleStatus.poweredOff) {
  209. // clearDevice(deleteStep: false);
  210. // ToastUtil.show("蓝牙服务已关闭");
  211. } else {}
  212. });
  213. // flutterReactiveBle.connectedDeviceStream.listen((event) {
  214. // print("bluetooth -- device state $event");
  215. // if (event.connectionState == DeviceConnectionState.disconnected) {
  216. // _online = false;
  217. // tryCount--;
  218. // if (event.failure?.code == ConnectionError.failedToConnect) {
  219. // notifyConnectTime("[$tryCount]E${RegExp(r"([0-9]+)").firstMatch("${event.failure?.message}")?.group(0)}");
  220. // // addErr("0", "${event.failure?.code}", "${event.failure?.message}");
  221. // } else {
  222. // notifyConnectTime("[$tryCount]E0");
  223. // }
  224. // disposeSubscription();
  225. //
  226. // if (event.failure == null) {
  227. // try {
  228. // _completerConnected?.complete(true);
  229. // } catch (e) {}
  230. // }
  231. // }
  232. // });
  233. connectRight = connectRightStream.listen((event) {
  234. print("bluetooth -- connect right ${_connectingDevice?.name} ${event}!");
  235. if (event == 1 && _isRightError != event) {
  236. notifyConnectTime("R");
  237. timerConnected?.cancel();
  238. dataNotifier.value = {};
  239. verNotifier.value = null;
  240. // 左右鞋连接状态就绪,正常连接
  241. final device = _connectingDevice;
  242. if (device != null) {
  243. _newConnect(checkDfuUpdate: false);
  244. _connected(device);
  245. _query();
  246. }
  247. }
  248. _isRightError = event;
  249. });
  250. deviceNotifier.addListener(() {
  251. if (deviceNotifier.value != null) {
  252. DiscoveredDevice device = deviceNotifier.value!;
  253. deviceNameNotifier.value = device.name;
  254. BluetoothDB().find().then((history) {
  255. if (history.isNotEmpty == true) {
  256. try {
  257. var item = history.firstWhere((element) => element[BluetoothDB.C_ID] == device.id);
  258. deviceNameNotifier.value = item[BluetoothDB.C_MARK] ?? device.name ?? "";
  259. } catch (e) {}
  260. }
  261. });
  262. } else {
  263. deviceNameNotifier.value = "";
  264. }
  265. });
  266. Broadcast.eventStream.listen((event) {
  267. disconnectDevice("iOS 进入游戏");
  268. });
  269. sdk = SDKApi();
  270. this.listen(context, init: true);
  271. }
  272. gameInit(int gameType) {
  273. sdk.gameInit(gameType);
  274. }
  275. SDKApi gameSDK() {
  276. return sdk;
  277. }
  278. createGameLog(String? name) async {
  279. super.createLog("${name}_${sdk.getVersion()}", device?.name ?? deviceId);
  280. }
  281. uploadGameLog() {
  282. uploadLog();
  283. }
  284. _newConnect({bool checkDfuUpdate = true}) {
  285. final device = _connectingDevice;
  286. if (device != null) {
  287. _saveDevice(device);
  288. // if (isDebugShoe) {
  289. // ToastUtil.show("${device.name} 已连接");
  290. // }
  291. BluetoothDB().insert(device);
  292. if (checkDfuUpdate == true) checkUpdate();
  293. }
  294. }
  295. Future<bool> _hasConnected() async {
  296. final device = _connectingDevice;
  297. if (device != null) {
  298. return (await BluetoothDB().findById(device.id)).isNotEmpty;
  299. }
  300. return false;
  301. }
  302. Future listen(BuildContext context, {bool init = false}) async {
  303. this._context = context;
  304. this._listen = true;
  305. print("bluetooth -- listen");
  306. Broadcast.broadcast("SHOE.SDK.BLUE_DISCONNECT");
  307. var prefs = await SharedPreferences.getInstance();
  308. if (!prefs.containsKey("token")) {
  309. return;
  310. }
  311. disconnectTimer?.cancel();
  312. disconnectTimes = 0;
  313. if (_dfu == true) return;
  314. if (init != true) {
  315. if (isConnected) {
  316. setupGameMode4h5(h5gameRNotifier.value);
  317. } else {
  318. autoConnect();
  319. }
  320. }
  321. }
  322. void runTimer() {
  323. heartbeat = 0;
  324. addSubscription(Stream.periodic(Duration(seconds: 60)).listen((event) async {
  325. if (!isConnected) return;
  326. heartbeat++;
  327. if (heartbeat > 3) {
  328. disconnectDevice("心跳异常");
  329. return;
  330. }
  331. await queryDeviceData();
  332. await queryDeviceStep();
  333. }));
  334. }
  335. autoConnect() {
  336. getHistoryDevice().then((value) {
  337. if (this._connecting == true) return;
  338. if (value != null) connectDevice(id: value);
  339. });
  340. }
  341. Future background(BuildContext context) async {
  342. this._listen = false;
  343. if (_showChargeDialog == true) {
  344. Navigator.maybePop(context);
  345. }
  346. disconnectTimer?.cancel();
  347. disconnectTimer = Timer.periodic(Duration(seconds: 10), (t) {
  348. disconnectTimes++;
  349. if (disconnectTimes >= 720) {
  350. disconnectDevice("后台时断开连接");
  351. t.cancel();
  352. }
  353. });
  354. }
  355. Future disposeBluetooth(BuildContext context) async {
  356. if (_dfu == true) return;
  357. // // 实时计步中不主动断开
  358. if (stepRealtimePageNotifier.value == true) return;
  359. gameModeTimer?.cancel();
  360. this._listen = false;
  361. if (_showChargeDialog == true) {
  362. Navigator.maybePop(context);
  363. }
  364. // if (Platform.isIOS) {
  365. await disconnectDevice("app退后台");
  366. // }
  367. }
  368. resetNotifierData() {
  369. dataNotifier.value = {};
  370. verNotifier.value = null;
  371. versionNotifier.value = "";
  372. electricityNotifier.value = -1;
  373. _connectRightController.add(0);
  374. stateNotifier.value = {0: 0, 1: 0};
  375. notifyConnectTime("dis");
  376. deviceWriteNotifier.value = false;
  377. deviceReadNotifier.value = false;
  378. deviceReadNotifyNotifier.value = false;
  379. _online = false;
  380. }
  381. Future disconnectDevice(String msg, {bool clearGatt = false, bool click = false}) async {
  382. print("bluetooth -- disconnect $msg ${_connectingDevice?.id}");
  383. _scanning = false;
  384. _deviceId = null;
  385. await disposeSubscription();
  386. try {
  387. _completerConnected?.complete(true);
  388. } catch (e) {}
  389. if (click == true) Broadcast.broadcast("SHOE.SDK.BLUE_DISCONNECT");
  390. resetNotifierData();
  391. _isRightError = 0;
  392. disconnectTimes = 0;
  393. _uploadLoged = false;
  394. _connectingDevice = null;
  395. deviceNotifier.value = null;
  396. errQueue.clear();
  397. }
  398. connect({DiscoveredDevice? device}) async {
  399. await connectDevice(discoveredDevice: device);
  400. }
  401. Future connectDevice({DiscoveredDevice? discoveredDevice, String? id, bool again = false}) async {
  402. await disconnectDevice("主动连接");
  403. this._connecting = true;
  404. // await _connectDeviceInner(discoveredDevice: discoveredDevice, id: id, again: again);
  405. timeUse = [];
  406. timeUseNotifier.value = {};
  407. if (discoveredDevice != null) {
  408. startTime = null;
  409. }
  410. notifyConnectTime("F");
  411. DiscoveredDevice? device = discoveredDevice;
  412. if (device == null) {
  413. device = await discoverDevice(deviceId: id);
  414. if (device == null) {
  415. await disconnectDevice("没有找到设备");
  416. return;
  417. }
  418. notifyConnectTime("FF");
  419. // 1秒可能会提高连接成功率
  420. await Future.delayed(Duration(seconds: 1));
  421. }
  422. _connectingDevice = device;
  423. await _connectDeviceInner(device);
  424. }
  425. Future _connectDeviceInner(DiscoveredDevice device) async {
  426. int tryCount = 3;
  427. while (tryCount > 0) {
  428. print("bluetooth -- connect id: ${device.id} (test=$tryCount) !");
  429. if (!_connecting) break;
  430. if (device.id != _connectingDevice?.id) break;
  431. String deviceId = _deviceId = device.id;
  432. try {
  433. if (Platform.isIOS && tryCount != 3) {
  434. DiscoveredDevice? device = await discoverDevice(deviceId: deviceId);
  435. if (device == null) {
  436. tryCount--;
  437. continue;
  438. }
  439. deviceId = device.id;
  440. notifyConnectTime("FF");
  441. // 1秒可能会提高连接成功率
  442. await Future.delayed(Duration(seconds: 1));
  443. }
  444. addSubscription(flutterReactiveBle.connectToDevice(id: deviceId, connectionTimeout: const Duration(seconds: 10)).listen((state) async {
  445. print("bluetooth -- connect state $state $_connecting ");
  446. if (state.connectionState == DeviceConnectionState.connected) {
  447. notifyConnectTime("[$tryCount]C");
  448. // bindConnectedDevice(id: deviceId);
  449. int result = await discoverServices(flutterReactiveBle, deviceId);
  450. notifyConnectTime("[$tryCount]D$result");
  451. print("bluetooth -- connect discover services $result");
  452. if (result != 3) {
  453. try {
  454. _completerConnected?.complete(true);
  455. } catch (e) {}
  456. return;
  457. }
  458. if (characteristicNotify != null) {
  459. print("bluetooth -- subscribe notify $characteristicNotify");
  460. addSubscription(flutterReactiveBle.subscribeToCharacteristic(characteristicNotify!).listen((event) {
  461. // print("bluetooth -- subscribe notify $event");
  462. deviceReadNotifyNotifier.value = true;
  463. byteNotifier.value = event;
  464. heartbeat = 0;
  465. parse(event);
  466. })
  467. ..onError((e) {
  468. print("bluetooth -- subscribe notify e -> $e");
  469. disconnectDevice("订阅服务失败");
  470. }));
  471. }
  472. Stream.periodic(const Duration(seconds: 1)).take(10).forEach((element) {
  473. write(BLE.BLE_Client_T_CONNECT_CONFIRM, Uint8List.fromList([BLE_CODE_1]), test: 10);
  474. });
  475. int timeout = 10;
  476. timerConnected = Timer.periodic(Duration(seconds: 1), (t) {
  477. queryDeviceInfo();
  478. queryDeviceRight();
  479. if (--timeout < 0) {
  480. if (isRightError) {
  481. clearDevice();
  482. }
  483. t.cancel();
  484. }
  485. });
  486. tryCount = 3;
  487. } else if (state.connectionState == DeviceConnectionState.disconnected) {
  488. tryCount--;
  489. notifyConnectTime("[$tryCount]E${RegExp(r"([0-9]+)").firstMatch("${state.failure?.message}")?.group(0) ?? "0"}");
  490. try {
  491. _completerConnected?.complete(!(state.failure?.code == ConnectionError.failedToConnect));
  492. } catch (e) {}
  493. }
  494. })
  495. ..onError((e) {}));
  496. if (_connecting) {
  497. var result = await (_completerConnected = Completer()).future;
  498. // true是主动断开
  499. _connecting = result != true;
  500. await disposeSubscription();
  501. if (!_connecting) break;
  502. }
  503. } catch (e) {
  504. print("bluetooth -- connect error: $e");
  505. print(e);
  506. break;
  507. }
  508. await Future.delayed(Duration(seconds: 3));
  509. }
  510. if(_connecting) {
  511. await disconnectDevice("断开蓝牙连接 $_connecting");
  512. }
  513. //
  514. // notifyConnectTime("F");
  515. //
  516. // if (discoveredDevice == null) {
  517. // DiscoveredDevice? d = await discoverDevice(deviceId: id);
  518. // if (d != null) {
  519. // discoveredDevice = d;
  520. // notifyConnectTime("FF");
  521. // } else {
  522. // disconnectDevice("搜索不到设备", clearGatt: true);
  523. // return;
  524. // }
  525. // }
  526. //
  527. // String deviceId = _deviceId = discoveredDevice.id;
  528. // _connectingDevice = discoveredDevice;
  529. //
  530. // print("bluetooth -- connect $deviceId $again!");
  531. //
  532. // final stream = flutterReactiveBle.connectToDevice(id: deviceId, connectionTimeout: const Duration(seconds: 10));
  533. // addSubscription(stream.listen(_connectState, onError: (Object e) {
  534. // disconnectDevice("连接服务异常", clearGatt: true);
  535. // }));
  536. }
  537. Future<DiscoveredDevice?> discoverDevice({String? deviceId, String? deviceName}) async {
  538. // 2022-04-26 11:10:53.285 17454-17479/com.ouj.sdk.test I/System.out: 00001800-0000-1000-8000-00805f9b34fb
  539. // 2022-04-26 11:10:53.285 17454-17479/com.ouj.sdk.test I/System.out: 00002a00-0000-1000-8000-00805f9b34fb
  540. // 2022-04-26 11:10:53.285 17454-17479/com.ouj.sdk.test I/System.out: 00002a01-0000-1000-8000-00805f9b34fb
  541. // 2022-04-26 11:10:53.285 17454-17479/com.ouj.sdk.test I/System.out: 00002a04-0000-1000-8000-00805f9b34fb
  542. // 2022-04-26 11:10:53.285 17454-17479/com.ouj.sdk.test I/System.out: 00002aa6-0000-1000-8000-00805f9b34fb
  543. // 2022-04-26 11:10:53.285 17454-17479/com.ouj.sdk.test I/System.out: 00001801-0000-1000-8000-00805f9b34fb
  544. // 2022-04-26 11:10:53.285 17454-17479/com.ouj.sdk.test I/System.out: 6e400001-b5a3-f393-e0a9-e50e24dcca9e
  545. // 2022-04-26 11:10:53.285 17454-17479/com.ouj.sdk.test I/System.out: 6e400002-b5a3-f393-e0a9-e50e24dcca9e
  546. // 2022-04-26 11:10:53.285 17454-17479/com.ouj.sdk.test D/BluetoothController: discovered characteristic write android.bluetooth.BluetoothGatt@28bbf97 android.bluetooth.BluetoothGattCharacteristic@81cd69e
  547. // 2022-04-26 11:10:53.285 17454-17479/com.ouj.sdk.test I/System.out: 6e400003-b5a3-f393-e0a9-e50e24dcca9e
  548. // 2022-04-26 11:10:53.285 17454-17479/com.ouj.sdk.test D/BluetoothGatt: setCharacteristicNotification() - uuid: 6e400003-b5a3-f393-e0a9-e50e24dcca9e enable: true
  549. // 2022-04-26 11:10:53.286 17454-17479/com.ouj.sdk.test D/BluetoothController: discovered characteristic notify android.bluetooth.BluetoothGatt@28bbf97 android.bluetooth.BluetoothGattCharacteristic@9dfb57f
  550. // 2022-04-26 11:10:53.286 17454-17479/com.ouj.sdk.test I/System.out: 0000fe59-0000-1000-8000-00805f9b34fb
  551. // 2022-04-26 11:10:53.286 17454-17479/com.ouj.sdk.test I/System.out: 8ec90003-f315-4f60-9fb8-838830daea50
  552. _scanning = true;
  553. Timer timeout = Timer(Duration(seconds: 10), () {
  554. _scanning = false;
  555. });
  556. var stream = flutterReactiveBle.scanForDevices(withServices: [Uuid.parse(BLE_UUID)], scanMode: ScanMode.lowPower);
  557. DiscoveredDevice? device;
  558. await for (var event in stream) {
  559. print('bluetooth -- scan device : ${event.id} ${event.name}');
  560. if (_scanning != true) {
  561. break;
  562. }
  563. if (event.id == deviceId || event.name == deviceName || (deviceName != null && event.name.contains(deviceName))) {
  564. device = event;
  565. break;
  566. }
  567. }
  568. timeout.cancel();
  569. print('bluetooth -- found: ${device?.id} ${device?.name}');
  570. return device;
  571. }
  572. Future<int> discoverServices(FlutterReactiveBle flutterReactiveBle, String deviceId) async {
  573. int result = 0;
  574. for (var i = 0; i < 3; i++) {
  575. bool findWrite = false;
  576. bool findRead = false;
  577. try {
  578. var services = await flutterReactiveBle.discoverServices(deviceId);
  579. for (DiscoveredService service in services) {
  580. for (var characteristic in service.characteristics) {
  581. if (characteristic.isWritableWithoutResponse) {
  582. characteristicWrite = QualifiedCharacteristic(serviceId: service.serviceId, characteristicId: characteristic.characteristicId, deviceId: deviceId);
  583. findWrite = true;
  584. }
  585. if (characteristic.isNotifiable) {
  586. characteristicNotify = QualifiedCharacteristic(serviceId: service.serviceId, characteristicId: characteristic.characteristicId, deviceId: deviceId);
  587. findRead = true;
  588. }
  589. }
  590. }
  591. } catch (e) {
  592. print(e);
  593. print("bluetooth -- service error $e");
  594. }
  595. deviceWriteNotifier.value = findWrite;
  596. deviceReadNotifier.value = findRead;
  597. if (findWrite && findRead) {
  598. print("bluetooth -- service write: $findWrite, read: $findRead");
  599. result = 3;
  600. break;
  601. } else {
  602. await Future.delayed(Duration(seconds: 2));
  603. if (findWrite) {
  604. result = 1;
  605. } else if (findRead) {
  606. result = 2;
  607. }
  608. }
  609. }
  610. return result;
  611. }
  612. _query() async {
  613. queryDeviceInfo();
  614. queryDeviceStep();
  615. queryDeviceCharge();
  616. queryDeviceData();
  617. }
  618. _connected(DiscoveredDevice newDevice) async {
  619. print("bluetooth -- connected: $newDevice");
  620. deviceNotifier.value = newDevice;
  621. _dfuController.add(false);
  622. _online = true;
  623. _partInfo = null;
  624. if ((startTime?.difference(DateTime.now()).inHours ?? 1) > 0) {
  625. notifyConnected();
  626. startTime = DateTime.now();
  627. }
  628. setupGameMode4h5(h5gameRNotifier.value);
  629. runTimer();
  630. }
  631. notifyConnectTime(String tag) {
  632. int now = DateTime.now().millisecondsSinceEpoch;
  633. Map<String, int> result = Map.from(timeUseNotifier.value);
  634. // print("111111111111111111 ${now} ${timeUse}");
  635. result[tag] = now - (timeUse.isNotEmpty ? timeUse.last : now);
  636. timeUseNotifier.value = result;
  637. timeUse.add(now);
  638. }
  639. notifyConnected() {
  640. this.vibrate(200);
  641. this.lighting(10000);
  642. }
  643. checkUpdate() async {
  644. var info = infoNotifier.value;
  645. print("bluetooth -- checkUpdate ${info}");
  646. if (info.isEmpty == true) return;
  647. if (h5gameRNotifier.value == true) return;
  648. String softwareVer = info['softwareVer'];
  649. String hardwareVer = info['hardwareVer'];
  650. List<String> device = info['device'];
  651. PackageInfo packageInfo = await PackageInfo.fromPlatform();
  652. String appVer = packageInfo.version;
  653. Hardware? updateInfo = (await GetIt.I<RestClient>().checkHardwareUpdate(hardwareVer, appVer)).data;
  654. if (updateInfo != null) {
  655. // PackageInfo packageInfo = await PackageInfo.fromPlatform();
  656. // if (updateInfo.min_app_ver?.isNotEmpty == true && versionCompare(packageInfo.version, updateInfo.min_app_ver ?? "0") < 0) {
  657. // debugPrint("bluetooth -- dfu update app ver ${packageInfo.version} min ${updateInfo.min_app_ver}");
  658. // return;
  659. // }
  660. // if (updateInfo.max_app_ver?.isNotEmpty == true && versionCompare(packageInfo.version, updateInfo.max_app_ver ?? "0") > 0) {
  661. // debugPrint("bluetooth -- dfu update app ver ${packageInfo.version} max ${updateInfo.max_app_ver}");
  662. // return;
  663. // }
  664. //
  665. // if (updateInfo.min_hardware_ver?.isNotEmpty == true && versionCompare(hardwareVer, updateInfo.min_hardware_ver ?? "0") < 0) {
  666. // debugPrint("bluetooth -- dfu update hardware ver ${hardwareVer} min ${updateInfo.min_hardware_ver}");
  667. // return;
  668. // }
  669. //
  670. // if (updateInfo.max_hardware_ver?.isNotEmpty == true && versionCompare(hardwareVer, updateInfo.max_hardware_ver ?? "0") > 0) {
  671. // debugPrint("bluetooth -- dfu update hardware ver ${hardwareVer} max ${updateInfo.max_hardware_ver}");
  672. // return;
  673. // }
  674. updateInfo.devices = [];
  675. updateInfo.localVer = softwareVer;
  676. print("bluetooth -- dfu versionCompare ${versionCompare(softwareVer, updateInfo.ver ?? "0.0")}");
  677. bool cancelable = this.testDfu >= 5 ? true : !isDebugShoe;
  678. if (this.testDfu >= 5) {
  679. } else {
  680. final testVersion = "梁剑波<font color=\"red\">DEBUG专用</font>";
  681. bool willTest = updateInfo.name == testVersion;
  682. if (willTest) {
  683. if (versionCompare(softwareVer, updateInfo.ver ?? "0.0") == 0) return;
  684. } else {
  685. if (versionCompare(softwareVer, updateInfo.ver ?? "0.0") >= 0) {
  686. return;
  687. }
  688. }
  689. }
  690. for (var i = device.length - 1; i >= 0; i--) {
  691. updateInfo.devices!.add(device[i]);
  692. }
  693. verNotifier.value = updateInfo;
  694. if (h5gameRNotifier.value == true) return;
  695. var context = _context;
  696. var value = updateInfo;
  697. var closeable = 0;
  698. var result = await showDialog(
  699. context: context,
  700. barrierDismissible: false,
  701. builder: (context) => CustomAlertDialog(
  702. title: '发现新的鞋子固件',
  703. child: WillPopScope(
  704. onWillPop: () async {
  705. return false;
  706. },
  707. child: GestureDetector(
  708. behavior: HitTestBehavior.opaque,
  709. onTap: () {
  710. closeable++;
  711. if (closeable >= 5) {
  712. Navigator.of(context).pop(false);
  713. }
  714. },
  715. child: Container(
  716. width: double.infinity,
  717. padding: const EdgeInsets.symmetric(horizontal: 24.0),
  718. child: Text(
  719. "${value.name}\n${value.localVer} -> ${value.ver}\n${value.msg}",
  720. style: TextStyle(fontSize: 14, color: Color(0xff333333), height: 1.8),
  721. )),
  722. ),
  723. ),
  724. textOk: '立即升级',
  725. cancelable: cancelable,
  726. ok: () => Navigator.of(context).pop(true)),
  727. );
  728. if (result != true) return;
  729. _dfuController.add(true);
  730. await Future.delayed(Duration(seconds: 1));
  731. result = await showDialog(
  732. context: context,
  733. barrierDismissible: false,
  734. builder: (context) => SimpleDialog(
  735. children: <Widget>[
  736. DfuUpdatePage(
  737. hardware: value,
  738. version: "${value.ver}",
  739. )
  740. ],
  741. ));
  742. }
  743. }
  744. void parse(List<int> event) {
  745. if (event.isEmpty == true) return;
  746. if (!_listen) return;
  747. ByteDataReader reader = ByteDataReader();
  748. reader.add(event);
  749. int flagAA = reader.readUint8();
  750. // int flagBB = reader.readUint8();
  751. // int flagCC = reader.readUint8();
  752. int len = reader.readUint8();
  753. int len1 = 0xFF - reader.readUint8();
  754. // int index = reader.readUint8();
  755. int cmd = reader.readUint8();
  756. // print(" change --> ${flagAA} ${len} ${~len} ${cmd}");
  757. // print(" change --> ${len} ${~len} ${len1}");
  758. // print(" change --> ${index} ${cmd}");
  759. if (!(flagAA == 0xAA)) return;
  760. if (len != len1) return;
  761. Uint8List byteArray = reader.read(event.length - 5);
  762. int ver = 0;
  763. for (int i = 0; i < event.length - 1; i++) {
  764. ver += event[i];
  765. }
  766. if (ver.toUnsigned(8) != event[event.length - 1]) return;
  767. parseCmd(cmd, byteArray);
  768. }
  769. void parseCmd(int cmd, Uint8List byteArray) {
  770. // if (isDebugShoe) print(" cmd $cmd data --> $byteArray");
  771. switch (cmd) {
  772. case 0x01:
  773. _parseAction(byteArray);
  774. break;
  775. case BLE.BLE_Client_T_MOTION:
  776. disconnectTimes = 0;
  777. if (appLifecycleState == AppLifecycleState.resumed) {
  778. sdk.gameProcess(byteArray);
  779. int cmd = sdk.getInteractionCMD();
  780. if (cmd > -1) {
  781. _sdkCmdController.add(cmd);
  782. }
  783. String gameData = sdk.getGameDataStr();
  784. _sdkMotionDataController.add(gameData);
  785. if (isDebugShoe) {
  786. // print("gameDate $gameData");
  787. writeLog(gameData);
  788. }
  789. List<int> result = sdk.getMotion();
  790. if (result.any((element) => element > 0)) {
  791. if (isDebugShoe) print("sdk -- motion $result");
  792. _sdkMotionController.add(result);
  793. }
  794. _dataController.add(byteArray);
  795. }
  796. break;
  797. case 0xA0:
  798. break;
  799. case BLE.BLE_Client_T_UPDATE:
  800. _parseQuery(byteArray);
  801. break;
  802. case BLE.BLE_Client_T_CONNET_R:
  803. _connectRightController.add(byteArray.first);
  804. break;
  805. case BLE.BLE_Client_T_REALTIMESTEP:
  806. _parseStepRealtime(byteArray);
  807. break;
  808. case BLE.BLE_Client_T_DFU:
  809. if (_completerSetupDeviceVer?.isCompleted != true) _completerSetupDeviceVer?.complete(true);
  810. break;
  811. case BLE.BLE_Client_T_CHARGE: //充电
  812. _parseCharge(byteArray);
  813. break;
  814. case BLE.BLE_Client_T_ERR: //异常
  815. _parseErr(byteArray);
  816. break;
  817. case BLE.BLE_Client_T_GAMEMODE:
  818. break;
  819. case BLE.BLE_Client_T_CONNECT_CONFIRM:
  820. _parseConnectConfirm(byteArray);
  821. break;
  822. }
  823. }
  824. void _parseConnectConfirm(Uint8List byteArray) {
  825. ByteDataReader reader = ByteDataReader();
  826. reader.add(byteArray);
  827. int state = reader.readUint8();
  828. }
  829. void _parseAction(Uint8List byteArray) {
  830. ByteDataReader reader = ByteDataReader();
  831. reader.add(byteArray);
  832. int action = reader.readUint8();
  833. int t = reader.readUint16();
  834. print("action: $action ");
  835. actionNotifier.value = action;
  836. }
  837. void _parseQuery(Uint8List byteArray) {
  838. ByteDataReader reader = ByteDataReader();
  839. reader.add(byteArray);
  840. int cmd = reader.readUint8();
  841. if (cmd != BLE_UPDATE.BASIC) {
  842. // 右鞋没连上,不处理下面的流程
  843. if (_isRightError != 1) return;
  844. }
  845. switch (cmd) {
  846. case BLE_UPDATE.BASIC: // 设备基本信息
  847. Map<String, dynamic> info = {};
  848. List<int> name = [];
  849. for (var i = 0; i < 64; i++) {
  850. name.add(reader.readUint8());
  851. }
  852. info['name'] = String.fromCharCodes(name).replaceAll("\u0000", "");
  853. List<int> softwareVer = [];
  854. List<int> hardwareVer = [];
  855. List<String> device = [];
  856. for (var i = 0; i < 2; i++) {
  857. List<String> macList = [];
  858. for (var j = 0; j < 6; j++) {
  859. macList.add(reader.readUint8().toRadixString(16).padLeft(2, "0"));
  860. }
  861. var mac = macList.join(":").toUpperCase();
  862. print("mac $i = $mac");
  863. for (var k = 0; k < 4; k++) {
  864. hardwareVer.add(reader.readUint8());
  865. }
  866. softwareVer.add(reader.readUint16());
  867. device.add(mac);
  868. }
  869. print("bluetooth dfu info $hardwareVer $softwareVer");
  870. if (hardwareVer.length != 8 || softwareVer.length != 2) return;
  871. String leftHardware = hardwareVer.sublist(1, 4).join(".");
  872. String rightHardware = hardwareVer.sublist(4 + 1, hardwareVer.length).join(".");
  873. int compareHardware = versionCompare(leftHardware, rightHardware);
  874. String minHardwareVersion = compareHardware < 0 ? leftHardware : rightHardware;
  875. print("bluetooth hardwareVer $leftHardware $rightHardware $compareHardware $minHardwareVersion");
  876. String leftSoftware = hardwareVer.sublist(1, 3).join(".") + ".${softwareVer[0]}";
  877. String rightSoftware = hardwareVer.sublist(4 + 1, 4 + 1 + 2).join(".") + ".${softwareVer[1]}";
  878. int compareSoftware = versionCompare(leftSoftware, rightSoftware);
  879. String minSoftwareVersion = compareSoftware < 0 ? leftSoftware : rightSoftware;
  880. print("bluetooth softwareVer $leftSoftware $rightSoftware $compareSoftware $minSoftwareVersion");
  881. shoeVersion = "$minSoftwareVersion";
  882. info['softwareVer'] = minSoftwareVersion;
  883. info['hardwareVer'] = minHardwareVersion;
  884. info['mac'] = device.length > 1 ? device.first : "";
  885. info['device'] = device;
  886. infoNotifier.value = info;
  887. if (versionNotifier.value != minSoftwareVersion) {
  888. versionNotifier.value = minSoftwareVersion;
  889. checkUpdate();
  890. }
  891. if (_uploadLoged != true) {
  892. _uploadLoged = true;
  893. _uploadLog();
  894. _uploadErr();
  895. }
  896. break;
  897. case BLE_UPDATE.DATA: // 设备数据(左鞋,右鞋)
  898. Map<String, dynamic> info = {};
  899. for (var i = 0; i < 2; i++) {
  900. info['${i}_electricity'] = reader.readUint8();
  901. info['${i}_temperature'] = reader.readUint8();
  902. info['${i}_pressure'] = reader.readUint(4);
  903. reader.readUint(4);
  904. }
  905. if (reader.remainingLength >= 4) {
  906. info['0_adc'] = reader.readUint16();
  907. info['1_adc'] = reader.readUint16();
  908. }
  909. // [170, 187, 204, 23, 232, 0, 161, 1, 50, 0, 33, 0, 0, 156, 41, 51, 0, 34, 0, 0, 150, 19, 232]
  910. dataNotifier.value = info;
  911. int electricity = min(info['0_electricity'] ?? 0, info['1_electricity'] ?? 0);
  912. electricityNotifier.value = electricity;
  913. if (electricity <= 10) {
  914. if (electricityTime == null || (electricityTime?.difference(DateTime.now()).inMinutes.abs() ?? 0) >= 60) {
  915. if (stateNotifier.value.values.every((element) => element > 1) != true) {
  916. ToastUtil.show("鞋子电量不足,请及时充电!");
  917. electricityTime = DateTime.now();
  918. }
  919. }
  920. }
  921. if (isDebugShoe) {
  922. _testElectricity(info);
  923. }
  924. break;
  925. case BLE_UPDATE.STEP: // 查询步数
  926. print("bluetooth -- step part ${_partInfo?.ready}");
  927. if (_partInfo == null) return;
  928. if (_partInfo?.ready == true) return;
  929. if (isDebugShoe) {
  930. _testStep(byteArray.toList().join(","));
  931. print("bluetooth -- step data ${byteArray.toList().join(",")}");
  932. }
  933. int start = reader.readUint64();
  934. int serialCount = reader.readUint16();
  935. int serial = reader.readUint16();
  936. // if(serialCount == 0){
  937. // _completerStep?.complete(false);
  938. // return;
  939. // }
  940. List<int> data = [];
  941. while (reader.remainingLength > 0) {
  942. data.add(reader.readUint32());
  943. }
  944. if (serial == 0 && data.isNotEmpty) {
  945. stepTotalNotifier.value = data.last;
  946. }
  947. _partInfo!.start = start;
  948. _partInfo!.serialCount = serialCount + 1;
  949. _partInfo!.data[serial] = data;
  950. if (isDebugShoe) print("bluetooth -- step start $start ${DateTime.fromMillisecondsSinceEpoch(start)} read ($serial,$serialCount) --> $data");
  951. if (_partInfo!.data.length == _partInfo!.serialCount) {
  952. _partInfo!.ready = true;
  953. var partResult = _partInfo!;
  954. Future.microtask(() async {
  955. await partResult.prepare();
  956. print("bluetooth -- step end ... ");
  957. if (_completerStep?.isCompleted != true) _completerStep?.complete(true);
  958. });
  959. }
  960. break;
  961. case BLE_UPDATE.STEP_DELETE: // 步数回调
  962. if (_completerStepDel != null) _completerStepDel!.complete(true);
  963. break;
  964. }
  965. }
  966. void _parseStepRealtime(Uint8List byteArray) {
  967. ByteDataReader reader = ByteDataReader();
  968. reader.add(byteArray);
  969. int cmd = reader.readUint8();
  970. if (cmd == 0) {
  971. } else if (cmd == 1) {
  972. int left = 0;
  973. int right = 0;
  974. if (reader.remainingLength > 4) {
  975. left = reader.readUint32();
  976. right = reader.readUint32();
  977. } else {
  978. left = reader.readUint16();
  979. right = reader.readUint16();
  980. }
  981. // print("left: ${left}, right: ${ right} = ${step}");
  982. stepRealtimeNotifier.value = [left, right];
  983. // 已经不是在实时计步页面,但还收到数据,关了!
  984. if (stepRealtimePageNotifier.value == false) {
  985. write(BLE.BLE_Client_T_REALTIMESTEP, Uint8List.fromList([BLE_CODE_0]));
  986. }
  987. }
  988. }
  989. void _parseCharge(Uint8List byteArray) async {
  990. ByteDataReader reader = ByteDataReader();
  991. reader.add(byteArray);
  992. int cmd = reader.readUint8();
  993. int state = reader.readUint8();
  994. Map<int, int> _state = Map.from(stateNotifier.value);
  995. _state.update(cmd, (value) => state);
  996. stateNotifier.value = _state;
  997. // print("111111111111111111111111 $_state");
  998. if (_state[0]! <= 1 || _state[1]! <= 1) {
  999. if (_showChargeDialog == true) {
  1000. Navigator.maybePop(_context);
  1001. }
  1002. return;
  1003. }
  1004. if (_state[0] == 3 && _state[1] == 3) {
  1005. queryDeviceData();
  1006. }
  1007. if (_state[0]! > 1 && _state[1]! > 1 && _showChargeDialog != true) {
  1008. _showChargeDialog = true;
  1009. showDialog(
  1010. context: _context,
  1011. barrierColor: Colors.transparent,
  1012. builder: (context) => SimpleDialog(
  1013. backgroundColor: Colors.transparent,
  1014. elevation: 0,
  1015. children: [
  1016. Center(
  1017. child: Container(
  1018. constraints: BoxConstraints(maxWidth: 180.0),
  1019. decoration: BoxDecoration(
  1020. borderRadius: BorderRadius.all(Radius.circular(10.0)),
  1021. color: Colors.black.withOpacity(.75),
  1022. ),
  1023. child: Column(
  1024. mainAxisSize: MainAxisSize.min,
  1025. children: [
  1026. Align(
  1027. child: GestureDetector(
  1028. child: Padding(
  1029. padding: const EdgeInsets.all(10.0),
  1030. child: Image.asset(
  1031. "lib/assets/img/btn_close_white.png",
  1032. width: 18,
  1033. ),
  1034. ),
  1035. onTap: () {
  1036. Navigator.maybePop(context);
  1037. },
  1038. behavior: HitTestBehavior.opaque,
  1039. ),
  1040. alignment: Alignment.topRight,
  1041. ),
  1042. Padding(
  1043. padding: const EdgeInsets.fromLTRB(20.0, 5, 20.0, 16.0),
  1044. child: ValueListenableBuilder<Map<int, int>>(
  1045. valueListenable: stateNotifier,
  1046. builder: (context, val, __) {
  1047. int totalState = (val[0]! + val[1]!) ~/ 2;
  1048. List<int> keys = val.keys.toList();
  1049. keys.sort();
  1050. return Column(
  1051. children: [
  1052. Center(
  1053. child: Row(
  1054. children: keys.map((key) {
  1055. int state = val[key]!;
  1056. String label = key == 0 ? "left" : "right";
  1057. return Padding(
  1058. padding: EdgeInsets.symmetric(horizontal: 10),
  1059. child: Image.asset(
  1060. state == 3
  1061. ? "lib/assets/img/pop_icon_${label}full.png"
  1062. : state == 2
  1063. ? "lib/assets/img/pop_icon_${label}charge.png"
  1064. : "lib/assets/img/pop_icon_${label}fault.png",
  1065. ),
  1066. );
  1067. }).toList(),
  1068. mainAxisSize: MainAxisSize.min,
  1069. ),
  1070. ),
  1071. const SizedBox(
  1072. height: 15,
  1073. ),
  1074. ValueListenableBuilder(
  1075. valueListenable: electricityNotifier,
  1076. builder: (BuildContext context, int value, Widget? child) {
  1077. int _power = max(0, (val[0]! > 1 && val[1]! > 1) ? value : 0);
  1078. return Column(
  1079. children: [
  1080. Text(
  1081. (_power > 1) ? "$_power%" : "",
  1082. style: TextStyle(fontSize: 8.0, color: Colors.white),
  1083. ),
  1084. const SizedBox(
  1085. height: 7,
  1086. ),
  1087. ClipRRect(
  1088. child: SizedBox(
  1089. height: 2,
  1090. child: LinearProgressIndicator(
  1091. backgroundColor: Color(0xff656565),
  1092. valueColor: AlwaysStoppedAnimation(Color(0xff00DC42)),
  1093. value: _power / 100,
  1094. ),
  1095. ),
  1096. borderRadius: BorderRadius.circular(5),
  1097. )
  1098. ],
  1099. );
  1100. },
  1101. ),
  1102. const SizedBox(
  1103. height: 11,
  1104. ),
  1105. Text(
  1106. (val[0] == 3 && val[1] == 3)
  1107. ? "智能鞋充电已完成"
  1108. : (val[0]! > 1 && val[1]! > 1)
  1109. ? "智能鞋充电中..."
  1110. : (val[0]! <= 1 && val[1]! <= 1)
  1111. ? "智能鞋连接异常"
  1112. : val[0]! <= 1
  1113. ? "左鞋充电连接异常"
  1114. : val[1]! <= 1
  1115. ? "右鞋充电连接异常"
  1116. : "连接异常",
  1117. style: TextStyle(fontSize: 12.0, color: Colors.white),
  1118. ),
  1119. ],
  1120. );
  1121. }),
  1122. ),
  1123. ],
  1124. )),
  1125. )
  1126. ],
  1127. )).then((value) => _showChargeDialog = false);
  1128. }
  1129. Future.delayed(Duration(seconds: 5)).then((value) {
  1130. if (_showChargeDialog == true) {
  1131. Map<int, int> val = stateNotifier.value;
  1132. print("_parseCharge $val");
  1133. if (val[0]! > 1 && val[1]! > 1) {
  1134. Navigator.pop(_context);
  1135. }
  1136. }
  1137. });
  1138. }
  1139. Map<String, Map<String, String?>> errQueue = {};
  1140. /// 错误处理
  1141. void _parseErr(Uint8List byteArray) async {
  1142. ByteDataReader r = ByteDataReader();
  1143. r.add(byteArray);
  1144. int leftOrRight = r.readUint8();
  1145. int code = r.readUint8();
  1146. List<int> msgData = r.read(r.remainingLength);
  1147. String msg = String.fromCharCodes(msgData);
  1148. String err = "${leftOrRight == 0 ? "左鞋" : "右鞋"}:$msg";
  1149. addErr("$code", err, "");
  1150. }
  1151. void _uploadErr() async {
  1152. // if (infoNotifier.value.isEmpty) return;
  1153. if (errQueue.isEmpty) return;
  1154. var info = infoNotifier.value;
  1155. // if (info.isEmpty) return;
  1156. PackageInfo packageInfo = await PackageInfo.fromPlatform();
  1157. String mac = info['mac']?.toString() ?? _connectingDevice?.id ?? _deviceId ?? "00:00:00:00:00:00";
  1158. String firmware = "${info['softwareVer']}";
  1159. String hardware = "${info['hardwareVer']}";
  1160. String app_ver = "${packageInfo.version}";
  1161. List<String> keys = errQueue.keys.toList();
  1162. for (var i = 0; i < keys.length; i++) {
  1163. String code = keys[i];
  1164. Map<String, String?> err = errQueue[code] as Map<String, String?>;
  1165. String? message = err["message"];
  1166. String? detail = err["detail"];
  1167. if (isDebugShoe) {
  1168. await _testErrLog();
  1169. }
  1170. var resp = await api.logHardwareErr(mac, firmware, hardware, app_ver, code, "$message", "$detail ${await Application.getDeviceInfo()}");
  1171. if (resp.code != 0) {
  1172. await Future.delayed(Duration(seconds: 2));
  1173. }
  1174. }
  1175. }
  1176. addErr(String code, String? message, String? detail) {
  1177. if (isDebugShoe) {
  1178. print("bluetooth -- err $code $message $detail");
  1179. }
  1180. if (!errQueue.containsKey(code)) {
  1181. errQueue[code] = {"code": code, "message": message, "detail": detail};
  1182. _uploadErr();
  1183. }
  1184. }
  1185. Future _saveInfo(PartInfo? partInfo) async {
  1186. if (partInfo == null) return;
  1187. print("bluetooth -- step save ${partInfo.start} ${partInfo.serialCount} ${partInfo.items.length}");
  1188. if (partInfo.items.isEmpty == true) return;
  1189. List<PartItem> _items = [];
  1190. for (var item in partInfo.items) {
  1191. _items.add(item);
  1192. print("bluetooth -- step save ${item.time} ${item.step}");
  1193. }
  1194. await StepDB().insertAll(_items);
  1195. _queryController.add(true);
  1196. }
  1197. Future<int> _uploadInfo(int startTime) async {
  1198. final now = DateTime.fromMillisecondsSinceEpoch(startTime);
  1199. final offset = DateTime(now.year, now.month, now.day, now.hour);
  1200. var list = await StepDB().find(offset.millisecondsSinceEpoch, _deviceId ?? "0");
  1201. if (list.isEmpty) return 0;
  1202. List<List<int>> data = [];
  1203. int step = 0;
  1204. for (var item in list) {
  1205. int _step = Converter.toInt(item['st']);
  1206. if (_step > 0 && _step < 10000000) {
  1207. data.add([_step, item['di'], (item['time'] as int) ~/ 1000]);
  1208. }
  1209. step += Converter.toInt(_step);
  1210. }
  1211. print("bluetooth -- step upload ${offset.millisecondsSinceEpoch} $startTime $data");
  1212. if (step > 5) {
  1213. var resp = await api.addDaily(data: json.encode(data));
  1214. if (resp.code == 0) {
  1215. // await StepDB().delete(last);
  1216. return 0;
  1217. }
  1218. }
  1219. return step == 0 ? 0 : -1;
  1220. // Directory appDocDir = await getApplicationDocumentsDirectory();
  1221. // String appDocPath = appDocDir.path;
  1222. // Directory saveDir = Directory("$appDocPath/step");
  1223. // var files = saveDir.listSync();
  1224. // for(var file in files){
  1225. // var f= new File(file.path);
  1226. // var content = f.readAsStringSync();
  1227. // await api.addDaily(data: content);
  1228. // file.delete();
  1229. // }
  1230. }
  1231. // 查询 设备基本信息
  1232. Future queryDeviceCharge() async {
  1233. await write(BLE.BLE_Client_T_CHARGE, Uint8List(0));
  1234. }
  1235. // 查询 设备右鞋
  1236. Future queryDeviceRight() async {
  1237. await write(BLE.BLE_Client_T_CONNET_R, Uint8List.fromList([]));
  1238. }
  1239. // 查询 设备基本信息
  1240. Future queryDeviceInfo() async {
  1241. await write(BLE.BLE_Client_T_UPDATE, Uint8List.fromList([BLE_CODE_0]));
  1242. }
  1243. // 查询 设备数据
  1244. Future queryDeviceData() async {
  1245. await write(BLE.BLE_Client_T_UPDATE, Uint8List.fromList([BLE_CODE_1]));
  1246. }
  1247. // 查询 查询步数
  1248. Future queryDeviceStep({bool test = false}) async {
  1249. if (!isConnected) return;
  1250. // await Future.delayed(Duration(seconds: 3));
  1251. // _queryController.add(true);
  1252. if (test != true) if (stepTotalTestNotifier.value == 1) return;
  1253. if (_partInfo != null) {
  1254. print("bluetooth -- step _partInfo.now ${_partInfo!.now.difference(DateTime.now()).inSeconds}");
  1255. if ((_partInfo!.now.difference(DateTime.now()).inSeconds) > -60) {
  1256. return;
  1257. }
  1258. }
  1259. print("bluetooth -- step init");
  1260. _partInfo = PartInfo(_deviceId ?? "0", 0, 0);
  1261. if (test == true) stepTotalNotifier.value = -1;
  1262. // await write(BLE.BLE_Client_T_UPDATE, createTime(BLE_UPDATE.STEP));
  1263. DateTime now = DateTime.now();
  1264. DateTime offset = DateTime(now.year, now.month, now.day, now.hour);
  1265. print("bluetooth -- create now .. $now - $offset (${offset.millisecondsSinceEpoch})");
  1266. ByteDataWriter writer = ByteDataWriter();
  1267. writer.writeUint8(BLE_UPDATE.STEP);
  1268. writer.writeUint16(BLE_CODE_0);
  1269. writer.writeUint64(now.millisecondsSinceEpoch);
  1270. await write(BLE.BLE_Client_T_UPDATE, writer.toBytes());
  1271. if (_completerStep != null && _completerStep?.isCompleted != true) _completerStep?.complete(false);
  1272. if (_completerStepDel != null && _completerStepDel?.isCompleted != true) _completerStepDel?.complete(false);
  1273. _completerStep = Completer();
  1274. _completerStepDel = Completer();
  1275. var timer = Timer.periodic(Duration(seconds: 1), (timer) {
  1276. if (_partInfo == null) return;
  1277. Iterable<int> keys = _partInfo!.data.keys;
  1278. if (keys.isEmpty) return;
  1279. for (var i = 1; i < _partInfo!.serialCount; i++) {
  1280. if (!keys.contains(i)) {
  1281. print("bluetooth -- step request package $i");
  1282. // 请求缺包
  1283. ByteDataWriter writer = ByteDataWriter();
  1284. writer.writeUint8(BLE_UPDATE.STEP);
  1285. writer.writeUint16(i);
  1286. writer.writeUint64(now.millisecondsSinceEpoch);
  1287. write(BLE.BLE_Client_T_UPDATE, writer.toBytes());
  1288. }
  1289. }
  1290. });
  1291. Timer timeout = Timer(Duration(seconds: 20), () {
  1292. if (_completerStep?.isCompleted != true) _completerStep?.complete(false);
  1293. });
  1294. var result = await _completerStep!.future;
  1295. timeout.cancel();
  1296. timer.cancel();
  1297. int stepTotal = 0;
  1298. if (result == true) {
  1299. await _saveInfo(_partInfo);
  1300. int code = await _uploadInfo(_partInfo!.start);
  1301. if (code != 0) {
  1302. code = _partInfo!.items.length;
  1303. }
  1304. if (isDebugShoe) {
  1305. var now = DateTime.now();
  1306. _partInfo?.items.forEach((element) {
  1307. var info = {"t": element.time, "s": element.step, "total": element.absolute};
  1308. _testStep("$_deviceId,${now.hour},${now.minute},${now.second},${info['t']},${info['s']},${info['total']}");
  1309. });
  1310. }
  1311. if (test == true) {
  1312. if (_partInfo?.items.isNotEmpty == true) {
  1313. stepTotal = _partInfo?.items.map((e) => e.step).reduce((value, element) => value + element) ?? 0;
  1314. } else {
  1315. stepTotal = 0;
  1316. }
  1317. }
  1318. if (code == 0) {
  1319. var timer = Timer.periodic(Duration(milliseconds: 1000), (timer) {
  1320. write(BLE.BLE_Client_T_UPDATE, createTime(BLE_UPDATE.STEP_DELETE));
  1321. if (_isRightError != 1) {
  1322. timer.cancel();
  1323. if (_completerStepDel?.isCompleted != true) _completerStepDel?.complete(false);
  1324. }
  1325. });
  1326. Timer timeout = Timer(Duration(seconds: 60), () {
  1327. if (_completerStepDel?.isCompleted != true) _completerStepDel?.complete(false);
  1328. });
  1329. await _completerStepDel!.future;
  1330. timer.cancel();
  1331. timeout.cancel();
  1332. }
  1333. _completerStepDel = null;
  1334. }
  1335. _partInfo = null;
  1336. print("bluetooth -- step reset");
  1337. stepNotifier.value = stepTotal;
  1338. }
  1339. // 固件升级
  1340. Future<bool> setupDeviceVer(int type) async {
  1341. _completerSetupDeviceVer = Completer();
  1342. int time = 10;
  1343. Timer timeout = Timer.periodic(Duration(seconds: 1), (t) {
  1344. try {
  1345. write(BLE.BLE_Client_T_DFU, Uint8List.fromList([type]));
  1346. } catch (e) {
  1347. print(e);
  1348. }
  1349. time--;
  1350. if (time < 0) {
  1351. if (_completerSetupDeviceVer?.isCompleted != true) _completerSetupDeviceVer?.complete(false);
  1352. t.cancel();
  1353. }
  1354. });
  1355. var result = (await _completerSetupDeviceVer?.future) ?? false;
  1356. timeout.cancel();
  1357. return result;
  1358. }
  1359. // 游戏模式
  1360. Future setupGameMode(bool mode) async {
  1361. if (mode == false && h5gameRNotifier.value == true) {
  1362. return;
  1363. }
  1364. print("=================================setupGameMode $mode=================================");
  1365. gameModeTimer?.cancel();
  1366. if (mode) {
  1367. gameModeTimer = Timer.periodic(Duration(seconds: 30), (timer) {
  1368. if (this._listen == true) write(BLE.BLE_Client_T_GAMEMODE, Uint8List.fromList([BLE_CODE_1]));
  1369. });
  1370. }
  1371. await write(BLE.BLE_Client_T_GAMEMODE, mode ? Uint8List.fromList([BLE_CODE_1]) : Uint8List.fromList([BLE_CODE_0]));
  1372. }
  1373. Future setupGameMode4h5(bool mode) async {
  1374. h5gameRNotifier.value = mode;
  1375. setupGameMode(mode);
  1376. }
  1377. Future setupDataDebug(bool mode) async {
  1378. await write(BLE.BLE_Client_T_GAMEMODE, mode ? Uint8List.fromList([BLE_CODE_1 + 1]) : Uint8List.fromList([BLE_CODE_0]));
  1379. //
  1380. // device?.rssi.listen((event) {
  1381. // rssiNotifier.value = event;
  1382. // });
  1383. //
  1384. // rssiTimer?.cancel();
  1385. // if (mode == true) {
  1386. // rssiTimer = Timer.periodic(Duration(seconds: 1), (timer) {
  1387. // device?.requestRssi();
  1388. // });
  1389. // }
  1390. }
  1391. Future vibrate(int vibrate, {int leftOrRight = 0}) async {
  1392. int duration = min(1000, max(100, vibrate));
  1393. ByteDataWriter writer = ByteDataWriter();
  1394. writer.writeUint16(duration);
  1395. writer.writeUint8(leftOrRight);
  1396. await write(BLE.BLE_Client_T_SHOCK, writer.toBytes());
  1397. }
  1398. Future lighting(int time) async {
  1399. int duration = min(10000, max(100, time));
  1400. ByteDataWriter writer = ByteDataWriter();
  1401. writer.writeUint16(duration);
  1402. await write(BLE.BLE_Client_T_LIGHTING, writer.toBytes());
  1403. }
  1404. Future stepRealTime(bool mode) async {
  1405. stepRealtimeNotifier.value = [];
  1406. stepRealtimePageNotifier.value = mode;
  1407. await write(BLE.BLE_Client_T_REALTIMESTEP, mode ? Uint8List.fromList([BLE_CODE_1]) : Uint8List.fromList([BLE_CODE_0]));
  1408. stepRealTimeTimer?.cancel();
  1409. if (mode == true) {
  1410. stepRealTimeTimer = Timer.periodic(Duration(seconds: 10), (timer) {
  1411. write(BLE.BLE_Client_T_REALTIMESTEP, Uint8List.fromList([BLE_CODE_1]));
  1412. });
  1413. }
  1414. }
  1415. Uint8List createTime(int cmd) {
  1416. DateTime now = DateTime.now();
  1417. DateTime offset = DateTime(now.year, now.month, now.day, now.hour);
  1418. print("bluetooth -- create now .. $now - $offset (${offset.millisecondsSinceEpoch})");
  1419. ByteDataWriter writer = ByteDataWriter();
  1420. writer.writeUint8(cmd);
  1421. writer.writeUint64(offset.millisecondsSinceEpoch);
  1422. writer.writeUint8(max(0, min(60, now.minute - offset.minute)));
  1423. return writer.toBytes();
  1424. }
  1425. Future write(int cmd, Uint8List data, {int test = 5}) async {
  1426. if (characteristicWrite == null) return;
  1427. int length = data.length + 5;
  1428. ByteDataWriter writer = ByteDataWriter();
  1429. writer.writeUint8(0xAA);
  1430. // writer.writeUint8(0xBB);
  1431. // writer.writeUint8(0xCC);
  1432. writer.writeUint8(length);
  1433. writer.writeUint8(0xFF - length);
  1434. // writer.writeUint8(0x00);
  1435. writer.writeUint8(cmd);
  1436. if (data.isNotEmpty) writer.write(data);
  1437. int ver = writer.toBytes().reduce((value, element) => value + element);
  1438. writer.writeUint8(ver);
  1439. Uint8List out = writer.toBytes();
  1440. if (isDebugShoe) {
  1441. print("bluetooth -- out ${cmd.toRadixString(16).padLeft(2, "0")} ${out.map((e) => e.toRadixString(16).padLeft(2, "0")).join(" ").toUpperCase()}");
  1442. }
  1443. // print("out ${out.map((e) => e.toRadixString(16)).join(",")}");
  1444. for (var i = 0; i < test; i++) {
  1445. try {
  1446. await flutterReactiveBle.writeCharacteristicWithoutResponse(characteristicWrite!, value: out);
  1447. break;
  1448. } catch (e) {
  1449. print(e);
  1450. await Future.delayed(Duration(milliseconds: 100));
  1451. }
  1452. }
  1453. }
  1454. Future writeUintList(Uint8List data) async {
  1455. if (characteristicWrite == null) return;
  1456. int length = data.length + 4;
  1457. ByteDataWriter writer = ByteDataWriter();
  1458. writer.writeUint8(0xAA);
  1459. // writer.writeUint8(0xBB);
  1460. // writer.writeUint8(0xCC);
  1461. writer.writeUint8(length);
  1462. writer.writeUint8(0xFF - length);
  1463. // writer.writeUint8(0x00);
  1464. if (data.isNotEmpty) writer.write(data);
  1465. int ver = writer.toBytes().reduce((value, element) => value + element);
  1466. writer.writeUint8(ver);
  1467. Uint8List out = writer.toBytes();
  1468. if (isDebugShoe) {
  1469. print("bluetooth -- out ${out.map((e) => e.toRadixString(16).padLeft(2, "0")).join(" ").toUpperCase()}");
  1470. }
  1471. for (var i = 0; i < 5; i++) {
  1472. try {
  1473. await flutterReactiveBle.writeCharacteristicWithoutResponse(characteristicWrite!, value: out);
  1474. break;
  1475. } catch (e) {
  1476. print(e);
  1477. await Future.delayed(Duration(milliseconds: 100));
  1478. }
  1479. }
  1480. }
  1481. _uploadLog() async {
  1482. var info = infoNotifier.value;
  1483. if (info.isEmpty == true) return;
  1484. final api = GetIt.I<RestClient>();
  1485. PackageInfo packageInfo = await PackageInfo.fromPlatform();
  1486. String os_name = Platform.operatingSystem;
  1487. String os_ver = Platform.operatingSystemVersion;
  1488. String phone_brand = "";
  1489. String phone_model = "";
  1490. try {
  1491. DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
  1492. if (Platform.isAndroid) {
  1493. AndroidDeviceInfo androidDeviceInfo = await deviceInfo.androidInfo;
  1494. phone_brand = androidDeviceInfo.brand;
  1495. phone_model = androidDeviceInfo.model;
  1496. } else if (Platform.isIOS) {
  1497. IosDeviceInfo iosDeviceInfo = await deviceInfo.iosInfo;
  1498. phone_brand = iosDeviceInfo.model;
  1499. phone_model = iosDeviceInfo.utsname.machine;
  1500. }
  1501. } catch (e) {
  1502. print(e);
  1503. }
  1504. api.onConnBt("${info['mac']}", "${info['softwareVer']}", "${info['hardwareVer']}", "${packageInfo.version}+${packageInfo.buildNumber}", os_name, os_ver, "${locale?.languageCode}", phone_brand, phone_model).then((value) => _uploadLoged = true);
  1505. }
  1506. _testErrLog() async {
  1507. Directory? dir = Platform.isAndroid ? await getExternalStorageDirectory() : await getTemporaryDirectory();
  1508. if (dir != null) {
  1509. var now = DateTime.now();
  1510. File file = File("${dir.path}/shoe/err_${now.year}_${now.month}_${now.day}.csv");
  1511. print("log file: $file $errQueue");
  1512. if (!file.parent.existsSync()) {
  1513. file.parent.createSync();
  1514. }
  1515. errQueue.forEach((k, v) {
  1516. file.writeAsStringSync("$k, $v\n", mode: FileMode.append, flush: true);
  1517. });
  1518. }
  1519. }
  1520. void _testElectricity(Map<String, dynamic> info) async {
  1521. Directory? dir = Platform.isAndroid ? await getExternalStorageDirectory() : await getTemporaryDirectory();
  1522. if (dir != null) {
  1523. var now = DateTime.now();
  1524. File file = File("${dir.path}/shoe/electricity_${now.year}_${now.month}_${now.day}.csv");
  1525. print("log file: $file");
  1526. if (!file.parent.existsSync()) {
  1527. file.parent.createSync();
  1528. }
  1529. file.writeAsStringSync("${now.hour},${now.minute},${now.second},${info['0_electricity']},${info['1_electricity']},${info['0_adc']},${info['1_adc']},${_connectingDevice?.name ?? deviceId}\n", mode: FileMode.append, flush: true);
  1530. }
  1531. }
  1532. void _testStep(String line) async {
  1533. Directory? dir = Platform.isAndroid ? await getExternalStorageDirectory() : await getTemporaryDirectory();
  1534. if (dir != null) {
  1535. var now = DateTime.now();
  1536. File file = File("${dir.path}/shoe/step_${now.year}_${now.month}_${now.day}.csv");
  1537. print("log file: $file");
  1538. if (!file.parent.existsSync()) {
  1539. file.parent.createSync();
  1540. }
  1541. file.writeAsStringSync("$line\n", mode: FileMode.append, flush: true);
  1542. }
  1543. }
  1544. void updateName(String name) {
  1545. DiscoveredDevice? device = deviceNotifier.value;
  1546. if (device != null) {
  1547. String newName = name.isNotEmpty ? name : device.name;
  1548. BluetoothDB().insert(device, mark: newName).then((value) {
  1549. deviceNameNotifier.value = newName;
  1550. });
  1551. }
  1552. }
  1553. }
  1554. class PartItem {
  1555. String shoe;
  1556. int step;
  1557. int distance;
  1558. int absolute;
  1559. int time;
  1560. PartItem(this.shoe, this.step, this.absolute, this.distance, this.time);
  1561. Map<String, dynamic> toJson() {
  1562. final Map<String, dynamic> data = new Map<String, dynamic>();
  1563. data['shoe'] = this.shoe;
  1564. data['step'] = this.step;
  1565. data['absolute'] = this.absolute;
  1566. data['distance'] = this.distance;
  1567. data['time'] = this.time;
  1568. return data;
  1569. }
  1570. }
  1571. class PartInfo {
  1572. String shoeId;
  1573. int start;
  1574. int serial = 0;
  1575. int serialCount;
  1576. List<PartItem> items = [];
  1577. late DateTime now;
  1578. late DateTime maxTime;
  1579. late Map<int, List<int>> data;
  1580. bool ready = false;
  1581. PartInfo(this.shoeId, this.start, this.serialCount) {
  1582. now = DateTime.now();
  1583. maxTime = DateTime(now.year, now.month, now.day, now.hour);
  1584. data = {};
  1585. }
  1586. final int offset = 60 * 60 * 1000;
  1587. prepare() async {
  1588. print("bluetooth -- step prepare ... ");
  1589. if (data.isEmpty) return;
  1590. if (start == 0) return;
  1591. var current = data[0] ?? [];
  1592. if (current.isEmpty) return;
  1593. int currentStep = current.first;
  1594. print("bluetooth -- step current ... $currentStep");
  1595. if (currentStep >= 2147483647) {
  1596. if (data.values.where((element) => element.first >= 2147483647).length <= 1) {
  1597. return;
  1598. }
  1599. }
  1600. var db = StepDB();
  1601. var history = await db.findHistory(start, shoeId);
  1602. print("bluetooth -- step history ... $start $history");
  1603. int startStep = 0;
  1604. var p = PartItem(shoeId, 0, currentStep, 0, start - offset);
  1605. if (history.isNotEmpty == true) {
  1606. startStep = history.first['st'];
  1607. if (startStep > currentStep) {
  1608. await db.deleteAll();
  1609. print("bluetooth -- history ... clear");
  1610. startStep = currentStep;
  1611. await db.insert(p);
  1612. print("bluetooth -- step add history ... ${p.toJson()}");
  1613. }
  1614. } else {
  1615. startStep = currentStep;
  1616. await db.insert(p);
  1617. print("bluetooth -- step add history ... ${p.toJson()}");
  1618. }
  1619. data[data.length] = current;
  1620. for (var i = 1; i < data.length; i++) {
  1621. var list = data[i] ?? [];
  1622. for (int e in list) {
  1623. int time = start + items.length * offset;
  1624. int step = max(0, e - startStep);
  1625. print("bluetooth -- step add $time $e s:$startStep step:$step");
  1626. items.add(PartItem(shoeId, step, e, 0, min(time, maxTime.millisecondsSinceEpoch)));
  1627. startStep = e;
  1628. }
  1629. }
  1630. }
  1631. }