Example #1
0
 /// <summary>
 /// Returns the distance traveled until the current time in meters.
 /// </summary>
 /// <param name="time">Time in seconds</param>
 /// <returns>Distance in meters</returns>
 public double GetDistance(float time)
 {
     int index = this.GetTrackPointIndex(time);
     double distance = this.gpsPoints[index].Distance;
     GPSCoord lastPosition = this.GetPosition(time);
     GPSPoint interpolatedPos = new GPSPoint(lastPosition.Longitude, lastPosition.Latitude, lastPosition.Elevation, 0, 0);
     return distance += interpolatedPos.DistanceFromPoint(this.gpsPoints[index]);
 }
Example #2
0
        private IMessage ParseTripEnd(IFrame frame)
        {
            //decoding
            var tripid = BitConverter.ToInt32(frame.Payload, DataStart);
            var fixedPackageSequenceNumber = BitConverter.ToUInt32(frame.Payload, DataStart + 4);
            var rtctime = ParseRtcTime(frame.Payload, DataStart + 8);
            //var totalTripMileage = BitConverter.ToInt32(Frame.Payload, dataStart + 12); //en millas
            //var totalTripFuelConsumption = BitConverter.ToInt32(Frame.Payload, dataStart + 16);
            var      dataFlag = frame.Payload[DataStart + 20];
            var      privacyFunctionenabledFlag = BitHelper.AreBitsSet(frame.Payload[DataStart + 20], 0x01);
            var      gpsDataFlag = BitHelper.AreBitsSet(frame.Payload[DataStart + 20], 0x02);
            var      offset      = DataStart + 18;
            GPSPoint pos         = null;

            if (!privacyFunctionenabledFlag && gpsDataFlag)
            {
                pos     = ParseGpsData(frame.Payload, offset);
                offset += 19;
            }
            else
            {
                var limit = 19;
                if (frame.Payload.Length - offset < 19)
                {
                    limit = frame.Payload.Length - offset;
                }
                STrace.Debug(GetType().FullName, Id, String.Format("No hay datos de gps, Flag={0:X2} pfeFlag={1} GpsFlag={2} payload={3}", dataFlag, privacyFunctionenabledFlag, gpsDataFlag, StringUtils.ByteArrayToHexString(frame.Payload, offset, limit)));
            }
            var vState = ParseVehicleState(frame.Payload, offset);

            STrace.Debug(GetType().FullName, Id, String.Format("TripEnd: tripid={0} VState.Length={1} payload={2}", tripid, vState.Length, GetData(frame)));

            var res = pos.ToPosition(Id, fixedPackageSequenceNumber);

            res.Tiempo = rtctime;
            return(res);
        }
Example #3
0
        public void exportJsonRoute()
        {
            //初始化一条路线,是由多条路组成的
            List <RoadInfo> route = new List <RoadInfo>();

            //初始化一条路,并为其添加一些关键点
            RoadInfo road1 = new RoadInfo("road1");
            GPSPoint p11   = new GPSPoint(1.1, 2.1);
            GPSPoint p12   = new GPSPoint(1.2, 2.2);
            GPSPoint p13   = new GPSPoint(1.3, 2.3);

            road1.AddPoint(p11);
            road1.AddPoint(p12);
            road1.AddPoint(p13);

            road1.AddNextRoadName("road2");
            route.Add(road1);

            RoadInfo road2 = new RoadInfo("road2");
            GPSPoint p21   = new GPSPoint(2.1, 3.1);
            GPSPoint p22   = new GPSPoint(2.2, 3.2);
            GPSPoint p23   = new GPSPoint(2.3, 3.3);

            road2.AddPoint(p21);
            road2.AddPoint(p22);
            road2.AddPoint(p23);

            //为该条路添加可以选择的路
            road2.AddNextRoadName("road3");
            road2.AddNextRoadName("road4");

            route.Add(road2);

            RoadInfo road3 = new RoadInfo("road3");
            GPSPoint p31   = new GPSPoint(3.1, 4.1);
            GPSPoint p32   = new GPSPoint(3.2, 4.2);
            GPSPoint p33   = new GPSPoint(3.3, 4.3);


            road3.AddPoint(p31);
            road3.AddPoint(p32);
            road3.AddPoint(p33);

            route.Add(road3);


            RoadInfo road4 = new RoadInfo("road4");
            GPSPoint p41   = new GPSPoint(4.1, 5.1);
            GPSPoint p42   = new GPSPoint(4.2, 5.2);
            GPSPoint p43   = new GPSPoint(4.3, 5.3);

            road4.AddPoint(p41);
            road4.AddPoint(p42);
            road4.AddPoint(p43);

            route.Add(road4);

            string json = Newtonsoft.Json.JsonConvert.SerializeObject(route);

            Debug.WriteLine(json);
            string serializedRoute = "[{\"RoadName\":\"road1\",\"PointList\":[{\"Lat\":1.1,\"Lng\":2.1,\"IndexInList\":0,\"RoadName\":\"road1\"},{\"Lat\":1.2,\"Lng\":2.2,\"IndexInList\":1,\"RoadName\":\"road1\"},{\"Lat\":1.3,\"Lng\":2.3,\"IndexInList\":2,\"RoadName\":\"road1\"}],\"NextRoadNameList\":[\"road2\"]},{\"RoadName\":\"road2\",\"PointList\":[{\"Lat\":2.1,\"Lng\":3.1,\"IndexInList\":0,\"RoadName\":\"road2\"},{\"Lat\":2.2,\"Lng\":3.2,\"IndexInList\":1,\"RoadName\":\"road2\"},{\"Lat\":2.3,\"Lng\":3.3,\"IndexInList\":2,\"RoadName\":\"road2\"}],\"NextRoadNameList\":[\"road3\",\"road4\"]},{\"RoadName\":\"road3\",\"PointList\":[{\"Lat\":3.1,\"Lng\":4.1,\"IndexInList\":0,\"RoadName\":\"road3\"},{\"Lat\":3.2,\"Lng\":4.2,\"IndexInList\":1,\"RoadName\":\"road3\"},{\"Lat\":3.3,\"Lng\":4.3,\"IndexInList\":2,\"RoadName\":\"road3\"}],\"NextRoadNameList\":[]},{\"RoadName\":\"road4\",\"PointList\":[{\"Lat\":4.1,\"Lng\":5.1,\"IndexInList\":0,\"RoadName\":\"road4\"},{\"Lat\":4.2,\"Lng\":5.2,\"IndexInList\":1,\"RoadName\":\"road4\"},{\"Lat\":4.3,\"Lng\":5.3,\"IndexInList\":2,\"RoadName\":\"road4\"}],\"NextRoadNameList\":[]}]";

            List <RoadInfo> newRoute = (List <RoadInfo>)Newtonsoft.Json.JsonConvert.DeserializeObject <List <RoadInfo> >(serializedRoute);

            Assert.IsTrue(newRoute[0].RoadName == road1.RoadName);
            Assert.IsTrue(newRoute[1].RoadName == road2.RoadName);
            Assert.IsTrue(newRoute[2].RoadName == road3.RoadName);
            Assert.IsTrue(newRoute[3].RoadName == road4.RoadName);
        }
Example #4
0
        public DeviceStatus ParsePosition()
        {
            if (!(new[] { "RPH", "RPI" }.Any(d => _command.StartsWith(d))))
            {
                return(null);
            }
            // RPI 190814161155 -3468748 -05847549 125 000 1 12 0000 1 008 1 1 16 0008042322 EF 27;ID=4629;#LOG:9C78;*72<
            // RPH 141014140025 -3460429 -05837906 145 000 1 03 0000 0 256 1 1 16 0000114489 0F 67;ID=5182;#LOG:506F;*0A<

            #region parse line

            var datetimeStr             = _command.Substring(3, 12);
            var latStr                  = _command.Substring(15, 8);
            var lonStr                  = _command.Substring(23, 9);
            var curseStr                = _command.Substring(32, 3); // Norte = 0, Este = 90, Sur = 180, Oeste = 270
            var speedStr                = _command.Substring(35, 3);
            var gpsOnOffStr             = _command.Substring(38, 1);
            var qSatStr                 = _command.Substring(39, 2);
            var posAgeStr               = _command.Substring(41, 4);
            var oneStr                  = _command.Substring(45, 1);
            var hdopStr                 = _command.Substring(46, 3);
            var gprsWithValidIPOnOffStr = _command.Substring(49, 1);
            var gsmStatusStr            = _command.Substring(50, 1);

            /*
             *  Estado de registro GSM
             *      0 not registered, ME is not currently searching a new operator to register to
             *      1 registered, home network
             *      2 not registered, but ME is currently searching a new operator to register to
             *      3 registration denied
             *      4 unknown
             *      5 registered, roaming
             */
            var gsmSignalStr = _command.Substring(51, 2);

            /*
             *  Nivel de señal GSM
             *      0 -113 dBm o menor
             *      1 -111 dBm
             *      2...30 -109... -53 dBm
             *      31 -51 dBm o mayor
             *      99 no detectado
             */
            var odometerStr = _command.Substring(53, 10);
            var inputsStr   = _command.Substring(63, 2);

            /*
             *  Estado de las entradas digitales en hexadecimal
             *      0x80 Estado de Contacto o Ignición
             *      0x40 Estado de Alimentación Principal
             *      0x20 Entrada digital 5
             *      0x10 Entrada digital 4
             *      0x08 Entrada digital 3
             *      0x04 Entrada digital 2
             *      0x02 Entrada digital 1
             *      0x01 Entrada digital 0
             */
            var eventStr = _command.Substring(65, 2);

            #endregion parse line
            // -----------------------

            var time     = DateTimeUtils.SafeParseFormat(datetimeStr, "ddMMyyHHmmss");
            var lat      = Convert.ToSingle(latStr) * (float)0.00001;
            var lon      = Convert.ToSingle(lonStr) * (float)0.00001;
            var vel      = Convert.ToSingle(speedStr);
            var dir      = Convert.ToSingle(curseStr); // (0 ..359), Norte = 0, Este = 90, Sur = 180, Oeste = 270
            var hdop     = Convert.ToSingle(hdopStr) / 10;
            var entradas = Convert.ToByte(inputsStr, 16);
            var evento   = Convert.ToByte(eventStr);
            var posEdad  = Convert.ToInt32(posAgeStr);

            var devId = (Int32?)null;

            if (_node != null)
            {
                devId = _node.Id;
            }

            GPSPoint gpoint = null;
            try
            {
                gpoint = new GPSPoint(time, lat, lon, vel, GPSPoint.SourceProviders.Unespecified, 0)
                {
                    Age            = posEdad,
                    Course         = new Course(dir),
                    HDOP           = hdop,
                    IgnitionStatus = BitHelper.AreBitsSet(entradas, 0x80) ? IgnitionStatus.On : IgnitionStatus.Off
                };
                if (devId != null)
                {
                    gpoint.DeviceId = devId.Value;
                }
            }
            catch (ArgumentOutOfRangeException e)
            {
                STrace.Exception(typeof(VirlocDeviceCommand).FullName, e, IdNum ?? 0, String.Format("Posición inválida {0}", getCommand()));
                gpoint = null;
            }

            var result = new DeviceStatus(devId, gpoint, evento, entradas);
            return(result);
        }
Example #5
0
 public LogPosicionDescartada(GPSPoint position, Coche coche, DiscardReason reasonCode)
     : base(position, coche)
 {
     MotivoDescarte = (int)reasonCode;
 }
Example #6
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);
        }
Example #7
0
 /// <summary>
 /// Determines if the givenn position is out of range.
 /// </summary>
 /// <param name="posicion"></param>
 /// <returns></returns>
 protected static bool FueraDelGlobo(GPSPoint posicion)
 {
     return(posicion.Lat == 0 || Math.Abs(posicion.Lat) > 90 || posicion.Lon == 0 || Math.Abs(posicion.Lon) > 180);
 }
Example #8
0
 public static Event FactoryEvent(this MessageIdentifier code, MessageIdentifier generic, int deviceId, ulong msgId, GPSPoint pos, DateTime dt, String rfid, IEnumerable <Int64> data)
 {
     return(new Event((short)generic, (short)code, deviceId, msgId, pos, dt, rfid, data, true));
 }
Example #9
0
 public void ActiveOT(GPSPoint last_point, int active_ot)
 {
     var dummy = new byte[1];
     //saliente.Push(String.Format("{0};ESTADO;0;{1}", IdDispositivo,
     ///                           DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")), dummy);
 }
Example #10
0
        public LogMensajeBase Save(IMessage evento, string codigo, Dispositivo dispositivo, Coche coche, Empleado chofer, DateTime fecha, GPSPoint inicio, GPSPoint fin, string texto, int?velPermitida, int?velAlcanzada, int?idReferenciaGeografica, Zona zonaManejo, ViajeDistribucion viaje, EntregaDistribucion entrega)
        {
            try
            {
                var device = dispositivo ?? DaoFactory.DispositivoDAO.GetGenericDevice(coche.Empresa);
                var driver = chofer ?? (coche != null && !coche.IdentificaChoferes ? coche.Chofer : null);

                if (string.IsNullOrEmpty(codigo.Trim()))
                {
                    return(null);
                }
                var mensaje = DaoFactory.MensajeDAO.GetByCodigo(codigo, coche != null ? coche.Empresa : null, coche != null ? coche.Linea : null);
                if (mensaje == null)
                {
                    return(DiscardDueToInvalidMessage(codigo, coche, inicio, device, fin, driver, fecha));
                }

                var ticket        = DaoFactory.TicketDAO.FindEnCurso(dispositivo);
                var detalleTicket = ticket == null ? null : ticket.GetDetalleProximo();
                driver = driver ?? (ticket != null ? ticket.Empleado : null);

                if (mensaje.Acceso >= Usuario.NivelAcceso.SysAdmin)
                {
                    return(null);

                    //var log = new LogMensajeAdmin
                    //{
                    //    Chofer = driver,
                    //    Coche = coche,
                    //    Dispositivo = device,
                    //    Estado = 0,
                    //    Fecha = fecha,
                    //    FechaAlta = DateTime.UtcNow,
                    //    Expiracion = DateTime.UtcNow.AddDays(1),
                    //    Horario = ticket,
                    //    DetalleHorario = detalleTicket,
                    //    Usuario = null,
                    //    Latitud = inicio != null ? inicio.Lat : 0,
                    //    Longitud = inicio != null ? inicio.Lon : 0,
                    //    FechaFin = fin != null ? fin.Date : (DateTime?)null,
                    //    LatitudFin = fin != null ? new Double?(fin.Lat) : null,
                    //    LongitudFin = fin != null ? new Double?(fin.Lon) : null,
                    //    VelocidadAlcanzada = velAlcanzada,
                    //    VelocidadPermitida = velPermitida,
                    //    IdPuntoDeInteres = idReferenciaGeografica,
                    //    Mensaje = DaoFactory.MensajeDAO.FindById(mensaje.Id),
                    //    Texto = String.Concat(mensaje.Texto, ' ', texto),
                    //    TieneFoto = codigo == ((int)MessageIdentifier.Picture).ToString(CultureInfo.InvariantCulture)
                    //};

                    //ProcessActions(log);

                    //return log;
                }
                else
                {
                    var log = new LogMensaje
                    {
                        Chofer             = driver,
                        Coche              = coche,
                        Dispositivo        = device,
                        Estado             = 0,
                        Fecha              = fecha,
                        FechaAlta          = DateTime.UtcNow,
                        Expiracion         = DateTime.UtcNow.AddDays(1),
                        Horario            = ticket,
                        DetalleHorario     = detalleTicket,
                        Usuario            = null,
                        Latitud            = inicio != null ? inicio.Lat : 0,
                        Longitud           = inicio != null ? inicio.Lon : 0,
                        FechaFin           = fin != null ? fin.Date : (DateTime?)null,
                        LatitudFin         = fin != null ? new Double?(fin.Lat) : null,
                        LongitudFin        = fin != null ? new Double?(fin.Lon) : null,
                        VelocidadAlcanzada = velAlcanzada,
                        VelocidadPermitida = velPermitida,
                        IdPuntoDeInteres   = idReferenciaGeografica,
                        Mensaje            = DaoFactory.MensajeDAO.FindById(mensaje.Id),
                        Texto              = String.Concat(mensaje.Texto, ' ', texto),
                        TieneFoto          = codigo == ((int)MessageIdentifier.Picture).ToString(CultureInfo.InvariantCulture),
                        Viaje              = viaje,
                        Entrega            = entrega
                    };

                    ProcessActions(log);

                    if (MessageIdentifierX.IsEngineOnOffEvent(log.Mensaje))
                    {
                        DaoFactory.LastVehicleEventDAO.Save(log, Coche.Totalizador.EstadoMotor);
                    }
                    else if (MessageIdentifierX.IsGarminOnOffEvent(log.Mensaje))
                    {
                        DaoFactory.LastVehicleEventDAO.Save(log, Coche.Totalizador.EstadoGarmin);
                    }
                    else if (MessageIdentifierX.IsPrivacyOnOffEvent(log.Mensaje))
                    {
                        DaoFactory.LastVehicleEventDAO.Save(log, Coche.Totalizador.EstadoGps);
                    }

                    return(log);
                }
            }
            catch (Exception ex)
            {
                STrace.Exception(GetType().FullName, ex);

                return(null);
            }
        }
Example #11
0
 public LogMensajeBase Save(IMessage evento, string codigo, Dispositivo dispositivo, Coche coche, Empleado chofer, DateTime fecha, GPSPoint inicio, GPSPoint fin, string texto, int?velPermitida, int?velAlcanzada, int?idReferenciaGeografica, Zona zonaManejo)
 {
     return(Save(evento, codigo, dispositivo, coche, chofer, fecha, inicio, fin, texto, velPermitida, velAlcanzada, idReferenciaGeografica, zonaManejo, null, null));
 }
Example #12
0
 public LogMensajeBase Save(IMessage evento, string codigo, Dispositivo dispositivo, Coche coche, Empleado chofer, DateTime fecha, GPSPoint inicio, string texto, int idReferenciaGeografica)
 {
     return(Save(evento, codigo, dispositivo, coche, chofer, fecha, inicio, null, texto, null, null, idReferenciaGeografica));
 }
Example #13
0
 public LogMensajeBase Save(IMessage evento, string codigo, Dispositivo dispositivo, Coche coche, Empleado chofer, DateTime fecha, GPSPoint inicio, GPSPoint fin, string texto, int velPermitida, int velAlcanzada)
 {
     return(Save(evento, codigo, dispositivo, coche, chofer, fecha, inicio, fin, texto, velPermitida, velAlcanzada, null));
 }
Example #14
0
 public LogMensajeBase Save(IMessage evento, string codigo, Dispositivo dispositivo, Coche coche, Empleado chofer, DateTime fecha, GPSPoint inicio, string texto, Zona zonaManejo)
 {
     return(Save(evento, codigo, dispositivo, coche, chofer, fecha, inicio, null, texto, null, null, null, zonaManejo));
 }
Example #15
0
 public void AddLocation(GPSPoint point)
 {
     throw new NotImplementedException();
 }
Example #16
0
        public static EstadoVehiculo Process(Coche vehiculo, GPSPoint position, DAOFactory daoFactory)
        {
            if (vehiculo == null || position == null)
            {
                return(null);
            }

            var t = new TimeElapsed();
            var estadoAnterior = GetEstadoVehiculo(vehiculo, daoFactory);

            if (t.getTimeElapsed().TotalSeconds > 0.5)
            {
                STrace.Debug("DispatcherLock", vehiculo.Dispositivo.Id, String.Format("GeocercaManager.Process/GetEstadoVehiculo ({0} secs)", t.getTimeElapsed().TotalSeconds));
            }

            t.Restart();
            var estadoActual = CalcularEstadoVehiculo(vehiculo, position, daoFactory);

            if (t.getTimeElapsed().TotalSeconds > 0.5)
            {
                STrace.Debug("DispatcherLock", vehiculo.Dispositivo.Id, String.Format("GeocercaManager.Process/CalcularEstadoVehiculo ({0} secs)", t.getTimeElapsed().TotalSeconds));
            }

            t.Restart();
            var geocercasAnterior = new Dictionary <int, EstadoGeocerca>();
            var geocercasActual   = new Dictionary <int, EstadoGeocerca>();

            if (estadoAnterior != null)
            {
                foreach (var estadoGeocerca in estadoAnterior.GeocercasDentro)
                {
                    if (!geocercasAnterior.ContainsKey(estadoGeocerca.Geocerca.Id))
                    {
                        geocercasAnterior.Add(estadoGeocerca.Geocerca.Id, estadoGeocerca);
                    }
                }
            }
            else
            {
                geocercasAnterior = null;
            }

            foreach (var estadoGeocerca in estadoActual.GeocercasDentro)
            {
                if (!geocercasActual.ContainsKey(estadoGeocerca.Geocerca.Id))
                {
                    geocercasActual.Add(estadoGeocerca.Geocerca.Id, estadoGeocerca);
                }
            }
            var geocercasTodas = geocercasAnterior != null?geocercasAnterior.Keys.Union(geocercasActual.Keys) : geocercasActual.Keys;

            if (t.getTimeElapsed().TotalSeconds > 1)
            {
                STrace.Debug("DispatcherLock", vehiculo.Dispositivo.Id, String.Format("GeocercaManager.Process/Part #1 ({0} secs)", t.getTimeElapsed().TotalSeconds));
            }

            foreach (var geocerca in geocercasTodas)
            {
                t.Restart();
                var anterior = geocercasAnterior != null && geocercasAnterior.ContainsKey(geocerca) ? geocercasAnterior[geocerca] : null;
                var actual   = geocercasActual.ContainsKey(geocerca) ? geocercasActual[geocerca] : new EstadoGeocerca {
                    Geocerca = anterior != null ? anterior.Geocerca : null, Estado = EstadosGeocerca.Fuera
                };
                if (t.getTimeElapsed().TotalSeconds > 1)
                {
                    STrace.Debug("DispatcherLock", vehiculo.Dispositivo.Id, String.Format("GeocercaManager.Process/ForEach Part #1 ({0} secs)", t.getTimeElapsed().TotalSeconds));
                }

                t.Restart();
                if (anterior != null && anterior.Geocerca != null && !anterior.Geocerca.IsVigente(position.Date))
                {
                    continue;
                }
                if (actual.Geocerca != null && !actual.Geocerca.IsVigente(position.Date))
                {
                    continue;
                }
                if (t.getTimeElapsed().TotalSeconds > 1)
                {
                    STrace.Debug("DispatcherLock", vehiculo.Dispositivo.Id, String.Format("GeocercaManager.Process/ForEach Part #2 ({0} secs)", t.getTimeElapsed().TotalSeconds));
                }

                t.Restart();
                var antesDentro = anterior != null;
                var dentro      = actual.Estado == EstadosGeocerca.Dentro;

                var sale  = antesDentro && !dentro;
                var entra = !antesDentro && dentro;

                if (t.getTimeElapsed().TotalSeconds > 1)
                {
                    STrace.Debug("DispatcherLock", vehiculo.Dispositivo.Id, String.Format("GeocercaManager.Process/ForEach Part #3 ({0} secs)", t.getTimeElapsed().TotalSeconds));
                }

                if (actual.Geocerca != null)
                {
                    t.Restart();
                    if (sale && actual.Geocerca.ControlaEntradaSalida)
                    {
                        estadoActual.Eventos.Add(new GeocercaEvent {
                            Evento = GeocercaEventState.Sale, Estado = actual
                        });
                    }
                    if (sale && (actual.Geocerca.EsInicio || actual.Geocerca.EsIntermedio || actual.Geocerca.EsFin))
                    {
                        estadoActual.Eventos.Add(new GeocercaEvent {
                            Evento = GeocercaEventState.TimeTrackingSalida, Estado = actual
                        });
                    }
                    if (entra && actual.Geocerca.ControlaEntradaSalida)
                    {
                        estadoActual.Eventos.Add(new GeocercaEvent {
                            Evento = GeocercaEventState.Entra, Estado = actual
                        });
                    }
                    if (entra && (actual.Geocerca.EsInicio || actual.Geocerca.EsIntermedio || actual.Geocerca.EsFin))
                    {
                        estadoActual.Eventos.Add(new GeocercaEvent {
                            Evento = GeocercaEventState.TimeTrackingEntrada, Estado = actual
                        });
                    }
                    if (t.getTimeElapsed().TotalSeconds > 1)
                    {
                        STrace.Debug("DispatcherLock", vehiculo.Dispositivo.Id, String.Format("GeocercaManager.Process/ForEach Part #4 ({0} secs)", t.getTimeElapsed().TotalSeconds));
                    }

                    if (actual.Geocerca.ControlaVelocidad)
                    {
                        t.Restart();
                        var antesExcedido = anterior != null && anterior.EnExcesoVelocidad;
                        var excedido      = actual.VelocidadMaxima > 0 && position.Velocidad > actual.VelocidadMaxima;
                        if (t.getTimeElapsed().TotalSeconds > 1)
                        {
                            STrace.Debug("DispatcherLock", vehiculo.Dispositivo.Id, String.Format("GeocercaManager.Process/ForEach Part #5 ({0} secs)", t.getTimeElapsed().TotalSeconds));
                        }
                        t.Restart();
                        if (dentro && !antesExcedido && excedido)
                        {
                            actual.InicioExceso(position);
                            if (t.getTimeElapsed().TotalSeconds > 1)
                            {
                                STrace.Debug("DispatcherLock", vehiculo.Dispositivo.Id, String.Format("GeocercaManager.Process/ForEach Part #6 (InicioExceso) ({0} secs)", t.getTimeElapsed().TotalSeconds));
                            }
                        }
                        else if (excedido)
                        {
                            actual.UpdateVelocidadPico(position.Velocidad);
                            if (t.getTimeElapsed().TotalSeconds > 1)
                            {
                                STrace.Debug("DispatcherLock", vehiculo.Dispositivo.Id, String.Format("GeocercaManager.Process/ForEach Part #7 (Excedido) ({0} secs)", t.getTimeElapsed().TotalSeconds));
                            }
                        }
                        t.Restart();
                        if (antesExcedido && (!dentro || !excedido))
                        {
                            estadoActual.Eventos.Add(new GeocercaEvent {
                                Evento = GeocercaEventState.ExcesoVelocidad, Estado = actual.Clone()
                            });
                            actual.FinExceso();
                            if (t.getTimeElapsed().TotalSeconds > 1)
                            {
                                STrace.Debug("DispatcherLock", vehiculo.Dispositivo.Id, String.Format("GeocercaManager.Process/ForEach Part #8 (FinExceso) ({0} secs)", t.getTimeElapsed().TotalSeconds));
                            }
                        }
                    }

                    if (antesDentro && !sale)
                    {
                        // Controla Permanencia en Geocerca
                        if (actual.Geocerca.ControlaPermanencia)
                        {
                            var entrada = daoFactory.LogMensajeDAO.GetLastGeoRefferenceEventDate(vehiculo, MessageCode.InsideGeoRefference.GetMessageCode(), actual.Geocerca.Id);
                            if (entrada.HasValue)
                            {
                                t.Restart();
                                var ultimaAlarma = daoFactory.LogMensajeDAO.GetLastGeoRefferenceEventDate(vehiculo, MessageCode.PermanenciaEnGeocercaExcedida.GetMessageCode(), actual.Geocerca.Id, entrada.Value);
                                if (t.getTimeElapsed().TotalSeconds > 1)
                                {
                                    STrace.Debug("DispatcherLock", vehiculo.Dispositivo.Id, String.Format("GeocercaManager.ProcessLogMensajeDAO.GetLastGeoRefferenceEventDate 1 ({0} secs)", t.getTimeElapsed().TotalSeconds));
                                }
                                if (!ultimaAlarma.HasValue)
                                {
                                    var tiempoActual = position.Date.Subtract(entrada.Value);
                                    if (tiempoActual.TotalMinutes > actual.Geocerca.MaximaPermanencia)
                                    {
                                        actual.PosicionInicioExceso = position;
                                        estadoActual.Eventos.Add(new GeocercaEvent {
                                            Evento = GeocercaEventState.ExcesoPermanencia, Estado = actual
                                        });
                                    }
                                }
                            }
                        }

                        // Controla Permanencia en Geocerca en Ciclo Logístico
                        if (actual.Geocerca.ControlaPermanenciaEntrega)
                        {
                            t.Restart();
                            var ticket = daoFactory.TicketDAO.FindEnCurso(vehiculo.Dispositivo);
                            if (t.getTimeElapsed().TotalSeconds > 1)
                            {
                                STrace.Debug("DispatcherLock", vehiculo.Dispositivo.Id, String.Format("GeocercaManager.Process/TicketDAO.FindEnCurso ({0} secs)", t.getTimeElapsed().TotalSeconds));
                            }
                            t.Restart();
                            var distri = daoFactory.ViajeDistribucionDAO.FindEnCurso(vehiculo);
                            if (t.getTimeElapsed().TotalSeconds > 1)
                            {
                                STrace.Debug("DispatcherLock", vehiculo.Dispositivo.Id, String.Format("GeocercaManager.Process/ViajeDistribucionDAO.FindEnCurso ({0} secs)", t.getTimeElapsed().TotalSeconds));
                            }
                            if (ticket != null || distri != null)
                            {
                                var entrada = daoFactory.LogMensajeDAO.GetLastGeoRefferenceEventDate(vehiculo, MessageCode.InsideGeoRefference.GetMessageCode(), actual.Geocerca.Id);
                                if (entrada.HasValue)
                                {
                                    var inicio = entrada.Value;

                                    if (ticket != null && ticket.FechaTicket.HasValue && ticket.FechaTicket.Value > inicio)
                                    {
                                        inicio = ticket.FechaTicket.Value;
                                    }
                                    if (distri != null && distri.InicioReal.HasValue && distri.InicioReal.Value > inicio)
                                    {
                                        inicio = distri.InicioReal.Value;
                                    }

                                    t.Restart();
                                    var ultimaAlarma = daoFactory.LogMensajeDAO.GetLastGeoRefferenceEventDate(vehiculo, MessageCode.PermanenciaEnGeocercaExcedidaEnCicloLogistico.GetMessageCode(), actual.Geocerca.Id, entrada.Value);
                                    if (t.getTimeElapsed().TotalSeconds > 1)
                                    {
                                        STrace.Debug("DispatcherLock", vehiculo.Dispositivo.Id, String.Format("GeocercaManager.ProcessLogMensajeDAO.GetLastGeoRefferenceEventDate 2 ({0} secs)", t.getTimeElapsed().TotalSeconds));
                                    }
                                    if (!ultimaAlarma.HasValue)
                                    {
                                        var tiempoActual = position.Date.Subtract(inicio);
                                        if (tiempoActual.TotalMinutes > actual.Geocerca.MaximaPermanenciaEntrega)
                                        {
                                            actual.PosicionInicioExceso = position;
                                            estadoActual.Eventos.Add(new GeocercaEvent {
                                                Evento = GeocercaEventState.ExcesoPermanenciaEntrega, Estado = actual
                                            });
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            estadoActual.Save();
            return(estadoActual);
        }
		public float DistanceMetersToPoint(IGPSPoint point) {
			GPSPoint thisPoint = new GPSPoint(
				this.LatitudeDegrees,
				this.LongitudeDegrees,
				0);
            if (point == null)
            {
                return float.MaxValue;
            }
			return point.DistanceMetersToPoint(thisPoint);
		}
Example #18
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);
        }
Example #19
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);
            }
        }
Example #20
0
        public void Discard(string codigo, Dispositivo dispositivo, Sensor sensor, DateTime fecha, GPSPoint inicio, GPSPoint fin, DiscardReason discardReason)
        {
            var mensaje = !String.IsNullOrEmpty(codigo) ? GetByCodigo(codigo, sensor) : null;

            DiscardEvent(mensaje, dispositivo, null, null, fecha, inicio, fin, discardReason, codigo);
        }
Example #21
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);*/
        }
Example #22
0
        private static IMessage FactoryHandShake(Parser dev, String[] data, ulong msgId, GPSPoint pos, IDataProvider dataProvider)
        {
            if (ParserUtils.IsInvalidDeviceId(dev.Id))
            {
                return(null);
            }

            var msg = new ConfigRequest(dev.Id, msgId);

            if (pos != null)
            {
                msg.GeoPoint = pos;
            }

            msg.AddStringToSend(Factory <String>(msgId, dev, "AH,0,{0:D4},{1}", dev.Id, DateTime.UtcNow.ToUnixTimeStamp()));

            //check Telephone
            if (data.Length > 4)
            {
                var   phone = data[4].TrimStart("+".ToCharArray());
                Int64 number;
                if (!String.IsNullOrEmpty(phone) && Int64.TryParse(phone, out number) && number > 0)
                {
                    var oldnumber = dataProvider.GetDetalleDispositivo(dev.Id, "Telephone").As("null");
                    if (oldnumber != phone)
                    {
                        STrace.Debug(typeof(Parser).FullName, dev.Id, String.Format("Setting Telephone: {0}", phone));
                        dataProvider.SetDetalleDispositivo(dev.Id, "Telephone", phone, "string");
                    }
                }
            }

            //check config_revision
            if (data.Length > 3)
            {
                var revision    = data[3];
                var oldrevision = dataProvider.GetDetalleDispositivo(dev.Id, "config_revision").As("");
                if (oldrevision != revision && !String.IsNullOrEmpty(revision))
                {
                    STrace.Debug(typeof(Parser).FullName, dev.Id, String.Format("Setting config_revision: {0}", revision));
                    //todo: update config
                    //DataProvider.SetDetalleDispositivo(Id, "config_revision", revision, "int");
                }
            }

            return(msg);
        }
Example #23
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));
        }
Example #24
0
        private static IMessage FactoryMensaje(Parser dev, String[] data, ulong msgId, GPSPoint pos)
        {
            IMessage msg;
            var      extra = (data.SingleOrDefault(s => s.StartsWith("rt")) != null) ? ",t=" + DateTime.UtcNow.ToUnixTimeStamp() : "";

            var t    = DateTimeUtils.SafeParseFormat(data[7], "ddMMyyHHmmss");
            var tmc  = (MessageIdentifier)Convert.ToInt16(data[8], CultureInfo.InvariantCulture);
            var body = data[9];

            if (tmc == MessageIdentifier.ReservedDoNotUse)
            {
                msg = new TextEvent(dev.Id, msgId, t)
                {
                    Text     = HttpUtility.UrlDecode(body),
                    GeoPoint = pos,
                };
            }
            else
            {
                msg = tmc.FactoryEvent(dev.Id, msgId, pos, t, null, null);
            }
            return(msg.AddStringToSend(Factory <String>(msgId, dev, "AM,0,{0},{1}{2}", data[2], data[4], extra)));
        }
Example #25
0
    IEnumerator GetReverseCleanPOI(BTCleanPOI poi, OnSuccessAddressCleanPOI callback)
    {
        if (poi == null)
        {
            ready = false;
            yield return(null);
        }
        Succes = false;
        string surl = string.Format("{0}?format=jsonv2&lat={1}&lon={2}&zoom={3}&addressdetails=1", url, GPSPoint.GetDoubleValue(poi.Latitude), GPSPoint.GetDoubleValue(poi.Longitude), zoomlevel);

        // email is necessary, for this service to work as stated in it's web site
        if (string.IsNullOrEmpty(email) == false)
        {
            surl = string.Format("{0}&email={1}", surl, email);
        }

        UnityWebRequest www = UnityWebRequest.Get(surl);

        yield return(www.SendWebRequest());

        while (!www.isDone)
        {
            yield return(null);
        }
        if (www.isNetworkError || www.isHttpError)
        {
            Succes = false;
            Debug.Log(www.error);
            LogManager.Instance.AddLog(string.Format("Error: Calling Reverse GPS Service: {0}", www.error));
            ready = false;
            yield return(null);
        }
        byte[]     resultdata = www.downloadHandler.data;
        string     POIJSON    = System.Text.Encoding.Default.GetString(resultdata);
        ReverseGPS revgps     = JsonUtility.FromJson <ReverseGPS>(POIJSON);

        Succes = true;

        ready = true;
        // update flag from global setting
        if (SaveReveseAddressToDatabase != GameManager.Instance.Setting.SaveReversePOIToSQLite)
        {
            SaveReveseAddressToDatabase = GameManager.Instance.Setting.SaveReversePOIToSQLite;
        }
        // now save this to database
        if (SaveReveseAddressToDatabase)
        {
            POIAddress poiad = POIAddress.GetPOIFromAddress(revgps.address, poi);
            try
            {
                if (db != null)
                {
                    // check if POI already exists in SQLite DB
                    POIAddress ad = db.GetPoiAddressByID(poi.ID);
                    if (ad == null)
                    {
                        db.InsertPoiAddress(poiad);
                        LogManager.Instance.AddLog(string.Format("Success insert to SQLite Poi: {0}", poi.ID));
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.Instance.AddLog(string.Format("Failed insert to SQLite Poi: {0} - {1}", poi.ID, ex.Message));
            }
        }
        // update the caller thru callback
        if (callback != null)
        {
            callback(poi, revgps.address);
        }
    }
Example #26
0
        public static void Process(DAOFactory daoFactory, string codigo, Coche vehiculo, GPSPoint point, IMessage message, bool ignoreMessages, Empleado chofer)
        {
            try
            {
                // Si no es uno de los codigos que cambian estados automáticos, salgo directamente;))
                if (!IsAutomaticCode(codigo))
                {
                    return;
                }

                var evento = EventFactory.GetEvent(daoFactory, point, codigo, null, message, vehiculo, chofer);
                if (evento == null)
                {
                    return;
                }

                Process(vehiculo, evento, ignoreMessages);
            }
            catch (Exception ex)
            {
                STrace.Exception(typeof(CicloLogisticoFactory).FullName, ex, "Code: " + (codigo ?? "null") + " vehicle: " + (vehiculo == null ? "null" : vehiculo.Id.ToString("#0")) + " message:" + (message == null ? "null" : message.ToString()) + " gpspoint:" + (point == null ? "null" : point.ToString()));
            }
        }
 public GPSPointViewModel(GPSPoint point)
 {
     this.point = point;
 }
Example #28
0
 public void InicioExceso(GPSPoint posicion)
 {
     EnExcesoVelocidad    = true;
     PosicionInicioExceso = posicion;
     VelocidadPico        = Math.Max(VelocidadPico, posicion.Velocidad);
 }
Example #29
0
        public void TestPlayRoad()
        {
            //初始化一条路线,是由多条路组成的
            List <RoadInfo> roads = new List <RoadInfo>();

            //初始化一条路,并为其添加一些关键点
            RoadInfo road1 = new RoadInfo("road1");
            GPSPoint p11   = new GPSPoint(1.1, 2.1);
            GPSPoint p12   = new GPSPoint(1.2, 2.2);
            GPSPoint p13   = new GPSPoint(1.3, 2.3);

            road1.AddPoint(p11);
            road1.AddPoint(p12);
            road1.AddPoint(p13);

            road1.AddNextRoadName("road2");
            roads.Add(road1);

            RoadInfo road2 = new RoadInfo("road2");
            GPSPoint p21   = new GPSPoint(2.1, 3.1);
            GPSPoint p22   = new GPSPoint(2.2, 3.2);
            GPSPoint p23   = new GPSPoint(2.3, 3.3);

            road2.AddPoint(p21);
            road2.AddPoint(p22);
            road2.AddPoint(p23);

            //为该条路添加可以选择的路
            road2.AddNextRoadName("road3");
            road2.AddNextRoadName("road4");

            roads.Add(road2);

            RoadInfo road3 = new RoadInfo("road3");
            GPSPoint p31   = new GPSPoint(3.1, 4.1);
            GPSPoint p32   = new GPSPoint(3.2, 4.2);
            GPSPoint p33   = new GPSPoint(3.3, 4.3);


            road3.AddPoint(p31);
            road3.AddPoint(p32);
            road3.AddPoint(p33);

            roads.Add(road3);


            RoadInfo road4 = new RoadInfo("road4");
            GPSPoint p41   = new GPSPoint(4.1, 5.1);
            GPSPoint p42   = new GPSPoint(4.2, 5.2);
            GPSPoint p43   = new GPSPoint(4.3, 5.3);

            road4.AddPoint(p41);
            road4.AddPoint(p42);
            road4.AddPoint(p43);

            roads.Add(road4);

            //添加运行到关键点的事件响应
            Action <GPSPoint> ringer = _point =>
            {
                Debug.WriteLine(_point.FormatPointString());
            };

            //添加当该条路线有继续运行的路时的事件响应
            Action <List <string> > RoadSelectRinger = _list =>
            {
                //打印出可以选择的道路
                foreach (string s in _list)
                {
                    Debug.WriteLine("next road => " + s);
                }
            };

            RoadPlayer player    = RoadPlayer.InitializeRoadPlayer(roads, ringer, RoadSelectRinger);
            GPSPoint   pointTemp = player.Play();

            Assert.IsTrue(pointTemp.RoadName == road1.RoadName && pointTemp.IndexInList == 0 && pointTemp.Lat == p11.Lat && pointTemp.Lng == p11.Lng);

            pointTemp = player.Play(pointTemp);
            Assert.IsTrue(pointTemp.RoadName == road1.RoadName && pointTemp.IndexInList == 1 && pointTemp.Lat == p12.Lat && pointTemp.Lng == p12.Lng);

            pointTemp = player.Play(pointTemp);
            Assert.IsTrue(pointTemp.RoadName == road1.RoadName && pointTemp.IndexInList == 2 && pointTemp.Lat == p13.Lat && pointTemp.Lng == p13.Lng);

            pointTemp = player.Play(pointTemp);
            Assert.IsTrue(pointTemp.RoadName == road2.RoadName && pointTemp.IndexInList == 0 && pointTemp.Lat == p21.Lat && pointTemp.Lng == p21.Lng);
            pointTemp = player.Play(pointTemp);
            Assert.IsTrue(pointTemp.RoadName == road2.RoadName && pointTemp.IndexInList == 1 && pointTemp.Lat == p22.Lat && pointTemp.Lng == p22.Lng);
            pointTemp = player.Play(pointTemp);
            Assert.IsTrue(pointTemp.RoadName == road2.RoadName && pointTemp.IndexInList == 2 && pointTemp.Lat == p23.Lat && pointTemp.Lng == p23.Lng);

            player.SetNextRoadName("road4");

            pointTemp = player.Play(pointTemp);
            Assert.IsTrue(pointTemp.RoadName == road4.RoadName && pointTemp.IndexInList == 0 && pointTemp.Lat == p41.Lat && pointTemp.Lng == p41.Lng);

            pointTemp = player.Play(pointTemp);
            Assert.IsTrue(pointTemp.RoadName == road4.RoadName && pointTemp.IndexInList == 1 && pointTemp.Lat == p42.Lat && pointTemp.Lng == p42.Lng);
        }
Example #30
0
 public void ShowGpsPoint(GPSPoint point)
 {
     map.PlaceCurrentPointDot(point);
 }
Example #31
0
        private int UnscaledMapImageHeight(double routeHeightLat, int zoomLevel)
        {
            //m/px
            double[] zoomScales =
            {
                    21282,
                    16355,
                    10064,
                    5540,
                    2909,
                    1485,
                    752,
                    378,
                    190,
                    95,
                    48,
                    24,
                    12,
                    6,
                    3,
                    1.48,
                    0.74,
                    0.37,
                    0.19
            };
            var origin = new GPSPoint(0, 0, 0, 0);
            var height = new GPSPoint(0, routeHeightLat, 0, 0);
            double distance = origin.DistanceFromPoint(height);
            double scale = zoomScales[zoomLevel - 1];
            var result = (int)Math.Round(distance / scale);

            //TODO: real fix, remove this hack.
            var quickDemoHack = new Dictionary<int, int>();
            quickDemoHack.Add(12, 10);
            quickDemoHack.Add(13, 29);
            quickDemoHack.Add(14, 75);

            return result;// - quickDemoHack[zoomLevel];
        }
Example #32
0
 public LocationPointWithId(GPSPoint station)
 {
     latitude  = station.lat;
     longitude = station.lon;
 }
Example #33
0
        public static EstadoVehiculo CalcularEstadoVehiculo(Coche vehiculo, GPSPoint position, DAOFactory daoFactory)
        {
            if (vehiculo == null || position == null)
            {
                return(null);
            }
            var estadoVehiculo = new EstadoVehiculo(vehiculo)
            {
                Posicion = position
            };
            var t = new TimeElapsed();

            lock (GetLock(vehiculo.Id))
            {
                if (t.getTimeElapsed().TotalSeconds > 0.5)
                {
                    STrace.Error("DispatcherLock", vehiculo.Dispositivo.Id, String.Format("CalcularEstadoVehiculo/EntroAlLock ({0} secs)", t.getTimeElapsed().TotalSeconds));
                }

                t.Restart();
                var qtree = GetQtree(vehiculo);
                if (t.getTimeElapsed().TotalSeconds > 0.5)
                {
                    STrace.Error("DispatcherLock", vehiculo.Dispositivo.Id, String.Format("CalcularEstadoVehiculo/GetQTree ({0} secs)", t.getTimeElapsed().TotalSeconds));
                }
                var geocercas = qtree != null && qtree.GetData(position.Lat, position.Lon) != null
                                    ? qtree.GetData(position.Lat, position.Lon) : new List <Geocerca>(0);

                t.Restart();
                if (vehiculo.Empresa.EvaluaSoloGeocercasViaje)
                {
                    var viajeActivo = daoFactory.ViajeDistribucionDAO.FindEnCurso(vehiculo);
                    if (viajeActivo != null)
                    {
                        var tiposGeocercaViaje = vehiculo.Empresa.TiposGeocercaViaje;
                        var idGeocercas        = geocercas.Where(g => !tiposGeocercaViaje.Contains(g.TipoReferenciaGeograficaId)).Select(g => g.Id).ToList();

                        var idsEntregas = viajeActivo.Detalles.Select(d => d.ReferenciaGeografica.Id).Distinct().ToList();

                        idGeocercas.AddRange(idsEntregas);
                        idGeocercas = idGeocercas.Distinct().ToList();

                        var faltantes = idsEntregas.Where(id => !idGeocercas.Contains(id));
                        if (faltantes.Any())
                        {
                            if (vehiculo.Empresa.Id == 92)
                            {
                                STrace.Error("ResetQtree", string.Format("Actual: {0} - Faltantes: {1}", geocercas.Count, faltantes.Count()));
                            }
                            foreach (var idGeocerca in faltantes)
                            {
                                try
                                {
                                    var geocerca = daoFactory.ReferenciaGeograficaDAO.FindGeocerca(idGeocerca);
                                    geocercas.Add(geocerca);
                                }
                                catch { }
                            }
                            if (vehiculo.Empresa.Id == 92)
                            {
                                STrace.Error("ResetQtree", "Total: " + geocercas.Count);
                            }
                        }

                        geocercas = geocercas.Where(g => idGeocercas.Contains(g.Id)).ToList();
                        if (t.getTimeElapsed().TotalSeconds > 0.5)
                        {
                            STrace.Error("DispatcherLock", vehiculo.Dispositivo.Id, String.Format("GeocercasViaje: {0} segundos", t.getTimeElapsed().TotalSeconds));
                        }
                    }
                }

                t.Restart();
                foreach (var geocerca in geocercas)
                {
                    var estadoGeocerca = new EstadoGeocerca {
                        Geocerca = geocerca
                    };
                    var inside = IsInside(geocerca, position.Lat, position.Lon);
                    if (!inside)
                    {
                        continue;
                    }

                    estadoGeocerca.Estado = EstadosGeocerca.Dentro;
                    if (geocerca.ControlaVelocidad)
                    {
                        estadoGeocerca.VelocidadMaxima      = geocerca.GetVelocidadMaxima(vehiculo.Id);
                        estadoGeocerca.EnExcesoVelocidad    = geocerca.ControlaVelocidad && position.Velocidad > estadoGeocerca.VelocidadMaxima;
                        estadoGeocerca.PosicionInicioExceso = estadoGeocerca.EnExcesoVelocidad ? position : null;
                        estadoGeocerca.VelocidadPico        = estadoGeocerca.EnExcesoVelocidad ? position.Velocidad : 0;
                    }
                    if (geocerca.ZonaManejo > 0)
                    {
                        if (estadoVehiculo.ZonaManejo == null || estadoVehiculo.ZonaManejo.PrioridadZona > geocerca.PrioridadZona)
                        {
                            estadoVehiculo.ZonaManejo = geocerca;
                        }
                    }

                    estadoVehiculo.GeocercasDentro.Add(estadoGeocerca);
                }
                if (t.getTimeElapsed().TotalSeconds > 0.5)
                {
                    STrace.Error("DispatcherLock", vehiculo.Dispositivo.Id, String.Format("CalcularEstadoVehiculo/ForEach ({0} secs)", t.getTimeElapsed().TotalSeconds));
                }

                return(estadoVehiculo);
            }
        }
Example #34
0
 public static Event FactoryRfid(int deviceId, ulong msgId, GPSPoint pos, DateTime dt, String rfid, Int64 data)
 {
     return(FactoryEvent(MessageIdentifier.RfidDetected, deviceId, msgId, pos, dt, rfid, new List <Int64> {
         data
     }));
 }