store.js 76 KB

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