Exemplo n.º 1
0
        //private bool StartDistribucion(int id)
        //{
        //    var distribucion = DAOFactory.ViajeDistribucionDAO.FindById(id);

        //    if (distribucion.Estado != ViajeDistribucion.Estados.Pendiente) return false;
        //    var ciclo = new CicloLogisticoDistribucion(distribucion, DAOFactory, new MessageSaver(DAOFactory));
        //    IEvent evento = new InitEvent(DateTime.UtcNow);

        //    ciclo.ProcessEvent(evento);
        //    return true;
        //}

        protected void BtIniciarClick(object sender, EventArgs e)
        {
            mpePanel.Hide();
            if (TicketToInitId.Get() <= 0)
            {
                return;
            }


            var ticket = DAOFactory.ViajeDistribucionDAO.FindById(TicketToInitId.Get());

            TicketToInitId.Set(-1);

            var ciclo = new CicloLogisticoDistribucion(ticket, DAOFactory, new MessageSaver(DAOFactory));

            var evento = new InitEvent(DateTime.UtcNow);

            try
            {
                ciclo.ProcessEvent(evento);
                ShowInfo(CultureManager.GetSystemMessage("CLOG_START_SENT") + ticket.Vehiculo.Interno);
                Bind();
            }
            catch (NoVehicleException)
            {
                ShowError(new ApplicationException(CultureManager.GetError("TICKET_NO_VEHICLE_ASSIGNED")));
            }
            catch //AlreadyOpenException, QueueException, Exception
            {
                ShowError(new ApplicationException(CultureManager.GetError("CLOG_MESSAGE_NOT_SENT") + ticket.Vehiculo.Interno));
            }
        }
Exemplo n.º 2
0
        public static void ProcessEstadoLogistico(Coche vehiculo, Event evento, string code)
        {
            try
            {
                if (vehiculo.Dispositivo == null)
                {
                    return;
                }

                var daoFactory   = new DAOFactory();
                var distribucion = daoFactory.ViajeDistribucionDAO.FindEnCurso(vehiculo);

                if (distribucion != null)
                {
                    var messageSaver = new MessageSaver(daoFactory);
                    CicloLogisticoDistribucion ciclo = null;
                    ciclo = new CicloLogisticoDistribucion(distribucion, daoFactory, messageSaver);

                    if (ciclo != null)
                    {
                        ciclo.ProcessEstadoLogistico(evento, code);
                    }
                }
            }
            catch (Exception ex)
            {
                STrace.Exception(typeof(CicloLogisticoFactory).FullName, ex);
            }
        }
Exemplo n.º 3
0
        public static void Process(Coche vehiculo, IEvent data, bool ignoreMessages)
        {
            try
            {
                if (vehiculo.Dispositivo == null)
                {
                    return;
                }

                var daoFactory   = new DAOFactory();
                var messageSaver = ignoreMessages ? null : new MessageSaver(daoFactory);

                ICicloLogistico ciclo  = null;
                var             garmin = data as GarminEvent;
                if (garmin != null && garmin.DetailId > 0)
                {
                    var detailId = Convert.ToInt32(garmin.DetailId);

                    var entrega = daoFactory.EntregaDistribucionDAO.FindById(detailId);
                    if (entrega == null)
                    {
                        STrace.Error(typeof(CicloLogisticoFactory).FullName, detailId, "No se ha encontrado una distribucion para el vehiculo (" + garmin.DetailId.ToString("#0") + ")");
                    }
                    else
                    {
                        if (entrega.Viaje == null)
                        {
                            STrace.Error(typeof(CicloLogisticoFactory).FullName, detailId, "No se ha encontrado el ticket para la entrega (" + entrega.Id + ")");
                        }
                        else
                        {
                            var ticket = entrega.Viaje;
                            ciclo = new CicloLogisticoDistribucion(ticket, daoFactory, messageSaver);
                        }
                    }
                }
                else
                {
                    ciclo = GetCiclo(vehiculo, messageSaver, daoFactory);
                }

                if (ciclo == null)
                {
                    return;
                }
                ciclo.ProcessEvent(data);
            }
            catch (Exception ex)
            {
                STrace.Exception(typeof(CicloLogisticoFactory).FullName, ex);
            }
        }
Exemplo n.º 4
0
 private void ControlarCierreDistribucionPorMensaje(string code, Event generico)
 {
     if (Coche.Empresa.CierreDistribucionPorMensaje &&
         code == Coche.Empresa.CierreDistribucionCodigoMensaje)
     {
         var distribucion = DaoFactory.ViajeDistribucionDAO.FindEnCurso(Coche);
         if (distribucion != null)
         {
             var evento = new CloseEvent(generico.Tiempo);
             var ciclo  = new CicloLogisticoDistribucion(distribucion, DaoFactory, new MessageSaver(DaoFactory));
             ciclo.ProcessEvent(evento);
         }
     }
 }
Exemplo n.º 5
0
        public short ReportDelivery(int routeId, long jobId, Coordinate coord, int messageId, short jobStatus, string deviceId, DateTime dateTime)
        {
            var ticket = DaoFactory.ViajeDistribucionDAO.FindById(routeId);
            var ciclo  = new CicloLogisticoDistribucion(ticket, DaoFactory, new MessageSaver(DaoFactory));
            var evento = new MobileEvent(dateTime, jobId, coord.Latitude, coord.Longitude, jobStatus, messageId, deviceId);

            try
            {
                ciclo.ProcessEvent(evento);
            }
            catch (Exception ex)
            {
                return(-9);
            }
            return(evento.Estado);
        }
Exemplo n.º 6
0
        public string FinalizeRoute(int routeId)
        {
            var ticket = DaoFactory.ViajeDistribucionDAO.FindById(routeId);

            //var opened = DaoFactory.ViajeDistribucionDAO.FindEnCurso(ticket.Vehiculo);

            if (ticket == null || ticket.Estado == ViajeDistribucion.Estados.Cerrado)
            {
                return("ROUTE_CLOSED");
            }

            var ciclo  = new CicloLogisticoDistribucion(ticket, DaoFactory, new MessageSaver(DaoFactory));
            var evento = new CloseEvent(DateTime.UtcNow);

            ciclo.ProcessEvent(evento);
            return("CLOG_FINALIZE_SENT");
        }
Exemplo n.º 7
0
 private void ControlarInicioDistribucionPorMensaje(string code, Event generico)
 {
     if (Coche.Empresa.InicioDistribucionPorMensaje &&
         code == Coche.Empresa.InicioDistribucionCodigoMensaje &&
         DaoFactory.ViajeDistribucionDAO.FindEnCurso(Coche) == null)
     {
         var distribucion = DaoFactory.ViajeDistribucionDAO.FindPendiente(new[] { Coche.Empresa.Id },
                                                                          new[] { -1 }, new[] { Coche.Id },
                                                                          DateTime.Today,
                                                                          DateTime.Today.AddDays(1));
         if (distribucion != null)
         {
             var evento = new InitEvent(generico.Tiempo);
             var ciclo  = new CicloLogisticoDistribucion(distribucion, DaoFactory, new MessageSaver(DaoFactory));
             ciclo.ProcessEvent(evento);
         }
     }
 }
Exemplo n.º 8
0
        protected override void OnExecute(Timer timer)
        {
            STrace.Trace(ComponentName, "Inicio de la tarea");

            var desde    = DateTime.UtcNow;
            var hasta    = desde.AddMinutes(1);
            var empresas = DaoFactory.EmpresaDAO.GetList();

            foreach (var empresa in empresas)
            {
                var centrosDeCosto = DaoFactory.CentroDeCostosDAO.GetList(new[] { empresa.Id }, new[] { -1 }, new[] { -1 });

                foreach (var centroDeCosto in centrosDeCosto)
                {
                    if (centroDeCosto.InicioAutomatico)
                    {
                        STrace.Trace(ComponentName, string.Format("Inicio Automático habilitado para: {0} - ({1})", centroDeCosto.Descripcion, empresa.RazonSocial));
                        var tareas = DaoFactory.ViajeDistribucionDAO.GetList(new[] { empresa.Id },
                                                                             new[] { -1 }, // LINEAS
                                                                             new[] { -1 }, // TRANSPORTISTAS
                                                                             new[] { -1 }, // DEPARTAMENTOS
                                                                             new[] { centroDeCosto.Id },
                                                                             new[] { -1 }, // SUBCENTROS DE COSTO
                                                                             new[] { -1 }, // VEHICULOS
                                                                             new[] { (int)ViajeDistribucion.Estados.Pendiente },
                                                                             desde,
                                                                             hasta)
                                     .Where(v => v.Vehiculo != null);

                        STrace.Trace(ComponentName, string.Format("Cantidad de tareas pendientes: {0}", tareas.Count()));

                        foreach (var viaje in tareas)
                        {
                            var evento = new InitEvent(DateTime.UtcNow);
                            var ciclo  = new CicloLogisticoDistribucion(viaje, DaoFactory, new MessageSaver(DaoFactory));
                            ciclo.ProcessEvent(evento);
                            STrace.Trace(ComponentName, string.Format("Viaje Iniciado - Código: {0} - Id: {1} ", viaje.Codigo, viaje.Id));
                        }
                    }
                }
            }

            STrace.Trace(ComponentName, "Fin de la tarea");
        }
Exemplo n.º 9
0
        public string StartRoute(int routeId)
        {
            var ticket = DaoFactory.ViajeDistribucionDAO.FindById(routeId);
            var ciclo  = new CicloLogisticoDistribucion(ticket, DaoFactory, new MessageSaver(DaoFactory));
            var evento = new InitEvent(DateTime.UtcNow);

            try
            {
                ciclo.ProcessEvent(evento);
                return("CLOG_START_SENT");
            }
            catch (NoVehicleException)
            {
                return("TICKET_NO_VEHICLE_ASSIGNED");
            }
            catch (Exception ex) //AlreadyOpenException, QueueException, Exception
            {
                return("CLOG_MESSAGE_NOT_SENT" + ex.Message.ToString() + ex.StackTrace.ToString());
            }
        }
Exemplo n.º 10
0
        protected void BtOpenedCerrarTicketClick(object sender, EventArgs e)
        {
            if (TicketToInitId.Get() <= 0)
            {
                return;
            }

            var ticket = DAOFactory.ViajeDistribucionDAO.FindById(TicketToInitId.Get());

            var opened = DAOFactory.ViajeDistribucionDAO.FindEnCurso(ticket.Vehiculo);

            if (opened != null)
            {
                var ciclo  = new CicloLogisticoDistribucion(opened, DAOFactory, new MessageSaver(DAOFactory));
                var evento = new CloseEvent(DateTime.UtcNow);
                ciclo.ProcessEvent(evento);
                STrace.Trace("CierreCicloLogistico", ticket.Vehiculo.Dispositivo.Id, "Cierre manual por el usuario: " + WebSecurity.AuthenticatedUser.Name);
            }

            StartTicketWindow(ticket);
        }
Exemplo n.º 11
0
        protected override void OnExecute(Timer timer)
        {
            STrace.Trace(ComponentName, "Inicio de la tarea");

            var empresas = DaoFactory.EmpresaDAO.GetList();

            foreach (var empresa in empresas)
            {
                if (empresa.CierreDistribucionAutomatico)
                {
                    STrace.Trace(ComponentName, string.Format("Cierre Automático habilitado para: {0}", empresa.RazonSocial));
                    var viajes = DaoFactory.ViajeDistribucionDAO.GetList(new[] { empresa.Id },
                                                                         new[] { -1 }, // LINEAS
                                                                         new[] { -1 }, // TRANSPORTISTAS
                                                                         new[] { -1 }, // DEPARTAMENTOS
                                                                         new[] { -1 }, // CENTROS DE COSTO
                                                                         new[] { -1 }, // SUB CENTROS DE COSTO
                                                                         new[] { -1 }, // VEHICULOS
                                                                         new[] { (int)ViajeDistribucion.Estados.EnCurso },
                                                                         DateTime.UtcNow.AddDays(-1),
                                                                         DateTime.UtcNow);

                    STrace.Trace(ComponentName, string.Format("Cantidad de tickets en curso: {0}", viajes.Count()));

                    foreach (var viaje in viajes)
                    {
                        var evento = new CloseEvent(DateTime.UtcNow);
                        var ciclo  = new CicloLogisticoDistribucion(viaje, DaoFactory, new MessageSaver(DaoFactory));
                        ciclo.ProcessEvent(evento);
                        STrace.Trace(ComponentName, string.Format("Viaje Cerrado - Código: {0} - Id: {1} ", viaje.Codigo, viaje.Id));
                    }
                }
            }

            STrace.Trace(ComponentName, "Fin de la tarea");
        }
Exemplo n.º 12
0
        protected void LnkbtnEstadoCommand(object sender, CommandEventArgs commandEventArgs)
        {
            try
            {
                var index        = Convert.ToInt32(commandEventArgs.CommandArgument);
                var id           = Convert.ToInt32(Grid.DataKeys[index].Value);
                var distribucion = DAOFactory.ViajeDistribucionDAO.FindById(id);

                switch (commandEventArgs.CommandName)
                {
                case "Start":
                    StartTicketWindow(distribucion);
                    //new InitEvent(DateTime.UtcNow);
                    break;

                case "Close":
                    var    ciclo  = new CicloLogisticoDistribucion(distribucion, DAOFactory, new MessageSaver(DAOFactory));
                    IEvent evento = new CloseEvent(DateTime.UtcNow);
                    ciclo.ProcessEvent(evento);
                    STrace.Trace("CierreCicloLogistico", distribucion.Vehiculo.Dispositivo.Id, string.Format("Viaje {0} cerrado manualmente por {1}", distribucion.Id, WebSecurity.AuthenticatedUser.Name));
                    Bind();
                    break;

                case "Reenviar":
                    try
                    {
                        var destinations = distribucion.Detalles.Where(d => d.PuntoEntrega != null &&
                                                                       d.ReferenciaGeografica != null &&
                                                                       Math.Abs(d.ReferenciaGeografica.Latitude) < 90 &&
                                                                       Math.Abs(d.ReferenciaGeografica.Longitude) < 180 &&
                                                                       d.Estado != EntregaDistribucion.Estados.Completado &&
                                                                       d.Estado != EntregaDistribucion.Estados.NoCompletado &&
                                                                       d.Estado != EntregaDistribucion.Estados.Completado)
                                           .Select(d => new Destination(d.Id,
                                                                        new GPSPoint(DateTime.UtcNow,
                                                                                     (float)d.ReferenciaGeografica.Latitude,
                                                                                     (float)d.ReferenciaGeografica.Longitude),
                                                                        d.Descripcion,
                                                                        d.PuntoEntrega.Descripcion,
                                                                        d.ReferenciaGeografica.Direccion.Descripcion))
                                           .ToArray();

                        if (destinations.Any())
                        {
                            // LOAD ROUTE
                            switch (distribucion.Vehiculo.Empresa.OrdenRutaGarmin)
                            {
                            case Empresa.OrdenRuta.DescripcionAsc:
                                destinations = destinations.OrderBy(d => d.Text).ToArray();
                                break;

                            case Empresa.OrdenRuta.DescripcionDesc:
                                destinations = destinations.OrderByDescending(d => d.Text).ToArray();
                                break;
                            }

                            var expiration = distribucion.Fin.AddMinutes(distribucion.Empresa.EndMarginMinutes);

                            var msg = MessageSender.CreateReloadRoute(distribucion.Vehiculo.Dispositivo, new MessageSaver(DAOFactory))
                                      .AddRouteId(distribucion.Id)
                                      .AddDestinations(destinations)
                                      .AddExpiration(expiration);

                            if (distribucion.Tipo == ViajeDistribucion.Tipos.Desordenado)
                            {
                                var ordenar = distribucion.Empresa.GetParameter(Empresa.Params.CicloDistribucionOrdenar);
                                if (ordenar != null && ordenar.ToLower() == "true")
                                {
                                    msg.AddParameter("sort", "true");
                                }
                            }
                            msg.Send();
                        }
                    }
                    catch (Exception ex)
                    {
                        STrace.Exception("ViajeDistribucion Inicio", ex, distribucion.Vehiculo.Dispositivo.Id);
                        throw;
                    }
                    break;

                case "Asociar":
                    AsociarVehiculoWindow(distribucion);
                    break;

                case "Combinar":
                    CombinarViajeWindow(distribucion);
                    break;
                }
            }
            catch (QueueException)
            {
                ShowError("Error de configuracion de Cola de Comandos");
            }
            catch (Exception ex)
            {
                ShowError(ex);
            }
        }
Exemplo n.º 13
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.º 14
0
        public static IEvent GetEvent(DAOFactory daoFactory, GPSPoint inicio, string codigo, Int32?idPuntoDeInteres, Int64 extraData, Int64 extraData2, Int64 extraData3, Coche vehiculo, Empleado chofer)
        {
            IEvent evento = null;
            int    cod;

            if (int.TryParse(codigo, out cod) && cod > 0 && cod < 20)
            {
                evento = new ManualEvent(inicio.Date, inicio.Lat, inicio.Lon, codigo);
            }
            else if (codigo == MessageCode.InsideGeoRefference.GetMessageCode() && idPuntoDeInteres.HasValue)
            {
                evento = new GeofenceEvent(inicio.Date, idPuntoDeInteres.Value, GeofenceEvent.EventoGeofence.Entrada, inicio.Lat, inicio.Lon, chofer);
            }
            else if (codigo == MessageCode.OutsideGeoRefference.GetMessageCode() && idPuntoDeInteres.HasValue)
            {
                evento = new GeofenceEvent(inicio.Date, idPuntoDeInteres.Value, GeofenceEvent.EventoGeofence.Salida, inicio.Lat, inicio.Lon, chofer);
            }
            else if (codigo == MessageCode.TolvaDeactivated.GetMessageCode())
            {
                evento = new TolvaEvent(inicio.Date, TolvaEvent.EstadoTolva.Off, inicio.Lat, inicio.Lon);
            }
            else if (codigo == MessageCode.TolvaActivated.GetMessageCode())
            {
                evento = new TolvaEvent(inicio.Date, TolvaEvent.EstadoTolva.On, inicio.Lat, inicio.Lon);
            }
            else if (codigo == MessageCode.MixerStopped.GetMessageCode())
            {
                evento = new TrompoEvent(inicio.Date, TrompoEvent.SentidoTrompo.Detenido, TrompoEvent.VelocidadTrompo.Undefined, inicio.Lat, inicio.Lon);
            }
            else if (codigo == MessageCode.MixerClockwiseFast.GetMessageCode())
            {
                evento = new TrompoEvent(inicio.Date, TrompoEvent.SentidoTrompo.HorarioDerecha, TrompoEvent.VelocidadTrompo.Fast, inicio.Lat, inicio.Lon);
            }
            else if (codigo == MessageCode.MixerClockwiseSlow.GetMessageCode())
            {
                evento = new TrompoEvent(inicio.Date, TrompoEvent.SentidoTrompo.HorarioDerecha, TrompoEvent.VelocidadTrompo.Slow, inicio.Lat, inicio.Lon);
            }
            else if (codigo == MessageCode.MixerClockwise.GetMessageCode())
            {
                evento = new TrompoEvent(inicio.Date, TrompoEvent.SentidoTrompo.HorarioDerecha, TrompoEvent.VelocidadTrompo.Undefined, inicio.Lat, inicio.Lon);
            }
            else if (codigo == MessageCode.MixerCounterClockwiseFast.GetMessageCode())
            {
                evento = new TrompoEvent(inicio.Date, TrompoEvent.SentidoTrompo.AntihorarioIzquierda, TrompoEvent.VelocidadTrompo.Fast, inicio.Lat, inicio.Lon);
            }
            else if (codigo == MessageCode.MixerCounterClockwiseSlow.GetMessageCode())
            {
                evento = new TrompoEvent(inicio.Date, TrompoEvent.SentidoTrompo.AntihorarioIzquierda, TrompoEvent.VelocidadTrompo.Slow, inicio.Lat, inicio.Lon);
            }
            else if (codigo == MessageCode.MixerCounterClockwise.GetMessageCode())
            {
                evento = new TrompoEvent(inicio.Date, TrompoEvent.SentidoTrompo.AntihorarioIzquierda, TrompoEvent.VelocidadTrompo.Undefined, inicio.Lat, inicio.Lon);
            }
            else if (codigo == MessageCode.GarminTextMessageCannedResponse.GetMessageCode())
            {
                // extraData = ID Device
                // extraData2 = ID Entrega / ID Ruta
                // extraData3 = Codigo Mensaje
                STrace.Debug(typeof(EventFactory).FullName, Convert.ToInt32(extraData), "extraData=" + extraData + " extraData2=" + extraData2 + " extraData3=" + extraData3);
                var veh = daoFactory.CocheDAO.FindMobileByDevice(Convert.ToInt32(extraData));

                if (veh != null && veh.Empresa.IntegrationServiceEnabled)
                {
                    var intService = new IntegrationService(daoFactory);

                    if (veh.Empresa.IntegrationServiceCodigoMensajeAceptacion == extraData3.ToString())
                    {
                        var distribucion = daoFactory.ViajeDistribucionDAO.FindById(Convert.ToInt32(extraData2));

                        if (distribucion != null)
                        {
                            var enCurso = daoFactory.ViajeDistribucionDAO.FindEnCurso(veh);
                            if (enCurso == null)
                            {
                                intService.ResponseAsigno(distribucion, true);
                                var eventoInicio = new InitEvent(inicio.Date);
                                var ciclo        = new CicloLogisticoDistribucion(distribucion, daoFactory, new MessageSaver(daoFactory));
                                ciclo.ProcessEvent(eventoInicio);
                            }
                            else
                            {
                                intService.ResponsePreasigno(distribucion, true);
                            }
                        }

                        return(null);
                    }
                    else if (veh.Empresa.IntegrationServiceCodigoMensajeRechazo == extraData3.ToString())
                    {
                        var distribucion = daoFactory.ViajeDistribucionDAO.FindById(Convert.ToInt32(extraData2));
                        distribucion.Vehiculo = null;
                        daoFactory.ViajeDistribucionDAO.SaveOrUpdate(distribucion);

                        var enCurso = daoFactory.ViajeDistribucionDAO.FindEnCurso(veh);
                        if (enCurso == null)
                        {
                            intService.ResponseAsigno(distribucion, false);
                        }
                        else
                        {
                            intService.ResponsePreasigno(distribucion, false);
                        }

                        return(null);
                    }
                }

                if (extraData2 == 0)
                {
                    return(null);
                }
                var entrega   = daoFactory.EntregaDistribucionDAO.FindById(Convert.ToInt32(extraData2));
                var mensajeVo = daoFactory.MensajeDAO.GetByCodigo(extraData3.ToString("#0"), veh.Empresa, veh.Linea);
                try
                {
                    var mensaje = daoFactory.MensajeDAO.FindById(mensajeVo.Id);
                    try
                    {
                        var descriptiva = " - " + entrega.Viaje.Codigo + " - " + entrega.Descripcion;

                        var ms  = new MessageSaver(daoFactory);
                        var log = ms.Save(null, Convert.ToString(extraData3), veh.Dispositivo, veh, chofer, inicio.Date, inicio, descriptiva, entrega.Viaje, entrega);

                        try
                        {
                            entrega.MensajeConfirmacion = log as LogMensaje;
                            daoFactory.EntregaDistribucionDAO.SaveOrUpdate(entrega);
                        }
                        catch (Exception) { }

                        if (mensaje.TipoMensaje.DeConfirmacion)
                        {
                            evento = new GarminEvent(inicio.Date, extraData2, inicio.Lat, inicio.Lon, EntregaDistribucion.Estados.Completado, chofer);
                        }
                        else if (mensaje.TipoMensaje.DeRechazo)
                        {
                            evento = new GarminEvent(inicio.Date, extraData2, inicio.Lat, inicio.Lon, EntregaDistribucion.Estados.NoCompletado, chofer);
                        }
                        else
                        {
                            STrace.Error(typeof(CicloLogisticoFactory).FullName, Convert.ToInt32(extraData), "Respuesta de mensaje de Canned Response inválida sin tipo de mensaje adecuado para la ocasión. (" + extraData2 + "-" + extraData + ")");
                        }
                    }
                    catch (Exception e)
                    {
                        STrace.Exception(typeof(EventFactory).FullName, e,
                                         "E#2 Vehicle=" + veh.Id + " entrega=" +
                                         (entrega == null ? "null" : entrega.Id.ToString("#0")) + " mensajeVo=" +
                                         mensajeVo.Id + " mensaje=" +
                                         (mensaje == null ? "null" : mensaje.Id.ToString("#0")));
                    }
                }
                catch (Exception e)
                {
                    STrace.Exception(typeof(EventFactory).FullName, e,
                                     "E#1 Vehicle=" + veh.Id + " entrega=" +
                                     (entrega == null ? "null" : entrega.Id.ToString("#0")) + " mensajeVo=" +
                                     (mensajeVo == null ? "null" : mensajeVo.Id.ToString("#0")));
                }
            }
            else if (codigo == MessageCode.ValidacionRuteo.GetMessageCode())
            {
                var deviceId = inicio.DeviceId;
                var vehicle  = daoFactory.CocheDAO.FindMobileByDevice(deviceId);
                if (vehicle != null)
                {
                    var ruta = daoFactory.ViajeDistribucionDAO.FindEnCurso(vehicle);
                    if (ruta != null)
                    {
                        evento = new RouteEvent(inicio.Date, ruta.Id, inicio.Lat, inicio.Lon, RouteEvent.Estados.Enviado);
                    }
                }
            }
            else if (codigo == MessageCode.GarminETAReceived.GetMessageCode())
            {
                if (vehiculo.HasActiveStop())
                {
                    var activeStop = vehiculo.GetActiveStop();
                    if (activeStop > 0)
                    {
                        var edDAO   = daoFactory.EntregaDistribucionDAO;
                        var vdDAO   = daoFactory.ViajeDistribucionDAO;
                        var detalle = edDAO.FindById(activeStop);

                        if (detalle != null)
                        {
                            var utcnow  = DateTime.UtcNow;
                            var fechora = vehiculo.EtaEstimated();
                            var minutos = fechora != null && fechora > utcnow?fechora.Value.Subtract(utcnow).TotalMinutes : 0;

                            var texto = String.Format(CultureManager.GetLabel("GARMIN_STOP_ETA_ARRIVAL"), minutos, fechora);

                            if (minutos > 0)
                            {
                                using (var transaction = SmartTransaction.BeginTransaction())
                                {
                                    try
                                    {
                                        try
                                        {
                                            new MessageSaver(daoFactory).Save(null, codigo, vehiculo.Dispositivo, vehiculo, chofer, DateTime.UtcNow, null, texto,
                                                                              detalle.Viaje, detalle);
                                        }
                                        catch (Exception ex)
                                        {
                                            STrace.Exception(typeof(EventFactory).FullName, ex, vehiculo.Dispositivo.Id,
                                                             String.Format("Exception doing MessageSaver.Save({0})", texto));
                                            throw ex;
                                        }
                                        try
                                        {
                                            detalle.GarminETA           = fechora;
                                            detalle.GarminETAInformedAt = utcnow;
                                            vdDAO.SaveOrUpdate(detalle.Viaje);
                                        }
                                        catch (Exception ex)
                                        {
                                            STrace.Exception(typeof(EventFactory).FullName, ex, vehiculo.Dispositivo.Id,
                                                             String.Format("Exception doing MessageSaver.Save({0})", texto));
                                            throw ex;
                                        }
                                        transaction.Commit();
                                    }
                                    catch (Exception ex)
                                    {
                                        transaction.Rollback();
                                        throw ex;
                                    }
                                }
                            }
                        }
                        else
                        {
                            STrace.Error(typeof(EventFactory).FullName, vehiculo.Dispositivo.Id, String.Format("Processing GarminETAReceived cannot be processed because EntregaDistribucion #{0} is null.", activeStop));
                        }
                    }
                    else
                    {
                        STrace.Error(typeof(EventFactory).FullName, vehiculo.Dispositivo.Id, "Processing GarminETAReceived cannot be processed because ActiveStop # is not valid.");
                    }
                }
            }
            else
            {
                var stopstatus = TranslateStopStatus(codigo);
                if (stopstatus != -1)
                {
                    evento = new GarminEvent(inicio.Date, extraData, inicio.Lat, inicio.Lon, stopstatus, chofer);
                }
            }

            return(evento);
        }