GPSEngine.cs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. using Comal.Classes;
  2. using InABox.Clients;
  3. using InABox.Core;
  4. using InABox.DigitalMatter;
  5. using InABox.IPC;
  6. using netDxf.Tables;
  7. using PRSServer.Engines;
  8. using System;
  9. using System.Collections.Concurrent;
  10. using System.Collections.Generic;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Net;
  14. using System.Net.Sockets;
  15. using System.Text;
  16. using System.Threading.Tasks;
  17. using System.Timers;
  18. namespace PRSServer
  19. {
  20. public class GPSDeviceUpdate : ISerializeBinary
  21. {
  22. public string AuditTrail { get; set; }
  23. public GPSTrackerLocation Location { get; set; }
  24. public void SerializeBinary(CoreBinaryWriter writer)
  25. {
  26. writer.Write(AuditTrail ?? "");
  27. writer.WriteObject(Location);
  28. }
  29. public void DeserializeBinary(CoreBinaryReader reader)
  30. {
  31. AuditTrail = reader.ReadString();
  32. Location = reader.ReadObject<GPSTrackerLocation>();
  33. }
  34. }
  35. public class GPSUpdateQueue
  36. {
  37. public string QueuePath;
  38. public GPSUpdateQueue(string queuePath)
  39. {
  40. QueuePath = queuePath;
  41. }
  42. public void InitQueueFolder()
  43. {
  44. try
  45. {
  46. Directory.CreateDirectory(QueuePath);
  47. }
  48. catch (Exception e)
  49. {
  50. throw new Exception($"Could not create directory for device update queue: {QueuePath}", e);
  51. }
  52. }
  53. public int GetNumberOfItems()
  54. {
  55. using var profiler = new Profiler(true);
  56. return Directory.EnumerateFiles(QueuePath).Count();
  57. }
  58. /// <summary>
  59. /// Get the first (earliest) items of the directory.
  60. /// </summary>
  61. /// <returns>A list of (filename, update) tuples.</returns>
  62. public IEnumerable<Tuple<string, GPSDeviceUpdate>> GetFirstItems()
  63. {
  64. using var profiler = new Profiler(true);
  65. var files = Directory.EnumerateFiles(QueuePath).OrderBy(x => x);
  66. foreach (var filename in files)
  67. {
  68. GPSDeviceUpdate? deviceUpdate = null;
  69. try
  70. {
  71. using var fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read);
  72. deviceUpdate = Serialization.ReadBinary<GPSDeviceUpdate>(fileStream, BinarySerializationSettings.Latest);
  73. }
  74. catch
  75. {
  76. // File is probably in use.
  77. }
  78. if(deviceUpdate is not null)
  79. {
  80. yield return new Tuple<string, GPSDeviceUpdate>(filename, deviceUpdate);
  81. }
  82. }
  83. }
  84. public void QueueUpdate(GPSDeviceUpdate deviceUpdate)
  85. {
  86. var filename = Path.Combine(QueuePath, $"{DateTime.UtcNow.Ticks} - {deviceUpdate.Location.Tracker.ID}");
  87. using var fileStream = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write);
  88. Serialization.WriteBinary(deviceUpdate, fileStream, BinarySerializationSettings.Latest);
  89. }
  90. public void QueueUpdate(string auditTrail, GPSTrackerLocation location) => QueueUpdate(new GPSDeviceUpdate
  91. {
  92. AuditTrail = auditTrail,
  93. Location = location
  94. });
  95. }
  96. internal class GPSDeviceCache : ConcurrentDictionary<string, Device>
  97. {
  98. public void Refresh()
  99. {
  100. Logger.Send(LogType.Information, "", "Refreshing Tracker Cache");
  101. var table = new Client<GPSTracker>().Query(
  102. null,
  103. new Columns<GPSTracker>(x => x.ID, x => x.DeviceID, x => x.Type.BatteryFormula));
  104. Logger.Send(LogType.Information, "", string.Format("- Tracker Cache: {0} devices", table.Rows.Count));
  105. Clear();
  106. foreach (var row in table.Rows)
  107. {
  108. var formula = row.Get<GPSTracker, string?>(x => x.Type.BatteryFormula);
  109. var expression = string.IsNullOrWhiteSpace(formula) ? null : new CoreExpression<GPSBatteryFormulaModel, double>(formula);
  110. this[row.Get<GPSTracker, string>(x => x.DeviceID)] =
  111. new Device(row.Get<GPSTracker, Guid>(x => x.ID), DateTime.MinValue, expression);
  112. }
  113. }
  114. }
  115. public class GPSEngine : Engine<GPSServerProperties>
  116. {
  117. private Listener<SigfoxHandler, SigfoxHandlerProperties> sigfoxListener;
  118. private OEMListener oemListener;
  119. private GPSDeviceCache DeviceCache = new();
  120. private Timer RefreshDevicesTimer;
  121. private Timer UpdateServerTimer;
  122. private GPSUpdateQueue UpdateQueue;
  123. public override void Configure(Server server)
  124. {
  125. base.Configure(server);
  126. UpdateQueue = new GPSUpdateQueue(Path.Combine(AppDataFolder, "device_queue"));
  127. }
  128. private void StartOEMListener()
  129. {
  130. if (Properties.ListenPort == 0)
  131. throw new Exception("Error: OEM Listen Port not Specified\n");
  132. Logger.Send(LogType.Information, "", "Starting OEM Listener on port " + Properties.ListenPort);
  133. oemListener = new OEMListener(Properties.ListenPort, DeviceCache, UpdateQueue);
  134. oemListener.Start();
  135. Logger.Send(LogType.Information, "", "OEM Listener started on port " + Properties.ListenPort);
  136. }
  137. private void StartSigfoxListener()
  138. {
  139. if (Properties.SigfoxListenPort == 0)
  140. {
  141. Logger.Send(LogType.Information, "", "No Sigfox listen port specified\n");
  142. return;
  143. }
  144. sigfoxListener = new Listener<SigfoxHandler, SigfoxHandlerProperties>(new SigfoxHandlerProperties(DeviceCache, UpdateQueue));
  145. sigfoxListener.InitPort((ushort)Properties.SigfoxListenPort);
  146. Logger.Send(LogType.Information, "", "Starting Sigfox Listener on port " + Properties.SigfoxListenPort);
  147. sigfoxListener.Start();
  148. Logger.Send(LogType.Information, "", "Sigfox Listener started on port " + Properties.SigfoxListenPort);
  149. }
  150. private void StartUpdateServerTask()
  151. {
  152. UpdateServerTimer = new Timer(Properties.UpdateTimer);
  153. UpdateServerTimer.Elapsed += (o, e) => UpdateServer();
  154. UpdateServerTimer.Start();
  155. }
  156. // List of (filename, update)
  157. private Queue<Tuple<string, GPSDeviceUpdate>> LocationQueueCache = new();
  158. private void GetLocationQueue(int nLocations)
  159. {
  160. LocationQueueCache.EnsureCapacity(LocationQueueCache.Count + nLocations);
  161. foreach(var item in UpdateQueue.GetFirstItems().Take(nLocations))
  162. {
  163. LocationQueueCache.Enqueue(item);
  164. }
  165. }
  166. private void UpdateServer()
  167. {
  168. // Cache a set of fifty, so that we're not running baack and forth to the filesystem all the time.
  169. if(LocationQueueCache.Count == 0)
  170. {
  171. GetLocationQueue(50);
  172. }
  173. if (LocationQueueCache.Count > 0)
  174. {
  175. var (filename, update) = LocationQueueCache.Dequeue();
  176. Logger.Send(LogType.Information, "",
  177. string.Format("Updating Server ({0}): {1} - {2}", UpdateQueue.GetNumberOfItems(), update.Location.DeviceID, update.AuditTrail));
  178. new Client<GPSTrackerLocation>().Save(update.Location, update.AuditTrail, (_, exception) =>
  179. {
  180. if (exception is not null)
  181. {
  182. Logger.Send(LogType.Error, "", $"Error saving GPS Tracker Location ({update.AuditTrail}): {CoreUtils.FormatException(exception)}");
  183. }
  184. });
  185. try
  186. {
  187. File.Delete(filename);
  188. }
  189. catch
  190. {
  191. // Probably got deleted.
  192. }
  193. }
  194. }
  195. public override void Run()
  196. {
  197. if (string.IsNullOrWhiteSpace(Properties.Server))
  198. {
  199. Logger.Send(LogType.Error, "", "Server is blank!");
  200. return;
  201. }
  202. Logger.Send(LogType.Information, "", "Registering Classes");
  203. CoreUtils.RegisterClasses();
  204. ComalUtils.RegisterClasses();
  205. ClientFactory.SetClientType(typeof(IPCClient<>), Platform.GPSEngine, Version, DatabaseServerProperties.GetPipeName(Properties.Server));
  206. CheckConnection();
  207. UpdateQueue.InitQueueFolder();
  208. // Refresh device cache and set up timer.
  209. DeviceCache.Refresh();
  210. RefreshDevicesTimer = new Timer(5 * 60 * 1000);
  211. RefreshDevicesTimer.Elapsed += (o, e) => DeviceCache.Refresh();
  212. RefreshDevicesTimer.Start();
  213. DMFactory.Initialise(Properties.DumpFormat, Properties.DumpFile);
  214. StartOEMListener();
  215. StartSigfoxListener();
  216. StartUpdateServerTask();
  217. }
  218. private bool CheckConnection()
  219. {
  220. if (ClientFactory.UserGuid == Guid.Empty)
  221. {
  222. // Wait for server connection
  223. while (!Client.Ping())
  224. {
  225. Logger.Send(LogType.Error, "", "Database server unavailable. Trying again in 30 seconds...");
  226. Task.Delay(30_000).Wait();
  227. Logger.Send(LogType.Information, "", "Retrying connection...");
  228. }
  229. ClientFactory.SetBypass();
  230. }
  231. return true;
  232. }
  233. public override void Stop()
  234. {
  235. oemListener.Stop();
  236. sigfoxListener.Stop();
  237. UpdateServerTimer.Stop();
  238. RefreshDevicesTimer.Stop();
  239. }
  240. }
  241. }