bluetooth.js 25 KB

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