Publishing commands to device in IBM IoT using MQTT in Java - 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

Related

JMS queue - 10 second pause between sending and receiving object message

I have two applications within my server, and use JMS via ActiveMQ to send messages between the two. My two apps are as follows
Web service - accepts HTTP requests, validates, then sends messages to be executed by the other application.
Exec App - accepts object messages, executes order, sends execution report back to the web service to present to the client.
My Exec app receives messages from the Web service within 200ms, no problems there. However when I send an exec report, the message can hang in the queue for over 10 seconds before being received by the web service. I am using the same code for both side's consumers so I am unsure what the cause would be.
Here is my message producer in the Exec App -
public void createAndSendExecReport(OrderExecutionReport theReport){
try {
logger.debug("Posting exec report: " +theReport.getOrderId());
this.excChannelMessageProducer.send(createMessage(theReport));
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
[there is a createMessage method which converts my POJO into an object message]
MessageListener listener = new MessageListener() {
#Override
public void onMessage(Message message) {
logger.debug("Incoming execution report");
try {
OrderExecutionReport report = (OrderExecutionReport)((ObjectMessage)message).getObject();
consumeExecutionReport(report);
} catch (Exception e) {
logger.error("Message handling failed. Caught: " + e);
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
logger.error(sw.toString());
}
}
};
I get the log message "sending execution report"
Then nothing in the web service for up to 15 seconds later until finally I get "incoming ... "
What could be the cause of this?
Make sure you have enough MDBs running on the Exec App so they can handle the load.

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

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.

How to send and receive SMS in java?

I want my Java application to send and receive SMS without using any additional hardware devices and it must be free.
I made my search but all i found is titles, i found somethings like SMSLib but at the other hand i didn't find tutorials or books to learn that.
I also found that SMSLib code but didn't understand:
Send Message/SMS Code
package SMSEngine;
import org.smslib.*;
class SendMessage
{
public static void sendMessage(String number, String message)
{
CService srv = new CService("COM4",9600,"huawei","E220");
try
{
srv.setSimPin("0000");
srv.setSimPin2("0000");
srv.setSmscNumber("");
srv.connect();
COutgoingMessage msg = new COutgoingMessage(number, message);
msg.setMessageEncoding(CMessage.MessageEncoding.Enc7Bit);
msg.setStatusReport(true);
msg.setValidityPeriod(8);
srv.sendMessage(msg);
srv.disconnect();
}
catch (Exception e)
{
e.printStackTrace();
}
System.exit(0);
}
}
Read Message/SMS Codes
package SMSEngine;
import org.smslib.*;
import java.util.*;
class ReadMessages
{
static CService srv;
public static LinkedList receiveMessage()
{
LinkedList msgList = new LinkedList();
/*
To Check COM port Go in following path in Windows7
Control Panel\Hardware and Sound\Bluetooth and Local COM
*/
srv = new CService("COM4",9600,"huawei","E220");//"COM1", 57600, "Nokia", ""
try
{
srv.setSimPin("0000");
srv.setSimPin2("0000");
srv.connect();
srv.readMessages(msgList, CIncomingMessage.MessageClass.Unread);
srv.disconnect();
return msgList;
}
catch (Exception e)
{
e.printStackTrace();
}
System.exit(0);
return msgList;
}
}
In order to send SMS messages you have two options: either use a gateway modem, or use a bulk service with an online API.
SMSLib is only a library that makes it easier to interface with a gateway (hardware device) or with a bulk SMS provider. Either way, the library by itself is not enough.
The code sample that you provided appears to try to use a gateway connected to a local serial port but since you don't have such a hardware device it's not going to work for you.
One way is to use SMS gateway and send them like ordinary emails.
"I also found that SMSLib code but didn't understand"-
Assuming that you know java/object oriented programming, read through an online tutorial on smslib for understanding the basics. May be you can start with this one http://smslib.org/doc/smslib/quickstart/

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

android bluetooth chat app (device loses connection immediately)

I have been going through several threads on here and didn't come across an answer to the issue I am running into.
My setup:
I have a Mac pc that I am using as a virtual serial port to communicate with my android Nexus S phone. Running the bluetooth chat app on the phone and using it as a client to talk to the virt comm I set up.
Initially I tried the bluetooth chat app with 2 android phones to confirm it works, which it does. I can send texts back and forth.
My Use case:
I have a device that reads RFid tags and sends the data to an android phone to collect the info.
I am using my PC to represent my device for now.
++++++++++++++++++
Ok to the problem,
I try to connect to the pc from my phone and initially I get a "connecting...." status bar update and after 15secs or so I get a toast message saying "I am connected to the pc" but immediately after I get "device lost connection" toast. Then the status bar goes to "not connected"
When I step through with the debugger, it seems to fail at the following portion of the bluetooth chat app. Specifically this line (bytes = mmInStream.read(buffer);)
public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
break;
}
}
}
When I look in logcat, the i/o exception is "software caused connection abort"
for the read() on inputstream.
Questions:
Does this have to do with my virtual port not setup right? I have the terminal up and waiting to receive input on /dev/tty.Nexus....
using the screen command # 9600 baud
Otherwise, I thought maybe the socket which the inputstream connects to is unavailable somehow. I printed that to log and it seems like it was not NULL. Every time I step through though it dies at the ConnectThread not in the ConnectedThread.
The following portion of code: specifically this line (mmSocket.connect();)
public void run() {
Log.i(TAG, "BEGIN mConnectThread");
setName("ConnectThread");
// Always cancel discovery because it will slow down a connection
mAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
} catch (IOException e) {
connectionFailed();
// Close the socket
try {
mmSocket.close();
} catch (IOException e2) {
Log.e(TAG, "unable to close() socket during connection failure", e2);
}
// Start the service over to restart listening mode
BluetoothChatService.this.start();
return;
}
// Reset the ConnectThread because we're done
synchronized (BluetoothChatService.this) {
mConnectThread = null;
}
// Start the connected thread
connected(mmSocket, mmDevice);
}
I wonder if the socket variable is losing scope due to multi-threading and the socket is being passed around?
Thanks
How you set up the virtual serial post on your Mac PC. Since you have tried to run the app on 2 phones and it's working, I think the problem is on the PC.
I have posted an entry about Android and Java Bluetooth here. Hope it will help.

Categories