World.cs 15 KB

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