World.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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 T GetWorldInstance<T>() where T : World
  44. {
  45. return (T)Worlds.Where(v => v.GetType() == typeof(T)).First();
  46. }
  47. public static T GetSystemInstance<T>() where T : SystemBase
  48. {
  49. try
  50. {
  51. return (T)World.Worlds.SelectMany(v => v.Systems).Where(v => v.GetType() == typeof(T)).First();
  52. }
  53. catch (Exception ex)
  54. {
  55. throw new Exception($"系统:{typeof(T).Name}未设置BelongToAttribute");
  56. }
  57. }
  58. public static void StartAll()
  59. {
  60. //MM_BeginPeriod(1);
  61. Worlds.ForEach(w => w.Init());
  62. foreach (World w in Worlds)
  63. {
  64. if (w.SystemTypes.Length == 0)
  65. continue;
  66. w.Start();
  67. }
  68. var arr = Worlds.SelectMany(v => v.SystemGroups).SelectMany(v => v.Value)
  69. .SelectMany(v => v.GetObjects().OfType<EntityEx<Device>>().Select(d => new { Sys = v, Obj = d }))
  70. .GroupBy(v => v.Obj.Entity.Code)
  71. .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() })
  72. .Where(v => v.Systems.Length > 1).ToArray();
  73. if (arr.Length > 0)
  74. {
  75. var msgs = arr.Select(v => $"设备{v.Code}同时存在于{v.Systems.Length}个系统:({string.Join(',', v.Systems)}),{v.Worlds.Length}个世界:({string.Join(',', v.Worlds)})中").ToArray();
  76. var str = string.Join('\n', msgs);
  77. Console.ForegroundColor = ConsoleColor.DarkYellow;
  78. Console.WriteLine(str);
  79. Console.ResetColor();
  80. }
  81. }
  82. public static void StopAll()
  83. {
  84. //MM_EndPeriod(1);
  85. foreach (World w in Worlds)
  86. w.Stop();
  87. }
  88. #endregion
  89. #region Dynamic
  90. public bool Stoped;
  91. Dictionary<Type, int> TypeOrder = new Dictionary<Type, int>();
  92. Dictionary<int, List<SystemBase>> SystemGroups = new Dictionary<int, List<SystemBase>>();
  93. protected Type[] SystemTypes;
  94. /// <summary>
  95. /// 周期最小间隔时间(毫秒)
  96. /// </summary>
  97. protected abstract int Interval {
  98. get;
  99. }
  100. public World()
  101. {
  102. SystemTypes = GetSystemTypes();
  103. }
  104. protected virtual Type[] GetSystemTypes()
  105. {
  106. var sysTypes = Assembly.GetEntryAssembly().GetTypes()
  107. .Where(v => !v.IsAbstract)
  108. .Where(v => typeof(SystemBase).IsAssignableFrom(v))
  109. .Where(v =>
  110. {
  111. var attr = v.GetCustomAttribute<BelongToAttribute>();
  112. if (attr == null)
  113. return GetType() == typeof(World);
  114. if (attr.WorldType == this.GetType())
  115. return true;
  116. return false;
  117. }).ToArray();
  118. return sysTypes;
  119. }
  120. public List<Device> Devices;
  121. /// <summary>
  122. /// 初始化,实例化世界下的所有系统
  123. /// </summary>
  124. public virtual void Init()
  125. {
  126. try
  127. {
  128. Devices = Protocols.Generate(this);
  129. foreach (var type in SystemTypes)
  130. {
  131. var sysDesc = type.GetCustomAttribute<DescriptionAttribute>()?.Description;
  132. Ltc.SetChannel(new Channel { World = Description, Stage = "Init", System = sysDesc ?? type.Name, Item = "排序" });
  133. Set(type, 0);
  134. }
  135. var arr = TypeOrder.OrderBy(v => v.Value).Select(v => v.Key).ToArray();
  136. var gs = TypeOrder.GroupBy(v => v.Value).OrderBy(v => v.Key).ToArray();
  137. for (int i = 0; i < gs.Length; i++)
  138. {
  139. var g = gs[i];
  140. var list = new List<SystemBase>();
  141. var sysArr = g.Select(v =>
  142. {
  143. var sysDesc = v.Key.GetCustomAttribute<DescriptionAttribute>()?.Description;
  144. Ltc.SetChannel(new Channel { World = Description, Stage="Init", System = sysDesc ?? v.Key.Name, Item = "构造" });
  145. return Activator.CreateInstance(v.Key);
  146. }).OfType<SystemBase>().ToArray();
  147. list.AddRange(sysArr);
  148. SystemGroups.Add(i, list);
  149. }
  150. }
  151. catch (Exception ex)
  152. {
  153. throw;
  154. }
  155. finally
  156. {
  157. }
  158. }
  159. int Set(Type type,int level)
  160. {
  161. if (!SystemTypes.Contains(type))
  162. throw new Exception($"OrderAttribute设置错误,与目标不属于同一世界。类型:{type}。");
  163. if (level > 10)
  164. {
  165. throw new Exception($"OrderAttribute设置错误,导致死循环。类型:{type}。");
  166. }
  167. var attr = type.GetCustomAttribute<OrderAttribute>();
  168. if (attr != null)
  169. {
  170. level++;
  171. var num = Set(attr.SystemType, level);
  172. TypeOrder[type] = num + (int)attr.Order;
  173. }
  174. else
  175. {
  176. TypeOrder[type] = 0;
  177. }
  178. return TypeOrder[type];
  179. }
  180. /// <summary>
  181. /// 开启世界主循环
  182. /// </summary>
  183. public void Start()
  184. {
  185. Stoped = false;
  186. Task.Run(Loop);//不要使用Thread,可以使用ThreadPool
  187. }
  188. void Loop()
  189. {
  190. var sw = new Stopwatch();
  191. while (!Stoped)
  192. {
  193. WorkTimes wt = new WorkTimes();
  194. wt.Key = $"{this.GetType().Name} 周期:{Interval}";
  195. sw.Restart();
  196. BeforeUpdate();
  197. Update(wt.Items);
  198. AfterUpdate();
  199. sw.Stop();
  200. var workTimes = (int)sw.ElapsedMilliseconds;
  201. var ms = Interval - workTimes;
  202. //sw.Start();
  203. if (ms > 0)
  204. {
  205. Thread.Sleep(ms);//不要使用Task.Delay().Wait()
  206. }
  207. //sw.Stop();
  208. //var total = sw.ElapsedMilliseconds;
  209. wt.Total = workTimes;
  210. FrameInfo(wt);
  211. }
  212. }
  213. public void Stop()
  214. {
  215. Stoped = true;
  216. }
  217. void Update(List<WorkTimes> list)
  218. {
  219. var wt = new WorkTimes();
  220. wt.Key = "读取PLC数据";
  221. var sw=new Stopwatch();
  222. sw.Start();
  223. LoadPlcData(wt.Items);
  224. sw.Stop();
  225. wt.Total = sw.ElapsedMilliseconds;
  226. list.AddSafe(wt);
  227. wt = new WorkTimes();
  228. wt.Key = "系统业务";
  229. sw.Restart();
  230. DoLogics(wt.Items);
  231. sw.Stop();
  232. wt.Total = sw.ElapsedMilliseconds;
  233. list.AddSafe(wt);
  234. }
  235. void LoadPlcData(List<WorkTimes> list)
  236. {
  237. Parallel.ForEach(this.GetDataBlocks(), db =>
  238. {
  239. var channel = new Channel
  240. {
  241. World = GetType().Name,
  242. Stage = "LoadPlcData",
  243. System = "",
  244. Item = $"{db.Entity.PLCInfo.IP}_{db.Entity.No}"
  245. };
  246. var sw = new Stopwatch();
  247. sw.Start();
  248. try
  249. {
  250. db.RefreshData();
  251. }
  252. catch (Exception ex)
  253. {
  254. this.Ex().Publish(channel, ex.GetBaseException().Message);
  255. }
  256. sw.Stop();
  257. list.AddSafe(new WorkTimes { Key = $"{db.Entity.PLCInfo.IP}/{db.Entity.No}", Total = sw.ElapsedMilliseconds });
  258. });
  259. }
  260. void DoLogics(List<WorkTimes> list)
  261. {
  262. foreach(var group in SystemGroups)
  263. {
  264. var wt=new WorkTimes();
  265. wt.Key = $"组{group.Key}";
  266. var sw = new Stopwatch();
  267. sw.Restart();
  268. Parallel.ForEach(group.Value, sys =>
  269. {
  270. var wt2=new WorkTimes();
  271. wt2.Key = sys.GetType().Name;
  272. var sw2 = new Stopwatch();
  273. sw2.Start();
  274. try
  275. {
  276. sys.Update(wt2.Items);
  277. }catch (Exception ex)
  278. {
  279. Console.ForegroundColor = ConsoleColor.Red;
  280. Console.WriteLine(ex.GetBaseException().Message);
  281. Console.ResetColor();
  282. }
  283. sw2.Stop();
  284. wt2.Total = sw2.ElapsedMilliseconds;
  285. list.AddSafe(wt2);
  286. });
  287. sw.Stop();
  288. wt.Total= sw.ElapsedMilliseconds;
  289. //list.AddSafe(wt);
  290. }
  291. }
  292. protected virtual void BeforeUpdate()
  293. {
  294. }
  295. protected virtual void AfterUpdate()
  296. {
  297. }
  298. #endregion
  299. public T GetSystem<T>() where T : SystemBase
  300. {
  301. var sys = Systems.Where(v => v.GetType() == typeof(T)).FirstOrDefault() as T;
  302. if (sys == null)
  303. throw new Exception($"世界{GetType().Name}中不存在系统{typeof(T).Name}");
  304. return sys;
  305. }
  306. public SystemBase[] Systems
  307. {
  308. get {
  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. internal protected abstract void OnError(Channel channel, Exception exception);
  326. internal protected 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. RedisClient Redis = new RedisClient(Configs.DebugRedisUrl);
  343. List<string> ChannelList = new List<string>();
  344. 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. }