World.cs 15 KB

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