Created
October 7, 2019 21:45
-
-
Save alekseichuk/e5733f4b0a632f895b0c6f3efa9250af to your computer and use it in GitHub Desktop.
RxTx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.BufferedReader; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.io.InputStreamReader; | |
import java.io.OutputStream; | |
import java.io.PrintWriter; | |
import java.util.Enumeration; | |
import java.util.TooManyListenersException; | |
import gnu.io.CommPortIdentifier; | |
import gnu.io.PortInUseException; | |
import gnu.io.UnsupportedCommOperationException; | |
import purejavacomm.SerialPort; | |
public class RxTxComPortCommunicator { | |
private static final int PORT_TIMEOUT = 2000; | |
private static final int BAUD_RATE = 9600; | |
private static BufferedReader mInputReader; | |
private static PrintWriter mOutputWriter; | |
public static void main(String[] args) throws PortInUseException, IOException, InterruptedException, UnsupportedCommOperationException, TooManyListenersException { | |
System.out.println("Program started"); | |
CommPortIdentifier serialPortId; | |
Enumeration enumComm = CommPortIdentifier.getPortIdentifiers(); | |
while (enumComm.hasMoreElements()) { | |
serialPortId = (CommPortIdentifier) enumComm.nextElement(); | |
if (serialPortId.getPortType() == CommPortIdentifier.PORT_SERIAL) { | |
gnu.io.SerialPort comPort = (gnu.io.SerialPort) serialPortId.open("USBCommunicator", PORT_TIMEOUT); | |
InputStream inputStream = comPort.getInputStream(); | |
OutputStream outputStream = comPort.getOutputStream(); | |
mInputReader = new BufferedReader(new InputStreamReader(inputStream)); | |
mOutputWriter = new PrintWriter(outputStream); | |
Thread.sleep(1000); | |
comPort.setSerialPortParams(BAUD_RATE, | |
SerialPort.DATABITS_8, | |
SerialPort.STOPBITS_1, | |
SerialPort.PARITY_NONE); | |
comPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE); | |
comPort.notifyOnDataAvailable(true); | |
comPort.addEventListener(System.out::println); | |
Thread.sleep(1000); | |
mOutputWriter.println("REQINFO,4"); | |
Thread.sleep(1000L); | |
System.out.println(mInputReader.readLine()); // Execution stops here forever | |
System.out.println(serialPortId.getName()); | |
} | |
} | |
Thread.sleep(60L * 1000L); | |
System.out.println("Finished successfully"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment