Exemplo n.º 1
0
        public void Start()
        {
            _storageService.TryReadOrCreate(out MqttServiceOptions options, MqttServiceOptions.Filename);

            var mqttFactory = new MqttFactory();

            _enableMqttLogging = options.EnableLogging;
            if (_enableMqttLogging)
            {
                _mqttServer = mqttFactory.CreateMqttServer(new LoggerAdapter(_logger));
            }
            else
            {
                _mqttServer = mqttFactory.CreateMqttServer();
            }

            _mqttServer.UseApplicationMessageReceivedHandler(new MqttApplicationMessageReceivedHandlerDelegate(e => OnApplicationMessageReceived(e)));

            var serverOptions = new MqttServerOptionsBuilder()
                                .WithDefaultEndpointPort(options.ServerPort)
                                .WithPersistentSessions();

            if (options.PersistRetainedMessages)
            {
                var storage = new MqttServerStorage(_storageService, _logger);
                storage.Start();
                serverOptions.WithStorage(storage);
            }

            _mqttServer.StartAsync(serverOptions.Build()).GetAwaiter().GetResult();

            Task.Factory.StartNew(() => ProcessIncomingMqttMessages(_systemCancellationToken.Token), _systemCancellationToken.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
        }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            var optionsBuilder = new MqttServerOptionsBuilder()
                                 .WithConnectionValidator(c =>
            {
                Console.WriteLine($"{c.ClientId} connection validator for c.Endpoint: {c.Endpoint}");
                c.ReasonCode = MqttConnectReasonCode.Success;
            })
                                 .WithApplicationMessageInterceptor(context =>
            {
                Console.WriteLine("WithApplicationMessageInterceptor block merging data");
                var newData    = Encoding.UTF8.GetBytes(DateTime.Now.ToString("O"));
                var oldData    = context.ApplicationMessage.Payload;
                var mergedData = newData.Concat(oldData).ToArray();
                context.ApplicationMessage.Payload = mergedData;
            })
                                 .WithDefaultEndpointBoundIPAddress(IPAddress.Loopback) // Set IP address
                                 .WithConnectionBacklog(100)
                                 .WithDefaultEndpointPort(1884);

            //start server
            var mqttServer = new MqttFactory().CreateMqttServer();

            mqttServer.StartAsync(optionsBuilder.Build());

            Console.WriteLine($"Broker is Running: Host: {mqttServer.Options.DefaultEndpointOptions.BoundInterNetworkAddress} Port: {mqttServer.Options.DefaultEndpointOptions.Port}");
            Console.WriteLine("Press any key to exit.");
            Console.ReadLine();

            Task.Run(() => Thread.Sleep(Timeout.Infinite)).Wait();

            mqttServer.StopAsync().Wait();
        }
Exemplo n.º 3
0
        static async Task Main(string[] args)
        {
            var optionsBuilder = new MqttServerOptionsBuilder()
                                 .WithConnectionBacklog(100)
                                 .WithDefaultEndpointPort(1884);

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

            mqttServer.ApplicationMessageReceived += (s, e) =>
            {
                Console.WriteLine();
                Console.WriteLine("### Mensagem Recebida ###");
                Console.WriteLine($"+ ClientId = {e.ClientId}");
                Console.WriteLine($"+ Topico = {e.ApplicationMessage.Topic}");
                Console.WriteLine($"+ Mensagem = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
                Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
                Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}");
                Console.WriteLine();
            };

            Console.WriteLine("Server Mqtt iniciado...");
            Console.WriteLine("Pressione qualquer tecla para fechar");
            Console.ReadLine();
            await mqttServer.StopAsync();
        }
Exemplo n.º 4
0
        static void Main(string[] args)
        {
            //Console.WriteLine("Hello World1!");
            //configure options
            var optionsBuilder = new MqttServerOptionsBuilder()
                                 .WithConnectionValidator(c =>
            {
                Console.WriteLine($"{c.ClientId} connection validator for c.Endpoint: {c.Endpoint}");
                c.ReasonCode = MqttConnectReasonCode.Success;
            })
                                 .WithConnectionBacklog(100)
                                 .WithDefaultEndpointPort(1884);


            //start server
            var mqttServer = new MqttFactory().CreateMqttServer();

            mqttServer.StartAsync(optionsBuilder.Build()).Wait();

            Console.WriteLine($"Broker is Running: Host: {mqttServer.Options.DefaultEndpointOptions.BoundInterNetworkAddress} Port: {mqttServer.Options.DefaultEndpointOptions.Port}");
            Console.WriteLine("Press any key to exit.");
            Console.ReadLine();

            mqttServer.StopAsync().Wait();
        }
Exemplo n.º 5
0
        private static async Task StartServer()
        {
            var optionsBuilder = new MqttServerOptionsBuilder()
                                 .WithConnectionBacklog(100)
                                 .WithDefaultEndpointPort(1883);

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

            var ct            = new CancellationTokenSource();
            var heartbeatTask = Task.Run(async() => await ServerHeartbeat(ct.Token, mqttServer));

            Console.WriteLine("Type 'quit' to exit");

            while (true)
            {
                string input = Console.ReadLine();

                if (input != null && input.Contains("quit"))
                {
                    break;
                }
            }
            ct.Cancel();
            await heartbeatTask;
            await mqttServer.StopAsync();
        }
Exemplo n.º 6
0
        //static  DeviceContext db = new DeviceContext();
        public static void ConfigureAndStart()
        {
            DeviceContext db = new DeviceContext();

            var optionsBuilder = new MqttServerOptionsBuilder()
                                 .WithDefaultEndpointPort(1884);

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

            // mqttServer.UseApplicationMessageReceivedHandler(new MqttMessageReceivedHandler());
            mqttServer.UseApplicationMessageReceivedHandler(e =>
            {
                string payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                //Console.WriteLine(payload);

                Device device = new Device {
                    Temperature = payload
                };
                db.devices.Add(device);
                db.SaveChanges();
                //db.devices.Add(new Device { Id = 2, Temperature = payload });
                //db.devices.Add(new Device {Id =4, Temperature= 3.ToString() });
            });

            mqttServer.StartAsync(optionsBuilder.Build()).GetAwaiter().GetResult();
        }
Exemplo n.º 7
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Starting MQTT Daemon on port " + _config.Value.Port);

            //Building the config
            var optionsBuilder = new MqttServerOptionsBuilder()
                                 .WithConnectionBacklog(1000)
                                 .WithDefaultEndpointPort(_config.Value.Port);


            //Getting an MQTT Instance
            _mqttServer = new MqttFactory().CreateMqttServer();

            //Wiring up all the events...

            _mqttServer.ClientSubscribedTopic      += _mqttServer_ClientSubscribedTopic;
            _mqttServer.ClientUnsubscribedTopic    += _mqttServer_ClientUnsubscribedTopic;
            _mqttServer.ClientConnected            += _mqttServer_ClientConnected;
            _mqttServer.ClientDisconnected         += _mqttServer_ClientDisconnected;
            _mqttServer.ApplicationMessageReceived += _mqttServer_ApplicationMessageReceived;

            //Now, start the server -- Notice this is resturning the MQTT Server's StartAsync, which is a task.
            await _mqttServer.StartAsync(optionsBuilder.Build());

            return;
        }
Exemplo n.º 8
0
        public void Start(ConnectionOptions options)
        {
            //configure options
            var optionsBuilder = new MqttServerOptionsBuilder()
                                 .WithConnectionValidator(context =>
            {
                _logger?.Log(nameof(Broker), $"{context.ClientId} connection validator for c.Endpoint: {context.Endpoint}");
                context.ReasonCode = MqttConnectReasonCode.Success;
            })
                                 .WithApplicationMessageInterceptor(context =>
            {
                _logger?.Log(nameof(Broker), $"Intercept data");

                //var newData = Encoding.UTF8.GetBytes(DateTime.Now.ToString("O"));
                //var oldData = context.ApplicationMessage.Payload;
                //var mergedData = newData.Concat(oldData).ToArray();
                //context.ApplicationMessage.Payload = mergedData;
            })
                                 .WithConnectionBacklog(100)
                                 .WithDefaultEndpointBoundIPAddress(IPAddress.Parse(options.IpAddress))
                                 .WithDefaultEndpointPort(options.Port)
            ;


            //start server
            _mqttServer = new MqttFactory().CreateMqttServer();
            _mqttServer.StartAsync(optionsBuilder.Build()).Wait();
        }
Exemplo n.º 9
0
        static void Main(string[] args)
        {
            var optionsBuilder = new MqttServerOptionsBuilder()
                                 .WithDefaultEndpoint().WithDefaultEndpointPort(1883) // For testing purposes only
                                                                                      //.WithEncryptedEndpoint().WithEncryptedEndpointPort(config.Port)
                                                                                      //.WithEncryptionCertificate(certificate.Export(X509ContentType.Pfx))
                                                                                      //.WithEncryptionSslProtocol(SslProtocols.Tls12)
                                 .WithConnectionValidator(
                c =>
            {
                Console.WriteLine(c.Username);
                c.ReasonCode = MqttConnectReasonCode.Success;
            }).WithSubscriptionInterceptor(
                c =>
            {
                c.AcceptSubscription = false;
            }).WithApplicationMessageInterceptor(
                c =>
            {
                c.AcceptPublish = false;
            });

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

            mqttServer.StartAsync(optionsBuilder.Build());
            Console.ReadLine();
        }
Exemplo n.º 10
0
        public async Task <ReuquestResult> StartMQServer()
        {
            try
            {
                if (mqttServer != null && mqOptionsBuilder != null)
                {
                    await mqttServer.StartAsync(mqOptionsBuilder.Build());

                    mqOptionsBuilder = null;
                    return(new ReuquestResult {
                        Successful = true
                    });
                }
                else
                {
                    LMLogs.NLog.Logger.Log(LMLogs.LogLevel.Exception, "MqttService", $"开启成功");
                }
                return(new ReuquestResult {
                    Successful = false
                });
            }
            catch (Exception e)
            {
                LMLogs.NLog.Logger.Log(LMLogs.LogLevel.Exception, "MqttService", $"开启异常:{e.Message}");
                return(new ReuquestResult {
                    Successful = false, Code = 500
                });
            }
        }
Exemplo n.º 11
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            var optionsBuilder = new MqttServerOptionsBuilder()
                                 .WithDefaultEndpoint().WithDefaultEndpointPort(1883).WithConnectionValidator(
                c =>
            {
                c.ReasonCode = MqttConnectReasonCode.Success;
            }).WithSubscriptionInterceptor(
                c =>
            {
                c.AcceptSubscription = true;
            }).WithApplicationMessageInterceptor(
                c =>
            {
                string s = string.Empty;

                foreach (byte b in c.ApplicationMessage.Payload)
                {
                    s += Convert.ToChar(b);
                }

                Console.WriteLine($"Sender: {c.ClientId} - Topic: {c.ApplicationMessage.Topic} - Message: {s}");

                c.AcceptPublish = true;
            });



            await _mqttServer.StartAsync(optionsBuilder.Build());
        }
        private async Task StartMqttServer()
        {
            // Start a MQTT server.
            Logger.LogInfo(LogCategory.Processor, this.Name, "Starting MQTT Server..");

            _mqttServer = new MqttFactory().CreateMqttServer();

            var optionsBuilder = new MqttServerOptionsBuilder()
                                 .WithConnectionBacklog(100)
                                 .WithDefaultEndpointPort(BrokerPort)
                                 .WithConnectionValidator(AuthenticateUser)
                                 .WithStorage(new RetainedMqttMessageHandler());

            if (!string.IsNullOrEmpty(SecureCommunicationCertLocation))
            {
                optionsBuilder.WithEncryptedEndpoint().WithEncryptedEndpointPort(EncryptedBrokerPort);
            }

            var options = optionsBuilder.Build();

            if (!string.IsNullOrEmpty(SecureCommunicationCertLocation))
            {
                var certificate = new X509Certificate(SecureCommunicationCertLocation, "");
                options.TlsEndpointOptions.Certificate = certificate.Export(X509ContentType.Cert);
            }

            await _mqttServer.StartAsync(options);
        }
Exemplo n.º 13
0
        public static void Main()
        {
            var currentPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         // ReSharper disable once AssignNullToNotNullAttribute
                         .WriteTo.File(Path.Combine(currentPath,
                                                    @"log\SimpleMqttServer_.txt"), rollingInterval: RollingInterval.Day)
                         .WriteTo.Console()
                         .CreateLogger();

            var config = ReadConfiguration(currentPath);

            var optionsBuilder = new MqttServerOptionsBuilder()
                                 .WithDefaultEndpoint().WithDefaultEndpointPort(config.Port).WithConnectionValidator(
                c =>
            {
                var currentUser = config.Users.FirstOrDefault(u => u.UserName == c.Username);

                if (currentUser == null)
                {
                    c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
                    LogMessage(c, true);
                    return;
                }

                if (c.Username != currentUser.UserName)
                {
                    c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
                    LogMessage(c, true);
                    return;
                }

                if (c.Password != currentUser.Password)
                {
                    c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
                    LogMessage(c, true);
                    return;
                }

                c.ReasonCode = MqttConnectReasonCode.Success;
                LogMessage(c, false);
            }).WithSubscriptionInterceptor(
                c =>
            {
                c.AcceptSubscription = true;
                LogMessage(c, true);
            }).WithApplicationMessageInterceptor(
                c =>
            {
                c.AcceptPublish = true;
                LogMessage(c);
            });

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

            mqttServer.StartAsync(optionsBuilder.Build());
            Console.ReadLine();
        }
Exemplo n.º 14
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            var currentPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         // ReSharper disable once AssignNullToNotNullAttribute
                         .WriteTo.File(Path.Combine(currentPath,
                                                    @"log\SimpleMqttServer_.txt"), rollingInterval: RollingInterval.Day)
                         .WriteTo.Console()
                         .CreateLogger();

            var optionsBuilder = new MqttServerOptionsBuilder().WithDefaultEndpoint().WithApplicationMessageInterceptor(
                c =>
            {
                c.AcceptPublish = true;
                LogMessage(c);
            }).WithSubscriptionInterceptor(
                c =>
            {
                c.AcceptSubscription = true;
                LogMessage(c, true);
            });
            var mqttServer = new MqttFactory().CreateMqttServer();

            mqttServer.StartAsync(optionsBuilder.Build());
            Console.ReadLine();
        }
Exemplo n.º 15
0
        static async void StartServer()
        {
            var optionsBuilder = new MqttServerOptionsBuilder()
                                 .WithConnectionBacklog(int.Parse(_configuration["backlog"]))
                                 .WithDefaultEndpointPort(int.Parse(_configuration["portNumber"]));

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

            var isEchoOn = bool.Parse(_configuration["echo"]);

            _topicsFilter = _configuration["echoTopicFilters"].Split(",");

            Console.WriteLine($"Mqtt broker listening on port {_configuration["portNumber"]} - press enter to exit.");

            if (isEchoOn)
            {
                Console.WriteLine($"echoing messages using topicFilter of {_configuration["echoTopicFilters"]}");
                mqttServer.UseClientConnectedHandler(ClientConnectedHandler);
                mqttServer.UseClientDisconnectedHandler(ClientDisconnectedHandler);
                mqttServer.UseApplicationMessageReceivedHandler(MessageReceivedHandler);
            }

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


            Console.ReadLine();
            await mqttServer.StopAsync();
        }
        public async Task ServerRun(SignalRService signalRService)
        {
            Debug.WriteLine("TestMQTTServer");
            var optionsBuilder = new MqttServerOptionsBuilder()
                                 .WithConnectionBacklog(100)
                                 .WithDefaultEndpointPort(8081);

            mqttServer = new MqttFactory().CreateMqttServer();
            mqttServer.ApplicationMessageReceived += async(s, e) =>
            {
                Debug.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
                Debug.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}");
                Debug.WriteLine($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
                Debug.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
                Debug.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}");
                Debug.WriteLine($"+ Retain = {e.ClientId}");
                var payload        = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                var splitedPayload = payload.Split('/');
                var isOn           = splitedPayload[2] == "on" ? true : false;
                await signalRService.InvokeSendStatusMethod(int.Parse(splitedPayload[1]), isOn);
            };
            await mqttServer.StartAsync(optionsBuilder.Build());

//            Console.WriteLine("Press any key to exit.");
//            Console.ReadLine();
//            await mqttServer.StopAsync();
        }
Exemplo n.º 17
0
        public override async Task StartAsync(CancellationToken cancellationToken)
        {
            // Server
            _logger.LogInformation($"Start MQTT-Broker (Port:{_brokerConfig.Port})");

            var optionsBuilder = new MqttServerOptionsBuilder()
                                 .WithDefaultEndpoint()
                                 .WithDefaultEndpointPort(_brokerConfig.Port)
                                 .WithSubscriptionInterceptor(
                c =>
            {
                c.AcceptSubscription = true;
                _logger.LogInformation($"New subscription: ClientId = {c.ClientId}, TopicFilter = {c.TopicFilter}");
            })
                                 .WithApplicationMessageInterceptor(
                c =>
            {
                c.ApplicationMessage.Payload =
                    Encoding.UTF8.GetBytes(
                        Encoding.UTF8.GetString(c.ApplicationMessage.Payload).Trim());
                //c.ApplicationMessage.Payload = Encoding.UTF8.GetBytes(payload);
            });

            _mqttServer = new MqttFactory().CreateMqttServer();

            _mqttServer.ClientConnectedHandler            = this;
            _mqttServer.ClientDisconnectedHandler         = this;
            _mqttServer.ApplicationMessageReceivedHandler = this;
            await _mqttServer.StartAsync(optionsBuilder.Build());

            await base.StartAsync(cancellationToken);
        }
Exemplo n.º 18
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            #region MQTT配置
            string hostIp   = Configuration["MqttOption:HostIp"];              //IP地址
            int    hostPort = int.Parse(Configuration["MqttOption:HostPort"]); //端口号
            int    timeout  = int.Parse(Configuration["MqttOption:Timeout"]);  //超时时间
            string username = Configuration["MqttOption:UserName"];            //用户名
            string password = Configuration["MqttOption:Password"];            //密码

            var optionBuilder = new MqttServerOptionsBuilder()
                                .WithDefaultEndpointBoundIPAddress(System.Net.IPAddress.Parse(hostIp))
                                .WithDefaultEndpointPort(hostPort)
                                .WithDefaultCommunicationTimeout(TimeSpan.FromMilliseconds(timeout))
                                .WithConnectionValidator(t =>
            {
                if (t.Username != username || t.Password != password)
                {
                    t.ReturnCode = MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
                }
                t.ReturnCode = MqttConnectReturnCode.ConnectionAccepted;
            });
            var option = optionBuilder.Build();

            services
            .AddHostedMqttServer(option)
            .AddMqttConnectionHandler()
            .AddConnections();
            #endregion
        }
Exemplo n.º 19
0
        public override async Task StartAsync(CancellationToken cancellationToken)
        {
            this.CancellationToken = cancellationToken;

            await LoadConfigurationAsync();

            Log.Information("[{where}] Broker is starting v {version} on port {port}...", nameof(MQTTServer), Program.Version, port);

            mqttServer = new MqttFactory().CreateMqttServer();

            var optionsBuilder = new MqttServerOptionsBuilder()
                                 .WithConnectionValidator(c =>
            {
                if (c.Username == username && c.Password == password)
                {
                    c.ReasonCode = MqttConnectReasonCode.Success;
                }
                else
                {
                    c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
                }
            })
                                 .WithConnectionBacklog(100)
                                 .WithDefaultEndpointPort(port)
                                 .WithApplicationMessageInterceptor(async context =>
            {
                Log.Verbose("[{where}] Message Received...\r\n[{client}] - {topic} - {msg}", nameof(MQTTServer), context.ClientId ?? "n/a", context.ApplicationMessage.Topic, context.ApplicationMessage.ConvertPayloadToString());

                if (context?.ClientId != null)
                {
                    // handle multiple devices mapped to the same payload
                    var clients = devices.Where(x => x.ClientId == context.ClientId || x.ClientId == "*");

                    Parallel.ForEach(clients, async(device) =>
                    {
                        if (device.TopicName.Equals(context.ApplicationMessage.Topic, StringComparison.InvariantCultureIgnoreCase) ||
                            device.AlternateTopicName?.Equals(context.ApplicationMessage.Topic, StringComparison.InvariantCultureIgnoreCase) == true)
                        {
                            await ProcessMessageAsync(device, context.ApplicationMessage);
                        }
                    });
                }

                CancelIfNeeded();

                await Task.CompletedTask;
            });

            var options = optionsBuilder.Build() as MqttServerOptions;

            try
            {
                await mqttServer.StartAsync(options);
            }
            catch (Exception ex)
            {
                Log.Error(ex, $"[{nameof(MqttServer)}].{nameof(StartAsync)}");
            }
        }
Exemplo n.º 20
0
 public async void StartServer()
 {
     optionsBuilder = new MqttServerOptionsBuilder()
                      .WithConnectionBacklog(100)
                      //.WithConnectionValidator(connValidator)
                      .WithDefaultEndpointPort(1884);
     await mqttServer.StartAsync(optionsBuilder.Build());
 }
Exemplo n.º 21
0
        public async Task ConfigBrocerAsync()
        {
            var optionsBuilder = new MqttServerOptionsBuilder()
                                 .WithDefaultEndpointPort(1889);

            var mqttServer = new MqttFactory().CreateMqttServer();
            await mqttServer.StartAsync(optionsBuilder.Build());
        }
Exemplo n.º 22
0
    // Use this for initialization
    async void Start()
    {
        // Start a MQTT server.
        mqttServer = new MqttFactory().CreateMqttServer();
        var ipAddress = new byte[] { 0, 0, 0, 0 };
        var ipObject  = new System.Net.IPAddress(ipAddress);
        var options   = new MqttServerOptionsBuilder()
                        .WithDefaultEndpointBoundIPAddress(ipObject)
                        .WithDefaultEndpointPort(1883);

        // Write all trace messages to the console window.
        MqttNetGlobalLogger.LogMessagePublished += (s, e) =>
        {
            var trace = $">> [{e.TraceMessage.Timestamp:O}] [{e.TraceMessage.ThreadId}] [{e.TraceMessage.Source}] [{e.TraceMessage.Level}]: {e.TraceMessage.Message}";
            if (e.TraceMessage.Exception != null)
            {
                trace += Environment.NewLine + e.TraceMessage.Exception.ToString();
            }

            Debug.Log(trace);
        };

        try
        {
            await mqttServer.StartAsync(options.Build());
        } catch (Exception e)
        {
            // testing...
            Debug.Log("exception!");
            Debug.Log(e.Message);
        }


        mqttServer.ClientConnected += (s, e) =>
        {
            Debug.Log("Client connected " + e.ClientId);
        };
        mqttServer.Started += (s, e) =>
        {
            Debug.Log("Server was started");
        };
        mqttServer.Stopped += (s, e) =>
        {
            Debug.Log("Server was stopped");
        };

        mqttServer.ApplicationMessageReceived += (s, e) =>
        {
            // TODO split values up! & find out what is what.
            // -> parse values like in the code from Ricky.
            Debug.Log("application message received");
            var payload = string.Concat(e.ApplicationMessage.Payload);
            Debug.Log(payload);
        };

        Debug.Log(mqttServer.Options.DefaultEndpointOptions.Port);
        Debug.Log(mqttServer.Options.DefaultEndpointOptions.BoundInterNetworkAddress);
    }
Exemplo n.º 23
0
        public async Task <bool> Start()
        {
            if (_neonConfig.Mqtt.RunEmbedded)
            {
                var mqttOptionBuilder = new MqttServerOptionsBuilder()
                                        .WithConnectionBacklog(100)
                                        .WithDefaultEndpointBoundIPAddress(IPAddress.Parse("0.0.0.0"))
                                        .WithDefaultEndpointPort(1883);

                _mqttServer = new MqttFactory().CreateMqttServer();
                _logger.LogInformation($"Starting embedded MQTT Server");
                await _mqttServer.StartAsync(mqttOptionBuilder.Build());

                _logger.LogInformation($"Embedded MQTT Server started");
                _neonConfig.Mqtt.Host = "127.0.0.1";
            }


            _logger.LogInformation($"Connecting to {_neonConfig.Mqtt.Host} with clientId: {_neonConfig.Mqtt.ClientId}");

            var options = new MqttClientOptionsBuilder()
                          .WithClientId(_neonConfig.Mqtt.ClientId)
                          .WithTcpServer(_neonConfig.Mqtt.Host)
                          .WithCleanSession()
                          .Build();

            _mqttClient = new MqttFactory().CreateMqttClient();
            _mqttClient.UseDisconnectedHandler(async e =>
            {
                if (_reconnectTry <= 5)
                {
                    _logger.LogWarning("Disconnected from MQTT Server, reconnecting in 10 seconds");
                    await Task.Delay(10000);
                    await Start();

                    _reconnectTry++;
                }
                else
                {
                    _logger.LogWarning("Max number reconnect try to MQTT Server, abort");
                }
            });

            _mqttClient.UseConnectedHandler(async e =>
            {
                await _mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("Neon.iot").Build());
                await _mqttClient.PublishAsync(new MqttApplicationMessageBuilder().WithTopic("Neon.iot")
                                               .WithPayload("connected!").WithExactlyOnceQoS().WithRetainFlag().Build());
            });
            _mqttClient.UseApplicationMessageReceivedHandler(args => { OnMessageReceived(args.ApplicationMessage); });
            await _mqttClient.ConnectAsync(options);

            _logger.LogInformation("Connected");

            ConnectMirror();

            return(true);
        }
Exemplo n.º 24
0
        private async Task StartMqttServer()
        {
            // Start a MQTT server.
            Logger.LogInfo(LogCategory.Processor, this.Name, "Starting MQTT Server..");

            _mqttServer = new MqttFactory().CreateMqttServer();

            var optionsBuilder = new MqttServerOptionsBuilder()
                                 .WithConnectionBacklog(100)
                                 .WithDefaultEndpointPort(BrokerPort)
                                 .WithConnectionValidator(AuthenticateUser)
                                 .WithStorage(new RetainedMqttMessageHandler());

            if (!string.IsNullOrEmpty(SecureCommunicationCertLocation))
            {
                optionsBuilder.WithEncryptedEndpoint().WithEncryptedEndpointPort(EncryptedBrokerPort);
            }

            var options = optionsBuilder.Build();

            if (!string.IsNullOrEmpty(SecureCommunicationCertLocation))
            {
                var certificate = new X509Certificate(SecureCommunicationCertLocation, "");
                options.TlsEndpointOptions.Certificate = certificate.Export(X509ContentType.Cert);
            }

            _mqttServer.Started += (s, a) =>
            {
                //Logger.LogTrace(LogCategory.Processor, this.Name, "MQTT Started", a.ToJSON());
            };

            _mqttServer.ApplicationMessageReceived += async(s, a) =>
            {
                Logger.LogTrace(LogCategory.Processor, this.Name, "MQTT Server Received Message", a.ToJSON());
            };

            _mqttServer.ClientSubscribedTopic += async(s, a) =>
            {
                //Logger.LogTrace(LogCategory.Processor, this.Name, "MQTT Client Subscribed to Topic", a.ToJSON());
            };

            _mqttServer.ClientUnsubscribedTopic += async(s, a) =>
            {
                //Logger.LogTrace(LogCategory.Processor, this.Name, "MQTT Client Unsubscribed to Topic", a.ToJSON());
            };

            _mqttServer.ClientConnected += async(s, a) =>
            {
                //Logger.LogTrace(LogCategory.Processor, this.Name, "MQTT Client Connected", a.ToJSON());
            };

            _mqttServer.ClientDisconnected += async(s, a) =>
            {
                //Logger.LogTrace(LogCategory.Processor, this.Name, "MQTT Client Disconnected", a.ToJSON());
            };

            await _mqttServer.StartAsync(options);
        }
Exemplo n.º 25
0
        static void Main(string[] args)
        {
            var optionsServer = new MqttServerOptionsBuilder()
                                .WithDefaultEndpointBoundIPAddress(new System.Net.IPAddress(new byte[] { 192, 168, 10, 254 }))
                                .WithDefaultEndpointPort(1883);


            IMqttServer _mqttBroker = new MqttFactory().CreateMqttServer();

            //IMqttClient mqttClient = new MqttFactory().CreateMqttClient();

            //var optionsClient = new MqttClientOptionsBuilder().WithClientId("9999").WithTcpServer("192.168.10.254", 1883);



            var receivedEvents = new List <string>();

            _mqttBroker.ClientConnected += delegate(object sender, MQTTnet.Server.MqttClientConnectedEventArgs e)
            {
                //receivedEvents.Add(args.ClientId);
                Console.WriteLine($"Client {e.ClientId} has connected");
            };


            _mqttBroker.ApplicationMessageReceived += delegate(object sender, MqttApplicationMessageReceivedEventArgs e)
            {
                //receivedEvents.Add(args.ClientId);
                Console.WriteLine($"Client {e.ClientId} Published ({e.ApplicationMessage.ConvertPayloadToString()})");
            };

            //** Start broker
            Task _brokerStart = Task.Run(() => _mqttBroker.StartAsync(optionsServer.Build()));

            _brokerStart.Wait();
            Console.WriteLine("Broker Started");

            //Task taskClientStart = Task.Run(() => mqttClient.ConnectAsync(optionsClient.Build()));
            //taskClientStart.Wait();

            Console.WriteLine("Waiting to exit, Press Any Key");
            var pause = new ManualResetEvent(false);

            Console.ReadKey();

            //pause.WaitOne();
            Console.WriteLine("Goodbye");



            //var taskClientStop = Task.Run(() => mqttClient.DisconnectAsync());
            //taskClientStop.Wait();

            //** Stop Broker
            Task _brokerTaskStop = Task.Run(() => _mqttBroker.StopAsync());

            _brokerTaskStop.Wait();
            Console.WriteLine("Broker Stopped");
        }
Exemplo n.º 26
0
        private async void StartMqttServer()
        {
            ClientDispatcher = Dispatcher.CurrentDispatcher;
            SetStatus("Configuring");
            MqttFactory factory = new MqttFactory();
            MqttServerOptionsBuilder optionsBuilder = new MqttServerOptionsBuilder()
                                                      .WithDefaultCommunicationTimeout(new TimeSpan(0, 0, 0, 60, 0))
                                                      .WithDefaultEndpoint()
                                                      .WithDefaultEndpointPort(PlainPort)
                                                      .WithMaxPendingMessagesPerClient(2000)
            ;

            Server = factory.CreateMqttServer();

            Server.ApplicationMessageReceived += Server_ApplicationMessageReceived;
            Server.ClientConnected            += Server_ClientConnected;
            Server.ClientDisconnected         += Server_ClientDisconnected;
            Server.ClientSubscribedTopic      += Server_ClientSubscribedTopic;
            Server.ClientUnsubscribedTopic    += Server_ClientUnsubscribedTopic;
            Server.Started += Server_Started;

#if HAVE_SYNC
            if (IsSync)
            {
                Server.Start(optionsBuilder.Build());
            }
            else
#endif
            await Server.StartAsync(optionsBuilder.Build());

            SetStatus("Started");
            // This will run the event queue forever, until we stop it
            Dispatcher.Run();

#if HAVE_SYNC
            if (IsSync)
            {
                Server.Stop();
            }
            else
#endif
            Server.StopAsync().Wait();

            await Dispatcher.BeginInvoke((Action)(() => OnServerThreadStopped()));
        }
Exemplo n.º 27
0
        async private static void CreateServer()
        {
            string ipAddress = config["mqttSettings:ipaddress"];
            int    port      = Convert.ToInt32(config["mqttSettings:port"]);
            bool   useSSL    = Convert.ToBoolean(config["mqttSettings:useSSL"]);

            // Setup client validator.
            var optionsBuilder = new MqttServerOptionsBuilder()
                                 .WithConnectionBacklog(100)
                                 // .WithDefaultEndpointBoundIPAddress(IPAddress.Parse(ipAddress))
                                 .WithDefaultEndpointPort(port);

            var options = optionsBuilder.Build() as MqttServerOptions;

            //options.ConnectionValidator = c =>
            //{
            //    ConnectionValidator.ValidateConnection(c);
            //};

            if (useSSL)
            {
                string                     certificateName = config["mqttSettings:certificateName"];
                X509Certificate            cert            = null;
                X509Store                  store           = new X509Store(StoreLocation.LocalMachine);
                X509Certificate2Collection cers            = store.Certificates.Find(X509FindType.FindBySubjectName, certificateName, true);
                if (cers.Count > 0)
                {
                    cert = cers[0];
                }
                ;
                options.TlsEndpointOptions.Certificate = cert.Export(X509ContentType.Cert);
            }

            mqttServer = new MqttFactory().CreateMqttServer();
            mqttServer.ClientConnected            += OnConnected;
            mqttServer.ClientDisconnected         += OnDisonnected;
            mqttServer.ClientSubscribedTopic      += OnSubscribe;
            mqttServer.ClientUnsubscribedTopic    += OnUnsubscribe;
            mqttServer.ApplicationMessageReceived += OnMessage;

            MqttNetGlobalLogger.LogMessagePublished += (s, e) =>
            {
                var trace = $">> [{e.TraceMessage.Timestamp:O}] [{e.TraceMessage.ThreadId}] [{e.TraceMessage.Source}] [{e.TraceMessage.Level}]: {e.TraceMessage.Message}";
                if (e.TraceMessage.Exception != null)
                {
                    trace += Environment.NewLine + e.TraceMessage.Exception.ToString();
                }

                Console.WriteLine(trace);
            };

            await mqttServer.StartAsync(options);

            Console.WriteLine("Press any key to exit.");
            Console.ReadLine();
            //await mqttServer.StopAsync();
        }