I'm trying to flip a switch based on a value I'm reading from my MQTT broker in Shelly script. My starting point was the "mqtt_discovery.js" example and I actually managed to get data read.
However, the data from the broker (mosqitto) is a JSON string - and that's where my problems start. While I managed to parse manually created JSON strings using JSON.parse(), I keep getting "Uncaught SyntaxError: Expecting a valid value, got EOF".
Could anybody please help me wrangle the (malformed?) JSON string?
Script:
JavaScript
// configuration object
let CONFIG = {
topic: "victron-multiplus/N/c0619ab08f1e/system/0/Ac/Grid/L1/Power",
threshold: 100,
};
// callback function for the subscriber
function MQTTCmdListener(topic, msg) {
print(msg);
var msgObj = JSON.parse(msg);
print(msgObj.value);
};
function subMQTT() {
MQTT.subscribe(CONFIG.topic, MQTTCmdListener);
};
subMQTT();
Alles anzeigen
Value in MQTT:
- plain: {"value": 193.2}
- string from Debug Log: "{\"value\": 193.2}"
Weird effect - if I use JSON.stringify() on the value, I get:
- plain: "{\"value\": 193.2}"
- string from Debug Log: "\"{\\\"value\\\": 187.6}\""
Error in debug log:
Code
< {"ts":1700520635.55< {"ts":1700520985.856, "level":2, "data":"shelly_scripts_rpc.:348 Sending \"script_1.js\""}
< {"ts":1700520985.869, "level":-1, "data":""}
< {"ts":1700520985.888, "level":-1, "data":"Uncaught SyntaxError: Expecting a valid value, got EOF"}
< {"ts":1700520985.891, "level":-1, "data":" at line 1 col 1"}
< {"ts":1700520985.892, "level":-1, "data":""}
< {"ts":1700520985.894, "level":-1, "data":"^"}
< {"ts":1700520985.898, "level":-1, "data":"in function called from system"}
< {"ts":1700520985.899, "level":-1, "data":""}
< {"ts":1700520985.905, "level":1, "data":"shelly_user_script.:397 syntax_error: Error in EjsCall"}
< {"ts":1700520985.935, "level":2, "data":"shelly_notification:163 Status change of script:1: {\"id\":1,\"errors\":[\"syntax_error\"],\"running\":false}"}