Exemplo n.º 1
0
        public FileDatetimeInfo(string _filename, ServiceTools.DatetimeExtractionMethod method = ServiceTools.DatetimeExtractionMethod.Filename,
                                string _datetimeFilenameMask = "?????xxxxxxxxxxxxxxxxxxx*")
        {
            filename = _filename;
            datetimeExtractionMethod = method;
            datetimeFilenameMask     = _datetimeFilenameMask;

            switch (method)
            {
            case ServiceTools.DatetimeExtractionMethod.Filename:
            {
                try
                {
                    string strDateOfFile =
                        String.Concat(
                            Path.GetFileName(filename)
                            .Zip(datetimeFilenameMask, (c, s) => (s == 'x') ? (c.ToString()) : (""))
                            .ToArray());
                    datetime = CommonTools.DateTimeOfString(strDateOfFile);
                    DateTime.SpecifyKind(datetime, DateTimeKind.Utc);
                }
                catch (Exception ex)
                {
                    throw ex;
                }

                break;
            }

            case ServiceTools.DatetimeExtractionMethod.FileCreation:
            {
                datetime = new FileInfo(filename).CreationTimeUtc;
                DateTime.SpecifyKind(datetime, DateTimeKind.Utc);
                break;
            }

            case ServiceTools.DatetimeExtractionMethod.Content:
            {
                Dictionary <string, object> currDict = ServiceTools.ReadDictionaryFromXML(filename);
                currDict.Add("XMLfileName", Path.GetFileName(filename));
                ConcurrentData retVal = null;
                try
                {
                    retVal   = new ConcurrentData(currDict);
                    datetime = retVal.datetimeUTC;
                    DateTime.SpecifyKind(datetime, DateTimeKind.Utc);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                break;
            }

            default:
            {
                break;
            }
            }
        }
        public static GPSdata FindProperGPSdataForImage(
            string imgFileName,
            object inLogWindow,
            Dictionary <string, object> defaultProperties,
            ref List <Tuple <string, DateTimeSpan> > NVdataFilesAlreadyReadDateTimeSpans,
            ref List <Tuple <string, List <IoffeVesselDualNavDataConverted> > > NVdataFilesAlreadyReadData)
        {
            DateTime curDateTime = DateTime.UtcNow;

            LogWindow theLogWindow = (LogWindow)inLogWindow;

            if (NVdataFilesAlreadyReadDateTimeSpans == null)
            {
                NVdataFilesAlreadyReadDateTimeSpans = new List <Tuple <string, DateTimeSpan> >();
            }
            if (NVdataFilesAlreadyReadData == null)
            {
                NVdataFilesAlreadyReadData = new List <Tuple <string, List <IoffeVesselDualNavDataConverted> > >();
            }

            string    ImageFileName = imgFileName;
            Image     anImage       = Image.FromFile(imgFileName);
            ImageInfo newIInfo      = new ImageInfo(anImage);

            string dateTime = (String)newIInfo.getValueByKey("ExifDTOrig");

            if (dateTime == null)
            {
                //попробуем вытащить из имени файла
                string strDateTime = Path.GetFileName(ImageFileName);
                strDateTime = strDateTime.Substring(4, 19);
                dateTime    = strDateTime;
            }

            try
            {
                curDateTime = CommonTools.DateTimeOfString(dateTime);
                if (theLogWindow != null)
                {
                    theLogWindow = ServiceTools.LogAText(theLogWindow,
                                                         "picture got date/time: " + curDateTime.ToString("s"));
                }
                else if (CommonTools.console_present())
                {
                    Console.WriteLine("picture got date/time: " + curDateTime.ToString("s"));
                }
            }
            catch (Exception ex)
            {
                if (theLogWindow != null)
                {
                    theLogWindow = ServiceTools.LogAText(theLogWindow,
                                                         "couldn`t get picture date/time for file: " + Environment.NewLine + ImageFileName);
                }
                else if (CommonTools.console_present())
                {
                    Console.WriteLine("couldn`t get picture date/time for file: " + Environment.NewLine + ImageFileName);
                }

                return(null);
            }
            curDateTime = DateTime.SpecifyKind(curDateTime, DateTimeKind.Utc);



            string strConcurrentDataXMLfilesPath = "";

            if (defaultProperties.ContainsKey("strConcurrentDataXMLfilesPath"))
            {
                strConcurrentDataXMLfilesPath = (string)defaultProperties["strConcurrentDataXMLfilesPath"];
            }
            else
            {
                strConcurrentDataXMLfilesPath = Directory.GetCurrentDirectory();
                strConcurrentDataXMLfilesPath = strConcurrentDataXMLfilesPath +
                                                ((strConcurrentDataXMLfilesPath.Last() == Path.DirectorySeparatorChar) ? ("") : (Path.DirectorySeparatorChar.ToString()));
                strConcurrentDataXMLfilesPath += "results" + Path.DirectorySeparatorChar.ToString();
            }



            GPSdata neededGPSdata = new GPSdata();
            string  currImgPath   = Path.GetDirectoryName(ImageFileName);
            string  err           = "";

            string strCurrImgConcurrentXMLdataFile = "";

            // поищем рядом с изображением
            try
            {
                strCurrImgConcurrentXMLdataFile = CommonTools.FindConcurrentDataXMLfile(ImageFileName, out err, currImgPath);
            }
            catch (Exception ex)
            {
                strCurrImgConcurrentXMLdataFile = "";
            }

            if (strCurrImgConcurrentXMLdataFile != "")
            {
                Dictionary <string, object> dictSavedData =
                    ServiceTools.ReadDictionaryFromXML(strCurrImgConcurrentXMLdataFile);
                GPSdata gps = new GPSdata((string)dictSavedData["GPSdata"], GPSdatasources.CloudCamArduinoGPS,
                                          DateTime.Parse((string)dictSavedData["GPSDateTimeUTC"], null,
                                                         DateTimeStyles.RoundtripKind));
                if (gps.validGPSdata)
                {
                    return(gps);
                }
            }

            // поищем в директории, где хранятся concurrent-данные
            try
            {
                strCurrImgConcurrentXMLdataFile = CommonTools.FindConcurrentDataXMLfile(ImageFileName, out err, strConcurrentDataXMLfilesPath);
            }
            catch (Exception ex)
            {
                strCurrImgConcurrentXMLdataFile = "";
            }

            if (strCurrImgConcurrentXMLdataFile != "")
            {
                Dictionary <string, object> dictSavedData =
                    ServiceTools.ReadDictionaryFromXML(strCurrImgConcurrentXMLdataFile);
                GPSdata gps = new GPSdata((string)dictSavedData["GPSdata"], GPSdatasources.CloudCamArduinoGPS,
                                          DateTime.Parse((string)dictSavedData["GPSDateTimeUTC"], null,
                                                         DateTimeStyles.RoundtripKind));
                if (gps.validGPSdata)
                {
                    return(gps);
                }
            }


            #region // obsolete
            //string[] xmlFileNames = Directory.GetFiles(currImgPath,
            //    "*data*" + curDateTime.ToString("s").Substring(0, 13).Replace(":", "-") + "*.xml"); // с точностью до часа
            //if (xmlFileNames.Count() > 0)
            //{
            //    List<GPSdata> lReadGPSdata = new List<GPSdata>();
            //    foreach (string xmlFileName in xmlFileNames)
            //    {
            //        Dictionary<string, object> dictSavedData = ServiceTools.ReadDictionaryFromXML(xmlFileName);
            //        //GPSdata gps = new GPSdata((string)dictSavedData["GPSdata"], GPSdatasources.CloudCamArduinoGPS);
            //        GPSdata gps =
            //            new GPSdata(new double[] { Convert.ToDouble(dictSavedData["GPSLat"]), Convert.ToDouble(dictSavedData["GPSLon"]) });
            //        lReadGPSdata.Add(gps);
            //    }
            //    lReadGPSdata.Sort((gpsRecord1, gpsRecord2) =>
            //    {
            //        double dev1 = Math.Abs((gpsRecord1.dateTimeUTC - curDateTime).TotalMilliseconds);
            //        double dev2 = Math.Abs((gpsRecord2.dateTimeUTC - curDateTime).TotalMilliseconds);
            //        return (dev1 >= dev2) ? (1) : (-1);
            //    });
            //    neededGPSdata = lReadGPSdata[0];


            //}
            //else
            //{
            #endregion // obsolete


            //string navFilesPath =
            //    "D:\\_gulevlab\\SkyImagesAnalysis_appData\\images_complete\\IOFFE\\NIKON-D80\\IOFFE-Mission34-Marina-2011\\data-meteo-nav\\";


            // Теперь среди данных навигации
            // Сначала - среди данных, которые уже были прочитаны. Если такие вообще есть.
            if (NVdataFilesAlreadyReadDateTimeSpans.Any(tpl => tpl.Item2.ContainsDateTime(curDateTime)))
            {
                string nvDataFileName =
                    NVdataFilesAlreadyReadDateTimeSpans.Where(tpl => tpl.Item2.ContainsDateTime(curDateTime)).ElementAt(0).Item1;

                if (NVdataFilesAlreadyReadData.Any(tpl => tpl.Item1 == nvDataFileName))
                {
                    List <IoffeVesselDualNavDataConverted> currFileNVdataFilesAlreadyReadData =
                        NVdataFilesAlreadyReadData.Where(tpl => tpl.Item1 == nvDataFileName).ElementAt(0).Item2;

                    currFileNVdataFilesAlreadyReadData.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 = currFileNVdataFilesAlreadyReadData[0].gps;
                    return(neededGPSdata);
                }
            }


            // если среди них не нашлось - ищем в тех, которые еще не прочитаны ранее
            string navFilesPath = defaultProperties["IoffeMeteoNavFilesDirectory"] as string;
            List <IoffeVesselDualNavDataConverted> lAllNavData = new List <IoffeVesselDualNavDataConverted>();

            string[] sNavFilenames = Directory.GetFiles(navFilesPath, "*.nv2", SearchOption.AllDirectories);
            if (!sNavFilenames.Any())
            {
                theLogWindow = ServiceTools.LogAText(theLogWindow, "Не найдено файлов данных навигации", true);
                return(null);
            }
            else
            {
                foreach (string navFilename in sNavFilenames)
                {
                    if (theLogWindow != null)
                    {
                        theLogWindow = ServiceTools.LogAText(theLogWindow, "scanning nav data file: " + navFilename, true);
                    }
                    else if (CommonTools.console_present())
                    {
                        Console.WriteLine("scanning nav data file: " + navFilename);
                    }


                    DateTimeSpan dtSpan = IoffeVesselNavDataReader.GetNavFileDateTimeMarginsDTS(navFilename);
                    if (dtSpan.IsEmpty)
                    {
                        continue;
                    }

                    NVdataFilesAlreadyReadDateTimeSpans.Add(new Tuple <string, DateTimeSpan>(navFilename, dtSpan));

                    if (!dtSpan.ContainsDateTime(curDateTime))
                    {
                        continue;
                    }

                    List <IoffeVesselDualNavDataConverted> dataHasBeenRead = IoffeVesselNavDataReader.ReadNavFile(navFilename);
                    if (dataHasBeenRead == null)
                    {
                        continue;
                    }

                    NVdataFilesAlreadyReadData.Add(new Tuple <string, List <IoffeVesselDualNavDataConverted> >(
                                                       navFilename, dataHasBeenRead));

                    if (theLogWindow != null)
                    {
                        theLogWindow = ServiceTools.LogAText(theLogWindow, "файл навигации прочитан: " + navFilename, true);
                    }
                    else if (CommonTools.console_present())
                    {
                        Console.WriteLine("файл навигации прочитан: " + navFilename);
                    }


                    Application.DoEvents();
                    lAllNavData.AddRange(dataHasBeenRead);
                }
            }

            if (!lAllNavData.Any())
            {
                if (theLogWindow != null)
                {
                    theLogWindow = ServiceTools.LogAText(theLogWindow, "Не найдено файлов данных с нужными данными", true);
                }
                else if (CommonTools.console_present())
                {
                    Console.WriteLine("Не найдено файлов данных с нужными данными");
                }

                return(null);
            }

            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;

            //}

            return(neededGPSdata);
        }
        public static string FindConcurrentDataXMLfile(string imgFileName, out string err, string basePath = "")
        {
            if (basePath == "")
            {
                basePath = Directory.GetCurrentDirectory();
                basePath = basePath +
                           ((basePath.Last() == Path.DirectorySeparatorChar)
                               ? ("")
                               : (Path.DirectorySeparatorChar.ToString()));
                basePath += "results" + Path.DirectorySeparatorChar;
            }

            DirectoryInfo dirConcurrentDataFiles = new DirectoryInfo(basePath);

            string strDateTime = Path.GetFileName(imgFileName);

            strDateTime = strDateTime.Substring(4, 19);
            DateTime currImgDateTime = CommonTools.DateTimeOfString(strDateTime);

            FileInfo[] concurrentDataFilesList =
                dirConcurrentDataFiles.GetFiles(
                    "data-" + currImgDateTime.ToString("s").Replace(":", "-").Substring(0, 16) + "*.xml",
                    SearchOption.TopDirectoryOnly);
            if (concurrentDataFilesList.Any())
            {
                List <Tuple <string, Dictionary <string, object> > > lTplConcurrentDataFilesInfo = new List <FileInfo>(
                    concurrentDataFilesList)
                                                                                                   .ConvertAll <Tuple <string, Dictionary <string, object> > >(
                    finfo =>
                {
                    Dictionary <string, object> dictSavedData =
                        ServiceTools.ReadDictionaryFromXML(concurrentDataFilesList[0].FullName) as
                        Dictionary <string, object>;
                    return(new Tuple <string, Dictionary <string, object> >(finfo.FullName, dictSavedData));
                });

                lTplConcurrentDataFilesInfo.RemoveAll(
                    tpl =>
                    !(new GPSdata((string)(tpl.Item2["GPSdata"]), GPSdatasources.CloudCamArduinoGPS,
                                  DateTime.Parse((string)tpl.Item2["GPSDateTimeUTC"], null, DateTimeStyles.RoundtripKind))).validGPSdata);

                if (!lTplConcurrentDataFilesInfo.Any())
                {
                    err = "========== ERROR: couldn`t find concurrent data file for " + imgFileName;
                    return("");
                }

                List <Tuple <string, Dictionary <string, object>, long> > lTplConcurrentData = lTplConcurrentDataFilesInfo
                                                                                               .ConvertAll(
                    tpl =>
                {
                    GPSdata currDataGPS = new GPSdata((string)(tpl.Item2["GPSdata"]),
                                                      GPSdatasources.CloudCamArduinoGPS,
                                                      DateTime.Parse((string)tpl.Item2["GPSDateTimeUTC"], null, DateTimeStyles.RoundtripKind));
                    long dt = (currDataGPS.DateTimeUTC - currImgDateTime).Ticks;
                    return(new Tuple <string, Dictionary <string, object>, long>(tpl.Item1, tpl.Item2, dt));
                });
                lTplConcurrentData.Sort(CompareTuplesByIntItem3);

                //get the first item as closest
                err = "";
                return(lTplConcurrentData[0].Item1);
            }
            else
            {
                err = "========== ERROR: couldn`t find concurrent data file for " + imgFileName;
                return("");
            }
        }