SafeDispatch/MotoTrbo_GW/EmergencyThread.cs
2024-02-22 18:43:59 +02:00

122 lines
4.0 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using MotoTRBO_GW;
using SafeMobileLib;
using System.Collections;
using System.Threading;
using MotoTRBO_XNL_Cmd;
namespace MotoTrbo_GW
{
class EmergencyThread
{
private string user4radioCon = "emergency";
private Int32 port;
private UdpMulticast udpMulticast;
private string trboRadioIP;
private String mIP;
private Int32 mPort;
private RadioConnection rc;
private bool ack_needed = false;
private System.Threading.Timer timer;
public EmergencyThread(RadioConnection rc_var,string trboIP, Int32 emergencyPort, String multicastID, String multicastPort)
{
port = emergencyPort;
trboRadioIP = trboIP;
mIP = multicastID;
mPort = Int32.Parse(multicastPort);
//rc = new RadioConnection(trboIP, port, user4radioCon);
rc = rc_var;
rc.OnEmergencyEvent += new RadioConnection.EmergencyEvent(radioCon_OnEmergencyEvent);
//rc.Start();
//starting timer
//timer = new System.Threading.Timer(timerDel, null, new TimeSpan(0, 0, 0), new TimeSpan(0, 0, 10));
}
private void timerDel(Object state)
{
if (ack_needed == true)
{
SafeMobileLib.Utils.WriteLine("Emergency was not ACK sending ACK again!!!");
rc.SendEmergencyACK();
}
}
void radioCon_OnEmergencyEvent(int radioId,bool status)
{
//emergency on
if (status)
{
SafeMobileLib.Utils.WriteLine("Received emergency from radio id: " + radioId);
string seqID = "0.0";
string toSend = "#138#" + radioId + "#";
String cmdok = "#" + seqID + toSend;
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);
//put on multicast bus
SafeMobileLib.Utils.WriteLine("Emergency alarm sent on multicast bus: " + cmdok);
udpMulticast.Send(buf, buf.Length);
//add timer for ack
timer = new System.Threading.Timer(timerDel, null, new TimeSpan(0, 0, 10), new TimeSpan(0, 0, 10));
ack_needed = true;
}
//emergency off
else
{
SafeMobileLib.Utils.WriteLine("Received emergency ACK for radio id: " + radioId);
ack_needed = false;
timer = null;
}
}
public void handleConnection()
{
SafeMobileLib.Utils.WriteLine("Emergency Thread - Initialized on Port " + port);
try
{
udpMulticast = new UdpMulticast(mIP, mPort);
SafeMobileLib.Utils.WriteLine("Emergency thread successfully registered to multicast group");
}
catch (Exception ex)
{
SafeMobileLib.Utils.WriteLine("Emergency Thread exception while joining the multicast group: " + ex.ToString());
}
while (true)
{ Thread.Sleep(100); }
}
public void Disconnect()
{
/*
if (rc != null)
{
rc.Stop();
rc = null;
}
*/
if (udpMulticast != null)
{
udpMulticast.StopListen();
udpMulticast = null;
}
if (timer != null)
{
timer.Dispose();
timer = null;
}
rc.OnEmergencyEvent -= new RadioConnection.EmergencyEvent(radioCon_OnEmergencyEvent);
}
}
}