World.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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. var aa = this.GetDataBlocks();
  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()
  290. {
  291. }
  292. protected virtual void AfterUpdate()
  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 > this.Interval)
  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. OnLog(Ltc.GetChannel(), log);
  321. }
  322. protected internal abstract void OnError(Channel channel, Exception exception);
  323. protected internal abstract void OnInternalLog(Channel channel, string msg);
  324. protected abstract void OnLog(Channel channel, object logObj);
  325. protected abstract IEnumerable<string> GetChannelMsg(Channel channel);
  326. internal void Publish()
  327. {
  328. var channel = Ltc.GetChannel();
  329. var msgs = GetChannelMsg(channel);
  330. var msg = string.Join("\n", msgs);
  331. this.Ex().Publish(channel, msg);
  332. }
  333. }
  334. public interface ILog
  335. {
  336. }
  337. public class WorldEx : EntityEx<World>
  338. {
  339. private RedisClient Redis = new RedisClient(Configs.DebugRedisUrl);
  340. private ConcurrentQueue<string> ChannelList = new ConcurrentQueue<string>();
  341. private DateTime SubTime = DateTime.Now;
  342. public WorldEx(World ent) : base(ent)
  343. {
  344. Redis.Subscribe("Login", (channel, msg) =>
  345. {
  346. ChannelList.Clear();
  347. foreach (var m in msg.ToString().Split(','))
  348. {
  349. ChannelList.Enqueue(m);
  350. }
  351. SubTime = DateTime.Now;
  352. Console.WriteLine($"调试工具正在使用中,已订阅:{msg}");
  353. });
  354. }
  355. public void Publish(Channel channel, string msg)
  356. {
  357. if ((DateTime.Now - SubTime).TotalSeconds > 20)
  358. return;
  359. var flag = false;
  360. flag = ChannelList.Any(v =>
  361. {
  362. var b = Regex.Match(channel.ToString(), $"^{v.Replace("*", ".*")}$");
  363. return b.Success;
  364. });
  365. if (flag)
  366. Redis.Publish(channel.ToString(), msg);
  367. }
  368. }
  369. public class WorkTimes
  370. {
  371. public string Key { get; set; } = "";
  372. public long Total { get; set; }
  373. public List<WorkTimes> Items { get; set; } = new List<WorkTimes>();
  374. public override string ToString()
  375. {
  376. return $"{Key},明细:{Items.Count},耗时:{Total}";
  377. }
  378. public string GetInfo()
  379. {
  380. var str = $"[{ToString()}]";
  381. if (Items.Count > 0) str += $" > {Items.MaxBy(v => v.Total)?.GetInfo()}";
  382. return str;
  383. }
  384. }
  385. public abstract class AttrClass<T> where T : Attribute
  386. {
  387. public T? Attr { get; private set; }
  388. public AttrClass()
  389. {
  390. Attr = GetType().GetCustomAttribute<T>();
  391. }
  392. }
  393. public abstract class DescriptionClass : AttrClass<DescriptionAttribute>
  394. {
  395. public string Description => Attr != null ? Attr.Description : GetType().Name;
  396. }
  397. }