123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113 |
- import game_store from "../store/game";
- import ble_store from "../store/bluetooth";
- import Notify from "../../static/vant/notify/notify";
- import {LogInDb} from "@/requests/log";
- var $ff = "ff";
- var $8f = "ffffffff"
- var control_close = false
- var current_device_sn = ""
- var current_device_mac = "";
- var connect_toy = true;
- var current_toy_id = "00";
- var current_toy_UUID = "";
- var FlagOpenControl = false;
- var ToyPower = 0;
- var logTime = "";
- var current_hex = "";
- var is_new = game_store.getters.getIsNew();
- var services = [
- "6e400001-b5a3-f393-e0a9-e50e24dcca9e".toUpperCase(),
- "0000fff0-0000-1000-8000-00805f9b34fb".toUpperCase()
- ]
- var charateristics = [
- {
- notify: "6e400003-b5a3-f393-e0a9-e50e24dcca9e".toUpperCase(),
- write: "6e400002-b5a3-f393-e0a9-e50e24dcca9e".toUpperCase()
- },
- {
- notify: "0000fff1-0000-1000-8000-00805f9b34fb".toUpperCase(),
- write: "0000fff2-0000-1000-8000-00805f9b34fb".toUpperCase()
- },
- ]
- function getServicesAndCharateristc() {
-
-
- let $deviceId = game_store.getters.getDeviceId();
- let $serviceId = game_store.getters.getServiceId();
- let $index = services.indexOf($serviceId.toUpperCase())
-
- return {
- deviceId: $deviceId,
- service: "6e400001-b5a3-f393-e0a9-e50e24dcca9e".toUpperCase(),
- charateristic: charateristics[0]
- }
- }
- var update_state = true;
- var update_index = 0;
- var update_seq1_index = 0;
- var update_seq2_index = 0;
- var totalBuffer = [];
- var model = "";
- var version = "";
- export default {
-
- connect_toy, control_close, current_toy_id, current_toy_UUID, ToyPower, current_device_sn, is_new,
-
- sendOpenBigData() {
- this.SendOrder('ff')
- },
-
- sendCloseBigData() {
- this.SendOrder('00')
- },
-
- sendGetToyType() {
- this.SendOrder('06')
- },
-
- sendControl() {
- let that = this;
-
- that.SendOrder('07')
- wx.showLoading({
- title: "正在启动"
- })
- let $intv = setInterval(() => {
- if (FlagOpenControl) {
-
- FlagOpenControl = false;
- clearInterval($intv)
- wx.hideLoading()
- } else {
- that.SendOrder('07')
- }
- }, 3000)
- },
-
- sendControlClose() {
- let that = this
- control_close = false;
- let $intv = setInterval(() => {
- if (!control_close) {
- that.SendOrder('09')
-
- if (!is_new) {
- that.sendConnectOneToMore('00')
- }
- } else {
-
- FlagOpenControl = false;
- clearInterval($intv)
-
- that.clearLocalDatas()
- }
- }, 1000)
- },
-
- sendConnectOneToMore(id) {
- this.WriteBufferInBle(`03 00 ${id} 00 0A`);
- },
-
- sendConnectOneToOne(id) {
- current_toy_id = id;
- this.WriteBufferInBle(`03 00 ${id} 01 0A`)
- },
-
- sendToyPower() {
- let that = this;
- if (is_new) {
- let $connect_false_count = 0;
- let toy_intv = setInterval(() => {
- let $game_status = game_store.getters.getGameStatus();
- if (connect_toy) {
- that.SendOrder('8a')
- } else {
- if ($game_status != 1) {
- clearInterval(toy_intv)
- }
- }
- }, 3000)
- } else {
- console.log("旧脑环不支持获取教具电量")
- }
- },
-
- get_big_data(hex) {
- if (hex.substr(0, 6) != "555520") {
- return false;
- }
-
-
-
- let $s1 = hex.substr(8, 2);
- if ($s1 != "00") {
- return false;
- }
-
- let $att = parseInt("0x" + hex.substr(12, 2));
-
- let $med = parseInt("0x" + hex.substr(16, 2));
-
- let $delta_1 = hex.substr(hex.indexOf("0418") + 4, 2);
- let $delta_2 = hex.substr(hex.indexOf("0418") + 6, 2);
- let $delta_3 = hex.substr(hex.indexOf("0418") + 8, 2);
- let $delta = parseInt($delta_1, 16) + parseInt($delta_2, 16) + parseInt($delta_3, 16);
-
- let $theta_1 = hex.substr(hex.indexOf("0418") + 10, 2);
- let $theta_2 = hex.substr(hex.indexOf("0418") + 12, 2);
- let $theta_3 = hex.substr(hex.indexOf("0418") + 14, 2);
- let $theta = parseInt($theta_1, 16) + parseInt($theta_2, 16) + parseInt($theta_3, 16);
-
- let $low_alpha_1 = hex.substr(hex.indexOf("0418") + 16, 2);
- let $low_alpha_2 = hex.substr(hex.indexOf("0418") + 18, 2);
- let $low_alpha_3 = hex.substr(hex.indexOf("0418") + 20, 2);
- let $low_alpha = parseInt($low_alpha_1, 16) + parseInt($low_alpha_2, 16) + parseInt($low_alpha_3, 16);
-
- let $high_alpha_1 = hex.substr(hex.indexOf("0418") + 22, 2);
- let $high_alpha_2 = hex.substr(hex.indexOf("0418") + 24, 2);
- let $high_alpha_3 = hex.substr(hex.indexOf("0418") + 26, 2);
- let $high_alpha = parseInt($high_alpha_1, 16) + parseInt($high_alpha_2, 16) + parseInt($high_alpha_3, 16);
-
- let $low_beta_1 = hex.substr(hex.indexOf("0418") + 28, 2);
- let $low_beta_2 = hex.substr(hex.indexOf("0418") + 30, 2);
- let $low_beta_3 = hex.substr(hex.indexOf("0418") + 32, 2);
- let $low_beta = parseInt($low_beta_1, 16) + parseInt($low_beta_2, 16) + parseInt($low_beta_3, 16);
-
- let $high_beta_1 = hex.substr(hex.indexOf("0418") + 34, 2);
- let $high_beta_2 = hex.substr(hex.indexOf("0418") + 36, 2);
- let $high_beta_3 = hex.substr(hex.indexOf("0418") + 38, 2);
- let $high_beta = parseInt($high_beta_1, 16) + parseInt($high_beta_2, 16) + parseInt($high_beta_3, 16);
- let $max_num = 30000;
- return {
- att: $att,
- med: $med,
- delta: $delta >= $max_num ? $max_num : $delta,
- theta: $theta >= $max_num ? $max_num : $theta,
- low_alpha: $low_alpha >= $max_num ? $max_num : $low_alpha,
- high_alpha: $high_alpha >= $max_num ? $max_num : $high_alpha,
- low_beta: $low_beta >= $max_num ? $max_num : $low_beta,
- high_beta: $high_beta >= $max_num ? $max_num : $high_beta
- };
- },
-
- get_device_elc(hex) {
- if (hex.substr(0, 8) != "55550203") {
- return false;
- }
- let $power = parseInt("0x" + hex.substr(8, 2));
- return $power;
- },
-
- watch_bluetooth_status($this) {
- let that = this;
-
- wx.onBLEConnectionStateChange((res) => {
-
- ble_store.setters.setBluetoothLinkStatus(res.connected);
- LogInDb(`${that.getNowTime()} 监听脑环断连`)
- if (res.connected == false) {
-
- let $game_status = game_store.getters.getGameStatus();
- if ($game_status == 1) {
-
- Notify({
- type: 'danger',
- duration: 0,
- message: '智脑环已断开连接,正在尝试重新连接',
- onOpened() {
- that.reconnect(res.deviceId, $this)
- }
- });
- control_close = true
-
- } else {
-
- connect_toy = false;
- game_store.setters.setGameStatus(0);
-
- game_store.setters.clearDeviceToy();
- $this.connect_toy = 0;
- $this.connect_show = false;
- $this.device_bg = false;
- $this.change_toy_connect_status(0);
- $this.device_status = 0;
- $this.device = {}
- $this.toy_UUID = "";
- $this.$forceUpdate();
- wx.closeBluetoothAdapter();
- }
- }
- });
- },
-
- reconnect($deviceId, $this) {
- let that = this;
- let $deviceInfo = getServicesAndCharateristc();
-
- let $connect_count = 0;
- let $rec = setInterval(() => {
- let $game_status = game_store.getters.getGameStatus();
- if ($game_status == 1) {
- wx.createBLEConnection({
- deviceId: $deviceInfo.deviceId,
- success(res) {
- clearInterval($rec)
- Notify({type: 'success', message: `第${$connect_count}次重新连接成功`});
- LogInDb(`${that.getNowTime()} 第${$connect_count}次重新连接成功`)
- let $system = wx.getSystemInfoSync()
- if ($system.platform == 'ios') {
- that.getBLEDeviceServices($deviceInfo.deviceId)
- that.watchingDevice($this)
- } else {
- that.openNotify($this)
- that.watch_bluetooth_status($this);
- }
-
- },
- fail(res) {
- Notify({type: 'danger', message: `第${$connect_count}次重新连接失败`});
- game_store.setters.setGameCloseStatus(1);
- }
- })
- if ($connect_count >= 3) {
- $this.game_finished();
- clearInterval($rec)
- }
- $connect_count += 1;
- } else {
- clearInterval($rec)
- }
- }, 7000)
- },
-
- getBLEDeviceServices(deviceId) {
- const that = this;
- current_device_mac = deviceId
- wx.getBLEDeviceServices({
- deviceId,
- success: (res) => {
- for (let i = 0; i < res.services.length; i++) {
- console.log("serviceItem:" + res.services[i].uuid);
- if (res.services[i].uuid.indexOf('6E') != -1 || res.services[i].uuid.indexOf('0000FFF0') != -1) {
- console.log("SelectedServiceItem:" + res.services[i].uuid);
- that.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid);
- game_store.setters.setServiceId(res.services[i].uuid)
- is_new = game_store.getters.getIsNew()
- return;
- }
- }
- },
- fail(res) {
- console.log("连接蓝牙成功,获取服务失败", res);
- },
- });
- },
-
- getBLEDeviceCharacteristics(deviceId, serviceId) {
- console.log(deviceId, serviceId);
- const $this = this;
- wx.getBLEDeviceCharacteristics({
- deviceId,
- serviceId,
- success: (res) => {
- console.log("getBLEDeviceCharacteristics success", res.characteristics);
- for (let i = 0; i < res.characteristics.length; i++) {
- let item = res.characteristics[i];
- let writeState = null;
- if (serviceId.indexOf("0001") != -1) {
- writeState = item.properties.write && item.uuid.indexOf("0002") != -1;
- } else {
- writeState = item.properties.write;
- }
- if (writeState) {
-
- $this.deviceId = deviceId;
- $this.serviceId = serviceId;
- $this.cid = item.uuid;
-
- $this.sendOpenBigData();
- }
- if (item.properties.notify || item.properties.indicate) {
- wx.notifyBLECharacteristicValueChange({
- deviceId,
- serviceId,
- characteristicId: item.uuid,
- state: true,
- });
- }
- }
- },
- fail(res) {
- console.error("getBLEDeviceCharacteristics", res);
- },
- });
- },
- openNotify($this) {
- let that = this;
- let $deviceInfo = getServicesAndCharateristc();
- console.log($deviceInfo)
- wx.notifyBLECharacteristicValueChange({
- deviceId: $deviceInfo.deviceId,
- serviceId: $deviceInfo.service,
- characteristicId: $deviceInfo.charateristic.notify,
- state: true,
- success() {
- that.watchingDevice($this)
- }
- });
- },
-
- ab2hex(buffer) {
- var hexArr = Array.prototype.map.call(
- new Uint8Array(buffer),
- function (bit) {
- return ("00" + bit.toString(16)).slice(-2);
- }
- );
- return hexArr.join("");
- },
-
- watchingDevice($this) {
- const that = this;
- let DeviceId = game_store.getters.getDeviceId();
- wx.onBLECharacteristicValueChange((characteristic) => {
-
- wx.getBLEDeviceRSSI({
- deviceId: DeviceId,
- success(res) {
- if (game_store.getters.getGameStatus() == 1) {
- $this.rssi = res.RSSI;
- }
- }
- })
- let hexStr = that.ab2hex(characteristic.value);
-
- if (hexStr.toUpperCase().indexOf("AADD") != -1 || hexStr.toUpperCase().indexOf("AAEE") != -1 && update_state == false) {
- let nowTime = Math.round(new Date() / 1000);
- console.log("应答", hexStr, '时间:' + that.getNowTime(), "长度", hexStr.length / 2);
- LogInDb(`${that.getNowTime()} 应答:${hexStr}`)
- }
- let $data = that.get_big_data(hexStr);
- let $game_status = game_store.getters.getGameStatus();
-
- if (hexStr.toUpperCase().indexOf("AAEE70") != -1) {
- connect_toy = false
- wx.showToast({
- title: "教具已断开",
- icon: "error"
- })
- LogInDb(`${that.getNowTime} 教具已断开`)
-
- if ($game_status == 1) {
- $this.game_finished();
- }
- }
- if (hexStr.toUpperCase().indexOf("AAEE8A0000005A") != -1) {
- that.SendOrder("8a")
- }
-
-
-
-
- if (hexStr.toUpperCase().indexOf("AAEE07") != -1) {
- that.sendControl();
- }
-
- if (hexStr.toUpperCase().indexOf("AADD0A") != -1) {
-
- if (hexStr.toUpperCase().indexOf("AADD0A0000") != -1) {
- if (is_new) {
- $this.change_toy_connect_status(3);
- }
- return false;
- }
- let $mHexStrIndex = hexStr.toUpperCase().indexOf("AADD0A");
- let $hex_index = hexStr.substr($mHexStrIndex + 28, 2)
- let $toy_id = hexStr.substr($mHexStrIndex + 8, 2)
- console.log("连接", $hex_index)
- console.log("玩具", $toy_id)
-
- if (new RegExp("00").test($hex_index) == true) {
- if (is_new) {
- that.sendConnectOneToOne($toy_id)
- $this.current_hex = `03 00 ${$toy_id} 01 0A`
- console.log("一对多")
- } else {
- $this.current_hex = "";
- wx.showToast({
- title: "已连接到" + $this.toy_item.name
- });
- $this.toy_connected = true;
- $this.change_toy_connect_status(2);
- }
- }
- if (new RegExp("01").test($hex_index) == true) {
- console.log("一对一")
- $this.current_hex = "";
- wx.showToast({
- title: "已连接到" + $this.toy_item.name
- });
- $this.toy_connected = true;
- connect_toy = true;
- $this.change_toy_connect_status(2);
-
-
-
- setTimeout(() => {
- that.SendOrder('87')
- }, 3000)
-
- setTimeout(() => {
- that.sendToyPower();
- }, 5000)
- }
- if (new RegExp("02").test($hex_index) == true) {
-
- connect_toy = true
- wx.hideLoading()
- wx.showToast({
- title: "教具重连成功"
- })
- that.sendControl()
-
- }
- }
-
-
- if (hexStr.toUpperCase().indexOf("AADD87") != -1) {
- let $mHexStr = hexStr.substr(hexStr.toUpperCase().indexOf("AADD87"))
- let $datas = that.DoAnalysis($mHexStr, 10)
- let $number = $datas.match(/\d+/)
- let toy_list_pre = {'01': "SW", '02': "KL", '04': "SC", '05': "PP", '06': "SU", '09': "UF"}
- let $sn = toy_list_pre[current_toy_id] + $number;
- $this.toy_sn = $sn;
-
-
- }
- if (hexStr.toUpperCase().indexOf("AAEE87") != -1) {
-
- that.SendOrder('87')
- }
-
-
- if (hexStr.toUpperCase().indexOf("AADD8A") != -1) {
- let $_hexStr = hexStr.substr(hexStr.toUpperCase().indexOf("AADD8A") + 6);
- let $power = parseInt($_hexStr.substr(0, 2), 16)
- let $voltage = parseInt($_hexStr.substr(2, 2), 16)
- connect_toy = true;
-
- if ($power > 0) {
- $this.toy_power = $power
- $this.toy_voltage = $voltage
- ToyPower = $power;
- }
-
-
-
-
-
-
-
-
-
- if (current_toy_UUID == "") {
-
- that.SendOrder('84')
- }
- }
-
- if (hexStr.substr(0, 6) == "555520") {
-
- let $s1 = hexStr.substr(8, 2);
-
- $this.device_bg = $s1 == "00";
- }
-
-
- if (hexStr.toUpperCase().indexOf("AADD84") != -1) {
- let $hex_index = hexStr.toUpperCase().indexOf("AADD84") + 6;
- let $datas = hexStr.substr($hex_index, 10);
- if ($datas != "0000000000") {
- console.log("以获取UUID:" + $datas)
- current_toy_UUID = $datas;
- $this.toy_UUID = $datas;
- }
- }
- if (hexStr.toUpperCase().indexOf("AADD09") != -1) {
- control_close = true;
- connect_toy = false;
- }
-
- if (hexStr.toUpperCase().indexOf("AADD8E") != -1) {
-
- that.WriteBufferInBle(`03 00 ${current_toy_id} 02 0A`)
- }
-
-
- if (hexStr.toUpperCase().indexOf("AADD07") != -1) {
- ble_store.setters.setBluetoothLinkStatus(true)
- FlagOpenControl = true;
- }
-
- if (hexStr.substr(0, 8) == "55550203") {
- let $power = parseInt(hexStr.substr(8, 2), 16);
- let $voltage = parseInt(hexStr.substr(10, 2), 16);
-
- $this.hasUsb = $voltage.toString().substr(0, 1) == 1
-
- if ($power) {
-
- $this.device_power = $power;
- $this.device_voltage = $voltage;
- }
- if ($power < 10 && $power > 0) {
- wx.showToast({
- title: "脑环电量不足",
- icon: "none",
- duration: 2000,
- success() {
-
- },
- });
- }
- }
-
- if (hexStr.toUpperCase().indexOf("AADD30") != -1 || hexStr.toUpperCase().indexOf("AADD31") != -1) {
- if (hexStr.toUpperCase().indexOf("AADD30") != -1) {
- update_index = 0;
- update_seq1_index = 0;
- update_seq2_index = 0;
- update_state = true;
- totalBuffer = [];
- }
-
- console.log("升级中")
- let buffer_len = 224
- if (update_state) {
- let total_index = Math.round($this.payload_len / buffer_len)
- let another_buffer_len = $this.payload_len % buffer_len;
- if (update_index < total_index) {
- that.SendUpdateData($this.buffers, $this.dec_index * 16 + update_index * buffer_len, buffer_len)
- } else {
- console.log(`update_index:${update_index}`,`total_index:${total_index}`)
- console.log("余:"+another_buffer_len)
- if (another_buffer_len > 0) {
- that.SendUpdateData($this.buffers, $this.dec_index * 16 + update_index * buffer_len, another_buffer_len)
- }
- update_state = false;
- }
- $this.progress = (update_index / total_index * 100).toFixed(2);
- } else {
-
- that.FinishBleUpdate()
- console.log(`文件buffer长度:${$this.payload_len},总共发送totalBuffer:${totalBuffer.length}`)
- }
- }
- if (hexStr.toUpperCase().indexOf("AAEE31") != -1) {
- let $hexStr = `03 32 00 00 00`;
- this.WriteBufferInBle($hexStr)
- $this.AddContent("更新停止")
- }
-
- if ($game_status == 1 && $data) {
- $this.do_datas($data);
- }
-
- if (hexStr.toUpperCase().indexOf("AADD33") != -1) {
-
- let $hexStr = `03 00 00 00 26`;
- this.WriteBufferInBle($hexStr)
- $this.step_active += 1;
- }
-
- if (hexStr.toUpperCase().indexOf("AADD02") != -1) {
- hexStr = hexStr.substr(10, 20)
- for (let i = 0; i < hexStr.length; i += 2) {
- model += String.fromCharCode(parseInt(hexStr.substr(i, 2), 16));
- }
- console.log(`model:${model}`)
- this.SendOrder("03");
- }
-
- if (hexStr.toUpperCase().indexOf("AADD03") != -1) {
- hexStr = hexStr.substr(6, 24)
- for (let i = 0; i < hexStr.length; i += 2) {
- version += String.fromCharCode(parseInt(hexStr.substr(i, 2), 16));
- }
- $this.software_version = version
- console.log(`version:${version}`)
- let firmware_info = JSON.parse(wx.getStorageSync("firmware_info"))
-
- if (model == firmware_info.model) {
-
- if (firmware_info.version != version) {
-
- $this.force_update = firmware_info.status == 1;
- $this.remote_version = `V${firmware_info.version}`;
- $this.update_show = true
- }
- }
- }
- });
- },
-
- formatPlaySeconds(value) {
-
- var secondTime = parseInt(value);
- var minuteTime = 0;
- if (secondTime > 60) {
-
-
- minuteTime = parseInt(secondTime / 60);
-
- secondTime = parseInt(secondTime % 60);
-
- }
- var result = "" + parseInt(secondTime);
- if (minuteTime > 0) {
- if (result.length == 1) {
- result = "0" + result;
- }
- if (parseInt(minuteTime).toString().length == 1) {
- minuteTime = "0" + parseInt(minuteTime);
- }
- result = "" + minuteTime + ":" + result;
- } else {
- result = "00:" + result;
- }
- return result;
- },
-
- GetopenBluetoothAdapterError(errCode) {
- let $errmsg = "";
- if (errCode == 10000) {
- $errmsg = "未初始化蓝牙适配器"
- }
- if (errCode == 10001) {
- $errmsg = "当前蓝牙适配器不可用"
- }
- if (errCode == 10002) {
- $errmsg = "没有找到指定设备"
- }
- if (errCode == 10003) {
- $errmsg = "连接失败"
- }
- if (errCode == 10006) {
- $errmsg = "当前连接已断开"
- }
- return $errmsg;
- },
-
- WriteBufferInBle($hex, $buffer_len = 8) {
- let that = this;
- let $deviceInfo = getServicesAndCharateristc();
- let $hex_header = "aa cc ";
-
- let $hex_sum = 0;
- let $hex_ary = $hex.split(" ");
- $hex_ary.forEach(($val, $index) => {
- $hex_sum += parseInt($val, 16);
- })
- let $checksum = ($hex_sum ^ parseInt($8f, 16)) & parseInt($ff, 16);
- $hex = $hex_header + $hex + " " + ("00" + $checksum.toString(16)).substr(-2, 2);
- let buffer = new ArrayBuffer($buffer_len);
- let dataView = new DataView(buffer);
- $hex_ary = $hex.split(" ");
- $hex_ary.forEach(($val, $index) => {
- dataView.setUint8($index, parseInt($val, 16))
- })
- if (!$deviceInfo.charateristic.write) {
- return false;
- }
- wx.writeBLECharacteristicValue({
- deviceId: $deviceInfo.deviceId,
- serviceId: $deviceInfo.service,
- characteristicId: $deviceInfo.charateristic.write,
- value: buffer,
- success: function (res) {
- if ($buffer_len <= 16) {
- console.log($hex + ',写入成功,时间:' + that.getNowTime())
- } else {
- console.log('写入成功,时间:' + that.getNowTime())
- }
-
- },
- fail: function (err) {
- console.log($hex + "写入失败", err);
- },
- });
- },
-
- SendOrder(id) {
- let $hexStr = `03 00 00 00 ${id}`;
- this.WriteBufferInBle($hexStr)
- },
-
- Send16Order(val, id) {
- let $str = val;
- let $str_ary = $str.split('');
- $str = "";
- $str_ary.forEach(($val, $index) => {
- $str += $val.charCodeAt().toString(16) + " "
- });
- $str = $str.substr(0, $str.length - 1)
- let $hexStr = "03 ff " + $str + ` ${id}`;
- this.WriteBufferInBle($hexStr, 16)
- },
-
- DoAnalysis(hexStr, byte_count, sublen = 6) {
-
- let $_str5 = hexStr.substr(sublen);
- let $datas = $_str5.substr(0, byte_count * 2);
- let $_data = "";
- for (let $i = 0; $i < $datas.length; $i += 2) {
- let $code = parseInt($datas.substr($i, 2), 16)
- $_data += String.fromCharCode($code)
- }
- return $_data;
- },
-
- ReconnectToy() {
- current_device_mac = game_store.getters.getDeviceId();
- let $game_status = game_store.getters.getGameStatus();
- let that = this;
- try {
-
- let $uuid_str = "";
- for (let $i = 0; $i < current_toy_UUID.length; $i += 2) {
- $uuid_str += current_toy_UUID.substr($i, 2) + " ";
- }
- let _deviceId = "";
- let deviceIds = current_device_mac.split(':');
- for (let i = 0; i < deviceIds.length; i++) {
- if (i != 2) {
- _deviceId += deviceIds[i] + " ";
- }
- }
- let sum = $uuid_str + _deviceId;
- sum = sum.substr(0, sum.length - 1);
- let $hexStr = `03 ff ${sum} 8e`;
- let loop_count = 0;
- if ($game_status == 1) {
- wx.showLoading({
- title: "重新连接教具中"
- })
- }
- LogInDb(`${that.getNowTime()} 重新连接教具中`)
- let connect_toy_intv = setInterval(() => {
- $game_status = game_store.getters.getGameStatus();
- if ($game_status == 1) {
- if (connect_toy == false) {
- if (loop_count == 3) {
- wx.hideLoading()
- wx.showToast("教具已无法连接")
- clearInterval(connect_toy_intv)
- }
- loop_count += 1;
-
-
- that.WriteBufferInBle($hexStr, 16)
- } else {
- wx.hideLoading()
- loop_count = 0;
- clearInterval(connect_toy_intv)
- }
- } else {
- wx.hideLoading()
- clearInterval(connect_toy_intv)
- }
- }, 3000)
- } catch (e) {
- console.log("ReconnectToy:", e)
- }
- },
-
- clearLocalDatas() {
- control_close = false
- connect_toy = false;
- current_toy_id = "00";
- current_toy_UUID = "";
- },
-
- CalBLEPower($voltage) {
- let $max = 4100;
- let $min = 3500;
-
-
- let $_voltage = $voltage * 100;
-
- let $percent = (($_voltage - $min) / ($max - $min)) * 100;
-
- return $percent;
- },
- getNowTime() {
- var date = new Date();
- const year = date.getFullYear();
- const month = date.getMonth() + 1;
- const day = date.getDate();
- const hour = date.getHours();
- const minutes = date.getMinutes();
- const seconds = date.getSeconds();
- const millSeconds = date.getMilliseconds();
- return `${year}/${month}/${day} ${hour}:${minutes}:${seconds}.${millSeconds}`;
- },
-
- sendAutoConnectRf(isOn, timeOut) {
- let that = this;
- let onVal = isOn ? '01' : '00';
- let mTimeOut = timeOut.toString(16);
- if (mTimeOut.length == 1) {
- mTimeOut = `0${mTimeOut}`
- }
- let $hexStr = `03 00 ${onVal} ${mTimeOut} d0`;
- this.WriteBufferInBle($hexStr)
- },
-
- SendUpdateData(buffers, start_index, speed = 248) {
- let buffer = new Uint8Array(buffers, start_index, speed)
- let $hexStr = [
- '03',
- '31',
- `00${update_seq1_index.toString(16)}`.substr(-2, 2),
- `00${update_seq2_index.toString(16)}`.substr(-2, 2),
- speed.toString(16),
- ]
- for (let j = 0; j < speed; j++) {
- let $hex = ('00' + buffer[j].toString(16)).substr(-2, 2)
- $hexStr.push($hex)
- totalBuffer.push($hex)
- }
- this.WriteBufferInBle($hexStr.join(' '), $hexStr.length + 3)
- update_seq1_index += 1;
- update_index += 1;
- if (update_seq1_index == 256) {
- update_seq1_index = 0;
- update_seq2_index += 1;
- }
- },
-
- FinishBleUpdate() {
- let $hexStr = `03 33 00 00 00`;
- this.WriteBufferInBle($hexStr)
- },
- };
|