store.js 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495
  1. import Vue from 'vue'
  2. import Vuex from 'vuex'
  3. import config from 'common/config.js'
  4. import reqUtil from 'util/util-js/requstUtil.js'
  5. import date from 'util/util-js/date.js'
  6. import cNumber from 'util/util-js/makeNumber.js'
  7. import BLE from 'util/util-js/BLE.js';
  8. //快速打击部分
  9. import o0 from "@/util/util-js/o0.js"
  10. import o0Project from "@/util/util-js/o0Project.js"
  11. import deviceData from "@/util/util-js/devices.js"
  12. Vue.use(Vuex)
  13. const store = new Vuex.Store({
  14. state: {
  15. //引导层
  16. bGuidePages: false,
  17. //是否显示Canvas
  18. bCanvasShow: true,
  19. /**
  20. * 是否需要强制登录
  21. */
  22. forcedLogin: false,
  23. /**
  24. * 蓝牙实时发送数据的页面的名称
  25. */
  26. currentPageName: '',
  27. hasLogin: false,
  28. userInfo: null,
  29. userName: "匿名",
  30. days: 0,
  31. remainingDays: 0,
  32. signature: '',
  33. avatarUrl: "/static/defaultAvatar.png",
  34. // 是否是新用户,
  35. //TODO:登录接口返回的数据来判断
  36. bNewUser: false,
  37. //是否是第一次走新手
  38. bNewGuide: false,
  39. token: '',
  40. gender: 0,
  41. //省市区数据
  42. city: {
  43. label: '北京市-北京市-东城区',
  44. cityCode: "110101",
  45. //picker 选择器的index数组
  46. value: [0, 0, 0]
  47. },
  48. birthday: date.formatTime(new Date()),
  49. //默认值
  50. height: 0,
  51. weight: 0,
  52. //最近在玩的列表
  53. playGames: [],
  54. //最近在玩的排行游戏列表
  55. playRankingGames: [],
  56. //全部的游戏列表
  57. allGames: [],
  58. //关注的游戏列表
  59. favoriteGames: [],
  60. // 排行榜里面显示的游戏
  61. rankSelectedGame: null,
  62. rankInfo: null,
  63. cityName: "某市",
  64. /**
  65. * 默认的运动数据
  66. * date.addDaysFromNewDate(new Date(),1)
  67. */
  68. defaultPlanData: {
  69. startTime: date.formatDate(new Date()),
  70. endTime: date.addDaysFromNewDate(new Date(), 6),
  71. targetWeight: 0, //目标公斤
  72. calorie: 360, //运动消耗的卡路里,默认300 大卡
  73. cumulativeCalorie: 0, //累计增重
  74. sportTime: 40, //运动时间
  75. /**
  76. * 本地记录的消耗卡路里数量
  77. */
  78. localCalorie: 0,
  79. /**
  80. * 显示卡路里,过了12点清空
  81. */
  82. showCalorie: 0,
  83. /**
  84. * 总和
  85. */
  86. allCalorie: 0
  87. },
  88. /**
  89. * 计划的运动数据
  90. */
  91. planData: {
  92. startTime: date.formatDate(new Date()),
  93. endTime: date.formatDate(new Date()), //date.addDaysFromNewDate(new Date(),1),
  94. targetWeight: 0, //目标公斤
  95. cumulativeCalorie: 0, //累计增重
  96. calorie: 300, //运动消耗的卡路里
  97. sportTime: 40, //运动时间
  98. /**
  99. * 本地记录的消耗卡路里数量
  100. */
  101. localCalorie: 0,
  102. /**
  103. * 显示卡路里,过了12点清空
  104. */
  105. showCalorie: 0,
  106. /**
  107. * 总和
  108. */
  109. allCalorie: 0
  110. },
  111. //记录表盘计划刷新的卡路里
  112. oldArcbarProCalorie: 0,
  113. //记录表盘当前的总卡路里
  114. oldArcbarAllCalorie: 0,
  115. //当前运动的世时间
  116. localSportTime: 0,
  117. //当前运动时间,运动时候记录的时间
  118. runingTime: 0,
  119. //蓝牙设备信息列表
  120. //id 不可变,用于保存到本地区分
  121. BLEInfoList: deviceData.getDeviceList(),
  122. //记录的蓝牙设备,保存id, 和对应的蓝牙连接数据
  123. BLEDeviceList: [],
  124. //显示的蓝牙设备,取本地数据时候更新
  125. BLEDeviceShowList: [],
  126. //选择连接的蓝牙设备
  127. BLEConnectDevice: null,
  128. //获取到的服务
  129. BLEGetServices: null,
  130. //当前发送给蓝牙的指令,目前是只有蓝牙手柄
  131. currentInstruction: '',
  132. instructionState: {
  133. // bAcc: false, //是否开启加速计状态
  134. // bGyroscope: false, //是否开启陀螺仪状态
  135. bOpen: false, //是否开启指令
  136. bSteps: false, //是否开启步数
  137. },
  138. //绑定的设备
  139. DeviceBindingList: [],
  140. ConnectBindingDevice: null,
  141. cIndex: -1,
  142. //当前是否连接
  143. bConnection: false,
  144. /**
  145. * 通过验证的连接,比如通过mac验证,或者说是首页直连,都设置这个参数,确保已经连上
  146. */
  147. bVerifiedConnection: false,
  148. /**
  149. * Android 出现不匹配的情况下,判断
  150. * ios 暂时没有此类问题
  151. */
  152. bPhoneMatched: false,
  153. //最近连接过的设备
  154. finallyUseDevice: null,
  155. //phoneNumber
  156. phoneNumber: '',
  157. openid: '',
  158. appleid: '',
  159. //获取验证码
  160. bCodeDisabled: false,
  161. count: 59,
  162. interval: null,
  163. //conversion列表
  164. oldSwiperList: [],
  165. // 计划任务过期
  166. bPlanExpired: false,
  167. // 制定玩计划任务后
  168. bPlanFinish: false,
  169. //标准体重,男女根据当前年龄计算
  170. standardWeight: 0,
  171. //是否安装了微信
  172. bInstallWechat: false,
  173. bHideWeixin: false,
  174. clientName:'',//但是客户端名字
  175. system: '', // 系统版本
  176. platform: '', // 平台
  177. appName: '',
  178. version: '1.6.3', //软件版本
  179. versionCode: '',
  180. showEndTime: config.endTime, //游戏显示时间字段,后台返回对应此时间之前的数据
  181. globalAcc: null,
  182. globalOri: null,
  183. //当前显示的模式下标
  184. currentModeIndex: 0,
  185. //蓝牙变量操作
  186. /**
  187. * 操作蓝牙设备
  188. */
  189. bOpenBluetooth: false,
  190. /**
  191. * 是否初始化蓝牙适配器
  192. */
  193. bOpenSuccess: false,
  194. /**
  195. * 是否监听蓝牙状态变化
  196. */
  197. bListenAdapterStateChange: false,
  198. /**
  199. * 是否监听寻找新设备事件
  200. */
  201. bListenDeviceFound: false,
  202. // 设备Id
  203. BLEDeviceId: "",
  204. // 服务Id
  205. BLEServiceId: "",
  206. // 特征值id
  207. BLENotifyCharacteristicId: "",
  208. //监听rssi对象
  209. BLERSSIInterval: null,
  210. //蓝牙服务timeout
  211. getBLEDeviceServicesTimeout: null,
  212. //本地游戏地址
  213. // http://192.168.0.112:7456/build/index.html
  214. // http://127.0.0.1:7456/build/index.html
  215. LocationGameUrl: "http://110.43.54.43/t8/",
  216. //快速打击对象
  217. filter: null,
  218. deviceMs: 1,
  219. /**
  220. * 蓝牙参数对象
  221. */
  222. // 设备Id
  223. deviceId: "",
  224. // 服务Id
  225. serviceId: "",
  226. notifyCharacteristicId: "",
  227. writeCharacteristicId: "",
  228. currentInstruction: "",
  229. showToast: false,
  230. bListenerUpdate: false,
  231. bListenerJson: false,
  232. bListenerMac: false,
  233. },
  234. mutations: {
  235. /**
  236. * 获取记录的最后一次连接设备
  237. * @param {Object} state
  238. */
  239. getFinalUseDevice(state) {
  240. // 获取本地存储的最后一次使用的设备
  241. //1.获取最近连接的蓝牙设备, 指蓝牙搜索到的obj
  242. const value = uni.getStorageSync('finallyUseDevice');
  243. if (value) {
  244. state.finallyUseDevice = value;
  245. }
  246. console.log('获取的finallyUseDevice', value);
  247. },
  248. /**
  249. * 存储最后一次使用的设备信息,后面登陆时候,如果存在设备最后一次使用信息,则自动连接
  250. * @param {Object} state
  251. * @param {Object} device
  252. */
  253. setFinallUseDevice(state, device) {
  254. uni.setStorage({
  255. key: 'finallyUseDevice',
  256. data: device,
  257. success: (res) => {
  258. state.finallyUseDevice = device;
  259. console.log("保存finallyUseDevice:", res);
  260. }
  261. })
  262. },
  263. /**
  264. * 移除记录的use device
  265. */
  266. clearFinallUseDevice(state) {
  267. uni.removeStorage({
  268. key: 'finallyUseDevice',
  269. success: (res) => {
  270. state.finallyUseDevice = null;
  271. console.log("移除finallyUseDevice:", res);
  272. }
  273. })
  274. },
  275. /**
  276. * 设置运动时间
  277. * @param {Object} state
  278. * @param {Object} time
  279. */
  280. setLocalSportTime(state, time) {
  281. // let _sportTime = Number(time);
  282. state.localSportTime = Number(time);
  283. uni.setStorage({
  284. key: 'localSportTime',
  285. data: state.localSportTime,
  286. success: (res) => {
  287. // uni.showToast({
  288. // title: "保存成功"
  289. // })
  290. }
  291. })
  292. },
  293. /**
  294. * 设置卡路里
  295. * @param {Object} state
  296. * @param {Object} calorie
  297. */
  298. setLocalCalorie(state, calorie) {
  299. state.planData.localCalorie = Number(calorie);
  300. uni.setStorage({
  301. key: 'localCalorie',
  302. data: state.planData.localCalorie,
  303. success: (res) => {
  304. // uni.showToast({
  305. // title: "保存成功"
  306. // })
  307. }
  308. })
  309. },
  310. /**
  311. * 设置表盘显示的卡路里,
  312. * @param {Object} state
  313. * @param {Object} calorie
  314. */
  315. setShowCalorie(state, calorie) {
  316. state.planData.showCalorie = Number(calorie);
  317. uni.setStorage({
  318. key: 'showCalorie',
  319. data: state.planData.showCalorie,
  320. success: (res) => {
  321. // uni.showToast({
  322. // title: "保存成功"
  323. // })
  324. }
  325. })
  326. },
  327. /**
  328. * 增加卡路里
  329. * @param {Object} state
  330. * @param {Object} calorie
  331. */
  332. addlocalCalorie(state, calorie) {
  333. //卡路里不能为负数
  334. calorie = Math.abs(calorie);
  335. //当前需要添加的卡路里
  336. let temNum = Number(calorie);
  337. //本地的卡路里
  338. let temNum2 = Number(state.planData.localCalorie);
  339. // 本地加 + 传入的卡路里
  340. let _numberLocal = temNum.add(temNum2);
  341. //显示的卡路里
  342. let _showCalorie = Number(state.planData.showCalorie);
  343. //显示的卡路里加上 本地卡路里 和添加的卡路里之和要小于或等于 计划的卡路里
  344. let _allCalorie = _numberLocal.add(_showCalorie);
  345. // console.log("计算的最后卡路里_showCalorie:", _showCalorie,_allCalorie);
  346. //如果超过计划的,用计划的卡路里记录
  347. if (_allCalorie > state.planData.calorie) {
  348. let _calorie = Number(state.planData.calorie);
  349. //假如更新时候,localCalorie 值不为0,但是还未更新给服务器,此时,不能设置localCalorie 0
  350. //用传入的值,减去 allcalorie 总和和目标的差
  351. let _value = Number(_allCalorie).sub(_calorie);
  352. let _endValue = Number(_numberLocal).sub(_value);
  353. state.planData.localCalorie = Number(_endValue.toFixed(2));
  354. //如果大于或者等于的话,用计划 于 显示的卡路里 差值
  355. // state.planData.localCalorie = Number(_calorie.sub(_showCalorie).toFixed(2));
  356. // //显示最大值
  357. // state.planData.showCalorie = Number(_calorie.sub(state.planData.localCalorie).toFixed(2));
  358. } else {
  359. //
  360. state.planData.localCalorie = Number(_numberLocal.toFixed(2));
  361. // //输入的卡路里 + 自身显示的卡路里
  362. // state.planData.showCalorie = Number(temNum.add(_showCalorie).toFixed(2));
  363. }
  364. console.log("计算的最后卡路里:", state.planData);
  365. if (state.planData.localCalorie < 0) {
  366. //如果修改计划时候,本地数据计算的结果为负数,先取总和,localCalorie负再重置为0
  367. state.planData.showCalorie = _showCalorie.add(state.planData.localCalorie);
  368. state.planData.allCalorie = state.planData.showCalorie;
  369. state.planData.localCalorie = 0;
  370. } else {
  371. state.planData.allCalorie = _showCalorie.add(state.planData.localCalorie);
  372. }
  373. try {
  374. uni.setStorageSync('localCalorie', state.planData.localCalorie);
  375. } catch (e) {
  376. // error
  377. console.error(e);
  378. }
  379. try {
  380. uni.setStorageSync('showCalorie', state.planData.showCalorie);
  381. } catch (e) {
  382. // error
  383. console.error(e);
  384. }
  385. // uni.setStorage({
  386. // key: 'localCalorie',
  387. // data: state.planData.localCalorie,
  388. // success: (res) => {
  389. // // uni.showToast({
  390. // // title: "保存成功"
  391. // // })
  392. // }
  393. // })
  394. // uni.setStorage({
  395. // key: 'showCalorie',
  396. // data: state.planData.showCalorie,
  397. // success: (res) => {
  398. // // uni.showToast({
  399. // // title: "保存成功"
  400. // // })
  401. // }
  402. // })
  403. },
  404. /**
  405. * 每次登陆同步本地数据到服务器
  406. * 当天的数据更新,只更新一次
  407. * @param {Object} state
  408. */
  409. syncLocalDataToServer(state, callback) {
  410. let self = this;
  411. uni.getStorage({
  412. key: 'syncDate',
  413. success: function(res) {
  414. // console.log(res.data);
  415. let oldTime = res.data;
  416. let nDate = new Date();
  417. let newTime = date.formatDate(nDate);
  418. let days = date.datedifference(newTime, oldTime);
  419. // console.log(days);
  420. // 如果相差大于1天,
  421. if (days != 0) {
  422. // 更新存储日期
  423. uni.setStorageSync("syncDate", newTime);
  424. // 执行更新函数
  425. self.commit("syncRequestEvent", {
  426. success: () => {
  427. //清空显示的本地数据
  428. self.commit("setShowCalorie", 0);
  429. state.planData.allCalorie = state.planData.showCalorie.
  430. add(state.planData.localCalorie);
  431. if (callback)
  432. callback({
  433. newDate: nDate
  434. });
  435. }
  436. });
  437. //清空记录的本地运动时间
  438. // console.log('情况运动时间');
  439. self.commit("setLocalSportTime", 0);
  440. //设置本地数据是0
  441. state.localSportTime = 0;
  442. } else {
  443. if (callback)
  444. callback({
  445. newDate: nDate
  446. });
  447. }
  448. // date.getDays.
  449. },
  450. fail: function(res) {
  451. // console.error(res);
  452. // 如果没有日期,则存储一个新的
  453. let nDate = new Date();
  454. let tempTime = date.formatDate(nDate);
  455. uni.setStorageSync("syncDate", tempTime);
  456. if (callback)
  457. callback({
  458. newDate: nDate
  459. });
  460. }
  461. });
  462. },
  463. // 同步数据的请求
  464. syncRequestEvent(state, data) {
  465. let self = this;
  466. let {
  467. success,
  468. fail
  469. } = data;
  470. //需要卡路里取整存服务器,小数点后面,继续保留。以消除累计误差
  471. let oldLocalCalorie = state.planData.localCalorie;
  472. let _localCalorieInt = parseInt(state.planData.localCalorie);
  473. //小数点后面
  474. let _afterLocalCalorie = Number(oldLocalCalorie).sub(_localCalorieInt);
  475. console.log("*******===:", oldLocalCalorie, _localCalorieInt, _afterLocalCalorie);
  476. if (_localCalorieInt === 0) {
  477. // uni.showToast({
  478. // title: '',
  479. // icon: 'loading',
  480. // mask: true,
  481. // duration: 1000
  482. // })
  483. if (success)
  484. success();
  485. return;
  486. }
  487. uni.showToast({
  488. title: '',
  489. icon: 'loading',
  490. mask: false,
  491. duration: 10000
  492. })
  493. //把卡路里累计到cumulativeCalorie 变量,之后传服务器 += Math.round(state.planData.localCalorie)
  494. state.planData.cumulativeCalorie += _localCalorieInt;
  495. //添加到showCalorie 中
  496. state.planData.showCalorie = Number(state.planData.showCalorie).add(_localCalorieInt);
  497. state.planData.allCalorie = state.planData.showCalorie.add(_afterLocalCalorie);
  498. //不管是否同步成功,清空本地记录的卡路里,前一步已添加到cumulativeCalorie
  499. self.commit("setLocalCalorie", _afterLocalCalorie);
  500. self.commit("setShowCalorie", Number(state.planData.showCalorie));
  501. // 把卡路里记录到服务器
  502. reqUtil.requestData(config.URL.FITNESSPROGRAM, state.planData, 'POST').then(
  503. res => {
  504. // console.warn(res);
  505. if (res.code == 0) {
  506. uni.showToast({
  507. title: '同步成功',
  508. mask: true,
  509. duration: 1000
  510. });
  511. //同步一下服务器的返回值
  512. state.planData = Object.assign(state.planData, res.data);
  513. //暂时默认同步拳击1 的卡路里
  514. reqUtil.requestData(config.URL.UPLOADRANKING, {
  515. gameId: '1', //拳击模式 game id = 1;
  516. score: _localCalorieInt,
  517. cityCode: state.city.cityCode,
  518. }, "POST").then(res => {
  519. console.warn('****上传首页拳击卡路里,后面多个模式,可能需要多个不同的游戏id ***', res);
  520. },
  521. e => {
  522. console.log(e)
  523. });
  524. setTimeout(() => {
  525. uni.hideToast();
  526. }, 1000);
  527. if (success)
  528. success();
  529. } else {
  530. state.planData.cumulativeCalorie = Number(state.planData.cumulativeCalorie).sub(_localCalorieInt);
  531. state.planData.showCalorie = Number(state.planData.showCalorie).sub(_localCalorieInt);
  532. self.commit("setLocalCalorie", oldLocalCalorie);
  533. if (fail)
  534. fail();
  535. }
  536. console.log("减法 ==", Number(state.planData.cumulativeCalorie).sub(_localCalorieInt));
  537. },
  538. e => {
  539. console.log(e);
  540. state.planData.cumulativeCalorie = Number(state.planData.cumulativeCalorie).sub(_localCalorieInt);
  541. state.planData.showCalorie = Number(state.planData.showCalorie).sub(_localCalorieInt);
  542. self.commit("setLocalCalorie", oldLocalCalorie);
  543. uni.hideToast();
  544. if (fail)
  545. fail();
  546. }
  547. );
  548. },
  549. //登录成功后,重置一下状态
  550. resetCountDown(state) {
  551. if (state.interval) {
  552. clearInterval(state.interval);
  553. state.interval = null;
  554. state.count = 59;
  555. state.bCodeDisabled = false;
  556. }
  557. },
  558. //验证码操作
  559. countDown(state, phoneNumber) {
  560. //限制验证码操作
  561. state.bCodeDisabled = true;
  562. state.interval = setInterval(() => {
  563. --state.count;
  564. if (state.count <= 0) {
  565. clearInterval(state.interval);
  566. state.interval = null;
  567. state.count = 59;
  568. state.bCodeDisabled = false;
  569. }
  570. }, 1000);
  571. setTimeout(() => {
  572. clearInterval(state.interval)
  573. state.count = 59;
  574. state.bCodeDisabled = false;
  575. }, 60000);
  576. reqUtil.requestData(config.URL.GETCODE, {
  577. "phoneNumber": phoneNumber
  578. }).then(res => {
  579. console.log('requestData GETCODE =====', res);
  580. uni.showToast({
  581. title: "发送成功",
  582. mask: true,
  583. duration: 1000
  584. })
  585. },
  586. e => {
  587. console.log(e)
  588. });
  589. },
  590. //获取记录的蓝牙列表数据
  591. getBLEDeviceList(state) {
  592. // console.log("getBLEDeviceList=");
  593. uni.getStorage({
  594. key: 'BLEDeviceList',
  595. success: (res) => {
  596. console.log("*****getBLEDeviceList=", res);
  597. let _list = res.data;
  598. state.BLEDeviceList = res.data;
  599. //更新BLEDeviceShowList 数组
  600. state.BLEDeviceShowList = [];
  601. _list.forEach(item => {
  602. //如果记录到本地的id,和信息列表中的id一致,则结合
  603. for (let i = 0; i < state.BLEInfoList.length; i++) {
  604. let eq = state.BLEInfoList[i];
  605. if (item.id == eq.id) {
  606. state.BLEDeviceShowList.push(Object.assign({}, item, eq));
  607. break;
  608. }
  609. }
  610. })
  611. }
  612. })
  613. },
  614. //添加蓝牙设备数据
  615. addBLEDevice(state, data) {
  616. let devicelist = [];
  617. if (state.BLEDeviceList && state.BLEDeviceList.length != 0) {
  618. devicelist = state.BLEDeviceList;
  619. }
  620. // console.log(data, devicelist)
  621. let bHas = false;
  622. devicelist.forEach((item, index, selfArr) => {
  623. if (item.id == data.id) {
  624. //如果存在,更新保存的数据,比如 mac或者uuid等
  625. selfArr[index] = item = Object.assign({}, item, data);
  626. bHas = true;
  627. }
  628. })
  629. //把当前添加的的蓝牙设信息备作为最后一次连接覆盖到本地
  630. this.commit('setFinallUseDevice', data);
  631. if (bHas) {
  632. return;
  633. }
  634. //设置蓝牙列表本地信息
  635. devicelist.push(data);
  636. uni.setStorage({
  637. key: 'BLEDeviceList',
  638. data: devicelist,
  639. success: (res) => {
  640. // uni.showToast({
  641. // title: "保存成功"
  642. // })
  643. state.BLEDeviceList = devicelist;
  644. // console.log("devicelist:",devicelist);
  645. //更新BLEDeviceShowList 数组
  646. state.BLEDeviceShowList = [];
  647. devicelist.forEach(item => {
  648. //如果记录到本地的id,和信息列表中的id一致,则结合
  649. for (let i = 0; i < state.BLEInfoList.length; i++) {
  650. let eq = state.BLEInfoList[i];
  651. if (item.id == eq.id) {
  652. // console.log("item:",item);
  653. state.BLEDeviceShowList.push(Object.assign({}, item, eq));
  654. break;
  655. }
  656. }
  657. })
  658. // console.log("state.BLEDeviceShowList:",state.BLEDeviceShowList);
  659. }
  660. })
  661. },
  662. //删除蓝牙设备数据
  663. deleteBLEDevice(state, index) {
  664. let devicelist = [];
  665. devicelist = state.BLEDeviceList;
  666. devicelist.splice(index, 1);
  667. uni.setStorage({
  668. key: 'BLEDeviceList',
  669. data: devicelist,
  670. success: (res) => {
  671. uni.showToast({
  672. title: "删除成功"
  673. })
  674. state.BLEDeviceList = devicelist;
  675. //更新BLEDeviceShowList 数组
  676. state.BLEDeviceShowList = [];
  677. devicelist.forEach(item => {
  678. //如果记录到本地的id,和信息列表中的id一致,则结合
  679. for (let i = 0; i < state.BLEInfoList.length; i++) {
  680. let eq = state.BLEInfoList[i];
  681. if (item.id == eq.id) {
  682. state.BLEDeviceShowList.push(Object.assign({}, item, eq));
  683. break;
  684. }
  685. }
  686. })
  687. }
  688. })
  689. },
  690. //获取计划表数据
  691. getPlanData(state, callback) {
  692. reqUtil.requestData(config.URL.FITNESSPROGRAMGET).then(res => {
  693. // console.log('获取计划表数据:getPlanData=====', res.data);
  694. if (res.code == 0) {
  695. state.planData = Object.assign(state.planData, res.data);
  696. // 处理本地数据
  697. let templocalCalorie = uni.getStorageSync("localCalorie");
  698. // console.log("templocalCalorie:", templocalCalorie, state.planData);
  699. if (templocalCalorie) {
  700. templocalCalorie = Number(templocalCalorie);
  701. if (templocalCalorie > state.planData.calorie) {
  702. state.planData.localCalorie = state.planData.calorie;
  703. uni.setStorage({
  704. key: "localCalorie",
  705. data: state.planData.localCalorie
  706. });
  707. } else {
  708. state.planData.localCalorie = templocalCalorie;
  709. }
  710. } else {
  711. state.planData.localCalorie = 0;
  712. }
  713. //处理本地的cumulativeCalorie
  714. let tempShowCalorie = uni.getStorageSync("showCalorie");
  715. // console.log("tempShowCalorie:", tempShowCalorie, state.planData);
  716. if (tempShowCalorie) {
  717. tempShowCalorie = Number(tempShowCalorie);
  718. if (tempShowCalorie > state.planData.calorie) {
  719. state.planData.showCalorie = state.planData.calorie;
  720. uni.setStorage({
  721. key: "showCalorie",
  722. data: state.planData.showCalorie
  723. });
  724. } else {
  725. state.planData.showCalorie = tempShowCalorie;
  726. }
  727. } else {
  728. state.planData.showCalorie = 0;
  729. }
  730. state.planData.allCalorie = state.planData.showCalorie.add(state.planData.localCalorie);
  731. // console.log("======",state.planData )
  732. state.days = date.datedifference(res.data.startTime, res.data.endTime) + 1;
  733. let nDate = new Date();
  734. let tempTime = date.formatDate(nDate);
  735. state.remainingDays = date.datedifference(tempTime, res.data.endTime) + 1;
  736. // console.log("state.remainingDays======", state.remainingDays);
  737. }
  738. // showArcbar
  739. if (callback) {
  740. callback();
  741. }
  742. },
  743. e => {
  744. console.log(e)
  745. });
  746. },
  747. /**
  748. * 获取全部游戏
  749. * @param {Object} state
  750. */
  751. getAllGame(state, callback) {
  752. //获得全部游戏列表
  753. if (state.allGames.length != 0) {
  754. if (callback)
  755. callback();
  756. return;
  757. }
  758. reqUtil.requestData(
  759. config.URL.GAMELIST_BY_RANKING_SHOW, {
  760. rankingShow: 1,
  761. page: 1,
  762. size: 100
  763. }
  764. ).then(res => {
  765. // console.log('获取默认的全部游戏 =====', res);
  766. if (res.code == 0) {
  767. state.allGames = [];
  768. state.allGames = state.allGames.concat(res.data);
  769. }
  770. if (callback)
  771. callback();
  772. },
  773. e => {
  774. console.log(e);
  775. if (callback)
  776. callback();
  777. }
  778. );
  779. },
  780. getRankGame(state, data) {
  781. let {
  782. param,
  783. callback
  784. } = data;
  785. reqUtil.requestData(config.URL.GETRANKRANGR, param).then(res => {
  786. console.log('获取默认的游戏数据:GETRANKRANGR=====', res);
  787. if (res.data != null) {
  788. state.rankSelectedGame = res.data.gameInfo;
  789. state.rankInfo = res.data.rankInfo;
  790. //然后获取排名
  791. }
  792. if (callback)
  793. callback(res);
  794. },
  795. e => {
  796. console.log(e)
  797. });
  798. },
  799. /**
  800. * 苹果端登陆
  801. * @param {Object} state
  802. * @param {Object} data
  803. */
  804. appleUserInfoLogin(state, data) {
  805. let self = this;
  806. let {
  807. params,
  808. callback
  809. } = data;
  810. console.log('获取用户数据:USERINFOAPPLEADD params=====', params);
  811. reqUtil.requestData(config.URL.USERINFOAPPLEADD, params, 'POST').then(res => {
  812. console.log('获取用户数据:USERINFOAPPLEADD =====', res);
  813. if (res.code == 0) {
  814. let userInfo = res.data;
  815. self.commit('login', userInfo);
  816. console.log("11~~");
  817. } else if (res.code = 201) {
  818. state.hasLogin = true;
  819. }
  820. console.log("apple callback!!!");
  821. callback();
  822. },
  823. e => {
  824. console.log(e)
  825. });
  826. },
  827. //添加用户信息和登录
  828. addUserAvatarAndLogin(state, data) {
  829. let self = this;
  830. let {
  831. params,
  832. filePath,
  833. callback
  834. } = data;
  835. console.log("addUserAvatarAndLogin 初始化对应数据");
  836. reqUtil.reqUpload(config.URL.USERINFOADDAVATARINFO, params, filePath).then(res => {
  837. console.log('获取用户数据:USERINFOADDAVATARINFO =====', res);
  838. if (res.code == 0) {
  839. let userInfo = res.data;
  840. self.commit('login', userInfo);
  841. } else if (res.code = 201) {
  842. state.hasLogin = true;
  843. }
  844. if (callback) {
  845. callback();
  846. }
  847. },
  848. e => {
  849. console.log(e)
  850. });
  851. },
  852. //app登录或h5
  853. accountLogin(state, callback) {
  854. let self = this;
  855. // console.log("app登录或h5 初始化对应数据")
  856. reqUtil.requestData(config.URL.USERINFOURL).then(res => {
  857. console.log('获取用户数据:USERINFOURL =====', res);
  858. if (res.code == 0) {
  859. let userInfo = res.data.userInfo;
  860. state.phoneNumber = res.data.phoneNumber || '';
  861. state.openid = res.data.openid || '';
  862. self.commit('login', userInfo);
  863. } else if (res.code = 201) {
  864. state.hasLogin = true;
  865. }
  866. if (callback) {
  867. callback();
  868. }
  869. },
  870. e => {
  871. console.log(e)
  872. });
  873. },
  874. //小程序页面登录
  875. login(state, userInfo) {
  876. console.log("登陆的信息==", userInfo);
  877. if (userInfo.cityCode == "" || userInfo.cityCode == null) {
  878. //不存在就设置默认值
  879. userInfo.cityCode = state.city.cityCode;
  880. }
  881. let cityCode = userInfo.cityCode;
  882. // console.log("cicicicitycode:", cityCode);
  883. let provinceData = require('@/components/slambb-picker/city-data/province.js').default;
  884. let cityData = require('@/components/slambb-picker/city-data/city.js').default;
  885. let areaData = require('@/components/slambb-picker/city-data/area.js').default;
  886. // 解析citycode
  887. for (let i = 0; i < provinceData.length; i++) {
  888. if (provinceData[i].value == cityCode.substr(0, 2)) {
  889. let currentCityData = cityData[i];
  890. for (let j = 0; j < currentCityData.length; j++) {
  891. if (currentCityData[j].value == cityCode.substr(0, 4)) {
  892. let areaDataTemp = areaData[i][j];
  893. for (let k = 0; k < areaDataTemp.length; k++) {
  894. if (areaDataTemp[k].value == cityCode) {
  895. state.city.value = [i, j, k];
  896. state.city.label = provinceData[i].label +
  897. '-' +
  898. currentCityData[j].label +
  899. '-' +
  900. areaDataTemp[k].label;
  901. state.cityName = currentCityData[j].label;
  902. break;
  903. }
  904. }
  905. break;
  906. }
  907. }
  908. break;
  909. }
  910. }
  911. state.userInfo = userInfo;
  912. state.userName = userInfo.username || '新用户';
  913. state.avatarUrl = userInfo.avatarUrl || '/static/defaultAvatar.png';
  914. state.gender = userInfo.gender;
  915. state.signature = userInfo.signature || '';
  916. state.birthday = userInfo.birthday;
  917. state.city.cityCode = cityCode.toString();
  918. state.weight = userInfo.weight || state.weight;
  919. state.height = userInfo.height || state.height;
  920. state.hasLogin = true;
  921. //登录时候 获取一下排行榜里面的游戏
  922. // this.commit('getRankGame', {
  923. // param: {
  924. // type: "china",
  925. // cityCode: 12345
  926. // }
  927. // });
  928. },
  929. // 退出登录
  930. // 删除token 操作
  931. delectToken(state, data) {
  932. let self = this;
  933. let {
  934. success
  935. } = data;
  936. reqUtil.requestData(config.URL.USERLOGINOUT, {}).then(res => {
  937. console.log('USERLOGINOUT=====', res);
  938. self.commit("logout");
  939. try {
  940. //清空保存的storage
  941. uni.clearStorageSync();
  942. } catch (e) {
  943. // error
  944. console.error(e);
  945. }
  946. if (state.BLERSSIInterval) {
  947. clearInterval(state.BLERSSIInterval);
  948. state.BLERSSIInterval = null;
  949. }
  950. if (state.BLEConnectDevice) {
  951. self.commit("onCloseBLEConnection", {
  952. getSuccess: () => {}
  953. });
  954. }
  955. if (success) {
  956. success(res);
  957. }
  958. },
  959. e => {
  960. console.log(e)
  961. });
  962. },
  963. logout(state) {
  964. state.userInfo = null;
  965. state.userName = "匿名";
  966. state.avatarUrl = '/static/defaultAvatar.png';
  967. state.days = '0';
  968. state.signature = '';
  969. state.gender = 0;
  970. state.hasLogin = false;
  971. state.phoneNumber = '';
  972. state.openid = '';
  973. state.appleid = '';
  974. //处理设备值
  975. state.cIndex = -1;
  976. //绑定的设备
  977. state.ConnectBindingDevice = null;
  978. //蓝牙设备
  979. state.BLEConnectDevice = null;
  980. //蓝牙服务
  981. state.BLEGetServices = null;
  982. //最近连接过的设备
  983. state.finallyUseDevice = null;
  984. //记录的蓝牙设备,保存id, 和对应的蓝牙连接数据
  985. state.BLEDeviceList = [];
  986. //显示的蓝牙设备,取本地数据时候更新
  987. state.BLEDeviceShowList = [];
  988. //记录表盘计划刷新的卡路里
  989. state.oldArcbarProCalorie = 0;
  990. //记录表盘当前的总卡路里
  991. state.oldArcbarAllCalorie = 0;
  992. },
  993. loginUserInfo(state, data) {
  994. let {
  995. infoRes,
  996. success,
  997. fail
  998. } = data;
  999. console.log('loginUserInfo');
  1000. reqUtil.requestData(config.URL.WXGETUSERINFO, {
  1001. appid: 'wxd6dfd60729d33d17',
  1002. encryptedData: infoRes.encryptedData,
  1003. iv: infoRes.iv,
  1004. signature: infoRes.signature,
  1005. rawData: infoRes.rawData
  1006. }).then(res => {
  1007. console.log('wxInfoRes=====', res);
  1008. let userInfo = res.data;
  1009. this.commit('login', userInfo);
  1010. if (success) {
  1011. success(res);
  1012. }
  1013. },
  1014. e => {
  1015. console.log(e)
  1016. if (fail) {
  1017. success(fail);
  1018. }
  1019. });
  1020. },
  1021. //这里统一静默处理login
  1022. oauth(state, context) {
  1023. let {
  1024. value,
  1025. callback
  1026. } = context;
  1027. uni.login({
  1028. provider: value,
  1029. success: (res) => {
  1030. // console.log('code:', res);
  1031. reqUtil.requestData(config.URL.USERlOGINURL, {
  1032. appid: 'wxd6dfd60729d33d17',
  1033. code: res.code,
  1034. platfrom: value
  1035. }).then(res => {
  1036. console.log('login token=====', res);
  1037. state.token = res.data.token;
  1038. uni.setStorageSync('token', state.token);
  1039. uni.getUserInfo({
  1040. provider: value,
  1041. success: (infoRes) => {
  1042. if (callback) {
  1043. callback(infoRes);
  1044. }
  1045. },
  1046. fail: (failRes) => {
  1047. //假如没有授权,login 之后,不做处理,需要用户点击授权时候,再进行处理用户登录
  1048. console.log('getUserInfo failRes:', failRes)
  1049. }
  1050. });
  1051. },
  1052. e => {
  1053. console.log(e)
  1054. });
  1055. },
  1056. fail: (err) => {
  1057. console.error('授权登录失败:' + JSON.stringify(err));
  1058. }
  1059. });
  1060. },
  1061. onLuanchLogin(state, data) {
  1062. let {
  1063. success
  1064. } = data;
  1065. const filters = ['weixin', 'qq', 'sinaweibo'];
  1066. let platform = '';
  1067. uni.getProvider({
  1068. service: 'oauth',
  1069. success: (res) => {
  1070. if (res.provider && res.provider.length) {
  1071. for (let i = 0; i < res.provider.length; i++) {
  1072. if (~filters.indexOf(res.provider[i])) {
  1073. platform = res.provider[i];
  1074. console.log("platform=", platform);
  1075. uni.showToast({
  1076. icon: 'loading',
  1077. title: ''
  1078. })
  1079. this.commit('oauth', {
  1080. value: platform,
  1081. callback: (infoRes) => {
  1082. // console.log("infoRes:", infoRes);
  1083. this.commit('loginUserInfo', {
  1084. infoRes: infoRes,
  1085. success: (res) => {
  1086. console.log("获取用户成功");
  1087. if (success) {
  1088. success(res);
  1089. }
  1090. uni.hideToast();
  1091. },
  1092. fail: (res) => {
  1093. console.error("获取用户失败");
  1094. uni.hideToast();
  1095. }
  1096. });
  1097. }
  1098. })
  1099. }
  1100. }
  1101. this.hasProvider = true;
  1102. }
  1103. },
  1104. fail: (err) => {
  1105. console.error('获取服务供应商失败:' + JSON.stringify(err));
  1106. }
  1107. });
  1108. },
  1109. initAdapter(state, callback) {
  1110. //初始化蓝牙模块
  1111. let params = {
  1112. success: (res) => {
  1113. state.bOpenSuccess = true;
  1114. state.bOpenBluetooth = true;
  1115. if (callback)
  1116. callback(res);
  1117. //监听断开事件
  1118. this.commit("B_OnBLEConnectionStateChange");
  1119. },
  1120. fail: (fail) => {
  1121. state.bOpenSuccess = false;
  1122. state.bOpenBluetooth = false;
  1123. uni.showToast({
  1124. title: '蓝牙尚未开启!',
  1125. icon: 'none'
  1126. })
  1127. },
  1128. complete: (complete) => {
  1129. console.log("complete bListenAdapterStateChange:", state.bListenAdapterStateChange);
  1130. if (state.bListenAdapterStateChange) return;
  1131. state.bListenAdapterStateChange = true;
  1132. uni.onBluetoothAdapterStateChange((res) => {
  1133. console.log('adapterState changed, now is', res)
  1134. // 手机蓝牙状态
  1135. state.bOpenBluetooth = res.available;
  1136. if (state.bOpenBluetooth && !state.bOpenSuccess) {
  1137. this.commit('initAdapter');
  1138. }
  1139. })
  1140. }
  1141. };
  1142. this.commit("B_OpenBluetoothAdapter", params);
  1143. },
  1144. // todo 未使用到
  1145. onGetDevices(state, context) {
  1146. let {
  1147. success
  1148. } = context;
  1149. if (!state.BLEConnectDevice) return;
  1150. // #ifdef APP-PLUS
  1151. let deviceId = state.BLEConnectDevice.deviceId;
  1152. uni.getBLEDeviceRSSI({
  1153. deviceId,
  1154. success: res => {
  1155. let _dis = Math.pow(Math.E, (Math.abs(res.RSSI) - 66.78) / 16.56);
  1156. if (_dis > state.BLEConnectDevice.limitDis) {
  1157. if (state.cIndex != -1) {
  1158. uni.showToast({
  1159. title: '设备断开连接!',
  1160. icon: 'none',
  1161. duration: 2000,
  1162. mask: true
  1163. })
  1164. }
  1165. setTimeout(() => {
  1166. this.commit("B_CloseBLEConnection", {
  1167. deviceId: deviceId
  1168. })
  1169. state.cIndex = -1;
  1170. state.bConnection = false;
  1171. state.bVerifiedConnection = false;
  1172. }, 1000)
  1173. } else {
  1174. // console.log("DIS~~~~~~~~~", _dis);
  1175. if (success) {
  1176. success({
  1177. RSSI: res.RSSI,
  1178. DIS: _dis
  1179. });
  1180. }
  1181. }
  1182. }
  1183. })
  1184. // #endif
  1185. },
  1186. //清除连接的开启的timeout
  1187. onUnloadCreateBLEConnectionTimeout(state) {
  1188. if (state.getBLEDeviceServicesTimeout) {
  1189. clearTimeout(state.getBLEDeviceServicesTimeout);
  1190. state.getBLEDeviceServicesTimeout = null;
  1191. }
  1192. },
  1193. initBLEData(state) {
  1194. // 设备Id
  1195. state.deviceId = "";
  1196. // 服务Id
  1197. state.serviceId = "";
  1198. state.notifyCharacteristicId = "";
  1199. state.writeCharacteristicId = "";
  1200. state.currentInstruction = "";
  1201. state.showToast = false;
  1202. state.bListenerUpdate = false;
  1203. state.bListenerJson = false;
  1204. state.bListenerMac = false;
  1205. },
  1206. //连接蓝牙
  1207. onCreateBLEConnection(state, context) {
  1208. let {
  1209. index,
  1210. item,
  1211. initItem = false,
  1212. getSuccess = null,
  1213. getinitAdapter = null
  1214. } = context;
  1215. let params = {
  1216. item: item,
  1217. success: (success) => {
  1218. // uni.getBluetoothDevices({
  1219. // success(res) {
  1220. // console.log("getBluetoothDevices:", res)
  1221. // }
  1222. // })
  1223. // uni.getConnectedBluetoothDevices({
  1224. // success(res) {
  1225. // console.log("getConnectedBluetoothDevices:", res)
  1226. // }
  1227. // })
  1228. state.bConnection = true;
  1229. if (state.getBLEDeviceServicesTimeout) {
  1230. clearTimeout(state.getBLEDeviceServicesTimeout);
  1231. state.getBLEDeviceServicesTimeout = null;
  1232. }
  1233. state.getBLEDeviceServicesTimeout = setTimeout(() => {
  1234. let retryCount = 5;
  1235. this.commit("B_GetBLEDeviceServices", {
  1236. retryCount: retryCount,
  1237. item: item,
  1238. callback: () => {
  1239. uni.showToast({
  1240. title: '连接成功',
  1241. icon: 'loading',
  1242. duration: 2000,
  1243. mask: true
  1244. })
  1245. //是否需要设置item,默认不设置
  1246. if (initItem) {
  1247. state.cIndex = index;
  1248. state.BLEConnectDevice = item;
  1249. }
  1250. if (getSuccess)
  1251. getSuccess();
  1252. /**
  1253. * 直接连接过成功
  1254. */
  1255. state.bVerifiedConnection = true;
  1256. },
  1257. getServiceList: (serviceList) => {
  1258. //搜索服务失败后
  1259. state.BLEGetServices = serviceList;
  1260. },
  1261. getFail: () => {
  1262. this.commit("B_CloseBLEConnection", {
  1263. deviceId: item.deviceId
  1264. })
  1265. state.cIndex = -1;
  1266. state.bConnection = false;
  1267. state.bVerifiedConnection = false;
  1268. }
  1269. });
  1270. }, 2000);
  1271. },
  1272. fail: (fail) => {
  1273. console.log("***fail:", fail);
  1274. if (fail.errCode === 10012) {
  1275. console.log("连接超时,请重试!");
  1276. uni.showToast({
  1277. title: '连接失败,设备无响应,请重试。',
  1278. icon: 'none',
  1279. duration: 3000,
  1280. mask: true
  1281. })
  1282. } else if (fail.errCode === 10013) {
  1283. console.log("连接失败,蓝牙地址无效!");
  1284. uni.showToast({
  1285. title: '连接失败,蓝牙地址无效',
  1286. icon: 'none',
  1287. duration: 2000,
  1288. mask: true
  1289. })
  1290. } else if (fail.errCode === 10000) {
  1291. // console.log("连接失败,初始化 uni.openBluetoothAdapter 调用之后使用");
  1292. // uni.showToast({
  1293. // title: '连接失败,检查手机蓝牙是否开启',
  1294. // icon: 'none',
  1295. // duration: 2000,
  1296. // mask: true
  1297. // })
  1298. this.commit('initAdapter', () => {
  1299. if (getinitAdapter) {
  1300. getinitAdapter();
  1301. }
  1302. })
  1303. // this.initAdapter(() => {
  1304. // this.onDevice(item, e);
  1305. // });
  1306. } else {
  1307. // err.errCode10003原因多种:蓝牙设备未开启或异常导致无法连接;蓝牙设备被占用或者上次蓝牙连接未断开导致无法连接
  1308. console.log("连接失败,请重试!");
  1309. uni.showToast({
  1310. title: '设备未开启或被占用异常导致无法连接。',
  1311. icon: 'none',
  1312. duration: 2000,
  1313. mask: true
  1314. })
  1315. }
  1316. }
  1317. };
  1318. this.commit("B_CreateBLEConnection", params);
  1319. },
  1320. //devices hardware 连接后验证,这里不需要处理 bVerifiedConnection,通过mac 验证后处理
  1321. onCreateBLESuccess(state, context) {
  1322. let {
  1323. item,
  1324. getSuccess = null
  1325. } = context;
  1326. this.commit("B_CreateBLEConnection", {
  1327. item: item,
  1328. success: success => {
  1329. state.BLEConnectDevice = item;
  1330. state.bConnection = true;
  1331. if (getSuccess) {
  1332. getSuccess();
  1333. }
  1334. },
  1335. fail: fail => {
  1336. if (fail.errCode === 10012) {
  1337. console.log("连接超时,请重试!");
  1338. uni.showToast({
  1339. title: '连接超时,检查对应设备是否开启?',
  1340. icon: 'none',
  1341. duration: 2000,
  1342. mask: true
  1343. })
  1344. } else if (fail.errCode === 10013) {
  1345. console.log("连接失败,蓝牙地址无效!");
  1346. uni.showToast({
  1347. title: '蓝牙地址无效,检查设备是否正常?',
  1348. icon: 'none',
  1349. duration: 2000,
  1350. mask: true
  1351. })
  1352. } else if (fail.errCode === 10000) {
  1353. console.log("连接失败,初始化 wx.openBluetoothAdapter 调用之后使用");
  1354. uni.showToast({
  1355. title: '连接失败,检查手机蓝牙是否开启?',
  1356. icon: 'none',
  1357. duration: 2000,
  1358. mask: true
  1359. })
  1360. } else {
  1361. console.log("连接失败,请重试!");
  1362. uni.showModal({
  1363. title: '连接失败',
  1364. content: '设备未开启或被占用。请重启app和设备后重新连接。'
  1365. })
  1366. // uni.showToast({
  1367. // title: '设备未开启或被占用异常导致无法连接。',
  1368. // icon: 'none',
  1369. // duration: 2000,
  1370. // mask: true
  1371. // })
  1372. }
  1373. }
  1374. });
  1375. },
  1376. //获取蓝牙服务
  1377. onGetBLEDeviceServices(state, context) {
  1378. let {
  1379. item,
  1380. success = null,
  1381. } = context;
  1382. let retryCount = 5;
  1383. this.commit("B_GetBLEDeviceServices", {
  1384. retryCount: retryCount,
  1385. item: item,
  1386. callback: success,
  1387. getServiceList: (serviceList) => {
  1388. state.BLEGetServices = serviceList;
  1389. },
  1390. getFail: () => {}
  1391. })
  1392. },
  1393. onCloseBLEConnection(state, context) {
  1394. console.log("onCloseBLEConnection", state.BLEConnectDevice);
  1395. let {
  1396. getSuccess = null,
  1397. } = context;
  1398. if (state.BLERSSIInterval) {
  1399. clearInterval(state.BLERSSIInterval);
  1400. state.BLERSSIInterval = null;
  1401. }
  1402. this.commit("B_CloseBLEConnection", {
  1403. deviceId: state.BLEConnectDevice.deviceId,
  1404. success: () => {
  1405. state.cIndex = -1;
  1406. state.BLEConnectDevice = null;
  1407. //蓝牙服务
  1408. state.BLEGetServices = null;
  1409. if (getSuccess) {
  1410. getSuccess();
  1411. }
  1412. state.bConnection = false;
  1413. state.bVerifiedConnection = false;
  1414. uni.closeBluetoothAdapter({
  1415. success(res) {
  1416. console.log(res)
  1417. state.bOpenBluetooth = false;
  1418. }
  1419. })
  1420. }
  1421. });
  1422. },
  1423. //不关闭 adapter
  1424. onOnlyCloseBLEConnection(state, context) {
  1425. let {
  1426. getSuccess = null
  1427. } = context;
  1428. if (state.BLERSSIInterval) {
  1429. clearInterval(state.BLERSSIInterval);
  1430. state.BLERSSIInterval = null;
  1431. }
  1432. this.commit("B_CloseBLEConnection", {
  1433. deviceId: state.BLEConnectDevice.deviceId,
  1434. success: () => {
  1435. state.cIndex = -1;
  1436. state.BLEConnectDevice = null;
  1437. //蓝牙服务
  1438. state.BLEGetServices = null;
  1439. if (getSuccess) {
  1440. getSuccess();
  1441. }
  1442. state.bConnection = false;
  1443. state.bVerifiedConnection = false;
  1444. }
  1445. });
  1446. },
  1447. onWriteBLEConnectionValue(state, context) {
  1448. let {
  1449. getSuccess = null,
  1450. getFail = null,
  1451. value
  1452. } = context;
  1453. if (!state.BLEConnectDevice && state.cIndex == -1) {
  1454. uni.showToast({
  1455. title: '蓝牙设备未连接',
  1456. icon: 'none'
  1457. })
  1458. }
  1459. // console.log(22);
  1460. //记录蓝牙盒子当前的指令
  1461. state.currentInstruction = value;
  1462. // 发送 3 :开启原始数据
  1463. // 发送4 :关闭原始数据
  1464. // 发送 5 :开启步数
  1465. // 发送6 :关闭步数
  1466. if (value == "3") {
  1467. state.instructionState.bOpen = true;
  1468. } else if (value == "4") {
  1469. state.instructionState.bOpen = false;
  1470. } else if (value == "5") {
  1471. state.instructionState.bSteps = true;
  1472. } else if (value == "6") {
  1473. state.instructionState.bSteps = false;
  1474. }
  1475. let retryCount = 5;
  1476. this.commit("B_WriteBLECharacteristicValue", {
  1477. value,
  1478. retryCount,
  1479. getSuccess,
  1480. getFail
  1481. });
  1482. },
  1483. //获取距离
  1484. onGetRSSITransDistance(state, context) {
  1485. let {
  1486. RSSI
  1487. } = context;
  1488. BLE.getRSSITransDistance(RSSI);
  1489. },
  1490. //添加使用的前端信息
  1491. gOnAddClientInfo(state, context) {
  1492. uni.getSystemInfo({
  1493. success: (res) => {
  1494. // console.log("系统信息:", res);
  1495. let clientInfo = res;
  1496. clientInfo.clientSystem = res.system;
  1497. reqUtil.requestData(config.URL.ADDCLIENTINFO, clientInfo, 'POST').then(
  1498. res => {
  1499. console.warn(res);
  1500. },
  1501. e => {}
  1502. );
  1503. },
  1504. fail: (err) => {},
  1505. complete: () => {}
  1506. })
  1507. },
  1508. //创建快速打击对象
  1509. gCreateFilterObj(state) {
  1510. state.filter = null;
  1511. state.deviceMs = 1;
  1512. state.filter = new o0Project.Filter();
  1513. console.log("gCreateFilterObj");
  1514. },
  1515. //更新快速打击对象数据
  1516. gUpdateFilter(state, context) {
  1517. let {
  1518. data,
  1519. callback
  1520. } = context;
  1521. let {
  1522. min,
  1523. s,
  1524. ms
  1525. } = data;
  1526. var msGap = ms - state.deviceMs;
  1527. state.deviceMs = ms;
  1528. while (msGap < 0) {
  1529. msGap += 1000;
  1530. }
  1531. // console.log(data);
  1532. let {
  1533. ax,
  1534. ay,
  1535. az
  1536. } = data.acc;
  1537. state.filter.Update(new o0.Vector3(ax, ay, az), msGap, callback); //我自己的更新acc的函数
  1538. },
  1539. /**
  1540. * 限制开始游戏
  1541. */
  1542. glimitPlayGame(state, context) {
  1543. let {
  1544. gameTags,
  1545. callback
  1546. } = context;
  1547. //没有标签直接进去
  1548. if (gameTags.length == 0) {
  1549. callback();
  1550. return;
  1551. }
  1552. let canPlay = false;
  1553. gameTags.forEach((item) => {
  1554. //如果存在普通模式
  1555. if (item.tagMode === 'normal') {
  1556. canPlay = true;
  1557. }
  1558. if (canPlay)
  1559. return;
  1560. })
  1561. if (!canPlay) {
  1562. //2.如果普通模式不存在,就判断是否连接硬件了
  1563. if (!state.BLEConnectDevice || state.cIndex == -1) {
  1564. uni.showToast({
  1565. title: "请连接标签对应的设备模式!",
  1566. icon: "none",
  1567. duration: 2000,
  1568. mask: true
  1569. })
  1570. return;
  1571. }
  1572. //3.如果连接了设备,判断但是处于什么模式
  1573. gameTags.forEach((item, index, selfArr) => {
  1574. //如果存在普通模式
  1575. if (item.tagMode === state.BLEConnectDevice.usageMode) {
  1576. canPlay = true;
  1577. }
  1578. if (canPlay)
  1579. return;
  1580. if (index == selfArr.length - 1) {
  1581. uni.showToast({
  1582. title: "游戏没有当前设备模式!",
  1583. icon: "none",
  1584. duration: 2000,
  1585. mask: true
  1586. })
  1587. }
  1588. })
  1589. }
  1590. if (canPlay) {
  1591. callback();
  1592. }
  1593. },
  1594. checkAppUpdata(state) {
  1595. //#ifdef APP-PLUS
  1596. let _temp = {
  1597. appid: plus.runtime.appid,
  1598. version: state.version,
  1599. versionCode: state.versionCode,
  1600. platform: state.platform.toLocaleLowerCase(),
  1601. }
  1602. //#endif
  1603. //#ifdef H5
  1604. //此 _temp 测试用
  1605. let _temp = {
  1606. appid: '1',
  1607. version: "2.0.0",
  1608. versionCode: "20122202",
  1609. platform: "android",
  1610. }
  1611. //#endif
  1612. reqUtil.requestData(config.URL.APPVERSIONUPDATE, _temp).then(res => {
  1613. console.log('requestData APPVERSIONUPDATE =====', res);
  1614. let _data = res.data;
  1615. if (res.code == 0 && res.data.status === 1) {
  1616. uni.showModal({ //提醒用户更新
  1617. title: "更新提示",
  1618. content: res.data.note,
  1619. success: (res) => {
  1620. if (res.confirm) {
  1621. if (state.platform.toLocaleLowerCase() == "android") {
  1622. plus.runtime.openURL(_data.url, function(res) {
  1623. plus.nativeUI.alert("本机没安装应用宝,请安装后获取新版本。");
  1624. }, 'com.tencent.android.qqdownloader');
  1625. } else {
  1626. //ios
  1627. plus.runtime.openURL(_data.url);
  1628. }
  1629. }
  1630. }
  1631. })
  1632. } else {
  1633. uni.showToast({
  1634. title: '当前为最新版本',
  1635. icon: 'none',
  1636. duration: 2000,
  1637. mask: true
  1638. })
  1639. }
  1640. },
  1641. e => {
  1642. console.log(e)
  1643. });
  1644. },
  1645. /**
  1646. * 蓝牙BLE迁移到store.js
  1647. */
  1648. // 初始化蓝牙模块适配器
  1649. B_OpenBluetoothAdapter(state, context) {
  1650. let {
  1651. success,
  1652. fail,
  1653. complete
  1654. } = context;
  1655. //#ifdef H5
  1656. console.warn('h5不加载蓝牙模块');
  1657. return;
  1658. //#endif
  1659. uni.openBluetoothAdapter({
  1660. success: res => {
  1661. if (success)
  1662. success(res);
  1663. },
  1664. fail: res => {
  1665. if (fail)
  1666. fail(res);
  1667. },
  1668. complete: res => {
  1669. if (complete)
  1670. complete(res);
  1671. }
  1672. })
  1673. },
  1674. /**
  1675. * 关闭蓝牙模块适配器
  1676. */
  1677. B_CloseBluetoothAdapter() {
  1678. //#ifdef H5
  1679. console.warn('h5不加载蓝牙模块');
  1680. return;
  1681. //#endif
  1682. uni.closeBluetoothAdapter({
  1683. success: res => {
  1684. console.log('断开蓝牙模块成功');
  1685. uni.showToast({
  1686. icon: "none",
  1687. title: "蓝牙已经断开!",
  1688. mask: false,
  1689. duration: 3000
  1690. });
  1691. }
  1692. });
  1693. },
  1694. B_OnBLEConnectionStateChange(state) {
  1695. //#ifdef H5
  1696. console.warn('h5不加载蓝牙模块');
  1697. return;
  1698. //#endif
  1699. uni.onBLEConnectionStateChange(res => {
  1700. // 该方法回调中可以用于处理连接意外断开等异常情况
  1701. console.log(`蓝牙连接状态 -------------------------->`, JSON.stringify(res));
  1702. if (!res.connected) {
  1703. uni.$emit('callbackCloseBLE');
  1704. }
  1705. });
  1706. },
  1707. /**
  1708. * 连接低功耗蓝牙设备。
  1709. * 若APP在之前已有搜索过某个蓝牙设备,并成功建立连接,可直接传入之前搜索获取的 deviceId 直接尝试连接该设备,无需进行搜索操作。
  1710. */
  1711. B_CreateBLEConnection(state, context) {
  1712. let {
  1713. item,
  1714. success,
  1715. fail
  1716. } = context;
  1717. this.commit('initBLEData');
  1718. state.deviceId = item.deviceId;
  1719. let timeout = 10000;
  1720. console.log("B_CreateBLEConnection deviceId ==", state.deviceId)
  1721. uni.createBLEConnection({
  1722. // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
  1723. deviceId: state.deviceId,
  1724. timeout: timeout,
  1725. success: res => {
  1726. if (success) {
  1727. success(res);
  1728. }
  1729. },
  1730. fail: res => {
  1731. if (fail)
  1732. fail(res);
  1733. }
  1734. });
  1735. },
  1736. /**
  1737. * 获取设备的服务ID
  1738. */
  1739. B_GetBLEDeviceServices(state, context) {
  1740. let {
  1741. retryCount,
  1742. item,
  1743. callback,
  1744. getServiceList,
  1745. getFail,
  1746. } = context;
  1747. let serviceList = [];
  1748. let _self = this;
  1749. uni.getBLEDeviceServices({
  1750. deviceId: item.deviceId,
  1751. success: res => {
  1752. console.log("getBLEDeviceServices==", JSON.stringify(res), item);
  1753. serviceList = res.services;
  1754. if (getServiceList) {
  1755. getServiceList(serviceList);
  1756. }
  1757. if (serviceList.length == 0) {
  1758. if (retryCount > 0) {
  1759. retryCount--;
  1760. context.retryCount = retryCount;
  1761. setTimeout(() => {
  1762. this.commit('B_GetBLEDeviceServices', context);
  1763. }, 500)
  1764. return;
  1765. }
  1766. if (getFail) {
  1767. getFail();
  1768. }
  1769. uni.hideToast();
  1770. uni.showModal({
  1771. title: '提示',
  1772. content: '1.获取服务失败,请尝试重新连接设备。\r\n2.尝试重启设备再重新连接。'
  1773. })
  1774. }
  1775. for (let i = 0; i < serviceList.length; i++) {
  1776. let service = serviceList[i];
  1777. if (service.uuid.toLocaleLowerCase() === item.PRIMARY_SERVICE.toLocaleLowerCase()) {
  1778. state.serviceId = service.uuid;
  1779. //开始获取指定服务的特征值
  1780. _self.commit('B_GetBLEDeviceCharacteristics', {
  1781. item: item,
  1782. callback: callback
  1783. });
  1784. break;
  1785. }
  1786. }
  1787. },
  1788. fail: failRes => {
  1789. console.log('device services:', failRes.services)
  1790. uni.showModal({
  1791. title: '连接失败',
  1792. content: '未获取到相应服务,请继续尝试连接设备。'
  1793. })
  1794. }
  1795. });
  1796. },
  1797. /**
  1798. * 获取指定服务的特征值
  1799. */
  1800. B_GetBLEDeviceCharacteristics(state, context) {
  1801. let {
  1802. item,
  1803. callback
  1804. } = context;
  1805. let deviceId = state.deviceId;
  1806. let serviceId = state.serviceId;
  1807. let characteristicsList = [];
  1808. uni.getBLEDeviceCharacteristics({
  1809. deviceId,
  1810. serviceId,
  1811. success: res => {
  1812. if (item.PRIMARY_NOTIFY != '') {
  1813. state.notifyCharacteristicId = item.PRIMARY_NOTIFY;
  1814. this.commit('B_NotifyBLECharacteristicValueChange', {
  1815. callback: callback
  1816. });
  1817. }
  1818. if (item.PRIMARY_WRITE != '') {
  1819. state.writeCharacteristicId = item.PRIMARY_WRITE;
  1820. }
  1821. },
  1822. fail: res => {
  1823. console.log('device getBLEDeviceCharacteristics failed:', JSON.stringify(res))
  1824. }
  1825. })
  1826. },
  1827. //启用低功耗蓝牙设备特征值变化时的 notify 功能,订阅特征值。
  1828. //注意:必须设备的特征值支持notify或者indicate才可以成功调用,具体参照 characteristic 的 properties 属性
  1829. B_NotifyBLECharacteristicValueChange(state, context) {
  1830. let {
  1831. callback
  1832. } = context;
  1833. // 启用notify功能
  1834. // console.log("启用notify功能");
  1835. uni.notifyBLECharacteristicValueChange({
  1836. state: true,
  1837. deviceId: state.deviceId,
  1838. serviceId: state.serviceId,
  1839. characteristicId: state.notifyCharacteristicId,
  1840. success: (res) => {
  1841. this.commit('B_OnBLECharacteristicValueChange', {
  1842. callback: callback
  1843. });
  1844. // _self.onBLECharacteristicValueChange(callback); //监听特征值变化
  1845. },
  1846. fail: (res) => {
  1847. uni.showToast({
  1848. title: 'notify启动失败',
  1849. icon: "none",
  1850. mask: true
  1851. });
  1852. }
  1853. })
  1854. },
  1855. //监听低功耗蓝牙设备的特征值变化。必须先启用notify接口才能接收到设备推送的notification。
  1856. B_OnBLECharacteristicValueChange(state, context) {
  1857. let {
  1858. callback
  1859. } = context;
  1860. console.log("onBLECharacteristicValueChange success");
  1861. if (callback) {
  1862. callback({
  1863. notifyCharacteristicId: state.notifyCharacteristicId,
  1864. writeCharacteristicId: state.writeCharacteristicId
  1865. })
  1866. }
  1867. uni.onBLECharacteristicValueChange(function(res) {
  1868. let box = {};
  1869. var resValue = BLE.ab2hext(res.value); //16进制字符串
  1870. if (state.currentInstruction == "V" && state.showToast) {
  1871. var resValueStr = BLE.hexToString(resValue);
  1872. let _info = {
  1873. type: 'version',
  1874. instruction: 'V',
  1875. value: resValueStr.replace(/\{|}/g, '').trim()
  1876. }
  1877. uni.$emit('listenerBLE', _info);
  1878. state.currentInstruction = "";
  1879. state.showToast = false;
  1880. return;
  1881. } else if (state.currentInstruction == 'M' && state.bListenerMac) {
  1882. var resValueStr = BLE.hexToString(resValue);
  1883. let _info = {
  1884. type: 'mac',
  1885. instruction: 'M',
  1886. value: resValueStr.replace(/\{|}/g, '').trim()
  1887. }
  1888. uni.$emit('listenerBLE', _info);
  1889. state.currentInstruction = "";
  1890. state.bListenerMac = false;
  1891. return;
  1892. }
  1893. //步数数据解析
  1894. if (state.bListenerJson) {
  1895. var resValueStr = BLE.hexToString(resValue);
  1896. console.log(resValueStr);
  1897. box["Json"] = resValueStr;
  1898. uni.$emit('updateBLEDeviceJson', box);
  1899. }
  1900. //原始数据解析
  1901. if (state.bListenerUpdate) {
  1902. //R/L 左手还是右手
  1903. let handle = resValue.substr(6, 2);
  1904. let axStr = resValue.substr(8, 4);
  1905. let ayStr = resValue.substr(12, 4);
  1906. let azStr = resValue.substr(16, 4);
  1907. //一个字节最大只能表示265 2个字节可以表示65536 然后你这边做一下转换 例如00 3E 3*16+14=62 ----->0.03 g
  1908. //(真实值= AD值 /32768 * 16)
  1909. //0.003 = 62 / 2768 * 16
  1910. let ax = BLE.hexToSignedInt(axStr) / 32768 * 16;
  1911. let ay = BLE.hexToSignedInt(ayStr) / 32768 * 16;
  1912. let az = BLE.hexToSignedInt(azStr) / 32768 * 16;
  1913. let gxStr = resValue.substr(20, 4);
  1914. let gyStr = resValue.substr(24, 4);
  1915. let gzStr = resValue.substr(28, 4);
  1916. //角速度(AD值/32768 * 2000) 角速度单位是 °/s 范围是 正负2000
  1917. let gx = BLE.hexToSignedInt(gxStr) / 32768 * 2000;
  1918. let gy = BLE.hexToSignedInt(gyStr) / 32768 * 2000;
  1919. let gz = BLE.hexToSignedInt(gzStr) / 32768 * 2000;
  1920. //毫秒
  1921. let ms = BLE.hex2int(resValue.substr(2, 4));
  1922. //分
  1923. let min = BLE.hex2int(resValue.substr(32, 2));
  1924. //秒
  1925. let s = BLE.hex2int(resValue.substr(34, 2));
  1926. box["handle"] = BLE.hexToString(handle);
  1927. box["acc"] = {
  1928. ax,
  1929. ay,
  1930. az
  1931. };
  1932. box["gyro"] = {
  1933. gx,
  1934. gy,
  1935. gz
  1936. };
  1937. box["min"] = min;
  1938. box["s"] = s;
  1939. box["ms"] = ms;
  1940. //更新数据给webview,在game-play-web||game-play-sub绑定
  1941. //后面更新数据都用此接口
  1942. uni.$emit('updateBLEDeviceData', box);
  1943. }
  1944. });
  1945. },
  1946. //向低功耗蓝牙设备特征值中写入二进制数据。注意:必须设备的特征值支持 write 才可以成功调用。
  1947. B_WriteBLECharacteristicValue(state, context) {
  1948. let {
  1949. value,
  1950. retryCount,
  1951. success,
  1952. getFail
  1953. } = context;
  1954. if (!value && value === '') {
  1955. uni.showToast({
  1956. title: "指令为空"
  1957. })
  1958. return;
  1959. }
  1960. //记录一下指令
  1961. state.currentInstruction = value;
  1962. //V 获取版本,M 获取mac 地址
  1963. if (value == "V")
  1964. state.showToast = true;
  1965. if (value == "M") {
  1966. state.showToast = true;
  1967. state.bListenerMac = true;
  1968. }
  1969. if (value == "4") {
  1970. state.bListenerUpdate = false;
  1971. }
  1972. if (value == "3") {
  1973. if (state.bListenerUpdate) {
  1974. uni.showToast({
  1975. title: "原始数据已开启"
  1976. })
  1977. return;
  1978. }
  1979. state.bListenerUpdate = true;
  1980. }
  1981. if (value == "6") {
  1982. state.bListenerJson = false;
  1983. }
  1984. if (value == "5") {
  1985. if (state.bListenerJson) {
  1986. uni.showToast({
  1987. title: "步数数据已开启"
  1988. })
  1989. return;
  1990. }
  1991. state.bListenerJson = true;
  1992. }
  1993. console.log("currentInstruction:", state.currentInstruction, value, state.bListenerUpdate, state.bListenerMac);
  1994. console.log("state.deviceId:", state.deviceId, state.serviceId, state.writeCharacteristicId);
  1995. uni.writeBLECharacteristicValue({
  1996. deviceId: state.deviceId,
  1997. serviceId: state.serviceId,
  1998. // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
  1999. characteristicId: state.writeCharacteristicId,
  2000. // 这里的value是ArrayBuffer类型
  2001. value: BLE.str2ab(value),
  2002. success: (res) => {
  2003. console.log('writeBLECharacteristicValue success', res.errMsg, value, retryCount);
  2004. if (success) {
  2005. success(res);
  2006. }
  2007. },
  2008. fail: (fail) => {
  2009. console.log(fail)
  2010. //重新写入
  2011. if (retryCount > 0) {
  2012. console.log("writeBLECharacteristicValue Rewrite ===================>" + value + " == " + retryCount);
  2013. retryCount--;
  2014. setTimeout(() => {
  2015. this.commit("B_WriteBLECharacteristicValue", {
  2016. value,
  2017. retryCount,
  2018. success,
  2019. getFail
  2020. });
  2021. }, 300);
  2022. }
  2023. if (getFail) {
  2024. getFail(fail);
  2025. }
  2026. }
  2027. })
  2028. },
  2029. /**
  2030. * 断开蓝牙连接
  2031. */
  2032. B_CloseBLEConnection(state, context) {
  2033. let {
  2034. deviceId,
  2035. success = null
  2036. } = context;
  2037. uni.closeBLEConnection({
  2038. deviceId,
  2039. success: res => {
  2040. if (success)
  2041. success();
  2042. },
  2043. fail: (fail) => {
  2044. console.log("关闭蓝牙失败", fail);
  2045. }
  2046. });
  2047. },
  2048. //获取手机中蓝牙已匹配的设备
  2049. B_GetBondedDevices(state, context) {
  2050. // console.log("getBondedDevices ====>");
  2051. // uni.getBluetoothDevices({
  2052. // success(res) {
  2053. // console.log("getBluetoothDevices:", res)
  2054. // }
  2055. // })
  2056. // uni.getConnectedBluetoothDevices({
  2057. // success(res) {
  2058. // console.log("getConnectedBluetoothDevices:", res)
  2059. // }
  2060. // })
  2061. let {
  2062. success = null
  2063. } = context;
  2064. //Android
  2065. function android_bluetooth_list(deviceName) {
  2066. var main = plus.android.runtimeMainActivity();
  2067. var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
  2068. var BAdapter = BluetoothAdapter.getDefaultAdapter();
  2069. var Context = plus.android.importClass("android.content.Context");
  2070. var lists = BAdapter.getBondedDevices();
  2071. plus.android.importClass(lists);
  2072. var len = lists.size();
  2073. // console.log("getBondedDevices.len=" + len);
  2074. if (len == 0) {
  2075. //如果没有配对的设备
  2076. return null;
  2077. } else {
  2078. var iterator = lists.iterator();
  2079. plus.android.importClass(iterator);
  2080. while (iterator.hasNext()) {
  2081. var d = iterator.next();
  2082. plus.android.importClass(d);
  2083. let temp = null;
  2084. //
  2085. if (d.getName().indexOf(deviceName) > -1) {
  2086. // console.log(d.getName());
  2087. // console.log(d.getAddress());
  2088. // Classic 1
  2089. // Dual 3
  2090. // Le 2
  2091. // Unknown 0
  2092. // console.log(d.getType());
  2093. // Bonded 12
  2094. // Bonding 11 Indicates bonding (pairing) is in progress with the remote device.
  2095. // None 10
  2096. // console.log(d.getBondState());
  2097. let typeEnum = {
  2098. 0: 'Unknown',
  2099. 1: 'Classic',
  2100. 2: 'Le',
  2101. 3: 'Dual'
  2102. };
  2103. let bondStateEnum = {
  2104. 10: 'None',
  2105. 11: 'Bonding',
  2106. 12: 'Bonded'
  2107. };
  2108. temp = {
  2109. name: d.getName(),
  2110. address: d.getAddress(),
  2111. type: {
  2112. 'value': d.getType(),
  2113. 'name': typeEnum[d.getType()]
  2114. },
  2115. bondState: {
  2116. 'value': d.getBondState(),
  2117. 'name': bondStateEnum[d.getBondState()]
  2118. }
  2119. }
  2120. }
  2121. return temp;
  2122. }
  2123. }
  2124. }
  2125. function searchIOS() {
  2126. var CBCentralManager = plus.ios.import("CBCentralManager");
  2127. var manager = new CBCentralManager();
  2128. var delegate = plus.ios.implements("CBCentralManagerDelegate", {
  2129. "centralManagerDidUpdateState:": centralManagerDidUpdateState,
  2130. "centralManager:didDiscoverPeripheral:advertisementData:RSSI:": didDiscoverPeripheral
  2131. });
  2132. if (plus.device.model == "iPad" || plus.device.model == "iPod") {
  2133. manager.initWithDelegatequeue(delegate, null);
  2134. } else {
  2135. manager.initWithDelegatequeue(delegate, null, null);
  2136. let arr = manager.retrieveConnectedPeripheralsWithServices();
  2137. console.error(arr.length);
  2138. }
  2139. }
  2140. function centralManagerDidUpdateState(central) {
  2141. console.log(central);
  2142. var state = central.plusGetAttribute('state');
  2143. console.log(state);
  2144. if (state == 4) {
  2145. writelog('请开启蓝牙');
  2146. }
  2147. if (state == 5) {
  2148. console.log("中央外设管理器状态 state= " + state);
  2149. central.scanForPeripheralsWithServicesoptions(null, null);
  2150. }
  2151. //writelog("中央外设管理器状态 state= " + state);
  2152. }
  2153. function didDiscoverPeripheral(central, peripheral, advertisementData, RSSI) {
  2154. var name = peripheral.plusGetAttribute("name");
  2155. var uuid = peripheral.plusGetAttribute("identifier").plusGetAttribute("UUIDString");
  2156. var rssi = RSSI.plusGetAttribute("intValue");
  2157. var dist = calcDistByRSSI(rssi, 74, 2);
  2158. writelog("蓝牙设备:" + name + " " + uuid + " " + rssi + " " + dist + "米");
  2159. }
  2160. function writelog(msg) {
  2161. console.log(msg);
  2162. }
  2163. function calcDistByRSSI(rssi, a, n) {
  2164. var rs = Math.abs(rssi);
  2165. var power = (rs - a) / (10 * n);
  2166. return Math.pow(10, parseFloat(power)).toFixed(2);
  2167. }
  2168. function ios_bluetooth_list(deviceName) {
  2169. // let CBCentralManager= plus.ios.importClass("CBCentralManager");
  2170. // let _centralManager = new CBCentralManager();
  2171. // _centralManager.initWithDelegatequeue(plus.ios.currentWebview(),null);
  2172. // let arr = _centralManager.retrieveConnectedPeripheralsWithServices();
  2173. // console.error(arr.length);
  2174. // searchIOS();
  2175. return null;
  2176. }
  2177. let device = null;
  2178. switch (plus.os.name) {
  2179. case "Android":
  2180. // Android平台: plus.android.*
  2181. device = android_bluetooth_list("BGBox");
  2182. console.log("android getBondedDevices 匹配的对象======>", device)
  2183. if (device != null) {
  2184. state.bPhoneMatched = true;
  2185. } else {
  2186. state.bPhoneMatched = false;
  2187. }
  2188. break;
  2189. case "iOS":
  2190. // iOS平台: plus.ios.*
  2191. device = ios_bluetooth_list("BGBox");
  2192. console.log("ios getBondedDevices 匹配的对象======>", device)
  2193. if (device != null) {
  2194. state.bPhoneMatched = true;
  2195. } else {
  2196. state.bPhoneMatched = false;
  2197. }
  2198. break;
  2199. default:
  2200. // 其它平台
  2201. break;
  2202. }
  2203. if (success) {
  2204. success(device);
  2205. }
  2206. },
  2207. B_OpenBLESetting() {
  2208. function android_bluetooth_setting() {
  2209. var main = plus.android.runtimeMainActivity(); //获取activity
  2210. var Intent = plus.android.importClass('android.content.Intent');
  2211. var Settings = plus.android.importClass('android.provider.Settings');
  2212. var intent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS); //可设置表中所有Action字段
  2213. main.startActivity(intent);
  2214. }
  2215. function ios_bluetooth_setting() {
  2216. // var UIApplication = plus.ios.import("UIApplication");
  2217. // var application2 = UIApplication.sharedApplication();
  2218. // var NSURL2 = plus.ios.import("NSURL");
  2219. // var setting2 = NSURL2.URLWithString("app-settings:");
  2220. // application2.openURL(setting2);
  2221. // plus.ios.deleteObject(setting2);
  2222. // plus.ios.deleteObject(NSURL2);
  2223. // plus.ios.deleteObject(application2);
  2224. // plus.runtime.openURL({
  2225. // action: 'App-Prefs:root=Bluetooth'
  2226. // }, function(e) {
  2227. // console.log(JSON.stringify(e));
  2228. // });
  2229. plus.runtime.launchApplication({action:'App-Prefs:root=Bluetooth'}, function(e){
  2230. console.log(JSON.stringify(e));
  2231. });
  2232. }
  2233. let device = null;
  2234. switch (plus.os.name) {
  2235. case "Android":
  2236. // Android平台: plus.android.*
  2237. android_bluetooth_setting();
  2238. break;
  2239. case "iOS":
  2240. // iOS平台: plus.ios.*
  2241. ios_bluetooth_setting();
  2242. break;
  2243. default:
  2244. // 其它平台
  2245. break;
  2246. }
  2247. }
  2248. }
  2249. })
  2250. export default store