Steve-Mcl / node-red-contrib-buffer-parser

A node-red node to convert values in a buffer, integer array or hex string into many different data type(s). Supports Big/Little Endian, BCD, byte swapping and much more.
MIT License
24 stars 8 forks source link

[Q] Understanding Length #8

Closed Sineos closed 3 years ago

Sineos commented 3 years ago

First many thanks for this nifty node. Really useful.

I'm reading a FloatBE buffer: grafik

A simple

const buf = Buffer.from(msg.payload.buffer);
const value = buf.readFloatBE();
const BufLength = buf.length

Gives the expected value and the expected length of 4.

Now using your node, when I put a Length of 4, I will get an error:

RangeError [ERR_OUT_OF_RANGE]: The value of "offset" is out of range. It must be >= 0 and <= 0. Received 4

A Length of -1 or 1 will work correctly.

Any insight on the Length parameter would be appreciated.

Steve-Mcl commented 3 years ago

Any insight on the Length parameter would be appreciated.

The built-in help says...

image

... so setting length to 4 will be asking for 4 floats from the buffer - that will require an input buffer of 4x4 bytes (12 bytes)

How to remember this :- the buffer parser already knows how many bytes are needed for a float (its 4) but it doesn't know how many floats you want (so that's the item length parameter)

Does that help?

Sineos commented 3 years ago

Many thanks for your quick respone. It is fully clear now. Am I correct that I could use Offset on a 4x4 buffer to split it into 4 individual values?

Steve-Mcl commented 3 years ago

Am I correct that I could use Offset on a 4x4 buffer to split it into 4 individual values?

You dont NEED to use offset - you can request length 4 (and it will get the 4 floats from byte 0, 4, 8, and 12) in an array.

However, it is usually more sense to name your requests and only convert the bytes you are interested in - so you can enter 4 rows in the UI with offsets 0, 4, 8, 12 (or any offset from the start of the input buffer you need).


Where this comes in useful...

Scenario - you need to get modbus registers 1, 2, 5, 10, 20 and 30

you could do 6 separate reads (but: this will be very slow, difficult to orchestrate, and the values will be inconsistent since they would be read at separate times)

Ideally, you would request 30 registers from modbus then use the offset to select those items from the buffer. So, since modbus values are ALWAYS 16 bit register 1 would be at byte 0, register 2 would be at byte 2, register 10 would be at byte 20.

e.g...

image

Sineos commented 3 years ago

The Modbus thing was exactly my intended scenario. Many thanks for your additional input. Makes this node even more valuable. 👍