Worker.cs 11 KB

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