public MqttClientService(IManagedMqttClientOptions options, IHubContext <AgentHub, IAgentEvent> hubContext) { this.hubContext = hubContext; this.options = options; mqttClient = new MqttFactory().CreateManagedMqttClient(); ConfigureMqttClient(); }
public MqttClientFacade(ILogger <MqttClientFacade> logger, IOptions <ConnectionSettings> connectionSettings) { ConnectionSettings = connectionSettings.Value; _logger = logger; // Build LWT message _lwtMessage = new MqttApplicationMessageBuilder() .WithPayload(Encoding.UTF8.GetBytes("Offline")) .WithTopic($"stat/{ConnectionSettings.ClientID}/LWT") .WithRetainFlag() .WithAtLeastOnceQoS() .Build(); // Create Client _clientOptions = new ManagedMqttClientOptionsBuilder() .WithAutoReconnectDelay(TimeSpan.FromSeconds(ConnectionSettings.AutoReconnectDelaySeconds)) .WithClientOptions(new MqttClientOptionsBuilder() .WithClientId(ConnectionSettings.ClientID) .WithTcpServer(ConnectionSettings.BrokerURL) .WithWillMessage(_lwtMessage) .WithKeepAlivePeriod(TimeSpan.FromSeconds(10)) .WithCommunicationTimeout(TimeSpan.FromMinutes(5)) .WithCredentials(ConnectionSettings.Username, ConnectionSettings.Password) .WithCleanSession() .Build() ).Build(); _mqttClient = new MqttFactory().CreateManagedMqttClient(); }
public static async Task <MqttClientHelper> Get(ILogger logger, IManagedMqttClientOptions clientOptions) { var clientHelper = new MqttClientHelper(logger, clientOptions); await clientHelper.StartMqttClient(); return(clientHelper); }
public MqttClientService(ILogger logger, IRedisCacheService redisCacheService, IManagedMqttClientOptions options) { this.options = options; this.logger = logger; this.redisCacheService = redisCacheService; mqttClient = new MqttFactory().CreateManagedMqttClient(); ConfigureMqttClient(); }
/// <inheritdoc/> /// <exception cref="ArgumentNullException"></exception> public Task StartAsync(IManagedMqttClientOptions options) { if (options is null) { throw new ArgumentNullException(nameof(options)); } return(InternalClient.StartAsync(options)); }
public MqttClientService( IManagedMqttClientOptions options, CalculationContext dbContext, HttpTransportService httpClient ) { _options = options; _dbContext = dbContext; _httpClient = httpClient; _mqttClient = new MqttFactory().CreateManagedMqttClient(); ConfigureMqttClient(); }
public MqttClientService(IManagedMqttClientOptions options, IHubContext <BrokerHub> hubContext, BrokerEvents brokerEvents, ZigbeeEvents zigbeeEvents, IServiceScopeFactory serviceScopeFactory, IConfiguration config) { _options = options; _hubContext = hubContext; _brokerEvents = brokerEvents; _zigbeeEvents = zigbeeEvents; _serviceScopeFactory = serviceScopeFactory; _clientSettings = new MqttClientSettings(); _zigbeeSettings = new Zigbee2mqttSettings(); config.GetSection(nameof(MqttClientSettings)).Bind(_clientSettings); config.GetSection(nameof(Zigbee2mqttSettings)).Bind(_zigbeeSettings); _mqttClient = new MqttFactory().CreateManagedMqttClient(); ConfigureMqttClient(); }
public MqttIpcClient(MqttIpcClientConfiguration conf, IIpcPacketRouter router, IIpcSerializer serializer) { _router = router; _serializer = serializer; _packetFactory = new PacketContainerFactory(); _client = new MqttFactory().CreateManagedMqttClient(new MqttNetLogger(conf.ClientName)); _options = new ManagedMqttClientOptionsBuilder() .WithAutoReconnectDelay(TimeSpan.FromSeconds(5)) .WithClientOptions(new MqttClientOptionsBuilder() .WithClientId(conf.ClientName) .WithTcpServer(conf.EndPoint) .Build()) .Build(); _client.ConnectedHandler = new MqttClientConnectedHandlerDelegate(Client_OnConnected); _client.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(Client_OnDisconnected); }
public static async Task <MqttClientHelper> Get(IManagedMqttClientOptions clientOptions) { var clientHelper = new MqttClientHelper(clientOptions); await clientHelper.StartMqttClient(); // wait for 5 seconds for client to be connected for (var i = 0; i < 100; i++) { if (clientHelper.IsConnected) { _logger.LogDebug($"Waited for {i * 50} milliseconds for client to be connected"); return(clientHelper); } await Task.Delay(50); } throw new Exception("Could not connect to server"); }
public Manager(string name, string ip) { var options = new ManagedMqttClientOptionsBuilder(). WithAutoReconnectDelay(TimeSpan.FromSeconds(5)) .WithClientOptions(new MqttClientOptionsBuilder() .WithClientId(name) //.WithCredentials("panon", "dellaMarra") .WithTcpServer(ip) //.WithTls() .Build()) .Build(); var _managedMqttClient = new MqttFactory().CreateManagedMqttClient(); managedMqttClient = _managedMqttClient; clientOptions = options; }
public MqttClientLifetimeService(IManagedMqttClient client, IManagedMqttClientOptions options, IServiceProvider serviceProvider) { _client = client; _options = options; // Initialize initial receives MqttEvents mqttEvents = serviceProvider.GetService <MqttEvents>(); if (mqttEvents != null) { IEnumerable <IMqttEventReceiver> receivers = serviceProvider.GetServices <IMqttEventReceiver>(); foreach (IMqttEventReceiver receiver in receivers) { mqttEvents.OnConnect += receiver.OnConnect; mqttEvents.OnDisconnect += receiver.OnDisconnect; } } }
public async Task StartAsync(IManagedMqttClientOptions options) { if (options == null) { throw new ArgumentNullException(nameof(options)); } if (options.ClientOptions == null) { throw new ArgumentException("The client options are not set.", nameof(options)); } if (!options.ClientOptions.CleanSession) { throw new NotSupportedException("The managed client does not support existing sessions."); } if (_connectionCancellationToken != null) { throw new InvalidOperationException("The managed client is already started."); } _options = options; if (_options.Storage != null) { _storageManager = new ManagedMqttClientStorageManager(_options.Storage); var messages = await _storageManager.LoadQueuedMessagesAsync().ConfigureAwait(false); foreach (var message in messages) { _messageQueue.Add(message); } } _connectionCancellationToken = new CancellationTokenSource(); #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed Task.Run(() => MaintainConnectionAsync(_connectionCancellationToken.Token), _connectionCancellationToken.Token); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed _logger.Info("Started"); }
public async void ReplaceMqttClient(IManagedMqttClientOptions options) { this._logger.LogInformation($"Replacing Mqtt client with new config"); await _mqttClient.StopAsync(); try { await _mqttClient.StartAsync(options); } catch (MqttConnectingFailedException ex) { this._mqttClientMessage = ex.ResultCode.ToString(); Log.Logger.Error("Could not connect to broker: " + ex.ResultCode.ToString()); } catch (MqttCommunicationException ex) { this._mqttClientMessage = ex.ToString(); Log.Logger.Error("Could not connect to broker: " + ex.Message); } }
private async void Button_Connect(object sender, RoutedEventArgs e) { try { options = new ManagedMqttClientOptionsBuilder() .WithAutoReconnectDelay(TimeSpan.FromSeconds(5)) .WithClientOptions(new MqttClientOptionsBuilder() .WithCommunicationTimeout(TimeSpan.FromSeconds(5)) // Default value .WithKeepAlivePeriod(TimeSpan.FromSeconds(7.5)) // Default Value .WithWebSocketServer(mqttAddress.Text) .Build()) .Build(); await mqttClient.StartAsync(options); } catch (Exception ex) { DisplayMessage($"EXCEPTION IN Button_Connect {ex.Message}"); } }
public MqttActor() { ThisContext = Context; Options = new ManagedMqttClientOptionsBuilder() .WithAutoReconnectDelay(TimeSpan.FromSeconds(10)) .WithClientOptions(new MqttClientOptionsBuilder() .WithProtocolVersion(MQTTnet.Serializer.MqttProtocolVersion.V311) .WithClientId(Environment.GetEnvironmentVariable("MqttClientId")) .WithTcpServer(Environment.GetEnvironmentVariable("MqttServer"), 1883) .WithCredentials(Environment.GetEnvironmentVariable("MqttUsername"), Environment.GetEnvironmentVariable("MqttPassword")) .WithCleanSession() .Build()) .Build(); MqttClient = new MqttFactory().CreateManagedMqttClient(); MqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived; MqttClient.Connected += MqttClient_Connected; Receive <MqttActorMessage.Start>(StartReceived, null); Receive <MqttActorMessage.Subscribe>(SubscribeReceived, null); }
/// <summary> /// Initializes a new instance of the <see cref="MqttService"/> class. /// </summary> /// <param name="defaultTopic">The default topic.</param> /// <param name="logger">The logger.</param> /// <param name="clientOptions">The client options</param> /// <param name="configuration">The configuration</param> /// <param name="services">the service provider</param> /// <exception cref="System.ArgumentNullException"> /// logger /// or /// options /// </exception> public MqttService(string defaultTopic, IMqttClientOptions clientOptions, IServiceProvider services, IConfiguration configuration, ILogger <MqttService> logger) { if (clientOptions is null) { throw new ArgumentNullException(nameof(clientOptions)); } if (services is null) { throw new ArgumentNullException(nameof(services)); } if (configuration is null) { throw new ArgumentNullException(nameof(configuration)); } if (logger is null) { throw new ArgumentNullException(nameof(logger)); } this.Logger = logger; this.services = services; this.DefaultTopic = defaultTopic; var reconnectMilliseconds = configuration.GetValue <int?>("MQTT:ReconnectMilliseconds") ?? 5000; options = new ManagedMqttClientOptionsBuilder() .WithAutoReconnectDelay(TimeSpan.FromMilliseconds(reconnectMilliseconds)) .WithClientOptions(clientOptions ?? throw new ArgumentNullException(nameof(clientOptions))) .Build(); MqttClient = new MqttFactory().CreateManagedMqttClient(); MqttClient.ApplicationMessageReceivedHandler = this; }
private MqttConsumerService <ManagedMqttSettings> CreateMqttConsumerService( Action <ManagedMqttSettings> managedMqttSettingsConfiguration, IManagedMqttClient managedMqttClientOverride = null, IMqttApplicationProvider mqttApplicationProviderOverride = null, IServiceScopeFactory serviceScopeFactoryOverride = null, IManagedMqttClientOptions managedMqttClientOptionsOverride = null ) { var managedMqttSettings = new ManagedMqttSettings(); managedMqttSettingsConfiguration.Invoke(managedMqttSettings); var managedMqttSettingsOptionsWrapper = new OptionsWrapper <ManagedMqttSettings>(managedMqttSettings); return(new MqttConsumerService <ManagedMqttSettings>( managedMqttClientOverride ?? MockManagedMqttClient.Object, mqttApplicationProviderOverride ?? MockMqttApplicationProvider.Object, serviceScopeFactoryOverride ?? MockServiceScopeFactory.Object, managedMqttClientOptionsOverride ?? MockManagedMqttClientOptions.Object, managedMqttSettingsOptionsWrapper, Logger )); }
public MqttListenerService(IManagedMqttClient client, IManagedMqttClientOptions options, IConfiguration configuration, IServiceId serviceId, ILogger <MqttListenerService> logger, IPointsOfSaleService posService, IServiceProvider serviceProvider, IPosTopicClassifier posTopicClassifier) { if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); } if (serviceId == null) { throw new ArgumentNullException(nameof(serviceId)); } _client = client ?? throw new ArgumentNullException(nameof(client)); _options = options ?? throw new ArgumentNullException(nameof(options)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _posService = posService ?? throw new ArgumentNullException(nameof(posService)); _posTopicClassifier = posTopicClassifier ?? throw new ArgumentNullException(nameof(posTopicClassifier)); _client.UseApplicationMessageReceivedHandler(OnMqttMessageReceived); _client.UseConnectedHandler(args => OnConnectedHandler(args)); _client.UseDisconnectedHandler(args => OnDisconnectedHandler(args)); _messageHandlers = serviceProvider.GetServices <IMqttMessageHandler>().ToArray(); }
public MqttConfigExample(string name, IManagedMqttClientOptions options) { Options = options; Name = name; }
public MqttConfigExample(IManagedMqttClientOptions options, IEnumerable <TopicFilter> topics) { Options = options; Topics = topics; }
/// <summary> /// Initializes a new instance of the <see cref="MqttConfiguration"/> class. /// </summary> /// <param name="options">The managed options.</param> /// <param name="topics">The topic filters.</param> public MqttConfiguration(IManagedMqttClientOptions options, IEnumerable <TopicFilter> topics) { Options = options ?? throw new ArgumentNullException(nameof(options)); Topics = topics ?? throw new ArgumentNullException(nameof(topics)); }
public TestMqttConfig(string name, IManagedMqttClientOptions options) { Name = name; Options = options; }
/// <summary> /// 连接服务器 /// </summary> /// <returns></returns> public int Connect() { string caCertPath = @"\certificate\DigiCertGlobalRootCA.crt.pem"; try { string timestamp = DateTime.Now.ToString("yyyyMMddHH"); string clientID = clientConf.DeviceId + "_0_0_" + timestamp; // 对密码进行HmacSHA256加密 string secret = string.Empty; if (!string.IsNullOrEmpty(clientConf.Secret)) { secret = EncryptUtil.HmacSHA256(clientConf.Secret, timestamp); } client = new MqttFactory().CreateManagedMqttClient(); // 判断是否为安全连接 if (clientConf.Port == 1883) { options = new ManagedMqttClientOptionsBuilder() .WithAutoReconnectDelay(TimeSpan.FromSeconds(RECONNECT_TIME)) .WithClientOptions(new MqttClientOptionsBuilder() .WithTcpServer(clientConf.ServerUri, clientConf.Port) .WithCommunicationTimeout(TimeSpan.FromSeconds(DEFAULT_CONNECT_TIMEOUT)) .WithCredentials(clientConf.DeviceId, secret) .WithClientId(clientID) .WithKeepAlivePeriod(TimeSpan.FromSeconds(DEFAULT_KEEPLIVE)) .WithCleanSession(false) .WithProtocolVersion(MqttProtocolVersion.V311) .Build()) .Build(); } else if (clientConf.Port == 8883 && clientConf.DeviceCert == null) { options = new ManagedMqttClientOptionsBuilder() .WithAutoReconnectDelay(TimeSpan.FromSeconds(RECONNECT_TIME)) .WithClientOptions(new MqttClientOptionsBuilder() .WithTcpServer(clientConf.ServerUri, clientConf.Port) .WithCommunicationTimeout(TimeSpan.FromSeconds(DEFAULT_CONNECT_TIMEOUT)) .WithCredentials(clientConf.DeviceId, secret) .WithClientId(clientID) .WithKeepAlivePeriod(TimeSpan.FromSeconds(DEFAULT_KEEPLIVE)) .WithCleanSession(false) .WithTls(new MqttClientOptionsBuilderTlsParameters() { AllowUntrustedCertificates = true, UseTls = true, Certificates = new List <X509Certificate> { IotUtil.GetCert(caCertPath) }, CertificateValidationHandler = delegate { return(true); }, IgnoreCertificateChainErrors = false, IgnoreCertificateRevocationErrors = false }) .WithProtocolVersion(MqttProtocolVersion.V311) .Build()) .Build(); } else { // 证书接入平台 options = new ManagedMqttClientOptionsBuilder() .WithAutoReconnectDelay(TimeSpan.FromSeconds(RECONNECT_TIME)) .WithClientOptions(new MqttClientOptionsBuilder() .WithTcpServer(clientConf.ServerUri, clientConf.Port) .WithCommunicationTimeout(TimeSpan.FromSeconds(DEFAULT_CONNECT_TIMEOUT)) .WithCredentials(clientConf.DeviceId, string.Empty) .WithClientId(clientID) .WithKeepAlivePeriod(TimeSpan.FromSeconds(DEFAULT_KEEPLIVE)) .WithCleanSession(false) .WithTls(new MqttClientOptionsBuilderTlsParameters() { AllowUntrustedCertificates = true, UseTls = true, Certificates = new List <X509Certificate> { IotUtil.GetCert(caCertPath), clientConf.DeviceCert }, CertificateValidationHandler = delegate { return(true); }, IgnoreCertificateChainErrors = false, IgnoreCertificateRevocationErrors = false }) .WithProtocolVersion(MqttProtocolVersion.V311) .Build()) .Build(); } // 注册事件 client.ApplicationMessageProcessedHandler = new ApplicationMessageProcessedHandlerDelegate(new Action <ApplicationMessageProcessedEventArgs>(ApplicationMessageProcessedHandlerMethod)); // 消息发布回调 client.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(new Action <MqttApplicationMessageReceivedEventArgs>(MqttApplicationMessageReceived)); // 命令下发回调 client.ConnectedHandler = new MqttClientConnectedHandlerDelegate(new Action <MqttClientConnectedEventArgs>(OnMqttClientConnected)); client.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(new Action <MqttClientDisconnectedEventArgs>(OnMqttClientDisconnected)); // 连接断开回调 client.ConnectingFailedHandler = new ConnectingFailedHandlerDelegate(new Action <ManagedProcessFailedEventArgs>(OnMqttClientConnectingFailed)); Log.Info("try to connect to server " + clientConf.ServerUri); // 连接平台设备 client.StartAsync(options); mre.WaitOne(); return(client.IsConnected ? 0 : -1); } catch (Exception ex) { Log.Error("SDK.Error: Connect to mqtt server fail, the deviceid is " + clientConf.DeviceId); return(-1); } }
/// <summary> /// Initializes a new instance of the <see cref="MqttConfiguration"/> class. /// </summary> /// <param name="name"></param> /// <param name="options">The managed options.</param> public MqttConfiguration(string name, IManagedMqttClientOptions options) { Name = name; Options = options ?? throw new ArgumentNullException(nameof(options)); }
public MqttClientService(IManagedMqttClientOptions options) { _options = options; _mqttClient = new MqttFactory().CreateManagedMqttClient(); ConfigureMqttClient(); }
private MqttClientHelper(ILogger logger, IManagedMqttClientOptions options) { _logger = logger; _options = options; }
public Task StartAsync(IManagedMqttClientOptions options) => Task.CompletedTask;
public TTNMqttConfiguration(string name, IManagedMqttClientOptions options) { Options = options; Name = name; }
private MqttClientHelper(IManagedMqttClientOptions options) { _options = options; }