SafeNet/LMdirect_SOC/Gateway.cs

135 lines
4.1 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Nini.Config;
using System.Threading;
using SafeNetLib;
using System.Net;
namespace LMdirect_SOC
{
class Gateway
{
public string CFG_FILE = "config.ini";
public static volatile int serverState = 0;
private UdpServer udpServer;
public Gateway()
{
serverState = 1;
int port = 10000;
port = (int)DBhandle.GetGatewayPort();
if (port == 0)
{
Console.WriteLine("Listen port not assigned for gateway " + Program.cfg.gatewayID);
Console.ReadKey();
}
else
{
udpServer = new UdpServer(port);
udpServer.OnNewDataEndPointRecv += new UdpServer.dataRecvEndPointDel(udpServer_OnNewDataEndPointRecv);
udpServer.Start();
while (true)
{
Thread.Sleep(1000000000);
}
}
}
void udpServer_OnNewDataEndPointRecv(byte[] data, int dataLen, System.Net.IPEndPoint ipEndPoint)
{
Console.WriteLine("Got data from :" + ipEndPoint.ToString());
//display received data on the screen
Utils.printBytesArray(data);
LMDirectParser tmp = new LMDirectParser(data, dataLen);
//send stuff on message bus
try
{
//insert db
//locManager.SendLoc2messagebus(tmp.ID.ToString(), (uint)tmp.TimeofFix, tmp.Speed.ToString(), tmp.Lat.ToString(), tmp.Long.ToString(), 0); //poll 30
}
catch (Exception ex)
{
Console.WriteLine("ConnectionThread.cs =>> Error sending location!!!");
Console.WriteLine(ex.ToString());
}
#region respond to client
//EX sending something back
Int32 lenghtResponse = 0;
lenghtResponse = 1 + 1 + 1 + tmp.ForACKMobidID.Length + 1 + tmp.ForACKMobidIDTypeLength + 1 + 1 + tmp.ForACKSequnceNumber.Length + 1 + 1 + 3;
byte[] somedata = new byte[lenghtResponse];
Int32 offset = 0;
//options byte
somedata[offset] = 0x83;
offset++;
//mobid ID lenght
somedata[offset] = tmp.ForACKMobidIDLength;
offset++;
//mobid ID
for (int i = 0; i < tmp.ForACKMobidIDLength; i++)
somedata[offset+i] = tmp.ForACKMobidID[i];
offset += tmp.ForACKMobidIDLength;
//mobid type lenght
somedata[offset] = tmp.ForACKMobidIDTypeLength;
offset++;
//mobid type
for (int i = 0; i < tmp.ForACKMobidIDTypeLength; i++)
somedata[offset + i] = tmp.ForACKMobidType[i];
offset += tmp.ForACKMobidIDTypeLength;
//service type
somedata[offset] = 0x02;
offset++;
//message type
somedata[offset] = 0x01;
offset++;
//sequence number
for (int i = 0; i < tmp.ForACKSequnceNumber.Length; i++)
somedata[offset + i] = tmp.ForACKSequnceNumber[i];
offset += tmp.ForACKSequnceNumber.Length;
//Type
somedata[offset] = tmp.ForACKMessageType;
offset++;
//ACK
somedata[offset] = 0x00;
offset++;
//App Version
somedata[offset] = 0x00;
offset++;
somedata[offset] = 0x00;
offset++;
somedata[offset] = 0x00;
//display ack packet on the screen
Utils.printBytesArray(somedata);
Console.WriteLine("Send ACK to IP:"+ipEndPoint.Address+" PORT:"+ipEndPoint.Port);
//IPEndPoint destEP = new IPEndPoint(ip, GPRS_PORT);//use the actual port
udpServer.Send(somedata, somedata.Length, ipEndPoint);
Console.WriteLine("ACK sent");
#endregion
}
}
}