store.js 61 KB

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