ServerConsole.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. using H.Pipes;
  2. using InABox.Wpf.Console;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using System.Timers;
  9. using System.Windows;
  10. using System.Windows.Media;
  11. using System.Windows.Threading;
  12. using Console = InABox.Wpf.Console.Console;
  13. namespace PRSServer;
  14. public class ServerConsole : Console
  15. {
  16. private PipeClient<string>? _client;
  17. private PRSService? _service;
  18. private readonly bool _monitoronly = true;
  19. public string ServiceName { get; private set; }
  20. private Timer? RefreshTimer;
  21. public ServerConsole(string servicename, string description, bool monitoronly = true): base(description)
  22. {
  23. ServiceName = servicename;
  24. _monitoronly = monitoronly;
  25. }
  26. protected override void OnLoaded()
  27. {
  28. base.OnLoaded();
  29. _client = new PipeClient<string>(ServiceName, ".");
  30. _client.MessageReceived += (o, args) =>
  31. {
  32. Dispatcher.BeginInvoke(() =>
  33. {
  34. ConsoleControl.LoadLogEntry(args.Message ?? "");
  35. });
  36. };
  37. _client.Connected += (o, args) =>
  38. {
  39. Dispatcher.BeginInvoke(() => ConsoleControl.Enabled = true);
  40. };
  41. _client.Disconnected += (o, args) =>
  42. {
  43. Dispatcher.BeginInvoke(() => ConsoleControl.Enabled = false);
  44. if (RefreshTimer == null)
  45. {
  46. RefreshTimer = new Timer(1000);
  47. RefreshTimer.Elapsed += RefreshTimer_Elapsed;
  48. }
  49. RefreshTimer.Start();
  50. };
  51. _client.ExceptionOccurred += (o, args) =>
  52. {
  53. };
  54. if (!_client.IsConnecting)
  55. {
  56. _client.ConnectAsync();
  57. }
  58. if (!_monitoronly)
  59. {
  60. var timer = new DispatcherTimer { Interval = new TimeSpan(0, 0, 3) };
  61. timer.Tick += (o, args) =>
  62. {
  63. timer.IsEnabled = false;
  64. _service = new PRSService(ServiceName, null);
  65. _service.Run(ServiceName);
  66. };
  67. timer.IsEnabled = true;
  68. }
  69. }
  70. private void RefreshTimer_Elapsed(object? sender, ElapsedEventArgs e)
  71. {
  72. if (_client is null) return;
  73. if (!_client.IsConnected)
  74. {
  75. if (!_client.IsConnecting)
  76. {
  77. _client.ConnectAsync();
  78. }
  79. }
  80. else
  81. {
  82. RefreshTimer?.Stop();
  83. }
  84. }
  85. protected override void OnClosing()
  86. {
  87. base.OnClosing();
  88. if (_monitoronly)
  89. {
  90. _client?.DisposeAsync().AsTask().Wait();
  91. RefreshTimer?.Stop();
  92. }
  93. else
  94. _service?.Halt();
  95. }
  96. protected override string GetLogDirectory()
  97. {
  98. return DatabaseEngine.GetPath(ServiceName);
  99. }
  100. }