private static async Task ReconnectWhenDisconnected() { if (_mqttClient == null || !_mqttClient.IsConnected) { _mqttClient = await _mqttService.Connect(); } }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { try { _logger.LogInformation("Worker started at: {time}", DateTimeOffset.Now); var message = $"{Environment.MachineName}/idleStatus"; IMqttClient mqttClient = await _mqttService.Connect(); while (!stoppingToken.IsCancellationRequested) { if (!mqttClient.IsConnected) { mqttClient = await _mqttService.Connect(); } var topic = GetLastUserInput.IsIdle().ToString(); await _mqttService.Publish(mqttClient, topic, message); await Task.Delay(10000, stoppingToken); } await mqttClient.DisconnectAsync(); _logger.LogInformation("Worker stopped at {time}", DateTimeOffset.Now); } catch (Exception e) { _logger.LogError(e.Message); if (e.InnerException != null) { _logger.LogError(e.InnerException.Message); } throw; } }
public async Task Connect(string device, string password) { _deviceState.DeviceId = device; _deviceState.Password = password; await _mqttService.Connect(device, password); }