| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462 | using FreeRedis;using System.ComponentModel;using System.Diagnostics;using System.Reflection;using System.Runtime.InteropServices;using System.Text.RegularExpressions;namespace WCS.Core{    /// <summary>    /// 世界用来管理下属System的执行周期,此为默认世界。也可以通过继承此类创建多个不同世界,不同世界的执行周期相互独立,不受其它世界延迟干扰。    /// </summary>    [Description("默认世界")]    public abstract class World : DescriptionClass    {        [DllImport("winmm.dll", EntryPoint = "timeBeginPeriod")]        public static extern uint MM_BeginPeriod(uint uMilliseconds);        [DllImport("winmm.dll", EntryPoint = "timeEndPeriod")]        public static extern uint MM_EndPeriod(uint uMilliseconds);        #region Static        /// <summary>        ///  世界是否启用成功        /// </summary>        public static bool IsStart = false;        private static List<World> _Worlds;        internal static List<World> Worlds        {            get            {                if (_Worlds == null)                {                    _Worlds = new List<World>();                    //_Worlds.Add(new World());//默认世界                    var arr = AppDomain.CurrentDomain.GetAssemblies().Select(v => v.GetTypes()).SelectMany(v => v).Where(v => typeof(World).IsAssignableFrom(v) && v != typeof(World)).Select(v => Activator.CreateInstance(v)).OfType<World>().ToArray();//自定义世界                    _Worlds.AddRange(arr);                }                return _Worlds;            }        }        public static T GetWorldInstance<T>() where T : World        {            return (T)Worlds.Where(v => v.GetType() == typeof(T)).First();        }        public static T GetSystemInstance<T>() where T : SystemBase        {            try            {                return (T)World.Worlds.SelectMany(v => v.Systems).Where(v => v.GetType() == typeof(T)).First();            }            catch (Exception ex)            {                throw new Exception($"系统:{typeof(T).Name}未设置BelongToAttribute");            }        }        public static void StartAll()        {            MM_BeginPeriod(1);            Worlds.ForEach(w => w.Init());            foreach (World w in Worlds)            {                if (w.SystemTypes.Length == 0)                    continue;                w.Start();            }            var arr = Worlds.SelectMany(v => v.SystemGroups).SelectMany(v => v.Value)                .SelectMany(v => v.GetObjects().OfType<EntityEx<Device>>().Select(d => new { Sys = v, Obj = d }))                .GroupBy(v => v.Obj.Entity.Code)                .Select(v => new { Code = v.Key, Systems = v.Select(d => d.Sys.GetType().Name).ToArray(), Worlds = v.Select(d => d.Sys.World.GetType().Name).Distinct().ToArray() })                .Where(v => v.Systems.Length > 1).ToArray();            if (arr.Length > 0)            {                var msgs = arr.Select(v => $"设备{v.Code}同时存在于{v.Systems.Length}个系统:({string.Join(',', v.Systems)}),{v.Worlds.Length}个世界:({string.Join(',', v.Worlds)})中").ToArray();                var str = string.Join('\n', msgs);                Console.ForegroundColor = ConsoleColor.DarkYellow;                Console.WriteLine(str);                Console.ResetColor();            }            IsStart = true;        }        public static void StopAll()        {            MM_EndPeriod(1);            foreach (World w in Worlds)                w.Stop();        }        #endregion Static        #region Dynamic        public bool Stoped;        private Dictionary<Type, int> TypeOrder = new Dictionary<Type, int>();        private Dictionary<int, List<SystemBase>> SystemGroups = new Dictionary<int, List<SystemBase>>();        protected Type[] SystemTypes;        /// <summary>        /// 周期最小间隔时间(毫秒)        /// </summary>        protected abstract int Interval        {            get;        }        public World()        {            SystemTypes = GetSystemTypes();        }        protected virtual Type[] GetSystemTypes()        {            var sysTypes = AppDomain.CurrentDomain.GetAssemblies().Select(v => v.GetTypes()).SelectMany(v => v)                .Where(v => !v.IsAbstract)                .Where(v => typeof(SystemBase).IsAssignableFrom(v))                .Where(v =>                {                    var attr = v.GetCustomAttribute<BelongToAttribute>();                    if (attr == null)                        return GetType() == typeof(World);                    if (attr.WorldType == this.GetType())                        return true;                    return false;                }).ToArray();            return sysTypes;        }        //public List<Device> Devices;        /// <summary>        /// 初始化,实例化世界下的所有系统        /// </summary>        public virtual void Init()        {            try            {                //Devices = Protocols.Generate(this);                foreach (var type in SystemTypes)                {                    var sysDesc = type.GetCustomAttribute<DescriptionAttribute>()?.Description;                    Ltc.SetChannel(new Channel { World = Description, Stage = "Init", System = sysDesc ?? type.Name, Item = "排序" });                    Set(type, 0);                }                var arr = TypeOrder.OrderBy(v => v.Value).Select(v => v.Key).ToArray();                var gs = TypeOrder.GroupBy(v => v.Value).OrderBy(v => v.Key).ToArray();                for (int i = 0; i < gs.Length; i++)                {                    var g = gs[i];                    var list = new List<SystemBase>();                    var sysArr = g.Select(v =>                    {                        var sysDesc = v.Key.GetCustomAttribute<DescriptionAttribute>()?.Description;                        Ltc.SetChannel(new Channel { World = Description, Stage = "Init", System = sysDesc ?? v.Key.Name, Item = "构造" });                        return Activator.CreateInstance(v.Key);                    }).OfType<SystemBase>().ToArray();                    list.AddRange(sysArr);                    SystemGroups.Add(i, list);                }            }            catch (Exception ex)            {                throw;            }            finally            {            }        }        private int Set(Type type, int level)        {            if (!SystemTypes.Contains(type))                throw new Exception($"OrderAttribute设置错误,与目标不属于同一世界。类型:{type}。");            if (level > 10)            {                throw new Exception($"OrderAttribute设置错误,导致死循环。类型:{type}。");            }            var attr = type.GetCustomAttribute<OrderAttribute>();            if (attr != null)            {                level++;                var num = Set(attr.SystemType, level);                TypeOrder[type] = num + (int)attr.Order;            }            else            {                TypeOrder[type] = 0;            }            return TypeOrder[type];        }        /// <summary>        /// 开启世界主循环        /// </summary>        public void Start()        {            Stoped = false;            Task.Run(Loop);//不要使用Thread,可以使用ThreadPool        }        private void Loop()        {            var sw = new Stopwatch();            while (!Stoped)            {                WorkTimes wt = new WorkTimes();                wt.Key = $"{this.Description} 周期:{Interval}";                sw.Restart();                BeforeUpdate();                Update(wt.Items);                AfterUpdate();                sw.Stop();                var workTimes = (int)sw.ElapsedMilliseconds;                var ms = Interval - workTimes;                //sw.Start();                if (ms > 0)                {                    Thread.Sleep(ms);//不要使用Task.Delay().Wait()                }                //sw.Stop();                //var total = sw.ElapsedMilliseconds;                wt.Total = workTimes;                FrameInfo(wt);            }        }        public void Stop()        {            Stoped = true;        }        private void Update(List<WorkTimes> list)        {            var wt = new WorkTimes();            wt.Key = "读取PLC数据";            var sw = new Stopwatch();            sw.Start();            LoadPlcData(wt.Items);            sw.Stop();            wt.Total = sw.ElapsedMilliseconds;            list.AddSafe(wt);            wt = new WorkTimes();            wt.Key = "系统业务";            sw.Restart();            DoLogics(wt.Items);            sw.Stop();            wt.Total = sw.ElapsedMilliseconds;            list.AddSafe(wt);        }        private void LoadPlcData(List<WorkTimes> list)        {            Parallel.ForEach(this.GetDataBlocks(), db =>            {                var channel = new Channel                {                    World = GetType().Name,                    Stage = "LoadPlcData",                    System = "",                    Item = $"{db.Entity.PLCInfo.IP}_{db.Entity.No}"                };                var sw = new Stopwatch();                sw.Start();                try                {                    db.RefreshData();                }                catch (Exception ex)                {                    this.Ex().Publish(channel, ex.GetBaseException().Message);                }                sw.Stop();                list.AddSafe(new WorkTimes { Key = $"{db.Entity.PLCInfo.IP}/{db.Entity.No}", Total = sw.ElapsedMilliseconds });            });        }        private void DoLogics(List<WorkTimes> list)        {            foreach (var group in SystemGroups)            {                var wt = new WorkTimes();                wt.Key = $"组{group.Key}";                var sw = new Stopwatch();                sw.Restart();                Parallel.ForEach(group.Value, sys =>                {                    var wt2 = new WorkTimes();                    wt2.Key = sys.Description;                    var sw2 = new Stopwatch();                    sw2.Start();                    try                    {                        sys.Update(wt2.Items);                    }                    catch (Exception ex)                    {                        Console.ForegroundColor = ConsoleColor.Red;                        Console.WriteLine(ex.GetBaseException().Message);                        Console.ResetColor();                    }                    sw2.Stop();                    wt2.Total = sw2.ElapsedMilliseconds;                    list.AddSafe(wt2);                });                sw.Stop();                wt.Total = sw.ElapsedMilliseconds;                //list.AddSafe(wt);            }        }        protected virtual void BeforeUpdate()        {        }        protected virtual void AfterUpdate()        {        }        #endregion Dynamic        public T GetSystem<T>() where T : SystemBase        {            var sys = Systems.Where(v => v.GetType() == typeof(T)).FirstOrDefault() as T;            if (sys == null)                throw new Exception($"世界{GetType().Name}中不存在系统{typeof(T).Name}");            return sys;        }        public SystemBase[] Systems        {            get            {                return SystemGroups.SelectMany(v => v.Value).ToArray();            }        }        protected virtual void FrameInfo(WorkTimes wt)        {            if (wt.Total > this.Interval)            {                Console.ForegroundColor = ConsoleColor.Red;            }            Console.WriteLine(wt.GetInfo());            Console.ResetColor();        }        public void Log<T>(T log) where T : ILog        {            OnLog(Ltc.GetChannel(), log);        }        protected internal abstract void OnError(Channel channel, Exception exception);        protected internal abstract void OnInternalLog(Channel channel, string msg);        protected abstract void OnLog(Channel channel, object logObj);        protected abstract IEnumerable<string> GetChannelMsg(Channel channel);        internal void Publish()        {            var channel = Ltc.GetChannel();            var msgs = GetChannelMsg(channel);            var msg = string.Join("\n", msgs);            this.Ex().Publish(channel, msg);        }    }    public interface ILog    {    }    public class WorldEx : EntityEx<World>    {        private RedisClient Redis = new RedisClient(Configs.DebugRedisUrl);        private List<string> ChannelList = new List<string>();        private DateTime SubTime = DateTime.Now;        public WorldEx(World ent) : base(ent)        {            Redis.Subscribe("Login", (channel, msg) =>            {                lock (ChannelList)                {                    ChannelList.Clear();                    ChannelList.AddSafe(msg.ToString().Split(','));                }                SubTime = DateTime.Now;                Console.WriteLine($"调试工具正在使用中,已订阅:{msg}");            });        }        public void Publish(Channel channel, string msg)        {            if ((DateTime.Now - SubTime).TotalSeconds > 20)                return;            var flag = false;            lock (ChannelList)            {                flag = ChannelList.Any(v =>                {                    var b = Regex.Match(channel.ToString(), $"^{v.Replace("*", ".*")}$");                    return b.Success;                });            }            if (flag)                Redis.Publish(channel.ToString(), msg);        }    }    public class WorkTimes    {        public string Key { get; set; } = "";        public long Total { get; set; }        public List<WorkTimes> Items { get; set; } = new List<WorkTimes>();        public override string ToString()        {            return $"{Key},明细:{Items.Count},耗时:{Total}";        }        public string GetInfo()        {            var str = $"[{ToString()}]";            if (Items.Count > 0)                str += $" > {Items.OrderBy(v => v.Total).LastOrDefault()?.GetInfo()}";            return str;        }    }    public abstract class AttrClass<T> where T : Attribute    {        public T? Attr { get; private set; }        public AttrClass()        {            Attr = GetType().GetCustomAttribute<T>();        }    }    public abstract class DescriptionClass : AttrClass<DescriptionAttribute>    {        public string Description        {            get            {                if (Attr != null)                    return Attr.Description;                else                    return GetType().Name;            }        }    }}
 |