/// <summary> /// Constructs a new <see cref="Frame"/> given the specified parameters. /// </summary> /// <param name="timestamp">Timestamp, in ticks, for this <see cref="Frame"/>.</param> /// <param name="measurements">Initial set of measurements to load into the <see cref="Frame"/>, if any.</param> public Frame(Ticks timestamp, IDictionary<MeasurementKey, IMeasurement> measurements) { m_timestamp = timestamp; m_receivedTimestamp = DateTime.UtcNow.Ticks; m_measurements = new ConcurrentDictionary<MeasurementKey, IMeasurement>(measurements); m_sortedMeasurements = -1; }
/// <summary> /// Initializes a new instance of the <see cref="TimestampTest"/> class. /// </summary> public TimestampTest() { m_badTimestampMeasurements = new Dictionary<Ticks, LinkedList<IMeasurement>>(); m_timeToPurge = Ticks.FromSeconds(1.0); m_warnInterval = Ticks.FromSeconds(4.0); m_purgeTimer = new System.Timers.Timer(); m_warningTimer = new System.Timers.Timer(); }
/// <summary> /// Creates a new instance of the <see cref="FlatlineTest"/> class. /// </summary> public FlatlineTest() { m_minFlatline = Ticks.FromSeconds(4); m_warnInterval = Ticks.FromSeconds(4); m_emailInterval = Ticks.FromSeconds(3600); m_smtpServer = Mail.DefaultSmtpServer; m_lastChange = new Dictionary<MeasurementKey, IMeasurement>(); m_lastNotified = new Dictionary<MeasurementKey, Ticks>(); m_warningTimer = new System.Timers.Timer(); }
private IMeasurement m_lastSortedMeasurement; // Last measurement sorted into this frame #endregion #region [ Constructors ] /// <summary> /// Constructs a new <see cref="Frame"/> given the specified parameters. /// </summary> /// <param name="timestamp">Timestamp, in ticks, for this <see cref="Frame"/>.</param> /// <param name="expectedMeasurements">Expected number of measurements for the <see cref="Frame"/>.</param> public Frame(Ticks timestamp, int expectedMeasurements = -1) { m_timestamp = timestamp; m_receivedTimestamp = DateTime.UtcNow.Ticks; if (expectedMeasurements > 0) m_measurements = new ConcurrentDictionary<MeasurementKey, IMeasurement>(s_defaultConcurrencyLevel, expectedMeasurements * 2); else m_measurements = new ConcurrentDictionary<MeasurementKey, IMeasurement>(); m_sortedMeasurements = -1; }
private void AddMeasurementWithBadTimestamp(Ticks timeArrived, IMeasurement measurement) { lock (m_badTimestampMeasurements) { LinkedList<IMeasurement> measurementList; if (!m_badTimestampMeasurements.TryGetValue(timeArrived, out measurementList)) { measurementList = new LinkedList<IMeasurement>(); m_badTimestampMeasurements.Add(timeArrived, measurementList); } measurementList.AddLast(measurement); m_totalBadTimestampMeasurements++; } }
/// <summary> /// Initializes <see cref="FlatlineTest"/>. /// </summary> public override void Initialize() { base.Initialize(); Dictionary<string, string> settings = Settings; string setting; if (settings.TryGetValue("minFlatline", out setting)) m_minFlatline = Ticks.FromSeconds(double.Parse(setting)); if (settings.TryGetValue("warnInterval", out setting)) m_warnInterval = Ticks.FromSeconds(double.Parse(setting)); if (settings.TryGetValue("adminEmailAddress", out m_adminEmailAddress)) { // emailInterval is entered in minutes. if (settings.TryGetValue("emailInterval", out setting)) m_emailInterval = Ticks.FromSeconds(long.Parse(setting) * 60L); } if (settings.TryGetValue("smtpServer", out setting)) m_smtpServer = setting; m_warningTimer.Interval = m_warnInterval.ToMilliseconds(); m_warningTimer.Elapsed += m_warningTimer_Elapsed; m_flatlineService = new FlatlineService(this); m_flatlineService.SettingsCategory = base.Name + m_flatlineService.SettingsCategory; m_flatlineService.ServiceProcessException += m_flatlineService_ServiceProcessException; m_flatlineService.Initialize(); InitializeLastChange(); }
/// <summary> /// Raises the <see cref="DataStartTime"/> event. /// </summary> /// <param name="startTime">Start time, in <see cref="Ticks"/>, of first measurement transmitted.</param> protected void OnDataStartTime(Ticks startTime) { try { if (DataStartTime != null) DataStartTime(this, new EventArgs<Ticks>(startTime)); } catch (Exception ex) { // We protect our code from consumer thrown exceptions OnProcessException(new InvalidOperationException(string.Format("Exception in consumer handler for DataStartTime event: {0}", ex.Message), ex)); } }
/// <summary> /// Creates a new instance of the <see cref="RangeTest"/> class. /// </summary> public RangeTest() { m_outOfRangeMeasurements = new Dictionary<MeasurementKey, LinkedList<IMeasurement>>(); m_timeToPurge = Ticks.FromSeconds(1.0); m_warnInterval = Ticks.FromSeconds(4.0); m_warningTimer = new System.Timers.Timer(); m_purgeTimer = new System.Timers.Timer(); }
/// <summary> /// Gets proper NTP offset based on <paramref name="timestamp"/> value, see RFC-2030. /// </summary> /// <param name="timestamp"><see cref="Ticks"/> timestamp value.</param> /// <returns>Proper NTP offset.</returns> protected static long GetBaseDateOffsetTicks(Ticks timestamp) { if (timestamp < NtpDateOffsetTicksAlt) return NtpDateOffsetTicks; else return NtpDateOffsetTicksAlt; }
/// <summary>Sets numeric value and timestamp, as ticks, of this <see cref="TemporalMeasurement"/>.</summary> /// <remarks> /// <para>Operation will only store a value that is newer than the cached value.</para> /// </remarks> /// <param name="timestamp">New timestamp, in ticks, for <see cref="TemporalMeasurement"/>.</param> /// <param name="value">New value for <see cref="TemporalMeasurement"/>, only stored if <paramref name="timestamp"/> are newer than current <see cref="Ticks"/>.</param> /// <returns><c>true</c> if value was updated; otherwise <c>false</c>.</returns> public bool SetValue(Ticks timestamp, double value) { // We only store a value that is is newer than the current value if (timestamp > Timestamp) { base.Value = value; Timestamp = timestamp; return true; } return false; }
// Determines whether the given value has // flatlined over the configured delay interval. private bool CheckFlatline(IMeasurement signal) { long dist, diff; if (signal.Value != m_lastValue) { m_lastChanged = signal.Timestamp; m_lastValue = signal.Value; } dist = Ticks.FromSeconds(Delay.Value); diff = signal.Timestamp - m_lastChanged; return diff >= dist; }
// Tests the given measurement to determine whether // its value indicates that the signal has been in // the alarming range for the configured delay time. private bool CheckRange(IMeasurement signal) { bool result = GetTestResult(signal); Ticks dist; if (!result) { // Keep track of the last time // the signal was in range m_lastNegative = signal.Timestamp; } else { // Get the amount of time since the // last time the value was in range dist = signal.Timestamp - m_lastNegative; // If the amount of time is larger than // the delay threshold, raise the alarm if (dist >= Ticks.FromSeconds(Delay.Value)) return true; } return false; }
/// <summary> /// Creates a new <see cref="IFrame"/> for the given <paramref name="timestamp"/>. /// </summary> /// <param name="timestamp">Timestamp for new <see cref="IFrame"/> in <see cref="Ticks"/>.</param> /// <returns>New <see cref="IFrame"/> at given <paramref name="timestamp"/>.</returns> /// <remarks> /// Derived classes can override this method to create a new custom <see cref="IFrame"/>. Default /// behavior creates a basic <see cref="Frame"/> to hold synchronized measurements. /// </remarks> protected internal virtual IFrame CreateNewFrame(Ticks timestamp) { return new Frame(timestamp, m_expectedMeasurements); }
/// <summary> /// Returns the deviation, in milliseconds, that the given number of ticks is from real-time (i.e., <see cref="ConcentratorBase.RealTime"/>). /// </summary> /// <param name="timestamp">Timestamp to calculate distance from real-time.</param> /// <returns>A <see cref="Double"/> value indicating the deviation in milliseconds.</returns> public double MillisecondsFromRealTime(Ticks timestamp) { return SecondsFromRealTime(timestamp) / SI.Milli; }
/// <summary> /// Returns the deviation, in seconds, that the given number of ticks is from real-time (i.e., <see cref="ConcentratorBase.RealTime"/>). /// </summary> /// <param name="timestamp">Timestamp to calculate distance from real-time.</param> /// <returns>A <see cref="Double"/> value indicating the deviation, in seconds, from real-time.</returns> public double SecondsFromRealTime(Ticks timestamp) { // Make sure real-time is initialized for initial distance calculation if (Thread.VolatileRead(ref m_realTimeTicks) == 0) { long currentTimeTicks; if (m_performTimestampReasonabilityCheck) currentTimeTicks = DateTime.UtcNow.Ticks; else currentTimeTicks = timestamp; Thread.VolatileWrite(ref m_realTimeTicks, currentTimeTicks); } return (RealTime - timestamp).ToSeconds(); }
/// <summary>Gets numeric value of this <see cref="TemporalMeasurement"/>, constrained within specified ticks.</summary> /// <remarks> /// <para>Operation will return NaN if ticks are outside of time deviation tolerances.</para> /// </remarks> /// <param name="timestamp">Timestamp, in ticks, used to constrain <see cref="TemporalMeasurement"/> (typically set to real-time, i.e. "now").</param> /// <returns>Raw value of this measurement (i.e., value that is not offset by adder and multiplier).</returns> public double GetValue(Ticks timestamp) { // We only return a measurement value that is up-to-date... return Timestamp.TimeIsValid(timestamp, m_lagTime, m_leadTime) ? base.Value : double.NaN; }
public void ToTicksTest() { Time target = new Time(10F); Ticks expected = new Ticks(100000000); Ticks actual; actual = target.ToTicks(); Assert.AreEqual(expected, actual); }
/// <summary> /// Creates a new <see cref="NtpTimeTag"/>, given specified <see cref="Ticks"/>. /// </summary> /// <param name="timestamp">Timestamp in <see cref="Ticks"/> to create Unix timetag from (minimum valid date is 1/1/1900).</param> /// <remarks> /// This constructor will accept a <see cref="DateTime"/> parameter since <see cref="Ticks"/> is implicitly castable to a <see cref="DateTime"/>. /// </remarks> public NtpTimeTag(Ticks timestamp) : base(GetBaseDateOffsetTicks(timestamp), timestamp) { }
/// <summary> /// Creates or updates cipher keys. /// </summary> internal void UpdateKeyIVs() { using (AesManaged symmetricAlgorithm = new AesManaged()) { symmetricAlgorithm.KeySize = 256; symmetricAlgorithm.GenerateKey(); symmetricAlgorithm.GenerateIV(); if (m_keyIVs == null) { // Initialize new key set m_keyIVs = new byte[2][][]; m_keyIVs[EvenKey] = new byte[2][]; m_keyIVs[OddKey] = new byte[2][]; m_keyIVs[EvenKey][KeyIndex] = symmetricAlgorithm.Key; m_keyIVs[EvenKey][IVIndex] = symmetricAlgorithm.IV; symmetricAlgorithm.GenerateKey(); symmetricAlgorithm.GenerateIV(); m_keyIVs[OddKey][KeyIndex] = symmetricAlgorithm.Key; m_keyIVs[OddKey][IVIndex] = symmetricAlgorithm.IV; m_cipherIndex = EvenKey; } else { // Generate a new key set for current cipher index m_keyIVs[m_cipherIndex][KeyIndex] = symmetricAlgorithm.Key; m_keyIVs[m_cipherIndex][IVIndex] = symmetricAlgorithm.IV; // Set run-time to the other key set m_cipherIndex ^= 1; } } m_lastCipherKeyUpdateTime = DateTime.UtcNow.Ticks; }
protected static ulong GetNTPTimestampFromTicks(Ticks timestamp) { timestamp -= GetBaseDateOffsetTicks(timestamp); uint seconds = (uint)Math.Truncate(timestamp.ToSeconds()); uint fraction = (uint)(timestamp.DistanceBeyondSecond().ToSeconds() * uint.MaxValue); return Word.MakeQword(seconds, fraction); }
/// <summary> /// Creates a copy of the specified measurement using a new value and timestamp. /// </summary> /// <param name="measurementToClone">Specified measurement to clone.</param> /// <param name="value">New value for cloned measurement.</param> /// <param name="timestamp">New timestamp, in ticks, for cloned measurement.</param> /// <returns>A copy of the <see cref="Measurement"/> object.</returns> public static Measurement Clone(IMeasurement measurementToClone, double value, Ticks timestamp) { return new Measurement() { ID = measurementToClone.ID, Key = measurementToClone.Key, Value = value, Adder = measurementToClone.Adder, Multiplier = measurementToClone.Multiplier, Timestamp = timestamp, TagName = measurementToClone.TagName, StateFlags = measurementToClone.StateFlags }; }
/// <summary> /// Initializes this <see cref="RangeTest"/>. /// </summary> public override void Initialize() { base.Initialize(); string errorMessage = "{0} is missing from Settings - Example: lowRange=59.95; highRange=60.05"; bool rangeSet = false; Dictionary<string, string> settings = Settings; string setting; if (settings.TryGetValue("signalType", out m_signalType)) rangeSet = TrySetRange(m_signalType); if(!rangeSet) { // Load required parameters if (!settings.TryGetValue("lowRange", out setting)) throw new ArgumentException(string.Format(errorMessage, "lowRange")); m_lowRange = double.Parse(setting); if (!settings.TryGetValue("highRange", out setting)) throw new ArgumentException(string.Format(errorMessage, "highRange")); m_highRange = double.Parse(setting); rangeSet = true; } // Load optional parameters if (settings.TryGetValue("timeToPurge", out setting)) m_timeToPurge = Ticks.FromSeconds(double.Parse(setting)); if (settings.TryGetValue("warnInterval", out setting)) m_warnInterval = Ticks.FromSeconds(double.Parse(setting)); m_warningTimer.Interval = m_warnInterval.ToMilliseconds(); m_warningTimer.Elapsed += m_warningTimer_Elapsed; m_purgeTimer.Interval = m_timeToPurge.ToMilliseconds(); m_purgeTimer.Elapsed += m_purgeTimer_Elapsed; }
/// <summary> /// Constructs a new <see cref="Measurement"/> using default settings. /// </summary> public Measurement() { m_receivedTimestamp = DateTime.UtcNow.Ticks; m_multiplier = 1.0D; }
static void ShowConnectedClients(object state) { Ticks displayTime = DateTime.UtcNow.Ticks; // Don't show client enumeration more than every two seconds... if ((displayTime - lastDisplayTime).ToSeconds() > 2.0D) { lastDisplayTime = displayTime; publisher.EnumerateClients(); } }
/// <summary> /// Creates a new <see cref="UnixTimeTag"/>, given specified <see cref="Ticks"/>. /// </summary> /// <param name="timestamp">Timestamp in <see cref="Ticks"/> to create Unix timetag from (minimum valid date is 1/1/1970).</param> /// <remarks> /// This constructor will accept a <see cref="DateTime"/> parameter since <see cref="Ticks"/> is implicitly castable to a <see cref="DateTime"/>. /// </remarks> public UnixTimeTag(Ticks timestamp) : base(UnixDateOffsetTicks, timestamp) { }
/// <summary> /// Initializes <see cref="TimestampTest"/>. /// </summary> public override void Initialize() { base.Initialize(); string errorMessage = "{0} is missing from Settings - Example: concentratorName=TESTSTREAM"; Dictionary<string, string> settings = Settings; string setting; // Load optional parameters if (settings.TryGetValue("timeToPurge", out setting)) m_timeToPurge = Ticks.FromSeconds(double.Parse(setting)); if (settings.TryGetValue("warnInterval", out setting)) m_warnInterval = Ticks.FromSeconds(double.Parse(setting)); // Load required parameters string concentratorName; if (!settings.TryGetValue("concentratorName", out concentratorName)) throw new ArgumentException(string.Format(errorMessage, "concentratorName")); m_discardingAdapter = null; // Find the adapter whose name matches the specified concentratorName foreach (IAdapter adapter in Parent) { IActionAdapter concentrator = adapter as IActionAdapter; if (concentrator != null && string.Compare(adapter.Name, concentratorName, true) == 0) { m_discardingAdapter = concentrator; break; } } if (m_discardingAdapter == null) throw new ArgumentException(string.Format("Concentrator {0} not found.", concentratorName)); // Wait for associated adapter to initialize int timeout = m_discardingAdapter.InitializationTimeout; m_discardingAdapter.WaitForInitialize(timeout); if (!m_discardingAdapter.Initialized) throw new TimeoutException(string.Format("Timeout waiting for concentrator {0} to initialize.", concentratorName)); // Attach to adapter's discarding measurements and disposed events m_discardingAdapter.DiscardingMeasurements += m_discardingAdapter_DiscardingMeasurements; m_discardingAdapter.Disposed += m_discardingAdapter_Disposed; m_purgeTimer.Interval = m_timeToPurge.ToMilliseconds(); m_purgeTimer.Elapsed += m_purgeTimer_Elapsed; m_warningTimer.Interval = m_warnInterval.ToMilliseconds(); m_warningTimer.Elapsed += m_warningTimer_Elapsed; m_timestampService = new TimestampService(this); m_timestampService.ServiceProcessException += m_timestampService_ServiceProcessException; m_timestampService.SettingsCategory = base.Name + m_timestampService.SettingsCategory; m_timestampService.Initialize(); }
/// <summary> /// Initializes a new instance of the <see cref="SerializableBadTimestampMeasurement"/> class. /// </summary> /// <param name="measurement"><see cref="IMeasurement"/> from which <see cref="SerializableOutOfRangeMeasurement"/> is to be initialized.</param> /// <param name="arrivalTime">The arrival time of the <see cref="IMeasurement"/>.</param> public SerializableBadTimestampMeasurement(IMeasurement measurement, Ticks arrivalTime) : base(measurement) { TimeOfArrival = ((DateTime)arrivalTime).ToString("yyyy-MM-dd HH:mm:ss.fff"); }