World.cs 14 KB

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