//chronopic init should not touch gtk, for the threads public bool Do(int currentCp, out Chronopic myCp, out SerialPort mySp, Chronopic.Plataforma myPS, string myPort, out string returnString, out bool success) { LogB.Information("starting connection with chronopic"); CancelledByUser = false; success = true; LogB.Information("chronopicInit-1"); LogB.Information(string.Format("chronopic port: {0}", myPort)); mySp = new SerialPort(myPort); try { mySp.Open(); LogB.Information("chronopicInit-2"); //-- Create chronopic object, for accessing chronopic myCp = new Chronopic(mySp); LogB.Information("chronopicInit-2.1"); myCp.Flush(); //if myCp has been cancelled if (myCp.AbortFlush) { LogB.Information("chronopicInit-2.2 cancelled"); success = false; myCp = new Chronopic(); //fake constructor } else { LogB.Information("chronopicInit-3"); //on windows, this check make a crash //i think the problem is: as we don't really know the Timeout on Windows (.NET) and this variable is not defined on chronopic.cs //the Read_platform comes too much soon (when cp is not totally created), and this makes crash //-- Obtener el estado inicial de la plataforma bool ok = false; LogB.Information("chronopicInit-4"); do { LogB.Information("chronopicInit-5"); ok = myCp.Read_platform(out myPS); LogB.Information("chronopicInit-6"); } while(!ok && !CancelledByUser); LogB.Information("chronopicInit-7"); if (!ok) { //-- Si hay error terminar LogB.Error(string.Format("Error: {0}", myCp.Error)); success = false; } } } catch { LogB.Error("chronopicInit-2.a catched"); success = false; myCp = new Chronopic(); //fake constructor } returnString = ""; return(success); }
// public static void MoveTempToEncoderData(int sessionID, int uniqueID) public static string CopyTempToEncoderData(int sessionID, int uniqueID, string personName, string timeStamp) { string fileName = ""; if (File.Exists(GetEncoderDataTempFileName())) { CreateEncoderSessionDirsIfNeeded(sessionID); // try { // File.Move(GetEncoderDataTempFileName(), GetEncoderSessionDataDir(sessionID)); // } catch { fileName = uniqueID.ToString() + "-" + personName + "-" + timeStamp + ".txt"; try { File.Copy(GetEncoderDataTempFileName(), GetEncoderSessionDataSignalDir(sessionID) + Path.DirectorySeparatorChar + fileName, true); } catch { new DialogMessage(Constants.MessageTypes.WARNING, Constants.FileCopyProblem); LogB.Error(Constants.FileCopyProblem); return(""); } // } } return(fileName); }
public bool CaptureBG() { LogB.Information("CaptureBG!"); sp.Open(); LogB.Information("sp opened"); int byteReaded; do { try { byteReaded = readByte(); } catch { LogB.Error("ERROR at InertialCaptureBackground: Maybe encoder cable is disconnected"); return(false); } byteReaded = convertByte(byteReaded); angleNow += byteReaded; if (StoreData) { EncoderCaptureInertialBackgroundStatic.ListCaptured.Add(byteReaded); } //LogB.Information("angleNow = " + angleNow.ToString()); } while (!finishBG); sp.Close(); return(true); }
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); }
private uint getFTDIdevicesWindows() { //based on: http://www.ftdichip.com/Support/SoftwareExamples/CodeExamples/CSharp/EEPROM.zip //UInt32 ftdiDeviceCount = 0; uint ftdiDeviceCount = 0; FTDI.FT_STATUS ftStatus = FTDI.FT_STATUS.FT_OK; // Determine the number of FTDI devices connected to the machine ftStatus = ftdiDeviceWin.GetNumberOfDevices(ref ftdiDeviceCount); // Check status if (ftStatus != FTDI.FT_STATUS.FT_OK) { LogB.Error("FTDI GetNumberOfDevices failed"); return(0); } if (ftdiDeviceCount == 0) { LogB.Information("FTDI GetNumberOfDevices 0"); return(0); } return(ftdiDeviceCount); }
//checks if there are Rjs with different number of TCs than TFs //then repair database manually, and look if the jump is jumpLimited, and how many jumps there are defined public static void FindBadRjs() { Sqlite.Open(); dbcmd.CommandText = "SELECT uniqueID, tcstring, tvstring, jumps, limited FROM jumpRj"; LogB.SQL(dbcmd.CommandText.ToString()); dbcmd.ExecuteNonQuery(); SqliteDataReader reader; reader = dbcmd.ExecuteReader(); reader.Read(); while (reader.Read()) { if (Util.GetNumberOfJumps(reader[1].ToString(), true) != Util.GetNumberOfJumps(reader[2].ToString(), true)) { LogB.Error(string.Format("Problem with jumpRj: {0}, tcstring{1}, tvstring{2}, jumps{3}, limited{4}", reader[0].ToString(), Util.GetNumberOfJumps(reader[1].ToString(), true).ToString(), Util.GetNumberOfJumps(reader[2].ToString(), true).ToString(), reader[3].ToString(), reader[4].ToString())); } } reader.Close(); Sqlite.Close(); }
/* * EXHIBITION //right now does not upload to server when connection returns */ public static void UploadExhibitionTest(ExhibitionTest et) { Json js = new Json(); if (!js.UploadExhibitionTest(et)) { LogB.Error(js.ResultMessage); SqliteJson.InsertTempExhibitionTest(false, et); //insert only if could'nt be uploaded } }
public void ShowNow() { if (GenericWindowBox == null) { LogB.Error("at showNow GenericWindowBox is null!!"); // GenericWindowBox = new GenericWindow(""); } GenericWindowBox.generic_window.Show(); }
public bool CaptureBG(bool simulated) { LogB.Information("CaptureBG!"); if (simulated) { rand = new Random(40); SimulatedReset(); } else { sp.Open(); LogB.Information("sp opened"); } int byteReaded; do { try { if (simulated) { byteReaded = simulateByte(); } else { byteReaded = readByte(); } } catch { LogB.Error("ERROR at InertialCaptureBackground: Maybe encoder cable is disconnected"); return(false); } byteReaded = convertByte(byteReaded); angleNow += byteReaded; if (StoreData) { EncoderCaptureInertialBackgroundStatic.ListCaptured.Add((short)byteReaded); } //LogB.Information("angleNow = " + angleNow.ToString()); } while (!finishBG); if (!simulated) { sp.Close(); } return(true); }
public void ReadStream() { if (stream[1] == "0") { state = false; } else if (stream[1] == "1") { state = true; } else { LogB.Error(Catalog.GetString("Error, state '{0}' non valid"), stream[1]); } }
public int ChangeMultitestFirmware(int debounceChange) { LogB.Information("change_multitest_firmware 3 a"); try { //write change ChronopicAuto ca = new ChronopicAutoChangeDebounce(); ca.Write(sp, debounceChange); //read if ok string ms = ""; bool success = false; int tryNum = 7; //try to connect seven times do { ca = new ChronopicAutoCheckDebounce(); ms = ca.Read(sp); if (ms.Length == 0) { LogB.Error("multitest firmware. ms is null"); } else if (ms[0] == '-') //is negative { LogB.Error("multitest firmware. ms = " + ms); } else { success = true; } tryNum--; } while (!success && tryNum > 0); LogB.Debug("multitest firmware. ms = " + ms); if (ms == "50 ms") { return(50); } else if (ms == "10 ms") { return(10); } } catch { LogB.Error("Could not change debounce"); } return(-1); }
private void on_button_check_last_version_clicked(object o, EventArgs args) { Json js = new Json(); bool success = js.GetLastVersion(progVersion); if (success) { LogB.Information(js.ResultMessage); label_send_log_message.Text = js.ResultMessage; } else { LogB.Error(js.ResultMessage); label_send_log_message.Text = js.ResultMessage; } }
private void on_button_send_log_clicked(object o, EventArgs args) { string email = entry_send_log.Text.ToString(); //email can be validated with Util.IsValidEmail(string) //or other methods, but maybe there's no need of complexity now //1st save email on sqlite if (email != null && email != "" && email != "0" && email != emailStored) { SqlitePreferences.Update("email", email, false); } //2nd add language as comments string language = get_send_log_language(); SqlitePreferences.Update("crashLogLanguage", language, false); string comments = "Answer in: " + language + "\n"; //3rd if there are comments, add them at the beginning of the file comments += textview_comments.Buffer.Text; //4th send Json Json js = new Json(); bool success = js.PostCrashLog(email, comments); if (success) { button_send_log.Label = Catalog.GetString("Thanks"); button_send_log.Sensitive = false; image_send_log_yes.Show(); image_send_log_no.Hide(); LogB.Information(js.ResultMessage); } else { button_send_log.Label = Catalog.GetString("Try again"); image_send_log_yes.Hide(); image_send_log_no.Show(); LogB.Error(js.ResultMessage); } label_send_log_message.Text = js.ResultMessage; }
private static void createBlankDBServer() { LogB.SQL("Creating blank database for server"); if (Sqlite.CheckFileServer()) { LogB.Error("File already exists. Cannot create."); } else { Sqlite.ConnectServer(); Sqlite.CreateFile(); Sqlite.CreateTables(true); //server LogB.SQL("Created blank database! Exiting"); string myVersion = UtilAll.ReadVersion(); LogB.Warning("CAUTION: client info about versionAvailable (on server): ", myVersion); SqlitePreferences.Update("availableVersion", myVersion, false); LogB.Information("Maybe you don't want to show this version on pings, change it to last stable published version"); } }
public static bool CopyEncoderDataToTemp(string url, string fileName) { string origin = url + Path.DirectorySeparatorChar + fileName; string dest = GetEncoderDataTempFileName(); if (File.Exists(origin)) { try { File.Copy(origin, dest, true); } catch { new DialogMessage(Constants.MessageTypes.WARNING, Constants.FileCopyProblem); LogB.Error(Constants.FileCopyProblem); return(false); } return(true); } new DialogMessage(Constants.MessageTypes.WARNING, Constants.FileNotFound); LogB.Error(Constants.FileNotFound); return(false); }
private void on_button_check_last_version_clicked(object o, EventArgs args) { Json js = new Json(); bool success = js.GetLastVersion(progVersion); if (success) { LogB.Information(js.ResultMessage); new DialogMessage( "Chronojump", Constants.MessageTypes.INFO, js.ResultMessage ); } else { LogB.Error(js.ResultMessage); new DialogMessage( "Chronojump", Constants.MessageTypes.WARNING, js.ResultMessage); } }
protected internal static void insertDefault(Constants.EncoderGI encoderGI) { //note DefaultString will not be translated because gettext is changed after this inserts if (encoderGI == Constants.EncoderGI.GRAVITATORY) { Insert(true, new EncoderConfigurationSQLObject( -1, encoderGI, true, Constants.DefaultString, new EncoderConfiguration(), "") //LINEAR, not inertial ); } else if (encoderGI == Constants.EncoderGI.INERTIAL) { EncoderConfiguration ec = new EncoderConfiguration(Constants.EncoderConfigurationNames.ROTARYAXISINERTIAL); ec.SetInertialDefaultOptions(); Insert(true, new EncoderConfigurationSQLObject( -1, encoderGI, true, Constants.DefaultString, ec, "") ); } else { LogB.Error("SqliteEncoderConfiguration.insertDefault with an ALL erroneous value"); } }
public bool Capture(string outputData1, EncoderRProcCapture encoderRProcCapture, bool compujump, Preferences.TriggerTypes cutByTriggers, double restClustersSeconds, bool playSoundsFromFile) { /* * removed at 1.7.0 * if(simulated) { * bool success = initSimulated(); * if(! success) * return false; * } */ lastTriggerOn = 0; inertialCalibratedFirstCross0Pos = 0; //only for cutByTriggers == Preferences.TriggerTypes.START_AT_FIRST_ON bool firstTriggerHappened = false; //playSoundsFromFile DateTime lastTriggeredSound = DateTime.MinValue; if (capturingInertialBG) { /* * reset capture list. If not done here, list will grow at each set * also this fixes the initial 0s after a set */ EncoderCaptureInertialBackgroundStatic.Initialize(); } do { //1 read data try { byteReaded = readByte(); } catch { if (!simulated) { LogB.Error("Maybe encoder cable is disconnected"); cancel = true; } break; } //2 check if readed data is a trigger if (byteReaded == TRIGGER_ON) { if (playSoundsFromFile) { TimeSpan ts = DateTime.Now.Subtract(lastTriggeredSound); if (ts.TotalMilliseconds > 50) { Util.NextSongInList(); lastTriggeredSound = DateTime.Now; } continue; } Trigger trigger = new Trigger(Trigger.Modes.ENCODER, i, true); if (triggerList.IsSpurious(trigger)) { triggerList.RemoveLastOff(); continue; } //TriggerTypes.START_AT_FIRST_ON starts capture at first trigger. So when this happens, reset capture if (cutByTriggers == Preferences.TriggerTypes.START_AT_FIRST_ON && !firstTriggerHappened) { LogB.Information("Cleaning on capture"); startCaptureFromHere(); firstTriggerHappened = true; i = -1; //will be 0 on next loop start continue; } if (cutByTriggers != Preferences.TriggerTypes.NO_TRIGGERS) { ecc = new EncoderCaptureCurve(lastTriggerOn, i); lastTriggerOn = i; 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); ecc.up = true; //make all concentric for the swimming application LogB.Debug("curve stuff" + ecc.startFrame + ":" + ecc.endFrame + ":" + encoderReaded.Count); bool success = encoderRProcCapture.SendCurve( ecc.startFrame, UtilEncoder.CompressData(curve, 25) //compressed ); if (!success) { cancel = true; } Ecca.curvesAccepted++; Ecca.ecc.Add(ecc); LogB.Information(ecc.ToString()); } triggerList.Add(trigger); continue; } else if (byteReaded == TRIGGER_OFF) { if (!playSoundsFromFile) { Trigger trigger = new Trigger(Trigger.Modes.ENCODER, i, false); triggerList.Add(trigger); } continue; } //3 if is not trigger: convertByte byteReaded = convertByte(byteReaded); //LogB.Information(" byte: " + byteReaded); i = i + 1; if (i >= 0) { if (cont) { recordedTimeCont++; } if (byteReaded == 0) { consecutiveZeros++; //clean variables when we are on cont and long time elapsed if (cont && Ecca.curvesAccepted == 0 && consecutiveZeros >= consecutiveZerosMax) { LogB.Information("Cleaning on capture"); //remove this time on existing trigger records triggerList.Substract(consecutiveZeros); startCaptureFromHere(); i = -1; //will be 0 on next loop start continue; } } 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 not in cont and a curve has not been found and then there are 2*n seconds of inactivity * ) and if consecutiveZeros > restClustersSeconds * 1.500 * * 1500 is conversion to milliseconds and * 1.5 to have enough time to move after clusters res */ if ( automaticallyEndByTime && ( (Ecca.curvesAccepted > 0 && consecutiveZeros >= consecutiveZerosMax) || (!cont && Ecca.curvesAccepted == 0 && consecutiveZeros >= (2 * consecutiveZerosMax)) ) && (restClustersSeconds == 0 || consecutiveZeros > restClustersSeconds * 1500) ) { finish = true; LogB.Information("SHOULD FINISH"); } //on inertialCalibrated set mark where 0 is crossed for the first time if (inertialCalibrated && inertialCalibratedFirstCross0Pos == 0) { if ((sumInertialDisc <= 0 && sumInertialDisc + byteReaded > 0) || (sumInertialDisc >= 0 && sumInertialDisc + byteReaded < 0)) { inertialCalibratedFirstCross0Pos = i; } } sumInertialDisc += byteReaded; encoderReadedInertialDisc.Add(byteReaded); if (inertialCalibrated && sumInertialDisc > 0) { byteReaded *= -1; } sum += byteReaded; encoderReaded.Add(byteReaded); if (!showOnlyBars) { assignEncoderCapturePoints(); EncoderCapturePointsCaptured = i; } if (!showOnlyBars) { 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; } } /* * on inertialCalibrated don't send curve until 0 is crossed * this ensures first stored phase will be ecc, that's what the rest of the program is expecting * TODO: maybe this can be problematic with triggers maybe can be desinchronized, just move values */ if (inertialCalibrated && inertialCalibratedFirstCross0Pos == 0) { sendCurveMaybe = false; } //if cutByTriggers, triggers send the curve at the beginning of this method if (cutByTriggers != Preferences.TriggerTypes.NO_TRIGGERS) { sendCurveMaybe = false; } 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; } //on inertial start when crossing 0 first time if (inertialCalibrated && startFrame < inertialCalibratedFirstCross0Pos) { startFrame = inertialCalibratedFirstCross0Pos; } 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 */ //store in a boolean to not call shouldSendCurve() two times because it changes some variables bool shouldSendCurveBool = shouldSendCurve(); if (shouldSendCurveBool) { //if compujump, wakeup screen if it's off //do it on the first repetition because it will not be sleeping on the rest of repetitions if (compujump && Ecca.curvesAccepted == 0) { Networks.WakeUpRaspberryIfNeeded(); } bool success = encoderRProcCapture.SendCurve( ecc.startFrame, UtilEncoder.CompressData(curve, 25) //compressed ); if (!success) { cancel = true; } Ecca.curvesAccepted++; Ecca.ecc.Add(ecc); LogB.Information(ecc.ToString()); 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 if (!capturingInertialBG) { sp.Close(); } if (cancel) { return(false); } saveToFile(outputData1); LogB.Debug("runEncoderCaptureCsharp ended"); return(true); }
public override void Manage() { //boolean to know if chronopic has been disconnected chronopicDisconnected = false; LogB.Error("at Manage!"); if (simulated) { if (StartIn) { platformState = Chronopic.Plataforma.ON; } else { platformState = Chronopic.Plataforma.OFF; } } else { platformState = chronopicInitialValue(cp); } bool canStart = false; if ( (StartIn && platformState == Chronopic.Plataforma.ON) || (!StartIn && platformState == Chronopic.Plataforma.OFF)) { canStart = true; } if (canStart) { feedbackMessage = Catalog.GetString("You are IN, RELEASE when prepared!"); //TODO: change this needShowFeedbackMessage = true; Util.PlaySound(Constants.SoundTypes.CAN_START, volumeOn); if (StartIn) { loggedState = States.ON; } else { loggedState = States.OFF; } //prepare reactionTime for being cancelled if desired cancel = false; totallyCancelled = false; //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) { if (StartIn) { platformState = Chronopic.Plataforma.OFF; } else { platformState = Chronopic.Plataforma.ON; } } //if discriminative, will fire the buttons FakeButtonReactionTimeStart.Click(); } else if (!canStart && (platformState == Chronopic.Plataforma.ON || platformState == Chronopic.Plataforma.OFF)) { ConfirmWindow confirmWin; confirmWin = ConfirmWindow.Show( Catalog.GetString("You are OUT, come inside and press the 'accept' button"), "", ""); //TODO:change this //System.Media.SystemSounds.Beep.Play(); Util.PlaySound(Constants.SoundTypes.BAD, volumeOn); //we call again this function confirmWin.Button_accept.Clicked += new EventHandler(callAgainManage); //if confirmWin.Button_cancel is pressed retuen confirmWin.Button_cancel.Clicked += new EventHandler(cancel_event_before_start); } else //UNKNOW (Chronopic disconnected, port changed, ...) platformStart == some error { chronopicHasBeenDisconnected(); } }
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); }
//chronopic init should not touch gtk, for the threads public bool Do(int currentCp, out Chronopic myCp, out SerialPort mySp, Chronopic.Plataforma myPS, string myPort, out string returnString, out bool success) { LogB.Information("starting connection with chronopic"); CancelledByUser = false; success = true; LogB.Information("chronopicInit-1"); LogB.Information(string.Format("chronopic port: {0}", myPort)); mySp = new SerialPort(myPort); try { mySp.Open(); LogB.Information("chronopicInit-2"); //-- Create chronopic object, for accessing chronopic myCp = new Chronopic(mySp); LogB.Information("chronopicInit-2.1"); myCp.Flush(); //if myCp has been cancelled if (myCp.AbortFlush) { LogB.Information("chronopicInit-2.2 cancelled"); success = false; myCp = new Chronopic(); //fake constructor } else { LogB.Information("chronopicInit-3"); //on windows, this check make a crash //i think the problem is: as we don't really know the Timeout on Windows (.NET) and this variable is not defined on chronopic.cs //the Read_platform comes too much soon (when cp is not totally created), and this makes crash //-- Obtener el estado inicial de la plataforma bool ok = false; LogB.Information("chronopicInit-4"); do { LogB.Information("chronopicInit-5"); ok = myCp.Read_platform(out myPS); LogB.Information("chronopicInit-6"); } while(!ok && !CancelledByUser); LogB.Information("chronopicInit-7"); if (!ok) { //-- Si hay error terminar LogB.Error(string.Format("Error: {0}", myCp.Error)); success = false; } } } catch { LogB.Error("chronopicInit-2.a catched"); success = false; myCp = new Chronopic(); //fake constructor } bool connected = false; returnString = ""; if (success) { if (currentCp == 1) { connected = true; } returnString = string.Format(Catalog.GetString("<b>Connected</b> to Chronopic on port: {0}"), myPort); } else { returnString = Catalog.GetString("Problems communicating to chronopic."); if (currentCp == 1) { returnString += " " + Catalog.GetString("Changed platform to 'Simulated'"); returnString += Catalog.GetString("\n\nWe recommend to remove and connect USB cable."); } //this will raise on_radiobutton_simulated_ativate and //will put cpRunning to false, and simulated to true and cp.Close() if (currentCp == 1) { connected = false; } } return(connected); }
//check if user has disconnected chronopic or port has changed private void checkChronopicDisconnected() { bool errorFound = false; foreach (ChronopicPortData a in cpd) { Chronopic myCP; Chronopic.Plataforma myPS; if (a.Num == 1) { myCP = cp; myPS = platformState; } else if (a.Num == 2) { myCP = cp2; myPS = platformState2; } else if (a.Num == 3) { myCP = cp3; myPS = platformState3; } else { myCP = cp4; myPS = platformState4; } bool ok = false; if (a.Connected) { string myPort = a.Port; //http://www.raspberrypi.org/forums/viewtopic.php?f=66&t=88415 //https://bugzilla.xamarin.com/show_bug.cgi?id=15514 if (!isWindows) { if (!File.Exists(myPort)) { LogB.Error("port does not exists:", myPort); errorFound = true; } } if (!errorFound) { //try { ok = myCP.Read_platform(out myPS); //} catch { // LogB.DebugLine("catch at 1"); //} if (!ok) { LogB.Error("false at 1"); errorFound = true; } } } } if (errorFound) { ArrayList myCPD = new ArrayList(); for (int i = 1; i <= 4; i++) { ChronopicPortData b = new ChronopicPortData(i, "", false); myCPD.Add(b); } Create(myCPD, encoderPort, true, volumeOn); connected = false; new DialogMessage(Constants.MessageTypes.WARNING, Catalog.GetString("One or more Chronopics have been disconnected.") + "\n" + Catalog.GetString("Please connect again, and configure on Chronopic window.")); } }
protected void sqliteThings() { configChronojump = new Config(); configChronojump.Read(); bool badExit = checkIfChronojumpExitAbnormally(); if (badExit) { if (chronojumpIsExecutingNTimes()) { messageToShowOnBoot += Catalog.GetString("Chronojump is already running") + "\n\n" + Catalog.GetString("Chronojump will exit now."); chronojumpHasToExit = true; quitNowCjTwoTimes = true; LogB.Error("Chronojump is already running."); return; } else { chronojumpCrashedBefore(); } } //print version of chronojump progVersion = BuildInfo.chronojumpVersion; LogB.Information("Chronojump version: {0}", progVersion); //to store user videos and photos Util.CreateMultimediaDirsIfNeeded(); //to store (encoder, force sensor, run encoder) data and graphs UtilEncoder.CreateEncoderDirIfNeeded(); Util.CreateForceSensorDirIfNeeded(); Util.CreateRaceAnalyzerDirIfNeeded(); //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 = ""; 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(); //TODO: fix this to the new code 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 (badExit) { 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(); // Chronojump sqlite is in an initialized state, let's keep the Sqlite state here // to be re-used Sqlite.saveClassState(); allSQLCallsDoneOnSqliteThingsThread = true; LogB.SQL("all SQL calls done on sqliteThings thread"); UtilAll.IsWindows(); //only as additional info here //Application.Init(); needEndSplashWin = true; }
protected void printJumpsRj(bool showSubjumps, string title) { int dec = preferences.digitsNumber; //decimals ArrayList myData = new ArrayList(1); bool isFirstHeader = true; if (myJumpsRj.Length > 0) { printTitles(title); } foreach (string jump in myJumpsRj) { if (showSubjumps) { myData = new ArrayList(1); } string weightName = Catalog.GetString("Weight"); if (preferences.weightStatsPercent) { weightName += " %"; } else { weightName += " Kg"; } //TODO: add power and stiffness //if show subjumps show this every time, else show only one if (isFirstHeader || showSubjumps) { myData.Add("\n" + Catalog.GetString("Person ID") + ":" + Catalog.GetString("Person name") + ":" + Catalog.GetString("jump ID") + ":" + Catalog.GetString("jump Type") + ":" + Catalog.GetString("TC Max") + ":" + Catalog.GetString("TF Max") + ":" + Catalog.GetString("Max Height") + ":" + Catalog.GetString("Max Initial Speed") + ":" + Catalog.GetString("TC AVG") + ":" + Catalog.GetString("TF AVG") + ":" + Catalog.GetString("AVG Height") + ":" + Catalog.GetString("AVG Initial Speed") + ":" + Catalog.GetString("Fall") + ":" + weightName + ":" + Catalog.GetString("Jumps") + ":" + Catalog.GetString("Time") + ":" + Catalog.GetString("Limited") + ":" + Catalog.GetString("Description") + ":" + //Catalog.GetString("Angles") + ":" + Catalog.GetString("Simulated") ); isFirstHeader = false; } string [] myStr = jump.Split(new char[] { ':' }); //find weight of person and extra weight int papsPosition = PersonAndPSUtil.Find(myPersonsAndPS, Convert.ToInt32(myStr[2])); //personID if (papsPosition == -1) { LogB.Error("PersonsAndPSUtil don't found person:", myStr[2]); return; } double personWeight = ((PersonAndPS)myPersonsAndPS[papsPosition]).ps.Weight; double extraWeightInKg = Util.WeightFromPercentToKg( Convert.ToDouble(myStr[8]), personWeight); string extraWeightPrint = ""; if (preferences.weightStatsPercent) { extraWeightPrint = myStr[8]; } else { extraWeightPrint = extraWeightInKg.ToString(); } //end of find weight of person and extra weight myData.Add( myStr[2] + ":" + //jumpRj.personID myStr[0] + ":" + myStr[1] + ":" + //person.name, jumpRj.uniqueID //myStr[2] + ":" + myStr[3] + ":" + //jumpRj.personID, jumpRj.sessionID myStr[4] + ":" + //jumpRj.type Util.TrimDecimals(myStr[6], dec) + ":" + //jumpRj.tcMax Util.TrimDecimals(myStr[5], dec) + ":" + //jumpRj.tvMax Util.TrimDecimals(Util.GetHeightInCentimeters(myStr[5]), dec) + ":" + //Max height Util.TrimDecimals(Util.GetInitialSpeed( myStr[5], preferences.metersSecondsPreferred), dec) + ":" + //Max initial speed (true:m/s) Util.TrimDecimals(myStr[11], dec) + ":" + //jumpRj.tcAvg Util.TrimDecimals(myStr[10], dec) + ":" + //jumpRj.tvAvg Util.TrimDecimals(Util.GetHeightInCentimeters(myStr[10]), dec) + ":" + //Avg height Util.TrimDecimals(Util.GetInitialSpeed( myStr[10], preferences.metersSecondsPreferred), dec) + ":" + //Avg Initial speed (true:m/s) myStr[7] + ":" + //jumpRj.Fall //myStr[8] + ":" + myStr[14] + ":" + //jumpRj.Weight, jumpRj.Jumps Util.TrimDecimals(extraWeightPrint, dec) + ":" + myStr[14] + ":" + //jumpRj.Weight, jumpRj.Jumps Util.TrimDecimals(myStr[15], dec) + ":" + Util.GetLimitedRounded(myStr[16], dec) + ":" + //jumpRj.Time, jumpRj.Limited Util.RemoveNewLine(myStr[9], true) + ":" + //jumpRj.Description //myStr[17] + ":" + //jumpRj.Angle Util.SimulatedTestNoYes(Convert.ToInt32(myStr[18])) //simulated ); if (showSubjumps) { writeData(myData); myData = new ArrayList(1); //print tvString and tcString string [] tvString = myStr[12].Split(new char[] { '=' }); string [] tcString = myStr[13].Split(new char[] { '=' }); int count = 0; myData.Add(" " + ":" + Catalog.GetString("TC") + ":" + Catalog.GetString("TF") + ":" + Catalog.GetString("Height") + ":" + Catalog.GetString("Power") + ":" + Catalog.GetString("Stiffness") ); //print Total, AVG, SD myData.Add(Catalog.GetString("Total") + ":" + Util.TrimDecimals(Util.GetTotalTime(myStr[13]).ToString(), dec) + ":" + Util.TrimDecimals(Util.GetTotalTime(myStr[12]).ToString(), dec)); myData.Add(Catalog.GetString("AVG") + ":" + Util.TrimDecimals(Util.GetAverage(myStr[13]).ToString(), dec) + ":" + Util.TrimDecimals(Util.GetAverage(myStr[12]).ToString(), dec)); myData.Add(Catalog.GetString("SD") + ":" + Util.TrimDecimals(Util.CalculateSD( Util.ChangeEqualForColon(myStr[13]), Util.GetTotalTime(myStr[13]), Util.GetNumberOfJumps(myStr[13], false)).ToString(), dec) + ":" + Util.TrimDecimals(Util.CalculateSD( Util.ChangeEqualForColon(myStr[12]), Util.GetTotalTime(myStr[12]), Util.GetNumberOfJumps(myStr[12], false)).ToString(), dec)); foreach (string myTv in tvString) { double tc = Convert.ToDouble(tcString[count]); double tv = Convert.ToDouble(myTv); //on first jump use fall from RJ option //on next jumps calculate from previous TV double fall; if (count == 0) { fall = Convert.ToDouble(myStr[7]); //jumpRj.Fall } else { fall = Convert.ToDouble(Util.GetHeightInCentimeters(tvString[count - 1].ToString())); } myData.Add((count + 1).ToString() + ":" + Util.TrimDecimals(tc, dec) + ":" + Util.TrimDecimals(tv, dec) + ":" + Util.TrimDecimals(Util.GetHeightInCentimeters(tv.ToString()), dec) + ":" + Util.TrimDecimals(getPower(tc, tv, personWeight, extraWeightInKg, fall), dec) + ":" + Util.TrimDecimals(Util.GetStiffness(personWeight, extraWeightInKg, tv, tc), dec) ); count++; } writeData(myData); writeData("VERTICAL-SPACE"); } } //if not showSubjumps write data at last for not having every row as TH if (!showSubjumps) { writeData(myData); } }
protected void printJumps(string title) { int dec = preferences.digitsNumber; //decimals string weightName = Catalog.GetString("Weight"); if (preferences.weightStatsPercent) { weightName += " %"; } else { weightName += " Kg"; } if (myJumps.Length > 0) { printTitles(title); ArrayList myData = new ArrayList(1); myData.Add("\n" + Catalog.GetString("Person ID") + ":" + Catalog.GetString("Person name") + ":" + Catalog.GetString("jump ID") + ":" + Catalog.GetString("Type") + ":" + Catalog.GetString("TC") + ":" + Catalog.GetString("TF") + ":" + Catalog.GetString("Fall") + ":" + weightName + ":" + Catalog.GetString("Height") + ":" + Catalog.GetString("Power") + ":" + Catalog.GetString("Stiffness") + ":" + Catalog.GetString("Initial Speed") + ":" + Catalog.GetString("Description") + ":" + Catalog.GetString("Angle") + ":" + Catalog.GetString("Simulated") ); foreach (string jumpString in myJumps) { string [] myStr = jumpString.Split(new char[] { ':' }); //find weight of person and extra weight int papsPosition = PersonAndPSUtil.Find(myPersonsAndPS, Convert.ToInt32(myStr[2])); //personID if (papsPosition == -1) { LogB.Error("PersonsAndPSUtil don't found person:", myStr[2]); return; } double personWeight = ((PersonAndPS)myPersonsAndPS[papsPosition]).ps.Weight; double extraWeightInKg = Util.WeightFromPercentToKg( Convert.ToDouble(myStr[8]), personWeight); string extraWeightPrint = ""; if (preferences.weightStatsPercent) { extraWeightPrint = myStr[8]; } else { extraWeightPrint = extraWeightInKg.ToString(); } //end of find weight of person and extra weight double fall = Convert.ToDouble(myStr[7]); double tc = Convert.ToDouble(myStr[6]); double tf = Convert.ToDouble(myStr[5]); myData.Add( myStr[2] + ":" + myStr[0] + ":" + //person.UniqueID, person.Name myStr[1] + ":" + //jump.uniqueID myStr[4] + ":" + Util.TrimDecimals(myStr[6], dec) + ":" + //jump.type, jump.tc Util.TrimDecimals(myStr[5], dec) + ":" + Util.TrimDecimals(myStr[7], dec) + ":" + //jump.tv, jump.fall Util.TrimDecimals(extraWeightPrint, dec) + ":" + Util.TrimDecimals(Util.GetHeightInCentimeters(myStr[5]), dec) + ":" + Util.TrimDecimals(getPower(tc, tf, personWeight, extraWeightInKg, fall), dec) + ":" + Util.TrimDecimals(Util.GetStiffness(personWeight, extraWeightInKg, tf, tc), dec) + ":" + Util.TrimDecimals(Util.GetInitialSpeed(myStr[5], preferences.metersSecondsPreferred), dec) + ":" + //true: m/s Util.RemoveNewLine(myStr[9], true) + ":" + //jump.description Util.TrimDecimals(myStr[10], dec) + ":" + //jump.angle Util.SimulatedTestNoYes(Convert.ToInt32(myStr[11])) //jump.simulated ); } writeData(myData); writeData("VERTICAL-SPACE"); } }
public static string EncoderSaveCurve(string fileNameSignal, int start, int duration, int inertialCheckStart, int inertialCheckDuration, bool inertialCheckPositive, //has to be positive (true) or negative (false) int sessionID, int uniqueID, string personName, string timeStamp, int curveIDMax) { string contents = Util.ReadFile(fileNameSignal, false); LogB.Information("EncoderSaveCurve start:" + start.ToString() + "; duration:" + duration.ToString()); /* * at inertial signals, first curve is eccentric (can be to left or right, maybe positive or negative) * graph.R manages correctly this * But, when saved a curve, eg. concentric this can be positive or negative * (depending on the rotating sign of inertial machine at that curve) * if it's concentric, and it's full of -1,-2,... we have to change sign * if it's eccentric-concentric, and in the eccentric phase is positive, then we should change sign of both phases */ bool reverseSign = false; if (inertialCheckStart != 0 && inertialCheckDuration != 0) { string [] startAndDurationCheckInertial = encoderFindPos(contents, inertialCheckStart, inertialCheckDuration); string contentsCheckInertial = contents.Substring( Convert.ToInt32(startAndDurationCheckInertial[0]), Convert.ToInt32(startAndDurationCheckInertial[1]) - 1); //-1 is for not ending file with a comma //see mean of contentsCheckInertial int sum = 0; int count = 0; using (StringReader reader = new StringReader(contentsCheckInertial)) { do { string line = reader.ReadLine(); if (line == null) { break; } string [] values = line.Split(new char[] { ',' }); foreach (string str in values) { if (str == null || str == "" || str == " ") { break; } //Log.Write ("(" + str + ":"); int num = Convert.ToInt32(str); //Log.Write (num.ToString() + ")"); sum += num; count++; } } while(true); if (sum == 0 || count == 0) { LogB.Warning("inertial check == 0, no data"); } else { double average = sum * 1.0 / count * 1.0; LogB.Information("inertial check == " + average.ToString()); if ( (average < 0 && inertialCheckPositive) || (average > 0 && !inertialCheckPositive)) { reverseSign = true; } } } } string [] startAndDuration = encoderFindPos(contents, start, duration); contents = contents.Substring( Convert.ToInt32(startAndDuration[0]), Convert.ToInt32(startAndDuration[1]) - 1); //-1 is for not ending file with a comma //don't know why but some curves are stored with a "," as last character //this curves also are in the form: "1, 2, 3, 4," instead of "1,2,3,4" //this produces an NA in reading of curves on graph.R //in the meantime this NA in reading in graph.R has been deleted //dataTempFile = dataTempFile[!is.na(dataTempFile)] string fileCurve = uniqueID.ToString() + "-" + personName + "-" + (++curveIDMax).ToString() + "-" + timeStamp + ".txt"; string fileCurveFull = GetEncoderSessionDataCurveDir(sessionID) + Path.DirectorySeparatorChar + fileCurve; if (reverseSign) { LogB.Information("reversingSign"); string contentsReversed = ""; string sep = ""; using (StringReader reader = new StringReader(contents)) { do { string line = reader.ReadLine(); if (line == null) { break; } string [] values = line.Split(new char[] { ',' }); foreach (string str in values) { if (str == null || str == "" || str == " ") { break; } //Log.Write ("(" + str + ":"); int num = Convert.ToInt32(str) * -1; //Log.Write (num.ToString() + ")"); contentsReversed += sep + num.ToString(); sep = ", "; } } while(true); } contents = contentsReversed; } try { TextWriter writer = File.CreateText(fileCurveFull); writer.Write(contents); writer.Flush(); writer.Close(); ((IDisposable)writer).Dispose(); } catch { LogB.Error("Problems on EncoderSaveCurve with file: " + fileCurveFull); return(""); } return(fileCurve); }
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())); */ LogSync.Initialize(); //1.4.10 Log.Start(); LogB.Debugging = true; //now LogB.Debug will be shown. Also there will be thread info on Warning, Error, Information if (args.Length > 0 && args[0] == "printAll") { LogB.PrintAllThreads = true; } var envPath = Environment.GetEnvironmentVariable("PATH"); var rBinPath = ""; baseDirectory = Util.GetPrefixDir(); /* * location of gtkrc file * DISABLED tight now because on windows there are inestabilities on jumps results * and on Mode menu */ //Rc.AddDefaultFile (Util.GetThemeFile()); //LogB.Information("gtk theme:" + Util.GetThemeFile()); 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) { LogB.Error("Could not found the specified path to the directory containing R.dll: ", rPath); throw new DirectoryNotFoundException(string.Format("Could not found the specified path to the directory containing R.dll: {0}", 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 currentDBVersion = SqlitePreferences.Select("databaseVersion", false); double currentDBVersionDouble = Convert.ToDouble(Util.ChangeDecimalSeparator(currentDBVersion)); if (currentDBVersionDouble < Convert.ToDouble(Util.ChangeDecimalSeparator("1.25"))) { language = ""; } else { language = SqlitePreferences.Select("language", false); } Sqlite.DisConnect(); if (language != "") { //convert pt-BR to pt_BR if (language.Contains("-")) { language = language.Replace("-", "_"); } 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); }
public void calculate() { int numMeasures = measures.Count; if (numMeasures < 3) { LogB.Error(string.Format("LeastSquares needs at least three values, has:", numMeasures)); Success = false; return; } double [] B = new double[3]; for (int i = 0; i < numMeasures; i++) { B[0] = B[0] + measures[i].Y; B[1] = B[1] + measures[i].X * measures[i].Y; B[2] = B[2] + measures[i].X * measures[i].X * measures[i].Y; } LogB.Information(string.Format("B = {0} {1} {2}", B[0], B[1], B[2])); double sumX = 0; //sumatory of the X values double sumX2 = 0; //sumatory of the squared X values double sumX3 = 0; //sumatory of the cubic X values double sumX4 = 0; //sumatory of the forth power of X values for (int i = 0; i < numMeasures; i++) { sumX = sumX + measures[i].X; sumX2 = sumX2 + Math.Pow(measures[i].X, 2); sumX3 = sumX3 + Math.Pow(measures[i].X, 3); sumX4 = sumX4 + Math.Pow(measures[i].X, 4); } double detA = numMeasures * sumX2 * sumX4 + 2 * sumX * sumX2 * sumX3 - sumX2 * sumX2 * sumX2 - sumX * sumX * sumX4 - numMeasures * sumX3 * sumX3; if (detA != 0) { double [,] invA = new double[3, 3]; invA[0, 0] = (sumX2 * sumX4 - sumX3 * sumX3) / detA; invA[0, 1] = (-sumX * sumX4 + sumX2 * sumX3) / detA; invA[0, 2] = (sumX * sumX3 - sumX2 * sumX2) / detA; invA[1, 1] = (numMeasures * sumX4 - sumX2 * sumX2) / detA; invA[1, 2] = (-numMeasures * sumX3 + sumX * sumX2) / detA; invA[2, 2] = (numMeasures * sumX2 - sumX * sumX) / detA; //Simetric matrix invA[1, 0] = invA[0, 1]; invA[2, 0] = invA[0, 2]; invA[2, 1] = invA[1, 2]; //coef = invA * B double [] coef = new double[3]; coef[0] = invA[0, 0] * B[0] + invA[0, 1] * B[1] + invA[0, 2] * B[2]; coef[1] = invA[1, 0] * B[0] + invA[1, 1] * B[1] + invA[1, 2] * B[2]; coef[2] = invA[2, 0] * B[0] + invA[2, 1] * B[1] + invA[2, 2] * B[2]; Success = true; Coef = coef; } else { LogB.Error("Determinant of matrix equal to zero"); Success = false; } }
//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); } }
private bool changeMultitestFirmwareDo(int debounceChange) { LogB.Information("ChangeMultitestFirmwareDo"); try { ChronopicAuto ca = new ChronopicAutoChangeDebounce(); //write change if (cpDoing == 1) { ca.Write(sp, debounceChange); } else { ca.Write(sp2, debounceChange); } string ms = ""; bool success = false; int tryNum = 10; //try to connect ten times do { //read if ok ca = new ChronopicAutoCheckDebounce(); if (cpDoing == 1) { ms = ca.Read(sp); //ms wil be eg. "50 ms" } else { ms = ca.Read(sp2); //ms wil be eg. "50 ms" } LogB.Information("ChronopicAutoCheckDebounce: " + ms); if (ms.Length == 0) { LogB.Error("multitest firmware. ms is null"); } else if (ms[0] == '-') //is negative { LogB.Error("multitest firmware. ms = " + ms); } else if (debounceChange.ToString() + " ms" == ms) { success = true; } tryNum--; } while (!success && tryNum > 0); LogB.Information("multitest firmware CHANGED to ms = " + ms); if (success) { return(true); } } catch { LogB.Error("Could not change debounce"); } return(false); }