Esempio n. 1
0
        public RFIDDetectado(byte[] buffer, int pos)
        {
            PDU this_pdu = this;

            Entrante = true;
            UrbetrackCodec.DecodeHeaders(buffer, ref this_pdu, ref pos);
            var d = Devices.I().FindById(this_pdu.IdDispositivo);

            switch (CL)
            {
            case 0x00:
                IdTarjeta = UrbetrackCodec.DecodeString(buffer, ref pos);
                Posicion  = UrbetrackCodec.DecodeGPSPoint(buffer, ref pos);
                Status    = 0xFE;
                break;

            case 0x20:
                IdTarjeta = UrbetrackCodec.DecodeString(buffer, ref pos);
                Posicion  = d.SupportsGPSPointEx ? UrbetrackCodec.DecodeGPSPointEx(buffer, ref pos, d) : UrbetrackCodec.DecodeGPSPoint(buffer, ref pos);
                Status    = UrbetrackCodec.DecodeByte(buffer, ref pos);
                break;

            default:
                throw new Exception("No conincide CL con el Tipo RFID Detectado.");
            }
        }
Esempio n. 2
0
        public override void FinalEncode(ref byte[] buffer, ref int pos)
        {
            UrbetrackCodec.EncodeShort(ref buffer, ref pos, Pagina);
            if (CL >= 0x02) // DataPage Extendida.
            {
                UrbetrackCodec.EncodeShort(ref buffer, ref pos, TotalDePaginas);
                UrbetrackCodec.EncodeShort(ref buffer, ref pos, (short)Buffer.GetLength(0));
                var md5Hasher = MD5.Create();
                var firma     = md5Hasher.ComputeHash(Buffer);
                if (firma.GetLength(0) != 16)
                {
                    throw new Exception("El tamaño del hash MD5 no es valido.");
                }

                if (Hacker.ServerUT.DataPageExSignatureError && (Pagina == 2 || Pagina == 4 || Pagina == 12) && Intento < 2)
                {
                    STrace.Debug(GetType().FullName, String.Format("DATAPAGE: Hacker de pagina {0}, Intento {1}, seq {2}", Pagina, Intento, Seq));
                    var lie = new byte[16];
                    UrbetrackCodec.EncodeBytes(ref buffer, ref pos, lie);
                }
                else
                {
                    UrbetrackCodec.EncodeBytes(ref buffer, ref pos, firma);
                }
            }
            UrbetrackCodec.EncodeBytes(ref buffer, ref pos, Buffer);
        }
Esempio n. 3
0
        public LoginRechazado(byte[] buffer, int pos)
        {
            Entrante = true;
            PDU this_pdu = this;

            UrbetrackCodec.DecodeHeaders(buffer, ref this_pdu, ref pos);
        }
Esempio n. 4
0
        public ExcesoVelocidad(byte[] buffer, int pos)
        {
            PDU this_pdu = this;

            Entrante = true;
            UrbetrackCodec.DecodeHeaders(buffer, ref this_pdu, ref pos);
            switch (CL)
            {
            case 0x10:
            {
                var d = Devices.I().FindById(IdDispositivo);
                PosicionDeAviso          = null;
                PosicionDeTicket         = d.SupportsGPSPointEx ? UrbetrackCodec.DecodeGPSPointEx(buffer, ref pos, d) : UrbetrackCodec.DecodeGPSPoint(buffer, ref pos);
                PosicionFinal            = d.SupportsGPSPointEx ? UrbetrackCodec.DecodeGPSPointEx(buffer, ref pos, d) : UrbetrackCodec.DecodeGPSPoint(buffer, ref pos);
                VelocidadMaximaPermitida = UrbetrackCodec.DecodeFloat(buffer, ref pos);
                VelocidadMaximaAlcanzada = UrbetrackCodec.DecodeFloat(buffer, ref pos);
            }
            break;

            case 0x11:
            {
                var d = Devices.I().FindById(IdDispositivo);
                PosicionDeAviso          = UrbetrackCodec.DecodeGPSPointEx(buffer, ref pos, d);
                PosicionDeTicket         = UrbetrackCodec.DecodeGPSPointEx(buffer, ref pos, d);
                PosicionFinal            = UrbetrackCodec.DecodeGPSPointEx(buffer, ref pos, d);
                VelocidadMaximaPermitida = UrbetrackCodec.DecodeFloat(buffer, ref pos);
                VelocidadMaximaAlcanzada = UrbetrackCodec.DecodeFloat(buffer, ref pos);
                RiderIdentifier          = Encoding.ASCII.GetString(UrbetrackCodec.DecodeBytes(buffer, ref pos, 10));
            }
            break;
            }
        }
Esempio n. 5
0
 public override void FinalEncode(ref byte[] buffer, ref int pos)
 {
     UrbetrackCodec.EncodeString(ref buffer, ref pos, IMEI);
     UrbetrackCodec.EncodeString(ref buffer, ref pos, Password);
     UrbetrackCodec.EncodeString(ref buffer, ref pos, Firmware);
     UrbetrackCodec.EncodeShort(ref buffer, ref pos, ConfigRevision);
 }
Esempio n. 6
0
            protected override void OnReceive(StreamBlock block)
            {
                // agregarmos al buffer.
                STrace.Debug(GetType().FullName, deviceId, String.Format("FileServer: bloque de datos={0}", block.TotalBytes));
                Array.Copy(block.Data, 0, active_buffer, buffer_position, block.TotalBytes);
                buffer_position += block.TotalBytes;
                if (!headers_readed)
                {
                    if (buffer_position >= 71)
                    {
                        // leer la cabecera... podemos
                        // Short            IdDispositivo
                        // Byte             Destino (0x00 = File, 0x01 = Queue)
                        // Integer          Tamaño del Archivo (setea $FileSize)
                        // Bytes[64]        Nombre de Archivo o Base64MessageQueue segun corresponda (Rellenado con 0)
                        // Bytes[$FileSize] Datos del archivo.
                        var pos = 0;
                        deviceId       = UrbetrackCodec.DecodeShort(active_buffer, ref pos);
                        op             = UrbetrackCodec.DecodeByte(active_buffer, ref pos);
                        chunk_size     = UrbetrackCodec.DecodeInteger(active_buffer, ref pos);
                        label          = UrbetrackCodec.DecodeBytesAsString(active_buffer, ref pos, 64);
                        headers_readed = true;
                        strm           = new MemoryStream();
                        STrace.Debug(GetType().FullName, deviceId, String.Format("Iniciando Recepcion: queue={0} size={1}", label, chunk_size));
                    }
                    else
                    {
                        return;  // aun no leimos suficiente.
                    }
                }

                while (buffer_position > payload_start)
                {
                    STrace.Debug(GetType().FullName, deviceId, String.Format("Recibiendo bloque: size={0}", buffer_position - payload_start));
                    var data_block = new byte[buffer_position - payload_start];
                    Array.Copy(active_buffer, payload_start, data_block, 0, buffer_position - payload_start);
                    strm.Write(data_block, 0, buffer_position - payload_start);
                    buffer_position = payload_start = 0;
                    if (strm.Length != chunk_size)
                    {
                        continue;
                    }
                    bool local_result;

                    try
                    {
                        local_result = MessageReceived(deviceId, op, label, strm, true);
                    }
                    catch (Exception e)
                    {
                        STrace.Exception(GetType().FullName, e);
                        local_result = false;
                    }

                    Send(Encoding.ASCII.GetBytes(local_result ? "A" : "N"), 1, deviceId, "MemoryStream");
                    STrace.Debug(GetType().FullName, deviceId, String.Format("Respondo {0} y cierro.", local_result ? "A" : "N"));
                    Disconnect();
                }
            }
Esempio n. 7
0
        public Heartbeat(byte[] buffer, int pos)
        {
            Entrante = true;
            PDU this_pdu = this;

            UrbetrackCodec.DecodeHeaders(buffer, ref this_pdu, ref pos);
            signature = UrbetrackCodec.DecodeString(buffer, ref pos);
        }
Esempio n. 8
0
        public LoginAceptado(byte[] buffer, int pos)
        {
            PDU this_pdu = this;

            Entrante = true;
            UrbetrackCodec.DecodeHeaders(buffer, ref this_pdu, ref pos);
            IdAsignado = UrbetrackCodec.DecodeShort(buffer, ref pos);
        }
Esempio n. 9
0
 public override void FinalEncode(ref byte[] buffer, ref int pos)
 {
     UrbetrackCodec.EncodeString(ref buffer, ref pos, Identifier);
     UrbetrackCodec.EncodeString(ref buffer, ref pos, Description);
     UrbetrackCodec.EncodeString(ref buffer, ref pos, File);
     UrbetrackCodec.EncodeInteger(ref buffer, ref pos, Revision);
     UrbetrackCodec.EncodeByte(ref buffer, ref pos, Flags);
 }
Esempio n. 10
0
        public Command(byte[] buffer, int pos)
        {
            PDU this_pdu = this;

            UrbetrackCodec.DecodeHeaders(buffer, ref this_pdu, ref pos);
            var size = UrbetrackCodec.DecodeShort(buffer, ref pos);

            Datos = size > 0 ? UrbetrackCodec.DecodeBytes(buffer, ref pos, size) : null;
        }
Esempio n. 11
0
        public RemoteShell(byte[] buffer, int pos)
        {
            PDU this_pdu = this;

            Entrante = true;
            UrbetrackCodec.DecodeHeaders(buffer, ref this_pdu, ref pos);
            Order       = UrbetrackCodec.DecodeInteger(buffer, ref pos);
            CommandLine = UrbetrackCodec.DecodeString(buffer, ref pos);
        }
Esempio n. 12
0
            void SendFile(string order, string signature, string src_file, string path)
            {
                var full_file = String.Format(@"{0}\{1}", path, src_file);
                var fota_file = String.Format(@"{0}\{1}.l4pnp", path, src_file);

                if (!File.Exists(full_file))
                {
                    send("E");
                    return;
                }

                IO.PadFile(full_file, fota_file, 512, 0x00, true);

                using (var fs = File.OpenRead(fota_file))
                {
                    var filesize = (int)fs.Length;
                    if (filesize % 512 != 0)
                    {
                        send("E");
                        return;
                    }
                    var filepages = filesize / 512;
                    var md5Hasher = MD5.Create();
                    var b         = md5Hasher.ComputeHash(fs);
                    if (b.GetLength(0) != 16)
                    {
                        throw new Exception("el hash md5 no retorna 16 bytes.");
                    }
                    var buffer = new byte[256];
                    var pos    = 0;
                    send("D");
                    UrbetrackCodec.EncodeByte(ref buffer, ref pos, (byte)(Convert.ToInt16(order) & 0xFF));
                    UrbetrackCodec.EncodeString(ref buffer, ref pos, signature);
                    UrbetrackCodec.EncodeInteger(ref buffer, ref pos, filepages);
                    UrbetrackCodec.EncodeBytes(ref buffer, ref pos, b);
                    send(buffer, pos);
                }

                using (var fs = File.OpenRead(fota_file))
                {
                    var b = new byte[512];
                    while (fs.Read(b, 0, 512) > 0)
                    {
                        send(b, 512);
                    }
                }

                var cpos   = 0;
                var commit = new byte[3];

                UrbetrackCodec.EncodeByte(ref commit, ref cpos, (byte)'A');
                UrbetrackCodec.EncodeByte(ref commit, ref cpos, (byte)(Convert.ToInt16(order) & 0xFF));
                UrbetrackCodec.EncodeByte(ref commit, ref cpos, (byte)'R');
                send(commit, 3);
            }
Esempio n. 13
0
 public override void FinalEncode(ref byte[] buffer, ref int pos)
 {
     if (puntos.Count > 255)
     {
         throw new Exception("SA: Demasiados puntos en Posicion.");
     }
     UrbetrackCodec.EncodeByte(ref buffer, ref pos, Convert.ToByte(puntos.Count & 0xFF));
     foreach (var point in puntos)
     {
         UrbetrackCodec.EncodeGPSPoint(ref buffer, ref pos, point);
     }
 }
Esempio n. 14
0
 public override void FinalEncode(ref byte[] buffer, ref int pos)
 {
     if (Datos != null && Datos.GetLength(0) > 0)
     {
         UrbetrackCodec.EncodeShort(ref buffer, ref pos, Convert.ToInt16(Datos.GetLength(0)));
         UrbetrackCodec.EncodeBytes(ref buffer, ref pos, Datos);
     }
     else
     {
         UrbetrackCodec.EncodeShort(ref buffer, ref pos, 0);
     }
 }
Esempio n. 15
0
        public DataPage(byte[] buffer, int pos)
        {
            PDU this_pdu = this;

            Entrante = true;
            UrbetrackCodec.DecodeHeaders(buffer, ref this_pdu, ref pos);
            if (CL != 0x00)
            {
                throw new Exception("No conincide CL con el Tipo FOTA DATA.");
            }
            Pagina = UrbetrackCodec.DecodeShort(buffer, ref pos);
            Buffer = UrbetrackCodec.DecodeBytes(buffer, ref pos, 512);
        }
Esempio n. 16
0
            bool SendFile(Device d, string name, string src_file, string path)
            {
                // var path = Process.GetApplicationFolder("temp");
                var full_file = String.Format(@"{0}\{1}", path, src_file);
                var fota_file = String.Format(@"{0}\{1}.l4pnp", path, src_file);

                if (!File.Exists(full_file))
                {
                    Send("E");
                    //T.ERROR("DEVICE[{0}]/FOTA: el archivo '{1}' no existe o no hay permisos.", d.LogId, full_file);
                    return(false);
                }

                IO.PadFile(full_file, fota_file, 512, 0x00, true);

                using (var fs = File.OpenRead(fota_file))
                {
                    var filesize = (int)fs.Length;
                    if (filesize % 512 != 0)
                    {
                        //T.ERROR("DEVICE[{0}]/FOTA: el archivo '{1}' no existe o no hay permisos.", d.LogId, full_file);
                        Send("C");
                        return(false);
                    }
                    var filepages = filesize / 512;
                    var md5Hasher = MD5.Create();
                    var b         = md5Hasher.ComputeHash(fs);
                    if (b.GetLength(0) != 16)
                    {
                        throw new Exception("el hash md5 no retorna 16 bytes.");
                    }
                    var buffer = new byte[256];
                    var pos    = 0;
                    Send("D");
                    UrbetrackCodec.EncodeString(ref buffer, ref pos, name);
                    UrbetrackCodec.EncodeInteger(ref buffer, ref pos, filepages);
                    UrbetrackCodec.EncodeBytes(ref buffer, ref pos, b);
                    Send(buffer, pos);
                }

                using (var fs = File.OpenRead(fota_file))
                {
                    var b = new byte[512];
                    while (fs.Read(b, 0, 512) > 0)
                    {
                        Send(b, 512);
                    }
                }

                return(true);
            }
Esempio n. 17
0
 public SystemReport(byte[] buffer, int pos)
 {
     PDU this_pdu = this;
     Entrante = true;
     UrbetrackCodec.DecodeHeaders(buffer, ref this_pdu, ref pos);
     SystemResets = UrbetrackCodec.DecodeInteger(buffer, ref pos);
     WatchDogResets = UrbetrackCodec.DecodeInteger(buffer, ref pos);
     GPS_FixedSeconds = UrbetrackCodec.DecodeInteger(buffer, ref pos);
     GPS_BlindSeconds = UrbetrackCodec.DecodeInteger(buffer, ref pos);
     GPS_Resets = UrbetrackCodec.DecodeInteger(buffer, ref pos);
     NETWORK_UDP_ReceivedBytes = UrbetrackCodec.DecodeInteger(buffer, ref pos);
     NETWORK_UDP_SentBytes = UrbetrackCodec.DecodeInteger(buffer, ref pos);
     NETWORK_UDP_ReceivedDgrams = UrbetrackCodec.DecodeInteger(buffer, ref pos);
     NETWORK_UDP_SentDgrams = UrbetrackCodec.DecodeInteger(buffer, ref pos);
     NETWORK_Resets = UrbetrackCodec.DecodeInteger(buffer, ref pos);
     MODEM_Resets = UrbetrackCodec.DecodeInteger(buffer, ref pos);
 }
Esempio n. 18
0
 public override void FinalEncode(ref byte[] buffer, ref int pos)
 {
     UrbetrackCodec.EncodeShort(ref buffer, ref pos, IdAsignado);
     if (CL == 0x01)
     {
         UrbetrackCodec.EncodeByte(ref buffer, ref pos, MaxPDUSamples);
         UrbetrackCodec.EncodeByte(ref buffer, ref pos, FlushTimeout);
         UrbetrackCodec.EncodeShort(ref buffer, ref pos, RetrieveFlags);
     }
     if (CL == 0x02)
     {
         UrbetrackCodec.EncodeByte(ref buffer, ref pos, MaxPDUSamples);
         UrbetrackCodec.EncodeByte(ref buffer, ref pos, FlushTimeout);
         UrbetrackCodec.EncodeShort(ref buffer, ref pos, RetrieveFlags);
         UrbetrackCodec.EncodeInteger(ref buffer, ref pos, ResetToSample);
     }
 }
Esempio n. 19
0
        public Evento(byte[] buffer, int pos)
        {
            PDU this_pdu = this;

            Entrante = true;
            UrbetrackCodec.DecodeHeaders(buffer, ref this_pdu, ref pos);
            var d = Devices.I().FindById(this_pdu.IdDispositivo);

            Posicion     = UrbetrackCodec.DecodeGPSPointEx(buffer, ref pos, d);
            CodigoEvento = UrbetrackCodec.DecodeShort(buffer, ref pos);
            Datos        = UrbetrackCodec.DecodeInteger(buffer, ref pos);
            Payload      = null;
            switch (CL)
            {
            case 0xFF:
                PayloadSize   = 0;
                Extra         = 0;
                RiderRevision = -1;
                if (d.Type == DeviceTypes.Types.URBETRACK_v1_0 ||
                    d.Type == DeviceTypes.Types.URBETRACK_v0_8 ||
                    d.Type == DeviceTypes.Types.URBETRACK_v0_8n)
                {
                    RiderIdentifier = Encoding.ASCII.GetString(UrbetrackCodec.DecodeBytes(buffer, ref pos, 10));
                    if (String.IsNullOrEmpty(RiderIdentifier))
                    {
                        RiderIdentifier = "0000000000";
                    }
                }
                else
                {
                    RiderIdentifier = "0000000000";
                }
                break;

            case 0xFE:
                RiderIdentifier = Encoding.ASCII.GetString(UrbetrackCodec.DecodeBytes(buffer, ref pos, 10));
                RiderRevision   = UrbetrackCodec.DecodeInteger(buffer, ref pos);
                Extra           = UrbetrackCodec.DecodeInteger(buffer, ref pos);
                PayloadSize     = UrbetrackCodec.DecodeInteger(buffer, ref pos);
                if (PayloadSize > 0)
                {
                    Payload = UrbetrackCodec.DecodeBytes(buffer, ref pos, PayloadSize);
                }
                break;
            }
        }
Esempio n. 20
0
 public override void FinalEncode(ref byte[] buffer, ref int pos)
 {
     switch (CL)
     {
     case 0x00:     // SET/MODIFY
     case 0x01:     // DELETE
     case 0x02:     // DELETE ALL
     case 0x03:     // SET LOGISTIC STATE
     case 0x04:     // SHOW DRAFT
     case 0x05:     // SHOW CUSTOM
     case 0x06:     // DELIVER
     case 0x07:     // READ RECEIPT
         UrbetrackCodec.EncodeInteger(ref buffer, ref pos, Revision);
         UrbetrackCodec.EncodeByte(ref buffer, ref pos, Convert.ToByte(Code & 0xFF));
         UrbetrackCodec.EncodeByte(ref buffer, ref pos, Convert.ToByte((Source == 'M' ? 0x1 : 0) & (Destination == 'M' ? 0x02 : 0)));
         UrbetrackCodec.EncodeString(ref buffer, ref pos, Message);
         UrbetrackCodec.EncodeString(ref buffer, ref pos, ReplyFilter);
         UrbetrackCodec.EncodeInteger(ref buffer, ref pos, Session);
         break;
     }
 }
Esempio n. 21
0
        //public Queue<byte[]> GetQTreeCompressed(int frame_limit, int from_revision)

        public Queue <byte[]> GetQTreeCompressed(int frame_limit, int from_revision)
        {
            frame_limit--; // reservo el espacio para el 0xAC (cierre)
            var       result              = new Queue <byte[]>();
            var       dataset             = GetActionsQueue(from_revision);
            var       data_buffer         = new byte[frame_limit + 1];
            var       db_cursor           = 0;
            var       pagina              = 0;
            var       huffman_sectors     = 0;
            var       rle_sectors         = 0;
            var       uncompresed_sectors = 0;
            var       total_sectors       = 0;
            const int adds                  = 0;
            byte      operaciones           = 0;
            var       operaciones_en_pagina = 0;
            var       source_size           = 0;

            // preparo el espacio pata operaciones.
            UrbetrackCodec.EncodeByte(ref data_buffer, ref db_cursor, 0);
            var total_de_pasos = dataset.Count;
            var pasos          = 0;

            foreach (var action in dataset)
            {
                pasos++;
                var completado = pasos * 100.0 / total_de_pasos;
                if (pasos % 5000 == 0)
                {
                    STrace.Debug(GetType().FullName, String.Format("QTREE/GETQTREECOMPRESSED: {0:0.0}% completado.", completado));
                }
                if (operaciones_en_pagina > Hacker.QTree.OperacionesPorPagina)
                {
                    UrbetrackCodec.EncodeByte(ref data_buffer, ref db_cursor, 0xAC); // Cierre del bloque
                    source_size++;
                    operaciones++;
                    operaciones_en_pagina = 0;
                    pagina++;
                    //Marshall.User("QTREE: un OPERACIONXPAGINA cerro msg {0} de {1} bytes y {2} operaciones", pagina, db_cursor, operaciones);

                    var transient = new byte[db_cursor];
                    var dummy     = 0;
                    Array.Copy(data_buffer, transient, db_cursor);
                    // Actualizo las operaciones en el bloque.
                    UrbetrackCodec.EncodeByte(ref transient, ref dummy, operaciones);
                    result.Enqueue(transient);
                    db_cursor   = 0;
                    operaciones = 0;
                    // preparo el espacio pata operaciones.
                    UrbetrackCodec.EncodeByte(ref data_buffer, ref db_cursor, 0);
                }
                switch (action.Action)
                {
                case QtreeAction.Actions.START_UPDATE:
                    //Marshall.User(String.Format("QTREE:MSG={0}/START={1}/SIZE={2}: FULL FORMAT", pagina, db_cursor, 5));
                    source_size += 5;
                    operaciones_en_pagina++;
                    // 0xFF es Full Format.
                    UrbetrackCodec.EncodeByte(ref data_buffer, ref db_cursor, 0xFF);
                    // Patron de Seguridad.
                    UrbetrackCodec.EncodeInteger(ref data_buffer, ref db_cursor, action.Sector);
                    operaciones++;
                    break;

                case QtreeAction.Actions.SET_GR2_DEFAULTS:
                    if (db_cursor + 8 > frame_limit)
                    {
                        //Marshall.User(String.Format("QTREE:MSG={0}/START={1}/SIZE={2}: CLOSE PAGE", pagina, db_cursor, 1));
                        UrbetrackCodec.EncodeByte(ref data_buffer, ref db_cursor, 0xAC);     // Cierre del bloque
                        source_size++;
                        operaciones++;
                        operaciones_en_pagina = 0;
                        pagina++;
                        //Marshall.User("QTREE: un UPDATE_REVISION cerro msg {0} de {1} bytes y {2} operaciones", pagina, db_cursor, operaciones);
                        var transient = new byte[db_cursor];
                        var dummy     = 0;
                        Array.Copy(data_buffer, transient, db_cursor);
                        // Actualizo las operaciones en el bloque.
                        UrbetrackCodec.EncodeByte(ref transient, ref dummy, operaciones);
                        result.Enqueue(transient);
                        db_cursor   = 0;
                        operaciones = 0;
                        // preparo el espacio pata operaciones.
                        UrbetrackCodec.EncodeByte(ref data_buffer, ref db_cursor, 0);
                    }
                    // 0xDF es DeFaults
                    UrbetrackCodec.EncodeByte(ref data_buffer, ref db_cursor, 0xDF);
                    UrbetrackCodec.EncodeShort(ref data_buffer, ref db_cursor, action.FileLat);
                    UrbetrackCodec.EncodeShort(ref data_buffer, ref db_cursor, action.FileLon);
                    UrbetrackCodec.EncodeByte(ref data_buffer, ref db_cursor, (byte)action.Sector);
                    operaciones++;
                    break;

                case QtreeAction.Actions.SET_M2:
                {
                    byte repeated_byte = 0;
                    var  sector        = GetSector(action.Filename, action.Sector, ref repeated_byte);
                    var  file_class    = (byte)matrix[action.Filename][5000];
                    if (repeated_byte != 0 && repeated_byte == file_class)
                    {
                        STrace.Debug(GetType().FullName, String.Format("QTREE/FILE[{0}]: saltando sector x defecto {1} class={2}", action.Filename,
                                                                       action.Sector, file_class));
                        continue;
                    }
                    source_size += 512;
                    var page_buffer = new byte[512];
                    var page_cursor = 0;

                    UrbetrackCodec.EncodeByte(ref page_buffer, ref page_cursor, 0x01);
                    UrbetrackCodec.EncodeShort(ref page_buffer, ref page_cursor, action.FileLat);
                    UrbetrackCodec.EncodeShort(ref page_buffer, ref page_cursor, action.FileLon);
                    UrbetrackCodec.EncodeInteger(ref page_buffer, ref page_cursor, action.Sector);


                    var    huff           = new Huffman();
                    var    result_huffman = huff.Compress(sector, 0, 512);
                    var    rle            = new RLE();
                    var    result_rle     = rle.Compress(sector, 0, 512);
                    byte[] compressed_data;

                    if (sector.GetLength(0) <= result_huffman.GetLength(0) && sector.GetLength(0) <= result_rle.GetLength(0))
                    {
                        uncompresed_sectors++;
                        compressed_data = sector;
                        UrbetrackCodec.EncodeShort(ref page_buffer, ref page_cursor, (short)compressed_data.GetLength(0));
                        UrbetrackCodec.EncodeByte(ref page_buffer, ref page_cursor, 0x00);         // indicador de algoritmo (Sin compresion)
                    }
                    else
                    if (result_huffman.GetLength(0) <= sector.GetLength(0) && result_huffman.GetLength(0) <= result_rle.GetLength(0))
                    {
                        huffman_sectors++;
                        compressed_data = result_huffman;
                        UrbetrackCodec.EncodeShort(ref page_buffer, ref page_cursor, (short)compressed_data.GetLength(0));
                        UrbetrackCodec.EncodeByte(ref page_buffer, ref page_cursor, 0x02);             // indicador de algoritmo (Huffman)
                    }
                    else
                    if (result_rle.GetLength(0) <= result_huffman.GetLength(0) && result_rle.GetLength(0) <= sector.GetLength(0))
                    {
                        rle_sectors++;
                        compressed_data = result_rle;
                        UrbetrackCodec.EncodeShort(ref page_buffer, ref page_cursor, (short)compressed_data.GetLength(0));
                        UrbetrackCodec.EncodeByte(ref page_buffer, ref page_cursor, 0x01);                 // indicador de algoritmo (RLE)
                    }
                    else
                    {
                        STrace.Debug(GetType().FullName, "QTREE: imposible elijir algoritmo.");
                        return(null);
                    }
                    // agrego el buffer de datos...
                    UrbetrackCodec.EncodeBytes(ref page_buffer, ref page_cursor, compressed_data);
                    // valido si es posible meter el buffer en una sola pagina al menos.
                    if (page_cursor > frame_limit)
                    {
                        STrace.Debug(GetType().FullName, "QTREE: el resultado de una pagina no entra en el buffer completo.");
                        STrace.Debug(GetType().FullName, "QTREE: el resultado de una pagina no entra en el buffer completo.");
                        return(null);
                    }
                    // ahora tengo que validar si me entra en esta pagina, o la cierro y empiezo otra.
                    if (db_cursor + page_cursor > frame_limit)
                    {
                        //Marshall.User(String.Format("QTREE:MSG={0}/START={1}/SIZE={2}: CLOSE PAGE", pagina, db_cursor, 1));
                        UrbetrackCodec.EncodeByte(ref data_buffer, ref db_cursor, 0xAC);         // Cierre del bloque
                        source_size++;
                        operaciones++;
                        operaciones_en_pagina = 0;
                        pagina++;
                        //Marshall.User("QTREE: un SET_M2 cerro msg {0} de {1} bytes y {2} operaciones", pagina, db_cursor, operaciones);

                        var transient = new byte[db_cursor];
                        var dummy     = 0;
                        Array.Copy(data_buffer, transient, db_cursor);
                        // Actualizo las operaciones en el bloque.
                        UrbetrackCodec.EncodeByte(ref transient, ref dummy, operaciones);
                        result.Enqueue(transient);
                        db_cursor   = 0;
                        operaciones = 0;
                        // preparo el espacio pata operaciones.
                        UrbetrackCodec.EncodeByte(ref data_buffer, ref db_cursor, 0);
                    }
                    Array.Copy(page_buffer, 0, data_buffer, db_cursor, page_cursor);
                    //Marshall.User(String.Format("QTREE:MSG={0}/START={1}/SIZE={2}: SET {3};{4} PAGE:{5}", pagina, db_cursor, page_cursor, action.FileLat, action.FileLon, action.Sector));
                    db_cursor += page_cursor;
                    total_sectors++;
                    operaciones++;
                    operaciones_en_pagina++;
                }
                break;

                case QtreeAction.Actions.UPDATE_REVISION:
                    if (db_cursor + 5 > frame_limit)
                    {
                        //Marshall.User(String.Format("QTREE:MSG={0}/START={1}/SIZE={2}: CLOSE PAGE", pagina, db_cursor, 1));
                        UrbetrackCodec.EncodeByte(ref data_buffer, ref db_cursor, 0xAC);     // Cierre del bloque
                        source_size++;
                        operaciones++;
                        operaciones_en_pagina = 0;
                        pagina++;
                        //Marshall.User("QTREE: un UPDATE_REVISION cerro msg {0} de {1} bytes y {2} operaciones", pagina, db_cursor, operaciones);
                        var transient = new byte[db_cursor];
                        var dummy     = 0;
                        Array.Copy(data_buffer, transient, db_cursor);
                        // Actualizo las operaciones en el bloque.
                        UrbetrackCodec.EncodeByte(ref transient, ref dummy, operaciones);
                        result.Enqueue(transient);
                        db_cursor   = 0;
                        operaciones = 0;
                        // preparo el espacio pata operaciones.
                        UrbetrackCodec.EncodeByte(ref data_buffer, ref db_cursor, 0);
                    }
                    //Marshall.User(String.Format("QTREE:MSG={0}/START={1}/SIZE={2}: UPDATE REVISION {3}", pagina, db_cursor, 5, action.Sector));
                    UrbetrackCodec.EncodeByte(ref data_buffer, ref db_cursor, 0x02);
                    UrbetrackCodec.EncodeInteger(ref data_buffer, ref db_cursor, action.Sector);
                    source_size += 5;
                    operaciones++;
                    operaciones_en_pagina++;
                    break;
                }
            }

            {
                //Marshall.User(String.Format("QTREE:MSG={0}/START={1}/SIZE={2}: UPDATE FINISH", pagina, db_cursor, 1));
                UrbetrackCodec.EncodeByte(ref data_buffer, ref db_cursor, 0xDC); // Fin de la actualizacion.
                var transient = new byte[db_cursor];
                var dummy     = 0;
                operaciones++;
                source_size += 1;
                //Marshall.User("QTREE: cerro la ultima pagina {0} de {1} bytes y {2} operaciones", pagina, db_cursor, operaciones);
                Array.Copy(data_buffer, transient, db_cursor);
                // Actualizo las operaciones en el bloque.
                UrbetrackCodec.EncodeByte(ref transient, ref dummy, operaciones);
                result.Enqueue(transient);
            }
            if (pagina == 0)
            {
                STrace.Debug(GetType().FullName, String.Format("QRTEE NO SE REQUIERE UPDATE revision {0}", from_revision));
                return(null);
            }
            var suma_total = result.Sum(tmp => tmp.GetLength(0));

            STrace.Debug(GetType().FullName, String.Format("QRTEE COMPRIMIDO entre revisiones {0} y {1}", from_revision, Revision));
            STrace.Debug(GetType().FullName, "===================================================================================");
            STrace.Debug(GetType().FullName, String.Format("  Tamaño Origninal:   {0} bytes en {1} paginas.", source_size, total_sectors));
            STrace.Debug(GetType().FullName, String.Format("  Tamaño Final:       {0} bytes en {1} paginas. ({2} bytes pormedio por pagina)", suma_total, pagina, (pagina > 0 ? suma_total / pagina : 0)));
            STrace.Debug(GetType().FullName, String.Format("  Tasa de Compresion: {0}%", suma_total * 100 / source_size));
            STrace.Debug(GetType().FullName, String.Format("  Paginas RAW:        {0} ({1}%)", uncompresed_sectors, uncompresed_sectors * 100 / total_sectors));
            STrace.Debug(GetType().FullName, String.Format("  Paginas RLE:        {0} ({1}%)", rle_sectors, rle_sectors * 100 / total_sectors));
            STrace.Debug(GetType().FullName, String.Format("  Paginas HUFFMAN:    {0} ({1}%)", huffman_sectors, huffman_sectors * 100 / total_sectors));
            STrace.Debug(GetType().FullName, String.Format("  GR2 Agreagados:     {0}", adds));

            return(result);
        }
Esempio n. 22
0
 public override void FinalEncode(ref byte[] buffer, ref int pos)
 {
     UrbetrackCodec.EncodeString(ref buffer, ref pos, IdTarjeta);
     UrbetrackCodec.EncodeGPSPoint(ref buffer, ref pos, Posicion);
 }
Esempio n. 23
0
 public override void FinalEncode(ref byte[] buffer, ref int pos)
 {
     UrbetrackCodec.EncodeString(ref buffer, ref pos, signature);
 }
Esempio n. 24
0
 public override void FinalEncode(ref byte[] buffer, ref int pos)
 {
     UrbetrackCodec.EncodeInteger(ref buffer, ref pos, Sensor);
     UrbetrackCodec.EncodeDateTime(ref buffer, ref pos, StartTime);
     UrbetrackCodec.EncodeDateTime(ref buffer, ref pos, EndTime);
 }
Esempio n. 25
0
        public Posicion(byte[] buffer, int pos)
        {
            PDU this_pdu = this;

            Entrante = true;
            UrbetrackCodec.DecodeHeaders(buffer, ref this_pdu, ref pos);
            puntos.Clear();
            switch (CL)
            {
            case 0x00:
                try
                {
                    var point = UrbetrackCodec.DecodeGPSPoint(buffer, ref pos);
                    if (point != null)
                    {
                        puntos.Add(point);
                    }
                } catch (Exception e)
                {
                    STrace.Exception(GetType().FullName, e);
                }
                break;

            case 0x01:
            {
                var items = UrbetrackCodec.DecodeByte(buffer, ref pos);
                Posiciones = items;
                while (items-- > 0)
                {
                    try
                    {
                        var point = UrbetrackCodec.DecodeGPSPoint(buffer, ref pos);
                        if (point != null)
                        {
                            puntos.Add(point);
                        }
                    } catch (Exception e)
                    {
                        STrace.Exception(GetType().FullName, e);
                    }
                }
            }
            break;

            case 0x02:
            {
                var items = UrbetrackCodec.DecodeByte(buffer, ref pos);
                var d     = Devices.I().FindById(this_pdu.IdDispositivo);
                while (items-- > 0)
                {
                    try
                    {
                        var point = UrbetrackCodec.DecodeGPSPointEx(buffer, ref pos, d);
                        if (point != null)
                        {
                            puntos.Add(point);
                        }
                    }
                    catch (Exception e)
                    {
                        STrace.Exception(GetType().FullName, e);
                    }
                }
            }
            break;

            default:
                throw new Exception("DAC, Subtipo de mensaje de posicion desconocido.");
            }
        }
Esempio n. 26
0
        public static bool SendMessage(IPEndPoint endPoint, short idDispositivo, byte op, byte[] mensaje, string filename)
        {
            var filesize = mensaje.GetLength(0);

            try
            {
                STrace.Debug(typeof(FileClient).FullName, String.Format("FileClient[{0}]: === inciando cliente ===", endPoint));
                var socket = new TcpClient();
                socket.Connect(endPoint);
                STrace.Debug(typeof(FileClient).FullName, String.Format("FileClient[{0}]: Se ha conectado el socket TCP/IP", endPoint));
                var buff = new byte[71];
                // ponemos a cero.
                for (var i = 0; i < 71; ++i)
                {
                    buff[i] = 0x00;
                }
                var pos = 0;
                UrbetrackCodec.EncodeShort(ref buff, ref pos, idDispositivo);
                UrbetrackCodec.EncodeByte(ref buff, ref pos, op);
                UrbetrackCodec.EncodeInteger(ref buff, ref pos, filesize);
                var b = Encoding.ASCII.GetBytes(filename);
                Array.Copy(b, 0, buff, pos, b.GetLength(0));
                socket.Client.Send(buff);
                STrace.Debug(typeof(FileClient).FullName, String.Format("FileClient[{0}]: Cabeceras enviadas", endPoint));
                var total = 0;
                var r     = socket.Client.Send(mensaje, mensaje.GetLength(0), SocketFlags.None);
                total += r;
                STrace.Debug(typeof(FileClient).FullName, String.Format("FileClient[{0}]: Cabeceras enviadas", endPoint));
                STrace.Debug(typeof(FileClient).FullName, String.Format("FileClient[{0}]: {1} byte enviados.", endPoint, total));
                var ack = new byte[1];
                ack[0] = Convert.ToByte('N');
                try
                {
                    if (socket.Client.Receive(ack, 0, 1, SocketFlags.None) == 1)
                    {
                        try
                        {
                            socket.Client.Shutdown(SocketShutdown.Send);
                            socket.Client.Close();
                        }
                        catch (Exception)
                        {
                        }

                        if (ack[0] == 'A')
                        {
                            STrace.Debug(typeof(FileClient).FullName, String.Format("FileClient[{0}]: ACK Recibido", endPoint));
                            return(true);
                        }
                        STrace.Debug(typeof(FileClient).FullName, String.Format("FileClient[{0}]: NACK Recibido", endPoint));
                    }
                    return(false);
                }
                catch (Exception e)
                {
                    STrace.Exception(typeof(FileClient).FullName, e, "FileClient.BeginPush WAIT FOR ACK/NACK PHASE");
                }
            }
            catch (Exception e)
            {
                STrace.Debug(typeof(FileClient).FullName, String.Format("Exception en FileClient: txt={0}", e.Message));
            }
            return(false);
        }
Esempio n. 27
0
        void WriterProc()
        {
            var remote_result = false;

            try
            {
                STrace.Debug(typeof(FileClient).FullName, String.Format("FileClient[{0}]: Thread de escritura iniciada.", device.LogId));
                socket = new TcpClient();
                socket.Connect(endPoint);
                STrace.Debug(typeof(FileClient).FullName, String.Format("FileClient[{0}]: Thread de escritura conectada.", device.LogId));
                var buff = new byte[71];
                // ponemos a cero.
                for (var i = 0; i < 71; ++i)
                {
                    buff[i] = 0x00;
                }
                var pos = 0;
                UrbetrackCodec.EncodeShort(ref buff, ref pos, device.Id_short);
                UrbetrackCodec.EncodeByte(ref buff, ref pos, op);
                UrbetrackCodec.EncodeInteger(ref buff, ref pos, filesize);
                var b = Encoding.ASCII.GetBytes(filename);
                Array.Copy(b, 0, buff, pos, b.GetLength(0));
                socket.Client.Send(buff);
                STrace.Debug(typeof(FileClient).FullName, String.Format("FileClient[{0}]: Cabeceras Enviadas.", device.LogId));
                var total = 0;
                var r     = socket.Client.Send(mensaje, mensaje.GetLength(0), SocketFlags.None);
                total += r;
                STrace.Debug(typeof(FileClient).FullName, String.Format("FileClient[{2}]: Termino el envio de archivo de {0} bytes. total={1}", total, total + 71, device.LogId));
                var ack = new byte[1];
                ack[0] = Convert.ToByte('N');
                try
                {
                    if (socket.Client.Receive(ack, 0, 1, SocketFlags.None) == 1)
                    {
                        try
                        {
                            socket.Client.Shutdown(SocketShutdown.Send);
                            socket.Client.Close();
                        }
                        catch (Exception)
                        {
                        }
                        if (ack[0] == 'A')
                        {
                            STrace.Debug(typeof(FileClient).FullName, String.Format("FileClient[{0}]: ACK Recibido", endPoint));
                            remote_result = true;
                        }
                        else
                        {
                            STrace.Debug(typeof(FileClient).FullName, String.Format("FileClient[{0}]: NACK Recibido", endPoint));
                        }
                    }
                }
                catch (Exception e)
                {
                    STrace.Exception(typeof(FileClient).FullName, e, "FileClient.BeginPush WAIT FOR ACK/NACK PHASE");
                }
                //socket.Client.Shutdown(SocketShutdown.Both);
                //socket.Client.Close();
            } catch (Exception e)
            {
                STrace.Exception(typeof(FileClient).FullName, e, String.Format("FileClient[{0}]", device.LogId));
            }
            finally
            {
                if (SendMessageResult != null)
                {
                    SendMessageResult(device.Id_short, filename, remote_result);
                }
                else
                {
                    throw new ApplicationException(String.Format("FileClient[{0}]: Finalizo operacion desconocida.", device.LogId));
                }
            }
        }
Esempio n. 28
0
 public override void FinalEncode(ref byte[] buffer, ref int pos)
 {
     UrbetrackCodec.EncodeInteger(ref buffer, ref pos, Revision);
     UrbetrackCodec.EncodeString(ref buffer, ref pos, Parameter);
     UrbetrackCodec.EncodeString(ref buffer, ref pos, Value);
 }
Esempio n. 29
0
        internal void PDURecibida(XBeeAPIPort uart, XBeePDU pdu)
        {
            STrace.Debug(typeof(XBeeRadioLinkProtocol).FullName, String.Format("XBEE-PDU: code={0:X}", pdu.Data[0]));
            switch (pdu.Data[0])
            {
            case (byte)FrameType.STATUS_REPORT:
            {
                var pos  = 1;
                var node = XBeeAPIPort.FindNode(pdu.Address);
                if (node == null)
                {
                    var addr = String.Format("{0:X}", pdu.Address);
                    var nd   = Devices.I().FindByXbeeAddr(addr);
                    if (nd == null)
                    {
                        return;
                    }
                    var nn = new XBeeNode
                    {
                        Address = pdu.Address,
                        Id      = String.Format("D:{0}", nd.Imei)
                    };
                    nn.Trace("NODO DETECTADO EN CALIENTE:");
                    node = nn;
                }
                XBeeAPIPort.UpdateNode(node);
                var d = Devices.I().FindByImei(node.IMEI());
                if (d == null)
                {
                    STrace.Debug(typeof(XBeeRadioLinkProtocol).FullName, String.Format("XBEERLP: device imei={0} no encontrado.", node.IMEI()));
                    return;
                }

                d.XBeeSession.Report.RadioLinkState     = (XBeeReport.DeviceXbeeMachineStates)UrbetrackCodec.DecodeByte(pdu.Data, ref pos);
                d.XBeeSession.Report.CommCoreState      = (XBeeReport.DeviceSessionMachineStates)UrbetrackCodec.DecodeByte(pdu.Data, ref pos);
                d.XBeeSession.Report.NetworkConnections = UrbetrackCodec.DecodeByte(pdu.Data, ref pos);
                d.XBeeSession.Report.QueryState         = (XBeeReport.QueryStates)UrbetrackCodec.DecodeByte(pdu.Data, ref pos);

                d.XBeeSession.Report.QueryStartSample = UrbetrackCodec.DecodeInteger(pdu.Data, ref pos);
                d.XBeeSession.Report.QueryEndSample   = UrbetrackCodec.DecodeInteger(pdu.Data, ref pos);
                d.XBeeSession.Report.CursorSample     = UrbetrackCodec.DecodeInteger(pdu.Data, ref pos);
                d.XBeeSession.Report.OldestSample     = UrbetrackCodec.DecodeInteger(pdu.Data, ref pos);

                d.XBeeSession.Report.OldestTrackingSample = UrbetrackCodec.DecodeInteger(pdu.Data, ref pos);
                d.XBeeSession.Report.Processed            = UrbetrackCodec.DecodeInteger(pdu.Data, ref pos);
                d.XBeeSession.Report.Empty    = UrbetrackCodec.DecodeInteger(pdu.Data, ref pos);
                d.XBeeSession.Report.Tracking = UrbetrackCodec.DecodeInteger(pdu.Data, ref pos);

                d.XBeeSession.Report.Detailed    = UrbetrackCodec.DecodeInteger(pdu.Data, ref pos);
                d.XBeeSession.Report.Sent        = UrbetrackCodec.DecodeInteger(pdu.Data, ref pos);
                d.XBeeSession.Report.SessionSent = UrbetrackCodec.DecodeInteger(pdu.Data, ref pos);
                d.XBeeSession.Report.Pendings    = UrbetrackCodec.DecodeInteger(pdu.Data, ref pos);

                d.Destino.XBee = new XBeeAddress {
                    Addr = pdu.Address
                };
                STrace.Debug(typeof(XBeeRadioLinkProtocol).FullName, String.Format("XBEERLP: device imei={0} actualizando. {1}/{2}/{3}", node.IMEI(), d.XBeeSession.Report.RadioLinkState, d.XBeeSession.Report.NetworkConnections, d.XBeeSession.Report.QueryState));
                TransporteXBEE.DoReceiveReport(d);
                return;
            }

            case (byte)FrameType.USER_PART:
            {
                var data_size       = pdu.Data.GetLength(0) - 1;
                var instance_buffer = new byte[data_size];
                Array.Copy(pdu.Data, 1, instance_buffer, 0, data_size);
                var node = XBeeAPIPort.FindNode(pdu.Address);
                if (node == null)
                {
                    STrace.Debug(typeof(XBeeRadioLinkProtocol).FullName, String.Format("XBEERLP IGNORANDO NODO {0}", pdu.Address));
                    return;
                }
                XBeeAPIPort.UpdateNode(node);
                var instance_addr = new XBeeAddress {
                    Addr = pdu.Address
                };
                TransporteXBEE.Receive(instance_buffer, data_size, instance_addr);
                return;
            }

            case (byte)FrameType.DISABLE_LINK_RESPONSE:
            {
                var node = XBeeAPIPort.FindNode(pdu.Address);
                if (node == null)
                {
                    return;
                }
                XBeeAPIPort.UpdateNode(node);
                var d = Devices.I().FindByImei(node.IMEI());
                d.XBeeSession.GoesInactive();
                TransporteXBEE.DoReceiveReport(d);
                RemoveTransaction(d);
                break;
            }

            case (byte)FrameType.ENABLE_LINK_RESPONSE:
            {
                var node = XBeeAPIPort.FindNode(pdu.Address);
                if (node == null)
                {
                    return;
                }
                XBeeAPIPort.UpdateNode(node);
                var d = Devices.I().FindByImei(node.IMEI());
                if (!FoundTransaction(d))
                {
                    break;
                }
                d.XBeeSession.GoesActive();
                TransporteXBEE.DoReceiveReport(d);
                RemoveTransaction(d);
                break;
            }

            default:
                STrace.Debug(typeof(XBeeRadioLinkProtocol).FullName, "@@@");
                break;
            }
            return;
        }
Esempio n. 30
0
 public override void FinalEncode(ref byte[] buffer, ref int pos)
 {
     UrbetrackCodec.EncodeInteger(ref buffer, ref pos, Order);
     UrbetrackCodec.EncodeString(ref buffer, ref pos, CommandLine);
 }