You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

53 rivejä
1.8 KiB

  1. using System;
  2. using ThunderboltTimeSync.Devices.Thunderbolt;
  3. namespace ThunderboltTimeSync.TimeProviders.Thunderbolt {
  4. class ThunderboltTimeProvider : ITimeProvider {
  5. private ThunderboltSerialPort thunderboltSerialPort;
  6. public event TimeAvailableEventHandler TimeAvailable;
  7. public event LogEventHandler Log;
  8. /// <summary>
  9. /// Creates an instance of the ThunderboltTimeProvider class, which provides time information through the ITimeProvider interface.
  10. /// The ThunderboltSerialPort instance passed into this function must not be open.
  11. /// </summary>
  12. /// <param name="thunderboltSerialPort">The ThunderboltSerialPort instance to use when communicating with the Thunderbolt.</param>
  13. public ThunderboltTimeProvider(ThunderboltSerialPort thunderboltSerialPort) {
  14. this.thunderboltSerialPort = thunderboltSerialPort;
  15. thunderboltSerialPort.PacketReceived += PacketReceived;
  16. }
  17. public void Start() {
  18. thunderboltSerialPort.Open();
  19. }
  20. public void Stop() {
  21. thunderboltSerialPort.Close();
  22. }
  23. private void PacketReceived(ThunderboltPacket packet) {
  24. if (packet.IsPacketValid) {
  25. if (packet.ID == 0x8F && packet.Data.Count == 17 && packet.Data[0] == 0xAB) {
  26. int timeOfWeek = packet.Data[1] << 24 | packet.Data[2] << 16 | packet.Data[3] << 8 | packet.Data[4];
  27. ushort weekNumber = (ushort) (packet.Data[5] << 8 | packet.Data[6]);
  28. short utcOffset = (short) (packet.Data[7] << 8 | packet.Data[8]);
  29. // Current epoch for GPS week numbers is the morning of 22/8/1999
  30. DateTime dateTime = new DateTime(1999, 8, 22, 0, 0, 0);
  31. dateTime = dateTime.AddDays(7 * weekNumber);
  32. dateTime = dateTime.AddSeconds(timeOfWeek);
  33. dateTime = dateTime.AddSeconds(-utcOffset);
  34. TimeAvailable?.Invoke(dateTime);
  35. }
  36. } else {
  37. Log?.Invoke("An invalid packet was received.", LogLevel.Warning);
  38. }
  39. }
  40. }
  41. }