Example #1
0
        private void ButConnect_OnClick(object sender, RoutedEventArgs e)
        {
            var mqttFactory = new MqttFactory();

            if (string.IsNullOrWhiteSpace(server))
            {
                MessageBox.Show("Invalid Mqtt Server");
                return;
            }

            if (port < 1024 || port > 65535)
            {
                MessageBox.Show("Invalid Mqtt Port");
                return;
            }

            client = new MqttClient(ClientSub, server, port, log);

            if (UseAuth)
            {
                client.UseAuthentication(Username, pwBox.Password);
            }

            if (UseTls)
            {
                try
                {
                    client.UseTls(GetCerts());
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"Invalid certificate {ex.Message}");
                    return;
                }
            }

            client.MessageReceived += (o, args) =>
            {
                if (CompareTopics(SearchTopic, args.Topic))
                {
                    UpdateTopicTags(args.Topic, args.Payload);
                }

                UpdateData(args.Topic, args.Payload);
            };

            try
            {
                client.Start();
            }
            catch (InvalidOperationException)
            {
                log.Add($"{DateTime.Now}: Unable to start client {ClientSub}");
                return;
            }

            IsConnected = true;

            Properties.Settings.Default.Port     = Port;
            Properties.Settings.Default.Server   = Server;
            Properties.Settings.Default.UseAuth  = UseAuth;
            Properties.Settings.Default.Username = Username;
            Properties.Settings.Default.UseTls   = UseTls;
            Properties.Settings.Default.CertPath = CertPath;
            Properties.Settings.Default.Save();
        }