Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Making Things Pretty #12

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 26 additions & 25 deletions advertise.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ var options = new getopt([
['S' , 'static' , 'static - do not connect to ws-slave/target device'],
['f' , 'funmode' , 'have fun!'],
['' , 'jk' , 'see http://xkcd.com/1692'],
['h' , 'help' , 'display this help'],
['h' , 'help' , 'display this help'],
]);
options.setHelp("Usage: node advertise -a <FILE> [ -s <FILE> ] [-S] \n[[OPTIONS]]" )
options.setHelp("\nUsage:".underline + " node".bold + " advertise.js".cyan.bold + " -a <FILE> ".yellow.bold + "[ -s <FILE> ]".magenta.bold + " [-S]".bold + " \n[[OPTIONS]]\n" )

opt=options.parseSystem();

Expand Down Expand Up @@ -68,7 +68,7 @@ if (opt.options.static) {

baseAdvFile=path.basename(opt.options.advertisement);
var peripheralId = baseAdvFile.substring(0, baseAdvFile.indexOf("_"));
console.log("peripheralid: " + peripheralId)
console.log('[+]'.green.bold + "Peripheral ID (MAC):".yellow.bold + " " + peripheralId)


if (opt.options.advertisement.indexOf('.adv.json') > -1 ) {
Expand All @@ -77,14 +77,15 @@ if (opt.options.advertisement.indexOf('.adv.json') > -1 ) {
advertisementFile=opt.options.advertisement + '.adv.json';
}

console.log('advertisement file: ' + advertisementFile)
console.log('[+]'.green.bold + 'Advertisement File:'.yellow.bold + " " + advertisementFile)

var advertisement = JSON.parse(fs.readFileSync(advertisementFile, 'utf8'));
var eir = new Buffer(advertisement.eir,'hex');
var scanResponse = advertisement.scanResponse ? new Buffer(advertisement.scanResponse, 'hex') : '';

console.log("EIR: " + eir.toString('hex'));
console.log("scanResponse: " + scanResponse.toString('hex'));
console.log('[+]'.green.bold + "EIR:".yellow.bold + " " + eir.toString('hex'));
console.log('[+]'.green.bold + "Scan Response:".yellow.bold + " " + scanResponse.toString('hex'));
console.log(getDateTime().bgCyan.bold);

if (opt.options.services) {
if (opt.options.services.indexOf('.srv.json') > -1 ) {
Expand All @@ -109,10 +110,10 @@ if (!staticRun) {
wsclient.on('ws_open', function(){
wsclient.getMac(function(address){
myAddress = address;
console.log('Noble MAC address : ' + myAddress);
console.log('[+]'.green.bold + 'Noble MAC address: '.blue.bold + myAddress);
})
wsclient.initialize(peripheralId, services, true, function(){
console.log('initialized !');
console.log('[+]Initialized!'.green.bold);
startAdvertising();
})
});
Expand All @@ -122,17 +123,17 @@ if (!staticRun) {

function startAdvertising(){
if (bleno.state != 'poweredOn') {
console.log('waiting for interface to initialize...');
console.log('Waiting for interface to initialize...'.yellow);
bleno.once('stateChange', function(state){
if (state === 'poweredOn') {
bleno.startAdvertisingWithEIRData(eir,scanResponse);
} else {
console.log('Interface down! Exiting...');
console.log('[-]'.red.bold + 'Interface down! Exiting...'.red.bold);
process.exit(1);
}
})
} else {
console.log('Static - start advertising');
console.log('[+]'.green.bold + 'Static - Start Advertising...'.green.bold);
bleno.startAdvertisingWithEIRData(eir,scanResponse);
}
}
Expand Down Expand Up @@ -206,33 +207,33 @@ function dumpLog(type, peripheralId, serviceUuid, uuid, data ){


bleno.on('stateChange', function(state) {
console.log('BLENO - on -> stateChange: ' + state);
console.log('[+]'.green.bold + 'BLENO - on -> stateChange: '.green.bold + state);
if (state === 'poweredOn') {
// console.log('poweredOn');
} else {
console.log('Interface down! Reset/power it up again...')
console.log('[-]'.red.bold + 'Interface down! Reset/Power it up again...'.red.bold)
bleno.stopAdvertising();
}
});

bleno.on('advertisingStart', function(error) {
console.log('on -> advertisingStart: ' + (error ? 'error ' + error : 'success'));
console.log('On -> advertisingStart: '.yellow.bold + (error ? 'Error '.red.bold + error : 'Success'.green.bold));

if (error) {
console.log("Adv error ".red,error);
console.log('[-]'.red.bold + "Advertising Error ".red.bold,error);
} else {
bleno.setServices( mitmservices, function(error){
console.log('setServices: ' + (error ? 'error ' + error : 'success'));
console.log(' <<<<<<<<<<<<<<<< INITIALIZED >>>>>>>>>>>>>>>>>>>> '.magenta.inverse)
console.log('setServices: '.yellow.bold + (error ? 'Error '.red.bold + error : 'Success'.green.bold));
console.log('\n <<<<<<<<<<<<<<<< INITIALIZED >>>>>>>>>>>>>>>>>>>> \n'.magenta.inverse)
});
}
});

bleno.on('accept', function(clientAddress) {
console.log('Client connected: ' + clientAddress);
console.log('Client Connected: \t'.green.bold + clientAddress + ' \t' + getDateTime().bgCyan.bold);

if (clientAddress === myAddress) {
console.log('SELF CONNECT!');
console.log('SELF CONNECT!'.green);
bleno.disconnect();
} else {
if (!staticRun) {
Expand All @@ -247,7 +248,7 @@ bleno.on('accept', function(clientAddress) {

//update the ws-slave on client disconnect
bleno.on('disconnect', function(clientAddress){
console.log('Client disconnected: ' + clientAddress);
console.log('Client Disconnected: \t'.red.bold + clientAddress + ' \t' + getDateTime().bgCyan.bold);
if (!staticRun) {
wsclient.clientConnection(clientAddress,false);
}
Expand All @@ -256,19 +257,19 @@ bleno.on('disconnect', function(clientAddress){


wsclient.on('disconnect', function(peripheralId){
console.log(' target device disconnected');
console.log(' -----Target device disconnected!'.red.bold + ' ' + getDateTime().bgCyan.bold);
})

wsclient.on('connect', function(peripheralId){
console.log(' target device connected');
console.log(' -----Target device connected!'.green.bold + ' ' + getDateTime().bgCyan.bold);
})

//change the advertisement
wsclient.on('advchange', function(newEir, newScanResponse){
bleno.stopAdvertising(function(){
//wait 2 seconds after stopAdvertising, otherwise the HCI will often fail with "Command Disallowed"
setTimeout(function() {
console.log('Advertisement change: waited 2s for device, should work now...');
console.log('Advertisement change: waited 2s for device, should work now...'.yellow);
console.log(' old ' + eir.toString('hex') + ' ('+ utils.hex2a(eir) +') '+ ' : ' + scanResponse.toString('hex') + ' ('+ utils.hex2a(scanResponse) +')');
console.log(' new ' + newEir.toString('hex') + ' ('+ utils.hex2a(newEir) +') '+ ' : ' + newScanResponse.toString('hex') + ' ('+ utils.hex2a(newScanResponse) +') ');
bleno.startAdvertisingWithEIRData(newEir,newScanResponse);
Expand Down Expand Up @@ -396,7 +397,7 @@ function setServices(services, callback){

var info = getServiceNames(serviceUuid, uuid);

debug('<< Read req : '.green + this.serviceUuid +' -> ' + this.uuid + ' offset: ' + offset)
debug('<< Read req: '.green + this.serviceUuid +' -> ' + this.uuid + ' offset: ' + offset)

//we assume the original device read success
//todo? - forward possible error to client
Expand Down Expand Up @@ -480,7 +481,7 @@ function setServices(services, callback){
callback(0x00);
});
} else {
console.log(' hook function did not return modified data');
console.log(' hook function did not return modified data'.yellow);
callback(0x00);
}
})
Expand Down
65 changes: 54 additions & 11 deletions lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,26 +23,39 @@ function hex2a(hex) {

function printAdvertisement(peripheralId, address, addressType, connectable, advertisement, rssi, isRefreshed) {

/* //Original
if (!isRefreshed) {
console.log('peripheral discovered (' + peripheralId +
' with address <' + address + ', ' + addressType + '>,' +
' connectable ' + connectable + ',' +
' RSSI ' + rssi + ':');
console.log('Peripheral discovered ('.yellow.bold + peripheralId.cyan.bold +
' with address <'.yellow.bold + address.cyan.bold + ', '.yellow.bold + addressType + '>,'.yellow.bold +
' connectable '.yellow.bold + connectable + ','.yellow.bold +
' RSSI '.yellow.bold + rssi + ')'.yellow.bold);
} else {
console.log('refreshed advertisement for ' + peripheralId + ' (' + advertisement.localName +')');
console.log('refreshed advertisement for '.yellow.bold + peripheralId.cyan.bold + ' ('.yellow.bold + advertisement.localName +')'.yellow.bold);
}
*/

//Modified
if (!isRefreshed) {
console.log('\n-----------------------------------------------------------------------------------------'.white.bold)
console.log('[+]'.green.bold + 'New Peripheral Discovered: '.yellow.bold + peripheralId.cyan.bold);
console.log('\tMAC Address: '.yellow.bold + address.cyan.bold + ', '.yellow.bold + addressType + '>'.yellow.bold);
console.log('\tConnectable: '.yellow.bold + connectable);
console.log('\tRSSI: '.yellow.bold + rssi);
} else {
console.log('Refreshed advertisement for '.yellow.bold + peripheralId.cyan.bold + ' ('.yellow.bold + advertisement.localName +')'.yellow.bold);
}

if (address.substring(0,8) === 'ec:fe:7e') {
console.log('BlueRadios MAC address - check AT commands service by blueRadiosCmd script!'.red)
console.log('BlueRadios MAC address - check AT commands service by blueRadiosCmd script!'.red.bold)
}
if (advertisement.localName) {
console.log('\tName: ' + advertisement.localName);
console.log('\tName: '.yellow.bold + advertisement.localName);
}
if (advertisement.eir){
console.log('\tEIR: ' + advertisement.eir.toString('hex') + ' (' + hex2a(advertisement.eir.toString('hex'))+')');
console.log('\tEIR: '.yellow.bold + advertisement.eir.toString('hex') + ' ('.yellow.bold + hex2a(advertisement.eir.toString('hex'))+')'.yellow.bold);
}
if (advertisement.scanResponse){
console.log('\tScan response: ' + advertisement.scanResponse.toString('hex') + ' (' + hex2a(advertisement.scanResponse.toString('hex'))+')');
console.log('\tScan response: '.yellow.bold + advertisement.scanResponse.toString('hex') + ' ('.yellow.bold + hex2a(advertisement.scanResponse.toString('hex'))+')'.yellow.bold);
}
console.log();
}
Expand Down Expand Up @@ -91,11 +104,41 @@ function checkAdvertisement(peripheralId, advertisement, callback){
}


/////////Added to time stamps during a scan - Freilich
function getDateTime() {

var date = new Date();

var hour = date.getHours();
hour = (hour < 10 ? "0" : "") + hour;

var min = date.getMinutes();
min = (min < 10 ? "0" : "") + min;

var sec = date.getSeconds();
sec = (sec < 10 ? "0" : "") + sec;

var msec = date.getMilliseconds();
msec = (msec < 100 ? "0" : "") + msec;

var year = date.getFullYear();

var month = date.getMonth() + 1;
month = (month < 10 ? "0" : "") + month;

var day = date.getDate();
day = (day < 10 ? "0" : "") + day;

return year + "." + month + "." + day + " " + hour + ":" + min + ":" + sec + '.' + msec;

}
/////
function saveAdvertisement(peripheralId, address, addressType, connectable, advertisement, rssi) {

checkAdvertisement(peripheralId, advertisement, function(newAdv){
if (newAdv === 'same' ) {
console.log('already saved advertisement for ' + peripheralId + ' (' + advertisement.localName +')');
console.log('\n-----------------------------------------------------------------------------------------'.white.bold)
console.log('['.green.bold + '*'.yellow.bold + ']'.green.bold + 'Previously Discovered & Saved Advertisement For: '.yellow.bold + peripheralId.cyan.bold + ' ('.yellow.bold + advertisement.localName +')'.yellow.bold + getDateTime().bgCyan.bold);
//no-op
return
} else {
Expand Down Expand Up @@ -143,7 +186,7 @@ function saveAdvertisement(peripheralId, address, addressType, connectable, adve
if(err) {
return console.log(err);
}
console.log("advertisement saved: "+ fileName );
console.log('[+]'.green.bold + "Advertisement saved: ".yellow.bold+ fileName );
});

}
Expand Down
16 changes: 8 additions & 8 deletions lib/ws-client.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ var myAddress='';

var wsClient = function(){

console.log('Ws-slave address: ' + slaveAddress);
console.log('\n[+]'.green.bold + 'WS-Slave IP Address:'.yellow.bold +" " + slaveAddress);

this.on('read', this.onRead);
events.EventEmitter.call(this);
Expand All @@ -31,7 +31,7 @@ var wsClient = function(){
var _this = this;
ws.on('open', function() {
// ws.send('something');
console.log('on open');
console.log('[+]'.green.bold + 'WS is On & Open'.yellow.bold);
_this.emit('ws_open');
});

Expand All @@ -43,16 +43,16 @@ wsClient.prototype.checkReadyState = function(callback){

switch (ws.readyState) {
case WebSocket.CONNECTING:
console.log('connecting');
console.log('Connecting'.green.bold);
break;
case WebSocket.OPEN:
console.log('connecting');
console.log('Connecting/Open'.green.bold);
break;
case WebSocket.CLOSING:
console.log('closing');
console.log('Closing'.red.bold);
break;
case WebSocket.CLOSED:
console.log('closed');
console.log('Closed'.red.bold);
break;
default:
break;
Expand Down Expand Up @@ -98,7 +98,7 @@ wsClient.prototype.onMessage = function(rawmessage) {
var handle = message.handle;

if (type === 'stateChange') {
console.log(state);
console.log('[+]'.green.bold + 'Current State: '.yellow.bold + state);
this.emit('stateChange', state);
} else if (type === 'discover') {

Expand Down Expand Up @@ -317,4 +317,4 @@ wsClient.prototype.getMac = function(callback) {
}
}

module.exports = new wsClient();
module.exports = new wsClient();
40 changes: 33 additions & 7 deletions replay.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,8 @@ function parse(line) {

if(waiting) {//we want it to match
console.log('LINE: ' + line);
setTimeout(parse(line), 500);//wait 50 millisecnds then recheck
//setTimeout(parse(line), 500;//wait 50 millisecnds then recheck
setTimeout(parse(line), 20;//wait 20 millisecnds then recheck - Modified
return;
}

Expand All @@ -82,25 +83,50 @@ function parse(line) {
var uuid = arr[3].trim().split(' ')[0];
var data = arr[4].trim().split(' ')[0];


/*
switch(operator) {
case '< W' : console.log('WRITE REQ: '.blue + data );
case '< W' : console.log('WRITE REQ: '.blue.bold + data );
wsclient.write(peripheralId, serviceUuid, uuid, new Buffer(data,'hex'), true , function(error) {
if (error){
console.log('------ Write error: '.red);
console.log('------ Write error: '.red.bold);
throw(error);
}
}); break;
case '< C' : console.log('WRITE CMD: '.blue + data );
wsclient.write(peripheralId, serviceUuid, uuid, new Buffer(data,'hex'), false , function(error) {
if (error){
console.log('------ Write error: '.red);
console.log('------ Write error: '.red.bold);
throw(error);
}
}); break;
*/

switch(operator) {
case '< W' : console.log('WRITE REQ: '.blue.bold + data.yellow + ' ('.yellow.bold + new Buffer(data, 'hex') + ')'.yellow.bold);
wsclient.write(peripheralId, serviceUuid, uuid, new Buffer(data,'hex'), true , function(error) {
if (error){
console.log('------ Write error: '.red.bold);
throw(error);
}
}); break;
case '< C' : console.log('WRITE CMD: '.green.bold + data.yellow + ' ('.yellow.bold + new Buffer(data, 'hex') + ')'.yellow.bold );
wsclient.write(peripheralId, serviceUuid, uuid, new Buffer(data,'hex'), false , function(error) {
if (error){
console.log('------ Write error: '.red.bold);
throw(error);
}
}); break;







case '> R' : console.log('READ: '.grey + data + ' --- skip');
case '> R' : console.log('READ: '.grey + data + ' --- skipped');
break
case '> N' : console.log('NOTIFICATION: '.grey + data + ' --- skip');
case '> N' : console.log('NOTIFICATION: '.grey + data + ' --- skipped');
break
}

Expand All @@ -110,7 +136,7 @@ function parse(line) {
wsclient.on('ws_open', function(){
wsclient.getMac(function(address){
myAddress = address;
console.log('Noble MAC address : ' + myAddress);
console.log('Noble MAC address: ' + myAddress);
})
wsclient.initialize(peripheralId, services, true, function(){
console.log('initialized !');
Expand Down
Loading