【问题标题】:Communicate with Android bluetooth device via NodeJS and Termux通过 NodeJS 和 Termux 与 Android 蓝牙设备通信
【发布时间】:2017-08-19 10:09:04
【问题描述】:

我们正在寻求与连接到 Android 平板电脑的蓝牙设备进行通信。我们正在使用 Termux 并安装了 NodeJS。有谁知道是否可以与蓝牙设备进行通信?我们是否必须尝试直接通过 /dev 文件夹与设备通信?

据我了解,Android 是构建在 Linux 内核之上的,但是,它在其之上实现了特定的东西来与其他东西进行交互,例如连接性。甚至可以通过 NodejS“serialport”或其他工具通过 /dev 文件夹访问该设备吗?

作为最后的手段,如果这是不可能的,我想我们可以尝试通过 root 终端在 Android 操作系统中构建 NodeJS。我听说这并不像人们想象的那么容易。通过 Termux,我可以访问 /dev 文件夹并查看所有设备。不确定该权限将如何工作。谢谢。

【问题讨论】:

    标签: android node.js linux bluetooth virtual-machine


    【解决方案1】:

    您可以使用此工具通过串行端口进行通信。我从来没有使用过这个工具,只是提供它作为参考,因为 android 是建立在 linux 内核上的,这可能会起作用。请注意,示例与文档相同。

    https://github.com/eelcocramer/node-bluetooth-serial-port

    基本客户端使用

    var btSerial = new (require('bluetooth-serial-port')).BluetoothSerialPort();
    
    btSerial.on('found', function(address, name) {
        btSerial.findSerialPortChannel(address, function(channel) {
            btSerial.connect(address, channel, function() {
                console.log('connected');
    
                btSerial.write(new Buffer('my data', 'utf-8'), function(err, bytesWritten) {
                    if (err) console.log(err);
                });
    
                btSerial.on('data', function(buffer) {
                    console.log(buffer.toString('utf-8'));
                });
            }, function () {
                console.log('cannot connect');
            });
    
            // close the connection when you're ready
            btSerial.close();
        }, function() {
            console.log('found nothing');
        });
    });
    
    btSerial.inquire();
    

    基本服务器使用(仅限 Linux)

    var server = new(require('bluetooth-serial-port')).BluetoothSerialPortServer();
    
    var CHANNEL = 10; // My service channel. Defaults to 1 if omitted.
    var UUID = '38e851bc-7144-44b4-9cd8-80549c6f2912'; // My own service UUID. Defaults to '1101' if omitted
    
    server.listen(function (clientAddress) {
        console.log('Client: ' + clientAddress + ' connected!');
        server.on('data', function(buffer) {
            console.log('Received data from client: ' + buffer);
    
            // ...
    
            console.log('Sending data to the client');
            server.write(new Buffer('...'), function (err, bytesWritten) {
                if (err) {
                    console.log('Error!');
                } else {
                    console.log('Send ' + bytesWritten + ' to the client!');
                }
            });
        });
    }, function(error){
        console.error("Something wrong happened!:" + error);
    }, {uuid: UUID, channel: CHANNEL} );
    

    【讨论】:

    • 请不要只发布指向某个工具或库的链接作为答案。至少在答案本身中展示how it solves the problem。
    • 此代码无法在安卓设备上Termux下的nodejs中安装运行。所以问题仍然悬而未决。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-29
    • 1970-01-01
    相关资源
    最近更新 更多