private string ReadLastConcurrentInfo()
        {
            DirectoryInfo   dir           = new DirectoryInfo(DataStoreDirectory);
            List <FileInfo> lXMLFilesInfo =
                dir.GetFiles(ConventionalTransitions.ImageConcurrentDataFilesNamesPattern(), SearchOption.AllDirectories)
                .ToList();

            lXMLFilesInfo.Sort((finfo1, finfo2) => finfo1.CreationTimeUtc.CompareTo(finfo2.CreationTimeUtc));

            Dictionary <string, object> dictReadXMLfileData =
                ServiceTools.ReadDictionaryFromXML(lXMLFilesInfo.Last().FullName);

            DateTime utcNow = DateTime.UtcNow;
            DateTime concurrentDataDateTime = DateTime.Parse(dictReadXMLfileData["DateTime"] as string);

            concurrentDataDateTime = concurrentDataDateTime.ToUniversalTime();

            string strDataToReport = "Current server date/time UTC: " + utcNow.ToString("dd.MM.yyyy HH:mm:ss") +
                                     Environment.NewLine;

            strDataToReport += "Concurrent data date/time UTC: " +
                               concurrentDataDateTime.ToString("dd.MM.yyyy HH:mm:ss") +
                               Environment.NewLine;
            strDataToReport += "time elapsed since last shot: " +
                               Math.Round((utcNow - concurrentDataDateTime).TotalSeconds) + "s" + Environment.NewLine;


            GPSdata gps = new GPSdata((string)dictReadXMLfileData["GPSdata"], GPSdatasources.CloudCamArduinoGPS,
                                      concurrentDataDateTime);

            strDataToReport += "GPS: " + gps.HRString(2) + Environment.NewLine;
            SPA spaCalcObject        = null;
            AzimuthZenithAngle angle = gps.SunZenithAzimuth(out spaCalcObject);


            DateTime  dtSunriseUTC  = utcNow;
            TimeOfDay todSunriseUTC = new TimeOfDay(spaCalcObject.spa.sunrise);

            dtSunriseUTC = new DateTime(dtSunriseUTC.Year, dtSunriseUTC.Month, dtSunriseUTC.Day, todSunriseUTC.hour,
                                        todSunriseUTC.minute, todSunriseUTC.second, DateTimeKind.Utc);


            // TimeZoneInfo mowTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Russian Standard Time");
            TimeZoneInfo mowTimeZone  = TimeZoneInfo.Local;
            DateTime     dtSunriseMOW = TimeZoneInfo.ConvertTimeFromUtc(dtSunriseUTC, mowTimeZone);

            strDataToReport += "Sunrise Moscow time: " + (dtSunriseMOW.TimeOfDay.ToString()) + Environment.NewLine;

            DateTime  dtSunsetUTC  = utcNow;
            TimeOfDay todSunsetUTC = new TimeOfDay(spaCalcObject.spa.sunset);

            dtSunsetUTC = new DateTime(dtSunsetUTC.Year, dtSunsetUTC.Month, dtSunsetUTC.Day, todSunsetUTC.hour,
                                       todSunsetUTC.minute, todSunsetUTC.second, DateTimeKind.Utc);
            DateTime dtSunsetMOW = TimeZoneInfo.ConvertTimeFromUtc(dtSunsetUTC, mowTimeZone);

            strDataToReport += "Sunset Moscow time: " + (dtSunsetMOW.TimeOfDay.ToString()) + Environment.NewLine;

            return(strDataToReport);
        }
        private void btnProcess_Click(object sender, EventArgs e)
        {
            string fName = richTextBox1.Text;

            if (!File.Exists(fName))
            {
                theLogWindow = ServiceTools.LogAText(theLogWindow, "couldn`t find a file: " + fName);
                return;
            }

            try
            {
                xlApp         = new Microsoft.Office.Interop.Excel.Application();
                xlApp.Visible = true;
                wb            = xlApp.Workbooks.Open(fName, Type.Missing, false);
                ws            = wb.Sheets[1];
            }
            catch (Exception)
            {
                CloseAll();
            }


            List <Tuple <int, SunElevationTestDataRecord> > lRecords = new List <Tuple <int, SunElevationTestDataRecord> >();
            int    rowIdx        = 2;
            double dDataTimeRead = 0.0d;

            while (true)
            {
                DateTime dtVal;
                SunElevationTestDataRecord currRec = new SunElevationTestDataRecord();

                System.Windows.Forms.Application.DoEvents();

                try
                {
                    Range rngDT = ws.Cells[rowIdx, 1];
                    var   dDataTimeReadValue = rngDT.Value2;
                    if (dDataTimeReadValue == null)
                    {
                        theLogWindow = ServiceTools.LogAText(theLogWindow,
                                                             "date-time value at row " + rowIdx + " is empty. Stopping reading.");
                        CloseAll();
                        break;
                    }
                    dDataTimeRead = (double)(dDataTimeReadValue);
                    if (dDataTimeRead == 0.0d)
                    {
                        theLogWindow = ServiceTools.LogAText(theLogWindow,
                                                             "date-time value at row " + rowIdx + " is empty. Stopping reading.");
                        CloseAll();
                        break;
                    }
                }
                catch (Exception ex)
                {
                    //CloseAll();
                    theLogWindow = ServiceTools.LogAText(theLogWindow, "=====================");
                    theLogWindow = ServiceTools.LogAText(theLogWindow,
                                                         ex.Message + Environment.NewLine + "for date-time value at row " + rowIdx);
                    theLogWindow = ServiceTools.LogAText(theLogWindow, "=====================");
                    lRecords.Add(new Tuple <int, SunElevationTestDataRecord>(rowIdx, currRec));
                    rowIdx++;
                    continue;
                }
                dtVal      = DateTime.FromOADate(dDataTimeRead);
                currRec.Dt = dtVal;



                double latVal = 0.0d;
                try
                {
                    Range rngLat    = ws.Cells[rowIdx, 2];
                    var   rngLatVal = rngLat.Value2;
                    if (rngLatVal == null)
                    {
                        theLogWindow = ServiceTools.LogAText(theLogWindow,
                                                             "latitude value at row " + rowIdx + " is empty");
                        //rowIdx++;
                        //continue;
                    }
                    else
                    {
                        latVal         = (double)(rngLatVal);
                        currRec.latDec = latVal;
                    }
                }
                catch (Exception ex)
                {
                    //CloseAll();
                    theLogWindow = ServiceTools.LogAText(theLogWindow, "=====================");
                    theLogWindow = ServiceTools.LogAText(theLogWindow,
                                                         ex.Message + Environment.NewLine + "for latitude value at row " + rowIdx);
                    theLogWindow = ServiceTools.LogAText(theLogWindow, "=====================");
                    lRecords.Add(new Tuple <int, SunElevationTestDataRecord>(rowIdx, currRec));
                    rowIdx++;
                    continue;
                }



                double lonVal = 0.0d;
                try
                {
                    Range rngLon    = ws.Cells[rowIdx, 3];
                    var   rngLonVal = rngLon.Value2;
                    if (rngLonVal == null)
                    {
                        theLogWindow = ServiceTools.LogAText(theLogWindow,
                                                             "longitude value at row " + rowIdx + " is empty");
                        //rowIdx++;
                        //continue;
                    }
                    else
                    {
                        lonVal         = (double)(rngLonVal);
                        currRec.lonDec = lonVal;
                    }
                }
                catch (Exception ex)
                {
                    //CloseAll();
                    theLogWindow = ServiceTools.LogAText(theLogWindow, "=====================");
                    theLogWindow = ServiceTools.LogAText(theLogWindow,
                                                         ex.Message + Environment.NewLine + "for longitude value at row " + rowIdx);
                    theLogWindow = ServiceTools.LogAText(theLogWindow, "=====================");
                    lRecords.Add(new Tuple <int, SunElevationTestDataRecord>(rowIdx, currRec));
                    rowIdx++;
                    continue;
                }



                double sunAltTestVal = 0.0d;
                try
                {
                    Range rngSunAltTest    = ws.Cells[rowIdx, 4];
                    var   rngSunAltTestVal = rngSunAltTest.Value2;
                    if (rngSunAltTestVal == null)
                    {
                        theLogWindow = ServiceTools.LogAText(theLogWindow,
                                                             "testing sun elevation value at row " + rowIdx + " is empty");
                        //rowIdx++;
                        //continue;
                    }
                    else
                    {
                        sunAltTestVal       = (double)(rngSunAltTestVal);
                        currRec.SunElevTest = sunAltTestVal;
                    }
                }
                catch (Exception ex)
                {
                    theLogWindow = ServiceTools.LogAText(theLogWindow, "=====================");
                    theLogWindow = ServiceTools.LogAText(theLogWindow,
                                                         ex.Message + Environment.NewLine + "for read sun elevation value at row " + rowIdx);
                    theLogWindow = ServiceTools.LogAText(theLogWindow, "=====================");
                    //CloseAll();
                    lRecords.Add(new Tuple <int, SunElevationTestDataRecord>(rowIdx, currRec));
                    rowIdx++;
                    continue;
                }



                ThreadSafeOperations.SetText(lblLoadingStatus, "loading " + rowIdx + " row", false);

                lRecords.Add(new Tuple <int, SunElevationTestDataRecord>(rowIdx, currRec));

                rowIdx++;
            }



            List <double> lDeviations = new List <double>();
            string        outFName    = Path.GetDirectoryName(fName) + "\\" + Path.GetFileNameWithoutExtension(fName) + "-output.txt";

            ServiceTools.logToTextFile(outFName, SunElevationTestDataRecord.TableFieldsHeader() + Environment.NewLine, true);

            foreach (Tuple <int, SunElevationTestDataRecord> tpl in lRecords)
            {
                rowIdx = tpl.Item1;
                SunElevationTestDataRecord currRec = tpl.Item2;

                if (currRec.WhetherAllValuesHasBeenRead)
                {
                    SPA spaCalc = new SPA(currRec.Dt.Year, currRec.Dt.Month, currRec.Dt.Day, currRec.Dt.Hour,
                                          currRec.Dt.Minute, currRec.Dt.Second, (float)currRec.lonDec, (float)currRec.latDec,
                                          (float)SPAConst.DeltaT(currRec.Dt));
                    int res = spaCalc.spa_calculate();
                    AzimuthZenithAngle sunPositionSPAext = new AzimuthZenithAngle(spaCalc.spa.azimuth,
                                                                                  spaCalc.spa.zenith);
                    currRec.SunElevCalc = sunPositionSPAext.ElevationAngle;

                    lDeviations.Add(currRec.SunElevCalc - currRec.SunElevTest);

                    ServiceTools.logToTextFile(outFName, currRec.ToString() + Environment.NewLine, true);
                }
                else
                {
                    ServiceTools.logToTextFile(outFName, currRec.ToString() + Environment.NewLine, true);
                }
            }


            HistogramDataAndProperties histData = new HistogramDataAndProperties(DenseVector.OfEnumerable(lDeviations), 20);
            HistogramCalcAndShowForm   histForm = new HistogramCalcAndShowForm("", defaultProperties);

            histForm.HistToRepresent = histData;
            histForm.Show();
            histForm.Represent();


            CloseAll();
        }
Ejemplo n.º 3
0
        private AngleSunDeviationCalcResult CalculateDevDataForImage(FileInfo finfo, Dictionary <string, object> defaultProperties, LogWindow currImageLogWindow, bool showOnlyErrors = false)
        {
            FileInfo currFileInfo = finfo;
            Dictionary <string, object> defaultProps = defaultProperties;


            AngleSunDeviationCalcResult retRes = new AngleSunDeviationCalcResult()
            {
                fileName = currFileInfo.FullName,
            };

            GPSdata gps = ServiceTools.FindProperGPSdataForImage(currFileInfo.FullName, theLogWindow, defaultProperties,
                                                                 ref NVdataFilesAlreadyReadDateTimeSpans, ref NVdataFilesAlreadyReadData);

            if (gps == null)
            {
                theLogWindow = ServiceTools.LogAText(theLogWindow, "Couldn`t find GPS data for this image.");
                retRes.calculationSucceeded = false;
                retRes.resultMessage        = "Couldn`t find GPS data for this image.";
                return(retRes);
            }

            #region // obsolete
            //// определяем дату-время файла
            //DateTime curDateTime = DateTime.UtcNow;

            //Image anImage = Image.FromFile(currFileInfo.FullName);
            //ImageInfo newIInfo = new ImageInfo(anImage);
            //int minute = 0;
            //String dateTime = (String)newIInfo.getValueByKey("ExifDTOrig");
            //if (dateTime == null)
            //{
            //    //попробуем вытащить из имени файла
            //    string strDateTime = currFileInfo.Name;
            //    strDateTime = strDateTime.Substring(4, 19);
            //    dateTime = strDateTime;
            //}

            //try
            //{
            //    curDateTime = CommonTools.DateTimeOfString(dateTime);
            //}
            //catch (Exception)
            //{
            //    retRes.calculationSucceeded = false;
            //    retRes.resultMessage = "couldn`t get date/time for file: " + Environment.NewLine + currFileInfo.Name;
            //    return retRes;
            //}
            //curDateTime = DateTime.SpecifyKind(curDateTime, DateTimeKind.Utc);

            //GPSdata neededGPSdata = new GPSdata();
            //string currPath = currFileInfo.DirectoryName;


            //string navFilesPath = defaultProps["IoffeMeteoNavFilesDirectory"] as string;
            //List<IoffeVesselDualNavDataConverted> lAllNavData = new List<IoffeVesselDualNavDataConverted>();

            //string[] sNavFilenames = Directory.GetFiles(navFilesPath, "*.nv2", SearchOption.AllDirectories);
            //if (!sNavFilenames.Any())
            //{
            //    retRes.calculationSucceeded = false;
            //    retRes.resultMessage = "Не найдено файлов данных навигации в директории " + navFilesPath;
            //    return retRes;
            //}
            //else
            //{
            //    foreach (string navFilename in sNavFilenames)
            //    {
            //        Tuple<DateTime, DateTime> timeSpan =
            //            IoffeVesselNavDataReader.GetNavFileDateTimeMargins(navFilename);
            //        if (timeSpan == null)
            //        {
            //            continue;
            //        }

            //        if ((curDateTime < timeSpan.Item1) || (curDateTime > timeSpan.Item2))
            //        {
            //            continue;
            //        }

            //        List<IoffeVesselDualNavDataConverted> dataHasBeenRead = IoffeVesselNavDataReader.ReadNavFile(navFilename);
            //        if (dataHasBeenRead == null)
            //        {
            //            continue;
            //        }
            //        Application.DoEvents();
            //        lAllNavData.AddRange(dataHasBeenRead);
            //    }
            //}

            //lAllNavData.Sort((gpsRecord1, gpsRecord2) =>
            //{
            //    double dev1 = Math.Abs((gpsRecord1.gps.dateTimeUTC - curDateTime).TotalMilliseconds);
            //    double dev2 = Math.Abs((gpsRecord2.gps.dateTimeUTC - curDateTime).TotalMilliseconds);
            //    return (dev1 >= dev2) ? (1) : (-1);
            //});
            //neededGPSdata = lAllNavData[0].gps;
            #endregion // obsolete

            retRes.gpsData = gps;


            #region obsolete
            //double lat = gps.LatDec;
            //double lon = gps.LonDec;


            //SPA spaCalc = new SPA(curDateTime.Year, curDateTime.Month, curDateTime.Day, curDateTime.Hour,
            //    curDateTime.Minute, curDateTime.Second, (float)lon, (float)lat,
            //    (float)SPAConst.DeltaT(curDateTime));
            //int res = spaCalc.spa_calculate();
            //AzimuthZenithAngle sunPositionSPAext = new AzimuthZenithAngle(spaCalc.spa.azimuth,
            //    spaCalc.spa.zenith);
            #endregion obsolete


            AzimuthZenithAngle sunPositionSPAext = gps.SunZenithAzimuth();

            if (!showOnlyErrors)
            {
                currImageLogWindow = ServiceTools.LogAText(currImageLogWindow,
                                                           "SPA ext sun position for " + gps.dateTimeUTC.ToString("s") + ": " + sunPositionSPAext);
            }

            retRes.sunSPAcomputedPosition = sunPositionSPAext;



            Image <Bgr, Byte> img2process = new Image <Bgr, byte>(currFileInfo.FullName);
            img2process = ImageProcessing.ImageResizer(img2process, Convert.ToInt32(defaultProps["DefaultMaxImageSize"]));
            Image <Bgr, Byte> LocalProcessingImage = ImageProcessing.SquareImageDimensions(img2process);

            RoundData sunRoundData = RoundData.nullRoundData();

            //посмотрим, нет ли уже имеющихся данных о положении и размере солнечного диска на изображении
            string sunDiskInfoFileName = ConventionalTransitions.SunDiskInfoFileName(currFileInfo.FullName);
            //string sunDiskInfoFileName = currFileInfo.DirectoryName + "\\" +
            //                             Path.GetFileNameWithoutExtension(currFileInfo.FullName) + "-SunDiskInfo.xml";

            RoundData existingRoundData             = RoundData.nullRoundData();
            Size      imgSizeUnderExistingRoundData = LocalProcessingImage.Bitmap.Size;
            object    existingRoundDataObj          = ServiceTools.ReadObjectFromXML(sunDiskInfoFileName, typeof(RoundDataWithUnderlyingImgSize));

            if (existingRoundDataObj != null)
            {
                existingRoundData             = ((RoundDataWithUnderlyingImgSize)existingRoundDataObj).circle;
                imgSizeUnderExistingRoundData = ((RoundDataWithUnderlyingImgSize)existingRoundDataObj).imgSize;
            }

            double currScale = (double)LocalProcessingImage.Width / (double)imgSizeUnderExistingRoundData.Width;
            if (currScale != 1.0d)
            {
                existingRoundData.DCenterX *= currScale;
                existingRoundData.DCenterY *= currScale;
                existingRoundData.DRadius  *= currScale;
            }
            if (!existingRoundData.IsNull)
            {
                sunRoundData = existingRoundData;
            }

            ImageProcessing imgP = new ImageProcessing(LocalProcessingImage, true);

            if (sunRoundData.IsNull)
            {
                SkyCloudClassification classificator = new SkyCloudClassification(img2process, defaultProperties);
                classificator.verbosityLevel             = 0;
                classificator.ParentForm                 = ParentForm;
                classificator.theLogWindow               = currImageLogWindow;
                classificator.ClassificationMethod       = ClassificationMethods.GrIx;
                classificator.isCalculatingUsingBgWorker = false;
                // classificator.SelfWorker = currBGWsender as BackgroundWorker;
                classificator.defaultOutputDataDirectory = (string)defaultProps["DefaultDataFilesLocation"];
                classificator.theStdDevMarginValueDefiningSkyCloudSeparation =
                    Convert.ToDouble(defaultProps["GrIxDefaultSkyCloudMarginWithoutSun"]);
                classificator.sourceImageFileName = currFileInfo.FullName;

                retRes.imageEdgesDetected = new RoundDataWithUnderlyingImgSize()
                {
                    circle  = imgP.imageRD,
                    imgSize = LocalProcessingImage.Size,
                };
                DenseMatrix dmProcessingData = (DenseMatrix)imgP.eval("grix").Clone();
                try
                {
                    sunRoundData = classificator.DetectSunWithSerieOfArcs(imgP, dmProcessingData);
                    if (!sunRoundData.IsNull)
                    {
                        RoundDataWithUnderlyingImgSize infoToSave = new RoundDataWithUnderlyingImgSize()
                        {
                            circle  = sunRoundData,
                            imgSize = LocalProcessingImage.Size,
                        };
                        ServiceTools.WriteObjectToXML(infoToSave, sunDiskInfoFileName);
                    }
                }
                catch (Exception ex)
                {
                    retRes.calculationSucceeded = false;
                    retRes.resultMessage        = ex.Message;
                    return(retRes);
                }
                ServiceTools.FlushMemory();
            }



            if (sunRoundData.IsNull)
            {
                throw new Exception(finfo.Name + ": couldn`t detect sun position");
            }
            else
            {
                retRes.sunDiskDetectedPosition = new RoundDataWithUnderlyingImgSize()
                {
                    circle  = sunRoundData,
                    imgSize = LocalProcessingImage.Size,
                };
            }



            RoundData imageDetectedRound = imgP.imageRD.Copy();
            retRes.imageEdgesDetected = new RoundDataWithUnderlyingImgSize()
            {
                circle  = imageDetectedRound,
                imgSize = LocalProcessingImage.Size,
            };

            try
            {
                double dev = retRes.computedAzimuthDeviation;
                retRes.calculationSucceeded = true;
            }
            catch (Exception ex)
            {
                retRes.calculationSucceeded = false;
                retRes.resultMessage        = ex.Message;
                return(retRes);
            }

            return(retRes);
        }