Read_event() public method

public Read_event ( double &timestamp, Plataforma, &plataforma ) : Respuesta,
timestamp double
plataforma Plataforma,
return Respuesta,
Example #1
0
    /**********************/
    /* PROGRAMA PRINCIPAL */
    /**********************/
    public static void Main()
    {
        Chronopic.Plataforma estado_plataforma;
        Chronopic.Respuesta respuesta;
        Automata estado_automata;
        double timestamp;
        double toff;

        //-- Crear objeto chronopic, para acceder al chronopic
        Chronopic cp = new Chronopic("/dev/ttyUSB0");

        //-- Obtener el estado inicial de la plataforma
        respuesta=cp.Read_platform(out estado_plataforma);
        switch(respuesta) {
          case Chronopic.Respuesta.Error:
        Console.WriteLine("Error en comunicacion con Chronopic");
        return;
          case Chronopic.Respuesta.Timeout:
        Console.WriteLine("Chronopic no responde");
        return;
          default:
        break;
        }

        Console.WriteLine("Estado plataforma: {0}",estado_plataforma);

        //-- Establecer el estado inicial del automata
        if (estado_plataforma==Chronopic.Plataforma.ON)
          estado_automata=Automata.ON;
        else {
          Console.WriteLine("Suba a la plataforma para realizar el salto");

          //-- Esperar a que llegue una trama con el estado de la plataforma
          //-- igual a ON. Esto indica que el usuario se ha subido
          do {
          respuesta = cp.Read_event(out timestamp, out estado_plataforma);
          } while (respuesta!=Chronopic.Respuesta.Ok);

          //-- Se han subido a la plataforma
          estado_automata = Automata.ON;
        }

        Console.WriteLine("");
        Console.WriteLine("Puede saltar cuando quiera");
        Console.WriteLine("Pulse control-c para finalizar la sesion");
        Console.WriteLine("-----------------------------------------");

        while(true) {

          //-- Esperar a que llegue una trama
          do {
        respuesta = cp.Read_event(out timestamp, out estado_plataforma);
          } while (respuesta!=Chronopic.Respuesta.Ok);

          //-- Segun el estado del automata
          switch(estado_automata) {

        case Automata.OFF: //-- Usuario estaba en el aire

          //-- Si ha aterrizado
          if (estado_plataforma==Chronopic.Plataforma.ON) {

            //-- Pasar al estado ON
            estado_automata=Automata.ON;

            //-- Registrar tiempo de vuelo
            toff = timestamp;

            //-- Imprimir informacion
            Console.WriteLine("Tiempo: {0:f1} ms",toff);
          }
          break;

        case Automata.ON: //-- Usuario estaba en la plataforma

          //-- Si ahora esta en el aire...
          if (estado_plataforma==Chronopic.Plataforma.OFF) {

            //-- Pasar al estado OFF
            estado_automata=Automata.OFF;
          }
          break;
          }

        }
    }
Example #2
0
    /**********************/
    /* PROGRAMA PRINCIPAL */
    /**********************/
    public static void Main(string[] args)
    {
        Chronopic.Plataforma estado_plataforma;
        Automata estado_automata;
        double timestamp;
        double toff;
        double ton;
        bool ok;
        string portName = "";
        string fileName = "";
        TextWriter writer;

        //always output to a file, but if not specified, output here and rewrite it every chronojump_mini execution
        string defaultFileName = Path.Combine(getOutputDir(), "output");

        System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("es-ES");
        System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("es-ES");

        //connect with catalog.cs for using gettext translation
        Catalog.Init ("chronojump", "./locale");

        //parameters passing only on linux
        if(! UtilAll.IsWindows()) {
            if(args.Length > 2)
                printSyntaxAndQuit();

            for( int i = 0; i != args.Length; ++i ) {
                Console.WriteLine("param[{0}]: {1}", i, args[i]);
                if(args[i].StartsWith("PORT="))
                    portName = args[i].Substring(5);
                else if (args[i].StartsWith("FILE=")) {
                    fileName = args[i].Substring(5);
                    fileName= getOutputDir() + Path.DirectorySeparatorChar + fileName;
                }
                else
                    printSyntaxAndQuit();
            }
        }

        //detection of ports
        string messageInfo;
        //string messageDetected ="";

        if(UtilAll.IsWindows()) {
            messageInfo = Constants.PortNamesWindows;
            /*
            messageDetected = Catalog.GetString("Detected ports:") + "\n";

            string jumpLine = "";
            foreach (string s in SerialPort.GetPortNames()) {
                messageDetected += jumpLine + s;
                jumpLine = "\n";
            }
            */
        } else {
            messageInfo = Constants.PortNamesLinux;
        }

        messageInfo += string.Format("\n" + Catalog.GetString("More information on Chronojump manual"));

        Console.WriteLine("---------------------------");
        Console.WriteLine(messageInfo);
        Console.WriteLine("---------------------------");

        if(portName == "") {
            if( ! UtilAll.IsWindows()) {
                Console.WriteLine(UtilAll.DetectPortsLinux(false)); //formatting
            }
            Console.WriteLine(Catalog.GetString("Print the port name where chronopic is connected:"));
            portName=Console.ReadLine();
        }

        //output file stuff
        fileName = manageFileName(fileName);
        if(fileName == "")
            fileName = defaultFileName + "-" + portName.Replace("/","") + ".csv";

        writer = File.CreateText(fileName);

        Console.WriteLine(Catalog.GetString("Opening port...") + " " +
                   Catalog.GetString("Please touch the platform or click Chronopic TEST button"));
        //-- Crear puerto serie
        SerialPort sp;
        sp = new SerialPort(portName);

        //-- Abrir puerto serie. Si ocurre algun error
        //-- Se lanzara una excepcion
        try {
            sp.Open();
        } catch (Exception e){
            Console.WriteLine(Catalog.GetString("Error opening serial port"));
            Console.WriteLine(e);
            Environment.Exit(1);
        }

        //-- Crear objeto chronopic, para acceder al chronopic
        Chronopic cp = new Chronopic(sp);
        cp.Flush();

        //-- Obtener el estado inicial de la plataforma
        // this do...while is here because currently there's no timeout on chronopic.cs on windows
        do {
            ok=cp.Read_platform(out estado_plataforma);
        } while(!ok);
        if (!ok) {
            //-- Si hay error terminar
            Console.WriteLine(string.Format(Catalog.GetString("Error: {0}"),cp.Error));
            System.Environment.Exit(-1);
        }
        Console.WriteLine(string.Format(Catalog.GetString("Platform state: {0}"), estado_plataforma));

        //Console.WriteLine("Automatic variables: ");
            //cp.Read_variables_automatic();

        //-- Establecer el estado inicial del automata
        if (estado_plataforma==Chronopic.Plataforma.ON)
            estado_automata=Automata.ON;
        else {
            Console.WriteLine(Catalog.GetString("Go up platform for jumping"));

            //-- Esperar a que llegue una trama con el estado de la plataforma
            //-- igual a ON. Esto indica que el usuario se ha subido
            do {
                ok = cp.Read_event(out timestamp, out estado_plataforma);
            } while (!ok);

            //-- Se han subido a la plataforma
            estado_automata = Automata.ON;
        }

        Console.WriteLine("");
        Console.WriteLine(Catalog.GetString("Jump when prepared"));
        Console.WriteLine(Catalog.GetString("Press CTRL-c for ending session"));
        Console.WriteLine("-----------------------------------------");

        double count = 1.0;

        Console.WriteLine("  TC(ms) TF(ms)");
        writer.WriteLine("count;TC(ms);TF(ms)");

        while(true) {
            //-- Esperar a que llegue una trama
            do {
                ok = cp.Read_event(out timestamp, out estado_plataforma);
            } while (ok==false);

            //-- Segun el estado del automata
            switch(estado_automata) {

                case Automata.OFF: //-- Usuario estaba en el aire

                    //-- Si ha aterrizado
                    if (estado_plataforma==Chronopic.Plataforma.ON) {

                        //-- Pasar al estado ON
                        estado_automata=Automata.ON;

                        //-- Registrar tiempo de vuelo
                        toff = timestamp;

                        //-- Imprimir informacion
                        Console.WriteLine("{0:f1}",toff);
                        writer.WriteLine("{0:f1}",toff);
                    }
                    break;

                case Automata.ON: //-- Usuario estaba en la plataforma

                    //-- Si ahora esta en el aire...
                    if (estado_plataforma==Chronopic.Plataforma.OFF) {

                        //-- Pasar al estado OFF
                        estado_automata=Automata.OFF;

                        //-- Registrar tiempo de contacto
                        ton = timestamp;

                        //-- Imprimir informacion
                        Console.Write(count + " {0:f1} ",ton);
                        writer.Write(count + ";{0:f1};",ton);
                    }
                    break;
            }

            writer.Flush();

            count += .5;
        }
    }
Example #3
0
    protected void waitEvent(Chronopic myCP, Chronopic.Plataforma myPS, States myLS, out string inStr, out string outStr, int cpNum)
    {
        double timestamp = 0;
        bool   success   = false;
        bool   ok;
        string inEqual  = "";
        string outEqual = "";

        inStr = ""; outStr = "";
        int runAnalysisTcCount = 0;
        int runAnalysisTfCount = 0;

        bool isFirstOut = true;
        bool isFirstIn  = true;

        syncStates syncing = syncStates.DONE;

        if (syncFirst)
        {
            syncing                 = syncStates.NOTHING;
            feedbackMessage         = Catalog.GetString("Press and maintain Test button in all Chronopics simultaneously.");
            needShowFeedbackMessage = true;
        }

        do
        {
            ok = myCP.Read_event(out timestamp, out myPS);

            //if chronopic signal is Ok and state has changed
            if (ok && (
                    (myPS == Chronopic.Plataforma.ON && myLS == States.OFF) ||
                    (myPS == Chronopic.Plataforma.OFF && myLS == States.ON)) &&
                !cancel && !finish)
            {
                //while no finished time or jumps, continue recording events
                if (!success)
                {
                    //don't record the time until the first event of the first Chronopic
                    //this is only executed on the first chronopic that receives a change
                    if (firstValue)
                    {
                        firstValue = false;
                        initializeTimer();                         //this is for first Chronopic and only for simulated

                        feedbackMessage         = "";
                        needShowFeedbackMessage = true;
                    }

                    if (syncing == syncStates.NOTHING && myPS == Chronopic.Plataforma.ON && myLS == States.OFF)
                    {
                        syncing                 = syncStates.CONTACTED;
                        feedbackMessage         = Catalog.GetString("Release Test button in all Chronopics simultaneously.");
                        needShowFeedbackMessage = true;
                    }
                    else if (syncing == syncStates.CONTACTED && myPS == Chronopic.Plataforma.OFF && myLS == States.ON)
                    {
                        syncing         = syncStates.DONE;
                        feedbackMessage = Catalog.GetString("Synchronization done.") + "\n" +
                                          Catalog.GetString("Test starts now.");
                        needShowFeedbackMessage = true;
                    }
                    else
                    {
                        if (type != Constants.RunAnalysisName)
                        {
                            needSensitiveButtonFinish = true;
                        }

                        if (myPS == Chronopic.Plataforma.ON && myLS == States.OFF)
                        {
                            //this is for runAnalysis, delete first tf on 2nd cp (jump cp)
                            if (cpNum == 2 && type == Constants.RunAnalysisName && runAnalysisTfCount == 0)
                            {
                                runAnalysisTfCount++;
                            }
                            //this is for multiChronopic, not for runAnalysis
                            else if (deleteFirst && isFirstOut)
                            {
                                isFirstOut = false;
                            }
                            else
                            {
                                double lastOut = timestamp / 1000.0;
                                LogB.Information(cpNum.ToString() + " landed: " + lastOut.ToString());
                                outStr   = outStr + outEqual + lastOut.ToString();
                                outEqual = "=";
                            }

                            /*
                             * if it's a runAnalysis,
                             * should end when arrive at 2n photocell (controlled by cp1)
                             */
                            if (cpNum == 1 && type == Constants.RunAnalysisName)
                            {
                                runAnalysisTcCount++;
                                if (runAnalysisTcCount >= 2)
                                {
                                    success = true;
                                    //better call also finish
                                    //then all cps know about ending
                                    finish = true;
                                }
                            }
                        }
                        else if (myPS == Chronopic.Plataforma.OFF && myLS == States.ON)
                        {
                            //this is for multiChronopic, not for runAnalysis
                            if (deleteFirst && isFirstIn)
                            {
                                isFirstIn = false;
                            }
                            else
                            {
                                double lastIn = timestamp / 1000.0;
                                LogB.Information(cpNum.ToString() + " jumped: " + lastIn.ToString());
                                inStr   = inStr + inEqual + lastIn.ToString();
                                inEqual = "=";
                            }
                        }

                        PrepareEventGraphMultiChronopicObject = new PrepareEventGraphMultiChronopic(
                            //timestamp/1000.0,
                            cp1StartedIn, cp2StartedIn, cp3StartedIn, cp4StartedIn,
                            cp1InStr, cp1OutStr, cp2InStr, cp2OutStr,
                            cp3InStr, cp3OutStr, cp4InStr, cp4OutStr);
                        needUpdateGraphType = eventType.MULTICHRONOPIC;
                        needUpdateGraph     = true;


                        updateProgressBar = new UpdateProgressBar(
                            true,                                  //isEvent
                            false,                                 //means activity mode
                            -1                                     //don't show text
                            );
                        needUpdateEventProgressBar = true;
                    }
                }

                if (myPS == Chronopic.Plataforma.OFF)
                {
                    myLS = States.OFF;
                }
                else
                {
                    myLS = States.ON;
                }
            }
        } while (!success && !cancel && !finish);

        if (finish)
        {
            finishThisCp();

            //call write on gui/chronojump.cs, because if done in execute/MultiChronopic,
            //will be called n times if n chronopics are working
            //write(false); //tempTable
        }
    }
Example #4
0
    protected override void waitEvent()
    {
        double timestamp = 0;
        bool   success   = false;
        string equal     = "";

        bool ok;

        //prepare variables to allow being cancelled or finished
        if (!simulated)
        {
            Chronopic.InitCancelAndFinish();
        }

        do
        {
            if (simulated)
            {
                ok = true;
            }
            else
            {
                ok = cp.Read_event(out timestamp, out platformState);
            }


            if (ok && !cancel && !finish)
            {
                if (platformState == Chronopic.Plataforma.ON && loggedState == States.OFF)
                {
                    //has arrived

                    //if we arrive to the platform for the first time, don't record anything
                    if (pulsePhase == pulsePhases.WAIT_FIRST_EVENT)
                    {
                        pulsePhase = pulsePhases.DOING;
                        //pulse starts
                        initializeTimer();

                        feedbackMessage         = "";
                        needShowFeedbackMessage = true;
                    }
                    else
                    {
                        //is not the first pulse
                        if (totalPulsesNum == -1)
                        {
                            //if is "unlimited",
                            //then play with the progress bar until finish button is pressed
                            if (simulated)
                            {
                                timestamp = simulatedTimeLast * 1000;                                         //conversion to milliseconds
                            }
                            if (timesString.Length > 0)
                            {
                                equal = "=";
                            }
                            timesString = timesString + equal + (contactTime / 1000.0 + timestamp / 1000.0).ToString();
                            tracks++;

                            //update event progressbar
                            //progressBarEventOrTimePreExecution(
                            updateProgressBar = new UpdateProgressBar(
                                true,                                                 //isEvent
                                false,                                                //activityMode
                                tracks
                                );

                            needUpdateEventProgressBar = true;

                            //update graph
                            //preparePulseGraph(timestamp/1000.0, timesString);
                            PrepareEventGraphPulseObject = new PrepareEventGraphPulse(timestamp / 1000.0, timesString);
                            needUpdateGraphType          = eventType.PULSE;
                            needUpdateGraph = true;

                            //put button_finish as sensitive when first jump is done (there's something recordable)
                            if (tracks == 1)
                            {
                                needSensitiveButtonFinish = true;
                            }
                        }
                        else
                        {
                            //is not the first pulse, and it's limited by tracks (ticks)
                            tracks++;

                            if (simulated)
                            {
                                timestamp = simulatedTimeLast * 1000;                                         //conversion to milliseconds
                            }
                            if (timesString.Length > 0)
                            {
                                equal = "=";
                            }
                            timesString = timesString + equal + (contactTime / 1000.0 + timestamp / 1000.0).ToString();

                            if (tracks >= totalPulsesNum)
                            {
                                //finished
                                write();
                                success    = true;
                                pulsePhase = pulsePhases.DONE;
                            }

                            //update event progressbar
                            //progressBarEventOrTimePreExecution(
                            updateProgressBar = new UpdateProgressBar(
                                true,                                                 //isEvent
                                true,                                                 //PercentageMode
                                tracks
                                );
                            needUpdateEventProgressBar = true;

                            //update graph
                            //preparePulseGraph(timestamp/1000.0, timesString);
                            PrepareEventGraphPulseObject = new PrepareEventGraphPulse(timestamp / 1000.0, timesString);
                            needUpdateGraphType          = eventType.PULSE;
                            needUpdateGraph = true;

                            //put button_finish as sensitive when first jump is done (there's something recordable)
                            if (tracks == 1)
                            {
                                needSensitiveButtonFinish = true;
                            }
                        }
                    }

                    //change the automata state
                    loggedState = States.ON;
                }
                else if (platformState == Chronopic.Plataforma.OFF && loggedState == States.ON)
                {
                    //it's out, was inside (= has abandoned platform)

                    if (simulated)
                    {
                        timestamp = simulatedTimeLast * 1000;                                 //conversion to milliseconds
                    }
                    contactTime = timestamp;

                    //change the automata state
                    loggedState = States.OFF;
                }
            }
        } while (!success && !cancel && !finish);

        if (finish)
        {
            write();
            pulsePhase = pulsePhases.DONE;
        }
    }
Example #5
0
    protected override void waitEvent()
    {
        double timestamp = 0;
        bool   success   = false;

        shouldFinishAtNextFall = false;

        bool ok;

        int countForSavingTempTable = 0;

        do
        {
            if (simulated)
            {
                ok = true;
            }
            else
            {
                ok = cp.Read_event(out timestamp, out platformState);
            }


            //if chronopic signal is Ok and state has changed
            if (ok && (
                    (platformState == Chronopic.Plataforma.ON && loggedState == States.OFF) ||
                    (platformState == Chronopic.Plataforma.OFF && loggedState == States.ON)) &&
                !cancel && !finish)
            {
                if (simulated)
                {
                    timestamp = simulatedTimeLast * 1000;                     //conversion to milliseconds
                }
                LogB.Information(Util.GetTotalTime(tcString, tvString).ToString());



                string equal = "";

                //while no finished time or jumps, continue recording events
                if (!success)
                {
                    //don't record the time until the first event
                    if (firstRjValue)
                    {
                        firstRjValue = false;

                        //but start timer
                        initializeTimer();

                        feedbackMessage         = "";
                        needShowFeedbackMessage = true;
                    }
                    else
                    {
                        //reactive jump has not finished... record the next jump
                        LogB.Information(string.Format("tcCount: {0}, tvCount: {1}", tcCount, tvCount));
                        if (tcCount == tvCount)
                        {
                            lastTc = timestamp / 1000.0;

                            if (tcCount > 0)
                            {
                                equal = "=";
                            }
                            tcString = tcString + equal + lastTc.ToString();

                            updateTimerCountWithChronopicData(tcString, tvString);

                            tcCount = tcCount + 1;
                        }
                        else
                        {
                            //tcCount > tvCount
                            lastTv = timestamp / 1000.0;

                            if (tvCount > 0)
                            {
                                equal = "=";
                            }
                            tvString = tvString + equal + lastTv.ToString();

                            updateTimerCountWithChronopicData(tcString, tvString);
                            tvCount = tvCount + 1;

                            //update event progressbar
                            //app1.ProgressBarEventOrTimePreExecution(
                            updateProgressBar = new UpdateProgressBar(
                                true,                                         //isEvent
                                jumpsLimited,                                 //if jumpsLimited: do fraction; if time limited: do pulse
                                tvCount
                                );
                            needUpdateEventProgressBar = true;

                            //update graph
                            PrepareEventGraphJumpReactiveObject = new PrepareEventGraphJumpReactive(lastTv, lastTc, tvString, tcString);
                            needUpdateGraphType = eventType.JUMPREACTIVE;
                            needUpdateGraph     = true;

                            //put button_finish as sensitive when first jump is done (there's something recordable)
                            if (tvCount == 1)
                            {
                                needSensitiveButtonFinish = true;
                            }

                            //save temp table if needed
                            countForSavingTempTable++;
                            if (countForSavingTempTable == timesForSavingRepetitive)
                            {
                                writeRj(true);                                 //tempTable
                                countForSavingTempTable = 0;
                            }
                        }
                    }
                }

                //if we finish by time, and allowFinishAfterTime == true, when time passed, if the jumper is jumping
                //if flags the shouldFinishAtNextFall that will finish when he arrives to the platform
                if (shouldFinishAtNextFall && platformState == Chronopic.Plataforma.ON && loggedState == States.OFF)
                {
                    finish = true;
                }


                //check if reactive jump should finish
                if (jumpsLimited)
                {
                    if (limitAsDouble != -1)
                    {
                        if (Util.GetNumberOfJumps(tvString, false) >= limitAsDouble)
                        {
                            jumpPhase = jumpPhases.PLATFORM_END;

                            writeRj(false);                             //tempTable
                            success = true;

                            //update event progressbar
                            //app1.ProgressBarEventOrTimePreExecution(
                            updateProgressBar = new UpdateProgressBar(
                                true,                                         //isEvent
                                true,                                         //percentageMode
                                tvCount
                                );
                            needUpdateEventProgressBar = true;

                            //update graph
                            PrepareEventGraphJumpReactiveObject = new PrepareEventGraphJumpReactive(lastTv, lastTc, tvString, tcString);
                            needUpdateGraphType = eventType.JUMPREACTIVE;
                            needUpdateGraph     = true;
                        }
                    }
                }

                if (platformState == Chronopic.Plataforma.OFF)
                {
                    loggedState = States.OFF;
                }
                else
                {
                    loggedState = States.ON;
                }
            }
        } while (!success && !cancel && !finish);


        if (finish)
        {
            //write only if there's a jump at minimum
            if (Util.GetNumberOfJumps(tcString, false) >= 1 && Util.GetNumberOfJumps(tvString, false) >= 1)
            {
                jumpPhase = jumpPhases.PLATFORM_END;

                writeRj(false);                 //tempTable

                totallyFinished = true;
            }
            else
            {
                //cancel a jump if clicked finish before any events done
                cancel = true;
            }
        }
        //if(cancel || finish)
        if (cancel)
        {
            //event will be raised, and managed in chronojump.cs
            fakeButtonFinished.Click();

            totallyCancelled = true;
        }
    }
Example #6
0
    protected override void waitEvent()
    {
        double timestamp = 0;
        bool   success   = false;

        bool ok;

        LogB.Information("Inside waitEvent");
        do
        {
            if (simulated)
            {
                ok = true;
            }
            else
            {
                ok = cp.Read_event(out timestamp, out platformState);
            }

            LogB.Information("Inside do");
            LogB.Information("cancel == ");
            LogB.Information(cancel.ToString());
            LogB.Information("ok == ");
            LogB.Information(ok.ToString());

            //if (ok) {
            if (ok && !cancel)
            {
                LogB.Information("ok!");
                if (platformState == Chronopic.Plataforma.ON && loggedState == States.OFF)
                {
                    //LogB.Information("condition guai! hem entrat!");
                    //has landed
                    if (simulated)
                    {
                        timestamp = simulatedTimeLast * 1000;                         //conversion to milliseconds
                    }
                    LogB.Information(string.Format("t1:{0}", timestamp));

                    time = timestamp / 1000.0;
                    write();

                    success = true;

                    //update event progressbar
                    double percentageToPass = 2;                     //has two phases

                    //progressBarEventOrTimePreExecution(
                    //don't do it, put a boolean value and let the PulseGTK do it
                    updateProgressBar = new UpdateProgressBar(
                        true,                                 //isEvent
                        true,                                 //percentageMode
                        percentageToPass
                        );
                    needUpdateEventProgressBar = true;

                    loggedState = States.ON;
                }
                else if (platformState == Chronopic.Plataforma.OFF && loggedState == States.ON)
                {
                    //LogB.Information("condition hem sortit");

                    //it's out, was inside (= has released)

                    initializeTimer();

                    feedbackMessage         = "";
                    needShowFeedbackMessage = true;

                    //update event progressbar
                    //progressBarEventOrTimePreExecution(
                    //don't do it, put a boolean value and let the PulseGTK do it
                    updateProgressBar = new UpdateProgressBar(
                        true,                             //isEvent
                        true,                             //percentageMode
                        1                                 //normal jump, phase 1/2
                        );
                    needUpdateEventProgressBar = true;

                    //change the automata state
                    loggedState = States.OFF;
                }
            }
//Log.WriteLine("PREEXIT");
        } while (!success && !cancel);
//Log.WriteLine("EXIT");

        if (cancel)
        {
            //event will be raised, and managed in chronojump.cs
            fakeButtonFinished.Click();

            totallyCancelled = true;
        }
    }
Example #7
0
    protected override void waitEvent()
    {
        double timestamp = 0;
        bool   success   = false;

        bool ok;
        int  phase = 0;

        do
        {
            if (simulated)
            {
                ok = true;
            }
            else
            {
                ok = cp.Read_event(out timestamp, out platformState);
            }


            /*
             *           \()/            \()/
             *            \/              \/
             *   _()_     /\     _()_     /\     _()_
             *    \/              \/              \/
             * ___/\______________/\______________/\___
             *
             *  GraphA  graphB  graphC  graphD  graphE
             *  unused  jumps   lands   jumps   lands
             *
             *    ______start_______             end
             *
             *    DJ      DJ      SJ
             * hasFall  hasFall
             * fall -1
             *
             */

            //if (ok)
            if (ok && !cancel)
            {
                if (platformState == Chronopic.Plataforma.ON && loggedState == States.OFF)
                {
                    //has landed
                    if (hasFall && tc == 0)
                    {
                        //**** graphC ****

                        if (fall == -1)
                        {
                            if (simulated)
                            {
                                timestamp = simulatedTimeLast * 1000;                                 //conversion to milliseconds
                            }
                            //calculate the fall height using flight time
                            double tvPreJump = timestamp / 1000.0;
                            fall = Convert.ToDouble(Util.GetHeightInCentimeters(tvPreJump.ToString()));
                        }

                        //jump with fall, landed first time
                        initializeTimer();

                        //app1.ProgressBarEventOrTimePreExecution(
                        //don't do it, put a boolean value and let the PulseGTK do it
                        updateProgressBar = new UpdateProgressBar(
                            true,                                     //isEvent
                            true,                                     //jumpsLimited: percentageMode
                            ++phase
                            );
                        needUpdateEventProgressBar = true;

                        feedbackMessage         = "";
                        needShowFeedbackMessage = true;
                    }
                    else
                    {
                        //**** graphE **** jump with fall: second landed; or without fall first landing

                        if (simulated)
                        {
                            timestamp = simulatedTimeLast * 1000;                             //conversion to milliseconds
                        }
                        LogB.Information(string.Format("t1:{0}", timestamp));

                        tv = timestamp / 1000.0;

                        jumpPhase = jumpPhases.PLATFORM_END;

                        write();

                        success = true;

                        //app1.ProgressBarEventOrTimePreExecution(
                        //don't do it, put a boolean value and let the PulseGTK do it
                        updateProgressBar = new UpdateProgressBar(
                            true,                                     //isEvent
                            true,                                     //percentageMode
                            ++phase
                            );
                        needUpdateEventProgressBar = true;
                    }
                    loggedState = States.ON;
                }
                else if (platformState == Chronopic.Plataforma.OFF && loggedState == States.ON)
                {
                    //it's out, was inside (= has jumped)

                    //fall != -1 because if it was == -1, it will change once touching floor for the first time
                    if (hasFall && fall != -1)
                    {
                        //**** graphD ****

                        if (simulated)
                        {
                            timestamp = simulatedTimeLast * 1000;                             //conversion to milliseconds
                        }
                        LogB.Information(string.Format("t2:{0}", timestamp));

                        //record the TC
                        tc = timestamp / 1000.0;

                        //takeOff jump (only one TC)
                        //if(fixedValue == 0.5)
                        if (type == Constants.TakeOffName || type == Constants.TakeOffWeightName)
                        {
                            tv = 0;

                            jumpPhase = jumpPhases.PLATFORM_END;

                            write();
                            success = true;
                        }

                        //update event progressbar
                        //app1.ProgressBarEventOrTimePreExecution(
                        //don't do it, put a boolean value and let the PulseGTK do it
                        updateProgressBar = new UpdateProgressBar(
                            true,                                     //isEvent
                            true,                                     //percentageMode
                            ++phase
                            );
                        needUpdateEventProgressBar = true;
                    }
                    else
                    {
                        //**** graphD (if normal jump) ****
                        //**** graphB (if hasFall and fall == -1) ****

                        initializeTimer();

                        //update event progressbar
                        //app1.ProgressBarEventOrTimePreExecution(
                        //don't do it, put a boolean value and let the PulseGTK do it
                        updateProgressBar = new UpdateProgressBar(
                            true,                                     //isEvent
                            true,                                     //percentageMode
                            ++phase
                            );
                        needUpdateEventProgressBar = true;

                        feedbackMessage         = "";
                        needShowFeedbackMessage = true;
                    }

                    //change the automata state
                    loggedState = States.OFF;
                }
            }
//Log.WriteLine("PREEXIT");
        } while (!success && !cancel);
//Log.WriteLine("EXIT");

        if (cancel)
        {
            //event will be raised, and managed in chronojump.cs
            fakeButtonFinished.Click();

            totallyCancelled = true;
        }
    }
    /**********************/
    /* PROGRAMA PRINCIPAL */
    /**********************/
    public static void Main(string[] args)
    {
        Chronopic.Plataforma estado_plataforma;
        Automata             estado_automata;
        double     timestamp;
        double     toff;
        double     ton;
        bool       ok;
        string     portName = "";
        string     fileName = "";
        TextWriter writer;

        //always output to a file, but if not specified, output here and rewrite it every chronojump_mini execution
        string defaultFileName = Path.Combine(getOutputDir(), "output");


        System.Threading.Thread.CurrentThread.CurrentCulture   = new System.Globalization.CultureInfo("es-ES");
        System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("es-ES");

        //connect with catalog.cs for using gettext translation
        Catalog.Init("chronojump", "./locale");

        //parameters passing only on linux
        if (!UtilAll.IsWindows())
        {
            if (args.Length > 2)
            {
                printSyntaxAndQuit();
            }

            for (int i = 0; i != args.Length; ++i)
            {
                Console.WriteLine("param[{0}]: {1}", i, args[i]);
                if (args[i].StartsWith("PORT="))
                {
                    portName = args[i].Substring(5);
                }
                else if (args[i].StartsWith("FILE="))
                {
                    fileName = args[i].Substring(5);
                    fileName = getOutputDir() + Path.DirectorySeparatorChar + fileName;
                }
                else
                {
                    printSyntaxAndQuit();
                }
            }
        }

        //detection of ports
        string messageInfo;

        //string messageDetected ="";

        if (UtilAll.IsWindows())
        {
            messageInfo = Constants.PortNamesWindows;

            /*
             * messageDetected = Catalog.GetString("Detected ports:") + "\n";
             *
             * string jumpLine = "";
             * foreach (string s in SerialPort.GetPortNames()) {
             *      messageDetected += jumpLine + s;
             *      jumpLine = "\n";
             * }
             */
        }
        else
        {
            messageInfo = Constants.PortNamesLinux;
        }

        messageInfo += string.Format("\n" + Catalog.GetString("More information on Chronojump manual"));

        Console.WriteLine("---------------------------");
        Console.WriteLine(messageInfo);
        Console.WriteLine("---------------------------");

        if (portName == "")
        {
            if (!UtilAll.IsWindows())
            {
                Console.WriteLine(UtilAll.DetectPortsLinux(false));                 //formatting
            }
            Console.WriteLine(Catalog.GetString("Print the port name where chronopic is connected:"));
            portName = Console.ReadLine();
        }

        //output file stuff
        fileName = manageFileName(fileName);
        if (fileName == "")
        {
            fileName = defaultFileName + "-" + portName.Replace("/", "") + ".csv";
        }

        writer = File.CreateText(fileName);


        Console.WriteLine(Catalog.GetString("Opening port...") + " " +
                          Catalog.GetString("Please touch the platform or click Chronopic TEST button"));
        //-- Crear puerto serie
        SerialPort sp;

        sp = new SerialPort(portName);

        //-- Abrir puerto serie. Si ocurre algun error
        //-- Se lanzara una excepcion
        try {
            sp.Open();
        } catch (Exception e) {
            Console.WriteLine(Catalog.GetString("Error opening serial port"));
            Console.WriteLine(e);
            Environment.Exit(1);
        }



        //-- Crear objeto chronopic, para acceder al chronopic
        Chronopic cp = new Chronopic(sp);

        cp.Flush();


        //-- Obtener el estado inicial de la plataforma
        // this do...while is here because currently there's no timeout on chronopic.cs on windows
        do
        {
            ok = cp.Read_platform(out estado_plataforma);
        } while(!ok);
        if (!ok)
        {
            //-- Si hay error terminar
            Console.WriteLine(string.Format(Catalog.GetString("Error: {0}"), cp.Error));
            System.Environment.Exit(-1);
        }
        Console.WriteLine(string.Format(Catalog.GetString("Platform state: {0}"), estado_plataforma));


        //Console.WriteLine("Automatic variables: ");
        //cp.Read_variables_automatic();


        //-- Establecer el estado inicial del automata
        if (estado_plataforma == Chronopic.Plataforma.ON)
        {
            estado_automata = Automata.ON;
        }
        else
        {
            Console.WriteLine(Catalog.GetString("Go up platform for jumping"));

            //-- Esperar a que llegue una trama con el estado de la plataforma
            //-- igual a ON. Esto indica que el usuario se ha subido
            do
            {
                ok = cp.Read_event(out timestamp, out estado_plataforma);
            } while (!ok);

            //-- Se han subido a la plataforma
            estado_automata = Automata.ON;
        }

        Console.WriteLine("");
        Console.WriteLine(Catalog.GetString("Jump when prepared"));
        Console.WriteLine(Catalog.GetString("Press CTRL-c for ending session"));
        Console.WriteLine("-----------------------------------------");

        double count = 1.0;

        Console.WriteLine("  TC(ms) TF(ms)");
        writer.WriteLine("count;TC(ms);TF(ms)");

        while (true)
        {
            //-- Esperar a que llegue una trama
            do
            {
                ok = cp.Read_event(out timestamp, out estado_plataforma);
            } while (ok == false);


            //-- Segun el estado del automata
            switch (estado_automata)
            {
            case Automata.OFF:                     //-- Usuario estaba en el aire

                //-- Si ha aterrizado
                if (estado_plataforma == Chronopic.Plataforma.ON)
                {
                    //-- Pasar al estado ON
                    estado_automata = Automata.ON;

                    //-- Registrar tiempo de vuelo
                    toff = timestamp;

                    //-- Imprimir informacion
                    Console.WriteLine("{0:f1}", toff);
                    writer.WriteLine("{0:f1}", toff);
                }
                break;

            case Automata.ON:                     //-- Usuario estaba en la plataforma

                //-- Si ahora esta en el aire...
                if (estado_plataforma == Chronopic.Plataforma.OFF)
                {
                    //-- Pasar al estado OFF
                    estado_automata = Automata.OFF;

                    //-- Registrar tiempo de contacto
                    ton = timestamp;

                    //-- Imprimir informacion
                    Console.Write(count + " {0:f1} ", ton);
                    writer.Write(count + ";{0:f1};", ton);
                }
                break;
            }

            writer.Flush();

            count += .5;
        }
    }
Example #9
0
    /**********************/
    /* PROGRAMA PRINCIPAL */
    /**********************/
    public static void Main()
    {
        Chronopic.Plataforma estado_plataforma;
        Chronopic.Respuesta  respuesta;
        Automata             estado_automata;
        double timestamp;
        double toff;

        //-- Crear objeto chronopic, para acceder al chronopic
        Chronopic cp = new Chronopic("/dev/ttyUSB0");

        //-- Obtener el estado inicial de la plataforma
        respuesta = cp.Read_platform(out estado_plataforma);
        switch (respuesta)
        {
        case Chronopic.Respuesta.Error:
            Console.WriteLine("Error en comunicacion con Chronopic");
            return;

        case Chronopic.Respuesta.Timeout:
            Console.WriteLine("Chronopic no responde");
            return;

        default:
            break;
        }

        Console.WriteLine("Estado plataforma: {0}", estado_plataforma);

        //-- Establecer el estado inicial del automata
        if (estado_plataforma == Chronopic.Plataforma.ON)
        {
            estado_automata = Automata.ON;
        }
        else
        {
            Console.WriteLine("Suba a la plataforma para realizar el salto");

            //-- Esperar a que llegue una trama con el estado de la plataforma
            //-- igual a ON. Esto indica que el usuario se ha subido
            do
            {
                respuesta = cp.Read_event(out timestamp, out estado_plataforma);
            } while (respuesta != Chronopic.Respuesta.Ok);

            //-- Se han subido a la plataforma
            estado_automata = Automata.ON;
        }

        Console.WriteLine("");
        Console.WriteLine("Puede saltar cuando quiera");
        Console.WriteLine("Pulse control-c para finalizar la sesion");
        Console.WriteLine("-----------------------------------------");

        while (true)
        {
            //-- Esperar a que llegue una trama
            do
            {
                respuesta = cp.Read_event(out timestamp, out estado_plataforma);
            } while (respuesta != Chronopic.Respuesta.Ok);


            //-- Segun el estado del automata
            switch (estado_automata)
            {
            case Automata.OFF: //-- Usuario estaba en el aire

                //-- Si ha aterrizado
                if (estado_plataforma == Chronopic.Plataforma.ON)
                {
                    //-- Pasar al estado ON
                    estado_automata = Automata.ON;

                    //-- Registrar tiempo de vuelo
                    toff = timestamp;

                    //-- Imprimir informacion
                    Console.WriteLine("Tiempo: {0:f1} ms", toff);
                }
                break;

            case Automata.ON: //-- Usuario estaba en la plataforma

                //-- Si ahora esta en el aire...
                if (estado_plataforma == Chronopic.Plataforma.OFF)
                {
                    //-- Pasar al estado OFF
                    estado_automata = Automata.OFF;
                }
                break;
            }
        }
    }
    protected void waitEvent(Chronopic myCP, Chronopic.Plataforma myPS, States myLS, out string inStr, out string outStr, int cpNum)
    {
        double timestamp = 0;
        bool success = false;
        bool ok;
        string inEqual = "";
        string outEqual = "";

        inStr = ""; outStr = "";
        int runAnalysisTcCount = 0;
        int runAnalysisTfCount = 0;

        bool isFirstOut = true;
        bool isFirstIn = true;

        syncStates syncing = syncStates.DONE;
        if(syncFirst) {
            syncing = syncStates.NOTHING;
            feedbackMessage = Catalog.GetString("Press and mantain Test button in all Chronopics simultaneously.");
            needShowFeedbackMessage = true;
        }

        do {
            ok = myCP.Read_event(out timestamp, out myPS);

            //if chronopic signal is Ok and state has changed
            if (ok && (
                    (myPS == Chronopic.Plataforma.ON && myLS == States.OFF) ||
                    (myPS == Chronopic.Plataforma.OFF && myLS == States.ON) )
                        && !cancel && !finish) {

                //while no finished time or jumps, continue recording events
                if ( ! success) {
                    //don't record the time until the first event of the first Chronopic
                    //this is only executed on the first chronopic that receives a change
                    if (firstValue) {
                        firstValue = false;
                        initializeTimer(); //this is for first Chronopic and only for simulated

                        feedbackMessage = "";
                        needShowFeedbackMessage = true;
                    }

                    if(syncing == syncStates.NOTHING && myPS == Chronopic.Plataforma.ON && myLS == States.OFF) {
                        syncing = syncStates.CONTACTED;
                        feedbackMessage = Catalog.GetString("Release Test button in all Chronopics simultaneously.");
                        needShowFeedbackMessage = true;
                    }
                    else if (syncing == syncStates.CONTACTED && myPS == Chronopic.Plataforma.OFF && myLS == States.ON) {
                        syncing = syncStates.DONE;
                        feedbackMessage = Catalog.GetString("Synchronization done.") + "\n" +
                            Catalog.GetString("Test starts now.");
                        needShowFeedbackMessage = true;
                    }
                    else {
                        if(type != Constants.RunAnalysisName)
                            needSensitiveButtonFinish = true;

                        if(myPS == Chronopic.Plataforma.ON && myLS == States.OFF) {
                            //this is for runAnalysis, delete first tf on 2nd cp (jump cp)
                            if(cpNum == 2 && type == Constants.RunAnalysisName && runAnalysisTfCount == 0)
                                runAnalysisTfCount ++;
                            //this is for multiChronopic, not for runAnalysis
                            else if(deleteFirst && isFirstOut)
                                isFirstOut = false;
                            else {
                                double lastOut = timestamp/1000.0;
                                Log.WriteLine(cpNum.ToString() + " landed: " + lastOut.ToString());
                                outStr = outStr + outEqual + lastOut.ToString();
                                outEqual = "=";
                            }
                            /*
                               if it's a runAnalysis,
                               should end when arrive at 2n photocell (controlled by cp1)
                               */
                            if(cpNum == 1 && type == Constants.RunAnalysisName) {
                                runAnalysisTcCount ++;
                                if(runAnalysisTcCount >= 2) {
                                    success = true;
                                    //better call also finish
                                    //then all cps know about ending
                                    finish = true;
                                }
                            }
                        }
                        else if(myPS == Chronopic.Plataforma.OFF && myLS == States.ON) {
                            //this is for multiChronopic, not for runAnalysis
                            if(deleteFirst && isFirstIn)
                                isFirstIn = false;
                            else {
                                double lastIn = timestamp/1000.0;
                                Log.WriteLine(cpNum.ToString() + " jumped: " + lastIn.ToString());
                                inStr = inStr + inEqual + lastIn.ToString();
                                inEqual = "=";
                            }
                        }

                        PrepareEventGraphMultiChronopicObject = new PrepareEventGraphMultiChronopic(
                                //timestamp/1000.0,
                                cp1StartedIn, cp2StartedIn, cp3StartedIn, cp4StartedIn,
                                cp1InStr, cp1OutStr, cp2InStr, cp2OutStr,
                                cp3InStr, cp3OutStr, cp4InStr, cp4OutStr);
                        needUpdateGraphType = eventType.MULTICHRONOPIC;
                        needUpdateGraph = true;

                        updateProgressBar = new UpdateProgressBar (
                                true, //isEvent
                                false, //means activity mode
                                -1 //don't show text
                                );
                        needUpdateEventProgressBar = true;
                    }
                }

                if(myPS == Chronopic.Plataforma.OFF)
                    myLS = States.OFF;
                else
                    myLS = States.ON;

            }
        } while ( ! success && ! cancel && ! finish );

        if (finish) {
            finishThisCp(cpNum);

            //call write on gui/chronojump.cs, because if done in execute/MultiChronopic,
            //will be called n times if n chronopics are working
            //write(false); //tempTable

            //event will be raised, and managed in chronojump.cs
            //only one call (that comes from first chronopic)
            if(cpNum == 1)
                fakeButtonFinished.Click();
        }
        if(cancel) {
            //event will be raised, and managed in chronojump.cs
            fakeButtonFinished.Click();
            cancelThisCp(cpNum);
        }
    }
Example #11
0
    protected override void waitEvent()
    {
        double timestamp             = 0;
        double timestampFirstContact = 0;    //used when runPhase == runPhases.PLATFORM_INI_YES_TIME;

        double timestampDCFlightTimes  = -1; //sum of the flight times that happen in small time
        double timestampDCContactTimes = -1; //sum of the contact times that happen in small time
        double timestampDCn            = 0;  //number of flight times

        bool success = false;
        bool ok;

        do
        {
            if (simulated)
            {
                ok = true;
            }
            else
            {
                ok = cp.Read_event(out timestamp, out platformState);
            }

            //if (ok) {
            if (ok && !cancel)
            {
                //LogB.Information("timestamp:" + timestamp);
                if (platformState == Chronopic.Plataforma.ON && loggedState == States.OFF)
                {
                    //has arrived
                    loggedState = States.ON;

                    if (runPhase == runPhases.PRE_RUNNING)
                    {
                        if (speedStartArrival)
                        {
                            runPhase = runPhases.PLATFORM_INI_YES_TIME;
                            initializeTimer();                             //timerCount = 0
                        }
                        else
                        {
                            runPhase = runPhases.PLATFORM_INI_NO_TIME;
                        }

                        updateProgressBar = new UpdateProgressBar(
                            true,                                 //isEvent
                            true,                                 //tracksLimited: percentageMode
                            1                                     //just reached platform, phase 1/3
                            );
                        needUpdateEventProgressBar = true;
                    }
                    else
                    {
                        //run finished:
                        //if started outside (behind platform) it's the second arrive
                        //if started inside: it's the first arrive

                        if (simulated)
                        {
                            timestamp = simulatedTimeLast * 1000;                             //conversion to milliseconds
                        }
                        //prevent double contact stuff
                        if (checkDoubleContactMode != Constants.DoubleContact.NONE)
                        {
                            if (timestamp <= checkDoubleContactTime)
                            {
                                /*
                                 * when checking double contact
                                 * first time that timestamp < checkDoubleContactTime
                                 * and we arrived (it's a flight time)
                                 * record this time as timestampDCFlightTimes
                                 */
                                timestampDCn++;
                                timestampDCFlightTimes += timestamp;
                            }
                            else
                            {
                                if (timestampDCn > 0)
                                {
                                    if (checkDoubleContactMode ==
                                        Constants.DoubleContact.FIRST)
                                    {
                                        /* user want first flight time,
                                         * then add all DC times*/
                                        timestamp += timestampDCFlightTimes +
                                                     timestampDCContactTimes;
                                    }
                                    else if (checkDoubleContactMode ==
                                             Constants.DoubleContact.LAST)
                                    {
                                        //user want last flight time, take that
                                        timestamp = timestamp;
                                    }
                                    else                                        /* do the avg of all flights and contacts
                                                                                 * then add to last timestamp */
                                    {
                                        timestamp +=
                                            (timestampDCFlightTimes +
                                             timestampDCContactTimes)
                                            / timestampDCn;
                                    }
                                }
                                success = true;
                            }
                        }

                        if (checkDoubleContactMode == Constants.DoubleContact.NONE)
                        {
                            success = true;
                        }

                        if (success)
                        {
                            runPhase = runPhases.PLATFORM_END;

                            //add the first contact time if PLATFORM_INI_YES_TIME
                            if (timestampFirstContact > 0)
                            {
                                timestamp += timestampFirstContact;
                            }

                            time = timestamp / 1000.0;
                            write();

                            //success = true;

                            updateProgressBar = new UpdateProgressBar(
                                true,                                         //isEvent
                                true,                                         //percentageMode
                                //percentageToPass
                                3
                                );
                            needUpdateEventProgressBar = true;
                        }
                    }
                }
                else if (platformState == Chronopic.Plataforma.OFF && loggedState == States.ON)
                {
                    //it's out, was inside (= has abandoned platform)
                    //don't record time

                    //change the automata state
                    loggedState = States.OFF;

                    if (checkDoubleContactMode != Constants.DoubleContact.NONE && timestampDCn > 0)
                    {
                        timestampDCContactTimes += timestamp;
                    }
                    else
                    {
                        if (runPhase == runPhases.PLATFORM_INI_YES_TIME)
                        {
                            timestampFirstContact = timestamp;
                        }
                        else if (runPhase == runPhases.PLATFORM_INI_NO_TIME)
                        {
                            initializeTimer();                             //timerCount = 0
                        }
                        //update event progressbar
                        updateProgressBar = new UpdateProgressBar(
                            true,                                 //isEvent
                            true,                                 //percentageMode
                            2                                     //normal run, phase 2/3
                            );
                        needUpdateEventProgressBar = true;

                        feedbackMessage         = "";
                        needShowFeedbackMessage = true;

                        runPhase = runPhases.RUNNING;
                    }
                }
            }
        } while (!success && !cancel);

        if (cancel)
        {
            //event will be raised, and managed in chronojump.cs
            fakeButtonFinished.Click();

            totallyCancelled = true;
        }
    }