aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/PPC/Modules/Tango.PPC.Events/App.xaml
blob: bd3cf16ee38b63b8fe359d1e2154ffc133fb25d5 (plain)
1
2
3
4
5
6
7
8
9
10
11
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Tango.Core;

namespace Tango.PPC.Common.WatchDog
{
    public class WatchDogClient : ExtendedObject
    {
        public event EventHandler ServerNotResponding;

        private NamedPipeClientStream _client;
        private StreamReader _reader;
        private StreamWriter _writer;
        private Thread _thread;

        public bool IsStarted { get; private set; }

        public TimeSpan Interval { get; set; }

        public WatchDogClient()
        {
            Interval = TimeSpan.FromSeconds(5);
        }

        public void Start()
        {
            if (!IsStarted)
            {
                LogManager.Log("Starting watchdog client...");

                IsStarted = true;

                _thread = new Thread(ThreadMethod);
                _thread.IsBackground = true;
                _thread.Start();
            }
        }

        private void ThreadMethod()
        {
            try
            {
                LogManager.Log("Watchdog client started.");

                while (IsStarted)
                {
                    _client = new NamedPipeClientStream("Tango_Watch_Dog_Pipe");
                    _client.Connect(5000);

                    _reader = new StreamReader(_client);
                    _writer = new StreamWriter(_client);

                    _writer.WriteLine("ping");
                    _writer.Flush();

                    var line = _reader.ReadLine();

                    if (line != "ping")
                    {
                        LogManager.Log("Watchdog server not found. Raising notification...");
                        try
                        {
                            IsStarted = false;
                            _client.Dispose();
                        }
                        catch { }

                        ServerNotResponding?.Invoke(this, new EventArgs());
                        return;
                    }

                    _client.Dispose();

                    Thread.Sleep(Interval);
                }
            }
            catch (Exception ex)
            {
                IsStarted = false;
                LogManager.Log(ex, "Error in watchdog client.");
                ServerNotResponding?.Invoke(this, new EventArgs());
            }
        }

        public void Stop()
        {
            IsStarted = false;
            _client.Dispose();
        }
    }
}