Exemplo n.º 1
0
        /// <summary>
        /// Connects to the specified mqtt server.
        /// </summary>
        /// <param name="server"></param>
        /// <param name="port"></param>
        /// <returns>The state of the connection.</returns>
		public ConnectionState Connect (string server, short port)
		{
			client = new MqttClient (server, port, Options.ClientIdentifier);
            syncContext = SynchronizationContext.Current;

			Trace.WriteLine ("Connecting to " + server + ":" + port.ToString ());
			
			return client.Connect(Options.Username, Options.Password);
		}
Exemplo n.º 2
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);
        }
Exemplo n.º 3
0
        static void Main(string[] args) {
            var client = new MqttClient("localhost", "whatter");
            client.Connect();

            var topicObservable = client.Observe<String, AsciiPayloadConverter>("Nmqtt_quickstart_topic",
                                                                                MqttQos.AtLeastOnce);
            topicObservable.Subscribe(
                msg => Console.WriteLine(String.Format("Msg Received on '{0}' is '{1}'", msg.Topic, msg.Payload)));
            topicObservable.Subscribe(
                msg => Console.WriteLine(String.Format("Second Msg Received on '{0}' is '{1}'", msg.Topic, msg.Payload)));


            Console.ReadKey();
        }
Exemplo n.º 4
0
        public void connect()
        {
            // SUBSCRIBER

            // create client instance
            MqttClient client = new MqttClient(IPAddress.Parse(MQTT_BROKER_ADDRESS));

            // register to message received
            client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;

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

            // subscribe to the topic "/home/temperature" with QoS 2
            client.Subscribe(new string[] { "/home/temperature" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
        }
Exemplo n.º 5
0
        static void Main(string[] args)
        {
            System.Console.WriteLine("start");
            // Create Client instance
            MqttClient myClient = new MqttClient("192.168.28.128");

            // Register to message received
            myClient.MqttMsgPublishReceived += client_recievedMessage;

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

            myClient.Connect(clientId);

            // Subscribe to topic
            myClient.Subscribe(new String[] { "meas/#" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
            // myClient.Subscribe(new String[] { "paine" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
            // myClient.Subscribe(new String[] { "lämpö" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
            System.Console.ReadLine();
        }
    public void PublishImageData()
    {
        client = new MqttClient(IPAddress.Parse(mqttTest.IPADRES), 1883, false, null);
        string clientId = Guid.NewGuid().ToString();

        client.Connect(clientId, "unityimage", "", true, 5);
        byte[] rawbytes = TheTexture.EncodeToPNG();
        s++;
        Debug.Log("Wysyłanie długość" + rawbytes.Length.ToString());
        if (client != null && client.IsConnected)
        {
            client.Publish(EXTERNALDEVICE_IMAGEDATA, rawbytes, MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE, true);
            Debug.Log("Polaczony");
        }
        else
        {
            Debug.Log("Nie udało się wysłać");
        }
    }
Exemplo n.º 7
0
    // Use this for initialization
    void Start()
    {
        time_curr = publish_speed;
        //MQTT SETUP
        IPHostEntry host;

        host = Dns.GetHostEntry("marcelochsendorf.com");
        IPAddress ip = IPAddress.Parse("18.194.104.195");

        if (host.AddressList.Length > 0)
        {
            ip = host.AddressList [0];
            Debug.Log("IP ADDRES FOUND BY DNS LOOKUP - marcelochsendorf.com");
        }


        client = new MqttClient(ip, 1883, false, null);
        client.Connect("1337");         //TODO CHANGE
    }
        static void SendTestMessage(Configuration.Mqtt mqttconfig)
        {
            mqttClient = new MqttClient(mqttconfig.broker);

            Sensor.Computer computer = new Sensor.Computer();

            Hass.Component.Sensor computersensor = new Hass.Component.Sensor(configuration.hass.uniqueid_base_prefix, "hardware_memory");
            computersensor.SetState(computer.GetMemoryUsage());

            string topic   = computersensor.StateTopic;
            string payload = computersensor.Payload;

            Console.WriteLine(topic);
            Console.WriteLine(payload);

            mqttClient.MqttMsgPublished += MqttClient_MqttMsgPublished;
            mqttClient.Connect(mqttconfig.clientid, mqttconfig.username, mqttconfig.password);
            mqttClient.Publish(topic, Encoding.ASCII.GetBytes(payload), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
        }
Exemplo n.º 9
0
        static void Main(string[] args)
        {
            System.Console.WriteLine("Hello, World!");
            // Create Client instance
            myClient = new MqttClient("iot.eclipse.org");


            // Register to message received
            myClient.MqttMsgPublishReceived += client_recievedMessage;
            myClient.MqttMsgPublished       += MyClient_MqttMsgPublished;

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

            myClient.Connect(clientId);

            // Subscribe to topic
            myClient.Subscribe(new String[] { "/master" }, new byte[] { MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE });
            System.Console.ReadLine();
        }
Exemplo n.º 10
0
        private void receiveSensorData()
        {
            try
            {
                m_cClient = new MqttClient("127.0.0.1");
                m_cClient.Connect(Guid.NewGuid().ToString());
                if (!m_cClient.IsConnected)
                {
                    Console.WriteLine("Error connecting to message broker...");
                    return;
                }

                m_cClient.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 11
0
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                client = new MqttClient(GetCurrentIP());
                
                client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;

                clientId = Guid.NewGuid().ToString();
                client.Connect(clientId);

                client.Subscribe(new string[] { Topic }, new byte[] { 2 });   // we need arrays as parameters because we can subscribe to different topics with one call
                listBox1.Items.Add("Connected to " + Topic);
            }
            catch (Exception ex)
            {
                listBox1.Items.Add(ex.Message);
            }
        }
Exemplo n.º 12
0
        public void initMQTT()
        {
            // create client instance
            client = new MqttClient("server.drewes-webdesign.nl", 1883, false, MqttSslProtocols.None);

            // register to message received
            client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;

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

            client.Connect(clientId, "inf2g", "!_pass12", true, 60);

            // subscribe to the topic "/home/temperature" with QoS 2
            client.Subscribe(new string[] { "POC/temperature" }, new byte[] { MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE });
            client.Subscribe(new string[] { "POC/humidity" }, new byte[] { MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE });
            client.Subscribe(new string[] { "POC/humidity" }, new byte[] { MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE });
            client.Subscribe(new string[] { "/app/present/#" }, new byte[] { MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE });
            client.Subscribe(new string[] { "/app/pair/request" }, new byte[] { MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE });
        }
Exemplo n.º 13
0
        public static void SetMqttClient()
        {
            try
            {
                if (MqttClient == null)
                {
                    MqttClient = new MqttClient("192.168.1.2");
                    byte code = MqttClient.Connect(Guid.NewGuid().ToString(), "hass", "3Erfoom1992");
                    LogHelper.Log($"MQTT Client is {MqttClient.IsConnected}: {MqttClient}", "info");
                    MqttClient.MqttMsgPublishReceived += mqttClient_recievedMessage;

                    MqttClient.Subscribe(new String[] { "homeassistant/light/axolotllight/set" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
                }
            }
            catch (Exception e)
            {
                LogHelper.Log(e.Message, "error");;
            }
        }
Exemplo n.º 14
0
        private async void Setup()
        {
            this.hat = await GIS.FEZHAT.CreateAsync();

            this.hat.D2.Color = GIS.FEZHAT.Color.Black;
            this.hat.D3.Color = GIS.FEZHAT.Color.Black;


            //mqtt
            if (client == null)
            {
                // create client instance
                MQTT_BROKER_ADDRESS = "cloud.makestro.com";
                client = new MqttClient(MQTT_BROKER_ADDRESS);
                string clientId = Guid.NewGuid().ToString();
                client.Connect(clientId, "mifmasterz", "123qweasd");
                SubscribeMessage();
            }
        }
Exemplo n.º 15
0
    // Start is called before the first frame update
    void Start()
    {
        client = new MqttClient(brokerEndPoint, brokerPort, false, null);
        client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
        string clientId = Guid.NewGuid().ToString();

        client.Connect(clientId);

        client.Subscribe(new string[] { temperatureTopic }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
        client.Subscribe(new string[] { hourTopic }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });

        if (dayState)
        {
            for (int i = 0; i < lights.Length; i++)
            {
                lights[i].enabled = false;
            }
        }
    }
Exemplo n.º 16
0
        public MainPage()
        {
            this.InitializeComponent();
            UpdateTime();
            UpdateTemp();
            UpdateMovements();
            datetimeUpdateTimer          = new DispatcherTimer();
            datetimeUpdateTimer.Tick    += DatetimeUpdateTimer_Tick;
            datetimeUpdateTimer.Interval = TimeSpan.FromMinutes(1);
            datetimeUpdateTimer.Start();

            dayUpdateTimer          = new DispatcherTimer();
            dayUpdateTimer.Tick    += DayUpdateTimer_Tick;
            dayUpdateTimer.Interval = TimeSpan.FromHours(1);
            dayUpdateTimer.Start();

            mqttClient = new MqttClient("10.10.10.1");
            mqttClient.Connect("mami");
            mqttClient.MqttMsgPublishReceived += MqttClient_MqttMsgPublishReceived;
            //, "/smarthome/mirrormain"

            var bs = new byte[] { uPLibrary.Networking.M2Mqtt.Messages.MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE };


            mqttClient.Subscribe(new[] { "/smarthome/mirror" }, bs);
            mqttClient.Subscribe(new[] { "/smarthome/mirrormain" }, bs);
            mqttClient.Subscribe(new[] { "/smarthome/news" }, bs);
            UpdateSun();
            //tbIcon.FontFamily = new FontFamily("");

            GetFeed();
            UpdateForecast();
            UpdateMessage();

            initializeSpeechRecognizer();

            synthesizer = new SpeechSynthesizer();

            speechContext           = ResourceContext.GetForCurrentView();
            speechContext.Languages = new string[] { SpeechSynthesizer.DefaultVoice.Language };

            speechResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("LocalizationTTSResources");
        }
Exemplo n.º 17
0
        public void Connect()
        {
            if (!_client.IsConnected)
            {
                // PCのユーザ名とtopicをclient idに使う
                string id = Path.GetFileName(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile));
                id += _channerl;

                _client.Connect(id);

                while (!_client.IsConnected)
                {
                    Task.Delay(100 /* ms */);
                }

                _client.MqttMsgPublishReceived += Receve;
                _client.Subscribe(new string[] { _channerl }, new byte[] { 2 });
            }
        }
Exemplo n.º 18
0
        static void Main(string[] args)
        {
            ReadFromExcel(AppDomain.CurrentDomain.BaseDirectory + "FicheiroConfBroker.xlsx");

            MqttClient client = null;

            string[] topics = { "Data", "Parks" };

            client = new MqttClient(ip);
            client.Connect(Guid.NewGuid().ToString());
            if (!client.IsConnected)
            {
                Console.WriteLine("Unable to connect with the broker");
            }
            client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
            client.MqttMsgUnsubscribed    += Client_MqttMsgUnsubscribed;
            byte[] qosLevels = { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE };
            client.Subscribe(topics, qosLevels);
        }
Exemplo n.º 19
0
        // Use this for initialization

        void Start()
        {
            LogSystem.InstallDefaultReactors();
            Runnable.Run(CreateService());

            // create client instance
            client = new MqttClient(IPAddress.Parse(brokerIpAddress), brokerPort, false, null);

            // register to message received
            //client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;

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

            client.Connect(clientId);

            // subscribe to the topic "/home/temperature" with QoS 2
            client.Subscribe(new string[] { temperatureTopic }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
            client.Subscribe(new string[] { lightTopic }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
        }
Exemplo n.º 20
0
        private void Form4_Load(object sender, EventArgs e)
        {
            if (ChannelServices.RegisteredChannels.Length == 0)
            {
                ChannelServices.RegisterChannel(new TcpChannel());

                iRemoting = (IMsg)Activator.GetObject(typeof(IMsg), "tcp://localhost:9501/RemoteObjectURI9501");
            }

            _Pwd.ConnectionKey = "123";
            //  m3_status_timer.Enabled = true;
            // m3_mqtt_timer.Enabled = true;

            //--------------------------------------------------------
            client = new MqttClient("liantw.com"); //MQTTServer在本機
            //client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;//當接收到訊息時處理函式
            clientId = Guid.NewGuid().ToString();  //取得唯一碼
            client.Connect(clientId);              //建立連線
        }
Exemplo n.º 21
0
        public void Start()
        {
            Log($"Starting XBeeMqtt serialPortName={serialPortName} baudRate={baudRate} mqttBrokerHost={mqttBrokerHost} mqttBrokerPort={mqttBrokerPort}");

            port = new SerialPort(serialPortName, baudRate);
            port.DataReceived += Port_DataReceived;
            port.Open();

            bee = new XBee();
            bee.setSerial(port);

            mqttClient = new MqttClient(mqttBrokerHost, mqttBrokerPort, false, null, null, MqttSslProtocols.None);
            string clientId = Guid.NewGuid().ToString();

            mqttClient.Connect(clientId);

            mqttClient.MqttMsgPublishReceived += MqttClient_MqttMsgPublishReceived;
            mqttClient.Subscribe(new string[] { "/cmd/TankWaterer/#" }, new byte[] { 0 });
        }
Exemplo n.º 22
0
        static void DeviceListenFromClientDevice(object param)
        {
            string     deviceName = param.ToString();
            MqttClient mqttClient = new MqttClient(mqttServerAddress, 61613, false, MqttSslProtocols.None, null, null);

            mqttClient.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
            try
            {
                string clientId = "Server_" + Guid.NewGuid().ToString();
                mqttClient.Connect(clientId, "admin", "passwordpassword");//, client.BaiDuYunName, client.BaiDuYunPwd
                mqttClient.Subscribe(new string[] { deviceName + "_WorkState" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
            }
            catch (Exception ee)
            {
                Action <string> log = new Action <string>(WriteErrLog);
                log(ee.Message + ee.StackTrace);
                Console.WriteLine("mqtt error:" + ee.Message);
            }
        }
Exemplo n.º 23
0
        static void Main(string[] args)
        {
            Console.WriteLine("start publishing");
            // Create Client instance
            MqttClient myClient = new MqttClient("192.168.28.129");

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

            myClient.Connect(clientId);

            for (int i = 0; i < 100; i++)
            {
                double temperature = 20 + 5 * Math.Sin(i / 10.0);
                string strValue    = Convert.ToString(temperature);

                myClient.Publish("measurements/temperature", Encoding.UTF8.GetBytes(strValue));
                Thread.Sleep(1000);
            }
        }
Exemplo n.º 24
0
        async void SetupMqtt(bool restart = false)
        {
            if (restart)
            {
                MqttClient.Disconnect();
            }
            MqttClient = new MqttClient(IPBrokerAddress);

            // register a callback-function (we have to implement, see below) which is called by the library when a message was received
            MqttClient.Subscribe(new string[] { ControlTopic }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
            MqttClient.MqttMsgPublishReceived += client_MqttMsgPublishReceived;

            var connected = MqttClient.IsConnected;

            //while (!connected && !cancellationToken.IsCancellationRequested)
            //{
            try
            {
                MqttClient.Connect(clientId, ClientUser, ClientPass);
                await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() =>
                {
                    TxtStatus.Text = "MQTT is connected";
                });

                NeedToReconnect = false;
                Console.WriteLine("MQTT is connected");
            }
            catch
            {
                await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() =>
                {
                    TxtStatus.Text = $"Fail to connect MQTT at {IPBrokerAddress}";
                });

                Console.WriteLine($"No connection to...{IPBrokerAddress}");
                NeedToReconnect = true;
            }
            connected = MqttClient.IsConnected;
            //return connected;
            //var token = new CancellationToken();
            //await TryReconnectAsync(token);
            //MqttClient.Connect(clientId, ClientUser, ClientPass);
        }
Exemplo n.º 25
0
    // Use this for initialization
    void Start()
    {
        // create client instance
        client = new MqttClient(IPAddress.Parse("127.0.0.1"), 1883, false, null);

        // register to message received
        client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;

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

        client.Connect(clientId);

        // subscribe to the topic "/home/temperature" with QoS 2
        client.Subscribe(new string[] { "hello/world" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
        //var init_ang = vrcam.transform.rotation.eulerAngles;
        //init_roll = init_ang[2];
        //init_pitch = init_ang[0];
        //init_yaw = init_ang[1];
    }
Exemplo n.º 26
0
    // Start is called before the first frame update
    void Start()
    {
        client = new MqttClient("broker.hivemq.com", 1883, false, null);

        // register to message received
        client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;

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

        client.Connect(clientId);

        // subscribe to the topic "/home/temperature" with QoS 2
        client.Subscribe(new string[] { "/AHXPD/arduino" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });

        //string strValue = Convert.ToString(value);

        // publish a message on "/home/temperature" topic with QoS 2
        //client.Publish("/home/temperature", Encoding.UTF8.GetBytes(strValue), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE);
    }
Exemplo n.º 27
0
        /// <summary>
        /// Main actions
        /// </summary>
        private void Run()
        {
            var pluginPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ServerConfig.Instance.PluginPath);

            pluginHandler = new PluginHandler(pluginPath);
            bool connected = false;

            if (pluginHandler.Init() == false)
            {
                return;
            }

            try
            {
                MqttClient = new MqttClient(ServerConfig.Instance.BrokerIP);
                MqttClient.MqttMsgPublishReceived += MqttDataRecieved;
                MqttClient.Connect(ServerConfig.Instance.ClientID);
                MqttClient.Subscribe(new string[] { ServerConfig.Instance.TopicData }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
                connected = true;
            }
            catch (Exception e)
            {
                System.Console.WriteLine($"{nameof(Run)}: Cannot connect to broker [{ServerConfig.Instance.BrokerIP}] => [{e.Message}]");
            }

            if (connected)
            {
                do
                {
                    while (!System.Console.KeyAvailable)
                    {
                        TFUtils.WaitNMilliseconds(ServerConfig.Instance.Delay);
                    }
                } while (System.Console.ReadKey(true).Key != ConsoleKey.Escape);
            }

            pluginHandler.Shutdown();

            if (connected)
            {
                MqttClient.Disconnect();
            }
        }
Exemplo n.º 28
0
        static void Main(string[] args)
        {
            System.Console.WriteLine("start publishing pressure");
            // Create Client instance
            MqttClient myClient = new MqttClient("192.168.28.128");

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

            myClient.Connect(clientId);

            for (int i = 0; i < 100; i++)
            {
                double pressure = 1024 + 5 * Math.Cos(i / 10.0);
                string strValue = Convert.ToString(pressure);
                Console.WriteLine("Pressure: " + pressure);
                myClient.Publish("measurements/pressure", Encoding.UTF8.GetBytes(strValue));
                Thread.Sleep(1000);
            }
        }
Exemplo n.º 29
0
        private void MqttConnect()
        {
            MqttClient client;
            string     username = "******";
            string     password = "******";
            string     host     = "m14.cloudmqtt.com";
            int        port     = 14953;
            ushort     msgId;

            client = new MqttClient(host, port, false, MqttSslProtocols.None);
            byte code = client.Connect(Guid.NewGuid().ToString(), username, password);

            client.Subscribe(new string[] { "Robot2" }, new byte[] { 0 });
            msgId = client.Publish("Robot2",                                                             // topic
                                   Encoding.UTF8.GetBytes("Mqtt đã kết nối với Raspberry thành công !"), // message body
                                   MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE,                                   // QoS level
                                   false);                                                               // retained
            client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
        }
 private bool ConnectToBrocker()
 {
     try
     {
         mqttClient.Connect(Guid.NewGuid().ToString());
     }
     catch (MqttConnectionException e)
     {
         var msg = "Cannot connect to the server , chech Params";
         MessageBox.Show(msg + " __ " + e.Message);
         return(false);
     }
     catch (Exception exx)
     {
         MessageBox.Show("MQTT Connetion " + exx.Message);
         return(false);
     }
     return(IsConnected);
 }
Exemplo n.º 31
0
        void SetupMqtt()
        {
            string IPBrokerAddress = ConfigurationManager.AppSettings["MqttHost"];
            string ClientUser      = ConfigurationManager.AppSettings["MqttUser"];
            string ClientPass      = ConfigurationManager.AppSettings["MqttPass"];


            MqttClient = new MqttClient(IPBrokerAddress);

            // register a callback-function (we have to implement, see below) which is called by the library when a message was received
            MqttClient.MqttMsgPublishReceived += client_MqttMsgPublishReceived;

            // use a unique id as client id, each time we start the application
            var clientId = "bmc-aquaponic";//Guid.NewGuid().ToString();

            MqttClient.Connect(clientId, ClientUser, ClientPass);
            MqttClient.Subscribe(new string[] { DataTopic, ControlTopic }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
            Console.WriteLine("MQTT is connected");
        } // this code runs when a message was received
Exemplo n.º 32
0
    // Use this for initialization
    void Start()
    {
        Arid = "";

        // create client instance
        //zyxel client = new MqttClient(IPAddress.Parse("192.168.2.2"), 1883, false, null);
        client = new MqttClient(IPAddress.Parse("192.168.2.2"), 1883, false, null);
        // register to message received
        client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;

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

        client.Connect(clientId);

        // subscribe to the topic "/home/temperature" with QoS 2
        client.Subscribe(new string[] { "/HOME/KEP/OY" }, new byte[] { MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE });

        client.Publish("/HOME/KEP/KU", System.Text.Encoding.UTF8.GetBytes("<" + Kuid + "=Myid?;|"), MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE, false);
    }
Exemplo n.º 33
0
        public void Connect(bool async = true)
        {
            if (!_myMqttClient.IsConnected)
            {
                try
                {
                    _myMqttClient.Connect(_clientId);
                }
                catch
                {
                    asyncReconnect();
                }
            }

            if (OnConnectionStateChange != null)
            {
                OnConnectionStateChange(_myMqttClient.IsConnected);
            }
        }
Exemplo n.º 34
0
    // Use this for initialization
    void Start()
    {
        notificationText.text = "";
        //hashedPass = PlayerPrefs.GetString("hashedPass");

        mqttClient = new MqttClient(IPAddress.Parse("129.16.155.34"), 1883, false, null);
        string clientId = Guid.NewGuid().ToString();

        mqttClient.Connect(clientId, "theHub", "theHub");

        ////creating the warning reddish color
        //warningColor.r = 104;
        //warningColor.g = 1;
        //warningColor.b = 1;
        ////creating the approval yellowish color
        //approvalColor.r = 240;
        //approvalColor.g = 255;
        //approvalColor.b = 0;
    }
Exemplo n.º 35
0
 public NetHelper MqttService(string server, int port, string clientId)
 {
     mqttClient = new MqttClient(server, port, clientId);
     if (this.networkCredential != null)
     {
         mqttClient.Connect(this.networkCredential.UserName, this.networkCredential.Password);
     }
     else
     {
         mqttClient.Connect();
     }
     return this;
 }
Exemplo n.º 36
0
        /// <summary>
        /// Connects to the specified mqtt server.
        /// </summary>
        /// <param name="server"></param>
        /// <param name="port"></param>
        /// <returns>The state of the connection.</returns>
        public ConnectionState Connect(string server, short port)
        {
            client = new MqttClient (server, port, Options.ClientIdentifier);
            client.MessageAvailable += ClientMessageAvailable;
            syncContext = SynchronizationContext.Current;

            Trace.WriteLine ("Connecting to " + server + ":" + port.ToString ());

            return client.Connect();
        }
Exemplo n.º 37
0
        // This method is run when the mainboard is powered up or reset.
        void ProgramStarted()
        {
            //setup wifi
            wifiRS21.DebugPrintEnabled = true;
            NetworkChange.NetworkAvailabilityChanged += NetworkChange_NetworkAvailabilityChanged;           // setup events
            NetworkChange.NetworkAddressChanged += NetworkChange_NetworkAddressChanged;
            wifiRS21.NetworkDown += new GT.Modules.Module.NetworkModule.NetworkEventHandler(wifi_NetworkDown);
            wifiRS21.NetworkUp += new GT.Modules.Module.NetworkModule.NetworkEventHandler(wifi_NetworkUp);
            // use the router's DHCP server to set my network info
            if (!wifiRS21.NetworkInterface.Opened)
                wifiRS21.NetworkInterface.Open();
            if (!wifiRS21.NetworkInterface.IsDhcpEnabled)
            {
                wifiRS21.UseDHCP();
                wifiRS21.NetworkInterface.EnableDhcp();
                wifiRS21.NetworkInterface.EnableDynamicDns();
            }
            // look for avaiable networks
            var scanResults = wifiRS21.NetworkInterface.Scan();

            // go through each network and print out settings in the debug window
            foreach (GHI.Networking.WiFiRS9110.NetworkParameters result in scanResults)
            {
                Debug.Print("****" + result.Ssid + "****");
                Debug.Print("ChannelNumber = " + result.Channel);
                Debug.Print("networkType = " + result.NetworkType);
                Debug.Print("PhysicalAddress = " + GetMACAddress(result.PhysicalAddress));
                Debug.Print("RSSI = " + result.Rssi);
                Debug.Print("SecMode = " + result.SecurityMode);
            }

            // locate a specific network
            GHI.Networking.WiFiRS9110.NetworkParameters[] info = wifiRS21.NetworkInterface.Scan(SSID);
            if (info != null)
            {
                wifiRS21.NetworkInterface.Join(info[0].Ssid, KeyWifi);
                wifiRS21.UseThisNetworkInterface();
                bool res = wifiRS21.IsNetworkConnected;
                Debug.Print("Network joined");
                Debug.Print("active:" + wifiRS21.NetworkInterface.ActiveNetwork.Ssid);
               }

            Debug.Print("Program Started");

            Mobil = new MobilRemote();
            GT.Timer timer = new GT.Timer(100);
            timer.Tick += (x) =>
            {
                if (isNavigating) return;
                isNavigating = true;
                ledStrip.TurnAllLedsOff();

                switch (Mobil.Arah)
                {
                    case MobilRemote.ArahJalan.Maju:
                        motorDriverL298.SetSpeed(MotorDriverL298.Motor.Motor1, 1);
                        motorDriverL298.SetSpeed(MotorDriverL298.Motor.Motor2, 1);
                        ledStrip.TurnAllLedsOn();
                        break;
                    case MobilRemote.ArahJalan.Mundur:
                        motorDriverL298.SetSpeed(MotorDriverL298.Motor.Motor1, -0.7);
                        motorDriverL298.SetSpeed(MotorDriverL298.Motor.Motor2, -0.7);
                        ledStrip.TurnLedOn(2);
                        ledStrip.TurnLedOn(3);
                        ledStrip.TurnLedOn(4);
                        break;
                    case MobilRemote.ArahJalan.Kiri:
                        motorDriverL298.SetSpeed(MotorDriverL298.Motor.Motor1, -0.7);
                        motorDriverL298.SetSpeed(MotorDriverL298.Motor.Motor2, 0.7);
                        ledStrip.TurnLedOn(0);
                        ledStrip.TurnLedOn(1);
                        break;
                    case MobilRemote.ArahJalan.Kanan:
                        motorDriverL298.SetSpeed(MotorDriverL298.Motor.Motor1, 0.7);
                        motorDriverL298.SetSpeed(MotorDriverL298.Motor.Motor2, -0.7);
                        ledStrip.TurnLedOn(5);
                        ledStrip.TurnLedOn(6);
                        break;
                    case MobilRemote.ArahJalan.Stop:
                        motorDriverL298.SetSpeed(MotorDriverL298.Motor.Motor1, 0);
                        motorDriverL298.SetSpeed(MotorDriverL298.Motor.Motor2, 0);

                        break;

                }
                isNavigating = false;
            };
            timer.Start();
            while (!wifiRS21.IsNetworkConnected || wifiRS21.NetworkInterface.IPAddress=="0.0.0.0")
            {
                Thread.Sleep(100);
            }
            client = new MqttClient(MQTT_BROKER_ADDRESS);
            string clientId = Guid.NewGuid().ToString();
            client.Connect(clientId);
            SubscribeMessage();
        }
Exemplo n.º 38
0
 public NetHelper MqttService(string server, int port, string username, string password, string clientId)
 {
     mqttClient = new MqttClient(server, port, clientId);
     mqttClient.Connect(username, password);
     return this;
 }
Exemplo n.º 39
0
 private void Connect()
 {
     Disconnect();
     mqttClient = new MqttClient(endPoint.Address, endPoint.Port, endPoint.ClientId);
     if (this.networkCredential != null)
     {
         mqttClient.Connect(this.networkCredential.UserName, this.networkCredential.Password);
     }
     else
     {
         mqttClient.Connect();
     }
 }
Exemplo n.º 40
0
 public static void Connect()
 {
     mqttClient = new MqttClient(Settings.Default.MqttServerName, Settings.Default.MqttServerPort, Settings.Default.MqttClientIdentifier);
     mqttClient.Connect();
 }