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!
Related
we are receiving data from controller using terminal software and as well as also java program ..
but think is that we get proper data on terminal software but java program can not show like terminal .. actually data come in ASCII and we convert to HEX terminal application show proper data but java program can not show terminal data.....
java program data
import java.io.*; // IOException
import java.util.*; // Scanner
import jssc.*;
/**
*
* #author Emiliarge
*/
public class ComPortSendReceive1 {
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());
for (char ch : receivedData.toCharArray()) {
System.out.format("%H ", ch);
} // prints "31 32 2E 30 31 33 "
}
catch (SerialPortException ex) {
System.out.println("Error in receiving response from port: " + ex);
}
}
}
}
}
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");
}}
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);
}
}
I have one client file clientRPC.java and server file serverRPC.java. Both communicate using TCP protocol and use objectinput and output stream to transfer data.
my client file:
public class clientRPC {
public static void main(String args[]) {
Socket s = null;
try {
int serverPort = 8888;
s = new Socket("localhost", serverPort);// server name is local host
//initializing input and output streams object and referencing them to get input and output
ObjectInputStream in = null;
ObjectOutputStream out = null;
out = new ObjectOutputStream(s.getOutputStream());
in = new ObjectInputStream(s.getInputStream());
MathsTutor mt = new MathsTutor();
out.writeObject(mt);
out.flush();
System.out.println("Welcome to Maths Tutor Service. The available maths exercises are:\n"
+ "Addition: Enter 'A' or 'a'\n"
+ "Subtraction: Enter 'S' or 's'\n"
+ "Multiplication: Enter 'M' or 'm'\n"
+ "Division: Enter 'D' or 'd'\n"
+ "Enter 'Q' or 'q' to quit");
//System.out.println();
MathsTutor mt1 = (MathsTutor) in.readObject();
String response = in.readUTF();
System.out.println(response);
} catch (UnknownHostException e) {
System.out.println("Socket:" + e.getMessage());
} catch (EOFException e) {
System.out.println("EOF:" + e.getMessage());
} catch (IOException e) {
System.out.println("readline:" + e.getMessage());
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} finally {
if (s != null) {
try {
s.close();
} catch (IOException e) {
System.out.println("close:" + e.getMessage());
}
}
}
}
}
and my server file :
public class serverRPC extends Thread {
String request;
String response;
public static void main(String args[]) {
try {
int serverPort = 8888;
ServerSocket listen_socket = new ServerSocket(serverPort);
while (true) {
Socket clientSocket = listen_socket.accept();
Connection c = new Connection(clientSocket);
}
} catch (IOException e) {
System.out.println("Listen socket:" + e.getMessage());
}
public serverRPC(String s) {
request = s;
}
}
class Connection extends Thread {
ObjectInputStream in;
ObjectOutputStream out;
Socket clientSocket;
public Connection(Socket aClientSocket) {
try {
clientSocket = aClientSocket;
in = new ObjectInputStream(clientSocket.getInputStream());
out = new ObjectOutputStream(clientSocket.getOutputStream());
this.start();
} catch (IOException e) {
System.out.println("Connection:" + e.getMessage());
}
}
public void run() {
try {
MathsTutor mt = (MathsTutor) in.readObject();
InetAddress ip = clientSocket.getInetAddress();
System.out.println("The Received Message from Client at address:/" + ip.getHostAddress());
System.out.println("====================================");
MathsTutor mt1 = new MathsTutor();
out.writeObject(mt1);
while(true) {
// Read from input
String command = in.readUTF();
System.out.println(command);
}
//System.out.println();
} catch (EOFException e) {
System.out.println("EOF:" + e.getMessage());
} catch (IOException e) {
System.out.println("readline:" + e.getMessage());
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} finally {
try {
clientSocket.close();
} catch (IOException e) {/*close failed*/
}
}
}
}
The problem is when I run server and then client on cmd, the client side displays the welcome msg and puts cursor on another line for user input but, I can't type anything, the cursor just blinks... I know this might be simple but it has taken already 3 hours for me and I'm stuck in the same thing.
The cursor marked with red keeps blinking but doesn't let me type anything.
You're writing an object with writeObject() and trying to read it with readUTF(). Illogical.
objects written with writeObject() must be read with readObject().
strings written with writeUTF() must be read with readUTF().
primitives written with writeXXX() must be read with readXXX(), for most values of X.
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)