using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Newtonsoft.Json; using TeamAAS.Communication.Interfaces; namespace TeamAAS.Communication.Base { public class DebugLogEntry { [JsonIgnore] public DateTime Time { get; set; } [JsonIgnore] public string Message { get; set; } public override string ToString() => $"[{Time:HH:mm:ss}] {Message}"; } [Serializable] /// /// 通讯设备基类:提供 INotifyPropertyChanged + SetProperty + Id/Index/Name/TypeKey 默认实现。 /// 设备实例本身就是配置对象(PropertyGrid 直接绑定),不再需要 Info 子类。 /// public abstract class BindableCommunicationBase : ICommunication, INotifyPropertyChanged { [field:NonSerialized] public event PropertyChangedEventHandler PropertyChanged; private Guid _id = Guid.NewGuid(); [Browsable(false)] public Guid Id { get { return _id; } set { SetProperty(ref _id, value); } } private int _index; [Browsable(false)] public int Index { get { return _index; } set { SetProperty(ref _index, value); } } private string _name; [Category("I.基础配置"), DisplayName("1.设备名称"), Description("设置设备名称")] public string Name { get { return _name; } set { SetProperty(ref _name, value); } } [Browsable(false)] public virtual string TypeKey => GetType().FullName; [Browsable(false)] public abstract string EndpointUrl { get; set; } [Category("I.基础配置"), DisplayName("2.是否已连接"), Description("是否已连接")] [ReadOnly(true)] public abstract bool IsConnected { get; } public abstract event Action ConnectChangedEvent; public abstract event Action DataReceivedEvent; [JsonIgnore, Browsable(false)] public ObservableCollection DebugLog { get; } = new ObservableCollection(); public void AppendLog(string message) { DebugLog.Add(new DebugLogEntry { Time = DateTime.Now, Message = message }); while (DebugLog.Count > 50) DebugLog.RemoveAt(0); } public abstract void Connect(); public abstract System.Threading.Tasks.Task ConnectAsync(); public abstract void Disconnect(); public abstract object ReadValue(string address); public abstract System.Threading.Tasks.Task ReadValueAsync(string address); public abstract void WriteValue(string address, object value); public abstract System.Threading.Tasks.Task WriteValueAsync(string address, object value); public abstract void Dispose(); protected bool SetProperty(ref T field, T value, [CallerMemberName] string propertyName = null) { if (Equals(field, value)) return false; field = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); return true; } protected void Notify([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }