Refactor arduino library as class, rather than object.

This commit is contained in:
mmcwilliams 2019-03-08 11:27:24 -05:00
parent febb39aef7
commit f0fae8ce1b
3 changed files with 627 additions and 632 deletions

View File

@ -7,6 +7,17 @@ const newlineRe = new RegExp('\n', 'g');
const returnRe = new RegExp('\r', 'g'); const returnRe = new RegExp('\r', 'g');
let eventEmitter; let eventEmitter;
let cfg; let cfg;
let arduino;
const KNOWN = [
'/dev/tty.usbmodem1a161',
'/dev/tty.usbserial-A800f8dk',
'/dev/tty.usbserial-A900cebm',
'/dev/tty.usbmodem1a131',
'/dev/tty.usbserial-a900f6de',
'/dev/tty.usbmodem1a141',
'/dev/ttyACM0',
'COM3'
];
/** /**
* Pause the process for X milliseconds in async/await functions * Pause the process for X milliseconds in async/await functions
* *
@ -20,117 +31,29 @@ async function delay(ms) {
}); });
} }
/** /**
* Send a command to an Arduino using async/await * Class representing the arduino communication features
*
* @param {string} device Arduino identifier
* @param {string} cmd Single character command to send
*
* @returns {Promise} Resolves after sending
**/ **/
async function send(device, cmd) { class Arduino {
return new Promise((resolve, reject) => { constructor() {
arduino.queue[cmd] = (ms) => { this.path = {};
return resolve(ms); this.known = KNOWN;
}; this.alias = {};
return arduino.serial[device].write(cmd, (err, results) => { this.serial = { connect: {}, projector: {}, camera: {}, light: {} };
if (err) { this.baud = 57600;
//console.error(err) this.queue = {};
return reject(err); this.timer = 0;
this.lock = false;
this.locks = {};
} }
// async enumerate() {
});
});
}
/**
* Send a string to an Arduino using async/await
*
* @param {string} device Arduino identifier
* @param {string} str String to send
*
* @returns {Promise} Resolves after sending
**/
async function write(device, str) {
return new Promise((resolve, reject) => {
arduino.serial[device].write(str, function (err, results) {
if (err) {
return reject(err);
}
//console.log('sent: ' + str)
return resolve(results);
});
});
}
/**
* Connect to an Arduino using async/await
*
* @param {string} device Arduino identifier
*
* @returns {Promise} Resolves after opening
**/
async function openArduino(device) {
return new Promise((resolve, reject) => {
return arduino.serial[device].open(error => {
if (error) {
return reject(error);
}
return resolve(true);
});
});
}
/**
* Close a connection to an Arduino using async/await
*
* @param {string} device Arduino identifier
*
* @returns {Promise} Resolves after closing
**/
async function closeArduino(device) {
return new Promise((resolve, reject) => {
return arduino.serial[device].close((err) => {
if (err) {
return reject(err);
}
return resolve(true);
});
});
}
/******
Arduino handlers
*******/
const arduino = {
path: {},
known: [
'/dev/tty.usbmodem1a161',
'/dev/tty.usbserial-A800f8dk',
'/dev/tty.usbserial-A900cebm',
'/dev/tty.usbmodem1a131',
'/dev/tty.usbserial-a900f6de',
'/dev/tty.usbmodem1a141',
'/dev/ttyACM0',
'COM3'
],
alias: {},
serial: {
connect: {},
projector: {},
camera: {},
light: {}
},
baud: 57600,
queue: {},
timer: 0,
lock: false,
locks: {}
};
arduino.enumerate = async function () {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
return SerialPort.list((err, ports) => { return SerialPort.list((err, ports) => {
let matches = []; let matches = [];
if (err) { if (err) {
return reject(err); return reject(err);
} }
ports.forEach(port => { ports.forEach((port) => {
if (arduino.known.indexOf(port.comName) !== -1) { if (this.known.indexOf(port.comName) !== -1) {
matches.push(port.comName); matches.push(port.comName);
} }
else if ((port.manufacturer + '').toLowerCase().indexOf('arduino') !== -1) { else if ((port.manufacturer + '').toLowerCase().indexOf('arduino') !== -1) {
@ -151,104 +74,141 @@ arduino.enumerate = async function () {
} }
}); });
}); });
}
/**
* Send a command to an Arduino using async/await
*
* @param {string} device Arduino identifier
* @param {string} cmd Single character command to send
*
* @returns {Promise} Resolves after sending
**/
async sendAsync(device, cmd) {
return new Promise((resolve, reject) => {
this.queue[cmd] = (ms) => {
return resolve(ms);
}; };
//commands which respond to a sent char return this.serial[device].write(cmd, (err, results) => {
arduino.send = async function (serial, cmd, res) { if (err) {
const device = arduino.alias[serial]; //console.error(err)
return reject(err);
}
//
});
});
}
async send(serial, cmd) {
const device = this.alias[serial];
let results; let results;
if (arduino.locks[serial]) { if (this.locks[serial]) {
return false; return false;
} }
arduino.locks[serial] = true; this.locks[serial] = true;
await delay(cfg.arduino.serialDelay); await delay(cfg.arduino.serialDelay);
try { try {
results = await send(device, cmd); results = await this.sendAsync(device, cmd);
} }
catch (e) { catch (e) {
return console.error(e); return console.error(e);
} }
arduino.locks[serial] = false; this.locks[serial] = false;
arduino.timer = new Date().getTime(); this.timer = new Date().getTime();
return await eventEmitter.emit('arduino_send', cmd); return await eventEmitter.emit('arduino_send', cmd);
}; }
//send strings, after char triggers firmware to accept async string(serial, str) {
arduino.string = async function (serial, str) { const device = this.alias[serial];
const device = arduino.alias[serial];
let writeSuccess; let writeSuccess;
await delay(cfg.arduino.serialDelay); await delay(cfg.arduino.serialDelay);
if (typeof arduino.serial[device].fake !== 'undefined' if (typeof this.serial[device].fake !== 'undefined'
&& arduino.serial[device].fake) { && this.serial[device].fake) {
return arduino.serial[device].string(str); return this.serial[device].string(str);
} }
else { else {
try { try {
writeSuccess = await write(device, str); writeSuccess = await this.writeAsync(device, str);
} }
catch (e) { catch (e) {
return console.error(e); return console.error(e);
} }
return writeSuccess; return writeSuccess;
} }
}; }
//respond with same char over serial when done /**
arduino.end = async function (serial, data) { * Send a string to an Arduino using async/await
*
* @param {string} device Arduino identifier
* @param {string} str String to send
*
* @returns {Promise} Resolves after sending
**/
async writeAsync(device, str) {
return new Promise((resolve, reject) => {
this.serial[device].write(str, function (err, results) {
if (err) {
return reject(err);
}
//console.log('sent: ' + str)
return resolve(results);
});
});
}
end(serial, data) {
const end = new Date().getTime(); const end = new Date().getTime();
const ms = end - arduino.timer; const ms = end - this.timer;
let complete; let complete;
if (arduino.queue[data] !== undefined) { if (this.queue[data] !== undefined) {
arduino.locks[serial] = false; this.locks[serial] = false;
//console.log('Command ' + data + ' took ' + ms + 'ms'); //console.log('Command ' + data + ' took ' + ms + 'ms');
complete = arduino.queue[data](ms); //execute callback complete = this.queue[data](ms); //execute callback
eventEmitter.emit('arduino_end', data); eventEmitter.emit('arduino_end', data);
delete arduino.queue[data]; delete this.queue[data];
} }
else { else {
//console.log('Received stray "' + data + '"'); //silent to user //console.log('Received stray "' + data + '"'); //silent to user
} }
return complete; return complete;
}; }
arduino.alias = function (serial, device) { aliasSerial(serial, device) {
console.log(`Making "${serial}" an alias of ${device}`); console.log(`Making "${serial}" an alias of ${device}`);
arduino.alias[serial] = device; this.alias[serial] = device;
}; }
arduino.connect = async function (serial, device, confirm) { async connect(serial, device, confirm) {
return new Promise(async (resolve, reject) => { return new Promise(async (resolve, reject) => {
let connectSuccess; let connectSuccess;
arduino.path[serial] = device; this.path[serial] = device;
arduino.alias[serial] = device; this.alias[serial] = device;
arduino.serial[device] = new SerialPort(arduino.path[serial], { this.serial[device] = new SerialPort(this.path[serial], {
autoOpen: false, autoOpen: false,
baudRate: cfg.arduino.baud, baudRate: cfg.arduino.baud,
parser: parser parser: parser
}); });
arduino.locks[device] = false; this.locks[device] = false;
try { try {
connectSuccess = await openArduino(device); connectSuccess = await this.openArduino(device);
} }
catch (e) { catch (e) {
console.error('failed to open: ' + e); console.error('failed to open: ' + e);
return reject(e); return reject(e);
} }
console.log(`Opened connection with ${arduino.path[serial]} as ${serial}`); console.log(`Opened connection with ${this.path[serial]} as ${serial}`);
if (!confirm) { if (!confirm) {
arduino.serial[device].on('data', async (data) => { this.serial[device].on('data', async (data) => {
let d = data.toString('utf8'); let d = data.toString('utf8');
d = d.replace(newlineRe, '').replace(returnRe, ''); d = d.replace(newlineRe, '').replace(returnRe, '');
return await arduino.end(serial, d); return this.end(serial, d);
}); });
} }
else { else {
arduino.serial[device].on('data', async (data) => { this.serial[device].on('data', async (data) => {
let d = data.toString('utf8'); let d = data.toString('utf8');
d = d.replace(newlineRe, '').replace(returnRe, ''); d = d.replace(newlineRe, '').replace(returnRe, '');
return await arduino.confirmEnd(d); return await this.confirmEnd(d);
}); });
} }
return resolve(arduino.path[serial]); return resolve(this.path[serial]);
}); });
}; }
arduino.confirmExec = {}; confirmEnd(data) {
arduino.confirmEnd = function (data) {
//console.dir(data) //console.dir(data)
if (data === cfg.arduino.cmd.connect if (data === cfg.arduino.cmd.connect
|| data === cfg.arduino.cmd.proj_identifier || data === cfg.arduino.cmd.proj_identifier
@ -257,15 +217,15 @@ arduino.confirmEnd = function (data) {
|| data === cfg.arduino.cmd.proj_light_identifier || data === cfg.arduino.cmd.proj_light_identifier
|| data === cfg.arduino.cmd.proj_cam_light_identifier || data === cfg.arduino.cmd.proj_cam_light_identifier
|| data === cfg.arduino.cmd.proj_cam_identifier) { || data === cfg.arduino.cmd.proj_cam_identifier) {
arduino.confirmExec(null, data); this.confirmExec(null, data);
arduino.confirmExec = {}; this.confirmExec = {};
} }
}; }
arduino.verify = async function () { async verify() {
return new Promise(async (resolve, reject) => { return new Promise(async (resolve, reject) => {
const device = arduino.alias['connect']; const device = this.alias['connect'];
let writeSuccess; let writeSuccess;
arduino.confirmExec = function (err, data) { this.confirmExec = function (err, data) {
if (data === cfg.arduino.cmd.connect) { if (data === cfg.arduino.cmd.connect) {
return resolve(true); return resolve(true);
} }
@ -275,20 +235,20 @@ arduino.verify = async function () {
}; };
await delay(cfg.arduino.serialDelay); await delay(cfg.arduino.serialDelay);
try { try {
writeSuccess = await send(device, cfg.arduino.cmd.connect); writeSuccess = await this.sendAsync(device, cfg.arduino.cmd.connect);
} }
catch (e) { catch (e) {
return reject(e); return reject(e);
} }
return resolve(writeSuccess); return resolve(writeSuccess);
}); });
}; }
arduino.distinguish = async function () { async distinguish() {
return new Promise(async (resolve, reject) => { return new Promise(async (resolve, reject) => {
const device = arduino.alias['connect']; const device = this.alias['connect'];
let writeSuccess; let writeSuccess;
let type; let type;
arduino.confirmExec = function (err, data) { this.confirmExec = function (err, data) {
if (data === cfg.arduino.cmd.proj_identifier) { if (data === cfg.arduino.cmd.proj_identifier) {
type = 'projector'; type = 'projector';
} }
@ -314,44 +274,43 @@ arduino.distinguish = async function () {
}; };
await delay(cfg.arduino.serialDelay); await delay(cfg.arduino.serialDelay);
try { try {
writeSuccess = await send(device, cfg.arduino.cmd.mcopy_identifier); writeSuccess = await this.sendAsync(device, cfg.arduino.cmd.mcopy_identifier);
} }
catch (e) { catch (e) {
console.error(e); console.error(e);
return reject(e); return reject(e);
} }
}); });
}; }
arduino.close = async function (callback) { async close() {
const device = arduino.alias['connect']; const device = this.alias['connect'];
let closeSuccess; let closeSuccess;
try { try {
closeSuccess = await closeArduino(device); closeSuccess = await this.closeArduino(device);
} }
catch (e) { catch (e) {
return console.error(e); return console.error(e);
} }
return closeSuccess; return closeSuccess;
}; }
arduino.fakeConnect = async function (serial) { ;
async fakeConnect(serial) {
//console.log('Connecting to fake arduino...'); //console.log('Connecting to fake arduino...');
const device = '/dev/fake'; const device = '/dev/fake';
arduino.alias[serial] = device; this.alias[serial] = device;
arduino.serial[device] = { this.serial[device] = {
write: function (cmd, cb) { write: async function (cmd, cb) {
const t = { const t = {
c: cfg.arduino.cam.time + cfg.arduino.cam.delay, c: cfg.arduino.cam.time + cfg.arduino.cam.delay,
p: cfg.arduino.proj.time + cfg.arduino.proj.delay p: cfg.arduino.proj.time + cfg.arduino.proj.delay
}; };
let timeout = t[cmd]; let timeout = t[cmd];
let end;
if (typeof timeout === 'undefined') if (typeof timeout === 'undefined')
timeout = 10; timeout = 10;
arduino.timer = +new Date(); arduino.timer = +new Date();
setTimeout(() => { await delay(timeout);
arduino.end(serial, cmd); arduino.end(serial, cmd);
return cb(); return cb();
}, timeout);
}, },
string: async function (str) { string: async function (str) {
//do nothing //do nothing
@ -359,13 +318,49 @@ arduino.fakeConnect = async function (serial) {
}, },
fake: true fake: true
}; };
//console.log('Connected to fake arduino! Not real! Doesn\'t exist!'); //console.log('Connected to fake arduino! Not real! Does not exist!');
return true; return true;
}; }
/**
* Connect to an Arduino using async/await
*
* @param {string} device Arduino identifier
*
* @returns {Promise} Resolves after opening
**/
async openArduino(device) {
return new Promise((resolve, reject) => {
return this.serial[device].open((err) => {
if (err) {
return reject(err);
}
return resolve(true);
});
});
}
/**
* Close a connection to an Arduino using async/await
*
* @param {string} device Arduino identifier
*
* @returns {Promise} Resolves after closing
**/
async closeArduino(device) {
return new Promise((resolve, reject) => {
return this.serial[device].close((err) => {
if (err) {
return reject(err);
}
return resolve(true);
});
});
}
}
if (typeof module !== 'undefined' && module.parent) { if (typeof module !== 'undefined' && module.parent) {
module.exports = function (c, ee) { module.exports = function (c, ee) {
eventEmitter = ee; eventEmitter = ee;
cfg = c; cfg = c;
arduino = new Arduino();
return arduino; return arduino;
}; };
} }

File diff suppressed because one or more lines are too long

View File

@ -4,12 +4,24 @@ const SerialPort = require('serialport')
const Readline = SerialPort.parsers.Readline const Readline = SerialPort.parsers.Readline
const exec = require('child_process').exec const exec = require('child_process').exec
const parser = new Readline('') const parser : any = new Readline('')
const newlineRe : RegExp = new RegExp('\n', 'g') const newlineRe : RegExp = new RegExp('\n', 'g')
const returnRe : RegExp = new RegExp('\r', 'g') const returnRe : RegExp = new RegExp('\r', 'g')
let eventEmitter : any let eventEmitter : any
let cfg : object let cfg : any
let arduino : any
const KNOWN : string[] = [
'/dev/tty.usbmodem1a161',
'/dev/tty.usbserial-A800f8dk',
'/dev/tty.usbserial-A900cebm',
'/dev/tty.usbmodem1a131',
'/dev/tty.usbserial-a900f6de',
'/dev/tty.usbmodem1a141',
'/dev/ttyACM0',
'COM3'
]
/** /**
* Pause the process for X milliseconds in async/await functions * Pause the process for X milliseconds in async/await functions
@ -25,126 +37,34 @@ async function delay (ms : number) {
} }
/** /**
* Send a command to an Arduino using async/await * Class representing the arduino communication features
*
* @param {string} device Arduino identifier
* @param {string} cmd Single character command to send
*
* @returns {Promise} Resolves after sending
**/ **/
async function send (device : string, cmd : string) {
return new Promise ((resolve, reject) => {
arduino.queue[cmd] = (ms : number) => {
return resolve(ms)
}
return arduino.serial[device].write(cmd, (err : any, results : any) => {
if (err) {
//console.error(err)
return reject(err)
}
//
})
})
}
/** class Arduino {
* Send a string to an Arduino using async/await
* path : any = {}
* @param {string} device Arduino identifier known : string[] = KNOWN
* @param {string} str String to send alias : any = {}
* serial : any = { connect : {}, projector : {}, camera : {}, light : {} }
* @returns {Promise} Resolves after sending baud : number = 57600
**/ queue : any = {}
async function write (device : string, str : string) { timer : number = 0
lock : boolean = false
locks : any = {}
confirmExec : any
constructor () {
}
async enumerate () {
return new Promise( (resolve, reject) => { return new Promise( (resolve, reject) => {
arduino.serial[device].write(str, function (err, results) { return SerialPort.list((err : any, ports : any[]) => {
let matches : string[] = []
if (err) { if (err) {
return reject(err) return reject(err)
} }
//console.log('sent: ' + str) ports.forEach((port : any) => {
return resolve(results) if (this.known.indexOf(port.comName) !== -1) {
})
})
}
/**
* Connect to an Arduino using async/await
*
* @param {string} device Arduino identifier
*
* @returns {Promise} Resolves after opening
**/
async function openArduino (device : string) {
return new Promise((resolve, reject) => {
return arduino.serial[device].open(error => {
if (error) {
return reject(error)
}
return resolve(true)
})
})
}
/**
* Close a connection to an Arduino using async/await
*
* @param {string} device Arduino identifier
*
* @returns {Promise} Resolves after closing
**/
async function closeArduino (device : string) {
return new Promise((resolve : any, reject : any) => {
return arduino.serial[device].close((err) => {
if (err) {
return reject(err)
}
return resolve(true)
})
})
}
/******
Arduino handlers
*******/
const arduino = {
path : {},
known: [
'/dev/tty.usbmodem1a161',
'/dev/tty.usbserial-A800f8dk',
'/dev/tty.usbserial-A900cebm',
'/dev/tty.usbmodem1a131',
'/dev/tty.usbserial-a900f6de',
'/dev/tty.usbmodem1a141',
'/dev/ttyACM0',
'COM3'
],
alias : {
},
serial : {
connect : {},
projector : {},
camera : {},
light : {}
},
baud : 57600,
queue : {},
timer : 0,
lock : false,
locks : {
}
}
arduino.enumerate = async function () {
return new Promise( (resolve, reject) => {
return SerialPort.list((err, ports) => {
let matches = []
if (err) {
return reject(err)
}
ports.forEach(port => {
if (arduino.known.indexOf(port.comName) !== -1) {
matches.push(port.comName) matches.push(port.comName)
} else if ((port.manufacturer + '').toLowerCase().indexOf('arduino') !== -1) { } else if ((port.manufacturer + '').toLowerCase().indexOf('arduino') !== -1) {
matches.push(port.comName) matches.push(port.comName)
@ -163,36 +83,57 @@ arduino.enumerate = async function () {
}) })
} }
//commands which respond to a sent char /**
arduino.send = async function (serial, cmd, res) { * Send a command to an Arduino using async/await
const device = arduino.alias[serial] *
let results * @param {string} device Arduino identifier
if (arduino.locks[serial]) { * @param {string} cmd Single character command to send
*
* @returns {Promise} Resolves after sending
**/
async sendAsync (device : string, cmd : string) {
return new Promise ((resolve, reject) => {
this.queue[cmd] = (ms : number) => {
return resolve(ms)
}
return this.serial[device].write(cmd, (err : any, results : any) => {
if (err) {
//console.error(err)
return reject(err)
}
//
})
})
}
async send (serial : string, cmd : string) {
const device : any = this.alias[serial]
let results : any
if (this.locks[serial]) {
return false return false
} }
arduino.locks[serial] = true this.locks[serial] = true
await delay(cfg.arduino.serialDelay) await delay(cfg.arduino.serialDelay)
try { try {
results = await send(device, cmd) results = await this.sendAsync(device, cmd)
} catch (e) { } catch (e) {
return console.error(e) return console.error(e)
} }
arduino.locks[serial] = false this.locks[serial] = false
arduino.timer = new Date().getTime() this.timer = new Date().getTime()
return await eventEmitter.emit('arduino_send', cmd) return await eventEmitter.emit('arduino_send', cmd)
} }
//send strings, after char triggers firmware to accept async string (serial : string, str : string) {
arduino.string = async function (serial, str) { const device : any = this.alias[serial]
const device = arduino.alias[serial] let writeSuccess : any
let writeSuccess
await delay(cfg.arduino.serialDelay) await delay(cfg.arduino.serialDelay)
if (typeof arduino.serial[device].fake !== 'undefined' if (typeof this.serial[device].fake !== 'undefined'
&& arduino.serial[device].fake) { && this.serial[device].fake) {
return arduino.serial[device].string(str) return this.serial[device].string(str)
} else { } else {
try { try {
writeSuccess = await write(device, str) writeSuccess = await this.writeAsync(device, str)
} catch (e) { } catch (e) {
return console.error(e) return console.error(e)
} }
@ -200,64 +141,83 @@ arduino.string = async function (serial, str) {
} }
} }
//respond with same char over serial when done /**
arduino.end = async function (serial, data) { * Send a string to an Arduino using async/await
*
* @param {string} device Arduino identifier
* @param {string} str String to send
*
* @returns {Promise} Resolves after sending
**/
async writeAsync (device : string, str : string) {
return new Promise ((resolve, reject) => {
this.serial[device].write(str, function (err : any, results : any) {
if (err) {
return reject(err)
}
//console.log('sent: ' + str)
return resolve(results)
})
})
}
end (serial : string, data : string) {
const end = new Date().getTime() const end = new Date().getTime()
const ms = end - arduino.timer const ms = end - this.timer
let complete let complete
if (arduino.queue[data] !== undefined) { if (this.queue[data] !== undefined) {
arduino.locks[serial] = false; this.locks[serial] = false;
//console.log('Command ' + data + ' took ' + ms + 'ms'); //console.log('Command ' + data + ' took ' + ms + 'ms');
complete = arduino.queue[data](ms) //execute callback complete = this.queue[data](ms) //execute callback
eventEmitter.emit('arduino_end', data) eventEmitter.emit('arduino_end', data)
delete arduino.queue[data] delete this.queue[data]
} else { } else {
//console.log('Received stray "' + data + '"'); //silent to user //console.log('Received stray "' + data + '"'); //silent to user
} }
return complete return complete
};
arduino.alias = function (serial, device) {
console.log(`Making "${serial}" an alias of ${device}`)
arduino.alias[serial] = device
} }
arduino.connect = async function (serial, device, confirm) {
aliasSerial (serial : string, device : string) {
console.log(`Making "${serial}" an alias of ${device}`)
this.alias[serial] = device
}
async connect (serial : string, device : string, confirm : any) {
return new Promise(async (resolve, reject) => { return new Promise(async (resolve, reject) => {
let connectSuccess let connectSuccess : any
arduino.path[serial] = device; this.path[serial] = device;
arduino.alias[serial] = device; this.alias[serial] = device;
arduino.serial[device] = new SerialPort(arduino.path[serial], { this.serial[device] = new SerialPort(this.path[serial], {
autoOpen : false, autoOpen : false,
baudRate: cfg.arduino.baud, baudRate: cfg.arduino.baud,
parser: parser parser: parser
}) })
arduino.locks[device] = false this.locks[device] = false
try { try {
connectSuccess = await openArduino(device) connectSuccess = await this.openArduino(device)
} catch (e) { } catch (e) {
console.error('failed to open: ' + e) console.error('failed to open: ' + e)
return reject(e) return reject(e)
} }
console.log(`Opened connection with ${arduino.path[serial]} as ${serial}`); console.log(`Opened connection with ${this.path[serial]} as ${serial}`);
if (!confirm) { if (!confirm) {
arduino.serial[device].on('data', async (data) => { this.serial[device].on('data', async (data : Buffer) => {
let d = data.toString('utf8') let d = data.toString('utf8')
d = d.replace(newlineRe, '').replace(returnRe, '') d = d.replace(newlineRe, '').replace(returnRe, '')
return await arduino.end(serial, d) return this.end(serial, d)
}) })
} else { } else {
arduino.serial[device].on('data', async (data) => { this.serial[device].on('data', async (data : Buffer) => {
let d = data.toString('utf8') let d = data.toString('utf8')
d = d.replace(newlineRe, '').replace(returnRe, '') d = d.replace(newlineRe, '').replace(returnRe, '')
return await arduino.confirmEnd(d) return await this.confirmEnd(d)
}) })
} }
return resolve(arduino.path[serial]) return resolve(this.path[serial])
}) })
} }
arduino.confirmExec = {}; confirmEnd (data : string) {
arduino.confirmEnd = function (data) {
//console.dir(data) //console.dir(data)
if (data === cfg.arduino.cmd.connect if (data === cfg.arduino.cmd.connect
|| data === cfg.arduino.cmd.proj_identifier || data === cfg.arduino.cmd.proj_identifier
@ -266,25 +226,27 @@ arduino.confirmEnd = function (data) {
|| data === cfg.arduino.cmd.proj_light_identifier || data === cfg.arduino.cmd.proj_light_identifier
|| data === cfg.arduino.cmd.proj_cam_light_identifier || data === cfg.arduino.cmd.proj_cam_light_identifier
|| data === cfg.arduino.cmd.proj_cam_identifier ) { || data === cfg.arduino.cmd.proj_cam_identifier ) {
arduino.confirmExec(null, data); this.confirmExec(null, data);
arduino.confirmExec = {}; this.confirmExec = {};
} }
} }
arduino.verify = async function () { async verify () {
return new Promise(async (resolve, reject) => { return new Promise(async (resolve, reject) => {
const device = arduino.alias['connect'] const device : any = this.alias['connect']
let writeSuccess let writeSuccess : any
arduino.confirmExec = function (err, data) { this.confirmExec = function (err : any, data : string) {
if (data === cfg.arduino.cmd.connect) { if (data === cfg.arduino.cmd.connect) {
return resolve(true) return resolve(true)
} else { } else {
return reject('Wrong data returned') return reject('Wrong data returned')
} }
} }
await delay(cfg.arduino.serialDelay) await delay(cfg.arduino.serialDelay)
try { try {
writeSuccess = await send(device, cfg.arduino.cmd.connect) writeSuccess = await this.sendAsync(device, cfg.arduino.cmd.connect)
} catch (e) { } catch (e) {
return reject(e) return reject(e)
} }
@ -292,12 +254,12 @@ arduino.verify = async function () {
}) })
} }
arduino.distinguish = async function () { async distinguish () {
return new Promise(async (resolve, reject) => { return new Promise(async (resolve, reject) => {
const device = arduino.alias['connect'] const device : any = this.alias['connect']
let writeSuccess let writeSuccess : any
let type let type : string
arduino.confirmExec = function (err, data) { this.confirmExec = function (err : any, data : string) {
if (data === cfg.arduino.cmd.proj_identifier) { if (data === cfg.arduino.cmd.proj_identifier) {
type = 'projector' type = 'projector'
} else if (data === cfg.arduino.cmd.cam_identifier) { } else if (data === cfg.arduino.cmd.cam_identifier) {
@ -317,7 +279,7 @@ arduino.distinguish = async function () {
} }
await delay(cfg.arduino.serialDelay) await delay(cfg.arduino.serialDelay)
try { try {
writeSuccess = await send(device, cfg.arduino.cmd.mcopy_identifier) writeSuccess = await this.sendAsync(device, cfg.arduino.cmd.mcopy_identifier)
} catch (e) { } catch (e) {
console.error(e) console.error(e)
return reject(e) return reject(e)
@ -325,51 +287,89 @@ arduino.distinguish = async function () {
}) })
} }
arduino.close = async function (callback) { async close () {
const device = arduino.alias['connect'] const device = this.alias['connect']
let closeSuccess let closeSuccess
try { try {
closeSuccess = await closeArduino(device) closeSuccess = await this.closeArduino(device)
} catch (e) { } catch (e) {
return console.error(e) return console.error(e)
} }
return closeSuccess return closeSuccess
}; };
arduino.fakeConnect = async function (serial) { async fakeConnect (serial : string) {
//console.log('Connecting to fake arduino...'); //console.log('Connecting to fake arduino...');
const device = '/dev/fake' const device : string = '/dev/fake'
arduino.alias[serial] = device this.alias[serial] = device
arduino.serial[device] = { this.serial[device] = {
write : function (cmd, cb) { write : async function (cmd : string, cb : any) {
const t = { const t : any = {
c : cfg.arduino.cam.time + cfg.arduino.cam.delay, c : cfg.arduino.cam.time + cfg.arduino.cam.delay,
p : cfg.arduino.proj.time + cfg.arduino.proj.delay p : cfg.arduino.proj.time + cfg.arduino.proj.delay
} }
let timeout = t[cmd] let timeout : number = t[cmd]
let end
if (typeof timeout === 'undefined') timeout = 10 if (typeof timeout === 'undefined') timeout = 10
arduino.timer = +new Date() arduino.timer = +new Date()
setTimeout(() => {
await delay(timeout)
arduino.end(serial, cmd) arduino.end(serial, cmd)
return cb() return cb()
}, timeout)
}, },
string : async function (str) { string : async function (str : string) {
//do nothing //do nothing
return true return true
}, },
fake : true fake : true
}; };
//console.log('Connected to fake arduino! Not real! Doesn\'t exist!'); //console.log('Connected to fake arduino! Not real! Does not exist!');
return true return true
} }
/**
* Connect to an Arduino using async/await
*
* @param {string} device Arduino identifier
*
* @returns {Promise} Resolves after opening
**/
async openArduino (device : string) {
return new Promise((resolve, reject) => {
return this.serial[device].open((err : any) => {
if (err) {
return reject(err)
}
return resolve(true)
})
})
}
/**
* Close a connection to an Arduino using async/await
*
* @param {string} device Arduino identifier
*
* @returns {Promise} Resolves after closing
**/
async closeArduino (device : string) {
return new Promise((resolve : any, reject : any) => {
return this.serial[device].close((err : any) => {
if (err) {
return reject(err)
}
return resolve(true)
})
})
}
}
if (typeof module !== 'undefined' && module.parent) { if (typeof module !== 'undefined' && module.parent) {
module.exports = function (c, ee) { module.exports = function (c : any, ee : any) {
eventEmitter = ee eventEmitter = ee
cfg = c cfg = c
arduino = new Arduino()
return arduino return arduino
} }
} }