OEMConnection.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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. if (gps.StatusFlags().Any(x => x == GPSStatus.NoSignal))
  77. {
  78. Logger.Send(LogType.Information, Serial, $"- Skipping: Invalid Signal ({Serial})");
  79. return null;
  80. }
  81. var timestamp = record.TimeStampToDateTime(record.TimeStamp);
  82. var age = timestamp - Devices[Serial].TimeStamp;
  83. if (age <= AgeThreshold)
  84. {
  85. Logger.Send(LogType.Information, Serial, $"- Skipping: Recent Update ({Serial}) {age:mm\\:ss}");
  86. return null;
  87. }
  88. var device = Devices[Serial];
  89. var location = new GPSTrackerLocation();
  90. location.DeviceID = Serial;
  91. location.Tracker.ID = device.ID;
  92. location.Location.Timestamp = timestamp;
  93. location.Location.Latitude = (double)gps.Latitude / 10000000.0F;
  94. location.Location.Longitude = (double)gps.Longitude / 10000000.0F;
  95. var analoguedata = record.GetFields<DMAnalogueDataField16>().FirstOrDefault();
  96. if (analoguedata != null)
  97. location.BatteryLevel = analoguedata.BatteryStrength
  98. ?? device.CalculateBatteryLevel(analoguedata.InternalVoltage);
  99. return location;
  100. }
  101. private GPSTrackerLocation? HandleBluetoothTag(DMGPSField gps, DMRecord record, DMBluetoothTag tag)
  102. {
  103. var tagID = tag.ID();
  104. if (!Devices.ContainsKey(tagID) && tagID.Length == 17 && tagID.Split(':').Length == 6)
  105. {
  106. var truncated = tagID[..15];
  107. var newtag = Devices.Keys.FirstOrDefault(x => x.StartsWith(truncated));
  108. Logger.Send(LogType.Information, Serial, $"- Truncating BT Tag: {tagID} -> {truncated} -> {newtag}");
  109. if (!string.IsNullOrWhiteSpace(newtag))
  110. tagID = newtag;
  111. }
  112. if (!Devices.ContainsKey(tagID))
  113. {
  114. Logger.Send(LogType.Information, Serial, $"- Skipping: Unknown Tag ({tagID})");
  115. return null;
  116. }
  117. var timestamp = record.TimeStampToDateTime(record.TimeStamp);
  118. var age = timestamp - Devices[tagID].TimeStamp;
  119. if (age <= AgeThreshold)
  120. {
  121. Logger.Send(LogType.Information, Serial, $"- Skipping: Recent Update ({tagID}) {age:mm\\:ss}");
  122. return null;
  123. }
  124. var device = Devices[tagID];
  125. var btloc = new GPSTrackerLocation();
  126. btloc.DeviceID = tagID;
  127. btloc.Tracker.ID = device.ID;
  128. btloc.Location.Timestamp = timestamp;
  129. btloc.Location.Latitude = (double)gps.Latitude / 10000000.0F;
  130. btloc.Location.Longitude = (double)gps.Longitude / 10000000.0F;
  131. if (tag is DMGuppyBluetoothTag guppy)
  132. {
  133. btloc.BatteryLevel = device.CalculateBatteryLevel(guppy.BatteryVoltage);
  134. //guppy.BatteryVoltage * 5F / 3F;
  135. }
  136. else if (tag is DMSensorNodeBluetoothTag sensornode)
  137. {
  138. // Need to check with Kenrick about the calcs here..
  139. // Guppies have 1 battery (ie 1.5V) while Sensornodes have 3 (4.5V)
  140. btloc.BatteryLevel = device.CalculateBatteryLevel(sensornode.BatteryVoltage);
  141. //btloc.BatteryLevel = sensornode.BatteryVoltage * 5F / 3F;
  142. }
  143. return btloc;
  144. }
  145. private IEnumerable<GPSTrackerLocation> HandleRecord(DMRecord record)
  146. {
  147. if (Devices.ContainsKey(Serial))
  148. {
  149. if (record.Fields.FirstOrDefault(x => x is DMGPSField && x.IsValid()) is DMGPSField gps)
  150. {
  151. if (record.TimeStamp != 0 && gps.Latitude != 0 && gps.Longitude != 0)
  152. {
  153. if (HandleTracker(gps, record) is GPSTrackerLocation trackerLocation)
  154. {
  155. yield return trackerLocation;
  156. }
  157. foreach (DMBluetoothTagList taglist in record.GetFields<DMBluetoothTagList>())
  158. foreach (var item in taglist.Items.Where(x => x.LogReason != 2))
  159. {
  160. if (HandleBluetoothTag(gps, record, item.Tag) is GPSTrackerLocation location)
  161. {
  162. yield return location;
  163. }
  164. }
  165. foreach (DMBluetoothTagData tag in record.GetFields<DMBluetoothTagData>())
  166. if (tag.LogReason != 2 && tag.TimeStamp != 0 && tag.Latitude != 0 && tag.Longitude != 0)
  167. {
  168. if (HandleBluetoothTag(gps, record, tag.Tag) is GPSTrackerLocation location)
  169. {
  170. yield return location;
  171. }
  172. }
  173. }
  174. else
  175. {
  176. Logger.Send(LogType.Information, Serial,
  177. string.Format("- Skipping: Invalid GPS Data ({0}) {1}{2}{3}", Serial,
  178. gps.TimeStamp == 0 ? "Bad TimeStamp " : "", gps.Latitude == 0 ? "Bad Latitude " : "",
  179. gps.Longitude == 0 ? "Bad Longitude " : "").Trim());
  180. }
  181. }
  182. else
  183. {
  184. Logger.Send(LogType.Information, Serial,
  185. string.Format("- Skipping: Missing GPS Data ({0})", Serial));
  186. }
  187. }
  188. else
  189. {
  190. Logger.Send(LogType.Information, Serial, string.Format("- Skipping: Unknown Device ({0})", Serial));
  191. }
  192. }
  193. private DMConfirmResponse HandleConfirm(DMConfirmRequest confirm)
  194. {
  195. Logger.Send(LogType.Information, Serial, string.Format("Goodbye {0} ({1})", Product, Serial));
  196. var updates = new List<GPSTrackerLocation>();
  197. foreach (var data in Data)
  198. foreach (var record in data.Records)
  199. {
  200. foreach(var update in HandleRecord(record))
  201. {
  202. updates.Add(update);
  203. }
  204. }
  205. if (updates.Any())
  206. {
  207. Logger.Send(LogType.Information, Serial,
  208. string.Format("Sending updates ({0}): {1}", updates.Count,
  209. string.Join(", ", updates.Select(x => x.DeviceID).Distinct())));
  210. foreach (var update in updates)
  211. {
  212. Logger.Send(LogType.Information, Serial,
  213. string.Format("- Updating Device Cache: ({0}): {1:yyyy-MM-dd hh:mm:ss}", update.DeviceID,
  214. update.Location.Timestamp));
  215. //if (m_devices.ContainsKey(update.DeviceID))
  216. var oldDevice = Devices[update.DeviceID];
  217. Devices[update.DeviceID] =
  218. new Device(oldDevice.ID, update.Location.Timestamp, oldDevice.BatteryFormula);
  219. }
  220. foreach (var update in updates)
  221. {
  222. Queue.QueueUpdate($"Updated by {Product} ({Serial})", update);
  223. }
  224. }
  225. return new DMConfirmResponse { Status = 1 };
  226. }
  227. private void HandleMessage(DMMessage message)
  228. {
  229. DMMessage? response;
  230. if (message is DMHelloRequest hello)
  231. {
  232. response = HandleHello(hello);
  233. }
  234. else if (message is DMDataRequest data)
  235. {
  236. response = HandleData(data);
  237. }
  238. else if (message is DMConfirmRequest confirm)
  239. {
  240. response = HandleConfirm(confirm);
  241. Confirmed = true;
  242. }
  243. else
  244. {
  245. Logger.Send(LogType.Information, "", $"Unknown message type {message.Type}");
  246. response = null;
  247. }
  248. if(response is not null)
  249. {
  250. Stream.Write(response.EncodeArray());
  251. }
  252. }
  253. /// <summary>
  254. ///
  255. /// </summary>
  256. /// <remarks>
  257. /// Read occurs asynchronously, so essentially this method spins off a read thread and then returns.
  258. /// If we call <see cref="Stop"/> before data comes in, the read does not occur.
  259. /// </remarks>
  260. private void DoRead()
  261. {
  262. var readData = false;
  263. // We pass in the cancellation token to prevent the task from continuing if we call stop.
  264. ReadTask = Stream.ReadAsync(Buffer, 0, Buffer.Length).ContinueWith(t =>
  265. {
  266. if(t.Exception is not null)
  267. {
  268. if (Finished)
  269. {
  270. Finish();
  271. }
  272. else
  273. {
  274. Logger.Send(LogType.Error, Environment.CurrentManagedThreadId.ToString(), CoreUtils.FormatException(t.Exception));
  275. }
  276. }
  277. else
  278. {
  279. readData = true;
  280. var nBytes = t.Result;
  281. if (nBytes > 0)
  282. {
  283. ConsolidatedBuffer.AddRange(Buffer.Take(nBytes));
  284. try
  285. {
  286. while (ConsolidatedBuffer.Count > 0)
  287. {
  288. DMMessage? message = null;
  289. try
  290. {
  291. var payloadLength = DMFactory.PeekPayloadLength(ConsolidatedBuffer);
  292. if (nBytes == Buffer.Length && ConsolidatedBuffer.Count < payloadLength)
  293. {
  294. // Probably we need more data.
  295. break;
  296. }
  297. else
  298. {
  299. message = DMFactory.ParseMessage(ConsolidatedBuffer);
  300. }
  301. }
  302. catch (Exception e)
  303. {
  304. Logger.Send(
  305. LogType.Error,
  306. Environment.CurrentManagedThreadId.ToString(),
  307. string.Format("Unable to Parse Record: {0} ({1})", e.Message, BitConverter.ToString(ConsolidatedBuffer.ToArray()))
  308. );
  309. break;
  310. }
  311. if (message is not null)
  312. {
  313. HandleMessage(message);
  314. ConsolidatedBuffer.RemoveRange(0, message.CheckSum + 5);
  315. }
  316. }
  317. }
  318. catch (Exception e)
  319. {
  320. Logger.Send(LogType.Error, Environment.CurrentManagedThreadId.ToString(), e.Message + "\n" + e.StackTrace);
  321. }
  322. }
  323. else
  324. {
  325. Finished = true;
  326. }
  327. if (Finished)
  328. {
  329. Finish();
  330. }
  331. else
  332. {
  333. // If we still have stuff to do, try reading again. Note that this isn't a recursive problem or anything, because
  334. // this method returns very soon.
  335. DoRead();
  336. }
  337. }
  338. }, TokenSource.Token);
  339. // After 15 seconds, close the connection (but only if it has been confirmed).
  340. var delay = Task.Delay(15_000).ContinueWith(t =>
  341. {
  342. if (!readData)
  343. {
  344. Finished = true;
  345. if (Confirmed)
  346. {
  347. Logger.Send(LogType.Error, "", "Closing connection after 15 seconds of silence.");
  348. Stream.Close();
  349. }
  350. else
  351. {
  352. Logger.Send(LogType.Error, "", "No data read for 15 seconds, but connection has not been confirmed.");
  353. }
  354. }
  355. });
  356. }
  357. public void Run()
  358. {
  359. Buffer = new byte[2048];
  360. ConsolidatedBuffer = new List<byte>();
  361. DoRead();
  362. }
  363. private void Finish()
  364. {
  365. Stream.Close();
  366. Client.Close();
  367. OnCompletion?.Invoke();
  368. }
  369. public void Stop()
  370. {
  371. // Cancel any read tasks which are yet to start.
  372. TokenSource.Cancel();
  373. Stream.Close();
  374. Client.Close();
  375. try
  376. {
  377. // Let the latest task finish.
  378. if(ReadTask?.Wait(1000) == false)
  379. {
  380. Logger.Send(LogType.Error, "", "The thread didn't die in time.");
  381. }
  382. }
  383. catch (AggregateException ae)
  384. {
  385. foreach(var exception in ae.InnerExceptions)
  386. {
  387. if(exception is not TaskCanceledException)
  388. {
  389. throw;
  390. }
  391. }
  392. }
  393. }
  394. }
  395. }