Nothing is received
I connect to my broker and subscribe to a topic where there is a retained message.
I expect to receive the message immediately.
But nothing happens.
public async Task<string> Get(string topic)
{
using (IMqttClient mqttClient = _MqttClientFactory.CreateMqttClient())
{
MqttClientOptions mqttClientOptions = new MqttClientOptionsBuilder().WithTcpServer(_Options.Host).Build();
MqttClientConnectResult rc = await mqttClient.ConnectAsync(mqttClientOptions);
mqttClient.ApplicationMessageReceivedAsync += MqttClient_ApplicationMessageReceivedAsync;
MqttClientSubscribeOptions mqttSubscribeOptions = _MqttClientFactory.CreateSubscribeOptionsBuilder()
.WithTopicFilter("zigbee2mqtt/Home/Hall/Thermostat")
.Build();
MqttClientSubscribeResult rs = await mqttClient.SubscribeAsync(mqttSubscribeOptions);
await Task.Delay(80000);
}
return string.Empty;
}
private async Task MqttClient_ApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs arg)
{
_Logger.LogDebug(arg.ToString());
string payload = Encoding.UTF8.GetString(arg.ApplicationMessage.Payload);
await Task.CompletedTask;
}
How do I get the message and return it to the caller?
Try to put the application message received handler in the line before connecting. Does this work?
MqttClientOptions mqttClientOptions = new MqttClientOptionsBuilder().WithTcpServer(_Options.Host).Build();
mqttClient.ApplicationMessageReceivedAsync += MqttClient_ApplicationMessageReceivedAsync;
MqttClientConnectResult rc = await mqttClient.ConnectAsync(mqttClientOptions);
Also please check if you are connected properly. The result of the connect method returns an object with information from the server. It may have denied your connection request and thus your client is not connected.
Topics are case sensitive, so you might want to subscribe to # and just see what topics you get messages on