/// <summary>
 /// Constructs a new <see cref="SignalReferenceMeasurement"/> from the specified parameters.
 /// </summary>
 /// <param name="measurement">Source <see cref="IMeasurement"/> value.</param>
 /// <param name="signalReference">Associated <see cref="SignalReference"/>.</param>
 public SignalReferenceMeasurement(IMeasurement measurement, SignalReference signalReference)
     : base(measurement.ID, measurement.Source, measurement.Value, measurement.Adder, measurement.Multiplier, measurement.Timestamp)
 {
     base.ValueQualityIsGood = measurement.ValueQualityIsGood;
     base.TimestampQualityIsGood = measurement.TimestampQualityIsGood;
     m_signalReference = signalReference;
 }
 /// <summary>
 /// Creates a new <see cref="SerializableMeasurement"/> from an existing <see cref="IMeasurement"/> value.
 /// </summary>
 /// <param name="measurement">Source <see cref="IMeasurement"/> value.</param>
 /// <param name="encoding">Character encoding used to convert strings to binary.</param>
 public SerializableMeasurement(IMeasurement measurement, Encoding encoding)
     : this(encoding)
 {
     Metadata = measurement.Metadata;
     Value = measurement.Value;
     Timestamp = measurement.Timestamp;
     StateFlags = measurement.StateFlags;
 }
Beispiel #3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SerializableMeasurement"/> class.
 /// </summary>
 /// <param name="measurement"><see cref="IMeasurement"/> from which <see cref="SerializableMeasurement"/> is to be initialized.</param>
 public SerializableMeasurement(IMeasurement measurement)
 {
     m_sourceMeasurement = measurement;
     Key = measurement.Key.ToString();
     SignalID = measurement.ID.ToString();
     Value = measurement.AdjustedValue;
     Timestamp = ((DateTime)measurement.Timestamp).ToString("yyyy-MM-dd HH:mm:ss.fff");
     SignalType = string.Empty;
     Device = string.Empty;
 }
Beispiel #4
0
 /// <summary>
 /// Creates a new <see cref="SerializableMeasurement"/> from an existing <see cref="IMeasurement"/> value.
 /// </summary>
 /// <param name="measurement">Source <see cref="IMeasurement"/> value.</param>
 /// <param name="encoding">Character encoding used to convert strings to binary.</param>
 public SerializableMeasurement(IMeasurement measurement, Encoding encoding)
     : this(encoding)
 {
     Key = measurement.Key;
     Value = measurement.Value;
     Adder = measurement.Adder;
     Multiplier = measurement.Multiplier;
     Timestamp = measurement.Timestamp;
     StateFlags = measurement.StateFlags;
 }
Beispiel #5
0
		public void PostMeasurement(IMeasurement measurement)
		{
			if (measurement == null)
			{
				return;
			}
			this.PostMeasurement(new IMeasurement[]
			{
				measurement
			});
		}
 /// <summary>
 /// Creates a new instance of the <see cref="MeasurementWrapper"/> class.
 /// </summary>
 /// <param name="measurement">The measurement to be wrapped by the wrapper.</param>
 public MeasurementWrapper(IMeasurement measurement)
 {
     Adder = measurement.Adder;
     SignalID = measurement.ID.ToString();
     ID = unchecked((int)measurement.Key.ID);
     Multiplier = measurement.Multiplier;
     Source = measurement.Key.Source;
     TagName = measurement.TagName;
     Timestamp = measurement.Timestamp;
     Value = measurement.Value;
 }
        /// <summary>
        /// Constructs a new <see cref="TemporalMeasurement"/> given the specified parameters.
        /// </summary>
        /// <param name="measurement">Source <see cref="IMeasurement"/> value.</param>
        /// <param name="lagTime">Past time deviation tolerance, in seconds - this becomes the amount of time to wait before publishing begins.</param>
        /// <param name="leadTime">Future time deviation tolerance, in seconds - this becomes the tolerated +/- accuracy of the local clock to real-time.</param>
        public TemporalMeasurement(IMeasurement measurement, double lagTime, double leadTime)
        {
            if (measurement != null)
            {
                Metadata = measurement.Metadata;
                Value = measurement.Value;
                Timestamp = measurement.Timestamp;
                StateFlags = measurement.StateFlags;
            }

            if (lagTime <= 0)
                throw new ArgumentOutOfRangeException(nameof(lagTime), "lagTime must be greater than zero, but it can be less than one");

            if (leadTime <= 0)
                throw new ArgumentOutOfRangeException(nameof(leadTime), "leadTime must be greater than zero, but it can be less than one");

            m_lagTime = lagTime;
            m_leadTime = leadTime;
        }
Beispiel #8
0
        /// <summary>
        /// Constructs a new <see cref="TemporalMeasurement"/> given the specified parameters.
        /// </summary>
        /// <param name="measurement">Source <see cref="IMeasurement"/> value.</param>
        /// <param name="lagTime">Past time deviation tolerance, in seconds - this becomes the amount of time to wait before publishing begins.</param>
        /// <param name="leadTime">Future time deviation tolerance, in seconds - this becomes the tolerated +/- accuracy of the local clock to real-time.</param>
        public TemporalMeasurement(IMeasurement measurement, double lagTime, double leadTime)
        {
            if (measurement != null)
            {
                Key = measurement.Key;
                Value = measurement.Value;
                Adder = measurement.Adder;
                Multiplier = measurement.Multiplier;
                Timestamp = measurement.Timestamp;
                StateFlags = measurement.StateFlags;
            }

            if (lagTime <= 0)
                throw new ArgumentOutOfRangeException("lagTime", "lagTime must be greater than zero, but it can be less than one");

            if (leadTime <= 0)
                throw new ArgumentOutOfRangeException("leadTime", "leadTime must be greater than zero, but it can be less than one");

            m_lagTime = lagTime;
            m_leadTime = leadTime;
        }
Beispiel #9
0
 /// <summary>
 /// Returns <c>true</c> if <see cref="MeasurementStateFlags.CalculatedValue"/> is set.
 /// </summary>
 /// <param name="measurement"><see cref="IMeasurement"/> instance to test.</param>
 /// <returns><c>true</c> if <see cref="MeasurementStateFlags.CalculatedValue"/> is not set.</returns>
 public static bool IsCalculated(this IMeasurement measurement)
 {
     return((measurement.StateFlags & MeasurementStateFlags.CalculatedValue) > 0);
 }
Beispiel #10
0
 /// <summary>
 /// Sets the multiplier (i.e., "m" of y = mx + b) for a <see cref="IMeasurement"/>.
 /// </summary>
 /// <param name="measurement"><see cref="IMeasurement"/> to create new <see cref="MeasurementMetadata"/> for.</param>
 /// <param name="multiplier">New multiplier value to assign to measurement's metadata.</param>
 public static void SetMultiplier(this IMeasurement measurement, double multiplier)
 {
     measurement.Metadata = measurement.Metadata.ChangeMultiplier(multiplier);
 }
Beispiel #11
0
 /// <summary>
 /// Gets a unique (run-time only) signal type ID for the given <paramref name="measurement"/> useful for sorting.
 /// </summary>
 /// <param name="measurement"><see cref="IMeasurement"/> to obtain signal type for.</param>
 /// <param name="dataSource"><see cref="DataSet"/> that contains measurement metadata.</param>
 /// <returns>Unique (run-time only) signal type ID for the given <paramref name="measurement"/>.</returns>
 public static int GetSignalType(this IMeasurement measurement, DataSet dataSource)
 {
     // This uses string hash code over something like item count + 1 to generate a unique run-time ID of the signal type since chances of a hash code collision
     // over a small set of signal types is much smaller than the possibility of duplicates due to possible race conditions when using item count + 1
     return(s_signalTypeIDCache.GetOrAdd(measurement.ID, signalID => s_signalTypeIDs.GetOrAdd(LookupSignalType(signalID, dataSource), signalType => signalType.GetHashCode())));
 }
Beispiel #12
0
        // Proxy function to process measurements after waiting for any external events, if needed
        private void StartMeasurementProcessing(IMeasurement[] measurements)
        {
            // Wait for any defined external events
            WaitForExternalEvents();

            // Call user measurement processing function
            ProcessMeasurements(measurements);
        }
Beispiel #13
0
 /// <summary>
 /// Queues a single measurement for processing.
 /// </summary>
 /// <param name="measurement">Measurement to queue for processing.</param>
 public virtual void QueueMeasurementForProcessing(IMeasurement measurement)
 {
     QueueMeasurementsForProcessing(new[] { measurement });
 }
Beispiel #14
0
        /// <summary>
        /// Archives <paramref name="measurements"/> locally.
        /// </summary>
        /// <param name="measurements">Measurements to be archived.</param>
        protected override void ProcessMeasurements(IMeasurement[] measurements)
        {
            if ((object)measurements != null)
            {
                foreach (IMeasurement measurement in measurements)
                {
                    // Create the command string to insert the measurement as a record in the table.
                    StringBuilder commandString = new StringBuilder("INSERT INTO Measurement VALUES ('");
                    IDbCommand command = m_connection.CreateCommand();

                    commandString.Append(measurement.ID);
                    commandString.Append("','");
                    commandString.Append((long)measurement.Timestamp);
                    commandString.Append("',");
                    commandString.Append(measurement.AdjustedValue);
                    commandString.Append(')');

                    command.CommandText = commandString.ToString();
                    command.ExecuteNonQuery();

                }
                m_measurementCount += measurements.Length;
            }
        }
Beispiel #15
0
        private void CollectFromSEL421Outputs(List <IMeasurement> measurements, TypeMapping typeMapping, SEL421_PowerCalculator.Model.SEL421.Outputs data, SEL421_PowerCalculator.Model.SEL421._OutputsMeta meta)
        {
            Dictionary <string, FieldMapping> fieldLookup = typeMapping.FieldMappings.ToDictionary(mapping => mapping.Field.Identifier);

            {
                // Convert value from "P1" field to measurement
                FieldMapping fieldMapping = fieldLookup["P1"];
                IMeasurement measurement  = MakeMeasurement(meta.P1, (double)data.P1);
                measurements.Add(measurement);
            }

            {
                // Convert value from "P2" field to measurement
                FieldMapping fieldMapping = fieldLookup["P2"];
                IMeasurement measurement  = MakeMeasurement(meta.P2, (double)data.P2);
                measurements.Add(measurement);
            }

            {
                // Convert value from "P3" field to measurement
                FieldMapping fieldMapping = fieldLookup["P3"];
                IMeasurement measurement  = MakeMeasurement(meta.P3, (double)data.P3);
                measurements.Add(measurement);
            }

            {
                // Convert value from "P4" field to measurement
                FieldMapping fieldMapping = fieldLookup["P4"];
                IMeasurement measurement  = MakeMeasurement(meta.P4, (double)data.P4);
                measurements.Add(measurement);
            }

            {
                // Convert value from "P5" field to measurement
                FieldMapping fieldMapping = fieldLookup["P5"];
                IMeasurement measurement  = MakeMeasurement(meta.P5, (double)data.P5);
                measurements.Add(measurement);
            }

            {
                // Convert value from "P6" field to measurement
                FieldMapping fieldMapping = fieldLookup["P6"];
                IMeasurement measurement  = MakeMeasurement(meta.P6, (double)data.P6);
                measurements.Add(measurement);
            }

            {
                // Convert value from "Q1" field to measurement
                FieldMapping fieldMapping = fieldLookup["Q1"];
                IMeasurement measurement  = MakeMeasurement(meta.Q1, (double)data.Q1);
                measurements.Add(measurement);
            }

            {
                // Convert value from "Q2" field to measurement
                FieldMapping fieldMapping = fieldLookup["Q2"];
                IMeasurement measurement  = MakeMeasurement(meta.Q2, (double)data.Q2);
                measurements.Add(measurement);
            }

            {
                // Convert value from "Q3" field to measurement
                FieldMapping fieldMapping = fieldLookup["Q3"];
                IMeasurement measurement  = MakeMeasurement(meta.Q3, (double)data.Q3);
                measurements.Add(measurement);
            }

            {
                // Convert value from "Q4" field to measurement
                FieldMapping fieldMapping = fieldLookup["Q4"];
                IMeasurement measurement  = MakeMeasurement(meta.Q4, (double)data.Q4);
                measurements.Add(measurement);
            }

            {
                // Convert value from "Q5" field to measurement
                FieldMapping fieldMapping = fieldLookup["Q5"];
                IMeasurement measurement  = MakeMeasurement(meta.Q5, (double)data.Q5);
                measurements.Add(measurement);
            }

            {
                // Convert value from "Q6" field to measurement
                FieldMapping fieldMapping = fieldLookup["Q6"];
                IMeasurement measurement  = MakeMeasurement(meta.Q6, (double)data.Q6);
                measurements.Add(measurement);
            }
        }
Beispiel #16
0
        /// <summary>
        /// Accepts formulas
        /// </summary>
        private void acceptFormulas()
        {
            output.Clear();
            acc.Clear();

            foreach (char c in vars.Keys)
            {
                Variable v;
                output.Add(Variable.GetMeasure(c, this, out v));
                acc[c + ""] = v;
            }
            foreach (char c in parameters.Keys)
            {
                IMeasurement        m = parameters[c] as IMeasurement;
                VariableMeasurement v = c.Create(m, this);
                acc[c + ""] = v;
            }
            foreach (char c in aliases.Keys)
            {
                AliasNameVariable v = new AliasNameVariable(c, this);
                acc[c + ""] = v;
                object[] o = aliases[c] as object[];
            }
            IAlias         al = this;
            IList <string> l  = al.AliasNames;

            foreach (string n in l)
            {
                if (n.Length == 1)
                {
                }
            }
            IFormulaObjectCreator creator = VariableDetector.GetCreator(this);

            variables.Clear();
            foreach (char c in vars.Keys)
            {
                variables[c] = new object[4];
            }
            IList <string>           an = AliasNames;
            List <ObjectFormulaTree> tt = new List <ObjectFormulaTree>();
            string proh = "\u03B4";

            foreach (char c in parameters.Keys)
            {
                IMeasurement m = parameters[c];
                if (m.Type is IOneVariableFunction)
                {
                    proh += c;
                }
            }
            foreach (char c in vars.Keys)
            {
                object   t  = null;
                object[] os = vars[c] as object[];
                if (an.Contains(c + ""))
                {
                    t = GetType(c + "");
                }
                else
                {
                    t = os[2];
                }
                if (t is IOneVariableFunction)
                {
                    proh += c;
                }
            }
            foreach (char c in vars.Keys)
            {
                object[] os = vars[c] as object[];
                object   t  = null;
                if (an.Contains(c + ""))
                {
                    t = GetType(c + "");
                }
                else
                {
                    t = os[2];
                }
                object[]          ol   = variables[c] as object[];
                string            f    = os[1] as string;
                MathFormula       form = MathFormula.FromString(MathSymbolFactory.Sizes, f);
                ObjectFormulaTree tree = ObjectFormulaTree.CreateTree(form.FullTransform(proh), creator);
                if (!t.Equals(tree.ReturnType))
                {
                    throw new Exception("Illegal return type");
                }
                ol[1] = tree;
                tt.Add(tree);
            }
            trees = tt.ToArray();
        }
Beispiel #17
0
 internal void FindGases(DissolvedGasAnalysis dga)
 {
     FirstGas = (IMeasurement)dga.GetType().GetProperty(FirstGasEnum.ToString()).GetValue(dga);
     SecondGas = (IMeasurement)dga.GetType().GetProperty(SecondGasEnum.ToString()).GetValue(dga);
     ThirdGas = (IMeasurement)dga.GetType().GetProperty(ThirdGasEnum.ToString()).GetValue(dga);
 }
        /*public override double[,] RelativeMatrix
         * {
         *  get
         *  {
         *      return base.RelativeMatrix;
         *  }
         *  set
         *  {
         *      base.RelativeMatrix = value;
         *    /  for (int i = 0; i < 4; i++)
         *      {
         *          initialConditions[i + 6] = relativeQuaternion[i];
         *      }
         *  }
         * }*/

        #endregion

        #region IDifferentialEquationSolver Members

        void IDifferentialEquationSolver.CalculateDerivations()
        {
            //IReferenceFrame f = this;
            //ReferenceFrame frame = f.Own;
            SetAliases();
            IDataConsumer cons = this;
            int           i    = 0;

            cons.Reset();

            cons.UpdateChildrenData();

            //Filling of massive of forces and moments using results of calculations of formula trees
            for (i = 0; i < 12; i++)
            {
                forces[i] = (double)measures[i].Parameter();
            }

            //Filling the part, responding to derivation of radius-vector

            /*for (i = 0; i < 3; i++)
             * {
             *  result[i, 1] = result[3 + i, 0];
             * }*/

            int k = 0;

            for (i = 0; i < 3; i++)
            {
                for (int j = i; j < 3; j++)
                {
                    IMeasurement min = inertia[k];
                    ++k;
                    if (min != null)
                    {
                        double jin = (double)min.Parameter();
                        J[i, j] = jin;
                        J[j, i] = jin;
                    }
                }
            }
            IMeasurement mm = inertia[6];

            if (mm != null)
            {
                unMass = (double)mm.Parameter();
                unMass = 1 / unMass;
            }

            //Filling the part, responding to derivation of linear velocity
            for (i = 0; i < 3; i++)
            {
                linAccAbsolute[i] = forces[6 + i] * unMass;
            }
            double[,] T = Relative.Matrix;
            RealMatrix.Multiply(linAccAbsolute, T, aux);
            for (i = 0; i < 3; i++)
            {
                linAccAbsolute[i] = forces[i] * unMass + aux[i];
            }
            RealMatrix.Multiply(J, omega, aux);
            StaticExtensionVector3D.VectorPoduct(omega, aux, aux1);
            RealMatrix.Add(aux1, 0, forces, 9, aux, 0, 3);
            Array.Copy(forces, 3, aux1, 0, 3);
            RealMatrix.Multiply(aux1, T, aux2);
            RealMatrix.Add(aux2, 0, forces, 9, aux1, 0, 3);
            RealMatrix.Add(aux1, 0, aux, 0, aux2, 0, 3);
            RealMatrix.Multiply(L, aux2, epsRelative);
            aux4d[0] = 0;
            Array.Copy(omega, 0, aux4d, 1, 3);
            StaticExtensionVector3D.QuaternionInvertMultiply(relativeQuaternion, aux4d, quaternionDervation);
            for (i = 0; i < 3; i++)
            {
                quaternionDervation[i] *= 0.5;
            }
            SetRelative();
            Update();
        }
Beispiel #19
0
        /// <summary>
        /// Creates a new <see cref="CompactMeasurement"/> from an existing <see cref="IMeasurement"/> value.
        /// </summary>
        /// <param name="measurement">Source <see cref="IMeasurement"/> value.</param>
        /// <param name="signalIndexCache">Signal index cache used to serialize or deserialize runtime information.</param>
        /// <param name="includeTime">Set to <c>true</c> to include time in serialized packet; otherwise <c>false</c>.</param>
        /// <param name="baseTimeOffsets">Base time offset array - set to <c>null</c> to use full fidelity measurement time.</param>
        /// <param name="timeIndex">Time index to use for base offset.</param>
        /// <param name="useMillisecondResolution">Flag that determines if millisecond resolution is in use for this serialization.</param>
        public CompactMeasurement(IMeasurement measurement, SignalIndexCache signalIndexCache, bool includeTime, long[] baseTimeOffsets, int timeIndex, bool useMillisecondResolution)
        {
            ID = measurement.ID;
            Key = measurement.Key;
            Value = measurement.Value;
            Adder = measurement.Adder;
            Multiplier = measurement.Multiplier;
            Timestamp = measurement.Timestamp;
            StateFlags = measurement.StateFlags;

            m_signalIndexCache = signalIndexCache;
            m_includeTime = includeTime;

            // We keep a clone of the base time offsets, if provided, since array contents can change at any time
            if (baseTimeOffsets == null)
                m_baseTimeOffsets = s_emptyBaseTimeOffsets;
            else
                m_baseTimeOffsets = new long[] { baseTimeOffsets[0], baseTimeOffsets[1] };

            m_timeIndex = timeIndex;
            m_useMillisecondResolution = useMillisecondResolution;
        }
Beispiel #20
0
 // Indicates whether the given measurement is not greater
 // than the set point, offset by the hysteresis.
 private bool ClearIfNotGreaterThan(IMeasurement measurement)
 {
     return (measurement.Value <= m_setPoint - m_hysteresis);
 }
Beispiel #21
0
 public override void ApplyStreamBackgroundAsync(IDAQOutputStream s, IMeasurement background)
 {
     throw new NotImplementedException();
 }
Beispiel #22
0
 // Indicates whether the given measurement is not less
 // than the set point, offset by the hysteresis.
 private bool ClearIfNotLessThan(IMeasurement measurement)
 {
     return (measurement.Value >= m_setPoint + m_hysteresis);
 }
Beispiel #23
0
 public OutputData(IEnumerable <IMeasurement> data,
                   IMeasurement sampleRate) :
     this(data, sampleRate, true)
 {
 }
Beispiel #24
0
        // Indicates whether the given measurement's value has changed.
        private bool ClearIfNotFlatline(IMeasurement measurement)
        {
            if (measurement.Value != m_lastValue)
            {
                m_lastChanged = measurement.Timestamp;
                m_lastValue = measurement.Value;

                return true;
            }

            return false;
        }
Beispiel #25
0
 /// <summary>
 /// Sets the associated <see cref="MeasurementKey"/> for a <see cref="IMeasurement"/>.
 /// </summary>
 /// <param name="measurement"><see cref="IMeasurement"/> to create new <see cref="MeasurementMetadata"/> for.</param>
 /// <param name="key">New measurement key value to assign to measurement's metadata.</param>
 public static void SetKey(this IMeasurement measurement, MeasurementKey key)
 {
     measurement.Metadata = measurement.Metadata.ChangeKey(key);
 }
Beispiel #26
0
        // Keeps track of the signal's timestamps to determine whether a given
        // measurement is eligible to raise the alarm based on the delay.
        private bool CheckDelay(IMeasurement measurement, bool raiseCondition)
        {
            Ticks dist;

            if (!raiseCondition)
            {
                // Keep track of the last time
                // the signal failed the raise test
                m_lastNegative = measurement.Timestamp;
            }
            else
            {
                // Get the amount of time since the last
                // time the signal failed the raise test
                dist = measurement.Timestamp - m_lastNegative;

                // If the amount of time is larger than
                // the delay threshold, raise the alarm
                if (dist >= Ticks.FromSeconds(m_delay.GetValueOrDefault()))
                    return true;
            }

            return false;
        }
Beispiel #27
0
 /// <summary>
 /// Returns <c>true</c> if <see cref="MeasurementStateFlags.BadTime"/> is not set.
 /// </summary>
 /// <param name="measurement"><see cref="IMeasurement"/> instance to test.</param>
 /// <returns><c>true</c> if <see cref="MeasurementStateFlags.BadTime"/> is not set.</returns>
 public static bool TimestampQualityIsGood(this IMeasurement measurement)
 {
     return((measurement.StateFlags & MeasurementStateFlags.BadTime) == 0);
 }
Beispiel #28
0
        /// <summary>
        /// Queues a collection of measurements for processing.
        /// </summary>
        /// <param name="measurements">Collection of measurements to queue for processing.</param>
        /// <remarks>
        /// Measurements are filtered against the defined <see cref="InputMeasurementKeys"/> so we override method
        /// so that dynamic updates to keys will be synchronized with filtering to prevent interference.
        /// </remarks>
        public override void QueueMeasurementsForProcessing(IEnumerable <IMeasurement> measurements)
        {
            if ((object)measurements == null)
            {
                return;
            }

            if (!m_startTimeSent && measurements.Any())
            {
                m_startTimeSent = true;

                IMeasurement measurement = measurements.FirstOrDefault(m => (object)m != null);
                Ticks        timestamp   = 0;

                if ((object)measurement != null)
                {
                    timestamp = measurement.Timestamp;
                }

                m_parent.SendDataStartTime(m_clientID, timestamp);
            }

            if (m_isNaNFiltered)
            {
                measurements = measurements.Where(measurement => !double.IsNaN(measurement.Value));
            }

            if (!measurements.Any() || !Enabled)
            {
                return;
            }

            if (TrackLatestMeasurements)
            {
                double publishInterval;

                // Keep track of latest measurements
                base.QueueMeasurementsForProcessing(measurements);
                publishInterval = (m_publishInterval > 0) ? m_publishInterval : LagTime;

                if (DateTime.UtcNow.Ticks > m_lastPublishTime + Ticks.FromSeconds(publishInterval))
                {
                    List <IMeasurement> currentMeasurements = new List <IMeasurement>();
                    Measurement         newMeasurement;

                    // Create a new set of measurements that represent the latest known values setting value to NaN if it is old
                    foreach (TemporalMeasurement measurement in LatestMeasurements)
                    {
                        newMeasurement = new Measurement
                        {
                            Key        = measurement.Key,
                            Value      = measurement.GetValue(RealTime),
                            Adder      = measurement.Adder,
                            Multiplier = measurement.Multiplier,
                            Timestamp  = measurement.Timestamp,
                            StateFlags = measurement.StateFlags
                        };

                        currentMeasurements.Add(newMeasurement);
                    }

                    // Order measurements by signal type for better compression when enabled
                    if (m_usePayloadCompression)
                    {
                        ProcessMeasurements(currentMeasurements.OrderBy(measurement => measurement.GetSignalType(DataSource)));
                    }
                    else
                    {
                        ProcessMeasurements(currentMeasurements);
                    }
                }
            }
            else
            {
                // Order measurements by signal type for better compression when enabled
                if (m_usePayloadCompression)
                {
                    ProcessMeasurements(measurements.OrderBy(measurement => measurement.GetSignalType(DataSource)));
                }
                else
                {
                    ProcessMeasurements(measurements);
                }
            }
        }
 public override void ApplyStreamBackgroundAsync(IDAQOutputStream s, IMeasurement background)
 {
 }
Beispiel #30
0
        private void CollectFromLSEEstimatorOutput(List <IMeasurement> measurements, TypeMapping typeMapping, openLSE.Model.LSE.EstimatorOutput data, openLSE.Model.LSE._EstimatorOutputMeta meta)
        {
            Dictionary <string, FieldMapping> fieldLookup = typeMapping.FieldMappings.ToDictionary(mapping => mapping.Field.Identifier);

            {
                // Convert values from array in "CircuitBreakerStatuses" field to measurements
                ArrayMapping arrayMapping = (ArrayMapping)fieldLookup["CircuitBreakerStatuses"];
                int          dataLength   = data.CircuitBreakerStatuses.Length;
                int          metaLength   = meta.CircuitBreakerStatuses.Length;

                if (dataLength != metaLength)
                {
                    throw new InvalidOperationException($"Values array length ({dataLength}) and MetaValues array length ({metaLength}) for field \"CircuitBreakerStatuses\" must be the same.");
                }

                for (int i = 0; i < dataLength; i++)
                {
                    IMeasurement measurement = MakeMeasurement(meta.CircuitBreakerStatuses[i], (double)data.CircuitBreakerStatuses[i]);
                    measurements.Add(measurement);
                }
            }

            {
                // Convert values from array in "TopologyProfilingData" field to measurements
                ArrayMapping arrayMapping = (ArrayMapping)fieldLookup["TopologyProfilingData"];
                int          dataLength   = data.TopologyProfilingData.Length;
                int          metaLength   = meta.TopologyProfilingData.Length;

                if (dataLength != metaLength)
                {
                    throw new InvalidOperationException($"Values array length ({dataLength}) and MetaValues array length ({metaLength}) for field \"TopologyProfilingData\" must be the same.");
                }

                for (int i = 0; i < dataLength; i++)
                {
                    IMeasurement measurement = MakeMeasurement(meta.TopologyProfilingData[i], (double)data.TopologyProfilingData[i]);
                    measurements.Add(measurement);
                }
            }

            {
                // Convert values from array in "MeasurementValidationFlags" field to measurements
                ArrayMapping arrayMapping = (ArrayMapping)fieldLookup["MeasurementValidationFlags"];
                int          dataLength   = data.MeasurementValidationFlags.Length;
                int          metaLength   = meta.MeasurementValidationFlags.Length;

                if (dataLength != metaLength)
                {
                    throw new InvalidOperationException($"Values array length ({dataLength}) and MetaValues array length ({metaLength}) for field \"MeasurementValidationFlags\" must be the same.");
                }

                for (int i = 0; i < dataLength; i++)
                {
                    IMeasurement measurement = MakeMeasurement(meta.MeasurementValidationFlags[i], (double)data.MeasurementValidationFlags[i]);
                    measurements.Add(measurement);
                }
            }

            {
                // Convert values from array in "VoltageMagnitudeEstimates" field to measurements
                ArrayMapping arrayMapping = (ArrayMapping)fieldLookup["VoltageMagnitudeEstimates"];
                int          dataLength   = data.VoltageMagnitudeEstimates.Length;
                int          metaLength   = meta.VoltageMagnitudeEstimates.Length;

                if (dataLength != metaLength)
                {
                    throw new InvalidOperationException($"Values array length ({dataLength}) and MetaValues array length ({metaLength}) for field \"VoltageMagnitudeEstimates\" must be the same.");
                }

                for (int i = 0; i < dataLength; i++)
                {
                    IMeasurement measurement = MakeMeasurement(meta.VoltageMagnitudeEstimates[i], (double)data.VoltageMagnitudeEstimates[i]);
                    measurements.Add(measurement);
                }
            }

            {
                // Convert values from array in "VoltageAngleEstimates" field to measurements
                ArrayMapping arrayMapping = (ArrayMapping)fieldLookup["VoltageAngleEstimates"];
                int          dataLength   = data.VoltageAngleEstimates.Length;
                int          metaLength   = meta.VoltageAngleEstimates.Length;

                if (dataLength != metaLength)
                {
                    throw new InvalidOperationException($"Values array length ({dataLength}) and MetaValues array length ({metaLength}) for field \"VoltageAngleEstimates\" must be the same.");
                }

                for (int i = 0; i < dataLength; i++)
                {
                    IMeasurement measurement = MakeMeasurement(meta.VoltageAngleEstimates[i], (double)data.VoltageAngleEstimates[i]);
                    measurements.Add(measurement);
                }
            }

            {
                // Convert values from array in "VoltageMagnitudeResiduals" field to measurements
                ArrayMapping arrayMapping = (ArrayMapping)fieldLookup["VoltageMagnitudeResiduals"];
                int          dataLength   = data.VoltageMagnitudeResiduals.Length;
                int          metaLength   = meta.VoltageMagnitudeResiduals.Length;

                if (dataLength != metaLength)
                {
                    throw new InvalidOperationException($"Values array length ({dataLength}) and MetaValues array length ({metaLength}) for field \"VoltageMagnitudeResiduals\" must be the same.");
                }

                for (int i = 0; i < dataLength; i++)
                {
                    IMeasurement measurement = MakeMeasurement(meta.VoltageMagnitudeResiduals[i], (double)data.VoltageMagnitudeResiduals[i]);
                    measurements.Add(measurement);
                }
            }

            {
                // Convert values from array in "VoltageAngleResiduals" field to measurements
                ArrayMapping arrayMapping = (ArrayMapping)fieldLookup["VoltageAngleResiduals"];
                int          dataLength   = data.VoltageAngleResiduals.Length;
                int          metaLength   = meta.VoltageAngleResiduals.Length;

                if (dataLength != metaLength)
                {
                    throw new InvalidOperationException($"Values array length ({dataLength}) and MetaValues array length ({metaLength}) for field \"VoltageAngleResiduals\" must be the same.");
                }

                for (int i = 0; i < dataLength; i++)
                {
                    IMeasurement measurement = MakeMeasurement(meta.VoltageAngleResiduals[i], (double)data.VoltageAngleResiduals[i]);
                    measurements.Add(measurement);
                }
            }

            {
                // Convert values from array in "CurrentFlowMagnitudeEstimates" field to measurements
                ArrayMapping arrayMapping = (ArrayMapping)fieldLookup["CurrentFlowMagnitudeEstimates"];
                int          dataLength   = data.CurrentFlowMagnitudeEstimates.Length;
                int          metaLength   = meta.CurrentFlowMagnitudeEstimates.Length;

                if (dataLength != metaLength)
                {
                    throw new InvalidOperationException($"Values array length ({dataLength}) and MetaValues array length ({metaLength}) for field \"CurrentFlowMagnitudeEstimates\" must be the same.");
                }

                for (int i = 0; i < dataLength; i++)
                {
                    IMeasurement measurement = MakeMeasurement(meta.CurrentFlowMagnitudeEstimates[i], (double)data.CurrentFlowMagnitudeEstimates[i]);
                    measurements.Add(measurement);
                }
            }

            {
                // Convert values from array in "CurrentFlowAngleEstimates" field to measurements
                ArrayMapping arrayMapping = (ArrayMapping)fieldLookup["CurrentFlowAngleEstimates"];
                int          dataLength   = data.CurrentFlowAngleEstimates.Length;
                int          metaLength   = meta.CurrentFlowAngleEstimates.Length;

                if (dataLength != metaLength)
                {
                    throw new InvalidOperationException($"Values array length ({dataLength}) and MetaValues array length ({metaLength}) for field \"CurrentFlowAngleEstimates\" must be the same.");
                }

                for (int i = 0; i < dataLength; i++)
                {
                    IMeasurement measurement = MakeMeasurement(meta.CurrentFlowAngleEstimates[i], (double)data.CurrentFlowAngleEstimates[i]);
                    measurements.Add(measurement);
                }
            }

            {
                // Convert values from array in "CurrentFlowMagnitudeResiduals" field to measurements
                ArrayMapping arrayMapping = (ArrayMapping)fieldLookup["CurrentFlowMagnitudeResiduals"];
                int          dataLength   = data.CurrentFlowMagnitudeResiduals.Length;
                int          metaLength   = meta.CurrentFlowMagnitudeResiduals.Length;

                if (dataLength != metaLength)
                {
                    throw new InvalidOperationException($"Values array length ({dataLength}) and MetaValues array length ({metaLength}) for field \"CurrentFlowMagnitudeResiduals\" must be the same.");
                }

                for (int i = 0; i < dataLength; i++)
                {
                    IMeasurement measurement = MakeMeasurement(meta.CurrentFlowMagnitudeResiduals[i], (double)data.CurrentFlowMagnitudeResiduals[i]);
                    measurements.Add(measurement);
                }
            }

            {
                // Convert values from array in "CurrentFlowAngleResiduals" field to measurements
                ArrayMapping arrayMapping = (ArrayMapping)fieldLookup["CurrentFlowAngleResiduals"];
                int          dataLength   = data.CurrentFlowAngleResiduals.Length;
                int          metaLength   = meta.CurrentFlowAngleResiduals.Length;

                if (dataLength != metaLength)
                {
                    throw new InvalidOperationException($"Values array length ({dataLength}) and MetaValues array length ({metaLength}) for field \"CurrentFlowAngleResiduals\" must be the same.");
                }

                for (int i = 0; i < dataLength; i++)
                {
                    IMeasurement measurement = MakeMeasurement(meta.CurrentFlowAngleResiduals[i], (double)data.CurrentFlowAngleResiduals[i]);
                    measurements.Add(measurement);
                }
            }

            {
                // Convert values from openLSE.Model.LSE.PerformanceMetrics UDT for "PerformanceMetrics" field to measurements
                FieldMapping fieldMapping  = fieldLookup["PerformanceMetrics"];
                TypeMapping  nestedMapping = GetTypeMapping(fieldMapping);
                CollectFromLSEPerformanceMetrics(measurements, nestedMapping, data.PerformanceMetrics, meta.PerformanceMetrics);
            }
        }
Beispiel #31
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="name">Mapping name</param>
 /// <param name="measure">Measure</param>
 public MappingMeasure(string name, IMeasurement measure)
 {
     this.name    = name;
     this.measure = measure;
 }
Beispiel #32
0
        private void CollectFromLSEPerformanceMetrics(List <IMeasurement> measurements, TypeMapping typeMapping, openLSE.Model.LSE.PerformanceMetrics data, openLSE.Model.LSE._PerformanceMetricsMeta meta)
        {
            Dictionary <string, FieldMapping> fieldLookup = typeMapping.FieldMappings.ToDictionary(mapping => mapping.Field.Identifier);

            {
                // Convert value from "ActiveVoltagesCount" field to measurement
                FieldMapping fieldMapping = fieldLookup["ActiveVoltagesCount"];
                IMeasurement measurement  = MakeMeasurement(meta.ActiveVoltagesCount, (double)data.ActiveVoltagesCount);
                measurements.Add(measurement);
            }

            {
                // Convert value from "ActiveCurrentFlowsCount" field to measurement
                FieldMapping fieldMapping = fieldLookup["ActiveCurrentFlowsCount"];
                IMeasurement measurement  = MakeMeasurement(meta.ActiveCurrentFlowsCount, (double)data.ActiveCurrentFlowsCount);
                measurements.Add(measurement);
            }

            {
                // Convert value from "ActiveCurrentInjectionsCount" field to measurement
                FieldMapping fieldMapping = fieldLookup["ActiveCurrentInjectionsCount"];
                IMeasurement measurement  = MakeMeasurement(meta.ActiveCurrentInjectionsCount, (double)data.ActiveCurrentInjectionsCount);
                measurements.Add(measurement);
            }

            {
                // Convert value from "RefreshTime" field to measurement
                FieldMapping fieldMapping = fieldLookup["RefreshTime"];
                IMeasurement measurement  = MakeMeasurement(meta.RefreshTime, (double)data.RefreshTime);
                measurements.Add(measurement);
            }

            {
                // Convert value from "ParsingTime" field to measurement
                FieldMapping fieldMapping = fieldLookup["ParsingTime"];
                IMeasurement measurement  = MakeMeasurement(meta.ParsingTime, (double)data.ParsingTime);
                measurements.Add(measurement);
            }

            {
                // Convert value from "MeasurementMappingTime" field to measurement
                FieldMapping fieldMapping = fieldLookup["MeasurementMappingTime"];
                IMeasurement measurement  = MakeMeasurement(meta.MeasurementMappingTime, (double)data.MeasurementMappingTime);
                measurements.Add(measurement);
            }

            {
                // Convert value from "ActiveCurrentDeterminationTime" field to measurement
                FieldMapping fieldMapping = fieldLookup["ActiveCurrentDeterminationTime"];
                IMeasurement measurement  = MakeMeasurement(meta.ActiveCurrentDeterminationTime, (double)data.ActiveCurrentDeterminationTime);
                measurements.Add(measurement);
            }

            {
                // Convert value from "ObservabilityAnalysisTime" field to measurement
                FieldMapping fieldMapping = fieldLookup["ObservabilityAnalysisTime"];
                IMeasurement measurement  = MakeMeasurement(meta.ObservabilityAnalysisTime, (double)data.ObservabilityAnalysisTime);
                measurements.Add(measurement);
            }

            {
                // Convert value from "StateComputationTime" field to measurement
                FieldMapping fieldMapping = fieldLookup["StateComputationTime"];
                IMeasurement measurement  = MakeMeasurement(meta.StateComputationTime, (double)data.StateComputationTime);
                measurements.Add(measurement);
            }

            {
                // Convert value from "ObservedBusCount" field to measurement
                FieldMapping fieldMapping = fieldLookup["ObservedBusCount"];
                IMeasurement measurement  = MakeMeasurement(meta.ObservedBusCount, (double)data.ObservedBusCount);
                measurements.Add(measurement);
            }

            {
                // Convert value from "OutputPreparationTime" field to measurement
                FieldMapping fieldMapping = fieldLookup["OutputPreparationTime"];
                IMeasurement measurement  = MakeMeasurement(meta.OutputPreparationTime, (double)data.OutputPreparationTime);
                measurements.Add(measurement);
            }

            {
                // Convert value from "TotalTimeInMilliseconds" field to measurement
                FieldMapping fieldMapping = fieldLookup["TotalTimeInMilliseconds"];
                IMeasurement measurement  = MakeMeasurement(meta.TotalTimeInMilliseconds, (double)data.TotalTimeInMilliseconds);
                measurements.Add(measurement);
            }

            {
                // Convert value from "TotalTimeInTicks" field to measurement
                FieldMapping fieldMapping = fieldLookup["TotalTimeInTicks"];
                IMeasurement measurement  = MakeMeasurement(meta.TotalTimeInTicks, (double)data.TotalTimeInTicks);
                measurements.Add(measurement);
            }
        }
 public TemperatureSensor(IMeasurement measurement) : base(measurement)
 {
 }
Beispiel #34
0
        // Handles the dump timer's Tick event.
        private void DumpTimer_Tick(object sender, EventArgs e)
        {
            byte[] buffer = BufferPool.TakeBuffer(65536);

            try
            {
                List<IMeasurement[]> dumpMeasurements = new List<IMeasurement[]>();
                IMeasurement dequeuedMeasurement;
                int count = 0;

                // Remove all the measurements from the buffer and place them in the list of samples.
                while (m_buffer.Count > m_numChannels)
                {
                    IMeasurement[] sample = new IMeasurement[m_numChannels];

                    for (int i = 0; i < m_numChannels; i++)
                    {
                        Guid id;
                        int index;

                        m_buffer.TryDequeue(out dequeuedMeasurement);
                        id = dequeuedMeasurement.ID;
                        index = m_channelIndexes[id];
                        sample[index] = dequeuedMeasurement;
                    }

                    dumpMeasurements.Add(sample);
                }

                foreach (IMeasurement[] sample in dumpMeasurements)
                {
                    // Put the sample in the buffer.
                    for (int i = 0; i < m_numChannels; i++)
                    {
                        byte[] channelValue;

                        // Assuming 16-bit integer samples for WAV files
                        if (sample[i] != null)
                            channelValue = LittleEndian.GetBytes((short)sample[i].Value);
                        else
                            channelValue = new byte[2];

                        Buffer.BlockCopy(channelValue, 0, buffer, count, 2);
                        count += 2;
                    }

                    // If the buffer is full, send it to the
                    // sound card and start a new buffer.
                    if (count + (m_numChannels * 2) > buffer.Length)
                    {
                        m_waveProvider.AddSamples(buffer, 0, count);
                        count = 0;
                    }

                    // Notify the user interface of new samples.
                    if (OnSample != null)
                    {
                        const float volume = 0.000035F;
                        float left = (sample[0] != null) ? (float)sample[0].Value : 0.0F;
                        float right = m_numChannels > 1 ? ((sample[1] != null) ? (float)sample[1].Value : 0.0F) : left;
                        OnSample(this, new SampleEventArgs(left * volume, right * volume));
                    }
                }

                // Send remaining samples to the sound card.
                if (count > 0)
                    m_waveProvider.AddSamples(buffer, 0, count);

                // If the buffer was empty, we're missing a full quarter second of data!
                // Go back to buffering, stop the dump timer, and start the timeout timer.
                //if (dumpMeasurements.Count == 0 && m_dumpTimer != null)
                //{
                //    OnStateChanged(PlaybackState.Buffering);
                //    m_dumpTimer.Stop();
                //    m_timeoutTimer.Start();
                //}
            }
            finally
            {
                if ((object)buffer != null)
                    BufferPool.ReturnBuffer(buffer);
            }
        }
Beispiel #35
0
 internal void CalculatePercentages(IMeasurement firstGas, IMeasurement secondGas, IMeasurement thirdGas)
 {
     TotalGases = firstGas.Value + secondGas.Value + thirdGas.Value;
     FirstPercentage = (firstGas.Value * 100.0) / TotalGases;
     SecondPercentage = (secondGas.Value * 100.0) / TotalGases;
     ThirdPercentage = (thirdGas.Value * 100.0) / TotalGases;
 }
Beispiel #36
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PacketType1"/> class.
 /// </summary>
 /// <param name="measurement">Object that implements the <see cref="IMeasurement"/> interface.</param>
 public PacketType1(IMeasurement measurement)
     : this()
 {
     HistorianID = (int)measurement.Key.ID;
     Time = new TimeTag((DateTime)measurement.Timestamp);
     Value = (float)measurement.AdjustedValue;
     Quality = measurement.HistorianQuality();
 }
Beispiel #37
0
 public CompactMeasurement(IMeasurement measurement, SignalIndexCache signalIndexCache)
     : this(measurement, signalIndexCache, true, null, 0 , false)
 {
     
 }
Beispiel #38
0
 /// <summary>
 /// Serializes measurements to data output stream.
 /// </summary>
 protected override void ProcessMeasurements(IMeasurement[] measurements)
 {
 }
        public void GivenDifferentNamedValues_WhenAddMeasurement_ThenGetValuesReturnsSorted_Test()
        {
            var startDate = new DateTime(2019, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            var endDate   = startDate.AddDays(1);

            var measurement = new IMeasurement[]
            {
                new Measurement
                {
                    OccurrenceTimeUtc = startDate,
                    Properties        = new List <MeasurementProperty>
                    {
                        new MeasurementProperty {
                            Name = "a", Value = "1"
                        },
                    },
                },
                new Measurement
                {
                    OccurrenceTimeUtc = endDate,
                    Properties        = new List <MeasurementProperty>
                    {
                        new MeasurementProperty {
                            Name = "a", Value = "2"
                        },
                    },
                },
                new Measurement
                {
                    OccurrenceTimeUtc = startDate.AddHours(1),
                    Properties        = new List <MeasurementProperty>
                    {
                        new MeasurementProperty {
                            Name = "a", Value = "3"
                        },
                    },
                },
                new Measurement
                {
                    OccurrenceTimeUtc = endDate,
                    Properties        = new List <MeasurementProperty>
                    {
                        new MeasurementProperty {
                            Name = "b", Value = "1"
                        },
                    },
                },
                new Measurement
                {
                    OccurrenceTimeUtc = startDate,
                    Properties        = new List <MeasurementProperty>
                    {
                        new MeasurementProperty {
                            Name = "b", Value = "2"
                        },
                    },
                },
                new Measurement
                {
                    OccurrenceTimeUtc = startDate,
                    Properties        = new List <MeasurementProperty>
                    {
                        new MeasurementProperty {
                            Name = "c", Value = "3"
                        },
                    },
                },
            };

            var og = new TimePeriodMeasurementObservationGroup((startDate, endDate));

            foreach (var m in measurement)
            {
                og.AddMeasurement(m);
            }

            var values = og.GetValues();

            var aValues = values["a"];

            Assert.Collection(
                aValues,
                v =>
            {
                Assert.Equal(startDate, v.Time);
                Assert.Equal("1", v.Value);
            },
                v =>
            {
                Assert.Equal(measurement[2].OccurrenceTimeUtc, v.Time);
                Assert.Equal("3", v.Value);
            },
                v =>
            {
                Assert.Equal(endDate, v.Time);
                Assert.Equal("2", v.Value);
            });

            var bValues = values["b"];

            Assert.Collection(
                bValues,
                v =>
            {
                Assert.Equal(startDate, v.Time);
                Assert.Equal("2", v.Value);
            },
                v =>
            {
                Assert.Equal(endDate, v.Time);
                Assert.Equal("1", v.Value);
            });

            var cValues = values["c"];

            Assert.Collection(
                cValues,
                v =>
            {
                Assert.Equal(startDate, v.Time);
                Assert.Equal("3", v.Value);
            });
        }
 public Volume(IMeasurement <Distance> length, IMeasurement <Area> area)
     : base(length, area, Provider)
 {
 }
Beispiel #41
0
        private void m_unsynchronizedSubscriber_NewMeasurements(object sender, EventArgs <ICollection <IMeasurement> > e)
        {
            if (0 == Interlocked.Exchange(ref m_processingUnsynchronizedMeasurements, 1))
            {
                try
                {
                    foreach (IMeasurement newMeasurement in e.Argument)
                    {
                        StatisticMeasurement measurement;

                        if (RealTimeStatistic.StatisticMeasurements.TryGetValue(newMeasurement.ID, out measurement))
                        {
                            if (!string.IsNullOrEmpty(measurement.DisplayFormat) && !string.IsNullOrEmpty(measurement.DataType))
                            {
                                measurement.Quality = newMeasurement.ValueQualityIsGood() ? "GOOD" : "BAD";
                                measurement.Value   = string.Format(measurement.DisplayFormat, ConvertValueToType(newMeasurement.AdjustedValue.ToString(), measurement.DataType));
                                measurement.TimeTag = newMeasurement.Timestamp.ToString("HH:mm:ss.fff");

                                StreamStatistic streamStatistic;
                                if (measurement.ConnectedState) //if measurement defines connection state.
                                {
                                    if ((measurement.Source == "System" && RealTimeStatistic.SystemStatistics.TryGetValue(measurement.DeviceID, out streamStatistic)) ||
                                        (measurement.Source == "InputStream" && RealTimeStatistic.InputStreamStatistics.TryGetValue(measurement.DeviceID, out streamStatistic)) ||
                                        (measurement.Source == "OutputStream" && RealTimeStatistic.OutputStreamStatistics.TryGetValue(measurement.DeviceID, out streamStatistic)) ||
                                        (measurement.Source == "Publisher" && RealTimeStatistic.DataPublisherStatistics.TryGetValue(measurement.DeviceID, out streamStatistic)) ||
                                        (measurement.Source == "Subscriber" && RealTimeStatistic.InputStreamStatistics.TryGetValue(measurement.DeviceID, out streamStatistic)))
                                    {
                                        if (Convert.ToBoolean(newMeasurement.AdjustedValue))
                                        {
                                            streamStatistic.StatusColor = "Green";
                                        }
                                        else
                                        {
                                            streamStatistic.StatusColor = "Red";
                                        }

                                        // We do extra validation on the input stream since devices can be technically connected and not receiving data (e.g., UDP)
                                        if (measurement.Source == "InputStream")
                                        {
                                            StatisticMeasurement totalFramesStat = RealTimeStatistic.StatisticMeasurements.Values.FirstOrDefault(stat => string.Compare(stat.SignalReference.ToNonNullString().Trim(), string.Format("{0}!IS-ST1", streamStatistic.Acronym.ToNonNullString().Trim()), true) == 0);

                                            if ((object)totalFramesStat != null)
                                            {
                                                IMeasurement totalFramesStatMeasurement = e.Argument.FirstOrDefault(m => m.ID == totalFramesStat.SignalID);

                                                if ((object)totalFramesStatMeasurement != null && totalFramesStatMeasurement.AdjustedValue <= 0.0D)
                                                {
                                                    streamStatistic.StatusColor = "Red";
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    LastRefresh = "Last Refresh: " + DateTime.UtcNow.ToString("HH:mm:ss.fff");

                    if ((object)NewMeasurements != null)
                    {
                        NewMeasurements(this, e);
                    }
                }
                finally
                {
                    Interlocked.Exchange(ref m_processingUnsynchronizedMeasurements, 0);
                }
            }
        }
 public Volume(IMeasurement <Distance> dist1, IMeasurement <Distance> dist2, IMeasurement <Distance> dist3)
     : this(dist1, dist2.Multiply(dist3))
 {
 }
Beispiel #43
0
 /// <summary>
 /// Queues a single measurement for processing. Measurement is automatically filtered to the defined <see cref="IAdapter.InputMeasurementKeys"/>.
 /// </summary>
 /// <param name="measurement">Measurement to queue for processing.</param>
 public virtual void QueueMeasurementForProcessing(IMeasurement measurement)
 {
     QueueMeasurementsForProcessing(new IMeasurement[] { measurement });
 }
Beispiel #44
0
 /// <summary>Returns True if the value of this measurement equals the value of the specified other measurement</summary>
 public bool Equals(IMeasurement other)
 {
     return (CompareTo(other) == 0);
 }
Beispiel #45
0
 /// <summary>
 /// Serializes measurements to data output stream.
 /// </summary>
 /// <remarks>
 /// <para>
 /// Derived classes must implement this function to process queued measurements.
 /// For example, this function would "archive" measurements if output adapter is for a historian.
 /// </para>
 /// <para>
 /// It is important that consumers "resume" connection cycle if processing fails (e.g., connection
 /// to archive is lost). Here is an example:
 /// <example>
 /// <code>
 /// protected virtual void ProcessMeasurements(IMeasurement[] measurements)
 /// {
 ///     try
 ///     {
 ///         // Process measurements...
 ///         foreach (IMeasurement measurement in measurement)
 ///         {
 ///             ArchiveMeasurement(measurement);
 ///         }
 ///     }
 ///     catch (Exception)
 ///     {                
 ///         // So long as user hasn't requested to stop, restart connection cycle
 ///         if (Enabled)
 ///             Start();
 ///     }
 /// }
 /// </code>
 /// </example>
 /// </para>
 /// </remarks>
 protected abstract void ProcessMeasurements(IMeasurement[] measurements);
Beispiel #46
0
 /// <summary>This implementation of a basic measurement compares itself by value</summary>
 public int CompareTo(IMeasurement other)
 {
     return m_value.CompareTo(other.Value);
 }
        private void PublishFrames()
        {
            while (m_nextPublicationTimeWithLatency - DateTime.UtcNow.Ticks < 1 * TimeSpan.TicksPerMillisecond)
            {
                if (!Enabled)
                    return;

                IMeasurement[] outputMeasurements = OutputMeasurements;
                IMeasurement[] newMeasurements = new IMeasurement[outputMeasurements.Length];
                for (int x = 0; x < outputMeasurements.Length; x++)
                {
                    newMeasurements[x] = Measurement.Clone(outputMeasurements[x], m_random.NextDouble(), m_nextPublicationTime);
                }
                OnNewMeasurements(newMeasurements);

                m_nextPublicationTime = GetNextPublicationTime(m_nextPublicationTime);
                m_nextPublicationTimeWithLatency = m_nextPublicationTime + (long)(m_latency.Next() * TimeSpan.TicksPerMillisecond);

                m_unprocessedMeasurements = (int)((DateTime.UtcNow.Ticks - m_nextPublicationTime) / (Ticks.PerSecond / m_publishRate));

            }

            if (!Enabled)
                return;

            long delay = ((m_nextPublicationTimeWithLatency - DateTime.UtcNow.Ticks) / TimeSpan.TicksPerMillisecond);

            if (delay < 1)
                m_timer.Start();
            else if (delay > 10000)
                m_timer.Start(10000);
            else
                m_timer.Start((int)delay);

        }
Beispiel #48
0
 /// <summary>Creates a copy of the specified measurement</summary>
 public static Measurement Clone(IMeasurement measurementToClone)
 {
     return new Measurement(measurementToClone.ID, measurementToClone.Source, measurementToClone.Value, measurementToClone.Adder, measurementToClone.Multiplier, measurementToClone.Ticks);
 }
Beispiel #49
0
 /// <summary>
 /// Sets the tag name for a <see cref="IMeasurement"/>.
 /// </summary>
 /// <param name="measurement"><see cref="IMeasurement"/> to create new <see cref="MeasurementMetadata"/> for.</param>
 /// <param name="tagName">New tag name value to assign to measurement's metadata.</param>
 public static void SetTagName(this IMeasurement measurement, string tagName)
 {
     measurement.Metadata = measurement.Metadata.ChangeTagName(tagName);
 }
Beispiel #50
0
 /// <summary>Creates a copy of the specified measurement using a new value and timestamp</summary>
 public static Measurement Clone(IMeasurement measurementToClone, double value, long ticks)
 {
     return new Measurement(measurementToClone.ID, measurementToClone.Source, value, measurementToClone.Adder, measurementToClone.Multiplier, ticks);
 }
Beispiel #51
0
 /// <summary>
 /// Sets the adder (i.e., "b" of y = mx + b) for a <see cref="IMeasurement"/>.
 /// </summary>
 /// <param name="measurement"><see cref="IMeasurement"/> to create new <see cref="MeasurementMetadata"/> for.</param>
 /// <param name="adder">New adder value to assign to measurement's metadata.</param>
 public static void SetAdder(this IMeasurement measurement, double adder)
 {
     measurement.Metadata = measurement.Metadata.ChangeAdder(adder);
 }
Beispiel #52
0
        public static string ToString(IMeasurement measurement)
        {
            if (measurement == null)
            {
                return "Undefined";
            }
            else
            {
                string tagName = measurement.TagName;
                string keyText = measurement.Key.ToString();

                if (string.IsNullOrEmpty(tagName))
                    return keyText;
                else
                    return string.Format("{0} [{1}]", tagName, keyText);
            }
        }
Beispiel #53
0
 /// <summary>
 /// Returns <c>true</c> if <see cref="MeasurementStateFlags.BadData"/> is not set.
 /// </summary>
 /// <param name="measurement"><see cref="IMeasurement"/> instance to test.</param>
 /// <returns><c>true</c> if <see cref="MeasurementStateFlags.BadData"/> is not set.</returns>
 public static bool ValueQualityIsGood(this IMeasurement measurement)
 {
     return((measurement.StateFlags & MeasurementStateFlags.BadData) == 0);
 }
Beispiel #54
0
 /// <summary>
 /// Gets a <see cref="Quality"/> value from a <see cref="IMeasurement"/> value.
 /// </summary>
 /// <param name="measurement"><see cref="IMeasurement"/> value to interpret.</param>
 /// <returns><see cref="Quality"/> value from a <see cref="IMeasurement"/> value.</returns>
 public static Quality HistorianQuality(this IMeasurement measurement)
 {
     return(measurement.IsDiscarded() ? Quality.DeletedFromProcessing : (measurement.ValueQualityIsGood() ? (measurement.TimestampQualityIsGood() ? Quality.Good : Quality.Old) : Quality.SuspectData));
 }
Beispiel #55
0
 /// <summary>
 /// Returns <c>true</c> if <see cref="MeasurementStateFlags.DiscardedValue"/> is set.
 /// </summary>
 /// <param name="measurement"><see cref="IMeasurement"/> instance to test.</param>
 /// <returns><c>true</c> if <see cref="MeasurementStateFlags.DiscardedValue"/> is not set.</returns>
 public static bool IsDiscarded(this IMeasurement measurement)
 {
     return((measurement.StateFlags & MeasurementStateFlags.DiscardedValue) > 0);
 }
Beispiel #56
0
 protected override IMeasurement ConvertOutput(IMeasurement deviceOutput)
 {
     return(ConvertOutput(deviceOutput, CurrentDeviceOutputParameters.Data));
 }
Beispiel #57
0
 /// <summary>
 /// Returns the measurement ID if defined, otherwise the run-time signal ID associated with the measurement key.
 /// </summary>
 /// <param name="measurement"><see cref="IMeasurement"/> instance to test.</param>
 /// <returns>Measurement ID if defined, otherwise the run-time signal ID associated with the measurement key.</returns>
 public static Guid RuntimeSignalID(this IMeasurement measurement)
 {
     return(measurement.ID);
 }
Beispiel #58
0
 public IMeasurement ConvertOutput(IMeasurement sample, DateTimeOffset time)
 {
     return(ConvertOutput(sample, DeviceParametersForOutput(time.ToUniversalTime()).Data));
 }
Beispiel #59
0
        /// <summary>
        /// Archives <paramref name="measurements"/> locally.
        /// </summary>
        /// <param name="measurements">Measurements to be archived.</param>
        protected override void ProcessMeasurements(IMeasurement[] measurements)
        {
            if ((object)measurements != null)
            {
                StringBuilder builder = new StringBuilder();

                foreach (IMeasurement measurement in measurements)
                {
                    builder.Append(measurement.ID);
                    builder.Append(',');
                    builder.Append(measurement.Key);
                    builder.Append(',');
                    builder.Append((long)measurement.Timestamp);
                    builder.Append(',');
                    builder.Append(measurement.AdjustedValue);
                    builder.Append(System.Environment.NewLine);
                }

                m_outStream.Write(builder.ToString());
                m_measurementCount += measurements.Length;
            }           
        }
Beispiel #60
0
 /// <summary>
 /// Sets the device background for a particular operating mode.
 /// </summary>
 /// <param name="operatingMode">Device operating mode</param>
 /// <param name="background">Desired background</param>
 public void SetBackgroundForMode(MultiClampInterop.OperatingMode operatingMode, IMeasurement background)
 {
     Backgrounds[operatingMode] = background;
 }