Ejemplo n.º 1
1
        public bool MqttConnect(string serveur, string clientid, string username = null, string password = null, bool willRetain = false, byte willQosLevel = 1, bool willFlag = false, string willTopic = null, string willMessage = null, bool cleanSession = true, ushort keepAlivePeriod = 60)
        {
            // create client instance 
            client = new MqttClient(serveur);
            client.MqttMsgSubscribed += Client_MqttMsgSubscribed;
            client.MqttMsgUnsubscribed += Client_MqttMsgUnsubscribed;
            // register to message received 
            client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
            //string clientId = Guid.NewGuid().ToString();
            if (username != null)
            {
                if (willFlag)
                    client.Connect(clientid, username, password, willRetain, willQosLevel, willFlag, willTopic, willMessage, cleanSession, keepAlivePeriod);
                else
                    client.Connect(clientid, username, password);
            }
            else
                client.Connect(clientid);
            //client.Unsubscribe(new string[] { "/#" });


            if (OnConnected != null)
                OnConnected(this, new EventArgs());
            return client.IsConnected;
        }
Ejemplo n.º 2
1
        public void TaskRun()
        {
            Trace.t(cc.Norm, "Vision TaskRun started");

            Program.Pilot.Send(new { Cmd = "SRVO", Value = servoPosition });

            if (!Program.PilotString.Contains("com"))
            {
                Mq = new MqttClient(Program.PilotString);
                Trace.t(cc.Norm, string.Format("vision connecting to MQTT @ {0}", Program.PilotString));
                Mq.Connect("MMPXY");
                Trace.t(cc.Norm, "vision connected");

                Mq.MqttMsgPublishReceived += PixyMqRecvd;
                Mq.Subscribe(new string[] { "robot1/pixyCam" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
            }

            SubState = VisionState.Run;

            // if finished, exit task
            while (Program.State != RobotState.Shutdown)
            {
                if (SubState == VisionState.Run)
                    if (coneFlag != ConeState.Lost && DateTime.Now > lastSeenTime + lostWaitTime)
                        LostCone();

                Program.Delay(100).Wait();
            }

            Trace.t(cc.Warn, "Vision exiting");
            SubState = VisionState.Idle;
            if (Mq != null && Mq.IsConnected)
                Mq.Disconnect();
        }
        private async void MainPage_Loaded(object s, RoutedEventArgs e)
        {
            disconnected();

            _mqtt = new MqttClient("m11.cloudmqtt.com", 12360, false, MqttSslProtocols.None);
            _mqtt.ConnectionClosed += (sender, args) =>
            {
                disconnected();
            };
            _mqtt.MqttMsgSubscribed += (sender, args) =>
            {
                connected();
            };

            _mqtt.MqttMsgPublishReceived += (sender, args) =>
            {
                var msg = Encoding.ASCII.GetString(args.Message);

                switch (msg)
                {
                    case "happy":
                    {
                        _animator.drawFrame(0);
                    }
                    break;
                    case "sad":
                    {
                        _animator.drawFrame(1);
                    }
                    break;
                    case "indifferent":
                    {
                        _animator.drawFrame(2);
                    }
                    break;
                }

                _clear.schedule(() => _backpack.clear(), 5000);
            };

            Task.Run(() =>
            {

                _mqtt.Connect("1", "mike", "cloudmqtt");
                _mqtt.Subscribe(new[] {"mqttdotnet/pubtest/#"}, new[] {MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE});
            });

            _backpack = new Adafrut8x8LEDBackpack();
            await _backpack.initializeAsync();

            _animator = new BackpackAnimator(_backpack, EmoticonsFrameGenerator.getAnimationFrames());
        }
Ejemplo n.º 4
0
        static void Main(string[] args)
        {
            try
            {
                localClient = new uPLibrary.Networking.M2Mqtt.MqttClient("172.30.28.5");
                string clientId = Guid.NewGuid().ToString();
                localClient.Connect(clientId);

                XmlDocument doc = new XmlDocument();
                doc.Load("\\Users\\Rodric\\Desktop\\values.xml");

                XmlNodeList elementList = doc.GetElementsByTagName("book");
                XmlNode node = elementList[1];

                for (int i = 0; i < elementList.Count; i++)
                {
                    string loc = elementList[i]["location"].InnerText;
                    string temp = elementList[i]["temperature"].InnerText;
                    string time = elementList[i]["time"].InnerText;

                    string allData = loc + ";" + temp + ";" + time;
                    byte[] data = Encoding.UTF8.GetBytes(allData);

                    localClient.Publish("/home/temperature", Encoding.UTF8.GetBytes(allData), uPLibrary.Networking.M2Mqtt.Messages.MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine("Connection Failed: " + ex.Message);
            }
        }
Ejemplo n.º 5
0
    protected void InitMqtt()
    {
        var client = new uPLibrary.Networking.M2Mqtt.MqttClient(appState.Config.MqttServer, int.Parse(appState.Config.MqttPort), false);

        try
        {
            client.Connect("holoclient");
        }
        catch (Exception e)
        {
            Debug.LogError("Error connecting to mqtt");
        }
        if (client.IsConnected)
        {
            // register to message received
            client.MqttMsgPublishReceived += (sender, e) =>
            {
                UnityMainThreadDispatcher.Instance().Enqueue(() =>
                {
                    var msg = Encoding.UTF8.GetString(e.Message);
                    switch (e.Topic)
                    {
                    case "view":
                        SetView(msg);
                        break;
                    }
                    GameObject _3dText = GameObject.Find("tbTemp");
                    _3dText.GetComponent <TextMesh>().text = msg;
                });
            };

            //// subscribe to the topic "/home/temperature" with QoS 2
            client.Subscribe(new string[] { "view" }, new byte[] { uPLibrary.Networking.M2Mqtt.Messages.MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
        }
    }
Ejemplo n.º 6
0
 // Use this for initialization
 void Start()
 {
     client = new MqttClient(MQTT_BROKER_ADDRESS);
     client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
     client.Connect("unity");
     client.Subscribe(new string[] { "doebi/#" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
 }
Ejemplo n.º 7
0
        static void Main(string[] args)
        {
            Console.WriteLine("***********PUBLISHER***********");

            //MqttClient client = new MqttClient("dev.rabbitmq.com", 1883, false, null);
            MqttClient client = new MqttClient("localhost", 1883, false, null);
            var state = client.Connect("Client993", "guest", "guest", false, 0, false, null, null, true, 60);

            string strValue = Convert.ToString("On");

            while (true)
            {
                // publish a message with command to turn LED on
                client.Publish("ABC12345/led", Encoding.UTF8.GetBytes(strValue), MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE, true);
                mcount++;

                Console.WriteLine(String.Format("Message {0} published.", mcount.ToString()));

                Console.WriteLine("Press enter to send Off command...");
                Console.ReadLine();

                // publish a message with command to turn LED on
                client.Publish("ABC12345/led", Encoding.UTF8.GetBytes("Off"), MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE, true);
                mcount++;

                Console.WriteLine(String.Format("Message {0} published.", mcount.ToString()));

                Console.WriteLine("Press enter to send On comamnd...");
                Console.ReadLine();
            }
        }
Ejemplo n.º 8
0
        public static void Main()
        {
            led = new OutputPort(Pins.ONBOARD_LED, false);

            Microsoft.SPOT.Hardware.Utility.SetLocalTime(new DateTime(2014, 4, 13));

            Thread.Sleep(10000);

            var networkInterface = NetworkInterface.GetAllNetworkInterfaces()[0];

            if (networkInterface.IPAddress == IPAddress.Any.ToString())
            {

                networkInterface.EnableDhcp();
                networkInterface.EnableDynamicDns();
                networkInterface.RenewDhcpLease();
            }

            // create client instance
            //MqttClient client = new MqttClient("dev.rabbitmq.com", 1883, false, null);
            MqttClient client = new MqttClient("206.205.188.34", 1883, false, null);

            // register to message received
            client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
            client.MqttMsgSubscribed += client_MqttMsgSubscribed;
            client.MqttMsgUnsubscribed += client_MqttMsgUnsubscribed;
            client.MqttMsgPublished += client_MqttMsgPublished;

            // subscribe to the topic
            client.Subscribe(new string[] { "ABC12345/led" }, new byte[] { MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE });

            //Console.ReadLine();
            var state = client.Connect("ABC12345", "guest", "guest", false, 0, false, null, null, true, 60);
        }
Ejemplo n.º 9
0
 public MQTTInbound(MqttClient connection, String sitewhereTopic, String commandTopic, IAgentCommandProcessor processor, ISiteWhereEventDispatcher dispatcher)
 {
     this.connection     = connection;
     this.sitewhereTopic = sitewhereTopic;
     this.commandTopic   = commandTopic;
     this.processor      = processor;
     this.dispatcher     = dispatcher;
 }
Ejemplo n.º 10
0
 public MqttWorker(string brokerHostname, string[] nodes)
 {
     client = new MqttClient(brokerHostname);
     client.Connect(Guid.NewGuid().ToString());
     client.Subscribe(nodes.Select(n => $"nodes/{n}/packets").ToArray(), nodes.Select(n => MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE).ToArray());
     client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
     WorkerSupportsCancellation = true;
 }
Ejemplo n.º 11
0
        public MQTTConnection(string brokerHostName, int brokerPort, string username, string password)
        {
            _username = username;
            _password = password;
            _clientId = "charl" + Guid.NewGuid().ToString().Substring(0, 6);

            _client = new MqttClient(brokerHostName, brokerPort, false, null);
            _client.MqttMsgPublishReceived += OnClientOnMqttMsgPublishReceived;
        }
 public MQTTDeviceManager(string broker,int port)
 {
     MQTTRoot = "/MQTTDevice";
     DeviceDiscoverTopic = MQTTRoot + "/Discover";
     DeviceSigninTopic = MQTTRoot + "/SignIn";
     DeviceDiscoverCallbackTopic = MQTTRoot + "/AllJoyn/Devices";
     client = new MqttClient(broker,port,false,MqttSslProtocols.None);
     client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
 }
Ejemplo n.º 13
0
        public void Setup()
        {
            mqttClient = new MqttClient(IPAddress.Parse(config.AppSettings["MqttHost"]), int.Parse(config.AppSettings["MqttPort"]), false, null);
            mqttClient.MqttMsgPublished += client_MqttMsgPublished;
            mqttClient.Connect(config.AppSettings["MqttClientName"] + "-" + config.AppSettings["MqttPairingCode"], config.AppSettings["MqttUsername"], config.AppSettings["MqttPassword"]);

            lyncxClient = new LyncxClient();
            lyncxClient.AvailabilityChanged += lyncxClient_AvailabilityChanged;

            lyncxClient.Setup();
        }
Ejemplo n.º 14
0
 public IOTHub()
 {
     if (client == null)
     {
         // create client instance 
         client = new MqttClient(MQTT_BROKER_ADDRESS);
         string clientId = Guid.NewGuid().ToString();
         client.Connect(clientId, "guest", "guest");
         SubscribeMessage();
     }
 }
Ejemplo n.º 15
0
        public AdafruitIOClient(string username, string key)
        {
            _username = username;
            _key = key;

            Feed.FeedChanged += OnFeedChanged;

            _client = new MqttClient("io.adafruit.com", 1883, false, MqttSslProtocols.None);
            _client.MqttMsgPublishReceived += OnMessageReceived;

            _client.Connect(Guid.NewGuid().ToString(), _username, _key);
        }
Ejemplo n.º 16
0
        public static void Main(string[] args)
        {
            MqttClient client = new MqttClient(MQTT_BROKER_ADDRESS);

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

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

            client.Subscribe(new string[] { "/testit/now" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
        }
Ejemplo n.º 17
0
        private void Form1_Load(object sender, EventArgs e)
        {
            // create client instance
            MqttClient client = new MqttClient("test.mosquitto.org");

            client.Connect("Test VS",null,null);

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

            // publish a message on "/home/temperature" topic with QoS 2
            client.Publish("/home/temperature", Encoding.UTF8.GetBytes("test"));
        }
Ejemplo n.º 18
0
        public void Setup()
        {
            mqttClient = new MqttClient(Config.MqttHost, Config.MqttPort, false, null);
            mqttClient.Connect(Config.MqttClientId, Config.MqttUsername, Config.MqttPassword);

            Console.WriteLine("Connected: " + mqttClient.IsConnected);

            mqttClient.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
            mqttClient.MqttMsgSubscribed += client_MqttMsgSubscribed;

            mqttClient.Subscribe(new string[] { Config.MqttTopic }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
        }
Ejemplo n.º 19
0
        public bool MqttConnect(string serveur, string clientid, string username, string password, bool willRetain, byte willQosLevel, bool willFlag, string willTopic, string willMessage, bool cleanSession, ushort keepAlivePeriod)
        {
            // create client instance 
            client = new MqttClient(serveur);

            // register to message received 
            client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
            //string clientId = Guid.NewGuid().ToString();
           var res= client.Connect(clientid,  username,  password,  willRetain,  willQosLevel,  willFlag,  willTopic,  willMessage,  cleanSession,  keepAlivePeriod);
            if (OnConnected != null)
                OnConnected(this, new EventArgs());
            return client.IsConnected ;
        }
Ejemplo n.º 20
0
        public override async Task TeardownAsync()
        {
            await base.TeardownAsync();

            if (_mqttclient != null)
            {
                _mqttclient.MqttMsgPublishReceived -= Mqttclient_MqttMsgPublishReceived;
                _mqttclient.ConnectionClosed       -= MqttclientOnConnectionClosed;
                _mqttclient.Disconnect();
                _mqttclient = null;
                _methodRegistrations.Clear();
            }
        }
Ejemplo n.º 21
0
        public bool MqttConnect(string serveur, string clientid)
        {
            // create client instance 
            client = new MqttClient(serveur);

            // register to message received 
            client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
            //string clientId = Guid.NewGuid().ToString();
            client.Connect(clientid);
            if (OnConnected != null)
                OnConnected(this, new EventArgs());
            return client.IsConnected;
        }
Ejemplo n.º 22
0
        public static void Main()
        {
            netduino = NetduinoFactory.Get(config.AppSettings["LedPinType"]);
            netduino.Setup();

            mqttClient = new MqttClient(IPAddress.Parse(config.AppSettings["MqttHost"]), int.Parse(config.AppSettings["MqttPort"]), false, null);
            mqttClient.Connect(config.AppSettings["MqttClientName"] + "-" + config.AppSettings["MqttPairingCode"], config.AppSettings["MqttUsername"], config.AppSettings["MqttPassword"]);

            mqttClient.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
            mqttClient.MqttMsgSubscribed += client_MqttMsgSubscribed;

            mqttClient.Subscribe(new string[] { config.AppSettings["MqttTopic"] + config.AppSettings["MqttPairingCode"] }, new byte[] { MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE });
        }
Ejemplo n.º 23
0
    private void Start()
    {
        mqttClient = new MqttClient(mqttBrokerHost);
        mqttClient.MqttMsgPublishReceived += HandleClientMqttMsgPublishReceived;

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

        mqttClient.Connect(clientId);

        string[] topics = { mqttTopic };
        byte[]   qualityOfServiceLevels = { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE };
        mqttClient.Subscribe(topics, qualityOfServiceLevels);
    }
        public SenderIOT()
        {
            clientPub = new MqttClient(ipAddress, brokerPort, false, caCert, sslProtocol);
            clientIdPub = Guid.NewGuid().ToString();
            try
            {
                clientPub.Connect(clientIdPub);
            }
            catch (Exception)
            {

            }
        }
Ejemplo n.º 25
0
        private static void ConnectSubscribe(string APIKEY, string FEEDID)
        {
            var ip = System.Net.IPAddress.Parse("216.52.233.120"); //this is api.xively.com ...

            var mqc = new MqttClient(ip);
            mqc.Connect(APIKEY);

            byte[] qosleve = new byte[1];
            qosleve[0] = 0;
            mqc.Subscribe(new string[] { APIKEY + FEEDID }, qosleve);

            mqc.MqttMsgPublishReceived += new MqttClient.MqttMsgPublishEventHandler(mqc_MqttMsgPublishReceived);
        }
Ejemplo n.º 26
0
        public static void Main()
        {
            netduino = NetduinoFactory.Get(ConfigurationManager.LedPinType);
            netduino.Setup();

            mqttClient = new MqttClient(ConfigurationManager.MqttHost, ConfigurationManager.MqttPort, false, null);
            mqttClient.Connect(ConfigurationManager.MqttClientId, ConfigurationManager.MqttUsername, ConfigurationManager.MqttPassword);

            mqttClient.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
            mqttClient.MqttMsgSubscribed += client_MqttMsgSubscribed;

            mqttClient.Subscribe(new string[] { ConfigurationManager.MqttTopic }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
        }
Ejemplo n.º 27
0
    // Use this for initialization
    void Start()
    {
        // create client instance
        client = new MqttClient("vps.provolot.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[] { "hello/world" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
    }
        public SenderIOT(string ipAddress, int brockerPort)
        {
            this.ipAddress = ipAddress;
            this.brokerPort = brockerPort;
            clientPub = new MqttClient(ipAddress, brokerPort, false, caCert, sslProtocol);
            clientIdPub = Guid.NewGuid().ToString();
            try
            {
                clientPub.Connect(clientIdPub);
            }
            catch (Exception)
            {

            }
        }
Ejemplo n.º 29
0
        public Transmitter(string transmitterId)
        {
            if (transmitterId == null || transmitterId == "")
            {
                throw new ArgumentException("Transmitter ID cannot be null or empty");
            }

            _client = new MqttClient("mqtt.relayr.io");
            _client.MqttMsgPublishReceived += _client_MqttMsgPublishReceived;
            
            _connectedDevices = new Dictionary<string, Device>();
            DefaultQualityOfService = QualityOfService.AtLeastOnce;

            _transmitterId = transmitterId;
        }
Ejemplo n.º 30
0
        protected override void OnStart(string[] args)
        {
            t = new Timer(10000); // Timer de 10 secondes.
            t.Elapsed += new ElapsedEventHandler(t_Elapsed);
            t.Start();
            // create client instance
            MqttClient client = new MqttClient("test.mosquitto.org");

            client.Connect("SMO_IoT_WindowsService", null, null);
            // publish a message on "/home/temperature" topic with QoS 2
            IoT_Topics iot = new IoT_Topics();
            Iot_Constants IOTCONST = new Iot_Constants();
            string sTopic = iot.Get_Topics("", "");
            client.Publish("ou", Encoding.UTF8.GetBytes(sTopic));
        }
Ejemplo n.º 31
0
 private void connectBtn_Click(object sender, RoutedEventArgs e)
 {
     string clientId = Guid.NewGuid().ToString();
     try
     {
         client = new MqttClient(brokerTB.Text);
         client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
         client.Connect(clientId);
         statusTB.Text = "Successfully connected to Broker";
     }
     catch (Exception ex)
     {
         statusTB.Text = ex.Message;
     }
 }
Ejemplo n.º 32
0
 public void Stop()
 {
     try
     {
         if (_client != null)
         {
             _client.Disconnect();
             _client.MqttMsgPublishReceived -= MqttMsgPublishReceived;
             _client = null;
         }
     }
     catch (Exception ex)
     {
         Debug.Print("Failed to connect to MQTT service." + ex.Message);
     }
 }
Ejemplo n.º 33
0
        public static void FireEvent()
        {
            var client = new MqttClient("mqtt.bconimg.com");

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

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

            client.Connect(clientId);

            // subscribe to the topic "/home/temperature" with QoS 2
            client.Subscribe(
                new string[] { "merge01" },
                new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
        }
Ejemplo n.º 34
0
        static void Main(string[] args)
        {
            // create client instance
            uPLibrary.Networking.M2Mqtt.MqttClient client = new uPLibrary.Networking.M2Mqtt.MqttClient(Properties.Settings.Default.BrokerIP);

            // 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[] { "#" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
            //client.Publish("ct/1/temp", Encoding.UTF8.GetBytes("20"));
        }
Ejemplo n.º 35
0
        //------------------------------------------------------------------------------------------------------------------------
        #endregion

        #region Constructor
        //------------------------------------------------------------------------------------------------------------------------
        public AWSApplicationClient(string brokerHostName, string clientpfx, string rootcert)
        {
            //create pfc certificate from cert and private key, using openssl
            //openssl pkcs12 -export -out YOURPFXFILE.pfx -inkey -private.pem.key -in -certificate.pem.crt
            var clientCert = new X509Certificate(clientpfx);
            //this is the AWS root.pem file
            var caCert = X509Certificate.CreateFromSignedFile(rootcert);
            //create mqtt client
            _mqttClient = new MqttClient(brokerHostName,
                                            MqttSettings.MQTT_BROKER_DEFAULT_SSL_PORT,
                                            true,
                                            caCert,
                                            clientCert,
                                            MqttSslProtocols.TLSv1_2,
                                            UserCertificateValidationCallback);
        }
Ejemplo n.º 36
0
        /// <summary>
        /// 브로커 접속 테스트
        /// </summary>
        /// <param name="BrokerIP">브로커 주소</param>
        /// <param name="ClientID">클라이언트 ID</param>
        /// <returns>테스트 결과</returns>
        public static bool Test(string BrokerIP, string ClientID)
        {
            bool ret = false;

            try
            {
                var client = new uPLibrary.Networking.M2Mqtt.MqttClient(BrokerIP);
                if (client.Connect(ClientID) == 0)
                {
                    ret = true;
                    System.Threading.Thread.Sleep(500);
                    client.Disconnect();
                }
            }
            catch (Exception) { }
            return(ret);
        }
Ejemplo n.º 37
0
        static void Main(string[] args)
        {
            // create client instance
            MqttClient client = new MqttClient(IPAddress.Parse("54.94.232.13"));
            client.ProtocolVersion = MqttProtocolVersion.Version_3_1;

            string clientId = Guid.NewGuid().ToString();
            client.Connect(clientId, "hack", "12345");

            string[] topic = { "presenca" };
            byte[] qosLevels = { MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE };
            client.Subscribe(topic, qosLevels);

            client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;

            Console.WriteLine("Aguardando requisições...");
        }
Ejemplo n.º 38
0
        public override async Task InitializeAsync(DevicePluginConfigurationModel configuration)
        {
            await base.InitializeAsync(configuration);

            try
            {
                _deviceid = configuration.Properties["DeviceId"];
                string deviceSas     = configuration.Properties["DeviceSas"];
                string iotHubAddress = configuration.Properties["IotHubAddress"];
                int    iotHubPort    = Int32.Parse(configuration.Properties["IotHubPort"]);

                // init mqtt client
                _mqttclient = new uPLibrary.Networking.M2Mqtt.MqttClient(iotHubAddress, iotHubPort, true, MqttSslProtocols.TLSv1_2);
                _mqttclient.ConnectionClosed += MqttclientOnConnectionClosed;
                _mqttclient.Connect(_deviceid, $"{iotHubAddress}/{_deviceid}/api-version=2016-11-14", deviceSas);
                _mqttclient.Subscribe(new[] { $"devices/{_deviceid}/messages/devicebound/#" }, new byte[] { 0 });
                _mqttclient.Subscribe(new[] { "$iothub/methods/POST/#" }, new byte[] { 0 });
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                //TODO Log
            }
        }
Ejemplo n.º 39
0
        void Client_MqttMsgConnected(object sender, MqttMsgConnectEventArgs e)
        {
            // [v3.1.1] session present flag
            bool sessionPresent = false;
            // [v3.1.1] generated client id for client who provides client id zero bytes length
            string clientId = null;

            MqttClient client = (MqttClient)sender;

            // verify message to determine CONNACK message return code to the client
            byte returnCode = this.MqttConnectVerify(e.Message);

            // [v3.1.1] if client id is zero length, the broker assigns a unique identifier to it
            clientId = (e.Message.ClientId.Length != 0) ? e.Message.ClientId : Guid.NewGuid().ToString();

            // connection "could" be accepted
            if (returnCode == MqttMsgConnack.CONN_ACCEPTED)
            {
                // check if there is a client already connected with same client Id
                MqttClient clientConnected = this.GetClient(clientId);

                // force connection close to the existing client (MQTT protocol)
                if (clientConnected != null)
                {
                    this.CloseClient(clientConnected);
                }
            }

            try
            {
                // connection accepted, load (if exists) client session
                if (returnCode == MqttMsgConnack.CONN_ACCEPTED)
                {
                    // check if not clean session and try to recovery a session
                    if (!e.Message.CleanSession)
                    {
                        // create session for the client
                        MqttClientSession clientSession = new MqttClientSession(clientId);

                        // get session for the connected client
                        MqttBrokerSession session = this.sessionManager.GetSession(clientId);

                        // set inflight queue into the client session
                        if (session != null)
                        {
                            clientSession.InflightMessages = session.InflightMessages;
                            // [v3.1.1] session present flag
                            if (client.ProtocolVersion == MqttProtocolVersion.Version_3_1_1)
                            {
                                sessionPresent = true;
                            }
                        }

                        // send CONNACK message to the client
                        client.Connack(e.Message, returnCode, clientId, sessionPresent);

                        // load/inject session to the client
                        client.LoadSession(clientSession);

                        if (session != null)
                        {
                            // set reference to connected client into the session
                            session.Client = client;

                            // there are saved subscriptions
                            if (session.Subscriptions != null)
                            {
                                // register all subscriptions for the connected client
                                foreach (MqttSubscription subscription in session.Subscriptions)
                                {
                                    this.subscriberManager.Subscribe(subscription.Topic, subscription.QosLevel, client);

                                    // publish retained message on the current subscription
                                    this.publisherManager.PublishRetaind(subscription.Topic, clientId);
                                }
                            }

                            // there are saved outgoing messages
                            if (session.OutgoingMessages.Count > 0)
                            {
                                // publish outgoing messages for the session
                                this.publisherManager.PublishSession(session.ClientId);
                            }
                        }
                    }
                    // requested clean session
                    else
                    {
                        // send CONNACK message to the client
                        client.Connack(e.Message, returnCode, clientId, sessionPresent);

                        this.sessionManager.ClearSession(clientId);
                    }
                }
                else
                {
                    // send CONNACK message to the client
                    client.Connack(e.Message, returnCode, clientId, sessionPresent);
                }
            }
            catch (MqttCommunicationException)
            {
                this.CloseClient(client);
            }
        }