World.cs 15 KB

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