I'm trying to make a Java interface to send some AT commands to a GPRS Module.
I already had a working interface on Processing, but I migrated to pure Java because I find it easier to make graphic interfaces.
The Processing program sends data over serial to COM#. COM# is an Arduino with a GPRS Shield. All the Arduino Code does is pass the data received to the GPRS module and viceversa:
void loop(){
if (GPRS.available())
{
while(GPRS.available())
{
buffer[count++]=GPRS.read();
if(count == 64)break;
}
Serial.write(buffer,count);
clearBufferArray();
count = 0;
}
if (Serial.available()){
delay(100);
while(Serial.available()){
GPRS.write(Serial.read());
}
}
}
So I know that works fine because I've tested it using the Processing interface, and an external tool called SSCOM and all the comands are interpreted correctly.
Now the problem is, that when I tried to make the interface on java, using RXTX, it's not working at all. I'm not getting any errors on the console, and the only data I'm receiving on the Arduino is ΓΏ (char 255) each time I run java, and it's being sent when opening the port, not when writing to the serial port.
Here's the SerialHandlerclass I'm using. I found it around the web.
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.UnsupportedCommOperationException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class SerialPortHandler {
private SerialPort serialPort;
private OutputStream outStream;
private InputStream inStream;
public void connect(String portName) throws IOException, PortInUseException, NoSuchPortException {
try {
// Obtain a CommPortIdentifier object for the port you want to open
CommPortIdentifier portId =
CommPortIdentifier.getPortIdentifier(portName);
// Get the port's ownership
serialPort =
(SerialPort) portId.open("Demo application", 5000);
// Set the parameters of the connection.
setSerialPortParameters();
// Open the input and output streams for the connection. If they won't
// open, close the port before throwing an exception.
outStream = serialPort.getOutputStream();
inStream = serialPort.getInputStream();
} catch (NoSuchPortException e) {
throw new IOException(e.getMessage());
} catch (PortInUseException e) {
throw new IOException(e.getMessage());
} catch (IOException e) {
serialPort.close();
throw e;
}
}
/**
* Get the serial port input stream
* #return The serial port input stream
*/
public InputStream getSerialInputStream() {
return inStream;
}
/**
* Get the serial port output stream
* #return The serial port output stream
*/
public OutputStream getSerialOutputStream() {
return outStream;
}
/**
* Sets the serial port parameters
*/
private void setSerialPortParameters() throws IOException {
int baudRate = 19200;
try {
serialPort.setSerialPortParams(
baudRate,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
serialPort.setFlowControlMode(
SerialPort.FLOWCONTROL_NONE);
} catch (UnsupportedCommOperationException ex) {
throw new IOException("Unsupported serial port parameter");
}
}
}
And here's my main class:
public class Main {
SerialPortHandler serial = new SerialPortHandler();
serial.connect("COM3");
OutputStream serialOut = serial.getSerialOutputStream();
String s = "AT+CPOWD=0\r\n";
serialOut.write(s.getBytes());
serialOut.flush();
}
}
rxtxSerial.dll and RXTXcomm.jar are in jre\bin and jre\lib\ext respectively.
I can't find the problem, like I said, I don't get any errors or warnings anywhere.
I'm using NetBeans 7.3.1, JDK 1.7 and Windows 8.1 x64.
I also tried using jSSC but I get the same results.
I solved the problem. It wasn't the jSSC or RXTX library.
PeterMmm was right, I needed a delay, but I needed it on my java program.
When I was testing communication, I was opening the port and sending data right away. The problem is Arduino by default resets when a connection is established, so the Arduino wasn't ready to process it.
A couple days ago, I decided to try again, with jSSC, but this time, the java program asked for an input to send through the serial port, leaving time for Arduino to boot. Arduino successfully received anything I typed.
Now that I implemented serial communication on the user interface I was developing, everything runs smoothly.
Related
I need some help on how EventListeners work in java. I'll be honest, the only Listener I know how to use is ActionListeners so forgive me for not knowing how. To start with, I would like to put on some reference.
Im working on an RFID Scanner Desktop App on java and EPOCH gave me this:
JSSC
The JSSC was able to provide me with the tools that I need to read my RFID but this time, I'm having issued on Implementing it on my application.
Here is my current Code:
First, Imports
import jssc.SerialPort;
import jssc.SerialPortEvent;
import jssc.SerialPortEventListener;
import jssc.SerialPortException;
Now for the class:
class SerialPortReader implements SerialPortEventListener {
SerialPort serialPort;
#Override
public void serialEvent(SerialPortEvent event) {
if(event.isRXCHAR()){//If data is available
if(event.getEventValue() == 10){//Check bytes count in the input buffer
//Read data, if 10 bytes available
try {
byte buffer[] = serialPort.readBytes(10);
}
catch (SerialPortException ex) {
System.out.println(ex);
}
}
}else if(event.isCTS()){//If CTS line has changed state
if(event.getEventValue() == 1){//If line is ON
System.out.println("CTS - ON");
}
else {
System.out.println("CTS - OFF");
}
}else if(event.isDSR()){///If DSR line has changed state
if(event.getEventValue() == 1){//If line is ON
System.out.println("DSR - ON");
}else {
System.out.println("DSR - OFF");
}
}
}
}
public class TestRF extends javax.swing.JFrame implements SerialPortEventListener{
SerialPort serialPort;
public TestRF() {
initComponents();
setSerialPort();
}
public void setSerialPort(){
SerialPort serialPort = new SerialPort("COM7");
try {
serialPort.openPort();//Open serial port
serialPort.setParams(9600, 8, 1, 0);//Set params.
byte[] buffer = serialPort.readBytes(10);//Read 10 bytes from serial port
//serialPort.closePort();//Close serial port
serialPort.addEventListener(this);//Add SerialPortEventListener
}
catch (SerialPortException ex) {
System.out.println(ex);
}
}
and lastly, the abstract method.. (I dont know what this does to be honest and im picking up books right now.)
#Override
public void serialEvent(SerialPortEvent spe) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
to put things simple. I need to get my RFID to read and pass that value anywhere in my project. I even thought of trying to extend my JFrame classes to a class file but so far, no luck.
tutorials anyone?
You can create 2 threads. 1st thread read data from serial port (RFID) while 2nd thread handles task specific to application. Also consider using serial communication manager library for serial port communication in java.
Please share RFID hardware details so that we can think best application design to use it.
I am trying to setup a client-server system with the Pi acting as the server, and the Android device being the client. Every time I run the code (I cobbled together from the internet) the client throws an IOException:
Connection timed out: connect
I just discovered that when I try to ping the Pi's IP it is unreachable.
How can I fix this?
Note I am currently testing Java code on a Windows PC until I get it working.
Client Code (Java):
import java.io.*;
import java.net.*;
public class client
{
static Socket clientSocket;
static String homeIp="192.168.0.105"; //internal ip of server (aka Pi in this case)
static int port=4242;
public static void main(String [] args)
{
sendToPi("I sent a message");
}
public static void sendToPi(String s)
{
//wordsList.append("in sendToPi()\n");
System.out.println("in sendToPi()");
//Log.e("aaa","in sendToPi()\n");
try {
clientSocket = new Socket(homeIp, port);
PrintStream out = new PrintStream(clientSocket.getOutputStream());
out.println(s);
} catch (UnknownHostException e) {
//Log.e("aaa","Don't know about host: "+homeIp+"."+e.getMessage());
System.out.println("Don't know about host: "+homeIp+"."+e.getMessage());
//System.exit(1);
} catch (IOException e) {
//Log.e("aaa","Couldn't get I/O for the connection to: "+homeIp+"."+e.getMessage());
System.out.println("Couldn't get I/O for the connection to: "+homeIp+"."+e.getMessage());
//System.exit(1);
}
}
}
Server Code (C): I used code from here exactly as written. compiled as server. Started with ./server 4242
In my case the solution was to explicitly forward the client port in my router.
I am trying to connect with a Biometric Fingerprint Attendance Device using a Java program. The device I am using is a Biocom Fingerprint attendance system. However, I am search and reading about that and I see the SDK could used which based on device type (which hard, not logical, moreover, it is not global solution!)
I research for a global standard on how to connect, send and retrieve data with a Fingerprint Device which again I wasn't lucky enough to find a clear solution. Currently, I tried to connect with the device by creating a Socket object (through Ethernet port) but also not executed with me. This open infinite loop problems on my head.
Is there any general, standard way to connect, send and retrieve data from such device using Java?
Can a Socket be considered as a solution for such problem?
If yes, what is wrong in my code below? What additional things more than the host IP and port number are needed to connect with the device?
The Socket code that used:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class Requester {
Socket requestSocket;
ObjectOutputStream out;
ObjectInputStream in;
String message;
Requester() {
}
void run() throws IOException {
try {
// 1. creating a socket to connect to the server
requestSocket = new Socket("192.168.0.19", 4370);
System.out.println("Connected to given host in port 4370");
// 2. get Input and Output streams
in = new ObjectInputStream(requestSocket.getInputStream());
// 3: Communicating with the server
String line;
while (true) {
line = in.readLine();
if (line != null) {
System.out.println(line);
}
}
} catch (UnknownHostException unknownHost) {
System.err.println("You are trying to connect to an unknown host!");
} catch (IOException ioException) {
ioException.printStackTrace();
} catch (Exception Exception) {
Exception.printStackTrace();
} finally {
in.close();
requestSocket.close();
}
}
void sendMessage(String msg) {
try {
out.writeObject(msg);
out.flush();
System.out.println("client: " + msg);
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
public static void main(String args[]) throws IOException {
Requester client = new Requester();
client.run();
}
}
This image may give more details:
You don't need the ObjectInputStream. Just use the InputStream you get from requestSocket.getInputStream().
Alternatively use a terminal programm like putty to connect to your device. This requires no coding.
Biocom Biometrics are ZKTeco devices. ZkTeco devices are launched only with windows SDK. You can download the SDK from https://www.zkteco.com/en/download_catgory.html and use the DLL in java which can run only on Windows platorm. For HTTP communication, to work in any platform through any language, refer http://camsunit.com/application/zk-teco-essl-api-integration.html
I am working on a project that involves an embedded device. I am expected to send a command to this device. This command is a string: "LAMP1_ON\r\n";
I am using RXTX with java and sending the data via serial port. But when i send the String command, the device receives "AMP_N" and some other scattered string.
I have no idea why it is so, and how i can fix it.
My code is below:
public class SerialWriter implements Runnable {
OutputStream out;
String str;
public SerialWriter(OutputStream out, String str) {
this.out = out;
this.str = str;
}
public void run() {
try {
byte[] array = this.str.getBytes();
this.out.write(array);
this.out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I expect to send the string to the port via the write method. It works but it doesn't send the exact String that is contained in this.str instead it sends "AMP_N" and "AMP" and scattered Strings
I have seen the problem. I didn't set the FLOWCONTROL property correctly. Thank you. This code works fine
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
I am using an Arduino Uno. I am experiencing weird behavior with Serial.readbytes(). The Arduino is powered and communicating via USB on COM4. I am running Eclipse on 64-bit Windows 7.
My current Arduino code looks like the following; the delays are so I can start and stop my Java service and look at the serial window in the Arduino IDE, inputBuffer is a character array.
char inputBuffer[10]; // For incoming serial data
void setup() {
Serial.begin(9600); // Opens serial port, sets data rate to 9600 bit/s.
}
void GetTemp(){
int temp = 123;
Serial.print(temp);
}
void loop() {
if (Serial.available() > 0) {
Serial.readBytes(inputBuffer, Serial.available());
delay(5000);
Serial.print("I got this ->");
Serial.print(inputBuffer);
Serial.println("<-");
}
delay(5000);
Serial.println("delay");
Serial.println(inputBuffer[0], DEC);
}
Here is the code for my Java side. I modified it from Two way communcation with the serial port. This just sends one byte array upon start.
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import java.io.IOException;
import java.io.OutputStream;
public class TwoWaySerialComm
{
public TwoWaySerialComm()
{
super();
}
void connect ( String portName ) throws Exception
{
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
if ( portIdentifier.isCurrentlyOwned() )
{
System.out.println("Error: Port is currently in use");
}
else
{
CommPort commPort = portIdentifier.open(this.getClass().getName(),2000);
if ( commPort instanceof SerialPort )
{
SerialPort serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
OutputStream out = serialPort.getOutputStream();
(new Thread(new SerialWriter(out))).start();
}
else
{
System.out.println("Error: Only serial ports are handled by this example.");
}
}
}
public static class SerialWriter implements Runnable
{
OutputStream out1;
public SerialWriter ( OutputStream out )
{
this.out1 = out;
}
public void run ()
{
try
{
byte[] test = ("H567").getBytes();//testing string to send
this.out1.write(test);
}
catch ( IOException e )
{
e.printStackTrace();
}
}
}
public static void main ( String[] args )
{
try
{
(new TwoWaySerialComm()).connect("COM4");
}
catch ( Exception e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
When I run it, my Arduino just prints out a blank line. If I prepare the Arduino with "hiya" using the Serial window first, then when the java is executed, it will return back to a blank line.
Since the char array is just over-written each time I sent "H567\r\n" and then in the Serial window typed sent "hiya" where the extra newline was still being executed, so I know characters are being stored somehow.
Another test was to change the last Serial.prinln() to Serial.println(inputBuffer[0], DEC). Using the Serial Window, results are as expected, but from Java it just prints out "0". Serial communication works wonderful coming from the Arduino talking to the Java code, just not from Java code to the Arduino. How can I fix this problem?
Per suggestion, I tried reading Serial.available() instead of a fixed max of 10. No changes were experienced.
I found a solution, but I am unsure of the reason. When starting the Serial writing thread, I must call thread.sleep(2000) upon start for the Arduino to read characters correctly.
Try adding out1.flush() after out1.write().