store.js 75 KB

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