Giter Site home page Giter Site logo

ble-bean's Introduction

#BLE-Bean Non Official api for the LightBlue Bean

I recommend you familiarize yourself with the Bean first, but the gist is it has a BLE transceiver and an Arduino onboard. You can program regular Arduino sketches on the Arduino, but the BLE transceiver is available no matter what sketch you have on the bean.

Second it might be helpful to familiarize yourself with noble as this library is built on noble-device.

#Install

npm install ble-bean

#Use To get started You include this library and ask the library to discover a bean:

var Bean = require('ble-bean');
Bean.discover(function(bean){

}

But you're not done yet, inside the discover you need to ask the bean to set itself up:

bean.connectAndSetup(function(){

}

When that returns you're finally ready to use the ble-bean api:

bean.requestTemp(callback);
bean.requestAccell(callback);
bean.setColor(color, callback); //where color is a buffer of r,g,b hex values
bean.write(data, callback); //where data is a buffer

Huge gotcha here though, the callback to all api commands DO NOT GIVE YOU BACK YOUR DATA, they simply confirms that the request has left your computer.

The data response is based on emitters. You need to listen for the event you're interested in. We offer:

  • serial - which returns data, valid - serial data from the Arduino
  • accell - which returns x, y, z, valid - accelerometer data from bean
  • temp - which returns temp, valid - accelerometer data from bean
  • raw - which returns packet, length, valid, command - which returns raw command packet from bean before it gets turned into accell, serial, temp, etc (with gst and gatt headers stripped)

Each of the events offers a valid flag to see if the checksum matched up, etc. It probably doesn't matter to you unless you're doing something mission critical.

Theres are also five scratch characteristics available on the bean. These are just another way to send data to your Arduino:

bean.readOne(callback); //explicit read from characteristic
bean.notifyOne(readCallback, callback); //listen for all data from characteristic
bean.writeOne(callback); //write data to characteristic
bean.unnotifyOne(readCallback, callback); //stop listening for all data from characteristic

For a fairly exhaustive example that connects, listens for serial data, sets the led color randomly, asks the bean for temp and accell data every second, and disconnects cleanly when you control-c, from bean directory run:

node examples/bean_example.js

###CHANGELOG 0.1.0 first

0.2.0 cleaned up scanning in the example and the package.json file

0.3.0 and 0.4.0 add scratch characteristics with notify fix accelerometer readings better logging in example, took console.log out of library

0.5.0 scale accelerometer readings added readme with changelog

0.6.0 only emit command specific emits when packets are valid refactor for cleaner code add write scratch characteristics

0.7.0 add write serial data to bean characteristic

0.7.1 Better readme, no code changes.

0.8.0 New Serial event for parsed serial data called 'serial'

1.0.0 Emitter callback signatures changed!! 'read' emitter became 'raw' accell and serial changed removing the sequence since its handled internally now. Added requestTemp.

2.0.0 Move to new noble-device pattern which significantly removes noble cruft from implementation. Changes the scratch characteristic API. Example has cleaner disconnect code.

2.0.1 Clean and split up examples

2.0.2 Fixed bug in Scratch write implementation clean up firmata example

2.1.0 newer firmwares are gating serial SEND during first x seconds, added unGate function to disable

ble-bean's People

Contributors

jacobrosenthal avatar russnelson avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ble-bean's Issues

Mulitple Beans?

If you want to read data from multiple beans, how would this be possible. I understand this can't be done simultaneously but how could I switch from one Bean to another? Sorry if this is the wrong place to ask this.

Would this check need to be done in Bean.js?

YourThing.is = function(peripheral) {
return (peripheral.advertisement.localName === 'My Thing's Name');
};

Documentation for example is insufficient

The documentation for the example is insufficient. It should say 1) what to do, and 2) what you should expect to see. It would also help if the documentation said what you should see if the bean cannot be detected. And it would help if it said what other tools there are for diagnosing problems with noble. For example, if the problem is with noble, then ble-bean is never going to work. If you give people the tools to show that the problem isn't in this code, you can help them solve the problem rather than trying to get the example to work.

Cannot request acceleration on linux; same code works on OSX

path/client/node_modules/ble-bean/lib/bean.js:140
    this.chara.write(gattBuffer, false, done);
               ^
TypeError: Cannot call method 'write' of undefined
    at Bean.send (path/client/node_modules/ble-bean/lib/bean.js:140:16)
    at Bean.requestAccell (path/client/node_modules/ble-bean/lib/bean.js:152:10)
    at null.<anonymous> (path/client/proximity.js:108:55)
    at wrapper [as _onTimeout] (timers.js:261:14)
    at Timer.listOnTimeout [as ontimeout] (timers.js:112:15)

I added a few debug logs above line 37 The output was:

cmdBuffer: [32,16]
gattBuffer: [128,2,0,32,16,127,125]
payloadBuffer: []

I've confirmed this error using Ubuntu 14.04 in a virtual-machine and on a raspberry pi. And I've tried to use a few different adapters.

Here's the dump of peripheral.

2014-11-03T22:29:33.107Z - info: EK-00001 in range!
2014-11-03T22:29:33.270Z - info: { _noble:
   { state: 'poweredOn',
     _bindings:
      { _addresses: [Object],
        _addresseTypes: [Object],
        _hciBle: [Object],
        _l2capBle: {},
        init: [Function],
        onStateChange: [Function],
        startScanning: [Function],
        onScanStart: [Function],
        stopScanning: [Function],
        onScanStop: [Function],
        onDiscover: [Function],
        connect: [Function],
        onConnect: [Function],
        disconnect: [Function],
        onDisconnect: [Function],
        exchangeMtu: [Function],
        onMtu: [Function],
        updateRssi: [Function],
        onRssi: [Function],
        discoverServices: [Function],
        onServicesDiscovered: [Function],
        discoverIncludedServices: [Function],
        onIncludedServicesDiscovered: [Function],
        discoverCharacteristics: [Function],
        onCharacteristicsDiscovered: [Function],
        read: [Function],
        onRead: [Function],
        write: [Function],
        onWrite: [Function],
        broadcast: [Function],
        onBroadcast: [Function],
        notify: [Function],
        onNotify: [Function],
        onNotification: [Function],
        discoverDescriptors: [Function],
        onDescriptorsDiscovered: [Function],
        readValue: [Function],
        onValueRead: [Function],
        writeValue: [Function],
        onValueWrite: [Function],
        readHandle: [Function],
        onHandleRead: [Function],
        writeHandle: [Function],
        onHandleWrite: [Function],
        onHandleNotify: [Function],
        _events: [Object],
        _scanServiceUuids: [] },
     _peripherals:
      { fe5c36f448ad: [Object],
        '7cd1c32a9b96': [Object],
        '5cf938d2c65c': [Object],
        d03972c9cda4: [Circular],
        e703c6df2100: [Object],
        fd76a0253018: [Object],
        e7727d87d867: [Object],
        f4f951c79119: [Object] },
     _services:
      { fe5c36f448ad: {},
        '7cd1c32a9b96': {},
        '5cf938d2c65c': {},
        d03972c9cda4: {},
        e703c6df2100: {},
        fd76a0253018: {},
        e7727d87d867: {},
        f4f951c79119: {} },
     _characteristics:
      { fe5c36f448ad: {},
        '7cd1c32a9b96': {},
        '5cf938d2c65c': {},
        d03972c9cda4: {},
        e703c6df2100: {},
        fd76a0253018: {},
        e7727d87d867: {},
        f4f951c79119: {} },
     _descriptors:
      { fe5c36f448ad: {},
        '7cd1c32a9b96': {},
        '5cf938d2c65c': {},
        d03972c9cda4: {},
        e703c6df2100: {},
        fd76a0253018: {},
        e7727d87d867: {},
        f4f951c79119: {} },
     _events: { stateChange: [Function], discover: [Function] },
     _discoveredPeripheralUUids:
      [ 'fe5c36f448ad',
        '7cd1c32a9b96',
        '5cf938d2c65c',
        'd03972c9cda4',
        'e703c6df2100',
        'fd76a0253018',
        'e7727d87d867',
        'f4f951c79119' ],
     _allowDuplicates: true },
  uuid: 'd03972c9cda4',
  advertisement:
   { localName: 'EK-00001',
     txPowerLevel: 4,
     manufacturerData: undefined,
     serviceData: [],
     serviceUuids: [ 'a495ff10c5b14b44b5121370f02d74de' ] },
  rssi: -72,
  services: null,
  state: 'disconnected' }

CRC library issue

Just a note, it seems that the CRC library made some changes since this library was last updated. In order for me to request and receive messages from Bean (temp, accel, etc...) I had to update line 74 to this: var crcString = crc.crc16ccitt(this.gst.slice(0,this.gst.length-2)).toString(16) and line 126 to this: var crcString = crc.crc16ccitt(gstBuffer).toString(16) in order for everything work correctly.

BLE example not working

I'm getting null values from the ble example (battery, serial, etc...)
Any ideas why this is happening?

Temperature command missing

The temperature command is missing:

MSG_ID_CC_TEMP_READ : new Buffer([0x20, 0x11]),

To recover the data onRead:

this.emit('temp', (data[5]) );

Multiple beans

Hello,

Thanks for your work, but, how to connect multiple beans ?

Thanks.

Noble issue?

Hi, I'm trying to install Ble-Bean, but I run into the following error:

[email protected] install /Users/lgaleana/hackathons/quadcopter/nodejs/node_modules/ble-bean/node_modules/noble
node-gyp rebuild

LINK(target) Release/hci-ble
Undefined symbols for architecture x86_64:
"_main", referenced from:
start in crt1.10.5.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [Release/hci-ble] Error 1
gyp ERR! build error
gyp ERR! stack Error: make failed with exit code: 2
gyp ERR! stack at ChildProcess.onExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:269:23)
gyp ERR! stack at ChildProcess.emit (events.js:110:17)
gyp ERR! stack at Process.ChildProcess._handle.onexit (child_process.js:1074:12)
gyp ERR! System Darwin 14.4.0
gyp ERR! command "node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /Users/lgaleana/hackathons/quadcopter/nodejs/node_modules/ble-bean/node_modules/noble
gyp ERR! node -v v0.12.7
gyp ERR! node-gyp -v v2.0.1
gyp ERR! not ok
npm ERR! Darwin 14.4.0
npm ERR! argv "node" "/usr/local/bin/npm" "install" "ble-bean"
npm ERR! node v0.12.7
npm ERR! npm v2.12.1
npm ERR! code ELIFECYCLE

npm ERR! [email protected] install: node-gyp rebuild
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] install script 'node-gyp rebuild'.
npm ERR! This is most likely a problem with the noble package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node-gyp rebuild
npm ERR! You can get their info via:
npm ERR! npm owner ls noble
npm ERR! There is likely additional logging output above.

LED is left on sometimes

The LED is left on sometimes on disconnect. It could that the disconnect message or the process.exit is reached before all the messages are sent.

connectedBean.setColor(new Buffer([0x00,0x00,0x00]), function(){
self.peripheral.disconnect( function(){
console.log('disconnected');
process.exit();
});
});

Adding a short timeout/delay solves the problem:

connectedBean.setColor(new Buffer([0x00,0x00,0x00]), function(){
//sometimes the led is left on, so we should give time for the led msg to arrive
setTimeout(function() {
self.peripheral.disconnect( function(){
console.log('disconnected');
process.exit();
});
}, 1000);
});

Maybe it would be even better on process.exit in case of that being the problem.

No need of RSP explicit command

When receiving the response message from the bean, the message can be identified by:

APP_MSG_RESPONSE_BIT is 0x80
messageId = (messageIdBytes[0]<<8) + messageIdBytes[1];
Then messageType = messageId & ~(APP_MSG_RESPONSE_BIT) will tell you the kind of response.

MSG_ID_CC_ACCEL_READ : new Buffer([0x20, 0x10]),
...20 90 ...

hex( ((0x20<<8) + 0x90) & ~(0x80) )
'0x2010'

MSG_ID_CC_TEMP_READ : new Buffer([0x20, 0x11]),
...20 91 ...

hex( ((0x20<<8) + 0x91) & ~(0x80) )
'0x2011'

So there is no need to have them as commands:
MSG_ID_CC_ACCEL_READ_RSP : new Buffer([0x20, 0x90]),
MSG_ID_CC_TEMP_READ_RSP : new Buffer([0x20, 0x91]),

Possible issue with temperature readings

I was testing my bean within a fridge and when the temperature fell to 0 it seems the reading overflows and hits 255 instead of showing a negative representation. This was done using the temp request function within bean.js just as was done in the examples.

screen shot 2015-03-19 at 09 45 06

Program receiving Serial Data AFTER sending serial data to Bean

So I am trying to use Node.js and the ble-bean library to send and receive serial data to the Bean. I am able to send Serial data just fine but receiving serial data AFTER writing serial data is a problem. I have written a basic Arduino sketch and Node.js program that essentially does an echo. The javascript program sends a value to the Bean and the Bean should send the same data back. Example code is below. The Arduino sketch works just fine on the bean when I use the Virtual Serial Monitor to send data to and receive data from the Bean. However, when using my Node.js program, I cannot receive data AFTER successfully sending data to the Bean. I have tried both on Mac OS X and Linix and get the same result, so I believe the issue may be with the ble-bean and/or the noble-device libraries.

Has anyone had any success reading data AFTER sending data to the Bean using the ble-bean Node.js module?

I believe that the issue may be related to the fact that the ble-bean library does not set the "\n" character as a delimiter/parser of the data from the bean, but I am not sure. With that said, when I use the PacketLogger bluetooth sniffer on Mac OS X, I do not see the notification come from the bean. However, when I use the Serial Monitor in the Arduino IDE, I do see the notification for the serial characteristic.

I have tried playing around with Node-RED and I am able to get send and receive serial data that way but I was hoping to write my own native Node.js code because I want to use some node modules that are not supported by Node-RED (and I was hoping to avoid porting them to Node-RED).

Any help would be greatly appreciated.

ble-bean library: https://github.com/jacobrosenthal/ble-bean
bean-serial library: https://github.com/monteslu/bean-serial/blob/master/index.js

Sample Code

Arduino sketch:

void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}

void loop() {
// put your main code here, to run repeatedly:
if(Serial.available() > 0) {
int readValue = Serial.parseInt();
Serial.println(readValue);
}
}

Node.js program

/*jslint node: true */
"use strict";

/*

  • This script requests the general BLE characteristics from the bean every second.
  • Requires a sketch on the Arduino to do a Serial.print() just like you were plugged
  • in over a serial cable. Any sketch will do.
    */

var Bean = require('ble-bean');
var SerialPort = require('bean-serial').SerialPort;
var serialPort;
var options = {
logging: true, // default to false
};

var intervalId;
var connectedBean;

Bean.discover(function(bean){
connectedBean = bean;
process.on('SIGINT', exitHandler.bind(this));

Problems with Bean+

I am using a Raspberry Pi 2 and a Bean+ that I have just received from Kickstarter. I am running bean_example.js. It sometimes works, but only if I switch the Bean+ off and on again. More often, it hangs after getting the message: noble: unknown peripheral 987bf3591a37 connected!

After getting that message, switching the Bean+ off and on halts the program with no output.

Sometimes it detects the Bean+, but says it cannot find the advertised service:
Error: service uuid a495ff10c5b14b44b5121370f02d74de not found!

Sometimes, when I switch the Bean+ on, the program just returns with no output.

(I started off using the node-red node, but that was even more unreliable due to these problems).

Has anyone else tried this code with a Bean+?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.