diff --git a/RS485 Monitor/src/Telegrams/BaseTelegram.cs b/RS485 Monitor/src/Telegrams/BaseTelegram.cs index ddc3f4d..14c15f1 100644 --- a/RS485 Monitor/src/Telegrams/BaseTelegram.cs +++ b/RS485 Monitor/src/Telegrams/BaseTelegram.cs @@ -137,6 +137,11 @@ public enum TelegramType /// public TelegramType Type { get => (TelegramType)RawType; } + /// + /// Timestamp when the telegram was received / created + /// + public DateTime TimeStamp { get; } + #endregion /// @@ -165,11 +170,15 @@ protected BaseTelegram(BaseTelegram c) /// Create a new base telegram based on the given raw data /// /// raw data of one telegram + /// + /// Optional timestamp when the telegram was received. If it stays null, + /// the current timestamp is used. + /// /// Raw data is null. /// Raw data is too short. /// Invalid data length in the raw data. /// Raw data does not contain End tag. - public BaseTelegram(byte[] rawData) + public BaseTelegram(byte[] rawData, DateTime? timestamp = null) { // Basic validation ArgumentNullException.ThrowIfNull(rawData); @@ -206,6 +215,9 @@ public BaseTelegram(byte[] rawData) log.Error("RawData does not hold Endtag"); throw new ArgumentException("Raw data does not contain End tag"); } + + // Set timestamp + TimeStamp = timestamp ?? DateTime.Now; } /// diff --git a/tests/BaseTelegramTest.cs b/tests/BaseTelegramTest.cs index 2a5a2cd..4181f68 100644 --- a/tests/BaseTelegramTest.cs +++ b/tests/BaseTelegramTest.cs @@ -114,4 +114,26 @@ public void NotEqualsTest() Assert.That(telegram1.Equals(telegram2), Is.EqualTo(false)); } + + [Test] + public void AutomaticTimeStampCreated() + { + byte[] raw = [0xB6, 0x6B, 0xAA, 0xDA, 0x0A, 0x02, 0x00, 0x04, 0x00, 0x00, 0x13, 0x00, 0x00, 0x02, 0x01, 0x1C, 0x0D]; + + BaseTelegram telegram = new(raw); + var now = DateTime.Now; + + Assert.That(telegram.TimeStamp.Ticks, Is.EqualTo(now.Ticks).Within(300)); + } + + [Test] + public void ManualTimeStampCreated() + { + byte[] raw = [0xB6, 0x6B, 0xAA, 0xDA, 0x0A, 0x02, 0x00, 0x04, 0x00, 0x00, 0x13, 0x00, 0x00, 0x02, 0x01, 0x1C, 0x0D]; + DateTime timestamp = new(2021, 12, 24, 12, 0, 0); + + BaseTelegram telegram = new(raw, timestamp); + + Assert.That(telegram.TimeStamp, Is.EqualTo(timestamp)); + } }