Library contents

R readBin and length

Read the bytes of a scanner record and check how many actually arrived.

A simple example

readBin and length

  1. Start with One available byte
  2. Do this Try to read a complete two-byte field
  3. Result One byte is missing
The read reached the end before the field was complete. Treating it as a full value would lose information.

Syntax

R syntax
length(record) < 4L
Run these examples in R

Save one example at a time as Lesson.R. Use R 4.x.

Rscript --vanilla Lesson.R

Read a stock count from a short record

A stock scanner sends each count as a four-byte integer. A transfer stops after two bytes, so the receiver must request the record again before posting the count to inventory.

From the programrecord <- readBin(packet, what = "raw", n = 4L)
ResultRequest the complete record
Lesson.R
packet <- as.raw(c(0, 5))
record <- readBin(packet, what = "raw", n = 4L)
if (length(record) < 4L) {
    cat("Request the complete record\n")
}
Output
Request the complete record

The two-byte transfer falls short of the four bytes required for a stock count.

Advertisements

Decode a complete gate count

A counter sends one four-byte record for the entrance. The device format requires a four-byte integer. Request another transmission if the input ends before all four bytes arrive.

Given00 00 00 09
Worked resultRecord complete

Detect a cut-off meter record

A sensor connection closes after the first two bytes of a four-byte record. The device format requires a four-byte integer. Request another transmission if the input ends before all four bytes arrive.

Given00 09
Worked resultRequest all four bytes

What to watch for

Requesting four bytes does not guarantee four are returned. Check the size before decoding.

Documentation for readBin and length