runEncoder.cs 16.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
/*
 * This file is part of ChronoJump
 *
 * ChronoJump is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or   
 *    (at your option) any later version.
 *    
 * ChronoJump is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 *    GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Copyright (C) 2018   Xavier de Blas <xaviblas@gmail.com>
 */

using System;
using System.IO;
using System.IO.Ports;
using System.Threading;
using Gtk;
using Gdk;
using Glade;
using System.Text; //StringBuilder
using System.Collections.Generic; //List<T>
using Mono.Unix;


public partial class ChronoJumpWindow 
{
35 36 37 38 39 40
	[Widget] Gtk.SpinButton race_analyzer_spinbutton_distance;
	[Widget] Gtk.SpinButton race_analyzer_spinbutton_temperature;

	int race_analyzer_distance;
	int race_analyzer_temperature;

41 42 43 44 45 46 47 48 49 50
	Thread runEncoderCaptureThread;
	static bool runEncoderProcessFinish;
	static bool runEncoderProcessCancel;
	static bool runEncoderProcessError;
	
	static string lastRunEncoderFile = "";
	static string lastRunEncoderFullPath = "";

	//int usbDisconnectedCount;
	//int usbDisconnectedLastTime;
51
	static arduinoCaptureStatus capturingRunEncoder = arduinoCaptureStatus.STOP;
52 53 54 55 56 57 58
	/*
	static bool redoingPoints; //don't draw while redoing points (adjusting screen)

	static bool forceCaptureStartMark; 	//Just needed to display "Capturing message"
	static ForceSensorValues forceSensorValues;

	*/
59
	static string captureEndedMessage;
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
	string runEncoderPortName;
	SerialPort portRE; //Attention!! Don't reopen port because arduino makes reset
	bool portREOpened;

	string runEncoderNotConnectedString =
		//Catalog.GetString("Run encoder sensor is not detected!") + " " +
		"Run encoder sensor is not detected!" + " " +
		Catalog.GetString("Plug cable and click on 'device' button.");


	//this can use GTK (forceSensor not because it's managed by non-gtk thread)
	private bool runEncoderConnect()
	{
		LogB.Information(" RE connect 0 ");
		if(chronopicRegister.ConnectedOfType(ChronopicRegisterPort.Types.ARDUINO_RUN_ENCODER) == null)
		{
			event_execute_label_message.Text = runEncoderNotConnectedString;
			return false;
		}

		LogB.Information(" RE connect 1 ");
		runEncoderPortName = chronopicRegister.ConnectedOfType(ChronopicRegisterPort.Types.ARDUINO_RUN_ENCODER).Port;
		LogB.Information(" RE connect 2 ");
		if(runEncoderPortName == null || runEncoderPortName == "")
		{
			event_execute_label_message.Text = "Please, select port!";
			return false;
		}
		LogB.Information(" RE connect 3 ");
		event_execute_label_message.Text = "Connecting ...";

		portRE = new SerialPort(runEncoderPortName, 115200); //runEncoder
		LogB.Information(" RE connect 4: opening port...");

		try {
			portRE.Open();
		}
		catch (System.IO.IOException)
		{
			event_execute_label_message.Text = runEncoderNotConnectedString;
			return false;
		}

		LogB.Information(" RE connect 5: let arduino start");

		Thread.Sleep(3000); //sleep to let arduino start reading serial event

		LogB.Information(" RE connect 6: get version");

		string version = runEncoderCheckVersionDo();
		LogB.Information("Version found: [" + version + "]");

		portREOpened = true;
		event_execute_label_message.Text = "Connected!";
		LogB.Information(" RE connect 7: connected and adjusted!");
		return true;
	}
	private void runEncoderDisconnect()
	{
		portRE.Close();
		portREOpened = false;
		event_execute_label_message.Text = "Disconnected!";
	}

Xavier de Blas's avatar
Xavier de Blas committed
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
	private string runEncoderCheckVersionDo()
	{
		if(! runEncoderSendCommand("get_version:", "Checking version ...", "Catched checking version"))
			return "";

		string str = "";
		do {
			Thread.Sleep(100); //sleep to let arduino start reading
			try {
				str = portRE.ReadLine().Trim();
			} catch {
				//forceSensorOtherMessage = "Disconnected";
				LogB.Information("catched! checking version");
				return "";
			}
			LogB.Information("init string: " + str);
		}
		while(! str.Contains("Race_Analyzer-"));

		//forceSensorOtherMessageShowSeconds = false;
		//forceSensorOtherMessage = str;

		//return the version without "Race_Analyzer-"
		return(str.Remove(0,14));
	}


151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
	//Attention: no GTK here!!
	private bool runEncoderSendCommand(string command, string displayMessage, string errorMessage)
	{
		//forceSensorOtherMessage = displayMessage;

		try {
			LogB.Information("Run Encoder command |" + command + "|");
			portRE.WriteLine(command);
		}
		catch (Exception ex)
		{
			if(ex is System.IO.IOException || ex is System.TimeoutException)
			{
				LogB.Information(errorMessage);
				portREOpened = false;
				return false;
			}
			//throw;
		}

		return true;
	}

	private void on_runs_encoder_capture_clicked ()
	{
176 177 178 179 180 181 182 183 184 185 186 187 188 189
		if(currentPersonSession.Weight == 0)
		{
			new DialogMessage(Constants.MessageTypes.WARNING,
					Catalog.GetString("Error, weight of the person cannot be 0"));
			return;
		}

		if(currentPersonSession.Height == 0)
		{
			new DialogMessage(Constants.MessageTypes.WARNING,
					Catalog.GetString("Error, height of the person cannot be 0"));
			return;
		}

190 191 192
		race_analyzer_distance = Convert.ToInt32(race_analyzer_spinbutton_distance.Value);
		race_analyzer_temperature = Convert.ToInt32(race_analyzer_spinbutton_temperature.Value);

193 194 195 196 197 198 199 200 201 202 203 204 205
		runEncoderButtonsSensitive(false);
		bool connected = runEncoderCapturePre();
		if(! connected)
			runEncoderButtonsSensitive(true);
	}

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

206 207 208
		if(File.Exists(UtilEncoder.GetSprintEncoderImage()))
			Util.FileDelete(UtilEncoder.GetSprintEncoderImage());

209
		event_execute_label_message.Text = "Please, wait ...";
210
		captureEndedMessage = "";
211
		capturingRunEncoder = arduinoCaptureStatus.STARTING;
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275

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

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

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

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

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

		event_execute_label_message.Text = "Capturing ...";

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

		LogB.ThreadStart();
		runEncoderCaptureThread.Start();
		return true;
	}

	//non GTK on this method
	private void runEncoderCaptureDo()
	{
		LogB.Information("runEncoderCaptureDo 0");
		lastChangedTime = 0;

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

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

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

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

278
		Util.CreateRaceAnalyzerSessionDirIfNeeded (currentSession.UniqueID);
279 280 281 282

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

		//fileName to save the csv
283
		string fileName = Util.GetRaceAnalyzerSessionDir(currentSession.UniqueID) + Path.DirectorySeparatorChar + nameDate + ".csv";
284 285 286 287 288 289

		//lastRunEncoderFile to save the images
		lastRunEncoderFile = nameDate;


		TextWriter writer = File.CreateText(fileName);
290
		writer.WriteLine("Pulses;Time(useconds);Force(N)");
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
		str = "";
		int firstTime = 0;

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

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

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

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

			if(strFull.Length != 3)
				continue;
321 322 323 324 325 326 327 328 329

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

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

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

334 335 336 337 338 339 340 341 342 343 344 345 346 347
			/*
			int time = Convert.ToInt32(strFull[0]);

			//measurement does not start at 0 time. When we start receiving data, mark this as firstTime
			if(firstTime == 0)
				firstTime = time;

			//use this to have time starting at 0
			time -= firstTime;

			double force = Convert.ToDouble(Util.ChangeDecimalSeparator(strFull[1]));
			*/
			int pulse = Convert.ToInt32(strFull[0]);
			int time = Convert.ToInt32(strFull[1]);
348 349
			int force = Convert.ToInt32(strFull[2]);
			writer.WriteLine(pulse.ToString() + ";" + time.ToString() + ";" + force.ToString());
350 351 352 353 354 355 356
		}
		LogB.Information(string.Format("FINISHED WITH conditions: {0}-{1}-{2}",
						runEncoderProcessFinish, runEncoderProcessCancel, runEncoderProcessError));
		LogB.Information("Calling end_capture");
		if(! runEncoderSendCommand("end_capture:", "Ending capture ...", "Catched ending capture"))
		{
			runEncoderProcessError = true;
357
			capturingRunEncoder = arduinoCaptureStatus.STOP;
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
			Util.FileDelete(fileName);
			return;
		}

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

		writer.Flush();
		writer.Close();
		((IDisposable)writer).Dispose();
378
		capturingRunEncoder = arduinoCaptureStatus.STOP;
379 380 381 382 383 384

		//port.Close();

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

389 390
		race_analyzer_distance = Convert.ToInt32(race_analyzer_spinbutton_distance.Value);
		race_analyzer_temperature = Convert.ToInt32(race_analyzer_spinbutton_temperature.Value);
391 392
			//create graph
			RunEncoderGraph reg = new RunEncoderGraph(
393
					 race_analyzer_distance,
394 395
					 currentPersonSession.Weight,  	//TODO: can be more if extra weight
					 currentPersonSession.Height,
396
					 race_analyzer_temperature);
397 398
			reg.CallR(1699, 768); 				//TODO: hardcoded

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

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

405
			captureEndedMessage = "Data on raceAnalyzer folder";
406 407 408
			if(File.Exists(UtilEncoder.GetSprintEncoderImage()))
			{
				LogB.Information("File exists on png, trying to copy");
409 410
				try {
					File.Copy(UtilEncoder.GetSprintEncoderImage(),
411
							Util.GetRaceAnalyzerSessionDir(currentSession.UniqueID) + Path.DirectorySeparatorChar +
412 413 414
							lastRunEncoderFile + 	//nameDate
							".png",
							true); //can be overwritten
415
					captureEndedMessage += " (png too)";
416 417
				} catch {
					LogB.Information("Couldn't copy the file");
418
					captureEndedMessage += " (Created png but only on tmp folder, could not copy file)";
419
				}
420 421
			} else {
				LogB.Information("File does not exist on png (after 5 seconds)");
422
				captureEndedMessage += " (png not created, problem doing the graph)";
423
			}
424 425

			capturingRunEncoder = arduinoCaptureStatus.COPIED_TO_TMP;
426 427
		}
	}
428

429 430 431 432 433
	private string readFromRunEncoderIfDataArrived()
	{
		string str = "";
		if (portRE.BytesToRead > 0)
			str = portRE.ReadLine();
434
			//LogB.Information("PRE_get_calibrationfactor bytes: " + portRE.ReadExisting());
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455

		return str;
	}

	private bool pulseGTKRunEncoderCapture ()
	{
LogB.Information(" fc A ");
		if(runEncoderCaptureThread == null)
		{
			Thread.Sleep (25);
			return true;
		}

LogB.Information(" fc B ");
		//LogB.Information(capturingRunEncoder.ToString())
		if(! runEncoderCaptureThread.IsAlive || runEncoderProcessFinish || runEncoderProcessCancel || runEncoderProcessError)
		{
LogB.Information(" fc C ");
			if(runEncoderProcessFinish)
			{
LogB.Information(" fc C finish");
456
				if(capturingRunEncoder != arduinoCaptureStatus.COPIED_TO_TMP)
457 458 459 460 461 462
				{
					Thread.Sleep (25); //Wait file is copied
					return true;
				}
				else
				{
463
					event_execute_label_message.Text = "Saved." + captureEndedMessage;
464 465 466 467 468 469 470 471 472 473 474
					Thread.Sleep (250); //Wait a bit to ensure is copied

					/*
					fscPoints.InitRealWidthHeight();
					forceSensorDoSignalGraphPlot();
					forceSensorDoRFDGraph();

					//if drawingarea has still not shown, don't paint graph because GC screen is not defined
					if(force_sensor_ai_drawingareaShown)
						forceSensorDoGraphAI();
					*/
475
				}
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
LogB.Information(" fc C finish 2");
			} else if(runEncoderProcessCancel || runEncoderProcessError)
			{
LogB.Information(" fc C cancel ");
				if(runEncoderProcessCancel)
					event_execute_label_message.Text = "Cancelled.";
				else
					event_execute_label_message.Text = runEncoderNotConnectedString;
LogB.Information(" fc C cancel 2");
			}
			else
				event_execute_label_message.Text = "";

			LogB.ThreadEnding();

			/*
			 * ensure runEncoderCaptureThread is ended:
			 * called: portRE.WriteLine("end_capture:");
			 * and received feedback from device
			 */
			while(runEncoderCaptureThread.IsAlive)
				Thread.Sleep (250);
LogB.Information(" fc D ");

			LogB.ThreadEnded(); 

			runEncoderButtonsSensitive(true);
			/*
			button_force_sensor_image_save_signal.Sensitive = true;
			button_force_sensor_analyze_recalculate.Sensitive = true;
			*/

			//finish, cancel: sensitive = false
			hideButtons();

			restTime.AddOrModify(currentPerson.UniqueID, currentPerson.Name, true);
			updateRestTimes();

			return false;
		}

LogB.Information(" fc E ");
/*
		if(forceCaptureStartMark)
		{
			event_execute_label_message.Text = "Capturing ...";
			forceCaptureStartMark = false;
		}
		*/
LogB.Information(" fc F ");

527
		if(capturingRunEncoder == arduinoCaptureStatus.CAPTURING)
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
		{
LogB.Information(" fc G ");


LogB.Information(" fc H2 ");
/*
			if(usbDisconnectedLastTime == forceSensorValues.TimeLast)
			{
				usbDisconnectedCount ++;
				if(usbDisconnectedCount >= 20)
				{
					event_execute_label_message.Text = "Disconnected!";
					runEncoderProcessError = true;
					return true;
				}
			}
			else
			{
				usbDisconnectedLastTime = forceSensorValues.TimeLast;
				usbDisconnectedCount = 0;
			}
			*/

LogB.Information(" fc I ");

LogB.Information(" fc Q ");
		}
LogB.Information(" fc R ");

		Thread.Sleep (25);
		//LogB.Information(" RunEncoder:"+ runEncoderCaptureThread.ThreadState.ToString());
		return true;
	}

	void runEncoderButtonsSensitive(bool sensitive)
	{
		button_execute_test.Sensitive = sensitive;

		//other gui buttons
		main_menu.Sensitive = sensitive;
		hbox_contacts_sup_capture_analyze_two_buttons.Sensitive = sensitive;
		frame_persons.Sensitive = sensitive;
		hbox_top_person.Sensitive = sensitive;
		hbox_chronopics_and_more.Sensitive = sensitive;
	}

}