World.cs 14 KB

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