store.js 84 KB

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