bluetooth.js 23 KB

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