Search code examples
javaibm-cloudmqttiot

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!


Solution

  • 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