GPSEngine.cs 11 KB

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