Hi i'm begginer in java,in my project datalogger is connected to com port i have to send 15 integer value to port then other device will send back 15 as a response,now i'm writing to outputstream but i'm not getting response.how to solve this problem plz help me.(i'm using javax.com package)
thanks for reply
You have to get an InputStream as well, you can't read from the OutputStream. Or am I missing something?
Also, remember to do OutputStream.flush() after writing your output, otherwise your data might be buffered to be sent later - if the responder is waiting for your data, this is most likely where things goes wrong.
Having said that: the javax.comm package is really old. Last time I worked with it, it almost seemed deprecated by Sun, or at least not maintained in any way. You might want to look at other solutions (SerialIO comes to mind).
Try following sample code
public static void init(String port) {
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL){
System.out.println(portId.getName());
if (portId.getName().equals(port)) {
try {sPort = (SerialPort) portId.open("PORT_NAME", 2000);
reader = new sms();
break;
}
catch (Exception e) { System.out.println(e);continue;}
}
}
}
and call init() method with com port name (like COM15,COM11,COM12 etc..) check your device com port to which it is connected.
Related
I would like to write a GUI in Java, in which there will be a button. Pressing the button will illuminate the diode connected to the Arduino. I'm using the RXTXcomm.jar library.
For now, I wrote code that displays the COM21 port because that's how my Arduino is connected to and opens it. Here's the code:
private String name;
private String portName;
private CommPortIdentifier portIdentifier = null;
private boolean staPort;
private void getPorts () throws PortInUseException {
List <String> list = new ArrayList ();
CommPortIdentifier serialPortId;
Enumeration enumComm;
enumComm = CommPortIdentifier.getPortIdentifiers ();
while (enumComm.hasMoreElements ()) {
serialPortId = (CommPortIdentifier) enumComm.nextElement ();
name = serialPortId.getName ();
if ("COM21" .equals (name)) {
if (serialPortId.isCurrentlyOwned ()) {
System.out.println ("Port is open");
} Else {
serialPortId.open (name, WIDTH);
}
} else {
System.out.println ("error");
}
}
}
I would like to ask how to now ignite a diode connected to eg pin1? What method to use? I use an Arduino Mega. I found a few posts on this subject, unfortunately no specific answer matching my problem. I will be grateful for any help, materials or links.
Understand that you'll need two programs to do this. The first is similar to your Java program. But the second is the program that runs on the Arduino itself.
Here is a link that should give you an idea. The code is repeated below in case the link goes stale:
int led = 13; // Pin 13
void setup()
{
pinMode(led, OUTPUT); // Set pin 13 as digital out
// Start up serial connection
Serial.begin(9600); // baud rate
Serial.flush();
}
void loop()
{
String input = "";
// Read any serial input
while (Serial.available() > 0)
{
input += (char) Serial.read(); // Read in one char at a time
delay(5); // Delay for 5 ms so the next char has time to be received
}
if (input == "on")
{
digitalWrite(led, HIGH); // on
}
else if (input == "off")
{
digitalWrite(led, LOW); // off
}
}
This is the C code that needs to run on the Arduino. In this case, as you can see, it is using pin 13. You'll need to get an Arduino development environment setup to get this part working. See the Arduino Software page for information on how to setup the Arduino IDE. That will be different from your Netbeans IDE but the concepts are similar.
After you've got your sketch uploaded to your Arduino you'll connect to it at 9600 baud as shown in the Arduino code. Your Java code isn't setting communication parameters like baud rate so you'll need to update it for that. I found several links for setting the serial communication parameters in RXTX so take a look around.
Good luck - it seems like alot at first but it's really not too bad.
My work is developing software for network capable cameras for retail enviroments. One of the peices of software my team is developing is a webserver that retrieves various reports generated in HTML by the camera itself (which has its own embedded webserver) and stored on the camera. Our software will then GET these reports from the camera and store it on a central webserver.
While we are fine plugging in the IPs of the cameras into our software, I am developing a simple Java class that will query the network and locate all cameras on the network.
The problem though is that while it runs just fine on my PC, and my coworker's PC, when we attempt to run it on the actual webserver PC that will host our software... it runs, but says every IP in the subnet is offline / unreachable EXCEPT for the gateway IP.
For example, if I run it from my PC or my coworkers PC when plugged into the closed LAN, I get the following active IPs found along with a flag telling me if its a camera or not.
(gateway is 192.168.0.1, subnet mask is 255.255.255.0, which means full range of 256 devices to be looked for)
IP:/192.168.0.1 Active:true Camera:false
IP:/192.168.0.100 Active:true Camera:true <- this is camera 1
IP:/192.168.0.101 Active:true Camera:true <- this is camera 2
IP:/192.168.0.103 Active:true Camera:false <- my PC
IP:/192.168.0.104 Active:true Camera:false <- this is our webserver
But for some reason, when running the same program from the webserver PC, using the same JRE, I only get the following found
IP:/192.168.0.1 Active:true Camera:false
Now my code, instead of enumerating through each IP in order on the main Thread, instead creates a seperate Thread for each IP to be checked and runs them concurrently (else it would take little over 21 minutes to enumerate through the entire IP range at a timeout of 5000ms / IP). The main Thread then re-runs these IP scan threads every 15 seconds over and over.
I have checked that all the threads are running to completion on all the PCs, no exceptions are being thrown. Even verified that none of the threads are getting stuck. Each Thread takes about 5001 to 5050ms from start to complete, and those Threads that have an active IP finish sooner (>5000ms), so I know that its correctly waiting the full 5000ms in the ipAddr.isReachable(5000) method.
Me and my coworker are stumped at this point while it seems to reach those active IPs fine when run on our PCs, yet getting no response from the webserver PC???
We have ruled out firewall issues, admin access issues, etc.. The only difference is that our webserver is Embedded Win XP, and our PCs are Windows 7.
This has us stumped. Any ideas why?
Below is the code that is running each IP Thread:
public void CheckIP() {
new Thread() {
#Override
public void run() {
try {
isActive = ipAddr.isReachable(5000);
if (isActive) {
if (!isCamera) {
isCamera = new IpHttpManager().GetResponse(ipAddr.toString());
}
} else {
isCamera = false;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
EDIT: Here is the code that builds each IP to check after determining the range based on gateway and subnet...
for(int i=subMin; i<=subMax; i++) {
byte[] ip = new byte[] {(byte)oct[0],(byte)oct[1],(byte)oct[2],(byte)i};
try {
scanners[subCount] = new IpScan(InetAddress.getByAddress(ip));
subCount++;
} catch (UnknownHostException e) {
e.printStackTrace();
}}
Thanks everyone, but I never did figure out or pinpoint why this oddity was happening. Everything I checked for was not the cause, so this question can be closed.
In any case, I ended up working around it completely. Instead of using InetAddress, I just went native and built my own ICMP ping class instead, via JNA, invoking Windows libraries IPHLPAPI.DLL and WSOCK32.DLL. Here is what I used...
public interface InetAddr extends StdCallLibrary {
InetAddr INSTANCE = (InetAddr)
Native.loadLibrary("wsock32.dll", InetAddr.class);
ULONG inet_addr(String cp); //in_addr creator. Creates the in_addr C struct used below
}
public interface IcmpEcho extends StdCallLibrary {
IcmpEcho INSTANCE = (IcmpEcho)
Native.loadLibrary("iphlpapi.dll", IcmpEcho.class);
int IcmpSendEcho(
HANDLE IcmpHandle, //Handle to the ICMP
ULONG DestinationAddress, //Destination address, in the form of an in_addr C Struct defaulted to ULONG
Pointer RequestData, //Pointer to the buffer where my Message to be sent is
short RequestSize, //size of the above buffer. sizeof(Message)
byte[] RequestOptions, //OPTIONAL!! Can set this to NULL
Pointer ReplyBuffer, //Pointer to the buffer where the replied echo is written to
int ReplySize, //size of the above buffer. Normally its set to the sizeof(ICMP_ECHO_REPLY), but arbitrarily set it to 256 bytes
int Timeout); //time, as int, for timeout
HANDLE IcmpCreateFile(); //win32 ICMP Handle creator
boolean IcmpCloseHandle(HANDLE IcmpHandle); //win32 ICMP Handle destroyer
}
And then using those to create the following method...
public void SendReply(String ipAddress) {
final IcmpEcho icmpecho = IcmpEcho.INSTANCE;
final InetAddr inetAddr = InetAddr.INSTANCE;
HANDLE icmpHandle = icmpecho.IcmpCreateFile();
byte[] message = new String("thisIsMyMessage!".toCharArray()).getBytes();
Memory messageData = new Memory(32); //In C/C++ this would be: void *messageData = (void*) malloc(message.length);
messageData.write(0, message, 0, message.length); //but ignored the length and set it to 32 bytes instead for now
Pointer requestData = messageData;
Pointer replyBuffer = new Memory(256);
replyBuffer.clear(256);
// HERE IS THE NATIVE CALL!!
reply = icmpecho.IcmpSendEcho(icmpHandle,
inetAddr.inet_addr(ipAddress),
requestData,
(short) 32,
null,
replyBuffer,
256,
timeout);
// NATIVE CALL DONE, CHECK REPLY!!
icmpecho.IcmpCloseHandle(icmpHandle);
}
public boolean IsReachable () {
return (reply > 0);
}
My guess is that your iteration logic to determine the different ip address is based upon different configuration hence your pc's fetches all addresses but your webserver doesn't.
Try adding debug in the logic where you build up the list of ip adresses to check.
I have Arm processor which is AllWinner A13 ,RAM- 512mb, and OS- Linaro 13.01 Ubuntu (means debian). Now i m making Serial Communication program for /dev/ttyS0. i made simple program for Two Way Serial Communication in java with netbeans. In my processor i short rx-tx of ttyS0 for loop back coonection checking. Means what ever i send through Serial port that i get return back. but i get error. i installed openjdk-7, librxtx-java on my processor. my code and error is below. If any have idea or solution then please suggest to me.
package serialcomm_linaro;
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
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(115200,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
InputStream in = serialPort.getInputStream();
OutputStream out = serialPort.getOutputStream();
(new Thread(new SerialReader(in))).start();
(new Thread(new SerialWriter(out))).start();
}
else
{
System.out.println("Error: Only serial ports are handled by this example.");
}
}
}
/** */
public static class SerialReader implements Runnable
{
InputStream in;
public SerialReader ( InputStream in )
{
this.in = in;
}
public void run ()
{
byte[] buffer = new byte[1024];
int len = -1;
try
{
while ( ( len = this.in.read(buffer)) > -1 )
{
System.out.print(new String(buffer,0,len));
}
}
catch ( IOException e )
{
e.printStackTrace();
}
}
}
/** */
public static class SerialWriter implements Runnable
{
OutputStream out;
public SerialWriter ( OutputStream out )
{
this.out = out;
}
public void run ()
{
try
{
int c = 0;
while ( ( c = System.in.read()) > -1 )
{
this.out.write(c);
}
}
catch ( IOException e )
{
e.printStackTrace();
}
}
}
public static void main ( String[] args )
{
try
{
(new TwoWaySerialComm()).connect("/dev/ttyS0");
}
catch ( Exception e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
my out is below . In this out i just send 123 and i get return back 23 first and then 1111... more time, and then errore. Instead of 111111.... i want only return back 123.
enter code here
RXTX Warning: Removing stale lock file. /var/lock/LCK..ttyS0
123
23
111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
java.io.IOExcepti on: Input/output error in nativeavailable
at gnu.io.RXTXPort.nativeavailable(Native Method)
at gnu.io.RXTXPort$SerialInputStream.read(RXTXPort.java:1429)
at gnu.io.RXTXPort$SerialInputStream.read(RXTXPort.java:1341)
at serialcomm_linaro.TwoWaySerialComm$SerialReader.run(TwoWaySerialComm.java:66)
at java.lang.Thread.run(Thread.java:722)
I hadn't tried serial communication over RXTX in a loopback scenario, but that shouldn't matter. The only thing that looks a bit suspicious is the part where you give the instance of the input stream to the SerialReader. I recommend that you pass SerialPort instance to both constructors, and every time you need to read from/write to the port's stream, use a stream getter, e.g. for reading:
public static class SerialReader implements Runnable
{
SerialPort serialPort;
public SerialReader ( SerialPort serialPort )
{
this.serialPort = serialPort;
}
public void run ()
{
byte[] buffer = new byte[1024];
int len = -1;
try
{
while ( ( len = serialPort.getInputStream().read(buffer)) > -1 )
{
System.out.print(new String(buffer,0,len));
}
}
catch ( IOException e )
{
e.printStackTrace();
}
}
}
please feedback.
UPDATE:
From my personal experience RXTX is a buggy solution. This however does not mean that this situation is caused by an underlying RXTX bug. It might be because the serial port isn't setup correctly, but in your case it is a standard port name with standard connection parameters. As a loooong shot, try replacing the baudrate 115200 with 9600, but that probably won't help. I can offer three paths from here:
try debugging the RXTX code - you might get more insight on what's happening
read the serial line troubleshooting
consider other Java solutions for serial communication, like JSSC instead of RXTX.
UPDATE:
I'm afraid I have been inattentive and jumped ahead. JSSC native libraries (.so,.dll) are inside the jssc.jar so they are loaded "automatically". With RXTX they come outside the jar file so you need to set the java.library.path system property in order for the JVM to find and load them or you'll get an UnsatisfiedLinkError.
You can open the JSSC jar file by a double click, and it will open in an archiver because it is actually a zip file. As with RXTX, you will notice that the native libs files are organized in directories named like operating systems (windows, linux, RXTX has Mac_OS_X and Solaris also).
Inside these directories there are the native libs files, the .so, dll., and .jnilib types of files, which are named after computer architectures. That's the broader meaning of the word, these are short codes for instruction set architectures (ISA). The instruction set defines the set of instructions (commands) for a CPU. In other words, there are many different CPU models (like your AllWinner A13) that conform to the same instruction set. The native libs source code is compiled to produce the executables (.so,...) which is a bunch of instructions from that same instruction set.
The reason why you got the UnsatisfiedLinkError with JSSC might be because you're on an unsupported architecture, and the corresponding native lib is being is searched for in an unexistent directory. The ISA short codes, which are also the names of these directories for JSSC are x86 and PPC architectures, both 32 and 64 bit variant. RXTX has many other's but I think that none of them is equivalent to ARMv7 which is the ISA of your AllWinner A13 CPU.
You can determine your architecture by executing this command in terminal:
uname -m
On my linux it ouputs:
x86_64
which means that it is a 64bit Intel 8086 architecture. Both JSSC and RXTX have implemented this architecture. If your architecture isn't implemented (supported) than you can't use these libraries to connect to serial port on that computer. In that case you must write your own or obtain a suitable implementation.
If the architecture matches and there are still native errors you might try recompiling the native libs sources. The sources are provided for both RXTX and JSSC.
UPDATE:
If your architecture is armv7l that means that JSSC, RXTX and JavaComm (approximatley said, RXTX "ancestor") in their current state are useless in your scenario.
I didn't manage to find any other open source java library for serial communication. If that is really true, you'd need to write your own native library conforming to the interface of the one of the above libraries to make them useful. In other words, you'd need to write a C program (something like this: 1, 2) with functionality of serial communication and JNI interface to the Java library.
In the sense of the answer completness, I'll mention a commercial product SerialIO which does support some ARM architectures (don't know if your is one of them). But if you decide for that solution, you can always send a query to their support.
Ok so the program is designed to take in connections, validate them, and resend that validation code. Before anyone get's angry it's just a simple little project and is not designed to be overly complex haha. However for some very strange reason the function is hanging on send.setAddess(packet.getAddress); I know this because I have commented out each individual line of code that deals with the Datagram packet "send" and have found that it "hangs" (or never progresses forward in the method again) on that particular line. Any thoughts? Am I doing something cluelessly wrong? I tried it on a linux server as well to make sure it didn't have anything to do with me and the same crap happened.
public static boolean authorize(String n, DatagramPacket packet) {
DatagramPacket send = new DatagramPacket(new byte[4096], 4096);
try {
System.out.println("in auth");
String[] t1 = n.split("%#");
String name = t1[1];
int k = genKey(name);
clients.put(name, k);
send.setAddress(packet.getAddress());
System.out.println("set add");
send.setPort(packet.getPort());
System.out.println("set port");
send.setData(("l-succeed%#" + Integer.toString(k)).getBytes());
System.out.println("set data");
main.dispathcer(send);
System.out.println("called send");
return true;
} catch(Exception e) {
send.setData("l-failed".getBytes());
main.dispathcer(send);
return false;
}
}
EDIT: it took 6 minutes before the authorization token was received by the client. So obviously the setAddress() works but is taking far too long...
It's possible that the process is hanging because there's an issue doing DNS resolution on the address for packet when you call .getAddress(). A few DNS calls are made in order to create the InetAddress object. On these machines, are you able to do a reverse DNS lookup on the IP that the packet packet came from? Try setting an entry for this IP in your /etc/hosts file.
I'm developing an app where the phone (Android program) is the client trying to send data through a socket to a Java receiver program on my computer.
So far I've been able to send simple strings or whatever, but now I'm trying to send custom objects that I create. I should note that both programs are separate Eclipse projects, and I seem to be having trouble including the same custom class "Order" on the server side (even though I have Order.java in the src folder of the server project).
Some code, for reference:
Server:
private void run() throws Exception {
ServerSocket mySS = new ServerSocket(4443);
while(true) {
Socket SS_accept = mySS.accept();
InputStream is = SS_accept.getInputStream();
ObjectInputStream ois = new ObjectInputStream(is);
Order order = (Order) ois.readObject();
if (order!=null){
java.util.List<String> items = order.getOrders();
int chair = order.getChair();
int table = order.getTable();
double price = order.getPrice();
System.out.println("Table: "+ table + " || Chair: " +chair);
for(String food: items) {
System.out.println(food);
}
System.out.println("Price: $"+price);
}
is.close();
SS_accept.close();
mySS.close();
}
And the relevant part of the client:
try {
mySocket = new Socket(serverService.ipAddress, serverService.port);
os = mySocket.getOutputStream();
oos = new ObjectOutputStream(os);
} catch(Exception e) {
Toast.makeText(PlaceOrder.this, "Error - not connected to server.", Toast.LENGTH_SHORT).show();
}
try {
oos.writeObject(order);
Toast.makeText(PlaceOrder.this, "Order Submitted!", Toast.LENGTH_SHORT).show();
refreshOrderPage(); //refresh page, allow waiter to make more orders
oos.close();
os.close();
mySocket.close();
} catch (Exception e) {
Toast.makeText(PlaceOrder.this, "Error - not connected to server.", Toast.LENGTH_SHORT).show();
}
Any ideas why I'm getting this error when trying to send objects through sockets?
Thanks.
You should probably set the serialVersionUID in the class, then build a jar with the shared classes and include that jar in both projects.
However, given you are using different JVMs (Oracle and Dalvik) there's no guarantee that the byte-level encoding is the same. You should either manually override the serialization using readObject/writeObject or use a different object encoding system that is guaranteed to be identical independent of the environment.
A stack trace would help, but almost certainly you're serializing an object on one side, sending it to the other, and the other side doesn't have a class definition with which it can reconstruct the object. In this case, it sounds like maybe your Server doesn't know about the com.foo.Order class.
You can also serialize object to some string format (json, yaml, xml) and pass it. It would much easier to maintain, I suppose.