Пример #1
0
 public MqttDomainProvider()
 {
     broker = new MqttBroker();
     broker.ClientDisconnected += OnDeviceDisconnected;
     broker.DidAcceptNewClient += OnDeviceJoinedDomain;
     broker.DidRecievePublishMessageFromClient += OnPropertyChanged;
 }
Пример #2
0
        private void KeepAliveThread()
        {
            var sleepPeriod = new TimeSpan(0, 0, MqttMsgConnect.KEEP_ALIVE_PERIOD_DEFAULT);

            while (this.IsRunning)
            {
                try
                {
                    var now = Environment.TickCount;
                    foreach (var clientConnection in MqttBroker.GetAllConnectedClients())
                    {
                        if (clientConnection.IsRunning && clientConnection.IsConnected)
                        {
                            var delta = now - clientConnection.LastCommunicationTime;
                            if (delta >= clientConnection.KeepAlivePeriod)
                            {
                                clientConnection.OnConnectionClosed();
                            }
                        }
                    }

                    Thread.Sleep(sleepPeriod);
                }
                catch (Exception)
                {
                }
            }
        }
Пример #3
0
        public override bool OnStart()
        {
            // Set the maximum number of concurrent connections
            ServicePointManager.DefaultConnectionLimit = int.MaxValue;

            logger = new ApplicationInsightsLogger();
            var options = new MqttOptions
            {
                ConnectionsPrProcessingManager = 1024,
                EndPoint = new IPEndPoint(IPAddress.Any, 1883),
                IndividualMessageBufferSize = 8192,
                NumberOfAcceptSaea          = 512,
                MaxConnections             = 32768,
                InitialNumberOfRawMessages = 1024,
                NumberOfSendBuffers        = 32768,
                ReadAndSendBufferSize      = 8192
            };

            broker = new MqttBroker(logger, options);

            broker.Start();

            bool result = base.OnStart();

            Trace.TraceInformation("GnatMQWorkerRole has been started");

            return(result);
        }
Пример #4
0
        public static void Main(string[] args)
        {
            var options = new MqttOptions
            {
                ConnectionsPrProcessingManager = 512,
                EndPoint = new IPEndPoint(IPAddress.Any, 1883),
                IndividualMessageBufferSize = 8192,
                NumberOfAcceptSaea          = 256,
                MaxConnections             = 1024,
                InitialNumberOfRawMessages = 1024,
                NumberOfSendBuffers        = 1024,
                ReadAndSendBufferSize      = 8192
            };

            var logger = new ConsoleLogger();

            // create and start broker
            MqttBroker broker = new MqttBroker(logger, options);

            broker.Start();

            while (true)
            {
                broker.PeriodicLogging();
                Thread.Sleep(new TimeSpan(0, 1, 0));
            }

            broker.Stop();
        }
Пример #5
0
        public MainPage()
        {
            this.InitializeComponent();

            this.NavigationCacheMode = NavigationCacheMode.Required;

            this.broker = new MqttBroker();
        }
Пример #6
0
 /// <summary>
 /// 启动Mqtt Broker
 /// </summary>
 private void StartMqttBroker()
 {
     // 启动mqtt服务
     if (null == broker)
     {
         broker = new MqttBroker();
         broker.Start();
     }
 }
Пример #7
0
        static void Main(string[] args)
        {
            MqttBroker broker = new MqttBroker();

            broker.Start();

            Console.ReadLine();

            broker.Stop();
        }
Пример #8
0
        static void Main(string[] args)
        {
            MqttBroker broker = new MqttBroker();

            broker.Start();
            broker.ClientConnected += Broker_ClientConnected;
            Console.WriteLine("Hello World!");
            Console.ReadLine();

            broker.Stop();
        }
Пример #9
0
 public void Disconnect()
 {
     try
     {
         mqttService.Stop();
     }
     catch
     {
     }
     mqttService = null;
 }
        private void Started()
        {
            if (_broker == null)
            {
                _broker = new MqttBroker();
            }

            _broker.Start();

            Receive <StopMQTTBroker>(msg => OnStopBroker());
        }
        public MqttNetClientFactoryTests()
        {
            var serviceProvider = ServiceProviderHelper.GetServiceProvider(
                services => services
                .AddFakeLogger()
                .AddSilverback()
                .WithConnectionToMessageBroker(options => options.AddMqtt()));

            _broker = serviceProvider.GetRequiredService <MqttBroker>();
            _logger = serviceProvider.GetRequiredService <ISilverbackLogger <MqttClientsCache> >();
        }
Пример #12
0
        public override void OnStop()
        {
            Trace.TraceInformation("IoTBroker is stopping");

            this.cancellationTokenSource.Cancel();
            this.runCompleteEvent.WaitOne();

            base.OnStop();
            this.broker.Stop();
            this.broker = null;
            Trace.TraceInformation("IoTBroker has stopped");
        }
Пример #13
0
        public MqttDomainProvider()
        {
            broker = new MqttBroker();

            // AuthService = new IotDeviceAuthorizationService();

            broker.ClientDisconnected += OnDeviceDisconnected;
            broker.DidAcceptNewClient += OnDeviceJoinedDomain;
            broker.DidRecievePublishMessageFromClient += OnPropertyChanged;

            broker.UserAuth += HandleAuth; //AuthService.AccessWithCredentials;
        }
Пример #14
0
        public IBroker Create(string clientName)
        {
            switch (this.brokerConfiguration.BrokerType)
            {
            case BrokerType.Mqtt:
                MqttBroker broker = new MqttBroker((MqttBrokerConfiguration)this.brokerConfiguration, clientName);
                return(broker);

            default:
                throw new Exception($"{this.brokerConfiguration.BrokerType} is not supported yet");
            }
        }
Пример #15
0
 public Application(ILogger logger, MqttBroker mqttBroker)
 {
     if (logger == null)
     {
         throw new ArgumentNullException("logger");
     }
     if (mqttBroker == null)
     {
         throw new ArgumentNullException("mqttBroker");
     }
     m_Logger     = logger;
     m_MqttBroker = mqttBroker;
 }
Пример #16
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(
            IApplicationBuilder app,
            IHostingEnvironment env,
            IApplicationLifetime applicationLifetime
            )
        {
            // Start MQTT
            var broker = new MqttBroker(Configuration, app.ApplicationServices.GetService <IServiceProvider>());

            // On application exit terminate MQTT to make sure the connection is ended properly
            applicationLifetime.ApplicationStopping.Register(() => broker.Terminate());

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
                app.UseHttpsRedirection(); //enkel redirecten in production aangezien https niet werkt in development
            }

            app.UseAuthentication();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapSubdomainRoute(
                    Constants.hostnames,
                    "TenantInSubdomain",
                    "{tenant}",
                    "{controller}/{action}",
                    new { controller = "Platform", action = "Index" }
                    );

                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            app.UseSignalR(routes =>
            {
                routes.MapHub <VoteHub>("/votehub");
                routes.MapHub <ActivityHub>("/activityhub");
            });
        }
Пример #17
0
        static void Main(string[] args)
        {
#if TRACE
            //MqttUtility.Trace.TraceLevel = MqttUtility.TraceLevel.Verbose | MqttUtility.TraceLevel.Frame;
            //MqttUtility.Trace.TraceListener = (f, a) => System.Diagnostics.Trace.WriteLine(System.String.Format(f, a));
#endif

            // create and start broker
            MqttBroker broker = new MqttBroker();
            broker.Start();

            Console.ReadLine();

            broker.Stop();
        }
Пример #18
0
        public override bool OnStart()
        {
            // Set the maximum number of concurrent connections
            ServicePointManager.DefaultConnectionLimit = 12;

            // For information on handling configuration changes
            // see the MSDN topic at https://go.microsoft.com/fwlink/?LinkId=166357.

            bool result = base.OnStart();

            Trace.TraceInformation("IoTBroker has been started");
            this.broker = new MqttBroker();
            this.broker.Start();

            return(result);
        }
Пример #19
0
        private bool disposedValue; // To detect redundant calls

        public LANManager()
        {
            lock (_lock)
            {
                if (_mqttBroker == null)
                {
                    _mqttBroker = new MqttBroker();
                    _mqttBroker.Start();
                    _udpMessaging = new UDPMessaging();
                    _mqttBroker.MsgPublishReceived += MqttMessageRecieved;
                }
                else
                {
                    throw new Exception("You should only instantiate this class once! ");
                }
            }
        }
Пример #20
0
        static void Main(string[] args)
        {
            Console.WriteLine("Start MQTT!");
            // create and start broker
            MqttBroker broker = new MqttBroker();

            broker.UserAuth = CheckUser;

            broker.ClientDisconnected += Broker_ClientDisconnected;
            broker.ClientConnected    += Broker_ClientConnected;
            broker.Start();
            Console.WriteLine("MQTT service is started. any key to stop..");
            //Once the broker is started, you applciaiton is free to do whatever it wants.
            Console.ReadLine();

            ///Stop broker
            broker.Stop();
        }
        public void OnConnectionClosed(MqttClientConnection clientConnection)
        {
            // if client is connected
            MqttClientConnection connectedClient;

            if (clientConnection.IsConnected && MqttBroker.TryRemoveClientConnection(clientConnection.ClientId, out connectedClient))
            {
                // client has a will message
                if (clientConnection.WillFlag)
                {
                    // create the will PUBLISH message
                    MqttMsgPublish publish = new MqttMsgPublish(clientConnection.WillTopic, Encoding.UTF8.GetBytes(clientConnection.WillMessage), false, clientConnection.WillQosLevel, false);

                    // publish message through publisher manager
                    this.publishManager.Publish(publish);
                }

                // if not clean session
                if (!clientConnection.CleanSession)
                {
                    List <MqttSubscription> subscriptions = clientConnection.Subscriptions.Values.ToList();

                    if (subscriptions.Count > 0)
                    {
                        MqttSessionManager.SaveSession(clientConnection.ClientId, clientConnection.Session, subscriptions);

                        // TODO : persist client session if broker close
                    }
                }

                foreach (var topic in clientConnection.Subscriptions.Keys)
                {
                    // delete client from runtime subscription
                    MqttSubscriberManager.Unsubscribe(topic, clientConnection);
                }

                // close the client
                CloseClientConnection(clientConnection);
                clientConnectionManager.ReturnConnection(clientConnection);
                Interlocked.Decrement(ref numberOfConnectedClients);
            }
        }
Пример #22
0
        public bool Connect()
        {
            bool success = false;

            //
            try
            {
                mqttService = new MqttBroker();
                mqttService.Start();
                success = true;
            }
            catch (Exception e)
            {
                Console.WriteLine("MQTT Broker could not be started: " + e.Message);
                Disconnect();
            }
            OnInterfaceModulesChanged(this.GetDomain());
            //
            return(success);
        }
Пример #23
0
        public static void Main(string[] args)
        {
            Console.WriteLine("[Broker] Starting in localhost...");
            // create and start broker
            MqttBroker broker = new MqttBroker();

            broker.ClientConnected += (s) => {
                Console.WriteLine($"[Broker] Client connected: {s.ClientId}");
            };

            broker.ClientDisconnected += (s) => {
                Console.WriteLine($"[Broker] Client disconnected: {s.ClientId}");
            };
            broker.Start();
            //Once the broker is started, you applciaiton is free to do whatever it wants.
            Console.WriteLine("[Broker] Started. Awaiting clients");
            while (true)
            {
            }
        }
Пример #24
0
        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    // TODO: dispose managed state (managed objects).
                    _udpMessaging?.Dispose();
                }
                if (_mqttBroker != null)
                {
                    _mqttBroker.MsgPublishReceived -= MqttMessageRecieved;
                    _mqttBroker.Stop();
                }
                _mqttBroker   = null;
                _udpMessaging = null;

                // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
                // TODO: set large fields to null.
                disposedValue = true;
            }
        }
Пример #25
0
        public static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("mqttsettings.json");

            Configuration = builder.Build();

            IServiceCollection serviceCollection = new ServiceCollection();

            ConfigureServices(serviceCollection);

            var serviceProvider = serviceCollection.BuildServiceProvider();

            var broker = new MqttBroker(serviceProvider);

            broker.Start();

            while (true)
            {
                Console.WriteLine("Broker running");
                Thread.Sleep(new TimeSpan(0, 1, 0));
            }
        }
        public void OnMqttMsgConnected(MqttClientConnection clientConnection, MqttMsgConnect message)
        {
            clientConnection.ProtocolVersion = (MqttProtocolVersion)message.ProtocolVersion;

            // verify message to determine CONNACK message return code to the client
            byte returnCode = MqttConnectVerify(message);

            // [v3.1.1] if client id is zero length, the broker assigns a unique identifier to it
            var clientId = (message.ClientId.Length != 0) ? message.ClientId : Guid.NewGuid().ToString();

            // connection "could" be accepted
            if (returnCode == MqttMsgConnack.CONN_ACCEPTED)
            {
                // check if there is a client already connected with same client Id
                MqttClientConnection clientConnectionConnected = MqttBroker.GetClientConnection(clientId);

                // force connection close to the existing client (MQTT protocol)
                if (clientConnectionConnected != null)
                {
                    OnConnectionClosed(clientConnectionConnected);
                }

                // add client to the collection
                MqttBroker.TryAddClientConnection(clientId, clientConnection);
                Interlocked.Increment(ref numberOfConnectedClients);
            }

            // connection accepted, load (if exists) client session
            if (returnCode == MqttMsgConnack.CONN_ACCEPTED)
            {
                // check if not clean session and try to recovery a session
                if (!message.CleanSession)
                {
                    // create session for the client
                    MqttClientSession clientSession = new MqttClientSession(clientId);

                    // get session for the connected client
                    MqttBrokerSession session = MqttSessionManager.GetSession(clientId);

                    // [v3.1.1] session present flag
                    bool sessionPresent = false;

                    // set inflight queue into the client session
                    if (session != null)
                    {
                        clientSession.InflightMessages = session.InflightMessages;
                        // [v3.1.1] session present flag
                        if (clientConnection.ProtocolVersion == MqttProtocolVersion.Version_3_1_1)
                        {
                            sessionPresent = true;
                        }
                    }

                    // send CONNACK message to the client
                    MqttOutgoingMessageManager.Connack(clientConnection, message, returnCode, clientId, sessionPresent);

                    // load/inject session to the client
                    clientConnection.LoadSession(clientSession);

                    if (session != null)
                    {
                        // set reference to connected client into the session
                        session.ClientConnection = clientConnection;

                        // there are saved subscriptions
                        if (session.Subscriptions != null)
                        {
                            // register all subscriptions for the connected client
                            foreach (MqttSubscription subscription in session.Subscriptions)
                            {
                                MqttSubscriberManager.Subscribe(
                                    subscription.Topic,
                                    subscription.QosLevel,
                                    clientConnection);

                                // publish retained message on the current subscription
                                RetainedMessageManager.PublishRetaind(subscription.Topic, clientConnection);
                            }
                        }

                        // there are saved outgoing messages
                        if (session.OutgoingMessages.Count > 0)
                        {
                            // publish outgoing messages for the session
                            this.publishManager.PublishSession(session.ClientId);
                        }
                    }
                }
                // requested clean session
                else
                {
                    // send CONNACK message to the client
                    MqttOutgoingMessageManager.Connack(clientConnection, message, returnCode, clientId, false);

                    MqttSessionManager.ClearSession(clientId);
                }
            }
            else
            {
                // send CONNACK message to the client
                MqttOutgoingMessageManager.Connack(clientConnection, message, returnCode, clientId, false);
            }
        }
Пример #27
0
        public MainPage()
        {
            this.InitializeComponent();

            this.broker = new MqttBroker();
        }
Пример #28
0
 private Broker()
 {
     service = new MqttBroker();
 }
Пример #29
0
        static void Main(string[] args)
        {
            var broker = new MqttBroker();

            broker.Start();
        }