ServerConsole.cs 2.8 KB

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