예제 #1
0
        public ZoneGuardMQTTService(IConfiguration configuration, IHostingEnvironment environment, ILogger <ZoneGuardMQTTService> logger, IOptions <ConfigServiceMQTT> config, IApplicationLifetime appLifetime)
            : base(configuration, environment, logger, config, appLifetime)
        {
            configMQTT = config.Value;

            /*
             * string host = configuration["host"];
             * string port = configuration["port"];
             * string user = configuration["user"];
             * string password = configuration["password"];
             */

            //This returns a correct service, but prevents me from adding additional AbstractBackgroundProcessService implementations with different type parameters.
            //Additionally, it seems like this reference was newly created, and not the instance that was created on application startup (i.e. the hash codes are different, and the constructor is called an additional time).
            //var service = g. GetService<ZoneGuardAlarmManagerService>();
        }
예제 #2
0
 public ServiceMQTT(ConfigServiceMQTT config, IManager manager) : base(config, manager)
 {
 }
예제 #3
0
        private async Task MqttServer_Connect()
        {
            try
            {
                ConfigServiceMQTT config = getConfig <ConfigServiceMQTT>();
                var factory = new MqttFactory();
                mqttClient = factory.CreateMqttClient();

                //lock (mqttClient)
                {
                    if (config.UseCrentials())
                    {
                        clientOptions = new MqttClientOptionsBuilder()
                                        .WithClientId(Guid.NewGuid().ToString())
                                        .WithTcpServer(config.Host)
                                        .WithCredentials(config.UserName, config.Password)
                                        .Build();
                    }
                    else
                    {
                        clientOptions = new MqttClientOptionsBuilder()
                                        .WithClientId(Guid.NewGuid().ToString())
                                        .WithTcpServer(config.Host)
                                        .Build();
                    }

                    //Set delegate for processing MQTT messages
                    mqttClient.ApplicationMessageReceived += onMqttMessageReceived;


                    mqttClient.Connected += async(s, e) =>
                    {
                        string msg = "### MQTT Service CONNECTED WITH MQTT-SERVER ###";
                        getLogger().LogDebug(msg);
                        Console.WriteLine(msg);
                    };

                    mqttClient.Disconnected += async(s, e) =>
                    {
                        Console.WriteLine("### DISCONNECTED FROM SERVER ###");
                        await Task.Delay(TimeSpan.FromSeconds(5));

                        try
                        {
                            await mqttClient.ConnectAsync(clientOptions);
                        }
                        catch
                        {
                            Console.WriteLine("### RECONNECTING FAILED ###");
                        }
                    };

                    try
                    {
                        await mqttClient.ConnectAsync(clientOptions);

                        while (!mqttClient.IsConnected)
                        {
                            Thread.Sleep(100);
                        }
                    }
                    catch (Exception exception)
                    {
                        Console.WriteLine("### CONNECTING FAILED ###" + Environment.NewLine + exception);
                    }
                }

                getLogger().LogDebug("### WAITING FOR APPLICATION MESSAGES ###");
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
        }
예제 #4
0
        /*
         * private async Task InitAsync()
         * {
         *  try {
         *
         *      ConfigServiceMQTT config = getConfig<ConfigServiceMQTT>();
         *      var factory = new MqttFactory();
         *      mqttClient = factory.CreateMqttClient();
         *
         *
         *      clientOptions = new MqttClientOptionsBuilder()
         *                      .WithClientId(Guid.NewGuid().ToString())
         *                      .WithTcpServer(config.Host)
         *                      .Build();
         *
         *
         *
         *      mqttClient.ApplicationMessageReceived += (s, e) =>
         *      {
         *          Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
         *          Console.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}");
         *          Console.WriteLine($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
         *          Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
         *          Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}");
         *          Console.WriteLine();
         *      };
         *
         *      mqttClient.Connected += async (s, e) =>
         *      {
         *          Console.WriteLine("### CONNECTED WITH SERVER ###");
         *
         * //                    await mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("#").Build());
         *
         * //                    Console.WriteLine("### SUBSCRIBED ###");
         *      };
         *
         *      mqttClient.Disconnected += async (s, e) =>
         *      {
         *          Console.WriteLine("### DISCONNECTED FROM SERVER ###");
         *          await Task.Delay(TimeSpan.FromSeconds(5));
         *
         *          try
         *          {
         *              await mqttClient.ConnectAsync(clientOptions);
         *          }
         *          catch
         *          {
         *              Console.WriteLine("### RECONNECTING FAILED ###");
         *          }
         *      };
         *
         *      try
         *      {
         *          await mqttClient.ConnectAsync(clientOptions);
         *      }
         *      catch (Exception exception)
         *      {
         *          Console.WriteLine("### CONNECTING FAILED ###" + Environment.NewLine + exception);
         *      }
         *
         *      Console.WriteLine("### WAITING FOR APPLICATION MESSAGES ###");
         *
         *  }
         *  catch (Exception exception)
         *  {
         *      Console.WriteLine(exception);
         *  }
         *
         * }
         *
         */
        /*
         * private async Task DoItAsync()
         * {
         *  try {
         *      bool isSubscribed = false;
         *      while (true)
         *      {
         *          Console.ReadLine();
         *
         *          if (isSubscribed)
         *          {
         *              var applicationMessage = new MqttApplicationMessageBuilder()
         *                                          .WithTopic("test/mysensor2")
         *                                          .WithPayload("Goodbye World")
         *                                          .WithAtLeastOnceQoS()
         *                                          .Build();
         *
         *              await mqttClient.PublishAsync(applicationMessage);
         *
         *
         *              await Unsubscribe("test/mysensor2");
         *
         *              applicationMessage = new MqttApplicationMessageBuilder()
         *                                          .WithTopic("test/mysensor2")
         *                                          .WithPayload("I am dead")
         *                                          .WithAtLeastOnceQoS()
         *                                          .Build();
         *
         *              await mqttClient.PublishAsync(applicationMessage);
         *
         *
         *              isSubscribed = false;
         *          }
         *          else
         *          {
         *              await Subscribe("test/mysensor2", this.MyCallback);
         *
         *              var applicationMessage = new MqttApplicationMessageBuilder()
         *                  .WithTopic("test/mysensor2")
         *                  .WithPayload("Hello World")
         *                  .WithAtLeastOnceQoS()
         *                  .Build();
         *
         *              await mqttClient.PublishAsync(applicationMessage);
         *
         *              applicationMessage = new MqttApplicationMessageBuilder()
         *                                          .WithTopic("test/mysensor2")
         *                                          .WithPayload("I am alive :-)")
         *                                          .WithAtLeastOnceQoS()
         *                                          .Build();
         *
         *              await mqttClient.PublishAsync(applicationMessage);
         *
         *              isSubscribed = true;
         *          }
         *      }
         *  }
         *  catch (Exception exception)
         *  {
         *      Console.WriteLine(exception);
         *  }
         *
         * }
         */
        /*
         * public async Task RunAsync()
         * {
         *  throw new NotImplementedException();
         *  try
         *  {
         *      //MqttNetConsoleLogger.ForwardToConsole();
         *
         *      var factory = new MqttFactory();
         *      var client = factory.CreateMqttClient();
         *      var clientOptions = new MqttClientOptions
         *      {
         *          ChannelOptions = new MqttClientTcpOptions
         *          {
         *              Server = "192.168.1.50"
         *          }
         *      };
         *
         *      client.ApplicationMessageReceived += (s, e) =>
         *      {
         *          Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
         *          Console.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}");
         *          Console.WriteLine($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
         *          Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
         *          Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}");
         *          Console.WriteLine();
         *      };
         *
         *      client.Connected += async (s, e) =>
         *      {
         *          Console.WriteLine("### CONNECTED WITH SERVER ###");
         *
         *          await client.SubscribeAsync(new TopicFilterBuilder().WithTopic("test/mysensor1").Build());
         *
         *          Console.WriteLine("### SUBSCRIBED ###");
         *      };
         *
         *      client.Disconnected += async (s, e) =>
         *      {
         *          Console.WriteLine("### DISCONNECTED FROM SERVER ###");
         *          await Task.Delay(TimeSpan.FromSeconds(5));
         *
         *          try
         *          {
         *              await client.ConnectAsync(clientOptions);
         *          }
         *          catch
         *          {
         *              Console.WriteLine("### RECONNECTING FAILED ###");
         *          }
         *      };
         *
         *      try
         *      {
         *          await client.ConnectAsync(clientOptions);
         *      }
         *      catch (Exception exception)
         *      {
         *          Console.WriteLine("### CONNECTING FAILED ###" + Environment.NewLine + exception);
         *      }
         *
         *      Console.WriteLine("### WAITING FOR APPLICATION MESSAGES ###");
         *      bool isSubscribed = false;
         *      while (true)
         *      {
         *          Console.ReadLine();
         *
         *          if (isSubscribed)
         *          {
         *              var applicationMessage = new MqttApplicationMessageBuilder()
         *                                          .WithTopic("test/mysensor2")
         *                                          .WithPayload("Goodbye World")
         *                                          .WithAtLeastOnceQoS()
         *                                          .Build();
         *
         *              await client.PublishAsync(applicationMessage);
         *
         *              List<string> topics = new List<string> { "test/mysensor2" };
         *              await client.UnsubscribeAsync (topics);
         *
         *              applicationMessage = new MqttApplicationMessageBuilder()
         *                                          .WithTopic("test/mysensor2")
         *                                          .WithPayload("I am dead")
         *                                          .WithAtLeastOnceQoS()
         *                                          .Build();
         *
         *              await client.PublishAsync(applicationMessage);
         *
         *
         *              isSubscribed = false;
         *          }
         *          else
         *          {
         *              await client.SubscribeAsync(new TopicFilter("test/mysensor2", MqttQualityOfServiceLevel.AtMostOnce));
         *              var applicationMessage = new MqttApplicationMessageBuilder()
         *                  .WithTopic("test/mysensor2")
         *                  .WithPayload("Hello World")
         *                  .WithAtLeastOnceQoS()
         *                  .Build();
         *
         *              await client.PublishAsync(applicationMessage);
         *
         *              applicationMessage = new MqttApplicationMessageBuilder()
         *                                          .WithTopic("test/mysensor2")
         *                                          .WithPayload("I am alive :-)")
         *                                          .WithAtLeastOnceQoS()
         *                                          .Build();
         *
         *              await client.PublishAsync(applicationMessage);
         *
         *              isSubscribed = true;
         *          }
         *      }
         *  }
         *  catch (Exception exception)
         *  {
         *      Console.WriteLine(exception);
         *  }
         * }
         *
         */

        protected void onInitialize_NA()
        {
            ConfigServiceMQTT config = getConfig <ConfigServiceMQTT>();
            //IMqttClientFactory factory = new MqttFactory();
            //IMqttClient mqtt_client = factoryCreateMqttClient();
            var factory     = new MqttFactory();
            var mqtt_client = factory.CreateManagedMqttClient();

            /*var options = new MqttClientOptionsBuilder()
             *              .WithClientId(Guid.NewGuid().ToString())
             *              .WithTcpServer(config.Host)
             *              .Build();
             */


            var options = new ManagedMqttClientOptions
            {
                ClientOptions = new MqttClientOptions
                {
                    ClientId = Guid.NewGuid().ToString(),
                    //Credentials = new RandomPassword(),
                    ChannelOptions = new MqttClientTcpOptions
                    {
                        Server = "broker.hivemq.com"
                    }
                },

                AutoReconnectDelay = TimeSpan.FromSeconds(1)
            };


            mqtt_client.Connected += async(s, e) =>
            {
                await mqtt_client.SubscribeAsync(new TopicFilterBuilder().WithTopic("test/mysensor1").Build());
            };


            Thread.Sleep(15000);
            bool b = mqtt_client.IsConnected;

            mqtt_client.ApplicationMessageReceived += (sender, e) =>
            {
                Console.WriteLine(sender.ToString());
                Console.WriteLine(Encoding.UTF8.GetString(e.ApplicationMessage.Payload));
            };

            mqtt_client.StartAsync(options);

            Thread.Sleep(15000);
            // mysensor1

            mqtt_client.SubscribeAsync(new TopicFilterBuilder().WithTopic("test/mysensor2").Build());

            Thread.Sleep(15000);
            // mysensor1 + mysensor2


            List <string> topics1 = new List <string>(new string[] { "test/mysensor1" });

            mqtt_client.UnsubscribeAsync(topics1);
            Thread.Sleep(15000);

            // mysensor2

            List <string> topics2 = new List <string>(new string[] { "test/mysensor2" });

            mqtt_client.UnsubscribeAsync(topics2);
            Thread.Sleep(15000);

            // None

            mqttClient = (MqttClient)mqtt_client;

            //throw new NotImplementedException();
        }