World.cs 14 KB

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