Using Node.js and Noble for BLE partners

User avatar
kolban
Posts: 1086
Joined: Mon Nov 16, 2015 4:43 pm
Location: Texas, USA

Using Node.js and Noble for BLE partners

Postby kolban » Sat Dec 02, 2017 7:55 pm

I'm a big fan of BLE on the ESP32 and have been using nRFConnect for my BLE testing. However I needed more than I can manually tinker with on my phone. I needed to run scripts, soak tests and more ... so I needed to write code than runs on my PC that communicate with the ESP32 through BLE. There are APIs for Windows, Linux and Mac ... but I'm pretty keen on interpreted languages for scripting tests and wanted something portable. Then I found Noble and Bleno:

https://github.com/sandeepmistry/noble
https://github.com/sandeepmistry/bleno

These are pretty darn good libraries for Node.js (JavaScript) that allow me to write BLE clients and servers that run on my PC (Windows or Linux) that can interact with an ESP32. The documentation isn't brilliant so I'm writing up some guides that suit me ... however the documentation is just about usable.

Here is a sample app that finds my ESP32 device, retrieves a service, retrieves a characteristic, reads the current value of the characteristic and writes a new one.

Code: Select all


var noble = require("noble");
const name = "MYDEVICE";
const ESP32_SERVICE        = "4fafc2001fb5459e8fccc5c9c331914b";
const ESP32_CHARACTERISTIC = "4fafc2011fb5459e8fccc5c9c331914b";

noble.on("discover", function(peripheral) {
   if (peripheral.advertisement.localName == name ) {
      noble.stopScanning();
      peripheral.connect((error) => {
         peripheral.discoverServices([ESP32_SERVICE], (error, services) => {
            if (services.length > 0) {
               services[0].discoverCharacteristics([ESP32_CHARACTERISTIC], (error, characteristics) => {
                  if (characteristics.length > 0) {
                     var characteristic = characteristics[0];
                     characteristic.read((error, data) => {
                        console.log("Here is the current value: " + data);
                        var newValue = "Hello world: " + new Date().getTime();
                        console.log("Changing to: " + newValue);
                        characteristic.write(Buffer.from(newValue));
                        peripheral.disconnect();
                     });
                  }
               });
            }
         });
      });
   }
});

noble.on("stateChange", function(state) {
   if (state == "poweredOn") {
      noble.startScanning();
   }
});


While it might look scary if you don't read JavaScript, the Noble and Bleno libraries are really quite well architected and easy to consume.

I wanted to pass this on in case you needed BLE interactions/testing from your PC <-> ESP32.
Free book on ESP32 available here: https://leanpub.com/kolban-ESP32

Who is online

Users browsing this forum: No registered users and 1 guest