SafeDispatch/ServiceGatewaySDR/MessageBuss.cs

319 lines
15 KiB
C#
Raw Permalink Normal View History

2024-02-22 16:43:59 +00:00
using SafeMobileLib;
using SDRGatewayService.Enums;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SDRGatewayService
{
class MessageBuss
{
private string messageBusIP;
private int messageBusPort;
private GeneralLocationManager GM;
private Thread t_GPS;
private Thread t_EVENT;
private Thread t_SMS;
private static UdpMulticast udp;
private SDR parentSDR = null;
public MessageBuss(string messageBusIP, string messageBusPort, SDR _parentSDR)
{
this.messageBusIP = messageBusIP;
this.messageBusPort = Convert.ToInt32(messageBusPort);
this.parentSDR = _parentSDR;
try
{
udp = new UdpMulticast(messageBusIP, this.messageBusPort);
Utils.WriteEventLog(Program.COMPANY, "MessageBuss ip:" + messageBusIP + " port:" + this.messageBusPort, EventLogEntryType.Information, (int)EventId.EVENT_MSGBUS);
//Main.activityQueue.PostItem(new RepString("MessageBuss ip:" + messageBusIP + " port:" + this.messageBusPort, Color.Green));
udp.OnNewDataRecv += new UdpMulticast.newData4Send(udp_OnNewDataRecv);
udp.StartListen();
}
catch (Exception ex)
{
Utils.WriteEventLog(Program.COMPANY, "MessageBuss exception while joining the message bus: " + ex.ToString(), EventLogEntryType.Error, (int)EventId.EVENT_MSGBUS);
//Main.activityQueue.PostItem(new RepString("Error:" + ex.Message, Color.Red));
}
//start messageBus for location
GM = new GeneralLocationManager(udp);
//start Process thread (handle GPS)
t_GPS = new Thread(new ThreadStart(Process_GPS));
t_GPS.IsBackground = true;
t_GPS.Start();
//start Process thread (handle EVENTS)
t_EVENT = new Thread(new ThreadStart(Process_EVENT));
t_EVENT.IsBackground = true;
t_EVENT.Start();
//start Process thread (handle SMS)
t_SMS = new Thread(new ThreadStart(Process_SMS));
t_SMS.IsBackground = true;
t_SMS.Start();
}
public static DateTime UnixTimeStampToDateTime(int unixTimeStamp)
{
// Unix timestamp is seconds past epoch
System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
dtDateTime = dtDateTime.AddSeconds(unixTimeStamp).ToLocalTime();
return dtDateTime;
}
void udp_OnNewDataRecv(byte[] data, int dataLen)
{
try
{
string str = System.Text.Encoding.ASCII.GetString(data, 0, dataLen);
//Utils.WriteLine($"--- MB [{str}]", ConsoleColor.Green);
String[] tempArray = str.Trim().Split(new char[] { '#' });//, StringSplitOptions.RemoveEmptyEntries);
if (tempArray.Length > 3)
{
//SMS message
if (tempArray[3].Equals("142") || tempArray[3].Equals("143"))
{
Utils.WriteEventLog(Program.COMPANY, "On SMS Request received [" + str.Trim() + "]", EventLogEntryType.Information, (int)EventId.EVENT_MSGBUS);
//Main.activityQueue.PostItem(new RepString("RX(multi SMS): " + str.Trim(), Color.DarkOrange));
// Console.WriteLine("SMSSendThread received from multicast bus: " + str.Trim());
int sched_timeGMT = 0;
if (tempArray.Length > 6)
sched_timeGMT = Convert.ToInt32(tempArray[6]);
// Console.WriteLine("SMS sched time={0} and current time ={1}",sched_timeGMT, DBmanager.DateTo70Format(DateTime.Now.ToUniversalTime()));
int gwid_recv = Convert.ToInt32((tempArray[4].Split('.'))[0]);
OnSDSRequest(Int64.Parse(tempArray[4].Split('.')[2]), gwid_recv,
Convert.ToInt32((tempArray[4].Split('.'))[1]),
tempArray[5], sched_timeGMT, tempArray[2]);
}
if (tempArray[3].Equals("154"))
{
Utils.WriteEventLog(Program.COMPANY, "On Poll Request received [" + str.Trim() + "]", EventLogEntryType.Information, (int)EventId.EVENT_MSGBUS);
//Main.activityQueue.PostItem(new RepString("RX(multi POLL): " + str.Trim(), Color.DarkOrange));
string SUID = (tempArray[4].Split('.'))[2];
try
{
if (tempArray.Length > 6)
OnPollRequest?.Invoke(Int64.Parse(SUID), int.Parse(tempArray[5]) == 1 ? true : false, tempArray[2]);
else
OnPollRequest?.Invoke(Int64.Parse(SUID), true, tempArray[2]);
}
catch (Exception ex)
{
Utils.WriteEventLog(Program.COMPANY, "Exception Poll request received: " + ex.ToString(), EventLogEntryType.Error, (int)EventId.EVENT_MSGBUS);
OnPollRequest?.Invoke(Int64.Parse(SUID), true, tempArray[2]);
}
//parentSDR.Send_Imed_Loc_req(Convert.ToUInt32(SUID), false);
}
if (tempArray[3].Equals("209"))
{
// raise event for units changed in the admin module
OnUnitsUpdated?.Invoke();
}
//receive CallOut
if (tempArray[3].Equals("177"))
{
string SUID = (tempArray[4]);
Utils.WriteEventLog(Program.COMPANY, "On CallOut Request received [" + str.Trim() + "]", EventLogEntryType.Information, (int)EventId.EVENT_MSGBUS);
try
{
OnCallOutRequest?.Invoke(UInt32.Parse(tempArray[4]), UInt16.Parse(tempArray[5]), tempArray[6]);
}
catch (Exception ex)
{
Utils.WriteEventLog(Program.COMPANY, "Exception CallOut request received: " + ex.ToString(), EventLogEntryType.Error, (int)EventId.EVENT_MSGBUS);
OnCallOutRequest?.Invoke(UInt32.Parse(tempArray[4]), UInt16.Parse(tempArray[5]), tempArray[6]);
}
}
//receive CallOut Stop
if (tempArray[3].Equals("178"))
{
string SUID = (tempArray[4]);
Utils.WriteEventLog(Program.COMPANY, "On CallOut Stop Request received [" + str.Trim() + "]", EventLogEntryType.Information, (int)EventId.EVENT_MSGBUS);
OnCallOutStopRequest?.Invoke(UInt32.Parse(tempArray[4]), UInt16.Parse(tempArray[5]));
}
}//if (tempArray.Length > 3)
}
catch (Exception ex)
{
Utils.WriteEventLog(Program.COMPANY, ex.ToString(), EventLogEntryType.Error, (int)EventId.EVENT_MSGBUS);
//Main.activityQueue.PostItem(new RepString("Error:" + ex.Message, Color.Red));
}
}
private double LATtest = 0;
private double LNGtest = 0;
private double Speedtest = 0;
private void Process_GPS()
{
Utils.WriteEventLog(Program.COMPANY, "Message buss message handler for GPS started!!!", EventLogEntryType.Information, (int)EventId.EVENT_MSGBUS);
//Main.activityQueue.PostItem(new RepString("Message buss message handler for GPS started!!!", Color.DarkOrange));
while (true)
{
try
{
msgCell cell = Program.gpsQueue.GetItem(100);
if (cell != null)
{
if (cell.msg == MSG_TYPE.GPS || cell.msg == MSG_TYPE.GPSpoll)
{
uint time70 = cell.time.DateTo70Format();
//if (cell.time70 != 0) time70 = cell.time70;
//double tempSpeed = double.Parse(cell.spd);
//tempSpeed = tempSpeed * 3.6; // convert from knots to KM
//cell.spd = ((int)tempSpeed).ToString();
// test before LAT LNG SPEED before put on the message bus
if ((Double.TryParse(cell.lat, out LATtest)) && (Double.TryParse(cell.lng, out LNGtest)) && (Double.TryParse(cell.spd, out Speedtest)))
if ((LATtest < 90) && (LATtest > -90) && (LNGtest < 180) && (LNGtest > -180) && (Speedtest < 250))
GM.SendLoc2messagebus(cell.IMEI, time70, cell.spd, cell.lat, cell.lng, cell.poll);
else GM.SendLoc2messagebus(cell.IMEI, time70, "0", "0", "0", cell.poll);
//Main.activityQueue.PostItem(new RepString("GPS sent on messagebuss", Color.DarkOrange));
}
}
Thread.Sleep(1);
}
catch (Exception ex)
{
Utils.WriteEventLog(Program.COMPANY, "Error in MessageBuss/Process \n" + ex.ToString(), EventLogEntryType.Error, (int)EventId.EVENT_MSGBUS);
Thread.Sleep(1000);
//Main.activityQueue.PostItem(new RepString("Error:" + ex.Message, Color.Red));
}
}
}
private void Process_EVENT()
{
Utils.WriteEventLog(Program.COMPANY, "Message buss message handler for EVENTS started!!!", EventLogEntryType.Information, (int)EventId.EVENT_MSGBUS);
//Main.activityQueue.PostItem(new RepString("Message buss message handler for EVENTS started!!!", Color.DarkOrange));
while (true)
{
try
{
msgCell cell = Program.eventQueue.GetItem(100);
if (cell != null)
{
if (cell.msg == MSG_TYPE.ARS)
{
String seqID = "0." + (DateTime.Now.GetSecondsLocalFromDT()) + DateTime.Now.Millisecond.ToString();
string msg = "#130#" + cell.IMEI + "#" + ((cell.ars == 1) ? "ON" : "OFF") + "#";
SendOnMsgBuss(seqID, msg);
//Main.activityQueue.PostItem(new RepString("ARS sent on messagebuss", Color.DarkOrange));
}
if (cell.msg == MSG_TYPE.Emergency)
{
String seqID = "0." + (DateTime.Now.GetSecondsLocalFromDT()) + DateTime.Now.Millisecond.ToString();
string msg = "#138#" + cell.IMEI + "#";
SendOnMsgBuss(seqID, msg);
// request gps position after each emergency
if (OnPollRequest != null)
OnPollRequest(Int64.Parse(cell.IMEI), true, seqID);
}
}
Thread.Sleep(1);
}
catch (Exception ex)
{
Utils.WriteEventLog(Program.COMPANY, "Error in MessageBuss/Process \n" + ex.ToString(), EventLogEntryType.Error, (int)EventId.EVENT_MSGBUS);
//Main.activityQueue.PostItem(new RepString("Error:" + ex.Message, Color.Red));
Thread.Sleep(1000);
}
}
}
private void Process_SMS()
{
Utils.WriteEventLog(Program.COMPANY, "###################"+ Environment.NewLine +
"Message buss message handler for SMS started!!!" + Environment.NewLine +
"###################", EventLogEntryType.Information, (int)EventId.EVENT_MSGBUS);
//Main.activityQueue.PostItem(new RepString("Message buss message handler for SMS started!!!", Color.DarkOrange));
while (true)
{
try
{
msgCell cell = Program.smsINQueue.GetItem(100);
if (cell != null)
{
if (cell.msg == MSG_TYPE.SMS)
{
String seqID = "0." + (DateTime.Now.GetSecondsLocalFromDT()) + DateTime.Now.Millisecond.ToString();
string msg = "#132#" + cell.IMEI + "#" + cell.sms + "#hyt#";
Utils.WriteEventLog(Program.COMPANY, "SMS [" + cell.sms + "] Received from " + cell.IMEI, EventLogEntryType.Information, (int)EventId.EVENT_MSGBUS);
SendOnMsgBuss(seqID, msg);
}
}
Thread.Sleep(1);
}
catch (Exception ex)
{
Utils.WriteEventLog(Program.COMPANY, "Error in MessageBuss/Process \n" + ex.ToString(), EventLogEntryType.Error, (int)EventId.EVENT_MSGBUS);
//Main.activityQueue.PostItem(new RepString("Error:" + ex.Message, Color.Red));
Thread.Sleep(1000);
}
}
}
public static void SendOnMsgBuss(string seqID, string test)
{
if (udp != null)
{
byte[] toSend = SafeMobileLib.Utils.Convert_text_For_multicast("#" + seqID + test);
udp.Send(toSend, toSend.Length);
Utils.WriteEventLog(Program.COMPANY, String.Format("+++ MB [{0}] ", Utils.ConvertBytesToString(toSend)), EventLogEntryType.Information, (int)EventId.EVENT_MSGBUS);
}
else
{
Utils.WriteEventLog(Program.COMPANY, "Error!!! SendOnMsgBuss messagebus =null", EventLogEntryType.Error, (int)EventId.EVENT_MSGBUS);
}
}
#region EVENTS REGION
public delegate void UnitsUpdated();
public event UnitsUpdated OnUnitsUpdated;
public delegate void PollRequest(Int64 radioID, bool isLong, string seqNumber);
public event PollRequest OnPollRequest;
public delegate void SDSRequest(Int64 radioID, Int64 gatewayID, Int64 gatewayRadioID, string message, int type, string seqID);
public event SDSRequest OnSDSRequest;
public delegate void CallOut(UInt64 destISSI, UInt16 callOutSeverity, string GeoName);
public event CallOut OnCallOutRequest;
public delegate void CallOutStop(UInt64 destISSI, UInt16 callOutSeverity);
public event CallOutStop OnCallOutStopRequest;
#endregion
}
}