private static IMessage FactoryEvento(IFoteable node, ulong msgid, String texto, String gmid, DateTime dt) { IMessage salida; if (texto.StartsWith(CodeStr)) { STrace.Debug(typeof(FmiPacketId).FullName, node.Id, String.Format("llego mensaje predefinido: {0}", texto)); var code = (MessageIdentifier) Convert.ToUInt32(texto.Substring(CodeStr.Length, texto.IndexOf(';', CodeStr.Length) - CodeStr.Length)); salida = code.FactoryEvent(node.Id, msgid, null, dt, null, null); } else { STrace.Debug(typeof(FmiPacketId).FullName, node.Id, String.Format("llego mensaje personalizado: {0}", texto)); salida = new TextEvent(node.Id, msgid, dt) { Text = texto, }; } var dc = BaseDeviceCommand.createFrom(String.Format(Mensaje.GarminFm, "A1062500" + gmid), node, null); salida.AddStringToSend(dc.ToString(true)); // Fota.EnqueueOnTheFly(node, 0, new[] { dc }, ref salida); return(salida); }
public static void EnqueueOnTheFly(IFoteable Device, ulong MessageId, string command, ref IMessage msg) { var lines = command.SplitLines().Reverse(); var reversed = lines.JoinLines(); var toSendStr = lines.Last(); if (msg != null) { msg.AddStringToPostSend(toSendStr); } if (Device.LastSent == null) { EnqueuePrivate(Device, MessageId, reversed, ".txR"); if (msg != null) { Device.LastSent = new INodeMessage(MessageId, toSendStr, DateTime.UtcNow); } } else { InsertAfterLastFotaCommand(Device, reversed.ToString()); } }
public static void EnqueueOnTheFly(IFoteable Device, ulong MessageId, BaseDeviceCommand[] arrCmds, ref IMessage msg) { var reversed = arrCmds.Reverse(); var commands = String.Join("", reversed.Select(bdc => bdc.ToString(false)).ToArray()); var toSend = reversed.Last(); var toSendStr = toSend.ToString(true); if (msg != null) { msg.AddStringToSend(toSendStr); } if (Device.LastSent == null) { if (msg != null) { Device.LastSent = new INodeMessage(toSend.MessageId ?? 0, toSendStr, DateTime.UtcNow); } EnqueuePrivate(Device, MessageId, commands, ".txR"); } else { InsertAfterLastFotaCommand(Device, commands); } }
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 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); }
public static void ResetStateMachine(IFoteable Device) { Device.LastSent = null; Archivar(Device, ".txt"); Archivar(Device, ".txR"); Archivar(Device, ".txR2"); Archivar(Device, ".tx1"); Archivar(Device, ".tx2"); }
private static void Archivar(IFoteable Device, String ext) { var src = GetFilePath(Device, ext); if (!IOUtils.FileExists(src)) { return; } var dst = src.Replace(ext, String.Format(" - {0:yyyy-MM-dd HH mm ss}{1}", DateTime.Now, ext)); File.Move(src, dst); }
public static void Enqueue(IFoteable Device, ulong MessageId, String Commands) { if (!Commands.EndsWith(Environment.NewLine)) { Commands += Environment.NewLine; } if (MessageId != 0) { Commands = Commands + VirtualMessageFactory(MessageIdentifier.AckEvent, MessageId); } EnqueuePrivate(Device, MessageId, Commands, ".txt"); }
public static void Dequeue(IFoteable Device, ulong?msgid) { if (!Device.LastSent.IsOnTheFly()) { var t = new TimeElapsed(); UpdateFotaCommand(Device, msgid, BaseDeviceCommand.Attributes.Status_Sent); if (t.getTimeElapsed().TotalSeconds > 1) { STrace.Debug("ParserLock", Device.Id, String.Format("Dequeue ({0} secs)", t.getTimeElapsed().TotalSeconds.ToString())); } } Device.LastSent = null; }
private static String CheckPending(IFoteable parser, String pending) { var bydiff = (parser.LastSent.GetText(null) != pending); var bytime = parser.LastSent.IsExpired(); var t = new TimeElapsed(); var md = parser.DataProvider.GetDetalleDispositivo(parser.GetDeviceId(), "GTE_MESSAGING_DEVICE"); if (t.getTimeElapsed().TotalSeconds > 1) { STrace.Debug("ParserLock", parser.Id, String.Format("Peek DetalleDispositivo({0} secs)", t.getTimeElapsed().TotalSeconds.ToString())); } var dc = BaseDeviceCommand.createFrom(pending, parser, null); var isGMessage = dc.isGarminMessage(); var garminConnected = (md != null && md.Valor == MessagingDevice.Garmin) && (parser.IsGarminConnected == true); if (isGMessage && !garminConnected) { if (dc.getStatus() != BaseDeviceCommand.Attributes.Status_GarminNotConnected) { dc = UpdateFotaCommand(parser, null, BaseDeviceCommand.Attributes.Status_GarminNotConnected, UpdateFotaCommands.UpdateTries); } parser.LastSent = null; return(null); } if (bydiff || bytime) { if (bytime) { t.Restart(); dc = UpdateFotaCommand(parser, null, null, UpdateFotaCommands.UpdateTries); if (t.getTimeElapsed().TotalSeconds > 1) { STrace.Debug("ParserLock", parser.Id, String.Format("Peek CheckPending UpdateFotaCommand ({0} secs)", t.getTimeElapsed().TotalSeconds.ToString())); } } var result = (dc != null ? dc.ToString() : null); parser.LastSent = (result == null ? null : new INodeMessage(dc.MessageId ?? 0, result, DateTime.UtcNow)); return(result); } return(null); }
private static IMessage FactoryEvento(IFoteable node, byte packetId, ulong msgid, DateTime dt, ushort resultCode) { STrace.Debug(typeof(FmiPacketId).FullName, node.Id, String.Format("llego confirmacion de lectura del ultimo mensaje enviado.")); IMessage salida = new TextEvent(node.Id, msgid, dt) { Text = (resultCode == 0 ? "No se ha podido entregar el ultimo mensaje enviado." : "Confirmacion de lectura del ultimo mensaje enviado.") }; /* var response = BaseDeviceCommand.createFrom(String.Format(Mensaje.GarminFm, GetHexAckFor(packetId)), node, null).ToString(true); * salida.AddStringToPostSend(response); * * return salida; */ return(null); }
public static String FindLast(IFoteable Device, String Text, bool lowPriorityFlag) { var file = ObtainFirstExistantReversedFile(Device); if (file == null) { return(null); } using (var sr = new StreamReader(file)) { String line; while ((line = sr.ReadLine()) != null) { var value = FindLastInLineNotSent(line, Text); if (value != null) { return(value); } } } return(null); }
public static void InsertAfterLastFotaCommand(IFoteable device, string commands) { var file = ObtainFirstExistantReversedFile(device); if (file == null) { EnqueuePrivate(device, 0, commands, ".txR"); return; } using (var sr = new BackwardReader(file)) { String line; if ((line = sr.ReadLine()) != null) { while (line != null && IsLastSequenceMessage(line)) { line = sr.ReadLine(); } if (line != null) { if (!commands.EndsWith(Environment.NewLine)) { commands += Environment.NewLine; } sr.Write(commands); sr.Write(line + Environment.NewLine); } if (device.Sequence != null) { sr.Write(LastSequenceFactory(device)); } } sr.TruncateHere(); } }
public static void EnqueueOnTheFly(IFoteable Device, ulong MessageId, string commands) { var zz = (IMessage)null; EnqueueOnTheFly(Device, MessageId, commands, ref zz); }
public static String GetFilePath(IFoteable Device, String ext) { return(GetFilePath(Device.Id, Device.FotaFolder, ext)); }
private static string LastSequenceFactory(IFoteable device) { return(LastSequence + "=" + device.Sequence + Environment.NewLine); }
private static void EnqueuePrivate(IFoteable device, ulong messageId, String commands, String ext) { try { if (!commands.EndsWith(Environment.NewLine)) { commands += Environment.NewLine; } var file = GetFilePath(device, ext); var fexists = IOUtils.FileExists(file); if (fexists) { using (var sr = new BackwardReader(file)) { String line; if ((line = sr.ReadLine()) != null) { while (line != null && IsLastSequenceMessage(line)) { line = sr.ReadLine(); } if (line != null) { sr.Write(line + Environment.NewLine); } sr.Write(commands); if (messageId != 0) { sr.Write(VirtualMessageFactory(MessageIdentifier.AckEvent, messageId)); } if (device.Sequence != null) { sr.Write(LastSequenceFactory(device)); } sr.TruncateHere(); } } } else { using (var sw = new StreamWriter(file, true)) { sw.Write(commands); if (messageId != 0) { sw.WriteLine(VirtualMessageFactory(MessageIdentifier.AckEvent, messageId)); } if (device.Sequence != null) { sw.Write(LastSequenceFactory(device)); } sw.Close(); } } } catch (Exception e) { STrace.Exception(typeof(Fota).FullName, e, device.Id); } }
private static void ProccessAnyPendingFileInternal(IFoteable device) { //txR --- txt --- txR2 --- tx1 --- tx2 //process // reverse // process // reverse // reverse var fileR = GetFilePath(device, ".txR"); var fileT = fileR.Replace(".txR", ".txt"); var fileR2 = fileR.Replace(".txR", ".txR2"); var file1 = fileR.Replace(".txR", ".tx1"); var file2 = fileR.Replace(".txR", ".tx2"); var fileBck = fileR.Replace(".txR", ".bck"); if (IOUtils.FileExists(fileR)) { return; } if (!IOUtils.FileExists(fileT) && IOUtils.FileExists(fileR2)) { return; } var fileAct = new List <String> { fileT, file1, file2 } .FirstOrDefault(IOUtils.FileExists); if (fileAct == null) { return; } if (IOUtils.FileExists(fileBck)) { Archivar(device, ".bck"); } using (var sr = new BackwardReader(fileAct)) { using (var sw = new StreamWriter(fileBck)) { String line; while ((line = sr.ReadLine()) != null) { if (!String.IsNullOrEmpty(line) && !IsLastSequenceMessage(line)) { sw.WriteLine(line); } } if (device.Sequence != null) { sw.Write(LastSequenceFactory(device)); } sw.Close(); } } File.Delete(fileAct); File.Move(fileBck, (fileAct == fileT) ? fileR : fileR2); }
private static String PeekPrivate(IFoteable device) { if (device.LastSent.IsOnTheFly()) { return(device.LastSent.Text); } var t = new TimeElapsed(); var fileR = GetFilePath(device, ".txR"); var fileT = GetFilePath(device, ".txt"); var fileR2 = GetFilePath(device, ".txR2"); if (t.getTimeElapsed().TotalSeconds > 1) { STrace.Debug("ParserLock", device.Id, String.Format("Peek Private GetFilePath ({0} secs)", t.getTimeElapsed().TotalSeconds.ToString())); } //txR --- txt --- txR2 --- tx1 --- tx2 //process // reverse // process // reverse // reverse t.Restart(); if ((!IOUtils.FileExists(fileR)) && (IOUtils.FileExists(fileT) || !IOUtils.FileExists(fileR2))) { if (t.getTimeElapsed().TotalSeconds > 1) { STrace.Debug("ParserLock", device.Id, String.Format("Peek Private FileExists ({0} secs)", t.getTimeElapsed().TotalSeconds.ToString())); } t.Restart(); ProccessAnyPendingFileInternal(device); if (t.getTimeElapsed().TotalSeconds > 1) { STrace.Debug("ParserLock", device.Id, String.Format("Peek Private ProcessAnyPending ({0} secs)", t.getTimeElapsed().TotalSeconds.ToString())); } /* ThreadPool.QueueUserWorkItem(ProccessAnyPendingFile, device); return null;*/ } //process t.Restart(); var file = ObtainFirstExistantReversedFile(device); if (t.getTimeElapsed().TotalSeconds > 1) { STrace.Debug("ParserLock", device.Id, String.Format("Peek Private ObtainFirstExistantReversedFile ({0} secs)", t.getTimeElapsed().TotalSeconds.ToString())); } if (file == null) { return(null); } String line; var validLines = 0; t.Restart(); var lineNumber = 0; using (var sr = new BackwardReader(file)) { if (t.getTimeElapsed().TotalSeconds > 1) { STrace.Debug("ParserLock", device.Id, String.Format("Peek Private using BackwardReader ({0} secs)", t.getTimeElapsed().TotalSeconds.ToString())); } while ((line = sr.ReadLine()) != null) { lineNumber++; if (t.getTimeElapsed().TotalSeconds > 1) { STrace.Debug("ParserLock", device.Id, String.Format("Peek Private Readline {1} ({0} secs)", t.getTimeElapsed().TotalSeconds.ToString(), lineNumber)); } line = line.Trim(); if (line.Contains("/*")) { line = line.Substring(0, line.IndexOf("/*")); } if (IsLastSequenceMessage(line)) { continue; } var t2 = new TimeElapsed(); if (IsVirtualMessage(line) || (line = GetNextInLineNotSentCommand(line)) != null) { validLines++; break; } if (t2.getTimeElapsed().TotalSeconds > 1) { STrace.Debug("ParserLock", device.Id, String.Format("Peek Private IsVirtual+GetNextInLine {1} ({0} secs)", t.getTimeElapsed().TotalSeconds.ToString(), lineNumber)); } } } if (t.getTimeElapsed().TotalSeconds > 1) { STrace.Debug("ParserLock", device.Id, String.Format("Peek Private end of BackwardReader ({0} secs)", t.getTimeElapsed().TotalSeconds.ToString())); } if (validLines == 0) { t.Restart(); File.Delete(file); if (t.getTimeElapsed().TotalSeconds > 1) { STrace.Debug("ParserLock", device.Id, String.Format("Peek Private Delete File ({0} secs)", t.getTimeElapsed().TotalSeconds.ToString())); } } return(line); }
public static String UpdateFotaCommand(IFoteable device, ulong?msgid, string newStatus) { var replaced = UpdateFotaCommand(device, msgid, newStatus, null, UpdateFotaCommands.None); return(replaced != null?replaced.ToString():null); }
public static String Peek(IFoteable parser, bool returnVMessages) { try { if (ParserUtils.IsInvalidDeviceId(parser.GetDeviceId())) { return(null); } //GetInfo var t = new TimeElapsed(); var pending = PeekPrivate(parser); if (t.getTimeElapsed().TotalSeconds > 1) { STrace.Debug("ParserLock", parser.Id, String.Format("Peek Private({0} secs)", t.getTimeElapsed().TotalSeconds.ToString())); } while (IsVirtualMessage(pending) && !returnVMessages) { var d1 = pending.Split(';'); var code = Convert.ToInt32(d1[0].Split('=')[1]); var mid = Convert.ToUInt64(d1[1].Split('=')[1]); try { if (code != (int)MessageIdentifier.AckEvent) { t.Restart(); var message = ((MessageIdentifier)code).FactoryEvent(parser.Id, mid, null, DateTime.UtcNow, null, null); parser.DataTransportLayer.DispatchMessage(parser, message); if (t.getTimeElapsed().TotalSeconds > 1) { STrace.Debug("ParserLock", parser.Id, String.Format("DispatchMessage ({0} secs)", t.getTimeElapsed().TotalSeconds.ToString())); } } else { t.Restart(); STrace.Debug(typeof(Fota).FullName, parser.Id, String.Format("Fota Ack message id = {0}", mid)); var msg = new UserMessage(parser.Id, mid) .SetUserSetting("user_message_code", "ACK") .SetUserSetting("trackingId", mid.ToString(CultureInfo.InvariantCulture)); parser.DataTransportLayer.DispatchMessage(parser, msg); if (t.getTimeElapsed().TotalSeconds > 1) { STrace.Debug("ParserLock", parser.Id, String.Format("Fota Ack({0} secs)", t.getTimeElapsed().TotalSeconds.ToString())); } } t.Restart(); Dequeue(parser, null); if (t.getTimeElapsed().TotalSeconds > 1) { STrace.Debug("ParserLock", parser.Id, String.Format("Peek Dequeue ({0} secs)", t.getTimeElapsed().TotalSeconds.ToString())); } } catch (Exception) { STrace.Error(typeof(Fota).FullName, parser.GetDeviceId(), "Error in DataTransportLayer.DispatchMessage?"); } t.Restart(); pending = PeekPrivate(parser); if (t.getTimeElapsed().TotalSeconds > 1) { STrace.Debug("ParserLock", parser.Id, String.Format("Peek Private({0} secs)", t.getTimeElapsed().TotalSeconds.ToString())); } } return(pending == null ? null : CheckPending(parser, pending)); } catch (Exception e) { STrace.Debug(typeof(Fota).FullName, parser.GetDeviceId(), String.Format("Error al Fotear {0}", e)); return(null); } }
public static BaseDeviceCommand UpdateFotaCommand(IFoteable device, ulong?msgid, string newStatus, BaseDeviceCommand newCommand, UpdateFotaCommands action) { var result = (BaseDeviceCommand)null; var file = ObtainFirstExistantReversedFile(device); if (file == null) { return(null); } using (var sr = new BackwardReader(file)) { var buffer = new StringBuilder(); var msgidfound = false; String line; while ((line = sr.ReadLine()) != null) // reads the lines from last to first { var lineOriginal = line = line.Trim(); if (IsLastSequenceMessage(line)) { continue; } if (IsVirtualMessage(line)) { break; } var newLine = new StringBuilder(); var isFirstCommand = true; // at begin of line evaluation, the next command in line is the first MatchCollection commandMatches = getMatchesAllCommandsFrom(line); var allSent = commandMatches.Count > 0; // the variable reflects if all commands in line were sent. for (var i = 0; i < commandMatches.Count; i++) { var cM = commandMatches[i]; var command = cM.Groups[0].Value; var dc = BaseDeviceCommand.createFrom(command, device, null); if (!dc.isAlreadySent()) { if (msgid == null || dc.MessageId == msgid) { allSent = allSent && (action != UpdateFotaCommands.RollbackTransaction && isFirstCommand && newStatus == BaseDeviceCommand.Attributes.Status_Sent); msgidfound = true; if (isFirstCommand) { isFirstCommand = false; if (newCommand != null) { dc = newCommand; dc.IdNum = device.GetDeviceId(); } if (action == UpdateFotaCommands.UpdateTries || action == UpdateFotaCommands.RollbackTransaction) { dc.Tries = (dc.Tries == null ? 0 : dc.Tries.Value) + 1; dc.LastTry = DateTime.Now; } if (action == UpdateFotaCommands.RollbackTransaction) { dc.setStatus(BaseDeviceCommand.Attributes.Status_Rollbacked); } else { dc.setStatus(newStatus); } } else if (action == UpdateFotaCommands.RollbackTransaction) { dc.Tries = (dc.Tries == null ? 0 : dc.Tries.Value) + 1; dc.LastTry = DateTime.Now; dc.setStatus(BaseDeviceCommand.Attributes.Status_Rollbacked); } if (result == null) // just catch first not sent message { result = dc; } } else { allSent = false; } } newLine.Append(dc.ToString()); } line = (allSent?null:newLine.ToString()); if (!String.IsNullOrEmpty(line)) { if (lineOriginal != line) { STrace.Debug(typeof(Fota).FullName, device.Id, "FOTA> LINE ORIGINAL: " + lineOriginal); STrace.Debug(typeof(Fota).FullName, device.Id, "FOTA> LINE REPLACED: " + line); } buffer.Insert(0, line + Environment.NewLine); } else { STrace.Debug(typeof(Fota).FullName, device.Id, "FOTA> LINE DELETED : " + lineOriginal); } if (msgidfound) { break; } } if (buffer.Length != 0) { sr.Write(buffer.ToString()); } if (device.Sequence != null) { sr.Write(LastSequenceFactory(device)); } sr.TruncateHere(); } if (IOUtils.FileExists(file)) { using (var sr = new BackwardReader(file)) { var allLastSequence = true; String line; while (allLastSequence && (line = sr.ReadLine()) != null) { allLastSequence = allLastSequence && IsLastSequenceMessage(line); } sr.Dispose(); if (allLastSequence) { File.Delete(file); } } } return(result); }
private static string ObtainFirstExistantReversedFile(IFoteable device) { return (new[] { ".txR", ".txR2", ".txG", ".txG2" }.Select(ext => GetFilePath(device, ext)).FirstOrDefault( IOUtils.FileExists)); }
public static void EnqueueLowPriority2(IFoteable Device, ulong MessageId, String Commands) { EnqueuePrivate(Device, MessageId, Commands, ".tx2"); }
public static BaseDeviceCommand UpdateFotaCommand(IFoteable device, ulong?msgid, string newStatus, UpdateFotaCommands action) { return(UpdateFotaCommand(device, msgid, newStatus, null, action)); }
public static void EnqueueGarmin(IFoteable Device, ulong MessageId, String Commands) { Enqueue(Device, MessageId, Commands); }
public static BaseDeviceCommand RollbackLastTransaction(IFoteable device, ulong?msgid) { return(UpdateFotaCommand(device, msgid, BaseDeviceCommand.Attributes.Status_Rollbacked, null, UpdateFotaCommands.RollbackTransaction)); }
public static String Peek(IFoteable parser) { return(Peek(parser, false)); }