2017-03-26 238 views
10

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

我的理解是,Android是建立在Linux内核的基础之上的,然而,它已经在它之上实现了特定的事情来与其他事物(例如连接)进行交互。该设备甚至可以通过NodeJS“serialport”或其他工具通过/ dev文件夹访问?

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

enter image description here

回答

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}); 
+1

请不要只是发布一个链接到一些工具或库作为一个答案。至少在答案中演示[它如何解决问题](http://meta.stackoverflow.com/a/251605)。 –