GPSEngine.cs 11 KB

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