Android MQTT Paho project don't connect in the broker mosquitto - java

I am trying to get this voice recognition project working with a Raspberry Pi and Android phone.
I'm running mosquitto (mqtt broker) on the Raspberry Pi. The Java application (jar file) and MyMQTT app (from the Play store) connect normally - I can tell this by controlling the LED on the Raspberry Pi via MyMQTT.
The MQTTPhone application in the project fails to connect to the mosquitto broker.
I'm using this code now only to test...
public class MqttService {
public void doDemo() {
try {
MqttClient client = new MqttClient("tcp://192.1XX.1.1YY:1883", MqttClient.generateClientId());
client.connect();
client.subscribe("ZZZ.jstnow.mqtt.topic/Home/YYYYY/XXX");
// We’ll now idle here sleeping, but your app can be busy
// working here instead
while (true) {
try { Thread.sleep (1000); } catch (InterruptedException e) {}
}
}
catch (MqttException e) { e.printStackTrace (); }
}
}
I'm using iptables, port forwarding in the router, etc.
Please help me.

Related

Publishing commands to device in IBM IoT using MQTT in Java

I am currently trying to publish a command to a specific topic in the IBM IoT Foundation MQTT Broker using a Java web application. My application is already able to listen to device events and act on them, however publishing commands to the device is a problem. I know for sure that my device is listening to the proper topic for commands, so what could be the problem? More specifically, here is the command I call to publish to the topic (from my Java app):
publish("iot-2/cmd/" + MQTTUtil.getDefaultCmdId() + "/fmt/json", rawJSONCommand, false, 0);
System.out.println("Finished sending command!");
Where the "publish" method is defined as follows:
public void publish(String topic, String message, boolean retained, int qos) { // check if client is connected
if (isMqttConnected())
{
// create a new MqttMessage from the message string
MqttMessage mqttMsg = new MqttMessage(message.getBytes());
// set retained flag
mqttMsg.setRetained(retained);
// set quality of service
mqttMsg.setQos(qos);
try {
System.out.println("About to send!");
client.publish(topic, mqttMsg);
System.out.println("Finished sending!"); }
catch (MqttPersistenceException e)
{ e.printStackTrace(); }
catch (MqttException e)
{ e.printStackTrace(); } }
else {
System.out.println("Connection lost!"); connectionLost(null);
} }
All that happens is that I enter the method, I get "About to send!" printed on my console as the code specifies, and then the actual 'client.publish(topic, mqttMsg)' call blocks my program indefinitely.. Eventually, after blocking for a while, I get the following error:
org.eclipse.paho.client.mqttv3.internal.ClientState checkForActivity SEVERE: a:2uwqwc:<MY_APP_NAME>: Timed out as no write activity, keepAlive=60,000 lastOutboundActivity=1,452,646,209,624 lastInboundActivity=1,452,646,149,303 time=1,452,646,329,628 lastPing=0
Thanks for the help!
If you are publishing from an application, are you specifying the device type and device id?
myAppClient.publishCommand(deviceType, deviceId, "stop", data);
Refer to section in documentation about publishing commands to connected devices.
https://docs.internetofthings.ibmcloud.com/java/java_cli_app.html

Client-Server connects while being on the same computer but not while being run on different ones

I'm trying to build a basic client-server application.
When I run both the server and the client on the same computer both manage to connect without a hitch but if I try to do so from different computers (desktop and laptop) the connection doesn't get though. The server isn't even aware that someone tried to connect to it while the client timeouts after a while. At first I assumed that it's a firewall problem but disabling the firewall completely on the server PC did not help. Tried changing ports and checked on multiple computers. Any ideas what could cause this?
I control both the server and the client and can change the code of both if necessary. The server always runs on the same PC and I'm connecting to it directly using hardcoded IP address.
This is the code of the client sending random int to the server.
public static void main(String[] args) {
Socket s = new Socket();
try {
s.connect(new InetSocketAddress("123.45.67.891", 8084), 5000);
s.getOutputStream().write(42);
s.close();
} catch (IOException e) {
e.printStackTrace();
return;
}
}
The server is slightly more complicated but considering the fact that they manage to connect while being run from the same PC I assume that the problem isn't with it.
edit: Server code (Thread per client. There shouldn't be too many of those)
public void run() {
try {
serverSocket = new ServerSocket(listenPort); //integer
} catch (IOException e) { ... }
while (shouldRun) {
try {
Socket clientSocket = serverSocket.accept(); // Blocked here while trying to connect from remote computer
//Never gets here
ConnectionHandler newConnection = connectionHandlerCreator.create(clientSocket);
connectionHandlers.add(newConnection);
newConnection.initialize();
new Thread(newConnection).start();
} catch (IOException e) { ... }
}
}
Initialize consists of the following (which latter used for I/O).
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out = new PrintWriter(clientSocket.getOutputStream(), true);
The problem is probably on your server side though: you have to make it respond to all ip's not just local one, by using the constructor:
ServerSocket(int port)
it will default accepting connections on any addresses which is not the case if you specified an IP

After Java 1.6.0_27 update Heroku application does not boot in 60 seconds

When I rollback to a previous version using 1.6.0_20 my application boots within 60 seconds. Given the facts below how can I debug and solve the issue?
My application is using Play 1.2.5
In the logs I see the application connects to the PostgreSQL database. That is usually the last log before R10 error.
--UPDATE
I have created a Plugin and issued a fake port bind which will be closed after 10 seconds. That solved the bind problem but now I have a memory problem. Under high load may app was using 600M of memory. But now I see ~1500M and it is continuously increasing.
#Override
public void onConfigurationRead() {
final int port = Integer.parseInt(Play.configuration.getProperty("http.port"));
try {
// Create a new server socket and set to non blocking mode
final ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.configureBlocking(false);
InetSocketAddress isa = new InetSocketAddress(port);
ssc.socket().bind(isa);
Logger.info("Fake bind to port %d", port);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
try {
ssc.socket().close();
Logger.info("Fake port closed");
} catch (IOException ioe) {
Logger.error(ioe, "Cannot close fake port");
}
}
}, 10000);
} catch (IOException ioe) {
Logger.error(ioe, "Cannot open fake port");
}
Cache.forcedCacheImpl = RedisCacheImpl.getInstance();
}
I have switched to jdk 7. My app now boots in 40 seconds and uses 500-600MB of memory. I have informed Heroku about the issue but they didn't really care.

how to run java tcp server in window azure?

how to run java tcp server in window azure?
can window azure do it?
I find so many article about java application for window azure,they is that open a JSP web project in eclipse, and than use worker role publish it in window azure, but my tcp server is general java project, so how to publish it to window azure?
my tcp server:
public class test {
private static int serverport = 12345;
private static ServerSocket serverSocket;
public static void main(String[] args) {
try {
serverSocket = new ServerSocket(serverport);
System.out.println("Server is start.");
while (!serverSocket.isClosed()) {
System.out.println("Wait new clinet connect!");
waitNewPlayer();
}
} catch (IOException e) {
System.out.println("Server Socket ERROR");
}
}
public static void waitNewPlayer() {
try {
Socket socket = serverSocket.accept();
System.out.println(socket.getInetAddress().getHostAddress()+"'s socket is connected now!");
createNewUser(socket);
} catch (IOException e) {
}
}
public static void createNewUser(final Socket socket) {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
out.println("nangnang");
} catch (IOException e) {
System.out.println("Socket is closed!");
}
System.out.println("This socket is removed form the player array!");
}
});
t.start();
}
}
You should be able to run an app like this in Azure, but you'll need to take care of a couple of things:
Open an Input Endpoint for your worker role - this opens the port to the outside world. You then need to either map it to the exact same port internally, or let Azure pick a port for you (and then you can ask the role environment which port you've been assigned, and open that port in your code instead of 12345)
For all your println's, you'd need to remote-desktop to see them, or you need to push them to diagnostics logging so you can see those debug statements via an external tool like Cerebrata's Diagnostics Manager.
As far as publishing: It's the same as the jsp examples you've seen: you build an Azure project to go along with your Java project, you set up the role size and instance count, create input endpoints, optionally create a cache, set up configuration settings for storage accounts, create a package to run in emulator or in the cloud, etc.
You might also want to try AzureRunMe which also supports Azure Java Project. http://azurerunme.codeplex.com/

Receiving SMS Messages using WMA in Java ME

I am trying to develop a sms sending and receiving test application in J2ME using the WMA API. I have separate threads for sending and receiving.
The Sending thread's run method -
public void run() {
try {
MessageConnection connection = (MessageConnection) Connector.open("sms://+" + number + ":1234");
BinaryMessage messageBody = (BinaryMessage) connection.newMessage(connection.BINARY_MESSAGE);
messageBody.setPayloadData(message.getBytes());
connection.send(messageBody);
connection.close();
} catch (IOException ex) {
}
}
The receiving thread's run method
public void run() {
try {
while (true) {
MessageConnection connection = (MessageConnection) Connector.open("sms://:1234");
BinaryMessage messageBody = (BinaryMessage) connection.receive();
message = new String(messageBody.getPayloadData());
number = messageBody.getAddress();
number = number.substring(6, 15);
App.setDisplay(number, message);
connection.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
I am initializing the receiving thread in the startApp() and initializing the sending thread when the send command is pressed. The problem I have is that if I use two Emulators, both sides can't send messages. One emulator can continuously send messages to the other but when the other emulator tries to send a message the message isn't received.
When a message is received by the emulator console shows -
[INFO] [sms ] ## javacall: SMS
sending...
when that line appears the emulator doesn't receive any messages. Where is the problem in my code?
PS: I saw that their is a way to use a listener to work around this problem with using a separate thread for receiving but I want to know where is the problem is in the above code?
Any help is really appreciated ^^
If you are running in emulator, use wma console available to send or receive messages. You can't do it from emulator to emulator. wma console is available at
utilities -> wma console
I found the problem... It's because SMS doesn't work in Netbeans above versions. It only works in Netbeans 6.1 ... Something is wrong with the emulator

Categories