store.js 75 KB

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