can-log-tools/src/main/java/com/rusefi/can/CANPacket.java

64 lines
1.5 KiB
Java
Raw Normal View History

2022-02-02 16:48:51 -08:00
package com.rusefi.can;
2022-11-12 19:13:12 -08:00
import com.rusefi.util.BitMathUtil;
2022-02-14 21:45:27 -08:00
import static com.rusefi.can.Utils.bytesToHexWithSpaces;
2022-02-02 16:48:51 -08:00
public class CANPacket {
private final double timeStamp;
private final int id;
private final byte[] data;
public CANPacket(double timeStamp, int id, byte[] data) {
this.timeStamp = timeStamp;
this.id = id;
this.data = data;
}
2022-02-20 21:33:22 -08:00
/**
* @param index, starting from zero
*/
public int getTwoBytesByByteIndex(int index) {
return getByBitIndex(index * 8, 16);
}
public int getByBitIndex(int bitIndex, int bitWidth) {
int byteIndex = bitIndex / 8;
int shift = bitIndex - byteIndex * 8;
int value = getUnsigned(byteIndex);
if (shift + bitIndex > 8) {
value = value + getUnsigned(byteIndex + 1) * 256;
}
2022-11-12 19:13:12 -08:00
return value >> shift & BitMathUtil.mask(bitWidth);
2022-02-02 21:03:56 -08:00
}
2022-02-02 16:48:51 -08:00
public double getTimeStamp() {
return timeStamp;
}
public int getId() {
return id;
}
public byte[] getData() {
return data;
}
2022-02-02 21:03:56 -08:00
public int getUnsigned(int i) {
return Byte.toUnsignedInt(data[i]);
}
2022-02-14 21:45:27 -08:00
public void assertThat(String msg, PackerAssertion assertion) {
if (!assertion.test(this))
throw new IllegalStateException("Not " + msg + " " + bytesToHexWithSpaces(data));
}
public int getUnsignedInt(int index) {
return Byte.toUnsignedInt(data[index]);
}
public interface PackerAssertion {
boolean test(CANPacket packet);
}
2022-02-02 16:48:51 -08:00
}