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)
Related
I want to transfer objects (AssignmentListener) from one Java Server to 5 Java Clients.
Therefore I wrote a method to send out the message:
private void sendMessage(AssignmentListener listener, int[] subpartitionIndices){
boolean success = false;
int failCount = 0;
// retry for the case of failure
while(!success && failCount < 10) {
try {
// get the stored socket & stream if stored
if(listener.getSocket() == null) {
if (localMode) {
listener.setSocket(new Socket("localhost", listener.getPort()));
} else {
listener.setSocket(new Socket(listener.getIp(), listener.getPort()));
}
listener.setOutputStream(new ObjectOutputStream(listener.getSocket().getOutputStream()));
}
AssignmentListenerMessage assignmentListenerMessage = new AssignmentListenerMessage(subpartitionIndices);
System.out.println("Sending " + assignmentListenerMessage);
listener.getOutputStream().writeObject(assignmentListenerMessage);
listener.getOutputStream().flush();
success = true;
} catch (IOException se) {
se.printStackTrace();
System.err.println("Failed to forward " + Arrays.toString(subpartitionIndices) + " to " + listener);
failCount++;
}
}
}
On the client side, I have the following:
public void run() {
String mode = "remote";
if(localMode) mode = "local";
// we need to register this listener at at the OverpartitioningManager
if(register(isLocalRequest)) System.out.println("Registered AssignmentListenerServer for index "+subpartitionIndex+" at ForwardingServer - "+mode);
running = true;
while (running) {
try {
socket = serverSocket.accept();
// Pass the socket to the RequestHandler thread for processing
RequestHandler requestHandler = new RequestHandler( socket );
requestHandler.start();
} catch (SocketException se) {
se.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class RequestHandler extends Thread {
private Socket socket;
RequestHandler(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
try {
System.out.println("Received a connection");
// Get input and output streams
inStream = new ObjectInputStream(socket.getInputStream());
//outStream = new DataOutputStream(socket.getOutputStream());
AssignmentListenerMessage incomingMessage = null;
while(socket.isBound()) {
try {
incomingMessage = (AssignmentListenerMessage) inStream.readObject();
}catch (StreamCorruptedException sce){
System.out.println("Failed to read AssignmentMessage from Stream, but will try again... (no ack)");
sce.printStackTrace();
continue;
}
// do stuff with the message
}
// Close our connection
inStream.close();
socket.close();
System.out.println("Connection closed");
} catch (Exception e) {
e.printStackTrace();
}
}
}
This works multiple times, but at one point I get the following exception:
java.io.StreamCorruptedException: invalid type code: 00
Does anyone have an idea or any other performance improvement for what I'm doing?
Thanks.
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)
I have written a code for serial communication using RXTX comm.When i write 13000 bytes on port then nothing is written but when i write 115200 or less bytes it works like a charm.One more thing this only happens on some systems.
Update:
Below is my code that write bytes on port:
public String portWriter(byte[] messageString) throws NoSuchPortException {
if (Processing.serialPort == null) {
System.out.println("serial port is null");
Processing.portId = CommPortIdentifier.getPortIdentifier(Processing.portText);
try {
Processing.serialPort = (SerialPort) Processing.portId.open("SimpleWriteApp", 2000);
} catch (PortInUseException e) {
return "Port in use by another application.";
}
try {
Processing.serialPort.setSerialPortParams(Processing.speed,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {
return "Unsupported comm operation.";
}
}
try {
outputStream = Processing.serialPort.getOutputStream();
outputStream.flush();
} catch (IOException e) {
return "Unable to write on port.";
}
try {
//System.out.println("write " + new BigInteger(1, messageString).toString(16));
outputStream.write(messageString);
} catch (IOException e) {
return "Unable to write on port.";
}
return null;
}
I'm trying to execute this command from the application emulator terminal (you can find it in google play) in this app i write su and press enter, so write:
screenrecord --time-limit 10 /sdcard/MyVideo.mp4
and press again enter and start the recording of the screen using the new function of android kitkat.
so, i try to execute the same code from java using this:
Process su = Runtime.getRuntime().exec("su");
Process execute = Runtime.getRuntime().exec("screenrecord --time-limit 10 /sdcard/MyVideo.mp4");
But don't work because the file is not created. obviously i'm running on a rooted device with android kitkat installed. where is the problem? how can i solve? because from terminal emulator works and in Java not?
You should grab the standard input of the su process just launched and write down the command there, otherwise you are running the commands with the current UID.
Try something like this:
try{
Process su = Runtime.getRuntime().exec("su");
DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());
outputStream.writeBytes("screenrecord --time-limit 10 /sdcard/MyVideo.mp4\n");
outputStream.flush();
outputStream.writeBytes("exit\n");
outputStream.flush();
su.waitFor();
}catch(IOException e){
throw new Exception(e);
}catch(InterruptedException e){
throw new Exception(e);
}
A modification of the code by #CarloCannas:
public static void sudo(String...strings) {
try{
Process su = Runtime.getRuntime().exec("su");
DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());
for (String s : strings) {
outputStream.writeBytes(s+"\n");
outputStream.flush();
}
outputStream.writeBytes("exit\n");
outputStream.flush();
try {
su.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
outputStream.close();
}catch(IOException e){
e.printStackTrace();
}
}
(You are welcome to find a better place for outputStream.close())
Usage example:
private static void suMkdirs(String path) {
if (!new File(path).isDirectory()) {
sudo("mkdir -p "+path);
}
}
Update:
To get the result (the output to stdout), use:
public static String sudoForResult(String...strings) {
String res = "";
DataOutputStream outputStream = null;
InputStream response = null;
try{
Process su = Runtime.getRuntime().exec("su");
outputStream = new DataOutputStream(su.getOutputStream());
response = su.getInputStream();
for (String s : strings) {
outputStream.writeBytes(s+"\n");
outputStream.flush();
}
outputStream.writeBytes("exit\n");
outputStream.flush();
try {
su.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
res = readFully(response);
} catch (IOException e){
e.printStackTrace();
} finally {
Closer.closeSilently(outputStream, response);
}
return res;
}
public static String readFully(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length = 0;
while ((length = is.read(buffer)) != -1) {
baos.write(buffer, 0, length);
}
return baos.toString("UTF-8");
}
The utility to silently close a number of Closeables (SoŃket may be no Closeable) is:
public class Closer {
// closeAll()
public static void closeSilently(Object... xs) {
// Note: on Android API levels prior to 19 Socket does not implement Closeable
for (Object x : xs) {
if (x != null) {
try {
Log.d("closing: "+x);
if (x instanceof Closeable) {
((Closeable)x).close();
} else if (x instanceof Socket) {
((Socket)x).close();
} else if (x instanceof DatagramSocket) {
((DatagramSocket)x).close();
} else {
Log.d("cannot close: "+x);
throw new RuntimeException("cannot close "+x);
}
} catch (Throwable e) {
Log.x(e);
}
}
}
}
}
Process p;
StringBuffer output = new StringBuffer();
try {
p = Runtime.getRuntime().exec(params[0]);
BufferedReader reader = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
p.waitFor();
}
}
catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
String response = output.toString();
return response;
Late reply, but it will benefit someone. You can use the sh command in the exec() method.
Here is my example:
try {
File workingDirectory = new File(getApplicationContext().getFilesDir().getPath());
Process shProcess = Runtime.getRuntime().exec("sh", null, workingDirectory);
try{
PrintWriter outputExec = new PrintWriter(new OutputStreamWriter(shProcess.getOutputStream()));
outputExec.println("PATH=$PATH:/data/data/com.bokili.server.nginx/files;export LD_LIBRARY_PATH=/data/data/com.bokili.server.nginx/files;nginx;exit;");
outputExec.flush();
} catch(Exception ignored){ }
shProcess.waitFor();
} catch (IOException ignored) {
} catch (InterruptedException e) {
try{ Thread.currentThread().interrupt(); }catch(Exception ignored){}
} catch (Exception ignored) { }
What have I done with this?
First I call the shell, then I change (set) the necessary environments in it, and finally I start my nginx with it.
This works on unrooted devices too.
Greetings.