store.js 85 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462
  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 o0ProjectRelease from "@/util/util-js/o0ProjectRelease0.1.js"
  12. import deviceData from "@/util/util-js/devices.js"
  13. Vue.use(Vuex)
  14. const store = new Vuex.Store({
  15. state: {
  16. //引导层
  17. bGuidePages: false,
  18. //是否显示Canvas
  19. bCanvasShow: true,
  20. /**
  21. * 是否需要强制登录
  22. */
  23. forcedLogin: false,
  24. /**
  25. * 蓝牙实时发送数据的页面的名称
  26. */
  27. currentPageName: '',
  28. hasLogin: false,
  29. userInfo: null,
  30. userName: "匿名",
  31. days: 0,
  32. remainingDays: 0,
  33. signature: '',
  34. avatarUrl: "/static/defaultAvatar.png",
  35. // 是否是新用户,
  36. //TODO:登录接口返回的数据来判断
  37. bNewUser: false,
  38. //是否是第一次走新手
  39. bNewGuide: false,
  40. token: '',
  41. gender: 0,
  42. //省市区数据
  43. city: {
  44. label: '北京市-北京市-东城区',
  45. cityCode: "110101",
  46. //picker 选择器的index数组
  47. value: [0, 0, 0]
  48. },
  49. birthday: date.formatTime(new Date()),
  50. //默认值
  51. height: 0,
  52. weight: 0,
  53. //最近在玩的列表
  54. playGames: [],
  55. //最近在玩的排行游戏列表
  56. playRankingGames: [],
  57. //全部的游戏列表
  58. allGames: [],
  59. //关注的游戏列表
  60. favoriteGames: [],
  61. // 排行榜里面显示的游戏
  62. rankSelectedGame: null,
  63. rankInfo: null,
  64. cityName: "某市",
  65. /**
  66. * 默认的运动数据
  67. * date.addDaysFromNewDate(new Date(),1)
  68. */
  69. defaultPlanData: {
  70. startTime: date.formatDate(new Date()),
  71. endTime: date.addDaysFromNewDate(new Date(), 6),
  72. targetWeight: 0, //目标公斤
  73. calorie: 360, //运动消耗的卡路里,默认300 大卡
  74. cumulativeCalorie: 0, //累计增重
  75. sportTime: 40, //运动时间
  76. /**
  77. * 本地记录的消耗卡路里数量
  78. */
  79. localCalorie: 0,
  80. /**
  81. * 显示卡路里,过了12点清空
  82. */
  83. showCalorie: 0,
  84. /**
  85. * 总和
  86. */
  87. allCalorie: 0
  88. },
  89. /**
  90. * 计划的运动数据
  91. */
  92. planData: {
  93. startTime: date.formatDate(new Date()),
  94. endTime: date.formatDate(new Date()), //date.addDaysFromNewDate(new Date(),1),
  95. targetWeight: 0, //目标公斤
  96. cumulativeCalorie: 0, //累计增重
  97. calorie: 300, //运动消耗的卡路里
  98. sportTime: 40, //运动时间
  99. /**
  100. * 本地记录的消耗卡路里数量
  101. */
  102. localCalorie: 0,
  103. /**
  104. * 显示卡路里,过了12点清空
  105. */
  106. showCalorie: 0,
  107. /**
  108. * 总和
  109. */
  110. allCalorie: 0
  111. },
  112. //记录表盘计划刷新的卡路里
  113. oldArcbarProCalorie: 0,
  114. //记录表盘当前的总卡路里
  115. oldArcbarAllCalorie: 0,
  116. //当前运动的世时间
  117. localSportTime: 0,
  118. //当前运动时间,运动时候记录的时间
  119. runingTime: 0,
  120. //蓝牙设备信息列表
  121. //id 不可变,用于保存到本地区分
  122. BLEInfoList: deviceData.getDeviceList(),
  123. //记录的蓝牙设备,保存id, 和对应的蓝牙连接数据
  124. BLEDeviceList: [],
  125. //显示的蓝牙设备,取本地数据时候更新
  126. BLEDeviceShowList: [],
  127. //选择连接的蓝牙设备
  128. BLEConnectDevice: null,
  129. //获取到的服务
  130. BLEGetServices: null,
  131. //当前发送给蓝牙的指令,目前是只有蓝牙手柄
  132. currentInstruction: '',
  133. instructionState: {
  134. // bAcc: false, //是否开启加速计状态
  135. // bGyroscope: false, //是否开启陀螺仪状态
  136. bOpen: false, //是否开启指令
  137. bSteps: false, //是否开启步数
  138. },
  139. //绑定的设备
  140. DeviceBindingList: [{
  141. id: 0,
  142. cname: "开启手机数据",
  143. ename: "bindMobilePhoneBandage",
  144. icon: "/static/devicesIcon/bandage.png",
  145. mIcon: "/static/devicesIcon/bandage.png",
  146. bRatio: false,
  147. usageMode: 'bindPhone',
  148. describe: '手机情景下使用',
  149. limitType: 'rebound', //限制回弹版本
  150. deviceType: 'mySelf', //指的是使用手机本身加速计计算
  151. deviceName: 'PHONE', //连接硬件名称
  152. }],
  153. ConnectBindingDevice: null,
  154. cIndex: -1,
  155. //当前是否连接
  156. bConnection: false,
  157. /**
  158. * 通过验证的连接,比如通过mac验证,或者说是首页直连,都设置这个参数,确保已经连上
  159. */
  160. bVerifiedConnection: false,
  161. /**
  162. * Android 出现不匹配的情况下,判断
  163. * ios 暂时没有此类问题
  164. */
  165. bPhoneMatched: false,
  166. //最近连接过的设备
  167. finallyUseDevice: null,
  168. /**
  169. * 用户选择好友的信息
  170. */
  171. finallySelectFriendInfo: null,
  172. //phoneNumber
  173. phoneNumber: '',
  174. openid: '',
  175. appleid: '',
  176. //获取验证码
  177. bCodeDisabled: false,
  178. count: 59,
  179. interval: null,
  180. //conversion列表
  181. oldSwiperList: [],
  182. // 计划任务过期
  183. bPlanExpired: false,
  184. // 制定玩计划任务后
  185. bPlanFinish: false,
  186. //标准体重,男女根据当前年龄计算
  187. standardWeight: 0,
  188. //是否安装了微信
  189. bInstallWechat: false,
  190. bHideWeixin: false,
  191. //导航栏高度。这里统一参数,单位px
  192. navHeight: 46,
  193. tabbarHeight: 65,
  194. systemInfo: null, //系统全部信息
  195. clientName: '', //但是客户端名字
  196. system: '', // 系统版本
  197. platform: '', // 平台
  198. appName: '',
  199. version: '1.6.3', //软件版本
  200. versionCode: '21030101',
  201. showEndTime: config.endTime, //游戏显示时间字段,后台返回对应此时间之前的数据
  202. //现在游戏显示在对应的平台
  203. gamePlatform: {
  204. 0: 'android',
  205. 1: 'ios',
  206. 2: 'all'
  207. },
  208. globalAcc: null,
  209. globalOri: null,
  210. globalAccData: {
  211. ax: 0,
  212. ay: 0,
  213. az: 0
  214. },
  215. globalGyroData: {
  216. gx: 0,
  217. gy: 0,
  218. gz: 0
  219. },
  220. globalLastGyroData: {
  221. gx: 0,
  222. gy: 0,
  223. gz: 0
  224. },
  225. globalMyAttitude: null,
  226. /**
  227. * 当前显示的模式下标,区分总体的显示模块
  228. * 比如拳击模块体验下,设置 0
  229. * 跳绳为主的模式体验下,设置 1
  230. */
  231. currentModeIndex: 1,
  232. //蓝牙变量操作
  233. /**
  234. * 操作蓝牙设备
  235. */
  236. bOpenBluetooth: false,
  237. /**
  238. * 是否初始化蓝牙适配器
  239. */
  240. bOpenSuccess: false,
  241. /**
  242. * 是否监听蓝牙状态变化
  243. */
  244. bListenAdapterStateChange: false,
  245. /**
  246. * 是否监听寻找新设备事件
  247. */
  248. bListenDeviceFound: false,
  249. // 设备Id
  250. BLEDeviceId: "",
  251. // 服务Id
  252. BLEServiceId: "",
  253. // 特征值id
  254. BLENotifyCharacteristicId: "",
  255. //监听rssi对象
  256. BLERSSIInterval: null,
  257. //蓝牙服务timeout
  258. getBLEDeviceServicesTimeout: null,
  259. //本地游戏地址
  260. // http://192.168.0.112:7456/build/index.html
  261. // http://127.0.0.1:7456/build/index.html
  262. LocationGameUrl: "http://110.43.54.43/t8/",
  263. //快速打击对象
  264. filter: null,
  265. deviceMs: 1,
  266. //改进版的沙袋打击对象
  267. sandbagAlgorithm: null,
  268. sandbagAlgorithmLastTime: new Date().getTime(),
  269. /**
  270. * 蓝牙参数对象
  271. */
  272. // 设备Id
  273. deviceId: "",
  274. // 服务Id
  275. serviceId: "",
  276. notifyCharacteristicId: "",
  277. writeCharacteristicId: "",
  278. showToast: false,
  279. bListenerUpdate: false,
  280. bListenerJson: false,
  281. bListenerMac: false,
  282. bListenerAccArray: false,
  283. /**
  284. * 发送16进制时候,返回的刷新数据
  285. */
  286. bListenerHexUpdate: false,
  287. BluetoothAdapter: null,
  288. //版本状态,用于区分部分特定的环境
  289. versionCodeState: null,
  290. //显示蓝牙是否断开连接Modal
  291. bShowBLEConnectModal: false,
  292. bGamePlaying: false,
  293. //跳绳条件下计数
  294. bRopeKeyOne: 0,
  295. bRopeKeyTwo: 0,
  296. //钻石,金币
  297. cDiamond: 0,
  298. cGold: 0,
  299. /**
  300. * 任务相关
  301. */
  302. currentJumpTask: null,
  303. multiPersonList: [],
  304. singlePersonList: [],
  305. /**
  306. * 校准识别部分
  307. */
  308. convertAcc: [{
  309. type: 'x',
  310. match: 'ax', //默认匹配一一对应
  311. direction: 1,
  312. }, {
  313. type: 'y',
  314. match: 'ay',
  315. direction: 1,
  316. }, {
  317. type: 'z',
  318. match: 'az',
  319. direction: 1,
  320. }],
  321. convertGyro: [{
  322. type: 'x',
  323. match: 'gx', //默认匹配一一对应
  324. direction: 1,
  325. }, {
  326. type: 'y',
  327. match: 'gy',
  328. direction: 1,
  329. }, {
  330. type: 'z',
  331. match: 'gz',
  332. direction: 1,
  333. }],
  334. /**
  335. * 签到列表
  336. */
  337. signInList: [],
  338. isSignIn:false,
  339. },
  340. mutations: {
  341. /**
  342. * 蓝牙解析后的数据,转化成对应的坐标系方向
  343. * @param {Object} context
  344. */
  345. onConvertDeviceData(state, context) {
  346. let {
  347. data,
  348. callback = null
  349. } = context;
  350. let {
  351. acc,
  352. gyro,
  353. } = data;
  354. //根据已校准的数据转化对应的轴
  355. let outAcc = {
  356. ax: acc[state.convertAcc[0].match] * state.convertAcc[0].direction,
  357. ay: acc[state.convertAcc[1].match] * state.convertAcc[1].direction,
  358. az: acc[state.convertAcc[2].match] * state.convertAcc[2].direction
  359. };
  360. let outGyro = {
  361. gx: gyro[state.convertGyro[0].match] * state.convertGyro[0].direction,
  362. gy: gyro[state.convertGyro[1].match] * state.convertGyro[1].direction,
  363. gz: gyro[state.convertGyro[2].match] * state.convertGyro[2].direction
  364. }
  365. if (callback)
  366. callback({
  367. convertAcc: outAcc,
  368. convertGyro: outGyro
  369. });
  370. },
  371. onAccAndGyroConvertDataGet(state) {
  372. const convertAcc = uni.getStorageSync('convertAcc');
  373. if (convertAcc) {
  374. state.convertAcc = convertAcc;
  375. }
  376. const convertGyro = uni.getStorageSync('convertGyro');
  377. if (convertGyro) {
  378. state.convertGyro = convertGyro;
  379. }
  380. },
  381. onAccAndGyroConvertDataSave(state) {
  382. uni.setStorageSync('convertAcc', state.convertAcc);
  383. uni.setStorageSync('convertGyro', state.convertGyro);
  384. },
  385. onAccAndGyroConvertDataReset(state) {
  386. state.convertAcc = [{
  387. type: 'x',
  388. match: 'ax', //默认匹配一一对应
  389. direction: 1,
  390. }, {
  391. type: 'y',
  392. match: 'ay',
  393. direction: 1,
  394. }, {
  395. type: 'z',
  396. match: 'az',
  397. direction: 1,
  398. }];
  399. state.convertGyro = [{
  400. type: 'x',
  401. match: 'gx', //默认匹配一一对应
  402. direction: 1,
  403. }, {
  404. type: 'y',
  405. match: 'gy',
  406. direction: 1,
  407. }, {
  408. type: 'z',
  409. match: 'gz',
  410. direction: 1,
  411. }];
  412. //重置一下数据保存
  413. this.commit('onAccAndGyroConvertDataSave');
  414. },
  415. /**
  416. * 设置当前操作的任务记录到本地
  417. * @param {Object} state
  418. * @param {Object} _taskObj
  419. */
  420. setActionJumpTask(state, _taskObj) {
  421. uni.setStorageSync('currentJumpTask', _taskObj);
  422. state.currentJumpTask = _taskObj;
  423. },
  424. //获取本地任务对象
  425. getActionJumpTask(state) {
  426. //如果存在本地任务
  427. const value = uni.getStorageSync('currentJumpTask');
  428. if (value) {
  429. state.currentJumpTask = value;
  430. }
  431. },
  432. resetActionJumpTask(state) {
  433. state.currentJumpTask = null;
  434. uni.setStorageSync('currentJumpTask', state.currentJumpTask);
  435. },
  436. setFinallSelectFriendInfo(state, friendInfo) {
  437. state.finallySelectFriendInfo = friendInfo;
  438. console.log('finallySelectFriendInfo', JSON.stringify(friendInfo));
  439. },
  440. clearFinallFriendInfo(state) {
  441. state.finallySelectFriendInfo = null;
  442. },
  443. /**
  444. * 获取记录的最后一次连接设备
  445. * @param {Object} state
  446. */
  447. getFinalUseDevice(state) {
  448. // 获取本地存储的最后一次使用的设备
  449. //1.获取最近连接的蓝牙设备, 指蓝牙搜索到的obj
  450. const value = uni.getStorageSync('finallyUseDevice');
  451. if (value) {
  452. state.finallyUseDevice = value;
  453. }
  454. console.log('获取的finallyUseDevice', value);
  455. },
  456. /**
  457. * 存储最后一次使用的设备信息,后面登陆时候,如果存在设备最后一次使用信息,则自动连接
  458. * @param {Object} state
  459. * @param {Object} device
  460. */
  461. setFinallUseDevice(state, device) {
  462. uni.setStorageSync('finallyUseDevice', device);
  463. state.finallyUseDevice = device;
  464. console.log("保存finallyUseDevice:", state.finallyUseDevice);
  465. // uni.setStorage({
  466. // key: 'finallyUseDevice',
  467. // data: device,
  468. // success: (res) => {
  469. // state.finallyUseDevice = device;
  470. // console.log("保存finallyUseDevice:", res);
  471. // }
  472. // })
  473. },
  474. /**
  475. * 移除记录的use device
  476. */
  477. clearFinallUseDevice(state) {
  478. uni.removeStorage({
  479. key: 'finallyUseDevice',
  480. success: (res) => {
  481. state.finallyUseDevice = null;
  482. console.log("移除finallyUseDevice:", res);
  483. }
  484. })
  485. },
  486. /**
  487. * 设置运动时间
  488. * @param {Object} state
  489. * @param {Object} time
  490. */
  491. setLocalSportTime(state, time) {
  492. // let _sportTime = Number(time);
  493. state.localSportTime = Number(time);
  494. uni.setStorage({
  495. key: 'localSportTime',
  496. data: state.localSportTime,
  497. success: (res) => {
  498. // uni.showToast({
  499. // title: "保存成功"
  500. // })
  501. }
  502. })
  503. },
  504. /**
  505. * 设置卡路里
  506. * @param {Object} state
  507. * @param {Object} calorie
  508. */
  509. setLocalCalorie(state, calorie) {
  510. state.planData.localCalorie = Number(calorie);
  511. uni.setStorage({
  512. key: 'localCalorie',
  513. data: state.planData.localCalorie,
  514. success: (res) => {
  515. // uni.showToast({
  516. // title: "保存成功"
  517. // })
  518. }
  519. })
  520. },
  521. /**
  522. * 设置表盘显示的卡路里,
  523. * @param {Object} state
  524. * @param {Object} calorie
  525. */
  526. setShowCalorie(state, calorie) {
  527. state.planData.showCalorie = Number(calorie);
  528. uni.setStorage({
  529. key: 'showCalorie',
  530. data: state.planData.showCalorie,
  531. success: (res) => {
  532. // uni.showToast({
  533. // title: "保存成功"
  534. // })
  535. }
  536. })
  537. },
  538. /**
  539. * 增加卡路里
  540. * @param {Object} state
  541. * @param {Object} calorie
  542. */
  543. addlocalCalorie(state, calorie) {
  544. //卡路里不能为负数
  545. calorie = Math.abs(calorie);
  546. //当前需要添加的卡路里
  547. let temNum = Number(calorie);
  548. //本地的卡路里
  549. let temNum2 = Number(state.planData.localCalorie);
  550. // 本地加 + 传入的卡路里
  551. let _numberLocal = temNum.add(temNum2);
  552. //显示的卡路里
  553. let _showCalorie = Number(state.planData.showCalorie);
  554. //显示的卡路里加上 本地卡路里 和添加的卡路里之和要小于或等于 计划的卡路里
  555. let _allCalorie = _numberLocal.add(_showCalorie);
  556. // console.log("计算的最后卡路里_showCalorie:", _showCalorie,_allCalorie);
  557. //如果超过计划的,用计划的卡路里记录
  558. if (_allCalorie > state.planData.calorie) {
  559. let _calorie = Number(state.planData.calorie);
  560. //假如更新时候,localCalorie 值不为0,但是还未更新给服务器,此时,不能设置localCalorie 0
  561. //用传入的值,减去 allcalorie 总和和目标的差
  562. let _value = Number(_allCalorie).sub(_calorie);
  563. let _endValue = Number(_numberLocal).sub(_value);
  564. state.planData.localCalorie = Number(_endValue.toFixed(2));
  565. //如果大于或者等于的话,用计划 于 显示的卡路里 差值
  566. // state.planData.localCalorie = Number(_calorie.sub(_showCalorie).toFixed(2));
  567. // //显示最大值
  568. // state.planData.showCalorie = Number(_calorie.sub(state.planData.localCalorie).toFixed(2));
  569. } else {
  570. //
  571. state.planData.localCalorie = Number(_numberLocal.toFixed(2));
  572. // //输入的卡路里 + 自身显示的卡路里
  573. // state.planData.showCalorie = Number(temNum.add(_showCalorie).toFixed(2));
  574. }
  575. console.log("计算的最后卡路里:", state.planData);
  576. if (state.planData.localCalorie < 0) {
  577. //如果修改计划时候,本地数据计算的结果为负数,先取总和,localCalorie负再重置为0
  578. state.planData.showCalorie = _showCalorie.add(state.planData.localCalorie);
  579. state.planData.allCalorie = state.planData.showCalorie;
  580. state.planData.localCalorie = 0;
  581. } else {
  582. state.planData.allCalorie = _showCalorie.add(state.planData.localCalorie);
  583. }
  584. try {
  585. uni.setStorageSync('localCalorie', state.planData.localCalorie);
  586. } catch (e) {
  587. // error
  588. console.error(e);
  589. }
  590. try {
  591. uni.setStorageSync('showCalorie', state.planData.showCalorie);
  592. } catch (e) {
  593. // error
  594. console.error(e);
  595. }
  596. // uni.setStorage({
  597. // key: 'localCalorie',
  598. // data: state.planData.localCalorie,
  599. // success: (res) => {
  600. // // uni.showToast({
  601. // // title: "保存成功"
  602. // // })
  603. // }
  604. // })
  605. // uni.setStorage({
  606. // key: 'showCalorie',
  607. // data: state.planData.showCalorie,
  608. // success: (res) => {
  609. // // uni.showToast({
  610. // // title: "保存成功"
  611. // // })
  612. // }
  613. // })
  614. },
  615. /**
  616. * 每次登陆同步本地数据到服务器
  617. * 当天的数据更新,只更新一次
  618. * @param {Object} state
  619. */
  620. syncLocalDataToServer(state, callback) {
  621. let self = this;
  622. uni.getStorage({
  623. key: 'syncDate',
  624. success: function(res) {
  625. // console.log(res.data);
  626. let oldTime = res.data;
  627. let nDate = new Date();
  628. let newTime = date.formatDate(nDate);
  629. let days = date.datedifference(newTime, oldTime);
  630. // console.log(days);
  631. // 如果相差大于1天,
  632. if (days != 0) {
  633. // 更新存储日期
  634. uni.setStorageSync("syncDate", newTime);
  635. // 执行更新函数
  636. self.commit("syncRequestEvent", {
  637. success: () => {
  638. //清空显示的本地数据
  639. self.commit("setShowCalorie", 0);
  640. state.planData.allCalorie = state.planData.showCalorie.
  641. add(state.planData.localCalorie);
  642. if (callback)
  643. callback({
  644. newDate: nDate
  645. });
  646. }
  647. });
  648. //清空记录的本地运动时间
  649. // console.log('情况运动时间');
  650. self.commit("setLocalSportTime", 0);
  651. //设置本地数据是0
  652. state.localSportTime = 0;
  653. } else {
  654. if (callback)
  655. callback({
  656. newDate: nDate
  657. });
  658. }
  659. // date.getDays.
  660. },
  661. fail: function(res) {
  662. // console.error(res);
  663. // 如果没有日期,则存储一个新的
  664. let nDate = new Date();
  665. let tempTime = date.formatDate(nDate);
  666. uni.setStorageSync("syncDate", tempTime);
  667. if (callback)
  668. callback({
  669. newDate: nDate
  670. });
  671. }
  672. });
  673. },
  674. // 同步数据的请求
  675. syncRequestEvent(state, data) {
  676. let self = this;
  677. let {
  678. success,
  679. fail
  680. } = data;
  681. //需要卡路里取整存服务器,小数点后面,继续保留。以消除累计误差
  682. let oldLocalCalorie = state.planData.localCalorie;
  683. let _localCalorieInt = parseInt(state.planData.localCalorie);
  684. //小数点后面
  685. let _afterLocalCalorie = Number(oldLocalCalorie).sub(_localCalorieInt);
  686. console.log("*******===:", oldLocalCalorie, _localCalorieInt, _afterLocalCalorie);
  687. if (_localCalorieInt === 0) {
  688. // uni.showToast({
  689. // title: '',
  690. // icon: 'loading',
  691. // mask: true,
  692. // duration: 1000
  693. // })
  694. if (success)
  695. success();
  696. return;
  697. }
  698. uni.showToast({
  699. title: '',
  700. icon: 'loading',
  701. mask: false,
  702. duration: 10000
  703. })
  704. //把卡路里累计到cumulativeCalorie 变量,之后传服务器 += Math.round(state.planData.localCalorie)
  705. state.planData.cumulativeCalorie += _localCalorieInt;
  706. //添加到showCalorie 中
  707. state.planData.showCalorie = Number(state.planData.showCalorie).add(_localCalorieInt);
  708. state.planData.allCalorie = state.planData.showCalorie.add(_afterLocalCalorie);
  709. //不管是否同步成功,清空本地记录的卡路里,前一步已添加到cumulativeCalorie
  710. self.commit("setLocalCalorie", _afterLocalCalorie);
  711. self.commit("setShowCalorie", Number(state.planData.showCalorie));
  712. // 把卡路里记录到服务器
  713. reqUtil.requestData(config.URL.FITNESSPROGRAM, state.planData, 'POST').then(
  714. res => {
  715. // console.warn(res);
  716. if (res.code == 0) {
  717. uni.showToast({
  718. title: '同步成功',
  719. mask: true,
  720. duration: 1000
  721. });
  722. //同步一下服务器的返回值
  723. state.planData = Object.assign(state.planData, res.data);
  724. //暂时默认同步拳击1 的卡路里
  725. reqUtil.requestData(config.URL.UPLOADRANKING, {
  726. gameId: '1', //拳击模式 game id = 1;
  727. score: _localCalorieInt,
  728. cityCode: state.city.cityCode,
  729. }, "POST").then(res => {
  730. console.warn('****上传首页拳击卡路里,后面多个模式,可能需要多个不同的游戏id ***', res);
  731. },
  732. e => {
  733. console.log(e)
  734. });
  735. setTimeout(() => {
  736. uni.hideToast();
  737. }, 1000);
  738. if (success)
  739. success();
  740. } else {
  741. state.planData.cumulativeCalorie = Number(state.planData.cumulativeCalorie).sub(
  742. _localCalorieInt);
  743. state.planData.showCalorie = Number(state.planData.showCalorie).sub(
  744. _localCalorieInt);
  745. self.commit("setLocalCalorie", oldLocalCalorie);
  746. if (fail)
  747. fail();
  748. }
  749. console.log("减法 ==", Number(state.planData.cumulativeCalorie).sub(_localCalorieInt));
  750. },
  751. e => {
  752. console.log(e);
  753. state.planData.cumulativeCalorie = Number(state.planData.cumulativeCalorie).sub(
  754. _localCalorieInt);
  755. state.planData.showCalorie = Number(state.planData.showCalorie).sub(_localCalorieInt);
  756. self.commit("setLocalCalorie", oldLocalCalorie);
  757. uni.hideToast();
  758. if (fail)
  759. fail();
  760. }
  761. );
  762. },
  763. //登录成功后,重置一下状态
  764. resetCountDown(state) {
  765. if (state.interval) {
  766. clearInterval(state.interval);
  767. state.interval = null;
  768. state.count = 59;
  769. state.bCodeDisabled = false;
  770. }
  771. },
  772. //验证码操作
  773. countDown(state, phoneNumber) {
  774. //限制验证码操作
  775. state.bCodeDisabled = true;
  776. state.interval = setInterval(() => {
  777. --state.count;
  778. if (state.count <= 0) {
  779. clearInterval(state.interval);
  780. state.interval = null;
  781. state.count = 59;
  782. state.bCodeDisabled = false;
  783. }
  784. }, 1000);
  785. setTimeout(() => {
  786. clearInterval(state.interval)
  787. state.count = 59;
  788. state.bCodeDisabled = false;
  789. }, 60000);
  790. reqUtil.requestData(config.URL.GETCODE, {
  791. "phoneNumber": phoneNumber
  792. }).then(res => {
  793. console.log('requestData GETCODE =====', res);
  794. uni.showToast({
  795. title: "发送成功",
  796. mask: true,
  797. duration: 1000
  798. })
  799. },
  800. e => {
  801. console.log(e)
  802. });
  803. },
  804. //获取记录的蓝牙列表数据
  805. getBLEDeviceList(state) {
  806. // console.log("getBLEDeviceList=");
  807. uni.getStorage({
  808. key: 'BLEDeviceList',
  809. success: (res) => {
  810. console.log("*****getBLEDeviceList=", res);
  811. let _list = res.data;
  812. state.BLEDeviceList = res.data;
  813. //更新BLEDeviceShowList 数组
  814. state.BLEDeviceShowList = [];
  815. _list.forEach(item => {
  816. //如果记录到本地的id,和信息列表中的id一致,则结合
  817. for (let i = 0; i < state.BLEInfoList.length; i++) {
  818. let eq = state.BLEInfoList[i];
  819. if (item.id == eq.id) {
  820. state.BLEDeviceShowList.push(Object.assign({}, item, eq));
  821. break;
  822. }
  823. }
  824. })
  825. }
  826. })
  827. },
  828. //添加蓝牙设备数据
  829. addBLEDevice(state, data) {
  830. let devicelist = [];
  831. if (state.BLEDeviceList && state.BLEDeviceList.length != 0) {
  832. devicelist = state.BLEDeviceList;
  833. }
  834. // console.log(data, devicelist)
  835. let bHas = false;
  836. devicelist.forEach((item, index, selfArr) => {
  837. if (item.id == data.id) {
  838. //如果存在,更新保存的数据,比如 mac或者uuid等
  839. selfArr[index] = item = Object.assign({}, item, data);
  840. bHas = true;
  841. }
  842. })
  843. //把当前添加的的蓝牙设信息备作为最后一次连接覆盖到本地
  844. this.commit('setFinallUseDevice', data);
  845. if (!bHas) {
  846. //如果不是更新数据,就添加但却数据到列表
  847. devicelist.push(data);
  848. }
  849. uni.setStorage({
  850. key: 'BLEDeviceList',
  851. data: devicelist,
  852. success: (res) => {
  853. // uni.showToast({
  854. // title: "保存成功"
  855. // })
  856. state.BLEDeviceList = devicelist;
  857. // console.log("devicelist:",devicelist);
  858. //更新BLEDeviceShowList 数组
  859. state.BLEDeviceShowList = [];
  860. devicelist.forEach(item => {
  861. //如果记录到本地的id,和信息列表中的id一致,则结合
  862. for (let i = 0; i < state.BLEInfoList.length; i++) {
  863. let eq = state.BLEInfoList[i];
  864. if (item.id == eq.id) {
  865. // console.log("存储的======================:", item, eq);
  866. state.BLEDeviceShowList.push(Object.assign({}, item, eq));
  867. break;
  868. }
  869. }
  870. })
  871. // console.log("state.BLEDeviceShowList:",state.BLEDeviceShowList);
  872. }
  873. })
  874. },
  875. //删除蓝牙设备数据
  876. deleteBLEDevice(state, index) {
  877. let devicelist = [];
  878. devicelist = state.BLEDeviceList;
  879. devicelist.splice(index, 1);
  880. uni.setStorage({
  881. key: 'BLEDeviceList',
  882. data: devicelist,
  883. success: (res) => {
  884. uni.showToast({
  885. title: "删除成功"
  886. })
  887. state.BLEDeviceList = devicelist;
  888. //更新BLEDeviceShowList 数组
  889. state.BLEDeviceShowList = [];
  890. devicelist.forEach(item => {
  891. //如果记录到本地的id,和信息列表中的id一致,则结合
  892. for (let i = 0; i < state.BLEInfoList.length; i++) {
  893. let eq = state.BLEInfoList[i];
  894. if (item.id == eq.id) {
  895. state.BLEDeviceShowList.push(Object.assign({}, item, eq));
  896. break;
  897. }
  898. }
  899. })
  900. }
  901. })
  902. },
  903. //获取计划表数据
  904. getPlanData(state, callback) {
  905. reqUtil.requestData(config.URL.FITNESSPROGRAMGET).then(res => {
  906. // console.log('获取计划表数据:getPlanData=====', res.data);
  907. if (res.code == 0) {
  908. state.planData = Object.assign(state.planData, res.data);
  909. // 处理本地数据
  910. let templocalCalorie = uni.getStorageSync("localCalorie");
  911. // console.log("templocalCalorie:", templocalCalorie, state.planData);
  912. if (templocalCalorie) {
  913. templocalCalorie = Number(templocalCalorie);
  914. if (templocalCalorie > state.planData.calorie) {
  915. state.planData.localCalorie = state.planData.calorie;
  916. uni.setStorage({
  917. key: "localCalorie",
  918. data: state.planData.localCalorie
  919. });
  920. } else {
  921. state.planData.localCalorie = templocalCalorie;
  922. }
  923. } else {
  924. state.planData.localCalorie = 0;
  925. }
  926. //处理本地的cumulativeCalorie
  927. let tempShowCalorie = uni.getStorageSync("showCalorie");
  928. // console.log("tempShowCalorie:", tempShowCalorie, state.planData);
  929. if (tempShowCalorie) {
  930. tempShowCalorie = Number(tempShowCalorie);
  931. if (tempShowCalorie > state.planData.calorie) {
  932. state.planData.showCalorie = state.planData.calorie;
  933. uni.setStorage({
  934. key: "showCalorie",
  935. data: state.planData.showCalorie
  936. });
  937. } else {
  938. state.planData.showCalorie = tempShowCalorie;
  939. }
  940. } else {
  941. state.planData.showCalorie = 0;
  942. }
  943. state.planData.allCalorie = state.planData.showCalorie.add(state.planData
  944. .localCalorie);
  945. // console.log("======",state.planData )
  946. state.days = date.datedifference(res.data.startTime, res.data.endTime) + 1;
  947. let nDate = new Date();
  948. let tempTime = date.formatDate(nDate);
  949. state.remainingDays = date.datedifference(tempTime, res.data.endTime) + 1;
  950. console.log("state.remainingDays======", tempTime, res.data.endTime, state
  951. .remainingDays);
  952. }
  953. // showArcbar
  954. if (callback) {
  955. callback();
  956. }
  957. },
  958. e => {
  959. console.log(e)
  960. });
  961. },
  962. /**
  963. * 获取全部游戏
  964. * @param {Object} state
  965. */
  966. getAllGame(state, callback) {
  967. //获得全部游戏列表
  968. if (state.allGames.length != 0) {
  969. if (callback)
  970. callback();
  971. return;
  972. }
  973. reqUtil.requestData(
  974. config.URL.GAMELIST_BY_RANKING_SHOW_AND_PLATFORM, {
  975. rankingShow: 1,
  976. page: 1,
  977. size: 100
  978. }
  979. ).then(res => {
  980. // console.log('获取默认的全部游戏 =====', res);
  981. if (res.code == 0) {
  982. state.allGames = [];
  983. state.allGames = state.allGames.concat(res.data);
  984. }
  985. if (callback)
  986. callback();
  987. },
  988. e => {
  989. console.log(e);
  990. if (callback)
  991. callback();
  992. }
  993. );
  994. },
  995. getRankGame(state, data) {
  996. let {
  997. param,
  998. callback
  999. } = data;
  1000. reqUtil.requestData(config.URL.GETRANKRANGR, param).then(res => {
  1001. console.log('获取默认的游戏数据:GETRANKRANGR=====', res);
  1002. if (res.data != null) {
  1003. state.rankSelectedGame = res.data.gameInfo;
  1004. state.rankInfo = res.data.rankInfo;
  1005. //然后获取排名
  1006. }
  1007. if (callback)
  1008. callback(res);
  1009. },
  1010. e => {
  1011. console.log(e)
  1012. });
  1013. },
  1014. /**
  1015. * 苹果端登陆
  1016. * @param {Object} state
  1017. * @param {Object} data
  1018. */
  1019. appleUserInfoLogin(state, data) {
  1020. let self = this;
  1021. let {
  1022. params,
  1023. callback
  1024. } = data;
  1025. console.log('获取用户数据:USERINFOAPPLEADD params=====', params);
  1026. reqUtil.requestData(config.URL.USERINFOAPPLEADD, params, 'POST').then(res => {
  1027. console.log('获取用户数据:USERINFOAPPLEADD =====', res);
  1028. if (res.code == 0) {
  1029. let userInfo = res.data;
  1030. self.commit('login', userInfo);
  1031. console.log("11~~");
  1032. } else if (res.code = 201) {
  1033. state.hasLogin = true;
  1034. }
  1035. console.log("apple callback!!!");
  1036. callback();
  1037. },
  1038. e => {
  1039. console.log(e)
  1040. });
  1041. },
  1042. //添加用户信息和登录
  1043. addUserAvatarAndLogin(state, data) {
  1044. let self = this;
  1045. let {
  1046. params,
  1047. filePath,
  1048. callback
  1049. } = data;
  1050. console.log("addUserAvatarAndLogin 初始化对应数据");
  1051. reqUtil.reqUpload(config.URL.USERINFOADDAVATARINFO, params, filePath).then(res => {
  1052. console.log('获取用户数据:USERINFOADDAVATARINFO =====', res);
  1053. if (res.code == 0) {
  1054. let userInfo = res.data;
  1055. self.commit('login', userInfo);
  1056. } else if (res.code = 201) {
  1057. state.hasLogin = true;
  1058. }
  1059. if (callback) {
  1060. callback();
  1061. }
  1062. },
  1063. e => {
  1064. console.log(e)
  1065. });
  1066. },
  1067. //app登录或h5
  1068. accountLogin(state, callback) {
  1069. let self = this;
  1070. // console.log("app登录或h5 初始化对应数据")
  1071. reqUtil.requestData(config.URL.USERINFOURL).then(res => {
  1072. console.log('获取用户数据:USERINFOURL =====', res);
  1073. if (res.code == 0) {
  1074. let userInfo = res.data.userInfo;
  1075. state.phoneNumber = res.data.phoneNumber || '';
  1076. state.openid = res.data.openid || '';
  1077. self.commit('login', userInfo);
  1078. } else if (res.code = 201) {
  1079. state.hasLogin = true;
  1080. }
  1081. if (callback) {
  1082. callback();
  1083. }
  1084. },
  1085. e => {
  1086. console.log(e)
  1087. });
  1088. },
  1089. //小程序页面登录
  1090. login(state, userInfo) {
  1091. console.log("登陆的信息==", userInfo);
  1092. if (userInfo.cityCode == "" || userInfo.cityCode == null) {
  1093. //不存在就设置默认值
  1094. userInfo.cityCode = state.city.cityCode;
  1095. }
  1096. let cityCode = userInfo.cityCode;
  1097. // console.log("cicicicitycode:", cityCode);
  1098. let provinceData = require('@/components/slambb-picker/city-data/province.js').default;
  1099. let cityData = require('@/components/slambb-picker/city-data/city.js').default;
  1100. let areaData = require('@/components/slambb-picker/city-data/area.js').default;
  1101. // 解析citycode
  1102. for (let i = 0; i < provinceData.length; i++) {
  1103. if (provinceData[i].value == cityCode.substr(0, 2)) {
  1104. let currentCityData = cityData[i];
  1105. for (let j = 0; j < currentCityData.length; j++) {
  1106. if (currentCityData[j].value == cityCode.substr(0, 4)) {
  1107. let areaDataTemp = areaData[i][j];
  1108. for (let k = 0; k < areaDataTemp.length; k++) {
  1109. if (areaDataTemp[k].value == cityCode) {
  1110. state.city.value = [i, j, k];
  1111. state.city.label = provinceData[i].label +
  1112. '-' +
  1113. currentCityData[j].label +
  1114. '-' +
  1115. areaDataTemp[k].label;
  1116. state.cityName = currentCityData[j].label;
  1117. break;
  1118. }
  1119. }
  1120. break;
  1121. }
  1122. }
  1123. break;
  1124. }
  1125. }
  1126. state.userInfo = userInfo;
  1127. state.userName = userInfo.username || '新用户';
  1128. state.avatarUrl = userInfo.avatarUrl || '/static/defaultAvatar.png';
  1129. state.gender = userInfo.gender;
  1130. state.signature = userInfo.signature || '';
  1131. state.birthday = userInfo.birthday;
  1132. state.city.cityCode = cityCode.toString();
  1133. state.weight = userInfo.weight || state.weight;
  1134. state.height = userInfo.height || state.height;
  1135. state.hasLogin = true;
  1136. //登录时候 获取一下排行榜里面的游戏
  1137. // this.commit('getRankGame', {
  1138. // param: {
  1139. // type: "china",
  1140. // cityCode: 12345
  1141. // }
  1142. // });
  1143. //进入此页面先设置平台参数
  1144. if (state.platform == "ios") {
  1145. uni.setStorageSync("platform", 1);
  1146. } else if (state.platform == "android") {
  1147. uni.setStorageSync("platform", 0);
  1148. }
  1149. //获取版本信息
  1150. this.commit('getVersionCode');
  1151. },
  1152. // 退出登录
  1153. // 删除token 操作
  1154. delectToken(state, data) {
  1155. let self = this;
  1156. let {
  1157. success
  1158. } = data;
  1159. reqUtil.requestData(config.URL.USERLOGINOUT, {}).then(res => {
  1160. console.log('USERLOGINOUT=====', res);
  1161. self.commit("logout");
  1162. try {
  1163. //清空保存的storage
  1164. uni.clearStorageSync();
  1165. } catch (e) {
  1166. // error
  1167. console.error(e);
  1168. }
  1169. if (state.BLERSSIInterval) {
  1170. clearInterval(state.BLERSSIInterval);
  1171. state.BLERSSIInterval = null;
  1172. }
  1173. if (state.BLEConnectDevice) {
  1174. self.commit("onCloseBLEConnection", {
  1175. getSuccess: () => {}
  1176. });
  1177. }
  1178. if (success) {
  1179. success(res);
  1180. }
  1181. },
  1182. e => {
  1183. console.log(e)
  1184. });
  1185. },
  1186. logout(state) {
  1187. state.userInfo = null;
  1188. state.userName = "匿名";
  1189. state.avatarUrl = '/static/defaultAvatar.png';
  1190. state.days = '0';
  1191. state.signature = '';
  1192. state.gender = 0;
  1193. state.hasLogin = false;
  1194. state.phoneNumber = '';
  1195. state.openid = '';
  1196. state.appleid = '';
  1197. //处理设备值
  1198. state.cIndex = -1;
  1199. //绑定的设备
  1200. state.ConnectBindingDevice = null;
  1201. //蓝牙设备
  1202. state.BLEConnectDevice = null;
  1203. //蓝牙服务
  1204. state.BLEGetServices = null;
  1205. //最近连接过的设备
  1206. state.finallyUseDevice = null;
  1207. //最近选择的好友
  1208. state.finallySelectFriendInfo = null;
  1209. //记录的蓝牙设备,保存id, 和对应的蓝牙连接数据
  1210. state.BLEDeviceList = [];
  1211. //显示的蓝牙设备,取本地数据时候更新
  1212. state.BLEDeviceShowList = [];
  1213. //记录表盘计划刷新的卡路里
  1214. state.oldArcbarProCalorie = 0;
  1215. //记录表盘当前的总卡路里
  1216. state.oldArcbarAllCalorie = 0;
  1217. //任务相关
  1218. state.currentJumpTask = null;
  1219. },
  1220. loginUserInfo(state, data) {
  1221. let {
  1222. infoRes,
  1223. success,
  1224. fail
  1225. } = data;
  1226. console.log('loginUserInfo');
  1227. reqUtil.requestData(config.URL.WXGETUSERINFO, {
  1228. appid: 'wxd6dfd60729d33d17',
  1229. encryptedData: infoRes.encryptedData,
  1230. iv: infoRes.iv,
  1231. signature: infoRes.signature,
  1232. rawData: infoRes.rawData
  1233. }).then(res => {
  1234. console.log('wxInfoRes=====', res);
  1235. let userInfo = res.data;
  1236. this.commit('login', userInfo);
  1237. if (success) {
  1238. success(res);
  1239. }
  1240. },
  1241. e => {
  1242. console.log(e)
  1243. if (fail) {
  1244. success(fail);
  1245. }
  1246. });
  1247. },
  1248. //这里统一静默处理login
  1249. oauth(state, context) {
  1250. let {
  1251. value,
  1252. callback
  1253. } = context;
  1254. uni.login({
  1255. provider: value,
  1256. success: (res) => {
  1257. // console.log('code:', res);
  1258. reqUtil.requestData(config.URL.USERlOGINURL, {
  1259. appid: 'wxd6dfd60729d33d17',
  1260. code: res.code,
  1261. platfrom: value
  1262. }).then(res => {
  1263. console.log('login token=====', res);
  1264. state.token = res.data.token;
  1265. uni.setStorageSync('token', state.token);
  1266. uni.getUserInfo({
  1267. provider: value,
  1268. success: (infoRes) => {
  1269. if (callback) {
  1270. callback(infoRes);
  1271. }
  1272. },
  1273. fail: (failRes) => {
  1274. //假如没有授权,login 之后,不做处理,需要用户点击授权时候,再进行处理用户登录
  1275. console.log('getUserInfo failRes:', failRes)
  1276. }
  1277. });
  1278. },
  1279. e => {
  1280. console.log(e)
  1281. });
  1282. },
  1283. fail: (err) => {
  1284. console.error('授权登录失败:' + JSON.stringify(err));
  1285. }
  1286. });
  1287. },
  1288. onLuanchLogin(state, data) {
  1289. let {
  1290. success
  1291. } = data;
  1292. const filters = ['weixin', 'qq', 'sinaweibo'];
  1293. let platform = '';
  1294. uni.getProvider({
  1295. service: 'oauth',
  1296. success: (res) => {
  1297. if (res.provider && res.provider.length) {
  1298. for (let i = 0; i < res.provider.length; i++) {
  1299. if (~filters.indexOf(res.provider[i])) {
  1300. platform = res.provider[i];
  1301. console.log("platform=", platform);
  1302. uni.showToast({
  1303. icon: 'loading',
  1304. title: ''
  1305. })
  1306. this.commit('oauth', {
  1307. value: platform,
  1308. callback: (infoRes) => {
  1309. // console.log("infoRes:", infoRes);
  1310. this.commit('loginUserInfo', {
  1311. infoRes: infoRes,
  1312. success: (res) => {
  1313. console.log("获取用户成功");
  1314. if (success) {
  1315. success(res);
  1316. }
  1317. uni.hideToast();
  1318. },
  1319. fail: (res) => {
  1320. console.error("获取用户失败");
  1321. uni.hideToast();
  1322. }
  1323. });
  1324. }
  1325. })
  1326. }
  1327. }
  1328. this.hasProvider = true;
  1329. }
  1330. },
  1331. fail: (err) => {
  1332. console.error('获取服务供应商失败:' + JSON.stringify(err));
  1333. }
  1334. });
  1335. },
  1336. initAdapter(state, callback) {
  1337. //初始化蓝牙模块
  1338. let params = {
  1339. success: (res) => {
  1340. state.bOpenSuccess = true;
  1341. state.bOpenBluetooth = true;
  1342. if (callback)
  1343. callback(res);
  1344. //监听断开事件
  1345. this.commit("B_OnBLEConnectionStateChange");
  1346. },
  1347. fail: (fail) => {
  1348. state.bOpenSuccess = false;
  1349. state.bOpenBluetooth = false;
  1350. uni.showToast({
  1351. title: '蓝牙尚未开启!',
  1352. icon: 'none'
  1353. })
  1354. },
  1355. complete: (complete) => {
  1356. console.log("complete bListenAdapterStateChange:", state.bListenAdapterStateChange);
  1357. if (state.bListenAdapterStateChange) return;
  1358. state.bListenAdapterStateChange = true;
  1359. uni.onBluetoothAdapterStateChange((res) => {
  1360. console.log('adapterState changed, now is', res)
  1361. // 手机蓝牙状态
  1362. state.bOpenBluetooth = res.available;
  1363. if (state.bOpenBluetooth && !state.bOpenSuccess) {
  1364. this.commit('initAdapter');
  1365. }
  1366. })
  1367. }
  1368. };
  1369. this.commit("B_OpenBluetoothAdapter", params);
  1370. },
  1371. // todo 未使用到
  1372. onGetDevices(state, context) {
  1373. let {
  1374. success
  1375. } = context;
  1376. if (!state.BLEConnectDevice) return;
  1377. // #ifdef APP-PLUS
  1378. let deviceId = state.BLEConnectDevice.deviceId;
  1379. uni.getBLEDeviceRSSI({
  1380. deviceId,
  1381. success: res => {
  1382. let _dis = Math.pow(Math.E, (Math.abs(res.RSSI) - 66.78) / 16.56);
  1383. if (_dis > state.BLEConnectDevice.limitDis) {
  1384. if (state.cIndex != -1) {
  1385. uni.showToast({
  1386. title: '设备断开连接!',
  1387. icon: 'none',
  1388. duration: 2000,
  1389. mask: true
  1390. })
  1391. }
  1392. setTimeout(() => {
  1393. this.commit("B_CloseBLEConnection", {
  1394. deviceId: deviceId
  1395. })
  1396. state.cIndex = -1;
  1397. state.bConnection = false;
  1398. state.bVerifiedConnection = false;
  1399. }, 1000)
  1400. } else {
  1401. // console.log("DIS~~~~~~~~~", _dis);
  1402. if (success) {
  1403. success({
  1404. RSSI: res.RSSI,
  1405. DIS: _dis
  1406. });
  1407. }
  1408. }
  1409. }
  1410. })
  1411. // #endif
  1412. },
  1413. //清除连接的开启的timeout
  1414. onUnloadCreateBLEConnectionTimeout(state) {
  1415. if (state.getBLEDeviceServicesTimeout) {
  1416. clearTimeout(state.getBLEDeviceServicesTimeout);
  1417. state.getBLEDeviceServicesTimeout = null;
  1418. }
  1419. },
  1420. initBLEData(state) {
  1421. // 设备Id
  1422. state.deviceId = "";
  1423. // 服务Id
  1424. state.serviceId = "";
  1425. state.notifyCharacteristicId = "";
  1426. state.writeCharacteristicId = "";
  1427. state.currentInstruction = "";
  1428. state.showToast = false;
  1429. state.bListenerUpdate = false;
  1430. state.bListenerJson = false;
  1431. state.bListenerMac = false;
  1432. state.bListenerAccArray = false;
  1433. //更新二进制的
  1434. state.bListenerHexUpdate = false;
  1435. },
  1436. //连接蓝牙
  1437. onCreateBLEConnection(state, context) {
  1438. let {
  1439. index,
  1440. item,
  1441. initItem = false,
  1442. getSuccess = null,
  1443. getinitAdapter = null
  1444. } = context;
  1445. uni.showToast({
  1446. title: '连接设备中...',
  1447. icon: 'loading',
  1448. duration: 10000,
  1449. mask: true
  1450. })
  1451. let params = {
  1452. item: item,
  1453. success: (success) => {
  1454. state.bConnection = true;
  1455. if (state.getBLEDeviceServicesTimeout) {
  1456. clearTimeout(state.getBLEDeviceServicesTimeout);
  1457. state.getBLEDeviceServicesTimeout = null;
  1458. }
  1459. state.getBLEDeviceServicesTimeout = setTimeout(() => {
  1460. let retryCount = 5;
  1461. this.commit("B_GetBLEDeviceServices", {
  1462. retryCount: retryCount,
  1463. item: item,
  1464. callback: () => {
  1465. uni.showToast({
  1466. title: '连接成功',
  1467. icon: 'loading',
  1468. duration: 2000,
  1469. mask: true
  1470. })
  1471. //是否需要设置item,默认不设置
  1472. if (initItem) {
  1473. state.cIndex = index;
  1474. state.BLEConnectDevice = item;
  1475. }
  1476. if (getSuccess)
  1477. getSuccess();
  1478. /**
  1479. * 直接连接过成功
  1480. */
  1481. state.bVerifiedConnection = true;
  1482. },
  1483. getServiceList: (serviceList) => {
  1484. //搜索服务失败后
  1485. state.BLEGetServices = serviceList;
  1486. },
  1487. getFail: () => {
  1488. this.commit("B_CloseBLEConnection", {
  1489. deviceId: item.deviceId
  1490. })
  1491. // state.cIndex = -1;
  1492. // state.bConnection = false;
  1493. // state.bVerifiedConnection = false;
  1494. this.commit("onResetBLEConnection");
  1495. }
  1496. });
  1497. }, 2000);
  1498. },
  1499. fail: (fail) => {
  1500. console.log("***fail:", fail);
  1501. if (fail.errCode === 10012) {
  1502. console.log("连接超时,请重试!");
  1503. uni.showToast({
  1504. title: '连接失败,开启设备后尝试重新连接!',
  1505. icon: 'none',
  1506. duration: 3000,
  1507. mask: true
  1508. })
  1509. } else if (fail.errCode === 10013) {
  1510. console.log("连接失败,蓝牙地址无效!");
  1511. uni.showToast({
  1512. title: '连接失败,蓝牙地址无效',
  1513. icon: 'none',
  1514. duration: 2000,
  1515. mask: true
  1516. })
  1517. } else if (fail.errCode === 10000) {
  1518. this.commit('initAdapter', () => {
  1519. if (getinitAdapter) {
  1520. getinitAdapter();
  1521. }
  1522. })
  1523. } else {
  1524. // err.errCode10003原因多种:蓝牙设备未开启或异常导致无法连接;蓝牙设备被占用或者上次蓝牙连接未断开导致无法连接
  1525. console.log("连接失败,请重试!", state.BLEConnectDevice);
  1526. uni.showToast({
  1527. title: '请尝试开启设备和重启app。',
  1528. icon: 'none',
  1529. duration: 2000,
  1530. mask: true
  1531. })
  1532. }
  1533. }
  1534. };
  1535. this.commit("B_CreateBLEConnection", params);
  1536. },
  1537. //devices hardware 连接后验证,这里不需要处理 bVerifiedConnection,通过mac 验证后处理
  1538. onCreateBLESuccess(state, context) {
  1539. let {
  1540. item,
  1541. getSuccess = null
  1542. } = context;
  1543. this.commit("B_CreateBLEConnection", {
  1544. item: item,
  1545. success: success => {
  1546. state.BLEConnectDevice = item;
  1547. state.bConnection = true;
  1548. if (getSuccess) {
  1549. getSuccess();
  1550. }
  1551. },
  1552. fail: fail => {
  1553. if (fail.errCode === 10012) {
  1554. console.log("连接超时,请重试!");
  1555. uni.showToast({
  1556. title: '连接超时,检查对应设备是否开启?',
  1557. icon: 'none',
  1558. duration: 2000,
  1559. mask: true
  1560. })
  1561. } else if (fail.errCode === 10013) {
  1562. console.log("连接失败,蓝牙地址无效!");
  1563. uni.showToast({
  1564. title: '蓝牙地址无效,检查设备是否正常?',
  1565. icon: 'none',
  1566. duration: 2000,
  1567. mask: true
  1568. })
  1569. } else if (fail.errCode === 10000) {
  1570. console.log("连接失败,初始化 wx.openBluetoothAdapter 调用之后使用");
  1571. uni.showToast({
  1572. title: '连接失败,检查手机蓝牙是否开启?',
  1573. icon: 'none',
  1574. duration: 2000,
  1575. mask: true
  1576. })
  1577. } else {
  1578. console.log("连接失败,请重试!");
  1579. uni.showModal({
  1580. title: '连接失败',
  1581. content: '设备未开启或被占用。请重启app和设备后重新连接。'
  1582. })
  1583. // uni.showToast({
  1584. // title: '设备未开启或被占用异常导致无法连接。',
  1585. // icon: 'none',
  1586. // duration: 2000,
  1587. // mask: true
  1588. // })
  1589. }
  1590. }
  1591. });
  1592. },
  1593. //获取蓝牙服务
  1594. onGetBLEDeviceServices(state, context) {
  1595. let {
  1596. item,
  1597. success = null,
  1598. } = context;
  1599. let retryCount = 5;
  1600. this.commit("B_GetBLEDeviceServices", {
  1601. retryCount: retryCount,
  1602. item: item,
  1603. callback: success,
  1604. getServiceList: (serviceList) => {
  1605. state.BLEGetServices = serviceList;
  1606. },
  1607. getFail: () => {
  1608. this.commit("B_CloseBLEConnection", {
  1609. deviceId: item.deviceId
  1610. })
  1611. this.commit("onResetBLEConnection");
  1612. }
  1613. })
  1614. },
  1615. //重置蓝牙连接参数
  1616. onResetBLEConnection(state) {
  1617. state.cIndex = -1;
  1618. state.BLEConnectDevice = null;
  1619. //蓝牙服务
  1620. state.BLEGetServices = null;
  1621. state.bConnection = false;
  1622. state.bVerifiedConnection = false;
  1623. },
  1624. onCloseBLEConnection(state, context) {
  1625. console.log("onCloseBLEConnection", state.BLEConnectDevice);
  1626. let {
  1627. getSuccess = null,
  1628. } = context;
  1629. if (state.BLERSSIInterval) {
  1630. clearInterval(state.BLERSSIInterval);
  1631. state.BLERSSIInterval = null;
  1632. }
  1633. this.commit("B_CloseBLEConnection", {
  1634. deviceId: state.BLEConnectDevice.deviceId,
  1635. success: () => {
  1636. state.cIndex = -1;
  1637. state.BLEConnectDevice = null;
  1638. //蓝牙服务
  1639. state.BLEGetServices = null;
  1640. if (getSuccess) {
  1641. getSuccess();
  1642. }
  1643. state.bConnection = false;
  1644. state.bVerifiedConnection = false;
  1645. uni.closeBluetoothAdapter({
  1646. success(res) {
  1647. console.log(res)
  1648. state.bOpenBluetooth = false;
  1649. }
  1650. })
  1651. }
  1652. });
  1653. },
  1654. //不关闭 adapter
  1655. onOnlyCloseBLEConnection(state, context) {
  1656. let {
  1657. getSuccess = null
  1658. } = context;
  1659. if (state.BLERSSIInterval) {
  1660. clearInterval(state.BLERSSIInterval);
  1661. state.BLERSSIInterval = null;
  1662. }
  1663. this.commit("B_CloseBLEConnection", {
  1664. deviceId: state.BLEConnectDevice.deviceId,
  1665. success: () => {
  1666. state.cIndex = -1;
  1667. state.BLEConnectDevice = null;
  1668. //蓝牙服务
  1669. state.BLEGetServices = null;
  1670. if (getSuccess) {
  1671. getSuccess();
  1672. }
  1673. state.bConnection = false;
  1674. state.bVerifiedConnection = false;
  1675. }
  1676. });
  1677. },
  1678. onWriteBLEConnectionValue(state, context) {
  1679. //#ifdef H5
  1680. console.warn("h5不支持蓝牙:", 'onWriteBLEConnectionValue');
  1681. return;
  1682. //#endif
  1683. let {
  1684. getSuccess = null,
  1685. getFail = null,
  1686. value,
  1687. bSendHex = false,
  1688. bOpen = false,
  1689. } = context;
  1690. if (!state.BLEConnectDevice && state.cIndex == -1) {
  1691. uni.showToast({
  1692. title: '蓝牙设备未连接',
  1693. icon: 'none'
  1694. })
  1695. }
  1696. // console.log(22);
  1697. //记录蓝牙盒子当前的指令
  1698. // state.currentInstruction = value;
  1699. // 发送 3 :开启原始数据
  1700. // 发送4 :关闭原始数据
  1701. // 发送 5 :开启步数
  1702. // 发送6 :关闭步数
  1703. if (value == "3") {
  1704. state.instructionState.bOpen = true;
  1705. } else if (value == "4") {
  1706. state.instructionState.bOpen = false;
  1707. } else if (value == "5") {
  1708. state.instructionState.bSteps = true;
  1709. } else if (value == "6") {
  1710. state.instructionState.bSteps = false;
  1711. } else if (bSendHex && bOpen) {
  1712. state.instructionState.bOpen = true;
  1713. } else if (bSendHex && !bOpen) {
  1714. state.instructionState.bOpen = false;
  1715. }
  1716. let retryCount = 5;
  1717. this.commit("B_WriteBLECharacteristicValue", {
  1718. value,
  1719. retryCount,
  1720. getSuccess,
  1721. getFail,
  1722. bSendHex
  1723. });
  1724. },
  1725. //获取距离
  1726. onGetRSSITransDistance(state, context) {
  1727. let {
  1728. RSSI
  1729. } = context;
  1730. BLE.getRSSITransDistance(RSSI);
  1731. },
  1732. //添加使用的前端信息
  1733. gOnAddClientInfo(state, context) {
  1734. uni.getSystemInfo({
  1735. success: (res) => {
  1736. // console.log("系统信息:", res);
  1737. let clientInfo = res;
  1738. clientInfo.clientSystem = res.system;
  1739. reqUtil.requestData(config.URL.ADDCLIENTINFO, clientInfo, 'POST').then(
  1740. res => {
  1741. console.warn(res);
  1742. },
  1743. e => {}
  1744. );
  1745. },
  1746. fail: (err) => {},
  1747. complete: () => {}
  1748. })
  1749. },
  1750. //创建快速打击对象
  1751. gCreateFilterObj(state) {
  1752. state.filter = null;
  1753. state.deviceMs = 1;
  1754. state.filter = new o0Project.Filter();
  1755. console.log("gCreateFilterObj");
  1756. },
  1757. //更新快速打击对象数据
  1758. gUpdateFilter(state, context) {
  1759. let {
  1760. data,
  1761. callback
  1762. } = context;
  1763. let {
  1764. min,
  1765. s,
  1766. ms
  1767. } = data;
  1768. var msGap = ms - state.deviceMs;
  1769. state.deviceMs = ms;
  1770. while (msGap < 0) {
  1771. msGap += 1000;
  1772. }
  1773. // console.log(data);
  1774. let {
  1775. ax,
  1776. ay,
  1777. az
  1778. } = data.acc;
  1779. let {
  1780. gx,
  1781. gy,
  1782. gz
  1783. } = data.gyro;
  1784. state.filter.Update(new o0.Vector3(ax, ay, az), msGap, new o0.Vector3(gx, gy, gz),
  1785. callback); //我自己的更新acc的函数
  1786. },
  1787. /**
  1788. * 创建一个沙袋打击对象
  1789. * @param {Object} state
  1790. */
  1791. gCreateSandbagAlgorithm(state) {
  1792. state.sandbagAlgorithm = null;
  1793. state.sandbagAlgorithmLastTime = new Date().getTime();
  1794. state.sandbagAlgorithm = new o0ProjectRelease.SandbagAlgorithm();
  1795. console.log("gCreateSandbagAlgorithm");
  1796. },
  1797. /**
  1798. * 更新 沙袋打击对象 数据
  1799. * @param {Object} state
  1800. * @param {Object} context
  1801. */
  1802. gUpdateSandbagAlgorithm(state, context) {
  1803. let {
  1804. data,
  1805. callback = null
  1806. } = context;
  1807. let {
  1808. ax,
  1809. ay,
  1810. az
  1811. } = data.acc;
  1812. let {
  1813. gx,
  1814. gy,
  1815. gz
  1816. } = data.gyro;
  1817. let [hit, dir] = state.sandbagAlgorithm.Update(ax / 10, az / 10, gz, -gx, data.ms);
  1818. if (dir != undefined) {
  1819. let temp = state.sandbagAlgorithm.getTempValue(dir);
  1820. if (callback) {
  1821. callback(temp);
  1822. }
  1823. }
  1824. },
  1825. /**
  1826. * 开启加速计,陀螺仪,并且模拟ble发送
  1827. * @param {Object} state
  1828. */
  1829. gStartSimulateBLEUpdate(state) {
  1830. //todo 区分平台,目前是android 模块
  1831. if (state.globalMyAttitude == null) {
  1832. state.globalMyAttitude = uni.requireNativePlugin("MyAttitude");
  1833. let globalEvent = uni.requireNativePlugin('globalEvent');
  1834. globalEvent.addEventListener('updateAccAndGyro', function(e) {
  1835. //updateAccAndGyro{"accelerometer":[-0.178375244140625,9.327804565429688,2.6168670654296875],"gyroscope":[0.0018310546875,-0.0019989013671875,0.0027923583984375]}
  1836. //console.log('updateAccAndGyro' + JSON.stringify(e));
  1837. let _accArray = e.accelerometer;
  1838. let _gyroArray = e.gyroscope;
  1839. state.globalAccData.ax = _accArray[0];
  1840. state.globalAccData.ay = _accArray[1];
  1841. state.globalAccData.az = _accArray[2];
  1842. state.globalGyroData.gx = _gyroArray[0];
  1843. state.globalGyroData.gy = _gyroArray[1];
  1844. state.globalGyroData.gz = _gyroArray[2];
  1845. let box = {};
  1846. box["acc"] = state.globalAccData;
  1847. box["gyro"] = state.globalGyroData;
  1848. box["ms"] = e.ms;
  1849. //更新数据给webview,在game-play-web||game-play-sub绑定
  1850. //后面更新数据都用此接口
  1851. uni.$emit('updateBLEDeviceData', box);
  1852. });
  1853. }
  1854. var ret = state.globalMyAttitude.onStartAccAndGyro();
  1855. if (!ret.accelerometer || !ret.gyroscope) {
  1856. uni.showModal({
  1857. title: '提示',
  1858. content: '是否初始化,加速计:' + ret.accelerometer + ',陀螺仪:' + ret.gyroscope
  1859. })
  1860. }
  1861. console.log('gStartSimulateBLEUpdate:', ret);
  1862. },
  1863. /**
  1864. * 停止加速计,陀螺仪
  1865. * @param {Object} state
  1866. */
  1867. gStopSimulateBLEUpdate(state) {
  1868. //todo 区分平台,目前是android 模块
  1869. let globalEvent = uni.requireNativePlugin('globalEvent');
  1870. globalEvent.removeEventListener('updateAccAndGyro');
  1871. var ret = state.globalMyAttitude.onStopAccAndGyro();
  1872. console.log('gStopSimulateBLEUpdate:', ret);
  1873. state.globalMyAttitude = null;
  1874. },
  1875. /**
  1876. * 限制开始游戏
  1877. */
  1878. glimitPlayGame(state, context) {
  1879. let {
  1880. gameTags,
  1881. callback
  1882. } = context;
  1883. //没有标签直接进去
  1884. if (gameTags.length == 0) {
  1885. callback();
  1886. return;
  1887. }
  1888. let canPlay = false;
  1889. gameTags.forEach((item) => {
  1890. //如果存在普通模式
  1891. if (item.tagMode === 'normal') {
  1892. canPlay = true;
  1893. }
  1894. if (canPlay)
  1895. return;
  1896. })
  1897. if (!canPlay) {
  1898. //2.如果普通模式不存在,就判断是否连接硬件了
  1899. if (!state.BLEConnectDevice || state.cIndex == -1) {
  1900. uni.showToast({
  1901. title: "请连接标签对应的设备模式!",
  1902. icon: "none",
  1903. duration: 2000,
  1904. mask: true
  1905. })
  1906. return;
  1907. }
  1908. //3.如果连接了设备,判断但是处于什么模式
  1909. gameTags.forEach((item, index, selfArr) => {
  1910. //如果存在普通模式
  1911. if (item.tagMode === state.BLEConnectDevice.usageMode) {
  1912. canPlay = true;
  1913. }
  1914. if (canPlay)
  1915. return;
  1916. if (index == selfArr.length - 1) {
  1917. uni.showToast({
  1918. title: "游戏没有当前设备模式!",
  1919. icon: "none",
  1920. duration: 2000,
  1921. mask: true
  1922. })
  1923. }
  1924. })
  1925. }
  1926. if (canPlay) {
  1927. callback();
  1928. }
  1929. },
  1930. checkAppUpdata(state) {
  1931. //#ifdef APP-PLUS
  1932. let _temp = {
  1933. appid: plus.runtime.appid,
  1934. version: state.version,
  1935. versionCode: state.versionCode,
  1936. platform: state.platform.toLocaleLowerCase(),
  1937. }
  1938. //#endif
  1939. //#ifdef H5
  1940. //此 _temp 测试用
  1941. let _temp = {
  1942. appid: '1',
  1943. version: "2.0.0",
  1944. versionCode: "20122202",
  1945. platform: "android",
  1946. }
  1947. //#endif
  1948. reqUtil.requestData(config.URL.APPVERSIONUPDATE, _temp).then(res => {
  1949. console.log('requestData APPVERSIONUPDATE =====', res);
  1950. let _data = res.data;
  1951. if (res.code == 0 && res.data.status === 1) {
  1952. uni.showModal({ //提醒用户更新
  1953. title: "更新提示",
  1954. content: res.data.note,
  1955. success: (res) => {
  1956. if (res.confirm) {
  1957. if (state.platform.toLocaleLowerCase() == "android") {
  1958. plus.runtime.openURL(_data.url, function(res) {
  1959. plus.nativeUI.alert("本机没安装应用宝,请安装后获取新版本。");
  1960. }, 'com.tencent.android.qqdownloader');
  1961. } else {
  1962. //ios
  1963. plus.runtime.openURL(_data.url);
  1964. }
  1965. }
  1966. }
  1967. })
  1968. } else {
  1969. uni.showToast({
  1970. title: '当前为最新版本',
  1971. icon: 'none',
  1972. duration: 2000,
  1973. mask: true
  1974. })
  1975. }
  1976. },
  1977. e => {
  1978. console.log(e)
  1979. });
  1980. },
  1981. /**
  1982. * 蓝牙BLE迁移到store.js
  1983. */
  1984. // 初始化蓝牙模块适配器
  1985. B_OpenBluetoothAdapter(state, context) {
  1986. let {
  1987. success,
  1988. fail,
  1989. complete
  1990. } = context;
  1991. //#ifdef H5
  1992. console.warn('h5不加载蓝牙模块');
  1993. return;
  1994. //#endif
  1995. uni.openBluetoothAdapter({
  1996. success: res => {
  1997. if (success)
  1998. success(res);
  1999. },
  2000. fail: res => {
  2001. if (fail)
  2002. fail(res);
  2003. },
  2004. complete: res => {
  2005. if (complete)
  2006. complete(res);
  2007. }
  2008. })
  2009. },
  2010. /**
  2011. * 关闭蓝牙模块适配器
  2012. */
  2013. B_CloseBluetoothAdapter() {
  2014. //#ifdef H5
  2015. console.warn('h5不加载蓝牙模块');
  2016. return;
  2017. //#endif
  2018. uni.closeBluetoothAdapter({
  2019. success: res => {
  2020. console.log('断开蓝牙模块成功');
  2021. uni.showToast({
  2022. icon: "none",
  2023. title: "蓝牙已经断开!",
  2024. mask: false,
  2025. duration: 3000
  2026. });
  2027. }
  2028. });
  2029. },
  2030. B_OnBLEConnectionStateChange(state) {
  2031. let _self = this;
  2032. //#ifdef H5
  2033. console.warn('h5不加载蓝牙模块');
  2034. return;
  2035. //#endif
  2036. uni.onBLEConnectionStateChange(res => {
  2037. // 该方法回调中可以用于处理连接意外断开等异常情况
  2038. console.log(`蓝牙连接状态 -------------------------->`, JSON.stringify(res));
  2039. if (!res.connected) {
  2040. //要在连接的状态下 ,并且获取过匹配列表有参数的情况下,才提示重连
  2041. if (!state.bShowBLEConnectModal && state.bVerifiedConnection && state
  2042. .bPhoneMatched) {
  2043. state.bShowBLEConnectModal = true;
  2044. let _connectItem = Object.assign({}, state.BLEConnectDevice);
  2045. let _cIndex = state.cIndex;
  2046. //断开连接后reset一下参数
  2047. _self.commit("onResetBLEConnection");
  2048. let _tip = state.bGamePlaying ? "蓝牙已断开是否重新连接蓝牙?重连需要重启游戏!" : "蓝牙已断开是否重新连接蓝牙";
  2049. uni.showModal({
  2050. title: _tip,
  2051. success: (sRes) => {
  2052. state.bShowBLEConnectModal = false;
  2053. if (sRes.confirm) {
  2054. console.log("重连的_cIndex:", _cIndex);
  2055. _self.commit("onCreateBLEConnection", {
  2056. item: _connectItem,
  2057. index: _cIndex,
  2058. initItem: true,
  2059. getSuccess: () => {
  2060. //此处不检查外部设备
  2061. uni.$emit('retryConnectBLESuccess');
  2062. },
  2063. getinitAdapter: () => {}
  2064. })
  2065. }
  2066. }
  2067. })
  2068. } else {
  2069. //断开连接后reset一下参数
  2070. _self.commit("onResetBLEConnection");
  2071. }
  2072. uni.$emit('callbackCloseBLE');
  2073. }
  2074. });
  2075. },
  2076. /**
  2077. * 连接低功耗蓝牙设备。
  2078. * 若APP在之前已有搜索过某个蓝牙设备,并成功建立连接,可直接传入之前搜索获取的 deviceId 直接尝试连接该设备,无需进行搜索操作。
  2079. */
  2080. B_CreateBLEConnection(state, context) {
  2081. let {
  2082. item,
  2083. success,
  2084. fail
  2085. } = context;
  2086. this.commit('initBLEData');
  2087. state.deviceId = item.deviceId;
  2088. let timeout = 10000;
  2089. console.log("B_CreateBLEConnection deviceId ==", state.deviceId)
  2090. uni.createBLEConnection({
  2091. // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
  2092. deviceId: state.deviceId,
  2093. timeout: timeout,
  2094. success: res => {
  2095. if (success) {
  2096. success(res);
  2097. }
  2098. },
  2099. fail: res => {
  2100. if (fail)
  2101. fail(res);
  2102. }
  2103. });
  2104. },
  2105. /**
  2106. * 获取设备的服务ID
  2107. */
  2108. B_GetBLEDeviceServices(state, context) {
  2109. let {
  2110. retryCount,
  2111. item,
  2112. callback,
  2113. getServiceList,
  2114. getFail,
  2115. } = context;
  2116. let serviceList = [];
  2117. let _self = this;
  2118. uni.getBLEDeviceServices({
  2119. deviceId: item.deviceId,
  2120. success: res => {
  2121. // console.log("getBLEDeviceServices==", JSON.stringify(res), item);
  2122. serviceList = res.services;
  2123. if (getServiceList) {
  2124. getServiceList(serviceList);
  2125. }
  2126. if (serviceList.length == 0) {
  2127. if (retryCount > 0) {
  2128. retryCount--;
  2129. context.retryCount = retryCount;
  2130. setTimeout(() => {
  2131. this.commit('B_GetBLEDeviceServices', context);
  2132. }, 500)
  2133. return;
  2134. }
  2135. if (getFail) {
  2136. getFail();
  2137. }
  2138. uni.hideToast();
  2139. uni.showModal({
  2140. title: '提示',
  2141. content: '1.获取服务失败,请尝试重新连接设备。\r\n2.尝试重启设备再重新连接。'
  2142. })
  2143. }
  2144. for (let i = 0; i < serviceList.length; i++) {
  2145. let service = serviceList[i];
  2146. if (service.uuid.toLocaleLowerCase() === item.PRIMARY_SERVICE
  2147. .toLocaleLowerCase()) {
  2148. state.serviceId = service.uuid;
  2149. //开始获取指定服务的特征值
  2150. _self.commit('B_GetBLEDeviceCharacteristics', {
  2151. item: item,
  2152. callback: callback
  2153. });
  2154. break;
  2155. }
  2156. }
  2157. },
  2158. fail: failRes => {
  2159. console.log('device services:', failRes.services)
  2160. uni.showModal({
  2161. title: '连接错误',
  2162. content: '请尝试重新连接设备。'
  2163. })
  2164. if (getFail) {
  2165. getFail();
  2166. }
  2167. }
  2168. });
  2169. },
  2170. /**
  2171. * 获取指定服务的特征值
  2172. */
  2173. B_GetBLEDeviceCharacteristics(state, context) {
  2174. let {
  2175. item,
  2176. callback
  2177. } = context;
  2178. let deviceId = state.deviceId;
  2179. let serviceId = state.serviceId;
  2180. let characteristicsList = [];
  2181. uni.getBLEDeviceCharacteristics({
  2182. deviceId,
  2183. serviceId,
  2184. success: res => {
  2185. if (item.PRIMARY_NOTIFY != '') {
  2186. state.notifyCharacteristicId = item.PRIMARY_NOTIFY;
  2187. this.commit('B_NotifyBLECharacteristicValueChange', {
  2188. callback: callback
  2189. });
  2190. }
  2191. if (item.PRIMARY_WRITE != '') {
  2192. state.writeCharacteristicId = item.PRIMARY_WRITE;
  2193. }
  2194. },
  2195. fail: res => {
  2196. console.log('device getBLEDeviceCharacteristics failed:', JSON.stringify(res))
  2197. }
  2198. })
  2199. },
  2200. //启用低功耗蓝牙设备特征值变化时的 notify 功能,订阅特征值。
  2201. //注意:必须设备的特征值支持notify或者indicate才可以成功调用,具体参照 characteristic 的 properties 属性
  2202. B_NotifyBLECharacteristicValueChange(state, context) {
  2203. let {
  2204. callback
  2205. } = context;
  2206. // 启用notify功能
  2207. // console.log("启用notify功能");
  2208. uni.notifyBLECharacteristicValueChange({
  2209. state: true,
  2210. deviceId: state.deviceId,
  2211. serviceId: state.serviceId,
  2212. characteristicId: state.notifyCharacteristicId,
  2213. success: (res) => {
  2214. this.commit('B_OnBLECharacteristicValueChange', {
  2215. callback: callback
  2216. });
  2217. // _self.onBLECharacteristicValueChange(callback); //监听特征值变化
  2218. },
  2219. fail: (res) => {
  2220. uni.showToast({
  2221. title: 'notify启动失败',
  2222. icon: "none",
  2223. mask: true
  2224. });
  2225. }
  2226. })
  2227. },
  2228. //监听低功耗蓝牙设备的特征值变化。必须先启用notify接口才能接收到设备推送的notification。
  2229. B_OnBLECharacteristicValueChange(state, context) {
  2230. let {
  2231. callback
  2232. } = context;
  2233. console.log("onBLECharacteristicValueChange success");
  2234. if (callback) {
  2235. callback({
  2236. notifyCharacteristicId: state.notifyCharacteristicId,
  2237. writeCharacteristicId: state.writeCharacteristicId
  2238. })
  2239. }
  2240. uni.onBLECharacteristicValueChange(function(res) {
  2241. let box = {};
  2242. var resValue = BLE.ab2hext(res.value); //16进制字符串
  2243. if (state.currentInstruction == "V" && state.showToast) {
  2244. var resValueStr = BLE.hexToString(resValue);
  2245. let _info = {
  2246. type: 'version',
  2247. instruction: 'V',
  2248. value: resValueStr.replace(/\{|}/g, '').trim()
  2249. }
  2250. uni.$emit('listenerBLE', _info);
  2251. state.currentInstruction = "";
  2252. state.showToast = false;
  2253. return;
  2254. } else if (state.currentInstruction == 'M' && state.bListenerMac) {
  2255. var resValueStr = BLE.hexToString(resValue);
  2256. let _info = {
  2257. type: 'mac',
  2258. instruction: 'M',
  2259. value: resValueStr.replace(/\{|}/g, '').trim()
  2260. }
  2261. uni.$emit('listenerBLE', _info);
  2262. state.currentInstruction = "";
  2263. state.bListenerMac = false;
  2264. return;
  2265. }
  2266. //步数数据解析
  2267. if (state.bListenerJson) {
  2268. var resValueStr = BLE.hexToString(resValue);
  2269. console.log(resValueStr);
  2270. box["Json"] = resValueStr;
  2271. uni.$emit('updateBLEDeviceJson', box);
  2272. }
  2273. //解析4组加速计数据
  2274. if (state.bListenerAccArray) {
  2275. let ms1 = BLE.hex2int(resValue.substr(2, 4));
  2276. let min1 = BLE.hex2int(resValue.substr(6, 2));
  2277. let s1 = BLE.hex2int(resValue.substr(8, 2));
  2278. let ax1Str = resValue.substr(10, 4);
  2279. let ay1Str = resValue.substr(14, 4);
  2280. let az1Str = resValue.substr(18, 4);
  2281. let ax1 = BLE.hexToSignedInt(ax1Str) / 32768 * 16;
  2282. let ay1 = BLE.hexToSignedInt(ay1Str) / 32768 * 16;
  2283. let az1 = BLE.hexToSignedInt(az1Str) / 32768 * 16;
  2284. let ms2 = BLE.hex2int(resValue.substr(22, 4));
  2285. let min2 = BLE.hex2int(resValue.substr(26, 2));
  2286. let s2 = BLE.hex2int(resValue.substr(28, 2));
  2287. let ax2Str = resValue.substr(30, 4);
  2288. let ay2Str = resValue.substr(34, 4);
  2289. let az2Str = resValue.substr(38, 4);
  2290. let ax2 = BLE.hexToSignedInt(ax2Str) / 32768 * 16;
  2291. let ay2 = BLE.hexToSignedInt(ay2Str) / 32768 * 16;
  2292. let az2 = BLE.hexToSignedInt(az2Str) / 32768 * 16;
  2293. let ms3 = BLE.hex2int(resValue.substr(42, 4));
  2294. let min3 = BLE.hex2int(resValue.substr(46, 2));
  2295. let s3 = BLE.hex2int(resValue.substr(48, 2));
  2296. let ax3Str = resValue.substr(50, 4);
  2297. let ay3Str = resValue.substr(54, 4);
  2298. let az3Str = resValue.substr(58, 4);
  2299. let ax3 = BLE.hexToSignedInt(ax3Str) / 32768 * 16;
  2300. let ay3 = BLE.hexToSignedInt(ay3Str) / 32768 * 16;
  2301. let az3 = BLE.hexToSignedInt(az3Str) / 32768 * 16;
  2302. let ms4 = BLE.hex2int(resValue.substr(62, 4));
  2303. let min4 = BLE.hex2int(resValue.substr(66, 2));
  2304. let s4 = BLE.hex2int(resValue.substr(68, 2));
  2305. let ax4Str = resValue.substr(70, 4);
  2306. let ay4Str = resValue.substr(74, 4);
  2307. let az4Str = resValue.substr(78, 4);
  2308. let ax4 = BLE.hexToSignedInt(ax4Str) / 32768 * 16;
  2309. let ay4 = BLE.hexToSignedInt(ay4Str) / 32768 * 16;
  2310. let az4 = BLE.hexToSignedInt(az4Str) / 32768 * 16;
  2311. let accArray = [{
  2312. ax: ax1,
  2313. ay: ay1,
  2314. az: az1,
  2315. ms: ms1,
  2316. min: min1,
  2317. s: s1
  2318. }, {
  2319. ax: ax2,
  2320. ay: ay2,
  2321. az: az2,
  2322. ms: ms2,
  2323. min: min2,
  2324. s: s2
  2325. }, {
  2326. ax: ax3,
  2327. ay: ay3,
  2328. az: az3,
  2329. ms: ms3,
  2330. min: min3,
  2331. s: s3
  2332. }, {
  2333. ax: ax4,
  2334. ay: ay4,
  2335. az: az4,
  2336. ms: ms4,
  2337. min: min4,
  2338. s: s4
  2339. }]
  2340. for (let i = 0; i < accArray.length; i++) {
  2341. let _temp = accArray[i];
  2342. box["acc"] = {
  2343. ax: _temp.ax,
  2344. ay: _temp.ay,
  2345. az: _temp.az,
  2346. };
  2347. box["min"] = _temp.min;
  2348. box["s"] = _temp.s;
  2349. box["ms"] = _temp.ms;
  2350. uni.$emit('updateBLEDeviceData', box);
  2351. }
  2352. }
  2353. //原始数据解析
  2354. if (state.bListenerUpdate) {
  2355. //R/L 左手还是右手
  2356. let handle = resValue.substr(6, 2);
  2357. let axStr = resValue.substr(8, 4);
  2358. let ayStr = resValue.substr(12, 4);
  2359. let azStr = resValue.substr(16, 4);
  2360. //一个字节最大只能表示265 2个字节可以表示65536 然后你这边做一下转换 例如00 3E 3*16+14=62 ----->0.03 g
  2361. //(真实值= AD值 /32768 * 16)
  2362. //0.003 = 62 / 2768 * 16
  2363. let ax = BLE.hexToSignedInt(axStr) / 32768 * 16;
  2364. let ay = BLE.hexToSignedInt(ayStr) / 32768 * 16;
  2365. let az = BLE.hexToSignedInt(azStr) / 32768 * 16;
  2366. let gxStr = resValue.substr(20, 4);
  2367. let gyStr = resValue.substr(24, 4);
  2368. let gzStr = resValue.substr(28, 4);
  2369. //角速度(AD值/32768 * 2000) 角速度单位是 °/s 范围是 正负2000
  2370. let gx = BLE.hexToSignedInt(gxStr) / 32768 * 2000;
  2371. let gy = BLE.hexToSignedInt(gyStr) / 32768 * 2000;
  2372. let gz = BLE.hexToSignedInt(gzStr) / 32768 * 2000;
  2373. //毫秒
  2374. let ms = BLE.hex2int(resValue.substr(2, 4));
  2375. //分
  2376. let min = BLE.hex2int(resValue.substr(32, 2));
  2377. //秒
  2378. let s = BLE.hex2int(resValue.substr(34, 2));
  2379. box["handle"] = BLE.hexToString(handle);
  2380. box["acc"] = {
  2381. ax,
  2382. ay,
  2383. az
  2384. };
  2385. box["gyro"] = {
  2386. gx,
  2387. gy,
  2388. gz
  2389. };
  2390. box["min"] = min;
  2391. box["s"] = s;
  2392. box["ms"] = ms;
  2393. //更新数据给webview,在game-play-web||game-play-sub绑定
  2394. //后面更新数据都用此接口
  2395. uni.$emit('updateBLEDeviceData', box);
  2396. }
  2397. //todo 解析跳绳模式
  2398. if (state.bListenerHexUpdate) {
  2399. //报头,固定
  2400. let byte1 = resValue.substr(0, 2);
  2401. //功能码,todo
  2402. let byte2 = resValue.substr(2, 2);
  2403. // 报文类型,后续区分在这里,目前是跳绳模式类型
  2404. let byte3 = resValue.substr(4, 2);
  2405. //报文内容,长度以 2为单位 动态变化
  2406. let byteData = resValue.substr(6, resValue.length - 10)
  2407. //报文按照长度2切割
  2408. let byteArray = byteData.replace(/(\d{2})(?=(?:\d{2})+(?!\d))/g, '$1,').split(',');
  2409. console.log("byteArray:", byteArray);
  2410. // 校验
  2411. let byteVerify = resValue.substr(resValue.length - 4, 2);
  2412. // 报尾,结束
  2413. let byteEnd = resValue.substr(resValue.length - 2, 2);
  2414. //todo 暂时先这样触发
  2415. if (byteArray.length == 2 && byteArray[0] != byteArray[1]) {
  2416. if (byteArray[0] == '00') {
  2417. state.bRopeKeyOne = 1;
  2418. } else {
  2419. //'01'
  2420. state.bRopeKeyTwo = 1;
  2421. }
  2422. if (state.bRopeKeyOne == 1 && state.bRopeKeyTwo == 1) {
  2423. state.bRopeKeyOne = 0;
  2424. state.bRopeKeyTwo = 0;
  2425. box["Rope"] = 1;
  2426. uni.$emit('updateBLEDeviceData', box);
  2427. }
  2428. }
  2429. }
  2430. });
  2431. },
  2432. /**
  2433. * 开启跳绳模式
  2434. */
  2435. B_OpenRopeSkipping() {
  2436. // this.commit('onWriteBLEConnectionValue', {
  2437. // value: "5B310101FE5D",
  2438. // bSendHex: true,
  2439. // bOpen: true
  2440. // });
  2441. console.log('B_OpenRopeSkipping', 3);
  2442. this.commit('onWriteBLEConnectionValue', {
  2443. value: "3"
  2444. });
  2445. },
  2446. /**
  2447. * 关闭跳绳模式
  2448. */
  2449. B_CloseRopeSkipping() {
  2450. // this.commit('onWriteBLEConnectionValue', {
  2451. // value: "5B210100FF5D",
  2452. // bSendHex: true,
  2453. // bOpen: false
  2454. // });
  2455. this.commit('onWriteBLEConnectionValue', {
  2456. value: "4"
  2457. });
  2458. },
  2459. //向低功耗蓝牙设备特征值中写入二进制数据。注意:必须设备的特征值支持 write 才可以成功调用。
  2460. B_WriteBLECharacteristicValue(state, context) {
  2461. let {
  2462. value,
  2463. retryCount,
  2464. success,
  2465. getFail,
  2466. bSendHex,
  2467. } = context;
  2468. if (!value && value === '') {
  2469. uni.showToast({
  2470. title: "指令为空"
  2471. })
  2472. return;
  2473. }
  2474. let _sendData;
  2475. if (bSendHex) {
  2476. state.bRopeKeyTwo = 0;
  2477. state.bRopeKeyOne = 0;
  2478. //如果是发送16进制
  2479. state.bListenerHexUpdate = true;
  2480. //重置原 update
  2481. state.bListenerUpdate = false;
  2482. let typedArray = new Uint8Array(value.match(/[\da-f]{2}/gi).map(function(h) {
  2483. return parseInt(h, 16)
  2484. }))
  2485. _sendData = typedArray.buffer;
  2486. } else {
  2487. state.bListenerHexUpdate = false;
  2488. //记录一下指令
  2489. state.currentInstruction = value;
  2490. //V 获取版本,M 获取mac 地址
  2491. if (value == "V")
  2492. state.showToast = true;
  2493. if (value == "M") {
  2494. state.showToast = true;
  2495. state.bListenerMac = true;
  2496. }
  2497. if (value == "4") {
  2498. state.bListenerUpdate = false;
  2499. }
  2500. if (value == "3") {
  2501. if (state.bListenerUpdate) {
  2502. uni.showToast({
  2503. title: "原始数据已开启"
  2504. })
  2505. return;
  2506. }
  2507. state.bListenerUpdate = true;
  2508. }
  2509. if (value == "6") {
  2510. // state.bListenerJson = false;
  2511. state.bListenerAccArray = false;
  2512. }
  2513. if (value == "5") {
  2514. // if (state.bListenerJson) {
  2515. // uni.showToast({
  2516. // title: "步数数据已开启"
  2517. // })
  2518. // return;
  2519. // }
  2520. // state.bListenerJson = true;
  2521. if (state.bListenerAccArray) {
  2522. uni.showToast({
  2523. title: "加速计组数据已开启"
  2524. })
  2525. return;
  2526. }
  2527. state.bListenerAccArray = true;
  2528. }
  2529. _sendData = BLE.str2ab(value);
  2530. }
  2531. console.log("currentInstruction:", state.currentInstruction, value, state.bListenerUpdate, state
  2532. .bListenerMac,
  2533. state.bListenerHexUpdate);
  2534. console.log("state.deviceId:", state.deviceId, state.serviceId, state.writeCharacteristicId);
  2535. uni.writeBLECharacteristicValue({
  2536. deviceId: state.deviceId,
  2537. serviceId: state.serviceId,
  2538. // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
  2539. characteristicId: state.writeCharacteristicId,
  2540. // 这里的value是ArrayBuffer类型
  2541. value: _sendData,
  2542. success: (res) => {
  2543. console.log('writeBLECharacteristicValue success', res.errMsg, value,
  2544. retryCount);
  2545. if (success) {
  2546. success(res);
  2547. }
  2548. },
  2549. fail: (fail) => {
  2550. console.log(fail)
  2551. //重新写入
  2552. if (retryCount > 0) {
  2553. console.log("writeBLECharacteristicValue Rewrite ===================>" +
  2554. value + " == " + retryCount);
  2555. retryCount--;
  2556. setTimeout(() => {
  2557. this.commit("B_WriteBLECharacteristicValue", {
  2558. value,
  2559. retryCount,
  2560. success,
  2561. getFail
  2562. });
  2563. }, 300);
  2564. }
  2565. if (getFail) {
  2566. getFail(fail);
  2567. }
  2568. }
  2569. })
  2570. },
  2571. /**
  2572. * 断开蓝牙连接
  2573. */
  2574. B_CloseBLEConnection(state, context) {
  2575. let {
  2576. deviceId,
  2577. success = null
  2578. } = context;
  2579. uni.closeBLEConnection({
  2580. deviceId,
  2581. success: res => {
  2582. if (success)
  2583. success();
  2584. },
  2585. fail: (fail) => {
  2586. console.log("关闭蓝牙失败", fail);
  2587. }
  2588. });
  2589. },
  2590. //获取手机中蓝牙已匹配的设备
  2591. B_GetBondedDevices(state, context) {
  2592. // console.log("getBondedDevices ====>");
  2593. let {
  2594. success = null,
  2595. deviceId = null
  2596. } = context;
  2597. //Android
  2598. function android_bluetooth_list(deviceName, deviceId, count, callback) {
  2599. console.log("===》调用android_bluetooth_list count:", count);
  2600. var main = plus.android.runtimeMainActivity();
  2601. var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
  2602. var BAdapter = BluetoothAdapter.getDefaultAdapter();
  2603. var Context = plus.android.importClass("android.content.Context");
  2604. var lists = BAdapter.getBondedDevices();
  2605. plus.android.importClass(lists);
  2606. var len = lists.size();
  2607. // var BluetoothManager = plus.android.importClass("android.bluetooth.BluetoothManager");
  2608. // var BluetoothDevice = plus.android.importClass("android.bluetooth.BluetoothDevice");
  2609. // var ProfileType = plus.android.importClass("android.bluetooth.ProfileType");
  2610. // plus.android.importClass(BluetoothManager);
  2611. // plus.android.importClass(BluetoothDevice);
  2612. // plus.android.importClass(ProfileType);
  2613. // var UUID = plus.android.importClass("java.util.UUID");
  2614. // var uuid = UUID.fromString("0000FFF0-0000-1000-8000-00805F9B34FB");
  2615. // var gDevice = BAdapter.getRemoteDevice("C5:5C:19:04:00:30");
  2616. // plus.android.importClass(gDevice);
  2617. // var bluetoothSocket = gDevice.createInsecureRfcommSocketToServiceRecord(uuid);
  2618. // plus.android.importClass(bluetoothSocket);
  2619. // console.log("是否连接:",bluetoothSocket.isConnected());
  2620. // var deviceLists = BluetoothManager.getConnectedDevices();
  2621. // plus.android.importClass(deviceLists);
  2622. // console.log("deviceLists.len=" + deviceLists.size());
  2623. console.log("getBondedDevices.len=", len, "deviceId:", deviceId);
  2624. //测试start===》 如果没有配对的设备,重新获取
  2625. // count--;
  2626. // if(count >0){
  2627. // setTimeout(()=>{
  2628. // android_bluetooth_list("BGBox", deviceId, count, callback);
  2629. // },1000)
  2630. // return;
  2631. // }
  2632. //测试end
  2633. if (len == 0) {
  2634. //如果没有配对的设备,重新获取
  2635. count--;
  2636. if (count > 0) {
  2637. setTimeout(() => {
  2638. android_bluetooth_list("BGBox", deviceId, count, callback);
  2639. }, 2000)
  2640. } else {
  2641. if (callback)
  2642. callback(null);
  2643. }
  2644. } else {
  2645. var iterator = lists.iterator();
  2646. let temp = null;
  2647. plus.android.importClass(iterator);
  2648. while (iterator.hasNext()) {
  2649. var d = iterator.next();
  2650. plus.android.importClass(d);
  2651. // if (d.getName().indexOf(deviceName) > -1)
  2652. // console.log(d.getAddress(), deviceId);
  2653. if (deviceId == null && d.getName().indexOf(deviceName) > -1) {
  2654. let typeEnum = {
  2655. 0: 'Unknown',
  2656. 1: 'Classic',
  2657. 2: 'Le',
  2658. 3: 'Dual'
  2659. };
  2660. let bondStateEnum = {
  2661. 10: 'None',
  2662. 11: 'Bonding',
  2663. 12: 'Bonded'
  2664. };
  2665. temp = {
  2666. name: d.getName(),
  2667. address: d.getAddress(),
  2668. type: {
  2669. 'value': d.getType(),
  2670. 'name': typeEnum[d.getType()]
  2671. },
  2672. bondState: {
  2673. 'value': d.getBondState(),
  2674. 'name': bondStateEnum[d.getBondState()]
  2675. }
  2676. }
  2677. console.log("获取到设备,并且跳出:", temp);
  2678. break;
  2679. } else if (d.getAddress() == deviceId) {
  2680. // console.log(d.getName());
  2681. // console.log(d.getAddress());
  2682. // Classic 1
  2683. // Dual 3
  2684. // Le 2
  2685. // Unknown 0
  2686. // console.log(d.getType());
  2687. // Bonded 12
  2688. // Bonding 11 Indicates bonding (pairing) is in progress with the remote device.
  2689. // None 10
  2690. // console.log(d.getBondState());
  2691. let typeEnum = {
  2692. 0: 'Unknown',
  2693. 1: 'Classic',
  2694. 2: 'Le',
  2695. 3: 'Dual'
  2696. };
  2697. let bondStateEnum = {
  2698. 10: 'None',
  2699. 11: 'Bonding',
  2700. 12: 'Bonded'
  2701. };
  2702. temp = {
  2703. name: d.getName(),
  2704. address: d.getAddress(),
  2705. type: {
  2706. 'value': d.getType(),
  2707. 'name': typeEnum[d.getType()]
  2708. },
  2709. bondState: {
  2710. 'value': d.getBondState(),
  2711. 'name': bondStateEnum[d.getBondState()]
  2712. }
  2713. }
  2714. console.log("获取到设备,并且跳出:", temp);
  2715. break;
  2716. }
  2717. }
  2718. // return temp;
  2719. if (temp == null && count > 0) {
  2720. count--;
  2721. setTimeout(() => {
  2722. android_bluetooth_list("BGBox", deviceId, count, callback);
  2723. }, 2000)
  2724. } else {
  2725. if (callback)
  2726. callback(temp);
  2727. }
  2728. }
  2729. }
  2730. function ios_bluetooth_list(deviceName, callback) {
  2731. //原生操作 首先需要通过 uni.requireNativePlugin("ModuleName") 获取 module
  2732. var SLABluetoothModule = uni.requireNativePlugin("SLABluetoothUniPlugin-SLAModule")
  2733. if (SLABluetoothModule) {
  2734. SLABluetoothModule.getConnectionDevicesAsync({
  2735. serviceUUIDs: "FFF0"
  2736. }, (res) => {
  2737. console.log("***************getConnectionDevicesAsync:", JSON.stringify(res));
  2738. if (res.data) {
  2739. console.log("获取到对应的匹配设备!");
  2740. let typeEnum = {
  2741. 0: 'Unknown',
  2742. 1: 'Classic',
  2743. 2: 'Le',
  2744. 3: 'Dual'
  2745. };
  2746. let bondStateEnum = {
  2747. 10: 'None',
  2748. 11: 'Bonding',
  2749. 12: 'Bonded'
  2750. };
  2751. let temp = {
  2752. name: res.data[0].name,
  2753. address: res.data[0].identifier,
  2754. type: {
  2755. 'value': 2,
  2756. 'name': typeEnum[2]
  2757. },
  2758. bondState: {
  2759. 'value': 12,
  2760. 'name': bondStateEnum[12]
  2761. }
  2762. }
  2763. if (callback) {
  2764. callback({
  2765. "device": temp
  2766. });
  2767. }
  2768. } else {
  2769. console.log("匹配设备数据不存在!");
  2770. if (callback) {
  2771. callback({
  2772. "device": null
  2773. });
  2774. }
  2775. }
  2776. })
  2777. } else {
  2778. console.error("不存在SLABluetoothModule ios 插件!");
  2779. if (callback) {
  2780. callback({
  2781. "device": null
  2782. });
  2783. }
  2784. }
  2785. }
  2786. let device = null;
  2787. let _count = 3;
  2788. switch (plus.os.name) {
  2789. case "Android":
  2790. // Android平台: plus.android.*
  2791. android_bluetooth_list("BGBox", deviceId, _count, (data) => {
  2792. device = data;
  2793. console.log("android getBondedDevices 匹配的对象======>", device)
  2794. if (device != null) {
  2795. state.bPhoneMatched = true;
  2796. } else {
  2797. state.bPhoneMatched = false;
  2798. }
  2799. if (success) {
  2800. success(device);
  2801. }
  2802. });
  2803. break;
  2804. case "iOS":
  2805. // iOS平台: plus.ios.*
  2806. ios_bluetooth_list("BGBox", (res) => {
  2807. device = res.device
  2808. if (success) {
  2809. success(device);
  2810. }
  2811. console.log("ios getBondedDevices 匹配的对象======>", device)
  2812. if (device != null) {
  2813. state.bPhoneMatched = true;
  2814. } else {
  2815. state.bPhoneMatched = false;
  2816. }
  2817. });
  2818. break;
  2819. default:
  2820. // 其它平台
  2821. if (success) {
  2822. success(device);
  2823. }
  2824. break;
  2825. }
  2826. // if (success) {
  2827. // success(device);
  2828. // }
  2829. },
  2830. B_OpenBLESetting() {
  2831. function android_bluetooth_setting() {
  2832. var main = plus.android.runtimeMainActivity(); //获取activity
  2833. var Intent = plus.android.importClass('android.content.Intent');
  2834. var Settings = plus.android.importClass('android.provider.Settings');
  2835. var intent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS); //可设置表中所有Action字段
  2836. main.startActivity(intent);
  2837. }
  2838. function ios_bluetooth_setting() {
  2839. // var UIApplication = plus.ios.import("UIApplication");
  2840. // var application2 = UIApplication.sharedApplication();
  2841. // var NSURL2 = plus.ios.import("NSURL");
  2842. // var setting2 = NSURL2.URLWithString("app-settings:");
  2843. // application2.openURL(setting2);
  2844. // plus.ios.deleteObject(setting2);
  2845. // plus.ios.deleteObject(NSURL2);
  2846. // plus.ios.deleteObject(application2);
  2847. // plus.runtime.openURL({
  2848. // action: 'App-Prefs:root=Bluetooth'
  2849. // }, function(e) {
  2850. // console.log(JSON.stringify(e));
  2851. // });
  2852. plus.runtime.launchApplication({
  2853. action: 'App-Prefs:root=Bluetooth'
  2854. }, function(e) {
  2855. console.log(JSON.stringify(e));
  2856. });
  2857. }
  2858. let device = null;
  2859. switch (plus.os.name) {
  2860. case "Android":
  2861. // Android平台: plus.android.*
  2862. android_bluetooth_setting();
  2863. break;
  2864. case "iOS":
  2865. // iOS平台: plus.ios.*
  2866. ios_bluetooth_setting();
  2867. break;
  2868. default:
  2869. // 其它平台
  2870. break;
  2871. }
  2872. },
  2873. //获取versionCode状态,用于处理特定的信息显示
  2874. getVersionCode(state) {
  2875. let self = this;
  2876. reqUtil.requestData(config.URL.GETVERSIONCODE, {
  2877. code: state.versionCode
  2878. }).then(res => {
  2879. console.log('获取GETVERSIONCODE =====', res);
  2880. if (res.code == 0) {
  2881. state.versionCodeState = res.data;
  2882. }
  2883. },
  2884. e => {
  2885. console.log(e)
  2886. });
  2887. },
  2888. /**
  2889. * 任务其他操作
  2890. */
  2891. //获取关卡信息
  2892. getLevelList(state, callback) {
  2893. let self = this;
  2894. reqUtil
  2895. .requestData(config.URL.GETLEVELJUMPLIST, {})
  2896. .then(
  2897. res => {
  2898. if (res.code == 0) {
  2899. // console.log('GETLEVELJUMPLIST:' + JSON.stringify(res.data.singlePerson));
  2900. state.singlePersonList = res.data.singlePerson;
  2901. state.multiPersonList = res.data.multiPerson;
  2902. //获取到数据时候,重置actionJump
  2903. self.commit('resetActionJumpTask');
  2904. if (callback)
  2905. callback();
  2906. }
  2907. },
  2908. e => {
  2909. console.log(e);
  2910. }
  2911. );
  2912. },
  2913. /**
  2914. * 获取钱包信息
  2915. * @param {Object} state
  2916. * @param {Object} callback
  2917. */
  2918. getUserWallets(state, callback) {
  2919. reqUtil
  2920. .requestData(config.URL.USERGETWALLETINFO, {})
  2921. .then(
  2922. res => {
  2923. if (res.code == 0) {
  2924. console.log('USERGETWALLETINFO:' + JSON.stringify(res.data));
  2925. state.cGold = res.data.gold;
  2926. state.cDiamond = res.data.diamond;
  2927. if (callback)
  2928. callback();
  2929. }
  2930. },
  2931. e => {
  2932. console.log(e);
  2933. }
  2934. );
  2935. },
  2936. setGoldAndDiamond(state, context) {
  2937. let {
  2938. gold,
  2939. diamond
  2940. } = context;
  2941. state.cGold = gold;
  2942. state.cDiamond = diamond;
  2943. },
  2944. /**
  2945. * 抽屉和弹出框
  2946. */
  2947. hideDrawerById(state, context) {
  2948. // let { id } = context;
  2949. //personal-drawer
  2950. uni.getSubNVueById('personal-drawer').hide('slide-in-left', 200);
  2951. },
  2952. showDrawerById(state, context) {
  2953. // let { id } = context;
  2954. //personal-drawer
  2955. uni.getSubNVueById('personal-drawer').show('slide-in-left', 200);
  2956. },
  2957. showPopupById(state, context) {
  2958. let {
  2959. type,
  2960. item
  2961. } = context;
  2962. console.log(type, item);
  2963. switch (type) {
  2964. case 'levelReward':
  2965. uni.$emit('reward-popup', {
  2966. title: '奖励',
  2967. content: '',
  2968. type: type,
  2969. item: {
  2970. gold: item.rewardGold,
  2971. diamond: item.rewardDiamond,
  2972. honor: item.rewardHonor
  2973. },
  2974. operationItem: item
  2975. });
  2976. break;
  2977. case 'prompt':
  2978. // 向 popup 传递消息
  2979. uni.$emit('reward-popup', {
  2980. title: '奖励',
  2981. content: '',
  2982. type: type,
  2983. item: {
  2984. gold: item.rewardGold,
  2985. diamond: item.rewardDiamond,
  2986. honor: item.rewardHonor
  2987. },
  2988. operationItem: item
  2989. });
  2990. break;
  2991. case 'unlock':
  2992. // 向 popup 传递消息
  2993. uni.$emit('reward-popup', {
  2994. title: '解锁关卡',
  2995. content: '',
  2996. type: type,
  2997. item: {
  2998. consumeGold: item.consumeGold,
  2999. consumeDiamond: item.consumeDiamond
  3000. },
  3001. operationItem: item
  3002. });
  3003. break;
  3004. case 'signIn':
  3005. this.commit("onSendSignInPopup",context);
  3006. break;
  3007. case 'pkFinish':
  3008. // 向 popup 传递消息
  3009. uni.$emit('reward-popup', {
  3010. title: 'pk完成',
  3011. content: '',
  3012. type: type,
  3013. item: item,
  3014. operationItem: item
  3015. });
  3016. break;
  3017. default:
  3018. uni.showToast({
  3019. title: 'showPopup类型为空',
  3020. icon: 'none'
  3021. })
  3022. break;
  3023. }
  3024. // #ifdef APP-PLUS
  3025. //personal-popup
  3026. const subNVue = uni.getSubNVueById('personal-popup')
  3027. subNVue.show('zoom-out', 250)
  3028. // #endif
  3029. },
  3030. showGuideById(state, context) {
  3031. let {
  3032. type,
  3033. item
  3034. } = context;
  3035. uni.$emit('guide-popup', {
  3036. title: 'guide',
  3037. content: '定制guide',
  3038. type: type,
  3039. item: item,
  3040. operationItem: item
  3041. });
  3042. const subNVue = uni.getSubNVueById('personal-guide')
  3043. subNVue.show('fade-in', 250)
  3044. },
  3045. getSignInList(state, callback) {
  3046. reqUtil
  3047. .requestData(config.URL.GETSIGNINLIST, {})
  3048. .then(
  3049. res => {
  3050. if (res.code == 0) {
  3051. console.log('GETSIGNINLIST:' + JSON.stringify(res.data));
  3052. state.signInList = res.data.signInList;
  3053. state.isSignIn = res.data.isSignIn;
  3054. if (callback)
  3055. callback(res.data);
  3056. }
  3057. },
  3058. e => {
  3059. console.log(e);
  3060. }
  3061. );
  3062. },
  3063. onUserSignIn(state, callback) {
  3064. reqUtil
  3065. .requestData(config.URL.USERSIGNIN, {})
  3066. .then(
  3067. res => {
  3068. console.log('USERSIGNIN:' + JSON.stringify(res));
  3069. if (res.code == 0) {
  3070. state.cGold = res.data.userGold;
  3071. state.cDiamond = res.data.userDiamond;
  3072. uni.showToast({
  3073. title: '签到成功',
  3074. mask: true
  3075. })
  3076. //根据dayType 计算最近一个flag
  3077. for(let i=0;i<state.signInList.length;i++){
  3078. if(res.data.signIn.dayType == state.signInList[i].dayType){
  3079. state.signInList[i] = Object.assign({},state.signInList[i],res.data.signIn);
  3080. break;
  3081. }
  3082. }
  3083. state.isSignIn = true;
  3084. if (callback)
  3085. callback(res.data);
  3086. } else if (res.code == 901) {
  3087. uni.showToast({
  3088. title: '今天已签到',
  3089. mask: true
  3090. })
  3091. }
  3092. },
  3093. e => {
  3094. console.log(e);
  3095. }
  3096. );
  3097. },
  3098. onSendSignInPopup(state,context){
  3099. let {
  3100. type,
  3101. item
  3102. } = context;
  3103. let _reward = [{
  3104. name: 'gold',
  3105. width: 28,
  3106. height: 28,
  3107. url: '../../../static/common/sideBar/sGold.png',
  3108. selectedUrl: '../../../static/common/subNVue/sign/sign-grey-gold@2x.png',
  3109. explain: '',
  3110. value: 20,
  3111. isSelect: false
  3112. },
  3113. {
  3114. name: 'diamond',
  3115. width: 28,
  3116. height: 28,
  3117. url: '../../../static/common/sideBar/sDiamond.png',
  3118. selectedUrl: '../../../static/common/subNVue/sign/sign-grey-diamond@2x.png',
  3119. explain: '',
  3120. value: 20,
  3121. isSelect: false
  3122. }
  3123. ];
  3124. let list = state.signInList;
  3125. let lists = [];
  3126. for (let i = 0; i < list.length; i++) {
  3127. if (0 !== list[i].gold) {
  3128. lists.push(Object.assign({}, _reward[0], {
  3129. value: list[i].gold
  3130. }))
  3131. } else if (0 !== list[i].diamond) {
  3132. lists.push(Object.assign({}, _reward[1], {
  3133. value: list[i].diamond
  3134. }))
  3135. }
  3136. lists[i].isSelect = list[i].flag == 1?true:false;
  3137. }
  3138. // 向 popup 传递消息
  3139. uni.$emit('reward-popup', {
  3140. title: '每日签到',
  3141. content: '',
  3142. type: type,
  3143. lists: lists,
  3144. isSignIn:state.isSignIn
  3145. });
  3146. }
  3147. }
  3148. })
  3149. export default store