NWreader.cs 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. using Logger;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.Globalization;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Net.Sockets;
  10. using System.Threading;
  11. using UnityEngine;
  12. namespace Networkreader
  13. {
  14. public class NWreader :AbstractNWReader, INWReader
  15. {
  16. #region Parameter
  17. private readonly int ROWLENGTHINBYTES = 3 * sizeof(Int32) + 1 * sizeof(Double) + 9 * sizeof(Single) + 2 * sizeof(UInt32);
  18. /// <summary>
  19. /// The time(in ms) data is buffered befor it is sorted and written to file.
  20. /// </summary>
  21. private double BufferTime { get; set; }
  22. /// <summary>
  23. /// A buffer for data containing the timestamp of the date and the the object as byte[] rep.
  24. /// </summary>
  25. private List<Tuple<double, byte[]>> Buffer { get; set; }
  26. /// <summary>
  27. /// Holds the latest read timestamp.
  28. /// </summary>
  29. private double NewestTimeStamp;
  30. /// <summary>
  31. /// Holds the first read timestamp.
  32. /// </summary>
  33. private double OldestTimeStamp;
  34. #endregion
  35. #region Constructor
  36. public NWreader(string ipAdress, int port, double buffertime) : base(ipAdress, port)
  37. {
  38. this.BufferTime = buffertime;
  39. this.Buffer = new List<Tuple<double, byte[]>>();
  40. this.NewestTimeStamp = 0;
  41. this.OldestTimeStamp = double.NaN;
  42. }
  43. #endregion
  44. #region Exposed
  45. /// <summary>
  46. /// Returns the newest timestamp that was written to the file.
  47. /// </summary>
  48. /// <returns></returns>
  49. public double GetNewestTimestamp()
  50. {
  51. return NewestTimeStamp;
  52. }
  53. /// <summary>
  54. /// Returns the first timestamp that was written to the file.
  55. /// </summary>
  56. /// <returns></returns>
  57. public double GetOldestTimestamp()
  58. {
  59. return OldestTimeStamp;
  60. }
  61. #endregion
  62. #region Internal
  63. private bool IsOutdated(Tuple<double, byte[]> elem)
  64. {
  65. return elem.Item1 < NewestTimeStamp;
  66. }
  67. /// <summary>
  68. /// A Thread that reads data from <see cref="Client"/>, stores it in <see cref="Buffer"/> and calls <see cref="DumpBuffer"/> after <see cref="BufferTime"/>.
  69. /// </summary>
  70. /// <param name="filepath">Filepath of the .bin file.</param>
  71. protected override void WriteToFileThread(object filepath)
  72. {
  73. Streaming = true;
  74. NWStream = Client.GetStream();
  75. Stopwatch watch = new Stopwatch();
  76. double lastWritten = 0;
  77. byte[] buffer;
  78. watch.Start();
  79. while (Streaming)
  80. {
  81. try
  82. {
  83. if (NWStream.DataAvailable)
  84. {
  85. buffer = new byte[ROWLENGTHINBYTES];
  86. ReadBuffer(buffer);
  87. //the timestamp is always at the second position of the bytearray adter the ID of the object
  88. double timestamp = BitConverter.ToDouble(buffer, sizeof(int));
  89. Buffer.Add(Tuple.Create(timestamp, buffer));
  90. }
  91. else
  92. Thread.Sleep(10);
  93. }
  94. catch (Exception e)
  95. {
  96. CityLogger.LogWarning("Unable to read data from NW stream with error: " + e.Message);
  97. return;
  98. }
  99. if (lastWritten + watch.ElapsedMilliseconds > BufferTime)
  100. {
  101. lastWritten = 0;
  102. DumpBuffer(filepath.ToString());
  103. watch.Restart();
  104. }
  105. }
  106. Client.Close();
  107. }
  108. /// <summary>
  109. /// Dumps <see cref="Buffer"/> to filepath.
  110. /// </summary>
  111. /// <param name="filepath">Filepath of the .bin file.</param>
  112. private void DumpBuffer(string filepath)
  113. {
  114. //Sort the buffered elements so that they will be saved in the right time order
  115. Buffer.Sort((a, b) => a.Item1.CompareTo(b.Item1));
  116. //and delete the one that are outdated
  117. int deleted = 0;
  118. if (Buffer.Count > 0)
  119. deleted = Buffer.RemoveAll(IsOutdated);
  120. if (deleted > 0)
  121. CityLogger.Log("Some timestamps came after their time: " + deleted, LogLevel.INFO);
  122. using (BinaryWriter sw = new BinaryWriter(new FileStream(filepath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite)))
  123. foreach (Tuple<double, byte[]> line in Buffer)
  124. sw.Write(line.Item2, 0, line.Item2.Length);
  125. if (Buffer.Count >= 1)
  126. NewestTimeStamp = Buffer.Last().Item1;
  127. if (double.IsNaN(OldestTimeStamp) && Buffer.Count >= 1)
  128. OldestTimeStamp = Buffer.First().Item1;
  129. Buffer.Clear();
  130. }
  131. protected override string GetFilename()
  132. {
  133. return "Stream_" + DateTime.Now.ToString(new CultureInfo("de-DE")).Replace(" ", "_").Replace(":", ".") + ".bin";
  134. }
  135. #endregion
  136. }
  137. }