File size: 27,231 Bytes
68ce2fc | 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 525 526 527 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 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 | /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* ex: set filetype=cpp softtabstop=4 shiftwidth=4 tabstop=4 cindent expandtab: */
/*
Author(s): Min Yang Jung, Anton Deguet
Created on: 2009-03-20
(C) Copyright 2009-2026 Johns Hopkins University (JHU), All Rights Reserved.
--- begin cisst license - do not edit ---
This software is provided "as is" under an open source license, with
no warranty. The complete license can be found in license.txt and
http://www.cisst.org/cisst/license.txt.
--- end cisst license ---
*/
#include <cisstMultiTask/mtsCollectorState.h>
#include <cisstCommon/cmnGenericObjectProxy.h>
#include <cisstCommon/cmnThrow.h>
#include <cisstOSAbstraction/osaGetTime.h>
#include <cisstOSAbstraction/osaTimeServer.h>
#include <cisstMultiTask/mtsManagerLocal.h>
#include <cisstMultiTask/mtsInterfaceRequired.h>
#include <iostream>
#include <fstream>
#include <sstream>
/* Header Definition. The value of END_OF_HEADER_SIZE should match the size of
END_OF_HEADER array. */
#define END_OF_HEADER_SIZE 5
#define END_OF_HEADER {0,1,2,1,0}
static char EndOfHeader[END_OF_HEADER_SIZE] = END_OF_HEADER;
//-------------------------------------------------------
// Constructor, Destructor, and Initializer
//-------------------------------------------------------
mtsCollectorState::mtsCollectorState(const std::string & collectorName):
mtsCollectorBase(collectorName,
COLLECTOR_FILE_FORMAT_UNDEFINED),
TargetComponent(0),
TargetStateTable(0)
{
this->Initialize();
}
mtsCollectorState::mtsCollectorState(const std::string & targetComponentName,
const std::string & targetStateTableName,
const mtsCollectorBase::CollectorFileFormat fileFormat):
mtsCollectorBase(std::string("StateCollectorFor") + targetComponentName + targetStateTableName,
fileFormat),
TargetComponent(0),
TargetStateTable(0)
{
this->SetStateTable(targetComponentName, targetStateTableName);
this->SetOutputToDefault(fileFormat);
this->Initialize();
}
mtsCollectorState::~mtsCollectorState()
{
// serializer was created for a binary output
if (this->Serializer) {
delete this->Serializer;
}
// this is a stream created internally, we should clean it
if (this->OutputFile) {
CMN_LOG_CLASS_INIT_VERBOSE << "destructor: closing file \"" << this->OutputFileName << "\"" << std::endl;
this->OutputFile->close();
delete this->OutputFile;
}
}
bool mtsCollectorState::SetStateTable(const std::string & componentName,
const std::string & stateTableName)
{
// check if this component has already been connected
if (this->ConnectedFlag) {
CMN_LOG_CLASS_INIT_ERROR << "SetStateTable: collector \"" << this->GetName()
<< "\" is already connected, you cannot modify the state table to collect" << std::endl;
return false;
}
// check if there is the specified component and the specified state table.
this->TargetComponent = GetManagerComponentServices()->ComponentGet(componentName);
if (!this->TargetComponent) {
cmnThrow(std::runtime_error("mtsCollectorState::SetStateTable: component \"" + componentName
+ "\" not found in component manager."));
}
// this task needs a pointer on the state table to perform a fast copy
this->TargetStateTable = this->TargetComponent->GetStateTable(stateTableName);
if (!this->TargetStateTable) {
CMN_LOG_CLASS_INIT_ERROR << "Initialize: cannot find state table \""
<< stateTableName << "\" in component \""
<< componentName << "\" for collector \""
<< this->GetName() << "\"" << std::endl;
this->TargetComponent = 0;
cmnThrow(std::runtime_error("mtsCollectorState::SetStateTable: cannot find state table."));
}
return true;
}
bool mtsCollectorState::Connect(void)
{
// check that a component/state table has been set properly
if (!(this->TargetComponent && this->TargetStateTable)) {
CMN_LOG_CLASS_INIT_ERROR << "Connect: component and/or state table has not been set for collector \""
<< this->GetName() << "\"" << std::endl;
return false;
}
// then connect the interface
CMN_LOG_CLASS_INIT_DEBUG << "Connect: connecting required interface \"" << this->GetName() << "::StateTable\" to provided interface \""
<< this->TargetComponent->GetName() << "::StateTable" << this->TargetStateTable->GetName() << "\"" << std::endl;
if (!GetManagerComponentServices()->Connect(this->GetName(), "StateTable",
this->TargetComponent->GetName(), "StateTable" + this->TargetStateTable->GetName())) {
CMN_LOG_CLASS_INIT_ERROR << "Connect: connect failed for required interface \"" << this->GetName() << "::StateTable\" to provided interface \""
<< this->TargetComponent->GetName() << "::StateTable" << this->TargetStateTable->GetName() << "\"" << std::endl;
return false;
}
this->ConnectedFlag = true;
return true;
}
bool mtsCollectorState::Disconnect(void)
{
// check that a component has been set properly
if (!(this->TargetComponent && this->TargetStateTable)) {
CMN_LOG_CLASS_INIT_ERROR << "Disconnect: component and/or state table has not been set for collector \""
<< this->GetName() << "\"" << std::endl;
return false;
}
// then connect the interface
CMN_LOG_CLASS_INIT_DEBUG << "Disconnect: disconnecting required interface \"" << this->GetName() << "::StateTable\" from provided interface \""
<< this->TargetComponent->GetName() << "::StateTable" << this->TargetStateTable->GetName() << "\"" << std::endl;
if (!GetManagerComponentServices()->Disconnect(this->GetName(), "StateTable",
this->TargetComponent->GetName(), "StateTable" + this->TargetStateTable->GetName())) {
CMN_LOG_CLASS_INIT_ERROR << "Disconnect: connect failed for required interface \"" << this->GetName() << "::StateTable\" from provided interface \""
<< this->TargetComponent->GetName() << "::StateTable" << this->TargetStateTable->GetName() << "\"" << std::endl;
return false;
}
this->ConnectedFlag = false;
return true;
}
void mtsCollectorState::Initialize(void)
{
CMN_LOG_CLASS_INIT_DEBUG << "Initialize: for \"" << this->GetName() << "\"" << std::endl;
LastReadIndex = -1;
TableHistoryLength = 0;
SamplingInterval = 1;
OffsetForNextRead = 0;
// add a required interface to the collector task to communicate with the component containing the state table
mtsInterfaceRequired * interfaceRequired = this->AddInterfaceRequired("StateTable");
if (interfaceRequired) {
// functions to stop/start collection
interfaceRequired->AddFunction("StartCollection", StateTableStartCollection);
interfaceRequired->AddFunction("StopCollection", StateTableStopCollection);
// event received when the state table fills up and needs to be collected
interfaceRequired->AddEventHandlerWrite(&mtsCollectorState::BatchReadyHandler,
this,
"BatchReady");
// add events for progress, these should not be queued as they
// are pass-thru events
interfaceRequired->AddEventHandlerVoid(&mtsCollectorState::CollectionStartedHandler, this,
"CollectionStarted", MTS_EVENT_NOT_QUEUED);
interfaceRequired->AddEventHandlerWrite(&mtsCollectorState::CollectionStoppedHandler, this,
"CollectionStopped", MTS_EVENT_NOT_QUEUED);
interfaceRequired->AddEventHandlerWrite(&mtsCollectorState::ProgressHandler, this,
"Progress", MTS_EVENT_NOT_QUEUED);
} else {
CMN_LOG_CLASS_INIT_ERROR << "Connect: unable to add required interface to communicate with state table for \""
<< this->GetName() << "\"" << std::endl;
cmnThrow(std::runtime_error("mtsCollectorState::Connect: unable to add required interface"));
}
}
std::string mtsCollectorState::GetDefaultOutputName(void)
{
std::string currentDateTime;
osaGetDateTimeString(currentDateTime);
std::string fileName;
if (TargetComponent && TargetStateTable) {
fileName =
"StateDataCollection-" + TargetComponent->GetName() + "-"
+ TargetStateTable->GetName() + "-" + currentDateTime;
} else {
fileName = "StateDataCollection-" + currentDateTime;
CMN_LOG_CLASS_INIT_WARNING << "GetDefaultOutputName: component and/or state table not yet provided, using fixed name \""
<< fileName << "\" for output" << std::endl;
}
return fileName;
}
void mtsCollectorState::Run(void)
{
CMN_LOG_CLASS_RUN_DEBUG << "Run: collector \"" << this->GetName() << "\"" << std::endl;
ProcessQueuedCommands();
ProcessQueuedEvents();
}
void mtsCollectorState::StartCollection(const double & delay)
{
mtsExecutionResult result = this->StateTableStartCollection(delay);
if (!result.IsOK()) {
CMN_LOG_CLASS_RUN_ERROR << "StartCollection failed for state collector \"" << this->GetName()
<< "\", the command might not be connected properly to the state table provided interface: "
<< result << std::endl;
}
}
void mtsCollectorState::StopCollection(const double & delay)
{
mtsExecutionResult result = this->StateTableStopCollection(delay);
if (!result.IsOK()) {
CMN_LOG_CLASS_RUN_ERROR << "StopCollection failed for state collector \"" << this->GetName()
<< "\", the command might not be connected properly to the state table provided interface: "
<< result << std::endl;
}
}
void mtsCollectorState::BatchReadyHandler(const mtsStateTable::IndexRange & range)
{
CMN_LOG_CLASS_RUN_DEBUG << "BatchReadyHandler: called for batch ["
<< range.First << ", " << range.Last << "]" << std::endl;
BatchCollect(range);
}
void mtsCollectorState::CollectionStartedHandler(void)
{
this->CollectionStartedEventTrigger(true);
}
void mtsCollectorState::CollectionStoppedHandler(const size_t & count)
{
this->ProgressEventTrigger(count);
this->CollectionStartedEventTrigger(false);
}
void mtsCollectorState::ProgressHandler(const size_t & count)
{
this->ProgressEventTrigger(count);
}
//-------------------------------------------------------
// Signal Management
//-------------------------------------------------------
bool mtsCollectorState::AddSignal(const std::string & signalName)
{
// Check if a user wants to collect all signals
bool collectAllSignal = (signalName.length() == 0);
if (!collectAllSignal) {
// Check if the specified signal does exist in the state table.
int StateVectorID = TargetStateTable->GetStateVectorID(signalName); // 0: Toc, 1: Tic, 2: Period, >=3: user
if (StateVectorID == -1) { // 0: Toc, 1: Tic, 2: Period, >3: user
const auto names = TargetStateTable->GetDataNames();
CMN_LOG_CLASS_INIT_ERROR << "AddSignal: collector \"" << this->GetName()
<< "\", cannot find signal \"" << signalName << "\". Signals available "
<< cmnDataVectorHumanReadable(names) << std::endl;
return false;
}
// Add a signal
if (!AddSignalElement(signalName, StateVectorID)) {
CMN_LOG_CLASS_INIT_ERROR << "AddSignal: collector \"" << this->GetName()
<< "\", already registered signal \"" << signalName << "\"" << std::endl;
return false;
}
} else {
// Add all signals in the state table
for (unsigned int i = 0; i < TargetStateTable->StateVectorDataNames.size(); ++i) {
if (!AddSignalElement(TargetStateTable->StateVectorDataNames[i], i)) {
CMN_LOG_CLASS_INIT_ERROR << "AddSignal: collector \"" << this->GetName()
<< "\", already registered signal \"" << TargetStateTable->StateVectorDataNames[i] << "\"" << std::endl;
return false;
}
}
}
// To reduce reference counter in the mtsCollectorState::Collect() method.
TableHistoryLength = TargetStateTable->HistoryLength;
return true;
}
bool mtsCollectorState::IsRegisteredSignal(const std::string & signalName) const
{
RegisteredSignalElementType::const_iterator it = RegisteredSignalElements.begin();
for (; it != RegisteredSignalElements.end(); ++it) {
if (it->Name == signalName) return true;
}
return false;
}
bool mtsCollectorState::AddSignalElement(const std::string & signalName, const unsigned int signalID)
{
// Prevent duplicate signal registration
if (IsRegisteredSignal(signalName)) {
return false;
}
SignalElement element;
element.Name = signalName;
element.ID = signalID;
RegisteredSignalElements.push_back(element);
CMN_LOG_CLASS_INIT_VERBOSE << "AddSignalElement: collector \"" << this->GetName()
<< "\", signal added \"" << signalName << "\"" << std::endl;
return true;
}
//-------------------------------------------------------
// Collecting Data
//-------------------------------------------------------
void mtsCollectorState::BatchCollect(const mtsStateTable::IndexRange & range)
{
if (RegisteredSignalElements.size() == 0) return;
// If this method is called for the first time, print out some information.
if (FirstRunningFlag) {
this->OpenFileIfNeeded();
PrintHeader(this->FileFormat);
}
const size_t startIndex = range.First.Ticks() % TableHistoryLength;
const size_t endIndex = range.Last.Ticks() % TableHistoryLength;
if (startIndex < endIndex) {
// normal case
if (FetchStateTableData(TargetStateTable, startIndex, endIndex)) {
LastReadIndex = (endIndex + (OffsetForNextRead - 1)) % TableHistoryLength;
}
} else if (startIndex == endIndex) {
// No data to be read. Wait for the next run
} else {
// Wrap-around case
// first part: from the last read index to the end of the array
if (FetchStateTableData(TargetStateTable, startIndex, TableHistoryLength - 1)) {
// second part: from the beginning of the array to the end of range
if (FetchStateTableData(TargetStateTable, 0, endIndex)) {
LastReadIndex = (endIndex + (OffsetForNextRead - 1)) % TableHistoryLength;
}
}
}
}
void mtsCollectorState::PrintHeader(const CollectorFileFormat & fileFormat)
{
std::string currentDateTime;
std::ostringstream out;
osaGetDateTimeString(currentDateTime);
const osaTimeServer & timeServer = mtsManagerLocal::GetInstance()->GetTimeServer();
osaAbsoluteTime origin;
timeServer.GetTimeOrigin(origin);
out.precision(20);
if (this->OutputHeaderStream) {
this->OutputHeaderStream->precision(20);
out << "Ticks";
const char unlikely_char = '\u001E';
RegisteredSignalElementType::const_iterator it = RegisteredSignalElements.begin();
for (; it != RegisteredSignalElements.end(); ++it) {
out << unlikely_char;
(*(TargetStateTable->StateVector[it->ID]))[0].ToStreamRaw(*((std::ostream*) &out), unlikely_char, true,
TargetStateTable->StateVectorDataNames[it->ID]);
}
out << std::endl;
// process the content and make header file
std::vector <std::string> fieldNames;
std::vector <double> fieldValues;
std::istringstream iss(out.str());
std::string token;
// get token
while (getline(iss, token, unlikely_char)) {
fieldNames.push_back(token);
}
// FileName:
// Date:
// Format:
// Delimiter
// Number Of Fields:
// Number Of Time Fields:
// Number Of Data Fields:
// Field 1
// ...
// Field N
// File Name
*(this->OutputHeaderStream) << this->OutputFileName << std::endl;
// Date
*(this->OutputHeaderStream) << currentDateTime << " ";
*(this->OutputHeaderStream) << origin.ToSeconds() << std::endl;
// Format
if (fileFormat == COLLECTOR_FILE_FORMAT_PLAIN_TEXT) {
*(this->OutputHeaderStream) << "Text" << std::endl ;
} else if (fileFormat == COLLECTOR_FILE_FORMAT_CSV) {
*(this->OutputHeaderStream) << "CSV" << std::endl ;
} else {
*(this->OutputHeaderStream) << "Binary" << std::endl;
}
// Delimiter
*(this->OutputHeaderStream) << this->Delimiter << std::endl;
// Number Of Fields
*(this->OutputHeaderStream) << fieldNames.size() << std::endl;
size_t timeElementsNumber = 0, dtaElementsNumber = 0;
for (size_t i = 0; i< fieldNames.size(); i++) {
std::string element = fieldNames.at(i);
if (element.find("time") != std::string::npos) {// this is a time element
timeElementsNumber ++;
} else {
dtaElementsNumber ++;
}
}
// Number Of Time Fields:
*(this->OutputHeaderStream) << timeElementsNumber << std::endl;
// Number Of Data Fields:
*(this->OutputHeaderStream) << dtaElementsNumber << std::endl;
// All Fields
for (size_t i = 0; i< fieldNames.size(); i++) {
std::string element = fieldNames.at(i);
if (element.find("time") != std::string::npos) {// this is a time element
*(this->OutputHeaderStream) << "Time: " << element << std::endl;
} else {
*(this->OutputHeaderStream) << "Data: " << element << std::endl;
}
}
}
else if (this->OutputStream) {
// Print out some information on the state table.
// All lines in the header should be preceded by '#' which represents
// the line contains header information rather than collected data.
*(this->OutputStream) << "# Component name : " << TargetComponent->GetName() << std::endl;
*(this->OutputStream) << "# Table name : " << TargetStateTable->GetName() << std::endl;
*(this->OutputStream) << "# Date & time : " << currentDateTime << std::endl;
*(this->OutputStream) << "# Total signal count : " << RegisteredSignalElements.size() << std::endl;
*(this->OutputStream) << "# Data format : ";
if (fileFormat == COLLECTOR_FILE_FORMAT_PLAIN_TEXT) {
*(this->OutputStream) << "Text";
} else if (fileFormat == COLLECTOR_FILE_FORMAT_CSV) {
*(this->OutputStream) << "Text (CSV)";
} else {
*(this->OutputStream) << "Binary";
}
*(this->OutputStream) << std::endl;
*(this->OutputStream) << "#" << std::endl;
*(this->OutputStream) << "# Ticks";
RegisteredSignalElementType::const_iterator it = RegisteredSignalElements.begin();
for (; it != RegisteredSignalElements.end(); ++it) {
*(this->OutputStream) << this->Delimiter;
(*(TargetStateTable->StateVector[it->ID]))[0].ToStreamRaw(*(this->OutputStream), this->Delimiter, true,
TargetStateTable->StateVectorDataNames[it->ID]);
}
*(this->OutputStream) << std::endl;
// In case of using binary format
if (fileFormat == COLLECTOR_FILE_FORMAT_BINARY) {
// Mark the end of the header.
MarkHeaderEnd(*(this->OutputStream));
// Remember the number of registered signals.
cmnULongLong cmnULongTotalSignalCount;
cmnULongTotalSignalCount.Data = RegisteredSignalElements.size();
StringStreamBufferForSerialization.str("");
Serializer->Serialize(cmnULongTotalSignalCount);
*(this->OutputStream) << StringStreamBufferForSerialization.str();
}
} else {
CMN_LOG_CLASS_RUN_ERROR << "PrintHeader: output stream for collector \"" << this->GetName() << "\" is not available." << std::endl;
}
FirstRunningFlag = false;
}
void mtsCollectorState::MarkHeaderEnd(std::ostream & output)
{
for (int i = 0; i < END_OF_HEADER_SIZE; ++i) {
output << EndOfHeader[i];
}
output << std::endl;
}
bool mtsCollectorState::IsHeaderEndMark(const char * buffer)
{
for (int i = 0; i < END_OF_HEADER_SIZE; ++i) {
if (buffer[i] != EndOfHeader[i]) {
return false;
}
}
return true;
}
bool mtsCollectorState::FetchStateTableData(const mtsStateTable * table,
const size_t startIndex,
const size_t endIndex)
{
if (this->OutputStream) {
if (this->OutputStream->good()) {
if (FileFormat == COLLECTOR_FILE_FORMAT_BINARY) {
cmnULongLong timeTick;
size_t i, j;
for (i = startIndex; i <= endIndex; i += SamplingInterval) {
StringStreamBufferForSerialization.str("");
timeTick.Data = TargetStateTable->Ticks[i];
Serializer->Serialize(timeTick);
*(this->OutputStream) << StringStreamBufferForSerialization.str();
for (j = 0; j < RegisteredSignalElements.size(); ++j) {
StringStreamBufferForSerialization.str("");
Serializer->Serialize((*table->StateVector[RegisteredSignalElements[j].ID])[i]);
*(this->OutputStream) << StringStreamBufferForSerialization.str();
}
}
OffsetForNextRead = (i - endIndex == 0 ? SamplingInterval : i - endIndex);
} else {
size_t i, j;
for (i = startIndex; i <= endIndex; i += SamplingInterval) {
*(this->OutputStream) << TargetStateTable->Ticks[i];
for (j = 0; j < RegisteredSignalElements.size(); ++j) {
*(this->OutputStream) << this->Delimiter;
(*table->StateVector[RegisteredSignalElements[j].ID])[i].ToStreamRaw(*(this->OutputStream), this->Delimiter);
}
*(this->OutputStream) << std::endl;
}
OffsetForNextRead = (i - endIndex == 0 ? SamplingInterval : i - endIndex);
}
} else {
CMN_LOG_CLASS_RUN_ERROR << "FetchStateTableData: encountered problem on output stream for collector \""
<< this->GetName() << "\"" << std::endl;
}
} else {
CMN_LOG_CLASS_RUN_ERROR << "FetchStateTableData: output stream for collector \"" << this->GetName() << "\" is not available." << std::endl;
}
return true;
}
bool mtsCollectorState::ConvertBinaryToText(const std::string sourceBinaryFileName,
const std::string targetPlainTextFileName,
const char delimiter)
{
// Try to open a binary file (source).
std::ifstream inFile(sourceBinaryFileName.c_str(), std::ios::in | std::ios::binary | std::ios::ate);
if (!inFile.is_open()) {
CMN_LOG_INIT_ERROR << "Class mtsCollectorState: ConvertBinaryToText: unable to open binary file: " << sourceBinaryFileName << std::endl;
return false;
}
// Prepare output file with plain text format.
std::ofstream outFile(targetPlainTextFileName.c_str(), std::ios::out);
if (!outFile.is_open()) {
CMN_LOG_INIT_ERROR << "Class mtsCollectorState: ConvertBinaryToText: unable to create text file: " << targetPlainTextFileName << std::endl;
inFile.close();
return false;
}
// Get the total size of the file in bytes.
std::ifstream::pos_type inFileTotalSize = inFile.tellg();
inFile.seekg(0, std::ios::beg);
// Read the first character in a line. If it is '#', it is a part of header.
char line[2048];
while (true) {
inFile.getline(line, 2048);
if (line[0] == '#') {
// Copy header lines.
outFile << line << std::endl;
continue;
}
break;
}
// Check the end of header.
if (!IsHeaderEndMark(line)) {
CMN_LOG_INIT_ERROR << "Class mtsCollectorState: ConvertBinaryToText: corrupted header (invalid end mark)." << std::endl;
inFile.close();
outFile.close();
return false;
}
cmnDeSerializer DeSerializer(inFile);
// Deserialize to get the total number of recorded signals.
cmnGenericObject * element = DeSerializer.DeSerialize();
// Should we check that element is not 0?
cmnULong * totalSignalCountObject = dynamic_cast<cmnULong *>(element);
if (!totalSignalCountObject) {
CMN_LOG_INIT_ERROR << "Class mtsCollectorState: ConvertBinaryToText: corrupted header (missing number of signals)." << std::endl;
inFile.close();
outFile.close();
// release memory internally allocated by deserializer
delete element;
return false;
}
unsigned int totalSignalCount = totalSignalCountObject->Data;
unsigned int columnCount = 0;
std::ifstream::pos_type currentPos = inFile.tellg();
while (currentPos < inFileTotalSize) {
element = DeSerializer.DeSerialize();
if (!element) {
CMN_LOG_INIT_ERROR << "Class mtsCollectorState: ConvertBinaryToText: unexpected termination: "
<< currentPos << " / " << inFileTotalSize << std::endl;
break;
}
element->ToStreamRaw(outFile, delimiter);
if (++columnCount == totalSignalCount + 1) { // +1 due to 'Ticks' field.
outFile << std::endl;
columnCount = 0;
} else {
outFile << delimiter;
}
currentPos = inFile.tellg();
// release memory internally allocated by deserializer
delete element;
}
CMN_LOG_INIT_VERBOSE << "Class mtsCollectorState: ConvertBinaryToText: conversion completed: " << targetPlainTextFileName << std::endl;
outFile.close();
inFile.close();
return true;
}
|