World.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. using System.Collections.Concurrent;
  2. using System.ComponentModel;
  3. using System.Diagnostics;
  4. using System.Reflection;
  5. using System.Runtime.InteropServices;
  6. using System.Text.RegularExpressions;
  7. using FreeRedis;
  8. namespace WCS.Core;
  9. /// <summary>
  10. /// 世界用来管理下属System的执行周期,此为默认世界。也可以通过继承此类创建多个不同世界,不同世界的执行周期相互独立,不受其它世界延迟干扰。
  11. /// </summary>
  12. [Description("默认世界")]
  13. public abstract class World : DescriptionClass
  14. {
  15. public SystemBase[] Systems
  16. {
  17. get { return SystemGroups.SelectMany(v => v.Value).ToArray(); }
  18. }
  19. [DllImport("winmm.dll", EntryPoint = "timeBeginPeriod")]
  20. public static extern uint MM_BeginPeriod(uint uMilliseconds);
  21. [DllImport("winmm.dll", EntryPoint = "timeEndPeriod")]
  22. public static extern uint MM_EndPeriod(uint uMilliseconds);
  23. public T GetSystem<T>() where T : SystemBase
  24. {
  25. var sys = Systems.FirstOrDefault(v => v.GetType() == typeof(T)) as T;
  26. if (sys == null) throw new Exception($"世界{GetType().Name}中不存在系统{typeof(T).Name}");
  27. return sys;
  28. }
  29. protected virtual void FrameInfo(WorkTimes wt)
  30. {
  31. if (wt.Total > Interval) Console.ForegroundColor = ConsoleColor.Red;
  32. Console.WriteLine(wt.GetInfo());
  33. Console.ResetColor();
  34. }
  35. public void Log<T>(T log) where T : ILog
  36. {
  37. var channel = Ltc.GetChannel();
  38. if (channel != null)
  39. OnLog(Ltc.GetChannel(), log);
  40. }
  41. protected internal abstract void OnError(Channel channel, Exception exception);
  42. protected internal abstract void OnInternalLog(Channel channel, string msg);
  43. protected abstract void OnLog(Channel channel, object logObj);
  44. protected abstract IEnumerable<string> GetChannelMsg(Channel channel);
  45. internal void Publish()
  46. {
  47. var channel = Ltc.GetChannel();
  48. if (channel != null)
  49. {
  50. var msgs = GetChannelMsg(channel);
  51. var msg = string.Join("\n", msgs);
  52. this.Ex().Publish(channel, msg);
  53. }
  54. }
  55. #region Static
  56. /// <summary>
  57. /// 世界是否启用成功
  58. /// </summary>
  59. public static bool IsStart;
  60. private static List<World> _Worlds;
  61. internal static List<World> Worlds
  62. {
  63. get
  64. {
  65. if (_Worlds == null)
  66. {
  67. _Worlds = new List<World>();
  68. //_Worlds.Add(new World());//默认世界
  69. var arr = AppDomain.CurrentDomain.GetAssemblies().Select(v => v.GetTypes()).SelectMany(v => v)
  70. .Where(v => typeof(World).IsAssignableFrom(v) && v != typeof(World))
  71. .Select(v => Activator.CreateInstance(v)).OfType<World>().ToArray(); //自定义世界
  72. _Worlds.AddRange(arr);
  73. }
  74. return _Worlds;
  75. }
  76. }
  77. public static T GetWorldInstance<T>() where T : World
  78. {
  79. return (T)Worlds.First(v => v.GetType() == typeof(T));
  80. }
  81. public static T GetSystemInstance<T>() where T : SystemBase
  82. {
  83. try
  84. {
  85. return (T)Worlds.SelectMany(v => v.Systems).First(v => v.GetType() == typeof(T));
  86. }
  87. catch (Exception ex)
  88. {
  89. throw new Exception($"系统:{typeof(T).Name}未设置BelongToAttribute");
  90. }
  91. }
  92. public static void StartAll()
  93. {
  94. MM_BeginPeriod(1);
  95. Worlds.ForEach(w => w.Init());
  96. foreach (var w in Worlds)
  97. {
  98. if (w.SystemTypes.Length == 0) continue;
  99. w.Start();
  100. }
  101. var arr = Worlds.SelectMany(v => v.SystemGroups).SelectMany(v => v.Value)
  102. .SelectMany(v => v.GetObjects().OfType<EntityEx<Device>>().Select(d => new { Sys = v, Obj = d }))
  103. .GroupBy(v => v.Obj.Entity.Code)
  104. .Select(v => new
  105. {
  106. Code = v.Key, Systems = v.Select(d => d.Sys.GetType().Name).ToArray(),
  107. Worlds = v.Select(d => d.Sys.World.GetType().Name).Distinct().ToArray()
  108. })
  109. .Where(v => v.Systems.Length > 1).ToArray();
  110. if (arr.Length > 0)
  111. {
  112. var msgs = arr.Select(v =>
  113. $"设备{v.Code}同时存在于{v.Systems.Length}个系统:({string.Join(',', v.Systems)}),{v.Worlds.Length}个世界:({string.Join(',', v.Worlds)})中")
  114. .ToArray();
  115. var str = string.Join('\n', msgs);
  116. Console.ForegroundColor = ConsoleColor.DarkYellow;
  117. Console.WriteLine(str);
  118. Console.ResetColor();
  119. }
  120. IsStart = true;
  121. }
  122. public static void StopAll()
  123. {
  124. MM_EndPeriod(1);
  125. foreach (var w in Worlds) w.Stop();
  126. }
  127. #endregion Static
  128. #region Dynamic
  129. public bool Stoped;
  130. private readonly Dictionary<Type, int> TypeOrder = new();
  131. private readonly Dictionary<int, List<SystemBase>> SystemGroups = new();
  132. protected Type[] SystemTypes;
  133. /// <summary>
  134. /// 周期最小间隔时间(毫秒)
  135. /// </summary>
  136. protected abstract int Interval { get; }
  137. public DateTime Frame { get; private set; }
  138. public World()
  139. {
  140. SystemTypes = GetSystemTypes();
  141. }
  142. protected virtual Type[] GetSystemTypes()
  143. {
  144. var sysTypes = AppDomain.CurrentDomain.GetAssemblies().Select(v => v.GetTypes()).SelectMany(v => v)
  145. .Where(v => !v.IsAbstract)
  146. .Where(v => typeof(SystemBase).IsAssignableFrom(v))
  147. .Where(v =>
  148. {
  149. var attr = v.GetCustomAttribute<BelongToAttribute>();
  150. if (attr == null) return GetType() == typeof(World);
  151. if (attr.WorldType == GetType()) return true;
  152. return false;
  153. }).ToArray();
  154. return sysTypes;
  155. }
  156. //public List<Device> Devices;
  157. /// <summary>
  158. /// 初始化,实例化世界下的所有系统
  159. /// </summary>
  160. public virtual void Init()
  161. {
  162. //Devices = Protocols.Generate(this);
  163. foreach (var type in SystemTypes)
  164. {
  165. var sysDesc = type.GetCustomAttribute<DescriptionAttribute>()?.Description;
  166. Ltc.SetChannel(new Channel
  167. { World = Description, Stage = "Init", System = sysDesc ?? type.Name, Item = "排序" });
  168. Set(type, 0);
  169. }
  170. var arr = TypeOrder.OrderBy(v => v.Value).Select(v => v.Key).ToArray();
  171. var gs = TypeOrder.GroupBy(v => v.Value).OrderBy(v => v.Key).ToArray();
  172. for (var i = 0; i < gs.Length; i++)
  173. {
  174. var g = gs[i];
  175. var list = new List<SystemBase>();
  176. var sysArr = g.Select(v =>
  177. {
  178. var sysDesc = v.Key.GetCustomAttribute<DescriptionAttribute>()?.Description;
  179. Ltc.SetChannel(new Channel
  180. { World = Description, Stage = "Init", System = sysDesc ?? v.Key.Name, Item = "构造" });
  181. return Activator.CreateInstance(v.Key);
  182. }).OfType<SystemBase>().ToArray();
  183. list.AddRange(sysArr);
  184. SystemGroups.Add(i, list);
  185. }
  186. }
  187. private int Set(Type type, int level)
  188. {
  189. if (!SystemTypes.Contains(type))
  190. throw new Exception($"OrderAttribute设置错误,与目标不属于同一世界。类型:{type}。");
  191. if (level > 10) throw new Exception($"OrderAttribute设置错误,导致死循环。类型:{type}。");
  192. var attr = type.GetCustomAttribute<OrderAttribute>();
  193. if (attr != null)
  194. {
  195. level++;
  196. var num = Set(attr.SystemType, level);
  197. TypeOrder[type] = num + (int)attr.Order;
  198. }
  199. else
  200. {
  201. TypeOrder[type] = 0;
  202. }
  203. return TypeOrder[type];
  204. }
  205. /// <summary>
  206. /// 开启世界主循环
  207. /// </summary>
  208. public void Start()
  209. {
  210. Stoped = false;
  211. Task.Run(Loop); //不要使用Thread,可以使用ThreadPool
  212. }
  213. private void Loop()
  214. {
  215. var sw = new Stopwatch();
  216. while (!Stoped)
  217. {
  218. Frame = DateTime.Now;
  219. var wt = new WorkTimes();
  220. wt.Key = $"{Description} 周期:{Interval}";
  221. sw.Restart();
  222. try
  223. {
  224. BeforeUpdate(wt.Items);
  225. Update(wt.Items);
  226. AfterUpdate(wt.Items);
  227. }
  228. catch (Exception ex)
  229. {
  230. Console.WriteLine(ex);
  231. }
  232. sw.Stop();
  233. var workTimes = (int)sw.ElapsedMilliseconds;
  234. var ms = Interval - workTimes;
  235. //sw.Start();
  236. if (ms > 0) Thread.Sleep(ms); //不要使用Task.Delay().Wait()
  237. //sw.Stop();
  238. //var total = sw.ElapsedMilliseconds;
  239. wt.Total = workTimes;
  240. FrameInfo(wt);
  241. }
  242. }
  243. public void Stop()
  244. {
  245. Stoped = true;
  246. }
  247. private void Update(List<WorkTimes> list)
  248. {
  249. var wt = new WorkTimes();
  250. wt.Key = "读取PLC数据";
  251. var sw = new Stopwatch();
  252. sw.Start();
  253. LoadPlcData(wt.Items);
  254. sw.Stop();
  255. wt.Total = sw.ElapsedMilliseconds;
  256. list.AddSafe(wt);
  257. wt = new WorkTimes();
  258. wt.Key = "系统业务";
  259. sw.Restart();
  260. DoLogics(wt.Items);
  261. sw.Stop();
  262. wt.Total = sw.ElapsedMilliseconds;
  263. list.AddSafe(wt);
  264. }
  265. private void LoadPlcData(List<WorkTimes> list)
  266. {
  267. Parallel.ForEach(this.GetDataBlocks(), db =>
  268. {
  269. var channel = new Channel
  270. {
  271. World = GetType().Name,
  272. Stage = "LoadPlcData",
  273. System = "",
  274. Item = $"{db.Entity.PLCInfo.IP}_{db.Entity.No}"
  275. };
  276. var sw = new Stopwatch();
  277. sw.Start();
  278. try
  279. {
  280. db.RefreshData();
  281. }
  282. catch (Exception ex)
  283. {
  284. this.Ex().Publish(channel, ex.GetBaseException().Message);
  285. }
  286. sw.Stop();
  287. list.AddSafe(new WorkTimes
  288. { Key = $"{db.Entity.PLCInfo.IP}/{db.Entity.No}", Total = sw.ElapsedMilliseconds });
  289. });
  290. }
  291. private void DoLogics(List<WorkTimes> list)
  292. {
  293. foreach (var group in SystemGroups)
  294. {
  295. var wt = new WorkTimes();
  296. wt.Key = $"组{group.Key}";
  297. var sw = new Stopwatch();
  298. sw.Restart();
  299. Parallel.ForEach(group.Value, sys =>
  300. {
  301. var wt2 = new WorkTimes();
  302. wt2.Key = sys.Description;
  303. var sw2 = new Stopwatch();
  304. sw2.Start();
  305. try
  306. {
  307. sys.Update(wt2.Items);
  308. }
  309. catch (Exception ex)
  310. {
  311. Console.ForegroundColor = ConsoleColor.Red;
  312. Console.WriteLine(ex.GetBaseException().Message);
  313. Console.ResetColor();
  314. }
  315. sw2.Stop();
  316. wt2.Total = sw2.ElapsedMilliseconds;
  317. list.AddSafe(wt2);
  318. });
  319. sw.Stop();
  320. wt.Total = sw.ElapsedMilliseconds;
  321. //list.AddSafe(wt);
  322. }
  323. }
  324. protected virtual void BeforeUpdate(List<WorkTimes> list)
  325. {
  326. }
  327. protected virtual void AfterUpdate(List<WorkTimes> list)
  328. {
  329. }
  330. #endregion Dynamic
  331. }
  332. public interface ILog
  333. {
  334. }
  335. public class WorldEx : EntityEx<World>
  336. {
  337. private readonly ConcurrentQueue<string> ChannelList = new();
  338. private readonly RedisClient Redis = new(Configs.DebugRedisUrl);
  339. private DateTime SubTime = DateTime.Now;
  340. public WorldEx(World ent) : base(ent)
  341. {
  342. return;
  343. Redis.Subscribe("Login", (channel, msg) =>
  344. {
  345. ChannelList.Clear();
  346. foreach (var m in msg.ToString().Split(',')) ChannelList.Enqueue(m);
  347. SubTime = DateTime.Now;
  348. Console.WriteLine($"调试工具正在使用中,已订阅:{msg}");
  349. });
  350. }
  351. public void Publish(Channel channel, string msg)
  352. {
  353. if ((DateTime.Now - SubTime).TotalSeconds > 20)
  354. return;
  355. var flag = false;
  356. flag = ChannelList.Any(v =>
  357. {
  358. var b = Regex.Match(channel.ToString(), $"^{v.Replace("*", ".*")}$");
  359. return b.Success;
  360. });
  361. if (flag)
  362. Redis.Publish(channel.ToString(), msg);
  363. }
  364. }
  365. public class WorkTimes
  366. {
  367. public string Key { get; set; } = "";
  368. public long Total { get; set; }
  369. public List<WorkTimes> Items { get; set; } = new();
  370. public override string ToString()
  371. {
  372. return $"{Key},明细:{Items.Count},耗时:{Total}";
  373. }
  374. public string GetInfo()
  375. {
  376. var str = $"[{ToString()}]";
  377. if (Items.Count > 0) str += $" > {Items.MaxBy(v => v.Total)?.GetInfo()}";
  378. return str;
  379. }
  380. }
  381. public abstract class AttrClass<T> where T : Attribute
  382. {
  383. public AttrClass()
  384. {
  385. Attr = GetType().GetCustomAttribute<T>();
  386. }
  387. public T? Attr { get; }
  388. }
  389. public abstract class DescriptionClass : AttrClass<DescriptionAttribute>
  390. {
  391. public string Description => Attr != null ? Attr.Description : GetType().Name;
  392. }