public bool ReloadRoute(ulong messageId, Destination[] route, bool sort, int routeId) { string cmd = null; var md = GetMessagingDevice(); switch (md) { case MessagingDevice.Garmin: var config = new StringBuilder(); config.AppendFormat("{0}{1}", BaseDeviceCommand.createFrom(">SSG161<", this, null).ToString(false), Environment.NewLine); //config.Append(GarminFmi.EncodeDataDeletionFor(DataDeletionProtocolId.DeleteAllStopsOnTheClient).ToTraxFM(this, false)); foreach (var p in route) { var stopStr = GarminFmi.EncodeA603StopProtocol(p.Point, p.Code, p.Text).ToTraxFM(this, false); //STrace.Debug(typeof(GarminFmi).FullName, Id, "ReloadRoute: Stop ID=" + Convert.ToString(p.Code) + " - " + stopStr); config.Append(stopStr); } config.Append(Environment.NewLine); config.Append(Fota.VirtualMessageFactory(MessageIdentifier.ReloadRouteSuccess, NextSequence)); cmd = config.ToString(); break; case MessagingDevice.Mpx01: break; } SendMessages(cmd, messageId, md); return(true); }
private void CheckFota(int msgId) { if (Lastsentmessageid == (ulong)msgId) { Fota.Dequeue(this, null); } }
public bool UnloadRoute(ulong messageId, Destination[] route, int routeId) { string cmd = null; var md = GetMessagingDevice(); switch (md) { case MessagingDevice.Garmin: var config = new StringBuilder(); config.AppendFormat("{0}{1}", BaseDeviceCommand.createFrom(">SSG160<", this, null).ToString(false), Environment.NewLine); config.Append(GarminFmi.EncodeDataDeletionFor(DataDeletionProtocolId.DeleteAllStopsOnTheClient).ToTraxFM(this, false)); foreach (var p in route) { config.Append(GarminFmi.EncodeDeleteTextmessage((UInt32)p.Code).ToTraxFM(this, false)); } config.Append(Environment.NewLine); config.Append(Fota.VirtualMessageFactory(MessageIdentifier.UnloadRouteSuccess, 0)); cmd = config.ToString(); break; case MessagingDevice.Mpx01: break; } SendMessages(cmd, messageId, md); return(true); }
private void SendMessages(String config, ulong messageId, String md) { if (string.IsNullOrEmpty(config)) { return; } switch (md) { case MessagingDevice.Garmin: Fota.EnqueueGarmin(this, messageId, config); break; default: Fota.Enqueue(this, messageId, config); break; } /* IMessage msg = null; * SendPendingFota(ref msg); * if (msg == null) return; * * STrace.Debug(typeof (Parser).FullName, Id, String.Format("Enviando: {0}", msg.GetPendingAsString())); * DataLinkLayer.SendMessage(Id, msg); */ }
private void CheckFota(ulong msgid) { if (LastSent.GetId() == msgid) { Fota.Dequeue(this, null); } }
public static void ForceReplyCheckingFota(this IMessage msg, bool canappend, IFoteable dev) { if ((msg == null) || !canappend) { return; } var pending = Fota.Peek(dev); if (!String.IsNullOrEmpty(pending)) { var lmid = dev.GetMessageId(pending); if (pending.Contains("///;#")) { pending = pending.Substring(0, pending.IndexOf("///;#")); } var lastmsg = dev.LastSent.GetText(null); STrace.Debug(typeof(UnexUtils).FullName, dev.GetDeviceId(), String.Format("ForceReplyCheckingFota 2: lastmsg={0} pending={1}", lastmsg, pending)); if (lastmsg != pending) { dev.LastSent = new INodeMessage(lmid, pending, DateTime.UtcNow); } msg.AddStringToSend(pending); } else { //HACK: si no le respondo algo a estos equipos se cuelgan un rato y pasan a estar en amarillo if (String.IsNullOrEmpty(msg.GetPendingAsString())) { msg.AddStringToSend("B"); } } }
private void CheckFota(ulong mid) { STrace.Trace(GetType().FullName, Id, String.Format("CheckFota: LastSent.GetId()={0} mid={1}", LastSent.GetId(), mid)); if (mid != 10000) //if (LastSent.GetId() == mid) { Fota.Dequeue(this, null); } }
private static int GetPendingFotaRevision(IFoteable Device) { var line = Fota.FindLast(Device, ">SSDG1,W0000008004", true) ?? ">SSDG1,W000000800400000000<"; line = line.Substring(line.IndexOf("04") + 2).TrimEnd('<'); var bytes = StringUtils.HexStringToByteList(line, 0).ToArray(); var value = BitConverter.ToInt32(bytes, 0); return(value); }
private IMessage Decode2(string buffer) { if (buffer == null) { return(null); } if (ParserUtils.IsInvalidDeviceId(Id) && !buffer.StartsWith(Reporte.HandShake)) { return(FactoryQueryHandShake(this)); } IMessage salida; var data = buffer.Split(';')[0].Split(','); var pos = GetPos(data); var msgId = GetMessageId(buffer); var tipoReporte = data[0]; //var requestTimestamp = data.SingleOrDefault(s => s.StartsWith("rt")); switch (tipoReporte) { case Reporte.HandShake: salida = FactoryHandShake(this, data, msgId, pos, DataProvider); break; case Reporte.KeepAlive: salida = FactoryKeepAlive(this, data, msgId); break; case Reporte.Position: salida = FactoryPositionOrEvent(this, data, msgId); break; case Reporte.Mensaje: salida = FactoryMensaje(this, data, msgId, pos); break; default: //es un ack o un mensaje no reconocido, no se responde, solo paso la info arriba salida = new UserMessage(Id, msgId); break; } CheckFota((int)msgId); var fotaCmd = Fota.Peek(this); if (!(salida is ConfigRequest) && !string.IsNullOrEmpty(fotaCmd)) { Lastsentmessageid = (ulong)GetMsgId(fotaCmd); salida.AddStringToPostSend(fotaCmd); } return(salida); }
private void SendMessages(String config, ulong messageId, String md) { if (string.IsNullOrEmpty(config)) { return; } switch (md) { default: Fota.Enqueue(this, messageId, config); break; } }
private void SendMessages(String text, ulong sequence, ulong messageId, Boolean sendnowflag) { //STrace.Debug("", Id, "SendMessages did={0} msg={1}", Id, text); var msg = new UserMessage(Id, sequence).AddStringToSend(text); if (!sendnowflag) { Fota.Enqueue(this, messageId, text); } else { DataLinkLayer.SendMessage(Id, msg); } }
private String GetFirm() { string[] fw = Encoding.ASCII.GetString(DataProvider.GetFirmware(Id)).Split(new[] { "\r\n", "\n", Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < fw.Length; i++) { fw[i] = String.Format(">SFUS{0:X4}{1}<", i, fw[i]); } return(String.Join(Environment.NewLine, fw) + fw[0].Replace(">SFUS0000", ">SFUSFFFF") + Environment.NewLine + ">SSR55AA<" + Environment.NewLine + Fota.VirtualMessageFactory(MessageIdentifier.FotaSuccess, NextSequence)); }
public bool SubmitTextMessage(ulong messageId, uint textMessageId, String textMessage, uint[] replies, int ackEvent) { STrace.Debug(typeof(Parser).FullName, Id, "SubmitTextMessage: messageId=" + messageId.ToString() + ",textMessageId=" + textMessageId.ToString() + ",textMessage=" + textMessage + ",replies=" + (replies == null?"null":String.Join(",", replies.Select(b => b.ToString()).ToArray()))); var md = GetMessagingDevice(); switch (md) { case MessagingDevice.Garmin: { var cnf = new StringBuilder(); // cnf.Append(GarminFmi.EncodeDeleteTextmessage(textMessageId).ToTraxFM(this, false)); if (replies != null && replies.Length > 0) { cnf.Append(GarminFmi.EncodeCannedResponseList(textMessageId, replies).ToTraxFM(this, false)); } else { cnf.Append(GarminFmi.EncodeDeleteTextmessage(textMessageId).ToTraxFM(this, false)); } cnf.Append(GarminFmi.EncodeOpenTextMessage(textMessageId, textMessage, true).ToTraxFM(this, false)); if (ackEvent != -1) { cnf.Append(Fota.VirtualMessageFactory((MessageIdentifier)ackEvent, NextSequence)); } var cmd = cnf.ToString(); SendMessages(cmd, messageId, md); break; } case MessagingDevice.Mpx01: { var cmd = EncodeMpx01Msg(textMessage, messageId, this); SendMessages(cmd, messageId, md); break; } case MessagingDevice.Sms: { var cmd = EncodeSmsMsg(textMessage, messageId, this); SendMessages(cmd, messageId, md); break; } } return(true); }
private String GetConfig(out String hash) { var config = new StringBuilder(DataProvider.GetConfiguration(Id).Replace("\r", "\n").Replace("\n", Environment.NewLine)); string md = DataProvider.GetDetalleDispositivo(Id, "GTE_MESSAGING_DEVICE").As(String.Empty); if (String.IsNullOrEmpty(config.ToString()) && (md != MessagingDevice.Garmin)) { hash = null; return(null); } //reemplazar cada "$ParameterName" con "ParameterValue" List <DetalleDispositivo> configParametersTable = DataProvider.GetDetallesDispositivo(Id); if (configParametersTable != null) { IEnumerable <DetalleDispositivo> configParameters = configParametersTable.Where(detalle => detalle.TipoParametro.Nombre.StartsWith("GTE_PARAM_")); foreach (DetalleDispositivo s in configParameters) { config.Replace("$" + s.TipoParametro.Nombre, s.As("--- PARAMETRO SIN VALOR! ---")); } config.Replace("$known_qtree_revision", DataProvider.GetDetalleDispositivo(Id, "known_qtree_revision").As("0")); } GetMessages(ref config); if (!String.IsNullOrEmpty(config.ToString().Trim())) { config.AppendFormat("{0}{0}Configuracion Generada Exitosamente{0}", Environment.NewLine); config.Insert(0, Fota.VirtualMessageFactory(MessageIdentifier.ConfigStart, 0)); } else { config.AppendLine("Configuracion vacia."); } config.Append(Fota.VirtualMessageFactory(MessageIdentifier.ConfigSuccess, 0)); string conf = config.ToString(); hash = conf.GetHashCode().ToString(CultureInfo.InvariantCulture); conf = conf.Replace("$revision", hash); return(conf); }
private static void SendSdWriteCommand(Parser dev, StringBuilder sb, bool allzeros, bool enviarceros) { sb.Insert(0, ">SSDG1,W"); sb.Append("<"); var cmd = sb.ToString(); sb.Remove(0, sb.Length); if (!allzeros) { Fota.EnqueueLowPriority1(dev, 0, cmd); } else if (enviarceros) { Fota.EnqueueLowPriority2(dev, 0, cmd); } }
public override IMessage Decode(IFrame frame) { if (ParserUtils.IsInvalidDeviceId(Id)) { return(null); } var s = Encoding.ASCII.GetString(frame.Payload, 0, frame.Payload.Length).Split(','); if (!s[0].StartsWith("+")) { return(null); } if (s[0] == Report.Exception || s[0] == Report.Exception2) { //deberia detectar si es un error en el foteo y archivar lo que se quiera fotear? return(new TextEvent(Id, 0, DateTime.UtcNow) { Text = String.Format("Error en dispositivo: Tipo={0} Comando={1} Parameter={2} Extra={3}", s[1], s[2], s[3], s[4]) }); } var mid = GetMessageId(s.Last()); var tiempo = DateTimeUtils.SafeParseFormat(s[s.Length - 2], "yyyyMMddHHmmss"); String peeked; var res = Decode2(mid, s, tiempo, out peeked); if (res != null) { res.Tiempo = tiempo; if (!s[0].StartsWith("+ACK:") || s[0] == Report.Heartbeat) { res.AddStringToSend(String.Format("+SACK:{0}", s.Last())); peeked = Fota.Peek(this); } res.AddStringToPostSend(peeked); } return(res); }
public bool SubmitLongTextMessage(ulong messageId, uint textMessageId, String textMessage, int ackEvent) { STrace.Debug(typeof(Parser).FullName, Id, "SubmitLongTextMessage: messageId=" + messageId.ToString() + ",textMessageId=" + textMessageId.ToString() + ",textMessage=" + textMessage); var md = GetMessagingDevice(); switch (md) { case MessagingDevice.Garmin: { var cnf = new StringBuilder(); cnf.Append(GarminFmi.EncodeDeleteTextmessage(textMessageId).ToTraxFM(this, false)); cnf.Append(GarminFmi.EncodeOpenLongTextMessage(textMessageId, textMessage, true).ToTraxFM(this, false)); if (ackEvent != -1) { cnf.Append(Fota.VirtualMessageFactory((MessageIdentifier)ackEvent, NextSequence)); } var cmd = cnf.ToString(); SendMessages(cmd, messageId, md); break; } case MessagingDevice.Mpx01: { var cmd = EncodeMpx01Msg(textMessage, messageId, this); SendMessages(cmd, messageId, md); break; } case MessagingDevice.Sms: { var cmd = EncodeSmsMsg(textMessage, messageId, this); SendMessages(cmd, messageId, md); break; } } return(true); }
private void CheckLastSentAndDequeueIt(BaseDeviceCommand dc) { string LastCmd = LastSent.GetText(String.Empty); if (LastSent != null) { if (LastSent.IsExpired()) { LastSent = null; } else { var lastDC = BaseDeviceCommand.createFrom(LastCmd, this, null); var result = lastDC.isExpectedResponse(dc); if (result == DeviceCommandResponseStatus.Valid) { Fota.Dequeue(this, lastDC.MessageId); } } } }
private String GetConfig(out String hash) { var config = new StringBuilder(DataProvider.GetConfiguration(Id).Replace("\r", "\n").Replace("\n", Environment.NewLine)); if (String.IsNullOrEmpty(config.ToString())) { hash = null; return(null); } //reemplazar cada "$ParameterName" con "ParameterValue" var configParametersTable = DataProvider.GetDetallesDispositivo(Id); if (configParametersTable != null) { var configParameters = configParametersTable.Where(detalle => detalle.TipoParametro.Nombre.StartsWith("CONFIG_PARAM_")); foreach (var s in configParameters) { config.Replace("$" + s.TipoParametro.Nombre, s.As("--- PARAMETRO SIN VALOR! ---")); } } if (!String.IsNullOrEmpty(config.ToString())) { config.AppendFormat("{0}{0}Configuracion Generada Exitosamente{0}", Environment.NewLine); config.Insert(0, Fota.VirtualMessageFactory(MessageIdentifier.ConfigStart, 0)); } else { config.AppendLine("Configuracion vacia."); } config.Append(Fota.VirtualMessageFactory(MessageIdentifier.ConfigSuccess, 0)); var conf = config.ToString(); hash = conf.GetHashCode().ToString(CultureInfo.InvariantCulture); return(conf.Replace("$revision", hash)); }
// TODO: unificar GTEDeviceCommand e INodeMessage si se puede private void SendPendingFota(ref IMessage msg) { string pending = Fota.Peek(this); if (String.IsNullOrEmpty(pending)) { return; } if (CheckImageSession(pending)) { return; } //procesar primero el pendiente pending = CheckConditionsBeforeSendPending(pending); if (String.IsNullOrEmpty(pending)) { return; } #region SendPending var gteDC = BaseDeviceCommand.createFrom(pending, this, null); pending = gteDC.ToString(true); msg = (msg ?? new UserMessage(Id, 0)); msg.AddStringToPostSend(pending); if (LastSent == null || LastSent.GetText(null) != pending) { LastSent = new INodeMessage((ulong)Id, pending, DateTime.UtcNow); } #endregion SendPending }
/*protected override void OnMemberwiseClone() * { * //reconfiglimit = DateTime.MinValue; * }//*/ #endregion #region Private Members private IMessage Decode2(ulong mid, String[] s, DateTime dtsent) { var msg = Decode3(mid, s, dtsent); if (msg == null) { return(null); } var pending = Fota.Peek(this); if (!String.IsNullOrEmpty(pending)) { Lastsentmessageid = GetMessageId(pending); if (msg.IsPending()) { msg.AddStringToPostSend(pending); } else { msg.AddStringToSend(pending); } } return(msg); }
private bool CheckLastSentAndDequeueIt(String buffer, ulong msgId, ref IMessage salida) { var result = true; string LastCmd = LastSent.GetText(String.Empty); ulong LastId = LastSent.GetId(); if (buffer.StartsWith(Reporte.SdLocked)) { _sdSession = false; STrace.Debug(typeof(Parser).FullName, Id, "Sesion de escritura en sd BORRANDO_POR_LOCKED"); } else if (buffer.StartsWith(Reporte.SdPassword)) { //Debug.Assert(LastSent.IsOnTheFly() == true); if (LastCmd.StartsWith(Reporte.StartGgWriteSession) && (LastId == msgId)) { LastSent = null; _sdSession = true; STrace.Debug(typeof(Parser).FullName, Id, "Sesion de escritura en sd ABIERTA"); } else if (_sdSession) { STrace.Debug(typeof(Parser).FullName, Id, "Sesion de escritura en sd NO_MANEJADO"); } else if (LastId == msgId) { ulong mid = NextSequence; LastSent = new INodeMessage(mid, Mensaje.Factory(mid, this, String.Format("{0}{1}", Reporte.StartGgWriteSession.TrimStart('>'), buffer.Substring(8, 8))), DateTime.MinValue) { IsOnTheFly = true }; salida.AddStringToSend(LastSent.Text); STrace.Debug(typeof(Parser).FullName, Id, "Sesion de escritura en sd ABRIENDO"); } else { STrace.Debug(typeof(Parser).FullName, Id, String.Format("Sesion de escritura en sd NADA (LastSent.GetId()={0} msgId={1})", LastSent.GetId(), msgId)); } } else if (LastSent != null) { if (LastSent.IsExpired()) { LastSent = null; } else { var lastDC = BaseDeviceCommand.createFrom(LastCmd, this, null); var respStatus = lastDC.isExpectedResponse(BaseDeviceCommand.createFrom(buffer, this, null)); switch (respStatus) { case DeviceCommandResponseStatus.Valid: result = true; Fota.Dequeue(this, lastDC.MessageId ?? null); break; case DeviceCommandResponseStatus.Invalid: result = false; break; case DeviceCommandResponseStatus.Exception: Fota.RollbackLastTransaction(this, lastDC.MessageId ?? null); result = false; break; } } } return(result); }
private void GetMessages(ref StringBuilder config, bool deleteMessagesPreviously) { string md = DataProvider.GetDetalleDispositivo(Id, "GTE_MESSAGING_DEVICE").As(String.Empty); if (md == MessagingDevice.Garmin || md == MessagingDevice.Mpx01) { // cargar todos los posibles responses switch (md) { case MessagingDevice.Garmin: List <Logictracker.Types.BusinessObjects.Messages.Mensaje> resp = DataProvider.GetResponsesMessagesTable(Id, 0); if (deleteMessagesPreviously) { config.Append(GarminFmi.EncodeDataDeletionFor(DataDeletionProtocolId.DeleteAllCannedRepliesOnTheClient).ToTraxFM(this, false)); } if (resp != null && resp.Any()) { var respArr = resp.OrderBy(m => m.Codigo).ToArray(); config.Append(GetCannedResponses4Garmin(respArr)); } break; default: break; } config.Append(Environment.NewLine); //cargar todos los canned messages List <Logictracker.Types.BusinessObjects.Messages.Mensaje> cmt = DataProvider.GetCannedMessagesTable(Id, 0); { if ((cmt != null) && (cmt.Any())) { Logictracker.Types.BusinessObjects.Messages.Mensaje[] messagesParameters = cmt.Where(m => !m.TipoMensaje.DeEstadoLogistico).OrderBy(m => m.Codigo).ToArray(); switch (md) { case MessagingDevice.Garmin: if (deleteMessagesPreviously) { config.Append(GarminFmi.EncodeDataDeletionFor(DataDeletionProtocolId.DeleteAllCannedMessagesOnTheClient).ToTraxFM(this, false)); } config.Append(GetCannedMessages4Garmin(messagesParameters)); break; case MessagingDevice.Mpx01: int count = 0; foreach (Logictracker.Types.BusinessObjects.Messages.Mensaje m in messagesParameters.Take(10)) { count++; string texto = m.Texto.ToUpper().PadRight(32); config.Replace(String.Format("$MENSAJE{0:D2}PARTE01", count), texto.Substring(0, 16)); config.Replace(String.Format("$MENSAJE{0:D2}PARTE02", count), texto.Substring(16, 16)); config.Replace(String.Format("$MENSAJE{0:D2}CODIGO", count), m.Codigo); } for (int i = count; i < 11; i++) { const String texto = " "; config.Replace(String.Format("$MENSAJE0{0:D1}PARTE01", i), texto); config.Replace(String.Format("$MENSAJE0{0:D1}PARTE02", i), texto); config.Replace(String.Format("$MENSAJE{0:D2}CODIGO", count), "00"); } break; } } } } if (!String.IsNullOrEmpty(config.ToString().Trim())) { config.AppendFormat("{0}{0}Envio de Mensajes Generado Exitosamente{0}", Environment.NewLine); config.Insert(0, Fota.VirtualMessageFactory(MessageIdentifier.MessagesStart, 0)); config.Append(Fota.VirtualMessageFactory(MessageIdentifier.MessagesSuccess, 0)); } else { config.AppendLine("No hay mensajes para Enviar"); } }
private IMessage Decode3(ulong mid, String[] s, DateTime dtsent) { switch (s[0]) { case Report.NonMovementEvent: return(ParsePosition(Id, mid, s)); case Report.MovementEvent: return(ParsePosition(Id, mid, s)); case Report.GpsRequest: return(ParsePosition(Id, mid, s)); case Report.Fixed: return(ParsePositionsFixed(Id, mid, s)); case Report.GpsHistoryFixRecords: return(ParseGpsHistoryFixRecords(Id, mid, s)); case Report.DevicePowerDown: return(ParseEventWithPosition(Id, mid, s, MessageIdentifier.DeviceShutdown, dtsent)); case Report.CrossBorderEvent: return(ParseEventWithPosition(Id, mid, s, s[5] == "1" ? MessageIdentifier.InsideGeoRefference : MessageIdentifier.OutsideGeoRefference, dtsent)); case Report.SpeedAlarm: return(ParseEventWithPosition(Id, mid, s, MessageIdentifier.SpeedingTicketEnd, dtsent)); case Report.PowerKeyShortPressEvent: return(ParseEventWithPosition(Id, mid, s, MessageIdentifier.PowerKeyShortPress, dtsent)); case Report.FreefallEvent: return(ParseEventWithPosition(Id, mid, s, MessageIdentifier.Freefall, dtsent)); case Report.DeviceInformation: return(ParseEventWithoutPosition(Id, mid, MessageIdentifier.DeviceOnLine)); case Report.BlackCallIncoming: { var res = (Event)ParseEventWithoutPosition(Id, mid, MessageIdentifier.BlackcallIncoming); res.SensorsDataString = s[4]; return(res); } case Report.SosEvent: return(ParseEventWithPosition(Id, mid, s, MessageIdentifier.PanicButtonOn, dtsent).AddStringToSend(String.Format("AT+GTRTO={1},C,,,,,,,{0:X4}$", NextSequence, DataProvider.GetDetalleDispositivo(Id, "Password").As(Password)))); case Report.Heartbeat: return(ParseHeartbeat(Id, mid, s)); case Report.BatteryTimer: return(ParseBatteryTimer(Id, mid, s)); default: if (s[0].StartsWith("+ACK")) { var mid2 = GetMessageId2(s, Id); if ((Lastsentmessageid == mid2)) { Fota.Dequeue(this, null); } } return(new UserMessage(Id, mid)); } }
private void SendMessages(String config, ulong messageId, ulong seq) { Fota.Enqueue(this, messageId, String.Format("{0}///;#{1:X4}", config, seq)); }
private static void CreateGeogrillaTxtInternal(TaskData td) { try { if (td.Device.LastGeogrillaSentTimestamp.AddMinutes(30) > DateTime.UtcNow) { STrace.Log(typeof(Mensaje).FullName, null, td.Device.Id, td.Full ? LogTypes.Error : LogTypes.Debug, null, String.Format("No Foteo Geogrilla {0} por tiempo de espera minimo entre actualizaciones no alcanzado, ultima actualizacion: {1}", td.Full ? "full" : "incremental", td.Device.LastGeogrillaSentTimestamp.ToLocalTime())); return; } td.Device.LastGeogrillaSentTimestamp = DateTime.UtcNow; var gg = new GeoGrillas { Repository = new Repository { BaseFolderPath = td.Path, } }; var headers = gg.GridStructure; //si no esta bien cargado el header fix it if (headers.ActiveKey != 0x55AA55AA) { headers.ActiveKey = 0x55AA55AA; headers.DataStart = 1; } //si hay en fota un envio de qtree usar esa revision como base var fotaRev = GetPendingFotaRevision(td.Device); if (fotaRev > td.BaseRev) { td.BaseRev = fotaRev; } int revision; var changedSectorsList = new TransactionLog(gg.Repository, td.Device.Id) .GetChangedSectorsAndRevision(td.BaseRev, out revision) .SelectMany(file => file.Value, (file, sectorindex) => (file.Key) + sectorindex) .ToArray(); if (td.Full) { var countSectors = (int)(Math.Ceiling(headers.Lat_GridCount / 32.0) * Math.Ceiling(headers.Lon_GridCount / 32.0)); changedSectorsList = Enumerable.Range(0, countSectors).ToArray(); } if (changedSectorsList.Length == 0) { STrace.Debug(typeof(Parser).FullName, td.Device.Id, String.Format("Cancelando envio de geogrilla por no haber sectores cambiados, BaseRev={0} LatestRev={1}", td.BaseRev, revision)); return; } var limit = td.Device.DataProvider.GetDetalleDispositivo(td.Device.Id, "LimiteGeogrillaIncremental").As(20480); if (!td.Full && changedSectorsList.Length > limit) { //limite en el tamaño del diferencial generado de x sectores o megas, configurable en la plataforma con el detalle de dispositivo "LimiteGeogrillaIncremental". STrace.Trace(typeof(Parser).FullName, td.Device.Id, String.Format(@"Cancelando envio de geogrilla incremental por superar el limite de sectores (detalle de dispositivo ""LimiteGeogrillaIncremental""): limite={0} cantidad={1}", limit, changedSectorsList.Length)); return; } //seteo desde ya la revision en la base por si vuelven a enviar un qtree diferencial que se sume solo lo nuevo td.Device.DataProvider.SetDetalleDispositivo(td.Device.Id, "known_qtree_revision", revision.ToString("D4"), "int"); STrace.Debug(typeof(Parser).FullName, td.Device.Id, String.Format("Generando Geogrilla, BaseRev={0} LatestRev={1} GGName={2}", td.BaseRev, revision, td.Path)); if (td.Full) { var head = td.Device.DataProvider.GetDetalleDispositivo(td.Device.Id, "FullQtreePartitionsSd").AsBoolean(false) ? String.Format( ">SUV29*<{0}>SUVU55AA<{0}>SSDF,|G1,{1},TestMap<{0}>SUV29AQSDF,14,3,|G1<{0}", Environment.NewLine, td.Device.DataProvider.GetDetalleDispositivo(td.Device.Id, "QtreeSdPartitionSize").As("3800000")) : String.Empty; Fota.EnqueueLowPriority1(td.Device, 0, SetGGParams(headers, head)); } Fota.EnqueueLowPriority1(td.Device, 0, Fota.VirtualMessageFactory(MessageIdentifier.QtreeStart, td.Device.NextSequence)); ProccessSectors(td, changedSectorsList, gg, td.Device); var bytes = BitConverter.GetBytes(revision); var hexa = StringUtils.ByteArrayToHexString(bytes, 0, bytes.Length); var salida = String.Format("{1}>SSDG1,W0000008004{0}<{2}{1}>QSDG1,R0000008004<{1}", hexa, Environment.NewLine, Fota.VirtualMessageFactory(MessageIdentifier.QtreeSuccess, 0)); Fota.EnqueueLowPriority2(td.Device, td.MessageId, salida); STrace.Trace(typeof(Parser).FullName, td.Device.Id, String.Format("geogrilla a revision: {0} desde: {1} cantidad de sectores: {2}", revision, td.BaseRev, changedSectorsList.Length)); } catch (Exception e) { STrace.Exception(typeof(Parser).FullName, e, td.Device.Id, "Exception during CreateGeogrillaTxt"); } }
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; }
private IMessage Decode2(ulong mid, String[] s, DateTime dtsent, out String peeked) { peeked = null; var ss = s[0].Replace("+BUFF", "+RESP"); switch (ss) { case Report.Fixed: return(ParsePositions(Id, mid, s)); case Report.CrossBorderEvent: return(ParseEventWithPosition(Id, mid, s, s[5] == "1" ? MessageIdentifier.InsideGeoRefference : MessageIdentifier.OutsideGeoRefference, dtsent, 7, null)); case Report.SpeedAlarm: return(ParsePosition(Id, mid, s)); case Report.SosEvent: return(ParseEventWithPosition(Id, mid, s, MessageIdentifier.PanicButtonOn, dtsent, 7, null)); case Report.RtoRtl: return(ParsePosition(Id, mid, s)); case Report.DevicePowerUpFirstPosition: return(ParseEventWithPosition(Id, mid, s, MessageIdentifier.GpsSignalOn, dtsent, 7, null)); case Report.NonMovementEvent: { var ev = (s[5] == "0") ? MessageIdentifier.StoppedEvent : ((s[5] == "1") ? MessageIdentifier.StartMovementEvent : /*s[5] == "2"*/ MessageIdentifier.Freefall); return(ParseEventWithPosition(Id, mid, s, ev, dtsent, 7, null)); } case Report.LocationByCall: { var res = (Event)ParseEventWithPosition(Id, mid, s, MessageIdentifier.BlackcallIncoming, dtsent, 5, null); res.SensorsDataString = s[4]; return(res); } case Report.LocationAsCentreOfGeofence: return(ParsePosition(Id, mid, s)); case Report.DeviceInformation: return(new UserMessage(Id, mid)); case Report.GpsRequest: return(new UserMessage(Id, mid)); case Report.GetAllConfiguration: return(new UserMessage(Id, mid)); case Report.RealTimeOperationCid: return(new UserMessage(Id, mid)); case Report.RealTimeOperationCsq: return(new UserMessage(Id, mid)); case Report.RealTimeOperationVer: return(new UserMessage(Id, mid)); case Report.RealTimeOperationBat: return(FactoryEventWithoutPosition(Id, mid, MessageIdentifier.BateryInfo, String.Format("BatteryPercentage:{0},BatteryVoltage:{1},ExternalPowerSupply:{2},Charging:{3},LedOn:{4}", s[6], s[7], s[4], s[8], s[9]))); case Report.RealTimeOperationTmz: return(new UserMessage(Id, mid)); case Report.PowerOn: return(FactoryEventWithoutPosition(Id, mid, MessageIdentifier.DeviceTurnedOn, null)); case Report.PowerOff: return(FactoryEventWithoutPosition(Id, mid, MessageIdentifier.DeviceShutdown, null)); case Report.ConnectingExternalPowerSupply: return(ParseEventWithPosition(Id, mid, s, MessageIdentifier.PowerReconnected, dtsent, 4, null)); case Report.DisconnectingExternalPowerSupply: return(ParseEventWithPosition(Id, mid, s, MessageIdentifier.PowerDisconnected, dtsent, 4, null)); case Report.BatteryLow: return(ParseEventWithPosition(Id, mid, s, MessageIdentifier.BateryLow, dtsent, 5, String.Format("BatteryVoltage:{0}", s[4]))); case Report.StartCharging: return(ParseEventWithPosition(Id, mid, s, MessageIdentifier.BatteryChargingStart, dtsent, 4, null)); case Report.StopCharging: return(ParseEventWithPosition(Id, mid, s, MessageIdentifier.BatteryChargingStop, dtsent, 5, null)); case Report.DeviceMotionStateIndication: return(new UserMessage(Id, mid)); case Report.GpsAntennaStatusIndication: return(new UserMessage(Id, mid)); case Report.SwitchOnOffGeofence0ViaFunctionKey: return(new UserMessage(Id, mid)); case Report.Heartbeat: return(ParseHeartbeat(Id, mid, s)); default: if (s[0].StartsWith("+ACK:")) { var midR = Convert.ToUInt64(s[s.Length - 3], 16); peeked = Fota.Peek(this); var midF = Convert.ToUInt64(peeked.Split(',').Last().TrimEnd('$'), 16); if (midR == midF) { Fota.Dequeue(this, null); } } return(null); } }
private void SendMessages(String config, ulong messageId) { Fota.Enqueue(this, messageId, config); }