Point me in the right direction to Parse TCP string

I try to parse the string below .
I think it is possible with the contrib-buffer-parser node but i don`t understand the working of the node completly

If header 1 is 100 then there is a error

[1,49,53,2,48,49,31,49,48,48,30,48,50,31,69,82,82,79,82,32,32,32,32,32,32,32,30,48,51,31,83,69,82,86,73,67,69,30,48,52,31,49,30,48,53,31,30,48,54,31,49,50,51,52,53,30,48,55,31,65,70,68,46,49,66,30,48,56,31,56,30,3]
150110002ERROR       03SERVICE04105061234507AFD.1B088

If header 1 is 101 then the error is fixed

[1,49,53,2,48,49,31,49,48,49,30,48,50,31,78,79,32,69,82,82,79,82,32,32,32,32,30,48,51,31,83,69,82,86,73,67,69,30,48,52,31,49,30,48,53,31,30,48,54,31,49,50,51,52,53,30,48,55,31,65,70,68,46,49,66,30,48,56,31,57,30,3]
150110102NO ERROR    03SERVICE04105061234507AFD.1B089

I want to make the error message (header index 1 100) visible in the UI table,
and let it disappear (header index 1 101) when the fault is resolved.
I got that part working, but when parsing the string I'm stuck
Maybe someone can help me in the right direction

regards mark

This is not suited to buffer parser as I suspect data sizes are not fixed.

there is a protocol if you look closely at the data...

everything is key/val pairs with markers between them.

after STX (2) starts a KEY then US (unit separator 31) denotes end of KEY / start of VALUE
Following the VALUS is an RS (record separator 30) that marks the end of the VALUE.

This is a case where a function node is best suited...

//character markers to look for
const STX = 2;
const ETX = 3;
const RS = 31; //RS (record separator)
const US = 30; //US (unit separator)

//state machine modes
const MODE_INIT = 0;
const MODE_KEY = 1;
const MODE_VAL = 2;

//data to parse
const data = msg.payload;

//variables
var result = {};
var mode = MODE_INIT;
var key = [];
var val = [];

//helper function for converting KEY and VAL to strings
//and store in the result object
function store(k,v) {
    if (!k || !k.length) return;
    var skey = Buffer.from(k).toString().trim();
    var sval = Buffer.from(v).toString().trim();
    result[skey] = sval;
}

//loop the buffers data and extract the parts 
for(let i = 0; i < data.length; i++){
    const c = data[i];
    if(c === STX) {
        mode = MODE_KEY;
    } else if(c === RS) {
        mode = MODE_VAL;
    } else if(c === US || c === ETX) {
        store(key,val);
        key = [];
        val = []; 
        mode = MODE_KEY;
    } else {
        if (mode === MODE_KEY) key.push(c);
        if (mode === MODE_VAL) val.push(c);
    }
}

//put results into payload and return it to next node.
msg.payload = result;
return msg;
1 Like

Hi Steve,
thank you very much for the solution.
I would never have solved this myself :ok_hand:

regards mark