Search code examples
android-studiomqttmosquittopaho

Send MQTT message from the android client to all the clients through MQTT broker


I need MQTT broker to publish the received MQTT message from the Android client to all other clients so added mosquitto pub command in the body of the message.

publish(client,"mosquitto_pub -h 192.34.63.138 -t fromApp -m "Turn" -d ");

It is giving error that "Can't resolve symbol "Turn" and ; or ) expected" .

Update

I understood it correctly later. I actually needed an MQTT message from the android client to be sent to all other clients so I thought to include publish keyword in the message body which was quite wrong. The MQTT itself sends the received messages to all the clients provided if the clients have subscribed to that topic.Hopefully, it will help other readers.


Solution

  • There are a number of problems with your approach.

    First, the compile time error is because you have nested " within a String (which is bound by ". To do this you need to escape the "'s with the \ as follows:

    "mosquitto_pub -h 192.34.63.138 -t fromApp -m \"Turn\" -d "
    

    The second problem is the more important one. MQTT doesn't work the way you seem to be expecting it to.

    You do not send commands to the broker for it to execute, you publish a message from one client to a topic, and the broker then delivers that message to all the clients that have subscribed to that topic. So in this case you would just publish a message with the payload Turn to the topic fromApp. Which is going to look something like:

    MqttMessage message = new MqttMessage("Turn".getBytes());
    sampleClient.publish("fromApp", message);