Esempio n. 1
0
        public ActionResult Get(int eventID, int pixels)
        {
            using (AdoDataConnection connection = new AdoDataConnection(m_configuration["OpenXDA:ConnectionString"], m_configuration["OpenXDA:DataProviderString"]))
            {
                Event evt = new TableOperations <Event>(connection).QueryRecordWhere("ID = {0}", eventID);
                if (evt == null)
                {
                    return(BadRequest("Must provide a valid EventID"));
                }
                Meter meter = new TableOperations <Meter>(connection).QueryRecordWhere("ID = {0}", evt.MeterID);
                meter.ConnectionFactory = () => new AdoDataConnection(m_configuration["OpenXDA:ConnectionString"], m_configuration["OpenXDA:DataProviderString"]);

                Dictionary <string, IEnumerable <double[]> > returnData = new Dictionary <string, IEnumerable <double[]> >();
                DataGroupHelper  dataGroupHelper  = new DataGroupHelper(m_configuration, m_memoryCache);
                VICycleDataGroup vICycleDataGroup = dataGroupHelper.QueryVICycleDataGroup(eventID, meter);


                Dictionary <string, List <double[]> > returnList = new Dictionary <string, List <double[]> >();

                foreach (CycleDataGroup dg in vICycleDataGroup.CycleDataGroups)
                {
                    if (dg.RMS.SeriesInfo.Channel.MeasurementType.Name == "Voltage")
                    {
                        string name = "V" + dg.RMS.SeriesInfo.Channel.Phase.Name;
                        returnList.Add(name, GetRapidVoltageChangeSeries(dg.RMS));
                    }
                }

                return(Ok(returnList));
            }
        }
Esempio n. 2
0
        public ActionResult Get(int eventID, int pixels)
        {
            using (AdoDataConnection connection = new AdoDataConnection(m_configuration["OpenXDA:ConnectionString"], m_configuration["OpenXDA:DataProviderString"]))
            {
                Event evt = new TableOperations <Event>(connection).QueryRecordWhere("ID = {0}", eventID);
                if (evt == null)
                {
                    return(BadRequest("Must provide a valid EventID"));
                }
                Meter meter = new TableOperations <Meter>(connection).QueryRecordWhere("ID = {0}", evt.MeterID);
                meter.ConnectionFactory = () => new AdoDataConnection(m_configuration["OpenXDA:ConnectionString"], m_configuration["OpenXDA:DataProviderString"]);

                Dictionary <string, IEnumerable <double[]> > returnData = new Dictionary <string, IEnumerable <double[]> >();
                DataGroupHelper dataGroupHelper = new DataGroupHelper(m_configuration, m_memoryCache);
                DataGroup       dataGroup       = dataGroupHelper.QueryDataGroup(eventID, meter);;
                VIDataGroup     vIDataGroup     = new VIDataGroup(dataGroup);
                double          systemFrequency = connection.ExecuteScalar <double?>("SELECT Value FROM Setting WHERE Name = 'SystemFrequency'") ?? 60.0;


                Dictionary <string, List <double[]> > returnList = new Dictionary <string, List <double[]> >();

                returnList.Add("VA", GenerateFrequency(systemFrequency, vIDataGroup.VA));
                returnList.Add("VB", GenerateFrequency(systemFrequency, vIDataGroup.VB));
                returnList.Add("VC", GenerateFrequency(systemFrequency, vIDataGroup.VC));
                returnList.Add("Average", GenerateFrequency(systemFrequency, vIDataGroup.VC));

                return(Ok(returnList));
            }
        }
        public ActionResult Get(int eventID, string type, int pixels)
        {
            using (AdoDataConnection connection = new AdoDataConnection(m_configuration["OpenXDA:ConnectionString"], m_configuration["OpenXDA:DataProviderString"]))
            {
                DateTime epoch = new DateTime(1970, 1, 1);

                Event evt = new TableOperations <Event>(connection).QueryRecordWhere("ID = {0}", eventID);
                if (evt == null)
                {
                    return(BadRequest("Must provide a valid EventID"));
                }
                Meter meter = new TableOperations <Meter>(connection).QueryRecordWhere("ID = {0}", evt.MeterID);
                meter.ConnectionFactory = () => new AdoDataConnection(m_configuration["OpenXDA:ConnectionString"], m_configuration["OpenXDA:DataProviderString"]);

                Dictionary <string, IEnumerable <double[]> > returnData = new Dictionary <string, IEnumerable <double[]> >();
                DataGroupHelper dataGroupHelper = new DataGroupHelper(m_configuration, m_memoryCache);
                DataGroup       dataGroup       = dataGroupHelper.QueryDataGroup(eventID, meter);;

                foreach (var series in dataGroup.DataSeries)
                {
                    List <double[]> data = series.DataPoints.Select(dp => new double[2] {
                        (dp.Time - epoch).TotalMilliseconds, dp.Value
                    }).ToList();
                    if (series.SeriesInfo.Channel.MeasurementType.Name == type && series.SeriesInfo.Channel.MeasurementCharacteristic.Name == "Instantaneous")
                    {
                        returnData.Add((type == "Voltage" ? "V" : "I") + series.SeriesInfo.Channel.Phase.Name, data);
                    }
                }

                VICycleDataGroup viCycleDataGroup = dataGroupHelper.QueryVICycleDataGroup(eventID, meter);;

                foreach (CycleDataGroup cdg in viCycleDataGroup.CycleDataGroups.Where(ds => ds.RMS.SeriesInfo.Channel.MeasurementType.Name == type))
                {
                    List <double[]> rmsPoints = cdg.RMS.DataPoints.Select(dp => new double[2] {
                        (dp.Time - epoch).TotalMilliseconds, dp.Value
                    }).ToList();
                    returnData.Add((type == "Voltage" ? "V" : "I") + cdg.RMS.SeriesInfo.Channel.Phase.Name + " RMS", rmsPoints);
                    List <double[]> ampPoints = cdg.Peak.DataPoints.Select(dp => new double[2] {
                        (dp.Time - epoch).TotalMilliseconds, dp.Value
                    }).ToList();
                    returnData.Add((type == "Voltage" ? "V" : "I") + cdg.Peak.SeriesInfo.Channel.Phase.Name + " Amplitude", ampPoints);
                    List <double[]> phPoints = cdg.Phase.DataPoints.Select(dp => new double[2] {
                        (dp.Time - epoch).TotalMilliseconds, dp.Value * 180 / Math.PI
                    }).ToList();
                    returnData.Add((type == "Voltage" ? "V" : "I") + cdg.Phase.SeriesInfo.Channel.Phase.Name + " Phase", phPoints);
                }

                return(Ok(returnData));
            }
        }
        public ActionResult Get(int eventID, int harmonic, int pixels)
        {
            using (AdoDataConnection connection = new AdoDataConnection(m_configuration["OpenXDA:ConnectionString"], m_configuration["OpenXDA:DataProviderString"]))
            {
                Event evt = new TableOperations <Event>(connection).QueryRecordWhere("ID = {0}", eventID);
                if (evt == null)
                {
                    return(BadRequest("Must provide a valid EventID"));
                }
                Meter meter = new TableOperations <Meter>(connection).QueryRecordWhere("ID = {0}", evt.MeterID);
                meter.ConnectionFactory = () => new AdoDataConnection(m_configuration["OpenXDA:ConnectionString"], m_configuration["OpenXDA:DataProviderString"]);

                Dictionary <string, IEnumerable <double[]> > returnData = new Dictionary <string, IEnumerable <double[]> >();
                DataGroupHelper dataGroupHelper = new DataGroupHelper(m_configuration, m_memoryCache);
                double          systemFrequency = connection.ExecuteScalar <double?>("SELECT Value FROM Setting WHERE Name = 'SystemFrequency'") ?? 60.0;
                DataGroup       dataGroup       = dataGroupHelper.QueryDataGroup(eventID, meter);;


                Dictionary <string, List <double[]> > returnList = new Dictionary <string, List <double[]> >();

                List <DataSeries> vAN = dataGroup.DataSeries.Where(x => x.SeriesInfo.Channel.MeasurementType.Name == "Voltage" && x.SeriesInfo.Channel.MeasurementCharacteristic.Name == "Instantaneous" && x.SeriesInfo.Channel.Phase.Name == "AN").ToList();
                List <DataSeries> iAN = dataGroup.DataSeries.Where(x => x.SeriesInfo.Channel.MeasurementType.Name == "Current" && x.SeriesInfo.Channel.MeasurementCharacteristic.Name == "Instantaneous" && x.SeriesInfo.Channel.Phase.Name == "AN").ToList();
                List <DataSeries> vBN = dataGroup.DataSeries.Where(x => x.SeriesInfo.Channel.MeasurementType.Name == "Voltage" && x.SeriesInfo.Channel.MeasurementCharacteristic.Name == "Instantaneous" && x.SeriesInfo.Channel.Phase.Name == "BN").ToList();
                List <DataSeries> iBN = dataGroup.DataSeries.Where(x => x.SeriesInfo.Channel.MeasurementType.Name == "Current" && x.SeriesInfo.Channel.MeasurementCharacteristic.Name == "Instantaneous" && x.SeriesInfo.Channel.Phase.Name == "BN").ToList();
                List <DataSeries> vCN = dataGroup.DataSeries.Where(x => x.SeriesInfo.Channel.MeasurementType.Name == "Voltage" && x.SeriesInfo.Channel.MeasurementCharacteristic.Name == "Instantaneous" && x.SeriesInfo.Channel.Phase.Name == "CN").ToList();
                List <DataSeries> iCN = dataGroup.DataSeries.Where(x => x.SeriesInfo.Channel.MeasurementType.Name == "Current" && x.SeriesInfo.Channel.MeasurementCharacteristic.Name == "Instantaneous" && x.SeriesInfo.Channel.Phase.Name == "CN").ToList();

                var vANResult = GenerateSpecifiedHarmonic(systemFrequency, vAN.First(), harmonic);
                returnList.Add("VAN Mag", vANResult.Magnitude);
                returnList.Add("VAN Ang", vANResult.Angle);
                var vBNResult = GenerateSpecifiedHarmonic(systemFrequency, vBN.First(), harmonic);
                returnList.Add("VBN Mag", vBNResult.Magnitude);
                returnList.Add("VBN Ang", vBNResult.Angle);
                var vCNResult = GenerateSpecifiedHarmonic(systemFrequency, vCN.First(), harmonic);
                returnList.Add("VCN Mag", vCNResult.Magnitude);
                returnList.Add("VCN Ang", vCNResult.Angle);
                var iANResult = GenerateSpecifiedHarmonic(systemFrequency, iAN.First(), harmonic);
                returnList.Add("IAN Mag", iANResult.Magnitude);
                returnList.Add("IAN Ang", iANResult.Angle);
                var iBNResult = GenerateSpecifiedHarmonic(systemFrequency, iBN.First(), harmonic);
                returnList.Add("IBN Mag", iBNResult.Magnitude);
                returnList.Add("IBN Ang", iBNResult.Angle);
                var iCNResult = GenerateSpecifiedHarmonic(systemFrequency, iCN.First(), harmonic);
                returnList.Add("ICN Mag", iCNResult.Magnitude);
                returnList.Add("ICN Ang", iCNResult.Angle);

                return(Ok(returnList));
            }
        }
        public static bool SetMapTagOnElement(BCOM.Element element,
                                              TagToDataGroupMapProperty mapProperty)
        {
            object propValue = DataGroupHelper.GetDataGroupPropertyValue(
                element, mapProperty.DataGroupXPath);

            if (propValue == null)
            {
                return(false);
            }

            MsdTagType tagType;

            if (propValue is string)
            {
                tagType = MsdTagType.Character;
            }
            else if (propValue is double)
            {
                tagType = MsdTagType.Double;
            }
            else if (propValue is int)
            {
                tagType = MsdTagType.ShortInteger;
            }
            else if (propValue is long)
            {
                tagType = MsdTagType.LongInteger;
            }
            else if (propValue is Byte[])
            {
                tagType = MsdTagType.ShortInteger;
            }
            else
            {
                tagType = MsdTagType.Character;
            }

            return(ElementHelper.setTagOnElement(element, mapProperty.TagSetName,
                                                 mapProperty.TagName, propValue, tagType));
        }
        private static void scanRecurse(BCOM.ModelReference model, BCOM.ElementScanCriteria criteria)
        {
            BCOM.ElementEnumerator iter = App.ActiveModelReference.Scan(criteria);

            var errorColl    = new Dictionary <BCOM.Element, List <TagToDataGroupMapProperty> >();
            var successList  = new List <BCOM.Element>();
            int summaryCount = 0;

            iter.Reset();
            while (iter.MoveNext())
            {
                IEnumerable <TagToDataGroupMapProperty> mapTags;
                if (!ScanElementHasMappingTags(iter.Current, out mapTags))
                {
                    continue;
                }

                ++summaryCount;
                var skippedProps = new List <TagToDataGroupMapProperty>();

                foreach (TagToDataGroupMapProperty mapTag in mapTags)
                {
                    bool res = DataGroupHelper.SetDataGroupPropertyValue(iter.Current,
                                                                         mapTag.DataGroupCatalogType, mapTag.DataGroupInstance,
                                                                         mapTag.DataGroupXPath, mapTag.TagName, mapTag.Value);

                    if (!res)
                    {
                        skippedProps.Add(mapTag);
                    }
                }

                if (skippedProps.Count == 0)
                {
                    successList.Add(iter.Current);
                }
                else
                {
                    errorColl.Add(iter.Current, skippedProps);
                }
            }

            string brief = $"Команда 'Экспорт свойств из Tags в DataGroup', успешно: {successList.Count()}/{summaryCount}";

            var builder = new StringBuilder();

            builder.AppendLine($"*** С ошибками: {errorColl.Count()} из {summaryCount}");
            if (errorColl.Count() > 0)
            {
                foreach (var pair in errorColl)
                {
                    var element  = pair.Key;
                    var errProps = pair.Value;

                    builder.AppendLine(element.ID.ToString() + ":");
                    foreach (TagToDataGroupMapProperty prop in errProps)
                    {
                        builder.AppendLine("    -" + XmlSerializerEx.ToXml(prop));
                    }
                }
            }
            builder.Append("\n\n");

            builder.AppendLine($"*** Успешно: {successList.Count()} из {summaryCount}");
            if (successList.Count() > 0)
            {
                foreach (var element in successList)
                {
                    builder.AppendLine(element.ID.ToString());
                }
            }

    #if V8i
            App.MessageCenter.AddMessage(brief, builder.ToString(), BCOM.MsdMessageCenterPriority.Info, true);
    #elif CONNECT
            Bentley.MstnPlatformNET.MessageCenter.Instance.ShowMessage(MessageType.Info, brief, builder.ToString(), MessageAlert.Dialog);
    #endif

            // TODO ОБРАБОТКА РЕФЕРЕНСОВ
            //foreach (BCOM.Attachment attachment in model.Attachments)
            //{
            //    if (!attachment.IsActive || !attachment.IsMissingFile || !attachment.IsMissingModel)
            //        return;

            //    ModelReference modelRef =
            //        App.MdlGetModelReferenceFromModelRefP(attachment.MdlModelRefP());
            //    scanRecurse(modelRef, criteria);
            //}
        }
        public ActionResult Get(int eventID, int pixels)
        {
            using (AdoDataConnection connection = new AdoDataConnection(m_configuration["OpenXDA:ConnectionString"], m_configuration["OpenXDA:DataProviderString"]))
            {
                Event evt = new TableOperations <Event>(connection).QueryRecordWhere("ID = {0}", eventID);
                if (evt == null)
                {
                    return(BadRequest("Must provide a valid EventID"));
                }
                Meter meter = new TableOperations <Meter>(connection).QueryRecordWhere("ID = {0}", evt.MeterID);
                meter.ConnectionFactory = () => new AdoDataConnection(m_configuration["OpenXDA:ConnectionString"], m_configuration["OpenXDA:DataProviderString"]);

                Dictionary <string, IEnumerable <double[]> > returnData = new Dictionary <string, IEnumerable <double[]> >();
                DataGroupHelper  dataGroupHelper  = new DataGroupHelper(m_configuration, m_memoryCache);
                VICycleDataGroup vICycleDataGroup = dataGroupHelper.QueryVICycleDataGroup(eventID, meter);


                Dictionary <string, List <double[]> > returnList = new Dictionary <string, List <double[]> >();


                if (vICycleDataGroup.VA != null && vICycleDataGroup.VB != null && vICycleDataGroup.VC != null)
                {
                    var va      = vICycleDataGroup.VA.RMS.DataPoints;
                    var vaPhase = vICycleDataGroup.VA.Phase.DataPoints;
                    var vb      = vICycleDataGroup.VB.RMS.DataPoints;
                    var vbPhase = vICycleDataGroup.VB.Phase.DataPoints;
                    var vc      = vICycleDataGroup.VC.RMS.DataPoints;
                    var vcPhase = vICycleDataGroup.VC.Phase.DataPoints;

                    IEnumerable <SequenceComponents> sequencComponents = va.Select((point, index) =>
                    {
                        DataPoint vaPoint      = point;
                        DataPoint vaPhasePoint = vaPhase[index];
                        Complex vaComplex      = Complex.FromPolarCoordinates(vaPoint.Value, vaPhasePoint.Value);

                        DataPoint vbPoint      = vb[index];
                        DataPoint vbPhasePoint = vbPhase[index];
                        Complex vbComplex      = Complex.FromPolarCoordinates(vbPoint.Value, vbPhasePoint.Value);

                        DataPoint vcPoint      = vc[index];
                        DataPoint vcPhasePoint = vcPhase[index];
                        Complex vcComplex      = Complex.FromPolarCoordinates(vcPoint.Value, vcPhasePoint.Value);

                        SequenceComponents sequenceComponents = CalculateSequenceComponents(vaComplex, vbComplex, vcComplex);

                        return(sequenceComponents);
                    });

                    returnList.Add("S0/S1 Voltage", sequencComponents.Select((point, index) => new double[] { va[index].Time.Subtract(m_epoch).TotalMilliseconds, point.S0.Magnitude / point.S1.Magnitude * 100.0D }).ToList());
                    returnList.Add("S2/S1 Voltage", sequencComponents.Select((point, index) => new double[] { va[index].Time.Subtract(m_epoch).TotalMilliseconds, point.S2.Magnitude / point.S1.Magnitude * 100.0D }).ToList());
                }


                if (vICycleDataGroup.IA != null && vICycleDataGroup.IB != null && vICycleDataGroup.IC != null)
                {
                    var ia      = vICycleDataGroup.IA.RMS.DataPoints;
                    var iaPhase = vICycleDataGroup.IA.Phase.DataPoints;
                    var ib      = vICycleDataGroup.IB.RMS.DataPoints;
                    var ibPhase = vICycleDataGroup.IB.Phase.DataPoints;
                    var ic      = vICycleDataGroup.IC.RMS.DataPoints;
                    var icPhase = vICycleDataGroup.IC.Phase.DataPoints;

                    IEnumerable <SequenceComponents> sequencComponents = ia.Select((point, index) =>
                    {
                        DataPoint iaPoint      = point;
                        DataPoint iaPhasePoint = iaPhase[index];
                        Complex iaComplex      = Complex.FromPolarCoordinates(iaPoint.Value, iaPhasePoint.Value);

                        DataPoint ibPoint      = ib[index];
                        DataPoint ibPhasePoint = ibPhase[index];
                        Complex ibComplex      = Complex.FromPolarCoordinates(ibPoint.Value, ibPhasePoint.Value);

                        DataPoint icPoint      = ic[index];
                        DataPoint icPhasePoint = icPhase[index];
                        Complex icComplex      = Complex.FromPolarCoordinates(icPoint.Value, icPhasePoint.Value);

                        SequenceComponents sequenceComponents = CalculateSequenceComponents(iaComplex, ibComplex, icComplex);

                        return(sequenceComponents);
                    });
                    returnList.Add("S0/S1 Current", sequencComponents.Select((point, index) => new double[] { ia[index].Time.Subtract(m_epoch).TotalMilliseconds, point.S0.Magnitude / point.S1.Magnitude * 100.0D }).ToList());
                    returnList.Add("S2/S1 Current", sequencComponents.Select((point, index) => new double[] { ia[index].Time.Subtract(m_epoch).TotalMilliseconds, point.S2.Magnitude / point.S1.Magnitude * 100.0D }).ToList());
                }

                return(Ok(returnList));
            }
        }
        public FileStreamResult Get(int eventID)
        {
            using (AdoDataConnection connection = new AdoDataConnection(m_configuration["OpenXDA:ConnectionString"], m_configuration["OpenXDA:DataProviderString"]))
            {
                DateTime epoch = new DateTime(1970, 1, 1);

                Event  evt      = new TableOperations <Event>(connection).QueryRecordWhere("ID = {0}", eventID);
                string fileName = $"Event_{eventID}.csv";

                if (evt == null)
                {
                    throw new Exception("Needs valid EventID");
                }
                Meter meter = new TableOperations <Meter>(connection).QueryRecordWhere("ID = {0}", evt.MeterID);
                meter.ConnectionFactory = () => new AdoDataConnection(m_configuration["OpenXDA:ConnectionString"], m_configuration["OpenXDA:DataProviderString"]);

                Dictionary <string, List <string> > returnData = new Dictionary <string, List <string> >();
                DataGroupHelper dataGroupHelper = new DataGroupHelper(m_configuration, m_memoryCache);
                DataGroup       dataGroup       = dataGroupHelper.QueryDataGroup(eventID, meter);;
                foreach (var series in dataGroup.DataSeries)
                {
                    if (!returnData.ContainsKey("Timestamps"))
                    {
                        returnData.Add("Timestamps", series.DataPoints.Select(x => x.Time.ToString("MM/dd/yyyyTHH:mm:ss.fffffffK")).ToList());
                    }

                    List <string> data = series.DataPoints.Select(dp => dp.Value.ToString()).ToList();
                    if (series.SeriesInfo.Channel.MeasurementType.Name == "Voltage" && series.SeriesInfo.Channel.MeasurementCharacteristic.Name == "Instantaneous")
                    {
                        returnData.Add("V" + series.SeriesInfo.Channel.Phase.Name, data);
                    }
                    else if (series.SeriesInfo.Channel.MeasurementType.Name == "Current" && series.SeriesInfo.Channel.MeasurementCharacteristic.Name == "Instantaneous")
                    {
                        returnData.Add("I" + series.SeriesInfo.Channel.Phase.Name, data);
                    }
                }

                VICycleDataGroup viCycleDataGroup = dataGroupHelper.QueryVICycleDataGroup(eventID, meter);;

                foreach (CycleDataGroup cdg in viCycleDataGroup.CycleDataGroups)
                {
                    List <string> rmsPoints = cdg.RMS.DataPoints.Select(dp => dp.Value.ToString()).ToList();
                    returnData.Add((cdg.RMS.SeriesInfo.Channel.MeasurementType.Name == "Voltage" ? "V" : "I") + cdg.RMS.SeriesInfo.Channel.Phase.Name + " RMS", rmsPoints);
                    List <string> ampPoints = cdg.Peak.DataPoints.Select(dp => dp.Value.ToString()).ToList();
                    returnData.Add((cdg.RMS.SeriesInfo.Channel.MeasurementType.Name == "Voltage" ? "V" : "I") + cdg.Peak.SeriesInfo.Channel.Phase.Name + " Amplitude", ampPoints);
                    List <string> phPoints = cdg.Phase.DataPoints.Select(dp => (dp.Value * 180 / Math.PI).ToString()).ToList();
                    returnData.Add((cdg.RMS.SeriesInfo.Channel.MeasurementType.Name == "Voltage"  ? "V" : "I") + cdg.Phase.SeriesInfo.Channel.Phase.Name + " Phase", phPoints);
                }


                string file = string.Join(",", returnData.Keys) + "\n";

                for (int i = 0; i < returnData.First().Value.Count(); ++i)
                {
                    file += string.Join(",", returnData.Keys.Select(key => {
                        if (i < returnData[key].Count())
                        {
                            return(returnData[key][i]);
                        }
                        else
                        {
                            return("");
                        }
                    })) + '\n';
                }

                byte[] fileBytes = Encoding.ASCII.GetBytes(file);
                Response.Headers.Add("fileName", fileName);
                return(new FileStreamResult(new MemoryStream(fileBytes), "text/csv")
                {
                    FileDownloadName = fileName,
                });
            }
        }
        public ActionResult Get(int eventID, int pixels)
        {
            using (AdoDataConnection connection = new AdoDataConnection(m_configuration["OpenXDA:ConnectionString"], m_configuration["OpenXDA:DataProviderString"]))
            {
                Event evt = new TableOperations <Event>(connection).QueryRecordWhere("ID = {0}", eventID);
                if (evt == null)
                {
                    return(BadRequest("Must provide a valid EventID"));
                }
                Meter meter = new TableOperations <Meter>(connection).QueryRecordWhere("ID = {0}", evt.MeterID);
                meter.ConnectionFactory = () => new AdoDataConnection(m_configuration["OpenXDA:ConnectionString"], m_configuration["OpenXDA:DataProviderString"]);

                Dictionary <string, IEnumerable <double[]> > returnData = new Dictionary <string, IEnumerable <double[]> >();
                DataGroupHelper  dataGroupHelper  = new DataGroupHelper(m_configuration, m_memoryCache);
                VICycleDataGroup vICycleDataGroup = dataGroupHelper.QueryVICycleDataGroup(eventID, meter);
                double           systemFrequency  = connection.ExecuteScalar <double?>("SELECT Value FROM Setting WHERE Name = 'SystemFrequency'") ?? 60.0;


                Dictionary <string, List <double[]> > returnList = new Dictionary <string, List <double[]> >();

                List <Complex> powerPointsAN = null;
                List <Complex> powerPointsBN = null;
                List <Complex> powerPointsCN = null;

                if (vICycleDataGroup.IA != null && vICycleDataGroup.VA != null)
                {
                    List <DataPoint> voltagePointsMag = vICycleDataGroup.VA.RMS.DataPoints;
                    List <DataPoint> voltagePointsAng = vICycleDataGroup.VA.Phase.DataPoints;
                    List <Complex>   voltagePoints    = voltagePointsMag.Select((vMagPoint, index) => Complex.FromPolarCoordinates(vMagPoint.Value, voltagePointsAng[index].Value)).ToList();

                    List <DataPoint> currentPointsMag = vICycleDataGroup.IA.RMS.DataPoints;
                    List <DataPoint> currentPointsAng = vICycleDataGroup.IA.Phase.DataPoints;
                    List <Complex>   currentPoints    = currentPointsMag.Select((iMagPoint, index) => Complex.Conjugate(Complex.FromPolarCoordinates(iMagPoint.Value, currentPointsAng[index].Value))).ToList();

                    powerPointsAN = voltagePoints.Select((vPoint, index) => currentPoints[index] * vPoint).ToList();
                    returnList.Add("AN Reactive Power", powerPointsAN.Select((iPoint, index) => new double[] { voltagePointsMag[index].Time.Subtract(m_epoch).TotalMilliseconds, iPoint.Imaginary / 1000 }).ToList());
                    returnList.Add("AN Active Power", powerPointsAN.Select((iPoint, index) => new double[] { voltagePointsMag[index].Time.Subtract(m_epoch).TotalMilliseconds, iPoint.Real / 1000 }).ToList());
                    returnList.Add("AN Apparent Power", powerPointsAN.Select((iPoint, index) => new double[] { voltagePointsMag[index].Time.Subtract(m_epoch).TotalMilliseconds, iPoint.Magnitude / 1000 }).ToList());
                    returnList.Add("AN Power Factor", powerPointsAN.Select((iPoint, index) => new double[] { voltagePointsMag[index].Time.Subtract(m_epoch).TotalMilliseconds, iPoint.Real / iPoint.Magnitude }).ToList());
                }

                if (vICycleDataGroup.IB != null && vICycleDataGroup.VB != null)
                {
                    List <DataPoint> voltagePointsMag = vICycleDataGroup.VB.RMS.DataPoints;
                    List <DataPoint> voltagePointsAng = vICycleDataGroup.VB.Phase.DataPoints;
                    List <Complex>   voltagePoints    = voltagePointsMag.Select((vMagPoint, index) => Complex.FromPolarCoordinates(vMagPoint.Value, voltagePointsAng[index].Value)).ToList();

                    List <DataPoint> currentPointsMag = vICycleDataGroup.IB.RMS.DataPoints;
                    List <DataPoint> currentPointsAng = vICycleDataGroup.IB.Phase.DataPoints;
                    List <Complex>   currentPoints    = currentPointsMag.Select((iMagPoint, index) => Complex.Conjugate(Complex.FromPolarCoordinates(iMagPoint.Value, currentPointsAng[index].Value))).ToList();

                    powerPointsBN = voltagePoints.Select((vPoint, index) => currentPoints[index] * vPoint).ToList();
                    returnList.Add("BN Reactive Power", powerPointsBN.Select((iPoint, index) => new double[] { voltagePointsMag[index].Time.Subtract(m_epoch).TotalMilliseconds, iPoint.Imaginary / 1000 }).ToList());
                    returnList.Add("BN Active Power", powerPointsBN.Select((iPoint, index) => new double[] { voltagePointsMag[index].Time.Subtract(m_epoch).TotalMilliseconds, iPoint.Real / 1000 }).ToList());
                    returnList.Add("BN Apparent Power", powerPointsBN.Select((iPoint, index) => new double[] { voltagePointsMag[index].Time.Subtract(m_epoch).TotalMilliseconds, iPoint.Magnitude / 1000 }).ToList());
                    returnList.Add("BN Power Factor", powerPointsBN.Select((iPoint, index) => new double[] { voltagePointsMag[index].Time.Subtract(m_epoch).TotalMilliseconds, iPoint.Real / iPoint.Magnitude }).ToList());
                }

                if (vICycleDataGroup.IC != null && vICycleDataGroup.VC != null)
                {
                    List <DataPoint> voltagePointsMag = vICycleDataGroup.VC.RMS.DataPoints;
                    List <DataPoint> voltagePointsAng = vICycleDataGroup.VC.Phase.DataPoints;
                    List <Complex>   voltagePoints    = voltagePointsMag.Select((vMagPoint, index) => Complex.FromPolarCoordinates(vMagPoint.Value, voltagePointsAng[index].Value)).ToList();

                    List <DataPoint> currentPointsMag = vICycleDataGroup.IC.RMS.DataPoints;
                    List <DataPoint> currentPointsAng = vICycleDataGroup.IC.Phase.DataPoints;
                    List <Complex>   currentPoints    = currentPointsMag.Select((iMagPoint, index) => Complex.Conjugate(Complex.FromPolarCoordinates(iMagPoint.Value, currentPointsAng[index].Value))).ToList();

                    powerPointsCN = voltagePoints.Select((vPoint, index) => currentPoints[index] * vPoint).ToList();
                    returnList.Add("CN Reactive Power", powerPointsCN.Select((iPoint, index) => new double[] { voltagePointsMag[index].Time.Subtract(m_epoch).TotalMilliseconds, iPoint.Imaginary / 1000 }).ToList());
                    returnList.Add("CN Active Power", powerPointsCN.Select((iPoint, index) => new double[] { voltagePointsMag[index].Time.Subtract(m_epoch).TotalMilliseconds, iPoint.Real / 1000 }).ToList());
                    returnList.Add("CN Apparent Power", powerPointsCN.Select((iPoint, index) => new double[] { voltagePointsMag[index].Time.Subtract(m_epoch).TotalMilliseconds, iPoint.Magnitude / 1000 }).ToList());
                    returnList.Add("CN Power Factor", powerPointsCN.Select((iPoint, index) => new double[] { voltagePointsMag[index].Time.Subtract(m_epoch).TotalMilliseconds, iPoint.Real / iPoint.Magnitude }).ToList());
                }

                if (powerPointsAN != null && powerPointsAN.Any() && powerPointsBN != null && powerPointsBN.Any() && powerPointsCN != null && powerPointsCN.Any())
                {
                    IEnumerable <Complex> powerPoints = powerPointsAN.Select((pPoint, index) => pPoint + powerPointsBN[index] + powerPointsCN[index]).ToList();
                    returnList.Add("Total Reactive Power", powerPointsAN.Select((iPoint, index) => new double[] { vICycleDataGroup.VC.RMS.DataPoints[index].Time.Subtract(m_epoch).TotalMilliseconds, iPoint.Imaginary / 1000 }).ToList());
                    returnList.Add("Total Active Power", powerPointsAN.Select((iPoint, index) => new double[] { vICycleDataGroup.VC.RMS.DataPoints[index].Time.Subtract(m_epoch).TotalMilliseconds, iPoint.Real / 1000 }).ToList());
                    returnList.Add("Total Apparent Power", powerPointsAN.Select((iPoint, index) => new double[] { vICycleDataGroup.VC.RMS.DataPoints[index].Time.Subtract(m_epoch).TotalMilliseconds, iPoint.Magnitude / 1000 }).ToList());
                    returnList.Add("Total Power Factor", powerPointsAN.Select((iPoint, index) => new double[] { vICycleDataGroup.VC.RMS.DataPoints[index].Time.Subtract(m_epoch).TotalMilliseconds, iPoint.Real / iPoint.Magnitude }).ToList());
                }


                return(Ok(returnList));
            }
        }
        public ActionResult GetData(int eventId, string type, string dataType, int pixels, string startDate, string endDate)
        {
            using (AdoDataConnection connection = new AdoDataConnection(m_configuration["OpenXDA:ConnectionString"], m_configuration["OpenXDA:DataProviderString"]))
            {
                DateTime epoch = new DateTime(1970, 1, 1);

                Event evt = new TableOperations <Event>(connection).QueryRecordWhere("ID = {0}", eventId);
                if (evt == null)
                {
                    return(BadRequest("Must provide a valid EventID"));
                }
                Meter meter = new TableOperations <Meter>(connection).QueryRecordWhere("ID = {0}", evt.MeterID);
                meter.ConnectionFactory = () => new AdoDataConnection(m_configuration["OpenXDA:ConnectionString"], m_configuration["OpenXDA:DataProviderString"]);

                int    calcCycle       = connection.ExecuteScalar <int?>("SELECT CalculationCycle FROM FaultSummary WHERE EventID = {0} AND IsSelectedAlgorithm = 1", evt.ID) ?? -1;
                double systemFrequency = connection.ExecuteScalar <double?>("SELECT Value FROM Setting WHERE Name = 'SystemFrequency'") ?? 60.0;

                Dictionary <string, IEnumerable <double[]> > returnData = new Dictionary <string, IEnumerable <double[]> >();
                DataGroupHelper dataGroupHelper = new DataGroupHelper(m_configuration, m_memoryCache);
                if (dataType == "Time")
                {
                    DataGroup dataGroup = dataGroupHelper.QueryDataGroup(eventId, meter);;
                    bool      hasVoltLN = dataGroup.DataSeries.Select(x => x.SeriesInfo.Channel.Phase.Name).Where(x => x.Contains("N")).Any();
                    foreach (var series in dataGroup.DataSeries)
                    {
                        List <double[]> data = series.DataPoints.Select(dp => new double[2] {
                            (dp.Time - epoch).TotalMilliseconds, dp.Value
                        }).ToList();
                        if (type == "Voltage")
                        {
                            if (series.SeriesInfo.Channel.MeasurementType.Name == "Voltage" && series.SeriesInfo.Channel.MeasurementCharacteristic.Name == "Instantaneous" && series.SeriesInfo.Channel.Phase.Name.Contains("N"))
                            {
                                returnData.Add("V" + series.SeriesInfo.Channel.Phase.Name, data);
                            }
                            else if (series.SeriesInfo.Channel.MeasurementType.Name == "Voltage" && series.SeriesInfo.Channel.MeasurementCharacteristic.Name == "Instantaneous" && !hasVoltLN)
                            {
                                returnData.Add("V" + series.SeriesInfo.Channel.Phase.Name, data);
                            }
                        }
                        else
                        {
                            if (series.SeriesInfo.Channel.MeasurementType.Name == "Current" && series.SeriesInfo.Channel.MeasurementCharacteristic.Name == "Instantaneous")
                            {
                                returnData.Add("I" + series.SeriesInfo.Channel.Phase.Name, data);
                            }
                        }
                    }
                }
                else if (dataType == "Trending")
                {
                    DateTime start = new DateTime(evt.StartTime.Year, evt.StartTime.Month, evt.StartTime.Day, evt.StartTime.Hour, 0, 0).AddHours(-3);
                    DateTime end   = start.AddHours(6);
                    IEnumerable <Channel> channels = new TableOperations <Channel>(connection).QueryRecordsWhere($"MeterID = {meter.ID} AND MeasurementTypeID = (SELECT ID FROM MeasurementType Where Name = '{type}') AND MeasurementCharacteristicID = (SELECT ID FROM MeasurementCharacteristic Where Name = 'RMS') AND PhaseID IN (SELECT ID FROM Phase Where Name IN ('AN', 'BN', 'CN'))");

                    using (API hids = new API())
                    {
                        string host        = connection.ExecuteScalar <string>("SELECT Value FROM Setting WHERE Name = 'HIDS.Host'") ?? "http://localhost:8086";
                        string tokenID     = connection.ExecuteScalar <string>("SELECT Value FROM Setting WHERE Name = 'HIDS.TokenID'") ?? "";
                        string pointBucket = connection.ExecuteScalar <string>("SELECT Value FROM Setting WHERE Name = 'HIDS.PointBucket'") ?? "point_bucket";
                        string orgID       = connection.ExecuteScalar <string>("SELECT Value FROM Setting WHERE Name = 'HIDS.OrganizationID'") ?? "gpa";

                        hids.TokenID        = tokenID;
                        hids.PointBucket    = pointBucket;
                        hids.OrganizationID = orgID;
                        hids.Connect(host);

                        List <Point> points = hids.ReadPointsAsync((t) =>
                        {
                            t.FilterTags(channels.Select(c => c.ID.ToString("x8")));
                            t.Range(start, end);
                        }).ToListAsync().Result;

                        foreach (Channel channel in channels)
                        {
                            channel.ConnectionFactory = () => new AdoDataConnection(m_configuration["OpenXDA:ConnectionString"], m_configuration["OpenXDA:DataProviderString"]);
                            returnData.Add($"{(type == "Voltage" ? "V" : "I")}{channel.Phase.Name}", points.Where(p => p.Tag == channel.ID.ToString("x8")).Select((p, index) => new[] { (p.Timestamp - epoch).TotalMilliseconds, p.Average }));
                        }
                    }
                    //MovingAverageRandomNumberGenerator generator = new MovingAverageRandomNumberGenerator((type=="Voltage" ? 1234 : 4321), 1, new[] { 0.2}, 50, 2);
                    //returnData.Add($"{(type == "Voltage" ? "V" : "I")}AN", generator.Next(36).Select((rv, index) => new[] { (start - epoch).TotalMilliseconds + index * 600000, rv.Value }));
                    //returnData.Add($"{(type == "Voltage" ? "V" : "I")}BN", generator.Next(36).Select((rv, index) => new[] { (start - epoch).TotalMilliseconds + index * 600000, rv.Value }));
                    //returnData.Add($"{(type == "Voltage" ? "V" : "I")}CN", generator.Next(36).Select((rv, index) => new[] { (start - epoch).TotalMilliseconds + index * 600000, rv.Value }));
                }

                return(Ok(returnData));
            }
        }