using System; using System.Collections.Generic; using System.Text; using System.Text.Json; using System.Timers; using Telegram.Bot; using ZaoBot.Config; namespace ZaoBot.Problems { class StatusManager { const int DEFAULT_INTERVAL = 2000; private OpenHab.OpenHabClient openhab; private ITelegramBotClient bot; private JsonDocument config; private Timer timer; private Dictionary statusItems = new Dictionary(); public IEnumerable StatusItems => statusItems.Values; public StatusManager(OpenHab.OpenHabClient openhab, ITelegramBotClient bot, IConfig config) { this.bot = bot; this.openhab = openhab; this.config = config.Data; UpdateStatus(); timer = new Timer(DEFAULT_INTERVAL); timer.Elapsed += OnTimer; timer.Enabled = true; } private void OnTimer(object sender, ElapsedEventArgs e) { UpdateStatus(); } private async void UpdateStatus() { try { var items = await openhab.GetItems(); foreach (var item in items) { if (!item.name.StartsWith("Problem_")) continue; Item statusItem = null; lock (statusItems) { if (statusItems.ContainsKey(item.name)) statusItem = statusItems[item.name]; else { statusItem = new Item() { name = item.name, label = item.label, status = Status.UNKNOWN }; statusItems[item.name] = statusItem; } } var state = await openhab.GetItemState(item.name); lock (statusItems) { if (state.state == "OFF") statusItem.status = Status.OK; else if (state.state == "ON") statusItem.status = Status.PROBLEM; else statusItem.status = Status.UNKNOWN; if (statusItem.status == Status.PROBLEM && statusItem.notified == false) { Notify(statusItem); statusItem.notified = true; } } } } catch (Exception ex) { Console.WriteLine("Exception on getting status: " + ex.ToString()); } } private async void Notify(Item item) { foreach (var element in config.RootElement.GetProperty("notify_user_ids").EnumerateArray()) { await bot.SendTextMessageAsync( chatId: element.GetString(), text: "Problem appeared: " + item.label ); } } } }