public static AspNetMqttServerOptionsBuilder WithAttributeRouting(this AspNetMqttServerOptionsBuilder options)
        {
            var router      = options.ServiceProvider.GetRequiredService <MqttRouter>();
            var interceptor = new MqttServerApplicationMessageInterceptorDelegate(context => router.OnIncomingApplicationMessage(options, context));

            options.WithApplicationMessageInterceptor(interceptor);

            return(options);
        }
Example #2
0
        public MqttConsumer()
        {
            /*
             * MqttServerOptions validator = new MqttServerOptions();
             * validator.ConnectionValidator = new IMqttServerConnectionValidator(
             * {
             *
             *  c.ReturnCode = MqttConnectReturnCode.ConnectionAccepted;
             *  Console.WriteLine("Connexion OK");
             * }
             *
             *
             * MqttServerOptions subValidator = new MqttServerOptions();
             * subValidator.SubscriptionInterceptor = context =>
             * {
             *  context.AcceptSubscription = true;
             *  Console.WriteLine("Subscribe OK");
             *
             * };
             *
             */

            //var certificate = new X509Certificate(@"C:\Users\StreamX\Desktop\TestCa.crt", "");
            //MqttServerOptions certifOption = new MqttServerOptions();
            //certifOption.TlsEndpointOptions.Certificate = certificate.Export(X509ContentType.Cert);
            //certifOption.TlsEndpointOptions.IsEnabled = true;
            var conUserValidator = new MqttServerOptions
            {
                ConnectionValidator = new MqttServerConnectionValidatorDelegate(p =>
                {
                    //if (p.ClientId != "SpecialClient") return;
                    if (p.Username != "test" || p.Password != "test")
                    {
                        p.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
                    }

                    if (string.IsNullOrEmpty(p.ClientId))
                    {
                        return;
                    }
                }),

                ApplicationMessageInterceptor = new MqttServerApplicationMessageInterceptorDelegate(context =>
                {
                    /*
                     * if (!MqttTopicFilterComparer.IsMatch(context.ApplicationMessage.Topic, "platooning"))
                     * {
                     *  // Replace the payload with the timestamp. But also extending a JSON
                     *  // based payload with the timestamp is a suitable use case.
                     *  context.ApplicationMessage.Payload = Encoding.UTF8.GetBytes(DateTime.Now.ToString("O"));
                     * }*/

                    if (!context.ApplicationMessage.Topic.StartsWith("platooning/"))
                    {
                        context.AcceptPublish   = false;
                        context.CloseConnection = true;
                    }
                }),

                SubscriptionInterceptor = new MqttServerSubscriptionInterceptorDelegate(context =>
                {
                    if (context.TopicFilter.Topic.StartsWith("platooning/broadcast/"))
                    {
                        var plotooningId    = context.TopicFilter.Topic.Replace("platooning/broadcast/", "");
                        using var dbcontext = new MqttBrokerDbContext();
                        try
                        {
                            var followvehicleEnable = dbcontext.Platoon.FirstOrDefault(f => f.Enable &&
                                                                                       f.IsFollower &&
                                                                                       f.ClientId == context.ClientId && f.PlatoonRealId == plotooningId);

                            if (followvehicleEnable == null)
                            {
                                context.AcceptSubscription = false;
                                context.CloseConnection    = true;
                            }
                        }
                        catch (Exception exception)
                        {
                            var log = new Log
                            {
                                Exception = exception.StackTrace
                            };
                            dbcontext.Log.AddAsync(log);
                            dbcontext.SaveChanges();
                            Console.WriteLine(exception);
                        }
                        //context.AcceptSubscription = false;
                        //context.CloseConnection = true;
                    }

                    if (context.TopicFilter.Topic.StartsWith("admin/foo/bar") && context.ClientId != "theAdmin")
                    {
                        //context.AcceptSubscription = false;
                    }

                    if (context.TopicFilter.Topic.StartsWith("the/secret/stuff") && context.ClientId != "Imperator")
                    {
                        //context.AcceptSubscription = false;
                        //context.CloseConnection = true;
                    }
                })
            };

            OptionsBuilder = new MqttServerOptionsBuilder()
                             .WithClientCertificate()
                             .WithConnectionBacklog(100)
                             .WithDefaultEndpointPort(1883)
                             .WithConnectionValidator(conUserValidator.ConnectionValidator)
                             .WithApplicationMessageInterceptor(conUserValidator.ApplicationMessageInterceptor)
                             .WithSubscriptionInterceptor(conUserValidator.SubscriptionInterceptor)
                             .WithPersistentSessions()
                             // .WithEncryptionCertificate(certifOption.TlsEndpointOptions.Certificate)
                             //.WithEncryptedEndpoint()
                             .Build();
            Server = new MqttFactory().CreateMqttServer();
        }