using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using MQTTnet; using MQTTnet.Client; using MQTTnet.Extensions.ManagedClient; using NLog.Fluent; namespace Dfs.WayneChina.CheryFuelController { public class CheryClient { private readonly string _host; private readonly int _port; private readonly string _clientId; private readonly int _interval; private readonly string _jobDownUrl; private readonly string _jobResUpUrl; private IManagedMqttClient _mqttClient; #region Logger NLog.Logger logger = NLog.LogManager.LoadConfiguration("NLog.config").GetLogger("Application"); #endregion public CheryClient(string host, int port, string clientId, string username, string password, int interval, string jobDownUrl, string jobResultUpUrl) { _host = host; _port = port; _clientId = clientId; _interval = interval; _jobDownUrl = jobDownUrl; _jobResUpUrl = jobResultUpUrl; _mqttClient = new MqttFactory().CreateManagedMqttClient(); _mqttClient.ConnectedAsync += this.OnConnected; _mqttClient.DisconnectedAsync += this.OnDisconnected; _mqttClient.ConnectingFailedAsync += this.OnConnectingFailed; _mqttClient.ApplicationMessageReceivedAsync += this.HandleApplicationMessageReceivedAsync; } public Task HandleApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs eventArgs) { string topic = $"Topic: {eventArgs.ApplicationMessage.Topic}"; string payload = $"- Payload: {System.Text.Encoding.UTF8.GetString(eventArgs.ApplicationMessage.Payload)}"; logger.Info($"Received: {topic + payload}"); return Task.CompletedTask; } private ManagedMqttClientOptions CreateOptions(string host, int port, string clientId) { MqttClientOptionsBuilder builder = new MqttClientOptionsBuilder() //.WithClientId(clientId) .WithTcpServer(host, port); ManagedMqttClientOptions options = new ManagedMqttClientOptionsBuilder() .WithAutoReconnectDelay(TimeSpan.FromSeconds(_interval)) .WithClientOptions(builder.Build()) .Build(); return options; } public async Task StartAsync() { var options = CreateOptions(_host, _port, _clientId); await _mqttClient.StartAsync(options); string topic = "test/downFillSet"; await _mqttClient.SubscribeAsync(new[] { new MqttTopicFilterBuilder().WithTopic(topic).Build() }); } public Task StopAsync() { return _mqttClient.StopAsync(); } public Task OnConnected(MqttClientConnectedEventArgs obj) { logger.Info($"Successfully connected to Broker, assigned id: {obj.ConnectResult.AssignedClientIdentifier}"); return Task.CompletedTask; } public Task OnConnectingFailed(ConnectingFailedEventArgs obj) { logger.Error($"Couldn't connect to broker, {obj.Exception}"); return Task.CompletedTask; } public Task OnDisconnected(MqttClientDisconnectedEventArgs obj) { logger.Error("Successfully disconnected."); return Task.CompletedTask; } } }