bluetooth.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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. export default {
  7. // 打开大包数据
  8. sendOpenBigData() {
  9. this.WriteBufferInBle("03 00 00 00 ff");
  10. },
  11. // 关闭大包数据
  12. sendCloseBigData() {
  13. this.WriteBufferInBle("03 00 00 00 00");
  14. },
  15. //获取当前连接的教具类型
  16. sendGetToyType() {
  17. this.WriteBufferInBle("03 00 00 00 06");
  18. },
  19. // 开启脑控
  20. sendControl() {
  21. this.WriteBufferInBle("03 00 00 00 07");
  22. },
  23. //暂停脑控
  24. sendControlPause() {
  25. //AA CC 03 00 00 00 09 F3
  26. this.WriteBufferInBle("03 00 00 00 08");
  27. },
  28. // 关闭脑控
  29. sendControlClose() {
  30. this.WriteBufferInBle("03 00 00 00 09");
  31. },
  32. //发送一对多连接
  33. sendConnectOneToMore(id) {
  34. this.WriteBufferInBle(`03 00 ${id} 00 0A`);
  35. },
  36. //发送一对一连接
  37. sendConnectOneToOne(id) {
  38. this.WriteBufferInBle(`03 00 ${id} 01 0A`)
  39. },
  40. // 获取大包数据 进行绘制图表
  41. get_big_data(hex) {
  42. if (hex.substr(0, 6) != "555520") {
  43. return false;
  44. }
  45. //当s1为 00时 数据有效
  46. let $s1 = hex.substr(8, 2);
  47. if ($s1 != "00") {
  48. return false;
  49. }
  50. //专注度数据
  51. let $att = parseInt("0x" + hex.substr(12, 2));
  52. //放松度数据
  53. let $med = parseInt("0x" + hex.substr(16, 2));
  54. //Delta数据
  55. let $delta_1 = hex.substr(hex.indexOf("0418") + 4, 2);
  56. let $delta_2 = hex.substr(hex.indexOf("0418") + 6, 2);
  57. let $delta_3 = hex.substr(hex.indexOf("0418") + 8, 2);
  58. let $delta = parseInt($delta_1 + $delta_2 + $delta_3, 16);
  59. //Theta数据
  60. let $theta_1 = hex.substr(hex.indexOf("0418") + 10, 2);
  61. let $theta_2 = hex.substr(hex.indexOf("0418") + 12, 2);
  62. let $theta_3 = hex.substr(hex.indexOf("0418") + 14, 2);
  63. let $theta = parseInt($theta_1 + $theta_2 + $theta_3, 16);
  64. //low_Alpha
  65. let $low_alpha_1 = hex.substr(hex.indexOf("0418") + 16, 2);
  66. let $low_alpha_2 = hex.substr(hex.indexOf("0418") + 18, 2);
  67. let $low_alpha_3 = hex.substr(hex.indexOf("0418") + 20, 2);
  68. let $low_alpha = parseInt($low_alpha_1 + $low_alpha_2 + $low_alpha_3, 16);
  69. //high_Alpha
  70. let $high_alpha_1 = hex.substr(hex.indexOf("0418") + 22, 2);
  71. let $high_alpha_2 = hex.substr(hex.indexOf("0418") + 24, 2);
  72. let $high_alpha_3 = hex.substr(hex.indexOf("0418") + 26, 2);
  73. let $high_alpha = parseInt($high_alpha_1 + $high_alpha_2 + $high_alpha_3, 16);
  74. //low_beta
  75. let $low_beta_1 = hex.substr(hex.indexOf("0418") + 28, 2);
  76. let $low_beta_2 = hex.substr(hex.indexOf("0418") + 30, 2);
  77. let $low_beta_3 = hex.substr(hex.indexOf("0418") + 32, 2);
  78. let $low_beta = parseInt($low_beta_1 + $low_beta_2 + $low_beta_3, 16);
  79. //high_beta
  80. let $high_beta_1 = hex.substr(hex.indexOf("0418") + 34, 2);
  81. let $high_beta_2 = hex.substr(hex.indexOf("0418") + 36, 2);
  82. let $high_beta_3 = hex.substr(hex.indexOf("0418") + 38, 2);
  83. let $high_beta = parseInt($high_beta_1 + $high_beta_2 + $high_beta_3, 16);
  84. let $max_num = 30000;
  85. return {
  86. att: $att,
  87. med: $med,
  88. delta: $delta >= $max_num ? $max_num : $delta,
  89. theta: $theta >= $max_num ? $max_num : $theta,
  90. low_alpha: $low_alpha >= $max_num ? $max_num : $low_alpha,
  91. high_alpha: $high_alpha >= $max_num ? $max_num : $high_alpha,
  92. low_beta: $low_beta >= $max_num ? $max_num : $low_beta,
  93. high_beta: $high_beta >= $max_num ? $max_num : $high_beta
  94. };
  95. },
  96. //获取设备电量
  97. get_device_elc(hex) {
  98. if (hex.substr(0, 8) != "55550203") {
  99. return false;
  100. }
  101. let $power = parseInt("0x" + hex.substr(8, 2));
  102. return $power;
  103. },
  104. // 监听蓝牙连接状态
  105. watch_bluetooth_status($that) {
  106. let that = this;
  107. // 微信自身监听低功耗蓝牙连接状态的改变事件
  108. wx.onBLEConnectionStateChange((res) => {
  109. // 该方法回调中可以用于处理连接意外断开等异常情况
  110. ble_store.setters.setBluetoothLinkStatus(res.connected);
  111. if (res.connected == false) {
  112. //断开玩具连接
  113. try {
  114. $that.change_toy_connect_status(0);
  115. //断开蓝牙连接
  116. $that.change_device_status(0);
  117. } catch (e) {
  118. console.log("方法不存在");
  119. }
  120. //判断游戏是否游戏中
  121. let $game_status = game_store.getters.getGameStatus();
  122. if ($game_status == 1) {
  123. // $that.game_finished();
  124. //清除状态 设置为默认初始状态 0 小乌龟
  125. Notify({
  126. type: 'danger',
  127. duration: 0,
  128. message: '智脑环已断开连接,请重新扫码智脑环'
  129. });
  130. // game_store.setters.setGameStatus(0);
  131. // 结束状态更改为1
  132. game_store.setters.setGameCloseStatus(1);
  133. }
  134. }
  135. });
  136. },
  137. //获取蓝牙设备服务
  138. getBLEDeviceServices(deviceId) {
  139. const $this = this;
  140. wx.getBLEDeviceServices({
  141. deviceId,
  142. success: (res) => {
  143. for (let i = 0; i < res.services.length; i++) {
  144. console.log("serviceItem:" + res.services[i].uuid);
  145. if (res.services[i].uuid.indexOf('6E') != -1 || res.services[i].uuid.indexOf('0000FFF0') != -1) {
  146. console.log("SelectedServiceItem:" + res.services[i].uuid);
  147. $this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid);
  148. return;
  149. }
  150. }
  151. },
  152. fail(res) {
  153. console.log("连接蓝牙成功,获取服务失败");
  154. },
  155. });
  156. },
  157. //获取蓝牙设备某个服务中所有特征值
  158. getBLEDeviceCharacteristics(deviceId, serviceId) {
  159. console.log(deviceId, serviceId);
  160. const $this = this;
  161. wx.getBLEDeviceCharacteristics({
  162. deviceId,
  163. serviceId,
  164. success: (res) => {
  165. console.log("getBLEDeviceCharacteristics success", res.characteristics);
  166. for (let i = 0; i < res.characteristics.length; i++) {
  167. let item = res.characteristics[i];
  168. if (item.properties.read) {
  169. wx.readBLECharacteristicValue({
  170. deviceId,
  171. serviceId,
  172. characteristicId: item.uuid,
  173. });
  174. }
  175. if (item.properties.write) {
  176. $this.deviceId = deviceId;
  177. $this.serviceId = serviceId;
  178. $this.cid = item.uuid;
  179. game_store.setters.setDeviceId(deviceId);
  180. game_store.setters.setServiceId(serviceId);
  181. game_store.setters.setCid(item.uuid);
  182. //打开数据帧
  183. $this.sendOpenBigData();
  184. }
  185. if (item.properties.notify || item.properties.indicate) {
  186. wx.notifyBLECharacteristicValueChange({
  187. deviceId,
  188. serviceId,
  189. characteristicId: item.uuid,
  190. state: true,
  191. });
  192. }
  193. }
  194. },
  195. fail(res) {
  196. console.error("getBLEDeviceCharacteristics", res);
  197. },
  198. });
  199. },
  200. // ArrayBuffer转16进度字符串示例
  201. ab2hex(buffer) {
  202. var hexArr = Array.prototype.map.call(
  203. new Uint8Array(buffer),
  204. function (bit) {
  205. return ("00" + bit.toString(16)).slice(-2);
  206. }
  207. );
  208. return hexArr.join("");
  209. },
  210. // 监听脑环是否带正
  211. watchingDevice($this) {
  212. const that = this;
  213. wx.onBLECharacteristicValueChange((characteristic) => {
  214. let hexStr = that.ab2hex(characteristic.value);
  215. if (hexStr.toUpperCase().indexOf("AADD")!=-1){
  216. console.log(hexStr);
  217. }
  218. let $data = that.get_big_data(hexStr);
  219. let $game_status = game_store.getters.getGameStatus();
  220. // 2021年10月20日17:18:13 判断教具 连接
  221. if (hexStr.toUpperCase().indexOf("AADD0A") != -1) {
  222. //没连接上教具
  223. if (hexStr.toUpperCase().indexOf("AADD0A0000") != -1) {
  224. $this.change_toy_connect_status(3);
  225. return false;
  226. }
  227. let $hexAry = $this.current_hex.split(" ")
  228. // 03 00 01 00 0a
  229. // [2] [3]
  230. // 连接上教具
  231. if (new RegExp("00").test($hexAry[2]) == false) {
  232. if (new RegExp("00").test($hexAry[3]) == true) {
  233. that.sendConnectOneToOne($hexAry[2])
  234. $this.current_hex = `03 00 $hexAry[2] 01 0A`
  235. console.log("一对多")
  236. } else {
  237. console.log("一对一")
  238. $this.current_hex = "";
  239. wx.showToast({
  240. title: "已连接到" + $this.toy_item.name
  241. });
  242. $this.change_toy_connect_status(2);
  243. }
  244. }
  245. }
  246. //2021年10月21日16:30:07 获取教具电量
  247. if (hexStr.toUpperCase().indexOf("AADD8A") != -1) {//接收教具电量状态
  248. let $_hexStr = hexStr.substr(6);
  249. let $power = parseInt($_hexStr.substr(0, 2), 16)
  250. let $voltage = parseInt($_hexStr.substr(2, 2), 16)
  251. console.log("电量:" + $power)
  252. console.log("电压:" + $voltage / 10)
  253. $this.toy_power = $power;
  254. }
  255. //监听佩戴正确
  256. if (hexStr.substr(0, 6) == "555520") {
  257. //当s1为 00时 数据有效
  258. let $s1 = hexStr.substr(8, 2);
  259. // console.log("监听脑环是否带正:", $s1 == '00')
  260. $this.device_bg = $s1 == "00";
  261. }
  262. //2021年10月21日17:22:37
  263. //收到一次UUID就发送一次获取教具的电量
  264. //读取教具UUID
  265. if (hexStr.toUpperCase().indexOf("AADD84") != -1) {//接收UUID 5个字节
  266. let $_hexStr = hexStr.substr(6);
  267. let $datas = $_hexStr.substr(0, 10);
  268. if ($datas != "0000000000") {
  269. $this.toy_UUID = $datas;
  270. //读取教具电量
  271. that.SendOrder('8a')
  272. } else {
  273. //如果游戏中则重新连接
  274. if ($game_status == 1) {
  275. //先发UUID 再发id 02
  276. console.log($this.toy_UUID)
  277. console.log(`aa cc 03 00 ${$this.toy_hex} 02 0a`)
  278. } else {
  279. $this.toy_UUID = ""
  280. $this.toy_power = 0;
  281. }
  282. }
  283. }
  284. // 监听脑环电量
  285. let $power = that.get_device_elc(hexStr);
  286. if ($power) {
  287. //发送一次获取教具的UUID
  288. that.SendOrder("84");
  289. // console.log("当前脑环电量:", $power)
  290. $this.device_power = $power;
  291. }
  292. if ($power < 10 && $power > 0) {
  293. wx.showToast({
  294. title: "脑环电量不足",
  295. icon: "none",
  296. duration: 2000,
  297. success() {
  298. // $this.change_device_status(0);
  299. },
  300. });
  301. }
  302. //游戏中模块
  303. if ($game_status == 1 && $data) {
  304. try {
  305. if ($this.played_time > 0) {
  306. //自定义定时器
  307. $this.played_time -= 1;
  308. game_store.setters.setPlayedTime($this.played_time)
  309. $this.played_time_text = that.formatPlaySeconds($this.played_time);
  310. $this.do_datas($data);
  311. // if ($this.played_time_text.indexOf(":00") != -1 || $this.played_time_text.indexOf(":30") != -1) {
  312. // $this.post_data();
  313. // }
  314. }
  315. if ($this.played_time == 0) {
  316. $this.post_data();
  317. //判断是否隐藏 隐藏则不绘画
  318. that.sendControlClose();
  319. let $hide_status = game_store.getters.getHideStatus();
  320. if (!$hide_status) {
  321. $this.game_finished();
  322. }
  323. }
  324. } catch (e) {
  325. console.log("调用方法失败", e);
  326. }
  327. }
  328. });
  329. },
  330. // 游玩时间倒计时
  331. formatPlaySeconds(value) {
  332. // 字符串转数字
  333. var secondTime = parseInt(value); // 秒
  334. var minuteTime = 0; // 分
  335. if (secondTime > 60) {
  336. //如果秒数大于60,将秒数转换成整数
  337. //获取分钟,除以60取整数,得到整数分钟
  338. minuteTime = parseInt(secondTime / 60);
  339. //获取秒数,秒数取佘,得到整数秒数
  340. secondTime = parseInt(secondTime % 60);
  341. //如果分钟大于60,将分钟转换成小时
  342. }
  343. var result = "" + parseInt(secondTime);
  344. if (minuteTime > 0) {
  345. if (result.length == 1) {
  346. result = "0" + result;
  347. }
  348. if (parseInt(minuteTime).toString().length == 1) {
  349. minuteTime = "0" + parseInt(minuteTime);
  350. }
  351. result = "" + minuteTime + ":" + result;
  352. } else {
  353. result = "00:" + result;
  354. }
  355. return result;
  356. },
  357. //根据错误代码返回字符串信息
  358. GetopenBluetoothAdapterError(errCode) {
  359. let $errmsg = "";
  360. if (errCode == 10000) {
  361. $errmsg = "未初始化蓝牙适配器"
  362. }
  363. if (errCode == 10001) {
  364. $errmsg = "当前蓝牙适配器不可用"
  365. }
  366. if (errCode == 10002) {
  367. $errmsg = "没有找到指定设备"
  368. }
  369. if (errCode == 10003) {
  370. $errmsg = "连接失败"
  371. }
  372. if (errCode == 10006) {
  373. $errmsg = "当前连接已断开"
  374. }
  375. return $errmsg;
  376. },
  377. //写入buffer
  378. WriteBufferInBle($hex,$buffer_len = 8) {
  379. let $device_id = game_store.getters.getDeviceId();
  380. let $service_id = game_store.getters.getServiceId()
  381. let $charateristic = game_store.getters.getCharacterId();
  382. let $hex_header = "aa cc ";
  383. // let $hex = "03 00 01 00 0a";
  384. let $hex_sum = 0;
  385. let $hex_ary = $hex.split(" ");
  386. $hex_ary.forEach(($val, $index) => {
  387. $hex_sum += parseInt($val, 16);
  388. })
  389. let $checksum = ($hex_sum ^ parseInt($8f, 16)) & parseInt($ff, 16);
  390. $hex = $hex_header + $hex + " " + $checksum.toString(16);
  391. let buffer = new ArrayBuffer($buffer_len);
  392. let dataView = new DataView(buffer);
  393. $hex_ary = $hex.split(" ");
  394. $hex_ary.forEach(($val, $index) => {
  395. dataView.setUint8($index, parseInt($val, 16))
  396. })
  397. wx.writeBLECharacteristicValue({
  398. deviceId: $device_id,
  399. serviceId: $service_id,
  400. characteristicId: $charateristic,
  401. value: buffer,
  402. success: function (res) {
  403. console.log($hex + ',写入成功')
  404. },
  405. fail: function (err) {
  406. console.log($hex + "写入失败");
  407. console.log(err);
  408. },
  409. });
  410. },
  411. //写入指令
  412. SendOrder(id) {
  413. let $hexStr = `03 00 00 00 ${id}`;
  414. this.WriteBufferInBle($hexStr)
  415. },
  416. Send16Order(val, id) {
  417. let $str = val;
  418. let $str_ary = $str.split('');
  419. $str = "";
  420. $str_ary.forEach(($val, $index) => {
  421. $str += $val.charCodeAt().toString(16) + " "
  422. });
  423. $str = $str.substr(0, $str.length - 1)
  424. let $hexStr = "03 ff " + $str + ` ${id}`;
  425. this.WriteBufferInBle($hexStr, 16)
  426. },
  427. };