private void ValidateIntegerRange(AdditionalField addField, AFValue afv)
 {
     if (addField.Range.Count != 0)
     {
         int  minValue  = Int32.Parse(addField.Range[0].Value);
         int  maxValue  = Int32.Parse(addField.Range[1].Value);
         bool isInRange = true;
         foreach (AFValueItem item in afv.Values)
         {
             if (isInRange)
             {
                 isInRange = Int32.Parse(item.Value) >= minValue &&
                             Int32.Parse(item.Value) <= maxValue;
             }
             else
             {
                 break;
             }
         }
         if (!isInRange)
         {
             throw new BusinessLogicException($"Error: One Request's additional field value was invalid, check {addField.Name}'s range");
         }
     }
 }
 private void ValidateDateRange(AdditionalField addField, AFValue afv)
 {
     if (addField.Range.Count != 0)
     {
         DateTime minDate   = DateTime.Parse(addField.Range[0].Value);
         DateTime maxDate   = DateTime.Parse(addField.Range[1].Value);
         bool     isInRange = true;
         foreach (AFValueItem item in afv.Values)
         {
             if (isInRange)
             {
                 try
                 {
                     DateTime afvDate = DateTime.Parse(item.Value);
                     isInRange = afvDate >= minDate && afvDate <= maxDate;
                 }
                 catch (FormatException)
                 {
                     isInRange = false;
                 }
             }
             else
             {
                 break;
             }
         }
         if (!isInRange)
         {
             throw new BusinessLogicException($"Error: One Request's additional field value was invalid, check {addField.Name}'s range");
         }
     }
 }
 private void ValidateTextRange(AdditionalField addField, AFValue afv)
 {
     if (addField.Range.Count != 0)
     {
         bool isInRange = true;
         bool notFound;
         foreach (AFValueItem item in afv.Values)
         {
             notFound = true;
             foreach (AFRangeItem r in addField.Range)
             {
                 if (r.Value == item.Value)
                 {
                     notFound = false;
                     break;
                 }
             }
             if (notFound)
             {
                 isInRange = false;
                 break;
             }
         }
         if (!isInRange)
         {
             throw new BusinessLogicException("Error: One Request's additional field value was invalid, check fields's range");
         }
     }
 }
Esempio n. 4
0
        // PI data updated handler
        private void m_dataUpdateObserver_DataUpdated(object sender, EventArgs <AFValue> e)
        {
            OnStatusMessage(MessageLevel.Debug, $"DEBUG: Data observer event handler called with a new value: {Convert.ToDouble(e.Argument.Value):N3}...");
            AFValue        value = e.Argument;
            MeasurementKey key;

            OnStatusMessage(MessageLevel.Debug, $"DEBUG: Data observer event handler looking up point ID {value.PIPoint.ID:N0} in table...");

            if ((object)value != null && m_tagKeyMap.TryGetValue(value.PIPoint.ID, out key))
            {
                OnStatusMessage(MessageLevel.Debug, $"DEBUG: Data observer event handler found point ID {value.PIPoint.ID:N0} in table: {key}...");
                Measurement measurement = new Measurement();

                measurement.Metadata  = key.Metadata;
                measurement.Value     = Convert.ToDouble(value.Value);
                measurement.Timestamp = value.Timestamp.UtcTime;

                OnNewMeasurements(new[] { measurement });

                m_lastReceivedTimestamp = measurement.Timestamp;
                m_lastReceivedValue     = measurement.Value;
            }
            else
            {
                OnStatusMessage(MessageLevel.Debug, $"DEBUG: Data observer event handler did not find point ID {value.PIPoint.ID:N0} in table...");
            }
        }
Esempio n. 5
0
        public void Run()
        {
            PIServers piServers = new PIServers();
            PIServer  piServer  = piServers["<PISERVER>"];

            IList <PIPoint> points = PIPoint.FindPIPoints(piServer, new[] { "sample_floatpoint", "sample_digitalpoint" });

            PIPoint floatingPIPoint = points[0];
            PIPoint digitalPIPoint  = points[1];

            AFEnumerationSet digSet = piServer.StateSets["Modes"];

            IList <AFValue> valuesToWrite = new List <AFValue>();

            for (int i = 0; i < 10; i++)
            {
                AFTime time = new AFTime(new DateTime(2015, 1, 1, i, 0, 0, DateTimeKind.Local));

                AFValue afValueFloat = new AFValue(i, time);
                // Associate the AFValue to a PI Point so we know where to write to.
                afValueFloat.PIPoint = floatingPIPoint;

                AFEnumerationValue digSetValue    = i % 2 == 0 ? digSet["Auto"] : digSet["Manual"];
                AFValue            afValueDigital = new AFValue(digSetValue, time);
                afValueDigital.PIPoint = digitalPIPoint;

                valuesToWrite.Add(afValueFloat);
                valuesToWrite.Add(afValueDigital);
            }

            // Perform a bulk write. Use a single local call to PI Buffer Subsystem if possible.
            // Otherwise, make a single call to the PI Data Archive.
            // We use no compression just so we can check all the values are written.
            piServer.UpdateValues(valuesToWrite, AFUpdateOption.InsertNoCompression, AFBufferOption.BufferIfPossible);
        }
Esempio n. 6
0
        // Writing Data to the AFServer
        /// <summary>
        /// Writes to AF, and checks in the element.
        /// </summary>
        /// <param name="element"> AFElement being written to.</param>
        /// <param name="attribute"> AFAttribute being changed.</param>
        /// <param name="value"> The new value being imported.</param>
        public static void writeToAF(AFElement element, AFAttribute attribute, double value)
        {
            AFValue input = new AFValue(attribute, value, AFTime.Now);

            attribute.SetValue(input);
            element.CheckIn();
        }
        public void Run()
        {
            PIServers piServers = new PIServers();
            PIServer piServer = piServers["<PISERVER>"];

            IList<PIPoint> points = PIPoint.FindPIPoints(piServer, new[] { "sample_floatpoint", "sample_digitalpoint" });

            PIPoint floatingPIPoint = points[0];
            PIPoint digitalPIPoint = points[1];

            AFEnumerationSet digSet = piServer.StateSets["Modes"];

            IList<AFValue> valuesToWrite = new List<AFValue>();
            for (int i = 0; i < 10; i++)
            {
                AFTime time = new AFTime(new DateTime(2015, 1, 1, i, 0, 0, DateTimeKind.Local));

                AFValue afValueFloat = new AFValue(i, time);
                // Associate the AFValue to a PI Point so we know where to write to.
                afValueFloat.PIPoint = floatingPIPoint;

                AFEnumerationValue digSetValue = i % 2 == 0 ? digSet["Auto"] : digSet["Manual"];
                AFValue afValueDigital = new AFValue(digSetValue, time);
                afValueDigital.PIPoint = digitalPIPoint;

                valuesToWrite.Add(afValueFloat);
                valuesToWrite.Add(afValueDigital);
            }

            // Perform a bulk write. Use a single local call to PI Buffer Subsystem if possible.
            // Otherwise, make a single call to the PI Data Archive.
            // We use no compression just so we can check all the values are written.
            piServer.UpdateValues(valuesToWrite, AFUpdateOption.InsertNoCompression, AFBufferOption.BufferIfPossible);
        }
Esempio n. 8
0
        private void btnUpdateData_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in dataGrid.Rows)
            {
                try
                {
                    if (row.Cells["CheckBox"].Value != null && (bool)row.Cells["CheckBox"].Value == true)
                    {
                        // Connect PIServerAFSDK
                        PIServer _PIServerAFSDK = piPointTagSearchPage1.PIServer;

                        // Find PIPoint
                        PIPoint piPoint = PIPoint.FindPIPoint(_PIServerAFSDK, (string)row.Cells["tag"].Value);

                        AFAttribute afAttribute = new AFAttribute(piPoint);

                        AFValue afValue = new AFValue(afAttribute, row.Cells["Value"].Value, AFTime.Parse(row.Cells["Timestamp"].Value.ToString()));

                        if (row.Cells["Annotation"].Value.ToString() != string.Empty)
                        {
                            afValue.SetAnnotation(row.Cells["Annotation"].Value.ToString());
                        }

                        piPoint.UpdateValue(afValue, AFUpdateOption.Replace, AFBufferOption.BufferIfPossible);
                    }
                }
                catch (Exception ex)
                {
                    row.Cells["Message"].Value = ex.Message;
                }
            }

            dataGrid.Refresh();
        }
Esempio n. 9
0
        /// <summary>
        /// This method demonstrates how to deal with the several possible types of AFValues that can be returned.
        ///
        /// </summary>
        /// <param name="afValue"></param>
        /// <returns></returns>
        private string GetStringValue(AFValue afValue)
        {
            string result = null;

            // Here, for each attribute we check the type and we print its value.
            //

            // we check if we have an enumeration value
            if (afValue.Value is AFEnumerationValue)
            {
                // in this case, obj.Value.ToString() give same result as obj.Value.ToString(), but in many circumstances it is
                // better to split the treatment of this type of values because they can be processed differently

                var digValue = (AFEnumerationValue)afValue.Value;
                result = digValue.Name;
            }

            // other known types
            // Note that you may need to split these to different else if statement depending on how you are processing
            // the values.  String or bool are rarely processed the same as a single...
            else if (afValue.Value is String || afValue.Value is Boolean || afValue.Value is double || afValue.Value is int ||
                     afValue.Value is DateTime || afValue.Value is Single)
            {
                result = afValue.Value.ToString();
            }

            // unknown types
            else
            {
                result = string.Format("{1} - Unknown type", afValue.Value.GetType().ToString());
            }

            return(result);
        }
 private void ValidateAFVObject(AFValue afv)
 {
     if (afv.Values == null || afv.Values.Count == 0)
     {
         throw new BusinessLogicException("Error: One Request's additional field value was empty");
     }
 }
Esempio n. 11
0
        public override AFValue GetValue(object context, object timeContext, AFAttributeList inputAttributes, AFValues inputValues)
        {
            if (!fChecked)
            {
                CheckConfig();
            }

            try {
                AFTime time;
                if (timeContext is AFTime)
                {
                    time = (AFTime)timeContext;
                }
                else if (timeContext is AFTimeRange)
                {
                    var timeRange = (AFTimeRange)timeContext;
                    time = (Attribute.Element is AFEventFrame) ? timeRange.StartTime : timeRange.EndTime;
                }
                else
                {
                    time = AFTime.NowInWholeSeconds;
                }

                AFValue result = Calculate(time, inputAttributes, inputValues);
                return(result);
            } catch (Exception) {
                UnloadParameters();
                fChecked = false;
                throw;
            }
        }
Esempio n. 12
0
        // IObserver interfaces
        public void OnNext(AFDataPipeEvent value)
        {
            try
            {
                if (value.Action.ToString() == "Add")
                {
                    AFValue val = value.Value;
                    Console.WriteLine($"{val.Value.ToString()} {val.PIPoint.Name} {val.Timestamp} {value.Action}");
                    _pendingEvents.Add(value);
                }
                else
                {
                    Console.WriteLine("An Event Type Received was :'" + value.Action + "'");
                }

                //https:/techsupport.osisoft.com/Documentation/PI-AF-SDK/html/T_OSIsoft_AF_Data_AFDataPipe.htm
            }
            catch (Exception ex)
            {
                Logs Err = new Logs();
                Err.MyLogFile(ex);
                Console.WriteLine("An Error has occured for details please check the Log File:'" + ex.Message + "'");
                Console.ReadLine();
            }
        }
Esempio n. 13
0
        public Request ToEntity()
        {
            Request reqToReturn = new Request()
            {
                Id             = this.Id,
                RequestNumber  = this.RequestNumber,
                TypeId         = this.TypeId,
                Details        = this.Details,
                Name           = this.Name,
                Email          = this.Email,
                Phone          = this.Phone,
                Status         = this.Status,
                Description    = this.Description,
                AddFieldValues = new List <AFValue>()
            };

            if (CreationDate != null)
            {
                reqToReturn.CreationDate = DateTime.Parse(this.CreationDate);
            }
            if (AddFieldValuesDTOs != null)
            {
                foreach (AFValueDTO afvDTO in this.AddFieldValuesDTOs)
                {
                    AFValue afv = afvDTO.ToEntity();
                    afv.Request = reqToReturn;
                    reqToReturn.AddFieldValues.Add(afv);
                }
            }
            return(reqToReturn);
        }
Esempio n. 14
0
        public override AFValue GetValue(object context, object timeContext, AFAttributeList inputAttributes, AFValues inputValues)
        {
            if (!fChecked)
            {
                CheckConfig();
            }

            try {
                // Note that timeContext is an object.
                // We need to examine it further in order to resolve it to an AFTime.
                AFTime time;
                if (timeContext is AFTime)
                {
                    time = (AFTime)timeContext;
                }
                else if (timeContext is AFTimeRange)
                {
                    var timeRange = (AFTimeRange)timeContext;
                    time = (Attribute.Element is AFEventFrame) ? timeRange.StartTime : timeRange.EndTime;
                }
                else
                {
                    time = AFTime.NowInWholeSeconds;
                }

                // Important to note that the order of inputValues matches the order of inputAttributes.
                AFValue result = Calculate(time, inputAttributes, inputValues);
                return(result);
            } catch (Exception) {
                UnloadParameters();
                throw;
            }
        }
 private void ValidateBoolAFV(AFValue afv)
 {
     if (afv.Values.Count != 1 || !afv.Values[0].Value.Equals("True") && !afv.Values[0].Value.Equals("False"))
     {
         throw new BusinessLogicException("Error: One boolean Additional Field type value was not valid");
     }
 }
Esempio n. 16
0
        private string ReadPIValueString(AFValue value)
        {
            String stringvalue;

            stringvalue = value.Value.ToString();
            return(stringvalue);
        }
Esempio n. 17
0
        public static void ConfirmValuesAtRangeEndpoints(this AFValues values, AFAttribute Attribute, AFTimeRange TimeRange)
        {
            AFTime StartTime = TimeRange.StartTime.ToPIPrecision();
            AFTime EndTime   = TimeRange.EndTime.ToPIPrecision();

            // Don't merely add a StartTime and EndTime.
            // First you must check to make sure they aren't already there.
            // Corner case: where EndTime == StartTime.
            if (values.Count == 0)
            {
                values.Add(CreateBadValue(Attribute, StartTime));
            }
            else if (values[0].Timestamp > StartTime)
            {
                // This will probably never happen but in extremely rare
                // case that it does, set a dummy value.
                values.Insert(0, CreateBadValue(Attribute, StartTime));
            }

            var last = values[values.Count - 1];

            if (last.Timestamp < EndTime)
            {
                // Carry the last value to the end of the range, including its status, etc.
                AFValue val = new AFValue(last);
                // Except we want to change its Timestamp
                val.Timestamp = EndTime;
                values.Add(val);
            }
        }
Esempio n. 18
0
        public string CreateEventFrame()
        {
            if (currentDb == null)
            {
                currentDb = InitializeAf();
            }
            string result;
            var    eventFrame = new EventFrame();

            if (currentDb != null)
            {
                AFEventFrame myEventFrame = new AFEventFrame(currentDb, "RandomEventFrame*");
                myEventFrame.SetStartTime("T-1w");
                myEventFrame.SetEndTime(AFTime.Now);
                myEventFrame.Template = currentDb.ElementTemplates["Сообщение"];
                AFValue myValue = new AFValue {
                    Value = "Test"
                };
                myEventFrame.Attributes["Текст сообщения"].SetValue(myValue);
                myEventFrame.Description = "This is my EventFrame";
                myEventFrame.CheckIn();

                eventFrame.Id       = myEventFrame.ID.ToString();
                eventFrame.Name     = myEventFrame.Name;
                eventFrame.DateTime = myEventFrame.EndTime.ToString();
                var serializer = new JavaScriptSerializer();
                result = serializer.Serialize(eventFrame);
            }
            else
            {
                result = "disconnect";
            }

            return(result);
        }
        public override AFValue GetValue(object context, object timeContext, AFAttributeList inputAttributes, AFValues inputValues)
        {
            // I could not find a free API that supports historial data. so I'm just getting newest forecast data
            AFValue result = new AFValue();

            using (var webClient = new WebClient())
            {
                // API only gives me access from a browser, so we need to identify as a browser
                webClient.Headers["User-Agent"] = "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko";
                webClient.Headers["Accept"]     = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8";

                var url  = new Uri($"{weatherBaseUrl}{Lat},{Lng}/forecast");
                var json = webClient.DownloadString(url);
                var j    = JObject.Parse(json);

                var results = j["properties"]["periods"].Select(sf => (JObject)sf).Select(sf =>
                                                                                          new WeatherForecastPeriod()
                {
                    Temperature     = sf["temperature"].Value <int>(),
                    TemperatureUnit = sf["temperatureUnit"].Value <string>(),
                    StartTime       = sf["startTime"].Value <DateTime>(),
                    EndTime         = sf["endTime"].Value <DateTime>()
                });
                result.Value = results.First().Temperature;
                result.UOM   = this.PISystem.UOMDatabase.UOMs.First(x => x.Abbreviation == $"°{results.First().TemperatureUnit}");
            }
            return(result);
        }
 private void ValidateDateAFV(AdditionalField addFieldById, AFValue afv)
 {
     if (!IsDateAFV(afv.Values))
     {
         throw new BusinessLogicException("Error: One Request's additional field value was invalid, check data type");
     }
     ValidateDateRange(addFieldById, afv);
 }
Esempio n. 21
0
 private AFValue createSource2(AFValue item)
 {
     return(new AFValue
     {
         Timestamp = item.Timestamp,
         Value = item.Value.ToString().Split('|')[0].Split('/')[3]
     });
 }
 private static double ToDouble(AFValue value)
 {
     if (value == null || !value.IsGood || !IsNumericType(value.ValueTypeCode))
     {
         return(double.NaN);
     }
     return(value.ValueAsDouble());
 }
Esempio n. 23
0
        //this is assuming two PLC values: one is time in HHMM format (e.g. 1456 for 2:56 pm) and the other is date in MMDD format (e.g. 0617 for June 17)
        private AFValue PLCTimeFormatExecution(AFValue dateVal, AFValue timeVal)
        {
            //get Date value
            DateTime dateAttributeTimestamp = dateVal.Timestamp; //this will be the queried time (DateTime.Now) if step is turned off
            int      dateAttributeVal       = Convert.ToInt32(dateVal.Value);

            //get Time value
            DateTime timeAttributeTimestamp = timeVal.Timestamp; //this will be the queried time (DateTime.Now) if step is turned off
            int      timeAttributeVal       = Convert.ToInt32(timeVal.Value);

            //The year is not stored in the PLC so we have to look at the timestamp of the historian archive data for the year for a baseline
            //Then we calculate the the year before and the year after and see which date is closest to the historian archive date

            int      compare = DateTime.Compare(dateAttributeTimestamp, timeAttributeTimestamp);
            DateTime compareDateTime;

            if (compare > 0) //use the more recent timestamp
            {
                compareDateTime = dateAttributeTimestamp;
            }
            else
            {
                compareDateTime = timeAttributeTimestamp;
            }

            if (dateAttributeVal != 0)
            {
                //date is in format MMDD
                int month = dateAttributeVal / 100;
                int day   = dateAttributeVal % 100;
                //time is in format HHMM
                int hour = timeAttributeVal / 100;
                int min  = timeAttributeVal % 100;

                int      year             = compareDateTime.Year;
                DateTime actualDateTime   = new DateTime(year, month, day, hour, min, 0, DateTimeKind.Local);
                DateTime lastYearDateTime = new DateTime(year - 1, month, day, hour, min, 0, DateTimeKind.Local);
                DateTime nextYearDateTime = new DateTime(year + 1, month, day, hour, min, 0, DateTimeKind.Local);

                TimeSpan minTime  = actualDateTime.Subtract(compareDateTime).Duration();
                TimeSpan tempTime = lastYearDateTime.Subtract(compareDateTime).Duration();
                if (tempTime < minTime)
                {
                    minTime = tempTime; actualDateTime = lastYearDateTime;
                }
                tempTime = nextYearDateTime.Subtract(compareDateTime).Duration();
                if (tempTime < minTime)
                {
                    minTime = tempTime; actualDateTime = nextYearDateTime;
                }

                return(new AFValue(actualDateTime, new AFTime(compareDateTime)));
            }
            else
            {
                return(new AFValue(0, new AFTime(compareDateTime)));
            }
        }
 private static double ToDouble(AFValue value)
 {
     if (value == null || !value.IsGood || !IsNumericType(value.ValueTypeCode))
     {
         return(double.NaN);
     }
     // https://techsupport.osisoft.com/Documentation/PI-AF-SDK/html/M_OSIsoft_AF_Asset_AFValue_ValueAsDouble.htm
     return(value.ValueAsDouble());
 }
Esempio n. 25
0
        public void OnNext(AFDataPipeEvent value)
        {
            AFValue v = value.Value;

            Console.WriteLine($"{Evt}, {v.PIPoint.Name,-12}, {v.Timestamp}, {v.Value}, {{{value.Action}, {DateTime.Now}}}");
            // timeseries subscription carries point archive information
            //Console.WriteLine(value.SpecificUpdatedValue);
            //if (ArchSubscribe && (value.PreviousEventAction == AFDataPipePreviousEventAction.PreviousEventArchived));
        }
Esempio n. 26
0
        public GraphQlAfAttribute(AFAttribute aAfAttribute, Field afAttributesField = null, Field tsPlotValuesField = null)
        {
            AFValue aAfValue = aAfAttribute.GetValue();

            name            = aAfAttribute.Name;
            ThisAfAttribute = aAfAttribute;
            value           = aAfValue.Value?.ToString();
            uom             = aAfAttribute.DisplayUOM?.Abbreviation;

            if (aAfAttribute.DataReference?.Name == "PI Point")
            {
                timeStamp = aAfValue.Timestamp.UtcTime.ToString("yyyy-MM-ddTHH:mm:ssZ");
            }

            if (afAttributesField != null)
            {
                var afAttributesNameFilterStrings = GraphQlHelpers.GetArgumentStrings(afAttributesField, "nameFilter");
                var afAttributesChildField        = GraphQlHelpers.GetFieldFromSelectionSet(afAttributesField, "afAttributes");

                var returnAttributesObject = new ConcurrentBag <GraphQlAfAttribute>();
                var afAttributeList        = aAfAttribute.Attributes.ToList <AFAttribute>();
                Parallel.ForEach(afAttributeList, aAfChildAttribute =>
                {
                    if (afAttributesNameFilterStrings.Count == 0 || afAttributesNameFilterStrings.Contains(aAfChildAttribute.Name))
                    {
                        returnAttributesObject.Add(new GraphQlAfAttribute(aAfAttribute, afAttributesChildField));
                    }
                });
                afAttributes = returnAttributesObject.OrderBy(x => x.name).ToList();
            }

            if (tsPlotValuesField != null)
            {
                if (aAfAttribute.DataReference?.Name == "PI Point")
                {
                    var plotDensity   = GraphQlHelpers.GetArgumentDouble(tsPlotValuesField, "plotDensity");
                    var startDateTime = GraphQlHelpers.GetArgumentDateTime(tsPlotValuesField, "startDateTime");
                    var endDateTime   = GraphQlHelpers.GetArgumentDateTime(tsPlotValuesField, "endDateTime");

                    var timeRange = new AFTimeRange(startDateTime, endDateTime);

                    AFValues asdf = ThisAfAttribute.GetValues(timeRange, (int)plotDensity, null);

                    var returnObject = new ConcurrentBag <GraphQlTsValue>();
                    foreach (AFValue aAfTsValue in asdf)
                    {
                        returnObject.Add(new GraphQlTsValue()
                        {
                            timeStamp = aAfTsValue.Timestamp.UtcTime.ToString("yyyy-MM-ddTHH:mm:ssZ"),
                            value     = aAfTsValue.Value.ToString()
                        });
                    }
                    tsPlotValues = returnObject.OrderBy(x => x.timeStamp).ToList();
                }
            }
        }
Esempio n. 27
0
        private AFValue Calculate(AFTime time, AFAttributeList inputAttributes, AFValues inputValues)
        {
            if (time == null)
            {
                throw new ArgumentException("No timestamp");
            }

            if (inputAttributes == null || inputAttributes.Count == 0)
            {
                throw new ArgumentException("No input attributes");
            }

            if (inputValues == null || inputValues.Count == 0)
            {
                throw new ArgumentException(Resources.ERR_NoInputValues);
            }

            AFValue inVal;

            if (inputAttributes.Count > 0)
            {
                inVal = inputAttributes[0].GetValue(time);

                if (inVal == null)
                {
                    throw new ApplicationException("Input value is null");
                }
                else
                {
                    AFEnumerationValue enumValue = inVal.Value as AFEnumerationValue;
                    if (enumValue != null && enumValue.Value == 248)
                    {
                        // Attempting to handle an error when the output value is 248 instead of the NoData state
                        return(AFValue.CreateSystemStateValue(this.Attribute, AFSystemStateCode.NoData, time));
                    }
                    else
                    {
                        double keyValue    = (double)inVal.Value;
                        double resultValue = GetCalibratedValue(keyValue);

                        if (!double.IsNaN(resultValue))
                        {
                            return(new AFValue(this.Attribute, resultValue, inVal.Timestamp, this.Attribute.DefaultUOM));
                        }
                        else
                        {
                            return(AFValue.CreateSystemStateValue(this.Attribute, AFSystemStateCode.NoData, time));
                        }
                    }
                }
            }
            else
            {
                throw new ApplicationException(string.Format("Input attribute not found (#{0}", 1));
            }
        }
        public override List<AFValue> ReadValues(AFElement element)
        {
            var attribute = element.Attributes["Value"];
            var min= (int)element.Attributes["LowValue"].GetValue().Value;
            var max = (int)element.Attributes["HighValue"].GetValue().Value;

            var newValue = _randomGenerator.Next(min,max);
            var afValue=new AFValue(attribute,newValue,AFTime.Now);

            return new List<AFValue>() {afValue};
        }
Esempio n. 29
0
        public void CreateAttribute()
        {
            AFElement element = new AFElement();

            string name = "Test Element 1";

            element.Name = name;
            Assert.Equals(element.Name, name);

            string desc = "Lazy PI Unit Test Element";

            element.Description = desc;
            Assert.Equals(element.Description, desc);

            Console.WriteLine("Test element creation.");

            Assert.IsTrue(_db.CreateElement(element), "Assert creation passed");

            element = _db.Elements[element.Name];

            //Check that the the element can be found through the AFDB
            Assert.IsNotNull(element, "Check AFDB element collection for new element.");

            AFAttribute attr = new AFAttribute();

            attr.Name        = "Test Attribute";
            attr.Description = "Created by WebAPI tests";

            element.Attributes.Add(attr);
            element.CheckIn();

            Assert.Equals(element.Attributes.Count, 1);
            attr = element.Attributes[attr.Name];

            Assert.IsNotNull(attr);
            Assert.IsNotNull(attr.ID);
            Assert.IsNotNull(attr.Name);
            Assert.IsNotNull(attr.Description);
            Assert.IsNotNull(attr.Path);

            string val = "Test string";

            // Test set and get of AFValue object
            attr.SetValue(new AFValue(val));
            AFValue valObj = attr.GetValue();

            Assert.Equals(valObj.Value, val);

            element.Delete();
            Assert.IsTrue(element.IsDeleted);

            element.CheckIn();
            Assert.IsNull(AFElement.Find(_conn, element.WebID));
        }
        internal void WriteValues(AFTime startTime)
        {
            AFValue nodataValue = new AFValue(nodata);

            foreach (KeyValuePair <AFAttributeTrait, AFValues> boundPair in bounds)
            {
                AFValues bound = boundPair.Value;
                nodataValue.Timestamp = timeShift(bound, startTime);
                boundAttributes[boundPair.Key].PIPoint.UpdateValues(bound, AFUpdateOption.Insert);
                boundAttributes[boundPair.Key].PIPoint.UpdateValue(nodataValue, AFUpdateOption.Insert);
            }
        }
Esempio n. 31
0
 public AFValueDTO(AFValue afv)
 {
     Id                = afv.Id;
     RequestId         = afv.Request.Id;
     AdditionalFieldId = afv.AdditionalFieldID;
     ValuesItemDTOs    = new List <AFValueItemDTO>();
     foreach (AFValueItem afvi in afv.Values)
     {
         AFValueItemDTO AFVItemDTO = new AFValueItemDTO(afvi);
         ValuesItemDTOs.Add(AFVItemDTO);
     }
 }
        private static string val(AFValue value)
        {
            string res = "";

            Type t = value.Value.GetType();

            if (t == typeof(int) || t == typeof(double))
            {
                res = string.Format("{0:0}", value.Value);
            }

            return(res);
        }
        public bool IsFiltered(AFValue value)
        {
            bool isFiltered = false;
            if (lastValue != null)
            {
                if (lastValue.Timestamp==value.Timestamp && lastValue.Value==value.Value)
                {
                    isFiltered = true;
                    _logger.DebugFormat("Fitlered duplicated value: {0} - {1} - {2}",value.PIPoint.Name, value.Timestamp,value.Value);
                }
            }

            lastValue = value;
            return isFiltered;
        }
        /// <summary>
        /// Compare the value with the specified threshold and report outliers
        /// </summary>
        /// <param name="obj"></param>
        public void ReportOutlier(AFValue obj)
        {
            var value = Convert.ToSingle(obj.Value);
            var element = (AFElement)obj.Attribute.Element;
            var threshold = Convert.ToSingle(element.Attributes[Constants.THRESHOLD_ATTRIBUTE].GetValue().Value);

            if (value > threshold)
            {
                lock (_fileLock)
                {
                    using (StreamWriter writer = new StreamWriter(_fileName, true))
                    {
                        writer.WriteLine("Found outlier in Branch element {0} at {1}", element.Name, obj.Timestamp);
                    }
                }
            }
        }
        public bool IsFiltered(AFValue value)
        {
            bool isFiltered = false;
            var enumerationValue = value.Value as AFEnumerationValue;
            if (enumerationValue != null)
            {
                var digValue = enumerationValue;

                isFiltered = _rejectedStates.Contains(digValue.Name.ToLower());

                if(isFiltered)
                    _logger.DebugFormat("Filtered digital value: {0} - {1} - {2}", value.PIPoint.Name, value.Timestamp, enumerationValue);

            }

            return isFiltered;
        }
        public void Run()
        {
            PISystems piSystems = new PISystems();
            PISystem piSystem = piSystems["<AFSERVER>"];

            AFDatabase afDatabase = piSystem.Databases["Basic-AFSDK-Sample"];

            AFElement boilerA = afDatabase.Elements["Region_0"].Elements["BoilerA"];

            AFElementTemplate elementTemplate = afDatabase.ElementTemplates["BasicBoilerTemplate"];
            AFAttributeTemplate temperatureAttrTemplate = elementTemplate.AttributeTemplates["Temperature"];
            AFAttributeTemplate modeAttrTemplate = elementTemplate.AttributeTemplates["Mode"];
            AFElement.LoadAttributes(new[] { boilerA }, new[] { temperatureAttrTemplate, modeAttrTemplate });

            AFEnumerationSet digSet = afDatabase.EnumerationSets["Modes"];

            IList<AFValue> valuesToWrite = new List<AFValue>();
            for (int i = 0; i < 10; i++)
            {
                AFTime time = new AFTime(new DateTime(2015, 1, 1, i, 0, 0, DateTimeKind.Local));

                AFValue afValueFloat = new AFValue(i, time);
                // Associate the AFValue to an attribute so we know where to write to.
                afValueFloat.Attribute = boilerA.Attributes["Temperature"];

                AFEnumerationValue digSetValue = i % 2 == 0 ? digSet["Auto"] : digSet["Manual"];
                AFValue afValueDigital = new AFValue(digSetValue, time);
                afValueDigital.Attribute = boilerA.Attributes["Mode"];

                valuesToWrite.Add(afValueFloat);
                valuesToWrite.Add(afValueDigital);
            }

            // Perform a bulk write. Use a single local call to PI Buffer Subsystem if possible.
            // Otherwise, make a single call to the PI Data Archive.
            // We use no compression just so we can check all the values are written.
            // AFListData is the class that provides the bulk write method.
            AFListData.UpdateValues(valuesToWrite, AFUpdateOption.InsertNoCompression, AFBufferOption.BufferIfPossible);
        }
        /// <summary>
        /// Converts FitFibt Time Series Data to AF Time Series Data
        /// </summary>
        /// <param name="tsDataList">FitBit Time Series data</param>
        /// <param name="type">Type of fit Bit data - this will determine the attribute name to write into. It can also influence the conversion logic.</param>
        /// <param name="element">The element that contains the attribute to write into</param>
        /// <param name="attributeName">Name of the AF Attribute in which time series data will be written into.</param>
        /// <returns></returns>
        public static AFValues ConvertToAFValues(TimeSeriesDataList tsDataList, TimeSeriesResourceType type, AFElement element, string attributeName)
        {
            // creates the list of values
            AFValues values = new AFValues();
            foreach (var result in tsDataList.DataList)
            {
                AFValue val = null;
                if (type != TimeSeriesResourceType.TimeEnteredBed)
                {
                    val = new AFValue(Convert.ToSingle(result.Value), new AFTime(result.DateTime));
                }
                else
                {
                    val = new AFValue(result.Value, new AFTime(result.DateTime));
                }
                values.Add(val);

            }

            values.Attribute = element.Attributes[attributeName];

            return values;
        }
        public AFValues ConvertToAFValues(TimeSeriesDataList tsDataList, FitbitStream stream, FitbitUser fitbitUser)
        {

            AFValues values = new AFValues();
            foreach (var result in tsDataList.DataList)
            {
                AFValue val = null;
                if (stream.FitbitSource != TimeSeriesResourceType.TimeEnteredBed)
                {
                    val = new AFValue(Convert.ToSingle(result.Value), new AFTime(result.DateTime), stream.UnitsOfMeasure);
                }
                else
                {
                    val = new AFValue(result.Value, new AFTime(result.DateTime), stream.UnitsOfMeasure);
                }
                values.Add(val);

            }

            values.Attribute = fitbitUser.UserElement.Elements["Fitbit"].Attributes[stream.AttributeName];

            return values;
        }
Esempio n. 39
0
        /// <summary>
        /// This method demonstrates how to deal with the several possible types of AFValues that can be returned.
        /// 
        /// </summary>
        /// <param name="afValue"></param>
        /// <returns></returns>
        private string GetStringValue(AFValue afValue)
        {
            string result = null;
            // Here, for each attribute we check the type and we print its value.
            //

            // we check if we have an enumeration value
            if (afValue.Value is AFEnumerationValue)
            {

                // in this case, obj.Value.ToString() give same result as obj.Value.ToString(), but in many circumstances it is
                // better to split the treatment of this type of values because they can be processed differently

                var digValue = (AFEnumerationValue)afValue.Value;
                result = digValue.Name;
            }

            // other known types
            // Note that you may need to split these to different else if statement depending on how you are processing
            // the values.  String or bool are rarely processed the same as a single...
            else if (afValue.Value is String || afValue.Value is Boolean || afValue.Value is double || afValue.Value is int ||
                     afValue.Value is DateTime || afValue.Value is Single)
            {
                result = afValue.Value.ToString();
            }

            // unknown types
            else
            {
                result = string.Format("{1} - Unknown type", afValue.Value.GetType().ToString());
            }

            return result;
        }
Esempio n. 40
0
		public void setAFValue(string Timestamp, string Value)
		{
			AFTime aftTime;

			if (AFTime.TryParse(Timestamp, out aftTime))
			{
				m_AFVal = new AFValue(Value, aftTime);
			}
		}
Esempio n. 41
0
		public void setAFValue(string Timestamp, string Value, string TagName, string PIServerName)
		{
			AFTime aftTime;

			if (AFTime.TryParse(Timestamp, out aftTime))
			{
				PIServers svrs = new PIServers();
				PIServer piSrv = svrs[PIServerName];
				PIPoint pipt = PIPoint.FindPIPoint(piSrv, TagName);

				m_AFVal = new AFValue(Value, aftTime);
				m_AFVal.PIPoint = pipt;
				
			}
		}
Esempio n. 42
0
 // Return all values (converted to AFValues) over a specific time interval
 public override AFValues GetValues(object context, AFTimeRange timeRange, int numberOfValues, AFAttributeList inputAttributes, AFValues[] inputValues)
 {
     AFValues values = new AFValues();
     DateTime startTime = timeRange.StartTime.LocalTime;
     DateTime endTime = timeRange.EndTime.LocalTime;
     using (SqlDataReader reader = SQLHelper.GetSQLData(SQLName, DBName, TableName, startTime, endTime))
     {
         while (reader.Read())
         {
             AFValue newVal = new AFValue();
             newVal.Timestamp = AFTime.Parse(reader["pi_time"].ToString());
             newVal.Value = reader["pi_value"];
             values.Add(newVal);
         }
     }
     return values;
 }
Esempio n. 43
0
        // Return latest value if timeContext is null, otherwise return latest value before a specific time
        public override AFValue GetValue(object context, object timeContext, AFAttributeList inputAttributes, AFValues inputValues)
        {
            AFValue currentVal = new AFValue();
            DateTime time;
            if (timeContext != null)
            {
                time = ((AFTime)timeContext).LocalTime;
            }
            else
            {
                time = DateTime.Now;
            }
            using (SqlDataReader reader = SQLHelper.GetSQLData(SQLName, DBName, TableName, DateTime.MinValue, time))
            {
                if (reader.Read())
                {
                    currentVal.Timestamp = AFTime.Parse(reader["pi_time"].ToString());
                    currentVal.Value = reader["pi_value"];
                }
            }

            return currentVal;
        }
Esempio n. 44
0
		public static WAFValue AFValueToWAFValue(AFValue val)
		{
			WAFValue cVal = new WAFValue();

			try
			{
				cVal.setAFValue(val);
			}
			catch (Exception ex)
			{
				System.Console.WriteLine(ex.Message);
				cVal = null;
			}

			return (cVal);
		}
Esempio n. 45
0
        private static bool CheckFilters(AFValue afValue, IDataFilter[] dataFilters)
        {
            if (dataFilters == null)
                return false;

            var isFiltered = false;
            foreach (var filter in dataFilters)
            {
                isFiltered = filter.IsFiltered(afValue);

                if (isFiltered)
                {
                    break;
                }
            }
            return isFiltered;
        }
Esempio n. 46
0
 // Writing Data to the AFServer
 /// <summary>
 /// Writes to AF, and checks in the element.
 /// </summary>
 /// <param name="element"> AFElement being written to.</param>
 /// <param name="attribute"> AFAttribute being changed.</param>
 /// <param name="value"> The new value being imported.</param>
 public static void writeToAF(AFElement element, AFAttribute attribute, double value)
 {
     AFValue input = new AFValue(attribute, value, AFTime.Now);
     attribute.SetValue(input);
     element.CheckIn();
 }
Esempio n. 47
0
 private string ReadPIValueString(AFValue value)
 {
     String stringvalue;
     stringvalue = value.Value.ToString();
     return stringvalue;
 }
Esempio n. 48
0
		public WAFValue()
		{
			m_AFVal = null;

		}
Esempio n. 49
0
        private void ArchiveAFValues(AFValue[] values)
        {
            Ticks startTime = DateTime.UtcNow.Ticks;

            m_connection.Server.UpdateValues(values, UseCompression ? AFUpdateOption.Insert : AFUpdateOption.InsertNoCompression);

            Interlocked.Add(ref m_totalProcessingTime, DateTime.UtcNow.Ticks - startTime);
            Interlocked.Add(ref m_processedMeasurements, values.Length);
        }
 public static string AFValueToString(AFValue value)
 {
     return string.Format("{0} @ {1}", value.Value.ToString(), value.Timestamp.LocalTime.ToString("MM-dd HH:mm:ss.F"));
 }
Esempio n. 51
0
		public void setAFValue(object val)
		{
			try
			{
				m_AFVal = (AFValue)val;
			}
			catch (Exception)
			{

			}
		}