This commit is contained in:
Koen Kanters
2020-06-15 20:10:30 +02:00
parent 79b4dbd24f
commit f8d082e18d
4 changed files with 103 additions and 16 deletions
+1 -5
View File
@@ -41,11 +41,7 @@ class Bridge extends Extension {
async onMQTTMessage(topic, message) {
const match = topic.match(requestRegex);
if (match && this.requestLookup[match[1].toLowerCase()]) {
try {
message = JSON.parse(message);
} catch (e) {
e;
}
message = utils.parseJSON(message, message);
try {
const response = await this.requestLookup[match[1].toLowerCase()](message);
+28
View File
@@ -13,6 +13,7 @@ class NetworkMap extends Extension {
this.legacyApi = settings.get().advanced.legacy_api;
this.legacyTopic = `${settings.get().mqtt.base_topic}/bridge/networkmap`;
this.legacyTopicRoutes = `${settings.get().mqtt.base_topic}/bridge/networkmap/routes`;
this.topic = `${settings.get().mqtt.base_topic}/bridge/request/networkmap`;
// Bind
this.raw = this.raw.bind(this);
@@ -33,6 +34,10 @@ class NetworkMap extends Extension {
this.mqtt.subscribe(this.legacyTopic);
this.mqtt.subscribe(this.legacyTopicRoutes);
}
if (settings.get().experimental.new_api) {
this.mqtt.subscribe(this.topic);
}
}
async onMQTTMessage(topic, message) {
@@ -46,6 +51,29 @@ class NetworkMap extends Extension {
this.mqtt.publish(`bridge/networkmap/${message}`, converted, {});
}
}
if (settings.get().experimental.new_api && topic === this.topic) {
try {
message = utils.parseJSON(message, message);
const type = typeof message === 'object' ? message.type : message;
if (!this.supportedFormats.hasOwnProperty(type)) {
throw new Error(`Type '${type}' not supported, allowed are: ${Object.keys(this.supportedFormats)}`);
}
const routes = typeof message === 'object' && message.routes;
const topology = await this.networkScan(routes);
const value = this.supportedFormats[type](topology);
await this.mqtt.publish(
'bridge/response/networkmap',
JSON.stringify(utils.getResponse(message, {routes, type, value}, null)),
);
} catch (error) {
await this.mqtt.publish(
'bridge/response/networkmap',
JSON.stringify(utils.getResponse(message, {}, error.message)),
);
}
}
}
raw(topology) {
+9
View File
@@ -142,6 +142,14 @@ function getResponse(request, data, error) {
return response;
}
function parseJSON(value, failedReturnValue) {
try {
return JSON.parse(value);
} catch (e) {
return failedReturnValue;
}
}
module.exports = {
millisecondsToSeconds: (milliseconds) => milliseconds / 1000,
secondsToMilliseconds: (seconds) => seconds * 1000,
@@ -160,4 +168,5 @@ module.exports = {
equalsPartial,
getResponse,
capitalize,
parseJSON,
};