bluetooth.js 24 KB

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