bluetooth.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113
  1. import game_store from "../store/game";
  2. import ble_store from "../store/bluetooth";
  3. import Notify from "../../static/vant/notify/notify";
  4. import {LogInDb} from "@/requests/log";
  5. var $ff = "ff";
  6. var $8f = "ffffffff"
  7. var control_close = false
  8. var current_device_sn = ""
  9. //记录当前脑环的mac地址
  10. var current_device_mac = "";
  11. //记录教具连接状态
  12. var connect_toy = true;
  13. //记录教具连接的id
  14. var current_toy_id = "00";
  15. //记录教具的UUID
  16. var current_toy_UUID = "";
  17. //标记是否打开脑控
  18. var FlagOpenControl = false;
  19. var ToyPower = 0;
  20. //Math.round(new Date() / 1000)
  21. var logTime = "";
  22. var current_hex = "";
  23. var is_new = game_store.getters.getIsNew();
  24. //2021年11月10日14:59:38
  25. // 0为旧 1为新
  26. var services = [
  27. "6e400001-b5a3-f393-e0a9-e50e24dcca9e".toUpperCase(),
  28. "0000fff0-0000-1000-8000-00805f9b34fb".toUpperCase()
  29. ]
  30. var charateristics = [
  31. {
  32. notify: "6e400003-b5a3-f393-e0a9-e50e24dcca9e".toUpperCase(),
  33. write: "6e400002-b5a3-f393-e0a9-e50e24dcca9e".toUpperCase()
  34. },
  35. {
  36. notify: "0000fff1-0000-1000-8000-00805f9b34fb".toUpperCase(),
  37. write: "0000fff2-0000-1000-8000-00805f9b34fb".toUpperCase()
  38. },
  39. ]
  40. function getServicesAndCharateristc() {
  41. //获取当前设备名称
  42. // let $brainSn = game_store.getters.getDeviceSn();
  43. let $deviceId = game_store.getters.getDeviceId();
  44. let $serviceId = game_store.getters.getServiceId();
  45. let $index = services.indexOf($serviceId.toUpperCase())
  46. // let $index = $brainSn.toUpperCase().indexOf("JELLYFISH") != -1 ? 0 : 1;
  47. return {
  48. deviceId: $deviceId,
  49. service: "6e400001-b5a3-f393-e0a9-e50e24dcca9e".toUpperCase(),
  50. charateristic: charateristics[0]
  51. }
  52. }
  53. var update_state = true;
  54. //全局升级下标
  55. var update_index = 0;
  56. //序列下标1
  57. var update_seq1_index = 0;
  58. //序列下标2
  59. var update_seq2_index = 0;
  60. var totalBuffer = [];
  61. // 脑环model
  62. var model = "";
  63. //脑环固件版本
  64. var version = "";
  65. export default {
  66. //变量
  67. connect_toy, control_close, current_toy_id, current_toy_UUID, ToyPower, current_device_sn, is_new,
  68. /**
  69. * todo:打开大包数据
  70. */
  71. sendOpenBigData() {
  72. this.SendOrder('ff')
  73. },
  74. /**
  75. * todo:关闭大包数据
  76. */
  77. sendCloseBigData() {
  78. this.SendOrder('00')
  79. },
  80. /**
  81. * todo:获取当前连接的教具类型
  82. */
  83. sendGetToyType() {
  84. this.SendOrder('06')
  85. },
  86. /**
  87. * todo:开启脑控
  88. */
  89. sendControl() {
  90. let that = this;
  91. // 先发第一次
  92. that.SendOrder('07')
  93. wx.showLoading({
  94. title: "正在启动"
  95. })
  96. let $intv = setInterval(() => {
  97. if (FlagOpenControl) {
  98. //设置打开脑控为false
  99. FlagOpenControl = false;
  100. clearInterval($intv)
  101. wx.hideLoading()
  102. } else {
  103. that.SendOrder('07')
  104. }
  105. }, 3000)
  106. },
  107. /**
  108. * todo:关闭脑控
  109. */
  110. sendControlClose() {
  111. let that = this
  112. control_close = false;
  113. let $intv = setInterval(() => {
  114. if (!control_close) {
  115. that.SendOrder('09')
  116. //如果是jellyfish则发送00教具
  117. if (!is_new) {
  118. that.sendConnectOneToMore('00')
  119. }
  120. } else {
  121. //设置打开脑控为false
  122. FlagOpenControl = false;
  123. clearInterval($intv)
  124. //清空当前数据
  125. that.clearLocalDatas()
  126. }
  127. }, 1000)
  128. },
  129. /**
  130. * todo:发送一对多连接
  131. */
  132. sendConnectOneToMore(id) {
  133. this.WriteBufferInBle(`03 00 ${id} 00 0A`);
  134. },
  135. /**
  136. * todo:发送一对一连接
  137. */
  138. sendConnectOneToOne(id) {
  139. current_toy_id = id;
  140. this.WriteBufferInBle(`03 00 ${id} 01 0A`)
  141. },
  142. /**
  143. * todo:获取教具电量
  144. */
  145. sendToyPower() {
  146. let that = this;
  147. if (is_new) {
  148. let $connect_false_count = 0;
  149. let toy_intv = setInterval(() => {
  150. let $game_status = game_store.getters.getGameStatus();
  151. if (connect_toy) {
  152. that.SendOrder('8a')
  153. } else {
  154. if ($game_status != 1) {
  155. clearInterval(toy_intv)
  156. }
  157. }
  158. }, 3000)
  159. } else {
  160. console.log("旧脑环不支持获取教具电量")
  161. }
  162. },
  163. /**
  164. * todo:获取大包数据进行绘制图表
  165. */
  166. get_big_data(hex) {
  167. if (hex.substr(0, 6) != "555520") {
  168. return false;
  169. }
  170. //当s1为 00时 数据有效
  171. // let hex_str = hex.substr(hex.indexOf("555520"))
  172. // let $s1 = hex_str.substr(8, 2);
  173. let $s1 = hex.substr(8, 2);
  174. if ($s1 != "00") {
  175. return false;
  176. }
  177. //专注度数据
  178. let $att = parseInt("0x" + hex.substr(12, 2));
  179. //放松度数据
  180. let $med = parseInt("0x" + hex.substr(16, 2));
  181. //Delta数据
  182. let $delta_1 = hex.substr(hex.indexOf("0418") + 4, 2);
  183. let $delta_2 = hex.substr(hex.indexOf("0418") + 6, 2);
  184. let $delta_3 = hex.substr(hex.indexOf("0418") + 8, 2);
  185. let $delta = parseInt($delta_1, 16) + parseInt($delta_2, 16) + parseInt($delta_3, 16);
  186. //Theta数据
  187. let $theta_1 = hex.substr(hex.indexOf("0418") + 10, 2);
  188. let $theta_2 = hex.substr(hex.indexOf("0418") + 12, 2);
  189. let $theta_3 = hex.substr(hex.indexOf("0418") + 14, 2);
  190. let $theta = parseInt($theta_1, 16) + parseInt($theta_2, 16) + parseInt($theta_3, 16);
  191. //low_Alpha
  192. let $low_alpha_1 = hex.substr(hex.indexOf("0418") + 16, 2);
  193. let $low_alpha_2 = hex.substr(hex.indexOf("0418") + 18, 2);
  194. let $low_alpha_3 = hex.substr(hex.indexOf("0418") + 20, 2);
  195. let $low_alpha = parseInt($low_alpha_1, 16) + parseInt($low_alpha_2, 16) + parseInt($low_alpha_3, 16);
  196. //high_Alpha
  197. let $high_alpha_1 = hex.substr(hex.indexOf("0418") + 22, 2);
  198. let $high_alpha_2 = hex.substr(hex.indexOf("0418") + 24, 2);
  199. let $high_alpha_3 = hex.substr(hex.indexOf("0418") + 26, 2);
  200. let $high_alpha = parseInt($high_alpha_1, 16) + parseInt($high_alpha_2, 16) + parseInt($high_alpha_3, 16);
  201. //low_beta
  202. let $low_beta_1 = hex.substr(hex.indexOf("0418") + 28, 2);
  203. let $low_beta_2 = hex.substr(hex.indexOf("0418") + 30, 2);
  204. let $low_beta_3 = hex.substr(hex.indexOf("0418") + 32, 2);
  205. let $low_beta = parseInt($low_beta_1, 16) + parseInt($low_beta_2, 16) + parseInt($low_beta_3, 16);
  206. //high_beta
  207. let $high_beta_1 = hex.substr(hex.indexOf("0418") + 34, 2);
  208. let $high_beta_2 = hex.substr(hex.indexOf("0418") + 36, 2);
  209. let $high_beta_3 = hex.substr(hex.indexOf("0418") + 38, 2);
  210. let $high_beta = parseInt($high_beta_1, 16) + parseInt($high_beta_2, 16) + parseInt($high_beta_3, 16);
  211. let $max_num = 30000;
  212. return {
  213. att: $att,
  214. med: $med,
  215. delta: $delta >= $max_num ? $max_num : $delta,
  216. theta: $theta >= $max_num ? $max_num : $theta,
  217. low_alpha: $low_alpha >= $max_num ? $max_num : $low_alpha,
  218. high_alpha: $high_alpha >= $max_num ? $max_num : $high_alpha,
  219. low_beta: $low_beta >= $max_num ? $max_num : $low_beta,
  220. high_beta: $high_beta >= $max_num ? $max_num : $high_beta
  221. };
  222. },
  223. /**
  224. * todo:获取设备电量
  225. */
  226. get_device_elc(hex) {
  227. if (hex.substr(0, 8) != "55550203") {
  228. return false;
  229. }
  230. let $power = parseInt("0x" + hex.substr(8, 2));
  231. return $power;
  232. },
  233. /**
  234. * todo:监听蓝牙连接状态
  235. */
  236. watch_bluetooth_status($this) {
  237. let that = this;
  238. // 微信自身监听低功耗蓝牙连接状态的改变事件
  239. wx.onBLEConnectionStateChange((res) => {
  240. // 该方法回调中可以用于处理连接意外断开等异常情况
  241. ble_store.setters.setBluetoothLinkStatus(res.connected);
  242. LogInDb(`${that.getNowTime()} 监听脑环断连`)
  243. if (res.connected == false) {
  244. //判断游戏是否游戏中
  245. let $game_status = game_store.getters.getGameStatus();
  246. if ($game_status == 1) {
  247. // $that.game_finished();
  248. Notify({
  249. type: 'danger',
  250. duration: 0,
  251. message: '智脑环已断开连接,正在尝试重新连接',
  252. onOpened() {
  253. that.reconnect(res.deviceId, $this)
  254. }
  255. });
  256. control_close = true
  257. // connect_toy = false;
  258. } else {
  259. //关闭脑控
  260. connect_toy = false;
  261. game_store.setters.setGameStatus(0);
  262. // 清空链接得设备 三值
  263. game_store.setters.clearDeviceToy();
  264. $this.connect_toy = 0;
  265. $this.connect_show = false;
  266. $this.device_bg = false;
  267. $this.change_toy_connect_status(0);
  268. $this.device_status = 0;
  269. $this.device = {}
  270. $this.toy_UUID = "";
  271. $this.$forceUpdate();
  272. wx.closeBluetoothAdapter();
  273. }
  274. }
  275. });
  276. },
  277. /**
  278. * todo:重新连接蓝牙
  279. */
  280. reconnect($deviceId, $this) {
  281. let that = this;
  282. let $deviceInfo = getServicesAndCharateristc();
  283. //重连的次数
  284. let $connect_count = 0;
  285. let $rec = setInterval(() => {
  286. let $game_status = game_store.getters.getGameStatus();
  287. if ($game_status == 1) {
  288. wx.createBLEConnection({
  289. deviceId: $deviceInfo.deviceId,
  290. success(res) {
  291. clearInterval($rec)
  292. Notify({type: 'success', message: `第${$connect_count}次重新连接成功`});
  293. LogInDb(`${that.getNowTime()}${$connect_count}次重新连接成功`)
  294. let $system = wx.getSystemInfoSync()
  295. if ($system.platform == 'ios') {
  296. that.getBLEDeviceServices($deviceInfo.deviceId)
  297. that.watchingDevice($this)
  298. } else {
  299. that.openNotify($this)
  300. that.watch_bluetooth_status($this);
  301. }
  302. // that.sendToyPower();
  303. },
  304. fail(res) {
  305. Notify({type: 'danger', message: `第${$connect_count}次重新连接失败`});
  306. game_store.setters.setGameCloseStatus(1);
  307. }
  308. })
  309. if ($connect_count >= 3) {
  310. $this.game_finished();
  311. clearInterval($rec)
  312. }
  313. $connect_count += 1;
  314. } else {
  315. clearInterval($rec)
  316. }
  317. }, 7000)
  318. },
  319. /**
  320. * todo 获取蓝牙设备服务
  321. * @param deviceId
  322. */
  323. getBLEDeviceServices(deviceId) {
  324. const that = this;
  325. current_device_mac = deviceId
  326. wx.getBLEDeviceServices({
  327. deviceId,
  328. success: (res) => {
  329. for (let i = 0; i < res.services.length; i++) {
  330. console.log("serviceItem:" + res.services[i].uuid);
  331. if (res.services[i].uuid.indexOf('6E') != -1 || res.services[i].uuid.indexOf('0000FFF0') != -1) {
  332. console.log("SelectedServiceItem:" + res.services[i].uuid);
  333. that.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid);
  334. game_store.setters.setServiceId(res.services[i].uuid)
  335. is_new = game_store.getters.getIsNew()
  336. return;
  337. }
  338. }
  339. },
  340. fail(res) {
  341. console.log("连接蓝牙成功,获取服务失败", res);
  342. },
  343. });
  344. },
  345. /**
  346. * todo 获取蓝牙设备某个服务中所有特征值
  347. */
  348. getBLEDeviceCharacteristics(deviceId, serviceId) {
  349. console.log(deviceId, serviceId);
  350. const $this = this;
  351. wx.getBLEDeviceCharacteristics({
  352. deviceId,
  353. serviceId,
  354. success: (res) => {
  355. console.log("getBLEDeviceCharacteristics success", res.characteristics);
  356. for (let i = 0; i < res.characteristics.length; i++) {
  357. let item = res.characteristics[i];
  358. let writeState = null;
  359. if (serviceId.indexOf("0001") != -1) {
  360. writeState = item.properties.write && item.uuid.indexOf("0002") != -1;
  361. } else {
  362. writeState = item.properties.write;
  363. }
  364. if (writeState) {
  365. // if (item.properties.write) {
  366. $this.deviceId = deviceId;
  367. $this.serviceId = serviceId;
  368. $this.cid = item.uuid;
  369. //打开数据帧
  370. $this.sendOpenBigData();
  371. }
  372. if (item.properties.notify || item.properties.indicate) {
  373. wx.notifyBLECharacteristicValueChange({
  374. deviceId,
  375. serviceId,
  376. characteristicId: item.uuid,
  377. state: true,
  378. });
  379. }
  380. }
  381. },
  382. fail(res) {
  383. console.error("getBLEDeviceCharacteristics", res);
  384. },
  385. });
  386. },
  387. openNotify($this) {
  388. let that = this;
  389. let $deviceInfo = getServicesAndCharateristc();
  390. console.log($deviceInfo)
  391. wx.notifyBLECharacteristicValueChange({
  392. deviceId: $deviceInfo.deviceId,
  393. serviceId: $deviceInfo.service,
  394. characteristicId: $deviceInfo.charateristic.notify,
  395. state: true,
  396. success() {
  397. that.watchingDevice($this)
  398. }
  399. });
  400. },
  401. /**
  402. * todo ArrayBuffer转16进度字符串示例
  403. * @param buffer
  404. * @returns {string}
  405. */
  406. ab2hex(buffer) {
  407. var hexArr = Array.prototype.map.call(
  408. new Uint8Array(buffer),
  409. function (bit) {
  410. return ("00" + bit.toString(16)).slice(-2);
  411. }
  412. );
  413. return hexArr.join("");
  414. },
  415. /**
  416. * todo 监听脑环数据
  417. * @param $this
  418. */
  419. watchingDevice($this) {
  420. const that = this;
  421. let DeviceId = game_store.getters.getDeviceId();
  422. wx.onBLECharacteristicValueChange((characteristic) => {
  423. // 获取脑环信号值
  424. wx.getBLEDeviceRSSI({
  425. deviceId: DeviceId,
  426. success(res) {
  427. if (game_store.getters.getGameStatus() == 1) {
  428. $this.rssi = res.RSSI;
  429. }
  430. }
  431. })
  432. let hexStr = that.ab2hex(characteristic.value);
  433. // console.log("数据", hexStr, "长度", hexStr.length / 2);
  434. if (hexStr.toUpperCase().indexOf("AADD") != -1 || hexStr.toUpperCase().indexOf("AAEE") != -1 && update_state == false) {
  435. let nowTime = Math.round(new Date() / 1000);
  436. console.log("应答", hexStr, '时间:' + that.getNowTime(), "长度", hexStr.length / 2);
  437. LogInDb(`${that.getNowTime()} 应答:${hexStr}`)
  438. }
  439. let $data = that.get_big_data(hexStr);
  440. let $game_status = game_store.getters.getGameStatus();
  441. // 教具断链
  442. if (hexStr.toUpperCase().indexOf("AAEE70") != -1) {
  443. connect_toy = false
  444. wx.showToast({
  445. title: "教具已断开",
  446. icon: "error"
  447. })
  448. LogInDb(`${that.getNowTime} 教具已断开`)
  449. //重连机制
  450. if ($game_status == 1) {
  451. $this.game_finished();
  452. }
  453. }
  454. if (hexStr.toUpperCase().indexOf("AAEE8A0000005A") != -1) {
  455. that.SendOrder("8a")
  456. }
  457. //防止在首页 连接的时候重复 选择教具 产生了发送多个教具电量
  458. // if(hexStr.toUpperCase().indexOf("AAEE8A000000FF76") != -1){
  459. // that.connect_toy = false;
  460. // }
  461. if (hexStr.toUpperCase().indexOf("AAEE07") != -1) {
  462. that.sendControl();
  463. }
  464. // 2021年10月20日17:18:13 判断教具 连接
  465. if (hexStr.toUpperCase().indexOf("AADD0A") != -1) {
  466. //没连接上教具
  467. if (hexStr.toUpperCase().indexOf("AADD0A0000") != -1) {
  468. if (is_new) {
  469. $this.change_toy_connect_status(3);
  470. }
  471. return false;
  472. }
  473. let $mHexStrIndex = hexStr.toUpperCase().indexOf("AADD0A");
  474. let $hex_index = hexStr.substr($mHexStrIndex + 28, 2)
  475. let $toy_id = hexStr.substr($mHexStrIndex + 8, 2)
  476. console.log("连接", $hex_index)
  477. console.log("玩具", $toy_id)
  478. // 连接上教具
  479. if (new RegExp("00").test($hex_index) == true) {
  480. if (is_new) {
  481. that.sendConnectOneToOne($toy_id)
  482. $this.current_hex = `03 00 ${$toy_id} 01 0A`
  483. console.log("一对多")
  484. } else {
  485. $this.current_hex = "";
  486. wx.showToast({
  487. title: "已连接到" + $this.toy_item.name
  488. });
  489. $this.toy_connected = true;
  490. $this.change_toy_connect_status(2);
  491. }
  492. }
  493. if (new RegExp("01").test($hex_index) == true) {
  494. console.log("一对一")
  495. $this.current_hex = "";
  496. wx.showToast({
  497. title: "已连接到" + $this.toy_item.name
  498. });
  499. $this.toy_connected = true;
  500. connect_toy = true;
  501. $this.change_toy_connect_status(2);
  502. //连接成功后 获取一次教具名称
  503. //TODO 2022-5-25 08:51:15 延迟发送教具UUID
  504. //2022年5月25日17:21:57 从2秒更换到3秒
  505. setTimeout(() => {
  506. that.SendOrder('87')
  507. }, 3000)
  508. // 更改为不断获取教具电量
  509. setTimeout(() => {
  510. that.sendToyPower();
  511. }, 5000)
  512. }
  513. if (new RegExp("02").test($hex_index) == true) {
  514. //发送教具连接
  515. connect_toy = true
  516. wx.hideLoading()
  517. wx.showToast({
  518. title: "教具重连成功"
  519. })
  520. that.sendControl()
  521. // that.sendToyPower();
  522. }
  523. }
  524. //2021年11月23日10:39:49
  525. // 获取教具名称
  526. if (hexStr.toUpperCase().indexOf("AADD87") != -1) {
  527. let $mHexStr = hexStr.substr(hexStr.toUpperCase().indexOf("AADD87"))
  528. let $datas = that.DoAnalysis($mHexStr, 10)
  529. let $number = $datas.match(/\d+/)
  530. let toy_list_pre = {'01': "SW", '02': "KL", '04': "SC", '05': "PP", '06': "SU", '09': "UF"}
  531. let $sn = toy_list_pre[current_toy_id] + $number;
  532. $this.toy_sn = $sn;
  533. //获取教具电量
  534. // that.SendOrder('8a')
  535. }
  536. if (hexStr.toUpperCase().indexOf("AAEE87") != -1) {
  537. //获取教具电量
  538. that.SendOrder('87')
  539. }
  540. //2021年10月21日16:30:07
  541. // 获取教具电量
  542. if (hexStr.toUpperCase().indexOf("AADD8A") != -1) {//接收教具电量状态
  543. let $_hexStr = hexStr.substr(hexStr.toUpperCase().indexOf("AADD8A") + 6);
  544. let $power = parseInt($_hexStr.substr(0, 2), 16)
  545. let $voltage = parseInt($_hexStr.substr(2, 2), 16)
  546. connect_toy = true;
  547. // $this.toy_power = Math.round(that.CalBLEPower($voltage));
  548. if ($power > 0) {
  549. $this.toy_power = $power
  550. $this.toy_voltage = $voltage
  551. ToyPower = $power;
  552. }
  553. //连接上教具的标识
  554. //FF为无效
  555. // 2022年5月10日15:55:34 已无效
  556. // if ($power != 0) {
  557. // connect_toy = true;
  558. // }
  559. // if (hexStr.toUpperCase().indexOf("FF") != -1) {
  560. // connect_toy = false;
  561. // }
  562. if (current_toy_UUID == "") {
  563. //获取教具UUID
  564. that.SendOrder('84')
  565. }
  566. }
  567. //监听佩戴正确
  568. if (hexStr.substr(0, 6) == "555520") {
  569. //当s1为 00时 数据有效
  570. let $s1 = hexStr.substr(8, 2);
  571. // console.log("监听脑环是否带正:", $s1 == '00')
  572. $this.device_bg = $s1 == "00";
  573. }
  574. // 2021年10月25日09:15:50
  575. // 读取教具UUID
  576. if (hexStr.toUpperCase().indexOf("AADD84") != -1) {//接收UUID 5个字节
  577. let $hex_index = hexStr.toUpperCase().indexOf("AADD84") + 6;
  578. let $datas = hexStr.substr($hex_index, 10);
  579. if ($datas != "0000000000") {
  580. console.log("以获取UUID:" + $datas)
  581. current_toy_UUID = $datas;
  582. $this.toy_UUID = $datas;
  583. }
  584. }
  585. if (hexStr.toUpperCase().indexOf("AADD09") != -1) {
  586. control_close = true;
  587. connect_toy = false;
  588. }
  589. //收到发送UUID的应答立马发送连接教具的指令
  590. if (hexStr.toUpperCase().indexOf("AADD8E") != -1) {
  591. //发送教具连接
  592. that.WriteBufferInBle(`03 00 ${current_toy_id} 02 0A`)
  593. }
  594. // 2021年11月10日14:34:26
  595. // 处理打开脑控的应答
  596. if (hexStr.toUpperCase().indexOf("AADD07") != -1) {
  597. ble_store.setters.setBluetoothLinkStatus(true)
  598. FlagOpenControl = true;
  599. }
  600. //todo 监听脑环电量
  601. if (hexStr.substr(0, 8) == "55550203") {
  602. let $power = parseInt(hexStr.substr(8, 2), 16);
  603. let $voltage = parseInt(hexStr.substr(10, 2), 16);
  604. //监听是否插入USB
  605. $this.hasUsb = $voltage.toString().substr(0, 1) == 1
  606. // 监听脑环电量
  607. if ($power) {
  608. // console.log("当前脑环电量:", $power)
  609. $this.device_power = $power;
  610. $this.device_voltage = $voltage;
  611. }
  612. if ($power < 10 && $power > 0) {
  613. wx.showToast({
  614. title: "脑环电量不足",
  615. icon: "none",
  616. duration: 2000,
  617. success() {
  618. // $this.change_device_status(0);
  619. },
  620. });
  621. }
  622. }
  623. // todo 监听ota升级
  624. if (hexStr.toUpperCase().indexOf("AADD30") != -1 || hexStr.toUpperCase().indexOf("AADD31") != -1) {
  625. if (hexStr.toUpperCase().indexOf("AADD30") != -1) {
  626. update_index = 0;
  627. update_seq1_index = 0;
  628. update_seq2_index = 0;
  629. update_state = true;
  630. totalBuffer = [];
  631. }
  632. // 开始升级、
  633. console.log("升级中")
  634. let buffer_len = 224
  635. if (update_state) {
  636. let total_index = Math.round($this.payload_len / buffer_len)
  637. let another_buffer_len = $this.payload_len % buffer_len;
  638. if (update_index < total_index) {
  639. that.SendUpdateData($this.buffers, $this.dec_index * 16 + update_index * buffer_len, buffer_len)
  640. } else {
  641. console.log(`update_index:${update_index}`,`total_index:${total_index}`)
  642. console.log("余:"+another_buffer_len)
  643. if (another_buffer_len > 0) {
  644. that.SendUpdateData($this.buffers, $this.dec_index * 16 + update_index * buffer_len, another_buffer_len)
  645. }
  646. update_state = false;
  647. }
  648. $this.progress = (update_index / total_index * 100).toFixed(2);
  649. } else {
  650. //更新结束
  651. that.FinishBleUpdate()
  652. console.log(`文件buffer长度:${$this.payload_len},总共发送totalBuffer:${totalBuffer.length}`)
  653. }
  654. }
  655. if (hexStr.toUpperCase().indexOf("AAEE31") != -1) {
  656. let $hexStr = `03 32 00 00 00`;
  657. this.WriteBufferInBle($hexStr)
  658. $this.AddContent("更新停止")
  659. }
  660. //游戏中模块
  661. if ($game_status == 1 && $data) {
  662. $this.do_datas($data);
  663. }
  664. //todo 监听收到更新结束
  665. if (hexStr.toUpperCase().indexOf("AADD33") != -1) {
  666. //发送重启脑环指令
  667. let $hexStr = `03 00 00 00 26`;
  668. this.WriteBufferInBle($hexStr)
  669. $this.step_active += 1;
  670. }
  671. //todo 监听收到脑环型号
  672. if (hexStr.toUpperCase().indexOf("AADD02") != -1) {
  673. hexStr = hexStr.substr(10, 20)
  674. for (let i = 0; i < hexStr.length; i += 2) {
  675. model += String.fromCharCode(parseInt(hexStr.substr(i, 2), 16));
  676. }
  677. console.log(`model:${model}`)
  678. this.SendOrder("03");
  679. }
  680. //todo 获取固件信息
  681. if (hexStr.toUpperCase().indexOf("AADD03") != -1) {
  682. hexStr = hexStr.substr(6, 24)
  683. for (let i = 0; i < hexStr.length; i += 2) {
  684. version += String.fromCharCode(parseInt(hexStr.substr(i, 2), 16));
  685. }
  686. $this.software_version = version
  687. console.log(`version:${version}`)
  688. let firmware_info = JSON.parse(wx.getStorageSync("firmware_info"))
  689. //todo 与数据库匹对固件升级
  690. if (model == firmware_info.model) {
  691. //版本不一样
  692. if (firmware_info.version != version) {
  693. //硬更/软更
  694. $this.force_update = firmware_info.status == 1;
  695. $this.remote_version = `V${firmware_info.version}`;
  696. $this.update_show = true
  697. }
  698. }
  699. }
  700. });
  701. },
  702. /**
  703. * todo 游玩时间倒计时
  704. * @param value
  705. * @returns {string}
  706. */
  707. formatPlaySeconds(value) {
  708. // 字符串转数字
  709. var secondTime = parseInt(value); // 秒
  710. var minuteTime = 0; // 分
  711. if (secondTime > 60) {
  712. //如果秒数大于60,将秒数转换成整数
  713. //获取分钟,除以60取整数,得到整数分钟
  714. minuteTime = parseInt(secondTime / 60);
  715. //获取秒数,秒数取佘,得到整数秒数
  716. secondTime = parseInt(secondTime % 60);
  717. //如果分钟大于60,将分钟转换成小时
  718. }
  719. var result = "" + parseInt(secondTime);
  720. if (minuteTime > 0) {
  721. if (result.length == 1) {
  722. result = "0" + result;
  723. }
  724. if (parseInt(minuteTime).toString().length == 1) {
  725. minuteTime = "0" + parseInt(minuteTime);
  726. }
  727. result = "" + minuteTime + ":" + result;
  728. } else {
  729. result = "00:" + result;
  730. }
  731. return result;
  732. },
  733. /**
  734. * todo 根据错误代码返回字符串信息
  735. * @param errCode
  736. * @returns {string}
  737. * @constructor
  738. */
  739. GetopenBluetoothAdapterError(errCode) {
  740. let $errmsg = "";
  741. if (errCode == 10000) {
  742. $errmsg = "未初始化蓝牙适配器"
  743. }
  744. if (errCode == 10001) {
  745. $errmsg = "当前蓝牙适配器不可用"
  746. }
  747. if (errCode == 10002) {
  748. $errmsg = "没有找到指定设备"
  749. }
  750. if (errCode == 10003) {
  751. $errmsg = "连接失败"
  752. }
  753. if (errCode == 10006) {
  754. $errmsg = "当前连接已断开"
  755. }
  756. return $errmsg;
  757. },
  758. /**
  759. * todo 写入buffer
  760. * @param $hex
  761. * @param $buffer_len
  762. * @constructor
  763. */
  764. WriteBufferInBle($hex, $buffer_len = 8) {
  765. let that = this;
  766. let $deviceInfo = getServicesAndCharateristc();
  767. let $hex_header = "aa cc ";
  768. // let $hex = "03 00 01 00 0a";
  769. let $hex_sum = 0;
  770. let $hex_ary = $hex.split(" ");
  771. $hex_ary.forEach(($val, $index) => {
  772. $hex_sum += parseInt($val, 16);
  773. })
  774. let $checksum = ($hex_sum ^ parseInt($8f, 16)) & parseInt($ff, 16);
  775. $hex = $hex_header + $hex + " " + ("00" + $checksum.toString(16)).substr(-2, 2);
  776. let buffer = new ArrayBuffer($buffer_len);
  777. let dataView = new DataView(buffer);
  778. $hex_ary = $hex.split(" ");
  779. $hex_ary.forEach(($val, $index) => {
  780. dataView.setUint8($index, parseInt($val, 16))
  781. })
  782. if (!$deviceInfo.charateristic.write) {
  783. return false;
  784. }
  785. wx.writeBLECharacteristicValue({
  786. deviceId: $deviceInfo.deviceId,
  787. serviceId: $deviceInfo.service,
  788. characteristicId: $deviceInfo.charateristic.write,
  789. value: buffer,
  790. success: function (res) {
  791. if ($buffer_len <= 16) {
  792. console.log($hex + ',写入成功,时间:' + that.getNowTime())
  793. } else {
  794. console.log('写入成功,时间:' + that.getNowTime())
  795. }
  796. // LogInDb(`${that.getNowTime()} ${$hex}',写入成功`)
  797. },
  798. fail: function (err) {
  799. console.log($hex + "写入失败", err);
  800. },
  801. });
  802. },
  803. /**
  804. * todo写入8位指令
  805. * @param id 末尾id
  806. * @constructor
  807. */
  808. SendOrder(id) {
  809. let $hexStr = `03 00 00 00 ${id}`;
  810. this.WriteBufferInBle($hexStr)
  811. },
  812. /**
  813. * todo 写入16个字节的指令
  814. * @param val
  815. * @param id
  816. * @constructor
  817. */
  818. Send16Order(val, id) {
  819. let $str = val;
  820. let $str_ary = $str.split('');
  821. $str = "";
  822. $str_ary.forEach(($val, $index) => {
  823. $str += $val.charCodeAt().toString(16) + " "
  824. });
  825. $str = $str.substr(0, $str.length - 1)
  826. let $hexStr = "03 ff " + $str + ` ${id}`;
  827. this.WriteBufferInBle($hexStr, 16)
  828. },
  829. /**
  830. * todo 解析hex
  831. * @param hexStr
  832. * @param byte_count
  833. * @param sublen
  834. * @returns {string}
  835. * @constructor
  836. */
  837. DoAnalysis(hexStr, byte_count, sublen = 6) {
  838. //byte_count
  839. let $_str5 = hexStr.substr(sublen);
  840. let $datas = $_str5.substr(0, byte_count * 2);
  841. let $_data = "";
  842. for (let $i = 0; $i < $datas.length; $i += 2) {
  843. let $code = parseInt($datas.substr($i, 2), 16)
  844. $_data += String.fromCharCode($code)
  845. }
  846. return $_data;
  847. },
  848. /**
  849. * todo 重连教具
  850. * @constructor
  851. */
  852. ReconnectToy() {
  853. current_device_mac = game_store.getters.getDeviceId();
  854. let $game_status = game_store.getters.getGameStatus();
  855. let that = this;
  856. try {
  857. //发送UUID
  858. let $uuid_str = "";
  859. for (let $i = 0; $i < current_toy_UUID.length; $i += 2) {
  860. $uuid_str += current_toy_UUID.substr($i, 2) + " ";
  861. }
  862. let _deviceId = "";
  863. let deviceIds = current_device_mac.split(':');
  864. for (let i = 0; i < deviceIds.length; i++) {
  865. if (i != 2) {
  866. _deviceId += deviceIds[i] + " ";
  867. }
  868. }
  869. let sum = $uuid_str + _deviceId;
  870. sum = sum.substr(0, sum.length - 1);
  871. let $hexStr = `03 ff ${sum} 8e`;
  872. let loop_count = 0;
  873. if ($game_status == 1) {
  874. wx.showLoading({
  875. title: "重新连接教具中"
  876. })
  877. }
  878. LogInDb(`${that.getNowTime()} 重新连接教具中`)
  879. let connect_toy_intv = setInterval(() => {
  880. $game_status = game_store.getters.getGameStatus();
  881. if ($game_status == 1) {
  882. if (connect_toy == false) {
  883. if (loop_count == 3) {
  884. wx.hideLoading()
  885. wx.showToast("教具已无法连接")
  886. clearInterval(connect_toy_intv)
  887. }
  888. loop_count += 1;
  889. // that.WriteBufferInBle(`03 00 ${current_toy_id} 02 0A`)
  890. // 发送教具UUID
  891. that.WriteBufferInBle($hexStr, 16)
  892. } else {
  893. wx.hideLoading()
  894. loop_count = 0;
  895. clearInterval(connect_toy_intv)
  896. }
  897. } else {
  898. wx.hideLoading()
  899. clearInterval(connect_toy_intv)
  900. }
  901. }, 3000)
  902. } catch (e) {
  903. console.log("ReconnectToy:", e)
  904. }
  905. },
  906. /**
  907. * todo 清空当前脚本的变量值
  908. */
  909. clearLocalDatas() {
  910. control_close = false
  911. connect_toy = false;
  912. current_toy_id = "00";
  913. current_toy_UUID = "";
  914. },
  915. /**
  916. * todo 计算电量
  917. * @param $voltage
  918. * @returns {number}
  919. * @constructor
  920. */
  921. CalBLEPower($voltage) {
  922. let $max = 4100;
  923. let $min = 3500;
  924. //(当前电压值(mV)-最低电压值(mV)) / (最大电压值(mV)-最低电压值(mV)) *100%
  925. //当前电压
  926. let $_voltage = $voltage * 100;
  927. // console.log(`计算的当前电压:${$_voltage}`)
  928. let $percent = (($_voltage - $min) / ($max - $min)) * 100;
  929. // console.log(`计算的电量:${$percent}`);
  930. return $percent;
  931. },
  932. getNowTime() {
  933. var date = new Date();
  934. const year = date.getFullYear();
  935. const month = date.getMonth() + 1;
  936. const day = date.getDate();
  937. const hour = date.getHours();
  938. const minutes = date.getMinutes();
  939. const seconds = date.getSeconds();
  940. const millSeconds = date.getMilliseconds();
  941. return `${year}/${month}/${day} ${hour}:${minutes}:${seconds}.${millSeconds}`;
  942. },
  943. /**
  944. * 自动发送RF重连
  945. * @param {Boolean} isOn 是否打开重连功能
  946. * @param {[type]} timeOut 有效时间
  947. * @return {[type]} [description]
  948. * AA CC 03 00 01 0a d0 21
  949. */
  950. sendAutoConnectRf(isOn, timeOut) {
  951. let that = this;
  952. let onVal = isOn ? '01' : '00';
  953. let mTimeOut = timeOut.toString(16);
  954. if (mTimeOut.length == 1) {
  955. mTimeOut = `0${mTimeOut}`
  956. }
  957. let $hexStr = `03 00 ${onVal} ${mTimeOut} d0`;
  958. this.WriteBufferInBle($hexStr)
  959. },
  960. /**
  961. * todo 发送升级数据
  962. * @param buffers 数据包
  963. * @param start_index 开始下标
  964. * @param speed 发送速率
  965. * @constructor
  966. */
  967. SendUpdateData(buffers, start_index, speed = 248) {
  968. let buffer = new Uint8Array(buffers, start_index, speed)
  969. let $hexStr = [
  970. '03',
  971. '31',
  972. `00${update_seq1_index.toString(16)}`.substr(-2, 2),
  973. `00${update_seq2_index.toString(16)}`.substr(-2, 2),
  974. speed.toString(16),
  975. ]
  976. for (let j = 0; j < speed; j++) {
  977. let $hex = ('00' + buffer[j].toString(16)).substr(-2, 2)
  978. $hexStr.push($hex)
  979. totalBuffer.push($hex)
  980. }
  981. this.WriteBufferInBle($hexStr.join(' '), $hexStr.length + 3)
  982. update_seq1_index += 1;
  983. update_index += 1;
  984. if (update_seq1_index == 256) {
  985. update_seq1_index = 0;
  986. update_seq2_index += 1;
  987. }
  988. },
  989. /**
  990. * 更新结束
  991. * @constructor
  992. */
  993. FinishBleUpdate() {
  994. let $hexStr = `03 33 00 00 00`;
  995. this.WriteBufferInBle($hexStr)
  996. },
  997. };