GPSEngine.cs 10 KB

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