BluWkm.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849
  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. let util = require('../utils/bluUtil.js')
  23. let dataTransition = require('../utils/dataTransition.js')
  24. class BluetoothManager {
  25. constructor() {
  26. this._connectDeviceName = 'shanxiango'
  27. this._isFoundDevice = false
  28. this._deviceId = ''
  29. this._serviceId = ''
  30. this._bikeMainId = ''
  31. this._mac='',
  32. this._sequenceId = 10
  33. this._characteristicId = ''
  34. this._characteristicId_write = ''
  35. this._discovering = false
  36. this.discoveryTimeOut = 10 * 1000
  37. this.isConnecting = false
  38. this.isAuth = false
  39. this.connnectTimeOut = 5 * 1000 //连接超时时间
  40. this.hardwareCallbackTimeOut = 5 * 1000 //硬件回调超时时间
  41. this.adapterStateChangeCallBack = undefined
  42. this.onConnectionStateChange = undefined
  43. this.heartTimer = ''
  44. // 处理接受数据
  45. this._receiveLength = 0
  46. this._receiveData = ''
  47. // this.initialNotification()
  48. this.readyStopDiscovery = false //标记准备关闭扫描
  49. }
  50. /*******初始化各种回调**********/
  51. initialNotification() {
  52. console.log('initialNotification')
  53. // this.getConnectedBluetoothDevices()
  54. // 监听蓝牙适配器状态改变
  55. wx.onBluetoothAdapterStateChange(
  56. res => {
  57. console.log('onBluetoothAdapterStateChange', res)
  58. if (this.adapterStateChangeCallBack) {
  59. this.adapterStateChangeCallBack(res)
  60. }
  61. if(res.available==false){
  62. this.isConnecting = false
  63. }
  64. }
  65. )
  66. // // 监听扫描到的设备
  67. wx.onBluetoothDeviceFound(
  68. res => {
  69. console.log('监听扫描到的设备')
  70. if (this._isFoundDevice){
  71. return
  72. }
  73. for (var i = 0; i < res.devices.length; i++) {
  74. const device = res.devices[i];
  75. var name = device.name
  76. if (name === 'shanxiango') {
  77. if (device.localName != name) return;
  78. if (name != this._connectDeviceName) return;
  79. let bf = device.advertisData.slice(2, 10);
  80. var abc = util.ab2hex(bf)
  81. let contentArr = util.strAverage2Arr(abc, 2)
  82. contentArr.reverse();
  83. var string = contentArr.join('').toUpperCase() //mac地址
  84. console.log(string,'Mead===>',res.devices[i],this._mac)
  85. if (!this._isFoundDevice && name == this._connectDeviceName) {
  86. // 获取车辆中控编号
  87. console.log(this._mac)
  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. if(box_no== wx.getStorageSync('box_no')) return;
  352. return new Promise(function (res, rej) {
  353. let param = {
  354. box_no: box_no, //我公司是通过设备编号获取的密钥
  355. };
  356. app.request('/blu/get-key',param,'GET').then(resp=>{
  357. that._mac = resp.data.key
  358. res(resp.data.key);
  359. wx.setStorageSync('box_no', box_no)
  360. })
  361. });
  362. }
  363. waitForDeviceFound() {
  364. return new Promise(
  365. (resolve, reject) => {
  366. this.deviceFoundBlock = resolve
  367. console.log('waitForDeviceFound ----')
  368. console.log(this._discovering, '<==>', !this._isFoundDevice)
  369. setTimeout(() => {
  370. console.log('waitForDeviceFound ++++', this._discovering, this._isFoundDevice)
  371. // 全局断了,_discovering 变为false(发心跳包失败,closeApater引起)
  372. console.log(this._discovering, '==>', !this._isFoundDevice)
  373. if (this._discovering && !this._isFoundDevice) {
  374. console.log('waitForDeviceFound 扫描超时00', 'isconnecting :', this.isConnecting)
  375. reject({
  376. errCode: errorCode.discovery_timeOut
  377. })
  378. }
  379. if (this._discovering) {
  380. this.stopDiscovery()
  381. }
  382. }, this.discoveryTimeOut);
  383. }
  384. )
  385. }
  386. disconnecDevice() {
  387. return this.closeConnection(this._deviceId).then(
  388. res => {
  389. return this.closeAdapter()
  390. }
  391. )
  392. }
  393. /***********初始化接口***************/
  394. /***********蓝牙处理*************/
  395. // 打开适配器
  396. openAdapter() {
  397. console.log('打开适配器')
  398. return new Promise(
  399. (resolve, reject) => {
  400. wx.openBluetoothAdapter({
  401. success: resolve,
  402. fail: reject
  403. })
  404. }
  405. )
  406. }
  407. // 关闭适配器
  408. closeAdapter() {
  409. console.log('关闭适配器')
  410. this._isFoundDevice = false
  411. this._discovering = false
  412. this.isConnecting = false
  413. this.adapterStateChangeCallBack = undefined
  414. this.onConnectionStateChange = undefined
  415. return new Promise(
  416. (resolve, reject) => {
  417. this.isOpenAdpater = false
  418. this.isConnecting = false
  419. wx.closeBluetoothAdapter({
  420. success: resolve,
  421. fail: reject
  422. })
  423. }
  424. )
  425. }
  426. // 开启扫描
  427. startDiscovery() {
  428. console.log('开启扫描')
  429. return new Promise(
  430. (resolve, reject) => {
  431. wx.startBluetoothDevicesDiscovery({
  432. services: ['FFF0'],
  433. allowDuplicatesKey: true,
  434. success: resolve,
  435. fail: reject
  436. })
  437. }
  438. )
  439. }
  440. // 关闭扫描
  441. stopDiscovery() {
  442. console.log('关闭扫描')
  443. this._isFoundDevice = false
  444. return new Promise(
  445. (resolve, reject) => {
  446. wx.stopBluetoothDevicesDiscovery({
  447. success: resolve,
  448. fail: reject
  449. })
  450. }
  451. )
  452. }
  453. // 创建连接
  454. createConnection(deviceId) {
  455. console.log('创建连接')
  456. return new Promise(
  457. (resolve, reject) => {
  458. this._connectionFailBlock = undefined
  459. this._connectionFailBlock = reject
  460. // this._needToToastConnectError = true
  461. console.log(deviceId)
  462. console.log(this.connnectTimeOut)
  463. wx.createBLEConnection({
  464. deviceId: deviceId,
  465. // timeout: this.connnectTimeOut,
  466. success: res => {
  467. console.log('--------createConnection success', res)
  468. // 创建成果并不代表发指令成功,有可能连接连接创建成功了,但是发指令的时候连接中断了
  469. resolve(res)
  470. },
  471. fail: error => {
  472. console.log('--------createConnection fail', error)
  473. this._connectionFailBlock = undefined
  474. reject(error)
  475. }
  476. })
  477. }
  478. )
  479. }
  480. // 关闭连接
  481. closeConnection(deviceId) {
  482. console.log('关闭连接')
  483. return new Promise(
  484. (resolve, reject) => {
  485. wx.closeBLEConnection({
  486. deviceId: deviceId,
  487. success: resolve,
  488. fail: reject
  489. })
  490. }
  491. )
  492. }
  493. // 获取服务
  494. getServices(deviceId) {
  495. console.log('获取服务')
  496. let that = this
  497. return new Promise(
  498. (resolve, reject) => {
  499. this._connectionFailBlock = undefined
  500. this._connectionFailBlock = reject
  501. wx.getBLEDeviceServices({
  502. deviceId: deviceId,
  503. success: res => {
  504. console.log('getServices success', res)
  505. if (res.errCode === 0) {
  506. res.services.forEach(function (value, index, array) {
  507. console.log("设备所有的UUId", value.uuid);
  508. if (value.uuid.indexOf(that._serviceId) > -1) { //找到serviceId包含FEF6的服务
  509. that._serviceId = array[index].uuid;
  510. // resolve(serviceId)
  511. }
  512. })
  513. }
  514. resolve(res)
  515. },
  516. fail: error => {
  517. console.log('getServices fail', error)
  518. reject(error)
  519. }
  520. })
  521. }
  522. )
  523. }
  524. // 获取特征值
  525. getCharacteristics(deviceId, serviceId) {
  526. console.log('获取特征值')
  527. let that = this
  528. return new Promise(
  529. (resolve, reject) => {
  530. this._connectionFailBlock = undefined
  531. this._connectionFailBlock = reject
  532. wx.getBLEDeviceCharacteristics({
  533. deviceId: deviceId,
  534. serviceId: serviceId,
  535. success: res => {
  536. console.log('getCharacteristics success', res)
  537. for (let i = 0; i < res.characteristics.length; i++) {
  538. if (res.characteristics[i].properties.notify && !res.characteristics[i].properties.write)
  539. that._characteristicId = res.characteristics[i].uuid; //读的uuid
  540. if (res.characteristics[i].properties.write)
  541. that._characteristicId_write = res.characteristics[i].uuid; //写的uuid
  542. }
  543. resolve(res)
  544. },
  545. fail: error => {
  546. console.log('getCharacteristics fail', error)
  547. reject(error)
  548. }
  549. })
  550. }
  551. )
  552. }
  553. // 开启notify功能,订阅特征值
  554. openNotifyChsValueChange(deviceId, serviceId, characteristicId) {
  555. let that = this
  556. return new Promise(
  557. (resolve, reject) => {
  558. this._connectionFailBlock = undefined
  559. this._connectionFailBlock = reject
  560. wx.notifyBLECharacteristicValueChange({
  561. deviceId: deviceId,
  562. serviceId: serviceId,
  563. characteristicId: characteristicId,
  564. state: true,
  565. success: res => {
  566. console.log('openNotifyChsValueChange success', res)
  567. resolve(res)
  568. },
  569. fail: error => {
  570. console.log('openNotifyChsValueChange fail', error)
  571. reject(error)
  572. }
  573. })
  574. }
  575. )
  576. }
  577. /***********蓝牙处理*************/
  578. /*********action**********/
  579. // //获取随机数
  580. // getRandom() {
  581. // return new Promise(
  582. // (resolve, reject) => {
  583. // console.log('---getRandom---')
  584. // // this.sendCommand(cmd.status, undefined, reject);
  585. // // this.unlockBike()
  586. // this.getRandomSuccessBlock = resolve
  587. // setTimeout(
  588. // () => {
  589. // console.log('---getRandom-超时回调ing--', )
  590. // if (this.getRandomSuccessBlock) {
  591. // console.log('---getRandom-超时了--')
  592. // this.getRandomSuccessBlock = undefined
  593. // reject({
  594. // errMsg: '硬件校验超时'
  595. // })
  596. // }
  597. // }, this.hardwareCallbackTimeOut
  598. // )
  599. // }
  600. // )
  601. // }
  602. // bellBike() {
  603. // return new Promise(
  604. // (resolve, reject) => {
  605. // // this.sendCommand(0x11, this.randomArray);
  606. // this.bellSuccessBlock = resolve
  607. // // this.sendCommand(cmd.bell, '', reject);
  608. // setTimeout(
  609. // () => {
  610. // console.log('---bellBike-超时回调')
  611. // if (this.bellSuccessBlock) {
  612. // this.bellSuccessBlock = undefined
  613. // console.log('---bellBike-超时了--')
  614. // reject({
  615. // errCode: errorCode.connet_timeOut,
  616. // errMsg: '寻铃超时'
  617. // })
  618. // }
  619. // }, this.hardwareCallbackTimeOut
  620. // )
  621. // }
  622. // )
  623. // }
  624. //开锁
  625. unlockBike() {
  626. var key2 = ['0x42', '0x44', '0x00', '0x01', '0x0A', '0x0A', '0x05', '0x05', '0x02', '0x01', '0x01']
  627. let value = util.CRC(key2)
  628. console.log(value)
  629. var value1 = '424400010A0A0505020101' + value
  630. console.log(value1)
  631. this.writeBLECharacteristicValue(util.hexStringToArrayBuffer(value1), '123')
  632. //播放语音
  633. var key5 = ['0x42', '0x44', '0x00', '0x01', '0x0A', '0x0A', '0x05', '0x05', '0x0A', '0x07', '0x01', '0x02', '0x00', '0x00', '0x00', '0x00', '0x00']
  634. let value2 = util.CRC(key5)
  635. var value3 = '424400010A0A05050A0701020000000000' + value2
  636. this.writeBLECharacteristicValue(util.hexStringToArrayBuffer(value3), '123')
  637. }
  638. //发送关锁指令
  639. lockBike() {
  640. var key2 = ['0x42', '0x44', '0x00', '0x01', '0x0A', '0x0A', '0x05', '0x05', '0x02', '0x01', '0x02']
  641. let value = util.CRC(key2)
  642. console.log(value)
  643. var value1 = '424400010A0A0505020102' + value
  644. console.log(value1)
  645. this.writeBLECharacteristicValue(util.hexStringToArrayBuffer(value1))
  646. //播放语音
  647. var key5 = ['0x42', '0x44', '0x00', '0x01', '0x0A', '0x0A', '0x05', '0x05', '0x0A', '0x07', '0x01', '0x01', '0x00', '0x00', '0x00', '0x00', '0x00']
  648. let value2 = util.CRC(key5)
  649. var value3 = '424400010A0A05050A0701010000000000' + value2
  650. this.writeBLECharacteristicValue(util.hexStringToArrayBuffer(value3))
  651. }
  652. play_voice() {
  653. var key5 = ['0x42', '0x44', '0x00', '0x01', '0x0A', '0x0A', '0x05', '0x05', '0x0A', '0x07', '0x01', '0x09', '0x00', '0x00', '0x00', '0x00', '0x00']
  654. let value = util.CRC(key5)
  655. console.log(value)
  656. var value1 = '424400010A0A05050A0701090000000000' + value
  657. console.log(value1)
  658. this.writeBLECharacteristicValue(util.hexStringToArrayBuffer(value1))
  659. }
  660. diankai() {
  661. var key3 = ['0x42', '0x44', '0x00', '0x01', '0x0A', '0x0A', '0x05', '0x05', '0x05', '0x01', '0x01']
  662. let value = util.CRC(key3)
  663. console.log(value)
  664. var value1 = '424400010A0A0505050101' + value
  665. console.log(value1)
  666. this.writeBLECharacteristicValue(util.hexStringToArrayBuffer(value1))
  667. }
  668. // 发送心跳包
  669. // heartBeat() {
  670. // console.log('发送心跳包')
  671. // let that = this
  672. // return new Promise(
  673. // (resolve, reject) => {
  674. // console.log(resolve)
  675. // console.log(reject)
  676. // that.heartSuccessBlock = resolve
  677. // that.heartTimer = setTimeout(
  678. // () => {
  679. // if (that.heartSuccessBlock) {
  680. // var key2 = ['0x42', '0x44', '0x00', '0x01', '0x0A', '0x0A', '0x05', '0x05', '0x01', '0x00']
  681. // let value = util.CRC(key2)
  682. // var value1 = '424400010A0A05050100' + value
  683. // // this.writeBLECharacteristicValue(util.hexStringToArrayBuffer(value1))
  684. // var key5 = ['0x42', '0x44', '0x00', '0x01', '0x0A', '0x0A', '0x05', '0x05', '0x0A', '0x07', '0x01', '0x01', '0x00', '0x00', '0x00', '0x00', '0x00']
  685. // let value2 = util.CRC(key5)
  686. // var value3 = '424400010A0A05050A0701010000000000' + value2
  687. // // this.writeBLECharacteristicValue(util.hexStringToArrayBuffer(value3))
  688. // that.heartSuccessBlock = undefined
  689. // reject({
  690. // errCode: errorCode.connet_timeOut,
  691. // errMsg: '超时'
  692. // })
  693. // }
  694. // }, 30 * 1000
  695. // )
  696. // }
  697. // )
  698. // }
  699. /*********action**********/
  700. /*******util*********/
  701. //发送指令
  702. // sendCommand(commandCode, dataArray, reject) {
  703. // let data = this.generateCommandData(commandCode, dataArray);
  704. // this._connectionFailBlock = undefined
  705. // this._connectionFailBlock = reject
  706. // var dataLen = Math.ceil(data.length / 40);
  707. // console.log(dataLen, 'datalen')
  708. // if (dataLen > 1) { //3
  709. // for (let i = 0; i < data.length; i += 40) {
  710. // let value = util.hexStringToArrayBuffer(data.slice(i, i + 40));
  711. // console.log("分包发送的数据", data.slice(i, i + 40))
  712. // //使用了重发机制,在此不做定时处理
  713. // // this.writeBLECharacteristicValue(value, reject);
  714. // }
  715. // } else {
  716. // let value = util.hexStringToArrayBuffer(data);
  717. // console.log(value)
  718. // // this.writeBLECharacteristicValue(value, reject);
  719. // }
  720. // }
  721. //发送数据
  722. writeBLECharacteristicValue(data, reject) {
  723. console.log(this._deviceId, this._serviceId, this._characteristicId_write, '发送参数')
  724. wx.writeBLECharacteristicValue({
  725. deviceId: this._deviceId,
  726. serviceId: this._serviceId,
  727. characteristicId: this._characteristicId_write,
  728. value: data,
  729. success: res => {
  730. console.log('writeBLECharacteristicValue success', res)
  731. },
  732. fail: err => {
  733. console.log('writeBLECharacteristicValue fail', err, this._deviceId, this._serviceId, this._characteristicId)
  734. // if(){
  735. this.isConnecting = false;
  736. // }
  737. reject(err)
  738. this.closeConnection(this._deviceId)
  739. }
  740. })
  741. }
  742. /**
  743. * 根据指令码生成指令帧数据
  744. * commandCode --> 指令码
  745. * array --> 额为携带的数据
  746. */
  747. // generateCommandData(commandCode, array) {
  748. // let sequenceId_16 = dataTransition.getSequenceId(this._sequenceId);
  749. // // this._sequenceId++;
  750. // let sendData = '';
  751. // console.log(commandCode)
  752. // // console.log(sequenceId_16)
  753. // switch (commandCode) {
  754. // case cmd.unlock:
  755. // sendData = '03 00 02 01 00';
  756. // break
  757. // case cmd.lock:
  758. // sendData = '03 00 01 01 01';
  759. // break;
  760. // case cmd.bell:
  761. // sendData = '03 00 04 01 01';
  762. // break;
  763. // case cmd.batteryUnlock:
  764. // sendData = '03 00 05 01 01';
  765. // break;
  766. // case cmd.batteryLock:
  767. // sendData = '03 00 05 01 00';
  768. // break;
  769. // case cmd.temporaryUnlockBike:
  770. // sendData = '03 00 02 01 00 07 01 01';
  771. // break
  772. // case cmd.temporaryLockBike:
  773. // sendData = '03 00 07 01 08';
  774. // break;
  775. // // case cmd.login:
  776. // // // let secretKey = array.key.toString().trim().toLowerCase();
  777. // // console.log(secretKey)
  778. // // // let c = secretKey.toString().replace(/\s+/g, "");
  779. // // // let cLength = dataTransition.getSecretKeyLength(c);
  780. // // //发送内容
  781. // // let send = `02 00 01`; //02 连接命令 01连接请求 cLength秘钥长度。
  782. // // sendData = `${send} ${secretKey}`;
  783. // // console.log(sendData, 'sendValue')
  784. // // break;
  785. // case cmd.status:
  786. // sendData = '42 44 00 01 0A 0A 05 05'
  787. // console.log(sendData)
  788. // break
  789. // case cmd.ack:
  790. // sendData = array.data
  791. // break;
  792. // }
  793. // let header = dataTransition.header(sendData);
  794. // console.log(header)
  795. // if (commandCode == 'responseAck') {
  796. // header = ''
  797. // }
  798. // let data = header + sendData.replace(/\s+/g, "");
  799. // console.log(data)
  800. // console.log(`发送${commandCode}指令`, data);
  801. // return data;
  802. // }
  803. /*******util*********/
  804. }
  805. // export {
  806. // BluetoothManager
  807. // }
  808. module.exports = {
  809. BluetoothManager: BluetoothManager,
  810. BtErrorCode: errorCode,
  811. CMD:cmd
  812. }