Compare commits

..

No commits in common. "master" and "refactor_code" have entirely different histories.

15 changed files with 443 additions and 737 deletions

View File

@ -23,7 +23,6 @@ namespace AppServer
private volatile DBvehiclesManager dbvehs; private volatile DBvehiclesManager dbvehs;
private DBvehiclesManager DBvehInfo; private DBvehiclesManager DBvehInfo;
public static volatile Int32 LocationCheckQueuesCount = 0; public static volatile Int32 LocationCheckQueuesCount = 0;
Int64 count = 0; Int64 count = 0;
private bool sendCalloutStop; private bool sendCalloutStop;
@ -185,12 +184,12 @@ namespace AppServer
{ {
Vehicle_Data v_data = (Vehicle_Data)MainForm.VehList[radioID2.ToString()]; Vehicle_Data v_data = (Vehicle_Data)MainForm.VehList[radioID2.ToString()];
Alarm alarm = v_data.alm; Alarm alarm = v_data.alm;
bool zone = false;
bool landMark = false;
bool zone = (alarm.Zone != "") ;
bool landMark = (alarm.Landmark != "") ;
String SpeedProccess = ""; String SpeedProccess = "";
if (alarm.Zone != "") zone = true;
if (alarm.Landmark != "") landMark = true;
if (zone || landMark) if (zone || landMark)
{ {
SpeedProccess = processZoneAlarm(radioID2, dec2.cell, zone, landMark, alarm.Email, !prevGps); SpeedProccess = processZoneAlarm(radioID2, dec2.cell, zone, landMark, alarm.Email, !prevGps);
@ -262,7 +261,6 @@ namespace AppServer
{ {
continue; continue;
} }
//get unit system position //get unit system position
int unitSC_ID = ((Vehicle_Data)MainForm.VehList[radioID2]).sc_id; int unitSC_ID = ((Vehicle_Data)MainForm.VehList[radioID2]).sc_id;
UnitSysPosition sysPos = DBvehInfo.getSystemPosition(unitSC_ID); UnitSysPosition sysPos = DBvehInfo.getSystemPosition(unitSC_ID);
@ -272,8 +270,7 @@ namespace AppServer
//send radio disable to GW //send radio disable to GW
Utils.WriteLine("Radio disable was sent on " + sysPos.Gw_id + "." + sysPos.R_gw_id + " gateway", ConsoleColor.Cyan); Utils.WriteLine("Radio disable was sent on " + sysPos.Gw_id + "." + sysPos.R_gw_id + " gateway", ConsoleColor.Cyan);
string test2 = $"#{(int)MessageBusCmds.RadioEnableDisableRequest}#" + dest + "#0#"; string test2 = $"#{(int)MessageBusCmds.RadioEnableDisableRequest}#" + dest + "#0#";
byte[] dataToSend = Utils.Convert_text_For_multicast("#0.0" + test2); MainForm.udp.Send(Utils.Convert_text_For_multicast("#0.0" + test2), Utils.Convert_text_For_multicast("#0.0" + test2).Length);
MainForm.udp.Send(dataToSend, dataToSend.Length);
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -351,13 +348,9 @@ namespace AppServer
try try
{ {
string test2 = "#210#1#Can't write GPS data in DB#"; string test2 = "#210#1#Can't write GPS data in DB#";
if (ex.Message == "AlarmError") if (ex.Message == "AlarmError") test2 = "#210#5#Can't write Alarm data in DB#";
test2 = "#210#5#Can't write Alarm data in DB#"; else if (ex.Message == "StolenError") test2 = "#210#6#Can't write Stolen data in DB#";
else if (ex.Message == "StolenError") MainForm.udp.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#0.0" + test2), SafeMobileLib.Utils.Convert_text_For_multicast("#0.0" + test2).Length);
test2 = "#210#6#Can't write Stolen data in DB#";
byte[] dataToSend = Utils.Convert_text_For_multicast("#0.0" + test2);
MainForm.udp.Send(dataToSend, dataToSend.Length);
} }
catch (Exception ex2) catch (Exception ex2)
{ {
@ -403,10 +396,7 @@ namespace AppServer
{ {
// send callout clear // send callout clear
string test = "#178#" + callout.RadioID.ToString() + "#" + callout.Severity + "#"; string test = "#178#" + callout.RadioID.ToString() + "#" + callout.Severity + "#";
MainForm.udp.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#0.0" + test), SafeMobileLib.Utils.Convert_text_For_multicast("#0.0" + test).Length);
byte[] dataToSend = Utils.Convert_text_For_multicast("#0.0" + test);
MainForm.udp.Send(dataToSend, dataToSend.Length);
Utils.WriteLine($"Sent CallOut Stop request with Severity [{callout.Severity}] for unit {callout.RadioID.ToString()} "); Utils.WriteLine($"Sent CallOut Stop request with Severity [{callout.Severity}] for unit {callout.RadioID.ToString()} ");
} }
} }
@ -418,16 +408,8 @@ namespace AppServer
private void sendMailGeo(string mes, String subj, string mailAdr) private void sendMailGeo(string mes, String subj, string mailAdr)
{ {
if (Program.cfg.enableEmailService) if (Program.cfg.enableEmailService && !String.IsNullOrEmpty(Program.cfg.emailAddress) && !String.IsNullOrEmpty(mailAdr))
{ {
if (!String.IsNullOrEmpty(Program.cfg.emailAddress) && !String.IsNullOrEmpty(mailAdr))
{
if (MainForm.IsBlacklistedAddress(mailAdr))
{
Utils.WriteLine($"sendMailGeo : The email '{subj}' was not sent. Email address '{mailAdr}' is in blacklist count = {MainForm.blackListAddress[mailAdr]}");
return;
}
try try
{ {
MailAddress from = new MailAddress(Program.cfg.emailAddress); MailAddress from = new MailAddress(Program.cfg.emailAddress);
@ -451,16 +433,7 @@ namespace AppServer
} }
catch (Exception ex) catch (Exception ex)
{ {
if (ex.ToString().Contains("timed out") || Console.WriteLine("Exception in sendMailGeo: ", ex.ToString());
ex.ToString().Contains("the client was not authenticated"))
MainForm.HandleTimeoutError(mailAdr);
Utils.WriteLine($"Exception in sendMailGeo: {ex.ToString()}");
}
}
else
{
Utils.WriteLine($"Missing email address From = {Program.cfg.emailAddress} To = {mailAdr})", ConsoleColor.Cyan);
} }
} }
else else
@ -470,20 +443,10 @@ namespace AppServer
} }
private void sendAlarmMail(string title, string mes, string mailAdr) private void sendAlarmMail(string title, string mes, string mailAdr)
{ {
if (Program.cfg.enableEmailService) if (Program.cfg.enableEmailService && !String.IsNullOrEmpty(Program.cfg.emailAddress) && !String.IsNullOrEmpty(mailAdr))
{ {
if (!String.IsNullOrEmpty(Program.cfg.emailAddress) && !String.IsNullOrEmpty(mailAdr))
{
if (MainForm.IsBlacklistedAddress(mailAdr))
{
Utils.WriteLine($" sendAlarmMail : The email '{title}' was not sent. Email address '{mailAdr}' is in blacklist count = {MainForm.blackListAddress[mailAdr]}");
return;
}
try try
{ {
MailAddress from = new MailAddress(Program.cfg.emailAddress); MailAddress from = new MailAddress(Program.cfg.emailAddress);
@ -495,19 +458,10 @@ namespace AppServer
} }
catch (Exception ex) catch (Exception ex)
{ {
if ( ex.ToString().Contains("timed out") ||
ex.ToString().Contains("the client was not authenticated"))
MainForm.HandleTimeoutError(mailAdr);
Utils.WriteLine("Exception in sendMailAlarm2: {0}" + ex.ToString(), ConsoleColor.Red); Utils.WriteLine("Exception in sendMailAlarm2: {0}" + ex.ToString(), ConsoleColor.Red);
} }
} }
else else
{
Utils.WriteLine($"Missing email address From = {Program.cfg.emailAddress} To = {mailAdr})", ConsoleColor.Cyan);
}
}
else
{ {
Utils.WriteLine("Email Server not Set",ConsoleColor.Cyan); Utils.WriteLine("Email Server not Set",ConsoleColor.Cyan);
} }
@ -587,8 +541,7 @@ namespace AppServer
{ {
//send alarm on message buss //send alarm on message buss
test = "#136#" + radioID.ToString() + "#" + tmpresp + "#"; test = "#136#" + radioID.ToString() + "#" + tmpresp + "#";
byte[] dataToSend = Utils.Convert_text_For_multicast("#0.0" + test); MainForm.udp.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#0.0" + test), SafeMobileLib.Utils.Convert_text_For_multicast("#0.0" + test).Length);
MainForm.udp.Send(dataToSend, dataToSend.Length);
} }
String date = DateTime.Now.ToUniversalTime().DateTo70Format().ToString(); String date = DateTime.Now.ToUniversalTime().DateTo70Format().ToString();
@ -616,10 +569,7 @@ namespace AppServer
tmpX = dbvehs.getSystemPosition(Convert.ToInt32(keyobj)); tmpX = dbvehs.getSystemPosition(Convert.ToInt32(keyobj));
test = "#142#" + tmpX.Gw_id + "." + tmpX.R_gw_id + "." + (String)tmpHashName[keyobj] + "#" + /*"Message from unit " + ((Vehicle_Data)MainForm.VehList[radioID.ToString()]).Name + " :" +*/ obj2.msgbody + "#" + date + "#"; test = "#142#" + tmpX.Gw_id + "." + tmpX.R_gw_id + "." + (String)tmpHashName[keyobj] + "#" + /*"Message from unit " + ((Vehicle_Data)MainForm.VehList[radioID.ToString()]).Name + " :" +*/ obj2.msgbody + "#" + date + "#";
MainForm.udp.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#0." + date + test), SafeMobileLib.Utils.Convert_text_For_multicast("#0." + date + test).Length);
byte[] dataToSend = Utils.Convert_text_For_multicast("#0." + date + test);
MainForm.udp.Send(dataToSend, dataToSend.Length);
Thread.Sleep(100); Thread.Sleep(100);
Utils.WriteLine($"Zone alert sms request [{obj2.msgbody}] for unit {(String)tmpHashName[keyobj]} on gw [{(tmpX.Gw_id + "." + tmpX.R_gw_id)}]"); Utils.WriteLine($"Zone alert sms request [{obj2.msgbody}] for unit {(String)tmpHashName[keyobj]} on gw [{(tmpX.Gw_id + "." + tmpX.R_gw_id)}]");
@ -631,8 +581,7 @@ namespace AppServer
{ {
tmpX = dbvehs.getSystemPositionIMEI(radioID); tmpX = dbvehs.getSystemPositionIMEI(radioID);
test = "#142#" + tmpX.Gw_id + "." + tmpX.R_gw_id + "." + radioID + "#" + obj2.msgbody2 + "#" + DateTime.Now.ToUniversalTime().DateTo70Format().ToString() + "#"; test = "#142#" + tmpX.Gw_id + "." + tmpX.R_gw_id + "." + radioID + "#" + obj2.msgbody2 + "#" + DateTime.Now.ToUniversalTime().DateTo70Format().ToString() + "#";
byte[] dataToSend = Utils.Convert_text_For_multicast("#0." + date + test); MainForm.udp.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#0." + date + test), SafeMobileLib.Utils.Convert_text_For_multicast("#0." + date + test).Length);
MainForm.udp.Send(dataToSend, dataToSend.Length);
Utils.WriteLine($"Zone alert sms request [{obj2.msgbody2}] for unit {radioID} on gw [{(tmpX.Gw_id + "." + tmpX.R_gw_id)}]"); Utils.WriteLine($"Zone alert sms request [{obj2.msgbody2}] for unit {radioID} on gw [{(tmpX.Gw_id + "." + tmpX.R_gw_id)}]");
} }
@ -642,8 +591,7 @@ namespace AppServer
{ {
tmpX = dbvehs.getSystemPositionIMEI(radioID); tmpX = dbvehs.getSystemPositionIMEI(radioID);
test = "#177#" + radioID.ToString() + "#" + obj2.calloutSeverity + "#" + obj2.name + "#"; test = "#177#" + radioID.ToString() + "#" + obj2.calloutSeverity + "#" + obj2.name + "#";
byte[] dataToSend = Utils.Convert_text_For_multicast("#0." + test); MainForm.udp.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#0.0" + test), SafeMobileLib.Utils.Convert_text_For_multicast("#0.0" + test).Length);
MainForm.udp.Send(dataToSend, dataToSend.Length);
callOutQueue.PostItem(new CallOut() { RadioID = radioID, Severity = obj2.calloutSeverity, Time = DateTime.Now}); callOutQueue.PostItem(new CallOut() { RadioID = radioID, Severity = obj2.calloutSeverity, Time = DateTime.Now});
Utils.WriteLine($"Zone CallOut request with Severity [{obj2.calloutSeverity}] for unit {radioID} on gw [{(tmpX.Gw_id + "." + tmpX.R_gw_id)}]"); Utils.WriteLine($"Zone CallOut request with Severity [{obj2.calloutSeverity}] for unit {radioID} on gw [{(tmpX.Gw_id + "." + tmpX.R_gw_id)}]");
@ -699,16 +647,14 @@ namespace AppServer
{ {
//send alarm on message buss //send alarm on message buss
string test = "#137#" + radioID.ToString() + "#" + tmpresp + "#"; string test = "#137#" + radioID.ToString() + "#" + tmpresp + "#";
byte[] dataToSend = Utils.Convert_text_For_multicast("#0.0" + test); MainForm.udp.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#0.0" + test), SafeMobileLib.Utils.Convert_text_For_multicast("#0.0" + test).Length);
MainForm.udp.Send(dataToSend, dataToSend.Length);
} }
//send CallOut //send CallOut
if(obj2.callout && tmpresp.ToString().Contains("IN ")) if(obj2.callout && tmpresp.ToString().Contains("IN "))
{ {
string test = "#177#" + radioID + "#" + obj2.calloutSeverity + "#" + obj2.name + "#"; string test = "#177#" + radioID + "#" + obj2.calloutSeverity + "#" + obj2.name + "#";
byte[] dataToSend = Utils.Convert_text_For_multicast("#0.0" + test); MainForm.udp.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#0.0" + test), SafeMobileLib.Utils.Convert_text_For_multicast("#0.0" + test).Length);
MainForm.udp.Send(dataToSend, dataToSend.Length);
callOutQueue.PostItem(new CallOut() { RadioID = radioID, Severity = obj2.calloutSeverity, Time = DateTime.Now }); callOutQueue.PostItem(new CallOut() { RadioID = radioID, Severity = obj2.calloutSeverity, Time = DateTime.Now });
Utils.WriteLine($"Landmark CallOut request with Severity [{obj2.calloutSeverity}] for unit {radioID} "); Utils.WriteLine($"Landmark CallOut request with Severity [{obj2.calloutSeverity}] for unit {radioID} ");
@ -777,8 +723,7 @@ namespace AppServer
//send alarm on message buss //send alarm on message buss
string speed4send = $"{speed}_{speedUnits}"; string speed4send = $"{speed}_{speedUnits}";
string test = "#135#" + radioID.ToString() + "#" + speed4send + "#"; string test = "#135#" + radioID.ToString() + "#" + speed4send + "#";
MainForm.udp.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#0.0" + test), SafeMobileLib.Utils.Convert_text_For_multicast("#0.0" + test).Length);
MainForm.udp.Send(Utils.Convert_text_For_multicast("#0.0" + test), Utils.Convert_text_For_multicast("#0.0" + test).Length);
} }
} }

View File

@ -96,9 +96,6 @@ namespace AppServer
public static String dbAccess; public static String dbAccess;
private WebsocketThread websocket = null; private WebsocketThread websocket = null;
public static Dictionary<string, int> blackListAddress = new Dictionary<string, int>();
public const int MAX_ATTEMPTS = 100;
public delegate void UpdateLicensesUIInvokeCallBack(); public delegate void UpdateLicensesUIInvokeCallBack();
public MainForm() public MainForm()
@ -341,37 +338,6 @@ namespace AppServer
} }
public static void HandleTimeoutError(string mailAdr)
{
// add address to backlist
if (!blackListAddress.ContainsKey(mailAdr))
blackListAddress.Add(mailAdr, MAX_ATTEMPTS);
}
public static bool IsBlacklistedAddress(string mailAdr)
{
if (!blackListAddress.ContainsKey(mailAdr))
return false;
// avoid to send the email MAX_ATTEMPTS times => give another chance to try to send email when count = 0
int count = blackListAddress[mailAdr];
if (count == 0)
{
blackListAddress.Remove(mailAdr);
return false;
}
blackListAddress[mailAdr] = count - 1;
return true;
}
private void ConfigureWebSocket() private void ConfigureWebSocket()
{ {
if (!checkWebsocketServerStatus.Enabled) if (!checkWebsocketServerStatus.Enabled)
@ -1058,8 +1024,7 @@ namespace AppServer
{ {
try try
{ {
byte[] dataToSend = Utils.Convert_text_For_multicast("#0.0#210#4#AppServer stoped#"); udp.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#0.0#210#4#AppServer stoped#"), SafeMobileLib.Utils.Convert_text_For_multicast("#0.0#210#4#AppServer stoped#").Length);
udp.Send(dataToSend, dataToSend.Length);
} }
catch (Exception ex2) catch (Exception ex2)
{ {
@ -1107,8 +1072,7 @@ namespace AppServer
error = true; error = true;
try try
{ {
byte[] dataToSend = Utils.Convert_text_For_multicast("#0.0#210#2#Dongle missing Application server stopped#"); udp.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#0.0#210#2#Dongle missing Application server stopped#"), SafeMobileLib.Utils.Convert_text_For_multicast("#0.0#210#2#Dongle missing Application server stopped#").Length);
udp.Send(dataToSend, dataToSend.Length);
} }
catch (Exception ex2) catch (Exception ex2)
{ {
@ -1228,10 +1192,8 @@ namespace AppServer
MainForm.websocketLocationQueue.PostItem(data); MainForm.websocketLocationQueue.PostItem(data);
if(!sendWebsocketTimer.Enabled) if(!sendWebsocketTimer.Enabled)
sendWebsocketTimer.Enabled = true; sendWebsocketTimer.Enabled = true;
if (!checkWebsocketServerStatus.Enabled) if (!checkWebsocketServerStatus.Enabled)
checkWebsocketServerStatus.Enabled = true; checkWebsocketServerStatus.Enabled = true;
} }
@ -1283,12 +1245,10 @@ namespace AppServer
} }
try try
{ {
byte[] dataToSend = Utils.Convert_text_For_multicast($"#0.0#{Utils.enumConvertToString(MessageBusCmds.WebsocketStatusToMsgBus)}#offline#"); udp.Send(Utils.Convert_text_For_multicast($"#0.0#{Utils.enumConvertToString(MessageBusCmds.WebsocketStatusToMsgBus)}#offline#"),
udp.Send(dataToSend, dataToSend.Length); Utils.Convert_text_For_multicast($"#0.0#{Utils.enumConvertToString(MessageBusCmds.WebsocketStatusToMsgBus)}#offline#").Length);
udp.Send(Utils.Convert_text_For_multicast("#0.0#210#4#Application server stopped#"),
Utils.Convert_text_For_multicast("#0.0#210#4#Application server stopped#").Length);
dataToSend = Utils.Convert_text_For_multicast("#0.0#210#4#Application server stopped#");
udp.Send(dataToSend, dataToSend.Length);
} }
catch (Exception ex2) catch (Exception ex2)
{ {
@ -1304,8 +1264,7 @@ namespace AppServer
{ {
try try
{ {
byte[] dataToSend = Utils.Convert_text_For_multicast("#0.0#210#5#Application server restart#"); udp.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#0.0#210#5#Application server restart#"), SafeMobileLib.Utils.Convert_text_For_multicast("#0.0#210#5#Application server restart#").Length);
udp.Send(dataToSend, dataToSend.Length);
} }
catch (Exception ex2) catch (Exception ex2)
{ {

View File

@ -28,7 +28,6 @@ namespace AppServer
private DBvehiclesManager dbvehs; private DBvehiclesManager dbvehs;
internal DBsubsOperationManager dbsubsoperManage; internal DBsubsOperationManager dbsubsoperManage;
private DBcallPatchManager dbCallPatch; private DBcallPatchManager dbCallPatch;
#region code for zone #region code for zone
private volatile static ArrayList ZoneList = new ArrayList(); private volatile static ArrayList ZoneList = new ArrayList();
private volatile static ArrayList LandList = new ArrayList(); private volatile static ArrayList LandList = new ArrayList();
@ -606,8 +605,7 @@ namespace AppServer
Utils.WriteLine("Radio disable was sent on " + sysPos.Gw_id + "." + sysPos.R_gw_id + " gateway", ConsoleColor.Cyan); Utils.WriteLine("Radio disable was sent on " + sysPos.Gw_id + "." + sysPos.R_gw_id + " gateway", ConsoleColor.Cyan);
//send radio disable to GW //send radio disable to GW
string test2 = "#150#" + dest + "#0#"; string test2 = "#150#" + dest + "#0#";
byte[] dataToSend = Utils.Convert_text_For_multicast("#0.0" + test2); MainForm.udp.Send(Utils.Convert_text_For_multicast("#0.0" + test2), Utils.Convert_text_For_multicast("#0.0" + test2).Length);
MainForm.udp.Send(dataToSend, dataToSend.Length);
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -728,9 +726,7 @@ namespace AppServer
UnitSysPosition sysPos = DBvehInfo.getSystemPosition(unitSC_ID); UnitSysPosition sysPos = DBvehInfo.getSystemPosition(unitSC_ID);
string message = string.Format("Ticket no. {0} is no longer active!", dec3.delete_ticket_id); string message = string.Format("Ticket no. {0} is no longer active!", dec3.delete_ticket_id);
string test1 = "#143#" + sysPos.Gw_id + "." + sysPos.R_gw_id + "." + radioID3 + "#" + message + "#" + 0 + "#"; string test1 = "#143#" + sysPos.Gw_id + "." + sysPos.R_gw_id + "." + radioID3 + "#" + message + "#" + 0 + "#";
MainForm.udp.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#0.0"+test1), SafeMobileLib.Utils.Convert_text_For_multicast("#0.0"+test1).Length);
byte[] cmd = Utils.Convert_text_For_multicast("#0.0" + test1);
MainForm.udp.Send(cmd, cmd.Length);
} }
//send to email if was sms->email type //send to email if was sms->email type
if (dec3.isEmail) if (dec3.isEmail)
@ -738,11 +734,12 @@ namespace AppServer
sendMail(dec3.emailAddr, dec3.messBody, radioID3); sendMail(dec3.emailAddr, dec3.messBody, radioID3);
} }
//send ACK back to GW //send ACK back to GW
test = (dec3.sqlResp == sqlResponse.done) ? "#232#1#" : "#232#0#"; test = "";
if (dec3.sqlResp == sqlResponse.done)
test = "#232#1#";
byte[] dataToSend = Utils.Convert_text_For_multicast("#" + seqID3 + test); else
MainForm.udp.Send(dataToSend, dataToSend.Length); test = "#232#0#";
MainForm.udp.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#" + seqID3 + test), SafeMobileLib.Utils.Convert_text_For_multicast("#" + seqID3 + test).Length);
if (MainForm.SendPOLLafterSMS) if (MainForm.SendPOLLafterSMS)
{ {
@ -752,8 +749,7 @@ namespace AppServer
string dest = $"0.0.{radioID3}"; string dest = $"0.0.{radioID3}";
if (sysPos != null) dest = $"{sysPos.Gw_id}.{sysPos.R_gw_id}.{radioID3}"; if (sysPos != null) dest = $"{sysPos.Gw_id}.{sysPos.R_gw_id}.{radioID3}";
dataToSend = Utils.Convert_text_For_multicast("#0.0#154#" + dest + "#"); MainForm.udp.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#0.0#154#" + dest + "#"), SafeMobileLib.Utils.Convert_text_For_multicast("#0.0#154#" + dest + "#").Length);
MainForm.udp.Send(dataToSend, dataToSend.Length);
} }
} }
catch (Exception ex) catch (Exception ex)
@ -931,9 +927,7 @@ namespace AppServer
System.Threading.Thread.Sleep(100); System.Threading.Thread.Sleep(100);
SM.Debug("Sending telemetry alarm to SD; digital:" + tObj.DigitalNr); SM.Debug("Sending telemetry alarm to SD; digital:" + tObj.DigitalNr);
test = $"#140#{radioID}#{tObj.Name}#"; test = $"#140#{radioID}#{tObj.Name}#";
MainForm.udp.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#0.0" + test), SafeMobileLib.Utils.Convert_text_For_multicast("#0.0"+test).Length);
byte[] dataToSend = Utils.Convert_text_For_multicast("#0.0" + test);
MainForm.udp.Send(dataToSend, dataToSend.Length);
} }
else else
{ {
@ -944,8 +938,7 @@ namespace AppServer
} }
if (IhaveData) if (IhaveData)
{ {
byte[] dataToSend = Utils.Convert_text_For_multicast("#0.0#154#" + dest + "#"); MainForm.udp.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#0.0#154#" + dest + "#"), SafeMobileLib.Utils.Convert_text_For_multicast("#0.0#154#" + dest + "#").Length);
MainForm.udp.Send(dataToSend, dataToSend.Length);
} }
} }
catch (Exception ex) catch (Exception ex)
@ -1039,8 +1032,7 @@ namespace AppServer
bgWorkerDBbackup.RunWorkerAsync(param); bgWorkerDBbackup.RunWorkerAsync(param);
//send ACK back to SUM //send ACK back to SUM
byte[] dataToSend = Utils.Convert_text_For_multicast("#0.0#71#1#"); MainForm.udp.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#0.0#71#1#"), SafeMobileLib.Utils.Convert_text_For_multicast("#0.0#71#1#").Length);
MainForm.udp.Send(dataToSend, dataToSend.Length);
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -1068,14 +1060,12 @@ namespace AppServer
object[] param2 = { completeFileName, posgresPath }; object[] param2 = { completeFileName, posgresPath };
bgWorkerDBrestore.RunWorkerAsync(param2); bgWorkerDBrestore.RunWorkerAsync(param2);
//send ACK back to SUM //send ACK back to SUM
byte[] dataToSend = Utils.Convert_text_For_multicast("#0.0#72#1#"); MainForm.udp.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#0.0#72#1#"), SafeMobileLib.Utils.Convert_text_For_multicast("#0.0#72#1#").Length);
MainForm.udp.Send(dataToSend, dataToSend.Length);
} }
else else
{ {
SM.Debug("DB restored failed !!!" + "File " + completeFileName + " missing!!!"); SM.Debug("DB restored failed !!!" + "File " + completeFileName + " missing!!!");
byte[] dataToSend = Utils.Convert_text_For_multicast("#0.0#62#0#"); MainForm.udp.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#0.0#62#0#"), SafeMobileLib.Utils.Convert_text_For_multicast("#0.0#62#0#").Length);
MainForm.udp.Send(dataToSend, dataToSend.Length);
} }
} }
catch (Exception ex) catch (Exception ex)
@ -1147,9 +1137,7 @@ namespace AppServer
//send broadcast messages I'm back in business //send broadcast messages I'm back in business
Utils.WriteLine(string.Format("receive 500 from radio: Gateway {0} is ON", ((RadioGateway)MainForm.RadioGWHash[key]).Name), ConsoleColor.Green); Utils.WriteLine(string.Format("receive 500 from radio: Gateway {0} is ON", ((RadioGateway)MainForm.RadioGWHash[key]).Name), ConsoleColor.Green);
string test1 = "#501#" + tempArr[4] + "#" + tempArr[5] + "#" + "ON#" + ((RadioGateway)MainForm.RadioGWHash[key]).Name + "#"; string test1 = "#501#" + tempArr[4] + "#" + tempArr[5] + "#" + "ON#" + ((RadioGateway)MainForm.RadioGWHash[key]).Name + "#";
MainForm.udp.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#" + seqID4 + test1), SafeMobileLib.Utils.Convert_text_For_multicast("#" + seqID4 + test1).Length);
byte[] dataToSend = Utils.Convert_text_For_multicast("#" + seqID4 + test1);
MainForm.udp.Send(dataToSend, dataToSend.Length);
} }
((RadioGateway)MainForm.RadioGWHash[key]).Alive = true; ((RadioGateway)MainForm.RadioGWHash[key]).Alive = true;
((RadioGateway)MainForm.RadioGWHash[key]).LastUpdate = DateTime.UtcNow; ((RadioGateway)MainForm.RadioGWHash[key]).LastUpdate = DateTime.UtcNow;
@ -1176,9 +1164,7 @@ namespace AppServer
string status = ((RadioGateway)(entry.Value)).Alive ? "ON" : "OFF"; string status = ((RadioGateway)(entry.Value)).Alive ? "ON" : "OFF";
Utils.WriteLine(string.Format("Response for SD request: Gateway {0} is {1}", ((RadioGateway)(entry.Value)).Name, status), status == "ON" ? ConsoleColor.Green : ConsoleColor.Red); Utils.WriteLine(string.Format("Response for SD request: Gateway {0} is {1}", ((RadioGateway)(entry.Value)).Name, status), status == "ON" ? ConsoleColor.Green : ConsoleColor.Red);
string test1 = "#501#" + ((RadioGateway)(entry.Value)).Gw_id + "#" + ((RadioGateway)(entry.Value)).Id + "#" + status + "#" + ((RadioGateway)(entry.Value)).Name + "#"; string test1 = "#501#" + ((RadioGateway)(entry.Value)).Gw_id + "#" + ((RadioGateway)(entry.Value)).Id + "#" + status + "#" + ((RadioGateway)(entry.Value)).Name + "#";
MainForm.udp.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#" + "0.0" + test1), SafeMobileLib.Utils.Convert_text_For_multicast("#" + "0.0" + test1).Length);
byte[] dataToSend = Utils.Convert_text_For_multicast("#" + "0.0" + test1);
MainForm.udp.Send(dataToSend, dataToSend.Length);
} }
} }
break; break;
@ -1301,14 +1287,11 @@ namespace AppServer
if (sysPos != null) dest = sysPos.Gw_id + "." + sysPos.R_gw_id + "." + radioID.ToString(); if (sysPos != null) dest = sysPos.Gw_id + "." + sysPos.R_gw_id + "." + radioID.ToString();
String test = "#154#" + dest + "#"; String test = "#154#" + dest + "#";
MainForm.udp.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#" + seqId + test), SafeMobileLib.Utils.Convert_text_For_multicast("#" + seqId + test).Length);
byte[] dataToSend = Utils.Convert_text_For_multicast("#" + seqId + test);
MainForm.udp.Send(dataToSend, dataToSend.Length);
//send emergency alarm to SD //send emergency alarm to SD
test = "#134#" + radioID.ToString() + "#" + emergencyType; test = "#134#" + radioID.ToString() + "#" + emergencyType;
dataToSend = Utils.Convert_text_For_multicast("#" + seqId + test); MainForm.udp.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#" + seqId + test), SafeMobileLib.Utils.Convert_text_For_multicast("#" + seqId + test).Length);
MainForm.udp.Send(dataToSend, dataToSend.Length);
((VehicleStatus)MainForm.VehicleHashStat[radioID]).curentStatus = Status_for_tab.EMERG; ((VehicleStatus)MainForm.VehicleHashStat[radioID]).curentStatus = Status_for_tab.EMERG;
((VehicleStatus)MainForm.VehicleHashStat[radioID]).lastArsTime = DateTime.Now; ((VehicleStatus)MainForm.VehicleHashStat[radioID]).lastArsTime = DateTime.Now;
@ -1389,9 +1372,7 @@ namespace AppServer
UnitSysPosition tmpX = dbvehs.getSystemPosition(msg.sc_id_dest); UnitSysPosition tmpX = dbvehs.getSystemPosition(msg.sc_id_dest);
//string test = "#143#" + tmpX.Gw_id + "." + tmpX.R_gw_id+"."+msg.imei_dest + "#" + msg.mess + "#" + msg.sched_timeGMT + "#"; //string test = "#143#" + tmpX.Gw_id + "." + tmpX.R_gw_id+"."+msg.imei_dest + "#" + msg.mess + "#" + msg.sched_timeGMT + "#";
string test = "#143#" + tmpX.Gw_id + "." + tmpX.R_gw_id + "." + msg.imei_dest + "#" + msg.mess + "#" + msg.sched_timeGMT + "#" + msg.dispatcherID + "#"; string test = "#143#" + tmpX.Gw_id + "." + tmpX.R_gw_id + "." + msg.imei_dest + "#" + msg.mess + "#" + msg.sched_timeGMT + "#" + msg.dispatcherID + "#";
MainForm.udp.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#" + msg.seq_id + test), SafeMobileLib.Utils.Convert_text_For_multicast("#" + msg.seq_id + test).Length);
byte[] dataToSend = Utils.Convert_text_For_multicast("#" + msg.seq_id + test);
MainForm.udp.Send(dataToSend, dataToSend.Length);
} }
else else
SM.Debug("message will be sent at a later time - schedule: " + msg.sched_timeGMT + " current:" + DateTime.Now.ToUniversalTime().DateTo70Format()); SM.Debug("message will be sent at a later time - schedule: " + msg.sched_timeGMT + " current:" + DateTime.Now.ToUniversalTime().DateTo70Format());
@ -1423,7 +1404,6 @@ namespace AppServer
string test = ""; string test = "";
String cmdok = ""; String cmdok = "";
var subsBlackList = new List<int> { (int)Status_for_tab.OFF, (int)Status_for_tab.DISABLE, (int)Status_for_tab.MADEOFF }; var subsBlackList = new List<int> { (int)Status_for_tab.OFF, (int)Status_for_tab.DISABLE, (int)Status_for_tab.MADEOFF };
byte[] dataToSend = null;
foreach (smsmessage msg in smss) foreach (smsmessage msg in smss)
{ {
@ -1436,9 +1416,7 @@ namespace AppServer
if (SysPosList[sc_id]!=null) if (SysPosList[sc_id]!=null)
test = "#143#" + ((UnitSysPosition)SysPosList[sc_id]).Gw_id + "." + ((UnitSysPosition)SysPosList[sc_id]).R_gw_id + "." + msg.imei_dest + "#" + msg.mess + "#" + msg.sched_timeGMT + "#" + msg.dispatcherID + "#"; test = "#143#" + ((UnitSysPosition)SysPosList[sc_id]).Gw_id + "." + ((UnitSysPosition)SysPosList[sc_id]).R_gw_id + "." + msg.imei_dest + "#" + msg.mess + "#" + msg.sched_timeGMT + "#" + msg.dispatcherID + "#";
else test = "#143#" + "0.0" + "." + msg.imei_dest + "#" + msg.mess + "#" + msg.sched_timeGMT + "#" + msg.dispatcherID + "#"; else test = "#143#" + "0.0" + "." + msg.imei_dest + "#" + msg.mess + "#" + msg.sched_timeGMT + "#" + msg.dispatcherID + "#";
MainForm.udp.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#" + msg.seq_id + test), SafeMobileLib.Utils.Convert_text_For_multicast("#" + msg.seq_id + test).Length);
dataToSend = Utils.Convert_text_For_multicast("#" + msg.seq_id + test);
MainForm.udp.Send(dataToSend, dataToSend.Length);
} }
else else
SM.Debug("message will be sent at a later time - schedule: " + msg.sched_timeGMT + " current:" + DateTime.Now.ToUniversalTime().DateTo70Format()); SM.Debug("message will be sent at a later time - schedule: " + msg.sched_timeGMT + " current:" + DateTime.Now.ToUniversalTime().DateTo70Format());
@ -1451,8 +1429,7 @@ namespace AppServer
UnitSysPosition tmpX = dbvehs.getSystemPosition_for_group(msg.imei_dest); UnitSysPosition tmpX = dbvehs.getSystemPosition_for_group(msg.imei_dest);
test = "#145#" + tmpX.Gw_id + "." + tmpX.R_gw_id + "." + msg.sc_id_dest + "#" + msg.mess + "#" + msg.sched_timeGMT + "#"; test = "#145#" + tmpX.Gw_id + "." + tmpX.R_gw_id + "." + msg.sc_id_dest + "#" + msg.mess + "#" + msg.sched_timeGMT + "#";
dataToSend = Utils.Convert_text_For_multicast("#" + msg.seq_id + test); MainForm.udp.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#" + msg.seq_id + test), SafeMobileLib.Utils.Convert_text_For_multicast("#" + msg.seq_id + test).Length);
MainForm.udp.Send(dataToSend, dataToSend.Length);
} }
Utils.WriteLine($"Undelivered {undeliveredSMS} private messages and {smss.Count} group messages", ConsoleColor.White); Utils.WriteLine($"Undelivered {undeliveredSMS} private messages and {smss.Count} group messages", ConsoleColor.White);
@ -1468,19 +1445,19 @@ namespace AppServer
{ {
//Check4ExpiredTickets //Check4ExpiredTickets
List<JobTickets> jtlist = new List<JobTickets>(); List<JobTickets> jtlist = new List<JobTickets>();
string list_of_id_text = "";
try try
{ {
DBTicketingManager DBT = new DBTicketingManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port); DBTicketingManager DBT = new DBTicketingManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port);
List<Int32> ExpiredTicketsIdList = DBT.updateTicketExpireDate(DateTo70Format(DateTime.UtcNow)); List<Int32> ExpiredTicketsIdList = DBT.updateTicketExpireDate(DateTo70Format(DateTime.UtcNow));
if(ExpiredTicketsIdList.Count>0) if(ExpiredTicketsIdList.Count>0)
{ {
foreach(Int32 id in ExpiredTicketsIdList)
// get comma separated list {
string list_of_id_text = string.Join<string>(",", ExpiredTicketsIdList.Select(x => $"{x}")); list_of_id_text += id + ",";
}
byte[] dataToSend = Utils.Convert_text_For_multicast($"#0.0#251#{list_of_id_text}#"); list_of_id_text = list_of_id_text.Substring(0, list_of_id_text.Length - 1);
MainForm.udp.Send(dataToSend, dataToSend.Length); MainForm.udp.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#0.0#251#" + list_of_id_text + "#"), SafeMobileLib.Utils.Convert_text_For_multicast("#0.0#251#" + list_of_id_text + "#").Length);
} }
} }
catch (Exception ex) catch (Exception ex)
@ -1518,10 +1495,7 @@ namespace AppServer
string head = "#143#0.0." + ticket.Imei + "#"; string head = "#143#0.0." + ticket.Imei + "#";
if (SysPosList[ticket.sc_id] != null) head = "#143#" + ((UnitSysPosition)SysPosList[ticket.sc_id]).Gw_id + "." + ((UnitSysPosition)SysPosList[ticket.sc_id]).R_gw_id + "." + ticket.Imei + "#"; if (SysPosList[ticket.sc_id] != null) head = "#143#" + ((UnitSysPosition)SysPosList[ticket.sc_id]).Gw_id + "." + ((UnitSysPosition)SysPosList[ticket.sc_id]).R_gw_id + "." + ticket.Imei + "#";
string test = head + message + "#" + 0 + "#"; string test = head + message + "#" + 0 + "#";
MainForm.udp.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#" + ticket.seq_id + test), SafeMobileLib.Utils.Convert_text_For_multicast("#" + ticket.seq_id + test).Length);
byte[] dataToSend = Utils.Convert_text_For_multicast("#" + ticket.seq_id + test);
MainForm.udp.Send(dataToSend, dataToSend.Length);
} }
} }
} }
@ -1547,8 +1521,7 @@ namespace AppServer
if (SysPosList[ticket.sc_id] != null) head = "#143#" + ((UnitSysPosition)SysPosList[ticket.sc_id]).Gw_id + "." + ((UnitSysPosition)SysPosList[ticket.sc_id]).R_gw_id + "." + ticket.Imei + "#"; if (SysPosList[ticket.sc_id] != null) head = "#143#" + ((UnitSysPosition)SysPosList[ticket.sc_id]).Gw_id + "." + ((UnitSysPosition)SysPosList[ticket.sc_id]).R_gw_id + "." + ticket.Imei + "#";
string test = head + ticket.Name + "#" + 0 + "#"; string test = head + ticket.Name + "#" + 0 + "#";
byte[] dataToSend = Utils.Convert_text_For_multicast("#" + ticket.seq_id + test); MainForm.udp.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#" + ticket.seq_id + test), SafeMobileLib.Utils.Convert_text_For_multicast("#" + ticket.seq_id + test).Length);
MainForm.udp.Send(dataToSend, dataToSend.Length);
} }
else else
SM.Debug("ticket will be sent at a later time - schedule: " + ticket.sched_timegmt + " current:" + DateTime.Now.ToUniversalTime().DateTo70Format()); SM.Debug("ticket will be sent at a later time - schedule: " + ticket.sched_timegmt + " current:" + DateTime.Now.ToUniversalTime().DateTo70Format());
@ -1580,9 +1553,7 @@ namespace AppServer
if (DateTime.Now.ToUniversalTime() > item.Timegmt.AddSeconds(item.ArsInterval + 10))// added 10 seconds; marja erroare if (DateTime.Now.ToUniversalTime() > item.Timegmt.AddSeconds(item.ArsInterval + 10))// added 10 seconds; marja erroare
{ {
SM.Debug("Unit:" + item.Imei + " ARS interval expired. Marking unit as OFF"); SM.Debug("Unit:" + item.Imei + " ARS interval expired. Marking unit as OFF");
MainForm.udp.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#0.0#130#" + item.Imei + "#OFF#"), SafeMobileLib.Utils.Convert_text_For_multicast("#0.0#130#" + item.Imei + "#OFF#").Length);
byte[] dataToSend = Utils.Convert_text_For_multicast("#0.0#130#" + item.Imei + "#OFF#");
MainForm.udp.Send(dataToSend, dataToSend.Length);
} }
} }
} }
@ -1628,9 +1599,7 @@ namespace AppServer
string test = "#501#" + ((RadioGateway)(entry.Value)).Gw_id + "#" + ((RadioGateway)(entry.Value)).Id + "#" + "OFF" + "#" + ((RadioGateway)(entry.Value)).Name + "#"; string test = "#501#" + ((RadioGateway)(entry.Value)).Gw_id + "#" + ((RadioGateway)(entry.Value)).Id + "#" + "OFF" + "#" + ((RadioGateway)(entry.Value)).Name + "#";
MainForm.udp.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#" + "0.0" + test), SafeMobileLib.Utils.Convert_text_For_multicast("#" + "0.0" + test).Length);
byte[] dataToSend = Utils.Convert_text_For_multicast("#" + "0.0" + test);
MainForm.udp.Send(dataToSend, dataToSend.Length);
((RadioGateway)(entry.Value)).Alive = false; ((RadioGateway)(entry.Value)).Alive = false;
} }
} }
@ -1715,9 +1684,7 @@ namespace AppServer
public static void PushStatus(String IMEI,Status_for_tab stat) public static void PushStatus(String IMEI,Status_for_tab stat)
{ {
Utils.WriteLine("Send PushStatus:" + stat+" Imei:"+IMEI,ConsoleColor.Yellow); Utils.WriteLine("Send PushStatus:" + stat+" Imei:"+IMEI,ConsoleColor.Yellow);
MainForm.udp.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#0.0#153#" + IMEI + "#" + (Int32)stat + "#"), SafeMobileLib.Utils.Convert_text_For_multicast("#0.0#153#" + IMEI + "#" + (Int32)stat + "#").Length);
byte[] dataToSend = Utils.Convert_text_For_multicast("#0.0#153#" + IMEI + "#" + (Int32)stat + "#");
MainForm.udp.Send(dataToSend, dataToSend.Length);
} }
@ -2116,8 +2083,7 @@ namespace AppServer
messageOnScreen = true; messageOnScreen = true;
try try
{ {
byte[] dataToSend = Utils.Convert_text_For_multicast("#Application server database connection failed#"); MainForm.udp.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#Application server database connection failed#"), SafeMobileLib.Utils.Convert_text_For_multicast("#0.0#210#3#Application server database connection failed#").Length);
MainForm.udp.Send(dataToSend, dataToSend.Length);
} }
catch (Exception ex2) catch (Exception ex2)
{ {
@ -2184,17 +2150,6 @@ namespace AppServer
private void sendAlarmMail(string mes, string mailAdr) private void sendAlarmMail(string mes, string mailAdr)
{ {
if (Program.cfg.enableEmailService)
{
if (!String.IsNullOrEmpty(Program.cfg.emailAddress) && !String.IsNullOrEmpty(mailAdr))
{
if (MainForm.IsBlacklistedAddress(mailAdr))
{
Utils.WriteLine($" sendAlarmMail : The email was not sent. Email address '{mailAdr}' is in blacklist ");
return;
}
try try
{ {
MailAddress from = new MailAddress(Program.cfg.emailAddress); MailAddress from = new MailAddress(Program.cfg.emailAddress);
@ -2206,24 +2161,10 @@ namespace AppServer
} }
catch (Exception ex) catch (Exception ex)
{ {
if (ex.ToString().Contains("timed out"))
MainForm.HandleTimeoutError(mailAdr);
Utils.WriteLine("Exception in sendMailAlarm: " + ex.ToString(), ConsoleColor.Red); Utils.WriteLine("Exception in sendMailAlarm: " + ex.ToString(), ConsoleColor.Red);
//Console.WriteLine(e.ToString()); //Console.WriteLine(e.ToString());
} }
} }
else
{
Utils.WriteLine($"Missing email address From = {Program.cfg.emailAddress} To = {mailAdr})", ConsoleColor.Red);
}
}
else
{
SM.Debug("email disabled");
}
}
public void sendDailyReportMail(String PdfFile, string mailAdr) public void sendDailyReportMail(String PdfFile, string mailAdr)
{ {
@ -2298,20 +2239,11 @@ namespace AppServer
if (Program.cfg.enableEmailService) if (Program.cfg.enableEmailService)
{ {
SM.Debug(new string[] { "Checking mail at:" + DateTime.Now.ToString(), "For " + Program.cfg.emailAddress.ToString() + " on " + Program.cfg.pop3Server.ToString() }); SM.Debug(new string[] { "Checking mail at:" + DateTime.Now.ToString(), "For " + Program.cfg.emailAddress.ToString() + " on " + Program.cfg.pop3Server.ToString() });
emailHT = dbsubsoperManage.getAll_imei_sc_id("ByMail"); emailHT = dbsubsoperManage.getAll_imei_sc_id("ByMail");
if (emailHT.Count > 0) if (emailHT.Count > 0)
{ {
SM.Debug("Load " + emailHT.Count + " subscribers emails from DB ..."); SM.Debug("Load " + emailHT.Count + " subscribers emails from DB ...");
} }
if (sslServer == null)
{
SM.Debug("sslServer is null");
return;
}
Int64 latestEmailTime = sslServer.getLastEmailTime(); Int64 latestEmailTime = sslServer.getLastEmailTime();
ArrayList EmailList = sslServer.getEmails(); ArrayList EmailList = sslServer.getEmails();
@ -2322,15 +2254,11 @@ namespace AppServer
DB.SetLastEmailTime(sslServer.getLastEmailTime()); DB.SetLastEmailTime(sslServer.getLastEmailTime());
} }
DBsmsManager DBsms = new DBsmsManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port);
DBvehiclesManager dbvehs = new DBvehiclesManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port); DBvehiclesManager dbvehs = new DBvehiclesManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port);
foreach (EmailtoSMS obj in EmailList) foreach (EmailtoSMS obj in EmailList)
{ {
String seqID = "0." + (DateTime.Now.GetSecondsLocalFromDT()) + DateTime.Now.Millisecond.ToString(); String seqID = "0." + (DateTime.Now.GetSecondsLocalFromDT()) + DateTime.Now.Millisecond.ToString();
SM.Debug(new string[] {"-----START OK----", SM.Debug(new string[] {"-----START OK----",
"From: " + obj.from, "From: " + obj.from,
"ID: " + obj.id, "ID: " + obj.id,
@ -2338,7 +2266,7 @@ namespace AppServer
try try
{ {
// app server idx =0 // app server idx =0
DBsmsManager DB = new DBsmsManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port);
//bigu code remove # from text and also replace "'" //bigu code remove # from text and also replace "'"
try try
{ {
@ -2349,15 +2277,13 @@ namespace AppServer
{ {
SM.Debug("Error on converting email:" + ex.ToString()); SM.Debug("Error on converting email:" + ex.ToString());
} }
//end bigu code //end bigu code
if (!obj.is_group) DBsms.insert_sms_received(obj.id, obj.text, 7, obj.from, seqID); if (!obj.is_group) DB.insert_sms_received(obj.id, obj.text, 7, obj.from, seqID);
if (obj.is_sierra) if (obj.is_sierra)
{ {
if (emailHT.Contains(obj.from)) if (emailHT.Contains(obj.from))
{ {
SM.Debug("Email received <<" + obj.text + ">> from address: " + obj.from); SM.Debug("Email received <<" + obj.text + ">> from address: " + obj.from);
seqID = "1." + Utils.GetSecondsLocalFromDT(DateTime.Now).ToString() + DateTime.Now.Millisecond.ToString(); seqID = "1." + Utils.GetSecondsLocalFromDT(DateTime.Now).ToString() + DateTime.Now.Millisecond.ToString();
string test = "#132#" + ((SW_Subscriber)emailHT[obj.from]).imei + "#" + obj.text + "#hyt#"; string test = "#132#" + ((SW_Subscriber)emailHT[obj.from]).imei + "#" + obj.text + "#hyt#";
String cmdok = "#" + seqID + test; Int32 tmp = cmdok.Length + 1; tmp += tmp.ToString().Length; cmdok = "#" + tmp.ToString() + cmdok; String cmdok = "#" + seqID + test; Int32 tmp = cmdok.Length + 1; tmp += tmp.ToString().Length; cmdok = "#" + tmp.ToString() + cmdok;
@ -2365,7 +2291,6 @@ namespace AppServer
byte[] buf = enc.GetBytes(cmdok); byte[] buf = enc.GetBytes(cmdok);
//send to messagebus //send to messagebus
MainForm.udp.Send(buf, buf.Length); MainForm.udp.Send(buf, buf.Length);
SM.Debug("Email thread successfully sent data to message bus"); SM.Debug("Email thread successfully sent data to message bus");
} }
} }
@ -2380,21 +2305,15 @@ namespace AppServer
obj.text = obj.text.Remove(140 - 3 - obj.from.Length) + " [" + obj.from + "]"; obj.text = obj.text.Remove(140 - 3 - obj.from.Length) + " [" + obj.from + "]";
else else
obj.text = obj.text + " [" + obj.from + "]"; obj.text = obj.text + " [" + obj.from + "]";
//send SMS on message buss //send SMS on message buss
if (!obj.is_sierra) if (!obj.is_sierra)
{
if (dbvehs != null)
{ {
UnitSysPosition tmpX = dbvehs.getSystemPosition(dbvehs.getSCID(obj.id)); UnitSysPosition tmpX = dbvehs.getSystemPosition(dbvehs.getSCID(obj.id));
string cmd = $"{tmpX.Gw_id}.{tmpX.R_gw_id}.{obj.id}#{obj.text}#{DateTime.Now.GetSecondsLocalFromDT()}#"; string msg = "#143#" + tmpX.Gw_id + "." + tmpX.R_gw_id + "." + obj.id + "#" + obj.text + "#" + (DateTime.Now.GetSecondsLocalFromDT()) + "#";
string code = (obj.is_group) ? "#144#" : "#143#" ; if (obj.is_group) msg = "#144#" + tmpX.Gw_id + "." + tmpX.R_gw_id + "." + obj.id + "#" + obj.text + "#" + (DateTime.Now.GetSecondsLocalFromDT()) + "#";
byte[] msg = Utils.Convert_text_For_multicast("#0.0" + code + cmd);
if (msg != null && msg.Length > 0) MainForm.udp.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#0.0" + msg), SafeMobileLib.Utils.Convert_text_For_multicast("#0.0" + msg).Length);
MainForm.udp.Send(msg, msg.Length);
if (obj.is_group) if (obj.is_group)
{ {
@ -2404,12 +2323,8 @@ namespace AppServer
if (oldgatewayID != obj2.Gw_id) if (oldgatewayID != obj2.Gw_id)
{ {
oldgatewayID = (Int32)obj2.Gw_id; oldgatewayID = (Int32)obj2.Gw_id;
cmd = $"#144#{obj2.Gw_id}.{obj2.Id}.{obj.id}#{obj.text}#{DateTime.Now.GetSecondsLocalFromDT()}#"; string msg2 = "#144#" + obj2.Gw_id + "." + obj2.Id + "." + obj.id + "#" + obj.text + "#" + (DateTime.Now.GetSecondsLocalFromDT()) + "#";
byte[] msg2 = Utils.Convert_text_For_multicast("#1." + (DateTime.Now.GetSecondsLocalFromDT()) + DateTime.Now.Ticks.ToString() + cmd); MainForm.udp.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#1." + (DateTime.Now.GetSecondsLocalFromDT()) + DateTime.Now.Ticks.ToString() + msg2), SafeMobileLib.Utils.Convert_text_For_multicast("#1." + (DateTime.Now.GetSecondsLocalFromDT()) + DateTime.Now.Ticks.ToString() + msg2).Length);
if( msg2 != null && msg2.Length > 0)
MainForm.udp.Send(msg2, msg2.Length);
}
} }
} }
} }
@ -2433,16 +2348,6 @@ namespace AppServer
{ {
if (Program.cfg.enableEmailService) if (Program.cfg.enableEmailService)
{ {
if (!String.IsNullOrEmpty(Program.cfg.emailAddress) && !String.IsNullOrEmpty(mailAdr))
{
if (MainForm.IsBlacklistedAddress(mailAdr))
{
Utils.WriteLine($"sendMail : The email was not sent. Email address '{mailAdr}' is in blacklist count = {MainForm.blackListAddress[mailAdr]}");
return;
}
SM.Debug("Sending mail to " + mailAdr + " from radioId " + radioID.ToString()); SM.Debug("Sending mail to " + mailAdr + " from radioId " + radioID.ToString());
try try
{ {
@ -2460,19 +2365,10 @@ namespace AppServer
} }
catch (Exception ex) catch (Exception ex)
{ {
if (ex.ToString().Contains("timed out") ||
ex.ToString().Contains("the client was not authenticated"))
MainForm.HandleTimeoutError(mailAdr);
Utils.WriteLine("Exception in sendMail: " + ex.ToString(), ConsoleColor.Red); Utils.WriteLine("Exception in sendMail: " + ex.ToString(), ConsoleColor.Red);
} }
} }
else else
{
Utils.WriteLine($"Missing email address From = {Program.cfg.emailAddress} To = {mailAdr})", ConsoleColor.Red);
}
}
else
{ {
SM.Debug("email disabled"); SM.Debug("email disabled");
} }
@ -2482,19 +2378,7 @@ namespace AppServer
//sms-> email Sierra Wireless //sms-> email Sierra Wireless
private void sendMail_SW(string mailAdr, string mailBody) private void sendMail_SW(string mailAdr, string mailBody)
{ {
if (Program.cfg.enableEmailService)
{
if (!String.IsNullOrEmpty(Program.cfg.emailAddress) && !String.IsNullOrEmpty(mailAdr))
{
if (MainForm.IsBlacklistedAddress(mailAdr))
{
Utils.WriteLine($"sendMail_SW : The email was not sent. Email address '{mailAdr}' is in blacklist count = {MainForm.blackListAddress[mailAdr]}");
return;
}
SM.Debug("Sending mail to " + mailAdr); SM.Debug("Sending mail to " + mailAdr);
try try
{ {
MailMessage message = new MailMessage(); MailMessage message = new MailMessage();
@ -2507,22 +2391,8 @@ namespace AppServer
} }
catch (Exception ex) catch (Exception ex)
{ {
if (ex.ToString().Contains("timed out") ||
ex.ToString().Contains("the client was not authenticated"))
MainForm.HandleTimeoutError(mailAdr);
Utils.WriteLine("Exception in sendMail Sierra Wireless Gateway: "+ ex.ToString() ,ConsoleColor.Red); Utils.WriteLine("Exception in sendMail Sierra Wireless Gateway: "+ ex.ToString() ,ConsoleColor.Red);
} }
}
else
{
Utils.WriteLine($"Missing email address From = {Program.cfg.emailAddress} To = {mailAdr})", ConsoleColor.Red);
}
}
else
{
SM.Debug("email disabled");
}
} }
#endregion #endregion
@ -2553,9 +2423,8 @@ namespace AppServer
{ {
//send emergency alarm to SD //send emergency alarm to SD
//send ACK back to GW //send ACK back to GW
string code = (backupDOne == true) ? "#61#1#" : "#61#0#"; string test = (backupDOne == true) ? "#61#1#" : "#61#0#";
byte[] dataToSend = Utils.Convert_text_For_multicast("#0.0" + code); MainForm.udp.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#0.0" + test), SafeMobileLib.Utils.Convert_text_For_multicast("#0.0" + test).Length);
MainForm.udp.Send(dataToSend, dataToSend.Length);
} }
#endregion #endregion
@ -2582,10 +2451,8 @@ namespace AppServer
{ {
//send emergency alarm to SD //send emergency alarm to SD
//send ACK back to GW //send ACK back to GW
string code = (restoreDOne == true) ? "#62#1#" : "#252#0#"; string test = (restoreDOne == true) ? "#62#1#" : "#252#0#";
MainForm.udp.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#0.0" + test), SafeMobileLib.Utils.Convert_text_For_multicast("#0.0" + test).Length);
byte[] dataToSend = Utils.Convert_text_For_multicast("#0.0" + code);
MainForm.udp.Send(dataToSend, dataToSend.Length);
} }
#endregion #endregion

View File

@ -215,8 +215,8 @@ namespace AppServer
Thread.Sleep(2000); Thread.Sleep(2000);
try try
{ {
byte[] dataToSend = Utils.Convert_text_For_multicast("#0.0#210#4#Application server stopped#"); MainForm.udp.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#0.0#210#4#Application server stopped#"),
MainForm.udp.Send(dataToSend, dataToSend.Length); Utils.Convert_text_For_multicast("#0.0#210#4#Application server stopped#").Length);
// save all unhandled gps positions // save all unhandled gps positions
MainForm.DumpLocationQueueToFile(); MainForm.DumpLocationQueueToFile();
@ -241,9 +241,7 @@ namespace AppServer
Thread.Sleep(2000); Thread.Sleep(2000);
try try
{ {
MainForm.udp?.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#0.0#210#4#Application server stopped#"), SafeMobileLib.Utils.Convert_text_For_multicast("#0.0#210#4#Application server stopped#").Length);
byte[] dataToSend = Utils.Convert_text_For_multicast("#0.0#210#4#Application server stopped#");
MainForm.udp?.Send(dataToSend, dataToSend.Length);
// save all unhandled gps positions // save all unhandled gps positions
MainForm.DumpLocationQueueToFile(); MainForm.DumpLocationQueueToFile();

View File

@ -108,9 +108,8 @@ namespace AppServer
+ Program.cfg.DB_schema + ";" + Program.cfg.DB_user + ";" + Program.cfg.DB_passwd + Program.cfg.DB_schema + ";" + Program.cfg.DB_user + ";" + Program.cfg.DB_passwd
+ ";" + Program.cfg.DB_port + ";" + Program.cfg.VoicePort + ";" + ";" + Program.cfg.DB_port + ";" + Program.cfg.VoicePort + ";"
+ audibleAlerts.ToString() + ";" + MainForm.dbAccess.ToString() + ";"; + audibleAlerts.ToString() + ";" + MainForm.dbAccess.ToString() + ";";
MainForm.udp.Send(Utils.Convert_text_For_multicast("#0.0#156#" + command[1].Trim() + "#"), Utils.Convert_text_For_multicast("#0.0#156#"
byte[] dataToSend = Utils.Convert_text_For_multicast("#0.0#156#" + command[1].Trim() + "#"); + command[1].Trim() + "#").Length);
MainForm.udp.Send(dataToSend, dataToSend.Length);
MainForm.RegistrationAnswer = false; MainForm.RegistrationAnswer = false;
Int32 countWait = 0; //maxim 30 = 3 seconds Int32 countWait = 0; //maxim 30 = 3 seconds

View File

@ -172,9 +172,7 @@ namespace AppServer
test = $"#155#{rec.id}#{rec.hddLocation}#{rec.gwID}#{rec.radioGWID}#{rec.group_cpsId}#{rec.subs_imei}#{rec.startTime}#{rec.endTime}#{rec.typeSD}#{rec.calltype}#{rec.dispatcher_id}#"; test = $"#155#{rec.id}#{rec.hddLocation}#{rec.gwID}#{rec.radioGWID}#{rec.group_cpsId}#{rec.subs_imei}#{rec.startTime}#{rec.endTime}#{rec.typeSD}#{rec.calltype}#{rec.dispatcher_id}#";
MainForm.udp.Send(SafeMobileLib.Utils.Convert_text_For_multicast("#0.0" + test), SafeMobileLib.Utils.Convert_text_For_multicast("#0.0" + test).Length);
byte[] dataToSend = Utils.Convert_text_For_multicast("#0.0" + test);
MainForm.udp.Send(dataToSend, dataToSend.Length);
} }
} }
catch (Exception ex) catch (Exception ex)

View File

@ -376,8 +376,34 @@ namespace MotoTrbo_GW
} }
private void FetchAudioSettings() private void ContinueConstructor()
{ {
if (!registeredIP)
{
tabVoice.Enabled = false;
DialogResult result = FeedbackRadMessageBox.ShowExclamation("Please register your copy of MotoTrbo Gateway using the Administrative Module.\n Your IP address is:" + YourIPaddress, "Info");
if (result == DialogResult.OK)
Application.Exit();
}
else if (registeredIP && !App.isValidVersion(APP_SERVER_VERSION,
System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()))
{
DialogResult dr = RadMessageBox.Show("Please update your version of software to the latest one required by Application Server. Do you wish to update now?",
"Update required...", MessageBoxButtons.YesNo, RadMessageIcon.Exclamation);
if (dr == DialogResult.Yes)
{
CheckForUpdate(true);
Application.Exit();
}
else
Application.Exit();
}
else
{
// Get Audio settings
DBsettingsManager dbSettings = new DBsettingsManager(DBServer, DBSchema, DBUser, DBPass, DBPort); DBsettingsManager dbSettings = new DBsettingsManager(DBServer, DBSchema, DBUser, DBPass, DBPort);
string tmpSamplaRate = dbSettings.getSettingValue(0, "sampleRate"); string tmpSamplaRate = dbSettings.getSettingValue(0, "sampleRate");
@ -408,99 +434,6 @@ namespace MotoTrbo_GW
} }
}
private void ContinueConstructor()
{
if (!registeredIP)
{
tabVoice.Enabled = false;
DialogResult result = FeedbackRadMessageBox.ShowExclamation("Please register your copy of MotoTrbo Gateway using the Administrative Module.\n Your IP address is:" + YourIPaddress, "Info");
if (result == DialogResult.OK)
Application.Exit();
}
else if (registeredIP && !App.isValidVersion(APP_SERVER_VERSION,
System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()))
{
DialogResult dr = RadMessageBox.Show("Please update your version of software to the latest one required by Application Server. Do you wish to update now?",
"Update required...", MessageBoxButtons.YesNo, RadMessageIcon.Exclamation);
if (dr == DialogResult.Yes)
CheckForUpdate(true);
Application.Exit();
}
else
{
//new code
List <Gateway> listGW = new List<Gateway>();
try
{
if (!string.IsNullOrEmpty(DBServer))
{
listGW = getGWidFromDB(DBServer);
}
if (listGW.Count == 0)
{
DBServer = "127.0.0.1";
listGW = getGWidFromDB(DBServer);
}
}
catch (Exception ex)
{
SafeMobileLib.Utils.WriteLine("Ex on find automat the gateway ID:" + ex.ToString());
}
try
{
if (listGW.Count == 0)
{
FeedbackRadMessageBox.ShowError("Gateway IP not present in DB\n\r Please go to Administrative module and register this GW with IP:!!!" + DBServer, "IP missing");
System.Environment.Exit(0);
return;
}
else
{
GWID = ((Gateway)listGW[0]).Id;
source = new IniConfigSource(Main.CFG_FILE);
source.Configs["Gateway"].Set("id", GWID);
// source.Configs["NAI"].Set("peerID", ((Gateway)listGW[0]).Peer_id);
source.Save();
SafeMobileLib.Utils.WriteLine("Gateway ID is " + GWID, ConsoleColor.Cyan);
//SafeMobileLib.Utils.WriteLine("ID:" + GWID + " saved to config file.");
btGWID.Text = GWID.ToString();
}
}
catch (Exception ex)
{
SafeMobileLib.Utils.WriteLine("DB error!!!");
SafeMobileLib.Utils.WriteLine(ex.ToString());
FeedbackRadMessageBox.ShowError("DB error.\n\rPlease turn down the firewall or add an exception for the Datebase in the firewall and try again!!!\n\r DB ip:" + DBServer,
"DB error");
System.Environment.Exit(0);
//System.Windows.Forms.Application.Exit();
return;
}
//end of new code
// Get Audio settings
FetchAudioSettings();
//int asio driver object //int asio driver object
if (Main.AudioDriver == AudioDriverType.Asio) if (Main.AudioDriver == AudioDriverType.Asio)
@ -536,7 +469,91 @@ namespace MotoTrbo_GW
} }
} }
} }
//old code
/*if (GWID == -1)
{
int id = getGWidFromDB(YourIPaddress);
if (id == -1)
{
RadMessageBox.Show("Gateway IP not present in DB\n\r Please go to Administrative module and register this GW with IP:!!!" + YourIPaddress, "IP missing", MessageBoxButtons.OK, RadMessageIcon.Error);
System.Environment.Exit(0);
}
else
{
GWID = id;
source = new IniConfigSource(Main.CFG_FILE);
source.Configs["Gateway"].Set("id", id);
source.Save();
SafeMobileLib.Utils.WriteLine("ID:" + id +" saved to config file.");
}
}*/
//new code
List <Gateway> listGW = new List<Gateway>();
try
{
listGW = getGWidFromDB(YourIPaddress);
if (listGW.Count == 0)
{
if (DBServer.Contains("127.0.0.1") || (DBServer.ToUpper().Contains("LOCALHOST")))
listGW = getGWidFromDB("127.0.0.1");
}
else
{
if (GWID != -1)
{
Boolean find = false;
foreach (Gateway obj in listGW)
if (obj.Id == GWID) { find = true; break; }
if ((!find) && (DBServer.Contains("127.0.0.1") || (DBServer.ToUpper().Contains("LOCALHOST"))))
listGW = getGWidFromDB("127.0.0.1");
}
}
}
catch (Exception ex)
{
SafeMobileLib.Utils.WriteLine("Ex on find automat the gateway ID:" + ex.ToString());
}
try
{
if (listGW.Count == 0)
{
FeedbackRadMessageBox.ShowError("Gateway IP not present in DB\n\r Please go to Administrative module and register this GW with IP:!!!" + YourIPaddress, "IP missing");
System.Environment.Exit(0);
return;
}
else
{
GWID = ((Gateway)listGW[0]).Id;
source = new IniConfigSource(Main.CFG_FILE);
source.Configs["Gateway"].Set("id", GWID);
// source.Configs["NAI"].Set("peerID", ((Gateway)listGW[0]).Peer_id);
source.Save();
SafeMobileLib.Utils.WriteLine("Gateway ID is " + GWID, ConsoleColor.Cyan);
//SafeMobileLib.Utils.WriteLine("ID:" + GWID + " saved to config file.");
btGWID.Text = GWID.ToString();
}
}
catch (Exception ex)
{
SafeMobileLib.Utils.WriteLine("DB error!!!");
SafeMobileLib.Utils.WriteLine(ex.ToString());
FeedbackRadMessageBox.ShowError("DB error.\n\rPlease turn down the firewall or add an exception for the Datebase in the firewall and try again!!!\n\r DB ip:" + YourIPaddress,
"DB error");
System.Environment.Exit(0);
//System.Windows.Forms.Application.Exit();
return;
}
//end of new code
/*try /*try
{ {
@ -1257,7 +1274,7 @@ because base station {radioGwID} failed to send PTT", ConsoleColor.Red);
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse(Main.ApplicationServer), registrationPort); IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse(Main.ApplicationServer), registrationPort);
client.Connect(serverEndPoint); client.Connect(serverEndPoint);
NetworkStream clientStream = client.GetStream(); NetworkStream clientStream = client.GetStream();
YourIPaddress = (client.Client.LocalEndPoint.ToString().Split(":".ToCharArray()))[0]; YourIPaddress = (client.Client.LocalEndPoint.ToString().Split(':'))[0];
Version v = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; Version v = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;

View File

@ -452,9 +452,13 @@ namespace SafeMobileLib
BatchHistoryData batchHistObj = null; BatchHistoryData batchHistObj = null;
try try
{ {
lat = Convert.ToDouble(dr["lat"]); lat = Convert.ToDouble(dr["lat"]);
lng = Convert.ToDouble(dr["lng"]); lng = Convert.ToDouble(dr["lng"]);
timegmt = Convert.ToInt32(dr["timegmt"]); timegmt = Convert.ToInt32(dr["timegmt"]);
@ -464,22 +468,16 @@ namespace SafeMobileLib
Department = dr["department"].ToString(), Department = dr["department"].ToString(),
Unit = dr["unit"].ToString(), Unit = dr["unit"].ToString(),
Location = ((getAddress && dr["address"] != DBNull.Value) ? dr["address"].ToString() : "LAT:" + Math.Round(lat, 5).ToString() + " , LNG:" + Math.Round(lat, 5).ToString()),
Speed = (isInMile) ? ((int)(Convert.ToInt32(dr["speed"]) * 0.621371192)).ToString() : Convert.ToInt32(dr["speed"]).ToString(), Speed = (isInMile) ? ((int)(Convert.ToInt32(dr["speed"]) * 0.621371192)).ToString() : Convert.ToInt32(dr["speed"]).ToString(),
Lat = lat, Lat = lat,
Lng = lng, Lng = lng,
Address = string.Empty, Address = dr["address"].ToString(),
Time = timegmt.TimeOfDayHHMMSSLocal(!is24hours), Time = timegmt.TimeOfDayHHMMSSLocal(!is24hours),
Date = timegmt.GetDTLocalFromSeconds().Date.ToShortDateString() Date = timegmt.GetDTLocalFromSeconds().Date.ToShortDateString()
}; };
if (getAddress)
{
batchHistObj.Location = dr["address"].ToString();
batchHistObj.Address = dr["address"].ToString();
}
else
batchHistObj.Location = "LAT:" + Math.Round(lat, 5).ToString() + " , LNG:" + Math.Round(lat, 5).ToString();
} }

View File

@ -25,8 +25,6 @@ namespace SafeMobileLib
private bool isSSL = true; private bool isSSL = true;
private Int64 lastEmailTime = 0; private Int64 lastEmailTime = 0;
private Int64 startEmailServiceTime = 0; private Int64 startEmailServiceTime = 0;
public static Dictionary<string, int> blackList = new Dictionary<string, int>();
public const int MAX_ATTEMPTS = 100;
// blank constructor in order to be used in Email Checking // blank constructor in order to be used in Email Checking
public EmailServerSSL() public EmailServerSSL()
@ -380,46 +378,11 @@ namespace SafeMobileLib
return ret; return ret;
} }
public static void HandleBlacklist(string key)
{
// add key to backlist
if (!blackList.ContainsKey(key))
blackList.Add(key, MAX_ATTEMPTS);
}
public static bool IsBlacklisted(string key)
{
if (!blackList.ContainsKey(key))
return false;
// avoid to connect to pop3 MAX_ATTEMPTS times => give another chance to try to connect to pop 3 when count = 0
int count = blackList[key];
if (count == 0)
{
blackList.Remove(key);
return false;
}
blackList[key] = count - 1;
return true;
}
/// <summary> /// <summary>
/// Connect to the Pop Server in order to be used to get the emails /// Connect to the Pop Server in order to be used to get the emails
/// </summary> /// </summary>
private void ConnectEmailPopServer() private void ConnectEmailPopServer()
{ {
if (IsBlacklisted(serverIP))
{
Utils.WriteLine($"ConnectEmailPopServer : Could not conenct to the pop server '{serverIP}'. The pop server '{serverIP}' is in blacklist count = {blackList[serverIP]}");
return;
}
Thread t = new Thread(() => Thread t = new Thread(() =>
{ {
ConnectAsync(); ConnectAsync();
@ -430,17 +393,8 @@ namespace SafeMobileLib
private void ConnectAsync() private void ConnectAsync()
{ {
try
{
if (popClient != null && popClient.Connected) if (popClient != null && popClient.Connected)
popClient.Disconnect(); popClient.Disconnect();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
popClient = null; popClient = null;
popClient = new Pop3Client(); popClient = new Pop3Client();
@ -458,25 +412,18 @@ namespace SafeMobileLib
Console.ForegroundColor = ConsoleColor.Yellow; Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("PopServerNotFoundException -> " + ee.ToString()); Console.WriteLine("PopServerNotFoundException -> " + ee.ToString());
Console.ForegroundColor = ConsoleColor.Gray; Console.ForegroundColor = ConsoleColor.Gray;
HandleBlacklist(serverIP);
} }
catch (InvalidLoginException e) catch (InvalidLoginException e)
{ {
Console.ForegroundColor = ConsoleColor.Yellow; Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("InvalidLoginException -> " + e.ToString()); Console.WriteLine("InvalidLoginException -> " + e.ToString());
Console.ForegroundColor = ConsoleColor.Gray; Console.ForegroundColor = ConsoleColor.Gray;
HandleBlacklist(serverIP);
} }
catch (Exception ex) catch (Exception ex)
{ {
Console.ForegroundColor = ConsoleColor.Red; Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("ConnectEmailPopServer -> " + ex.ToString()); Console.WriteLine("ConnectEmailPopServer -> " + ex.ToString());
Console.ForegroundColor = ConsoleColor.Gray; Console.ForegroundColor = ConsoleColor.Gray;
HandleBlacklist(serverIP);
} }
} }

View File

@ -91,8 +91,7 @@ namespace SafeMobileLib
{ {
if (udpMulticast != null) if (udpMulticast != null)
{ {
byte[] dataToSend = Utils.Convert_text_For_multicast("#" + seqID + test); udpMulticast.Send(Utils.Convert_text_For_multicast("#" + seqID + test), Utils.Convert_text_For_multicast("#" + seqID + test).Length);
udpMulticast.Send(dataToSend, dataToSend.Length);
} }
else else
{ {

View File

@ -42,11 +42,11 @@ namespace SafeMobileLib
recv = s.Receive(b); recv = s.Receive(b);
else else
break;//break if socket == null break;//break if socket == null
if (recv == 0) if (recv == 0)
continue;//continue if return nr bytes == 0 continue;//continue if return nr bytes == 0
if (OnNewDataRecv != null)
{
byte[] tmp = new byte[recv]; byte[] tmp = new byte[recv];
for (int i = 0; i < recv; i++) for (int i = 0; i < recv; i++)
{ {
@ -56,14 +56,22 @@ namespace SafeMobileLib
byte[] decByte = Encrypted ? Encryption.Decrypt(tmp, EncryptionAlgorithm.Des64) : tmp; byte[] decByte = Encrypted ? Encryption.Decrypt(tmp, EncryptionAlgorithm.Des64) : tmp;
// trigger event // trigger event
if (OnNewDataRecv != null)
OnNewDataRecv(decByte, decByte.Length); OnNewDataRecv(decByte, decByte.Length);
}
if (OnNewDataReceived != null)
{
byte[] tmp = new byte[recv];
for (int i = 0; i < recv; i++)
{
tmp[i] = b[i];
}
byte[] decByte = Encrypted ? Encryption.Decrypt(tmp, EncryptionAlgorithm.Des64) : tmp;
// trigger event // trigger event
if (OnNewDataReceived != null)
OnNewDataReceived(mcastGroup, decByte, decByte.Length); OnNewDataReceived(mcastGroup, decByte, decByte.Length);
}
if (s == null) if (s == null)
@ -100,19 +108,27 @@ namespace SafeMobileLib
byte[] b = new byte[65507]; byte[] b = new byte[65507];
Thread.Sleep(1); Thread.Sleep(1);
int recv = s.Receive(b); int recv = s.Receive(b);
if (OnNewDataRecv != null)
{
byte[] tmp = new byte[recv]; byte[] tmp = new byte[recv];
for (int i = 0; i < recv; i++) for (int i = 0; i < recv; i++)
{ {
tmp[i] = b[i]; tmp[i] = b[i];
} }
if (this.OnNewDataRecv != null) if (this.OnNewDataRecv != null)
this.OnNewDataRecv(tmp, tmp.Length); this.OnNewDataRecv(tmp, tmp.Length);
}
if (OnNewDataReceived != null)
{
byte[] tmp = new byte[recv];
for (int i = 0; i < recv; i++)
{
tmp[i] = b[i];
}
if (this.OnNewDataReceived != null) if (this.OnNewDataReceived != null)
this.OnNewDataReceived(mcastGroup, tmp, tmp.Length); this.OnNewDataReceived(mcastGroup, tmp, tmp.Length);
}
if (s == null) if (s == null)
{ {
@ -201,17 +217,16 @@ namespace SafeMobileLib
IPEndPoint ipep = new IPEndPoint(myIP, port); IPEndPoint ipep = new IPEndPoint(myIP, port);
s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1); s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
s.Bind(ipep); s.Bind(ipep);
IPAddress ip = IPAddress.Parse(mcastGroup); IPAddress ip = IPAddress.Parse(mcastGroup);
s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip, myIP)); s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip, myIP));
s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, int.Parse("1")); s.SetSocketOption(SocketOptionLevel.IP,
SocketOptionName.MulticastTimeToLive, int.Parse("1"));
listenThread = new Thread(new ThreadStart(Listen)); listenThread = new Thread(new ThreadStart(Listen));
listenThread.IsBackground = true; listenThread.IsBackground = true;
} }
if (listenThread != null) if (listenThread != null)
listenThread.Start(); listenThread.Start();
ret = true; ret = true;
Utils.WriteLine($"++++++++++++++++++++++++++++++++++++++++++\nUdpMulticast bind on {mcastGroup}:{port} Ethernet: {myIP}\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); Utils.WriteLine($"++++++++++++++++++++++++++++++++++++++++++\nUdpMulticast bind on {mcastGroup}:{port} Ethernet: {myIP}\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
@ -228,14 +243,12 @@ namespace SafeMobileLib
bool ret = false; bool ret = false;
working = true; working = true;
useThreadPool = true; useThreadPool = true;
try try
{ {
if (s == null) if (s == null)
{ {
s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
} }
if (s != null) if (s != null)
{ {
Utils.WriteLine(String.Format("[### {0:H:mm:ss} ###] Port multi cast {1}", DateTime.Now, port)); Utils.WriteLine(String.Format("[### {0:H:mm:ss} ###] Port multi cast {1}", DateTime.Now, port));
@ -244,7 +257,8 @@ namespace SafeMobileLib
s.Bind(ipep); s.Bind(ipep);
IPAddress ip = IPAddress.Parse(mcastGroup); IPAddress ip = IPAddress.Parse(mcastGroup);
s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip, IPAddress.Any)); s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip, IPAddress.Any));
s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, int.Parse("1")); s.SetSocketOption(SocketOptionLevel.IP,
SocketOptionName.MulticastTimeToLive, int.Parse("1"));
ThreadPool.QueueUserWorkItem(new WaitCallback(Listen_pool)); ThreadPool.QueueUserWorkItem(new WaitCallback(Listen_pool));
@ -268,7 +282,6 @@ namespace SafeMobileLib
{ {
s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
} }
if (s != null) if (s != null)
{ {
Utils.WriteLine(String.Format("[### {0:H:mm:ss} ###] Port multi cast {1}", DateTime.Now, port)); Utils.WriteLine(String.Format("[### {0:H:mm:ss} ###] Port multi cast {1}", DateTime.Now, port));
@ -277,14 +290,13 @@ namespace SafeMobileLib
s.Bind(ipep); s.Bind(ipep);
IPAddress ip = IPAddress.Parse(mcastGroup); IPAddress ip = IPAddress.Parse(mcastGroup);
s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip, IPAddress.Any)); s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip, IPAddress.Any));
s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, int.Parse("1")); s.SetSocketOption(SocketOptionLevel.IP,
SocketOptionName.MulticastTimeToLive, int.Parse("1"));
listenThread = new Thread(new ThreadStart(Listen_Decoded)); listenThread = new Thread(new ThreadStart(Listen_Decoded));
listenThread.IsBackground = true; listenThread.IsBackground = true;
} }
if (listenThread != null) if (listenThread != null)
listenThread.Start(); listenThread.Start();
ret = true; ret = true;
} }
catch (Exception ex) catch (Exception ex)

View File

@ -441,10 +441,8 @@ namespace SafeMobileLib
Int32 tmp = cmdok.Length + 1; Int32 tmp = cmdok.Length + 1;
tmp += tmp.ToString().Length; tmp += tmp.ToString().Length;
String TMPcmdok = "#" + tmp.ToString() + cmdok; String TMPcmdok = "#" + tmp.ToString() + cmdok;
if (tmp != TMPcmdok.Length) if (tmp != TMPcmdok.Length) cmdok = "#" + TMPcmdok.Length + cmdok;
cmdok = "#" + TMPcmdok.Length + cmdok; else cmdok = TMPcmdok;
else
cmdok = TMPcmdok;
System.Text.Encoding enc = System.Text.Encoding.ASCII; System.Text.Encoding enc = System.Text.Encoding.ASCII;
byte[] buf = enc.GetBytes(cmdok); byte[] buf = enc.GetBytes(cmdok);

View File

@ -263,24 +263,19 @@ namespace SipComponent
} }
else else
_localIPaddress = localIPAddress; _localIPaddress = localIPAddress;
_sipDomainPort = sipDomainPort; _sipDomainPort = sipDomainPort;
_sipClient = CreateSipClientClass(sipDomain, _sipDomainPort, _localIPaddress, localSipPort, userName, password, requestTimeout); _sipClient = CreateSipClientClass(sipDomain, _sipDomainPort, _localIPaddress, localSipPort, userName, password, requestTimeout);
_bufferMiliseconds = bufferMiliseconds; _bufferMiliseconds = bufferMiliseconds;
// Registration Timer // Registration Timer
_registrationInterval = registrationInterval; _registrationInterval = registrationInterval;
_registrationData = new RegistrationData(userName, _registrationInterval + 2); _registrationData = new RegistrationData(userName, _registrationInterval + 2);
System.Timers.Timer registrationTimer = new System.Timers.Timer(); System.Timers.Timer registrationTimer = new System.Timers.Timer();
// Set up the registration timer // Set up the registration timer
registrationTimer.Interval = _registrationInterval * 1000; registrationTimer.Interval = _registrationInterval * 1000;
registrationTimer.Elapsed += _registrationTimer_Elapsed; registrationTimer.Elapsed += _registrationTimer_Elapsed;
_sipID_regTimer_regStatus_Dict.Add(userName, _sipID_regTimer_regStatus_Dict.Add(userName,
new Tuple<System.Timers.Timer, RegistrationStatus>(registrationTimer, RegistrationStatus.RegistrationNotStarted new Tuple<System.Timers.Timer, RegistrationStatus>(registrationTimer, RegistrationStatus.RegistrationNotStarted
)); ));
_IDsregisteredList.Add(userName); _IDsregisteredList.Add(userName);
StartRegistrationTimer(); StartRegistrationTimer();
@ -309,7 +304,6 @@ namespace SipComponent
throw new ObjectDisposedException("SipClientClass"); throw new ObjectDisposedException("SipClientClass");
if (idToInvite == null) if (idToInvite == null)
throw new ArgumentNullException("idToInvite"); throw new ArgumentNullException("idToInvite");
lock (_lockerSipDialog) lock (_lockerSipDialog)
{ {
if (!_IDsentInviteDict.ContainsKey(idToInvite) && !_IDreceivedInviteDict.ContainsKey(idToInvite) if (!_IDsentInviteDict.ContainsKey(idToInvite) && !_IDreceivedInviteDict.ContainsKey(idToInvite)
@ -330,7 +324,6 @@ namespace SipComponent
throw new ObjectDisposedException("SipClientClass"); throw new ObjectDisposedException("SipClientClass");
if (groupIDtoInvite == null) if (groupIDtoInvite == null)
throw new ArgumentNullException("groupIDtoInvite"); throw new ArgumentNullException("groupIDtoInvite");
// Check if registered to the group id // Check if registered to the group id
lock (_lockerSipDialog) lock (_lockerSipDialog)
{ {
@ -349,7 +342,6 @@ namespace SipComponent
{ {
if (_sipClassClosed) if (_sipClassClosed)
throw new ObjectDisposedException("SipClientClass"); throw new ObjectDisposedException("SipClientClass");
Task t = null; Task t = null;
CancelInvite_private(idToCancel, out t); CancelInvite_private(idToCancel, out t);
} }
@ -378,7 +370,6 @@ namespace SipComponent
{ {
return dialog.CallID == _IDsentInviteDict[idToCancel].CallID; return dialog.CallID == _IDsentInviteDict[idToCancel].CallID;
}); });
if (d != null) if (d != null)
{ {
//Send Cancel Request //Send Cancel Request
@ -396,7 +387,6 @@ namespace SipComponent
} }
}, d); }, d);
} }
// Remove from dict // Remove from dict
_IDsentInviteDict.Remove(idToCancel); _IDsentInviteDict.Remove(idToCancel);
_IDsCalledByMeList.Remove(idToCancel); _IDsCalledByMeList.Remove(idToCancel);
@ -595,7 +585,6 @@ namespace SipComponent
{ {
if (_sipClassClosed) if (_sipClassClosed)
throw new ObjectDisposedException("SipClientClass"); throw new ObjectDisposedException("SipClientClass");
lock (_lockerSipDialog) lock (_lockerSipDialog)
{ {
if (_IDdialogTuple.ContainsKey(idToSendVoice)) if (_IDdialogTuple.ContainsKey(idToSendVoice))
@ -614,11 +603,8 @@ namespace SipComponent
{ {
if (_sipClassClosed) if (_sipClassClosed)
throw new ObjectDisposedException("SipClientClass"); throw new ObjectDisposedException("SipClientClass");
if (idToRequestGps != null)
if (idToRequestGps == null) {
throw new ArgumentNullException("idToRequestGps");
// Send Gps request for Linx // Send Gps request for Linx
// [#msgLen]#seqID#154# // [#msgLen]#seqID#154#
string cmdText = string.Format("#{0}#154#", seqID); string cmdText = string.Format("#{0}#154#", seqID);
@ -636,6 +622,9 @@ namespace SipComponent
; // Probably timeout exception, do not do anything ; // Probably timeout exception, do not do anything
} }
}); });
}
else
throw new ArgumentNullException("idToRequestGps");
} }
@ -647,10 +636,8 @@ namespace SipComponent
{ {
if (_sipClassClosed) if (_sipClassClosed)
throw new ObjectDisposedException("SipClientClass"); throw new ObjectDisposedException("SipClientClass");
if (linxID != null)
if (linxID == null) {
throw new ArgumentNullException("linxID");
// Send [#msgLen]#seqID#238# // Send [#msgLen]#seqID#238#
string textToSend = string.Format("#{0}#238#", _rand.Next().ToString()); string textToSend = string.Format("#{0}#238#", _rand.Next().ToString());
string cmdToSend = AddMsgLenForMBus(textToSend); string cmdToSend = AddMsgLenForMBus(textToSend);
@ -666,7 +653,9 @@ namespace SipComponent
// Do nothing // Do nothing
} }
}); });
}
else
throw new ArgumentNullException("linxID");
} }
/// <summary> /// <summary>
@ -680,12 +669,10 @@ namespace SipComponent
{ {
if (_sipClassClosed) if (_sipClassClosed)
throw new ObjectDisposedException("SipClientClass"); throw new ObjectDisposedException("SipClientClass");
if (idToSendSMS != null && text != null) if (idToSendSMS != null && text != null)
{ {
bool sendSipMessage = true; bool sendSipMessage = true;
string unconfirmedSmsKey = null; string unconfirmedSmsKey = null;
if (_smsConfirmationFromServer) if (_smsConfirmationFromServer)
{ {
unconfirmedSmsKey = idToSendSMS + text.GetHashCode(); unconfirmedSmsKey = idToSendSMS + text.GetHashCode();
@ -704,7 +691,6 @@ namespace SipComponent
} }
} }
} }
if (sendSipMessage) if (sendSipMessage)
{ {
// Create a new thread on which: // Create a new thread on which:
@ -757,16 +743,15 @@ namespace SipComponent
throw new ArgumentNullException("text"); throw new ArgumentNullException("text");
} }
private Message GenerateSipMessage(string destinationID, string senderID, string sipServer, int sipServerPort, string text) private Message GenerateSipMessage(string destinationID, string senderID, string sipServer,
int sipServerPort, string text)
{ {
Message sipMessage = new Message() Message sipMessage = new Message();
{ sipMessage.Uri = "sip:" + destinationID + "@" + sipServer + ":" + sipServerPort;
Uri = $"sip:{destinationID}@{sipServer}:{sipServerPort}", sipMessage.From = new ContactInfo(string.Format("sip:{0}@{1}", senderID, sipServer));
From = new ContactInfo($"sip:{senderID}@{sipServer}"), sipMessage.To = new ContactInfo(string.Format("sip:{0}@{1}", destinationID, sipServer));
To = new ContactInfo($"sip:{destinationID}@{sipServer}"), sipMessage.ContentType = "text/plain;charset=UTF-8";
ContentType = "text/plain;charset=UTF-8", sipMessage.Body = text;
Body = text
};
return sipMessage; return sipMessage;
} }
@ -848,12 +833,10 @@ namespace SipComponent
if (!_sipClassClosed) if (!_sipClassClosed)
{ {
_sipClassClosed = true; _sipClassClosed = true;
// Send ARS OFF and disconnect from socket IO // Send ARS OFF and disconnect from socket IO
if (_sendArsOnOff) if (_sendArsOnOff)
_socketIOClass.SendArs(new ArsInfo(false, "0", UserName)); _socketIOClass.SendArs(new ArsInfo(false, "0", UserName));
_socketIOClass.Disconect(); _socketIOClass.Disconect();
// //
List<string> sipIDs = new List<string>(); List<string> sipIDs = new List<string>();
Task task = null; Task task = null;
@ -909,7 +892,6 @@ namespace SipComponent
// Stop sip class // Stop sip class
_sipClient.Disconnect(); _sipClient.Disconnect();
}); });
if (!async) if (!async)
t.Wait(); t.Wait();
} }
@ -929,8 +911,6 @@ namespace SipComponent
zeroRegistrationData = new RegistrationData(id, 0, true); zeroRegistrationData = new RegistrationData(id, 0, true);
else else
zeroRegistrationData = new RegistrationData(id, 0); zeroRegistrationData = new RegistrationData(id, 0);
_sipID_regTimer_regStatus_Dict[id].Item1.Stop(); _sipID_regTimer_regStatus_Dict[id].Item1.Stop();
SendSipRegister(zeroRegistrationData); SendSipRegister(zeroRegistrationData);
} }
@ -1418,10 +1398,9 @@ namespace SipComponent
string lastWord = source.Substring(source.LastIndexOf(' ') + 1); string lastWord = source.Substring(source.LastIndexOf(' ') + 1);
if (lastWord.Contains("delivered")) if (lastWord.Contains("delivered"))
return true; return true;
else if (lastWord.Contains("failed"))
if (lastWord.Contains("failed"))
return false; return false;
else
throw new ApplicationException("Error on parsing the sms confirmation from sip server"); throw new ApplicationException("Error on parsing the sms confirmation from sip server");
} }
@ -1439,13 +1418,11 @@ namespace SipComponent
// Extract ip and port where to send voice to simoco // Extract ip and port where to send voice to simoco
IPAddress ipToSendAudio = null; IPAddress ipToSendAudio = null;
int portToSendAudio; int portToSendAudio;
if (IPAddress.TryParse(receivedSDP.Connection.Address, out ipToSendAudio)) if (IPAddress.TryParse(receivedSDP.Connection.Address, out ipToSendAudio))
{ {
portToSendAudio = receivedSDP.Media[0].Port; portToSendAudio = receivedSDP.Media[0].Port;
} }
else else throw new ApplicationException("Canot determine ip where to send audio");
throw new ApplicationException("Canot determine ip where to send audio");
// Creez clientul de UDP conectat la portul pe care voi primi voce // Creez clientul de UDP conectat la portul pe care voi primi voce
UdpClient udpClient = new UdpClient(localRTPport); UdpClient udpClient = new UdpClient(localRTPport);
@ -1586,9 +1563,9 @@ namespace SipComponent
private SipClient CreateSipClientClass(string sipDomain, int sipDomainPort, string localIPaddress, int localSipPort, string userName, string password, int requestTimeout) private SipClient CreateSipClientClass(string sipDomain, int sipDomainPort, string localIPaddress, int localSipPort, string userName, string password, int requestTimeout)
{ {
SipClient sipClient;
// Set up the master SIP class // Set up the master SIP class
SipClient sipClient = new SipClient(sipDomain, sipDomainPort, Independentsoft.Sip.ProtocolType.Udp, userName, password); sipClient = new SipClient(sipDomain, sipDomainPort, Independentsoft.Sip.ProtocolType.Udp, userName, password);
sipClient.LocalIPEndPoint = new IPEndPoint(IPAddress.Parse(localIPaddress), localSipPort); sipClient.LocalIPEndPoint = new IPEndPoint(IPAddress.Parse(localIPaddress), localSipPort);
// Turn on logging // Turn on logging
//sipClient.Logger = new Logger(AppDomain.CurrentDomain.BaseDirectory + "\\sipLog.txt"); //sipClient.Logger = new Logger(AppDomain.CurrentDomain.BaseDirectory + "\\sipLog.txt");
@ -1613,7 +1590,6 @@ namespace SipComponent
int rtpPort = ReturnAvailablePort(); int rtpPort = ReturnAvailablePort();
SessionDescription sdp = CreateSDP(rtpPort); SessionDescription sdp = CreateSDP(rtpPort);
Invite inv = new Invite(); Invite inv = new Invite();
inv.Uri = "sip:" + idToCall + "@" + sipServerIP; inv.Uri = "sip:" + idToCall + "@" + sipServerIP;
inv.From = new ContactInfo("sip:" + sipID.ToString() + "@" + sipServerIP); inv.From = new ContactInfo("sip:" + sipID.ToString() + "@" + sipServerIP);
@ -1674,7 +1650,6 @@ namespace SipComponent
private void SendSipRegister(object registrationDataObj) private void SendSipRegister(object registrationDataObj)
{ {
string sipServerIP = _sipClient.Domain; string sipServerIP = _sipClient.Domain;
RegistrationData regData = (RegistrationData)registrationDataObj; RegistrationData regData = (RegistrationData)registrationDataObj;
string sipIDfrom = _sipClient.Username; string sipIDfrom = _sipClient.Username;
string sipIDto = regData.SipID; string sipIDto = regData.SipID;
@ -1683,8 +1658,12 @@ namespace SipComponent
Register reg = new Register(); Register reg = new Register();
reg.Uri = "sip:" + sipServerIP; reg.Uri = "sip:" + sipServerIP;
reg.From = new ContactInfo( sipIDfrom.ToString(), $"sip:{sipIDfrom}@{sipServerIP}"); reg.From = new ContactInfo(
reg.To = new ContactInfo( sipIDto.ToString(), $"sip:{sipIDto}@{sipServerIP}"); sipIDfrom.ToString(),
"sip:" + sipIDfrom + "@" + sipServerIP);
reg.To = new ContactInfo(
sipIDto.ToString(),
"sip:" + sipIDto.ToString() + "@" + sipServerIP);
reg.Contact = new Contact("sip:" + sipIDfrom.ToString() + "@" + _sipClient.LocalIPEndPoint.ToString()); reg.Contact = new Contact("sip:" + sipIDfrom.ToString() + "@" + _sipClient.LocalIPEndPoint.ToString());
reg.Expires = expiresValue; reg.Expires = expiresValue;
@ -1784,7 +1763,6 @@ namespace SipComponent
{ {
SendSipRegister(state); SendSipRegister(state);
}, _registrationData); }, _registrationData);
// Start registration timer // Start registration timer
_sipID_regTimer_regStatus_Dict[UserName].Item1.Start(); _sipID_regTimer_regStatus_Dict[UserName].Item1.Start();
} }
@ -1829,11 +1807,9 @@ namespace SipComponent
{ {
rtpPort += 2; rtpPort += 2;
} }
if (rtpPort < MaxRtpPortNumber) if (rtpPort < MaxRtpPortNumber)
return rtpPort; return rtpPort;
else
throw new SipClassException( throw new SipClassException(
string.Format("Nu gasesc port liber in range-ul {0} - {1}", MinRtpPortNumber, MaxRtpPortNumber)); string.Format("Nu gasesc port liber in range-ul {0} - {1}", MinRtpPortNumber, MaxRtpPortNumber));
} }
@ -1845,8 +1821,10 @@ namespace SipComponent
{ {
return invite.SessionDescription.Media[0].Port == portNb; return invite.SessionDescription.Media[0].Port == portNb;
}); });
if (inv != null)
return (inv != null); return true;
else
return false;
} }
private bool IsPortAllreadyInUse(int portNumber) private bool IsPortAllreadyInUse(int portNumber)
@ -1865,11 +1843,14 @@ namespace SipComponent
public static bool ValidRtpPort(int rtpPort) public static bool ValidRtpPort(int rtpPort)
{ {
if (rtpPort < 1024 || rtpPort > 65534) if (rtpPort < 1024 || rtpPort > 65534)
{
return false; return false;
}
if (rtpPort % 2 == 1) else if (rtpPort % 2 == 1)
{
return false; return false;
}
else
return true; return true;
} }
@ -1889,6 +1870,11 @@ namespace SipComponent
private bool IsInSameSubnet(IPAddress address2, IPAddress address, IPAddress subnetMask) private bool IsInSameSubnet(IPAddress address2, IPAddress address, IPAddress subnetMask)
{ {
IPAddress network1 = GetNetworkAddress(address, subnetMask); IPAddress network1 = GetNetworkAddress(address, subnetMask);

View File

@ -837,26 +837,17 @@ namespace SubscriberAndUserManager
private void SendBackupListRequest() private void SendBackupListRequest()
{ {
if(MainForm.udp != null) if(MainForm.udp != null)
{ MainForm.udp.Send(Utils.Convert_text_For_multicast("#0.0#53#1#"), Utils.Convert_text_For_multicast("#0.0#53#1#").Length);
byte[] dataToSend = Utils.Convert_text_For_multicast("#0.0#53#1#");
MainForm.udp.Send(dataToSend, dataToSend.Length);
}
} }
private void SendBackupRequest() private void SendBackupRequest()
{ {
if (MainForm.udp != null) if (MainForm.udp != null)
{ MainForm.udp.Send(Utils.Convert_text_For_multicast("#0.0#51#1#"), Utils.Convert_text_For_multicast("#0.0#51#1#").Length);
byte[] dataToSend = Utils.Convert_text_For_multicast("#0.0#51#1#");
MainForm.udp.Send(dataToSend, dataToSend.Length);
}
} }
private void SendRestoreRequest(string filename) private void SendRestoreRequest(string filename)
{ {
if (MainForm.udp != null) if (MainForm.udp != null)
{ MainForm.udp.Send(Utils.Convert_text_For_multicast("#0.0#52#" + filename + "#"), Utils.Convert_text_For_multicast("#0.0#52#" + filename + "#").Length);
byte[] dataToSend = Utils.Convert_text_For_multicast("#0.0#52#" + filename + "#");
MainForm.udp.Send(dataToSend, dataToSend.Length);
}
} }
delegate void UpdateList(string fileNames); delegate void UpdateList(string fileNames);

View File

@ -112,9 +112,7 @@
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None> </None>
<None Include="prebuild.sh" /> <None Include="prebuild.sh" />
<None Include="RunMessagesPartitioning.bat"> <None Include="RunMessagesPartitioning.bat" />
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<BootstrapperPackage Include=".NETFramework,Version=v4.5"> <BootstrapperPackage Include=".NETFramework,Version=v4.5">
@ -146,9 +144,7 @@
<Content Include="7toLatest7.sql"> <Content Include="7toLatest7.sql">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content> </Content>
<Content Include="call_messages_partitioning.sql"> <Content Include="call_messages_partitioning.sql" />
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="CreateMissingForeignKeys.sql"> <Content Include="CreateMissingForeignKeys.sql">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content> </Content>
@ -158,12 +154,8 @@
<Content Include="CreateMissingPrimaryKeys.sql"> <Content Include="CreateMissingPrimaryKeys.sql">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content> </Content>
<Content Include="generate_partitioning_of_an_existing_table_by_date_unix_time.sql"> <Content Include="generate_partitioning_of_an_existing_table_by_date_unix_time.sql" />
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <Content Include="get_query_partitioning_of_an_existing_table_by_date_unix_time.sql" />
</Content>
<Content Include="get_query_partitioning_of_an_existing_table_by_date_unix_time.sql">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="NewFields.sql"> <Content Include="NewFields.sql">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content> </Content>