Closed ws1088 closed 3 years ago
@PeterStaev This is probably similar to #16, 1
is a valid JSON string. What I have seen and done in other python libraries is to look for at least open curly brace first. If yes, then attempt to parse JSON. If no, then print it out. You can do fancier logic to look for things like {"m":
@PeterStaev A very "hacky" solution to show the cause of the problem.
constructor(location: string, logger: Logger) {
this._serialPort = new SerialPort(location, {
baudRate: 115200,
autoOpen: false,
});
this._serialPort.setDefaultEncoding("utf-8");
this._parser = this._serialPort.pipe(new SerialPort.parsers.Readline({ delimiter: "\r" }));
this._parser.on("data", (data: string) => {
let json: { [key: string]: any };
let print_data = false;
try {
if ((data.length >= 1 && data.charAt(0) === "{") ||
(data.length >= 2 && data.charAt(0) === "\n" && data.charAt(1) === "{")) {
json = JSON.parse(data);
}
else {
print_data = true;
}
}
catch (e) {
print_data = true;
}
if (print_data) {
// When data cannot be JSON parsed we re probably getting text from user's `print` command so we log it
if (data.length > 0 && data.charAt(0) === "\n") {
logger?.info(data.substring(1).replace(/\n/gi, "\n\r"));
}
else {
logger?.info(data.replace(/\n/gi, "\n\r"));
}
logger?.info("\n\r");
return;
}
bare printing a number is not working:
but this will work