bluetooth.js 13 KB

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