BluWkm.js 28 KB

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