Comparar commits

..

4 Commits

Autor SHA1 Mensagem Data
AJ Keller 595c6dea5a Add: Coverage over sampleRate and numberOfChannels when info property is null 2016-12-05 10:48:17 -05:00
AJ Keller 89b5f35abc Add test for testSignal function 2016-12-05 10:48:17 -05:00
AJ Keller 9dd090df44 Add: test for print register settings 2016-12-05 10:47:52 -05:00
AJ Keller 8993a6c23b Enh: Drop factory Add: index.js Remove: Node 4 and 5 support 2016-12-05 10:47:52 -05:00
32 arquivos alterados com 4092 adições e 5333 exclusões
+2 -8
Ver Arquivo
@@ -1,12 +1,5 @@
language: node_js
node_js:
- "4.0"
- "4.1"
- "4.2"
- "4.3"
- "4.4"
- "4.5"
- "4.6"
- "5.11.0"
- "6.0"
- "6.1"
@@ -17,8 +10,9 @@ node_js:
- "6.6"
- "6.7"
- "6.8"
- "7.0"
- "7.1"
install:
- npm install --all
script:
- npm run lint
- npm run test-cov
+336 -363
Ver Arquivo
Diferenças do arquivo suprimidas por serem muito extensas Carregar Diff
+18 -32
Ver Arquivo
@@ -1,41 +1,27 @@
# 1.5.1
# 2.0.0
### New Features
* Add new example for Lab stream layer (#139) thanks @gabrielibagon
* `index.js` file allows for ES6 destructing
### Breaking changes
* Removed `impedanceCalculationForChannel()` and `impedanceCalculationForAllChannels` from `OpenBCISample.js`
### Breaking Changes
* Change name of `OpenBCIBoard` to `Cyton` to follow new naming convention.
Simply change:
```ecmascript 6
const OpenBCIBoard = require('openbci').OpenBCIBoard;
const ourBoard = new OpenBCIBoard();
```
```ecmascript 6
const Cyton = require('openbci').Cyton;
const ourBoard = new Cyton();
```
* Major change to how board is initialized with removal of `factory` paradigm.
* Drop support for Node 4 and 5 due to lack of EMACS 6
### Bug Fixes
* Fixes #28- Impedance not working properly.
# 1.5.0
### New Features
* New simulator option `simulatorDaisyModuleCanBeAttached` - Boolean, deafults to true, allows the simulation of the a hot swapped daisy board or simulates a misinformed module.
* New `EventEmitter` - `hardSet` - for when the module detects the board is not configured as the options for the module intended and tries to save itself. i.e. when the `daisy` option is `true` and a soft reset message is parsed and the module determines that a daisy was not detected, the module will emit `hardSet` then send an attach daisy command to recover. Either `error` will be emitted if unable to attach or `ready` will be emitted if success.
* Add example for streaming with `daisy` and `hardSet`.
### Breaking changes
* `.setInfoForBoardType()` changed to `.overrideInfoForBoardType()` to elevate it's dangerous nature.
* `.setMaxChannels()` changed to `.hardSetBoardType()` and input changed from numerical to string: 8 and 16 to `default` and `daisy` respectively.
### Bug Fixes
* Fixes #131 - 16 chan not working by sending a channel command and parsing the return.
* Fixed bug where end of transmission characters would not be ejected from buffer.
* Documentation error with `testSignal` function.
### Enhancements
* Separated radio tests from main board test file.
# 1.4.4
### New Features
* Set max number of channels for the board to use with `.setMaxChannels()` see readme.md
* Set the core info object that drives the module with `.overrideInfoForBoardType()` see readme.md
* Get info for the core object that drives the module with `.getInfo()` see readme.md
### Work In Progress
* Bug where daisy would sometimes not be recognized which destroyed all data.
* Add more tests for public API functions.
# 1.4.3
@@ -276,7 +262,7 @@ The second major release for the OpenBCI Node.js SDK brings major changes, impro
### Bug Fixes
* updates to README.me and comments to change ntp to sntp, because the two are similar, but not the same and we do not want to be misleading
* Extended [Stnp](https://www.npmjs.com/package/sntp) to main openBCIBoard.js
* Extended [Stnp](https://www.npmjs.com/package/sntp) to main openBCICyton.js
* Add `.sntpNow()` function to get ntp time.
# 0.3.1
+7 -6
Ver Arquivo
@@ -45,6 +45,7 @@ ourBoard.autoFindOpenBCIBoard().then(portName => {
*/
var readyFunc = () => {
// Get the sample rate after 'ready'
sampleRate = ourBoard.sampleRate();
if (stream) {
ourBoard.streamStart()
.catch(err => {
@@ -64,10 +65,10 @@ var sampleFunc = sample => {
ourBoard.on('ready', readyFunc);
ourBoard.on('sample', sampleFunc);
function exitHandler (options, err) {
if (options.cleanup) {
if (verbose) console.log('clean');
ourBoard.removeAllListeners();
/** Do additional clean up here */
}
if (err) console.log(err.stack);
@@ -80,14 +81,14 @@ function exitHandler (options, err) {
}
}
if (process.platform === 'win32') {
const rl = require('readline').createInterface({
if (process.platform === "win32") {
const rl = require("readline").createInterface({
input: process.stdin,
output: process.stdout
});
rl.on('SIGINT', function () {
process.emit('SIGINT');
rl.on("SIGINT", function () {
process.emit("SIGINT");
});
}
@@ -104,4 +105,4 @@ process.on('SIGINT', exitHandler.bind(null, {
// catches uncaught exceptions
process.on('uncaughtException', exitHandler.bind(null, {
exit: true
}));
}));
+1 -1
Ver Arquivo
@@ -13,6 +13,6 @@
"author": "AJ Keller",
"license": "MIT",
"dependencies": {
"openbci": "^1.5.0"
"openbci": "^1.4.1"
}
}
+9 -10
Ver Arquivo
@@ -27,12 +27,12 @@ ourBoard.autoFindOpenBCIBoard().then(portName => {
*/
ourBoard.connect(portName) // Port name is a serial port name, see `.listPorts()`
.then(() => {
ourBoard.on('ready', () => {
ourBoard.on('ready',() => {
ourBoard.streamStart();
ourBoard.on('sample', (sample) => {
ourBoard.on('sample',(sample) => {
/** Work with sample */
for (let i = 0; i < ourBoard.numberOfChannels(); i++) {
console.log(`Channel ${(i + 1)}: ${sample.channelData[i].toFixed(8)} Volts.`);
for (var i = 0; i < ourBoard.numberOfChannels(); i++) {
console.log("Channel " + (i + 1) + ": " + sample.channelData[i].toFixed(8) + " Volts.");
// prints to the console
// "Channel 1: 0.00001987 Volts."
// "Channel 2: 0.00002255 Volts."
@@ -51,7 +51,6 @@ ourBoard.autoFindOpenBCIBoard().then(portName => {
function exitHandler (options, err) {
if (options.cleanup) {
if (verbose) console.log('clean');
ourBoard.removeAllListeners();
/** Do additional clean up here */
}
if (err) console.log(err.stack);
@@ -61,14 +60,14 @@ function exitHandler (options, err) {
}
}
if (process.platform === 'win32') {
const rl = require('readline').createInterface({
if (process.platform === "win32") {
const rl = require("readline").createInterface({
input: process.stdin,
output: process.stdout
});
rl.on('SIGINT', function () {
process.emit('SIGINT');
rl.on("SIGINT", function () {
process.emit("SIGINT");
});
}
@@ -85,4 +84,4 @@ process.on('SIGINT', exitHandler.bind(null, {
// catches uncaught exceptions
process.on('uncaughtException', exitHandler.bind(null, {
exit: true
}));
}));
+1 -1
Ver Arquivo
@@ -13,6 +13,6 @@
"author": "AJ Keller",
"license": "MIT",
"dependencies": {
"openbci": "^1.5.0"
"openbci": "^1.4.1"
}
}
@@ -1,94 +0,0 @@
/**
* This is an example from the readme.md
* On windows you should run with PowerShell not git bash.
* Install
* [nodejs](https://nodejs.org/en/)
*
* To run:
* change directory to this file `cd examples/debug`
* do `npm install`
* then `npm start`
*/
var debug = false; // Pretty print any bytes in and out... it's amazing...
var verbose = true; // Adds verbosity to functions
var OpenBCIBoard = require('openbci').OpenBCIBoard;
var ourBoard = new OpenBCIBoard({
boardType: 'daisy',
debug: debug,
hardSet: true,
verbose: verbose
});
ourBoard.on('error', (err) => {
console.log(err);
});
ourBoard.autoFindOpenBCIBoard().then(portName => {
if (portName) {
/**
* Connect to the board with portName
* Only works if one board is plugged in
* i.e. ourBoard.connect(portName).....
*/
ourBoard.connect(portName) // Port name is a serial port name, see `.listPorts()`
.then(() => {
ourBoard.once('ready', () => {
ourBoard.streamStart();
ourBoard.on('sample', (sample) => {
/** Work with sample */
for (let i = 0; i < ourBoard.numberOfChannels(); i++) {
console.log(`Channel ${(i + 1)}: ${sample.channelData[i].toFixed(8)} Volts.`);
// prints to the console
// "Channel 1: 0.00001987 Volts."
// "Channel 2: 0.00002255 Volts."
// ...
// "Channel 16: -0.00001875 Volts."
}
});
});
});
} else {
/** Unable to auto find OpenBCI board */
console.log('Unable to auto find OpenBCI board');
}
});
function exitHandler (options, err) {
if (options.cleanup) {
if (verbose) console.log('clean');
ourBoard.removeAllListeners();
/** Do additional clean up here */
}
if (err) console.log(err.stack);
if (options.exit) {
if (verbose) console.log('exit');
ourBoard.disconnect().catch(console.log);
}
}
if (process.platform === 'win32') {
const rl = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
rl.on('SIGINT', function () {
process.emit('SIGINT');
});
}
// do something when app is closing
process.on('exit', exitHandler.bind(null, {
cleanup: true
}));
// catches ctrl+c event
process.on('SIGINT', exitHandler.bind(null, {
exit: true
}));
// catches uncaught exceptions
process.on('uncaughtException', exitHandler.bind(null, {
exit: true
}));
-18
Ver Arquivo
@@ -1,18 +0,0 @@
{
"name": "get-streaming-daisy",
"version": "1.0.0",
"description": "Get streaming with hard set daisy example",
"main": "getStreaming.js",
"scripts": {
"start": "node getStreamingDaisy.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"get"
],
"author": "AJ Keller",
"license": "MIT",
"dependencies": {
"openbci": "^1.5.0"
}
}
-142
Ver Arquivo
@@ -1,142 +0,0 @@
/**
* This is an example from the readme.md
* On windows you should run with PowerShell not git bash.
* Install
* [nodejs](https://nodejs.org/en/)
*
* To run:
* change directory to this file `cd examples/debug`
* do `npm install`
* then `npm start`
*/
var debug = false; // Pretty print any bytes in and out... it's amazing...
var verbose = true; // Adds verbosity to functions
var OpenBCIBoard = require('openbci').OpenBCIBoard;
var ourBoard = new OpenBCIBoard({
debug: debug,
verbose: verbose
});
var k = require('openbci').OpenBCIConstants;
let startedImpedance = false;
let iBuffer = [];
let count = 0;
const window = 50;
ourBoard.autoFindOpenBCIBoard().then(portName => {
if (portName) {
/**
* Connect to the board with portName
* Only works if one board is plugged in
* i.e. ourBoard.connect(portName).....
*/
ourBoard.connect(portName) // Port name is a serial port name, see `.listPorts()`
.then(() => {
ourBoard.on('ready', () => {
ourBoard.streamStart();
ourBoard.on('sample', (sample) => {
if (startedImpedance === false) {
startedImpedance = true;
k.getImpedanceSetter(1, false, true)
.then((commands) => {
return ourBoard.write(commands);
})
.then(() => {
console.log('wrote commands to board');
})
.catch((err) => {
console.log('errr', err);
});
}
/** Work with sample */
const chan1ValInVolts = sample.channelData[0];
// const impedance = chan1ValInVolts / k.OBCILeadOffDriveInAmps;
// console.log(`impedance:\t${impedance} kOhms`);
iBuffer.push(chan1ValInVolts);
count++;
if (count >= window) {
let max = 0.0; // sumSquared
for (let i = 0; i < window; i++) {
if (iBuffer[i] > max) {
max = iBuffer[i];
}
// sumSquared += iBuffer[i] * iBuffer[i];
}
let min = 0.0;
for (let i = 0; i < window; i++) {
if (iBuffer[i] < min) {
min = iBuffer[i];
}
// sumSquared += iBuffer[i] * iBuffer[i];
}
const vP2P = max - min; // peak to peak
console.log(`impedance: \t${vP2P / 2 / k.OBCILeadOffDriveInAmps}`);
// console.log(`impedance: ${vRms/k.OBCILeadOffDriveInAmps}`);
// const mean_squared = sumSquared / window;
// const root_mean_squared = Math.sqrt(mean_squared);
// console.log(`impedance: ${root_mean_squared/k.OBCILeadOffDriveInAmps}`);
count = 0;
iBuffer = [];
}
// console.log(`uV:\t${chan1ValInVolts/(10*6)}\nimpedance:\t${impedance}`);
});
});
});
} else {
/** Unable to auto find OpenBCI board */
console.log('Unable to auto find OpenBCI board');
}
});
function exitHandler (options, err) {
if (options.cleanup) {
if (verbose) console.log('clean');
/** Do additional clean up here */
ourBoard.disconnect().catch(console.log);
ourBoard.removeAllListeners();
}
if (err) console.log(err.stack);
if (options.exit) {
if (verbose) console.log('exit');
ourBoard.streamStop()
.then(() => {
process.exit(0);
})
.catch((err) => {
console.log(err);
process.exit(0);
});
}
}
if (process.platform === 'win32') {
const rl = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
rl.on('SIGINT', function () {
process.emit('SIGINT');
});
}
// do something when app is closing
process.on('exit', exitHandler.bind(null, {
cleanup: true
}));
// catches ctrl+c event
process.on('SIGINT', exitHandler.bind(null, {
exit: true
}));
// catches uncaught exceptions
process.on('uncaughtException', exitHandler.bind(null, {
exit: true
}));
-18
Ver Arquivo
@@ -1,18 +0,0 @@
{
"name": "get-streaming",
"version": "1.0.0",
"description": "Get impedance example",
"main": "getStreaming.js",
"scripts": {
"start": "node impedance.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"get"
],
"author": "AJ Keller",
"license": "MIT",
"dependencies": {
"openbci": "^1.5.0"
}
}
-90
Ver Arquivo
@@ -1,90 +0,0 @@
import json
import sys
import numpy as np
import time
import zmq
from pylsl import StreamInfo, StreamOutlet
class Interface:
def __init__(self, verbose=False):
context = zmq.Context()
self._socket = context.socket(zmq.PAIR)
self._socket.connect("tcp://localhost:3004")
self.verbose = verbose
if self.verbose:
print("Client Ready!")
# Send a quick message to tell node process we are up and running
self.send(json.dumps({
'action': 'started',
'command': 'status',
'message': time.time()*1000.0
}))
def send(self, msg):
"""
Sends a message to TCP server
:param msg: str
A string to send to node TCP server, could be a JSON dumps...
:return: None
"""
if self.verbose:
print('<- out ' + msg)
self._socket.send_string(msg)
return
def recv(self):
"""
Checks the ZeroMQ for data
:return: str
String of data
"""
return self._socket.recv()
def initializeOutlet(interface):
"""
Initializes and returns an LSL outlet
:param interface: Interface
the Python interface to communicate with node
:return: StreamOutlet
returns a labstreaminglayer StreamOutlet
"""
numChans = None
while not numChans:
msg = interface.recv()
try:
dicty = json.loads(msg)
numChans = dicty.get('numChans')
sampleRate = dicty.get('sampleRate')
except ValueError as e:
print(e)
info = StreamInfo('OpenBCI_EEG', 'EEG', numChans, sampleRate, 'float32', 'myuid34234')
outlet = StreamOutlet(info)
print('init')
return outlet
def main(argv):
verbose = False
# Create a new python interface.
interface = Interface(verbose)
# Create a new labstreaminglayer outlet
outlet = initializeOutlet(interface);
# Stream incoming data to LSL
while True:
msg = interface.recv()
try:
dicty = json.loads(msg)
message = dicty.get('message')
data=message.get('channelData')
timeStamp = message.get('timeStamp')
outlet.push_sample(data,timeStamp)
except BaseException as e:
print(e)
if __name__ == '__main__':
main(sys.argv[1:])
-157
Ver Arquivo
@@ -1,157 +0,0 @@
/**
* This is an example from the readme.md
* On windows you should run with PowerShell not git bash.
* Install
* [nodejs](https://nodejs.org/en/)
*
* To run:
* change directory to this file `cd examples/debug`
* do `npm install`
* then `npm start`
*/
var OpenBCIBoard = require('openbci').OpenBCIBoard;
var portPub = 'tcp://127.0.0.1:3004';
var zmq = require('zmq-prebuilt');
var socket = zmq.socket('pair');
var debug = false; // Pretty print any bytes in and out... it's amazing...
var verbose = true; // Adds verbosity to functions
var ourBoard = new OpenBCIBoard({
simulatorFirmwareVersion: 'v2',
debug: debug,
verbose: verbose
});
var timeSyncPossible = false;
var resyncPeriodMin = 1;
var secondsInMinute = 60;
var numChans = 8;
var resyncPeriod = ourBoard.sampleRate() * resyncPeriodMin * secondsInMinute;
ourBoard.autoFindOpenBCIBoard().then(portName => {
if (portName) {
/**
* Connect to the board with portName
* i.e. ourBoard.connect(portName).....
*/
// Call to connect
ourBoard.connect(portName)
.then(() => {
ourBoard.on('ready', () => {
// Get the sample rate after 'ready'
numChans = ourBoard.numberOfChannels();
if (numChans === 16) {
ourBoard.overrideInfoForBoardType('daisy');
}
// Find out if you can even time sync, you must be using v2 and this is only accurate after a `.softReset()` call which is called internally on `.connect()`. We parse the `.softReset()` response for the presence of firmware version 2 properties.
timeSyncPossible = ourBoard.usingVersionTwoFirmware();
sendToPython({'numChans': numChans, 'sampleRate': ourBoard.sampleRate()});
if (timeSyncPossible) {
ourBoard.streamStart()
.catch(err => {
console.log(`stream start: ${err}`);
});
} else {
console.log('not able to time sync');
}
});
})
.catch(err => {
console.log(`connect: ${err}`);
});
} else {
/** Unable to auto find OpenBCI board */
console.log('Unable to auto find OpenBCI board');
}
});
var sampleFunc = sample => {
if (sample._count % resyncPeriod === 0) {
ourBoard.syncClocksFull()
.then(syncObj => {
// Sync was successful
if (syncObj.valid) {
// Log the object to check it out!
console.log(`timeOffset`, syncObj.timeOffsetMaster);
} else {
// Retry it
console.log(`Was not able to sync... retry!`);
}
});
}
if (sample.timeStamp) { // true after the first successful sync
if (sample.timeStamp < 10 * 60 * 60 * 1000) { // Less than 10 hours
console.log(`Bad time sync ${sample.timeStamp}`);
} else {
sendToPython({
action: 'process',
command: 'sample',
message: sample
});
}
}
};
// Subscribe to your functions
ourBoard.on('sample', sampleFunc);
// ZMQ
socket.bind(portPub, function (err) {
if (err) throw err;
console.log(`bound to ${portPub}`);
});
/**
* Used to send a message to the Python process.
* @param {Object} interProcessObject The standard inter-process object.
* @return {None}
*/
var sendToPython = (interProcessObject, verbose) => {
if (verbose) {
console.log(`<- out ${JSON.stringify(interProcessObject)}`);
}
if (socket) {
socket.send(JSON.stringify(interProcessObject));
}
};
function exitHandler (options, err) {
if (options.cleanup) {
if (verbose) console.log('clean');
/** Do additional clean up here */
}
if (err) console.log(err.stack);
if (options.exit) {
if (verbose) console.log('exit');
ourBoard.disconnect().catch(console.log);
}
}
if (process.platform === 'win32') {
const rl = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
rl.on('SIGINT', function () {
process.emit('SIGINT');
});
}
// do something when app is closing
process.on('exit', exitHandler.bind(null, {
cleanup: true
}));
// catches ctrl+c event
process.on('SIGINT', exitHandler.bind(null, {
exit: true
}));
// catches uncaught exceptions
process.on('uncaughtException', exitHandler.bind(null, {
exit: true
}));
-31
Ver Arquivo
@@ -1,31 +0,0 @@
{
"name": "labstreaminglayer",
"version": "1.0.0",
"description": "labstreaminglayer example",
"main": "index.js",
"scripts": {
"start": "concurrently --kill-others \"python handoff.py\" \"node index.js\"",
"start-node": "node index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"python",
"openbci",
"node",
"labstreaminglayer",
"LSL"
],
"author": "AJ Keller",
"license": "MIT",
"dependencies": {
"openbci": "^1.4.2",
"zmq-prebuilt": "^2.1.0"
},
"devEngines": {
"node": "<=6.x",
"npm": ">=3.x"
},
"devDependencies": {
"concurrently": "^3.1.0"
}
}
-111
Ver Arquivo
@@ -1,111 +0,0 @@
# OpenBCI Node SDK to Lab Streaming Layer
## About
This code provides an example of how to stream OpenBCI data through the [lab streaming layer](https://github.com/sccn/labstreaminglayer) using the NodeJS SDK.
Follow the steps in this README to start streaming. The code is ready to run as-is, but can be modified and extended to customize how you are sending your data. This is designed to be used with the **OpenBCI Cyton** (for **Ganglion support**, see the [Ganglion Node SDK](https://github.com/OpenBCI/OpenBCI_NodeJS_Ganglion/tree/master/examples/labstreaminglayer)).
## Prerequisites
* [Python](https://www.python.org/downloads/)
* [ZeroMQ](http://zeromq.org/bindings:python)
```py
pip install pyzmq
```
* [Node.js LTS](https://nodejs.org/en/)
* [Lab Streaming Layer](https://github.com/sccn/labstreaminglayer)
```py
pip install pylsl
```
## Installation
First, install Python dependencies:
```bash
python setup.py install
```
Next, install NodeJS dependencies:
```bash
npm install
```
Note: depending on your computer settings, you may need to run as administrator or with `sudo`.
## Running
```
npm start
```
For running just the node, for example if you were running the python in a separate ide and debugging, it's useful.
```python
npm run start-node
```
Note: depending on your computer settings, you may need to run as administrator or with `sudo`.
## Writing Lab Streaming Layer Code
If you would like to use lab streaming layer in a custom OpenBCI NodeJS application, you must include an instance of the OpenBCI NodeJS library and an instance of a Python interface. A basic example is shown below:
index.js
```js
var OpenBCIBoard = require('openbci').OpenBCIBoard;
var portPub = 'tcp://127.0.0.1:3004';
var zmq = require('zmq-prebuilt');
var socket = zmq.socket('pair');
var ourBoard = new OpenBCIBoard();
socket.bind(portPub);
ourBoard.autoFindOpenBCIBoard().then(portName => {
if (portName) {
ourBoard.connect(portName) // Port name is a serial port name, see `.listPorts()`
.then(() => {
ourBoard.on('ready',() => {
ourBoard.streamStart();
ourBoard.on('sample',(sample) => {
if (socket) {
socket.send(JSON.stringify({message: sample}));
}
}
});
});
});
} else {
console.log('Unable to auto find OpenBCI board');
}
});
/* Insert additional exit handlers and cleanup below*/
```
handoff.py
```python
import json
import zmq
from pylsl import StreamInfo, StreamOutlet
# Create ZMQ socket
context = zmq.Context()
_socket = context.socket(zmq.PAIR)
_socket.connect("tcp://localhost:3004")
# Create a new labstreaminglayer outlet
numChans = 8;
sampleRate = 250;
info = StreamInfo('OpenBCI_EEG', 'EEG', numChans, sampleRate, 'float32', 'openbci_12345')
outlet = StreamOutlet(info)
# Stream incoming data to LSL
while True:
msg = _socket.recv()
try:
dicty = json.loads(msg)
message = dicty.get('message')
data=message.get('channelData')
timeStamp = message.get('timeStamp')
outlet.push_sample(data,timeStamp)
except BaseException as e:
print(e)
```
## Contributing
Please PR if you have code to contribute!
-12
Ver Arquivo
@@ -1,12 +0,0 @@
from setuptools import setup, find_packages
setup(name='openbci-node-labstreaminglayer',
version='0.0.1',
description='Labstreaminglayer with NodeJS',
url='',
author='AJ Keller',
author_email='pushtheworldllc@gmail.com',
license='MIT',
packages=find_packages(),
install_requires=['numpy', 'pyzmq','pylsl'],
zip_safe=False)
+17 -13
Ver Arquivo
@@ -10,20 +10,21 @@
* then `npm start`
*/
var OpenBCIBoard = require('openbci').OpenBCIBoard;
var portPub = 'tcp://127.0.0.1:3004';
var port_pub = 'tcp://127.0.0.1:3004';
var zmq = require('zmq-prebuilt');
var socket = zmq.socket('pair');
var simulate = false; // Sends synthetic data
var simulate = true; // Sends synthetic data
var debug = false; // Pretty print any bytes in and out... it's amazing...
var verbose = true; // Adds verbosity to functions
var ourBoard = new OpenBCIBoard({
simulate: simulate, // Uncomment to see how it works with simulator!
// simulate: simulate, // Uncomment to see how it works with simulator!
simulatorFirmwareVersion: 'v2',
debug: debug,
verbose: verbose
});
var sampleRate = 250; // Default to 250, ALWAYS verify with a call to `.sampleRate()` after 'ready' event!
var timeSyncPossible = false;
var resyncPeriodMin = 1;
var secondsInMinute = 60;
@@ -39,6 +40,9 @@ ourBoard.autoFindOpenBCIBoard().then(portName => {
ourBoard.connect(portName)
.then(() => {
ourBoard.on('ready', () => {
// Get the sample rate after 'ready'
sampleRate = ourBoard.sampleRate();
// Find out if you can even time sync, you must be using v2 and this is only accurate after a `.softReset()` call which is called internally on `.connect()`. We parse the `.softReset()` response for the presence of firmware version 2 properties.
timeSyncPossible = ourBoard.usingVersionTwoFirmware();
@@ -50,7 +54,7 @@ ourBoard.autoFindOpenBCIBoard().then(portName => {
} else {
console.log('not able to time sync');
}
});
})
})
.catch(err => {
console.log(`connect: ${err}`);
@@ -94,9 +98,9 @@ ourBoard.on('sample', sampleFunc);
// ZMQ fun
socket.bind(portPub, function (err) {
socket.bind(port_pub, function (err) {
if (err) throw err;
console.log(`bound to ${portPub}`);
console.log(`bound to ${port_pub}`);
});
/**
@@ -113,9 +117,9 @@ var sendToPython = (interProcessObject, verbose) => {
}
};
var receiveFromPython = (rawData) => {
var receiveFromPython = (raw_data) => {
try {
let body = JSON.parse(rawData); // five because `resp `
let body = JSON.parse(raw_data); // five because `resp `
processInterfaceObject(body);
} catch (err) {
console.log('in -> ' + 'bad json');
@@ -181,14 +185,14 @@ function exitHandler (options, err) {
}
}
if (process.platform === 'win32') {
const rl = require('readline').createInterface({
if (process.platform === "win32") {
const rl = require("readline").createInterface({
input: process.stdin,
output: process.stdout
});
rl.on('SIGINT', function () {
process.emit('SIGINT');
rl.on("SIGINT", function () {
process.emit("SIGINT");
});
}
@@ -205,4 +209,4 @@ process.on('SIGINT', exitHandler.bind(null, {
// catches uncaught exceptions
process.on('uncaughtException', exitHandler.bind(null, {
exit: true
}));
}));
+5 -6
Ver Arquivo
@@ -10,7 +10,6 @@
var OpenBCIBoard = require('openbci').OpenBCIBoard;
var ourBoard = new OpenBCIBoard({});
var verbose = true; // Adds verbosity to functions
var sampleRate = 250; // Default to 250, ALWAYS verify with a call to `.sampleRate()` after 'ready' event!
var timeSyncPossible = false;
@@ -101,14 +100,14 @@ function exitHandler (options, err) {
}
}
if (process.platform === 'win32') {
const rl = require('readline').createInterface({
if (process.platform === "win32") {
const rl = require("readline").createInterface({
input: process.stdin,
output: process.stdout
});
rl.on('SIGINT', function () {
process.emit('SIGINT');
rl.on("SIGINT", function () {
process.emit("SIGINT");
});
}
@@ -125,4 +124,4 @@ process.on('SIGINT', exitHandler.bind(null, {
// catches uncaught exceptions
process.on('uncaughtException', exitHandler.bind(null, {
exit: true
}));
}));
+2
Ver Arquivo
@@ -0,0 +1,2 @@
module.exports.Cyton = require('./openBCICyton');
module.exports.Constants = require('./openBCIConstants');
-2531
Ver Arquivo
Diferenças do arquivo suprimidas por serem muito extensas Carregar Diff
+12 -14
Ver Arquivo
@@ -156,11 +156,6 @@ const obciMiscSoftReset = 'v';
/** 16 Channel Commands */
const obciChannelMaxNumber8 = 'c';
const obciChannelMaxNumber16 = 'C';
const obciChannelMaxNumber8NoDaisyToRemove = '';
const obciChannelMaxNumber8SuccessDaisyRemoved = 'daisy removed';
const obciChannelMaxNumber16DaisyAlreadyAttached = '16';
const obciChannelMaxNumber16DaisyAttached = 'daisy attached16';
const obciChannelMaxNumber16NoDaisyAttached = 'no daisy to attach!8';
/** 60Hz line filter */
const obciFilterDisable = 'g';
@@ -208,6 +203,7 @@ const obciSimulatorFragmentationNone = 'none';
/** Possible Sample Rates */
const obciSampleRate125 = 125;
const obciSampleRate200 = 200;
const obciSampleRate250 = 250;
/** Max sample number */
@@ -237,9 +233,13 @@ const obciByteStart = 0xA0;
const obciByteStop = 0xC0;
/** Errors */
const errorNobleAlreadyScanning = 'Scan already under way';
const errorNobleNotAlreadyScanning = 'No scan started';
const errorNobleNotInPoweredOnState = 'Please turn blue tooth on.';
const errorInvalidByteLength = 'Invalid Packet Byte Length';
const errorInvalidByteStart = 'Invalid Start Byte';
const errorInvalidByteStop = 'Invalid Stop Byte';
const errorInvalidType = 'Invalid Type';
const errorTimeSyncIsNull = "'this.sync.curSyncObj' must not be null";
const errorTimeSyncNoComma = 'Missed the time sync sent confirmation. Try sync again';
const errorUndefinedOrNullInput = 'Undefined or Null Input';
@@ -340,10 +340,9 @@ const obciRadioBaudRateFastStr = 'fast';
/** Emitters */
const obciEmitterClose = 'close';
const obciEmitterDroppedPacket = 'droppedPacket';
const obciEmitterEot = 'eot';
const obciEmitterError = 'error';
const obciEmitterHardSet = 'hardSet';
const obciEmitterImpedanceArray = 'impedanceArray';
const obciEmitterMessage = 'message';
const obciEmitterQuery = 'query';
const obciEmitterRawDataPacket = 'rawDataPacket';
const obciEmitterReady = 'ready';
@@ -731,11 +730,6 @@ module.exports = {
/** 16 Channel Commands */
OBCIChannelMaxNumber8: obciChannelMaxNumber8,
OBCIChannelMaxNumber16: obciChannelMaxNumber16,
OBCIChannelMaxNumber8NoDaisyToRemove: obciChannelMaxNumber8NoDaisyToRemove,
OBCIChannelMaxNumber8SuccessDaisyRemoved: obciChannelMaxNumber8SuccessDaisyRemoved,
OBCIChannelMaxNumber16DaisyAlreadyAttached: obciChannelMaxNumber16DaisyAlreadyAttached,
OBCIChannelMaxNumber16DaisyAttached: obciChannelMaxNumber16DaisyAttached,
OBCIChannelMaxNumber16NoDaisyAttached: obciChannelMaxNumber16NoDaisyAttached,
/** Filters */
OBCIFilterDisable: obciFilterDisable,
OBCIFilterEnable: obciFilterEnable,
@@ -761,6 +755,7 @@ module.exports = {
},
/** Possible Sample Rates */
OBCISampleRate125: obciSampleRate125,
OBCISampleRate200: obciSampleRate200,
OBCISampleRate250: obciSampleRate250,
/** Max sample number */
OBCISampleNumberMax: obciSampleNumberMax,
@@ -770,9 +765,13 @@ module.exports = {
OBCIByteStart: obciByteStart,
OBCIByteStop: obciByteStop,
/** Errors */
OBCIErrorNobleAlreadyScanning: errorNobleAlreadyScanning,
OBCIErrorNobleNotAlreadyScanning: errorNobleNotAlreadyScanning,
OBCIErrorNobleNotInPoweredOnState: errorNobleNotInPoweredOnState,
OBCIErrorInvalidByteLength: errorInvalidByteLength,
OBCIErrorInvalidByteStart: errorInvalidByteStart,
OBCIErrorInvalidByteStop: errorInvalidByteStop,
OBCIErrorInvalidType: errorInvalidType,
OBCIErrorTimeSyncIsNull: errorTimeSyncIsNull,
OBCIErrorTimeSyncNoComma: errorTimeSyncNoComma,
OBCIErrorUndefinedOrNullInput: errorUndefinedOrNullInput,
@@ -906,10 +905,9 @@ module.exports = {
/** Emitters */
OBCIEmitterClose: obciEmitterClose,
OBCIEmitterDroppedPacket: obciEmitterDroppedPacket,
OBCIEmitterEot: obciEmitterEot,
OBCIEmitterError: obciEmitterError,
OBCIEmitterHardSet: obciEmitterHardSet,
OBCIEmitterImpedanceArray: obciEmitterImpedanceArray,
OBCIEmitterMessage: obciEmitterMessage,
OBCIEmitterQuery: obciEmitterQuery,
OBCIEmitterRawDataPacket: obciEmitterRawDataPacket,
OBCIEmitterReady: obciEmitterReady,
+2351
Ver Arquivo
Diferenças do arquivo suprimidas por serem muito extensas Carregar Diff
+129 -48
Ver Arquivo
@@ -1,7 +1,7 @@
'use strict';
var gaussian = require('gaussian');
var k = require('./openBCIConstants');
var StreamSearch = require('streamsearch');
const gaussian = require('gaussian');
const k = require('./openBCIConstants');
const StreamSearch = require('streamsearch');
/** Constants for interpreting the EEG data */
// Reference voltage for ADC in ADS1299.
@@ -13,6 +13,14 @@ const SCALE_FACTOR_ACCEL = 0.002 / Math.pow(2, 4);
const ACCEL_NUMBER_AXIS = 3;
// Default ADS1299 gains array
// For computing Goertzel Algorithm
// See: http://www.embedded.com/design/configurable-systems/4024443/The-Goertzel-Algorithm
// In the tutorial cited above, GOERTZEL_BLOCK_SIZE is referred to as N
const GOERTZEL_BLOCK_SIZE = 62;
const GOERTZEL_K_250 = Math.floor(0.5 + ((GOERTZEL_BLOCK_SIZE * k.OBCILeadOffFrequencyHz) / k.OBCISampleRate250));
const GOERTZEL_W_250 = ((2 * Math.PI) / GOERTZEL_BLOCK_SIZE) * GOERTZEL_K_250;
const GOERTZEL_COEFF_250 = 2 * Math.cos(GOERTZEL_W_250);
var sampleModule = {
/**
@@ -203,6 +211,59 @@ var sampleModule = {
},
floatTo3ByteBuffer,
floatTo2ByteBuffer,
/**
* @description Calculate the impedance for one channel only.
* @param sampleObject - Standard OpenBCI sample object
* @param channelNumber - Number, the channel you want to calculate impedance for.
* @returns {Promise} - Fulfilled with impedance value for the specified channel.
* @author AJ Keller
*/
impedanceCalculationForChannel: (sampleObject, channelNumber) => {
const sqrt2 = Math.sqrt(2);
return new Promise((resolve, reject) => {
if (sampleObject === undefined || sampleObject === null) reject('Sample Object cannot be null or undefined');
if (sampleObject.channelData === undefined || sampleObject.channelData === null) reject('Channel cannot be null or undefined');
if (channelNumber < 1 || channelNumber > k.OBCINumberOfChannelsDefault) reject('Channel number invalid.');
var index = channelNumber - 1;
if (sampleObject.channelData[index] < 0) {
sampleObject.channelData[index] *= -1;
}
var impedance = (sqrt2 * sampleObject.channelData[index]) / k.OBCILeadOffDriveInAmps;
// if (index === 0) console.log("Voltage: " + (sqrt2*sampleObject.channelData[index]) + " leadoff amps: " + k.OBCILeadOffDriveInAmps + " impedance: " + impedance)
resolve(impedance);
});
},
/**
* @description Calculate the impedance for all channels.
* @param sampleObject - Standard OpenBCI sample object
* @returns {Promise} - Fulfilled with impedances for the sample
* @author AJ Keller
*/
impedanceCalculationForAllChannels: sampleObject => {
const sqrt2 = Math.sqrt(2);
return new Promise((resolve, reject) => {
if (sampleObject === undefined || sampleObject === null) reject('Sample Object cannot be null or undefined');
if (sampleObject.channelData === undefined || sampleObject.channelData === null) reject('Channel cannot be null or undefined');
var sampleImpedances = [];
var numChannels = sampleObject.channelData.length;
for (var index = 0; index < numChannels; index++) {
if (sampleObject.channelData[index] < 0) {
sampleObject.channelData[index] *= -1;
}
var impedance = (sqrt2 * sampleObject.channelData[index]) / k.OBCILeadOffDriveInAmps;
sampleImpedances.push(impedance);
// if (index === 0) console.log("Voltage: " + (sqrt2*sampleObject.channelData[index]) + " leadoff amps: " + k.OBCILeadOffDriveInAmps + " impedance: " + impedance)
}
sampleObject.impedances = sampleImpedances;
resolve(sampleObject);
});
},
interpret16bitAsInt32: twoByteBuffer => {
var prefix = 0;
@@ -213,7 +274,7 @@ var sampleModule = {
return (prefix << 16) | (twoByteBuffer[0] << 8) | twoByteBuffer[1];
},
interpret24bitAsInt32: threeByteBuffer => {
interpret24bitAsInt32: (threeByteBuffer) => {
var prefix = 0;
if (threeByteBuffer[0] > 127) {
@@ -357,53 +418,73 @@ var sampleModule = {
scaleFactorAux: SCALE_FACTOR_ACCEL,
k,
/**
* Calculate the impedance
* @param sample {Object} - Standard sample
* @param impedanceTest {Object} - Impedance Object from openBCIBoard.js
* @return {null | Object} - Null if not enough samples have passed to calculate an accurate
*/
impedanceCalculateArray: (sample, impedanceTest) => {
impedanceTest.buffer.push(sample.channelData);
impedanceTest.count++;
* @description Use the Goertzel algorithm to calculate impedances
* @param sample - a sample with channelData Array
* @param goertzelObj - An object that was created by a call to this.goertzelNewObject()
* @returns {Array} - Returns an array if finished computing
*/
goertzelProcessSample: (sample, goertzelObj) => {
// calculate the goertzel values for all channels
for (var i = 0; i < goertzelObj.numberOfChannels; i++) {
var q0 = GOERTZEL_COEFF_250 * goertzelObj.q1[i] - goertzelObj.q2[i] + sample.channelData[i];
goertzelObj.q2[i] = goertzelObj.q1[i];
goertzelObj.q1[i] = q0;
if (impedanceTest.count >= impedanceTest.window) {
let output = [];
for (let i = 0; i < sample.channelData.length; i++) {
let max = 0.0; // sumSquared
for (let j = 0; j < impedanceTest.window; j++) {
if (impedanceTest.buffer[i][j] > max) {
max = impedanceTest.buffer[i][j];
}
}
let min = 0.0;
for (let j = 0; j < impedanceTest.window; j++) {
if (impedanceTest.buffer[i][j] < min) {
min = impedanceTest.buffer[i][j];
}
}
const vP2P = max - min; // peak to peak
output.push(vP2P / 2 / k.OBCILeadOffDriveInAmps);
}
impedanceTest.count = 0;
return output;
// console.log('Q1: ' + goertzelObj.q1[i] + ' Q2: ' + goertzelObj.q2[i])
}
// Increment the index counter
goertzelObj.index++;
// Have we iterated more times then block size?
if (goertzelObj.index > GOERTZEL_BLOCK_SIZE) {
var impedanceArray = [];
for (var j = 0; j < goertzelObj.numberOfChannels; j++) {
// Calculate the magnitude of the voltage
// var q1SQRD = goertzelObj.q1[j] * goertzelObj.q1[j];
// var q2SQRD = goertzelObj.q2[j] * goertzelObj.q2[j];
// var lastPart = goertzelObj.q1[j] * goertzelObj.q2[j] * GOERTZEL_COEFF_250;
// console.log('Chan ' + j + ', Q1^2: ' + q1SQRD + ', Q2^2: ' + q2SQRD + ', Last Part: ' + lastPart)
var voltage = Math.sqrt((goertzelObj.q1[j] * goertzelObj.q1[j]) + (goertzelObj.q2[j] * goertzelObj.q2[j]) - goertzelObj.q1[j] * goertzelObj.q2[j] * GOERTZEL_COEFF_250);
// Calculate the impedance r = v/i
var impedance = voltage / k.OBCILeadOffDriveInAmps;
// Push the impedance into the final array
impedanceArray.push(impedance);
// Reset the goertzel variables to get ready for the next iteration
goertzelObj.q1[j] = 0;
goertzelObj.q2[j] = 0;
}
// Reset the goertzel index counter
goertzelObj.index = 0;
// Pass out the impedance array
return impedanceArray;
} else {
// This reject is really just for debugging
return;
}
return null;
},
impedanceTestObjDefault: (impedanceTestObj) => {
let newObj = impedanceTestObj || {};
newObj['active'] = false;
newObj['buffer'] = [];
newObj['count'] = 0;
newObj['isTestingPInput'] = false;
newObj['isTestingNInput'] = false;
newObj['onChannel'] = 0;
newObj['sampleNumber'] = 0;
newObj['continuousMode'] = false;
newObj['impedanceForChannel'] = 0;
newObj['window'] = 40;
return newObj;
goertzelNewObject: numberOfChannels => {
// Object to help calculate the goertzel
var q1 = [];
var q2 = [];
for (var i = 0; i < numberOfChannels; i++) {
q1.push(0);
q2.push(0);
}
return {
q1: q1,
q2: q2,
index: 0,
numberOfChannels: numberOfChannels
};
},
GOERTZEL_BLOCK_SIZE,
samplePacket: sampleNumber => {
return new Buffer([0xA0, sampleNumberNormalize(sampleNumber), 0, 0, 1, 0, 0, 2, 0, 0, 3, 0, 0, 4, 0, 0, 5, 0, 0, 6, 0, 0, 7, 0, 0, 8, 0, 0, 0, 1, 0, 2, makeTailByteFromPacketType(k.OBCIStreamPacketStandardAccel)]);
},
@@ -1038,7 +1119,7 @@ function isSuccessInBuffer (dataBuffer) {
*/
function stripToEOTBuffer (dataBuffer) {
let indexOfEOT = dataBuffer.indexOf(k.OBCIParseEOT);
if (indexOfEOT >= 0) {
if (indexOfEOT > 0) {
indexOfEOT += k.OBCIParseEOT.length;
} else {
return dataBuffer;
+1 -26
Ver Arquivo
@@ -15,7 +15,6 @@ function OpenBCISimulatorFactory () {
alpha: true,
boardFailure: false,
daisy: false,
daisyCanBeAttached: true,
drift: 0,
firmwareVersion: [k.OBCIFirmwareV1, k.OBCIFirmwareV2],
fragmentation: [k.OBCISimulatorFragmentationNone, k.OBCISimulatorFragmentationRandom, k.OBCISimulatorFragmentationFullBuffers, k.OBCISimulatorFragmentationOneByOne],
@@ -121,7 +120,7 @@ function OpenBCISimulatorFactory () {
if (size > this.outputBuffered) size = this.outputBuffered;
// buffer is copied because presently openBCIBoard.js reuses it
// buffer is copied because presently openBCICyton.js reuses it
var outBuffer = new Buffer(this.outputBuffer.slice(0, size));
this.outputBuffer.copy(this.outputBuffer, 0, size, this.outputBuffered);
@@ -253,30 +252,6 @@ function OpenBCISimulatorFactory () {
}, 10);
}
break;
case k.OBCIChannelMaxNumber8:
if (this.options.daisy) {
this.options.daisy = false;
this._output(new Buffer(k.OBCIChannelMaxNumber8SuccessDaisyRemoved));
this._printEOT();
} else {
this._printEOT();
}
break;
case k.OBCIChannelMaxNumber16:
if (this.options.daisy) {
this._output(new Buffer(k.OBCIChannelMaxNumber16DaisyAlreadyAttached));
this._printEOT();
} else {
if (this.options.daisyCanBeAttached) {
this.options.daisy = true;
this._output(new Buffer(k.OBCIChannelMaxNumber16DaisyAttached));
this._printEOT();
} else {
this._output(new Buffer(k.OBCIChannelMaxNumber16NoDaisyAttached));
this._printEOT();
}
}
break;
default:
break;
}
+35
Ver Arquivo
@@ -0,0 +1,35 @@
module.exports = {
debugBytes
};
/**
* @description Output passed bytes on the console as a hexdump, if enabled
* @param prefix - label to show to the left of bytes
* @param data - bytes to output, a buffer or string
* @private
*/
function debugBytes (prefix, data) {
if (typeof data === 'string') data = new Buffer(data);
console.log('Debug bytes:');
for (var j = 0; j < data.length;) {
var hexPart = '';
var ascPart = '';
for (var end = Math.min(data.length, j + 16); j < end; ++j) {
var byt = data[j];
var hex = ('0' + byt.toString(16)).slice(-2);
hexPart += (((j & 0xf) === 0x8) ? ' ' : ' '); // puts an extra space 8 bytes in
hexPart += hex;
var asc = (byt >= 0x20 && byt < 0x7f) ? String.fromCharCode(byt) : '.';
ascPart += asc;
}
// pad to fixed width for alignment
hexPart = (hexPart + ' ').substring(0, 3 * 17);
console.log(prefix + ' ' + hexPart + '|' + ascPart + '|');
}
}
+6 -5
Ver Arquivo
@@ -1,10 +1,9 @@
{
"name": "openbci",
"version": "1.5.1",
"version": "2.0.0",
"description": "The official Node.js SDK for the OpenBCI Biosensor Board.",
"main": "openBCIBoard",
"main": "index.js",
"scripts": {
"lint": "semistandard | snazzy",
"start": "node index",
"test": "semistandard | snazzy && mocha test",
"test-cov": "istanbul cover ./node_modules/mocha/bin/_mocha -- -R spec && codecov"
@@ -17,10 +16,12 @@
"license": "MIT",
"dependencies": {
"buffer-equal": "^1.0.0",
"clone": "^2.0.0",
"gaussian": "^1.0.0",
"lodash": "^4.16.6",
"mathjs": "^3.3.0",
"performance-now": "^0.2.0",
"serialport": "4.0.1",
"serialport": "4.0.6",
"sntp": "^2.0.0",
"streamsearch": "^0.1.2"
},
@@ -37,7 +38,6 @@
"sandboxed-module": "^2.0.3",
"semistandard": "^9.0.0",
"sinon": "^1.17.2",
"sinon-as-promised": "^4.0.2",
"sinon-chai": "^2.8.0",
"snazzy": "^5.0.0"
},
@@ -55,6 +55,7 @@
"semistandard": {
"globals": [
"describe",
"xdescribe",
"context",
"before",
"beforeEach",
+6 -16
Ver Arquivo
@@ -443,13 +443,6 @@ describe('OpenBCIConstants', function () {
it('sets max of 16', function () {
assert.equal('C', k.OBCIChannelMaxNumber16);
});
it('has correct return messages', function () {
assert.equal('', k.OBCIChannelMaxNumber8NoDaisyToRemove);
assert.equal('daisy removed', k.OBCIChannelMaxNumber8SuccessDaisyRemoved);
assert.equal('16', k.OBCIChannelMaxNumber16DaisyAlreadyAttached);
assert.equal('daisy attached16', k.OBCIChannelMaxNumber16DaisyAttached);
assert.equal('no daisy to attach!8', k.OBCIChannelMaxNumber16NoDaisyAttached);
});
});
describe('On board filters', function () {
it('disable', function () {
@@ -771,6 +764,9 @@ describe('OpenBCIConstants', function () {
it('should be 125', function () {
assert.equal(125, k.OBCISampleRate125);
});
it('should be 250', function () {
assert.equal(200, k.OBCISampleRate200);
});
it('should be 250', function () {
assert.equal(250, k.OBCISampleRate250);
});
@@ -1447,18 +1443,15 @@ describe('OpenBCIConstants', function () {
it('Event Emitter Dropped Packet', function () {
assert.equal('droppedPacket', k.OBCIEmitterDroppedPacket);
});
it('Event Emitter EOT', function () {
assert.equal('eot', k.OBCIEmitterEot);
});
it('Event Emitter Error', function () {
assert.equal('error', k.OBCIEmitterError);
});
it('Event Emitter Hard Set', function () {
assert.equal('hardSet', k.OBCIEmitterHardSet);
});
it('Event Emitter Impedance Array', function () {
assert.equal('impedanceArray', k.OBCIEmitterImpedanceArray);
});
it('Event Emitter Message', function () {
assert.equal('message', k.OBCIEmitterMessage);
});
it('Event Emitter Query', function () {
assert.equal('query', k.OBCIEmitterQuery);
});
@@ -1472,7 +1465,4 @@ describe('OpenBCIConstants', function () {
assert.equal('sample', k.OBCIEmitterSample);
});
});
describe('Errors', function () {
});
});
+72 -83
Ver Arquivo
@@ -2,28 +2,28 @@
* Created by ajk on 12/15/15.
*/
'use strict';
var bluebirdChecks = require('./bluebirdChecks');
var openBCISample = require('../openBCISample');
var chai = require('chai');
var expect = chai.expect;
var assert = chai.assert;
var should = chai.should(); // eslint-disable-line no-unused-vars
const bluebirdChecks = require('./bluebirdChecks');
const openBCISample = require('../openBCISample');
const chai = require('chai');
const expect = chai.expect;
const assert = chai.assert;
const should = chai.should(); // eslint-disable-line no-unused-vars
var chaiAsPromised = require('chai-as-promised');
var sinonChai = require('sinon-chai');
const chaiAsPromised = require('chai-as-promised');
const sinonChai = require('sinon-chai');
chai.use(chaiAsPromised);
chai.use(sinonChai);
var bufferEqual = require('buffer-equal');
const bufferEqual = require('buffer-equal');
var k = openBCISample.k;
const k = require('../openBCIConstants');
const defaultChannelSettingsArray = k.channelSettingsArrayInit(k.OBCINumberOfChannelsDefault);
var sampleBuf = openBCISample.samplePacket();
const sampleBuf = openBCISample.samplePacket();
var accelArray;
let accelArray;
var channelScaleFactor = 4.5 / 24 / (Math.pow(2, 23) - 1);
const channelScaleFactor = 4.5 / 24 / (Math.pow(2, 23) - 1);
describe('openBCISample', function () {
beforeEach(function () {
@@ -600,28 +600,6 @@ describe('openBCISample', function () {
expect(sample.timeStamp).to.equal(time + timeOffset);
});
});
describe('#interpret24bitAsInt32', function () {
it('converts a small positive number', function () {
var buf1 = new Buffer([0x00, 0x06, 0x90]); // 0x000690 === 1680
var num = openBCISample.interpret24bitAsInt32(buf1);
assert.equal(num, 1680);
});
it('converts a large positive number', function () {
var buf1 = new Buffer([0x02, 0xC0, 0x01]); // 0x02C001 === 180225
var num = openBCISample.interpret24bitAsInt32(buf1);
assert.equal(num, 180225);
});
it('converts a small negative number', function () {
var buf1 = new Buffer([0xFF, 0xFF, 0xFF]); // 0xFFFFFF === -1
var num = openBCISample.interpret24bitAsInt32(buf1);
num.should.be.approximately(-1, 1);
});
it('converts a large negative number', function () {
var buf1 = new Buffer([0x81, 0xA1, 0x01]); // 0x81A101 === -8281855
var num = openBCISample.interpret24bitAsInt32(buf1);
num.should.be.approximately(-8281855, 1);
});
});
describe('#interpret16bitAsInt32', function () {
it('converts a small positive number', function () {
var buf1 = new Buffer([0x06, 0x90]); // 0x0690 === 1680
@@ -644,6 +622,28 @@ describe('openBCISample', function () {
assert.equal(num, -32351);
});
});
describe('#interpret24bitAsInt32', function () {
it('converts a small positive number', function () {
var buf1 = new Buffer([0x00, 0x06, 0x90]); // 0x000690 === 1680
var num = openBCISample.interpret24bitAsInt32(buf1);
assert.equal(num, 1680);
});
it('converts a large positive number', function () {
var buf1 = new Buffer([0x02, 0xC0, 0x01]); // 0x02C001 === 180225
var num = openBCISample.interpret24bitAsInt32(buf1);
assert.equal(num, 180225);
});
it('converts a small negative number', function () {
var buf1 = new Buffer([0xFF, 0xFF, 0xFF]); // 0xFFFFFF === -1
var num = openBCISample.interpret24bitAsInt32(buf1);
num.should.be.approximately(-1, 1);
});
it('converts a large negative number', function () {
var buf1 = new Buffer([0x81, 0xA1, 0x01]); // 0x81A101 === -8281855
var num = openBCISample.interpret24bitAsInt32(buf1);
num.should.be.approximately(-8281855, 1);
});
});
describe('#floatTo3ByteBuffer', function () {
it('converts random floats to a 3-byte buffer', function () {
var generateSample = openBCISample.randomSample(k.OBCINumberOfChannelsDefault, k.OBCISampleRate250);
@@ -708,6 +708,19 @@ describe('openBCISample', function () {
assert(passed, 'a sample with accel data was produced');
});
});
describe('#impedanceCalculationForChannel', function () {
it('rejects when undefined sampleObject', function (done) {
var bad;
openBCISample.impedanceCalculationForChannel(bad, 1).should.be.rejected.and.notify(done);
});
it('rejects when undefined channel number', function (done) {
var bad;
openBCISample.impedanceCalculationForChannel('taco', bad).should.be.rejected.and.notify(done);
});
it('rejects when invalid channel number', function (done) {
openBCISample.impedanceCalculationForChannel('taco', 69).should.be.rejected.and.notify(done);
});
});
describe('#impedanceSummarize', function () {
var impedanceArray = [];
var numberOfChannels = 8;
@@ -1208,21 +1221,6 @@ $$$`);
}
expect(openBCISample.stripToEOTBuffer(buf).toString()).to.equal(buf.toString());
});
it('should slice the buffer after just eot $$$', function () {
let eotBuf = null;
let bufPost = null;
if (k.getVersionNumber(process.version) >= 6) {
// From introduced in node version 6.x.x
eotBuf = Buffer.from(k.OBCIParseEOT);
bufPost = Buffer.from('tacos');
} else {
eotBuf = new Buffer(k.OBCIParseEOT);
bufPost = new Buffer('tacos');
}
let totalBuf = Buffer.concat([eotBuf, bufPost]);
expect(openBCISample.stripToEOTBuffer(totalBuf).toString()).to.equal(bufPost.toString());
});
it('should slice the buffer after eot $$$', function () {
let bufPre = null;
let eotBuf = null;
@@ -1257,43 +1255,34 @@ $$$`);
expect(openBCISample.stripToEOTBuffer(totalBuf)).to.equal(null);
});
});
describe('#impedanceTestObjDefault', function () {
it('should give a new impedance object', function () {
const expectedImpedanceObj = {
active: false,
buffer: [],
count: 0,
isTestingPInput: false,
isTestingNInput: false,
onChannel: 0,
sampleNumber: 0,
continuousMode: false,
impedanceForChannel: 0,
window: 40
};
expect(openBCISample.impedanceTestObjDefault()).to.deep.equal(expectedImpedanceObj);
});
});
describe('#impedanceCalculateArray', function () {
const numberOfChannels = k.OBCINumberOfChannelsDefault;
const newRandomSample = openBCISample.randomSample(numberOfChannels, k.OBCISampleRate250, false, 'none');
});
afterEach(() => bluebirdChecks.noPendingPromises());
describe('#goertzelProcessSample', function () {
var numberOfChannels = k.OBCINumberOfChannelsDefault;
var goertzelObj = openBCISample.goertzelNewObject(numberOfChannels);
var newRandomSample = openBCISample.randomSample(numberOfChannels, k.OBCISampleRate250);
it('should not produce an array of impedances till window', function () {
const impTestObj = openBCISample.impedanceTestObjDefault();
for (let i = 0; i < impTestObj.window - 1; i++) {
expect(openBCISample.impedanceCalculateArray(newRandomSample(i), impTestObj)).to.equal(null);
afterEach(() => bluebirdChecks.noPendingPromises());
it('produces an array of impedances', function (done) {
var passed = false;
for (var i = 0; i < openBCISample.GOERTZEL_BLOCK_SIZE + 1; i++) {
// console.log('Iteration ' + i)
var impedanceArray = openBCISample.goertzelProcessSample(newRandomSample(i), goertzelObj);
if (impedanceArray) {
// console.log('Impedance Array: ')
for (var j = 0; j < numberOfChannels; j++) {
console.log('Channel ' + (j + 1) + ': ' + impedanceArray[j].toFixed(8));
}
passed = true;
}
expect(impTestObj.buffer.length).to.equal(impTestObj.window - 1);
});
it('should produce and array of impedances at window', function () {
const impTestObj = openBCISample.impedanceTestObjDefault();
let impedanceArray = null;
for (let i = 0; i < impTestObj.window; i++) {
impedanceArray = openBCISample.impedanceCalculateArray(newRandomSample(i), impTestObj);
}
setTimeout(() => {
if (passed) {
done();
} else {
done('Failed to produce impedance array within block size + 1');
}
expect(impedanceArray.length).to.equal(numberOfChannels);
});
});
});
-949
Ver Arquivo
@@ -1,949 +0,0 @@
'use strict';
var bluebirdChecks = require('./bluebirdChecks');
var sinon = require('sinon'); // eslint-disable-line no-unused-vars
var chai = require('chai');
var expect = chai.expect;
var should = chai.should(); // eslint-disable-line no-unused-vars
var openBCIBoard = require('../openBCIBoard');
var openBCISample = openBCIBoard.OpenBCISample;
var k = openBCISample.k;
var chaiAsPromised = require('chai-as-promised');
var sinonChai = require('sinon-chai');
chai.use(chaiAsPromised);
chai.use(sinonChai);
describe('openbci-radios', function () {
this.timeout(2000);
var ourBoard, masterPortName;
before(function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard();
ourBoard.autoFindOpenBCIBoard()
.then(portName => {
ourBoard = null;
masterPortName = portName;
done();
})
.catch(() => {
ourBoard = null;
masterPortName = k.OBCISimulatorPortName;
done();
});
});
after(done => {
if (ourBoard) {
if (ourBoard['connected']) {
ourBoard.disconnect()
.then(() => {
done();
})
.catch(err => {
done(err);
});
} else {
done();
}
} else {
done();
}
});
describe('#radioChannelSet', function () {
afterEach(function (done) {
if (ourBoard.isConnected()) {
ourBoard.disconnect().then(() => {
done();
}).catch(() => done);
} else {
done();
}
});
afterEach(() => bluebirdChecks.noPendingPromises());
it('should not change the channel number if not connected', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true,
simulatorFirmwareVersion: 'v2'
});
ourBoard.radioChannelGet().should.be.rejected.and.notify(done);
});
it('should reject if streaming', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true,
simulatorFirmwareVersion: 'v2'
});
ourBoard.connect(k.OBCISimulatorPortName)
.then(() => {
ourBoard.once('ready', () => {
ourBoard.streamStart()
.then(() => {
ourBoard.radioChannelSet(1).then(() => {
done('should have rejected');
}).catch(() => {
done(); // Test pass
});
}).catch(err => done(err));
});
}).catch(err => done(err));
});
it('should reject if not firmware version 2', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true
});
ourBoard.connect(k.OBCISimulatorPortName)
.then(() => {
ourBoard.once('ready', () => {
ourBoard.radioChannelSet(1).should.be.rejected.and.notify(done);
});
}).catch(err => done(err));
});
it('should reject if a number is not sent as input', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true,
simulatorFirmwareVersion: 'v2'
});
ourBoard.connect(k.OBCISimulatorPortName)
.then(() => {
ourBoard.once('ready', () => {
ourBoard.radioChannelSet('1').should.be.rejected.and.notify(done);
});
}).catch(err => done(err));
});
it('should reject if no channel number is presented as arg', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true,
simulatorFirmwareVersion: 'v2'
});
ourBoard.connect(k.OBCISimulatorPortName)
.then(() => {
ourBoard.once('ready', () => {
ourBoard.radioChannelSet().should.be.rejected.and.notify(done);
});
}).catch(err => done(err));
});
it('should reject if the requested new channel number is lower than 0', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true,
simulatorFirmwareVersion: 'v2'
});
ourBoard.connect(k.OBCISimulatorPortName)
.then(() => {
ourBoard.once('ready', () => {
ourBoard.radioChannelSet(-1).should.be.rejected.and.notify(done);
});
}).catch(err => done(err));
});
it('should reject if the requested new channel number is higher than 25', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true,
simulatorFirmwareVersion: 'v2'
});
ourBoard.connect(k.OBCISimulatorPortName)
.then(() => {
ourBoard.once('ready', () => {
ourBoard.radioChannelSet(26).should.be.rejected.and.notify(done);
});
}).catch(err => done(err));
});
it('should not change the channel if the board is not communicating with the host', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true,
simulatorBoardFailure: true,
simulatorFirmwareVersion: 'v2'
});
ourBoard.connect(k.OBCISimulatorPortName)
.then(() => {
ourBoard.once('ready', () => {
ourBoard.radioChannelSet(1).should.be.rejected.and.notify(done);
});
}).catch(err => done(err));
});
it('should change the channel if connected, not steaming, and using firmware version 2+', function (done) {
var newChannelNumber = 2;
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true,
simulatorFirmwareVersion: 'v2'
});
ourBoard.connect(k.OBCISimulatorPortName)
.then(() => {
ourBoard.once('ready', () => {
ourBoard.radioChannelSet(newChannelNumber).then(channelNumber => {
expect(channelNumber).to.be.equal(newChannelNumber);
done();
}).catch(err => done(err));
});
}).catch(err => done(err));
});
});
describe('#radioChannelSetHostOverride', function () {
afterEach(function (done) {
if (ourBoard.isConnected()) {
ourBoard.disconnect().then(() => {
done();
}).catch(() => done);
} else {
done();
}
});
afterEach(() => bluebirdChecks.noPendingPromises());
it('should not change the channel number if not connected', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true,
simulatorFirmwareVersion: 'v2'
});
ourBoard.radioChannelSetHostOverride().should.be.rejected.and.notify(done);
});
it('should reject if streaming', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true,
simulatorFirmwareVersion: 'v2'
});
ourBoard.connect(k.OBCISimulatorPortName)
.then(() => {
ourBoard.once('ready', () => {
ourBoard.streamStart()
.then(() => {
ourBoard.radioChannelSetHostOverride(1).then(() => {
done('should have rejected');
}).catch(() => {
done(); // Test pass
});
}).catch(err => done(err));
});
}).catch(err => done(err));
});
it('should reject if a number is not sent as input', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true,
simulatorFirmwareVersion: 'v2'
});
ourBoard.connect(k.OBCISimulatorPortName)
.then(() => {
ourBoard.once('ready', () => {
ourBoard.radioChannelSetHostOverride('1').should.be.rejected.and.notify(done);
});
}).catch(err => done(err));
});
it('should reject if no channel number is presented as arg', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true,
simulatorFirmwareVersion: 'v2'
});
ourBoard.connect(k.OBCISimulatorPortName)
.then(() => {
ourBoard.once('ready', () => {
ourBoard.radioChannelSetHostOverride().should.be.rejected.and.notify(done);
});
}).catch(err => done(err));
});
it('should reject if the requested new channel number is lower than 0', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true,
simulatorFirmwareVersion: 'v2'
});
ourBoard.connect(k.OBCISimulatorPortName)
.then(() => {
ourBoard.once('ready', () => {
ourBoard.radioChannelSetHostOverride(-1).should.be.rejected.and.notify(done);
});
}).catch(err => done(err));
});
it('should reject if the requested new channel number is higher than 25', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true,
simulatorFirmwareVersion: 'v2'
});
ourBoard.connect(k.OBCISimulatorPortName)
.then(() => {
ourBoard.once('ready', () => {
ourBoard.radioChannelSetHostOverride(26).should.be.rejected.and.notify(done);
});
}).catch(err => done(err));
});
it('should change the channel if connected, not steaming, and using firmware version 2+', function (done) {
var newChannelNumber = 2;
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true,
simulatorFirmwareVersion: 'v2'
});
ourBoard.connect(k.OBCISimulatorPortName)
.then(() => {
ourBoard.once('ready', () => {
ourBoard.radioChannelSetHostOverride(newChannelNumber).then(channelNumber => {
expect(channelNumber).to.be.equal(newChannelNumber);
done();
}).catch(err => done(err));
});
}).catch(err => done(err));
});
});
describe('#radioChannelGet', function () {
afterEach(function (done) {
if (ourBoard.isConnected()) {
ourBoard.disconnect().then(() => {
done();
}).catch(() => done);
} else {
done();
}
});
afterEach(() => bluebirdChecks.noPendingPromises());
it('should not query if not connected', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true
});
ourBoard.radioChannelGet().should.be.rejected.and.notify(done);
});
it('should not query if streaming', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true
});
ourBoard.connect(k.OBCISimulatorPortName)
.then(() => {
ourBoard.once('ready', () => {
ourBoard.streamStart()
.then(() => {
ourBoard.radioChannelGet().then(() => {
done('should have rejected');
}).catch(() => {
done(); // Test pass
});
}).catch(err => done(err));
});
}).catch(err => done(err));
});
it('should not query if not firmware version 2', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true
});
ourBoard.connect(k.OBCISimulatorPortName)
.then(() => {
ourBoard.once('ready', () => {
ourBoard.radioChannelGet().should.be.rejected.and.notify(done);
});
}).catch(err => done(err));
});
it('should query if firmware version 2', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true,
simulatorFirmwareVersion: 'v2'
});
ourBoard.connect(k.OBCISimulatorPortName)
.then(() => {
ourBoard.once('ready', () => {
ourBoard.radioChannelGet().then(res => {
expect(res.channelNumber).to.be.within(k.OBCIRadioChannelMin, k.OBCIRadioChannelMax);
done();
}).catch(err => done(err));
});
}).catch(err => done(err));
});
it('should get message even if the board is not communicating with dongle', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true,
simulatorBoardFailure: true,
simulatorFirmwareVersion: 'v2'
});
ourBoard.connect(k.OBCISimulatorPortName)
.then(() => {
ourBoard.once('ready', () => {
ourBoard.radioChannelGet().should.be.rejected.and.notify(done);
});
}).catch(err => done(err));
});
});
describe('#radioPollTimeSet', function () {
afterEach(function (done) {
if (ourBoard.isConnected()) {
ourBoard.disconnect().then(() => {
done();
}).catch(() => done);
} else {
done();
}
});
afterEach(() => bluebirdChecks.noPendingPromises());
it('should not change the channel number if not connected', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true,
simulatorFirmwareVersion: 'v2'
});
ourBoard.radioPollTimeSet().should.be.rejected.and.notify(done);
});
it('should reject if streaming', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true,
simulatorFirmwareVersion: 'v2'
});
ourBoard.connect(k.OBCISimulatorPortName)
.then(() => {
ourBoard.once('ready', () => {
ourBoard.streamStart()
.then(() => {
ourBoard.radioPollTimeSet(1).then(() => {
done('should have rejected');
}).catch(() => {
done(); // Test pass
});
}).catch(err => done(err));
});
}).catch(err => done(err));
});
it('should reject if not firmware version 2', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true
});
ourBoard.connect(k.OBCISimulatorPortName)
.then(() => {
ourBoard.once('ready', () => {
ourBoard.radioPollTimeSet(1).should.be.rejected.and.notify(done);
});
}).catch(err => done(err));
});
it('should reject if a number is not sent as input', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true,
simulatorFirmwareVersion: 'v2'
});
ourBoard.connect(k.OBCISimulatorPortName)
.then(() => {
ourBoard.once('ready', () => {
ourBoard.radioPollTimeSet('1').should.be.rejected.and.notify(done);
});
}).catch(err => done(err));
});
it('should reject if no poll time is presented as arg', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true,
simulatorFirmwareVersion: 'v2'
});
ourBoard.connect(k.OBCISimulatorPortName)
.then(() => {
ourBoard.once('ready', () => {
ourBoard.radioPollTimeSet().should.be.rejected.and.notify(done);
});
}).catch(err => done(err));
});
it('should reject if the requested new poll time is lower than 0', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true,
simulatorFirmwareVersion: 'v2'
});
ourBoard.connect(k.OBCISimulatorPortName)
.then(() => {
ourBoard.once('ready', () => {
ourBoard.radioPollTimeSet(-1).should.be.rejected.and.notify(done);
});
}).catch(err => done(err));
});
it('should reject if the requested new poll time is higher than 255', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true,
simulatorFirmwareVersion: 'v2'
});
ourBoard.connect(k.OBCISimulatorPortName)
.then(() => {
ourBoard.once('ready', () => {
ourBoard.radioPollTimeSet(256).should.be.rejected.and.notify(done);
});
}).catch(err => done(err));
});
it('should not change the poll time if the board is not communicating with the host', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true,
simulatorBoardFailure: true,
simulatorFirmwareVersion: 'v2'
});
ourBoard.connect(k.OBCISimulatorPortName)
.then(() => {
ourBoard.once('ready', () => {
ourBoard.radioPollTimeSet(1).should.be.rejected.and.notify(done);
});
}).catch(err => done(err));
});
it('should change the poll time if connected, not steaming, and using firmware version 2+', function (done) {
var newPollTime = 69;
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true,
simulatorFirmwareVersion: 'v2'
});
ourBoard.connect(k.OBCISimulatorPortName)
.then(() => {
ourBoard.once('ready', () => {
ourBoard.radioPollTimeSet(newPollTime).then(() => {
done();
}).catch(err => {
done(err);
});
});
}).catch(err => done(err));
});
});
describe('#radioPollTimeGet', function () {
afterEach(function (done) {
if (ourBoard.isConnected()) {
ourBoard.disconnect().then(() => {
done();
}).catch(() => done);
} else {
done();
}
});
afterEach(() => bluebirdChecks.noPendingPromises());
it('should not query if not connected', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true
});
ourBoard.radioPollTimeGet().should.be.rejected.and.notify(done);
});
it('should not query if streaming', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true
});
ourBoard.connect(k.OBCISimulatorPortName)
.then(() => {
ourBoard.once('ready', () => {
ourBoard.streamStart()
.then(() => {
ourBoard.radioPollTimeGet().then(() => {
done('should have rejected');
}).catch(() => {
done(); // Test pass
});
}).catch(err => done(err));
});
}).catch(err => done(err));
});
it('should not query if not firmware version 2', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true
});
ourBoard.connect(k.OBCISimulatorPortName)
.then(() => {
ourBoard.once('ready', () => {
ourBoard.radioPollTimeGet().should.be.rejected.and.notify(done);
});
}).catch(err => done(err));
});
it('should query if firmware version 2', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true,
simulatorFirmwareVersion: 'v2'
});
ourBoard.connect(k.OBCISimulatorPortName)
.then(() => {
ourBoard.once('ready', () => {
ourBoard.radioPollTimeGet().then(pollTime => {
expect(pollTime).to.be.greaterThan(0);
done();
}).catch(err => done(err));
});
}).catch(err => done(err));
});
it('should get failure message if the board is not communicating with dongle', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true,
simulatorBoardFailure: true,
simulatorFirmwareVersion: 'v2'
});
ourBoard.connect(k.OBCISimulatorPortName)
.then(() => {
ourBoard.once('ready', () => {
ourBoard.radioPollTimeGet().should.be.rejected.and.notify(done);
});
}).catch(err => done(err));
});
});
describe('#radioBaudRateSet', function () {
afterEach(function (done) {
if (ourBoard.isConnected()) {
ourBoard.disconnect().then(() => {
done();
}).catch(() => done);
} else {
done();
}
});
afterEach(() => bluebirdChecks.noPendingPromises());
it('should not try to set baud rate if not connected', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true
});
ourBoard.radioBaudRateSet('default').should.be.rejected.and.notify(done);
});
it('should reject if no input', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true
});
ourBoard.radioBaudRateSet().should.be.rejected.and.notify(done);
});
it('should be rejected if input type incorrect', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true
});
ourBoard.radioBaudRateSet(1).should.be.rejected.and.notify(done);
});
it('should not try to change the baud rate if streaming', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true
});
ourBoard.connect(k.OBCISimulatorPortName)
.then(() => {
ourBoard.once('ready', () => {
ourBoard.streamStart()
.then(() => {
ourBoard.radioBaudRateSet('default').then(() => {
done('should have rejected');
}).catch(() => {
done(); // Test pass
});
}).catch(err => done(err));
});
}).catch(err => done(err));
});
it('should not try to change the baud rate if not firmware version 2', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true
});
ourBoard.connect(k.OBCISimulatorPortName)
.then(() => {
ourBoard.once('ready', () => {
ourBoard.radioBaudRateSet('default').should.be.rejected.and.notify(done);
});
}).catch(err => done(err));
});
it('should set the baud rate to default if firmware version 2', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true,
simulatorFirmwareVersion: 'v2'
});
ourBoard.connect(k.OBCISimulatorPortName)
.then(() => {
ourBoard.once('ready', () => {
ourBoard.radioBaudRateSet('default').then(baudrate => {
expect(baudrate).to.be.equal(115200);
done();
}).catch(err => done(err));
});
}).catch(err => done(err));
});
it('should set the baud rate to fast if firmware version 2', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true,
simulatorFirmwareVersion: 'v2'
});
ourBoard.connect(k.OBCISimulatorPortName)
.then(() => {
ourBoard.once('ready', () => {
ourBoard.radioBaudRateSet('fast').then(baudrate => {
expect(baudrate).to.be.equal(230400);
done();
}).catch(err => done(err));
});
}).catch(err => done(err));
});
});
describe('#radioSystemStatusGet', function () {
afterEach(function (done) {
if (ourBoard.isConnected()) {
ourBoard.disconnect().then(() => {
done();
}).catch(() => done);
} else {
done();
}
});
afterEach(() => bluebirdChecks.noPendingPromises());
it('should not get system status if not connected', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true
});
ourBoard.radioSystemStatusGet().should.be.rejected.and.notify(done);
});
it('should not get system status if streaming', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true
});
ourBoard.connect(k.OBCISimulatorPortName)
.then(() => {
ourBoard.once('ready', () => {
ourBoard.streamStart()
.then(() => {
ourBoard.radioSystemStatusGet().then(() => {
done('should have rejected');
}).catch(() => {
done(); // Test pass
});
}).catch(err => done(err));
});
}).catch(err => done(err));
});
it('should not get system status if not firmware version 2', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true
});
ourBoard.connect(k.OBCISimulatorPortName)
.then(() => {
ourBoard.once('ready', () => {
ourBoard.radioSystemStatusGet().should.be.rejected.and.notify(done);
});
}).catch(err => done(err));
});
it('should get up system status if firmware version 2', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true,
simulatorFirmwareVersion: 'v2'
});
ourBoard.connect(k.OBCISimulatorPortName)
.then(() => {
ourBoard.once('ready', () => {
ourBoard.radioSystemStatusGet().then(isUp => {
expect(isUp).to.be.true;
done();
}).catch(err => done(err));
});
}).catch(err => done(err));
});
it('should get down system status if firmware version 2', function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulate: true,
simulatorFirmwareVersion: 'v2',
simulatorBoardFailure: true
});
ourBoard.connect(k.OBCISimulatorPortName)
.then(() => {
ourBoard.once('ready', () => {
ourBoard.radioSystemStatusGet().then(isUp => {
expect(isUp).to.be.false;
done();
}).catch(err => done(err));
});
}).catch(err => done(err));
});
});
describe('#radioTests', function () {
this.timeout(0);
before(function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
verbose: true,
simulatorFirmwareVersion: 'v2',
simulatorFragmentation: k.OBCISimulatorFragmentationRandom
});
ourBoard.connect(masterPortName).catch(err => done(err));
ourBoard.once('ready', () => {
done();
});
});
after(function (done) {
if (ourBoard.isConnected()) {
ourBoard.disconnect().then(() => {
done();
});
} else {
done();
}
});
after(() => bluebirdChecks.noPendingPromises());
it('should be able to get the channel number', function (done) {
// Don't test if not using v2
if (!ourBoard.usingVersionTwoFirmware()) return done();
// The channel number should be between 0 and 25. Those are hard limits.
ourBoard.radioChannelGet().then(res => {
expect(res.channelNumber).to.be.within(0, 25);
done();
}).catch(err => done(err));
});
it('should be able to set the channel to 1', function (done) {
// Don't test if not using v2
if (!ourBoard.usingVersionTwoFirmware()) return done();
ourBoard.radioChannelSet(1).then(channelNumber => {
expect(channelNumber).to.equal(1);
done();
}).catch(err => done(err));
});
it('should be able to set the channel to 2', function (done) {
// Don't test if not using v2
if (!ourBoard.usingVersionTwoFirmware()) return done();
ourBoard.radioChannelSet(2).then(channelNumber => {
expect(channelNumber).to.equal(2);
done();
}).catch(err => done(err));
});
it('should be able to set the channel to 25', function (done) {
// Don't test if not using v2
if (!ourBoard.usingVersionTwoFirmware()) return done();
ourBoard.radioChannelSet(25).then(channelNumber => {
expect(channelNumber).to.equal(25);
done();
}).catch(err => done(err));
});
it('should be able to set the channel to 5', function (done) {
// Don't test if not using v2
if (!ourBoard.usingVersionTwoFirmware()) return done();
ourBoard.radioChannelSet(5).then(channelNumber => {
expect(channelNumber).to.equal(5);
done();
}).catch(err => done(err));
});
it('should be able to override host channel number, verify system is down, set the host back and verify system is up', function (done) {
// Don't test if not using v2
if (!ourBoard.usingVersionTwoFirmware()) return done();
var systemChanNumber = 0;
var newChanNum = 0;
// var timey = Date.now()
// Get the current system channel
ourBoard.radioChannelGet()
.then(res => {
// Store it
systemChanNumber = res.channelNumber;
// console.log(`system channel number: ${res.channelNumber}`)
if (systemChanNumber === 25) {
newChanNum = 24;
} else {
newChanNum = systemChanNumber + 1;
}
// Call to change just the host
return ourBoard.radioChannelSetHostOverride(newChanNum);
})
.then(newChanNumActual => {
expect(newChanNumActual).to.equal(newChanNum);
// timey = Date.now()
// console.log(`new chan ${newChanNumActual} got`, timey, '0ms')
return new Promise((resolve, reject) => {
setTimeout(function () {
// console.log(`get status`, Date.now(), `${Date.now() - timey}ms`)
ourBoard.radioSystemStatusGet().then(isUp => {
// console.log('resolving', Date.now(), `${Date.now() - timey}ms`)
resolve(isUp);
})
.catch(err => {
reject(err);
});
}, 270); // Should be accurate after 270 seconds
});
})
.then(isUp => {
// console.log(`isUp test`, Date.now(), `${Date.now() - timey}ms`)
expect(isUp).to.be.false;
return ourBoard.radioChannelSetHostOverride(systemChanNumber); // Set back to good
})
.then(newChanNumActual => {
// Verify we set it back to normal
expect(newChanNumActual).to.equal(systemChanNumber);
return ourBoard.radioSystemStatusGet();
})
.then(isUp => {
expect(isUp).to.be.true;
done();
})
.catch(err => done(err));
});
it('should be able to get the poll time', function (done) {
// Don't test if not using v2
if (!ourBoard.usingVersionTwoFirmware()) return done();
ourBoard.radioPollTimeGet().should.eventually.be.greaterThan(0).and.notify(done);
});
it('should be able to set the poll time', function (done) {
// Don't test if not using v2
if (!ourBoard.usingVersionTwoFirmware()) return done();
ourBoard.radioPollTimeSet(80).should.become(80).and.notify(done);
});
it('should be able to change to default baud rate', function (done) {
// Don't test if not using v2
if (!ourBoard.usingVersionTwoFirmware()) return done();
ourBoard.radioBaudRateSet('default').should.become(115200).and.notify(done);
});
it('should be able to change to fast baud rate', function (done) {
// Don't test if not using v2
if (!ourBoard.usingVersionTwoFirmware()) return done();
ourBoard.radioBaudRateSet('fast').then(newBaudRate => {
expect(newBaudRate).to.equal(230400);
return ourBoard.radioBaudRateSet('default');
}).then(() => {
done();
}).catch(err => done(err));
});
it('should be able to set the system status', function (done) {
// Don't test if not using v2
if (!ourBoard.usingVersionTwoFirmware()) return done();
ourBoard.radioSystemStatusGet().then(isUp => {
expect(isUp).to.be.true;
done();
}).catch(err => done(err));
});
});
});
@@ -1,13 +1,13 @@
'use strict';
var bluebirdChecks = require('./bluebirdChecks');
var chai = require('chai');
var should = chai.should(); // eslint-disable-line no-unused-vars
var openBCIBoard = require('../openBCIBoard');
var openBCISample = openBCIBoard.OpenBCISample;
var k = openBCISample.k;
const bluebirdChecks = require('./bluebirdChecks');
const chai = require('chai');
const should = chai.should(); // eslint-disable-line no-unused-vars
const Cyton = require('../openBCICyton');
const openBCISample = require('../openBCISample');
const k = openBCISample.k;
var chaiAsPromised = require('chai-as-promised');
var sinonChai = require('sinon-chai');
const chaiAsPromised = require('chai-as-promised');
const sinonChai = require('sinon-chai');
chai.use(chaiAsPromised);
chai.use(sinonChai);
@@ -16,7 +16,7 @@ describe('#impedanceTesting', function () {
this.timeout(20000);
before(function (done) {
ourBoard = new openBCIBoard.OpenBCIBoard({
ourBoard = new Cyton({
verbose: true,
simulatorFragmentation: k.OBCISimulatorFragmentationRandom
});
Diferenças do arquivo suprimidas por serem muito extensas Carregar Diff
+10 -68
Ver Arquivo
@@ -1,13 +1,13 @@
'use strict';
var bluebirdChecks = require('./bluebirdChecks');
var bufferEqual = require('buffer-equal');
var chai = require('chai');
var chaiAsPromised = require(`chai-as-promised`);
var expect = chai.expect;
var should = chai.should(); // eslint-disable-line no-unused-vars
var openBCISimulator = require('../openBCISimulator');
var openBCISample = require('../openBCISample');
var k = openBCISample.k;
const bluebirdChecks = require('./bluebirdChecks');
const bufferEqual = require('buffer-equal');
const chai = require('chai');
const chaiAsPromised = require(`chai-as-promised`);
const expect = chai.expect;
const should = chai.should(); // eslint-disable-line no-unused-vars
const openBCISimulator = require('../openBCISimulator');
const openBCISample = require('../openBCISample');
const k = require('../openBCIConstants');
chai.use(chaiAsPromised);
@@ -32,7 +32,6 @@ describe('openBCISimulator', function () {
expect(simulator.options.alpha).to.be.true;
expect(simulator.options.boardFailure).to.be.false;
expect(simulator.options.daisy).to.be.false;
expect(simulator.options.daisyCanBeAttached).to.be.true;
expect(simulator.options.drift).to.equal(0);
expect(simulator.options.firmwareVersion).to.equal(k.OBCIFirmwareV1);
expect(simulator.options.lineNoise).to.equal(k.OBCISimulatorLineNoiseHz60);
@@ -273,69 +272,12 @@ describe('openBCISimulator', function () {
simulator.once('open', done);
});
afterEach(() => {
simulator.removeAllListeners('data');
simulator = null;
});
describe('set max channels', function () {
this.timeout(100);
it('should send nothing if no daisy attached', function (done) {
simulator.options.daisy = false;
simulator.on('data', function (data) {
expect(data.toString().match(k.OBCIParseEOT)).to.not.equal(null);
if (data.toString().match(k.OBCIParseEOT)) {
done();
}
});
simulator.write(k.OBCIChannelMaxNumber8);
});
it('should send daisy removed if daisy attached', function (done) {
simulator.options.daisy = true;
simulator.on('data', function (data) {
expect(data.toString().match(`daisy removed${k.OBCIParseEOT}`)).to.not.equal(null);
if (data.toString().match(k.OBCIParseEOT)) {
expect(simulator.options.daisy).to.equal(false);
done();
}
});
simulator.write(k.OBCIChannelMaxNumber8);
});
it('should send just 16 if daisy already attached', function (done) {
simulator.options.daisy = true;
simulator.on('data', function (data) {
expect(data.toString().match(`16${k.OBCIParseEOT}`)).to.not.equal(null);
if (data.toString().match(k.OBCIParseEOT)) {
done();
}
});
simulator.write(k.OBCIChannelMaxNumber16);
});
it('should send daisy attached if able to attach', function (done) {
simulator.options.daisy = false;
simulator.options.daisyCanBeAttached = true;
simulator.on('data', function (data) {
expect(data.toString().match(`daisy attached16`)).to.not.equal(null);
if (data.toString().match(k.OBCIParseEOT)) {
expect(simulator.options.daisy).to.equal(true);
done();
}
});
simulator.write(k.OBCIChannelMaxNumber16);
});
it('should send daisy attached if not able to attach', function (done) {
simulator.options.daisy = false;
simulator.options.daisyCanBeAttached = false;
simulator.on('data', function (data) {
expect(data.toString().match(`no daisy to attach!`)).to.not.equal(null);
if (data.toString().match(k.OBCIParseEOT)) {
done();
}
});
simulator.write(k.OBCIChannelMaxNumber16);
});
});
describe('reset', function () {
it('should be v2', function (done) {
simulator.on('data', function (data) {
console.log(data.toString());
expect(data.toString().match('v2')).to.not.equal(null);
done();
});