GPSEngine.cs 10 KB

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