【问题标题】:What is the optimal structure of a BLE app in ionic with cordova plugin带有cordova插件的离子中BLE应用程序的最佳结构是什么
【发布时间】:2019-03-22 10:24:35
【问题描述】:

我正在使用 Cordova 在 Ionic 4 中开发 BLE 应用程序。 我正在从这个 GitHub 存储库实现逻辑:https://github.com/don/ionic-ble-examples/blob/master/scan/src/pages/home/home.ts

但我想创建一个蓝牙服务并在 ngOnInit 中调用扫描函数。我在 viewDidLoad-Method 中分配找到的设备数组。

但我不确定这是否是 BLE 的干净实现。特别是我不知道何时调用不同的状态(扫描,将找到的设备分配给数组)。

当我在 ios 设备上运行我的应用程序时,我会找到蓝牙设备,它们在阵列中是 listet。

我的存储库可以在这里找到: https://github.com/goodcare/tobimat

感谢您的帮助!

【问题讨论】:

  • 我意识到许多关于 SO 的问题都被否决了,因为他们的答案可能过于“固执己见”,但我认为这是一个很棒的问题。太多的 Cordova 插件使用示例只是 不要遵循良好的做法,并在不知不觉中带领经验不足的开发人员走上危险的道路。因此,作为目前正在研究在 Ionic 4 应用程序中实现 BLE 连接的更好方法的其他人,我感谢您提出这个问题。 :)

标签: cordova ionic-framework bluetooth-lowenergy


【解决方案1】:

我建议这样做:

制作一个蓝牙服务

@Injectable()
export class BluetoothService {
    constructor(private _ble: BLE) {

    }

    //make all the api level calls here and maybe more if you want to cache it and use the infos from here later on in the app.

    scan() {
       return this._ble.scan();
    }

}

接下来,制作设备模型

export class DeviceNameModel {
    constructor(private _ble: BLE) {}

    deviceSpecificFunction() {}

    turnOnLamp() {
       this._ble.write(some arraybuffer);
    }

}

最后在您的页面中:

扫描页面以扫描并连接到设备。

  export class ScanPage() {
     private _myDevice: DeviceNameModel;
            scannedDevices: DeviceNameModel

            constructor(private _ble: BLE){}

            ngOnInit() {
              this._ble.scan(scanTime)
                .filter(filter predicate to remove devices that you don't ever 
                        need to connect to)
                .subscribe((response: DeviceNameModel[]) => {
                   this.scannedDevices = response;
                });
            }

            connectTo(device: DeviceNameModel) {
               this._ble.connect(device).subscribe(() => do sth);
            }
    }

与连接设备交互的主页。

export class HomePage implements OnInit {
    private _myDevice: DeviceNameModel;

    constructor(private _ble: BLE){
      this._myDevice = new DeviceNameModel(_ble);
    }

    onToggle(event: boolean) {
        return event ? this._myDevice.turnOnLamp() : this._myDevice.turnOffLamp();
    }
}

请注意,其中大部分是伪助手代码,您需要根据需要定制服务、模型和页面。

【讨论】:

  • 仅供参考,我刚刚发现了一篇精彩的文章,涵盖了Angular Observable Data Services,我将其用作我刚刚在自己的应用程序中创建的BleService 的参考。将 this 答案中描述的概念与 that 文章的基于 Observable 的实现相结合是一个可靠的胜利,
猜你喜欢
  • 1970-01-01
  • 2023-03-06
  • 2010-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多