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;
}
Related
I'm trying to connect to my FTP server in Java SE 1.8. To do so I use this method :
private void connectFTP() {
String server = "ftp.XXXXXXXXXX.site";
int port = 21;
String user = "XXXX";
String pass = "XXXX";
if(!ftpConnexionSuccess.get())
{
client = new FTPClient();
client.configure(new FTPClientConfig(FTPClientConfig.SYST_UNIX));
try {
client.connect(server, port);
ftpConnexionSuccess.set(client.login(user, pass));
if (!ftpConnexionSuccess.get()) {
System.out.println("Could not login to the server");
return;
}
else
{
System.out.println("LOGGED IN SERVER");
client.changeWorkingDirectory("/crypto");
listenedFile = getListenedFile();
System.out.println(listenedFile.getName());
if(listenedFile != null)
{
baseFileTimeStamp.set(listenedFile.getTimestamp().getTimeInMillis());
}
System.out.println(baseFileTimeStamp);
}
} catch (Exception ex) {
System.err.println("FTP connection error : Sleeping for 5 seconds before trying again (" + ex.getMessage() + ")");
ex.printStackTrace();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {e.printStackTrace();}
try {
client.disconnect();
} catch (IOException e) {e.printStackTrace();}
connectFTP();
}
}
}
It works great when I'm on Eclipse and when I export the app on my Windows 10.
Nonetheless, when I try to launch the app on my AWS Webmachine I get a null pointer exception at "listenedFile". The method to listen to this file is the one below.
private FTPFile getListenedFile() {
FTPFile returnedFile = null;
try {
for(FTPFile file : client.listFiles())
{
if(file.getName().contains("filetolisten.txt"))
returnedFile = file;
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
try {
client.disconnect();
} catch (IOException e1) {e1.printStackTrace();}
connectFTP();
return getListenedFile();
}
return returnedFile;
}
I thought it was because of the line
client.configure(new FTPClientConfig(FTPClientConfig.SYST_UNIX));
I tried to delete the line, and to replace SYST_UNIX with SYST_NT, but nothing worked.
I tried to delete the line, and to replace SYST_UNIX with SYST_NT, but nothing worked. Also updated Java, updated the common-nets library. Nothing worked
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)
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)
import javax.comm.*;
import java.io.*;
import java.util.*;
public class Sms {
public synchronized static String main1(String arr) {
char cntrlZ=(char)26;
InputStream input = null;
OutputStream output = null;
SerialPort serialPort = null;
try {
CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier("COM3");
serialPort = (SerialPort) portId.open("SimpleReadApp1", 2000);
//System.out.println("sdiosdfdsf");
String f=null;int n;
input = serialPort.getInputStream();
output = serialPort.getOutputStream();
Thread readThread;
serialPort.notifyOnDataAvailable(true);
try {
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {}
output.write(("ATZ\r\natH\r\n+CMGW: 0\r\n+CMGW: 1\r\n").getBytes());
output.flush();Thread.sleep(200);
output.write(("ath0\r\n").getBytes());
output.flush();Thread.sleep(200);
output.write(("AT+CMGF=1\r\n").getBytes());
output.flush();Thread.sleep(200);
output.write(("AT+CMGS=\"09629993650\"\r\n+CMGW: 20\r\n").getBytes());
output.write(("hellooopssss445 545inoo you there?").getBytes());
output.write(("\032").getBytes());
output.flush();
Thread.sleep(2000);
byte[] readBuffer = new byte[120];
try {
while (input.available() > 0) {
int numBytes = input.read(readBuffer);
}
input.close();
output.close();
serialPort.removeEventListener();
serialPort.sendBreak(1000);
serialPort.getInputStream().close();
serialPort.getOutputStream().close();
if (serialPort!=null)
System.out.print("Port is not null!!!");
//serialPort.closeport();
if (serialPort!=null)
System.out.print("Port is not null!!!");
System.out.print(new String(readBuffer));
return(new String(readBuffer));
} catch (IOException e) {}
output.flush();
} catch (NoSuchPortException e) {
System.out.println("Exception in Adding Listener" + e);
} catch (PortInUseException e) {
System.out.println("Exception in Adding Listener" + e);
} catch (IOException e) {
System.out.println("Exception in Adding Listener" + e);
}
catch (InterruptedException e) {
System.out.println("Exception in Adding Listener" + e);
}
return ("fault");
}
public static void main(String[] arg) {
char ii[]=main1("").toCharArray();
for(int j=0;j<ii.length;j++)
{
if((ii[j]=='O')&&(ii[j+1]=='K'))
System.out.println("GOT");
}
}
}
When I compile and execute this program, message is not sent until I remove my Mobile from USB.And if I don't remove my Mobile and run the same program, Its shows Busy and CMI ERROR : 503.
And second message is never sent (when program is compiled again).Moreover Port is never closed as you can see in the program.
What can be done in this code? Please don't provide me some other program like SMSLIB rather improve/edit this code.
I'm trying this for about 3 days , still negative results.
Please help me.I want to send Bulk SMS without disconnecting the mobile again and again.
You must never use sleep like that; you must read and parse the response given by the modem. Sleeping like that is only marginally better then not waiting at all (which I address in this answer). See this answer for how to read and parse the response you get back.
BTW, an AT command should be terminated with only \r and not \r\n (unless you have changed S3, and you should not do that), see V.250 for more details on that and AT commands in general (e.g. if you have not already read that specification it is highly recommended).
I'm conducting an experiment to see how long it takes the TCP in java. First I start the server. Then call the function client_tcp many times, more than 50000 times. And measure the time it takes to connect, and send and receive 1 byte. When the server get more than 16384 requests (sometimes varies), the client can't connect to the server.
I don't know if it is because of the receive buffer size in the server socket. In my case, ss.getReceiveBufferSize() = 131072.
Here is the code:
public synchronized void server_tcp(int port) {
ServerSocket ss;
Socket so;
InputStream is;
OutputStream os;
try {
ss = new ServerSocket(port);
} catch (Exception e) {
System.out.println("Unable to connect to port " + port +
" TCP socket.");
return;
}
while (true) {
try {
so = ss.accept();
is = so.getInputStream();
os = so.getOutputStream();
int ch = is.read();
os.write(65);
so.close();
} catch (IOException e) {
System.out.println("Something went wrong.");
} catch (InterruptedException e) {
System.out.println("Bye.");
}
}
}
public void client_tcp(String host, int port) {
Socket so = null;
InputStream is = null;
OutputStream os = null;
try {
so = new Socket(host, port);
} catch (UnknownHostException e) {
System.err.println("Error Host not found.");
return;
} catch (IOException e) {
Syste.err.println("Error Creating socket.");
return;
}
try {
os = so.getOutputStream();
is = so.getInputStream();
os.write(65);
is.read();
os.close();
is.close();
so.close();
} catch (IOException e) {
System.err.println("Error.");
return;
}
}
What's wrong?
Thank you.
You are creating a massive number of sockets almost at once and the OS is not having time enough to release them. You could add a tiny delay (to be experimentally tuned) to the loop that invokes the client_tcp() method.
for(int i=0; i<50000; i++) {
new SocketReuse().client_tcp("127.0.0.1", 4444);
Thread.sleep(2); // 2 milliseconds delay
}