store.js 85 KB

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