Send command with ASCII to USB port - java

I need to send a command to the USB device. I tried a lot of examples, but without result. I do not know if the problem is in the structure of a command or send a command.
The structure is as follows \ x1B COMMAND \ n (without spaces Between command and marks).
Thank you for any advice or a better solution
public static void main(String[] args) {
char ESC = (char) 27;
char LN = (char) 10;
String cmd = "command";
String cmdString = ESC + cmd + LN;
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
System.out.println(portList);
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals("/dev/ttyUSB0")) {
try {
serialPort = (SerialPort) portId.open("SimpleWriteApp", 2000);
} catch (PortInUseException e) {
}
try {
outputStream = serialPort.getOutputStream();
} catch (IOException e) {
}
try {
serialPort.setSerialPortParams(57600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {
;
}
try {
outputStream.write(cmdString.getBytes());
outputStream.flush();
} catch (IOException e) {
}
}
}
}
}
}

Problem was solved. I used library JSSC https://github.com/scream3r/java-simple-serial-connector
There is simple source code:
public static void main(String[] args) {
char ESC = (char) 27; // Ascii character for Escape
char LN = (char) 10;
String message = "TX ENROLL:0 PGX:0 PGY:0 ALARM:0 BEEP:NONE";
String cmd = ESC + message + LN;
SerialPort serialPort = new SerialPort("/dev/ttyUSB0");
try {
serialPort.openPort();
serialPort.setParams(SerialPort.BAUDRATE_57600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
serialPort.writeString(cmd);
serialPort.closePort();
} catch (SerialPortException ex) {
System.out.println(ex);
}
}

Related

Reading from Com Port java

I am a beginner java developer. I have a problem with reading from com port. Code:
public class Main {
private static SerialPort serialPort;
public static void main(String[] args) {
serialPort = new SerialPort("COM3");
try {
serialPort.openPort();
Thread.sleep(2000);
serialPort.setParams(SerialPort.BAUDRATE_57600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
serialPort.writeBytes("Test".getBytes());
serialPort.setEventsMask(SerialPort.MASK_RXCHAR);
serialPort.addEventListener(new EventListener());
}
catch (SerialPortException | InterruptedException ex) {
System.out.println(ex);
}
}
private static class EventListener implements SerialPortEventListener {
public void serialEvent(SerialPortEvent event) {
if(event.isRXCHAR() && event.getEventValue() == 8){
try {
byte[] buffer = serialPort.readBytes(8);
for(int i = 0; i < buffer.length; i++){
System.out.println("Output" + buffer[i]);
}
serialPort.closePort();
}
catch (SerialPortException ex) {
System.out.println(ex);
}
}
}
}
Nothing is displayed but I know that the data are written. Help, please.
What is the lib you are using for comm/serial stuff?
You may try add serialPort.addEventListener(new EventListener()); line before you send anything, this is possible that a receive event is sent before listener mapping.

Wait all byte (JSSC)

I'm trying to read a String from my Sara g350 module. I'm using a serial port comunication. The code that I use is this one:
private static SerialPort serialPort;
public static void main(String[] args) {
String[] portNames = SerialPortList.getPortNames();
if (portNames.length == 0) {
System.out.println("There are no serial-ports :( You can use an emulator, such ad VSPE, to create a virtual serial port.");
System.out.println("Press Enter to exit...");
try {
System.in.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return;
}
// OPEN PORT
System.out.println("Available com-ports:");
for (int i = 0; i < portNames.length; i++){
System.out.println(portNames[i]);
}
System.out.println("Type port name, which you want to use, and press Enter...");
Scanner in = new Scanner(System.in);
String portName = in.next();
// writing to port
serialPort = new SerialPort(portName);
try {
// opening port
serialPort.openPort();
serialPort.setParams(SerialPort.BAUDRATE_9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN |
SerialPort.FLOWCONTROL_RTSCTS_OUT);
serialPort.addEventListener(new PortReader(), SerialPort.MASK_RXCHAR);
// writing string to port
serialPort.writeString("AT+CMEE=2");
System.out.println("String wrote to port, waiting for response..");
}
catch (SerialPortException ex) {
System.out.println("Error in writing data to port: " + ex);
}
}
// receiving response from port
private static class PortReader implements SerialPortEventListener {
#Override
public void serialEvent(SerialPortEvent event) {
if(event.isRXCHAR() && event.getEventValue() > 0) {
try {
// получение ответа от порта
String receivedData = serialPort.readString(event.getEventValue());
System.out.println("Received response from port: " + receivedData);
}
catch (SerialPortException ex) {
System.out.println("Error in receiving response from port: " + ex);
}
}
}
}
}
The Problem is that i read only the eco response and not all String.
I send "AT+CMEE=2" and the response could be:
AT+CMEE=2
OK
Can anyone help me? Thank you!

Arduino Uno in Proteus send � character

I'm writing a java program to read data from COM3 port. Data sent by Arduino [1]: https://imgur.com/a/MiNfTZN
But in Java Program (I'm using JSSC) it return � character. If I use RXTX, it return java.io.IOException: Underlying input stream returned zero bytes. I wonder how I can fix it?
This is my code
Using JSSC:
public class SerialTestJSSC {
private static SerialPort serialPort;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String[] portNames = SerialPortList.getPortNames();
if (portNames.length == 0) {
System.out.println("There are no serial-ports :( You can use an emulator, such ad VSPE, to create a virtual serial port.");
System.out.println("Press Enter to exit...");
try {
System.in.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return;
}
// выбор порта
System.out.println("Available com-ports:");
for (int i = 0; i < portNames.length; i++){
System.out.println(portNames[i]);
}
System.out.println("Type port name, which you want to use, and press Enter...");
Scanner in = new Scanner(System.in);
String portName = in.next();
// writing to port
serialPort = new SerialPort(portName);
try {
// opening port
serialPort.openPort();
serialPort.setParams(SerialPort.BAUDRATE_9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN |
SerialPort.FLOWCONTROL_RTSCTS_OUT);
serialPort.addEventListener(new PortReader(), SerialPort.MASK_RXCHAR);
// writing string to port
serialPort.writeString("Hurrah!!!");
System.out.println("String wrote to port, waiting for response..");
}
catch (SerialPortException ex) {
System.out.println("Error in writing data to port: " + ex);
}
}
// receiving response from port
private static class PortReader implements SerialPortEventListener {
#Override
public void serialEvent(SerialPortEvent event) {
if(event.isRXCHAR() && event.getEventValue() > 0) {
try {
// получение ответа от порта
String receivedData = serialPort.readString(event.getEventValue());
System.out.println("Received response from port: " + receivedData);
}
catch (SerialPortException ex) {
System.out.println("Error in receiving response from port: " + ex);
}
}
}
}
Using RXTX
public class SerialTest implements SerialPortEventListener {
SerialPort serialPort;
/** The port we're normally going to use. */
private static final String PORT_NAMES[] = {
"COM3", // Windows
};
/**
* A BufferedReader which will be fed by a InputStreamReader
* converting the bytes into characters
* making the displayed results codepage independent
*/
private static BufferedReader input;
/** The output stream to the port */
private OutputStream output;
/** Milliseconds to block while waiting for port open */
private static final int TIME_OUT = 2000;
/** Default bits per second for COM port. */
private static final int DATA_RATE = 9600;
public void initialize() {
// the next line is for Raspberry Pi and
// gets us into the while loop and was suggested here was suggested http://www.raspberrypi.org/phpBB3/viewtopic.php?f=81&t=32186
//System.setProperty("gnu.io.rxtx.SerialPorts", "/dev/ttyACM0");
CommPortIdentifier portId = null;
Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
//First, Find an instance of serial port as set in PORT_NAMES.
while (portEnum.hasMoreElements()) {
CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
for (String portName : PORT_NAMES) {
if (currPortId.getName().equals(portName)) {
portId = currPortId;
break;
}
}
}
if (portId == null) {
System.out.println("Could not find COM port.");
return;
}
try {
// open serial port, and use class name for the appName.
serialPort = (SerialPort) portId.open(this.getClass().getName(),TIME_OUT);
// set port parameters
serialPort.setSerialPortParams(DATA_RATE,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
// open the streams
input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
output = serialPort.getOutputStream();
// add event listeners
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
} catch (Exception e) {
System.err.println(e.toString());
}
}
/**
* This should be called when you stop using the port.
* This will prevent port locking on platforms like Linux.
*/
public synchronized void close() {
if (serialPort != null) {
serialPort.removeEventListener();
serialPort.close();
}
}
/**
* Handle an event on the serial port. Read the data and print it.
*/
public synchronized void serialEvent(SerialPortEvent oEvent) {
if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
String inputLine=input.readLine();
System.out.println("System "+inputLine);
} catch (Exception e) {
System.err.println(e.toString());
}
}
// Ignore all the other eventTypes, but you should consider the other ones.
}
public static void main(String[] args) throws Exception {
SerialTest main = new SerialTest();
main.initialize();
Thread t=new Thread() {
public void run() {
try {
Thread.sleep(1000000);} catch (InterruptedException ie) {}
}
};
t.start();
System.out.println("Started");
}}

cannot read all response AT Command

what should i do to read all response from AT Command, i have created one method to send AT Command in class SendAtCommand.java but it always give me some blank result, here is my code:
public String sendCommand(String cmd, CommPortIdentifier portX) throws UnsupportedCommOperationException, IOException, PortInUseException {
String result="kosong";
SerialPort port = null;
try {
port = (SerialPort) portX.open("Wavecom", 5000); // Wait max. 10 sec. to acquire port
} catch (PortInUseException e) {
System.err.println("Port already in use: " + e);
System.exit(0);
}
try {
port.setSerialPortParams(
115200,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (Exception e) {
System.out.println(e.toString());
}
BufferedReader is = null;
PrintStream os = null;
try {
is = new BufferedReader(new InputStreamReader(port.getInputStream()));
} catch (IOException e) {
System.err.println("Can't open input stream");
is = null;
}
try {
os = new PrintStream(port.getOutputStream(), true);
} catch (IOException e) {
System.err.println("Can't open output stream");
is = null;
}
os.print(cmd);
os.print("\n\r");
String respon;
try {
Thread.sleep(1000);//asal 3000
} catch (InterruptedException ex) {
Logger.getLogger(ThreadConsloe.class.getName()).log(Level.SEVERE, null, ex);
}
try {
while ((respon = is.readLine())!=null) {
result=is.readLine();
try {
Thread.sleep(1500);//asal 3000
} catch (InterruptedException ex) {
Logger.getLogger(ThreadConsloe.class.getName()).log(Level.SEVERE, null, ex);
}
if(result.contains("\n")){
// result.rep
}
System.out.println("result "+result);
}
} catch (IOException e)
{
System.err.println("Can't recieve input signals");
}
port.close();
return result;
}
and i am try to send AT Command using above method like this :
CommPortIdentifier port = CommPortIdentifier.getPortIdentifier("COM15");
SendAtCommand sendX = new SendAtCommand();
String provMenu= sendX.sendCommand("AT+STGI=0", port);
The result (Hyperterminal output) of AT+STGI=0 sholud look like this :
AT+STGI=0
+STGI: "i-SEV Menu"
+STGI: 1,3,"Isi Ulang",0
+STGI: 2,3,"Transfer",0
+STGI: 3,3,"Optional",0
and the result (java output) using my code is :
result
result +STGI: "i-SEV Menu"
result +STGI: 1,3,"Transfer",0
result
result
I assume reason is that you do readLine twice, but print only once. It should be:
while ((result = is.readLine()) != null) {
try {
(reason changed to result variable)

RXTX Can't receive input signals

Need help,..how to send AT command and reading response using RXTX, previously i am using javax.comm and my code running very well,but i can't receive signal using RXTX,i have read this link http://rxtx.qbang.org/wiki/index.php/Two_way_communcation_with_the_serial_port but i don't know how to use it to send AT command, this is my code :
public class SendAtCommand {
Enumeration portIdentifiers = CommPortIdentifier.getPortIdentifiers();
private int indexNya;
public String sendCommand(String cmd, CommPortIdentifier portX) throws UnsupportedCommOperationException, IOException, PortInUseException {
while (true) {
try {
Thread.sleep(3000);
} catch (InterruptedException ex) {
Logger.getLogger(SendAtCommand.class.getName()).log(Level.SEVERE, null, ex);
}
if (portX == null) {
System.err.println("Could not find serial port ");
System.exit(0);
}
SerialPort port = null;
try {
port = (SerialPort) portX.open("Wavecom", 10000); // Wait max. 10 sec. to acquire port
} catch (PortInUseException e) {
System.err.println("Port already in use: " + e);
System.exit(0);
}
try {
port.setSerialPortParams(
115200,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (Exception e) {
System.out.println(e.toString());
}
BufferedReader is = null;
PrintStream os = null;
try {
is = new BufferedReader(new InputStreamReader(port.getInputStream()));
} catch (IOException e) {
System.err.println("Can't open input stream");
is = null;
}
try {
os = new PrintStream(port.getOutputStream(), true);
} catch (IOException e) {
System.err.println("Can't open output stream");
is = null;
}
os.print(cmd);
os.print("\r\n");
os.flush();
try {
cmd = is.readLine();
cmd=is.readLine();
cmd=is.readLine();
os.flush();
System.out.println(cmd);
} catch (IOException e)
{
System.err.println("Can't recieve input signals");
}
port.close();
return cmd;
}
}
public static void main(String[] args) throws NoSuchPortException, IOException, PortInUseException {
SendAtCommand sendX = new SendAtCommand();
try {
CommPortIdentifier port = CommPortIdentifier.getPortIdentifier("COM16");
String countSms = sendX.sendCommand("AT+CIMI", port);
} catch (UnsupportedCommOperationException ex) {
Logger.getLogger(SendAtCommand.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
and when i printStackTrace() i am getting this error message :
java.io.IOException: Underlying input stream returned zero bytes
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:287)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:325)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:177)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:154)
at java.io.BufferedReader.readLine(BufferedReader.java:317)
at java.io.BufferedReader.readLine(BufferedReader.java:382)
at mobodmt.SendAtCommand.sendCommand(SendAtCommand.java:84)
at mobodmt.SendAtCommand.main(SendAtCommand.java:108)

Categories