Exemple #1
0
 public bool Connect(string connString, string clientId, ushort keepAlive,
                     string username          = null, string password = null,
                     IPersistence persistence = null)
 {
     try
     {
         mqtt = MqttClientFactory.CreateClient(connString, clientId,
                                               username, password, persistence);
         mqtt.KeepAliveInterval = keepAlive;
         if (withWill)
         {
             mqtt.Connect(willTopic, willQos,
                          new MqttPayload(willMessage), willRetained, cleanSession);
         }
         else
         {
             mqtt.Connect(cleanSession);
         }
         mqtt.Connected      += Mqtt_Connected;
         mqtt.PublishArrived += Mqtt_PublishArrived;
         mqtt.Published      += Mqtt_Published;
         mqtt.Subscribed     += Mqtt_Subscribed;
         mqtt.Unsubscribed   += Mqtt_Unsubscribed;
         mqtt.ConnectionLost += Mqtt_ConnectionLost;
         return(true);
     }
     catch (Exception m_ex)
     {
         return(false);
     }
 }
Exemple #2
0
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            global::Xamarin.Forms.Forms.Init ();

            // Code for starting up the Xamarin Test Cloud Agent
            #if ENABLE_TEST_CLOUD
            Xamarin.Calabash.Start();
            #endif

            MqttClient.Ios.Bootstrapper.Setup ();

            LoadApplication (new App ());

            var connectionString = Keys.MQTT_BROKER_CONNECTION;
            var clientId = "iphone";

            // Instantiate client using MqttClientFactory
            _client = MqttClientFactory.CreateClient(connectionString, clientId);

            // Setup some useful client delegate callbacks
            _client.Connected += new ConnectionDelegate(client_Connected);
            _client.ConnectionLost += new ConnectionDelegate(client_ConnectionLost);
            _client.PublishArrived += new PublishArrivedDelegate (client_PublishArrived);

            _client.Connect ();
            _client.Subscribe (
                new Subscription[] {
                    new Subscription ("/status", QoS.BestEfforts),
                    new Subscription ("/cmd", QoS.BestEfforts),
                    new Subscription ("/event", QoS.BestEfforts),

                });

            return base.FinishedLaunching (app, options);
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            lblConnected.Text = "Disconnected";
            _mqttClient = MqttClientFactory.CreateClient("tcp://m11.cloudmqtt.com:12360", Guid.NewGuid().ToString(), "mike", "cloudmqtt");
            _mqttClient.Connected += (object sender, EventArgs e) => {

                InvokeOnMainThread(() =>
                {
                    var subscription = new Subscription("mqttdotnet/pubtest", QoS.BestEfforts);
                    _mqttClient.Subscribe(subscription);
                    setConneectedState();
                });
            };
            _mqttClient.ConnectionLost += (object sender, EventArgs e) => {
                InvokeOnMainThread(() => {
                    setDisconnectedState();
                });
            };
            _mqttClient.Subscribed += _mqttClient_Subscribed;
            _mqttClient.Unsubscribed += _mqttClient_Unsubscribed;
            _mqttClient.PublishArrived += _mqttClient_PublishArrived;

            _mqttClient.Connect();
        }
Exemple #4
0
        public void PublishSystemData()
        {
            if (_mqtt.IsConnected == false)
            {
                _mqtt.Connect(MqttSettings.MqttServer, MqttSettings.MqttPort, MqttSettings.MqttUsername, MqttSettings.MqttPassword);
            }

            if (_mqtt.IsConnected == true)
            {
                if (MqttSettings.IsComputerUsed)
                {
                    PublishStatus();
                }
                if (MqttSettings.CpuSensor)
                {
                    try
                    {
                        _mqtt.Publish("cpuprosessortime", Processor.GetCpuProcessorTime());
                    }
                    catch (Exception)
                    {
                        //we ignore
                    }
                }
                if (MqttSettings.FreeMemorySensor)
                {
                    _mqtt.Publish("freememory", Memory.GetFreeMemory());
                }
                if (MqttSettings.VolumeSensor)
                {
                    PublishAudio();
                }
                if (MqttSettings.ScreenshotEnable)
                {
                    PublishScreenshot(Properties.Settings.Default["ScreenShotpath"].ToString());
                }
                if (MqttSettings.MqttSlideshow)
                {
                    if (Properties.Settings.Default["MqttSlideshowFolder"].ToString().Length > 5)
                    {
                        string folder = @Properties.Settings.Default["MqttSlideshowFolder"].ToString();
                        MqttCameraSlide(folder);
                    }
                }
                if (MqttSettings.BatterySensor)
                {
                    PublishBattery();
                }
                if (MqttSettings.DiskSensor)
                {
                    PublishDiskStatus();
                }
                if (MqttSettings.EnableWebCamPublish)
                {
                    PublishCamera(GLocalWebcamFile);
                }
            }
        }
Exemple #5
0
        private void ConnectToBroker()
        {
            if (Servers.SelectedIndex < 0)
            {
                ShowSettingsPage();
                return;
            }
            if (_clientConnected)
            {
                return;
            }

            Settings settings = Settings.LoadSettings(Servers.Items[Servers.SelectedIndex]);

            if (!settings.EnableControls)
            {
                return;
            }
            IWifi wifi = new Wifi();

            string server = wifi.GetSSID() == $"\"{settings.LocalSSID}\""
                ? settings.LocalServerName
                : settings.RemoteServerName;

            string connectionString = $"tcp://{server}:{settings.MqttPort}";

            Device.BeginInvokeOnMainThread(() =>
            {
                if (!string.IsNullOrEmpty(settings.Username))
                {
                    client = MqttClientFactory.CreateClient(connectionString, Guid.NewGuid().ToString(), settings.Username,
                                                            settings.Password);
                }
                else
                {
                    client = MqttClientFactory.CreateClient(connectionString, Guid.NewGuid().ToString());
                }

                client.Connected      += ClientConnected;
                client.ConnectionLost += ClientConnectionLost;
                client.PublishArrived += ClientPublishArrived;

                IDeviceInfo device = new DeviceInfo();
                string name        = device.GetName();

                try
                {
                    client.Connect("car/DISCONNECT", QoS.BestEfforts, new MqttPayload(name), false, true);
                }
                catch (Exception ex)
                {
                    Toaster(ex.Message, ToastPriority.Critical, ToastLength.Long);
                    _clientConnected = false;
                }
            });
        }
Exemple #6
0
        private void OpenMqtt()
        {
            client = MqttClientFactory.CreateClient(connectionString, clientId);
            client.Connect(true);

            client.Connected      += new ConnectionDelegate(client_Connected);
            client.ConnectionLost += new ConnectionDelegate(_client_ConnectionLost);
            client.PublishArrived += new PublishArrivedDelegate(client_PublishArrived);
            client.Published      += new CompleteDelegate(_client_Published);
        }
Exemple #7
0
        public async void PublishSystemData()
        {
            List <System.Threading.Tasks.Task> task = new List <System.Threading.Tasks.Task>();

            if (_mqtt.IsConnected == false)
            {
                _mqtt.Connect(MqttSettings.MqttServer, MqttSettings.MqttPort, MqttSettings.MqttUsername, MqttSettings.MqttPassword);
            }

            if (_mqtt.IsConnected == true)
            {
                if (MqttSettings.IsComputerUsed)
                {
                    task.Add(Task.Run(() => PublishStatus()));
                }
                if (MqttSettings.CpuSensor)
                {
                    task.Add(Task.Run(() => _mqtt.Publish("cpuprosessortime", Processor.GetCpuProcessorTime())));
                }
                if (MqttSettings.FreeMemorySensor)
                {
                    task.Add(Task.Run(() => _mqtt.Publish("freememory", Memory.GetFreeMemory())));
                }
                if (MqttSettings.VolumeSensor)
                {
                    task.Add(Task.Run(() => PublishAudio()));
                }
                if (MqttSettings.MqttSlideshow)
                {
                    if (Properties.Settings.Default["MqttSlideshowFolder"].ToString().Length > 5)
                    {
                        string folder = @Properties.Settings.Default["MqttSlideshowFolder"].ToString();
                        task.Add(Task.Run(() => MqttCameraSlide(folder)));
                    }
                }
                if (MqttSettings.BatterySensor)
                {
                    task.Add(Task.Run(() => PublishBattery()));
                }
                if (MqttSettings.DiskSensor)
                {
                    task.Add(Task.Run(() => PublishDiskStatus()));
                }
                if (MqttSettings.EnableWebCamPublish)
                {
                    task.Add(Task.Run(() => PublishCamera()));
                }
                if (MqttSettings.ScreenshotEnable)
                {
                    task.Add(Task.Run(() => PublishScreenshot()));
                }
            }
            await Task.WhenAll(task).ConfigureAwait(false);
        }
        /// <summary>
        /// Execute start up tasks
        /// </summary>
        /// <param name="sender">object sending the event</param>
        /// <param name="e">event arguments</param>
        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            m_client = MqttClientFactory.CreateClient("tcp://192.168.0.50:1883", "MQTTKinect");
            m_client.Connect(cleanStart: true);
            m_client.Publish("text", "Kinect 2.0 just loaded!", QoS.BestEfforts, false);
            timer = System.DateTimeOffset.Now.AddSeconds(0.1f);

            if (this.bodyFrameReader != null)
            {
                this.bodyFrameReader.FrameArrived += this.Reader_FrameArrived;
            }
        }
        public void Connect(string clientId)
        {
            // Instantiate client using MqttClientFactory
            this._clientId = clientId;
            this._client   = MqttClientFactory.CreateClient(this._connectionString, this._clientId, this._authMode, this._authToken);

            // Setup some useful client delegate callbacks
            this._client.Connected      += new ConnectionDelegate(client_Connected);
            this._client.ConnectionLost += new ConnectionDelegate(client_ConnectionLost);
            this._client.PublishArrived += new PublishArrivedDelegate(client_PublishArrived);

            //instantiating the connection
            _client.Connect(true);
        }
Exemple #10
0
 private void AutoConnect()
 {
     while (mqtt != null && !mqtt.IsConnected)
     {
         try
         {
             mqtt.Connect();
         }
         catch (Exception m_Ex)
         {
             Console.WriteLine("AutoConnect False");
         }
         System.Threading.Thread.Sleep(TimeSpan.FromSeconds(mqtt.KeepAliveInterval));
     }
 }
Exemple #11
0
    // Use this for initialization
    protected void Start()
    {
        Debug.Log("Starting");
        // Instantiate client using MqttClientFactory
        _client = MqttClientFactory.CreateClient(ConnectionString, ClientId, UserName, Password);

        Debug.Log(_client);
        // Setup some useful client delegate callbacks
        _client.Connected      += new ConnectionDelegate(client_Connected);
        _client.ConnectionLost += new ConnectionDelegate(_client_ConnectionLost);
        _client.PublishArrived += new PublishArrivedDelegate(client_PublishArrived);

        Debug.Log("Connecting......");
        _client.Connect();
    }
Exemple #12
0
        void init()
        {
            // User Settings

            XmlDocument xmlConfig = new XmlDocument();

            xmlConfig.Load(AppDomain.CurrentDomain.BaseDirectory + "config.xml");
            var mqttConfig = xmlConfig["RazerChromaMqtt"]["MQTT"];
            var v          = mqttConfig["MqttUser"].InnerText.Trim();

            mqttHost     = mqttConfig["MqttHost"].InnerText.Trim();
            mqttPort     = mqttConfig["MqttPort"].InnerText.Trim();
            mqttUser     = mqttConfig["MqttUser"].InnerText.Trim();
            mqttPw       = mqttConfig["MqttPw"].InnerText.Trim();
            mqttPreTopic = mqttConfig["MqttPreTopic"].InnerText.Trim();

            if (mqttUser == "" || mqttPw == "")
            {
                mqttUser = mqttPw = null;
            }


            // MQTT
            mqttClient                 = MqttClientFactory.CreateClient($"tcp://{mqttHost}:{mqttPort}", "chroma", mqttUser, mqttPw);
            mqttClient.Connected      += MqttC_Connected;
            mqttClient.ConnectionLost += MqttC_ConnectionLost;
            mqttClient.PublishArrived += MqttC_PublishArrived;

            MqttAppender.mqttClient   = mqttClient;
            MqttAppender.mqttPreTopic = mqttPreTopic;

            try
            {
                mqttClient.Connect(mqttPreTopic + "state", QoS.BestEfforts, new MqttPayload("offline"), false);
            }
            catch (Exception e)
            {
                log.Error("Mqtt connect eror : " + e.Message);
                base.Stop();
            }


            Task <IChroma> connectChroma = ColoreProvider.CreateNativeAsync();

            connectChroma.Wait();
            chroma = connectChroma.Result;
        }
Exemple #13
0
 // begin to connect
 public void BeginReceive()
 {
     ThreadPool.QueueUserWorkItem((o) =>
     {
         Log.Info("BeginReceive handle.Connect(true);");
         try
         {
             handle.Connect(true);
         }
         catch (Exception e)
         {
             // todo event that connect failed must be thrown to upper layer
             Log.Error("MqttAdaptor BeginReceive throw exp:{0}", e);
             throw;
         }
     });
 }
Exemple #14
0
 // reconnect
 // todo easy one implementation
 // just drop old handle
 public void Reconnect()
 {
     ThreadPool.QueueUserWorkItem((o) =>
     {
         Log.Info("Reconnect handle.Connect(false);");
         try
         {
             handle   = null;
             clientId = string.Format("client_{0}", Guid.NewGuid());
             InitHandle();
             handle.Connect(false);
             Log.Info("Reconnect handle.Connect(false); complete");
         }
         catch (Exception e)
         {
             Log.Error("MqttAdaptor Reconnect throw exp:{0}", e);
         }
     });
 }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad ();
            // Perform any additional setup after loading the view, typically from a nib.

            btnConnect.Enabled = true;
            btnPush.Enabled = false;

            lbConnected.TextColor = UIColor.Red;
            lbConnected.Text = "Not connected";
            lbStatus.Text = "...";

            _wormHole = new Wormhole ("group.tech.seamlessthingies.ccmqttex", "messageDir");
            _wormHole.ListenForMessage<string> ("emotion", (message) => {
                _mqttClient.Publish("mqttdotnet/pubtest", "Hi from your watch!", QoS.BestEfforts, false);
                InvokeOnMainThread(() => { lbStatus.Text = "got message from watch: " + _i.ToString();});
                _i++;
            });

            _mqttClient = MqttClientFactory.CreateClient ("tcp://m11.cloudmqtt.com:12360", Guid.NewGuid ().ToString (), "mike", "cloudmqtt");
            _mqttClient.Connected += (object sender, EventArgs e) => {
                InvokeOnMainThread (() => {
                    btnConnect.Enabled = false;
                    btnPush.Enabled = true;
                    lbConnected.TextColor = UIColor.Green;
                    lbConnected.Text = "Connected";
                    _connected = true;
                });
            };

            _mqttClient.ConnectionLost += (object sender, EventArgs e) => {
                InvokeOnMainThread (() => {
                    btnConnect.Enabled = true;
                    btnPush.Enabled = false;
                    lbConnected.TextColor = UIColor.Red;
                    lbConnected.Text = "Not connected";
                    _connected = false;
                });
            };

            _mqttClient.Connect (true);
        }
Exemple #16
0
        void Start()
        {
            //ColetorTopicoLog ctlm = new ColetorTopicoLog();
            //ctlm.Id_ColetorTopico = 1;
            //ctlm.DataHora = getData();
            //ctlm.Valor = "Start Inicio";
            //db.ColetorTopicoLog.Add(ctlm);
            //db.SaveChanges();

            // _client.Connect(true);
            //ColetorTopicoLog ctlm2 = new ColetorTopicoLog();
            //ctlm2.Id_ColetorTopico = 1;
            //ctlm2.DataHora = getData();
            //ctlm2.Valor = "Start Fim";
            //db.ColetorTopicoLog.Add(ctlm2);
            //db.SaveChanges();

            try
            {
                _client.Connect(true);
                //ColetorTopicoLog ctlm2 = new ColetorTopicoLog();
                //ctlm2.Id_ColetorTopico = 1;
                //ctlm2.DataHora = getData();
                //ctlm2.Valor = "Start Fim";
                //db.ColetorTopicoLog.Add(ctlm2);
                //db.SaveChanges();
            }
            catch (Exception exc)
            {
                ColetorTopicoLog ctlm2 = new ColetorTopicoLog();
                ctlm2.Id_ColetorTopico = 1;
                ctlm2.DataHora         = getData();
                ctlm2.Valor            = "Erro: " + exc.Message;
                db.ColetorTopicoLog.Add(ctlm2);
                db.SaveChanges();
            }
            // Connect to broker in 'CleanStart' mode
            //Console.WriteLine("Client connecting\n");
        }
Exemple #17
0
 public void Start()
 {
     // Connect to broker in 'CleanStart' mode
     _client.Connect(true);
 }
Exemple #18
0
 //Awake function connects to the mqtt broker and sets a function to be called whenever a publish arrives
 //NOTE: a factory class may be used to allow connections to any mqtt broker not just a hard coded one
 void Awake()
 {
     m_client = MqttClientFactory.CreateClient("tcp://" + IPAddress + ":" + Port, "UnityProxy");
     m_client.Connect(true);
     m_client.PublishArrived += new PublishArrivedDelegate(MessageRecieved);
 }
        private void ConnectToBroker(string ip, int port, string clientId)
        {
            if (string.IsNullOrEmpty(ip) || string.IsNullOrEmpty(clientId) || port == 0)
                return;
            if (_client != null)
            {
                _client.PublishArrived -= new PublishArrivedDelegate(_client_PublishArrived);
                _client.Connected -= new ConnectionDelegate(_client_Connected);
                _client.ConnectionLost -= new ConnectionDelegate(_client_ConnectionLost);
                _client.Published -= new CompleteDelegate(_client_Published);
                _client.Subscribed -= new CompleteDelegate(_client_Subscribed);
                _client.Unsubscribed -= new CompleteDelegate(_client_Unsubscribed);
                if (_client.IsConnected)
                {
                    // TODO this might be async
                    _client.Disconnect();
                }
            }

            _client = MqttClientFactory.CreateClient("tcp://" + ip + ":" + port.ToString(), clientId);

            _client.Connect();

            // Subscribe to the house code in config
            string houseCode = ConfigurationManager.AppSettings["HouseCode"];

            _client.Subscribe("/" + houseCode + "/#", QoS.BestEfforts);
            _client.Subscribe("$SYS/broker/clients/#", QoS.BestEfforts);
            _client.PublishArrived += new PublishArrivedDelegate(_client_PublishArrived);
            _client.Connected += new ConnectionDelegate(_client_Connected);
            _client.ConnectionLost += new ConnectionDelegate(_client_ConnectionLost);
            _client.Published += new CompleteDelegate(_client_Published);
            _client.Subscribed += new CompleteDelegate(_client_Subscribed);
            _client.Unsubscribed += new CompleteDelegate(_client_Unsubscribed);
        }
Exemple #20
0
        private static void SetupMqtt()
        {
            try
            {
                _mqtt = MqttClientFactory.CreateClient(_settings.Server, _settings.Key);

                _mqtt.PublishArrived -= new PublishArrivedDelegate(MqttPublishArrived);
                _mqtt.ConnectionLost -= new ConnectionDelegate(MqttConnectionLost);

                _mqtt.Connect();

                Subscription subscription = new Subscription(_settings.Key, QoS.BestEfforts);
                _mqtt.Subscribe(subscription);

                _mqtt.PublishArrived += new PublishArrivedDelegate(MqttPublishArrived);
                _mqtt.ConnectionLost += new ConnectionDelegate(MqttConnectionLost);

                _blinkLedCommand.Execute(CreateLedBlinkCommand(2));
            }
            catch (Exception ex)
            {
                Restart("Setup MQTT has failed", ex);
            }
        }
Exemple #21
0
 public void ReloadApp()
 {
     _mqtt.Connect(MqttSettings.MqttServer, MqttSettings.MqttPort, MqttSettings.MqttUsername, MqttSettings.MqttPassword);
     SetupTimer();
     new SystemShutdown(_mqtt).Subscribe();
 }
Exemple #22
0
 // reconnect
 // todo easy one implementation 
 // just drop old handle
 public void Reconnect()
 {
     ThreadPool.QueueUserWorkItem((o) =>
     {
         Log.Info("Reconnect handle.Connect(false);");
         try
         {
             handle = null;
             clientId = string.Format("client_{0}", Guid.NewGuid());
             InitHandle();
             handle.Connect(false);
             Log.Info("Reconnect handle.Connect(false); complete");
         }
         catch (Exception e)
         {
             Log.Error("MqttAdaptor Reconnect throw exp:{0}", e);
         }
     });
 }
Exemple #23
0
 private void Connect()
 {
     Debug.Log("Connecting......");
     _client.Connect();
 }
Exemple #24
0
 void Start()
 {
     Console.WriteLine("Client connecting\n");
     _client.Connect(true);
 }
Exemple #25
0
 void Start()
 {
     // Connect to broker in 'CleanStart' mode
     Console.WriteLine("Client connecting\n");
     _client.Connect(true);
 }
Exemple #26
0
 public void ReconnectMqtt()
 {
     _mqtt.Connect(MqttSettings.MqttServer, MqttSettings.MqttPort, MqttSettings.MqttUsername, MqttSettings.MqttPassword);
 }
Exemple #27
0
 void Start()
 {
     _client.Connect(true);
 }