示例#1
0
        public EDDNCommunicator(Form1 caller)
        {
            _caller                     = caller;
            _SendDelayTimer             = new System.Timers.Timer(2000);
            _SendDelayTimer.AutoReset   = false;
            _SendDelayTimer.Elapsed     += new System.Timers.ElapsedEventHandler(this.SendDelayTimer_Elapsed);

            _logger                     = new SingleThreadLogger(ThreadLoggerType.EddnSubscriber);
        }
示例#2
0
        public EDDNCommunicator(Form1 caller)
        {
            _caller                   = caller;
            _SendDelayTimer           = new System.Timers.Timer(2000);
            _SendDelayTimer.AutoReset = false;
            _SendDelayTimer.Elapsed  += new System.Timers.ElapsedEventHandler(this.SendDelayTimer_Elapsed);

            _logger = new SingleThreadLogger(ThreadLoggerType.EddnSubscriber);
        }
        public void TestSingleThreadQueue()
        {
            var logger = new SingleThreadLogger();

            for (var i = 0; i < 20; ++i)
            {
                logger.Enqueue(i.ToString());
            }
        }
示例#4
0
        public EDStarmapInterface(DBConnector dbConnection)
        {
            try
            {
                m_SendQueue      = new Queue <EDSMTransmissionData>(100);
                m_LogFile        = new SingleThreadLogger(ThreadLoggerType.EDSMInterface, null, true);
                m_CurrentVersion = Enums_and_Utility_Classes.VersionHelper.Parts(System.Reflection.Assembly.GetExecutingAssembly().GetName().Version, 3);
                m_GUIInterface   = new DBGuiInterface(DB_GROUPNAME, dbConnection);

                m_SendTimer           = new System.Timers.Timer();
                m_SendTimer.AutoReset = false;
                m_SendTimer.Elapsed  += i_TransmitQueuedData;
                m_SendTimer.Start();
            }
            catch (Exception ex)
            {
                throw new Exception("Error while initialization", ex);
            }
        }
示例#5
0
        public EDStarmapInterface(DBConnector dbConnection)
        {
            try
            {
                m_SendQueue             = new Queue<EDSMTransmissionData>(100);
                m_LogFile               = new SingleThreadLogger(ThreadLoggerType.EDSMInterface, null, true);
                m_CurrentVersion        = Enums_and_Utility_Classes.VersionHelper.Parts(System.Reflection.Assembly.GetExecutingAssembly().GetName().Version, 3);
                m_GUIInterface          = new DBGuiInterface(DB_GROUPNAME, dbConnection);

                m_SendTimer             = new System.Timers.Timer();
                m_SendTimer.AutoReset   = false;
                m_SendTimer.Elapsed    += i_TransmitQueuedData;
                m_SendTimer.Start();
            }
            catch (Exception ex)
            {
                throw new Exception("Error while initialization", ex);
            }
        }
示例#6
0
        private void SubmitReferenceEvents(ref JToken latestLocationEvent, ref JToken latestFileHeader, ref SingleThreadLogger logger)
        {
            try
            {
                if (latestFileHeader != null)
                {
                    logger.Log("submit ref event : latestFileHeader");
                    // memorize the latest header
                    JournalEventRecieved.Raise(this, new JournalEventArgs()
                    {
                        EventType = JournalEvent.Fileheader, Data = latestFileHeader
                    });
                    latestFileHeader = null;
                }

                if (latestLocationEvent != null)
                {
                    logger.Log("submit ref event : latestLocationEvent");

                    // pre-check for base data which is currently not in the database.
                    BasedataEventArgs newBasedataArgItem = new BasedataEventArgs()
                    {
                        EventType = JournalEvent.Basedata,
                        System    = latestLocationEvent.Value <String>("StarSystem").NToString(""),
                        Station   = latestLocationEvent.Value <String>("StationName").NToString("")
                    };

                    if (latestLocationEvent.Value <Object>("StarPos") != null)
                    {
                        newBasedataArgItem.Coordinates = new Point3Dbl((Double)latestLocationEvent["StarPos"][0],
                                                                       (Double)latestLocationEvent["StarPos"][1],
                                                                       (Double)latestLocationEvent["StarPos"][2]);
                    }

                    BasedataEventRecieved.Raise(this, newBasedataArgItem);


                    // always inform about the latest location information
                    JournalEventRecieved.Raise(this, new JournalEventArgs()
                    {
                        EventType = JournalEvent.Location, Data = latestLocationEvent
                    });
                    latestLocationEvent = null;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error while processing reference events", ex);
            }
        }
示例#7
0
        private void JournalScannerWorker()
        {
            SingleThreadLogger      logger              = new SingleThreadLogger(ThreadLoggerType.FileScanner);
            String                  latestFile          = "";
            StreamReader            journalStreamReader = null;
            FileStream              journalFileStream   = null;
            JournalEvent            eventName;
            String                  rawEventName;
            DateTime                rawTimeStamp;
            string                  dataLine;
            JToken                  journalEntry        = "";
            List <String>           newFiles            = new List <string>();
            Boolean                 isFirstRun          = true;
            Boolean                 gotLatestEvent      = false;
            JToken                  latestLocationEvent = null;
            JToken                  latestFileHeader    = null;
            String                  lastEvent           = "";
            DateTime                lastEventTime       = DateTime.MinValue;
            List <JournalEventArgs> history             = new List <JournalEventArgs>();
            Boolean                 isZeroRun           = false;

            m_NewFileDetected = false;
            Boolean missingMessagePossible = true;
            Int32   errorCount             = 0;
            Boolean parsingError           = false;

            if (m_extLogging)
            {
                logger.Log("scanning started");
            }

            do
            {
                try
                {
                    if (!isFirstRun && missingMessagePossible && String.IsNullOrWhiteSpace(m_LastScan_JournalFile))
                    {
                        if (m_extLogging)
                        {
                            logger.Log("Can't find E:D journal file!");
                        }
                        Program.MainForm.AddComboboxLine(Program.MainForm.txtEventInfo, "Can't find E:D journal file!");
                        missingMessagePossible = false;
                    }

                    // new files needed or notified ?
                    if (String.IsNullOrWhiteSpace(m_LastScan_JournalFile) && (newFiles.Count == 0))
                    {
                        if (m_extLogging)
                        {
                            logger.Log("new files");
                        }
                        // get jounal for the first time, get only the latest
                        IOrderedEnumerable <string> journals = Directory.EnumerateFiles(m_SavedgamesPath, "Journal.*.log", SearchOption.TopDirectoryOnly).OrderByDescending(x => x);

                        if ((journals.Count() > 0) && (GetTimeValueFromFilename(journals.ElementAt <String>(0)) > 0))
                        {
                            m_LastScan_JournalFile = journals.ElementAt <String>(0);
                        }

                        if (isFirstRun)
                        {
                            isZeroRun = true;
                        }
                    }
                    else if (m_NewFileDetected || isFirstRun)
                    {
                        if (m_extLogging)
                        {
                            logger.Log("first run");
                        }

                        // check for new files
                        m_NewFileDetected = false;

                        IOrderedEnumerable <string> journals = Directory.EnumerateFiles(m_SavedgamesPath, "Journal.*.log", SearchOption.TopDirectoryOnly).OrderByDescending(File.GetLastWriteTime);

                        foreach (String newFile in journals)
                        {
                            Debug.Print(newFile);

                            // add every new file, but only if
                            //  - it's "timevalue" is newer than the "timevalue" of the current file
                            //  - it's last write time is not longer than 24 hours ago
                            if ((GetTimeValueFromFilename(newFile) > GetTimeValueFromFilename(m_LastScan_JournalFile)) && ((DateTime.UtcNow - File.GetLastWriteTime(newFile)).TotalHours < 24))
                            {
                                if (!newFiles.Contains(newFile))
                                {
                                    var pos = newFiles.FindIndex(x => (GetTimeValueFromFilename(x) > GetTimeValueFromFilename(newFile))) + 1;
                                    newFiles.Insert(pos, newFile);
                                }
                            }
                            else
                            {
                                // now comes the older files
                                break;
                            }
                        }
                    }

                    isFirstRun = false;

                    // check current file for existence, get another if necessary and existing, filter out "dead bodies"
                    if (!String.IsNullOrWhiteSpace(m_LastScan_JournalFile))
                    {
                        if (!File.Exists(m_LastScan_JournalFile))
                        {
                            if (m_extLogging)
                            {
                                logger.Log("file not existing : " + m_LastScan_JournalFile);
                            }
                            m_LastScan_JournalFile = "";
                        }
                    }

                    if (String.IsNullOrWhiteSpace(m_LastScan_JournalFile) && (newFiles.Count > 0))
                    {
                        for (int i = (newFiles.Count - 1); i >= 0; i--)
                        {
                            if (File.Exists(newFiles[i]))
                            {
                                // new "current" file
                                m_LastScan_JournalFile = newFiles[i];
                                newFiles.RemoveAt(i);
                                break;
                            }
                            else
                            {
                                // dead body
                                newFiles.RemoveAt(i);
                            }
                        }
                    }


                    if (!String.IsNullOrWhiteSpace(m_LastScan_JournalFile))
                    {
                        if (m_extLogging)
                        {
                            logger.Log("check file for new events : " + Path.GetFileName(m_LastScan_JournalFile) + " (" + gotLatestEvent + ")");
                        }

                        missingMessagePossible = false;

                        // we still have a current file
                        if (journalFileStream == null)
                        {
                            Program.DBCon.setIniValue(DB_GROUPNAME, "LastScan_JournalFile", m_LastScan_JournalFile);

                            journalFileStream   = File.Open(m_LastScan_JournalFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                            journalStreamReader = new StreamReader(journalFileStream);
                        }

                        while (!journalStreamReader.EndOfStream)
                        {
                            // get json object
                            dataLine = journalStreamReader.ReadLine();

                            if (m_extLogging)
                            {
                                logger.Log("new line from : " + Path.GetFileName(m_LastScan_JournalFile) + " : " + dataLine);
                            }

                            parsingError = false;

                            try
                            {
                                journalEntry = JsonConvert.DeserializeObject <JToken>(dataLine);
                            }
                            catch (Exception ex)
                            {
                                parsingError = true;
                                String msg = "Error while parsing json string from file '" + Path.GetFileName(m_LastScan_JournalFile) + "' : \n<" + dataLine + ">";
                                logger.Log(ErrorViewer.GetErrorMessage(ref msg, ex));
                            }

                            if (!parsingError)
                            {
                                // identify the event
                                rawEventName = journalEntry.Value <String>("event");
                                rawTimeStamp = journalEntry.Value <DateTime>("timestamp");

                                if (rawEventName == JournalEvent.Died.ToString())
                                {
                                    Debug.Print("here");
                                }

                                if ((rawEventName != null) && (rawTimeStamp != null))
                                {
                                    if (!Enum.TryParse <JournalEvent>(rawEventName, out eventName))
                                    {
                                        eventName = JournalEvent.Not_Supported;
                                    }

                                    if (gotLatestEvent)
                                    {
                                        // every recognized event is accepted as new
                                        lastEvent     = rawEventName;
                                        lastEventTime = rawTimeStamp;

                                        SubmitReferenceEvents(ref latestLocationEvent, ref latestFileHeader, ref logger);

                                        // pre-check for base data which is currently not in the database.
                                        switch (eventName)
                                        {
                                        case JournalEvent.Location:
                                        case JournalEvent.Docked:
                                        case JournalEvent.FSDJump:
                                        case JournalEvent.Resurrect:

                                            if (m_extLogging)
                                            {
                                                logger.Log("accepted (pre) : " + eventName.ToString());
                                            }
                                            Debug.Print("accepted (pre) : " + eventName.ToString());

                                            BasedataEventArgs newBasedataArgItem = new BasedataEventArgs()
                                            {
                                                EventType = JournalEvent.Basedata,
                                                System    = journalEntry.Value <String>("StarSystem").NToString(""),
                                                Station   = journalEntry.Value <String>("StationName").NToString("")
                                            };

                                            if (journalEntry.Value <Object>("StarPos") != null)
                                            {
                                                newBasedataArgItem.Coordinates = new Point3Dbl((Double)journalEntry["StarPos"][0],
                                                                                               (Double)journalEntry["StarPos"][1],
                                                                                               (Double)journalEntry["StarPos"][2]);
                                            }

                                            BasedataEventRecieved.Raise(this, newBasedataArgItem);

                                            break;
                                        }

                                        // switch what to do
                                        switch (eventName)
                                        {
                                        case JournalEvent.Fileheader:
                                        case JournalEvent.Location:

                                        case JournalEvent.Docked:
                                        case JournalEvent.Undocked:

                                        case JournalEvent.SupercruiseEntry:
                                        case JournalEvent.SupercruiseExit:

                                        case JournalEvent.Liftoff:
                                        case JournalEvent.Touchdown:

                                        case JournalEvent.FSDJump:

                                        case JournalEvent.Died:
                                        case JournalEvent.Resurrect:

                                        case JournalEvent.Scan:

                                        case JournalEvent.MissionAccepted:
                                        case JournalEvent.MissionCompleted:
                                        case JournalEvent.MissionAbandoned:
                                        case JournalEvent.MissionFailed:

                                        case JournalEvent.LoadGame:


                                            /*******************************************************/
                                            /***************       send events    ******************/
                                            /*******************************************************/
                                            if (eventName == JournalEvent.Docked)
                                            {
                                                Debug.Print("stop");
                                            }

                                            if (m_extLogging)
                                            {
                                                logger.Log("accepted : " + eventName.ToString());
                                            }
                                            Debug.Print("accepted : " + eventName.ToString());
                                            JournalEventArgs newJournalArgItem = new JournalEventArgs()
                                            {
                                                EventType = eventName, Data = journalEntry, History = history
                                            };

                                            JournalEventRecieved.Raise(this, newJournalArgItem);

                                            newJournalArgItem.History = null;
                                            history.Insert(0, newJournalArgItem);
                                            if (history.Count > 5)
                                            {
                                                history.RemoveAt(5);
                                            }

                                            break;

                                        default:
                                            Debug.Print("ignored (contact): <" + rawEventName + ">");

                                            break;
                                        }
                                    }
                                    else
                                    {
                                        if (isZeroRun)
                                        {
                                            // every recognized event is accepted as new
                                            lastEvent     = rawEventName;
                                            lastEventTime = rawTimeStamp;
                                        }

                                        // switch what to do
                                        switch (eventName)
                                        {
                                        case JournalEvent.Fileheader:
                                            latestFileHeader = journalEntry;
                                            Program.MainForm.AddComboboxLine(Program.MainForm.txtEventInfo, "Initial fileheader found");
                                            break;

                                        case JournalEvent.Location:
                                            latestLocationEvent = journalEntry;
                                            break;

                                        case JournalEvent.SupercruiseExit:
                                            if (latestLocationEvent != null)
                                            {
                                                latestLocationEvent["StarSystem"] = journalEntry["StarSystem"];
                                                latestLocationEvent["Body"]       = journalEntry["Body"];
                                                latestLocationEvent["BodyType"]   = journalEntry["BodyType"];
                                            }
                                            break;

                                        case JournalEvent.SupercruiseEntry:
                                            if (latestLocationEvent != null)
                                            {
                                                latestLocationEvent["StarSystem"]  = journalEntry["StarSystem"];
                                                latestLocationEvent["StationName"] = "";
                                                latestLocationEvent["Docked"]      = "false";
                                                latestLocationEvent["Body"]        = "";
                                                latestLocationEvent["BodyType"]    = "";
                                                latestLocationEvent["StationType"] = "";
                                            }

                                            break;

                                        case JournalEvent.FSDJump:
                                            if (latestLocationEvent != null)
                                            {
                                                latestLocationEvent["StarSystem"]  = journalEntry["StarSystem"];
                                                latestLocationEvent["StationName"] = "";
                                                latestLocationEvent["Docked"]      = "false";
                                                latestLocationEvent["StarPos"]     = journalEntry["StarPos"];
                                                latestLocationEvent["Body"]        = journalEntry["Body"];
                                                latestLocationEvent["BodyType"]    = journalEntry["BodyType"];
                                                latestLocationEvent["Faction"]     = journalEntry["Faction"];
                                                latestLocationEvent["Allegiance"]  = journalEntry["Allegiance"];
                                                latestLocationEvent["Economy"]     = journalEntry["Economy"];
                                                latestLocationEvent["Government"]  = journalEntry["Government"];
                                                latestLocationEvent["Security"]    = journalEntry["Security"];


                                                latestLocationEvent["StationType"] = "";
                                            }

                                            break;

                                        case JournalEvent.Docked:
                                            if (latestLocationEvent != null)
                                            {
                                                latestLocationEvent["StarSystem"]  = journalEntry["StarSystem"];
                                                latestLocationEvent["StationName"] = journalEntry["StationName"];
                                                latestLocationEvent["Docked"]      = "true";
                                                latestLocationEvent["StationType"] = journalEntry["StationType"];;
                                            }

                                            break;

                                        default:
                                            //Debug.Print("ignored (seeking) : <" + rawEventName + ">");
                                            break;
                                        }
                                    }
                                }
                            }
                        }

                        if (lastEventTime > DateTime.MinValue)
                        {
                            if (m_extLogging)
                            {
                                logger.Log("write new time");
                            }
                            // only rewrite if we've got a new event
                            Program.DBCon.setIniValue(DB_GROUPNAME, "LastScan_Event", lastEvent);
                            Program.DBCon.setIniValue(DB_GROUPNAME, "LastScan_TimeStamp", lastEventTime.ToString());

                            lastEventTime = DateTime.MinValue;
                        }

                        if (isZeroRun)
                        {
                            gotLatestEvent = true;
                        }

                        if (newFiles.Count > 0)
                        {
                            if (m_extLogging)
                            {
                                logger.Log("still have new files");
                            }

                            // prepare switching to next file
                            if (journalFileStream != null)
                            {
                                journalFileStream.Dispose();
                            }

                            if (journalStreamReader != null)
                            {
                                journalStreamReader.Dispose();
                            }

                            journalFileStream   = null;
                            journalStreamReader = null;

                            m_LastScan_JournalFile = "";
                        }
                        else if (!gotLatestEvent)
                        {
                            // it's the end of the actual file -> so we found the latest item
                            gotLatestEvent = true;
                            if (m_extLogging)
                            {
                                logger.Log("force latest event");
                            }
                        }

                        if (gotLatestEvent)
                        {
                            SubmitReferenceEvents(ref latestLocationEvent, ref latestFileHeader, ref logger);
                        }
                    }

                    isZeroRun  = false;
                    errorCount = 0;
                }
                catch (Exception ex)
                {
                    errorCount++;

                    Program.MainForm.AddComboboxLine(Program.MainForm.txtEventInfo, "Error while parsing E:D journal !");

                    Debug.Print("AnalyseError");

                    String msg = "Error in the journal scanner main routine";

                    logger.Log(ErrorViewer.GetErrorMessage(ref msg, ex));

                    if (lastEventTime > DateTime.MinValue)
                    {
                        // only rewrite if we've got a new event
                        Program.DBCon.setIniValue(DB_GROUPNAME, "LastScan_Event", lastEvent);
                        Program.DBCon.setIniValue(DB_GROUPNAME, "LastScan_TimeStamp", lastEventTime.ToString());

                        lastEventTime = DateTime.MinValue;
                    }

                    if (errorCount > 1)
                    {
                        // prepare switching to next file
                        if (journalFileStream != null)
                        {
                            journalFileStream.Dispose();
                        }

                        if (journalStreamReader != null)
                        {
                            journalStreamReader.Dispose();
                        }

                        journalFileStream   = null;
                        journalStreamReader = null;
                        gotLatestEvent      = false;
                    }
                }

                if (newFiles.Count == 0)
                {
                    Thread.Sleep(1000);
                    //  Because the current file is opened by ED with a permanent write stream no changed event
                    //  raises reliably in the SystemFileWatcher.  With Sleep(1000) we get every second the chance to
                    //  to detect new data with the line
                    //     while (!journalStreamReader.EndOfStream)
                }
                else
                {
                    Debug.Print("because new files : " + DateTime.UtcNow);
                }
            }while (!m_Stop);

            // clean up
            if (journalFileStream != null)
            {
                journalFileStream.Dispose();
            }

            if (journalStreamReader != null)
            {
                journalStreamReader.Dispose();
            }

            if (m_extLogging)
            {
                logger.Log("stopped !");
            }
        }
示例#8
0
        /// <summary>
        /// starts scanning of the logfile
        /// </summary>
        public void Start()
        {
            Boolean            existing = true;
            SingleThreadLogger logger   = new SingleThreadLogger(ThreadLoggerType.FileScanner);

            try
            {
                if (m_JournalScanner_Thread == null)
                {
                    m_SavedgamesPath = Program.DBCon.getIniValue <String>(IBESettingsView.DB_GROUPNAME, "JournalPath", "");

                    if (m_extLogging)
                    {
                        logger.Log("Init : read path <" + m_SavedgamesPath + ">");
                    }

                    existing = Directory.Exists(m_SavedgamesPath);

                    if (String.IsNullOrWhiteSpace(m_SavedgamesPath) || (!existing))
                    {
                        if (m_extLogging)
                        {
                            logger.Log("Init : check 1 : existing = " + existing.ToString() + " - <" + m_SavedgamesPath + ">");
                        }

                        if (SHGetKnownFolderPath(SAVED_GAMES, 0, IntPtr.Zero, out m_SavedgamesPath) != 0)
                        {
                            if (m_extLogging)
                            {
                                logger.Log("Init : check 2 : folder path = " + Environment.GetFolderPath(Environment.SpecialFolder.UserProfile));
                            }
                            m_SavedgamesPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Saved Games");
                        }

                        existing = Directory.Exists(m_SavedgamesPath);

                        if (m_extLogging)
                        {
                            logger.Log("Init : check 3 : existing = " + existing.ToString() + " - <" + m_SavedgamesPath + ">");
                        }

                        if (existing)
                        {
                            m_SavedgamesPath = Path.Combine(m_SavedgamesPath, @"Frontier Developments\Elite Dangerous");
                        }

                        existing = Directory.Exists(m_SavedgamesPath);

                        if (m_extLogging)
                        {
                            logger.Log("Init : check 4 : existing = " + existing.ToString() + " - <" + m_SavedgamesPath + ">");
                        }

                        if (!existing)
                        {
                            m_SavedgamesPath = null;
                            throw new Exception("ED-IBE can't find the \"Saved Games\" path to access the E:D journal file");
                        }
                        else
                        {
                            Program.DBCon.setIniValue(IBESettingsView.DB_GROUPNAME, "JournalPath", m_SavedgamesPath);
                        }
                    }

                    m_Stop = false;

                    m_JournalScanner_Thread              = new Thread(new ThreadStart(JournalScannerWorker));
                    m_JournalScanner_Thread.Name         = "JournalScanner_Thread";
                    m_JournalScanner_Thread.IsBackground = false;
                    m_JournalScanner_Thread.Start();

                    m_FileWatcher = new FileSystemWatcher(m_SavedgamesPath, "*.log");
                    m_FileWatcher.EnableRaisingEvents = true;

                    m_FileWatcher.Created += FileWatcher_Created;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error while starting the journal scanner", ex);
            }
        }
示例#9
0
文件: Ocr.cs 项目: carriercomm/ED-IBE
        public Ocr(Form1 callingForm)
        {
            _callingForm = callingForm;

            _logger = new SingleThreadLogger(ThreadLoggerType.Ocr);
        }
示例#10
0
文件: Ocr.cs 项目: mlof/ED-IBE
        public Ocr(Form1 callingForm)
        {
            _callingForm = callingForm;

            _logger = new SingleThreadLogger(ThreadLoggerType.Ocr);
        }
示例#11
0
        private void UpdateSystemNameFromLogFile_worker()
        {
            SingleThreadLogger logger           = new SingleThreadLogger(ThreadLoggerType.FileScanner);
            Regex RegExTest_FindBestIsland      = new Regex(String.Format("FindBestIsland:.+:.+:.+:.+", Regex.Escape(Program.DBCon.getIniValue<String>(IBE.IBESettingsView.DB_GROUPNAME, "PilotsName"))), RegexOptions.IgnoreCase);
            Regex RegExTest_Island_Claimed      = new Regex(String.Format("vvv------------ ISLAND .+ CLAIMED ------------vvv"), RegexOptions.IgnoreCase);

            do
            {
                try
                {
                    Boolean EndNow = false;
                    string Systemname = "";
                    string Locationname = "";
                    string currentLogString;
                    Match m = null;
                    Boolean Got_Jump = false;
                    List<String> PossibleLocations      = new List<string>();
                    List<LogEvent> LoggedEvents         = new List<LogEvent>();  
                    DateTime TimestampCurrentLine       = DateTime.MinValue;
                    String InfoCurrentLine              = "";
                    //DateTime Timestamp_YoungestLine     = DateTime.MaxValue;
                    Int32 LineCountRaw                  = 0;
                    Int32 LineCount                     = 0;
                    DateTime TimestampLastScanCandidate = DateTime.MinValue;
                    String InfoLastScanCandidate        = "";

                    #if extScanLog
                        logger.Log("start, RegEx = <" + String.Format("FindBestIsland:.+:.+:.+:.+", Regex.Escape(Program.RegulatedNoiseSettings.PilotsName)) + ">");
                    #endif

                    var appConfigPath = Program.DBCon.getIniValue("Settings", "GamePath");

                    if (Directory.Exists(appConfigPath))
                    {
                        //var versions = Directory.GetDirectories(appConfigPath).Where(x => x.Contains("FORC-FDEV")).ToList().OrderByDescending(x => x).ToList();
                        var versions = new String[] {appConfigPath};

                        if (versions.Count() == 0)
                        {
#if extScanLog
                                logger.Log("no dirs with <FORC-FDEV> found");
                                var versions2 = Directory.GetDirectories(appConfigPath).ToList().OrderByDescending(x => x).ToList();
                                foreach (string SubPath in versions2)
                                {
                                    logger.Log("but found <" +  SubPath + ">");   
                                }
#endif
                        }
                        else
                        {
#if extScanLog
                                logger.Log("lookin' for files in <" + versions[0] + ">");
#endif

                            // We'll just go right ahead and use the latest log...
                            var netLogs =
                                Directory.GetFiles(versions[0] + "\\Logs", "netLog*.log")
                                    .OrderByDescending(File.GetLastWriteTime)
                                    .ToArray();

                            if (netLogs.Length != 0)
                            {
                                Systemname          = "";
                                Locationname         = "";
                                LoggedEvents.Clear();
                                var newestNetLog    = netLogs[0];

                                if(!m_currentLogFile.Equals(newestNetLog, StringComparison.InvariantCultureIgnoreCase))
                                {
                                    // new logfile -> ignore the first jump again, it's simpply the "startjump" of ED, not a real jump
                                    m_InitialJumpFound = false;
                                    m_currentLogFile   = newestNetLog;

                                    Program.DBCon.setIniValue(DB_GROUPNAME, "CurrentLogfile",    m_currentLogFile);
                                    Program.DBCon.setIniValue(DB_GROUPNAME, "InitialJumpFound",  m_InitialJumpFound.ToString());

                                    m_TimestampLastScan = DateTime.MinValue;
                                    m_InfoLastScan      = "";
                                    Program.DBCon.setIniValue(DB_GROUPNAME, "TimestampLastScan", m_TimestampLastScan.ToString());
                                    Program.DBCon.setIniValue(DB_GROUPNAME, "InfoLastScan",      m_InfoLastScan);      
                                }

                                #if extScanLog
                                    Debug.Print("File opened : <" + newestNetLog + ">");
                                    logger.Log("File opened : <" + newestNetLog + ">");
                                #endif

                                FileStream Datei = new FileStream(newestNetLog, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                                Byte[] ByteBuffer = new Byte[1];
                                Byte[] LineBuffer = new Byte[SEARCH_MAXLENGTH];

                                Datei.Seek(0, SeekOrigin.End);

                                while (!EndNow && (Datei.Position >= 2))
                                {
                                    long StartPos   = -1;
                                    long EndPos     = -1;

                                    do
                                    {
                                        Datei.Read(ByteBuffer, 0, ByteBuffer.Length);
                                        //Debug.Print(ByteBuffer[0].ToString("x") + " ");
                                        if ((ByteBuffer[0] == 0x0A) || (ByteBuffer[0] == 0x0D))
                                            if (EndPos == -1)
                                            {
                                                if (ByteBuffer[0] == 0x0D)
                                                    EndPos = Datei.Position + 1;
                                                else
                                                    EndPos = Datei.Position;

                                                Datei.Seek(-3, SeekOrigin.Current);
                                            }
                                            else
                                            {
                                                if (ByteBuffer[0] == 0x0D)
                                                    StartPos = Datei.Position + 1;
                                                else
                                                    StartPos = Datei.Position;
                                            }
                                        else
                                        {
                                            if((LineCountRaw == 0) && (EndPos == -1))
                                            { 
                                                EndPos = Datei.Position;
                                            }

                                            Datei.Seek(-3, SeekOrigin.Current);
                                        }
                                            

                                    } while (StartPos == -1 && Datei.Position >= 3);

                                    LineCountRaw++;

                                    if((StartPos == -1) && ((EndPos - StartPos) > SEARCH_MINLENGTH))
                                        StartPos = 0;

                                    if ((StartPos >= 0) && ((EndPos - StartPos) <= SEARCH_MAXLENGTH))
                                    {
                                        // found a line and it's not too long
                                        // read
                                        Datei.Read(LineBuffer, 0, (int)(EndPos - StartPos));
                                        // and convert to string
                                        currentLogString = Encoding.ASCII.GetString(LineBuffer, 0, (int)(EndPos - StartPos) );

                                        Debug.Print("log - scanning :" + currentLogString);

                                        if (currentLogString != null)
                                        {

                                            // *********************************************
                                            // check the timestamp of the current line to avoid to re-analyse older data
                                            if(TryGetTimeFromLine(currentLogString, ref TimestampCurrentLine, ref InfoCurrentLine))
                                            { 
                                                if(TimestampCurrentLine < m_TimestampLastScan)
                                                { 
                                                    // everything is coming now is older
                                                    EndNow = true;
                                                }
                                                else if ((TimestampCurrentLine == m_TimestampLastScan) && (InfoCurrentLine.Equals(m_InfoLastScan)))
                                                {
                                                    // everything is coming now is older
                                                    EndNow = true;
                                                }

                                                // if it's the first line we have to save the "new youngest line" 
                                                // to avoid to re-analyse the same lines lines next scan
                                                if(LineCount == 0)
                                                {
                                                    TimestampLastScanCandidate = TimestampCurrentLine;
                                                    InfoLastScanCandidate      = InfoCurrentLine;
                                                }

                                                LineCount++;

                                                if(!EndNow)
                                                {
                                                    // first: check if we've jumped
                                                    m = RegExTest_Island_Claimed.Match(currentLogString);
                                                    if (m.Success)
                                                    {
                                                        if(!Got_Jump)
                                                        { 
                                                            LoggedEvents.Add(new LogEvent() { EventType = enLogEvents.Jump, Value = "", Time = TimestampCurrentLine});
                                                            Got_Jump = true;
                                                        }

                                                        #if extScanLog
                                                            Debug.Print("Jump Recognized");
                                                            logger.Log("Jump Recognized : " + currentLogString.Replace("\n", "").Replace("\r", ""));
                                                        #endif
                                                    }

                                                    // *********************************************
                                                    // second: looking for the systemname
                                                    if(String.IsNullOrEmpty(Systemname))
                                                    {
                                                        if (currentLogString.Contains("System:"))
                                                        {
                                                            #if extScanLog
                                                                Debug.Print("Systemstring:" + currentLogString);
                                                                logger.Log("Systemstring:" + currentLogString.Replace("\n", "").Replace("\r", ""));
                                                            #endif

                                                            // before 2.1 :
                                                            // Systemname = currentLogString.Substring(currentLogString.IndexOf("(", StringComparison.Ordinal) + 1);
                                                            // Systemname = Systemname.Substring(0, Systemname.IndexOf(")", StringComparison.Ordinal));

                                                            // since 2.1 :
                                                            currentLogString = currentLogString.Replace("\r", "").Replace("\n", "").Replace(@"\\", "");
                                                            MatchCollection matchCollection = Regex.Matches(currentLogString, @"(?<match>[^""\s]+)|\""(?<match>[^""]*)""");
                                                            Point3Dbl systemPosition = new Point3Dbl();

                                                            for (int i = 0; i < matchCollection.Count; i++)
                                                            {
                                                                if ((matchCollection[i].ToString().Equals("System:")) && (matchCollection.Count > i))
                                                                {
                                                                    Systemname = matchCollection[i+1].ToString().Replace("\"", "");
                                                                }
                                                                else if ((matchCollection[i].ToString().StartsWith("System:")) && (matchCollection[i].ToString().Length > "System:".Length))
                                                                {
                                                                    Systemname = matchCollection[i].ToString().Substring("System:".Length).Replace("\"", "");
                                                                }
                                                                else if (matchCollection[i].ToString().StartsWith("StarPos:("))
                                                                {
                                                                    try
                                                                    {
                                                                        var posParts = matchCollection[i].ToString().Replace("StarPos:(", "").Replace(")ly", "").Replace(")", "").Split(new char[] {','});    

                                                                        systemPosition.X = Double.Parse(posParts[0], System.Globalization.CultureInfo.InvariantCulture);
                                                                        systemPosition.Y = Double.Parse(posParts[1], System.Globalization.CultureInfo.InvariantCulture);
                                                                        systemPosition.Z = Double.Parse(posParts[2], System.Globalization.CultureInfo.InvariantCulture);
                                                                    }
                                                                    catch (Exception)
                                                                    {
                                                                    }
                                                                }

                                                            }


                                                            LoggedEvents.Add(new LogEvent() { EventType = enLogEvents.System, Value = Systemname, Time = TimestampCurrentLine, Position = systemPosition});

                                                            #if extScanLog
                                                                Debug.Print("System: " + systemName);
                                                                logger.Log("System: " + systemName);
                                                            #endif

                                                            // preparing search for location info
                                                            RegExTest_FindBestIsland = new Regex(String.Format("FindBestIsland:.+:.+:.+:{0}", Regex.Escape(Systemname)), RegexOptions.IgnoreCase);

                                                            #if extScanLog
                                                                logger.Log("new Regex : <" + String.Format("FindBestIsland:.+:.+:.+:{0}", Regex.Escape(systemName)) + ">");
                                                            #endif

                                                            // we may have candidates, check them and if nothing found search from the current position
                                                            foreach (string candidate in PossibleLocations)
                                                            {
                                                                #if extScanLog
                                                                    Debug.Print("check candidate : " + candidate);
                                                                    logger.Log("check candidate : " + candidate.Replace("\n", "").Replace("\r", ""));
                                                                #endif

                                                                m = RegExTest_FindBestIsland.Match(candidate);
                                                                //Debug.Print(currentLogString);
                                                                //if (currentLogString.Contains("Duke Jones"))
                                                                //    Debug.Print("Stop");
                                                                if (m.Success)
                                                                {
                                                                    #if extScanLog
                                                                        Debug.Print("locationstring from candidate : " + candidate);
                                                                        logger.Log("locationstring from candidate : " + candidate.Replace("\n", "").Replace("\r", ""));
                                                                    #endif

                                                                    getLocation(ref Locationname, m);

                                                                    DateTime CurrentTimestamp = new DateTime();
                                                                    String   CurrentInfo      = "";
                                                                    TryGetTimeFromLine(currentLogString, ref CurrentTimestamp, ref CurrentInfo);
                                                                    LoggedEvents.Add(new LogEvent() { EventType = enLogEvents.Location, Value = Locationname, Time = CurrentTimestamp});

                                                                    EndNow = true;
                                                                    break;
                                                                }
                                                            }
                                                        }
                                                        else 
                                                        {
                                                            m = RegExTest_FindBestIsland.Match(currentLogString);
                                                            if (m.Success)
                                                            {
                                                                #if extScanLog
                                                                    Debug.Print("Candidate : " + currentLogString);
                                                                    logger.Log("Candidate added : " + currentLogString.Replace("\n", "").Replace("\r", ""));
                                                                #endif

                                                                PossibleLocations.Add(currentLogString);
                                                            }
                                                        }
                                                    }
                                                }

                                                if(!EndNow)
                                                {
                                                    // if we have the systemname we're looking for the locationname
                                                    if (!string.IsNullOrEmpty(Systemname) && string.IsNullOrEmpty(Locationname))
                                                    {
                                                        m = RegExTest_FindBestIsland.Match(currentLogString);
                                                        //Debug.Print(currentLogString);
                                                        //if (currentLogString.Contains("Duke Jones"))
                                                        //    Debug.Print("Stop");
                                                        if (m.Success)
                                                        {
                                                            #if extScanLog
                                                                Debug.Print("locationstring (direct) : " + currentLogString);
                                                                logger.Log("locationstring (direct) : " + currentLogString.Replace("\n", "").Replace("\r", ""));
                                                            #endif

                                                            getLocation(ref Locationname, m);
                                                            LoggedEvents.Add(new LogEvent() { EventType = enLogEvents.Location, Value = Locationname, Time = TimestampCurrentLine});

                                                            EndNow = true;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }

                                    if(!EndNow)
                                    { 
                                        if (StartPos >= 3)
                                        {
                                            Datei.Seek(StartPos-1, SeekOrigin.Begin);
                                        }
                                        else
                                            Datei.Seek(0, SeekOrigin.Begin);
                                    }
                                }


                                if((!m_TimestampLastScan.Equals(TimestampLastScanCandidate)) || (!m_InfoLastScan.Equals(InfoLastScanCandidate)))
                                {
                                    // save only if changed
                                    m_TimestampLastScan = TimestampLastScanCandidate;
                                    m_InfoLastScan      = InfoLastScanCandidate;

                                    Program.DBCon.setIniValue(DB_GROUPNAME, "TimestampLastScan", m_TimestampLastScan.ToString());
                                    Program.DBCon.setIniValue(DB_GROUPNAME, "InfoLastScan",      m_InfoLastScan);      
                                }

                                Datei.Close();
                                Datei.Dispose();

                                #if extScanLog
                                    Debug.Print("Datei geschlossen");
                                    logger.Log("File closed");
                                #endif

                                processingLocationInfo(LoggedEvents);

                                LoggedEvents.Clear();

                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.Print("AnalyseError");
                    logger.Log(ex.Message + "\n" + ex.StackTrace + "\n\n");
                }

                #if extScanLog
                    logger.Log("sleeping...");
                    logger.Log("\n\n\n");
                    Debug.Print("\n\n\n");
                #endif

                m_LogfileScanner_ARE.WaitOne();

                #if extScanLog
                    logger.Log("awake...");
                #endif

            }while (!m_Closing);

            #if extScanLog
                Debug.Print("out");
            #endif

        }
示例#12
0
        public EDDNCommunicator()
        {
            m_lDBCon = new SQL.DBConnector(Program.DBCon.ConfigData, true);
            
            m_Reciever = new Dictionary<String, EDDNReciever>();

            _SendDelayTimer_Market                = new System.Timers.Timer(2000);
            _SendDelayTimer_Market.AutoReset      = false;
            _SendDelayTimer_Market.Elapsed        += new System.Timers.ElapsedEventHandler(this.SendDelayTimerMarket_Elapsed);

            _SendDelayTimer_Commodity             = new System.Timers.Timer(2000);
            _SendDelayTimer_Commodity.AutoReset   = false;
            _SendDelayTimer_Commodity.Elapsed     += new System.Timers.ElapsedEventHandler(this.SendDelayTimerCommodity_Elapsed);

            _SendDelayTimer_Outfitting            = new System.Timers.Timer(2000);
            _SendDelayTimer_Outfitting.AutoReset  = false;
            _SendDelayTimer_Outfitting.Elapsed    += new System.Timers.ElapsedEventHandler(this.SendDelayTimerOutfitting_Elapsed);

            _SendDelayTimer_Shipyard              = new System.Timers.Timer(2000);
            _SendDelayTimer_Shipyard.AutoReset    = false;
            _SendDelayTimer_Shipyard.Elapsed      += new System.Timers.ElapsedEventHandler(this.SendDelayTimerShipyard_Elapsed);

            _SendDelayTimer_Journal               = new System.Timers.Timer(2000);
            _SendDelayTimer_Journal.AutoReset     = false;
            _SendDelayTimer_Journal.Elapsed       += new System.Timers.ElapsedEventHandler(this.SendDelayTimerJournal_Elapsed);
                                                  
            _logger                     = new SingleThreadLogger(ThreadLoggerType.EddnSubscriber);

            m_RejectedData              = new List<String>();
            m_RawData                   = new List<String>();

            UserIdentification();
        }
示例#13
0
        private void UpdateSystemNameFromLogFile_worker()
        {
            SingleThreadLogger logger      = new SingleThreadLogger(ThreadLoggerType.FileScanner);
            Regex RegExTest_FindBestIsland = new Regex(String.Format("FindBestIsland:.+:.+:.+:.+", Regex.Escape(Program.DBCon.getIniValue <String>(IBE.IBESettingsView.DB_GROUPNAME, "PilotsName"))), RegexOptions.IgnoreCase);
            Regex RegExTest_Island_Claimed = new Regex(String.Format("vvv------------ ISLAND .+ CLAIMED ------------vvv"), RegexOptions.IgnoreCase);

            do
            {
                try
                {
                    Boolean         EndNow       = false;
                    string          Systemname   = "";
                    string          Locationname = "";
                    string          currentLogString;
                    Match           m                    = null;
                    Boolean         Got_Jump             = false;
                    List <String>   PossibleLocations    = new List <string>();
                    List <LogEvent> LoggedEvents         = new List <LogEvent>();
                    DateTime        TimestampCurrentLine = DateTime.MinValue;
                    String          InfoCurrentLine      = "";
                    //DateTime Timestamp_YoungestLine     = DateTime.MaxValue;
                    Int32    LineCountRaw = 0;
                    Int32    LineCount    = 0;
                    DateTime TimestampLastScanCandidate = DateTime.MinValue;
                    String   InfoLastScanCandidate      = "";

                    #if extScanLog
                    logger.Log("start, RegEx = <" + String.Format("FindBestIsland:.+:.+:.+:.+", Regex.Escape(Program.RegulatedNoiseSettings.PilotsName)) + ">");
                    #endif

                    var appConfigPath = Program.DBCon.getIniValue("Settings", "GamePath");

                    if (Directory.Exists(appConfigPath))
                    {
                        //var versions = Directory.GetDirectories(appConfigPath).Where(x => x.Contains("FORC-FDEV")).ToList().OrderByDescending(x => x).ToList();
                        var versions = new String[] { appConfigPath };

                        if (versions.Count() == 0)
                        {
#if extScanLog
                            logger.Log("no dirs with <FORC-FDEV> found");
                            var versions2 = Directory.GetDirectories(appConfigPath).ToList().OrderByDescending(x => x).ToList();
                            foreach (string SubPath in versions2)
                            {
                                logger.Log("but found <" + SubPath + ">");
                            }
#endif
                        }
                        else
                        {
#if extScanLog
                            logger.Log("lookin' for files in <" + versions[0] + ">");
#endif

                            // We'll just go right ahead and use the latest log...
                            var netLogs =
                                Directory.GetFiles(versions[0] + "\\Logs", "netLog*.log")
                                .OrderByDescending(File.GetLastWriteTime)
                                .ToArray();

                            if (netLogs.Length != 0)
                            {
                                Systemname   = "";
                                Locationname = "";
                                LoggedEvents.Clear();
                                var newestNetLog = netLogs[0];

                                if (!m_currentLogFile.Equals(newestNetLog, StringComparison.InvariantCultureIgnoreCase))
                                {
                                    // new logfile -> ignore the first jump again, it's simpply the "startjump" of ED, not a real jump
                                    m_InitialJumpFound = false;
                                    m_currentLogFile   = newestNetLog;

                                    Program.DBCon.setIniValue(DB_GROUPNAME, "CurrentLogfile", m_currentLogFile);
                                    Program.DBCon.setIniValue(DB_GROUPNAME, "InitialJumpFound", m_InitialJumpFound.ToString());

                                    m_TimestampLastScan = DateTime.MinValue;
                                    m_InfoLastScan      = "";
                                    Program.DBCon.setIniValue(DB_GROUPNAME, "TimestampLastScan", m_TimestampLastScan.ToString());
                                    Program.DBCon.setIniValue(DB_GROUPNAME, "InfoLastScan", m_InfoLastScan);
                                }

                                #if extScanLog
                                Debug.Print("File opened : <" + newestNetLog + ">");
                                logger.Log("File opened : <" + newestNetLog + ">");
                                #endif

                                FileStream Datei      = new FileStream(newestNetLog, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                                Byte[]     ByteBuffer = new Byte[1];
                                Byte[]     LineBuffer = new Byte[SEARCH_MAXLENGTH];

                                Datei.Seek(0, SeekOrigin.End);

                                while (!EndNow && (Datei.Position >= 2))
                                {
                                    long StartPos = -1;
                                    long EndPos   = -1;

                                    do
                                    {
                                        Datei.Read(ByteBuffer, 0, ByteBuffer.Length);
                                        //Debug.Print(ByteBuffer[0].ToString("x") + " ");
                                        if ((ByteBuffer[0] == 0x0A) || (ByteBuffer[0] == 0x0D))
                                        {
                                            if (EndPos == -1)
                                            {
                                                if (ByteBuffer[0] == 0x0D)
                                                {
                                                    EndPos = Datei.Position + 1;
                                                }
                                                else
                                                {
                                                    EndPos = Datei.Position;
                                                }

                                                Datei.Seek(-3, SeekOrigin.Current);
                                            }
                                            else
                                            {
                                                if (ByteBuffer[0] == 0x0D)
                                                {
                                                    StartPos = Datei.Position + 1;
                                                }
                                                else
                                                {
                                                    StartPos = Datei.Position;
                                                }
                                            }
                                        }
                                        else
                                        {
                                            if ((LineCountRaw == 0) && (EndPos == -1))
                                            {
                                                EndPos = Datei.Position;
                                            }

                                            Datei.Seek(-3, SeekOrigin.Current);
                                        }
                                    } while (StartPos == -1 && Datei.Position >= 3);

                                    LineCountRaw++;

                                    if ((StartPos == -1) && ((EndPos - StartPos) > SEARCH_MINLENGTH))
                                    {
                                        StartPos = 0;
                                    }

                                    if ((StartPos >= 0) && ((EndPos - StartPos) <= SEARCH_MAXLENGTH))
                                    {
                                        // found a line and it's not too long
                                        // read
                                        Datei.Read(LineBuffer, 0, (int)(EndPos - StartPos));
                                        // and convert to string
                                        currentLogString = Encoding.ASCII.GetString(LineBuffer, 0, (int)(EndPos - StartPos));

                                        Debug.Print("log - scanning :" + currentLogString);

                                        if (currentLogString != null)
                                        {
                                            // *********************************************
                                            // check the timestamp of the current line to avoid to re-analyse older data
                                            if (TryGetTimeFromLine(currentLogString, ref TimestampCurrentLine, ref InfoCurrentLine))
                                            {
                                                if (TimestampCurrentLine < m_TimestampLastScan)
                                                {
                                                    // everything is coming now is older
                                                    EndNow = true;
                                                }
                                                else if ((TimestampCurrentLine == m_TimestampLastScan) && (InfoCurrentLine.Equals(m_InfoLastScan)))
                                                {
                                                    // everything is coming now is older
                                                    EndNow = true;
                                                }

                                                // if it's the first line we have to save the "new youngest line"
                                                // to avoid to re-analyse the same lines lines next scan
                                                if (LineCount == 0)
                                                {
                                                    TimestampLastScanCandidate = TimestampCurrentLine;
                                                    InfoLastScanCandidate      = InfoCurrentLine;
                                                }

                                                LineCount++;

                                                if (!EndNow)
                                                {
                                                    // first: check if we've jumped
                                                    m = RegExTest_Island_Claimed.Match(currentLogString);
                                                    if (m.Success)
                                                    {
                                                        if (!Got_Jump)
                                                        {
                                                            LoggedEvents.Add(new LogEvent()
                                                            {
                                                                EventType = enLogEvents.Jump, Value = "", Time = TimestampCurrentLine
                                                            });
                                                            Got_Jump = true;
                                                        }

                                                        #if extScanLog
                                                        Debug.Print("Jump Recognized");
                                                        logger.Log("Jump Recognized : " + currentLogString.Replace("\n", "").Replace("\r", ""));
                                                        #endif
                                                    }

                                                    // *********************************************
                                                    // second: looking for the systemname
                                                    if (String.IsNullOrEmpty(Systemname))
                                                    {
                                                        if (currentLogString.Contains("System:"))
                                                        {
                                                            #if extScanLog
                                                            Debug.Print("Systemstring:" + currentLogString);
                                                            logger.Log("Systemstring:" + currentLogString.Replace("\n", "").Replace("\r", ""));
                                                            #endif

                                                            // before 2.1 :
                                                            // Systemname = currentLogString.Substring(currentLogString.IndexOf("(", StringComparison.Ordinal) + 1);
                                                            // Systemname = Systemname.Substring(0, Systemname.IndexOf(")", StringComparison.Ordinal));

                                                            // since 2.1 :
                                                            currentLogString = currentLogString.Replace("\r", "").Replace("\n", "").Replace(@"\\", "");
                                                            MatchCollection matchCollection = Regex.Matches(currentLogString, @"(?<match>[^""\s]+)|\""(?<match>[^""]*)""");
                                                            Point3Dbl       systemPosition  = new Point3Dbl();

                                                            for (int i = 0; i < matchCollection.Count; i++)
                                                            {
                                                                if ((matchCollection[i].ToString().Equals("System:")) && (matchCollection.Count > i))
                                                                {
                                                                    Systemname = matchCollection[i + 1].ToString().Replace("\"", "");
                                                                }
                                                                else if ((matchCollection[i].ToString().StartsWith("System:")) && (matchCollection[i].ToString().Length > "System:".Length))
                                                                {
                                                                    Systemname = matchCollection[i].ToString().Substring("System:".Length).Replace("\"", "");
                                                                }
                                                                else if (matchCollection[i].ToString().StartsWith("StarPos:("))
                                                                {
                                                                    try
                                                                    {
                                                                        var posParts = matchCollection[i].ToString().Replace("StarPos:(", "").Replace(")ly", "").Replace(")", "").Split(new char[] { ',' });

                                                                        systemPosition.X = Double.Parse(posParts[0], System.Globalization.CultureInfo.InvariantCulture);
                                                                        systemPosition.Y = Double.Parse(posParts[1], System.Globalization.CultureInfo.InvariantCulture);
                                                                        systemPosition.Z = Double.Parse(posParts[2], System.Globalization.CultureInfo.InvariantCulture);
                                                                    }
                                                                    catch (Exception)
                                                                    {
                                                                    }
                                                                }
                                                            }


                                                            LoggedEvents.Add(new LogEvent()
                                                            {
                                                                EventType = enLogEvents.System, Value = Systemname, Time = TimestampCurrentLine, Position = systemPosition
                                                            });

                                                            #if extScanLog
                                                            Debug.Print("System: " + systemName);
                                                            logger.Log("System: " + systemName);
                                                            #endif

                                                            // preparing search for location info
                                                            RegExTest_FindBestIsland = new Regex(String.Format("FindBestIsland:.+:.+:.+:{0}", Regex.Escape(Systemname)), RegexOptions.IgnoreCase);

                                                            #if extScanLog
                                                            logger.Log("new Regex : <" + String.Format("FindBestIsland:.+:.+:.+:{0}", Regex.Escape(systemName)) + ">");
                                                            #endif

                                                            // we may have candidates, check them and if nothing found search from the current position
                                                            foreach (string candidate in PossibleLocations)
                                                            {
                                                                #if extScanLog
                                                                Debug.Print("check candidate : " + candidate);
                                                                logger.Log("check candidate : " + candidate.Replace("\n", "").Replace("\r", ""));
                                                                #endif

                                                                m = RegExTest_FindBestIsland.Match(candidate);
                                                                //Debug.Print(currentLogString);
                                                                //if (currentLogString.Contains("Duke Jones"))
                                                                //    Debug.Print("Stop");
                                                                if (m.Success)
                                                                {
                                                                    #if extScanLog
                                                                    Debug.Print("locationstring from candidate : " + candidate);
                                                                    logger.Log("locationstring from candidate : " + candidate.Replace("\n", "").Replace("\r", ""));
                                                                    #endif

                                                                    getLocation(ref Locationname, m);

                                                                    DateTime CurrentTimestamp = new DateTime();
                                                                    String   CurrentInfo      = "";
                                                                    TryGetTimeFromLine(currentLogString, ref CurrentTimestamp, ref CurrentInfo);
                                                                    LoggedEvents.Add(new LogEvent()
                                                                    {
                                                                        EventType = enLogEvents.Location, Value = Locationname, Time = CurrentTimestamp
                                                                    });

                                                                    EndNow = true;
                                                                    break;
                                                                }
                                                            }
                                                        }
                                                        else
                                                        {
                                                            m = RegExTest_FindBestIsland.Match(currentLogString);
                                                            if (m.Success)
                                                            {
                                                                #if extScanLog
                                                                Debug.Print("Candidate : " + currentLogString);
                                                                logger.Log("Candidate added : " + currentLogString.Replace("\n", "").Replace("\r", ""));
                                                                #endif

                                                                PossibleLocations.Add(currentLogString);
                                                            }
                                                        }
                                                    }
                                                }

                                                if (!EndNow)
                                                {
                                                    // if we have the systemname we're looking for the locationname
                                                    if (!string.IsNullOrEmpty(Systemname) && string.IsNullOrEmpty(Locationname))
                                                    {
                                                        m = RegExTest_FindBestIsland.Match(currentLogString);
                                                        //Debug.Print(currentLogString);
                                                        //if (currentLogString.Contains("Duke Jones"))
                                                        //    Debug.Print("Stop");
                                                        if (m.Success)
                                                        {
                                                            #if extScanLog
                                                            Debug.Print("locationstring (direct) : " + currentLogString);
                                                            logger.Log("locationstring (direct) : " + currentLogString.Replace("\n", "").Replace("\r", ""));
                                                            #endif

                                                            getLocation(ref Locationname, m);
                                                            LoggedEvents.Add(new LogEvent()
                                                            {
                                                                EventType = enLogEvents.Location, Value = Locationname, Time = TimestampCurrentLine
                                                            });

                                                            EndNow = true;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }

                                    if (!EndNow)
                                    {
                                        if (StartPos >= 3)
                                        {
                                            Datei.Seek(StartPos - 1, SeekOrigin.Begin);
                                        }
                                        else
                                        {
                                            Datei.Seek(0, SeekOrigin.Begin);
                                        }
                                    }
                                }


                                if ((!m_TimestampLastScan.Equals(TimestampLastScanCandidate)) || (!m_InfoLastScan.Equals(InfoLastScanCandidate)))
                                {
                                    // save only if changed
                                    m_TimestampLastScan = TimestampLastScanCandidate;
                                    m_InfoLastScan      = InfoLastScanCandidate;

                                    Program.DBCon.setIniValue(DB_GROUPNAME, "TimestampLastScan", m_TimestampLastScan.ToString());
                                    Program.DBCon.setIniValue(DB_GROUPNAME, "InfoLastScan", m_InfoLastScan);
                                }

                                Datei.Close();
                                Datei.Dispose();

                                #if extScanLog
                                Debug.Print("Datei geschlossen");
                                logger.Log("File closed");
                                #endif

                                processingLocationInfo(LoggedEvents);

                                LoggedEvents.Clear();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.Print("AnalyseError");
                    logger.Log(ex.Message + "\n" + ex.StackTrace + "\n\n");
                }

                #if extScanLog
                logger.Log("sleeping...");
                logger.Log("\n\n\n");
                Debug.Print("\n\n\n");
                #endif

                m_LogfileScanner_ARE.WaitOne();

                #if extScanLog
                logger.Log("awake...");
                #endif
            }while (!m_Closing);

            #if extScanLog
            Debug.Print("out");
            #endif
        }
示例#14
0
        private void SubmitReferenceEvents(ref JToken latestLocationEvent, ref JToken latestFileHeader, ref SingleThreadLogger logger)
        {
            try
            {
                if (latestFileHeader != null)
                {
                    logger.Log("submit ref event : latestFileHeader");
                    // memorize the latest header
                    JournalEventRecieved.Raise(this, new JournalEventArgs() { EventType = JournalEvent.Fileheader, Data = latestFileHeader });
                    latestFileHeader = null;
                }

                if (latestLocationEvent != null)
                {
                    logger.Log("submit ref event : latestLocationEvent");

                    // pre-check for base data which is currently not in the database.
                    BasedataEventArgs newBasedataArgItem = new BasedataEventArgs() {
                                                                        EventType = JournalEvent.Basedata,
                                                                        System    = latestLocationEvent.Value<String>("StarSystem").NToString(""),
                                                                        Station   = latestLocationEvent.Value<String>("StationName").NToString("")
                                                                    };

                    if(latestLocationEvent.Value<Object>("StarPos") != null)
                    {
                        newBasedataArgItem.Coordinates   = new Point3Dbl((Double)latestLocationEvent["StarPos"][0], 
                                                                         (Double)latestLocationEvent["StarPos"][1], 
                                                                         (Double)latestLocationEvent["StarPos"][2]);
                    }

                    BasedataEventRecieved.Raise(this, newBasedataArgItem);


                    // always inform about the latest location information
                    JournalEventRecieved.Raise(this, new JournalEventArgs() { EventType = JournalEvent.Location, Data = latestLocationEvent });
                    latestLocationEvent = null;
                }

            }
            catch (Exception ex)
            {
                throw new Exception("Error while processing reference events", ex);
            }
        }
示例#15
0
        private void JournalScannerWorker()
        {
            SingleThreadLogger logger           = new SingleThreadLogger(ThreadLoggerType.FileScanner);
            String latestFile                   = "";
            StreamReader journalStreamReader    = null;
            FileStream journalFileStream        = null;
            JournalEvent eventName;
            String rawEventName;
            DateTime rawTimeStamp;
            string dataLine;
            JToken journalEntry = "";
            List<String> newFiles = new List<string>();
            Boolean isFirstRun = true;
            Boolean gotLatestEvent = false;
            JToken latestLocationEvent = null;
            JToken latestFileHeader = null;
            String lastEvent = "";
            DateTime lastEventTime = DateTime.MinValue;
            List<JournalEventArgs> history = new List<JournalEventArgs>();
            Boolean isZeroRun = false;
            m_NewFileDetected = false;
            Boolean missingMessagePossible = true;
            Int32 errorCount = 0;
            Boolean parsingError = false;

            if(m_extLogging) logger.Log("scanning started");

            do
            {
                try
                {
                    if(!isFirstRun && missingMessagePossible && String.IsNullOrWhiteSpace(m_LastScan_JournalFile))
                    {
                        if(m_extLogging) logger.Log("Can't find E:D journal file!");
                        Program.MainForm.AddComboboxLine(Program.MainForm.txtEventInfo, "Can't find E:D journal file!");                        
                        missingMessagePossible = false;
                    }

                    // new files needed or notified ?
                    if(String.IsNullOrWhiteSpace(m_LastScan_JournalFile) && (newFiles.Count == 0))
                    {
                        if(m_extLogging) logger.Log("new files");
                        // get jounal for the first time, get only the latest
                        IOrderedEnumerable<string> journals = Directory.EnumerateFiles(m_SavedgamesPath, "Journal.*.log", SearchOption.TopDirectoryOnly).OrderByDescending(x => x);

                        if ((journals.Count() > 0) && (GetTimeValueFromFilename(journals.ElementAt<String>(0)) > 0))
                            m_LastScan_JournalFile  = journals.ElementAt<String>(0);

                        if(isFirstRun)
                            isZeroRun = true;
                    }
                    else if(m_NewFileDetected || isFirstRun)
                    {
                        if(m_extLogging) logger.Log("first run");

                        // check for new files
                        m_NewFileDetected = false;

                        IOrderedEnumerable<string> journals =Directory.EnumerateFiles(m_SavedgamesPath, "Journal.*.log", SearchOption.TopDirectoryOnly).OrderByDescending(File.GetLastWriteTime);

                        foreach (String newFile in journals)
                        {
                            Debug.Print(newFile);

                            // add every new file, but only if 
                            //  - it's "timevalue" is newer than the "timevalue" of the current file
                            //  - it's last write time is not longer than 24 hours ago
                            if((GetTimeValueFromFilename(newFile) > GetTimeValueFromFilename(m_LastScan_JournalFile)) && ((DateTime.Now - File.GetLastWriteTime(newFile)).TotalHours < 24))
                            {
                                if(!newFiles.Contains(newFile))
                                {
                                    var pos = newFiles.FindIndex(x => (GetTimeValueFromFilename(x) > GetTimeValueFromFilename(newFile))) + 1;
                                    newFiles.Insert(pos, newFile); 
                                }
                            }
                            else
                            {
                                // now comes the older files
                                break;
                            }
                        }
                    }

                    isFirstRun = false;

                    // check current file for existence, get another if necessary and existing, filter out "dead bodies"
                    if (!String.IsNullOrWhiteSpace(m_LastScan_JournalFile))
                    {
                        if(!File.Exists(m_LastScan_JournalFile))
                        {
                            if(m_extLogging) logger.Log("file not existing : " + m_LastScan_JournalFile);
                            m_LastScan_JournalFile = "";
                        }
                    }

                    if(String.IsNullOrWhiteSpace(m_LastScan_JournalFile) && (newFiles.Count > 0))
                    {
                        for (int i = (newFiles.Count-1); i >= 0; i--)
                        {
                            if(File.Exists(newFiles[i]))
                            {
                                // new "current" file
                                m_LastScan_JournalFile = newFiles[i];
                                newFiles.RemoveAt(i);
                                break;
                            }
                            else
                            {
                                // dead body
                                newFiles.RemoveAt(i);
                            }
                        }
                    }
                    

                    if (!String.IsNullOrWhiteSpace(m_LastScan_JournalFile))
                    {
                        if(m_extLogging) logger.Log("check file for new events : " +  Path.GetFileName(m_LastScan_JournalFile) + " (" + gotLatestEvent +")");

                        missingMessagePossible = false;

                        // we still have a current file
                        if(journalFileStream == null)
                        {
                            Program.DBCon.setIniValue(DB_GROUPNAME,   "LastScan_JournalFile",  m_LastScan_JournalFile);

                            journalFileStream     = File.Open(m_LastScan_JournalFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                            journalStreamReader   = new StreamReader(journalFileStream);
                        }

                        while (!journalStreamReader.EndOfStream)
                        {
                            // get json object
                            dataLine     = journalStreamReader.ReadLine();

                            if(m_extLogging) logger.Log("new line from : " + Path.GetFileName(m_LastScan_JournalFile) + " : " + dataLine);

                            parsingError = false;

                            try
                            {
                                journalEntry = JsonConvert.DeserializeObject<JToken>(dataLine);
                            }
                            catch (Exception ex)
                            {
                                parsingError = true;
                                String msg = "Error while parsing json string from file '" + Path.GetFileName(m_LastScan_JournalFile) + "' : \n<" + dataLine + ">";
                                logger.Log(ErrorViewer.GetErrorMessage(ref msg, ex));
                            }

                            if(!parsingError)
                            {
                                // identify the event
                                rawEventName = journalEntry.Value<String>("event");
                                rawTimeStamp = journalEntry.Value<DateTime>("timestamp");

                                if(rawEventName == JournalEvent.Died.ToString())
                                    Debug.Print("here");

                                if ((rawEventName != null) && (rawTimeStamp != null))
                                {
                                    if(!Enum.TryParse<JournalEvent>(rawEventName, out eventName))
                                    {
                                        eventName = JournalEvent.Not_Supported;
                                    }

                                    if(gotLatestEvent)
                                    {
                                        // every recognized event is accepted as new
                                        lastEvent = rawEventName;
                                        lastEventTime = rawTimeStamp;

                                        SubmitReferenceEvents(ref latestLocationEvent, ref latestFileHeader, ref logger);

                                        // pre-check for base data which is currently not in the database.
                                        switch (eventName)
                                        {
                                            case JournalEvent.Location:
                                            case JournalEvent.Docked:
                                            case JournalEvent.FSDJump:
                                            case JournalEvent.Resurrect:

                                                if(m_extLogging) logger.Log("accepted (pre) : " + eventName.ToString());
                                                Debug.Print("accepted (pre) : " + eventName.ToString());

                                                BasedataEventArgs newBasedataArgItem = new BasedataEventArgs() {
                                                                                                  EventType = JournalEvent.Basedata,
                                                                                                  System    = journalEntry.Value<String>("StarSystem").NToString(""),
                                                                                                  Station   = journalEntry.Value<String>("StationName").NToString("")
                                                                                                };

                                                if(journalEntry.Value<Object>("StarPos") != null)
                                                {
                                                    newBasedataArgItem.Coordinates   = new Point3Dbl((Double)journalEntry["StarPos"][0], 
                                                                                                     (Double)journalEntry["StarPos"][1], 
                                                                                                     (Double)journalEntry["StarPos"][2]);
                                                }

                                                BasedataEventRecieved.Raise(this, newBasedataArgItem);

                                                break;
                                        }

                                        // switch what to do
                                        switch (eventName)
                                        {
                                            case JournalEvent.Fileheader:
                                            case JournalEvent.Location:

                                            case JournalEvent.Docked:
                                            case JournalEvent.Undocked:

                                            case JournalEvent.SupercruiseEntry:
                                            case JournalEvent.SupercruiseExit:

                                            case JournalEvent.Liftoff:
                                            case JournalEvent.Touchdown:

                                            case JournalEvent.FSDJump:

                                            case JournalEvent.Died:
                                            case JournalEvent.Resurrect:

                                            case JournalEvent.Scan:


                                                if(eventName == JournalEvent.Docked)
                                                    Debug.Print("stop");

                                                if(m_extLogging) logger.Log("accepted : " + eventName.ToString());
                                                Debug.Print("accepted : " + eventName.ToString());
                                                JournalEventArgs newJournalArgItem = new JournalEventArgs() { EventType = eventName, Data = journalEntry, History = history };

                                                JournalEventRecieved.Raise(this, newJournalArgItem);

                                                newJournalArgItem.History = null;
                                                history.Insert(0, newJournalArgItem);
                                                if(history.Count > 5)
                                                    history.RemoveAt(5);

                                                break;

                                            default:
                                                Debug.Print("ignored (contact): <" + rawEventName + ">");

                                                break;
                                        }
                                    }
                                    else
                                    {
                                        if(isZeroRun)
                                        { 
                                            // every recognized event is accepted as new
                                            lastEvent       = rawEventName;
                                            lastEventTime   = rawTimeStamp;
                                        }

                                        // switch what to do
                                        switch (eventName)
                                        {
                                            case JournalEvent.Fileheader:
                                                latestFileHeader = journalEntry;
                                                Program.MainForm.AddComboboxLine(Program.MainForm.txtEventInfo, "Initial fileheader found");                        
                                                break;

                                            case JournalEvent.Location:
                                                latestLocationEvent = journalEntry;
                                                break;

                                            case JournalEvent.SupercruiseExit:
                                                if(latestLocationEvent != null)
                                                {
                                                    latestLocationEvent["StarSystem"]   = journalEntry["StarSystem"];
                                                    latestLocationEvent["Body"]         = journalEntry["Body"];
                                                    latestLocationEvent["BodyType"]     = journalEntry["BodyType"];
                                                }
                                                break;

                                            case JournalEvent.SupercruiseEntry:
                                                if(latestLocationEvent != null)
                                                {
                                                    latestLocationEvent["StarSystem"]   = journalEntry["StarSystem"];
                                                    latestLocationEvent["StationName"]  = "";
                                                    latestLocationEvent["Docked"]       = "false";
                                                    latestLocationEvent["Body"]         = "";
                                                    latestLocationEvent["BodyType"]     = "";
                                                    latestLocationEvent["StationType"]  = "";
                                                }

                                                break;

                                            case JournalEvent.FSDJump:
                                                if(latestLocationEvent != null)
                                                {
                                                    latestLocationEvent["StarSystem"]   = journalEntry["StarSystem"];
                                                    latestLocationEvent["StationName"]  = "";
                                                    latestLocationEvent["Docked"]       = "false";
                                                    latestLocationEvent["StarPos"]      = journalEntry["StarPos"];
                                                    latestLocationEvent["Body"]         = journalEntry["Body"];
                                                    latestLocationEvent["BodyType"]     = journalEntry["BodyType"];
                                                    latestLocationEvent["Faction"]      = journalEntry["Faction"];
                                                    latestLocationEvent["Allegiance"]   = journalEntry["Allegiance"];
                                                    latestLocationEvent["Economy"]      = journalEntry["Economy"];
                                                    latestLocationEvent["Government"]   = journalEntry["Government"];
                                                    latestLocationEvent["Security"]     = journalEntry["Security"];

                                                
                                                    latestLocationEvent["StationType"]  = "";
                                                }
                                            
                                                break;

                                            case JournalEvent.Docked:
                                                if(latestLocationEvent != null)
                                                {
                                                    latestLocationEvent["StarSystem"]   = journalEntry["StarSystem"];
                                                    latestLocationEvent["StationName"]  = journalEntry["StationName"];
                                                    latestLocationEvent["Docked"]       = "true";
                                                    latestLocationEvent["StationType"]  = journalEntry["StationType"];;
                                                }

                                                break;

                                            default:
                                                Debug.Print("ignored (seeking) : <" + rawEventName + ">");
                                                break;
                                        }
                                    }
                                }
                            }
                        }

                        if(lastEventTime > DateTime.MinValue)
                        {
                            if(m_extLogging) logger.Log("write new time");
                            // only rewrite if we've got a new event
                            Program.DBCon.setIniValue(DB_GROUPNAME, "LastScan_Event",     lastEvent);
                            Program.DBCon.setIniValue(DB_GROUPNAME, "LastScan_TimeStamp", lastEventTime.ToString());

                            lastEventTime = DateTime.MinValue;
                        }

                        if(isZeroRun)
                            gotLatestEvent = true;

                        if(newFiles.Count > 0)
                        {
                            if(m_extLogging) logger.Log("still have new files");

                            // prepare switching to next file
                            if(journalFileStream != null)
                                journalFileStream.Dispose();

                            if(journalStreamReader != null)
                                journalStreamReader.Dispose();

                            journalFileStream = null;
                            journalStreamReader = null;

                            m_LastScan_JournalFile = "";
                        }
                        else if(!gotLatestEvent)
                        {
                            // it's the end of the actual file -> so we found the latest item
                            gotLatestEvent = true;
                            if(m_extLogging) logger.Log("force latest event");
                        }

                        if(gotLatestEvent)
                            SubmitReferenceEvents(ref latestLocationEvent, ref latestFileHeader, ref logger);

                    }

                    isZeroRun = false;
                    errorCount = 0;

                }
                catch (Exception ex)
                {
                    errorCount++;

                    Program.MainForm.AddComboboxLine(Program.MainForm.txtEventInfo, "Error while parsing E:D journal !");  
                                          
                    Debug.Print("AnalyseError");
                    
                    String msg = "Error in the journal scanner main routine";

                    logger.Log(ErrorViewer.GetErrorMessage(ref msg, ex));

                    if (lastEventTime > DateTime.MinValue)
                    {
                        // only rewrite if we've got a new event
                        Program.DBCon.setIniValue(DB_GROUPNAME, "LastScan_Event",     lastEvent);
                        Program.DBCon.setIniValue(DB_GROUPNAME, "LastScan_TimeStamp", lastEventTime.ToString());

                        lastEventTime = DateTime.MinValue;
                    }

                    if(errorCount > 1)
                    {
                        // prepare switching to next file
                        if(journalFileStream != null)
                            journalFileStream.Dispose();

                        if(journalStreamReader != null)
                            journalStreamReader.Dispose();

                        journalFileStream   = null;
                        journalStreamReader = null;
                        gotLatestEvent      = false;
                    }
                }

                if (newFiles.Count == 0)
                {
                    Thread.Sleep(1000);  
                    //  Because the current file is opened by ED with a permanent write stream no changed event 
                    //  raises reliably in the SystemFileWatcher.  With Sleep(1000) we get every second the chance to 
                    //  to detect new data with the line 
                    //     while (!journalStreamReader.EndOfStream)
                }
                else
                    Debug.Print("because new files : " + DateTime.Now);

            }while (!m_Stop);

            // clean up
            if(journalFileStream != null)
                journalFileStream.Dispose();

            if(journalStreamReader != null)
                journalStreamReader.Dispose();

            if(m_extLogging) logger.Log("stopped !");
        }