bluetooth.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  1. const app = getApp();
  2. var util = require('../../utils/util');
  3. var datagramHelp = require('../../utils/datagramHelp');
  4. var task_timer;
  5. var scan_timer;
  6. Page({
  7. data: {
  8. devices: [],
  9. alreadyConnectDevices: [],
  10. connected: false,
  11. chs: [],
  12. isOpenBluetooth: false,
  13. bluetoothOpening: false,
  14. findBtnDisabled: true,
  15. isFinding: false,
  16. scanBtn: 'inline',
  17. rtu_wakeup: '唤醒中...',
  18. btnName: '开始扫描',
  19. bluetoothConnectBtn: '连接设备',
  20. connectedBluetoothName: '',
  21. datagramBuff: '',
  22. rtuWakeup: false,
  23. read_datagram_bluebooth_css: '',
  24. deviceId: '',
  25. serviceId: '',
  26. characteristicId: '',
  27. showBleOpenFailDig: false,
  28. showBleOtherErrorDig: false,
  29. bleOtherErrorReeponseMsg: '',
  30. discoveryStarted: false,
  31. loadingHidden: true,
  32. wakeupCount: 0,
  33. scanDeviceTimeCount: 0,
  34. },
  35. /**
  36. * 生命周期函数--监听页面加载
  37. */
  38. onLoad: function (options) {
  39. console.log('bluebooth home load ', '**********************************************')
  40. this.connectBle();
  41. // var devices = [];
  42. // var d = {};
  43. // d['name'] = "1";
  44. // d['localName'] = "1";
  45. // d['RSSI'] = "1";
  46. // d['deviceId'] = "1";
  47. // devices.push(d);
  48. // devices.push(d);
  49. // devices.push(d);
  50. // devices.push(d);
  51. // devices.push(d);
  52. // devices.push(d);
  53. // var devices2 = [];
  54. // devices2.push(d);
  55. // this.setData({
  56. // rtuWakeup: false,
  57. // devices: devices,
  58. // alreadyConnectDevices: devices2
  59. // })
  60. var tmpDevices = wx.getStorageSync('alreadyConnectDevices');
  61. if (null != tmpDevices && undefined != tmpDevices) {
  62. this.setData({
  63. alreadyConnectDevices: tmpDevices
  64. })
  65. }
  66. },
  67. /**
  68. * 生命周期函数--监听页面隐藏
  69. */
  70. onHide: function () {
  71. console.log('bluebooth home onHide ', '**********************************************')
  72. this.cancelTaskTime();
  73. this.cancelScanTime();
  74. },
  75. /**
  76. * 生命周期函数--监听页面卸载
  77. */
  78. onUnload: function () {
  79. console.log('bluebooth home onUnload ', '**********************************************')
  80. this.cancelTaskTime();
  81. this.cancelScanTime();
  82. this.closeBluetoothAdapter();
  83. this.blueboothCloseState();
  84. },
  85. /**
  86. * 生命周期函数--监听页面显示
  87. */
  88. onShow: function () {
  89. console.log('bluebooth home onShow ', '**********************************************')
  90. },
  91. /**
  92. * 蓝牙适配器-打开状态
  93. */
  94. blueboothOpenState() {
  95. this.setData({
  96. isOpenBluetooth: true,
  97. })
  98. },
  99. /**
  100. * 蓝牙适配器-关闭状态
  101. */
  102. blueboothCloseState() {
  103. this.setData({
  104. isOpenBluetooth: false,
  105. })
  106. },
  107. /**
  108. * 开始连接蓝牙
  109. */
  110. connectBle() {
  111. console.log("connectBle ", "isOpenBluetooth " + this.data.isOpenBluetooth);
  112. if (!this.data.isOpenBluetooth) {
  113. if (!this.data.bluetoothOpening) {
  114. this.setData({
  115. bluetoothOpening: true,
  116. })
  117. this.openBluetoothAdapter();
  118. }
  119. }
  120. },
  121. /**
  122. * 打开蓝牙适配器
  123. */
  124. openBluetoothAdapter() {
  125. let that = this;
  126. console.log("openBluetoothAdapter", "***** open **********")
  127. wx.openBluetoothAdapter({
  128. success: (res) => {
  129. //改变连接状态
  130. that.blueboothOpenState();
  131. console.log("openBluetoothAdapter", "***** open success " + that.data.isOpenBluetooth);
  132. that.setData({
  133. bluetoothOpening: false,
  134. })
  135. //初始化成功,监听
  136. that.onBluetoothAdapterStateChange();
  137. //消息提示
  138. wx.showToast({
  139. title: '蓝牙设备打开成功',
  140. icon: 'none',
  141. duration: 2000,
  142. })
  143. },
  144. fail: (res) => {
  145. if (res.errCode != undefined) {
  146. let code = res.errCode;
  147. // if (code == app.globalData.bluetoothErrCode.alreadyConnect) {
  148. // console.log("openBluetoothAdapter","***** openBluetoothAdapter alreadyConnect **********")
  149. // //已连接,监听
  150. // that.onBluetoothAdapterStateChange();
  151. // //改变连接状态
  152. // that.blueboothOpenState();
  153. // } else
  154. if (code == app.globalData.bluetoothErrCode.notAvailable) {
  155. console.log("openBluetoothAdapter", "***** openBluetoothAdapter notAvailable **********")
  156. //蓝牙未打开,提示用户
  157. that.setData({
  158. showBleOpenFailDig: true,
  159. loadingHidden: true,
  160. })
  161. } else {
  162. //其它错误
  163. console.log("openBluetoothAdapter", "***** openBluetoothAdapter error code " + code + " **********")
  164. that.setData({
  165. bleOtherErrorReeponseMsg: "蓝牙模块系统异常,请重新打开蓝牙助手再试,错误代码: " + code,
  166. showBleOtherErrorDig: true,
  167. loadingHidden: true,
  168. })
  169. }
  170. } else {
  171. //未知错误
  172. console.log("openBluetoothAdapter", "***** openBluetoothAdapter error msg " + res.errMsg + " **********")
  173. that.setData({
  174. bleOtherErrorReeponseMsg: "蓝牙模块系统异常,请重新打开蓝牙助手再试,错误信息: " + res.errMsg,
  175. showBleOtherErrorDig: true,
  176. loadingHidden: true,
  177. })
  178. }
  179. that.setData({
  180. bluetoothOpening: false,
  181. })
  182. }
  183. })
  184. },
  185. /**
  186. * 关闭蓝牙适配器
  187. */
  188. closeBluetoothAdapter() {
  189. if (this.data.isOpenBluetooth) {
  190. wx.closeBluetoothAdapter();
  191. this.setData({
  192. bluetoothOpening: false
  193. })
  194. }
  195. },
  196. /**
  197. * 监听蓝牙适配器的变化
  198. */
  199. onBluetoothAdapterStateChange() {
  200. let that = this;
  201. wx.onBluetoothAdapterStateChange(function (res) {
  202. if (res.available) {
  203. console.log("onBluetoothAdapterStateChange", "******* onBluetoothAdapterStateChange available *********")
  204. that.connectBle();
  205. } else {
  206. console.log("onBluetoothAdapterStateChange", "******* onBluetoothAdapterStateChange unavailable *********")
  207. that.blueboothCloseState();
  208. wx.showToast({
  209. title: '蓝牙设备断开',
  210. icon: 'none',
  211. duration: 2000
  212. })
  213. }
  214. if (res.discovering) {
  215. console.log("onBluetoothAdapterStateChange", "******* onBluetoothAdapterStateChange discovering *********")
  216. } else {
  217. console.log("onBluetoothAdapterStateChange", "******* onBluetoothAdapterStateChange stop discovering *********")
  218. }
  219. })
  220. },
  221. /**
  222. * 打开蓝牙失败确认事件
  223. * @param {}} e
  224. */
  225. bluetoothOpenEvent(e) {
  226. this.setData({
  227. showBleOpenFailDig: false
  228. })
  229. const btn = e.detail.index;
  230. if (btn == 0) {
  231. this.closeBluetoothAdapter();
  232. wx.navigateBack();
  233. } else if (btn == 1) {
  234. this.connectBle();
  235. }
  236. },
  237. /**
  238. * 蓝牙系统错误确认事件
  239. * @param {*} e
  240. */
  241. bluetoothOtherErrorEvent(e) {
  242. this.setData({
  243. showBleOtherErrorDig: false
  244. })
  245. this.closeBluetoothAdapter();
  246. wx.navigateBack();
  247. },
  248. /**
  249. * 开始扫描操作事件
  250. */
  251. scanBluetoothDevicesHandle() {
  252. if (this.data.isFinding) {
  253. this.stopBluetoothDevicesDiscovery()
  254. this.cancelScanTime();
  255. console.log('scanBluetoothDevicesHandle', 'stop scan bluebooth devices *****************');
  256. } else {
  257. this.startBluetoothDevicesDiscovery()
  258. console.log('scanBluetoothDevicesHandle', 'start scan bluebooth devices *****************');
  259. }
  260. },
  261. /**
  262. * 开始扫描蓝牙设置
  263. */
  264. startBluetoothDevicesDiscovery() {
  265. if (this.data.discoveryStarted) {
  266. return
  267. }
  268. const that = this;
  269. let data = [];
  270. this.setData({
  271. btnName: '停止扫描',
  272. isFinding: true,
  273. devices: data,
  274. rtuWakeu: false,
  275. scanDeviceTimeCount: 0
  276. })
  277. wx.startBluetoothDevicesDiscovery({
  278. allowDuplicatesKey: true,
  279. success: (res) => {
  280. console.log('startBluetoothDevicesDiscovery success', res)
  281. that.setData({
  282. discoveryStarted: true
  283. })
  284. that.scanTimeCallback();
  285. wx.onBluetoothDeviceFound((res) => {
  286. res.devices.forEach(device => {
  287. if (device.name != undefined && device.name.length > 0) {
  288. //console.log('bluetooth find *************************************', device.name)
  289. if (device.name.indexOf('XT-') == 0 || device.name.indexOf('DH') == 0 || device.name.indexOf('dh') == 0) {
  290. let foundDevices = that.data.devices
  291. let idx = util.inArray(foundDevices, 'deviceId', device.deviceId)
  292. if (idx === -1) {
  293. foundDevices[foundDevices.length] = device;
  294. that.setData({
  295. scanDeviceTimeCount: 0
  296. });
  297. } else {
  298. foundDevices[idx] = device;
  299. }
  300. that.setData({
  301. devices: foundDevices
  302. });
  303. }
  304. }
  305. })
  306. })
  307. },
  308. fail: (res) => {
  309. console.log('startBluetoothDevicesDiscovery fail', res)
  310. that.setData({
  311. isFinding: false,
  312. btnName: '开始扫描',
  313. discoveryStarted: false
  314. })
  315. }
  316. })
  317. },
  318. /**
  319. * 停止扫描蓝牙设备
  320. */
  321. stopBluetoothDevicesDiscovery() {
  322. let that = this;
  323. wx.stopBluetoothDevicesDiscovery({
  324. success(res) {
  325. that.cancelScanTime();
  326. that.setData({
  327. isFinding: false,
  328. btnName: '开始扫描',
  329. discoveryStarted: false
  330. })
  331. }
  332. });
  333. },
  334. /**
  335. * 连接蓝牙设备
  336. * @param {*} e
  337. */
  338. onBLEConnectionHandle(e) {
  339. var that = this;
  340. const ds = e.currentTarget.dataset;
  341. const deviceId = ds.deviceId;
  342. const name = ds.name;
  343. if (this.data.discoveryStarted) {
  344. this.stopBluetoothDevicesDiscovery();
  345. this.cancelScanTime();
  346. }
  347. this.setData({
  348. connectedBluetoothName: name,
  349. deviceId: deviceId,
  350. isFinding: false,
  351. loadingHidden: false,
  352. wakeupCount: 1,
  353. rtuWakeup: false
  354. })
  355. console.log('onBLEConnectionHandle connect ', name)
  356. wx.createBLEConnection({
  357. deviceId,
  358. timeout: 5000,
  359. success: (res) => {
  360. console.log('onBLEConnectionHandle connect success ', name)
  361. that.setData({
  362. connected: true
  363. })
  364. // wx.onBLEConnectionStateChange(function (res) {
  365. // // 该方法回调中可以用于处理连接意外断开等异常情况
  366. // console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`)
  367. // })
  368. that.getBLEDeviceServices(deviceId);
  369. },
  370. fail(res) {
  371. if (res.errCode != undefined) {
  372. if (res.errCode == app.globalData.bluetoothErrCode.alreadyConnect) {
  373. that.setData({
  374. loadingHidden: true,
  375. rtuWakeup: false,
  376. wakeupCount: 1
  377. })
  378. that.datagramReadTask();
  379. that.taskTimeCallback();
  380. } else {
  381. console.log("onBLEConnectionHandle ", "***** error code " + res.errCode + " **********")
  382. that.setData({
  383. bleOtherErrorReeponseMsg: "蓝牙模块系统异常,请重新打开蓝牙助手再试,错误代码: " + res.errCode,
  384. showBleOtherErrorDig: true,
  385. loadingHidden: true
  386. })
  387. }
  388. } else {
  389. console.log("onBLEConnectionHandle ", "***** error msg " + res.errMsg + " **********")
  390. that.setData({
  391. bleOtherErrorReeponseMsg: "蓝牙模块系统异常,请重新打开蓝牙助手再试,错误信息: " + res.errMsg,
  392. showBleOtherErrorDig: true,
  393. loadingHidden: true
  394. })
  395. }
  396. }
  397. })
  398. },
  399. onBLEConnectionFormQr(device) {
  400. var that = this;
  401. const deviceId = device.deviceId;
  402. const name = device.name;
  403. if (this.data.discoveryStarted) {
  404. this.stopBluetoothDevicesDiscovery();
  405. this.cancelScanTime();
  406. }
  407. this.setData({
  408. connectedBluetoothName: name,
  409. deviceId: deviceId,
  410. isFinding: false,
  411. loadingHidden: false,
  412. wakeupCount: 1,
  413. rtuWakeup: false
  414. })
  415. console.log('onBLEConnectionHandle connect ', name)
  416. wx.createBLEConnection({
  417. deviceId,
  418. timeout: 5000,
  419. success: (res) => {
  420. console.log('onBLEConnectionHandle connect success ', name)
  421. that.setData({
  422. connected: true
  423. })
  424. that.getBLEDeviceServices(deviceId);
  425. },
  426. fail(res) {
  427. if (res.errCode != undefined) {
  428. if (res.errCode == app.globalData.bluetoothErrCode.alreadyConnect) {
  429. that.setData({
  430. loadingHidden: true,
  431. rtuWakeup: false,
  432. wakeupCount: 1
  433. })
  434. that.datagramReadTask();
  435. that.taskTimeCallback();
  436. } else {
  437. console.log("onBLEConnectionHandle ", "***** error code " + res.errCode + " **********")
  438. that.setData({
  439. bleOtherErrorReeponseMsg: "蓝牙模块系统异常,请重新打开蓝牙助手再试,错误代码: " + res.errCode,
  440. showBleOtherErrorDig: true,
  441. loadingHidden: true
  442. })
  443. }
  444. } else {
  445. console.log("onBLEConnectionHandle ", "***** error msg " + res.errMsg + " **********")
  446. that.setData({
  447. bleOtherErrorReeponseMsg: "蓝牙模块系统异常,请重新打开蓝牙助手再试,错误信息: " + res.errMsg,
  448. showBleOtherErrorDig: true,
  449. loadingHidden: true
  450. })
  451. }
  452. }
  453. })
  454. },
  455. onStartQr: function (e) {
  456. var that = this;
  457. // 允许从相机和相册扫码
  458. wx.scanCode({
  459. success: (res) => {
  460. var result = res.result;
  461. if (result != undefined && result.length > 0) {
  462. that.findDeviceByQr(result)
  463. }
  464. }
  465. })
  466. },
  467. findDeviceByQr(qr) {
  468. for (let i = 0; i < this.data.devices.length; i++) {
  469. let d = this.data.devices[i];
  470. if (d.name == qr) {
  471. this.onBLEConnectionFormQr(d);
  472. return;
  473. }
  474. }
  475. for (let i = 0; i < this.data.alreadyConnectDevices.length; i++) {
  476. let d = this.data.alreadyConnectDevices[i];
  477. if (d.name == qr) {
  478. this.onBLEConnectionFormQr(d);
  479. return;
  480. }
  481. }
  482. wx.showToast({
  483. title: '没匹配到设备',
  484. icon: 'error',
  485. duration: 2000
  486. })
  487. },
  488. /**
  489. * 获取蓝牙设备所有服务(service)
  490. * @param {*} deviceId
  491. */
  492. getBLEDeviceServices(deviceId) {
  493. const that = this;
  494. console.log('*************************** getBLEDeviceServices start', deviceId);
  495. wx.getBLEDeviceServices({
  496. deviceId,
  497. success: (res) => {
  498. console.log('*************************** getBLEDeviceServices ', "ok");
  499. let toNext = false;
  500. for (let i = 0; i < res.services.length; i++) {
  501. console.log(' res++++++++++++ ', res.services[i])
  502. if (res.services[i].isPrimary) {
  503. toNext = true;
  504. that.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid);
  505. break;
  506. }
  507. }
  508. if (!toNext) {
  509. that.setData({
  510. loadingHidden: true
  511. })
  512. }
  513. },
  514. fail: (res) => {
  515. console.log("getBLEDeviceServices ", "***** error msg " + res.errMsg + " **********")
  516. that.setData({
  517. bleOtherErrorReeponseMsg: "蓝牙模块系统异常,请重新打开蓝牙助手再试,错误信息: " + res.errMsg,
  518. showBleOtherErrorDig: true,
  519. loadingHidden: true
  520. })
  521. }
  522. })
  523. },
  524. /**
  525. * 获取蓝牙设备某个服务中所有特征值(characteristic)
  526. * @param {*} deviceId
  527. * @param {*} serviceId
  528. */
  529. getBLEDeviceCharacteristics(deviceId, serviceId) {
  530. var that = this
  531. wx.getBLEDeviceCharacteristics({
  532. deviceId,
  533. serviceId,
  534. success: (res) => {
  535. console.log('getBLEDeviceCharacteristics success', res.characteristics)
  536. that.setData({
  537. canWrite: false
  538. })
  539. let write_uuid = [];
  540. for (let i = 0; i < res.characteristics.length; i++) {
  541. let item = res.characteristics[i]
  542. if (item.properties.read) {
  543. console.log("read uuid", item.uuid)
  544. // that.setData({
  545. // deviceId: deviceId,
  546. // serviceId: serviceId,
  547. // characteristicId: item.uuid
  548. // })
  549. wx.readBLECharacteristicValue({
  550. deviceId,
  551. serviceId,
  552. characteristicId: item.uuid,
  553. })
  554. }
  555. if (item.properties.write) {
  556. //使用透传UUID进行读
  557. console.log("write uuid", item.uuid)
  558. let u = "" + item.uuid;
  559. write_uuid.push(u);
  560. // if (u.includes("FFE1", 0)) {
  561. that.setData({
  562. canWrite: true,
  563. // deviceId: deviceId,
  564. // serviceId: serviceId,
  565. // characteristicId: item.uuid
  566. })
  567. // }
  568. }
  569. if (item.properties.notify || item.properties.indicate) {
  570. console.log("notify uuid", item.uuid)
  571. // console.log('notify success+++++++++++++++++++++++ ')
  572. // that.setData({
  573. // deviceId: deviceId,
  574. // serviceId: serviceId,
  575. // characteristicId: item.uuid
  576. // })
  577. wx.notifyBLECharacteristicValueChange({
  578. deviceId,
  579. serviceId,
  580. characteristicId: item.uuid,
  581. state: true,
  582. })
  583. }
  584. }
  585. that.setData({
  586. loadingHidden: true
  587. })
  588. if (this.data.canWrite) {
  589. if (write_uuid.length == 1) {
  590. console.log("get uuid", write_uuid[0])
  591. that.setData({
  592. deviceId: deviceId,
  593. serviceId: serviceId,
  594. characteristicId: write_uuid[0]
  595. })
  596. } else {
  597. for (let j = 0; j < write_uuid.length; j++) {
  598. let uid = "" + write_uuid[j];
  599. if (uid.includes("FFE1", 0)) {
  600. console.log("get uuid", uid)
  601. that.setData({
  602. // canWrite: true,
  603. deviceId: deviceId,
  604. serviceId: serviceId,
  605. characteristicId: uid
  606. })
  607. break;
  608. }
  609. }
  610. }
  611. that.canWriteBLECharacteristicValue()
  612. }
  613. },
  614. fail(res) {
  615. console.log("getBLEDeviceCharacteristics ", "***** error msg " + res.errMsg + " **********")
  616. that.setData({
  617. bleOtherErrorReeponseMsg: "蓝牙模块系统异常,请重新打开蓝牙助手再试,错误信息: " + res.errMsg,
  618. showBleOtherErrorDig: true,
  619. loadingHidden: true
  620. })
  621. }
  622. })
  623. },
  624. /**
  625. * 发送蓝牙设备唤醒报文
  626. */
  627. datagramReadTask() {
  628. const that = this;
  629. this.setData({
  630. read_datagram_bluebooth_css: 'shanshuo'
  631. })
  632. if (!this.data.rtuWakeup) {
  633. console.log("------------------------------------f6 datagram----------------------------");
  634. this.sendWakeupDatagram();
  635. }
  636. },
  637. processWakeupDatagram() {
  638. let datagram = this.data.datagramBuff;
  639. if (datagram.length > 0) {
  640. if (datagram.indexOf("7e7e") >= 0) {
  641. if (datagram.length >= 50) {
  642. const funcode = datagram.substring(20, 22);
  643. if (funcode == 'f6') {
  644. console.log("------------------------------------find f6 datagram----------------------------");
  645. this.setData({
  646. read_datagram_bluebooth_css: '',
  647. rtuWakeup: true,
  648. datagramBuff: ''
  649. })
  650. } else {
  651. this.setData({
  652. datagramBuff: ''
  653. })
  654. }
  655. }
  656. } else {
  657. this.setData({
  658. datagramBuff: ''
  659. })
  660. }
  661. }
  662. if (this.data.rtuWakeup) {
  663. this.cancelTaskTime();
  664. this.cancelScanTime();
  665. this.setData({
  666. loadingHidden: true
  667. })
  668. var tmpDevices = [];
  669. var device = {};
  670. device['deviceId'] = this.data.deviceId;
  671. device['name'] = this.data.connectedBluetoothName;
  672. device['serviceId'] = this.data.serviceId;
  673. device['characteristicId'] = this.data.characteristicId;
  674. tmpDevices.push(device);
  675. var devices = this.data.alreadyConnectDevices;
  676. for (var i = 0; i < devices.length; i++) {
  677. var d = devices[i];
  678. if (device['deviceId'] !== d['deviceId']) {
  679. tmpDevices.push(d);
  680. }
  681. if (tmpDevices.length >= 5) {
  682. break;
  683. }
  684. }
  685. try {
  686. wx.setStorageSync('alreadyConnectDevices', tmpDevices);
  687. } catch (e) {
  688. console.log(e);
  689. }
  690. this.setData({
  691. alreadyConnectDevices: tmpDevices
  692. })
  693. //跳转到蓝牙主页
  694. wx.navigateTo({
  695. url: '/pages/bluetooth/home/bluetoothHome?connectedBluetoothName=' + this.data.connectedBluetoothName + '&deviceId=' + this.data.deviceId + '&serviceId=' + this.data.serviceId + '&characteristicId=' + this.data.characteristicId,
  696. })
  697. }
  698. },
  699. /**
  700. * 接收到数据
  701. * @param {} datagram
  702. */
  703. pushDatagram(datagram) {
  704. if (null != datagram && datagram.length > 0) {
  705. var tmpdatagramBuff = this.data.datagramBuff;
  706. if (tmpdatagramBuff.length > 0) {
  707. tmpdatagramBuff = tmpdatagramBuff + datagram;
  708. } else {
  709. tmpdatagramBuff = datagram;
  710. }
  711. console.log(" datagram buff ==========", tmpdatagramBuff)
  712. this.setData({
  713. datagramBuff: tmpdatagramBuff
  714. })
  715. this.processWakeupDatagram();
  716. }
  717. },
  718. /**
  719. * 发送唤醒蓝牙设备操作
  720. */
  721. sendWakeupDatagram() {
  722. let datagram = datagramHelp.datagram_f6();
  723. let buffer = util.HexStr2Bytes(datagram);
  724. var that = this
  725. wx.writeBLECharacteristicValue({
  726. deviceId: this.data.deviceId,
  727. serviceId: this.data.serviceId,
  728. characteristicId: this.data.characteristicId,
  729. value: buffer,
  730. success(res) {
  731. console.log('writeBLECharacteristicValue success', res.errMsg)
  732. // 操作之前先监听,保证第一时间获取数据
  733. wx.onBLECharacteristicValueChange((characteristic) => {
  734. console.log("read datagram==========", util.ab2hex(characteristic.value))
  735. let datagram = util.ab2hex(characteristic.value);
  736. that.pushDatagram(datagram);
  737. })
  738. wx.readBLECharacteristicValue({
  739. deviceId: that.data.deviceId,
  740. serviceId: that.data.serviceId,
  741. characteristicId: that.data.characteristicId,
  742. success: function (res) {
  743. console.log('readBLECharacteristicValue')
  744. }
  745. })
  746. },
  747. fail(res) {
  748. console.log('writeBLECharacteristicValue success', res.errMsg);
  749. }
  750. })
  751. },
  752. taskTimeCallback() {
  753. console.log("------------------------------------Task Time CallBack----------------------------");
  754. var that = this;
  755. if (!this.data.rtuWakeup) {
  756. if (this.data.wakeupCount >= 5) {
  757. this.setData({
  758. loadingHidden: true
  759. })
  760. } else {
  761. task_timer = setTimeout(function () {
  762. that.datagramReadTask();
  763. that.taskTimeCallback();
  764. }, 3000);
  765. }
  766. }
  767. },
  768. cancelTaskTime() {
  769. if (task_timer != undefined) {
  770. clearTimeout(task_timer);
  771. task_timer = undefined;
  772. }
  773. },
  774. scanTimeCallback() {
  775. console.log("------------------------------------Scan Time CallBack----------------------------");
  776. var that = this;
  777. if (this.data.scanDeviceTimeCount >= 6) {
  778. console.log("Scan Time CallBack stopBluetoothDevicesDiscovery");
  779. this.stopBluetoothDevicesDiscovery();
  780. } else {
  781. let c = this.data.scanDeviceTimeCount + 2;
  782. this.setData({
  783. scanDeviceTimeCount: c
  784. })
  785. scan_timer = setTimeout(function () {
  786. that.scanTimeCallback();
  787. }, 2000);
  788. }
  789. },
  790. cancelScanTime() {
  791. if (scan_timer != undefined) {
  792. clearTimeout(scan_timer);
  793. scan_timer = undefined;
  794. }
  795. },
  796. canWriteBLECharacteristicValue() {
  797. if (!this.data.rtuWakeup) {
  798. this.setData({
  799. isFinding: false,
  800. btnName: '开始扫描',
  801. rtuWakeup: false
  802. })
  803. console.log("----------------------------------- 发送第一个包----------------------------");
  804. this.datagramReadTask();
  805. this.taskTimeCallback();
  806. }
  807. }
  808. })