SafeDispatch/Safedispatch_4_0/AlarmList.cs

658 lines
27 KiB
C#
Raw Permalink Normal View History

2024-02-22 16:43:59 +00:00
//#define jurgen
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Telerik.WinControls;
using Telerik.WinControls.UI;
using SafeMobileLib;
using System.Timers;
using System.Threading;
using System.Threading.Tasks;
namespace Safedispatch_4_0
{
public partial class AlarmFrom : Telerik.WinControls.UI.RadForm
{
private DBalarmManager dbalm;
private MainForm2 parent;
private static String silenceOption = MainForm2.returnLNGString("silentNo");
private static String sleepUntilLabel = MainForm2.returnLNGString("silentNot");
private System.Timers.Timer alertUIChangeTimer;
private Boolean comboboxValueChanged = false;
private DateTime previousTime;
private Dictionary<string, string> alertCommand = null;
private void setLanguage()
{
try
{
this.Text = MainForm2.returnLNGString("alarmList");//newnamex
AlarmListView1.Columns["UnitName"].HeaderText = MainForm2.returnLNGString("htableVehiclesListColumns1");
AlarmListView1.Columns["Type"].HeaderText = MainForm2.returnLNGString("alarmtype");
AlarmListView1.Columns["Text"].HeaderText = MainForm2.returnLNGString("lbDescript");
AlarmListView1.Columns["Timegmt"].HeaderText = MainForm2.returnLNGString("SMSMessTime");
AlarmListView1.Columns["location"].HeaderText = MainForm2.returnLNGString("location");
}
catch (Exception ex)
{
SM.Debug("EX to setlang:" + ex.ToString());
}
}
public AlarmFrom(MainForm2 _parent)
{
parent = _parent;
InitializeComponent();
radWaitingBar1.StartWaiting();
previousTime = DateTime.Now;
// Create a timer
alertUIChangeTimer = new System.Timers.Timer();
// Tell the timer what top do when it elapses
alertUIChangeTimer.Elapsed += new ElapsedEventHandler(TimerCallback);
// Set it to go off every five seconds
alertUIChangeTimer.Interval = 1000;
// And start it
alertUIChangeTimer.Enabled = true;
dbalm = new DBalarmManager(MainForm2.cfg.DB_IP, MainForm2.cfg.DB_schema, MainForm2.cfg.DB_user, MainForm2.cfg.DB_passwd, MainForm2.cfg.DB_port);
rddSilentIntervals.Items.Add(MainForm2.returnLNGString("silentNo"));
rddSilentIntervals.Items.Add(MainForm2.returnLNGString("silent1Min"));
rddSilentIntervals.Items.Add(MainForm2.returnLNGString("silent5Min"));
rddSilentIntervals.Items.Add(MainForm2.returnLNGString("silent15Min"));
rddSilentIntervals.Items.Add(MainForm2.returnLNGString("silent30Min"));
rddSilentIntervals.Items.Add(MainForm2.returnLNGString("silent1H"));
rddSilentIntervals.Items.Add(MainForm2.returnLNGString("silent2H"));
rddSilentIntervals.Items.Add(MainForm2.returnLNGString("silent5H"));
rddSilentIntervals.Items.Add(MainForm2.returnLNGString("silent12H"));
rddSilentIntervals.Items.Add(MainForm2.returnLNGString("silent1D"));
rddSilentIntervals.Items.Add(MainForm2.returnLNGString("silentRestart"));
// set the old value
rddSilentIntervals.Text = silenceOption;
labelSleep.Text = sleepUntilLabel;
rbSaveClose.Text = MainForm2.returnLNGString("saveAndClose");
labelSilent.Text = MainForm2.returnLNGString("silentAlerts");
lbText.Text = MainForm2.returnLNGString("loadingAlerts");
comboboxValueChanged = false;
#region THEMING
labelSilent.ForeColor = MainForm2.LabelColor;
rbSaveClose.ButtonElement.ButtonFillElement.BackColor = MainForm2.ButtonColor;
#endregion
//ThemeResolutionService.ApplyThemeToControlTree(this, "ControlDefault");
//updateList();
setLanguage();
if ((MainForm2.radioType != RADIOTYPE.MOTO) && (MainForm2.radioType != RADIOTYPE.CONECTPLUS) && (MainForm2.radioType != RADIOTYPE.REPEATER_TRBO) && (MainForm2.radioType != RADIOTYPE.TETRA))
{
try
{
if (MainForm2.radioType == RADIOTYPE.HYT)
{
this.Icon = global::Dispatcher.Properties.Resources.HytSmall24;
this.BackColor = MainForm2.HyteraColor;
}
else if (MainForm2.radioType == RADIOTYPE.HARRIS) this.Icon = global::Dispatcher.Properties.Resources.HarrisSmall;
else if (MainForm2.radioType == RADIOTYPE.SIMOCO) this.Icon = global::Dispatcher.Properties.Resources.simoco_dispatch_24;
else if (MainForm2.radioType == RADIOTYPE.EXCERA) this.Icon = global::Dispatcher.Properties.Resources.AXYS_ICON;
else this.Icon = global::Dispatcher.Properties.Resources.ATLICO32; //ATLASCHANGE
this.AlarmListView1.TableElement.CellSpacing = -1;
this.AlarmListView1.TableElement.RowSpacing = -1;
}
catch (Exception ex)
{
SM.Debug("Error on change color hytera:" + ex.ToString());
}
}
try
{
if (MainForm2.is24hours)
{
if (MainForm2.DayFirst)
((GridViewDateTimeColumn)AlarmListView1.Columns[5]).FormatString = "{0:dd/MM/yyyy HH:mm:ss}";
else
((GridViewDateTimeColumn)AlarmListView1.Columns[5]).FormatString = "{0:MM/dd/yyyy HH:mm:ss}";
}
else
{
if (MainForm2.DayFirst)
((GridViewDateTimeColumn)AlarmListView1.Columns[5]).FormatString = "{0:dd/MM/yyyy hh:mm:ss tt}";
else
((GridViewDateTimeColumn)AlarmListView1.Columns[5]).FormatString = "{0:MM/dd/yyyy hh:mm:ss tt}";
}
openedByUser = true;
alertCommand = dbalm.InitAlertCommandDictionary();
}
catch (Exception ex)
{
SM.Debug("Error on gridview DateFormat:"+ex.ToString());
}
}
private static CancellationTokenSource tokenSource2 = new CancellationTokenSource();
private static CancellationToken ct = tokenSource2.Token;
public bool openedByUser = false;
private static Task runningUpdateTask = null;
public static bool shouldUpdateAgain = false;
public async void updateList()
{
//Utils.WriteLine("Updating alarms list", ConsoleColor.Blue);
try
{
if (runningUpdateTask != null)
{
shouldUpdateAgain = true;
// cancel the task
//tokenSource2.Cancel();
return;
}
List<AlarmHisItem> tmp2 = null;
List<AlarmHisItem> tmp = null;
panelLoading.Visible = true;
radWaitingBar1.StartWaiting();
await (runningUpdateTask = Task.Factory.StartNew(() =>
{
// Were we already canceled?
ct.ThrowIfCancellationRequested();
Thread.Sleep(100);
tmp2 = dbalm.Get_nonACK_alarms1(MainForm2.cfg.maxAlertsNumber);
Utils.WriteLine("received " + tmp2.Count + " alerts", ConsoleColor.Blue);
//filter alarm only for the unit from user
tmp = new List<AlarmHisItem>();
foreach (AlarmHisItem obj in tmp2)
if (MainForm2.VehIDHash[obj.Sc_id] != null) tmp.Add(obj);
//end filter
foreach (AlarmHisItem obj in tmp)
{
if (obj.Type == AlarmTypes.speed)
{
if (MainForm2.isInMile)
{
try
{
obj.Text = Convert.ToString((int)Math.Round(Convert.ToInt32(obj.Text) * 0.621371192));
}
catch (Exception ex)
{
SM.Debug("Error on convert KM to MILES" + ex.ToString());
}
}
}
}
}, tokenSource2.Token));
if (this.InvokeRequired)
this.Invoke((Action)(() =>
{
radWaitingBar1.StopWaiting();
panelLoading.Visible = false;
}));
else
{
radWaitingBar1.StopWaiting();
panelLoading.Visible = false;
}
//if ((MainForm2.isInMile) && (!volInMessMile)) volSpeed = Convert.ToString((int)((Convert.ToInt32(volSpeed)) * 0.621371192));
AlarmListView1.Rows.Clear();
AlarmListView1.DataSource = tmp;
AlarmListView1.Columns[5].SortOrder = RadSortOrder.Descending;
MainForm2.AlarmCountNotAck = tmp.Count;//dbalm.countAlarm;
AlarmListView1.TableElement.ScrollToRow(0);
// select first row
if (AlarmListView1.Rows.Count > 0)
AlarmListView1.CurrentRow = AlarmListView1.Rows[0];
//for update down Icon that is this procedure
if (tmp.Count > 0)
{
AlarmHisItem elem = tmp[0];
foreach (AlarmHisItem obj in tmp)
if (elem.Timegmt < obj.Timegmt) elem = obj;
//parent.AlarmACKUpdate(elem, tmp.Count);
}
//else parent.AlarmACKUpdate(null, 0);
openedByUser = false;
previousTime = DateTime.Now;
runningUpdateTask = null;
if (shouldUpdateAgain)
{
shouldUpdateAgain = false;
this.Invoke((MethodInvoker)delegate ()
{
updateList();
});
}
}
catch (Exception ex)
{
radWaitingBar1.StopWaiting();
panelLoading.Visible = false;
SM.Debug("EX:" + ex.ToString());
}
}
void ackAlarm_Click(object sender, EventArgs e)
{
try
{
for (int contor = 0; contor < AlarmListView1.SelectedRows.Count; contor++)
{
int alarm_id = (int)AlarmListView1.SelectedRows[contor].Cells[0].Value;
AlarmTypes type = (AlarmTypes)AlarmListView1.SelectedRows[contor].Cells[3].Value;
string unitName = (String)AlarmListView1.SelectedRows[contor].Cells[2].Value;
dbalm.ACKalarms(alarm_id, type, MainForm2.userIDX, DateTime.Now.ToUniversalTime().DateTo70Format());
//if (type == AlarmTypes.emergency)
{
String Totrans = "";
/*
((Vehicle)MainForm2.vehicleHT[unitName]).is_emergency = false;
String Totrans = "#153#" + ((Vehicle)MainForm2.vehicleHT[unitName]).IMEI + "#" + (Int32)Status_for_tab.ON + "#";
parent.Send_UDP_cmd(Totrans, 0, 0);
*/
//String unitName = (String)AlarmListView1.SelectedRows[0].Cells[2].Value;
Utils.WriteLine("Sending ALARM ACK to " + unitName);
//update GwandRadioID for current vehicle if is 0.0
((Vehicle)MainForm2.vehicleHT[unitName]).CheckPositionInSystem();
Totrans = "#238#" + ((Vehicle)MainForm2.vehicleHT[unitName]).GwandRadioID + "."
+ ((Vehicle)MainForm2.vehicleHT[unitName]).IMEI + "#" + (int)type;
parent.Send_UDP_cmd(Totrans, 0, 0);
Thread.Sleep(30);
MainForm2.UpdateStatusLive(unitName);
// trigger event for alarm acknowledged
//OnAlarmAcknowledged?.Invoke(AlarmListView1.SelectedRows[contor].DataBoundItem as AlarmHisItem);
}
//if (MainForm2.iconType == ICONTYPE.EMERG)
//{
//NEED TO DO SAME STUFF FROM PUT EMERGENCY IN RED
foreach (String name in ((Vehicle)MainForm2.vehicleHT[unitName]).MapsHT.Keys)
{
((Vehicle)MainForm2.vehicleHT[unitName]).is_emergency = false;
((MapElement)((Vehicle)MainForm2.vehicleHT[unitName]).MapsHT[name]).UpdateSymbol();
MainForm2.RemoveIconsFromMap();
}
Thread.Sleep(100);
// trigger event for alarm acknowledged
//OnAlarmAcknowledged?.Invoke(AlarmListView1.SelectedRows[contor].DataBoundItem as AlarmHisItem);
MainForm2.UpdateStatusLive(unitName);
// }
}
}
catch (Exception ex)
{
SM.Debug("EX:" + ex.ToString());
}
try { updateList(); }
catch (Exception ex)
{
radWaitingBar1.StopWaiting();
panelLoading.Visible = false;
SM.Debug("EX:" + ex.ToString());
}
}
void ackAlarms_Click(object sender, EventArgs e)
{
try
{
StringBuilder sb = new StringBuilder();
for (int contor = 0; contor < AlarmListView1.Rows.Count; contor++)
{
int alarm_id = (int)AlarmListView1.Rows[contor].Cells[0].Value;
AlarmTypes type = (AlarmTypes)AlarmListView1.Rows[contor].Cells[3].Value;
string unitName = (String)AlarmListView1.Rows[contor].Cells[2].Value;
sb.Append(string.Format(alertCommand[type.ToString()], alarm_id, MainForm2.userIDX, DateTime.Now.ToUniversalTime().DateTo70Format()));
//if (type == AlarmTypes.emergency)
{
((Vehicle)MainForm2.vehicleHT[unitName]).is_emergency = false;
String Totrans = "#153#" + ((Vehicle)MainForm2.vehicleHT[unitName]).IMEI + "#" + (Int32)Status_for_tab.ON + "#";
parent.Send_UDP_cmd(Totrans, 0, 0);
Utils.WriteLine("Sending ALARM ACK to " + unitName);
//update GwandRadioID for current vehicle if is 0.0
((Vehicle)MainForm2.vehicleHT[unitName]).CheckPositionInSystem();
Totrans = "#238#" + ((Vehicle)MainForm2.vehicleHT[unitName]).GwandRadioID + "."
+ ((Vehicle)MainForm2.vehicleHT[unitName]).IMEI + "#" + (int) type;
parent.Send_UDP_cmd(Totrans, 0, 0);
foreach (String name in ((Vehicle)MainForm2.vehicleHT[unitName]).MapsHT.Keys)
{
((Vehicle)MainForm2.vehicleHT[unitName]).is_emergency = false;
((MapElement)((Vehicle)MainForm2.vehicleHT[unitName]).MapsHT[name]).UpdateSymbol();
MainForm2.RemoveIconsFromMap();
}
Thread.Sleep(30);
MainForm2.UpdateStatusLive(unitName);
// trigger event for alarm acknowledged
//OnAlarmAcknowledged?.Invoke(AlarmListView1.SelectedRows[contor].DataBoundItem as AlarmHisItem);
}
}
openedByUser = true;
dbalm.ACKalarms(sb.ToString());
}
catch (Exception ex)
{
SM.Debug("EX:" + ex.ToString());
}
try { updateList(); }
catch (Exception ex)
{
radWaitingBar1.StopWaiting();
panelLoading.Visible = false;
SM.Debug("EX:" + ex.ToString());
}
}
private void AlarmListView1_ContextMenuOpening(object sender, ContextMenuOpeningEventArgs e)
{
try
{
RadDropDownMenu openedSMSmenu = new RadDropDownMenu();
RadMenuItem menuItem1 = new RadMenuItem(MainForm2.returnLNGString("acxalarm"));
menuItem1.Click += new EventHandler(ackAlarm_Click);
openedSMSmenu.Items.Add(menuItem1);
RadMenuItem menuItem2 = new RadMenuItem(MainForm2.returnLNGString("alarmALLACK"));
menuItem2.Click += new EventHandler(ackAlarms_Click);
openedSMSmenu.Items.Add(menuItem2);
if (e.ContextMenuProvider is GridDataCellElement)
{
e.ContextMenu = openedSMSmenu;
}
}
catch (Exception ex)
{
SM.Debug("Add context menu:" + ex.ToString());
}
}
/// <summary>
/// Save the silence time and update the label if necessary
/// </summary>
private void rbSaveClose_Click(object sender, EventArgs e)
{
// update the labels
DateTime sleepTime = UpdateTimeLabel();
// save the time until when the alert is silenced
MainForm2.alertSilenceEndTime = sleepTime;
this.Close();
}
/// <summary>
/// Method called by the timer when the timer ellapsed
/// </summary>
private void TimerCallback(object source, ElapsedEventArgs e)
{
// update the UI labels
try
{
DateTime dt = UpdateTimeLabel();
if (comboboxValueChanged)
{
this.Invoke(new MethodInvoker(delegate()
{
// set labels
if (rddSilentIntervals.SelectedIndex == 0)
sleepUntilLabel = MainForm2.returnLNGString("silentNo");
else if (rddSilentIntervals.SelectedIndex == rddSilentIntervals.Items.Count - 1)
sleepUntilLabel = MainForm2.returnLNGString("silentRestart");
else if (rddSilentIntervals.SelectedIndex == rddSilentIntervals.Items.Count - 2)
sleepUntilLabel = MainForm2.returnLNGString("silentTomorrow") + dt.ToString("HH:mm:ss dd/MM");
else
sleepUntilLabel = string.Format(MainForm2.returnLNGString("silentUntil"), dt.ToString("HH:mm:ss dd/MM"));
// set labels
labelSleep.Text = sleepUntilLabel;
}));
}
else
sleepUntilLabel = MainForm2.returnLNGString("silenced") + dt.ToString("HH:mm:ss dd/MM");
}
catch (Exception ex)
{
Utils.WriteLine("Error on Alarm tab go to silent:"+ex.ToString(),ConsoleColor.Red);
}
}
private DateTime UpdateTimeLabel()
{
if(alertUIChangeTimer == null)
{
// Create a timer
alertUIChangeTimer = new System.Timers.Timer();
// Tell the timer what top do when it elapses
alertUIChangeTimer.Elapsed += new ElapsedEventHandler(TimerCallback);
// Set it to go off every five seconds
alertUIChangeTimer.Interval = 1000;
// And start it
alertUIChangeTimer.Enabled = true;
}
silenceOption = rddSilentIntervals.Text;
DateTime sleepTime = DateTime.Now;
switch (rddSilentIntervals.SelectedIndex)
{
case 0:
// no silence
break;
case 1:
// 1 minute
sleepTime = sleepTime.AddMinutes(1);
break;
case 2:
// 5 minute
sleepTime = sleepTime.AddMinutes(5);
break;
case 3:
// 15 minute
sleepTime = sleepTime.AddMinutes(15);
break;
case 4:
// 30 minute
sleepTime = sleepTime.AddMinutes(30);
break;
case 5:
// 1 hour
sleepTime = sleepTime.AddHours(1);
break;
case 6:
// 2 hours
sleepTime = sleepTime.AddHours(2);
break;
case 7:
// 5 hours
sleepTime = sleepTime.AddHours(5);
break;
case 8:
// 12 hours
sleepTime = sleepTime.AddHours(12);
break;
case 9:
// 1 day
sleepTime = sleepTime.AddDays(1);
break;
case 10:
// until restart
sleepTime = sleepTime.AddYears(20);
break;
}
// set labels
if (rddSilentIntervals.SelectedIndex == 0)
sleepUntilLabel = MainForm2.returnLNGString("silentNo");
else if (rddSilentIntervals.SelectedIndex == rddSilentIntervals.Items.Count - 1)
sleepUntilLabel = MainForm2.returnLNGString("silentRestart");
else if (rddSilentIntervals.SelectedIndex == rddSilentIntervals.Items.Count - 2)
sleepUntilLabel = MainForm2.returnLNGString("silentTomorrow") + sleepTime.ToString("HH:mm:ss dd/MM");
else
sleepUntilLabel = MainForm2.returnLNGString("silenced") + sleepTime.ToString("HH:mm:ss dd/MM");
return sleepTime;
}
private void AlarmFrom_FormClosing(object sender, FormClosingEventArgs e)
{
AlarmListView1?.Rows?.Clear();
if (AlarmListView1 != null)
AlarmListView1.DataSource = null;
if (alertUIChangeTimer != null)
{
// close the timer
alertUIChangeTimer.Stop();
alertUIChangeTimer.Dispose();
alertUIChangeTimer = null;
}
comboboxValueChanged = false;
if (!MainForm2.ClosingApp)
{
this.Hide();
e.Cancel = true;
}
}
private void rddSilentIntervals_SelectedIndexChanged(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e)
{
comboboxValueChanged = true;
// update the label for expired time
UpdateTimeLabel();
}
/// <summary>
/// Change background color for the row according to its state and theme
/// </summary>
private void AlarmListView1_RowFormatting(object sender, RowFormattingEventArgs e)
{
if (e.RowElement.IsSelected)
{
e.RowElement.DrawFill = true;
e.RowElement.BackColor = MainForm2.GridSelectedRow;
e.RowElement.NumberOfColors = 1;
}
else
e.RowElement.DrawFill = false;
}
private void AlarmListView1_CellFormatting(object sender, CellFormattingEventArgs e)
{
GridCellElement cellElement = e.CellElement;
GridViewDataColumn columnInfo = e.CellElement.ColumnInfo as GridViewDataColumn;
if (cellElement == null || columnInfo == null)
return;
// do not draw border
cellElement.DrawBorder = false;
// do not highlight the cell on which was clicked
if (e.CellElement.IsCurrent)
{
e.CellElement.IsCurrent = false;
}
AlarmHisItem alarm = null;
if (e.Row.DataBoundItem is AlarmHisItem)
{
alarm = (AlarmHisItem)e.Row.DataBoundItem;
}
// change the way on which the DateTime is displayed
if (cellElement is GridDataCellElement && columnInfo.Name == "location")
{
Font font = new Font(
cellElement.Font.FontFamily,
10,
FontStyle.Bold,
GraphicsUnit.Pixel);
cellElement.ForeColor = Color.DarkGray;
cellElement.Font = font;
if (alarm == null)
cellElement.Visibility = ElementVisibility.Hidden;
else
{
cellElement.Visibility = ElementVisibility.Visible;
if(alarm.Latitude != 0 || alarm.Longitude != 0)
cellElement.Text = $"[{alarm.Latitude:###.####}{alarm.Longitude:###.####}]";
else
cellElement.Text = MainForm2.returnLNGString("unknownAddr");
}
}
}
private void AlarmListView1_CellClick(object sender, GridViewCellEventArgs e)
{
AlarmHisItem alarm = null;
if (e.Row.DataBoundItem is AlarmHisItem)
{
alarm = (AlarmHisItem)e.Row.DataBoundItem;
}
// change the way on which the DateTime is displayed
if (e.Column != null && e.Column.Name.Equals("location") && alarm != null)
{
foreach (LiveTabWind obj in MainForm2.LiveTabs.Values)
{
if (MainForm2.MapType == MapTYPE.Google)
{
obj.livetab.CenterAndOpenBubble(alarm.UnitName);
}
}
}
}
private void AlarmListView1_MouseMove(object sender, MouseEventArgs e)
{
GridDataCellElement cell = this.AlarmListView1.ElementTree.GetElementAtPoint(e.Location) as GridDataCellElement;
if (cell != null && cell.ColumnInfo.Name.Equals("location"))
this.AlarmListView1.Cursor = Cursors.Hand;
else
this.AlarmListView1.Cursor = Cursors.Default;
}
public delegate void AlarmAckMethodDelegate(AlarmHisItem ackAlarm);
public event AlarmAckMethodDelegate OnAlarmAcknowledged;
}
}