SafeDispatch/MotoRepeaterCore/SafeNetForm.cs
2024-02-22 18:43:59 +02:00

685 lines
25 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 SafeMobileLib;
using System.Diagnostics;
using System.Threading;
using System.Collections;
using AutoUpdaterDotNET;
namespace MotoRepeater
{
public partial class SafeNetForm : Form
{
private MotoRepeater_GW gateway;
public string LocalIPaddress = "";
// database connection to get the config parameters and the units
private DBhandle DB;
private Thread ThreadUIRefresh;
public SafeNetForm()
{
InitializeComponent();
// set the form result
this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
// check Credentials
Utils.WriteLine("SAFENET", ConsoleColor.Red);
// Load the Database configuration
LoadConfig();
/*
if (MotoRepeater_GW.cfg.GWCODE == 0)
{
LoginForm lf = new LoginForm();
lf.ShowDialog();
DialogResult dr = lf.DialogResult;
if (lf.DialogResult == System.Windows.Forms.DialogResult.OK)
{
// nothing to do here, all went fine
}
else
{
Load += (s, e) => Close();
MotoRepeater_GW.isRunning = false;
return;
}
}*/
// write the username and then move the label to be at the same right corner location
int rightCorner = lbUsername.Location.X + lbUsername.Size.Width;
lbUsername.Text = MotoRepeater_GW.cfg.USERNAME.ToUpper();
lbUsername.Location = new Point(rightCorner - lbUsername.Size.Width, lbUsername.Location.Y);
lbPeerStatus.Text = "peer id " + MotoRepeater_GW.cfg.PEER_ID + " status";
pbButton_Click(pbOverview, null);
Utils.WriteLine("Safenet MotoRepeater Gateway. SafeMobile 2015");
Utils.WriteLine("");
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.";
lbStatus.Text = "Registrating";
/*
this.WindowState = FormWindowState.Minimized;
this.Visible = false;
Repeater_Notify_Icon.Visible = true;
Repeater_Notify_Icon.ShowBalloonTip(500);
*/
}
private void SafeNetForm_Load(object sender, EventArgs e)
{
if (MotoRepeater_GW.cfg.AUTOUPDATE)
AutoUpdater.Start("http://portal.safemobile.com/upload/safenet/updates/safenet_repeater_gateway.xml");
}
private void SafeNetForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (gateway != null)
gateway.Stop();
}
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;
}
}
private void ContinueConstructor()
{
Utils.WriteLine("######################## Gateway Code " + MotoRepeater_GW.cfg.GWCODE + " | ID: " +
MotoRepeater_GW.cfg.GWID , ConsoleColor.Red);
//lbStatus.Text = "Gateway registered. Please press Connect.";
lbStatus.Text = "Offline";
gateway = new MotoRepeater_GW();
gateway.PropertyChanged += new PropertyChangedEventHandler(gateway_PropertyChanged);
gateway.OnEventToDisplayOnUI += new MotoRepeater_GW.EventToDisplayOnUIDEl(UpdateLabelEvent);
gateway.OnGPSInsertedBlocked += Gateway_OnGPSInsertedBlocked;
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);
}
}
private void Gateway_OnGPSInsertedBlocked()
{
RestartApp();
}
delegate void PropertyChangedCallback(REP_STATUS register);
void gateway_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (MotoRepeater_GW.isRunning)
{
Utils.WriteLine("### GATEWAY RADIO STATUS IS " + ((MotoRepeater_GW)sender).registered);
//SM.Debug("New value for radio status:" + );
PropertyChangedCallback d = new PropertyChangedCallback(RegStatusChanged);
try
{
this.Invoke(d, new object[] { ((MotoRepeater_GW)sender).registered });
}
catch (Exception ex) { }
}
}
private void RegStatusChanged(REP_STATUS rStatus)
{
if (rStatus == REP_STATUS.started)
{
lbStatus.Text = "DDMS Online";
}
else if (rStatus == REP_STATUS.ddmsUP)
{
lbStatus.Text = "DDMS Online";
UpdateLabelEvent("DDMS is now connected");
}
else if (rStatus == REP_STATUS.ddmsDOWN)
{
lbStatus.Text = "DDMS is down";
UpdateLabelEvent("DDMS is now disconnected");
}
else
lbStatus.Text = "Offline";
}
/// <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);
//System.Environment.Exit(0);
};
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;
}
private void LoadSettings_GUI()
{
numericARSPort.Value = MotoRepeater_GW.cfg.ARS_PORT;
numericDDMSPort.Value = MotoRepeater_GW.cfg.DDMS_PORT;
numericLocationPort.Value = MotoRepeater_GW.cfg.GPS_PORT;
numericPeerId.Value = MotoRepeater_GW.cfg.PEER_ID;
numericRepeaterPort.Value = MotoRepeater_GW.cfg.MASTER_PORT;
numericTelemetryPort.Value = MotoRepeater_GW.cfg.TELEMETRY_PORT;
numericTextPort.Value = MotoRepeater_GW.cfg.SMS_PORT;
tbDDMSIP.Text = MotoRepeater_GW.cfg.DDMS_IP;
tbRepeaterIP.Text = MotoRepeater_GW.cfg.MASTER_IP;
lbSystemType.Text = Config.GetSystemTypeFromConfig(Config.GetSystemTypeForConfig(MotoRepeater_GW.cfg.SYSTEM_TYPE));
tbAuthKey.Text = MotoRepeater_GW.cfg.AUTHENTICATION_KEY;
}
/// <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)
{
try
{
this.Invoke((MethodInvoker)delegate
{
tbEvent.BackColor = Color.FromArgb(34, 34, 34);
// 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:HH:mm:ss} - {1}", DateTime.Now, message) + Environment.NewLine);
});
}
catch (Exception ex)
{
Utils.WriteLine("Invoke error" + ex.ToString(), ConsoleColor.Red);
}
}
#region UI
private void pbSystemType_Click(object sender, EventArgs e)
{
cbSystemType.DroppedDown = !cbSystemType.DroppedDown;
}
private void pbSystemType_MouseEnter(object sender, EventArgs e)
{
lbSystemType.BackColor = Color.FromArgb(17, 61, 66);
pbSystemType.Image = MotoRepeater.Properties.Resources.comboBox_over;
}
private void pbSystemType_MouseLeave(object sender, EventArgs e)
{
lbSystemType.BackColor = Color.FromArgb(32, 49, 51);
pbSystemType.Image = MotoRepeater.Properties.Resources.comboBox;
}
private void cbSystemType_SelectedIndexChanged(object sender, EventArgs e)
{
lbSystemType.Text = cbSystemType.Text;
}
#region NUMERIC UP DOWN
private void pbNumeric_MouseEnter(object sender, EventArgs e)
{
if (((PictureBox)sender).Tag.Equals("up"))
((PictureBox)sender).Image = MotoRepeater.Properties.Resources.up_over;
else if (((PictureBox)sender).Tag.Equals("down"))
((PictureBox)sender).Image = MotoRepeater.Properties.Resources.down_over;
}
private void pbNumeric_MouseLeave(object sender, EventArgs e)
{
if (((PictureBox)sender).Tag.Equals("up"))
((PictureBox)sender).Image = MotoRepeater.Properties.Resources.up;
else if (((PictureBox)sender).Tag.Equals("down"))
((PictureBox)sender).Image = MotoRepeater.Properties.Resources.down;
}
private void pbPeerID_Click(object sender, EventArgs e)
{
if ((PictureBox)sender == pbPeerIDUp)
{
if (numericPeerId.Value < 16777215)
numericPeerId.Value = (numericPeerId.Value) + 1;
}
else if ((PictureBox)sender == pbPeerIDDown)
{
if (numericPeerId.Value > 1)
numericPeerId.Value = (numericPeerId.Value) - 1;
}
}
private void pbRepeaterPort_Click(object sender, EventArgs e)
{
if ((PictureBox)sender == pbRepeaterPortUp)
{
if (numericRepeaterPort.Value < 16777215)
numericRepeaterPort.Value = (numericRepeaterPort.Value) + 1;
}
else if ((PictureBox)sender == pbRepeaterPortDown)
{
if (numericRepeaterPort.Value > 1)
numericRepeaterPort.Value = (numericRepeaterPort.Value) - 1;
}
}
private void pbDDMSPort_Click(object sender, EventArgs e)
{
if ((PictureBox)sender == pbDDMSPortUp)
{
if (numericDDMSPort.Value < 65000)
numericDDMSPort.Value = (numericDDMSPort.Value) + 1;
}
else if ((PictureBox)sender == pbDDMSPortDown)
{
if (numericDDMSPort.Value > 1)
numericDDMSPort.Value = (numericDDMSPort.Value) - 1;
}
}
private void pbLocationPort_Click(object sender, EventArgs e)
{
if ((PictureBox)sender == pbLocationPortUp)
{
if (numericLocationPort.Value < 65000)
numericLocationPort.Value = (numericLocationPort.Value) + 1;
}
else if ((PictureBox)sender == pbLocationPortDown)
{
if (numericLocationPort.Value > 1)
numericLocationPort.Value = (numericLocationPort.Value) - 1;
}
}
private void pbARSPort_Click(object sender, EventArgs e)
{
if ((PictureBox)sender == pbARSPortUp)
{
if (numericARSPort.Value < 65000)
numericARSPort.Value = (numericARSPort.Value) + 1;
}
else if ((PictureBox)sender == pbARSPortDown)
{
if (numericARSPort.Value > 1)
numericARSPort.Value = (numericARSPort.Value) - 1;
}
}
private void pbTextPort_Click(object sender, EventArgs e)
{
if ((PictureBox)sender == pbTextPortUp)
{
if (numericTextPort.Value < 65000)
numericTextPort.Value = (numericTextPort.Value) + 1;
}
else if ((PictureBox)sender == pbTextPortDown)
{
if (numericTextPort.Value > 1)
numericTextPort.Value = (numericTextPort.Value) - 1;
}
}
private void pbTelemetryPort_Click(object sender, EventArgs e)
{
if ((PictureBox)sender == pbTelemetryPortUp)
{
if (numericTelemetryPort.Value < 65000)
numericTelemetryPort.Value = (numericTelemetryPort.Value) + 1;
}
else if ((PictureBox)sender == pbTelemetryPortDown)
{
if (numericTelemetryPort.Value > 1)
numericTelemetryPort.Value = (numericTelemetryPort.Value) - 1;
}
}
#endregion
#region BUTTONS LEFT-RIGHT
private void pbButton_MouseLeave(object sender, EventArgs e)
{
if (((PictureBox)sender).Tag.Equals("selected"))
((PictureBox)sender).Image = ((PictureBox)sender == pbSettings) ? MotoRepeater.Properties.Resources.bt_settings3 : MotoRepeater.Properties.Resources.bt_overview3;
else if (((PictureBox)sender).Tag.Equals("unselected"))
((PictureBox)sender).Image = ((PictureBox)sender == pbSettings) ? MotoRepeater.Properties.Resources.bt_settings2 : MotoRepeater.Properties.Resources.bt_overview2;
}
private void pbButton_MouseEnter(object sender, EventArgs e)
{
if (((PictureBox)sender).Tag.Equals("selected"))
((PictureBox)sender).Image = ((PictureBox)sender == pbSettings) ? MotoRepeater.Properties.Resources.bt_settings3 : MotoRepeater.Properties.Resources.bt_overview3;
else if (((PictureBox)sender).Tag.Equals("unselected"))
((PictureBox)sender).Image = ((PictureBox)sender == pbSettings) ? MotoRepeater.Properties.Resources.bt_settings : MotoRepeater.Properties.Resources.bt_overview;
}
private void pbButton_Click(object sender, EventArgs e)
{
if ((PictureBox)sender == pbSettings)
{
pbSettings.Tag = "selected";
pbSettings.Image = MotoRepeater.Properties.Resources.bt_settings;
pbOverview.Tag = "unselected";
pbOverview.Image = MotoRepeater.Properties.Resources.bt_overview2;
panelOverview.Visible = false;
panelSettings.Visible = true;
}
else if ((PictureBox)sender == pbOverview)
{
pbOverview.Tag = "selected";
pbOverview.Image = MotoRepeater.Properties.Resources.bt_overview;
pbSettings.Tag = "unselected";
pbSettings.Image = MotoRepeater.Properties.Resources.bt_settings2;
panelOverview.Visible = true;
panelSettings.Visible = false;
}
}
#endregion
/// <summary>
/// Change the username label and picture box image and color
/// </summary>
/// <param name="sender">Label or PictureBox which generated the event</param>
/// <param name="e">Event arguments</param>
private void controlUsername_MouseEnter(object sender, EventArgs e)
{
pbUsername.Image = MotoRepeater.Properties.Resources.login_user_over;
lbUsername.ForeColor = Color.DarkTurquoise;
}
/// <summary>
/// Change the username label and picture box image and color
/// </summary>
/// <param name="sender">Label or PictureBox which generated the event</param>
/// <param name="e">Event arguments</param>
private void controlUsername_MouseLeave(object sender, EventArgs e)
{
pbUsername.Image = MotoRepeater.Properties.Resources.login_user;
lbUsername.ForeColor = Color.LightGray;
}
/// <summary>
/// Show or hide the settings menu and bind the UI elements to the config file values
/// </summary>
/// <param name="sender">Username label or Username Picture Box which generated the event</param>
/// <param name="e">Event arguments</param>
private void controlUsernameClick(object sender, EventArgs e)
{
cbMenuKeepSigned.Checked = MotoRepeater_GW.cfg.SIGNEDIN;
// clear all gateway codes from the comboBox and fill with the new ones
cbMenuGatewayCodes.Items.Clear();
List<SafenetGatewayIdent> gateways = DB.GetRepeaterGatewayIDForCredentials(MotoRepeater_GW.cfg.USERNAME, MotoRepeater_GW.cfg.PASSWORD);
foreach (SafenetGatewayIdent gw in gateways)
{
cbMenuGatewayCodes.Items.Add(gw.Code + "");
}
cbMenuGatewayCodes.Text = MotoRepeater_GW.cfg.GWCODE+"";
panelUsernameSettings.Visible = !panelUsernameSettings.Visible;
}
/// <summary>
/// Close the Main form and then show the Login form once again. In the same time,
/// the configuration will be reseted to initial blank values
/// </summary>
/// <param name="sender">Logout Button which generated the event</param>
/// <param name="e">Event arguments</param>
private void btMenuLogout_Click(object sender, EventArgs e)
{
// clear credentials and gateway values from the loaded configuration
MotoRepeater_GW.cfg.USERNAME = "";
MotoRepeater_GW.cfg.PASSWORD = "";
MotoRepeater_GW.cfg.GWCODE = 0;
MotoRepeater_GW.cfg.GWID = 0;
MotoRepeater_GW.cfg.SIGNEDIN = false;
// reset credentials and gateway code from the config file
Config.UpdateConfigParameter("CREDENTIALS", "USER", "");
Config.UpdateConfigParameter("CREDENTIALS", "PASSWORD", "");
Config.UpdateConfigParameter("CREDENTIALS", "SIGNEDIN", "false");
Config.UpdateConfigParameter("GATEWAY", "CODE", "0");
// flag that the logout was made
this.DialogResult = System.Windows.Forms.DialogResult.OK;
// close the database connection
DB.StopDB();
// close this form in order for the threads to close
this.Close();
}
/// <summary>
/// Save the changes made in the menu (eg. gateway code, keep signed in)
/// The changes are saved in the cfg file only and will be applied after
/// the user will restart the gateway
/// </summary>
/// <param name="sender">Save Button which generated the event</param>
/// <param name="e">Event arguments</param>
private void btMenuSave_Click(object sender, EventArgs e)
{
// change if the user is remembered or not
Config.UpdateConfigParameter("CREDENTIALS", "SIGNEDIN", cbMenuKeepSigned.Checked ? "true" : "false");
Config.UpdateConfigParameter("GATEWAY", "CODE", cbMenuGatewayCodes.Text);
// hide username settings panel
panelUsernameSettings.Visible = false;
// show restart app message
MessageBox.Show("You must restart your application for the changes to take effect.", "Save completed");
}
#endregion
private void SafeNetForm_Shown(object sender, EventArgs e)
{
// the login frame was canceled close the application
if (!MotoRepeater_GW.isRunning)
return;
// this piese of code will be run after the login is finished
DB = new DBhandle(MotoRepeater_GW.cfg.DB_SERVER, MotoRepeater_GW.cfg.DB_DATABASE, MotoRepeater_GW.cfg.DB_USERNAME, MotoRepeater_GW.cfg.DB_PASSWORD);
DB.StartDB();
RepeaterConfig repeaterConfig = DB.GetRepeaterGatewayConfiguration(MotoRepeater_GW.cfg.GWCODE);
//repeaterConfig.RepeaterIP = "10.120.1.196";
if (repeaterConfig != null)
{
MotoRepeater_GW.cfg.UpdateRepeaterConfig(repeaterConfig);
}
else
{
MessageBox.Show("No configuration for this repeater gateway defined into Database. Please go into Safenet Admin and define one.");
return;
}
// start a thread to get all the units
new Thread(delegate()
{
// load the units from the database
DB.LoadUnitInfo(MotoRepeater_GW.cfg.GWCODE);
// remove all units in order for the location thread to not find them as new interval units
SN_Queues.NewIntervalQueue.Clear();
//DB.StopDB();
}).Start();
// Continue with the Constructor
ContinueConstructor();
// update values for settings
LoadSettings_GUI();
// enable all services
pictureBoxArs.Image = MotoRepeater.Properties.Resources.ars_icon;
pictureBoxPosition.Image = MotoRepeater.Properties.Resources.gps_icon;
pictureBoxSMS.Image = MotoRepeater.Properties.Resources.sms_icon;
pictureBoxDatabase.Image = MotoRepeater.Properties.Resources.database_icon;
ThreadUIRefresh = new Thread(delegate()
{
int count = 0;
while (MotoRepeater_GW.isRunning)
{
if (count++ % 2 == 0)
{
try
{
this.Invoke((MethodInvoker)delegate()
{
lbUnits.Text = SafeMobileLib.SN_Queues.ht_SUInfo.Count + " units assigned" + Environment.NewLine
+ "to gateway " + MotoRepeater_GW.cfg.GWCODE;
lbSMS.Text = MotoRepeater_GW.smsStatistic.incoming + " received" + Environment.NewLine
+ MotoRepeater_GW.smsStatistic.outgoing + " (re)sent";
lbGPS.Text = MotoRepeater_GW.gpsStatistic.incoming + " positions" + Environment.NewLine
+ MotoRepeater_GW.pollStatistic.incoming + " poll responses";
});
count = 0;
}
catch (Exception) { }
}
Thread.Sleep(500);
}
}
);
ThreadUIRefresh.Start();
}
/// <summary>
/// Restart the application and close other notify icons
/// </summary>
public void RestartApp()
{
CloseNotifyIcon();
MotoRepeater_GW.isRunning = false;
Thread p = new Thread(new ThreadStart(delegate ()
{
//oldProcess.WaitForExit(8000);
Process.Start(System.Reflection.Assembly.GetExecutingAssembly().Location, String.Join(" ", Program.commandLineArgs));
CloseApp();
}));
p.Start();
}
private void CloseApp()
{
Process oldProcess = Process.GetCurrentProcess();
oldProcess.Kill();
Application.Exit();
}
/// <summary>
/// Hide the notify icon method. This will cause the right bottom icon to be hide
/// </summary>
private void CloseNotifyIcon()
{
if (Repeater_Notify_Icon != null)
{
Repeater_Notify_Icon.Visible = false;
Repeater_Notify_Icon.Icon = null;
Repeater_Notify_Icon.Dispose();
}
}
}
}