Ejemplo n.º 1
0
 public void Stop()
 {
     if (Running)
     {
         Running = false;
         try
         {
             _serverSocket.Close();
         }
         catch (Exception ex)
         {
             _logger.Log("Error in webserver start 1:", true);
             _logger.Log(ex.ToString(), true);
             _logger.Log(ex.Message, true);
             _logger.Log(ex.StackTrace, true);
             if (ex.InnerException != null)
             {
                 _logger.Log(ex.InnerException.ToString(), true);
             }
         }
         _serverSocket = null;
         if (_requestListenerT != null)
         {
             _requestListenerT.Abort();
         }
     }
 }
        static public void processError(Exception ex, string Infotext, bool noAsking)
        {
            string Info;

            // first log the complete exception
            _logger.Log(Infotext, true);
            _logger.Log(ex.ToString(), true);
            _logger.Log(ex.Message, true);
            _logger.Log(ex.StackTrace, true);
            if (ex.InnerException != null)
            {
                _logger.Log(ex.InnerException.ToString(), true);
            }

            if (Infotext.Trim().Length > 0)
            {
                Info = Infotext + Environment.NewLine + Environment.NewLine + ex.Message + Environment.NewLine;
            }
            else
            {
                Info = ex.Message + Environment.NewLine;
            }

            if (ex.InnerException != null)
            {
                Info += Environment.NewLine + ex.GetBaseException().Message;
            }

            Info += string.Format("{0}{0}(see detailed info in logfile \"{1}\")", Environment.NewLine, _logger.logPathName);

            Info += string.Format("{0}{0}Suppress exception ? (App can be unstable!)", Environment.NewLine);

            Program.CreateMiniDump("RegulatedNoiseDump_handled.dmp");

            // ask user what to do
            if (noAsking || (MessageBox.Show(Info, "Exception occured", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2) == DialogResult.No))
            {
                MessageBox.Show("Fatal error.\r\n\r\nA dump file (\"RegulatedNoiseDump_handled.dmp\" has been created in your RegulatedNoise directory.  \r\n\r\nPlease place this in a file-sharing service such as Google Drive or Dropbox, then link to the file in the Frontier forums or on the GitHub archive.  This will allow the developers to fix this problem.  \r\n\r\nThanks, and sorry about the crash...");
                Environment.Exit(-1);
            }
        }
Ejemplo n.º 3
0
        private void ProcessNewScreenshot(string screenshot)
        {
            CurrentScreenshot         = screenshot;
            CurrentScreenshotDateTime = File.GetCreationTime(CurrentScreenshot);

            if (_bOriginal != null)
            {
                _bOriginal.Dispose();
            }
            if (_bOriginalClone != null)
            {
                _bOriginalClone.Dispose();
            }

            // Well, we can get the bitmap without locking its file, like this... maybe it will help
            using (Stream s = File.OpenRead(CurrentScreenshot))
                _bOriginal = (Bitmap)Bitmap.FromStream(s);

            using (Stream s = File.OpenRead(CurrentScreenshot))
                _bOriginalClone = (Bitmap)Bitmap.FromStream(s);

            Bitmap _bAnotherClone = null;

            // I apologise for what comes next.
            try
            {
                if (_bOriginal != null)
                {
                    _bAnotherClone = (Bitmap)(_bOriginal.Clone());
                }
            }
            catch (Exception ex)
            {
                _logger.Log("Ignoring _bOriginal.Clone() error...\r\n" + ex);
            }
            _calibrationPoints = _callingForm.UpdateOriginalImage(_bAnotherClone);

            var trim = new Rectangle(_calibrationPoints[2].X, _calibrationPoints[2].Y,
                                     _calibrationPoints[10].X - _calibrationPoints[2].X, _calibrationPoints[11].Y - _calibrationPoints[2].Y);

            if (_bTrimmed != null)
            {
                _bTrimmed.Dispose();
            }
            _bTrimmed = Crop(_bOriginalClone, trim);

            var textRowLocations = new List <Tuple <int, int> >();

            var nextLine = 0;

            while (nextLine < _bTrimmed.Height - 1)
            {
                int startLine = -1, endLine = -1;
                for (int i = nextLine; i < _bTrimmed.Height - 1; i++)
                {
                    nextLine = i + 1;


                    bool hasOrangePixel;

                    using (Bitmap singlePixelRow = Crop(_bTrimmed, new Rectangle(0, i, _bTrimmed.Width, 1)))
                    {
                        hasOrangePixel = HasOrangePixel(singlePixelRow);
                    }
                    //Debug.WriteLine(i + " of " + bTrimmed.Height + ": " + hasOrangePixel);
                    if (endLine == -1 && !hasOrangePixel)
                    {
                        startLine = i;
                    }
                    else
                    {
                        if (hasOrangePixel)
                        {
                            endLine = i + 1;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                if (startLine != -1 && endLine != -1)
                {
                    textRowLocations.Add(new Tuple <int, int>(startLine, endLine));
                }
            }



            trim = new Rectangle(_calibrationPoints[0].X, _calibrationPoints[0].Y,
                                 _calibrationPoints[10].X - _calibrationPoints[0].X, _calibrationPoints[1].Y - _calibrationPoints[0].Y);

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

            _bTrimmedHeader = PreprocessScreenshot(Crop(_bOriginalClone, trim));

            _bTrimmed = PreprocessScreenshot(_bTrimmed);

            _callingForm.UpdateTrimmedImage(_bTrimmed, _bTrimmedHeader);

            int min = 100, max = 0;

            if (textRowLocations.Count < 1)
            {
                _logger.Log("No text row locations found...");
                _callingForm.GenericSingleParameterMessage(null, AppDelegateType.MaximizeWindow);
                MessageBox.Show(
                    "Couldn't find any text row locations to process.  Have you changed the UI somehow?  You might like to investigate the \"I've changed the UI colour\" button on the OCR Calibration tab...");
            }

            else
            {
                var finalRowLocation = textRowLocations[textRowLocations.Count - 1];

                foreach (var x in textRowLocations)
                {
                    if (x.Item1 != finalRowLocation.Item1)
                    {
                        if (min > x.Item2 - x.Item1)
                        {
                            min = x.Item2 - x.Item1;
                        }
                        if (max < x.Item2 - x.Item1)
                        {
                            max = x.Item2 - x.Item1;
                        }
                    }
                }

                if (finalRowLocation.Item2 - finalRowLocation.Item1 < (min - 2))
                {
                    textRowLocations.RemoveAt(textRowLocations.Count - 1);
                }
                //if(textRowLocations.ElementAt(textRowLocations.Count))
                //textRowLocations[textRow].
            }
            PerformOcr(textRowLocations);
        }
Ejemplo n.º 4
0
        public void UpdateSystemNameFromLogFile_worker()
        {
            SingleThreadLogger logger = new SingleThreadLogger(ThreadLoggerType.FileScanner);

            do
            {
                try
                {
                    DateTime TimestampCurrentLine = DateTime.MinValue;
                    DateTime TimestampLastRecognized = DateTime.MinValue;
                    Boolean EndNow = false;
                    Boolean LocationChanged = false;
                    string systemName = "";
                    string stationName = "";
                    string logLump;
                    Regex RegExTest = null;
                    Regex RegExTest2 = null;
                    Match m = null;
                    List<String> PossibleStations = new List<string>();

#if extScanLog
                    logger.Log("start, RegEx = <" + String.Format("FindBestIsland:.+:.+:.+:.+", Regex.Escape(RegulatedNoiseSettings.PilotsName)) + ">");
#endif
                    RegExTest  = new Regex(String.Format("FindBestIsland:.+:.+:.+:.+", Regex.Escape(RegulatedNoiseSettings.PilotsName)), RegexOptions.IgnoreCase);
                    RegExTest2 = new Regex(String.Format("vvv------------ ISLAND .+ CLAIMED ------------vvv"), RegexOptions.IgnoreCase);

                    var appConfigPath = RegulatedNoiseSettings.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)
                            {
                                var newestNetLog = netLogs[0];

#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 && String.IsNullOrEmpty(stationName) && (Datei.Position >= 2))
                                {
                                    long StartPos = -1;
                                    long EndPos = -1;

                                    do
                                    {
                                        Datei.Read(ByteBuffer, 0, ByteBuffer.Length);

                                        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
                                            Datei.Seek(-3, SeekOrigin.Current);

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

                                    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
                                        logLump = Encoding.ASCII.GetString(LineBuffer, 0, (int)(EndPos - StartPos) );

                                        
                                        if (logLump != null && String.IsNullOrEmpty(systemName))
                                        {
                                            // check the timestamp of the current line to avoid to re-analyse older data
                                            TimestampCurrentLine = DateTime.MaxValue;
                                            Int32 StartBracket = logLump.IndexOf('{', 0, 5);
                                            Int32 EndBracket   = logLump.IndexOf('}', 0, 15);

                                            if((StartBracket >= 0) && (EndBracket >= 0) && ((EndBracket - StartBracket) > 0))
                                                if(DateTime.TryParse(logLump.Substring(StartBracket+1, EndBracket - (StartBracket+1)), out TimestampCurrentLine))
                                                {
                                                    if(TimestampLastRecognized.Equals(DateTime.MinValue))
                                                        TimestampLastRecognized = TimestampCurrentLine;

                                                    if(TimestampCurrentLine < m_TimestampLastScan)
                                                    { 
                                                        // everything is coming now is older
                                                        EndNow = true;
                                                    }
                                                }

                                            if(!EndNow)
                                            {
                                                // first looking for the systemname
                                                if (logLump.Contains("System:"))
                                                {
    #if extScanLog
                                                    Debug.Print("Systemstring:" + logLump);
                                                    logger.Log("Systemstring:" + logLump.Replace("\n", "").Replace("\r", ""));
    #endif
                                                    systemName = logLump.Substring(logLump.IndexOf("(", StringComparison.Ordinal) + 1);
                                                    systemName = systemName.Substring(0, systemName.IndexOf(")", StringComparison.Ordinal));

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

                                                    // preparing search for station info
                                                    RegExTest = 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

                                                    // start search at the beginning

                                                    if (RegExTest != null)
                                                    {
                                                        // we may have candidates, check them and if nothing found search from the current position
                                                        foreach (string candidate in PossibleStations)
                                                        {
    #if extScanLog
                                                            Debug.Print("check candidate : " + candidate);
                                                            logger.Log("check candidate : " + candidate.Replace("\n", "").Replace("\r", ""));
    #endif
                                                            m = RegExTest.Match(candidate);
                                                            //Debug.Print(logLump);
                                                            //if (logLump.Contains("Duke Jones"))
                                                            //    Debug.Print("Stop");
                                                            if (m.Success)
                                                            {
    #if extScanLog
                                                                Debug.Print("Stationstring from candidate : " + candidate);
                                                                logger.Log("Stationstring from candidate : " + candidate.Replace("\n", "").Replace("\r", ""));
    #endif
                                                                getStation(ref stationName, m);
                                                                break;
                                                            }

                                                        }
                                                    }
                                                    else
                                                    {
                                                        // we must start from the end
                                                        Datei.Seek(0, SeekOrigin.End);
                                                    }
                                                }
                                                else if (RegExTest != null)
                                                {
                                                    m = RegExTest.Match(logLump);
                                                    //Debug.Print(logLump);
                                                    //if (logLump.Contains("Duke Jones"))
                                                    //    Debug.Print("Stop");
                                                    if (m.Success)
                                                    {
    #if extScanLog
                                                        Debug.Print("Candidate : " + logLump);
                                                        logger.Log("Candidate added : " + logLump.Replace("\n", "").Replace("\r", ""));
    #endif
                                                        PossibleStations.Add(logLump);
                                                    }
                                                    else
                                                    {
                                                        Debug.Print(logLump);
                                                        m = RegExTest2.Match(logLump);
                                                        if (m.Success)
                                                        {
                                                            LocationChanged = true;
        #if extScanLog
                                                            Debug.Print("Location changed");
                                                            logger.Log("Location changed : " + logLump.Replace("\n", "").Replace("\r", ""));
        #endif
                                                        }

                                                    }

                                                }
                                            }
                                        }

                                        if(!EndNow)
                                        { 
                                            // if we have the systemname we're looking for the stationname
                                            if (!string.IsNullOrEmpty(systemName) && string.IsNullOrEmpty(stationName))
                                            {
                                                m = RegExTest.Match(logLump);
                                                //Debug.Print(logLump);
                                                //if (logLump.Contains("Duke Jones"))
                                                //    Debug.Print("Stop");
                                                if (m.Success)
                                                {
    #if extScanLog
                                                    Debug.Print("Stationstring (direct) : " + logLump);
                                                    logger.Log("Stationstring (direct) : " + logLump.Replace("\n", "").Replace("\r", ""));
    #endif
                                                    getStation(ref stationName, m);
                                                }
                                            }
                                        }
                                    }

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

                                if(m_TimestampLastScan < TimestampLastRecognized)
                                    m_TimestampLastScan = TimestampLastRecognized;

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

                                setLocationInfo(systemName, stationName, LocationChanged);

                            }
                        }
                    }
                }
                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 (!this.Disposing && !m_Closing);

#if extScanLog
            Debug.Print("out");
#endif
        }
Ejemplo n.º 5
0
        public Form1()
        {
            _InitDone = false ;

            InstanceObject = this;

            _Splash = new SplashScreenForm();

#if !ep_Debug
            _Splash.Show();
#endif
            Cursor = Cursors.WaitCursor;

            try
            {

                _logger = new SingleThreadLogger(ThreadLoggerType.Form);
                _logger.Log("Initialising...\n");

                _Splash.InfoAdd("load settings...");
                LoadSettings();
                _logger.Log("  - settings loaded");
                _Splash.InfoChange("load settings...<OK>");
                
                string FormName = this.GetType().Name;
                if(RegulatedNoiseSettings.WindowBaseData.ContainsKey(FormName))
                    _Splash.setPosition(RegulatedNoiseSettings.WindowBaseData[FormName]);

                _Splash.InfoAdd("initialize components...");
                InitializeComponent();
                _logger.Log("  - initialised component");
                _Splash.InfoChange("initialize components...<OK>");

                _Splash.InfoAdd("doing special work if something to do...");
                doSpecial(enDoSpecial.onStart);
                _logger.Log("  - special things done");
                _Splash.InfoChange("doing special work if something to do...<OK>");

                _Splash.InfoAdd("load settings...");
                SetProductPath();
                _logger.Log("  - product path set");
                _Splash.InfoChange("load settings...<OK>");

                SetProductAppDataPath();
                _logger.Log("  - product appdata set");

                _Splash.InfoAdd("load game settings...");
                GameSettings = new GameSettings(this);
                _logger.Log("  - loaded game settings");
                _Splash.InfoChange("load game settings...<OK>");

                _Splash.InfoAdd("prepare listviews...");
                SetListViewColumnsAndSorters();
                _logger.Log("  - set list views");
                _Splash.InfoChange("prepare listviews...<OK>");

                _Splash.InfoAdd("prepare network interfaces...");
                PopulateNetworkInterfaces();
                _logger.Log("  - populated network interfaces");
                _Splash.InfoChange("prepare network interfaces...<OK>");

                _Splash.InfoAdd("create OCR object...");
                ocr = new Ocr(this);
                _logger.Log("  - created OCR object");
                _Splash.InfoChange("create OCR object...<OK>");

                Application.ApplicationExit += Application_ApplicationExit;
                _logger.Log("  - set application exit handler");

                _Splash.InfoAdd("create ocr calibrator...");
                OcrCalibrator = new OcrCalibrator();
                OcrCalibrator.LoadCalibration();
                var OcrCalibratorTabPage = new TabPage("OCR Calibration");
                OcrCalibratorTabPage.Name = "OCR_Calibration";
                var oct = new OcrCalibratorTab { Dock = DockStyle.Fill };
                OcrCalibratorTabPage.Controls.Add(oct);
                tabCtrlOCR.Controls.Add(OcrCalibratorTabPage);
                _logger.Log("  - initialised Ocr Calibrator");
                _Splash.InfoChange("create ocr calibrator...<OK>");

                _Splash.InfoAdd("prepare EDDN interface...");
                EDDNComm = new RegulatedNoise.EDDN.EDDNCommunicator(this);
                _logger.Log("  - created EDDN object");
                _Splash.InfoChange("prepare EDDN interface...<OK>");
                
                ImportSystemLocations();
                _logger.Log("  - system locations imported");

                doSpecial(enDoSpecial.afterMilkyway);

                _Splash.InfoAdd("prepare 'Commander's Log'...");
                CommandersLog = new CommandersLog(this);
                dtpLogEventDate.CustomFormat = System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat.ShortDatePattern + " " + 
                                                            System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat.LongTimePattern;
                dtpLogEventDate.Format       = System.Windows.Forms.DateTimePickerFormat.Custom;

                _logger.Log("  - created Commander's Log object");
                CommandersLog.LoadLog(true);
                _logger.Log("  - loaded Commander's Log");
                CommandersLog.UpdateCommandersLogListView();
                _logger.Log("  - updated Commander's Log List View");
                _Splash.InfoChange("prepare 'Commander's Log'...<OK>");
                
                _Splash.InfoAdd("load collected market data...");
                if (File.Exists("AutoSave.csv"))
                {
                    _logger.Log("  - found autosaved CSV");
                    var s = new string[1];
                    s[0] = "AutoSave.csv";
                    ImportListOfCsvs(s);
                    _logger.Log("  - imported CSVs");
                    SetupGui();
                    _logger.Log("  - Updated UI");
                }
                _Splash.InfoChange("load collected market data...<OK>");

                _Splash.InfoAdd("load station history...");
                _StationHistory.loadHistory(@".\Data\StationHistory.json", true);
                _Splash.InfoChange("load station history...<OK>");

                _Splash.InfoAdd("apply settings...");
                ApplySettings();
                _Splash.InfoChange("apply settings...<OK>");

                _logger.Log("  - applied settings");

                if (!Directory.Exists(".//OCR Correction Images"))
                    Directory.CreateDirectory(".//OCR Correction Images");

                _logger.Log("Initialisation complete");



                // two methods with the same functionality 
                // maybe this was the better way but I've already improved the other 
                // way (UpdateSystemNameFromLogFile()) 
                // maybe this will some day be reactivated
                //var edl = new EdLogWatcher();

                //subscribe to edlogwatcherevents
                //edl.ClientArrivedtoNewSystem += (OnClientArrivedtoNewSystem);

                //After event subscriptino we can initialize
                //edl.Initialize();
                //edl.StartWatcher();

                _Splash.InfoAdd("load and prepare international commodity names...");
                // read the commodities and prepare language depending list
                prepareCommodityNames();

                // depending of the language this will be removed
                _EDDNTabPageIndex = tabCtrlMain.TabPages.IndexOfKey("tabEDDN");
                _EDDNTabPage = tabCtrlMain.TabPages[_EDDNTabPageIndex];

                // set language
                setLanguageCombobox();

                // load commodities in the correct language
                loadCommodities(RegulatedNoiseSettings.Language);
                loadCommodityLevels(RegulatedNoiseSettings.Language);
                _Splash.InfoChange("load and prepare international commodity names...<OK>");

                // check consistency of different commodity dictionaries
                _Milkyway.addLocalized2RN(_commodities.Names);

                setOCRCalibrationTabVisibility();

                _Splash.InfoAdd("load tool tips...");
                loadToolTips();
                _Splash.InfoChange("load tool tips...<OK>");

                _Splash.InfoAdd("prepare system/location view...");
                prePrepareSystemAndStationFields();
                _Splash.InfoChange("prepare system/location view...<OK>");

                _Splash.InfoAdd("prepare GUI elements...");
                SetupGui(true);
                _Splash.InfoChange("prepare GUI elements...<OK>");

                _Splash.InfoAdd("starting logfile watcher...");
                UpdateSystemNameFromLogFile();
                _logger.Log("  - fetched system name from file");
                _Splash.InfoChange("starting logfile watcher...<OK>");

            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                cErr.processError(ex, "Error in main init function");    
            }

            _Splash.InfoAdd("\nstart sequence finished !!!");

            Cursor = Cursors.Default;
            _InitDone = true;
        }
Ejemplo n.º 6
0
        public bool Start(IPAddress ipAddress, int port, int maxNOfCon, string contentPath, Form1 callingForm)
        {
            _callingForm = callingForm;

            _logger = new SingleThreadLogger(ThreadLoggerType.Webserver);

            if (Running) return false; // If it is already running, exit.
            Running = true;
            //try
            {
                // A tcp/ip socket (ipv4)
                _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
                               ProtocolType.Tcp);
                _serverSocket.Bind(new IPEndPoint(ipAddress, port));
                _serverSocket.Listen(maxNOfCon);
                _serverSocket.ReceiveTimeout = timeout;
                _serverSocket.SendTimeout = timeout;
                
                this._contentPath = contentPath;
            }
            //catch { return false; }

            // Our thread that will listen connection requests
            // and create new threads to handle them.
            _requestListenerT = new Thread(() =>
            {
                while (Running)
                {
                    Socket clientSocket;
                    try
                    {
                        clientSocket = _serverSocket.Accept();
                        // Create new thread to handle the request and continue to listen the socket.
                        Thread requestHandler = new Thread(() =>
                        {
                            clientSocket.ReceiveTimeout = timeout;
                            clientSocket.SendTimeout = timeout;
                            try { HandleRequest(clientSocket); }
                            catch (Exception)
                            {


                                try { clientSocket.Close(); }
                                catch (Exception ex2)
                                {
                                _logger.Log("Error in webserver start 2:", true);
                                _logger.Log(ex2.ToString(), true);
                                _logger.Log(ex2.Message, true);
                                _logger.Log(ex2.StackTrace, true);
                                if (ex2.InnerException != null)
                                    _logger.Log(ex2.InnerException.ToString(), true);

                                }
                            }
                        });
                        requestHandler.Start();
                    }
                    catch (Exception ex)
                    {
                        _logger.Log("Error in webserver start 1:", true);
                        _logger.Log(ex.ToString(), true);
                        _logger.Log(ex.Message, true);
                        _logger.Log(ex.StackTrace, true);
                        if (ex.InnerException != null)
                            _logger.Log(ex.InnerException.ToString(), true);
                    }
                }
            });
            _requestListenerT.Start();

            return true;
        }
Ejemplo n.º 7
0
        private void ProcessNewScreenshot(string screenshot)
        {
            CurrentScreenshot         = screenshot;
            CurrentScreenshotDateTime = File.GetCreationTime(CurrentScreenshot);

            if (_bOriginal != null)
            {
                _bOriginal.Dispose();
            }
            if (_bOriginalClone != null)
            {
                _bOriginalClone.Dispose();
            }
            if (_bTrimmed_4_View != null)
            {
                _bTrimmed_4_View.Dispose();
            }
            if (_bTrimmed_4_OCR != null)
            {
                _bTrimmed_4_OCR.Dispose();
            }
            if (_bTrimmedHeader != null)
            {
                _bTrimmedHeader.Dispose();
            }

            // Well, we can get the bitmap without locking its file, like this... maybe it will help
            using (Stream s = File.OpenRead(CurrentScreenshot))
                _bOriginal = (Bitmap)Bitmap.FromStream(s);

            using (Stream s = File.OpenRead(CurrentScreenshot))
                _bOriginalClone = (Bitmap)Bitmap.FromStream(s);

            Bitmap _bAnotherClone = null;

            // I apologise for what comes next.
            try
            {
                if (_bOriginal != null)
                {
                    _bAnotherClone = (Bitmap)(_bOriginal.Clone());
                }
            }
            catch (Exception ex)
            {
                _logger.Log("Ignoring _bOriginal.Clone() error...\r\n" + ex);
            }
            _calibrationPoints = _callingForm.UpdateOriginalImage(_bAnotherClone);

            // get the area of the commodity data
            var trim_4_CommodityArea = new Rectangle(_calibrationPoints[2].X, _calibrationPoints[2].Y,
                                                     _calibrationPoints[10].X - _calibrationPoints[2].X,
                                                     _calibrationPoints[11].Y - _calibrationPoints[2].Y);

            // RNGraphics.Crop image to the commodity area
            _bTrimmed_4_OCR = RNGraphics.Crop(_bOriginalClone, trim_4_CommodityArea);

            // save the still colored area for viewing reasons
            _bTrimmed_4_View = (Bitmap)(_bTrimmed_4_OCR.Clone());

            // set all dark colors to black - this removes all crap
            _bTrimmed_4_OCR = RNGraphics.changeColour(_bTrimmed_4_OCR, Color.Black, Color.Black, Form1.RegulatedNoiseSettings.GUIColorCutoffLevel, RNGraphics.enPixelCompare.pc_RGB_all);

            // find automatically the textlines in the commodity area
            var textRowLocations = new List <Tuple <int, int> >();
            var nextLine         = 0;

            while (nextLine < _bTrimmed_4_OCR.Height - 1)
            {
                int startLine = -1, endLine = -1;
                for (int i = nextLine; i < _bTrimmed_4_OCR.Height - 1; i++)
                {
                    nextLine = i + 1;
                    bool hasOrangePixel;
                    using (Bitmap singlePixelRow = RNGraphics.Crop(_bTrimmed_4_OCR, new Rectangle(0, i, _bTrimmed_4_OCR.Width, 1)))
                    {
                        hasOrangePixel = RNGraphics.hasGUIColoredPixel(singlePixelRow);
                    }
                    //Debug.WriteLine(i + " of " + bTrimmed.Height + ": " + hasOrangePixel);
                    if (endLine == -1 && !hasOrangePixel)
                    {
                        startLine = i;
                    }
                    else
                    if (hasOrangePixel)
                    {
                        endLine = i + 1;
                    }
                    else
                    {
                        break;
                    }
                }
                if (startLine != -1 && endLine != -1)
                {
                    textRowLocations.Add(new Tuple <int, int>(startLine, endLine));
                }
            }

            // get the area of the header
            var trim_4_Header = new Rectangle(_calibrationPoints[0].X, _calibrationPoints[0].Y,
                                              _calibrationPoints[10].X - _calibrationPoints[0].X,
                                              _calibrationPoints[1].Y - _calibrationPoints[0].Y);

            // RNGraphics.Crop image to the header area and preprocess for OCR
            _bTrimmedHeader = RNGraphics.PreprocessScreenshot(RNGraphics.Crop(_bOriginalClone, trim_4_Header), 1, Form1.RegulatedNoiseSettings.GUIColorCutoffLevel);

            // now process screenshot for OCR and Elitebrainerous
            _bTrimmed_4_OCR = RNGraphics.PreprocessScreenshot(_bTrimmed_4_OCR, 1, Form1.RegulatedNoiseSettings.GUIColorCutoffLevel);

            // show preprocessed parts on the GUI
            _callingForm.UpdateTrimmedImage(_bTrimmed_4_OCR, _bTrimmedHeader);

            int min = 100, max = 0;

            if (textRowLocations.Count > 0)
            {
                // check if the last line is complete or RNGraphics.Cropped -> if it's RNGraphics.Cropped we delete it
                var finalRowLocation = textRowLocations[textRowLocations.Count - 1];

                foreach (var x in textRowLocations)
                {
                    if (x.Item1 != finalRowLocation.Item1)
                    {
                        if (min > x.Item2 - x.Item1)
                        {
                            min = x.Item2 - x.Item1;
                        }

                        if (max < x.Item2 - x.Item1)
                        {
                            max = x.Item2 - x.Item1;
                        }
                    }
                }

                if (finalRowLocation.Item2 - finalRowLocation.Item1 < (min - 2))
                {
                    textRowLocations.RemoveAt(textRowLocations.Count - 1);
                }
            }

            Debug.Print("process screenshot " + screenshot);
            PerformOcr(textRowLocations);
        }
Ejemplo n.º 8
0
        public bool Start(IPAddress ipAddress, int port, int maxNOfCon, string contentPath, Form1 callingForm)
        {
            _callingForm = callingForm;

            _logger = new SingleThreadLogger(ThreadLoggerType.Webserver);

            if (Running)
            {
                return(false);         // If it is already running, exit.
            }
            Running = true;
            //try
            {
                // A tcp/ip socket (ipv4)
                _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
                                           ProtocolType.Tcp);
                _serverSocket.Bind(new IPEndPoint(ipAddress, port));
                _serverSocket.Listen(maxNOfCon);
                _serverSocket.ReceiveTimeout = timeout;
                _serverSocket.SendTimeout    = timeout;

                this._contentPath = contentPath;
            }
            //catch { return false; }

            // Our thread that will listen connection requests
            // and create new threads to handle them.
            _requestListenerT = new Thread(() =>
            {
                while (Running)
                {
                    Socket clientSocket;
                    try
                    {
                        clientSocket = _serverSocket.Accept();
                        // Create new thread to handle the request and continue to listen the socket.
                        Thread requestHandler = new Thread(() =>
                        {
                            clientSocket.ReceiveTimeout = timeout;
                            clientSocket.SendTimeout    = timeout;
                            try { HandleRequest(clientSocket); }
                            catch (Exception)
                            {
                                try { clientSocket.Close(); }
                                catch (Exception ex2)
                                {
                                    _logger.Log("Error in webserver start 2:", true);
                                    _logger.Log(ex2.ToString(), true);
                                    _logger.Log(ex2.Message, true);
                                    _logger.Log(ex2.StackTrace, true);
                                    if (ex2.InnerException != null)
                                    {
                                        _logger.Log(ex2.InnerException.ToString(), true);
                                    }
                                }
                            }
                        });
                        requestHandler.Start();
                    }
                    catch (Exception ex)
                    {
                        _logger.Log("Error in webserver start 1:", true);
                        _logger.Log(ex.ToString(), true);
                        _logger.Log(ex.Message, true);
                        _logger.Log(ex.StackTrace, true);
                        if (ex.InnerException != null)
                        {
                            _logger.Log(ex.InnerException.ToString(), true);
                        }
                    }
                }
            });
            _requestListenerT.Start();

            return(true);
        }