store.js 67 KB

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