【问题标题】:how to receive data from bluetooth device using node.js如何使用 node.js 从蓝牙设备接收数据
【发布时间】:2017-12-12 03:28:33
【问题描述】:

我是 javascript 和 node.js 的新手。目前从事医疗项目。首先我会解释我的工作。我必须从蓝牙设备接收数据(正常血压率、脉率)并使用 node.js 在网络应用程序中显示读数。我不知道如何从蓝牙设备(病人监护仪)接收数据,你们能不能给我推荐一些博客或书籍来阅读。提前致谢。

【问题讨论】:

标签: javascript node.js bluetooth


【解决方案1】:

您可以使用“node-bluetooth”分别从设备发送和接收数据。这是一个示例代码:-

const bluetooth = require('node-bluetooth');

// create bluetooth device instance

const device = new bluetooth.DeviceINQ();

device
    .on('finished', console.log.bind(console, 'finished'))
    .on('found', function found(address, name) {
        console.log('Found: ' + address + ' with name ' + name);

        device.findSerialPortChannel(address, function(channel) {
            console.log('Found RFCOMM channel for serial port on %s: ', name, channel);

            // make bluetooth connect to remote device
            bluetooth.connect(address, channel, function(err, connection) {
                if (err) return console.error(err);
                connection.write(new Buffer('Hello!', 'utf-8'));
            });

        });

        // make bluetooth connect to remote device
        bluetooth.connect(address, channel, function(err, connection) {
            if (err) return console.error(err);

            connection.on('data', (buffer) => {
                console.log('received message:', buffer.toString());
            });

            connection.write(new Buffer('Hello!', 'utf-8'));
        });
    }).inquire();

它扫描“设备”变量中给出的设备名称。

【讨论】:

  • 感谢兄弟它的工作,但我在这里遇到了问题。它没有显示可以配对的蓝牙设备。它会自动连接到附近的蓝牙设备。你能帮我列出蓝牙设备吗@Asim Raja 提前谢谢。
  • 谢谢兄弟@Asim Raja,但它与之前没有显示蓝牙设备列表相同,它只显示一个设备并尝试自动配对,配对后出现错误:bluetooth.connect(地址,频道, function(err, connection){ ^ ReferenceError: channel is not defined
  • hi asim,sello,我只是使用下面的代码来获取可用设备的列表,但它会抛出如下所述的错误,请指导我 device .on('finished', console .log.bind(console, 'finished')) .on('found', function found(address, name) { console.log('Found: ' + address + ' with name ' + name); }).inquire ();错误:}).inquire();错误:打开套接字。 ^
  • 嘿,我正在寻找支持蓝牙版本 5 的包。虽然我无法安装 node-bluetooth 包,因为它给出了 gyp 错误。如果你能分享你是如何安装这个包的,那就太好了。
【解决方案2】:

试试noble 库。这就是我获取小米手环 3 设备信息的方式:

const arrayBufferToHex = require('array-buffer-to-hex')
const noble = require('noble')

const DEVICE_INFORMATION_SERVICE_UUID = '180a'

noble.on('stateChange', state => {
  console.log(`State changed: ${state}`)
  if (state === 'poweredOn') {
    noble.startScanning()
  }
})

noble.on('discover', peripheral => {
  console.log(`Found device, name: ${peripheral.advertisement.localName}, uuid: ${peripheral.uuid}`)

  if (peripheral.advertisement.localName === 'Mi Band 3') {
    noble.stopScanning()

    peripheral.on('connect', () => console.log('Device connected'))
    peripheral.on('disconnect', () => console.log('Device disconnected'))

    peripheral.connect(error => {
      peripheral.discoverServices([DEVICE_INFORMATION_SERVICE_UUID], (error, services) => {
        console.log(`Found service, name: ${services[0].name}, uuid: ${services[0].uuid}, type: ${services[0].type}`)

        const service = services[0]

        service.discoverCharacteristics(null, (error, characteristics) => {
          characteristics.forEach(characteristic => {
            console.log(`Found characteristic, name: ${characteristic.name}, uuid: ${characteristic.uuid}, type: ${characteristic.type}, properties: ${characteristic.properties.join(',')}`)
          })

          characteristics.forEach(characteristic => {
            if (characteristic.name === 'System ID' || characteristic.name === 'PnP ID') {
              characteristic.read((error, data) => console.log(`${characteristic.name}: 0x${arrayBufferToHex(data)}`))
            } else {
              characteristic.read((error, data) => console.log(`${characteristic.name}: ${data.toString('ascii')}`))
            }
          })
        })
      })
    })
  }
})

【讨论】:

    【解决方案3】:

    您可以使用 node-ble 一个利用 D-Bus 并避免 C++ 绑定的 Node.JS 库。 https://github.com/chrvadala/node-ble

    这里是一个基本的例子

    async function main () {
      const { bluetooth, destroy } = createBluetooth()
    
      // get bluetooth adapter
      const adapter = await bluetooth.defaultAdapter()
      await adapter.startDiscovery()
      console.log('discovering')
    
      // get device and connect
      const device = await adapter.waitDevice(TEST_DEVICE)
      console.log('got device', await device.getAddress(), await device.getName())
      await device.connect()
      console.log('connected')
    
      const gattServer = await device.gatt()
    
      // read write characteristic
      const service1 = await gattServer.getPrimaryService(TEST_SERVICE)
      const characteristic1 = await service1.getCharacteristic(TEST_CHARACTERISTIC)
      await characteristic1.writeValue(Buffer.from('Hello world'))
      const buffer = await characteristic1.readValue()
      console.log('read', buffer, buffer.toString())
    
      // subscribe characteristic
      const service2 = await gattServer.getPrimaryService(TEST_NOTIFY_SERVICE)
      const characteristic2 = await service2.getCharacteristic(TEST_NOTIFY_CHARACTERISTIC)
      await characteristic2.startNotifications()
      await new Promise(done => {
        characteristic2.once('valuechanged', buffer => {
          console.log('subscription', buffer)
          done()
        })
      })
    
      await characteristic2.stopNotifications()
      destroy()
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-02
      • 1970-01-01
      • 2014-10-04
      • 2021-02-13
      • 1970-01-01
      • 2020-03-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多