Esempio n. 1
0
        private static async Task CheckAndPublishPresenceState()
        {
            var currentIdleState = GetLastUserInput.IsIdle();

            if (currentIdleState != _lastIdleState)
            {
                var haActiveState = new HomeAssistantUserActiveState()
                {
                    State = (!currentIdleState).ToString()
                };

                await _mqttService.Publish(_mqttClient, JsonConvert.SerializeObject(haActiveState), UserActiveTopic);

                _lastIdleState = currentIdleState;
            }
        }
        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;
            }
        }