/// <summary> /// /// </summary> /// <param name="state"></param> private async void HandelTeltonikaSockets(object state) { string imei = string.Empty; using (var client = ((TcpClient)state)) { using (NetworkStream stream = ((TcpClient)state).GetStream()) { try { var gpsResult = new List <CreateTeltonikaGps>(); var buffer = new byte[client.ReceiveBufferSize]; while (true) { if (imei == string.Empty) { int bytesRead = stream.Read(buffer, 0, client.ReceiveBufferSize) - 2; lock (stream) { imei = _devicesParser.GetIMEI(buffer, bytesRead); Console.WriteLine("IMEI received : " + imei); Byte[] b = { 0x01 }; stream.Write(b, 0, 1); } await SendNewDeviceCommad(imei); } else if (imei != string.Empty) { _semaphore = new Semaphore(1, 10, imei); lock (stream) { // _semaphore.WaitOne(); gpsResult.AddRange(_devicesParser.Decode(new List <byte>(buffer), imei)); var bytes = Convert.ToByte(gpsResult.Count); stream.Write(new byte[] { 0x00, 0x0, 0x0, bytes }, 0, 4); client.Close(); // _semaphore.Release(); } await SendDecodedData(gpsResult, imei); break; } else { break; } } } catch (Exception e) { Console.WriteLine(e); client.Close(); //throw; } } } }
private List <CreateTeltonikaGps> ParseAvlData(string imei, byte[] buffer) { List <CreateTeltonikaGps> gpsResult = new List <CreateTeltonikaGps>(); var parser = new DevicesParser(); gpsResult.AddRange(parser.Decode(new List <byte>(buffer), imei)); LogAvlData(gpsResult); return(gpsResult); }
private async Task <List <CreateTeltonikaGps> > ParsseAvlData(string imei, byte[] buffer) { List <CreateTeltonikaGps> gpsResult = new List <CreateTeltonikaGps>(); var parser = new DevicesParser(); gpsResult.AddRange(parser.Decode(new List <byte>(buffer), imei)); // await GeoReverseCodeGpsData(gpsResult); LogAvlData(gpsResult); return(gpsResult); }
/// <summary> /// /// </summary> /// <param name="imei"></param> /// <param name="dataReceived"></param> /// <param name="stream"></param> /// <param name="buffer"></param> /// <returns></returns> private static async Task ParseTeltonikaData(TcpClient client, NetworkStream stream, byte[] buffer, string imei) { var currentImei = string.Empty; var gpsResult = new List <CreateTeltonikaGps>(); while (true) { if (currentImei == string.Empty) { currentImei = imei; Console.WriteLine("IMEI received : " + currentImei); Byte[] b = { 0x01 }; stream.Write(b, 0, 1); var command = new CreateBoxCommand(); command.Imei = imei; if (_bus != null) { await _bus.Send(command); } } else { int dataNumber = Convert.ToInt32(buffer.Skip(9).Take(1).ToList()[0]); while (dataNumber > 0) { var parser = new DevicesParser(); gpsResult.AddRange(parser.Decode(new List <byte>(buffer), imei)); dataNumber--; } await stream.WriteAsync(new byte[] { 0x00, 0x00, 0x00, 0x01 }, 0, 4).ConfigureAwait(false); } if (!gpsResult.Any() && imei.Any()) { continue; } foreach (var gpSdata in gpsResult) { if (_bus != null) { await _bus.Send(gpSdata); } } break; } }
private static async void ThreadProc(object state) { string imei = string.Empty; var client = ((TcpClient)state); NetworkStream nwStream = ((TcpClient)state).GetStream(); byte[] buffer = new byte[client.ReceiveBufferSize]; try { var gpsResult = new List <CreateTeltonikaGps>(); while (true) { int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize) - 2; string dataReceived = Encoding.ASCII.GetString(buffer, 2, bytesRead); if (imei == string.Empty) { imei = dataReceived; Console.WriteLine("IMEI received : " + dataReceived); Byte[] b = { 0x01 }; nwStream.Write(b, 0, 1); var command = new CreateBoxCommand(); command.Imei = imei; await _endpoint.Result.Send(command); } else { int dataNumber = Convert.ToInt32(buffer.Skip(9).Take(1).ToList()[0]); var parser = new DevicesParser(); gpsResult.AddRange(parser.Decode(new List <byte>(buffer), imei)); var bytes = Convert.ToByte(dataNumber); await nwStream.WriteAsync(new byte[] { 0x00, 0x0, 0x0, bytes }, 0, 4); client.Close(); } if (gpsResult.Count <= 0) { continue; } foreach (var gpSdata in gpsResult) { gpSdata.Address = await _reverseGeoCodingService.ReverseGoecode(gpSdata.Lat, gpSdata.Long); Console.WriteLine("IMEI: " + imei + " Date: " + gpSdata.Timestamp + " latitude : " + gpSdata.Lat + " Longitude:" + gpSdata.Long + " Speed: " + gpSdata.Speed + " Direction:" + "" + " address " + gpSdata.Address + " milage :" + gpSdata.Mileage); await _bus.Publish(gpSdata); } break; } } catch (Exception) { // Console.WriteLine(e); client.Close(); //throw; } //throw new NotImplementedException(); }
// ReSharper disable once ExcessiveIndentation private void ReceiveCallback(IAsyncResult result) { ConnectionInfo connection = (ConnectionInfo)result.AsyncState; try { //get a number of received bytes int bytesRead = connection.Socket.EndReceive(result); if (bytesRead > 0) { //because device sends data with portions we need summary all portions to total buffer if (connection.IsPartialLoaded) { connection.TotalBuffer.AddRange(connection.Buffer.Take(bytesRead).ToList()); } else { if (connection.TotalBuffer != null) { connection.TotalBuffer.Clear(); } connection.TotalBuffer = connection.Buffer.Take(bytesRead).ToList(); } //-------- Get Length of current received data ---------- string hexDataLength = string.Empty; //Skip four zero bytes an take next four bytes with value of AVL data array length connection.TotalBuffer.Skip(4).Take(4).ToList().ForEach(delegate(byte b) { hexDataLength += String.Format("{0:X2}", b); }); int dataLength = Convert.ToInt32(hexDataLength, 16); // //bytesRead = 17 when parser receive IMEI from device //if datalength encoded in data > then total buffer then is a partial data a device will send next part //we send confirmation and wait next portion of data // ReSharper disable once ComplexConditionExpression if (dataLength + 12 > connection.TotalBuffer.Count && bytesRead != 17) { connection.IsPartialLoaded = true; connection.Socket.Send(new byte[] { 0x01 }); connection.Socket.BeginReceive(connection.Buffer, 0, connection.Buffer.Length, SocketFlags.None, ReceiveCallback, connection); return; } bool isDataPacket = true; //when device send AVL data first 4 bytes is 0 string firstRourBytes = string.Empty; connection.TotalBuffer.Take(4).ToList().ForEach(delegate(byte b) { firstRourBytes += String.Format("{0:X2}", b); }); if (Convert.ToInt32(firstRourBytes, 16) > 0) { isDataPacket = false; } // if is true then is AVL data packet // else that a IMEI sended if (isDataPacket) { if (true) { //all data we convert this to string in hex format only for diagnostic StringBuilder data = new StringBuilder(); connection.TotalBuffer.ForEach(delegate(byte b) { data.AppendFormat("{0:X2}", b); }); Console.WriteLine("<" + data); } var decAvl = new DevicesParser(); decAvl.OnDataReceive += decAVL_OnDataReceive; //if CRC not correct number of data returned by AVL parser = 0; var avlData = decAvl.Decode(connection.TotalBuffer, connection.Imei); if (!connection.IsPartialLoaded) { // send to device number of received data for confirmation. if (avlData.Count > 0) { connection.Socket.Send(new byte[] { 0x00, 0x00, 0x00, Convert.ToByte(avlData.Count) }); LogAvlData(avlData); var events = new TLGpsDataEvents { Id = Guid.NewGuid(), Events = avlData }; var lastGpsData = events.Events.Last(); var command = new CreateBoxCommand(); command.Imei = connection.Imei; command.Longitude = lastGpsData.Long; command.Latitude = lastGpsData.Lat; command.LastValidGpsDataUtc = lastGpsData.DateTimeUtc; command.Speed = lastGpsData.Speed; _bus.Publish(command).ConfigureAwait(false); Thread.Sleep(1000); _bus.Publish(events).ConfigureAwait(false); } else { //send 0 number of data if CRC not correct for resend data from device connection.Socket.Send(new byte[] { 0x00, 0x00, 0x00, 0x00 }); } } decAvl.OnDataReceive -= decAVL_OnDataReceive; Console.WriteLine("Modem ID: " + connection.Imei + " send data"); } else { //if is not data packet then is it IMEI info send from device connection.Imei = Encoding.ASCII.GetString(connection.TotalBuffer.Skip(2).ToArray()); connection.Socket.Send(new byte[] { 0x01 }); Console.WriteLine("Modem ID: " + connection.Imei + " connected"); } // Get next data portion from device connection.Socket.BeginReceive(connection.Buffer, 0, connection.Buffer.Length, SocketFlags.None, ReceiveCallback, connection); }//if all data received then close connection else { CloseConnection(connection); } } catch (SocketException exc) { CloseConnection(connection); Console.WriteLine("Socket exception: " + exc.SocketErrorCode); } catch (Exception exc) { CloseConnection(connection); Console.WriteLine("Exception: " + exc); } }