Protocols.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Diagnostics.Tracing;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace WCS.Core
  9. {
  10. public class Protocols
  11. {
  12. protected static ConcurrentDictionary<Type, ConcurrentDictionary<string, ProtocolInfo>> ItemOfType = new ConcurrentDictionary<Type, ConcurrentDictionary<string, ProtocolInfo>>();
  13. public static bool HasProtocol(Type type, string code)
  14. {
  15. return ItemOfType[type].ContainsKey(code);
  16. }
  17. public static ProtocolInfo Get(Type type, string code)
  18. {
  19. ItemOfType[type].TryGetValue(code, out var info);
  20. return info;
  21. }
  22. public static void Add(Type protocolType, string code, ProtocolInfo info)
  23. {
  24. if (!ItemOfType.TryGetValue(protocolType, out var item))
  25. {
  26. item = new ConcurrentDictionary<string, ProtocolInfo>();
  27. ItemOfType[protocolType] = item;
  28. }
  29. if (!item.TryAdd(code, info))
  30. throw new Exception($"Protocols {protocolType} 添加了重复的设备号");
  31. }
  32. /// <summary>
  33. /// 实例化Device,并未实例化Protocol
  34. /// </summary>
  35. /// <param name="world"></param>
  36. /// <returns></returns>
  37. public static List<Device> Generate(World world)
  38. {
  39. List<Device> list = new List<Device>();
  40. var gs = ItemOfType.SelectMany(v => v.Value.Select(d => new { code = d.Key, proto = d.Value, type = v.Key })).GroupBy(v=>v.code).ToList();
  41. foreach (var g in gs)
  42. {
  43. var dev = new Device { Code = g.Key, World = world };
  44. list.Add(dev);
  45. }
  46. return list;
  47. }
  48. }
  49. public class Protocols<T> : Protocols
  50. {
  51. public static void Add(string code, ProtocolInfo info)
  52. {
  53. Protocols.Add(typeof(T), code, info);
  54. }
  55. public static ProtocolInfo Get(string code)
  56. {
  57. return Get(typeof(T), code);
  58. }
  59. }
  60. }