Beispiel #1
0
        public ILink OnLinkTranslation(IUnderlayingNetworkLayer unl, EndPoint ep, IFrame frame)
        {
            try
            {
                var former = LinksTree.Find(ep, unl).GetDeviceId();
                var dev    = unl.Parser.Factory(frame, former) ?? unl.Parser;

                if (ParserUtils.IsInvalidDeviceId(dev.GetDeviceId()))
                {
                    return(null);
                }

                var link = LinksTree.GetOrCreate(dev, unl, ep, former);

                if (LogCambioDeIp)
                {
                    if (dev.GetDeviceId() != former)
                    {
                        STrace.Trace(GetType().FullName, dev.GetDeviceId(), String.Format("Detectado cambio de id: Former={0} Received={1} Address={2} Payload={3}", former, dev.GetDeviceId(), frame.RemoteAddressAsString, Encoding.ASCII.GetString(frame.Payload)));
                    }

                    if (!ep.Equals(link.EndPoint))                     // el operador == siempre da falso por que solo compara la referencia y son 2 instancias distintas con los mismos datos!
                    {
                        STrace.Trace(GetType().FullName, dev.GetDeviceId(), String.Format("Detectado cambio de ip: FormerAddress={0} ReceivedAddress={1} DeviceId={2} Payload={3}", link.EndPoint, ep, dev.GetDeviceId(), Encoding.ASCII.GetString(frame.Payload)));
                    }
                }

                return(link);
            }
            catch (ObjectNotFoundException)
            {
                STrace.Debug(GetType().FullName, String.Format("Dispositivo no registrado: {0}", frame.PayloadAsString));
            }
            catch (Exception e)
            {
                STrace.Exception(GetType().FullName, e, String.Format("OnLinkTranslation: {0}", frame.PayloadAsString));
            }
            return(null);
        }
Beispiel #2
0
 public int GetPositionClass(float lat, float lon)
 {
     try
     {
         return(State != States.READY ? -1 : Q43_GetPositionClass(native, lat, lon));
     }
     catch (DllNotFoundException e)
     {
         STrace.Debug(GetType().FullName, "QTREE: la interface de acceso y edicion de datos (de clase y extendidos) queda deshabilitada.");
         STrace.Debug(GetType().FullName, "QTREE: debido a que falta el archivo QuadTree.DLL o una de sus dependencias.");
         STrace.Exception(GetType().FullName, e);
         State = States.DLLMISSING;
     }
     catch (Exception e)
     {
         STrace.Debug(GetType().FullName, "QTREE: la interface de acceso y edicion de datos (de clase y extendidos) queda deshabilitada.");
         STrace.Debug(GetType().FullName, "QTREE: debido a un error no especificado.");
         STrace.Exception(GetType().FullName, e);
         State = States.ERROR;
     }
     return(-1);
 }
Beispiel #3
0
        public override bool Send(PDU pdu)
        {
            var d = Devices.I().FindById(pdu.IdDispositivo);

            STrace.Debug(GetType().FullName, String.Format("XBEE/SEND: d={0}", (d == null ? "(nil)" : d.LogId)));
            if (d != null && d.State == DeviceTypes.States.ONLINE)
            {
                d.Touch(pdu.Destino);
            }
            var size            = 0;
            var instance_buffer = new byte[8192];
            var bytes           = CODEC.Encode(ref instance_buffer, ref size, pdu);

            STrace.Debug(GetType().FullName, String.Format("---XBEE SENDING {0}/{1} bytes TO {2}----------\n{3}", bytes, size, pdu.Destino.XBee, pdu.Trace("")));

            /*if (pdu.SourcePdu != null && pdu.SourcePdu.CH == (byte)Codes.HighCommand.MsgPosicion)
             * {
             *  STrace.Trace(GetType().FullName,0, "--- PAUSA XBEE DE POSICION ---");
             *  Thread.Sleep(1000);
             * }*/
            return(links[0].Send(instance_buffer, size, pdu.Destino.XBee));
        }
Beispiel #4
0
        /// <summary>
        /// Performs all necesary actions for handling the givenn message.
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public HandleResults HandleMessage(T message)
        {
            //Update Performance Counters
            //var cat = new BackendCategory();
            //PerformanceCounterHelper.Increment(cat.CategoryName, cat.DispatcherCount, cat.DispatcherProm, STrace.Module + message.GetType().Name);
            STrace.Debug(GetType().FullName, message.DeviceId,
                         "HandleMessage (BaseHandler) dt=" + message.Tiempo + " T=" + message.GetType().Name + " Id=" +
                         message.DeviceId);

            lock (GetLockByDevice(message.DeviceId))
            {
                using (var transaction = SmartTransaction.BeginTransaction())
                {
                    try
                    {
                        var result = OnHandleMessage(message);
                        transaction.Commit();
                        return(result);
                    }
                    catch (Exception e)
                    {
                        STrace.Exception(GetType().FullName, e, message.DeviceId);
                        try
                        {
                            transaction.Rollback();
                        }
                        catch (Exception ex2)
                        {
                            STrace.Exception(GetType().FullName, ex2, message.DeviceId, "HandleMessage(T); Doing rollback");
                        }
                        return(HandleResults.SilentlyDiscarded);
                    }
                    finally
                    {
                        DisposeResources();
                    }
                }
            }
        }
Beispiel #5
0
        protected override List <RetrasoVo> GetResults()
        {
            var inicio = DateTime.UtcNow;

            try
            {
                var coches = DAOFactory.CocheDAO.GetList(new[] { ddlLocation.Selected },
                                                         new[] { ddlPlanta.Selected },
                                                         lbTipoMovil.SelectedValues,
                                                         new[] { -1 },
                                                         lbCentroCosto.SelectedValues)
                             .Where(c => QueryExtensions.IncludesAll((IEnumerable <int>)lbMovil.SelectedValues) ||
                                    lbMovil.SelectedValues.Contains(c.Id));

                var fecha = DateTime.UtcNow;
                fecha = new DateTime(fecha.Year, fecha.Month, fecha.Day, fecha.Hour, fecha.Minute, fecha.Second);

                var results = coches.Select(c => CicloLogisticoFactory.GetCiclo(c, null))
                              .Where(c => c != null)
                              .Where(c => c.Iniciado.AddMinutes(npEnCiclo.Value) < fecha ||
                                     (c.EnGeocerca &&
                                      c.EnGeocercaDesde.HasValue &&
                                      c.EnGeocercaDesde.Value.AddMinutes(npEnGeocerca.Value) < fecha))
                              .Select(c => new RetrasoVo(c, fecha))
                              .ToList();

                var duracion = (DateTime.UtcNow - inicio).TotalSeconds.ToString("##0.00");

                STrace.Trace("Reporte de Retrasos", String.Format("Duración de la consulta: {0} segundos", duracion));

                return(results);
            }
            catch (Exception e)
            {
                STrace.Exception("Reporte de Retrasos", e, String.Format("Reporte: Reporte de Retrasos. Duración de la consulta: {0:##0.00} segundos", (DateTime.UtcNow - inicio).TotalSeconds));

                throw;
            }
        }
Beispiel #6
0
        /// <summary>
        /// Determines if the current service should be restarted.
        /// </summary>
        /// <param name="service"></param>
        /// <returns></returns>
        private Boolean MustRestartService(ServiceController service)
        {
            try
            {
                var key = Registry.LocalMachine.OpenSubKey(String.Format(@"SYSTEM\CurrentControlSet\Services\{0}", service.ServiceName), true);

                if (key == null)
                {
                    return(true);
                }

                var value = key.GetValue("Start");

                return(value == null || Convert.ToInt32(value) != 4);
            }
            catch (Exception e)
            {
                STrace.Exception(GetType().FullName, e);

                return(true);
            }
        }
Beispiel #7
0
        protected override List <KmHsProductivosVo> GetResults()
        {
            var inicio = DateTime.UtcNow;

            try
            {
                var results = DAOFactory.CocheDAO.GetList((IEnumerable <int>)ddlLocacion.SelectedValues, (IEnumerable <int>)ddlPlanta.SelectedValues, (IEnumerable <int>)ddlTipoVehiculo.SelectedValues)
                              .Where(v => ddlVehiculo.SelectedValues.Contains(v.Id))
                              .Select(v => new KmHsProductivosVo(v, dpDesde.SelectedDate != null ? SecurityExtensions.ToDataBaseDateTime(dpDesde.SelectedDate.Value) : DateTime.Today, dpHasta.SelectedDate != null ? SecurityExtensions.ToDataBaseDateTime(dpHasta.SelectedDate.Value) : DateTime.Today.AddDays(1)))
                              .ToList();

                STrace.Trace("Reporte de Horas Productivas", String.Format("Duración de la consulta: {0:##0.00} segundos", (DateTime.UtcNow - inicio).TotalSeconds));

                return(results);
            }
            catch (Exception e)
            {
                STrace.Exception("Reporte de Horas Productivas", e, String.Format("Reporte: Reporte de Horas Productivas. Duración de la consulta: {0:##0.00} segundos", (DateTime.UtcNow - inicio).TotalSeconds));

                throw;
            }
        }
Beispiel #8
0
        /// <summary>
        /// Performs a database delete with the givenn query.
        /// </summary>
        /// <param name="sql"></param>
        private void Delete(String sql)
        {
            using (var transaction = SmartTransaction.BeginTransaction())
            {
                try
                {
                    DaoFactory.CreateSqlQuery(String.Format("{0} ; select @@rowcount as count;", sql))
                    .AddScalar("count", NHibernateUtil.Int32)
                    .SetParameter("date", _minDate)
                    .SetTimeout(0)
                    .UniqueResult();

                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    STrace.Exception(GetType().FullName, ex);
                    transaction.Rollback();
                    throw ex;
                }
            }
        }
Beispiel #9
0
        protected override void OnSave()
        {
            EditObject.Telefono    = txtTelefono.Text.Trim();
            EditObject.Descripcion = txtDescripcion.Text.Trim();
            EditObject.Codigo      = txtCodigo.Text.Trim();

            if (chkExistente.Checked)
            {
                EditObject.ReferenciaGeografica = SelectGeoRef1.Selected > 0 ? DAOFactory.ReferenciaGeograficaDAO.FindById(SelectGeoRef1.Selected) : null;
            }
            else
            {
                EditObject.ReferenciaGeografica             = EditEntityGeoRef1.GetNewGeoRefference();
                EditObject.ReferenciaGeografica.Empresa     = EditObject.Empresa;
                EditObject.ReferenciaGeografica.Linea       = EditObject.Linea;
                EditObject.ReferenciaGeografica.Descripcion = EditObject.Descripcion;

                var code = txtCodigo.Text.Trim();
                var i    = 1;

                var byCode = DAOFactory.ReferenciaGeograficaDAO.FindByCodigoStartWith(new[] { -1 },
                                                                                      new[] { -1 },
                                                                                      new[] { EditEntityGeoRef1.TipoReferenciaGeograficaId },
                                                                                      code);

                while (byCode.Any(r => r.Codigo == code && EditObject.ReferenciaGeografica.Id != r.Id))
                {
                    code += "(" + i++ + ")";
                }

                EditObject.ReferenciaGeografica.Codigo = code;

                DAOFactory.ReferenciaGeograficaDAO.SingleSaveOrUpdate(EditObject.ReferenciaGeografica);
                STrace.Trace("QtreeReset", "TallerAlta");
            }

            DAOFactory.TallerDAO.SaveOrUpdate(EditObject);
        }
Beispiel #10
0
        protected override List <ReporteTicketVo> GetListData()
        {
            var inicio = DateTime.UtcNow;
            var desde  = dpDesde.SelectedDate.HasValue
                            ? SecurityExtensions.ToDataBaseDateTime(dpDesde.SelectedDate.Value)
                            : inicio;
            var hasta = dpHasta.SelectedDate.HasValue
                            ? SecurityExtensions.ToDataBaseDateTime(dpHasta.SelectedDate.Value)
                            : inicio;

            try
            {
                var results = DAOFactory.SupportTicketDAO.GetList(cbEmpresa.SelectedValues,
                                                                  cbCategoria.SelectedValues,
                                                                  cbSubcategoria.SelectedValues,
                                                                  cbNivel.SelectedValues,
                                                                  desde,
                                                                  hasta);

                var estados = cbEstados.GetSelectedIndices();
                if (Enumerable.Any <int>(estados) && !Enumerable.Contains(estados, -1))
                {
                    results = results.Where(ts => Enumerable.Contains <int>(estados, ts.CurrentState)).ToList();
                }

                var duracion = (DateTime.UtcNow - inicio).TotalSeconds.ToString("##0.00");

                STrace.Trace("Reporte de Soporte", String.Format("Duración de la consulta: {0} segundos", duracion));

                return(results.Select(st => new ReporteTicketVo(st)).ToList());
            }
            catch (Exception e)
            {
                STrace.Exception("Reporte de Soporte", e, String.Format("Reporte: Reporte de Soporte. Duración de la consulta: {0:##0.00} segundos", (DateTime.UtcNow - inicio).TotalSeconds));

                throw;
            }
        }
Beispiel #11
0
        public Respuesta <ControlDeCiclo[]> GetControlDeCiclo(string sessionId, string company, string branch, DateTime utcDate)
        {
            try
            {
                ValidateLoginInfo(sessionId, Securables.WebServiceTickets);
                ValidateExpiration(string.Concat("GetControlDeCiclo[", company, ",", branch, "]"), 180);

                var empresa = GetEmpresaByCode(company);
                var linea   = string.IsNullOrEmpty(branch) ? null : GetLineaByCode(branch, empresa);
                var desde   = utcDate.Date;
                var hasta   = desde.AddDays(1).AddMilliseconds(-1);

                var empty = new[] { -1 };

                var results = DAOFactory.TicketDAO.GetList(new[] { empresa.Id },
                                                           new[] { linea != null ? linea.Id : -1 },
                                                           empty,
                                                           empty,
                                                           empty,
                                                           empty,
                                                           empty,
                                                           empty,
                                                           empty,
                                                           empty,
                                                           empty,
                                                           desde,
                                                           hasta)
                              .Select(t => new ControlDeCiclo(t))
                              .ToArray();

                return(Respuesta <ControlDeCiclo[]> .Create(results));
            }
            catch (Exception e)
            {
                STrace.Error("WebService Tickets", e.Message);
                return(Respuesta <ControlDeCiclo[]> .CreateError(e.Message));
            }
        }
Beispiel #12
0
        private IMessage ParseUploadAlarm(IFrame frame, PacketType packettype)
        {
            //decoding
            var tripid = BitConverter.ToInt32(frame.Payload, DataStart);
            var fixedPackageSequenceNumber = BitConverter.ToUInt32(frame.Payload, DataStart + 4);
            var rtctime = ParseRtcTime(frame.Payload, DataStart + 8);
            //var TripMileage = BitConverter.ToInt32(Frame.Payload, dataStart + 12); //en millas
            var      dataFlag = frame.Payload[DataStart + 16];
            var      privacyFunctionenabledFlag = BitHelper.AreBitsSet(frame.Payload[DataStart + 16], 0x01);
            var      gpsDataFlag = BitHelper.AreBitsSet(frame.Payload[DataStart + 16], 0x02);
            var      offset      = DataStart + 17;
            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);
            var alarmIdentifier = BitConverter.ToInt32(frame.Payload, offset + 4);
            var alarmDetailedDescriptionField = BitConverter.ToInt32(frame.Payload, offset + 8);

            STrace.Debug(GetType().FullName, Id, String.Format("{0}: tripid={1} VState.Length={2} AlarmIdentifier={3:X} AlarmDetailedDescriptionField={4:X} payload={5}", packettype, tripid, vState.Length, alarmIdentifier, alarmDetailedDescriptionField, GetData(frame)));

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

            res.Tiempo = rtctime;
            return(res);
        }
Beispiel #13
0
 private QuadTree()
 {
     try
     {
         State = States.WF_INIT;
         Q43_Create(out native);
         State = States.CREATED;
     }
     catch (DllNotFoundException e)
     {
         STrace.Debug(GetType().FullName, "QTREE: la interface de acceso y edicion de datos (de clase y extendidos) queda deshabilitada.");
         STrace.Debug(GetType().FullName, "QTREE: debido a que falta el archivo QuadTree.DLL o una de sus dependencias.");
         STrace.Exception(GetType().FullName, e);
         State = States.DLLMISSING;
     }
     catch (Exception e)
     {
         STrace.Debug(GetType().FullName, "QTREE: la interface de acceso y edicion de datos (de clase y extendidos) queda deshabilitada.");
         STrace.Debug(GetType().FullName, "QTREE: debido a un error no especificado.");
         STrace.Exception(GetType().FullName, e);
         State = States.ERROR;
     }
 }
Beispiel #14
0
        /// <summary>
        /// Gets the DetalleDispositivo that matches with the parameter name
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        //public virtual DetalleDispositivo FindDetailByName(string name)
        //{
        //    var lName = name.ToLower().Trim();
        //    var t = new TimeElapsed();
        //    var detalles = DetallesDispositivo.Cast<DetalleDispositivo>();
        //    if (t.getTimeElapsed().TotalSeconds > 1) STrace.Debug("DispatcherLock", Id, String.Format("Dispositivo - FindDetailByName -  Cast Detalles ({0} secs)", t.getTimeElapsed().TotalSeconds.ToString()));
        //    t.Restart();
        //    var filtrado =
        //        detalles.FirstOrDefault(
        //            w =>
        //            w.TipoParametro.DispositivoTipo.Equals(w.Dispositivo.TipoDispositivo) &&
        //            w.TipoParametro.Nombre.ToLower().Trim().Equals(lName));
        //    if (t.getTimeElapsed().TotalSeconds > 1) STrace.Debug("DispatcherLock", Id, String.Format("Dispositivo - FindDetailByName - filtrado Detalle ({0} secs)", t.getTimeElapsed().TotalSeconds.ToString()));
        //    return filtrado;
        //}

        public virtual IEnumerable <DetalleDispositivo> FindDetailsStartWith(string name)
        {
            var lName    = name.ToLower().Trim();
            var t        = new TimeElapsed();
            var detalles = DetallesDispositivo.Cast <DetalleDispositivo>();

            if (t.getTimeElapsed().TotalSeconds > 1)
            {
                STrace.Debug("DispatcherLock", Id, String.Format("Dispositivo - FindDetailsStartWith - Cast Detalles ({0} secs)", t.getTimeElapsed().TotalSeconds.ToString()));
            }
            t.Restart();
            var filtrado =
                detalles.Where(
                    w =>
                    w.TipoParametro.DispositivoTipo.Equals(w.Dispositivo.TipoDispositivo) &&
                    w.TipoParametro.Nombre.ToLower().Trim().StartsWith(lName));

            if (t.getTimeElapsed().TotalSeconds > 1)
            {
                STrace.Debug("DispatcherLock", Id, String.Format("Dispositivo - FindDetailsStartWith - filtrado Detalles ({0} secs)", t.getTimeElapsed().TotalSeconds.ToString()));
            }
            return(filtrado);
        }
Beispiel #15
0
        /// <summary>
        /// Process handler main tasks.
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        protected override HandleResults OnHandleMessage(TextEvent message)
        {
            var coche    = DaoFactory.CocheDAO.FindMobileByDevice(message.DeviceId);
            var posicion = new LogPosicionVo(new LogPosicion
            {
                Coche          = coche,
                Dispositivo    = coche.Dispositivo,
                Altitud        = message.GeoPoint.Height.Unpack(),
                Latitud        = message.GeoPoint.Lat,
                Longitud       = message.GeoPoint.Lon,
                Velocidad      = message.GeoPoint.Velocidad,
                FechaMensaje   = message.GeoPoint.Date,
                FechaRecepcion = DateTime.UtcNow
            });
            var eventName = message.Text;

            var service = new Service();
            var result  = service.ReportEvent(eventName, coche, posicion);

            STrace.Debug(typeof(Handler).FullName, coche.Dispositivo.Id, String.Format("AssistCargo Event: {0} -> {1}: {2}", coche.Patente, eventName, result));

            return(HandleResults.Success);
        }
Beispiel #16
0
        public override void VencimientoTV(int timer_id)
        {
            //Marshall.Debug("MSR: TV vencido.");
            switch (Estado)
            {
            case Estados.CONFIRMANDO:
                Estado = Estados.TERMINADO;
                Transporte.TransaccionCompleta(this, pdu);
                break;

            case Estados.RESPONDIENDO:
                Estado = Estados.TERMINADO;
                TransactionUser.RespuestaNoEntregada(rta, this, Transporte);
                Transporte.TransaccionCompleta(this, pdu);
                break;

            default:
                STrace.Debug(GetType().FullName, String.Format("MRS: Error en timer de vencimeinto, el estado es inconsistente state={0}", Estado));
                Estado = Estados.TERMINADO;
                Transporte.TransaccionCompleta(this, pdu);
                break;
            }
        }
Beispiel #17
0
        private void _ReadCallback(IAsyncResult ar)
        {
            try
            {
                var dgram = (Datagram)ar.AsyncState;

                dgram.Size = Socket.EndReceiveFrom(ar, ref dgram.remoteAddress);

                OnReceive(dgram);
            }
            catch (Exception e)
            {
                Dispose();

                CreateSocket();

                STrace.Exception(GetType().FullName, e);
            }
            finally
            {
                BeginRecieve();
            }
        }
 private bool InChannelMessageReceived(byte[] data)
 {
     try
     {
         ReceivedMessages.Inc(1);
         ReceivedBytes.Inc((ulong)data.GetLength(0));
         var message = (OpaqueMessage.OpaqueMessage)GZip.DecompressAndDeserialize(data);
         if (message == null)
         {
             return(false);
         }
         _dispatcher.Dispatch(message);
         var outbuff = GZip.SerializeAndCompress(new OpaqueMessageReply(message));
         _outChannel.Send(outbuff);
         SentBytes.Inc((ulong)outbuff.GetLength(0));
         return(true);
     }
     catch (Exception e)
     {
         STrace.Exception(GetType().FullName, e);
     }
     return(false);
 }
Beispiel #19
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()));
            }
        }
Beispiel #20
0
        /// <summary>
        /// Performs taks main actions.
        /// </summary>
        /// <param name="timer"></param>
        protected override void OnExecute(Timer timer)
        {
            STrace.Trace(GetType().FullName, "Processing engines.");

            foreach (var m in DaoFactory.CaudalimetroDAO.FindAll())
            {
                ProcessAllCaudalimetrosMovements(m);
            }

            STrace.Trace(GetType().FullName, "Processing tanks by location.");

            foreach (var t in DaoFactory.TanqueDAO.FindAllEnPlanta())
            {
                ProcessTankEnPlantaConsumptions(t);
            }

            STrace.Trace(GetType().FullName, "Processing tanks by equipment.");

            foreach (var t in DaoFactory.TanqueDAO.FindAllEnEquipo())
            {
                ProcessTankEnEquipoConsumptions(t);
            }
        }
Beispiel #21
0
 public INode Get(int deviceId, INode device)
 {
     try
     {
         if (deviceId == 0)
         {
             return(null);
         }
         var dev1 = device.Get(deviceId);
         if (dev1 != null)
         {
             return(dev1);
         }
         STrace.Debug(GetType().FullName, deviceId, String.Format("ForceById Get"));
         var dev = DaoFactory.DispositivoDAO.ForceById(deviceId);
         return(dev == null ? null : device.FactoryShallowCopy(dev.Id, dev.IdNum, dev.Imei));
     }
     catch (Exception e)
     {
         STrace.Debug(GetType().FullName, deviceId, String.Format("No se encontro el dispositivo en la base; Error: {0}", e));
         return(null);
     }
 }
Beispiel #22
0
 public void SetReference <TYPE>(float lat, float lon, string name, TYPE value)
 {
     if (State != States.INSERVICE)
     {
         throw new ApplicationException("El indice esta fuera de servicio");
     }
     try
     {
         var data = new byte[512];
         unsafe
         {
             fixed(byte *ptrBuffer = &data[0])
             {
                 Marshal.StructureToPtr(value, new IntPtr(ptrBuffer), true);
                 StoreExtended(ReferencePath(lat, lon, name), data);
             }
         }
     }
     catch (Exception e)
     {
         STrace.Exception(typeof(GR2).FullName, e);
     }
 }
Beispiel #23
0
 /// <summary>
 /// este metodo inicial la conexion asincronica al destino indicado.
 /// </summary>
 /// <param name="ep">endpoint a donde realizar la conexion.</param>
 /// <param name="sync">indica si la conexion debe hacerse sincronica o asicnronicamente.</param>
 public bool connect(IPEndPoint ep, bool sync)
 {
     try
     {
         if (sync)
         {
             _handler.Connect(ep);
             if (_handler.Connected)
             {
                 _handler.BeginReceive(_read_buffer, 0, _buffersize, 0, _ReadCallback, _handler);
                 return(true);
             }
             return(false);
         }
         _handler.BeginConnect(ep, _ConnectedCallBack, _handler);
         return(true);
     }
     catch (SocketException e)
     {
         STrace.Log(GetType().FullName, e, 0, LogTypes.Trace, null, e.Message);
         return(false);
     }
 }
Beispiel #24
0
 /// <summary>
 /// Consumes a email from the queue.
 /// </summary>
 private static void Consume()
 {
     while (true)
     {
         try
         {
             Semaphore.WaitOne();
             Email em;
             while ((em = Queue.Dequeue()) != null)
             {
                 SendMail(em);
             }
         }
         catch (ThreadAbortException)
         {
             return;
         }
         catch (Exception e)
         {
             STrace.Exception(typeof(Consumer).FullName, e);
         }
     }
 }
Beispiel #25
0
 // constructor utilizado al crear la base de datos
 public DeviceState(short id, States initial_state)
 {
     STrace.Debug(GetType().FullName, String.Format("DEVICE_STATE: constructor de ALTA id={0}.", id));
     Id                  = id;
     ServiceState        = initial_state;
     QTreeState          = DeviceTypes.QTreeStates.UNKNOWN;
     firstActivity       = DateTime.MinValue;
     LastCommit          = DateTime.MinValue;
     FlashCounter        = new Gauge64();
     CrapReceivedCounter = new Gauge64();
     StatesChanges       = new Gauge64();
     PERMANENTCounter    = new Gauge64();
     MAINTCounter        = new Gauge64();
     OFFLINECounter      = new Gauge64();
     CONNECTEDCounter    = new Gauge64();
     ONLINECounter       = new Gauge64();
     ONNETCounter        = new Gauge64();
     SHUTDOWNCounter     = new Gauge64();
     SYNCINGCounter      = new Gauge64();
     OUTOFSERVICECounter = new Gauge64();
     //TransitionTrend     = new Toolkit.TransitionTrend<ServiceStates>();
     AverageConnectedTime = new ArithmeticMean(32);
 }
Beispiel #26
0
        private GPSPoint ParseGpsData(byte[] ba, int offset)
        {
            var mark           = ba[offset + 17];
            var invalidQuality = (mark & 0x0C) == 0x00;

            if (invalidQuality)
            {
                return(null);
            }

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

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

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

            STrace.Debug(typeof(Parser).FullName, Id, String.Format("GPS: {0}", res));
            return(res);
        }
Beispiel #27
0
        private String CheckConditionsBeforeSendPending(String pending)
        {
            if (!LastSent.IsOnTheFly())
            {
                string md = GetMessagingDevice();
                if (md == MessagingDevice.Garmin && BaseDeviceCommand.createFrom(pending, this, null).isGarminMessage())
                {
                    if (IsGarminConnected == null || !IsGarminConnected.Value)
                    {
                        // var mid = NextSequence;
                        // pending = GarminFmi.EncodePing().ToTraxFm<String>(mid, this);
                        // LastSent = new INodeMessage(mid, pending, DateTime.UtcNow) { IsOnTheFly = true };
                        // STrace.Debug(typeof(IFoteable).FullName, this.GetDeviceId(), "GARMIN PING Sent");
                        LastSent = null;
                        return(null);
                    }
                }
                else
                {
                    ulong mid = ParserUtils.GetMsgIdTaip(pending);

                    if (pending.StartsWith(Reporte.WriteGgPrefix) &&
                        !_sdSession)
                    {
                        //si quiero escribir en la sd tengo que abrir sesion antes, y antes tengo que pedir la password para abrir sesion
                        STrace.Debug(typeof(Parser).FullName, Id, "Sesion de escritura en sd QUERING");
                        mid      = NextSequence;
                        pending  = Mensaje.Factory(mid, this, Reporte.QuerySdSessionPassword.TrimStart('>'));
                        LastSent = new INodeMessage(mid, pending, DateTime.UtcNow)
                        {
                            IsOnTheFly = true
                        };
                    }
                }
            }
            return(pending);
        }
Beispiel #28
0
            public override void on_data()
            {
                STrace.Debug(GetType().FullName, String.Format("FotaServer: datos recibidos={0}", get_read_bytes()));

                var fields = Encoding.ASCII.GetString(get_buffer(), 0, get_read_bytes()).Split("/".ToCharArray());

                if (fields.GetLength(0) < 4)
                {
                    send("X");
                    close();
                    return;
                }

                send("L4PNP");
                const string specs = "RNR-OSv1-Torino(R)-BL";
                const string path  = @"C:\Documents and Settings\Administrator\Desktop\rnros\trunk\torino\bin";

                if (fields[3] == "REQ")
                {
                    var signature = IniFile.Get(path + @"\" + specs + ".ini", "install", "image.signature", "");
                    if (string.IsNullOrEmpty(signature))
                    {
                        send("E");
                        close();
                        return;
                    }
                    var order = IniFile.Get(specs + ".ini", "", "image.install.order", "0");

                    const string file = specs + ".bin";
                    SendFile(order, signature, file, path);
                }
                else
                if (fields[3] == "E01")
                {
                    send("C");
                }
            }
Beispiel #29
0
        private PidData[] ParsePidDataStream(byte[] payload, int _offset)
        {
            var pidlenTable = new Dictionary <int, int>
            {
                { 0x210C, 2 },
                { 0x2110, 2 },
                { 0x2121, 2 },
                { 0x2123, 2 },
                { 0x2124, 2 },
                { 0x2152, 2 },
                { 0x2142, 2 },
            };

            var offset = _offset;
            var res    = new List <PidData>();
            var count  = payload[offset];            //total number of ECU supported PID types

            offset++;
            for (var i = 0; i < count; i++)
            {
                var pid = BitConverter.ToInt16(payload, offset);
                if ((pid & 0x2100) != 0x2100)
                {
                    STrace.Debug(typeof(Parser).FullName, Id, String.Format("ParsePidDataStream, pid desconocido: {0}", StringUtils.ByteArrayToHexString(payload, _offset, payload.Length - (_offset + 4))));
                    return(null);
                }
                offset += 2;
                var arithmeticnumber = BitConverter.ToInt16(payload, offset);
                offset += 2;
                var datalen = pidlenTable.ContainsKey(pid) ? pidlenTable[pid] : 1;
                var data    = new byte[datalen];
                offset += datalen;
                res.Add(new PidData(pid, arithmeticnumber, data));
            }

            return(res.ToArray());
        }
Beispiel #30
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);
        }