SafeNet/SN_Server/ServerConnector.cs
2021-02-24 13:50:23 +02:00

313 lines
9.1 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Collections;
using SN_Server.ServerMSGS;
namespace SN_Server
{
public class ServerConnector
{
public static string serialNr;
private string _ip;
private int _port;
private ServerIdentlist iplist;
private TcpClient client;
private IPEndPoint serverEndPoint;
private NetworkStream clientStream;
private String leftovers = "";
public bool _connected = false;
private Thread listenThread;
public ServerConnector(string sn)
{
serialNr = sn;
iplist = new ServerIdentlist();
bool stat = Connect();
if (stat)
{
listenThread = new Thread(new ThreadStart(HandleServerComm));
listenThread.IsBackground = true;
listenThread.Start();
}
}
private bool Connect()
{
bool ret = false;
if (iplist.IP_list.Count < 1)
{
Console.WriteLine("No valid IPs found in config file!!!");
return ret;
}
int cont = 0;
while (!_connected)
{
if (cont > iplist.IP_list.Count - 1) cont = 0;
ServerIdent si = (ServerIdent)iplist.IP_list[cont];
client = new TcpClient();
Console.WriteLine("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
Console.WriteLine("ServerConnector -> try to connect on " + si.IP + " port " + si.Port);
try
{
client.Connect(si.IP, si.Port);
Console.WriteLine("ServerConnector connected on " + si.IP + ":" + si.Port);
clientStream = client.GetStream();
if (clientStream != null)
{
//set read timeout to 35 seconds, according to Motorola Connect Plus PN_Watcher specifications
clientStream.ReadTimeout = 35000;
_connected = true;
//exit while loop
break;
}
else
{
_connected = false;
Console.WriteLine("ServerConnector -> clientStream==null");
cont++;
}
}
catch (Exception ex)
{
Console.WriteLine("Erorr ServerConnector connecting to " + si.IP + " port " + si.Port +" \n" + ex.Message);
_connected = false;
cont++;
}
}
return _connected;
}
private void HandleServerComm()
{
while (true)
{
try
{
clientStream.ReadTimeout = 65000;
byte[] buff = new byte[1024];
int recv = clientStream.Read(buff, 0, buff.Length);
if (OnNewDataRecv != null)
{
byte[] tmp = new byte[recv];
for (int i = 0; i < recv; i++)
{
tmp[i] = buff[i];
}
string str_tmp = System.Text.Encoding.ASCII.GetString(tmp, 0, tmp.Length);
str_tmp = str_tmp.Trim();
Console.WriteLine("RX: " + str_tmp.Trim());
leftovers = leftovers + str_tmp.Trim();
ArrayList ar = parseLeftOvers();//ServerMSG.Split(str_tmp, str_tmp.Length);
if (this.OnNewDataRecv != null)
{
foreach (string str in ar)
this.OnNewDataRecv(str);
}
}
}
catch (System.IO.IOException ex)
{
Console.WriteLine("I/O exception!!");
Console.WriteLine(ex.ToString());
Thread.Sleep(1000);
_connected = false;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Thread.Sleep(30000);
_connected = false;
}
while (_connected == false)
{
Console.WriteLine("HandleServerComm -> _connected==false Restarting TCP");
Connect();
Thread.Sleep(30000);
}
}
}
private ArrayList parseLeftOvers()
{
ArrayList ar = new ArrayList();
//Console.WriteLine("\n\n");
//Console.WriteLine("I have to parse leftovers : " + leftovers);
Boolean areLeftoversFinished = false;
while (!areLeftoversFinished)
{
int msgLen = getMessageLength(leftovers);
if (msgLen == -1)
{
// Console.WriteLine("The message is incorrect -> " + leftovers);
}
else
{
// Console.WriteLine("MSG LENGTH = " + msgLen);
// if expected message is smaller than actual string add it to leftovers
if (msgLen > leftovers.Length)
{
areLeftoversFinished = true;
break;
}
else if (msgLen == leftovers.Length)
{
//Console.WriteLine("\nLEFTOVERS: " + leftovers);
ar.Add(leftovers);
//parseServerMsg(leftovers);
leftovers = "";
areLeftoversFinished = true;
break;
}
else
{
string toParseMsg = leftovers.Substring(0, msgLen);
leftovers = leftovers.Substring(msgLen);
ar.Add(toParseMsg);
// Console.WriteLine("\nTO PARSE: " + toParseMsg);
//Console.WriteLine("LEFTOVERS: " + leftovers);
//parseServerMsg(toParseMsg);
}
}
}
return ar;
}
/* Get the message length, this will be first element after splitting by '#' */
private int getMessageLength(String data)
{
String[] tempArr = data.Split('#');
if ((tempArr.Length == 0) || (tempArr.Length == 1))
return -1;
try
{
return Int32.Parse(tempArr[1]);
}
catch (InvalidCastException ex)
{
Console.WriteLine(ex.ToString());
}
return -1;
}
public delegate void newData4Send(string data);
public event newData4Send OnNewDataRecv;
public bool Send(byte[] data, int len)
{
bool ret = false;
string str = System.Text.Encoding.ASCII.GetString(data, 0, len);
Console.WriteLine("TX: " + str.Trim());
try
{
if (clientStream != null)
{
clientStream.Write(data, 0, len);
clientStream.Flush();
ret = true;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
ret = false;
}
return ret;
}
public void UpdateIPlist(List<ServerIdent> list)
{
iplist.IP_list.Clear();
foreach (ServerIdent si in list)
{
iplist.IP_list.Add(si);
}
iplist.UpdateFile();
iplist.Print();
}
//insert messages
//ARS
public void InsertARS(string suid, string arsState)
{
byte[] buff = SM_ARS.GenARSMsg(suid, arsState);
Send(buff, buff.Length);
}
//GPS
public bool InsertGPS(GPS gps)
{
byte[] buff = SM_GPS.GenGPSMsg(gps);
Send(buff, buff.Length);
return true;
}
//GPS poll
public bool InsertPOLL(int func, SM_POLLmsg msg)
{
byte[] buff = SM_GPS.GenPollACKMsg(func, msg);
Send(buff, buff.Length);
return true;
}
//SMS
public bool InsertSMS(SMS sms)
{
byte[] buff = SM_SMS.GenSMSInsertMsg(sms);
Send(buff, buff.Length);
return true;
}
//SMS ACK
public bool InsertSMSack(SMS sms)
{
byte[] buff = SM_SMS.GenSMSAckMsg(sms);
Send(buff, buff.Length);
return true;
}
}
}