Worker.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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. //SqlSugarHelper.SetDb(new SqlSugarScope(connectionConfigs, db =>
  78. //{
  79. // db.GetConnectionScope(Wcsdb).Aop.OnLogExecuting = (sql, pars) =>
  80. // {
  81. // Console.WriteLine(db.GetConnectionScope(Wcsdb).Ado.Connection.ConnectionString + "\r\n " + sql);
  82. // Console.WriteLine();
  83. // Console.WriteLine();
  84. // };
  85. // db.GetConnectionScope(WcsDlog).Aop.OnLogExecuting = (sql, pars) =>
  86. // {
  87. // Console.WriteLine(db.GetConnectionScope(WcsDlog).Ado.Connection.ConnectionString + "\r\n " + sql);
  88. // Console.WriteLine();
  89. // Console.WriteLine();
  90. // };
  91. //}));
  92. //初始化数据库
  93. SqlSugarHelper.Do(db =>
  94. {
  95. foreach (var connectionString in ServiceHub.DbConnectionStrings!)
  96. {
  97. var _db = db.Connect.GetConnectionScope(connectionString.Key);
  98. switch (connectionString.Key)
  99. {
  100. case "WCSDB"://WCS基本数据库
  101. SqlSugarHelper.SetDefault(connectionString.Key);
  102. _db.CodeFirst.InitTables(typeof(WCS_PlcSet));
  103. _db.CodeFirst.InitTables(typeof(WCS_PlcDataBlock));
  104. _db.CodeFirst.InitTables(typeof(WCS_PlcData));
  105. _db.CodeFirst.InitTables(typeof(WCS_DeviceInfo));
  106. _db.CodeFirst.InitTables(typeof(WCS_DeviceGrp));
  107. _db.CodeFirst.InitTables(typeof(WCS_DeviceProt));
  108. _db.CodeFirst.InitTables(typeof(WCS_PathInfo));
  109. _db.CodeFirst.InitTables(typeof(WCS_PathGrp));
  110. _db.CodeFirst.InitTables(typeof(WCS_Route));
  111. _db.CodeFirst.InitTables(typeof(WCS_TaskInfo));
  112. _db.CodeFirst.InitTables(typeof(WCS_TaskDtl));
  113. _db.CodeFirst.InitTables(typeof(WCS_TaskOld));
  114. _db.CodeFirst.InitTables(typeof(WCS_AgvTaskInfo));
  115. break;
  116. case "WCSDlog"://WCS日志数据库
  117. SqlSugarHelper.SetDlog(connectionString.Key);
  118. _db.DbMaintenance.CreateDatabase();
  119. _db.CodeFirst.InitTables(typeof(WCS_BCR80));
  120. //db.Context(WcsDlog).CodeFirst.InitTables(typeof(WCS_RGV520));
  121. //db.Context(WcsDlog).CodeFirst.InitTables(typeof(WCS_RGV521));
  122. //db.Context(WcsDlog).CodeFirst.InitTables(typeof(WCS_RGV523));
  123. //_db.CodeFirst.InitTables(typeof(WCS_SRM520));
  124. //_db.CodeFirst.InitTables(typeof(WCS_SRM521));
  125. //db.Context(WcsDlog).CodeFirst.InitTables(typeof(WCS_SRM537));
  126. _db.CodeFirst.InitTables(typeof(WCS_Station520));
  127. _db.CodeFirst.InitTables(typeof(WCS_Station521));
  128. _db.CodeFirst.InitTables(typeof(WCS_Station523));
  129. _db.CodeFirst.InitTables(typeof(WCS_Station91));
  130. break;
  131. default: //其他库
  132. break;
  133. };
  134. };
  135. });
  136. #endregion 初始化数据库连接
  137. #region 创建虚拟PLC
  138. var isOpenVirtualPlc = RedisHub.Default.Check("isOpenVirtualPLC") ?? throw new Exception("请在Redsi中配置是否启用虚拟PLC");
  139. if (isOpenVirtualPlc == "1")
  140. {
  141. var plcDataConnectionString = RedisHub.Default.Check("plcDataConnectionString") ?? throw new Exception("请在Redsi中配置虚拟PLC使用的Redis连接字符串");
  142. //从现有结构解析出需要的结构
  143. var list = new List<PLCData>();
  144. SqlSugarHelper.Do(db =>
  145. {
  146. var _db = db.Connect;
  147. var dataBlocks = _db.Queryable<WCS_PlcDataBlock>().Includes(v => v.PLC).ToList();
  148. list.AddRange(dataBlocks.Select(dataBlock => new PLCData()
  149. {
  150. IP = dataBlock.PLC.IP,
  151. DB = dataBlock.NO,
  152. Length = dataBlock.Length,
  153. DataLength = dataBlock.DataLength,
  154. }));
  155. });
  156. PlcData.Init(plcDataConnectionString).InitPlcData(list);
  157. ServiceHub.AddSystemMode(SystemMode.虚拟plc);
  158. }
  159. #endregion 创建虚拟PLC
  160. var a = typeof(IStation520);
  161. //创建PLC访问器
  162. Configs.PLCAccessorCreater = new PLCAccessors.PLCAccessorsCreater();
  163. try
  164. {
  165. SqlSugarHelper.Do(db =>
  166. {
  167. var _db = db.Connect;
  168. //获取所有DB块读写协议
  169. var dbProtocols = _db.Queryable<WCS_DeviceProt>().Includes(v => v.DB, p => p.PLC).ToList();
  170. foreach (var dbProtocol in dbProtocols)
  171. {
  172. #pragma warning disable CS8604 // 引用类型参数可能为 null。
  173. Add(Type.GetType(dbProtocol.DB.Protocol), dbProtocol.DeviceCode, dbProtocol.Position, dbProtocol.DB, dbProtocol.DB.PLC);
  174. #pragma warning restore CS8604 // 引用类型参数可能为 null。
  175. }
  176. });
  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. }
  193. /// <summary>
  194. /// 添加协议
  195. /// </summary>
  196. /// <param name="type">协议类型</param>
  197. /// <param name="code">设备号</param>
  198. /// <param name="position">地址</param>
  199. /// <param name="db">db</param>
  200. /// <param name="plc">PLC</param>
  201. public static void Add(Type type, string code, int position, WCS_PlcDataBlock db, WCS_PlcSet plc)
  202. {
  203. var info = new ProtocolInfo
  204. {
  205. Position = position,
  206. DBInfo = new DBInfo
  207. {
  208. No = (ushort)db.NO,
  209. PLCInfo = new PLCInfo
  210. {
  211. IP = plc.IP,
  212. Port = plc.Port,
  213. Rack = plc.Rack,
  214. Slot = plc.Slot,
  215. Type = Core.PLCType.Siemens
  216. }
  217. }
  218. };
  219. try
  220. {
  221. Protocols.Add(type, code, info);
  222. }
  223. catch (Exception ex)
  224. {
  225. var a = ex;
  226. }
  227. }
  228. }
  229. }