MQTT Java как подписаться на несколько тем?
Не понимаю как:
- подписать темы
- вывести темы
Вот что я пока написал:
public class ClientMQTT {
public static final String HOST = "tcp://mqtt.by:1883";
public static final String TopicKWH0 = "user/id/KWH0";
public static final String TopicW1 = "user/id/W1";
public static final String TopicW2 = "user/id/W2";
private MqttClient client;
private MqttConnectOptions options;
private final String userName = "Login";
private final String passWord = "Password";
@SuppressWarnings("unused")
private ScheduledExecutorService scheduler;
private void start() {
try {
client = new MqttClient(HOST, MqttClient.generateClientId(), new MemoryPersistence());
options = new MqttConnectOptions();
options.setCleanSession(false);
options.setUserName(userName);
options.setPassword(passWord.toCharArray());
options.setKeepAliveInterval(61);
options.setConnectionTimeout(601);
client.setCallback(new PushCallBack());
client.connect(options);
int[] Qos = {1};
String[] topic = {TopicKWH0, TopicW1, TopicW2};
client.subscribe(topic, Qos);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws MqttException {
ClientMQTT client = new ClientMQTT();
client.start();
}
}
public class PushCallBack implements MqttCallback {
public void connectionLost(Throwable cause) {
System.out.println ("Соединение разорвано, вы можете переподключиться");
}
public void deliveryComplete(IMqttDeliveryToken token) {
System.out.println("deliveryComplete---------" + token.isComplete());
}
public void messageArrived(String topic, MqttMessage message) throws Exception {
if(topic.equals(ClientMQTT.TopicKWH0)){
System.out.println("KWH0 - "+(new String(message.getPayload())));
} else if (topic.equals(ClientMQTT.TopicW1)){
System.out.println("W1 - "+(new String(message.getPayload())));
} else if (topic.equals(ClientMQTT.TopicW2)){
System.out.println("W2 - "+(new String(message.getPayload())));
}
}
}
Ответы (1 шт):
Автор решения: TimChesko
→ Ссылка
В mqtt клиент указываем
public static final String Topic = "iotGoodways/id устройства/#";
client.subscribe(Topic);
В PushCallBack -> messageArrived прописываем условия
if(topic.equals("iotGoodways/id устройства/KWH0")){
System.out.println("KWH0 - "+(new String(message.getPayload())));
} else if (topic.equals("iotGoodways/id устройства/W1")){
System.out.println("W1 - "+(new String(message.getPayload())));
} else if (topic.equals("iotGoodways/id устройства/W2")){
System.out.println("W2 - "+(new String(message.getPayload())));
}