World.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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(wt.Items);
  194. Update(wt.Items);
  195. AfterUpdate(wt.Items);
  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. Parallel.ForEach(this.GetDataBlocks(), db =>
  235. {
  236. var channel = new Channel
  237. {
  238. World = GetType().Name,
  239. Stage = "LoadPlcData",
  240. System = "",
  241. Item = $"{db.Entity.PLCInfo.IP}_{db.Entity.No}"
  242. };
  243. var sw = new Stopwatch();
  244. sw.Start();
  245. try
  246. {
  247. db.RefreshData();
  248. }
  249. catch (Exception ex)
  250. {
  251. this.Ex().Publish(channel, ex.GetBaseException().Message);
  252. }
  253. sw.Stop();
  254. list.AddSafe(new WorkTimes { Key = $"{db.Entity.PLCInfo.IP}/{db.Entity.No}", Total = sw.ElapsedMilliseconds });
  255. });
  256. }
  257. private void DoLogics(List<WorkTimes> list)
  258. {
  259. foreach (var group in SystemGroups)
  260. {
  261. var wt = new WorkTimes();
  262. wt.Key = $"组{group.Key}";
  263. var sw = new Stopwatch();
  264. sw.Restart();
  265. Parallel.ForEach(group.Value, sys =>
  266. {
  267. var wt2 = new WorkTimes();
  268. wt2.Key = sys.Description;
  269. var sw2 = new Stopwatch();
  270. sw2.Start();
  271. try
  272. {
  273. sys.Update(wt2.Items);
  274. }
  275. catch (Exception ex)
  276. {
  277. Console.ForegroundColor = ConsoleColor.Red;
  278. Console.WriteLine(ex.GetBaseException().Message);
  279. Console.ResetColor();
  280. }
  281. sw2.Stop();
  282. wt2.Total = sw2.ElapsedMilliseconds;
  283. list.AddSafe(wt2);
  284. });
  285. sw.Stop();
  286. wt.Total = sw.ElapsedMilliseconds;
  287. //list.AddSafe(wt);
  288. }
  289. }
  290. protected virtual void BeforeUpdate(List<WorkTimes> list)
  291. {
  292. }
  293. protected virtual void AfterUpdate(List<WorkTimes> list)
  294. {
  295. }
  296. #endregion Dynamic
  297. public T GetSystem<T>() where T : SystemBase
  298. {
  299. var sys = Systems.FirstOrDefault(v => v.GetType() == typeof(T)) as T;
  300. if (sys == null) throw new Exception($"世界{GetType().Name}中不存在系统{typeof(T).Name}");
  301. return sys;
  302. }
  303. public SystemBase[] Systems
  304. {
  305. get
  306. {
  307. return SystemGroups.SelectMany(v => v.Value).ToArray();
  308. }
  309. }
  310. protected virtual void FrameInfo(WorkTimes wt)
  311. {
  312. if (wt.Total > this.Interval)
  313. {
  314. Console.ForegroundColor = ConsoleColor.Red;
  315. }
  316. Console.WriteLine(wt.GetInfo());
  317. Console.ResetColor();
  318. }
  319. public void Log<T>(T log) where T : ILog
  320. {
  321. var channel = Ltc.GetChannel();
  322. if (channel != null)
  323. OnLog(Ltc.GetChannel(), log);
  324. }
  325. protected internal abstract void OnError(Channel channel, Exception exception);
  326. protected internal abstract void OnInternalLog(Channel channel, string msg);
  327. protected abstract void OnLog(Channel channel, object logObj);
  328. protected abstract IEnumerable<string> GetChannelMsg(Channel channel);
  329. internal void Publish()
  330. {
  331. var channel = Ltc.GetChannel();
  332. if (channel != null)
  333. {
  334. var msgs = GetChannelMsg(channel);
  335. var msg = string.Join("\n", msgs);
  336. this.Ex().Publish(channel, msg);
  337. }
  338. }
  339. }
  340. public interface ILog
  341. {
  342. }
  343. public class WorldEx : EntityEx<World>
  344. {
  345. private RedisClient Redis = new RedisClient(Configs.DebugRedisUrl);
  346. private ConcurrentQueue<string> ChannelList = new ConcurrentQueue<string>();
  347. private DateTime SubTime = DateTime.Now;
  348. public WorldEx(World ent) : base(ent)
  349. {
  350. Redis.Subscribe("Login", (channel, msg) =>
  351. {
  352. ChannelList.Clear();
  353. foreach (var m in msg.ToString().Split(','))
  354. {
  355. ChannelList.Enqueue(m);
  356. }
  357. SubTime = DateTime.Now;
  358. Console.WriteLine($"调试工具正在使用中,已订阅:{msg}");
  359. });
  360. }
  361. public void Publish(Channel channel, string msg)
  362. {
  363. if ((DateTime.Now - SubTime).TotalSeconds > 20)
  364. return;
  365. var flag = false;
  366. flag = ChannelList.Any(v =>
  367. {
  368. var b = Regex.Match(channel.ToString(), $"^{v.Replace("*", ".*")}$");
  369. return b.Success;
  370. });
  371. if (flag)
  372. Redis.Publish(channel.ToString(), msg);
  373. }
  374. }
  375. public class WorkTimes
  376. {
  377. public string Key { get; set; } = "";
  378. public long Total { get; set; }
  379. public List<WorkTimes> Items { get; set; } = new List<WorkTimes>();
  380. public override string ToString()
  381. {
  382. return $"{Key},明细:{Items.Count},耗时:{Total}";
  383. }
  384. public string GetInfo()
  385. {
  386. var str = $"[{ToString()}]";
  387. if (Items.Count > 0) str += $" > {Items.MaxBy(v => v.Total)?.GetInfo()}";
  388. return str;
  389. }
  390. }
  391. public abstract class AttrClass<T> where T : Attribute
  392. {
  393. public T? Attr { get; private set; }
  394. public AttrClass()
  395. {
  396. Attr = GetType().GetCustomAttribute<T>();
  397. }
  398. }
  399. public abstract class DescriptionClass : AttrClass<DescriptionAttribute>
  400. {
  401. public string Description => Attr != null ? Attr.Description : GetType().Name;
  402. }
  403. }