ShiftWatcherService.cs 15 KB

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