using System; using System.Collections.Generic; using Newtonsoft.Json; using PepperDash.Core; using PepperDash.Core.Logging; using PepperDash.Essentials.Core.DeviceTypeInterfaces; namespace PepperDash.Essentials.AppServer.Messengers { /// /// Represents a ISelectableItemsMessenger /// public class ISelectableItemsMessenger : MessengerBase { private readonly ISelectableItems itemDevice; private readonly string _propName; private List _itemKeys = new List(); /// /// Constructs a messenger for a device that implements ISelectableItems /// /// /// /// /// public ISelectableItemsMessenger(string key, string messagePath, ISelectableItems device, string propName) : base(key, messagePath, device as IKeyName) { itemDevice = device; _propName = propName; } protected override void RegisterActions() { base.RegisterActions(); AddAction("/fullStatus", (id, context) => SendFullStatus(id) ); AddAction("/itemsStatus", (id, content) => SendFullStatus(id)); AddAction("/selectItem", (id, content) => { try { var key = content.ToObject(); if (key == null) { this.LogError("No key specified to select"); return; } if (itemDevice.Items.ContainsKey((TKey)Convert.ChangeType(key, typeof(TKey)))) { itemDevice.Items[(TKey)Convert.ChangeType(key, typeof(TKey))].Select(); } else { this.LogError("Key {0} not found in items", key); } } catch (Exception e) { this.LogError("Error selecting item: {0}", e.Message); } }); itemDevice.ItemsUpdated += (sender, args) => { SetItems(); }; itemDevice.CurrentItemChanged += (sender, args) => { SendFullStatus(); }; SetItems(); } /// /// Sets the items and registers their update events /// private void SetItems() { if (_itemKeys != null && _itemKeys.Count > 0) { /// Clear out any existing item actions foreach (var item in _itemKeys) { RemoveAction($"/{item}"); } _itemKeys.Clear(); } foreach (var item in itemDevice.Items) { var key = item.Key; var localItem = item.Value; AddAction($"/{key}", (id, content) => { localItem.Select(); }); _itemKeys.Add(key.ToString()); localItem.ItemUpdated -= LocalItem_ItemUpdated; localItem.ItemUpdated += LocalItem_ItemUpdated; } } private void LocalItem_ItemUpdated(object sender, EventArgs e) { SendFullStatus(); } private void SendFullStatus(string id = null) { try { this.LogInformation("Sending full status"); var stateObject = new ISelectableItemsStateMessage { Items = itemDevice.Items, CurrentItem = itemDevice.CurrentItem }; PostStatusMessage(stateObject, id); } catch (Exception e) { this.LogError("Error sending full status: {0}", e.Message); } } } /// /// Represents a ISelectableItemsStateMessage /// public class ISelectableItemsStateMessage : DeviceStateMessageBase { /// /// Gets or sets the Items /// [JsonProperty("items")] public Dictionary Items { get; set; } /// /// Gets or sets the CurrentItem /// [JsonProperty("currentItem")] public TKey CurrentItem { get; set; } } }