GPSEngine.cs 11 KB

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