How to get communication response using MQTT

Asked

Viewed 533 times

0

I am developing an application which I use the MQTT communication protocol, where my system sends a command to a certain equipment, my equipment is receiving the command and changing the status. The problem is, how do I get feedback from my equipment? Because my system needs to get back if the equipment has changed status and what the current status is to be displayed on my system.

My class MQTT `package business;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

public class Mqtt implements MqttCallback {

private static Mqtt INSTANCE;

MqttClient client;
//String ipPatchPanel;
//String mensagem = "D" + "numeroPorta" + "comando";
String topico = "Stream";

private Mqtt() throws MqttException {
    client = new MqttClient("tcp://192.168.1.105:1883", "Enviando...");
    client.connect();
    client.setCallback(this);
}

//Singleton
public static Mqtt getInstance() throws MqttException {
    if (INSTANCE == null) {
        return new Mqtt();
    } else {
        return INSTANCE;
    }
}

public void comandoMqtt(String ip, String porta, String comando) {
    try {
        String comandos = ip + "&" + porta + "&" + comando; // string que recebe e concatena três parâmetros recebidos na função
        client.subscribe(topico);//tópico de subscrição é o mesmo valor do IP
        MqttMessage message = new MqttMessage();
        message.setPayload(comandos.getBytes());
        client.publish(topico, message);//tópico onde publica é o mesmo valor do ip e o outro parâmetro é a mensagem
    } catch (MqttException e) {
        e.printStackTrace();
    }
}

@Override
public void connectionLost(Throwable cause) {
    // TODO Auto-generated method stub

}

@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
    System.out.println(message);
}

@Override
public void deliveryComplete(IMqttDeliveryToken token) {
    // TODO Auto-generated method stub

}

}

E meu MQTT-Arduino:#include #include #include

// Update these with values suitable for your network.
byte mac[]    = {  0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
IPAddress ip(192, 168, 1, 122);
IPAddress server(192, 168, 1, 117);
char mensagem;
int ledAmarelo = 3;
int ledVerde = 4;

void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i=0;i<length;i++) {
mensagem = (char)payload[i];
Serial.print((char)payload[i]);

if(mensagem == "ativoAmarelo"){
  Serial.println("Led Amarelo Ativado");
  digitalWrite(ledAmarelo, HIGH);
}
if(mensagem == "ativoVerde"){
  Serial.println("Led Verde Ativado");
  digitalWrite(ledVerde, HIGH);
}
}
Serial.println();
}

EthernetClient ethClient;
PubSubClient client(ethClient);

void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("arduinoClient")) {
  Serial.println("connected");
  // Once connected, publish an announcement...
  client.publish("outTopic","hello world");
  // ... and resubscribe
  client.subscribe("inTopic");

} else {
  Serial.print("failed, rc=");
  Serial.print(client.state());
  Serial.println(" try again in 5 seconds");
  // Wait 5 seconds before retrying
  delay(5000);
}
}
}

void setup()
{
 Serial.begin(57600);

 client.setServer(server, 1883);
 client.setCallback(callback);

 Ethernet.begin(mac, ip);
 // Allow the hardware to sort itself out
 delay(1500);
}

void loop()
{
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
}

`

In the console I see the sending taking the ip of the equipment and the command corresponding to the button clicked on the web system. inserir a descrição da imagem aqui

1 answer

1


Is your command coming to Arduin and is it changing status? I ask this because by your code you are publishing on a topic called Stream while Arduin is subscribing to a topic called inTopic. The topic should be the same in both cases for the published command to be received by Arduin.

For the turn the same thing, only on another topic, which may be the outTopic (Arduin publishes on this topic and the class Mqtt subscribes to the same topic).

By the way, your Singleton has a small bug: the variable INSTANCE never gets the new Mqtt().

  • It’s coming to the Antarctic, but I’m having a hard time handling the string, which will consequently cause the Antarctic to change its status. @Piovezan Voce have any complete example of this communication using JAVA-Arduino? I don’t know this protocol, I’m getting to know it now.

  • 1

    I don’t have. To treat the string, as my C is rusty, you should look about comparing strings in this language, or launch a new question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.