Exemplo n.º 1
1
        public void start()
        {
            this.shouldStop = false;
            if (mqttBrokerAddress == null)
            {
                throw new ArgumentOutOfRangeException("Mqtt Broker Address not initialized");
            }
            mqttClient = new uPLibrary.Networking.M2Mqtt.MqttClient(mqttBrokerAddress, mqttBrokerPort, false, null, null, uPLibrary.Networking.M2Mqtt.MqttSslProtocols.None);

            string clientID = new Guid().ToString();

            try
            {
                if (MqttUserName == null || MqttPassword == null)
                {
                    mqttClient.Connect(clientID);
                }
                else
                {
                    mqttClient.Connect(clientID, MqttUserName, MqttPassword);
                }
                if (!modbusClient.Connected)
                {
                    modbusClient.Connect();
                }
            }
            catch (Exception exc)
            {
                if (!this.AutomaticReconnect)
                {
                    throw exc;
                }
            }
            for (int i = 0; i < readOrders.Count; i++)
            {
                readOrders[i].thread = new System.Threading.Thread(new ParameterizedThreadStart(ProcessData));
                readOrders[i].thread.Start(readOrders[i]);
            }
        }
Exemplo n.º 2
0
        public void publish(string topic, string payload, string mqttBrokerAddress)
        {
            if (mqttClient != null)
            {
                if (!mqttBrokerAddress.Equals(this.MqttBrokerAddressPublish) & mqttClient.IsConnected)
                {
                    mqttClient.Disconnect();
                }
            }
            mqttClient = new uPLibrary.Networking.M2Mqtt.MqttClient(mqttBrokerAddress, mqttBrokerPort, false, null, null, uPLibrary.Networking.M2Mqtt.MqttSslProtocols.None);
            string clientID = Guid.NewGuid().ToString();

            if (!mqttClient.IsConnected)
            {
                if (MqttUserName == null || MqttPassword == null)
                {
                    mqttClient.Connect(clientID);
                }
                else
                {
                    mqttClient.Connect(clientID, MqttUserName, MqttPassword);
                }
            }

            if (payload != null)
            {
                mqttClient.Publish(topic, Encoding.UTF8.GetBytes(payload), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, RetainMessages);
            }
            else
            {
                mqttClient.Publish(topic, null, MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, RetainMessages);
            }
        }
Exemplo n.º 3
0
        public void publish(string[] topic, string[] payload, string mqttBrokerAddress)
        {
            if (mqttClient != null)
            {
                if (!mqttBrokerAddress.Equals(this.MqttBrokerAddressPublish) & mqttClient.IsConnected)
                {
                    mqttClient.Disconnect();
                }
            }
            if (topic.Length != payload.Length)
            {
                throw new ArgumentOutOfRangeException("Array topic and payload must be the same size");
            }
            mqttClient = new uPLibrary.Networking.M2Mqtt.MqttClient(mqttBrokerAddress, mqttBrokerPort, false, null, null, uPLibrary.Networking.M2Mqtt.MqttSslProtocols.None);
            string clientID = Guid.NewGuid().ToString();

            if (!mqttClient.IsConnected)
            {
                if (MqttUserName == null || MqttPassword == null)
                {
                    mqttClient.Connect(clientID);
                }
                else
                {
                    mqttClient.Connect(clientID, MqttUserName, MqttPassword);
                }
            }

            for (int i = 0; i < payload.Length; i++)
            {
                mqttClient.Publish(topic[i], Encoding.UTF8.GetBytes(payload[i]), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
            }
        }
Exemplo n.º 4
0
        public void Connect()
        {
            var username = configuration["mqtt:username"];
            var password = configuration["mqtt:password"];

            if (string.IsNullOrWhiteSpace(username))
            {
                throw new InvalidOperationException("Missing 'username' in config file");
            }

            if (string.IsNullOrWhiteSpace(password))
            {
                throw new InvalidOperationException("Missing 'password' in config file");
            }

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

            logger.LogInformation($"Connecting MQTT Server on {hostName}...");
            mqttClient.Connect(clientId, username, password);

            if (SpinWait.SpinUntil(() => mqttClient.IsConnected, 30000))
            {
                logger.LogInformation("Connected");
                return;
            }

            throw new TimeoutException("Could not connect to mqtt client");
        }
Exemplo n.º 5
0
        private static async Task <int> _publish()
        {
            Console.WriteLine("Type 'q' to quit");

            var client = new uPLibrary.Networking.M2Mqtt.MqttClient("grissom.klingon");

            client.Connect(Guid.NewGuid().ToString());
            Random r    = new Random((int)(DateTime.Now.Ticks + (long)Environment.CurrentManagedThreadId));
            string text = null;

            do
            {
                text = Console.ReadLine();
                if (text != "q")
                {
                    double d     = r.NextDouble() * 100.00;
                    var    bytes = System.Text.Encoding.UTF8.GetBytes(string.Format("{{ \"temp\":{0} }}", d));

                    client.Publish("house/serverroom/temp", bytes);

                    Console.WriteLine(1);
                }
            } while(text != "q");

            client.Disconnect();

            return(1);
        }
Exemplo n.º 6
0
        private static void _subscribe(MqttConfig cfg)
        {
            //System.Threading.Timer tmr;
            //"192.168.9.21"

            var client = new uPLibrary.Networking.M2Mqtt.MqttClient(cfg.server);

            client.ProtocolVersion         = uPLibrary.Networking.M2Mqtt.MqttProtocolVersion.Version_3_1_1;
            client.MqttMsgSubscribed      += Client_MqttMsgSubscribed;
            client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
            client.MqttMsgPublished       += Client_MqttMsgPublished;

            if (!string.IsNullOrWhiteSpace(cfg.username))
            {
                client.Connect(Guid.NewGuid().ToString(), cfg.username, cfg.password);
            }
            else
            {
                client.Connect(Guid.NewGuid().ToString());
            }

            var channels = new List <string>();
            var qoss     = new List <byte>();

            {
                foreach (var s in cfg.subscriptions)
                {
                    channels.Add(s.channel);
                    qoss.Add(s.qos);
                }
            }

            /*client.Subscribe(new string[] {"house/serverroom/temp"}, new byte[] { 0});*/
            client.Subscribe(channels.ToArray(), qoss.ToArray());

            Console.WriteLine("Type 'q' to quit");
            string text = null;

            do
            {
                text = Console.ReadLine();
            } while(text != "q");

            client.Disconnect();
        }
Exemplo n.º 7
0
 public MqttClient(Connect.Conference.Core.Models.Conferences.Conference conference)
 {
     Conference = conference;
     if (!string.IsNullOrEmpty(conference.MqttBroker))
     {
         var filename = string.Format("{0}\\Portals\\_default\\Logs\\Connect.Conference.{1}.{2:yyyy-MM-dd}", DotNetNuke.Common.Globals.ApplicationMapPath, Conference.ConferenceId, System.DateTime.Now);
         var i        = 0;
         while (true)
         {
             try
             {
                 if (Logger == null)
                 {
                     Logger = new StreamWriter(string.Format("{0}-{1}.resources", filename, i), true, Encoding.UTF8);
                 }
                 break;
             }
             catch (System.Exception)
             {
             }
             i++;
         }
         string clientId = string.Format("Connect.Conference.{0}.{1}", DotNetNuke.Entities.Host.Host.GUID, conference.ConferenceId);
         Client = new uPLibrary.Networking.M2Mqtt.MqttClient(conference.MqttBroker);
         Client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
         if (string.IsNullOrEmpty(conference.MqttBrokerUsername))
         {
             Client.Connect(clientId);
         }
         else
         {
             Client.Connect(clientId, conference.MqttBrokerUsername, conference.MqttBrokerPassword, false, 1000);
         }
         Client.Subscribe(new string[] { Conference.BaseTopicPath + "rfid/room/+" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
     }
 }
Exemplo n.º 8
0
        public void start()
        {
            this.shouldStop = false;
            if (mqttBrokerAddress == null)
            {
                throw new ArgumentOutOfRangeException("Mqtt Broker Address not initialized");
            }
            if (!modbusClient.Connected)
            {
                modbusClient.Connect();
            }
            mqttClient = new uPLibrary.Networking.M2Mqtt.MqttClient(mqttBrokerAddress);
            string clientID = new Guid().ToString();

            mqttClient.Connect(clientID);
            for (int i = 0; i < readOrders.Count; i++)
            {
                readOrders[i].thread = new System.Threading.Thread(new ParameterizedThreadStart(ProcessData));
                readOrders[i].thread.Start(readOrders[i]);
            }
        }
Exemplo n.º 9
0
        private void ConnectionService()
        {
            Console.WriteLine("Starting Connection Service");

            _nextReconnectAttempt = DateTime.Now;

            while (true)
            {
                if (_IsSetup && !_client.IsConnected)
                {
                    if (DateTime.Now.Subtract(_nextReconnectAttempt).TotalMilliseconds > 0)
                    {
                        try
                        {
                            Console.WriteLine("Connect procedure");

                            _client.Connect(_clientId);

                            var savedTopics = _subscribedTopics.ToArray();
                            _subscribedTopics.Clear();

                            foreach (string topic in savedTopics)
                            {
                                Subscribe(topic);
                            }
                        }
                        catch (Exception)
                        {
                            Console.WriteLine("Error while trying to connect, retry in {0} seconds", CONNECTION_DELAY);
                        }
                        finally
                        {
                            _nextReconnectAttempt = DateTime.Now.AddSeconds(CONNECTION_DELAY);
                        }
                    }
                }

                Thread.Sleep(1);
            }
        }
Exemplo n.º 10
0
        private void ProcessData(object param)
        {
            while (!shouldStop)
            {
                try
                {
                    if (!mqttClient.IsConnected)
                    {
                        mqttClient = new uPLibrary.Networking.M2Mqtt.MqttClient(mqttBrokerAddress, mqttBrokerPort, false, null, null, uPLibrary.Networking.M2Mqtt.MqttSslProtocols.None);
                        string clientID = Guid.NewGuid().ToString();
                        if (MqttUserName == null || MqttPassword == null)
                        {
                            mqttClient.Connect(clientID);
                        }
                        else
                        {
                            mqttClient.Connect(clientID, MqttUserName, MqttPassword);
                        }
                    }
                }
                catch (Exception exc)
                {
                    if (!this.AutomaticReconnect)
                    {
                        throw exc;
                    }
                }
                ReadOrder readOrder = (ReadOrder)param;
                lock (lockProcessData)
                {
                    try
                    {
                        if (readOrder.FunctionCode == FunctionCode.ReadCoils)
                        {
                            bool[] value = modbusClient.ReadCoils(readOrder.StartingAddress, readOrder.Quantity);
                            for (int i = 0; i < value.Length; i++)
                            {
                                if (readOrder.oldvalue[i] == null)
                                {
                                    mqttClient.Publish(readOrder.Topic[i], Encoding.UTF8.GetBytes(value[i].ToString()), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, readOrder.Retain[i]);
                                }
                                else if ((bool)readOrder.oldvalue[i] != value[i])
                                {
                                    mqttClient.Publish(readOrder.Topic[i], Encoding.UTF8.GetBytes(value[i].ToString()), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, readOrder.Retain[i]);
                                }
                                readOrder.oldvalue[i] = value[i];
                            }
                        }
                        if (readOrder.FunctionCode == FunctionCode.ReadDiscreteInputs)
                        {
                            bool[] value = modbusClient.ReadDiscreteInputs(readOrder.StartingAddress, readOrder.Quantity);
                            for (int i = 0; i < value.Length; i++)
                            {
                                if (readOrder.oldvalue[i] == null)
                                {
                                    mqttClient.Publish(readOrder.Topic[i], Encoding.UTF8.GetBytes(value[i].ToString()), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, readOrder.Retain[i]);
                                }
                                else if ((bool)readOrder.oldvalue[i] != value[i])
                                {
                                    mqttClient.Publish(readOrder.Topic[i], Encoding.UTF8.GetBytes(value[i].ToString()), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, readOrder.Retain[i]);
                                }
                                readOrder.oldvalue[i] = value[i];
                            }
                        }
                        if (readOrder.FunctionCode == FunctionCode.ReadHoldingRegisters)
                        {
                            int[] value = modbusClient.ReadHoldingRegisters(readOrder.StartingAddress, readOrder.Quantity);
                            for (int i = 0; i < value.Length; i++)
                            {
                                float scale = readOrder.Scale != null ? (readOrder.Scale[i] == 0) ? 1 : readOrder.Scale[i] : 1;
                                if (readOrder.oldvalue[i] == null)
                                {
                                    mqttClient.Publish(readOrder.Topic[i], (readOrder.Unit == null ? Encoding.UTF8.GetBytes(((float)value[i] * scale).ToString()) : Encoding.UTF8.GetBytes(((float)value[i] * scale) + " " + readOrder.Unit[i])), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, readOrder.Retain[i]);
                                    readOrder.oldvalue[i] = value[i];
                                }
                                else if (((int)readOrder.oldvalue[i] != value[i]) && (readOrder.Hysteresis != null ? ((value[i] < (int)readOrder.oldvalue[i] - (int)readOrder.Hysteresis[i]) | (value[i] > (int)readOrder.oldvalue[i] + (int)readOrder.Hysteresis[i])) : true))
                                {
                                    mqttClient.Publish(readOrder.Topic[i], (readOrder.Unit == null ? Encoding.UTF8.GetBytes(((float)value[i] * scale).ToString()) : Encoding.UTF8.GetBytes(((float)value[i] * scale).ToString() + " " + readOrder.Unit[i])), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, readOrder.Retain[i]);
                                    readOrder.oldvalue[i] = value[i];
                                }
                            }
                        }

                        if (readOrder.FunctionCode == FunctionCode.ReadInputRegisters)
                        {
                            int[] value = modbusClient.ReadInputRegisters(readOrder.StartingAddress, readOrder.Quantity);
                            for (int i = 0; i < value.Length; i++)
                            {
                                float scale = readOrder.Scale != null ? (readOrder.Scale[i] == 0) ? 1 : readOrder.Scale[i] : 1;
                                if (readOrder.oldvalue[i] == null)
                                {
                                    mqttClient.Publish(readOrder.Topic[i], (readOrder.Unit == null ? Encoding.UTF8.GetBytes(((float)value[i] * scale).ToString()) : Encoding.UTF8.GetBytes(((float)value[i] * scale).ToString() + " " + readOrder.Unit[i])), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, readOrder.Retain[i]);
                                    readOrder.oldvalue[i] = value[i];
                                }
                                else if (((int)readOrder.oldvalue[i] != value[i]) && (readOrder.Hysteresis != null ? ((value[i] < (int)readOrder.oldvalue[i] - (int)readOrder.Hysteresis[i]) | (value[i] > (int)readOrder.oldvalue[i] + (int)readOrder.Hysteresis[i])) : true))
                                {
                                    mqttClient.Publish(readOrder.Topic[i], (readOrder.Unit == null ? Encoding.UTF8.GetBytes(((float)value[i] * scale).ToString()) : Encoding.UTF8.GetBytes(((float)value[i] * scale).ToString() + " " + readOrder.Unit[i])), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, readOrder.Retain[i]);
                                    readOrder.oldvalue[i] = value[i];
                                }
                            }
                        }
                    }
                    catch (Exception exc)
                    {
                        modbusClient.Disconnect();
                        Thread.Sleep(2000);
                        if (!AutomaticReconnect)
                        {
                            throw exc;
                        }
                        if (!modbusClient.Connected)
                        {
                            try
                            {
                                modbusClient.Connect();
                            }
                            catch (Exception) { }
                        }
                    }
                }
                System.Threading.Thread.Sleep(readOrder.CylceTime);
            }
        }