store.js 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001
  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. },
  2269. /**
  2270. * 关闭跳绳模式
  2271. */
  2272. B_CloseRopeSkipping() {
  2273. this.commit('onWriteBLEConnectionValue', {
  2274. value: "5B210100FF5D",
  2275. bSendHex: true,
  2276. bOpen: false
  2277. });
  2278. },
  2279. //向低功耗蓝牙设备特征值中写入二进制数据。注意:必须设备的特征值支持 write 才可以成功调用。
  2280. B_WriteBLECharacteristicValue(state, context) {
  2281. let {
  2282. value,
  2283. retryCount,
  2284. success,
  2285. getFail,
  2286. bSendHex,
  2287. } = context;
  2288. if (!value && value === '') {
  2289. uni.showToast({
  2290. title: "指令为空"
  2291. })
  2292. return;
  2293. }
  2294. let _sendData;
  2295. if (bSendHex) {
  2296. state.bRopeKeyTwo = 0;
  2297. state.bRopeKeyOne = 0;
  2298. //如果是发送16进制
  2299. state.bListenerHexUpdate = true;
  2300. //重置原 update
  2301. state.bListenerUpdate = false;
  2302. let typedArray = new Uint8Array(value.match(/[\da-f]{2}/gi).map(function(h) {
  2303. return parseInt(h, 16)
  2304. }))
  2305. _sendData = typedArray.buffer;
  2306. } else {
  2307. state.bListenerHexUpdate = false;
  2308. //记录一下指令
  2309. state.currentInstruction = value;
  2310. //V 获取版本,M 获取mac 地址
  2311. if (value == "V")
  2312. state.showToast = true;
  2313. if (value == "M") {
  2314. state.showToast = true;
  2315. state.bListenerMac = true;
  2316. }
  2317. if (value == "4") {
  2318. state.bListenerUpdate = false;
  2319. }
  2320. if (value == "3") {
  2321. if (state.bListenerUpdate) {
  2322. uni.showToast({
  2323. title: "原始数据已开启"
  2324. })
  2325. return;
  2326. }
  2327. state.bListenerUpdate = true;
  2328. }
  2329. if (value == "6") {
  2330. // state.bListenerJson = false;
  2331. state.bListenerAccArray = false;
  2332. }
  2333. if (value == "5") {
  2334. // if (state.bListenerJson) {
  2335. // uni.showToast({
  2336. // title: "步数数据已开启"
  2337. // })
  2338. // return;
  2339. // }
  2340. // state.bListenerJson = true;
  2341. if (state.bListenerAccArray) {
  2342. uni.showToast({
  2343. title: "加速计组数据已开启"
  2344. })
  2345. return;
  2346. }
  2347. state.bListenerAccArray = true;
  2348. }
  2349. _sendData = BLE.str2ab(value);
  2350. }
  2351. console.log("currentInstruction:", state.currentInstruction, value, state.bListenerUpdate, state.bListenerMac,
  2352. state.bListenerHexUpdate);
  2353. console.log("state.deviceId:", state.deviceId, state.serviceId, state.writeCharacteristicId);
  2354. uni.writeBLECharacteristicValue({
  2355. deviceId: state.deviceId,
  2356. serviceId: state.serviceId,
  2357. // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
  2358. characteristicId: state.writeCharacteristicId,
  2359. // 这里的value是ArrayBuffer类型
  2360. value: _sendData,
  2361. success: (res) => {
  2362. console.log('writeBLECharacteristicValue success', res.errMsg, value, retryCount);
  2363. if (success) {
  2364. success(res);
  2365. }
  2366. },
  2367. fail: (fail) => {
  2368. console.log(fail)
  2369. //重新写入
  2370. if (retryCount > 0) {
  2371. console.log("writeBLECharacteristicValue Rewrite ===================>" + value + " == " + retryCount);
  2372. retryCount--;
  2373. setTimeout(() => {
  2374. this.commit("B_WriteBLECharacteristicValue", {
  2375. value,
  2376. retryCount,
  2377. success,
  2378. getFail
  2379. });
  2380. }, 300);
  2381. }
  2382. if (getFail) {
  2383. getFail(fail);
  2384. }
  2385. }
  2386. })
  2387. },
  2388. /**
  2389. * 断开蓝牙连接
  2390. */
  2391. B_CloseBLEConnection(state, context) {
  2392. let {
  2393. deviceId,
  2394. success = null
  2395. } = context;
  2396. uni.closeBLEConnection({
  2397. deviceId,
  2398. success: res => {
  2399. if (success)
  2400. success();
  2401. },
  2402. fail: (fail) => {
  2403. console.log("关闭蓝牙失败", fail);
  2404. }
  2405. });
  2406. },
  2407. //获取手机中蓝牙已匹配的设备
  2408. B_GetBondedDevices(state, context) {
  2409. // console.log("getBondedDevices ====>");
  2410. let {
  2411. success = null,
  2412. deviceId = null
  2413. } = context;
  2414. //Android
  2415. function android_bluetooth_list(deviceName, deviceId, count, callback) {
  2416. console.log("===》调用android_bluetooth_list count:", count);
  2417. var main = plus.android.runtimeMainActivity();
  2418. var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
  2419. var BAdapter = BluetoothAdapter.getDefaultAdapter();
  2420. var Context = plus.android.importClass("android.content.Context");
  2421. var lists = BAdapter.getBondedDevices();
  2422. plus.android.importClass(lists);
  2423. var len = lists.size();
  2424. // var BluetoothManager = plus.android.importClass("android.bluetooth.BluetoothManager");
  2425. // var BluetoothDevice = plus.android.importClass("android.bluetooth.BluetoothDevice");
  2426. // var ProfileType = plus.android.importClass("android.bluetooth.ProfileType");
  2427. // plus.android.importClass(BluetoothManager);
  2428. // plus.android.importClass(BluetoothDevice);
  2429. // plus.android.importClass(ProfileType);
  2430. // var UUID = plus.android.importClass("java.util.UUID");
  2431. // var uuid = UUID.fromString("0000FFF0-0000-1000-8000-00805F9B34FB");
  2432. // var gDevice = BAdapter.getRemoteDevice("C5:5C:19:04:00:30");
  2433. // plus.android.importClass(gDevice);
  2434. // var bluetoothSocket = gDevice.createInsecureRfcommSocketToServiceRecord(uuid);
  2435. // plus.android.importClass(bluetoothSocket);
  2436. // console.log("是否连接:",bluetoothSocket.isConnected());
  2437. // var deviceLists = BluetoothManager.getConnectedDevices();
  2438. // plus.android.importClass(deviceLists);
  2439. // console.log("deviceLists.len=" + deviceLists.size());
  2440. console.log("getBondedDevices.len=", len, "deviceId:", deviceId);
  2441. //测试start===》 如果没有配对的设备,重新获取
  2442. // count--;
  2443. // if(count >0){
  2444. // setTimeout(()=>{
  2445. // android_bluetooth_list("BGBox", deviceId, count, callback);
  2446. // },1000)
  2447. // return;
  2448. // }
  2449. //测试end
  2450. if (len == 0) {
  2451. //如果没有配对的设备,重新获取
  2452. count--;
  2453. if (count > 0) {
  2454. setTimeout(() => {
  2455. android_bluetooth_list("BGBox", deviceId, count, callback);
  2456. }, 2000)
  2457. } else {
  2458. if (callback)
  2459. callback(null);
  2460. }
  2461. } else {
  2462. var iterator = lists.iterator();
  2463. let temp = null;
  2464. plus.android.importClass(iterator);
  2465. while (iterator.hasNext()) {
  2466. var d = iterator.next();
  2467. plus.android.importClass(d);
  2468. // if (d.getName().indexOf(deviceName) > -1)
  2469. // console.log(d.getAddress(), deviceId);
  2470. if (deviceId == null && d.getName().indexOf(deviceName) > -1) {
  2471. let typeEnum = {
  2472. 0: 'Unknown',
  2473. 1: 'Classic',
  2474. 2: 'Le',
  2475. 3: 'Dual'
  2476. };
  2477. let bondStateEnum = {
  2478. 10: 'None',
  2479. 11: 'Bonding',
  2480. 12: 'Bonded'
  2481. };
  2482. temp = {
  2483. name: d.getName(),
  2484. address: d.getAddress(),
  2485. type: {
  2486. 'value': d.getType(),
  2487. 'name': typeEnum[d.getType()]
  2488. },
  2489. bondState: {
  2490. 'value': d.getBondState(),
  2491. 'name': bondStateEnum[d.getBondState()]
  2492. }
  2493. }
  2494. console.log("获取到设备,并且跳出:", temp);
  2495. break;
  2496. } else if (d.getAddress() == deviceId) {
  2497. // console.log(d.getName());
  2498. // console.log(d.getAddress());
  2499. // Classic 1
  2500. // Dual 3
  2501. // Le 2
  2502. // Unknown 0
  2503. // console.log(d.getType());
  2504. // Bonded 12
  2505. // Bonding 11 Indicates bonding (pairing) is in progress with the remote device.
  2506. // None 10
  2507. // console.log(d.getBondState());
  2508. let typeEnum = {
  2509. 0: 'Unknown',
  2510. 1: 'Classic',
  2511. 2: 'Le',
  2512. 3: 'Dual'
  2513. };
  2514. let bondStateEnum = {
  2515. 10: 'None',
  2516. 11: 'Bonding',
  2517. 12: 'Bonded'
  2518. };
  2519. temp = {
  2520. name: d.getName(),
  2521. address: d.getAddress(),
  2522. type: {
  2523. 'value': d.getType(),
  2524. 'name': typeEnum[d.getType()]
  2525. },
  2526. bondState: {
  2527. 'value': d.getBondState(),
  2528. 'name': bondStateEnum[d.getBondState()]
  2529. }
  2530. }
  2531. console.log("获取到设备,并且跳出:", temp);
  2532. break;
  2533. }
  2534. }
  2535. // return temp;
  2536. if (temp == null && count > 0) {
  2537. count--;
  2538. setTimeout(() => {
  2539. android_bluetooth_list("BGBox", deviceId, count, callback);
  2540. }, 2000)
  2541. } else {
  2542. if (callback)
  2543. callback(temp);
  2544. }
  2545. }
  2546. }
  2547. function ios_bluetooth_list(deviceName, callback) {
  2548. //原生操作 首先需要通过 uni.requireNativePlugin("ModuleName") 获取 module
  2549. var SLABluetoothModule = uni.requireNativePlugin("SLABluetoothUniPlugin-SLAModule")
  2550. if (SLABluetoothModule) {
  2551. SLABluetoothModule.getConnectionDevicesAsync({
  2552. serviceUUIDs: "FFF0"
  2553. }, (res) => {
  2554. console.log("***************getConnectionDevicesAsync:", JSON.stringify(res));
  2555. if (res.data) {
  2556. console.log("获取到对应的匹配设备!");
  2557. let typeEnum = {
  2558. 0: 'Unknown',
  2559. 1: 'Classic',
  2560. 2: 'Le',
  2561. 3: 'Dual'
  2562. };
  2563. let bondStateEnum = {
  2564. 10: 'None',
  2565. 11: 'Bonding',
  2566. 12: 'Bonded'
  2567. };
  2568. let temp = {
  2569. name: res.data[0].name,
  2570. address: res.data[0].identifier,
  2571. type: {
  2572. 'value': 2,
  2573. 'name': typeEnum[2]
  2574. },
  2575. bondState: {
  2576. 'value': 12,
  2577. 'name': bondStateEnum[12]
  2578. }
  2579. }
  2580. if (callback) {
  2581. callback({
  2582. "device": temp
  2583. });
  2584. }
  2585. } else {
  2586. console.log("匹配设备数据不存在!");
  2587. if (callback) {
  2588. callback({
  2589. "device": null
  2590. });
  2591. }
  2592. }
  2593. })
  2594. } else {
  2595. console.error("不存在SLABluetoothModule ios 插件!");
  2596. if (callback) {
  2597. callback({
  2598. "device": null
  2599. });
  2600. }
  2601. }
  2602. }
  2603. let device = null;
  2604. let _count = 3;
  2605. switch (plus.os.name) {
  2606. case "Android":
  2607. // Android平台: plus.android.*
  2608. android_bluetooth_list("BGBox", deviceId, _count, (data) => {
  2609. device = data;
  2610. console.log("android getBondedDevices 匹配的对象======>", device)
  2611. if (device != null) {
  2612. state.bPhoneMatched = true;
  2613. } else {
  2614. state.bPhoneMatched = false;
  2615. }
  2616. if (success) {
  2617. success(device);
  2618. }
  2619. });
  2620. break;
  2621. case "iOS":
  2622. // iOS平台: plus.ios.*
  2623. ios_bluetooth_list("BGBox", (res) => {
  2624. device = res.device
  2625. if (success) {
  2626. success(device);
  2627. }
  2628. console.log("ios getBondedDevices 匹配的对象======>", device)
  2629. if (device != null) {
  2630. state.bPhoneMatched = true;
  2631. } else {
  2632. state.bPhoneMatched = false;
  2633. }
  2634. });
  2635. break;
  2636. default:
  2637. // 其它平台
  2638. if (success) {
  2639. success(device);
  2640. }
  2641. break;
  2642. }
  2643. // if (success) {
  2644. // success(device);
  2645. // }
  2646. },
  2647. B_OpenBLESetting() {
  2648. function android_bluetooth_setting() {
  2649. var main = plus.android.runtimeMainActivity(); //获取activity
  2650. var Intent = plus.android.importClass('android.content.Intent');
  2651. var Settings = plus.android.importClass('android.provider.Settings');
  2652. var intent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS); //可设置表中所有Action字段
  2653. main.startActivity(intent);
  2654. }
  2655. function ios_bluetooth_setting() {
  2656. // var UIApplication = plus.ios.import("UIApplication");
  2657. // var application2 = UIApplication.sharedApplication();
  2658. // var NSURL2 = plus.ios.import("NSURL");
  2659. // var setting2 = NSURL2.URLWithString("app-settings:");
  2660. // application2.openURL(setting2);
  2661. // plus.ios.deleteObject(setting2);
  2662. // plus.ios.deleteObject(NSURL2);
  2663. // plus.ios.deleteObject(application2);
  2664. // plus.runtime.openURL({
  2665. // action: 'App-Prefs:root=Bluetooth'
  2666. // }, function(e) {
  2667. // console.log(JSON.stringify(e));
  2668. // });
  2669. plus.runtime.launchApplication({
  2670. action: 'App-Prefs:root=Bluetooth'
  2671. }, function(e) {
  2672. console.log(JSON.stringify(e));
  2673. });
  2674. }
  2675. let device = null;
  2676. switch (plus.os.name) {
  2677. case "Android":
  2678. // Android平台: plus.android.*
  2679. android_bluetooth_setting();
  2680. break;
  2681. case "iOS":
  2682. // iOS平台: plus.ios.*
  2683. ios_bluetooth_setting();
  2684. break;
  2685. default:
  2686. // 其它平台
  2687. break;
  2688. }
  2689. },
  2690. //获取versionCode状态,用于处理特定的信息显示
  2691. getVersionCode(state) {
  2692. let self = this;
  2693. reqUtil.requestData(config.URL.GETVERSIONCODE, {
  2694. code: state.versionCode
  2695. }).then(res => {
  2696. console.log('获取GETVERSIONCODE =====', res);
  2697. if (res.code == 0) {
  2698. state.versionCodeState = res.data;
  2699. }
  2700. },
  2701. e => {
  2702. console.log(e)
  2703. });
  2704. },
  2705. }
  2706. })
  2707. export default store