| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099 |
- import Vue from 'vue'
- import Vuex from 'vuex'
- import config from 'common/config.js'
- import reqUtil from 'util/util-js/requstUtil.js'
- import date from 'util/util-js/date.js'
- import cNumber from 'util/util-js/makeNumber.js'
- import BLE from 'util/util-js/BLE.js';
- //快速打击部分
- import o0 from "@/util/util-js/o0.js"
- import o0Project from "@/util/util-js/o0Project.js"
- import o0ProjectRelease from "@/util/util-js/o0ProjectRelease0.1.js"
- import deviceData from "@/util/util-js/devices.js"
- Vue.use(Vuex)
- const store = new Vuex.Store({
- state: {
- // vLog:'',
- //引导层
- bGuidePages: false,
- //是否显示Canvas
- bCanvasShow: true,
- /**
- * 是否需要强制登录
- */
- forcedLogin: false,
- /**
- * 蓝牙实时发送数据的页面的名称
- */
- currentPageName: '',
- hasLogin: false,
- userInfo: null,
- userName: "匿名",
- days: 0,
- remainingDays: 0,
- signature: '',
- avatarUrl: "/static/defaultAvatar.png",
- /**
- * 新手教程相关
- */
- // 是否是新用户,
- //TODO:登录接口返回的数据来判断
- bNewUser: false,
- //是否是第一次走新手
- bNewGuide: false,
- //解锁状态,和首次安装app相关
- //注意添加新字段时候。需要到 platform-page/guide.vue 确认需不需要添加新的reset
- guideUnlockState: {
- firstInstallation: true, //是否首次安装
- firstDisconnectBluetooth: true, //是否首次连接蓝牙
- firstUnlockJumpUp: true, //是否首次向上跳
- firstUnlockLeftAndRightJump: true, //是否首次左右跳
- firstUnlockLeftAndRightRotationJump: true,
- firstPromptSelectLevel: true //是否首次提示选择关卡
- },
- token: '',
- gender: 0,
- //省市区数据
- city: {
- label: '北京市-北京市-东城区',
- cityCode: "110101",
- //picker 选择器的index数组
- value: [0, 0, 0]
- },
- birthday: date.formatTime(new Date()),
- //默认值
- height: 0,
- weight: 0,
- //最近在玩的列表
- playGames: [],
- //最近在玩的排行游戏列表
- playRankingGames: [],
- //全部的游戏列表
- allGames: [],
- //关注的游戏列表
- favoriteGames: [],
- // 排行榜里面显示的游戏
- rankSelectedGame: null,
- rankInfo: null,
- cityName: "某市",
- /**
- * 默认的运动数据
- * date.addDaysFromNewDate(new Date(),1)
- */
- defaultPlanData: {
- startTime: date.formatDate(new Date()),
- endTime: date.addDaysFromNewDate(new Date(), 6),
- targetWeight: 0, //目标公斤
- calorie: 360, //运动消耗的卡路里,默认300 大卡
- cumulativeCalorie: 0, //累计增重
- sportTime: 40, //运动时间
- /**
- * 本地记录的消耗卡路里数量
- */
- localCalorie: 0,
- /**
- * 显示卡路里,过了12点清空
- */
- showCalorie: 0,
- /**
- * 总和
- */
- allCalorie: 0
- },
- /**
- * 计划的运动数据
- */
- planData: {
- startTime: date.formatDate(new Date()),
- endTime: date.formatDate(new Date()), //date.addDaysFromNewDate(new Date(),1),
- targetWeight: 0, //目标公斤
- cumulativeCalorie: 0, //累计增重
- calorie: 300, //运动消耗的卡路里
- sportTime: 40, //运动时间
- /**
- * 本地记录的消耗卡路里数量
- */
- localCalorie: 0,
- /**
- * 显示卡路里,过了12点清空
- */
- showCalorie: 0,
- /**
- * 总和
- */
- allCalorie: 0
- },
- //记录表盘计划刷新的卡路里
- oldArcbarProCalorie: 0,
- //记录表盘当前的总卡路里
- oldArcbarAllCalorie: 0,
- //当前运动的世时间
- localSportTime: 0,
- //当前运动时间,运动时候记录的时间
- runingTime: 0,
- //蓝牙设备信息列表
- //id 不可变,用于保存到本地区分
- BLEInfoList: deviceData.getDeviceList(),
- //记录的蓝牙设备,保存id, 和对应的蓝牙连接数据
- BLEDeviceList: [],
- //显示的蓝牙设备,取本地数据时候更新
- BLEDeviceShowList: [],
- //选择连接的蓝牙设备
- BLEConnectDevice: null,
- //获取到的服务
- BLEGetServices: null,
- //当前发送给蓝牙的指令,目前是只有蓝牙手柄
- currentInstruction: '',
- instructionState: {
- // bAcc: false, //是否开启加速计状态
- // bGyroscope: false, //是否开启陀螺仪状态
- bOpen: false, //是否开启指令
- bSteps: false, //是否开启步数
- },
- //绑定的设备
- DeviceBindingList: [{
- id: 0,
- cname: "开启手机数据",
- ename: "bindMobilePhoneBandage",
- icon: "/static/devicesIcon/bandage.png",
- mIcon: "/static/devicesIcon/bandage.png",
- bRatio: false,
- usageMode: 'bindPhone',
- describe: '手机情景下使用',
- limitType: 'rebound', //限制回弹版本
- deviceType: 'mySelf', //指的是使用手机本身加速计计算
- deviceName: 'PHONE', //连接硬件名称
- }],
- ConnectBindingDevice: null,
- cIndex: -1,
- //当前是否连接
- bConnection: false,
- /**
- * 通过验证的连接,比如通过mac验证,或者说是首页直连,都设置这个参数,确保已经连上
- */
- bVerifiedConnection: false,
- /**
- * 默认不是旧设备,旧设备使用的轴向不一样,名字为 BGBox_202012 ,新设备为 BGBox_202112
- */
- bOldDeviceType: false,
- /**
- * Android 出现不匹配的情况下,判断
- * ios 暂时没有此类问题
- */
- bPhoneMatched: false,
- //最近连接过的设备
- finallyUseDevice: null,
- /**
- * 用户选择好友的信息
- */
- finallySelectFriendInfo: null,
- //phoneNumber
- phoneNumber: '',
- mailboxNumber: '',
- //是否是第一次设置密码,根据这个值判断.默认未设置,即设置true
- setPasswordFirstTime: true,
- openid: '',
- appleid: '',
- //获取验证码
- bCodeDisabled: false,
- count: 59,
- interval: null,
- //conversion列表
- oldSwiperList: [],
- // 计划任务过期
- bPlanExpired: false,
- // 制定玩计划任务后
- bPlanFinish: false,
- //标准体重,男女根据当前年龄计算
- standardWeight: 0,
- //是否安装了微信
- bInstallWechat: false,
- bHideWeixin: false,
- //导航栏高度。这里统一参数,单位px
- navHeight: 46,
- tabbarHeight: 65,
- systemInfo: null, //系统全部信息
- clientName: '', //但是客户端名字
- system: '', // 系统版本
- platform: '', // 平台
- appName: '',
- version: '1.6.3', //软件版本
- versionCode: '21120701', //app.vue 自动获取.目前是h5 设置给了一个默认值
- showEndTime: config.endTime, //游戏显示时间字段,后台返回对应此时间之前的数据
- //现在游戏显示在对应的平台
- gamePlatform: {
- 0: 'android',
- 1: 'ios',
- 2: 'all'
- },
- globalAcc: null,
- globalOri: null,
- globalAccData: {
- ax: 0,
- ay: 0,
- az: 0
- },
- globalGyroData: {
- gx: 0,
- gy: 0,
- gz: 0
- },
- globalLastGyroData: {
- gx: 0,
- gy: 0,
- gz: 0
- },
- globalMyAttitude: null,
- /**
- * 当前显示的模式下标,区分总体的显示模块
- * 比如拳击模块体验下,设置 0
- * 跳绳为主的模式体验下,设置 1
- */
- currentModeIndex: 0,
- //蓝牙变量操作
- /**
- * 操作蓝牙设备
- */
- bOpenBluetooth: false,
- /**
- * 是否初始化蓝牙适配器
- */
- bOpenSuccess: false,
- /**
- * 是否监听蓝牙状态变化
- */
- bListenAdapterStateChange: false,
- /**
- * 是否监听寻找新设备事件
- */
- bListenDeviceFound: false,
- // 设备Id
- BLEDeviceId: "",
- // 服务Id
- BLEServiceId: "",
- // 特征值id
- BLENotifyCharacteristicId: "",
- //监听rssi对象
- BLERSSIInterval: null,
- //蓝牙服务timeout
- getBLEDeviceServicesTimeout: null,
- //本地游戏地址
- // http://192.168.0.112:7456/build/index.html
- // http://127.0.0.1:7456/build/index.html
- LocationGameUrl: "", //192.168.1.12:7456
- //快速打击对象
- filter: null,
- deviceMs: 1,
- //改进版的沙袋打击对象
- sandbagAlgorithm: null,
- sandbagAlgorithmLastTime: new Date().getTime(),
- /**
- * 蓝牙参数对象
- */
- // 设备Id
- deviceId: "",
- // 服务Id
- serviceId: "",
- notifyCharacteristicId: "",
- writeCharacteristicId: "",
- showToast: false,
- bListenerUpdate: false,
- bListenerJson: false,
- bListenerMac: false,
- bListenerAccArray: false,
- /**
- * OTA config
- */
- UUID_OTA_SERVICE: "f000ffc0-0451-4000-b000-000000000000", //OTA 服务对应的服务的 UUID
- UUID_IDENTFY: "f000ffc1-0451-4000-b000-000000000000", //OTA 版本特征值的UUID,读取版本就是写向这个特征值写入:0x00
- UUID_BLOCK: "f000ffc2-0451-4000-b000-000000000000", //OTA 写bin文件特征值UUID,发送bin文件就是写这个特征值
- /*****/
- /**
- * 发送16进制时候,返回的刷新数据
- */
- bListenerHexUpdate: false,
- BluetoothAdapter: null,
- //版本状态,用于区分部分特定的环境
- versionCodeState: {
- showGame: false,
- showVideo: false,
- versionCode: 0,
- title: 'none'
- },
- //显示蓝牙是否断开连接Modal
- bShowBLEConnectModal: false,
- bGamePlaying: false,
- //跳绳条件下计数
- bRopeKeyOne: 0,
- bRopeKeyTwo: 0,
- //钻石,金币
- cDiamond: 0,
- cGold: 0,
- /**
- * 任务相关
- */
- currentJumpTask: null,
- multiPersonList: [],
- singlePersonList: [],
- levels: [],
- /**
- * 校准识别部分
- */
- convertAcc: [{
- type: 'x',
- match: 'ax', //默认匹配一一对应
- direction: 1,
- }, {
- type: 'y',
- match: 'ay',
- direction: -1,
- }, {
- type: 'z',
- match: 'az',
- direction: -1,
- }],
- convertGyro: [{
- type: 'x',
- match: 'gx', //默认匹配一一对应
- direction: 1,
- }, {
- type: 'y',
- match: 'gy',
- direction: 1,
- }, {
- type: 'z',
- match: 'gz',
- direction: 1,
- }],
- /**
- * 签到列表
- */
- signInList: [],
- isSignIn: false,
- },
- mutations: {
- onSetLocationGameUrl(state, value) {
- uni.setStorageSync('LocationGameUrl', value);
- state.LocationGameUrl = value;
- },
- //获取本地任务对象
- onGetLocationGameUrl(state) {
- //如果存在本地任务
- const value = uni.getStorageSync('LocationGameUrl');
- if (value) {
- state.LocationGameUrl = value;
- }
- return value;
- console.log('onGetLocationGameUrl ' + value);
- },
- /**
- * 蓝牙解析后的数据,转化成对应的坐标系方向
- * @param {Object} context
- */
- onConvertDeviceData(state, context) {
- let {
- data,
- callback = null
- } = context;
- let {
- acc,
- gyro,
- } = data;
- //根据已校准的数据转化对应的轴
- let outAcc = {
- ax: acc[state.convertAcc[0].match] * state.convertAcc[0].direction,
- ay: acc[state.convertAcc[1].match] * state.convertAcc[1].direction,
- az: acc[state.convertAcc[2].match] * state.convertAcc[2].direction
- };
- let outGyro = {
- gx: gyro[state.convertGyro[0].match] * state.convertGyro[0].direction,
- gy: gyro[state.convertGyro[1].match] * state.convertGyro[1].direction,
- gz: gyro[state.convertGyro[2].match] * state.convertGyro[2].direction
- }
- if (callback)
- callback({
- convertAcc: outAcc,
- convertGyro: outGyro
- });
- },
- onAccAndGyroConvertDataGet(state) {
- const convertAcc = uni.getStorageSync('convertAcc');
- if (convertAcc) {
- state.convertAcc = convertAcc;
- }
- const convertGyro = uni.getStorageSync('convertGyro');
- if (convertGyro) {
- state.convertGyro = convertGyro;
- }
- },
- onAccAndGyroConvertDataSave(state) {
- uni.setStorageSync('convertAcc', state.convertAcc);
- uni.setStorageSync('convertGyro', state.convertGyro);
- },
- onAccAndGyroConvertDataReset(state) {
- state.convertAcc = [{
- type: 'x',
- match: 'ax', //默认匹配一一对应
- direction: 1,
- }, {
- type: 'y',
- match: 'ay',
- direction: -1,
- }, {
- type: 'z',
- match: 'az',
- direction: -1,
- }];
- state.convertGyro = [{
- type: 'x',
- match: 'gx', //默认匹配一一对应
- direction: 1,
- }, {
- type: 'y',
- match: 'gy',
- direction: 1,
- }, {
- type: 'z',
- match: 'gz',
- direction: 1,
- }];
- //重置一下数据保存
- this.commit('onAccAndGyroConvertDataSave');
- },
- setGuideUnlockState(state, _guideUnlockState) {
- uni.setStorageSync('guideUnlockState', _guideUnlockState);
- state.guideUnlockState = _guideUnlockState;
- },
- getGuideUnlockState(state, _guideUnlockState) {
- //如果存在本地任务
- const value = uni.getStorageSync('guideUnlockState');
- if (value) {
- state.guideUnlockState = value;
- }
- console.log('获取guideUnlockState', state.guideUnlockState)
- },
- /**
- * 设置当前操作的任务记录到本地
- * @param {Object} state
- * @param {Object} _taskObj
- */
- setActionJumpTask(state, _taskObj) {
- uni.setStorageSync('currentJumpTask', _taskObj);
- state.currentJumpTask = _taskObj;
- },
- //获取本地任务对象
- getActionJumpTask(state) {
- //如果存在本地任务
- const value = uni.getStorageSync('currentJumpTask');
- if (value) {
- state.currentJumpTask = value;
- }
- },
- resetActionJumpTask(state) {
- state.currentJumpTask = null;
- uni.setStorageSync('currentJumpTask', state.currentJumpTask);
- },
- setFinallSelectFriendInfo(state, friendInfo) {
- state.finallySelectFriendInfo = friendInfo;
- console.log('finallySelectFriendInfo', JSON.stringify(friendInfo));
- },
- clearFinallFriendInfo(state) {
- state.finallySelectFriendInfo = null;
- },
- /**
- * 获取记录的最后一次连接设备
- * @param {Object} state
- */
- getFinalUseDevice(state) {
- // 获取本地存储的最后一次使用的设备
- //1.获取最近连接的蓝牙设备, 指蓝牙搜索到的obj
- const value = uni.getStorageSync('finallyUseDevice');
- if (value) {
- state.finallyUseDevice = value;
- }
- console.log('获取的finallyUseDevice', value);
- },
- /**
- * 存储最后一次使用的设备信息,后面登陆时候,如果存在设备最后一次使用信息,则自动连接
- * @param {Object} state
- * @param {Object} device
- */
- setFinallUseDevice(state, device) {
- uni.setStorageSync('finallyUseDevice', device);
- state.finallyUseDevice = device;
- // console.log("保存finallyUseDevice:", state.finallyUseDevice);
- // uni.setStorage({
- // key: 'finallyUseDevice',
- // data: device,
- // success: (res) => {
- // state.finallyUseDevice = device;
- // console.log("保存finallyUseDevice:", res);
- // }
- // })
- },
- //获取记录的蓝牙列表数据
- getBLEDeviceList(state) {
- // console.log("getBLEDeviceList=");
- uni.getStorage({
- key: 'BLEDeviceList',
- success: (res) => {
- // console.log("*****getBLEDeviceList=", res);
- let _list = res.data;
- state.BLEDeviceList = res.data;
- //更新BLEDeviceShowList 数组
- state.BLEDeviceShowList = [];
- _list.forEach(item => {
- //如果记录到本地的id,和信息列表中的id一致,则结合
- for (let i = 0; i < state.BLEInfoList.length; i++) {
- let eq = state.BLEInfoList[i];
- if (item.id == eq.id) {
- state.BLEDeviceShowList.push(Object.assign({}, item, eq));
- break;
- }
- }
- })
- }
- })
- },
- //添加蓝牙设备数据
- addBLEDevice(state, data) {
- let devicelist = [];
- if (state.BLEDeviceList && state.BLEDeviceList.length != 0) {
- devicelist = state.BLEDeviceList;
- }
- // console.log(data, devicelist)
- let bHas = false;
- devicelist.forEach((item, index, selfArr) => {
- if (item.id == data.id) {
- //如果存在,更新保存的数据,比如 mac或者uuid等
- selfArr[index] = item = Object.assign({}, item, data);
- bHas = true;
- }
- })
- //把当前添加的的蓝牙设信息备作为最后一次连接覆盖到本地
- this.commit('setFinallUseDevice', data);
- if (!bHas) {
- //如果不是更新数据,就添加但却数据到列表
- devicelist.push(data);
- }
- uni.setStorage({
- key: 'BLEDeviceList',
- data: devicelist,
- success: (res) => {
- // uni.showToast({
- // title: "保存成功"
- // })
- state.BLEDeviceList = devicelist;
- // console.log("devicelist:",devicelist);
- //更新BLEDeviceShowList 数组
- state.BLEDeviceShowList = [];
- devicelist.forEach(item => {
- //如果记录到本地的id,和信息列表中的id一致,则结合
- for (let i = 0; i < state.BLEInfoList.length; i++) {
- let eq = state.BLEInfoList[i];
- if (item.id == eq.id) {
- // console.log("存储的======================:", item, eq);
- state.BLEDeviceShowList.push(Object.assign({}, item, eq));
- break;
- }
- }
- })
- // console.log("state.BLEDeviceShowList:",state.BLEDeviceShowList);
- }
- })
- },
- //删除蓝牙设备数据
- deleteBLEDevice(state, index) {
- let devicelist = [];
- devicelist = state.BLEDeviceList;
- devicelist.splice(index, 1);
- uni.setStorage({
- key: 'BLEDeviceList',
- data: devicelist,
- success: (res) => {
- uni.showToast({
- title: "删除成功"
- })
- state.BLEDeviceList = devicelist;
- //更新BLEDeviceShowList 数组
- state.BLEDeviceShowList = [];
- devicelist.forEach(item => {
- //如果记录到本地的id,和信息列表中的id一致,则结合
- for (let i = 0; i < state.BLEInfoList.length; i++) {
- let eq = state.BLEInfoList[i];
- if (item.id == eq.id) {
- state.BLEDeviceShowList.push(Object.assign({}, item, eq));
- break;
- }
- }
- })
- }
- })
- },
- initAdapter(state, callback) {
- //初始化蓝牙模块
- let params = {
- success: (res) => {
- state.bOpenSuccess = true;
- state.bOpenBluetooth = true;
- if (callback)
- callback(res);
- //监听断开事件
- this.commit("B_OnBLEConnectionStateChange");
- },
- fail: (fail) => {
- state.bOpenSuccess = false;
- state.bOpenBluetooth = false;
- uni.showToast({
- title: '蓝牙尚未开启!',
- icon: 'none'
- })
- },
- complete: (complete) => {
- // console.log("complete bListenAdapterStateChange:", state.bListenAdapterStateChange);
- if (state.bListenAdapterStateChange) return;
- state.bListenAdapterStateChange = true;
- uni.onBluetoothAdapterStateChange((res) => {
- // console.log('adapterState changed, now is', res)
- // 手机蓝牙状态
- state.bOpenBluetooth = res.available;
- if (state.bOpenBluetooth && !state.bOpenSuccess) {
- this.commit('initAdapter');
- }
- })
- }
- };
- this.commit("B_OpenBluetoothAdapter", params);
- },
- // todo 未使用到
- onGetDevices(state, context) {
- let {
- success
- } = context;
- if (!state.BLEConnectDevice) return;
- // #ifdef APP-PLUS
- let deviceId = state.BLEConnectDevice.deviceId;
- uni.getBLEDeviceRSSI({
- deviceId,
- success: res => {
- let _dis = Math.pow(Math.E, (Math.abs(res.RSSI) - 66.78) / 16.56);
- if (_dis > state.BLEConnectDevice.limitDis) {
- if (state.cIndex != -1) {
- uni.showToast({
- title: '设备断开连接!',
- icon: 'none',
- duration: 2000,
- mask: true
- })
- }
- setTimeout(() => {
- this.commit("B_CloseBLEConnection", {
- deviceId: deviceId
- })
- state.cIndex = -1;
- state.bConnection = false;
- state.bVerifiedConnection = false;
- }, 1000)
- } else {
- // console.log("DIS~~~~~~~~~", _dis);
- if (success) {
- success({
- RSSI: res.RSSI,
- DIS: _dis
- });
- }
- }
- }
- })
- // #endif
- },
- //清除连接的开启的timeout
- onUnloadCreateBLEConnectionTimeout(state) {
- if (state.getBLEDeviceServicesTimeout) {
- clearTimeout(state.getBLEDeviceServicesTimeout);
- state.getBLEDeviceServicesTimeout = null;
- }
- },
- initBLEData(state) {
- // 设备Id
- state.deviceId = "";
- // 服务Id
- state.serviceId = "";
- state.notifyCharacteristicId = "";
- state.writeCharacteristicId = "";
- state.currentInstruction = "";
- state.showToast = false;
- state.bListenerUpdate = false;
- state.bListenerJson = false;
- state.bListenerMac = false;
- state.bListenerAccArray = false;
- //更新二进制的
- state.bListenerHexUpdate = false;
- },
- //连接蓝牙
- onCreateBLEConnection(state, context) {
- let {
- index,
- item,
- initItem = false,
- getSuccess = null,
- getinitAdapter = null
- } = context;
- uni.showToast({
- title: '连接设备中...',
- icon: 'loading',
- duration: 10000,
- mask: true
- })
- let params = {
- item: item,
- success: (success) => {
- state.bConnection = true;
- if (state.getBLEDeviceServicesTimeout) {
- clearTimeout(state.getBLEDeviceServicesTimeout);
- state.getBLEDeviceServicesTimeout = null;
- }
- state.getBLEDeviceServicesTimeout = setTimeout(() => {
- let retryCount = 5;
- this.commit("B_GetBLEDeviceServices", {
- retryCount: retryCount,
- item: item,
- callback: () => {
- uni.showToast({
- title: '连接成功',
- icon: 'loading',
- duration: 2000,
- mask: true
- })
- //是否需要设置item,默认不设置
- if (initItem) {
- state.cIndex = index;
- state.BLEConnectDevice = item;
- }
- if (getSuccess)
- getSuccess();
- /**
- * 直接连接过成功
- */
- state.bVerifiedConnection = true;
- },
- getServiceList: (serviceList) => {
- //搜索服务失败后
- state.BLEGetServices = serviceList;
- },
- getFail: () => {
- this.commit("B_CloseBLEConnection", {
- deviceId: item.deviceId
- })
- // state.cIndex = -1;
- // state.bConnection = false;
- // state.bVerifiedConnection = false;
- this.commit("onResetBLEConnection");
- }
- });
- }, 2000);
- },
- fail: (fail) => {
- console.log("***fail:", fail);
- if (fail.errCode === 10012) {
- console.log("连接超时,请重试!");
- uni.showToast({
- title: '连接失败,开启设备后尝试重新连接!',
- icon: 'none',
- duration: 3000,
- mask: true
- })
- } else if (fail.errCode === 10013) {
- console.log("连接失败,蓝牙地址无效!");
- uni.showToast({
- title: '连接失败,蓝牙地址无效',
- icon: 'none',
- duration: 2000,
- mask: true
- })
- } else if (fail.errCode === 10000) {
- this.commit('initAdapter', () => {
- if (getinitAdapter) {
- getinitAdapter();
- }
- })
- } else {
- // err.errCode10003原因多种:蓝牙设备未开启或异常导致无法连接;蓝牙设备被占用或者上次蓝牙连接未断开导致无法连接
- console.log("连接失败,请重试!", state.BLEConnectDevice);
- uni.showToast({
- title: '请尝试开启设备和重启app。',
- icon: 'none',
- duration: 2000,
- mask: true
- })
- }
- }
- };
- this.commit("B_CreateBLEConnection", params);
- },
- //devices hardware 连接后验证,这里不需要处理 bVerifiedConnection,通过mac 验证后处理
- onCreateBLESuccess(state, context) {
- let {
- item,
- getSuccess = null
- } = context;
- this.commit("B_CreateBLEConnection", {
- item: item,
- success: success => {
- state.BLEConnectDevice = item;
- state.bConnection = true;
- if (getSuccess) {
- getSuccess();
- }
- },
- fail: fail => {
- if (fail.errCode === 10012) {
- console.log("连接超时,请重试!");
- uni.showToast({
- title: '连接超时,检查对应设备是否开启?',
- icon: 'none',
- duration: 2000,
- mask: true
- })
- } else if (fail.errCode === 10013) {
- console.log("连接失败,蓝牙地址无效!");
- uni.showToast({
- title: '蓝牙地址无效,检查设备是否正常?',
- icon: 'none',
- duration: 2000,
- mask: true
- })
- } else if (fail.errCode === 10000) {
- console.log("连接失败,初始化 wx.openBluetoothAdapter 调用之后使用");
- uni.showToast({
- title: '连接失败,检查手机蓝牙是否开启?',
- icon: 'none',
- duration: 2000,
- mask: true
- })
- } else {
- console.log("连接失败,请重试!");
- uni.showModal({
- title: '连接失败',
- content: '设备未开启或被占用。请重启app和设备后重新连接。'
- })
- // uni.showToast({
- // title: '设备未开启或被占用异常导致无法连接。',
- // icon: 'none',
- // duration: 2000,
- // mask: true
- // })
- }
- }
- });
- },
- //获取蓝牙服务
- onGetBLEDeviceServices(state, context) {
- let {
- item,
- success = null,
- } = context;
- let retryCount = 5;
- this.commit("B_GetBLEDeviceServices", {
- retryCount: retryCount,
- item: item,
- callback: success,
- getServiceList: (serviceList) => {
- state.BLEGetServices = serviceList;
- },
- getFail: () => {
- this.commit("B_CloseBLEConnection", {
- deviceId: item.deviceId
- })
- this.commit("onResetBLEConnection");
- }
- })
- },
- //重置蓝牙连接参数
- onResetBLEConnection(state) {
- state.cIndex = -1;
- state.BLEConnectDevice = null;
- //蓝牙服务
- state.BLEGetServices = null;
- state.bConnection = false;
- state.bVerifiedConnection = false;
- },
- onCloseBLEConnection(state, context) {
- console.log("onCloseBLEConnection", state.BLEConnectDevice);
- let {
- getSuccess = null,
- } = context;
- if (state.BLERSSIInterval) {
- clearInterval(state.BLERSSIInterval);
- state.BLERSSIInterval = null;
- }
- this.commit("B_CloseBLEConnection", {
- deviceId: state.BLEConnectDevice.deviceId,
- success: () => {
- state.cIndex = -1;
- state.BLEConnectDevice = null;
- //蓝牙服务
- state.BLEGetServices = null;
- if (getSuccess) {
- getSuccess();
- }
- state.bConnection = false;
- state.bVerifiedConnection = false;
- uni.closeBluetoothAdapter({
- success(res) {
- console.log(res)
- state.bOpenBluetooth = false;
- }
- })
- }
- });
- },
- //不关闭 adapter
- onOnlyCloseBLEConnection(state, context) {
- let {
- getSuccess = null
- } = context;
- if (state.BLERSSIInterval) {
- clearInterval(state.BLERSSIInterval);
- state.BLERSSIInterval = null;
- }
- this.commit("B_CloseBLEConnection", {
- deviceId: state.BLEConnectDevice.deviceId,
- success: () => {
- state.cIndex = -1;
- state.BLEConnectDevice = null;
- //蓝牙服务
- state.BLEGetServices = null;
- if (getSuccess) {
- getSuccess();
- }
- state.bConnection = false;
- state.bVerifiedConnection = false;
- }
- });
- },
- onWriteBLEConnectionValue(state, context) {
- //#ifdef H5
- console.warn("h5不支持蓝牙:", 'onWriteBLEConnectionValue');
- return;
- //#endif
- let {
- getSuccess = null,
- getFail = null,
- value,
- bSendHex = false,
- bOpen = false,
- } = context;
- if (!state.BLEConnectDevice && state.cIndex == -1) {
- uni.showToast({
- title: '蓝牙设备未连接',
- icon: 'none'
- })
- }
- // console.log(22);
- //记录蓝牙盒子当前的指令
- // state.currentInstruction = value;
- // 发送 3 :开启原始数据
- // 发送4 :关闭原始数据
- // 发送 5 :开启步数
- // 发送6 :关闭步数
- if (value == "3") {
- state.instructionState.bOpen = true;
- } else if (value == "4") {
- state.instructionState.bOpen = false;
- } else if (value == "5") {
- state.instructionState.bSteps = true;
- } else if (value == "6") {
- state.instructionState.bSteps = false;
- } else if (bSendHex && bOpen) {
- state.instructionState.bOpen = true;
- } else if (bSendHex && !bOpen) {
- state.instructionState.bOpen = false;
- }
- let retryCount = 5;
- this.commit("B_WriteBLECharacteristicValue", {
- value,
- retryCount,
- getSuccess,
- getFail,
- bSendHex
- });
- },
- //获取距离
- onGetRSSITransDistance(state, context) {
- let {
- RSSI
- } = context;
- BLE.getRSSITransDistance(RSSI);
- },
- //添加使用的前端信息
- gOnAddClientInfo(state, context) {
- uni.getSystemInfo({
- success: (res) => {
- // console.log("系统信息:", res);
- let clientInfo = res;
- clientInfo.clientSystem = res.system;
- reqUtil.requestData(config.URL.ADDCLIENTINFO, clientInfo, 'POST').then(
- res => {
- console.warn(res);
- },
- e => {}
- );
- },
- fail: (err) => {},
- complete: () => {}
- })
- },
- //创建快速打击对象
- gCreateFilterObj(state) {
- state.filter = null;
- state.deviceMs = 1;
- state.filter = new o0Project.Filter();
- console.log("gCreateFilterObj");
- },
- //更新快速打击对象数据
- gUpdateFilter(state, context) {
- let {
- data,
- callback
- } = context;
- let {
- min,
- s,
- ms
- } = data;
- var msGap = ms - state.deviceMs;
- state.deviceMs = ms;
- while (msGap < 0) {
- msGap += 1000;
- }
- // console.log(data);
- let {
- ax,
- ay,
- az
- } = data.acc;
- let {
- gx,
- gy,
- gz
- } = data.gyro;
- state.filter.Update(new o0.Vector3(ax, ay, az), msGap, new o0.Vector3(gx, gy, gz),
- callback); //我自己的更新acc的函数
- },
- /**
- * 创建一个沙袋打击对象
- * @param {Object} state
- */
- gCreateSandbagAlgorithm(state) {
- state.sandbagAlgorithm = null;
- state.deviceMs = 1;
- state.sandbagAlgorithmLastTime = new Date().getTime();
- state.sandbagAlgorithm = new o0ProjectRelease.SandbagAlgorithm();
- console.log("gCreateSandbagAlgorithm");
- },
- /**
- * 更新 沙袋打击对象 数据
- * @param {Object} state
- * @param {Object} context
- */
- gUpdateSandbagAlgorithm(state, context) {
- let {
- data,
- callback = null
- } = context;
- let {
- min,
- s,
- ms
- } = data;
- let msGap = ms - state.deviceMs;
- state.deviceMs = ms;
- while (msGap < 0) {
- msGap += 1000;
- }
- let {
- ax,
- ay,
- az
- } = data.acc;
- let {
- gx,
- gy,
- gz
- } = data.gyro;
- // ax / 10, az / 10, gz, -gx, data.ms ----- old
- // ay / 10, -az / 10, gy, gz, data.ms
- let [hit, dir] = state.sandbagAlgorithm.Update(ay, -az, gz, gy, msGap);
- if (dir != undefined) {
- let temp = state.sandbagAlgorithm.getTempValue(dir);
- if (callback) {
- callback(temp);
- }
- }
- },
- /**
- * 开启加速计,陀螺仪,并且模拟ble发送
- * @param {Object} state
- */
- gStartSimulateBLEUpdate(state) {
- //todo 区分平台,目前是android 模块
- if (state.globalMyAttitude == null) {
- state.globalMyAttitude = uni.requireNativePlugin("MyAttitude");
- let globalEvent = uni.requireNativePlugin('globalEvent');
- globalEvent.addEventListener('updateAccAndGyro', function(e) {
- //updateAccAndGyro{"accelerometer":[-0.178375244140625,9.327804565429688,2.6168670654296875],"gyroscope":[0.0018310546875,-0.0019989013671875,0.0027923583984375]}
- //console.log('updateAccAndGyro' + JSON.stringify(e));
- let _accArray = e.accelerometer;
- let _gyroArray = e.gyroscope;
- state.globalAccData.ax = _accArray[0];
- state.globalAccData.ay = _accArray[1];
- state.globalAccData.az = _accArray[2];
- state.globalGyroData.gx = _gyroArray[0];
- state.globalGyroData.gy = _gyroArray[1];
- state.globalGyroData.gz = _gyroArray[2];
- let box = {};
- box["acc"] = state.globalAccData;
- box["gyro"] = state.globalGyroData;
- box["ms"] = e.ms;
- //更新数据给webview,在game-play-web||game-play-sub绑定
- //后面更新数据都用此接口
- uni.$emit('updateBLEDeviceData', box);
- });
- }
- var ret = state.globalMyAttitude.onStartAccAndGyro();
- if (!ret.accelerometer || !ret.gyroscope) {
- uni.showModal({
- title: '提示',
- content: '是否初始化,加速计:' + ret.accelerometer + ',陀螺仪:' + ret.gyroscope
- })
- }
- console.log('gStartSimulateBLEUpdate:', ret);
- },
- /**
- * 停止加速计,陀螺仪
- * @param {Object} state
- */
- gStopSimulateBLEUpdate(state) {
- //todo 区分平台,目前是android 模块
- let globalEvent = uni.requireNativePlugin('globalEvent');
- globalEvent.removeEventListener('updateAccAndGyro');
- var ret = state.globalMyAttitude.onStopAccAndGyro();
- console.log('gStopSimulateBLEUpdate:', ret);
- state.globalMyAttitude = null;
- },
- /**
- * 限制开始游戏
- */
- glimitPlayGame(state, context) {
- let {
- gameTags,
- callback
- } = context;
- //没有标签直接进去
- if (gameTags.length == 0) {
- callback();
- return;
- }
- let canPlay = false;
- gameTags.forEach((item) => {
- //如果存在普通模式
- if (item.tagMode === 'normal') {
- canPlay = true;
- }
- if (canPlay)
- return;
- })
- if (!canPlay) {
- //2.如果普通模式不存在,就判断是否连接硬件了
- if (!state.BLEConnectDevice || state.cIndex == -1) {
- uni.showToast({
- title: "请连接标签对应的设备模式!",
- icon: "none",
- duration: 2000,
- mask: true
- })
- return;
- }
- //3.如果连接了设备,判断但是处于什么模式
- gameTags.forEach((item, index, selfArr) => {
- //如果存在普通模式
- if (item.tagMode === state.BLEConnectDevice.usageMode) {
- canPlay = true;
- }
- if (canPlay)
- return;
- if (index == selfArr.length - 1) {
- uni.showToast({
- title: "游戏没有当前设备模式!",
- icon: "none",
- duration: 2000,
- mask: true
- })
- }
- })
- }
- if (canPlay) {
- callback();
- }
- },
- checkAppUpdata(state) {
- //#ifdef APP-PLUS
- let _temp = {
- appid: plus.runtime.appid,
- version: state.version,
- versionCode: state.versionCode,
- platform: state.platform.toLocaleLowerCase(),
- }
- //#endif
- //#ifdef H5
- //此 _temp 测试用
- let _temp = {
- appid: '1',
- version: "2.0.0",
- versionCode: "20122202",
- platform: "android",
- }
- //#endif
- reqUtil.requestData(config.URL.APPVERSIONUPDATE, _temp).then(res => {
- console.log('requestData APPVERSIONUPDATE =====', res);
- let _data = res.data;
- if (res.code == 0 && res.data.status === 1) {
- uni.showModal({ //提醒用户更新
- title: "更新提示",
- content: res.data.note,
- success: (res) => {
- if (res.confirm) {
- if (state.platform.toLocaleLowerCase() == "android") {
- plus.runtime.openURL(_data.url, function(res) {
- plus.nativeUI.alert("本机没安装应用宝,请安装后获取新版本。");
- }, 'com.tencent.android.qqdownloader');
- } else {
- //ios
- plus.runtime.openURL(_data.url);
- }
- }
- }
- })
- } else {
- uni.showToast({
- title: '当前为最新版本',
- icon: 'none',
- duration: 2000,
- mask: true
- })
- }
- },
- e => {
- console.log(e)
- });
- },
- /**
- * 蓝牙BLE迁移到store.js
- */
- // 初始化蓝牙模块适配器
- B_OpenBluetoothAdapter(state, context) {
- let {
- success,
- fail,
- complete
- } = context;
- //#ifdef H5
- console.warn('h5不加载蓝牙模块');
- return;
- //#endif
- uni.openBluetoothAdapter({
- success: res => {
- if (success)
- success(res);
- },
- fail: res => {
- if (fail)
- fail(res);
- },
- complete: res => {
- if (complete)
- complete(res);
- }
- })
- },
- /**
- * 关闭蓝牙模块适配器
- */
- B_CloseBluetoothAdapter() {
- //#ifdef H5
- console.warn('h5不加载蓝牙模块');
- return;
- //#endif
- uni.closeBluetoothAdapter({
- success: res => {
- console.log('断开蓝牙模块成功');
- uni.showToast({
- icon: "none",
- title: "蓝牙已经断开!",
- mask: false,
- duration: 3000
- });
- }
- });
- },
- B_OnBLEConnectionStateChange(state) {
- let _self = this;
- //#ifdef H5
- console.warn('h5不加载蓝牙模块');
- return;
- //#endif
- uni.onBLEConnectionStateChange(res => {
- // 该方法回调中可以用于处理连接意外断开等异常情况
- console.log(`蓝牙连接状态 -------------------------->`, JSON.stringify(res));
- if (!res.connected) {
- //要在连接的状态下 ,并且获取过匹配列表有参数的情况下,才提示重连
- if (!state.bShowBLEConnectModal && state.bVerifiedConnection) {
- state.bShowBLEConnectModal = true;
- let _connectItem = Object.assign({}, state.BLEConnectDevice);
- let _cIndex = state.cIndex;
- //断开连接后reset一下参数
- _self.commit("onResetBLEConnection");
- let _tip = state.bGamePlaying ? "蓝牙已断开是否重新连接蓝牙?重连需要重启游戏!" : "蓝牙已断开是否重新连接蓝牙";
- uni.showModal({
- title: _tip,
- success: (sRes) => {
- state.bShowBLEConnectModal = false;
- if (sRes.confirm) {
- console.log("重连的_cIndex:", _cIndex);
- _self.commit("onCreateBLEConnection", {
- item: _connectItem,
- index: _cIndex,
- initItem: true,
- getSuccess: () => {
- //此处不检查外部设备
- uni.$emit('retryConnectBLESuccess');
- },
- getinitAdapter: () => {}
- })
- }
- }
- })
- } else {
- //断开连接后reset一下参数
- _self.commit("onResetBLEConnection");
- }
- uni.$emit('callbackCloseBLE');
- }
- });
- },
- /**
- * 连接低功耗蓝牙设备。
- * 若APP在之前已有搜索过某个蓝牙设备,并成功建立连接,可直接传入之前搜索获取的 deviceId 直接尝试连接该设备,无需进行搜索操作。
- */
- B_CreateBLEConnection(state, context) {
- let {
- item,
- success,
- fail
- } = context;
- this.commit('initBLEData');
- state.deviceId = item.deviceId;
- let timeout = 10000;
- // console.log("B_CreateBLEConnection deviceId ==", state.deviceId)
- uni.createBLEConnection({
- // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
- deviceId: state.deviceId,
- timeout: timeout,
- success: res => {
- if (success) {
- success(res);
- }
- //设置mtu
- // setTimeout(() => {
- // uni.setBLEMTU({
- // deviceId: state.deviceId,
- // mtu: 80,
- // success: (res) => {
- // console.log("设置mtu");
- // console.log(res)
- // uni.$emit('log', "设置mtu=80," + JSON.stringify(
- // res));
- // },
- // fail: (error) => {
- // console.log(error)
- // }
- // })
- // }, 1000)
- },
- fail: res => {
- if (fail)
- fail(res);
- }
- });
- },
- /**
- * 获取设备的服务ID
- */
- B_GetBLEDeviceServices(state, context) {
- let {
- retryCount,
- item,
- callback,
- getServiceList,
- getFail,
- } = context;
- let serviceList = [];
- let _self = this;
- uni.getBLEDeviceServices({
- deviceId: item.deviceId,
- success: res => {
- // console.log("getBLEDeviceServices==", JSON.stringify(res), item);
- serviceList = res.services;
- if (getServiceList) {
- getServiceList(serviceList);
- }
- if (serviceList.length == 0) {
- console.log(item.deviceId + " retryCount:" + retryCount);
- if (retryCount > 0) {
- retryCount--;
- context.retryCount = retryCount;
- setTimeout(() => {
- this.commit('B_GetBLEDeviceServices', context);
- }, 1000)
- return;
- }
- if (getFail) {
- getFail();
- }
- uni.hideToast();
- uni.showModal({
- title: '提示',
- content: '1.获取服务失败,请尝试重新连接设备。\r\n2.尝试重启设备再重新连接。'
- })
- }
- for (let i = 0; i < serviceList.length; i++) {
- let service = serviceList[i];
- if (service.uuid.toLocaleLowerCase() === item.PRIMARY_SERVICE
- .toLocaleLowerCase()) {
- state.serviceId = service.uuid;
- //开始获取指定服务的特征值
- _self.commit('B_GetBLEDeviceCharacteristics', {
- item: item,
- callback: callback
- });
- break;
- }
- }
- },
- fail: failRes => {
- console.log('device services:', failRes.services);
- uni.hideToast();
- uni.showModal({
- title: '连接错误',
- content: '请尝试重新连接设备。'
- })
- if (getFail) {
- getFail();
- }
- }
- });
- },
- /**
- * 获取指定服务的特征值
- */
- B_GetBLEDeviceCharacteristics(state, context) {
- let {
- item,
- callback
- } = context;
- let deviceId = state.deviceId;
- let serviceId = state.serviceId;
- let characteristicsList = [];
- uni.getBLEDeviceCharacteristics({
- deviceId,
- serviceId,
- success: res => {
- if (item.PRIMARY_NOTIFY != '') {
- state.notifyCharacteristicId = item.PRIMARY_NOTIFY;
- this.commit('B_NotifyBLECharacteristicValueChange', {
- callback: callback
- });
- }
- if (item.PRIMARY_WRITE != '') {
- state.writeCharacteristicId = item.PRIMARY_WRITE;
- }
- },
- fail: res => {
- console.log('device getBLEDeviceCharacteristics failed:', JSON.stringify(res))
- }
- })
- },
- //启用低功耗蓝牙设备特征值变化时的 notify 功能,订阅特征值。
- //注意:必须设备的特征值支持notify或者indicate才可以成功调用,具体参照 characteristic 的 properties 属性
- B_NotifyBLECharacteristicValueChange(state, context) {
- let {
- callback
- } = context;
- // 启用notify功能
- // console.log("启用notify功能");
- uni.notifyBLECharacteristicValueChange({
- state: true,
- deviceId: state.deviceId,
- serviceId: state.serviceId,
- characteristicId: state.notifyCharacteristicId,
- success: (res) => {
- this.commit('B_OnBLECharacteristicValueChange', {
- callback: callback
- });
- },
- fail: (res) => {
- uni.showToast({
- title: 'notify启动失败',
- icon: "none",
- mask: true
- });
- }
- })
- },
- //监听低功耗蓝牙设备的特征值变化。必须先启用notify接口才能接收到设备推送的notification。
- B_OnBLECharacteristicValueChange(state, context) {
- let {
- callback
- } = context;
- // console.log("onBLECharacteristicValueChange success");
- if (callback) {
- callback({
- notifyCharacteristicId: state.notifyCharacteristicId,
- writeCharacteristicId: state.writeCharacteristicId
- })
- }
- uni.onBLECharacteristicValueChange(function(res) {
- //如果是ota 更新服务,这里处理通知ota更新数据
- if (res.serviceId.toLocaleLowerCase() === state.UUID_OTA_SERVICE) {
- uni.$emit("OTAValueChange", res);
- return;
- }
- //serviceId 0000FFF0-0000-1000-8000-00805F9B34FB characteristic 0000FFF1-0000-1000-8000-00805F9B34FB
- // console.log(`store ${res.serviceId} characteristic ${res.characteristicId} has changed, now is ${res.value}`);
- let box = {};
- var resValue = BLE.ab2hext(res.value); //16进制字符串
- if (state.currentInstruction == "V" && state.showToast) {
- var resValueStr = BLE.hexToString(resValue);
- let _info = {
- type: 'version',
- instruction: 'V',
- value: resValueStr.replace(/\{|}/g, '').trim()
- }
- uni.$emit('listenerBLE', _info);
- state.currentInstruction = "";
- state.showToast = false;
- return;
- } else if (state.currentInstruction == 'M' && state.bListenerMac) {
- var resValueStr = BLE.hexToString(resValue);
- let _info = {
- type: 'mac',
- instruction: 'M',
- value: resValueStr.replace(/\{|}/g, '').trim()
- }
- uni.$emit('listenerBLE', _info);
- state.currentInstruction = "";
- state.bListenerMac = false;
- return;
- }
- //步数数据解析
- if (state.bListenerJson) {
- var resValueStr = BLE.hexToString(resValue);
- console.log(resValueStr);
- box["Json"] = resValueStr;
- uni.$emit('updateBLEDeviceJson', box);
- }
- //解析4组加速计数据
- if (state.bListenerAccArray) {
- let accArray = [];
- // 5B00E000260019F7F4FFF6FFF1000000E200260019F7F4FFF6FFF1000000E60031001BF81AFFF5FFF0000000E90031001BF81AFFF5FFF0000000EB0031001BF81AFFF5FFF000005D: length =144
- // console.log("1======= " + BLE.buf2hex(res.value));
- // var hex =
- // '5B00E000260019F7F4FFF6FFF1000000E200260019F7F4FFF6FFF1000000E60031001BF81AFFF5FFF0000000E90031001BF81AFFF5FFF0000000EB0031001BF81AFFF5FFF000005D'
- // var typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function(h) {
- // return parseInt(h, 16)
- // }))
- // var buffer = typedArray.buffer;
- // console.log("hex= " + resValue + ",length:"+ resValue.length);
- // console.log(resValue.length);
- // console.log(res.value);
- // console.log(buffer);
- for (let i = 0; i < 5; i++) {
- let index = i * 28;
- let ms = BLE.hex2int(resValue.substr(2 + index, 4));
- // console.log(index + "==" + resValue.substr(2 + index, 4));
- let axStr = resValue.substr(6 + index, 4);
- let ayStr = resValue.substr(10 + index, 4);
- let azStr = resValue.substr(14 + index, 4);
- let gxStr = resValue.substr(18 + index, 4);
- let gyStr = resValue.substr(22 + index, 4);
- let gzStr = resValue.substr(26 + index, 4);
- //一个字节最大只能表示265 2个字节可以表示65536 然后你这边做一下转换 例如00 3E 3*16+14=62 ----->0.03 g
- //(真实值= AD值 /32768 * 16)
- //0.003 = 62 / 2768 * 16
- let ax = BLE.hexToSignedInt(axStr) / 32768 * 16;
- let ay = BLE.hexToSignedInt(ayStr) / 32768 * 16;
- let az = BLE.hexToSignedInt(azStr) / 32768 * 16;
- //角速度(AD值/32768 * 2000) 角速度单位是 °/s 范围是 正负2000
- let gx = BLE.hexToSignedInt(gxStr) / 32768 * 2000;
- let gy = BLE.hexToSignedInt(gyStr) / 32768 * 2000;
- let gz = BLE.hexToSignedInt(gzStr) / 32768 * 2000;
- accArray.push({
- acc: {
- ax: ax,
- ay: ay,
- az: az
- },
- gyro: {
- gx: gx,
- gy: gy,
- gz: gz
- },
- ms: ms
- })
- }
- uni.$emit('updateBLEDeviceData', accArray);
- // for (let i = 0; i < accArray.length; i++) {
- // let _temp = accArray[i];
- // box["acc"] = {
- // ax: _temp.ax,
- // ay: _temp.ay,
- // az: _temp.az,
- // };
- // box["gyro"] = {
- // gx: _temp.gx,
- // gy: _temp.gy,
- // gz: _temp.gz,
- // };
- // box["ms"] = _temp.ms;
- // uni.$emit('updateBLEDeviceData', box);
- // }
- }
- //原始数据解析
- if (state.bListenerUpdate) {
- //R/L 左手还是右手
- let handle = resValue.substr(6, 2);
- let axStr = resValue.substr(8, 4);
- let ayStr = resValue.substr(12, 4);
- let azStr = resValue.substr(16, 4);
- //一个字节最大只能表示265 2个字节可以表示65536 然后你这边做一下转换 例如00 3E 3*16+14=62 ----->0.03 g
- //(真实值= AD值 /32768 * 16)
- //0.003 = 62 / 2768 * 16
- let ax = BLE.hexToSignedInt(axStr) / 32768 * 16;
- let ay = BLE.hexToSignedInt(ayStr) / 32768 * 16;
- let az = BLE.hexToSignedInt(azStr) / 32768 * 16;
- let gxStr = resValue.substr(20, 4);
- let gyStr = resValue.substr(24, 4);
- let gzStr = resValue.substr(28, 4);
- //角速度(AD值/32768 * 2000) 角速度单位是 °/s 范围是 正负2000
- let gx = BLE.hexToSignedInt(gxStr) / 32768 * 2000;
- let gy = BLE.hexToSignedInt(gyStr) / 32768 * 2000;
- let gz = BLE.hexToSignedInt(gzStr) / 32768 * 2000;
- //毫秒
- let ms = BLE.hex2int(resValue.substr(2, 4));
- //分
- let min = BLE.hex2int(resValue.substr(32, 2));
- //秒
- let s = BLE.hex2int(resValue.substr(34, 2));
- box["handle"] = BLE.hexToString(handle);
- box["acc"] = {
- ax,
- ay,
- az
- };
- box["gyro"] = {
- gx,
- gy,
- gz
- };
- box["min"] = min;
- box["s"] = s;
- box["ms"] = ms;
- //更新数据给webview,在game-play-web||game-play-sub绑定
- //后面更新数据都用此接口
- uni.$emit('updateBLEDeviceData', box);
- }
- });
- },
- onTestEmit(state) {
- let box = {};
- let accArray = [];
- var resValue =
- '5B00E000260019F7F4FFF6FFF1000000E200260019F7F4FFF6FFF1000000E60031001BF81AFFF5FFF0000000E90031001BF81AFFF5FFF0000000EB0031001BF81AFFF5FFF000005D';
- for (let i = 0; i < 5; i++) {
- let index = i * 28;
- let ms = BLE.hex2int(resValue.substr(2 + index, 4));
- // console.log(index + "==" + resValue.substr(2 + index, 4));
- let axStr = resValue.substr(6 + index, 4);
- let ayStr = resValue.substr(10 + index, 4);
- let azStr = resValue.substr(14 + index, 4);
- let gxStr = resValue.substr(18 + index, 4);
- let gyStr = resValue.substr(22 + index, 4);
- let gzStr = resValue.substr(26 + index, 4);
- //一个字节最大只能表示265 2个字节可以表示65536 然后你这边做一下转换 例如00 3E 3*16+14=62 ----->0.03 g
- //(真实值= AD值 /32768 * 16)
- //0.003 = 62 / 2768 * 16
- let ax = BLE.hexToSignedInt(axStr) / 32768 * 16;
- let ay = BLE.hexToSignedInt(ayStr) / 32768 * 16;
- let az = BLE.hexToSignedInt(azStr) / 32768 * 16;
- //角速度(AD值/32768 * 2000) 角速度单位是 °/s 范围是 正负2000
- let gx = BLE.hexToSignedInt(gxStr) / 32768 * 2000;
- let gy = BLE.hexToSignedInt(gyStr) / 32768 * 2000;
- let gz = BLE.hexToSignedInt(gzStr) / 32768 * 2000;
- accArray.push({
- ax: ax,
- ay: ay,
- az: az,
- gx: gx,
- gy: gy,
- gz: gz,
- ms: ms
- })
- }
- for (let i = 0; i < accArray.length; i++) {
- let _temp = accArray[i];
- box["acc"] = {
- ax: _temp.ax,
- ay: _temp.ay,
- az: _temp.az,
- };
- box["gyro"] = {
- gx: _temp.gx,
- gy: _temp.gy,
- gz: _temp.gz,
- };
- box["ms"] = _temp.ms;
- uni.$emit('updateBLEDeviceData', box);
- }
- },
- //向低功耗蓝牙设备特征值中写入二进制数据。注意:必须设备的特征值支持 write 才可以成功调用。
- B_WriteBLECharacteristicValue(state, context) {
- let {
- value,
- retryCount,
- success,
- getFail,
- bSendHex,
- } = context;
- if (!value && value === '') {
- uni.showToast({
- title: "指令为空"
- })
- return;
- }
- let _sendData;
- if (bSendHex) {
- state.bRopeKeyTwo = 0;
- state.bRopeKeyOne = 0;
- //如果是发送16进制
- state.bListenerHexUpdate = true;
- //重置原 update
- state.bListenerUpdate = false;
- let typedArray = new Uint8Array(value.match(/[\da-f]{2}/gi).map(function(h) {
- return parseInt(h, 16)
- }))
- _sendData = typedArray.buffer;
- } else {
- state.bListenerHexUpdate = false;
- //记录一下指令
- state.currentInstruction = value;
- state.showToast = false;
- state.bListenerUpdate = false;
- state.bListenerAccArray = false;
- //V 获取版本,M 获取mac 地址
- if (value == "V")
- state.showToast = true;
- if (value == "M") {
- state.showToast = true;
- state.bListenerMac = true;
- }
- if (value == "4") {
- state.bListenerUpdate = false;
- }
- if (value == "3") {
- if (state.bListenerUpdate) {
- console.warn("原始数据已开启");
- }
- state.bListenerUpdate = true;
- }
- if (value == "h") {
- state.bListenerAccArray = false;
- }
- if (value == "H") {
- if (state.bListenerAccArray) {
- uni.showToast({
- title: "加速计组数据已开启"
- })
- return;
- }
- state.bListenerAccArray = true;
- }
- _sendData = BLE.str2ab(value);
- }
- console.log("currentInstruction:" + state.currentInstruction);
- uni.writeBLECharacteristicValue({
- deviceId: state.deviceId,
- serviceId: state.serviceId,
- // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
- characteristicId: state.writeCharacteristicId,
- // 这里的value是ArrayBuffer类型
- value: _sendData,
- success: (res) => {
- console.log('writeBLECharacteristicValue success', res.errMsg, value,
- retryCount);
- if (success) {
- success(res);
- }
- },
- fail: (fail) => {
- console.log(fail)
- //重新写入
- if (retryCount > 0) {
- console.log("writeBLECharacteristicValue Rewrite ===================>" +
- value + " == " + retryCount);
- retryCount--;
- setTimeout(() => {
- this.commit("B_WriteBLECharacteristicValue", {
- value,
- retryCount,
- success,
- getFail
- });
- }, 300);
- }
- if (getFail) {
- getFail(fail);
- }
- }
- })
- },
- B_OnSetMTU(state) {
- uni.setBLEMTU({
- deviceId: state.deviceId,
- mtu: 80,
- success: (res) => {
- console.log("设置mtu");
- console.log(res)
- uni.$emit('log', "设置mtu=80," + JSON.stringify(
- res));
- },
- fail: (error) => {
- console.log(error)
- }
- })
- },
- /**
- * 断开蓝牙连接
- */
- B_CloseBLEConnection(state, context) {
- let {
- deviceId,
- success = null
- } = context;
- uni.closeBLEConnection({
- deviceId,
- success: res => {
- console.log("关闭蓝牙连接!deviceId=" + deviceId);
- if (success)
- success();
- },
- fail: (fail) => {
- console.log("关闭蓝牙失败", fail);
- }
- });
- }
- }
- })
- export default store
|