I am trying to write a program that will send GPS coordinates using telnet.
I keep getting the following exception:
Exception in thread "Timer-0" java.lang.NullPointerException
at org.apache.commons.net.telnet.Telnet._sendByte(Telnet.java:1060)
at org.apache.commons.net.telnet.TelnetOutputStream.write(TelnetOutputStream.java:87)
at org.apache.commons.net.io.ToNetASCIIOutputStream.write(ToNetASCIIOutputStream.java:77)
at org.apache.commons.net.io.ToNetASCIIOutputStream.write(ToNetASCIIOutputStream.java:111)
at java.io.PrintStream.write(PrintStream.java:430)
at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:202)
at sun.nio.cs.StreamEncoder.implFlushBuffer(StreamEncoder.java:272)
at sun.nio.cs.StreamEncoder.flushBuffer(StreamEncoder.java:85)
at java.io.OutputStreamWriter.flushBuffer(OutputStreamWriter.java:168)
at java.io.PrintStream.write(PrintStream.java:477)
at java.io.PrintStream.print(PrintStream.java:619)
at java.io.PrintStream.println(PrintStream.java:756)
at com.example.myandroid.gpsSender$1.run(gpsSender.java:34)
at java.util.TimerThread.mainLoop(Timer.java:512)
at java.util.TimerThread.run(Timer.java:462)
I don't know why I am getting this. Can you please tell me? thanks
Here is my code:
package com.example.myandroid;
import org.apache.commons.net.telnet.TelnetClient;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.SocketException;
import java.util.Timer;
import java.util.TimerTask;
public class gpsSender {
private TelnetClient telnet = new TelnetClient();
public static void main(String[] args) throws Exception {
gpsSender client = new gpsSender();
client.start();
}
public String start() throws Exception {
// Connect to the specified server
telnet.connect("localhost", 5554);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
float longitude = 1;
float latitude = 1;
int count = 0;
PrintStream out = new PrintStream(telnet.getOutputStream());
public void run() {
out.println("geo fix " + String.valueOf(longitude) + " "
+ String.valueOf(latitude));
out.flush();
System.out.println("geo fix " + String.valueOf(longitude) + " "
+ String.valueOf(latitude));
longitude++;
latitude++;
count++;
if (count > 1000) {
cancel();
}
}
}, 0, 1000);
try {
telnet.disconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ("Done");
}
public void write(String value) {
try {
} catch (Exception e) {
e.printStackTrace();
}
}
}
The line
telnet.disconnect();
is going to execute, so you won't have an output stream to write to, hence the NPE. You should remove that line.
Instead of using localhost, try 10.0.2.2 - that's the IP address the emulator is usually on but I'm not sure if you can establish telnet comms with the emulator.
Edit: Here's a link to telnet the emulator but it's from a command window - perhaps you could write a small batch script for your tests to send gps coordinates but if you have to syncronise this somehow with your running test, you would have to do it from the Android app. It looks like the emulator is indeed on localhost and your 'pc' is on 10.0.2.2
Of course Use the 10.0.2.2 iP and also make sure you're giving the right permissions in your manifest .. but still, if you need to input the long. and lat. to use them in another app .. you don't really need telnet and for the emulator there's a little window called "Emulator Control" where you input manually the long. and lat. but using telnet communication with the emulator, that probably doesn't happen. and on a real phone you can use the "NetwProvider.getLocation()" but of course you can't test that on an emulator as well..
Thanks for publishing this question. This approach lets me easily manipulate the hardware and the sensors of the emulator from within my Robotium tests. Here is a code snippet to set the battery charge of the emulator to 100%:
TelnetClient telnet = new TelnetClient();
telnet.connect("10.0.2.2",5554);
PrintStream out = new PrintStream(telnet.getOutputStream());
out.println("power capacity 100");
out.flush();
telnet.disconnect();
Related
public void connect() {
final String msg = "";
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
s = new Socket("192.168.1.3", 1337);
textView.setText("Connection acquired");
out = s.getOutputStream();
output = new PrintWriter(out);
output.println(msg);
textView.setText("message sent : " + msg.length());
output.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
}
I am using the above code to connect to desired IP [192.168.1.3]... I have created another program at the other end... The problem is that the IP sometimes changes to 192.168.1.4 or 192.168.1.6... and when I use another network it changes to 192.168.43.2... now due to this I have to go every time into the code and change it manually....
Is there any function or any other thing that might search for IPs available then check if desired port exists and then connect... Thanks in advance
That's why DNS names exist. If you use an IP address, you have to use that exact address. If you use DNS, you do a name->IP lookup. Get a dynamic DNS provider and use that to give your server a name.
You really do not want to start port scanning to find open ports. You will be treated as an attacker and kicked off the network, because you really would be doing something attackers do.
I have configured one xbee pro as coordinator (API mode) and other as router (API mode). I trying to send data from coordinator to router using xbee java api, but in the router code i keep getting null, am I doing something wrong.
Below is the code for Sending data (coordinator):
public class MainApp {
private static final String PORT = "/dev/ttyUSB0";
private static final int BAUDRATE = 9600;
public static void main(String[] args)
{
String data = "Helloww";
XBeeDevice mycord = new XBeeDevice(PORT, BAUDRATE);
try {
mycord.open();
System.out.println("Port is opened\n");
System.out.println("remote device connection\n");
//mac of my router
RemoteXBeeDevice router = new RemoteXBeeDevice(mycord,
new XBee64BitAddress("0013A20040DD9BDD"));
System.out.println("Sending data\n");
mycord.sendData(router, data.getBytes());
} catch (XBeeException e) {
e.printStackTrace();
mycord.close();
System.exit(1);
}
}
}
code on router side
public class RecvApp {
private static final String PORT = "/dev/ttyUSB1";
private static final int BAUDRATE = 9600;
public static void main(String[] args)
{
XBeeDevice myrouter = new XBeeDevice(PORT, BAUDRATE);
try {
myrouter.open();
System.out.println("router port opened\n");
//mac of coordinator
RemoteXBeeDevice remotecord = new RemoteXBeeDevice(myrouter, new XBee64BitAddress("0013A20040D96FE5"));
XBeeMessage msg = myrouter.readDataFrom(remotecord);
System.out.print(msg);
} catch (XBeeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
myrouter.close();
System.exit(1);
}
}
}
On the router you need to have a loop that checks for messages and prints them out. The API should have a method you can call to check for messages before calling readDataFrom() (or maybe you just ignore the null response). Sleep for a few milliseconds between each check. Right now, there isn't much opportunity for your message to come through before the program quits.
When debugging something like this, start by isolating your problem. Which side is failing, the coordinator or the router? Are you sure the XBee modules have joined to each other and are on the same network?
One test would be to run a simple terminal emulator on the serial port connected to the router, do you see any frames coming through? If you look at a hex dump of the bytes, do you see your "Helloww" message? If not, you need to get the coordinator working first before you debug your router.
Found the issue, I was not converting the message received in the correct format. Added the below lines
String content = HexUtils.prettyHexString(HexUtils.byteArrayToHexString(xbeeMessage.getData()));
System.out.println("Hex data" + "" + content + "\n");
String value = new String(xbeeMessage.getData());
System.out.print("Actual msg" + " " + value + "\n");
Works now :)
I am trying to set up a java-arduino serial communication. So far I downloaded the code from the Arduino page (http://playground.arduino.cc/interfacing/java) but I get an error.
Code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.util.Enumeration;
public class SerialTest implements SerialPortEventListener {
SerialPort serialPort;
/** The port we're normally going to use. */
private static final String PORT_NAMES[] = {
"/dev/tty.usbserial-A9007UX1", // Mac OS X
"/dev/ttyACM0", // Raspberry Pi
"/dev/ttyUSB0", // Linux
"COM3", // Windows
};
/**
* A BufferedReader which will be fed by a InputStreamReader
* converting the bytes into characters
* making the displayed results codepage independent
*/
private BufferedReader input;
/** The output stream to the port */
private OutputStream output;
/** Milliseconds to block while waiting for port open */
private static final int TIME_OUT = 2000;
/** Default bits per second for COM port. */
private static final int DATA_RATE = 9600;
public void initialize() {
// the next line is for Raspberry Pi and
// gets us into the while loop and was suggested here was suggested http://www.raspberrypi.org/phpBB3/viewtopic.php?f=81&t=32186
System.setProperty("gnu.io.rxtx.SerialPorts", "/dev/ttyACM0");
CommPortIdentifier portId = null;
Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
//First, Find an instance of serial port as set in PORT_NAMES.
while (portEnum.hasMoreElements()) {
CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
for (String portName : PORT_NAMES) {
if (currPortId.getName().equals(portName)) {
portId = currPortId;
break;
}
}
}
if (portId == null) {
System.out.println("Could not find COM port.");
return;
}
try {
// open serial port, and use class name for the appName.
serialPort = (SerialPort) portId.open(this.getClass().getName(),
TIME_OUT);
// set port parameters
serialPort.setSerialPortParams(DATA_RATE,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
// open the streams
input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
output = serialPort.getOutputStream();
// add event listeners
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
} catch (Exception e) {
System.err.println(e.toString());
}
}
/**
* This should be called when you stop using the port.
* This will prevent port locking on platforms like Linux.
*/
public synchronized void close() {
if (serialPort != null) {
serialPort.removeEventListener();
serialPort.close();
}
}
/**
* Handle an event on the serial port. Read the data and print it.
*/
public synchronized void serialEvent(SerialPortEvent oEvent) {
if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
String inputLine=input.readLine();
System.out.println(inputLine);
} catch (Exception e) {
System.err.println(e.toString());
}
}
// Ignore all the other eventTypes, but you should consider the other ones.
}
public static void main(String[] args) throws Exception {
SerialTest main = new SerialTest();
main.initialize();
Thread t=new Thread() {
public void run() {
//the following line will keep this app alive for 1000 seconds,
//waiting for events to occur and responding to them (printing incoming messages to console).
try {Thread.sleep(1000000);} catch (InterruptedException ie) {}
}
};
t.start();
System.out.println("Started");
}
}
That's the output i get:
Stable Library ========================================= Native lib
Version = RXTX-2.2pre2 Java lib Version = RXTX-2.1-7 WARNING: RXTX
Version mismatch Jar version = RXTX-2.1-7 native lib Version =
RXTX-2.2pre2
Could not find COM port.
Started
I am using Linux. And I think the port is correct. Anyone could help?
After seeing the problems and struggling with RXTX and JSSC for while, I developed the JAVA Arduino Communication Library.
My library has (hopefullyy) great documentation(found on the SourceForge Wiki for the library) and tells you exactly how to install and use it. After downloading both JARs in the library and including them in your classpath, just include the following statement before your class definition:
import arduino.*;
Now, all you need is the following code snippet in your method, and you're good to go!
String ArduinoPort = ""; //Your port name here
int BAUD_RATE = 9600;
Arduino arduino = new Arduino(ArduinoPort, BAUD_RATE);
arduino.openConnection();
arduino.serialWrite('1'); //serialWrite is an overridden method, allowing both characters and strings.
arduino.serialWrite('1', 20); //its second parameter even allows delays. more details can be found in the documentation.
The library also comes with example code that I thought would help speed along the process.
it seems to be permission issue.
try : sudo chmod 666 /dev/ttyACM0 (you usb ) and rerun the java code again.
"Could Not Find Com Port" is the default error for when your Arduino can't interface with Arduino IDE.
In this case though, the error isn't saying that the Arduino IDE can't see your Arduino - its saying that the RXTX library can't see the Arduino.
Your PC's driver may be an older version, and not yet support the com required by RXTX...
Here's my advice:
Plugin your Arduino Board
Go to Control Panel ---> System and Security ---> System ---> On the left pane Device Manger
Expand Other Devices.
Under Other Devices you will notice a icon with a small yellow error graphic. (Unplug all your other devices attached to any Serial Port)
Right Click on that device ---> Update Driver Software
Select Browse my computer for Driver Software
Click on Browse ---> Browse for the folder of Arduino Environment which you have downloaded from Arduino website. If not downloaded then http://arduino.cc/en/Main/Software
After Browsing mark include subfolder.
Click next ---> Your driver will be installed.
Collapse Other Devices ---> Expand Port ( its in device manager only under other devices )
You will see Arduino Written ---> Look for its COM PORT (close device manager)
Go to Arduino Environment ---> Tools ---> Serial Port ---> Select the COM PORT as mentioned in PORT in device manager. (If you are using any other Arduino Board instead of UNO then select the same in boards )
Some Reference Material: http://www.devfactor.net/2014/10/26/arduino-basics-serial-communication/
CONTEXT:
I am creating a cross-platform multicast client-server system for mobile. I have created the server side in Java. I also created the android client side and it works perfectly.
WHAT I WANT TO KNOW:
I want to know if I could create a client side in iOS using the listener program in this example http://ntrg.cs.tcd.ie/undergrad/4ba2/multicast/antony/example.html that would be compatible with my server-side that I created in Java.
If the above example will not work is there a way I can still use my Java server-side and create a native iOS client system that is compatible with the Java server-side?
SAMPLE CODE OF JAVA SERVER SIDE FOR REFERENCE:
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
//more imports...
class Server2 {
public static MulticastSocket ms1;
public static void main(String[] args) throws IOException {
try {
InetAddress sessAddr1 = InetAddress.getByName("224.2.76.24");
ms1 = new MulticastSocket(5500);
ms1.joinGroup(sessAddr1);
while(true) {
byte[] message = new byte[1024];
message = getIpAddress().getBytes();
DatagramPacket dp = new DatagramPacket(message, message.length, sessAddr1, 5500);
ms1.send(dp);
System.out.println(String.format("Sent message: %s", message));
Thread.sleep(1000);
}
} catch (Exception e) {
System.out.println(String.format("Error: %s", e));
}
}
public static String getIpAddress() {
InetAddress ip;
try {
ip = InetAddress.getLocalHost();
return(String.format("%s",ip.getHostAddress()));
} catch (Exception e) {
return("false");
}
}
}
I tested the listener code in the link and it worked perfectly.
Should not be a problem. iOS is POSIX compliant and Objective-C is defined on top of ANSI C, so you could paste the code you linked to with minor modifications straight into your project, build a simple wrapper to Objective-C and your app should compile, run and work as desired.
On my machine, the following code compiles within Eclipse but throws an exception within Netbeans. The error message says "Exception in thread "main" java.net.BindException: Address already in use".
What is the proper configuration within Netbeans to make this code compile? It seems like the problem has to do with the fact that I have two main functions. If I start running either one of the apps, the second will fail to start, throwing the exception posted above.
Server.java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws Exception {
Server myServ = new Server();
myServ.run();
}
public void run() throws Exception {
ServerSocket mySS = new ServerSocket(9999);
Socket SS_accept = mySS.accept();
InputStreamReader mySR = new InputStreamReader(SS_accept.getInputStream());
BufferedReader myBR = new BufferedReader(mySR);
String temp = myBR.readLine();
System.out.println(temp);
}
}
Client.java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws Exception {
Client myCli = new Client();
myCli.run();
}
public void run() throws Exception {
Socket mySkt = new Socket("localhost", 9999);
PrintStream myPS = new PrintStream(mySkt.getOutputStream());
myPS.println("Hello server");
}
}
The problem is due to the fact that you left one instance of your server running and then started another one.
The way to achieve what I want is to right-click on the particular class (ex. Server.java) that I want to run and select "Run this file". This enables me to run only the Server app. Then, do the same process for the other file, Client.java.
However, Netbeans is somewhat confusing/deceiving in this particular circumstance. What Netbeans does is it runs the Server process, but labels that process as the name of the project (ex. MyTestNetworkingProject) and puts a run number on it, thus giving us MyTestNetworkingProject run #1 (it actually leaves out the #1 on the first process). Then, if I go to the Client.java file and select "Run this file", it generates a second process, MyTestNetworkingProject run #2. It then generates a second results window down at the bottom of the screen, as it generates these in new tabs as new processes get created.
Because of the nature of my specific code, what I wanted to see in my results window to confirm that my application was working was I wanted to observe the Server.java results window (which in this case is MyTestNetworkingProject run #1). Given my exact sequence of steps outlined above of running the different files, run #2 is the last run process and thus the tab on top, covering the run #1 tab. I can click on run #1 and see the results I was hoping to see in the console ("Hello server"), but I just have to know/remember that MyTestNetworkingProject run #1 represents the Server app and not the Client app.
Uncool, IMO.
If you write this in Windows OS,you can use "netstat -nao" to see which process use the 9999 port.If it is some unimportant process,you can kill this process.Otherwise you can change the port of the pragram.
I change the port address and it work for me in the Neat Beans IDE . This problem will come if we used the same port address for other one times . so to fix this error you have to change the port address and I am sure it will work
Server.java
public class SocServer {
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(5001);
Socket client = server.accept();
DataOutputStream os = new DataOutputStream(client.getOutputStream());
os.writeBytes("Hello Sockets\n");
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client.java
public class SocClient {
public static void main(String[] args) {
try {
Socket socClient = new Socket("localhost", 5001);
InputStream is = socClient.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String receivedData = br.readLine();
System.out.println("Received Data: " + receivedData);
} catch (IOException e) {
e.printStackTrace();
}
}
}
refer above code and it works for me..
I did try the method catch and solved the problem.