3
votes

I'm trying to use M2MQTT library to send MQTT messages to an Azure IoT Hub. I've followed the guidance here IoT Hub MQTT support to come up with the right parameters for connect and so on in the native MQTT section of that article.

I'm connecting successfully (CONNACK return value 0) with the following code:

_publishClient = new MqttClient(_hostName, 8883, true, null, null,MqttSslProtocols.TLSv1_2);
_publishClient.MqttMsgPublished += _client_MqttMsgPublished;
_publishClient.ConnectionClosed += _client_ConnectionClosed;
var connack = _publishClient.Connect(_publishDeviceId, string.Format("{0}/{1}", 
             _hostName, _publishDeviceId), _publishSas,true,3600);

but as soon as I make a Publish call (where deviceid is my device id):

var pubresult = _publishClient.Publish("/devices/{deviceid}/messages/events/", Encoding.UTF8.GetBytes("Hello"), MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE, false);

M2MQTT disconnects and raises the OnConnectionClosed event, and the message never gets delivered to the Azure IoT Hub.

I've tried stepping down through the M2MQTT MqttClient class code and the disconnect is coming from the ReceiveThread with the comments making it sound like it is Azure IoT Hub end that closed the connection:

// zero bytes read, peer gracefully closed socket
else
{
    // wake up thread that will notify connection is closing
    this.OnConnectionClosing();
}

If anyone has any ideas on why it is closing or how to troubleshoot, I'm all ears/eyes.

2
I'm seeing the same error.Jackie
Have your tried using windows-iot-sdk for mqtt client?Jackie
Hi, Azure IoT SDK team here - may I ask what is it that you like about m2mqtt or that doesn't work in our SDK that steers you away from using it?pierreca - MSFT
@pierreca-MSFT Trying to remember since this was almost 2 years ago... either you didn't have MQTT support in the SDK at that point, or it might have been a customer request to use that library, afraid I can't recall. I would normally of course use your SDK.Brian Noyes

2 Answers

2
votes

You might want to remove the first '/' in your publish topic string, so instead of

var pubresult = _publishClient.Publish("/devices/{deviceid}/messages/events/", Encoding.UTF8.GetBytes("Hello"), MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE, false);

Using

var pubresult = _publishClient.Publish("devices/{deviceid}/messages/events/", Encoding.UTF8.GetBytes("Hello"), MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE, false);

This is suggested on this page, and works on me.

1
votes

I'm not using the m2mqtt library but the Paho C library and I had the same issue. It wasn't until I specified the a recent API version in the username when managed to successfully publish a message to the Iot Hub.

In my case the username was: <iothubname>/<deviceid>/api-version=2016-11-14

I stumbled upon this issue and its fix here: https://blog.baeke.info/2017/05/16/iot-hub-device-twin-and-mqtt/

Couldn't find anything in Microsoft documentation about this issue