Skip to content

Commit

Permalink
Merge pull request #304 from IAmNickNack/wait-for-expected-bytes-from…
Browse files Browse the repository at this point in the history
…-socket-stream

Read expected payload size of GPIO packet
  • Loading branch information
eitch authored Oct 24, 2023
2 parents 449704d + c0a880b commit de5bfd9
Showing 1 changed file with 28 additions and 28 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -350,24 +350,12 @@ public String dataToString(){
* @throws IOException if an error occurs accessing {@code stream}.
*/
public static PiGpioPacket decode(InputStream stream) throws IOException {
return PiGpioPacket.decode(stream.readNBytes(stream.available()));
}
// read only header bytes
byte[] header = stream.readNBytes(16);

/**
* <p>decode.</p>
*
* @param data an array of {@link byte} objects.
* @return a {@link com.pi4j.library.pigpio.PiGpioPacket} object.
*/
public static PiGpioPacket decode(byte[] data) {
ByteBuffer rx = ByteBuffer.wrap(data);
ByteBuffer rx = ByteBuffer.wrap(header);
rx.order(ByteOrder.LITTLE_ENDIAN);

// check data length for minimum package size
if(data.length < 16){
throw new IllegalArgumentException("Insufficient number of data bytes bytes received; COUNT=" + data.length);
}

// parse packet parameters from raw received bytes
PiGpioCmd cmd = PiGpioCmd.from(rx.getInt()); // CMD <4 bytes :: 0-3>
int p1 = rx.getInt(); // P1 <4 bytes :: 4-7>
Expand All @@ -376,23 +364,37 @@ public static PiGpioPacket decode(byte[] data) {

// create new packet
PiGpioPacket packet = new PiGpioPacket(cmd, p1, p2)
.p3(p3); // set RAW P3 value

// apply any extra payload data (if available)
int remaining = rx.remaining();
.p3(p3); // set RAW P3 value

// bounds check remaining byte count
if(p3 < remaining) remaining = p3;
int remaining = bytesToRead(packet, stream);

//logger.info("HAS-REMAINING: " + remaining);
if(remaining > 0){
var temp = new byte[remaining];
rx.get(temp, 0, remaining);
if(remaining > 0) {
var temp = stream.readNBytes(remaining);
packet.data(temp);
}
return packet;
}

/**
* The packet may indicate the number of bytes to expect from the stream.
*
* E.g. I2C packets provide this value via {@link PiGpioPacket#p3}
*
* @param packet the packet being read
* @param stream incoming data
* @return the number of bytes to expect to read from the input stream
* @throws IOException
*/
static int bytesToRead(PiGpioPacket packet, InputStream stream) throws IOException {
switch (packet.cmd) {
case I2CRI:
case I2CRD:
return packet.p3;
default:
return stream.available();
}
}

/**
* <p>encode.</p>
*
Expand Down Expand Up @@ -427,6 +429,4 @@ public String toString(){
else
return String.format("CMD=%s(%d); P1=%d; P2=%d; P3=%d", cmd().name(), cmd().value(), p1(), p2(), p3());
}
}


}

0 comments on commit de5bfd9

Please sign in to comment.