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": {
"active": true,
"lifetime": 15
"lifetime": 0
},
"log": {
"level": "debug",

View file

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

View file

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

View file

@ -1,10 +1,13 @@
const config = require('../config.json');
const logger = require('./logger.js');
const constants = require('./constants.js');
const timeDiff = require('./util.js').timeDiff;
const active = config.cache.active;
const lifetime = config.cache.lifetime * 60000;
let modep;
const cache = new Map();
function isActive() {
@ -15,8 +18,26 @@ function getLifetime() {
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() {
cache = new Map();
cache.clear();
}
function validLifetime(timestamp) {
@ -42,7 +63,7 @@ function getValue(key) {
}
function setValue(key, value) {
if (!active) {
if (!isActive) {
return;
}
logger.debug('caching \'' + key + '\'...');
@ -128,6 +149,7 @@ function setInfo(value) {
module.exports = {
isActive,
getLifetime,
fill,
clear,
getBanks,
clearBanks,

View file

@ -1,9 +1,11 @@
const logger = require('./logger.js');
const util = require('./util.js');
const { spawn } = require('child_process');
function execute(cmd, args) {
return new Promise(function (resolve, reject) {
var spawned = spawn(cmd, args);
spawned.timestamp = new Date();
spawned.stdout.on('data', function (data) {
logger.debug(data);
});
@ -11,11 +13,11 @@ function execute(cmd, args) {
logger.error(data);
});
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();
});
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_POST = 'POST';
exports.API_INFO = '/info';
exports.API_TEMPERATURE = '/temperature';
exports.API_BANKS = '/banks';
exports.API_PEDALBOARDS = '/pedalboards';
exports.API_PEDALBOARDS_DEFAULT = '/pedalboards/default';
exports.API_PEDALBOARDS_CURRENT = '/pedalboards/current';
exports.API_PEDALS = '/pedals';
exports.API_BYPASS = '/bypass';
exports.API_INFO = INFO;
exports.API_TEMPERATURE = TEMPERATURE;
exports.API_BANKS = BANKS;
exports.API_BANKS_BY_ID = BANKS + '/' + VARIABLE_ID;
exports.API_PEDALBOARDS = PEDALBOARDS;
exports.API_PEDALBOARDS_DEFAULT = PEDALBOARDS + '/default';
exports.API_PEDALBOARDS_CURRENT = PEDALBOARDS + '/current';
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_BANKS = "banks";

View file

@ -450,7 +450,7 @@ async function toggleBypass(pedalId) {
}
try {
await setControl(bypass, value);
blinky.setPedalStatus([pedal]);
blinky.setPedalStatus(pedal);
} catch (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 http = require('http');
const ID = require('./constants.js').VARIABLE_ID;
var server;
async function start() {
@ -20,11 +22,20 @@ async function start() {
function handleRequests() {
server.on('request', function (request, response) {
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);
}
var endpoint = api.getEndpoints().get(request.url);
if (!endpoint) {
let id;
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(
request,
response,
@ -34,7 +45,7 @@ function handleRequests() {
return;
}
endpoint = endpoint[request.method];
if (endpoint == undefined || endpoint.method == undefined) {
if (endpoint === undefined || endpoint.method === undefined) {
endRequest(
request,
response,
@ -45,7 +56,7 @@ function handleRequests() {
}
getRequestParams(request)
.then(function (params) {
return endpoint.method(endpoint.id, params);
return endpoint.method(id, params);
})
.then(function (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 util = require('./libs/util.js');
const blinky = require('./libs/blinky.js');
const cache = require('./libs/cache.js');
const packageJSON = require('./package.json');
const INTERRUPTS = ['beforeExit', 'SIGINT', 'SIGTERM'];
@ -23,6 +24,7 @@ util.fileExists(config)
.then(() => {
logger.info("launching " + packageJSON.name + " " + packageJSON.version);
})
.then(cache.fill)
.then(api.setupEndpoints)
.then(server.start)
.catch((err) => {