using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using SafeNetLib; using System.Threading; using System.Diagnostics; using System.Net.Sockets; using System.Collections; using System.Text.RegularExpressions; using System.Drawing.Text; using AutoUpdaterDotNET; namespace MotoTRBO_SOC { public partial class FormMain : Form { private Thread threadInitAll; private TallysmanReceiveThread TallysmanReceiveConnection = null; private Thread TallysmanReceiveThreadObj = null; private Thread restartThread = null; private ToolStripMenuItem notifyIconCloseMenuItem; private Address adr; private static Boolean gatewayStatus = false; private Boolean isMessageBoxShown = false; private PerformanceCounter cpuCounter = new PerformanceCounter(); private PerformanceCounter ramCounter = new PerformanceCounter("Memory", "Available MBytes"); public FormMain() { InitializeComponent(); Application.ApplicationExit += new EventHandler(this.OnApplicationExit); cpuCounter.CategoryName = "Processor"; cpuCounter.CounterName = "% Processor Time"; cpuCounter.InstanceName = "_Total"; } private void FormMain_Load(object sender, EventArgs e) { /* // The ToolTip for the PictureBox. new ToolTip().SetToolTip(pictureBoxArs, "ARS"); new ToolTip().SetToolTip(pictureBoxPosition, "Position"); new ToolTip().SetToolTip(pictureBoxSMS, "SMS"); new ToolTip().SetToolTip(pictureBoxDatabase, "Database"); // change fonts to all labels PrivateFontCollection pfc = new PrivateFontCollection(); pfc.AddFontFile(@"Resources\OCRAExtended.ttf"); labelAppTitle.Font = new Font(pfc.Families[0], 11, FontStyle.Bold); labelGwStatus.Font = new Font(pfc.Families[0], 27, FontStyle.Bold); labelStatus.Font = new Font(pfc.Families[0], 7, FontStyle.Regular); labelEvent.Font = new Font(pfc.Families[0], 7, FontStyle.Regular); labelVersion.Font = new Font(pfc.Families[0], 9, FontStyle.Regular); */ // create notify Icon notifyIcon = new NotifyIcon(); notifyIcon.MouseDoubleClick += notifyIcon_DoubleClick; notifyIcon.Visible = true; notifyIcon.BalloonTipText = "MotoTRBO Gateway is stil running..."; notifyIcon.BalloonTipTitle = "MotoTRBO Gateway Minimized"; notifyIcon.BalloonTipIcon = ToolTipIcon.Info; notifyIcon.Icon = this.Icon; notifyIcon.Text = "MotoTRBO Gateway"; //Optional - Add a context menu to the TrayIcon: notifyIconContextMenuStrip = new ContextMenuStrip(); notifyIconCloseMenuItem = new ToolStripMenuItem(); notifyIconContextMenuStrip.SuspendLayout(); // // TrayIconContextMenu // this.notifyIconContextMenuStrip.Items.AddRange(new ToolStripItem[] { this.notifyIconCloseMenuItem}); this.notifyIconContextMenuStrip.Name = "TrayIconContextMenu"; this.notifyIconContextMenuStrip.Size = new Size(153, 70); // // CloseMenuItem // this.notifyIconCloseMenuItem.Name = "CloseMenuItem"; this.notifyIconCloseMenuItem.Size = new Size(152, 22); this.notifyIconCloseMenuItem.Text = "Exit"; this.notifyIconCloseMenuItem.Click += new EventHandler(this.CloseMenuItem_Click); notifyIconContextMenuStrip.ResumeLayout(false); notifyIcon.ContextMenuStrip = notifyIconContextMenuStrip; new Thread(new ThreadStart(StartLOG)).Start(); threadInitAll = new Thread(new ThreadStart(ThreadsInit)); threadInitAll.Start(); } private void CloseMenuItem_Click(object sender, EventArgs e) { pictureBoxClose_Click(sender, e); } private void StartLOG() { MotoTRBO_GW.hLOG = new LOGS(); } private void ThreadsInit() { Utils.ConsWrite(DebugMSG_Type.DB, System.Reflection.Assembly.GetExecutingAssembly().Location); Version v = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; Utils.ConsWrite(DebugMSG_Type.DB, "Version: " + v.ToString()); //load config file if (!LoadConfig()) { //Utils.ConsWrite(DebugMSG_Type.always, "EERROR loading configs!!!!\nPlease fix configs in DB/cfg file and restart the GW!!!"); return; } this.Invoke((MethodInvoker)delegate { if (MotoTRBO_GW.running) { labelVersion.Text = "Version " + v.ToString(); labelStatus.Text = "gateway " + MotoTRBO_GW.cfg.masterRadioIP + " [" + MotoTRBO_GW.cfg.gw_id + "] status"; } }); CheckForUpdate(); //SOC_connection sc = new SOC_connection(Server_IP, Server_Port, gatewayID); string MyConString = "SERVER=" + MotoTRBO_GW.cfg.SERVER + "; " + "DATABASE=" + MotoTRBO_GW.cfg.DATABASE + "; " + "UID=" + MotoTRBO_GW.cfg.UID + "; " + "PASSWORD=" + MotoTRBO_GW.cfg.PASSWORD + "; Pooling=false;"; MotoTRBO_GW.DBConnection = new DBconnThread(MyConString, MotoTRBO_GW.cfg.gw_id); MotoTRBO_GW.DBConnection.StartDB(); restartThread = new Thread(new ThreadStart(WaitForMessageBox)); // check if account is enabled or not if (!MotoTRBO_GW.DBConnection.DB.DBconnected) { isMessageBoxShown = true; restartThread.Start(); MessageBox.Show("Could not connect to DataBase. Please check your internet connection and try again.", "DataBase Connection Error"); isMessageBoxShown = false; System.Windows.Forms.Application.Exit(); return; } MotoTRBO_GW.DBConnection.DB.TestSafeMobileChanges(); bool result = MotoTRBO_GW.DBConnection.DB.CheckGatewayIsEnabled(MotoTRBO_GW.cfg.gw_id); if (!result) { isMessageBoxShown = true; restartThread.Start(); MessageBox.Show("Your gateway is deactivated. Please contact us at support@safemobile.com or reconfigure your gateway from setting button [right bottom corner].", "Gateway Deactivated"); isMessageBoxShown = false; System.Windows.Forms.Application.Exit(); return; } StartDBService(); //wait while (!MotoTRBO_GW.unitsLoaded && MotoTRBO_GW.running) { Utils.ConsWrite(DebugMSG_Type.DB, "Waiting for units to be fetched..."); Thread.Sleep(500); } Utils.ConsWrite(DebugMSG_Type.always, "»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»««««««««««««««««««««««««««««««"); Utils.ConsWrite(DebugMSG_Type.always, String.Format("»»»»»»»»»»»»»»»» Finished loading {0:D4} UNITS «««««««««««««««", SN_Queues.ht_SUInfo.Count)); Utils.ConsWrite(DebugMSG_Type.always, "»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»««««««««««««««««««««««««««««««"); UpdateLabelEvent("Finished loading " + SN_Queues.ht_SUInfo.Count + " units"); ArrayList list = new ArrayList(); foreach (DictionaryEntry de in SN_Queues.ht_SUInfo) { list.Add(de.Key); } MotoTRBO_GW.routeManager = new RouteManager(MotoTRBO_GW.cfg.masterRadioIP, list, MotoTRBO_GW.cfg.capPlus); //routeManager.OnRadioStatusUpdate += new RouteManager.RadioStatusUpdateDEl(routeManager_OnRadioStatusUpdate); MotoTRBO_GW.routeManager.OnRadioPing += new RouteManager.RadioPingDEl(routeManager_OnRadioPing); MotoTRBO_GW.routeManager.Start(); /* //add route for cap plus if (MotoTRBO_GW.cfg.capPlus) RoutingUtils.UpdateRoutes(MotoTRBO_GW.cfg.masterRadioIP, true); else { // get Interface ID RouteManager.networkID = RadioUtils.GetInterfaceID(MotoTRBO_GW.cfg.masterRadioIP); RoutingUtils.UpdateRoutes_NonCapPlus(MotoTRBO_GW.cfg.masterRadioIP, RadioUtils.GetInterface(MotoTRBO_GW.cfg.masterRadioIP), RouteManager.networkID); } */ StartARSService(); StartLocationService(); StartSMSService(); StartTallysmanService(); // ! NOT NOW BECAUSE IT'S TO MUCH TRAFFIC ON THE OTA // send to all units a Triggered message //MotoTRBO_GW.ARSConnection.onPowerUPGateway(); //p.StartEmailService();//new //p.StartComputeAddr();- adress are done throw a bing script int count = 0; while (MotoTRBO_GW.running) { count++; Thread.Sleep(1000); TimeSpan span = DateTime.Now.Subtract(MotoTRBO_GW.lastEntry); //Console.WriteLine("LAST TIME : " + MotoTRBO_GW.lastPositionThreadUpdate.ToString()); // check if the Threads are still running if (DateTime.Now.Subtract(MotoTRBO_GW.lastPositionThreadUpdate).TotalSeconds < 10) { // change icon to enabled if (pictureBoxPosition.Tag.ToString().Contains("Disabled")) { pictureBoxPosition.Image = Properties.Resources.gps_icon; pictureBoxPosition.Tag = "Enabled"; } } else { /* // change icon to disabled if (pictureBoxPosition.Tag.ToString().Contains("Enabled")) { pictureBoxPosition.Image = Properties.Resources.gps_icon_disabled; pictureBoxPosition.Tag = "Disabled"; } */ } /* // check if the Threads are still running if (DateTime.Now.Subtract(MotoTRBO_GW.lastARSThreadUpdate).TotalSeconds < 10) { // change icon to enabled if (pictureBoxArs.Tag.ToString().Contains("Disabled")) { pictureBoxArs.Image = Properties.Resources.ars_icon; pictureBoxArs.Tag = "Enabled"; } } // check if the Threads are still running if (DateTime.Now.Subtract(MotoTRBO_GW.lastSMSThreadUpdate).TotalSeconds < 10) { // change icon to enabled if (pictureBoxSMS.Tag.ToString().Contains("Disabled")) { pictureBoxSMS.Image = Properties.Resources.sms_icon; pictureBoxSMS.Tag = "Enabled"; } } */ // check if the Threads are still running if (DateTime.Now.Subtract(MotoTRBO_GW.lastEntry).TotalMinutes < 10) { // change icon to enabled if (pictureBoxDatabase.Tag.ToString().Contains("Disabled")) { pictureBoxDatabase.Image = Properties.Resources.database_icon; pictureBoxDatabase.Tag = "Enabled"; } } double cpuValue = 0; if (count % 10 == 0) { Utils.ConsWrite(DebugMSG_Type.DB, "Last entry at:" + MotoTRBO_GW.lastEntry); //Utils.ConsWrite(DebugMSG_Type.DB, "CPU : " + getCurrentCpuUsage()); //Utils.ConsWrite(DebugMSG_Type.DB, "RAM : " + getAvailableRAM()); PerformanceCounter myAppCpu = new PerformanceCounter("Process", "% Processor Time", "Safenet MotoTRBO Gateway", true); try { if (myAppCpu != null) { cpuValue = myAppCpu.NextValue(); //Console.WriteLine("My App'S CPU % = " + cpuValue); if (cpuValue > 15) { Utils.ConsWrite(DebugMSG_Type.always, "CPU Value is more than 15%. Restarting Gateway..."); RestartApp(); } } } catch (InvalidOperationException) { } } if (count % 60 == 0) { count = 0; GWstatus gws = new GWstatus(); gws.gw_id = MotoTRBO_GW.cfg.gw_id; gws.status = (gatewayStatus) ? 1 : 0; gws.message = "Last entry at:" + MotoTRBO_GW.lastEntry + " [CPU: " + cpuValue + "]"; SN_Queues.gwstatusQueue.PostItem(gws); if (span.TotalSeconds > MotoTRBO_GW.cfg.gw_restart_inactive_seconds) { Utils.ConsWrite(DebugMSG_Type.DB, "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); Utils.ConsWrite(DebugMSG_Type.DB, "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); Utils.ConsWrite(DebugMSG_Type.always, "Nothing received for " + MotoTRBO_GW.cfg.gw_restart_inactive_seconds + " seconds."); Utils.ConsWrite(DebugMSG_Type.DB, "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); Utils.ConsWrite(DebugMSG_Type.DB, "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); LOGS.LOG("Nothing received for 10 minutes."); //MotoTRBO_GW.lastEntry = DateTime.Now; if (MotoTRBO_GW.cfg.gw_restart) { Utils.ConsWrite(DebugMSG_Type.DB, "Adding restart INFO to LOG file"); string format = "dd/MM/yyyy HH:mm"; string s_time = "[" + DateTime.Now.ToString(format) + "] "; LOGS.LOG("@@@@@@@@@@@@@@@@@@@@@"); LOGS.LOG(s_time + "no GPS received for 10 minutes"); LOGS.LOG(s_time + "should restart"); LOGS.LOG("@@@@@@@@@@@@@@@@@@@@@"); RestartApp(); } else { /* StopDBService(); Thread.Sleep(10 * 1000); StartDBService(); */ Utils.ConsWrite(DebugMSG_Type.DB, "Adding restart INFO to LOG file"); string format = "dd/MM/yyyy HH:mm"; string s_time = "[" + DateTime.Now.ToString(format) + "] "; LOGS.LOG("@@@@@@@@@@@@@@@@@@@@@"); LOGS.LOG(s_time + "no GPS received for 10 minutes"); LOGS.LOG(s_time + "SHOULD restart DB thread"); LOGS.LOG("@@@@@@@@@@@@@@@@@@@@@"); } } } //TimerTask(); } Utils.ConsWrite(DebugMSG_Type.DB, "Finishing app..."); } private double previousValue = 0; // UNUSED public void TimerTask() { while (MotoTRBO_GW.running) { Thread.Sleep(5000); Process[] processList = Process.GetProcesses(); foreach (Process process in processList) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Process: " + process.ProcessName); Console.ForegroundColor = ConsoleColor.Gray; if (!process.ProcessName.Equals("Safenet MotoTRBO Gateway")) continue; using (PerformanceCounter pcProcess = new PerformanceCounter("Process", "% Processor Time", process.ProcessName)) using (PerformanceCounter memProcess = new PerformanceCounter("Memory", "Available MBytes")) { Console.WriteLine("CPU Usage & Memory Monitorring", EventLogEntryType.Information, 101); float cpuUseage = pcProcess.NextValue(); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Process: '{0}' CPU Usage: {1}%", process.ProcessName, cpuUseage); float memUseage = memProcess.NextValue(); Console.Write("CPU Usage: "); Console.ForegroundColor = ConsoleColor.White; Console.Write(cpuUseage + "%\n"); //Console.WriteLine("Process: '{0}' RAM Free: {1}MB", process.ProcessName, memUseage); previousValue = cpuUseage; //Console.WriteLine("CPU Usage : " + cpuUseage, EventLogEntryType.Information, 101); } /* Process p = new Process(); p.StartInfo.FileName = "cmd.exe"; p.StartInfo.Arguments = "/c tasklist /fi \"IMAGENAME eq notepad++.exe\" /FO CSV /NH"; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.Start(); string output = p.StandardOutput.ReadToEnd(); //this.EventLog.WriteEntry("Tasklist : " + output, EventLogEntryType.Information, 101); */ } } } public string getCurrentCpuUsage(){ // For the current process Process proceso = Process.GetProcessById(11860); PerformanceCounterCategory cat = new PerformanceCounterCategory("Process"); string[] instances = cat.GetInstanceNames(); foreach (string instance in instances) { using (PerformanceCounter cnt = new PerformanceCounter("Process", "ID Process", instance, true)) { int val = (int)cnt.RawValue; if (val == proceso.Id) { return 0 + "%"; } } } return 0 + "%"; } public string getAvailableRAM(){ return ramCounter.NextValue()+"MB"; } void routeManager_OnRadioPing(bool status, string ip) { GWstatus gws = new GWstatus(); gws.gw_id = MotoTRBO_GW.cfg.gw_id; gws.status = (status) ? 1 : 0; // send message to the queue in order to be added into the DB only if Loading message is displayed // or if Gateway Status has changed if (labelGwStatus.Text.Contains("Loading") || (labelGwStatus.Text.Contains("Online") && gws.status == 0) || (labelGwStatus.Text.Contains("Offline") && gws.status == 1)) { if (status && !labelGwStatus.Text.Contains("Loading")) { //add route for cap plus if (MotoTRBO_GW.cfg.capPlus) RoutingUtils.UpdateRoutes(MotoTRBO_GW.cfg.masterRadioIP, true); else { // get Interface ID RouteManager.networkID = RadioUtils.GetInterfaceID(MotoTRBO_GW.cfg.masterRadioIP); RoutingUtils.UpdateRoutes_NonCapPlus(MotoTRBO_GW.cfg.masterRadioIP, RadioUtils.GetInterface(MotoTRBO_GW.cfg.masterRadioIP), RouteManager.networkID); } } SN_Queues.gwstatusQueue.PostItem(gws); //Console.WriteLine("[### {0:H:mm:ss} ###] Gateway [" + ip + "] is now " + (status ? "ONLINE" : "OFFLINE"), DateTime.Now); Utils.ConsWrite(DebugMSG_Type.always, "»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»««««««««««««««««««««««««««««««"); Utils.ConsWrite(DebugMSG_Type.always, "»»»»»»»»»»»»»»» Gateway " + ip + " is now " + (status ? "ONLINE" : "OFFLINE")); Utils.ConsWrite(DebugMSG_Type.always, "»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»««««««««««««««««««««««««««««««"); this.Invoke((MethodInvoker)delegate { pictureBoxLoading.Visible = false; labelGwStatus.Text = (status ? "Online" : "Offline"); labelGwStatus.ForeColor = (status ? Color.DeepSkyBlue : Color.Maroon); UpdateLabelEvent(labelGwStatus.Text); }); gws.message = (status) ? "Running Online" : "Running Offline"; routeManager_OnRadioStatusUpdate(status, ip); } // save current gateway status gatewayStatus = status; } static void routeManager_OnRadioStatusUpdate(bool status, string ip) { Utils.ConsWrite(DebugMSG_Type.DB, "IP:" + ip + "status:" + status); GWstatus gws = new GWstatus(); gws.gw_id = MotoTRBO_GW.cfg.gw_id; gws.status = (status) ? 1 : 0; gws.message = (status) ? "Online" : "Offline"; SN_Queues.gwstatusQueue.PostItem(gws); } /// /// Load configuration from the config.ini file /// /// A boolean value representing if the action was successfull or not private bool LoadConfig() { bool ret = false; MotoTRBO_GW.cfg = new Config(); MotoTRBO_GW.cfg.OnConfigFileWasBroken += delegate() { MessageBox.Show("Something was wrong with your configuration file. " + System.Environment.NewLine + "Now you're running a default configuration. Please reconfigure your gateway from setting button [right bottom corner] or contact us at " + "support@safemobil.com. " + System.Environment.NewLine + System.Environment.NewLine + "Thank you!", "Reconfiguration needed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); pictureBoxSettings_Click(null, null); return; //System.Environment.Exit(0); }; MotoTRBO_GW.cfg.LoadConfig(); string MyConString = "SERVER=" + MotoTRBO_GW.cfg.SERVER + ";" + "DATABASE=" + MotoTRBO_GW.cfg.DATABASE + ";" + "UID=" + MotoTRBO_GW.cfg.UID + ";" + "PASSWORD=" + MotoTRBO_GW.cfg.PASSWORD + ";Connect Timeout=5;Pooling=false;"; ret = true; return ret; } void StartDBService() { try { //Start GPS DB thread MotoTRBO_GW.DBThreadobjGPS = new Thread(new ThreadStart(MotoTRBO_GW.DBConnection.HandleConnectionGPS)); MotoTRBO_GW.DBThreadobjGPS.IsBackground = true; MotoTRBO_GW.DBThreadobjGPS.Start(); Thread.Sleep(200); //Start ARS DB thread MotoTRBO_GW.DBThreadobjARS = new Thread(new ThreadStart(MotoTRBO_GW.DBConnection.HandleConnectionARS)); MotoTRBO_GW.DBThreadobjARS.IsBackground = true; MotoTRBO_GW.DBThreadobjARS.Start(); Thread.Sleep(200); //Start Units DB thread MotoTRBO_GW.DBThreadobjAux = new Thread(new ThreadStart(MotoTRBO_GW.DBConnection.HandleConnectionAux)); MotoTRBO_GW.DBThreadobjAux.IsBackground = true; MotoTRBO_GW.DBThreadobjAux.Start(); Thread.Sleep(200); //Start SMS DB thread MotoTRBO_GW.DBThreadobjSMS = new Thread(new ThreadStart(MotoTRBO_GW.DBConnection.HandleConnectionSMS)); MotoTRBO_GW.DBThreadobjSMS.IsBackground = true; MotoTRBO_GW.DBThreadobjSMS.Start(); Thread.Sleep(200); //Start SMS DB thread MotoTRBO_GW.DBThreadobjSMS_conf = new Thread(new ThreadStart(MotoTRBO_GW.DBConnection.HandleConnectionSMS_conf)); MotoTRBO_GW.DBThreadobjSMS_conf.IsBackground = true; MotoTRBO_GW.DBThreadobjSMS_conf.Start(); Thread.Sleep(200); //Start Addres insert thread MotoTRBO_GW.DBThreadobjAddr = new Thread(new ThreadStart(MotoTRBO_GW.DBConnection.HandleConnectionAddr)); MotoTRBO_GW.DBThreadobjAddr.IsBackground = true; //MotoTRBO_GW.DBThreadobjAddr.Start(); //Thread.Sleep(200); //Start POLL thread MotoTRBO_GW.DBThreadobjPOLL = new Thread(new ThreadStart(MotoTRBO_GW.DBConnection.HandleConnectionPOLL)); MotoTRBO_GW.DBThreadobjPOLL.IsBackground = true; MotoTRBO_GW.DBThreadobjPOLL.Start(); Thread.Sleep(200); //Start POLL thread MotoTRBO_GW.DBThreadobjTallysman = new Thread(new ThreadStart(MotoTRBO_GW.DBConnection.HandleTallysmanEvents)); MotoTRBO_GW.DBThreadobjTallysman.IsBackground = true; MotoTRBO_GW.DBThreadobjTallysman.Start(); Thread.Sleep(200); } catch (Exception e) { Utils.ConsWrite(DebugMSG_Type.always, "Could not intialize the connection with location server!\r\n" + e.Message + "\r\nPlease check your internet connection !!"); //System.Environment.Exit(1); } } private void StopDBService() { // close the DatabaseConnection if(MotoTRBO_GW.DBConnection != null) MotoTRBO_GW.DBConnection.StopDB(); if (MotoTRBO_GW.DBThreadobjARS != null) { MotoTRBO_GW.DBThreadobjARS.Abort(); } if (MotoTRBO_GW.DBThreadobjGPS != null) { MotoTRBO_GW.DBThreadobjGPS.Abort(); } if (MotoTRBO_GW.DBThreadobjAux != null) { MotoTRBO_GW.DBThreadobjAux.Abort(); } if (MotoTRBO_GW.DBThreadobjSMS != null) { MotoTRBO_GW.DBThreadobjSMS.Abort(); } if (MotoTRBO_GW.DBThreadobjSMS_conf != null) { MotoTRBO_GW.DBThreadobjSMS_conf.Abort(); } if (MotoTRBO_GW.DBThreadobjAddr != null) { MotoTRBO_GW.DBThreadobjAddr.Abort(); } if (MotoTRBO_GW.DBThreadobjPOLL != null) { MotoTRBO_GW.DBThreadobjPOLL.Abort(); } if (MotoTRBO_GW.DBThreadobjTallysman != null) { MotoTRBO_GW.DBThreadobjTallysman.Abort(); } } /// /// Restart the application and close other notify icons /// private void RestartApp() { CloseNotifyIcon(); MotoTRBO_GW.running = false; Thread p = new Thread(new ThreadStart(delegate() { //oldProcess.WaitForExit(8000); System.Diagnostics.Process.Start(System.Reflection.Assembly.GetExecutingAssembly().Location, MotoTRBO_GW.isConsoleEnabled ? " -c" : ""); Process oldProcess = Process.GetCurrentProcess(); oldProcess.Kill(); System.Windows.Forms.Application.Exit(); })); p.Start(); } private void WaitForMessageBox() { try { int count = 0; while (isMessageBoxShown) { Thread.Sleep(500); if (count++ > 13) { isMessageBoxShown = false; RestartApp(); } } } catch (Exception ex) { } } #region ARS SERVICE void StartARSService() { if (MotoTRBO_GW.cfg.capPlus) { CapacityPlus.UpdateRoutes(MotoTRBO_GW.cfg.masterRadioIP); } else { // get Interface ID RouteManager.networkID = RadioUtils.GetInterfaceID(MotoTRBO_GW.cfg.masterRadioIP); RoutingUtils.UpdateRoutes_NonCapPlus(MotoTRBO_GW.cfg.masterRadioIP, RadioUtils.GetInterface(MotoTRBO_GW.cfg.masterRadioIP), RouteManager.networkID); } // create thread to listen UDP Utils.ConsWrite(DebugMSG_Type.DB, "ARS port:" + (ushort)MotoTRBO_GW.cfg.arsPort); MotoTRBO_GW.ARSConnection = new ARSThread((ushort)MotoTRBO_GW.cfg.arsPort); //UpdateLabelEvent("Registered for ARS"); // event handler for when the connection on UDP Changes MotoTRBO_GW.ARSConnection.OnUDPConnectionChanged += new ARSThread.UDPConnectionChangedDelegate(delegate(bool isConnected, String gatewayIP) { if (isConnected) { pictureBoxArs.Image = Properties.Resources.ars_icon; pictureBoxArs.Tag = "Enabled"; UpdateLabelEvent("Registered for ARS" + (gatewayIP.Length > 0 ? " on gateway " + gatewayIP : "")); } else { pictureBoxArs.Image = Properties.Resources.ars_icon_disabled; pictureBoxArs.Tag = "Disabled"; } }); // event handler for when an ARS is received MotoTRBO_GW.ARSConnection.OnArsReceived += new ARSThread.ARSReceivedDEl(delegate(string suid, bool isOn) { UpdateLabelEvent(String.Format("ARS {0} from {1}", (isOn ? "ON" : "OFF"), suid)); }); // event handler for when the Location Request is sent MotoTRBO_GW.ARSConnection.OnTriggeredLocationRequest += new ARSThread.TriggeredLocationRequestDEl(delegate(string radioID, int reportingInterval) { UpdateLabelEvent("Location request [" + reportingInterval + " sec] for " + radioID); }); MotoTRBO_GW.ARSConnection.Start(); // start the ARS Thread which will handle all ARS messages MotoTRBO_GW.ARSThreadobj = new Thread(new ThreadStart(MotoTRBO_GW.ARSConnection.HandleConnection)); MotoTRBO_GW.ARSThreadobj.IsBackground = true; MotoTRBO_GW.ARSThreadobj.Start(); } #endregion private bool tallysmanGwStatusMessage = false; void StartTallysmanService() { //create thread for receiving Tallysman notifications from the radios TallysmanReceiveConnection = new TallysmanReceiveThread((ushort)MotoTRBO_GW.cfg.TALLYSMAN_PORT); // event handler for when the connection on UDP Changes TallysmanReceiveConnection.OnUDPConnectionChanged += new TallysmanReceiveThread.UDPConnectionChangedDelegate(delegate(bool isConnected) { if (isConnected) { //UpdateLabelEvent("Registered for Tallysman messages"); } else { } }); #region TALLYSMAN Received Events TallysmanReceiveConnection.OnLocationReceived += delegate(MotoTRBO_SOC.TallysmanReceiveThread.LocationEventArgs e) { UpdateLabelEvent(String.Format("Pos. [{0:0.0000},{1:0.0000}] from {2}{3}{4}", Math.Round(e.Latitude, 4), Math.Round(e.Longitude, 4), e.RadioID, e.Altitude > 0 ? System.Environment.NewLine + "\t Altitude [" + e.Altitude + " meters]" : "", e.LevelOfConfidence > -1 ? "" + "\t Level of confidence [" + e.LevelOfConfidence + "%]" : "")); // add the gateway status if (!tallysmanGwStatusMessage) { AddGatewayStatusMessage(MotoTRBO_GW.cfg.gw_id, (gatewayStatus) ? true : false, "TALLYSMAN CONNECTED"); tallysmanGwStatusMessage = true; } try { htCell_t cell = new htCell_t(); cell.altitude = (int)e.Altitude; cell.d_lat = e.Latitude; cell.d_lng = e.Longitude; cell.isCSBK = false; cell.lat = e.Latitude + ""; cell.level_confidence = (int)e.LevelOfConfidence; cell.lng = e.Longitude + ""; cell.location_time = (new DateTime(1970, 1, 1)).AddSeconds(e.GPSTime); cell.seqID = e.seqID; cell.spd = e.Speed + ""; cell.suid = e.RadioID + ""; cell.triggered = false; SN_Queues.DBQueueLocation.PostItem(cell); } catch (Exception ex) { Utils.WriteLine("EXCEPTION EX " + ex.ToString(), ConsoleColor.Red); } }; TallysmanReceiveConnection.OnTelemetryReceived += delegate(MotoTRBO_SOC.TallysmanReceiveThread.TelemetryReceivedEventArgs e) { UpdateLabelEvent("Telemetry from radio " + e.RadioID); }; TallysmanReceiveConnection.OnTallysmanEventReceived += delegate(MotoTRBO_SOC.TallysmanReceiveThread.TallysmanEventArgs e) { }; #endregion TallysmanReceiveThreadObj = new Thread(new ThreadStart(TallysmanReceiveConnection.handleConnection)); TallysmanReceiveThreadObj.IsBackground = true; TallysmanReceiveThreadObj.Start(); } private void AddGatewayStatusMessage(String gwCode, bool connected, string message) { //add gateway status!! GWstatus gws = new GWstatus(); gws.gw_id = gwCode; gws.status = connected ? 1 : 0; gws.message = message; SN_Queues.gwstatusQueue.PostItem(gws); } void StartEmailService() { string MyConString = "SERVER=" + MotoTRBO_GW.cfg.SERVER + ";" + "DATABASE=" + MotoTRBO_GW.cfg.DATABASE + ";" + "UID=" + MotoTRBO_GW.cfg.UID + ";" + "PASSWORD=" + MotoTRBO_GW.cfg.PASSWORD + ";Pooling=false;"; MotoTRBO_GW.emailH = new EmailHandler(MyConString, MotoTRBO_GW.cfg.gw_id); } void StartLocationService() { // create thread to listen UDP MotoTRBO_GW.LocationConnection = new LocationThread(MotoTRBO_GW.cfg.locPort); // event handler for when the connection on UDP Changes MotoTRBO_GW.LocationConnection.OnUDPConnectionChanged += new LocationThread.UDPConnectionChangedDelegate(delegate(bool isConnected) { if (isConnected) { pictureBoxPosition.Image = Properties.Resources.gps_icon; pictureBoxPosition.Tag = "Enabled"; UpdateLabelEvent("Registered for Location messages"); } else { pictureBoxPosition.Image = Properties.Resources.gps_icon_disabled; pictureBoxPosition.Tag = "Disabled"; } }); MotoTRBO_GW.LocationConnection.OnLocationReceived += new LocationThread.LocationReceivedDEl(delegate(htCell_t position) { UpdateLabelEvent(String.Format("{3} [{0:00.0000},{1:00.0000}] from {2}", Math.Round(Double.Parse(position.lat), 4), Math.Round(Double.Parse(position.lng), 4), position.suid, (position.triggered ? "Pos." : "Poll"))); }); MotoTRBO_GW.LocationConnection.OnTriggeredLocationRequest += new LocationThread.TriggeredLocationRequestDEl(delegate(string radioID, int reportingInterval) { UpdateLabelEvent("Location request [" + reportingInterval + " sec] for " + radioID); }); MotoTRBO_GW.LocationConnection.OnImmediateLocationRequest += new LocationThread.ImmediateLocationRequestDEl(delegate(string radioID) { UpdateLabelEvent("««« Poll request for " + radioID); }); //LocationConnection.port = cfg.locPort; //LocationConnection.parent = this; MotoTRBO_GW.LocationThreadobj = new Thread(new ThreadStart(MotoTRBO_GW.LocationConnection.handleConnection)); MotoTRBO_GW.LocationThreadobj.IsBackground = true; MotoTRBO_GW.LocationThreadobj.Start(); } void StartSMSService() { string MyConString = "SERVER=" + MotoTRBO_GW.cfg.SERVER + ";" + "DATABASE=" + MotoTRBO_GW.cfg.DATABASE + ";" + "UID=" + MotoTRBO_GW.cfg.UID + ";" + "PASSWORD=" + MotoTRBO_GW.cfg.PASSWORD + ";Pooling=false;"; bool isSMSInitialized = false; while (!isSMSInitialized) { try { MotoTRBO_GW.smsUDPclient = new UdpClient(MotoTRBO_GW.cfg.smsPort); MotoTRBO_GW.smsUDPclient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); //udpClient.Client.Bind(new IPEndPoint(IPAddress.Any, port)); MotoTRBO_GW.smsUDPclient.Client.ReceiveTimeout = 1000 * ReceiveSMSThread.READ_TIMEOUT; isSMSInitialized = true; pictureBoxSMS.Image = MotoTRBO_SOC.Properties.Resources.sms_icon; pictureBoxSMS.Tag = "Enabled"; Utils.WriteLine("Text message udp client initiated", ConsoleColor.Green); UpdateLabelEvent("Registered for Text messages"); } catch (Exception ex) { if (ex.ToString().Contains(" Only one usage of each socket address")) { Console.ForegroundColor = ConsoleColor.Red; Utils.ConsWrite(DebugMSG_Type.always, "UDP Port for SMS is already in use. Retry in 500 miliseconds."); Console.ForegroundColor = ConsoleColor.Gray; Thread.Sleep(500); //MessageBox.Show("UDP Port for SMS is already in use. Please try again after fixing the error.", "SMS Error"); //System.Windows.Forms.Application.Exit(); } else { Console.ForegroundColor = ConsoleColor.Red; Utils.ConsWrite(DebugMSG_Type.always, "SMS UDP Exception: " + ex.ToString()); Console.ForegroundColor = ConsoleColor.Gray; MessageBox.Show("Could not create UDP Connection for SMS. Application will now close", "SMS Error"); System.Windows.Forms.Application.Exit(); } } } // create thread to listen UDP MotoTRBO_GW.ReceiveSMSthr = new ReceiveSMSThread((ushort)MotoTRBO_GW.cfg.smsPort, MyConString, MotoTRBO_GW.cfg.gw_id); MotoTRBO_GW.ReceiveSMSthr.OnUDPConnectionChanged += new ReceiveSMSThread.UDPConnectionChangedDelegate(delegate(bool isConnected) { if (isConnected) { pictureBoxSMS.Image = Properties.Resources.sms_icon; pictureBoxPosition.Tag = "Enabled"; UpdateLabelEvent("Registered for Text messages"); } else { pictureBoxSMS.Image = Properties.Resources.sms_icon_disabled; pictureBoxPosition.Tag = "Disabled"; } }); MotoTRBO_GW.ReceiveSMSthr.OnSMSReceived += new ReceiveSMSThread.SMSReceivedDEl(ReceiveSMSthr_OnSMSReceived); //ARSConnection.parent = this; MotoTRBO_GW.ReceiveSMSThreadobj = new Thread(new ThreadStart(MotoTRBO_GW.ReceiveSMSthr.HandleConnection)); MotoTRBO_GW.ReceiveSMSThreadobj.IsBackground = true; MotoTRBO_GW.ReceiveSMSThreadobj.Start(); // create thread to listen UDP MotoTRBO_GW.SendSMSthr = new SendSMSThread(MotoTRBO_GW.cfg.smsPort); MotoTRBO_GW.SendSMSthr.OnSMSSent += new SendSMSThread.SMSSentDEl(SendSMSthr_OnSMSSent); //ARSConnection.parent = this; MotoTRBO_GW.SendSMSThreadobj = new Thread(new ThreadStart(MotoTRBO_GW.SendSMSthr.HandleConnection)); MotoTRBO_GW.SendSMSThreadobj.IsBackground = true; MotoTRBO_GW.SendSMSThreadobj.Start(); } /* Delegate which handles every SMS message received */ void ReceiveSMSthr_OnSMSReceived(String message, String radioID) { UpdateLabelEvent(String.Format("SMS [{0}] from {1}", message, radioID)); } /* Delegate which handles every SMS message is sent */ void SendSMSthr_OnSMSSent(string message, string radioID) { UpdateLabelEvent(String.Format("SMS [{0}] to {1}", message, radioID)); } /// /// Update the label from the UI in which all events are stored /// /// The message which needs to be written into the label private void UpdateLabelEvent(String message) { if (MotoTRBO_GW.running) { this.Invoke((MethodInvoker)delegate { tbEvent.AppendText(String.Format("{0:H:mm:ss} - {1}", DateTime.Now, message) + Environment.NewLine); }); } } void StartComputeAddr() { adr = new Address(); MotoTRBO_GW.CompAddrThread = new Thread(new ThreadStart(adr.Compute)); MotoTRBO_GW.CompAddrThread.IsBackground = true; MotoTRBO_GW.CompAddrThread.Start(); } private bool dragging = false; private Point dragCursorPoint; private Point dragFormPoint; private void FormMain_MouseDown(object sender, MouseEventArgs e) { dragging = true; dragCursorPoint = Cursor.Position; dragFormPoint = this.Location; } private void FormMain_MouseMove(object sender, MouseEventArgs e) { if (dragging) { Point dif = Point.Subtract(Cursor.Position, new Size(dragCursorPoint)); this.Location = Point.Add(dragFormPoint, new Size(dif)); } } private void FormMain_MouseUp(object sender, MouseEventArgs e) { dragging = false; } private void FormMain_Resize(object sender, EventArgs e) { if (FormWindowState.Minimized == this.WindowState) { this.ShowInTaskbar = false; notifyIcon.Visible = true; notifyIcon.ShowBalloonTip(500); this.Hide(); } else if (FormWindowState.Normal == this.WindowState) { notifyIcon.Visible = true; } } private void pictureBoxMinimize_MouseEnter(object sender, EventArgs e) { pictureBoxMinimize.Image = Properties.Resources.minimize_over; } private void pictureBoxMinimize_MouseLeave(object sender, EventArgs e) { pictureBoxMinimize.Image = Properties.Resources.minimize; } private void pictureBoxMinimize_Click(object sender, EventArgs e) { this.WindowState = FormWindowState.Minimized; } private void pictureBoxClose_MouseEnter(object sender, EventArgs e) { pictureBoxClose.Image = Properties.Resources.close_over; } private void pictureBoxClose_MouseLeave(object sender, EventArgs e) { pictureBoxClose.Image = Properties.Resources.close; } private void pictureBoxClose_Click(object sender, EventArgs e) { LOGS.LOG("#####################"); LOGS.LOG("Application ended by user"); LOGS.LOG("#####################"); /* GWstatus gws = new GWstatus(); gws.gw_id = MotoTRBO_GW.cfg.gw_id; gws.status = (gatewayStatus) ? 1 : 0; gws.message = "Gateway is closing!!!"; SN_Queues.gwstatusQueue.PostItem(gws); // wait for Gateway Status message to be addded into DB Thread.Sleep(300); */ //StopDBService(); /* Process oldProcess = Process.GetCurrentProcess(); oldProcess.WaitForExit(1000); oldProcess.Kill(); */ if(this.InvokeRequired) { this.Invoke((MethodInvoker)delegate { this.Close(); }); } else System.Environment.Exit(0); } private void notifyIcon_DoubleClick(object sender, MouseEventArgs e) { this.Show(); this.ShowInTaskbar = true; this.WindowState = FormWindowState.Normal; } private void FormMain_FormClosing(object sender, FormClosingEventArgs e) { MotoTRBO_GW.running = false; if (MotoTRBO_GW.DBConnection != null) MotoTRBO_GW.DBConnection.StopDB(); // close the ars connection if (MotoTRBO_GW.ARSConnection != null) MotoTRBO_GW.ARSConnection.StopARSThread(); // close the location connection if (MotoTRBO_GW.LocationConnection != null) MotoTRBO_GW.LocationConnection.Stop(); if (TallysmanReceiveConnection != null) TallysmanReceiveConnection.Stop(); // close the sms client if(MotoTRBO_GW.smsUDPclient != null) { MotoTRBO_GW.smsUDPclient.Close(); MotoTRBO_GW.smsUDPclient = null; } if (adr != null) adr.StopAddressThread(); CloseNotifyIcon(); pictureBoxClose_Click(sender, null); } private void pictureBoxSettings_Click(object sender, EventArgs e) { // display the settings form SettingsForm sf = new SettingsForm(); sf.OnCommandRequested += delegate(String uiMessage) { UpdateLabelEvent(uiMessage); }; // display the form over this form sf.Location = this.Location; // restart app if selected sf.OnRestartSelected += delegate() { labelGwStatus.Text = "Restarting..."; RestartApp(); }; sf.ShowDialog(); } private void OnApplicationExit(object sender, EventArgs e) { CloseNotifyIcon(); } private void CloseNotifyIcon() { if (notifyIcon != null) { notifyIcon.Visible = false; notifyIcon.Icon = null; notifyIcon.Dispose(); } } /// /// Check for new version release on SafeMobile Portal /// The check is done by comparing Current Assembly Version with the one /// written in a xml file on the portal. /// private void CheckForUpdate() { //Uncomment below line to see Russian version //AutoUpdater.CurrentCulture = CultureInfo.CreateSpecificCulture("ru-RU"); //If you want to open download page when user click on download button uncomment below line. //AutoUpdater.OpenDownloadPage = true; //Don't want user to select remind later time in AutoUpdater notification window then uncomment 3 lines below so default remind later time will be set to 2 days. //AutoUpdater.LetUserSelectRemindLater = false; //AutoUpdater.RemindLaterTimeSpan = RemindLaterFormat.Days; //AutoUpdater.RemindLaterAt = 2; bool isDevelope = false; if(MotoTRBO_GW.cfg.autoupdate) AutoUpdater.Start("http://portal.safemobile.com/upload/safenet/updates" + (isDevelope ? "/develop" : "/production") +"/conventional/safenet_trbo_gateway.xml"); } private void pictureBox2_Click(object sender, EventArgs e) { System.Diagnostics.Process.Start("https://safenet.safemobile.com/"); } int count = 0; private void labelVersion_DoubleClick(object sender, EventArgs e) { count++; if (count >= 3) { DebugCmd cmd = new DebugCmd(); cmd.ShowDialog(); count = 0; } } } }