Exemplo n.º 1
0
        private IMqttServerOptions CreateMqttServerOptions()
        {
            var options = new MqttServerOptionsBuilder()
                          .WithMaxPendingMessagesPerClient(_settings.MaxPendingMessagesPerClient)
                          .WithDefaultCommunicationTimeout(TimeSpan.FromSeconds(_settings.CommunicationTimeout))
                          .WithConnectionValidator(_mqttConnectionValidator)
                          .WithStorage(_mqttServerStorage);

            // Configure unencrypted connections
            if (_settings.TcpEndPoint.Enabled)
            {
                options.WithDefaultEndpoint();

                if (_settings.TcpEndPoint.TryReadIPv4(out var address4))
                {
                    options.WithDefaultEndpointBoundIPAddress(address4);
                }

                if (_settings.TcpEndPoint.TryReadIPv6(out var address6))
                {
                    options.WithDefaultEndpointBoundIPV6Address(address6);
                }

                if (_settings.TcpEndPoint.Port > 0)
                {
                    options.WithDefaultEndpointPort(_settings.TcpEndPoint.Port);
                }
            }
            else
            {
                options.WithoutDefaultEndpoint();
            }

            if (_settings.ConnectionBacklog > 0)
            {
                options.WithConnectionBacklog(_settings.ConnectionBacklog);
            }

            if (_settings.EnablePersistentSessions)
            {
                options.WithPersistentSessions();
            }

            if (_settings.UseOriginalReseiverClientId)
            {
                options.WithApplicationMessageInterceptor(_messageInterceptor);
            }

            return(options.Build());
        }
Exemplo n.º 2
0
        public void changeServerConfig(ServerConfigData MQTTConfigData)
        {
            _theAuthenticator    = MQTTConfigData.Authenticator;
            _ServerConfiguration = new MqttServerOptionsBuilder();
            _ServerConfiguration.WithConnectionValidator(this);
            _ServerConfiguration.WithApplicationMessageInterceptor(this);
            _ServerConfiguration.WithSubscriptionInterceptor(this);
            _ServerConfiguration.WithClientId("Server");
            _ServerConfiguration.WithDefaultEndpointBoundIPAddress(MQTTConfigData.listenAdress);
            _ServerConfiguration.WithDefaultEndpointPort(MQTTConfigData.Port);
            _ServerConfiguration.WithMaxPendingMessagesPerClient(FedNetConstante.MAX_MESSAGE_PENDING);

            _logSystem.Info("reinitialisation finnised !!");
        }
Exemplo n.º 3
0
        public FedNetServer(ServerConfigData MQTTConfigData, IFedNetLogger newlogSystem = null)
        {
            _logSystem = newlogSystem;
            if (_logSystem == null)
            {
                _logSystem = new DefaultLogger();
            }

            _theAuthenticator    = MQTTConfigData.Authenticator;
            _ServerConfiguration = new MqttServerOptionsBuilder();
            _ServerConfiguration.WithConnectionValidator(this);
            _ServerConfiguration.WithApplicationMessageInterceptor(this);
            _ServerConfiguration.WithSubscriptionInterceptor(this);
            _ServerConfiguration.WithClientId("Server");
            _ServerConfiguration.WithDefaultEndpointBoundIPAddress(MQTTConfigData.listenAdress);
            _ServerConfiguration.WithDefaultEndpointPort(MQTTConfigData.Port);
            _ServerConfiguration.WithMaxPendingMessagesPerClient(FedNetConstante.MAX_MESSAGE_PENDING);

            _theClientList = new List <ClientData>();
            _theGameServer = new MqttFactory().CreateMqttServer();
            _theGameServer.UseApplicationMessageReceivedHandler(e => {
                if (e.ClientId == "" || e.ClientId == " " || e.ClientId == null)
                {
                    return;
                }
                if (MessageReceived != null)
                {
                    MessageReceived.Invoke(this, Message.getMessage(e.ApplicationMessage));
                }
            });
            _theGameServer.UseClientConnectedHandler(e => {
                _logSystem.Info("new client connected : " + e.ClientId);
                //_theGameServer.SubscribeAsync("Server", FedNetConstante.CLIENT_TO_SERVER + FedNetConstante.DEFAULT_TOPIC_SEPARATOR + FedNetConstante.DEFAULT_TOPIC_JOKER, (MqttQualityOfServiceLevel)FedNetConstante.PRIORITY_SERVER_TO_CLIENT);
            });
            _theGameServer.StartedHandler            = this;
            _theGameServer.StoppedHandler            = this;
            _theGameServer.ClientDisconnectedHandler = this;

            _logSystem.Info("initialisation finished !!");
        }
Exemplo n.º 4
0
        public static async Task <MqttServerInstance> StartServer(MqttServerConfiguration serverConfiguration)
        {
            logger.Info($"Starting Mqtt Server");
            string storagefile = Path.Combine(PlugInData.HomeSeerDirectory, "data", PlugInData.PlugInId, "mqtt", "retained.json");

            // Configure MQTT server.
            var optionsBuilder = new MqttServerOptionsBuilder()
                                 .WithConnectionBacklog(512)
                                 .WithStorage(new MqttStorage(storagefile))
                                 .WithDefaultEndpointPort(serverConfiguration.Port);

            if (serverConfiguration.BoundIPAddress != null)
            {
                optionsBuilder = optionsBuilder.WithDefaultEndpointBoundIPAddress(serverConfiguration.BoundIPAddress);
            }
            optionsBuilder = optionsBuilder.WithDefaultEndpointBoundIPV6Address(IPAddress.None);

            var mqttServer = new MqttFactory(new MqttNetLogger()).CreateMqttServer();
            await mqttServer.StartAsync(optionsBuilder.Build()).ConfigureAwait(false);

            return(new MqttServerInstance(mqttServer, serverConfiguration));
        }
Exemplo n.º 5
0
        private void BuildServerOptions()
        {
            try
            {
                var ipAddress      = IPAddress.Parse(mqttConfiguration.BrokerHostName);
                var optionsBuilder = new MqttServerOptionsBuilder();

                if (mqttConfiguration.UseSSL)
                {
                    //// TODO: Implement insert certification
                    optionsBuilder.WithClientCertificate()
                    .WithEncryptionSslProtocol(mqttConfiguration.MqttSslProtocol);
                }

                optionsBuilder.WithDefaultEndpointBoundIPAddress(ipAddress)
                .WithDefaultEndpointPort(mqttConfiguration.BrokerPort)
                .WithConnectionValidator(MQTTConnectionValidator)
                .WithSubscriptionInterceptor(c =>
                {
                    c.AcceptSubscription = true;
                    LogMessage(mqttServiceLogger, c, true);
                })
                .WithApplicationMessageInterceptor(c =>
                {
                    c.AcceptPublish = true;
                    LogMessage(mqttServiceLogger, c);
                });

                mqttServerOptions = optionsBuilder.Build();
            }
            catch (Exception ex)
            {
                mqttServiceLogger.LogError(ex.Message);
                throw;
            }
        }
Exemplo n.º 6
0
        public async void Start()
        {
            // Backlog:表示服务器可以接受的并发请求的最大值
            var optionBuilder = new MqttServerOptionsBuilder().WithConnectionBacklog(1000).WithDefaultEndpointPort(Convert.ToInt32(this._port));

            optionBuilder.WithDefaultEndpointBoundIPAddress(IPAddress.Parse(this._ip));

            var options = optionBuilder.Build() as MqttServerOptions;

            options.ConnectionValidator        += this.ConnectionValidator;
            options.MaxPendingMessagesPerClient = 1000;
            options.EnablePersistentSessions    = true;

            this._mqttServer = new MqttFactory().CreateMqttServer();
            this._mqttServer.ClientConnected            += this.ClientConnected;
            this._mqttServer.ClientDisconnected         += this.ClientDisconnected;
            this._mqttServer.ApplicationMessageReceived += this.ApplicationMessageReceived;
            this._mqttServer.ClientSubscribedTopic      += this.ClientSubscribedTopic;
            this._mqttServer.ClientUnsubscribedTopic    += this.ClientUnsubscribedTopic;
            this._mqttServer.Started += this.Started;
            this._mqttServer.Stopped += this.Stopped;

            await _mqttServer.StartAsync(options);
        }
Exemplo n.º 7
0
        public void Start(out string errMsg)
        {
            errMsg = "";
            if (IsRuning)
            {
                return;
            }

            if (this.mqttParam == null)
            {
                errMsg = "MQTT服务启动失败,没有指明服务所需参数";
                return;
            }
            if (mqttServer == null)
            {
                try
                {
                    mqttServer.StopAsync();
                    mqttServer = null;
                }
                catch { }
            }

            // MQTT 动态库本身已经实现异步启动,这里不用在用异步调用了
            var optionsBuilder = new MqttServerOptionsBuilder();

            try
            {
                //在 MqttServerOptions 选项中,你可以使用 ConnectionValidator 来对客户端连接进行验证。
                //比如客户端ID标识 ClientId,用户名 Username 和密码 Password 等。
                optionsBuilder.WithConnectionValidator(ClientCheck);
                //指定 ip地址,默认为本地
                optionsBuilder.WithDefaultEndpointBoundIPAddress(IPAddress.Parse(this.mqttParam.ip));
                //指定端口
                optionsBuilder.WithDefaultEndpointPort(this.mqttParam.port);
                //连接记录数,默认 一般为2000
                //optionsBuilder.WithConnectionBacklog(2000);
                mqttServer = new MqttFactory().CreateMqttServer() as MqttServer;

                // 客户端支持 Connected、Disconnected 和 ApplicationMessageReceived 事件,
                //用来处理客户端与服务端连接、客户端从服务端断开以及客户端收到消息的事情。
                //其中 ClientConnected 和 ClientDisconnected 事件的事件参数一个客户端连接对象 ConnectedMqttClient,
                //通过该对象可以获取客户端ID标识 ClientId 和 MQTT 版本 ProtocolVersion。
                mqttServer.ClientConnected    += MqttServer_ClientConnected;
                mqttServer.ClientDisconnected += MqttServer_ClientDisconnected;

                //ApplicationMessageReceived 的事件参数包含了客户端ID标识 ClientId 和 MQTT 应用消息 MqttApplicationMessage 对象,
                //通过该对象可以获取主题 Topic、QoS QualityOfServiceLevel 和消息内容 Payload 等信息。
                mqttServer.ApplicationMessageReceived += MqttServer_ApplicationMessageReceived;
            }
            catch (Exception ex)
            {
                // log.Info("创建Mqtt服务,连接客户端的Id长度过短(不得小于5),或不是指定的合法客户端(以Eohi_开头)");
                errMsg = "创建MQTT服务失败:" + ex.Message;
                return;
            }

            Task task = mqttServer.StartAsync(optionsBuilder.Build());

            task.Wait(5000);

            IsRuning = task.IsCompleted;
        }
Exemplo n.º 8
0
        private async void MqttServer()
        {
            if (null != _mqttServer)
            {
                return;
            }

            var optionBuilder =
                new MqttServerOptionsBuilder().WithConnectionBacklog(1000).WithDefaultEndpointPort(Convert.ToInt32(TxbPort.Text));

            if (!String.IsNullOrEmpty(TxbServer.Text))
            {
                optionBuilder.WithDefaultEndpointBoundIPAddress(IPAddress.Parse(TxbServer.Text));
            }

            var options = optionBuilder.Build();


            (options as MqttServerOptions).ConnectionValidator += context =>
            {
                if (context.ClientId.Length < 1)
                {
                    context.ReturnCode = MqttConnectReturnCode.ConnectionRefusedIdentifierRejected;
                    return;
                }

                context.ReturnCode = MqttConnectReturnCode.ConnectionAccepted;
                clientId           = context.ClientId;
            };


            _mqttServer = new MqttFactory().CreateMqttServer();
            _mqttServer.ClientConnected += (sender, args) =>
            {
                richTextBox1.BeginInvoke(_updateListBoxAction, $">Client Connected:ClientId:{args.ClientId},ProtocalVersion:");

                var s = _mqttServer.GetClientSessionsStatus();
                label3.BeginInvoke(new Action(() => { label3.Text = $"连接总数:{s.Count}"; }));

                TopicFilter topicFilter = new TopicFilter(this.tbTopic.Text + args.ClientId, MqttQualityOfServiceLevel.AtLeastOnce);
                _mqttServer.SubscribeAsync(args.ClientId, new List <TopicFilter>()
                {
                    topicFilter
                });
            };

            _mqttServer.ClientDisconnected += (sender, args) =>
            {
                TopicFilter topicFilter = new TopicFilter(this.tbTopic.Text, MqttQualityOfServiceLevel.AtLeastOnce);
                _mqttServer.SubscribeAsync(clientId, new List <TopicFilter>()
                {
                    topicFilter
                });
                richTextBox1.BeginInvoke(_updateListBoxAction, $"<Client DisConnected:ClientId:{args.ClientId}");
                var s = _mqttServer.GetClientSessionsStatus();
                label3.BeginInvoke(new Action(() => { label3.Text = $"连接总数:{s.Count}"; }));
            };

            _mqttServer.ApplicationMessageReceived += (sender, args) =>
            {
                richTextBox1.BeginInvoke(_updateListBoxAction,
                                         $"ClientId:{args.ClientId} Topic:{args.ApplicationMessage.Topic} Payload:{Encoding.UTF8.GetString(args.ApplicationMessage.Payload)} QualityOfServiceLevel:{args.ApplicationMessage.QualityOfServiceLevel}");
            };

            _mqttServer.ClientSubscribedTopic += (sender, args) =>
            {
                richTextBox1.BeginInvoke(_updateListBoxAction, $"@ClientSubscribedTopic ClientId:{args.ClientId} Topic:{args.TopicFilter.Topic} QualityOfServiceLevel:{args.TopicFilter.QualityOfServiceLevel}");
            };
            _mqttServer.ClientUnsubscribedTopic += (sender, args) =>
            {
                richTextBox1.BeginInvoke(_updateListBoxAction, $"%ClientUnsubscribedTopic ClientId:{args.ClientId} Topic:{args.TopicFilter.Length}");
            };

            _mqttServer.Started += (sender, args) =>
            {
                richTextBox1.BeginInvoke(_updateListBoxAction, "Mqtt Server Start...");
            };

            _mqttServer.Stopped += (sender, args) =>
            {
                richTextBox1.BeginInvoke(_updateListBoxAction, "Mqtt Server Stop...");
            };

            await _mqttServer.StartAsync(options);
        }
Exemplo n.º 9
0
        IMqttServerOptions CreateMqttServerOptions()
        {
            var options = new MqttServerOptionsBuilder()
                          .WithMaxPendingMessagesPerClient(_settings.MaxPendingMessagesPerClient)
                          .WithDefaultCommunicationTimeout(TimeSpan.FromSeconds(_settings.CommunicationTimeout))
                          .WithConnectionValidator(_mqttConnectionValidator)
                          .WithApplicationMessageInterceptor(_mqttApplicationMessageInterceptor)
                          .WithSubscriptionInterceptor(_mqttSubscriptionInterceptor)
                          .WithUnsubscriptionInterceptor(_mqttUnsubscriptionInterceptor)
                          .WithStorage(_mqttServerStorage);

            // Configure unencrypted connections
            if (_settings.TcpEndPoint.Enabled)
            {
                options.WithDefaultEndpoint();

                if (_settings.TcpEndPoint.TryReadIPv4(out var address4))
                {
                    options.WithDefaultEndpointBoundIPAddress(address4);
                }

                if (_settings.TcpEndPoint.TryReadIPv6(out var address6))
                {
                    options.WithDefaultEndpointBoundIPV6Address(address6);
                }

                if (_settings.TcpEndPoint.Port > 0)
                {
                    options.WithDefaultEndpointPort(_settings.TcpEndPoint.Port);
                }
            }
            else
            {
                options.WithoutDefaultEndpoint();
            }

            // Configure encrypted connections
            if (_settings.EncryptedTcpEndPoint.Enabled)
            {
#if NETCOREAPP3_1 || NET5_0
                options
                .WithEncryptedEndpoint()
                .WithEncryptionSslProtocol(SslProtocols.Tls13);
#else
                options
                .WithEncryptedEndpoint()
                .WithEncryptionSslProtocol(SslProtocols.Tls12);
#endif

                if (!string.IsNullOrEmpty(_settings.EncryptedTcpEndPoint?.Certificate?.Path))
                {
                    IMqttServerCertificateCredentials certificateCredentials = null;

                    if (!string.IsNullOrEmpty(_settings.EncryptedTcpEndPoint?.Certificate?.Password))
                    {
                        certificateCredentials = new MqttServerCertificateCredentials
                        {
                            Password = _settings.EncryptedTcpEndPoint.Certificate.Password
                        };
                    }

                    options.WithEncryptionCertificate(_settings.EncryptedTcpEndPoint.Certificate.ReadCertificate(), certificateCredentials);
                }

                if (_settings.EncryptedTcpEndPoint.TryReadIPv4(out var address4))
                {
                    options.WithEncryptedEndpointBoundIPAddress(address4);
                }

                if (_settings.EncryptedTcpEndPoint.TryReadIPv6(out var address6))
                {
                    options.WithEncryptedEndpointBoundIPV6Address(address6);
                }

                if (_settings.EncryptedTcpEndPoint.Port > 0)
                {
                    options.WithEncryptedEndpointPort(_settings.EncryptedTcpEndPoint.Port);
                }
            }
            else
            {
                options.WithoutEncryptedEndpoint();
            }

            if (_settings.ConnectionBacklog > 0)
            {
                options.WithConnectionBacklog(_settings.ConnectionBacklog);
            }

            if (_settings.EnablePersistentSessions)
            {
                options.WithPersistentSessions();
            }

            return(options.Build());
        }
Exemplo n.º 10
0
        private async void MqttServer()
        {
            if (null != _mqttServer)
            {
                return;
            }

            var optionBuilder =
                new MqttServerOptionsBuilder().WithConnectionBacklog(1000).WithDefaultEndpointPort(Convert.ToInt32(TxbPort.Text));

            if (!TxbServer.Text.IsNullOrEmpty())
            {
                optionBuilder.WithDefaultEndpointBoundIPAddress(IPAddress.Parse(TxbServer.Text));
            }

            var options = optionBuilder.Build();

            (options as MqttServerOptions).ConnectionValidator += context =>
            {
                if (context.ClientId.Length < 10)
                {
                    context.ReturnCode = MqttConnectReturnCode.ConnectionRefusedIdentifierRejected;
                    return;
                }
                if (!context.Username.Equals("admin"))
                {
                    context.ReturnCode = MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
                    return;
                }
                if (!context.Password.Equals("public"))
                {
                    context.ReturnCode = MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
                    return;
                }
                context.ReturnCode = MqttConnectReturnCode.ConnectionAccepted;
            };

            _mqttServer = new MqttFactory().CreateMqttServer();
            _mqttServer.ClientConnected += (sender, args) =>
            {
                listBox1.BeginInvoke(_updateListBoxAction, $">Client Connected:ClientId:{args.ClientId},ProtocalVersion:");

                var s = _mqttServer.GetClientSessionsStatusAsync();
                label3.BeginInvoke(new Action(() => { label3.Text = $"Total Count:{s.Result.Count}"; }));
            };

            _mqttServer.ClientDisconnected += (sender, args) =>
            {
                listBox1.BeginInvoke(_updateListBoxAction, $"<Client DisConnected:ClientId:{args.ClientId}");
                var s = _mqttServer.GetClientSessionsStatusAsync();
                label3.BeginInvoke(new Action(() => { label3.Text = $"Total Count:{s.Result.Count}"; }));
            };

            _mqttServer.ApplicationMessageReceived += (sender, args) =>
            {
                listBox1.BeginInvoke(_updateListBoxAction,
                                     $"ClientId:{args.ClientId} Topic:{args.ApplicationMessage.Topic} Payload:{Encoding.UTF8.GetString(args.ApplicationMessage.Payload)} QualityOfServiceLevel:{args.ApplicationMessage.QualityOfServiceLevel}");
            };

            _mqttServer.ClientSubscribedTopic += (sender, args) =>
            {
                listBox1.BeginInvoke(_updateListBoxAction, $"@ClientSubscribedTopic ClientId:{args.ClientId} Topic:{args.TopicFilter.Topic} QualityOfServiceLevel:{args.TopicFilter.QualityOfServiceLevel}");
            };
            _mqttServer.ClientUnsubscribedTopic += (sender, args) =>
            {
                listBox1.BeginInvoke(_updateListBoxAction, $"%ClientUnsubscribedTopic ClientId:{args.ClientId} Topic:{args.TopicFilter.Length}");
            };

            _mqttServer.Started += (sender, args) =>
            {
                listBox1.BeginInvoke(_updateListBoxAction, "Mqtt Server Start...");
            };

            _mqttServer.Stopped += (sender, args) =>
            {
                listBox1.BeginInvoke(_updateListBoxAction, "Mqtt Server Stop...");
            };

            await _mqttServer.StartAsync(options);
        }
Exemplo n.º 11
0
        protected override void Start()
        {
            if (null != _mqttServer)
            {
                return;
            }
            ///相关参数不能为空
            if (this.IOServer == null || this.IOCommunication == null)
            {
                return;
            }

            var optionBuilder =
                new MqttServerOptionsBuilder().WithConnectionBacklog(1000).WithDefaultEndpointPort(ServerPort);

            if (!String.IsNullOrEmpty(ServerIP))
            {
                optionBuilder.WithDefaultEndpointBoundIPAddress(IPAddress.Parse(ServerIP));
            }

            var options = optionBuilder.Build();


            //连接验证
            (options as MqttServerOptions).ConnectionValidator += context =>
            {
                string clientId = "";
                Task.Run(() =>
                {
                    try
                    {
                        ParaPack paraPack = new ParaPack(this.IOCommunication.IO_COMM_PARASTRING);

                        if (context.ClientId.Length < 2)
                        {
                            context.ReturnCode = MqttConnectReturnCode.ConnectionRefusedIdentifierRejected;
                            return;
                        }
                        if (EaableAnonymousAuthentication)
                        {
                            if (!context.Username.Equals(this.UserName))
                            {
                                context.ReturnCode = MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
                                return;
                            }
                            if (!context.Password.Equals(this.Password))
                            {
                                context.ReturnCode = MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
                                return;
                            }
                        }
                        bool isValidCleint = false;

                        for (int i = 0; i < IODevices.Count; i++)
                        {
                            ParaPack deviceparaPack = new ParaPack(IODevices[i].IO_DEVICE_PARASTRING);
                            clientId = deviceparaPack.GetValue("MQTT连接ID号").Trim();    // 将字符串转换为字符数组
                            if (clientId.Trim() == context.ClientId.Trim())
                            {
                                isValidCleint    = true;
                                IODevices[i].Tag = clientId.Trim();//标记对应的客户端ID号
                            }
                        }
                        if (isValidCleint)
                        {
                            context.ReturnCode = MqttConnectReturnCode.ConnectionAccepted;
                        }
                        else
                        {
                            context.ReturnCode = MqttConnectReturnCode.ConnectionRefusedIdentifierRejected;
                        }
                    }
                    catch
                    {
                        context.ReturnCode = MqttConnectReturnCode.ConnectionRefusedIdentifierRejected;
                    }
                    if (string.IsNullOrEmpty(clientId))
                    {
                        context.ReturnCode = MqttConnectReturnCode.ConnectionRefusedIdentifierRejected;
                    }
                });
            };


            _mqttServer = new MqttFactory().CreateMqttServer();


            //开始连接
            _mqttServer.ClientConnected += (sender, args) =>
            {
                if (args.ClientId == null || args.ClientId == "")
                {
                    return;
                }


                IO_DEVICE device = this.IODevices.Find(x => x.Tag.ToString().Trim() == args.ClientId.Trim());
                if (device == null)
                {
                    for (int i = 0; i < IODevices.Count; i++)
                    {
                        ParaPack deviceparaPack = new ParaPack(IODevices[i].IO_DEVICE_PARASTRING);
                        string   clientId       = deviceparaPack.GetValue("MQTT连接ID号").Trim(); // 将字符串转换为字符数组
                        if (clientId.Trim() == args.ClientId.Trim())
                        {
                            IODevices[i].Tag = clientId.Trim();//标记对应的客户端ID号
                            device           = IODevices[i];
                            break;
                        }
                    }
                }
                if (device == null)
                {
                    return;
                }



                ParaPack commPack   = new ParaPack(this.IOCommunication.IO_COMM_PARASTRING);
                ParaPack devicePack = new ParaPack(device.IO_DEVICE_PARASTRING);
                #region 通用MQTT解析
                {
                    //客户端连接上后发布订阅数据
                    List <TopicFilter> topicFilters = new List <TopicFilter>();
                    device.IO_DEVICE_STATUS = 1;
                    this.DeviceStatus(this.IOServer, IOCommunication, device, null, "1");

                    string clientId = devicePack.GetValue("MQTT连接ID号").Trim();    // 将字符串转换为字符数组
                    device.Tag = clientId;
                    if (clientId.Trim() == args.ClientId.Trim())
                    {
                        TopicFilter topicFilter = new TopicFilter(devicePack.GetValue("数据订阅主题").Trim(), MessageQulity);
                        topicFilters.Add(topicFilter);
                        try
                        {
                            Task.Run(async() =>
                            {
                                await _mqttServer.SubscribeAsync(args.ClientId.Trim(), topicFilters);
                            });
                        }
                        catch (Exception)
                        {
                            this.DeviceException("ERROR=MQTTNet_20006,发布订阅主题失败 ");
                        }
                    }
                    else
                    {
                        this.DeviceException("ERROR=MQTTNet_20006,MQTT ID与设备配置ID不匹配 ");
                    }
                    //定时向客户端发布一个读取数据的订阅
                    if (commPack.GetValue("接收方式") == "主动")
                    {
                        MQTTTimer cleintMqtt = new MQTTTimer()
                        {
                            ClientID = args.ClientId
                        };
                        MqttClientTimes.Add(cleintMqtt);

                        cleintMqtt.Timer = new Timer(delegate
                        {
                            if (!cleintMqtt.IsStop)
                            {
                                try
                                {
                                    _mqttServer.PublishAsync(
                                        new MqttApplicationMessage()
                                    {
                                        QualityOfServiceLevel = MessageQulity,
                                        Retain  = false,
                                        Topic   = devicePack.GetValue("主动请求主题").Trim(),
                                        Payload = Encoding.UTF8.GetBytes("{\"uid\":\"" + devicePack.GetValue("设备ID编码").Trim() + "\",\"updatecycle\":\"" + device.IO_DEVICE_UPDATECYCLE + "\",\"topic\":\"" + devicePack.GetValue("数据订阅主题").Trim() + "\"}")
                                    }

                                        );
                                    ///服务端向客户端发送一个服务器端循环查询数据的周期

                                    _mqttServer.PublishAsync(
                                        new MqttApplicationMessage()
                                    {
                                        QualityOfServiceLevel = MessageQulity,
                                        Retain  = false,
                                        Topic   = devicePack.GetValue("循环周期主题").Trim(),
                                        Payload = Encoding.UTF8.GetBytes("{\"uid\":\"" + devicePack.GetValue("设备ID编码").Trim() + "\",\"updatecycle\":\"" + device.IO_DEVICE_UPDATECYCLE + "\",\"topic\":\"" + devicePack.GetValue("数据订阅主题").Trim() + "\"}")
                                    }

                                        );
                                }
                                catch (Exception)
                                {
                                    this.DeviceException("ERROR=MQTTNet_20006,发布订阅主题失败 ");
                                }
                            }
                        }, args, 1000, device.IO_DEVICE_UPDATECYCLE * 1000);
                    }
                }
                #endregion
            };
            ///断开连接
            _mqttServer.ClientDisconnected += (sender, args) =>
            {
                Task.Run(() =>
                {
                    if (args.WasCleanDisconnect)
                    {
                        IO_DEVICE device = this.IODevices.Find(x => x.Tag.ToString().Trim() == args.ClientId.Trim());
                        if (device != null)
                        {
                            device.IO_DEVICE_STATUS = 0;
                            this.DeviceStatus(this.IOServer, IOCommunication, device, null, "0");
                        }
                    }
                });
                MQTTTimer cleintTimer = MqttClientTimes.Find(x => x.ClientID == args.ClientId);
                if (cleintTimer != null)
                {
                    cleintTimer.Close();
                    MqttClientTimes.Remove(cleintTimer);
                }
            };
            ///接收到订阅主题的数据数据

            _mqttServer.ApplicationMessageReceived += (sender, args) =>
            {
                if (args.ClientId == null || args.ClientId.Trim() == "")
                {
                    return;
                }

                if (args.ApplicationMessage.Payload == null || args.ApplicationMessage.Payload.Length <= 0)
                {
                    this.DeviceException("接收的数据为空");

                    return;
                }
                ParaPack commPack = new ParaPack(this.IOCommunication.IO_COMM_PARASTRING);

                try
                {
                    Task.Run(() =>
                    {
                        string cleintId = args.ClientId.Trim();
                        //将接收到的数据发送到实际的对应的解析数据库中

                        List <IO_DEVICE> selects = this.IODevices.FindAll(x => x.Tag.ToString().Trim() == args.ClientId.Trim());
                        if (selects.Count <= 0)
                        {
                            return;
                        }

                        string strs = ScadaHexByteOperator.UTF8ByteToString(args.ApplicationMessage.Payload);

                        IO_DEVICE device = null;
                        for (int i = 0; i < selects.Count; i++)
                        {
                            ParaPack selePack = new ParaPack(selects[i].IO_DEVICE_PARASTRING);

                            #region
                            CommonMqttJsonObject mqttJsonObject = ScadaHexByteOperator.JsonToObject <CommonMqttJsonObject>(strs);
                            if (mqttJsonObject == null || mqttJsonObject.paras == null || mqttJsonObject.paras.Count <= 0)
                            {
                                this.DeviceException("接收数据对象转换失败了,没有数据" + strs.Count());
                                this.DeviceException(strs);
                                continue;
                            }

                            string selectUid = selePack.GetValue("设备ID编码");
                            if (selectUid.Trim() == mqttJsonObject.device.uid.Trim())
                            {
                                device = selects[i];
                                break;
                            }
                            #endregion
                        }
                        if (device == null)
                        {
                            return;
                        }
                        device.IO_DEVICE_STATUS = 1;
                        ParaPack paraPack       = new ParaPack(device.IO_DEVICE_PARASTRING);
                        #region
                        string deviceUid = paraPack.GetValue("设备ID编码");
                        if (!string.IsNullOrEmpty(device.IO_DEVICE_PARASTRING) && args.ApplicationMessage.Topic.Trim() == paraPack.GetValue("数据订阅主题").Trim())
                        {
                            CommonMqttJsonObject mqttJsonObject = ScadaHexByteOperator.JsonToObject <CommonMqttJsonObject>(strs);
                            this.ReceiveData(this.IOServer, IOCommunication, device, args.ApplicationMessage.Payload, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), mqttJsonObject);
                        }
                        #endregion
                    });
                }
                catch
                {
                    return;
                }
            };
            ///订阅主题

            _mqttServer.ClientSubscribedTopic += (sender, args) =>
            {
            };
            ///取消订阅主题
            _mqttServer.ClientUnsubscribedTopic += (sender, args) =>
            {
            };

            _mqttServer.Started += (sender, args) =>
            {
                this.IOCommunication.IO_COMM_STATUS = 1;
            };

            _mqttServer.Stopped += (sender, args) =>
            {
                this.IOCommunication.IO_COMM_STATUS = 0;
            };
            _mqttServer.StartAsync(options);

            ParaPack commpack = new ParaPack(this.IOCommunication.IO_COMM_PARASTRING);


            this.CommunctionStartChanged(this.IOServer, this.IOServer.SERVER_IP + " " + this.IOServer.SERVER_NAME + "启动服务");
        }
Exemplo n.º 12
0
        private async void MqttServer()
        {
            if (_mqttServer is not null)
            {
                return;
            }

            var optionBuilder =
                new MqttServerOptionsBuilder()
                .WithConnectionBacklog(1000)
                .WithDefaultEndpointPort(Convert.ToInt32(TxbPort.Text));

            if (!string.IsNullOrEmpty(TxbServer.Text))
            {
                optionBuilder.WithDefaultEndpointBoundIPAddress(IPAddress.Parse(TxbServer.Text));
            }

            optionBuilder.WithConnectionValidator(c =>
            {
                if (c.ClientId.Length < 10)
                {
                    c.ReasonCode = MqttConnectReasonCode.ClientIdentifierNotValid;
                    return;
                }

                if (!c.Username.Equals("admin"))
                {
                    c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
                    return;
                }

                if (!c.Password.Equals("public"))
                {
                    c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
                    return;
                }

                c.ReasonCode = MqttConnectReasonCode.Success;
            });

            _mqttServer = new MqttFactory().CreateMqttServer();
            _mqttServer.ClientConnectedHandler = new MqttServerClientConnectedHandlerDelegate(e =>
            {
                listBox1.BeginInvoke(_updateListBoxAction, $"{DateTime.Now} Client Connected:ClientId:{e.ClientId}");
                var s = _mqttServer.GetSessionStatusAsync();
                lblClientCount.BeginInvoke(new Action(() => { lblClientCount.Text = $@"{DateTime.Now} 连接总数:{s.Result.Count}"; }));
            });

            _mqttServer.ClientDisconnectedHandler = new MqttServerClientDisconnectedHandlerDelegate(e =>
            {
                listBox1.BeginInvoke(_updateListBoxAction, $"{DateTime.Now} Client Disconnected:ClientId:{e.ClientId}");
                var s = _mqttServer.GetSessionStatusAsync();
                lblClientCount.BeginInvoke(new Action(() => { lblClientCount.Text = $@"{DateTime.Now} 连接总数:{s.Result.Count}"; }));
            });

            _mqttServer.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(e =>
            {
                listBox1.BeginInvoke(_updateListBoxAction,
                                     $"{DateTime.Now} ClientId:{e.ClientId} Topic:{e.ApplicationMessage.Topic} Payload:{Encoding.UTF8.GetString(e.ApplicationMessage.Payload)} QualityOfServiceLevel:{e.ApplicationMessage.QualityOfServiceLevel}");
            });

            _mqttServer.ClientSubscribedTopicHandler = new MqttServerClientSubscribedHandlerDelegate(e =>
            {
                listBox1.BeginInvoke(_updateListBoxAction, $"{DateTime.Now} Client subscribed topic. ClientId:{e.ClientId} Topic:{e.TopicFilter.Topic} QualityOfServiceLevel:{e.TopicFilter.QualityOfServiceLevel}");
            });

            _mqttServer.ClientUnsubscribedTopicHandler = new MqttServerClientUnsubscribedTopicHandlerDelegate(e =>
            {
                listBox1.BeginInvoke(_updateListBoxAction, $"{DateTime.Now} Client unsubscribed topic. ClientId:{e.ClientId} Topic:{e.TopicFilter.Length}");
            });

            _mqttServer.StartedHandler = new MqttServerStartedHandlerDelegate(e =>
            {
                listBox1.BeginInvoke(_updateListBoxAction, $"{DateTime.Now} Mqtt Server Started...");
            });

            _mqttServer.StoppedHandler = new MqttServerStoppedHandlerDelegate(e =>
            {
                listBox1.BeginInvoke(_updateListBoxAction, $"{DateTime.Now} Mqtt Server Stopped...");
            });

            await _mqttServer.StartAsync(optionBuilder.Build());
        }
Exemplo n.º 13
0
        static Igloo15MqttServer InitializeServer(Options config, ILoggerFactory factory)
        {
            Igloo15MqttServer server = null;

            try
            {
                MqttServerOptionsBuilder serverBuilder = new MqttServerOptionsBuilder();

                if (config.Encrypted && File.Exists(config.CertificateLocation))
                {
                    if (config.IPAddress == "Any")
                    {
                        serverBuilder.WithEncryptedEndpoint();
                    }
                    else if (IPAddress.TryParse(config.IPAddress, out IPAddress address))
                    {
                        serverBuilder.WithEncryptedEndpointBoundIPAddress(address);
                    }
                    else
                    {
                        _logger.LogWarning($"Failed to parse provided IP Address : {config.IPAddress} using default");
                        serverBuilder.WithEncryptedEndpoint();
                    }

                    serverBuilder.WithEncryptedEndpointPort(config.Port);

                    var certificate = new X509Certificate2(config.CertificateLocation, config.CertificatePassword);
                    var certBytes   = certificate.Export(X509ContentType.Cert);

                    serverBuilder.WithEncryptionCertificate(certBytes);
                }
                else
                {
                    if (config.IPAddress == "Any")
                    {
                        serverBuilder.WithDefaultEndpoint();
                    }
                    else if (IPAddress.TryParse(config.IPAddress, out IPAddress address))
                    {
                        serverBuilder.WithDefaultEndpointBoundIPAddress(address);
                    }
                    else
                    {
                        _logger.LogWarning("Failed to parse provided IP Address : {IPAddress} using default", config.IPAddress);
                        serverBuilder.WithDefaultEndpoint();
                    }

                    serverBuilder.WithDefaultEndpointPort(config.Port);
                }

                if (config.Persistent)
                {
                    serverBuilder.WithPersistentSessions();
                }

                if (!String.IsNullOrEmpty(config.MessageStorageLocation))
                {
                    serverBuilder.WithStorage(new RetainedMessageHandler(config.MessageStorageLocation));
                }

                if (config.ShowSubscriptions)
                {
                    serverBuilder.WithSubscriptionInterceptor(_interceptors.SubscriptionInterceptor);
                }

                if (config.ShowMessages)
                {
                    serverBuilder.WithApplicationMessageInterceptor(_interceptors.MessageInterceptor);
                }

                if (config.ShowClientConnections)
                {
                    serverBuilder.WithConnectionValidator(_interceptors.ConnectionInterceptor);
                }

                serverBuilder
                .WithConnectionBacklog(config.ConnectionBacklog)
                .WithMaxPendingMessagesPerClient(config.MaxPendingMessagesPerClient)
                .WithDefaultCommunicationTimeout(TimeSpan.FromSeconds(config.CommunicationTimeout));


                server = new Igloo15MqttServer(serverBuilder.Build(), factory);
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Exception occured during Initialization of Server");
                return(null);
            }

            return(server);
        }
Exemplo n.º 14
0
        private async void btnStart_Click(object sender, EventArgs e)
        {
            if (this.mqttServer != null)
            {
                return;
            }

            this.mqttServer = new MqttFactory().CreateMqttServer();
            this.mqttServer.StartedHandler                    = this;
            this.mqttServer.StoppedHandler                    = this;
            this.mqttServer.ClientConnectedHandler            = this;
            this.mqttServer.ClientDisconnectedHandler         = this;
            this.mqttServer.ClientSubscribedTopicHandler      = this;
            this.mqttServer.ClientUnsubscribedTopicHandler    = this;
            this.mqttServer.ApplicationMessageReceivedHandler = this;

            var optionsBuilder = new MqttServerOptionsBuilder().WithConnectionBacklog(1000).WithDefaultEndpointPort(Convert.ToInt32(tbxPort.Text));

            if (!string.IsNullOrEmpty(tbxServer.Text))
            {
                optionsBuilder.WithDefaultEndpointBoundIPAddress(IPAddress.Parse(tbxServer.Text));
            }

            optionsBuilder.WithConnectionValidator(context =>
            {
                if (string.IsNullOrEmpty(context.ClientId))
                {
                    context.ReasonCode = MqttConnectReasonCode.ClientIdentifierNotValid;
                    return;
                }

                if (context.Username != Settings.Default.Username || context.Password != Settings.Default.Password)
                {
                    context.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
                    return;
                }

                context.ReasonCode = MqttConnectReasonCode.Success;
            });

            optionsBuilder.WithApplicationMessageInterceptor(context =>
            {
                // 控管 client 發佈
                if (string.IsNullOrEmpty(context.ClientId) || !context.ClientId.StartsWith(Settings.Default.ClientId))
                {
                    context.AcceptPublish = false;
                    return;
                }
            });

            optionsBuilder.WithSubscriptionInterceptor(context =>
            {
                // 控管 client 訂閱
                if (!context.ClientId.StartsWith(Settings.Default.ClientId))
                {
                    context.AcceptSubscription = false;
                    return;
                }
            });

            await this.mqttServer.StartAsync(optionsBuilder.Build());

            tbxServer.Enabled = false;
            tbxPort.Enabled   = false;
            btnStart.Enabled  = false;
            btnStop.Enabled   = true;
        }
Exemplo n.º 15
0
        IMqttServerOptions CreateMqttServerOptions()
        {
            // Create client id if none provided
            var cid = string.IsNullOrWhiteSpace(_settings.BrokerClientId) ? Guid.NewGuid().ToString("N").ToUpper() : _settings.BrokerClientId;

            var options = new MqttServerOptionsBuilder()
                          .WithMaxPendingMessagesPerClient(_settings.MaxPendingMessagesPerClient)
                          .WithDefaultCommunicationTimeout(TimeSpan.FromSeconds(_settings.CommunicationTimeout))
                          .WithConnectionValidator(_mqttConnectionValidator)
                          .WithApplicationMessageInterceptor(_mqttApplicationMessageInterceptor)
                          .WithSubscriptionInterceptor(_mqttSubscriptionInterceptor)
                          .WithUnsubscriptionInterceptor(_mqttUnsubscriptionInterceptor)
                          .WithClientId(cid);

            // Configure unencrypted connections
            if (_settings.TcpEndPoint.Enabled)
            {
                options.WithDefaultEndpoint();

                if (_settings.TcpEndPoint.TryReadIPv4(out var address4))
                {
                    options.WithDefaultEndpointBoundIPAddress(address4);
                }

                if (_settings.TcpEndPoint.TryReadIPv6(out var address6))
                {
                    options.WithDefaultEndpointBoundIPV6Address(address6);
                }

                if (_settings.TcpEndPoint.Port > 0)
                {
                    options.WithDefaultEndpointPort(_settings.TcpEndPoint.Port);
                    _logger.LogInformation($"MQTT Broker '{_settings.BrokerName}' listening on TCP port {_settings.TcpEndPoint.Port}, ClientID: {cid}");
                }
            }
            else
            {
                options.WithoutDefaultEndpoint();
            }

            // Configure encrypted connections
            if (_settings.EncryptedTcpEndPoint.Enabled)
            {
                options
                .WithEncryptedEndpoint()
                .WithEncryptionSslProtocol(SslProtocols.Tls13);

                if (!string.IsNullOrEmpty(_settings.EncryptedTcpEndPoint?.Certificate?.Path))
                {
                    IMqttServerCertificateCredentials certificateCredentials = null;

                    if (!string.IsNullOrEmpty(_settings.EncryptedTcpEndPoint?.Certificate?.Password))
                    {
                        certificateCredentials = new MqttServerCertificateCredentials
                        {
                            Password = _settings.EncryptedTcpEndPoint.Certificate.Password
                        };
                    }

                    options.WithEncryptionCertificate(_settings.EncryptedTcpEndPoint.Certificate.ReadCertificate(), certificateCredentials);
                }

                if (_settings.EncryptedTcpEndPoint.TryReadIPv4(out var address4))
                {
                    options.WithEncryptedEndpointBoundIPAddress(address4);
                }

                if (_settings.EncryptedTcpEndPoint.TryReadIPv6(out var address6))
                {
                    options.WithEncryptedEndpointBoundIPV6Address(address6);
                }

                if (_settings.EncryptedTcpEndPoint.Port > 0)
                {
                    options.WithEncryptedEndpointPort(_settings.EncryptedTcpEndPoint.Port);
                    _logger.LogInformation($"MQTT Broker {_settings.BrokerName} listening on SSL port {_settings.TcpEndPoint.Port}");
                }
            }
            else
            {
                options.WithoutEncryptedEndpoint();
            }

            if (_settings.ConnectionBacklog > 0)
            {
                options.WithConnectionBacklog(_settings.ConnectionBacklog);
            }

            if (_settings.EnablePersistentSessions)
            {
                options.WithPersistentSessions();
            }

            return(options.Build());
        }
Exemplo n.º 16
0
        public void Start(out string errMsg)
        {
            errMsg = "";
            if (IsRuning)
            {
                return;
            }

            if (this.mqttParam == null)
            {
                errMsg = "MQTT服务启动失败,没有指明服务所需参数";
                return;
            }
            // 检查端口是否空闲
            if (!IPTool.IsValidPort(this.mqttParam.port))
            {
                errMsg = "数据发布服务器的监听端口被占用,请更换端口号";
                return;
            }
            if (mqttServer == null)
            {
                try
                {
                    mqttServer.StopAsync();
                    mqttServer = null;
                }
                catch { }
            }

            // MQTT 动态库本身已经实现异步启动,这里不用在用异步调用了

            try
            {
                var optionsBuilder = new MqttServerOptionsBuilder();

                // //在 MqttServerOptions 选项中,你可以使用 ConnectionValidator 来对客户端连接进行验证。
                // //比如客户端ID标识 ClientId,用户名 Username 和密码 Password 等。
                optionsBuilder.WithConnectionValidator(ClientCheck);
                //指定 ip地址,默认为本地
                if (string.IsNullOrWhiteSpace(this.mqttParam.ip))
                {
                    optionsBuilder.WithDefaultEndpointBoundIPAddress(IPAddress.Parse(this.mqttParam.ip));
                }
                else
                {
                    optionsBuilder.WithDefaultEndpointBoundIPAddress(IPAddress.Any);
                }
                //指定端口
                optionsBuilder.WithDefaultEndpointPort(this.mqttParam.port);

                // //  optionsBuilder.WithConnectionBacklog(100).WithEncryptedEndpointBoundIPAddress(IPAddress.Any).WithEncryptedEndpointPort(9323);

                // var certificate = new X509Certificate(@"D:\ddd.cer", "");
                //var  options = optionsBuilder.Build();
                // options.TlsEndpointOptions.Certificate = certificate.Export(X509ContentType.Cert);

                // //ssl
                //var certificate = new X509Certificate(@"D:\ddd.cer", "");
                //MqttServerOptions certifOption = new MqttServerOptions();
                //certifOption.TlsEndpointOptions.Certificate = certificate.Export(X509ContentType.Cert);
                //certifOption.TlsEndpointOptions.IsEnabled = true;
                //optionsBuilder.WithEncryptionCertificate(certifOption.TlsEndpointOptions.Certificate);



                // var optionsBuilder = new MqttServerOptionsBuilder()
                //.WithConnectionBacklog(100)
                //.WithEncryptedEndpointPort(1884)
                //.WithoutDefaultEndpoint();

                var mqttServer = new MqttFactory().CreateMqttServer();



                //连接记录数,默认 一般为2000
                //optionsBuilder.WithConnectionBacklog(2000);
                mqttServer = new MqttFactory().CreateMqttServer() as MqttServer;

                // 客户端支持 Connected、Disconnected 和 ApplicationMessageReceived 事件,
                //用来处理客户端与服务端连接、客户端从服务端断开以及客户端收到消息的事情。
                //其中 ClientConnected 和 ClientDisconnected 事件的事件参数一个客户端连接对象 ConnectedMqttClient,
                //通过该对象可以获取客户端ID标识 ClientId 和 MQTT 版本 ProtocolVersion。
                mqttServer.ClientConnected    += MqttServer_ClientConnected;
                mqttServer.ClientDisconnected += MqttServer_ClientDisconnected;

                //ApplicationMessageReceived 的事件参数包含了客户端ID标识 ClientId 和 MQTT 应用消息 MqttApplicationMessage 对象,
                //通过该对象可以获取主题 Topic、QoS QualityOfServiceLevel 和消息内容 Payload 等信息。
                mqttServer.ApplicationMessageReceived += MqttServer_ApplicationMessageReceived;

                //  Task task = mqttServer.StartAsync(options);
                Task task = mqttServer.StartAsync(optionsBuilder.Build());
                task.Wait(5000);
                IsRuning = task.IsCompleted;
            }
            catch (Exception ex)
            {
                // log.Info("创建Mqtt服务,连接客户端的Id长度过短(不得小于5),或不是指定的合法客户端(以Eohi_开头)");
                errMsg = "创建MQTT服务失败:" + ex.Message + "堆栈:" + ex.StackTrace;
                return;
            }
            //Task task = mqttServer.StartAsync(options);
            ////  Task task = mqttServer.StartAsync(optionsBuilder.Build());
            //task.Wait(5000);
        }