Exemplo n.º 1
0
    //TODO: do all this with an "other" thread like in force sensor to allow connecting messages to be displayed
    private bool runEncoderCapturePre()
    {
        if (!portREOpened)
        {
            if (!runEncoderConnect())
            {
                return(false);
            }
        }

        if (File.Exists(UtilEncoder.GetSprintEncoderImage()))
        {
            Util.FileDelete(UtilEncoder.GetSprintEncoderImage());
        }

        event_execute_label_message.Text = "Please, wait ...";
        captureEndedMessage = "";
        capturingRunEncoder = arduinoCaptureStatus.STARTING;

        button_execute_test.Sensitive         = false;
        event_execute_button_finish.Sensitive = true;
        event_execute_button_cancel.Sensitive = true;

        //forceCaptureStartMark = false;

        runEncoderProcessFinish = false;
        runEncoderProcessCancel = false;
        runEncoderProcessError  = false;

        //To know if USB has been disconnected
        usbDisconnectedCount    = 0;
        usbDisconnectedLastTime = 0;

        /*
         * //initialize
         * forceSensorValues = new ForceSensorValues();
         */

        event_execute_ButtonFinish.Clicked -= new EventHandler(on_finish_clicked);
        event_execute_ButtonFinish.Clicked += new EventHandler(on_finish_clicked);

        event_execute_ButtonCancel.Clicked -= new EventHandler(on_cancel_clicked);
        event_execute_ButtonCancel.Clicked += new EventHandler(on_cancel_clicked);

        event_execute_label_message.Text = "Capturing ...";

        runEncoderCaptureThread = new Thread(new ThreadStart(runEncoderCaptureDo));
        GLib.Idle.Add(new GLib.IdleHandler(pulseGTKRunEncoderCapture));

        LogB.ThreadStart();
        runEncoderCaptureThread.Start();
        return(true);
    }
Exemplo n.º 2
0
    //non GTK on this method
    private void runEncoderCaptureDo()
    {
        LogB.Information("runEncoderCaptureDo 0");
        lastChangedTime = 0;

        if (!runEncoderSendCommand("start_capture:", "", "Catched run encoder capturing"))
        {
            runEncoderProcessError = true;
            return;
        }

        string str = "";

        LogB.Information("runEncoderCaptureDo 1");
        do
        {
            Thread.Sleep(100);             //sleep to let arduino start reading
            try {
                str = portRE.ReadLine();
            } catch {
                runEncoderProcessError = true;
                return;
            }

            LogB.Information("init string: " + str);
        }while(!str.Contains("Starting capture"));

        //forceCaptureStartMark = true;
        capturingRunEncoder = arduinoCaptureStatus.CAPTURING;

        Util.CreateRaceAnalyzerSessionDirIfNeeded(currentSession.UniqueID);

        string nameDate = currentPerson.Name + "_" + UtilDate.ToFile(DateTime.Now);

        //fileName to save the csv
        string fileName = Util.GetRaceAnalyzerSessionDir(currentSession.UniqueID) + Path.DirectorySeparatorChar + nameDate + ".csv";

        //lastRunEncoderFile to save the images
        lastRunEncoderFile = nameDate;


        TextWriter writer = File.CreateText(fileName);

        writer.WriteLine("Pulses;Time(useconds);Force(N)");
        str = "";
        int firstTime = 0;

        while (!runEncoderProcessFinish && !runEncoderProcessCancel && !runEncoderProcessError)
        {
            //LogB.Information(string.Format("finish conditions: {0}-{1}-{2}",
            //			runEncoderProcessFinish, runEncoderProcessCancel, runEncoderProcessError));

            /*
             * The difference between forceSensor and runEncoder is:
             * runEncoder is not always returning data
             * if user press "finish" button, and they don't move the encoder,
             * this will never end:
             * //str = portRE.ReadLine();
             * so use the following method that allows to return a "" when there no data
             * and then the while above will end with the runEncoderProcessFinish condition
             */
            str = readFromRunEncoderIfDataArrived();
            //LogB.Information("str: " + str); //TODO: remove this log
            if (str == "")
            {
                continue;
            }

            //check if there is one and only one ';'
            //if( ! (str.Contains(";") && str.IndexOf(";") == str.LastIndexOf(";")) )

            string [] strFull = str.Split(new char[] { ';' });
            LogB.Information("captured str: " + str);

            if (strFull.Length != 3)
            {
                continue;
            }

            LogB.Information("pulses: " + strFull[0]);
            if (!Util.IsNumber(strFull[0], false))
            {
                continue;
            }

            LogB.Information("time microseconds: " + strFull[1]);
            if (!Util.IsNumber(strFull[1], false))
            {
                continue;
            }

            LogB.Information("force avg (N): " + strFull[1]);
            if (!Util.IsNumber(strFull[2], false))
            {
                continue;
            }

            /*
             * int time = Convert.ToInt32(strFull[0]);
             *
             * //measurement does not start at 0 time. When we start receiving data, mark this as firstTime
             * if(firstTime == 0)
             *      firstTime = time;
             *
             * //use this to have time starting at 0
             * time -= firstTime;
             *
             * double force = Convert.ToDouble(Util.ChangeDecimalSeparator(strFull[1]));
             */
            int pulse = Convert.ToInt32(strFull[0]);
            int time  = Convert.ToInt32(strFull[1]);
            int force = Convert.ToInt32(strFull[2]);
            writer.WriteLine(pulse.ToString() + ";" + time.ToString() + ";" + force.ToString());
        }
        LogB.Information(string.Format("FINISHED WITH conditions: {0}-{1}-{2}",
                                       runEncoderProcessFinish, runEncoderProcessCancel, runEncoderProcessError));
        LogB.Information("Calling end_capture");
        if (!runEncoderSendCommand("end_capture:", "Ending capture ...", "Catched ending capture"))
        {
            runEncoderProcessError = true;
            capturingRunEncoder    = arduinoCaptureStatus.STOP;
            Util.FileDelete(fileName);
            return;
        }

        LogB.Information("Waiting end_capture");
        do
        {
            Thread.Sleep(10);
            try {
                str = portRE.ReadLine();
            } catch {
                LogB.Information("Catched waiting end_capture feedback");
            }
            LogB.Information("waiting \"Capture ended\" string: " + str);
        }while(!str.Contains("Capture ended"));
        LogB.Information("Success: received end_capture");

        writer.Flush();
        writer.Close();
        ((IDisposable)writer).Dispose();
        capturingRunEncoder = arduinoCaptureStatus.STOP;

        //port.Close();

        if (runEncoderProcessCancel || runEncoderProcessError)
        {
            Util.FileDelete(fileName);
        }
        else
        {
            //call graph. Prepare data
            File.Copy(fileName, UtilEncoder.GetRaceAnalyzerCSVFileName(), true);             //can be overwritten
            lastRunEncoderFullPath = fileName;

            race_analyzer_distance    = Convert.ToInt32(race_analyzer_spinbutton_distance.Value);
            race_analyzer_temperature = Convert.ToInt32(race_analyzer_spinbutton_temperature.Value);
            //create graph
            RunEncoderGraph reg = new RunEncoderGraph(
                race_analyzer_distance,
                currentPersonSession.Weight,                            //TODO: can be more if extra weight
                currentPersonSession.Height,
                race_analyzer_temperature);
            reg.CallR(1699, 768);                                       //TODO: hardcoded

            DateTime runEncoderGraphStarted = DateTime.Now;
            //TODO: check better if png is saved and have a cancel button

            while (!File.Exists(UtilEncoder.GetSprintEncoderImage()) && DateTime.Now.Subtract(runEncoderGraphStarted).TotalSeconds < 5)
            {
                Thread.Sleep(500);
            }

            captureEndedMessage = "Data on raceAnalyzer folder";
            if (File.Exists(UtilEncoder.GetSprintEncoderImage()))
            {
                LogB.Information("File exists on png, trying to copy");
                try {
                    File.Copy(UtilEncoder.GetSprintEncoderImage(),
                              Util.GetRaceAnalyzerSessionDir(currentSession.UniqueID) + Path.DirectorySeparatorChar +
                              lastRunEncoderFile +             //nameDate
                              ".png",
                              true);                           //can be overwritten
                    captureEndedMessage += " (png too)";
                } catch {
                    LogB.Information("Couldn't copy the file");
                    captureEndedMessage += " (Created png but only on tmp folder, could not copy file)";
                }
            }
            else
            {
                LogB.Information("File does not exist on png (after 5 seconds)");
                captureEndedMessage += " (png not created, problem doing the graph)";
            }

            capturingRunEncoder = arduinoCaptureStatus.COPIED_TO_TMP;
        }
    }