SafeDispatch/MotoRepeaterCore/MainForm.cs

875 lines
34 KiB
C#

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Diagnostics;
using System.Threading;
using System.Text.RegularExpressions;
using SafeMobileLib;
using System.Collections;
using SharedUI;
using SafeMobileLib.Registration;
namespace MotoRepeater
{
public partial class MainForm : Form
{
// save the version of the application server in order to use it for the updater
public static String APP_SERVER_VERSION = "";
private MotoRepeater_GW gateway;
private BackgroundWorker bgWorkerRegistration;
private TcpClient client;
private Boolean registeredIP;
public string LocalIPaddress = "";
// database connection to get the config parameters and the units
private DBhandle DB;
public MainForm()
{
Utils.WriteLine("Safenet MotoRepeater Gateway. SafeMobile 2015");
Utils.WriteLine("");
InitializeComponent();
// load the configuration file
LoadConfig();
Version v = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
Utils.WriteLine(lbVersion.Text = ("Version: " + v.ToString()));
this.Text += " " + v.ToString();
lbStatus.Text = "No connection. Please press connect.";
LoadSettings_GUI();
lbStatus.Text = "Registrating";
btnConnect.Enabled = false;
this.WindowState = FormWindowState.Minimized;
this.Visible = false;
Repeater_Notify_Icon.Visible = true;
Repeater_Notify_Icon.ShowBalloonTip(500);
}
private void MainForm_Load(object sender, EventArgs e)
{
ContextMenu contextMenu = new ContextMenu();
contextMenu.MenuItems.Add("Check for updates...", (s, e2) => {
UpdateForm uf = new UpdateForm(App.GW_REPEATER, true) { IsDevelop = MotoRepeater_GW.cfg.isDevelope };
uf.Show();
});
contextMenu.MenuItems.Add("Exit", (s, e2) => CloseApp());
Repeater_Notify_Icon.ContextMenu = contextMenu;
HideAllPanels();
OnMenuButtonClick(menuView, null);
this.Visible = false;
// check if the application is already running
if (testIfAlreadyRunning())
{
Process[] processlist = Process.GetProcesses();
Process curentP = Process.GetCurrentProcess();
Utils.WriteLine("App already running!!!");
MessageBox.Show("Aplication already running!!", "error", MessageBoxButtons.OK);
foreach (Process theprocess in processlist)
{
if (theprocess.ProcessName.Equals(curentP.ProcessName) && !curentP.ProcessName.Contains("vshost"))
{
Console.WriteLine("Process: {0} ID: {1}", theprocess.ProcessName, theprocess.Id);
Console.WriteLine("Curent Process: {0} ID: {1}", curentP.ProcessName, curentP.Id);
if (theprocess.Id != curentP.Id)
{
Console.WriteLine("Killing Process: {0} ID: {1}", theprocess.ProcessName, theprocess.Id);
theprocess.Kill();
}
}
}
Thread.Sleep(1000);
}
switch (MotoRepeater_GW.appType)
{
case AppType.SAFEDISPATCH:
{
Utils.WriteLine("SAFEDISPATCH", ConsoleColor.Cyan);
bgWorkerRegistration = new BackgroundWorker();
bgWorkerRegistration.DoWork += new DoWorkEventHandler(bgWorkerRegistration_DoWork);
bgWorkerRegistration.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorkerRegistration_RunWorkerCompleted);
bgWorkerRegistration.RunWorkerAsync();
break;
}
}
// Load Units
//MotoTRBO_GW.unitsLoaded = DB.LoadUnitInfo(gatewayID);
}
#region UPDATE
/// <summary>
/// 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.
/// </summary>
private void CheckForUpdate(bool isModal)
{
App appType = App.GW_REPEATER;
if (isModal)
{
UpdateForm uf = new UpdateForm(appType, true) { IsDevelop = MotoRepeater_GW.cfg.isDevelope };
uf.ShowDialog();
}
else
{
AutoUpdate au = new AutoUpdate(appType) { IsDevelop = MotoRepeater_GW.cfg.isDevelope };
au.OnNewVersionAvailable += delegate (string version)
{
if (APP_SERVER_VERSION.Split('.')[2].Equals(version.Split('.')[2]))
{
Repeater_Notify_Icon.Text = "New version available";
Repeater_Notify_Icon.ShowBalloonTip(2500, $"{App.GetAppName(appType)} version {version} available",
$"Press to download and install the latest version of {App.GetAppName(appType)}.", ToolTipIcon.Info);
Repeater_Notify_Icon.BalloonTipClicked += delegate (object sender, EventArgs e)
{
if (Repeater_Notify_Icon.Text.Equals("New version available"))
{
UpdateForm uf = new UpdateForm(appType, true) { IsDevelop = MotoRepeater_GW.cfg.isDevelope };
uf.Show();
}
};
}
else
SafeMobileLib.Utils.WriteLine("New version available but AppServer is an old version stil");
};
// call method to check for new updated
au.CheckUpdate();
}
}
#endregion
/// <summary>
/// Load the configuration parameters for the DataBase
/// </summary>
/// <returns>A confirmation that the configurations were successfully loaded, or a negativ
/// response in case something went wrong</returns>
private bool LoadConfig()
{
bool ret = false;
try
{
MotoRepeater_GW.cfg = new Config();
MotoRepeater_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 it or contact " +
"support@safemobil.com. "
+ System.Environment.NewLine + System.Environment.NewLine + "Thank you!", "Reconfiguration needed",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
};
MotoRepeater_GW.cfg.LoadConfig(MotoRepeater_GW.appType);
ret = true;
}
catch (Exception ex)
{
Utils.WriteLine("Unable to parse Config File: " + ex.ToString(), ConsoleColor.Red);
}
return ret;
}
/// <summary>
/// Check if the application is already running in order to prevent it from running multiple
/// </summary>
private bool testIfAlreadyRunning()
{
Process[] processlist = Process.GetProcesses();
Process curentP = Process.GetCurrentProcess();
int count = 0;
foreach (Process theprocess in processlist)
{
if (theprocess.ProcessName.Equals(curentP.ProcessName) && !curentP.ProcessName.Contains("vshost"))
{
count++;
}
}
if (count > 1)
{
return true;
}
return false;
}
private void ContinueConstructor()
{
Utils.WriteLine("########################", ConsoleColor.Red);
//lbStatus.Text = "Gateway registered. Please press Connect.";
lbStatus.Text = "Offline";
btnConnect.Enabled = true;
gateway = new MotoRepeater_GW();
gateway.PropertyChanged += new PropertyChangedEventHandler(gateway_PropertyChanged);
gateway.OnEventToDisplayOnUI += new MotoRepeater_GW.EventToDisplayOnUIDEl(UpdateLabelEvent);
gateway.Start();
if (MotoRepeater_GW.cfg.SLOT1_VOICE || MotoRepeater_GW.cfg.SLOT2_VOICE)
gateway.StartLinkEstablishment();
try
{
Utils.WriteEventLog("Safemobile", "Moto repGateway Gateway ON", EventLogEntryType.Information, 2152);
}
catch (Exception ex)
{
Utils.WriteLine("Unable to write log event : " + ex.ToString(), ConsoleColor.Red);
}
// check for a new version if available
if (MotoRepeater_GW.cfg.autoupdate)
CheckForUpdate(false);
}
private void btnSave_Click(object sender, EventArgs e)
{
}
private void LoadSettings_GUI()
{
//MUPS
tbDDMSip.Text = MotoRepeater_GW.cfg.DDMS_IP.ToString();
npDDMSport.Text = MotoRepeater_GW.cfg.DDMS_PORT.ToString();
npARSPort.Text = MotoRepeater_GW.cfg.ARS_PORT.ToString();
npGPSport.Text = MotoRepeater_GW.cfg.GPS_PORT.ToString();
npTMport.Text = MotoRepeater_GW.cfg.SMS_PORT.ToString();
npTelemPort.Text = MotoRepeater_GW.cfg.TELEMETRY_PORT.ToString();
//message buss
tbMBip.Text = MotoRepeater_GW.cfg.MBUS_IP;
npMBport.Text = MotoRepeater_GW.cfg.MBUS_PORT.ToString();
//DataBAse
//tbDBip.Text = MotoRepeater_GW.cfg.DB_IP;
//tbDBport.Text = MotoRepeater_GW.cfg.DB_port;
// NAI
npPeerID.Text = MotoRepeater_GW.cfg.PEER_ID.ToString();
npPeerPort.Text = MotoRepeater_GW.cfg.PEER_PORT.ToString();
tbMasterRepeaterIP.Text = MotoRepeater_GW.cfg.MASTER_IP;
npMasterRepeaterPort.Text = MotoRepeater_GW.cfg.MASTER_PORT.ToString();
tbAuthenticationKey.Text = MotoRepeater_GW.cfg.AUTHENTICATION_KEY;
cbNetworkType.Text = LinkEstablishment.GetStringSystemType(MotoRepeater_GW.cfg.SYSTEM_TYPE);
lbGateway.Text = "peer " + MotoRepeater_GW.cfg.PEER_ID.ToString() + " status";
}
private void btnConnect_Click(object sender, EventArgs e)
{
/*
btnConnect.Enabled = false;
if (gateway.registered != REP_STATUS.started)
{
gateway.Start();
//gateway.StartLinkEstablishment();
}
else
{
//gateway.Stop();
}
* */
}
delegate void PropertyChangedCallback(REP_STATUS register);
void gateway_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
Utils.WriteLine("### GATEWAY RADIO STATUS IS " + ((MotoRepeater_GW)sender).registered);
//SM.Debug("New value for radio status:" + );
PropertyChangedCallback d = new PropertyChangedCallback(RegStatusChanged);
this.Invoke(d, new object[] { ((MotoRepeater_GW)sender).registered });
}
private void RegStatusChanged(REP_STATUS rStatus)
{
if (rStatus == REP_STATUS.started)
{
lbStatus.Text = "Online";
btnConnect.Enabled = false;
}
else if (rStatus == REP_STATUS.ddmsUP)
{
lbStatus.Text = "Online";
btnConnect.Enabled = false;
UpdateLabelEvent("DDMS is now connected");
}
else if (rStatus == REP_STATUS.ddmsDOWN)
{
lbStatus.Text = "DDMS is down";
btnConnect.Text = "Stop";
UpdateLabelEvent("DDMS is now disconnected");
}
else
{
lbStatus.Text = "Offline";
btnConnect.Text = "Stop";
}
}
private void getGwConfiguration(int gatewayID)
{
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (gateway != null)
gateway.Stop();
}
/// <summary>
/// Close necessary things before closing the app
/// </summary>
private void CloseApp()
{
if (gateway != null)
gateway.Stop();
Process oldProcess = Process.GetCurrentProcess();
oldProcess.Kill();
Application.Exit();
}
// save all UI elements
private void menuSave_Click(object sender, EventArgs e)
{
try
{
MotoRepeater_GW.cfg.DDMS_IP = tbDDMSip.Text;
Config.UpdateConfigParameter("GATEWAY", "ddmsip", MotoRepeater_GW.cfg.DDMS_IP);
MotoRepeater_GW.cfg.DDMS_PORT = int.Parse(npDDMSport.Text);
Config.UpdateConfigParameter("GATEWAY", "ddms_port", MotoRepeater_GW.cfg.DDMS_PORT+"");
MotoRepeater_GW.cfg.ARS_PORT = int.Parse(npARSPort.Text);
Config.UpdateConfigParameter("GATEWAY", "ars_port", MotoRepeater_GW.cfg.ARS_PORT + "");
MotoRepeater_GW.cfg.GPS_PORT = int.Parse(npGPSport.Text);
Config.UpdateConfigParameter("GATEWAY", "gps_port", MotoRepeater_GW.cfg.GPS_PORT + "");
MotoRepeater_GW.cfg.SMS_PORT = int.Parse(npTMport.Text);
Config.UpdateConfigParameter("GATEWAY", "tm_port", MotoRepeater_GW.cfg.SMS_PORT + "");
MotoRepeater_GW.cfg.TELEMETRY_PORT = int.Parse(npTelemPort.Text);
Config.UpdateConfigParameter("GATEWAY", "tallysman_port", MotoRepeater_GW.cfg.TELEMETRY_PORT + "");
/*
MotoRepeater_GW.cfg.MBUS_IP = tbMBip.Text;
Config.UpdateConfigParameter("MESSAGEBUS", "ip", MotoRepeater_GW.cfg.MBUS_IP);
MotoRepeater_GW.cfg.MBUS_PORT = int.Parse(npMBport.Text);
Config.UpdateConfigParameter("MESSAGEBUS", "port", MotoRepeater_GW.cfg.MBUS_PORT + "");
*/
// blocked in the DB
//MotoRepeater_GW.cfg.PEER_ID = Int64.Parse(npPeerID.Text);
//MotoRepeater_GW.cfg.MASTER_IP = tbMasterRepeaterIP.Text;
MotoRepeater_GW.cfg.PEER_PORT = int.Parse(npPeerPort.Text);
Config.UpdateConfigParameter("NAI", "peerPort", MotoRepeater_GW.cfg.PEER_PORT + "");
MotoRepeater_GW.cfg.MASTER_PORT = int.Parse(npMasterRepeaterPort.Text);
Config.UpdateConfigParameter("NAI", "masterRepeaterPort", MotoRepeater_GW.cfg.MASTER_PORT + "");
MotoRepeater_GW.cfg.AUTHENTICATION_KEY = tbAuthenticationKey.Text;
Config.UpdateConfigParameter("NAI", "authenticationKey", MotoRepeater_GW.cfg.AUTHENTICATION_KEY);
MotoRepeater_GW.cfg.SYSTEM_TYPE = LinkEstablishment.GetSystemType(cbNetworkType.Text);
Config.UpdateConfigParameter("NAI", "networkType", LinkEstablishment.GetSystemTypeForConfig(MotoRepeater_GW.cfg.SYSTEM_TYPE));
//MotoRepeater_GW.cfg.SaveCFGFile();
MessageBox.Show("Configs saved to file. Please restart the gateway for this settings to be used.");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
#region SAFEDISPATCH BG WORKER EVENTS
void bgWorkerRegistration_DoWork(object sender, DoWorkEventArgs e)
{
registeredIP = getRegistration();
}
void bgWorkerRegistration_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// verrify if the App Server is running
if (appServerMissing)
{
MessageBox.Show("Could not reach Application Server. Please check the connection and try again!!!", "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
System.Environment.Exit(0);
}
// check if the gateway is registered into Admin Module
if (!registeredIP)
{
btnConnect.Enabled = false;
MessageBox.Show("Please register your copy of MotoRepeater Gateway using the Administrative Module.\n Your IP address is:" + LocalIPaddress, "Info", MessageBoxButtons.OK);
System.Environment.Exit(0);
}
else if (registeredIP && !App.isValidVersion(APP_SERVER_VERSION,
System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()))
{
DialogResult dr = MessageBox.Show("Please update your version of software to the latest one required by Application Server. Do you wish to update now?",
"Update required...", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);
if (dr == DialogResult.Yes)
{
CheckForUpdate(true);
Application.Exit();
}
else
Application.Exit();
}
else if (registeredIP)
{
MotoRepeater_GW.cfg.DB_DATABASE = regResponse.DataBaseName;
MotoRepeater_GW.cfg.DB_PASSWORD = regResponse.DataBasePassword;
MotoRepeater_GW.cfg.DB_PORT = regResponse.DataBasePort+"";
MotoRepeater_GW.cfg.DB_SERVER = regResponse.DataBaseServerIP;
MotoRepeater_GW.cfg.DB_USERNAME = regResponse.DataBaseUser;
MotoRepeater_GW.cfg.MBUS_IP = regResponse.MessageBusIP;
MotoRepeater_GW.cfg.MBUS_PORT = regResponse.MessageBusPort;
// get the list of radio gateways.
bool result = GetRadioGWsList();
// continue with initializing the LE connection and others
if (result)
ContinueConstructor();
}
}
private bool appServerMissing = false;
private RegistrationResponse regResponse;
/// <summary>
/// Get the status of this gateway, meaning that a check if the gateway is flaged as a registered
/// gateway into the App Server data
/// </summary>
/// <returns>True is the gateway is valid, or false is the registration fails for any reason</returns>
private Boolean getRegistration()
{
Boolean toReturn = false;
try
{
client = new TcpClient();
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse(MotoRepeater_GW.cfg.APPLICATION_SERVER_IP), MotoRepeater_GW.cfg.MBUS_REG_PORT);
client.Connect(serverEndPoint);
NetworkStream clientStream = client.GetStream();
LocalIPaddress = (client.Client.LocalEndPoint.ToString().Split(':'))[0];
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
byte[] buffer = encoding.GetBytes("200");
//encryption doesn't work, to be added when working
//byte[] encodedBuffer = Encryption.Encrypt(buffer);
clientStream.Write(buffer, 0, buffer.Length);
//Utils.WriteLine(ConsoleType.ALL, "Sent registration request to server, waiting...");
byte[] message = new byte[128];
//set read timeout to 10s
clientStream.ReadTimeout = 10000;
int result = clientStream.Read(message, 0, message.Length);
//close waiting thread
//byte[] decodedMessage = Encryption.Decrypt(message);
//Console.WriteLine("Received registration from server");
String decodedString = encoding.GetString(message).Trim('\0');
regResponse = new RegistrationResponse(decodedString);
String[] options = decodedString.Split(';');
if (options[0].Equals("201"))
{
Utils.WriteLine(String.Format("Gateway is {0}", options[1].StartsWith("invalid") ? "not registered!" : "registerd"), ConsoleColor.Cyan, ConsoleType.ALL);
UpdateLabelEvent(String.Format("Gateway is {0}", options[1].StartsWith("invalid") ? "not registered!" : "registerd"));
if (options[1].StartsWith("invalid"))
{
toReturn = false;
}
else
{
APP_SERVER_VERSION = options[1].Replace("valid-", "");
toReturn = true;
}
}
}
catch (Exception ex)
{
Console.WriteLine("Exception in gateway:getRegistration():" + ex.ToString(), ConsoleColor.DarkRed);
appServerMissing = true;
}
return toReturn;
}
/// <summary>
/// Get the list o Radio Gateways attached to this Gateway
/// </summary>
private bool GetRadioGWsList()
{
if (!registeredIP)
{
MessageBox.Show("Please register your copy of MotoRepeater Gateway using the Administrative Module.\n Your IP address is:" + LocalIPaddress);
System.Windows.Forms.Application.Exit();
return false;
}
else
{
//new code
List<Gateway> listGW = new List<Gateway>();
try
{
// get the Gateway ID from the database using the local IP address
listGW = getGWidFromDB(LocalIPaddress);
// if no gateway is received using the local IP address
if (listGW.Count == 0)
{
// get the gateways using localhost IP
if (MotoRepeater_GW.cfg.DB_SERVER.Contains("127.0.0.1") || (MotoRepeater_GW.cfg.DB_SERVER.ToUpper().Contains("LOCALHOST")))
listGW = getGWidFromDB("127.0.0.1");
}
else
{
// if the list of gateways contains items I should check to see if my GW ID is still
// in the Admin Module
if (MotoRepeater_GW.cfg.GWID != -1)
{
Boolean find = false;
foreach (Gateway obj in listGW)
if (obj.Id == MotoRepeater_GW.cfg.GWID)
{
find = true;
break;
}
// if the previous GW ID is not founnd, then test for gateway ID with localhost IP
if ((!find) && (MotoRepeater_GW.cfg.DB_SERVER.Contains("127.0.0.1") || (MotoRepeater_GW.cfg.DB_SERVER.ToUpper().Contains("LOCALHOST"))))
listGW = getGWidFromDB("127.0.0.1");
}
}
}
catch (Exception ex)
{
SM.Debug("Ex on find automat the gateway ID:" + ex.ToString());
return false;
}
try
{
// check to see if the IP address was found in the Admin Module
if (listGW.Count == 0)
{
MessageBox.Show("Gateway IP not present in DB\n\r Please go to Administrative module and register this GW with IP:!!!" + LocalIPaddress);
//System.Environment.Exit(0);
System.Windows.Forms.Application.Exit();
return false;
}
else
{
Utils.WriteLine("Gateway ID is " + ((Gateway)listGW[0]).Id, ConsoleColor.Cyan);
Utils.WriteLine("Peer ID is " + ((Gateway)listGW[0]).Peer_id, ConsoleColor.Cyan);
// save the new gateway ID into the loaded config file
MotoRepeater_GW.cfg.GWID = ((Gateway)listGW[0]).Id;
MotoRepeater_GW.cfg.PEER_ID = ((Gateway)listGW[0]).Peer_id;
// exit if the configured gateway is not a repeater one
if (((Gateway)listGW[0]).Peer_id == 0)
{
MessageBox.Show("Please register a repeater gateway in the Admin Module.");
System.Windows.Forms.Application.Exit();
}
// update value into UI
npPeerID.Value = ((Gateway)listGW[0]).Peer_id;
lbGateway.Text = "peer " + MotoRepeater_GW.cfg.PEER_ID.ToString() + " status";
// update the radio ID inside the config file
Config.UpdateConfigParameter("GATEWAY", "id", (((Gateway)listGW[0]).Id).ToString());
// update the peer ID inside the config file
Config.UpdateConfigParameter("NAI", "peerID", (((Gateway)listGW[0]).Peer_id).ToString());
// get all radio gateways for this gateway
MotoRepeater_GW.radioGWs = getRadioGWsFromDB(MotoRepeater_GW.cfg.GWID);
// update the repeater ip based on the radioGWs IP
if (MotoRepeater_GW.radioGWs.Count > 0)
{
tbMasterRepeaterIP.Text = MotoRepeater_GW.radioGWs[0].Ip;
bool hasVoice = MotoRepeater_GW.radioGWs[0].Gw_voice > 0;
MotoRepeater_GW.cfg.SLOT1_VOICE = hasVoice;
MotoRepeater_GW.cfg.SLOT2_VOICE = hasVoice;
MotoRepeater_GW.cfg.SaveConfigOption("GATEWAY", "voice", hasVoice ? "true" : "false");
}
}
}
catch (Exception ex)
{
SM.Debug("DB error!!!");
SM.Debug(ex.ToString());
Utils.WriteLine("DB error.\n\rPlease turn down the firewall or add an exception for the Datebase in the firewall and try again!!!\n\r DB ip:" + LocalIPaddress, ConsoleColor.DarkRed);
MessageBox.Show("DB error.\n\rPlease turn down the firewall or add an exception for the Datebase in the firewall and try again!!!\n\r DB ip:" + LocalIPaddress);
//System.Environment.Exit(0);
System.Windows.Forms.Application.Exit();
return false;
}
}
return true;
}
/// <summary>
/// Get the list of GWs that are registered with the selected IP address
/// </summary>
/// <param name="currentIP">IP address of the server where the GWs are registered</param>
/// <returns></returns>
private List<Gateway> getGWidFromDB(string currentIP)
{
DBgatewaysManager dbmanager = new DBgatewaysManager(MotoRepeater_GW.cfg.DB_SERVER, MotoRepeater_GW.cfg.DB_DATABASE,
MotoRepeater_GW.cfg.DB_USERNAME, MotoRepeater_GW.cfg.DB_PASSWORD, MotoRepeater_GW.cfg.DB_PORT);
// bring all the gateways from the DB
List<Gateway> list = dbmanager.getAllGateways();
List<Gateway> listtoreturn = new List<Gateway>();
// itterate through all the gateways and see which one is registered to the desired IP
foreach (Gateway g in list)
{
if (g.Ip == currentIP)
{
SM.Debug("Gateway IP found in registration tabel. ID:" + g.Id);
listtoreturn.Add(g);
}
}
return listtoreturn;
}
private List<RadioGateway> getRadioGWsFromDB(Int64 gatewayID)
{
DBgatewaysManager dbmanager = new DBgatewaysManager(MotoRepeater_GW.cfg.DB_SERVER, MotoRepeater_GW.cfg.DB_DATABASE,
MotoRepeater_GW.cfg.DB_USERNAME, MotoRepeater_GW.cfg.DB_PASSWORD, MotoRepeater_GW.cfg.DB_PORT);
List<RadioGateway> list = dbmanager.gelAllRadioGateways(MotoRepeater_GW.cfg.GWID);
List<RadioGateway> listtoreturn = new List<RadioGateway>();
foreach (RadioGateway g in list)
listtoreturn.Add(g);
return listtoreturn;
}
#endregion
#region MENU BUTTONS
private void OnMenuButtonClick(object sender, EventArgs e)
{
SetWhiteBackgroundAndGrayFont();
HideAllPanels();
((Label)sender).BackColor = Color.DodgerBlue;
((Label)sender).ForeColor = Color.White;
if (sender == menuView)
{
panelView.BringToFront();
panelView.Visible = true;
}
else if (sender == menuNAI)
{
panelNAI.BringToFront();
panelNAI.Visible = true;
}
else if (sender == menuDDMS)
{
panelDDMS.BringToFront();
panelDDMS.Visible = true;
}
else if (sender == menuPorts)
{
panelPorts.BringToFront();
panelPorts.Visible = true;
}
else if (sender == menuSave)
{
}
}
private void SetWhiteBackgroundAndGrayFont()
{
menuView.BackColor = Color.Transparent;
menuView.ForeColor = Color.DarkGray;
menuNAI.BackColor = Color.Transparent;
menuNAI.ForeColor = Color.DarkGray;
menuPorts.BackColor = Color.Transparent;
menuPorts.ForeColor = Color.DarkGray;
menuDDMS.BackColor = Color.Transparent;
menuDDMS.ForeColor = Color.DarkGray;
menuSave.BackColor = Color.Transparent;
menuSave.ForeColor = Color.DarkGray;
}
private void HideAllPanels()
{
panelView.Visible = false;
panelView.SendToBack();
panelNAI.Visible = false;
panelNAI.SendToBack();
panelMessageBus.Visible = false;
panelMessageBus.SendToBack();
panelPorts.Visible = false;
panelPorts.SendToBack();
panelDDMS.Visible = false;
panelDDMS.SendToBack();
}
#endregion
/// <summary>
/// Update the label from the UI in which all events are stored
/// </summary>
/// <param name="message">The message which needs to be written into the label</param>
private void UpdateLabelEvent(String message)
{
this.Invoke((MethodInvoker)delegate
{
if (tbEvent.Lines.Length > 200)
tbEvent.Text = "";
tbEvent.BackColor = Color.White;
// remove a line
/*
if (Regex.Matches(labelEvent.Text, Environment.NewLine).Count >= labelEventMaxLines)
labelEvent.Text = labelEvent.Text.Substring(labelEvent.Text.IndexOf(Environment.NewLine) + 1);
*/
// add message at which the date is added
tbEvent.AppendText(String.Format("{0:H:mm:ss} - {1}", DateTime.Now, message) + Environment.NewLine);
tbEvent.ScrollToCaret();
});
}
#region UI Mouse Events
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 pictureBoxMinimize_MouseEnter(object sender, EventArgs e)
{
pictureBoxMinimize.Image = MotoRepeater.Properties.Resources.minimize_over;
}
private void pictureBoxMinimize_MouseLeave(object sender, EventArgs e)
{
pictureBoxMinimize.Image = MotoRepeater.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 = MotoRepeater.Properties.Resources.close_over;
}
private void pictureBoxClose_MouseLeave(object sender, EventArgs e)
{
pictureBoxClose.Image = MotoRepeater.Properties.Resources.close;
}
#endregion
private void pictureBoxClose_Click(object sender, EventArgs e)
{
// stop any service
// close process
System.Windows.Forms.Application.Exit();
}
private void Repeater_Notify_Icon_DoubleClick(object sender, EventArgs e)
{
this.Visible = true;
this.WindowState = FormWindowState.Normal;
Repeater_Notify_Icon.Visible = false;
}
private void MainForm_Resize(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Minimized)
{
this.Visible = false;
Repeater_Notify_Icon.Visible = true;
}
}
}
}