util.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. const manager = require('./manager');
  2. module.exports = {
  3. BleUtil
  4. }
  5. class BleUtil {
  6. static _instance = new BleUtil();
  7. static getInstance() {
  8. return BleUtil._instance;
  9. }
  10. constructor() {
  11. var that = this;
  12. that.manager = new manager();
  13. }
  14. ///获取比较的数据
  15. getCompareList() {
  16. var that = this;
  17. return that.manager.getCompareList();
  18. }
  19. getDissmissDevice() {
  20. var that = this;
  21. return that.manager.getDissmissDevice();
  22. }
  23. getCallBackConnect() {
  24. var that = this;
  25. return that.manager.getCallBackConnect();
  26. }
  27. ///初始化蓝牙适配器
  28. initBluetoothAdapter() {
  29. var that = this;
  30. that.manager.initBlueAdapter();
  31. }
  32. ///获取蓝牙设备 connect:true,去连接,false,去对比
  33. listenBlueDevices() {
  34. var that = this;
  35. that.manager.listenBlueDevices();
  36. }
  37. ///搜索蓝牙设备
  38. startScan(connectWillDevice, boolean, callBackConnect) {
  39. var that = this;
  40. that.manager.startScan(
  41. connectWillDevice,
  42. boolean,
  43. callBackConnect,
  44. );
  45. }
  46. ///停止搜索蓝牙设备
  47. async stopScan() {
  48. var that = this;
  49. await that.manager.stopScan();
  50. }
  51. ///开始连接设备
  52. async startConnect(device, onChanged) {
  53. var that = this;
  54. await that.stopScan();
  55. await that.disconnect(device);
  56. var res = await that.manager.startConnect(device);
  57. if (!res) {
  58. onChanged(false, device);
  59. return;
  60. }
  61. const strings = require('./../../utils/strings');
  62. var services = await that.manager.getNotifyServices(device);
  63. if (strings.isEmpty(services)) {
  64. onChanged(false, device);
  65. return;
  66. }
  67. that.manager.getCharacteristics(device, services, 0, false, false, false,
  68. async function (notifyServiceId, notifyCharaterId) {
  69. var isTrue = that.manager.monitorCharacteristicValueChange(device, notifyServiceId, notifyCharaterId);
  70. if (!isTrue) {
  71. onChanged(false, device);
  72. return;
  73. }
  74. const hex_util = require('./../../utils/hex_util');
  75. that.manager.onBLECharacteristicValueChange(function (value) {
  76. var receiveText = hex_util.buf2string(value);
  77. console.log('接收到数据文字:' + receiveText)
  78. });
  79. },
  80. function () {
  81. onChanged(false, device);
  82. return;
  83. });
  84. }
  85. ///发送数据
  86. async sendData(device, text) {
  87. var isTrue = await that.manager.sendData(device, text);
  88. ///发送数据成功
  89. if (isTrue) {
  90. }
  91. }
  92. ///断开设备连接
  93. async disconnect(device) {
  94. var that = this;
  95. await that.manager.disconnect(device);
  96. }
  97. }