World.cs 16 KB

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