using System; using System.Collections.Generic; using System.Linq; using System.Text; using SafeMobileLib; using SafeMobileLib.MessageDecoders; using System.Collections; using System.Net.Mail; using System.Windows.Forms; using System.IO; using System.ComponentModel; using System.Diagnostics; using System.Net.Mime; using SocketIOComponent; namespace AppServer { public class MulticastListener { private string messageBusIP; private int messageBusPort; private string seqID; private Hashtable ht_vRecording; private Hashtable Privatecall_ACK_Recording; private VoiceRecording vRecording; private DBmanager DB; internal DBuserManager dbuser; private DBvehiclesManager dbvehs; internal DBsubsOperationManager dbsubsoperManage; private DBcallPatchManager dbCallPatch; #region code for zone private volatile static ArrayList ZoneList = new ArrayList(); private volatile static ArrayList LandList = new ArrayList(); private volatile static List UserListTMP = new List(); private volatile static ArrayList ImeitoMADEOFFList = new ArrayList(); private volatile static List VehicleListTMP = new List(); public volatile static List UserReportTimeListTMP = new List(); private volatile static List VehLastPos = new List(); private volatile static List GatewayListTMP = new List(); public volatile static Hashtable GatewayList = new Hashtable(); public volatile static Hashtable UserList = new Hashtable(); public volatile static Hashtable VehicleList = new Hashtable(); public volatile static Hashtable MobileVehicleList = new Hashtable(); public volatile static Hashtable emailHT = new Hashtable(); private volatile static ArrayList ZoneListTMP = new ArrayList(); private volatile static ArrayList LandListTMP = new ArrayList(); private volatile static Hashtable VehListTMP = new Hashtable(); private volatile static Hashtable VehImeiStatus = new Hashtable(); private volatile static Hashtable EmergencyHash = new Hashtable(); private volatile static ArrayList RadioListIP = new ArrayList(); private volatile Int32 countErrorLoc = 0; private static System.Threading.Timer tZone; public static readonly object locker = new object(); #endregion #region emai stuff private EmailServerSSL sslServer; private static System.Threading.Timer tCheckMail; private static System.Threading.Timer tCheckSMS; private static System.Threading.Timer tCheckARS; private static System.Threading.Timer EmergTime; private static System.Threading.Timer tCheckReportMail; private static System.Threading.Timer tCheckTickets; #endregion #region create a usb3000 decoder object private USB3000 usb3000 = null; private MainForm parent; #endregion private volatile Boolean ARSoff = false; public MulticastListener(string messageBusIP, int messageBusPort, MainForm _parent) { SM.Debug("Constructor for MulticastListener start on IP " + messageBusIP + ":" + messageBusPort); this.messageBusIP = messageBusIP; this.messageBusPort = messageBusPort; ht_vRecording = new Hashtable(); Privatecall_ACK_Recording = new Hashtable(); // create the udp only if not created if (MainForm.udp == null) { MainForm.udp = new UdpMulticast(messageBusIP, messageBusPort); MainForm.udp.OnNewDataRecv += new UdpMulticast.newData4Send(udp_OnNewDataRecv); } if (Program.cfg.enableEmailService) { //email server ini SM.Debug("Turning on EmailService on " + Program.cfg.emailAddress); sslServer = new EmailServerSSL(Program.cfg.pop3Server, Program.cfg.pop3Port, Program.cfg.emailAddress, Program.cfg.emailPassword, Program.cfg.popSSLState); sslServer.setLastEmailTime(Program.cfg.lastEmailTime); } else { SM.Debug("EmailService is disabled from admin module"); } backup = new DBbackup(Program.cfg.DB_user, Program.cfg.DB_schema, Program.cfg.DB_IP); reloadEmergHashes(); SM.Debug("Constructor for MulticastListener end"); parent = _parent; } /// /// Add a new recording file path /// /// private void OnRecordingFileWritten(string filePath) { if (usb3000 != null) usb3000.AddRecordingInDecodingQueue(filePath); } /// /// Opens Multicast Connection and start all timers which checks for different things in the DB /// public void Start() { firstStartProccesStatus = true; if (!MainForm.UdpMulticastConnectionStatus) MainForm.UdpMulticastConnectionStatus = MainForm.udp.StartListen(Program.cfg.LocalIPAddress); if (!MainForm.UdpMulticastConnectionStatus) { FeedbackRadMessageBox.ShowError("Multicast Can't connect to " + messageBusIP + ".Please check your network settings.", "App Server Multicast Error"); try { Utils.WriteEventLog(Program.COMPANY, "Multicast Can't connect to " + messageBusIP + ".Please check your network settings.", EventLogEntryType.Information, 3152); } catch (Exception exe) { SM.Debug("Unable to write log Event ex:" + exe.ToString()); } //System.Environment.Exit(0); System.Windows.Forms.Application.Exit(); } SM.Debug("MulticastListener started!!!!"); //start zone timer... refresh time 5 min tZone = new System.Threading.Timer(ComputeZones, null, new TimeSpan(0, 0, 0), new TimeSpan(0, 5, 0)); //start email timer... refresh time 1 min tCheckMail = new System.Threading.Timer(CheckMail, null, new TimeSpan(0, 0, 0), new TimeSpan(0, 1, 0)); //report to email tCheckReportMail = new System.Threading.Timer(Check4ReportEmail, null, new TimeSpan(0, 0, 0), new TimeSpan(0, 0, 20)); //sms tCheckSMS = new System.Threading.Timer(Check4SMS, null, new TimeSpan(0, 0, 0), new TimeSpan(0, 1, 0)); //ars tCheckARS = new System.Threading.Timer(Check4ARS, null, new TimeSpan(0, 0, 0), new TimeSpan(0, 0, 5)); //check for tickets if (MainForm.Job_ticking_count > 0) tCheckTickets = new System.Threading.Timer(Check4Tickets, null, new TimeSpan(0, 0, 0), new TimeSpan(0, 0, 21)); } void udp_OnNewDataRecv(byte[] data, int dataLen) { string str = System.Text.Encoding.ASCII.GetString(data, 0, dataLen); try { if (!MainForm.error) BussMessageParser(data, dataLen); else SM.Debug("Message received but no Dongle present"); } catch (Exception ex) { Utils.WriteLine("udp_OnNewDataRecv eror: "+ ex.ToString(), ConsoleColor.Red); } } /// /// Parses the information from multicast /// /// /// /// private bool BussMessageParser(byte[] rawData, int actualLen) { string data = System.Text.Encoding.ASCII.GetString(rawData, 0, actualLen); string[] tempArr = data.Split("#".ToCharArray()); if ((tempArr.Length == 0) || (tempArr.Length == 1)) { SM.Debug("incorect message=" + data); return false; } int messLen = Convert.ToInt32(tempArr[1]); if (actualLen != messLen) { Console.WriteLine("message length({0}) != actual length({1})", messLen, actualLen); return false; } seqID = tempArr[2]; int opCode = Convert.ToInt32(tempArr[3]); string ip2; string radioID; string test; int gwID; int radiogwID; int remoteID; int SDuserId;int GroupId; byte[] buf;string posgresPath; string dirBackup; switch (opCode) { case 101: SM.Debug("got ALL CALL from SD"); try { //ignore call patching signals if (tempArr.Length > 6) { if (tempArr[6] == "1") break; } ip2 = tempArr[5]; string[] dataArr = tempArr[4].Split(".".ToCharArray()); //GW indentifiers gwID = Convert.ToInt32(dataArr[0]); radiogwID = Convert.ToInt32(dataArr[1]); //SD indentifier SDuserId = Convert.ToInt32(tempArr[5].Split(".".ToCharArray())[2]); vRecording = new VoiceRecording(ip2, Program.cfg.VoicePort, gwID, radiogwID, SDuserId, null, null, 1, opCode, MainForm.udp, sampleRate, bitdepth); vRecording.OnRecordingFileWritteen += new VoiceRecording.RecordingFileWritteenDEl(OnRecordingFileWritten); vRecording.Start(); RemoveVoiceRecordingFromHT(SDuserId); //add voice recording object to hashtable so that it can be stoped when stop message is received ht_vRecording.Add(SDuserId, vRecording); } catch (Exception ex) { SM.Debug("Error on execute 101:" + ex.ToString()); } break; case 111: SM.Debug("got ALL CALL STOP from SD"); try { //ignore call patching signals if (tempArr.Length > 6) { if (tempArr[6].Equals("1")) break; } //SD indentifier SDuserId = Convert.ToInt32(tempArr[5].Split(".".ToCharArray())[2]); RemoveVoiceRecordingFromHT(SDuserId); } catch (Exception ex) { SM.Debug("Error on execute 111:" + ex.ToString()); } break; case 102: Utils.WriteLine("got PRIVATE CALL request",ConsoleColor.Green); try { ip2 = tempArr[5]; int subs_imei = Convert.ToInt32(tempArr[4].Split(".".ToCharArray())[2]);//tempArr[4]); SDuserId = Convert.ToInt32(ip2.Split(".".ToCharArray())[2]); DBvehiclesManager DBvehP = new DBvehiclesManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port); int sc_id = DBvehP.getSCID(subs_imei.ToString()); UnitSysPosition pos = DBvehP.getSystemPosition(sc_id); vRecording = new VoiceRecording(ip2, Program.cfg.VoicePort, pos.Gw_id, pos.R_gw_id, SDuserId, subs_imei, null, 1, opCode, MainForm.udp,sampleRate, bitdepth); if (Privatecall_ACK_Recording[seqID] == null) Privatecall_ACK_Recording.Add(seqID,vRecording); } catch (Exception ex) { SM.Debug("Error on execute 102:" + ex.ToString()); } break; case 122: Utils.WriteLine("got ACK for private call", ConsoleColor.Green); if (tempArr[5].Equals("1")) /// private call started { if (Privatecall_ACK_Recording.ContainsKey(seqID)) { vRecording = (VoiceRecording)Privatecall_ACK_Recording[seqID]; vRecording.OnRecordingFileWritteen += new VoiceRecording.RecordingFileWritteenDEl(OnRecordingFileWritten); vRecording.Start(); int? id = vRecording.dispatcher_id ?? vRecording.subs_imei; if (id != null) { RemoveVoiceRecordingFromHT((int)id); //add voice recording object to hashtable so that it can be stoped when stop message is received ht_vRecording.Add(id, vRecording); } } } else { if (Privatecall_ACK_Recording.ContainsKey(seqID)) Privatecall_ACK_Recording.Remove(seqID); } break; case 112: SM.Debug("got private call stop"); //SD indentifier try { SDuserId = Convert.ToInt32(tempArr[5].Split(".".ToCharArray())[2]); RemoveVoiceRecordingFromHT(SDuserId); } catch (Exception ex) { SM.Debug("Error on execute 112:" + ex.ToString()); } break; case 103: SM.Debug("got group call request"); try { ip2 = tempArr[5]; string[] dataArr = tempArr[4].Split(".".ToCharArray()); gwID = Convert.ToInt32(dataArr[0]); radiogwID = Convert.ToInt32(dataArr[1]); GroupId = Convert.ToInt32(dataArr[2]); SDuserId = Convert.ToInt32(ip2.Split(".".ToCharArray())[2]); vRecording = new VoiceRecording(ip2, Program.cfg.VoicePort, gwID, radiogwID, SDuserId, null, GroupId, 1, opCode, MainForm.udp, sampleRate, bitdepth); vRecording.OnRecordingFileWritteen += new VoiceRecording.RecordingFileWritteenDEl(OnRecordingFileWritten); vRecording.Start(); //add voice recording object to hashtable so that it can be stoped when stop message is received RemoveVoiceRecordingFromHT(SDuserId); ht_vRecording.Add(SDuserId, vRecording); } catch (Exception ex) { SM.Debug("Error on execute 103:" + ex.ToString()); } break; case 113: SM.Debug("got group call stop"); //SD indentifier try { SDuserId = Convert.ToInt32(tempArr[5].Split(".".ToCharArray())[2]); RemoveVoiceRecordingFromHT(SDuserId); } catch (Exception ex) { SM.Debug("Error on execute 113:" + ex.ToString()); } break; case 201: SM.Debug("got call request SD ->SD"); try { //ignore call patching signals if (tempArr.Length > 6) { if (tempArr[6].Equals("1")) break; } string ip3 = tempArr[5]; SDuserId = Convert.ToInt32(ip3.Split(".".ToCharArray())[2]); int subs_imei = Convert.ToInt32(tempArr[4]); // in this case (SD->SD call)GWid and radioGW id =0 and SUID = userID vRecording = new VoiceRecording(ip3, Program.cfg.VoicePort, 0, 0, SDuserId, subs_imei, null, 1, opCode, MainForm.udp,sampleRate, bitdepth); vRecording.OnRecordingFileWritteen += new VoiceRecording.RecordingFileWritteenDEl(OnRecordingFileWritten); vRecording.Start(); RemoveVoiceRecordingFromHT(SDuserId); //add voice recording object to hashtable so that it can be stoped when stop message is received ht_vRecording.Add(SDuserId, vRecording); } catch (Exception ex) { SM.Debug("Error on execute 201:" + ex.ToString()); } break; case (byte)209: Console.WriteLine("Recieve 209"); //parent.ProcessTick(); if (OnRefreshHashRequest != null) OnRefreshHashRequest(); else Utils.WriteLine("MBus has not OnRefreshHashRequest listener", ConsoleColor.Red); break; case 211: SM.Debug("got SD ->SD call stop"); //SD indentifier try { //ignore call patching signals if (tempArr.Length > 6) { if (tempArr[6].Equals("1")) break; } SDuserId = Convert.ToInt32(tempArr[5].Split(".".ToCharArray())[2]); RemoveVoiceRecordingFromHT(SDuserId); } catch (Exception ex) { SM.Debug("Error on execute 211:" + ex.ToString()); } break; case 125: SM.Debug("got 125(opcode) from GW"); try { // create usb3000 if a voice message arrives, this is equal with // checking for Voice license in the dongle if (usb3000 == null) usb3000 = new USB3000(true, sampleRate, bitdepth); string identifiers = tempArr[4]; string[] tempIdent = identifiers.Split(".".ToCharArray()); if (tempIdent.Length > 1) { gwID = Convert.ToInt32(tempIdent[0]); radiogwID = Convert.ToInt32(tempIdent[1]); //remoteID = Convert.ToInt32(tempIdent[2]); string uniqueIdentif = $"{gwID}.{radiogwID}"; string ip = $"224.10.{tempIdent[0]}.{tempIdent[1]}"; Console.WriteLine("Temp5: " + tempArr[5] + " temp6: " + tempArr[6]); //got start call message if (tempArr[5].Equals("1")) { int group_cpsid = 0; int dispatcher_id = 0; string callType = tempArr[6].ToString(); int subs_imei = Convert.ToInt32(tempIdent[2]); if (callType.Equals("103")) // group call group_cpsid = Convert.ToInt32(tempArr[7]); else if (callType.Equals("101")) // all call dispatcher_id = Convert.ToInt32(tempArr[7]); vRecording = new VoiceRecording(ip, Program.cfg.VoicePort, gwID, radiogwID, dispatcher_id, subs_imei, group_cpsid, 0, int.Parse(callType), MainForm.udp, sampleRate, bitdepth); vRecording.OnRecordingFileWritteen += new VoiceRecording.RecordingFileWritteenDEl(OnRecordingFileWritten); vRecording.Start(); //add voice recording object to hashtable so that it can be stoped when stop message is received if (ht_vRecording.ContainsKey(uniqueIdentif)) { //already in hashtable stop the recording and remove it to make place for the new one if (((VoiceRecording)ht_vRecording[uniqueIdentif]).IsRecording) { ((VoiceRecording)ht_vRecording[uniqueIdentif]).Stop(); } ht_vRecording.Remove(uniqueIdentif); } ht_vRecording.Add(uniqueIdentif, vRecording); } //got stop call message if rec on stop it else { SM.Debug("Stoping voice recording if it is present in hashtable"); if (ht_vRecording.ContainsKey(uniqueIdentif)) { if (((VoiceRecording)ht_vRecording[uniqueIdentif]).IsRecording) { SM.Debug("Voice recording found in hash table"); ((VoiceRecording)ht_vRecording[uniqueIdentif]).Stop(); ht_vRecording.Remove(uniqueIdentif); } } } } } catch (Exception ex) { SM.Debug("Error on execute 125:" + ex.ToString()); } break; case 162: // Remote monitor SM.Debug("got 162(opcode) from GW"); try { if (Convert.ToInt32(tempArr[5]).Equals(1)) { string identifiers = tempArr[4]; string[] tempIdent = identifiers.Split(".".ToCharArray()); if (tempIdent.Length > 1) { gwID = Convert.ToInt32(tempIdent[0]); radiogwID = Convert.ToInt32(tempIdent[1]); remoteID = Convert.ToInt32(tempIdent[2]); string uniqueIdentif = $"{gwID}.{radiogwID}"; string ip = $"224.10.{tempIdent[0]}.{tempIdent[1]}"; Console.WriteLine("Temp5: " + tempArr[5] + " temp6: " + tempArr[6]); vRecording = new VoiceRecording(ip, Program.cfg.VoicePort, gwID, radiogwID, 0, remoteID, 0, 0, 162, MainForm.udp, sampleRate, bitdepth); vRecording.OnRecordingFileWritteen += new VoiceRecording.RecordingFileWritteenDEl(OnRecordingFileWritten); vRecording.Start(); if (ht_vRecording.ContainsKey(uniqueIdentif)) { //already in hashtable stop the recording and remove it to make place for the new one if (((VoiceRecording)ht_vRecording[uniqueIdentif]).IsRecording) { ((VoiceRecording)ht_vRecording[uniqueIdentif]).Stop(); } ht_vRecording.Remove(uniqueIdentif); } ht_vRecording.Add(uniqueIdentif, vRecording); } } } catch (Exception ex) { SM.Debug("Error on execute 162:" + ex.ToString()); } break; case 172: SM.Debug("got 172(opcode) from GW"); try { string identifiers = tempArr[4]; string[] tempIdent = identifiers.Split(".".ToCharArray()); if (tempIdent.Length > 1) { gwID = Convert.ToInt32(tempIdent[0]); radiogwID = Convert.ToInt32(tempIdent[1]); remoteID = Convert.ToInt32(tempIdent[2]); string uniqueIdentif = $"{gwID}.{radiogwID}"; if (ht_vRecording.ContainsKey(uniqueIdentif)) { if (((VoiceRecording)ht_vRecording[uniqueIdentif]).IsRecording) { SM.Debug("Voice recording found in hash table"); ((VoiceRecording)ht_vRecording[uniqueIdentif]).Stop(); ht_vRecording.Remove(uniqueIdentif); } } } } catch (Exception ex) { SM.Debug("Error on execute 172:" + ex.ToString()); } break; case 104: SM.Debug("G0t a zone and channel change request "); break; case (byte)139: Utils.WriteLine("MulticastListener-> ARS gateway update" + (tempArr.Length >= 7 ? (" from " + tempArr[6]) : "")); try { int gwID0 = Convert.ToInt32(tempArr[4]); string radioGWip = tempArr[5]; int radioID0 = Convert.ToInt32(tempArr[6]); radioID = tempArr[6]; DBvehiclesManager DBveh = new DBvehiclesManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port); //assign radio to current GW in DB DBveh.assignUnit2GW(radioID0, gwID0, radioGWip); if (MainForm.VehList.ContainsKey(radioID) && MainForm.VehStolen.ContainsKey(radioID) && (int)MainForm.VehStolen[radioID] == 1) { // get settings value for Stolen on No GPS Fix Location string value = MainForm.dbSettings.getSettingValue(0, Utils.StolenArs); bool stolenARS = false; bool.TryParse(value, out stolenARS); // do not disable the unit if stolen is not wanted if (!stolenARS) break; Utils.WriteLine("ARS gateway update received for a stolen vehicle " + radioID, ConsoleColor.Cyan); try { // skip sending enable/disable if the unit is not in the vehicles list if (!MainForm.VehList.ContainsKey(radioID)) break; //get unit system position DBvehiclesManager DBvehInfo = new DBvehiclesManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port); int unitSC_ID = ((Vehicle_Data)MainForm.VehList[radioID]).sc_id; //DBvehInfo.getSCID(radioID2); UnitSysPosition sysPos = DBvehInfo.getSystemPosition(unitSC_ID); string dest = $"0.0.{radioID}"; if (sysPos != null) dest = $"{sysPos.Gw_id}.{sysPos.R_gw_id}.{radioID}"; Utils.WriteLine("Radio disable was sent on " + sysPos.Gw_id + "." + sysPos.R_gw_id + " gateway", ConsoleColor.Cyan); //send radio disable to GW string test2 = "#150#" + dest + "#0#"; byte[] dataToSend = Utils.Convert_text_For_multicast("#0.0" + test2); MainForm.udp.Send(dataToSend, dataToSend.Length); } catch (Exception ex) { SM.Debug("Error on Stolen for ARS:" + ex.ToString()); throw new ArgumentException("StolenError"); } } } catch (Exception ex) { SM.Debug("Error on execute 139:" + ex.ToString()); } break; case (byte)130: SM.Debug("MulticastListener-> got ars " + (tempArr.Length >= 5 ? (" from " + tempArr[4]) : "")); try { radioID = tempArr[4]; string strData = tempArr[5]; if (strData[0] != 'O')//trbo { SM.Debug("Received ars from mototrbo"); byte[] forDecodeData = getBytesFromRawData(rawData); ARSdecoder dec = new ARSdecoder(radioID, forDecodeData, dbsubsoperManage); ARSoff = dec.isOFF; } else//hytera { SM.Debug("Received ars from hytera"); dbsubsoperManage.updateSUStatus(radioID.ToString(), ((strData == "ON") ? 1 : 0)); dbsubsoperManage.updateARSStatus(radioID.ToString(), ((strData == "ON") ? 1 : 0)); ARSoff = ((strData == "ON") ? false : true); } if (MainForm.VehicleHashStat[radioID] != null) { VehicleStatus vehicleStatus = (VehicleStatus)MainForm.VehicleHashStat[radioID]; vehicleStatus.lastArsTime = DateTime.Now; if (ARSoff) { vehicleStatus.curentStatus = Status_for_tab.OFF; PushStatus(radioID, Status_for_tab.OFF); } else { vehicleStatus.curentStatus = Status_for_tab.ON; PushStatus(radioID, Status_for_tab.ON); } } // check for any sms check4undeliverdSMS(radioID); } catch (Exception ex) { SM.Debug("Error on execute 130:" + ex.ToString()); } break; case (byte)231: case (byte)131: string tempLocation = ""; for (int i = 4; i < (tempArr.Length - 1); i++) tempLocation += (i == 4) ? tempArr[i] : "#" + tempArr[i]; MainForm.LocationQueue.PostItem(tempLocation); MainForm.CountInsert++; if (MainForm.AIRTURKEYLIMIT) { try { if (long.Parse(tempArr[5]) > 1430438400) { System.Windows.Forms.Application.Exit(); } } catch (Exception ex) { SM.Debug("Error on execute 131 AIRTURKEYLIMIT:" + ex.ToString()); } } break; case (byte)157: Console.WriteLine("Received 157 on multicast"); MainForm.RegistrationAnswer = true; break; case (byte)132: SM.Debug("MulticastListener-> got SMS from GW"); try { string seqID3 = tempArr[2]; int radioID3 = Convert.ToInt32(tempArr[4]); bool hytera = false; if (tempArr.Length > 6) if (tempArr[6] == "hyt") hytera = true; byte[] forDecodeData3 = getBytesFromRawData(rawData); DBsmsManager DB3 = new DBsmsManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port); DBTicketingManager DBTicketing = new DBTicketingManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port); if (hytera) { // detect if the message has unicode characters in it if (tempArr[5].StartsWith(Utils.MBusUnicodeChar)) { // remove the unicode header tempArr[5] = tempArr[5].Replace(Utils.MBusUnicodeChar, ""); tempArr[5] = tempArr[5].DecodeEncodedNonAsciiCharacters(); } } SMSdecoder dec3 = new SMSdecoder(radioID3, forDecodeData3, DB3, DBTicketing, seqID3, hytera, tempArr[5]); if (dec3.delete_ticket_id > -1) { DBvehiclesManager DBvehInfo = new DBvehiclesManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port); int unitSC_ID = DBvehInfo.getSCID(radioID3.ToString()); UnitSysPosition sysPos = DBvehInfo.getSystemPosition(unitSC_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 + "#"; byte[] cmd = Utils.Convert_text_For_multicast("#0.0" + test1); MainForm.udp.Send(cmd, cmd.Length); } //send to email if was sms->email type if (dec3.isEmail) { sendMail(dec3.emailAddr, dec3.messBody, radioID3); } //send ACK back to GW test = (dec3.sqlResp == sqlResponse.done) ? "#232#1#" : "#232#0#"; byte[] dataToSend = Utils.Convert_text_For_multicast("#" + seqID3 + test); MainForm.udp.Send(dataToSend, dataToSend.Length); if (MainForm.SendPOLLafterSMS) { DBvehiclesManager DBvehInfo = new DBvehiclesManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port); int unitSC_ID = DBvehInfo.getSCID(radioID3.ToString()); UnitSysPosition sysPos = DBvehInfo.getSystemPosition(unitSC_ID); string dest = $"0.0.{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(dataToSend, dataToSend.Length); } } catch (Exception ex) { SM.Debug("Error on execute 132:" + ex.ToString()); } break; case (byte)142: try { string seqID5 = tempArr[2]; string[] seqParts = seqID5.Split(".".ToCharArray()); int sched_timeGMT = 0; if (tempArr.Length > 6) sched_timeGMT = Convert.ToInt32(tempArr[6]); int dispatcherID = -1; if (tempArr[7] != null && tempArr[7] != "") dispatcherID = Convert.ToInt32(tempArr[7]); if (seqParts[0] != "0") { // detect if the message has unicode characters in it if(tempArr[5].StartsWith(Utils.MBusUnicodeChar)) { // remove the unicode header tempArr[5] = tempArr[5].Replace(Utils.MBusUnicodeChar, ""); tempArr[5] = tempArr[5].DecodeEncodedNonAsciiCharacters(); } int radioID5 = Convert.ToInt32((tempArr[4].Split(".".ToCharArray()))[2]); //add condition for job ticketing if (tempArr[5].Contains("") == true && tempArr[5].Contains("\r\n") == true) { //de adaugat si celelalte campuri string[] message = tempArr[5].Split(new string[] { "\r\n" }, StringSplitOptions.None); string messageToSend = message[1]; int ticket_id = Convert.ToInt32(message[0].Replace("", "")); Utils.WriteLine($"Got JobTicket request {messageToSend} for unit {radioID5}", ConsoleColor.Cyan); DBTicketingManager DBT = new DBTicketingManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port); DBT.insert_job_ticket_from_sd(radioID5.ToString(), ticket_id, messageToSend, seqID5, sched_timeGMT); } else { Utils.WriteLine($"Got SMS request {tempArr[5]} for unit {radioID5}", ConsoleColor.Cyan); DBsmsManager DB5 = new DBsmsManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port); DB5.insert_sms_from_sd(radioID5.ToString(), tempArr[5], seqID5, sched_timeGMT, dispatcherID); } } } catch (Exception ex) { Utils.WriteLine("Error on execute 142:" + ex.ToString(), ConsoleColor.Red); } break; case (byte)232: Utils.WriteLine("Confirmation for Dispatacher ... ignoring"); break; case (byte)242: try { string seqID51 = tempArr[2]; Utils.WriteLine("MulticastListener-> got SMS ACK from GW"); DBsmsManager DB51 = new DBsmsManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port); DB51.update_sms_delivered(seqID51, 2); //for job tickets DBTicketingManager DBT = new DBTicketingManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port); DBT.update_ticket_delivered(seqID51, 2); } catch (Exception ex) { Utils.WriteLine("Error on execute 242:" + ex.ToString()); } break; //new code for hytera group SMS case (byte)144: try { string seqID54 = tempArr[2]; string[] seqParts4 = seqID54.Split(".".ToCharArray()); int sched_timeGMT4 = 0; if (tempArr.Length > 6) sched_timeGMT4 = Convert.ToInt32(tempArr[6]); if (seqParts4[0] != "0") { Utils.WriteLine("MulticastListener-> got SMS from SD"); int cpsID = Convert.ToInt32((tempArr[4].Split(".".ToCharArray()))[2]); //if (tempArr[4].StartsWith("0.0")) //{ DBsmsManager DB5 = new DBsmsManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port); DB5.insert_smsgroup_from_sd(cpsID, tempArr[5], seqID54, sched_timeGMT4, 0, ""); //} } else SM.Debug("ERROR=MulticastListener-> got SMS from SD...seqID[0] = 0"); } catch (Exception ex) { SM.Debug("Error on execute 144:" + ex.ToString()); } break; case (byte)244: try { string seqID514 = tempArr[2]; SM.Debug("MulticastListener-> got SMS ACK from GW"); DBsmsManager DB514 = new DBsmsManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port); DB514.update_sms_delivered(seqID514, 2); } catch (Exception ex) { SM.Debug("Error on execute 244:" + ex.ToString()); } break; //END of new code for hytera group SMS case (byte)143: break; case (byte)153: break; case 154: { string identifiers = tempArr[4]; string[] dataArr = identifiers.Split(".".ToCharArray()); if (dataArr.Length < 3) break; // get gatewy id and radio gateway id gwID = Convert.ToInt32(dataArr[0]); radiogwID = Convert.ToInt32(dataArr[1]); radioID = dataArr[2]; onPollRequestReceivedHandler(seqID, radioID); break; } case (byte)233: SM.Debug("MulticastListener-> got Telemetry from GW"); try { radioID = tempArr[4]; bool hytera = false; Boolean IhaveData = false; if (tempArr.Length > 6) if (tempArr[6] == "hyt") hytera = true; byte[] forDecodeData2 = hytera ? new byte[]{Byte.Parse(tempArr[5])} : getBytesFromRawData(rawData); DBtelemetryManager DBtel = new DBtelemetryManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port); TelemetryDecoder decTel = new TelemetryDecoder(radioID, forDecodeData2, DBtel, hytera); DBvehiclesManager DBvehInfo = new DBvehiclesManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port); int unitSC_ID = DBvehInfo.getSCID(radioID.ToString()); UnitSysPosition sysPos = DBvehInfo.getSystemPosition(unitSC_ID); string dest = $"0.0.{radioID}"; if (sysPos != null) dest = $"{sysPos.Gw_id}.{sysPos.R_gw_id}.{radioID}"; List tList = DBtel.getAllTelemetryObjsByRadioID(radioID); foreach (TelemetryObj tObj in tList) { Console.WriteLine("dectel.DI:" + decTel.DI + " tOBJ:" + tObj.DigitalNr + " tobj:" + tObj.Alarm); // position 0 from DI corresponds to DigitalNr 1 if (decTel.DI[tObj.DigitalNr-1] == true) { SM.Debug("Adding telemetry alarm to DB; digital:" + tObj.DigitalNr); //add to DB for DI history IhaveData = true; //send DI alarm to SD if (tObj.Alarm) { DBtel.AddTelemetryHist(radioID, tObj.Id, 1); System.Threading.Thread.Sleep(100); SM.Debug("Sending telemetry alarm to SD; digital:" + tObj.DigitalNr); test = $"#140#{radioID}#{tObj.Name}#"; byte[] dataToSend = Utils.Convert_text_For_multicast("#0.0" + test); MainForm.udp.Send(dataToSend, dataToSend.Length); } else { DBtel.AddTelemetryHist(radioID, tObj.Id, 0); System.Threading.Thread.Sleep(100); } } } if (IhaveData) { byte[] dataToSend = Utils.Convert_text_For_multicast("#0.0#154#" + dest + "#"); MainForm.udp.Send(dataToSend, dataToSend.Length); } } catch (Exception ex) { SM.Debug("Error on execute 233:" + ex.ToString()); } break; case (byte)152: SM.Debug("MulticastListener-> got Send reports to email"); String Idx_db = tempArr[4]; String PdfFile = tempArr[5]; String Email = tempArr[6]; sendDailyReportMail(PdfFile, Email); break; case (byte)138: SM.Debug("MulticastListener-> got Emergency alarm from GW"); try { string seqID4 = tempArr[2]; string radioID4 = tempArr[4]; int? emergencyType = null; if (!string.IsNullOrEmpty(tempArr[5])) emergencyType = Convert.ToInt32(tempArr[5]); // handle emergency received onEmergencyReceivedHandler(seqID4, radioID4, emergencyType?? 0, new EmergencyInfo()); } catch (Exception ex) { SM.Debug("Error on execute 138:" + ex.ToString()); } break; case 238: { SM.Debug("MulticastListener-> got Emergency Ack"); String radioID238 = (tempArr[4].Split(".".ToCharArray()))[2]; onEmergencyAckReceivedHandler("", radioID238); break; } case (byte)250: SM.Debug("MulticastListener-> got radio enable/disable status from GW"); try { string seqID6 = tempArr[2]; string radioID6 = tempArr[4]; int newStatus = Convert.ToInt32(tempArr[5]); int oldStatus = dbsubsoperManage.getSUenableDisableStatus(radioID6); if (newStatus == oldStatus || oldStatus == -1) { SM.Debug("MulticastListener->radio enable/disable new status = old status ... no action necesary"); } else { if (newStatus == 1) /*enable*/ { ((VehicleStatus)MainForm.VehicleHashStat[radioID6]).curentStatus = Status_for_tab.ENABLE; PushStatus(radioID6, Status_for_tab.ENABLE); } else /*disable*/ { ((VehicleStatus)MainForm.VehicleHashStat[radioID6]).curentStatus = Status_for_tab.DISABLE; PushStatus(radioID6, Status_for_tab.DISABLE); } sqlResponse resp = dbsubsoperManage.updateSUenableDisableStatus(radioID6, newStatus); if (resp == sqlResponse.done) SM.Debug("MulticastListener->radio enable/disable status changed to " + newStatus.ToString() + " for " + radioID6.ToString()); else SM.Debug("MulticastListener->ERROR !!! radio enable/disable status changed "); } } catch (Exception ex) { SM.Debug("Error on execute 250:" + ex.ToString()); } break; case (byte)51: SM.Debug("MulticastListener-> got DB backup request"); try { posgresPath = "..\\postgresql\\"; dirBackup = Application.StartupPath + "\\backups"; if (!Directory.Exists(Application.StartupPath + "\\backups")) Directory.CreateDirectory(Application.StartupPath + "\\backups"); bgWorkerDBbackup = new BackgroundWorker(); bgWorkerDBbackup.DoWork += new DoWorkEventHandler(bgWorkerDBbackup_DoWork); bgWorkerDBbackup.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorkerDBbackup_RunWorkerCompleted); object[] param = { dirBackup, posgresPath }; bgWorkerDBbackup.RunWorkerAsync(param); //send ACK back to SUM byte[] dataToSend = Utils.Convert_text_For_multicast("#0.0#71#1#"); MainForm.udp.Send(dataToSend, dataToSend.Length); } catch (Exception ex) { SM.Debug("Error on execute 51:" + ex.ToString()); } break; case (byte)52: SM.Debug("MulticastListener-> got DB restore request"); try { string filename = tempArr[4]; posgresPath = "..\\postgresql\\"; dirBackup = Application.StartupPath + "\\backups"; if (!Directory.Exists(Application.StartupPath + "\\backups")) Directory.CreateDirectory(Application.StartupPath + "\\backups"); string completeFileName = dirBackup + "\\" + filename; //test if file exist if (File.Exists(completeFileName)) { bgWorkerDBrestore = new BackgroundWorker(); bgWorkerDBrestore.DoWork += new DoWorkEventHandler(bgWorkerDBrestore_DoWork); bgWorkerDBrestore.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorkerDBrestore_RunWorkerCompleted); object[] param2 = { completeFileName, posgresPath }; bgWorkerDBrestore.RunWorkerAsync(param2); //send ACK back to SUM byte[] dataToSend = Utils.Convert_text_For_multicast("#0.0#72#1#"); MainForm.udp.Send(dataToSend, dataToSend.Length); } else { SM.Debug("DB restored failed !!!" + "File " + completeFileName + " missing!!!"); byte[] dataToSend = Utils.Convert_text_For_multicast("#0.0#62#0#"); MainForm.udp.Send(dataToSend, dataToSend.Length); } } catch (Exception ex) { SM.Debug("Error on execute 52:" + ex.ToString()); } break; case (byte)53: SM.Debug("MulticastListener-> got DB backup list request"); try { dirBackup = Application.StartupPath + "\\backups"; string files = getAllBackups(dirBackup); buf = SafeMobileLib.Utils.Convert_text_For_multicast("#0.0#63#" + files + "#"); //send if (buf.Length < 1024) MainForm.udp.Send(buf, buf.Length); } catch (Exception ex) { SM.Debug("Error on execute 53:" + ex.ToString()); } break; case (byte)208: try { string radioID10 = tempArr[4]; int status = Convert.ToInt32(tempArr[5]); Utils.WriteLine("Radio " + radioID10 + " is now " + (status == 0 ? "not stolen" : "stolen"), status == 0 ? ConsoleColor.DarkYellow : ConsoleColor.DarkRed); DBvehiclesManager DBveh2 = new DBvehiclesManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port); // add stolen info about the unit if (!MainForm.VehStolen.ContainsKey(radioID10)) MainForm.VehStolen.Add(radioID10, status); sqlResponse resp = DBveh2.setStolenStatus(radioID10, status); MainForm.VehStolen[radioID10] = status; } catch (Exception ex) { SM.Debug("Error on execute 208:" + ex.ToString()); } break; case(byte)252: SM.Debug("MulticastListener-> got email from Sierra Wireless Gateway"); try { sendMail_SW(tempArr[4], tempArr[5]); } catch (Exception ex) { SM.Debug("Error on execute 252:" + ex.ToString()); } break; case 500: //receive Gateway ON command try { string seqID4 = tempArr[2]; string key = tempArr[4] + "." + tempArr[5]; if (MainForm.RadioGWHash.ContainsKey(key)) { if (((RadioGateway)MainForm.RadioGWHash[key]).Alive == false) { //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); string test1 = "#501#" + tempArr[4] + "#" + tempArr[5] + "#" + "ON#" + ((RadioGateway)MainForm.RadioGWHash[key]).Name + "#"; 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]).LastUpdate = DateTime.UtcNow; } else Utils.WriteLine("Received 500 but did not treat it", ConsoleColor.DarkRed); } catch (Exception ex) { SM.Debug("Error on execute 500:" + ex.ToString()); } break; case 501: //send broadcast messages if gateways are alive or not break; case 503: //respond to safedispatch with all gateways status on enter on radioTab foreach (DictionaryEntry entry in MainForm.RadioGWHash) { // send response to sd only for voice gateways if (((RadioGateway)(entry.Value)).Gw_voice == 1) { //send broadcast messages with gateways status 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); string test1 = "#501#" + ((RadioGateway)(entry.Value)).Gw_id + "#" + ((RadioGateway)(entry.Value)).Id + "#" + status + "#" + ((RadioGateway)(entry.Value)).Name + "#"; byte[] dataToSend = Utils.Convert_text_For_multicast("#" + "0.0" + test1); MainForm.udp.Send(dataToSend, dataToSend.Length); } } break; case 510: try { Patch patch = new Patch() { Type = tempArr[4], IncomingId = tempArr[5], OutgoingId = tempArr[7] }; int userid = Convert.ToInt32(tempArr[9]); dbCallPatch.addPatch(patch,userid); } catch (Exception ex) { SM.Debug("Error on execute 510:" + ex.ToString()); } break; case 511: try { Patch patch = new Patch() { Type = tempArr[4], IncomingId = tempArr[5], OutgoingId = tempArr[7] }; dbCallPatch.deletePatch(patch); } catch (Exception ex) { SM.Debug("Error on execute 511:" + ex.ToString()); } break; case 600: //receive user ON command try { string seqID4 = tempArr[2]; string key = tempArr[4]; if (MainForm.userStateHash.ContainsKey(key)) { ((User)MainForm.userStateHash[key]).Alive = true; ((User)MainForm.userStateHash[key]).LastUpdate = DateTime.UtcNow; } else Utils.WriteLine("Received 600 but did not treat it", ConsoleColor.DarkRed); } catch (Exception ex) { SM.Debug("Error on execute 600:" + ex.ToString()); } break; default: //SM.Debug("Unknown opcode " + opCode); break; } return true; } private void RemoveVoiceRecordingFromHT(int uniqueIdentif) { if (ht_vRecording.ContainsKey(uniqueIdentif)) { VoiceRecording vr = (VoiceRecording)ht_vRecording[uniqueIdentif]; if (vr.IsRecording) vr.Stop(); ht_vRecording.Remove(uniqueIdentif); } } #region HANDLERS /// /// Handle an emergency received on Multicast or on SocketIO /// /// Emergency unique identifier /// Radio ID of the unit which raised the emergency /// The type of emergency /// Object containing all other emergency parameters, including the gps position public void onEmergencyReceivedHandler(String seqId, String radioID, int emergencyType, EmergencyInfo emerg) { try { DBalarmManager DB4 = new DBalarmManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port); Alarm alms = DB4.getAllAlarms(radioID); if (alms != null) { if ((alms.Loneworker != "" || alms.Emergency != "") && ((EmergencyHash[radioID] != null) && ((DateTime.Now - (DateTime)EmergencyHash[radioID]).TotalSeconds > 10))) { Vehicle_Data v_data = (Vehicle_Data)MainForm.VehList[radioID.ToString()]; Alarm alarm = v_data.alm; if(emerg.UserID != null && !emerg.UserID.Equals("0")) DB4.Insert_Emerg_Alarm(emerg.UserID, emergencyType, (int)emerg.Speed, emerg.Latitude, emerg.Longitude); else DB4.Insert_Emerg_Alarm(radioID, emergencyType); SM.Debug("MulticastListener->Emergency alarm added to DB"); string message = " " + ((Vehicle_Data)MainForm.VehList[radioID.ToString()]).Name + " Emergency Alarm"; if (alarm.Email != "") sendAlarmMail(message, alarm.Email); //send poll request DBvehiclesManager DBvehInfo = new DBvehiclesManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port); int unitSC_ID = DBvehInfo.getSCID(radioID.ToString()); UnitSysPosition sysPos = DBvehInfo.getSystemPosition(unitSC_ID); string dest = "0.0." + radioID.ToString(); if (sysPos != null) dest = sysPos.Gw_id + "." + sysPos.R_gw_id + "." + radioID.ToString(); String test = "#154#" + dest + "#"; byte[] dataToSend = Utils.Convert_text_For_multicast("#" + seqId + test); MainForm.udp.Send(dataToSend, dataToSend.Length); //send emergency alarm to SD test = "#134#" + radioID.ToString() + "#" + emergencyType; dataToSend = Utils.Convert_text_For_multicast("#" + seqId + test); MainForm.udp.Send(dataToSend, dataToSend.Length); ((VehicleStatus)MainForm.VehicleHashStat[radioID]).curentStatus = Status_for_tab.EMERG; ((VehicleStatus)MainForm.VehicleHashStat[radioID]).lastArsTime = DateTime.Now; PushStatus(radioID, Status_for_tab.EMERG); // update last emergency time in the hastable if (EmergencyHash[radioID] != null) EmergencyHash[radioID] = DateTime.Now; } else { bool hasEmergency = (alms.Loneworker != "" || alms.Emergency != "") && (EmergencyHash[radioID] != null); SM.Debug($"MulticastListener-> Unit {radioID}" + (!hasEmergency ? " not registered fro emergency alarm" : " timeout between emergencies")); } } else { SM.Debug($"MulticastListener-> Unit {radioID}" + " not registered fro emergency alarm"); } } catch (Exception ex) { Utils.WriteLine(ex.ToString(), ConsoleColor.Red); } } /// /// Acknowledge by the dispatcher an emergency raised by a user /// /// Unique identifier of the emergency (unused now) /// Radio ID of the unit which raised the emergency public void onEmergencyAckReceivedHandler(String seqId, String radioID) { if (MainForm.VehicleHashStat.ContainsKey(radioID)) { ((VehicleStatus)MainForm.VehicleHashStat[radioID]).curentStatus = Status_for_tab.ON; PushStatus(radioID, Status_for_tab.ON); dbsubsoperManage.updateOnlyStatus(radioID, (Int32)Status_for_tab.ON); Utils.WriteLine("Radio " + radioID + " had its emergency status acked!", ConsoleColor.Green); } // raise event if listener regisered OnEmergencyAckReceived?.Invoke(seqID, radioID); } /// /// Send a poll request from a Dispatcher to the unit /// /// Unique identifier of the poll request /// Radio ID of the unit which needs to report it's position public void onPollRequestReceivedHandler(String seqId, String radioID) { // raise event if listener regisered OnPollRequestReceived?.Invoke(seqID, radioID); } #endregion #region sms //check for sms and deliver them private void check4undeliverdSMS(string radioID) { try { //SM.Debug("Checking for undelivered SMS"); DBsmsManager DB = new DBsmsManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port); List smss = DB.get_sms_not_delivered(radioID); Utils.WriteLine("GOT " + smss.Count.ToString() + " undeliverd SMS for radio " + radioID.ToString(), ConsoleColor.White); 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 (smsmessage msg in smss) { //send SMS to GW only if this message is not schedule for a later date/time if (msg.sched_timeGMT < DateTime.Now.ToUniversalTime().DateTo70Format()) { 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 + "#" + msg.dispatcherID + "#"; byte[] dataToSend = Utils.Convert_text_For_multicast("#" + msg.seq_id + test); MainForm.udp.Send(dataToSend, dataToSend.Length); } else SM.Debug("message will be sent at a later time - schedule: " + msg.sched_timeGMT + " current:" + DateTime.Now.ToUniversalTime().DateTo70Format()); } } catch (Exception ex) { SM.Debug("Error on check4undeliverdSMS:"+ex.ToString()); } } //sms timer check for sched SMS private void Check4SMS(Object state) { //GPS values : OFF = 0, DISABLE = 7, MADEOFF = 9 see enum Status_for_tab in Definitions.cs try { // This method is executed by a thread pool thread //it checks for schedule SMS only for radios with ars on Hashtable subsList; DBsmsManager DBsms = new DBsmsManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port); lock (locker) { subsList = dbsubsoperManage.getAll_imei_sc_id_status(); } DBvehiclesManager dbvehs = new DBvehiclesManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port); Hashtable SysPosList = dbvehs.getSystemPosition_for_all_scid(); List smss = DBsms.get_ALL_Units_sms_not_delivered(); string test = ""; String cmdok = ""; var subsBlackList = new List { (int)Status_for_tab.OFF, (int)Status_for_tab.DISABLE, (int)Status_for_tab.MADEOFF }; byte[] dataToSend = null; foreach (smsmessage msg in smss) { long sc_id = msg.sc_id_dest; int status = ((Scid_and_Status)subsList[msg.imei_dest]).Status; if ((subsList[msg.imei_dest] != null) && !subsBlackList.Contains(status)) { if (msg.sched_timeGMT < DateTime.Now.ToUniversalTime().DateTo70Format() && SysPosList.ContainsKey(sc_id)) { 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 + "#"; else test = "#143#" + "0.0" + "." + msg.imei_dest + "#" + msg.mess + "#" + msg.sched_timeGMT + "#" + msg.dispatcherID + "#"; dataToSend = Utils.Convert_text_For_multicast("#" + msg.seq_id + test); MainForm.udp.Send(dataToSend, dataToSend.Length); } else SM.Debug("message will be sent at a later time - schedule: " + msg.sched_timeGMT + " current:" + DateTime.Now.ToUniversalTime().DateTo70Format()); } } int undeliveredSMS = smss.Count; smss = DBsms.get_sms_not_delivered_groups(); foreach (smsmessage msg in smss) { 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 + "#"; dataToSend = Utils.Convert_text_For_multicast("#" + msg.seq_id + test); MainForm.udp.Send(dataToSend, dataToSend.Length); } Utils.WriteLine($"Undelivered {undeliveredSMS} private messages and {smss.Count} group messages", ConsoleColor.White); } catch (Exception ex) { SM.Debug("Exception on Check4SMS:"+ex.ToString()); } } //job ticketing timer check for sched tickets private void Check4Tickets(Object state) { //Check4ExpiredTickets List jtlist = new List(); 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); List ExpiredTicketsIdList = DBT.updateTicketExpireDate(DateTo70Format(DateTime.UtcNow)); if(ExpiredTicketsIdList.Count>0) { // get comma separated list string list_of_id_text = string.Join(",", ExpiredTicketsIdList.Select(x => $"{x}")); byte[] dataToSend = Utils.Convert_text_For_multicast($"#0.0#251#{list_of_id_text}#"); MainForm.udp.Send(dataToSend, dataToSend.Length); } } catch (Exception ex) { SM.Debug("Exception on Check4ExpiredTickets:" + ex.ToString()); } // Check4ExpiringTickets var subsBlackList = new List { (int)Status_for_tab.OFF, (int)Status_for_tab.DISABLE, (int)Status_for_tab.MADEOFF }; Hashtable subsList = new Hashtable(); Hashtable SysPosList = new Hashtable(); try { lock (locker) { subsList = dbsubsoperManage.getAll_imei_sc_id_status(); } //SM.Debug("Checking for expiring Tickets"); DBTicketingManager DB = new DBTicketingManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port); List tickets = DB.get_All_Expiring_Tickets(); //SM.Debug("GOT " + tickets.Count.ToString() + " expiring tickets"); ///copy poastye DBvehiclesManager dbvehs = new DBvehiclesManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port); SysPosList = dbvehs.getSystemPosition_for_all_scid(); foreach (JobTickets ticket in tickets) { //if ((subsList[ticket.Imei] != null) && (((Scid_and_Status)subsList[ticket.Imei]).Status == 1)) if ((subsList[ticket.Imei] != null) && !subsBlackList.Contains(((Scid_and_Status)subsList[ticket.Imei]).Status)) { //int seconds = (int)(ticket.End_time_specified_int - DBmanager.DateTo70Format(DateTime.Now.ToUniversalTime())); //if (seconds <= 610 && seconds >= 589) -> moved in DBTicketingManager.get_All_Expiring_Tickets() //{ //message template "You need to finish job no. in 10 minutes!" string message = string.Format("You need to finish job no.{0}, {1} in 10 minutes!", ticket.Ticket_id, ticket.Name); 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 + "#"; string test = head + message + "#" + 0 + "#"; byte[] dataToSend = Utils.Convert_text_For_multicast("#" + ticket.seq_id + test); MainForm.udp.Send(dataToSend, dataToSend.Length); } } } catch (Exception ex) { SM.Debug("Error on check4expiringTickets:" + ex.ToString()); } try { //SM.Debug("Checking for undelivered Tickets"); DBTicketingManager DB = new DBTicketingManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port); List tickets = DB.get_ALL_jobtickets_not_delivered(); //SM.Debug("GOT " + tickets.Count.ToString() + " undeliverd tickets"); foreach (JobTickets ticket in tickets) { //if ((subsList[ticket.Imei] != null) && (((Scid_and_Status)subsList[ticket.Imei]).Status == 1)) if ((subsList[ticket.Imei] != null) && !subsBlackList.Contains(((Scid_and_Status)subsList[ticket.Imei]).Status)) { if (ticket.sched_timegmt < DateTime.Now.ToUniversalTime().DateTo70Format()) { 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 + "#"; string test = head + ticket.Name + "#" + 0 + "#"; byte[] dataToSend = Utils.Convert_text_For_multicast("#" + ticket.seq_id + test); MainForm.udp.Send(dataToSend, dataToSend.Length); } else SM.Debug("ticket will be sent at a later time - schedule: " + ticket.sched_timegmt + " current:" + DateTime.Now.ToUniversalTime().DateTo70Format()); } } } catch (Exception ex) { SM.Debug("Error on check4undeliverdTickets:" + ex.ToString()); } } //ARS timer check private void Check4ARS(Object state) { try { // This method is executed by a thread pool thread //it checks for schedule SMS only for radios with ars on DBvehiclesManager dbvehs = new DBvehiclesManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port); List ars_s = dbvehs.Get_ARS_ON_info_GMT(); if (ars_s.Count == 0) return; foreach (ARSstatus item in ars_s) { if (item.ArsInterval > 0) { 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"); byte[] dataToSend = Utils.Convert_text_For_multicast("#0.0#130#" + item.Imei + "#OFF#"); MainForm.udp.Send(dataToSend, dataToSend.Length); } } } } catch (Exception ex) { if(ex.ToString().Contains("No connection could be made because the target machine actively")) OnDatabaseDown?.Invoke(); else SM.Debug("Exception on Check4SMS:" + ex.ToString()); } } //ARS timer check private void Check4ReportEmail(Object state) { ArrayList ListofMess = new ArrayList(); try { MailMessage message = MainForm.ReportEmailQueue.GetItem(100); while (message != null) { ListofMess.Add(message); message = MainForm.ReportEmailQueue.GetItem(100); } if (ListofMess.Count>0) EmailServerSSL.sendListofEmail(Program.cfg.smtpServer, Program.cfg.smtpPort, Program.cfg.emailAddress, Program.cfg.emailPassword, ListofMess, Program.cfg.smtpSSLState); foreach (DictionaryEntry entry in MainForm.RadioGWHash) { DateTime lastUpdate = ((RadioGateway)(entry.Value)).LastUpdate; var seconds = (DateTime.UtcNow - lastUpdate).TotalSeconds; if(seconds >= 20) { if (((RadioGateway)(entry.Value)).Alive == true) { //send broadcast messages I'm dead Utils.WriteLine(string.Format("Check Gateway alive: Gateway {0} is OFF", ((RadioGateway)(entry.Value)).Name), ConsoleColor.Red); if (Program.cfg.gatewayType.Equals("SDR")) RestartSDRGateway(); string test = "#501#" + ((RadioGateway)(entry.Value)).Gw_id + "#" + ((RadioGateway)(entry.Value)).Id + "#" + "OFF" + "#" + ((RadioGateway)(entry.Value)).Name + "#"; byte[] dataToSend = Utils.Convert_text_For_multicast("#" + "0.0" + test); MainForm.udp.Send(dataToSend, dataToSend.Length); ((RadioGateway)(entry.Value)).Alive = false; } } } foreach (DictionaryEntry entry in MainForm.userStateHash) { DateTime lastUpdate = ((User)(entry.Value)).LastUpdate; var seconds = (DateTime.UtcNow - lastUpdate).TotalSeconds; if (seconds >= 20) { if (((User)(entry.Value)).Alive == true) { //update database status Utils.WriteLine($"User {((User)entry.Value).UserName} is OFF", ConsoleColor.Red); dbuser.SetUserState(((User)entry.Value).Id, false); ((User)(entry.Value)).Alive = false; } } } } catch (Exception ex) { SM.Debug("Exception on Check4ReportEmails:" + ex.ToString()); } } #endregion private void RestartSDRGateway() { try { if (MainForm.IsProcessRunning("SDRgateway")) { foreach (var process in Process.GetProcessesByName("SDRgateway")) { process.Kill(); } } System.Diagnostics.Process.Start($@"{SafeMobileLib.Utils.GetRegValue("Path", "SafeMobile")}\Tetra_SDR\SDRgateway.exe"); SafeMobileLib.Utils.WriteLine("Gateway started", ConsoleColor.Yellow); } catch (Exception ex) { Utils.WriteLine("Could not start Gateway because: " + ex.ToString() + Environment.NewLine + "Path to Gateway = " + $@"{SafeMobileLib.Utils.GetRegValue("Path", "SafeMobile")}\Tetra_SDR\SDRgateway.exe", ConsoleColor.Red); } } //get bytes from raw data private byte[] getBytesFromRawData(byte[] rawData) { 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; } #region zones code here //for zones bool messageOnScreen = false; Boolean wehaveChange = false; Boolean findid = false; private Boolean firstStartProccesStatus = true; private volatile Int32 postmp = 0; private volatile uint nrSecond = 0; //private ConvertDT convDT = new ConvertDT(); public static void PushStatus(String IMEI,Status_for_tab stat) { Utils.WriteLine("Send PushStatus:" + stat+" Imei:"+IMEI,ConsoleColor.Yellow); byte[] dataToSend = Utils.Convert_text_For_multicast("#0.0#153#" + IMEI + "#" + (Int32)stat + "#"); MainForm.udp.Send(dataToSend, dataToSend.Length); } int sampleRate = 8000; int bitdepth = 16; void readZones() { // code for zone DBsettingsManager dbsett = new DBsettingsManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port); DBalarmManager dbalm = new DBalarmManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port); dbuser = new DBuserManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port); DBvehiclesManager dbveh = new DBvehiclesManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port); DBgatewaysManager dbgate = new DBgatewaysManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port); DBReportingManager dbrep = new DBReportingManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port); try { Int32.TryParse(dbsett.getSettingValue(0, "sampleRate"), out sampleRate); Int32.TryParse(dbsett.getSettingValue(0, "bitDepth"), out bitdepth); MainForm.VehList.Clear(); MainForm.userReportTimeList.Clear(); MainForm.VehStolen.Clear(); //MainForm.VehicleHashStat.Clear(); ImeitoMADEOFFList.Clear(); UserListTMP = dbuser.getAllUsers(); UserList.Clear(); foreach (User obj in UserListTMP) { if (UserList.ContainsKey(obj.Id)) UserList.Remove(obj.Id); UserList.Add(obj.Id, obj.UserName); } // gateways GatewayListTMP = dbgate.getAllGateways(); GatewayList.Clear(); foreach (Gateway obj in GatewayListTMP) { if (GatewayList.ContainsKey(obj.Id)) GatewayList.Remove(obj.Id); GatewayList.Add(obj.Id, (obj.Peer_id > 0)); } // vehicles VehicleListTMP = dbveh.getAllVehicles(); VehicleList.Clear(); foreach (Vehicles obj in VehicleListTMP) { if (VehicleList.ContainsKey(obj.Imei)) VehicleList.Remove(obj.Imei); VehicleList.Add(obj.Imei, obj.VehName); } //VehicleListMobileTMP = dbveh.getAllMobileVehicles(); foreach (Vehicles obj in VehicleListTMP) { if (MobileVehicleList.ContainsKey(obj.Id + "")) MobileVehicleList.Remove(obj.Id + ""); MobileVehicleList.Add(obj.Id + "", obj.Imei); } UserReportTimeListTMP = dbrep.getUserReportTime(); MainForm.userReportTimeList.Clear(); foreach (UserReportTime obj in UserReportTimeListTMP) { if (MainForm.userReportTimeList.ContainsKey(obj.UserID)) MainForm.userReportTimeList.Remove(obj.UserID); MainForm.userReportTimeList.Add(obj.UserID, obj); } dbgate.gelAllGatewaysAndRadioGatewaysHT(ref MainForm.RadioGWHash); dbuser.RefreshUserHT(ref MainForm.userStateHash); SM.Debug("Step1 "); try { if (MainForm.VehList.Count == 0) { VehImeiStatus = dbalm.getImeiLastStatus(); } foreach (Vehicles obj in VehicleListTMP) { if (!MainForm.VehicleHashStat.ContainsKey(obj.Imei)) MainForm.VehicleHashStat.Add(obj.Imei, new VehicleStatus(obj.Gps_poor, obj.Gps_off, obj.Made_off)); else { VehicleStatus vehicleStatus = (VehicleStatus)MainForm.VehicleHashStat[obj.Imei]; //prevent reset lastPositionTime & lastArsTime on create new VehicleStatus object vehicleStatus.gps_poor = obj.Gps_poor; vehicleStatus.gps_off = obj.Gps_off; vehicleStatus.made_off = obj.Made_off; } } if (firstStartProccesStatus) { DBgatewaysManager dbgateway = new DBgatewaysManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port); RadioListIP = dbgateway.get_all_GatewaywithIDandIP(); firstStartProccesStatus = false; VehLastPos = dbveh.GetLastPos(); //define status now foreach (UnitGpsPos obj in VehLastPos) { //if ((obj.status != 0) && (obj.status != 7) && (obj.status != 8) && (obj.status != 9)) if ((obj.status != (int)Status_for_tab.OFF) && (obj.status != (int)Status_for_tab.DISABLE) && (obj.status != (int)Status_for_tab.EMERG) && (obj.status != (int)Status_for_tab.MADEOFF)) { nrSecond = DateTime.Now.GetSecondsLocalFromDT() - (uint)obj.timeGMT; //Utils.WriteLine("Nr second:" + nrSecond + " Imei:" + obj.IMEI, ConsoleColor.Green); if (MainForm.VehicleHashStat[obj.IMEI] != null) { VehicleStatus vehicleStatus = (VehicleStatus)MainForm.VehicleHashStat[obj.IMEI]; // save last position time vehicleStatus.lastPositionTime = ((uint)obj.timeGMT).GetDTLocalFromSeconds(); if (vehicleStatus.made_off <= nrSecond) { PushStatus(obj.IMEI, Status_for_tab.MADEOFF); vehicleStatus.curentStatus = Status_for_tab.MADEOFF; } else if (vehicleStatus.gps_off <= nrSecond) { PushStatus(obj.IMEI, Status_for_tab.GPS_OFF); vehicleStatus.curentStatus = Status_for_tab.GPS_OFF; } else if (vehicleStatus.gps_poor <= nrSecond) { PushStatus(obj.IMEI, Status_for_tab.GPS_POOR); vehicleStatus.curentStatus = Status_for_tab.GPS_POOR; } else { if (obj.status == (int)Status_for_tab.GPS_ON) { Int64 left = DateTime.Now.GetSecondsLocalFromDT(); Int64 right = (uint)obj.timeGMT; nrSecond = (uint)Math.Abs(left - right); if (vehicleStatus.made_off <= nrSecond) { ImeitoMADEOFFList.Add(obj.IMEI); } } else if ((obj.status == (int)Status_for_tab.NOGPSFIX) || (obj.status == (int)Status_for_tab.ON)) { if ((Int64)Math.Abs(vehicleStatus.made_off - nrSecond) * 1000 < Int32.MaxValue) ; } vehicleStatus.curentStatus = (Status_for_tab)obj.status; } } } else { if (MainForm.VehicleHashStat[obj.IMEI] != null) ((VehicleStatus)MainForm.VehicleHashStat[obj.IMEI]).curentStatus = (Status_for_tab)obj.status; } } } } catch (Exception ex) { SM.Debug("Error on putting the status:"+ex.ToString()); try { foreach (Vehicles obj in VehicleListTMP) { if (!MainForm.VehicleHashStat.Contains(obj.Imei)) MainForm.VehicleHashStat.Add(obj.Imei, new VehicleStatus(obj.Gps_poor, obj.Gps_off, obj.Made_off)); } foreach (String obj in MainForm.VehicleHashStat.Keys) ((VehicleStatus)MainForm.VehicleHashStat[obj]).curentStatus = Status_for_tab.OFF; } catch (Exception exe) { SM.Debug("Error on put all the stuff OFF:"+exe.ToString()); } } reloadEmergHashes(); // populate vehicles list if (MainForm.VehList.Count == 0) { //old code Utils.WriteLine("Compute zone first time init Vehlist"); ZoneList = dbalm.get_all_zone(); LandList = dbalm.get_all_landmarks(); Dictionary usersSpeedUnits = dbuser.getAllUsersSpeedUnit(); MainForm.VehList = dbalm.get_Vehicle_and_zone(); #region DISPLAY ALL UNITS IDs TO CONSOLE Utils.WriteLine("=================================================================="); Utils.WriteLine($"Received {MainForm.VehList.Count } vehicles", ConsoleColor.Green); int i = 0; foreach(Vehicle_Data veh in MainForm.VehList.Cast().ToList() .Select(d => d.Value).OrderBy(d => ((Vehicle_Data)d).imei)) { //Vehicle_Data veh = (pair.Value as Vehicle_Data); Utils.Write(String.Format("{0,15}", veh.imei + (veh.active ? " [X]" : "[ ]") ), ConsoleType.ALL); if (i % 5 == 0) Utils.Write("|\n", ConsoleType.ALL); i++; } Utils.Write("\n", ConsoleType.ALL); Utils.WriteLine("=================================================================="); #endregion if ((ZoneList.Count != 0) || (LandList.Count != 0)) { Utils.WriteLine("Compute zone first time if i have some zones or LANDmarks"); foreach (String obj in MainForm.VehList.Keys) { Vehicle_Data vehicle_Data = (Vehicle_Data)MainForm.VehList[obj]; ArrayList tmparr = new ArrayList(); foreach (ZoneClass obj2 in ZoneList) { ZoneClass tmp = new ZoneClass(obj2, obj2.id, obj2.arrSc_id); if (!usersSpeedUnits.ContainsKey(tmp.useridx)) usersSpeedUnits.Add(tmp.useridx, "m"); tmp.speedUnit = usersSpeedUnits[tmp.useridx]; tmparr.Add(tmp); } vehicle_Data.zonelist = tmparr; ArrayList tmparr2 = new ArrayList(); foreach (LandMark obj2 in LandList) { LandMark tmp = new LandMark(obj2.name, obj2.lat, obj2.lng, obj2.land_id, obj2.useridx, obj2.callout, obj2.calloutSeverity); if (!usersSpeedUnits.ContainsKey(tmp.useridx)) usersSpeedUnits.Add(tmp.useridx, "m"); tmp.speedUnit = usersSpeedUnits[tmp.useridx]; tmparr2.Add(tmp); } vehicle_Data.landlist = tmparr2; } foreach (String obj in MainForm.VehList.Keys) { Vehicle_Data vehicle_Data = (Vehicle_Data)MainForm.VehList[obj]; foreach (ZoneClass obj2 in vehicle_Data.zonelist) obj2.CheckZone(vehicle_Data.lat, vehicle_Data.lng, out postmp); foreach (LandMark obj2 in vehicle_Data.landlist) obj2.CheckPosition(vehicle_Data.lat, vehicle_Data.lng); } } } else { //new code made calcation for zone only if something change Console.WriteLine("Compute zone calculation only something is change"); ZoneListTMP = dbalm.get_all_zone(); LandListTMP = dbalm.get_all_landmarks(); /// condition to recalculate zone if ((ZoneListTMP.Count != 0) || (LandListTMP.Count != 0)) { VehListTMP = dbalm.get_Vehicle_and_zone(); // check if zone ID is change try { wehaveChange = false; foreach (ZoneClass obj in ZoneListTMP) { findid = false; foreach (ZoneClass obj2 in ZoneList) if (obj.id == obj2.id) { findid = true; break; } if (!findid) { wehaveChange = true; break; } } } catch (Exception ex) { SM.Debug("Error compare zone ID"+ex.ToString()); } // end check zone ID change if ((VehListTMP.Count != MainForm.VehList.Count) || (ZoneListTMP.Count != ZoneList.Count) || (LandListTMP.Count != LandList.Count) || (wehaveChange)) { Console.WriteLine("Something is change on Zone or Landmark begin proccess"); foreach (String obj in VehListTMP.Keys) { Vehicle_Data vehicle_Data = (Vehicle_Data)VehListTMP[obj]; // populate Zone list ArrayList tmparr = new ArrayList(); foreach (ZoneClass obj2 in ZoneListTMP) { tmparr.Add(new ZoneClass(obj2, obj2.id, obj2.arrSc_id)); } vehicle_Data.zonelist = tmparr; // populate Landmark list ArrayList tmparr2 = new ArrayList(); foreach (LandMark obj2 in LandListTMP) { tmparr2.Add(new LandMark(obj2.name, obj2.lat, obj2.lng, obj2.land_id, obj2.useridx, obj2.callout, obj2.calloutSeverity)); } vehicle_Data.landlist = tmparr2; } foreach (String obj in VehListTMP.Keys) { Vehicle_Data vehicle_Data = (Vehicle_Data)VehListTMP[obj]; foreach (ZoneClass obj2 in vehicle_Data.zonelist) obj2.CheckZone(vehicle_Data.lat, vehicle_Data.lng, out postmp); foreach (LandMark obj2 in vehicle_Data.landlist) obj2.CheckPosition(vehicle_Data.lat, vehicle_Data.lng); } //clear all ZoneList.Clear(); LandList.Clear(); MainForm.VehList.Clear(); // move from TMP used List ZoneList.AddRange(ZoneListTMP); LandList.AddRange(LandListTMP); foreach (String obj in VehListTMP.Keys) { Vehicle_Data tmp = (Vehicle_Data)VehListTMP[obj]; MainForm.VehList.Add(obj, tmp); } MainForm.VehListWithGroupDetails.Clear(); List list = dbvehs.getAllVehicles(); foreach (Vehicles veh in list) { // remove old object if still exists if (MainForm.VehListWithGroupDetails.Contains(veh.Imei)) MainForm.VehListWithGroupDetails.Remove(veh.Imei); MainForm.VehListWithGroupDetails.Add(veh.Imei, veh); } } } } Utils.WriteLine("Before updating status"); foreach (String obj in ImeitoMADEOFFList) { PushStatus(obj, Status_for_tab.MADEOFF); ((VehicleStatus)MainForm.VehicleHashStat[obj]).curentStatus = Status_for_tab.MADEOFF; System.Threading.Thread.Sleep(10); } } catch (Exception ex) { Console.WriteLine("Error load zone " + ex.ToString()); //Console.ReadKey(true); if (!messageOnScreen) { messageOnScreen = true; try { byte[] dataToSend = Utils.Convert_text_For_multicast("#Application server database connection failed#"); MainForm.udp.Send(dataToSend, dataToSend.Length); } catch (Exception ex2) { SM.Debug("Error on sending Message to SD that APPServer has problem: " + ex2.ToString()); } try { Utils.WriteEventLog(Program.COMPANY, "AppServer restart imminent due to DB connection failed", EventLogEntryType.Information, 3152); } catch (Exception exe) { SM.Debug("Unable to write log Event ex:" + exe.ToString()); } //short initial = FeedbackRadMessageBox.InteractionWaitSeconds; //FeedbackRadMessageBox.InteractionWaitSeconds = 1; FeedbackRadMessageBox.ShowError("DB connection failed!!!Please check DB server and restart Application server!!", "App Server Database Error"); //FeedbackRadMessageBox.InteractionWaitSeconds = initial; Environment.Exit(0); } } } private void reloadEmergHashes() { try { //DB = new DBmanager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port); //DB.InitConnection(); //load vehs for stolen test dbvehs = new DBvehiclesManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port); dbsubsoperManage = new DBsubsOperationManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port); List list = dbvehs.getAllVehicles(); MainForm.VehListWithGroupDetails.Clear(); foreach (Vehicles veh in list) { // remove old object if still exists if (MainForm.VehStolen.Contains(veh.Imei)) MainForm.VehStolen.Remove(veh.Imei); MainForm.VehStolen.Add(veh.Imei, veh.IsStolen); if (EmergencyHash.Contains(veh.Imei)) EmergencyHash.Remove(veh.Imei); EmergencyHash.Add(veh.Imei, new DateTime(0)); // remove old object if still exists if (MainForm.VehListWithGroupDetails.Contains(veh.Imei)) MainForm.VehListWithGroupDetails.Remove(veh.Imei); MainForm.VehListWithGroupDetails.Add(veh.Imei, veh); } dbCallPatch = new DBcallPatchManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port); } catch (Exception ex) { SM.Debug(ex.ToString()); } } 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 { MailAddress from = new MailAddress(Program.cfg.emailAddress); MailAddress to = new MailAddress(mailAdr); MailMessage message = new MailMessage(from, to); message.Subject = "Alarm"; message.Body = mes; EmailServerSSL.sendEmail(Program.cfg.smtpServer, Program.cfg.smtpPort, Program.cfg.emailAddress, Program.cfg.emailPassword, message, Program.cfg.smtpSSLState); } catch (Exception ex) { if (ex.ToString().Contains("timed out")) MainForm.HandleTimeoutError(mailAdr); Utils.WriteLine("Exception in sendMailAlarm: " + ex.ToString(), ConsoleColor.Red); //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) { try { MailAddress from = new MailAddress(Program.cfg.emailAddress); //MailAddress to = new MailAddress(mailAdr); String[] address = mailAdr.Split(";".ToCharArray()); MailAddress to = new MailAddress(address[0]); MailMessage message = new MailMessage(from, to); if (address.Count() > 1) { Boolean skipeFirst=true; foreach (String obj in address) { if (skipeFirst) { skipeFirst = false; } else message.To.Add(new MailAddress(obj)); } } message.Subject = "Daily Reports from " + Program.COMPANY + " Dispatch System"; message.Body = "Hello you have attached a PDF file with you Daily Reports from " + Program.COMPANY + " Dispatch System"; // Create the file attachment for this e-mail message. Attachment data = new Attachment(PdfFile, MediaTypeNames.Application.Octet); // Add time stamp information for the file. ContentDisposition disposition = data.ContentDisposition; disposition.CreationDate = System.IO.File.GetCreationTime(PdfFile); disposition.ModificationDate = System.IO.File.GetLastWriteTime(PdfFile); disposition.ReadDate = System.IO.File.GetLastAccessTime(PdfFile); // Add the file attachment to this e-mail message. message.Attachments.Add(data); MainForm.ReportEmailQueue.PostItem(message); } catch (Exception ex) { SM.Debug("Exception in sendMailReport: "+ex.ToString()); //Console.WriteLine(e.ToString()); } } private void ComputeZones(Object state) { // This method is executed by a thread pool thread Console.WriteLine("Computing Zones"); MainForm.ZonesBussy = true; readZones(); MainForm.ZonesBussy = false; } private uint DateTo70Format(DateTime param) { long nOfSeconds; //Console.WriteLine("DateTo70Format param=" + param); System.DateTime dt70 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); TimeSpan span = param - dt70; nOfSeconds = (long)span.TotalSeconds; return ((uint)nOfSeconds); } #endregion #region email private void CheckMail(Object state) { // This method is executed by a thread pool thread try { if (Program.cfg.enableEmailService) { 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"); if (emailHT.Count > 0) { SM.Debug("Load " + emailHT.Count + " subscribers emails from DB ..."); } if (sslServer == null) { SM.Debug("sslServer is null"); return; } Int64 latestEmailTime = sslServer.getLastEmailTime(); ArrayList EmailList = sslServer.getEmails(); // update the latest email time if changed if (latestEmailTime < sslServer.getLastEmailTime()) { DBemailServiceManager DB = new DBemailServiceManager(Program.cfg.DB_IP, Program.cfg.DB_schema, Program.cfg.DB_user, Program.cfg.DB_passwd, Program.cfg.DB_port); 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); foreach (EmailtoSMS obj in EmailList) { String seqID = "0." + (DateTime.Now.GetSecondsLocalFromDT()) + DateTime.Now.Millisecond.ToString(); SM.Debug(new string[] { "-----START OK----", "From: " + obj.from, "ID: " + obj.id, "Text: " + obj.text}); try { // app server idx =0 //bigu code remove # from text and also replace "'" try { obj.text = obj.text.Replace("'", "`"); obj.text = obj.text.Replace("#", " "); } catch (Exception ex) { SM.Debug("Error on converting email:" + ex.ToString()); } //end bigu code if (!obj.is_group) DBsms.insert_sms_received(obj.id, obj.text, 7, obj.from, seqID); if (obj.is_sierra) { if (emailHT.Contains(obj.from)) { SM.Debug("Email received <<" + obj.text + ">> from address: " + obj.from); seqID = "1." + Utils.GetSecondsLocalFromDT(DateTime.Now).ToString() + DateTime.Now.Millisecond.ToString(); 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; System.Text.Encoding enc = System.Text.Encoding.ASCII; byte[] buf = enc.GetBytes(cmdok); //send to messagebus MainForm.udp.Send(buf, buf.Length); SM.Debug("Email thread successfully sent data to message bus"); } } } catch (Exception ex) { Utils.WriteLine(ex.ToString(), ConsoleColor.Red); } if (obj.text.Length > 140 - 3 - obj.from.Length) obj.text = obj.text.Remove(140 - 3 - obj.from.Length) + " [" + obj.from + "]"; else obj.text = obj.text + " [" + obj.from + "]"; //send SMS on message buss if (!obj.is_sierra) { if (dbvehs != null) { 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 code = (obj.is_group) ? "#144#" : "#143#" ; byte[] msg = Utils.Convert_text_For_multicast("#0.0" + code + cmd); if (msg != null && msg.Length > 0) MainForm.udp.Send(msg, msg.Length); if (obj.is_group) { Int32 oldgatewayID = 0; foreach (RadioGateway obj2 in RadioListIP) { if (oldgatewayID != obj2.Gw_id) { oldgatewayID = (Int32)obj2.Gw_id; cmd = $"#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); if( msg2 != null && msg2.Length > 0) MainForm.udp.Send(msg2, msg2.Length); } } } } } } SM.Debug("Email check done!!!"); } else { SM.Debug("Email disabled"); } } catch (Exception ex) { SM.Debug("Error on CheckMAil:" + ex.ToString()); } } //sms-> email private void sendMail( string mailAdr, string mailBody, int radioID) { 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()); try { MailMessage message = new MailMessage(); message.From = new MailAddress(Program.cfg.emailAddress); message.To.Add(mailAdr); message.Subject = "RadioID: " + radioID.ToString() + " Subject:" + (mailBody.Length < 25 ? mailBody : (mailBody.Remove(25) + "...")); message.Body = "You received a message from radio id " + radioID.ToString() + "\n------------------------------\n" + mailBody + "\n------------------------------\n "; message.IsBodyHtml = true; EmailServerSSL.sendEmail(Program.cfg.smtpServer, Program.cfg.smtpPort, Program.cfg.emailAddress, Program.cfg.emailPassword, message, Program.cfg.smtpSSLState); } 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); } } else { Utils.WriteLine($"Missing email address From = {Program.cfg.emailAddress} To = {mailAdr})", ConsoleColor.Red); } } else { SM.Debug("email disabled"); } } //sms-> email Sierra Wireless 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); try { MailMessage message = new MailMessage(); message.From = new MailAddress(Program.cfg.emailAddress); message.To.Add(mailAdr); message.Body = mailBody; message.IsBodyHtml = true; EmailServerSSL.sendEmail(Program.cfg.smtpServer, Program.cfg.smtpPort, Program.cfg.emailAddress, Program.cfg.emailPassword, message, Program.cfg.smtpSSLState); } 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); } } else { Utils.WriteLine($"Missing email address From = {Program.cfg.emailAddress} To = {mailAdr})", ConsoleColor.Red); } } else { SM.Debug("email disabled"); } } #endregion #region DB backup/restore private DBbackup backup; private BackgroundWorker bgWorkerDBbackup; private volatile bool backupDOne = false; #region bg worker DBbackup events void bgWorkerDBbackup_DoWork(object sender, DoWorkEventArgs e) { object[] param = (object[])e.Argument; if (backup.performBackupPostgres(param[0].ToString(), param[1].ToString())) { Console.WriteLine(" Backup done."); backupDOne = true; } else { Console.WriteLine(" Backup failed."); backupDOne = false; } } void bgWorkerDBbackup_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { //send emergency alarm to SD //send ACK back to GW string code = (backupDOne == true) ? "#61#1#" : "#61#0#"; byte[] dataToSend = Utils.Convert_text_For_multicast("#0.0" + code); MainForm.udp.Send(dataToSend, dataToSend.Length); } #endregion private BackgroundWorker bgWorkerDBrestore; private volatile bool restoreDOne; #region bg worker DBrestore events void bgWorkerDBrestore_DoWork(object sender, DoWorkEventArgs e) { object[] param = (object[])e.Argument; if (backup.performRestorePostgres(param[0].ToString(), param[1].ToString())) { Console.WriteLine(" restore done."); restoreDOne = true; } else { Console.WriteLine(" restore failed."); restoreDOne = false; } } void bgWorkerDBrestore_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { //send emergency alarm to SD //send ACK back to GW string code = (restoreDOne == true) ? "#62#1#" : "#252#0#"; byte[] dataToSend = Utils.Convert_text_For_multicast("#0.0" + code); MainForm.udp.Send(dataToSend, dataToSend.Length); } #endregion private string getAllBackups(string dirFolder) { SM.Debug("Searching for backups in:" + dirFolder); string ret=""; if (!Directory.Exists(dirFolder)) return ""; DirectoryInfo di = new DirectoryInfo(dirFolder); di.Refresh(); FileInfo[] fileNames = di.GetFiles("*.tar"); for (int i = 1; i < 35; i++) { //get last backups if((fileNames.Length - i)>=0) ret += fileNames[fileNames.Length - i].Name + ";"; } Utils.WriteLine(ret, ConsoleColor.Green); return ret; } #endregion public delegate void RefreshHashRequest(); public event RefreshHashRequest OnRefreshHashRequest; public delegate void DatabaseDownDel(); public event DatabaseDownDel OnDatabaseDown; public delegate void EmergencyAckDelegate(String seqID, String radioID); public event EmergencyAckDelegate OnEmergencyAckReceived; public delegate void PollRequestDelegate(String seqID, String radioID); public event PollRequestDelegate OnPollRequestReceived; } }