private void writeOptionsFile(int graphWidth, int graphHeight) { string scriptsPath = UtilEncoder.GetSprintPath(); if (UtilAll.IsWindows()) { scriptsPath = scriptsPath.Replace("\\", "/"); } System.Globalization.NumberFormatInfo localeInfo = new System.Globalization.NumberFormatInfo(); localeInfo = System.Globalization.NumberFormatInfo.CurrentInfo; string scriptOptions = "#scriptsPath\n" + UtilEncoder.GetScriptsPath() + "\n" + "#filename\n" + UtilEncoder.GetRaceAnalyzerCSVFileName() + "\n" + "#mass\n" + Util.ConvertToPoint(mass) + "\n" + "#personHeight\n" + Util.ConvertToPoint(personHeight / 100.0) + "\n" + //send it in meters "#tempC\n" + tempC + "\n" + "#testLength\n" + testLength.ToString() + "\n" + "#os\n" + UtilEncoder.OperatingSystemForRGraphs() + "\n" + "#graphWidth\n" + graphWidth.ToString() + "\n" + "#graphHeight\n" + graphHeight.ToString(); TextWriter writer = File.CreateText(Path.GetTempPath() + "Roptions.txt"); writer.Write(scriptOptions); writer.Flush(); writer.Close(); ((IDisposable)writer).Dispose(); }
static void printSyntaxAndQuit() { Console.WriteLine(Catalog.GetString("Invalid args. Use:")); if (UtilAll.IsWindows()) { Console.WriteLine("chronojump_mini.bat [PORT=portName>] [FILE=outputFile]"); Console.WriteLine(Catalog.GetString("Examples:")); Console.WriteLine("chronojump_mini.bat"); Console.WriteLine("chronojump_mini.bat PORT=COM1"); Console.WriteLine("chronojump_mini.bat FILE=myFile.csv"); Console.WriteLine("chronojump_mini.bat PORT=COM1 FILE=myFile.csv"); } else { Console.WriteLine("./chronojump_mini.sh [PORT=portName>] [FILE=outputFile]"); Console.WriteLine(Catalog.GetString("Examples:")); Console.WriteLine("./chronojump_mini.sh"); Console.WriteLine("./chronojump_mini.sh PORT=/dev/ttyS0"); Console.WriteLine("./chronojump_mini.sh FILE=myFile.csv"); Console.WriteLine("./chronojump_mini.sh PORT=/dev/ttyUSB0 FILE=myFile.csv"); } Environment.Exit(1); }
public static bool CallR(string script) { string executable = UtilEncoder.RProcessBinURL(); List <string> parameters = new List <string>(); //A) fix script name if (UtilAll.IsWindows()) { script = script.Replace("\\", "/"); } parameters.Insert(0, "\"" + script + "\""); //B) tempPath string tempPath = Path.GetTempPath(); if (UtilAll.IsWindows()) { tempPath = tempPath.Replace("\\", "/"); } parameters.Insert(1, "\"" + tempPath + "\""); LogB.Information("\nCalling R file ----->"); //C) call process //ExecuteProcess.run (executable, parameters); Result execute_result = run(executable, parameters, true, true); //LogB.Information("Result = " + execute_result.stdout); LogB.Information("\n<------ Done calling R file."); return(execute_result.success); }
private void writeOptionsFile(int graphWidth, int graphHeight) { string scriptsPath = UtilEncoder.GetSprintPath(); if (UtilAll.IsWindows()) { scriptsPath = scriptsPath.Replace("\\", "/"); } System.Globalization.NumberFormatInfo localeInfo = new System.Globalization.NumberFormatInfo(); localeInfo = System.Globalization.NumberFormatInfo.CurrentInfo; string scriptOptions = "#os\n" + UtilEncoder.OperatingSystemForRGraphs() + "\n" + "#decimalChar\n" + localeInfo.NumberDecimalSeparator + "\n" + "#graphWidth\n" + graphWidth.ToString() + "\n" + "#graphHeight\n" + graphHeight.ToString() + "\n" + "#averageLength\n" + Util.ConvertToPoint(averageLength) + "\n" + "#percentChange\n" + Util.ConvertToPoint(percentChange) + "\n" + "#vlineT0\n" + Util.BoolToRBool(vlineT0) + "\n" + "#vline50fmax.raw\n" + Util.BoolToRBool(vline50fmax_raw) + "\n" + "#vline50fmax.fitted\n" + Util.BoolToRBool(vline50fmax_fitted) + "\n" + "#hline50fmax.raw\n" + Util.BoolToRBool(hline50fmax_raw) + "\n" + "#hline50fmax.fitted\n" + Util.BoolToRBool(hline50fmax_fitted) + "\n" + "#RFDs"; foreach (ForceSensorRFD rfd in rfdList) { if (rfd.active) { scriptOptions += "\n" + rfd.ToR(); } else { scriptOptions += "\n-1"; } } if (impulse.active) { scriptOptions += "\n" + impulse.ToR(); } else { scriptOptions += "\n-1"; } scriptOptions += "\n#testLength\n" + testLength.ToString() + "\n" + "#title\n" + title + "\n" + "#scriptsPath\n" + UtilEncoder.GetScriptsPath() + "\n"; TextWriter writer = File.CreateText(Path.GetTempPath() + "Roptions.txt"); writer.Write(scriptOptions); writer.Flush(); writer.Close(); ((IDisposable)writer).Dispose(); }
//when select from database, ensure path separators are ok for this platform //useful if person moved database between diff OS private static string fixOSpath(string url) { if (UtilAll.IsWindows()) { return(url.Replace("/", "\\")); } else { return(url.Replace("\\", "/")); } }
/* * DEPRECATED, now use always RDotNet. Until 1.5.0 where RDotNet is not used anymore. Neither this Pyton method. * public static void RunEncoderCapturePython(string title, EncoderStruct es, string port) * { * CancelRScript = false; * * ProcessStartInfo pinfo; * Process p; * //Old comment: * //If output file is not given, R will try to write in the running folder * //in which we may haven't got permissions * * string pBin=""; * pinfo = new ProcessStartInfo(); * * string outputFileCheck = ""; * * * //on Windows (py2exe) we execute a exe with the py file that contains python * //on linux we execute python and call to the py file * //also on windows we need the full path to find R * if (UtilAll.IsWindows()) { * pBin=getEncoderScriptCapturePython(); * pinfo.Arguments = title + " " + es.OutputData1 + " " + es.Ep.ToString1() + " " + port + " " + changeSpaceToSpaceMark( + System.IO.Path.Combine(Util.GetPrefixDir(), "bin" + Path.DirectorySeparatorChar + "R.exe")); + } + else { + pBin="python"; + pinfo.Arguments = getEncoderScriptCapturePython() + " " + title + " " + + es.OutputData1 + " " + es.Ep.ToString1() + " " + port; + } + + outputFileCheck = es.OutputData1; + + pinfo.FileName=pBin; + + pinfo.CreateNoWindow = true; + pinfo.UseShellExecute = false; + + Console.WriteLine(outputFileCheck); + if (File.Exists(outputFileCheck)) + File.Delete(outputFileCheck); + + p = new Process(); + p.StartInfo = pinfo; + p.Start(); + Log.WriteLine(p.Id.ToString()); + + p.WaitForExit(); + while ( ! ( File.Exists(outputFileCheck) || CancelRScript) ); + } */ //R plots on Windows using Cairo, need to know if it's windows or not public static string OperatingSystemForRGraphs() { string operatingSystem = "Linux"; if (UtilAll.IsWindows()) { operatingSystem = "Windows"; } return(operatingSystem); }
public ChronopicWindow(Chronopic cpDetected, ArrayList myCpd) { LogB.Debug("constructor"); Glade.XML gxml; gxml = Glade.XML.FromAssembly(Util.GetGladePath() + "chronojump.glade", "chronopic_window", "chronojump"); gxml.Autoconnect(this); cpd = myCpd; if (cpDetected != null) { cp = cpDetected; sp = new SerialPort(((ChronopicPortData)cpd[0]).Port); } UtilGtk.IconWindow(chronopic_window); if (UtilAll.IsWindows()) { isWindows = true; } else { isWindows = false; } setDefaultValues(); chronopicInit = new ChronopicInit(); //Pixbuf pixbuf = new Pixbuf (null, Util.GetImagePath(false) + "chronopic_128.png"); //chronopic_image.Pixbuf = pixbuf; /* * Pixbuf pixbuf; * pixbuf = new Pixbuf (null, Util.GetImagePath(true) + Constants.FileNameContactPlatformModular); * image_contact_modular.Pixbuf = pixbuf; * pixbuf = new Pixbuf (null, Util.GetImagePath(true) + Constants.FileNameInfrared); * image_infrared.Pixbuf = pixbuf; */ /* * if(chronopicPort1 != Constants.ChronopicDefaultPortWindows && * (chronopicPort1 != Constants.ChronopicDefaultPortLinux && File.Exists(chronopicPort1)) * ) { * ConfirmWindow confirmWin = ConfirmWindow.Show(Catalog.GetString("Do you want to connect to Chronopic now?"), "", ""); * confirmWin.Button_accept.Clicked += new EventHandler(chronopicAtStart); * } */ }
private void on_button_info_clicked(object o, EventArgs args) { string str = Constants.FindDriverNeed; if (UtilAll.IsWindows()) { str += "\n\n" + Constants.FindDriverWindows; } else { str += "\n\n" + Constants.FindDriverOthers; } new DialogMessage(Constants.MessageTypes.INFO, str); }
protected string pBinURL() { string pBin = "Rscript"; if (UtilAll.IsWindows()) { //on Windows we need the \"str\" to call without problems in path with spaces pBin = "\"" + System.IO.Path.Combine(Util.GetPrefixDir(), "bin" + Path.DirectorySeparatorChar + "Rscript.exe") + "\""; } else if (UtilAll.GetOSEnum() == UtilAll.OperatingSystems.MACOSX) { pBin = Constants.RScriptOSX; } LogB.Information("pBin:", pBin); return(pBin); }
private static Result executeChronojumpImporter(List <string> parameters) { string importer_executable; if (UtilAll.IsWindows()) { // On Windows we execute the .exe file (it's the Python with py2exe) importer_executable = System.IO.Path.Combine(Util.GetPrefixDir(), "bin\\chronojump-importer\\chronojump_importer.exe"); } else { // On Linux and OSX we execute Python and we pass the path to the script as a first argument importer_executable = "python"; // chronojump_importer.py works on Python 2 and Python 3 string importer_script_path = System.IO.Path.Combine(Util.GetPrefixDir(), "bin/chronojump_importer.py"); // first argument of the Python: the path to the script parameters.Insert(0, importer_script_path); } ExecuteProcess.Result execute_result = ExecuteProcess.run(importer_executable, parameters, true, true); if (execute_result.exitCode != 0) { // Python interpretar was executed but the Python file wasn't found or the script failed string errorMessage = ""; if (execute_result.errorMessage == "") { // The Python script has been executed and failed (syntax error, crashed). // The error message will be in the output: errorMessage = execute_result.allOutput; errorMessage += "\nArguments: " + String.Join(" ", parameters); } else { // The Python script has not been executed, return the error message from ExecuteProcess errorMessage = execute_result.errorMessage; } return(new Result(false, execute_result.allOutput, errorMessage)); } // All good, returns the output return(new Result(true, execute_result.allOutput)); }
private string addHtmlIfNeeded(string myFile) { int posOfDot = myFile.LastIndexOf('.'); if (posOfDot == -1) { if (UtilAll.IsWindows()) { myFile += ".htm"; } else { myFile += ".html"; } } return(myFile); }
private bool chronojumpIsExecutingNTimes() { try { StreamReader reader = File.OpenText(runningFileName); string pid = reader.ReadToEnd(); reader.Close(); //delete the '\n' that ReaderToEnd() has put pid = pid.TrimEnd(new char[1] { '\n' }); if (UtilAll.IsWindows()) { return(chronojumpIsExecutingNTimesComparePids("Chronojump", pid)); } else { //in linux process was names mono, but now is named mono-sgen bool found = chronojumpIsExecutingNTimesComparePids("mono", pid); if (found) { return(true); } else { return(chronojumpIsExecutingNTimesComparePids("mono-sgen", pid)); } } } catch { /* * if we a chronojump older that 0.8.9.8 has crashed, and now we install 0.8.9.8 * it will try to read the pid * but there will be no pid because old chronojumps have nothing written on that file * A -not perfect- solution is if there are problems here, return false: (is not executing n times) */ return(false); } }
/* * The process.Responding only works on GUI processes * So, here we send a "ping" expecting to see the result in short time * * TODO: maybe is good to kill the unresponsive processes */ public static bool IsResponsive(Process p) { Random rnd = new Random(); int randomInt = rnd.Next(); //eg. 1234 string randomPingStr = "PING" + Path.Combine(Path.GetTempPath(), "chronojump" + randomInt.ToString() + ".txt"); //eg Linux: 'PING/tmp/chronojump1234.txt' //eg Windows: 'PINGC:\Temp...\chronojump1234.txt' if (UtilAll.IsWindows()) { //On win32 R understands backlash as an escape character and //a file path uses Unix-like path separator '/' randomPingStr = randomPingStr.Replace("\\", "/"); } //eg Windows: 'PINGC:/Temp.../chronojump1234.txt' LogB.Information("Sending ping: " + randomPingStr); try { p.StandardInput.WriteLine(randomPingStr); } catch { LogB.Warning("Catched waiting response"); return(false); } //wait 250ms the response System.Threading.Thread.Sleep(250); //On Linux will be '/' on Windows '\' if (File.Exists(Path.Combine(Path.GetTempPath(), "chronojump" + randomInt.ToString() + ".txt"))) { LogB.Information("Process is responding"); return(true); } LogB.Warning("Process is NOT responding"); return(false); }
private void writeOptionsFile(int graphWidth, int graphHeight, string personName) { /* * string scriptOptions = * "#positions\n" + "0;20;40;70" + "\n" + * "#splitTimes\n" + "0;2.73;4.49;6.95" + "\n" + * "#mass\n" + "75" + "\n" + * "#personHeight\n" + "1.65" + "\n" + * "#tempC\n" + "25" + "\n"; */ string scriptsPath = UtilEncoder.GetSprintPath(); if (UtilAll.IsWindows()) { scriptsPath = scriptsPath.Replace("\\", "/"); } string scriptOptions = "#scriptsPath\n" + scriptsPath + "\n" + "#positions\n" + positions + "\n" + "#splitTimes\n" + splitTimes + "\n" + "#mass\n" + Util.ConvertToPoint(mass) + "\n" + "#personHeight\n" + Util.ConvertToPoint(personHeight / 100.0) + "\n" + //send it in meters "#tempC\n" + tempC + "\n" + "#os\n" + UtilEncoder.OperatingSystemForRGraphs() + "\n" + "#graphWidth\n" + graphWidth.ToString() + "\n" + "#graphHeight\n" + graphHeight.ToString() + "\n" + "#personName\n" + personName + "\n"; TextWriter writer = File.CreateText(Path.GetTempPath() + "Roptions.txt"); writer.Write(scriptOptions); writer.Flush(); writer.Close(); ((IDisposable)writer).Dispose(); }
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 override bool startProcess() { CurvesReaded = 0; //If output file is not given, R will try to write in the running folder //in which we may haven't got permissions pinfo = new ProcessStartInfo(); string pBin = pBinURL(); if (UtilAll.IsWindows()) { //On win32 R understands backlash as an escape character and //a file path uses Unix-like path separator '/' optionsFile = optionsFile.Replace("\\", "/"); } //on Windows we need the \"str\" to call without problems in path with spaces pinfo.Arguments = "\"" + getEncoderScriptCallGraph() + "\" " + optionsFile; LogB.Information("Arguments:", pinfo.Arguments); LogB.Information("--- 1 --- " + optionsFile.ToString() + " ---"); //LogB.Information("--- 2 --- " + scriptOptions + " ---"); LogB.Information("--- 3 --- " + pinfo.Arguments.ToString() + " ---"); string outputFileCheck = ""; string outputFileCheck2 = ""; //Wait until this to update encoder gui (if don't wait then treeview will be outdated) //exportCSV is the only one that doesn't have graph. all the rest Analysis have graph and data if (es.Ep.Analysis == "exportCSV") { outputFileCheck = es.OutputData1; } else { //outputFileCheck = es.OutputGraph; // //OutputData1 because since Chronojump 1.3.6, //encoder analyze has a treeview that can show the curves //when a graph analysis is done, curves file has to be written outputFileCheck = es.OutputData1; //check also the otuput graph outputFileCheck2 = es.OutputGraph; } LogB.Information("outputFileChecks"); LogB.Information(outputFileCheck); LogB.Information(outputFileCheck2); pinfo.FileName = pBin; pinfo.CreateNoWindow = true; pinfo.UseShellExecute = false; pinfo.RedirectStandardInput = true; pinfo.RedirectStandardError = true; /* * if redirect this there are problems because the buffers get saturated * pinfo.RedirectStandardOutput = true; * if is not redirected, then prints are shown by console (but not in logB * best solution is make the prints as write("message", stderr()) * and then will be shown in logB by readError */ //delete output file check(s) deleteFile(outputFileCheck); if (outputFileCheck2 != "") { deleteFile(outputFileCheck2); } //delete status-6 mark used on export csv if (es.Ep.Analysis == "exportCSV") { Util.FileDelete(UtilEncoder.GetEncoderStatusTempBaseFileName() + "6.txt"); } //delete SpecialData if exists string specialData = UtilEncoder.GetEncoderSpecialDataTempFileName(); if (File.Exists(specialData)) { File.Delete(specialData); } try { p = new Process(); p.StartInfo = pinfo; //do not redirect ouptut. Read above //p.OutputDataReceived += new DataReceivedEventHandler(readingOutput); p.ErrorDataReceived += new DataReceivedEventHandler(readingError); p.Start(); //don't do this ReadToEnd because then this method never ends //LogB.Information(p.StandardOutput.ReadToEnd()); //LogB.Warning(p.StandardError.ReadToEnd()); // Start asynchronous read of the output. // Caution: This has to be called after Start //p.BeginOutputReadLine(); p.BeginErrorReadLine(); if (outputFileCheck2 == "") { while (!(Util.FileReadable(outputFileCheck) || CancelRScript)) { ; } } else { while (!((Util.FileReadable(outputFileCheck) && Util.FileReadable(outputFileCheck2)) || CancelRScript)) { ; } } //copy export from temp file to the file that user has selected if (es.Ep.Analysis == "exportCSV" && !CancelRScript) { copyExportedFile(); } } catch { LogB.Warning("catched at startProcess"); return(false); } return(true); }
public HelpPorts() { Glade.XML gladeXML; gladeXML = Glade.XML.FromAssembly(Util.GetGladePath() + "chronojump.glade", "dialog_help_ports", "chronojump"); gladeXML.Autoconnect(this); //put an icon to window UtilGtk.IconWindow(dialog_help_ports); string messageInfo; string messageDetected = ""; if (UtilAll.IsWindows()) { messageInfo = Constants.PortNamesWindows; /* * autodetection disabled on Linux and windows because mono doesn't allow it * string jumpLine = ""; * foreach (string s in SerialPort.GetPortNames()) { * messageDetected += jumpLine + s; * jumpLine = "\n"; * } */ messageDetected = string.Format(Catalog.GetString("Auto-Detection currently disabled")); } else { messageInfo = Constants.PortNamesLinux; messageDetected = UtilAll.DetectPortsLinux(true); //formatting button_check_port.Hide(); button_force_port.Hide(); } label_info.Text = messageInfo; label_info.UseMarkup = true; label_detected.Text = messageDetected; label_detected.UseMarkup = true; if (UtilAll.IsWindows()) { label_help_info.Text = Constants.FindDriverWindows + "\n\n" + Catalog.GetString("Ports above COM4 may not work.") + "\n" + Catalog.GetString("If you want a safer port, press:") + "\n" + Catalog.GetString("Force Chronopic to port <b>COM1 - COM4</b>'."); } else { label_help_info.Text = Constants.FindDriverOthers; } label_help_info.UseMarkup = true; label_help_manual.Text = Catalog.GetString("More information on <b>Chronojump Manual</b>") + "\n" + "<i>" + Path.GetFullPath(Util.GetManualDir()) + "</i>\n\n" + Catalog.GetString("Newer versions will be on this site:") + "\n" + "<i>http://chronojump.org/documents.html</i>"; label_help_manual.UseMarkup = true; }
/* * DEPRECATED, now use always RDotNet. Until 1.5.0 where RDotNet is not used anymore. Neither this Pyton method. * public static void RunEncoderCapturePython(string title, EncoderStruct es, string port) * { * CancelRScript = false; * * ProcessStartInfo pinfo; * Process p; * //Old comment: * //If output file is not given, R will try to write in the running folder * //in which we may haven't got permissions * * string pBin=""; * pinfo = new ProcessStartInfo(); * * string outputFileCheck = ""; * * * //on Windows (py2exe) we execute a exe with the py file that contains python * //on linux we execute python and call to the py file * //also on windows we need the full path to find R * if (UtilAll.IsWindows()) { * pBin=getEncoderScriptCapturePython(); * pinfo.Arguments = title + " " + es.OutputData1 + " " + es.Ep.ToString1() + " " + port + " " + changeSpaceToSpaceMark( + System.IO.Path.Combine(Util.GetPrefixDir(), "bin" + Path.DirectorySeparatorChar + "R.exe")); + } + else { + pBin="python"; + pinfo.Arguments = getEncoderScriptCapturePython() + " " + title + " " + + es.OutputData1 + " " + es.Ep.ToString1() + " " + port; + } + + outputFileCheck = es.OutputData1; + + pinfo.FileName=pBin; + + pinfo.CreateNoWindow = true; + pinfo.UseShellExecute = false; + + Console.WriteLine(outputFileCheck); + if (File.Exists(outputFileCheck)) + File.Delete(outputFileCheck); + + p = new Process(); + p.StartInfo = pinfo; + p.Start(); + Log.WriteLine(p.Id.ToString()); + + p.WaitForExit(); + while ( ! ( File.Exists(outputFileCheck) || CancelRScript) ); + } */ public static EncoderGraphROptions PrepareEncoderGraphOptions(string title, EncoderStruct es, bool neuromuscularProfileDo, bool translate, bool debug, bool crossValidate) { string operatingSystem = "Linux"; title = Util.RemoveBackSlash(title); title = Util.RemoveChar(title, '\''); if (UtilAll.IsWindows()) { //convert accents to Unicode in order to be plotted correctly on R windows title = Util.ConvertToUnicode(title); //On win32 R understands backlash as an escape character and //a file path uses Unix-like path separator '/' es.InputData = es.InputData.Replace("\\", "/"); es.OutputGraph = es.OutputGraph.Replace("\\", "/"); es.OutputData1 = es.OutputData1.Replace("\\", "/"); //es.OutputData2 = es.OutputData2.Replace("\\","/"); //es.SpecialData = es.SpecialData.Replace("\\","/"); es.EncoderTempPath = es.EncoderTempPath.Replace("\\", "/"); operatingSystem = "Windows"; } //if translators add ";", it will be converted to ',' //if translators add a "\n", it will be converted to " " int count = 0; string temp = ""; string [] encoderTranslatedWordsOK = new String [Constants.EncoderTranslatedWords.Length]; //if ! translate, then just print the english words if (translate) { foreach (string etw in Constants.EncoderTranslatedWords) { temp = Util.ChangeChars(Catalog.GetString(etw), ";", ","); temp = Util.RemoveChar(temp, '\''); temp = Util.RemoveNewLine(temp, true); temp = Util.RemoveChar(temp, '#'); //needed to distinguish comments '#' than normal lines like the EncoderTranslatedWords if (UtilAll.IsWindows()) { LogB.Debug(" (1) Unicoding:", temp); temp = Util.ConvertToUnicode(temp); LogB.Debug(" (2) Unicoded:", temp); } encoderTranslatedWordsOK[count++] = temp; } } else { encoderTranslatedWordsOK = Constants.EncoderEnglishWords; } return(new EncoderGraphROptions( es.InputData, es.OutputGraph, es.OutputData1, //es.OutputData2, es.SpecialData, es.EncoderRPath, es.EncoderTempPath, es.Ep, title, operatingSystem, Util.StringArrayToString(Constants.EncoderEnglishWords, ";"), Util.StringArrayToString(encoderTranslatedWordsOK, ";"), debug, crossValidate )); }
protected void checkFile(string formatFile) { string exportString = ""; if (formatFile == "report") { exportString = Catalog.GetString("Save report as..."); } else { exportString = Catalog.GetString("Export session in format " + formatFile); } Gtk.FileChooserDialog fc = new Gtk.FileChooserDialog(exportString, app1, FileChooserAction.Save, Catalog.GetString("Cancel"), ResponseType.Cancel, Catalog.GetString("Export"), ResponseType.Accept ); //set default name string nameString = mySession.Name + "_" + mySession.DateShortAsSQL; if (formatFile == "report") { if (UtilAll.IsWindows()) { nameString += ".htm"; } else { nameString += ".html"; } } else { nameString += ".csv"; } fc.CurrentName = nameString; if (fc.Run() == (int)ResponseType.Accept) { fileName = fc.Filename; if (formatFile == "report") { //add ".html" if needed, remember that on windows should be .htm fileName = addHtmlIfNeeded(fileName); } else { //add ".csv" if needed fileName = Util.AddCsvIfNeeded(fileName); } try { if (File.Exists(fileName)) { LogB.Warning(string.Format("File {0} exists with attributes {1}, created at {2}", fileName, File.GetAttributes(fileName), File.GetCreationTime(fileName))); LogB.Information("Overwrite..."); ConfirmWindow confirmWin = ConfirmWindow.Show(Catalog.GetString("Are you sure you want to overwrite file: "), "", fileName); confirmWin.Button_accept.Clicked += new EventHandler(on_overwrite_file_accepted); } else { writer = File.CreateText(fileName); getData(); printData(); closeWriter(); string myString = string.Format(Catalog.GetString("Saved to {0}"), fileName) + spreadsheetString; new DialogMessage(Constants.MessageTypes.INFO, myString); } } catch { string myString = string.Format(Catalog.GetString("Cannot export to file {0} "), fileName); new DialogMessage(Constants.MessageTypes.WARNING, myString); } } else { LogB.Information("cancelled"); //report does not currently send the appBar reference if (formatFile != "report") { new DialogMessage(Constants.MessageTypes.INFO, Catalog.GetString("Cancelled.")); } fc.Hide(); return; } //Don't forget to call Destroy() or the FileChooserDialog window won't get closed. fc.Destroy(); return; }
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); }
protected internal static void initializeTable(string databaseVersion, bool creatingBlankDatabase) { using (SqliteTransaction tr = dbcon.BeginTransaction()) { using (SqliteCommand dbcmdTr = dbcon.CreateCommand()) { dbcmdTr.Transaction = tr; Insert("databaseVersion", databaseVersion, dbcmdTr); if (UtilAll.IsWindows() || creatingBlankDatabase) { Insert("chronopicPort", Constants.ChronopicDefaultPortWindows, dbcmdTr); } else { Insert("chronopicPort", Constants.ChronopicDefaultPortLinux, dbcmdTr); } //appearance Insert("maximized", Preferences.MaximizedTypes.NO.ToString(), dbcmdTr); Insert("personWinHide", "False", dbcmdTr); Insert("personPhoto", "True", dbcmdTr); Insert("encoderCaptureShowOnlyBars", "False", dbcmdTr); Insert("encoderCaptureShowNRepetitions", "-1", dbcmdTr); Insert("digitsNumber", "3", dbcmdTr); Insert("showPower", "True", dbcmdTr); Insert("showStiffness", "True", dbcmdTr); Insert("showInitialSpeed", "True", dbcmdTr); Insert("showAngle", "False", dbcmdTr); //for treeviewjumps Insert("showQIndex", "False", dbcmdTr); //for treeviewJumps Insert("showDjIndex", "False", dbcmdTr); //for treeviewJumps Insert("simulated", "True", dbcmdTr); Insert("weightStatsPercent", "False", dbcmdTr); Insert("askDeletion", "True", dbcmdTr); Insert("heightPreferred", "False", dbcmdTr); Insert("metersSecondsPreferred", "True", dbcmdTr); Insert("language", "", dbcmdTr); Insert("crashLogLanguage", "", dbcmdTr); Insert("allowFinishRjAfterTime", "True", dbcmdTr); Insert("volumeOn", "True", dbcmdTr); Insert(Preferences.GstreamerStr, Preferences.GstreamerTypes.GST_0_1.ToString(), dbcmdTr); Insert("videoOn", "True", dbcmdTr); Insert("evaluatorServerID", "-1", dbcmdTr); Insert("versionAvailable", "", dbcmdTr); Insert("runSpeedStartArrival", "True", dbcmdTr); Insert("runDoubleContactsMode", Constants.DoubleContact.LAST.ToString(), dbcmdTr); Insert("runDoubleContactsMS", "300", dbcmdTr); Insert("runIDoubleContactsMode", Constants.DoubleContact.AVERAGE.ToString(), dbcmdTr); Insert("runIDoubleContactsMS", "300", dbcmdTr); Insert("thresholdJumps", "50", dbcmdTr); Insert("thresholdRuns", "10", dbcmdTr); Insert("thresholdOther", "50", dbcmdTr); Random rnd = new Random(); string machineID = rnd.Next().ToString(); Insert("machineID", machineID, dbcmdTr); Insert("multimediaStorage", Constants.MultimediaStorage.BYSESSION.ToString(), dbcmdTr); //encoder Insert("encoderCaptureTime", "60", dbcmdTr); Insert("encoderCaptureInactivityEndTime", "3", dbcmdTr); Insert("encoderCaptureMainVariable", Constants.EncoderVariablesCapture.MeanPower.ToString(), dbcmdTr); Insert("encoderCaptureMinHeightGravitatory", "20", dbcmdTr); Insert("encoderCaptureMinHeightInertial", "5", dbcmdTr); Insert("encoderCaptureInertialDiscardFirstN", "3", dbcmdTr); Insert("encoderCaptureCheckFullyExtended", "True", dbcmdTr); Insert("encoderCaptureCheckFullyExtendedValue", "4", dbcmdTr); Insert("encoderCaptureBarplotFontSize", "14", dbcmdTr); Insert("encoderShowStartAndDuration", "False", dbcmdTr); Insert("encoderCaptureCutByTriggers", Preferences.TriggerTypes.NO_TRIGGERS.ToString(), dbcmdTr); Insert("encoderPropulsive", "True", dbcmdTr); Insert("encoderSmoothEccCon", "0.6", dbcmdTr); Insert("encoderSmoothCon", "0.7", dbcmdTr); Insert("encoder1RMMethod", Constants.Encoder1RMMethod.WEIGHTED2.ToString(), dbcmdTr); ArrayList encoderExercises = SqliteEncoder.SelectEncoderExercises(true, -1, true); if (encoderExercises.Count > 0) { EncoderExercise ex = (EncoderExercise)encoderExercises[0]; Insert(EncoderExerciseIDGravitatory, ex.uniqueID.ToString(), dbcmdTr); Insert(EncoderExerciseIDInertial, ex.uniqueID.ToString(), dbcmdTr); } else { Insert(EncoderExerciseIDGravitatory, "1", dbcmdTr); Insert(EncoderExerciseIDInertial, "1", dbcmdTr); } Insert(EncoderContractionGravitatory, Constants.Concentric, dbcmdTr); Insert(EncoderContractionInertial, Constants.EccentricConcentric, dbcmdTr); Insert(EncoderLateralityGravitatory, "RL", dbcmdTr); Insert(EncoderLateralityInertial, "RL", dbcmdTr); Insert(EncoderMassGravitatory, "10", dbcmdTr); Insert(EncoderWeightsInertial, "0", dbcmdTr); //encoderRhythm EncoderRhythm er = new EncoderRhythm(); Insert(EncoderRhythmActiveStr, er.Active.ToString(), dbcmdTr); Insert(EncoderRhythmRepsOrPhasesStr, er.RepsOrPhases.ToString(), dbcmdTr); Insert(EncoderRhythmRepSecondsStr, Util.ConvertToPoint(er.RepSeconds), dbcmdTr); Insert(EncoderRhythmEccSecondsStr, Util.ConvertToPoint(er.EccSeconds), dbcmdTr); Insert(EncoderRhythmConSecondsStr, Util.ConvertToPoint(er.ConSeconds), dbcmdTr); Insert(EncoderRhythmRestRepsSecondsStr, Util.ConvertToPoint(er.RestRepsSeconds), dbcmdTr); Insert(EncoderRhythmRestAfterEccStr, er.RestAfterEcc.ToString(), dbcmdTr); Insert(EncoderRhythmRepsClusterStr, Util.ConvertToPoint(er.RepsCluster), dbcmdTr); Insert(EncoderRhythmRestClustersSecondsStr, Util.ConvertToPoint(er.RestClustersSeconds), dbcmdTr); Insert("videoDevice", "", dbcmdTr); //first Insert("videoDeviceResolution", "", dbcmdTr); Insert("videoDeviceFramerate", "", dbcmdTr); Insert("videoStopAfter", "2", dbcmdTr); Insert("inertialmomentum", "0.01", dbcmdTr); Insert("CSVExportDecimalSeparator", Util.GetDecimalSeparatorFromLocale(), dbcmdTr); Insert("RGraphsTranslate", "True", dbcmdTr); Insert("useHeightsOnJumpIndexes", "True", dbcmdTr); Insert("encoderAutoSaveCurve", Constants.EncoderAutoSaveCurve.BEST.ToString(), dbcmdTr); Insert("email", "", dbcmdTr); Insert("muteLogs", "False", dbcmdTr); Insert(ForceSensorTareDateTimeStr, "", dbcmdTr); Insert(ForceSensorTareStr, "-1", dbcmdTr); //result value from sensor. Decimal is point!! Insert(ForceSensorCalibrationDateTimeStr, "", dbcmdTr); Insert(ForceSensorCalibrationWeightStr, "-1", dbcmdTr); Insert(ForceSensorCalibrationFactorStr, "-1", dbcmdTr); //result value from sensor. Decimal is point!! //removed on 1.37 //Insert ("encoderConfiguration", new EncoderConfiguration().ToStringOutput(EncoderConfiguration.Outputs.SQL), dbcmdTr); } tr.Commit(); } }
protected internal static void initializeTable(string databaseVersion, bool creatingBlankDatabase) { using (SqliteTransaction tr = dbcon.BeginTransaction()) { using (SqliteCommand dbcmdTr = dbcon.CreateCommand()) { dbcmdTr.Transaction = tr; Insert("databaseVersion", databaseVersion, dbcmdTr); if (UtilAll.IsWindows() || creatingBlankDatabase) { Insert("chronopicPort", Constants.ChronopicDefaultPortWindows, dbcmdTr); } else { Insert("chronopicPort", Constants.ChronopicDefaultPortLinux, dbcmdTr); } Insert("digitsNumber", "3", dbcmdTr); Insert("showPower", "True", dbcmdTr); Insert("showStiffness", "True", dbcmdTr); Insert("showInitialSpeed", "True", dbcmdTr); Insert("showAngle", "False", dbcmdTr); //for treeviewjumps Insert("showQIndex", "False", dbcmdTr); //for treeviewJumps Insert("showDjIndex", "False", dbcmdTr); //for treeviewJumps Insert("simulated", "True", dbcmdTr); Insert("weightStatsPercent", "False", dbcmdTr); Insert("askDeletion", "True", dbcmdTr); Insert("heightPreferred", "False", dbcmdTr); Insert("metersSecondsPreferred", "True", dbcmdTr); Insert("language", "", dbcmdTr); Insert("allowFinishRjAfterTime", "True", dbcmdTr); Insert("volumeOn", "True", dbcmdTr); Insert("videoOn", "True", dbcmdTr); Insert("evaluatorServerID", "-1", dbcmdTr); Insert("versionAvailable", "", dbcmdTr); Insert("runSpeedStartArrival", "True", dbcmdTr); Insert("runDoubleContactsMode", Constants.DoubleContact.LAST.ToString(), dbcmdTr); Insert("runDoubleContactsMS", "300", dbcmdTr); Insert("runIDoubleContactsMode", Constants.DoubleContact.AVERAGE.ToString(), dbcmdTr); Insert("runIDoubleContactsMS", "300", dbcmdTr); Insert("thresholdJumps", "50", dbcmdTr); Insert("thresholdRuns", "10", dbcmdTr); Insert("thresholdOther", "50", dbcmdTr); Random rnd = new Random(); string machineID = rnd.Next().ToString(); Insert("machineID", machineID, dbcmdTr); Insert("multimediaStorage", Constants.MultimediaStorage.BYSESSION.ToString(), dbcmdTr); //encoder Insert("encoderCaptureTime", "60", dbcmdTr); Insert("encoderCaptureInactivityEndTime", "3", dbcmdTr); Insert("encoderCaptureMainVariable", Constants.EncoderVariablesCapture.MeanPower.ToString(), dbcmdTr); Insert("encoderCaptureMinHeightGravitatory", "20", dbcmdTr); Insert("encoderCaptureMinHeightInertial", "5", dbcmdTr); Insert("encoderCaptureCheckFullyExtended", "True", dbcmdTr); Insert("encoderCaptureCheckFullyExtendedValue", "4", dbcmdTr); Insert("encoderShowStartAndDuration", "False", dbcmdTr); Insert("encoderPropulsive", "True", dbcmdTr); Insert("encoderSmoothEccCon", "0.6", dbcmdTr); Insert("encoderSmoothCon", "0.7", dbcmdTr); Insert("encoder1RMMethod", Constants.Encoder1RMMethod.WEIGHTED2.ToString(), dbcmdTr); Insert("videoDevice", "0", dbcmdTr); //first Insert("inertialmomentum", "0.01", dbcmdTr); Insert("CSVExportDecimalSeparator", Util.GetDecimalSeparatorFromLocale(), dbcmdTr); Insert("RGraphsTranslate", "True", dbcmdTr); Insert("useHeightsOnJumpIndexes", "True", dbcmdTr); Insert("encoderAutoSaveCurve", Constants.EncoderAutoSaveCurve.BEST.ToString(), dbcmdTr); Insert("email", "", dbcmdTr); //removed on 1.37 //Insert ("encoderConfiguration", new EncoderConfiguration().ToStringOutput(EncoderConfiguration.Outputs.SQL), dbcmdTr); } tr.Commit(); } }
/**********************/ /* PROGRAMA PRINCIPAL */ /**********************/ public static void Main(string[] args) { Chronopic.Plataforma estado_plataforma; Automata estado_automata; double timestamp; double toff; double ton; bool ok; string portName = ""; string fileName = ""; TextWriter writer; //always output to a file, but if not specified, output here and rewrite it every chronojump_mini execution string defaultFileName = Path.Combine(getOutputDir(), "output"); System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("es-ES"); System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("es-ES"); //connect with catalog.cs for using gettext translation Catalog.Init("chronojump", "./locale"); //parameters passing only on linux if (!UtilAll.IsWindows()) { if (args.Length > 2) { printSyntaxAndQuit(); } for (int i = 0; i != args.Length; ++i) { Console.WriteLine("param[{0}]: {1}", i, args[i]); if (args[i].StartsWith("PORT=")) { portName = args[i].Substring(5); } else if (args[i].StartsWith("FILE=")) { fileName = args[i].Substring(5); fileName = getOutputDir() + Path.DirectorySeparatorChar + fileName; } else { printSyntaxAndQuit(); } } } //detection of ports string messageInfo; //string messageDetected =""; if (UtilAll.IsWindows()) { messageInfo = Constants.PortNamesWindows; /* * messageDetected = Catalog.GetString("Detected ports:") + "\n"; * * string jumpLine = ""; * foreach (string s in SerialPort.GetPortNames()) { * messageDetected += jumpLine + s; * jumpLine = "\n"; * } */ } else { messageInfo = Constants.PortNamesLinux; } messageInfo += string.Format("\n" + Catalog.GetString("More information on Chronojump manual")); Console.WriteLine("---------------------------"); Console.WriteLine(messageInfo); Console.WriteLine("---------------------------"); if (portName == "") { if (!UtilAll.IsWindows()) { Console.WriteLine(UtilAll.DetectPortsLinux(false)); //formatting } Console.WriteLine(Catalog.GetString("Print the port name where chronopic is connected:")); portName = Console.ReadLine(); } //output file stuff fileName = manageFileName(fileName); if (fileName == "") { fileName = defaultFileName + "-" + portName.Replace("/", "") + ".csv"; } writer = File.CreateText(fileName); Console.WriteLine(Catalog.GetString("Opening port...") + " " + Catalog.GetString("Please touch the platform or click Chronopic TEST button")); //-- Crear puerto serie SerialPort sp; sp = new SerialPort(portName); //-- Abrir puerto serie. Si ocurre algun error //-- Se lanzara una excepcion try { sp.Open(); } catch (Exception e) { Console.WriteLine(Catalog.GetString("Error opening serial port")); Console.WriteLine(e); Environment.Exit(1); } //-- Crear objeto chronopic, para acceder al chronopic Chronopic cp = new Chronopic(sp); cp.Flush(); //-- Obtener el estado inicial de la plataforma // this do...while is here because currently there's no timeout on chronopic.cs on windows do { ok = cp.Read_platform(out estado_plataforma); } while(!ok); if (!ok) { //-- Si hay error terminar Console.WriteLine(string.Format(Catalog.GetString("Error: {0}"), cp.Error)); System.Environment.Exit(-1); } Console.WriteLine(string.Format(Catalog.GetString("Platform state: {0}"), estado_plataforma)); //Console.WriteLine("Automatic variables: "); //cp.Read_variables_automatic(); //-- Establecer el estado inicial del automata if (estado_plataforma == Chronopic.Plataforma.ON) { estado_automata = Automata.ON; } else { Console.WriteLine(Catalog.GetString("Go up platform for jumping")); //-- Esperar a que llegue una trama con el estado de la plataforma //-- igual a ON. Esto indica que el usuario se ha subido do { ok = cp.Read_event(out timestamp, out estado_plataforma); } while (!ok); //-- Se han subido a la plataforma estado_automata = Automata.ON; } Console.WriteLine(""); Console.WriteLine(Catalog.GetString("Jump when prepared")); Console.WriteLine(Catalog.GetString("Press CTRL-c for ending session")); Console.WriteLine("-----------------------------------------"); double count = 1.0; Console.WriteLine(" TC(ms) TF(ms)"); writer.WriteLine("count;TC(ms);TF(ms)"); while (true) { //-- Esperar a que llegue una trama do { ok = cp.Read_event(out timestamp, out estado_plataforma); } while (ok == false); //-- Segun el estado del automata switch (estado_automata) { case Automata.OFF: //-- Usuario estaba en el aire //-- Si ha aterrizado if (estado_plataforma == Chronopic.Plataforma.ON) { //-- Pasar al estado ON estado_automata = Automata.ON; //-- Registrar tiempo de vuelo toff = timestamp; //-- Imprimir informacion Console.WriteLine("{0:f1}", toff); writer.WriteLine("{0:f1}", toff); } break; case Automata.ON: //-- Usuario estaba en la plataforma //-- Si ahora esta en el aire... if (estado_plataforma == Chronopic.Plataforma.OFF) { //-- Pasar al estado OFF estado_automata = Automata.OFF; //-- Registrar tiempo de contacto ton = timestamp; //-- Imprimir informacion Console.Write(count + " {0:f1} ", ton); writer.Write(count + ";{0:f1};", ton); } break; } writer.Flush(); count += .5; } }
//Inertia Momentum //TODO: make this work with encoderRProc public static void RunEncoderCalculeIM(double weight, double length, EncoderRProcAnalyze encoderRProcAnalyze) { encoderRProcAnalyze.CancelRScript = false; ProcessStartInfo pinfo; Process p; //If output file is not given, R will try to write in the running folder //in which we may haven't got permissions string pBin = ""; pinfo = new ProcessStartInfo(); string inputData = GetEncoderDataTempFileName(); string outputData = GetEncoderSpecialDataTempFileName(); string operatingSystem = "Linux"; string scriptUtilR = GetEncoderScriptUtilR(); pBin = "Rscript"; if (UtilAll.IsWindows()) { //on Windows we need the \"str\" to call without problems in path with spaces pBin = "\"" + System.IO.Path.Combine(Util.GetPrefixDir(), "bin" + Path.DirectorySeparatorChar + "Rscript.exe") + "\""; LogB.Information("pBin:", pBin); //On win32 R understands backlash as an escape character and //a file path uses Unix-like path separator '/' inputData = inputData.Replace("\\", "/"); scriptUtilR = scriptUtilR.Replace("\\", "/"); operatingSystem = "Windows"; } //--- way A. passing options to a file string scriptOptions = inputData + "\n" + outputData + "\n" + Util.ConvertToPoint(weight) + "\n" + Util.ConvertToPoint(length) + "\n" + scriptUtilR + "\n"; string optionsFile = Path.GetTempPath() + "Roptions.txt"; TextWriter writer = File.CreateText(optionsFile); writer.Write(scriptOptions); writer.Flush(); writer.Close(); ((IDisposable)writer).Dispose(); if (UtilAll.IsWindows()) { //On win32 R understands backlash as an escape character and //a file path uses Unix-like path separator '/' optionsFile = optionsFile.Replace("\\", "/"); } //on Windows we need the \"str\" to call without problems in path with spaces pinfo.Arguments = "\"" + getEncoderScriptInertiaMomentum() + "\" " + optionsFile; LogB.Information("Arguments:", pinfo.Arguments); //Wait until this to update encoder gui (if don't wait then treeview will be outdated) string outputFileCheck = outputData; pinfo.FileName = pBin; pinfo.CreateNoWindow = true; pinfo.UseShellExecute = false; pinfo.RedirectStandardError = true; pinfo.RedirectStandardOutput = true; //delete output file check(s) LogB.Information("Deleting... ", outputFileCheck); if (File.Exists(outputFileCheck)) { File.Delete(outputFileCheck); } try { p = new Process(); p.StartInfo = pinfo; p.Start(); LogB.Information(p.StandardOutput.ReadToEnd()); LogB.Warning(p.StandardError.ReadToEnd()); p.WaitForExit(); while (!(File.Exists(outputFileCheck) || encoderRProcAnalyze.CancelRScript)) { ; } } catch { } }