World.cs 16 KB

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