World.cs 15 KB

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