store.js 86 KB

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