store.js 85 KB

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