code optimization and fixes for blinky

This commit is contained in:
Daniel Sommer 2022-03-10 00:32:38 +01:00
parent 99be4a2ad5
commit dc01956269
9 changed files with 125 additions and 104 deletions

View file

@ -5,7 +5,7 @@
}, },
"cache": { "cache": {
"active": true, "active": true,
"lifetime": 15 "lifetime": 0
}, },
"log": { "log": {
"level": "debug", "level": "debug",

View file

@ -7,96 +7,65 @@ const info = require('./info.js');
const endpoints = new Map(); const endpoints = new Map();
function setEndpoint(url, get, post) { function setEndpoint(url, get, post) {
return new Promise(function (resolve, reject) { if (get === undefined && post === undefined) {
if (get == undefined && post == undefined) { return;
return resolve();
} }
var endpoint = {}; var endpoint = {};
if (get != undefined) { if (get !== undefined) {
endpoint.GET = get; endpoint.GET = get;
} }
if (post != undefined) { if (post !== undefined) {
endpoint.POST = post; endpoint.POST = post;
} }
endpoints.set(url, endpoint); endpoints.set(url, endpoint);
logger.debug('set up endpoint \'' + url + '\' > ' + JSON.stringify(endpoint)); logger.debug('set up endpoint \'' + url + '\' > ' + JSON.stringify(endpoint));
return resolve();
});
} }
function getEndpoints() { function getEndpoints() {
return endpoints; return endpoints;
} }
function setupEndpoints() { async function setupEndpoints() {
return new Promise(function (resolve, reject) { const timestamp = new Date();
var startTime = new Date();
logger.debug('setting up endpoints...'); logger.debug('setting up endpoints...');
setEndpoint(constants.API_INFO, { method: info.getHostInfo }) setEndpoint(constants.API_INFO, { method: info.getHostInfo });
.then(setEndpoint(constants.API_TEMPERATURE, { method: info.getTemperature })) setEndpoint(constants.API_TEMPERATURE, { method: info.getTemperature });
.then(modep.getBanks) setEndpoint(constants.API_BANKS, { method: modep.getBanks })
.then(function (banks) { setEndpoint(constants.API_BANKS_BY_ID, { method: modep.getBankById });
setEndpoint(constants.API_BANKS, { method: modep.getBanks });
for (var index = 0; index < banks.length; index++) {
var id = banks[index].id;
setEndpoint(
constants.API_BANKS + '/' + id,
{ method: modep.getBankById, id: id }
);
}
})
.then(modep.getPedalboards)
.then(function (pedalboards) {
setEndpoint(constants.API_PEDALBOARDS, { method: modep.getPedalboards }); setEndpoint(constants.API_PEDALBOARDS, { method: modep.getPedalboards });
for (var index = 0; index < pedalboards.length; index++) {
var id = pedalboards[index].id;
setEndpoint( setEndpoint(
constants.API_PEDALBOARDS + '/' + id, constants.API_PEDALBOARDS_BY_ID,
{ method: modep.getPedalboardById, id: id }, { method: modep.getPedalboardById },
{ method: modep.setPedalboardById, id: id } { method: modep.setPedalboardById }
); );
} setEndpoint(
})
.then(setEndpoint(
constants.API_PEDALBOARDS_DEFAULT, constants.API_PEDALBOARDS_DEFAULT,
{ method: modep.getDefaultPedalboard } { method: modep.getDefaultPedalboard }
)) );
.then(setEndpoint( setEndpoint(
constants.API_PEDALBOARDS_CURRENT, constants.API_PEDALBOARDS_CURRENT,
{ method: modep.getCurrentPedalboard } { method: modep.getCurrentPedalboard }
)) );
.then(setEndpoint(
constants.API_BYPASS,
undefined,
{ method: modep.toggleBypass }
))
.then(modep.getCurrentPedals)
.then(function (pedals) {
setEndpoint( setEndpoint(
constants.API_PEDALS, constants.API_PEDALS,
{ method: modep.getCurrentPedals } { method: modep.getCurrentPedals }
); );
for (var index = 0; index < pedals.length; index++) {
var id = pedals[index].id;
setEndpoint( setEndpoint(
constants.API_PEDALS + '/' + id, constants.API_PEDAL_BY_ID,
{ method: modep.getCurrentPedalById, id: id }, { method: modep.getCurrentPedalById },
{ method: modep.setControlByRequest, id: id } { method: modep.setControlByRequest }
); );
setEndpoint( setEndpoint(
constants.API_BYPASS + '/' + id, constants.API_BYPASS,
undefined, undefined,
{ method: modep.toggleBypass, id: id } { method: modep.toggleBypass }
); );
} setEndpoint(
}) constants.API_BYPASS_BY_ID,
.then(function () { undefined,
logger.debug('setting up ' + endpoints.size + ' endpoints took ' + util.timeDiff(startTime) + 'ms'); { method: modep.toggleBypass }
resolve(); );
}) logger.debug('setting up ' + endpoints.size + ' endpoints took ' + util.timeDiff(timestamp) + 'ms');
.catch(reject);
});
} }
module.exports = { module.exports = {

View file

@ -108,7 +108,6 @@ async function setBypass(bypassActive) {
} }
} }
function getPedalColorByName(name) { function getPedalColorByName(name) {
return global.config.blinky?.colors[name] || 'random'; return global.config.blinky?.colors[name] || 'random';
} }

View file

@ -1,10 +1,13 @@
const config = require('../config.json'); const config = require('../config.json');
const logger = require('./logger.js'); const logger = require('./logger.js');
const constants = require('./constants.js'); const constants = require('./constants.js');
const timeDiff = require('./util.js').timeDiff;
const active = config.cache.active; const active = config.cache.active;
const lifetime = config.cache.lifetime * 60000; const lifetime = config.cache.lifetime * 60000;
let modep;
const cache = new Map(); const cache = new Map();
function isActive() { function isActive() {
@ -15,8 +18,26 @@ function getLifetime() {
return lifetime; return lifetime;
} }
async function fill() {
if (!isActive) {
return;
}
const timestamp = new Date();
logger.debug('filling cache...');
clear();
if (modep === undefined) {
modep = require('./modep.js');
}
await modep.getBanks();
await modep.getPedalboards();
await modep.getDefaultPedalboard();
await modep.getCurrentPedalboard();
await modep.getCurrentPedals();
logger.debug('cache filled after ' + timeDiff(timestamp) + 'ms');
}
function clear() { function clear() {
cache = new Map(); cache.clear();
} }
function validLifetime(timestamp) { function validLifetime(timestamp) {
@ -42,7 +63,7 @@ function getValue(key) {
} }
function setValue(key, value) { function setValue(key, value) {
if (!active) { if (!isActive) {
return; return;
} }
logger.debug('caching \'' + key + '\'...'); logger.debug('caching \'' + key + '\'...');
@ -128,6 +149,7 @@ function setInfo(value) {
module.exports = { module.exports = {
isActive, isActive,
getLifetime, getLifetime,
fill,
clear, clear,
getBanks, getBanks,
clearBanks, clearBanks,

View file

@ -1,9 +1,11 @@
const logger = require('./logger.js'); const logger = require('./logger.js');
const util = require('./util.js');
const { spawn } = require('child_process'); const { spawn } = require('child_process');
function execute(cmd, args) { function execute(cmd, args) {
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
var spawned = spawn(cmd, args); var spawned = spawn(cmd, args);
spawned.timestamp = new Date();
spawned.stdout.on('data', function (data) { spawned.stdout.on('data', function (data) {
logger.debug(data); logger.debug(data);
}); });
@ -11,11 +13,11 @@ function execute(cmd, args) {
logger.error(data); logger.error(data);
}); });
spawned.on('close', function (code) { spawned.on('close', function (code) {
logger.debug('command \'' + cmd + '\' with args \'' + args + '\' finished with exit code ' + code); logger.debug('command \'' + cmd + '\' with args \'' + args + '\' finished with exit code ' + code + ' after ' + util.timeDiff(spawned.timestamp) + 'ms');
resolve(); resolve();
}); });
spawned.on('error', function (err) { spawned.on('error', function (err) {
return reject('command \'' + cmd + '\' with args \'' + args + '\' encountered an error >>> ' + err); return reject('command \'' + cmd + '\' with args \'' + args + '\' encountered an error after ' + util.timeDiff(spawned.timestamp) + 'ms >>> ' + err);
}); });
}); });
} }

View file

@ -1,14 +1,30 @@
const VARIABLE_ID = '{{ id }}';
const INFO = '/info';
const TEMPERATURE = '/temperature';
const BANKS = '/banks';
const PEDALBOARDS = '/pedalboards';
const PEDALS = '/pedals';
const BYPASS = '/bypass';
exports.VARIABLE_ID = VARIABLE_ID;
exports.HTTP_GET = 'GET'; exports.HTTP_GET = 'GET';
exports.HTTP_POST = 'POST'; exports.HTTP_POST = 'POST';
exports.API_INFO = '/info'; exports.API_INFO = INFO;
exports.API_TEMPERATURE = '/temperature'; exports.API_TEMPERATURE = TEMPERATURE;
exports.API_BANKS = '/banks'; exports.API_BANKS = BANKS;
exports.API_PEDALBOARDS = '/pedalboards'; exports.API_BANKS_BY_ID = BANKS + '/' + VARIABLE_ID;
exports.API_PEDALBOARDS_DEFAULT = '/pedalboards/default'; exports.API_PEDALBOARDS = PEDALBOARDS;
exports.API_PEDALBOARDS_CURRENT = '/pedalboards/current'; exports.API_PEDALBOARDS_DEFAULT = PEDALBOARDS + '/default';
exports.API_PEDALS = '/pedals'; exports.API_PEDALBOARDS_CURRENT = PEDALBOARDS + '/current';
exports.API_BYPASS = '/bypass'; exports.API_PEDALBOARDS_BY_ID = PEDALBOARDS + '/' + VARIABLE_ID;
exports.API_PEDALS = PEDALS;
exports.API_PEDAL_BY_ID = PEDALS + '/' + VARIABLE_ID;
exports.API_BYPASS = BYPASS;
exports.API_BYPASS_BY_ID = BYPASS + '/' + VARIABLE_ID;
exports.CACHE_INFO = "info"; exports.CACHE_INFO = "info";
exports.CACHE_BANKS = "banks"; exports.CACHE_BANKS = "banks";

View file

@ -450,7 +450,7 @@ async function toggleBypass(pedalId) {
} }
try { try {
await setControl(bypass, value); await setControl(bypass, value);
blinky.setPedalStatus([pedal]); blinky.setPedalStatus(pedal);
} catch (err) { } catch (err) {
throw new Error('could not toggle bypass for pedal ' + pedal.name + ' with id \'' + pedal.id + '\' > ' + err); throw new Error('could not toggle bypass for pedal ' + pedal.name + ' with id \'' + pedal.id + '\' > ' + err);
} }

View file

@ -4,6 +4,8 @@ const api = require('./api.js');
const blinky = require('./blinky.js'); const blinky = require('./blinky.js');
const http = require('http'); const http = require('http');
const ID = require('./constants.js').VARIABLE_ID;
var server; var server;
async function start() { async function start() {
@ -20,11 +22,20 @@ async function start() {
function handleRequests() { function handleRequests() {
server.on('request', function (request, response) { server.on('request', function (request, response) {
request.timestamp = new Date().getTime(); request.timestamp = new Date().getTime();
if (request.url.endsWith('/')) { if (request.url.length > 1 && request.url.endsWith('/')) {
request.url = request.url.substring(0, request.url.length - 1); request.url = request.url.substring(0, request.url.length - 1);
} }
var endpoint = api.getEndpoints().get(request.url); let id;
if (!endpoint) { let endpointName = request.url;
let separatorIndex = request.url.lastIndexOf('/');
if (separatorIndex > 0) {
id = request.url.substring(separatorIndex + 1, request.url.length);
if (!isNaN(id)) {
endpointName = endpointName.substring(0, separatorIndex + 1) + ID;
}
}
var endpoint = api.getEndpoints().get(endpointName);
if (endpoint === undefined) {
endRequest( endRequest(
request, request,
response, response,
@ -34,7 +45,7 @@ function handleRequests() {
return; return;
} }
endpoint = endpoint[request.method]; endpoint = endpoint[request.method];
if (endpoint == undefined || endpoint.method == undefined) { if (endpoint === undefined || endpoint.method === undefined) {
endRequest( endRequest(
request, request,
response, response,
@ -45,7 +56,7 @@ function handleRequests() {
} }
getRequestParams(request) getRequestParams(request)
.then(function (params) { .then(function (params) {
return endpoint.method(endpoint.id, params); return endpoint.method(id, params);
}) })
.then(function (result) { .then(function (result) {
endRequest(request, response, result); endRequest(request, response, result);

2
pbc.js
View file

@ -3,6 +3,7 @@ const api = require('./libs/api.js');
const server = require('./libs/server.js') const server = require('./libs/server.js')
const util = require('./libs/util.js'); const util = require('./libs/util.js');
const blinky = require('./libs/blinky.js'); const blinky = require('./libs/blinky.js');
const cache = require('./libs/cache.js');
const packageJSON = require('./package.json'); const packageJSON = require('./package.json');
const INTERRUPTS = ['beforeExit', 'SIGINT', 'SIGTERM']; const INTERRUPTS = ['beforeExit', 'SIGINT', 'SIGTERM'];
@ -23,6 +24,7 @@ util.fileExists(config)
.then(() => { .then(() => {
logger.info("launching " + packageJSON.name + " " + packageJSON.version); logger.info("launching " + packageJSON.name + " " + packageJSON.version);
}) })
.then(cache.fill)
.then(api.setupEndpoints) .then(api.setupEndpoints)
.then(server.start) .then(server.start)
.catch((err) => { .catch((err) => {