I have the following code for a simple MqttClient using Spring…
package com.cbusha.be.component;
import com.hivemq.client.mqtt.MqttClient;
import com.hivemq.client.mqtt.MqttClientState;
import com.hivemq.client.mqtt.MqttGlobalPublishFilter;
import com.hivemq.client.mqtt.datatypes.MqttQos;
import com.hivemq.client.mqtt.mqtt3.Mqtt3AsyncClient;
import com.hivemq.client.mqtt.mqtt3.message.publish.Mqtt3Publish;
import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class MqttClientComponent {
private static final Logger logger = LoggerFactory.getLogger(MqttClientComponent.class);
@Value("${mqtt.server.uri}")
private String serverUri;
@Value("${mqtt.client.id}")
private String clientId;
@Value("${mqtt.username}")
private String username;
@Value("${mqtt.password}")
private String password;
private Mqtt3AsyncClient mqttClient;
@PostConstruct
public void connect() {
logger.info("Connecting to the MQTT server: {}", serverUri);
mqttClient = MqttClient.builder()
.useMqttVersion3()
.identifier(clientId)
.serverHost(serverUri.split(":")[1].substring(2))
.serverPort(Integer.parseInt(serverUri.split(":")[2]))
.buildAsync();
mqttClient.connectWith()
.simpleAuth()
.username(username)
.password(password.getBytes())
.applySimpleAuth()
.send()
.whenComplete((connAck, throwable) -> {
if (throwable != null) {
logger.error("Error connecting to MQTT server", throwable);
} else {
logger.info("Connected to MQTT server: {}", serverUri);
subscribeToTopic();
}
});
}
private void subscribeToTopic() {
mqttClient.subscribeWith()
.topicFilter("/zwave/Office/Big_Boy_Plug/lastActive")
.qos(MqttQos.fromCode(0))
.callback(this::handleMessage)
.send()
.whenComplete((subAck, throwable) -> {
if (throwable != null) {
logger.error("Error subscribing to topic", throwable);
} else {
logger.info("Subscribed to /zwave/Office/Big_Boy_Plug/lastActive");
}
});
}
private void handleMessage(Mqtt3Publish publish) {
logger.info("Message received on topic {}: {}", publish.getTopic(), new String(publish.getPayloadAsBytes()));
}
}
And I have an MQTT client I am using to make sure it is publishing correctly
But I never see the Handle Message method get hit on the component. I do see the connection and subscribe success messages get called so I am not sure what I am missing.
My initial guess is it has something to do with the QOS. I am using HiveMQ and have Home Assistant on the other side. I set the QOS to 0 since I believe that should be the default.
I am using the lastActive because it is constantly updating.