store.js 84 KB

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