using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Threading;
using Tango.Core;
using Tango.Core.Helpers;
namespace Tango.PPC.Common.WatchDog
{
public class WatchDogServer : ExtendedObject, IDisposable
{
private NamedPipeServerStream _server;
private StreamReader _reader;
private StreamWriter _writer;
private Thread _thread;
private Dispatcher _dispatcher;
private String _watchdogAppPath;
private Process _watchdogProcess;
public bool IsStarted { get; private set; }
public WatchDogServer(Dispatcher uiDispatcher)
{
_watchdogAppPath = Path.Combine(AssemblyHelper.GetCurrentAssemblyFolder(), "Tango.PPC.WatchDog.exe");
_dispatcher = uiDispatcher;
}
public void Start()
{
LogManager.Log("Starting watchdog server...");
try
{
_watchdogProcess = Process.GetProcessesByName("Tango.PPC.WatchDog").FirstOrDefault();
_server = new NamedPipeServerStream("Tango_Watch_Dog_Pipe");
_reader = new StreamReader(_server);
_writer = new StreamWriter(_server);
IsStarted = true;
_thread = new Thread(ThreadMethod);
_thread.IsBackground = true;
_thread.Start();
LogManager.Log("Watchdog server started.");
}
catch (Exception ex)
{
LogManager.Log(ex, "Error starting watchdog server!");
}
}
private void ThreadMethod()
{
IsStarted = true;
try
{
while (IsStarted)
{
if (_watchdogProcess == null)
{
LogManager.Log($"Starting watchdog process at '{_watchdogAppPath}'...");
try
{
_watchdogProcess = Process.Start(_watchdogAppPath);
}
catch (Exception ex)
{
LogManager.Log(ex, "Error starting watchdog process!");
return;
}
}
_server.WaitForConnection();
var line = _reader.ReadLine();
_dispatcher.Invoke(() =>
{
_writer.WriteLine(line);
_writer.Flush();
});
_server.Disconnect();
}
}
catch (Exception ex)
{
LogManager.Log(ex, "Error in watchdog server. Restarting watchdog...");
IsStarted = false;
try
{
_server.Dispose();
}
catch { }
Start();
return;
}
}
public void Stop()
{
if (IsStarted)
{
try
{
_watchdogProcess.Kill();
_watchdogProcess = null;
}
catch (Exception ex)
{
LogManager.Log(ex, "Error killing watchdog process!");
}
IsStarted = false;
_server.Dispose();
}
}
public void Dispose()
{
Stop();
}
}
}