Exemplo n.º 1
0
        private static GPSPoint ParseGpsPoint(String[] s, int offset)
        {
            var gpsAccuracy = Convert.ToInt32(s[offset]);             //(hdop)

            if (gpsAccuracy == 0)
            {
                return(null);
            }

            return(GPSPoint.Factory(
                       DateTimeUtils.SafeParseFormat(s[offset + 6], "yyyyMMddHHmmss"),
                       Convert.ToSingle(s[offset + 5], CultureInfo.InvariantCulture),
                       Convert.ToSingle(s[offset + 4], CultureInfo.InvariantCulture),
                       Convert.ToSingle(s[offset + 1], CultureInfo.InvariantCulture),
                       0,
                       Convert.ToSingle(s[offset + 3], CultureInfo.InvariantCulture),
                       gpsAccuracy));

            //var GPSaccuracy = Convert.ToByte(s[offset]); //(hdop)
            //var Speed = new Speed(Convert.ToSingle(s[offset + 1], CultureInfo.InvariantCulture));
            //var Azimuth = Convert.ToInt32(s[offset + 2], CultureInfo.InvariantCulture);
            //var Altitude = new Altitude(Convert.ToSingle(s[offset + 3], CultureInfo.InvariantCulture));
            //var Longitude = Convert.ToSingle(s[offset + 4], CultureInfo.InvariantCulture);
            //var Latitude = Convert.ToSingle(s[offset + 5], CultureInfo.InvariantCulture);
            //var dt = FechasUtm.SafeParseFormat(s[offset + 6], "yyyyMMddHHmmss");
            //var MCC = s[offset + 7]; //Mobile country code of the service cell, it is 3 digits in length and ranges from 000 to 999.
            //var MNC = s[offset + 8]; //Mobile network code of the service cell, it is 3 digits in length and ranges from 000 to 999.
            //var LAC = s[offset + 9]; //Location area code in hex format of the service cell.
            //var CELL ID = s[offset + 10]; //CELL ID in hex format of the service cell.
            //reserved
        }
Exemplo n.º 2
0
        private static GPSPoint ParseGpsPoint(String[] s)
        {
            if (String.IsNullOrEmpty(s[16]))
            {
                return(null);
            }

            var fechaHora = DateTimeUtils.SafeParseFormat(s[16], "yyyyMMddHHmmss");
            var latitude  = Convert.ToSingle(s[15], CultureInfo.InvariantCulture);
            var longitude = Convert.ToSingle(s[14], CultureInfo.InvariantCulture);
            var speed     = Convert.ToSingle(s[11], CultureInfo.InvariantCulture);
            var azimuth   = Convert.ToSingle(s[12], CultureInfo.InvariantCulture);
            var hdop      = Convert.ToSingle(s[10], CultureInfo.InvariantCulture);
            var altitude  = Convert.ToSingle(s[13], CultureInfo.InvariantCulture);

            var pos = GPSPoint.Factory(fechaHora, latitude, longitude, speed, azimuth, altitude, hdop);

            return(pos);

            //var Speed = new Speed(Convert.ToSingle(s[11], CultureInfo.InvariantCulture));
            //var Longitude = Convert.ToSingle(s[14], CultureInfo.InvariantCulture);
            //var Latitude = Convert.ToSingle(s[15], CultureInfo.InvariantCulture);
            //var dt = FechasUtm.SafeParseFormat(s[16], "yyyyMMddHHmmss");
            //var MCC = s[17]; //Mobile country code of the service cell
            //var MNC = s[18]; //Mobile network code of the service cell.
            //var LAC = s[19]; //Location area code in hex format of the service cell.
            //var CELL ID = s[20]; //CELL ID in hex format of the service cell.
            //var battery_percentage = s[21];
        }
Exemplo n.º 3
0
        public static GPSPoint ParsearPosicionCorta(String src)
        {
            var partes = src.Split(',');
            var date   = partes[0];

            if (partes.GetLength(0) < 3)
            {
                return(null);
            }

            DateTime t;

            try
            {
                t = new DateTime(Convert.ToInt32(date.Substring(0, 2)) + 2000,
                                 Convert.ToInt32(date.Substring(4, 2)),
                                 Convert.ToInt32(date.Substring(2, 2)),
                                 Convert.ToInt32(date.Substring(6, 2)),
                                 Convert.ToInt32(date.Substring(8, 2)),
                                 Convert.ToInt32(date.Substring(10, 2)), DateTimeKind.Utc);
            }
            catch (FormatException)
            {
                return(null);
            }

            return(GPSPoint.Factory(t, GPSPoint.ResampleAxis(partes[1]), GPSPoint.ResampleAxis(partes[2])));
        }
Exemplo n.º 4
0
        private static GPSPoint ParsearPosicion(String src)
        {
            var partes = src.Split(",".ToCharArray());
            var date   = partes[0];

            if ((date.Length < 12) || (partes.GetLength(0) < 5))
            {
                return(null);
            }
            DateTime t;

            try
            {
                t = new DateTime(Convert.ToInt32(date.Substring(0, 2)) + 2000,
                                 Convert.ToInt32(date.Substring(4, 2)),
                                 Convert.ToInt32(date.Substring(2, 2)),
                                 Convert.ToInt32(date.Substring(6, 2)),
                                 Convert.ToInt32(date.Substring(8, 2)),
                                 Convert.ToInt32(date.Substring(10, 2)), DateTimeKind.Utc);
            }
            catch (FormatException)
            {
                return(null);
            }
            return(GPSPoint.Factory(
                       t,
                       GPSPoint.ResampleAxis(partes[1]),
                       GPSPoint.ResampleAxis(partes[2]),
                       Speed.KnotToKm(Convert.ToSingle(String.IsNullOrEmpty(partes[3]) ? "0" : partes[3], CultureInfo.InvariantCulture)),
                       Convert.ToSingle(String.IsNullOrEmpty(partes[4]) ? "0" : partes[4], CultureInfo.InvariantCulture),
                       0,
                       0));
        }
Exemplo n.º 5
0
        public static GPSPoint Parse(String[] data)
        {
            //check edad
            if ((data[3].Length > 20) && (Convert.ToInt32(data[3].Substring(20, 4)) > 300))
            {
                return(null);
            }

            DateTime time;

            try
            {
                time = DateTimeUtils.SafeParseFormatWithTraxFix(data[1], "ddMMyyHHmmss");
            }
            catch (Exception)
            {
                var ss = new StringBuilder();
                foreach (var s in data)
                {
                    ss.Append(s);
                }
                STrace.Debug(typeof(Posicion).FullName, String.Format(@"DateTime invalido ""{0}""", ss));
                time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            }
            var lat  = Convert.ToSingle(data[3].Substring(0, 8)) * (float)0.00001;
            var lon  = Convert.ToSingle(data[3].Substring(8, 9)) * (float)0.00001;
            var dir  = Convert.ToSingle(data[3].Substring(17, 3));
            var hdop = Convert.ToByte(Convert.ToSingle(data[4].Substring(0, 3)) / 10);
            var vel  = Speed.KnotToKm(Convert.ToSingle(data[5]));

            //STrace.Trace(GetType().FullName,"TraxDecodePoint {0};{1};vel={2};dir={3};hdop={4};{5:u}", lat, lon, vel, dir, hdop, time);

            return(GPSPoint.Factory(time, lat, lon, vel, dir, 0, hdop));
        }
Exemplo n.º 6
0
 private static IMessage ParseGpsHistoryFixRecords(int id, ulong mid, String[] s)
 {
     return(GPSPoint.Factory(
                DateTimeUtils.SafeParseFormat(s[9], "yyyyMMddHHmmss"),
                Convert.ToSingle(s[4], CultureInfo.InvariantCulture),
                Convert.ToSingle(s[5], CultureInfo.InvariantCulture),
                Convert.ToSingle(s[7], CultureInfo.InvariantCulture))
            .ToPosition(id, mid));
 }
Exemplo n.º 7
0
        private static IMessage FactoryPositionOrEvent(Parser dev, String[] data, ulong msgId)
        {
            IMessage res;
            var      extra = (data.LastOrDefault(s => s.StartsWith("rt")) != null) ? ",t=" + DateTime.UtcNow.ToUnixTimeStamp() : "";

            var date = DateTimeUtils.SafeParseFormat(data[2], "ddMMyyHHmmss");

            var pos = GPSPoint.Factory(
                date,
                Convert.ToSingle(data[3], CultureInfo.InvariantCulture),
                Convert.ToSingle(data[4], CultureInfo.InvariantCulture),
                Convert.ToSingle(data[5], CultureInfo.InvariantCulture),
                Convert.ToSingle(data[6], CultureInfo.InvariantCulture),
                0,                                                        // Altitude
                0,                                                        // Hdop
                GetProvider(data[7]),                                     // SourceProvider
                Convert.ToSingle(data[8], CultureInfo.InvariantCulture)); // HorizontalAccuracy

            // si la lat es cero, no hay posicion.
            if (pos.Lat == 0.0)
            {
                pos = null;
            }

            var ev = data.SingleOrDefault(s => s.StartsWith("e="));

            if (ev != null)
            {
                var codigo = (MessageIdentifier)Convert.ToInt32(ev.Substring(2));
                if (codigo == MessageIdentifier.DeviceTurnedOn)
                {
                    date = DateTime.UtcNow;
                }
                var          xd    = data.SingleOrDefault(s => s.StartsWith("x="));
                List <Int64> xdata = null;
                if (xd != null)
                {
                    xdata = new List <Int64> {
                        Convert.ToInt32(xd.Substring(2))
                    };
                    var xd2 = data.SingleOrDefault(s => s.StartsWith("x2="));
                    if (xd2 != null)
                    {
                        xdata.Add(Convert.ToInt32(xd2.Substring(3)));
                    }
                }
                res = codigo.FactoryEvent(dev.Id, msgId, pos, date, null, xdata);
            }
            else
            {
                res = pos.ToPosition(dev.Id, msgId);
            }

            return(res.AddStringToSend(Factory <String>(msgId, dev, "AP,0{0}", extra)));
        }
Exemplo n.º 8
0
        public static GPSPoint ParseCompact(String data, bool hdopF)
        {
            var time = DateTimeUtils.SafeParseFormatWithTraxFix(data.Substring(0, 12), "ddMMyyHHmmss");
            var lat  = Convert.ToSingle(data.Substring(12, 8)) * (float)0.00001;
            var lon  = Convert.ToSingle(data.Substring(20, 9)) * (float)0.00001;
            var dir  = Convert.ToSingle(data.Substring(29, 3));
            var vel  = Convert.ToSingle(data.Substring(32, 3));
            var hdop = hdopF ? Convert.ToByte(Convert.ToSingle(data.Substring(35, 3)) / 10) : (byte)0;

            return(GPSPoint.Factory(time, lat, lon, vel, dir, 0, hdop));
        }
Exemplo n.º 9
0
        public static GPSPoint ParseOld(String[] data)
        {
            var time = DateTimeUtils.SafeParseFormatWithTraxFix(data[1], "ddMMyyHHmmss");
            var lat  = Convert.ToSingle(data[4]) * (float)0.00001;
            var lon  = Convert.ToSingle(data[5]) * (float)0.00001;
            var dir  = Convert.ToSingle(data[6]);
            var hdop = Convert.ToByte(Math.Round(Convert.ToSingle(data[7]) / 10));
            var vel  = Speed.KnotToKm(Convert.ToSingle(data[9]));

            //STrace.Trace(GetType().FullName,"TraxDecodePoint {0};{1};{2};{3};{4:u}", lat, lon, vel, dir, time);

            return(GPSPoint.Factory(time, lat, lon, vel, dir, 0, hdop));
        }
Exemplo n.º 10
0
        public static GPSPoint Parse(byte[] data)
        {
            //var time = Utils.FromUnixTimeStamp(BitConverter.ToUInt32(data, 0));
            var time = FromFulmarTime(data, 0);

            var lat = Convert.ToSingle(BitConverter_BigEndian.ToInt32(data, 4)) / 100000;
            var lon = Convert.ToSingle(BitConverter_BigEndian.ToInt32(data, 8)) / 100000;

            //var edad = data[12];
            var vel = Convert.ToSingle(data[13]);
            //var velPico = data[14];
            var dir = Convert.ToSingle(data[15]) * 2;             //puaj, viene dividida por 2 para q entre en un byte

            return(GPSPoint.Factory(time, lat, lon, vel, dir, 0, 0));
        }
Exemplo n.º 11
0
        public static IMessage Factory(String buffer, int node)
        {
            var partes = buffer.Split(',');

            if (partes[3] != "A")
            {
                return(null);
            }
            var time      = DateTimeUtils.SafeParseFormat(partes[10] + partes[2].Substring(0, 6), "ddMMyyHHmmss");
            var latitud   = GPSPoint.ResampleAxis(partes[4]) * ((partes[5] == "N") ? 1 : -1);
            var longitud  = GPSPoint.ResampleAxis(partes[6]) * ((partes[7] == "E") ? 1 : -1);
            var velocidad = Speed.KnotToKm(Convert.ToSingle(partes[8], CultureInfo.InvariantCulture));
            var direccion = Convert.ToSingle(partes[9]);

            return(GPSPoint.Factory(time, latitud, longitud, velocidad, direccion, 0, 0).ToPosition(node, 0));
        }
Exemplo n.º 12
0
        public static IMessage GetPosition(byte[] request)
        {
            var did = GetDeviceId(request);

            if (request[7] != 0x08)
            {
                return(null);
            }

            var positionCount = BitConverter.ToUInt16(request, 9);
            var dt            = GetDateTime(request, 11);
            var latitude      = DecodeFloat(request, 15);
            var longitude     = DecodeFloat(request, 19);
            var speed         = new Speed(request[27]).Unpack();

            return(GPSPoint.Factory(dt, latitude, longitude, speed).ToPosition(did, positionCount));
        }
Exemplo n.º 13
0
        private static GPSPoint GetPos(string[] data)
        {
            var dt = data.SingleOrDefault(s => s.StartsWith("t="));

            if (dt == null)
            {
                return(null);
            }
            var lat = Convert.ToSingle(data.SingleOrDefault(s => s.StartsWith("lat=")) ?? "0", CultureInfo.InvariantCulture);

            if (lat == 0.0)
            {
                return(null);
            }
            var lon = Convert.ToSingle(data.SingleOrDefault(s => s.StartsWith("lon=")) ?? "0", CultureInfo.InvariantCulture);

            return(lon == 0.0 ? null : GPSPoint.Factory(DateTimeUtils.SafeParseFormat(dt, "ddMMyyHHmmss"), lat, lon));
        }
Exemplo n.º 14
0
        public override IMessage Decode(IFrame frame)
        {
            /*
             * $D         = Packet header
             * Campo 1	   = ID de equipo 6 dígitos
             * Campo 2	   = Numero de paquete
             * Campo 3	   = Numero de Evento
             * Campo 4	   = Latitud
             * Campo 5	   = Longitud
             * Campo 6	   = Velocidad (nudos)
             * Campo 7	   = Rumbo
             * Campo 8	   = Edad de posición
             * Campo 9	   = Estado de entradas
             * Campo 10   = Estado de salidas
             * Campo 11   = Fecha
             * Campo 12   = Hora
             * Campo 13   = Tensión de alimentación (x 0.07 = Volt)
             * Campo 14   = Tensión de batería (x0.07 = Volt)
             * Campo 15   = Corriente de antena GPS (x1.21 = mA)
             * Campo 16   = Tiempo de reporte en minutos
             * Campo 17   = Tiempo de reporte 2 en minutos
             * Campo 18   = Clave de acceso
             * Campo 19   = Nivel de señal GSM
             * Campo 20   = Tipo de paquete de datos (significado de Dato 1 – 4)
             * Campo 21   = Dato 1
             * Campo 22   = Dato 2
             * Campo 23   = Dato 3
             * Campo 24   = Dato 4
             * $E	   = Packet end
             */
            var s        = Encoding.ASCII.GetString(frame.Payload, 0, frame.Payload.Length).Split(',');
            var nodecode = Convert.ToInt32(s[1]);
            var msgid    = Convert.ToUInt32(s[2]);
            var dt       = DateTime.Parse(s[11] + " " + s[12]);
            var speed    = Convert.ToSingle(s[6]);
            var lat      = Convert.ToSingle(s[4]);
            var lon      = Convert.ToSingle(s[5]);
            var ack      = String.Format("$B,{0},ACK={1},$E", s[1], s[2]);

            return(GPSPoint.Factory(dt, lat, lon, speed)
                   .ToPosition(nodecode, msgid)
                   .AddStringToSend(ack));
        }
Exemplo n.º 15
0
        private static GPSPoint PositionParse(String[] src)
        {
            //GSr,IMEI,[T,S,]Device_Mode,Report_Type,Alarm_Status,Geofence_status,GPS_Fix,UTC_Date,UTC_Time,Longitude,Latitude,Altitude,Speed,Heading,Number_of_Satellites,HDOP,Battery_capacity*checksum!
            //GSr,011412000845531,2,2,00,,1,020109,022556,+0,+0,135,0.00,0,0,0.0,94#68!
            //GSr,011412000845531,2,2,00,,3,050112,185436,-58425608,-34614105,65,0.04,350,7,1.4,100#64!

            if ((src[6] != "2") && (src[6] != "3"))
            {
                return(null);
            }
            var time = DateTimeUtils.SafeParseFormat(src[7] + src[8], "ddMMyyHHmmss");
            var lat  = GetDegrees(src[10]);
            var lon  = GetDegrees(src[9]);

            var dir  = Convert.ToSingle(src[13], CultureInfo.InvariantCulture);
            var vel  = Speed.KnotToKm(Convert.ToSingle(src[12], CultureInfo.InvariantCulture));
            var hdop = Convert.ToByte(Math.Round(Convert.ToSingle(src[15], CultureInfo.InvariantCulture)));

            return(GPSPoint.Factory(time, lat, lon, vel, dir, 0, hdop));
        }
Exemplo n.º 16
0
 private static GPSPoint ParseGpsPoint(String[] s, int offset)
 {
     return(GPSPoint.Factory(
                DateTimeUtils.SafeParseFormat(s[offset + 7], "yyyyMMddHHmmss"),
                Convert.ToSingle(s[offset + 6], CultureInfo.InvariantCulture),
                Convert.ToSingle(s[offset + 5], CultureInfo.InvariantCulture),
                Convert.ToSingle(s[offset + 2], CultureInfo.InvariantCulture)));
     //var dop = s[offset];
     //var GPSaccuracy = s[offset + 1];
     //var Speed = new Speed(Convert.ToSingle(s[offset + 2], CultureInfo.InvariantCulture));
     //var Azimuth = Convert.ToInt32(s[offset + 3], CultureInfo.InvariantCulture);
     //var Altitude = new Altitude(Convert.ToSingle(s[offset + 4], CultureInfo.InvariantCulture));
     //var Longitude = Convert.ToSingle(s[offset + 5], CultureInfo.InvariantCulture);
     //var Latitude = Convert.ToSingle(s[offset + 6], CultureInfo.InvariantCulture);
     //var dt = FechasUtm.SafeParseFormat(s[offset + 7], "yyyyMMddHHmmss");
     //var MCC = s[offset + 8]; //Mobile country code of the service cell
     //var MNC = s[offset + 9]; //Mobile network code of the service cell.
     //var LAC = s[offset + 10]; //Location area code in hex format of the service cell.
     //var CELL ID = s[offset + 11]; //CELL ID in hex format of the service cell.
     //var TA = s[offset + 12]; //Timing advance. Blank when it cannot be obtained.
     //var CSQ RSSI = s[offset + 13]; //Receiving signal strength indication: 0=less than or equal -115dBm; 1=-111dBm; 2...30=-110...-54dBm; 31=greater than or equal to -52dBm; 99=unknown or undetectable
 }
Exemplo n.º 17
0
        private GPSPoint ParseGpsData(byte[] ba, int offset)
        {
            var mark           = ba[offset + 17];
            var invalidQuality = (mark & 0x0C) == 0x00;

            if (invalidQuality)
            {
                return(null);
            }

            var dt  = new DateTime((DateTime.UtcNow.Year / 100) * 100 + ba[offset + 2], ba[offset + 1], ba[offset], ba[offset + 3], ba[offset + 4], ba[offset + 5], DateTimeKind.Utc);
            var lat = (float)(BitConverter.ToInt32(ba, offset + 6) / 3600000.0) * (!BitHelper.AreBitsSet(mark, 0x02) ? -1 : 1);
            var lon = (float)(BitConverter.ToInt32(ba, offset + 10) / 3600000.0) * (!BitHelper.AreBitsSet(mark, 0x01) ? -1 : 1);
            var vel = (BitConverter.ToInt16(ba, offset + 14) * 36) / 1000;     // reporta centimetros por segundo, multiplico por 0.036 para pasar a kilometros por segundo
            var dir = BitConverter.ToInt16(ba, offset + 16);

            //var cantsat = (flags & 0xF0) >> 4;

            var res = GPSPoint.Factory(dt, lat, lon, vel, dir, 0, 0);

            STrace.Debug(typeof(Parser).FullName, Id, String.Format("GPS: {0}", res));
            return(res);
        }
Exemplo n.º 18
0
        private void ProcessEvent(string code, Event generico)
        {
            string applicationCode;
            var    esConfirmacionUbox = false;

            ControlarInicioDistribucionPorMensaje(code, generico);

            ControlarCierreDistribucionPorMensaje(code, generico);

            if (MessageIdentifierX.IsRfidEvent(generico.Code))
            {
                applicationCode = ProcessRfidEvent(code, generico);
            }
            else if (MessageIdentifierX.IsEstadoLogistico(generico.GetData()))
            {
                applicationCode = ProcessEstadoLogistico(code, generico);
            }
            else if (MessageIdentifierX.IsPanicEvent(code))
            {
                applicationCode = ProcessPanicEvent(generico, code);
            }
            else if (code.Equals(MessageCode.SpeedingTicket.GetMessageCode()))
            {
                applicationCode = ProcessVelocidadExcedidaGenericEvent(generico);
            }
            else if (MessageIdentifierX.IsConfirmacionUbox(generico.GetData()))
            {
                applicationCode    = code;
                esConfirmacionUbox = true;
                // DEFINE EL PROCESAMIENTO CUANDO SABE SI TIENE UN PUNTO
            }
            else
            {
                applicationCode = ProcessGenericEvent(generico, code);
            }

            if (DaoFactory.DetalleDispositivoDAO.GetProcesarCicloLogisticoFlagValue(generico.DeviceId))
            {
                GPSPoint point = null;
                if (generico.GeoPoint != null)
                {
                    point = GPSPoint.Factory(generico.GeoPoint.Date, generico.GeoPoint.Lat, generico.GeoPoint.Lon);
                }
                else
                {
                    var maxMonths = Coche.Empresa != null ? Coche.Empresa.MesesConsultaPosiciones : 3;
                    var pos       = DaoFactory.LogPosicionDAO.GetFirstPositionOlderThanDate(Coche.Id, generico.Tiempo, maxMonths);
                    if (pos != null)
                    {
                        point = GPSPoint.Factory(generico.Tiempo, (float)pos.Latitud, (float)pos.Longitud);
                    }
                }

                if (point != null)
                {
                    if (esConfirmacionUbox)
                    {
                        ProcessConfirmacionUbox(code, generico, point);
                    }
                    else
                    {
                        CicloLogisticoFactory.Process(DaoFactory, applicationCode, Coche, point, generico, false, GetChofer(generico.GetRiderId()));
                        CicloLogisticoFactory.ProcessEstadoLogistico(Coche, generico, applicationCode);
                    }
                }
                else if (esConfirmacionUbox)
                {
                    ProcessGenericEvent(generico, code);
                }
            }
        }
Exemplo n.º 19
0
        public override IMessage Decode(IFrame frame)
        {
            var chR = BitConverter_BigEndian.ToInt32(frame.Payload, frame.Payload.Length - 4);
            var chC = GetChecksum(frame.Payload);

            if (chC != chR)
            {
                STrace.Debug(GetType().FullName, Id, String.Format("Paquete descartado por checksum: checksum {0:X8}:{1:X8} {2}", chC, chR, StringUtils.MakeString(frame.Payload)));
                return(null);
            }

            var tipo = (PacketType)frame.Payload[0];
            //var packetLenght = BitConverter_BigEndian.ToInt16(Frame.Payload, 3);
            var msgId = BitConverter_BigEndian.ToUInt32(frame.Payload, 5);

            var      dt1 = (frame.Payload[11] == 0 || frame.Payload[10] == 0 || frame.Payload[9] == 0) ? DateTime.UtcNow : new DateTime(((DateTime.UtcNow.Year / 100) * 100) + frame.Payload[11], frame.Payload[10], frame.Payload[9], frame.Payload[12], frame.Payload[13], frame.Payload[14]);
            IMessage res;

            switch (tipo)
            {
            case PacketType.ReportPosition:
            {
                var data = Encoding.ASCII.GetString(frame.Payload, 15, frame.Payload.Length - 19).Split(',');

                var dt2 = DateTimeUtils.SafeParseFormat(data[10] + data[2].Split('.')[0], "ddMMyyHHmmss");
                var lat = GPSPoint.ResampleAxis(data[4]) * ((data[5] == "N") ? 1 : -1);
                var lon = GPSPoint.ResampleAxis(data[6]) * ((data[7] == "E") ? 1 : -1);
                var vel = Speed.KnotToKm(Convert.ToSingle(data[8], CultureInfo.InvariantCulture));
                var dir = Convert.ToSingle(data[9], CultureInfo.InvariantCulture);
                var pos = GPSPoint.Factory(dt2, lat, lon, vel, dir, 0, 0);

                res = pos.ToPosition(Id, msgId);
                var interval = BitConverter_BigEndian.GetBytes((Int16)1);                                 //este numero multiplicado * 10'' es el intervalo de reporte
                var resdata  = new []
                {
                    (byte)DateTime.UtcNow.Day,
                    (byte)DateTime.UtcNow.Month,
                    (byte)DateTime.UtcNow.Year,
                    (byte)DateTime.UtcNow.Hour,
                    (byte)DateTime.UtcNow.Minute,
                    (byte)DateTime.UtcNow.Second,
                    interval[0],
                    interval[1]
                };
                res.Response = FactoryResponse(PacketType.AckPosition, frame.Payload, resdata);
                STrace.Debug(GetType().FullName, Id, String.Format("dt {0} {1}", dt1, pos));
                break;
            }

            case PacketType.ReportModbusData:
            {
                var source = frame.Payload[15];
                var count  = (frame.Payload.Length - Nondatalen) / Recordlen;                                //cantidad de bytes de los datos / 4 bytes por cada dato
                var sb     = new StringBuilder();
                for (var i = 0; i < count; i++)
                {
                    var key   = GetShort(frame, i, 16);
                    var value = GetShort(frame, i, 18) * 1.0;

                    if (key == 40108)
                    {
                        value /= 10;                                                   //para "Fuel Rate" el valor viene expresado en decilitros y es conveniente visualizarlo en "Litros"
                    }
                    if ((value != 0x8000) && (value != 0x80000000))
                    {
                        sb.AppendFormat(CultureInfo.InvariantCulture, "Modbus_{0}_{1}:{2},", source, key, value);
                    }
                }

                res = MessageIdentifier.AnalogicInputs.FactoryEvent(MessageIdentifier.TelemetricData, Id, msgId, null, dt1, null, null);
                ((Event)res).SensorsDataString = sb.ToString();
                res.Response = FactoryResponse(PacketType.AckModbusData, frame.Payload, null);
                STrace.Debug(GetType().FullName, Id, String.Format("ModbusData {0} dt {1} payload {2}", sb, dt1, StringUtils.MakeString(frame.Payload)));
                break;
            }

            case PacketType.ReplyModbusList:
                //pendiente Fota.Dequeue(PacketType.Command_ModbusList)
                STrace.Debug(GetType().FullName, Id, String.Format("ModbusList (dt {0}) {1}", dt1, StringUtils.MakeString(frame.Payload)));
                res = new UserMessage(Id, msgId);
                break;

            case PacketType.RequestBiosNewPage:
            {
                STrace.Debug(GetType().FullName, Id, String.Format("BiosNewPage (dt {0}) {1}", dt1, StringUtils.MakeString(frame.Payload)));
                //pendiente fota de bios
                //var requestedpagelen = BitConverter_BigEndian.ToUInt16(Frame.Payload, 15);
                //var requestedpagenumber = BitConverter_BigEndian.ToUInt16(Frame.Payload, 17);
                //var resdata = new byte[50];
                //Array.Copy(biosdata, 0, resdata, 0, 50);
                res = new UserMessage(Id, msgId);
                //res.Response = FactoryResponse(PacketType.BiosNewPage, Frame.Payload, resdata);
                break;
            }

            case PacketType.ReportEngineData:
            {
                var enginenum      = frame.Payload[15];
                var engineStateNum = frame.Payload[16];
                var engineState    = (EngineStates)engineStateNum;
                MessageIdentifier evcode;
                var isevent = new List <EngineStates> {
                    EngineStates.Start, EngineStates.Stop
                }.Contains(engineState);
                if (_enginesStates.ContainsKey(enginenum) && (!isevent) && ((_enginesStates[enginenum]) == engineState))
                {
                    evcode = MessageIdentifier.AnalogicInputs;
                }
                else
                {
                    if (!_enginesStates.ContainsKey(enginenum))
                    {
                        _enginesStates.Add(enginenum, engineState);
                    }
                    switch (engineState)
                    {
                    case EngineStates.Start:
                        evcode = MessageIdentifier.EngineOn;
                        break;

                    case EngineStates.Stop:
                        evcode = MessageIdentifier.EngineOff;
                        break;

                    //case EngineStates.DataInfo:
                    //case EngineStates.Unknown:
                    default:
                        evcode = MessageIdentifier.TelemetricData;
                        break;
                    }
                }

                var sb = new StringBuilder();

                var engHours           = BitConverter_BigEndian.ToUInt32(frame.Payload, 17);
                var fuelUsed           = BitConverter_BigEndian.ToUInt32(frame.Payload, 21);
                var kVAhours           = BitConverter_BigEndian.ToUInt32(frame.Payload, 25);
                var kVAhoursParcial    = BitConverter_BigEndian.ToUInt32(frame.Payload, 29);
                var segundosRunParcial = BitConverter_BigEndian.ToUInt32(frame.Payload, 33);

                sb.AppendFormat(CultureInfo.InvariantCulture, "Modbus_{0}_EngineState:{1},", enginenum, engineState);
                if ((engHours != 0x8000) && (engHours != 0x80000000))
                {
                    sb.AppendFormat(CultureInfo.InvariantCulture, "Modbus_{0}_43587:{1},", enginenum, engHours);
                }
                if ((fuelUsed != 0x8000) && (fuelUsed != 0x80000000))
                {
                    sb.AppendFormat(CultureInfo.InvariantCulture, "Modbus_{0}_40126:{1},", enginenum, fuelUsed);
                }
                if ((kVAhours != 0x8000) && (kVAhours != 0x80000000))
                {
                    sb.AppendFormat(CultureInfo.InvariantCulture, "Modbus_{0}_43595:{1},", enginenum, kVAhours);
                }
                if ((kVAhoursParcial != 0x8000) && (kVAhoursParcial != 0x80000000))
                {
                    sb.AppendFormat(CultureInfo.InvariantCulture, "Modbus_{0}_40337:{1},", enginenum, kVAhoursParcial);
                }
                if ((segundosRunParcial != 0x8000) && (segundosRunParcial != 0x80000000))
                {
                    sb.AppendFormat(CultureInfo.InvariantCulture, "Modbus_{0}_SegundosRunParcial:{1},", enginenum, segundosRunParcial);
                }

                var res_ = evcode.FactoryEvent(MessageIdentifier.TelemetricData, Id, msgId, null, dt1, null, null);
                res_.SensorsDataString = sb.ToString();
                STrace.Debug(GetType().FullName, Id, String.Format("EngineData: {0} Payload: {1}", res_.SensorsDataString, StringUtils.MakeString(frame.Payload)));
                res_.Response = FactoryResponse(PacketType.AckEngineData, frame.Payload, null);
                res           = res_;
                break;
            }

            default:
                STrace.Debug(GetType().FullName, Id, String.Format("paquete no reconocido: {0}", StringUtils.MakeString(frame.Payload)));
                return(null);
            }
            //Debug.Assert(res != null);
            res.Tiempo = dt1;
            return(res);
        }
Exemplo n.º 20
0
        internal static IMessage Parse(String asString, INode node)
        {
            Debug.Assert(node != null);

            // [8-12] : sentido de giro del trompo (5)
            var girotrompo = new GIRO_TROMPO[5];

            for (var i = 0; i < 5; i++)
            {
                var sg = asString[8 + i];

                switch (sg)
                {
                case 'D': girotrompo[i] = GIRO_TROMPO.Derecha; break;

                case 'I': girotrompo[i] = GIRO_TROMPO.Izquierda; break;

                case 'N': girotrompo[i] = GIRO_TROMPO.Reposo; break;

                default: girotrompo[i] = GIRO_TROMPO.Reposo; break;
                }
            }

            var pl = new List <GPSPoint>();
            // [7] : Cantidad de posiciones en el paquete (0 a 5)
            //[13-47][48-82][83-117][118-152][153-187] : posiciones
            // hasta 5 la cantidad esta dada por CantPos
            // hhmmss,ddmm.mmmm,[N|S|I],0ddmm.mmmm,[W|E|I],vvv.
            var cantPos = Convert.ToInt32(asString.Substring(7, 1));

            for (var i = 0; i < cantPos; i++)
            {
                var subMsg = asString.Substring(13 + (36 * i), 36);

                var ordLat = subMsg[17];
                var ordLon = subMsg[30];

                float lat, lon;

                //parseo la latitud
                switch (ordLat)
                {
                case 'N': lat = GPSPoint.ResampleAxis(subMsg.Substring(7, 9)); break;

                case 'S': lat = -GPSPoint.ResampleAxis(subMsg.Substring(7, 9)); break;

                default: continue;
                }

                //parseo la longitud
                switch (ordLon)
                {
                case 'E': lon = GPSPoint.ResampleAxis(subMsg.Substring(19, 9)); break;

                case 'W': lon = -GPSPoint.ResampleAxis(subMsg.Substring(19, 9)); break;

                default: continue;
                }

                pl.Add(GPSPoint.Factory(ExtraeHhmmss(subMsg.Substring(0, 6)), lat, lon, Convert.ToInt32(subMsg.Substring(32, 3))));
            }

            return(pl.ToPosition(node.Id, 0));
        }
Exemplo n.º 21
0
        protected override HandleResults OnDeviceHandleMessage(TextEvent message)
        {
            var employee = GetChofer(message.UserIdentifier);

            var pos = message.GeoPoint;

            if (pos == null)
            {
                var pp = DaoFactory.LogPosicionDAO.GetLastOnlineVehiclePosition(Coche);
                pos = GPSPoint.Factory(message.GetDateTime(), pp == null ? (float)0.0 : (float)pp.Latitud, pp == null ? (float)0.0 : (float)pp.Longitud);
            }

            MessageSaver.Save(message, MessageCode.TextEvent.GetMessageCode(), Dispositivo, Coche, employee, pos.Date, pos, message.Text);

            if (Coche.Empresa.IntegrationServiceEnabled)
            {
                var text = message.Text.Trim().ToUpperInvariant();
                var ruta = DaoFactory.ViajeDistribucionDAO.FindEnCurso(Coche);
                if (ruta != null && text.Contains(Coche.Empresa.IntegrationServicePrefixConfirmation))
                {
                    var sosTicket = DaoFactory.SosTicketDAO.FindByCodigo(ruta.Codigo);
                    if (sosTicket != null)
                    {
                        text = text.Replace(Coche.Empresa.IntegrationServicePrefixConfirmation, string.Empty);
                        var intService = new IntegrationService(DaoFactory);
                        if (sosTicket.Patente.ToUpperInvariant().Contains(text))
                        {
                            intService.ConfirmaPatente(sosTicket, true);
                        }
                        else
                        {
                            intService.ConfirmaPatente(sosTicket, false);
                        }
                    }
                }
            }

            if (Coche.Empresa.AsignoDistribucionPorMensaje)
            {
                var text = message.Text.Trim().ToUpperInvariant();
                STrace.Trace("AsignoDistribucionPorMensaje", string.Format("Text: {0}", text));

                var prefijo = Coche.Empresa.AsignoDistribucionPrefijoMensaje.Trim().ToUpperInvariant();
                if (text.Contains(prefijo))
                {
                    STrace.Trace("AsignoDistribucionPorMensaje", string.Format("Empresa: {0} - Coche: {1} - Msj: {2}", Coche.Empresa.Id, Coche.Id, text));

                    var mensaje = MessageSender.Create(Dispositivo, new MessageSaver(DaoFactory))
                                  .AddCommand(MessageSender.Comandos.SubmitTextMessage);

                    var viajeEnCurso = DaoFactory.ViajeDistribucionDAO.FindEnCurso(Coche);
                    if (viajeEnCurso == null)
                    {
                        var codigoRuta = DateTime.Today.ToString("yyMMdd") + "|" + text.Replace(prefijo, string.Empty).Trim();
                        var viaje      = DaoFactory.ViajeDistribucionDAO.FindByCodigo(Coche.Empresa.Id, Coche.Linea.Id, codigoRuta);
                        if (viaje != null)
                        {
                            if (viaje.Estado == ViajeDistribucion.Estados.Pendiente)
                            {
                                viaje.Vehiculo = Coche;
                                DaoFactory.ViajeDistribucionDAO.SaveOrUpdate(viaje);

                                var ciclo  = new CicloLogisticoDistribucion(viaje, DaoFactory, new MessageSaver(DaoFactory));
                                var evento = new InitEvent(DateTime.UtcNow);
                                ciclo.ProcessEvent(evento);

                                mensaje = mensaje.AddMessageText("RUTA " + codigoRuta + " INICIADA");
                                STrace.Trace("AsignoDistribucionPorMensaje", string.Format("RUTA {0} INICIADA", codigoRuta));
                            }
                            else
                            {
                                mensaje = mensaje.AddMessageText("NO ES POSIBLE INICIAR LA RUTA " + codigoRuta);
                                STrace.Trace("AsignoDistribucionPorMensaje", string.Format("NO ES POSIBLE INICIAR LA RUTA {0}", codigoRuta));
                            }
                        }
                        else
                        {
                            mensaje = mensaje.AddMessageText("RUTA " + codigoRuta + " NO ENCONTRADA");
                            STrace.Trace("AsignoDistribucionPorMensaje", string.Format("RUTA {0} NO ENCONTRADA", codigoRuta));
                        }
                    }
                    else
                    {
                        mensaje = mensaje.AddMessageText("USTED YA TIENE ASIGNADA UNA RUTA INICIADA");
                        STrace.Trace("AsignoDistribucionPorMensaje", string.Format("USTED YA TIENE ASIGNADA UNA RUTA INICIADA"));
                    }
                    mensaje.Send();
                }
            }

            return(HandleResults.Success);
        }
Exemplo n.º 22
0
        public override IMessage Decode(IFrame frame)
        {
            try
            {
                var type = frame.Payload[0];
                var time = GetTiempo(BitConverter_BigEndian.ToInt32(frame.Payload, 1));
                switch (type)
                {
                case 1:     //posicion
                    var lat   = (float)(BitConverter_BigEndian.ToUInt24(frame.Payload, 5) / 100000.0);
                    var lon   = (float)(BitConverter_BigEndian.ToUInt24(frame.Payload, 8) / 100000.0);
                    var signs = frame.Payload[11];
                    if (BitHelper.IsBitSet(signs, 2))
                    {
                        lat *= -1;
                    }
                    if (BitHelper.IsBitSet(signs, 1))
                    {
                        lon *= -1;
                    }
                    STrace.Debug(GetType().FullName, String.Format("posicion: {0}:{1}:{2} === {3}", time, lat, lon, frame.Payload));
                    return(GPSPoint.Factory(time, lat, lon).ToPosition(Id, 0));

                case 2:                                              //login
                    return(GetLogEvent(frame.Payload, Id, time, 3)); //quote dispatcher code: "case 3: return MessageCode.RfidEmployeeLogin.GetMessageCode();"

                case 3:                                              //logout
                    return(GetLogEvent(frame.Payload, Id, time, 4)); //quote dispatcher code: "case 4: return MessageCode.RfidEmployeeLogout.GetMessageCode();"

                case 6:                                              //teclado: SMS, LOGIN_RFID, LOGOUT_RFID, LOGIN_LEGAJO, LOGOUT_LEGAJO
                    var strs  = Encoding.ASCII.GetString(frame.Payload, 5, frame.Payload.Length - 5).Split(" ".ToCharArray(), 2);
                    var tipo  = strs[0];
                    var texto = strs[1].Trim();
                    switch (tipo)
                    {
                    case MensajeTeclado.Sms:
                        return(new TextEvent(Id, 0, time)
                        {
                            Text = texto,
                        });

                    case MensajeTeclado.LoginRfid:
                    {
                        var rfid = decodeRFID(texto, 'm');
                        return(MessageIdentifierX.FactoryRfid(Id, 0, null, time, rfid, 3));
                    }

                    case MensajeTeclado.LoginLegajo:
                    {
                        var msg = MessageIdentifierX.FactoryRfid(Id, 0, null, time, null, 3);
                        msg.SensorsDataString = texto;                                                 //legajo
                        return(msg);
                    }

                    case MensajeTeclado.LogoutRfid:
                    {
                        var rfid = decodeRFID(texto, 'm');
                        return(MessageIdentifierX.FactoryRfid(Id, 0, null, time, rfid, 4));
                    }

                    case MensajeTeclado.LogoutLegajo:
                    {
                        var msg = MessageIdentifierX.FactoryRfid(Id, 0, null, time, null, 4);
                        msg.SensorsDataString = texto;                                                 //legajo
                        return(msg);
                    }

                    default:
                        return(null);
                    }

                default:
                    return(null);
                }
            }
            catch (Exception e)
            {
                STrace.Exception(GetType().FullName, e, Id, String.Format("Parser Orbcomm message: {0}", frame.Payload));
                return(null);
            }
        }
Exemplo n.º 23
0
        public override IMessage Decode(IFrame frame)
        {
            IMessage salida = null;
            string   buffer = AsString(frame);

            if (buffer == null)
            {
                return(null);
            }

            CusatUniversalParser parser = new CusatUniversalParser(buffer);

            /*
             *
             *
             * >RU1PBN177  110316154602-3292596-06883632 325 500 000 10 80 04 012|#1BDE4B<
             *    patente 8 caracteres DDMMYYHHMMSS   8dig lat    8dig long  fix3d  age 3  vel    Sat  dop  enhex 2   evento 3
             * >RU1 PBN177  ------------ 110316154602  -3292596   -0688363      2     325    500     80    04        012
             *
             *
             *
             *
             * Universal 6, este es nuestro y hay algunas variantes mas ( ancho fijo ):
             * RU1XYZ12345DDMMYYHHMMSS-3400000-58000003000000000080280017|#1234
             * RU1 = OPCODE
             * XYZ12345 = MATRICULA ( 8)
             * DDMMYYHHMMSS = FECHA
             * -3400000 = LAT
             * -5800000 = LON
             * 3 = Fix 3D
             * 000 = Age
             * 000 = Vel
             * 000 = Dir
             * 08 = Sat
             * 02 = Dop
             * 80 = ent en hexa ( 128 )
             * 017 = evento
             * 1234 = número de bloque
             * NOTA: entre “|” y “#” está pensado para poner data ( quizás variable ) en el futuro, nunca se usó.
             *
             *
             *
             *
             *
             */
            ulong    msgId = NextSequence;// ulong.Parse(parser[6]);
            GPSPoint pos;
            var      code = EventCodes.Position;
            var      time = DateTime.ParseExact(parser.Fecha, "ddMMyyHHmmss",
                                                System.Globalization.CultureInfo.InvariantCulture);
            var lat = float.Parse(parser.Latitud.Insert(3, ","));// parser[2].Replace('.', ','));
            var lon = float.Parse(parser.Longitud.Insert(4, ","));
            var vel = float.Parse(parser.Vel);
            var dir = float.Parse(parser.Dir);

            short codeevent = (short)0;

            /*
             * 0=PEDIDO DE POSICION
             * 1=BOTON DE PANICO
             * 8=CONTACTO ON
             * 15=BAT. DESCONECTADA
             * 16=CONTACTO OFF
             * 17=POSICION EN CONTACTO
             * 18=POSICION SIN CONTACTO
             * 23=RESET DE EQUIPO
             *
             * 0=PEDIDO DE POSICION
             * 8001=BOTON DE PANICO
             * 8008=CONTACTO ON
             * 8015=BAT. DESCONECTADA
             * 8016=CONTACTO OFF
             * 8017=POSICION EN CONTACTO
             * 8018=POSICION SIN CONTACTO
             * 8023=RESET DE EQUIPO
             *
             *
             *
             */

            switch (parser.Evento)
            {
            case "001":
            {
                codeevent = 8001;         //8001=BOTON DE PANICO
            }
            break;

            case "008":
            {
                codeevent = 8008;         //8008=CONTACTO ON
            }
            break;

            case "015":
            {
                codeevent = 8015;         //8015=BAT. DESCONECTADA
            }
            break;

            case "016":
            {
                codeevent = 8016;         //8016=CONTACTO OFF
            }
            break;

            case "017":
            {
                codeevent = 8017;         //8017=POSICION EN CONTACTO
            }
            break;

            case "018":
            {
                codeevent = 8018;         //8018=POSICION SIN CONTACTO
            }
            break;

            case "023":
            {
                codeevent = 8023;         //8023=RESET DE EQUIPO
            }
            break;

            default:
                break;
            }



            var hdop = 0;

            pos = GPSPoint.Factory(time, lat, lon, vel, dir, 0, hdop);
            var device   = DataProvider.FindByIMEI(parser.Matricula, this);
            var deviceid = 0;

            if (device == null)
            {
                var         empresa         = _daoFactory.EmpresaDAO.FindByCodigo("QP");
                var         tipodispositivo = _daoFactory.TipoDispositivoDAO.FindByModelo("CUSATUNIVERSAL6");
                Dispositivo newdispo        = new Dispositivo();
                newdispo.Empresa = empresa;
                //  newdispo.Linea = _daoFactory.LineaDAO.FindByNombre(empresa.Id, "Generica");
                newdispo.TipoDispositivo = tipodispositivo;
                newdispo.Clave           = parser.Matricula.ToString();
                newdispo.Tablas          = "";
                newdispo.Port            = 6070;
                //  newdispo.Firmware = _daoFactory.FirmwareDAO.FindById(5);
                newdispo.Imei   = parser.Matricula.ToString();
                newdispo.Codigo = parser.Matricula.ToString();
                _daoFactory.DispositivoDAO.Save(newdispo);
                if (_daoFactory.CocheDAO.FindByPatente(empresa.Id, parser.Matricula.ToString()) == null)
                {
                    Coche newcoche = new Coche();
                    newcoche.Patente           = parser.Matricula.ToString();
                    newcoche.Interno           = parser.Matricula.ToString();
                    newcoche.ModeloDescripcion = "";
                    newcoche.Empresa           = empresa;
                    newcoche.Dispositivo       = newdispo;
                    _daoFactory.CocheDAO.Save(newcoche);
                }
                else
                {
                    Coche coche = _daoFactory.CocheDAO.FindByPatente(empresa.Id, parser.Matricula.ToString());
                    coche.Dispositivo = newdispo;
                    _daoFactory.CocheDAO.Save(coche);
                }
                deviceid = newdispo.Id;
            }
            else
            {
                deviceid = DataProvider.FindByIMEI(parser.Matricula.ToString(), this).Id;
            }

            if (codeevent == 0)
            {
                salida = pos.ToPosition(deviceid, msgId);
            }
            else
            {
                salida = new Event(codeevent, -1, deviceid, msgId, pos, pos.GetDate(), "", new List <long>(), true);
            }

            return(salida);

            /*
             *
             *
             *
             *          if (ParserUtils.IsInvalidDeviceId(Id)) return null;
             *
             *          var buffer = AsString(frame);
             * if (buffer == null || !buffer.Contains(">RU")) return null;
             *
             *          var dt = DateTimeUtils.SafeParseFormat(buffer.Substring(28, 12), "ddMMyyHHmmss");
             *          var codEv = GetEventCode(buffer);
             *
             *          //var msgId = GetMsgId(buffer); //siempre es 0001!!!
             *          var msgId = (ulong)((dt.Ticks << 8) + codEv);
             *
             *
             *          var gpsPoint = ParseRu2(buffer, dt);
             *          return GetSalida(gpsPoint, dt, "00000000", codEv, this, msgId);*/
        }
Exemplo n.º 24
0
        public override IMessage Decode(IFrame frame)
        {
            if (ParserUtils.IsInvalidDeviceId(Id))
            {
                return(null);
            }

            //Debug.Assert(Frame.Payload[5] == 0x77);
            //var SENDOK = Frame.Payload[7];
            //var IDLETIME = Frame.Payload[13] + Frame.Payload[14] << 8;

            var msgId       = BitConverter.ToUInt32(frame.Payload, 87);
            var tipoReporte = frame.Payload[4];

            var vel = Speed.KnotToKm(frame.Payload[26]);

            var hour8 = frame.Payload[27];

            if (hour8 < 0x80)
            {
                STrace.Trace(GetType().FullName, Id, "Descartando reporte por hora invalida");
                return(null);
            }

            var year   = Convert.ToInt32(frame.Payload[25].ToString("X2")) + ((DateTime.UtcNow.Year / 100) * 100);
            var month  = Convert.ToInt32(frame.Payload[24].ToString("X2"));
            var day    = Convert.ToInt32(frame.Payload[23].ToString("X2"));
            var minute = Convert.ToInt32(frame.Payload[28].ToString("X2"));
            var second = Convert.ToInt32(frame.Payload[29].ToString("X2"));

            var hour = Convert.ToInt32((hour8 - 0x80).ToString("X2"));
            var date = new DateTime(year, month, day, hour, minute, second, DateTimeKind.Utc);
            var lat  = (float)(BitConverter.ToInt32(frame.Payload, 30) / (-600000.0));
            var lon  = (float)(BitConverter.ToInt32(frame.Payload, 34) / (-600000.0));

            var pos = GPSPoint.Factory(date, lat, lon, vel);

            //var TIMESPEED = Frame.Payload[38];
            //var SPEED = Frame.Payload[39-49];

            var chofer = (frame.Payload[62] + frame.Payload[63] << 8).ToString("X10");

            lock (ChoferesLock)
            {
                if (Choferes.ContainsKey(Id))
                {
                    var lastChofer = Choferes[Id];
                    ProcessChoferState(pos, date, msgId, lastChofer, 1);                 //logout
                    ProcessChoferState(pos, date, msgId, chofer, 0);                     //login
                }
                else
                {
                    Choferes.Add(Id, chofer);
                }
            }

            switch (tipoReporte)
            {
            case 0x17:     //Reset del equipo completo.
                return(MessageIdentifier.DeviceShutdown.FactoryEvent(MessageIdentifier.GenericMessage, Id, msgId, pos, date, chofer, null));

            case 0x18:     //Inicio (power up) del equipo.
                return(MessageIdentifier.DeviceTurnedOn.FactoryEvent(MessageIdentifier.GenericMessage, Id, msgId, pos, date, chofer, null));

            case 0x19:     //Intento de reconexión del modulo GSM.
                return(MessageIdentifier.GsmSignalOn.FactoryEvent(MessageIdentifier.GenericMessage, Id, msgId, pos, date, chofer, null));

            case 0x25:     //Reset del modulo GPS.
                return(MessageIdentifier.GpsSignalOff.FactoryEvent(MessageIdentifier.GenericMessage, Id, msgId, pos, date, chofer, null));

            case 0x63:     //Recupero de información.//posicion encolada
            case 0x64:     //Información actual.//posicion online
            case 0x65:     //Información actual conectado a capturador de datos.//posicion online
                return(pos.ToPosition(Id, msgId));

            default:
                STrace.Debug(GetType().FullName, Id, String.Format("Llego reporte de tipo no soportado: tipo=0x{0:X2} lat={1} lon={2} date={3} chofer={4}", tipoReporte, pos.Lat, pos.Lon, date, chofer));
                return(null);
            }
        }
Exemplo n.º 25
0
        private void ProcessGps(String file)
        {
            Empresa     empresa     = null;
            Dispositivo dev         = null;
            var         errorslist  = new List <String>();
            var         infoList    = new List <String>();
            var         moveAllFile = false;
            var         lastdt      = DateTime.MinValue;
            var         latestdt    = DateTime.MinValue;
            var         repro       = file.Contains("_r_");

            using (var sr = new StreamReader(file))
            {
                String line;
                while ((moveAllFile == false) && ((line = sr.ReadLine()) != null))
                {
                    var datos = line.Split('@');
                    try
                    {
                        switch (datos[0])
                        {
                        //default:
                        //STrace.Trace(GetType().FullName, "Tipo de linea ignorada: {0}", line);
                        //break;
                        case "1":                                 //info
                        {
                            infoList.Add(line);
                            try
                            {
                                switch (datos[1])
                                {
                                //default:
                                //STrace.Trace(GetType().FullName, "Tipo de linea de info ignorada: {0}", line);
                                //break;
                                case "3":                                                         //"Nombre de la Empresa"
                                    empresa = DaoFactory.EmpresaDAO.FindByCodigo(datos[2]);
                                    if (empresa == null)
                                    {
                                        throw new InvalidDataException(String.Format("No se encontro la empresa: {0}", datos[2]));
                                    }
                                    break;

                                case "4":                                                         //"Fecha Y Hora de la Captura"
                                    //generar un evento?
                                    break;

                                case "13":                                                         //"Numero de Movil"
                                    if (empresa == null)
                                    {
                                        throw new InvalidDataException("Primero declare la empresa!");
                                    }
                                    dev = DaoFactory.CocheDAO.FindByInterno(new List <int> {
                                            empresa.Id
                                        }, null, datos[2].Substring(0, datos[2].Length - 2)).Dispositivo;
                                    if (dev == null)
                                    {
                                        throw new InvalidDataException(String.Format("No se encontro el dispositivo o el movil: {0}", datos[2]));
                                    }
                                    lastdt = GetLastDt(dev);
                                    break;
                                }
                            }
                            catch
                            {
                                moveAllFile = true;
                                throw;
                            }
                            break;
                        }

                        case "2":                                 //data
                        {
                            if (dev == null)
                            {
                                moveAllFile = true;
                                throw new ArgumentNullException("", "Primero declare el movil!");
                            }
                            try
                            {
                                Debug.Assert(line.StartsWith("2@100@0@"));
                                DispatcherDispatch(GPSPoint.Factory(
                                                       DateTimeUtils.SafeParseFormat(datos[3] + datos[4].PadLeft(6, '0'), "yyyyMMddHHmmss"),
                                                       Convert.ToSingle(datos[5], CultureInfo.InvariantCulture),
                                                       Convert.ToSingle(datos[6], CultureInfo.InvariantCulture),
                                                       Convert.ToSingle(datos[7], CultureInfo.InvariantCulture)).ToPosition(dev.Id, 0), lastdt, repro, ref latestdt);
                            }
                            catch
                            {
                                errorslist.Add(line);
                                throw;
                            }
                            break;
                        }
                        }
                    }
                    catch (Exception e)
                    {
                        STrace.Exception(GetType().FullName, e, dev.GetId());
                    }
                }
                sr.Close();
            }
            Finishit(file, infoList, moveAllFile, errorslist, latestdt, dev.Id);
        }