EventLogger.java 15.7 KB
Newer Older
Andrey Filippov's avatar
Andrey Filippov committed
1 2 3 4 5
package com.elphel.imagej.ims;

import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
Andrey Filippov's avatar
Andrey Filippov committed
6 7
import java.nio.file.Path;
import java.nio.file.Paths;
Andrey Filippov's avatar
Andrey Filippov committed
8 9 10 11 12 13 14 15 16
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import ij.Prefs;

public class EventLogger {
	public  EventLoggerFileInfo [] logger_files;
17
	public EventLogger (String dir, String debug_prefix) { // dir should contain only event logger files
Andrey Filippov's avatar
Andrey Filippov committed
18 19 20 21 22 23 24 25 26 27
		if (!dir.endsWith(Prefs.getFileSeparator())) {
			dir+=Prefs.getFileSeparator();
		}
		ArrayList<String> files = new ArrayList<String>( // Set
				Stream.of(new File(dir).listFiles())
			      .filter(file -> !file.isDirectory())
			      .map(File::getName)
			      .collect(Collectors.toSet()));
		logger_files = new EventLoggerFileInfo [files.size()];
		for (int nf = 0; nf < logger_files.length; nf++) { // may use threads (per file)
28
			String debug_path= (debug_prefix != null) ? (debug_prefix+nf+".csv") : null;
Andrey Filippov's avatar
Andrey Filippov committed
29
			try {
30
				logger_files[nf] = new EventLoggerFileInfo(dir+files.get(nf), false, debug_path);
Andrey Filippov's avatar
Andrey Filippov committed
31 32 33 34 35
			} catch (IOException e) {
				logger_files[nf] = null;
				e.printStackTrace();
			}
		}
36 37
		Arrays.sort(logger_files); // increasing start time stamps
		
38 39 40
//		testInterpolateDidIns1();
//		testInterpolateDidIns1();
//		testInterpolateDidIns1();
Andrey Filippov's avatar
Andrey Filippov committed
41 42
		System.out.println("Processed "+logger_files.length+" event log files");
	}
Andrey Filippov's avatar
Andrey Filippov committed
43
	
44 45 46 47 48 49 50 51
	public void printGps(
			String out_did_gps_path,
			int gps_mask) { // 7: // +1 - DID_GPS1_POS, +2 - DID_GPS2_POS, +4 - DID_GPS1_UBX_POS
		out_did_gps_path = Paths.get(out_did_gps_path).normalize().toString();
		Path op_did_gps = Paths.get(out_did_gps_path);
		op_did_gps=op_did_gps.normalize();
		(new File(op_did_gps.getParent().toString())).mkdirs();
		for (int nf = 0; nf < logger_files.length; nf++) {
52
			String out_path= out_did_gps_path+"-"+String.format("%03d", nf)+".csv";
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
			System.out.println("Printing all DID_GPS data in "+logger_files[nf].abs_path+" to "+out_path);
			try {
				logger_files[nf].listGPS(out_path, gps_mask, false);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	
	public void printDidIns1(String out_did1_path) {
		out_did1_path = Paths.get(out_did1_path).normalize().toString();
		Path op_did1 = Paths.get(out_did1_path);
		op_did1=op_did1.normalize();
		(new File(op_did1.getParent().toString())).mkdirs();
		for (int nf = 0; nf < logger_files.length; nf++) {
70
			String out_path= out_did1_path+"-"+String.format("%03d", nf)+".csv";
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
			System.out.println("Printing all DID_INS_1 data in "+logger_files[nf].abs_path+" to "+out_path);
			try {
				logger_files[nf].listDidIns1(out_path,false);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public void printDidIns2(String out_did2_path) {
		out_did2_path = Paths.get(out_did2_path).normalize().toString();
		Path op_did2 = Paths.get(out_did2_path);
		op_did2=op_did2.normalize();
		(new File(op_did2.getParent().toString())).mkdirs();
		for (int nf = 0; nf < logger_files.length; nf++) {
87
			String out_path= out_did2_path+"-"+String.format("%03d", nf)+".csv";
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
			System.out.println("Printing all DID_INS_2 data in "+logger_files[nf].abs_path+" to "+out_path);
			try {
				logger_files[nf].listDidIns2(out_path,false);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public void printPimu(String out_pimu_path) {
		out_pimu_path = Paths.get(out_pimu_path).normalize().toString();
		Path op_pimu = Paths.get(out_pimu_path);
		op_pimu=op_pimu.normalize();
		(new File(op_pimu.getParent().toString())).mkdirs();
		for (int nf = 0; nf < logger_files.length; nf++) {
104
			String out_path= out_pimu_path+"-"+String.format("%03d", nf)+".csv";
105 106 107 108 109 110 111 112 113 114
			System.out.println("Printing all DID_INS_1 data in "+logger_files[nf].abs_path+" to "+out_path);
			try {
				logger_files[nf].listPimu(out_path,false);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
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
	public void printStrobeInTime(String out_sit_path) {
		out_sit_path = Paths.get(out_sit_path).normalize().toString();
		Path op_sit = Paths.get(out_sit_path);
		op_sit=op_sit.normalize();
		(new File(op_sit.getParent().toString())).mkdirs();
		for (int nf = 0; nf < logger_files.length; nf++) {
			String out_path= out_sit_path+"-"+String.format("%03d", nf)+".csv";
			System.out.println("Printing all DID_STROBE_IN_TIME data in "+logger_files[nf].abs_path+" to "+out_path);
			try {
				logger_files[nf].listStrobeInTime(out_path,false);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public void print2Pps(String out_1pps_path) {
		out_1pps_path = Paths.get(out_1pps_path).normalize().toString();
		Path op_1pps = Paths.get(out_1pps_path);
		op_1pps=op_1pps.normalize();
		(new File(op_1pps.getParent().toString())).mkdirs();
		for (int nf = 0; nf < logger_files.length; nf++) {
			String out_path= out_1pps_path+"-"+String.format("%03d", nf)+".csv";
			System.out.println("Printing all DID_STROBE_IN_TIME data in "+logger_files[nf].abs_path+" to "+out_path);
			try {
				logger_files[nf].list1Pps(out_path,false);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
149
	
Andrey Filippov's avatar
Andrey Filippov committed
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
	public void testInterpolateDidIns1() {
		boolean exit_now = false;
		double ts_master = 1694576078.939126;
		while (!exit_now) {
			Did_ins_1 d1=null;
			try {
				d1=interpolateDidIns1(
						ts_master,
						0);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} // debug_level) throws IOException {
			System.out.println("ts_master="+ts_master);
		}
Andrey Filippov's avatar
Andrey Filippov committed
165 166
		
	}
Andrey Filippov's avatar
Andrey Filippov committed
167 168
	
	
Andrey Filippov's avatar
Andrey Filippov committed
169
	//Did_ins_1
170
	public Did_ins_1 interpolateDidIns1(
Andrey Filippov's avatar
Andrey Filippov committed
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
			double ts_master,
			int       debug_level) throws IOException {
		byte [][] payload = new byte[2][];
		int did = Imx5.DID_INS_1;
		double frac = getDidAtTS(
				ts_master, // double    ts_master,
				did, // int       did,   // DID value (4 for DID_INS_1, 3 for DID_PIMU) 
				payload, // byte [][] payload,
				debug_level); // int       debug_level)
		if (Double.isNaN(frac)) {
			if (debug_level > -1){
				System.out.println("interpolateDidIns1(): Failed to extract DID_INS_1 data");
			}
			return null;
		}
		Did_ins_1 did_below = new Did_ins_1(ByteBuffer.wrap(payload[0]));
		Did_ins_1 did_above = new Did_ins_1(ByteBuffer.wrap(payload[1]));
		return did_below.interpolate(
				frac, // double frac,
				did_above); // Did_ins_1 next_did))
	}
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
	//Did_ins_2
	public Did_ins_2 interpolateDidIns2(
			double ts_master,
			int       debug_level) throws IOException {
		byte [][] payload = new byte[2][];
		int did = Imx5.DID_INS_2;
		double frac = getDidAtTS(
				ts_master, // double    ts_master,
				did, // int       did,   // DID value (4 for DID_INS_1, 3 for DID_PIMU) 
				payload, // byte [][] payload,
				debug_level); // int       debug_level)
		if (Double.isNaN(frac)) {
			if (debug_level > -1){
				System.out.println("interpolateDidIns1(): Failed to extract DID_INS_2 data");
			}
			return null;
		}
		Did_ins_2 did_below = new Did_ins_2(ByteBuffer.wrap(payload[0]));
		Did_ins_2 did_above = new Did_ins_2(ByteBuffer.wrap(payload[1]));
		return did_below.interpolate(
				frac, // double frac,
				did_above); // Did_ins_1 next_did))
	}
	
	public Did_gps_pos interpolateDidGpsPos(
			double ts_master,
			int    did, // Imx5.DID_GPS1_POS, Imx5.DID_GPS2_POS, Imx5.DID_GPS1_UBX_POS
			int       debug_level) throws IOException {
		byte [][] payload = new byte[2][];
		double frac = getDidAtTS(
				ts_master, // double    ts_master,
				did, // int       did,   // DID value (4 for DID_INS_1, 3 for DID_PIMU) 
				payload, // byte [][] payload,
				debug_level); // int       debug_level)
		if (Double.isNaN(frac)) {
			if (debug_level > -1){
				System.out.println("interpolateDidIns1(): Failed to extract DID_GPS_POS data");
			}
			return null;
		}
		Did_gps_pos did_below = new Did_gps_pos(ByteBuffer.wrap(payload[0]));
		Did_gps_pos did_above = new Did_gps_pos(ByteBuffer.wrap(payload[1]));
		return did_below.interpolate(
				frac, // double frac,
				did_above); // Did_gps_pos next_did))
	}
	
	public Did_pimu interpolateDidPimu(
			double ts_master,
			int       debug_level) throws IOException {
		byte [][] payload = new byte[2][];
		int did = Imx5.DID_PIMU;
		double frac = getDidAtTS(
				ts_master, // double    ts_master,
				did, // int       did,   // DID value (4 for DID_INS_1, 3 for DID_PIMU) 
				payload, // byte [][] payload,
				debug_level); // int       debug_level)
		if (Double.isNaN(frac)) {
			if (debug_level > -1){
				System.out.println("interpolateDidIns1(): Failed to extract DID_PIMU data");
			}
			return null;
		}
		Did_pimu did_below = new Did_pimu(ByteBuffer.wrap(payload[0]));
		Did_pimu did_above = new Did_pimu(ByteBuffer.wrap(payload[1]));
		return did_below.interpolate(
				frac, // double frac,
				did_above); // Did_ins_1 next_did))
	}
	
	
Andrey Filippov's avatar
Andrey Filippov committed
263 264 265 266 267 268 269
	
	public double getDidAtTS(
			double    ts_master,
			int       did,   // DID value (4 for DID_INS_1, 3 for DID_PIMU) 
			byte [][] payload,
			int       debug_level) throws IOException // initialize to [2][] - will return a pair of byte arrays
	{
Andrey Filippov's avatar
Andrey Filippov committed
270
		int min_debug = 1; //-1 to enable
Andrey Filippov's avatar
Andrey Filippov committed
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
		// 1 find file with the first subpacket
		int type = (EventLoggerFileInfo.REC_TYPE_GPS << 4) | EventLoggerFileInfo.REC_SUBTYPE_IMX5; // 0x18 - first subpacket
		int file_index_below = 0; // if ts_master is between the two files? use last of previous
		search_file: {
			for (; file_index_below < logger_files.length; file_index_below++) {
				double [] first_last_ts = logger_files[file_index_below].getFirstLastTS(type, did); 
				if (first_last_ts != null ) {
					if ((first_last_ts[0] <= ts_master) && (first_last_ts[1] >= ts_master)) { 
						break search_file; // this file contains info
					}
					// as files are ordered in ascending timestamps, no sense to go beyond
					if (first_last_ts[0] > ts_master) {
						if (file_index_below == 0) {
							if (debug_level > -1){
								System.out.println("getDidAtTS(): Required timestamp is too early");
							}
							return Double.NaN;
						}
						file_index_below--; // use last in the previous file
						break;
					}
				}
			}
			if (debug_level > -1){
				System.out.println("getDidAtTS(): Required timestamp is too late");
			}
			return Double.NaN; // here? Use last of ...
		}
		logger_files[file_index_below].open();
		int nrec_below = logger_files[file_index_below].getLastBeforeIndex( // bb should be open
				ts_master, // double    ts_master,
				false,     // boolean   after, // false - before (including ==)
				type,      // int       type,
				did);      // int       did)
		if (nrec_below < 0) {
			System.out.println("getDidAtTS(): Something is wrong, could not get record for "+type+":"+did);
			return Double.NaN;
		}
		
		int file_index_above = file_index_below; //
		// first try in the same file
		int nrec_above = logger_files[file_index_above].getLastBeforeIndex( // bb should be open
				ts_master, // double    ts_master,
				true,     // boolean   after, // false - before (including ==)
				type,      // int       type,
				did);      // int       did)
		if (nrec_above < 0) {
			file_index_above++;
			if (file_index_above >= logger_files.length) {
				if (debug_level > -1){
					System.out.println("getDidAtTS(): No next record for interpolation available");
				}
				return Double.NaN; // no next file
			}
			logger_files[file_index_above].open();
			nrec_above = logger_files[file_index_above].getFirstLastIndex(type, did)[0]; // first of this type
		}
		double ts_below = logger_files[file_index_below].getMasterTS(nrec_below); 
		double ts_above = logger_files[file_index_above].getMasterTS(nrec_above);
		double frac = (ts_master - ts_below)/(ts_above - ts_below);
Andrey Filippov's avatar
Andrey Filippov committed
331 332 333 334
		if ((debug_level >= min_debug) && (did == Imx5.DID_INS_2)) {
			System.out.println (String.format("%6d - %6d frac=%6.4f, ts_master = %17.6f, ts_below = %17.6f, ts_above = %17.6f",
					nrec_below, nrec_above, frac, ts_master, ts_below, ts_above));
		}
Andrey Filippov's avatar
Andrey Filippov committed
335 336 337 338 339 340 341 342 343
		
		// now read both byte arrays and set byte [][] payload
		EventLoggerFileInfo fileinfo_next_below =
				(file_index_below < (logger_files.length -1))?  logger_files[file_index_below + 1] : null;
		EventLoggerFileInfo fileinfo_next_above =
				(file_index_above < (logger_files.length -1))?  logger_files[file_index_above + 1] : null;
		payload[0] = logger_files[file_index_below].getDidPayload(
				fileinfo_next_below, // , // int file_index,
				nrec_below);      // int nrec)
Andrey Filippov's avatar
Andrey Filippov committed
344
		payload[1] = logger_files[file_index_above].getDidPayload( // was file_index_below
Andrey Filippov's avatar
Andrey Filippov committed
345 346 347 348 349 350 351 352 353 354 355 356 357
				fileinfo_next_above, // , // int file_index,
				nrec_above);      // int nrec)
		if ((payload[0] == null) || (payload[1] == null)) {
			if (debug_level > -1){
				if (payload[0] == null) {
					System.out.println("getDidAtTS(): failed to get payload[0]");
				}
				if (payload[1] == null) {
					System.out.println("getDidAtTS(): failed to get payload[1]");
				}
			}
			return Double.NaN;
		}
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
		// if it is DID_INS_1 or DID_INS_2 use TOW for calculating fraction
		if ((did == Imx5.DID_INS_1) || (did == Imx5.DID_INS_2)) {
			double tow_corr = logger_files[file_index_below].getTimeOfWeekCorrection(ts_master);
			int week0, week1;
			double tow0, tow1;
			if (!Double.isNaN(tow_corr)) { 
				double tow = logger_files[file_index_below].getLinearTimeOfWeek(ts_master) - tow_corr;
				@SuppressWarnings("rawtypes")
				Did_ins did_ins_0 = (did == Imx5.DID_INS_2) ?
						(new Did_ins_2(ByteBuffer.wrap(payload[0]))) : (new Did_ins_1(ByteBuffer.wrap(payload[0])));
				@SuppressWarnings("rawtypes")
				Did_ins did_ins_1 = (did == Imx5.DID_INS_2) ?
						(new Did_ins_2(ByteBuffer.wrap(payload[1]))) : (new Did_ins_1(ByteBuffer.wrap(payload[1])));
				tow0 = did_ins_0.timeOfWeek;
				tow1 = did_ins_1.timeOfWeek;
				if (did_ins_1.week > did_ins_0.week) {
					tow1+=	Did_ins.WEEK_SECONDS;
				}
				frac = (tow - tow0) /(tow1-tow0);
			} else {
				System.out.println("ERROR: getDidAtTS(): tow_corr is NaN, keeping frac="+frac);
			}
		}
Andrey Filippov's avatar
Andrey Filippov committed
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
		return frac; 
	}
	
	/*
	
	byte [] getDidPayload(
			int file_index,
			int nrec) throws IOException {
		logger_files[file_index].open();
		int [] full_type = logger_files[file_index].getFullType(nrec); // 0x18
		int did_len = logger_files[file_index].getIMX5Length(nrec);
		if (did_len < 0) {
			System.out.println("Wrong packet length (-"+did_len+")");
			return null; // error - length too large
		}
		byte [] payload = new byte [did_len];
		int bytes_left = did_len;
		int bytes_offset = 0;
		// read all/some from the initial sub packet;
		int subpacket = 0;
		while (bytes_left > 0) {
			int bytes_copied = logger_files[file_index].copyPayload (
					nrec,         // int        nrec,
					payload,      // byte []    payload,
					bytes_offset, // int        offset,
					bytes_left);  // int        len) {
			bytes_left -= bytes_copied;
			bytes_offset += bytes_copied;
			subpacket ++;
			if (bytes_left > 0) {
				// find next subpacket, open new file if needed
				if (subpacket > EventLoggerFileInfo.REC_SUBPACKET_IMX5) {
					System.out.println("Too many subpackets (>"+EventLoggerFileInfo.REC_SUBPACKET_IMX5+")");
					return null; // throw - illegal subpacket index 
				}
				nrec = logger_files[file_index].getNextIndex( // assuming open
						nrec,                     // int       indx,
						full_type[0] + subpacket, //  int       type,
						full_type[1]); //int       did)
				if (nrec < 0) {
					System.out.println("Reached the end of the current log file, proceeding to the next one");
					file_index++;
					if (file_index >= logger_files.length) {
						System.out.println("No log files left");
						return null;
					}
					logger_files[file_index].open();
					nrec = logger_files[file_index].getFirstLastIndex( // earliest in a file
							full_type[0] + subpacket,
							full_type[1])[0];
				}
			}
		}
		return null;
	}
	*/
	
}