Comunicação por soquete GPS (CONCOX)

1]1Eu tenho um dispositivo GPS que deve enviar dados GPRMC, mas requer pacote de login Revise a folha de dadosFicha de dados do dispositivo

posso receber o login 787811010XXX739050313XXX20200001000E0EAD0D0A

     IMEI Sart With XXX

o pacote é diferente do exemplo Image

Eu tenho 2 perguntas 1-de acordo com os dados recebidos e o exemplo o que devo enviar 2- como calcular a verificação de erro Obrigado

Editar

public static void StartListening()
{
    // Data buffer for incoming data.
    byte[] bytes = new Byte[1024];

    // Establish the local endpoint for the socket.
    // The DNS name of the computer
    // running the listener is "host.contoso.com".
    IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
    IPAddress ipAddress = ipHostInfo.AddressList[0];
    IPAddress local = IPAddress.Parse("My IP");
    IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 8841);

    // Create a TCP/IP socket.
    Socket listener = new Socket(AddressFamily.InterNetwork,
        SocketType.Stream, ProtocolType.Tcp);

    // Bind the socket to the local endpoint and listen for incoming connections.
    try
    {
        listener.Bind(localEndPoint);
        listener.Listen(100);

        while (true)
        {
            // Set the event to nonsignaled state.
            allDone.Reset();

            // Start an asynchronous socket to listen for connections.
            // Console.WriteLine("Waiting for a connection...");
            listener.BeginAccept(
                new AsyncCallback(AcceptCallback),
                listener);

            // Wait until a connection is made before continuing.
            allDone.WaitOne();
        }

    }
    catch (Exception e)
    {
        // Console.WriteLine(e.ToString());
    }

    // Console.WriteLine("\nPress ENTER to continue...");
    // Console.Read();

}
private static void Send(Socket handler, String data)
{
    // Convert the string data to byte data using ASCII encoding.
    byte[] byteData = Encoding.ASCII.GetBytes(data);

    // Begin sending the data to the remote device.
    handler.BeginSend(byteData, 0, byteData.Length, 0,
        new AsyncCallback(SendCallback), handler);
}
private static void Send(Socket handler, byte[]  data)
{
    // Convert the string data to byte data using ASCII encoding.
   // byte[] byteData = Encoding.ASCII.GetBytes(data);

    // Begin sending the data to the remote device.
    handler.BeginSend(data, 0, data.Length, 0,
        new AsyncCallback(SendCallback), handler);
}
private static void SendCallback(IAsyncResult ar)
{
    try
    {
        // Retrieve the socket from the state object.
        Socket handler = (Socket)ar.AsyncState;

        // Complete sending the data to the remote device.
        int bytesSent = handler.EndSend(ar);
        // Console.WriteLine("Sent {0} bytes to client.", bytesSent);

        handler.Shutdown(SocketShutdown.Both);
        handler.Close();

    }
    catch (Exception e)
    {
        // Console.WriteLine(e.ToString());
    }
}
public static void AcceptCallback(IAsyncResult ar)
{
    // Signal the main thread to continue.
    allDone.Set();

    // Get the socket that handles the client request.
    Socket listener = (Socket)ar.AsyncState;
    Socket handler = listener.EndAccept(ar);

    // Create the state object.
    StateObject state = new StateObject();
    state.workSocket = handler;
    handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
        new AsyncCallback(ReadCallback), state);
}
static byte[] Unpack(string data)
{
    //return null indicates an error
    List<byte> bytes = new List<byte>();

    // check start and end bytes

    if ((data.Substring(0, 4) != "7878") && (data.Substring(data.Length - 4) != "0D0A"))
    {
        return null;
    }

    for (int index = 4; index < data.Length - 4; index += 2)
    {
        bytes.Add(byte.Parse(data.Substring(index, 2), System.Globalization.NumberStyles.HexNumber));
    }
    //crc test
    byte[] packet = bytes.Take(bytes.Count - 2).ToArray();
    byte[] crc = bytes.Skip(bytes.Count - 2).ToArray();

    uint CalculatedCRC = crc_bytes(packet);


    return packet;
}
public static UInt16 crc_bytes(byte[] data)
{
    ushort crc = 0xFFFF;

    for (int i = 0; i < data.Length; i++)
    {
        crc ^= (ushort)(data[i] << 8);
        for (int j = 0; j < 8; j++)
        {
            if ((crc & 0x8000) > 0)
                crc = (ushort)((crc << 1) ^ 0x1021);
            else
                crc <<= 1;
        }
    }

    return crc;
}
public static void ReadCallback(IAsyncResult ar)
{
    String content = String.Empty;

    // Retrieve the state object and the handler socket
    // from the asynchronous state object.
    StateObject state = (StateObject)ar.AsyncState;
    Socket handler = state.workSocket;

    // Read data from the client socket. 
    int bytesRead = handler.EndReceive(ar);

    if (bytesRead > 0)
    {

        if (state.buffer[3] == 1)
        {

            string input = BitConverter.ToString(state.buffer, 0, bytesRead).Replace("-", "");

            byte[] bytes = Unpack(input);

            byte[] serialNumber = bytes.Skip(bytes.Length - 2).ToArray();

            byte[] response = { 0x78, 0x78, 0x05, 0x01, 0x00, 0x00, 0x00, 0x0 };

            serialNumber.CopyTo(response, 4);

            UInt16 sendCRC = crc_bytes(response.Take(response.Length - 2).ToArray());

            response[response.Length - 2] = (byte)((sendCRC >> 8) & 0xFF);
            response[response.Length - 1] = (byte)((sendCRC) & 0xFF);

            Send(handler, response);
           // handler.Send(response);
        }
        else
        {
            // There  might be more data, so store the data received so far.
            state.sb.Append(Encoding.ASCII.GetString(
                state.buffer, 0, bytesRead));

            // Check for end-of-file tag. If it is not there, read 
            // more data.
            content = state.sb.ToString();


            SaveData(content);
            // Not all data received. Get more.
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
            new AsyncCallback(ReadCallback), state);
            // }
        }
    }
}

Folha de dados do fornecedor

4.6 Verificação de erro Um código de verificação pode ser usado pelo terminal ou pelo servidor para distinguir se as informações recebidas são ou não erros. Para evitar que ocorram erros durante a transmissão de dados, a verificação de erros é adicionada à operação incorreta dos dados, de modo a aumentar a segurança e a eficiência do sistema. O código de verificação é gerado pelo método de verificação CRC-ITU. Os códigos de verificação dos dados na estrutura do protocolo, do Comprimento do pacote ao Número de série da informação (incluindo "Comprimento do pacote" e "Número de série da informação"), são valores do CRC-ITU. O erro CRC ocorre quando a informação recebida é calculada, o receptor ignora e descarta o pacote de dados. 4

Tabela DataBase

CREATE TABLE [dbo].[T_Tracking](
[id] [int] IDENTITY(1,1) NOT NULL,
[IMEI] [nvarchar](50) NULL,
[TrackTime] [datetime] NULL,
[CurrTime] [datetime] NULL CONSTRAINT [DF_T_Tracking_CurrTime]  DEFAULT (getutcdate()),
[Longitude] [nvarchar](50) NULL,
[Lattitude] [nvarchar](50) NULL,
[speed] [float] NULL    

Você codifica

 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 terminalID = Encoding.ASCII.GetString(receiveMessage.Skip(4).Take(messageLength - 5).ToArray());
                                    Console.WriteLine("Received good login message from Serial Number : '{0}', Terminal ID = '{1}'", "0x" + serialNumber[0].ToString("X2") + serialNumber[1].ToString("X2"), terminalID);

                                    Console.WriteLine("Send Message : '{0}'", BytesToString(loginResponse));
                                    Send(state.workSocket, loginResponse);

                                    break;
                                case PROTOCOL_NUMBER.LOCATION_DATA:
                                    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);
                                    Console.WriteLine("Received good location message from Serial Number '{0}', Time = '{1}'", "0x" + serialNumber[0].ToString("X2") + serialNumber[1].ToString("X2"), date.ToLongDateString()); string lng = message.Substring(22, 8);
                                Int64 lngVal = Convert.ToInt64(lng, 16);

                                double step3 = (double)lngVal / 30000;
                                double step4 = (double)((step3 / 60));
                                //int lngdeg =Convert.ToInt32( step4.ToString().Split('.')[0]);

                                //  double step5 = (double)(step4 * 60) - step3;


                                string lat = message.Substring(30, 8);
                                Int64 altVal = Convert.ToInt64(lat, 16);
                                double Lstep3 = (double)altVal / 30000;
                                double Lstep4 = (double)((Lstep3) / 60);
                                //  double Lstep5 = (double)(Lstep4 * 60) - Lstep3;
                                //Console.WriteLine("Date : '{0}',Long : '{1}', Receive Message : '{2}'", dateStr, step4, Lstep4);
                                string speedstr = message.Substring(38, 2);
                                int SpeedVal = Convert.ToInt32(speedstr, 16);
                                SaveData(IMEI , dateStr, step4.ToString(), Lstep4.ToString(), SpeedVal);//Get IMEI From Login Message that is the Problem
                                    break;

Mensagem de status

questionAnswers(4)

yourAnswerToTheQuestion