eclipse / paho.mqtt.m2mqtt

Eclipse Public License 1.0
512 stars 303 forks source link

InvalidCastException on connect #138

Open beecomm-noam opened 1 year ago

beecomm-noam commented 1 year ago

Hi, i'm getting this weird exception when connecting to the broker:

Unable to cast object of type 'uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPingResp' to type 'uPLibrary.Networking.M2Mqtt.Messages.MqttMsgConnack'.

This one thrown after a connection failure, when trying to reconnect to the broker. Here is my code:

private void Connect()
{
    try
    {
        Logger.Log(Level.Debug, "Client is trying to connect to the broker...");

        _client.Connect(
            $"adapter.{Settings.branchId}",
            Settings.brokerUsername,
            Settings.brokerPassword,
            false,
            MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE,
            true,
            $"adapters/{Settings.branchId}/status",
            JsonConvert.SerializeObject(new { status = "DISCONNECTED" }),
            false,
            5
        );

        if (_client.IsConnected)
        {
            Logger.Log(Level.Debug, "Client is connected, sending restoreOrders event...");
            _client.Publish($"restoreOrders/{Settings.branchId}", new byte[] { }, MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
        }
        else
        {
            Logger.Log(Level.Debug, "Client is !!! disconnected");
        }
    }
    catch (Exception e)
    {
        Logger.Log(Level.Exception, $"Failed to reconnect Mqtt server: {e.Message}");
        Thread.Sleep(10_000);

        Logger.Log(Level.Exception, "Retrying connection...");
        Connect();
    }
}

Is something wrong in the connection function? or is it an internal error? i havn't seen anything that can throw cast exception in the source.. please help 🙏🏼