World.cs 14 KB

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