World.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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. DoAddtional();
  221. }
  222. ConcurrentQueue<Action> Actions = new ConcurrentQueue<Action>();
  223. void DoAddtional()
  224. {
  225. while (Actions.TryDequeue(out Action? action))
  226. {
  227. if (action == null)
  228. throw new Exception("World.DoAddtional未知错误!");
  229. action();
  230. }
  231. }
  232. internal T _Do<TWorld,T>(Func<TWorld,T> func) where TWorld:World
  233. {
  234. var flag = false;
  235. T result=default(T);
  236. Actions.Enqueue(() =>
  237. {
  238. result = func((TWorld)this);
  239. flag = true;
  240. });
  241. while (!flag)
  242. Thread.Sleep(1);
  243. return result;
  244. }
  245. internal void _Do<TWorld>(Action<TWorld> action) where TWorld : World
  246. {
  247. _Do<TWorld, int>(w =>
  248. {
  249. action(w);
  250. return 1;
  251. });
  252. }
  253. void LoadPlcData(List<WorkTimes> list)
  254. {
  255. var logs = new List<LogInfo>();
  256. Parallel.ForEach(this.GetDataBlocks(), db =>
  257. {
  258. var channel = new Channel
  259. {
  260. World = GetType().Name,
  261. System = "读取PLC",
  262. Item = $"{db.Entity.PLCInfo.IP}_{db.Entity.No}"
  263. };
  264. var sw = new Stopwatch();
  265. sw.Start();
  266. try
  267. {
  268. db.RefreshData();
  269. }
  270. catch (KnownException ex)
  271. {
  272. logs.AddSafe(new LogInfo { Channel = channel, Message = $"{ex.GetBaseException().Message}", Level = ex.Level, Type = ErrorType.已知 });
  273. this.Ex().Publish(channel, ex.GetBaseException().Message);
  274. }
  275. catch (Exception ex)
  276. {
  277. logs.AddSafe(new LogInfo { Channel = channel, Message = $"{ex.GetBaseException().Message}", Level = LogLevel.高, Type = ErrorType.未知 });
  278. this.Ex().Publish(channel, ex.GetBaseException().Message);
  279. }
  280. sw.Stop();
  281. list.AddSafe(new WorkTimes { Key = $"{db.Entity.PLCInfo.IP}/{db.Entity.No}", Total = sw.ElapsedMilliseconds });
  282. });
  283. Configs.OnLog?.Invoke(logs);
  284. }
  285. void DoLogics(List<WorkTimes> list)
  286. {
  287. foreach(var group in SystemGroups)
  288. {
  289. var wt=new WorkTimes();
  290. wt.Key = $"组{group.Key}";
  291. var sw = new Stopwatch();
  292. sw.Restart();
  293. Parallel.ForEach(group.Value, sys =>
  294. {
  295. var wt2=new WorkTimes();
  296. wt2.Key = sys.GetType().Name;
  297. var sw2 = new Stopwatch();
  298. sw2.Start();
  299. try
  300. {
  301. sys.Update(wt2.Items);
  302. }catch (Exception ex)
  303. {
  304. Console.ForegroundColor = ConsoleColor.Red;
  305. Console.WriteLine(ex.GetBaseException().Message);
  306. Console.ResetColor();
  307. }
  308. sw2.Stop();
  309. wt2.Total = sw2.ElapsedMilliseconds;
  310. list.AddSafe(wt2);
  311. });
  312. sw.Stop();
  313. wt.Total= sw.ElapsedMilliseconds;
  314. //list.AddSafe(wt);
  315. }
  316. }
  317. protected virtual void BeforeUpdate()
  318. {
  319. }
  320. protected virtual void AfterUpdate()
  321. {
  322. }
  323. #endregion
  324. public T GetSystem<T>() where T : SystemBase
  325. {
  326. var sys = Systems.Where(v => v.GetType() == typeof(T)).FirstOrDefault() as T;
  327. if (sys == null)
  328. throw new Exception($"世界{GetType().Name}中不存在系统{typeof(T).Name}");
  329. return sys;
  330. }
  331. public SystemBase[] Systems
  332. {
  333. get {
  334. return SystemGroups.SelectMany(v => v.Value).ToArray();
  335. }
  336. }
  337. }
  338. public class WorldEx : EntityEx<World>
  339. {
  340. RedisClient Redis = new RedisClient(Configs.DebugRedisUrl);
  341. List<string> ChannelList = new List<string>();
  342. DateTime SubTime = DateTime.Now;
  343. public WorldEx(World ent) : base(ent)
  344. {
  345. Redis.Subscribe("Login", (channel, msg) =>
  346. {
  347. lock (ChannelList)
  348. {
  349. ChannelList.Clear();
  350. ChannelList.AddSafe(msg.ToString().Split(','));
  351. }
  352. SubTime = DateTime.Now;
  353. Console.WriteLine($"调试工具正在使用中,已订阅:{msg}");
  354. });
  355. }
  356. public void Publish(Channel channel, string msg)
  357. {
  358. if ((DateTime.Now - SubTime).TotalSeconds > 20)
  359. return;
  360. var flag = false;
  361. lock (ChannelList)
  362. {
  363. flag=ChannelList.Any(v =>
  364. {
  365. var b = Regex.Match(channel.ToString(), $"^{v.Replace("*", ".*")}$");
  366. return b.Success;
  367. });
  368. }
  369. if (flag)
  370. Redis.Publish(channel.ToString(), msg);
  371. }
  372. }
  373. public class WorkTimes
  374. {
  375. public string Key { get; set; } = "";
  376. public long Total { get; set; }
  377. public List<WorkTimes> Items { get; set; } = new List<WorkTimes>();
  378. public override string ToString()
  379. {
  380. return $"{Key},明细:{Items.Count},耗时:{Total}";
  381. }
  382. public string GetInfo()
  383. {
  384. var str = $"[{ToString()}]";
  385. if (Items.Count > 0)
  386. str += $" > {Items.OrderBy(v => v.Total).LastOrDefault()?.GetInfo()}";
  387. return str;
  388. }
  389. }
  390. public abstract class AttrClass<T> where T : Attribute
  391. {
  392. public T? Attr { get; private set; }
  393. public AttrClass()
  394. {
  395. Attr = GetType().GetCustomAttribute<T>();
  396. }
  397. }
  398. public abstract class DescriptionClass:AttrClass<DescriptionAttribute>
  399. {
  400. public string Description
  401. {
  402. get
  403. {
  404. if (Attr != null)
  405. return Attr.Description;
  406. else
  407. return GetType().Name;
  408. }
  409. }
  410. }
  411. }