Generally converted only to use non-deprecated ToadicusTools methods.
[VOID.git] /
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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
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
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
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
// VOID
//
// VOID_DataLogger.cs
//
// Copyright © 2014, toadicus
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation and/or other
//    materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used
//    to endorse or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// TODO: Remove ToadicusTools. prefixes after refactor is done.

using KSP;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using ToadicusTools.DebugTools;
using ToadicusTools.GUIUtils;
using ToadicusTools.Text;
using UnityEngine;

namespace VOID
{
	public class VOID_DataLogger : VOID_WindowModule, IVOID_BehaviorModule
	{
		/*
		 * Fields
		 * */
		#region Fields

		protected bool _loggingActive;
		protected bool firstWrite;

		[AVOID_SaveValue("waitForLaunch")]
		protected VOID_SaveValue<bool> waitForLaunch;

		[AVOID_SaveValue("logInterval")]
		protected VOID_SaveValue<float> logInterval;
		protected string logIntervalStr;

		protected float csvCollectTimer;

		protected List<byte> csvBytes;

		protected string _fileName;
		protected FileStream _outputFile;

		protected uint outstandingWrites;

		protected System.Text.UTF8Encoding _utf8Encoding;

		#endregion

		/*
		 * Properties
		 * */

		#region Properties

		// TODO: Add configurable or incremental file names.
		protected bool loggingActive
		{
			get
			{
				return this._loggingActive;
			}
			set
			{
				if (value != this._loggingActive)
				{
					if (value)
					{
						this.csvCollectTimer = 0f;
					}
					else
					{
						this.CloseFileIfOpen();
					}

					this._loggingActive = value;
				}
			}
		}

		protected string fileName
		{
			get
			{
				if (this._fileName == null || this._fileName == string.Empty)
				{
					this._fileName = KSP.IO.IOUtils.GetFilePathFor(
						typeof(VOIDCore),
						string.Format(
							"{0}_{1}",
							this.Vessel.vesselName,
							"data.csv"
						),
						null
					);
				}

				return this._fileName;
			}
		}

		protected FileStream outputFile
		{
			get
			{
				if (this._outputFile == null)
				{
					using (PooledDebugLogger logger = PooledDebugLogger.New(this))
					{
						logger.AppendFormat("Initializing output file '{0}' with mode ", this.fileName);

						if (File.Exists(this.fileName))
						{
							logger.Append("append");
							this._outputFile = new FileStream(
								this.fileName,
								FileMode.Append,
								FileAccess.Write,
								FileShare.Read,
								512,
								true
							);
						}
						else
						{
							logger.Append("create");
							this._outputFile = new FileStream(
								this.fileName,
								FileMode.Create,
								FileAccess.Write,
								FileShare.Read,
								512,
								true
							);

							byte[] byteOrderMark = utf8Encoding.GetPreamble();

							logger.Append(" and writing preamble");
							this._outputFile.Write(byteOrderMark, 0, byteOrderMark.Length);
						}

						logger.Append('.');

						logger.AppendFormat("  File is {0}opened asynchronously.", this._outputFile.IsAsync ? "" : "not ");

						logger.Print();
					}
				}

				return this._outputFile;
			}
		}

		public UTF8Encoding utf8Encoding
		{
			get
			{
				if (this._utf8Encoding == null)
				{
					this._utf8Encoding = new UTF8Encoding(true);
				}

				return this._utf8Encoding;
			}
		}

		#endregion

		/*
		 * Methods
		 * */
		#region Monobehaviour Lifecycle
		public void Update()
		{
			if (this.csvBytes != null && this.csvBytes.Count > 0)
			{
				// csvList is not empty, write it
				this.AsyncWriteData();
			}

			// CSV Logging
			// from ISA MapSat
			if (loggingActive && (!waitForLaunch || this.Vessel.situation != Vessel.Situations.PRELAUNCH))
			{
				//data logging is on
				//increment timers
				this.csvCollectTimer += Time.deltaTime;

				if (this.csvCollectTimer >= this.logInterval)
				{
					//data logging is on, vessel is not prelaunch, and interval has passed
					//write a line to the list
					this.CollectLogData();
				}
			}
		}

		public void FixedUpdate() {}

		public void OnDestroy()
		{
			using (PooledDebugLogger logger = PooledDebugLogger.New(this))
			{
				logger.Append("Destroying...");

				this.CloseFileIfOpen();

				logger.Append(" Done.");
				logger.Print(false);
			}
		}

		#endregion

		#region VOID_Module Overrides

		public override void LoadConfig()
		{
			base.LoadConfig();

			this.logIntervalStr = this.logInterval.value.ToString("#.0##");
		}

		public override void ModuleWindow(int id)
		{
			GUILayout.BeginVertical();

			GUILayout.Label(
				string.Format("System time: {0}", DateTime.Now.ToString("HH:mm:ss")),
				GUILayout.ExpandWidth(true)
			);
			GUILayout.Label(
				string.Format("Kerbin time: {0}", VOID_Tools.FormatDate(Planetarium.GetUniversalTime())),
				GUILayout.ExpandWidth(true)
			);

			GUIStyle activeLabelStyle = VOID_Styles.labelRed;
			string activeLabelText = "Inactive";
			if (loggingActive)
			{
				activeLabelText = "Active";
				activeLabelStyle = VOID_Styles.labelGreen;
			}

			this.loggingActive = Layout.Toggle(
				loggingActive,
				string.Format("Data logging: {0}", activeLabelText),
				null,
				activeLabelStyle
			);

			this.waitForLaunch.value = Layout.Toggle(
				this.waitForLaunch,
				"Wait for launch"
			);

			GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));

			GUILayout.Label("Interval: ", GUILayout.ExpandWidth(false));

			logIntervalStr = GUILayout.TextField(logIntervalStr, GUILayout.ExpandWidth(true));
			GUILayout.Label("s", GUILayout.ExpandWidth(false));

			GUILayout.EndHorizontal();

			float newLogInterval;
			if (float.TryParse(logIntervalStr, out newLogInterval))
			{
				logInterval.value = newLogInterval;
				this.logIntervalStr = this.logInterval.value.ToString("#.0##");
			}

			GUILayout.EndVertical();

			base.ModuleWindow(id);
		}

		#endregion

		#region Data Collection

		private void CollectLogData()
		{
			if (this.csvBytes == null)
			{
				this.csvBytes = new List<byte>();
			}

			//called if logging is on and interval has passed
			//writes one line to the csvList

			using (PooledStringBuilder line = PooledStringBuilder.Get())
			{
				if (firstWrite)
				{
					firstWrite = false;
					line.Append(
						"\"Kerbin Universal Time (s)\"," +
						"\"Mission Elapsed Time (s)\t\"," +
						"\"Altitude ASL (m)\"," +
						"\"Altitude above terrain (m)\"," +
						"\"Surface Latitude (°)\"," +
						"\"Surface Longitude (°)\"," +
						"\"Apoapsis Altitude (m)\"," +
						"\"Periapsis Altitude (m)\"," +
						"\"Orbital Velocity (m/s)\"," +
						"\"Surface Velocity (m/s)\"," +
						"\"Vertical Speed (m/s)\"," +
						"\"Horizontal Speed (m/s)\"," +
						"\"Gee Force (gees)\"," +
						"\"Temperature (°C)\"," +
						"\"Gravity (m/s²)\"," +
						"\"Atmosphere Density (g/m³)\"," +
						"\"Downrange Distance  (m)\"," +
						"\n"
					);
				}

				// Universal time
				line.Append(Planetarium.GetUniversalTime().ToString("F2"));
				line.Append(',');

				//Mission time
				line.Append(Vessel.missionTime.ToString("F3"));
				line.Append(',');

				//Altitude ASL
				line.Append(VOID_Data.orbitAltitude.Value.ToString("F3"));
				line.Append(',');

				//Altitude (true)
				line.Append(VOID_Data.trueAltitude.Value.ToString("F3"));
				line.Append(',');

				// Surface Latitude
				line.Append('"');
				line.Append(VOID_Data.surfLatitude.Value);
				line.Append('"');
				line.Append(',');

				// Surface Longitude
				line.Append('"');
				line.Append(VOID_Data.surfLongitude.Value);
				line.Append('"');
				line.Append(',');

				// Apoapsis Altitude
				line.Append(VOID_Data.orbitApoAlt.Value.ToString("G3"));
				line.Append(',');

				// Periapsis Altitude
				line.Append(VOID_Data.oribtPeriAlt.Value.ToString("G3"));
				line.Append(',');

				//Orbital velocity
				line.Append(VOID_Data.orbitVelocity.Value.ToString("F3"));
				line.Append(',');

				//surface velocity
				line.Append(VOID_Data.surfVelocity.Value.ToString("F3"));
				line.Append(',');

				//vertical speed
				line.Append(VOID_Data.vertVelocity.Value.ToString("F3"));
				line.Append(',');

				//horizontal speed
				line.Append(VOID_Data.horzVelocity.Value.ToString("F3"));
				line.Append(',');

				//gee force
				line.Append(VOID_Data.geeForce.Value.ToString("F3"));
				line.Append(',');

				//temperature
				line.Append(VOID_Data.temperature.Value.ToString("F2"));
				line.Append(',');

				//gravity
				line.Append(VOID_Data.gravityAccel.Value.ToString("F3"));
				line.Append(',');

				//atm density
				line.Append(VOID_Data.atmDensity.Value.ToString("G3"));
				line.Append(',');

				// Downrange Distance
				line.Append((VOID_Data.downrangeDistance.Value.ToString("G3")));

				line.Append('\n');

				csvBytes.AddRange(this.utf8Encoding.GetBytes(line.ToString()));

				this.csvCollectTimer = 0f;
			}
		}

		#endregion

		#region File IO Methods

		protected void AsyncWriteCallback(IAsyncResult result)
		{
			ToadicusTools.Logging.PostDebugMessage(this, "Got async callback, IsCompleted = {0}", result.IsCompleted);

			this.outputFile.EndWrite(result);
			this.outstandingWrites--;
		}

		private void AsyncWriteData()
		{
			WriteState state = new WriteState();

			state.bytes = this.csvBytes.ToArray();
			state.stream = this.outputFile;

			this.outstandingWrites++;
			var writeCallback = new AsyncCallback(this.AsyncWriteCallback);

			this.outputFile.BeginWrite(state.bytes, 0, state.bytes.Length, writeCallback, state);

			this.csvBytes.Clear();
		}

		private void CloseFileIfOpen()
		{
			using (PooledDebugLogger logger = PooledDebugLogger.New(this))
			{
				logger.AppendFormat("Cleaning up file {0}...", this.fileName);

				if (this.csvBytes != null && this.csvBytes.Count > 0)
				{
					logger.Append(" Writing remaining data...");
					this.AsyncWriteData();
				}

				logger.Append(" Waiting for writes to finish.");
				while (this.outstandingWrites > 0)
				{
					logger.Append('.');
					System.Threading.Thread.Sleep(10);
				}

				if (this._outputFile != null)
				{
					this._outputFile.Close();
					this._outputFile = null;
					logger.Append(" File closed.");
				}

				logger.Print(false);
			}
		}

		#endregion

		#region Constructors & Destructors

		public VOID_DataLogger()
		{
			this.Name = "CSV Data Logger";

			this.loggingActive = false;
			this.firstWrite = true;

			this.waitForLaunch = (VOID_SaveValue<bool>)true;

			this.logInterval = (VOID_SaveValue<float>)0.5f;
			this.csvCollectTimer = (VOID_SaveValue<float>)0f;

			this.outstandingWrites = 0;

			this.WindowPos.x = Screen.width - 520f;
			this.WindowPos.y = 85f;

			this.core.onApplicationQuit += delegate(object sender)
			{
				this.CloseFileIfOpen();
			};
		}

		~VOID_DataLogger()
		{
			this.OnDestroy();
		}

		#endregion

		#region Subclasses

		private class WriteState
		{
			public byte[] bytes;
			public FileStream stream;
		}

		#endregion
	}
}