示例#1
0
        public MqttClient(string clientId, IMqttClient client)
        {
            if (clientId.Length < 1 || clientId.Length > 23)
            {
                throw new ArgumentException("Client identifier must be between 1 and 23 charascters.");
            }

            _clientState = ClientState.Disconnected;
            ClientId = clientId;
            _client = client;
            _client.OnMessageReceived += ClientOnMessageReceived;
            _client.OnNetworkDisconnected += ClientOnOnNetworkDisconnected;
            _manager = new StateMachineManager(_client);
        }
示例#2
0
 public MosquittoMqttClient(IMqttClientOptions options)
 {
     Options = options;
     client  = new MqttFactory().CreateMqttClient();
     client.UseApplicationMessageReceivedHandler(OnMessage);
 }
示例#3
0
 public MqttDispatcher(IMqttClient mqttClient)
 {
     _mqttClient = mqttClient;
 }
示例#4
0
 public ToiletHub(MqttClientService provider)
 {
     _mqttClient = provider.mqttClient;
 }
示例#5
0
        /// <summary>
        ///     MQTT服务器连接
        /// </summary>
        public async Task ConnectMqttServerAsync()
        {
            // 配置文件设置了不启用MQTT服务
            if (!GlobalContext.SystemConfig.MqttIsOpen)
            {
                return;
            }

            try
            {
                var factory = new MqttFactory();
                _mqttClient = factory.CreateMqttClient();

                var options = new MqttClientOptionsBuilder()
                              .WithTcpServer(GlobalContext.SystemConfig.MqttTcpServer, GlobalContext.SystemConfig.MqttTcpHost)
                              .WithCredentials(GlobalContext.SystemConfig.MqttUserName, GlobalContext.SystemConfig.MqttPasswrod)
                              .WithClientId(Guid.NewGuid().ToString().Substring(0, 5))
                              .Build();

                // 接受消息
                _mqttClient.UseApplicationMessageReceivedHandler(async e =>
                {
                    try
                    {
                        // 获取收到的信息
                        var msg = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                        // 响应主题
                        var topic = e.ApplicationMessage.Topic;
                        if (string.IsNullOrEmpty(msg))
                        {
                            return;
                        }

                        // 日志记录
                        var mqttMsgBll = App.ServiceProvider.GetService <IMqttMsgBLL>();
                        await mqttMsgBll.SaveForm(new MqttMsgEntity
                        {
                            Msg = msg, ThemeName = topic, Time = DateTime.Now
                        });

                        // 调用业务方法需要: var bll = App.ServiceProvider.GetService<业务类名>();
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Error("接受到MQTT消息后处理失败!", ex);
                    }
                });

                // 重连机制
                _mqttClient.UseDisconnectedHandler(async e =>
                {
                    Console.WriteLine("与服务器断开连接!");
                    await Task.Delay(TimeSpan.FromSeconds(5));
                    try
                    {
                        await _mqttClient.ConnectAsync(options);
                    }
                    catch (Exception exp)
                    {
                        LogHelper.Error($"重新连接服务器失败 Msg:{exp}");
                    }
                });

                await _mqttClient.ConnectAsync(options);

                // 批量订阅
                var mqttThemeBll = App.ServiceProvider.GetService <IMqttThemeService>();
                var themes       = await mqttThemeBll.GetList(new MqttThemeListParam { IsSubscribe = true });

                foreach (var topic in themes)
                {
                    await Subscribe(topic.ThemeName);
                }
            }
            catch (Exception exp)
            {
                LogHelper.Error("连接服务器失败", exp);
            }
        }
示例#6
0
 private static Task PublishSingleMessage(IMqttClient client, MqttMessage applicationMessage, ref int count)
 {
     Interlocked.Increment(ref count);
     return(Task.Run(() => client.PublishAsync(applicationMessage)));
 }
示例#7
0
 private static void OnConnected(MqttClientConnectedEventArgs x, IMqttClient client)
 {
     Clients.TryAdd(client.Options.ClientId, client);
     Console.WriteLine($"{DateTime.Now:g} - {Clients.Count} Clients Connected");
 }
示例#8
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="mediator"></param>
 /// <param name="deviceQueries"></param>
 /// <param name="identityService"></param>
 /// <param name="logger"></param>
 /// <param name="mapper"></param>
 /// <param name="skynetTerminalClient"></param>
 public TerminalController(IMediator mediator, IDeviceQueries deviceQueries, IIdentityService identityService, ILogger <DeviceController> logger, IMapper mapper, ISkynetTerminalClient skynetTerminalClient, ITerminalQueries terminalQueries, IMqttClient mqttClient, IOptions <DeviceSettings> options)
 {
     _mediator             = mediator ?? throw new ArgumentNullException(nameof(mediator));
     _deviceQueries        = deviceQueries ?? throw new ArgumentNullException(nameof(deviceQueries));
     _identityService      = identityService ?? throw new ArgumentNullException(nameof(identityService));
     _logger               = logger ?? throw new ArgumentNullException(nameof(logger));
     _mapper               = mapper ?? throw new ArgumentNullException(nameof(mapper));
     _skynetTerminalClient = skynetTerminalClient ?? throw new ArgumentNullException(nameof(skynetTerminalClient));
     _terminalQueries      = terminalQueries ?? throw new ArgumentException(nameof(terminalQueries));
     _mqttClient           = mqttClient ?? throw new ArgumentNullException(nameof(mqttClient));
     _options              = options ?? throw new ArgumentNullException(nameof(options));
 }
        protected async override void OnAppearing()
        {
            client = await MqttClient.CreateAsync(host, port);

            await client.ConnectAsync();
        }
示例#10
0
 public ToConnecting(IMqttClient client)
 {
     Client = client;
 }
示例#11
0
 public TestApplicationMessageReceivedHandler(IMqttClient mqttClient)
 {
     mqttClient.ApplicationMessageReceivedAsync += MqttClientOnApplicationMessageReceivedAsync;
 }
        static void Main(string[] args)
        {
            MqttFactory factory = new MqttFactory();

            mqttClient = factory.CreateMqttClient();

            if ((args.Length != 3))
            {
                Console.WriteLine("[MQTT Server] [UserName] [ClientID]");
                Console.WriteLine("Press <enter> to exit");
                Console.ReadLine();
                return;
            }

            server   = args[0];
            username = args[1];
            deviceID = args[2];

            Console.WriteLine($"MQTT Server:{server} DeviceID:{deviceID}");

            // AllThingsTalk formatted device state update topic
            string topicD2C = $"device/{deviceID}/state";

            mqttOptions = new MqttClientOptionsBuilder()
                          .WithTcpServer(server)
                          .WithCredentials(username, "HighlySecurePassword")
                          .WithClientId(deviceID)
                          .WithTls()
                          .Build();

            mqttClient.UseDisconnectedHandler(new MqttClientDisconnectedHandlerDelegate(e => MqttClient_Disconnected(e)));
            mqttClient.UseApplicationMessageReceivedHandler(new MqttApplicationMessageReceivedHandlerDelegate(e => MqttClient_ApplicationMessageReceived(e)));
            mqttClient.ConnectAsync(mqttOptions).Wait();

            // AllThingsTalk formatted device command with wildcard topic
            string topicC2D = $"device/{deviceID}/asset/+/command";

            mqttClient.SubscribeAsync(topicC2D, MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce).GetAwaiter().GetResult();

            while (true)
            {
                JObject payloadJObject = new JObject();

                double temperature = 22.0 + (DateTime.UtcNow.Millisecond / 1000.0);
                temperature = Math.Round(temperature, 1);
                double humidity = 50 + (DateTime.UtcNow.Millisecond / 100.0);
                humidity = Math.Round(humidity, 1);

                JObject temperatureJObject = new JObject
                {
                    { "value", temperature }
                };
                payloadJObject.Add("Temperature", temperatureJObject);

                JObject humidityJObject = new JObject
                {
                    { "value", humidity }
                };
                payloadJObject.Add("Humidity", humidityJObject);

                string payload = JsonConvert.SerializeObject(payloadJObject);
                Console.WriteLine($"Topic:{topicD2C} Payload:{payload}");

                var message = new MqttApplicationMessageBuilder()
                              .WithTopic(topicD2C)
                              .WithPayload(payload)
                              .WithAtMostOnceQoS()
//					.WithAtLeastOnceQoS()
                              .Build();

                Console.WriteLine("PublishAsync start");
                mqttClient.PublishAsync(message).Wait();
                Console.WriteLine("PublishAsync finish");

                Thread.Sleep(15100);
            }
        }
示例#13
0
        public async Task <MqttClientPublishResult> PublishAsync(string topic, string payload, bool retain, ClsImageQueueItem CurImg)
        {
            using var Trace = new Trace();  //This c# 8.0 using feature will auto dispose when the function is done.

            MqttClientPublishResult res = null;
            Stopwatch sw = Stopwatch.StartNew();

            await Task.Run(async() =>
            {
                MqttFactory factory = new MqttFactory();

                IMqttClient mqttClient = null;
                bool subscribed        = false;

                using (mqttClient = factory.CreateMqttClient())
                {
                    try
                    {
                        string server = Global.GetWordBetween(AppSettings.Settings.mqtt_serverandport, "", ":");
                        string port   = Global.GetWordBetween(AppSettings.Settings.mqtt_serverandport, ":", "/");
                        int portint   = 0;
                        if (!string.IsNullOrEmpty(port))
                        {
                            portint = Convert.ToInt32(port);
                        }
                        if (portint == 0 && AppSettings.Settings.mqtt_UseTLS)
                        {
                            portint = 8883;
                        }
                        else if (portint == 0)
                        {
                            portint = 1883;
                        }

                        bool IsWebSocket = (AppSettings.Settings.mqtt_serverandport.IndexOf("ws://", StringComparison.OrdinalIgnoreCase) >= 0 ||
                                            AppSettings.Settings.mqtt_serverandport.IndexOf("/mqtt", StringComparison.OrdinalIgnoreCase) >= 0 ||
                                            AppSettings.Settings.mqtt_serverandport.IndexOf("wss://", StringComparison.OrdinalIgnoreCase) >= 0);

                        bool UseTLS = (AppSettings.Settings.mqtt_UseTLS || portint == 8883 || AppSettings.Settings.mqtt_serverandport.ToLower().Contains("wss://"));

                        bool UseCreds = (!string.IsNullOrWhiteSpace(AppSettings.Settings.mqtt_username));

                        IMqttClientOptions options;


                        //=====================================================================
                        //Seems like there should be a better way here with this Options builder...
                        //I dont see an obvious way to directly modify options without the builder
                        //and I cant seem to put IF statements around each part of the option builder
                        //parameters.
                        //=====================================================================



                        if (UseTLS)
                        {
                            if (UseCreds)
                            {
                                if (IsWebSocket)
                                {
                                    options = new MqttClientOptionsBuilder()
                                              .WithClientId(AppSettings.Settings.mqtt_clientid)
                                              .WithWebSocketServer(AppSettings.Settings.mqtt_serverandport)
                                              .WithCredentials(AppSettings.Settings.mqtt_username, AppSettings.Settings.mqtt_password)
                                              .WithTls()
                                              .WithCleanSession()
                                              .Build();
                                }
                                else
                                {
                                    options = new MqttClientOptionsBuilder()
                                              .WithClientId(AppSettings.Settings.mqtt_clientid)
                                              .WithTcpServer(server, portint)
                                              .WithCredentials(AppSettings.Settings.mqtt_username, AppSettings.Settings.mqtt_password)
                                              .WithTls()
                                              .WithCleanSession()
                                              .Build();
                                }
                            }
                            else
                            {
                                if (IsWebSocket)
                                {
                                    options = new MqttClientOptionsBuilder()
                                              .WithClientId(AppSettings.Settings.mqtt_clientid)
                                              .WithWebSocketServer(AppSettings.Settings.mqtt_serverandport)
                                              .WithTls()
                                              .WithCleanSession()
                                              .Build();
                                }
                                else
                                {
                                    options = new MqttClientOptionsBuilder()
                                              .WithClientId(AppSettings.Settings.mqtt_clientid)
                                              .WithTcpServer(server, portint)
                                              .WithTls()
                                              .WithCleanSession()
                                              .Build();
                                }
                            }
                        }
                        else
                        {
                            if (UseCreds)
                            {
                                if (IsWebSocket)
                                {
                                    options = new MqttClientOptionsBuilder()
                                              .WithClientId(AppSettings.Settings.mqtt_clientid)
                                              .WithWebSocketServer(AppSettings.Settings.mqtt_serverandport)
                                              .WithCredentials(AppSettings.Settings.mqtt_username, AppSettings.Settings.mqtt_password)
                                              .WithCleanSession()
                                              .Build();
                                }
                                else
                                {
                                    options = new MqttClientOptionsBuilder()
                                              .WithClientId(AppSettings.Settings.mqtt_clientid)
                                              .WithTcpServer(server, portint)
                                              .WithCredentials(AppSettings.Settings.mqtt_username, AppSettings.Settings.mqtt_password)
                                              .WithCleanSession()
                                              .Build();
                                }
                            }
                            else
                            {
                                if (IsWebSocket)
                                {
                                    options = new MqttClientOptionsBuilder()
                                              .WithClientId(AppSettings.Settings.mqtt_clientid)
                                              .WithTcpServer(server, portint)
                                              .WithCleanSession()
                                              .Build();
                                }
                                else
                                {
                                    options = new MqttClientOptionsBuilder()
                                              .WithClientId(AppSettings.Settings.mqtt_clientid)
                                              .WithWebSocketServer(AppSettings.Settings.mqtt_serverandport)
                                              .WithCleanSession()
                                              .Build();
                                }
                            }
                        }

                        if (string.IsNullOrWhiteSpace(topic))
                        {
                            topic = Guid.NewGuid().ToString();
                        }

                        mqttClient.UseDisconnectedHandler(async e =>
                        {
                            string excp = "";
                            if (e.Exception != null)
                            {
                                excp = e.Exception.Message;
                            }
                            Log($"Debug: MQTT: ### DISCONNECTED FROM SERVER ### - Reason: {e.ReasonCode}, ClientWasDisconnected: {e.ClientWasConnected}, {excp}");

                            //reconnect here if needed?
                        });


                        mqttClient.UseApplicationMessageReceivedHandler(async e =>
                        {
                            Log($"Debug: MQTT: ### RECEIVED APPLICATION MESSAGE ###");
                            Log($"Debug: MQTT: + Topic = {e.ApplicationMessage.Topic}");
                            if (e.ApplicationMessage.Payload.Length < 64)
                            {
                                Log($"Debug: MQTT: + Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
                            }
                            Log($"Debug: MQTT: + QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
                            Log($"Debug: MQTT: + Retain = {e.ApplicationMessage.Retain}");
                            Log("");
                        });


                        mqttClient.UseConnectedHandler(async e =>
                        {
                            Log($"Debug: MQTT: ### CONNECTED WITH SERVER '{AppSettings.Settings.mqtt_serverandport}' ### - Result: {e.AuthenticateResult.ResultCode}, '{e.AuthenticateResult.ReasonString}'");

                            // Subscribe to the topic
                            await mqttClient.SubscribeAsync(topic, MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce);

                            subscribed = true;

                            Log($"Debug: MQTT: ### SUBSCRIBED to topic '{topic}'");
                        });


                        Log($"Debug: MQTT: Sending topic '{topic}' with payload '{payload}' to server '{server}:{portint}'...");


                        MqttClientAuthenticateResult cres = await mqttClient.ConnectAsync(options, CancellationToken.None);

                        if (cres != null && cres.ResultCode == MqttClientConnectResultCode.Success)
                        {
                            MqttApplicationMessage ma;

                            if (CurImg != null)
                            {
                                using FileStream image_data = System.IO.File.OpenRead(CurImg.image_path);

                                ma = new MqttApplicationMessageBuilder()
                                     .WithTopic(topic)
                                     .WithPayload(image_data)
                                     .WithAtLeastOnceQoS()
                                     .WithRetainFlag(retain)
                                     .Build();

                                res = await mqttClient.PublishAsync(ma, CancellationToken.None);


                                if (res.ReasonCode == MqttClientPublishReasonCode.Success)
                                {
                                    Log($"Debug: MQTT: ...Sent image in {sw.ElapsedMilliseconds}ms, Reason: '{res.ReasonCode}' ({Convert.ToInt32(res.ReasonCode)} - '{res.ReasonString}')");
                                }
                                else
                                {
                                    Log($"Error: MQTT: sending image: ({sw.ElapsedMilliseconds}ms) Reason: '{res.ReasonCode}' ({Convert.ToInt32(res.ReasonCode)} - '{res.ReasonString}')");
                                }
                            }
                            else
                            {
                                ma = new MqttApplicationMessageBuilder()
                                     .WithTopic(topic)
                                     .WithPayload(payload)
                                     .WithAtLeastOnceQoS()
                                     .WithRetainFlag(retain)
                                     .Build();

                                res = await mqttClient.PublishAsync(ma, CancellationToken.None);

                                //Success = 0,
                                //        NoMatchingSubscribers = 0x10,
                                //        UnspecifiedError = 0x80,
                                //        ImplementationSpecificError = 0x83,
                                //        NotAuthorized = 0x87,
                                //        TopicNameInvalid = 0x90,
                                //        PacketIdentifierInUse = 0x91,
                                //        QuotaExceeded = 0x97,
                                //        PayloadFormatInvalid = 0x99

                                if (res.ReasonCode == MqttClientPublishReasonCode.Success)
                                {
                                    Log($"Debug: MQTT: ...Sent in {sw.ElapsedMilliseconds}ms, Reason: '{res.ReasonCode}' ({Convert.ToInt32(res.ReasonCode)} - '{res.ReasonString}')");
                                }
                                else
                                {
                                    Log($"Error: MQTT: sending: ({sw.ElapsedMilliseconds}ms) Reason: '{res.ReasonCode}' ({Convert.ToInt32(res.ReasonCode)} - '{res.ReasonString}')");
                                }
                            }
                        }
                        else if (cres != null)
                        {
                            Log($"Error: MQTT: connecting: ({sw.ElapsedMilliseconds}ms) Result: '{cres.ResultCode}' - '{cres.ReasonString}'");
                        }
                        else
                        {
                            Log($"Error: MQTT: Error connecting: ({sw.ElapsedMilliseconds}ms) cres=null");
                        }

                        if (mqttClient != null && mqttClient.IsConnected)
                        {
                            if (subscribed)
                            {
                                Log($"Debug: MQTT: Unsubscribing from topic '{topic}'");
                                await mqttClient.UnsubscribeAsync(topic);
                            }
                            Log($"Debug: MQTT: Disconnecting from server.");
                            await mqttClient.DisconnectAsync();
                        }
                    }
                    catch (Exception ex)
                    {
                        Log($"Error: MQTT: Unexpected Error: Topic '{topic}' Payload '{payload}': " + Global.ExMsg(ex));
                    }
                    finally
                    {
                        if (mqttClient != null && mqttClient.IsConnected)
                        {
                            if (subscribed)
                            {
                                Log($"Debug: MQTT: Unsubscribing from topic '{topic}'");
                                await mqttClient.UnsubscribeAsync(topic);
                            }
                            Log($"Debug: MQTT: Disconnecting from server.");
                            await mqttClient.DisconnectAsync();
                            mqttClient.Dispose();                  //using should dispose anyway
                        }
                    }
                }
            });


            return(res);
        }
示例#14
0
        static void Main(string[] args)
        {
            MqttFactory factory = new MqttFactory();

            mqttClient = factory.CreateMqttClient();

            if ((args.Length != 6) && (args.Length != 8) && (args.Length != 9))
            {
                Console.WriteLine("[MQTT Server] [UserName] [Password] [WriteAPIKey] [ClientID] [Channel]");
                Console.WriteLine("[MQTT Server] [UserName] [Password] [WriteAPIKey] [ClientID] [Channel] [channelSubscribe] [ReadApiKey]");
                Console.WriteLine("[MQTT Server] [UserName] [Password] [WriteAPIKey] [ClientID] [Channel] [channelSubscribe] [ReadApiKey] [Field]");
                Console.WriteLine("Press <enter> to exit");
                Console.ReadLine();
                return;
            }

            server      = args[0];
            username    = args[1];
            password    = args[2];
            writeApiKey = args[3];
            clientId    = args[4];
            channelData = args[5];

            if (args.Length == 6)
            {
                Console.WriteLine($"MQTT Server:{server} Username:{username} ClientID:{clientId} ChannelData:{channelData}");
            }

            if (args.Length == 8)
            {
                channelSubscribe = args[6];
                readApiKey       = args[7];
                Console.WriteLine($"MQTT Server:{server} Username:{username} ClientID:{clientId} ChannelData:{channelData} ChannelSubscribe:{channelSubscribe}");
            }

            if (args.Length == 9)
            {
                channelSubscribe = args[6];
                readApiKey       = args[7];
                field            = args[8];
                Console.WriteLine($"MQTT Server:{server} Username:{username} ClientID:{clientId} ChannelData:{channelData} ChannelSubscribe:{channelSubscribe} Field:{field}");
            }

            mqttOptions = new MqttClientOptionsBuilder()
                          .WithTcpServer(server)
                          .WithCredentials(username, password)
                          .WithClientId(clientId)
                          .WithTls()
                          .Build();

            mqttClient.ConnectAsync(mqttOptions).Wait();

            if (args.Length == 8)
            {
                string topic = $"channels/{channelSubscribe}/subscribe/fields/+/{readApiKey}";

                Console.WriteLine($"Subscribe Topic:{topic}");

                mqttClient.SubscribeAsync(topic, MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce).Wait();
                mqttClient.UseApplicationMessageReceivedHandler(new MqttApplicationMessageReceivedHandlerDelegate(e => MqttClient_ApplicationMessageReceived(e)));
            }
            if (args.Length == 9)
            {
                string topic = $"channels/{channelSubscribe}/subscribe/fields/{field}/{readApiKey}";

                Console.WriteLine($"Subscribe Topic:{topic}");

                mqttClient.SubscribeAsync(topic, MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce).Wait();
                mqttClient.UseApplicationMessageReceivedHandler(new MqttApplicationMessageReceivedHandlerDelegate(e => MqttClient_ApplicationMessageReceived(e)));
            }

            mqttClient.UseDisconnectedHandler(new MqttClientDisconnectedHandlerDelegate(e => MqttClient_Disconnected(e)));

            string topicTemperatureData = $"channels/{channelData}/publish/{writeApiKey}";

            Console.WriteLine();

            while (true)
            {
                string value = "field1=22." + DateTime.UtcNow.Millisecond.ToString() + "&field2=60." + DateTime.UtcNow.Millisecond.ToString();
                Console.WriteLine($"Publish Topic {topicTemperatureData}  Value {value}");

                var message = new MqttApplicationMessageBuilder()
                              .WithTopic(topicTemperatureData)
                              .WithPayload(value)
                              .WithAtMostOnceQoS()
                              .Build();

                Console.WriteLine("PublishAsync start");
                mqttClient.PublishAsync(message).Wait();
                Console.WriteLine("PublishAsync finish");
                Console.WriteLine();

                Thread.Sleep(30100);
            }
        }
示例#15
0
        public async Task ConnectMqttServerAsync()
        {
            // Create a new MQTT client.
            if (mqttClient == null)
            {
                var factory = new MqttFactory();
                isReconnect = true;
                mqttClient  = factory.CreateMqttClient();

                mqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived;
                mqttClient.Connected    += MqttClient_Connected;
                mqttClient.Disconnected += MqttClient_Disconnected;
            }

            //非托管客户端
            try
            {
                ////Create TCP based options using the builder.
                //var options1 = new MqttClientOptionsBuilder()
                //    .WithClientId("client001")
                //    .WithTcpServer("192.168.88.3")
                //    .WithCredentials("bud", "%spencer%")
                //    .WithTls()
                //    .WithCleanSession()
                //    .Build();

                //// Use TCP connection.
                //var options2 = new MqttClientOptionsBuilder()
                //    .WithTcpServer("192.168.88.3", 8222) // Port is optional
                //    .Build();

                //// Use secure TCP connection.
                //var options3 = new MqttClientOptionsBuilder()
                //    .WithTcpServer("192.168.88.3")
                //    .WithTls()
                //    .Build();

                //Create TCP based options using the builder.
                var options = new MqttClientOptionsBuilder()
                              .WithClientId(clientId)
                              .WithTcpServer(ip, Convert.ToInt32(port))

                              //.WithTls()//服务器端没有启用加密协议,这里用tls的会提示协议异常
                              .WithCleanSession()
                              .Build();

                //// For .NET Framwork & netstandard apps:
                //MqttTcpChannel.CustomCertificateValidationCallback = (x509Certificate, x509Chain, sslPolicyErrors, mqttClientTcpOptions) =>
                //{
                //    if (mqttClientTcpOptions.Server == "server_with_revoked_cert")
                //    {
                //        return true;
                //    }

                //    return false;
                //};

                //2.4.0版本的
                //var options0 = new MqttClientTcpOptions
                //{
                //    Server = "127.0.0.1",
                //    ClientId = Guid.NewGuid().ToString().Substring(0, 5),
                //    UserName = "******",
                //    Password = "******",
                //    CleanSession = true
                //};

                await mqttClient.ConnectAsync(options);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"连接到MQTT服务器失败!" + Environment.NewLine + ex.Message + Environment.NewLine);
                Trace.WriteLine($"连接到MQTT服务器失败!" + Environment.NewLine + ex.Message + Environment.NewLine, "MqttConnectStatus");
            }

            //托管客户端
            try
            {
                //// Setup and start a managed MQTT client.
                //var options = new ManagedMqttClientOptionsBuilder()
                //    .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                //    .WithClientOptions(new MqttClientOptionsBuilder()
                //        .WithClientId("Client_managed")
                //        .WithTcpServer("192.168.88.3", 8223)
                //        .WithTls()
                //        .Build())
                //    .Build();

                //var mqttClient = new MqttFactory().CreateManagedMqttClient();
                //await mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("my/topic").Build());
                //await mqttClient.StartAsync(options);
            }
            catch (Exception)
            {
            }
        }
 public EPresMessageHandler(IKebaConnector kebaConnector,
                            ILoggerFactory loggerfactory, IMqttClient mqttClient)
     : base(kebaConnector, loggerfactory, mqttClient)
 {
 }
示例#17
0
 public static IMqttClient UseDisconnectedHandler(this IMqttClient client, IMqttClientDisconnectedHandler handler)
 {
     client.DisconnectedHandler = handler;
     return(client);
 }
示例#18
0
        static void Main(string[] args)
        {
            bool IsConnected = false;
            bool isDebug     = false;
            int  msPause     = 5000;

            //Find replay file
            string sFile = "Replay0909.txt";

            if (args.Length > 0 && args[0] != null)
            {
                sFile = args[0];
                Console.WriteLine($"Reading from {sFile}");
            }
            string sQualifier = "2019-";

            if (args.Length > 1 && args[1] != null)
            {
                sQualifier = args[1];
                Console.WriteLine($"Qualifier {sQualifier}");
            }
            if (args.Length > 2 && args[2] != null)
            {
                if (args[2].Equals("0"))
                {
                    isDebug = false;
                    Console.WriteLine($"Pausing between sections until keypress");
                }
                else
                {
                    isDebug = true;
                    msPause = int.Parse(args[2]);
                    Console.WriteLine($"Debugging, pause {msPause} ms");
                }
            }


//            string sBrokerURL="mqtt.symlink.se";
//            string sBrokerUser="******";
//            string sBrokerPasswd="UlCoPGgk";

            string sBrokerURL = "192.168.222.20";
//            string sBrokerUser="******";
            //string sBrokerPasswd="UlCoPGgk";

            MqttFactory Factory = new MqttFactory();

            IMqttClient MqttClnt = Factory.CreateMqttClient();

            IMqttClientOptions options = new MqttClientOptionsBuilder()
                                         .WithClientId("EnergyAppTester")
                                         .WithTcpServer(sBrokerURL)
                                         //.WithCredentials(sBrokerUser, sBrokerPasswd)
                                         //.WithCleanSession()
                                         .Build();

            //var result = MqttClnt.ConnectAsync(options);
            #region UseConnectedHandler
            MqttClnt.UseConnectedHandler(e =>
            {
                Console.WriteLine("### CONNECTED TO SERVER ###");
                IsConnected = true;
                // Subscribe to topics
//                foreach(string Name in bcLookup.Keys) {
//                  await MqttClnt.SubscribeAsync(new TopicFilterBuilder().WithTopic($"{Name}/#").Build());
//            }
                //await MqttClnt.SubscribeAsync(new TopicFilterBuilder().WithTopic("+/status/#").Build());
                //await MqttClnt.SubscribeAsync(new TopicFilterBuilder().WithTopic("+/set/#").Build());

                Console.WriteLine("### SUBSCRIBED to ###");
            });
            #endregion

            MqttClnt.UseDisconnectedHandler(async e =>
            {
                Console.WriteLine("### DISCONNECTED FROM SERVER ###");
                IsConnected = false;
                await Task.Delay(TimeSpan.FromSeconds(5));
                try
                {
                    await MqttClnt.ConnectAsync(options);
                    IsConnected = true;
                }
                catch
                {
                    Console.WriteLine("### RECONNECTING FAILED ###");
                }
            });


            var result = MqttClnt.ConnectAsync(options);

            Console.WriteLine($"Replaying from {sFile}");

            MessageHandler msgHandler = new MessageHandler(sQualifier);

            foreach (string line in File.ReadLines(sFile, Encoding.UTF8))
            {
                if (msgHandler.HandleRow(line))
                {
                    if (msgHandler.NextSection())
                    {
                        if (isDebug)
                        {
                            Thread.Sleep(msPause);
                        }
                        else
                        {
                            Console.WriteLine("Press key for next topic post");
                            Console.ReadLine();
                        }
                    }
                    string sNewTopic = "Test" + msgHandler.Topic;

                    //Check if connected
                    while (!IsConnected)
                    {
                        Console.WriteLine("Waiting for connection");
                        //Task.Delay(TimeSpan.FromSeconds(5));
                        Thread.Sleep(5000);
                    }
                    MqttClnt.PublishAsync(sNewTopic,
                                          msgHandler.Value,
                                          MqttQualityOfServiceLevel.AtLeastOnce,
                                          false);
                    Console.WriteLine($"Sent {msgHandler.Value} to {sNewTopic} (time {msgHandler.PostDTM})");
                }
            }
        }
示例#19
0
 public static IMqttClient UseMessageReceivedHandler(this IMqttClient client, Action <Message> handler)
 {
     return(client.UseApplicationMessageReceivedHandler(new MessageReceivedHandler(handler)));
 }
示例#20
0
        public SlaveRuntime(IServiceProvider services, ILogger <SlaveRuntime> logger)
        {
            var config = services.GetRequiredService <IConfiguration>();

            _logger = logger;

            _masterAddress = config["server:master"];
            _clientKey     = config["server:clientKey"];

            _slaveId = config["server:clientId"];
            _options = new MqttClientOptionsBuilder()
                       .WithClientId(_slaveId)
                       //   .WithWebSocketServer("localhost:5001/mqtt")
                       .WithTcpServer(_masterAddress, 1883)
                       .WithCredentials(_slaveId, _clientKey)
                       .WithCleanSession()
                       .Build();

            if (!String.IsNullOrEmpty(Environment.GetEnvironmentVariable("MQTT_LOG_VERBOSE")))
            {
                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();
                    }

                    _logger.LogTrace(trace);
                };
            }

            _mqttClient = new MqttFactory().CreateMqttClient();
            _mqttClient.ApplicationMessageReceivedHandler = new ApplicationMessageReceivedHandler(this, _logger);

            try
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                {
                    _dockerClient = new DockerClientConfiguration(new Uri("unix:///var/run/docker.sock")).CreateClient();
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    _dockerClient = new DockerClientConfiguration(new Uri("npipe://./pipe/docker_engine")).CreateClient();
                }
                else
                {
                    throw new PlatformNotSupportedException();
                }
            }
            catch (PlatformNotSupportedException)
            {
                throw;
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"Could not connect do docker daemon!");
            }


            _timer.Elapsed += _timer_Elapsed;
        }
示例#21
0
 public static IMqttClient UseApplicationMessageReceivedHandler(this IMqttClient client, IMessageReceivedHandler handler)
 {
     client.MessageReceivedHandler = handler;
     return(client);
 }
示例#22
0
 public Services(ILogger <Services> logger, IMqttClient client)
 {
     _logger = logger;
     _client = client;
 }
示例#23
0
 public static IMqttClient UseConnectedHandler(this IMqttClient client, Action handler)
 {
     return(client.UseConnectedHandler(new MqttClientConnectedHandler(handler)));
 }
示例#24
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SparkplugBase"/> class.
 /// </summary>
 /// <param name="nameSpace">The namespace.</param>
 public SparkplugBase(SparkplugNamespace nameSpace)
 {
     this.NameSpace = nameSpace;
     this.Client    = new MqttFactory().CreateMqttClient();
 }
示例#25
0
        public MqttRpcClient(IMqttClient mqttClient)
        {
            _mqttClient = mqttClient ?? throw new ArgumentNullException(nameof(mqttClient));

            _mqttClient.ApplicationMessageReceived += OnApplicationMessageReceived;
        }
示例#26
0
 public TestClientWrapper(IMqttClient implementation, TestContext testContext)
 {
     Implementation = implementation;
     TestContext    = testContext;
 }
示例#27
0
        /// <summary>
        /// Perform the connection to the MQTTBroker
        /// </summary>
        /// <param name="reconnectInterval"></param>
        /// <param name="mqttClientOptions"></param>
        /// <param name="mqttClient"></param>
        private static async Task Connect(int reconnectInterval, IMqttClientOptions mqttClientOptions, IMqttClient mqttClient)
        {
            try
            {
                var result = await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None).ConfigureAwait(false);

                if (MqttClientConnectResultCode.Success == result.ResultCode)
                {
                    Utils.Trace("MQTT client {0} successfully connected", mqttClient?.Options?.ClientId);
                }
                else
                {
                    Utils.Trace("MQTT client {0} connect atempt returned {0}", mqttClient?.Options?.ClientId, result?.ResultCode);
                }
            }
            catch (Exception e)
            {
                Utils.Trace("MQTT client {0} connect atempt returned {1} will try to reconnect in {2} seconds",
                            mqttClient?.Options?.ClientId,
                            e.Message,
                            reconnectInterval);
            }
        }
示例#28
0
        public void Open()
        {
            Close();
            mqttClient = factory.CreateMqttClient();
            if (string.IsNullOrEmpty(userClientId))
            {
                clientId = Guid.NewGuid().ToString();
            }
            else
            {
                clientId = userClientId;
            }
            var options = new MqttClientOptionsBuilder()
                          .WithTcpServer(serverAddress, port).WithClientId(clientId)
                          .Build();

            mqttClient.UseApplicationMessageReceivedHandler(t =>
            {
                string str          = ASCIIEncoding.ASCII.GetString(t.ApplicationMessage.Payload);
                GXJsonParser parser = new GXJsonParser();
                GXMessage msg       = parser.Deserialize <GXMessage>(str);
                if (msg.id == messageId || (MesssageType)msg.type == MesssageType.Close || (MesssageType)msg.type == MesssageType.Exception)
                {
                    switch ((MesssageType)msg.type)
                    {
                    case MesssageType.Open:
                        m_OnMediaStateChange?.Invoke(this, new MediaStateEventArgs(MediaState.Open));
                        replyReceivedEvent.Set();
                        break;

                    case MesssageType.Send:
                        break;

                    case MesssageType.Receive:
                        byte[] bytes = Gurux.Common.GXCommon.HexToBytes(msg.frame);
                        replyReceivedEvent.Set();
                        if (bytes.Length != 0)
                        {
                            HandleReceivedData(bytes.Length, bytes, t.ClientId);
                        }
                        break;

                    case MesssageType.Close:
                        m_OnMediaStateChange?.Invoke(this, new MediaStateEventArgs(MediaState.Closed));
                        replyReceivedEvent.Set();
                        break;

                    case MesssageType.Exception:
                        lastException = msg.exception;
                        replyReceivedEvent.Set();
                        break;
                    }
                }
                else
                {
                    m_OnTrace?.Invoke(this, new TraceEventArgs(TraceTypes.Info, "Unknown reply. " + msg, msg.sender));
                }
            });
            mqttClient.UseConnectedHandler(t =>
            {
                // Subscribe to a topic
                mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic(clientId).WithAtMostOnceQoS().Build()).Wait();
                m_OnMediaStateChange?.Invoke(this, new MediaStateEventArgs(MediaState.Opening));
                GXMessage msg = new GXMessage()
                {
                    id = MessageId, type = (int)MesssageType.Open, sender = clientId
                };
                PublishMessage(msg);
            });
            mqttClient.UseDisconnectedHandler(t =>
            {
                m_OnMediaStateChange?.Invoke(this, new MediaStateEventArgs(MediaState.Closed));
                replyReceivedEvent.Set();
            });
            try
            {
                replyReceivedEvent.Reset();
                if (AsyncWaitTime == 0)
                {
                    mqttClient.ConnectAsync(options).Wait();
                }
                else
                {
                    mqttClient.ConnectAsync(options).Wait((int)AsyncWaitTime * 1000);
                }
            }
            catch (AggregateException ex)
            {
                if (mqttClient != null)
                {
                    mqttClient.DisconnectAsync().Wait(10000);
                }
                mqttClient = null;
                throw ex.InnerException;
            }
            replyReceivedEvent.WaitOne();
            if (lastException != null)
            {
                throw new Exception(lastException);
            }
        }
示例#29
0
        /// <summary>
        /// The method which returns an MQTT client
        /// </summary>
        /// <param name="reconnectInterval">Number of seconds to reconnect to the MQTT broker</param>
        /// <param name="mqttClientOptions">The client options for MQTT broker connection</param>
        /// <param name="receiveMessageHandler">The receiver message handler</param>
        /// <param name="topicFilter">The topics to which to subscribe</param>
        /// <returns></returns>
        internal static async Task <IMqttClient> GetMqttClientAsync(int reconnectInterval,
                                                                    IMqttClientOptions mqttClientOptions,
                                                                    Action <MqttApplicationMessageReceivedEventArgs> receiveMessageHandler,
                                                                    StringCollection topicFilter = null)
        {
            IMqttClient mqttClient = mqttClientFactory.Value.CreateMqttClient();

            // Hook the receiveMessageHandler in case we deal with a subscriber
            if ((receiveMessageHandler != null) && (topicFilter != null))
            {
                HashSet <string>       uniqueTopics = new HashSet <string>(topicFilter.ToArray());
                List <MqttTopicFilter> topics       = new List <MqttTopicFilter>();
                foreach (var topic in uniqueTopics)
                {
                    MqttTopicFilter tf = new MqttTopicFilter();
                    tf.Topic = topic;
                    topics.Add(tf);
                }

                mqttClient.UseApplicationMessageReceivedHandler(receiveMessageHandler);
                mqttClient.UseConnectedHandler(async e => {
                    Utils.Trace("{0} Connected to MQTTBroker", mqttClient?.Options?.ClientId);

                    try
                    {
                        // subscribe to provided topics, messages are also filtered on the receiveMessageHandler
                        await mqttClient.SubscribeAsync(topics.ToArray()).ConfigureAwait(false);
                        Utils.Trace("{0} Subscribed to topics: {1}", mqttClient?.Options?.ClientId, string.Join(",", topics));
                    }
                    catch (Exception exception)
                    {
                        Utils.Trace(exception, "{0} could not subscribe to topics: {1}", mqttClient?.Options?.ClientId, string.Join(",", topics));
                    }
                });
            }
            else
            {
                if (receiveMessageHandler == null)
                {
                    Utils.Trace("The provided MQTT message handler is null therefore messages will not be processed on client {0}!!!", mqttClient?.Options?.ClientId);
                }
                if (topicFilter == null)
                {
                    Utils.Trace("The provided MQTT message topic filter is null therefore messages will not be processed on client {0}!!!", mqttClient?.Options?.ClientId);
                }
            }

            // Setup reconnect handler
            mqttClient.UseDisconnectedHandler(async e => {
                await Task.Delay(TimeSpan.FromSeconds(reconnectInterval)).ConfigureAwait(false);
                try
                {
                    Utils.Trace("Disconnect Handler called on client {0}, reason: {1} was connected: {2}",
                                mqttClient?.Options?.ClientId,
                                e.Reason,
                                e.ClientWasConnected);
                    await Connect(reconnectInterval, mqttClientOptions, mqttClient).ConfigureAwait(false);
                }
                catch (Exception excOnDisconnect)
                {
                    Utils.Trace("{0} Failed to reconnect after disconnect occurred: {1}", mqttClient?.Options?.ClientId, excOnDisconnect.Message);
                }
            });

            await Connect(reconnectInterval, mqttClientOptions, mqttClient).ConfigureAwait(false);

            return(mqttClient);
        }
示例#30
0
        private static void Main(string[] args)
        {
            var turnOffPayLoad = new StatusPayload
            {
                ApplicationId = "wilink",
                EntityId      = Guid.NewGuid(),
                EntityType    = "AGE",
                IdentifyCode  = "ec3cc6d0-829a-11e9-bc42-526af7764f64",
                Status        = "OFF"
            };
            var turnOffPayloadJson = JsonConvert.SerializeObject(turnOffPayLoad);
            var lastWillMessage    = new MqttApplicationMessage
            {
                Topic   = DeviceChangeStatusToPic,
                Payload = Encoding.UTF8.GetBytes(turnOffPayloadJson),
                QualityOfServiceLevel = MqttQualityOfServiceLevel.ExactlyOnce,
                Retain = true
            };

            var options = new MqttClientOptionsBuilder()
                          .WithClientId("clientId-pXiamU1MOP33")
                          //.WithTcpServer("127.0.0.1", 8000)
                          .WithWebSocketServer("wss://wilinkhub//mqtt")
                          .WithTls(parameters: new MqttClientOptionsBuilderTlsParameters()
            {
                UseTls = true,
                AllowUntrustedCertificates        = false,
                IgnoreCertificateChainErrors      = true,
                IgnoreCertificateRevocationErrors = true,
                SslProtocol = SslProtocols.Tls12,
                CertificateValidationCallback = (x, y, z, o) => true
            })
                          .WithCredentials("mySecretUser", "mySecretPassword")
                          .WithCleanSession()
                          .WithWillMessage(lastWillMessage)
                          .WithRequestResponseInformation()
                          .Build();

            _publisherClient = new MqttFactory().CreateMqttClient();
            _publisherClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(ConnectedHandler);
            _publisherClient.ConnectAsync(options);

            while (true)
            {
                Console.WriteLine("Press 0 to exit, 1 to connect again, type message to publish.");
                var command = Console.ReadLine();

                switch (command)
                {
                case "0":
                {
                    var connectMessage = new MqttApplicationMessageBuilder()
                                         .WithTopic(DeviceChangeStatusToPic)
                                         .WithPayload(turnOffPayloadJson)
                                         .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.ExactlyOnce)
                                         .WithRetainFlag()
                                         .Build();
                    _publisherClient.PublishAsync(connectMessage).ContinueWith(s => _publisherClient.DisconnectAsync());
                }
                break;

                case "1":
                {
                    if (!_publisherClient.IsConnected)
                    {
                        _publisherClient.ConnectAsync(options);
                    }
                    break;
                }

                default:
                {
                    if (_publisherClient.IsConnected)
                    {
                        var topic2Message = new MqttApplicationMessageBuilder()
                                            .WithTopic("testtopic/2")
                                            .WithPayload(command)
                                            .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.ExactlyOnce)
                                            .WithRetainFlag(false)
                                            .Build();
                        var result = _publisherClient.PublishAsync(topic2Message);
                        if (result.IsCompleted)
                        {
                            Console.WriteLine("Publish success!");
                        }
                    }
                    break;
                }
                }
            }
        }
示例#31
0
        public static IManagedMqttClient CreateManagedMqttClient(this MqttFactory factory, IMqttClient mqttClient = null)
        {
            if (factory == null)
            {
                throw new ArgumentNullException(nameof(factory));
            }

            if (mqttClient == null)
            {
                return(new ManagedMqttClient(factory.CreateMqttClient(), factory.DefaultLogger));
            }

            return(new ManagedMqttClient(mqttClient, factory.DefaultLogger));
        }