Arduino not able to send serial data back - java

So I found out how to connect the Arduino to my java program. But using the serial connections doesn't give any useful data back, its either in the wrong format, or just sends it as a box. I've looked at the related questions posted early in here, but none of the tips seems to help. So does anyone know how to send the data between an Arduino and a computer using the serial port?
This is the code I'm using, provided by this person:
http://silveiraneto.net/2009/03/01/arduino-and-java/
package serialtalk;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import java.io.InputStream;
import java.io.OutputStream;
import processing.app.Preferences;
public class Main {
static InputStream input;
static OutputStream output;
public static void main(String[] args) throws Exception{
Preferences.init();
System.out.println("Using port: " + Preferences.get("serial.port"));
CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(
Preferences.get("serial.port"));
SerialPort port = (SerialPort)portId.open("serial talk", 4000);
input = port.getInputStream();
output = port.getOutputStream();
port.setSerialPortParams(Preferences.getInteger("serial.debug_rate"),
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
while(true){
while(input.available()>0) {
System.out.print((char)(input.read()));
}
}
}
}
The Arduino is this:
http://www.arduino.cc/en/Main/ArduinoBoardDuemilanove
The code simply receives a number, and determines which analog reading it should be sending back, from my Arduino.

When dealing with serial connections make sure of the following key points:
BAUD Rates match
DATABITS should match
STOPBITS should match
PARITY should match
Make sure you are using the correct cable (Null modem if needed)
Make sure the cable run isn't too long
All of the above can cause odd stuff to come out of the com port on the Java side. Once you get the hang of this it gets much easier.
My personal favorite library here.

Related

How to verify if DB remote server is running using only java raw sockets [Telnet]

I wanted to explore an option to write minimal code to check if db2 server is running using plain java sockets. Just like doing telnet to server. It seems db2 is not configured to respond for telnet connection. Any help?
Below code works for mysql, but not working db2.
This code is equivalent to telnet ip port
Below is the java code
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class myApp {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("192.168.8.142", 50000);
String pattern = "mysql|oracle|db2";
Pattern r = Pattern.compile(pattern);
InputStream in = socket.getInputStream();
byte[] b = new byte[512];
in.read(b);
String response = new String(b);
in.close();
socket.close();
Matcher m = r.matcher(response);
System.out.println(m.find(0));
}
}
For mysql2, telnet return some characters with mysql text, version and some encoded ascii characters. But for db2, its seems like telnet is stuck without any response.
If you telnet to a Db2-server (Db2 for Linux/Unix/Windows) on the correct port, and telnet shows "Connected to" then it means that something is listening on that port on that host.
If something is listening on that port, then telnet will first display Connected to ..., and Escape character is ... . If it is a Db2-LUW server that is listening on the port, you will see nothing further (which looks like a hang). You can then abort the process.
If you do not get a connection (and get an error message) then either a firewall blocks that port, or address is incorrect, or nothing is listening on the specified port at this time.
If it is a Db2-LUW server that is listening on the port, your code should not do a read on the socket, after getting a connection, because it will hang (for as long as the TCP timeout I believe) , as would telnet.
The Db2 Knowledge Center should be the first place to look for details.
If the Db2-server participates in discovery solutions, this can help. Otherwise, connecting to the database is the way to know if a Db2-server is running. That means, apart from drivers, you need to know in advance the host/port, the authentication-mechanism, and any configured encryption, plus any relevant credential tokens/keys/certs/uid+pwd as needed for authentication.
You could also look at the Apache Derby source code, as it implements the DRDA protocol, too see if you can mimic a connection attempt.
Keep in mind that enterprises often have production Db2-servers in a high availability configuration, and often have monitoring and alerting systems that verify constantly that the Db2-server is behaving properly. So consider whether wheel re-invention is useful.
This will still not solve the problem as an tcp server can produce similar behaviour.

Using Android TCP Client app to interface with sensor

UPDATE #2: BLUF: I think I found the problem, but I need help figuring out how to fix it. The device needs a command with prefix and suffix STX>command ETX> (I had to drop the open bracket so stackoverflow would show it). When I send over TCP using Hercules (which works), the host interprets STX> and ETX> correctly and just displays "command", however I wrote a java client program that sends the same information but it shows up on the host as "STX>commandETX>". What is java doing differently?
Original:
I've been troubleshooting this for the last few days and I'm out of ideas so here I am. First some background information that may or may not be relevant:
I have a SICK LMS151 LIDAR sensor that I need to access through an Android application. The sensor is designed as a TCP server so you connect as a client and send the command STX>sRN LMDscandataETX>. This cues the sensor to spit a bunch of data back to the client. On a computer I can use a program like Hercules in TCP client mode, send the command and instantly receive the data without issue. However getting an Android app to do the same has been problematic (I've attached the client code below).
I wrote a server app on a separate android device which my client app has been able to connect to and exchange data. I send the command "STX>sRN LMDscandataETX>" through the connection and that's exactly how it shows up on the server side. When the server app sends data, I can see it on my client. However, when I attempt to connect to the sensor with the client, it connects but does not respond to my request for data. Any ideas of issues to look into would be helpful because at this point I'm fresh out. Thanks!
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
public class TcpClient extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
runTcpClient();
}
private static final int TCP_SERVER_PORT = 2111;
private void runTcpClient() {
try {
Socket s = new Socket("192.168.0.105", TCP_SERVER_PORT);
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
Log.i("TcpClient", "Connected!");
//send output msg
String outMsg = "<STX>sRN LMDscandata<ETX>";
out.write(outMsg);
out.flush();
Log.i("TcpClient", "sent: " + outMsg);
//accept server response
String inMsg = in.readLine() + System.getProperty("line.separator");
Log.i("TcpClient", "received: " + inMsg);
//close connection
s.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
UPDATE: Spent some more time on this today. Added a BoundedInputStream from Apache in hopes that maybe I wasn't seeing anything because the sensor wasn't sending a /n character at the end of each reading. Also converted from BufferedReader to Scanner. No luck. I'm fairly convinced now that it's not a problem with my client reading but instead it is somehow sending the command differently from the computer such that it isn't understood by the sensor.
Ok, I solved this issue and I think its worth sharing. After using wireshark I found that the command that worked is substituting STX> and ETX> for \u0002 and \u0003. These are standard TCP headers and footers. I manually went into my code to make the substitution and voila! It worked.

Broadcast Message in Java

I need some mechanism that allows me to transfer some data from one java program to another within a same PC. I already investigated RMI but I want 1st app to broadcast some message for 2nd without request of 2nd application. In RMI only client can initiate a communication.
Raw sockets are also not desirable (very low level).
I need something like RMI with a different scheme of starting communication: 1 server broadcasts messages for several clients without requests from clients.
Could you please suggest me some libs/technologies (for desktop app)?
I suggest you to use java messaging service and one of it's implementations such as ApacheMQ.
A good starting point is here.
I would suggest using a database with a trigger and store procedure. Here is an example of calling java methods from the database. A message queue will work, but that is an overly complex solution.
Here's an excerpt from an example of how to create a procedure and call it via a trigger:
First, you add the following Java method to the class DBTrigger
CREATE OR REPLACE PROCEDURE add_emp (
emp_no NUMBER, emp_name VARCHAR2, dept_name VARCHAR2)
AS LANGUAGE JAVA
NAME 'DBTrigger.addEmp(int, java.lang.String, java.lang.String)';
Then, you create the INSTEAD OF trigger:
CREATE OR REPLACE TRIGGER emps_trig
INSTEAD OF INSERT ON emps
FOR EACH ROW
CALL add_emp(:new.empno, :new.ename, :new.dname);
Since you tagged this with CORBA, you could use the Event Service to broadcast a notice to all interested clients.
To enable the server to send packets of information to the client/clients. A datagram, by definition, is “an independent, self-contained message sent over the network whose arrival, arrival time, and content are not guaranteed”. Essentially, we are opening a DatagramSocket in order to send DatagramPacket messages to the client. We are using the datagram classes (instead of standard sockets) because they allow us to broadcast information to multiple clients, that are all connected to a MulticastSocket.
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class MulticastSocketServer {
final static String INET_ADDR = "224.0.0.3";
final static int PORT = 8888;
public static void main(String[] args) throws UnknownHostException, InterruptedException {
// Get the address that we are going to connect to.
InetAddress addr = InetAddress.getByName(INET_ADDR);
// Open a new DatagramSocket, which will be used to send the data.
try (DatagramSocket serverSocket = new DatagramSocket()) {
for (int i = 0; i < 100; i++) {
String msg = "Sent message no " + i;
// Create a packet that will contain the data
// (in the form of bytes) and send it.
DatagramPacket msgPacket = new DatagramPacket(msg.getBytes(),
msg.getBytes().length, addr, PORT);
serverSocket.send(msgPacket);
System.out.println("Server sent packet with msg: " + msg);
Thread.sleep(500);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
One thing that we need to take into consideration here, is that there are specific addresses that allow us to use a MulticastSocket are limited, specifically in the range of 224.0.0.0 to 239.255.255.255. Some of them are reserved, like 224.0.0.0. The address that we are using, 224.0.0.3, can be used safely.
Regarding the client, we are going to move a little bit differently. We are going to create a client class, that will accept incoming messages from the server, and then we are going to duplicate this class. The point here is that by using the same code, we can connect to the server seamlessly, while having as many clients as we like.
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
public class MulticastSocketClient
{
final static String INET_ADDR = "224.0.0.3";
final static int PORT = 8888;
public static void main(String[] args) throws UnknownHostException {
// Get the address that we are going to connect to.
InetAddress address = InetAddress.getByName(INET_ADDR);
// Create a buffer of bytes, which will be used to store
// the incoming bytes containing the information from the server.
// Since the message is small here, 256 bytes should be enough.
byte[] buf = new byte[256];
// Create a new Multicast socket (that will allow other sockets/programs
// to join it as well.
try (MulticastSocket clientSocket = new MulticastSocket(PORT)){
//Joint the Multicast group.
clientSocket.joinGroup(address);
while (true) {
// Receive the information and print it.
DatagramPacket msgPacket = new DatagramPacket(buf, buf.length);
clientSocket.receive(msgPacket);
String msg = new String(buf, 0, buf.length);
System.out.println("Socket 1 received msg: " + msg);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
First, we start the clients, which will keep waiting for incoming packets of information. As soon as we start the server, it will send the information packets and the clients will receive them and print the information on the screen
ZeroMQ could be what you are searching, but I have only used it in C, C++ and Python, so I am not totally sure of how well it is usable in Java. But they have implemented the Publisher-Subscriber pattern for their sockets and at least the static library of the version 3.2.2 under ubuntu 12.04 is stable and works very well.
As a "quick fix" write the output to file and have the second app read the file.
This is not elegant at all, but if you code to interfaces you can later replace the implementation with something better.
A good solution would be an implementation of the OMG Data Distribution Standard (DDS). With DDS there is just a global data space with a dynamic discovery protocol. See for example RTI DDS, there is a free community edition.

BindException: Address already in use even with unique port

I've asked this question yesterday and no one was able to figure out the problem I was having. So I was hoping of providing a more up to date code with the suggestions from yesterday added on. Basically, I've been trying to form a connection between a server and a client but whenever I executed the server then the client, I'd get this exception: Address already in use. The obvious answer would be to give it a new port, but even then I still get this error. I'm assuming it has something to do with my code somewhere going wrong. Can anyone spot it please? I have attached the server class and the client class.
This is the error I get:
Exception in thread "main" java.net.BindException: Address already in use
at java.net.PlainSocketImpl.socketBind(Native Method)
at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:376)
at java.net.ServerSocket.bind(ServerSocket.java:376)
at java.net.ServerSocket.<init>(ServerSocket.java:237)
at java.net.ServerSocket.<init>(ServerSocket.java:128)
at MessageServer.main(MessageServer.java:16)
Server code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;
public class MessageServer {
public static void main(String[] args) throws IOException {
try {
int port = 53705;
ServerSocket server = new ServerSocket(port);
while (true) {
System.out.println("Waiting for client...");
//server.setReuseAddress(true);
Socket client = server.accept();
System.out.println("Client from " + server.getInetAddress() + " connected.");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String inputLine = in.readLine();
System.out.println("Client said: '"+inputLine+"'");
Writer count = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
byte c [] = count.toString().getBytes();
count.flush();
count.close();
in.close();
}
} catch (IOException e) {
System.err.println(e);
}
}
}
Client code:
import java.net.*;
import java.io.*;
public class MessageSendClient {
public static void man(String args[]) throws IOException {
String servername = "localhost";
int port = 53705;
Socket server;
//server.setReuseAddress(true);
try {
server = new Socket (servername,port);
System.out.println("Connected to " + server.getInetAddress());
DataInputStream in = new DataInputStream(new BufferedInputStream(server.getInputStream()));
server.close();
byte c[] = new byte[100];
int num = in.read(c);
String count = new String(c);
System.out.println("Server said: " + count);
} catch (Exception e) { }
}
}
You're getting the error when the server program attempts to open up a socket on port 53705 for listening. The Address already in use message means just that, another process on your machine is already using port 53705. It could be that some daemon process has opened this same port by coincidence, or your web browser has opened this port and is still using it.
Most likely, though, is that you have another instance of your server program running somewhere in the background. Check all your terminal windows, or check your IDE for tabs containing the status of running programs.
By the way, "unique port" is a bit misleading, as port 53705 isn't "unique" in any way, it just happens to be a port number you (or somebody) picked that you hope isn't already in use. To get a truly unique port, use new ServerSocket(0) which will ask the system to allocate an unused port. To find out which port was assigned, use serverSocket.getLocalPort(). You might print it out, and then pass it to the client program as a command-line option.
I think you are running into a plattform and java liberary specific issue.
Please provide additional infos about your os plattform (x86/x64) and which version of jdk from which vendor are you using?
According to this Link
http://www.oracle.com/technetwork/java/javase/7u51-relnotes-2085002.html
Above Oracle JDK 7u51: The default socket permissions assigned to all code including untrusted code have been changed. You can only bind sockets to the ephemeral port range on each system.
Port 53705 should be a save ephemeral port.
But still use
netstat -an | grep 53705
to double check if the port is used in linux and use netstat or tcpview for windows.
You can use
less /proc/sys/net/ipv4/ip_local_port_range
for linux to check your ephemeral port range for linux and find
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters
in windows to get determine your ephemeral port range. More about ephemeral range in windows can be found in how to change/view ephemeral port range in windows machines
I can confirm your server code and client without the "man" -> "main" typo is running under Opensuse 12.3 with
Java version "1.7.0_51"
OpenJDK Runtime Environment (IcedTea 2.4.4) (suse-8.32.5-i386)
OpenJDK Client VM (build 24.45-b08, mixed mode)
jvm is running by an non admin user with groups: www,dialout,video,shadow,users
I tested your code and it works correctly (meaning: I can connect to the server, didn't test the rest). Just pay attention to the main method in MessageSendClient, there's a typo ("man" instead of "main") and the correct signature is:
public static void main(String[] args)
not
public static void main(String args[]) // Still compatible but not recommended (C-like syntax)
Make sure the listening port is free by executing (replace YOUR_PORT with the number)
netstat -tulpn | grep :YOUR_PORT
because that's the reason why you get that exception. If you're on Windows you might just run
netstat -an
and search for the port.

How can I modify this code to allow my client socket program to send a string to the server?

Hi ive written some code to connect to a server through the use of a socket. Id like to write some simple code that allows me to send a string to the server, im assuming this will involve input and output streams but I am new to this. Ive put the code I am working with below, any insights into the best way to accomplish this would be great.
import java.net.*;
import java.io.*;
public class SocketMarket
{
public static void main(String [] args)
{
String serverName = "XX.X.X.XXX";
int port = XXXX;
try
{
System.out.println("Connecting to " + serverName + " on port " + port);
Socket client = new Socket(serverName, port);
System.out.println("Connected to " + client.getRemoteSocketAddress());
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Thanks in advance
client.getOutputStream().write("Hello World".getBytes());
client.getOutputStream().flush();
The above is how you would send just a String, but you will probably want to build up some infrastructure around sending arbitrary text.
The general idea is that your server and client will communicate with each other using InputStream's and OutputStream's, which can be accessed from a Socket via getInputStream() and getOutputStream(), once the connection between them is made.
For your server to receive connections, you should be using a ServerSocket to accept() incoming connections.
Insight is here, the "really big index" for java.
http://docs.oracle.com/javase/tutorial/networking/sockets/readingWriting.html
Yes, it involves OutputStreams. If you want to output Strings you could write raw bytes via the OutputStream you get from the connection but then you completely loose control over encoding. You need to learn about reader/writer/streams first, then networking via sockets is simple. You can find the relevant part of the Java tutorials here: http://docs.oracle.com/javase/tutorial/essential/io/ (you can ignore the NIO part completely for the beginning). After that you can learn about socket networking: http://docs.oracle.com/javase/tutorial/networking/sockets/index.html .

Categories