store.js 102 KB

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