store.js 95 KB

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