bluetest/lib/index.js

111 lines
2.0 KiB
JavaScript
Raw Normal View History

2016-07-06 12:58:51 +00:00
/**
*
* User: Martin Donnelly
* Date: 2016-07-06
* Time: 13:37
*
*/
2016-07-06 13:26:22 +00:00
var cp = require('child_process');
var spawn = cp.spawn;
var fork = cp.fork;
2016-07-06 12:58:51 +00:00
var EventEmitter = require('events');
var busEmitter = new EventEmitter();
var util = require('util');
var logger = require('log4js').getLogger();
var bluetest = module.exports = function(options) {
'use strict';
2016-07-06 13:23:38 +00:00
var core = {
mac:''
};
2016-07-06 12:58:51 +00:00
2016-07-06 13:13:26 +00:00
core.connectGatt = function() {
logger.info('trying to connect using gatttool');
2016-07-06 13:34:53 +00:00
var gatt = spawn('gatttool',['-I']);
2016-07-06 13:24:59 +00:00
var cStr;
2016-07-06 13:15:57 +00:00
gatt.on('error', function(err) {
logger.error(err);
});
2016-07-06 13:13:26 +00:00
gatt.on('exit', function(code) {
logger.debug('gatt exit code', code);
});
2016-07-06 13:36:09 +00:00
gatt.on('message', function(m) {
logger.info(m);
});
2016-07-06 13:38:01 +00:00
gatt.stdout.on('data', (data) => {
logger.info(`stdout: ${data}`);
});
gatt.stderr.on('data', (data) => {
logger.info(`stderr: ${data}`);
});
gatt.on('close', (code) => {
logger.warn(`child process exited with code ${code}`);
});
2016-07-06 13:23:38 +00:00
logger.info('Trying to connect to ', core.mac);
2016-07-06 13:34:53 +00:00
cStr = 'connect ' + core.mac + '\n';
gatt.stdin.write(cStr);
2016-07-06 13:38:01 +00:00
2016-07-06 13:13:26 +00:00
};
2016-07-06 12:58:51 +00:00
core.init = function(options) {
2016-07-06 13:23:38 +00:00
2016-07-06 13:01:04 +00:00
var tool_path = '';
2016-07-06 13:02:16 +00:00
var hcidev = 'hvi0';
2016-07-06 12:58:51 +00:00
2016-07-06 13:06:21 +00:00
//If ()
if (typeof options.mac !== 'undefined') {
2016-07-06 13:23:38 +00:00
core.mac = options.mac;
2016-07-06 13:06:21 +00:00
} else {
console.log('You need to pass a mac address.');
process.exit(1);
}
logger.info('Working with:' , options);
2016-07-06 12:58:51 +00:00
var hciconfig = spawn(tool_path + 'hciconfig', [hcidev, 'up']);
hciconfig.on('exit', function(code) {
logger.debug('code',code);
2016-07-06 13:06:21 +00:00
if (code !== 0) {
// Could not get the device UP, maybe due to permissions, should run with sudo.
busEmitter.emit('error','hciconfig: failed to bring up device ' + hcidev + '. Try running with sudo.');
return;
} else {
2016-07-06 13:13:26 +00:00
core.connectGatt();
2016-07-06 13:06:21 +00:00
}
2016-07-06 12:58:51 +00:00
});
};
core.init(options);
};
util.inherits(bluetest, EventEmitter);