store.js 78 KB

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