java logging migration

This commit is contained in:
rusefi 2020-07-24 12:44:29 -04:00
parent 09a9ecf90e
commit 862505f40e
56 changed files with 363 additions and 369 deletions

View File

@ -7,7 +7,6 @@ import com.hoho.android.usbserial.driver.ProbeTable;
import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialPort;
import com.hoho.android.usbserial.driver.UsbSerialProber;
import com.opensr5.Logger;
import com.opensr5.io.DataListener;
import com.rusefi.binaryprotocol.IncomingDataBuffer;
import com.rusefi.dfu.DfuLogic;
@ -32,9 +31,9 @@ public class AndroidSerial extends AbstractIoStream {
return prober.findAllDrivers(usbManager);
}
public AndroidSerial(UsbSerialPort usbSerialPort, Logger logger) {
public AndroidSerial(UsbSerialPort usbSerialPort) {
this.usbSerialPort = usbSerialPort;
dataBuffer = IncomingDataBuffer.createDataBuffer("", this, logger);
dataBuffer = IncomingDataBuffer.createDataBuffer("", this);
}
@Override
@ -50,7 +49,7 @@ public class AndroidSerial extends AbstractIoStream {
@Override
public void setInputListener(DataListener listener) {
ByteReader reader = buffer -> usbSerialPort.read(buffer, 5000);
ByteReader.runReaderLoop("", listener, reader, Logger.CONSOLE, TcpIoStream.DisconnectListener.VOID);
ByteReader.runReaderLoop("", listener, reader, TcpIoStream.DisconnectListener.VOID);
}
@Override

View File

@ -34,7 +34,6 @@ import android.widget.TextView;
import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialPort;
import com.opensr5.Logger;
import com.rusefi.Listener;
import com.rusefi.dfu.DfuConnection;
import com.rusefi.dfu.DfuImage;
@ -233,9 +232,9 @@ public class rusEFI extends Activity {
port.open(connection);
port.setParameters(115200, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
AndroidSerial serial = new AndroidSerial(port, Logger.CONSOLE);
AndroidSerial serial = new AndroidSerial(port);
mResultView.append("Switching to DFU\n");
DfuHelper.sendDfuRebootCommand(serial, new StringBuilder(), Logger.CONSOLE);
DfuHelper.sendDfuRebootCommand(serial, new StringBuilder());
} catch (IOException e) {
throw new IllegalStateException(e);

View File

@ -555,7 +555,7 @@ public class AutoTest {
boolean failed = false;
try {
LinkManager linkManager = new LinkManager(FileLog.LOGGER);
LinkManager linkManager = new LinkManager();
IoUtil.connectToSimulator(linkManager, startSimulator);
new AutoTest(linkManager, linkManager.getCommandQueue()).mainTestBody();
} catch (Throwable e) {

View File

@ -12,7 +12,7 @@ public class EnduranceTest {
private static final int DEFAULT_COUNT = 2000;
public static void main(String[] args) {
LinkManager linkManager = new LinkManager(FileLog.LOGGER);
LinkManager linkManager = new LinkManager();
CommandQueue commandQueue = linkManager.getCommandQueue();
long start = System.currentTimeMillis();
int count = parseCount(args);

View File

@ -1,6 +1,5 @@
package com.rusefi;
import com.rusefi.io.CommandQueue;
import com.rusefi.io.LinkManager;
import org.jetbrains.annotations.NotNull;
@ -83,7 +82,7 @@ public class RealHwTest {
}
private static void runRealHardwareTest(String port) throws Exception {
LinkManager linkManager = new LinkManager(FileLog.LOGGER);
LinkManager linkManager = new LinkManager();
IoUtil.realHardwareConnect(linkManager, port);
new AutoTest(linkManager, linkManager.getCommandQueue()).mainTestBody();
}

View File

@ -1,6 +1,8 @@
package com.rusefi;
import com.devexperts.logging.Logging;
import com.opensr5.Logger;
import com.rusefi.core.MessagesCentral;
import com.rusefi.io.IoStream;
import com.rusefi.io.commands.HelloCommand;
import com.rusefi.io.tcp.BinaryProtocolProxy;
@ -13,13 +15,14 @@ import com.rusefi.tools.online.ProxyClient;
import java.io.IOException;
import static com.devexperts.logging.Logging.getLogging;
public class LocalApplicationProxy {
private static final Logging log = getLogging(LocalApplicationProxy.class);
public static final int SERVER_PORT_FOR_APPLICATIONS = 8002;
private final Logger logger;
private final ApplicationRequest applicationRequest;
public LocalApplicationProxy(Logger logger, ApplicationRequest applicationRequest) {
this.logger = logger;
public LocalApplicationProxy(ApplicationRequest applicationRequest) {
this.applicationRequest = applicationRequest;
}
@ -30,23 +33,23 @@ public class LocalApplicationProxy {
* @param jsonHttpPort
* @param disconnectListener
*/
public static ServerHolder startAndRun(Logger logger, int serverPortForRemoteUsers, ApplicationRequest applicationRequest, int localApplicationPort, int jsonHttpPort, TcpIoStream.DisconnectListener disconnectListener) throws IOException {
String version = HttpUtil.executeGet(logger,ProxyClient.getHttpAddress(jsonHttpPort) + ProxyClient.VERSION_PATH);
logger.info("Server says version=" + version);
public static ServerHolder startAndRun(int serverPortForRemoteUsers, ApplicationRequest applicationRequest, int localApplicationPort, int jsonHttpPort, TcpIoStream.DisconnectListener disconnectListener) throws IOException {
String version = HttpUtil.executeGet(ProxyClient.getHttpAddress(jsonHttpPort) + ProxyClient.VERSION_PATH);
log.info("Server says version=" + version);
if (!version.contains(ProxyClient.BACKEND_VERSION))
throw new IOException("Unexpected backend version " + version + " while we want " + ProxyClient.BACKEND_VERSION);
IoStream authenticatorToProxyStream = new TcpIoStream("authenticatorToProxyStream ", logger, rusEFISSLContext.getSSLSocket(HttpUtil.RUSEFI_PROXY_HOSTNAME, serverPortForRemoteUsers), disconnectListener);
LocalApplicationProxy localApplicationProxy = new LocalApplicationProxy(logger, applicationRequest);
logger.info("Pushing " + applicationRequest);
IoStream authenticatorToProxyStream = new TcpIoStream("authenticatorToProxyStream ", rusEFISSLContext.getSSLSocket(HttpUtil.RUSEFI_PROXY_HOSTNAME, serverPortForRemoteUsers), disconnectListener);
LocalApplicationProxy localApplicationProxy = new LocalApplicationProxy(applicationRequest);
log.info("Pushing " + applicationRequest);
localApplicationProxy.run(authenticatorToProxyStream);
return BinaryProtocolProxy.createProxy(logger, authenticatorToProxyStream, localApplicationPort);
return BinaryProtocolProxy.createProxy(authenticatorToProxyStream, localApplicationPort);
}
public void run(IoStream authenticatorToProxyStream) throws IOException {
// right from connection push session authentication data
new HelloCommand(logger, applicationRequest.toJson()).handle(authenticatorToProxyStream);
new HelloCommand(applicationRequest.toJson()).handle(authenticatorToProxyStream);
}
public static void start(String[] strings) {

View File

@ -1,5 +1,6 @@
package com.rusefi.binaryprotocol;
import com.devexperts.logging.Logging;
import com.opensr5.ConfigurationImage;
import com.opensr5.Logger;
import com.opensr5.io.ConfigurationImageFile;
@ -12,6 +13,7 @@ import com.rusefi.config.generated.Fields;
import com.rusefi.core.*;
import com.rusefi.io.*;
import com.rusefi.io.commands.GetOutputsCommand;
import com.rusefi.io.serial.PortHolder;
import com.rusefi.stream.LogicdataStreamFile;
import com.rusefi.stream.StreamFile;
import com.rusefi.stream.TSHighSpeedLog;
@ -33,6 +35,7 @@ import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static com.devexperts.logging.Logging.getLogging;
import static com.rusefi.binaryprotocol.IoHelper.*;
/**
@ -45,6 +48,7 @@ import static com.rusefi.binaryprotocol.IoHelper.*;
* 3/6/2015
*/
public class BinaryProtocol implements BinaryProtocolCommands {
private static final Logging log = getLogging(BinaryProtocol.class);
private static final String USE_PLAIN_PROTOCOL_PROPERTY = "protocol.plain";
private static final String CONFIGURATION_RUSEFI_BINARY = "current_configuration.rusefi_binary";
@ -57,7 +61,6 @@ public class BinaryProtocol implements BinaryProtocolCommands {
public static boolean PLAIN_PROTOCOL = Boolean.getBoolean(USE_PLAIN_PROTOCOL_PROPERTY);
private final LinkManager linkManager;
private final Logger logger;
private final IoStream stream;
private final IncomingDataBuffer incomingData;
private boolean isBurnPending;
@ -130,15 +133,14 @@ public class BinaryProtocol implements BinaryProtocolCommands {
private final Thread hook = new Thread(() -> closeComposites(), "BinaryProtocol::hook");
public BinaryProtocol(LinkManager linkManager, final Logger logger, IoStream stream, IncomingDataBuffer dataBuffer) {
public BinaryProtocol(LinkManager linkManager, IoStream stream, IncomingDataBuffer dataBuffer) {
this.linkManager = linkManager;
this.logger = logger;
this.stream = stream;
communicationLoggingListener = new CommunicationLoggingListener() {
@Override
public void onPortHolderMessage(Class clazz, String message) {
MessagesCentral.getInstance().postMessage(logger, clazz, message);
MessagesCentral.getInstance().postMessage(clazz, message);
}
};
@ -150,7 +152,7 @@ public class BinaryProtocol implements BinaryProtocolCommands {
needCompositeLogger = linkManager.getCompositeLogicEnabled();
lastLowRpmTime = System.currentTimeMillis();
} else if (System.currentTimeMillis() - lastLowRpmTime > HIGH_RPM_DELAY * Timeouts.SECOND) {
logger.info("Time to turn off composite logging");
log.info("Time to turn off composite logging");
needCompositeLogger = false;
}
};
@ -175,7 +177,7 @@ public class BinaryProtocol implements BinaryProtocolCommands {
}
public void doSend(final String command, boolean fireEvent) throws InterruptedException {
logger.info("Sending [" + command + "]");
log.info("Sending [" + command + "]");
if (fireEvent && LinkManager.LOG_LEVEL.isDebugEnabled()) {
communicationLoggingListener.onPortHolderMessage(BinaryProtocol.class, "Sending [" + command + "]");
}
@ -197,7 +199,7 @@ public class BinaryProtocol implements BinaryProtocolCommands {
} catch (ExecutionException e) {
throw new IllegalStateException(e);
} catch (TimeoutException e) {
getLogger().error("timeout sending [" + command + "] giving up: " + e);
log.error("timeout sending [" + command + "] giving up: " + e);
return;
}
/**
@ -247,7 +249,7 @@ public class BinaryProtocol implements BinaryProtocolCommands {
}
sleep(Timeouts.TEXT_PULL_PERIOD);
}
logger.info("Stopping text pull");
log.info("Stopping text pull");
}
};
Thread tr = new Thread(textPull);
@ -275,10 +277,6 @@ public class BinaryProtocol implements BinaryProtocolCommands {
compositeLogs.clear();
}
public Logger getLogger() {
return logger;
}
private void dropPending() {
synchronized (ioLock) {
if (isClosed)
@ -315,7 +313,7 @@ public class BinaryProtocol implements BinaryProtocolCommands {
private byte[] receivePacket(String msg, boolean allowLongResponse) throws EOFException {
long start = System.currentTimeMillis();
synchronized (ioLock) {
return incomingData.getPacket(logger, msg, allowLongResponse, start);
return incomingData.getPacket(msg, allowLongResponse, start);
}
}
@ -331,7 +329,7 @@ public class BinaryProtocol implements BinaryProtocolCommands {
return;
}
setController(image);
logger.info("Got configuration from controller.");
log.info("Got configuration from controller.");
ConnectionStatusLogic.INSTANCE.setValue(ConnectionStatusValue.CONNECTED);
}
@ -343,7 +341,7 @@ public class BinaryProtocol implements BinaryProtocolCommands {
int offset = 0;
long start = System.currentTimeMillis();
logger.info("Reading from controller...");
log.info("Reading from controller...");
while (offset < image.getSize() && (System.currentTimeMillis() - start < Timeouts.READ_IMAGE_TIMEOUT)) {
if (isClosed)
@ -363,7 +361,7 @@ public class BinaryProtocol implements BinaryProtocolCommands {
if (!checkResponseCode(response, RESPONSE_OK) || response.length != requestSize + 1) {
String code = (response == null || response.length == 0) ? "empty" : "code " + response[0];
String info = response == null ? "NO RESPONSE" : (code + " size " + response.length);
logger.info("readImage: ERROR UNEXPECTED Something is wrong, retrying... " + info);
log.info("readImage: ERROR UNEXPECTED Something is wrong, retrying... " + info);
continue;
}
@ -435,7 +433,7 @@ public class BinaryProtocol implements BinaryProtocolCommands {
sendPacket(packet);
return receivePacket(msg, allowLongResponse);
} catch (IOException e) {
logger.error(msg + ": executeCommand failed: " + e);
log.error(msg + ": executeCommand failed: " + e);
close();
return null;
}
@ -509,7 +507,7 @@ public class BinaryProtocol implements BinaryProtocolCommands {
}
private void sendPacket(byte[] command) throws IOException {
stream.sendPacket(command, logger);
stream.sendPacket(command);
}
@ -549,7 +547,7 @@ public class BinaryProtocol implements BinaryProtocolCommands {
Thread.sleep(100);
return new String(response, 1, response.length - 1);
} catch (InterruptedException e) {
logger.error(e.toString());
log.error(e.toString());
return null;
}
}

View File

@ -1,6 +1,6 @@
package com.rusefi.binaryprotocol;
import com.opensr5.Logger;
import com.devexperts.logging.Logging;
import com.rusefi.Timeouts;
import com.rusefi.config.generated.Fields;
import com.rusefi.io.IoStream;
@ -13,6 +13,7 @@ import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;
import static com.devexperts.logging.Logging.getLogging;
import static com.rusefi.binaryprotocol.IoHelper.*;
/**
@ -23,39 +24,40 @@ import static com.rusefi.binaryprotocol.IoHelper.*;
*/
@ThreadSafe
public class IncomingDataBuffer {
private static final Logging log = getLogging(IoStream.class);
private static final int BUFFER_SIZE = 32768;
private static String loggingPrefix;
/**
* buffer for response bytes from controller
*/
private final CircularByteBuffer cbb;
private final Logger logger;
private final AbstractIoStream.StreamStats streamStats;
public IncomingDataBuffer(Logger logger, AbstractIoStream.StreamStats streamStats) {
public IncomingDataBuffer(AbstractIoStream.StreamStats streamStats) {
this.streamStats = Objects.requireNonNull(streamStats, "streamStats");
this.cbb = new CircularByteBuffer(BUFFER_SIZE);
this.logger = logger;
}
public static IncomingDataBuffer createDataBuffer(String loggingPrefix, IoStream stream, Logger logger) {
public static IncomingDataBuffer createDataBuffer(String loggingPrefix, IoStream stream) {
IncomingDataBuffer.loggingPrefix = loggingPrefix;
IncomingDataBuffer incomingData = new IncomingDataBuffer(logger, stream.getStreamStats());
IncomingDataBuffer incomingData = new IncomingDataBuffer(stream.getStreamStats());
stream.setInputListener(incomingData::addData);
return incomingData;
}
public byte[] getPacket(Logger logger, String msg, boolean allowLongResponse) throws EOFException {
return getPacket(logger, msg, allowLongResponse, System.currentTimeMillis());
public byte[] getPacket(String msg, boolean allowLongResponse) throws EOFException {
return getPacket(msg, allowLongResponse, System.currentTimeMillis());
}
public byte[] getPacket(Logger logger, String msg, boolean allowLongResponse, long start) throws EOFException {
public byte[] getPacket(String msg, boolean allowLongResponse, long start) throws EOFException {
boolean isTimeout = waitForBytes(msg + " header", start, 2);
if (isTimeout)
return null;
int packetSize = swap16(getShort());
logger.trace( loggingPrefix + "Got packet size " + packetSize);
if (log.debugEnabled())
log.debug(loggingPrefix + "Got packet size " + packetSize);
if (packetSize < 0)
return null;
if (!allowLongResponse && packetSize > Math.max(BinaryProtocolCommands.BLOCKING_FACTOR, Fields.TS_OUTPUT_SIZE) + 10)
@ -72,20 +74,22 @@ public class IncomingDataBuffer {
boolean isCrcOk = actualCrc == packetCrc;
if (!isCrcOk) {
logger.trace(String.format("%x", actualCrc) + " vs " + String.format("%x", packetCrc));
if (log.debugEnabled())
log.debug(String.format("%x", actualCrc) + " vs " + String.format("%x", packetCrc));
return null;
}
streamStats.onPacketArrived();
logger.trace("packet " + Arrays.toString(packet) + ": crc OK");
if (log.debugEnabled())
log.debug("packet " + Arrays.toString(packet) + ": crc OK");
return packet;
}
public void addData(byte[] freshData) {
logger.info("IncomingDataBuffer: " + freshData.length + " byte(s) arrived");
log.info("IncomingDataBuffer: " + freshData.length + " byte(s) arrived");
synchronized (cbb) {
if (cbb.size() - cbb.length() < freshData.length) {
logger.error("IncomingDataBuffer: buffer overflow not expected");
log.error("IncomingDataBuffer: buffer overflow not expected");
cbb.clear();
}
cbb.put(freshData);
@ -103,12 +107,12 @@ public class IncomingDataBuffer {
}
public boolean waitForBytes(int timeoutMs, String loggingMessage, long startTimestamp, int count) {
logger.info(loggingMessage + ": waiting for " + count + " byte(s)");
log.info(loggingMessage + ": waiting for " + count + " byte(s)");
synchronized (cbb) {
while (cbb.length() < count) {
int timeout = (int) (startTimestamp + timeoutMs - System.currentTimeMillis());
if (timeout <= 0) {
logger.info(loggingMessage + ": timeout. Got only " + cbb.length());
log.info(loggingMessage + ": timeout. Got only " + cbb.length());
return true; // timeout. Sad face.
}
try {
@ -126,10 +130,10 @@ public class IncomingDataBuffer {
synchronized (cbb) {
int pending = cbb.length();
if (pending > 0) {
logger.error("dropPending: Unexpected pending data: " + pending + " byte(s)");
log.error("dropPending: Unexpected pending data: " + pending + " byte(s)");
byte[] bytes = new byte[pending];
cbb.get(bytes);
logger.error("data: " + Arrays.toString(bytes));
log.error("data: " + Arrays.toString(bytes));
}
}
}
@ -163,7 +167,7 @@ public class IncomingDataBuffer {
}
public byte readByte(int timeoutMs) throws IOException {
boolean isTimeout = waitForBytes(timeoutMs,loggingPrefix + "readByte", System.currentTimeMillis(), 1);
boolean isTimeout = waitForBytes(timeoutMs, loggingPrefix + "readByte", System.currentTimeMillis(), 1);
if (isTimeout)
throw new IOException("Timeout in readByte");
return (byte) getByte();

View File

@ -1,6 +1,5 @@
package com.rusefi.file;
import com.opensr5.Logger;
import com.rusefi.core.EngineState;
import com.rusefi.io.LinkManager;
@ -12,8 +11,8 @@ import java.util.List;
* Andrey Belomutskiy, (c) 2013-2020
*/
public class FileUtils {
public static void readFile(String filename, EngineState.EngineStateListener listener, Logger logger) {
readFile2(filename, new EngineState(listener, logger));
public static void readFile(String filename, EngineState.EngineStateListener listener) {
readFile2(filename, new EngineState(listener));
}
public static void readFile2(String filename, EngineState engineState) {

View File

@ -1,8 +1,10 @@
package com.rusefi.io;
import com.devexperts.logging.Logging;
import com.opensr5.Logger;
import com.opensr5.io.DataListener;
import com.rusefi.config.generated.Fields;
import com.rusefi.io.tcp.BinaryProtocolServer;
import com.rusefi.io.tcp.TcpIoStream;
import java.io.IOException;
@ -10,8 +12,12 @@ import java.util.Arrays;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import static com.devexperts.logging.Logging.getLogging;
public interface ByteReader {
static void runReaderLoop(String loggingPrefix, DataListener listener, ByteReader reader, Logger logger, TcpIoStream.DisconnectListener disconnectListener) {
Logging log = getLogging(ByteReader.class);
static void runReaderLoop(String loggingPrefix, DataListener listener, ByteReader reader, TcpIoStream.DisconnectListener disconnectListener) {
/**
* Threading of the whole input/output does not look healthy at all!
*
@ -25,7 +31,7 @@ public interface ByteReader {
threadExecutor.execute(() -> {
Thread.currentThread().setName("TCP connector loop");
logger.info(loggingPrefix + "Running TCP connection loop");
log.info(loggingPrefix + "Running TCP connection loop");
byte inputBuffer[] = new byte[Fields.BLOCKING_FACTOR * 2];
while (true) {
@ -35,7 +41,7 @@ public interface ByteReader {
throw new IOException("TcpIoStream: End of input?");
listener.onDataArrived(Arrays.copyOf(inputBuffer, result));
} catch (IOException e) {
logger.error("TcpIoStream: End of connection " + e);
log.error("TcpIoStream: End of connection " + e);
disconnectListener.onDisconnect();
return;
}

View File

@ -1,6 +1,6 @@
package com.rusefi.io;
import com.opensr5.Logger;
import com.devexperts.logging.Logging;
import com.rusefi.config.generated.Fields;
import com.rusefi.core.MessagesCentral;
import org.jetbrains.annotations.NotNull;
@ -9,6 +9,8 @@ import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import static com.devexperts.logging.Logging.getLogging;
/**
* This singleton keeps re-sending commands till a proper confirmation is received
*
@ -18,6 +20,7 @@ import java.util.concurrent.LinkedBlockingQueue;
*/
@SuppressWarnings("FieldCanBeLocal")
public class CommandQueue {
private static final Logging log = getLogging(LinkManager.class);
public static final String CONFIRMATION_PREFIX = "confirmation_";
public static final int DEFAULT_TIMEOUT = 500;
private static final int COMMAND_CONFIRMATION_TIMEOUT = 1000;
@ -36,7 +39,6 @@ public class CommandQueue {
private final List<CommandQueueListener> commandListeners = new ArrayList<>();
private final Runnable runnable;
private final Logger logger;
private static boolean isSlowCommand(String cmd) {
String lc = cmd.toLowerCase();
@ -98,27 +100,26 @@ public class CommandQueue {
}
if (counter != 1)
MessagesCentral.getInstance().postMessage(logger, CommandQueue.class, "Took " + counter + " attempts");
MessagesCentral.getInstance().postMessage(CommandQueue.class, "Took " + counter + " attempts");
}
public CommandQueue(LinkManager linkManager, Logger logger) {
public CommandQueue(LinkManager linkManager) {
this.linkManager = linkManager;
runnable = new Runnable() {
@SuppressWarnings("InfiniteLoopStatement")
@Override
public void run() {
MessagesCentral.getInstance().postMessage(logger, COMMAND_QUEUE_CLASS, "SerialIO started");
MessagesCentral.getInstance().postMessage(COMMAND_QUEUE_CLASS, "SerialIO started");
while (true) {
try {
sendPendingCommand();
} catch (Throwable e) {
logger.error("CommandQueue error" + e);
log.error("CommandQueue error" + e);
System.exit(-2);
}
}
}
};
this.logger = logger;
Thread thread = new Thread(runnable, "Commands Queue");
thread.setDaemon(true);
thread.start();
@ -136,10 +137,10 @@ public class CommandQueue {
MessagesCentral mc = MessagesCentral.getInstance();
String confirmation = LinkManager.unpackConfirmation(message);
if (confirmation == null)
mc.postMessage(logger, CommandQueue.class, "Broken confirmation length: " + message);
mc.postMessage(CommandQueue.class, "Broken confirmation length: " + message);
pendingConfirmations.add(confirmation);
if (LinkManager.LOG_LEVEL.isDebugEnabled())
mc.postMessage(logger, CommandQueue.class, "got valid conf! " + confirmation + ", still pending: " + pendingCommands.size());
mc.postMessage(CommandQueue.class, "got valid conf! " + confirmation + ", still pending: " + pendingCommands.size());
// FileLog.MAIN.logLine("templog got valid conf " + confirmation + " " + System.currentTimeMillis() + " " + new Date());

View File

@ -1,16 +1,15 @@
package com.rusefi.io;
import com.opensr5.Logger;
import com.rusefi.binaryprotocol.BinaryProtocol;
import com.rusefi.config.generated.Fields;
import java.io.IOException;
public class DfuHelper {
public static void sendDfuRebootCommand(IoStream stream, StringBuilder messages, Logger logger) {
public static void sendDfuRebootCommand(IoStream stream, StringBuilder messages) {
byte[] command = BinaryProtocol.getTextCommandBytes(Fields.CMD_REBOOT_DFU);
try {
stream.sendPacket(command, logger);
stream.sendPacket(command);
stream.close();
messages.append("Reboot command sent!\n");
} catch (IOException e) {

View File

@ -1,5 +1,6 @@
package com.rusefi.io;
import com.devexperts.logging.Logging;
import com.opensr5.Logger;
import com.opensr5.io.DataListener;
import com.opensr5.io.WriteStream;
@ -13,6 +14,8 @@ import org.jetbrains.annotations.NotNull;
import java.io.EOFException;
import java.io.IOException;
import static com.devexperts.logging.Logging.getLogging;
/**
* Physical bi-directional controller communication level
* <p>
@ -21,6 +24,7 @@ import java.io.IOException;
* 5/11/2015.
*/
public interface IoStream extends WriteStream {
Logging log = getLogging(IoStream.class);
static String printHexBinary(byte[] data) {
char[] hexCode = "0123456789ABCDEF".toCharArray();
@ -47,7 +51,7 @@ public interface IoStream extends WriteStream {
flush();
}
default void sendPacket(byte[] plainPacket, Logger logger) throws IOException {
default void sendPacket(byte[] plainPacket) throws IOException {
byte[] packet;
if (BinaryProtocol.PLAIN_PROTOCOL) {
packet = plainPacket;
@ -55,7 +59,7 @@ public interface IoStream extends WriteStream {
packet = IoHelper.makeCrc32Packet(plainPacket);
}
// todo: verbose mode printHexBinary(plainPacket))
logger.info(getLoggingPrefix() + "Sending packet " + BinaryProtocol.findCommand(plainPacket[0]) + " length=" + plainPacket.length);
log.debug(getLoggingPrefix() + "Sending packet " + BinaryProtocol.findCommand(plainPacket[0]) + " length=" + plainPacket.length);
write(packet);
flush();
}

View File

@ -1,7 +1,7 @@
package com.rusefi.io;
import com.devexperts.logging.Logging;
import com.fazecast.jSerialComm.SerialPort;
import com.opensr5.Logger;
import com.rusefi.Callable;
import com.rusefi.NamedThreadFactory;
import com.rusefi.binaryprotocol.BinaryProtocol;
@ -19,6 +19,8 @@ import java.util.Arrays;
import java.util.Objects;
import java.util.concurrent.*;
import static com.devexperts.logging.Logging.getLogging;
/**
* See TcpCommunicationIntegrationTest
*
@ -26,6 +28,8 @@ import java.util.concurrent.*;
* 3/3/14
*/
public class LinkManager implements Closeable {
private static final Logging log = getLogging(LinkManager.class);
@NotNull
public static LogLevel LOG_LEVEL = LogLevel.INFO;
@ -38,23 +42,21 @@ public class LinkManager implements Closeable {
public static final String LOG_VIEWER = "log viewer";
private final CommandQueue commandQueue;
private final Logger logger;
private LinkConnector connector;
private boolean isStarted;
private boolean compositeLogicEnabled = true;
private boolean needPullData = true;
public LinkManager(Logger logger) {
this.logger = logger;
public LinkManager() {
engineState = new EngineState(new EngineState.EngineStateListenerImpl() {
@Override
public void beforeLine(String fullLine) {
logger.info(fullLine);
log.info(fullLine);
HeartBeatListeners.onDataArrived();
}
}, logger);
commandQueue = new CommandQueue(this, logger);
});
commandQueue = new CommandQueue(this);
}
@NotNull
@ -196,7 +198,7 @@ public class LinkManager implements Closeable {
public void start(String port, ConnectionStateListener stateListener) {
Objects.requireNonNull(port, "port");
logger.info("LinkManager: Starting " + port);
log.info("LinkManager: Starting " + port);
if (isLogViewerMode(port)) {
setConnector(LinkConnector.VOID);
} else if (TcpConnector.isTcpPort(port)) {
@ -208,7 +210,7 @@ public class LinkManager implements Closeable {
int portPart = TcpConnector.getTcpPort(port);
String hostname = TcpConnector.getHostname(port);
socket = new Socket(hostname, portPart);
TcpIoStream tcpIoStream = new TcpIoStream("[start] ", logger, socket);
TcpIoStream tcpIoStream = new TcpIoStream("[start] ", socket);
return tcpIoStream;
} catch (Throwable e) {
@ -218,13 +220,13 @@ public class LinkManager implements Closeable {
}
};
setConnector(new StreamConnector(this, port, logger, streamFactory));
setConnector(new StreamConnector(this, port, streamFactory));
isSimulationMode = true;
} else {
Callable<IoStream> ioStreamCallable = new Callable<IoStream>() {
@Override
public IoStream call() {
IoStream stream = ((Callable<IoStream>) () -> SerialIoStreamJSerialComm.openPort(port, logger)).call();
IoStream stream = ((Callable<IoStream>) () -> SerialIoStreamJSerialComm.openPort(port)).call();
if (stream == null) {
// error already reported
return null;
@ -232,7 +234,7 @@ public class LinkManager implements Closeable {
return stream;
}
};
setConnector(new StreamConnector(this, port, logger, ioStreamCallable));
setConnector(new StreamConnector(this, port, ioStreamCallable));
}
}

View File

@ -1,6 +1,5 @@
package com.rusefi.io.commands;
import com.opensr5.Logger;
import com.rusefi.binaryprotocol.BinaryProtocolCommands;
import com.rusefi.binaryprotocol.IncomingDataBuffer;
import com.rusefi.config.generated.Fields;
@ -14,21 +13,19 @@ import java.io.IOException;
import static com.rusefi.binaryprotocol.IoHelper.checkResponseCode;
public class HelloCommand implements Command {
private final Logger logger;
private final String tsSignature;
public HelloCommand(Logger logger, String tsSignature) {
this.logger = logger;
public HelloCommand(String tsSignature) {
this.tsSignature = tsSignature;
}
public static void send(IoStream stream, Logger logger) throws IOException {
stream.sendPacket(new byte[]{Fields.TS_HELLO_COMMAND}, logger);
public static void send(IoStream stream) throws IOException {
stream.sendPacket(new byte[]{Fields.TS_HELLO_COMMAND});
}
@Nullable
public static String getHelloResponse(IncomingDataBuffer incomingData, Logger logger) throws EOFException {
byte[] response = incomingData.getPacket(logger, "[hello]", false);
public static String getHelloResponse(IncomingDataBuffer incomingData) throws EOFException {
byte[] response = incomingData.getPacket("[hello]", false);
if (!checkResponseCode(response, BinaryProtocolCommands.RESPONSE_OK))
return null;
return new String(response, 1, response.length - 1);
@ -41,6 +38,6 @@ public class HelloCommand implements Command {
@Override
public void handle(IoStream stream) throws IOException {
stream.sendPacket((BinaryProtocolServer.TS_OK + tsSignature).getBytes(), logger);
stream.sendPacket((BinaryProtocolServer.TS_OK + tsSignature).getBytes());
}
}

View File

@ -1,6 +1,6 @@
package com.rusefi.io.serial;
import com.opensr5.Logger;
import com.devexperts.logging.Logging;
import com.rusefi.Callable;
import com.rusefi.binaryprotocol.BinaryProtocol;
import com.rusefi.core.MessagesCentral;
@ -13,6 +13,8 @@ import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import static com.devexperts.logging.Logging.getLogging;
/**
* This class holds the reference to the actual Serial port object
* <p/>
@ -20,8 +22,9 @@ import java.awt.*;
* Andrey Belomutskiy, (c) 2013-2020
*/
public class PortHolder {
private static final Logging log = getLogging(PortHolder.class);
private final DataListener dataListener;
private final Logger logger;
private final Callable<IoStream> ioStreamCallable;
private final LinkManager linkManager;
@ -32,11 +35,10 @@ public class PortHolder {
@Nullable
private BinaryProtocol bp;
protected PortHolder(String port, LinkManager linkManager, Logger logger, Callable<IoStream> ioStreamCallable) {
protected PortHolder(String port, LinkManager linkManager, Callable<IoStream> ioStreamCallable) {
this.port = port;
this.linkManager = linkManager;
dataListener = freshData -> linkManager.getEngineState().processNewData(new String(freshData), LinkManager.ENCODER);
this.logger = logger;
this.ioStreamCallable = ioStreamCallable;
}
@ -44,7 +46,7 @@ public class PortHolder {
if (port == null)
return false;
MessagesCentral.getInstance().postMessage(logger, getClass(), "Opening port: " + port);
MessagesCentral.getInstance().postMessage(getClass(), "Opening port: " + port);
IoStream stream = ioStreamCallable.call();
if (stream == null) {
@ -52,7 +54,7 @@ public class PortHolder {
return false;
}
synchronized (portLock) {
bp = new BinaryProtocol(linkManager, logger, stream, stream.getDataBuffer());
bp = new BinaryProtocol(linkManager, stream, stream.getDataBuffer());
portLock.notifyAll();
}

View File

@ -1,13 +1,15 @@
package com.rusefi.io.serial;
import com.devexperts.logging.Logging;
import com.fazecast.jSerialComm.SerialPort;
import com.fazecast.jSerialComm.SerialPortDataListener;
import com.fazecast.jSerialComm.SerialPortEvent;
import com.opensr5.Logger;
import com.opensr5.io.DataListener;
import com.rusefi.binaryprotocol.IncomingDataBuffer;
import com.rusefi.io.IoStream;
import static com.devexperts.logging.Logging.getLogging;
/**
* https://github.com/Fazecast/jSerialComm looks to be alive as of 2020
* <p>
@ -15,19 +17,18 @@ import com.rusefi.io.IoStream;
* 06/03/2019
*/
public class SerialIoStreamJSerialComm extends AbstractIoStream {
private static final Logging log = getLogging(SerialIoStreamJSerialComm.class);
private SerialPort sp;
private final String port;
private final Logger logger;
private final IncomingDataBuffer dataBuffer;
/**
* @see #openPort(String, Logger)
* @see #openPort(String)
*/
private SerialIoStreamJSerialComm(SerialPort sp, String port, Logger logger) {
private SerialIoStreamJSerialComm(SerialPort sp, String port) {
this.sp = sp;
this.port = port;
this.logger = logger;
this.dataBuffer = IncomingDataBuffer.createDataBuffer("[serial] ", this, logger);
this.dataBuffer = IncomingDataBuffer.createDataBuffer("[serial] ", this);
}
@Override
@ -68,10 +69,10 @@ public class SerialIoStreamJSerialComm extends AbstractIoStream {
@Override
public void close() {
logger.info(port + ": Closing port...");
log.info(port + ": Closing port...");
super.close();
sp.closePort();
logger.info(port + ": Closed port.");
log.info(port + ": Closed port.");
}
@Override
@ -83,12 +84,12 @@ public class SerialIoStreamJSerialComm extends AbstractIoStream {
* Just open physical serial and not much more
* @see PortHolder#connectAndReadConfiguration()
*/
public static IoStream openPort(String port, Logger logger) {
logger.info("[SerialIoStreamJSerialComm] openPort " + port);
public static IoStream openPort(String port) {
log.info("[SerialIoStreamJSerialComm] openPort " + port);
SerialPort serialPort = SerialPort.getCommPort(port);
serialPort.setBaudRate(BaudRateHolder.INSTANCE.baudRate);
serialPort.openPort(0);
// FileLog.LOGGER.info("[SerialIoStreamJSerialComm] opened " + port);
return new SerialIoStreamJSerialComm(serialPort, port, logger);
return new SerialIoStreamJSerialComm(serialPort, port);
}
}

View File

@ -1,6 +1,6 @@
package com.rusefi.io.serial;
import com.opensr5.Logger;
import com.devexperts.logging.Logging;
import com.rusefi.Callable;
import com.rusefi.binaryprotocol.BinaryProtocol;
import com.rusefi.core.MessagesCentral;
@ -9,34 +9,32 @@ import com.rusefi.io.IoStream;
import com.rusefi.io.LinkConnector;
import com.rusefi.io.LinkManager;
import static com.devexperts.logging.Logging.getLogging;
/**
* @author Andrey Belomutskiy
* 3/3/14
*/
public class StreamConnector implements LinkConnector {
private static final Logging log = getLogging(StreamConnector.class);
private final PortHolder portHolder;
private final Logger logger;
private final LinkManager linkManager;
public StreamConnector(LinkManager linkManager, String portName, Logger logger, Callable<IoStream> ioStreamCallable) {
public StreamConnector(LinkManager linkManager, String portName, Callable<IoStream> ioStreamCallable) {
this.linkManager = linkManager;
this.logger = logger;
portHolder = new PortHolder(portName, linkManager, logger, ioStreamCallable);
portHolder = new PortHolder(portName, linkManager, ioStreamCallable);
}
@Override
public void connectAndReadConfiguration(ConnectionStateListener listener) {
logger.info("StreamConnector: connecting");
log.info("StreamConnector: connecting");
portHolder.listener = listener;
logger.info("scheduleOpening");
linkManager.execute(new Runnable() {
@Override
public void run() {
logger.info("scheduleOpening>openPort");
portHolder.connectAndReadConfiguration();
}
log.info("scheduleOpening");
linkManager.execute(() -> {
log.info("scheduleOpening>openPort");
portHolder.connectAndReadConfiguration();
});
}
@ -52,13 +50,10 @@ public class StreamConnector implements LinkConnector {
@Override
public void restart() {
linkManager.execute(new Runnable() {
@Override
public void run() {
MessagesCentral.getInstance().postMessage(logger, StreamConnector.this.getClass(), "Restarting serial IO");
portHolder.close();
portHolder.connectAndReadConfiguration();
}
linkManager.execute(() -> {
MessagesCentral.getInstance().postMessage(StreamConnector.this.getClass(), "Restarting serial IO");
portHolder.close();
portHolder.connectAndReadConfiguration();
});
}

View File

@ -1,6 +1,6 @@
package com.rusefi.io.tcp;
import com.opensr5.Logger;
import com.devexperts.logging.Logging;
import com.rusefi.Timeouts;
import com.rusefi.binaryprotocol.BinaryProtocol;
import com.rusefi.binaryprotocol.IncomingDataBuffer;
@ -12,29 +12,31 @@ import java.io.IOException;
import java.net.Socket;
import java.util.function.Function;
import static com.devexperts.logging.Logging.getLogging;
import static com.rusefi.binaryprotocol.BinaryProtocolCommands.COMMAND_PROTOCOL;
import static com.rusefi.config.generated.Fields.TS_PROTOCOL;
public class BinaryProtocolProxy {
private static final Logging log = getLogging(BinaryProtocolProxy.class);
/**
* we expect server to at least request output channels once in a while
* it could be a while between user connecting authenticator and actually connecting application to authenticator
*/
public static final int USER_IO_TIMEOUT = 600 * Timeouts.SECOND;
public static ServerHolder createProxy(Logger logger, IoStream targetEcuSocket, int serverProxyPort) {
public static ServerHolder createProxy(IoStream targetEcuSocket, int serverProxyPort) {
Function<Socket, Runnable> clientSocketRunnableFactory = clientSocket -> () -> {
try {
TcpIoStream clientStream = new TcpIoStream("[[proxy]] ", logger, clientSocket);
runProxy(logger, targetEcuSocket, clientStream);
TcpIoStream clientStream = new TcpIoStream("[[proxy]] ", clientSocket);
runProxy(targetEcuSocket, clientStream);
} catch (IOException e) {
logger.error("BinaryProtocolProxy::run " + e);
log.error("BinaryProtocolProxy::run " + e);
}
};
return BinaryProtocolServer.tcpServerSocket(serverProxyPort, "proxy", clientSocketRunnableFactory, Logger.CONSOLE, null);
return BinaryProtocolServer.tcpServerSocket(serverProxyPort, "proxy", clientSocketRunnableFactory, null);
}
public static void runProxy(Logger logger, IoStream targetEcu, IoStream clientStream) throws IOException {
public static void runProxy(IoStream targetEcu, IoStream clientStream) throws IOException {
/*
* Each client socket is running on it's own thread
*/
@ -45,7 +47,7 @@ public class BinaryProtocolProxy {
clientStream.write(TS_PROTOCOL.getBytes());
continue;
}
proxyClientRequestToController(logger, clientStream.getDataBuffer(), firstByte, targetEcu);
proxyClientRequestToController(clientStream.getDataBuffer(), firstByte, targetEcu);
proxyControllerResponseToClient(targetEcu, clientStream);
}
@ -54,11 +56,11 @@ public class BinaryProtocolProxy {
public static void proxyControllerResponseToClient(IoStream targetInputStream, IoStream clientOutputStream) throws IOException {
BinaryProtocolServer.Packet packet = targetInputStream.readPacket();
System.out.println("Relaying controller response length=" + packet.getPacket().length);
log.info("Relaying controller response length=" + packet.getPacket().length);
clientOutputStream.sendPacket(packet);
}
private static void proxyClientRequestToController(Logger logger, IncomingDataBuffer in, byte firstByte, IoStream targetOutputStream) throws IOException {
private static void proxyClientRequestToController(IncomingDataBuffer in, byte firstByte, IoStream targetOutputStream) throws IOException {
byte secondByte = in.readByte();
int length = firstByte * 256 + secondByte;
@ -67,7 +69,7 @@ public class BinaryProtocolProxy {
DataInputStream dis = new DataInputStream(new ByteArrayInputStream(packet.getPacket()));
byte command = (byte) dis.read();
logger.info("Relaying client command " + BinaryProtocol.findCommand(command));
log.info("Relaying client command " + BinaryProtocol.findCommand(command));
// sending proxied packet to controller
targetOutputStream.sendPacket(packet);
}

View File

@ -1,5 +1,6 @@
package com.rusefi.io.tcp;
import com.devexperts.logging.Logging;
import com.opensr5.ConfigurationImage;
import com.opensr5.Logger;
import com.rusefi.Listener;
@ -20,6 +21,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import static com.devexperts.logging.Logging.getLogging;
import static com.rusefi.binaryprotocol.IoHelper.swap16;
import static com.rusefi.config.generated.Fields.TS_PROTOCOL;
import static com.rusefi.config.generated.Fields.TS_RESPONSE_BURN_OK;
@ -33,9 +35,9 @@ import static com.rusefi.config.generated.Fields.TS_RESPONSE_BURN_OK;
*/
public class BinaryProtocolServer implements BinaryProtocolCommands {
private static final Logging log = getLogging(BinaryProtocolServer.class);
private static final int DEFAULT_PROXY_PORT = 2390;
public static final String TS_OK = "\0";
private final Logger logger;
public AtomicInteger unknownCommands = new AtomicInteger();
@ -51,27 +53,22 @@ public class BinaryProtocolServer implements BinaryProtocolCommands {
}
};
public BinaryProtocolServer(Logger logger) {
this.logger = logger;
}
public void start(LinkManager linkManager) {
start(linkManager, DEFAULT_PROXY_PORT, null);
}
public void start(LinkManager linkManager, int port, Listener serverSocketCreationCallback) {
logger.info("BinaryProtocolServer on " + port);
log.info("BinaryProtocolServer on " + port);
Function<Socket, Runnable> clientSocketRunnableFactory = clientSocket -> () -> {
try {
runProxy(linkManager, clientSocket);
} catch (IOException e) {
logger.info("proxy connection: " + e);
log.info("proxy connection: " + e);
}
};
tcpServerSocket(port, "BinaryProtocolServer", clientSocketRunnableFactory, logger, serverSocketCreationCallback);
tcpServerSocket(port, "BinaryProtocolServer", clientSocketRunnableFactory, serverSocketCreationCallback);
}
/**
@ -80,15 +77,14 @@ public class BinaryProtocolServer implements BinaryProtocolCommands {
* @param port server port to accept connections
* @param threadName
* @param socketRunnableFactory method to invoke on a new thread for each new client connection
* @param logger
* @param serverSocketCreationCallback this callback is invoked once we open the server socket
* @return
*/
public static ServerHolder tcpServerSocket(int port, String threadName, Function<Socket, Runnable> socketRunnableFactory, final Logger logger, Listener serverSocketCreationCallback) {
return tcpServerSocket(logger, socketRunnableFactory, port, threadName, serverSocketCreationCallback, PLAIN_SOCKET_FACTORY);
public static ServerHolder tcpServerSocket(int port, String threadName, Function<Socket, Runnable> socketRunnableFactory, Listener serverSocketCreationCallback) {
return tcpServerSocket(socketRunnableFactory, port, threadName, serverSocketCreationCallback, PLAIN_SOCKET_FACTORY);
}
public static ServerHolder tcpServerSocket(Logger logger, Function<Socket, Runnable> clientSocketRunnableFactory, int port, String threadName, Listener serverSocketCreationCallback, Function<Integer, ServerSocket> nonSecureSocketFunction) {
public static ServerHolder tcpServerSocket(Function<Socket, Runnable> clientSocketRunnableFactory, int port, String threadName, Listener serverSocketCreationCallback, Function<Integer, ServerSocket> nonSecureSocketFunction) {
ServerSocket serverSocket = nonSecureSocketFunction.apply(port);
ServerHolder holder = new ServerHolder() {
@ -108,10 +104,10 @@ public class BinaryProtocolServer implements BinaryProtocolCommands {
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
logger.info("Client socket closed right away" + e);
log.info("Client socket closed right away" + e);
continue;
}
logger.info("Binary protocol proxy port connection");
log.info("Binary protocol proxy port connection");
new Thread(clientSocketRunnableFactory.apply(clientSocket), "proxy connection").start();
}
};
@ -121,7 +117,7 @@ public class BinaryProtocolServer implements BinaryProtocolCommands {
@SuppressWarnings("InfiniteLoopStatement")
private void runProxy(LinkManager linkManager, Socket clientSocket) throws IOException {
TcpIoStream stream = new TcpIoStream("[proxy] ", logger, clientSocket);
TcpIoStream stream = new TcpIoStream("[proxy] ", clientSocket);
IncomingDataBuffer in = stream.getDataBuffer();
@ -137,7 +133,8 @@ public class BinaryProtocolServer implements BinaryProtocolCommands {
continue;
}
System.out.println("Got [" + length + "] length promise");
if (log.debugEnabled())
log.debug("Got [" + length + "] length promise");
Packet packet = readPromisedBytes(in, length);
byte[] payload = packet.getPacket();
@ -147,19 +144,18 @@ public class BinaryProtocolServer implements BinaryProtocolCommands {
byte command = payload[0];
System.out.println("Got command " + BinaryProtocol.findCommand(command));
log.info("Got command " + BinaryProtocol.findCommand(command));
if (command == Fields.TS_HELLO_COMMAND) {
new HelloCommand(logger, Fields.TS_SIGNATURE).handle(stream);
new HelloCommand(Fields.TS_SIGNATURE).handle(stream);
} else if (command == COMMAND_PROTOCOL) {
// System.out.println("Ignoring crc F command");
stream.sendPacket((TS_OK + TS_PROTOCOL).getBytes(), logger);
stream.sendPacket((TS_OK + TS_PROTOCOL).getBytes());
} else if (command == Fields.TS_GET_FIRMWARE_VERSION) {
stream.sendPacket((TS_OK + "rusEFI proxy").getBytes(), logger);
stream.sendPacket((TS_OK + "rusEFI proxy").getBytes());
} else if (command == COMMAND_CRC_CHECK_COMMAND) {
handleCrc(linkManager, stream);
} else if (command == COMMAND_PAGE) {
stream.sendPacket(TS_OK.getBytes(), logger);
stream.sendPacket(TS_OK.getBytes());
} else if (command == COMMAND_READ) {
DataInputStream dis = new DataInputStream(new ByteArrayInputStream(payload, 1, payload.length - 1));
handleRead(linkManager, dis, stream);
@ -167,16 +163,16 @@ public class BinaryProtocolServer implements BinaryProtocolCommands {
DataInputStream dis = new DataInputStream(new ByteArrayInputStream(payload, 1, payload.length - 1));
handleWrite(linkManager, payload, dis, stream);
} else if (command == Fields.TS_BURN_COMMAND) {
stream.sendPacket(new byte[]{TS_RESPONSE_BURN_OK}, logger);
stream.sendPacket(new byte[]{TS_RESPONSE_BURN_OK});
} else if (command == Fields.TS_GET_COMPOSITE_BUFFER_DONE_DIFFERENTLY) {
System.err.println("NOT IMPLEMENTED TS_GET_COMPOSITE_BUFFER_DONE_DIFFERENTLY relay");
// todo: relay command
stream.sendPacket(TS_OK.getBytes(), logger);
stream.sendPacket(TS_OK.getBytes());
} else if (command == Fields.TS_OUTPUT_COMMAND) {
DataInputStream dis = new DataInputStream(new ByteArrayInputStream(payload, 1, payload.length - 1));
int offset = swap16(dis.readShort());
int count = swap16(dis.readShort());
logger.info("TS_OUTPUT_COMMAND offset=" + offset + "/count=" + count);
log.info("TS_OUTPUT_COMMAND offset=" + offset + "/count=" + count);
byte[] response = new byte[1 + count];
response[0] = (byte) TS_OK.charAt(0);
@ -184,15 +180,15 @@ public class BinaryProtocolServer implements BinaryProtocolCommands {
byte[] currentOutputs = binaryProtocolState.getCurrentOutputs();
if (currentOutputs != null)
System.arraycopy(currentOutputs, 1 + offset, response, 1, count);
stream.sendPacket(response, logger);
stream.sendPacket(response);
} else if (command == Fields.TS_GET_TEXT) {
// todo: relay command
System.err.println("NOT IMPLEMENTED TS_GET_TEXT relay");
stream.sendPacket(TS_OK.getBytes(), logger);
stream.sendPacket(TS_OK.getBytes());
} else {
unknownCommands.incrementAndGet();
new IllegalStateException().printStackTrace();
logger.info("Error: unexpected " + BinaryProtocol.findCommand(command));
log.info("Error: unexpected " + BinaryProtocol.findCommand(command));
}
}
}
@ -241,7 +237,7 @@ public class BinaryProtocolServer implements BinaryProtocolCommands {
}
public static void handleProtocolCommand(Socket clientSocket) throws IOException {
System.out.println("Got plain F command");
log.info("Got plain F command");
OutputStream outputStream = clientSocket.getOutputStream();
outputStream.write(TS_PROTOCOL.getBytes());
outputStream.flush();
@ -251,10 +247,10 @@ public class BinaryProtocolServer implements BinaryProtocolCommands {
dis.readShort(); // page
int offset = swap16(dis.readShort());
int count = swap16(dis.readShort());
logger.info("TS_CHUNK_WRITE_COMMAND: offset=" + offset + " count=" + count);
log.info("TS_CHUNK_WRITE_COMMAND: offset=" + offset + " count=" + count);
BinaryProtocolState bp = linkManager.getBinaryProtocolState();
bp.setRange(packet, 7, offset, count);
stream.sendPacket(TS_OK.getBytes(), logger);
stream.sendPacket(TS_OK.getBytes());
}
private void handleRead(LinkManager linkManager, DataInputStream dis, TcpIoStream stream) throws IOException {
@ -262,9 +258,10 @@ public class BinaryProtocolServer implements BinaryProtocolCommands {
int offset = swap16(dis.readShort());
int count = swap16(dis.readShort());
if (count <= 0) {
logger.info("Error: negative read request " + offset + "/" + count);
log.info("Error: negative read request " + offset + "/" + count);
} else {
System.out.println("read " + page + "/" + offset + "/" + count);
if (log.debugEnabled())
log.debug("read " + page + "/" + offset + "/" + count);
BinaryProtocolState bp = linkManager.getBinaryProtocolState();
byte[] response = new byte[1 + count];
response[0] = (byte) TS_OK.charAt(0);
@ -272,19 +269,19 @@ public class BinaryProtocolServer implements BinaryProtocolCommands {
ConfigurationImage configurationImage = bp.getControllerConfiguration();
Objects.requireNonNull(configurationImage, "configurationImage");
System.arraycopy(configurationImage.getContent(), offset, response, 1, count);
stream.sendPacket(response, logger);
stream.sendPacket(response);
}
}
private void handleCrc(LinkManager linkManager, TcpIoStream stream) throws IOException {
System.out.println("CRC check");
log.info("CRC check");
BinaryProtocolState bp = linkManager.getBinaryProtocolState();
byte[] content = bp.getControllerConfiguration().getContent();
int result = IoHelper.getCrc32(content);
ByteArrayOutputStream response = new ByteArrayOutputStream();
response.write(TS_OK.charAt(0));
new DataOutputStream(response).writeInt(result);
stream.sendPacket(response.toByteArray(), logger);
stream.sendPacket(response.toByteArray());
}
public static class Packet {

View File

@ -1,6 +1,5 @@
package com.rusefi.io.tcp;
import com.opensr5.Logger;
import com.opensr5.io.DataListener;
import com.rusefi.binaryprotocol.IncomingDataBuffer;
import com.rusefi.io.ByteReader;
@ -21,22 +20,21 @@ import java.net.Socket;
public class TcpIoStream extends AbstractIoStream {
private final InputStream input;
private final OutputStream output;
private final Logger logger;
private final String loggingPrefix;
private final DisconnectListener disconnectListener;
@NotNull
private final Socket socket;
private final IncomingDataBuffer dataBuffer;
public TcpIoStream(Logger logger, Socket socket) throws IOException {
this("", logger, socket);
public TcpIoStream(Socket socket) throws IOException {
this("", socket);
}
public TcpIoStream(String loggingPrefix, Logger logger, Socket socket) throws IOException {
this(loggingPrefix, logger, socket, DisconnectListener.VOID);
public TcpIoStream(String loggingPrefix, Socket socket) throws IOException {
this(loggingPrefix, socket, DisconnectListener.VOID);
}
public TcpIoStream(String loggingPrefix, Logger logger, Socket socket, DisconnectListener disconnectListener) throws IOException {
public TcpIoStream(String loggingPrefix, Socket socket, DisconnectListener disconnectListener) throws IOException {
this.loggingPrefix = loggingPrefix;
this.disconnectListener = disconnectListener;
if (socket == null)
@ -44,12 +42,11 @@ public class TcpIoStream extends AbstractIoStream {
this.socket = socket;
InputStream input = new BufferedInputStream(socket.getInputStream());
OutputStream output = socket.getOutputStream();
this.logger = logger;
if (output == null)
throw new NullPointerException("output");
this.output = output;
this.input = input;
this.dataBuffer = IncomingDataBuffer.createDataBuffer(loggingPrefix, this, logger);
this.dataBuffer = IncomingDataBuffer.createDataBuffer(loggingPrefix, this);
}
@Override
@ -81,7 +78,7 @@ public class TcpIoStream extends AbstractIoStream {
@Override
public void setInputListener(final DataListener listener) {
ByteReader.runReaderLoop(loggingPrefix, listener, input::read, logger, disconnectListener);
ByteReader.runReaderLoop(loggingPrefix, listener, input::read, disconnectListener);
}
public interface DisconnectListener {

View File

@ -1,5 +1,6 @@
package com.rusefi.tools.online;
import com.devexperts.logging.Logging;
import com.opensr5.Logger;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
@ -15,7 +16,11 @@ import org.json.simple.parser.ParseException;
import java.io.IOException;
import static com.devexperts.logging.Logging.getLogging;
public class HttpUtil {
private static final Logging log = getLogging(Logging.class);
// todo: migrate proxy http json API server to TLS
public static final String RUSEFI_PROXY_JSON_PROTOCOL = "http://";
public static final int PROXY_JSON_API_HTTP_PORT = 8001;
@ -35,18 +40,18 @@ public class HttpUtil {
public static String getResponse(HttpResponse response) throws IOException {
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity, "UTF-8");
Logger.CONSOLE.info("responseString=" + responseString);
log.info("responseString=" + responseString);
return responseString;
}
public static String executeGet(Logger logger, String url) throws IOException {
public static String executeGet(String url) throws IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpParams httpParameters = httpclient.getParams();
// HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIMEOUT);
// HttpConnectionParams.setSoTimeout(httpParameters, WAIT_RESPONSE_TIMEOUT);
// without this magic http response is pretty slow
HttpConnectionParams.setTcpNoDelay(httpParameters, true);
logger.info("GET " + url);
log.info("GET " + url);
HttpGet httpget = new HttpGet(url);
// in case of emergency

View File

@ -1,9 +1,7 @@
package com.rusefi.tools.online;
import com.opensr5.Logger;
import com.rusefi.server.ControllerInfo;
import com.rusefi.server.UserDetails;
import org.apache.http.HttpResponse;
import org.jetbrains.annotations.NotNull;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
@ -32,7 +30,7 @@ public class ProxyClient {
@NotNull
public static List<PublicSession> getOnlineApplications(String url) throws IOException {
String responseString = HttpUtil.executeGet(Logger.CONSOLE, url);
String responseString = HttpUtil.executeGet(url);
List<PublicSession> userLists = new ArrayList<>();
try {

View File

@ -1,5 +1,6 @@
package com.rusefi.core;
import com.devexperts.logging.Logging;
import com.opensr5.Logger;
import com.rusefi.config.generated.Fields;
import com.rusefi.io.LinkDecoder;
@ -8,6 +9,8 @@ import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.util.*;
import static com.devexperts.logging.Logging.getLogging;
/**
* Date: 12/25/12
* Andrey Belomutskiy, (c) 2013-2020
@ -15,6 +18,8 @@ import java.util.*;
* @see #registerStringValueAction
*/
public class EngineState {
private static final Logging log = getLogging(EngineState.class);
public static final String SEPARATOR = ",";
public static final String PACKING_DELIMITER = ":";
public static final Class<EngineState> ENGINE_STATE_CLASS = EngineState.class;
@ -43,11 +48,10 @@ public class EngineState {
}
private final ResponseBuffer buffer;
private final Logger logger;
private final List<StringActionPair> actions = new ArrayList<>();
private final Set<String> keys = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
public EngineState(@NotNull final EngineStateListener listener, Logger logger) {
public EngineState(@NotNull final EngineStateListener listener) {
buffer = new ResponseBuffer(new ResponseBuffer.ResponseListener() {
public void onResponse(String response) {
if (response != null) {
@ -64,9 +68,8 @@ public class EngineState {
}
}
);
this.logger = logger;
registerStringValueAction(Fields.PROTOCOL_MSG, value -> MessagesCentral.getInstance().postMessage(logger, ENGINE_STATE_CLASS, value));
registerStringValueAction(Fields.PROTOCOL_MSG, value -> MessagesCentral.getInstance().postMessage(ENGINE_STATE_CLASS, value));
}
/**
@ -133,7 +136,7 @@ public class EngineState {
response = handleStringActionPair(response, pair, listener);
}
if (originalResponse.length() == response.length()) {
logger.info("EngineState.unknown: " + response);
log.info("EngineState.unknown: " + response);
int keyEnd = response.indexOf(SEPARATOR);
if (keyEnd == -1) {
// discarding invalid line
@ -146,7 +149,7 @@ public class EngineState {
return "";
}
String value = response.substring(keyEnd, valueEnd);
logger.info("Invalid key [" + unknownKey + "] value [" + value + "]");
log.info("Invalid key [" + unknownKey + "] value [" + value + "]");
// trying to process the rest of the line
response = response.substring(valueEnd + SEPARATOR.length());
}

View File

@ -1,11 +1,13 @@
package com.rusefi.core;
import com.opensr5.Logger;
import com.devexperts.logging.Logging;
import javax.swing.*;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import static com.devexperts.logging.Logging.getLogging;
/**
* Messages from the firmware and UI panels which want to display them
*
@ -13,6 +15,8 @@ import java.util.concurrent.CopyOnWriteArrayList;
* Andrey Belomutskiy, (c) 2013-2020
*/
public class MessagesCentral {
private static final Logging log = getLogging(MessagesCentral.class);
private static final MessagesCentral INSTANCE = new MessagesCentral();
private final List<MessageListener> listeners = new CopyOnWriteArrayList<>();
@ -27,8 +31,8 @@ public class MessagesCentral {
listeners.add(listener);
}
public void postMessage(Logger logger, final Class clazz, final String message) {
logger.info("postMessage " + clazz.getSimpleName() + ": " + message);
public void postMessage(final Class clazz, final String message) {
log.info("postMessage " + clazz.getSimpleName() + ": " + message);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {

View File

@ -1,6 +1,5 @@
package com.irnems;
import com.rusefi.FileLog;
import com.rusefi.core.EngineState;
import com.rusefi.file.FileUtils;
@ -41,7 +40,7 @@ public class AdcFilter {
}
};
EngineState engineState = new EngineState(listener, FileLog.LOGGER);
EngineState engineState = new EngineState(listener);
FileUtils.readFile2(filename, engineState);

View File

@ -1,6 +1,5 @@
package com.irnems.file;
import com.rusefi.FileLog;
import com.rusefi.core.EngineState;
import com.rusefi.file.FileUtils;
@ -42,7 +41,7 @@ public class FrequencyDivider {
lineCounter++;
}
};
FileUtils.readFile(filename, listener, FileLog.LOGGER);
FileUtils.readFile(filename, listener);
fos.close();
}
}

View File

@ -143,7 +143,7 @@ public class ConsoleUI {
tabbedPane.addTab("Trigger Shape", new AverageAnglePanel(uiContext).getPanel());
}
MessagesCentral.getInstance().postMessage(FileLog.LOGGER, ConsoleUI.class, "COMPOSITE_OFF_RPM=" + BinaryProtocol.COMPOSITE_OFF_RPM);
MessagesCentral.getInstance().postMessage(ConsoleUI.class, "COMPOSITE_OFF_RPM=" + BinaryProtocol.COMPOSITE_OFF_RPM);
tabbedPane.addTab("rusEFI Online", new OnlineTab(uiContext).getContent());
@ -235,7 +235,7 @@ public class ConsoleUI {
new ConsoleUI(port);
} else {
for (String p : LinkManager.getCommPorts())
MessagesCentral.getInstance().postMessage(FileLog.LOGGER, Launcher.class, "Available port: " + p);
MessagesCentral.getInstance().postMessage(Launcher.class, "Available port: " + p);
new StartupFrame().chooseSerialPort();
}

View File

@ -100,7 +100,7 @@ public class EcuStimulator {
putValue("engine_load", engineLoad) +
putValue("advance", advance) +
putValue("dwell", dwell);
MessagesCentral.getInstance().postMessage(FileLog.LOGGER, EcuStimulator.class, msg);
MessagesCentral.getInstance().postMessage(EcuStimulator.class, msg);
try {
csv.write(msg + "\r\n");
@ -232,7 +232,7 @@ public class EcuStimulator {
}
private static void log(String message) {
MessagesCentral.getInstance().postMessage(FileLog.LOGGER, EcuStimulator.class, message);
MessagesCentral.getInstance().postMessage(EcuStimulator.class, message);
FileLog.MAIN.logLine(message);
}

View File

@ -1,6 +1,5 @@
package com.rusefi.autodetect;
import com.rusefi.FileLog;
import com.rusefi.IoUtil;
import com.rusefi.io.ConnectionStatusLogic;
import com.rusefi.io.LinkManager;
@ -11,7 +10,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
public class ReconnectSandbox {
public static void main(String[] args) {
LinkManager linkManager = new LinkManager(FileLog.LOGGER);
LinkManager linkManager = new LinkManager();
LightweightGUI.waitForDeviceAndStart(linkManager);

View File

@ -38,12 +38,12 @@ public class SerialAutoChecker implements Runnable {
@Override
public void run() {
IoStream stream = SerialIoStreamJSerialComm.openPort(serialPort, logger);
IoStream stream = SerialIoStreamJSerialComm.openPort(serialPort);
Logger logger = FileLog.LOGGER;
IncomingDataBuffer incomingData = stream.getDataBuffer();
try {
HelloCommand.send(stream, logger);
byte[] response = incomingData.getPacket(logger, "", false);
HelloCommand.send(stream);
byte[] response = incomingData.getPacket("", false);
if (!checkResponseCode(response, BinaryProtocolCommands.RESPONSE_OK))
return;
String signature = new String(response, 1, response.length - 1);

View File

@ -40,7 +40,7 @@ public abstract class TestSequenceStep {
next.execute(executor);
}
} else {
MessagesCentral.getInstance().postMessage(FileLog.LOGGER, TestSequenceStep.class, "ETB test sequence done!");
MessagesCentral.getInstance().postMessage(TestSequenceStep.class, "ETB test sequence done!");
}
}

View File

@ -2,7 +2,6 @@ package com.rusefi.maintenance;
import com.opensr5.ini.IniFileModel;
import com.rusefi.ConsoleUI;
import com.rusefi.FileLog;
import com.rusefi.Launcher;
import com.rusefi.Timeouts;
import com.rusefi.autodetect.PortDetector;
@ -45,14 +44,14 @@ public class DfuFlasher {
if (!PortDetector.isAutoPort(port)) {
messages.append("Using selected " + port + "\n");
IoStream stream = SerialIoStreamJSerialComm.openPort(port, FileLog.LOGGER);
DfuHelper.sendDfuRebootCommand(stream, messages, FileLog.LOGGER);
IoStream stream = SerialIoStreamJSerialComm.openPort(port);
DfuHelper.sendDfuRebootCommand(stream, messages);
} else {
messages.append("Auto-detecting port...\n");
// instead of opening the just-detected port we execute the command using the same stream we used to discover port
// it's more reliable this way
port = PortDetector.autoDetectSerial(stream -> {
DfuHelper.sendDfuRebootCommand(stream, messages, FileLog.LOGGER);
DfuHelper.sendDfuRebootCommand(stream, messages);
return null;
});
if (port == null) {

View File

@ -147,9 +147,9 @@ public class ConsoleTools {
String autoDetectedPort = autoDetectPort();
if (autoDetectedPort == null)
return;
IoStream stream = SerialIoStreamJSerialComm.openPort(autoDetectedPort, FileLog.LOGGER);
IoStream stream = SerialIoStreamJSerialComm.openPort(autoDetectedPort);
byte[] commandBytes = BinaryProtocol.getTextCommandBytes(command);
stream.sendPacket(commandBytes, FileLog.LOGGER);
stream.sendPacket(commandBytes);
}
@ -208,11 +208,11 @@ public class ConsoleTools {
System.err.println(RUS_EFI_NOT_DETECTED);
return;
}
LinkManager linkManager = new LinkManager(FileLog.LOGGER);
LinkManager linkManager = new LinkManager();
linkManager.startAndConnect(autoDetectedPort, new ConnectionStateListener() {
@Override
public void onConnectionEstablished() {
new BinaryProtocolServer(FileLog.LOGGER).start(linkManager);
new BinaryProtocolServer().start(linkManager);
}
@Override
@ -318,19 +318,19 @@ public class ConsoleTools {
System.out.println(RUS_EFI_NOT_DETECTED);
return;
}
IoStream stream = SerialIoStreamJSerialComm.openPort(autoDetectedPort, FileLog.LOGGER);
IoStream stream = SerialIoStreamJSerialComm.openPort(autoDetectedPort);
Logger logger = FileLog.LOGGER;
IncomingDataBuffer incomingData = stream.getDataBuffer();
byte[] commandBytes = BinaryProtocol.getTextCommandBytes("hello");
stream.sendPacket(commandBytes, logger);
stream.sendPacket(commandBytes);
// skipping response
incomingData.getPacket(logger, "", true);
incomingData.getPacket("", true);
sleep(300);
stream.sendPacket(new byte[]{Fields.TS_GET_TEXT}, logger);
stream.sendPacket(new byte[]{Fields.TS_GET_TEXT});
sleep(300);
byte[] response = incomingData.getPacket(logger, "", true);
byte[] response = incomingData.getPacket("", true);
if (response == null) {
System.out.println("No response");
return;

View File

@ -6,7 +6,6 @@ import com.rusefi.autoupdate.AutoupdateUtil;
import com.rusefi.config.generated.Fields;
import com.rusefi.core.MessagesCentral;
import com.rusefi.io.CommandQueue;
import com.rusefi.io.LinkManager;
import com.rusefi.ui.util.UiUtils;
import javax.swing.*;
@ -293,7 +292,7 @@ public class RecentCommands {
} catch (IOException e) {
throw new IllegalStateException(e);
}
MessagesCentral.getInstance().postMessage(FileLog.LOGGER, AverageAnglesUtil.class, report);
MessagesCentral.getInstance().postMessage(AverageAnglesUtil.class, report);
}
}
});

View File

@ -1,13 +1,12 @@
package com.rusefi.ui;
import com.rusefi.FileLog;
import com.rusefi.SensorSnifferCentral;
import com.rusefi.io.CommandQueue;
import com.rusefi.io.LinkManager;
import com.rusefi.sensor_logs.SensorLogger;
public class UIContext {
private final LinkManager linkManager = new LinkManager(FileLog.LOGGER);
private final LinkManager linkManager = new LinkManager();
public SensorLogger sensorLogger = new SensorLogger(this);
public GaugesPanel.DetachedRepository DetachedRepositoryINSTANCE = new GaugesPanel.DetachedRepository(this);

View File

@ -60,7 +60,7 @@ public class MainFrame {
tabbedPane.settingsTab.showContent();
tabbedPane.logsManager.showContent();
tabbedPane.fuelTunePane.showContent();
new BinaryProtocolServer(FileLog.LOGGER).start(consoleUI.uiContext.getLinkManager());
new BinaryProtocolServer().start(consoleUI.uiContext.getLinkManager());
}
};
}
@ -96,7 +96,7 @@ public class MainFrame {
tabbedPane.settingsTab.showContent();
tabbedPane.logsManager.showContent();
tabbedPane.fuelTunePane.showContent();
new BinaryProtocolServer(FileLog.LOGGER).start(linkManager);
new BinaryProtocolServer().start(linkManager);
}
});

View File

@ -1,6 +1,5 @@
package com.rusefi.ui.etb;
import com.rusefi.FileLog;
import com.rusefi.core.MessagesCentral;
import com.rusefi.core.Sensor;
import com.rusefi.core.SensorCentral;
@ -62,14 +61,14 @@ public class EtbMonteCarloSequence {
":pFactor:" + pFactor +
":iFactor:" + iFactor +
":dFactor:" + dFactor;
MessagesCentral.getInstance().postMessage(FileLog.LOGGER, EtbMonteCarloSequence.class, stats);
MessagesCentral.getInstance().postMessage(EtbMonteCarloSequence.class, stats);
uiContext.getCommandQueue().write("etbreset");
uiContext.getCommandQueue().write("set etb_o " + offset);
uiContext.getCommandQueue().write("set etb_p " + pFactor);
uiContext.getCommandQueue().write("set etb_i " + iFactor);
uiContext.getCommandQueue().write("set etb_d " + dFactor);
MessagesCentral.getInstance().postMessage(FileLog.LOGGER, EtbMonteCarloSequence.class,
MessagesCentral.getInstance().postMessage(EtbMonteCarloSequence.class,
uiContext.sensorLogger.getSecondsSinceFileStart() + " running " + stats);
TestSequenceStep firstStep = new EtbTarget(uiContext, 10 * SECOND, DEFAULT_POSITION, null, TestSequenceStep.Condition.YES);
@ -79,7 +78,7 @@ public class EtbMonteCarloSequence {
double currentValue = StandardTestSequence.metric.getStandardDeviation();
boolean shouldRun = currentValue < bestResultSoFar;
if (!shouldRun) {
MessagesCentral.getInstance().postMessage(FileLog.LOGGER, EtbMonteCarloSequence.class,
MessagesCentral.getInstance().postMessage(EtbMonteCarloSequence.class,
"Two much error accumulated, aborting! " + currentValue + " > " + bestResultSoFar);
}
@ -93,7 +92,7 @@ public class EtbMonteCarloSequence {
Runnable onEachStep = () -> SwingUtilities.invokeLater(() -> {
String state = stepCounter.incrementAndGet() + "/" + totalSteps.get();
double value = StandardTestSequence.metric.getStandardDeviation();
MessagesCentral.getInstance().postMessage(FileLog.LOGGER, EtbMonteCarloSequence.class,"Running " + state + ", current=" + value);
MessagesCentral.getInstance().postMessage(EtbMonteCarloSequence.class,"Running " + state + ", current=" + value);
});
TestSequenceStep last = StandardTestSequence.addSequence(uiContext, firstStep, onEachStep, condition);
@ -109,18 +108,18 @@ public class EtbMonteCarloSequence {
double cycleResult = SensorCentral.getInstance().getValue(Sensor.ETB_CONTROL_QUALITY);
if (cycleResult < bestResultSoFar) {
bestResultSoFar = cycleResult;
MessagesCentral.getInstance().postMessage(FileLog.LOGGER, EtbMonteCarloSequence.class,
MessagesCentral.getInstance().postMessage(EtbMonteCarloSequence.class,
uiContext.sensorLogger.getSecondsSinceFileStart() + ":" + stats + ":new_record:" + bestResultSoFar);
}
MessagesCentral.getInstance().postMessage(FileLog.LOGGER, EtbMonteCarloSequence.class,
MessagesCentral.getInstance().postMessage(EtbMonteCarloSequence.class,
uiContext.sensorLogger.getSecondsSinceFileStart() + ":" + stats + ":result:" + cycleResult);
if (counter == TOTAL_CYCLES_COUNT) {
stopETB();
MessagesCentral.getInstance().postMessage(FileLog.LOGGER, EtbTestSequence.class, "ETB MC sequence done!");
MessagesCentral.getInstance().postMessage(EtbTestSequence.class, "ETB MC sequence done!");
return;
}
counter++;
MessagesCentral.getInstance().postMessage(FileLog.LOGGER, EtbTestSequence.class, "Starting " + counter + " of " + TOTAL_CYCLES_COUNT);
MessagesCentral.getInstance().postMessage(EtbTestSequence.class, "Starting " + counter + " of " + TOTAL_CYCLES_COUNT);
runRandomCycle();
}

View File

@ -1,10 +1,8 @@
package com.rusefi.ui.etb;
import com.rusefi.FileLog;
import com.rusefi.core.MessagesCentral;
import com.rusefi.core.Sensor;
import com.rusefi.core.SensorCentral;
import com.rusefi.io.CommandQueue;
import com.rusefi.ui.UIContext;
import javax.swing.*;
@ -82,7 +80,7 @@ public class EtbReturnToNeutral {
uiContext.getCommandQueue().write(ZERO_DUTY_CYCLE_COMMAND);
// CommandQueue.getInstance().write(DirectDrivePanel.CANCEL_DIRECT_DRIVE_COMMAND);
MessagesCentral.getInstance().postMessage(FileLog.LOGGER, getClass(), "Cycles = " + CYCLES_COUNT + ", errors = " + errorCount);
MessagesCentral.getInstance().postMessage(getClass(), "Cycles = " + CYCLES_COUNT + ", errors = " + errorCount);
}
/**
@ -90,10 +88,10 @@ public class EtbReturnToNeutral {
*/
private boolean assertPosition(String msg, float expectedPosition) {
double tps = SensorCentral.getInstance().getValue(Sensor.TPS);
MessagesCentral.getInstance().postMessage(FileLog.LOGGER, getClass(), msg + " TPS=" + tps);
MessagesCentral.getInstance().postMessage(getClass(), msg + " TPS=" + tps);
boolean isError = Math.abs(tps - expectedPosition) > ACCEPTABLE_ERROR;
if (isError)
MessagesCentral.getInstance().postMessage(FileLog.LOGGER, getClass(), msg + " NOT GREAT " + tps + " while expected " + expectedPosition);
MessagesCentral.getInstance().postMessage(getClass(), msg + " NOT GREAT " + tps + " while expected " + expectedPosition);
return isError;
}

View File

@ -1,10 +1,8 @@
package com.rusefi.ui.etb;
import com.rusefi.FileLog;
import com.rusefi.core.MessagesCentral;
import com.rusefi.core.Sensor;
import com.rusefi.core.SensorCentral;
import com.rusefi.io.CommandQueue;
import com.rusefi.io.InvocationConfirmationListener;
import com.rusefi.ui.UIContext;
import org.putgemin.VerticalFlowLayout;
@ -66,7 +64,7 @@ public class MagicSpotsFinder {
sleep(SLEEP);
double tpsPosition = SensorCentral.getInstance().getValue(Sensor.TPS);
MessagesCentral.getInstance().postMessage(FileLog.LOGGER, getClass(), "ETB duty " + currentDutyCycle + ": tps=" + tpsPosition);
MessagesCentral.getInstance().postMessage(getClass(), "ETB duty " + currentDutyCycle + ": tps=" + tpsPosition);
if (tpsPosition >= 100 - MEASURMENT_PRECISION) {
currentDutyCycle -= DUTY_CYCLE_STEP;
@ -77,7 +75,7 @@ public class MagicSpotsFinder {
// if that's the first we've moved let's remember duty cycle value
startedToCloseValue = currentDutyCycle;
startedToCloseValueLabel.setText(String.format("Started Close %.1f", startedToCloseValue));
MessagesCentral.getInstance().postMessage(FileLog.LOGGER, getClass(), "Started to close at " + startedToCloseValue);
MessagesCentral.getInstance().postMessage(getClass(), "Started to close at " + startedToCloseValue);
}
currentDutyCycle -= DUTY_CYCLE_STEP;
@ -85,10 +83,10 @@ public class MagicSpotsFinder {
} else {
backToZeroValue = currentDutyCycle;
backToZeroValueLabel.setText(String.format("Back Zero %.1f", backToZeroValue));
MessagesCentral.getInstance().postMessage(FileLog.LOGGER, getClass(), "Back closed to close at " + backToZeroValue);
MessagesCentral.getInstance().postMessage(getClass(), "Back closed to close at " + backToZeroValue);
MessagesCentral.getInstance().postMessage(FileLog.LOGGER, getClass(), "startedToOpenValue = " + startedToOpenValue + ", reached100Value = " + reached100Value);
MessagesCentral.getInstance().postMessage(FileLog.LOGGER, getClass(), "startedToCloseValue = " + startedToCloseValue + ", backToZeroValue = " + backToZeroValue);
MessagesCentral.getInstance().postMessage(getClass(), "startedToOpenValue = " + startedToOpenValue + ", reached100Value = " + reached100Value);
MessagesCentral.getInstance().postMessage(getClass(), "startedToCloseValue = " + startedToCloseValue + ", backToZeroValue = " + backToZeroValue);
button.setEnabled(true);
button.setText(MAGIC_SPOTS_FINDER);
}
@ -108,7 +106,7 @@ public class MagicSpotsFinder {
sleep(SLEEP);
double tpsPosition = SensorCentral.getInstance().getValue(Sensor.TPS);
MessagesCentral.getInstance().postMessage(FileLog.LOGGER, getClass(), "ETB duty " + currentDutyCycle + ": tps=" + tpsPosition);
MessagesCentral.getInstance().postMessage(getClass(), "ETB duty " + currentDutyCycle + ": tps=" + tpsPosition);
if (tpsPosition < defaultTpsPosition + MEASURMENT_PRECISION) {
// ETB has not moved yet, keep going up
@ -120,7 +118,7 @@ public class MagicSpotsFinder {
// if that's the first we've moved let's remember duty cycle value
startedToOpenValue = currentDutyCycle;
startedToOpenValueLabel.setText(String.format("Start to open: %.1f", startedToOpenValue));
MessagesCentral.getInstance().postMessage(FileLog.LOGGER, getClass(), "Started to open at " + startedToOpenValue);
MessagesCentral.getInstance().postMessage(getClass(), "Started to open at " + startedToOpenValue);
}
@ -132,7 +130,7 @@ public class MagicSpotsFinder {
// looks like we have reached 100%, cool!
reached100Value = currentDutyCycle;
reached100ValueLabel.setText(String.format("Reached 100: %.1f", reached100Value));
MessagesCentral.getInstance().postMessage(FileLog.LOGGER, getClass(), "startedToOpenValue = " + startedToOpenValue + ", reached100Value = " + reached100Value);
MessagesCentral.getInstance().postMessage(getClass(), "startedToOpenValue = " + startedToOpenValue + ", reached100Value = " + reached100Value);
currentDutyCycle -= DUTY_CYCLE_STEP;
uiContext.getCommandQueue().write(CMD_ETB_DUTY + " " + currentDutyCycle, goingDown);
@ -157,7 +155,7 @@ public class MagicSpotsFinder {
public void run() {
state = State.START;
MessagesCentral.getInstance().postMessage(FileLog.LOGGER, getClass(), "Start!");
MessagesCentral.getInstance().postMessage(getClass(), "Start!");
resetValues();
uiContext.getCommandQueue().write(CMD_ETB_DUTY + " " + currentDutyCycle, goingUp);
@ -210,7 +208,7 @@ public class MagicSpotsFinder {
private void sleep(long millis) {
try {
MessagesCentral.getInstance().postMessage(FileLog.LOGGER, getClass(), "Sleeping " + millis + "ms");
MessagesCentral.getInstance().postMessage(getClass(), "Sleeping " + millis + "ms");
Thread.sleep(millis);
} catch (InterruptedException unexpected) {
unexpected.printStackTrace();

View File

@ -179,7 +179,7 @@ public class LogViewer extends JPanel {
EngineState.EngineStateListener listener = new EngineState.EngineStateListenerImpl();
ChartRepository.getInstance().clear();
EngineState engineState = new EngineState(listener, FileLog.LOGGER);
EngineState engineState = new EngineState(listener);
// this is pretty dirty, better OOP desperately needed
ConsoleUI.engineSnifferPanel.setOutpinListener(engineState);
engineState.registerStringValueAction(EngineReport.ENGINE_CHART, new EngineState.ValueCallback<String>() {

View File

@ -136,9 +136,9 @@ public class AnyCommand {
String result = prepareEvalCommand(rawCommand);
if (result.equals(rawCommand)) {
// result was not translated
MessagesCentral.getInstance().postMessage(FileLog.LOGGER, AnyCommand.class, "Not valid expression");
MessagesCentral.getInstance().postMessage(FileLog.LOGGER, AnyCommand.class, "Please try eval \"2 + 2\"");
MessagesCentral.getInstance().postMessage(FileLog.LOGGER, AnyCommand.class, "For RPN use rpn_eval \"2 2 +\"");
MessagesCentral.getInstance().postMessage(AnyCommand.class, "Not valid expression");
MessagesCentral.getInstance().postMessage(AnyCommand.class, "Please try eval \"2 + 2\"");
MessagesCentral.getInstance().postMessage(AnyCommand.class, "For RPN use rpn_eval \"2 2 +\"");
}
return result;
} else if (rawCommand.toLowerCase().startsWith("stim_check" + " ")) {
@ -165,7 +165,7 @@ public class AnyCommand {
private static void handleStimulationSelfCheck(String rawCommand, LinkManager linkManager) {
String[] parts = rawCommand.split(" ", 4);
if (parts.length != 4) {
MessagesCentral.getInstance().postMessage(FileLog.LOGGER, AnyCommand.class, "Invalid command length " + parts);
MessagesCentral.getInstance().postMessage(AnyCommand.class, "Invalid command length " + parts);
return; // let's ignore invalid command
}
int rpm = Integer.parseInt(parts[1]);
@ -174,14 +174,14 @@ public class AnyCommand {
new Thread(new Runnable() {
@Override
public void run() {
MessagesCentral.getInstance().postMessage(FileLog.LOGGER, AnyCommand.class, "Will test with RPM " + rpm + ", settle time" + settleTime + "s and duration" + durationTime + "s");
MessagesCentral.getInstance().postMessage(AnyCommand.class, "Will test with RPM " + rpm + ", settle time" + settleTime + "s and duration" + durationTime + "s");
Function<String, Object> callback = new Function<String, Object>() {
@Override
public Object apply(String status) {
if (status == null) {
MessagesCentral.getInstance().postMessage(FileLog.LOGGER, AnyCommand.class, rpm + " worked!");
MessagesCentral.getInstance().postMessage(AnyCommand.class, rpm + " worked!");
} else {
MessagesCentral.getInstance().postMessage(FileLog.LOGGER, AnyCommand.class, rpm + " failed " + status);
MessagesCentral.getInstance().postMessage(AnyCommand.class, rpm + " failed " + status);
}
return null;
}
@ -201,12 +201,12 @@ public class AnyCommand {
private static void handleDecodeRpn(String rawCommand) {
String[] parts = rawCommand.split(" ", 2);
if (parts.length != 2) {
MessagesCentral.getInstance().postMessage(FileLog.LOGGER, AnyCommand.class, "Failed to parse, one argument expected");
MessagesCentral.getInstance().postMessage(AnyCommand.class, "Failed to parse, one argument expected");
return;
}
String argument = unquote(parts[1]);
String humanForm = InfixConverter.getHumanInfixFormOrError(argument);
MessagesCentral.getInstance().postMessage(FileLog.LOGGER, AnyCommand.class, "Human form is \"" + humanForm + "\"");
MessagesCentral.getInstance().postMessage(AnyCommand.class, "Human form is \"" + humanForm + "\"");
}
public static String prepareEvalCommand(String rawCommand) {

View File

@ -1,9 +1,6 @@
package com.rusefi.ui.widgets;
import com.rusefi.FileLog;
import com.rusefi.core.MessagesCentral;
import com.rusefi.core.Sensor;
import com.rusefi.core.SensorCentral;
import com.rusefi.EcuStimulator;
import com.rusefi.io.CommandQueue;
@ -91,7 +88,7 @@ public class PotCommand {
public static int getPotResistance(double vout, double vRef) {
double r = getR1InVoltageDivider3(vout, vRef, EcuStimulator.getInstance().getInputs().getEngineLoadR2Resistance());
MessagesCentral.getInstance().postMessage(FileLog.LOGGER, PotCommand.class, "VRef=" + vRef + ", needed resistance: " + r);
MessagesCentral.getInstance().postMessage(PotCommand.class, "VRef=" + vRef + ", needed resistance: " + r);
// pot command accept resistance and does the conversion itself
return (int) r;
}

View File

@ -1,7 +1,6 @@
package com.rusefi;
import com.opensr5.ConfigurationImage;
import com.opensr5.Logger;
import com.opensr5.ini.field.ScalarIniField;
import com.rusefi.binaryprotocol.BinaryProtocol;
import com.rusefi.config.generated.Fields;
@ -27,8 +26,6 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class FullServerTest {
private final static Logger logger = Logger.CONSOLE;
@Before
public void setTestCertificate() throws MalformedURLException {
ServerTest.commonServerTest();
@ -47,7 +44,7 @@ public class FullServerTest {
UserDetailsResolver userDetailsResolver = authToken -> new UserDetails(authToken.substring(0, 5), userId);
int httpPort = 8103;
int applicationTimeout = 7 * SECOND;
try (Backend backend = new Backend(userDetailsResolver, httpPort, logger, applicationTimeout) {
try (Backend backend = new Backend(userDetailsResolver, httpPort, applicationTimeout) {
@Override
protected void onRegister(ControllerConnectionState controllerConnectionState) {
super.onRegister(controllerConnectionState);
@ -59,7 +56,7 @@ public class FullServerTest {
super.close(applicationConnectionState);
applicationClosed.countDown();
}
}; LinkManager clientManager = new LinkManager(logger)) {
}; LinkManager clientManager = new LinkManager()) {
int serverPortForControllers = 7001;
int serverPortForRemoteUsers = 7003;
@ -71,7 +68,7 @@ public class FullServerTest {
// create virtual controller to which "rusEFI network connector" connects to
int controllerPort = 7002;
ConfigurationImage controllerImage = prepareImage(value, createIniField(Fields.CYLINDERSCOUNT));
TestHelper.createVirtualController(controllerPort, controllerImage, logger);
TestHelper.createVirtualController(controllerPort, controllerImage);
// start "rusEFI network connector" to connect controller with backend since in real life controller has only local serial port it does not have network
@ -84,7 +81,7 @@ public class FullServerTest {
// start authenticator
int authenticatorPort = 7004; // local port on which authenticator accepts connections from Tuner Studio
LocalApplicationProxy.startAndRun(logger, serverPortForRemoteUsers, applicationRequest, authenticatorPort, httpPort, TcpIoStream.DisconnectListener.VOID);
LocalApplicationProxy.startAndRun(serverPortForRemoteUsers, applicationRequest, authenticatorPort, httpPort, TcpIoStream.DisconnectListener.VOID);
CountDownLatch connectionEstablishedCountDownLatch = new CountDownLatch(1);

View File

@ -35,7 +35,7 @@ public class MockRusEfiDevice {
Socket socket = rusEFISSLContext.getSSLSocket(LOCALHOST, serverPort);
BaseBroadcastingThread baseBroadcastingThread = new BaseBroadcastingThread(socket,
sessionDetails,
logger, TcpIoStream.DisconnectListener.VOID) {
TcpIoStream.DisconnectListener.VOID) {
@Override
protected void handleCommand(BinaryProtocolServer.Packet packet, TcpIoStream stream) throws IOException {
super.handleCommand(packet, stream);
@ -43,7 +43,7 @@ public class MockRusEfiDevice {
if (packet.getPacket()[0] == Fields.TS_OUTPUT_COMMAND) {
byte[] response = new byte[1 + Fields.TS_OUTPUT_SIZE];
response[0] = (byte) BinaryProtocolServer.TS_OK.charAt(0);
stream.sendPacket(response, logger);
stream.sendPacket(response);
}
}
};

View File

@ -53,7 +53,7 @@ public class ServerTest {
CountDownLatch allConnected = new CountDownLatch(1);
try (Backend backend = new Backend(createTestUserResolver(), httpPort, logger) {
try (Backend backend = new Backend(createTestUserResolver(), httpPort) {
@Override
public void register(ControllerConnectionState clientConnectionState) {
super.register(clientConnectionState);
@ -143,7 +143,7 @@ covered by FullServerTest
int httpPort = 8001;
int serverPortForRemoteUsers = 6801;
CountDownLatch disconnectedCountDownLatch = new CountDownLatch(1);
try (Backend backend = new Backend(createTestUserResolver(), httpPort, logger) {
try (Backend backend = new Backend(createTestUserResolver(), httpPort) {
@Override
protected void onDisconnectApplication(ApplicationConnectionState applicationConnectionState) {
super.onDisconnectApplication(applicationConnectionState);
@ -155,7 +155,7 @@ covered by FullServerTest
// start authenticator
IoStream authenticatorToProxyStream = TestHelper.secureConnectToLocalhost(serverPortForRemoteUsers, logger);
new HelloCommand(logger, "hello").handle(authenticatorToProxyStream);
new HelloCommand("hello").handle(authenticatorToProxyStream);
assertTrue(disconnectedCountDownLatch.await(30, TimeUnit.SECONDS));
}
@ -174,7 +174,7 @@ covered by FullServerTest
CountDownLatch disconnectedCountDownLatch = new CountDownLatch(1);
try (Backend backend = new Backend(createTestUserResolver(), httpPort, logger) {
try (Backend backend = new Backend(createTestUserResolver(), httpPort) {
@Override
protected void onDisconnectApplication(ApplicationConnectionState applicationConnectionState) {
super.onDisconnectApplication(applicationConnectionState);
@ -189,7 +189,7 @@ covered by FullServerTest
// start authenticator
IoStream authenticatorToProxyStream = TestHelper.secureConnectToLocalhost(serverPortForRemoteUsers, logger);
LocalApplicationProxy localApplicationProxy = new LocalApplicationProxy(logger, applicationRequest);
LocalApplicationProxy localApplicationProxy = new LocalApplicationProxy(applicationRequest);
localApplicationProxy.run(authenticatorToProxyStream);
assertTrue(disconnectedCountDownLatch.await(30, TimeUnit.SECONDS));

View File

@ -41,14 +41,14 @@ public class TestHelper {
}
@NotNull
public static BinaryProtocolServer createVirtualController(ConfigurationImage ci, int port, Listener serverSocketCreationCallback, Logger logger) {
public static BinaryProtocolServer createVirtualController(ConfigurationImage ci, int port, Listener serverSocketCreationCallback) {
BinaryProtocolState state = new BinaryProtocolState();
state.setController(ci);
state.setCurrentOutputs(new byte[1 + Fields.TS_OUTPUT_SIZE]);
LinkManager linkManager = new LinkManager(logger);
LinkManager linkManager = new LinkManager();
linkManager.setConnector(LinkConnector.getDetachedConnector(state));
BinaryProtocolServer server = new BinaryProtocolServer(logger);
BinaryProtocolServer server = new BinaryProtocolServer();
server.start(linkManager, port, serverSocketCreationCallback);
return server;
}
@ -57,7 +57,7 @@ public class TestHelper {
public static IoStream secureConnectToLocalhost(int controllerPort, Logger logger) {
IoStream targetEcuSocket;
try {
targetEcuSocket = new TcpIoStream("[local]", logger, rusEFISSLContext.getSSLSocket(LOCALHOST, controllerPort));
targetEcuSocket = new TcpIoStream("[local]", rusEFISSLContext.getSSLSocket(LOCALHOST, controllerPort));
} catch (IOException e) {
throw new IllegalStateException("Failed to connect to controller " + LOCALHOST + ":" + controllerPort);
}
@ -68,16 +68,16 @@ public class TestHelper {
public static IoStream connectToLocalhost(int controllerPort, Logger logger) {
IoStream targetEcuSocket;
try {
targetEcuSocket = new TcpIoStream("[local]", logger, new Socket(LOCALHOST, controllerPort));
targetEcuSocket = new TcpIoStream("[local]", new Socket(LOCALHOST, controllerPort));
} catch (IOException e) {
throw new IllegalStateException("Failed to connect to controller " + LOCALHOST + ":" + controllerPort);
}
return targetEcuSocket;
}
public static BinaryProtocolServer createVirtualController(int controllerPort, ConfigurationImage controllerImage, Logger logger) throws InterruptedException {
public static BinaryProtocolServer createVirtualController(int controllerPort, ConfigurationImage controllerImage) throws InterruptedException {
CountDownLatch controllerCreated = new CountDownLatch(1);
BinaryProtocolServer server = createVirtualController(controllerImage, controllerPort, parameter -> controllerCreated.countDown(), logger);
BinaryProtocolServer server = createVirtualController(controllerImage, controllerPort, parameter -> controllerCreated.countDown());
assertTrue(controllerCreated.await(READ_IMAGE_TIMEOUT, TimeUnit.MILLISECONDS));
return server;
}

View File

@ -1,11 +1,8 @@
package com.rusefi.io;
import com.opensr5.ConfigurationImage;
import com.rusefi.FileLog;
import com.rusefi.binaryprotocol.BinaryProtocolState;
import com.rusefi.config.generated.Fields;
import com.rusefi.io.LinkConnector;
import com.rusefi.io.LinkManager;
import com.rusefi.io.tcp.BinaryProtocolServer;
class BinaryProtocolServerSandbox {
@ -14,8 +11,8 @@ class BinaryProtocolServerSandbox {
state.setController(new ConfigurationImage(new byte[Fields.TOTAL_CONFIG_SIZE]));
state.setCurrentOutputs(new byte[1 + Fields.TS_OUTPUT_SIZE]);
LinkManager linkManager = new LinkManager(FileLog.LOGGER);
LinkManager linkManager = new LinkManager();
linkManager.setConnector(LinkConnector.getDetachedConnector(state));
new BinaryProtocolServer(FileLog.LOGGER).start(linkManager);
new BinaryProtocolServer().start(linkManager);
}
}

View File

@ -27,7 +27,7 @@ public class TcpCommunicationIntegrationTest {
CountDownLatch failedCountDownLatch = new CountDownLatch(1);
LinkManager clientManager = new LinkManager(LOGGER);
LinkManager clientManager = new LinkManager();
clientManager.startAndConnect(Integer.toString(port), new ConnectionStateListener() {
@Override
public void onConnectionEstablished() {
@ -51,13 +51,13 @@ public class TcpCommunicationIntegrationTest {
ConfigurationImage serverImage = TestHelper.prepareImage(value, iniField);
int port = 6100;
BinaryProtocolServer server = TestHelper.createVirtualController(port, serverImage, LOGGER);
BinaryProtocolServer server = TestHelper.createVirtualController(port, serverImage);
CountDownLatch connectionEstablishedCountDownLatch = new CountDownLatch(1);
// todo: remove CONFIGURATION_RUSEFI_BINARY or nicer API to disable local file load
LinkManager clientManager = new LinkManager(LOGGER);
LinkManager clientManager = new LinkManager();
clientManager.startAndConnect(TestHelper.LOCALHOST + ":" + port, new ConnectionStateListener() {
@Override
public void onConnectionEstablished() {
@ -88,18 +88,18 @@ public class TcpCommunicationIntegrationTest {
int controllerPort = 6102;
// create virtual controller
TestHelper.createVirtualController(controllerPort, serverImage, LOGGER);
TestHelper.createVirtualController(controllerPort, serverImage);
int proxyPort = 6103;
// connect proxy to virtual controller
IoStream targetEcuSocket = TestHelper.connectToLocalhost(controllerPort, LOGGER);
BinaryProtocolProxy.createProxy(LOGGER, targetEcuSocket, proxyPort);
BinaryProtocolProxy.createProxy(targetEcuSocket, proxyPort);
CountDownLatch connectionEstablishedCountDownLatch = new CountDownLatch(1);
// connect to proxy and read virtual controller through it
LinkManager clientManager = new LinkManager(LOGGER);
LinkManager clientManager = new LinkManager();
clientManager.startAndConnect(TestHelper.LOCALHOST + ":" + proxyPort, new ConnectionStateListener() {
@Override
public void onConnectionEstablished() {

View File

@ -1,6 +1,6 @@
package com.rusefi.proxy;
import com.opensr5.Logger;
import com.devexperts.logging.Logging;
import com.rusefi.NamedThreadFactory;
import com.rusefi.binaryprotocol.IncomingDataBuffer;
import com.rusefi.config.generated.Fields;
@ -13,16 +13,18 @@ import com.rusefi.server.SessionDetails;
import java.io.IOException;
import java.net.Socket;
import static com.devexperts.logging.Logging.getLogging;
import static com.rusefi.io.tcp.BinaryProtocolServer.getPacketLength;
import static com.rusefi.io.tcp.BinaryProtocolServer.readPromisedBytes;
public class BaseBroadcastingThread {
private static final Logging log = getLogging(BaseBroadcastingThread.class);
private static final NamedThreadFactory BASE_BROADCASTING_THREAD = new NamedThreadFactory("BaseBroadcastingThread");
private final Thread thread;
@SuppressWarnings("InfiniteLoopStatement")
public BaseBroadcastingThread(Socket socket, SessionDetails sessionDetails, Logger logger, TcpIoStream.DisconnectListener disconnectListener) throws IOException {
TcpIoStream stream = new TcpIoStream("[broadcast] ", logger, socket, disconnectListener);
public BaseBroadcastingThread(Socket socket, SessionDetails sessionDetails, TcpIoStream.DisconnectListener disconnectListener) throws IOException {
TcpIoStream stream = new TcpIoStream("[broadcast] ", socket, disconnectListener);
IncomingDataBuffer in = stream.getDataBuffer();
thread = BASE_BROADCASTING_THREAD.newThread(() -> {
@ -41,14 +43,14 @@ public class BaseBroadcastingThread {
// first TS_HELLO_COMMAND is PROXY request, consecutive TS_HELLO_COMMAND would be real deal from user desktop application
isFirstHello = false;
// respond on hello request with information about session
logger.info("Replying to controller connector@proxy: " + sessionDetails);
new HelloCommand(logger, sessionDetails.toJson()).handle(stream);
log.info("Replying to controller connector@proxy: " + sessionDetails);
new HelloCommand(sessionDetails.toJson()).handle(stream);
} else {
handleCommand(packet, stream);
}
}
} catch (IOException e) {
logger.error("exiting thread " + e);
log.error("exiting thread " + e);
}
});
}

View File

@ -25,7 +25,7 @@ import java.util.concurrent.TimeUnit;
*/
public class NetworkConnector {
public static SessionDetails runNetworkConnector(String authToken, String controllerPort, int serverPortForControllers, TcpIoStream.DisconnectListener disconnectListener) throws InterruptedException, IOException {
LinkManager linkManager = new LinkManager(Logger.CONSOLE)
LinkManager linkManager = new LinkManager()
.setCompositeLogicEnabled(false)
.setNeedPullData(false);
@ -55,8 +55,8 @@ public class NetworkConnector {
@NotNull
private static SessionDetails runNetworkConnector(int serverPortForControllers, LinkManager linkManager, final Logger logger, String authToken, final TcpIoStream.DisconnectListener disconnectListener) throws IOException {
IoStream targetEcuSocket = linkManager.getConnector().getBinaryProtocol().getStream();
HelloCommand.send(targetEcuSocket, logger);
String helloResponse = HelloCommand.getHelloResponse(targetEcuSocket.getDataBuffer(), logger);
HelloCommand.send(targetEcuSocket);
String helloResponse = HelloCommand.getHelloResponse(targetEcuSocket.getDataBuffer());
if (helloResponse == null)
throw new IOException("Error getting hello response");
String controllerSignature = helloResponse.trim();
@ -71,7 +71,7 @@ public class NetworkConnector {
BaseBroadcastingThread baseBroadcastingThread = new BaseBroadcastingThread(rusEFISSLContext.getSSLSocket(HttpUtil.RUSEFI_PROXY_HOSTNAME, serverPortForControllers),
deviceSessionDetails,
logger, disconnectListener) {
disconnectListener) {
@Override
protected void handleCommand(BinaryProtocolServer.Packet packet, TcpIoStream stream) throws IOException {
super.handleCommand(packet, stream);

View File

@ -1,8 +1,7 @@
package com.rusefi.server;
import com.opensr5.Logger;
import com.devexperts.logging.Logging;
import com.rusefi.Listener;
import com.rusefi.Timeouts;
import com.rusefi.binaryprotocol.BinaryProtocol;
import com.rusefi.core.Sensor;
import com.rusefi.io.IoStream;
@ -29,6 +28,7 @@ import java.net.BindException;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
import static com.devexperts.logging.Logging.getLogging;
import static com.rusefi.Timeouts.SECOND;
/**
@ -36,6 +36,8 @@ import static com.rusefi.Timeouts.SECOND;
* @see BackendLauncher
*/
public class Backend implements Closeable {
private static final Logging log = getLogging(Backend.class);
public static final int SERVER_PORT_FOR_CONTROLLERS = 8003;
private static final String MAX_PACKET_GAP = "MAX_PACKET_GAP";
private static final String IS_USED = "isUsed";
@ -62,24 +64,22 @@ public class Backend implements Closeable {
private final int applicationTimeout;
private final UserDetailsResolver userDetailsResolver;
private final Logger logger;
public final static AtomicLong totalSessions = new AtomicLong();
public int serverPortForApplications;
public int serverPortForControllers;
public Backend(UserDetailsResolver userDetailsResolver, int httpPort, Logger logger) {
this(userDetailsResolver, httpPort, logger, 600 * SECOND);
public Backend(UserDetailsResolver userDetailsResolver, int httpPort) {
this(userDetailsResolver, httpPort, 600 * SECOND);
}
public Backend(UserDetailsResolver userDetailsResolver, int httpPort, Logger logger, int applicationTimeout) {
public Backend(UserDetailsResolver userDetailsResolver, int httpPort, int applicationTimeout) {
this.applicationTimeout = applicationTimeout;
this.userDetailsResolver = userDetailsResolver;
this.logger = logger;
new Thread(() -> {
try {
System.out.println("Starting http backend on " + httpPort);
log.info("Starting http backend on " + httpPort);
try {
new FtBasic(
new TkFork(showOnlineControllers,
@ -102,7 +102,7 @@ public class Backend implements Closeable {
} catch (BindException e) {
throw new IllegalStateException("While binding " + httpPort, e);
}
logger.info("Shutting down backend on port " + httpPort);
log.info("Shutting down backend on port " + httpPort);
} catch (IOException e) {
throw new IllegalStateException(e);
}
@ -111,7 +111,7 @@ public class Backend implements Closeable {
new Thread(() -> {
while (true) {
logger.info(getApplicationsCount() + " applications, " + getControllersCount() + " controllers");
log.info(getApplicationsCount() + " applications, " + getControllersCount() + " controllers");
runApplicationConnectionsCleanup();
BinaryProtocol.sleep(applicationTimeout);
}
@ -144,28 +144,28 @@ public class Backend implements Closeable {
this.serverPortForApplications = serverPortForApplications;
// connection from authenticator app which proxies for Tuner Studio
// authenticator pushed hello packet on connect
System.out.println("Starting application connector at " + serverPortForApplications);
BinaryProtocolServer.tcpServerSocket(logger, applicationSocket -> () -> {
logger.info("new application connection!");
log.info("Starting application connector at " + serverPortForApplications);
BinaryProtocolServer.tcpServerSocket(applicationSocket -> () -> {
log.info("new application connection!");
totalSessions.incrementAndGet();
// connection from authenticator app which proxies for Tuner Studio
IoStream applicationClientStream = null;
ApplicationConnectionState applicationConnectionState = null;
try {
applicationClientStream = new TcpIoStream("[app] ", logger, applicationSocket);
applicationClientStream = new TcpIoStream("[app] ", applicationSocket);
// authenticator pushed hello packet on connect
String jsonString = HelloCommand.getHelloResponse(applicationClientStream.getDataBuffer(), logger);
String jsonString = HelloCommand.getHelloResponse(applicationClientStream.getDataBuffer());
if (jsonString == null) {
logger.info("ERROR: null HELLO");
log.error("ERROR: null HELLO");
return;
}
ApplicationRequest applicationRequest = ApplicationRequest.valueOf(jsonString);
logger.info("Application Connected: " + applicationRequest);
log.info("Application Connected: " + applicationRequest);
String authToken = applicationRequest.getSessionDetails().getAuthToken();
UserDetails userDetails = userDetailsResolver.apply(authToken);
if (userDetails == null) {
logger.info("Authentication failed for application " + authToken);
log.info("Authentication failed for application " + authToken);
return;
}
@ -175,7 +175,7 @@ public class Backend implements Closeable {
state = acquire(controllerKey);
}
if (state == null) {
logger.info("No controller for " + controllerKey);
log.info("No controller for " + controllerKey);
return;
}
applicationConnectionState = new ApplicationConnectionState(userDetails, applicationClientStream, state);
@ -183,10 +183,10 @@ public class Backend implements Closeable {
applications.add(applicationConnectionState);
}
BinaryProtocolProxy.runProxy(logger, state.getStream(), applicationClientStream);
BinaryProtocolProxy.runProxy(state.getStream(), applicationClientStream);
} catch (Throwable e) {
logger.info("Application Connector: Got error " + e);
log.info("Application Connector: Got error " + e);
} finally {
if (applicationClientStream != null)
applicationClientStream.close();
@ -222,15 +222,15 @@ public class Backend implements Closeable {
applications.remove(applicationConnectionState);
}
}
logger.info("Disconnecting application");
log.info("Disconnecting application " + applicationConnectionState);
}
public void runControllerConnector(int serverPortForControllers, Listener<?> serverSocketCreationCallback) {
this.serverPortForControllers = serverPortForControllers;
logger.info("Starting controller connector at " + serverPortForControllers);
BinaryProtocolServer.tcpServerSocket(logger, controllerSocket -> () -> {
log.info("Starting controller connector at " + serverPortForControllers);
BinaryProtocolServer.tcpServerSocket(controllerSocket -> () -> {
totalSessions.incrementAndGet();
ControllerConnectionState controllerConnectionState = new ControllerConnectionState(controllerSocket, logger, getUserDetailsResolver());
ControllerConnectionState controllerConnectionState = new ControllerConnectionState(controllerSocket, getUserDetailsResolver());
try {
controllerConnectionState.requestControllerInfo();
@ -305,7 +305,7 @@ public class Backend implements Closeable {
}
for (ApplicationConnectionState inactiveClient : inactiveApplications) {
logger.error("Kicking out application " + inactiveClient);
log.error("Kicking out application " + inactiveClient);
close(inactiveClient);
}
}

View File

@ -1,6 +1,5 @@
package com.rusefi.server;
import com.opensr5.Logger;
import com.rusefi.LocalApplicationProxy;
import com.rusefi.tools.online.HttpUtil;
@ -15,7 +14,7 @@ public class BackendLauncher {
UserDetailsResolver userDetailsFunction = new JsonUserDetailsResolver();
Backend backend = new Backend(userDetailsFunction, HttpUtil.PROXY_JSON_API_HTTP_PORT, Logger.CONSOLE);
Backend backend = new Backend(userDetailsFunction, HttpUtil.PROXY_JSON_API_HTTP_PORT);
backend.runApplicationConnector(LocalApplicationProxy.SERVER_PORT_FOR_APPLICATIONS, parameter -> {
});
backend.runControllerConnector(Backend.SERVER_PORT_FOR_CONTROLLERS, parameter -> {

View File

@ -1,6 +1,6 @@
package com.rusefi.server;
import com.opensr5.Logger;
import com.devexperts.logging.Logging;
import com.rusefi.auth.AutoTokenUtil;
import com.rusefi.binaryprotocol.IncomingDataBuffer;
import com.rusefi.core.SensorsHolder;
@ -14,9 +14,11 @@ import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.net.Socket;
import static com.devexperts.logging.Logging.getLogging;
public class ControllerConnectionState {
private static final Logging log = getLogging(ControllerConnectionState.class);
private final Socket clientSocket;
private final Logger logger;
private final UserDetailsResolver userDetailsResolver;
private boolean isClosed;
@ -35,12 +37,11 @@ public class ControllerConnectionState {
private final TwoKindSemaphore twoKindSemaphore = new TwoKindSemaphore();
private final SensorsHolder sensorsHolder = new SensorsHolder();
public ControllerConnectionState(Socket clientSocket, Logger logger, UserDetailsResolver userDetailsResolver) {
public ControllerConnectionState(Socket clientSocket, UserDetailsResolver userDetailsResolver) {
this.clientSocket = clientSocket;
this.logger = logger;
this.userDetailsResolver = userDetailsResolver;
try {
stream = new TcpIoStream("[controller] ", logger, clientSocket);
stream = new TcpIoStream("[controller] ", clientSocket);
incomingData = stream.getDataBuffer();
} catch (IOException e) {
close();
@ -65,21 +66,21 @@ public class ControllerConnectionState {
}
public void requestControllerInfo() throws IOException {
HelloCommand.send(stream, logger);
String jsonString = HelloCommand.getHelloResponse(incomingData, logger);
HelloCommand.send(stream);
String jsonString = HelloCommand.getHelloResponse(incomingData);
if (jsonString == null)
return;
sessionDetails = SessionDetails.valueOf(jsonString);
if (!AutoTokenUtil.isToken(sessionDetails.getAuthToken()))
throw new IOException("Invalid token in " + jsonString);
logger.info(sessionDetails.getAuthToken() + " New client: " + sessionDetails.getControllerInfo());
log.info(sessionDetails.getAuthToken() + " New client: " + sessionDetails.getControllerInfo());
userDetails = userDetailsResolver.apply(sessionDetails.getAuthToken());
if (userDetails == null) {
throw new IOException("Unable to resolve " + sessionDetails.getAuthToken());
}
controllerKey = new ControllerKey(userDetails.getUserId(), sessionDetails.getControllerInfo());
logger.info("User " + userDetails);
log.info("User " + userDetails);
}
public UserDetails getUserDetails() {
@ -93,9 +94,9 @@ public class ControllerConnectionState {
public void getOutputs() throws IOException {
byte[] commandPacket = GetOutputsCommand.createRequest();
stream.sendPacket(commandPacket, logger);
stream.sendPacket(commandPacket);
byte[] packet = incomingData.getPacket(logger, "msg", true);
byte[] packet = incomingData.getPacket("msg", true);
if (packet == null)
throw new IOException("getOutputs: No response");
sensorsHolder.grabSensorValues(packet);

View File

@ -1,8 +1,6 @@
package com.rusefi.server;
import com.opensr5.Logger;
import com.rusefi.tools.online.HttpUtil;
import org.apache.http.HttpResponse;
import org.jetbrains.annotations.Nullable;
import org.json.simple.JSONObject;
import org.json.simple.parser.ParseException;
@ -15,7 +13,7 @@ public class JsonUserDetailsResolver implements UserDetailsResolver {
public UserDetails apply(String authToken) {
try {
String responseString = HttpUtil.executeGet(Logger.CONSOLE,HttpUtil.RUSEFI_ONLINE_JSON_API_PREFIX + "getUserByToken&rusefi_token=" + authToken);
String responseString = HttpUtil.executeGet(HttpUtil.RUSEFI_ONLINE_JSON_API_PREFIX + "getUserByToken&rusefi_token=" + authToken);
JSONObject json = HttpUtil.getJsonResponse(responseString);
System.out.println("String " + json);
Object getUserByToken = json.get("getUserByToken");

View File

@ -2,7 +2,7 @@
<configuration default="false" name="RemoteTabSandbox" type="Application" factoryName="Application" nameIsGenerated="true">
<option name="MAIN_CLASS_NAME" value="com.rusefi.ts_plugin.RemoteTabSandbox" />
<module name="ts_plugin" />
<option name="VM_PARAMETERS" value="-DRUSEFI_PROXY_URL=localhost" />
<option name="VM_PARAMETERS" value="-DRUSEFI_PROXY_URL=localhost -Dorg.apache.commons.logging.Log=org.apache.commons.logging.impl.SimpleLog -Dorg.apache.commons.logging.simplelog.showdatetime=true -Dorg.apache.commons.logging.simplelog.log.org.apache.http=DEBUG -Dorg.apache.commons.logging.simplelog.log.org.apache.http.wire=ERROR" />
<extension name="coverage">
<pattern>
<option name="PATTERN" value="com.rusefi.ts_plugin.*" />