can-log-tools/playback/src/main/java/com/rusefi/io/can/PCanHelper.java

62 lines
2.0 KiB
Java
Raw Normal View History

2024-01-03 13:59:54 -08:00
package com.rusefi.io.can;
import peak.can.basic.*;
import static peak.can.basic.TPCANMessageType.PCAN_MESSAGE_STANDARD;
public class PCanHelper {
public static final TPCANHandle CHANNEL = TPCANHandle.PCAN_USBBUS1;
// @NotNull
2024-01-05 21:29:29 -08:00
public static PCANBasic createPCAN() {
2024-01-03 13:59:54 -08:00
PCANBasic can = new PCANBasic();
can.initializeAPI();
return can;
}
public static TPCANStatus init(PCANBasic can) {
return can.Initialize(CHANNEL, TPCANBaudrate.PCAN_BAUD_500K, TPCANType.PCAN_TYPE_NONE, 0, (short) 0);
}
public static TPCANStatus send(PCANBasic can, int id, byte[] payLoad) {
//log.info(String.format("Sending id=%x %s", id, HexBinary.printByteArray(payLoad)));
TPCANMsg msg = new TPCANMsg(id, PCAN_MESSAGE_STANDARD.getValue(),
(byte) payLoad.length, payLoad);
return can.Write(CHANNEL, msg);
}
public static PCANBasic createAndInit() {
2024-01-05 21:29:29 -08:00
PCANBasic pcan = createPCAN();
2024-01-03 13:59:54 -08:00
TPCANStatus initStatus = init(pcan);
if (initStatus != TPCANStatus.PCAN_ERROR_OK) {
2024-01-12 19:30:23 -08:00
System.out.println("createAndInit: *** ERROR *** TPCANStatus " + initStatus);
2024-01-03 13:59:54 -08:00
System.exit(-1);
}
return pcan;
}
2024-01-05 21:29:29 -08:00
public static CanSender create() {
PCANBasic pcan = createAndInit();
2024-01-12 19:30:23 -08:00
return (id, payload) -> {
TPCANStatus status = send(pcan, id, payload);
if (status == TPCANStatus.PCAN_ERROR_XMTFULL || status == TPCANStatus.PCAN_ERROR_QXMTFULL) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
// System.out.println(String.format("Let's retry ID=%x", packet.getId()) + " OK=" + okCounter);
status = send(pcan, id, payload);
2024-01-05 21:29:29 -08:00
}
2024-01-12 19:30:23 -08:00
boolean isHappy = status == TPCANStatus.PCAN_ERROR_OK;
if (!isHappy) {
System.out.println("Error sending " + status);
}
return isHappy;
2024-01-05 21:29:29 -08:00
};
}
2024-01-03 13:59:54 -08:00
}