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;
|
|
|
|
}
|
|
|
|
|
2023-07-30 21:01:10 -07:00
|
|
|
public StringBuilder asLua(String arrayName) {
|
|
|
|
StringBuilder result = new StringBuilder();
|
|
|
|
result.append(arrayName + " = {");
|
|
|
|
|
|
|
|
byte[] data = getData();
|
|
|
|
System.out.println(String.format("Got ECU 0x%x", getId()) + " " + data.length);
|
|
|
|
|
|
|
|
for (int index = 0; index < data.length; index++) {
|
|
|
|
if (index > 0)
|
|
|
|
result.append(", ");
|
|
|
|
|
|
|
|
result.append(String.format("0x%02x", data[index]));
|
|
|
|
|
|
|
|
}
|
|
|
|
result.append("}\n");
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
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
|
|
|
}
|