Problem with MQTT client

dreamer76

Member
Joined
Mar 26, 2024
Messages
9
Programming Experience
1-3
I'm trying to learn C#.
I am working on a script with MQTT. I am using the M2Mqtt library. If I use a while loop in my script, for example while (i < 10), it works just fine. but when I want to create an endless loop I get the following message.

WARNING: Using default timeout value 5000.
WARNING: Using default retries value 0.

I searched for this and found that a timeout and retry must be set. because this is the standard.
But I can't figure out how to do this.
I have tried this, among other things, but I get the next error 'MqttClient' does not contain a constuctor that takes 3 arguments.

int timeoutMilliseconds = 10000; // 10 seconden time-out
int retries = 3; // 3 herhalingen
MqttClient client = new MqttClient(brokerAddress, timeoutMilliseconds, retries);

can anyone help me out
 
From what I saw with a quick search, you create an MqttConnectOptions object with that data and pass it as an argument when you call MqttClient.Connect. I may be wrong about that, as I've never used these classes and I didn't search very rigorously.
 
I'm puzzle if your loop of i <10 works, but an endless loop doesn't work, what happens when you have a loop of i < 1000000 ?

Looking at the code for M2MQTT, it looks like the default time out is 30 seconds, and it does 3 retries. Something else must be changing the default time out to 5000 and retries to 0.


Anyway, I think you'll need to twiddle the properties of the singleton MqttSettings to change time out and retry values, but it's unclear to me how you would go about doing that since the class looks like it only has getters, and only internal setters.
 
Please show your code with the fixed loop size vs. the endless loop. I would expected the large loop limit to exhibit the same as endless.
 
WARNING: Using default timeout value 5000. WARNING: Using default retries value 0.:
namespace AtsAdvancedTest.Actions
{
    using Ace;
    using Ace.Ats;
    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Text;
    using System.Threading;
    using uPLibrary.Networking.M2Mqtt;
    using uPLibrary.Networking.M2Mqtt.Messages;
    using Newtonsoft.Json;

    internal class ActionGetZoneStat : ActionLogin
    {

        private List<int> zones = new List<int>();

        internal ActionGetZoneStat(Panel panel, LoginOptions options, Action completed)
            : base(panel, options, completed)
            
        {

          //  int timeoutMilliseconds = 1000; // 10 seconds
         //   int retryCount = 3; // Retry three times
            

            int i = 5;
          //  while (i < 10000)   
                //if (i == 11)
            while (true) ;
            {
                //int timeout = 10000; // Timeout van 10 seconden (in milliseconden)
                //int retries = 3;     // 3 retries
             //   while (true) ;                 //  while (i > 10)
                foreach (string zone in options.Zones.Split(',', ';'))
                {
                  //  while (true)
                        this.zones.Add(int.Parse(zone));
                      //   Thread.Sleep(5000);
                           i++;
                }     

             }
        }

        protected override void ExecuteAsync(Action completed)
        {

            Debug.Assert(completed != null, "Missing action to be called when the process is completed.");
            foreach (int zone in zones)
            {
                IMessage request = this.Panel.CreateMessage("getSTAT.ZONE");
                request.SetProperty("objectID", 0, zone);
                this.Panel.BeginSend(request, this.Completed, completed);

                
            }
        }

        internal static string GetZoneStat(ZoneStat info)
        {
            return new StringBuilder()
                 .AppendLine("ZONE")
                .AppendFormat("{0}", info.Index)
                .AppendLine()
                .AppendFormat("\tOpen zone    = {0}", info.ActiveState)
                .AppendLine()
                .AppendFormat("\ttamper state    = {0}", info.TamperState)
                .AppendLine()
                .AppendFormat("\tAnti-Mask state    = {0}", info.AntiMask)
                .AppendLine()
                .AppendFormat("\tbattery fail    = {0}", info.BatteryFail)
                .AppendLine()

                

                .ToString();

        }

        internal static string GetZoneStat1(ZoneStat info)
        {

            var zoneStatsObject = new
            {
                ActiveState = info.ActiveState,
                Index = info.Index,
                TamperState = info.TamperState,
                Antimaskeee = info.AntiMask,
            };
            return JsonConvert.SerializeObject(zoneStatsObject, Formatting.Indented);
            
        }
        private void Completed(IAsyncResult ar)
        {
            //zoneStatus();
            Action completed = ar.AsyncState as Action;
            
            try
            {
                
                var result = new ZoneStat(this.Panel.EndSend(ar));
               // Program.Log(GetZoneStat(result));
               // Console.WriteLine(GetZoneStat(result));
                // Mqtt1();
                //////////////////////////////////////////////////////
              /*  if (GetZoneStat(result) == "hallo")
                {
                    Console.WriteLine("werkt niet");

                }
                else
                  
                    */{
                    int zoneIndex = result.Index;
                    // MQTT server instellingen
                    string brokerAddress = "192.168.4.33"; // Vervang "mqtt-server-adres" door het daadwerkelijke IP-adres of de hostnaam van de MQTT-server

                    string clientId = "client1";
                    string baseTopic = "ATS/";
                    string topic = $"{baseTopic}zone{zoneIndex}";


                    int timeoutMilliseconds = 10000; // 10 seconden time-out
                    int retries = 3; // 3 herhalingen
                    // Vervang "onderwerp" door het gewenste MQTT-onderwerp
                    //int timeout = 10000; // Timeout van 10 seconden (in milliseconden)
                    //int retries = 3;     // 3 retries

                    // MQTT client initialiseren
                  
                    
                    MqttClient client = new MqttClient(brokerAddress);

                   // client.Timeout = TimeSpan.FromSeconds(5);
                   // client.Retries = 3;
                    // Event handler toevoegen voor ontvangen berichten
                    // client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;

                    // Client-ID instellen en verbinden met MQTT-server
                    client.Connect(clientId);

                    // Bericht om te verzenden
                    string message = (GetZoneStat1(result)); //"Dit is een testberichtfffffffffffffffff";
                    Console.WriteLine(message);
                    // Bericht publiceren naar MQTT-server
                    string jsonPayload = JsonConvert.SerializeObject(message);
                    client.Publish(topic, Encoding.UTF8.GetBytes(message), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, true);

                    Console.WriteLine($"Bericht '{message}' verzonden naar MQTT-server op onderwerp '{topic}'.");

                    // Wacht tot er een toets wordt ingedrukt voordat het programma wordt afgesloten
                    //Console.ReadLine();
                    Thread.Sleep(1000);
                    // Client verbreken van MQTT-server
                    client.Disconnect();


                }
               // }
            }
            catch (AtsFaultException e)
            {
                string message = string.Format("Fault response {0}, {1}", e.Code, e.Message);
                Program.Error(message);
            }
            catch (Exception e)
            {
                Program.Error(e.Message);
            }
            finally
            {
                completed?.Invoke();
            }
        }
    
    }
}
 
Working:
namespace AtsAdvancedTest.Actions
{
    using Ace;
    using Ace.Ats;
    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Text;
    using System.Threading;
    using uPLibrary.Networking.M2Mqtt;
    using uPLibrary.Networking.M2Mqtt.Messages;
    using Newtonsoft.Json;

    internal class ActionGetZoneStat : ActionLogin
    {

        private List<int> zones = new List<int>();

        internal ActionGetZoneStat(Panel panel, LoginOptions options, Action completed)
            : base(panel, options, completed)
            
        {

          //  int timeoutMilliseconds = 1000; // 10 seconds
         //   int retryCount = 3; // Retry three times
            

            int i = 5;
            while (i < 10000)   
                //if (i == 11)
           // while (true) ;
            {
                //int timeout = 10000; // Timeout van 10 seconden (in milliseconden)
                //int retries = 3;     // 3 retries
             //   while (true) ;                 //  while (i > 10)
                foreach (string zone in options.Zones.Split(',', ';'))
                {
                  //  while (true)
                        this.zones.Add(int.Parse(zone));
                      //   Thread.Sleep(5000);
                           i++;
                }     

             }
        }

        protected override void ExecuteAsync(Action completed)
        {

            Debug.Assert(completed != null, "Missing action to be called when the process is completed.");
            foreach (int zone in zones)
            {
                IMessage request = this.Panel.CreateMessage("getSTAT.ZONE");
                request.SetProperty("objectID", 0, zone);
                this.Panel.BeginSend(request, this.Completed, completed);

                
            }
        }

        internal static string GetZoneStat(ZoneStat info)
        {
            return new StringBuilder()
                 .AppendLine("ZONE")
                .AppendFormat("{0}", info.Index)
                .AppendLine()
                .AppendFormat("\tOpen zone    = {0}", info.ActiveState)
                .AppendLine()
                .AppendFormat("\ttamper state    = {0}", info.TamperState)
                .AppendLine()
                .AppendFormat("\tAnti-Mask state    = {0}", info.AntiMask)
                .AppendLine()
                .AppendFormat("\tbattery fail    = {0}", info.BatteryFail)
                .AppendLine()

              

                .ToString();

        }

        internal static string GetZoneStat1(ZoneStat info)
        {

            var zoneStatsObject = new
            {
                ActiveState = info.ActiveState,
                Index = info.Index,
                TamperState = info.TamperState,
                Antimaskeee = info.AntiMask,
            };
            return JsonConvert.SerializeObject(zoneStatsObject, Formatting.Indented);
            
        }
        private void Completed(IAsyncResult ar)
        {
            //zoneStatus();
            Action completed = ar.AsyncState as Action;
            
            try
            {
                
                var result = new ZoneStat(this.Panel.EndSend(ar));
               // Program.Log(GetZoneStat(result));
               // Console.WriteLine(GetZoneStat(result));
                // Mqtt1();
                //////////////////////////////////////////////////////
              /*  if (GetZoneStat(result) == "hallo")
                {
                    Console.WriteLine("werkt niet");

                }
                else
                  
                    */{
                    int zoneIndex = result.Index;
                    // MQTT server instellingen
                    string brokerAddress = "192.168.4.33"; // Vervang "mqtt-server-adres" door het daadwerkelijke IP-adres of de hostnaam van de MQTT-server

                    string clientId = "client1";
                    string baseTopic = "ATS/";
                    string topic = $"{baseTopic}zone{zoneIndex}";


                    int timeoutMilliseconds = 10000; // 10 seconden time-out
                    int retries = 3; // 3 herhalingen
                    // Vervang "onderwerp" door het gewenste MQTT-onderwerp
                    //int timeout = 10000; // Timeout van 10 seconden (in milliseconden)
                    //int retries = 3;     // 3 retries

                    // MQTT client initialiseren
                  
                    
                    MqttClient client = new MqttClient(brokerAddress);

                   // client.Timeout = TimeSpan.FromSeconds(5);
                   // client.Retries = 3;
                    // Event handler toevoegen voor ontvangen berichten
                    // client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;

                    // Client-ID instellen en verbinden met MQTT-server
                    client.Connect(clientId);

                    // Bericht om te verzenden
                    string message = (GetZoneStat1(result)); //"Dit is een testberichtfffffffffffffffff";
                    Console.WriteLine(message);
                    // Bericht publiceren naar MQTT-server
                    string jsonPayload = JsonConvert.SerializeObject(message);
                    client.Publish(topic, Encoding.UTF8.GetBytes(message), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, true);

                    Console.WriteLine($"Bericht '{message}' verzonden naar MQTT-server op onderwerp '{topic}'.");

                    // Wacht tot er een toets wordt ingedrukt voordat het programma wordt afgesloten
                    //Console.ReadLine();
                    Thread.Sleep(1000);
                    // Client verbreken van MQTT-server
                    client.Disconnect();


                }
               // }
            }
            catch (AtsFaultException e)
            {
                string message = string.Format("Fault response {0}, {1}", e.Code, e.Message);
                Program.Error(message);
            }
            catch (Exception e)
            {
                Program.Error(e.Message);
            }
            finally
            {
                completed?.Invoke();
            }
        }
    
    }
}
 
*sigh* Beware the trailing semicolon.

This line:
C#:
while (true) ;    // <-- notice trailing semicolon here
{
    // do stuff here
}

is the same as:
C#:
while (true)
{
    // do nothing forever
}

// we never get here
{
    // do stuff here
}

which is different from:
C#:
while (i < 10000)
{
    // do stuff here
}
 
Did you mean "remove the semicolon"?

Leaving the semicolon on line 32 will give you an infinite loop that will never get past line 32. I can only assume that your code is multi-threaded because otherwise, you'd not even get that error message because the computer would be looping forever on line 32 and not be able to do anything else.

Stepping back a bit taking a different tack: Can you tell us what line of code causes the error message to appear? Is it one of your exception handlers? If so, can you show us the call stack when that exception is thrown?
 

Latest posts

Back
Top Bottom