Worker.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. using DBHelper;
  2. using DBHelper.Redis;
  3. using LogHelper;
  4. using Newtonsoft.Json;
  5. using ServiceCenter;
  6. using ServiceCenter.Virtual_PLC;
  7. using SqlSugar;
  8. using System.Text;
  9. using WCS.Core;
  10. using WCS.Entity;
  11. using WCS.Entity.Protocol;
  12. using WCS.Entity.Protocol.BCR;
  13. using WCS.Entity.Protocol.Station;
  14. using WCS.Service.Systems;
  15. namespace WCS.Service
  16. {
  17. /// <summary>
  18. /// 工作服务
  19. /// </summary>
  20. public class Worker : BackgroundService
  21. {
  22. /// <summary>
  23. /// 记录器
  24. /// </summary>
  25. private readonly ILogger<Worker> _logger;
  26. /// <summary>
  27. /// 构造函数
  28. /// </summary>
  29. /// <param name="logger">记录器</param>
  30. public Worker(ILogger<Worker> logger)
  31. {
  32. _logger = logger;
  33. }
  34. public static readonly string WcsDlog = "WCSDlog";
  35. public static readonly string Wcsdb = "WCSDB";
  36. /// <summary>
  37. /// 执行
  38. /// </summary>
  39. /// <param name="stoppingToken">停止令牌</param>
  40. /// <returns></returns>
  41. protected override async Task ExecuteAsync(CancellationToken stoppingToken)
  42. {
  43. if (stoppingToken.IsCancellationRequested)
  44. return;
  45. #region 启用日志
  46. var logConfigText = RedisHub.Default.Check("LogConfigText") ?? throw new Exception("请在Redis中配置log4net相关内容");
  47. var logConfig = JsonConvert.DeserializeObject<LogConfig>(logConfigText);
  48. LogHub.SetConfigInfo(logConfig!);
  49. #endregion 启用日志
  50. _logger.LogInformation("WCS开始启动");
  51. Configs.ProtocolProxyBaseType = typeof(ProtocolProxy);
  52. Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
  53. Configs.StringEncoding = Encoding.UTF8;
  54. var warehouseName = RedisHub.Default.Check("WarehouseName") ?? throw new Exception("请在Redis中配置仓库名称");
  55. if (string.IsNullOrEmpty(warehouseName)) throw new Exception("请在Redis中配置仓库名称");
  56. ServiceHub.SetWarehouseName(warehouseName);
  57. #region 初始化数据库连接
  58. var dbConnectionStrings = RedisHub.Default.Check("DbConnectionStrings") ?? throw new Exception("请在Redis中配置数据库连接相关内容");
  59. ServiceHub.DbConnectionStrings = JsonConvert.DeserializeObject<List<DataBaseConnectionString>>(dbConnectionStrings);
  60. if (ServiceHub.DbConnectionStrings != null)
  61. {
  62. if (ServiceHub.DbConnectionStrings.All(v => v.Key != Wcsdb)) throw new Exception("请在DbConnectionStrings中配置WCS基础数据库连接字符串");
  63. if (ServiceHub.DbConnectionStrings.All(v => v.Key == Wcsdb && !v.IsDefault)) throw new Exception("请在DbConnectionStrings中配置WCS基础数据库为默认数据库");
  64. if (ServiceHub.DbConnectionStrings.All(v => v.Key != WcsDlog)) throw new Exception("请在DbConnectionStrings中配置WCS日志数据库连接字符串");
  65. }
  66. foreach (var connectionString in ServiceHub.DbConnectionStrings!)
  67. {
  68. Db.CreateContext(new ConnectionConfig()
  69. {
  70. ConnectionString = connectionString.ConnectionString,
  71. DbType = connectionString.DbType
  72. }, connectionString.Key);
  73. if (connectionString.IsDefault) Db.SetDefaultDbContextType(connectionString.Key);
  74. switch (connectionString.Key)
  75. {
  76. case "WCSDB"://WCS基本数据库
  77. Db.Do(db =>
  78. {
  79. db.Default.CodeFirst.InitTables(typeof(WCS_PLC));
  80. db.Default.CodeFirst.InitTables(typeof(WCS_DATABLOCK));
  81. db.Default.CodeFirst.InitTables(typeof(WCS_DEVICEHdr));
  82. db.Default.CodeFirst.InitTables(typeof(WCS_PathHdr));
  83. db.Default.CodeFirst.InitTables(typeof(WCS_PathDtl));
  84. db.Default.CodeFirst.InitTables(typeof(WCS_ROUTE));
  85. db.Default.CodeFirst.InitTables(typeof(WCS_TASK));
  86. db.Default.CodeFirst.InitTables(typeof(WCS_TASK_DTL));
  87. db.Default.CodeFirst.InitTables(typeof(WCS_TASK_OLD));
  88. db.Default.CodeFirst.InitTables(typeof(WCS_PlcData));
  89. db.Default.CodeFirst.InitTables(typeof(WCS_AGVTask));
  90. db.Default.CodeFirst.InitTables(typeof(WCS_DEVICEPROTOCOL));
  91. db.Default.CodeFirst.InitTables(typeof(WCS_GROUPMEMBER));
  92. //db.Default.CodeFirst.InitTables(typeof(WCS_BCR80));
  93. //db.Default.CodeFirst.InitTables(typeof(WCS_RGV520));
  94. //db.Default.CodeFirst.InitTables(typeof(WCS_RGV521));
  95. //db.Default.CodeFirst.InitTables(typeof(WCS_RGV523));
  96. //db.Default.CodeFirst.InitTables(typeof(WCS_SRM520));
  97. //db.Default.CodeFirst.InitTables(typeof(WCS_SRM521));
  98. //db.Default.CodeFirst.InitTables(typeof(WCS_SRM537));
  99. //db.Default.CodeFirst.InitTables(typeof(WCS_Station520));
  100. //db.Default.CodeFirst.InitTables(typeof(WCS_Station521));
  101. //db.Default.CodeFirst.InitTables(typeof(WCS_Station523));
  102. });
  103. break;
  104. case "WCSDlog"://WCS日志数据库
  105. Db.Do(db =>
  106. {
  107. db.Context(WcsDlog).DbMaintenance.CreateDatabase();
  108. db.Context(WcsDlog).CodeFirst.InitTables(typeof(WCS_BCR80));
  109. //db.Context(WcsDlog).CodeFirst.InitTables(typeof(WCS_RGV520));
  110. //db.Context(WcsDlog).CodeFirst.InitTables(typeof(WCS_RGV521));
  111. //db.Context(WcsDlog).CodeFirst.InitTables(typeof(WCS_RGV523));
  112. //db.Context(WcsDlog).CodeFirst.InitTables(typeof(WCS_SRM520));
  113. //db.Context(WcsDlog).CodeFirst.InitTables(typeof(WCS_SRM521));
  114. //db.Context(WcsDlog).CodeFirst.InitTables(typeof(WCS_SRM537));
  115. db.Context(WcsDlog).CodeFirst.InitTables(typeof(WCS_Station520));
  116. db.Context(WcsDlog).CodeFirst.InitTables(typeof(WCS_Station521));
  117. db.Context(WcsDlog).CodeFirst.InitTables(typeof(WCS_Station523));
  118. db.Context(WcsDlog).CodeFirst.InitTables(typeof(WCS_Station91));
  119. //db.Context(WcsDlog).CodeFirst.InitTables(typeof(WCS.Entity.PlcRawData));
  120. });
  121. break;
  122. default: //其他库
  123. break;
  124. };
  125. };
  126. #endregion 初始化数据库连接
  127. #region 创建虚拟PLC
  128. var isOpenVirtualPlc = RedisHub.Default.Check("isOpenVirtualPLC") ?? throw new Exception("请在Redsi中配置是否启用虚拟PLC");
  129. if (isOpenVirtualPlc == "1")
  130. {
  131. var plcDataConnectionString = RedisHub.Default.Check("plcDataConnectionString") ?? throw new Exception("请在Redsi中配置虚拟PLC使用的Redis连接字符串");
  132. //从现有结构解析出需要的结构
  133. var list = new List<PLCData>();
  134. Db.Do(db =>
  135. {
  136. var dataBlocks = db.Default.Queryable<WCS_DATABLOCK>().Includes(v => v.PLC).ToList();
  137. list.AddRange(dataBlocks.Select(dataBlock => new PLCData()
  138. {
  139. IP = dataBlock.PLC.IP,
  140. DB = dataBlock.NO,
  141. Length = dataBlock.LENGTH,
  142. DataLength = dataBlock.DATALENGTH,
  143. }));
  144. });
  145. PlcData.Init(plcDataConnectionString).InitPlcData(list);
  146. ServiceHub.AddSystemMode(SystemMode.虚拟plc);
  147. }
  148. #endregion 创建虚拟PLC
  149. var a = typeof(IStation520);
  150. //日志发布事件s
  151. Configs.PublishEvent += () =>
  152. {
  153. //WMS.UploadDevInfo();
  154. //ProtocolProxy.Do();
  155. };
  156. //异常上抛
  157. Configs.UploadException = (d, s) =>
  158. {
  159. //if (s == "接口调用中") return;
  160. //if (ProtocolProxy.AllDatas.ContainsKey(d))
  161. //{
  162. // ProtocolProxy.AllDatas[d].Info = s;
  163. // //ProtocolProxy.AllDatas[d].Frame = LogicHandler.Frame;
  164. //}
  165. //WMS.TaskException(d, s);
  166. };
  167. //创建PLC访问器
  168. Configs.PLCAccessorCreater = new PLCAccessors.PLCAccessorsCreater();
  169. try
  170. {
  171. Db.Do(db =>
  172. {
  173. //获取所有DB块读写协议
  174. var dbProtocols = db.Default.Queryable<WCS_DEVICEPROTOCOL>().Includes(v => v.DB, p => p.PLC).ToList();
  175. foreach (var dbProtocol in dbProtocols)
  176. {
  177. #pragma warning disable CS8604 // 引用类型参数可能为 null。
  178. Add(Type.GetType(dbProtocol.DB.PROTOCOL), dbProtocol.DEVICECODE, dbProtocol.POSITION, dbProtocol.DB, dbProtocol.DB.PLC);
  179. #pragma warning restore CS8604 // 引用类型参数可能为 null。
  180. }
  181. });
  182. #region 唤醒所有的世界
  183. World.StartAll();
  184. #endregion 唤醒所有的世界
  185. _logger.LogInformation("WCS启动成功");
  186. #region 启用数据采集器
  187. while (true)
  188. {
  189. Ltc.GetSystem<DataCollectionSysyem>().Invoke(true);
  190. }
  191. #endregion 启用数据采集器
  192. }
  193. catch (Exception ex)
  194. {
  195. _logger.LogError("WCS启动失败{0}", ex.Message);
  196. }
  197. }
  198. /// <summary>
  199. /// 添加协议
  200. /// </summary>
  201. /// <param name="type">协议类型</param>
  202. /// <param name="code">设备号</param>
  203. /// <param name="position">地址</param>
  204. /// <param name="db">db</param>
  205. /// <param name="plc">PLC</param>
  206. public static void Add(Type type, string code, int position, WCS_DATABLOCK db, WCS_PLC plc)
  207. {
  208. var info = new ProtocolInfo
  209. {
  210. Position = position,
  211. DBInfo = new DBInfo
  212. {
  213. No = (ushort)db.NO,
  214. PLCInfo = new PLCInfo
  215. {
  216. IP = plc.IP,
  217. Port = plc.PORT,
  218. Rack = plc.RACK,
  219. Slot = plc.SLOT,
  220. Type = Core.PLCType.Siemens
  221. }
  222. }
  223. };
  224. try
  225. {
  226. Protocols.Add(type, code, info);
  227. }
  228. catch (Exception ex)
  229. {
  230. var a = ex;
  231. }
  232. }
  233. }
  234. }