World.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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 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 int Interval = 800;
  83. public World()
  84. {
  85. SystemTypes = GetSystemTypes();
  86. }
  87. protected virtual Type[] GetSystemTypes()
  88. {
  89. var sysTypes = Assembly.GetEntryAssembly().GetTypes()
  90. .Where(v => !v.IsAbstract)
  91. .Where(v => typeof(SystemBase).IsAssignableFrom(v))
  92. .Where(v =>
  93. {
  94. var attr = v.GetCustomAttribute<BelongToAttribute>();
  95. if (attr == null)
  96. return GetType() == typeof(World);
  97. if (attr.WorldType == this.GetType())
  98. return true;
  99. return false;
  100. }).ToArray();
  101. return sysTypes;
  102. }
  103. public List<Device> Devices;
  104. /// <summary>
  105. /// 初始化,实例化世界下的所有系统
  106. /// </summary>
  107. public virtual void Init()
  108. {
  109. Ltc.SetChannel(new Channel { World = Description, Item = "初始化" });
  110. Ltc.ClearChannel();
  111. try
  112. {
  113. Devices = Protocols.Generate(this);
  114. foreach (var type in SystemTypes)
  115. {
  116. Set(type, 0);
  117. }
  118. var arr = TypeOrder.OrderBy(v => v.Value).Select(v => v.Key).ToArray();
  119. var gs = TypeOrder.GroupBy(v => v.Value).OrderBy(v => v.Key).ToArray();
  120. for (int i = 0; i < gs.Length; i++)
  121. {
  122. var g = gs[i];
  123. var list = new List<SystemBase>();
  124. var sysArr = g.Select(v => Activator.CreateInstance(v.Key)).OfType<SystemBase>().ToArray();
  125. list.AddRange(sysArr);
  126. SystemGroups.Add(i, list);
  127. }
  128. }
  129. catch (Exception ex)
  130. {
  131. Ltc.Log(ex.GetBaseException().Message, LogLevel.高, ErrorType.未知);
  132. throw;
  133. }
  134. finally
  135. {
  136. Configs.OnLog?.Invoke(Ltc.GetLogInfo());
  137. }
  138. }
  139. int Set(Type type,int level)
  140. {
  141. if (!SystemTypes.Contains(type))
  142. throw new Exception($"OrderAttribute设置错误,与目标不属于同一世界。类型:{type}。");
  143. if (level > 10)
  144. {
  145. throw new Exception($"OrderAttribute设置错误,导致死循环。类型:{type}。");
  146. }
  147. var attr = type.GetCustomAttribute<OrderAttribute>();
  148. if (attr != null)
  149. {
  150. level++;
  151. var num = Set(attr.SystemType, level);
  152. TypeOrder[type] = num + (int)attr.Order;
  153. }
  154. else
  155. {
  156. TypeOrder[type] = 0;
  157. }
  158. return TypeOrder[type];
  159. }
  160. /// <summary>
  161. /// 开启世界主循环
  162. /// </summary>
  163. public void Start()
  164. {
  165. Stoped = false;
  166. Task.Run(Loop);//不要使用Thread,可以使用ThreadPool
  167. }
  168. void Loop()
  169. {
  170. var sw = new Stopwatch();
  171. while (!Stoped)
  172. {
  173. WorkTimes wt = new WorkTimes();
  174. wt.Key = this.GetType().Name;
  175. sw.Restart();
  176. BeforeUpdate();
  177. Update(wt.Items);
  178. AfterUpdate();
  179. sw.Stop();
  180. var workTimes = (int)sw.ElapsedMilliseconds;
  181. var ms = Interval - workTimes;
  182. sw.Start();
  183. if (ms > 0)
  184. {
  185. Thread.Sleep(ms);//不要使用Task.Delay().Wait()
  186. }
  187. else
  188. {
  189. Console.ForegroundColor = ConsoleColor.Red;
  190. }
  191. sw.Stop();
  192. var total = sw.ElapsedMilliseconds;
  193. wt.Total = total;
  194. var aa = wt.GetInfo();
  195. Console.WriteLine(aa);
  196. Console.ResetColor();
  197. }
  198. }
  199. public void Stop()
  200. {
  201. Stoped = true;
  202. }
  203. void Update(List<WorkTimes> list)
  204. {
  205. var wt = new WorkTimes();
  206. wt.Key = "读取PLC数据";
  207. var sw=new Stopwatch();
  208. sw.Start();
  209. LoadPlcData(wt.Items);
  210. sw.Stop();
  211. wt.Total = sw.ElapsedMilliseconds;
  212. list.AddSafe(wt);
  213. wt = new WorkTimes();
  214. wt.Key = "系统业务";
  215. sw.Restart();
  216. DoLogics(wt.Items);
  217. sw.Stop();
  218. wt.Total = sw.ElapsedMilliseconds;
  219. list.AddSafe(wt);
  220. }
  221. void LoadPlcData(List<WorkTimes> list)
  222. {
  223. var logs = new List<LogInfo>();
  224. Parallel.ForEach(this.GetDataBlocks(), db =>
  225. {
  226. var channel = new Channel
  227. {
  228. World = GetType().Name,
  229. System = "读取PLC",
  230. Item = $"{db.Entity.PLCInfo.IP}_{db.Entity.No}"
  231. };
  232. var sw = new Stopwatch();
  233. sw.Start();
  234. try
  235. {
  236. db.RefreshData();
  237. }
  238. catch (KnownException ex)
  239. {
  240. logs.AddSafe(new LogInfo { Channel = channel, Message = $"{ex.GetBaseException().Message}", Level = ex.Level, Type = ErrorType.已知 });
  241. this.Ex().Publish(channel, ex.GetBaseException().Message);
  242. }
  243. catch (Exception ex)
  244. {
  245. logs.AddSafe(new LogInfo { Channel = channel, Message = $"{ex.GetBaseException().Message}", Level = LogLevel.高, Type = ErrorType.未知 });
  246. this.Ex().Publish(channel, ex.GetBaseException().Message);
  247. }
  248. sw.Stop();
  249. list.AddSafe(new WorkTimes { Key = $"{db.Entity.PLCInfo.IP}/{db.Entity.No}", Total = sw.ElapsedMilliseconds });
  250. });
  251. Configs.OnLog?.Invoke(logs);
  252. }
  253. 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.GetType().Name;
  265. var sw2 = new Stopwatch();
  266. sw2.Start();
  267. try
  268. {
  269. sys.Update(wt2.Items);
  270. }catch (Exception ex)
  271. {
  272. Console.ForegroundColor = ConsoleColor.Red;
  273. Console.WriteLine(ex.GetBaseException().Message);
  274. Console.ResetColor();
  275. }
  276. sw2.Stop();
  277. wt2.Total = sw2.ElapsedMilliseconds;
  278. list.AddSafe(wt2);
  279. });
  280. sw.Stop();
  281. wt.Total= sw.ElapsedMilliseconds;
  282. //list.AddSafe(wt);
  283. }
  284. }
  285. protected virtual void BeforeUpdate()
  286. {
  287. }
  288. protected virtual void AfterUpdate()
  289. {
  290. }
  291. #endregion
  292. public T GetSystem<T>() where T : SystemBase
  293. {
  294. var sys = Systems.Where(v => v.GetType() == typeof(T)).FirstOrDefault() as T;
  295. if (sys == null)
  296. throw new Exception($"世界{GetType().Name}中不存在系统{typeof(T).Name}");
  297. return sys;
  298. }
  299. public SystemBase[] Systems
  300. {
  301. get {
  302. return SystemGroups.SelectMany(v => v.Value).ToArray();
  303. }
  304. }
  305. }
  306. public class WorldEx : EntityEx<World>
  307. {
  308. RedisClient Redis = new RedisClient(Configs.DebugRedisUrl);
  309. List<string> ChannelList = new List<string>();
  310. DateTime SubTime = DateTime.Now;
  311. public WorldEx(World ent) : base(ent)
  312. {
  313. Redis.Subscribe("Login", (channel, msg) =>
  314. {
  315. lock (ChannelList)
  316. {
  317. ChannelList.Clear();
  318. ChannelList.AddSafe(msg.ToString().Split(','));
  319. }
  320. SubTime = DateTime.Now;
  321. Console.WriteLine($"调试工具正在使用中,已订阅:{msg}");
  322. });
  323. }
  324. public void Publish(Channel channel, string msg)
  325. {
  326. if ((DateTime.Now - SubTime).TotalSeconds > 20)
  327. return;
  328. var flag = false;
  329. lock (ChannelList)
  330. {
  331. flag=ChannelList.Any(v =>
  332. {
  333. var b = Regex.Match(channel.ToString(), $"^{v.Replace("*", ".*")}$");
  334. return b.Success;
  335. });
  336. }
  337. if (flag)
  338. Redis.Publish(channel.ToString(), msg);
  339. }
  340. }
  341. public class WorkTimes
  342. {
  343. public string Key { get; set; } = "";
  344. public long Total { get; set; }
  345. public List<WorkTimes> Items { get; set; } = new List<WorkTimes>();
  346. public override string ToString()
  347. {
  348. return $"{Key},明细:{Items.Count},耗时:{Total}";
  349. }
  350. public string GetInfo()
  351. {
  352. var str = $"[{ToString()}]";
  353. if (Items.Count > 0)
  354. str += $" > {Items.OrderBy(v => v.Total).LastOrDefault()?.GetInfo()}";
  355. return str;
  356. }
  357. }
  358. public abstract class AttrClass<T> where T : Attribute
  359. {
  360. public T? Attr { get; private set; }
  361. public AttrClass()
  362. {
  363. Attr = GetType().GetCustomAttribute<T>();
  364. }
  365. }
  366. public abstract class DescriptionClass:AttrClass<DescriptionAttribute>
  367. {
  368. public string Description
  369. {
  370. get
  371. {
  372. if (Attr != null)
  373. return Attr.Description;
  374. else
  375. return GetType().Name;
  376. }
  377. }
  378. }
  379. }