ShiftWatcherService.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. using Prism.Events;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using TeamAAS_VP.Core;
  9. using TeamAAS_VP.Events;
  10. using TeamAAS_VP.Models;
  11. namespace TeamAAS_VP.Services
  12. {
  13. public class ShiftWatcherService
  14. {
  15. private readonly IEventAggregator _eventAggregator;
  16. private Timer _timer;
  17. private string _lastShift;
  18. private WorkShift workShift;
  19. public ShiftWatcherService(IEventAggregator eventAggregator)
  20. {
  21. this._eventAggregator = eventAggregator;
  22. }
  23. public void Start()
  24. {
  25. // 中文注释:每秒检测一次
  26. _timer = new Timer(_ => CheckShift(), null, 0, 1000);
  27. try
  28. {
  29. this.workShift = FileHelper.ReadJsonFile<WorkShift>(FilePath.WorkShiftParamPath);
  30. }
  31. catch (Exception)
  32. { }
  33. _eventAggregator.GetEvent<WorkShiftUpdateNotification>().Subscribe((p) =>
  34. {
  35. this.workShift = p;
  36. });
  37. }
  38. private void CheckShift()
  39. {
  40. DateTime dateTimeDayShift = DateTime.Now;
  41. DateTime dateTimeNightShift = DateTime.Now;
  42. try
  43. {
  44. dateTimeDayShift = DateTime.Parse(workShift.DayShift);
  45. dateTimeNightShift = DateTime.Parse(workShift.NightShift);
  46. }
  47. catch
  48. {
  49. }
  50. string currentShift =
  51. (DateTime.Now.Hour >= 8 && DateTime.Now.Hour < 20) ? "Day" : "Night";
  52. if (_lastShift == null)
  53. {
  54. _lastShift = currentShift;
  55. return;
  56. }
  57. if (_lastShift != currentShift)
  58. {
  59. _lastShift = currentShift;
  60. // 只负责“通知”,不要弹窗
  61. _ = App.Current.Dispatcher.BeginInvoke(new Action(() =>
  62. {
  63. _eventAggregator.GetEvent<WorkShiftChangedNotification>().Publish();
  64. }));
  65. }
  66. }
  67. }
  68. }
  69. /*
  70. ```csharp
  71. // ===========================
  72. // 文件1:ShiftChangedEvent.cs
  73. // ===========================
  74. using Prism.Events;
  75. using System;
  76. namespace YourApp.Shift
  77. {
  78. // 中文注释:班次切换事件(发布/订阅用)
  79. public class ShiftChangedEvent : PubSubEvent<ShiftChangedPayload> { }
  80. // 中文注释:班次切换携带的数据
  81. public class ShiftChangedPayload
  82. {
  83. public string NewShiftName { get; set; } // 中文注释:新班次名称
  84. public DateTime SwitchTime { get; set; } // 中文注释:切换时间
  85. }
  86. }
  87. ```
  88. ```csharp
  89. // ===========================
  90. // 文件2:IShiftWatcher.cs / ShiftWatcher.cs
  91. // ===========================
  92. using Prism.Events;
  93. using System;
  94. using System.Threading;
  95. namespace YourApp.Shift
  96. {
  97. public interface IShiftWatcher
  98. {
  99. void Start();
  100. void Stop();
  101. }
  102. public class ShiftWatcher : IShiftWatcher
  103. {
  104. private readonly IEventAggregator _ea;
  105. private Timer _timer;
  106. private string _lastShiftKey;
  107. public ShiftWatcher(IEventAggregator ea)
  108. {
  109. _ea = ea;
  110. }
  111. public void Start()
  112. {
  113. // 中文注释:每秒检查一次(你可以改成 5s/10s)
  114. _timer = new Timer(_ => CheckShift(), null, TimeSpan.Zero, TimeSpan.FromSeconds(1));
  115. }
  116. public void Stop()
  117. {
  118. _timer?.Dispose();
  119. _timer = null;
  120. }
  121. private void CheckShift()
  122. {
  123. // 中文注释:示例班次规则:白班 08:00-20:00,夜班 20:00-08:00
  124. var now = DateTime.Now;
  125. string currentShift = (now.Hour >= 8 && now.Hour < 20) ? "Day" : "Night";
  126. if (_lastShiftKey == null)
  127. {
  128. _lastShiftKey = currentShift;
  129. return;
  130. }
  131. if (_lastShiftKey != currentShift)
  132. {
  133. _lastShiftKey = currentShift;
  134. // 中文注释:只发布事件,不在定时器线程里弹窗
  135. _ea.GetEvent<ShiftChangedEvent>().Publish(new ShiftChangedPayload
  136. {
  137. NewShiftName = currentShift,
  138. SwitchTime = now
  139. });
  140. }
  141. }
  142. }
  143. }
  144. ```
  145. ```csharp
  146. // ===========================
  147. // 文件3:IMainProcess.cs / MainProcess.cs
  148. // ===========================
  149. using System.Threading;
  150. using System.Threading.Tasks;
  151. namespace YourApp.Process
  152. {
  153. public interface IMainProcess
  154. {
  155. Task RunAsync(CancellationToken token);
  156. }
  157. public class MainProcess : IMainProcess
  158. {
  159. public async Task RunAsync(CancellationToken token)
  160. {
  161. // 中文注释:示例主流程循环(把你的采图/检测/运动控制逻辑放这里)
  162. while (!token.IsCancellationRequested)
  163. {
  164. // TODO: 在这里写你的主流程逻辑(注意尊重 token)
  165. await Task.Delay(100, token); // 中文注释:模拟工作
  166. }
  167. }
  168. }
  169. }
  170. ```
  171. ```csharp
  172. // ===========================
  173. // 文件4:MainWindowViewModel.cs(整合:切班→停流程→隐藏主窗口→ShowDialog登录→恢复)
  174. // ===========================
  175. using Prism.Events;
  176. using Prism.Mvvm;
  177. using System;
  178. using System.Text;
  179. using System.Threading;
  180. using System.Threading.Tasks;
  181. using System.Windows;
  182. using YourApp.Process;
  183. using YourApp.Shift;
  184. namespace YourApp.ViewModels
  185. {
  186. public class MainWindowViewModel : BindableBase
  187. {
  188. private readonly IEventAggregator _ea;
  189. private readonly IMainProcess _mainProcess;
  190. private CancellationTokenSource _mainFlowCts;
  191. private bool _loginShowing;
  192. public MainWindowViewModel(IEventAggregator ea, IMainProcess mainProcess)
  193. {
  194. _ea = ea;
  195. _mainProcess = mainProcess;
  196. // 中文注释:订阅班次切换事件,强制在UI线程执行(这样可以安全Hide/Show主窗口和弹窗)
  197. _ea.GetEvent<ShiftChangedEvent>()
  198. .Subscribe(OnShiftChanged, ThreadOption.UIThread);
  199. }
  200. // 中文注释:你可以在程序启动后调用一次,启动主流程
  201. public void StartMainFlow()
  202. {
  203. _mainFlowCts?.Cancel();
  204. _mainFlowCts = new CancellationTokenSource();
  205. // 中文注释:后台线程运行主流程,不阻塞UI
  206. Task.Run(async () =>
  207. {
  208. try
  209. {
  210. await _mainProcess.RunAsync(_mainFlowCts.Token);
  211. }
  212. catch (OperationCanceledException)
  213. {
  214. // 中文注释:正常取消
  215. }
  216. catch (Exception ex)
  217. {
  218. // 中文注释:实际项目里这里写日志
  219. Application.Current.Dispatcher.Invoke(() =>
  220. {
  221. MessageBox.Show(ex.Message, "主流程异常");
  222. });
  223. }
  224. });
  225. }
  226. // 中文注释:班次切换时触发:停流程→隐藏主窗口→弹登录→登录成功恢复
  227. private void OnShiftChanged(ShiftChangedPayload payload)
  228. {
  229. if (_loginShowing)
  230. return;
  231. _loginShowing = true;
  232. // 1️⃣ 中断主流程(取消后台任务,不动UI线程)
  233. _mainFlowCts?.Cancel();
  234. // 2️⃣ 隐藏主窗口
  235. var mainWindow = Application.Current.MainWindow;
  236. mainWindow?.Hide();
  237. // 3️⃣ 弹出重新登录窗口(你当前是 Window.ShowDialog)
  238. var loginWindow = new LoginWindow
  239. {
  240. Owner = mainWindow // 中文注释:设置Owner,防止窗口跑到后面
  241. };
  242. // 中文注释:可选,把提示原因传给登录窗口(你需要在LoginWindow里定义这个属性)
  243. loginWindow.LoginReason = $"班次切换到 {payload.NewShiftName},请重新登录";
  244. bool? result = loginWindow.ShowDialog();
  245. // 4️⃣ 根据登录结果处理
  246. if (result == true)
  247. {
  248. // 中文注释:登录成功 → 显示主窗口 → 重新启动主流程
  249. mainWindow?.Show();
  250. StartMainFlow();
  251. }
  252. else
  253. {
  254. // 中文注释:登录失败/取消:按需求决定(示例:仍显示主窗口但不启动流程)
  255. mainWindow?.Show();
  256. // 如果你想强制退出可以用:
  257. // Application.Current.Shutdown();
  258. }
  259. _loginShowing = false;
  260. }
  261. }
  262. }
  263. ```
  264. ```csharp
  265. // ===========================
  266. // 文件5:App.xaml.cs(Prism启动:注册服务 + 启动初始化 + 启动班次监控)
  267. // ===========================
  268. using Prism.Ioc;
  269. using Prism.Unity; // 如果你用 DryIoc/Autofac,这里换对应的PrismApplication基类命名空间
  270. using System.Text;
  271. using System.Windows;
  272. using YourApp.Process;
  273. using YourApp.Shift;
  274. namespace YourApp
  275. {
  276. public partial class App : PrismApplication
  277. {
  278. protected override Window CreateShell()
  279. {
  280. // 中文注释:支持GBK等编码(如果你有CSV/老设备编码需求)
  281. Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
  282. // 中文注释:创建主窗口(MainWindowView)
  283. return Container.Resolve<MainWindowView>();
  284. }
  285. protected override void RegisterTypes(IContainerRegistry containerRegistry)
  286. {
  287. // 中文注释:注册主流程服务
  288. containerRegistry.RegisterSingleton<IMainProcess, MainProcess>();
  289. // 中文注释:注册班次监控(定时器)
  290. containerRegistry.RegisterSingleton<IShiftWatcher, ShiftWatcher>();
  291. // 你原来这些也可以在这里注册或在别处注册
  292. // containerRegistry.RegisterSingleton<IConfigService, ConfigService>();
  293. // containerRegistry.RegisterSingleton<IDatabaseInitializer, DatabaseInitializer>();
  294. }
  295. protected override void OnInitialized()
  296. {
  297. base.OnInitialized();
  298. // 中文注释:启动时初始化(你原来Resolve的配置、数据库初始化可以放这里)
  299. var configService = Container.Resolve<IConfigService>();
  300. var dbInit = Container.Resolve<IDatabaseInitializer>();
  301. dbInit.Initialize();
  302. // 中文注释:启动班次监控
  303. var watcher = Container.Resolve<IShiftWatcher>();
  304. watcher.Start();
  305. // 中文注释:启动主流程(通过主窗口VM调用)
  306. // 注意:主窗口已经显示后再启动更合理
  307. if (Current.MainWindow?.DataContext is YourApp.ViewModels.MainWindowViewModel vm)
  308. {
  309. vm.StartMainFlow();
  310. }
  311. }
  312. }
  313. }
  314. ```
  315. ```csharp
  316. // ===========================
  317. // 文件6:LoginWindow.xaml.cs(示例:让 MainWindowViewModel 能设置 LoginReason)
  318. // 说明:你已有LoginWindow就按需合并,不需要照搬UI
  319. // ===========================
  320. using System.Windows;
  321. namespace YourApp
  322. {
  323. public partial class LoginWindow : Window
  324. {
  325. // 中文注释:给外部传入提示原因(可选)
  326. public string LoginReason
  327. {
  328. get { return (string)GetValue(LoginReasonProperty); }
  329. set { SetValue(LoginReasonProperty, value); }
  330. }
  331. public static readonly DependencyProperty LoginReasonProperty =
  332. DependencyProperty.Register(nameof(LoginReason), typeof(string), typeof(LoginWindow), new PropertyMetadata(""));
  333. public LoginWindow()
  334. {
  335. InitializeComponent();
  336. }
  337. // 中文注释:登录成功按钮
  338. private void BtnOk_Click(object sender, RoutedEventArgs e)
  339. {
  340. // TODO:这里做你的账号密码校验
  341. // 校验成功:
  342. this.DialogResult = true;
  343. this.Close();
  344. }
  345. // 中文注释:取消/关闭按钮
  346. private void BtnCancel_Click(object sender, RoutedEventArgs e)
  347. {
  348. this.DialogResult = false;
  349. this.Close();
  350. }
  351. }
  352. }
  353. ```
  354. */
  355. /*
  356. ///// <summary>
  357. ///// 判断在班次时间内是否是登录过点控
  358. ///// </summary>
  359. ///// <param name="DayShhift"></param>
  360. ///// <param name="NightShift"></param>
  361. ///// <returns></returns>
  362. //public bool JudgeIsSpotCheck(string DayShhift, string NightShift)
  363. //{
  364. // DateTime dateTimeDayShift = DateTime.Now;
  365. // DateTime dateTimeNightShift = DateTime.Now;
  366. // try
  367. // {
  368. // dateTimeDayShift = DateTime.Parse(DayShhift);
  369. // dateTimeNightShift = DateTime.Parse(NightShift);
  370. // }
  371. // catch (Exception)
  372. // {
  373. // AddLog(2, "Check Time格式输入错误,请参照 7:50 该格式进行填写");
  374. // MessageBox.Show("Check Time格式输入错误,请参照 7:50 该格式进行填写");
  375. // return false;
  376. // }
  377. // DateTime LoginTime = DateTime.Parse(IniConfigHelper.ReadIniData("CheckTime", "LoginTime", ""));
  378. // //在原有的基础上增加一天
  379. // DateTime endOfDateTimeDayShift = dateTimeDayShift.AddDays(1);
  380. // DateTime NowDataTime = DateTime.Now;
  381. // if (NowDataTime >= dateTimeDayShift && NowDataTime <= dateTimeNightShift)
  382. // {
  383. // if (!GlobalVariable.CheckTime.DayShiftSpotCheck && LoginTime >= dateTimeDayShift)
  384. // {
  385. // frmSpotCheck = new FrmSpotCheck(IniConfigHelper.ReadIniData("CheckTime", "LoginTime", ""), dateTimeDayShift, dateTimeNightShift);
  386. // if (frmSpotCheck.ShowDialog() == DialogResult.OK)
  387. // {
  388. // return true;
  389. // }
  390. // else
  391. // {
  392. // return false;
  393. // }
  394. // }
  395. // }
  396. // if (NowDataTime >= dateTimeNightShift && NowDataTime <= endOfDateTimeDayShift)
  397. // {
  398. // if (!GlobalVariable.CheckTime.NightShiftSpotCheck && LoginTime >= dateTimeNightShift)
  399. // {
  400. // frmSpotCheck = new FrmSpotCheck(IniConfigHelper.ReadIniData("CheckTime", "LoginTime", ""), dateTimeDayShift, dateTimeNightShift);
  401. // if (frmSpotCheck.ShowDialog() == DialogResult.OK)
  402. // {
  403. // return true;
  404. // }
  405. // else
  406. // {
  407. // return false;
  408. // }
  409. // }
  410. // }
  411. // return true;
  412. //}
  413. //[CheckTime]
  414. //DayShift=7:50
  415. //NightShift=19:50
  416. //NtcTempSelectStore=NTC.xlsx
  417. //LoginTime = 2025年8月14日 13:28
  418. //DayShiftSpotCheck=1
  419. //NightShiftSpotCheck=0
  420. #endregion
  421. */