SafeDispatch/Safedispatch_4_0/MainForm2.cs

9487 lines
430 KiB
C#
Raw Permalink Blame History

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using Telerik.WinControls;
using Telerik.WinControls.UI;
using Telerik.WinControls.UI.Docking;
using System.Linq;
using System.Diagnostics;
using System.Collections;
using System.Globalization;
using MapGoogle;
using System.Threading;
using SafeMobileLib;
using System.IO;
using SafeMobileLib.MessageDecoders;
using SafeMobileLib.Modules;
using System.Resources;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.esriSystem;
using System.Net.Sockets;
using System.Net;
using System.Text.RegularExpressions;
using Dispatcher.maptab.UIClasses;
using Telerik.WinControls.Data;
using Safedispatch_4_0.Radio;
using NAudio.Wave;
using SharedUI;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Text;
using Telerik.WinControls.Layouts;
using Telerik.WinControls.Enumerations;
using resources = Dispatcher.Properties.Resources;
namespace Safedispatch_4_0
{
public partial class MainForm2 : Telerik.WinControls.UI.RadForm
{
#region THEMING
public static Color LabelColor = Color.FromArgb(255, 64, 0);
public static Color LabelColorTicketSubject = Color.FromArgb(72, 191, 255);
public static Color ButtonColor = Color.FromArgb(211, 111, 15);
public static Color ButtonColorDisabled = Color.FromArgb(113, 113, 113);
public static Color GroupHeaderColor = Color.FromArgb(255, 64, 0);
public static Color TabSelectedColor = Color.FromArgb(15, 158, 190);
public static Color TabOverColor = Color.FromArgb(255, 64, 0);
public static Color TabNormalColor = Color.FromArgb(15, 115, 211);
public static Color GridSelectedRow = Color.FromArgb(146, 217, 255);
public static Color GridAlternateRow = Color.FromArgb(193, 235, 255);
public static Dictionary<String, Image> imagesDictionary = new Dictionary<string, Image>();
public static string mapLanguage = "en";
private AppServerMonitoring appServerMonitoring;
private bool forceReconnectToNewIP = false;
public static ToggleState isWebsocketConnected = ToggleState.Indeterminate;
public static Boolean hasDBAccess = false;
public static void setThemingColors(RADIOTYPE themeType)
{
switch (themeType)
{
case RADIOTYPE.MOTO:
case RADIOTYPE.CONECTPLUS:
case RADIOTYPE.REPEATER_TRBO:
case RADIOTYPE.TETRA:
case RADIOTYPE.LINX:
case RADIOTYPE.LINXB:
{
LabelColor = Color.FromArgb(27, 161, 226);
LabelColorTicketSubject = Color.FromArgb(72, 191, 255);
ButtonColor = Color.FromArgb(27, 161, 226);
ButtonColorDisabled = Color.FromArgb(113, 113, 113);
GroupHeaderColor = Color.FromArgb(27, 161, 226);
TabSelectedColor = Color.FromArgb(15, 158, 190);
TabOverColor = Color.FromArgb(23, 131, 238);
TabNormalColor = Color.FromArgb(15, 115, 211);
GridSelectedRow = Color.FromArgb(146, 217, 255);
GridAlternateRow = Color.FromArgb(239, 250, 255);
break;
}
case RADIOTYPE.HYT:
{
LabelColor = Color.FromArgb(244, 177, 131);
LabelColorTicketSubject = Color.FromArgb(0, 99, 147);
ButtonColor = Color.FromArgb(244, 177, 131);
ButtonColorDisabled = Color.FromArgb(113, 113, 113);
GroupHeaderColor = Color.FromArgb(244, 177, 131);
TabSelectedColor = Color.FromArgb(255, 181, 61);
TabOverColor = Color.FromArgb(200, 122, 49);
TabNormalColor = Color.FromArgb(255, 164, 101);
GridSelectedRow = Color.FromArgb(255, 184, 146);
GridAlternateRow = Color.FromArgb(255, 244, 239);
break;
}
case RADIOTYPE.SIMOCO:
{
LabelColor = Color.FromArgb(71, 101, 154);
LabelColorTicketSubject = Color.FromArgb(0, 99, 147);
ButtonColor = Color.FromArgb(71, 101, 154);
ButtonColorDisabled = Color.FromArgb(113, 113, 113);
GroupHeaderColor = Color.FromArgb(71, 101, 154);
TabSelectedColor = Color.FromArgb(117, 139, 217);
TabOverColor = Color.FromArgb(70, 102, 213);
TabNormalColor = Color.FromArgb(71, 101, 154);
GridSelectedRow = Color.FromArgb(177, 200, 223);
GridAlternateRow = Color.FromArgb(239, 248, 255);
break;
}
case RADIOTYPE.EXCERA:
{
LabelColor = Color.FromArgb(139, 146, 158);
LabelColorTicketSubject = Color.FromArgb(158, 167, 171);
ButtonColor = Color.FromArgb(56, 60, 63);
ButtonColorDisabled = Color.FromArgb(113, 113, 113);
GroupHeaderColor = Color.FromArgb(139, 146, 158);
TabSelectedColor = Color.FromArgb(139, 146, 158);
TabOverColor = Color.FromArgb(151, 153, 161);
TabNormalColor = Color.FromArgb(56, 60, 63);
GridSelectedRow = Color.FromArgb(222, 224, 226);
GridAlternateRow = Color.FromArgb(231, 235, 239);
break;
}
case RADIOTYPE.HARRIS:
{
LabelColor = Color.FromArgb(184, 54, 41);
LabelColorTicketSubject = Color.FromArgb(0, 99, 147);
ButtonColor = Color.FromArgb(184, 54, 41);
ButtonColorDisabled = Color.FromArgb(113, 113, 113);
GroupHeaderColor = Color.FromArgb(184, 54, 41);
TabSelectedColor = Color.FromArgb(215, 125, 100);
TabOverColor = Color.FromArgb(208, 82, 47);
TabNormalColor = Color.FromArgb(184, 54, 41);
GridSelectedRow = Color.FromArgb(240, 160, 164);
GridAlternateRow = Color.FromArgb(255, 244, 245);
break;
}
case RADIOTYPE.ATLAS:
{
LabelColor = Color.FromArgb(0, 0, 0);
LabelColorTicketSubject = Color.FromArgb(0, 99, 147);
ButtonColor = Color.FromArgb(0, 0, 0);
ButtonColorDisabled = Color.FromArgb(113, 113, 113);
GroupHeaderColor = Color.FromArgb(0, 0, 0);
TabSelectedColor = Color.FromArgb(200, 200, 200);
TabOverColor = Color.FromArgb(155, 155, 155);
TabNormalColor = Color.FromArgb(0, 0, 0);
GridSelectedRow = Color.FromArgb(200, 200, 200);
GridAlternateRow = Color.FromArgb(244, 244, 244);
break;
}
default:
{
break;
}
}
}
#endregion
// save the version of the application server in order to use it for the updater
public static String APP_SERVER_VERSION = "";
public static DateTime alertSilenceEndTime = DateTime.Now;
public static IconTheme iconThemeType = IconTheme.PIN;
public static String googlemaptype = "map";
public static Config cfg = new Config();//stores staic configs from file
public static Boolean VoiceTabStarted = false;
public static Boolean NOAddress = false;
public static volatile Boolean DayFirst = false;
public static volatile String MapHtmlName = "SfmbMapsMain.html";
public static volatile Int32 uniqueID = 0;
public static volatile Boolean IsInLogin = true;
public static List<RadioGateway> myGatewaylist = new List<RadioGateway>();
public static Int32 nrOfUnreadMessages = 0;
public static Int32 nrOfUnreadAlerts = 0;
private static System.Threading.Timer tRefreshGrid;
public Hashtable tabsHash = new Hashtable();
private Boolean OnEnterValid = false;
private static LicenseInitializer m_AOLicenseInitializer = new Safedispatch_4_0.LicenseInitializer();
List<DataforSystemList> startList = new List<DataforSystemList>();
internal static System.Media.SoundPlayer soundPlayer = new System.Media.SoundPlayer();
System.Threading.Timer _userStatusTimer = null;
#region Fields for Sip
/// <summary>
/// Sip Class variable
/// </summary>
private Dispatcher.Sip.ISipComponent _sipClient = null;
private string _sipServerIP = null;
private int _sipServerPort;
private int _socketIOPort;
private string _sipGWIDandRadioID;
internal event EventHandler SipClassInitialized;
private UdpMulticast _udpMulForGwRecording = null;
private Dictionary<int, string> _sipIdToSeqId = null;
/// <summary>
/// Dictionary with key - sipID, value - ContactLinx
/// </summary>
Dictionary<Int32, ContactLinx> _sipIdToContactLinx_Dictionary = null;
#endregion
#region Value from old SD
public static bool isRunning = true;
//form SD variables
public static Boolean InterCalcAddr = true;
public static MapTYPE MapType = MapTYPE.Google;
public static String ShapeCMD = "";
public static Hashtable vehicleHT = new Hashtable();
public static Hashtable jobTicketHT = new Hashtable();
internal static Hashtable radioGwHT = new Hashtable();
DBgatewaysManager DBgw;
DBcontactsManager DBcontacts;
public static CultureInfo culture = CultureInfo.CreateSpecificCulture("");
public static Double LatStart = 44.41905;
public static Double LngStart = 26.09876;
public static Int32 ZoomStart = 8;
public static Boolean Connfailed = false;
public static Boolean LATLNGforDinamicReports = false;
//for DB
public static String ServerDBip;
public static String PortDB;
public static String UserDB;
public static String PassDB;
public static String Schema;
public static String MyConString;
public static Int32 MapCallTimeout;
public static Boolean MapDebugConsole;
public static Boolean MoreHist = false;
public static Boolean ComputeAddress = false;
public static Int32 PlayTime = 20;
public static Int32 PauseTime = 200;
public static Int32 GPSResh = 5000;
public static long RestartMEM = 990000000;//990000000;//750.000.000
public static Boolean MotoTURBO = true;
public static IconType iconType = IconType.ICONS;
public volatile static Boolean KillAPP = false;
public static volatile String langTime = "Time:";
public static volatile String langSpeed = "Speed:";
public static String LatLngUTM = "Lat/Lng No.";
public volatile static Boolean StandbyON = false;
public static volatile String PassAlarm = "";
public volatile static bool ClosingApp = false;
public static Boolean Displaywithname = false;
public static Int32 RefNorm = 10000;
public static Boolean StandbyEnable = false;
public static Int32 StandbyStart = 10000;
public static Int32 StandbyResh = 10000;
private String langLastTime;
private String langReshTime;
private String secName;
public static Boolean StopRefresh = false;
private SMdb_access smdbObj;
public static String msgRetAddr;
public static String userLog = "default";
public static Int32 Delta1 = 70;//70
public static Int32 Delta2 = 100;//100
public static Boolean StartStop = false;
public static Boolean LastDay = false;
public static Int32 Langidx = 0;
public static Int32 Styleidx = 0;
public static Boolean ReportDecide = false;
public static Boolean HasVoice = false;
public static Boolean recordingsDecide = false;
public static Boolean TelemDecide = false;
public static Boolean SMSDecide = false;
public static Boolean TicketingDecide = false;
public static Boolean GPSDecide = false;
public static Boolean ZonesDecide = false;
private static Int32 uid = 1738349905;
private static Int32 hid = 0;
public static Boolean MapsUS = true;
public static Int32 TicketingNrinTab = 0;
public static String POLLunit = "";
/// worker thread
public static volatile Boolean HideInactiveUnitsCheck = false;
public static volatile Int32 Livelastmin = 10;
private volatile int conttab;
private volatile Int32 timenowsec;
private volatile int contor;
private volatile Locationx locTemp;
private volatile SMdb_access smdbObj1;
private volatile SMdb_access smdbObjAddress;
private volatile SMdb_access smdbObjAddressInsert;
public static volatile Int32 sc_id_Geo = 0;
public static volatile Int32 sc_id_Land = 0;
public static volatile String Zone_Alarm = "";
public static volatile String Land_Alarm = "";
public static volatile Int32 sc_id_Speed = 0;
public static volatile Int32 sc_id_Mess = 0;
public static volatile String Mess_Alarm = "";
public static volatile Int32 sc_id_EMERG = 0;
public static volatile Int32 Speed_unit = 0;
public static volatile String newSMSTime;
public static volatile Boolean NewMess;
public static volatile Boolean NewZone;
public static volatile Boolean NewLand;
public static volatile Boolean NewSpeed;
public static volatile Boolean NewEMERG;
public static volatile Int32 userIDX = 0;
public static int userSipId = 0;
public static volatile USERTYPE userType;
public static volatile Boolean LimitedUser = false;
public volatile static Boolean isInMile = true;
public volatile static Boolean is24hours = true;
public static volatile String milesh, kmh;
public static volatile String Measure;
private volatile Pushpinx pptmp;
private volatile Recordsetx rs;
private volatile Pushpinx pp;
private volatile ArrayList currentPositions = new ArrayList();
public static volatile Boolean SystemLogDataComplete = true;
public static volatile Boolean SystemLogSortComplete = true;
public static volatile Boolean SystemLogFinish = true;
public static volatile Boolean ForceSaveZone = false;
public static volatile Boolean forceLogin = false;
//Hashuri
public static ArrayList mapControls = new ArrayList();
public static Hashtable carlist = new Hashtable();
public static Hashtable PlaceTypes = new Hashtable();
public static Hashtable PlaceTypesGIS = new Hashtable();
public static Hashtable GroupHash = new Hashtable();
public static Hashtable GroupCPSIDOnlyHash = new Hashtable();
public static Dictionary<int, SafeMobileLib.Group> TalkGroups = new Dictionary<int, SafeMobileLib.Group>();
public static Hashtable GroupsAndRadioGW = new Hashtable();
public static Dictionary<string, SafeMobileLib.Group> GroupCPSIDOnlyHashWithoutCategory = new Dictionary<string, SafeMobileLib.Group>() ;
public Hashtable isCanceled = new Hashtable();
public Hashtable NoteAddr = new Hashtable();
public static Hashtable PassHash = new Hashtable();
public static Hashtable VehIDHash = new Hashtable();
public static Hashtable ZoneIDHash = new Hashtable();
public static Hashtable LandIDHash = new Hashtable();
public static Hashtable LandIDuserIDX = new Hashtable();
public static Hashtable userIDHash = new Hashtable();
public static Hashtable passUserHash = new Hashtable();
public static ArrayList DefineSMSList = new ArrayList();
public static ArrayList RadioListIP = new ArrayList();
public static ArrayList AlarmforUnitList = new ArrayList();
public static Int32 cnt_User_Radio_assign = 0;
public static Hashtable VehIMEIHash = new Hashtable();
public static volatile Int32 cntMapPointID = 0;
public static Hashtable mapPointElementHash = new Hashtable();
public static Boolean ForcePutLabelsONGoogle = false;
public static Hashtable TicketingStatusesHT = new Hashtable();
public static Hashtable HashVal = new Hashtable();
public static Boolean emergOnlyCheck = false;
#endregion
#region Load Config
private void loadConfigs()
{
ServerDBip = cfg.DB_IP;
PortDB = cfg.DB_port;
UserDB = cfg.DB_user;
PassDB = cfg.DB_passwd;
Schema = cfg.DB_schema;
MapCallTimeout = cfg.MapCallTimeout;
MapDebugConsole = cfg.MapDebugConsole;
MyConString = $"Server={ServerDBip};Port={PortDB};User Id={UserDB};Password={PassDB};Database={Schema};Pooling=true;MinPoolSize=30;MaxPoolSize=300;Timeout=15;CommandTimeout=15;";
DBgw = new DBgatewaysManager(MainForm2.ServerDBip, MainForm2.Schema, MainForm2.UserDB, MainForm2.PassDB, MainForm2.PortDB);
DBcontacts = new DBcontactsManager(MainForm2.ServerDBip, MainForm2.Schema, MainForm2.UserDB, MainForm2.PassDB, MainForm2.PortDB);
}
#endregion
#region Value from SD_LITE
enum NodeType
{
trash = 0,
inbox,
outbox,
grInbox,
grOutbox,
subInbox,
subOutbox
}
internal static ArrayList arVehSCID;
ArrayList arInboxSMS;
ArrayList arDeletedSMS;
public static Hashtable htGroupsKeyNAmeValueID;
#endregion
#region New values
public static volatile Int32 cntaddr = 0;
public static Hashtable GrpIdforScId = new Hashtable();
public static List<User> UsersList;
public static Hashtable AddrHass = new Hashtable();
public static Int32 AddrCnt = 0;
public static Hashtable IdReportHS = new Hashtable();
public static Hashtable PopupOpen = new Hashtable();
public static Int32 HistSpeedLimit = 5;
public static Int32 HistUpperSpeedLimit = 5;
public static Dictionary<String, LiveTabWind> LiveTabs = new Dictionary<string, LiveTabWind>();
public static ArrayList HistTabs = new ArrayList();
public static RADIOTYPE radioType = RADIOTYPE.HARRIS;
private Int32 cntlive = 0;
public static Boolean PlayingFile = false;
public static Int32 PlayingFileCount = 0;
public Boolean VoiceFirstTime = true;
public static Int32 AlarmCountNotAck = 0;
public SMSuserControl SMSControl = null;
public RadioTab RadioTabControl = null;
public TicketingUserControl TicketingControl = null;
public ReportCont RepControl = null;
public TelemTab TelemGOControl = null;
public TelemTabGIS TelemGISControl = null;
public LandZoneCfg LandZoneControl = null;
public LandZoneCfgGIS LandZoneGISControl = null;
public static Boolean GoogleMapCheck = false;
public static String ArcGisFileName = "";
public static Color HyteraColor = Color.Moccasin;
public static Color HarrisColor = System.Drawing.SystemColors.ControlDark;
public static Color HarTextColor = Color.White;
public static Boolean hasAudibleAlerts = false;
#endregion
private static Boolean isVoiceModuleEnabled = false;
#region Language
private String lasttimeRef = "";
public static ResourceManager RManager;
/// Hashtable for keep the units and dispatchers
public static Dictionary<Int32, String> allDispatchersNames = new Dictionary<int, string>();
public static string returnLNGString(string name)
{
string returnSTR = "";
string temp = RManager.GetString(name, culture);
returnSTR = temp;
if (temp != null)
if (temp.Contains("\\r\\n"))
{
returnSTR = temp.Replace("\\r\\n", "\r\n");
}
return returnSTR;
}
private void setLanguage()
{
msgRetAddr = returnLNGString("retrevAddr");
labelReportDetails.Text = returnLNGString("systemDescription");
rcbDropDropDownUnitEvent.NullText = rdpEndTime.NullText = rdpStartTime.NullText = rcbDropDownEventType.NullText = returnLNGString("displayall");
radLabel4.Text = returnLNGString("eventype");
radLabel6.Text = returnLNGString("eventfrom");
radLabel2.Text = returnLNGString("eventuntil");
radLabel3.Text = returnLNGString("unit");
labelReportName.Text = returnLNGString("sysLog");
kmh = returnLNGString("kmh");
milesh = returnLNGString("milesh");
langTime = returnLNGString("alarmsListColumns1") + ":";
langSpeed = returnLNGString("tablevehiclesListColumns3") + ":";
tabLive.Text = returnLNGString("tabLive");
tabHistory.Text = returnLNGString("tabHist");
tabTelem.Text = returnLNGString("tabTelem");
tabGeo.Text = returnLNGString("tabGeo");
tabSystem.Text = returnLNGString("system");//"System";//returnLNGString("tabHelp");
tabReport.Text = returnLNGString("tabRep");
tabVoice.Text = returnLNGString("tabVoice");
tabNewRadio.Text = returnLNGString("radio");
if (radioType == RADIOTYPE.LINX || radioType == RADIOTYPE.LINXB)
tabNewRadio.Text = returnLNGString("voice");
if (radioType == RADIOTYPE.REPEATER_TRBO)
tabVoice.Text = returnLNGString("tabrec");
tabSMS.Text = returnLNGString("tabSMS");
tabAlerts.Text = returnLNGString("tabAlerts");
tabTicketing.Text = returnLNGString("tabTicketing");
lasttimeRef = MainForm2.returnLNGString("lbLastTime");
btExportReport.Text = returnLNGString("exporttolog");
SystemGridView.Columns["Type"].HeaderText = returnLNGString("type");
SystemGridView.Columns["opcode"].HeaderText = returnLNGString("code");
SystemGridView.Columns["imei"].HeaderText = returnLNGString("imei");
SystemGridView.Columns["comand"].HeaderText = returnLNGString("cmd");
SystemGridView.Columns["SysEventMsg"].HeaderText = returnLNGString("eventype");
SystemGridView.Columns["HumanMsg"].HeaderText = returnLNGString("eventMessage");
SystemGridView.Columns["timecmd"].HeaderText = returnLNGString("datetimefil");
documentWindow3.Text = returnLNGString("filters");
rcbAutoRefresh.Text = returnLNGString("enableautorefreshgrid");
btForceRefresh.Text = MainForm2.returnLNGString("forceRefresh");
}
#endregion
#region LoadValue
private void LoadValue()
{
try
{
DBsettingsManager tmp = new DBsettingsManager(ServerDBip, Schema, UserDB, PassDB, PortDB);
HashVal = tmp.getAllSettings(userIDX);
//start
try
{
if (HashVal.ContainsKey("iconTheme"))
{
iconThemeType = IconTheme.GetIconType(HashVal["iconTheme"].ToString());
SafeMobileLib.Utils.WriteLine("IconType is: " + HashVal["iconTheme"].ToString(), ConsoleColor.Yellow);
}
//get Separator
string decimalSeparator = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
// if (MainForm2.culture.Name.StartsWith("en")) DayFirst = false;
Console.WriteLine("PC culture: " + System.Globalization.CultureInfo.CurrentCulture.Name);
if (System.Globalization.CultureInfo.CurrentCulture.Name.StartsWith("en")) DayFirst = false;
else DayFirst = true;
String tmpLat = (String)HashVal["startLar"];
String tmpLng = (String)HashVal["startLng"];
if ((decimalSeparator == ",") && (tmpLat.Contains(".")))
{
tmpLat = tmpLat.Replace(".", ",");
tmpLng = tmpLng.Replace(".", ",");
}
else if ((decimalSeparator == ".") && (tmpLat.Contains(",")))
{
tmpLat = tmpLat.Replace(",", ".");
tmpLng = tmpLng.Replace(",", ".");
}
try
{
LatStart = Convert.ToDouble(tmpLat);
LngStart = Convert.ToDouble(tmpLng);
}
catch (Exception ex)
{
LatStart = 42.060647;
LngStart = -88.02413;
SM.Debug("Error load LAT, LNG Start force default LatStart = 42.060647,LngStart = -88.024134");
}
{
iconThemeType = IconTheme.GetIconType(HashVal["iconTheme"].ToString());
SafeMobileLib.Utils.WriteLine("IconType is: " + HashVal["iconTheme"].ToString(), ConsoleColor.Yellow);
}
}
catch
{
LatStart = 42.060647;
LngStart = -88.02413;
SM.Debug("Error load LAT, LNG Start force default LatStart = 42.060647,LngStart = -88.024134");
}
try
{
ZoomStart = Convert.ToInt32(Convert.ToDecimal(HashVal["startZoom"]));
if (ZoomStart == 0) ZoomStart = 1;
}
catch
{
ZoomStart = 2;
SM.Debug("Error load Zoom Start force default ZoomStart = 2");
}
isInMile = StaticMembers.isInMile = (((String)HashVal["startUnits"]) == "0") ? false : true;
try
{
if (((String)HashVal["startAddress"]) == "0") is24hours = false;
else is24hours = true;
}
catch { SM.Debug("Error load time format set default fotmat to 24hour"); is24hours = true; }
ComputeAddress = Convert.ToBoolean(HashVal["hisCompAddr"]);
PlayTime = Convert.ToInt32(HashVal["hisPlayTime"]);
PauseTime = Convert.ToInt32(HashVal["hisPauseTime"]);
LastDay = Convert.ToBoolean(HashVal["hisQuick"]);
HistSpeedLimit = Convert.ToInt32(HashVal["hisMinSpeed"]);
HistUpperSpeedLimit = Convert.ToInt32(HashVal["hisMaxSpeed"]);
StaticMembers.IDLETime = Convert.ToInt32(HashVal["repIdleTime"]);
//live
HideInactiveUnitsCheck = Convert.ToBoolean(HashVal["liveCheck"]);
Livelastmin = Convert.ToInt32(HashVal["liveIdleTime"]);
Displaywithname = Convert.ToBoolean(HashVal["liveNameDisplay"]);
if (!tmp.getSettingValue(0, DBsettingsManager.EMERGENCY_ONLY_KEY).Equals(""))
{
emergOnlyCheck = Convert.ToBoolean(tmp.getSettingValue(0, DBsettingsManager.EMERGENCY_ONLY_KEY));
}
else emergOnlyCheck = false;
String tmpVal = HashVal["liveMultiColor"].ToString().ToUpper();
if ((tmpVal.CompareTo("TRUE") == 0) || (tmpVal.CompareTo("FALSE") == 0))
{
MainForm2.iconType = Convert.ToBoolean(HashVal["liveMultiColor"]) == true ? IconType.ARROWS : IconType.ICONS;
}
else
{
if (((String)HashVal["liveMultiColor"]).CompareTo("0") == 0) MainForm2.iconType = IconType.ICONS;
else if (((String)HashVal["liveMultiColor"]).CompareTo("1") == 0) MainForm2.iconType = IconType.ARROWS;
else MainForm2.iconType = IconType.EMERG;
}
if (isInMile) Measure = " " + milesh;
else Measure = " " + kmh;
}
catch (Exception ex)
{
SM.Debug("Unable to load value from database" + ex.ToString());
}
}
#endregion
#region InitData
private void LoadHashTable()
{
arInboxSMS = new ArrayList();
arVehSCID = new ArrayList();
arDeletedSMS = new ArrayList();
try
{
PlaceTypes = smdbObj.get_all_place_type_picture();
if (MapType.Equals(MapTYPE.ArcGis))
{
PlaceTypesGIS = smdbObj.get_all_place_type_picture_GIS();
}
SM.Debug("Place count:" + PlaceTypes.Count);
}
catch (Exception e)
{
SM.Debug("Erorr load place" + e.Message);
}
// populate the gateways
try
{
DBgw = new DBgatewaysManager(MainForm2.ServerDBip, MainForm2.Schema, MainForm2.UserDB, MainForm2.PassDB, MainForm2.PortDB);
List<Gateway> listgw = DBgw.getAllGateways();
foreach (Gateway rad in listgw)
{
// skip the gateways that are not active
if (!rad.Active)
continue;
List<RadioGateway> listRadgw = DBgw.gelAllRadioGateways_forUser(rad.Id, MainForm2.userIDX);
MainForm2.myGatewaylist.AddRange(listRadgw.Where(x => x.Gw_voice == 1).ToList());
}
}
catch (Exception ex)
{
Utils.WriteLine("Error on load gateway: " + ex.ToString(), ConsoleColor.Red);
}
try
{
try
{
RadioListIP = smdbObj.get_all_GatewaywithIDandIP();
SM.Debug("Radio count:" + RadioListIP.Count);
AlarmforUnitList = smdbObj.get_all_Alarm_Pop_Sound();
SM.Debug("Alarm count:" + AlarmforUnitList.Count);
smdbObj.oneConnectionHASH();
if (MainForm2.cnt_User_Radio_assign == 0)
{
try
{
smdbObj.AssignGatewayToUsers();
}
catch (Exception ex)
{
Console.WriteLine("Error on force assign radio to users:" + ex.ToString());
}
}
}
catch (Exception e)
{
SM.Debug("Ex1:" + e.ToString());
if ((MainForm2.radioType == RADIOTYPE.HARRIS) || (MainForm2.radioType == RADIOTYPE.ATLAS)) ((RadLabel)RadMessageBox.Instance.Controls[1]).LabelElement.ForeColor = MainForm2.HarTextColor;
RadMessageBox.Show(MainForm2.returnLNGString("oldDB"), MainForm2.returnLNGString("error"), MessageBoxButtons.OK, RadMessageIcon.Error);
this.Dispose();
return;
}
ArrayList vehandIDList = smdbObj.get_vehicles_and_ID(out VehIDHash, out VehIMEIHash, out arVehSCID);
Utils.WriteLine($"Received {vehandIDList.Count} vehicles", ConsoleColor.Green);
Boolean hasVoice = false;
Boolean hasSMS = false;
if (((radioType == RADIOTYPE.MOTO) || (radioType == RADIOTYPE.LINX) || (radioType == RADIOTYPE.LINXB)
|| (radioType == RADIOTYPE.HYT) || (radioType == RADIOTYPE.SIMOCO) || (radioType == RADIOTYPE.EXCERA)
|| (radioType == RADIOTYPE.TETRA)
|| (radioType == RADIOTYPE.REPEATER_TRBO)
|| (radioType == RADIOTYPE.HARRIS)) && (HasVoice))
{
hasVoice = true;
isVoiceModuleEnabled = true;
}
if (!isVoiceModuleEnabled)
{
documentTabStrip1.Controls.Remove(tabVoice);
documentTabStrip1.Controls.Remove(tabNewRadio);
}
if (SMSDecide) hasSMS = true;
//==========================
// populate vehicles
//==========================
for (int i=0; i < vehandIDList.Count; i++)
{
VehandID obj = (VehandID)vehandIDList[i];
try
{
//alarmsound
SoundandPopup tmp = new SoundandPopup(obj.sc_id, true, true, true, true, true, true, true, true);
foreach (SoundandPopup obx in AlarmforUnitList)
{
if (obx.sc_id == obj.sc_id)
{
tmp = obx;
break;
}
}
Car c = ((Car)MainForm2.carlist[obj.IconID]);
if (obj.groupID == 0)
obj.groupName = MainForm2.returnLNGString("otherunit");
Hashtable prevMapsHT = new Hashtable();
// store the previous live tabs for this unit
if (vehicleHT.ContainsKey(obj.Name))
prevMapsHT = ((Vehicle)(vehicleHT[obj.Name])).MapsHT;
// add the vehicle to the hash table
vehicleHT[obj.Name] = new Vehicle(obj.Name, null, obj.color, obj.IconID, obj.Imei, obj.sc_id, obj.veh_id, obj.report_int, this, obj.is_stolen, tmp)
{
GwandRadioID = obj.GwandRadioID,
IconName = c.googleAddresPath,
group = new SafeMobileLib.Group(obj.groupID, obj.groupName, 0),
hasEmailAlert = obj.hasEmailAlert,
hasLandmarkAlert = obj.hasLandmarkAlert,
hasEmergencyAlert = obj.hasEmergencyAlert,
hasLoneWorkerAlert = obj.hasLoneWorkerAlert,
hasSpeedAlert = obj.hasSpeedAlert,
hasZoneAlert = obj.hasZoneAlert,
hasTelemetryAlert = true,
has_voice = hasVoice,
has_text = hasSMS,
canMakeSipCalls = MainForm2.radioType == RADIOTYPE.EXCERA ? true : obj.canMakeSipCalls,
sipID = MainForm2.radioType == RADIOTYPE.EXCERA ? int.Parse(obj.Imei) : obj.sipID,
MapsHT = prevMapsHT
};
((Vehicle)vehicleHT[obj.Name]).has_text = SMSDecide; //VehIDHash.Add(obj.sc_id, obj.Name);VehIDHash.Add(obj.sc_id, obj.Name);
StaticMembers.vehicleHT[obj.Name] = new VehicleForReports(obj.Name, null, obj.color, obj.IconID, obj.Imei, obj.sc_id, obj.veh_id, obj.report_int, obj.is_stolen);
}
catch (Exception ex) { SM.Debug("Fail to add VECHICLE in hash:" + obj.ToString()); }
}
//========================================
// get all history colors for units
//========================================
foreach (DictionaryEntry pair in HashVal)
{
try
{
if (pair.Key.ToString().StartsWith("histColor"))
{
Int32 sc_id = 0;
int.TryParse(Clean_sc_id(pair.Key.ToString().Substring(10)) , out sc_id);
if (VehIDHash.ContainsKey(sc_id))
{
string veh_name = (String)VehIDHash[sc_id];
((Vehicle)vehicleHT[veh_name]).histcolor = ColorTranslator.FromHtml(pair.Value.ToString());
}
}
if (pair.Key.ToString().StartsWith("isFav"))
{
// units FAV value should not contain GROUP, ALL, DISPATCHE text
if (!pair.Key.ToString().Contains("_GROUP_") && !pair.Key.ToString().Contains("_ALL_")
&& !pair.Key.ToString().Contains("_DISPATCHER_"))
{
Int32 sc_id = 0;
int.TryParse(Clean_sc_id(pair.Key.ToString().Substring(6)), out sc_id);
if (Boolean.Parse(pair.Value.ToString()))
{
if (VehIDHash.ContainsKey(sc_id))
{
string veh_name = (String)VehIDHash[sc_id];
((Vehicle)vehicleHT[veh_name]).is_favorite =
Boolean.Parse(pair.Value.ToString());
}
}
}
}
}
catch (Exception ex)
{
Utils.WriteLine("EXCEPTION ON GET HashVal VALUES: " + ex.ToString(), ConsoleColor.Red);
}
}
//====================================
// Populate images to the dictionary
//====================================
String GroupNameforgrid = "";
foreach (String obj in MainForm2.vehicleHT.Keys)
{
GroupNameforgrid = MainForm2.returnLNGString("otherunit");
if (MainForm2.GrpIdforScId[((Vehicle)MainForm2.vehicleHT[obj]).sc_id] != null)
GroupNameforgrid = ((GroupClass)MainForm2.GrpIdforScId[((Vehicle)MainForm2.vehicleHT[obj]).sc_id]).name;
Car crtCar = ((Car)MainForm2.carlist[((Vehicle)MainForm2.vehicleHT[obj]).IconID]);
if (crtCar == null)
{
Utils.WriteLine("nullllll", ConsoleColor.Cyan);
continue;
}
String iconPath = crtCar.listFilePath;
try
{
Bitmap bmp = new Bitmap(iconPath);
Image tmp2 = Utils.ScaleImage(bmp, 64, 64); //tmp.ToBitmap();
tmp2.Tag = crtCar.listFilePath;
// add image to the dictionary if not exists
if (!MainForm2.imagesDictionary.ContainsKey(crtCar.listFilePath))
MainForm2.imagesDictionary.Add(crtCar.listFilePath, tmp2);
}
catch (Exception)
{
Utils.WriteLine("Grid icon could not be found [" + iconPath + "]");
}
}
try
{
ArrayList TempPosition = smdbObj.get_lastPos3();
Utils.WriteLine("LastPos count:" + TempPosition.Count);
foreach (SMposition obj in TempPosition)
{
//=============================================================
Vehicle vehicle = vehicleHT[obj.m_vehName] as Vehicle;
//=============================================================
if (vehicle != null)
{
vehicle.SetLATandLast(obj.m_lat);
vehicle.SetLNGandLast(obj.m_lng);
vehicle.SetALTandLast(obj.m_alt);
vehicle.SetSpeed(obj.m_speed);
vehicle.SetTimeFrist(obj.m_time); // SetTime(
// update the last Valid GPS Time
if ((Math.Round(obj.m_lat) != 0) || (Math.Round(obj.m_lng) != 0))
vehicle.SetValidGPSTime(obj.m_time);
vehicle.SetDI(obj.m_di);
vehicle.SetDO(obj.m_do);
vehicle.SetLastAddress(obj.m_address);
vehicle.actual_status = (Status_for_tab)obj.m_motostat;
}
}
}
catch (Exception ex)
{
Utils.WriteLine("lastpos <> vehnames Ex:" + ex.ToString());
}
//====================================
///get telemetry info for each vehicle
//====================================
try
{
string veh_name = "";
DBtelemetryManager tmptel = new DBtelemetryManager(ServerDBip, Schema, UserDB, PassDB, PortDB);
List<TelemetryObj> ListAllTelem = tmptel.getAllTelemetryObjsAll();
Utils.WriteLine("TelemALL count:" + ListAllTelem.Count);
List<TelemetryPOS> ListPosTelem = tmptel.GetTelemetryPOSAll();
Utils.WriteLine("telemPOS count:" + ListPosTelem.Count);
foreach (TelemetryObj obj in ListAllTelem)
{
veh_name = (String)VehIDHash[obj.Sc_Id];
if (!string.IsNullOrEmpty(veh_name))
{
((Vehicle)vehicleHT[veh_name]).telemList.Add(obj);
((VehicleForReports)StaticMembers.vehicleHT[veh_name]).telemList.Add(obj);
}
}
foreach (TelemetryPOS obj in ListPosTelem)
{
veh_name = (String)VehIDHash[obj.Sc_id];
if (!string.IsNullOrEmpty(veh_name))
{
((Vehicle)vehicleHT[veh_name]).telemPos = obj;
((VehicleForReports)StaticMembers.vehicleHT[veh_name]).telemPos = obj;
}
}
}
catch (Exception ex)
{
Utils.WriteLine("Telemetry load prolem" + ex.ToString());
}
// get number of unread SMS
nrOfUnreadMessages = smdbObj.GetNumberOfUnreadMessages(userIDX);
//set user ON
smdbObj.SetUserState(userIDX, true);
}
catch (Exception ex)
{
Utils.WriteLine("lastpos <> vehnames EX:" + ex.ToString());
}
//===========================
//job ticketing statuses
//===========================
try
{
DBTicketingManager DBT = new DBTicketingManager(cfg.DB_IP, cfg.DB_schema, cfg.DB_user, cfg.DB_passwd, cfg.DB_port);
List<TicketingStatus> ticketStatuses = DBT.getAllTicketStatuses();
Utils.WriteLine("Job ticketing statuses count:" + ticketStatuses.Count);
foreach (TicketingStatus obj in ticketStatuses)
// add ticket to hash
{
if (!TicketingStatusesHT.Contains(obj.Status))
TicketingStatusesHT.Add(obj.Status, obj);
}
}
catch (Exception ex)
{
Utils.WriteLine("Error on load " + ex.ToString());
}
}
public static string Clean_sc_id(string input)
{
Regex digitsOnly = new Regex(@"[^\d]");
return digitsOnly.Replace(input, "");
}
private static Double tmpxLat = 0;
private static Double tmpxLNG = 0;
private static volatile String StrxLat = "";
private static volatile String StrxLNG = "";
public static String FixDoubleLAT(String s)
{
StrxLat = s;
try
{
tmpxLat = Convert.ToDouble(s);
tmpxLat = (Math.Round(tmpxLat * 100000)) / 100000;
if (tmpxLat <= -90) StrxLat = "-89.99";
else if (tmpxLat >= 90) StrxLat = "89.99";
}
catch (Exception ex)
{
StrxLat = "0";
Utils.WriteLine("Erorr convert LAT:" + ex.ToString());
}
return StrxLat.Replace(',', '.');
}
public static String FixDoubleLNG(String s)
{
StrxLNG = s;
try
{
tmpxLNG = Convert.ToDouble(s);
tmpxLNG = (Math.Round(tmpxLNG * 100000)) / 100000;
if (tmpxLNG <= -180) StrxLNG = "-179.99";
else if (tmpxLNG >= 180) StrxLNG = "179.99";
}
catch (Exception ex)
{
StrxLNG = "0";
Utils.WriteLine("Erorr convert LAT:" + ex.ToString());
}
return StrxLNG.Replace(',', '.');
}
public static String FixComma(String s)
{
if (s == null)
return "";
else
{
String tmp = s;
tmp = tmp.Replace(',', ' ');
tmp = tmp.Replace('\'', '`');
return tmp;
}
}
#endregion
public static void CheckCreateEmergencyIcon(int iconID)
{
Car crtCar = ((Car)MainForm2.carlist[iconID]);
if (crtCar == null)
{
Utils.WriteLine("nullllll", ConsoleColor.Cyan);
return;
}
String iconPath = crtCar.fileName;
try
{
if (File.Exists(iconPath.Replace(".png", "_FF79A6_l.png")))
{
// emergency icon was created i can return
return;
}
else
{
Bitmap bmp = new Bitmap(iconPath);
bmp = Utils.ChangeColor(bmp, Color.FromArgb(255, 0, 0));
bmp.Save(iconPath.Replace(".png", "_FF79A6_l.png"));
// Dispose
bmp.Dispose();
}
}
catch (Exception ex)
{
Utils.WriteLine("CheckCreateEmergencyIcon: " + ex.ToString());
}
}
public static void CheckCreateNamedIcon(int iconID, String vehicleName, int sc_id)
{
Car crtCar = ((Car)MainForm2.carlist[iconID]);
if (crtCar == null)
{
Utils.WriteLine("nullllll", ConsoleColor.Cyan);
return;
}
String iconPath = crtCar.fileName;
String labeledFileExtension = "_" + iconID + "_" + sc_id + ".png";
try
{
if (File.Exists(iconPath.Replace(".png", labeledFileExtension)))
{
// named icon was created i can return
return;
}
else
{
using (Bitmap bmp = new Bitmap(iconPath))
{
using (Graphics gr1 = Graphics.FromImage(bmp))
{
// Set up string.
Font stringFont = new Font("Segoe UI", 8, FontStyle.Regular);
SizeF stringSize = gr1.MeasureString(vehicleName, stringFont);
stringSize.Width += 4;
stringSize.Height += 2;
using (Bitmap emptyCanvas = new Bitmap(bmp.Width + (int)stringSize.Width, bmp.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb))
{
using (Graphics gr = Graphics.FromImage(emptyCanvas))
{
// Draw pin with no affects
gr.DrawImage(bmp, 0, 0, bmp.Width, bmp.Height);
// Draw rectangle representing size of string.
gr.FillRectangle(new SolidBrush(Color.FromArgb(255,40,123,167)), bmp.Width / 2, bmp.Height - stringSize.Height, stringSize.Width + bmp.Width / 2, stringSize.Height);
// Draw string to screen.
gr.DrawString(vehicleName, stringFont, Brushes.White, new PointF(bmp.Width / 2, bmp.Height - stringSize.Height + 1));
Image resizedImage = Utils.ScaleImage(emptyCanvas, emptyCanvas.Width, emptyCanvas.Height);
resizedImage.Save(iconPath.Replace(".png", labeledFileExtension));
emptyCanvas.Dispose();
// Dispose
bmp.Dispose();
resizedImage.Dispose();
}
}
}
};
}
}
catch (Exception ex)
{
Utils.WriteLine("CheckCreateNamesIcon: " + ex.ToString());
}
}
#region Refresh Time
long Computation(BackgroundWorker worker, DoWorkEventArgs e)
{
try
{
currentPositions.Clear();
currentPositions = smdbObj1.get_lastPos3();
if (MapType == MapTYPE.Google)
{
foreach (LiveTabWind objw in LiveTabs.Values)
{
objw.livetab.updatecomand = "updateDataset,vehicles_positions";
objw.livetab.getADDRcomand = "";
objw.livetab.deleteDsetcomand = "deleteFromDataset,vehicles_positions";
}
}
timenowsec = (int)(DateTime.Now.GetSecondsLocalFromDT());
//SM.Debug("In computation: " + timenowsec);
foreach (SMposition obj in currentPositions)
{
//====================================================
Vehicle vehicle = vehicleHT[obj.m_vehName] as Vehicle;
//====================================================
if (vehicle != null)
{
//SM.Debug("Compare Time1: " + obj.m_time + " " + ((Vehicle)vehicleHT[obj.m_vehName]).lastTime + " NAME: " + obj.m_vehName);
if (obj.m_time >= vehicle.lastActivityTime)
{
foreach (LiveTabWind objw in LiveTabs.Values)
{
String tabNameSel = "";
if (MapType == MapTYPE.Google)
tabNameSel = objw.livetab.tabName;
else if (MapType == MapTYPE.ArcGis)
tabNameSel = objw.livetabgis.tabName;
//================================================================
MapElement mapElement = vehicle.MapsHT[tabNameSel] as MapElement;
//================================================================
mapElement.vehCompute = false;
if (mapElement.isActive)
{
//SM.Debug("Compare PArt2: " + ((Vehicle)vehicleHT[obj.m_vehName]).lastTime + " < " + (timenowsec - (Livelastmin * 60)) + " NAME: " + obj.m_vehName);
//vehCompute = true;
if (HideInactiveUnitsCheck)
if (vehicle.lastActivityTime < (timenowsec - (Livelastmin * 30)))
{
SM.Debug("Deactivate Pushpin from compute");
mapElement.DeactivatePushpin();
//vehCompute = true;
if (MapType == MapTYPE.Google)
{
objw.livetab.deleteDsetcomand += "," + obj.m_vehName;
vehicle.RemoveFromMap = true;
}
}
else { mapElement.vehCompute = true; }
else { mapElement.vehCompute = true; }
}
else
{
if (HideInactiveUnitsCheck)
if ((vehicle.lastActivityTime > (timenowsec - (Livelastmin * 30)))
&& (mapElement.itemCheck))
{
mapElement.ActivatePushPin();
mapElement.vehCompute = true;
}
}
}
vehicle.SetLAT(obj.m_lat);
vehicle.SetLNG(obj.m_lng);
vehicle.SetALT(obj.m_alt);
vehicle.SetTime(obj.m_time);
// update the last Valid GPS Time
if ((Math.Round(obj.m_lat) != 0) || (Math.Round(obj.m_lng) != 0))
vehicle.SetValidGPSTime(obj.m_time);
vehicle.SetSpeed(obj.m_speed);
vehicle.SetDI(obj.m_di);
vehicle.SetDO(obj.m_do);
foreach (LiveTabWind objw in LiveTabs.Values)
{
String tabNameSel = "";
if (MapType == MapTYPE.Google) tabNameSel = objw.livetab.tabName;
else if (MapType == MapTYPE.ArcGis) tabNameSel = objw.livetabgis.tabName;
//================================================================
MapElement mapElement = vehicle.MapsHT[tabNameSel] as MapElement;
//================================================================
if ((System.Math.Round(obj.m_lat) == 0) && (System.Math.Round(obj.m_lng) == 0)) mapElement.vehCompute = false;
if (mapElement.vehCompute)
{
bool newLalLong = mapElement.SetLastLocation();
#region NEW POSITION RECEIVED
if (newLalLong)
{
try
{
mapElement.SetLastPushpin();
mapElement.ActivatePushPin();
}
catch (Exception ex)
{
SM.Debug("Display Telerik.WinControls.UI.RadButton don't click: " + ex.ToString());
}
if (MapType == MapTYPE.Google)
{
//Google choice
if (mapElement.pp != null)
{
AddrGISQueue.Enqueue(new AddrAndID(obj.m_vehName, vehicle.LAT, vehicle.LNG));
vehicle.SetLastAddress(msgRetAddr);
mapElement.pp.Note += "<br>" + FixComma(vehicle.lastAddress);
}
DateTime positionTime = (vehicle.lastValidPositionTime.ConvertGMTToLocal()).GetDTFromSeconds();
// change scheduled value to future position to be displayed in the grid
string timeAgo = LiveGridCellElement.GetDateTimeAgo(positionTime);
string time = timeAgo.Equals(MainForm2.returnLNGString("scheduled")) ? MainForm2.returnLNGString("inTheFuture") : timeAgo;
int daysDifference = DateTime.Now.Subtract(positionTime).Days;
if (daysDifference < 1)
time = String.Format("{0, 17} [{1:HH:mm:ss}]", time, positionTime);
else if (positionTime.Year == DateTime.Now.Year)
time = String.Format("{0, 17} [{1:MM/dd HH:mm:ss}]", time, positionTime);
else
time = String.Format("{0, 17} [{1:MM/dd/yyyy HH:mm:ss}]", time, positionTime);
string iconName = mapElement.pp.GetSymbName();
if (((Vehicle)vehicleHT[obj.m_vehName]).is_emergency)
{
iconName = iconName.Replace(".png", "_FF79A6_l.png");
// check and create emergency icon
CheckCreateEmergencyIcon(vehicle.IconID);
}
// set the command which will contains the points icon, name, speed, lat, lng, altitude, address
objw.livetab.updatecomand = objw.livetab.updatecomand + ","
+ FixDoubleLAT(obj.m_lat.ToString()) + ","
+ FixDoubleLNG(obj.m_lng.ToString()) + ","
+ positionTime.ToString("yyyy-MM-dd HH:mm:ss") + ","
+ mapElement.pp.Name + ","
+ vehicle.GetSpeed() + (MainForm2.isInMile ? "mph" : "kph") + ","
+ vehicle.GetAlt() + ","
+ vehicle.GetLastAddress().Replace(',', ' ') + ","
//+ mapElement.pp.GetSymbName() + ","
+ iconName + ","
+ vehicle.has_voice + "," + vehicle.has_text + "," + vehicle.inCall;
//+ ((MapElement)((Vehicle)vehicleHT[obj.m_vehName]).MapsHT[tabNameSel]).pp.Note + ","
if ((NoteAddr[obj.m_vehName] == null))
NoteAddr.Add(obj.m_vehName, mapElement.pp.Note);
else
NoteAddr[obj.m_vehName] = mapElement.pp.Note;
}
else if (MapType == MapTYPE.ArcGis)
{
if (mapElement.GISID != -1)
AddrGISQueue.Enqueue(new AddrAndID(obj.m_vehName, vehicle.LAT, vehicle.LNG));
}
}
#endregion
else
{
if (vehicle.lastAddress.CompareTo("") == 0)
{
if (MapType == MapTYPE.Google)
{
if (mapElement.pp != null)
mapElement.pp.Note = langSpeed + " "
+ Convert.ToString(vehicle.GetSpeed()) + Measure + " "
+ langTime + " " + vehicle.lastActivityTime.TimeOfDayHHMMLocal();
}
else if (MapType == MapTYPE.ArcGis)
{
if (mapElement.GISID != -1)
mapElement.UpdateLabelCMD(false);
}
}
else
if (MapType == MapTYPE.Google)
{
if (mapElement.pp != null)
mapElement.pp.Note = langSpeed + " "
+ Convert.ToString(vehicle.GetSpeed()) + Measure + " "
+ langTime + " " + vehicle.lastActivityTime.TimeOfDayHHMMLocal()
+ "<br>" + vehicle.lastAddress.Replace(',', ' ');
}
else if (MapType == MapTYPE.ArcGis)
{
if (mapElement.GISID != -1)
mapElement.UpdateLabelCMD(true);
}
}
//cand dau check si nu aret address ala lastpos
if ((((Vehicle)vehicleHT[obj.m_vehName]).lastAddress.CompareTo("") == 0) || (vehicle.lastAddress.CompareTo(" ") == 0))
{
if (MapType == MapTYPE.Google)
{
if (mapElement.pp != null)
{
//google choice
AddrGISQueue.Enqueue(new AddrAndID(obj.m_vehName, vehicle.LAT, vehicle.LNG));
vehicle.SetLastAddress(msgRetAddr);
mapElement.pp.Note += "<br>" + FixComma(vehicle.lastAddress);
//}
}
}
else if (MapType == MapTYPE.ArcGis)
{
if (mapElement.GISID != -1)
AddrGISQueue.Enqueue(new AddrAndID(obj.m_vehName, vehicle.LAT, vehicle.LNG));
}
}
if (MapType == MapTYPE.Google)
{
if (NoteAddr[obj.m_vehName] != null)
if (((String)NoteAddr[obj.m_vehName]) != mapElement.pp.Note)
{
DateTime positionTime = vehicle.lastValidPositionTime.ConvertGMTToLocal().GetDTFromSeconds();
string iconName = mapElement.pp.GetSymbName();
if (vehicle.is_emergency)
{
iconName = iconName.Replace(".png", "_FF79A6_l.png");
// check and create emergency icon
CheckCreateEmergencyIcon(vehicle.IconID);
}
int smsLength = SmsUtils.GetMaxNumberOfCharacters(MainForm2.radioType);
#region mapCallTimeout
int mapCallTimeout = 3;
((Vehicle)MainForm2.vehicleHT[obj.m_vehName]).CheckPositionInSystem();
string GatewayAndRadioID = vehicle.GwandRadioID;
int gwType = (int)GatewayType.Unknown;
if (MainForm2.radioGwHT[GatewayAndRadioID] != null)
{
if (((RadioGateway)MainForm2.radioGwHT[GatewayAndRadioID]).Type == (int)GatewayType.Broadband ||
((RadioGateway)MainForm2.radioGwHT[GatewayAndRadioID]).Type == (int)GatewayType.Tier3Radio)
{
mapCallTimeout = MainForm2.MapCallTimeout;
}
gwType = ((RadioGateway)MainForm2.radioGwHT[GatewayAndRadioID]).Type;
smsLength = SmsUtils.GetMaxNumberOfCharacters(gwType);
}
#endregion
bool hasVoice = documentTabStrip1.Controls.Contains(tabVoice) || documentTabStrip1.Controls.Contains(tabNewRadio);
bool hasText = documentTabStrip1.Controls.Contains(tabSMS);
// set the command which will contains the points icon, name, speed, lat, lng, altitude, address
objw.livetab.updatecomand = objw.livetab.updatecomand + ","
+ FixDoubleLAT(obj.m_lat.ToString()) + ","
+ FixDoubleLNG(obj.m_lng.ToString()) + ","
+ positionTime.ToString("yyyy-MM-dd HH:mm:ss") + ","
+ mapElement.pp.Name + ","
+ vehicle.GetSpeed() + (MainForm2.isInMile ? "mph" : "kph") + ","
+ vehicle.GetAlt() + ","
+ vehicle.GetLastAddress().Replace(',', ' ') + ","
+ iconName + "," + (hasVoice ? mapCallTimeout : 0) + "," + (hasText ? smsLength : 0) + "," + vehicle.inCall;
}
}
}
} // end foreach lives
}
}
}
worker.ReportProgress(0);
}
catch (Exception ev)
{
SM.Debug("File: LiveTabs.cs Meth: computation livetab.cs: " + ev.ToString());
Connfailed = true;
}
return 1;
}
volatile private Boolean volHit = false;
volatile private String voltoret = "";
public static Int32 getMapPointZoom()
{
Int32[] toreturn = { 1, 2, 8, 24, 70, 200, 580, 1700, 5000, 10000, 32000 };
if ( MainForm2.ZoomStart >=0 && MainForm2.ZoomStart <= 10)
return toreturn[MainForm2.ZoomStart];
return 32000;
}
#endregion
#region Traking
/// <summary>
/// Add a new Tool Window of specific type
/// </summary>
/// <param name="Type">Type of the tool window</param>
/// <param name="toolwin"></param>
private void AddTrackWindow(track_type Type, ToolWindow toolwin)
{
switch (Type)
{
case track_type.LIVE:
if (MapType == MapTYPE.Google)
{
LiveTab tmpx = new LiveTab(this, toolwin.Text);
tmpx.OnAlertRequiredReceived += delegate (LiveTab.AlertRequiredEventArgs e)
{
// fire the alarm event
AlarmTracking_Click(null, null);
};
//tmpWind.Text = "Live";
tmpx.Visible = true;
tmpx.Dock = System.Windows.Forms.DockStyle.Fill;
tmpx.Location = new System.Drawing.Point(0, 0);
toolwin.Controls.Add(tmpx);
if (LiveTabs.ContainsKey(toolwin.Text))
LiveTabs.Remove(toolwin.Text);
LiveTabs.Add(toolwin.Text, new LiveTabWind(toolwin, tmpx));
// add tab to the user settings
VisualSettings.SetLiveTabVisibility(toolwin.Text, true);
}
else if (MapType == MapTYPE.ArcGis)
{
LiveTabGIS tmpx = new LiveTabGIS(this, "Live" + cntlive);
//tmpWind.Text = "Live";
tmpx.Visible = true;
tmpx.Dock = System.Windows.Forms.DockStyle.Fill;
tmpx.Location = new System.Drawing.Point(0, 0);
toolwin.Controls.Add(tmpx);
if (LiveTabs.ContainsKey(toolwin.Text))
LiveTabs.Remove(toolwin.Text);
LiveTabs.Add(toolwin.Text, new LiveTabWind(toolwin, tmpx));
}
cntlive++;
break;
case track_type.HIST:
if (MapType == MapTYPE.Google)
{
HistoryTab tmph = new HistoryTab(this, "History" + cntlive);
//tmpWind.Text = "History";
tmph.Visible = true;
tmph.Dock = System.Windows.Forms.DockStyle.Fill;
tmph.Location = new System.Drawing.Point(0, 0);
toolwin.Controls.Add(tmph);
HistTabs.Add(new HistTabWind(toolwin, tmph));
}
else if (MapType == MapTYPE.ArcGis)
{
HistoryTabGIS tmph = new HistoryTabGIS(this, "History" + cntlive);
//tmpWind.Text = "History";
tmph.Visible = true;
tmph.Dock = System.Windows.Forms.DockStyle.Fill;
tmph.Location = new System.Drawing.Point(0, 0);
toolwin.Controls.Add(tmph);
}
cntlive++;
break;
case track_type.LANDZONE:
if (MapType == MapTYPE.Google)
{
LandZoneControl = new LandZoneCfg(this);
LandZoneControl.Visible = true;
LandZoneControl.Dock = System.Windows.Forms.DockStyle.Fill;
LandZoneControl.Location = new System.Drawing.Point(0, 0);
toolwin.Controls.Add(LandZoneControl);
}
else if (MapType == MapTYPE.ArcGis)
{
LandZoneGISControl = new LandZoneCfgGIS("LandZone" + cntlive);
LandZoneGISControl.Visible = true;
LandZoneGISControl.Dock = System.Windows.Forms.DockStyle.Fill;
LandZoneGISControl.Location = new System.Drawing.Point(0, 0);
toolwin.Controls.Add(LandZoneGISControl);
}
cntlive++;
break;
case track_type.SMS:
SMSControl = new SMSuserControl(this);
SMSControl.Visible = true;
SMSControl.Dock = System.Windows.Forms.DockStyle.Fill;
SMSControl.Location = new System.Drawing.Point(0, 0);
toolwin.Controls.Add(SMSControl);
break;
case track_type.TICKETING:
TicketingControl = new TicketingUserControl(this);
TicketingControl.Visible = true;
TicketingControl.Dock = System.Windows.Forms.DockStyle.Fill;
TicketingControl.Location = new System.Drawing.Point(0, 0);
toolwin.Controls.Add(TicketingControl);
break;
case track_type.RADIO:
try
{
RadioTabControl = new RadioTab(this);
RadioTabControl.Visible = true;
RadioTabControl.Dock = System.Windows.Forms.DockStyle.Fill;
RadioTabControl.Location = new System.Drawing.Point(0, 0);
toolwin.Controls.Add(RadioTabControl);
//VoiceFirstTime = false;
}
catch (Exception ex)
{
SM.Debug("Erorr create radio:" + ex.ToString());
}
break;
case track_type.REPORTS:
RepControl = new ReportCont();
RepControl.Visible = true;
RepControl.Dock = System.Windows.Forms.DockStyle.Fill;
RepControl.Location = new System.Drawing.Point(0, 0);
toolwin.Controls.Add(RepControl);
break;
case track_type.TELEM:
if (MapType == MapTYPE.Google)
{
TelemGOControl = new TelemTab(this);
TelemGOControl.Visible = true;
TelemGOControl.Dock = System.Windows.Forms.DockStyle.Fill;
TelemGOControl.Location = new System.Drawing.Point(0, 0);
toolwin.Controls.Add(TelemGOControl);
}
else if (MapType == MapTYPE.ArcGis)
{
TelemGISControl = new TelemTabGIS(this);
TelemGISControl.Visible = true;
TelemGISControl.Dock = System.Windows.Forms.DockStyle.Fill;
TelemGISControl.Location = new System.Drawing.Point(0, 0);
toolwin.Controls.Add(TelemGISControl);
}
break;
}
}
#endregion
#region comunication
public Hashtable Listcmd = new Hashtable();
UdpMulticast udp = null;
Int32 cmdcnt = 0;
public volatile Queue CmdList = new Queue();
public volatile Hashtable WaitConfirm = new Hashtable();
public static volatile UdpMulticast udp4Voice;
public volatile Hashtable IDHyteraLast = new Hashtable();
public static InterthreadMessageQueue<string> gpsQueue = new InterthreadMessageQueue<string>();
public static InterthreadMessageQueue<string> statusUpdateQueue = new InterthreadMessageQueue<string>();
public static Dictionary<String, Status_for_tab> radioIdToStatus = new Dictionary<string, Status_for_tab>();
private void initComunicaton()
{
udp = new UdpMulticast(cfg.MSG_BUS_IP, Convert.ToInt32(cfg.MSg_BUS_port));
udp.StartListen(cfg.LocalIP);
udp.OnNewDataRecv += new UdpMulticast.newData4Send(udp_OnNewDataRecv);
string voiceMulticastIP = "224.20." + MainForm2.userIDX + ".1"; //"224.10.1.0";
udp4Voice = new UdpMulticast(voiceMulticastIP, Convert.ToInt32(cfg.V_MSG_BUS_port));
udp4Voice.StartListen(cfg.LocalIP);
Utils.WriteLine($"UDP for voice started listening on interface {cfg.LocalIP}", ConsoleColor.Cyan);
// start a task that will consume the unit status messages (153)
Task.Factory.StartNew(() => ConsumeUnitStatus());
// start a task that will consume the gps messages (131, 231)
Task.Factory.StartNew(() => ConsumeGPS());
}
private void ConsumeUnitStatus()
{
Utils.WriteLine("Consuming Unit status", ConsoleColor.Magenta);
while (MainForm2.isRunning)
{
try
{
string line = statusUpdateQueue.GetItem(100);
while (line != default(string))
{
string[] tempArr = line.Split("#".ToCharArray());
if (tempArr.Length > 4 && tempArr[3].Equals("153"))
{
string radioID = tempArr[4];
Status_for_tab status = (Status_for_tab)Convert.ToInt32(tempArr[5]);
String nameveh = VehIMEIHash[radioID].ToString();
int sc_id = ((Vehicle)vehicleHT[nameveh]).sc_id;
if (VehIDHash[sc_id] != null)
{
((Vehicle)vehicleHT[(String)VehIDHash[sc_id]]).actual_status = status;
//Utils.WriteLine("153 Command : " + (String)VehIDHash[sc_id] + " | " + status.ToString(), ConsoleColor.DarkRed);
this.Invoke((MethodInvoker)delegate ()
{
UpdateStatusLive((String)VehIDHash[sc_id]);
// update the number of unack alerts - I don't think it is required here only if on emergency
if (((Vehicle)vehicleHT[(String)VehIDHash[sc_id]]).actual_status == Status_for_tab.EMERG)
{
AlarmChange(true, rep_type.EMERG, (String)VehIDHash[sc_id], "", false);
UpdateNumberOfUnAckAlerts();
}
});
}
}
// get the new status
line = statusUpdateQueue.GetItem(100);
}
}
catch (Exception ex)
{
Utils.WriteLine("Error on updating unit status " + ex.ToString(), ConsoleColor.DarkRed);
}
}
}
private void ConsumeGPS()
{
Utils.WriteLine("Consuming GPS", ConsoleColor.Magenta);
while (MainForm2.isRunning)
{
try
{
string line = gpsQueue.GetItem(100);
while (line != default(string))
{
string[] tempArr = line.Split("#".ToCharArray());
if (tempArr.Length > 4 && (tempArr[3].Equals("131") || tempArr[3].Equals("231")))
{
String[] locString = new String[4];
for (int i = 0; i < 4; i++)
{
locString[i] = tempArr[i + 5];
}
LocationDecoder dec2 = new LocationDecoder(tempArr[4], locString);
htCell_t tmpcell = dec2.cell;
if (tmpcell.lat == null)
{
tmpcell.lat = "0";
tmpcell.lng = "0";
tmpcell.spd = "0";
tmpcell.location_time = DateTime.UtcNow;
}
Int32 speed = Convert.ToInt32(Convert.ToDouble(tmpcell.spd));
Commands tmpCOM = new Commands(Convert.ToInt32(tempArr[3]), tempArr[4], tmpcell.location_time.GetSecondsFromDT(),
Convert.ToDouble(tmpcell.lat), Convert.ToDouble(tmpcell.lng), speed,
Convert.ToInt32(tmpcell.di), Convert.ToDouble(tmpcell.alt));
string radioID = tempArr[4];
Status_for_tab status = (Status_for_tab)Convert.ToInt32(tempArr[5]);
if (!VehIMEIHash.ContainsKey(radioID))
{
// get the new status
line = gpsQueue.GetItem(100);
continue;
}
String nameveh = VehIMEIHash[radioID].ToString();
//==================================================
Vehicle vehicle = (Vehicle)vehicleHT[nameveh];
//==================================================
//UpdateStatusLive(nameveh);
int sc_id = vehicle.sc_id;
vehicle.SetSpeed((byte)tmpCOM.speed);
if (tmpCOM.lat != 0 || tmpCOM.lng != 0)
{
vehicle.SetLAT(tmpCOM.lat);
vehicle.SetLNG(tmpCOM.lng);
}
vehicle.SetALT(tmpCOM.alt);
vehicle.SetDI((byte)tmpCOM.di);
vehicle.SetTime(tmpCOM.time);
//((Vehicle)vehicleHT[nameveh]).StartTimer();
if ((Math.Round(tmpCOM.lat) != 0) || (Math.Round(tmpCOM.lng) != 0))
{
// update the last Valid GPS Time
vehicle.SetValidGPSTime(tmpCOM.time);
vehicle.needAddress = true;
AddrGISQueue.Enqueue(new AddrAndID(nameveh, tmpCOM.lat, tmpCOM.lng));
if (MapType == MapTYPE.Google)
{
//aici se face update google
SendDataToMapQUE.PostItem(nameveh);
try { if (SendDataToMapHASH[nameveh] == null) SendDataToMapHASH.Add(nameveh, 0); }
catch(Exception ex) { Utils.WriteLine(ex.ToString(), ConsoleColor.Red); }
}
}
if (VehIDHash[sc_id] != null)
{
if (MapType != MapTYPE.Google)
{
this.Invoke((MethodInvoker)delegate ()
{
foreach (String name in ((Vehicle)vehicleHT[nameveh]).MapsHT.Keys)
{
//================================================================
MapElement mapElement = vehicle.MapsHT[name] as MapElement;
//================================================================
if (((HideInactiveUnitsCheck) && mapElement.itemCheck) ||
(emergOnlyCheck && vehicle.actual_status == Status_for_tab.EMERG))
{
mapElement.isActive = true;
}
// update the location
if (Math.Round(vehicle.LAT) != 0 && Math.Round(vehicle.LNG) != 0)
{
mapElement.SetLastLocation();
}
if (mapElement.isActive)
{
if (Math.Round(vehicle.LAT) != 0 && Math.Round(vehicle.LNG) != 0)
{
mapElement.SetLastPushpin();
Utils.WriteLine("ActivatePushPin on ProgressChanged");
mapElement.ActivatePushPin();
}
if ((MainForm2.POLLunit == nameveh) && (vehicle.LAT != 0 && vehicle.LNG != 0))
{
MovePOLL = true;
if (MapType == MapTYPE.ArcGis)
mapElement.AxMapGIS.Extent
= MainForm2.ZoomTo(((Vehicle)MainForm2.vehicleHT[MainForm2.POLLunit]).LNG, ((Vehicle)MainForm2.vehicleHT[MainForm2.POLLunit]).LAT,
((Vehicle)MainForm2.vehicleHT[MainForm2.POLLunit]).LNG, ((Vehicle)MainForm2.vehicleHT[MainForm2.POLLunit]).LAT);
Thread.Sleep(1);
}
}
}
if (MovePOLL)
{ MainForm2.POLLunit = ""; MovePOLL = false; }
//ONLY FOR TEST
foreach (LiveTabWind obj in LiveTabs.Values)
{
if (MapType == MapTYPE.Google)
obj.livetab.CenterAndOpenBubble(nameveh);
else if (MapType == MapTYPE.ArcGis)
obj.livetabgis.CheckForUpdate(nameveh);
}
});
}
else
{
foreach (LiveTabWind obj in LiveTabs.Values)
{
//SafeMobileLib.Utils.WriteLine("UPDATE FROM POSITION ", ConsoleColor.Yellow);
bool isFirstPositionForUnit = false;
if (vehicle.lastLocLAT == 0.1 && vehicle.lastLocLNG == 0.1)
isFirstPositionForUnit = true;
if (vehicle.LAT != 0 && vehicle.LNG != 0)
{
vehicle.first_live_gps = true;
obj.livetab.onGPSPositionReceivedHandler(nameveh, isFirstPositionForUnit);
}
}
}
lastupdate = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
if (tempArr[3].Equals("231"))
{
this.Invoke((MethodInvoker)delegate ()
{
SMSDesktopAlert.FixedSize = new System.Drawing.Size(329, 120);
SMSDesktopAlert.ContentImage = resources.alert_gps;
html_message = "<span><size=11><color=blue>" + returnLNGString("RecLoc") + ": " + nameveh + " </span>";
SMSDesktopAlert.ContentText = "<html>" + html_message + "</html>"; // mesajul din interior editat cu html
title = returnLNGString("pollResp");
SMSDesktopAlert.CaptionText = title;
//SMSDesktopAlert.ContentText = (e.UserState as String);
SMSDesktopAlert.Show();
//force check unit on the list
foreach (LiveTabWind obj in LiveTabs.Values)
{
if (MapType == MapTYPE.Google)
{
obj.livetab.onPollResponseReceivedHandler((Vehicle)vehicleHT[nameveh]);
}
}
});
}
}
}
// get the new status
line = gpsQueue.GetItem(100);
}
}
catch (Exception ex)
{
Utils.WriteLine("Error on updating unit status " + ex.ToString(), ConsoleColor.DarkRed);
}
}
}
private void udp_OnNewDataRecv(byte[] data, int dataLen)
{
string str = "";
try
{
String seqID = "1";
str = System.Text.Encoding.ASCII.GetString(data, 0, dataLen);
//SM.Debug("RX: " + str.Trim());
Utils.WriteLine($"<22><><EFBFBD> MB: {str}", ConsoleColor.Yellow);
SystemMessQueue.PostItem(new SystemLog(false, str.Trim()));
//find seqID in parse
String[] tmp = str.Split("#".ToCharArray());
String Station = "";
String GwPlusRadio = "";
Boolean findstation = false;
if (((tmp.Length) >= 3) && (str.Length == Convert.ToInt32(tmp[1])))
{
switch (tmp[3])
{
case "124":
if (VoiceTabStarted)
{
}
break;
case "121":
int result = Convert.ToInt32(tmp[5]);
Utils.WriteLine("Received " + tmp[3] + " | " + result);
UpdateRadioGWPTTStatus(result, tmp[4]);
if (!String.IsNullOrEmpty(tmp[6]))
{
if (Convert.ToInt32(tmp[6]) != MainForm2.userIDX)
break;
}
OnCallStatusHangChanged(RadioTabControl.selected_Subscriber.DispatcherName, (result == 1), false, tmp[4]);
if (Listcmd[tmp[2]] != null) SaveValue(((TimerAndResp)Listcmd[tmp[2]]), result, Convert.ToInt32(tmp[3]));
break;
case "251":
if ((MainForm2.TicketingDecide) && ((Boolean)tabsHash[tabTicketing.Name]) == true)
CmdList.Enqueue(new Commands(Convert.ToInt32(tmp[3]), tmp[4], false));
break;
case "100":
if (VoiceTabStarted)
{
}
break;
case "202":
if (VoiceTabStarted)
{
}
break;
case "212":
if (VoiceTabStarted)
{
}
break;
case "221":
OnCallStatusHangChanged(RadioTabControl.selected_Subscriber.DispatcherName, true, false, "");
if (Listcmd[tmp[2]] != null)
{
SaveValue(((TimerAndResp)Listcmd[tmp[2]]), Convert.ToInt32(tmp[5]), Convert.ToInt32(tmp[3]));
cmdcnt++;
seqID = MainForm2.userIDX + "." + cmdcnt;
RadioTabControl.WatchList.Add(seqID);
}
break;
case "201":
if (Convert.ToInt32(tmp[4]) == userIDX)
{
String[] tmpStr = tmp[2].ToString().Split(".".ToCharArray());
if (VoiceTabStarted)
{
RadioTab.PersonalIP = String.Format("224.20.{0}.1", tmpStr[0]);
cmdcnt++;
seqID = MainForm2.userIDX + "." + cmdcnt;
TimerAndResp tmptime = new TimerAndResp(null, false);
if (tmp.Length > 6)
{
tmptime.GrpID = Convert.ToInt32(tmp[6]);
}
else tmptime.GrpID = 0;
if (tmptime.GrpID == 0)
{
RadioTabControl.StartCallPatch("Dispatcher", "Dispatcher." + tmpStr[0], tmpStr[0].ToString());
}
String[] tmpIP = tmp[5].ToString().Split(".".ToCharArray());
SaveValue(tmptime, Convert.ToInt32(tmpIP[2]), Convert.ToInt32(tmp[3]));
RadioTabControl.WatchList.Add(seqID);
Listcmd.Add(seqID, tmptime);
Send_UDP_cmd_sent_withOutID($"#{tmp[2]}#221#0#1#");
}
}
break;
case "211":
if (Convert.ToInt32(tmp[4]) == userIDX)
{
String[] tmpStr = tmp[2].ToString().Split(".".ToCharArray());
if (VoiceTabStarted)
{
RadioTab.PersonalIP = String.Format("224.20.{0}.1", tmpStr[0]);
cmdcnt++;
seqID = MainForm2.userIDX + "." + cmdcnt;
TimerAndResp tmptime = new TimerAndResp(null, false);
String[] tmpIP = tmp[5].ToString().Split(".".ToCharArray());
SaveValue(tmptime, Convert.ToInt32(tmpIP[2]), Convert.ToInt32(tmp[3]));
RadioTabControl.WatchList.Add(seqID);
Listcmd.Add(seqID, tmptime);
}
}
break;
case "162":
case "122":
string dispatcherID = null;
if (!String.IsNullOrEmpty(tmp[6]))
dispatcherID = tmp[6];
Utils.WriteLine("Received " + tmp[3] + " | " + int.Parse(tmp[5]));
Handle122Command(tmp[2], tmp[4], int.Parse(tmp[5]), dispatcherID);
break;
case "123":
dispatcherID = null;
if (!String.IsNullOrEmpty(tmp[6]))
dispatcherID = tmp[6];
Utils.WriteLine("Received " + tmp[3] + " | " + int.Parse(tmp[5]));
Handle123Command(tmp[2], tmp[4], int.Parse(tmp[5]), dispatcherID);
break;
case "125":
if (tmp[2] == "0.0" && tmp.Length == 9) // Don't process 125 commands sent by the SD for recordings (for EXCERA or LINX)
{
string[] tmp4Arr = tmp[4].Split(".".ToCharArray());
Utils.WriteLine("tmp[4].Split('.')[0] = " + tmp4Arr[0] + "\r\n" +
"tmp[4].Split('.')[1] = " + tmp4Arr[1] + "\r\n" +
"tmp[4].Split('.')[2] = " + tmp4Arr[2] + "\r\n" +
"int.Parse(tmp[5]) = " + tmp[5] + "\r\n" +
"int.Parse(tmp[6]) = " + tmp[6] + "\r\n" +
"tmp[7] = " + tmp[7]);
Utils.WriteLine("RECEIVED " + tmp[3] + " | " + int.Parse(tmp[5]));
try
{
string[] arrData = tmp[4].Split(".".ToCharArray());
if (arrData != null)
{
string gatewayID = arrData[0];
string gatewayRadioID = arrData[1];
string sourceRadioID = arrData[2];
int _callStatus = 0;
int _callType = 0;
int _targetID = 0;
int.TryParse(tmp[5], out _callStatus);
int.TryParse(tmp[6], out _callType);
int.TryParse(tmp[7], out _targetID);
Handle125Command(gatewayID, gatewayRadioID, sourceRadioID, _callStatus, _callType, _targetID);
}
}
catch (System.OverflowException ov)
{
SafeMobileLib.Utils.WriteLine("Error or Parse 125Command: " + ov.ToString(), ConsoleColor.Red);
}
}
break;
case "155":
//test = "#155#" + rec.id.ToString() + "#" + rec.hddLocation + "#" + rec.gwID + "#" + rec.radioGWID + "#" + rec.Group_ID + "#" + rec.subID.ToString() + "#" + rec.startTime + "#" + rec.endTime + "#" + rec.typeSD + "#" + rec.calltype + "#";
Utils.WriteLine("tmp " + tmp[6] + " | " + tmp[7]);
GwPlusRadio = $"{tmp[6]}.{tmp[7]}";
RadioTab.responseGW = GwPlusRadio;
int callType = -1;
Int32.TryParse(tmp[13], out callType);
findstation = false;
if (VoiceTabStarted)
{
foreach (RadioGateway obj in myGatewaylist)
{
if ((GwPlusRadio.CompareTo((String)(obj.Gw_id.ToString() + '.' + obj.Id.ToString())) == 0))
{
findstation = true;
break;
}
}
//dispatcher to dispatcher call
if (callType == 3)
findstation = true;
// in need see the case when I talk
if (findstation)
{
Int64 recId = Convert.ToInt64(tmp[4]);
Int32 startTime = Convert.ToInt32(tmp[10]);
Int32 endTime = Convert.ToInt32(tmp[11]);
DateTime startDateTime = Convert.ToInt32(tmp[10]).ConvertGMTToLocal().GetDTFromSeconds();
DateTime endDateTime = Convert.ToInt32(tmp[11]).ConvertGMTToLocal().GetDTFromSeconds();
string hddLocation = tmp[5];
int? subs_imei = null;
if (tmp[9] != "")
subs_imei = Convert.ToInt32(tmp[9]);
int gwID = Convert.ToInt32(tmp[6]);
int radioGWID = Convert.ToInt32(tmp[7]);
int typeSD = Convert.ToInt32(tmp[12]);
int? _group_cpsId = null;
if (tmp[8] != "")
_group_cpsId = Convert.ToInt32(tmp[8]);
int? dispatcher_id = null;
dispatcher_id = Convert.ToInt32(tmp[14]);
SafeMobileLib.Recording tmpRec = new SafeMobileLib.Recording(recId,
startTime, endTime,
startDateTime, endDateTime,
hddLocation,
subs_imei,
gwID,
radioGWID,
typeSD,
callType,
_group_cpsId,
dispatcher_id);
RadioTabControl.Addrow(tmpRec);
}
}
break;
case "230":
case "130":
if (VehIMEIHash[tmp[4]] != null)
{
try
{
string strData = tmp[5];
if (strData[0] != 'O')
{
byte[] forDecodeData2 = getBytesFromRawData(data);
ARSdecoder dec2 = new ARSdecoder();
SafeMobileLib.MessageDecoders.ARSdecoder.header_T tmpHead = dec2.DecodePacket(forDecodeData2);
switch (tmpHead.pdu_type)
{
case 0x00: // registration
goto case 0x0F;
case 0x0F: // query reply
CmdList.Enqueue(new Commands(Convert.ToInt32(tmp[3]), tmp[4], true));
break;
case 0x01: // deregistration
CmdList.Enqueue(new Commands(Convert.ToInt32(tmp[3]), tmp[4], false));
break;
default: break;
}
}
else
{
bool isArsOn = (strData == "ON");
CmdList.Enqueue(new Commands(Convert.ToInt32(tmp[3]), tmp[4], isArsOn));
}
}
catch (Exception ex)
{
SM.Debug("Error adding commands with type 130" + ex.ToString());
}
}
break;
case "153":
if (VehIMEIHash[tmp[4]] != null)
{
//Utils.WriteLine("153 Command string:" + str, ConsoleColor.Cyan);
//toParseUnitStatusMessagesQueue.PostItem(str);
//CmdList.Enqueue(new Commands(Convert.ToInt32(tmp[3]), tmp[4], Convert.ToInt32(tmp[5]), false));
//if (this == null)
// return;
//this.Invoke((MethodInvoker)delegate ()
//{
// if (tmpAlarmFrm == null)
// return;
// if (tmpAlarmFrm.Visible)
// tmpAlarmFrm?.updateList();
//});
statusUpdateQueue.PostItem(str);
}
break;
case "134":
{
string unitName = (string)VehIMEIHash[tmp[4]];
Utils.WriteLine($"Emergency received from {unitName}", ConsoleColor.Yellow);
Thread.Sleep(30);
// do not update if the unit name is not found <=> not assigned
if (unitName == null)
break;
// do not update the emergency if the unit isn't assigned to this dispatcher
if (!MainForm2.vehicleHT.ContainsKey(unitName))
{
Utils.WriteLine($"!MainForm2.vehicleHT.ContainsKey(unitName)", ConsoleColor.Cyan);
break;
}
if (((Vehicle)vehicleHT[unitName]).hasEmergencyAlert)
{
string description = "";
if (tmp[5] != null)
description = (tmp[5] == "") ? "" : ((EmergencyTypes)(Convert.ToInt32(tmp[5]))).ToString();
((Vehicle)vehicleHT[VehIMEIHash[tmp[4]].ToString()]).EventLists.Add(new Alarms(rep_type.EMERG, DateTime.Now, "", description));
}
else
Utils.WriteLine($"!((Vehicle)vehicleHT[unitName]).hasEmergencyAlert", ConsoleColor.Cyan);
break;
}
case "10":
/* if (Listcmd[tmp[2]] != null)
{
String[] tmpzone = tmp[5].Split('.');
SaveValue(((TimerAndResp)Listcmd[tmp[2]]), Convert.ToInt32(tmpzone[0]) * 100 + Convert.ToInt32(tmpzone[1]), Convert.ToInt32(tmp[3]));
}
else if (tmp[2] == "0.0")
{*/
Boolean findstationX = false;
if (VoiceTabStarted)
{
}
/*if (mainRadioForms != null)
foreach (ShapeNew obj in mainRadioForms)
{
if (tmp[4] == obj.gwandradID)
{
cmdcnt++;
seqID = MainForm2.userIDX + "." + cmdcnt;
((radioFrom)obj).WatchList.Add(seqID);
findstationX = true;
break;
}
*/
if (findstationX)
{
TimerAndResp tmptime = new TimerAndResp(null, false);
SaveValue(tmptime, Convert.ToInt32(tmp[5]), Convert.ToInt32(tmp[3]));
Listcmd.Add(seqID, tmptime);
}
//}
break;
case "207":
if (tmp[2] == "0.0")
{
findstation = false;
if (VoiceTabStarted)
{
}
/*if ((mainRadioForms != null) && (tmp[5] != MainForm2.userIDX.ToString()))
foreach (ShapeNew obj in mainRadioForms)
{
if (tmp[4] == obj.gwandradID)
{
cmdcnt++;
seqID = MainForm2.userIDX + "." + cmdcnt;
((radioFrom)obj).WatchList.Add(seqID);
findstation = true;
break;
}
}*/
if (findstation)
{
TimerAndResp tmptime = new TimerAndResp(null, false);
SaveValue(tmptime, Convert.ToInt32(tmp[6]), Convert.ToInt32(tmp[3]));
Listcmd.Add(seqID, tmptime);
}
}
break;
case "111":
case "112":
case "113":
{
// requests for terminating the calls
}
break;
case "115":
case "116":
case "117":
// RESPONSE FROM TERMINATNG REQUESTS
// Get gwPlusRadio
GwPlusRadio = tmp[4];
string[] parts = GwPlusRadio.Split(".".ToCharArray());
if (parts.Length > 2)
GwPlusRadio = $"{parts[0]}.{parts[1]}";
// gateway is not in ptt
if (radioGwHT.ContainsKey(GwPlusRadio))
{
Utils.WriteLine("RECEIVED " + tmp[3]);
((RadioGateway)(radioGwHT[GwPlusRadio])).InPTT = false;
/*
((RadioGateway)(radioGwHT[GwPlusRadio])).State = RadioState.IDLE;
// notify the radio tab that something changed
RadioTabControl?.OnRadioGatewayStateChanged((RadioGateway)(radioGwHT[GwPlusRadio]), RadioState.IDLE);
// CHECK IF HANGTIME*/
if (Convert.ToInt32(tmp[5]) == 1 && radioGwHT.ContainsKey(GwPlusRadio))
RadioTabControl?.OnRadioGatewayStateChanged((RadioGateway)(radioGwHT[GwPlusRadio]), RadioState.IDLE);
}
if ((Listcmd[tmp[2]] != null) && (((TimerAndResp)Listcmd[tmp[2]]).typeID > 110) && (((TimerAndResp)Listcmd[tmp[2]]).typeID < 114))
SaveValue(((TimerAndResp)Listcmd[tmp[2]]), Convert.ToInt32(tmp[5]), Convert.ToInt32(tmp[3]));
else
{
try
{
String usermess = tmp[2].Split(".".ToCharArray())[0];
if ((tmp[2] == "0.0") || (Convert.ToInt32(usermess) == userIDX))
{
findstation = false;
if (MainForm2.VoiceTabStarted)
{
foreach (RadioGateway obj in myGatewaylist)
{
if ((GwPlusRadio.CompareTo((String)(obj.Gw_id.ToString() + '.' + obj.Id.ToString())) == 0) || (GwPlusRadio.CompareTo("1.8") == 0))
{
findstation = true;
break;
}
}
}
if (findstation)
{
cmdcnt++;
seqID = MainForm2.userIDX + "." + cmdcnt;
RadioTabControl.WatchList.Add(seqID);
TimerAndResp tmptime = new TimerAndResp(null, false);
SaveValue(tmptime, 1, Convert.ToInt32(tmp[3]));
Listcmd.Add(seqID, tmptime);
if (Convert.ToInt32(tmp[3]) == 116)
RaiseOnCallStatusChangedEvent(RadioTabControl.selected_Subscriber.DispatcherName, false, false);
}
}
RadioTab.responseGW = GwPlusRadio;
}
catch (Exception ex)
{
SM.Debug("Erorr processing 115,116,117:" + ex.ToString());
}
}
break;
case "139":
try
{
if (VehIMEIHash[tmp[6]] != null)
{
int gwID0 = Convert.ToInt32(tmp[4]);
string radioGWip = tmp[5];
int radioID0 = Convert.ToInt32(tmp[6]);
int radioGateID = 0;
foreach (GatewayIDandIP obj in RadioListIP)
{
if ((obj.IP == radioGWip) && (obj.GWID == gwID0))
{
radioGateID = obj.ID;
break;
}
}
Utils.WriteLine($"Received Gateway update for {radioID0} [{gwID0}.{radioGateID}]", ConsoleColor.Green);
((Vehicle)vehicleHT[VehIMEIHash[tmp[6]].ToString()]).GwandRadioID = gwID0.ToString() + "." + radioGateID.ToString();
// flag that the unit had changed to a new gateway
this.Invoke((MethodInvoker)delegate ()
{
RadioTabControl?.updateGwAndRagioGatewayForSubscriber(tmp[6], tmp[4], radioGateID + "");
foreach (LiveTabWind obj in LiveTabs.Values)
{
if (MapType == MapTYPE.Google)
obj.livetab.updateGwAndRagioGatewayForSubscriber(tmp[6], tmp[4], radioGateID + "");
else if (MapType == MapTYPE.ArcGis)
obj.livetabgis.updateGwAndRagioGatewayForSubscriber(tmp[6], tmp[4], radioGateID + "");
}
});
}
}
catch (Exception ex)
{
SM.Debug("Error on proccess 139:" + ex.ToString());
}
break;
case "208":
{
int radioId = Convert.ToInt32(tmp[4]);
bool isStolen = (int.Parse(tmp[5]) == 1 ? true : false);
Utils.WriteLine($"Unit {radioId} is now {(isStolen ? "stolen" : "unstolen")}");
String unitName = ((Vehicle)vehicleHT[VehIMEIHash[tmp[4]].ToString()]).busName;
((Vehicle)vehicleHT[VehIMEIHash[tmp[4]].ToString()]).is_stolen = isStolen;
this.Invoke((MethodInvoker)delegate ()
{
foreach (LiveTabWind obj in LiveTabs.Values)
{
if (MapType == MapTYPE.Google)
obj.livetab.OnUnitStolenChanged(unitName, isStolen);
//obj.livetab.UpdateVehList(name, true);
else if (MapType == MapTYPE.ArcGis)
obj.livetabgis.OnUnitStolenChanged(unitName, isStolen);
}
});
}
break;
case "231":
case "131":
if (VehIMEIHash[tmp[4]] != null)
{
gpsQueue.PostItem(str);
//SM.Debug("Ticks2:" + DateTime.Now.Ticks);
}
break;
case "156":
if ((!IsInLogin) && (uniqueID == Convert.ToInt32(tmp[4])))
{
Send_UDP_cmd("#157#", 0, 0);
}
break;
case "132":
if (VehIMEIHash[tmp[4]] != null)
{
try
{
byte[] forDecodeData2 = getBytesFromRawData(data);
bool hytera = false;
if (tmp.Length > 6) if (tmp[6] == "hyt") hytera = true;
SMSdecoder dec2 = new SMSdecoder(hytera);
// detect if the message has unicode characters in it
if (tmp[5].StartsWith(Utils.MBusUnicodeChar))
{
// remove the unicode header
tmp[5] = tmp[5].Replace(Utils.MBusUnicodeChar, "");
tmp[5] = tmp[5].DecodeEncodedNonAsciiCharacters();
}
if (!hytera)
{
dec2.DecodePacket(forDecodeData2);
}
else
{
dec2.DecodePacketHyt(tmp[5]);
}
if (dec2.messBody != "")
{
if (dec2.messBody.Contains("<JTS>"))
{
CmdList.Enqueue(new Commands(Convert.ToInt32(tmp[3]), tmp[4], dec2.messBody, dec2.emailAddr));
((Vehicle)vehicleHT[VehIMEIHash[tmp[4]].ToString()]).EventLists.Add(new Alarms(rep_type.JOB_TICKETING, DateTime.Now, "", dec2.messBody));
}
else
{
if (tmp[7] != null && tmp[7] != "")
if (tmp[7] != userIDX.ToString())
break; // If sms has a destination id, check if I am the destination
if (WaitConfirm.Contains(tmp[2]))
WaitConfirm.Remove(tmp[2]);
WaitConfirm.Add(tmp[2], new Commands(Convert.ToInt32(tmp[3]), tmp[4], dec2.messBody, dec2.emailAddr));
((Vehicle)vehicleHT[VehIMEIHash[tmp[4]].ToString()]).EventLists.Add(new Alarms(rep_type.SMSRECIVE, DateTime.Now, "", dec2.messBody));
}
}
}
catch (Exception ex)
{
SM.Debug("Error adding commands with type 132" + ex.ToString());
}
}
break;
case "233":
if (VehIMEIHash[tmp[4]] != null)
{
try
{
if ((tmp.Length > 6) && (tmp[6] == "hyt"))
{
CmdList.Enqueue(new Commands(Convert.ToInt32(tmp[3]), tmp[4], Convert.ToInt32(tmp[5]), true));
}
else
{
byte[] forDecodeData2 = getBytesFromRawData(data);
Int32 tmptype = (Int32)forDecodeData2[2];
Int32 tmpbyte = (Int32)forDecodeData2[3];
//test opcode 0x10 = Announce Status 0x0C =QueryStatusResponse
if (tmptype == 0x10) CmdList.Enqueue(new Commands(Convert.ToInt32(tmp[3]), tmp[4], tmpbyte, false));
else CmdList.Enqueue(new Commands(Convert.ToInt32(tmp[3]), tmp[4], tmpbyte, true));
}
}
catch (Exception ex)
{
SM.Debug("Error adding commands with type 233" + ex.ToString());
}
}
break;
case "232":
if (WaitConfirm[tmp[2]] != null)
{
if (tmp[4] == "1") CmdList.Enqueue((Commands)WaitConfirm[tmp[2]]);
WaitConfirm.Remove(tmp[2]);
}
break;
case "238":
try
{
string IMEI = tmp[4].Split(".".ToCharArray())[2];
string unitName = (string)VehIMEIHash[IMEI];
Thread.Sleep(30);
Utils.WriteLine("Received Emergency ack for unit: " + unitName, ConsoleColor.Green);
// do not update if the unit name is not found <=> not assigned
if (unitName == null)
{
Utils.WriteLine("unit name is null ", ConsoleColor.Red);
break;
}
// do not update the emergency if the unit isn't assigned to this dispatcher
if (!MainForm2.vehicleHT.ContainsKey(unitName))
{
Utils.WriteLine("!MainForm2.vehicleHT.ContainsKey(unitName)", ConsoleColor.Red);
break;
}
((Vehicle)MainForm2.vehicleHT[unitName]).is_emergency = false;
//NEED TO DO SAME STUFSTOCK
foreach (String name in ((Vehicle)MainForm2.vehicleHT[unitName]).MapsHT.Keys)
{
((MapElement)((Vehicle)MainForm2.vehicleHT[unitName]).MapsHT[name]).UpdateSymbol();
MainForm2.RemoveIconsFromMap();
}
Utils.WriteLine("Received Emergency ack " + str, ConsoleColor.Green);
//force check unit on the list
foreach (LiveTabWind obj in LiveTabs.Values)
{
Vehicle veh = (Vehicle)MainForm2.vehicleHT[unitName];
if (MapType == MapTYPE.Google)
{
obj.livetab.onEmergencyStateChangedHandler(veh, false);
}
if (MapType == MapTYPE.ArcGis)
{
obj.livetabgis.onEmergencyStateChangedHandler(veh, false);
}
}
UpdateStatusLive(unitName);
this.Invoke((MethodInvoker)delegate ()
{
RefreshAlarmFrm(true);
UpdateNumberOfUnAckAlerts();
});
}
catch (Exception ex)
{
Utils.WriteLine("Error processing alert acknoledged" + ex.ToString(), ConsoleColor.Red);
}
break;
case "135":
case "136":
case "137":
case "140":
nrOfUnreadAlerts++;
string txt = String.Format("{0} ({1})", returnLNGString("tabAlerts"), nrOfUnreadAlerts);
SetText(txt.ToString());
//tabAlerts.Text = String.Format("{0} ({1})", returnLNGString("tabAlerts"), nrOfUnreadAlerts);
if (VehIMEIHash[tmp[4]] != null)
{
try
{
CmdList.Enqueue(new Commands(Convert.ToInt32(tmp[3]), tmp[4], tmp[5]));
if (tmp[3] == "135")
{
// skip this event if the vehicle doesn not has this alert active
if (!((Vehicle)vehicleHT[VehIMEIHash[tmp[4]].ToString()]).hasSpeedAlert)
break;
//AlarmList.Add(new Alarms(rep_type.SPEED, DateTime.Now, VehIMEIHash[tmp[4]].ToString(), tmp[5]));
((Vehicle)vehicleHT[VehIMEIHash[tmp[4]].ToString()]).EventLists.Add(new Alarms(rep_type.SPEED, DateTime.Now, "", tmp[5]));
}
else if (tmp[3] == "136")
{
// skip this event if the vehicle doesn not has this alert active
if (!((Vehicle)vehicleHT[VehIMEIHash[tmp[4]].ToString()]).hasZoneAlert)
break;
//AlarmList.Add(new Alarms(rep_type.GEOFENC, DateTime.Now, VehIMEIHash[tmp[4]].ToString(), tmp[5]));
((Vehicle)vehicleHT[VehIMEIHash[tmp[4]].ToString()]).EventLists.Add(new Alarms(rep_type.GEOFENC, DateTime.Now, "", tmp[5]));
}
else if (tmp[3] == "137")
{
// skip this event if the vehicle doesn not has this alert active
if (!((Vehicle)vehicleHT[VehIMEIHash[tmp[4]].ToString()]).hasLandmarkAlert)
break;
///AlarmList.Add(new Alarms(rep_type.LAND, DateTime.Now, VehIMEIHash[tmp[4]].ToString(), tmp[5]));
((Vehicle)vehicleHT[VehIMEIHash[tmp[4]].ToString()]).EventLists.Add(new Alarms(rep_type.LAND, DateTime.Now, "", tmp[5]));
}
else if (tmp[3] == "140")
{
// skip this event if the vehicle doesn not has this alert active
if (!((Vehicle)vehicleHT[VehIMEIHash[tmp[4]].ToString()]).hasTelemetryAlert)
break;
//AlarmList.Add(new Alarms(rep_type.TELEMETRY, DateTime.Now, VehIMEIHash[tmp[4]].ToString(), tmp[5]));
((Vehicle)vehicleHT[VehIMEIHash[tmp[4]].ToString()]).EventLists.Add(new Alarms(rep_type.TELEMETRY_ALARM, DateTime.Now, "", tmp[5]));
}
}
catch (Exception ex)
{
SM.Debug("Error adding commands with type 134" + ex.ToString());
}
}
break;
case "210":
CmdList.Enqueue(new Commands(Convert.ToInt32(tmp[3]), tmp[4], tmp[5]));
break;
case "172":
if (tmp[2] == "0.0")
{
string[] tmp4Arr = tmp[4].Split(".".ToCharArray());
if (tmp4Arr == null)
break;
Station = tmp4Arr[2];
GwPlusRadio = $"{tmp4Arr[0]}.{tmp4Arr[1]}";
findstation = false;
if (MainForm2.VoiceTabStarted)
{
foreach (RadioGateway obj in myGatewaylist)
{
if ((GwPlusRadio.CompareTo((String)(obj.Gw_id.ToString() + '.' + obj.Id.ToString())) == 0) || (GwPlusRadio.CompareTo("1.8") == 0))
{
findstation = true;
break;
}
}
if (findstation)
{
cmdcnt++;
seqID = MainForm2.userIDX + "." + cmdcnt;
RadioTabControl.WatchList.Add(seqID);
TimerAndResp tmptime = new TimerAndResp(null, false);
SaveValue(tmptime, Convert.ToInt32(Station), Convert.ToInt32(tmp[3]));
Listcmd.Add(seqID, tmptime);
}
}
}
break;
case "250":
if (VehIMEIHash[tmp[4]] != null)
{
try
{
if (tmp[5] == "0") CmdList.Enqueue(new Commands(Convert.ToInt32(tmp[3]), tmp[4], false));
else CmdList.Enqueue(new Commands(Convert.ToInt32(tmp[3]), tmp[4], true));
}
catch (Exception ex)
{
SM.Debug("Error adding commands with type 250" + ex.ToString());
}
}
break;
case "475":
try
{
if (tmp[4].IndexOf(Login.IPaddress) == -1)
{
KickOutUser();
}
}
catch (Exception ex)
{
SM.Debug("Error adding commands with type 475" + ex.ToString());
}
break;
case "501":
try
{
if (tmp[6] == null)
break;
bool status = tmp[6] == "ON" ? true : false;
if (OnRadioGatewayStatusChanged != null)
OnRadioGatewayStatusChanged(tmp[4] + "." + tmp[5], status);
this.Invoke((MethodInvoker)delegate
{
SMSDesktopAlert.ContentImage = status ? resources.green_status : resources.red_status;
SMSDesktopAlert.ContentText = string.Format(returnLNGString("gwStatusHTML"), tmp[7], tmp[6]);
SMSDesktopAlert.CaptionText = returnLNGString("gwStatus"); ;
SMSDesktopAlert.Show();
});
}
catch (Exception ex)
{
SM.Debug("Error adding commands with type 501" + ex.ToString());
}
break;
case "507":
{
appServerMonitoring?.NewHeartBeatReceived();
}
break;
//receive new patch command
case "510":
try
{
if (tmp[9] != userIDX.ToString())
{
Patch patch = new Patch()
{
Type = tmp[4],
IncomingId = tmp[5],
Incoming = tmp[6],
OutgoingId = tmp[7],
Outgoing = tmp[8]
};
RadioTabControl?.UpdateCallPatchGridViewInfo(510, patch);
}
}
catch (Exception ex)
{
SM.Debug("Error on execute 510:" + ex.ToString());
}
break;
//receive delete patch command
case "511":
try
{
if (tmp[9] != userIDX.ToString())
{
Patch patch = new Patch()
{
Type = tmp[4],
IncomingId = tmp[5],
Incoming = tmp[6],
OutgoingId = tmp[7],
Outgoing = tmp[8]
};
RadioTabControl?.UpdateCallPatchGridViewInfo(511, patch);
}
}
catch (Exception ex)
{
SM.Debug("Error on execute 511:" + ex.ToString());
}
break;
// Failover status
case "610":
if (cfg.hasFailover)
{
try
{
string messageCode = tmp[5];
this.Invoke((MethodInvoker)delegate
{
string text = MainForm2.returnLNGString(messageCode);
if (string.IsNullOrEmpty(text))
text = $"missing message: {messageCode}";
if (!messageCode.ToLower().Contains("successfully"))
BuildFailoverAlert2("Failover notification", text);
});
}
catch (Exception ex)
{
SM.Debug("Error on execute 610 (Failover status):" + ex.ToString());
}
}
break;
//force re-login on new IP
case "611":
if (cfg.hasFailover)
{
string newIP = tmp[5];
IPAddress ipAddress;
if (IPAddress.TryParse(newIP, out ipAddress))
{
cfg.UpdateConfigParameter("Server", "IP", newIP);
forceReconnectToNewIP = true;
}
}
break;
case "612":
if (hasDBAccess)
{
string websocketStatus = tmp[4];
isWebsocketConnected = (websocketStatus == "online") ? ToggleState.On : ToggleState.Off;
this.Invoke((MethodInvoker)delegate ()
{
foreach (LiveTabWind obj in LiveTabs.Values)
{
obj.livetab.OnWebSocketStatusChanged(isWebsocketConnected);
}
});
}
break;
}
}
else
{
if ((tmp.Length) >= 3)
;// SM.Debug("Difrent length: " + str.Length + " WITH " + tmp[1]);
}
}
catch (Exception ex)
{
SM.Debug($"Exceptia de la receive [{str}]:" + ex.ToString() );
}
}
delegate void SetTextCallback(string text);
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.tabAlerts.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.tabAlerts.Text = text;
}
}
private void BuildFailoverAlert(string text)
{
DockLayoutPanel dockPanel = new DockLayoutPanel();
LightVisualElement imageElement = new LightVisualElement();
imageElement.Image = resources.red_status;
LightVisualElement textElement = new LightVisualElement();
textElement.TextAlignment = ContentAlignment.MiddleLeft;
textElement.Text = text;
dockPanel.Children.Add(imageElement);
dockPanel.Children.Add(textElement);
FailoverDesktopAlert.Popup.AlertElement.ContentElement.Children.Clear();
FailoverDesktopAlert.Popup.AlertElement.ContentElement.Children.Add(dockPanel);
FailoverDesktopAlert.Popup.AlertElement.ContentElement.TextAlignment = ContentAlignment.MiddleLeft;
FailoverDesktopAlert.Popup.AlertElement.ContentElement.ImageAlignment = ContentAlignment.MiddleLeft;
FailoverDesktopAlert.Show();
}
private void BuildFailoverAlert2(string captionText, string text)
{
FailoverDesktopAlert.CaptionText = captionText;
FailoverDesktopAlert.ContentText = text;
FailoverDesktopAlert.ContentImage = resources.red_status;
FailoverDesktopAlert.Show();
}
/// <summary>
/// Handles 125 command in MainForm
/// </summary>
/// <param name="gatewayID">The ID of the Gateway App</param>
/// <param name="gatewayRadioID">The ID of the physical gateway</param>
/// <param name="sourceRadioID">The ID of the radio which initiated the call</param>
/// <param name="callStatus">The State of the call: 1 - Initiated, 2 - HangTime, 3 - Ended</param>
/// <param name="callType">The type of the call: 101 - All Call, 102 - Private Call, 103 - Group Call, 104 - Emergency Call </param>
/// <param name="targetID">The ID of the field or group which received the call</param>
internal void Handle125Command(string gatewayID, string gatewayRadioID, string sourceRadioID, int callStatus, int callType, int targetID, bool sipCall = false)
{
string GwPlusRadio = gatewayID + "." + gatewayRadioID;
RadioTab.responseGW = GwPlusRadio;
if (sipCall)
{
if (callType == 102)
RadioTab.PersonalIP = sourceRadioID;
else if (callType == 103)
RadioTab.PersonalIP = targetID.ToString();
}
else
RadioTab.PersonalIP = "224.10." + GwPlusRadio;
bool findstation = false;
if (VoiceTabStarted)
{
int index = -1;
if (sipCall)
{
findstation = true;
}
else
{
foreach (RadioGateway obj in myGatewaylist)
{
index++;
if ((GwPlusRadio.CompareTo((String)(obj.Gw_id.ToString() + '.' + obj.Id.ToString())) == 0))
{
findstation = true;
break;
}
}
}
if (findstation)
{
Utils.WriteLine("125 " + callStatus);
RadioState state = RadioState.IDLE;
// update the call status for this gateway
if (callStatus == 1)
state = RadioState.RX;
else if (callStatus == 2)
state = RadioState.HANGTIME;
else if (callStatus == 3 || callStatus == 7)
state = RadioState.IDLE;
((RadioGateway)myGatewaylist[index]).State1 = state;
// notify the radio tab that something changed
RadioTabControl?.OnRadioGatewayStateChanged((RadioGateway)(radioGwHT[GwPlusRadio]), state);
TimerAndResp tmptime = new TimerAndResp(null, false);
//if (Convert.ToInt32(tmp[5]) == 0) tmptime.StatusON = false;
//else tmptime.StatusON = true;
tmptime.callStatus = callStatus;
if ((VehIMEIHash[sourceRadioID] != null) && (vehicleHT[VehIMEIHash[sourceRadioID]] != null))
{
if (tmptime.callStatus == 1 || tmptime.callStatus == 2)
{
((Vehicle)vehicleHT[VehIMEIHash[sourceRadioID]]).inCall = true;
// trigger event for the map
if (tmptime.callStatus == 1) RaiseOnCallStatusChangedEvent(((Vehicle)vehicleHT[VehIMEIHash[sourceRadioID]]).busName, true, true);
else RaiseOnCallStatusChangedEvent(((Vehicle)vehicleHT[VehIMEIHash[sourceRadioID]]).busName, false, true);
}
else if (tmptime.callStatus == 3 || tmptime.callStatus == 7)
{
((Vehicle)vehicleHT[VehIMEIHash[sourceRadioID]]).inCall = false;
// trigger event for the map
RaiseOnCallStatusChangedEvent(((Vehicle)vehicleHT[VehIMEIHash[sourceRadioID]]).busName, false, true);
}
}
if (!sipCall)
{
if ((tmptime.callStatus > 1) && (sourceRadioID == "0"))
if (IDHyteraLast[GwPlusRadio] != null) sourceRadioID = (String)IDHyteraLast[GwPlusRadio];
tmptime.callType = callType;
tmptime.GrpID = targetID;
tmptime.gwID = gatewayID;
tmptime.radioGwID = gatewayRadioID;
SaveValue(tmptime, Convert.ToInt64(sourceRadioID), (int)MessageBusCmds.CallStatusBroadcast);
cmdcnt++;
string seqID = MainForm2.userIDX + "." + cmdcnt;
RadioTabControl.WatchList.Add(seqID);
Listcmd.Add(seqID, tmptime);
}
}
}
}
private void Handle122Command(string seqID, string gwPlusRadio, int result, string dispatherID)
{
UpdateRadioGWPTTStatus(result, gwPlusRadio);
if (!String.IsNullOrEmpty(dispatherID))
{
if (Convert.ToInt32(dispatherID) != MainForm2.userIDX)
return;
}
RaiseOnCallStatusChangedEvent(RadioTabControl.selected_Subscriber.DispatcherName, (result == 1), false);
OnCallStatusHangChanged(RadioTabControl.selected_Subscriber.DispatcherName, (result == 1), false, gwPlusRadio);
if (Listcmd[seqID] != null)
{
SaveValue(((TimerAndResp)Listcmd[seqID]), result, (int)MessageBusCmds.InitPrivateCallResponse);
}
}
private void UpdateRadioGWPTTStatus(int result, string gwPlusRadio)
{
if (result == 1) // Update the radio gateway PTT status (in ptt)
{
if (radioGwHT.ContainsKey(gwPlusRadio))
{
RadioGateway radioGateway = (RadioGateway)radioGwHT[gwPlusRadio];
radioGateway.State1 = RadioState.TX;
radioGateway.InPTT = true;
// notify the radio tab that something changed
RadioTabControl?.OnRadioGatewayStateChanged(radioGateway, RadioState.TX);
}
}
}
private void Handle123Command(string seqID, string gwPlusRadio, int result, string dispatcherID)
{
UpdateRadioGWPTTStatus(result, gwPlusRadio);
if (!String.IsNullOrEmpty(dispatcherID))
{
if (Convert.ToInt32(dispatcherID) != MainForm2.userIDX)
return;
}
OnCallStatusHangChanged(RadioTabControl.selected_Subscriber.DispatcherName, (result == 1), false, gwPlusRadio);
if (Listcmd[seqID] != null) SaveValue(((TimerAndResp)Listcmd[seqID]), result, (int)MessageBusCmds.InitGroupCallResponse);
}
private byte[] getBytesFromRawData(byte[] rawData)
{
try
{
Int32 head = 0;
for (int i = 0; i < (rawData.Length - 1); i++)
if (rawData[i] == 35) head = i;
byte[] forDecodeData3 = new byte[rawData.Length - head - 2];
Int32 j = 0;
for (int i = (head + 1); i < (rawData.Length - 1); i++)
{
forDecodeData3[j] = rawData[i];
j++;
}
return forDecodeData3;
}
catch (Exception ex)
{
SM.Debug("Ex6:" + ex.ToString());
return null;
}
}
private void SaveValue(TimerAndResp baseVar, Int64 IntVal, Int32 TypeID)
{
try
{
baseVar.typeID = TypeID;
baseVar.intval = IntVal;
baseVar.Respose = true;
baseVar.wait = false;
}
catch (Exception ex)
{
SM.Debug("Ex7:" + ex.ToString());
}
}
public String Send_delay(String cmd, Int32 timeout, Int32 ID, Int32 waittime)
{
Thread.Sleep(waittime);
return Send_UDP_cmd(cmd, timeout, ID);
}
public String Send_UDP_cmd(String cmd, Int32 timeout, Int32 ID, string userID = null)
{
try
{
String user_ID = string.IsNullOrEmpty(userID) ? MainForm2.userIDX.ToString() : userID;
cmdcnt++;
Thread.Sleep(1);
String seqID = user_ID + "." + DateTime.Now.GetSecondsLocalFromDT() + DateTime.Now.Ticks.ToString();//Millisecond.ToString();
if (timeout != 0)
{
System.Threading.Timer t1 = new System.Threading.Timer(SendStop, seqID, timeout, System.Threading.Timeout.Infinite);
try
{
Listcmd.Add(seqID, new TimerAndResp(t1, true, ID));
}
catch (Exception ex)
{
SM.Debug("Error add in listcmd Send_UDP_cmd:" + ex.ToString());
}
}
String cmdok = "";
byte[] buf = Utils.Convert_text_For_multicast("#" + seqID + cmd, out cmdok);
SystemMessQueue.PostItem(new SystemLog(true, cmdok));
udp.Send(buf, buf.Length);
return seqID;
}
catch (Exception ex)
{
SM.Debug("Ex8:" + ex.ToString());
return "";
}
}
public void Send_UDP_cmd_sent_withOutID(String cmd)
{
try
{
String cmdok = "";
byte[] buf = Utils.Convert_text_For_multicast(cmd, out cmdok);
SystemMessQueue.PostItem(new SystemLog(true, cmdok));
udp.Send(buf, buf.Length);
}
catch (Exception ex)
{
SM.Debug("Ex9:" + ex.ToString());
}
}
private void SendStop(object state)
{
try
{
if (Listcmd[state.ToString()] != null)
((TimerAndResp)Listcmd[state.ToString()]).wait = false;
}
catch (Exception ex)
{
SM.Debug("Ex10:" + ex.ToString());
}
}
private void RestartProcess210(object state)
{
try
{
processOther210 = true;
}
catch (Exception ex)
{
SM.Debug("Ex101:" + ex.ToString());
}
}
public void Send_telem(String name, String GPIOName, Int32 type)
{
try
{
Vehicle vehicle = (Vehicle)MainForm2.vehicleHT[name];
foreach (TelemetryObj obj in vehicle.telemList)
if (obj.Name == GPIOName)
{
vehicle.CheckPositionInSystem();
String Totrans = "#0.0#133#" + vehicle.GwandRadioID + "." + vehicle.IMEI + "#" + obj.DigitalNr + "." + type + "#";
Send_UDP_cmd_sent_withOutID(Totrans);
break;
}
}
catch (Exception ex)
{
SM.Debug("Ex11:" + ex.ToString());
}
}
public void Send_telem_digit(String name, Int32 Digit, Int32 type)
{
((Vehicle)MainForm2.vehicleHT[name]).CheckPositionInSystem();
String Totrans = "#0.0#133#" + ((Vehicle)MainForm2.vehicleHT[name]).GwandRadioID + "." + ((Vehicle)MainForm2.vehicleHT[name]).IMEI + "#" + Digit + "." + type + "#";
Send_UDP_cmd_sent_withOutID(Totrans);
}
public void Send_EnableOrDisable(String name, CMDTYPE Status)
{
try
{
Vehicle vehicle = (Vehicle)MainForm2.vehicleHT[name];
String Totrans = "";
switch (Status)
{
case CMDTYPE.EnableCMD:
case CMDTYPE.DisableCMD:
vehicle.CheckPositionInSystem();
Totrans = $"#{(Int32)API.RADIO_ENABLE_DISABLE_REQ}#{vehicle.GwandRadioID}.{vehicle.IMEI}#{(int)Status}#";
break;
case CMDTYPE.POLLGPSCMD:
vehicle.CheckPositionInSystem();
//Totrans = "#" + (Int32)API.POLL_GPS_REQ + "#" + ((Vehicle)MainForm2.vehicleHT[name]).GwandRadioID + "." + ((Vehicle)MainForm2.vehicleHT[name]).IMEI + "#";
// Add dispatcher (user) id to the poll gps request
Totrans = $"#{(Int32)API.POLL_GPS_REQ}#{vehicle.GwandRadioID}.{vehicle.IMEI}#{userIDX}#";
break;
case CMDTYPE.StolenONCMD:
Totrans = $"#{(Int32)API.STOLEN_REQ}#{vehicle.IMEI}#1#";
vehicle.is_stolen = true;
break;
case CMDTYPE.StolenOFFCMD:
Totrans = $"#{(Int32)API.STOLEN_REQ}#{vehicle.IMEI}#0#";
vehicle.is_stolen = false;
break;
// CHECK THE SATUS OF ON UNIT
case CMDTYPE.POLLARSCMD:
((Vehicle)MainForm2.vehicleHT[name]).CheckPositionInSystem();
Totrans = $"#{(Int32)API.POLL_ARS_REQ}#{vehicle.GwandRadioID}.{vehicle.IMEI}#{userIDX}#";
break;
}
if (Status != CMDTYPE.POLLGPSCMD)
Send_UDP_cmd(Totrans, 0, 0);
else
Send_UDP_cmd(Totrans, 0, 0);
}
catch (Exception ex)
{
SM.Debug("Error to send enable disable:" + ex.ToString());
}
}
private void checkMessage_DoWork(object sender, DoWorkEventArgs e)
{
try
{
BackgroundWorker worker = sender as BackgroundWorker;
e.Result = ComputMess(worker, e);
}
catch (Exception ex)
{
SM.Debug("Ex12:" + ex.ToString());
}
}
Boolean MovePOLL = false;
private static volatile Int32 lastupdate = 0;
private volatile Int32 volsc_id = 0;
private volatile Int32 voltypeID = 0;
private volatile String volSpeed = "";
private volatile Boolean volInMessMile;
private volatile Boolean volARSStat;
private volatile Boolean volmakeUpdate;
private volatile String volVehName = "";
private volatile String volVehNamePoll = "";
private volatile String html_message = "";
private volatile String html_status = "";
private volatile String title = "";
private volatile Boolean processOther210 = true;
public static SDRegistration verifyReg(byte[] message)
{
SDRegistration toReturn = new SDRegistration();
UTF8Encoding encoding = new UTF8Encoding();
SM.Debug("Received registration from server");
String decodedString = encoding.GetString(message);
Console.WriteLine("Result string:" + decodedString);
String[] options = decodedString.Split(";".ToCharArray());
//option[19] = audible alerts ; option[20] = db access;
if(options[19] != null)
hasAudibleAlerts = (options[19].Equals("1") ? true : false);
if (options[20] != null)
hasDBAccess = (options[20].Equals("1") ? true : false);
if (options[0].Equals("101"))
{
if (options[1].StartsWith("invalid"))
{
toReturn.ip = "invalid";
if (options[8].Equals("False"))
Utils.WriteLine("SafeDispatch is not registered.");
//toReturn.map_type = Int16.Parse(options[8]);
}
else
{
APP_SERVER_VERSION = options[1].Replace("valid-", "");
toReturn.ip = "valid";
int i = 2;
toReturn.gps = Boolean.Parse(options[i++]);
toReturn.sms = Boolean.Parse(options[i++]);
toReturn.ticketing = Boolean.Parse(options[i++]);
toReturn.reports = Boolean.Parse(options[i++]);
toReturn.voice = Boolean.Parse(options[i++]);
toReturn.recordings = Boolean.Parse(options[i++]);
toReturn.zones = Boolean.Parse(options[i++]);
toReturn.telemetry = Boolean.Parse(options[i++]);
toReturn.map_type = Int16.Parse(options[i++]);
toReturn.MSG_BUS_IP = options[i++];
toReturn.MSg_BUS_port = options[i++];
toReturn.DatabaseIP = options[i++];
toReturn.Db_schema = options[i++];
toReturn.Db_user = options[i++];
toReturn.Db_password = options[i++];
toReturn.Db_port = options[i++];
toReturn.VoiceMessageBusPort = options[i++];
}
}
return toReturn;
}
private Thread threadAppServerDown = null;
private Boolean isAppServerDownThreadRunning = false;
private void checkMessage_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
try
{
volsc_id = e.ProgressPercentage / 1000;
voltypeID = e.ProgressPercentage % 1000;
switch (voltypeID)
{
case 230:
volARSStat = Convert.ToBoolean(e.UserState as String);
SMSDesktopAlert.FixedSize = new System.Drawing.Size(329, 120);
SMSDesktopAlert.ContentImage = resources.alert_gps;
if (volARSStat) html_status = "<span><br/><br/><b><color=red><size=11>" + returnLNGString("statON") + "</b></span>";
else html_status = "<span><br/><br/><b><color=red><size=11>" + returnLNGString("statOFF") + "</b></span>";
html_message = "<span><size=11><color=blue>" + returnLNGString("RecRRS") + ": " + (String)VehIDHash[volsc_id] + " </span>";
SMSDesktopAlert.ContentText = "<html>" + html_message + html_status + "</html>"; // mesajul din interior editat cu html
title = returnLNGString("pollResp");
SMSDesktopAlert.CaptionText = title;
//SMSDesktopAlert.ContentText = (e.UserState as String);
SMSDesktopAlert.Show();
break;
case 130:
if (VehIDHash[volsc_id] != null)
UpdateStatusLive((String)VehIDHash[volsc_id]);
lastupdate = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
break;
case 251:
if (TicketingControl != null) TicketingControl.UpdateExpiredTickets(e.UserState as String);
break;
case 153:
break;
case 210:
if (processOther210)
{
if (volsc_id != 5)
{
String title = "AppServer Error";
DisplayDesktopAlertForAppServer(title, (e.UserState as String), true);
Console.WriteLine("Value of voltypeID:" + voltypeID);
}
else
{
//after recive restart from APPServer drop other #210 Stop Commands from Application server
processOther210 = false;
System.Threading.Timer t1 = new System.Threading.Timer(RestartProcess210, null, 30000, System.Threading.Timeout.Infinite);
}
if ((volsc_id == 2) || (volsc_id == 4))
{
Utils.WriteLine("Received App Server is down msg " + volsc_id, ConsoleColor.Green);
if (isAppServerDownThreadRunning)
return;
threadAppServerDown = new Thread(new ThreadStart(delegate ()
{
isAppServerDownThreadRunning = true;
// wait 1 second before testing for App Server status
Thread.Sleep(500);
Thread.Sleep(500);
//test again APPServer
Boolean DecisionDown = true;
try
{
TcpClient client = new TcpClient();
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse(MainForm2.cfg.APPLICATION_SERVER_IP), MainForm2.cfg.RegsPort);
client.Connect(serverEndPoint);
NetworkStream clientStream = client.GetStream();
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
byte[] buffer = encoding.GetBytes("100");
clientStream.Write(buffer, 0, buffer.Length);
SM.Debug("Sent registration request to server, waiting...");
byte[] message = new byte[128];
//byte[] decryptedMessage = Encryption.Decrypt(message);
clientStream.ReadTimeout = 10000;
int result = clientStream.Read(message, 0, message.Length);
SM.Debug("Received registration from server");
String decodedString = encoding.GetString(message);
String[] options = decodedString.Split(";".ToCharArray());
if (options[0].Equals("101"))
{
DecisionDown = false;
}
}
catch
{
SM.Debug("App server registration not available!");
DecisionDown = true;
}
Utils.WriteLine("App Server is " + (DecisionDown ? "DOWN" : "UP"), ConsoleColor.Green);
// if the app server is back up I should terminate
if (!DecisionDown)
return;
this.Invoke((MethodInvoker)delegate
{
RadMessageBox.Instance.Dispose();
RadMessageBox.SetThemeName("TelerikMetroBlue");
RadMessageBox.Instance.TopMost = true;
RadMessageBox.Instance.TopLevel = true;
RadMessageBox.Show(this, "Application Server is down. Please check the status of Application Server and be sure is up and running, if is still down the Dispacther will be also shut down.", "Error", MessageBoxButtons.OK, RadMessageIcon.Error);
RadMessageBox.Instance.TopMost = false;
RadMessageBox.Instance.TopLevel = false;
});
//test again APPServer
DecisionDown = true;
try
{
TcpClient client = new TcpClient();
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse(MainForm2.cfg.APPLICATION_SERVER_IP), MainForm2.cfg.RegsPort);
client.Connect(serverEndPoint);
NetworkStream clientStream = client.GetStream();
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
byte[] buffer = encoding.GetBytes("100");
clientStream.Write(buffer, 0, buffer.Length);
SM.Debug("Sent registration request to server, waiting...");
byte[] message = new byte[128];
//byte[] decryptedMessage = Encryption.Decrypt(message);
clientStream.ReadTimeout = 10000;
int result = clientStream.Read(message, 0, message.Length);
SM.Debug("Received registration from server");
String decodedString = encoding.GetString(message);
String[] options = decodedString.Split(";".ToCharArray());
if (options[0].Equals("101"))
{
DecisionDown = false;
}
}
catch
{
SM.Debug("App server registration not available!");
DecisionDown = true;
}
if (DecisionDown && MainForm2.isRunning)
{
this.Invoke((MethodInvoker)delegate
{
RadMessageBox.Instance.Dispose();
RadMessageBox.SetThemeName("TelerikMetroBlue");
RadMessageBox.Instance.TopMost = true;
RadMessageBox.Instance.TopLevel = true;
RadMessageBox.Show(this, "Dispacther will be also shut down because Application Server is still down.", "Error", MessageBoxButtons.OK, RadMessageIcon.Error);
RadMessageBox.Instance.TopMost = false;
RadMessageBox.Instance.TopLevel = false;
appServerMonitoring?.StopMonitoring();
if (MainForm2.ActiveForm != null && MainForm2.ActiveForm.InvokeRequired)
{
MainForm2.ActiveForm?.Invoke((MethodInvoker)delegate ()
{
MainForm2.ActiveForm?.Close();
//System.Environment.Exit(0);
this.Close();
System.Windows.Forms.Application.Exit();
});
}
else
{
MainForm2.ActiveForm?.Close();
//System.Environment.Exit(0);
this.Close();
System.Windows.Forms.Application.Exit();
}
});
}
//MainForm2.ActiveForm.Close();
//System.Environment.Exit(0);
isAppServerDownThreadRunning = false;
}));
threadAppServerDown.Start();
}
}
break;
case 231:
case 131:
{
}
break;
case 132:
if (_sipClient != null)
{
// Check if sender is motorola
if (!((Vehicle)vehicleHT[(String)VehIDHash[volsc_id]]).canMakeSipCalls)
{
string message = ((messBody)e.UserState).body;
// Check if sms is from motorola to linx
if (message.IndexOf("linx", 0, StringComparison.InvariantCultureIgnoreCase) == 0)
{
int indexOfFirstPoint;
if ((indexOfFirstPoint = message.IndexOf('.', 4)) != -1)
{
string linxIDstring = message.Substring(4, indexOfFirstPoint - 4);
int linxID;
if (int.TryParse(linxIDstring, out linxID))
{
// check if destination id is a linx
if (VehIMEIHash.Contains(linxIDstring))
{
if (((Vehicle)vehicleHT[VehIMEIHash[linxIDstring]]).canMakeSipCalls)
break;
}
}
}
}
}
}
UpdateSMStabUI(e);
if ((e.UserState as messBody).body.Contains("<JTS>"))
{
string mess = (e.UserState as messBody).body.Replace("<JTS>", "");
string status = Regex.Replace(mess, "[0-9]", "");
Int32 ticket_id = Convert.ToInt32(Regex.Replace(mess, "[a-zA-z]", ""));
TicketingStatus ts = (TicketingStatus)TicketingStatusesHT[status];
if (jobTicketHT.Contains(ticket_id) || MainForm2.userType == USERTYPE.TicketingAdmin)
{
if (TicketingControl != null)
{
TicketingControl.UpdateTicketList(ticket_id, status, ts, ((Vehicle)vehicleHT[(String)VehIDHash[volsc_id]]));
}
if (documentTabStrip1.SelectedTab != tabTicketing)
{
SMSDesktopAlert.FixedSize = new System.Drawing.Size(329, 120);
if ((e.UserState as messBody).body.Contains("<JTS>"))
{
TicketingNrinTab++;
tabTicketing.Text = String.Format("{0} ({1})", returnLNGString("tabTicketing"), TicketingNrinTab.ToString());
//SMSDesktopAlert.ContentImage = resources.ticket;
String html_from = "<span>" + ((MainForm2.radioType != RADIOTYPE.MOTO) ? "<br/>" : "") + "<b><color=maroon><size=11>From: </b></span> <span><size=10>" + (e.UserState as messBody).name + "<br/><br/></span>";
html_message = "<span><b><color=maroon><size=11>Ticket id: </b></span> <span><size=10>" + ticket_id + "<span><b><color=maroon><size=11> Status:</b></span> <span><size=10>" + status + "</span>";
//"<span><color=black>" + (e.UserState as messBody).body +" </span>";
SMSDesktopAlert.ContentText = "<html>" + html_from + html_message + "</html>"; // mesajul din interior editat cu html
//returnLNGString("newtmfrom") + ": " + (e.UserState as messBody).name;
SMSDesktopAlert.CaptionText = "Job Ticket received";
//SMSDesktopAlert.ContentText = (e.UserState as String);
SMSDesktopAlert.Show();
}
}
}
}
break;
//No need to process 138 command in SafeDispatch
//It will generate mismatches, because when are made modifies in admin appServer will restart but SafeDispatch wount refresh it's hashtables
//so in SafeDispatch will be processes 153 command for alarms
//Please do not uncomment the following
//case 138:
// Console.WriteLine("Comanda cu 138");
// AlarmChange(true, rep_type.EMERG, (String)VehIDHash[volsc_id], "", false);
// break;
case 135:
try
{
volSpeed = (e.UserState as String);
volInMessMile = false;
if (volSpeed.Contains("_m")) volInMessMile = true;
volSpeed = volSpeed.Remove(volSpeed.IndexOf('_'));
if ((MainForm2.isInMile) && (!volInMessMile)) volSpeed = Convert.ToString((int)((Convert.ToInt32(volSpeed)) * 0.621371192));
else if ((!MainForm2.isInMile) && (volInMessMile)) volSpeed = Convert.ToString((int)((Convert.ToInt32(volSpeed)) * 1.609344));
if (MainForm2.isInMile) volSpeed += " " + milesh;
else volSpeed += " " + kmh;
AlarmChange(true, rep_type.SPEED, (String)VehIDHash[volsc_id], volSpeed, false);
}
catch (Exception ex)
{
SM.Debug("Error on process alarm" + ex.ToString());
}
break;
case 136:
AlarmChange(true, rep_type.GEOFENC, (String)VehIDHash[volsc_id], (e.UserState as String), false);
break;
case 137:
AlarmChange(true, rep_type.LAND, (String)VehIDHash[volsc_id], (e.UserState as String), false);
break;
case 140:
AlarmChange(true, rep_type.TELEMETRY_ALARM, (String)VehIDHash[volsc_id], (e.UserState as String), false);
break;
case 233:
SM.Debug("Proccess 233 for name :" + (String)VehIDHash[volsc_id]);
if (MapType == MapTYPE.Google)
{
if (TelemGOControl != null)
TelemGOControl.updateName((String)VehIDHash[volsc_id]);
}
else if (MapType == MapTYPE.ArcGis)
if (TelemGISControl != null) TelemGISControl.updateName((String)VehIDHash[volsc_id]);
break;
case 250:
foreach (LiveTabWind obj in LiveTabs.Values)
{
if (MapType == MapTYPE.Google)
{
for (int contor = 0; contor < obj.livetab.gridVehicles.Rows.Count; contor++)
{
if (obj.livetab.gridVehicles.Rows[contor].Cells[2].Value.ToString() == ((String)VehIDHash[volsc_id]))
{
try
{
if (((Vehicle)vehicleHT[(String)VehIDHash[volsc_id]]).RadioEnabled)
((Vehicle)vehicleHT[(String)VehIDHash[volsc_id]]).is_disabled = false;
else
((Vehicle)vehicleHT[(String)VehIDHash[volsc_id]]).is_disabled = true;
obj.livetab.gridVehicles.Refresh();
break;
}
catch (Exception ex)
{
SM.Debug("Erorr on command 250 Google " + ex.ToString());
}
}
}
}
else if (MapType == MapTYPE.ArcGis)
{
for (int contor = 0; contor < obj.livetabgis.vehiclesList.Rows.Count; contor++)
{
if (obj.livetabgis.vehiclesList.Rows[contor].Cells[2].Value.ToString() == ((String)VehIDHash[volsc_id]))
{
try
{
if (((Vehicle)vehicleHT[(String)VehIDHash[volsc_id]]).RadioEnabled)
((Vehicle)vehicleHT[(String)VehIDHash[volsc_id]]).is_disabled = false;
else
((Vehicle)vehicleHT[(String)VehIDHash[volsc_id]]).is_disabled = true;
obj.livetabgis.vehiclesList.Refresh();
break;
}
catch (Exception ex)
{
SM.Debug("Erorr on command 250 Arcgis " + ex.ToString());
}
}
}
}
}
break;
}
}
catch (Exception ex)
{
Utils.WriteLine("Error on compute mesages from bus" + ex.ToString(), ConsoleColor.Red);
}
}
private void DisplayDesktopAlertForAppServer(String title, String message, bool isError)
{
SMSDesktopAlert.FixedSize = new System.Drawing.Size(329, 120);
SMSDesktopAlert.ContentImage = isError ? resources.alert_error : resources.outboxNewGE;
html_message = "<span><size=11><color=maroon>" + message + " </span>";
SMSDesktopAlert.ContentText = "<html>" + html_message + "</html>"; // mesajul din interior editat cu html
SMSDesktopAlert.CaptionText = title;
//SMSDesktopAlert.ContentText = (e.UserState as String);
SMSDesktopAlert.Show();
}
volatile String nameveh = "";
private volatile Commands tmpCOM = null;
private volatile messBody messtmp = null;
void UpdateSMStabUI(ProgressChangedEventArgs e)
{
if (SMSControl != null)
{
try
{
volmakeUpdate = false;
if (SMSControl.inboxSelec)
{
SMSControl.updateOnlytree(volsc_id, (String)VehIDHash[volsc_id]);
if ((SMSControl.selectedSC_ID != 0) && (SMSControl.selectedSC_ID == volsc_id)) volmakeUpdate = true;
else if (SMSControl.selectedSC_ID == 0)
{
if (SMSControl.selectedSC_IDlist != null)
{
foreach (Int32 objx in SMSControl.selectedSC_IDlist)
if (objx == volsc_id) { volmakeUpdate = true; break; }
}
}
}
if (volmakeUpdate)
{
SMSControl.updateDataGrid(SMSControl.selectedSC_IDlist, true, false, false, false);
}
//(String)VehIDHash[volsc_id]
}
catch (Exception ex)
{
SM.Debug("Ex13:" + ex.ToString());
}
}
try
{
if (MainForm2.PopupOpen[((Vehicle)vehicleHT[(String)VehIDHash[volsc_id]]).IMEI] != null)
((FastCommandWindow)MainForm2.PopupOpen[((Vehicle)vehicleHT[(String)VehIDHash[volsc_id]]).IMEI]).populate();
}
catch (Exception ex)
{
SM.Debug("Error unable populate list SMS sound:" + ex.ToString());
}
// SMS sound
try
{
System.Media.SoundPlayer myPlayer = new System.Media.SoundPlayer();
myPlayer.Stream = resources.new_sms;
myPlayer.Play();
}
catch (Exception ex)
{
SM.Debug("Error unable to play SMS sound:" + ex.ToString());
}
// end SMS sound
if (documentTabStrip1.SelectedTab != tabSMS)
{
SMSDesktopAlert.FixedSize = new System.Drawing.Size(329, 120);
if (!(e.UserState as messBody).body.Contains("<JTS>"))
{
//update only tree
//fac update in data grid daca e deschis
//if (!moto2Linx)
// SMSControl?.updateOnlytree(volsc_id, (String)VehIDHash[volsc_id]);
if (!SMSuserControl.isSMSLoaded) nrOfUnreadMessages++;
tabSMS.Text = String.Format("{0} ({1})", returnLNGString("tabSMS"), nrOfUnreadMessages);
SMSDesktopAlert.ContentImage = resources.alert_message;
String html_from = "<span>" + ((MainForm2.radioType != RADIOTYPE.MOTO) ? "<br/>" : "") + "<b><color=maroon><size=11>From: </b></span> <span><size=10>" + (e.UserState as messBody).name + "<br/><br/></span>";
html_message = "<span><b><color=maroon><size=11>Message: </b></span> <span><size=10>" + (e.UserState as messBody).body + "</span>";
//"<span><color=black>" + (e.UserState as messBody).body +" </span>";
SMSDesktopAlert.ContentText = "<html>" + html_from + html_message + "</html>"; // mesajul din interior editat cu html
title = returnLNGString("yourecv");
//returnLNGString("newtmfrom") + ": " + (e.UserState as messBody).name;
SMSDesktopAlert.CaptionText = title;
//SMSDesktopAlert.ContentText = (e.UserState as String);
SMSDesktopAlert.Show();
}
}
}
long ComputMess(BackgroundWorker worker, DoWorkEventArgs e)
{
while (MainForm2.isRunning)
{
try
{
while (CmdList.Count > 0)
{
tmpCOM = (Commands)CmdList.Dequeue();
if (tmpCOM.type != 210 && tmpCOM.type != 251)
nameveh = VehIMEIHash[tmpCOM.imei].ToString();
Vehicle vehicle = (Vehicle)MainForm2.vehicleHT[nameveh];
switch (tmpCOM.type)
{
case 231:
case 131:
break;
case 230:
worker.ReportProgress(vehicle.sc_id * 1000 + 230, tmpCOM.ARSon.ToString());
break;
case 130:
if (tmpCOM.ARSon)
;
else
vehicle.SetARSOFF();
worker.ReportProgress(vehicle.sc_id * 1000 + 130);
//else worker.ReportProgress(((Vehicle)vehicleHT[nameveh]).sc_id * 1000 + 230);
break;
case 153:
worker.ReportProgress(vehicle.sc_id * 1000 + 153, tmpCOM.di.ToString());
break;
case 132:
messtmp = new messBody(tmpCOM.messages, nameveh);
worker.ReportProgress(vehicle.sc_id * 1000 + 132, messtmp);
break;
case 138:
worker.ReportProgress(vehicle.sc_id * 1000 + 138);
break;
case 251:
//in tmpCom.IMEI you have the list of id split with coma
string[] ticketExpiredList = tmpCOM.imei.Split(",".ToCharArray());
string list_of_my_tickets = "";
foreach (string ticketExpired in ticketExpiredList)
{
if (jobTicketHT.Contains(Convert.ToInt32(ticketExpired)))
list_of_my_tickets += ticketExpired + ",";
}
list_of_my_tickets = list_of_my_tickets.Substring(0, list_of_my_tickets.Length - 1);
worker.ReportProgress(251, list_of_my_tickets);
break;
case 135:
case 136:
case 137:
case 140:
worker.ReportProgress(vehicle.sc_id * 1000 + tmpCOM.type, tmpCOM.zone);
break;
case 210:
worker.ReportProgress(Convert.ToInt32(tmpCOM.imei) * 1000 + tmpCOM.type, tmpCOM.zone);
break;
case 250:
nameveh = VehIMEIHash[tmpCOM.imei].ToString();
((Vehicle)MainForm2.vehicleHT[nameveh]).RadioEnabled = tmpCOM.ARSon;
worker.ReportProgress(((Vehicle)MainForm2.vehicleHT[nameveh]).sc_id * 1000 + 250);
break;
case 233:
if (vehicle.telemList.Count != 0)
{
if (vehicle.telemPos != null)
{
if ((MainForm2.radioType == RADIOTYPE.MOTO) || (MainForm2.radioType == RADIOTYPE.REPEATER_TRBO))
{
if (tmpCOM.diNew)
vehicle.telemPos.ByteValue = tmpCOM.di;
else
vehicle.telemPos.ByteValue |= tmpCOM.di;
}
else
{
vehicle.telemPos.ByteValue = tmpCOM.di;
}
vehicle.telemPos.TimeGMT = ((DateTime.Now.GetSecondsFromDT().ConvertLocalToGMT()));
}
else
{
//Console.WriteLine("((Vehicle)MainForm2.vehicleHT[nameveh]).telemPos ========null");
try
{
//Console.WriteLine("DI este" + tmpCOM.di);
vehicle.telemPos = new TelemetryPOS(0, vehicle.IMEI, ((DateTime.Now.GetSecondsFromDT().ConvertLocalToGMT())), tmpCOM.di);
}
catch (Exception ex)
{
SM.Debug("Error convert IMEI" + ex.ToString());
}
}
}
worker.ReportProgress(vehicle.sc_id * 1000 + tmpCOM.type);
break;
}
}
}
catch (Exception ex)
{
SM.Debug("Error on radio list" + ex.ToString());
}
Thread.Sleep(2);
if (MainForm2.ClosingApp)
{
SM.Debug("ComputMess: CancellationPending in Radio: ");
e.Cancel = true;
return 1;
}
}
return 0;
}
#endregion
#region Voice Values
//private NSpeexVoiceClass nVoice;
public static ArrayList PatchList = new ArrayList();
public void First_time_start_radio()
{
SM.Debug("First time start radio for popup window");
Thread th = new Thread(new ThreadStart(delegate ()
{
try
{
/*RadioControl tmpz = new RadioControl(this, true);
tmpz.Visible = true;
tmpz.Dock = System.Windows.Forms.DockStyle.Fill;
tmpz.Location = new System.Drawing.Point(0, 0);
tabVoice.Controls.Add(tmpz);
tabsHash[tabVoice.Name] = true;
VoiceFirstTime = false;*/
}
catch (Exception ex)
{
SM.Debug("Error on first time start radio:" + ex.ToString());
}
}));
th.Start();
}
#endregion
AlarmFrom tmpAlarmFrm = null;
public void AlarmTracking_Click(object sender, EventArgs e)
{
// do not do anything if the form is not loaded
if (!isMainForm2Loaded)
return;
try
{
RefreshAlarmFrm(true);
if (smdbObj.get_Count_addr() < 100)
{
ArrayList tmpH = smdbObj.get_HistoryfillAddr();
smdbObj.INIT();
foreach (SMposition obj in tmpH)
{
try
{
if ((obj.m_address != "") && (obj.m_address != " "))
smdbObj.Insert_Address_fast(obj.m_address, Math.Round(obj.m_lat, 4), Math.Round(obj.m_lng, 4));
}
catch (Exception ex)
{
// do not show error for duplicate
if (!ex.ToString().ToLower().Contains("duplicate key value violates"))
Utils.WriteLine("Error on Insert_Address_fast: " + ex.ToString());
}
}
smdbObj.CLOSE();
}
AlarmChange(false, rep_type.IDLE, "", "", false);
}
catch (Exception ex)
{
SM.Debug("Ex14:" + ex.ToString());
}
}
public void RefreshAlarmFrm(bool openedByUser)
{
displayAlarmsForm(false, openedByUser);
}
private void displayAlarmsForm(bool specialEmergency, bool openedByUser)
{
if (tmpAlarmFrm == null)
{
//if the unit have alarm
tmpAlarmFrm = new AlarmFrom(this);
tmpAlarmFrm.openedByUser = openedByUser;
tmpAlarmFrm.OnAlarmAcknowledged += alarmForm_OnAlarmAcknowledged;
if (specialEmergency)
{
tmpAlarmFrm.Show();
int y = Screen.PrimaryScreen.WorkingArea.Height - tmpAlarmFrm.Height;
tmpAlarmFrm.Location = new System.Drawing.Point(tmpAlarmFrm.Location.X, y);
tmpAlarmFrm.TopMost = true;
}
else
{
tmpAlarmFrm.Show();
}
//Thread.Sleep(800);
//tmpAlarmFrm = null;
}
else
{
tmpAlarmFrm.openedByUser = openedByUser;
if (!tmpAlarmFrm.Visible)
tmpAlarmFrm.Show();
tmpAlarmFrm.BringToFront();
if (tmpAlarmFrm.WindowState == FormWindowState.Minimized)
tmpAlarmFrm.WindowState = FormWindowState.Normal;
}
tmpAlarmFrm.updateList();
}
private void alarmForm_OnAlarmAcknowledged(AlarmHisItem ackAlarm)
{
// throw new NotImplementedException();
Utils.WriteLine(ackAlarm.Text + " " + ackAlarm.Id);
}
public void AlarmACKUpdate(AlarmHisItem typeX, int nrOfUnAckAlerts)
{
// update the label for Alerts tab
tabAlerts.Text = String.Format("{0} ({1})", returnLNGString("tabAlerts"), nrOfUnAckAlerts);
try
{
if (typeX == null)
AlarmChange(false, rep_type.IDLE, "", "", true);
else
{
rep_type truetype = rep_type.LAND;
switch ((Int32)typeX.Type)
{
case 0: truetype = rep_type.EMERG; break;
case 1: truetype = rep_type.LAND; break;
case 2: truetype = rep_type.GEOFENC; break;
case 3: truetype = rep_type.SPEED; break;
case 4: truetype = rep_type.TELEMETRY_ALARM; break;
}
AlarmChange(true, truetype, (String)VehIDHash[typeX.Sc_id], typeX.Text, true);
}
}
catch (Exception ex)
{
SM.Debug("Ex15:" + ex.ToString());
}
}
private Boolean keyPTTpressed = false;
private void MainForm_KeyDown(object sender, KeyEventArgs e)
{
try
{
if (documentTabStrip1.SelectedTab == tabVoice)
{
if (MainForm2.VoiceTabStarted)
{
}
/*if (mainRadioForms != null)
foreach (ShapeNew obj in mainRadioForms)
if (obj.typeRadio)
((radioFrom)obj).KeyDown(e.KeyValue);
else ((dispFrom)obj).KeyDown(e.KeyValue); */
keyPTTpressed = true;
}
}
catch (Exception ex)
{
SM.Debug("Ex16:" + ex.ToString());
}
}
private void MainForm_KeyUp(object sender, KeyEventArgs e)
{
try
{
if ((documentTabStrip1.SelectedTab == tabVoice) || (keyPTTpressed))
{
//SM.Debug("Key Up:" + e.KeyValue);
if (MainForm2.VoiceTabStarted)
{
}
/*if (mainRadioForms != null)
foreach (ShapeNew obj in mainRadioForms)
if (obj.typeRadio)
((radioFrom)obj).KeyUP(e.KeyValue);
else ((dispFrom)obj).KeyUP(e.KeyValue); */
keyPTTpressed = false;
}
}
catch (Exception ex)
{
SM.Debug("Ex17:" + ex.ToString());
}
}
private void AlarmChange(Boolean ON, rep_type type, String Name, String Detail, Boolean withoutsound)
{
try
{
//Console.WriteLine("PAS0");
if (ON)
{
System.Media.SoundPlayer myPlayer = new System.Media.SoundPlayer();
//UpdateNumberOfUnAckAlerts();
//Console.WriteLine("PAS1");
Boolean alarmOK = false;
Boolean SpecialEmerg = false;
Boolean isAlarmSilence = !(DateTime.Now.CompareTo(alertSilenceEndTime) > 0);
//====================================================
Vehicle vehicle = vehicleHT[Name] as Vehicle;
//====================================================
if (type != rep_type.IDLE && Name != null && vehicle != null)
{
switch (type)
{
case rep_type.EMERG://emergon
//Console.WriteLine("PAS2");
//AlarmName.Text = returnLNGString("emergon") + " " + Name + Detail;
if (vehicle.AlarmSound.EMpopup)
{
alarmOK = true;
if (selectedTabType == track_type.LIVE)
SpecialEmerg = true;
}
UpdateStatusLive(Name);
vehicle.is_emergency = true;
//Console.WriteLine("PAS3");
AlarmCountNotAck++;
if (!withoutsound)
{
//if the unit has sound
if (vehicle.AlarmSound.EMsound && !isAlarmSilence)
{
myPlayer.Stream = resources.panic;
myPlayer.Play();
}
}
if (MapType == MapTYPE.ArcGis && ON)
{
foreach (LiveTabWind obj in LiveTabs.Values)
obj.livetabgis.onEmergencyStateChangedHandler(vehicle, true);
}
//put unit in center of the screen
foreach (String nameMap in vehicle.MapsHT.Keys)
{
//===============================================================================
MapElement mapElement = ((MapElement)((Vehicle)vehicleHT[Name]).MapsHT[nameMap]);
//===============================================================================
//need to force udpdate
//Console.WriteLine("PAS4");
if (!mapElement.isActive)
{
//Console.WriteLine("PAS5");
if (Math.Round(vehicle.LAT) != 0 && Math.Round(vehicle.LNG) != 0)
{
mapElement.SetLastLocation();
mapElement.SetLastPushpin();
mapElement.ActivatePushPin();
if (MapType == MapTYPE.Google)
{
try {
if (SendDataToMapHASH[Name] == null)
SendDataToMapHASH.Add(Name, 0); }
catch(Exception ex)
{ Utils.WriteLine(ex.ToString(), ConsoleColor.Red); }
SendDataToMapQUE.PostItem(Name);
}
}
//force check unit on the list
foreach (LiveTabWind obj in LiveTabs.Values)
{
if (MapType == MapTYPE.ArcGis)
{
//obj.livetabgis.
obj.livetabgis.ForceUnitState(Name, true);
obj.livetabgis.displayButton.PerformClick();
}
else if (MapType == MapTYPE.Google)
{
/*
obj.livetab.CenterAndOpenBubble(Name);
obj.livetab.ForceUnitState(Name, true);
obj.livetab.rbDisplay.PerformClick();
*/
}
}
}
if (MapType == MapTYPE.ArcGis)
mapElement.AxMapGIS.Extent = MainForm2.ZoomTo(vehicle.LNG, vehicle.LAT,vehicle.LNG, vehicle.LAT);
else
{
foreach (LiveTabWind obj in LiveTabs.Values)
{
if ((Math.Round(vehicle.LNG) != 0 && Math.Round(vehicle.LAT) != 0))
{
//((MapElement)((Vehicle)vehicleHT[Name]).MapsHT[nameMap]).UpdateSymbol();
RemoveIconsFromMap();
obj.livetab.mapControl.mapGoogles.ExecuteScript("window.GWTcallback('centerzoom,"
+ MainForm2.FixDoubleLAT(vehicle.LAT.ToString()) + ","
+ MainForm2.FixDoubleLNG(vehicle.LNG.ToString()) + ",15');");
}
else if (Math.Round(vehicle.lastLocLNG) != 0 && Math.Round(vehicle.lastLocLAT) != 0)
{
//((MapElement)((Vehicle)vehicleHT[Name]).MapsHT[nameMap]).UpdateSymbol();
RemoveIconsFromMap();
obj.livetab.mapControl.mapGoogles.ExecuteScript("window.GWTcallback('centerzoom,"
+ MainForm2.FixDoubleLAT(vehicle.lastLocLAT.ToString())
+ "," + MainForm2.FixDoubleLNG(vehicle.lastLocLNG.ToString()) + ",15');");
}
}
}
Thread.Sleep(1);
// trigger event for unit that changed it's status
foreach (LiveTabWind obj in LiveTabs.Values)
{
Vehicle veh = (Vehicle)MainForm2.vehicleHT[Name];
if (MapType == MapTYPE.Google)
{
obj.livetab.onEmergencyStateChangedHandler(veh, true);
}
//if(MapType == MapTYPE.ArcGis)
// obj.livetabgis.onEmergencyStateChangedHandler(veh, true);
}
}
//end moving the unit
break;
case rep_type.SPEED:
//AlarmName.Text = Name + " " + Detail;
if (((Vehicle)vehicleHT[Name]).AlarmSound.SPEEDpopup) alarmOK = true;
AlarmCountNotAck++;
if (!withoutsound)
{
//if the unit has sound
if (((Vehicle)vehicleHT[Name]).AlarmSound.SPEEDsound && !isAlarmSilence)
{
myPlayer.Stream = resources.speeding;
myPlayer.Play();
}
}
break;
case rep_type.GEOFENC:
//AlarmName.Text = Name + " " + Detail;
if (vehicle.AlarmSound.GEOpopup) alarmOK = true;
AlarmCountNotAck++;
if (!withoutsound)
{
if (vehicle.AlarmSound.GEOsound && !isAlarmSilence)
{
myPlayer.Stream = resources.zone;
myPlayer.Play();
}
}
break;
case rep_type.LAND:
//AlarmName.Text = Name + " " + Detail;
if (vehicle.AlarmSound.GEOpopup) alarmOK = true;
AlarmCountNotAck++;
if (!withoutsound)
{
if (vehicle.AlarmSound.GEOsound && !isAlarmSilence)
{
myPlayer.Stream = resources.zone;
myPlayer.Play();
}
}
break;
case rep_type.TELEMETRY_ALARM:
//AlarmName.Text = Name + " " + Detail;
if (vehicle.AlarmSound.TELEMpopup) alarmOK = true;
AlarmCountNotAck++;
if (!withoutsound)
{
if (vehicle.AlarmSound.TELEMsound && !isAlarmSilence)
{
myPlayer.Stream = resources.telem;
myPlayer.Play();
}
}
break;
}
try
{
if (MainForm2.PopupOpen[vehicle.IMEI] != null)
((FastCommandWindow)MainForm2.PopupOpen[vehicle.IMEI]).populate();
}
catch (Exception ex)
{
SM.Debug("Error unable populate list SMS sound:" + ex.ToString());
}
}
if (!withoutsound)
{
if (alarmOK)
{
if (!isAlarmSilence)
{
displayAlarmsForm(SpecialEmerg, false);
}
}
}
}
/*
else
{
AlarmIcon.Image = resources.emergencyoff16x;
AlarmName.Text = returnLNGString("noalarm");
}
if (AlarmCountNotAck > 0)
{
if ((AlarmName.Text.Length > 0) && (AlarmName.Text[AlarmName.Text.Length - 1] != ')'))
AlarmName.Text = AlarmName.Text + " (" + AlarmCountNotAck + " " + returnLNGString("notack") + ")";
}
else
{
AlarmIcon.Image = resources.emergencyoff16x;
AlarmName.Text = returnLNGString("noalarm");
}
* */
}
catch (Exception ex)
{
SM.Debug("Ex18:" + ex.ToString());
}
}
private String lastcmd = "";
private volatile Int32 volcont = 0;
private volatile String[] volSplit = null;
private volatile String vollimei = "";
private volatile String volltype = "";
private volatile String vollopcode = "";
private volatile String vollHumanMsg = "";
private volatile Int32 transmitWay = 1;
public static volatile String PriorityIP = "";
private void ReorderAlphabetized(RadCheckedDropDownList ddl)
{
ddl.BeginUpdate();
List<RadListDataItem> listCopy = ddl.Items.OrderBy(item => item.Text).ToList();
ddl.DataSource = null;
ddl.DataSource = listCopy;
ddl.EndUpdate();
}
private BindingList<DataforSystemList> listSystemUnitEvent = new BindingList<DataforSystemList>();
private BindingList<DataforSystemList> listSysEventMsg = new BindingList<DataforSystemList>();
private void FailoverStatus(ToggleState toggleState)
{
FailoverStatusM(toggleState);
FailoverStatusS(toggleState);
}
private void FailoverStatusM(ToggleState toggleState)
{
chkFailoverServiceAliveM.ToggleState = toggleState;
chkFailoverServiceAliveM.ForeColor = Color.Gray;
chkDatabaseServiceAliveM.ToggleState = toggleState;
chkDatabaseServiceAliveM.ForeColor = Color.Gray;
chkReplicationSlotActiveM.ToggleState = toggleState;
chkReplicationSlotActiveM.ForeColor = Color.Gray;
chkProperConfiguredM.ToggleState = toggleState;
chkProperConfiguredM.ForeColor = Color.Gray;
chkSDRServiceAliveM.ToggleState = toggleState;
chkSDRServiceAliveM.ForeColor = Color.Gray;
chkSDRActiveM.ToggleState = toggleState;
chkSDRActiveM.ForeColor = Color.Gray;
}
private void FailoverStatusS(ToggleState toggleState)
{
chkFailoverServiceAliveS.ToggleState = toggleState;
chkFailoverServiceAliveS.ForeColor = Color.Gray;
chkDatabaseServiceAliveS.ToggleState = toggleState;
chkDatabaseServiceAliveS.ForeColor = Color.Gray;
chkReplicationSlotActiveS.ToggleState = toggleState;
chkReplicationSlotActiveS.ForeColor = Color.Gray;
chkProperConfiguredS.ToggleState = toggleState;
chkProperConfiguredS.ForeColor = Color.Gray;
chkSDRServiceAliveS.ToggleState = toggleState;
chkSDRServiceAliveS.ForeColor = Color.Gray;
chkSDRActiveS.ToggleState = toggleState;
chkSDRActiveS.ForeColor = Color.Gray;
}
public void AddDataToSystemGrid(Boolean transmit, String cmd, ContactType callSourceType = ContactType.UNIT)
{
try
{
volSplit = cmd.Split("#".ToCharArray());
bool isVehicle;
Status_for_tab status = Status_for_tab.UNKNOW;
if (volSplit[3].Equals("131") || volSplit[3].Equals("231"))
{
isVehicle = true;
string imei = volSplit[4];
status = ((Vehicle)(MainForm2.vehicleHT[MainForm2.VehIMEIHash[imei].ToString()])).actual_status;
}
else
isVehicle = false;
if ((lastcmd != cmd) && (!isVehicle || ((emergOnlyCheck && (status == Status_for_tab.EMERG))|| !emergOnlyCheck)))
{
//SystemGridView.Columns[4].SortOrder = RadSortOrder.None;
//SystemGridView.Rows.AddNew();
//SystemGridView.TableElement.BeginUpdate();
//volcont = SystemGridView.Rows.Count - 1;
transmitWay = 1;
if (transmit) transmitWay = 0;
//volSplit = cmd.Split("#".ToCharArray());
try
{
vollopcode = volSplit[3];
switch (volSplit[3])
{
case "10":
{
volltype = "BUSSY";
vollHumanMsg = "Busy";
break;
}
case "100":
{
volltype = "ON/OFF";
vollHumanMsg = "";
break;
}
case "101":
volltype = "INIT ALL CALL";
break;
case "121":
volltype = "ACK INIT ALL CALL";
break;
case "111":
volltype = "END ALL CALL";
break;
case "115":
volltype = "ACK END ALL CALL";
break;
case "103":
volltype = "INIT GROUP CALL";
break;
case "123":
volltype = "ACK INIT GROUP CALL";
break;
case "113":
volltype = "END GROUP CALL";
break;
case "117":
volltype = "ACK END GROUP CALL";
break;
case "102":
volltype = "INIT PRIV CALL";
break;
case "122":
volltype = "ACK INIT PRIV CALL";
break;
case "112":
volltype = "END PRIV CALL";
break;
case "116":
volltype = "ACK END PRIV CALL";
break;
case "94":
volltype = "First Ch. REQ.";
break;
case "104":
volltype = "Chanel REQ.";
break;
case "124":
volltype = "Chanel RECEIVED";
break;
case "125":
volltype = "Call Start";
break;
case "130":
volltype = "ARS";
break;
case "230":
volltype = "POLL ARS";
break;
case "131":
volltype = "LOCATION";
break;
case "132":
if (cmd.Contains("<JTS>"))
volltype = "TICKET RECEIVED";
else
volltype = "SMS RECEIVED";
break;
case "232":
volltype = "SMS ACK";
break;
case "142":
if (cmd.Contains("<JTS>"))
volltype = "TICKET SEND";
else
volltype = "SMS SEND";
break;
case "242":
volltype = "SMS ACK";
break;
case "144":
volltype = "SMS GROUP SEND";
break;
case "244":
volltype = "SMS GROUP ACK";
break;
case "133":
volltype = "Telemetry SEND";
break;
case "233":
volltype = "Telemetry RECEIVED";
break;
case "231":
volltype = "POLL LOCATION";
break;
case "207":
volltype = "CH. BUSY/FREE";
break;
case "202":
volltype = "USER ON";
break;
case "212":
volltype = "USER OFF";
break;
case "201":
volltype = "USER CALL";
break;
case "221":
volltype = "ACK USER CALL";
break;
case "211":
volltype = "END USER CALL";
break;
case "134":
//case "153":
volltype = "EMERGENCY";
break;
case "238":
volltype = "EMERGENCY ACK";
break;
case "150":
volltype = "Enable/Disable CMD";
break;
case "151":
volltype = "Enable/Disable STAT";
break;
case "250":
volltype = "Enable/Disable Broadcast";
break;
case "160":
volltype = "Radio DeKEY";
break;
case "161":
volltype = "Remote Monitor";
break;
case "162":
volltype = "Remote Monitor Response";
break;
case "172":
volltype = "End Remote Monitor";
break;
case "135":
volltype = "Speed Alarm";
break;
case "136":
volltype = "Zone Alarm";
break;
case "137":
volltype = "LandMark Alarm";
break;
/*
case "139":
volltype = "Subs. Location";
break;*/
case "140":
volltype = "DI alarm";
break;
case "149":
volltype = "Radio online check";
break;
case "154":
volltype = "POLL request";
break;
case "152":
volltype = "Email report";
break;
//case "153":
// volltype = "STATUS";
// break;
case "155":
case "209":
return;
case "507":
return;
case "610":
volltype = "Failover status";
SaveFailoverIPAndUpdateState(cmd);
break;
default:
return;
}
vollimei = volSplit[4];
}
catch (Exception ex)
{
SM.Debug("Error convert code for line" + ex.ToString());
}
// create object for grid
DataforSystemList item = new DataforSystemList(transmitWay, volltype, vollopcode, vollimei, DateTime.Now, cmd, callSourceType);
// add command only if not inserted allready, this means that a sent command will
// not be added when it will be received back on the message bus
if (startList.Count > 0 && !startList[startList.Count - 1].Cmd.Equals(cmd))
startList.Add(item);
else if (startList.Count == 0)
startList.Add(item);
//// add the new unit into the list
if (!rcbDropDropDownUnitEvent.Items.Contains(item.Imei) && item.SysEvent != DataforSystemList.SystemEvent.UNKNOWN)
{
rcbDropDropDownUnitEvent.Items.Add(item.Imei);
//ReorderAlphabetized(rcbDropDropDownUnitEvent);
}
//// add event type to the comboBox
if (!rcbDropDownEventType.Items.Contains(item.SysEventMsg) && item.SysEvent != DataforSystemList.SystemEvent.UNKNOWN)
{
rcbDropDownEventType.Items.Add(item.SysEventMsg);
//ReorderAlphabetized(rcbDropDownEventType);
}
/*
//// add the new unit into the list
if (listSystemUnitEvent.Select(d => d.Imei.Equals(item.Imei)) == null && item.SysEvent != DataforSystemList.SystemEvent.UNKNOWN)
{
rcbDropDropDownUnitEvent.BeginUpdate();
listSystemUnitEvent.Add(item);
//var res = new BindingList<DataforSystemList>(listSystemUnitEvent.OrderBy(d => d.Imei).ToList());
rcbDropDropDownUnitEvent.EndUpdate();
//if(systemTabVisible)
//ReorderAlphabetized(rcbDropDropDownUnitEvent);
}
//// add event type to the comboBox
if (listSysEventMsg.Select(d => d.SysEventMsg.Equals(item.SysEventMsg)) == null && item.SysEvent != DataforSystemList.SystemEvent.UNKNOWN)
{
rcbDropDownEventType.BeginUpdate();
listSysEventMsg.Add(item);
//listSysEventMsg = new BindingList<DataforSystemList>(listSystemUnitEvent.OrderBy(d => d.SysEventMsg).ToList());
rcbDropDownEventType.EndUpdate();
//if(systemTabVisible)
//ReorderAlphabetized(rcbDropDownEventType);
}*/
// clear list if more than 10000 elements
if (startList.Count > 10000)
{
startList.Clear();
}
// hide panel for no events
if (startList.Count > 0)
panelNoEvents.Visible = false;
}
//SystemGridView.Refresh();
}
catch (Exception ex)
{
SM.Debug("Unable to put data in the SystemGridView:" + ex.ToString());
}
}
private void SaveFailoverIPAndUpdateState(string cmd)
{
string[] cmdParts = cmd.Split("#".ToCharArray());
if (cmdParts.Length < 6)
return;
string ip = cmdParts[4];
string key = cmdParts[5];
string master = cmdParts[6];
string strMaster = master.Equals("M") ? "master" : "slave";
if (string.IsNullOrEmpty(lblIPS.Text) &&
string.IsNullOrEmpty(lblIPM.Text)
)
{
if (master.Equals("M"))
{
lblIPM.Text = ip;
lblStateM.Text = strMaster;
}
else if (master.Equals("S"))
{
lblIPS.Text = ip;
lblStateS.Text = strMaster;
}
}
else if (!lblIPM.Text.Equals(ip) &&
string.IsNullOrEmpty(lblIPS.Text)
)
{
lblIPS.Text = ip;
lblStateS.Text = strMaster;
}
else if (!lblIPS.Text.Equals(ip) &&
string.IsNullOrEmpty(lblIPM.Text))
{
lblIPM.Text = ip;
lblStateM.Text = strMaster;
}
else if (lblIPS.Text.Equals(ip))
{
lblIPS.Text = ip;
if (!lblStateS.Text.Equals(strMaster))
{
FailoverStatusS(ToggleState.Indeterminate);
lblStateS.Text = strMaster;
}
}
else if (lblIPM.Text.Equals(ip))
{
lblIPM.Text = ip;
if (!lblStateM.Text.Equals(strMaster))
{
FailoverStatusM(ToggleState.Indeterminate);
lblStateM.Text = strMaster;
}
}
UpdateFailoverState(ip, master, key);
}
private void CheckboxSetToggleState(RadCheckBox checkBox, ToggleState toggleState)
{
checkBox.ToggleState = toggleState;
checkBox.ForeColor = (toggleState == ToggleState.On) ? Color.Green : Color.Red;
if (checkBox.Name.EndsWith("M") && toggleState == ToggleState.On)
{ chkFailoverServiceAliveM.ToggleState = toggleState;
chkFailoverServiceAliveM.ForeColor = Color.Green;
}
else if (checkBox.Name.EndsWith("S") && toggleState == ToggleState.On)
{
chkFailoverServiceAliveS.ToggleState = toggleState;
chkFailoverServiceAliveS.ForeColor = Color.Green;
}
}
private void UpdateFailoverState(string ip, string master, string key)
{
if (master.Equals("M"))
{
if (lblIPM.Text.Equals(ip))
{
//===================
// Start/Stop service
//===================
if (key.Equals("Failover_SuccessfullyStartedService"))
CheckboxSetToggleState(chkFailoverServiceAliveM, ToggleState.On);
else if (key.Equals("Failover_StopService"))
{
//CheckboxSetToggleState(chkFailoverServiceAliveM, ToggleState.Off);
FailoverStatusM(ToggleState.Indeterminate);
lblIPM.Text = string.Empty;
lblStateM.Text = string.Empty;
}
//===================
// Database alive
//===================
if (key.Equals("Failover_DatabaseIsNotAlive"))
CheckboxSetToggleState(chkDatabaseServiceAliveM, ToggleState.Off);
else if (key.Equals("Failover_SuccessfullyDatabaseTest"))
CheckboxSetToggleState(chkDatabaseServiceAliveM, ToggleState.On);
//=======================
// Active Replication
//=======================
if (key.Equals("Failover_ReplicationNotActiveAnymore"))
CheckboxSetToggleState(chkReplicationSlotActiveM, ToggleState.Off);
else if (key.Equals("Failover_SuccessfullyActiveReplicationTest"))
CheckboxSetToggleState(chkReplicationSlotActiveM, ToggleState.On);
//===========
// Active SDR
//===========
if (key.Equals("Failover_SuccessfullySDRPingTest"))
CheckboxSetToggleState(chkSDRActiveM, ToggleState.On);
else if (key.Equals("Failover_SDRNotWorking"))
CheckboxSetToggleState(chkSDRActiveM, ToggleState.Off);
//==============
// SDR service
//===============
if (key.Equals("Failover_SuccessfullySDRServiceTest"))
CheckboxSetToggleState(chkSDRServiceAliveM, ToggleState.On);
else if (key.Equals("Failover_SDRServiceIsNotWorking"))
CheckboxSetToggleState(chkSDRServiceAliveM, ToggleState.Off);
//===================
// Proper Configured
//===================
if (key.Equals("Failover_SuccessfullyMasterConfigTest"))
CheckboxSetToggleState(chkProperConfiguredM, ToggleState.On);
else if (key.Equals("Failover_ReconfigureMasterComputer"))
CheckboxSetToggleState(chkProperConfiguredM, ToggleState.Off);
}
else if (lblIPS.Text.Equals(ip))
{
//===================
// Start/Stop service
//===================
if (key.Equals("Failover_SuccessfullyStartedService"))
CheckboxSetToggleState(chkFailoverServiceAliveS, ToggleState.On);
else if (key.Equals("Failover_StopService"))
{
//CheckboxSetToggleState(chkFailoverServiceAliveS, ToggleState.Off);
FailoverStatusS(ToggleState.Indeterminate);
lblIPS.Text = string.Empty;
lblStateS.Text = string.Empty;
}
//===================
// Database alive
//===================
if (key.Equals("Failover_DatabaseIsNotAlive"))
CheckboxSetToggleState(chkDatabaseServiceAliveS, ToggleState.Off);
else if (key.Equals("Failover_SuccessfullyDatabaseTest"))
CheckboxSetToggleState(chkDatabaseServiceAliveS, ToggleState.On);
//=======================
// Active Replication
//=======================
if (key.Equals("Failover_ReplicationNotActiveAnymore"))
CheckboxSetToggleState(chkReplicationSlotActiveS, ToggleState.Off);
else if (key.Equals("Failover_SuccessfullyActiveReplicationTest"))
CheckboxSetToggleState(chkReplicationSlotActiveS, ToggleState.On);
//===========
// Active SDR
//===========
if (key.Equals("Failover_SDRNotWorking"))
CheckboxSetToggleState(chkSDRActiveS, ToggleState.Off);
else if (key.Equals("Failover_SuccessfullySDRPingTest"))
CheckboxSetToggleState(chkSDRActiveS, ToggleState.On);
//===================
// Proper Configured
//===================
if (key.Equals("Failover_SuccessfullyMasterConfigTest"))
CheckboxSetToggleState(chkProperConfiguredS, ToggleState.On);
else if (key.Equals("Failover_ReconfigureMasterComputer"))
CheckboxSetToggleState(chkProperConfiguredS, ToggleState.Off);
}
}
else if (master.Equals("S"))
{
if (lblIPS.Text.Equals(ip))
{
//===================
// Start/Stop service
//===================
if (key.Equals("Failover_SuccessfullyStartedService"))
CheckboxSetToggleState(chkFailoverServiceAliveS, ToggleState.On);
else if (key.Equals("Failover_StopService"))
{
//CheckboxSetToggleState(chkFailoverServiceAliveS, ToggleState.Off);
FailoverStatusS(ToggleState.Indeterminate);
lblIPS.Text = string.Empty;
lblStateS.Text = string.Empty;
}
//===================
// Database alive
//===================
if (key.Equals("Failover_DatabaseIsNotAliveOnSlave"))
CheckboxSetToggleState(chkDatabaseServiceAliveS, ToggleState.Off);
else if (key.Equals("Failover_SuccessfullyDatabaseTest"))
CheckboxSetToggleState(chkDatabaseServiceAliveS, ToggleState.On);
//===================
// Proper Configured
//===================
if (key.Equals("Failover_SuccessfullySlaveConfigTest"))
CheckboxSetToggleState(chkProperConfiguredS, ToggleState.On);
else if (key.Equals("Failover_DatabaseIsNotProperForSlave"))
CheckboxSetToggleState(chkProperConfiguredS, ToggleState.Off);
//===================
// SDR Active
//===================
if (key.Equals("Failover_SDRIsNotWorkingOnSlave"))
CheckboxSetToggleState(chkSDRActiveS, ToggleState.Off);
else if (key.Equals("Failover_SuccessfullySDRPingTest"))
CheckboxSetToggleState(chkSDRActiveS, ToggleState.On);
}
else if (lblIPM.Text.Equals(ip))
{
//===================
// Start/Stop service
//===================
if (key.Equals("Failover_SuccessfullyStartedService"))
CheckboxSetToggleState(chkFailoverServiceAliveM, ToggleState.On);
else if (key.Equals("Failover_StopService"))
{
//CheckboxSetToggleState(chkFailoverServiceAliveM, ToggleState.Off);
FailoverStatusM(ToggleState.Indeterminate);
lblIPM.Text = string.Empty;
lblStateM.Text = string.Empty;
}
//===================
// Database alive
//===================
if (key.Equals("Failover_DatabaseIsNotAliveOnSlave"))
CheckboxSetToggleState(chkDatabaseServiceAliveM, ToggleState.Off);
else if (key.Equals("Failover_SuccessfullyDatabaseTest"))
CheckboxSetToggleState(chkDatabaseServiceAliveM, ToggleState.On);
//===================
// Proper Configured
//===================
if (key.Equals("Failover_SuccessfullySlaveConfigTest"))
CheckboxSetToggleState(chkProperConfiguredM, ToggleState.On);
else if (key.Equals("Failover_DatabaseIsNotProperForSlave"))
CheckboxSetToggleState(chkProperConfiguredM, ToggleState.Off);
//===================
// SDR Active
//===================
if (key.Equals("Failover_SDRIsNotWorkingOnSlave"))
CheckboxSetToggleState(chkSDRActiveM, ToggleState.Off);
else if (key.Equals("Failover_SuccessfullySDRPingTest"))
CheckboxSetToggleState(chkSDRActiveM, ToggleState.On);
//==============
// SDR service
//===============
if (key.Equals("Failover_SuccessfullySDRServiceTest"))
CheckboxSetToggleState(chkSDRServiceAliveM, ToggleState.On);
else if (key.Equals("Failover_SDRServiceIsNotWorking"))
CheckboxSetToggleState(chkSDRServiceAliveM, ToggleState.Off);
}
}
}
/// <summary>
/// Format the cells while they are created
/// </summary>
private bool showCellBorders = false;
private void SystemGridView_CellFormatting(object sender, Telerik.WinControls.UI.CellFormattingEventArgs e)
{
GridCellElement cellElement = e.CellElement;
GridViewDataColumn columnInfo = e.CellElement.ColumnInfo as GridViewDataColumn;
if (e.Row is GridViewDataRowInfo)
{
if (showCellBorders)
{
e.CellElement.ResetValue(GridDataCellElement.DrawBorderProperty, Telerik.WinControls.ValueResetFlags.Local);
}
else
{
e.CellElement.DrawBorder = false;
}
}
// do not highlight the cell on which was clicked
if (e.CellElement.IsCurrent)
{
e.CellElement.IsCurrent = false;
}
// change the way on which the DateTime is displayed
if (cellElement is GridDataCellElement && columnInfo.Name == "timecmd")
{
Font font = new Font(
cellElement.Font.FontFamily,
10,
FontStyle.Bold,
GraphicsUnit.Pixel);
cellElement.ForeColor = Color.DarkGray;
cellElement.Font = font;
}
else if (cellElement is GridDataCellElement && columnInfo.Name == "Color")
{
GridColorCellElement colorCellElement = e.CellElement as GridColorCellElement;
colorCellElement.Text = string.Empty;
int colorBoxWidth = 20;
int leftMargin = (this.SystemGridView.Columns["Color"].Width - colorBoxWidth) / 2;
colorCellElement.ColorBox.Margin = new Padding(leftMargin, 2, 2, 2);
}
else if (cellElement is GridDataCellElement && columnInfo.Name == "direct")
{
// do not show text
cellElement.DrawText = false;
if (cellElement != null && cellElement.Value != null && (int)cellElement.Value == 0)
cellElement.BackgroundImage = resources.call_made_24x20;
else
cellElement.BackgroundImage = resources.call_received_24X20;
}
}
void RadDockEvents_TabStripItemCreating(object sender, TabStripItemCreatingEventArgs args)
{
// style only desired tabs
if (args.Window == tabLive || args.Window == tabHistory
|| args.Window == tabGeo || args.Window == tabSMS
|| args.Window == tabTicketing
|| args.Window == tabVoice
|| args.Window == tabNewRadio
|| args.Window == tabReport || args.Window == tabTelem
|| args.Window == tabSystem || args.Window == tabAlerts
|| radDock1.DockWindows.ToolWindows.Contains(args.Window)
|| (args.Window.Tag != null && args.Window.Tag is Tabs)
)
{
// UI settings
args.TabItem.ImageAlignment = ContentAlignment.MiddleCenter;
args.TabItem.MaxSize = new Size(65, 50);
args.TabItem.MinSize = new Size(65, 50);
args.TabItem.DrawText = true;
args.TabItem.TextOrientation = Orientation.Vertical;
args.TabItem.TextImageRelation = TextImageRelation.TextBeforeImage;
args.TabItem.TextAlignment = ContentAlignment.MiddleCenter;
args.TabItem.TextWrap = true;
args.TabItem.ForeColor = Color.White;
args.TabItem.Font = new Font(
new FontFamily("Segoe UI"),
9,
FontStyle.Regular,
GraphicsUnit.Pixel);
args.TabItem.Padding = new Padding(0);
args.TabItem.ImageAlignment = ContentAlignment.MiddleCenter;
args.TabItem.ImageLayout = ImageLayout.Center;
args.TabItem.ForeColor = Color.White;
args.TabItem.DrawFill = true;
args.TabItem.NumberOfColors = 1;
args.TabItem.BackColor = TabNormalColor;
args.TabItem.BorderBottomWidth = 3;
args.TabItem.BorderColor = Color.FromArgb(66, 66, 66);
args.TabItem.BorderGradientStyle = GradientStyles.Solid;
args.TabItem.DrawBorder = true;
// change color for rollover
args.TabItem.MouseEnter += delegate (object sender2, EventArgs e2)
{
args.TabItem.BackColor = TabOverColor;
};
// change color for rollout
args.TabItem.MouseLeave += delegate (object sender2, EventArgs e2)
{
// decide if tab is active or not
args.TabItem.BackColor = (radDock1 != null && radDock1.ActiveWindow == args.Window) ? TabSelectedColor : TabNormalColor;
};
}
else
{
args.TabItem.ForeColor = Color.Black;
args.TabItem.DrawFill = true;
args.TabItem.NumberOfColors = 1;
// set background color based on its state
if (args.TabItem.IsSelected)
args.TabItem.BackColor = Color.White;
else
args.TabItem.BackColor = Color.White;
}
}
private CultureInfo getCultureInfo(int idx)
{
Dictionary<int, string> culture_dictionary = new Dictionary < int, string> { { 0, "en" }, { 1, "zh-CN" }, { 2, "cs" }, {3, "fr" }, { 4, "de" },
{ 5, "it"}, { 6, "ja"},{ 7, "pl"},{ 8, "pt"},{ 9, "ro"},{ 10, "ru"},{ 11, "sr"},{12, "es"},{ 13, "sv"},{ 14, "tr"},{ 15, "ar"}};
if (culture_dictionary.ContainsKey(idx))
return CultureInfo.CreateSpecificCulture(culture_dictionary[idx]);
return culture = CultureInfo.CreateSpecificCulture("en");
}
private void PopulateImageDictionary()
{
imagesDictionary.Add("fc_sms", Utils.ScaleImage(resources.fc_sms, 24, 24));
imagesDictionary.Add("fc_remote", Utils.ScaleImage(resources.fc_remote, 24, 24));
imagesDictionary.Add("fc_favorite_yellow", Utils.ScaleImage(resources.fc_favorite_yellow, 24, 24));
imagesDictionary.Add("fc_favorite", Utils.ScaleImage(resources.fc_favorite, 24, 24));
imagesDictionary.Add("fc_live", Utils.ScaleImage(resources.fc_live, 24, 24));
imagesDictionary.Add("i_classic_bus_02", Utils.ScaleImage(resources.i_classic_bus_02, 64, 64));
imagesDictionary.Add("i_classic_moto_05", Utils.ScaleImage(resources.i_classic_moto_05, 64, 64));
imagesDictionary.Add("i_dispatch", Utils.ScaleImage(resources.i_dispatch, 64, 64));
imagesDictionary.Add("i_group", Utils.ScaleImage(resources.i_group, 64, 64));
imagesDictionary.Add("i_all_call", Utils.ScaleImage(resources.i_all_call, 64, 64));
imagesDictionary.Add("i_manual_dial", Utils.ScaleImage(resources.i_manual_dial, 64, 64));
imagesDictionary.Add("l_alert", resources.l_alert);
imagesDictionary.Add("l_text", resources.l_text);
imagesDictionary.Add("l_center", resources.l_center);
}
private void SetTabsForEachWindow()
{
tabAlerts.Tag = Tabs.ALERTS;
tabLive.Tag = Tabs.LIVE;
tabGeo.Tag = Tabs.GEOFENCE;
tabHistory.Tag = Tabs.HISTORY;
tabSMS.Tag = Tabs.TEXT;
tabTicketing.Tag = Tabs.TICKETING;
tabVoice.Tag = Tabs.VOICE;
tabNewRadio.Tag = Tabs.RADIO;
tabTelem.Tag = Tabs.TELEMETRY;
tabReport.Tag = Tabs.REPORTS;
tabSystem.Tag = Tabs.SYSTEM;
}
private void DestroyMapPoint()
{
Process[] processes = Process.GetProcessesByName("MapPoint");
foreach (Process proc in processes)
{
proc.CloseMainWindow();
proc.Kill();
proc.WaitForExit();
}
}
private void ChangeIconAndText(Login parent)
{
try
{
switch (MainForm2.radioType)
{
case RADIOTYPE.UNKNOWN:
this.Text = parent.Text;
break;
case RADIOTYPE.HYT:
this.Icon = resources.HytSmall24;
this.Text = parent.Text;
break;
case RADIOTYPE.HARRIS:
this.Icon = resources.HarrisSmall;
this.Text = parent.Text;
break;
case RADIOTYPE.ATLAS:
this.Icon = resources.ATLICO32;
this.Text = parent.Text;
break;
case RADIOTYPE.SIMOCO:
this.Icon = resources.simoco_dispatch_24;
this.Text = parent.Text;
break;
case RADIOTYPE.EXCERA:
this.Icon = resources.AXYS_ICON;
this.Text = parent.Text;
break;
default:
break;
}
}
catch (Exception ex)
{
SM.Debug("Error on change icon and text on MainForm:\n" + ex.ToString());
}
}
private void InitializeSystemGridView()
{
string dateTimeFormat = "";
try
{
SystemGridView.DataSource = null;
SystemGridView.DataSource = startList;
SystemGridView.Columns["timecmd"].IsVisible = true;
SystemGridView.Columns["timeAgo"].IsVisible = false;
if (MainForm2.is24hours)
dateTimeFormat = MainForm2.DayFirst ? "{0:dd/MM/yyyy HH:mm:ss}" : "{0:MM/dd/yyyy HH:mm:ss}";
else
dateTimeFormat = MainForm2.DayFirst ? "{0:dd/MM/yyyy HH:mm:ss tt}" : "{0:MM/dd/yyyy HH:mm:ss tt}";
((GridViewDateTimeColumn)SystemGridView.Columns["timecmd"]).FormatString = dateTimeFormat;
}
catch (Exception ex)
{
SM.Debug("Error on populate grid" + ex.ToString());
}
}
private void LoadTabList()
{
tabsHash.Clear();
tabsHash.Add(tabAlerts.Name, false);
tabsHash.Add(tabLive.Name, false);
tabsHash.Add(tabHistory.Name, false);
tabsHash.Add(tabSMS.Name, false);
tabsHash.Add(tabTicketing.Name, false);
tabsHash.Add(tabVoice.Name, false);
tabsHash.Add(tabNewRadio.Name, false);
tabsHash.Add(tabTelem.Name, false);
tabsHash.Add(tabReport.Name, false);
tabsHash.Add(tabGeo.Name, false);
tabsHash.Add(tabSystem.Name, false);
}
private void SetDefaultFloatingSizeForTabs(int width, int height)
{
tabLive.DefaultFloatingSize = new System.Drawing.Size(width, height);
tabHistory.DefaultFloatingSize = new System.Drawing.Size(width, height);
tabSMS.DefaultFloatingSize = new System.Drawing.Size(width, height);
tabTicketing.DefaultFloatingSize = new System.Drawing.Size(width, height);
tabVoice.DefaultFloatingSize = new System.Drawing.Size(width, height);
tabNewRadio.DefaultFloatingSize = new System.Drawing.Size(width, height);
tabTelem.DefaultFloatingSize = new System.Drawing.Size(width, height);
tabReport.DefaultFloatingSize = new System.Drawing.Size(width, height);
tabGeo.DefaultFloatingSize = new System.Drawing.Size(width, height);
tabSystem.DefaultFloatingSize = new System.Drawing.Size(width, height);
}
private void RemoveCloseButtonFromTabs()
{
tabSMS.DocumentButtons &= ~DocumentStripButtons.Close;
tabTicketing.DocumentButtons &= ~DocumentStripButtons.Close;
tabVoice.DocumentButtons &= ~DocumentStripButtons.Close;
tabNewRadio.DocumentButtons &= ~DocumentStripButtons.Close;
tabTelem.DocumentButtons &= ~DocumentStripButtons.Close;
tabReport.DocumentButtons &= ~DocumentStripButtons.Close;
tabGeo.DocumentButtons &= ~DocumentStripButtons.Close;
tabSystem.DocumentButtons &= ~DocumentStripButtons.Close;
}
public MainForm2(Login parent)
{
RadDockEvents.TabStripItemCreating += RadDockEvents_TabStripItemCreating;
InitializeComponent();
// load config from config.ini
loadConfigs();
if (!cfg.hasFailover)
{
grpFailover.Visible = false;
}
else
FailoverStatus(ToggleState.Indeterminate);
notifyStatic = notifyIcon1;
App appType = App.DISPATCH_MOTOROLA;
switch (MainForm2.radioType)
{
case RADIOTYPE.MOTO:
case RADIOTYPE.TETRA:
case RADIOTYPE.REPEATER_TRBO:
case RADIOTYPE.CONECTPLUS: appType = App.DISPATCH_MOTOROLA; break;
case RADIOTYPE.ATLAS: appType = App.DISPATCH_ATLAS; break;
case RADIOTYPE.HYT: appType = App.DISPATCH_HYTERA; break;
case RADIOTYPE.HARRIS: appType = App.DISPATCH_HARRIS; break;
case RADIOTYPE.SIMOCO: appType = App.DISPATCH_SIMOCO; break;
case RADIOTYPE.EXCERA: appType = App.DISPATCH_EXCERA; break;
}
ContextMenu contextMenu = new ContextMenu();
contextMenu.MenuItems.Add("Check for updates...", (s, e) => {
UpdateForm uf = new UpdateForm(appType, true) { IsDevelop = cfg.isDevelope };
uf.Show();
});
contextMenu.MenuItems.Add("Exit", (s, e) => CloseApp());
notifyIcon1.ContextMenu = contextMenu;
PopulateImageDictionary();
// set theme according to the radio type
//setThemingColors(radioType);
#region MAP LANGUAGE CHANGE
MapHtmlName += "?language="+ mapLanguage;
// save file
#endregion
// start receiving heartbeat from app server to detect when it goes off
#region APP SERVER HEARTBEAT
appServerMonitoring = new AppServerMonitoring();
//appServerMonitoring.MISSED_INTERVALS = 240;
appServerMonitoring.OnAppServerUnreacheable += delegate ()
{
Utils.WriteLine($"OnAppServerUnreacheable with monitoring {(cfg.appServerMonitoring ? "on" : "off")}", ConsoleColor.Red);
if (cfg.appServerMonitoring)
{
this.Invoke((MethodInvoker)delegate ()
{
//if (RadMessageBox.Instance == null)// || RadMessageBox.Instance.is) // || !RadMessageBox.Instance.MessageText.StartsWith("Application Server is down"))
{
RadMessageBox.Instance.Dispose();
RadMessageBox.SetThemeName("TelerikMetroBlue");
RadMessageBox.Instance.TopMost = true;
RadMessageBox.Instance.TopLevel = true;
//RadMessageBox.Show("Application Server is down. Please check the status of Application Server and be sure is up and running, if is still down the Dispacther will be also shut down.", "Error", MessageBoxButtons.OK, RadMessageIcon.Error);
DialogResult dr = RadMessageBox.Show(this, "Application Server is unreachable and the Dispacther will now close. \nContact your administrator in order to fix this issue.",
"Error", MessageBoxButtons.OK, RadMessageIcon.Error);
RadMessageBox.Instance.TopMost = false;
RadMessageBox.Instance.TopLevel = false;
MainForm_FormClosing(this, new FormClosingEventArgs(CloseReason.UserClosing, false));
System.Windows.Forms.Application.Exit();
}
//else
// RadMessageBox.Instance.Close();
//MainForm_FormClosing(this, new FormClosingEventArgs(CloseReason.UserClosing, false));
////System.Environment.Exit(0);
//System.Windows.Forms.Application.Exit();
});
}
this.Invoke((MethodInvoker)delegate ()
{
if (cfg.appServerPopUp)
DisplayDesktopAlertForAppServer("App Server Error", "Unable to communicate with App Server", true);
});
//MainForm_FormClosing(this, new FormClosingEventArgs(CloseReason.UserClosing, false));
//System.Windows.Forms.Application.Exit();
};
appServerMonitoring.OnAppServerReacheableAgain += delegate()
{
this.Invoke((MethodInvoker)delegate ()
{
if (cfg.appServerPopUp)
DisplayDesktopAlertForAppServer("App Server Notification", "App Server communication was established again", false);
});
SM.Debug("Before load hashtable");
LoadValue();
LoadHashTable();
SM.Debug("Finish load hashtable");
updateAllGPSPositions();
};
appServerMonitoring.StartAppServerMonitoring();
#endregion
RManager = new ResourceManager("Dispatcher.Language.myRes", typeof(MainForm2).Assembly);
culture = getCultureInfo(Langidx);
//set language
setLanguage();
// set theme for the Message Box
RadMessageBox.SetThemeName("TelerikMetroBlue");
RadMessageBox.ShowInTaskbar = true;
#region THEMING
pbReportType.Image = Utils.ChangeColor(resources.r_system, ButtonColor);
labelReportName.ForeColor = LabelColor;
pbClearStartTime.Image = pbClearEndTime.Image
= Utils.ChangeColor(resources.b_clear, ButtonColor);
btExportReport.ButtonElement.ButtonFillElement.BackColor = Color.White;
btExportReport.ButtonElement.TextElement.ForeColor = ButtonColor;
#endregion
RegisterCustomCommand();
radDock1.RootElement.Margin = new Padding(-2);
radDock1.RootElement.Padding = new Padding(-2);
documentContainer1.RootElement.Padding = new Padding(-2);
documentContainer1.RootElement.Margin = new Padding(-2);
//radScrollablePanel1.RootElement.Padding = new Padding(0);
documentTabStrip1.RootElement.Padding = new Padding(-2);
splitPanel1.RootElement.Padding = new Padding(-2);
radSplitContainer1.RootElement.Padding = new Padding(-2);
//radSplitContainer2.RootElement.Padding = new Padding(0);
radDock1.ActivateWindow(tabLive);
// set Tabs for each toolWindow
SetTabsForEachWindow();
// set time for system grid filtering
rdpStartTime.Value = DateTime.Now;
// set the allowed dock state for each tool windows
// in order to prevent them from being closed or hide
foreach (ToolWindow tool in documentTabStrip1.Controls.OfType<ToolWindow>().ToList())
{
tool.AllowedDockState = AllowedDockState.Docked | AllowedDockState.Floating | AllowedDockState.TabbedDocument;
// ADD close option if Live or History tab
if (((Tabs)tool.Tag) == Tabs.LIVE || ((Tabs)tool.Tag) == Tabs.HISTORY)
tool.AllowedDockState |= AllowedDockState.Hidden;
}
if (MapType == MapTYPE.ArcGis)
{
string[] fileEntries;
try
{
fileEntries = Directory.GetFiles(System.Windows.Forms.Application.StartupPath + @"\WorkMaps");
foreach (string fileName in fileEntries)
{
String fileNametmp = fileName.Substring(fileName.LastIndexOf('\\'));
if (fileNametmp.Contains(".mxd") || fileNametmp.Contains(".MXD"))
{
ArcGisFileName = System.Windows.Forms.Application.StartupPath + @"\WorkMaps\\" + fileNametmp;
break;
}
}
}
catch (Exception ex)
{
SM.Debug("Eroare la incarcat harta" + ex.ToString());
}
}
this.radDock1.DocumentTabsAlignment = Telerik.WinControls.UI.TabStripAlignment.Left;
// remove all context menu options for the left panels
ContextMenuService menuService2 = this.radDock2.GetService<ContextMenuService>();
menuService2.ContextMenuDisplaying += delegate (object sender, ContextMenuDisplayingEventArgs e)
{
if (e.MenuType == ContextMenuType.DockWindow &&
e.DockWindow.DockTabStrip is DocumentTabStrip)
{
//remove the "Close" menu items
//for (int i = 0; i < e.MenuItems.Count; i++)
// e.MenuItems[i].Visibility = Telerik.WinControls.ElementVisibility.Collapsed;
e.MenuItems.ForEach(x => x.Visibility = ElementVisibility.Collapsed);
}
};
//this disables the context menu
menuService2.AllowActiveWindowListContextMenu = false;
menuService2.AllowDocumentContextMenu = false;
menuService2.AllowToolContextMenu = false;
ChangeFont();
//old main
parent.Visible = false;
//LoginControl = parent;
this.Visible = false;
this.Location = new System.Drawing.Point(0, 0);
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
smdbObj = new SMdb_access();
smdbObj1 = new SMdb_access();
smdbObjAddress = new SMdb_access();
smdbObjAddressInsert = new SMdb_access();
smdbObjAddressInsert.InitConnectionForAddress();
//convDT = new ConvertDT();
// Int32 oldcount = radRibbonBar1.CommandTabs.Count;
/// Force to remove old voice tab
documentTabStrip1.Controls.Remove(tabVoice);
if (!TelemDecide) documentTabStrip1.Controls.Remove(tabTelem);
if (!ReportDecide) documentTabStrip1.Controls.Remove(tabReport);
// remove voice tab is no license available
if (!HasVoice)
{
documentTabStrip1.Controls.Remove(tabVoice);
documentTabStrip1.Controls.Remove(tabNewRadio);
}
if (!SMSDecide) documentTabStrip1.Controls.Remove(tabSMS);
if (!TicketingDecide) documentTabStrip1.Controls.Remove(tabTicketing);
if ((radioType != RADIOTYPE.REPEATER_TRBO) && (radioType != RADIOTYPE.MOTO) && (radioType != RADIOTYPE.LINXB))
documentTabStrip1.Controls.Remove(tabTicketing);
if (!ZonesDecide) documentTabStrip1.Controls.Remove(tabGeo);
if ((radioType != RADIOTYPE.REPEATER_TRBO) && (radioType != RADIOTYPE.MOTO) && (radioType != RADIOTYPE.LINXB) && (radioType != RADIOTYPE.HARRIS) && (radioType != RADIOTYPE.HYT))
{
if (TelemDecide) documentTabStrip1.Controls.Remove(tabTelem);
// if (VoiceDecide) documentTabStrip1.Controls.Remove(tabVoice);
}
try
{
if ((radioType == RADIOTYPE.ATLAS) || (radioType == RADIOTYPE.CONECTPLUS) || (radioType == RADIOTYPE.LISF))
{
//documentTabStrip1.Controls.Remove(tabVoice);
documentTabStrip1.Controls.Remove(tabNewRadio);
}
}
catch (Exception ex)
{
SM.Debug("Error on remove tab:" + ex.ToString());
}
try
{
if ((radioType == RADIOTYPE.LINX))
{
notifyIcon1.BalloonTipText = notifyIcon1.BalloonTipTitle = notifyIcon1.Text = this.Text = " LINX Dispatch";
documentTabStrip1.Controls.Remove(tabTelem);
documentTabStrip1.Controls.Remove(tabTicketing);
}
if ((radioType == RADIOTYPE.LINXB))
{
notifyIcon1.BalloonTipText = notifyIcon1.BalloonTipTitle = notifyIcon1.Text = this.Text = " LINX Dispatch";
}
}
catch (Exception ex)
{
SM.Debug("Error on remove tab:" + ex.ToString());
}
if (MapType == MapTYPE.ArcGis)
{
//LicenseInitializer m_AOLicenseInitializer = new Safedispatch_4_0.LicenseInitializer();
//ESRI License Initializer generated code.
m_AOLicenseInitializer.InitializeApplication(new esriLicenseProductCode[] { esriLicenseProductCode.esriLicenseProductCodeEngine, esriLicenseProductCode.esriLicenseProductCodeArcServer },
new esriLicenseExtensionCode[] { });
m_AOLicenseInitializer.ShutdownApplication();
initTextSize();
}
SM.Debug("Before load hashtable");
LoadValue();
LoadHashTable();
SM.Debug("Finish load hashtable");
//Help Remove for demo is empty
//documentTabStrip1.Controls.Remove(tabHelp);
//tabHelp.Text = "System";
ContextMenuService menuService = this.radDock1.GetService<ContextMenuService>();
menuService.ContextMenuDisplaying += menuService_ContextMenuDisplaying;
// HIDE LIVE TAB IF NOT GPS LICENSE
// hide live tab if no GPS license available or if the Live tab was previously closed by the user
if (!GPSDecide) // || (!VisualSettings.isLiveTabVisible(tabLive.Text) && GetTotalNumberOfLiveTabs() > 0))
{
LiveTabs.Clear();
documentTabStrip1.Controls.Remove(tabLive);
documentTabStrip1.Controls.Remove(tabHistory);
}
if (MainForm2.LimitedUser)
{
if (TelemDecide) documentTabStrip1.Controls.Remove(tabTelem);
if (ReportDecide) documentTabStrip1.Controls.Remove(tabReport);
if (SMSDecide) documentTabStrip1.Controls.Remove(tabSMS);
if (TicketingDecide) documentTabStrip1.Controls.Remove(tabTicketing);
if (GPSDecide) documentTabStrip1.Controls.Remove(tabHistory);
}
if (MainForm2.userType == USERTYPE.TicketingAdmin)
{
documentTabStrip1.Controls.Remove(tabGeo);
documentTabStrip1.Controls.Remove(tabLive);
documentTabStrip1.Controls.Remove(tabVoice);
documentTabStrip1.Controls.Remove(tabNewRadio);
documentTabStrip1.Controls.Add(tabTicketing);
}
// disable close and HIDE
//ContextMenuService menuService = this.radDock1.GetService<ContextMenuService>();
//menuService.ContextMenuDisplaying += menuService_ContextMenuDisplaying1;
//populateEvents();
AlarmChange(false, rep_type.IDLE, "", "", false);
this.KeyPreview = true;
///init SystemGridView
InitializeSystemGridView();
initComunicaton();
setLanguage();
checkMessage.RunWorkerAsync();
//destroy mappoint
DestroyMapPoint();
// Chamge icon and form text
ChangeIconAndText(parent);
// Display caption and the version
try
{
Version v = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
this.Text += $" - {returnLNGString("username")} : {MainForm2.userLog} - {returnLNGString("version")} : {v.ToString()}";
}
catch (Exception ex)
{
SM.Debug("Error on put name on main form caption:" + ex.ToString());
}
//load list tabs
LoadTabList();
SetDefaultFloatingSizeForTabs(1024, 768);
RemoveCloseButtonFromTabs();
this.Visible = true;
documentTabStrip1.SelectedIndex = 0;
DBsettingsManager dbSettingsManager = new DBsettingsManager(ServerDBip, Schema, UserDB, PassDB, PortDB);
#region read voice parameters
try
{
RadioTab.voicemanager_sampleRate = Convert.ToInt32(dbSettingsManager.getSettingValue(0, "sampleRate"));
RadioTab.voicemanager_bufferMilliseconds = Convert.ToInt32(dbSettingsManager.getSettingValue(0, "bufferMilliseconds"));
RadioTab.voicemanager_bitDepth = Convert.ToInt32(dbSettingsManager.getSettingValue(0, "bitDepth"));
}
catch(Exception ex) { Utils.WriteLine(ex.ToString(), ConsoleColor.Red); }
#endregion
OnEnterValid = true;
//on ENter don' work here
if (documentTabStrip1.SelectedTab == tabLive) CheckTabs(track_type.LIVE, tabLive);
else if (documentTabStrip1.SelectedTab == tabGeo) CheckTabs(track_type.LANDZONE, tabGeo);
else if (documentTabStrip1.SelectedTab == tabHistory) CheckTabs(track_type.HIST, tabHistory);
else if (documentTabStrip1.SelectedTab == tabReport) CheckTabs(track_type.REPORTS, tabReport);
else if (documentTabStrip1.SelectedTab == tabSMS) CheckTabs(track_type.SMS, tabSMS);
else if (documentTabStrip1.SelectedTab == tabTicketing) CheckTabs(track_type.TICKETING, tabTicketing);
else if (documentTabStrip1.SelectedTab == tabNewRadio) CheckTabs(track_type.RADIO, tabNewRadio);
else if (documentTabStrip1.SelectedTab == tabTelem) CheckTabs(track_type.TELEM, tabTelem);
else if (documentTabStrip1.SelectedTab == tabSystem) CheckTabs(track_type.SYSTEM, tabSystem);
GisAddress.RunWorkerAsync();
SendDataToMap.RunWorkerAsync();
SystemlogWorker.RunWorkerAsync();
if (MapType == MapTYPE.Google)
RestartSoftware.RunWorkerAsync();
// get all dispatchers
allDispatchersNames = smdbObj.GetDispatchersNames();
//start grid refresh timer
tRefreshGrid = new System.Threading.Timer(RefreshGrid, null, new TimeSpan(0, 0, 0), new TimeSpan(0, 0, 15));
DBgw.gelAllGatewaysAndRadioGatewaysHT(ref MainForm2.radioGwHT);
#region Sip class initiatization
bool registerToAsterisk = false;
GatewayType gwType = GatewayType.Unknown;
#if LINX || LINXB || EXCERA
registerToAsterisk = true;
#if LINX || LINXB
gwType = GatewayType.Broadband;
#elif EXCERA
gwType = GatewayType.Tier3Radio;
#endif
#endif
if (registerToAsterisk)
{
if (userSipId != -1)
{
// Store some sip related variables
_sipServerIP = dbSettingsManager.getSettingValue(0, "lanLinxServer"); // sipServerIP
string sipServerPort = dbSettingsManager.getSettingValue(0, "lanSipPort");
string webServicePort = dbSettingsManager.getSettingValue(0, "lanSigPort"); //webServicePort
if (!string.IsNullOrEmpty(_sipServerIP) && !string.IsNullOrEmpty(webServicePort) && !string.IsNullOrEmpty(sipServerPort))
{
if (int.TryParse(sipServerPort, out _sipServerPort) && int.TryParse(webServicePort, out _socketIOPort))
{
Utils.WriteLine($"LINX version\nRegistering with id {userSipId} to sip server {_sipServerIP}:{_sipServerPort}, signalling on {_sipServerIP}:{_socketIOPort}",
ConsoleColor.Green);
// Initialize dictionary with corespondance between radio and sipid
_sipIdToContactLinx_Dictionary = DBcontacts.getAllSipIds(MainForm2.radioType);
foreach (DictionaryEntry entry in radioGwHT)
{
RadioGateway rg = (RadioGateway)entry.Value;
if (rg.Type == (int)gwType)
{
_sipGWIDandRadioID = entry.Key.ToString();
_udpMulForGwRecording = new UdpMulticast("224.10." + _sipGWIDandRadioID, Convert.ToInt32(MainForm2.cfg.V_MSG_BUS_port));
break;
}
}
_sipIdToSeqId = new Dictionary<int, string>();
// Create sip class
_sipClient = CreateSipClass(_sipServerIP, _sipServerPort, 5060, userSipId.ToString(), "safemobile123", 30, 200, 10000, _socketIOPort);
OnSipClassInitialized();
// Stop sipClass when application closes
this.FormClosing += MainForm2_FormClosing;
}
else
{
Utils.WriteLine("LINX version - values for sip server port and web server port not in correct format", ConsoleColor.Red);
}
}
else
{
Utils.WriteLine("LINX version - could not retrieve sip server and web server info from database", ConsoleColor.Red);
}
}
}
#endregion
#region init voice for Linx
if((radioType == RADIOTYPE.LINX || radioType == RADIOTYPE.LINXB || radioType == RADIOTYPE.EXCERA) && HasVoice)
CheckTabs(track_type.RADIO, GetTabNewRadio);
#endregion
#region send isOn message
_userStatusTimer = new System.Threading.Timer(_userStatusTimer_Elapsed, null, 3000, 10000);
#endregion
}
private void updateAllGPSPositions()
{
List<Vehicle> vehicles = (MainForm2.vehicleHT.Values.Cast<Vehicle>().ToList());
foreach (Vehicle veh in vehicles)
{
String vehName = veh.busName;
UpdateStatusLive(vehName);
foreach (LiveTabWind obj in LiveTabs.Values)
{
if (MapType == MapTYPE.Google)
obj.livetab.onUnitPositionOrStateChanged(vehName);
//obj.livetab.UpdateVehList(name, true);
//else if (MapType == MapTYPE.ArcGis) obj.livetabgis.UpdateVehList(name, true);
else if (MapType == MapTYPE.ArcGis)
obj.livetabgis.onUnitPositionOrStateChanged(vehName);
//ONLY FOR TEST
obj.livetab.onGPSPositionReceivedHandler(vehName, false);
}
}
}
void _userStatusTimer_Elapsed(object obj)
{
string test1 = "#600#" + userIDX + "#ON#";
String cmdok1 = "#" + "0.0" + test1; Int32 tmp1 = cmdok1.Length + 1; tmp1 += tmp1.ToString().Length; cmdok1 = "#" + tmp1.ToString() + cmdok1;
var enc = System.Text.Encoding.ASCII;
var buf = enc.GetBytes(cmdok1);
udp.Send(buf, buf.Length);
}
private void RefreshGrid(Object state)
{
try
{
//Utils.WriteLine("Triggered refresh grid timer on live tab", ConsoleColor.DarkMagenta);
//if (state != null)
this.Invoke((MethodInvoker)delegate
{
foreach (LiveTabWind obj in LiveTabs.Values)
{
if (MapType == MapTYPE.Google)
{
obj.livetab.populateTableVehiclesList2(false, null);
}
if (MapType == MapTYPE.ArcGis)
obj.livetabgis.populateTableVehiclesList2(false, null);
}
});
}
catch (Exception ex)
{
Utils.WriteLine("refresh grid timer has failed", ConsoleColor.Red);
}
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
MainForm2.isRunning = false;
udp.StopListen();
try
{
if (SystemlogWorker != null)
{
SystemlogWorker.CancelAsync();
}
}
catch (Exception ex) { Utils.WriteLine(ex.ToString(), ConsoleColor.Red); }
// stop APP Server monitoring module
appServerMonitoring?.StopMonitoring();
ClosingApp = true;
try
{
Send_UDP_cmd_sent_withOutID("#0.0#212#" + userIDX.ToString() + "#");
smdbObj.SetUserState(userIDX, false);
if (VisualSettings.ChangedSettingsHash.Count > 0)
{
DBsettingsManager tmp = new DBsettingsManager(ServerDBip, Schema, UserDB, PassDB, PortDB);
tmp.SaveSettingsForUser(userIDX, VisualSettings.ChangedSettingsHash);
}
}
catch (Exception ex)
{
SM.Debug("Error on close:" + ex.ToString());
}
try
{
if (MainForm2.VoiceTabStarted)
{
}
}
catch (Exception ex)
{
SM.Debug("Error on close2 save PTT:" + ex.ToString());
}
}
/// <summary>
/// Close necessary things before closing the app
/// </summary>
private void CloseApp()
{
// close necessary things in the app
MainForm_FormClosing(null, null);
Process oldProcess = Process.GetCurrentProcess();
oldProcess.Kill();
System.Windows.Forms.Application.Exit();
}
private void RegisterCustomCommand()
{
radDock1.CommandManager.Enabled = true;
this.radDock1.CommandManager.RegisterCommand(new FloatWindowCommand());
}
private void menuService_ContextMenuDisplaying(object sender, ContextMenuDisplayingEventArgs e)
{
try
{
if (e.MenuType == ContextMenuType.DockWindow &&
e.DockWindow.DockTabStrip is DocumentTabStrip)
{
//remove the "Close" menu items
for (int i = 0; i < e.MenuItems.Count; i++)
{
RadMenuItemBase menuItem = e.MenuItems[i];
if (menuItem.AccessibleName.StartsWith("Close All") ||
menuItem.AccessibleName.StartsWith("Close All") ||
menuItem.AccessibleName.Equals("Auto-Hide") ||
menuItem.AccessibleName.Equals("Rename") ||
menuItem.AccessibleName.StartsWith("New Horizontal") ||
menuItem.AccessibleName.StartsWith("New Vertical") ||
menuItem.AccessibleName.Equals("Hide") ||
menuItem is RadMenuSeparatorItem)
{
menuItem.Visibility = Telerik.WinControls.ElementVisibility.Collapsed;
}
else
{
switch (menuItem.Name)
{
case "Floating":
menuItem.Text = returnLNGString("menuFloat");
break;
case "Docked":
menuItem.Text = returnLNGString("menuDock");
break;
case "NewHTabGroup":
menuItem.Text = returnLNGString("menuNewH");
break;
case "NewVTabGroup":
menuItem.Text = returnLNGString("menuNewV");
break;
}
}
if (e.DockWindow.Tag != Tabs.LIVE && menuItem.Name == "CloseWindow")
{
menuItem.Visibility = Telerik.WinControls.ElementVisibility.Collapsed;
}
}
RadMenuSeparatorItem sp = new RadMenuSeparatorItem();
e.MenuItems.Add(sp);
RadMenuItemBase menuItem1;
menuItem1 = new RadMenuItem(returnLNGString("rename"));
menuItem1.Click += this.Rename;
//e.MenuItems.Add(menuItem1);
if (GPSDecide)
{
menuItem1 = new RadMenuItem(returnLNGString("newLive"));
menuItem1.Click += this.NewLive;
e.MenuItems.Add(menuItem1);
if (!LimitedUser)
{
menuItem1 = new RadMenuItem(returnLNGString("newHist"));
menuItem1.Click += this.NewHistory;
e.MenuItems.Add(menuItem1);
}
}
}
if (e.DockWindow.FloatingParent != null)
{
e.MenuItems[0].Visibility = ElementVisibility.Collapsed;
e.MenuItems[1].Visibility = ElementVisibility.Collapsed;
e.MenuItems[4].Visibility = ElementVisibility.Collapsed;
}
}
catch (Exception ex)
{
SM.Debug("Error on remove menu from floating:" + ex.ToString());
}
}
private void NewLive(object sender, EventArgs e)
{
if (GPSDecide)
{
TabName frmName = new TabName("", false);
DialogResult dr = frmName.ShowDialog();
// skip if form was closed or canceled
if (dr != DialogResult.OK)
return;
AddLiveTab(frmName.Name);
}
}
/// <summary>
/// Add new live tab to the tab strip with the desired name
/// </summary>
/// <param name="title">Title for the new live instance</param>
private void AddLiveTab(String title)
{
ToolWindow tmpWind = new ToolWindow();
tmpWind.Text = title;
tmpWind.Tag = Tabs.LIVE;
tmpWind.Image = Utils.ScaleImage(resources.t_live_b, 25, 25);
tmpWind.DefaultFloatingSize = new System.Drawing.Size(800, 600);
tmpWind.Enter += new EventHandler(tabLive_Enter);
tmpWind.Leave += new EventHandler(tabLive_Leave);
documentTabStrip1.Controls.Add(tmpWind);
}
/// <summary>
/// Get all Live Tabs that were oppened in the last SD Session
/// </summary>
/// <returns>Array containing all tab names for visible Live Tabs in previous session</returns>
private List<String> GetAllVisibleLiveTabs()
{
List<String> tabNames = new List<string>();
foreach (DictionaryEntry pair in HashVal)
{
// detect live tabs that are visible
if (pair.Key.ToString().StartsWith("liveTab_") && Boolean.Parse(pair.Value.ToString()))
tabNames.Add(pair.Key.ToString().Replace("liveTab_",""));
}
return tabNames;
}
/// <summary>
/// Return the total number of live tabs that were generated from the begining of SD
/// </summary>
/// <returns>Number of live tab instances ever created</returns>
private int GetTotalNumberOfLiveTabs()
{
int count = 0;
foreach (DictionaryEntry pair in HashVal)
{
// add live tab to the count
if (pair.Key.ToString().StartsWith("liveTab_"))
count++;
}
return count;
}
private void NewHistory(object sender, EventArgs e)
{
if (GPSDecide)
{
TabName frmName = new TabName("", false);
frmName.ShowDialog();
ToolWindow tmpWind = new ToolWindow();
tmpWind.Text = frmName.Name;
tmpWind.Tag = Tabs.HISTORY;
tmpWind.Image = SafeMobileLib.Utils.ScaleImage(resources.t_history_b, 25, 25);
tmpWind.DefaultFloatingSize = new System.Drawing.Size(800, 600);
tmpWind.Enter += new EventHandler(tabHistory_Enter);
tmpWind.Leave += new EventHandler(tabHistory_Leave);
documentTabStrip1.Controls.Add(tmpWind);
}
}
private void NewGeofenc(object sender, EventArgs e)
{
TabName frmName = new TabName("", false);
frmName.ShowDialog();
ToolWindow tmpWind = new ToolWindow();
tmpWind.Text = frmName.Name;
tmpWind.DefaultFloatingSize = new System.Drawing.Size(800, 600);
tmpWind.Enter += new EventHandler(tabGeo_Enter);
documentTabStrip1.Controls.Add(tmpWind);
}
private void Rename(object sender, EventArgs e)
{
TabName frmName = new TabName(radDock1.ActiveWindow.Text, false);
frmName.ShowDialog();
this.radDock1.ActiveWindow.Text = frmName.Name;
}
private void LoadDock(object sender, EventArgs e)
{
this.radDock1.LoadFromXml("test.xml");
}
private void SaveDock(object sender, EventArgs e)
{
RadMenuItem m = (RadMenuItem)sender;
int i = this.documentTabStrip1.SelectedIndex;
//Telerik.WinControls.UI.Docking.DockWindow dw = this.radDock1[i];
//this.documentTabStrip1.Controls.Add(this.History);
this.radDock1.SaveToXml("test.xml");
}
private bool isMainForm2Loaded = false;
private void MainForm2_Load(object sender, EventArgs e)
{
documentTabStrip1.SelectedIndex = 0;
documentTabStrip1.Update();
// force displaying the alert icon in the Alerts tab
radDock1.ActivateWindow(tabAlerts);
isMainForm2Loaded = true;
// check for a new version if available
if (cfg.autoupdate)
CheckForUpdate();
/*
rcbDropDropDownUnitEvent.DataSource = null;
rcbDropDropDownUnitEvent.DataSource = listSystemUnitEvent;
rcbDropDropDownUnitEvent.DisplayMember = "Imei";
rcbDropDownEventType.DataSource = null;
rcbDropDownEventType.DataSource = listSysEventMsg;
rcbDropDownEventType.DisplayMember = "SysEventMsg";
*/
/*
// create the key intercepting listener
Keys toListenKey = Keys.P;
Keys toListenSpecialKey = Keys.Alt;
KeyInterceptor key = new KeyInterceptor(Keys.P, Keys.Alt);
key.OnKeyPressedStateChanged += delegate (Keys searchedKey, Keys specialKey, KeyInterceptor.KeyState state)
{
if (searchedKey == toListenKey && specialKey == toListenSpecialKey)
{
Utils.WriteLine("State is " + (state == KeyInterceptor.KeyState.DOWN ? "DOWN" : "UP"), state == KeyInterceptor.KeyState.DOWN ? ConsoleColor.Blue : ConsoleColor.Yellow);
if (state == KeyInterceptor.KeyState.DOWN)
externalPTTDown();
else
externalPTTUp();
}
};
*/
}
private void externalPTTDown()
{
if (RadioTabControl == null)
return;
if (!RadioTabControl.pttIsPressed)
{
RadioTabControl.pttIsPressed = true;
RadioTabControl.pbPTT_MouseDown(null, null);
}
}
private void externalPTTUp()
{
if (RadioTabControl == null)
return;
if (RadioTabControl.pttIsPressed)
{
RadioTabControl.pttIsPressed = false;
RadioTabControl.pbPTT_MouseUp(null, null);
}
}
#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()
{
App appType = App.DISPATCH_MOTOROLA;
switch (MainForm2.radioType)
{
case RADIOTYPE.MOTO:
case RADIOTYPE.TETRA:
case RADIOTYPE.REPEATER_TRBO:
case RADIOTYPE.CONECTPLUS: appType = App.DISPATCH_MOTOROLA; break;
case RADIOTYPE.ATLAS: appType = App.DISPATCH_ATLAS; break;
case RADIOTYPE.HYT: appType = App.DISPATCH_HYTERA; break;
case RADIOTYPE.HARRIS: appType = App.DISPATCH_HARRIS; break;
case RADIOTYPE.SIMOCO: appType = App.DISPATCH_SIMOCO; break;
case RADIOTYPE.EXCERA: appType = App.DISPATCH_EXCERA; break;
}
AutoUpdate au = new AutoUpdate(appType) { IsDevelop = cfg.isDevelope };
au.OnNewVersionAvailable += delegate (string version)
{
notifyIcon1.Text = "New version available";
notifyIcon1.ShowBalloonTip(2500, $"{App.GetAppName(appType)} version {version} available",
$"Press to download and install the latest version of {App.GetAppName(appType)}.", ToolTipIcon.Info);
notifyIcon1.BalloonTipClicked += delegate (object sender, EventArgs e)
{
if (notifyIcon1.Text.Equals("New version available"))
{
UpdateForm uf = new UpdateForm(appType, true) { IsDevelop = cfg.isDevelope };
uf.Show();
}
};
};
// call method to check for new updated
au.CheckUpdate();
}
#endregion
public ToolWindow GetTabNewRadio
{
get { return this.tabNewRadio; }
}
private track_type selectedTabType = track_type.LIVE;
public void CheckTabs(track_type type, ToolWindow tool)
{
try
{
//Console.WriteLine("CHECK TABS: " + type);
selectedTabType = type;
if (OnEnterValid)
{
if (tabsHash[tool.Name] != null)
{
if (((Boolean)tabsHash[tool.Name]) == false)
{
tabsHash[tool.Name] = true;
AddTrackWindow(type, tool);
}
else
{
if ((MapType == MapTYPE.Google) && (GoogleMapCheck))
{
if ((type == track_type.LANDZONE) && (LandZoneControl != null) && (LandZoneControl.docLoad))
{
GoogleMapCheck = false;
}
if (type == track_type.TELEM)
{
if (TelemGOControl.docLoad)
GoogleMapCheck = false;
}
if (type == track_type.LIVE)
{
foreach (LiveTabWind obj in LiveTabs.Values)
{
if (obj.toolwind == tool)
{
if (obj.livetab.docLoad)
{
GoogleMapCheck = false;
}
break;
}
}
}
if (type == track_type.HIST)
{
foreach (HistTabWind obj in HistTabs)
{
if (obj.toolwind == tool)
{
if (obj.histtab.docLoad)
{
GoogleMapCheck = false;
}
break;
}
}
}
}
}
}
else
{
tabsHash.Add(tool.Name, true);
AddTrackWindow(type, tool);
}
//Console.WriteLine("Tabs type: " + type);
if (type != track_type.LANDZONE)
{
if (MapType == MapTYPE.ArcGis)
if (MainForm2.ForceSaveZone) LandZoneGISControl.ForceSave();
}
}
}
catch (Exception ex)
{
SM.Debug("Ex tab Enter:" + ex.ToString());
RadMessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK, RadMessageIcon.Exclamation);
}
}
private void RefreshReport()
{
switch (selectedTabType)
{
case track_type.LIVE:
foreach (LiveTabWind obj in LiveTabs.Values)
{
if ((obj.toolwind.DockState == DockState.TabbedDocument) && (obj.livetab != null))
{
//obj.livetab.toolWindow2.AutoHide();
//obj.livetab.toolWindow2.DockState = DockState.TabbedDocument;
}
}
break;
case track_type.REPORTS:
if (RepControl != null)
{
try
{
//RepControl.OnFocusControl.toolWindow1.AutoHide();
//RepControl.OnFocusControl.toolWindow1.DockState = DockState.Docked;
}
catch (Exception ex)
{
SM.Debug("Error Resize:" + ex.ToString());
}
}
break;
case track_type.TELEM:
if (TelemGOControl != null)
{
try
{
if (TelemGOControl.toolWindow3.DockState == DockState.Docked)
{
TelemGOControl.toolWindow3.AutoHide();
TelemGOControl.toolWindow3.DockState = DockState.Docked;
}
if (TelemGOControl.toolWindow2.DockState == DockState.TabbedDocument)
{
TelemGOControl.toolWindow2.AutoHide();
TelemGOControl.toolWindow2.DockState = DockState.TabbedDocument;
}
}
catch (Exception ex)
{
SM.Debug("Error Resize:" + ex.ToString());
}
}
break;
}
}
private void MainForm2_Resize(object sender, EventArgs e)
{
// do not nothing in 7.0 version
}
private track_type getTrack_type(String s)
{
track_type tmp = track_type.LIVE;
switch (s)
{
case "tabLive": tmp = track_type.LIVE; break;
case "tabHistory": tmp = track_type.HIST; break;
case "tabSystem": tmp = track_type.SYSTEM; break;
case "tabGeo": tmp = track_type.LANDZONE; break;
case "tabVoice": tmp = track_type.VOICE; break;
case "tabNewRadio": tmp = track_type.RADIO; break;
case "tabReport": tmp = track_type.REPORTS; break;
case "tabSMS": tmp = track_type.SMS; break;
case "tabTicketing": tmp = track_type.TICKETING; break;
case "tabTelem": tmp = track_type.TELEM; break;
}
return tmp;
}
private void radDock1_DockStateChanging(object sender, DockStateChangingEventArgs e)
{
// do not allow to enter in alerts
if (e.NewWindow == tabAlerts)
e.Cancel = true;
}
private Icon getClasicIcon(ToolWindow dockWindow)
{
Icon icon;
if (dockWindow == tabLive)
icon = Icon.FromHandle(resources.t_live.GetHicon()); //Icon.FromHandle(resources.Live_mini_ico_norm.GetHicon());
else if (dockWindow == tabGeo)
icon = Icon.FromHandle(resources.Geo_mini_ico_norm.GetHicon());
else if (dockWindow == tabHistory)
icon = Icon.FromHandle(resources.Hist_mini_ico_norm.GetHicon());
else if (dockWindow == tabReport)
icon = Icon.FromHandle(resources.Report_mini_ico_norm.GetHicon());
else if (dockWindow == tabSMS)
icon = Icon.FromHandle(resources.SMS_mini_ico_norm.GetHicon());
else if (dockWindow == tabVoice)
icon = Icon.FromHandle(resources.Voice_mini_ico_norm.GetHicon());
else if (dockWindow == tabNewRadio)
icon = Icon.FromHandle(resources.Voice_mini_ico_norm.GetHicon());
else if (dockWindow == tabTelem)
icon = Icon.FromHandle(resources.Telem_mini_ico_norm.GetHicon());
else
icon = Icon.FromHandle(resources.Sys_mini_ico_norm.GetHicon());
return icon;
}
private Icon getPinIcon(ToolWindow dockWindow)
{
Icon icon;
if (dockWindow == tabLive)
icon = Icon.FromHandle(resources.t_live.GetHicon()); //Icon.FromHandle(resources.Live_mini_ico_pin_norm.GetHicon());
else if (dockWindow == tabGeo)
icon = Icon.FromHandle(resources.Geo_mini_ico_pin_norm.GetHicon());
else if (dockWindow == tabHistory)
icon = Icon.FromHandle(resources.Hist_mini_ico_pin_norm.GetHicon());
else if (dockWindow == tabReport)
icon = Icon.FromHandle(resources.Report_mini_ico_pin_norm.GetHicon());
else if (dockWindow == tabSMS)
icon = Icon.FromHandle(resources.SMS_mini_ico_pin_norm.GetHicon());
else if (dockWindow == tabVoice)
icon = Icon.FromHandle(resources.Voice_mini_ico_pin_norm.GetHicon());
else if (dockWindow == tabNewRadio)
icon = Icon.FromHandle(resources.Voice_mini_ico_pin_norm.GetHicon());
else if (dockWindow == tabTelem)
icon = Icon.FromHandle(resources.Telem_mini_ico_pin_norm.GetHicon());
else
icon = Icon.FromHandle(resources.Sys_mini_ico_pin_norm.GetHicon());
return icon;
}
private void radDock1_DockStateChanged(object sender, DockWindowEventArgs e)
{
try
{
if (e.DockWindow.DockState == Telerik.WinControls.UI.Docking.DockState.Floating)
{
FloatingWindow floatingWindow = (FloatingWindow)e.DockWindow.FloatingParent;
floatingWindow.FormBorderStyle = FormBorderStyle.Sizable;
floatingWindow.MaximizeBox = true;
if (iconThemeType == IconTheme.CLASSIC)
{
floatingWindow.Icon = getClasicIcon((ToolWindow)e.DockWindow);
}
else if (iconThemeType == IconTheme.PIN)
{
floatingWindow.Icon = getPinIcon((ToolWindow)e.DockWindow);
}
else
floatingWindow.Icon = Icon.FromHandle(resources.Live_mini_ico_pin.GetHicon());
//floatingWindow.MinimizeBox = true;
floatingWindow.FormElement.TitleBar.CloseButton.Visibility = ElementVisibility.Collapsed;
}
}
catch (Exception ex)
{
SM.Debug("Error remove Close button and add MAXIM and MIN:" + ex.ToString());
}
}
#region TAB LEAVE ENTER REMOVE ...
private void tabLive_Enter(object sender, EventArgs e)
{
CheckTabs(track_type.LIVE, (ToolWindow)sender);
}
private void tabHistory_Enter(object sender, EventArgs e)
{
CheckTabs(track_type.HIST, (ToolWindow)sender);
}
private void tabSMS_Enter(object sender, EventArgs e)
{
CheckTabs(track_type.SMS, (ToolWindow)sender);
//SMSnrinTab = 0;
//tabSMS.Text = returnLNGString("tabSMS");
}
private void tabTicketing_Enter(object sender, EventArgs e)
{
CheckTabs(track_type.TICKETING, (ToolWindow)sender);
TicketingNrinTab = 0;
tabTicketing.Text = returnLNGString("tabTicketing");
}
private void tabVoice_Enter(object sender, EventArgs e)
{
CheckTabs(track_type.VOICE, (ToolWindow)sender);
}
private void tabNewRadio_Enter(object sender, EventArgs e)
{
CheckTabs(track_type.RADIO, (ToolWindow)sender);
}
private void tabReport_Enter(object sender, EventArgs e)
{
CheckTabs(track_type.REPORTS, (ToolWindow)sender);
}
private void tabTelem_Enter(object sender, EventArgs e)
{
CheckTabs(track_type.TELEM, (ToolWindow)sender);
}
private void tabGeo_Enter(object sender, EventArgs e)
{
CheckTabs(track_type.LANDZONE, (ToolWindow)sender);
}
private void tabLive_Leave(object sender, EventArgs e)
{
try
{
if (MapType == MapTYPE.Google)
{
foreach (LiveTabWind obj in LiveTabs.Values)
{
if (obj.toolwind == sender)
{
if (obj.livetab.docLoad)
{
GoogleMapCheck = true;
obj.livetab.mapGoogles.ExecuteScript("window.GWTcallback('getMapType');");
Thread.Sleep(1);
//obj.livetab.LeaveTimer.Enabled = true;
//obj.livetab.LeaveTimer.Start();
}
break;
}
}
}
}
catch (Exception ex)
{
SM.Debug("Erorr on Live LEAVE" + ex.ToString());
}
}
private void tabTelem_Leave(object sender, EventArgs e)
{
try
{
if (TelemGOControl.docLoad)
{
GoogleMapCheck = true;
TelemGOControl.mapGoogles.ExecuteScript("window.GWTcallback('getMapType');");
//TelemGOControl.LeaveTimer.Enabled = true;
//TelemGOControl.LeaveTimer.Start();
}
}
catch (Exception ex)
{
SM.Debug("Erorr on telem LEAVE" + ex.ToString());
}
}
private void tabGeo_Leave(object sender, EventArgs e)
{
try
{
if ((MainForm2.MapType == MapTYPE.Google) && (LandZoneControl.docLoad))
{
GoogleMapCheck = true;
LandZoneControl.mapGoogles.ExecuteScript("window.GWTcallback('getMapType');");
//LandZoneControl.LeaveTimer.Enabled = true;
//LandZoneControl.LeaveTimer.Start();
}
}
catch (Exception ex)
{
SM.Debug("Erorr on geozone LEAVE" + ex.ToString());
}
}
private void tabHistory_Leave(object sender, EventArgs e)
{
try
{
foreach (HistTabWind obj in HistTabs)
{
if (obj.toolwind == sender)
{
if (obj.histtab.docLoad)
{
GoogleMapCheck = true;
obj.histtab.mapGoogles.ExecuteScript("window.GWTcallback('getMapType');");
//obj.histtab.LeaveTimer.Enabled = true;
//obj.histtab.LeaveTimer.Start();
}
break;
}
}
}
catch (Exception ex)
{
SM.Debug("Erorr on Live LEAVE" + ex.ToString());
}
}
private void documentTabStrip1_ControlRemoved(object sender, ControlEventArgs e)
{
try
{
if (documentTabStrip1.SelectedTab != null)
{
track_type tmp = getTrack_type(documentTabStrip1.SelectedTab.Name);
if (documentTabStrip1.SelectedTab is ToolWindow)
{
// flag that the live tab was removed
if (tmp == track_type.LIVE && MapType != MapTYPE.ArcGis)
VisualSettings.SetLiveTabVisibility(((ToolWindow)documentTabStrip1.SelectedTab).Text, false);
CheckTabs(tmp, (ToolWindow)documentTabStrip1.SelectedTab);
}
else
{
// ALERTS TAB WILL BECOME NEW SELECTED TAB
CheckTabs(tmp, tabLive);
}
}
else
{
if ((documentTabStrip1.SelectedIndex - 1) >= 0)
{
//track_type tmp = getTrack_type(documentTabStrip1.TabPanels[documentTabStrip1.SelectedIndex - 1].Name);
//if (documentTabStrip1.TabPanels[documentTabStrip1.SelectedIndex - 1] is ToolWindow)
// CheckTabs(tmp, (ToolWindow)documentTabStrip1.TabPanels[documentTabStrip1.SelectedIndex - 1]);
track_type tmp = getTrack_type(documentTabStrip1.TabPanels[documentTabStrip1.TabPanels.Count - 1].Name);
if (documentTabStrip1.TabPanels[documentTabStrip1.TabPanels.Count - 1] is ToolWindow)
{
// flag that the live tab was removed
if (tmp == track_type.LIVE && MapType != MapTYPE.ArcGis)
VisualSettings.SetLiveTabVisibility(((ToolWindow)documentTabStrip1.SelectedTab).Text, false);
CheckTabs(tmp, (ToolWindow)documentTabStrip1.TabPanels[documentTabStrip1.TabPanels.Count - 1]);
}
else
{
// ALERTS TAB WILL BECOME NEW SELECTED TAB
CheckTabs(tmp, tabLive);
}
}
}
}
catch (Exception ex)
{
SM.Debug("Error on remove Panel:" + ex.ToString());
}
}
public static void UpdateStatusLive(String name)
{
// ONLY FOR TEST
try
{
foreach (LiveTabWind obj in LiveTabs.Values)
{
if (MapType == MapTYPE.Google)
obj.livetab.onUnitPositionOrStateChanged(name);
//obj.livetab.UpdateVehList(name, true);
//else if (MapType == MapTYPE.ArcGis) obj.livetabgis.UpdateVehList(name, true);
else if (MapType == MapTYPE.ArcGis) obj.livetabgis.onUnitPositionOrStateChanged(name);
}
}
catch (Exception ex)
{
SM.Debug("Error update status:" + ex.ToString());
}
}
public static void ChangeIconStatusForArrowType(String name)
{
try
{
foreach (LiveTabWind obj in LiveTabs.Values)
{
if (MainForm2.MapType == MapTYPE.Google)
{
//fake cmd to make parse
((MapElement)((Vehicle)vehicleHT[name]).MapsHT[obj.livetab.tabName]).UpdateSymbol();
obj.livetab.deleteDsetcomand = "deleteFromDataset,vehicles_positions,101,";
obj.livetab.ComputeCheckedVehicles(false);
}
else if (MainForm2.MapType == MapTYPE.ArcGis)
{
Console.WriteLine("Face ArcGIS-ul");
((MapElement)((Vehicle)vehicleHT[name]).MapsHT[obj.livetabgis.tabName]).UpdateSymbol();
//obj.livetabgis.ComputeCheckedVehicles(false);
obj.livetabgis.ComputeCheckedVehicles(true);
}
}
}
catch (Exception ex)
{
SM.Debug("Error update status:" + ex.ToString());
}
}
public static void RemoveIconsFromMap()
{
try
{
foreach (LiveTabWind obj in LiveTabs.Values)
{
if (MainForm2.MapType == MapTYPE.Google)
{
//fake cmd to make parse
obj.livetab.deleteDsetcomand = "deleteFromDataset,vehicles_positions,101,";
obj.livetab.ComputeCheckedVehicles(false);
}
else if (MainForm2.MapType == MapTYPE.ArcGis)
{
obj.livetabgis.ComputeCheckedVehicles(false);
}
}
}
catch (Exception ex)
{
SM.Debug("Error update status:" + ex.ToString());
}
}
public static void ChangeIconsFromMap()
{
try
{
foreach (LiveTabWind obj in LiveTabs.Values)
{
if (MainForm2.MapType == MapTYPE.Google)
obj.livetab.ComputeCheckedVehicles(false);
else if (MainForm2.MapType == MapTYPE.ArcGis)
{
obj.livetabgis.ComputeCheckedVehicles(false);
}
}
}
catch (Exception ex)
{
SM.Debug("Error update status:" + ex.ToString());
}
}
#endregion
#region ARCGIS
public static ISimpleTextSymbol simpleTextSymbol = null;
private void initTextSize()
{
try
{
IColor color = new RgbColorClass() { Red = 0, Green = 0, Blue = 205 };
ITextSymbol textSymbol = new TextSymbolClass();
textSymbol.Size = 10;
//System.Drawing.Font drawFont = new System.Drawing.Font("Arial", 14, FontStyle.Bold);
simpleTextSymbol = (ISimpleTextSymbol)textSymbol;
simpleTextSymbol.YOffset = 20;
simpleTextSymbol.XOffset = -12;
simpleTextSymbol.Color = color;
}
catch (Exception ex)
{
SM.Debug("Ex20:" + ex.ToString());
}
}
public static ISpatialReference CreateGeoCoordSys()
{
try
{
ISpatialReferenceFactory2 spatialRefFactory = new SpatialReferenceEnvironmentClass();
IGeographicCoordinateSystem wgs84GeoCoordSys = spatialRefFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984);
return (ISpatialReference)wgs84GeoCoordSys;
}
catch (Exception ex)
{
SM.Debug("Ex21:" + ex.ToString());
return null;
}
}
public static ESRI.ArcGIS.Geometry.IEnvelope ZoomTo(Double lNGMIN, Double lATMIN, Double lNGMAX, Double lATMAX)
{
try
{
Double LATMAX = 0, LATMIN = 0, LNGMAX = 0, LNGMIN = 0, steplat = 0, steplng = 0;
if ((lATMAX != lATMIN) && (lNGMAX != lNGMIN))
{
steplat = (lATMAX - lATMIN) / 10;
steplng = (lNGMAX - lNGMIN) / 10;
if (steplng < 0.01) steplng = 0.01;
if (steplat < 0.01) steplat = 0.01;
LATMAX = lATMAX + steplat;
LNGMAX = lNGMAX + steplng;
LATMIN = lATMIN - steplat;
LNGMIN = lNGMIN - steplng;
}
else
{
LATMAX = lATMAX + 0.001;
LNGMAX = lNGMAX + 0.001;
LATMIN = lATMIN - 0.001;
LNGMIN = lNGMIN - 0.001;
}
ESRI.ArcGIS.Geometry.IPoint UL = new ESRI.ArcGIS.Geometry.PointClass();
UL.PutCoords(LNGMIN, LATMAX);
UL.SpatialReference = CreateGeoCoordSys();
ESRI.ArcGIS.Geometry.IPoint DL = new ESRI.ArcGIS.Geometry.PointClass();
DL.PutCoords(LNGMIN, LATMIN);
DL.SpatialReference = CreateGeoCoordSys();
ESRI.ArcGIS.Geometry.IPoint DR = new ESRI.ArcGIS.Geometry.PointClass();
DR.PutCoords(LNGMAX, LATMIN);
DR.SpatialReference = CreateGeoCoordSys();
ESRI.ArcGIS.Geometry.IPoint UR = new ESRI.ArcGIS.Geometry.PointClass();
UR.PutCoords(LNGMAX, LATMAX);
UR.SpatialReference = CreateGeoCoordSys();
ESRI.ArcGIS.Geometry.IEnvelope envelope = new ESRI.ArcGIS.Geometry.EnvelopeClass();
envelope.LowerLeft = DL;
envelope.LowerRight = DR;
envelope.UpperLeft = UL;
envelope.UpperRight = UR;
return envelope;
}
catch (Exception ex)
{
SM.Debug("Ex22:" + ex.ToString());
return null;
}
}
public static volatile Queue AddrGISQueue = new Queue();
public static volatile InterthreadMessageQueue<SystemLog> SystemMessQueue = new InterthreadMessageQueue<SystemLog>();
public Double valHash = 0;
public volatile Boolean findaddress = false;
public volatile LiveTab LiveForAddres = null;
public volatile Hashtable ListForWait = new Hashtable();
private volatile AddrAndID tmpAddrAndID = null;
private volatile String AddrtmpX = "";
private volatile ReverseGeocoding volltmpGo2 = new ReverseGeocoding(MainForm2.cfg.ReverseGeoOSM);
private void GisAddress_DoWork(object sender, DoWorkEventArgs e)
{
smdbObjAddress.InitConnectionForAddress();
while (isRunning)
{
try
{
while (AddrGISQueue.Count > 0)
{
tmpAddrAndID = AddrGISQueue.Dequeue() as AddrAndID;
findaddress = false;
// skip invalid addresses
if (tmpAddrAndID == null)
{
continue;
}
try
{
tmpAddrAndID.LNG = Math.Round(tmpAddrAndID.LNG, 4);
tmpAddrAndID.LAT = Math.Round(tmpAddrAndID.LAT, 4);
valHash = tmpAddrAndID.LNG + tmpAddrAndID.LAT * 0.000001;
if (AddrHass[valHash] != null)
{
// get address from hashtable
tmpAddrAndID.Address = (String)AddrHass[valHash];
findaddress = true;
}
else
{
// get address from database
AddrtmpX = smdbObjAddress.get_address_one_connection(tmpAddrAndID.LAT, tmpAddrAndID.LNG);
if (AddrtmpX != "")
{
AddrHass.Add(valHash, AddrtmpX);
tmpAddrAndID.Address = AddrtmpX;
findaddress = true;
}
}
}
catch(Exception ex)
{
Utils.WriteLine(ex.ToString(), ConsoleColor.Red);
}
if (!findaddress)
{
// get address by reverse geocoding
tmpAddrAndID.Address = volltmpGo2.getAddressLATLNG(tmpAddrAndID.LAT, tmpAddrAndID.LNG);
}
if ((tmpAddrAndID.Address != "") && (tmpAddrAndID.Address != " "))
{
if (!findaddress)
{
try
{
if (tmpAddrAndID.Address != "N/A")
{
valHash = tmpAddrAndID.LNG + tmpAddrAndID.LAT * 0.000001;
AddrHass.Add(valHash, tmpAddrAndID.Address);
AddrtmpX = smdbObjAddress.get_address_one_connection(tmpAddrAndID.LAT, tmpAddrAndID.LNG); //just for avoid Error from Event Viewer
if (AddrtmpX == "")
smdbObjAddress.Insert_Address_with_one_connection(tmpAddrAndID.Address, tmpAddrAndID.LAT, tmpAddrAndID.LNG);
}
}
catch (Exception ex)
{
SM.Debug("Error: " + ex.ToString());
}
}
GisAddress.ReportProgress(tmpAddrAndID.ID, tmpAddrAndID);
if ((tmpAddrAndID.ID == 0) && (tmpAddrAndID.Address != "N/A"))
{
Vehicle vehicle = ((Vehicle)vehicleHT[tmpAddrAndID.Name]);
smdbObjAddress.Update_address_with_one_connection(vehicle.IMEI, vehicle.sc_id, vehicle.lastActivityTime, tmpAddrAndID.Address, tmpAddrAndID.LAT, tmpAddrAndID.LNG);
}
else
smdbObjAddress.UpdateInsertAddressHash(tmpAddrAndID.Address, tmpAddrAndID.LAT, tmpAddrAndID.LNG);
}
}
}
catch (Exception ex)
{
SM.Debug("Error retrive address:" + ex.ToString());
}
Thread.Sleep(10);
}
//must be close conection but not here
}
private volatile AddrAndID procAddrAndID = null;
private volatile ArrayList idToRemove = new ArrayList();
private void GisAddress_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
try
{
procAddrAndID = (AddrAndID)e.UserState;
MakeUpdateWithAddress(e.ProgressPercentage, procAddrAndID);
}
catch (Exception ex)
{
SM.Debug("Erorr:" + ex.ToString());
}
}
private void MakeUpdateWithAddress(Int32 ID, AddrAndID tmp)
{
if (ID == 0)
{
try
{
((Vehicle)vehicleHT[tmp.Name]).SetLastAddress(tmp.Address);
((Vehicle)vehicleHT[tmp.Name]).needAddress = false;
foreach (LiveTabWind obj in LiveTabs.Values)
{
if (MapType == MapTYPE.Google)
{
// refresh position for the unit
obj.livetab.RefreshPositionsGrid(tmp.Name);
}
}
try { if (SendDataToMapHASH[tmp.Name] == null) SendDataToMapHASH.Add(tmp.Name, 1); }
catch(Exception ex) { Utils.WriteLine(ex.ToString(), ConsoleColor.Red); }
SendDataToMapQUE.PostItem(tmp.Name);
}
catch (Exception ex)
{
SM.Debug("error on update adress in live" + ex.ToString());
}
}
else
{
try
{
MainForm2.IdReportHS[ID.ToString()] = tmp.Address;
StaticMembers.IdReportHS[ID.ToString()] = tmp.Address;
}
catch (Exception ex)
{
SM.Debug("Error add addres i HASH" + ex.ToString());
}
}
}
#endregion
private void SystemlogWorker_DoWork(object sender, DoWorkEventArgs e)
{
while (MainForm2.isRunning)
{
try
{
// do not autorefresh grid if not wanted
if (!rcbAutoRefresh.Checked)
{
Thread.Sleep(300);
continue;
}
while (SystemMessQueue.Count > 0)
{
SystemLog log = SystemMessQueue.GetItem(100);
if(log != null)
SystemlogWorker.ReportProgress(0, log);
Thread.Sleep(2);
}
if ((SystemLogFinish) && (SystemLogDataComplete) && (SystemLogSortComplete))
SystemlogWorker.ReportProgress(1);
}
catch (Exception ex)
{
SM.Debug("Error on parse system MessageWorker do work:" + ex.ToString());
}
Thread.Sleep(5000);
}
}
private void SystemlogWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (e.ProgressPercentage == 0)
{
try
{
AddDataToSystemGrid(((SystemLog)e.UserState).Senddata, ((SystemLog)e.UserState).cmd);
}
catch (Exception ex)
{
SM.Debug("Error on progress change:" + ex.ToString());
}
}
else
{
try
{
if ((SystemLogFinish) && (SystemLogDataComplete) && (SystemLogSortComplete))
{
if (MainForm2.is24hours) lbLastRefresh.Text = lasttimeRef + ": " + DateTime.Now.ToLocalTime().ToString("MM/dd/yyyy HH:mm:ss");
else lbLastRefresh.Text = lasttimeRef + ": " + DateTime.Now.ToLocalTime().ToString("MM/dd/yyyy hh:mm:ss tt");
SystemLogFinish = false;
SystemLogDataComplete = false;
if (!SystemGridView.IsDisposed)
{
SystemGridView.Columns["timecmd"].SortOrder = RadSortOrder.None;
SystemLogSortComplete = false;
try
{
SystemGridView.DataSource = null;
SystemGridView.DataSource = startList;
}
catch (Exception ex)
{
SM.Debug("Error on populate grid" + ex.ToString());
}
SystemGridView.Columns["timecmd"].SortOrder = RadSortOrder.Descending;
SystemGridView.TableElement.ScrollToRow(0);
}
SystemLogFinish = true;
}
}
catch (Exception ex)
{
SystemLogFinish = true;
SM.Debug("Error on progress change:" + ex.ToString());
}
}
}
private DateTime lastMapUpdateFromSendDataToMap;
public static volatile InterthreadMessageQueue<String> SendDataToMapQUE = new InterthreadMessageQueue<String>();
private volatile ArrayList Recheck = new ArrayList();
public static volatile Hashtable SendDataToMapHASH = new Hashtable();
private volatile Boolean valueCMD = false;
private volatile String tmpname = "";
private void SendDataToMap_DoWork(object sender, DoWorkEventArgs e)
{
while (MainForm2.isRunning)
{
try
{
lastMapUpdateFromSendDataToMap = DateTime.Now;
Recheck.Clear();
while (SendDataToMapQUE.Count > 0)
{
valueCMD = true;
tmpname = (String)SendDataToMapQUE.GetItem(int.MaxValue);
if ((tmpname != null) && (tmpname != "") && (tmpname != " ") && (SendDataToMapHASH[tmpname] != null))
{
try
{
if ((((Int32)SendDataToMapHASH[tmpname]) == 0) && (((Vehicle)vehicleHT[tmpname]).needAddress))
{
SendDataToMapHASH[tmpname] = 1;
Recheck.Add(tmpname);
}
else
SendDataToMapHASH.Remove(tmpname);
}
catch (Exception ex)
{
Utils.WriteLine("SendDataToMap_DoWork error: " + ex.ToString(), ConsoleColor.Red);
}
//===================================================
Vehicle vehicle = vehicleHT[tmpname] as Vehicle;
//===================================================
if ( vehicle != null && vehicle.MapsHT != null)
{
foreach (String name in vehicle.MapsHT.Keys)
{
//==================================================================================
MapElement mapElement = (MapElement)((Vehicle)vehicleHT[tmpname]).MapsHT[name];
//==================================================================================
if (( HideInactiveUnitsCheck && mapElement.itemCheck) ||
(emergOnlyCheck && vehicle.actual_status == Status_for_tab.EMERG))
{
mapElement.isActive = true;
}
if (mapElement.isActive)
{
mapElement.SetLastLocation();
mapElement.SetLastPushpin();
//temp solution for don't update the address on the Icon on live
if (MapType != MapTYPE.ArcGis)
mapElement.ActivatePushPin();
if (MapType == MapTYPE.Google)
{
if (vehicle.needAddress)
vehicle.SetLastAddress(msgRetAddr);
mapElement.pp.Note =
langSpeed + " " + Convert.ToString(vehicle.GetSpeed()) + Measure
+ " " + langTime + " " + vehicle.lastActivityTime.TimeOfDayHHMMLocal()
+ "<br>" + FixComma(vehicle.lastAddress);
//if ((MainForm2.POLLunit == tmpname) && ((Math.Round(((Vehicle)vehicleHT[volVehN]).LAT) != 0) && (Math.Round(((Vehicle)vehicleHT[volVehName]).LNG) != 0)))
if (MainForm2.POLLunit == tmpname && Math.Round(vehicle.LAT) != 0 && Math.Round(vehicle.LNG) != 0)
{
MovePOLL = true;
;// SendDataToMap.ReportProgress(1, ((MapElement)((Vehicle)vehicleHT[tmpname]).MapsHT[name]));
}
}
}
}
}
if (MovePOLL) { MainForm2.POLLunit = ""; MovePOLL = false; }
}
Thread.Sleep(10);
foreach (String name in Recheck)
SendDataToMapQUE.PostItem(name);
//SendDataToMap.ReportProgress(0);
valueCMD = false;
Recheck.Clear();
Thread.Sleep(100);
}
if (valueCMD)
{
foreach (String name in Recheck)
SendDataToMapQUE.PostItem(name);
//SendDataToMap.ReportProgress(0);
}
}
catch (Exception ex)
{
Utils.WriteLine("Error on Send data to map:" + ex.ToString(), ConsoleColor.Red);
}
Thread.Sleep(200);//3000
}
}
private void setMapDataSet(List<String> unitNames)
{
foreach (String unitName in unitNames)
{
//==================================================
Vehicle vehicle = (Vehicle)vehicleHT[unitName];
//==================================================
Boolean hasVoice = vehicle.has_voice;
Boolean hasText = vehicle.has_text;
Boolean isInCall = vehicle.inCall;
DateTime positionTime = vehicle.lastValidPositionTime.ConvertGMTToLocal().GetDTFromSeconds();
#region mapCallTimeout && sms length
int smsLength = SmsUtils.GetMaxNumberOfCharacters(MainForm2.radioType);
int mapCallTimeout = 3;
vehicle.CheckPositionInSystem();
string GatewayAndRadioID = vehicle.GwandRadioID;
int gwType = (int)GatewayType.Unknown;
if (MainForm2.radioGwHT[GatewayAndRadioID] != null)
{
if (((RadioGateway)MainForm2.radioGwHT[GatewayAndRadioID]).Type == (int)GatewayType.Broadband
|| ((RadioGateway)MainForm2.radioGwHT[GatewayAndRadioID]).Type == (int)GatewayType.Tier3Radio)
{
mapCallTimeout = MainForm2.MapCallTimeout;
}
gwType = ((RadioGateway)MainForm2.radioGwHT[GatewayAndRadioID]).Type;
smsLength = SmsUtils.GetMaxNumberOfCharacters(gwType);
}
#endregion
foreach (String name in vehicle.MapsHT.Keys)
{
//==================================================================================
MapElement mapElement = (MapElement)((Vehicle)vehicleHT[tmpname]).MapsHT[name];
//==================================================================================
string iconName = mapElement.pp.GetSymbName();
if (vehicle.is_emergency)
{
iconName = iconName.Replace(".png", "_FF79A6_l.png");
// check and create emergency icon
CheckCreateEmergencyIcon(vehicle.IconID);
}
/*
else if (MainForm2.Displaywithname)
{
iconName = iconName.Replace(".png", "_" + veh.IconID + "_" + veh.sc_id + ".png");
// check and create emergency icon
CheckCreateNamedIcon(veh.IconID, veh.busName, veh.sc_id);
}*/
// set the command which will contains the points icon, name, speed, lat, lng, altitude, address
mapElement.mapControl.parLive.updatecomand += ","
+ FixDoubleLAT(vehicle.LAT.ToString()) + ","
+ FixDoubleLNG(vehicle.LNG.ToString()) + ","
+ positionTime.ToString("yyyy-MM-dd HH:mm:ss") + ","
+ unitName + ","
+ vehicle.GetSpeed() + (MainForm2.isInMile ? "mph" : "kph") + ","
+ vehicle.GetAlt() + ","
+ vehicle.GetLastAddress().Replace(',', ' ') + ","
//+ ((MapElement)((Vehicle)vehicleHT[tmpname]).MapsHT[name]).pp.GetSymbName() + ","
+ iconName + "," + (hasVoice ? mapCallTimeout : 0) + "," + (hasText ? smsLength : 0) + "," + isInCall;
}
}
}
private void SendDataToMap_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
try
{
if (e.ProgressPercentage == 0)
{
foreach (LiveTabWind obj in LiveTabs.Values)
{
if (MapType == MapTYPE.Google)
{
if (obj.livetab.updatecomand != "")
{
if (obj.livetab.setdatasetBool)
{
if (obj.livetab.updatecomand.Contains("updateDataset,vehicles_positions")) ;
else obj.livetab.updatecomand = "updateDataset,vehicles_positions" + obj.livetab.updatecomand;
}
else
{
if (obj.livetab.updatecomand.IndexOf(',') != obj.livetab.updatecomand.LastIndexOf(','))
{
if (obj.livetab.updatecomand.Contains("updateDataset,vehicles_positions"))
obj.livetab.updatecomand = obj.livetab.updatecomand.Replace("updateDataset", "setDataset");
else
obj.livetab.updatecomand = "setDataset,vehicles_positions" + obj.livetab.updatecomand;
obj.livetab.setdatasetBool = true;
}
else obj.livetab.updatecomand = "updateDataset,vehicles_positions";
}
obj.livetab.ComputeCheckedVehicles(false);
}//ONLY FOR TEST
obj.livetab.onGPSPositionReceivedHandler(volVehName, false);
}
else if (MapType == MapTYPE.ArcGis) obj.livetabgis.CheckForUpdate(volVehName);
}
}
else if (e.ProgressPercentage == 1)
{
if (volVehNamePoll != "")
{
foreach (LiveTabWind obj in LiveTabs.Values)
{
if (MapType == MapTYPE.Google)
{
obj.livetab.CenterAndOpenBubble(volVehNamePoll);
}
}
}
/*
if ((Math.Round(((Vehicle)MainForm2.vehicleHT[MainForm2.POLLunit]).LNG) != 0) && (Math.Round(((Vehicle)MainForm2.vehicleHT[MainForm2.POLLunit]).LAT) != 0))
((MapElement)e.UserState).mapControl.mapGoogles.ExecuteScript("window.GWTcallback('centerzoom," + MainForm2.FixDoubleLAT(((Vehicle)MainForm2.vehicleHT[MainForm2.POLLunit]).LAT.ToString()) + "," + MainForm2.FixDoubleLNG(((Vehicle)MainForm2.vehicleHT[MainForm2.POLLunit]).LNG.ToString()) + ",15');");
Thread.Sleep(1);*/
}
}
catch (Exception ex)
{
SM.Debug("Error on Refreshing 3sec:" + ex.ToString());
}
}
private void SystemGridView_DataBindingComplete(object sender, GridViewBindingCompleteEventArgs e)
{
//Console.WriteLine("Data Binding Complete");
SystemLogDataComplete = true;
}
private void SystemGridView_SortChanged(object sender, GridViewCollectionChangedEventArgs e)
{
//Console.WriteLine("Sort changed");
SystemLogSortComplete = true;
}
private void MainForm2_FormClosed(object sender, FormClosedEventArgs e)
{
try
{
RadDockEvents.TabStripItemCreating -= RadDockEvents_TabStripItemCreating;
//System.Environment.Exit(0);
System.Windows.Forms.Application.Exit();
}
catch (Exception ex)
{
Utils.WriteLine(ex.ToString(), ConsoleColor.Red);
}
}
private void btForceRefresh_Click(object sender, EventArgs e)
{
try
{
while (SystemMessQueue.Count > 0)
{
try
{
SystemLog log = SystemMessQueue.GetItem(100);
if (log != null)
AddDataToSystemGrid(log.Senddata, log.cmd);
}
catch (Exception ex)
{
SM.Debug("Error on progress change:" + ex.ToString());
}
Thread.Sleep(10);
}
if ((SystemLogFinish) && (SystemLogDataComplete) && (SystemLogSortComplete))
{
if (MainForm2.is24hours) lbLastRefresh.Text = lasttimeRef + ": " + DateTime.Now.ToLocalTime().ToString("MM/dd/yyyy HH:mm:ss");
else lbLastRefresh.Text = lasttimeRef + ": " + DateTime.Now.ToLocalTime().ToString("MM/dd/yyyy hh:mm:ss tt");
SystemLogFinish = false;
SystemLogDataComplete = false;
SystemGridView.Columns["timecmd"].SortOrder = RadSortOrder.None;
SystemLogSortComplete = false;
try
{
SystemGridView.DataSource = null;
SystemGridView.DataSource = startList;
}
catch (Exception ex)
{
SM.Debug("Error on populate grid" + ex.ToString());
}
SystemGridView.Columns["timecmd"].SortOrder = RadSortOrder.Descending;
SystemGridView.TableElement.ScrollToRow(0);
SystemLogFinish = true;
}
}
catch (Exception ex)
{
SM.Debug("Error on populate system tab grid:" + ex.ToString());
}
}
private void RestartSoftware_DoWork(object sender, DoWorkEventArgs e)
{
try
{
BackgroundWorker worker = sender as BackgroundWorker;
e.Result = RestartSoft(worker, e);
}
catch (Exception ex)
{
SM.Debug("Ex12:" + ex.ToString());
}
}
private Int64 contsTimer = 0;
private volatile Int32 count6 = 0;
private volatile Int32 DistroyTime = 0;
private volatile Boolean forceRefresh = false;
private volatile Boolean Stopdecision = false;
private void RestartSoftware_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
try
{
WaitToLoad temp = new WaitToLoad(true);
temp.Show();
}
catch (Exception ex)
{
SM.Debug("Error on show restarting window");
}
}
long RestartSoft(BackgroundWorker worker, DoWorkEventArgs e)
{
//return 0;
while (MainForm2.isRunning)
{
contsTimer++;
if (Stopdecision)
{
count6++;
if (count6 > 6) Stopdecision = false;
}
try
{
Process curentProcess = Process.GetCurrentProcess();
Process[] ProcessDispatchList = Process.GetProcessesByName("Dispatcher");
Process ProcessDispName = null;
try
{
if (ProcessDispatchList.Length > 0)
{
if (ProcessDispatchList[0] != null) ProcessDispName = ProcessDispatchList[0];
}
}
catch (Exception ex)
{
SM.Debug("Error on get proccess by name" + ex.ToString());
}
Process ProcessDispatch = Process.GetCurrentProcess();
//ok i will put 650 Mega to include more stuff with hisotry and geofence
if (ProcessDispName != null)
{
//Utils.WriteLine("CurentProcess:" + curentProcess.WorkingSet64 + " ProccessDispName:" + ProcessDispName.WorkingSet64, ConsoleColor.Green);
//Utils.WriteLine("rResatr ameem value:" + MainForm2.RestartMEM, ConsoleColor.Green);
if ( (((curentProcess.WorkingSet64 > MainForm2.RestartMEM) || (ProcessDispName.WorkingSet64 > MainForm2.RestartMEM)) && (!Stopdecision))
|| forceReconnectToNewIP )//3000//7000//30000
{
Stopdecision = true;
if (forceReconnectToNewIP)
forceReconnectToNewIP = false;
worker.ReportProgress(1);
try
{
Process oldProcess = Process.GetCurrentProcess();
oldProcess.WaitForExit(8000);
String argument = " forcelogin";
switch (MainForm2.radioType)
{
case RADIOTYPE.MOTO:
argument = String.Concat("motorola", argument);
break;
case RADIOTYPE.HYT:
argument = String.Concat("hytera", argument);
break;
case RADIOTYPE.HARRIS:
argument = String.Concat("harris", argument);
break;
case RADIOTYPE.ATLAS:
argument = String.Concat("atlas", argument);
break;
case RADIOTYPE.TETRA:
argument = String.Concat("tetra", argument);
break;
case RADIOTYPE.CONECTPLUS:
argument = String.Concat("conplus", argument);
break;
case RADIOTYPE.REPEATER_TRBO:
argument = String.Concat("repeater", argument);
break;
case RADIOTYPE.SIMOCO:
argument = String.Concat("simoco", argument);
break;
case RADIOTYPE.EXCERA:
argument = String.Concat("excera", argument);
break;
}
Process.Start(System.Windows.Forms.Application.ExecutablePath, argument);
oldProcess.Kill();
System.Windows.Forms.Application.Exit();
}
catch (Exception ex)
{
SM.Debug("Error on restart timer:" + ex.ToString());
// the process did not exist - probably already closed!
//TODO: --> LOG
}
}
}
Thread.Sleep(5000);
if (MainForm2.ClosingApp)
{
SM.Debug("RestartSoft: CancellationPending in Radio: ");
e.Cancel = true;
return 1;
}
}
catch (Exception ex)
{
SM.Debug("Error on restart thread:" + ex.ToString());
}
}
return 0;
}
private int counter = 1;
private void btExportReport_Click(object sender, EventArgs e)
{
//Boolean errormess = false;
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Docx|*.docx";
sfd.Title = "Save all events";
string dateTime = DateTime.Now.ToString();
dateTime = dateTime.Replace("/", "_");
dateTime = dateTime.Replace("\\", "_");
dateTime = dateTime.Replace(" ", "_");
dateTime = dateTime.Replace(":", ".");
sfd.FileName = String.Format(@"" + (MainForm2.radioType == RADIOTYPE.SIMOCO ? "Simoco" : MainForm2.radioType == RADIOTYPE.EXCERA ? "Excera" : "SafeMobile")
+ "_log_{0}.docx", dateTime);
DialogResult dr = sfd.ShowDialog();
// If the file name is not an empty string open it for saving.
if (dr == System.Windows.Forms.DialogResult.OK
|| dr == System.Windows.Forms.DialogResult.Yes)
{
// We will need a file name for our output file (change to suit your machine):
string fileNameTemplate = sfd.FileName + (sfd.FileName.EndsWith(".docx") ? "" : ".docx"); //@"Invoice_{0}-{1:MM_dd_yy_HH.mm.ss}.docx";
// Let's save the file with a meaningful name, including the applicant name and the letter date:
//System.IO.Directory.CreateDirectory("exports");
//string outputFileName = string.Format("exports/" + fileNameTemplate, cbCabinetWork.Text, DateTime.Now);
// Grab a reference to the desired template
var doc = Novacode.DocX.Load(@"resource\templates\export_system.docx");
doc.ReplaceText("%DATA%", String.Format("{0}", DateTime.Now.ToString()));
doc.ReplaceText("%COMPANY%", "Generated using " + (MainForm2.radioType == RADIOTYPE.SIMOCO ? "Simoco" : MainForm2.radioType == RADIOTYPE.EXCERA ? "Excera" : "SafeMobile")
+ " Dispatch");
#region Works
// get the empty template row
Novacode.Row emptyRow = doc.Tables[0].Rows[doc.Tables[0].RowCount - 1];
counter = 1;
if (SystemGridView.ChildRows.Count != 0)
{
foreach (GridViewRowInfo groupRow in SystemGridView.ChildRows)
{
if (groupRow.ChildRows.Count > 0)
{
foreach (GridViewRowInfo gridRow in groupRow.ChildRows)
{
DataforSystemList log = gridRow.DataBoundItem as DataforSystemList;
// skip group headers and others UI elements withoug databound items
if (log == null)
continue;
// add the wor to the export file
WriteRowToExportDoc(doc, emptyRow, log);
}
}
else
{
DataforSystemList log = groupRow.DataBoundItem as DataforSystemList;
// skip group headers and others UI elements withoug databound items
if (log == null)
continue;
// add the wor to the export file
WriteRowToExportDoc(doc, emptyRow, log);
}
}
}
else
{
foreach (GridViewRowInfo gridRow in SystemGridView.Rows)
{
DataforSystemList log = gridRow.DataBoundItem as DataforSystemList;
// skip group headers and others UI elements withoug databound items
if (log == null)
continue;
// add the wor to the export file
WriteRowToExportDoc(doc, emptyRow, log);
}
}
// remove first row after the header because is an empty one
doc.Tables[0].RemoveRow(1);
#endregion
try
{
// Save as New filename:
doc.SaveAs(sfd.FileName);
// Open in word:
//Process.Start("WINWORD.EXE", "\"" + outputFileName + "\"");
DisplayToast(MainForm2.returnLNGString("SysLogSucces"), string.Format(MainForm2.returnLNGString("HTMLSavedSucces"), fileNameTemplate, sfd.FileName));
} catch (Exception ex)
{
DisplayToast(MainForm2.returnLNGString("SysLogFailed"), string.Format(MainForm2.returnLNGString("SysLogFailedMsg"), fileNameTemplate, sfd.FileName));
}
}
}
private void WriteRowToExportDoc(Novacode.DocX doc, Novacode.Row emptyRow, DataforSystemList logInfo)
{
FontFamily centuryGothic = null;
try
{
centuryGothic = new FontFamily("Century Gothic");
}
catch (Exception ex)
{
Utils.WriteLine(ex.ToString(), ConsoleColor.Red);
}
FontFamily font = new FontFamily("Arial");
if (centuryGothic != null)
font = centuryGothic;
// add a new empty row and then edit it
doc.Tables[0].InsertRow(emptyRow);
// get the new inserted row which is empty
Novacode.Row row = doc.Tables[0].Rows[doc.Tables[0].RowCount - 1];
int column = 0;
row.Cells[column++].Paragraphs[0].Append(counter++ + "").FontSize(9).Font(font);
using (MemoryStream ms = new MemoryStream())
{
//write image to the memory stream
if (logInfo.Direct == 0)
resources.call_made_24x20.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
else
resources.call_received_24X20.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
// go to the begining of the picture
ms.Seek(0, SeekOrigin.Begin);
Novacode.Image img = doc.AddImage(ms); // Create image.
Novacode.Picture pic1 = img.CreatePicture(); // Create picture.
row.Cells[column++].Paragraphs[0].AppendPicture(pic1);
}
using (MemoryStream ms = new MemoryStream())
{
using (Bitmap bmp = new Bitmap(40, 40))
{
using (Graphics g = Graphics.FromImage(bmp))
{
using (Brush brush = new SolidBrush(logInfo.Color))
{
g.FillRectangle(brush, 0, 0, 40, 40);
}
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
// go to the begining of the picture
ms.Seek(0, SeekOrigin.Begin);
Novacode.Image img = doc.AddImage(ms); // Create image.
Novacode.Picture pic1 = img.CreatePicture(); // Create picture.
row.Cells[column++].Paragraphs[0].AppendPicture(pic1);
}
}
}
// write log row into the doc
row.Cells[column++].Paragraphs[0].Append(logInfo.SysEventMsg != null ? logInfo.SysEventMsg : "").FontSize(9).Font(font);
row.Cells[column++].Paragraphs[0].Append(logInfo.Imei != null ? logInfo.Imei : "").FontSize(9).Font(font);
row.Cells[column++].Paragraphs[0].Append(logInfo.HumanMsg != null ? logInfo.HumanMsg : "").FontSize(9).Font(font);
row.Cells[column - 1].Paragraphs[0].Bold();
row.Cells[column++].Paragraphs[0].Append(logInfo.Cmd != null ? logInfo.Cmd : "").FontSize(9).Font(font);
row.Cells[column++].Paragraphs[0].Append(logInfo.Timecmd.ToString("dd.MM.yyyy HH:mm:ss")).FontSize(8).Font(font);
row.Cells[column - 1].Paragraphs[0].Color(Color.FromArgb(66, 66, 66));
}
private void ChangeFont()
{
foreach (ToolWindow tw in this.radDock1.DockWindows.ToolWindows)
//foreach (Control dw in documentTabStrip1.Controls)
{
//tw.TabStripItem.Font = f;
tw.TabStripItem.Image = resources.adduserwhite1;
//if (iconThemeType == IconType.CLASSIC)
{
if (tw.TabStripItem.TabPanel == tabLive)
tw.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_live, 25, 25);
else if (tw.TabStripItem.TabPanel == tabGeo)
tw.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_geofence, 25, 25);
else if (tw.TabStripItem.TabPanel == tabHistory)
tw.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_history, 25, 25);
else if (tw.TabStripItem.TabPanel == tabReport)
tw.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_reports, 25, 25);
else if (tw.TabStripItem.TabPanel == tabSMS)
tw.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_sms, 25, 25);
else if (tw.TabStripItem.TabPanel == tabVoice)
tw.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_voice, 25, 25);
else if (tw.TabStripItem.TabPanel == tabNewRadio)
tw.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_voice, 25, 25);
else if (tw.TabStripItem.TabPanel == tabTicketing)
tw.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_ticketing, 25, 25);
else if (tw.TabStripItem.TabPanel == tabTelem)
tw.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_telemetry, 25, 25);
else if (tw.TabStripItem.TabPanel == tabAlerts)
tw.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_alert, 25, 25);
else if (tw.Tag != null && tw.Tag is Tabs)
{
if (tw.Tag == Tabs.LIVE)
tw.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_live, 25, 25);
else if (tw.Tag == Tabs.HISTORY)
tw.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_history, 25, 25);
else if (tw.Tag == Tabs.GEOFENCE)
tw.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_geofence, 25, 25);
else if (tw.Tag == Tabs.REPORTS)
tw.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_reports, 25, 25);
else if (tw.Tag == Tabs.TEXT)
tw.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_sms, 25, 25);
else if (tw.Tag == Tabs.TICKETING)
tw.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_ticketing, 25, 25);
else if (tw.Tag == Tabs.VOICE)
tw.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_voice, 25, 25);
else if (tw.Tag == Tabs.RADIO)
tw.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_voice, 25, 25);
else if (tw.Tag == Tabs.SYSTEM)
tw.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_system, 25, 25);
else if (tw.Tag == Tabs.TELEMETRY)
tw.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_telemetry, 25, 25);
else if (tw.Tag == Tabs.ALERTS)
tw.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_alert, 25, 25);
else
tw.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_system, 25, 25);
}
else
tw.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_system, 25, 25);
tw.TabStripItem.Image.RotateFlip(RotateFlipType.Rotate90FlipNone);
}
/*
else if (iconThemeType == IconType.PIN)
{
if (tw.TabStripItem.TabPanel == tabLive) tw.TabStripItem.Image = Utils.ScaleImage(resources.Live_mini_ico_pin, 28, 28);
else if (tw.TabStripItem.TabPanel == tabGeo) tw.TabStripItem.Image = Utils.ScaleImage(resources.Geo_mini_ico_pin, 28, 28);
else if (tw.TabStripItem.TabPanel == tabHistory) tw.TabStripItem.Image = Utils.ScaleImage(resources.Hist_mini_ico_pin, 28, 28);
else if (tw.TabStripItem.TabPanel == tabReport) tw.TabStripItem.Image = Utils.ScaleImage(resources.Report_mini_ico_pin, 28, 28);
else if (tw.TabStripItem.TabPanel == tabSMS) tw.TabStripItem.Image = Utils.ScaleImage(resources.SMS_mini_ico_pin, 28, 28);
else if (tw.TabStripItem.TabPanel == tabVoice) tw.TabStripItem.Image = Utils.ScaleImage(resources.Voice_mini_ico_pin, 28, 28);
else if (tw.TabStripItem.TabPanel == tabTelem) tw.TabStripItem.Image = Utils.ScaleImage(resources.Telem_mini_ico_pin, 28, 28);
else tw.TabStripItem.Image = Utils.ScaleImage(resources.Sys_mini_ico_pin, 28, 28);
}
*/
//tw.TabStripItem.ImageAlignment = ContentAlignment.TopLeft;
//dw.TabStripItem.FlipText = true;
//tw.TabStripItem.TextAlignment = ContentAlignment.MiddleCenter;
//tw.TabStripItem.TextImageRelation = TextImageRelation.ImageBeforeText;
//tw.TabStripItem.TextImageRelation = TextImageRelation.TextBeforeImage;
}
}
private void documentTabStrip1_ControlAdded(object sender, ControlEventArgs e)
{
ChangeFont();
}
//private bool skipedAlertsFirstTime = true;
private DockWindow oldDockWindow = null;
private void radDock1_ActiveWindowChanging(object sender, DockWindowCancelEventArgs e)
{
// if alert was clicked I should cancel the tab change
if (e.NewWindow.Tag != null && e.NewWindow.Tag is Tabs)
{
// allow the alerts windows to be displayed only if not first time
// this event has been raised
if (e.NewWindow.Tag == Tabs.ALERTS && !isMainForm2Loaded)
{
// set the image for the alerts tab
e.NewWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_alert, 25, 25);
e.NewWindow.TabStripItem.Image.RotateFlip(RotateFlipType.Rotate90FlipNone);
// cancel this event in order to not change the tab
e.Cancel = true;
return;
}
else if (e.NewWindow.Tag == Tabs.ALERTS)// && !skipedAlertsFirstTime)
{
//skipedAlertsFirstTime = true;
// cancel this event in order to not change the tab
e.Cancel = true;
return;
}
}
if (e.OldWindow != null)
{
// reset the background icon for the previous tab
e.OldWindow.TabStripItem.BackColor = MainForm2.TabNormalColor;
if (e.OldWindow.TabStripItem.TabPanel == tabLive)
e.OldWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_live, 25, 25);
else if (e.OldWindow.TabStripItem.TabPanel == tabGeo)
e.OldWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_geofence, 25, 25);
else if (e.OldWindow.TabStripItem.TabPanel == tabHistory)
e.OldWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_history, 25, 25);
else if (e.OldWindow.TabStripItem.TabPanel == tabReport)
e.OldWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_reports, 25, 25);
else if (e.OldWindow.TabStripItem.TabPanel == tabSMS)
e.OldWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_sms, 25, 25);
else if (e.OldWindow.TabStripItem.TabPanel == tabVoice)
e.OldWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_voice, 25, 25);
else if (e.OldWindow.TabStripItem.TabPanel == tabNewRadio)
e.OldWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_voice, 25, 25);
else if (e.OldWindow.TabStripItem.TabPanel == tabTicketing)
e.OldWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_ticketing, 25, 25);
else if (e.OldWindow.TabStripItem.TabPanel == tabTelem)
e.OldWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_telemetry, 25, 25);
// change the image for the selected tab if the TAG is a Tabs object
else if (e.OldWindow.Tag != null && e.OldWindow.Tag is Tabs)
{
if (e.OldWindow.Tag == Tabs.LIVE)
e.OldWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_live, 25, 25);
else if (e.OldWindow.Tag == Tabs.HISTORY)
e.OldWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_history, 25, 25);
else if (e.OldWindow.Tag == Tabs.GEOFENCE)
e.OldWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_geofence, 25, 25);
else if (e.OldWindow.Tag == Tabs.REPORTS)
e.OldWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_reports, 25, 25);
else if (e.OldWindow.Tag == Tabs.TEXT)
e.OldWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_sms, 25, 25);
else if (e.OldWindow.Tag == Tabs.TICKETING)
e.OldWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_ticketing, 25, 25);
else if (e.OldWindow.Tag == Tabs.VOICE)
e.OldWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_voice, 25, 25);
else if (e.OldWindow.Tag == Tabs.RADIO)
e.OldWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_voice, 25, 25);
else if (e.OldWindow.Tag == Tabs.SYSTEM)
e.OldWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_system, 25, 25);
else if (e.OldWindow.Tag == Tabs.TELEMETRY)
e.OldWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_telemetry, 25, 25);
else if (e.OldWindow.Tag == Tabs.ALERTS)
e.OldWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_alert, 25, 25);
else
e.OldWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_system_b, 25, 25);
}
else if (e.OldWindow.TabStripItem.TabPanel == tabAlerts)
e.OldWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_alert, 25, 25);
else
e.OldWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_system, 25, 25);
// rotate the image 90 degrees clockwise
e.OldWindow.TabStripItem.Image.RotateFlip(RotateFlipType.Rotate90FlipNone);
}
if (e.NewWindow != null)
{
// change the background color of the tab
e.NewWindow.TabStripItem.BackColor = MainForm2.TabSelectedColor;// Color.FromArgb(79, 139, 237);
// change the image for the selected tab
if (e.NewWindow.TabStripItem.TabPanel == tabLive)
e.NewWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_live_b, 25, 25);
else if (e.NewWindow.TabStripItem.TabPanel == tabGeo)
e.NewWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_geofence_b, 25, 25);
else if (e.NewWindow.TabStripItem.TabPanel == tabHistory)
e.NewWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_history_b, 25, 25);
else if (e.NewWindow.TabStripItem.TabPanel == tabReport)
e.NewWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_reports_b, 25, 25);
else if (e.NewWindow.TabStripItem.TabPanel == tabSMS)
e.NewWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_sms_b, 25, 25);
else if (e.NewWindow.TabStripItem.TabPanel == tabVoice)
e.NewWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_voice_b, 25, 25);
else if (e.NewWindow.TabStripItem.TabPanel == tabNewRadio)
e.NewWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_voice_b, 25, 25);
else if (e.NewWindow.TabStripItem.TabPanel == tabTicketing)
e.NewWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_ticketing_b, 25, 25);
else if (e.NewWindow.TabStripItem.TabPanel == tabTelem)
e.NewWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_telemetry_b, 25, 25);
else if (e.NewWindow.Tag != null && e.OldWindow != null && e.OldWindow.Tag is Tabs)
{
// change the image for the selected tab if the TAG is a Tabs object
if (e.NewWindow.Tag == Tabs.LIVE)
e.NewWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_live_b, 25, 25);
else if (e.NewWindow.Tag == Tabs.HISTORY)
e.NewWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_history_b, 25, 25);
else if (e.NewWindow.Tag == Tabs.GEOFENCE)
e.NewWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_geofence_b, 25, 25);
else if (e.NewWindow.Tag == Tabs.REPORTS)
e.NewWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_reports_b, 25, 25);
else if (e.NewWindow.Tag == Tabs.TEXT)
e.NewWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_sms_b, 25, 25);
else if (e.NewWindow.Tag == Tabs.TICKETING)
e.NewWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_ticketing_b, 25, 25);
else if (e.NewWindow.Tag == Tabs.VOICE)
e.NewWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_voice_b, 25, 25);
else if (e.NewWindow.Tag == Tabs.RADIO)
e.NewWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_voice_b, 25, 25);
else if (e.NewWindow.Tag == Tabs.SYSTEM)
e.NewWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_system_b, 25, 25);
else if (e.NewWindow.Tag == Tabs.TELEMETRY)
e.NewWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_telemetry_b, 25, 25);
else if (e.NewWindow.Tag == Tabs.ALERTS)
e.NewWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_alert_b, 25, 25);
else
e.NewWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_system_b, 25, 25);
}
else if (e.NewWindow.TabStripItem.TabPanel == tabAlerts)
e.NewWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_alert_b, 25, 25);
else
e.NewWindow.TabStripItem.Image = SafeMobileLib.Utils.ScaleImage(resources.t_system_b, 25, 25);
// rotate the image 90 degrees clockwise
e.NewWindow.TabStripItem.Image.RotateFlip(RotateFlipType.Rotate90FlipNone);
}
// reset font familiy for both tabs
if( e.OldWindow != null)
e.OldWindow.TabStripItem.Font = new Font(
new FontFamily("Segoe UI"),
9,
FontStyle.Regular,
GraphicsUnit.Pixel);
if (e.NewWindow != null)
e.NewWindow.TabStripItem.Font
= new Font(
new FontFamily("Segoe UI"),
9,
FontStyle.Regular,
GraphicsUnit.Pixel);
// save old dock window
oldDockWindow = e.OldWindow;
}
public static void SafeConvertStringToDouble(String slat, String slng, out Double lat, out Double lng)
{
string tmpLat = slat;
String tmpLng = slng;
string decimalSeparator = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
if ((decimalSeparator == ",") && (tmpLat.Contains(".")))
{
tmpLat = tmpLat.Replace(".", ",");
tmpLng = tmpLng.Replace(".", ",");
}
else if ((decimalSeparator == ".") && (tmpLat.Contains(",")))
{
tmpLat = tmpLat.Replace(",", ".");
tmpLng = tmpLng.Replace(",", ".");
}
try
{
lat = Convert.ToDouble(tmpLat);
lng = Convert.ToDouble(tmpLng);
lat = Math.Round(lat, 5);
lng = Math.Round(lng, 5);
}
catch
{
lat = 44.41905;
lng = 26.09876;
SM.Debug("Error load LAT, LNG Start force default LatStart = 44.41905 LngStart = 26.09876");
SM.Debug("slat:" + slat + " slng:" + slng);
}
}
private void radDock1_ActiveWindowChanged(object sender, DockWindowEventArgs e)
{
//ChangeFont();
//e.DockWindow.BackColor = Color.FromArgb(79, 139, 237);
SafeMobileLib.Utils.WriteLine("ACTIVE WINDOW : " + e.DockWindow.Text, ConsoleColor.Red);
e.DockWindow.TabStripItem.Font = new Font(
new FontFamily("Segoe UI"),
9,
FontStyle.Regular,
GraphicsUnit.Pixel);
if (oldDockWindow != null)
oldDockWindow.TabStripItem.Font = new Font(
new FontFamily("Segoe UI"),
9,
FontStyle.Regular,
GraphicsUnit.Pixel);
//e.DockWindow.TabStripItem.Image = Utils.ScaleImage(resources.t_history_b, 25, 25);
/*
foreach (ToolWindow tw in this.radDock1.DockWindows.ToolWindows)
{
if (e.DockWindow.TabStripItem.TabPanel == tabLive)
tw.TabStripItem.Image = Utils.ScaleImage(resources.t_live, 25, 25);
else if (e.DockWindow.TabStripItem.TabPanel == tabGeo)
tw.TabStripItem.Image = Utils.ScaleImage(resources.t_geofence, 25, 25);
else if (e.DockWindow.TabStripItem.TabPanel == tabHistory)
tw.TabStripItem.Image = Utils.ScaleImage(resources.t_history, 25, 25);
else if (e.DockWindow.TabStripItem.TabPanel == tabReport)
tw.TabStripItem.Image = Utils.ScaleImage(resources.t_reports, 25, 25);
else if (e.DockWindow.TabStripItem.TabPanel == tabSMS)
tw.TabStripItem.Image = Utils.ScaleImage(resources.t_sms, 25, 25);
else if (e.DockWindow.TabStripItem.TabPanel == tabVoice)
tw.TabStripItem.Image = Utils.ScaleImage(resources.t_voice, 25, 25);
else if (e.DockWindow.TabStripItem.TabPanel == tabTicketing)
tw.TabStripItem.Image = Utils.ScaleImage(resources.t_ticketing, 25, 25);
else if (e.DockWindow.TabStripItem.TabPanel == tabTelem)
tw.TabStripItem.Image = Utils.ScaleImage(resources.t_telemetry, 25, 25);
else
tw.TabStripItem.Image = Utils.ScaleImage(resources.t_system, 25, 25);
tw.TabStripItem.Image.RotateFlip(RotateFlipType.Rotate90FlipNone);
}
*/
}
/// <summary>
/// filter system events based on the selected types
/// </summary>
private void rcbDropDownEventType_ItemCheckedChanged(object sender, RadCheckedListDataItemEventArgs e)
{
// clear all statuses filters
SystemGridView.FilterDescriptors.Remove("SysEventMsg");
// add filters only if selected event types
if (rcbDropDownEventType.CheckedItems.Count > 0)
{
// Create a composite file descriptor with OR logic
CompositeFilterDescriptor statusDescriptor = new CompositeFilterDescriptor();
statusDescriptor.LogicalOperator = FilterLogicalOperator.Or;
// for each selected status add a custom filedescroptor
foreach (RadListDataItem item in rcbDropDownEventType.CheckedItems)
{
statusDescriptor.FilterDescriptors.Add(new FilterDescriptor("SysEventMsg", FilterOperator.Contains, item.Text.ToString()));
}
// add filter
this.SystemGridView.FilterDescriptors.Add(statusDescriptor);
}
}
private void rcbDropDropDownUnitEvent_ItemCheckedChanged(object sender, RadCheckedListDataItemEventArgs e)
{
// clear all priority filters
SystemGridView.FilterDescriptors.Remove("imei");
// add filters only if selected users
if (rcbDropDropDownUnitEvent.CheckedItems.Count > 0)
{
// create a composite file descriptor with OR logic
CompositeFilterDescriptor fileDescriptor = new CompositeFilterDescriptor();
fileDescriptor.LogicalOperator = FilterLogicalOperator.Or;
// for each selected imei add a custom fildescriptor
foreach (RadListDataItem item in rcbDropDropDownUnitEvent.CheckedItems)
{
fileDescriptor.FilterDescriptors.Add(new FilterDescriptor("imei", FilterOperator.Contains, item.Text.ToString()));
}
// add filter
this.SystemGridView.FilterDescriptors.Add(fileDescriptor);
}
}
/// <summary>
/// Filter System Events on them start time [this value can be reset to none]
/// </summary>
/// <param name="sender">DateTime Picker which changed it's value</param>
private void rdpStartTime_ValueChanged(object sender, EventArgs e)
{
if (rdpStartTime.Value > new DateTime(2015, 1, 1))
rdpEndTime.MinDate = rdpStartTime.Value;
// remove file descriptor for Start time
SystemGridView.FilterDescriptors.Remove("timecmd");
// add only if date is older than 2015
if (rdpStartTime.Value > new DateTime(2015, 1, 1))
{
FilterDescriptor startFileDescriptor = new FilterDescriptor("timecmd", FilterOperator.IsGreaterThanOrEqualTo, rdpStartTime.Value);
this.SystemGridView.FilterDescriptors.Add(startFileDescriptor);
}
else
// remove file descriptor for Start time
SystemGridView.FilterDescriptors.Remove("timecmd");
}
/// <summary>
/// Filter System Events based on them end time [this value can be reset to none]
/// </summary>
/// <param name="sender">DateTime Picker which changed it's value</param>
private void rdpEndTime_ValueChanged(object sender, EventArgs e)
{
// remove file descriptor for Start time
SystemGridView.FilterDescriptors.Remove("timecmd");
// add only if date is older than minimum date
if (rdpEndTime.Value > rdpEndTime.MinDate)
{
FilterDescriptor startFileDescriptor = new FilterDescriptor("timecmd", FilterOperator.IsLessThanOrEqualTo, rdpEndTime.Value);
this.SystemGridView.FilterDescriptors.Add(startFileDescriptor);
}
else
// remove file descriptor for Start time
SystemGridView.FilterDescriptors.Remove("timecmd");
}
/// <summary>
/// Reset start and end DateTime Picker values in order to reset the filter on
/// Start and End time
/// </summary>
/// <param name="sender">PictureBox for which datetime should be reset</param>
private void pbClearTime_Click(object sender, EventArgs e)
{
// clear start time
if ((PictureBox)sender == pbClearStartTime)
rdpStartTime.SetToNullValue();
// clear end time
if ((PictureBox)sender == pbClearEndTime)
rdpEndTime.SetToNullValue();
}
string filterName = "none";
/// <summary>
/// Filter the system events grid when a picture box is clicked
/// The filtering is done first ASC, then DESC, and finaly it is removed is
/// it was selected.
/// </summary>
/// <param name="sender">Picture box corresponding for the filter needed</param>
private Image themelFilterUser_Image = Utils.ChangeColor(resources.s_filter_user, MainForm2.ButtonColor);
private Image themelFilterType_Image = Utils.ChangeColor(resources.s_filter_type, MainForm2.ButtonColor);
private Image themelFilterDirection_Image = Utils.ChangeColor(resources.s_filter_direction, MainForm2.ButtonColor);
private void pbFilter_Click(object sender, EventArgs e)
{
// set all images to gray
pbFilterDirection.Image = resources.s_filter_direction_grey;
pbFilterType.Image = resources.s_filter_type_grey;
pbFilterUnit.Image = resources.s_filter_user_grey;
filterName = "none";
ListSortDirection sortDirection = ListSortDirection.Ascending;
if ((PictureBox)sender == pbFilterUnit)
{
filterName = "imei";
// check to see if it's the same filter
if (SystemGridView.GroupDescriptors.Count > 0 &&
SystemGridView.GroupDescriptors[0].Expression.Contains(filterName)
&& SystemGridView.GroupDescriptors[0].Expression.Contains("DESC"))
// do not change the filter image
filterName = "none";
else
pbFilterUnit.Image = themelFilterUser_Image;
}
else if ((PictureBox)sender == pbFilterType)
{
filterName = "SysEventMsg";
// check to see if it's the same filter
if (SystemGridView.GroupDescriptors.Count > 0 &&
SystemGridView.GroupDescriptors[0].Expression.Contains(filterName)
&& SystemGridView.GroupDescriptors[0].Expression.Contains("DESC"))
// do not change the filter image
filterName = "none";
else
pbFilterType.Image = themelFilterType_Image;
}
else if ((PictureBox)sender == pbFilterDirection)
{
filterName = "direct";
// check to see if it's the same filter
if (SystemGridView.GroupDescriptors.Count > 0 &&
SystemGridView.GroupDescriptors[0].Expression.Contains(filterName)
&& SystemGridView.GroupDescriptors[0].Expression.Contains("DESC"))
// do not change the filter image
filterName = "none";
else
pbFilterDirection.Image = themelFilterDirection_Image;
}
if (SystemGridView.GroupDescriptors.Count > 0 &&
SystemGridView.GroupDescriptors[0].Expression.Contains(filterName))
{
GroupDescriptor gd = SystemGridView.GroupDescriptors[0];
sortDirection = gd.Expression.Contains("ASC") ? ListSortDirection.Descending : ListSortDirection.Ascending;
// clear previous filters
SystemGridView.GroupDescriptors.Clear();
if (!filterName.Equals("none"))
{
GroupDescriptor groupDescriptor = new GroupDescriptor(new SortDescriptor[] { new SortDescriptor(filterName, sortDirection) });
SystemGridView.GroupDescriptors.Add(groupDescriptor);
}
}
else
{
// clear previous filters
SystemGridView.GroupDescriptors.Clear();
if (!filterName.Equals("none"))
{
GroupDescriptor groupDescriptor = new GroupDescriptor(new SortDescriptor[] { new SortDescriptor(filterName, sortDirection) });
SystemGridView.GroupDescriptors.Add(groupDescriptor);
}
}
// force refresh of grid
SystemGridView.DataSource = null;
SystemGridView.DataSource = startList;
pbFilterDirection.Tag = pbFilterType.Tag = pbFilterUnit.Tag = "disabled";
((PictureBox)sender).Tag = "enabled";
}
/// <summary>
/// Format the header for the groups depending on the value
/// that was used
/// </summary>
private void SystemGridView_GroupSummaryEvaluate(object sender, GroupSummaryEvaluationEventArgs e)
{
try
{
// get the count portion
string suff = String.Concat(" (", e.Group.ItemCount.ToString(), ")");
// set name for incoming and outgoing
if (filterName.Equals("direct") && e.Group.Header.Equals("1"))
e.FormatString = "Incoming ".ToUpper() + suff;
else if (filterName.Equals("direct") && e.Group.Header.Equals("0"))
e.FormatString = "Outgoing ".ToUpper() + suff;
// convert to upper case
e.FormatString = e.FormatString.ToUpper();
// remove the filter name
if (e.FormatString.Contains(":"))
{
e.FormatString = e.FormatString.Replace("{0}:", "");
}
// add the count portion if not exists
if (!e.FormatString.EndsWith(suff))
{
e.FormatString = String.Concat(e.FormatString, suff);
}
}
catch (Exception ex)
{
SM.Debug("Erorr on GroupSummaryEvaluate" + ex.ToString());
}
}
/// <summary>
/// Prevent or enable the grid to auto refresh each time an event is generated
/// </summary>
private void rcbAutoRefresh_ToggleStateChanged(object sender, StateChangedEventArgs args)
{
btForceRefresh.Visible = !rcbAutoRefresh.Checked;
}
/// <summary>
/// Intercept when a document window had changed it's state, on double click
/// or drag/drop, and set that it is not allowed to close/hide it
/// </summary>
private void radDock2_DockStateChanged(object sender, DockWindowEventArgs e)
{
e.DockWindow.ToolCaptionButtons = ToolStripCaptionButtons.None;
e.DockWindow.AllowedDockState = AllowedDockState.Docked | AllowedDockState.TabbedDocument;
}
/// <summary>
/// Event handler for when the left tab panel needs to be docked/transfor in floating state.
/// This will cancel this event in order to prevent the stupid case with hiding the dock window
/// </summary>
private void radDock2_DockStateChanging(object sender, DockStateChangingEventArgs e)
{
e.Cancel = true;
}
public delegate void CallStatusChanged(string unitname, bool inCall, Boolean fromField);
public event CallStatusChanged OnCallStatusChanged;
internal void RaiseOnCallStatusChangedEvent(string unitname, bool inCall, Boolean fromField)
{
CallStatusChanged handler = OnCallStatusChanged;
if (handler != null)
{
// We have listeners so we can raise the event
handler(unitname, inCall, fromField);
}
}
public delegate void CallStatusHangChanged(string unitname, bool inCall, Boolean fromField, string GwPlusRadio);
public event CallStatusHangChanged OnCallStatusHangChanged;
public delegate void RadioGatewayStatusChanged(string GatewayAndRadioGateway, bool active);
public event RadioGatewayStatusChanged OnRadioGatewayStatusChanged;
/// <summary>
/// Change background color for the row according to its state and theme
/// </summary>
private void SystemGridView_RowFormatting(object sender, RowFormattingEventArgs e)
{
e.RowElement.DrawFill = true;
e.RowElement.NumberOfColors = 1;
if (e.RowElement.IsSelected)
e.RowElement.BackColor = MainForm2.GridSelectedRow;
else
e.RowElement.BackColor = (e.RowElement.RowInfo.Index % 2 == 0 ? Color.White : MainForm2.GridAlternateRow);
}
#region CHANGE TABS BACKGROUND
private DockWindow oldDockWindow2 = null;
private void radDock2_ActiveWindowChanging(object sender, DockWindowCancelEventArgs e)
{
// reset the background icon for the previous tab
e.OldWindow.TabStripItem.BackColor = Color.White;
e.OldWindow.TabStripItem.DrawFill = true;
e.OldWindow.TabStripItem.NumberOfColors = 1;
// reset the background for the new window
e.NewWindow.TabStripItem.DrawFill = true;
e.NewWindow.TabStripItem.NumberOfColors = 1;
e.NewWindow.TabStripItem.BackColor = MainForm2.TabSelectedColor;
// save old dock window
oldDockWindow2 = e.OldWindow;
}
private void radDock2_ActiveWindowChanged(object sender, DockWindowEventArgs e)
{
// reset the background icon for the previous tab
oldDockWindow2.TabStripItem.BackColor = Color.White;
oldDockWindow2.TabStripItem.DrawFill = true;
oldDockWindow2.TabStripItem.NumberOfColors = 1;
e.DockWindow.TabStripItem.DrawFill = true;
e.DockWindow.TabStripItem.NumberOfColors = 1;
e.DockWindow.TabStripItem.BackColor = MainForm2.TabSelectedColor;
}
#endregion
public void DisplayToast(String captionText, String contentText)
{
// hide alert if already opened
if (desktopAlertFeedback.IsDisposed || desktopAlertFeedback.IsDisposing)
desktopAlertFeedback.Hide();
desktopAlertFeedback.CaptionText = captionText;
desktopAlertFeedback.ContentText = contentText;
desktopAlertFeedback.Show();
}
private void MainForm2_Shown(object sender, EventArgs e)
{
// update the title of the sms tab
UpdateUnreadMessagesNumber();
// update the title of the alerts tab
UpdateNumberOfUnAckAlerts();
}
/// <summary>
/// Update the number of unread messages and then update this number
/// in the sms tab name
/// </summary>
public void UpdateUnreadMessagesNumber()
{
// get number of unread SMS
nrOfUnreadMessages = smdbObj.GetNumberOfUnreadMessages(userIDX);
// update the title of the sms tab
tabSMS.Text = String.Format("{0} ({1})", returnLNGString("tabSMS"), nrOfUnreadMessages);
}
private DBalarmManager dbalm;
public async void UpdateNumberOfUnAckAlerts()
{
Utils.WriteLine("Start Update Number async");
if (dbalm == null)
dbalm = new DBalarmManager(MainForm2.cfg.DB_IP, MainForm2.cfg.DB_schema, MainForm2.cfg.DB_user, MainForm2.cfg.DB_passwd, MainForm2.cfg.DB_port);
nrOfUnreadAlerts = await Task.Factory.StartNew(() => (dbalm.Get_nonACK_alarms_count(userIDX)));
// update the title of the alerts tab
tabAlerts.Text = String.Format("{0} ({1})", returnLNGString("tabAlerts"), nrOfUnreadAlerts);
Utils.WriteLine("End Update Number async");
}
private void pbGrouping_MouseEnter(object sender, EventArgs e)
{
PictureBox pbSender = (PictureBox)sender;
String toolTipTitle = "";
String toolTipText = "";
if (pbSender == pbFilterDirection)
{
toolTipTitle = MainForm2.returnLNGString("eventDirGrp");
toolTipText = String.Format(MainForm2.returnLNGString("eventDirGrpDet"));
}
else if (pbSender == pbFilterType)
{
toolTipTitle = MainForm2.returnLNGString("eventTypeGrp");
toolTipText = String.Format(MainForm2.returnLNGString("eventTypeGrpDet"));
}
else if (pbSender == pbFilterUnit)
{
toolTipTitle = MainForm2.returnLNGString("eventSourceGrp");
toolTipText = String.Format(MainForm2.returnLNGString("eventSourceGrpDet"));
}
toolTipHelp.ToolTipTitle = toolTipTitle + ": " + (pbSender.Tag.Equals("enabled") ? MainForm2.returnLNGString("active") : MainForm2.returnLNGString("inactive"));
toolTipHelp.Show(
String.Format(toolTipText), pbSender, 150000);
}
private void pbGrouping_MouseLeave(object sender, EventArgs e)
{
toolTipHelp.Hide((PictureBox)sender);
}
/// <summary>
/// Prevent the rad dock to enter in Alerts tab by selecting the live tab
/// </summary>
private void tabAlerts_Enter(object sender, EventArgs e)
{
ToolWindow toolWindow = (tabLive != null) ? tabLive : tabSystem;
radDock1.ActivateWindow(toolWindow);
}
/// <summary>
/// Intercept the change on the selected tab strip item and verify if Alerts tab is
/// the new one selected
/// </summary>
private void documentTabStrip1_SelectedIndexChanging(object sender, TabStripPanelSelectedIndexChangingEventArgs args)
{
DocumentWindow newWindow = args.NewTabPanel as DocumentWindow;
// check if alerts tab is the new window which will be selected
if (newWindow != null && newWindow.Text.StartsWith("Alerts"))
// cancel the event to prevent entering in the alerts tab
args.Cancel = true;
}
/// <summary>
/// Intercept the mouse click on the tabStrip in order to open the alerts window
/// This must be done because the SelectedIndexChanging is triggered even when the
/// a tab is undocked
/// </summary>
private void documentTabStrip1_MouseClick(object sender, MouseEventArgs e)
{
//tabSize = new Size(65, 50);
// detect where the alerts tab item is placed
int startY = 0;
foreach (TabPanel panel in documentTabStrip1.TabPanels)
{
// I found the alerts tab starting at startY position
//if(panel.Text.StartsWith("Alerts"))
if (panel.Text.StartsWith(returnLNGString("tabAlerts")))
{
// verify if the mouse in at the alerts position
if (e.Y > startY && e.Y < startY + 65 && e.X > 0 && e.X < 54)
// trigger alert event
AlarmTracking_Click(sender, EventArgs.Empty);
}
// move to the new item start position
startY += 65;
}
}
/// <summary>
/// Prevent display of the context menu fost system grid
/// </summary>
private void SystemGridView_ContextMenuOpening(object sender, ContextMenuOpeningEventArgs e)
{
e.Cancel = true;
}
public static Image GetImage(String key)
{
if (imagesDictionary.ContainsKey(key))
return imagesDictionary[key];
return resources.classic_unknown;
}
public static String GetIconPathForUnit(String unitName)
{
String iconPath = "";
if ((Vehicle)MainForm2.vehicleHT[unitName] != null)
{
Car crtCar = ((Car)MainForm2.carlist[((Vehicle)MainForm2.vehicleHT[unitName])?.IconID%10000]);
if (crtCar == null)
{
Utils.WriteLine("nullllll", ConsoleColor.Cyan);
return "unknown";
}
iconPath = "";
iconPath = crtCar.listFilePath;
}
return iconPath;
}
public static String GetMapPathForUnit(String unitName)
{
String iconPath = "";
if ((Vehicle)MainForm2.vehicleHT[unitName] != null)
{
Car crtCar = ((Car)MainForm2.carlist[((Vehicle)MainForm2.vehicleHT[unitName])?.IconID%10000]);
if (crtCar == null)
{
Utils.WriteLine("nullllll", ConsoleColor.Cyan);
return "unknown";
}
iconPath = "";
iconPath = crtCar.listFilePath;
}
return iconPath;
}
public void KickOutUser()
{
this.Invoke((MethodInvoker)delegate
{
string message = "";
switch (MainForm2.radioType)
{
case RADIOTYPE.CONECTPLUS:
case RADIOTYPE.TETRA:
case RADIOTYPE.MOTO:
case RADIOTYPE.REPEATER_TRBO:
message = $"Please register your copy of SafeDispatch using the Administrative Module.\n Your IP address is: {Login.IPaddress}";
break;
case RADIOTYPE.HYT:
message = $"Please register your copy of SafeSyt using the Administrative Module.\n Your IP address is: {Login.IPaddress} ";
break;
case RADIOTYPE.HARRIS:
((RadLabel)RadMessageBox.Instance.Controls[1]).LabelElement.ForeColor = MainForm2.HarTextColor;
message = $"Please register your copy of Vision using the Administrative Module.\n Your IP address is: {Login.IPaddress}";
break;
case RADIOTYPE.ATLAS:
((RadLabel)RadMessageBox.Instance.Controls[1]).LabelElement.ForeColor = MainForm2.HarTextColor;
message = $"Please register your copy of ATL25 using the Administrative Module.\n Your IP address is: {Login.IPaddress}";
break;
case RADIOTYPE.SIMOCO:
((RadLabel)RadMessageBox.Instance.Controls[1]).LabelElement.ForeColor = MainForm2.HarTextColor;
message = $"Please register your copy of Simoco using the Administrative Module.\n Your IP address is: {Login.IPaddress}";
break;
case RADIOTYPE.EXCERA:
((RadLabel)RadMessageBox.Instance.Controls[1]).LabelElement.ForeColor = MainForm2.HarTextColor;
message = $"Please register your copy of Excera using the Administrative Module.\n Your IP address is: {Login.IPaddress}";
break;
}
if( !string.IsNullOrEmpty(message) )
RadMessageBox.Show(message, "Info", MessageBoxButtons.OK, RadMessageIcon.Info);
System.Windows.Forms.Application.Exit();
});
}
#region Sip Class Event Handlers
internal static bool sipStatus = false;
private void _sipClient_RegistrationStateChanged(object sender, SipComponent.RegistrationStateChangedEventArgs e)
{
ConsoleColor msgColor = (e.Reason == SipComponent.RegistrationStatus.Registered || e.Reason == SipComponent.RegistrationStatus.UnregisteredAtRequest) ?
ConsoleColor.Green :
ConsoleColor.Red;
Utils.WriteLine($"Safedispatch sip id {e.RegisteredId} registration status is {e.Reason.ToString()}", msgColor);
sipStatus = (e.Reason == SipComponent.RegistrationStatus.Registered) ? true : false;
RadioTabControl?.UpdateSipStatus(sipStatus);
// In case of error in IndependentSoft library, reinitialize the class
if (e.Reason == SipComponent.RegistrationStatus.SocketError)
{
StopSipClass(_sipClient, false);
Thread.Sleep(5000);
_sipClient = CreateSipClass(_sipServerIP, _sipServerPort, 5060, userSipId.ToString(), "safemobile123", 30, 200, 10000, _socketIOPort);
OnSipClassInitialized();
}
}
private void _sipClient_InviteReceived(object sender, SipComponent.InviteReceivedArgs e)
{
if (VoiceTabStarted)
{
// Respond
_sipClient.AcceptInvite(e.SipIDinDialogWith);
}
else
{
// Decline
_sipClient.Decline(e.SipIDinDialogWith);
Utils.WriteLine($"Declined the call from sip id {e.SipIDinDialogWith} because voice tab not initialized", ConsoleColor.Green);
}
}
private void _sipClient_SmsOnSipReceived(object sender, SipComponent.SmsReceivedEventsArgs e)
{
// A sip sms received from Asterisk
// put the message on mBus
// Generate string command to send on message bus
// #Opcode#remoteRadioId#message#hyt#dispatcherID#
//string toTrans = string.Format("#{0}#{1}#{2}#hyt#{3}#",
// (int)MessageBusCmds.SMSReceived, e.SipIDinDialogWith, e.Message, MainForm2.userIDX);
int senderSipID = int.Parse(e.SipIDinDialogWith);
string toTrans = string.Format("#{0}#{1}#{2}#hyt#{3}#",
(int)MessageBusCmds.SMSReceived, ContactLinxFromSipID(senderSipID)?.Id ?? senderSipID, e.Message, userIDX);
// Send on Mbus
Send_UDP_cmd(toTrans, 0, 0);
}
private void _sipClient_ExceraEmergencyReceived(object sender, SipComponent.SipEventArgs e)
{
// send emergency cmd on Mbus
// #msgLen#seqID#Opcode#remoteRadioId#emergecyType#
// Generate string command for message bus
// #seqID#Opcode#remoteRadioId#emergecyType#
string seqID = DateTime.Now.GetSecondsLocalFromDT() + DateTime.Now.Ticks.ToString();
string toSend = $"#{seqID}#{(int)MessageBusCmds.RadioEmergencyReceived}#{e.SipIDinDialogWith}#{(int)EmergencyTypes.NORMAL}#";
Send_UDP_cmd_sent_withOutID(toSend);
}
private void SipClass_SmsOnSocketIOReceived(object sender, SipComponent.SocketIOSmsEventArgs e)
{
throw new NotImplementedException();
}
private void SipClass_SocketIOSmsAckReceived(object sender, SipComponent.SocketIoSmsAckEventArgs e)
{
throw new NotImplementedException();
}
#endregion
#region Methods for Sip
private Dispatcher.Sip.ISipComponent CreateSipClass(string sipServerIP, int sipServerPort, int localSipPort, string userName, string password, int registrationInterval,
int bufferMiliseconds, int requestTimeout, int socketIOPort)
{
//SipComponent.SipClientClassSD sipClass = new SipComponent.SipClientClass2(
// sipServerIP, // sip domain
// sipServerPort, // sip domain port
// localSipPort, // local sip port
// userName, // user name
// password, // password
// registrationInterval, // registration interval
// bufferMiliseconds, // buffer miliseconds
// requestTimeout, // request timeout
// socketIOPort // socketIO port
// );
//SipComponent.SipClientClass2 sipClass = new SipComponent.SipClientClass2(
// sipServerIP, // sip domain
// sipServerPort, // sip domain port
// localSipPort, // local sip port
// userName, // user name
// password, // password
// registrationInterval, // registration interval
// bufferMiliseconds, // buffer miliseconds
// requestTimeout, // request timeout
// socketIOPort, // socketIO port
// true // send Ars On and Off
// );
Dispatcher.Sip.ISipComponent sipClass = null;
#if LINX || LINXB
sipClass = new Dispatcher.Sip.LinxForSafeDispatch(
sipServerIP, // sip domain
sipServerPort, // sip domain port
localSipPort, // local sip port
userName, // user name
password, // password
registrationInterval, // registration interval
bufferMiliseconds, // buffer miliseconds
requestTimeout, // request timeout
socketIOPort // socketIO port
);
#endif
#if EXCERA
// Create excera class
sipClass = new Dispatcher.Sip.ExceraForSafeDispatch(
sipServerIP, // Excera repeater IP
sipServerPort, // Excera repeater sip ID
localSipPort, // local sip port
userName, // user name
//TalkGroups.Keys.ToList(), // IEnumerable collection of excera radio group ids
(from x in TalkGroups.Values select x.CPS_Id).ToList(), // IEnumerable collection of excera radio group cp_ids
registrationInterval, // registration interval
bufferMiliseconds, // buffer miliseconds
requestTimeout); // request timeout
#endif
AddSipEventHandlers(sipClass);
return sipClass;
}
private void StopSipClass(Dispatcher.Sip.ISipComponent sipClass, bool async)
{
RemoveEventHandlers(sipClass);
sipClass.Stop(async);
sipClass = null;
}
private void AddSipEventHandlers(Dispatcher.Sip.ISipComponent sipClass)
{
sipClass.InviteReceived += _sipClient_InviteReceived;
sipClass.RegistrationStateChanged += _sipClient_RegistrationStateChanged;
sipClass.SmsReceived += _sipClient_SmsOnSipReceived;
if (sipClass is Dispatcher.Sip.ExceraForSafeDispatch)
{
// Add event handler for Excera emergency
((Dispatcher.Sip.ExceraForSafeDispatch)sipClass).ExceraEmergencyReceived += _sipClient_ExceraEmergencyReceived;
}
if (sipClass is Dispatcher.Sip.ISocketIOComponent)
{
Dispatcher.Sip.ISocketIOComponent socketIoClass = (Dispatcher.Sip.ISocketIOComponent)sipClass;
socketIoClass.SocketIOSmsReceived += SipClass_SmsOnSocketIOReceived;
socketIoClass.SocketIOSmsAckReceived += SipClass_SocketIOSmsAckReceived;
}
}
private void RemoveEventHandlers(Dispatcher.Sip.ISipComponent sipClass)
{
sipClass.InviteReceived -= _sipClient_InviteReceived;
sipClass.RegistrationStateChanged -= _sipClient_RegistrationStateChanged;
sipClass.SmsReceived -= _sipClient_SmsOnSipReceived;
if (sipClass is Dispatcher.Sip.ExceraForSafeDispatch)
{
// Remove event handler for Excera emergency
((Dispatcher.Sip.ExceraForSafeDispatch)sipClass).ExceraEmergencyReceived -= _sipClient_ExceraEmergencyReceived;
}
if (sipClass is Dispatcher.Sip.ISocketIOComponent)
{
Dispatcher.Sip.ISocketIOComponent socketIoClass = (Dispatcher.Sip.ISocketIOComponent)sipClass;
socketIoClass.SocketIOSmsReceived -= SipClass_SmsOnSocketIOReceived;
socketIoClass.SocketIOSmsAckReceived -= SipClass_SocketIOSmsAckReceived;
}
}
/// <summary>
/// Adds an event handler for the DialogCreated event
/// <para>To use in RadioTab</para>
/// </summary>
/// <param name="eventHandler">The method that will be called when DialogCreated event is fired</param>
internal void AddDialogCreatedEventHandler(EventHandler<Dispatcher.Sip.SipDialogCreatedEventArgs> eventHandler)
{
if (_sipClient != null)
_sipClient.DialogCreated += eventHandler;
}
/// <summary>
/// Adds an event handler for the SdReceivesCallInit event
/// <para>To use in RadioTab</para>
/// </summary>
/// <param name="eventHandler"></param>
internal void AddSdReceivesSipCallInintEventHandler(EventHandler<Dispatcher.Sip.SdReceivedCallStatusEventArgs> eventHandler)
{
if (_sipClient != null)
_sipClient.SdReceivesCallInit += eventHandler;
}
/// <summary>
/// Adds an event handler for the SdCanSendVoice event
/// <para>To use in RadioTab</para>
/// </summary>
/// <param name="eventHandler"></param>
internal void AddSdCanSendSipVoiceEventHandler(EventHandler<Dispatcher.Sip.SdCanSendVoiceEventArgs> eventHandler)
{
if (_sipClient != null)
_sipClient.SdCanSendVoice += eventHandler;
}
/// <summary>
/// Adds an event handler for the VoiceReceived event
/// <para>To use in RadioTab</para>
/// </summary>
/// <param name="eventHandler">The method that will be called when VoiceReceived event is fired</param>
internal void AddVoiceReceivedEventHandler(EventHandler<Dispatcher.Sip.SipVoiceReceivedEventArgs> eventHandler)
{
if (_sipClient != null)
_sipClient.VoiceReceived += eventHandler;
}
/// <summary>
/// Adds an event handler for the DialogClosed event
/// <para>To use in RadioTab</para>
/// </summary>
/// <param name="eventHandler">The method that will be called when DialogClosed event is fired</param>
internal void AddDialogClosedEventHandler(EventHandler<Dispatcher.Sip.SipDialogClosedEventArgs> eventHandler)
{
if (_sipClient != null)
_sipClient.DialogClosed += eventHandler;
}
/// <summary>
/// Adds an event handler for the HangtimeEnded event
/// <para>To use in RadioTab</para>
/// </summary>
/// <param name="eventHandler">The method that will be called when HangtimeEnded event is fired</param>
internal void AddHangtimeEventHandler(EventHandler<Dispatcher.Sip.SdReceivedCallStatusEventArgs> eventHandler)
{
if (_sipClient != null)
_sipClient.SdReceivesStopPTT += eventHandler;
}
/// <summary>
/// Adds an event handler for the ErrorOnCreatingDialog event
/// <para>To use in RadioTab</para>
/// </summary>
/// <param name="eventHandler">The method will be called when ErrorOnCreatingDialog event is fired</param>
internal void AddErrorOnCreatingDialogEventHandler(EventHandler<SipComponent.ErrorEventArgs> eventHandler)
{
if (_sipClient != null)
_sipClient.ErrorOnCreatingDialog += eventHandler;
}
internal void AddSdCannotSendVoiceEventArgs(EventHandler<Dispatcher.Sip.SdCannotSendVoiceEventArgs> eventHandler)
{
if (_sipClient != null)
_sipClient.SdCannotSendVoice += eventHandler;
}
/// <summary>
/// Sends a Sip Invite to a linx sip id
/// </summary>
/// <param name="linxSipID">the linx sip id to call</param>
/// <param name="toGroup">true if the id is a linx sip group id, else false</param>
internal void SendCallRequest(string linxSipID, bool toGroup)
{
_sipClient.SendCallRequest(linxSipID, toGroup);
}
/// <summary>
/// Stops ptt to a sip device
/// </summary>
/// <param name="linxSipID">The linx sip id</param>
internal void StopPtt(string linxSipID)
{
_sipClient.StopPTT(linxSipID);
}
/// <summary>
/// Sends an audio buffer in a specified format to a linx sip id
/// </summary>
/// <param name="sipIdToSendVoiceTo">The linx sip id where to send voice</param>
/// <param name="audioBuffer">The audio buffer</param>
/// <param name="bufferLength">The length of the buffer</param>
/// <param name="audioFormat">The audio format</param>
internal void SendSipVoice(string sipIdToSendVoiceTo, byte[] audioBuffer, int bufferLength, SipComponent.AudioFormat audioFormat)
{
_sipClient.SendAudio(sipIdToSendVoiceTo, audioBuffer, bufferLength, audioFormat);
}
/// <summary>
/// Method used to send an sms to sip id as a Sip message
/// <para>This method does not block the calling thread while waiting for the confirmation</para>
/// </summary>
/// <param name="idToSendSMS">The sip id where to send the sms</param>
/// <param name="text">The sms text</param>
/// <returns>True if the sms was received, else returns false</returns>
internal async System.Threading.Tasks.Task<bool> SendSipSmsAsync(string idToSendSms, string text)
{
return await _sipClient.SendSmsAsync(idToSendSms, text);
}
/// <summary>
/// Sends an sms on socket IO
/// </summary>
/// <param name="seqID">Unique seqID. It should be in the format dispatcherSipID.timestamp</param>
/// <param name="fromScID">SC ID of the sender</param>
/// <param name="destinationSipID">The sip group ID</param>
/// <param name="destinationScID">SC ID of the group</param>
/// <param name="text">The text</param>
/// <param name="isGroupSms">True if is group sms, else false</param>
internal void SendSocketIoSMS(string seqID, int fromScID, int destinationSipID, int destinationScID, string text, bool isGroupSms)
{
if (_sipClient is Dispatcher.Sip.ISocketIOComponent)
{
((Dispatcher.Sip.ISocketIOComponent)_sipClient).SendSms(seqID, fromScID, destinationSipID, destinationScID, text, isGroupSms);
}
}
private static NotifyIcon notifyStatic = null;
public static void CloseNotifyIcon()
{
if (notifyStatic != null)
{
notifyStatic.Visible = false;
notifyStatic.Icon = null;
notifyStatic.Dispose();
}
}
private void MainForm2_FormClosing(object sender, FormClosingEventArgs e)
{
CloseNotifyIcon();
isRunning = false;
// Stop the sip clas
if (_sipClient != null)
{
StopSipClass(_sipClient, true);
}
}
internal UdpMulticast UdpMultForGwRecording
{
get { return _udpMulForGwRecording; }
}
internal void AddCallRequestForSip(int sipId, string callRequestSeqId)
{
_sipIdToSeqId[sipId] = callRequestSeqId;
}
internal string GetCallRequestForSip(int sipId)
{
if (_sipIdToSeqId.ContainsKey(sipId))
return _sipIdToSeqId[sipId];
else
return null;
}
/// <summary>
/// <para>Returns the ContactLinx object corresponding to the sip id</para>
/// <para>It returns null if the sip id is not known</para>
/// </summary>
/// <param name="sipID">The Sip id</param>
/// <returns></returns>
internal ContactLinx ContactLinxFromSipID(int sipID)
{
if (_sipIdToContactLinx_Dictionary.ContainsKey(sipID))
return _sipIdToContactLinx_Dictionary[sipID];
else
{
// in case of a call or sms received from an uncknown sip id
return null;
}
}
/// <summary>
/// Returns the name (of unit, dispatcher, group, gateway) corresponding to the sipID
/// </summary>
/// <param name="sipID">The Sip iD</param>
/// <returns></returns>
internal string DisplayNameFromSipID(int sipID)
{
if (_sipIdToContactLinx_Dictionary.ContainsKey(sipID))
return _sipIdToContactLinx_Dictionary[sipID].Name;
else
return "";
}
private void OnSipClassInitialized()
{
EventHandler handler = SipClassInitialized;
if (handler != null)
handler(this, new EventArgs());
}
internal string SipGWIDandRadioID
{
get { return _sipGWIDandRadioID; }
}
private bool systemTabVisible = false;
private void tabSystem_Enter(object sender, EventArgs e)
{
systemTabVisible = true;
}
private void tabSystem_Leave(object sender, EventArgs e)
{
systemTabVisible = false;
}
#endregion
public void SendSMSGroup(string text, int cps_id, int sched_timegmt, String groupName)
{
try
{
String Totrans = "";
foreach (GatewayIDandIP obj in MainForm2.RadioListIP)
{
Totrans = "#144#" + obj.GWID + "." + obj.ID + "." + cps_id + "#" + text + "#" + sched_timegmt + "#";
Send_UDP_cmd(Totrans, 0, 0);
}
//DisplayToast(MainForm2.returnLNGString("txtMsgTo") + " " + SMSTreeView.SelectedNode.Text, string.Format(MainForm2.returnLNGString("MsHTML"), text));
DisplayToast(returnLNGString("txtMsgTo") + groupName, "<html>" + returnLNGString("msj") + " " + "<i>" + text + "</i>" + " " + returnLNGString("wasSentToGW") + "</html>");
}
catch (Exception ex)
{
SM.Debug("Send SMS Group error:" + ex.ToString());
}
}
/// <summary>
/// Sends sms command (142) on message bus
/// </summary>
/// <param name="text"></param>
/// <param name="sc_id"></param>
/// <param name="sched_timegmt"></param>
internal async void SendSmsOnMBus(string text, int sc_id, int sched_timegmt)
{
try
{
if (text == "")
return;
String mbusText = text;
byte[] asciiText = Encoding.ASCII.GetBytes(text);
// detect if the message should be converted as unicode or not
if (!text.Equals(Encoding.ASCII.GetString(asciiText)))
{
mbusText = mbusText.EncodeNonAsciiCharacters();
mbusText = $"{Utils.MBusUnicodeChar}{mbusText}";
}
string veh_name = (String)VehIDHash[sc_id];
if ( !string.IsNullOrEmpty(veh_name) && vehicleHT.ContainsKey(veh_name))
{
Vehicle veh = ((Vehicle)vehicleHT[veh_name]);
veh.CheckPositionInSystem();
String Totrans = "#" + (int)MessageBusCmds.SendSMSRequest + "#" + veh.GwandRadioID + "." + veh.IMEI + "#" + mbusText + "#" + sched_timegmt + "#" + userIDX + "#";
//old
//String Totrans = "#142#" + ((Vehicle)MainForm2.vehicleHT[MainForm2.VehIDHash[sc_id].ToString()]).IMEI + "#" + text + "#" + sched_timegmt + "#";
string smsSeqID = Send_UDP_cmd(Totrans, 0, 0);
Utils.WriteLine("<22><><EFBFBD> Text message to " + sc_id + " [" + text + "]", ConsoleColor.White);
veh.EventLists.Add(new Alarms(rep_type.SMSSEND, DateTime.Now, "", text));
if (PopupOpen[veh.IMEI] != null)
((FastCommandWindow)PopupOpen[veh.IMEI]).populate();
DisplayToast(returnLNGString("txtMsgTo") + veh.busName, "<html>" + returnLNGString("msj") + " " + "<i>" + text + "</i>" + " " + returnLNGString("wasSentToGW") + "</html>");
// The message has been put on mbus and saved in the database
// Send also sip message if destination is linx
if (_sipClient != null)
{
if (veh.canMakeSipCalls)
{
bool sipSmsReceived = await SendSipSmsAsync(veh.sipID.ToString(), text);
// Send sms confirmation on mbus
// #msgLen#seqID#Opcode#state#
// Generate string command to send on message bus
// #seqID#Opcode#state#
string toTrans = string.Format("#{0}#{1}#{2}#",
smsSeqID, (int)MessageBusCmds.FieldRadioReceivedSmsAck, sipSmsReceived ? "1" : "2");
Utils.WriteLine(string.Format("Send Ack on mbus: message with id {0} was {1} by linx",
smsSeqID, sipSmsReceived ? "received" : "not received"),
ConsoleColor.Green);
// Send
}
}
}
}
catch (Exception ex)
{
SM.Debug("Send SMS error on hash:" + ex.ToString());
}
}
}
#region class DOCK
public class FloatWindowCommand : RadDockCommand
{
public FloatWindowCommand()
{
this.Name = "FloatWindow1";
this.Shortcuts.Add(new RadShortcut(Keys.Control, Keys.F));
}
public override bool CanExecute(object parameter)
{
RadDock dock = parameter as RadDock;
if (dock == null)
{
return false;
}
return dock.ActiveWindow is ToolWindow;
}
public override object Execute(params object[] settings)
{
RadDock dock = settings[0] as RadDock;
Debug.Assert(dock != null, "Invalid execute parameter!");
ToolWindow toolWindow = dock.ActiveWindow as ToolWindow;
if (toolWindow != null)
{
dock.FloatWindow(toolWindow);
}
return base.Execute(settings);
}
}
#endregion
}