Exemplo n.º 1
0
        /// <summary>
        /// Connect to the mqtt broker through settings
        /// </summary>
        /// <param name="settings">Settings model where the mqtt broker address is stored</param>
        private void ConnectToMQTT(SettingsModel settings)
        {
            Debug.WriteLine("Connecting " + settings.BrokerIpAddress);
            if (client == null)
            {
                client = new MqttClient(settings.BrokerIpAddress);

                //client = new MqttClient(IPAddress.Parse(settings.BrokerIpAddress));
            }
            else
            {
                if (client.IsConnected)
                {
                    client.Unsubscribe(subscribedStrings.ToArray());
                    client.Disconnect();
                }
                try
                {
                    //client = new MqttClient(IPAddress.Parse(settings.BrokerIpAddress));
                    client = new MqttClient(settings.BrokerIpAddress);
                }
                catch
                {
                    MessageBox.Show("Wrong IP address provided");
                    return;
                }
            }
            connectToServer();
        }
Exemplo n.º 2
0
        private void btnMQTTListen_Click(object sender, EventArgs e)
        {
            if (listening)
            {
                try
                {
                    mqttClient.Disconnect();
                    mqttClient         = null;
                    listening          = false;
                    btnMQTTListen.Text = "Listen";
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.ToString());
                }
            }
            else
            {
                mqttMessages             = new BindingSource();
                dataGridView1.DataSource = mqttMessages;
                dataGridView1.AutoSize   = true;

                string host = txtMQTTHostname.Text;
                int    port = int.Parse(txtMQTTPort.Text);
                mqttClient = new MqttClient(host, port, false, null, null, MqttSslProtocols.None);
                string clientId = Guid.NewGuid().ToString();
                mqttClient.Connect(clientId);
                mqttClient.MqttMsgPublishReceived += MqttClient_MqttMsgPublishReceived;
                mqttClient.Subscribe(new string[] { txtTopicString.Text }, new byte[] { 0 });
                listening          = true;
                btnMQTTListen.Text = "Stop Listening";
                mouseLocation      = null;
            }
        }
Exemplo n.º 3
0
 private void Dashboard_Closing(object sender, System.ComponentModel.CancelEventArgs e)
 {
     if (client.IsConnected)
     {
         client.Disconnect();
     }
 }
Exemplo n.º 4
0
 private void BtnDisconnect_Click(object sender, EventArgs e)
 {
     client.Disconnect();
     BtnConnect.Enabled    = true;
     BtnDisconnect.Enabled = false;
     LblAlert.Text         = "DISCONNECTED!!";
 }
Exemplo n.º 5
0
 public void Disconnect()
 {
     if (_myMqttClient.IsConnected)
     {
         _myMqttClient.Disconnect();
     }
 }
Exemplo n.º 6
0
    public void Connect(string host)
    {
        if (client != null)
        {
            client.MqttMsgPublishReceived -= client_MqttMsgPublishReceived;
            client.Disconnect();
        }

        BrokerHost = host;

        client = new MqttClient(host);
        client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;

        string clientId = Guid.NewGuid().ToString();

        Exception lastConnectionException = null;

        for (int i = 1; i <= ConnectionRetries && !client.IsConnected; i++)
        {
            try {
                monitor.WriteLine($"[Net] Connecting to Broker ({host}) with client id: {clientId} ({i}/{ConnectionRetries}) ... ");
                client.Connect(clientId);
            } catch (Exception ex) {
                monitor.WriteLine($"[Net] Error connecting! Check if your Broker is up!");
                lastConnectionException = ex;
                System.Threading.Thread.Sleep(2000);
            }
        }

        if (!client.IsConnected)
        {
            throw lastConnectionException;
        }
    }
Exemplo n.º 7
0
 public void Stop()
 {
     _client.Unsubscribe(new string[] { "owntracks.*.*" });
     _client.Unsubscribe(new string[] { "owntracks.*.*.event" });
     _client.Unsubscribe(new string[] { "owntracks.*.*.info" });
     _client.Disconnect();
 }
Exemplo n.º 8
0
 private void Form1_Closing(object sender, FormClosingEventArgs e)
 {
     if (client != null && client.IsConnected)
     {
         client.Disconnect();
     }
 }
Exemplo n.º 9
0
        public void Disconnect()
        {
            if (_client != null && _client.IsConnected)
            {
                try
                {
                    //if(_topics != null)
                    //    _client.Unsubscribe(_topics);

                    _client.Disconnect();
                    Thread.Sleep(1000);
                }
                catch (Exception ex)
                {
                    try
                    {
                        // one more change to disconnect
                        if (_client.IsConnected)
                        {
                            _client.Disconnect();
                            Thread.Sleep(1000);
                        }
                    }
                    catch (Exception ex2)
                    {
                        throw new Exception($"Disconnect device failed, error = {ex2.Message}");
                    }
                    finally
                    {
                        LogMessage($"[{this.Name}] Disconnecting device failed: {ex.Message}", "Error");
                    }
                }
            }
        }
Exemplo n.º 10
0
    void OnGUI()
    {
        if (customButtonStyle == null)
        {
            customButtonStyle          = new GUIStyle(GUI.skin.button);
            customButtonStyle.font     = m_Font;
            customButtonStyle.fontSize = 22;
        }


        if (client != null && !client.IsConnected)
        {
            if (GUI.Button(new Rect(10, 60, 100, 30), "Połącz", customButtonStyle))
            {
                //client = new MqttClient(IPAddress.Parse("192.168.43.237"), 1883, false, null);
                client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
                string clientId = Guid.NewGuid().ToString();
                client.Connect(clientId, "unity", "", true, 5);
                string[] topic     = { "Sym/#" };
                byte[]   qosLevels = { MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE };
                client.Subscribe(topic, qosLevels);
                split_Joints_Angles = new string[] { "0", "45", "0" };

                //client.Subscribe(new string[] { "Target/x" , "Target/y" , "Target/z" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
                Debug.Log(client.WillTopic);
            }


            if (IKToggle.active == true)
            {
                IKToggle.SetActive(true);
            }
        }
        else if (client.IsConnected)
        {
            if (GUI.Button(new Rect(10, 130, 240, 30), "Resetuj pozycje celu", customButtonStyle))
            {
                client.Publish(EXTERNALDEVICE_TARGETRESET, System.Text.Encoding.UTF8.GetBytes("1"), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, true);
            }

            if (GUI.Button(new Rect(10, 170, 180, 30), "Uruchom IK", customButtonStyle))
            {
                client.Publish(EXTERNALDEVICE_IKRUN, System.Text.Encoding.UTF8.GetBytes("1"), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, true);
            }

            if (GUI.Button(new Rect(10, 60, 100, 30), "Odłącz", customButtonStyle))
            {
                split_Joints_Angles = new string[] { "0", "0", "0" };
                SetJointsAngle();
                client.Disconnect();
            }

            if (IKToggle.active == false)
            {
                IKToggle.SetActive(true);
            }
        }
    }
Exemplo n.º 11
0
        private void frmAgentScrew_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (client.IsConnected)
            {
                client.Disconnect();
            }

            active = false;
        }
Exemplo n.º 12
0
 private void Form1_Closing(object sender, FormClosingEventArgs e)
 {
     //Encerra definitivamente o form quando fechado!
     //Realiza desconexão do client
     if (client != null && client.IsConnected)
     {
         client.Disconnect();
     }
 }
Exemplo n.º 13
0
 private void ExitButton_Click(object sender, EventArgs e)
 {
     //wciśnięcie przycisku Logout
     client.Publish(LoginForm.loginData[1], Encoding.UTF8.GetBytes($"{LoginForm.loginData[0]},disconnect"), MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE, false);
     client.Disconnect();
     //this.Close();
     Environment.Exit(1);
     //Application.Exit();
 }
Exemplo n.º 14
0
        public void Disconnect(bool bLog = false)
        {
            if (_client != null)
            {
                _configData.AutoReconnect = false;
            }

            if (_client != null && _client.IsConnected)
            {
                try
                {
                    //if(_topics != null)
                    //    _client.Unsubscribe(_topics);
                    _client.Disconnect();
                    if (bLog)
                    {
                        LogMessage($"[{this.Name}] Client has been disconnected and the appDomain {AppDomain.CurrentDomain.FriendlyName} is going to be unloaded");
                    }
                    Thread.Sleep(1000);
                }
                catch (Exception ex)
                {
                    try
                    {
                        // one more change to disconnect
                        if (_client.IsConnected)
                        {
                            _client.Disconnect();
                            if (bLog)
                            {
                                LogMessage($"[{this.Name}] After one more time, the Client has been disconnected and the appDomain {AppDomain.CurrentDomain.FriendlyName} is going to be unloaded");
                            }
                            Thread.Sleep(1000);
                        }
                    }
                    catch (Exception ex2)
                    {
                        throw new Exception($"Disconnect device failed, error = {ex2.Message}");
                    }
                    finally
                    {
                        if (bLog)
                        {
                            LogMessage($"[{this.Name}] Disconnecting device failed: {ex.Message}", "Error");
                        }
                    }
                }
            }
            else
            {
                if (bLog)
                {
                    LogMessage($"[{this.Name}] Client has been already disconnected and the appDomain {AppDomain.CurrentDomain.FriendlyName} is going to be unloaded");
                }
            }
        }
Exemplo n.º 15
0
 private void buttonDisconnect_Click(object sender, EventArgs e)
 {
     if (mClient != null && mClient.IsConnected)
     {
         labelStatus.Text = "Disconnected";
         mClient.Unsubscribe(topics);
         mClient.Disconnect(); //Free process and process's resources
     }
     mClient = null;
 }
Exemplo n.º 16
0
 public void Stop()
 {
     System.Diagnostics.Debug.WriteLine("stop");
     sonoff_client.Disconnect();
     sonoff_client = null;
     //ar844_client.Disconnect();
     //ar844_client = null;
     //antscale_client.Disconnect();
     //antscale_client = null;
 }
Exemplo n.º 17
0
        public void UpdateUserScanByMemberid(string trunscan, string topicsearch) // สถานะการสแกน
        {
            client.ProtocolVersion = MqttProtocolVersion.Version_3_1;
            try
            {
                client.Connect(Guid.NewGuid().ToString(),
                               "fjhgvxul",
                               "cT9BYUzB5yCR",
                               true,                               // will retain flag
                               MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, // will QoS
                               true,                               // will flag
                               "/test",                            // will topic
                               "default",                          // will message
                               true,
                               60);
            }
            catch
            {
                Debug.WriteLine("Error Connect");
            }

            client.MqttMsgPublishReceived += client_MqttMsgPublishRecieved_GetSubscribe;
            // client.Subscribe(new string[] { topicup,topicdown }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE , MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE});
            client.Subscribe(new string[] { topicsearch }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });

            Debug.WriteLine("OnGetSubscribeUp");

            void client_MqttMsgPublishRecieved_GetSubscribe(object sender, MqttMsgPublishEventArgs e)
            {
                UserScanDAO userscan = new UserScanDAO();

                if (trunscan == "ขึ้นรถรับส่งเด็กนักเรียน")
                {
                    string fingerprintid = Encoding.UTF8.GetString(e.Message);
                    int    memberuserid  = Convert.ToInt32(fingerprintid);
                    Debug.WriteLine("Received = " + fingerprintid + "\ron topic = " + e.Topic + "\rtrunscan = " + trunscan + DateTime.Now.ToString("dd-MM-yyyy เวลา HH:mm:ss\r"));
                    userscan.UpdateUserScanByIDMember_Up(memberuserid, DateTime.Now.ToString("dd-MM-yyyy เวลา HH:mm:ss"));
                    //userscan.UpdateUserScanByFingerprintid_Up(fingerprintid, DateTime.Now.ToString("dd-MM-yyyy เวลา HH:mm:ss"));
                    Debug.WriteLine("OKScanup");
                    client.Disconnect();
                }

                if (trunscan == "ลงรถรับส่งเด็กนักเรียน")
                {
                    string fingerprintid = Encoding.UTF8.GetString(e.Message);
                    int    memberuserid  = Convert.ToInt32(fingerprintid);
                    Debug.WriteLine("Received = " + fingerprintid + "\ron topic = " + e.Topic + "\rtrunscan = " + trunscan + DateTime.Now.ToString("dd-MM-yyyy เวลา HH:mm:ss\n"));
                    userscan.UpdateUserScanByIDMember_Down(memberuserid, DateTime.Now.ToString("dd-MM-yyyy เวลา HH:mm:ss"));
                    //userscan.UpdateUserScanByFingerprintid_Down(fingerprintid, DateTime.Now.ToString("dd-MM-yyyy เวลา HH:mm:ss"));

                    Debug.WriteLine("OKScanDown");
                    client.Disconnect();
                }
            }
        }
Exemplo n.º 18
0
        protected override void OnClosed(EventArgs e)
        {

            //Do something 
            client.Disconnect();

            //////////////////

            base.OnClosed(e);
            System.Windows.Forms.Application.Exit();
        }
Exemplo n.º 19
0
 private void Form1_FormClosing(object sender, FormClosingEventArgs e)
 {
     if (client != null && client.IsConnected)
     {
         client.Disconnect();
     }
     else
     {
         MessageBox.Show("Client was not initialized...Skipping killing it.", "Report", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
     }
 }
Exemplo n.º 20
0
 private void btnStop_Click(object sender, RoutedEventArgs e)
 {
     if (client != null)
     {
         client.Disconnect();
         btnConnect.IsEnabled  = true;
         btnTopic.IsEnabled    = false;
         btnStop.IsEnabled     = false;
         btnPubTopic.IsEnabled = false;
     }
 }
Exemplo n.º 21
0
 private void Form1_FormClosing(object sender, FormClosingEventArgs e)
 {
     if (m_cClient.IsConnected)
     {
         m_cClient.Unsubscribe(m_strTopicsInfo);
         m_cClient.Disconnect(); //Free process and process's resources
     }
     if (conn != null)
     {
         conn.Close();
     }
 }
Exemplo n.º 22
0
        private void Exit(object sender, MouseButtonEventArgs e)
        {
            try
            {
                client.Disconnect();
            }
            catch (Exception Ex)
            {
            }

            this.Close();
        }
Exemplo n.º 23
0
        static void initClipboard()
        {
            // Clipboard bekommen
            String myClipboard = Clipboard.GetText();

            // Connecten
            MqttClient client = new MqttClient("broker.mqttdashboard.com");
            byte       code   = client.Connect(Guid.NewGuid().ToString());

            Console.WriteLine("Gib \"get\" oder \"post\" ein!");
            string GetPostCmd = Console.ReadLine();

            if (GetPostCmd.ToLower() == "get")
            {
                Console.WriteLine("Gib das Passwort ein.");
                string PasswordEingabe = Console.ReadLine();
                // Zum Topic Subscriben
                client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;

                ushort msgIdSub = client.Subscribe(new string[] { "zwischenablage" + PasswordEingabe + "/windows" },
                                                   new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
                Console.WriteLine("Du kannst nun Clipboards geteilt bekommen. Drücke eine Taste, um Abzubrechen.");
                Console.ReadKey();
                Console.Clear();
                client.Disconnect();
                initClipboard();
            }
            else if (GetPostCmd.ToLower() == "post")
            {
                Console.WriteLine("Wähle ein Passwort.");
                string Password = Console.ReadLine();
                Console.WriteLine("Das Passwort wurde gewählt. Drücke eine Taste um deine Zwischenablage zu posten.");
                Console.ReadKey();
                Console.Clear();
                // Clipboard publishen
                ushort msgIdPub = client.Publish("zwischenablage" + Password + "/windows",
                                                 Encoding.UTF8.GetBytes(myClipboard),
                                                 MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE,
                                                 false);
                Console.WriteLine("Dein Clipboard wurde erfolgreich gepostet. Das Programm wird neugestartet, wenn du eine Taste drückst.");
                Console.ReadKey();
                Console.Clear();
                client.Disconnect();
                initClipboard();
            }
            else
            {
                Console.WriteLine("Falsches Kommando! Versuche es erneut");
                client.Disconnect();
                initClipboard();
            }
        }
 private void ConnectMenu_Click(object sender, RoutedEventArgs e)
 {
     if (ConnectMenu.Header.ToString() == "Connect")
     {
         Connect_window conenctWindow = new Connect_window();
         conenctWindow.Show();
     }
     else
     {
         gimbal.Disconnect();
         ConnectMenu.Header = "Connect";
     }
 }
Exemplo n.º 25
0
        public override void Flush()
        {
            if (IsFlushing)
            {
                return;
            }

            Console.WriteLine($"### Flush ###");

            //清空中
            IsFlushing = true;

            Task.Factory.StartNew(() =>
            {
                Policy
                .HandleResult <bool>(x => x)
                .WaitAndRetryForever(x =>
                {
                    Console.WriteLine($"### 重试{x}次 ###");
                    return(TimeSpan.FromSeconds(1));
                })
                .Execute(() => IsConnected == false);

                //断开客户端
                mqttClient.Disconnect();

                Policy
                .HandleResult <bool>(x => x)
                .WaitAndRetryForever(x =>
                {
                    Console.WriteLine($"### 重试{x}次 ###");
                    return(TimeSpan.FromSeconds(10));
                })
                .Execute(() => IsConnected);

                //以clean session方式连接broker
                ConnectWrap(true, () => Console.WriteLine("### RECONNECTING SUCCEED ###"), () => Console.WriteLine("### RECONNECTING FAILED ###"));

                Console.WriteLine($"### IsConnected:{IsConnected} ###");

                //清空中状态重置
                IsFlushing = false;

                //断开broker
                //断开事件中会自动连接
                mqttClient.Disconnect();
            });
        }
Exemplo n.º 26
0
 public void Disconnect()
 {
     if (_client.IsConnected)
     {
         _client.Disconnect();
     }
 }
Exemplo n.º 27
0
        static void Main(string[] args)
        {
            try
            {
                //Guid key = Common.CommonConnection.ConnectTLS();
                Guid key = Common.CommonConnection.Connect();


                string topic = ConfigurationManager.AppSettings["topic"];

                Console.WriteLine($"Enter the message you want to send, type exit to quit.");

                string command = Console.ReadLine();
                while (command != "exit")
                {
                    MqttStatus status = MqttClient.Publish(key, topic, command, 1, false, 60);
                    if (status.Error)
                    {
                        throw new Exception(status.ErrorMessage);
                    }

                    command = Console.ReadLine();
                }

                MqttClient.Disconnect(key);
            }
            catch (Exception ex)
            {
                while (ex != null)
                {
                    Console.WriteLine(ex.Message);
                    ex = ex.InnerException;
                }
            }
        }
 //Disconnects from MQTT broker
 private void Disconnect()
 {
     if (client != null)
     {
         client.Disconnect();
     }
 }
Exemplo n.º 29
0
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("*******************************  PARK SS  *******************************");

                #region Start connection...
                Console.WriteLine("Connecting with 127.0.0.1...");

                m_cClient.Connect(Guid.NewGuid().ToString());

                if (m_cClient.IsConnected)
                {
                    Console.WriteLine("Connected.");
                }
                else
                {
                    Console.WriteLine("Error connecting to message broker...");
                    return;
                }
                #endregion

                #region Connection with ParkTU
                Console.WriteLine("Waiting to receive Parking Spots And Parks XML info from PARK TU...");

                //Subscribe chat channel
                byte[] qosLevels = { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE };//QoS
                m_cClient.Subscribe(m_strTopicsInfo, qosLevels);

                do
                {
                    Console.WriteLine("Press 'ESC' to stop connection.");

                    //receive message
                    m_cClient.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
                } while (Console.ReadKey(true).Key != ConsoleKey.Escape);
                #endregion

                //Unsubscribe all topics
                m_cClient.Unsubscribe(m_strTopicsInfo);

                #region End connection...
                Console.WriteLine("Closing connection with 127.0.0.1...");
                do
                {
                    Console.WriteLine("Still on connection, closing...");
                    m_cClient.Disconnect();
                    Thread.Sleep(1000);
                } while (m_cClient.IsConnected);
                #endregion

                Console.WriteLine("Disconnected. Other applications to disconnect: PARK TU & PARK DACE");
                Console.WriteLine("Press a key to exit.");
                Console.ReadKey();
            }
            catch (MqttClientException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Exemplo n.º 30
0
 public void disconnect()
 {
     if (client.IsConnected)
     {
         client.Disconnect();
     }
 }
Exemplo n.º 31
0
        public void Connect()
        {
            var c = new MqttClient("clientId", new MockMqttClient());

            Assert.IsFalse(c.IsConnected);
            c.Connect(new IPEndPoint(IPAddress.Loopback, 1883)).Wait();
            Assert.IsTrue(c.IsConnected);
            c.Disconnect(TimeSpan.FromSeconds(1));
            Assert.IsFalse(c.IsConnected);
        }