SafeDispatch/SDRgateway/MessageBuss.cs

338 lines
15 KiB
C#
Raw Normal View History

2024-02-22 16:43:59 +00:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SafeMobileLib;
using System.Threading;
using System.Drawing;
namespace SDRgateway
{
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.WriteLine("MessageBuss ip:" + messageBusIP + " port:" + this.messageBusPort);
//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.WriteLine("MessageBuss exception while joining the message bus: " + ex.ToString(), ConsoleColor.Red);
//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.WriteLine("On SMS Request received [" + str.Trim() + "]");
//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 (sched_timeGMT <= (DBmanager.DateTo70Format(DateTime.Now.ToUniversalTime())+60))
{
Console.WriteLine("Past time check!!!!");
String IMEI = (tempArray[4].Split('.'))[2];
msgCell cell = new msgCell();
cell.IMEI = IMEI;
cell.sms = tempArray[5];
Program.smsOutQueue.PostItem(cell);
string test = "#242#1#";
String cmdok = "#" + tempArray[2] + 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 SMS ack
udp.Send(buf, buf.Length);
}
*/
}//if (tempArray[3].Equals("142") || tempArray[3].Equals("143"))
if (tempArray[3].Equals("154"))
{
Utils.WriteLine("On Poll Request received [" + str.Trim() + "]");
//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.WriteLine("Exception Poll request received: " + ex.ToString(), ConsoleColor.Red);
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.WriteLine("On CallOut Request received [" + str.Trim() + "]");
try
{
OnCallOutRequest?.Invoke(UInt32.Parse(tempArray[4]), UInt16.Parse(tempArray[5]), tempArray[6]);
}
catch (Exception ex)
{
Utils.WriteLine("Exception CallOut request received: " + ex.ToString(), ConsoleColor.Red);
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.WriteLine("On CallOut Stop Request received [" + str.Trim() + "]");
OnCallOutStopRequest?.Invoke(UInt32.Parse(tempArray[4]), UInt16.Parse(tempArray[5]));
}
}//if (tempArray.Length > 3)
}
catch (Exception ex)
{
SM.Debug(ex.ToString());
//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.WriteLine("Message buss message handler for GPS started!!!");
//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.WriteLine("Error in MessageBuss/Process \n" + ex.ToString(), ConsoleColor.Red);
Thread.Sleep(1000);
//Main.activityQueue.PostItem(new RepString("Error:" + ex.Message, Color.Red));
}
}
}
private void Process_EVENT()
{
Utils.WriteLine("Message buss message handler for EVENTS started!!!");
//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.WriteLine("Error in MessageBuss/Process \n" + ex.ToString(), ConsoleColor.Red);
//Main.activityQueue.PostItem(new RepString("Error:" + ex.Message, Color.Red));
Thread.Sleep(1000);
}
}
}
private void Process_SMS()
{
Utils.WriteLine("###################", ConsoleColor.Yellow);
Utils.WriteLine("Message buss message handler for SMS started!!!", ConsoleColor.Yellow);
Utils.WriteLine("###################", ConsoleColor.Yellow);
//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.WriteLine("SMS [" + cell.sms + "] Received from " + cell.IMEI, ConsoleColor.Yellow);
SendOnMsgBuss(seqID, msg);
}
}
Thread.Sleep(1);
}
catch (Exception ex)
{
Utils.WriteLine("Error in MessageBuss/Process \n" + ex.ToString(), ConsoleColor.Red);
//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.WriteLine(String.Format("+++ MB [{0}] ", Utils.ConvertBytesToString(toSend)), ConsoleColor.White);
}
else
{
Utils.WriteLine("Error!!! SendOnMsgBuss messagebus =null", ConsoleColor.Red);
}
}
#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
}
}