OEMConnection.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. using Comal.Classes;
  2. using InABox.Core;
  3. using InABox.DigitalMatter;
  4. using NPOI.HSSF.Record.CF;
  5. using PRS.Shared;
  6. using Syncfusion.Data;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Linq;
  10. using System.Net.Sockets;
  11. using System.Text;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. using System.Windows.Media.Media3D;
  15. namespace PRSServer
  16. {
  17. /// <summary>
  18. /// Represents one conversation between OEM and our GPS Engine.
  19. /// </summary>
  20. internal class OEMConnection
  21. {
  22. private TcpClient Client;
  23. private NetworkStream Stream;
  24. private byte[] Buffer;
  25. private List<byte> ConsolidatedBuffer;
  26. private bool Finished = false;
  27. private bool Confirmed = false;
  28. private Task? ReadTask;
  29. private CancellationTokenSource TokenSource = new();
  30. // References to necessary caches
  31. private GPSDeviceCache Devices;
  32. private GPSUpdateQueue Queue;
  33. // Fields of this conversation; these should be initialised by the 'Hello' message.
  34. private string Product;
  35. private string Serial;
  36. // Anything more recent than this threshold is ignored.
  37. private static TimeSpan AgeThreshold = TimeSpan.FromMinutes(2);
  38. // Data that forms the the request.
  39. private List<DMDataRequest> Data = new();
  40. public delegate void CompletedEvent();
  41. public CompletedEvent? OnCompletion;
  42. public OEMConnection(TcpClient client, GPSDeviceCache cache, GPSUpdateQueue queue)
  43. {
  44. Client = client;
  45. Stream = Client.GetStream();
  46. Devices = cache;
  47. Queue = queue;
  48. }
  49. private DMHelloResponse HandleHello(DMHelloRequest hello)
  50. {
  51. Product = DMFactory.GetDeviceName(hello.ProductID);
  52. Serial = hello.SerialNumber.ToString();
  53. Logger.Send(LogType.Information, Serial, string.Format("Hello {0} ({1})", Product, Serial));
  54. return new DMHelloResponse();
  55. }
  56. private DMMessage? HandleData(DMDataRequest data)
  57. {
  58. Logger.Send(LogType.Information, Serial, string.Format("{0} DataRecords Received", data.Records.Length));
  59. var iRecord = 1;
  60. foreach (var record in data.Records)
  61. {
  62. Logger.Send(LogType.Information, Serial,
  63. string.Format("- Data Record #{0}: {1:dd MMM yy hh-mm-ss} ({2} Fields)", iRecord,
  64. record.TimeStampToDateTime(record.TimeStamp), record.Fields.Length));
  65. iRecord++;
  66. foreach (var field in record.Fields)
  67. Logger.Send(LogType.Information, Serial,
  68. string.Format(" [{0}] {1}: {2}", field.IsValid() ? "X" : " ", DMFactory.GetFieldName(field.Type),
  69. field));
  70. }
  71. Data.Add(data);
  72. return null;
  73. }
  74. private GPSTrackerLocation? HandleTracker(DMGPSField gps, DMRecord record)
  75. {
  76. var flags = gps.StatusFlags();
  77. // Sometimes we get a ping that has both "Valid" and "NoSignal" set
  78. // In this case, lets treat it as valid
  79. if (flags.Contains(GPSStatus.NoSignal) && !flags.Contains(GPSStatus.Valid))
  80. {
  81. Logger.Send(LogType.Information, Serial, $"- Skipping: Invalid Signal ({Serial})");
  82. return null;
  83. }
  84. var timestamp = record.TimeStampToDateTime(record.TimeStamp);
  85. var age = timestamp - Devices[Serial].TimeStamp;
  86. if (age <= AgeThreshold)
  87. {
  88. Logger.Send(LogType.Information, Serial, $"- Skipping: Recent Update ({Serial}) {age:mm\\:ss}");
  89. return null;
  90. }
  91. var device = Devices[Serial];
  92. var location = new GPSTrackerLocation();
  93. location.DeviceID = Serial;
  94. location.Tracker.ID = device.ID;
  95. location.Location.Timestamp = timestamp;
  96. location.Location.Latitude = (double)gps.Latitude / 10000000.0F;
  97. location.Location.Longitude = (double)gps.Longitude / 10000000.0F;
  98. var analoguedata = record.GetFields<DMAnalogueDataField16>().FirstOrDefault();
  99. if (analoguedata != null)
  100. location.BatteryLevel = analoguedata.BatteryStrength
  101. ?? device.CalculateBatteryLevel(analoguedata.InternalVoltage);
  102. return location;
  103. }
  104. private GPSTrackerLocation? HandleBluetoothTag(DMGPSField gps, DMRecord record, DMBluetoothTag tag)
  105. {
  106. var tagID = tag.ID();
  107. if (!Devices.ContainsKey(tagID) && tagID.Length == 17 && tagID.Split(':').Length == 6)
  108. {
  109. var truncated = tagID[..15];
  110. var newtag = Devices.Keys.FirstOrDefault(x => x.StartsWith(truncated));
  111. Logger.Send(LogType.Information, Serial, $"- Truncating BT Tag: {tagID} -> {truncated} -> {newtag}");
  112. if (!string.IsNullOrWhiteSpace(newtag))
  113. tagID = newtag;
  114. }
  115. if (!Devices.ContainsKey(tagID))
  116. {
  117. Logger.Send(LogType.Information, Serial, $"- Skipping: Unknown Tag ({tagID})");
  118. return null;
  119. }
  120. var timestamp = record.TimeStampToDateTime(record.TimeStamp);
  121. var age = timestamp - Devices[tagID].TimeStamp;
  122. if (age <= AgeThreshold)
  123. {
  124. Logger.Send(LogType.Information, Serial, $"- Skipping: Recent Update ({tagID}) {age:mm\\:ss}");
  125. return null;
  126. }
  127. var device = Devices[tagID];
  128. var btloc = new GPSTrackerLocation();
  129. btloc.DeviceID = tagID;
  130. btloc.Tracker.ID = device.ID;
  131. btloc.Location.Timestamp = timestamp;
  132. btloc.Location.Latitude = (double)gps.Latitude / 10000000.0F;
  133. btloc.Location.Longitude = (double)gps.Longitude / 10000000.0F;
  134. if (tag is DMGuppyBluetoothTag guppy)
  135. {
  136. btloc.BatteryLevel = device.CalculateBatteryLevel(guppy.BatteryVoltage);
  137. //guppy.BatteryVoltage * 5F / 3F;
  138. }
  139. else if (tag is DMSensorNodeBluetoothTag sensornode)
  140. {
  141. // Need to check with Kenrick about the calcs here..
  142. // Guppies have 1 battery (ie 1.5V) while Sensornodes have 3 (4.5V)
  143. btloc.BatteryLevel = device.CalculateBatteryLevel(sensornode.BatteryVoltage);
  144. //btloc.BatteryLevel = sensornode.BatteryVoltage * 5F / 3F;
  145. }
  146. return btloc;
  147. }
  148. private IEnumerable<GPSTrackerLocation> HandleRecord(DMRecord record)
  149. {
  150. if (Devices.ContainsKey(Serial))
  151. {
  152. if (record.Fields.FirstOrDefault(x => x is DMGPSField && x.IsValid()) is DMGPSField gps)
  153. {
  154. if (record.TimeStamp != 0 && gps.Latitude != 0 && gps.Longitude != 0)
  155. {
  156. if (HandleTracker(gps, record) is GPSTrackerLocation trackerLocation)
  157. {
  158. yield return trackerLocation;
  159. }
  160. foreach (DMBluetoothTagList taglist in record.GetFields<DMBluetoothTagList>())
  161. foreach (var item in taglist.Items.Where(x => x.LogReason != 2))
  162. {
  163. if (HandleBluetoothTag(gps, record, item.Tag) is GPSTrackerLocation location)
  164. {
  165. yield return location;
  166. }
  167. }
  168. foreach (DMBluetoothTagData tag in record.GetFields<DMBluetoothTagData>())
  169. if (tag.LogReason != 2 && tag.TimeStamp != 0 && tag.Latitude != 0 && tag.Longitude != 0)
  170. {
  171. if (HandleBluetoothTag(gps, record, tag.Tag) is GPSTrackerLocation location)
  172. {
  173. yield return location;
  174. }
  175. }
  176. }
  177. else
  178. {
  179. Logger.Send(LogType.Information, Serial,
  180. string.Format("- Skipping: Invalid GPS Data ({0}) {1}{2}{3}", Serial,
  181. gps.TimeStamp == 0 ? "Bad TimeStamp " : "", gps.Latitude == 0 ? "Bad Latitude " : "",
  182. gps.Longitude == 0 ? "Bad Longitude " : "").Trim());
  183. }
  184. }
  185. else
  186. {
  187. Logger.Send(LogType.Information, Serial,
  188. string.Format("- Skipping: Missing GPS Data ({0})", Serial));
  189. }
  190. }
  191. else
  192. {
  193. Logger.Send(LogType.Information, Serial, string.Format("- Skipping: Unknown Device ({0})", Serial));
  194. }
  195. }
  196. private DMConfirmResponse HandleConfirm(DMConfirmRequest confirm)
  197. {
  198. Logger.Send(LogType.Information, Serial, string.Format("Goodbye {0} ({1})", Product, Serial));
  199. var updates = new List<GPSTrackerLocation>();
  200. foreach (var data in Data)
  201. foreach (var record in data.Records)
  202. {
  203. foreach(var update in HandleRecord(record))
  204. {
  205. updates.Add(update);
  206. }
  207. }
  208. if (updates.Any())
  209. {
  210. Logger.Send(LogType.Information, Serial,
  211. string.Format("Sending updates ({0}): {1}", updates.Count,
  212. string.Join(", ", updates.Select(x => x.DeviceID).Distinct())));
  213. foreach (var update in updates)
  214. {
  215. Logger.Send(LogType.Information, Serial,
  216. string.Format("- Updating Device Cache: ({0}): {1:yyyy-MM-dd hh:mm:ss}", update.DeviceID,
  217. update.Location.Timestamp));
  218. //if (m_devices.ContainsKey(update.DeviceID))
  219. var oldDevice = Devices[update.DeviceID];
  220. Devices[update.DeviceID] =
  221. new Device(oldDevice.ID, update.Location.Timestamp, oldDevice.BatteryFormula);
  222. }
  223. foreach (var update in updates)
  224. {
  225. Queue.QueueUpdate($"Updated by {Product} ({Serial})", update);
  226. }
  227. }
  228. return new DMConfirmResponse { Status = 1 };
  229. }
  230. private void HandleMessage(DMMessage message)
  231. {
  232. DMMessage? response;
  233. if (message is DMHelloRequest hello)
  234. {
  235. response = HandleHello(hello);
  236. }
  237. else if (message is DMDataRequest data)
  238. {
  239. response = HandleData(data);
  240. }
  241. else if (message is DMConfirmRequest confirm)
  242. {
  243. response = HandleConfirm(confirm);
  244. Confirmed = true;
  245. }
  246. else
  247. {
  248. Logger.Send(LogType.Information, "", $"Unknown message type {message.Type}");
  249. response = null;
  250. }
  251. if(response is not null)
  252. {
  253. Stream.Write(response.EncodeArray());
  254. }
  255. }
  256. /// <summary>
  257. ///
  258. /// </summary>
  259. /// <remarks>
  260. /// Read occurs asynchronously, so essentially this method spins off a read thread and then returns.
  261. /// If we call <see cref="Stop"/> before data comes in, the read does not occur.
  262. /// </remarks>
  263. private void DoRead()
  264. {
  265. var readData = false;
  266. // We pass in the cancellation token to prevent the task from continuing if we call stop.
  267. ReadTask = Stream.ReadAsync(Buffer, 0, Buffer.Length).ContinueWith(t =>
  268. {
  269. if(t.Exception is not null)
  270. {
  271. if (Finished)
  272. {
  273. Finish();
  274. }
  275. else
  276. {
  277. Logger.Send(LogType.Error, Environment.CurrentManagedThreadId.ToString(), CoreUtils.FormatException(t.Exception));
  278. }
  279. }
  280. else
  281. {
  282. readData = true;
  283. var nBytes = t.Result;
  284. if (nBytes > 0)
  285. {
  286. ConsolidatedBuffer.AddRange(Buffer.Take(nBytes));
  287. try
  288. {
  289. while (ConsolidatedBuffer.Count > 0)
  290. {
  291. DMMessage? message = null;
  292. try
  293. {
  294. var payloadLength = DMFactory.PeekPayloadLength(ConsolidatedBuffer);
  295. if (nBytes == Buffer.Length && ConsolidatedBuffer.Count < payloadLength)
  296. {
  297. // Probably we need more data.
  298. break;
  299. }
  300. else
  301. {
  302. message = DMFactory.ParseMessage(ConsolidatedBuffer);
  303. }
  304. }
  305. catch (Exception e)
  306. {
  307. Logger.Send(
  308. LogType.Error,
  309. Environment.CurrentManagedThreadId.ToString(),
  310. string.Format("Unable to Parse Record: {0} ({1})", e.Message, BitConverter.ToString(ConsolidatedBuffer.ToArray()))
  311. );
  312. break;
  313. }
  314. if (message is not null)
  315. {
  316. HandleMessage(message);
  317. ConsolidatedBuffer.RemoveRange(0, message.CheckSum + 5);
  318. }
  319. }
  320. }
  321. catch (Exception e)
  322. {
  323. Logger.Send(LogType.Error, Environment.CurrentManagedThreadId.ToString(), e.Message + "\n" + e.StackTrace);
  324. }
  325. }
  326. else
  327. {
  328. Finished = true;
  329. }
  330. if (Finished)
  331. {
  332. Finish();
  333. }
  334. else
  335. {
  336. // If we still have stuff to do, try reading again. Note that this isn't a recursive problem or anything, because
  337. // this method returns very soon.
  338. DoRead();
  339. }
  340. }
  341. }, TokenSource.Token);
  342. // After 15 seconds, close the connection (but only if it has been confirmed).
  343. var delay = Task.Delay(15_000).ContinueWith(t =>
  344. {
  345. if (!readData)
  346. {
  347. Finished = true;
  348. if (Confirmed)
  349. {
  350. Logger.Send(LogType.Error, "", "Closing connection after 15 seconds of silence.");
  351. Stream.Close();
  352. }
  353. else
  354. {
  355. Logger.Send(LogType.Error, "", "No data read for 15 seconds, but connection has not been confirmed.");
  356. }
  357. }
  358. });
  359. }
  360. public void Run()
  361. {
  362. Buffer = new byte[2048];
  363. ConsolidatedBuffer = new List<byte>();
  364. DoRead();
  365. }
  366. private void Finish()
  367. {
  368. Stream.Close();
  369. Client.Close();
  370. OnCompletion?.Invoke();
  371. }
  372. public void Stop()
  373. {
  374. // Cancel any read tasks which are yet to start.
  375. TokenSource.Cancel();
  376. Stream.Close();
  377. Client.Close();
  378. try
  379. {
  380. // Let the latest task finish.
  381. if(ReadTask?.Wait(1000) == false)
  382. {
  383. Logger.Send(LogType.Error, "", "The thread didn't die in time.");
  384. }
  385. }
  386. catch (AggregateException ae)
  387. {
  388. foreach(var exception in ae.InnerExceptions)
  389. {
  390. if(exception is not TaskCanceledException)
  391. {
  392. throw;
  393. }
  394. }
  395. }
  396. }
  397. }
  398. }