【问题标题】:How to send data via BLE using ionic 3 and angular 4?如何使用 ionic 3 和 angular 4 通过 BLE 发送数据?
【发布时间】:2018-10-11 17:38:01
【问题描述】:

我的第一个问题在这里。

我目前正在使用 cordova-plugin-ble-central 插件通过我的 BLE 设备发送数据。我真的不明白如何发送数据。

我应该做的是使用 Unit8Array 发送一组 8 字节的字符串。

这是我要发送的示例:

  array: string[] = [
    '10111010',
    '00000000',
    '00000000',
    '0',
    '00000000',
    '0000',
    '0000',
    '0',
    '0',
    '0000'
]

这就是我现在正在尝试的:

stringToBytes(strings: any[]) {
    var arrayBuffer = new ArrayBuffer(144);
    var array = new Uint8Array(arrayBuffer);
    for (let string of strings) {
        // console.log('string from 1st for : ', string);
        for (var i = 0, l = string.length; i < l; i++) {
            // console.log('string from 2nd for : ', string);
            array[i] = string.charCodeAt(i);
        }
    }
    console.log(array.buffer, 'array : ', array);
    return array.buffer;
}

这是正确的方法吗?有什么建议吗?

抱歉英语不好,如果问题有一些错误。

感谢您的建议, 乔治。

【问题讨论】:

    标签: angular ionic-framework bluetooth-lowenergy


    【解决方案1】:

    首先,我强烈建议使用 Ionic Native 用于 cordova 插件 Bluetooth Serial 的包装器。

    1。安装 Cordova 和 Ionic Native 插件:

    $ ionic cordova plugin add cordova-plugin-bluetooth-serial
    $ npm install --save @ionic-native/bluetooth-serial
    

    2。安装插件包后,将其添加到应用的 NgModule 中。

    ...
    
    import { Camera } from '@ionic-native/camera';
    
    ...
    
    @NgModule({
      ...
    
      providers: [
        ...
        BluetoothSerial,
        ...
      ]
      ...
    })
    export class AppModule { }
    

    3。用法

    import { BluetoothSerial } from '@ionic-native/bluetooth-serial';
    
    constructor(private bluetoothSerial: BluetoothSerial) { }
    
    
    // Write a string
    this.bluetoothSerial.write('hello world').then(success, failure);
    
    // Array of int or bytes
    this.bluetoothSerial.write([186, 220, 222]).then(success, failure);
    
    // Typed Array
    var data = new Uint8Array(4);
    data[0] = 0x41;
    data[1] = 0x42;
    data[2] = 0x43;
    data[3] = 0x44;
    this.bluetoothSerial.write(data).then(success, failure);
    
    // Array Buffer
    this.bluetoothSerial.write(data.buffer).then(success, failure);
    

    【讨论】:

    • 首先感谢您的快速答复。我已经使用过这个插件,但我找不到活动的 BLE 设备。这正常吗?感谢您的建议。
    • 我的回答涵盖Bluetooth Serial。这与BLE 不同。看看吧,它会为你工作。
    • 也许我已经解决了直接声明和填充一个 Uint8Array,而不是尝试将字符串数组转换为字节数组。现在我有另一个问题。如果我想发送一个名字,我必须发送每个字母的 ASCII 码吗? ASCII 到字母的转换取决于接收数据的设备?
    • 是的,完全正确。在蓝牙协议中,传输的都是原始字节。
    猜你喜欢
    • 2021-11-29
    • 1970-01-01
    • 1970-01-01
    • 2018-02-21
    • 2017-12-29
    • 1970-01-01
    • 1970-01-01
    • 2018-03-03
    • 2021-08-16
    相关资源
    最近更新 更多