using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace SafeMobileLib.Modules { public class AppServerMonitoring { public static int APP_SERVER_HEARTBEAT_SEC = 5; #if DEBUG public int MISSED_INTERVALS = 240; #else public int MISSED_INTERVALS = 24; #endif // thread to check at periodic time private Thread monitoringThread; // flag that the monitoring should be running or not private bool isRunning = false; private bool isUnreachable = false; private DateTime _lastAppServerHeartbeat; public DateTime lastAppServerHeartbeat { get { return _lastAppServerHeartbeat; } set { _lastAppServerHeartbeat = value; } } public AppServerMonitoring() { _lastAppServerHeartbeat = new DateTime(0); } public void NewHeartBeatReceived() { if (isUnreachable) { isUnreachable = false; OnAppServerReacheableAgain?.Invoke(); } // set the last app server heartbeat to now lastAppServerHeartbeat = DateTime.Now; } /// /// Start the thread which will manage the monitoring of the usb device plug & unplug /// public void StartAppServerMonitoring() { if (this.isRunning) return; this.isRunning = true; monitoringThread = new Thread(new ThreadStart(MonitoringThreadHandler)); monitoringThread.Start(); } /// /// Stop the thread which is monitoring the detection of application server is on or off /// public void StopMonitoring() { this.isRunning = false; } /// /// Thread function /// private void MonitoringThreadHandler() { int count = -1; while (isRunning) { // wait until checking again Thread.Sleep(500); // trigger event if more than two interval are missed and it at least one App Server heartbeat was received if(lastAppServerHeartbeat.Year > 2015 && (new TimeSpan(DateTime.Now.Ticks - lastAppServerHeartbeat.Ticks)).TotalSeconds > APP_SERVER_HEARTBEAT_SEC * MISSED_INTERVALS && !isUnreachable) { isUnreachable = true; OnAppServerUnreacheable?.Invoke(); } } } public delegate void AppServerUnreacheable(); public event AppServerUnreacheable OnAppServerUnreacheable; public delegate void AppServerReacheableAgain(); public event AppServerReacheableAgain OnAppServerReacheableAgain; } }