Async/Await refactor for arduino and sequence-related features

This commit is contained in:
mmcwilliams 2018-03-02 22:42:15 -05:00
parent 99c59a6c34
commit c453e7ac43
2 changed files with 402 additions and 265 deletions

View File

@ -10,6 +10,58 @@ let eventEmitter
const mcopy = {} const mcopy = {}
async function delay (ms) {
return new Promise(resolve => {
return setTimeout(resolve, ms)
})
}
async function send (device, cmd) {
return new Promise ((resolve, reject) => {
mcopy.arduino.serial[device].write(cmd, (err, results) => {
if (err) {
//console.error(err)
return reject(err)
}
return resolve(results)
})
})
}
async function write (device, str) {
return new Promise ((resolve, reject) => {
mcopy.arduino.serial[device].write(str, function (err, results) {
if (err) {
return reject(err)
}
//console.log('sent: ' + str)
return resolve(results)
})
})
}
async function open (device) {
return new Promise((resolve, reject) => {
return mcopy.arduino.serial[device].open(error => {
if (error) {
return reject(error)
}
return resolve(true)
})
})
}
async function close (device) {
return new Promise((resolve, reject) => {
return mcopy.arduino.serial[device].close((err) => {
if (err) {
return reject(err)
}
return resolve(true)
})
})
}
/****** /******
Arduino handlers Arduino handlers
*******/ *******/
@ -40,10 +92,13 @@ mcopy.arduino = {
lock : false lock : false
} }
mcopy.arduino.enumerate = function (callback) { mcopy.arduino.enumerate = async function () {
return new Promise( (resolve, reject) => {
return SerialPort.list((err, ports) => {
let matches = [] let matches = []
SerialPort.list((err, ports) => { if (err) {
//console.dir(ports) return reject(err)
}
ports.forEach(port => { ports.forEach(port => {
if (mcopy.arduino.known.indexOf(port.comName) !== -1) { if (mcopy.arduino.known.indexOf(port.comName) !== -1) {
matches.push(port.comName) matches.push(port.comName)
@ -52,44 +107,52 @@ mcopy.arduino.enumerate = function (callback) {
} }
}) })
if (matches.length === 0) { if (matches.length === 0) {
if (callback) { callback('No USB devices found'); } return reject('No USB devices found');
} else if (matches.length > 0) { } else if (matches.length > 0) {
if (callback) { callback(null, matches); } return resolve(matches)
} }
}) })
})
} }
//commands which respond to a sent char //commands which respond to a sent char
mcopy.arduino.send = function (serial, cmd, res) { mcopy.arduino.send = async function (serial, cmd, res) {
const device = mcopy.arduino.alias[serial] const device = mcopy.arduino.alias[serial]
if (!mcopy.arduino.lock) { let results
if (mcopy.arduino.lock) {
return false
}
mcopy.arduino.lock = true mcopy.arduino.lock = true
mcopy.arduino.queue[cmd] = res mcopy.arduino.queue[cmd] = res
setTimeout(() => { await delay(mcopy.cfg.arduino.serialDelay)
mcopy.arduino.serial[device].write(cmd, (err, results) => { try {
if (err) { console.log(err) } results = await send(device, cmd)
} catch (e) {
return console.error(e)
}
mcopy.arduino.lock = false mcopy.arduino.lock = false
mcopy.arduino.timer = new Date().getTime() mcopy.arduino.timer = new Date().getTime()
}) return await eventEmitter.emit('arduino_send', cmd)
}, mcopy.cfg.arduino.serialDelay) }
eventEmitter.emit('arduino_send', cmd)
}
};
//send strings, after char triggers firmware to accept //send strings, after char triggers firmware to accept
mcopy.arduino.string = function (serial, str) { mcopy.arduino.string = async function (serial, str) {
const device = mcopy.arduino.alias[serial] const device = mcopy.arduino.alias[serial]
setTimeout(function () { let writeSuccess
await delay(mcopy.cfg.arduino.serialDelay)
if (typeof mcopy.arduino.serial[device].fake !== 'undefined' if (typeof mcopy.arduino.serial[device].fake !== 'undefined'
&& mcopy.arduino.serial[device].fake) { && mcopy.arduino.serial[device].fake) {
mcopy.arduino.serial[device].string(str); return mcopy.arduino.serial[device].string(str)
} else { } else {
mcopy.arduino.serial[device].write(str, function (err, results) { try {
if (err) { console.log(err); } writeSuccess = await write(device, str)
//console.log('sent: ' + str); } catch (e) {
}); return console.error(e)
} }
}, mcopy.cfg.arduino.serialDelay); return writeSuccess
}; }
}
//respond with same char over serial when done //respond with same char over serial when done
mcopy.arduino.end = function (data) { mcopy.arduino.end = function (data) {
var end = new Date().getTime(), var end = new Date().getTime(),
@ -98,32 +161,35 @@ mcopy.arduino.end = function (data) {
mcopy.arduino.lock = false; mcopy.arduino.lock = false;
//console.log('Command ' + data + ' took ' + ms + 'ms'); //console.log('Command ' + data + ' took ' + ms + 'ms');
mcopy.arduino.queue[data](ms); //execute callback mcopy.arduino.queue[data](ms); //execute callback
eventEmitter.emit('arduino_end', data); eventEmitter.emit('arduino_end', data)
delete mcopy.arduino.queue[data]; delete mcopy.arduino.queue[data]
} else { } else {
console.log('Received stray "' + data + '"'); //silent to user //console.log('Received stray "' + data + '"'); //silent to user
} }
}; };
mcopy.arduino.alias = function (serial, device) { mcopy.arduino.alias = function (serial, device) {
console.log(`Making "${serial}" an alias of ${device}`) console.log(`Making "${serial}" an alias of ${device}`)
mcopy.arduino.alias[serial] = device mcopy.arduino.alias[serial] = device
} }
mcopy.arduino.connect = function (serial, device, confirm, callback) { mcopy.arduino.connect = async function (serial, device, confirm) {
return new Promise(async (resolve, reject) => {
let connectSuccess
mcopy.arduino.path[serial] = device; mcopy.arduino.path[serial] = device;
mcopy.arduino.alias[serial] = device; mcopy.arduino.alias[serial] = device;
mcopy.arduino.serial[device] = new SerialPort(mcopy.arduino.path[serial], { mcopy.arduino.serial[device] = new SerialPort(mcopy.arduino.path[serial], {
autoOpen : false, autoOpen : false,
baudRate: mcopy.cfg.arduino.baud, baudRate: mcopy.cfg.arduino.baud,
parser: parser parser: parser
}); })
mcopy.arduino.serial[device].open(error => { try {
if (error) { connectSuccess = await open(device)
if (callback) { callback(error); } } catch (e) {
return console.log('failed to open: '+ error); console.error('failed to open: ' + e)
} else { return reject(e)
}
console.log(`Opened connection with ${mcopy.arduino.path[serial]} as ${serial}`); console.log(`Opened connection with ${mcopy.arduino.path[serial]} as ${serial}`);
if (!confirm) { if (!confirm) {
mcopy.arduino.serial[device].on('data', data => { mcopy.arduino.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, '')
mcopy.arduino.end(d) mcopy.arduino.end(d)
@ -135,12 +201,10 @@ mcopy.arduino.connect = function (serial, device, confirm, callback) {
mcopy.arduino.confirmEnd(d) mcopy.arduino.confirmEnd(d)
}) })
} }
if (callback) { return resolve(mcopy.arduino.path[serial])
callback(null, mcopy.arduino.path[serial]) })
}
} }
});
};
mcopy.arduino.confirmExec = {}; mcopy.arduino.confirmExec = {};
mcopy.arduino.confirmEnd = function (data) { mcopy.arduino.confirmEnd = function (data) {
@ -155,24 +219,32 @@ mcopy.arduino.confirmEnd = function (data) {
mcopy.arduino.confirmExec(null, data); mcopy.arduino.confirmExec(null, data);
mcopy.arduino.confirmExec = {}; mcopy.arduino.confirmExec = {};
} }
}; }
mcopy.arduino.verify = function (callback) {
mcopy.arduino.verify = async function () {
return new Promise(async (resolve, reject) => {
const device = mcopy.arduino.alias['connect'] const device = mcopy.arduino.alias['connect']
let writeSuccess
mcopy.arduino.confirmExec = function (err, data) { mcopy.arduino.confirmExec = function (err, data) {
if (data === mcopy.cfg.arduino.cmd.connect) { if (data === mcopy.cfg.arduino.cmd.connect) {
callback(null, true); return resolve(true)
} else {
return reject('Wrong data returned')
} }
};
setTimeout(function () {
mcopy.arduino.serial[device].write(mcopy.cfg.arduino.cmd.connect, (err, results) => {
if (err) {
return console.log(err);
} }
}); await delay(mcopy.cfg.arduino.serialDelay)
}, mcopy.cfg.arduino.serialDelay); try {
}; writeSuccess = await send(device, mcopy.cfg.arduino.cmd.connect)
mcopy.arduino.distinguish = function (callback) { } catch (e) {
return reject(e)
}
return resolve(writeSuccess)
})
}
mcopy.arduino.distinguish = async function (callback) {
const device = mcopy.arduino.alias['connect'] const device = mcopy.arduino.alias['connect']
let writeSuccess
mcopy.arduino.confirmExec = function (err, data) { mcopy.arduino.confirmExec = function (err, data) {
if (data === mcopy.cfg.arduino.cmd.proj_identifier) { if (data === mcopy.cfg.arduino.cmd.proj_identifier) {
callback(null, 'projector'); callback(null, 'projector');
@ -188,30 +260,33 @@ mcopy.arduino.distinguish = function (callback) {
callback(null, 'projector,camera') callback(null, 'projector,camera')
} }
} }
setTimeout(function () { await delay(mcopy.cfg.arduino.serialDelay)
mcopy.arduino.serial[device].write(mcopy.cfg.arduino.cmd.mcopy_identifier, function (err, results) { try {
if (err) { writeSuccess = await send(device, mcopy.cfg.arduino.cmd.mcopy_identifier)
return console.log(err); } catch (e) {
return console.error(e)
} }
}); return writeSuccess
}, mcopy.cfg.arduino.serialDelay);
} }
mcopy.arduino.close = function (callback) { mcopy.arduino.close = async function (callback) {
let device = mcopy.arduino.alias['connect'] const device = mcopy.arduino.alias['connect']
mcopy.arduino.serial[device].close((err) => { let closeSuccess
if (callback) { try {
callback(err) closeSuccess = await close(device)
} catch (e) {
return console.error(e)
} }
}); return closeSuccess
}; };
mcopy.arduino.fakeConnect = function (serial, callback) { mcopy.arduino.fakeConnect = async function (serial) {
//console.log('Connecting to fake arduino...'); //console.log('Connecting to fake arduino...');
const device = '/dev/fake' const device = '/dev/fake'
mcopy.arduino.alias[serial] = device mcopy.arduino.alias[serial] = device
mcopy.arduino.serial[device] = { mcopy.arduino.serial[device] = {
write : function (cmd, res) { write : async function (cmd, res) {
return new Promise(async (resolve, reject) => {
var t = { var t = {
c : mcopy.cfg.arduino.cam.time + mcopy.cfg.arduino.cam.delay, c : mcopy.cfg.arduino.cam.time + mcopy.cfg.arduino.cam.delay,
p : mcopy.cfg.arduino.proj.time + mcopy.cfg.arduino.proj.delay p : mcopy.cfg.arduino.proj.time + mcopy.cfg.arduino.proj.delay
@ -219,18 +294,18 @@ mcopy.arduino.fakeConnect = function (serial, callback) {
timeout = t[cmd]; timeout = t[cmd];
if (typeof timeout === 'undefined') timeout = 10; if (typeof timeout === 'undefined') timeout = 10;
mcopy.arduino.timer = +new Date(); mcopy.arduino.timer = +new Date();
setTimeout(() => { await delay(timeout)
mcopy.arduino.end(cmd) return await mcopy.arduino.end(cmd)
}, timeout) })
}, },
string : function (str) { string : async function (str) {
//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! Doesn\'t exist!');
if (callback) callback() return true
} }
if (typeof module !== 'undefined' && module.parent) { if (typeof module !== 'undefined' && module.parent) {

View File

@ -36,6 +36,12 @@ let camera
let server let server
let menu let menu
async function delay (ms) {
return new Promise(resolve => {
return setTimeout(resolve, ms)
})
}
//console.log(process.version) //console.log(process.version)
mcopy.cfg = require('./data/cfg.json') mcopy.cfg = require('./data/cfg.json')
@ -53,17 +59,18 @@ dev.listen = function () {
}) })
} }
dev.enumerate = function (err, devices) { dev.enumerate = async function () {
if (err) { let devices
try{
devices = await arduino.enumerate()
} catch (err) {
log.info(err, 'SERIAL', false, true) log.info(err, 'SERIAL', false, true)
setTimeout(() =>{ await delay(1000)
dev.all([]) return dev.all([])
}, 1000) }
} else {
log.info(`Found ${devices.length} USB devices`, 'SERIAL', true, true) log.info(`Found ${devices.length} USB devices`, 'SERIAL', true, true)
devices = dev.favor(devices) devices = dev.favor(devices)
dev.all(devices) return dev.all(devices)
}
} }
dev.favor = function (devices) { dev.favor = function (devices) {
@ -88,162 +95,218 @@ dev.favor = function (devices) {
return devices return devices
} }
dev.distinguish = function (device, callback) { dev.distinguish = async function (device, callback) {
var connectCb = function (err, device) { let connectSuccess
if (err) { let verifySuccess
return console.error(err) let type
try {
connectSuccess = await arduino.connect('connect', device, true)
} catch (err) {
console.error(err)
return null
} }
setTimeout(function () {
arduino.verify(verifyCb) await delay(2000)
}, 2000);
}, try {
verifyCb = function (err, success) { verifySuccess = await arduino.verify()
if (err) { } catch (err) {
return console.error(err) console.error(err)
return null
} }
log.info(`Verified ${device} as mcopy device`, 'SERIAL', true, true) log.info(`Verified ${device} as mcopy device`, 'SERIAL', true, true)
setTimeout(function () { await delay(1000)
arduino.distinguish(distinguishCb);
}, 1000);
},
distinguishCb = function (err, type) {
if (err) {
return console.error(err)
}
dev.remember('arduino', device, type)
log.info(`Determined ${device} to be ${type}`, 'SERIAL', true, true) try {
if (callback) { callback(err, type); } type = await arduino.distinguish()
} catch (err) {
console.error(err)
return null
} }
arduino.connect('connect', device, true, connectCb)
}; dev.remember('arduino', device, type)
log.info(`Determined ${device} to be ${type}`, 'SERIAL', true, true)
return type
}
dev.fakeProjector = async function () {
dev.connected.projector = '/dev/fake'
try {
await arduino.fakeConnect('projector')
} catch (err) {
console.error(err)
log.error(`Error connecting to fake PRONECTOR device`, 'SERIAL', true, true)
return false
}
log.info('Connected to fake PROJECTOR device', 'SERIAL', true, true)
return true
}
dev.fakeCamera = async function () {
dev.connected.camera = '/dev/fake'
try {
await arduino.fakeConnect('camera')
} catch (err) {
console.error(err)
log.error(`Error connecting to fake CAMERA device`, 'SERIAL', true, true)
return false
}
log.info('Connected to fake CAMERA device', 'SERIAL', true, true)
return true
}
dev.fakeLight = async function () {
dev.connected.light = '/dev/fake'
try {
await arduino.fakeConnect('light')
} catch (err) {
console.error(err)
log.error(`Error connecting to fake LIGHT device`, 'SERIAL', true, true)
return false
}
log.info('Connected to fake LIGHT device', 'SERIAL', true, true)
return true
}
dev.connectDevice = async function (device, type) {
let closeSuccess
let connectSuccess
try {
closeSuccess = await arduino.close()
} catch (err) {
console.error(err)
return false
}
if (type === 'projector') {
dev.connected.projector = device
try {
connectSuccess = await arduino.connect('projector', device, false)
} catch (err) {
console.error(err)
return false
}
log.info(`Connected to ${device} as PROJECTOR`, 'SERIAL', true, true)
} else if (type === 'camera') {
dev.connected.camera = device
try {
connectSuccess = await arduino.connect('camera', device, false)
} catch (err) {
console.error(err)
return false
}
log.info(`Connected to ${device} as CAMERA`, 'SERIAL', true, true)
} else if (type === 'light') {
dev.connected.light = device
try {
connectSuccess = await arduino.connect('light', device, false)
} catch (err) {
console.error(err)
return false
}
log.info(`Connected to ${device} as LIGHT`, 'SERIAL', true, true)
} else if (type === 'projector,light') {
dev.connected.projector = device
dev.connected.light = device
arduino.alias('light', device)
try{
connectSuccess = await arduino.connect('projector', device, false)
} catch (err) {
console.error(err)
return false
}
log.info(`Connected to ${device} as PROJECTOR + LIGHT`, 'SERIAL', true, true)
} else if (type === 'projector,camera,light') {
dev.connected.projector = device
dev.connected.camera = device
dev.connected.light = device
arduino.alias('camera', device)
arduino.alias('light', device)
try {
connectSuccess = await arduino.connect('projector', device, false)
} catch (err) {
console.error(err)
return false
}
log.info(`Connected to ${device} as PROJECTOR + CAMERA + LIGHT`, 'SERIAL', true, true)
} else if (type === 'projector,camera') {
dev.connected.projector = device
dev.connected.camera = device
arduino.alias('camera', device)
try {
connectSuccess = await arduino.connect('projector', device, false)
} catch (err) {
console.error(err)
return false
}
log.info(`Connected to ${device} as PROJECTOR`, 'SERIAL', true, true)
}
return connectSuccess
}
//Cases for 1 or 2 arduinos connected //Cases for 1 or 2 arduinos connected
dev.all = function (devices) { dev.all = async function (devices) {
const connected = { dev.connected = {
projector : false, projector : false,
camera : false, camera : false,
light : false light : false
} }
let checklist = [] let checklist = []
var fakeProjector = function () {
connected.projector = '/dev/fake'
arduino.fakeConnect('projector', () => {
log.info('Connected to fake PROJECTOR device', 'SERIAL', true, true)
}) /*await Promise.all(devices.map(async (device) => {
} return new Promise( async (resolve, reject) => {
var fakeCamera = function () { let type
connected.camera = '/dev/fake' let d
arduino.fakeConnect('camera', () => { try {
log.info('Connected to fake CAMERA device', 'SERIAL', true, true) type = await dev.distinguish(device)
}) } catch (err) {
}
var fakeLight = function () {
connected.light = '/dev/fake'
arduino.fakeConnect('light', () => {
log.info('Connected to fake LIGHT device', 'SERIAL', true, true)
})
}
var distinguishCb = function (device, type, cb) {
arduino.close(() => {
if (type === 'projector') {
connected.projector = device
arduino.connect('projector', device, false, () => {
log.info(`Connected to ${device} as PROJECTOR`, 'SERIAL', true, true)
cb()
})
} else if (type === 'camera') {
connected.camera = device
arduino.connect('camera', device, false, () => {
log.info(`Connected to ${device} as CAMERA`, 'SERIAL', true, true)
cb()
})
} else if (type === 'light') {
connected.light = device
arduino.connect('light', device, false, () => {
log.info(`Connected to ${device} as LIGHT`, 'SERIAL', true, true)
cb()
})
} else if (type === 'projector,light') {
connected.projector = device
connected.light = device
arduino.connect('projector', device, false, () => {
log.info(`Connected to ${device} as PROJECTOR + LIGHT`, 'SERIAL', true, true)
cb()
})
arduino.alias('light', device)
} else if (type === 'projector,camera,light') {
connected.projector = device
connected.camera = device
connected.light = device
arduino.connect('projector', device, false, () => {
log.info(`Connected to ${device} as PROJECTOR + CAMERA + LIGHT`, 'SERIAL', true, true)
cb()
})
arduino.alias('camera', device)
arduino.alias('light', device)
} else if (type === 'projector,camera') {
connected.projector = device
connected.camera = device
arduino.connect('projector', device, false, () => {
log.info(`Connected to ${device} as PROJECTOR`, 'SERIAL', true, true)
cb()
})
arduino.alias('camera', device)
} else {
cb()
}
})
}
checklist = devices.map(device => {
return next => {
dev.distinguish(device, (err, type) => {
if (err) {
console.error(err) console.error(err)
return next() return reject(err)
} }
distinguishCb(device, type, next) try {
}) d = await dev.connectDevice(device, type)
} catch (err) {
console.error(err)
return reject(err)
} }
return resolve(d)
}) })
})*/
async.series(checklist, () => {
//done checking devices //done checking devices
let c = {} let c = {}
let p = {} let p = {}
let l = {} let l = {}
if (!connected.projector) { if (!dev.connected.projector) {
fakeProjector() await dev.fakeProjector()
} }
p.arduino = connected.projector p.arduino = dev.connected.projector
if (!connected.camera) { if (!dev.connected.camera) {
fakeCamera() await dev.fakeCamera()
} }
c.arduino = connected.camera c.arduino = dev.connected.camera
if (mcopy.settings.camera.intval) { if (mcopy.settings.camera.intval) {
c.intval = mcopy.settings.camera.intval c.intval = mcopy.settings.camera.intval
console.dir(mcopy.settings.camera) console.dir(mcopy.settings.camera)
setTimeout(() => { await delay(1000)
cam.connectIntval(null, { connect : true, url : c.intval }) cam.connectIntval(null, { connect : true, url : c.intval })
}, 1000)
} }
if (!connected.light) { if (!dev.connected.light) {
fakeLight() await dev.fakeLight()
} }
l.arduino = connected.light
l.arduino = dev.connected.light
dev.ready(p, c, l) dev.ready(p, c, l)
}) }
};
dev.remember = function (which, device, type) { dev.remember = function (which, device, type) {
let deviceEntry let deviceEntry
@ -539,7 +602,7 @@ transfer.listen = function () {
}) })
} }
*/ */
var init = function () { var init = async function () {
createWindow() createWindow()
createMenu() createMenu()
@ -560,9 +623,8 @@ var init = function () {
settings.restore() settings.restore()
mcopy.settings = settings.all() mcopy.settings = settings.all()
setTimeout( () => { await delay(1000)
arduino.enumerate(dev.enumerate) await dev.enumerate()
}, 1000)
} }
app.on('ready', init) app.on('ready', init)