BlueMgr.js 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043
  1. // 安卓平台上,在调用 notifyBLECharacteristicValueChange 成功后立即调用 writeBLECharacteristicValue 接口,在部分机型上会发生 10008 系统错误
  2. var http = require("../utils/config.js");
  3. const cmd = {
  4. heartBeat: 'heart', // 心跳包
  5. unlock: 'openBike', // 开锁命令
  6. lock: 'lock', // 开锁命令
  7. bell: 'bellBike', // 关锁命令
  8. temporaryUnlockBike: 'temporaryUnlockBike', // 关锁命令
  9. temporaryLockBike: 'temporaryLockBike', // 关锁命令
  10. batteryUnlock: 'batteryUnlock', // 关锁命令
  11. batteryLock: 'batteryLock', // 关锁命令
  12. login: 'login', // 关锁命令
  13. status: 'status', // 关锁命令
  14. ack: 'ack', // 关锁命令
  15. }
  16. const errorCode = {
  17. no_connection: 10006, //失去连接
  18. no_service: 10004, //没有找到指定服务
  19. apdater_no_avilable: 10001, //当前蓝牙适配器不可用
  20. discovery_timeOut: 1100, //扫描失败
  21. connet_timeOut: 10003 //连接超时
  22. }
  23. const GetBluUrl = http.url+'bike/getKey'
  24. let util = require('../utils/bluUtil.js')
  25. let dataTransition = require('../utils/dataTransition.js')
  26. class BluetoothManager {
  27. constructor() {
  28. this._connectDeviceName = 'TBIT-WA209D'
  29. this._isFoundDevice = false
  30. this._deviceId = ''
  31. this._serviceId = ''
  32. this._bikeMainId = ''
  33. this._sequenceId = 10
  34. this._characteristicId = ''
  35. this._characteristicId_write = ''
  36. this._discovering = false
  37. this.discoveryTimeOut = 10 * 1000
  38. this.isConnecting = false
  39. this.isAuth = false
  40. this.connnectTimeOut = 5 * 1000 //连接超时时间
  41. this.hardwareCallbackTimeOut = 5 * 1000 //硬件回调超时时间
  42. this.adapterStateChangeCallBack = undefined
  43. this.onConnectionStateChange = undefined
  44. this.heartTimer = ''
  45. // 处理接受数据
  46. this._receiveLength = 0
  47. this._receiveData = ''
  48. // this.initialNotification()
  49. this.readyStopDiscovery = false //标记准备关闭扫描
  50. }
  51. /*******初始化各种回调**********/
  52. initialNotification() {
  53. console.log('initialNotification')
  54. // 监听蓝牙适配器状态改变
  55. wx.onBluetoothAdapterStateChange(
  56. res => {
  57. console.log('onBluetoothAdapterStateChange', res)
  58. if (res.available && !res.discovering) {
  59. // this._connectDeivece()
  60. }
  61. if (this.adapterStateChangeCallBack) {
  62. // if(!res.discovering && !this.isFinishDiscover){
  63. // this.isFinishDiscover = false
  64. this.adapterStateChangeCallBack(res)
  65. // }
  66. }
  67. }
  68. )
  69. // // 监听扫描到的设备
  70. wx.onBluetoothDeviceFound(
  71. res => {
  72. if (this._isFoundDevice)
  73. return
  74. if (res.devices[0].name)
  75. console.log('onFound:', res.devices[0].name, 'DeviceName', this._connectDeviceName)
  76. for (var i = 0; i < res.devices.length; i++) {
  77. const device = res.devices[i]
  78. if (!this._isFoundDevice && device.name && device.name == this._connectDeviceName) {
  79. // 获取车辆中控编号
  80. let machineNO = util.encrypt(util.ab2hex(device.advertisData).slice(4, 13));
  81. if (machineNO == this._bikeMainId) {
  82. console.log('-------found ---', device.name, machineNO)
  83. this._isFoundDevice = true
  84. this._deviceId = device.deviceId
  85. if (this.deviceFoundBlock) {
  86. this.deviceFoundBlock(device.deviceId)
  87. }
  88. return
  89. }
  90. }
  91. }
  92. }
  93. )
  94. // 监听蓝牙连接状态
  95. wx.onBLEConnectionStateChange(
  96. res => {
  97. console.log('onBLEConnectionStateChange', res, this._deviceId)
  98. this.isConnecting = res.connected
  99. if (res.deviceId == this._deviceId && res.connected == false) {
  100. console.log('onBLEConnectionStateChange fail', this._connectionFailBlock);
  101. if (this._connectionFailBlock) {
  102. // wx.showModal({
  103. // title: '提示',
  104. // content: '蓝牙连接超时',
  105. // showCancel: false
  106. // })
  107. wx.hideLoading()
  108. this._connectionFailBlock(res)
  109. this._connectionFailBlock = undefined
  110. }
  111. if (this.onConnectionStateChange) {
  112. this.onConnectionStateChange(res)
  113. }
  114. wx.closeBLEConnection({
  115. deviceId: this._deviceId,
  116. success: function (res) {
  117. console.log('closeBLEConnection', res)
  118. },
  119. })
  120. } else if (res.deviceId == this._deviceId && res.connected) {
  121. // 按需求决定是否重新获取服务,获取特征值通道
  122. //console.log('onBLEConnectionStateChange : connect succes ',res)
  123. }
  124. }
  125. )
  126. // 监听特征值变化
  127. wx.onBLECharacteristicValueChange(
  128. characteristic => {
  129. // console.log('onBLECharacteristicValueChange', characteristic)
  130. if (characteristic.value) {
  131. let res = characteristic.value
  132. let resData = util.ab2hex(res.value);
  133. if (this._receiveLength == 0) {
  134. this._receiveLength = parseInt(resData.slice(8, 12), 16)
  135. }
  136. this._receiveData += resData
  137. if (this._receiveData.length === (this._receiveLength * 2 + 16)) {
  138. let _receiveData = this._receiveData
  139. console.log(_receiveData, '_receiveData')
  140. let flay = _receiveData.slice(0, 4)
  141. let crc16 = _receiveData.slice(12, 16);
  142. let systemState = _receiveData.slice(4, 6); //4c
  143. let sequenceId_16 = _receiveData.slice(6, 8); //0a
  144. let body = _receiveData.slice(16)
  145. let contentArr = util.addFlagBeforeArr(util.strAverage2Arr(body, 2));
  146. //校检数据
  147. if (parseInt(dataTransition.getCRC16(contentArr), 16) == parseInt(crc16, 16)) {
  148. let value = util.hexStringToArrayBuffer(`aa12${systemState}${sequenceId_16}00000000`);
  149. if (flay === 'aa10') {
  150. if (body.indexOf('aa10550b') > -1) {
  151. if (this.getRandomSuccessBlock) {
  152. this.getRandomSuccessBlock(body)
  153. this.getRandomSuccessBlock = undefined
  154. }
  155. }
  156. console.log('指令发送成功', body)
  157. } else if (flay === 'aa00') {
  158. } else if (flay === 'aa30') {
  159. console.log('校检错误')
  160. } else {
  161. this.writeBLECharacteristicValue(value)
  162. that.analysisBLEContent(body)
  163. }
  164. }
  165. // 返回ACK
  166. this._receiveLength = 0
  167. this._receiveData = ''
  168. }
  169. }
  170. }
  171. )
  172. }
  173. //解析蓝牙发送内容
  174. analysisBLEContent(content) {
  175. let that = this
  176. console.log('解析数据数据***************', content);
  177. if(content=='') return false;
  178. if (content.indexOf('0500020101') > -1) {
  179. this.isAuth = true
  180. if (that.authLoginSuccessBlock) {
  181. setTimeout(() => {
  182. that.authLoginSuccessBlock()
  183. that.authLoginSuccessBlock = undefined
  184. }, 50)
  185. }
  186. console.log('授权成功')
  187. } else if (content.indexOf('040085') > -1) {
  188. console.log('心跳包')
  189. } else if (content.indexOf('0300820100') > -1) {
  190. if (that.unlockSuccessBlock) {
  191. that.unlockSuccessBlock()
  192. that.unlockSuccessBlock = undefined
  193. console.log('开锁成功');
  194. }
  195. } else if (content.indexOf('0300840100') > -1) {
  196. if (that.bellSuccessBlock) {
  197. that.bellSuccessBlock()
  198. that.bellSuccessBlock = undefined
  199. console.log('响铃成功')
  200. }
  201. } else if (content.indexOf('0300810100') > -1) {
  202. if (that.lockSuccessBlock) {
  203. that.lockSuccessBlock()
  204. that.lockSuccessBlock = undefined
  205. console.log('关锁成功');
  206. }
  207. } else if (content.indexOf('0300850100') > -1) {
  208. that.batterySuccessBlock = undefined
  209. if (that.batterySuccessBlock) {
  210. that.batterySuccessBlock = undefined
  211. console.log('操作电池锁成功');
  212. }
  213. } else if (content.indexOf('04008524') > -1) {
  214. that.heartSuccessBlock = undefined
  215. if (that.heartSuccessBlock) {
  216. that.heartSuccessBlock = undefined
  217. console.log('心跳包成功');
  218. }
  219. } else if (content.indexOf('020100') > -1) {
  220. this.isAuth = false
  221. if (that.authLoginSuccessBlock) {
  222. that.authLoginSuccessBlock = undefined
  223. }
  224. console.log(授权失败)
  225. } else {
  226. wx.showToast({
  227. title: content === '0300810102' ? '运动中不能上锁!' : '蓝牙操作失败,请重试!',
  228. mask: true,
  229. icon: 'none',
  230. duration: 5000
  231. })
  232. if(content=='0300810102'){
  233. }
  234. }
  235. if (that.heartSuccessBlock) {
  236. that.heartSuccessBlock = undefined
  237. }
  238. clearInterval(this.heartTimer)
  239. that.heartBeat().then(res => {
  240. this.closeConnection()
  241. })
  242. }
  243. /*******初始化各种回调**********/
  244. /***********初始化接口***************/
  245. connectDeivece(bikeMainId) {
  246. let bike_id = bikeMainId
  247. // 初始化蓝牙
  248. if (bike_id == this._bikeMainId && this.isConnecting) {
  249. console.log('已连接')
  250. return this.getRandom()
  251. }
  252. this._bikeMainId = bike_id
  253. this.initialNotification()
  254. return this.openAdapter().then(res => {
  255. return this.startDiscovery()
  256. }).then(
  257. res => {
  258. console.log('startDiscovery---------')
  259. this._discovering = true
  260. // 等待发现设备
  261. return this.waitForDeviceFound()
  262. },
  263. reject => {
  264. console.log(reject)
  265. }
  266. ).then(
  267. res => {
  268. console.log('stopDiscovery---------')
  269. this.readyStopDiscovery = true
  270. //关闭扫描
  271. return this.stopDiscovery()
  272. }
  273. ).then(
  274. res => {
  275. this.readyStopDiscovery = false
  276. this._discovering = false
  277. console.log('createConnection---------', res)
  278. //开始连接设备
  279. return this.createConnection(this._deviceId)
  280. }
  281. ).then(
  282. res => {
  283. console.log('getServices---------', res)
  284. // 获取服务
  285. return this.getServices(this._deviceId)
  286. }
  287. ).then(
  288. res => {
  289. console.log('getCharacteristics---------', res)
  290. // 获取特征值
  291. return this.getCharacteristics(this._deviceId, this._serviceId)
  292. }
  293. ).then(
  294. res => {
  295. console.log('openNotifyChsValueChange---------', res)
  296. // 开启notify通道
  297. console.log(this._deviceId, '=>', this._serviceId, '<++', this._characteristicId)
  298. return this.openNotifyChsValueChange(this._deviceId, this._serviceId, this._characteristicId)
  299. }
  300. ).then(
  301. res => {
  302. return this.onBLECharacteristicValueChange()
  303. }
  304. ).then(res => {
  305. return this.getSecretKey()
  306. }).then(res => {
  307. return this.bluetoothAuthLogin(res)
  308. })
  309. }
  310. // 监听特征值变化
  311. onBLECharacteristicValueChange() {
  312. let that = this
  313. wx.onBLECharacteristicValueChange(
  314. characteristic => {
  315. console.log('onBLECharacteristicValueChange', characteristic)
  316. if (characteristic.value) {
  317. let res = characteristic.value
  318. let resData = util.ab2hex(res);
  319. if (this._receiveLength == 0) {
  320. this._receiveLength = parseInt(resData.slice(8, 12), 16)
  321. }
  322. this._receiveData += resData
  323. if (this._receiveData.length === (this._receiveLength * 2 + 16)) {
  324. let _receiveData = this._receiveData
  325. console.log(_receiveData)
  326. let flay = _receiveData.slice(0, 4)
  327. let crc16 = _receiveData.slice(12, 16);
  328. let systemState = _receiveData.slice(4, 6); //4c
  329. let sequenceId_16 = _receiveData.slice(6, 8); //0a
  330. let dcArr = [];
  331. let body = _receiveData.slice(16)
  332. let contentArr = util.addFlagBeforeArr(util.strAverage2Arr(body, 2));
  333. //校检数据
  334. if (parseInt(dataTransition.getCRC16(contentArr), 16) == parseInt(crc16, 16)) {
  335. let response = util.hexStringToArrayBuffer(`aa12${systemState}${sequenceId_16}00000000`);
  336. if (flay === 'aa10') {
  337. console.log(this.getRandomSuccessBlock, 'getRandomSuccessBlock')
  338. if (this.getRandomSuccessBlock) {
  339. this.getRandomSuccessBlock(body)
  340. this.getRandomSuccessBlock = undefined
  341. }
  342. console.log('指令发送成功', body)
  343. } else if (flay === 'aa00') {
  344. } else if (flay === 'aa30') {
  345. console.log('CRC校验失败', body);
  346. } else {
  347. //响应数据
  348. that.writeBLECharacteristicValue(response, undefined)
  349. that.analysisBLEContent(body)
  350. }
  351. }
  352. this._receiveLength = 0
  353. this._receiveData = ''
  354. }
  355. }
  356. }
  357. )
  358. }
  359. //蓝牙认证
  360. bluetoothAuthLogin(key) {
  361. return new Promise(
  362. (resolve, reject) => {
  363. console.log('---auth---')
  364. this.sendCommand(cmd.login, {
  365. key: key
  366. }, reject);
  367. this.authLoginSuccessBlock = resolve
  368. // resolve()
  369. setTimeout(
  370. () => {
  371. console.log('---认证-超时回调ing--', this.authLoginSuccessBlock)
  372. if (this.authLoginSuccessBlock) {
  373. console.log('---认证-超时了--')
  374. this.authLoginSuccessBlock = undefined
  375. reject({
  376. errCode: errorCode.connet_timeOut,
  377. errMsg: '硬件校验超时'
  378. })
  379. }
  380. }, this.hardwareCallbackTimeOut
  381. )
  382. }
  383. )
  384. }
  385. //获取秘钥
  386. getSecretKey(box_no) {
  387. if (!box_no) box_no = this._bikeMainId
  388. return new Promise(function (res, rej) {
  389. let param = {
  390. box_no: box_no, //我公司是通过设备编号获取的密钥
  391. };
  392. console.log('获取蓝牙密钥')
  393. wx.request({
  394. url: GetBluUrl,
  395. data: param,
  396. header:{
  397. 'Authorization': 'bearer ' + wx.getStorageSync('token'),
  398. 'content-type': 'application/x-www-form-urlencoded',
  399. },
  400. success: (resp) => {
  401. res(resp.data.key);
  402. console.log('获取蓝牙密钥')
  403. }
  404. })
  405. });
  406. }
  407. waitForDeviceFound() {
  408. return new Promise(
  409. (resolve, reject) => {
  410. this.deviceFoundBlock = resolve
  411. console.log('waitForDeviceFound ----')
  412. console.log(this._discovering, '<==>', !this._isFoundDevice)
  413. setTimeout(() => {
  414. console.log('waitForDeviceFound ++++', this._discovering, this._isFoundDevice)
  415. // 全局断了,_discovering 变为false(发心跳包失败,closeApater引起)
  416. console.log(this._discovering, '==>', !this._isFoundDevice)
  417. if (this._discovering && !this._isFoundDevice) {
  418. console.log('waitForDeviceFound 扫描超时00', 'isconnecting :', this.isConnecting)
  419. reject({
  420. errCode: errorCode.discovery_timeOut
  421. })
  422. }
  423. if (this._discovering) {
  424. this.stopDiscovery()
  425. }
  426. }, this.discoveryTimeOut);
  427. }
  428. )
  429. }
  430. disconnecDevice() {
  431. return this.closeConnection(this._deviceId).then(
  432. res => {
  433. return this.closeAdapter()
  434. }
  435. )
  436. }
  437. /***********初始化接口***************/
  438. /***********蓝牙处理*************/
  439. // 打开适配器
  440. openAdapter() {
  441. return new Promise(
  442. (resolve, reject) => {
  443. wx.openBluetoothAdapter({
  444. success: resolve,
  445. fail: reject
  446. })
  447. }
  448. )
  449. }
  450. // 关闭适配器
  451. closeAdapter() {
  452. this._isFoundDevice = false
  453. this._discovering = false
  454. this.isConnecting = false
  455. this.adapterStateChangeCallBack = undefined
  456. this.onConnectionStateChange = undefined
  457. return new Promise(
  458. (resolve, reject) => {
  459. this.isOpenAdpater = false
  460. this.isConnecting = false
  461. wx.closeBluetoothAdapter({
  462. success: resolve,
  463. fail: reject
  464. })
  465. }
  466. )
  467. }
  468. // 开启扫描
  469. startDiscovery() {
  470. return new Promise(
  471. (resolve, reject) => {
  472. wx.startBluetoothDevicesDiscovery({
  473. services: ['FEF6'],
  474. allowDuplicatesKey: true,
  475. success: resolve,
  476. fail: reject
  477. })
  478. }
  479. )
  480. }
  481. // 关闭扫描
  482. stopDiscovery() {
  483. this._isFoundDevice = false
  484. return new Promise(
  485. (resolve, reject) => {
  486. wx.stopBluetoothDevicesDiscovery({
  487. success: resolve,
  488. fail: reject
  489. })
  490. }
  491. )
  492. }
  493. // 创建连接
  494. createConnection(deviceId) {
  495. return new Promise(
  496. (resolve, reject) => {
  497. this._connectionFailBlock = undefined
  498. this._connectionFailBlock = reject
  499. // this._needToToastConnectError = true
  500. wx.createBLEConnection({
  501. deviceId: deviceId,
  502. timeout: this.connnectTimeOut,
  503. success: res => {
  504. console.log('--------createConnection success', res)
  505. // 创建成果并不代表发指令成功,有可能连接连接创建成功了,但是发指令的时候连接中断了
  506. resolve(res)
  507. },
  508. fail: error => {
  509. console.log('--------createConnection fail', error)
  510. this._connectionFailBlock = undefined
  511. reject(error)
  512. }
  513. })
  514. }
  515. )
  516. }
  517. // 关闭连接
  518. closeConnection(deviceId) {
  519. return new Promise(
  520. (resolve, reject) => {
  521. wx.closeBLEConnection({
  522. deviceId: deviceId,
  523. success: resolve,
  524. fail: reject
  525. })
  526. }
  527. )
  528. }
  529. // 获取服务
  530. getServices(deviceId) {
  531. let that = this
  532. return new Promise(
  533. (resolve, reject) => {
  534. this._connectionFailBlock = undefined
  535. this._connectionFailBlock = reject
  536. wx.getBLEDeviceServices({
  537. deviceId: deviceId,
  538. success: res => {
  539. console.log('getServices success', res)
  540. if (res.errCode === 0) {
  541. res.services.forEach(function (value, index, array) {
  542. console.log("设备所有的UUId", value.uuid);
  543. if (value.uuid.indexOf(that._serviceId) > -1) { //找到serviceId包含FEF6的服务
  544. that._serviceId = array[index].uuid;
  545. // resolve(serviceId)
  546. }
  547. })
  548. }
  549. resolve(res)
  550. },
  551. fail: error => {
  552. console.log('getServices fail', error)
  553. reject(error)
  554. }
  555. })
  556. }
  557. )
  558. }
  559. // 获取特征值
  560. getCharacteristics(deviceId, serviceId) {
  561. let that = this
  562. return new Promise(
  563. (resolve, reject) => {
  564. this._connectionFailBlock = undefined
  565. this._connectionFailBlock = reject
  566. wx.getBLEDeviceCharacteristics({
  567. deviceId: deviceId,
  568. serviceId: serviceId,
  569. success: res => {
  570. console.log('getCharacteristics success', res)
  571. for (let i = 0; i < res.characteristics.length; i++) {
  572. if (res.characteristics[i].properties.notify && !res.characteristics[i].properties.write)
  573. that._characteristicId = res.characteristics[i].uuid; //读的uuid
  574. if (res.characteristics[i].properties.write)
  575. that._characteristicId_write = res.characteristics[i].uuid; //写的uuid
  576. }
  577. resolve(res)
  578. },
  579. fail: error => {
  580. console.log('getCharacteristics fail', error)
  581. reject(error)
  582. }
  583. })
  584. }
  585. )
  586. }
  587. // 开启notify功能,订阅特征值
  588. openNotifyChsValueChange(deviceId, serviceId, characteristicId) {
  589. let that = this
  590. return new Promise(
  591. (resolve, reject) => {
  592. this._connectionFailBlock = undefined
  593. this._connectionFailBlock = reject
  594. wx.notifyBLECharacteristicValueChange({
  595. deviceId: deviceId,
  596. serviceId: serviceId,
  597. characteristicId: characteristicId,
  598. state: true,
  599. success: res => {
  600. console.log('openNotifyChsValueChange success', res)
  601. resolve(res)
  602. },
  603. fail: error => {
  604. console.log('openNotifyChsValueChange fail', error)
  605. reject(error)
  606. }
  607. })
  608. }
  609. )
  610. }
  611. /***********蓝牙处理*************/
  612. /*********action**********/
  613. //获取随机数
  614. getRandom() {
  615. return new Promise(
  616. (resolve, reject) => {
  617. console.log('---getRandom---')
  618. resolve(true)
  619. // this.sendCommand(cmd.status, undefined, reject);
  620. // this.getRandomSuccessBlock = resolve
  621. // setTimeout(
  622. // () => {
  623. // console.log('---getRandom-超时回调ing--')
  624. // if (this.getRandomSuccessBlock) {
  625. // console.log('---getRandom-超时了--')
  626. // this.getRandomSuccessBlock = undefined
  627. // this.isConnecting = false
  628. // reject({
  629. // errMsg: '硬件校验超时'
  630. // })
  631. // }
  632. // }, this.hardwareCallbackTimeOut
  633. // )
  634. }
  635. )
  636. }
  637. bellBike() {
  638. return new Promise(
  639. (resolve, reject) => {
  640. // this.sendCommand(0x11, this.randomArray);
  641. this.bellSuccessBlock = resolve
  642. this.sendCommand(cmd.bell, '', reject);
  643. wx.showToast({
  644. title: '找车成功',
  645. icon: 'none'
  646. })
  647. setTimeout(
  648. () => {
  649. console.log('---bellBike-超时回调')
  650. if (this.bellSuccessBlock) {
  651. this.bellSuccessBlock = undefined
  652. console.log('---bellBike-超时了--')
  653. this.isConnecting = false
  654. reject({
  655. errCode: errorCode.connet_timeOut,
  656. errMsg: '寻铃超时'
  657. })
  658. }
  659. }, this.hardwareCallbackTimeOut
  660. )
  661. }
  662. )
  663. }
  664. //开锁
  665. unlockBike() {
  666. return new Promise(
  667. (resolve, reject) => {
  668. this.unlockSuccessBlock = resolve
  669. this.sendCommand(cmd.unlock, '', reject);
  670. setTimeout(
  671. () => {
  672. console.log('---unlockBike-超时回调')
  673. if (this.unlockSuccessBlock) {
  674. this.unlockSuccessBlock = undefined
  675. console.log('---unlockBike-超时了--')
  676. this.isConnecting = false
  677. reject({
  678. errCode: errorCode.connet_timeOut,
  679. errMsg: '开启电门超时'
  680. })
  681. }
  682. }, this.hardwareCallbackTimeOut
  683. )
  684. }
  685. )
  686. }
  687. //发送关锁指令
  688. lockBike() {
  689. return new Promise(
  690. (resolve, reject) => {
  691. console.log('---lockBike---')
  692. this.lockSuccessBlock = resolve
  693. this.sendCommand(cmd.lock, undefined, reject);
  694. setTimeout(
  695. () => {
  696. console.log('---lockBike-超时回调')
  697. // 硬件回调后 会把 lockSuccessBlock 清空,n秒后还没清空,就当指令发送失败
  698. if (this.lockSuccessBlock) {
  699. console.log('---lockBike-超时了--')
  700. this.isConnecting = false
  701. this.lockSuccessBlock = undefined
  702. reject({
  703. errCode: errorCode.connet_timeOut,
  704. errMsg: '关闭电门超时'
  705. })
  706. }
  707. }, this.hardwareCallbackTimeOut
  708. )
  709. }
  710. )
  711. }
  712. temporaryUnlockBike() {
  713. return new Promise(
  714. (resolve, reject) => {
  715. this.temporaryUnlockSuccessBlock = resolve
  716. this.sendCommand(cmd.temporaryUnlockBike, '', reject);
  717. setTimeout(
  718. () => {
  719. console.log('---unlockBike-超时回调')
  720. if (this.temporaryUnlockSuccessBlock) {
  721. this.temporaryUnlockSuccessBlock = undefined
  722. console.log('---unlockBike-超时了--')
  723. this.isConnecting = false
  724. reject({
  725. errCode: errorCode.connet_timeOut,
  726. errMsg: '开启电门超时'
  727. })
  728. }
  729. }, this.hardwareCallbackTimeOut
  730. )
  731. }
  732. )
  733. }
  734. //发送关锁指令
  735. temporaryLockBike() {
  736. return new Promise(
  737. (resolve, reject) => {
  738. console.log('---lockBike---')
  739. this.temporaryLockSuccessBlock = resolve
  740. this.sendCommand(cmd.temporaryLockBike, undefined, reject);
  741. setTimeout(
  742. () => {
  743. console.log('---lockBike-超时回调')
  744. // 硬件回调后 会把 lockSuccessBlock 清空,n秒后还没清空,就当指令发送失败
  745. if (this.temporaryLockSuccessBlock) {
  746. console.log('---lockBike-超时了--')
  747. this.isConnecting = false
  748. this.temporaryLockSuccessBlock = undefined
  749. reject({
  750. errCode: errorCode.connet_timeOut,
  751. errMsg: '关闭电门超时'
  752. })
  753. }
  754. }, this.hardwareCallbackTimeOut
  755. )
  756. }
  757. )
  758. }
  759. batteryUnlockBike() {
  760. return new Promise(
  761. (resolve, reject) => {
  762. this.batterySuccessBlock = resolve
  763. this.sendCommand(cmd.batteryUnlock, '', reject);
  764. setTimeout(
  765. () => {
  766. console.log('---batteryUnlockBike-超时回调')
  767. if (this.batterySuccessBlock) {
  768. this.batterySuccessBlock = undefined
  769. console.log('---batteryUnlockBike-超时了--')
  770. this.isConnecting = false
  771. reject({
  772. errCode: errorCode.connet_timeOut,
  773. errMsg: '开启电池锁超时'
  774. })
  775. }
  776. }, this.hardwareCallbackTimeOut
  777. )
  778. }
  779. )
  780. }
  781. batteryLockBike() {
  782. return new Promise(
  783. (resolve, reject) => {
  784. this.batterySuccessBlock = resolve
  785. this.sendCommand(cmd.batteryLock, '', reject);
  786. setTimeout(
  787. () => {
  788. console.log('---batteryLockBike-超时回调')
  789. if (this.batterySuccessBlock) {
  790. this.batterySuccessBlock = undefined
  791. console.log('---batteryLockBike-超时了--')
  792. this.isConnecting = false
  793. reject({
  794. errCode: errorCode.connet_timeOut,
  795. errMsg: '关启电池锁超时'
  796. })
  797. }
  798. }, this.hardwareCallbackTimeOut
  799. )
  800. }
  801. )
  802. }
  803. // 发送心跳包
  804. heartBeat() {
  805. let that = this
  806. return new Promise(
  807. (resolve, reject) => {
  808. that.heartSuccessBlock = resolve
  809. that.heartTimer = setTimeout(
  810. () => {
  811. if (that.heartSuccessBlock) {
  812. that.heartSuccessBlock = undefined
  813. reject({
  814. errCode: errorCode.connet_timeOut,
  815. errMsg: '超时'
  816. })
  817. }
  818. }, 30 * 1000
  819. )
  820. }
  821. )
  822. }
  823. /*********action**********/
  824. /*******util*********/
  825. //发送指令
  826. sendCommand(commandCode, dataArray, reject) {
  827. let data = this.generateCommandData(commandCode, dataArray);
  828. this._connectionFailBlock = undefined
  829. this._connectionFailBlock = reject
  830. var dataLen = Math.ceil(data.length / 40);
  831. console.log(dataLen, 'datalen')
  832. if (dataLen > 1) { //3
  833. for (let i = 0; i < data.length; i += 40) {
  834. let value = util.hexStringToArrayBuffer(data.slice(i, i + 40));
  835. console.log("分包发送的数据", data.slice(i, i + 40))
  836. //使用了重发机制,在此不做定时处理
  837. this.writeBLECharacteristicValue(value, reject);
  838. }
  839. } else {
  840. let value = util.hexStringToArrayBuffer(data);
  841. this.writeBLECharacteristicValue(value, reject);
  842. }
  843. }
  844. //发送数据
  845. writeBLECharacteristicValue(data, reject) {
  846. console.log(this._deviceId, this._serviceId, this._characteristicId_write, '发送参数')
  847. wx.writeBLECharacteristicValue({
  848. deviceId: this._deviceId,
  849. serviceId: this._serviceId,
  850. characteristicId: this._characteristicId_write,
  851. value: data,
  852. success: res => {
  853. console.log('writeBLECharacteristicValue success', res)
  854. },
  855. fail: err => {
  856. console.log('writeBLECharacteristicValue fail', err, this._deviceId, this._serviceId, this._characteristicId)
  857. // if(){
  858. this.isConnecting = false;
  859. // }
  860. reject(err)
  861. this.closeConnection(this._deviceId)
  862. }
  863. })
  864. }
  865. /**
  866. * 根据指令码生成指令帧数据
  867. * commandCode --> 指令码
  868. * array --> 额为携带的数据
  869. */
  870. generateCommandData(commandCode, array) {
  871. let sequenceId_16 = dataTransition.getSequenceId(this._sequenceId);
  872. this._sequenceId++;
  873. let sendData = '';
  874. switch (commandCode) {
  875. case cmd.unlock:
  876. sendData = '03 00 02 01 00';
  877. break
  878. case cmd.lock:
  879. sendData = '03 00 01 01 01';
  880. break;
  881. case cmd.bell:
  882. sendData = '03 00 04 01 01';
  883. break;
  884. case cmd.batteryUnlock:
  885. sendData = '03 00 05 01 01';
  886. break;
  887. case cmd.batteryLock:
  888. sendData = '03 00 05 01 00';
  889. break;
  890. case cmd.temporaryUnlockBike:
  891. sendData = '03 00 02 01 00 07 01 01';
  892. break
  893. case cmd.temporaryLockBike:
  894. sendData = '03 00 07 01 08';
  895. break;
  896. case cmd.login:
  897. let secretKey = array.key.toString().trim().toLowerCase();
  898. let c = secretKey.toString().replace(/\s+/g, "");
  899. let cLength = dataTransition.getSecretKeyLength(c);
  900. //发送内容
  901. let send = `02 00 01 ${cLength}`; //02 连接命令 01连接请求 cLength秘钥长度。
  902. sendData = `${send} ${secretKey}`;
  903. console.log(sendData, 'sendValue')
  904. break;
  905. case cmd.status:
  906. sendData = '04 00 0b 01 00'
  907. break
  908. case cmd.ack:
  909. sendData = array.data
  910. break;
  911. }
  912. let header = dataTransition.header(sendData, 0, '00', sequenceId_16);
  913. if (commandCode == 'responseAck') {
  914. header = ''
  915. }
  916. let data = header + sendData.replace(/\s+/g, "");
  917. console.log(`发送${commandCode}指令`, data);
  918. return data;
  919. }
  920. /*******util*********/
  921. }
  922. // export {
  923. // BluetoothManager
  924. // }
  925. module.exports = {
  926. BluetoothManager: BluetoothManager,
  927. BtErrorCode: errorCode
  928. }