Beispiel #1
0
        private IMessage GetLogEvent(byte[] payload, int device, DateTime time, int data)
        {
            var rfid = decodeRFID(Encoding.ASCII.GetString(payload, 5, 8), 'm');

            STrace.Debug(typeof(Parser).FullName, String.Format("login/logout: {0}:{1} === {2}", time, rfid, payload));
            return(MessageIdentifierX.FactoryRfid(device, 0, null, time, rfid, data));
        }
Beispiel #2
0
        private bool IsInvalidMessage(string code, IGeoPoint message)
        {
            var discardReason = DiscardReason.None;

            if (Coche == null && !MessageIdentifierX.IsEntityMessage(code))
            {
                discardReason = DiscardReason.NoAssignedMobile;
            }
            else if (message.GeoPoint != null && FechaInvalida(message.GeoPoint.Date, DeviceParameters))
            {
                discardReason = DiscardReason.InvalidDate;
            }
            else if (message.GeoPoint != null && FueraDelGlobo(message.GeoPoint))
            {
                discardReason = DiscardReason.OutOfGlobe;
            }
            else if (IsVelocidadInvalida(message))
            {
                discardReason = DiscardReason.InvalidSpeed;
            }

            if (discardReason.Equals(DiscardReason.None))
            {
                return(false);
            }

            DiscardEvent(code, message, discardReason);

            return(true);
        }
Beispiel #3
0
        private void ProcessChoferState(GPSPoint pos, DateTime date, uint msgId, String chofer, int state)
        {
            if ((chofer == "0000000000") || (chofer == "000000FFFF"))
            {
                return;
            }
            var ev = MessageIdentifierX.FactoryRfid(Id, msgId, pos, date, chofer, state);

            DataTransportLayer.DispatchMessage(this, ev);
        }
Beispiel #4
0
        private void DoWork()
        {
            var daoFactory = new DAOFactory();
            var buffer     = new Byte[420];

            Connect();

            var receive = true;

            while (receive)
            {
                try
                {
                    _socket.ReceiveFrom(buffer, 0, 419, SocketFlags.None, ref _remoteEndPoint);
                    if (buffer[9] != 0x51)
                    {
                        continue;
                    }

                    var mac = BitConverter.ToString(buffer, 10, 6).Replace("-", String.Empty);
                    var dev = daoFactory.DispositivoDAO.GetByIMEI(mac);
                    if (dev == null)
                    {
                        STrace.Error(GetType().FullName, String.Format("Access no esta dado de alta, dar de alta un Dispositivo con el Imei: {0}", mac));
                        continue;
                    }

                    var rfid    = BitConverter.ToString(buffer, 31, 4).Replace("-", String.Empty);
                    var entrada = StringUtils.AreBitsSet(buffer[27], 0x01);
                    var dt      = new DateTime(buffer[26] + (DateTime.UtcNow.Year / 100) * 100, buffer[25], buffer[24], buffer[23], buffer[22], buffer[21]);
                    var msg     = MessageIdentifierX.FactoryRfid(dev.Id, 0, null, dt, rfid, entrada ? 3 : 4);
                    if (msg == null)
                    {
                        STrace.Debug(GetType().FullName, dev.Id, String.Format("Se descarta: DateTime={0} UserId={1} EsEntrada={2}", dt, rfid, entrada));
                        continue;
                    }

                    STrace.Debug(GetType().FullName, String.Format("Llego: DateTime={0} UserId={1} EsEntrada={2}", dt, rfid, entrada));
                    Dispatcher.Dispatch(msg);
                }
                catch (ThreadAbortException)
                {
                    receive = false;
                }
                catch (Exception e)
                {
                    STrace.Exception(GetType().FullName, e, "Stopping Access Main Loop due to exception");
                }
            }
        }
Beispiel #5
0
        protected override HandleResults OnDeviceHandleMessage(Event message)
        {
            //STrace.Debug(typeof(Events).FullName, message.DeviceId, "OnDeviceHandleMessage (EventsHandler)");

            AdjustRfidData(message);
            var code = GetGenericEventCode(message);

            STrace.Debug(typeof(Events).FullName, message.DeviceId, String.Format("code:{0} Subcode:{1}", code, message.GetData()));

            #region protect garmin on/off messages from be banned because of invalid date

            if ((code == MessageCode.GarminOn.GetMessageCode() || code == MessageCode.GarminOff.GetMessageCode()) && message.GeoPoint != null && FechaInvalida(message.GeoPoint.Date, DeviceParameters))
            {
                message.GeoPoint.Date = DateTime.UtcNow;
            }

            #endregion protect garmin on/off messages from be banned because of invalid date

            //if (IsGarbageMessage(code))
            //{
            //    return HandleResults.BreakSuccess;
            //}

            if (IsInvalidMessage(code, message))
            {
                return(HandleResults.BreakSuccess);
            }

            ExtraText = new ExtraText(DaoFactory);

            if (MessageIdentifierX.IsEntityMessage(code))
            {
                ProcessEntityEvent(message, code);
            }
            else if (Coche != null)
            {
                var estado = GeocercaManager.CalcularEstadoVehiculo(Coche, message.GeoPoint, DaoFactory);
                ZonaManejo = estado != null && estado.ZonaManejo != null && estado.ZonaManejo.ZonaManejo > 0
                    ? DaoFactory.ZonaDAO.FindById(estado.ZonaManejo.ZonaManejo) : null;
                ProcessEvent(code, message);
                ProcessPosition(message);
            }

            return(HandleResults.Success);
        }
Beispiel #6
0
        private static string GetGenericEventCode(Event message)
        {
            var data              = message.GetData();
            var dataS             = data.ToString(CultureInfo.InvariantCulture);
            var identifier        = message.Code;
            var identifierS       = identifier.ToString(CultureInfo.InvariantCulture);
            var messageIdentifier = (MessageIdentifier)Enum.Parse(typeof(MessageIdentifier), identifierS, true);

            if (messageIdentifier.Equals(MessageIdentifier.RfidDetected))
            {
                return(GetRfidAction(data, message.GetRiderId()));
            }
            if (MessageIdentifierX.IsEstadoLogistico(message.GetData()))
            {
                return(dataS);
            }
            return((identifierS == MessageCode.SpeedingTicket.GetMessageCode()) ? MessageCode.SpeedingTicket.GetMessageCode() : GetCode(identifier, data));
        }
Beispiel #7
0
        private static bool UrbetrackUT_RFIDDetected(object sender, RFIDDetectado pdu)
        {
            var d = Devices.I().FindById(pdu.IdDispositivo);

            if (d == null)
            {
                return(false);
            }

            if (DataTransportLayer.IsRetransmission(d.Id, pdu.Seq))
            {
                return(false);
            }

            DecorateFixWithZone(pdu.Posicion);

            var msg = MessageIdentifierX.FactoryRfid(d.Id, pdu.Seq, pdu.Posicion, pdu.Posicion.GetDate(), pdu.IdTarjeta, pdu.Status);

            Dispatcher.Dispatch(msg);
            return(true);
        }
Beispiel #8
0
        private static IMessage DecodeGarminFmi(byte[] text, ulong msgId, Parser node)
        {
            byte packetId = text[1];
            //byte packetSize = text[2];
            ulong msgid = 0;

            //bool needsAck = true;

            var response = "";

            switch (packetId)
            {
            case PacketIdCode.Ack:
                byte packetIdAcked = text[3];
                STrace.Debug(typeof(GarminFmi).FullName, node.GetDeviceId(),
                             "GARMIN ACK FOR PACKET ID: 0x" + StringUtils.ByteToHexString(packetIdAcked));
                //needsAck = false;
                break;

            case PacketIdCode.UnitIdEsn:
                var unitIdEsn  = BitConverter.ToUInt32(text, 3);
                var otherStuff = BitConverter.ToUInt32(text, 7);
                STrace.Debug(typeof(GarminFmi).FullName, node.GetDeviceId(),
                             "GARMIN PACKET ID: UnitId/ESN (Command Response)");
                STrace.Debug(typeof(GarminFmi).FullName, node.GetDeviceId(),
                             "GARMIN UNIT ID/ESN: " + unitIdEsn.ToString("#0"));
                STrace.Debug(typeof(GarminFmi).FullName, node.GetDeviceId(),
                             "GARMIN OTHER STUFF: " + otherStuff.ToString("#0"));
                break;

            case PacketIdCode.DateTimeData:
                STrace.Debug(typeof(GarminFmi).FullName, node.GetDeviceId(), "GARMIN PACKET ID: DateTime Data");
                break;

            case PacketIdCode.FleetManagementPacket:
                ushort fmiPacketId    = BitConverter.ToUInt16(text, 3);
                string hexFmiPacketId = StringUtils.UInt16ToHexString(fmiPacketId);

                STrace.Debug("GarminTalk", node.Id, String.Format("RX: {0}", BitConverter.ToString(text)));

                switch (fmiPacketId)
                {
                case FmiPacketId.CsProductIdData:
                case FmiPacketId.CsProductSupportData:
                case FmiPacketId.CsUnicodeSupportRequest:
                    STrace.Debug(typeof(GarminFmi).FullName, node.Id,
                                 "La función FMI Packet ID " + hexFmiPacketId + " no esta implementada.");
                    break;

                case FmiPacketId.CsTextMessageAcknowledgement:
                    // when a canned response list text message is replied with a response, this acknowledgement is received with the response selected.
                {
                    var dt         = text.ToDateTime(5);
                    var idSize     = Convert.ToByte(text[9]);
                    var id         = BitConverter.ToUInt32(text, 13);
                    var responseId = BitConverter.ToUInt32(text, 29);

                    STrace.Debug(typeof(GarminFmi).FullName, node.GetDeviceId(),
                                 String.Format("GarminTextMessageCannedResponse: {0}",
                                               BitConverter.ToString(text)));
                    STrace.Debug(typeof(GarminFmi).FullName, node.GetDeviceId(),
                                 String.Format(
                                     "GarminTextMessageCannedResponse: dt={0}, IdSize={1}, Id={2}, ResponseId={3}",
                                     dt, idSize, id, responseId));
                    STrace.Debug(typeof(GarminFmi).FullName, node.GetDeviceId(),
                                 String.Format("GarminTextMessageCannedResponse: {0}", response));

                    var salida = (IMessage)MessageIdentifier.GarminTextMessageCannedResponse
                                 .FactoryEvent(node.Id, (UInt32)msgid, null, DateTime.UtcNow, null,
                                               new List <Int64> {
                            node.GetDeviceId(), id, responseId
                        });


                    salida.AddStringToSend(EncodeTextMessageAckReceipt(id).ToTraxFM(node).ToString(true));

                    var bcdArr = new[] { EncodeDeleteTextmessage(id).ToTraxFM(node) };
                    STrace.Debug(typeof(GarminFmi).FullName, node.Id, "StopResponse: Stop ID=" + Convert.ToString(id) + " - " + EncodeDeleteTextmessage(id).ToTraxFM(node, false));
                    Fota.EnqueueOnTheFly(node, 0, bcdArr, ref salida);

                    return(salida);
                }

                case FmiPacketId.CsTextMessageOpenClient2Server:
                {
                    msgid = node.NextSequence;             // por si hace falta lo tengo a mano
                    var dt       = text.ToDateTime(5);
                    var strText1 = Encoding.ASCII.GetString(text, 13, text[2] - 11);
                    var strText2 = StringUtils.ByteArrayToHexString(text, 9, 4);
                    STrace.Debug(typeof(GarminFmi).FullName, node.GetDeviceId(),
                                 "GARMIN A607 Client to Server Text Message (" + hexFmiPacketId + "): ID=" +
                                 msgid + ", Text=" + strText1);

                    return(FactoryEvento(node, msgid, strText1, strText2, dt));
                }

                case FmiPacketId.CsA607Client2ServerTextMessage:
                {
                    //Parser.EnsureMessagingDeviceIsGarmin(node);
                    var dt = text.ToDateTime(5);
                    msgid = BitConverter.ToUInt32(text, 17);
                    var strText1 = Encoding.ASCII.GetString(text, 41, text[2] - 39);
                    var strText2 = StringUtils.ByteArrayToHexString(text, 17, 4);
                    STrace.Debug(typeof(GarminFmi).FullName, node.GetDeviceId(),
                                 "GARMIN A607 Client to Server Text Message (" + hexFmiPacketId + "): ID=" +
                                 msgid + ", Text=" + strText1);

                    return(FactoryEvento(node, msgid, strText1, strText2, dt));
                }

                case FmiPacketId.CsCannedResponseListReceipt:
                    //STrace.Debug(typeof (GarminFmi).FullName, node.GetDeviceId(), "GARMIN PACKET ID: CANNED_RESPONSE_LIST_RECEIPT (NOT IMPLEMENTED)");
                    STrace.Trace(typeof(GarminFmi).FullName, node.GetDeviceId(),
                                 "GARMIN PACKET ID: CANNED_RESPONSE_LIST_RECEIPT:" +
                                 StringUtils.ByteArrayToHexString(text, 0, text.Length));
                    break;

                case FmiPacketId.CsTextMessageReceiptA604OpenServer2Client:
                {
                    Parser.EnsureMessagingDeviceIsGarmin(node);
                    var a604TmoprDatetime   = text.ToDateTime(5);
                    var a604TmoprIdsize     = (int)text[9];
                    var a604TmoprResultCode = (ushort)(text[10] == 0 ? 0 : 1);
                    var a604TmoprUid        = (ulong)0;
                    if (a604TmoprIdsize > 0)
                    {
                        a604TmoprUid = BitConverter.ToUInt32(text, 13);
                    }
                    return(FactoryEvento(node, packetId, a604TmoprUid, a604TmoprDatetime,
                                         a604TmoprResultCode));
                }

                case FmiPacketId.CsSetCannedResponseReceipt:
                case FmiPacketId.CsDeleteCannedResponseReceipt:
                    break;

                case FmiPacketId.CsRequestCannedResponseListRefresh:
//                            node.ReloadMessages(0);
                    break;

                case FmiPacketId.CsTextMessageStatus:
                    break;

                case FmiPacketId.CsSetCannedMessageReceipt:
                    // Sucede cuando se envian los mensajes predeterminados

/*                            STrace.Debug(typeof(GarminFmi).FullName, node.Id, "La función FMI Packet ID " + hexFMIPacketId +
 *                             " no esta implementada."); */
                    break;

                case FmiPacketId.CsDeleteCannedMessageReceipt:
                    // Sucede cuando se envian los mensajes predeterminados y se borran los mensajes no utilizados

/*                            STrace.Debug(typeof(GarminFmi).FullName, node.Id, "La función FMI Packet ID " + hexFMIPacketId +
 *                             " no esta implementada."); */
                    break;

                case FmiPacketId.CsRefreshCannedMessageList:
                case FmiPacketId.CsLongTextMessageReceiptA611LongServer2Client:
                case FmiPacketId.CsSortStopListAcknowledgement:
                case FmiPacketId.CsCreateWaypointReceipt:
                case FmiPacketId.WaypointDeleted:
                case FmiPacketId.CsDeleteWaypointByCategoryReceipt:
                case FmiPacketId.CsCreateWaypointByCategoryReceipt:
                    STrace.Debug(typeof(GarminFmi).FullName, node.Id,
                                 "La función FMI Packet ID " + hexFmiPacketId + " no esta implementada.");
                    break;

                case FmiPacketId.CsEtaData:
                {
                    msgid = BitConverter.ToUInt32(text, 5);
                    var dt         = text.ToDateTime(9);
                    var distanceTo = BitConverter.ToUInt32(text, 13);
                    var pos_lat    = text.ScToDegrees(15);
                    var pos_long   = text.ScToDegrees(17);
                    STrace.Debug(typeof(GarminFmi).FullName, node.GetDeviceId(),
                                 String.Format("GARMIN ETA DATA ({0}): ID={1}, LAT/LONG={2}/{3}, ETA={4}", hexFmiPacketId, msgid, pos_lat, pos_long,
                                               dt.ToString()));

                    setETAReceivedAt(node.Id, DateTime.UtcNow);
                    setETAEstimated(node.Id, dt);
                    setETADistanceTo(node.Id, distanceTo);

                    var salida = (IMessage)MessageIdentifier.GarminETA.FactoryEvent(node.Id, 0, null, DateTime.UtcNow, null, null);
                    salida.AddStringToSend(EncodeEtaDataReceipt((UInt32)msgid).ToTraxFM(node).ToString(true));

                    return(salida);
                }

                case FmiPacketId.CsStopStatus:
                {
                    var uid = BitConverter.ToUInt32(text, 5);
                    var ss  = BitConverter.ToUInt16(text, 9);
                    STrace.Debug(typeof(GarminFmi).FullName, node.GetDeviceId(),
                                 "GARMIN STOP STATUS (0x" + hexFmiPacketId + "): ID=" + uid);

                    var salida = (IMessage)TranslateStopStatus((StopStatusValue)ss, node.Id)
                                 .FactoryEvent(node.Id, 0, null, DateTime.UtcNow, null, new List <Int64> {
                            (int)uid
                        });

                    STrace.Debug(typeof(GarminFmi).FullName, node.Id, "StopStatus: Stop ID=" + Convert.ToString(uid) + " - " + EncodeStopStatusReceipt(uid).ToTraxFM(node, false));

                    salida.AddStringToSend(EncodeStopStatusReceipt(uid).ToTraxFM(node).ToString(true));

                    return(salida);
                }

                case FmiPacketId.CsUserInterfaceTextReceipt:
                    STrace.Debug(typeof(GarminFmi).FullName, node.GetDeviceId(),
                                 "GARMIN USER INTERFACE TEXT RECEIPT (0x" + hexFmiPacketId + ")");
                    // NOTE:    everytime UserInterfaceText is changed,
                    //          we receive this event and the gateway doesnt expect to do nothing by now.
                    break;

                case FmiPacketId.CsMessageThrottlingResponse:
                    break;

                case FmiPacketId.CsMessageThrottlingQueryResponse:
                case FmiPacketId.PingCommunicationStatus:
                    STrace.Debug(typeof(GarminFmi).FullName, node.Id, "La función FMI Packet ID " + hexFmiPacketId + " no esta implementada.");
                    //needsAck = false;
                    break;

                case FmiPacketId.PingCommunicationStatusResponse:
                    node.IsGarminConnected = true;
                    STrace.Debug(typeof(GarminFmi).FullName, node.GetDeviceId(), "GARMIN PONG received");
                    //needsAck = false;
                    break;

                case FmiPacketId.CsGpiFileStartReceipt:
                case FmiPacketId.CsGpiPacketReceipt:
                case FmiPacketId.CsGpiFileEndReceipt:
                case FmiPacketId.CsGpiFileInformation:
                case FmiPacketId.CsSetDriverStatusListItemReceipt:
                case FmiPacketId.CsDeleteDriverStatusListItemReceipt:
                case FmiPacketId.CsDriverStatusListRefresh:
                    STrace.Debug(typeof(GarminFmi).FullName, node.Id, "La función FMI Packet ID " + hexFmiPacketId + " no esta implementada.");
                    break;

                case FmiPacketId.DriverIdUpdate:
                {
                    msgid = node.NextSequence;
                    var changeId   = BitConverter.ToUInt32(text, 5);
                    var changeTime = text.ToDateTime(9);
                    var driverId   = text.GetString(13);
                    var rfid       = GetRfidFromDriverId(driverId);
                    STrace.Debug(typeof(GarminFmi).FullName, node.GetDeviceId(),
                                 "GARMIN DRIVER ID UPDATE (" + hexFmiPacketId + "): ID=" + driverId +
                                 ", RFID=" + rfid);


                    var salida = (IMessage)MessageIdentifierX.FactoryRfid(node.Id, msgid, null, changeTime, rfid, 0);

                    salida.AddStringToSend(EncodeDriverIdReceipt(changeId).ToTraxFM(node).ToString(true));

                    return(salida);
                }

                case FmiPacketId.DriverIdReceipt:
                    STrace.Debug(typeof(GarminFmi).FullName, node.Id, "La función FMI Packet ID " + hexFmiPacketId + " no esta implementada.");
                    break;

                case FmiPacketId.ScA607DriverIdUpdate:
                {
                    msgid = node.NextSequence;
                    var changeId   = BitConverter.ToUInt32(text, 5);
                    var changeTime = text.ToDateTime(9);
                    var driverId   = text.GetString(17);
                    var rfid       = GetRfidFromDriverId(driverId);

                    STrace.Debug(typeof(GarminFmi).FullName, node.GetDeviceId(),
                                 "GARMIN DRIVER ID UPDATE (" + hexFmiPacketId + "): ID=" + driverId +
                                 ", RFID=" + rfid);


                    var salida = (IMessage)MessageIdentifierX.FactoryRfid(node.Id, msgid, null, changeTime, rfid, 0);
                    salida.AddStringToSend(EncodeDriverIdReceipt(changeId).ToTraxFM(node).ToString(true));
                    return(salida);
                }

                case FmiPacketId.DriverStatusUpdate:
                case FmiPacketId.DriverStatusReceipt:
                case FmiPacketId.A607DriverStatusUpdate:
                case FmiPacketId.CsFmiSafeModeReceipt:
                case FmiPacketId.CsSpeedLimitAlertSetupReceipt:
                case FmiPacketId.CsSpeedLimitAlert:
                    STrace.Debug(typeof(GarminFmi).FullName, node.Id, "La función FMI Packet ID " + hexFmiPacketId + " no esta implementada.");
                    break;
                }
                break;

            case PacketIdCode.NAck:
                node.LastSent = null;
                STrace.Debug(typeof(GarminFmi).FullName, node.GetDeviceId(), "GARMIN PACKET ID: NACK (NOT IMPLEMENTED)");
                //needsAck = false;
                break;

            case PacketIdCode.PvtData:
                msgid = node.NextSequence;
                STrace.Debug(typeof(GarminFmi).FullName, node.GetDeviceId(), "GARMIN PACKET ID: PVT DATA");
                STrace.Debug(typeof(GarminFmi).FullName, node.GetDeviceId(), "GARMIN PVTDATA:" + msgid);
                //needsAck = false;
                break;

            case PacketIdCode.StreetPilotStopMessage:
                STrace.Debug(typeof(GarminFmi).FullName, node.GetDeviceId(), "GARMIN PACKET ID: STREET PILOT STOP MESSAGE");
                break;

            case PacketIdCode.StreetPilotTextMessage:
                STrace.Debug(typeof(GarminFmi).FullName, node.GetDeviceId(), "GARMIN PACKET ID: STREET PILOT TEXT MESSAGE");
                break;
            }

            return(null);

            //if (needsAck)
            //{
            //    var salida = (IMessage) new UserMessage(node.Id, 0);
            //    var cmd = BaseDeviceCommand.createFrom(String.Format(Mensaje.GarminFm, GetHexAckFor(packetId)), node, DateTime.UtcNow.AddSeconds(30)).ToString(true);
            //    salida.AddStringToSend(cmd);
            //    return salida;
            //}

            //return null;
        }
Beispiel #9
0
        public OutData[] Process(int empresa, int linea, QueryParams parameters)
        {
            var data = new OutData("fichada");

            try
            {
                var server = parameters.ContainsKey("server") ? parameters["server"] : string.Empty;

                if (!parameters.ContainsKey("data"))
                {
                    throw new ApplicationException("No se encontraron los datos de la fichada");
                }
                var pq    = parameters["data"];
                var parts = pq.Split(':');
                if (pq[0] != 'F' || parts.Length != 7)
                {
                    throw new ApplicationException("Format de paquete incorrecto");
                }
                var equipo    = System.Convert.ToInt16(parts[1]);
                var point     = parts[2];
                var tipo      = parts[3];
                var fecha     = parts[4];
                var tarjeta   = System.Convert.ToInt32(parts[5]);
                var direccion = parts[6];
                var datetime  = new DateTime(System.Convert.ToInt32(fecha.Substring(0, 4)),
                                             System.Convert.ToInt32(fecha.Substring(4, 2)),
                                             System.Convert.ToInt32(fecha.Substring(6, 2)),
                                             System.Convert.ToInt32(fecha.Substring(8, 2)),
                                             System.Convert.ToInt32(fecha.Substring(10, 2)),
                                             System.Convert.ToInt32(fecha.Substring(12, 2)));


                var puerta = DaoFactory.PuertaAccesoDAO.FindByCodigo(empresa, linea, equipo);
                if (puerta == null)
                {
                    throw new ApplicationException("No se encontró una puerta con el código " + equipo);
                }
                if (puerta.Vehiculo == null)
                {
                    throw new ApplicationException("La puerta " + equipo + " no tiene un vehiculo asignado");
                }
                if (puerta.Vehiculo.Dispositivo == null)
                {
                    throw new ApplicationException("La puerta " + equipo + " no tiene un dispositivo asignado");
                }
                var device = puerta.Vehiculo.Dispositivo.Id;
                var tarj   = DaoFactory.TarjetaDAO.FindList(new[] { empresa }, new[] { linea }).FirstOrDefault(trj => Convert.GetPinCerbero(trj) == tarjeta);
                var pin    = tarj != null ? tarj.Pin : tarjeta.ToString();
                var t      = direccion == "0" ? 3 : 4; //3: Login Empleado, 4: Logout Empleado
                var msg    = MessageIdentifierX.FactoryRfid(device, 0, null, datetime, pin, t);

                var queue = GetDispatcherQueue();
                if (queue == null)
                {
                    throw new ApplicationException("No se pudo crear la cola");
                }
                queue.Send(msg);

                data.AddProperty("done", "true");

                return(new[] { data });
            }
            catch (Exception ex)
            {
                data.AddProperty("done", "false");
                data.AddProperty("message", ex.ToString());
                return(new[] { data });
            }
        }
Beispiel #10
0
        private void ProcessTaco(String file)
        {
            Empresa     empresa     = null;
            Dispositivo dev         = null;
            var         errorslist  = new List <String>();
            var         infoList    = new List <String>();
            var         moveAllFile = false;
            var         maxvel      = 0;
            var         maxrpm      = 0;
            String      chofer      = null;
            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 "6":                                                         //"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]).Dispositivo;
                                    if (dev == null)
                                    {
                                        throw new InvalidDataException(String.Format("No se encontro el dispositivo o el movil: {0}", datos[2]));
                                    }
                                    lastdt = GetLastDt(dev);
                                    break;

                                case "11":                                                         //"Velocidad Maxima Programada"
                                    maxvel = Convert.ToInt32(datos[2], CultureInfo.InvariantCulture);
                                    break;

                                case "12":                                                         //"RPM Maxima Programada"
                                    maxrpm = Convert.ToInt32(datos[2], CultureInfo.InvariantCulture);
                                    break;
                                }
                            }
                            catch
                            {
                                moveAllFile = true;
                                throw;
                            }
                            break;
                        }

                        case "2":                                 //data
                        {
                            if (dev == null)
                            {
                                moveAllFile = true;
                                throw new ArgumentNullException("", "Primero declare el movil!");
                            }
                            // usar el odometro para algo?
                            try
                            {
                                switch (datos[1])
                                {
                                //default:
                                //STrace.Trace(GetType().FullName, "Tipo de linea de datos ignorada: {0}", line);
                                //break;
                                case "1":                                                         //"Dato simple"
                                {
                                    //2@1@0@20111118@144100@27@270          "Evento;R;Fecha;Hora;Velocidad;Kilometros"
                                    var dt = DateTimeUtils.SafeParseFormat(datos[3] + datos[4].PadLeft(6, '0'), "yyyyMMddHHmmss");
                                    //var code = (MessageIdentifier) Convert.ToInt16(datos[2], CultureInfo.InvariantCulture);
                                    //Dispatcher_Dispatch(code.FactoryEvent(dev.Id, 0, null, dt, null, null));
                                    ////
                                    ReportOdometer(datos[6], datos[5], dev, dt, chofer, lastdt, repro, ref latestdt);
                                    break;
                                }

                                case "2":                                                         //"Motor apagado"
                                {
                                    var dt = DateTimeUtils.SafeParseFormat(datos[3] + datos[4].PadLeft(6, '0'), "yyyyMMddHHmmss");
                                    DispatcherDispatch(MessageIdentifier.EngineOffInternal.FactoryEvent(dev.Id, 0, null, dt, chofer, null), lastdt, repro, ref latestdt);
                                    //
                                    ReportOdometer(datos[6], datos[5], dev, dt, chofer, lastdt, repro, ref latestdt);
                                    break;
                                }

                                case "3":                                                         //"Motor encendido"
                                {
                                    var dt = DateTimeUtils.SafeParseFormat(datos[3] + datos[4].PadLeft(6, '0'), "yyyyMMddHHmmss");
                                    DispatcherDispatch(MessageIdentifier.EngineOnInternal.FactoryEvent(dev.Id, 0, null, dt, chofer, null), lastdt, repro, ref latestdt);
                                    //
                                    ReportOdometer(datos[6], datos[5], dev, dt, chofer, lastdt, repro, ref latestdt);
                                    break;
                                }

                                case "4":                                                         //"Aceleracion Brusca"
                                {
                                    //2@4@23418@20111202@135000@0@874           "Evento;CHOFER;Fecha;Hora;R;Kilometros"
                                    var dt = DateTimeUtils.SafeParseFormat(datos[3] + datos[4].PadLeft(6, '0'), "yyyyMMddHHmmss");
                                    chofer = GetChoferPin(empresa, datos[2], dev.Id);
                                    DispatcherDispatch(MessageIdentifier.AccelerationEvent.FactoryEvent(dev.Id, 0, null, dt, chofer, null), lastdt, repro, ref latestdt);
                                    //
                                    ReportOdometer(datos[6], null, dev, dt, chofer, lastdt, repro, ref latestdt);
                                    break;
                                }

                                case "5":                                                         //"Desaceleracion Brusca"
                                {
                                    var dt = DateTimeUtils.SafeParseFormat(datos[3] + datos[4].PadLeft(6, '0'), "yyyyMMddHHmmss");
                                    chofer = GetChoferPin(empresa, datos[2], dev.Id);
                                    DispatcherDispatch(MessageIdentifier.DesaccelerationEvent.FactoryEvent(dev.Id, 0, null, dt, chofer, null), lastdt, repro, ref latestdt);
                                    //
                                    ReportOdometer(datos[6], null, dev, dt, chofer, lastdt, repro, ref latestdt);
                                    break;
                                }

                                case "6":                                                         //"Inicio Infraccion"
                                {
                                    //2@6@23418@20111203@203405@23418@880       "Evento;CHOFER;Fecha;Hora;CHOFER;Kilometros"
                                    var dt = DateTimeUtils.SafeParseFormat(datos[3] + datos[4].PadLeft(6, '0'), "yyyyMMddHHmmss");
                                    chofer = GetChoferPin(empresa, datos[2], dev.Id);
                                    DispatcherDispatch(MessageIdentifier.SpeedingTicketInit.FactoryEvent(dev.Id, 0, null, dt, chofer, null), lastdt, repro, ref latestdt);
                                    //
                                    ReportOdometer(datos[6], null, dev, dt, chofer, lastdt, repro, ref latestdt);
                                    break;
                                }

                                case "7":                                                         //"Fin Infraccion"
                                {
                                    //2@7@23418@20111203@203405@195@2           "Evento;CHOFER;Fecha;Hora;Velocidad MAXIMA;minutos de infraccion"
                                    var dt = DateTimeUtils.SafeParseFormat(datos[3] + datos[4].PadLeft(6, '0'), "yyyyMMddHHmmss");
                                    chofer = GetChoferPin(empresa, datos[2], dev.Id);
                                    var lista = new List <Int64>
                                    {
                                        Convert.ToInt32(datos[5], CultureInfo.InvariantCulture),                                                                                 //reached speed
                                        Convert.ToInt32(datos[6], CultureInfo.InvariantCulture) * 60,                                                                            //duration
                                        maxvel,
                                    };

                                    DispatcherDispatch(MessageIdentifier.SpeedingTicketEnd.FactoryEvent(dev.Id, 0, null, dt, chofer, lista), lastdt, repro, ref latestdt);
                                    break;
                                }

                                case "9":                                                         //"Desconexion"
                                {
                                    //2@9@23418@20111119@203405@213000@20111119@0     "Evento;CHOFER;Fecha(reco);Hora;Hora(desco);Fecha;R"
                                    var dt = DateTimeUtils.SafeParseFormat(datos[3] + datos[4].PadLeft(6, '0'), "yyyyMMddHHmmss");
                                    chofer = GetChoferPin(empresa, datos[2], dev.Id);
                                    var dt2 = DateTimeUtils.SafeParseFormat(datos[6] + datos[5].PadLeft(6, '0'), "yyyyMMddHHmmss");
                                    DispatcherDispatch(MessageIdentifier.SensorPowerDisconected.FactoryEvent(dev.Id, 0, null, dt2, chofer, null), lastdt, repro, ref latestdt);
                                    DispatcherDispatch(MessageIdentifier.SensorPowerReconected.FactoryEvent(dev.Id, 0, null, dt, chofer, null), lastdt, repro, ref latestdt);
                                    break;
                                }

                                case "10":                                                         //"Inicio RPM Maxima"
                                {
                                    //2@10@23418@20111119@203405@0@339          "Evento;R;Fecha;Hora;Velocidad;R;Kilometros"
                                    //todo, este ejemplo tomado del mail no concuerda con su descripcion...
                                    var dt = DateTimeUtils.SafeParseFormat(datos[3] + datos[4].PadLeft(6, '0'), "yyyyMMddHHmmss");
                                    //var chofer = GetChoferPin(empresa, datos[2], dev.Id);
                                    DispatcherDispatch(MessageIdentifier.RpmTicketInit.FactoryEvent(dev.Id, 0, null, dt, chofer, null), lastdt, repro, ref latestdt);
                                    //
                                    ReportOdometer(datos[6], datos[5], dev, dt, chofer, lastdt, repro, ref latestdt);
                                    break;
                                }

                                case "11":                                                         //"Final RPM Maxima"
                                {
                                    //2@11@23418@20111119@203500@0@10300        "Evento;R;Fecha;Hora;Velocidad;R;RPM MAXIMA"
                                    //todo, este ejemplo tomado del mail no concuerda con su descripcion...
                                    var dt = DateTimeUtils.SafeParseFormat(datos[3] + datos[4].PadLeft(6, '0'), "yyyyMMddHHmmss");
                                    //var chofer = GetChoferPin(empresa, datos[2], dev.Id);
                                    DispatcherDispatch(MessageIdentifier.RpmTicketEnd.FactoryEvent(dev.Id, 0, null, dt, chofer, new List <Int64> {
                                                Convert.ToInt32(datos[6], CultureInfo.InvariantCulture), maxrpm
                                            }), lastdt, repro, ref latestdt);
                                    //
                                    ReportOdometer(null, datos[5], dev, dt, chofer, lastdt, repro, ref latestdt);
                                    break;
                                }

                                case "12":                                                         //"Inicio Chofer"
                                {
                                    //2@12@23418@20111120@132302@0@23418        "Evento;CHOFER;Fecha;Hora;R;CHOFER;"
                                    var dt = DateTimeUtils.SafeParseFormat(datos[3] + datos[4].PadLeft(6, '0'), "yyyyMMddHHmmss");
                                    chofer = GetChoferPin(empresa, datos[2], dev.Id);
                                    DispatcherDispatch(MessageIdentifierX.FactoryRfid(dev.Id, 0, null, dt, chofer, 0), lastdt, repro, ref latestdt);
                                    break;
                                }

                                case "13":                                                         //"Final Chofer"
                                {
                                    var dt = DateTimeUtils.SafeParseFormat(datos[3] + datos[4].PadLeft(6, '0'), "yyyyMMddHHmmss");
                                    chofer = GetChoferPin(empresa, datos[2], dev.Id);
                                    DispatcherDispatch(MessageIdentifierX.FactoryRfid(dev.Id, 0, null, dt, chofer, 1), lastdt, repro, ref latestdt);
                                    chofer = null;
                                    break;
                                }

                                case "15":                                                         //"Servicio Tecnico"
                                {
                                    var dt = DateTimeUtils.SafeParseFormat(datos[3] + datos[4].PadLeft(6, '0'), "yyyyMMddHHmmss");
                                    DispatcherDispatch(MessageIdentifier.TechnicalService.FactoryEvent(dev.Id, 0, null, dt, chofer, null), lastdt, repro, ref latestdt);
                                    break;
                                }

                                case "30":                                                         //"Movimiento desde hasta y minutos de marcha"
                                {
                                    //2@30@23418@20111119@81800@85200@34        "Evento;CHOFER;Fecha;Hora INI;Hora FIN;Minutos de marcha"
                                    var dt    = DateTimeUtils.SafeParseFormat(datos[3] + datos[5].PadLeft(6, '0'), "yyyyMMddHHmmss");
                                    var lista = new List <Int64>
                                    {
                                        (Int32)(DateTimeUtils.SafeParseFormat(datos[3] + datos[4].PadLeft(6, '0'), "yyyyMMddHHmmss") - dt).TotalSeconds,                            //duration evento
                                        Convert.ToInt32(datos[6], CultureInfo.InvariantCulture) * 60,                                                                               //durationmarcha
                                    };
                                    chofer = GetChoferPin(empresa, datos[2], dev.Id);
                                    //DispatcherDispatch(MessageIdentifier.TraveledLeg.FactoryEvent(dev.Id, 0, null, dt, chofer, lista), lastdt, repro, ref latestdt);
                                    break;
                                }

                                case "31":                                                         //"Ultimo dato de detenido?"
                                {
                                    //2@31@23418@20111119@85200@0@327           "Evento;CHOFER;Fecha;Hora;R;Kilometros"
                                    var dt = DateTimeUtils.SafeParseFormat(datos[3] + datos[4].PadLeft(6, '0'), "yyyyMMddHHmmss");
                                    chofer = GetChoferPin(empresa, datos[2], dev.Id);
                                    DispatcherDispatch(MessageIdentifier.StoppedEvent.FactoryEvent(dev.Id, 0, null, dt, chofer, null), lastdt, repro, ref latestdt);
                                    //
                                    ReportOdometer(datos[6], null, dev, dt, chofer, lastdt, repro, ref latestdt);
                                    break;
                                }
                                }
                            }
                            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);
        }
Beispiel #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, 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);
            }
        }
Beispiel #12
0
        protected override void OnExecute(Timer timer)
        {
            STrace.Trace(ComponentName, "Inicio de la tarea");
            var queue = GetDispatcherQueue();

            if (queue == null)
            {
                STrace.Error(ComponentName, "No se encontró la cola del Dispatcher");
                return;
            }

            var puertas = DaoFactory.PuertaAccesoDAO.GetList(new[] { -1 }, new[] { -1 });

            foreach (var puertaAcceso in puertas)
            {
                if (puertaAcceso.Vehiculo != null && puertaAcceso.Vehiculo.Dispositivo != null && DaoFactory.DetalleDispositivoDAO.GetAccesoHabilitadoValue(puertaAcceso.Vehiculo.Dispositivo.Id))
                {
                    STrace.Trace(ComponentName, String.Format("Acceso habilitado: {0}", puertaAcceso.Descripcion));
                    var ip     = DaoFactory.DetalleDispositivoDAO.GetAccesoIpValue(puertaAcceso.Vehiculo.Dispositivo.Id);
                    var user   = DaoFactory.DetalleDispositivoDAO.GetAccesoUsuarioValue(puertaAcceso.Vehiculo.Dispositivo.Id);
                    var pass   = DaoFactory.DetalleDispositivoDAO.GetAccesoPasswordValue(puertaAcceso.Vehiculo.Dispositivo.Id);
                    var inicio = DaoFactory.DetalleDispositivoDAO.GetAccesoInicioValue(puertaAcceso.Vehiculo.Dispositivo.Id);
                    STrace.Trace(ComponentName, String.Format("IP: {0}, User: {1}, Pass: {2}, Inicio: {3}", ip, user, pass, inicio.ToString("dd/MM/yyyy")));

                    var ultimoAcceso = DaoFactory.EventoAccesoDAO.FindLastEventForCompanyAndBase(puertaAcceso.Empresa.Id,
                                                                                                 puertaAcceso.Linea != null
                                                                                                    ? puertaAcceso.Linea.Id
                                                                                                    : -1,
                                                                                                 DateTime.UtcNow);
                    var lastLog = ultimoAcceso != null?ultimoAcceso.Fecha.AddHours(-3) : inicio;

                    STrace.Trace(ComponentName, String.Format("LastLog: {0}", lastLog.ToString("dd/MM/yyyy HH:mm:ss")));

                    var pct100Dumper = new Pct100Dumper(new Uri("http://" + ip), user, pass, lastLog, DateTime.UtcNow);
                    var reader       = new StreamReader(pct100Dumper.Execute());
                    var archivo      = reader.ReadToEnd();
                    var accesos      = archivo.Replace("\r\n", "|").Split('|');
                    var logueos      = new List <Logueo>();

                    for (var i = 1; i < accesos.Length - 1; i++)
                    {
                        try
                        {
                            var campos = accesos[i].Split(',');
                            if (campos.Length != 8)
                            {
                                STrace.Trace(ComponentName, String.Format("No se puede parsear: {0}", accesos[i]));
                                continue;
                            }
                            var nroTarjeta = campos[3];
                            var date       = campos[4].Split('/');
                            var mes        = Convert.ToInt32(date[0]);
                            var dia        = Convert.ToInt32(date[1]);
                            var anio       = Convert.ToInt32(date[2]);
                            var time       = campos[5].Split(':');
                            var hora       = Convert.ToInt32(time[0]);
                            var min        = Convert.ToInt32(time[1]);
                            var seg        = Convert.ToInt32(time[2]);
                            var evento     = campos[6];

                            var log = new Logueo
                            {
                                NroTarjeta = nroTarjeta,
                                Fecha      = new DateTime(anio, mes, dia, hora, min, seg, DateTimeKind.Utc),
                                Evento     = evento == "Entrada" ? 3 : 4
                            };

                            STrace.Trace(ComponentName, String.Format("LogFecha: {0}, LastLog: {1}", log.Fecha, lastLog));

                            if (log.Fecha > lastLog)
                            {
                                STrace.Trace(ComponentName, String.Format("Acceso: {0}", accesos[i]));
                                logueos.Add(log);
                            }
                        }
                        catch (Exception ex)
                        {
                            STrace.Exception(ComponentName, ex);
                        }
                    }

                    foreach (var logueo in logueos.OrderBy(l => l.Fecha))
                    {
                        STrace.Debug(ComponentName, String.Format("Envio: DateTime={0} Rfid={1} Evento={2}", logueo.Fecha.AddHours(3), logueo.NroTarjeta, logueo.Evento));
                        var msg = MessageIdentifierX.FactoryRfid(puertaAcceso.Vehiculo.Dispositivo.Id, 0, null, logueo.Fecha.AddHours(3), logueo.NroTarjeta, logueo.Evento);
                        queue.Send(msg);
                    }
                }
                else
                {
                    STrace.Trace(ComponentName, String.Format("Acceso no habilitado: {0}", puertaAcceso.Descripcion));
                }
            }
        }
Beispiel #13
0
        public override IMessage Decode(IFrame frame)
        {
            try
            {
                var type = frame.Payload[0];
                var time = GetTiempo(BitConverter_BigEndian.ToInt32(frame.Payload, 1));
                switch (type)
                {
                case 1:     //posicion
                    var lat   = (float)(BitConverter_BigEndian.ToUInt24(frame.Payload, 5) / 100000.0);
                    var lon   = (float)(BitConverter_BigEndian.ToUInt24(frame.Payload, 8) / 100000.0);
                    var signs = frame.Payload[11];
                    if (BitHelper.IsBitSet(signs, 2))
                    {
                        lat *= -1;
                    }
                    if (BitHelper.IsBitSet(signs, 1))
                    {
                        lon *= -1;
                    }
                    STrace.Debug(GetType().FullName, String.Format("posicion: {0}:{1}:{2} === {3}", time, lat, lon, frame.Payload));
                    return(GPSPoint.Factory(time, lat, lon).ToPosition(Id, 0));

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

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

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

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

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

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

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

                    default:
                        return(null);
                    }

                default:
                    return(null);
                }
            }
            catch (Exception e)
            {
                STrace.Exception(GetType().FullName, e, Id, String.Format("Parser Orbcomm message: {0}", frame.Payload));
                return(null);
            }
        }
Beispiel #14
0
        private void ProcessEvent(string code, Event generico)
        {
            string applicationCode;
            var    esConfirmacionUbox = false;

            ControlarInicioDistribucionPorMensaje(code, generico);

            ControlarCierreDistribucionPorMensaje(code, generico);

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

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

                if (point != null)
                {
                    if (esConfirmacionUbox)
                    {
                        ProcessConfirmacionUbox(code, generico, point);
                    }
                    else
                    {
                        CicloLogisticoFactory.Process(DaoFactory, applicationCode, Coche, point, generico, false, GetChofer(generico.GetRiderId()));
                        CicloLogisticoFactory.ProcessEstadoLogistico(Coche, generico, applicationCode);
                    }
                }
                else if (esConfirmacionUbox)
                {
                    ProcessGenericEvent(generico, code);
                }
            }
        }
Beispiel #15
0
        private static IMessage GetSalidaReal(GPSPoint gpsPoint, String rfid, int codEv, INode device, ulong msgId, byte[] data)
        {
            MessageIdentifier codigo;

            switch (codEv)             // codigo del Evento generador del reporte
            {
            case Evento.MotorOn:             codigo = MessageIdentifier.EngineOnInternal;           break;

            case Evento.MotorOff:            codigo = MessageIdentifier.EngineOffInternal;          break;

            case Evento.GarminOn:            codigo = MessageIdentifier.GarminOn;                           break;

            case Evento.GarminOff:           codigo = MessageIdentifier.GarminOff;                          break;

            case Evento.PanicButtonOn:       codigo = MessageIdentifier.PanicButtonOn;                      break;

            case Evento.PanicButtonOff:      codigo = MessageIdentifier.PanicButtonOff;                     break;

            case Evento.AmbulanciaSirenaOn:  codigo = MessageIdentifier.SirenOn;                            break;

            case Evento.AmbulanciaSirenaOff: codigo = MessageIdentifier.SirenOff;                           break;

            case Evento.AmbulanciaBalizaOn:  codigo = MessageIdentifier.BeaconOn;                           break;

            case Evento.AmbulanciaBalizaOff: codigo = MessageIdentifier.BeaconOff;                          break;

            case Evento.GsmOn:               codigo = MessageIdentifier.GsmSignalOn;                        break;

            case Evento.GsmOff:              codigo = MessageIdentifier.GsmSignalOff;                       break;

            case Evento.GpsSignalOn:         codigo = MessageIdentifier.GpsSignalOn;                        break;

            case Evento.GpsSignalOff:        codigo = MessageIdentifier.GpsSignalOff;                       break;

            case Evento.Gps3DSignalOff:      codigo = MessageIdentifier.GpsSignal3DOff;                     break;

            case Evento.Gps2DSignalOn:       codigo = MessageIdentifier.GpsSignal2DOn;                      break;

            case Evento.PistonOff:           codigo = MessageIdentifier.PistonOff;                          break;

            case Evento.PistonOn:            codigo = MessageIdentifier.PistonOn;                           break;

            case Evento.DistanciaSinChofer:  codigo = MessageIdentifier.NoDriverMovement;           break;

            case Evento.DistanciaMotorOff:   codigo = MessageIdentifier.NoEngineMovement;           break;

            case Evento.ChoferLoggedOn:  return(MessageIdentifierX.FactoryRfid(device.Id, msgId, gpsPoint, gpsPoint.GetDate(), rfid, 0));

            case Evento.ChoferLoggedOff: return(MessageIdentifierX.FactoryRfid(device.Id, msgId, gpsPoint, gpsPoint.GetDate(), rfid, 1));

            case Evento.Infraccion:
                var maxVel       = data[14];
                var maxPermitida = Speed.KmToKnot(80);                         //volvemos al hardcoded ya q no hay qtree
                var posIni       = device.Retrieve <GPSPoint>("IniInfraccion") ?? gpsPoint;
                return(new SpeedingTicket(device.Id, msgId, posIni, gpsPoint, maxVel, maxPermitida, rfid));

            case Evento.InfraccionInicio:
                device.Store("IniInfraccion", gpsPoint);
                goto default;

            default:
                return(gpsPoint.ToPosition(device.Id, msgId));
            }
            return(codigo.FactoryEvent(device.Id, msgId, gpsPoint, gpsPoint.GetDate(), rfid, null));
        }