Worker.cs 11 KB

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