Worker.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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.Routes)
  127. .Includes(v => v.Paths)
  128. .Includes(v => v.DeviceGroup)
  129. .Includes(v => v.DeviceProtocol)
  130. .ToList();
  131. });
  132. #endregion 初始化设备信息
  133. #region 创建虚拟PLC
  134. var isOpenVirtualPlc = RedisHub.Default.Check("isOpenVirtualPLC") ?? throw new Exception("请在Redsi中配置是否启用虚拟PLC");
  135. if (isOpenVirtualPlc == "1")
  136. {
  137. var plcDataConnectionString = RedisHub.Default.Check("plcDataConnectionString") ?? throw new Exception("请在Redsi中配置虚拟PLC使用的Redis连接字符串");
  138. //从现有结构解析出需要的结构
  139. var list = new List<PLCData>();
  140. SqlSugarHelper.Do(db =>
  141. {
  142. var _db = db.Connect;
  143. var dataBlocks = _db.Queryable<WCS_PlcDataBlock>().Includes(v => v.PLC).ToList();
  144. list.AddRange(dataBlocks.Select(dataBlock => new PLCData()
  145. {
  146. IP = dataBlock.PLC.IP,
  147. DB = dataBlock.NO,
  148. Length = dataBlock.Length,
  149. DataLength = dataBlock.DataLength,
  150. }));
  151. });
  152. PlcData.Init(plcDataConnectionString).InitPlcData(list);
  153. ServiceHub.AddSystemMode(SystemMode.虚拟plc);
  154. }
  155. #endregion 创建虚拟PLC
  156. var a = typeof(IStation520);
  157. #region 初始化PLC访问器及PLC读取协议
  158. //创建PLC访问器
  159. Configs.PLCAccessorCreater = new PLCAccessors.PLCAccessorsCreater();
  160. try
  161. {
  162. SqlSugarHelper.Do(db =>
  163. {
  164. var _db = db.Connect;
  165. //获取所有DB块读写协议
  166. var dbProtocols = _db.Queryable<WCS_DeviceProt>().Includes(v => v.DB, p => p.PLC).ToList();
  167. foreach (var dbProtocol in dbProtocols)
  168. {
  169. Add(Type.GetType(dbProtocol.DB.Protocol), dbProtocol.DeviceCode, dbProtocol.Position, dbProtocol.DB, dbProtocol.DB.PLC);
  170. }
  171. });
  172. #region 唤醒所有的世界
  173. World.StartAll();
  174. #endregion 唤醒所有的世界
  175. _logger.LogInformation("WCS启动成功");
  176. #region 启用数据采集器
  177. while (true)
  178. {
  179. World.GetSystemInstance<DataCollectionSysyem>().Invoke(true);
  180. }
  181. #endregion 启用数据采集器
  182. }
  183. catch (Exception ex)
  184. {
  185. _logger.LogError("WCS启动失败{0}", ex.Message);
  186. }
  187. #endregion 初始化PLC访问器及PLC读取协议
  188. }
  189. /// <summary>
  190. /// 添加协议
  191. /// </summary>
  192. /// <param name="type">协议类型</param>
  193. /// <param name="code">设备号</param>
  194. /// <param name="position">地址</param>
  195. /// <param name="db">db</param>
  196. /// <param name="plc">PLC</param>
  197. public static void Add(Type type, string code, int position, WCS_PlcDataBlock db, WCS_PlcSet plc)
  198. {
  199. var info = new ProtocolInfo
  200. {
  201. Position = position,
  202. DBInfo = new DBInfo
  203. {
  204. No = (ushort)db.NO,
  205. PLCInfo = new PLCInfo
  206. {
  207. IP = plc.IP,
  208. Port = plc.Port,
  209. Rack = plc.Rack,
  210. Slot = plc.Slot,
  211. Type = Core.PLCType.Siemens
  212. }
  213. }
  214. };
  215. try
  216. {
  217. Protocols.Add(type, code, info);
  218. }
  219. catch (Exception ex)
  220. {
  221. var a = ex;
  222. }
  223. }
  224. }
  225. }