Example #1
0
        private void CreateMQChannel()
        {
            if (m_mqttClient.IsPublishing)
            {
                return;
            }
            StopMQTTChannel();

            try
            {
                var connArgs = new MqttConnectionArgs()
                {
                    ClientId  = m_clientId,
                    Hostname  = m_mqttServerAddress,
                    Port      = m_mqttPort,
                    Keepalive = new TimeSpan(1, 0, 0)
                };

                m_mqttClient = new MqttConnection(connArgs, m_mqttPersistence, null);

                m_mqttClient.Connect();
            }
            catch (Exception ex)
            {
                string text = "创建MQTTChannel失败," + ex.Message;
                m_eventLogger.WriteWarning(text);
                USeNotifyEventArgs notify = new USeNotifyEventArgs(USeNotifyLevel.Warning, text);
                SafeRaiseNotifyEvent(this, notify);
            }
        }
Example #2
0
        /// <summary>
        /// Communication line initialized
        /// </summary>
        public void Connect(XmlNode MQTTSettings)
        {
            connArgs = new MqttConnectionArgs
            {
                ClientId     = MQTTSettings.Attributes.GetNamedItem("ClientID").Value,
                Hostname     = MQTTSettings.Attributes.GetNamedItem("Hostname").Value,
                Port         = Convert.ToInt32(MQTTSettings.Attributes.GetNamedItem("Port").Value),
                Username     = MQTTSettings.Attributes.GetNamedItem("UserName").Value,
                Password     = MQTTSettings.Attributes.GetNamedItem("Password").Value,
                Keepalive    = TimeSpan.FromSeconds(60),
                ReadTimeout  = TimeSpan.FromSeconds(10),
                WriteTimeout = TimeSpan.FromSeconds(10)
            };

            Persistence       = new InMemoryPersistence();
            Transport         = new TcpTransport(connArgs.Hostname, connArgs.Port);
            Transport.Version = connArgs.Version;
            Transport.SetTimeouts(connArgs.ReadTimeout, connArgs.WriteTimeout);

            Send(MakeConnectMessage(connArgs));
            ReceiveConnack();
            ResumeOutgoingFlows();

            if (sp.Topics.Length > 0)
            {
                Subscribe(sp);
            }

            WriteToLog(Localization.UseRussian ? "Инициализация линии связи выполнена успешно." : "Communication line initialized successfully");
        }
Example #3
0
 /// <summary>
 /// Sets the default values.
 /// </summary>
 private void SetToDefault()
 {
     ConnectionArgs = new MqttConnectionArgs();
     SubTopics      = new List <MqttSubTopic>();
     PubTopics      = new List <MqttPubTopic>();
     PubCmds        = new List <MqttPubCmd>();
     SubCmds        = new List <MqttSubCmd>();
     SubJSs         = new List <MqttSubJS>();
 }
        /// <summary>
        /// 读数据线程
        /// </summary>
        private void DoWork()
        {
            lock (m_locker)
            {
                try
                {
                    var connArgs = new MqttConnectionArgs()
                    {
                        ClientId  = m_clientId,
                        Hostname  = m_mqttServerAddress,
                        Port      = m_mqttPort,
                        Keepalive = new TimeSpan(1, 0, 0)
                    };

                    using (m_mqttClient = new MqttConnection(connArgs))
                    {
                        m_mqttClient.Connect();

                        while (m_runFlag)
                        {
                            USeMarketData marketData = null;
                            m_marketDataQueue.TryDequeue(out marketData);
                            if (marketData == null)
                            {
                                Thread.Sleep(1000);
                                continue;
                            }

                            Debug.WriteLine(string.Format("当前MQTT链接:{0}", connArgs.ClientId));

                            //[hanyu]暂时只推送上期的品种行情
                            if (marketData.Instrument.Market == USeMarket.SHFE || marketData.Instrument.Market == USeMarket.LME)
                            {
                                InternalSendTotMQTT(marketData);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);

                    string text = string.Format("** {0}链接MQTT失败,{1}", this.StoreageName, ex.Message);
                    m_eventLogger.WriteError(text);
                    USeNotifyEventArgs notify = new USeNotifyEventArgs(USeNotifyLevel.Warning, text);
                    SafeRaiseNotifyEvent(this, notify);
                }
                finally
                {
                    m_mqttClient.Disconnect();
                    DoWork();
                }
            }
        }
Example #5
0
 private void Session_OnConnect(object sender, MqttConnectionArgs args)
 {
     try
     {
         adapter.LoadDurableSubscriptionsAsync(session.Identity).GetAwaiter();
     }
     catch (Exception ex)
     {
         logger.LogError(ex, $"MQTT adapter Session_OnConnect error on channel '{Channel.Id}'.");
         OnError?.Invoke(this, new ProtocolAdapterErrorEventArgs(Channel.Id, ex));
     }
 }
Example #6
0
        private void WorkerThreadProc()
        {
            try
            {
                var connArgs = new MqttConnectionArgs()
                {
                    Hostname        = _connectionInfo.Connection.Server,
                    Port            = _connectionInfo.Connection.Port,
                    Secure          = false,
                    ProtocolVersion = MqttProtocolVersion.V3_1_1,
                    ClientId        = _connectionInfo.Connection.ConnectionUser,
                    Username        = _connectionInfo.Connection.ConnectionUser,
                    Password        = _connectionInfo.Connection.Password,
                    CleanSession    = true,
                    Keepalive       = TimeSpan.FromSeconds(60),
                    WillMessage     = null,
                    ReadTimeout     = TimeSpan.FromSeconds(10),
                    WriteTimeout    = TimeSpan.FromSeconds(10)
                };
                using (var conn = new MqttConnection(connArgs))
                {
                    conn.Connect();

                    conn.PublishReceived += HandlePublishReceived;

                    if (_connectionInfo.Subscriptions != null)
                    {
                        foreach (var s in _connectionInfo.Subscriptions)
                        {
                            logger.Info($"Subscribe: {Key} -> {s.TopicFilter}, {s.QoS}");
                            conn.Subscribe(s.TopicFilter, (MqttQos)s.QoS);
                        }
                    }

                    while (conn.Loop())
                    {
                        // etc...
                    }

                    logger.Warn("Disconnected: " + Key);
                }
            }
            catch (ThreadAbortException)
            {
                logger.Info("Aborted: " + Key);
            }
            catch (Exception ex)
            {
                logger.Error("Error in WorkerProc", ex);
            }
        }
Example #7
0
        public void Run()
        {
            var connArgs = new MqttConnectionArgs()
            {
                ClientId        = this.ClientId,
                Hostname        = "localhost",
                CleanSession    = false,
                ProtocolVersion = MqttProtocolVersion.V3_1
            };

            using (var conn = new MqttConnection(connArgs, clientPersistence))
            {
                conn.Connect();
                Console.WriteLine("{0} connected", ClientId);
                try
                {
                    BindEvents(conn);

                    if (!conn.IsSessionPresent)
                    {
                        Subscribe(conn);
                    }

                    while (conn.Loop(PollLimit))
                    {
                        if (Finished && !conn.IsPublishing)
                        {
                            break;
                        }

                        bool finishedPublishing = previousPublishedNumber >= maxNumber;
                        bool canPublishNext     = numbersPersistence.GetLastReceived(TopicToPublish) >= previousPublishedNumber;

                        if (!conn.IsPublishing && !finishedPublishing && canPublishNext)
                        {
                            PublishNext(conn);
                        }
                    }
                }
                finally
                {
                    UnbindEvents(conn);
                }
            }
        }
Example #8
0
        public void Run()
        {
            var connArgs = new MqttConnectionArgs()
            {
                ClientId     = this.ClientId,
                Hostname     = "localhost",
                Port         = 1883,
                Secure       = true,
                CleanSession = false
            };

            using (var conn = new MqttConnection(connArgs, persistence))
            {
                conn.Connect();
                Console.WriteLine("{0} connected", ClientId);

                try
                {
                    BindEvents(conn);

                    if (!conn.IsSessionPresent)
                    {
                        Subscribe(conn);
                    }

                    while (conn.Loop(PollLimit) && !Finished)
                    {
                        if (!conn.IsPublishing)
                        {
                            PublishNext(conn);
                        }
                    }
                }
                finally
                {
                    UnbindEvents(conn);
                }
            }
        }
Example #9
0
        private ConnectPacket MakeConnectMessage(MqttConnectionArgs args)
        {
            ConnectPacket conn = new ConnectPacket();

            conn.ProtocolVersion = args.Version;

            conn.ClientId = args.ClientId;
            conn.Username = args.Username;
            conn.Password = args.Password;

            if (args.WillMessage != null)
            {
                conn.WillFlag     = true;
                conn.WillTopic    = args.WillMessage.Topic;
                conn.WillMessage  = args.WillMessage.Message;
                conn.WillQosLevel = args.WillMessage.Qos;
                conn.WillRetain   = args.WillMessage.Retain;
            }

            conn.CleanSession    = args.CleanSession;
            conn.KeepAlivePeriod = (ushort)args.Keepalive.TotalSeconds;
            return(conn);
        }
Example #10
0
 private void Session_OnConnect(object sender, MqttConnectionArgs args)
 {
     code = args.Code;
 }
Example #11
0
        public override void OnAddedToCommLine()
        {
            List <TagGroup> tagGroups  = new List <TagGroup> ();
            TagGroup        tagGroup   = new TagGroup("GroupMQTT");
            TagGroup        tagGroupJS = new TagGroup("GoupJS");

            XmlDocument xmlDoc   = new XmlDocument();
            string      filename = ReqParams.CmdLine.Trim();

            xmlDoc.Load(AppDirs.ConfigDir + filename);

            XmlNode MQTTSubTopics = xmlDoc.DocumentElement.SelectSingleNode("MqttSubTopics");
            XmlNode MQTTPubTopics = xmlDoc.DocumentElement.SelectSingleNode("MqttPubTopics");
            XmlNode MQTTPubCmds   = xmlDoc.DocumentElement.SelectSingleNode("MqttPubCmds");
            XmlNode MQTTSubCmds   = xmlDoc.DocumentElement.SelectSingleNode("MqttSubCmds");
            XmlNode MQTTSubJSs    = xmlDoc.DocumentElement.SelectSingleNode("MqttSubJSs");
            XmlNode RapSrvCnf     = xmlDoc.DocumentElement.SelectSingleNode("RapSrvCnf");
            XmlNode MQTTSettings  = xmlDoc.DocumentElement.SelectSingleNode("MqttParams");

            CommSettings cs = new CommSettings()
            {
                ServerHost = RapSrvCnf.Attributes.GetNamedItem("ServerHost").Value,
                ServerPort = Convert.ToInt32(RapSrvCnf.Attributes.GetNamedItem("ServerPort").Value),
                ServerUser = RapSrvCnf.Attributes.GetNamedItem("ServerUser").Value,
                ServerPwd  = RapSrvCnf.Attributes.GetNamedItem("ServerPwd").Value
            };

            RSrv = new RapSrvEx(cs);
            RSrv.Conn();
            MQTTPTs  = new List <MQTTPubTopic> ();
            MQTTCmds = new List <MQTTPubCmd> ();

            foreach (XmlElement MqttPTCnf in MQTTPubTopics)
            {
                MQTTPubTopic MqttPT = new MQTTPubTopic()
                {
                    NumCnl                 = Convert.ToInt32(MqttPTCnf.GetAttribute("NumCnl")),
                    QosLevels              = (MqttQos)Convert.ToByte(MqttPTCnf.GetAttribute("QosLevel")),
                    TopicName              = MqttPTCnf.GetAttribute("TopicName"),
                    PubBehavior            = MqttPTCnf.GetAttribute("PubBehavior"),
                    NumberDecimalSeparator = MqttPTCnf.GetAttribute("NDS"),
                    Value = 0
                };
                MQTTPTs.Add(MqttPT);
            }

            foreach (XmlElement MqttPTCnf in MQTTPubCmds)
            {
                MQTTPubCmd MqttPTCmd = new MQTTPubCmd()
                {
                    NumCmd    = MqttPTCnf.GetAttrAsInt("NumCmd"),
                    QosLevels = (MqttQos)Convert.ToByte(MqttPTCnf.GetAttribute("QosLevel")),
                    Retain    = false,
                    TopicName = MqttPTCnf.GetAttribute("TopicName")
                };
                MQTTCmds.Add(MqttPTCmd);
            }

            sp = new SubscribePacket();
            int i     = 0;
            int spCnt = MQTTSubTopics.ChildNodes.Count;

            spCnt += MQTTSubCmds.ChildNodes.Count;
            spCnt += MQTTSubJSs.ChildNodes.Count;

            sp.Topics    = new string[spCnt];
            sp.QosLevels = new MqttQos[spCnt];

            foreach (XmlElement elemGroupElem in MQTTSubTopics.ChildNodes)
            {
                sp.Topics [i]    = elemGroupElem.GetAttribute("TopicName");
                sp.QosLevels [i] = (MqttQos)Convert.ToByte(elemGroupElem.GetAttribute("QosLevel"));
                KPTag KPt = new KPTag()
                {
                    Signal = i + 1,
                    Name   = sp.Topics [i],
                    CnlNum = Convert.ToInt32(elemGroupElem.GetAttribute("NumCnl"))
                };
                tagGroup.KPTags.Add(KPt);
                i++;
            }
            tagGroups.Add(tagGroup);
            InitKPTags(tagGroups);



            SubCmds = new List <MQTTSubCmd> ();

            foreach (XmlElement elemGroupElem in MQTTSubCmds.ChildNodes)
            {
                sp.Topics [i]    = elemGroupElem.GetAttribute("TopicName");
                sp.QosLevels [i] = (MqttQos)Convert.ToByte(elemGroupElem.GetAttribute("QosLevel"));
                MQTTSubCmd cmd = new MQTTSubCmd()
                {
                    TopicName  = sp.Topics[i],
                    CmdNum     = elemGroupElem.GetAttrAsInt("NumCmd", 0),
                    CmdType    = elemGroupElem.GetAttribute("CmdType"),
                    KPNum      = elemGroupElem.GetAttrAsInt("KPNum", 0),
                    IDUser     = elemGroupElem.GetAttrAsInt("IDUser", 0),
                    NumCnlCtrl = elemGroupElem.GetAttrAsInt("NumCnlCtrl", 0)
                };
                SubCmds.Add(cmd);
                i++;
            }

            SubJSs = new List <MQTTSubJS>();

            foreach (XmlElement elemGroupElem in MQTTSubJSs.ChildNodes)
            {
                sp.Topics[i]    = elemGroupElem.GetAttribute("TopicName");
                sp.QosLevels[i] = (MqttQos)Convert.ToByte(elemGroupElem.GetAttribute("QosLevel"));
                MQTTSubJS msjs = new MQTTSubJS()
                {
                    TopicName     = sp.Topics[i],
                    CnlCnt        = elemGroupElem.GetAttrAsInt("CnlCnt", 1),
                    JSHandlerPath = elemGroupElem.GetAttrAsString("JSHandlerPath", "")
                };
                if (msjs.LoadJSHandler())
                {
                    SubJSs.Add(msjs);
                    i++;
                }
            }



            connArgs              = new MqttConnectionArgs();
            connArgs.ClientId     = MQTTSettings.Attributes.GetNamedItem("ClientID").Value;
            connArgs.Hostname     = MQTTSettings.Attributes.GetNamedItem("Hostname").Value;
            connArgs.Port         = Convert.ToInt32(MQTTSettings.Attributes.GetNamedItem("Port").Value);
            connArgs.Username     = MQTTSettings.Attributes.GetNamedItem("UserName").Value;
            connArgs.Password     = MQTTSettings.Attributes.GetNamedItem("Password").Value;
            connArgs.Keepalive    = TimeSpan.FromSeconds(60);
            connArgs.ReadTimeout  = TimeSpan.FromSeconds(10);
            connArgs.WriteTimeout = TimeSpan.FromSeconds(10);

            this.Persistence  = new InMemoryPersistence();
            Transport         = new TcpTransport(connArgs.Hostname, connArgs.Port);
            Transport.Version = connArgs.Version;
            Transport.SetTimeouts(connArgs.ReadTimeout, connArgs.WriteTimeout);

            Send(MakeConnectMessage(connArgs));
            ReceiveConnack();
            ResumeOutgoingFlows();

            if (sp.Topics.Length > 0)
            {
                Subscribe(sp);
            }

            WriteToLog(Localization.UseRussian ? "Инициализация линии связи выполнена успешно." : "Communication line initialized successfully");
        }
Example #12
0
        public override void OnAddedToCommLine()
        {
            List <TagGroup> tagGroups = new List <TagGroup> ();
            TagGroup        tagGroup  = new TagGroup("GroupMQTT");

            XmlDocument xmlDoc   = new XmlDocument();
            string      filename = ReqParams.CmdLine.Trim();

            xmlDoc.Load(AppDirs.ConfigDir + filename);

            XmlNode MQTTSubTopics = xmlDoc.DocumentElement.SelectSingleNode("MqttSubTopics");
            XmlNode MQTTPubTopics = xmlDoc.DocumentElement.SelectSingleNode("MqttPubTopics");
            XmlNode RapSrvCnf     = xmlDoc.DocumentElement.SelectSingleNode("RapSrvCnf");
            XmlNode MQTTSettings  = xmlDoc.DocumentElement.SelectSingleNode("MqttParams");

            CommSettings cs = new CommSettings()
            {
                ServerHost = RapSrvCnf.Attributes.GetNamedItem("ServerHost").Value,
                ServerPort = Convert.ToInt32(RapSrvCnf.Attributes.GetNamedItem("ServerPort").Value),
                ServerUser = RapSrvCnf.Attributes.GetNamedItem("ServerUser").Value,
                ServerPwd  = RapSrvCnf.Attributes.GetNamedItem("ServerPwd").Value
            };

            RSrv = new RapSrvEx(cs);
            RSrv.Conn();
            MQTTPTs = new List <MQTTPubTopic> ();



            foreach (XmlElement MqttPTCnf in MQTTPubTopics)
            {
                MQTTPubTopic MqttPT = new MQTTPubTopic()
                {
                    NumCnl    = Convert.ToInt32(MqttPTCnf.GetAttribute("NumCnl")),
                    QosLevels = (MqttQos)Convert.ToByte(MqttPTCnf.GetAttribute("QosLevel")),
                    TopicName = MqttPTCnf.GetAttribute("TopicName"),
                    Value     = 0
                };
                MQTTPTs.Add(MqttPT);
            }



            sp = new SubscribePacket();
            int i = 0;

            sp.Topics    = new string[MQTTSubTopics.ChildNodes.Count];
            sp.QosLevels = new MqttQos[MQTTSubTopics.ChildNodes.Count];

            foreach (XmlElement elemGroupElem in MQTTSubTopics.ChildNodes)
            {
                sp.Topics [i]    = elemGroupElem.GetAttribute("TopicName");
                sp.QosLevels [i] = (MqttQos)Convert.ToByte(elemGroupElem.GetAttribute("QosLevel"));
                KPTag KPt = new KPTag()
                {
                    Signal = i + 1,
                    Name   = sp.Topics [i],
                    CnlNum = Convert.ToInt32(elemGroupElem.GetAttribute("NumCnl"))
                };
                tagGroup.KPTags.Add(KPt);
                i++;
            }



            tagGroups.Add(tagGroup);
            InitKPTags(tagGroups);

            connArgs          = new MqttConnectionArgs();
            connArgs.ClientId = MQTTSettings.Attributes.GetNamedItem("ClientID").Value;
            connArgs.Hostname = MQTTSettings.Attributes.GetNamedItem("Hostname").Value;
            connArgs.Port     = Convert.ToInt32(MQTTSettings.Attributes.GetNamedItem("Port").Value);
            connArgs.Username = MQTTSettings.Attributes.GetNamedItem("UserName").Value;
            connArgs.Password = MQTTSettings.Attributes.GetNamedItem("Password").Value;

            this.Persistence  = new InMemoryPersistence();
            Transport         = new TcpTransport(connArgs.Hostname, connArgs.Port);
            Transport.Version = connArgs.Version;
            Transport.SetTimeouts(connArgs.ReadTimeout, connArgs.WriteTimeout);

            Send(MakeConnectMessage(connArgs));
            ReceiveConnack();
            ResumeOutgoingFlows();
            Subscribe(sp);
        }