Пример #1
0
 private void on_fake_button_rows_selected_clicked(object o, EventArgs args)
 {
     LogB.Information("fakeButtonRowsSelected in statType.cs");
     fakeButtonRowsSelected.Click();
 }
Пример #2
0
    public static void Main(string [] args)
    {    /*
          *     bool timeLogPassedOk = Log.Start(args);
          *     Log.WriteLine(string.Format("Time log passed: {0}", timeLogPassedOk.ToString()));
          *     Log.WriteLine(string.Format("Client database option 1 in ... " + Util.GetDatabaseDir()));
          *     Log.WriteLine(string.Format("Client database option 2 in ... " + Util.GetDatabaseTempDir()));
          */
        //1.4.10
        Log.Start();
        LogB.Debugging = true;         //now LogB.Debug will be shown. Also there will be thread info on Warning, Error, Information

        var envPath  = Environment.GetEnvironmentVariable("PATH");
        var rBinPath = "";

        baseDirectory = Util.GetPrefixDir();
        if (UtilAll.IsWindows())
        {
            //Environment.SetEnvironmentVariable ("R_HOME", RelativeToPrefix ("library"));
            //rBinPath = RelativeToPrefix ("lib");
            //rBinPath = RelativeToPrefix ("library");
            //var rPath = System.Environment.Is64BitProcess ? @"C:\Program Files\R\R-3.0.2\bin\x64" : @"C:\Program Files\R\R-3.0.2\bin\i386";
            string x64   = "bin" + System.IO.Path.DirectorySeparatorChar + "x64";
            string i386  = "bin" + System.IO.Path.DirectorySeparatorChar + "i386";
            var    rPath = System.Environment.Is64BitProcess ?
                           System.IO.Path.Combine(baseDirectory, x64) : System.IO.Path.Combine(baseDirectory, i386);

            if (Directory.Exists(rPath) == false)
            {
                throw new DirectoryNotFoundException(string.Format("Could not found the specified path to the directory containing R.dll: {0}", rPath));
                LogB.Error("Could not found the specified path to the directory containing R.dll: ", rPath);
            }

            var newPath = string.Format("{0}{1}{2}", rPath, System.IO.Path.PathSeparator, envPath);
            LogB.Information("newPath:", newPath);

            System.Environment.SetEnvironmentVariable("PATH", newPath);
            LogB.Information("path:", System.Environment.GetEnvironmentVariable("PATH"));

            //use this because we don't want to look at the registry
            //we don't want to force user to install R
            Environment.SetEnvironmentVariable("R_HOME", baseDirectory);
            LogB.Information("R_HOME:", baseDirectory);
        }
        else
        {
            switch (UtilAll.GetOSEnum())
            {
            case UtilAll.OperatingSystems.MACOSX:
                LogB.Information(Environment.GetEnvironmentVariable("R_HOME"));
                rBinPath = "/Library/Frameworks/R.Framework/Libraries";
                Environment.SetEnvironmentVariable("R_HOME", "/Library/Frameworks/R.Framework/Resources");
                Environment.SetEnvironmentVariable("PATH", rBinPath + Path.PathSeparator + envPath);
                LogB.Information("environments");
                LogB.Information(Environment.GetEnvironmentVariable("R_HOME"));
                LogB.Information(Environment.GetEnvironmentVariable("PATH"));

                //Gstreamer stuff
                string prefix = "/Applications/Chronojump.app/Contents/Home/";
                Environment.SetEnvironmentVariable("GST_PLUGIN_PATH", prefix + "lib/gstreamer-0.10");
                Environment.SetEnvironmentVariable("GST_PLUGIN_SYSTEM_PATH", prefix + "lib/gstreamer-0.10");
                Environment.SetEnvironmentVariable("GST_PLUGIN_SCANNER_PATH", prefix + "lib/gstreamer-0.10/gst-plugin-scanner");
                break;

            case UtilAll.OperatingSystems.LINUX:
                rBinPath = @"/usr/lib/R/lib";
                Environment.SetEnvironmentVariable("R_HOME", @"/usr/lib/R");
                Environment.SetEnvironmentVariable("PATH", envPath + Path.PathSeparator + rBinPath);
                break;
            }
        }

        LogB.Information("Platform:" + Environment.OSVersion.Platform);

        LogB.Information("baseDir0:", System.AppDomain.CurrentDomain.BaseDirectory);
        LogB.Information("baseDir1:", baseDirectory);
        LogB.Information("envPath+rBinPath:", envPath + Path.PathSeparator + rBinPath);


        //UtilCSV.ReadValues("/tmp/chronojump-encoder-graph-input-multi.csv");

        if (UtilAll.IsWindows())
        {
            Environment.SetEnvironmentVariable("GST_PLUGIN_PATH", RelativeToPrefix("lib\\gstreamer-0.10"));
        }

        //this call has to be done to chronojump.prg
        //chronojump.prg createBlankDB
        //this creates a blank database and exists.
        //Then new user will have an updated database without the need of creating in
        if (args.Length > 0 && args[0] == "createBlankDB")
        {
            createBlankDB();
            Environment.Exit(1);
        }

        if (args.Length > 0 && args[0] == "createBlankDBServer")
        {
            createBlankDBServer();
            Environment.Exit(1);
        }


        string language = "";

        if (File.Exists(System.IO.Path.Combine(Util.GetDatabaseDir(), "chronojump.db")))
        {
            try {
                Sqlite.Connect();

                /*
                 * chronojump 1.5.2 converts DB 1.24 to 1.25 changing language to ""
                 * but this operation is done later (on sqliteThings)
                 * We need here! to define the language from the beginning
                 * so we use language = "" if version is prior to 1.25
                 */
                string currentVersion       = SqlitePreferences.Select("databaseVersion", false);
                double currentVersionDouble = Convert.ToDouble(Util.ChangeDecimalSeparator(currentVersion));
                if (currentVersionDouble < Convert.ToDouble(Util.ChangeDecimalSeparator("1.25")))
                {
                    language = "";
                }
                else
                {
                    language = SqlitePreferences.Select("language", false);
                }

                Sqlite.DisConnect();

                if (language != "")
                {
                    Environment.SetEnvironmentVariable("LANGUAGE", language);              //works
#if OSTYPE_WINDOWS
                    g_setenv("LANGUAGE", language, true);
#endif
                }
            }
            catch {
                LogB.Warning("Problem reading language on start");
            }
        }

        Catalog.Init("chronojump", System.IO.Path.Combine(Util.GetPrefixDir(), "share/locale"));

        new ChronoJump(args);
    }
Пример #3
0
    /*
     * public static bool CheckPort(string port)
     * {
     *      if(File.Exists(UtilAll.GetECapSimSignalFileName())) { //simulatedEncoder
     *              simulated = true;
     *              return true;
     *      }
     *
     *      simulated = false;
     *
     *      LogB.Information("testing encoder port: ", port);
     *      sp = new SerialPort(port);
     *      sp.BaudRate = 115200;
     *      LogB.Information("testing 1: sp created");
     *      try {
     *              sp.Open();
     *              LogB.Information("testing 2: sp opened");
     *              sp.Close();
     *              LogB.Information("testing 3: sp closed. Success!");
     *      } catch {
     *              LogB.Error("testing encoder port failed");
     *              return false;
     *      }
     *      return true;
     * }
     */

    //if cont (continuous mode), then will not end when too much time passed before start
    public void InitGlobal(int widthG, int heightG, int time, int timeEnd, bool cont, string eccon, string port)
    {
        this.widthG  = widthG;
        this.heightG = heightG;
        this.cont    = cont;
        this.eccon   = eccon;

        //---- a) open port -----
        if (!simulated)
        {
            LogB.Debug("runEncoderCaptureCsharp start port:", port);
            sp          = new SerialPort(port);
            sp.BaudRate = 115200;
            LogB.Information("sp created");
            sp.Open();
            LogB.Information("sp opened");
        }

        //---- b) initialize variables ----

        Ecca = new EncoderCaptureCurveArray();

        Countdown = time;
        msCount   = 0;          //used for visual feedback of remaining time

        recordingTime    = time * 1000;
        recordedTimeCont = 1;         //not 0 to not have divide by zero problems

        encoderReaded                    = new List <int>();
        encoderReadedInertialDisc        = new List <int>();
        EncoderCapturePoints             = new List <Gdk.Point>();
        EncoderCapturePointsInertialDisc = new List <Gdk.Point>();
        EncoderCapturePointsCaptured     = 0;
        EncoderCapturePointsPainted      = 0;           //-1 means delete screen
        sum = 0;

        i = -20;         //delete first records because there's encoder bug

        /*
         * calculate params with R explanation
         */

        /*               3
         *              / \
         *             /   B
         *            /     \
         * --1       /
         *    \     /
         *     \   A
         *      \2/
         *
         * Record the signal, when arrive to A, then store the descending phase (1-2) and calculate params (power, ...)
         * When arrive to B, then store the ascending phase (2-3)
         */

        directionChangePeriod = 25;       //how long (ms) to recognize as change direction. (from 2 to A in ms)
        //it's in ms and not in cm, because it's easier to calculate
        directionChangeCount = 0;         //counter for this period
        directionNow         = 1;         // +1 or -1
        directionLastMSecond = 1;         // +1 or -1 (direction on last millisecond)
        directionCompleted   = -1;        // +1 or -1
        previousEnd          = 0;
        lastNonZero          = 0;

        //this will be used to stop encoder automatically (on !cont mode)
        consecutiveZeros    = -1;
        consecutiveZerosMax = timeEnd * 1000;

        //only can be true on inertial capture subclass
        inertialShouldCheckStartDirection = false;
        inertialCaptureDirectionInverted  = false;

        initSpecific();

        cancel = false;
        finish = false;
    }
Пример #4
0
    //get pending tasks on other stations
    public List <StationCount> GetOtherStationsWithPendingTasks(int personID, int stationID)
    {
        // Create a request using a URL that can receive a post.
        if (!createWebRequest(requestType.GENERIC, "/getOtherStationsWithPendingTasks"))
        {
            return(new List <StationCount>());
        }

        // Set the Method property of the request to POST.
        request.Method = "POST";

        // Set the ContentType property of the WebRequest.
        request.ContentType = "application/json; Charset=UTF-8";         //but this is not enough, see this line:

        // Creates the json object
        JsonObject json = new JsonObject();

        json.Add("personId", personID.ToString());
        json.Add("stationId", stationID.ToString());

        // Converts it to a String
        String js = json.ToString();

        // Writes the json object into the request dataStream
        Stream dataStream;

        if (!getWebRequestStream(request, out dataStream, Catalog.GetString("Could not get tasks from other sessions.")))
        {
            return(new List <StationCount>());
        }

        dataStream.Write(Encoding.UTF8.GetBytes(js), 0, js.Length);
        dataStream.Close();

        HttpWebResponse response;

        if (!getHttpWebResponse(request, out response, Catalog.GetString("Could not get tasks from other sessions.")))
        {
            return(new List <StationCount>());
        }

        string responseFromServer;

        using (var sr = new StreamReader(response.GetResponseStream()))
        {
            responseFromServer = sr.ReadToEnd();
        }

        LogB.Information("GetOtherStationsWithPendingTasks: " + responseFromServer);

        if (responseFromServer == "" || responseFromServer == "[]")
        {
            LogB.Information(" Empty ");
            return(new List <StationCount>());
        }

        //return taskDeserializeFromServer (responseFromServer);
        List <StationCount> stations     = new List <StationCount>();
        JsonValue           jsonStations = JsonValue.Parse(responseFromServer);

        foreach (JsonValue jsonStation in jsonStations)
        {
            string stationName = jsonStation ["stationName"];
            int    tasksCount  = jsonStation ["tasksCount"];
            stations.Add(new StationCount(stationName, tasksCount));
        }
        return(stations);
    }
Пример #5
0
    /*
     * Unused, now using the above methods
     *
     * public EncoderExercise GetEncoderExercise(int exerciseId)
     * {
     *      EncoderExercise ex = new EncoderExercise();
     *
     *      // Create a request using a URL that can receive a post.
     *      WebRequest request = WebRequest.Create (serverUrl + "/getEncoderExercise");
     *
     *      // Set the Method property of the request to POST.
     *      request.Method = "POST";
     *
     *      // Set the ContentType property of the WebRequest.
     *      request.ContentType = "application/json; Charset=UTF-8"; //but this is not enough, see this line:
     *
     *      // Creates the json object
     *      JsonObject json = new JsonObject();
     *      json.Add("exerciseId", exerciseId);
     *
     *      // Converts it to a String
     *      String js = json.ToString();
     *
     *      // Writes the json object into the request dataStream
     *      Stream dataStream;
     *      try {
     *              dataStream = request.GetRequestStream ();
     *      } catch {
     *              this.ResultMessage =
     *                      string.Format(Catalog.GetString("You are not connected to the Internet\nor {0} server is down."),
     *                      serverUrl);
     *              return ex;
     *      }
     *
     *      dataStream.Write (Encoding.UTF8.GetBytes(js), 0, js.Length);
     *
     *      dataStream.Close ();
     *
     *      HttpWebResponse response;
     *      try {
     *              response = (HttpWebResponse) request.GetResponse();
     *      } catch {
     *              this.ResultMessage =
     *                      string.Format(Catalog.GetString("You are not connected to the Internet\nor {0} server is down."),
     *                      serverUrl);
     *              return ex;
     *      }
     *
     *      string responseFromServer;
     *      using (var sr = new StreamReader(response.GetResponseStream()))
     *      {
     *              responseFromServer = sr.ReadToEnd();
     *      }
     *
     *      LogB.Information("GetEncoderExercise: " + responseFromServer);
     *
     *      if(responseFromServer == "")
     *              LogB.Information(" Empty "); //never happens
     *      else if(responseFromServer == "[]")
     *              LogB.Information(" Empty2 "); //when rfid is not on server
     *      else {
     *              ex = encoderExerciseDeserialize(responseFromServer);
     *      }
     *
     *      return ex;
     * }
     * private EncoderExercise encoderExerciseDeserialize(string str)
     * {
     *      JsonValue jsonEx = JsonValue.Parse(str);
     *
     *      Int32 id = jsonEx ["id"];
     *      string name = jsonEx ["name"];
     *      Int32 stationId = jsonEx ["stationId"];
     *      int percentBodyMassDisplaced = jsonEx ["percentBodyMassDisplaced"];
     *
     *      return new EncoderExercise(id, name, percentBodyMassDisplaced,
     *                      "", "", 0); //ressitance, description, speed1RM
     * }
     */

    public bool UploadSprintData(UploadSprintDataObject o)
    {
        LogB.Information("calling upload sprint");
        // Create a request using a URL that can receive a post.
        if (!createWebRequest(requestType.GENERIC, "/uploadSprintData"))
        {
            return(false);
        }

        /*
         * LogB.Information("UploadSprintData doubles:");
         * foreach(double d in splitTimesL)
         *      LogB.Information(d.ToString());
         */

        // Set the Method property of the request to POST.
        request.Method = "POST";

        // Set the ContentType property of the WebRequest.
        request.ContentType = "application/json; Charset=UTF-8";         //but this is not enough, see this line:
        //exerciseName = Util.RemoveAccents(exerciseName);

        // Creates the json object
        JsonObject json = new JsonObject();

        json.Add("personId", o.personId);
        json.Add("distances", o.sprintPositions);
        json.Add("t1", o.splitTimesL[1]);

        //splitTimesL starts with a 0 that is not passed
        if (o.splitTimesL.Count >= 3)
        {
            json.Add("t2", o.splitTimesL[2] - o.splitTimesL[1]);             //return lap (partial time) and not split (accumulated time)
        }
        else
        {
            json.Add("t2", "");
        }

        if (o.splitTimesL.Count >= 4)
        {
            json.Add("t3", o.splitTimesL[3] - o.splitTimesL[2]);
        }
        else
        {
            json.Add("t3", "");
        }

        if (o.splitTimesL.Count >= 5)
        {
            json.Add("t4", o.splitTimesL[4] - o.splitTimesL[3]);
        }
        else
        {
            json.Add("t4", "");
        }

        json.Add("k", o.k);
        json.Add("vmax", o.vmax);
        json.Add("amax", o.amax);
        json.Add("fmax", o.fmax);
        json.Add("pmax", o.pmax);

        // Converts it to a String
        String js = json.ToString();

        // Writes the json object into the request dataStream
        Stream dataStream;

        if (!getWebRequestStream(request, out dataStream, Catalog.GetString("Could not upload sprint data.")))
        {
            return(false);
        }

        dataStream.Write(Encoding.UTF8.GetBytes(js), 0, js.Length);

        dataStream.Close();

        // Get the response.
        WebResponse response;

        if (!getWebResponse(request, out response, Catalog.GetString("Could not upload sprint data.")))
        {
            return(false);
        }


        // Display the status (will be 202, CREATED)
        Console.WriteLine(((HttpWebResponse)response).StatusDescription);

        // Clean up the streams.
        dataStream.Close();
        response.Close();

        this.ResultMessage = "Sprint data sent.";
        return(true);
    }
Пример #6
0
    public bool Ping(string osVersion, string cjVersion, string machineID)
    {
        requestPingAborting = false;

        if (!createWebRequest(requestType.PING, "/ping"))
        {
            return(false);
        }

        // Set the Method property of the request to POST.
        requestPing.Method = "POST";

        // Set the ContentType property of the WebRequest.
        requestPing.ContentType = "application/json";

        // Creates the json object
        JsonObject json = new JsonObject();

        json.Add("os_version", osVersion);
        json.Add("cj_version", cjVersion);
        json.Add("machine_id", machineID);

        // Converts it to a String
        String js = json.ToString();

        // Writes the json object into the request dataStream
        Stream dataStream;

        if (!getWebRequestStream(requestPing, out dataStream, "Could not send ping (A)."))
        {
            return(false);
        }

        if (requestPingAborting)
        {
            LogB.Information("Aborted from PingAbort");
            return(false);
        }

        dataStream.Write(Encoding.UTF8.GetBytes(js), 0, js.Length);

        dataStream.Close();

        // Get the response.
        WebResponse response;

        if (!getWebResponse(requestPing, out response, "Could not send ping (B)."))
        {
            return(false);
        }

        if (requestPingAborting)
        {
            LogB.Information("Aborted from PingAbort");
            return(false);
        }

        // Display the status (will be 201, CREATED)
        Console.WriteLine(((HttpWebResponse)response).StatusDescription);

        // Clean up the streams.
        dataStream.Close();
        response.Close();

        this.ResultMessage = "Ping sent.";
        return(true);
    }
Пример #7
0
    public List <Task> GetTasks(int personID, int stationID)
    {
        connected = false;

        // Create a request using a URL that can receive a post.
        if (!createWebRequest(requestType.GENERIC, "/getTasks"))
        {
            return(new List <Task>());
        }

        // Set the Method property of the request to POST.
        request.Method = "POST";

        // Set the ContentType property of the WebRequest.
        request.ContentType = "application/json; Charset=UTF-8";         //but this is not enough, see this line:

        // Creates the json object
        JsonObject json = new JsonObject();

        json.Add("personId", personID.ToString());
        json.Add("stationId", stationID.ToString());

        // Converts it to a String
        String js = json.ToString();

        // Writes the json object into the request dataStream
        Stream dataStream;

        if (!getWebRequestStream(request, out dataStream, "Cannot get tasks."))
        {
            return(new List <Task>());
        }

        dataStream.Write(Encoding.UTF8.GetBytes(js), 0, js.Length);
        dataStream.Close();

        HttpWebResponse response;

        if (!getHttpWebResponse(request, out response, "Cannot get tasks."))
        {
            return(new List <Task>());
        }

        string responseFromServer;

        using (var sr = new StreamReader(response.GetResponseStream()))
        {
            responseFromServer = sr.ReadToEnd();
        }

        LogB.Information("GetTasks: " + responseFromServer);

        connected = true;

        if (responseFromServer == "" || responseFromServer == "[]")
        {
            LogB.Information(" Empty ");
            return(new List <Task>());
        }

        return(taskDeserializeFromServer(responseFromServer));
    }
Пример #8
0
    public override void ManageFall()
    {
        //boolean to know if chronopic has been disconnected
        chronopicDisconnected = false;

        if (simulated)
        {
            if (fall != -1)
            {
                platformState = Chronopic.Plataforma.OFF;
            }
            else
            {
                platformState = Chronopic.Plataforma.ON;
            }
        }
        else
        {
            platformState = chronopicInitialValue(cp);
        }



        if (platformState != Chronopic.Plataforma.OFF &&
            platformState != Chronopic.Plataforma.ON)
        {
            //UNKNOW (Chronopic disconnected, port changed, ...)
            chronopicHasBeenDisconnected();
            return;
        }

        //if we are outside
        //or we are inside, but with fall == -1 (calculate fall using a previous jump (start inside))
        if (
            (platformState == Chronopic.Plataforma.OFF && fall != -1) ||
            (platformState == Chronopic.Plataforma.ON && fall == -1)
            )
        {
            if (fall != -1)
            {
                feedbackMessage = Catalog.GetString("You are OUT, JUMP when prepared!");
                loggedState     = States.OFF;
            }
            else
            {
                feedbackMessage = Catalog.GetString("You are IN, JUMP when prepared!");
                loggedState     = States.ON;
            }

            needShowFeedbackMessage = true;
            Util.PlaySound(Constants.SoundTypes.CAN_START, volumeOn);


            //useful also for tracking the jump phases
            tc = 0;

            //prepare jump for being cancelled if desired
            cancel = false;

            jumpPhase = jumpPhases.PRE_OR_DOING;

            //in simulated mode, make the jump start just when we arrive to waitEvent at the first time
            if (simulated)
            {
                if (fall != -1)
                {
                    platformState = Chronopic.Plataforma.ON;                     //mark now that we have arrived:
                }
                else
                {
                    platformState = Chronopic.Plataforma.OFF;                     //mark now that we have jumped
                }
            }

            //start thread
            thread = new Thread(new ThreadStart(waitEvent));
            GLib.Idle.Add(new GLib.IdleHandler(PulseGTK));

            LogB.ThreadStart();
            thread.Start();
        }
        else
        {
            ConfirmWindow confirmWin;

            string message = Catalog.GetString("You are IN, please leave the platform, and press the 'accept' button");
            if (fall == -1)
            {
                message = Catalog.GetString("You are OUT, please enter the platform, prepare for jump and press the 'accept' button");
            }

            confirmWin = ConfirmWindow.Show(message, "", "");

            Util.PlaySound(Constants.SoundTypes.BAD, volumeOn);

            //we call again this function
            confirmWin.Button_accept.Clicked += new EventHandler(callAgainManageFall);

            //if confirmWin.Button_cancel is pressed return
            confirmWin.Button_cancel.Clicked += new EventHandler(cancel_event_before_start);
        }
    }
Пример #9
0
    protected override void waitEvent()
    {
        double timestamp = 0;
        bool   success   = false;

        bool ok;
        int  phase = 0;

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

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


            /*
             *           \()/            \()/
             *            \/              \/
             *   _()_     /\     _()_     /\     _()_
             *    \/              \/              \/
             * ___/\______________/\______________/\___
             *
             *  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;
                }
            }
        } while (!success && !cancel);

        LogB.Information("Exited waitEvent main bucle");
    }
Пример #10
0
    protected void writeRj(bool tempTable)
    {
        LogB.Information("----------WRITING----------");
        int    jumps;
        string limitString = "";
        string description = "";

        //if user clicked in finish earlier
        //or toggled with shouldFinishAtNextTime
        if (finish)
        {
            //if user clicked finish and last event was tc, probably there are more TCs than TFs
            //if last event was tc, it has no sense, it should be deleted
            tcString = Util.DeleteLastTcIfNeeded(tcString, tvString);

            //when we mark that jump should finish by time, chronopic thread is probably capturing data
            //check if it captured more than date limit, and if it has done, delete last(s) jump(s)
            //also have in mind that allowFinishAfterTime exist
            bool deletedEvent = false;
            if (!jumpsLimited && limitAsDouble != -1)
            {
                bool eventPassed = Util.EventPassedFromMaxTime(tcString, tvString, limitAsDouble, allowFinishAfterTime);
                while (eventPassed)
                {
                    tcString = Util.DeleteLastSubEvent(tcString);
                    tvString = Util.DeleteLastSubEvent(tvString);
                    LogB.Information("Deleted one event out of time");
                    eventPassed  = Util.EventPassedFromMaxTime(tcString, tvString, limitAsDouble, allowFinishAfterTime);
                    deletedEvent = true;
                }
            }
            if (deletedEvent)
            {
                //update graph if a event was deleted
                PrepareEventGraphJumpReactiveObject = new PrepareEventGraphJumpReactive(Util.GetLast(tvString), Util.GetLast(tcString), tvString, tcString);
                needUpdateGraphType = eventType.JUMPREACTIVE;
                needUpdateGraph     = true;



                //try to fix this:
                //http://mail.gnome.org/archives/chronojump-list/2007-June/msg00013.html
                updateProgressBar = new UpdateProgressBar(
                    true,                                                     //isEvent
                    jumpsLimited,                                             //if jumpsLimited: do fraction; if time limited: do pulse
                    Util.GetNumberOfJumps(tvString, false)
                    );
                needUpdateEventProgressBar = true;
                //and this:
                //http://mail.gnome.org/archives/chronojump-list/2007-June/msg00017.html
                updateTimerCountWithChronopicData(tcString, tvString);
            }

            jumps = Util.GetNumberOfJumps(tvString, false);


            if (jumpsLimited)
            {
                limitString = jumps.ToString() + "J";
            }
            else
            {
                limitString = Util.GetTotalTime(tcString, tvString) + "T";
                limited     = limitString;             //define limited because it's checked in treeviewJump, and possibly it's not the initial defined time (specially when allowFinishRjAfterTime is true)
                //leave the initial selected time into description/comments:
                description = string.Format(Catalog.GetString("Initially selected {0} seconds"), limitAsDouble.ToString());
            }
        }
        else
        {
            if (jumpsLimited)
            {
                limitString = limitAsDouble.ToString() + "J";
                jumps       = (int)limitAsDouble;
            }
            else
            {
                //if time finished and the last event was tc, probably there are more TCs than TFs
                //if last event was tc, it has no sense, it should be deleted
                //this is not aplicable in tempTable
                if (!tempTable)
                {
                    tcString = Util.DeleteLastTcIfNeeded(tcString, tvString);
                }

                //limitString = limitAsDouble.ToString() + "T";
                limitString = Util.GetTotalTime(tcString, tvString) + "T";
                limited     = limitString;             //define limited because it's checked in treeviewJump, and possibly it's not the initial defined time (specially when allowFinishRjAfterTime is true)

                //leave the initial selected time into description/comments:
                description = string.Format(Catalog.GetString("Initially selected {0} seconds"), limitAsDouble.ToString());

                string [] myStringFull = tcString.Split(new char[] { '=' });
                jumps = myStringFull.Length;
            }
        }

        if (type == Constants.RunAnalysisName)
        {
            //double speed = (fall /10) / Util.GetTotalTime(tcString, tvString);

            /*
             *		Josep Ma Padullés test
             *
             *              string tcStringWithoutFirst = Util.DeleteFirstSubEvent(tcString);
             *              string tvStringWithoutFirst = Util.DeleteFirstSubEvent(tvString);
             *
             *              double averagePlatformTimes = ( Util.GetAverage(tcStringWithoutFirst) + Util.GetAverage(tvStringWithoutFirst) ) / 2;
             *              double freq = 1 / averagePlatformTimes;
             *
             *              //amplitud
             *              double range = speed / freq;
             *
             *              //don't put "=" because can appear problems in different parts of the code
             *              description =
             *                      Catalog.GetString ("AVG speed") + "->" + Util.TrimDecimals(speed.ToString(), pDN) + "m/s, " +
             *                      Catalog.GetString ("AVG frequencies") + "->" + Util.TrimDecimals(freq.ToString(), pDN) + "Hz, " +
             *                      Catalog.GetString ("AVG range") + "->" + Util.TrimDecimals(range.ToString(), pDN) + "m.";
             */
        }


        if (tempTable)
        {
            SqliteJumpRj.Insert(false, Constants.TempJumpRjTable, "NULL", personID, sessionID,
                                type, Util.GetMax(tvString), Util.GetMax(tcString),
                                fall, weight, description,
                                Util.GetAverage(tvString), Util.GetAverage(tcString),
                                tvString, tcString,
                                jumps, Util.GetTotalTime(tcString, tvString), limitString, angleString, Util.BoolToNegativeInt(simulated)
                                );
        }
        else
        {
            uniqueID = SqliteJumpRj.Insert(false, Constants.JumpRjTable, "NULL", personID, sessionID,
                                           type, Util.GetMax(tvString), Util.GetMax(tcString),
                                           fall, weight, description,
                                           Util.GetAverage(tvString), Util.GetAverage(tcString),
                                           tvString, tcString,
                                           jumps, Util.GetTotalTime(tcString, tvString), limitString, angleString, Util.BoolToNegativeInt(simulated)
                                           );

            //define the created object
            eventDone = new JumpRj(uniqueID, personID, sessionID, type, tvString, tcString, fall, weight, description, jumps, Util.GetTotalTime(tcString, tvString), limitString, angleString, Util.BoolToNegativeInt(simulated));


            //event will be raised, and managed in chronojump.cs

            /*
             * string myStringPush =
             *      //Catalog.GetString("Last jump: ") +
             *      personName + " " +
             *      type + " (" + limitString + ") " +
             *      " " + Catalog.GetString("AVG TF") + ": " + Util.TrimDecimals( Util.GetAverage (tvString).ToString(), pDN ) +
             *      " " + Catalog.GetString("AVG TC") + ": " + Util.TrimDecimals( Util.GetAverage (tcString).ToString(), pDN ) ;
             */
            if (simulated)
            {
                feedbackMessage = Catalog.GetString(Constants.SimulatedMessage);
            }
            else
            {
                feedbackMessage = "";
            }
            needShowFeedbackMessage = true;

            needEndEvent = true;             //used for hiding some buttons on eventWindow, and also for updateTimeProgressBar here
        }
    }
Пример #11
0
    public override void Manage()
    {
        //boolean to know if chronopic has been disconnected
        chronopicDisconnected = false;

        if (simulated)
        {
            platformState = Chronopic.Plataforma.ON;
        }
        else
        {
            platformState = chronopicInitialValue(cp);
        }


        if (platformState == Chronopic.Plataforma.ON)
        {
            feedbackMessage         = Catalog.GetString("You are IN, JUMP when prepared!");
            needShowFeedbackMessage = true;
            Util.PlaySound(Constants.SoundTypes.CAN_START, volumeOn);

            loggedState = States.ON;

            //prepare jump for being cancelled if desired
            cancel = false;

            jumpPhase = jumpPhases.PRE_OR_DOING;

            //in simulated mode, make the jump start just when we arrive to waitEvent at the first time
            //mark now that we have leaved platform:
            if (simulated)
            {
                platformState = Chronopic.Plataforma.OFF;
            }

            //start thread
            thread = new Thread(new ThreadStart(waitEvent));
            GLib.Idle.Add(new GLib.IdleHandler(PulseGTK));

            LogB.ThreadStart();
            thread.Start();
        }
        else if (platformState == Chronopic.Plataforma.OFF)
        {
            ConfirmWindow confirmWin;
            confirmWin = ConfirmWindow.Show(Catalog.GetString(
                                                "You are OUT, please enter the platform, prepare for jump and press the 'accept' button"), "", "");

            Util.PlaySound(Constants.SoundTypes.BAD, volumeOn);

            //we call again this function
            confirmWin.Button_accept.Clicked += new EventHandler(callAgainManage);

            //if confirmWin.Button_cancel is pressed return
            confirmWin.Button_cancel.Clicked += new EventHandler(cancel_event_before_start);
        }
        else           //UNKNOW (Chronopic disconnected, port changed, ...)
        {
            chronopicHasBeenDisconnected();
        }
    }
Пример #12
0
    private static void on_server_upload_session_started()
    {
        int evalSID = Convert.ToInt32(SqlitePreferences.Select("evaluatorServerID"));

        try {
            ChronojumpServer myServer = new ChronojumpServer();
            LogB.Information(myServer.ConnectDatabase());

            int state = (int)Constants.ServerSessionStates.UPLOADINGSESSION;
            //create ServerSession based on Session currentSession
            ServerSession serverSession = new ServerSession(currentSession, evalSID, progName + " " + progVersion,
                                                            UtilAll.GetOS(), DateTime.Now, state);

            //if uploading session for first time
            if (currentSession.ServerUniqueID == Constants.ServerUndefinedID)
            {
                //upload ServerSession
                int idAtServer = myServer.UploadSession(serverSession);

                //update session currentSession (serverUniqueID) on client database
                currentSession.ServerUniqueID = idAtServer;
                SqliteSession.UpdateServerUniqueID(currentSession.UniqueID, currentSession.ServerUniqueID);
            }

            state = (int)Constants.ServerSessionStates.UPLOADINGDATA;
            myServer.UpdateSession(currentSession.ServerUniqueID, state);

            sessionUploadPersonData.testTypes = "";
            string testTypesSeparator = "";
            sessionUploadPersonData.sports = "";
            string sportsSeparator = "";

            //upload persons (updating also person.serverUniqueID locally)
            ArrayList persons = SqlitePersonSession.SelectCurrentSessionPersons(
                serverSession.UniqueID,
                false);                         //means: do not returnPersonAndPSlist

            Constants.UploadCodes uCode;
            ArrayList             notToUpload = SqlitePersonSessionNotUpload.SelectAll(currentSession.UniqueID);

            //store in variable for updating progressBar from other thread
            progressBarPersonsNum = persons.Count - notToUpload.Count;

            foreach (Person p in persons)
            {
                Person person = p;

                //do not continue with this person if has been banned to upload
                if (Util.FoundInArrayList(notToUpload, person.UniqueID.ToString()))
                {
                    continue;
                }

                PersonSession ps = SqlitePersonSession.Select(person.UniqueID, currentSession.UniqueID);

                //check person if exists
                if (person.ServerUniqueID != Constants.ServerUndefinedID)
                {
                    uCode = Constants.UploadCodes.EXISTS;
                }
                else
                {
                    uCode = Constants.UploadCodes.OK;

                    person = serverUploadPerson(myServer, person, serverSession.UniqueID);
                }

                //if sport is user defined, upload it
                //and when upload the person, do it with new sportID
                Sport sport = SqliteSport.Select(false, ps.SportID);
                //but record old sport ID because locally will be a change in serverUniqueID
                //(with slite update)
                //but local sport has not to be changed
                int sportUserDefinedLocal = -1;

                if (sport.UserDefined)
                {
                    sportUserDefinedLocal = sport.UniqueID;

                    //this will be uploaded
                    int newSport = myServer.UploadSport(sport);
                    if (newSport != -1)
                    {
                        ps.SportID = newSport;
                        sessionUploadPersonData.sports += sportsSeparator + sport.Name;
                        sportsSeparator = ", ";
                    }
                }

                //a person can be in the database for one session,
                //but maybe now we add jumps from another session and we should add an entry at personsession
                serverUploadPersonSessionIfNeeded(myServer, person.ServerUniqueID,
                                                  currentSession.ServerUniqueID, ps, sportUserDefinedLocal);

                //other thread updates the gui:
                sessionUploadPersonData.person     = person;
                sessionUploadPersonData.personCode = uCode;

                //upload jumps
                int countU = 0;
                int countE = 0;
                int countS = 0;

                string [] jumps = SqliteJump.SelectJumps(false, currentSession.UniqueID, person.UniqueID, "", "",
                                                         Sqlite.Orders_by.DEFAULT, -1);
                Sqlite.Open();
                foreach (string myJump in jumps)
                {
                    string [] js = myJump.Split(new char[] { ':' });
                    //select jump
                    Jump test = SqliteJump.SelectJumpData(Convert.ToInt32(js[1]), true);                     //uniqueID
                    //fix it to server person, session keys
                    test.PersonID  = person.ServerUniqueID;
                    test.SessionID = currentSession.ServerUniqueID;

                    //if test is not simulated and has not been uploaded,
                    //see if it's type is not predefined and is not in the database
                    //then upload it first
                    if (test.Simulated == 0)
                    {
                        //upload jumpType if is user defined and doesn't exists in server database
                        //JumpType type = new JumpType(test.Type);
                        JumpType type = SqliteJumpType.SelectAndReturnJumpType(test.Type, true);
                        if (!type.IsPredefined)
                        {
                            //Console.WriteLine("USER DEFINED TEST: " + test.Type);
                            //
                            //this uploads the new type, as it's user created, it will be like this
                            //eg: for user defined jumpType: "supra" of evaluatorServerID: 9
                            //at server will be "supra-9"
                            //then two problems get solved:
                            //1.- every evaluator that uploads a type will have a different name
                            //than other evaluator uploading a type that is named the same but could be different
                            //(one can think that "supra" is another thing
                            //2- when the same evaluator upload some supra's, only a new type is created

                            //test.Type = myServer.UploadJumpType(type, evalSID);
                            //int testType = (int) Constants.TestTypes.JUMP;
                            //string insertedType = myServer.UploadTestType(Constants.TestTypes.JUMP, type, evalSID);
                            //string insertedType = myServer.UploadTestType(testType, type, evalSID);
                            string insertedType = myServer.UploadJumpType(type, evalSID);
                            if (insertedType != "-1")
                            {
                                //record type in test (with the "-7" if it's done by evaluator 7)
                                test.Type = insertedType;

                                //show user uploaded type (without the "-7")
                                sessionUploadPersonData.testTypes += testTypesSeparator + type.Name;
                                testTypesSeparator = ", ";
                            }

                            //test.Type in the server will have the correct name "supra-9"
                        }
                    }

                    //upload... (if not because of simulated or uploaded before, report also the user)
                    uCode = serverUploadTest(myServer, Constants.TestTypes.JUMP, Constants.JumpTable, test);

                    if (uCode == Constants.UploadCodes.OK)
                    {
                        countU++;
                    }
                    else if (uCode == Constants.UploadCodes.EXISTS)
                    {
                        countE++;
                    }
                    else                     //SIMULATED
                    {
                        countS++;
                    }
                }
                Sqlite.Close();

                //other thread updates the gui:
                sessionUploadPersonData.jumpsU = countU;
                sessionUploadPersonData.jumpsE = countE;
                sessionUploadPersonData.jumpsS = countS;

                //upload jumpsRj
                countU = 0;
                countE = 0;
                countS = 0;

                string [] jumpsRj = SqliteJumpRj.SelectJumps(false, currentSession.UniqueID, person.UniqueID, "", "");
                Sqlite.Open();
                foreach (string myJump in jumpsRj)
                {
                    string [] js = myJump.Split(new char[] { ':' });
                    //select jump
                    JumpRj test = SqliteJumpRj.SelectJumpData(Constants.JumpRjTable, Convert.ToInt32(js[1]), true);                     //uniqueID
                    //fix it to server person, session keys
                    test.PersonID  = person.ServerUniqueID;
                    test.SessionID = currentSession.ServerUniqueID;

                    if (test.Simulated == 0)
                    {
                        JumpType type = SqliteJumpType.SelectAndReturnJumpRjType(test.Type, true);
                        if (!type.IsPredefined)
                        {
                            string insertedType = myServer.UploadJumpRjType(type, evalSID);
                            if (insertedType != "-1")
                            {
                                test.Type = insertedType;
                                sessionUploadPersonData.testTypes += testTypesSeparator + type.Name;
                                testTypesSeparator = ", ";
                            }
                        }
                    }

                    //upload...
                    uCode = serverUploadTest(myServer, Constants.TestTypes.JUMP_RJ, Constants.JumpRjTable, test);

                    if (uCode == Constants.UploadCodes.OK)
                    {
                        countU++;
                    }
                    else if (uCode == Constants.UploadCodes.EXISTS)
                    {
                        countE++;
                    }
                    else                     //SIMULATED
                    {
                        countS++;
                    }
                }
                Sqlite.Close();

                //other thread updates the gui:
                sessionUploadPersonData.jumpsRjU = countU;
                sessionUploadPersonData.jumpsRjE = countE;
                sessionUploadPersonData.jumpsRjS = countS;

                //upload runs
                countU = 0;
                countE = 0;
                countS = 0;

                string [] runs = SqliteRun.SelectRuns(false, currentSession.UniqueID, person.UniqueID, "",
                                                      Sqlite.Orders_by.DEFAULT, -1);

                Sqlite.Open();
                foreach (string myRun in runs)
                {
                    string [] js = myRun.Split(new char[] { ':' });
                    //select run
                    Run test = SqliteRun.SelectRunData(Convert.ToInt32(js[1]), true);                     //uniqueID
                    //fix it to server person, session keys
                    test.PersonID  = person.ServerUniqueID;
                    test.SessionID = currentSession.ServerUniqueID;

                    if (test.Simulated == 0)
                    {
                        RunType type = SqliteRunType.SelectAndReturnRunType(test.Type, true);
                        if (!type.IsPredefined)
                        {
                            string insertedType = myServer.UploadRunType(type, evalSID);
                            if (insertedType != "-1")
                            {
                                test.Type = insertedType;
                                sessionUploadPersonData.testTypes += testTypesSeparator + type.Name;
                                testTypesSeparator = ", ";
                            }
                        }
                    }

                    //upload...
                    uCode = serverUploadTest(myServer, Constants.TestTypes.RUN, Constants.RunTable, test);

                    if (uCode == Constants.UploadCodes.OK)
                    {
                        countU++;
                    }
                    else if (uCode == Constants.UploadCodes.EXISTS)
                    {
                        countE++;
                    }
                    else                     //SIMULATED
                    {
                        countS++;
                    }
                }
                Sqlite.Close();

                //other thread updates the gui:
                sessionUploadPersonData.runsU = countU;
                sessionUploadPersonData.runsE = countE;
                sessionUploadPersonData.runsS = countS;

                //upload runs intervallic
                countU = 0;
                countE = 0;
                countS = 0;

                string [] runsI = SqliteRunInterval.SelectRuns(false, currentSession.UniqueID, person.UniqueID, "");
                Sqlite.Open();
                foreach (string myRun in runsI)
                {
                    string [] js = myRun.Split(new char[] { ':' });
                    //select run
                    RunInterval test = SqliteRunInterval.SelectRunData(Constants.RunIntervalTable, Convert.ToInt32(js[1]), true);                     //uniqueID
                    //fix it to server person, session keys
                    test.PersonID  = person.ServerUniqueID;
                    test.SessionID = currentSession.ServerUniqueID;

                    if (test.Simulated == 0)
                    {
                        RunType type = SqliteRunIntervalType.SelectAndReturnRunIntervalType(test.Type, true);
                        if (!type.IsPredefined)
                        {
                            string insertedType = myServer.UploadRunIntervalType(type, evalSID);
                            if (insertedType != "-1")
                            {
                                test.Type = insertedType;
                                sessionUploadPersonData.testTypes += testTypesSeparator + type.Name;
                                testTypesSeparator = ", ";
                            }
                        }
                    }
                    //upload...
                    uCode = serverUploadTest(myServer, Constants.TestTypes.RUN_I, Constants.RunIntervalTable, test);

                    if (uCode == Constants.UploadCodes.OK)
                    {
                        countU++;
                    }
                    else if (uCode == Constants.UploadCodes.EXISTS)
                    {
                        countE++;
                    }
                    else                     //SIMULATED
                    {
                        countS++;
                    }
                }
                Sqlite.Close();

                //other thread updates the gui:
                sessionUploadPersonData.runsIU = countU;
                sessionUploadPersonData.runsIE = countE;
                sessionUploadPersonData.runsIS = countS;

                //upload reaction times
                countU = 0;
                countE = 0;
                countS = 0;

                string [] rts = SqliteReactionTime.SelectReactionTimes(false, currentSession.UniqueID, person.UniqueID,
                                                                       Sqlite.Orders_by.DEFAULT, -1);

                Sqlite.Open();
                foreach (string myRt in rts)
                {
                    string [] js = myRt.Split(new char[] { ':' });
                    //select rt
                    ReactionTime test = SqliteReactionTime.SelectReactionTimeData(Convert.ToInt32(js[1]), true);                     //uniqueID
                    //fix it to server person, session keys
                    test.PersonID  = person.ServerUniqueID;
                    test.SessionID = currentSession.ServerUniqueID;
                    //upload...
                    uCode = serverUploadTest(myServer, Constants.TestTypes.RT, Constants.ReactionTimeTable, test);

                    if (uCode == Constants.UploadCodes.OK)
                    {
                        countU++;
                    }
                    else if (uCode == Constants.UploadCodes.EXISTS)
                    {
                        countE++;
                    }
                    else                     //SIMULATED
                    {
                        countS++;
                    }
                }
                Sqlite.Close();

                //other thread updates the gui:
                sessionUploadPersonData.rtsU = countU;
                sessionUploadPersonData.rtsE = countE;
                sessionUploadPersonData.rtsS = countS;

                //upload pulses
                countU = 0;
                countE = 0;
                countS = 0;

                string [] pulses = SqlitePulse.SelectPulses(false, currentSession.UniqueID, person.UniqueID);
                Sqlite.Open();
                foreach (string myPulse in pulses)
                {
                    string [] js = myPulse.Split(new char[] { ':' });
                    //select pulse
                    Pulse test = SqlitePulse.SelectPulseData(Convert.ToInt32(js[1]), true);                     //uniqueID
                    //fix it to server person, session keys
                    test.PersonID  = person.ServerUniqueID;
                    test.SessionID = currentSession.ServerUniqueID;
                    //upload...
                    uCode = serverUploadTest(myServer, Constants.TestTypes.PULSE, Constants.PulseTable, test);

                    if (uCode == Constants.UploadCodes.OK)
                    {
                        countU++;
                    }
                    else if (uCode == Constants.UploadCodes.EXISTS)
                    {
                        countE++;
                    }
                    else                     //SIMULATED
                    {
                        countS++;
                    }
                }
                Sqlite.Close();

                //other thread updates the gui:
                sessionUploadPersonData.pulsesU = countU;
                sessionUploadPersonData.pulsesE = countE;
                sessionUploadPersonData.pulsesS = countS;

                //upload multiChronopic
                countU = 0;
                countE = 0;
                countS = 0;

                string [] mcs = SqliteMultiChronopic.SelectTests(false, currentSession.UniqueID, person.UniqueID);
                Sqlite.Open();
                foreach (string mc in mcs)
                {
                    string [] js = mc.Split(new char[] { ':' });
                    //select mc
                    MultiChronopic test = SqliteMultiChronopic.SelectMultiChronopicData(Convert.ToInt32(js[1]), true);                     //uniqueID
                    //fix it to server person, session keys
                    test.PersonID  = person.ServerUniqueID;
                    test.SessionID = currentSession.ServerUniqueID;
                    //upload...
                    uCode = serverUploadTest(myServer, Constants.TestTypes.MULTICHRONOPIC, Constants.MultiChronopicTable, test);

                    if (uCode == Constants.UploadCodes.OK)
                    {
                        countU++;
                    }
                    else if (uCode == Constants.UploadCodes.EXISTS)
                    {
                        countE++;
                    }
                    else                     //SIMULATED
                    {
                        countS++;
                    }
                }
                Sqlite.Close();

                //other thread updates the gui:
                sessionUploadPersonData.mcsU = countU;
                sessionUploadPersonData.mcsE = countE;
                sessionUploadPersonData.mcsS = countS;

                needUpdateServerSession = true;
                while (needUpdateServerSession)
                {
                    //wait until data is printed on the other thread
                }
            }

            state = (int)Constants.ServerSessionStates.DONE;
            //myServer.UpdateSession(currentSession.ServerUniqueID, (ServerSessionStates)  Constants.ServerSessionStates.DONE);
            myServer.UpdateSession(currentSession.ServerUniqueID, state);

            LogB.Information(myServer.DisConnectDatabase());
        } catch {
            //other thread updates the gui:
            serverSessionError = true;
        }
    }
Пример #13
0
    //if all persons, put -1 in personID
    public static string[] SelectTests(bool dbconOpened, int sessionID, int personID)
    {
        if (!dbconOpened)
        {
            Sqlite.Open();
        }

        string tp = Constants.PersonTable;

        string filterPersonString = "";

        if (personID != -1)
        {
            filterPersonString = " AND " + tp + ".uniqueID == " + personID;
        }

        dbcmd.CommandText = "SELECT " + tp + ".name, multiChronopic.* " +
                            " FROM " + tp + ", multiChronopic " +
                            " WHERE " + tp + ".uniqueID == multiChronopic.personID" +
                            " AND multiChronopic.sessionID == " + sessionID +
                            filterPersonString +
                            " ORDER BY upper(" + tp + ".name), multiChronopic.uniqueID";

        LogB.SQL(dbcmd.CommandText.ToString());
        dbcmd.ExecuteNonQuery();

        SqliteDataReader reader;

        reader = dbcmd.ExecuteReader();

        ArrayList myArray = new ArrayList(2);

        int count = new int();

        count = 0;


        while (reader.Read())
        {
            //Util.ConvertToPointIfNeeded is used because multichronopic data is recorded by mistake as ',' instead of '.' on database
            myArray.Add(reader[0].ToString() + ":" +                               //person.name
                        reader[1].ToString() + ":" +                               //mc.uniqueID
                        reader[2].ToString() + ":" +                               //mc.personID
                        reader[3].ToString() + ":" +                               //mc.sessionID
                        reader[4].ToString() + ":" +                               //mc.type
                        reader[5].ToString() + ":" +                               //mc.cp1StartedIn
                        reader[6].ToString() + ":" +                               //mc.cp2StartedIn
                        reader[7].ToString() + ":" +                               //mc.cp3StartedIn
                        reader[8].ToString() + ":" +                               //mc.cp4StartedIn
                        Util.ConvertToPointIfNeeded(reader[9].ToString()) + ":" +  //mc.cp1InStr
                        Util.ConvertToPointIfNeeded(reader[10].ToString()) + ":" + //mc.cp1OutStr
                        Util.ConvertToPointIfNeeded(reader[11].ToString()) + ":" + //mc.cp2InStr
                        Util.ConvertToPointIfNeeded(reader[12].ToString()) + ":" + //mc.cp2OutStr
                        Util.ConvertToPointIfNeeded(reader[13].ToString()) + ":" + //mc.cp3InStr
                        Util.ConvertToPointIfNeeded(reader[14].ToString()) + ":" + //mc.cp3OutStr
                        Util.ConvertToPointIfNeeded(reader[15].ToString()) + ":" + //mc.cp4InStr
                        Util.ConvertToPointIfNeeded(reader[16].ToString()) + ":" + //mc.cp4OutStr
                        reader[17].ToString() + ":" +                              //vars
                        reader[18].ToString() + ":" +                              //description
                        reader[19].ToString()                                      //simulated
                        );
            count++;
        }

        reader.Close();

        if (!dbconOpened)
        {
            Sqlite.Close();
        }

        string [] myEvents = new string[count];
        count = 0;
        foreach (string line in myArray)
        {
            myEvents [count++] = line;
        }

        return(myEvents);
    }
Пример #14
0
    public bool ChooseStat()
    {
        if (statisticType == Constants.TypeSessionSummary)
        {
            int    jumperID   = -1;        //all jumpers
            string jumperName = "";        //all jumpers
            if (graph)
            {
                myStat = new GraphGlobal(myStatTypeStruct, jumperID, jumperName);
            }
            else
            {
                myStat = new StatGlobal(myStatTypeStruct, treeview_stats, jumperID, jumperName);
            }
        }
        else if (statisticType == Constants.TypeJumperSummary)
        {
            if (statisticApplyTo.Length == 0)
            {
                LogB.Information("Jumper-ret");
                return(false);
            }
            int jumperID = Util.FetchID(statisticApplyTo);
            if (jumperID == -1)
            {
                return(false);
            }

            string jumperName = Util.FetchName(statisticApplyTo);
            if (graph)
            {
                myStat = new GraphGlobal(myStatTypeStruct, jumperID, jumperName);
            }
            else
            {
                myStat = new StatGlobal(myStatTypeStruct, treeview_stats,
                                        jumperID, jumperName);
            }
        }
        else if (statisticType == Constants.TypeJumpsSimple)
        {
            if (statisticApplyTo.Length == 0)
            {
                LogB.Information("Simple-ret");
                return(false);
            }

            if (statisticSubType != Catalog.GetString("No indexes"))
            {
                string indexType = "";
                if (statisticSubType == Catalog.GetString(Constants.SubtractionBetweenTests))
                {
                    indexType = "subtraction";
                }
                else if (statisticSubType == Constants.ChronojumpProfile)
                {
                    indexType = "ChronojumpProfile";
                }
                else if (statisticSubType == Constants.IeIndexFormula)
                {
                    indexType = "IE";
                }
                else if (statisticSubType == Constants.ArmsUseIndexFormula)
                {
                    indexType = "Arms Use Index";
                }
                else if (statisticSubType == Constants.IRnaIndexFormula)
                {
                    indexType = "IRna";
                }
                else if (statisticSubType == Constants.IRaIndexFormula)
                {
                    indexType = "IRa";
                }
                else if (statisticSubType == Constants.FvIndexFormula)
                {
                    indexType = "F/V";
                }
                else if (
                    statisticSubType == Constants.PotencyLewisFormulaShort ||
                    statisticSubType == Constants.PotencyHarmanFormulaShort ||
                    statisticSubType == Constants.PotencySayersSJFormulaShort ||
                    statisticSubType == Constants.PotencySayersCMJFormulaShort ||
                    statisticSubType == Constants.PotencyShettyFormulaShort ||
                    statisticSubType == Constants.PotencyCanavanFormulaShort ||
                    //statisticSubType == Constants.PotencyBahamondeFormula ||
                    statisticSubType == Constants.PotencyLaraMaleApplicantsSCFormulaShort ||
                    statisticSubType == Constants.PotencyLaraFemaleEliteVoleiFormulaShort ||
                    statisticSubType == Constants.PotencyLaraFemaleMediumVoleiFormulaShort ||
                    statisticSubType == Constants.PotencyLaraFemaleSCStudentsFormulaShort ||
                    statisticSubType == Constants.PotencyLaraFemaleSedentaryFormulaShort
                    )
                {
                    indexType = statisticSubType;
                }

                if (indexType == "subtraction")
                {
                    if (graph)
                    {
                        myStat = new GraphJumpSimpleSubtraction(myStatTypeStruct);
                    }
                    else
                    {
                        myStat = new StatJumpSimpleSubtraction(myStatTypeStruct, treeview_stats);
                    }
                }
                else if (indexType == "ChronojumpProfile")
                {
                    if (graph)
                    {
                        //myStat = new GraphChronojumpProfile(myStatTypeStruct);
                        LogB.Warning("TODO");
                    }
                    else
                    {
                        myStat = new StatChronojumpProfile(myStatTypeStruct, treeview_stats);
                    }
                }
                else if (indexType == "IE" || indexType == Constants.ArmsUseIndexName ||
                         indexType == "IRna" || indexType == "IRa")
                {
                    if (graph)
                    {
                        myStat = new GraphJumpIndexes(myStatTypeStruct, indexType);
                    }
                    else
                    {
                        myStat = new StatJumpIndexes(myStatTypeStruct, treeview_stats, indexType);
                    }
                }
                else if (indexType == "F/V")
                {
                    if (graph)
                    {
                        myStat = new GraphFv(myStatTypeStruct, indexType);
                    }
                    else
                    {
                        myStat = new StatFv(myStatTypeStruct, treeview_stats, indexType);
                    }
                }
                else
                {
                    //indexType = (Potency sayers or lewis);
                    if (graph)
                    {
                        myStat = new GraphPotency(myStatTypeStruct, indexType);
                    }
                    else
                    {
                        myStat = new StatPotency(myStatTypeStruct, treeview_stats, indexType);
                    }
                }
            }
            else
            {
                JumpType myType = new JumpType(statisticApplyTo);

                //manage all weight jumps and the AllJumpsName (simple)
                if (myType.HasWeight ||
                    statisticApplyTo == Constants.AllJumpsName)
                {
                    if (graph)
                    {
                        myStat = new GraphSjCmjAbkPlus(myStatTypeStruct);
                    }
                    else
                    {
                        myStat = new StatSjCmjAbkPlus(myStatTypeStruct, treeview_stats);
                    }
                }
                else
                {
                    if (graph)
                    {
                        myStat = new GraphSjCmjAbk(myStatTypeStruct);
                    }
                    else
                    {
                        myStat = new StatSjCmjAbk(myStatTypeStruct, treeview_stats);
                    }
                }
            }
        }
        else if (statisticType == Constants.TypeJumpsSimpleWithTC)
        {
            if (statisticApplyTo.Length == 0)
            {
                LogB.Information("WithTC-ret");
                return(false);
            }

            if (statisticSubType == Constants.DjIndexFormula)
            {
                if (graph)
                {
                    myStat = new GraphDjIndex(myStatTypeStruct);
                }
                //heightPreferred is not used, check this
                else
                {
                    myStat = new StatDjIndex(myStatTypeStruct, treeview_stats);
                }
                //heightPreferred is not used, check this
            }
            else if (statisticSubType == Constants.QIndexFormula)
            {
                if (graph)
                {
                    myStat = new GraphDjQ(myStatTypeStruct);
                }
                //heightPreferred is not used, check this
                else
                {
                    myStat = new StatDjQ(myStatTypeStruct, treeview_stats);
                }
                //heightPreferred is not used, check this
            }
            else if (statisticSubType == Constants.DjPowerFormula)
            {
                if (graph)
                {
                    myStat = new GraphDjPower(myStatTypeStruct);
                }
                //heightPreferred is not used, check this
                else
                {
                    myStat = new StatDjPower(myStatTypeStruct, treeview_stats);
                }
                //heightPreferred is not used, check this
            }
        }
        else if (statisticType == Constants.TypeJumpsReactive)
        {
            if (statisticSubType == Catalog.GetString("Average Index"))
            {
                if (graph)
                {
                    myStat = new GraphRjIndex(myStatTypeStruct);
                }
                else
                {
                    myStat = new StatRjIndex(myStatTypeStruct, treeview_stats);
                }
            }
            else if (statisticSubType == Constants.RJPotencyBoscoFormula)
            {
                if (graph)
                {
                    myStat = new GraphRjPotencyBosco(myStatTypeStruct);
                }
                else
                {
                    myStat = new StatRjPotencyBosco(myStatTypeStruct, treeview_stats);
                }
            }
            else if (statisticSubType == Catalog.GetString("Evolution"))
            {
                if (graph)
                {
                    myStat = new GraphRjEvolution(myStatTypeStruct, evolution_mark_consecutives);
                }
                else
                {
                    myStat = new StatRjEvolution(myStatTypeStruct, evolution_mark_consecutives, treeview_stats);
                }
            }
            else if (statisticSubType == Constants.RJAVGSDRjIndexName)
            {
                if (graph)
                {
                    myStat = new GraphRjAVGSD(myStatTypeStruct, Constants.RjIndexName);
                }
                else
                {
                    myStat = new StatRjAVGSD(myStatTypeStruct, treeview_stats, Constants.RjIndexName);
                }
            }
            else if (statisticSubType == Constants.RJAVGSDQIndexName)
            {
                if (graph)
                {
                    myStat = new GraphRjAVGSD(myStatTypeStruct, Constants.QIndexName);
                }
                else
                {
                    myStat = new StatRjAVGSD(myStatTypeStruct, treeview_stats, Constants.QIndexName);
                }
            }
        }
        else if (statisticType == Constants.TypeRunsSimple)
        {
            if (statisticApplyTo.Length == 0)
            {
                LogB.Information("Simple-ret");
                return(false);
            }

            if (graph)
            {
                myStat = new GraphRunSimple(myStatTypeStruct);
            }
            else
            {
                myStat = new StatRunSimple(myStatTypeStruct, treeview_stats);
            }
        }
        else if (statisticType == Constants.TypeRunsIntervallic)
        {
            if (statisticApplyTo.Length == 0)
            {
                LogB.Information("Simple-ret");
                return(false);
            }

            if (graph)
            {
                myStat = new GraphRunIntervallic(myStatTypeStruct, evolution_mark_consecutives);
            }
            else
            {
                myStat = new StatRunIntervallic(myStatTypeStruct,
                                                evolution_mark_consecutives, treeview_stats);
            }
        }

        myStat.FakeButtonRowCheckedUnchecked.Clicked +=
            new EventHandler(on_fake_button_row_checked_clicked);
        myStat.FakeButtonRowsSelected.Clicked +=
            new EventHandler(on_fake_button_rows_selected_clicked);
        myStat.FakeButtonNoRowsSelected.Clicked +=
            new EventHandler(on_fake_button_no_rows_selected_clicked);

        myStat.PrepareData();

        if (toReport)
        {
            if (graph)
            {
                bool notEmpty = myStat.CreateGraphR(fileName, false, statCount);                 //dont' show
                if (notEmpty)
                {
                    linkImage(fileName);
                }
            }
            else
            {
                writer.WriteLine(myStat.ReportString());
            }
        }
        else
        {
            if (graph)
            {
                //myStat.CreateGraph();
                myStat.CreateGraphR(Constants.FileNameRGraph, true, -1);                 //show
            }
        }


        //if we just made a graph, store is not made,
        //and we cannot change the Male/female visualizations in the combo
        //with this we can assign a store to the graph (we assign the store of the last stat (not graph)
        if (!toReport)
        {
            if (!graph)
            {
                lastStore = myStat.Store;
            }
            else
            {
                myStat.Store      = lastStore;
                myStat.MarkedRows = markedRows;
            }
        }

        return(true);
    }
Пример #15
0
    /*
     * this method closes the port to "flush" but this doesn't work always
     * is best to use above method that does an explicit flush
     *
     * private bool makeOld(SerialPort sp)
     * {
     *      this.sp = sp;
     *
     *      if (sp == null)
     *              return false;
     *
     *      try {
     *              if (sp != null)
     *                      if (sp.IsOpen) {
     *                              LogB.Information("Port is opened. Closing ... ");
     *                              sp.Close(); //close to ensure no bytes are comming
     *                              LogB.Information("closed");
     *                      }
     *
     *              LogB.Information("opening port... ");
     *              sp.Open();
     *      } catch {
     *              LogB.Warning("catched!");
     *              return false;
     *      }
     *      LogB.Information("opened");
     *
     *      if(IsEncoder)
     *              setEncoderBauds();
     *
     *      str = "";
     *      return true;
     * }
     */

    private void close(SerialPort sp)
    {
        LogB.Information("closing port... ");
        sp.Close();
    }
Пример #16
0
    public override void Manage()
    {
        //boolean to know if chronopic has been disconnected
        chronopicDisconnected = false;

        if (simulated)
        {
            if (hasFall)
            {
                platformState = Chronopic.Plataforma.OFF;
            }
            else
            {
                platformState = Chronopic.Plataforma.ON;
            }
        }
        else
        {
            platformState = chronopicInitialValue(cp);
        }

        if (platformState == Chronopic.Plataforma.OFF)
        {
            loggedState = States.OFF;
        }
        else if (platformState == Chronopic.Plataforma.ON)
        {
            loggedState = States.ON;
        }
        else           //UNKNOW (Chronopic disconnected, port changed, ...)
        {
            chronopicHasBeenDisconnected();
            return;
        }


        bool success = false;

        if (platformState == Chronopic.Plataforma.OFF && hasFall)
        {
            feedbackMessage         = Catalog.GetString("You are OUT, JUMP when prepared!");
            needShowFeedbackMessage = true;
            Util.PlaySound(Constants.SoundTypes.CAN_START, volumeOn);
            success = true;
        }
        else if (platformState == Chronopic.Plataforma.ON && !hasFall)
        {
            feedbackMessage         = Catalog.GetString("You are IN, JUMP when prepared!");
            needShowFeedbackMessage = true;
            Util.PlaySound(Constants.SoundTypes.CAN_START, volumeOn);
            success = true;
        }
        else
        {
            string myMessage = Catalog.GetString("You are IN, please leave the platform, and press the 'accept' button");
            if (platformState == Chronopic.Plataforma.OFF)
            {
                myMessage = Catalog.GetString("You are OUT, please enter the platform, prepare for jump and press the 'accept' button");
            }
            ConfirmWindow confirmWin;
            confirmWin = ConfirmWindow.Show(myMessage, "", "");
            Util.PlaySound(Constants.SoundTypes.BAD, volumeOn);

            //we call again this function
            confirmWin.Button_accept.Clicked += new EventHandler(callAgainManage);
            //if confirmWin.Button_cancel is pressed return
            confirmWin.Button_cancel.Clicked += new EventHandler(cancel_event_before_start);
        }

        if (success)
        {
            //initialize strings of TCs and TFs
            tcString     = "";
            tvString     = "";
            tcCount      = 0;
            tvCount      = 0;
            firstRjValue = true;

            //if jump starts on TF, write a "-1" in TC
            if (!hasFall)
            {
                double myTc = -1;
                tcString = myTc.ToString();
                tcCount  = 1;
            }

            //prepare jump for being cancelled if desired
            cancel = false;

            //prepare jump for being finished earlier if desired
            finish = false;

            jumpPhase = jumpPhases.PRE_OR_DOING;

            //in simulated mode, make the jump start just when we arrive to waitEvent at the first time
            //mark now that the opposite as before:
            if (simulated)
            {
                if (hasFall)
                {
                    platformState = Chronopic.Plataforma.ON;
                }
                else
                {
                    platformState = Chronopic.Plataforma.OFF;
                }
            }

            //start thread
            thread = new Thread(new ThreadStart(waitEvent));
            GLib.Idle.Add(new GLib.IdleHandler(PulseGTK));

            LogB.ThreadStart();
            thread.Start();
        }
    }
Пример #17
0
 private void setEncoderBauds()
 {
     sp.BaudRate = 115200;         //encoder, 20MHz
     LogB.Information("sp.BaudRate = 115200 bauds");
 }
Пример #18
0
    protected override void waitEvent()
    {
        double timestamp = 0;
        bool   success   = false;

        shouldFinishAtNextFall = false;

        bool ok;

        int countForSavingTempTable = 0;

        //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 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
            }
            else
            {
                //cancel a jump if clicked finish before any events done
                cancel = true;
            }
        }
    }
Пример #19
0
    public Person GetPersonByRFID(string rfid)
    {
        connected = false;
        Person person = new Person(-1);

        // Create a request using a URL that can receive a post.
        if (!createWebRequest(requestType.GENERIC, "/getPersonByRFID"))
        {
            return(person);
        }

        // Set the Method property of the request to POST.
        request.Method = "POST";

        // Set the ContentType property of the WebRequest.
        request.ContentType = "application/json; Charset=UTF-8";         //but this is not enough, see this line:

        // Creates the json object
        JsonObject json = new JsonObject();

        json.Add("rfid", rfid);

        // Converts it to a String
        String js = json.ToString();

        // Writes the json object into the request dataStream
        Stream dataStream;

        if (!getWebRequestStream(request, out dataStream, "Cannot get person by RFID."))
        {
            return(person);
        }

        dataStream.Write(Encoding.UTF8.GetBytes(js), 0, js.Length);

        dataStream.Close();

        HttpWebResponse response;

        if (!getHttpWebResponse(request, out response, "Cannot get person by RFID."))
        {
            return(person);
        }

        string responseFromServer;

        using (var sr = new StreamReader(response.GetResponseStream()))
        {
            responseFromServer = sr.ReadToEnd();
        }

        LogB.Information("GetPersonByRFID: " + responseFromServer);

        if (responseFromServer == "")
        {
            LogB.Information(" Empty ");             //never happens
        }
        else if (responseFromServer == "[]")
        {
            LogB.Information(" Empty2 ");             //when rfid is not on server
        }
        else
        {
            //patheticPersonDeserialize("[[2, \"(playername)\", 82.0, \"253,20,150,13\", \"\"]]");
            //patheticPersonDeserialize("[[2, \"(playername)\", 82.0, \"253,20,150,13\", \"jugadors/player.jpg\"]]");
            person = personDeserialize(responseFromServer);
        }

        connected = true;
        return(person);
    }
Пример #20
0
    void on_button_accept_clicked(object o, EventArgs args)
    {
        //ConsoleB.Information(getEntriesString());
        string name = Util.RemoveTildeAndColonAndDot(entry_name.Text);

        name = Util.RemoveChar(name, '"');

        //check if this run type exists, and check it's name is not AllRunsName
        bool runTypeExists = Sqlite.Exists(false, Constants.RunTypeTable, name);

        if (name == Constants.AllRunsName)
        {
            runTypeExists = true;
        }

        if (runTypeExists)
        {
            string myString = string.Format(Catalog.GetString("Race type: '{0}' exists. Please, use another name"), name);
            LogB.Information(myString);
            ErrorWindow.Show(myString);
        }
        else
        {
            RunType type = new RunType();
            type.Name        = name;
            type.Description = Util.RemoveTildeAndColon(textview_description.Buffer.Text);

            if (radiobutton_dist_variable.Active)
            {
                type.Distance = 0;
            }
            else if (radiobutton_dist_fixed.Active)
            {
                type.Distance = spin_distance_fixed.Value;
            }
            else
            {
                //dist_different (only on intervallic)
                type.Distance        = -1;
                type.DistancesString = getEntriesString();
            }

            if (radiobutton_simple.Active)
            {
                SqliteRunType.Insert(type, Constants.RunTypeTable, false);                 //false, because dbcon is not opened
                InsertedSimple = true;
            }
            else
            {
                if (radiobutton_unlimited.Active)
                {
                    //unlimited (but in runs do like if it's limited by seconds: TracksLimited = false
                    //(explanation in sqlite/jumpType.cs)
                    type.TracksLimited = false;
                    type.FixedValue    = 0;
                    type.Unlimited     = true;
                }
                else
                {
                    type.TracksLimited = radiobutton_limited_tracks.Active;

                    if (checkbutton_limited_fixed.Active)
                    {
                        type.FixedValue = Convert.ToInt32(spin_fixed_tracks_or_time.Value);
                    }
                    else
                    {
                        type.FixedValue = 0;
                    }


                    type.Unlimited = false;
                }

                SqliteRunIntervalType.Insert(type, Constants.RunIntervalTypeTable, false);                 //false, because dbcon is not opened
                InsertedSimple = false;
            }

            //LogB.Information(string.Format("Inserted: {0}", type));

            fakeButtonAccept.Click();

            RunTypeAddWindowBox.run_type_add.Hide();
            RunTypeAddWindowBox = null;
        }
    }
Пример #21
0
    public bool PostCrashLog(string email, string comments)
    {
        string filePath = UtilAll.GetLogFileOld();

        if (!File.Exists(filePath))
        {
            this.ResultMessage = Catalog.GetString("Could not send file.\nIt does not exist.");
            return(false);
        }

        if (comments != null && comments != "")
        {
            Util.InsertTextBeginningOfFile(
                "----------\nUser comments:\n" + comments + "\n----------\n", filePath);
        }

        // Create a request using a URL that can receive a post.
        if (!createWebRequest(requestType.GENERIC, "/backtrace/" + UtilAll.ReadVersionFromBuildInfo() + "-" + email))
        {
            return(false);
        }

        // Set the Method property of the request to POST.
        request.Method = "POST";

        // Create POST data and convert it to a byte array.
        byte[] byteArray = readFile(filePath);

        // Set the ContentType property of the WebRequest.
        request.ContentType = "application/x-www-form-urlencoded";

        // Set the ContentLength property of the WebRequest.
        request.ContentLength = byteArray.Length;

        // Get the request stream.
        Stream dataStream;

        if (!getWebRequestStream(request, out dataStream, Catalog.GetString("Could not send file.")))
        {
            return(false);
        }

        // Write the data to the request stream.
        dataStream.Write(byteArray, 0, byteArray.Length);

        // Close the Stream object.
        dataStream.Close();

        // Get the response.
        WebResponse response;

        if (!getWebResponse(request, out response, Catalog.GetString("Could not send file.")))
        {
            return(false);
        }


        // Display the status.
        LogB.Information(((HttpWebResponse)response).StatusDescription);

        // Get the stream containing content returned by the server.
        dataStream = response.GetResponseStream();

        // Open the stream using a StreamReader for easy access.
        StreamReader reader = new StreamReader(dataStream);

        // Read the content.
        string responseFromServer = reader.ReadToEnd();

        // Display the content.
        LogB.Information(responseFromServer);

        // Clean up the streams.
        reader.Close();
        dataStream.Close();
        response.Close();


        JsonValue result   = JsonValue.Parse(responseFromServer);
        string    crash_id = result["crash_id"];

        LogB.Information("crash_id: ", crash_id);

        this.ResultMessage = Catalog.GetString("Log sent. Thank you.");
        return(true);
    }
Пример #22
0
    public int GetPosOfBiggestTC(bool started)
    {
        LogB.Information(string.Format("startPos at GetPosOfBiggestTC: {0}, started: {1}", startPos, started));
        TrackDoneHasToBeCalledAgain = false;

        //Read below message: "Message oneTCAfterTheTf"
        if (countTCs() == 1 && oneTCAfterTheTf())
        {
            return(startPos + 1);
        }

        double max            = 0;
        int    posBiggest     = 0;
        double lastTcDuration = 0;

        /*
         * first time we need to know if first TC is greater than the others
         * but once started, we care for endings of each track,
         * do not use the first value because it's the TC of previous track
         */
        int forStartPos;

        if (started)
        {
            forStartPos = startPos + 1;
        }
        else
        {
            forStartPos = startPos;
        }

        LogB.Information("forStartPos A: " + forStartPos.ToString());

        int tracks = findTracksInThisChunk(forStartPos);

        LogB.Information("findTracksInThisChunk tracks: " + tracks.ToString());

        //on track starts, maybe there are some tc+tf pairs before the big tf
        //A is the track start
        //B is the big tf, we should find biggest tc after this tf
        // A   __   ___B                      __  ___
        if (tracks >= 1)
        {
            forStartPos = findTfPosOfChunk(forStartPos);
            //note forStartPos has changed and following findTfPosOfChunk will start from this tf
        }

        LogB.Information("forStartPos B: " + forStartPos.ToString());

        //this will be the pos of the tf of second Track if exists
        int forEnds = list.Count;

        if (tracks >= 2)
        {
            forEnds = findTfPosOfChunk(forStartPos);
            TrackDoneHasToBeCalledAgain = true;
        }

        LogB.Information("forEnds: " + forEnds.ToString());

        for (int pos = forStartPos; pos < forEnds; pos++)
        {
            RunPhaseInfo rpi = (RunPhaseInfo)list[pos];

            LogB.Information("rpi: " + rpi.ToString());

            /*
             * record tc duration as lastTcDuration and add to tf duration to see if is greater than checktime
             * this allows to return biggest_tc of one track without messing with next track that maybe is captured
             * this happens because double contacts is eg: 300 and trackDone is calle at 300 * 1,5
             * But then trackDone has to be called again!
             */
            if (rpi.IsContact())
            {
                lastTcDuration = rpi.Duration;
            }

            //record posBiggest position
            if (rpi.IsContact() && rpi.Duration > max)
            {
                max        = rpi.Duration;
                posBiggest = pos;
            }
        }

        return(posBiggest);
    }
Пример #23
0
    public List <EncoderExercise> GetStationExercises(int stationId)
    {
        List <EncoderExercise> ex_list = new List <EncoderExercise>();

        // Create a request using a URL that can receive a post.
        if (!createWebRequest(requestType.GENERIC, "/getStationExercises"))
        {
            return(ex_list);
        }

        // Set the Method property of the request to POST.
        request.Method = "POST";

        // Set the ContentType property of the WebRequest.
        request.ContentType = "application/json; Charset=UTF-8";         //but this is not enough, see this line:

        // Creates the json object
        JsonObject json = new JsonObject();

        json.Add("stationId", stationId);

        // Converts it to a String
        String js = json.ToString();

        // Writes the json object into the request dataStream
        Stream dataStream;

        if (!getWebRequestStream(request, out dataStream, Catalog.GetString("Could not get station exercises.")))
        {
            return(ex_list);
        }

        dataStream.Write(Encoding.UTF8.GetBytes(js), 0, js.Length);

        dataStream.Close();

        HttpWebResponse response;

        if (!getHttpWebResponse(request, out response, Catalog.GetString("Could not get station exercises.")))
        {
            return(ex_list);
        }


        string responseFromServer;

        using (var sr = new StreamReader(response.GetResponseStream()))
        {
            responseFromServer = sr.ReadToEnd();
        }

        LogB.Information("GetStationExercises: " + responseFromServer);

        if (responseFromServer == "")
        {
            LogB.Information(" Empty ");             //never happens
        }
        else if (responseFromServer == "[]")
        {
            LogB.Information(" Empty2 ");             //when rfid is not on server
        }
        else
        {
            ex_list = stationExercisesDeserialize(responseFromServer);
        }

        return(ex_list);
    }
Пример #24
0
    public List <RunPhaseTimeListObject> InListForPainting()
    {
        List <RunPhaseTimeListObject> list_in = new List <RunPhaseTimeListObject>();
        int currentMS = 0;
        int startInMS = -1;

        // 1) create a copy of listPhaseTime in order to do foreach without problems with other thread that adds records
        //This is problematic (Collection was modified; enumeration operation may not execute) if other thread is changing it:
        //foreach(PhaseTime pt in listPhaseTime)
        //solution:
        List <PhaseTime> listPhaseTimeShallowCloned = new List <PhaseTime>(listPhaseTime);

        /*
         * 2) check if we started in because 1st TC has to be counted in the track
         * but 2nd TC has to be the end of the first track
         * we need this to synchronize correctly
         */
//		bool startedIn = false;
        if (listPhaseTimeShallowCloned.Count >= 1)
        {
            PhaseTime ptFirst = (PhaseTime)listPhaseTimeShallowCloned[0];
//		if(ptFirst.IsContact)
//				startedIn = true;
        }

        // 3) add elements to the list
        LogB.Information("InListForPainting foreach:");
        int       count          = 0;
        double    negativeValues = 0;      //double contacts times at start
        PhaseTime ptLast         = null;

        RunPhaseTimeListObject.Phases currentPhase = RunPhaseTimeListObject.Phases.START;
        RunPhaseTimeListObject        rptloToAdd   = null;

        foreach (PhaseTime pt in listPhaseTimeShallowCloned)
        {
            LogB.Information(pt.ToString());

            if (FirstRPIs > count)
            {
                negativeValues += pt.Duration / 1000.0;
                LogB.Information("InListForPainting negativeValues = " + negativeValues.ToString());
            }

            if (pt.IsContact)
            {
                startInMS = currentMS;
            }
            else if (startInMS >= 0)
            {
                //see if previous has ended to mark as END or STARTEND
                if (rptloToAdd != null)
                {
                    bool thisPhaseEnds = false;
                    if (list_in.Count == 0 && !SpeedStart)
                    {
                        //on ! speedStart first tc+tf pair, count only tf
                        if (startInMS / 1000.0 - rptloToAdd.tcEnd > checkTime / 1000.0)
                        {
                            thisPhaseEnds = true;
                        }
                    }
                    else if (startInMS / 1000.0 - rptloToAdd.tcStart > checkTime / 1000.0)
                    {
                        thisPhaseEnds = true;
                    }

                    if (thisPhaseEnds)
                    {
                        if (rptloToAdd.phase == RunPhaseTimeListObject.Phases.START)
                        {
                            rptloToAdd.phase = RunPhaseTimeListObject.Phases.STARTANDEND;
                        }
                        else
                        {
                            rptloToAdd.phase = RunPhaseTimeListObject.Phases.END;
                        }

                        currentPhase = RunPhaseTimeListObject.Phases.START;
                    }
                    else
                    {
                        currentPhase = RunPhaseTimeListObject.Phases.MIDDLE;
                    }

                    list_in.Add(rptloToAdd);
                }

                //this will be added in next iteration of flight (! pt.IsContact)
                rptloToAdd = new RunPhaseTimeListObject(
                    currentPhase,
                    startInMS / 1000.0,
                    currentMS / 1000.0);
            }

            currentMS += Convert.ToInt32(pt.Duration);

            LogB.Information(string.Format("End of iteration: {0}, pt.IsContact: {1}, startInMS: {2}, currentMS: {3}",
                                           count, pt.IsContact, startInMS, currentMS));

            ptLast = pt;
            count++;
        }

        //add pending rptl
        if (startInMS / 1000.0 - rptloToAdd.tcStart > checkTime / 1000.0)
        {
            if (rptloToAdd.phase == RunPhaseTimeListObject.Phases.START)
            {
                rptloToAdd.phase = RunPhaseTimeListObject.Phases.STARTANDEND;
            }
            else
            {
                rptloToAdd.phase = RunPhaseTimeListObject.Phases.END;
            }
        }

        list_in.Add(rptloToAdd);

        //when track ends, last phase is a TC, add it
        if (ptLast != null && ptLast.IsContact)
        {
            RunPhaseTimeListObject rptloLast = new RunPhaseTimeListObject(
                RunPhaseTimeListObject.Phases.STARTANDEND,
                startInMS / 1000.0,
                (startInMS + ptLast.Duration) / 1000.0);

            if (rptloToAdd.phase == RunPhaseTimeListObject.Phases.START ||
                rptloToAdd.phase == RunPhaseTimeListObject.Phases.MIDDLE)
            {
                rptloLast.phase = RunPhaseTimeListObject.Phases.END;
            }

            list_in.Add(rptloLast);
        }

        //manage the negative values
        if (negativeValues > 0)
        {
            LogB.Information("Fixing negative values (double contacts times at start)");
            for (int i = 0; i < list_in.Count; i++)
            {
                LogB.Information(string.Format("PRE i: {0}, list_in[{0}]: {1}", i, list_in[i]));

                RunPhaseTimeListObject rptlo = (RunPhaseTimeListObject)list_in[i];
                rptlo.tcStart -= negativeValues;
                rptlo.tcEnd   -= negativeValues;
                list_in[i]     = rptlo;
            }
        }

        return(list_in);
    }
Пример #25
0
    protected void sqliteThings()
    {
        bool crashedBefore = checkIfChronojumpExitAbnormally();

        if (crashedBefore)
        {
            if (chronojumpIsExecutingNTimes())
            {
                quitNow = true;
                LogB.Error("Chronojump is already running.");
                Application.Quit();
                return;
            }
            else
            {
                chronojumpCrashedBefore();
            }
        }

        //print version of chronojump
        progVersion = UtilAll.ReadVersion();

        LogB.Information("Chronojump version: {0}", progVersion);

        //to store user videos and photos
        Util.CreateMultimediaDirsIfNeeded();
        //to store encoder data and graphs
        UtilEncoder.CreateEncoderDirIfNeeded();

//TODO: when a session is deleted, encoder data has to be deleted, also multimedia videos, I suppose. Show message to user warning about it
//TODO: encoder weight auto written depending on person loaded, and changes if it changes person or weight


        //move database to new location if chronojump version is before 0.7
        moveDatabaseToNewLocationIfNeeded();

        LogB.Information("move? ended");

        splashMessageChange(1);          //checking database

        /*
         * splashMessage = "pre-connect";
         * needUpdateSplashMessage = true;
         * Console.ReadLine();
         */

        Sqlite.CreateDir();
        bool defaultDBLocation = Sqlite.Connect();

        LogB.SQL("sqlite connected");

        /*
         * splashMessage = "post-connect" + defaultDBLocation.ToString();
         * needUpdateSplashMessage = true;
         * Console.ReadLine();
         */

        //Chech if the DB file exists
        if (!Sqlite.CheckTables(defaultDBLocation))
        {
            LogB.SQL(Catalog.GetString("no tables, creating ..."));

            creatingDB = true;
            splashMessageChange(2);              //creating database



            /*
             * splashMessage = "pre-create";
             * needUpdateSplashMessage = true;
             * Console.ReadLine();
             */



            Sqlite.CreateDir();
            Sqlite.CreateFile();
            //Sqlite.CreateFile(defaultDBLocation);



            /*
             * splashMessage = "post-create";
             * needUpdateSplashMessage = true;
             * Console.ReadLine();
             */



            createRunningFileName(runningFileName);
            Sqlite.CreateTables(false);             //not server
            creatingDB = false;
        }
        else
        {
            LogB.SQL("doing backup");
            //backup the database
            Util.BackupDirCreateIfNeeded();

            splashMessageChange(3);              //making db backup

            Util.BackupDatabase();
            LogB.SQL("made a database backup");              //not compressed yet, it seems System.IO.Compression.DeflateStream and
            //System.IO.Compression.GZipStream are not in mono


            if (!Sqlite.IsSqlite3())
            {
                bool ok = Sqlite.ConvertFromSqlite2To3();
                if (!ok)
                {
                    LogB.Error("problem with sqlite");
                    //check (spanish)
                    //http://mail.gnome.org/archives/chronojump-devel-list/2008-March/msg00011.html
                    string errorMessage = Catalog.GetString("Failed database conversion, ensure you have libsqlite3-0 installed. \nIf problems persist ask in chronojump-list");
                    errorMessage += "\n\n" + string.Format(Catalog.GetString("If you have no data on your database (you just installed Chronojump), you can fix this problem deleting this file: {0}"),
                                                           Util.GetDatabaseDir() + Path.DirectorySeparatorChar + "chronojump.db") +
                                    "\n" + Catalog.GetString("And starting Chronojump again.");
                    LogB.Error(errorMessage);
                    messageToShowOnBoot += errorMessage;
                    chronojumpHasToExit  = true;
                    return;
                }
                Sqlite.Connect();
            }

            splashMessageChange(4);              //updating DB
            updatingDB = true;

            if (Sqlite.ChangeDjToDJna())
            {
                messageToShowOnBoot += Catalog.GetString("All DJ jumps have been renamed as 'DJna' (Drop Jumps with No Arms).") + "\n\n" +
                                       Catalog.GetString("If your Drop Jumps were executed using the arms, please rename them manually as 'DJa'.") + "\n";
            }

            bool softwareIsNew = Sqlite.ConvertToLastChronojumpDBVersion();
            updatingDB = false;


            if (!softwareIsNew)
            {
                //Console.Clear();
                string errorMessage = string.Format(Catalog.GetString("Sorry, this Chronojump version ({0}) is too old for your database."), progVersion) + "\n" +
                                      Catalog.GetString("Please update Chronojump") + ":\n";
                errorMessage += "http://chronojump.org";
                //errorMessage += "\n\n" + Catalog.GetString("Press any key");
                LogB.Error(errorMessage);
                messageToShowOnBoot += errorMessage;
                chronojumpHasToExit  = true;
            }

            LogB.Information(Catalog.GetString("tables already created"));


            //check for bad Rjs (activate if program crashes and you use it in the same db before v.0.41)
            //SqliteJump.FindBadRjs();

            createRunningFileName(runningFileName);
        }



        //splashMessageChange(5);  //check for new version
        splashMessageChange(5);          //connecting to server

        messageToShowOnBoot += recuperateBrokenEvents();

        //connect to server to Ping
        versionAvailable = "";

        /*
         * pingStart = false;
         * pingEnd = false;
         *
         * // disable server connection on start until server is not working on windows again
         * bool connectServerAtStart = false;
         * if(connectServerAtStart) {
         *      thread = new Thread(new ThreadStart(findVersion));
         *      GLib.Idle.Add (new GLib.IdleHandler (PulseGTKPing));
         *      thread.Start();
         *
         *      //wait until pinging process start
         *      while(! pingStart) {
         *      }
         * }
         * else
         *      on_find_version_cancelled(new object(), new EventArgs());
         */
        versionAvailable = Constants.ServerOffline;


        //doing ping using json methods

        /*
         * temporarily disabled on start
         * string machineID = SqlitePreferences.Select("machineID", false);
         * Json js = new Json();
         * bool success = js.Ping(UtilAll.GetOS(), progVersion, machineID);
         * if(success)
         *      LogB.Information(js.ResultMessage);
         * else
         *      LogB.Error(js.ResultMessage);
         */


        allSQLCallsDoneOnSqliteThingsThread = false;

        //wait until pinging ends (or it's cancelled)
        //while(! pingEnd) {
        //}

        Sqlite.Open();

        string versionAvailableKnown = SqlitePreferences.Select("versionAvailable", true);

        if (versionAvailable != Constants.ServerOffline && new Version(versionAvailable) > new Version(progVersion))
        {
            //check if available version is higher than known available version
            Version versionAvailableAsV = new Version(versionAvailable);

            Version versionAvailableKnownAsV;
            bool    updateKnownVersion = false;
            if (versionAvailableKnown == "")
            {
                updateKnownVersion = true;
            }
            else
            {
                versionAvailableKnownAsV = new Version(versionAvailableKnown);
                if (versionAvailableAsV > versionAvailableKnownAsV)
                {
                    updateKnownVersion = true;
                }
            }

            if (updateKnownVersion)
            {
                //is the first time we know about this new version
                //just write on db and show message to user
                SqlitePreferences.Update(Constants.PrefVersionAvailable, versionAvailable, true);
                versionAvailableKnown = versionAvailable;
                messageToShowOnBoot  += string.Format(Catalog.GetString(
                                                          "\nNew Chronojump version available on website.\nYour Chronojump version is: {1}"),
                                                      versionAvailable, progVersion) + "\n\n" +
                                        Catalog.GetString("Please, update to new version.") + "\n";
            }
        }


        //if chronojump chrashed before
        if (crashedBefore)
        {
            if (versionAvailableKnown.Length > 0 && new Version(versionAvailableKnown) > new Version(progVersion))
            {
                messageToShowOnBoot += "\n" + Catalog.GetString("Chronojump crashed before.") + "\n" +
                                       Catalog.GetString("Please, update to new version: ") + versionAvailableKnown + "\n";
            }
            else
            {
                messageToShowOnBoot += messageCrashedBefore;
                //SqlitePreferences.Update("videoOn", "False", true);
            }
        }


        splashMessageChange(6);          //preparing main window


        //start as "simulated"
        SqlitePreferences.Update("simulated", "True", true);         //dbcon opened

        Sqlite.Close();

        allSQLCallsDoneOnSqliteThingsThread = true;
        LogB.SQL("all SQL calls done on sqliteThings thread");

        UtilAll.IsWindows();            //only as additional info here

        //Application.Init();

        needEndSplashWin = true;
    }
Пример #26
0
    public static string[] SelectPulseTypes(string allPulsesName, bool onlyName)
    {
        //allPulsesName: add and "allPulsesName" value
        //onlyName: return only type name

        Sqlite.Open();
        dbcmd.CommandText = "SELECT * " +
                            " FROM " + Constants.PulseTypeTable +
                            " ORDER BY uniqueID";

        LogB.SQL(dbcmd.CommandText.ToString());
        dbcmd.ExecuteNonQuery();

        SqliteDataReader reader;

        reader = dbcmd.ExecuteReader();

        ArrayList myArray = new ArrayList(2);

        int count = new int();

        count = 0;
        while (reader.Read())
        {
            if (onlyName)
            {
                myArray.Add(reader[1].ToString());
            }
            else
            {
                myArray.Add(reader[0].ToString() + ":" +                        //uniqueID
                            reader[1].ToString() + ":" +                        //name
                            reader[2].ToString() + ":" +                        //fixedPulse
                            reader[3].ToString() + ":" +                        //totalPulsesNum
                            reader[4].ToString()                                //description
                            );
            }
            count++;
        }

        reader.Close();
        Sqlite.Close();

        int numRows;

        if (allPulsesName != "")
        {
            numRows = count + 1;
        }
        else
        {
            numRows = count;
        }
        string [] myTypes = new string[numRows];
        count = 0;
        if (allPulsesName != "")
        {
            myTypes [count++] = allPulsesName;
            //LogB.SQL("{0} - {1}", myTypes[count-1], count-1);
        }
        foreach (string line in myArray)
        {
            myTypes [count++] = line;
            //LogB.SQL("{0} - {1}", myTypes[count-1], count-1);
        }

        return(myTypes);
    }
Пример #27
0
    //move database to new location if chronojump version is before 0.7
    private void moveDatabaseToNewLocationIfNeeded()
    {
        string reallyOldDB = Util.GetReallyOldDatabaseDir();
        string oldDB       = Util.GetOldDatabaseDir();
        string newDB       = Util.GetDatabaseDir();
        string previous    = "";
        bool   moveNeeded  = false;

        if (!Directory.Exists(newDB))
        {
            if (Directory.Exists(oldDB))
            {
                previous   = oldDB;
                moveNeeded = true;
            }
            else if (Directory.Exists(reallyOldDB))
            {
                previous   = reallyOldDB;
                moveNeeded = true;
            }
        }

        if (moveNeeded)
        {
            try {
                Directory.Move(previous, newDB);
            }
            catch {
                string feedback = "";
                feedback += string.Format(Catalog.GetString("Cannot move database directory from {0} to {1}"),
                                          previous, Path.GetFullPath(newDB)) + "\n";
                feedback += string.Format(Catalog.GetString("Trying to move/copy each file now")) + "\n";

                int fileMoveProblems = 0;
                int fileCopyProblems = 0;

                try {
                    Directory.CreateDirectory(newDB);
                    Directory.CreateDirectory(newDB + Path.DirectorySeparatorChar + "backup");

                    string [] filesToMove = Directory.GetFiles(previous);
                    foreach (string oldFile in filesToMove)
                    {
                        string newFile = newDB + Path.DirectorySeparatorChar + oldFile.Substring(oldDB.Length);
                        try {
                            File.Move(oldFile, newFile);
                        }
                        catch {
                            fileMoveProblems++;
                            try {
                                LogB.Warning(string.Format("{0}-{1}", oldFile, newFile));
                                File.Copy(oldFile, newFile);
                            }
                            catch {
                                fileCopyProblems++;
                            }
                        }
                    }
                }
                catch {
                    feedback            += string.Format(Catalog.GetString("Cannot create directory {0}"), Path.GetFullPath(newDB)) + "\n";
                    feedback            += string.Format(Catalog.GetString("Please, do it manually.")) + "\n";
                    feedback            += string.Format(Catalog.GetString("Chronojump will exit now.")) + "\n";
                    messageToShowOnBoot += feedback;
                    LogB.Error(feedback);
                    chronojumpHasToExit = true;
                }
                if (fileCopyProblems > 0)
                {
                    feedback            += string.Format(Catalog.GetString("Cannot copy {0} files from {1} to {2}"), fileCopyProblems, previous, Path.GetFullPath(newDB)) + "\n";
                    feedback            += string.Format(Catalog.GetString("Please, do it manually.")) + "\n";
                    feedback            += string.Format(Catalog.GetString("Chronojump will exit now.")) + "\n";
                    messageToShowOnBoot += feedback;
                    LogB.Error(feedback);
                    chronojumpHasToExit = true;
                }
                if (fileMoveProblems > 0)
                {
                    feedback            += string.Format(Catalog.GetString("Cannot move {0} files from {1} to {2}"), fileMoveProblems, previous, Path.GetFullPath(newDB)) + "\n";
                    feedback            += string.Format(Catalog.GetString("Please, do it manually")) + "\n";
                    messageToShowOnBoot += feedback;
                    LogB.Error(feedback);
                }
            }

            string dbMove = string.Format(Catalog.GetString("Database is now here: {0}"), Path.GetFullPath(newDB));
            messageToShowOnBoot += dbMove;
            LogB.Warning(dbMove);
        }
    }
Пример #28
0
    //private void on_button_discriminative_lights_start_clicked (object o, EventArgs args)
    private void reaction_time_discriminative_lights_prepare()
    {
        //TODO: check if nothing activated, Start should be unsensitive

        if (check_reaction_time_disc_buzzer.Active == true)        //all this are with buzzer
        {
            if (check_reaction_time_disc_red.Active == true)
            {
                if (check_reaction_time_disc_yellow.Active == true)
                {
                    if (check_reaction_time_disc_green.Active == true)
                    {
                        discriminativeCharToSend = "X";                                 //all lights
                    }
                    else
                    {
                        discriminativeCharToSend = "U";                                 //red + yellow
                    }
                }
                else                     //! yellow
                {
                    if (check_reaction_time_disc_green.Active == true)
                    {
                        discriminativeCharToSend = "Y";                                 //red + green
                    }
                    else
                    {
                        discriminativeCharToSend = "R";                                 //red
                    }
                }
            }
            else                        // ! red
            {
                if (check_reaction_time_disc_yellow.Active == true)
                {
                    if (check_reaction_time_disc_green.Active == true)
                    {
                        discriminativeCharToSend = "W";                                 //yellow + green
                    }
                    else
                    {
                        discriminativeCharToSend = "S";                                 //yellow
                    }
                }
                else                            // ! yellow
                {
                    if (check_reaction_time_disc_green.Active == true)
                    {
                        discriminativeCharToSend = "T";                                         //green
                    }
                    else
                    {
                        discriminativeCharToSend = "Z";                                         //only buzzer
                    }
                }
            }
        }
        else                                                    //all this are without buzzer
        {
            if (check_reaction_time_disc_red.Active == true)
            {
                if (check_reaction_time_disc_yellow.Active == true)
                {
                    if (check_reaction_time_disc_green.Active == true)
                    {
                        discriminativeCharToSend = "x";                                 //all lights
                    }
                    else
                    {
                        discriminativeCharToSend = "u";                                 //red + yellow
                    }
                }
                else                     //! yellow
                {
                    if (check_reaction_time_disc_green.Active == true)
                    {
                        discriminativeCharToSend = "y";                                 //red + green
                    }
                    else
                    {
                        discriminativeCharToSend = "r";                                 //red
                    }
                }
            }
            else                        // ! red
            {
                if (check_reaction_time_disc_yellow.Active == true)
                {
                    if (check_reaction_time_disc_green.Active == true)
                    {
                        discriminativeCharToSend = "w";                                 //yellow + green
                    }
                    else
                    {
                        discriminativeCharToSend = "s";                                 //yellow
                    }
                }
                else                                // ! yellow
                {
                    discriminativeCharToSend = "t"; //green
                }
            }
        }

        rnd = new Random();
        double rndDouble = rnd.NextDouble();         //double between 0 and 1
        int    range     = Convert.ToInt32(spinbutton_discriminative_lights_maximum.Value) -
                           Convert.ToInt32(spinbutton_discriminative_lights_minimum.Value);

        discriminativeStartTime = (rndDouble * range) + Convert.ToInt32(spinbutton_discriminative_lights_minimum.Value);

        LogB.Information("discriminativeStartTime");
        LogB.Information(discriminativeStartTime.ToString());

        LogB.Information("discriminativeCharToSend");
        LogB.Information(discriminativeCharToSend);

        //on_button_execute_test_clicked(o, args);
    }
Пример #29
0
    public bool Capture(string outputData1, EncoderRProcCapture encoderRProcCapture)
    {
        if (simulated)
        {
            bool success = initSimulated();
            if (!success)
            {
                return(false);
            }
        }

        do
        {
            try {
                byteReaded = readByte();
            } catch {
                if (!simulated)
                {
                    LogB.Error("Maybe encoder cable is disconnected");
                    cancel = true;
                }

                break;
            }

            byteReaded = convertByte(byteReaded);

            i = i + 1;
            if (i >= 0)
            {
                if (cont)
                {
                    recordedTimeCont++;
                }

                if (inertialCaptureDirectionInverted)
                {
                    byteReaded *= -1;
                }

                if (byteReaded == 0)
                {
                    consecutiveZeros++;
                }
                else
                {
                    consecutiveZeros = -1;
                }

                //stop if n seconds of inactivity
                //but it has to be moved a little bit first, just to give time to the people
                //if(consecutiveZeros >= consecutiveZerosMax && sum > 0) #Not OK because sum maybe is 0: +1,+1,-1,-1
                //if(consecutiveZeros >= consecutiveZerosMax && ecca.ecc.Count > 0) #Not ok because when ecca is created, ecc.Count == 1
                //
                //process ends
                //when a curve has been found and then there are n seconds of inactivity, or
                //when a curve has not been found and then there are 2*n seconds of inactivity
                if (
                    (Ecca.curvesAccepted > 0 && consecutiveZeros >= consecutiveZerosMax) ||
                    (!cont && Ecca.curvesAccepted == 0 && consecutiveZeros >= (2 * consecutiveZerosMax)))
                {
                    finish = true;
                    LogB.Information("SHOULD FINISH");
                }


                sumInertialDisc += byteReaded;
                encoderReadedInertialDisc.Add(byteReaded);

                if (inertialChangedConToEcc())
                {
                    byteReaded *= -1;
                }

                sum += byteReaded;
                encoderReaded.Add(byteReaded);

                assignEncoderCapturePoints();

                EncoderCapturePointsCaptured = i;

                //this only applies to inertial subclass
                if (inertialShouldCheckStartDirection)
                {
                    inertialCheckIfInverted();
                }

                encoderCapturePointsAdaptativeDisplay();

                // ---- prepare to send to R ----

                //if string goes up or down, store the direction
                //direction is only up or down
                if (byteReaded != 0)
                {
                    directionNow = (int)byteReaded / (int)Math.Abs(byteReaded);                       //1 (up) or -1 (down)
                }
                //if we don't have changed the direction, store the last non-zero that we can find
                if (directionChangeCount == 0 && directionNow == directionLastMSecond)
                {
                    //check which is the last non-zero value
                    //this is suitable to find where starts the only-zeros previous to the change
                    if (byteReaded != 0)
                    {
                        lastNonZero = i;
                    }
                }

                bool sendCurveMaybe = false;

                //if it's different than the last direction, mark the start of change
                if (directionNow != directionLastMSecond)
                {
                    directionLastMSecond = directionNow;
                    directionChangeCount = 0;
                }
                else if (directionNow != directionCompleted)
                {
                    //we are in a different direction than the last completed

                    //we cannot add byteReaded because then is difficult to come back n frames to know the max point
                    //directionChangeCount += byteReaded
                    directionChangeCount++;

                    if (directionChangeCount > directionChangePeriod)                           //count >= than change_period
                    {
                        sendCurveMaybe = true;
                    }
                }

                if (sendCurveMaybe)
                {
                    //int startFrame = previousFrameChange - directionChangeCount;	//startFrame

                    /*
                     * at startFrame we do the "-directionChangePeriod" because
                     * we want data a little bit earlier, because we want some zeros
                     * that will be removed by reduceCurveBySpeed
                     * if not done, then the data:
                     * 0 0 0 0 0 0 0 0 0 1
                     * will start at 10th digit (the 1)
                     * if done, then at speed will be like this:
                     * 0 0 0 0.01 0.04 0.06 0.07 0.08 0.09 1
                     * and will start at fourth digit
                     */

                    //this is better, takes a lot of time before, and then reduceCurveBySpeed will cut it
                    //but reduceCurveBySpeed is not implemented on inertial
                    //TODO: implement it
                    int startFrame = previousEnd;                       //startFrame
                    LogB.Debug("startFrame", startFrame.ToString());
                    if (startFrame < 0)
                    {
                        startFrame = 0;
                    }

                    LogB.Information("TTTT - i," + i.ToString() +
                                     "; directionChangeCount: " +
                                     directionChangeCount.ToString() +
                                     "; lastNonZero: " +
                                     lastNonZero.ToString() +
                                     "; final: " +
                                     ((i - directionChangeCount + lastNonZero) / 2).ToString());

                    ecc = new EncoderCaptureCurve(
                        startFrame,
                        (i - directionChangeCount + lastNonZero) / 2                                    //endFrame
                        //to find endFrame, first substract directionChangePeriod from i
                        //then find the middle point between that and lastNonZero
                        //this means that the end is in central point at displacements == 0
                        );

                    //since 1.5.0 secundary thread is capturing and sending data to R process
                    //while main thread is reading data coming from R and updating GUI

                    LogB.Debug("curve stuff" + ecc.startFrame + ":" + ecc.endFrame + ":" + encoderReaded.Count);
                    if (ecc.endFrame - ecc.startFrame > 0)
                    {
                        double [] curve = new double[ecc.endFrame - ecc.startFrame];
                        int       mySum = 0;
                        for (int k = 0, j = ecc.startFrame; j < ecc.endFrame; j++)
                        {
                            curve[k] = encoderReaded[j];
                            k++;
                            mySum += encoderReaded[j];
                        }
                        ecc.up = (mySum >= 0);

                        previousEnd = ecc.endFrame;

                        //22-may-2015: This is done in R now

                        //1) check heightCurve in a fast way first to discard curves soon
                        //   only process curves with height >= min_height
                        //2) if it's concentric, only take the concentric curves,
                        //   but if it's concentric and inertial: take both.
                        //
                        //   When capturing on inertial, we have the first graph
                        //   that will be converted to the second.
                        //   we need the eccentric phase in order to detect the Ci2

                        /*
                         *             /\
                         *            /  \
                         *           /    \
                         *____      C1     \      ___
                         *    \    /        \    /
                         *     \  /          \  C2
                         *      \/            \/
                         *
                         * C1, C2: two concentric phases
                         */

                        /*
                         *____                    ___
                         *    \    /\      /\    /
                         *     \ Ci1 \   Ci2 \ Ci3
                         *      \/    \  /    \/
                         *             \/
                         *
                         * Ci1, Ci2, Ci3: three concentric phases on inertial
                         *
                         * Since 1.6.1:
                         * on inertial curve is sent when rope is fully extended,
                         * this will allow to see at the moment c or e. Not wait the change of direction to see both
                         */


                        if (shouldSendCurve())
                        {
                            encoderRProcCapture.SendCurve(
                                UtilEncoder.CompressData(curve, 25)                                             //compressed
                                );

                            Ecca.curvesAccepted++;
                            Ecca.ecc.Add(ecc);

                            lastDirectionStoredIsUp = ecc.up;
                        }
                    }

                    //on inertial is different
                    markDirectionChanged();
                }

                //this is for visual feedback of remaining time
                msCount++;
                if (msCount >= 1000)
                {
                    Countdown--;
                    msCount = 1;
                }
            }
        } while ((cont || i < (recordingTime - 1)) && !cancel && !finish);

        LogB.Debug("runEncoderCaptureCsharp main bucle end");

        //leave some time to capture.R be able to paint data, and to create two Roptions.txt file correctly
        if (simulated)
        {
            System.Threading.Thread.Sleep(2000);
        }
        else
        {
            sp.Close();
        }

        if (cancel)
        {
            return(false);
        }

        saveToFile(outputData1);

        LogB.Debug("runEncoderCaptureCsharp ended");

        return(true);
    }
Пример #30
0
    //the difference between this select and others, is that this returns and ArrayList of Persons
    //this is better than return the strings that can produce bugs in the future
    //use this in the future:
    public static ArrayList SelectCurrentSessionPersons(int sessionID, bool returnPersonAndPSlist)
    {
        string tp  = Constants.PersonTable;
        string tps = Constants.PersonSessionTable;

        string tpsString = "";

        if (returnPersonAndPSlist)
        {
            tpsString = ", " + tps + ".* ";
        }

        Sqlite.Open();
        dbcmd.CommandText = "SELECT " + tp + ".*" + tpsString +
                            " FROM " + tp + ", " + tps +
                            " WHERE " + tps + ".sessionID == " + sessionID +
                            " AND " + tp + ".uniqueID == " + tps + ".personID " +
                            " ORDER BY upper(" + tp + ".name)";
        LogB.SQL(dbcmd.CommandText.ToString());
        dbcmd.ExecuteNonQuery();
        SqliteDataReader reader;

        reader = dbcmd.ExecuteReader();

        ArrayList myArray = new ArrayList(1);

        while (reader.Read())
        {
            Person person = new Person(
                Convert.ToInt32(reader[0].ToString()),                          //uniqueID
                reader[1].ToString(),                                           //name
                reader[2].ToString(),                                           //sex
                UtilDate.FromSql(reader[3].ToString()),                         //dateBorn
                Convert.ToInt32(reader[4].ToString()),                          //race
                Convert.ToInt32(reader[5].ToString()),                          //countryID
                reader[6].ToString(),                                           //description
                reader[7].ToString(),                                           //future1: rfid
                Convert.ToInt32(reader[9].ToString())                           //serverUniqueID
                );

            if (returnPersonAndPSlist)
            {
                PersonSession ps = new PersonSession(
                    Convert.ToInt32(reader[10].ToString()),                               //uniqueID
                    Convert.ToInt32(reader[11].ToString()),                               //personID
                    Convert.ToInt32(reader[12].ToString()),                               //sessionID
                    Convert.ToDouble(Util.ChangeDecimalSeparator(reader[13].ToString())), //height
                    Convert.ToDouble(Util.ChangeDecimalSeparator(reader[14].ToString())), //weight
                    Convert.ToInt32(reader[15].ToString()),                               //sportID
                    Convert.ToInt32(reader[16].ToString()),                               //speciallityID
                    Convert.ToInt32(reader[17].ToString()),                               //practice
                    reader[18].ToString()                                                 //comments
                    );
                myArray.Add(new PersonAndPS(person, ps));
            }
            else
            {
                myArray.Add(person);
            }
        }
        reader.Close();
        Sqlite.Close();
        return(myArray);
    }