You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
1.6 KiB

1 year ago
  1. import BLEHandler from "./bleHandler"
  2. class BLE extends BLEHandler {
  3. constructor(blename, emitter) {
  4. super(blename, emitter)
  5. }
  6. listen(callback) {
  7. // 蓝牙事件注册,打开channel
  8. this.emitter.removeAllListeners("channel")
  9. this.emitter.on("channel", callback)
  10. }
  11. removeListen() {
  12. // 移除所有蓝牙事件
  13. this.emitter.removeAllListeners("channel")
  14. }
  15. async init() {
  16. let flow = false
  17. // 打开蓝牙适配器状态监听
  18. this.onBLEConnectionStateChange()
  19. // 蓝牙适配器初始化
  20. await this.openAdapter()
  21. // 搜索蓝牙设备
  22. await this.startSearch()
  23. // 获取设备ID
  24. flow = await this.onBluetoothFound()
  25. if (!flow) return
  26. // 停止搜索设备
  27. await this.stopSearchBluetooth()
  28. // 连接蓝牙
  29. await this.connectBlue();
  30. //安卓手机需要设置MTU Size
  31. await this.setBLEMTU();
  32. // 获取serviceId
  33. await this.getBLEServices()
  34. // 设置特征值
  35. await this.getCharacteristics();
  36. // 订阅特征值
  37. await this.notifyBLECharacteristicValueChange()
  38. // 打开传输监听,等待设备反馈数据
  39. this.onBLECharacteristicValueChange()
  40. }
  41. // 发送指令
  42. async send(cmd, payload,timestamp,callback) {
  43. let flow = await this.sentOrder(cmd, payload,timestamp,callback)
  44. return flow
  45. }
  46. async close() {
  47. await this.closeBLEConnection()
  48. await this.closeBLEAdapter()
  49. }
  50. }
  51. export { BLE };