Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 28

using iSmartTechnologies;

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Device.Location;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace GPSTrackerServer
{
public partial class Service1 : ServiceBase
{
public IPAddress localAddr =
IPAddress.Parse(ConfigurationManager.AppSettings["IP"].ToString());
private Thread workerThread = null;

static readonly object _lock = new object();


static readonly Dictionary<int, TcpClient> list_clients = new
Dictionary<int, TcpClient>();
public Int32 PortASCII =
Convert.ToInt32(ConfigurationManager.AppSettings["PortASCII"].ToString());

static readonly Dictionary<int, StateObject> Concoxlist_clients = new


Dictionary<int, StateObject>();
public Int32 PortConcox =
Convert.ToInt32(ConfigurationManager.AppSettings["PortConcox"].ToString());

int DeviceCount = 1;

public Service1()
{
InitializeComponent();
}

protected override void OnStart(string[] args)


{
WriteToFile("Service is started at " + DateTime.Now);

// Initialise and start worker thread


this.workerThread = new Thread(new ThreadStart(this.connectAscii));
this.workerThread.Start();

// Initialise and start worker thread


this.workerThread = new Thread(new ThreadStart(this.connectConcox));
this.workerThread.Start();
}

protected override void OnStop()


{
WriteToFile("Service is Stopped at " + DateTime.Now);
}

private void RestartWindowsService(string serviceName)


{
ServiceController serviceController = new
ServiceController(serviceName);
try
{
if
((serviceController.Status.Equals(ServiceControllerStatus.Running)) ||
(serviceController.Status.Equals(ServiceControllerStatus.StartPending)))
{
serviceController.Stop();
}
serviceController.WaitForStatus(ServiceControllerStatus.Stopped);
serviceController.Start();
serviceController.WaitForStatus(ServiceControllerStatus.Running);
}
catch (Exception ex)
{
WriteToFile("Error In service restart " + DateTime.Now + "Error: "
+ ex.Message);
//ShowMsg(AppTexts.Information, AppTexts.SystematicError,
MessageBox.Icon.WARNING);
}
}

void connectAscii()
{
//Concox gps = new
Concox(ConfigurationManager.AppSettings["IP"].ToString(), PortConcox);

TcpListener ServerSocketASCII = new TcpListener(localAddr, PortASCII);


ServerSocketASCII.Start();

while (true)
{
TcpClient client1 = ServerSocketASCII.AcceptTcpClient();
lock (_lock) list_clients.Add(DeviceCount, client1);

Thread t1 = new Thread(handle_ASCIIclients);


t1.Start(DeviceCount);
DeviceCount++;
}

public void handle_ASCIIclients(object o)


{
try
{

int id = (int)o;
TcpClient client;

lock (_lock) client = list_clients[id];


while (true)
{
NetworkStream stream = client.GetStream();
byte[] buffer = new byte[1024];
int byte_count = stream.Read(buffer, 0, buffer.Length);

if (byte_count == 0)
{
break;
}

string data = Encoding.ASCII.GetString(buffer, 0, byte_count);

WriteToFile(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + ">>


" + data);

if (data.Length > 18)


{
if (data.Substring(13, 4) == "BR00")
{
try
{
string deviceid = data.Substring(1, 12);

string tmpDate = data.Substring(17, 6);


string Date = "20" + tmpDate.Substring(0, 2) + "-"
+ tmpDate.Substring(2, 2) + "-" + tmpDate.Substring(4, 2);////data.Substring(17,
6);

string tmptime = data.Substring(50, 6);


string time = tmptime.Substring(0, 2) + ":" +
tmptime.Substring(2, 2) + ":" + tmptime.Substring(4, 2);//data.Substring(50, 6);

string availability = data.Substring(23, 1);

//2056.3146N
string templat = data.Substring(24, 10);
string lat =
ConvertDegreeAngleToDouble(templat.Substring(0, 2), templat.Substring(2, 7),
templat.Substring(9, 1));//templat.Substring(0, 2) + "." + templat.Substring(2,
templat.Length - 1);

//07255.9841E
string templog = data.Substring(34, 11);
string log =
ConvertDegreeAngleToDouble(templog.Substring(0, 3), templog.Substring(3, 7),
templog.Substring(10, 1));

string speed = data.Substring(45, 5);


string mainPower = (data.Substring(62, 1) == "0") ?
"On" : "Off";
string ignition = (data.Substring(63, 1) == "0") ?
"Off" : "On";

Date = Date + " " + time;


//convert UTC to IST
DateTime utcDate = DateTime.ParseExact(Date, "yyyy-
MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
string istdate =
TimeZoneInfo.ConvertTimeFromUtc(utcDate, TimeZoneInfo.FindSystemTimeZoneById("India
Standard Time")).ToString("yyyy-MM-dd hh:mm:ss tt");

//WriteToFile("deviceid:" + deviceid + " | " +


"date: " + istdate + " | " + "time: " + time + " | " + "availability: " +
availability + " | " + "lat: " + lat + "|" + "log: " + log + " | " + "speed: " +
speed + " | " + "main power(0=off & 1=on) : " + mainPower + " | " + "ignition(0=off
& 1=on) : " + ignition);

string res = insertData(deviceid, istdate,


availability, lat, log, speed, mainPower, ignition);
WriteToFile("Insert res :" + res);
//send data to client
//SendCommandToDevice(deviceid, client);

#region send data to client

Global g = new Global();

string strStud = "GetDeviceCommands";

SqlParameter[] param = new SqlParameter[1];

param[0] = new SqlParameter();


param[0].ParameterName = "DeviceID";
param[0].Value = deviceid;
param[0].SqlDbType = SqlDbType.VarChar;

DataSet ds = g.ExecuteProcedureWithParam(strStud,
param);

#region GEO FENSE


if (ds.Tables[0].Rows.Count > 0 && !
ds.Tables[0].Rows[0][0].ToString().Contains("Error"))
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i+
+)
{
string protocol = ds.Tables[0].Rows[i]
["ProtocolData"].ToString();

double lat1 =
double.Parse(ds.Tables[0].Rows[i]["Latitude"].ToString());
double lat2 =
double.Parse(ds.Tables[0].Rows[i]["Latitude2"].ToString());

double lng1 =
double.Parse(ds.Tables[0].Rows[i]["Longitude"].ToString());
double lng2 =
double.Parse(ds.Tables[0].Rows[i]["Longitude2"].ToString());

protocol = protocol.Replace("$deviceid$",
deviceid);

protocol = protocol.Replace("$geomode$",
"1");

string minlat =
ConvertDoubleDegreeAngle("lat", ((lat1 > lat2) ? lat2 : lat1).ToString());
protocol = protocol.Replace("$lattype$",
minlat.Substring(minlat.Length - 1, 1));

protocol = protocol.Replace("$minlat$",
minlat.Substring(0, minlat.Length - 1));

string maxlat =
ConvertDoubleDegreeAngle("lat", ((lat1 > lat2) ? lat1 : lat2).ToString());
protocol = protocol.Replace("$maxlat$",
maxlat.Substring(0, maxlat.Length - 1));

string minlng =
ConvertDoubleDegreeAngle("lmg", ((lng1 > lng2) ? lng2 : lng1).ToString());
protocol = protocol.Replace("$lngtype$",
minlng.Substring(minlng.Length - 1, 1));
protocol = protocol.Replace("$minlng$",
minlng.Substring(0, minlng.Length - 1));

string maxlng =
ConvertDoubleDegreeAngle("lmg", ((lng1 > lng2) ? lng1 : lng2).ToString());
protocol = protocol.Replace("$maxlng$",
maxlng.Substring(0, maxlng.Length - 1));

WriteToFile("protocol1:" + protocol);

byte[] SendData =
Encoding.ASCII.GetBytes(protocol);
NetworkStream Netstream =
client.GetStream();
Netstream.Write(SendData, 0,
SendData.Length);
}
}
#endregion

#region lock
if (ds.Tables[1].Rows.Count > 0 && !
ds.Tables[1].Rows[0][0].ToString().Contains("Error"))
{
string protocol = ds.Tables[1].Rows[0]
["ProtocolData"].ToString();
string strlock = (ds.Tables[1].Rows[0]
["lock"].ToString() == "True") ? "0" : "1";
protocol = protocol.Replace("$deviceid$",
deviceid);
protocol = protocol.Replace("$lock$", strlock);
WriteToFile("protocol2:" + protocol);

byte[] SendData =
Encoding.ASCII.GetBytes(protocol);
NetworkStream Netstream = client.GetStream();
Netstream.Write(SendData, 0, SendData.Length);
}
#endregion

#region overspeed
if (ds.Tables[2].Rows.Count > 0 && !
ds.Tables[2].Rows[0][0].ToString().Contains("Error"))
{
string protocol = ds.Tables[2].Rows[0]
["ProtocolData"].ToString();
string strhigh = "0" + ds.Tables[2].Rows[0]
["MaxSpeed"].ToString();
string strlow = "0" + ds.Tables[2].Rows[0]
["MinSpeed"].ToString();
protocol = protocol.Replace("$deviceid$",
deviceid);
protocol = protocol.Replace("$high$", strhigh);
protocol = protocol.Replace("$low$", strlow);
WriteToFile("protocol3:" + protocol);

byte[] SendData =
Encoding.ASCII.GetBytes(protocol);
NetworkStream Netstream = client.GetStream();
Netstream.Write(SendData, 0, SendData.Length);
}
#endregion

#endregion

}
catch (Exception ex)
{
WriteToFile(ex.Message);
}
}
if (data.Substring(13, 4) == "BO01")
{
string alarm = data.Substring(17, 1);

//0:Vehicle power off


if (alarm == "0")
{

}
//1:Alarm when inside of Geo - fence

//2:Vehicle robbery(SOS help)

//3:Vehicle anti-theft and alarming

//4:Lowerspeed Alert

//5:Overspeed Alert

//6 : Alarm when out of Geo-fence


}
}
}

//lock (_lock) list_clients.Remove(id);


//client.Client.Shutdown(SocketShutdown.Both);
//client.Close();

WriteToFile("Active Threads :" + list_clients.Count);


}
catch (Exception ex)
{
WriteToFile(ex.Message);
}

#region concox

static byte[] loginResponse = { 0x78, 0x78, 0x05, 0x01, 0x00, 0x00, 0x00,
0x00, 0x0D, 0x0A };

static byte[] alarmResponse = { 0x78, 0x78, 0x05, 0x16, 0x00, 0x00, 0x00,
0x00, 0x0D, 0x0A };

static byte[] alarmDataAddressResponse = { 0x78, 0x78, 0x00, 0x97, 0x7E,


0x00, 0x00, 0x00, 0x01,
0x41, 0x4C, 0x41, 0x52, 0x4D, 0x53, 0x4D,
0x53, //ALARMS
0x26, 0x26,
//&&
0x80, 0x00, 0x72, 0x00, 0x79, 0x00, 0x78,
0x00, // PHONE HOME
0x69, 0x00, 0x32, 0x00, 0x72, 0x00, 0x79,
0x00,
0x77, 0x00, 0x69,
0x26, 0x26,
//&&
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, // Phone Numbe
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x23, 0x23,
//##
0x00, 0x00,
//serial number
0x00, 0x00,
//check bytes
0x0D, 0x0A
//stop bytes
};

static byte[] heartbeatResponse = { 0x78, 0x78, 0x05, 0x13, 0x00, 0x00,


0x00, 0x00, 0x0D, 0x0A };

static byte[] connectOilAndEletricity = {


0x78, 0x78, 0x16, 0x80, 0x10, 0x12, 0x34,
0x56, 0x78, 0x48, //server flag bit 0x12345678
0x46, 0x59, 0x44, 0x2C, 0x30, 0x30, 0x30,
0x30, 0x30, 0x30,
0x23, 0x00, 0x00, 0x00, 0x00, 0x0D, 0x0A
};

public class StateObject


{
public long connectionNumber = -1;
public TcpClient workSocket { get; set; }
public byte[] buffer { get; set; }
public int fifoCount { get; set; }
public string IMEI { get; set; }
}
public enum ALARM : Byte
{
NORMAL = 0,
SHOCK_ALARM = 1,
POWER_CUT_ALARM = 2,
LOW_BATTERY = 3,
SOS = 4
}

public enum PROTOCOL_NUMBER


{
LOGIN_MESSAGE = 0x01,
LOCATION_DATA = 0x12,
STATUS_INFO = 0X13,
STRING_INFO = 0X15,
ALARM_DATA = 0X16,
GPS_QUERY_ADDR_PHONE_NUM = 0X1A,
COMMAND_INFO = 0X80,
NONE
}

static public UInt16 crc_bytes(byte[] data)


{
ushort crc = 0xFFFF;

for (int i = 0; i < data.Length; i++)


{
crc ^= (ushort)(Reflect(data[i], 8) << 8);
for (int j = 0; j < 8; j++)
{
if ((crc & 0x8000) > 0)
crc = (ushort)((crc << 1) ^ 0x1021);
else
crc <<= 1;
}
}
crc = Reflect(crc, 16);
crc = (ushort)~crc;
return crc;
}

static public ushort Reflect(ushort data, int size)


{
ushort output = 0;
for (int i = 0; i < size; i++)
{
int lsb = data & 0x01;
output = (ushort)((output << 1) | lsb);
data >>= 1;
}
return output;
}

#endregion
void connectConcox()
{

TcpListener ServerSocketConcox = new TcpListener(localAddr,


PortConcox);
ServerSocketConcox.Start();

while (true)
{
TcpClient client1 = ServerSocketConcox.AcceptTcpClient();

StateObject obj = new StateObject();


obj.connectionNumber = DeviceCount;
obj.workSocket = client1;

lock (_lock) Concoxlist_clients.Add(DeviceCount, obj);

Thread t1 = new Thread(handle_Concoxclients);


t1.Start(DeviceCount);
DeviceCount++;
}

public void handle_Concoxclients(object o)


{
try
{
int id = (int)o;

StateObject objstate;
lock (_lock) objstate = Concoxlist_clients[id];

TcpClient client;
lock (_lock) client = objstate.workSocket;

UInt16 sendCRC = 0;
byte[] serverFlagBit = null;
byte[] stringArray = null;
string stringMessage = "";
byte lengthOfCommand = 0;

while (true)
{
Global g = new Global();
NetworkStream stream = client.GetStream();
byte[] buffer = new byte[1024];
int byte_count = stream.Read(buffer, 0, buffer.Length);

if (byte_count == 0)
{
break;
}

//string data = Encoding.ASCII.GetString(buffer, 0,


byte_count);

byte[] receiveMessage = new byte[byte_count];


Array.Copy(buffer, receiveMessage, byte_count);
string data = BytesToString(receiveMessage);

//WriteToFile(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") +
">> " + data);

byte[] serialNumber = null;


int messageLength = receiveMessage[2];
serialNumber = receiveMessage.Skip(2 + 1 + messageLength -
4).Take(2).ToArray();

PROTOCOL_NUMBER protocolNumber = PROTOCOL_NUMBER.NONE;


protocolNumber = (PROTOCOL_NUMBER)receiveMessage[3];

switch (protocolNumber)
{
case PROTOCOL_NUMBER.LOGIN_MESSAGE:

serialNumber.CopyTo(loginResponse, 4);
sendCRC =
crc_bytes(loginResponse.Skip(2).Take(loginResponse.Length - 6).ToArray());

loginResponse[loginResponse.Length - 4] = (byte)
((sendCRC >> 8) & 0xFF);
loginResponse[loginResponse.Length - 3] = (byte)
((sendCRC) & 0xFF);

//
string IMEI =
BytesToString(receiveMessage.Skip(4).Take(messageLength - 5).ToArray());
objstate.IMEI = IMEI;

//byteState.Value.IMEI = IMEI;
//Concoxlist_clients[id] = IMEI;
//WriteToFile(DateTime.Now.ToString("yyyy-MM-dd
hh:mm:ss") + ">> " + IMEI);

//send responce
NetworkStream Netstream = client.GetStream();
Netstream.Write(loginResponse, 0,
loginResponse.Length);

break;

case PROTOCOL_NUMBER.LOCATION_DATA:

//WriteToFile(DateTime.Now.ToString("yyyy-MM-dd
hh:mm:ss") + ">> Client IMEI:" + objstate.IMEI);

DateTime date;
int year = 0;
int month = 0;
int day = 0;
int hour = 0;
int minute = 0;
int second = 0;

year = receiveMessage[4];
month = receiveMessage[5];
day = receiveMessage[6];
hour = receiveMessage[7];
minute = receiveMessage[8];
second = receiveMessage[9];

date = new DateTime(2000 + year, month, day, hour,


minute, second);

byte[] lattitude = new byte[4];


Array.Copy(receiveMessage, 11, lattitude, 0, 4);

byte[] longitude = new byte[4];


Array.Copy(receiveMessage, 15, longitude, 0, 4);

float speed = receiveMessage[19];

byte[] courseStatus = new byte[2];


Array.Copy(receiveMessage, 20, courseStatus, 0, 2);

string binarystring =
hex2bin(BytesToString(courseStatus));//String.Join(String.Empty,
courseStatus.Select(c => Convert.ToString(Convert.ToInt32(c.ToString(), 16),
2).PadLeft(4, '0')));

//check 2nd bit if 1 then>> check 1st bit if 1 =on if


0=off
string Ignition = (binarystring.Substring(1, 1) == "1")
? (binarystring.Substring(0, 1) == "1") ? "On" : "Off" : "Off";

uint number =
BitConverter.ToUInt32(longitude.Reverse().ToArray(), 0);
double lon = number / 1800000.0;
number =
BitConverter.ToUInt32(lattitude.Reverse().ToArray(), 0);
double lat = number / 1800000.0;

string res = insertData(objstate.IMEI,


date.ToString("yyyy-MM-dd HH:mm:ss"), "A", lat.ToString(), lon.ToString(),
speed.ToString(), "On", Ignition);
if (res != "1")
{
WriteToFile(res);
}
//WriteToFile("Serial Number " + "0x" +
serialNumber[0].ToString("X2") + serialNumber[1].ToString("X2") + ", Time = " +
date.ToString() + "ing=" + binarystring + " res:" + res);
break;

case PROTOCOL_NUMBER.ALARM_DATA:

//first response
int alarmPacketLen = alarmResponse.Length - 5;
alarmResponse[2] = (byte)(alarmPacketLen & 0xFF);

serialNumber.CopyTo(alarmResponse, alarmPacketLen - 1);

sendCRC =
crc_bytes(alarmResponse.Skip(2).Take(alarmPacketLen - 1).ToArray());
alarmResponse[alarmPacketLen + 1] = (byte)((sendCRC >>
8) & 0xFF);
alarmResponse[alarmPacketLen + 2] = (byte)((sendCRC) &
0xFF);

//WriteToFile("Send Alarm Response Message : '" +


BytesToString(alarmResponse));
//Send(state.workSocket, alarmResponse);
//send responce
NetworkStream Netstream1 = client.GetStream();
Netstream1.Write(alarmResponse, 0,
alarmResponse.Length);

//second response
year = receiveMessage[4];
month = receiveMessage[5];
day = receiveMessage[6];
hour = receiveMessage[7];
minute = receiveMessage[8];
second = receiveMessage[9];

date = new DateTime(2000 + year, month, day, hour,


minute, second);

//WriteToFile("Received good alarm message from Serial


Number " + "0x" + serialNumber[0].ToString("X2") + serialNumber[1].ToString("X2") +
", Time = " + date.ToLongDateString());

int alarmDataAddressPacketLen =
alarmDataAddressResponse.Length - 5;
alarmDataAddressResponse[2] = (byte)
(alarmDataAddressPacketLen & 0xFF);

serialNumber.CopyTo(alarmDataAddressResponse,
alarmDataAddressPacketLen - 1);

sendCRC =
crc_bytes(alarmDataAddressResponse.Skip(2).Take(alarmDataAddressPacketLen -
1).ToArray());

alarmDataAddressResponse[alarmDataAddressPacketLen + 1]
= (byte)((sendCRC >> 8) & 0xFF);
alarmDataAddressResponse[alarmDataAddressPacketLen + 2]
= (byte)((sendCRC) & 0xFF);

//WriteToFile("Send Alarm Data Address Message :" +


BytesToString(alarmDataAddressResponse));

byte[] Alarm = new byte[2];


Array.Copy(receiveMessage, 34, Alarm, 0, 2);

//normal
if (Alarm[0] == 0x00)
{
WriteToFile("normal");
}
//SOS
if (Alarm[0] == 0x01)
{
WriteToFile("SOS");
sendNotification("SOS ALERT", "$VehicleName$ SOS
ALERT", "$VehicleNo$ SOS Button Pressed at " + date, objstate.IMEI,
date.ToString("yyyy-MM-dd HH:mm:ss"), "", "", "");
}
//Power Cut
if (Alarm[0] == 0x02)
{
WriteToFile("Power Cut");
sendNotification("POWERCUT ALERT", " $VehicleName$
POWERCUT ALERT", "$VehicleNo$ Power Failure at " + date, objstate.IMEI,
date.ToString("yyyy-MM-dd HH:mm:ss"), "", "", "");
}
//Vibration
if (Alarm[0] == 0x03)
{
WriteToFile("Vibration");
sendNotification("VIBRATION ALERT", "$VehicleName$
VIBRATION ALERT", "$VehicleNo$ Vibration at " + date, objstate.IMEI,
date.ToString("yyyy-MM-dd HH:mm:ss"), "", "", "");
}
//Enter Fence
if (Alarm[0] == 0x04)
{
WriteToFile("Enter Fence");
sendNotification("FENCE ALERT", "$VehicleName$
GEOFENCE ALERT", "$VehicleNo$ Enter Geo Fence at " + date, objstate.IMEI,
date.ToString("yyyy-MM-dd HH:mm:ss"), "In", "", "");

}
//Exit Fence
if (Alarm[0] == 0x05)
{
WriteToFile("Exit Fence");
sendNotification("FENCE ALERT", "$VehicleName$
GEOFENCE ALERT", "$VehicleNo$ Exit Geo Fence at " + date, objstate.IMEI,
date.ToString("yyyy-MM-dd HH:mm:ss"), "Out", "", "");
}
//Over speed
if (Alarm[0] == 0x06)
{
WriteToFile("Over speed");
sendNotification("OVER SPEED", "$VehicleName$
OVERSPEED ALERT", "$VehicleNo$ Overspeed at " + date, objstate.IMEI,
date.ToString("yyyy-MM-dd HH:mm:ss"), "", "", "");
}

//0x09 Moving alarm

//0x0A Enter GPS dead zone alarm

//0x0BExit GPS dead zone alarm

//0x0C Power on alarm

//0x0D GPS First fix notice


//0x0E Low battery alarm
if (Alarm[0] == 0x0E)
{
WriteToFile("Low battery alarm");
sendNotification("LOW BATTERY", "$VehicleName$ LOW
BATTERY ALERT", "$VehicleNo$ Battery at " + date, objstate.IMEI,
date.ToString("yyyy-MM-dd HH:mm:ss"), "", "", "");
}

//0x0F Low battery protection alarm


//0x10SIM change notice
//0x11Power low-off alarm
//0x12Airplane mode alarm
//0x13Disassemble alarm
//0x14 Door alarm
//0x15 Shutdown alarm

//Send(state.workSocket, alarmDataAddressResponse);

//send responce
NetworkStream Netstream2 = client.GetStream();
Netstream2.Write(alarmDataAddressResponse, 0,
alarmDataAddressResponse.Length);

break;

case PROTOCOL_NUMBER.STATUS_INFO:

//WriteToFile(objstate.IMEI + "Status Received.");


//sendNotification("Status Info", "$VehicleName$
$VehicleNo$ Vehicle Status", "$VehicleName$ $VehicleNo$ Vehicle Status Received",
objstate.IMEI, DateTime.Now.ToString());

serialNumber.CopyTo(heartbeatResponse, 4);

byte info = receiveMessage[4];


byte voltage = receiveMessage[5];
byte GSMsignalStrength = receiveMessage[6];

byte[] infoBytes = new byte[1];


Array.Copy(receiveMessage, 4, infoBytes, 0, 1);

string infoString = hex2bin(BytesToString(infoBytes));

//Bit7 1: Oil and electricity disconnected


// 0: Oil and electricity connected
//Bit6
// 1: GPS tracking is on
// 0: GPS tracking is off
//Bit3~Bit5
// Extended Bit
//Bit2
// 1: Charge On
// 0: Charge Off
//Bit1
// 1: ACC high
// 0: ACC Low
//Bit0
// 1: Defense Activated
// 0: Defense Deactivated

string relay = infoString.Substring(0, 1);


string gpstracking = infoString.Substring(1, 1);
string MainPower = (infoString.Substring(5, 1) ==
"1") ? "On" : "Off";
string AccOn = infoString.Substring(6, 1);
string DefenceAct = infoString.Substring(7, 1);

string Status = (AccOn == "1") ? "Idle" : "Parked";

res = UpdateHeartbeatData(objstate.IMEI,
voltage.ToString(), "", GSMsignalStrength.ToString(), Status,
DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt"), MainPower);
//WriteToFile("res of status heartbeat:" + res);

UInt16 alarmLanguage = (UInt16)((receiveMessage[7] <<


8) | receiveMessage[8]);

ALARM alarm = (ALARM)((info >> 3) & 0x07);

sendCRC =
crc_bytes(heartbeatResponse.Skip(2).Take(heartbeatResponse.Length - 6).ToArray());

heartbeatResponse[heartbeatResponse.Length - 4] =
(byte)((sendCRC >> 8) & 0xFF);
heartbeatResponse[heartbeatResponse.Length - 3] =
(byte)((sendCRC) & 0xFF);

//WriteToFile("Received good status message from Serial


Number : " + "0x" + serialNumber[0].ToString("X2") + serialNumber[1].ToString("X2")
+ " INFO : 0x" + info.ToString("X2") + voltage.ToString("X2") +
GSMsignalStrength.ToString("X2") + alarmLanguage.ToString("X4"));
//WriteToFile("Send Message : " +
BytesToString(heartbeatResponse));

//Send(state.workSocket, heartbeatResponse);
//send responce
NetworkStream Netstream3 = client.GetStream();
Netstream3.Write(heartbeatResponse, 0,
heartbeatResponse.Length);

switch (alarm)
{
//reset cut off alarm
case ALARM.POWER_CUT_ALARM:

int connectOilAndElectricityPacketLen =
connectOilAndEletricity.Length - 5;
serialNumber.CopyTo(connectOilAndEletricity,
connectOilAndElectricityPacketLen - 1);
sendCRC =
crc_bytes(connectOilAndEletricity.Skip(2).Take(connectOilAndEletricity.Length -
6).ToArray());

connectOilAndEletricity[connectOilAndEletricity.Length - 4] = (byte)((sendCRC >> 8)


& 0xFF);

connectOilAndEletricity[connectOilAndEletricity.Length - 3] = (byte)((sendCRC) &


0xFF);

serverFlagBit = new byte[4];


Array.Copy(connectOilAndEletricity, 5,
serverFlagBit, 0, 4);

lengthOfCommand = connectOilAndEletricity[4];
stringArray = new byte[lengthOfCommand -
4]; //do not include server flag bit
Array.Copy(connectOilAndEletricity, 9,
stringArray, 0, lengthOfCommand - 4);

stringMessage =
Encoding.ASCII.GetString(stringArray);

WriteToFile("Reset Oil and Electricity, Server


Flag Bit : " + serverFlagBit[0].ToString("X2") + serverFlagBit[1].ToString("X2") +
serverFlagBit[2].ToString("X2") + serverFlagBit[3].ToString("X2") + ", Message : "
+ stringMessage);
//Send(state.workSocket,
connectOilAndEletricity);

//send responce
NetworkStream Netstream4 = client.GetStream();
Netstream4.Write(connectOilAndEletricity, 0,
connectOilAndEletricity.Length);

break;
}

break;

case PROTOCOL_NUMBER.STRING_INFO:

lengthOfCommand = receiveMessage[4];
serverFlagBit = new byte[4];
Array.Copy(receiveMessage, 5, serverFlagBit, 0, 4);

stringArray = new byte[lengthOfCommand - 4]; //do not


include server flag bit
Array.Copy(receiveMessage, 9, stringArray, 0,
lengthOfCommand - 4);

stringMessage = Encoding.ASCII.GetString(stringArray);
string server = BitConverter.ToInt32(serverFlagBit,
0).ToString();

WriteToFile("command:" + "String Message :" +


stringMessage + " >>Server Flagbit : " + server);

string strCommand = "update DeviceCommandHistory set


response=N'" + stringMessage + "' where ID= " + server;
g.InsertUpdateDelete(strCommand);

break;
}

#region send data to client


string strStud = "GetDeviceCommands";
SqlParameter[] param = new SqlParameter[1];

param[0] = new SqlParameter();


param[0].ParameterName = "DeviceID";
param[0].Value = objstate.IMEI;
param[0].SqlDbType = SqlDbType.VarChar;

DataSet ds = g.ExecuteProcedureWithParam(strStud, param);

#region GEO FENSE


if (ds.Tables[0].Rows.Count > 0 && !ds.Tables[0].Rows[0]
[0].ToString().Contains("Error"))
{
WriteToFile("GEO Fence");

for (int i = 0; i < ds.Tables[0].Rows.Count; i++)


{
double lat1 = double.Parse(ds.Tables[0].Rows[i]
["Latitude"].ToString());
double lng1 = double.Parse(ds.Tables[0].Rows[i]
["Longitude"].ToString());

byte[] startCommands = { 0x78, 0x78, 0x00, 0x80, 0x00,


0x00, 0x00, 0x00, 0x00 };

string strCommand = "FENCE,ON,0," + lat1 + "," + lng1 +


"," + 5 + ",,0#";

//WriteToFile("ASCII command:" + strCommand);


byte[] cmdbyte = Ascii2Hex(strCommand);
//WriteToFile("command:" + BytesToString(cmdbyte));

int cmdlen = cmdbyte.Length + 4;


int totLen = 6 + cmdlen;

startCommands[2] = (byte)(totLen & 0xFF);


startCommands[4] = (byte)(cmdlen & 0xFF);

byte[] FinalCommands = new byte[15 + cmdbyte.Length];

Array.Copy(startCommands, 0, FinalCommands, 0,
startCommands.Length);

Array.Copy(cmdbyte, 0, FinalCommands,
startCommands.Length, cmdbyte.Length);

FinalCommands[FinalCommands.Length - 6] = 0x00;
FinalCommands[FinalCommands.Length - 5] = 0x01;

sendCRC =
crc_bytes(FinalCommands.Skip(2).Take(FinalCommands.Length - 6).ToArray());

FinalCommands[FinalCommands.Length - 4] = (byte)
((sendCRC >> 8) & 0xFF);
FinalCommands[FinalCommands.Length - 3] = (byte)
((sendCRC) & 0xFF);
FinalCommands[FinalCommands.Length - 2] = 0x0D;
FinalCommands[FinalCommands.Length - 1] = 0x0A;

string cmd = BytesToString(FinalCommands);


//WriteToFile("Full command : " + cmd);

NetworkStream Netstream = client.GetStream();


Netstream.Write(FinalCommands, 0,
FinalCommands.Length);

//string protocol = ds.Tables[0].Rows[i]


["ProtocolData"].ToString();

//double lat1 = double.Parse(ds.Tables[0].Rows[i]


["Latitude"].ToString());
//double lat2 = double.Parse(ds.Tables[0].Rows[i]
["Latitude2"].ToString());

//double lng1 = double.Parse(ds.Tables[0].Rows[i]


["Longitude"].ToString());
//double lng2 = double.Parse(ds.Tables[0].Rows[i]
["Longitude2"].ToString());

//protocol = protocol.Replace("$deviceid$",
objstate.IMEI);

//protocol = protocol.Replace("$geomode$", "1");

//string minlat = ConvertDoubleDegreeAngle("lat",


((lat1 > lat2) ? lat2 : lat1).ToString());
//protocol = protocol.Replace("$lattype$",
minlat.Substring(minlat.Length - 1, 1));

//protocol = protocol.Replace("$minlat$",
minlat.Substring(0, minlat.Length - 1));

//string maxlat = ConvertDoubleDegreeAngle("lat",


((lat1 > lat2) ? lat1 : lat2).ToString());
//protocol = protocol.Replace("$maxlat$",
maxlat.Substring(0, maxlat.Length - 1));

//string minlng = ConvertDoubleDegreeAngle("lmg",


((lng1 > lng2) ? lng2 : lng1).ToString());
//protocol = protocol.Replace("$lngtype$",
minlng.Substring(minlng.Length - 1, 1));
//protocol = protocol.Replace("$minlng$",
minlng.Substring(0, minlng.Length - 1));

//string maxlng = ConvertDoubleDegreeAngle("lmg",


((lng1 > lng2) ? lng1 : lng2).ToString());
//protocol = protocol.Replace("$maxlng$",
maxlng.Substring(0, maxlng.Length - 1));

//WriteToFile("protocol1:" + protocol);

//byte[] SendData = Encoding.ASCII.GetBytes(protocol);


//NetworkStream Netstream = client.GetStream();
//Netstream.Write(SendData, 0, SendData.Length);
strCommand = "update VehiclesGeoFenceSetting set Sync=1
where ID= " + ds.Tables[0].Rows[i]["ID"].ToString();
g.InsertUpdateDelete(strCommand);
}
}
#endregion

#region lock
if (ds.Tables[1].Rows.Count > 0 && !ds.Tables[1].Rows[0]
[0].ToString().Contains("Error"))
{
WriteToFile("Lock command");
byte[] startCommands = { 0x78, 0x78, 0x00, 0x80, 0x00,
0x00, 0x00, 0x00, 0x00 };

//{ 0x78, 0x78, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x01, 0x00, 0x00, 0x0D, 0x0A };
//string protocol = ds.Tables[1].Rows[0]
["ProtocolData"].ToString();

string strlock = (ds.Tables[1].Rows[0]["lock"].ToString()


== "True") ? "1" : "0";
string strCommand = "relay," + strlock + "#";

//WriteToFile("ASCII command:" + strCommand);


byte[] cmdbyte = Ascii2Hex(strCommand);
//WriteToFile("command:" + BytesToString(cmdbyte));

int cmdlen = cmdbyte.Length + 4;


int totLen = 6 + cmdlen;

startCommands[2] = (byte)(totLen & 0xFF);


startCommands[4] = (byte)(cmdlen & 0xFF);

byte[] FinalCommands = new byte[15 + cmdbyte.Length];

Array.Copy(startCommands, 0, FinalCommands, 0,
startCommands.Length);

Array.Copy(cmdbyte, 0, FinalCommands, startCommands.Length,


cmdbyte.Length);

FinalCommands[FinalCommands.Length - 6] = 0x00;
FinalCommands[FinalCommands.Length - 5] = 0x01;

sendCRC =
crc_bytes(FinalCommands.Skip(2).Take(FinalCommands.Length - 6).ToArray());

FinalCommands[FinalCommands.Length - 4] = (byte)((sendCRC
>> 8) & 0xFF);
FinalCommands[FinalCommands.Length - 3] = (byte)((sendCRC)
& 0xFF);

FinalCommands[FinalCommands.Length - 2] = 0x0D;
FinalCommands[FinalCommands.Length - 1] = 0x0A;

string cmd = BytesToString(FinalCommands);


//WriteToFile("Full command : " + cmd);
NetworkStream Netstream = client.GetStream();
Netstream.Write(FinalCommands, 0, FinalCommands.Length);

strCommand = "update VehiclesLockSetting set Sync=1 where


ID= " + ds.Tables[1].Rows[0]["ID"].ToString();
g.InsertUpdateDelete(strCommand);
}
#endregion

#region overspeed
if (ds.Tables[2].Rows.Count > 0 && !ds.Tables[2].Rows[0]
[0].ToString().Contains("Error"))
{
WriteToFile("Over Speed");

//string protocol = ds.Tables[2].Rows[0]


["ProtocolData"].ToString();
string strhigh = ds.Tables[2].Rows[0]
["MaxSpeed"].ToString();
string strInterval = ds.Tables[2].Rows[0]
["MinSpeed"].ToString();
//protocol = protocol.Replace("$deviceid$", objstate.IMEI);
//protocol = protocol.Replace("$high$", strhigh);
//protocol = protocol.Replace("$low$", strlow);

byte[] startCommands = { 0x78, 0x78, 0x00, 0x80, 0x00,


0x00, 0x00, 0x00, 0x00 };

string strCommand = "SPEED,ON," + strInterval + "," +


strhigh + ",0#";

//WriteToFile("ASCII command:" + strCommand);


byte[] cmdbyte = Ascii2Hex(strCommand);
//WriteToFile("command:" + BytesToString(cmdbyte));

int cmdlen = cmdbyte.Length + 4;


int totLen = 6 + cmdlen;

startCommands[2] = (byte)(totLen & 0xFF);


startCommands[4] = (byte)(cmdlen & 0xFF);

byte[] FinalCommands = new byte[15 + cmdbyte.Length];

Array.Copy(startCommands, 0, FinalCommands, 0,
startCommands.Length);

Array.Copy(cmdbyte, 0, FinalCommands, startCommands.Length,


cmdbyte.Length);

FinalCommands[FinalCommands.Length - 6] = 0x00;
FinalCommands[FinalCommands.Length - 5] = 0x01;

sendCRC =
crc_bytes(FinalCommands.Skip(2).Take(FinalCommands.Length - 6).ToArray());

FinalCommands[FinalCommands.Length - 4] = (byte)((sendCRC
>> 8) & 0xFF);
FinalCommands[FinalCommands.Length - 3] = (byte)((sendCRC)
& 0xFF);
FinalCommands[FinalCommands.Length - 2] = 0x0D;
FinalCommands[FinalCommands.Length - 1] = 0x0A;

string cmd = BytesToString(FinalCommands);


//WriteToFile("Full command : " + cmd);

NetworkStream Netstream = client.GetStream();


Netstream.Write(FinalCommands, 0, FinalCommands.Length);

strCommand = "update VehiclesOverspeedSetting set Sync=1


where ID= " + ds.Tables[2].Rows[0]["ID"].ToString();
g.InsertUpdateDelete(strCommand);

}
#endregion

#region Defence & sensor

if (ds.Tables[3].Rows.Count > 0 && !ds.Tables[3].Rows[0]


[0].ToString().Contains("Error"))
{
WriteToFile("Defence command");
byte[] startCommands = { 0x78, 0x78, 0x00, 0x80, 0x00,
0x00, 0x00, 0x00, 0x00 };

//{ 0x78, 0x78, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x01, 0x00, 0x00, 0x0D, 0x0A };
//string protocol = ds.Tables[1].Rows[0]
["ProtocolData"].ToString();
string strCommand = "";
if (ds.Tables[3].Rows[0]["Defence"].ToString() == "True")
{
strCommand = "SENALM,ON,0#";
//0/1/2, way of alarming, 0 :GPRS only, 1: SMS+GPRS,
2 : GPRS+SMS+phone call
}
else
{
strCommand = "SENALM,OFF#";
}

//WriteToFile("ASCII command:" + strCommand);


byte[] cmdbyte = Ascii2Hex(strCommand);
//WriteToFile("command:" + BytesToString(cmdbyte));

int cmdlen = cmdbyte.Length + 4;


int totLen = 6 + cmdlen;

startCommands[2] = (byte)(totLen & 0xFF);


startCommands[4] = (byte)(cmdlen & 0xFF);

byte[] FinalCommands = new byte[15 + cmdbyte.Length];

Array.Copy(startCommands, 0, FinalCommands, 0,
startCommands.Length);

Array.Copy(cmdbyte, 0, FinalCommands, startCommands.Length,


cmdbyte.Length);

FinalCommands[FinalCommands.Length - 6] = 0x00;
FinalCommands[FinalCommands.Length - 5] = 0x01;

sendCRC =
crc_bytes(FinalCommands.Skip(2).Take(FinalCommands.Length - 6).ToArray());

FinalCommands[FinalCommands.Length - 4] = (byte)((sendCRC
>> 8) & 0xFF);
FinalCommands[FinalCommands.Length - 3] = (byte)((sendCRC)
& 0xFF);

FinalCommands[FinalCommands.Length - 2] = 0x0D;
FinalCommands[FinalCommands.Length - 1] = 0x0A;

string cmd = BytesToString(FinalCommands);


//WriteToFile("Full command : " + cmd);

NetworkStream Netstream = client.GetStream();


Netstream.Write(FinalCommands, 0, FinalCommands.Length);

strCommand = "update VehiclesDefenceSetting set Sync=1


where ID= " + ds.Tables[3].Rows[0]["ID"].ToString();
g.InsertUpdateDelete(strCommand);
}
#endregion

#region Commands
if (ds.Tables[4].Rows.Count > 0 && !ds.Tables[4].Rows[0]
[0].ToString().Contains("Error"))
{
WriteToFile("command");
byte[] startCommands = { 0x78, 0x78, 0x00, 0x80, 0x00,
0x00, 0x00, 0x00, 0x00 };

//{ 0x78, 0x78, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x01, 0x00, 0x00, 0x0D, 0x0A };
//string protocol = ds.Tables[1].Rows[0]
["ProtocolData"].ToString();

//string strlock = (ds.Tables[1].Rows[0]["lock"].ToString()


== "True") ? "1" : "0";
string strCommand = ds.Tables[4].Rows[0]
["Command"].ToString();
string commandNo = ds.Tables[4].Rows[0]["ID"].ToString();

byte[] serverflag = new byte[4];


serverflag = intToBytes(int.Parse(commandNo), 4);
Array.Copy(serverflag, 0, startCommands, 5, 4);

//WriteToFile("ASCII command:" + strCommand);


byte[] cmdbyte = Ascii2Hex(strCommand);
//WriteToFile("command:" + BytesToString(cmdbyte));

int cmdlen = cmdbyte.Length + 4;


int totLen = 6 + cmdlen;

startCommands[2] = (byte)(totLen & 0xFF);


startCommands[4] = (byte)(cmdlen & 0xFF);

byte[] FinalCommands = new byte[15 + cmdbyte.Length];

Array.Copy(startCommands, 0, FinalCommands, 0,
startCommands.Length);

Array.Copy(cmdbyte, 0, FinalCommands, startCommands.Length,


cmdbyte.Length);

FinalCommands[FinalCommands.Length - 6] = 0x00;
FinalCommands[FinalCommands.Length - 5] = 0x01;

sendCRC =
crc_bytes(FinalCommands.Skip(2).Take(FinalCommands.Length - 6).ToArray());

FinalCommands[FinalCommands.Length - 4] = (byte)((sendCRC
>> 8) & 0xFF);
FinalCommands[FinalCommands.Length - 3] = (byte)((sendCRC)
& 0xFF);

FinalCommands[FinalCommands.Length - 2] = 0x0D;
FinalCommands[FinalCommands.Length - 1] = 0x0A;

string cmd = BytesToString(FinalCommands);


//WriteToFile("Full command : " + cmd);

NetworkStream Netstream = client.GetStream();


Netstream.Write(FinalCommands, 0, FinalCommands.Length);

strCommand = "update DeviceCommandHistory set Sync=1 where


ID= " + ds.Tables[4].Rows[0]["ID"].ToString();
g.InsertUpdateDelete(strCommand);
}
#endregion

#endregion

//lock (_lock) list_clients.Remove(id);


//client.Client.Shutdown(SocketShutdown.Both);
//client.Close();

WriteToFile("Active Threads :" + list_clients.Count);


}
catch (Exception ex)
{
WriteToFile(ex.Message);
}

public byte[] intToBytes(int num, int byteLength)


{
byte[] res = new byte[byteLength];

byte[] temp = BitConverter.GetBytes(num);


Array.Copy(temp, res, byteLength);

return res;
}

static string BytesToString(byte[] bytes)


{
return string.Join("", bytes.Select(x => x.ToString("X2")));
}

public string hex2bin(string value)


{
return Convert.ToString(Convert.ToInt32(value, 16),
2).PadLeft(value.Length * 4, '0');
}

public byte[] Ascii2Hex(string cmd)


{
byte[] ba = Encoding.Default.GetBytes(cmd);
var hexString = BitConverter.ToString(ba);

//byte[] bytes = new byte[hexString.Length / 2];


//for (int i = 0; i < hexString.Length; i += 2)
// bytes[i / 2] = Convert.ToByte(hexString.Substring(i, 2), 16);

string[] data = hexString.Split('-');

byte[] bytes = new byte[data.Length];


for (int i = 0; i < data.Length; i++)
bytes[i] = Convert.ToByte(data[i], 16);

return bytes;
}

public string ConvertDegreeAngleToDouble(string deg, string min, string


Cord)
{
//Example: 17.21.18S
//2056.3194N
//07255.9813E.

var multiplier = (Cord.Contains("S") || Cord.Contains("W")) ? -1 :


1; //handle south and west

double data = (Double.Parse(deg) + (double.Parse(min) / 60)) *


multiplier;
return data.ToString("0.000000");

public string ConvertDoubleDegreeAngle(string type, string latlng)


{
//2056.8085N 07255.2953E
//20.9467877,72.9216258

string DegreeAng = "";

decimal degree = decimal.Parse(latlng.Split('.')[0]);


string min = (decimal.Parse("." + latlng.Split('.')[1]) *
60).ToString("0.000");

string ltngtype = "";


if (type == "lat")
{
if (latlng.Contains("-"))
{
ltngtype = "S";
}
else
{
ltngtype = "N";
}
DegreeAng = degree.ToString("00") + min + ltngtype;
}
else
{
if (latlng.Contains("-"))
{
ltngtype = "W";
}
else
{
ltngtype = "E";
}
DegreeAng = degree.ToString("000") + min + ltngtype;
}
return DegreeAng;
}

public void WriteToFile(string Message)


{
string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string filepath = AppDomain.CurrentDomain.BaseDirectory +
"\\Logs\\ServiceLog_" + DateTime.Now.Date.ToShortDateString().Replace('/', '_') +
".txt";
if (!File.Exists(filepath))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(filepath))
{
sw.WriteLine(Message);
}
}
else
{
using (StreamWriter sw = File.AppendText(filepath))
{
sw.WriteLine(Message);
}
}
}

public string insertData(string DeviceID, string Date, string Availability,


string latitude, string longitude, string Speed, string MainPower, string ignition)
{
Global g = new Global();
string strStud = "AddGPSData";

SqlParameter[] param = new SqlParameter[8];

param[0] = new SqlParameter();


param[0].ParameterName = "DeviceID";
param[0].Value = DeviceID;
param[0].SqlDbType = SqlDbType.VarChar;

param[1] = new SqlParameter();


param[1].ParameterName = "Date";
param[1].Value = Date;
param[1].SqlDbType = SqlDbType.DateTime;

param[2] = new SqlParameter();


param[2].ParameterName = "Availability";
param[2].Value = Availability;
param[2].SqlDbType = SqlDbType.VarChar;

param[3] = new SqlParameter();


param[3].ParameterName = "latitude";
param[3].Value = latitude;
param[3].SqlDbType = SqlDbType.VarChar;

param[4] = new SqlParameter();


param[4].ParameterName = "longitude";
param[4].Value = longitude;
param[4].SqlDbType = SqlDbType.VarChar;

param[5] = new SqlParameter();


param[5].ParameterName = "Speed";
param[5].Value = Speed;
param[5].SqlDbType = SqlDbType.VarChar;

param[6] = new SqlParameter();


param[6].ParameterName = "MainPower";
param[6].Value = MainPower;
param[6].SqlDbType = SqlDbType.VarChar;

param[7] = new SqlParameter();


param[7].ParameterName = "ignition";
param[7].Value = ignition;
param[7].SqlDbType = SqlDbType.VarChar;

DataSet ds = g.ExecuteProcedureWithParam(strStud, param);

try
{
if (ds.Tables[0].Rows.Count > 0 && ds.Tables[0].Rows[0]
[0].ToString() == "1")
{
if (ds.Tables[0].Rows[0]["IsNotification"].ToString() ==
"True")
{
sendNotification("IGNITION ALERT", ds.Tables[0].Rows[0]
["NotificationTitle"].ToString(), ds.Tables[0].Rows[0]
["NotificationBody"].ToString(), DeviceID, Date, "", "", "");
}
else
{

}
}
}
catch (Exception ex)
{
WriteToFile(ex.Message);
}
return ds.Tables[0].Rows[0][0].ToString();
}

public string UpdateHeartbeatData(string DeviceID, string VoltageLevel,


string GPSSignal, string GSMSignal, string Status, string LastUpdated, string
MainPower)
{
Global g = new Global();
string strStud = "UpdateHeartbeadData";

SqlParameter[] param = new SqlParameter[7];

param[0] = new SqlParameter();


param[0].ParameterName = "DeviceID";
param[0].Value = DeviceID;
param[0].SqlDbType = SqlDbType.VarChar;

param[1] = new SqlParameter();


param[1].ParameterName = "VoltageLevel";
param[1].Value = VoltageLevel;
param[1].SqlDbType = SqlDbType.VarChar;

param[2] = new SqlParameter();


param[2].ParameterName = "GPSSignal";
param[2].Value = GPSSignal;
param[2].SqlDbType = SqlDbType.VarChar;

param[3] = new SqlParameter();


param[3].ParameterName = "GSMSignal";
param[3].Value = GSMSignal;
param[3].SqlDbType = SqlDbType.VarChar;

param[4] = new SqlParameter();


param[4].ParameterName = "Status";
param[4].Value = Status;
param[4].SqlDbType = SqlDbType.VarChar;

param[5] = new SqlParameter();


param[5].ParameterName = "LastUpdated";
param[5].Value = LastUpdated;
param[5].SqlDbType = SqlDbType.VarChar;

param[6] = new SqlParameter();


param[6].ParameterName = "MainPower";
param[6].Value = MainPower;
param[6].SqlDbType = SqlDbType.VarChar;

DataSet ds = g.ExecuteProcedureWithParam(strStud, param);


return ds.Tables[0].Rows[0][0].ToString();
}

void sendNotification(string NotificationType, string Title, string body,


string DeviceID, string Date, string FenceMode, string Lat, string lng)
{
Global gl = new Global();
string qry = "select DeviceRegistrationID AS
FCMID,VehicleNo,VehicleName from FCMDeviceReg f,Vehicles v where f.UserID =
v.UserID AND v.DeviceID = '" + DeviceID + "' ";
DataTable dt = gl.Select(qry);

body = body.Replace("$VehicleNo$", dt.Rows[0]["VehicleNo"].ToString());


body = body.Replace("$VehicleName$", dt.Rows[0]
["VehicleName"].ToString());

Title = Title.Replace("$VehicleNo$", dt.Rows[0]


["VehicleNo"].ToString());
Title = Title.Replace("$VehicleName$", dt.Rows[0]
["VehicleName"].ToString());

qry = "Insert into Notifications([Date],[DeviceID],


[NotificationType],NotificationTitle,[Notification]) values('" + Date + "','" +
DeviceID + "','" + NotificationType + "',N'" + Title + "',N'" + body + "')";
string res = gl.InsertUpdateDelete(qry);

if (NotificationType == "FENCE ALERT")


{
qry = "INSERT INTO [dbo].[NotificationsGeoFence]([Date],[DeviceID],
[FenceMode],[Latitude],[Longitude]) values ('" + Date + "','" + DeviceID + "','" +
FenceMode + "','" + Lat + "','" + lng + "')";
res = gl.InsertUpdateDelete(qry);
if (res != "1")
{
WriteToFile(qry);
}

}
//WriteToFile(qry);
for (int i = 0; i < dt.Rows.Count; i++)
{
gl.SendPushNotification(body, Title, dt.Rows[i]
["FCMID"].ToString());
}
}
}
}

You might also like