From 891e2bed8398dd63ae71194ce908bc5e4f60d483 Mon Sep 17 00:00:00 2001 From: hturkmanovic Date: Thu, 29 Oct 2026 15:44:28 +0100 Subject: [PATCH 1/4] Latest --- Source/Processing/batteryparamsextraction.cpp | 401 +++++---- Source/Processing/batteryparamsextraction.h | 24 +- Source/Processing/fileprocessing.cpp | 11 +- Source/Processing/waveform.cpp | 55 ++ Source/Processing/waveform.h | 20 + .../Windows/BatteryParams/batterycyclewnd.cpp | 32 + .../Windows/BatteryParams/batterycyclewnd.h | 2 + .../batteryparamssettingsdlg.cpp | 16 +- .../BatteryParams/batteryparamssettingsdlg.h | 3 +- .../BatteryParams/batteryparamswnd.cpp | 781 +++++++++++++++++- .../Windows/BatteryParams/batteryparamswnd.h | 32 + Source/Windows/DataAnalyzer/dataanalyzer.cpp | 9 + .../DataAnalyzer/dataanalyzerprofile.cpp | 191 ++++- .../DataAnalyzer/dataanalyzerprofile.h | 4 + Source/Windows/Device/devicewnd.cpp | 3 + Source/Windows/Device/devicewnd.h | 2 + Source/Windows/Device/devicewnd.ui | 59 ++ Source/Windows/Device/energycontrolwnd.cpp | 532 +++++++++--- Source/Windows/Device/energycontrolwnd.h | 38 +- Source/Windows/Plot/plot.cpp | 32 + Source/Windows/Plot/plot.h | 3 + Source/devicecontainer.cpp | 286 ++++++- Source/devicecontainer.h | 22 + Source/images/NewSet/battery.png | Bin 0 -> 395 bytes Source/resource.qrc | 1 + 25 files changed, 2248 insertions(+), 311 deletions(-) create mode 100644 Source/images/NewSet/battery.png diff --git a/Source/Processing/batteryparamsextraction.cpp b/Source/Processing/batteryparamsextraction.cpp index 1fb0e48..ccb5120 100644 --- a/Source/Processing/batteryparamsextraction.cpp +++ b/Source/Processing/batteryparamsextraction.cpp @@ -14,6 +14,7 @@ BatteryParamsExtraction::BatteryParamsExtraction(QObject *parent) samplingPeriod = 0; settings = settingsDefault(); analysisDeferred = false; + captureIncomplete = false; chargeTotal = 0; cycleActive = false; cycleCounter = 0; @@ -43,7 +44,6 @@ batteryparams_settings_t BatteryParamsExtraction::settingsDefault() defaults.model = BATTERYPARAMS_MODEL_SECOND_ORDER; defaults.fitEnd = BATTERYPARAMS_FIT_END_PAUSE; defaults.tauGridPoints = BATTERYPARAMS_TAU_GRID_POINTS; - defaults.tauRefinementNo = BATTERYPARAMS_TAU_REFINEMENT_NO; defaults.tauSeparation = BATTERYPARAMS_TAU_SEPARATION; defaults.capacity = 0; defaults.initialSoc = BATTERYPARAMS_INITIAL_SOC_DEFAULT; @@ -65,6 +65,36 @@ void BatteryParamsExtraction::setAnalysisDeferred(bool aDeferred) analysisDeferred = aDeferred; } +void BatteryParamsExtraction::setCaptureIncomplete(bool aCapture) +{ + captureIncomplete = aCapture; +} + +void BatteryParamsExtraction::finalizeIncompleteCycle(double pauseEndKey) +{ + if(!cycleActive) return; + + if(activeCycle.pulseStartKey <= 0 || keySamples.isEmpty()) + { + cycleActive = false; + return; + } + + activeCycle.pauseEndKey = pauseEndKey; + activeCycle.incomplete = true; + storeCycleSamples(); + cycles.append(activeCycle); + cycleActive = false; + emit sigCycleFinished(activeCycle); + trimSamples(pauseEndKey); +} + +void BatteryParamsExtraction::flushIncompleteCycle() +{ + if(!cycleActive || keySamples.isEmpty()) return; + finalizeIncompleteCycle(keySamples.last()); +} + batteryparams_settings_t BatteryParamsExtraction::getSettings() { return settings; @@ -113,81 +143,81 @@ static int prvBATTERYPARAMS_RelaxationPositionGet(const QVector &keys, c return -1; } -/*With the time constants fixed the relaxation curve is linear in its remaining - parameters, so the open circuit voltage the cell is heading to and the branch - amplitudes are obtained by least squares. Fitting the asymptote instead of - taking it from the last sample keeps the result usable even when the pause is - cut short*/ -static bool prvBATTERYPARAMS_RelaxationFit(const QVector &time, const QVector &voltage, - double tauFast, double tauSlow, bool secondOrder, - double *openCircuitVoltage, double *amplitudeFast, double *amplitudeSlow) +/*Fits a single decaying exponential value ~ amplitude * exp(-time / tau) over the + given index range. The time constant is searched on a logarithmic grid, the + amplitude is solved by least squares for every candidate, and the grid is narrowed + around the best value a few times. Used for peeling the slow and fast branches off + separate portions of the relaxation*/ +static bool prvBATTERYPARAMS_SingleExpFit(const QVector &time, const QVector &value, + int startIndex, int endIndex, + double tauLow, double tauHigh, + int gridPoints, int refinementNo, + double *bestTau, double *bestAmplitude) { - int size = secondOrder ? 3 : 2; - double matrix[3][4]; + if((startIndex < 0) || (endIndex >= time.size()) || ((endIndex - startIndex) < 1)) return false; + if(gridPoints < 2) gridPoints = 2; + if(refinementNo < 1) refinementNo = 1; + if(tauLow <= 0) return false; + if(tauHigh <= tauLow) tauHigh = tauLow * 10.0; - for(int row = 0; row < size; row++) - { - for(int column = 0; column < size + 1; column++) - { - matrix[row][column] = 0; - } - } + double low = tauLow; + double high = tauHigh; + double resultTau = 0; + double resultAmplitude = 0; + bool found = false; - for(int i = 0; i < time.size(); i++) + for(int refinement = 0; refinement < refinementNo; refinement++) { - double basis[3]; - - basis[0] = 1.0; - basis[1] = exp(-time[i] / tauFast); - basis[2] = secondOrder ? exp(-time[i] / tauSlow) : 0; + double refineBestError = -1; + double refineBestTau = 0; + double refineBestAmplitude = 0; - for(int row = 0; row < size; row++) + for(int step = 0; step < gridPoints; step++) { - for(int column = 0; column < size; column++) + double tau = low * pow(high / low, (double)step / (gridPoints - 1)); + double sumXe = 0; + double sumEe = 0; + + for(int i = startIndex; i <= endIndex; i++) { - matrix[row][column] += basis[row] * basis[column]; + double basis = exp(-time[i] / tau); + sumXe += value[i] * basis; + sumEe += basis * basis; } - matrix[row][size] += basis[row] * voltage[i]; - } - } - for(int column = 0; column < size; column++) - { - int pivot = column; + if(sumEe <= 0) continue; - for(int row = column + 1; row < size; row++) - { - if(fabs(matrix[row][column]) > fabs(matrix[pivot][column])) pivot = row; - } + double amplitude = sumXe / sumEe; + double error = 0; - if(fabs(matrix[pivot][column]) < 1e-18) return false; + for(int i = startIndex; i <= endIndex; i++) + { + double residual = value[i] - amplitude * exp(-time[i] / tau); + error += residual * residual; + } - for(int i = 0; i < size + 1; i++) - { - double temporary = matrix[column][i]; - matrix[column][i] = matrix[pivot][i]; - matrix[pivot][i] = temporary; + if((refineBestError < 0) || (error < refineBestError)) + { + refineBestError = error; + refineBestTau = tau; + refineBestAmplitude = amplitude; + } } - for(int row = 0; row < size; row++) - { - double factor; - - if(row == column) continue; + if(refineBestError < 0) break; - factor = matrix[row][column] / matrix[column][column]; + resultTau = refineBestTau; + resultAmplitude = refineBestAmplitude; + found = true; - for(int i = column; i < size + 1; i++) - { - matrix[row][i] -= factor * matrix[column][i]; - } - } + low = refineBestTau / BATTERYPARAMS_TAU_REFINEMENT_SPAN; + high = refineBestTau * BATTERYPARAMS_TAU_REFINEMENT_SPAN; } - *openCircuitVoltage = matrix[0][size] / matrix[0][0]; - *amplitudeFast = -matrix[1][size] / matrix[1][1]; - *amplitudeSlow = secondOrder ? (-matrix[2][size] / matrix[2][2]) : 0; + if(!found) return false; + *bestTau = resultTau; + *bestAmplitude = resultAmplitude; return true; } @@ -197,7 +227,6 @@ bool BatteryParamsExtraction::analyzeCycle(batteryparams_cycle_t *cycle, battery int pauseStart = -1; int pauseEnd = -1; int relaxPosition; - int fastPosition; bool secondOrder = (model == BATTERYPARAMS_MODEL_SECOND_ORDER); double threshold = settings.relaxationThreshold / 1000.0; double window = settings.relaxationWindow * 1000.0; @@ -219,6 +248,8 @@ bool BatteryParamsExtraction::analyzeCycle(batteryparams_cycle_t *cycle, battery cycle->modelValid = false; cycle->tauFast = 0; cycle->tauSlow = 0; + cycle->fastPortionEndKey = 0; + cycle->fitEndKey = 0; cycle->r1 = 0; cycle->c1 = 0; cycle->r2 = 0; @@ -281,9 +312,10 @@ bool BatteryParamsExtraction::analyzeCycle(batteryparams_cycle_t *cycle, battery } } - /*Cell is at rest once it relaxed, so the voltage measured there is its open - circuit voltage*/ - cycle->ocv = cycle->relaxationVoltage; + /*Open circuit voltage is taken at the end of the fit interval: the relaxation + point when the fit stops there, otherwise the end of the pause. This keeps the + parameters independent of the relaxation point when the whole pause is used*/ + cycle->ocv = (settings.fitEnd == BATTERYPARAMS_FIT_END_RELAXATION) ? cycle->relaxationVoltage : cycle->plotVoltage[pauseEnd]; /*Overpotential left on the RC branches when the pulse ends, decaying to zero as the cell relaxes towards its open circuit voltage*/ @@ -292,6 +324,8 @@ bool BatteryParamsExtraction::analyzeCycle(batteryparams_cycle_t *cycle, battery cover the whole pause, so the two settings stay comparable*/ int fitEndPosition = (settings.fitEnd == BATTERYPARAMS_FIT_END_RELAXATION) ? relaxPosition : pauseEnd; + cycle->fitEndKey = cycle->plotKeys[fitEndPosition]; + for(int i = pauseStart; i <= fitEndPosition; i++) { relaxTime.append((cycle->plotKeys[i] - cycle->pauseStartKey) / 1000.0); @@ -300,127 +334,138 @@ bool BatteryParamsExtraction::analyzeCycle(batteryparams_cycle_t *cycle, battery if(relaxTime.size() < 4) return false; - /*Time constants are searched for on a logarithmic grid, with the asymptote - and the amplitudes solved by least squares for every candidate. The grid is - then narrowed around the best pair a few times to refine the result. - Settling takes about five time constants, so nothing much longer than the - relaxation itself is worth trying*/ + /*The fit is anchored at both ends: the open circuit voltage is the relaxed + voltage, and the branch amplitudes sum to the overpotential present at the + pause start, so the drawn curve always starts exactly from the pause start + point and settles on the open circuit voltage. + The slow branch is peeled from the later portion of the relaxation, where the + fast branch has already settled, and the fast branch is then fitted on the + early residual, so it is clear which portion of the signal each time constant + comes from*/ + openCircuitVoltage = cycle->ocv; + + double overpotential = openCircuitVoltage - cycle->pauseStartVoltage; + + if(fabs(overpotential) < 1e-6) return false; + { + int sampleNo = relaxTime.size(); double relaxDuration = relaxTime.last(); - double tauFastLow = relaxTime[1] - relaxTime[0]; - double tauFastHigh = relaxDuration / BATTERYPARAMS_SETTLING_TAU_NO * 2.0; - double tauSlowLow; - double tauSlowHigh; - double bestError = -1; + QVector decay(sampleNo); - if(tauFastLow <= 0) tauFastLow = relaxDuration / 1000.0; - if(tauFastHigh <= tauFastLow) tauFastHigh = tauFastLow * 10.0; + for(int i = 0; i < sampleNo; i++) + { + decay[i] = openCircuitVoltage - relaxValue[i]; + } - tauSlowLow = tauFastLow; - tauSlowHigh = tauFastHigh; + double sampleStep = relaxTime[1] - relaxTime[0]; + if(sampleStep <= 0) sampleStep = relaxDuration / sampleNo; - for(int refinement = 0; refinement < settings.tauRefinementNo; refinement++) + int splitIndex = sampleNo - 1; + for(int i = 0; i < sampleNo; i++) { - double bestTauFast = 0; - double bestTauSlow = 0; - double bestAmplitudeFast = 0; - double bestAmplitudeSlow = 0; - double bestVoltage = 0; + if(relaxTime[i] >= relaxDuration * BATTERYPARAMS_PEEL_SPLIT) + { + splitIndex = i; + break; + } + } + if(splitIndex < 1) splitIndex = 1; + if(splitIndex > sampleNo - 2) splitIndex = sampleNo - 2; + + double tauSlowValue = 0; + double amplitudeSlowValue = 0; + bool slowOk = secondOrder && + prvBATTERYPARAMS_SingleExpFit(relaxTime, decay, splitIndex, sampleNo - 1, + sampleStep, relaxDuration, settings.tauGridPoints, BATTERYPARAMS_TAU_REFINEMENT_NO, + &tauSlowValue, &litudeSlowValue); - bestError = -1; + double tauFastValue = 0; + double amplitudeFastValue = 0; + bool fastOk; - for(int fastStep = 0; fastStep < settings.tauGridPoints; fastStep++) + if(slowOk) + { + QVector residual(splitIndex); + + for(int i = 0; i < splitIndex; i++) { - double tauFastCandidate = tauFastLow * pow(tauFastHigh / tauFastLow, - (double)fastStep / (settings.tauGridPoints - 1)); - int slowSteps = secondOrder ? settings.tauGridPoints : 1; - - for(int slowStep = 0; slowStep < slowSteps; slowStep++) - { - double tauSlowCandidate = 0; - double candidateFast = 0; - double candidateSlow = 0; - double candidateVoltage = 0; - double errorSum = 0; - - if(secondOrder) - { - tauSlowCandidate = tauSlowLow * pow(tauSlowHigh / tauSlowLow, - (double)slowStep / (settings.tauGridPoints - 1)); - - /*Branches have to be clearly separated, otherwise the two - exponentials describe the same thing*/ - if(tauSlowCandidate < tauFastCandidate * settings.tauSeparation) continue; - } - - if(!prvBATTERYPARAMS_RelaxationFit(relaxTime, relaxValue, tauFastCandidate, tauSlowCandidate, - secondOrder, &candidateVoltage, &candidateFast, &candidateSlow)) - { - continue; - } - - if(candidateFast < 0) continue; - if(secondOrder && (candidateSlow < 0)) continue; - - for(int i = 0; i < relaxTime.size(); i++) - { - double fitted = candidateVoltage - candidateFast * exp(-relaxTime[i] / tauFastCandidate); - double error; - - if(secondOrder) fitted -= candidateSlow * exp(-relaxTime[i] / tauSlowCandidate); - - error = relaxValue[i] - fitted; - errorSum += error * error; - } - - if((bestError < 0) || (errorSum < bestError)) - { - bestError = errorSum; - bestTauFast = tauFastCandidate; - bestTauSlow = tauSlowCandidate; - bestAmplitudeFast = candidateFast; - bestAmplitudeSlow = candidateSlow; - bestVoltage = candidateVoltage; - } - } + residual[i] = decay[i] - amplitudeSlowValue * exp(-relaxTime[i] / tauSlowValue); } - if(bestError < 0) return false; + fastOk = prvBATTERYPARAMS_SingleExpFit(relaxTime, residual, 0, splitIndex - 1, + sampleStep, tauSlowValue / settings.tauSeparation, + settings.tauGridPoints, BATTERYPARAMS_TAU_REFINEMENT_NO, + &tauFastValue, &litudeFastValue); + } + else + { + fastOk = prvBATTERYPARAMS_SingleExpFit(relaxTime, decay, 0, sampleNo - 1, + sampleStep, relaxDuration, settings.tauGridPoints, BATTERYPARAMS_TAU_REFINEMENT_NO, + &tauFastValue, &litudeFastValue); + secondOrder = false; + } + + (void)amplitudeFastValue; - cycle->tauFast = bestTauFast; - cycle->tauSlow = bestTauSlow; - amplitudeFast = bestAmplitudeFast; - amplitudeSlow = bestAmplitudeSlow; - openCircuitVoltage = bestVoltage; + if(!fastOk) return false; - tauFastLow = bestTauFast / BATTERYPARAMS_TAU_REFINEMENT_SPAN; - tauFastHigh = bestTauFast * BATTERYPARAMS_TAU_REFINEMENT_SPAN; + if(secondOrder && (tauSlowValue <= tauFastValue)) + { + secondOrder = false; + } + + cycle->tauFast = tauFastValue; + cycle->tauSlow = secondOrder ? tauSlowValue : 0; + + if(secondOrder) + { + /*Amplitudes are re-solved under the constraint that they sum to the + overpotential, so the curve is pinned to the pause start voltage*/ + double numerator = 0; + double denominator = 0; - if(secondOrder) + for(int i = 0; i < sampleNo; i++) { - tauSlowLow = bestTauSlow / BATTERYPARAMS_TAU_REFINEMENT_SPAN; - tauSlowHigh = bestTauSlow * BATTERYPARAMS_TAU_REFINEMENT_SPAN; + double basisFast = exp(-relaxTime[i] / cycle->tauFast); + double basisSlow = exp(-relaxTime[i] / cycle->tauSlow); + double difference = basisFast - basisSlow; + + numerator += (decay[i] - overpotential * basisSlow) * difference; + denominator += difference * difference; } + + amplitudeFast = (denominator > 0) ? (numerator / denominator) : overpotential; + + if((overpotential > 0) && (amplitudeFast < 0)) amplitudeFast = 0; + if((overpotential < 0) && (amplitudeFast > 0)) amplitudeFast = 0; + if(fabs(amplitudeFast) > fabs(overpotential)) amplitudeFast = overpotential; + + amplitudeSlow = overpotential - amplitudeFast; + } + else + { + amplitudeFast = overpotential; + amplitudeSlow = 0; } - } - if(secondOrder && (cycle->tauSlow <= cycle->tauFast)) - { - secondOrder = false; - cycle->model = BATTERYPARAMS_MODEL_FIRST_ORDER; - cycle->tauSlow = 0; - amplitudeSlow = 0; + double boundaryTime = BATTERYPARAMS_PEEL_BOUNDARY_TAU * cycle->tauFast; + + if(secondOrder && (boundaryTime > relaxTime[splitIndex])) boundaryTime = relaxTime[splitIndex]; + if(boundaryTime > relaxDuration) boundaryTime = relaxDuration; + + cycle->fastPortionEndKey = cycle->pauseStartKey + boundaryTime * 1000.0; } - /*Overpotential left on the RC branches when the pulse ends, decaying to zero - as the cell relaxes towards its open circuit voltage*/ + cycle->model = secondOrder ? BATTERYPARAMS_MODEL_SECOND_ORDER : BATTERYPARAMS_MODEL_FIRST_ORDER; + + /*During the pulse each branch charges towards I*R, so the amplitude seen at the + beginning of the relaxation is scaled by how far it got*/ pulseDuration = (cycle->pulseEndKey - cycle->pulseStartKey) / 1000.0; pulseCurrent = cycle->pulseEndCurrent / 1000.0; if((pulseDuration <= 0) || (fabs(pulseCurrent) < 1e-9)) return false; - /*During the pulse each branch charges towards I*R, so the amplitude seen at - the beginning of the relaxation is scaled by how far it got*/ double chargedFast = 1.0 - exp(-pulseDuration / cycle->tauFast); if(chargedFast <= 0) return false; @@ -496,6 +541,7 @@ void BatteryParamsExtraction::cycleReset() activeCycle.soc = 0; activeCycle.resistanceValid = false; activeCycle.socValid = false; + activeCycle.incomplete = false; activeCycle.relaxationReached = false; activeCycle.relaxationKey = 0; activeCycle.relaxationVoltage = 0; @@ -702,6 +748,43 @@ bool BatteryParamsExtraction::cyclePointsFit(batteryparams_cycle_t *cycle) return true; } +/*Moves the pause start onto the sample at or after the given key and recomputes the + series resistance from the new pause start. Pulse end stays where it is, so the + instantaneous step the resistance is read from is measured against the new pause + start. The RC fit is left to analyzeCycle, which reads the updated pause start*/ +bool BatteryParamsExtraction::setPauseStart(batteryparams_cycle_t *cycle, double pauseStartKey) +{ + int position = -1; + + if(cycle == NULL) return false; + if(cycle->plotKeys.size() != cycle->plotVoltage.size()) return false; + if(cycle->plotKeys.size() != cycle->plotCurrent.size()) return false; + + for(int i = 0; i < cycle->plotKeys.size(); i++) + { + if(cycle->plotKeys[i] >= pauseStartKey) + { + position = i; + break; + } + } + + if(position < 0) return false; + if(cycle->plotKeys[position] <= cycle->pulseEndKey) return false; + if(cycle->plotKeys[position] >= cycle->pauseEndKey) return false; + + cycle->pauseStartKey = cycle->plotKeys[position]; + cycle->pauseStartVoltage = cycle->plotVoltage[position]; + cycle->pauseStartCurrent = cycle->plotCurrent[position]; + + cycle->deltaVoltage = cycle->pauseStartVoltage - cycle->pulseEndVoltage; + cycle->deltaCurrent = cycle->pulseEndCurrent - cycle->pauseStartCurrent; + cycle->resistanceValid = fabs(cycle->deltaCurrent) > 0.000001; + cycle->resistance = cycle->resistanceValid ? cycle->deltaVoltage / (cycle->deltaCurrent / 1000.0) : 0; + + return true; +} + void BatteryParamsExtraction::seriesSmooth(const QVector &keys, const QVector &values, double window, QVector *smoothed) { @@ -847,10 +930,9 @@ void BatteryParamsExtraction::processPendingMarkers() { double markerKey; - if(samplingPeriod <= 0) return; if(keySamples.isEmpty()) return; - markerKey = pendingMarkers.first().key * samplingPeriod; + markerKey = pendingMarkers.first().key; if(markerKey > keySamples.last()) return; @@ -877,6 +959,7 @@ void BatteryParamsExtraction::processMarker(QString name, int position) if(name == pulseStartMarker) { + if(captureIncomplete && cycleActive) finalizeIncompleteCycle(key); cycleReset(); cycleActive = true; cycleCounter++; diff --git a/Source/Processing/batteryparamsextraction.h b/Source/Processing/batteryparamsextraction.h index 98ec8b3..03b9b7d 100644 --- a/Source/Processing/batteryparamsextraction.h +++ b/Source/Processing/batteryparamsextraction.h @@ -20,6 +20,10 @@ #define BATTERYPARAMS_TAU_SEPARATION 3.0 #define BATTERYPARAMS_TAU_REFINEMENT_NO 3 #define BATTERYPARAMS_TAU_REFINEMENT_SPAN 1.6 +#define BATTERYPARAMS_PEEL_SPLIT 0.4 +#define BATTERYPARAMS_PEEL_BOUNDARY_TAU 3.0 +#define BATTERYPARAMS_START_SWEEP_WINDOW 5000.0 +#define BATTERYPARAMS_START_SWEEP_MAX_STEPS 40 #define BATTERYPARAMS_INITIAL_SOC_DEFAULT 100.0 #define BATTERYPARAMS_CYCLE_PLOT_STEP_WINDOW 50.0 @@ -43,7 +47,6 @@ typedef struct batteryparams_model_t model; batteryparams_fit_end_t fitEnd; int tauGridPoints; - int tauRefinementNo; double tauSeparation; double capacity; double initialSoc; @@ -81,10 +84,14 @@ typedef struct double relaxationVoltage; double ocv; + bool incomplete; + batteryparams_model_t model; bool modelValid; double tauFast; double tauSlow; + double fastPortionEndKey; + double fitEndKey; double r1; double c1; double r2; @@ -105,6 +112,16 @@ typedef struct Q_DECLARE_METATYPE(batteryparams_cycle_t); +typedef struct +{ + unsigned int index; + double startKey; + double endKey; + double capacity; +}batteryparams_charge_cycle_t; + +Q_DECLARE_METATYPE(batteryparams_charge_cycle_t); + class BatteryParamsExtraction : public QObject { Q_OBJECT @@ -115,6 +132,8 @@ class BatteryParamsExtraction : public QObject void setSamplingPeriod(double aSamplingPeriod); void setSettings(batteryparams_settings_t aSettings); void setAnalysisDeferred(bool aDeferred); + void setCaptureIncomplete(bool aCapture); + void flushIncompleteCycle(); batteryparams_settings_t getSettings(); static batteryparams_settings_t settingsDefault(); @@ -122,6 +141,7 @@ class BatteryParamsExtraction : public QObject static int relaxationPositionGet(const QVector &keys, const QVector &voltage, int start, int end, double threshold, double window); static bool cyclePointsFit(batteryparams_cycle_t *cycle); + static bool setPauseStart(batteryparams_cycle_t *cycle, double pauseStartKey); static void seriesSmooth(const QVector &keys, const QVector &values, double window, QVector *smoothed); QVector getCycles(); @@ -153,6 +173,7 @@ public slots: double samplingPeriod; batteryparams_settings_t settings; bool analysisDeferred; + bool captureIncomplete; double chargeTotal; QVector pendingMarkers; @@ -167,6 +188,7 @@ public slots: void processMarker(QString name, int position); void trimSamples(double key); void storeCycleSamples(); + void finalizeIncompleteCycle(double pauseEndKey); void cycleReset(); }; diff --git a/Source/Processing/fileprocessing.cpp b/Source/Processing/fileprocessing.cpp index fb0bd35..28e2793 100644 --- a/Source/Processing/fileprocessing.cpp +++ b/Source/Processing/fileprocessing.cpp @@ -164,6 +164,7 @@ bool FileProcessing::appendSummaryFile(QString content) bool FileProcessing::appendSampleData(QVector* voltage, QVector* voltageKeys, QVector* current, QVector* currentKeys) { + if(samplesFile == NULL) return false; if(!samplesFile->isOpen()) { if(!samplesFile->open(QIODevice::WriteOnly | QIODevice::Text| QIODevice::Append)) return false; @@ -172,10 +173,10 @@ bool FileProcessing::appendSampleData(QVector* voltage, QVector* //TODO: Check QVectors sizes; for(unsigned int i = 0; i < voltage->size(); i++) { - out << QString::asprintf("%1.5f", voltage->at(i)) << ","; - out << QString::asprintf("%1.7f", voltageKeys->at(i)) << ","; - out << QString::asprintf("%1.5f", current->at(i)) << ","; - out << QString::asprintf("%1.7f", currentKeys->at(i)) << "\n"; + out << QString::asprintf("%1.5f", voltage->at(i)) << ","; + out << QString::asprintf("%1.7f", voltageKeys->at(i)) << ","; + out << QString::asprintf("%1.5f", current->at(i)) << ","; + out << QString::asprintf("%1.7f", currentKeys->at(i)) << "\n"; } samplesFile->close(); return true; @@ -183,6 +184,7 @@ bool FileProcessing::appendSampleData(QVector* voltage, QVector* bool FileProcessing::appendConsumptionData(QVector *consumption, QVector *consumptionKeys) { + if(consumptionFile == NULL) return false; if(!consumptionFile->isOpen()) { if(!consumptionFile->open(QIODevice::WriteOnly | QIODevice::Text| QIODevice::Append)) return false; @@ -200,6 +202,7 @@ bool FileProcessing::appendConsumptionData(QVector *consumption, QVector bool FileProcessing::appendEPData(QString name, int key) { + if(epFile == NULL) return false; if(!epFile->isOpen()) { if(!epFile->open(QIODevice::WriteOnly | QIODevice::Text| QIODevice::Append)) return false; diff --git a/Source/Processing/waveform.cpp b/Source/Processing/waveform.cpp index bf17776..1533abe 100644 --- a/Source/Processing/waveform.cpp +++ b/Source/Processing/waveform.cpp @@ -18,6 +18,12 @@ Waveform::Waveform() amplitude = 0; period = 0; points = 0; + batParam = false; + batCapacity = 0; + batRelaxAdaptive = false; + batRelaxThreshold = 0; + batRelaxWindow = 0; + batRelaxFilter = 0; } bool Waveform::isValid() @@ -367,6 +373,31 @@ QJsonObject Waveform::toJson() obj["amplitude"] = (int)amplitude; obj["period"] = (int)period; obj["points"] = (int)points; + obj["batParam"] = batParam; + if(batParam) + { + obj["batCapacity"] = batCapacity; + obj["batRelaxAdaptive"] = batRelaxAdaptive; + obj["batRelaxThreshold"] = batRelaxThreshold; + obj["batRelaxWindow"] = batRelaxWindow; + obj["batRelaxFilter"] = batRelaxFilter; + + QJsonArray regionsArray; + for(int i = 0; i < batRegions.size(); i++) + { + QJsonObject regionObj; + regionObj["socHigh"] = batRegions[i].socHigh; + regionObj["socLow"] = batRegions[i].socLow; + regionObj["accuracy"] = batRegions[i].accuracy; + regionObj["amplitude"] = batRegions[i].amplitude; + regionObj["pause"] = batRegions[i].pause; + regionObj["relaxThreshold"] = batRegions[i].relaxThreshold; + regionObj["relaxWindow"] = batRegions[i].relaxWindow; + regionObj["relaxFilter"] = batRegions[i].relaxFilter; + regionsArray.append(regionObj); + } + obj["batRegions"] = regionsArray; + } for(int i = 0; i < chunks.size(); i++) { QJsonObject chunkObj; @@ -395,6 +426,30 @@ bool Waveform::fromJson(QJsonObject obj) amplitude = obj["amplitude"].toInt(); period = obj["period"].toInt(); points = obj["points"].toInt(); + batParam = obj["batParam"].toBool(false); + batCapacity = obj["batCapacity"].toDouble(0); + batRelaxAdaptive = obj["batRelaxAdaptive"].toBool(false); + batRelaxThreshold = obj["batRelaxThreshold"].toDouble(0); + batRelaxWindow = obj["batRelaxWindow"].toDouble(0); + batRelaxFilter = obj["batRelaxFilter"].toDouble(0); + batRegions.clear(); + { + QJsonArray regionsArray = obj["batRegions"].toArray(); + for(int i = 0; i < regionsArray.size(); i++) + { + QJsonObject regionObj = regionsArray[i].toObject(); + waveform_batregion_t region; + region.socHigh = regionObj["socHigh"].toDouble(0); + region.socLow = regionObj["socLow"].toDouble(0); + region.accuracy = regionObj["accuracy"].toDouble(0); + region.amplitude = regionObj["amplitude"].toDouble(0); + region.pause = regionObj["pause"].toDouble(0); + region.relaxThreshold = regionObj["relaxThreshold"].toDouble(0); + region.relaxWindow = regionObj["relaxWindow"].toDouble(0); + region.relaxFilter = regionObj["relaxFilter"].toDouble(0); + batRegions.append(region); + } + } chunks.clear(); for(int i = 0; i < chunksArray.size(); i++) { diff --git a/Source/Processing/waveform.h b/Source/Processing/waveform.h index 81286d7..c1fb22f 100644 --- a/Source/Processing/waveform.h +++ b/Source/Processing/waveform.h @@ -39,6 +39,18 @@ typedef struct QString markerPos; }waveform_chunk_t; +typedef struct +{ + double socHigh; + double socLow; + double accuracy; + double amplitude; + double pause; + double relaxThreshold; + double relaxWindow; + double relaxFilter; +}waveform_batregion_t; + class Waveform { public: @@ -79,6 +91,14 @@ class Waveform unsigned int amplitude; unsigned int period; unsigned int points; + + bool batParam; + double batCapacity; + bool batRelaxAdaptive; + double batRelaxThreshold; + double batRelaxWindow; + double batRelaxFilter; + QList batRegions; }; class WaveformLibrary : public QObject diff --git a/Source/Windows/BatteryParams/batterycyclewnd.cpp b/Source/Windows/BatteryParams/batterycyclewnd.cpp index 2fccd7e..c455d75 100644 --- a/Source/Windows/BatteryParams/batterycyclewnd.cpp +++ b/Source/Windows/BatteryParams/batterycyclewnd.cpp @@ -22,6 +22,8 @@ BatteryCycleWnd::BatteryCycleWnd(QWidget *parent) : setFont(defaultFont); setWindowTitle("Battery cycle"); + fitSettings = BatteryParamsExtraction::settingsDefault(); + infoLabel = new QLabel(this); mainLayout->addWidget(infoLabel); @@ -208,13 +210,24 @@ void BatteryCycleWnd::refreshMarkerEdits() pauseEndEdit->setText(QString::number(cycle.pauseEndKey / timeScale(), 'f', timeDecimals())); } +void BatteryCycleWnd::setSettings(batteryparams_settings_t settings) +{ + fitSettings = settings; +} + void BatteryCycleWnd::onFitPoints() { if(!BatteryParamsExtraction::cyclePointsFit(&cycle)) return; + cycle.incomplete = false; + + BatteryParamsExtraction::analyzeCycle(&cycle, fitSettings); + refreshMarkerEdits(); updateInfo(); updatePlots(); + + emit sigCycleUpdated(cycle); } void BatteryCycleWnd::onRestore() @@ -254,6 +267,8 @@ void BatteryCycleWnd::applyMarkers() cycle.resistanceValid = fabs(cycle.deltaCurrent) > 0.000001; cycle.resistance = cycle.resistanceValid ? cycle.deltaVoltage / (cycle.deltaCurrent / 1000.0) : 0; + BatteryParamsExtraction::analyzeCycle(&cycle, fitSettings); + refreshMarkerEdits(); updateInfo(); @@ -340,6 +355,7 @@ void BatteryCycleWnd::updatePlots() voltagePlot->markersAtKeyClear(); currentPlot->markersAtKeyClear(); voltagePlot->overlayClear(); + voltagePlot->shadeClear(); QVector scaledKeys; @@ -380,6 +396,22 @@ void BatteryCycleWnd::updatePlots() } voltagePlot->overlaySetData(cycle.fitVoltage, scaledFitKeys); + + /*Shade the portion of the relaxation each time constant was peeled from: + the early part feeds the fast branch, the later part the slow branch*/ + if(cycle.relaxationReached && (cycle.fastPortionEndKey > cycle.pauseStartKey)) + { + double fastStart = cycle.pauseStartKey / timeScale(); + double fastEnd = cycle.fastPortionEndKey / timeScale(); + double slowEnd = (cycle.fitEndKey > 0 ? cycle.fitEndKey : cycle.relaxationKey) / timeScale(); + + voltagePlot->shadeKeyRange(fastStart, fastEnd, QColor(80, 140, 255, 45)); + + if((cycle.model == BATTERYPARAMS_MODEL_SECOND_ORDER) && (slowEnd > fastEnd)) + { + voltagePlot->shadeKeyRange(fastEnd, slowEnd, QColor(255, 160, 60, 40)); + } + } } if(!cycle.plotKeys.isEmpty()) diff --git a/Source/Windows/BatteryParams/batterycyclewnd.h b/Source/Windows/BatteryParams/batterycyclewnd.h index a490a16..f9dbb82 100644 --- a/Source/Windows/BatteryParams/batterycyclewnd.h +++ b/Source/Windows/BatteryParams/batterycyclewnd.h @@ -22,6 +22,7 @@ class BatteryCycleWnd : public QWidget void setCycle(batteryparams_cycle_t aCycle); void setPlotSettings(batteryparams_plot_settings_t settings); + void setSettings(batteryparams_settings_t settings); signals: void sigCycleUpdated(batteryparams_cycle_t cycle); @@ -51,6 +52,7 @@ private slots: QStringList markerNames; batteryparams_plot_settings_t plotSettings; + batteryparams_settings_t fitSettings; batteryparams_cycle_t cycle; batteryparams_cycle_t originalCycle; diff --git a/Source/Windows/BatteryParams/batteryparamssettingsdlg.cpp b/Source/Windows/BatteryParams/batteryparamssettingsdlg.cpp index 2e569ec..426a10b 100644 --- a/Source/Windows/BatteryParams/batteryparamssettingsdlg.cpp +++ b/Source/Windows/BatteryParams/batteryparamssettingsdlg.cpp @@ -66,9 +66,7 @@ BatteryParamsSettingsDlg::BatteryParamsSettingsDlg(QWidget *parent) : tauGridPointsEdit = createEntry(extractionLayout, 2, "Tau search points", "", "Number of candidate time constants tried per decade of the search range.\nMore points give a finer fit and take longer"); - tauRefinementEdit = createEntry(extractionLayout, 3, "Tau refinement steps", "", - "How many times the search range is narrowed around the best result"); - tauSeparationEdit = createEntry(extractionLayout, 4, "Tau separation", "x", + tauSeparationEdit = createEntry(extractionLayout, 3, "Tau separation", "x", "Smallest allowed ratio between the slow and the fast time constant.\nBranches closer than this describe the same effect"); QTabWidget *tabWidget = new QTabWidget(this); @@ -140,6 +138,16 @@ BatteryParamsSettingsDlg::BatteryParamsSettingsDlg(QWidget *parent) : setPlotSettings(BATTERYPARAMSPLOT_SettingsDefault()); } +void BatteryParamsSettingsDlg::setExtractionRunning(bool running) +{ + bool editable = !running; + + relaxationThresholdEdit->setEnabled(editable); + relaxationWindowEdit->setEnabled(editable); + relaxationFilterEdit->setEnabled(editable); + fitEndCombo->setEnabled(editable); +} + QLineEdit* BatteryParamsSettingsDlg::createEntry(QGridLayout *layout, int row, QString name, QString unit, QString tooltip) { QLabel *label = new QLabel(name, this); @@ -168,7 +176,6 @@ void BatteryParamsSettingsDlg::setSettings(batteryparams_settings_t settings) modelCombo->setCurrentIndex(settings.model == BATTERYPARAMS_MODEL_FIRST_ORDER ? 0 : 1); fitEndCombo->setCurrentIndex(settings.fitEnd == BATTERYPARAMS_FIT_END_RELAXATION ? 0 : 1); tauGridPointsEdit->setText(QString::number(settings.tauGridPoints)); - tauRefinementEdit->setText(QString::number(settings.tauRefinementNo)); tauSeparationEdit->setText(QString::number(settings.tauSeparation)); } @@ -222,7 +229,6 @@ batteryparams_settings_t BatteryParamsSettingsDlg::getSettings() if(relaxationFilterEdit->text().toDouble() >= 0) settings.relaxationFilter = relaxationFilterEdit->text().toDouble(); if(plotDecimationEdit->text().toInt() > 0) settings.plotDecimation = plotDecimationEdit->text().toInt(); if(tauGridPointsEdit->text().toInt() > 1) settings.tauGridPoints = tauGridPointsEdit->text().toInt(); - if(tauRefinementEdit->text().toInt() > 0) settings.tauRefinementNo = tauRefinementEdit->text().toInt(); if(tauSeparationEdit->text().toDouble() > 1) settings.tauSeparation = tauSeparationEdit->text().toDouble(); settings.model = (modelCombo->currentIndex() == 0) ? BATTERYPARAMS_MODEL_FIRST_ORDER : BATTERYPARAMS_MODEL_SECOND_ORDER; diff --git a/Source/Windows/BatteryParams/batteryparamssettingsdlg.h b/Source/Windows/BatteryParams/batteryparamssettingsdlg.h index 1697a52..4f927c4 100644 --- a/Source/Windows/BatteryParams/batteryparamssettingsdlg.h +++ b/Source/Windows/BatteryParams/batteryparamssettingsdlg.h @@ -25,6 +25,8 @@ class BatteryParamsSettingsDlg : public QDialog void setPlotSettings(batteryparams_plot_settings_t settings); batteryparams_plot_settings_t getPlotSettings(); + void setExtractionRunning(bool running); + private: QLineEdit *capacityEdit; QLineEdit *initialSocEdit; @@ -35,7 +37,6 @@ class BatteryParamsSettingsDlg : public QDialog QComboBox *modelCombo; QComboBox *fitEndCombo; QLineEdit *tauGridPointsEdit; - QLineEdit *tauRefinementEdit; QLineEdit *tauSeparationEdit; QFontComboBox *plotFontCombo; diff --git a/Source/Windows/BatteryParams/batteryparamswnd.cpp b/Source/Windows/BatteryParams/batteryparamswnd.cpp index 316e3c5..45160d5 100644 --- a/Source/Windows/BatteryParams/batteryparamswnd.cpp +++ b/Source/Windows/BatteryParams/batteryparamswnd.cpp @@ -7,13 +7,24 @@ #include #include #include +#include +#include +#include +#include +#include #include + +#include "Chart/qcustomplot.h" #include #include #include #include +#include +#include +#include +#include -#define BATTERYPARAMS_COLUMN_NO 21 +#define BATTERYPARAMS_COLUMN_NO 22 #define BATTERYPARAMS_SETTINGS_EDIT_WIDTH 80 #define BATTERYPARAMS_SETTINGS_ROW_HEIGHT 28 #define BATTERYPARAMS_AUTO_RESIZE_ROW_NO 10 @@ -41,6 +52,8 @@ BatteryParamsWnd::BatteryParamsWnd(QWidget *parent) : settings = BatteryParamsExtraction::settingsDefault(); parallelAnswer = -1; settingsDlg = NULL; + extractionRunning = false; + fitInProgress = false; resistanceTrendWnd = NULL; capacitanceTrendWnd = NULL; ocvTrendWnd = NULL; @@ -55,6 +68,10 @@ BatteryParamsWnd::BatteryParamsWnd(QWidget *parent) : settingsButton->setFixedHeight(BATTERYPARAMS_SETTINGS_ROW_HEIGHT); settingsButton->setToolTip("Battery capacity, initial state of charge, relaxation and extraction settings"); + statisticsButton = new QPushButton("Statistics", this); + statisticsButton->setFixedHeight(BATTERYPARAMS_SETTINGS_ROW_HEIGHT); + statisticsButton->setToolTip("Charge and discharge capacity and other summary figures"); + resistanceTrendButton = new QPushButton("R vs SoC", this); resistanceTrendButton->setFixedHeight(BATTERYPARAMS_SETTINGS_ROW_HEIGHT); resistanceTrendButton->setToolTip("Show R0, R1 and R2 against the state of charge"); @@ -95,10 +112,19 @@ BatteryParamsWnd::BatteryParamsWnd(QWidget *parent) : fitPointsRestoreButton->setFixedHeight(BATTERYPARAMS_SETTINGS_ROW_HEIGHT); fitPointsRestoreButton->setToolTip("Return every corrected cycle to the points reported by the device"); + fitPointsFindStartButton = new QPushButton("Find new start point", this); + fitPointsFindStartButton->setFixedHeight(BATTERYPARAMS_SETTINGS_ROW_HEIGHT); + fitPointsFindStartButton->setToolTip("Sweep the pause start of every cycle over a short window and show the\nminimum RMSE and the minimum maximum error reachable.\nThen apply the pause start by the chosen criterion to all cycles"); + + recalculateButton = new QPushButton("Recalculate", this); + recalculateButton->setFixedHeight(BATTERYPARAMS_SETTINGS_ROW_HEIGHT); + recalculateButton->setToolTip("Force a fresh re-analysis of every cycle with the current settings and points"); + settingsLabel = new QLabel(this); settingsLabel->setStyleSheet("color: gray;"); settingsLayout->addWidget(settingsButton); + settingsLayout->addWidget(statisticsButton); settingsLayout->addSpacing(15); settingsLayout->addWidget(resistanceTrendButton); settingsLayout->addWidget(capacitanceTrendButton); @@ -111,11 +137,26 @@ BatteryParamsWnd::BatteryParamsWnd(QWidget *parent) : settingsLayout->addWidget(fitPointsButton); settingsLayout->addWidget(fitPointsSaveButton); settingsLayout->addWidget(fitPointsRestoreButton); + settingsLayout->addWidget(fitPointsFindStartButton); + settingsLayout->addWidget(recalculateButton); settingsLayout->addSpacing(15); settingsLayout->addWidget(settingsLabel, 1); - mainLayout->addLayout(settingsLayout); + + QWidget *settingsBar = new QWidget(this); + settingsLayout->setContentsMargins(0, 0, 0, 0); + settingsBar->setLayout(settingsLayout); + + QScrollArea *settingsScroll = new QScrollArea(this); + settingsScroll->setWidget(settingsBar); + settingsScroll->setWidgetResizable(true); + settingsScroll->setFrameShape(QFrame::NoFrame); + settingsScroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); + settingsScroll->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + settingsScroll->setFixedHeight(BATTERYPARAMS_SETTINGS_ROW_HEIGHT + 18); + mainLayout->addWidget(settingsScroll); connect(settingsButton, &QPushButton::clicked, this, &BatteryParamsWnd::onSettings); + connect(statisticsButton, &QPushButton::clicked, this, &BatteryParamsWnd::onStatistics); connect(resistanceTrendButton, &QPushButton::clicked, this, &BatteryParamsWnd::onResistanceTrend); connect(capacitanceTrendButton, &QPushButton::clicked, this, &BatteryParamsWnd::onCapacitanceTrend); connect(ocvTrendButton, &QPushButton::clicked, this, &BatteryParamsWnd::onOcvTrend); @@ -126,6 +167,8 @@ BatteryParamsWnd::BatteryParamsWnd(QWidget *parent) : connect(fitPointsButton, &QPushButton::clicked, this, &BatteryParamsWnd::onFitCyclePoints); connect(fitPointsSaveButton, &QPushButton::clicked, this, &BatteryParamsWnd::onFitPointsSave); connect(fitPointsRestoreButton, &QPushButton::clicked, this, &BatteryParamsWnd::onFitPointsRestore); + connect(fitPointsFindStartButton, &QPushButton::clicked, this, &BatteryParamsWnd::onFindNewStartPoint); + connect(recalculateButton, &QPushButton::clicked, this, &BatteryParamsWnd::recalculate); updateSettingsLabel(); updateFitPointsButtons(); @@ -136,7 +179,7 @@ BatteryParamsWnd::BatteryParamsWnd(QWidget *parent) : << "I pulse end [mA]" << "I pause start [mA]" << "dI [mA]" << "R0 [mOhm]" << "R1 [mOhm]" << "C1 [F]" << "R2 [mOhm]" << "C2 [F]" - << "RMSE [mV]" << "Max err [mV]"; + << "RMSE [mV]" << "Max err [mV]" << "Rtotal [mOhm]"; cyclesTable = new QTableWidget(0, BATTERYPARAMS_COLUMN_NO, this); cyclesTable->setHorizontalHeaderLabels(header); @@ -150,26 +193,53 @@ BatteryParamsWnd::BatteryParamsWnd(QWidget *parent) : cyclesTable->setSelectionBehavior(QAbstractItemView::SelectRows); cyclesTable->setEditTriggers(QAbstractItemView::NoEditTriggers); cyclesTable->setMinimumHeight(200); - mainLayout->addWidget(cyclesTable, 1); + + QStringList chargeHeader; + chargeHeader << "Charge cycle" << "Start [ms]" << "End [ms]" << "Capacity [mAh]"; + chargeCyclesTable = new QTableWidget(0, chargeHeader.size(), this); + chargeCyclesTable->setHorizontalHeaderLabels(chargeHeader); + chargeCyclesTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive); + chargeCyclesTable->horizontalHeader()->setStretchLastSection(true); + chargeCyclesTable->horizontalHeader()->setMinimumSectionSize(40); + chargeCyclesTable->resizeColumnsToContents(); + chargeCyclesTable->verticalHeader()->setVisible(false); + chargeCyclesTable->verticalHeader()->setDefaultSectionSize(22); + chargeCyclesTable->setSelectionBehavior(QAbstractItemView::SelectRows); + chargeCyclesTable->setEditTriggers(QAbstractItemView::NoEditTriggers); + chargeCyclesTable->setMinimumHeight(200); + + cycleTabs = new QTabWidget(this); + cycleTabs->addTab(cyclesTable, "Discharge"); + cycleTabs->addTab(chargeCyclesTable, "Charge"); + mainLayout->addWidget(cycleTabs, 1); summaryLabel = new QLabel(this); summaryLabel->setStyleSheet("color: gray;"); bottomLayout->addWidget(summaryLabel, 1); + saveCyclesButton = new QPushButton("Save New Cycles", this); + saveCyclesButton->setToolTip("Remove the deleted cycles from the table and update ep.csv so the removal, fitted points and new cycles are saved (voltage and current recording is kept)"); + storeCyclesButton = new QPushButton("Store New Points", this); + storeCyclesButton->setToolTip("Write the current pulse/pause points of every cycle into ep.csv and refresh the main plot (offline profile)"); exportButton = new QPushButton("Export CSV", this); clearButton = new QPushButton("Clear", this); + bottomLayout->addWidget(saveCyclesButton); + bottomLayout->addWidget(storeCyclesButton); bottomLayout->addWidget(exportButton); bottomLayout->addWidget(clearButton); mainLayout->addLayout(bottomLayout); - cyclesTable->setToolTip("Click a cycle to show its waveform.\nColumns can be resized and reordered by dragging the header"); + cyclesTable->setToolTip("Right-click a cycle for options (show data, delete, fit points).\nColumns can be resized and reordered by dragging the header"); cycleWnd = NULL; fittedPositions.clear(); fittedOriginals.clear(); connectedToCycleWnd = false; - connect(cyclesTable, &QTableWidget::cellClicked, this, &BatteryParamsWnd::onCycleSelected); + cyclesTable->setContextMenuPolicy(Qt::CustomContextMenu); + connect(cyclesTable, &QTableWidget::customContextMenuRequested, this, &BatteryParamsWnd::onCycleContextMenu); + connect(saveCyclesButton, &QPushButton::clicked, this, &BatteryParamsWnd::onSaveNewCycles); + connect(storeCyclesButton, &QPushButton::clicked, this, &BatteryParamsWnd::onStoreNewPoints); connect(exportButton, &QPushButton::clicked, this, &BatteryParamsWnd::onExport); connect(clearButton, &QPushButton::clicked, this, &BatteryParamsWnd::onClear); @@ -192,7 +262,10 @@ QTableWidgetItem* BatteryParamsWnd::createItem(QString text) void BatteryParamsWnd::fillCycleRow(int row, batteryparams_cycle_t cycle) { - cyclesTable->setItem(row, 0, createItem(QString::number(cycle.index) + (fittedPositions.contains(row) ? " *" : ""))); + QString cycleText = QString::number(cycle.index); + if(cycle.incomplete) cycleText += " (inc)"; + if(fittedPositions.contains(row)) cycleText += " *"; + cyclesTable->setItem(row, 0, createItem(cycleText)); cyclesTable->setItem(row, 1, createItem(QString::number(cycle.pulseStartKey, 'f', 3))); cyclesTable->setItem(row, 2, createItem(QString::number(cycle.pauseEndKey, 'f', 3))); cyclesTable->setItem(row, 3, createItem(QString::number(cycle.charge, 'f', 3))); @@ -214,9 +287,14 @@ void BatteryParamsWnd::fillCycleRow(int row, batteryparams_cycle_t cycle) cyclesTable->setItem(row, 19, createItem(cycle.modelValid ? QString::number(cycle.fitRmse * 1000.0, 'f', 3) : "-")); cyclesTable->setItem(row, 20, createItem(cycle.modelValid ? QString::number(cycle.fitMaxError * 1000.0, 'f', 3) : "-")); - /*Green marks a cycle where the cell relaxed and the model could be fitted, - yellow one where it did not*/ - QColor rowColor = cycle.relaxationReached ? QColor(200, 240, 200) : QColor(255, 245, 190); + double rTotal = cycle.resistance + (cycle.modelValid ? cycle.r1 + ((cycle.model == BATTERYPARAMS_MODEL_SECOND_ORDER) ? cycle.r2 : 0.0) : 0.0); + cyclesTable->setItem(row, 21, createItem((cycle.resistanceValid && cycle.modelValid) ? QString::number(rTotal * 1000.0, 'f', 2) : "-")); + + /*Light purple marks a discharge cycle where the cell relaxed and the model + could be fitted, yellow one where it did not, light red an incomplete cycle*/ + QColor rowColor; + if(cycle.incomplete) rowColor = QColor(255, 210, 210); + else rowColor = cycle.relaxationReached ? QColor(226, 212, 240) : QColor(255, 245, 190); for(int column = 0; column < BATTERYPARAMS_COLUMN_NO; column++) { @@ -245,9 +323,12 @@ void BatteryParamsWnd::updateSummary() { double sum = 0; int validNo = 0; + double totalCharge = 0; for(int i = 0; i < cycles.size(); i++) { + totalCharge += cycles[i].charge; + if(!cycles[i].resistanceValid) continue; sum += cycles[i].resistance; validNo++; @@ -255,12 +336,13 @@ void BatteryParamsWnd::updateSummary() if(validNo == 0) { - summaryLabel->setText(QString::number(cycles.size()) + " cycles, no resistance calculated yet"); + summaryLabel->setText(QString::number(cycles.size()) + " cycles, " + + QString::number(totalCharge, 'f', 3) + " mAh extracted, no resistance calculated yet"); return; } summaryLabel->setText(QString::number(cycles.size()) + " cycles, " + - QString::number(cycles.last().chargeTotal, 'f', 3) + " mAh extracted" + + QString::number(totalCharge, 'f', 3) + " mAh extracted" + (cycles.last().socValid ? ", " + QString::number(cycles.last().socUsed, 'f', 2) + " % SoC used" : "") + ", average resistance " + QString::number(sum / validNo * 1000.0, 'f', 2) + " mOhm"); } @@ -279,22 +361,109 @@ void BatteryParamsWnd::addCycles(QVector newCycles, QProg void BatteryParamsWnd::onCycleStarted(unsigned int index, double key) { + if(fitInProgress) return; statusLabel->setText("Cycle " + QString::number(index) + " ongoing (started at " + QString::number(key, 'f', 3) + " ms)"); } void BatteryParamsWnd::onCycleFinished(batteryparams_cycle_t cycle) { + if(fitInProgress) + { + pendingCycles.append(cycle); + return; + } + cycles.append(cycle); addCycleRow(cycle); updateSummary(); statusLabel->setText("Cycle " + QString::number(cycle.index) + " done, waiting for the next one..."); } +void BatteryParamsWnd::addChargeCycleRow(batteryparams_charge_cycle_t cycle) +{ + int row = chargeCyclesTable->rowCount(); + + chargeCyclesTable->insertRow(row); + chargeCyclesTable->setItem(row, 0, createItem(QString::number(cycle.index))); + chargeCyclesTable->setItem(row, 1, createItem(QString::number(cycle.startKey, 'f', 3))); + chargeCyclesTable->setItem(row, 2, createItem(QString::number(cycle.endKey, 'f', 3))); + chargeCyclesTable->setItem(row, 3, createItem(QString::number(cycle.capacity, 'f', 3))); + + QColor rowColor(200, 240, 200); + for(int c = 0; c < chargeCyclesTable->columnCount(); c++) + if(chargeCyclesTable->item(row, c) != NULL) chargeCyclesTable->item(row, c)->setBackground(rowColor); + + chargeCyclesTable->scrollToBottom(); +} + +void BatteryParamsWnd::onChargeCycleFinished(batteryparams_charge_cycle_t cycle) +{ + chargeCycles.append(cycle); + addChargeCycleRow(cycle); +} + +void BatteryParamsWnd::addChargeCycles(QVector newCharges) +{ + for(int i = 0; i < newCharges.size(); i++) onChargeCycleFinished(newCharges[i]); +} + +void BatteryParamsWnd::onStatistics() +{ + double dischargeCapacity = 0; + double chargeCapacity = 0; + double resistanceSum = 0; + int resistanceNo = 0; + int dischargeValid = 0; + + for(int i = 0; i < cycles.size(); i++) + { + dischargeCapacity += cycles[i].charge; + if(cycles[i].resistanceValid) + { + resistanceSum += cycles[i].resistance; + resistanceNo++; + } + if(cycles[i].pulseStartKey > 0) dischargeValid++; + } + + for(int i = 0; i < chargeCycles.size(); i++) chargeCapacity += chargeCycles[i].capacity; + + QDialog dialog(this); + dialog.setWindowTitle("Battery statistics"); + + QFormLayout *form = new QFormLayout(&dialog); + + form->addRow("Discharge cycles:", new QLabel(QString::number(dischargeValid), &dialog)); + form->addRow("Discharge capacity [mAh]:", new QLabel(QString::number(dischargeCapacity, 'f', 3), &dialog)); + form->addRow("Charge cycles:", new QLabel(QString::number(chargeCycles.size()), &dialog)); + form->addRow("Charge capacity [mAh]:", new QLabel(QString::number(chargeCapacity, 'f', 3), &dialog)); + + if(chargeCapacity > 0) + form->addRow("Coulombic efficiency [%]:", new QLabel(QString::number(dischargeCapacity / chargeCapacity * 100.0, 'f', 2), &dialog)); + + if(resistanceNo > 0) + form->addRow("Average R0 [mOhm]:", new QLabel(QString::number(resistanceSum / resistanceNo * 1000.0, 'f', 2), &dialog)); + + if(!cycles.isEmpty() && cycles.last().socValid) + form->addRow("SoC used [%]:", new QLabel(QString::number(cycles.last().socUsed, 'f', 2), &dialog)); + + QDialogButtonBox *box = new QDialogButtonBox(QDialogButtonBox::Close, &dialog); + connect(box, &QDialogButtonBox::rejected, &dialog, &QDialog::reject); + connect(box, &QDialogButtonBox::accepted, &dialog, &QDialog::accept); + form->addRow(box); + + dialog.exec(); +} + void BatteryParamsWnd::onCycleSelected(int row, int column) { Q_UNUSED(column); + openCycleData(row); +} +void BatteryParamsWnd::openCycleData(int row) +{ if(row < 0 || row >= cycles.size()) return; if(cycleWnd == NULL) @@ -310,6 +479,7 @@ void BatteryParamsWnd::onCycleSelected(int row, int column) } cycleWnd->setPlotSettings(plotSettings); + cycleWnd->setSettings(settings); cycleWnd->setCycle(cycles[row]); cycleWnd->show(); cycleWnd->raise(); @@ -318,12 +488,27 @@ void BatteryParamsWnd::onCycleSelected(int row, int column) void BatteryParamsWnd::updateFitPointsButtons() { - fitPointsSaveButton->setEnabled(!fittedPositions.isEmpty()); - fitPointsRestoreButton->setEnabled(!fittedPositions.isEmpty()); + fitPointsButton->setEnabled(!extractionRunning); + recalculateButton->setEnabled(!extractionRunning); + fitPointsSaveButton->setEnabled(!extractionRunning && !fittedPositions.isEmpty()); + fitPointsRestoreButton->setEnabled(!extractionRunning && !fittedPositions.isEmpty()); + fitPointsFindStartButton->setEnabled(!extractionRunning && !cycles.isEmpty()); +} + +void BatteryParamsWnd::endFit() +{ + fitInProgress = false; + + QVector deferred = pendingCycles; + pendingCycles.clear(); + for(int i = 0; i < deferred.size(); i++) onCycleFinished(deferred[i]); } void BatteryParamsWnd::onFitCyclePoints() { + if(extractionRunning) return; + if(cycles.isEmpty()) return; + QVector working = cycles; QVector changed; QProgressDialog progressDialog("Fitting cycle points...", QString(), 0, cycles.size(), this); @@ -331,7 +516,22 @@ void BatteryParamsWnd::onFitCyclePoints() int cycleNo = cycles.size(); int fittedNo = 0; - if(cycles.isEmpty()) return; + /*Each cycle carries its own sample vectors, which are implicitly shared with the + ones in "cycles". The parallel tasks write into them, so the shared data is + detached into independent copies here before the tasks start, otherwise live + cycles arriving during processEvents would race with the worker threads*/ + for(int i = 0; i < working.size(); i++) + { + working[i].plotKeys = QVector(working[i].plotKeys.constBegin(), working[i].plotKeys.constEnd()); + working[i].plotVoltage = QVector(working[i].plotVoltage.constBegin(), working[i].plotVoltage.constEnd()); + working[i].plotCurrent = QVector(working[i].plotCurrent.constBegin(), working[i].plotCurrent.constEnd()); + working[i].fitKeys = QVector(working[i].fitKeys.constBegin(), working[i].fitKeys.constEnd()); + working[i].fitVoltage = QVector(working[i].fitVoltage.constBegin(), working[i].fitVoltage.constEnd()); + working[i].relaxKeys = QVector(working[i].relaxKeys.constBegin(), working[i].relaxKeys.constEnd()); + working[i].relaxVoltage = QVector(working[i].relaxVoltage.constBegin(), working[i].relaxVoltage.constEnd()); + } + + fitInProgress = true; changed.fill(0, cycleNo); @@ -352,6 +552,7 @@ void BatteryParamsWnd::onFitCyclePoints() if(!BatteryParamsExtraction::cyclePointsFit(&working[i])) continue; + working[i].incomplete = false; BatteryParamsExtraction::analyzeCycle(&working[i], usedSettings); changed[i] = 1; } @@ -374,6 +575,7 @@ void BatteryParamsWnd::onFitCyclePoints() { if(!BatteryParamsExtraction::cyclePointsFit(&workingData[position])) return; + workingData[position].incomplete = false; BatteryParamsExtraction::analyzeCycle(&workingData[position], usedSettings); changedData[position] = 1; }); @@ -411,6 +613,8 @@ void BatteryParamsWnd::onFitCyclePoints() fittedNo++; } + endFit(); + updateSummary(); updateFitPointsButtons(); @@ -470,6 +674,318 @@ void BatteryParamsWnd::onFitPointsRestore() statusLabel->setText("Points reported by the device restored on " + QString::number(no) + " cycles"); } +void BatteryParamsWnd::onFindNewStartPoint() +{ + if(extractionRunning) return; + if(cycles.isEmpty()) return; + + /*Ask how far to the right the pause start may move and with how many points*/ + double windowSeconds = 5.0; + int pointNo = 40; + + { + QDialog paramDialog(this); + paramDialog.setWindowTitle("Find new start point"); + + QFormLayout *form = new QFormLayout(¶mDialog); + + QDoubleSpinBox *windowSpin = new QDoubleSpinBox(¶mDialog); + windowSpin->setRange(0.1, 600.0); + windowSpin->setDecimals(2); + windowSpin->setValue(windowSeconds); + windowSpin->setSuffix(" s"); + + QSpinBox *pointSpin = new QSpinBox(¶mDialog); + pointSpin->setRange(2, 500); + pointSpin->setValue(pointNo); + + QDialogButtonBox *box = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, ¶mDialog); + + form->addRow("Move pause start right by:", windowSpin); + form->addRow("Number of points:", pointSpin); + form->addRow(box); + + connect(box, &QDialogButtonBox::accepted, ¶mDialog, &QDialog::accept); + connect(box, &QDialogButtonBox::rejected, ¶mDialog, &QDialog::reject); + + if(paramDialog.exec() != QDialog::Accepted) return; + + windowSeconds = windowSpin->value(); + pointNo = pointSpin->value(); + } + + int cycleNo = cycles.size(); + double windowMs = windowSeconds * 1000.0; + batteryparams_settings_t usedSettings = settings; + + QVector> shiftSeries(cycleNo); + QVector> rmseSeries(cycleNo); + QVector> maxSeries(cycleNo); + QVector bestRmseKey(cycleNo, 0); + QVector bestVmaxKey(cycleNo, 0); + QVector found(cycleNo, 0); + + /*Each cycle carries its own sample vectors, implicitly shared with the ones in + "cycles". The tasks read them, so a fully detached copy is made here before the + sweep starts so the workers never share a Qt container with the live cycles*/ + QVector work = cycles; + for(int i = 0; i < work.size(); i++) + { + work[i].plotKeys = QVector(work[i].plotKeys.constBegin(), work[i].plotKeys.constEnd()); + work[i].plotVoltage = QVector(work[i].plotVoltage.constBegin(), work[i].plotVoltage.constEnd()); + work[i].plotCurrent = QVector(work[i].plotCurrent.constBegin(), work[i].plotCurrent.constEnd()); + work[i].fitKeys = QVector(work[i].fitKeys.constBegin(), work[i].fitKeys.constEnd()); + work[i].fitVoltage = QVector(work[i].fitVoltage.constBegin(), work[i].fitVoltage.constEnd()); + work[i].relaxKeys = QVector(work[i].relaxKeys.constBegin(), work[i].relaxKeys.constEnd()); + work[i].relaxVoltage = QVector(work[i].relaxVoltage.constBegin(), work[i].relaxVoltage.constEnd()); + } + + bool parallel = parallelGet(cycleNo); + + QProgressDialog progressDialog("Sweeping pause start...", "Cancel", 0, cycleNo, this); + progressDialog.setWindowModality(Qt::WindowModal); + progressDialog.setWindowTitle("Find new start point"); + progressDialog.setMinimumDuration(0); + progressDialog.setValue(0); + + fitInProgress = true; + + batteryparams_cycle_t *workData = work.data(); + QVector *shiftData = shiftSeries.data(); + QVector *rmseData = rmseSeries.data(); + QVector *maxData = maxSeries.data(); + double *bestRmseData = bestRmseKey.data(); + double *bestVmaxData = bestVmaxKey.data(); + int *foundData = found.data(); + + auto sweepCycle = [=](int i) + { + const batteryparams_cycle_t &original = workData[i]; + double minRmse = -1; + double minVmax = -1; + double lastKey = -1; + + for(int p = 0; p < pointNo; p++) + { + double targetKey = original.pauseStartKey + windowMs * (double)p / (double)(pointNo - 1); + batteryparams_cycle_t working = original; + + if(!BatteryParamsExtraction::setPauseStart(&working, targetKey)) continue; + if(working.pauseStartKey == lastKey) continue; + lastKey = working.pauseStartKey; + + BatteryParamsExtraction::analyzeCycle(&working, usedSettings); + if(!working.modelValid) continue; + + double shift = (working.pauseStartKey - original.pauseStartKey) / 1000.0; + double rmseMv = working.fitRmse * 1000.0; + double maxMv = working.fitMaxError * 1000.0; + + shiftData[i].append(shift); + rmseData[i].append(rmseMv); + maxData[i].append(maxMv); + + if((minRmse < 0) || (rmseMv < minRmse)) { minRmse = rmseMv; bestRmseData[i] = working.pauseStartKey; } + if((minVmax < 0) || (maxMv < minVmax)) { minVmax = maxMv; bestVmaxData[i] = working.pauseStartKey; } + } + + if(minRmse >= 0) foundData[i] = 1; + }; + + if(!parallel) + { + for(int i = 0; i < cycleNo; i++) + { + progressDialog.setLabelText(QString("Sweeping cycle %1 of %2...").arg(i + 1).arg(cycleNo)); + progressDialog.setValue(i); + QApplication::processEvents(); + + if(progressDialog.wasCanceled()) { endFit(); return; } + + sweepCycle(i); + } + } + else + { + QVector positions; + for(int i = 0; i < cycleNo; i++) positions.append(i); + + QFutureWatcher watcher; + QFuture future = QtConcurrent::map(positions, sweepCycle); + watcher.setFuture(future); + + while(!watcher.isFinished()) + { + progressDialog.setLabelText(QString("Sweeping %1 cycles on %2 cores, %3 done...") + .arg(cycleNo).arg(QThread::idealThreadCount()).arg(watcher.progressValue())); + progressDialog.setValue(watcher.progressValue()); + QApplication::processEvents(); + QThread::msleep(20); + + if(progressDialog.wasCanceled()) + { + future.cancel(); + future.waitForFinished(); + endFit(); + return; + } + } + } + + progressDialog.setValue(cycleNo); + + endFit(); + + bool anyFound = false; + for(int i = 0; i < cycleNo; i++) if(found[i]) { anyFound = true; break; } + + if(!anyFound) + { + QMessageBox::information(this, "Find new start point", + "No cycle could be fitted while sweeping the pause start."); + return; + } + + /*Results dialog: one curve per cycle, RMSE and max error over the pause start shift*/ + QDialog dialog(this); + dialog.setWindowTitle("Find new start point"); + + QVBoxLayout *dialogLayout = new QVBoxLayout(&dialog); + + QCustomPlot *rmsePlot = new QCustomPlot(&dialog); + rmsePlot->xAxis->setLabel("Pause start shift [s]"); + rmsePlot->yAxis->setLabel("RMSE [mV]"); + rmsePlot->legend->setVisible(true); + rmsePlot->legend->setFont(QFont("Arial", 7)); + rmsePlot->legend->setWrap(8); + rmsePlot->legend->setFillOrder(QCPLegend::foColumnsFirst); + rmsePlot->axisRect()->insetLayout()->setInsetAlignment(0, Qt::AlignTop | Qt::AlignRight); + + QCustomPlot *maxPlot = new QCustomPlot(&dialog); + maxPlot->xAxis->setLabel("Pause start shift [s]"); + maxPlot->yAxis->setLabel("Max error [mV]"); + maxPlot->legend->setVisible(true); + maxPlot->legend->setFont(QFont("Arial", 7)); + maxPlot->legend->setWrap(8); + maxPlot->legend->setFillOrder(QCPLegend::foColumnsFirst); + maxPlot->axisRect()->insetLayout()->setInsetAlignment(0, Qt::AlignTop | Qt::AlignRight); + + for(int i = 0; i < cycleNo; i++) + { + if(!found[i] || shiftSeries[i].isEmpty()) continue; + + QColor color = QColor::fromHsv((i * 47) % 360, 200, 220); + QString name = "Cycle " + QString::number(cycles[i].index); + + QCPGraph *rmseGraph = rmsePlot->addGraph(); + rmseGraph->setData(shiftSeries[i], rmseSeries[i]); + rmseGraph->setPen(QPen(color, 1.5)); + rmseGraph->setName(name); + + QCPGraph *maxGraph = maxPlot->addGraph(); + maxGraph->setData(shiftSeries[i], maxSeries[i]); + maxGraph->setPen(QPen(color, 1.5)); + maxGraph->setName(name); + + /*Mark the point that would be chosen: the minimum of each metric for this + cycle. That is the pause start applied when the matching button is pressed*/ + int rmseMinIndex = 0; + int maxMinIndex = 0; + + for(int k = 1; k < rmseSeries[i].size(); k++) + { + if(rmseSeries[i][k] < rmseSeries[i][rmseMinIndex]) rmseMinIndex = k; + if(maxSeries[i][k] < maxSeries[i][maxMinIndex]) maxMinIndex = k; + } + + QCPGraph *rmseDot = rmsePlot->addGraph(); + rmseDot->setData(QVector{shiftSeries[i][rmseMinIndex]}, QVector{rmseSeries[i][rmseMinIndex]}); + rmseDot->setLineStyle(QCPGraph::lsNone); + rmseDot->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssDisc, color, 7)); + rmseDot->removeFromLegend(); + + QCPGraph *maxDot = maxPlot->addGraph(); + maxDot->setData(QVector{shiftSeries[i][maxMinIndex]}, QVector{maxSeries[i][maxMinIndex]}); + maxDot->setLineStyle(QCPGraph::lsNone); + maxDot->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssDisc, color, 7)); + maxDot->removeFromLegend(); + } + + rmsePlot->rescaleAxes(); + rmsePlot->replot(); + maxPlot->rescaleAxes(); + maxPlot->replot(); + + dialogLayout->addWidget(rmsePlot, 1); + dialogLayout->addWidget(maxPlot, 1); + + QHBoxLayout *buttonLayout = new QHBoxLayout(); + QPushButton *applyRmseButton = new QPushButton("Apply by RMSE", &dialog); + QPushButton *applyVmaxButton = new QPushButton("Apply by max error", &dialog); + QPushButton *cancelButton = new QPushButton("Cancel", &dialog); + + buttonLayout->addStretch(); + buttonLayout->addWidget(applyRmseButton); + buttonLayout->addWidget(applyVmaxButton); + buttonLayout->addWidget(cancelButton); + dialogLayout->addLayout(buttonLayout); + + int choice = 0; + + connect(applyRmseButton, &QPushButton::clicked, &dialog, [&choice, &dialog]() { choice = 1; dialog.accept(); }); + connect(applyVmaxButton, &QPushButton::clicked, &dialog, [&choice, &dialog]() { choice = 2; dialog.accept(); }); + connect(cancelButton, &QPushButton::clicked, &dialog, &QDialog::reject); + + dialog.resize(820, 680); + + if((dialog.exec() != QDialog::Accepted) || (choice == 0)) return; + + int appliedNo = 0; + int processedNo = 0; + + int toApply = 0; + for(int i = 0; i < cycleNo; i++) if(found[i]) toApply++; + + QProgressDialog applyProgress("Applying the new pause start and recalculating...", QString(), 0, toApply, this); + applyProgress.setWindowModality(Qt::WindowModal); + applyProgress.setWindowTitle("Find new start point"); + applyProgress.setMinimumDuration(0); + applyProgress.setValue(0); + + for(int i = 0; i < cycleNo; i++) + { + if(!found[i]) continue; + + applyProgress.setValue(processedNo++); + QApplication::processEvents(); + + double key = (choice == 1) ? bestRmseKey[i] : bestVmaxKey[i]; + batteryparams_cycle_t working = cycles[i]; + + if(!BatteryParamsExtraction::setPauseStart(&working, key)) continue; + + BatteryParamsExtraction::analyzeCycle(&working, usedSettings); + + if(!fittedPositions.contains(i)) + { + fittedPositions.append(i); + fittedOriginals.append(cycles[i]); + } + + cycles[i] = working; + fillCycleRow(i, cycles[i]); + appliedNo++; + } + + applyProgress.setValue(toApply); + + updateSummary(); + updateFitPointsButtons(); + + statusLabel->setText("Pause start set by " + QString(choice == 1 ? "RMSE" : "max error") + + " on " + QString::number(appliedNo) + " cycles, marked with * and not confirmed yet"); +} + void BatteryParamsWnd::onCycleUpdated(batteryparams_cycle_t cycle) { for(int i = 0; i < cycles.size(); i++) @@ -484,14 +1000,223 @@ void BatteryParamsWnd::onCycleUpdated(batteryparams_cycle_t cycle) } } +void BatteryParamsWnd::deleteCycleAt(int row) +{ + if(row < 0 || row >= cycles.size()) return; + + batteryparams_cycle_t &cycle = cycles[row]; + + if(cycle.pulseStartKey > 0) removedMarkerKeys.append(cycle.pulseStartKey); + if(cycle.pulseEndKey > 0) removedMarkerKeys.append(cycle.pulseEndKey); + if(cycle.pauseStartKey > 0) removedMarkerKeys.append(cycle.pauseStartKey); + if(cycle.pauseEndKey > 0) removedMarkerKeys.append(cycle.pauseEndKey); + + cycle.pulseStartKey = 0; + cycle.pulseEndKey = 0; + cycle.pauseStartKey = 0; + cycle.pauseEndKey = 0; + cycle.pulseEndVoltage = 0; + cycle.pulseEndCurrent = 0; + cycle.pauseStartVoltage = 0; + cycle.pauseStartCurrent = 0; + cycle.deltaVoltage = 0; + cycle.deltaCurrent = 0; + cycle.resistance = 0; + cycle.charge = 0; + cycle.chargeTotal = 0; + cycle.socUsed = 0; + cycle.soc = 0; + cycle.resistanceValid = false; + cycle.socValid = false; + cycle.relaxationReached = false; + cycle.relaxationKey = 0; + cycle.relaxationVoltage = 0; + cycle.ocv = 0; + cycle.modelValid = false; + cycle.tauFast = 0; + cycle.tauSlow = 0; + cycle.fastPortionEndKey = 0; + cycle.r1 = 0; + cycle.c1 = 0; + cycle.r2 = 0; + cycle.c2 = 0; + cycle.fitRmse = 0; + cycle.fitMaxError = 0; + cycle.fitKeys.clear(); + cycle.fitVoltage.clear(); + cycle.relaxKeys.clear(); + cycle.relaxVoltage.clear(); + + int fitIndex = fittedPositions.indexOf(row); + if(fitIndex >= 0) + { + fittedPositions.remove(fitIndex); + fittedOriginals.remove(fitIndex); + } + + deletedCycleRows.insert(row); + + fillCycleRow(row, cycle); +} + +void BatteryParamsWnd::onDeleteCycle() +{ + QVector rows; + QModelIndexList selected = cyclesTable->selectionModel()->selectedRows(); + + for(int i = 0; i < selected.size(); i++) rows.append(selected[i].row()); + + if(rows.isEmpty()) + { + int current = cyclesTable->currentRow(); + if(current >= 0) rows.append(current); + } + + if(rows.isEmpty()) return; + + for(int i = 0; i < rows.size(); i++) deleteCycleAt(rows[i]); + + updateSummary(); + updateFitPointsButtons(); +} + +void BatteryParamsWnd::fitCycleAt(int row) +{ + if(extractionRunning) return; + if(row < 0 || row >= cycles.size()) return; + + batteryparams_cycle_t working = cycles[row]; + + if(!BatteryParamsExtraction::cyclePointsFit(&working)) + { + statusLabel->setText("Cycle " + QString::number(cycles[row].index) + " already sits on the settled levels"); + return; + } + + BatteryParamsExtraction::analyzeCycle(&working, settings); + + if(!fittedPositions.contains(row)) + { + fittedPositions.append(row); + fittedOriginals.append(cycles[row]); + } + + cycles[row] = working; + fillCycleRow(row, cycles[row]); + updateSummary(); + updateFitPointsButtons(); + statusLabel->setText("Cycle points fitted on cycle " + QString::number(cycles[row].index) + ", marked with * and not confirmed yet"); +} + +void BatteryParamsWnd::onCycleContextMenu(const QPoint &pos) +{ + int row = cyclesTable->rowAt(pos.y()); + if(row < 0 || row >= cycles.size()) return; + + cyclesTable->selectRow(row); + + QMenu menu(this); + QAction *showAction = menu.addAction("Show cycle data"); + QAction *deleteAction = menu.addAction("Delete cycle"); + QAction *fitAction = menu.addAction("Fit cycle points"); + + fitAction->setEnabled(!extractionRunning); + + QAction *chosen = menu.exec(cyclesTable->viewport()->mapToGlobal(pos)); + + if(chosen == showAction) openCycleData(row); + else if(chosen == deleteAction) + { + deleteCycleAt(row); + updateSummary(); + updateFitPointsButtons(); + } + else if(chosen == fitAction) fitCycleAt(row); +} + +void BatteryParamsWnd::onSaveNewCycles() +{ + if(deletedCycleRows.isEmpty()) return; + + QVector rows; + for(QSet::const_iterator it = deletedCycleRows.constBegin(); it != deletedCycleRows.constEnd(); ++it) + rows.append(*it); + std::sort(rows.begin(), rows.end()); + + for(int i = rows.size() - 1; i >= 0; i--) + { + int row = rows[i]; + if(row < 0 || row >= cycles.size()) continue; + + int fitIndex = fittedPositions.indexOf(row); + if(fitIndex >= 0) + { + fittedPositions.remove(fitIndex); + fittedOriginals.remove(fitIndex); + } + for(int j = 0; j < fittedPositions.size(); j++) + if(fittedPositions[j] > row) fittedPositions[j] -= 1; + + cycles.remove(row); + cyclesTable->removeRow(row); + } + + int no = deletedCycleRows.size(); + deletedCycleRows.clear(); + removedMarkerKeys.clear(); + + fittedPositions.clear(); + fittedOriginals.clear(); + for(int i = 0; i < cycles.size(); i++) fillCycleRow(i, cycles[i]); + + emit sigPointsStored(collectCycleMarkers()); + + if(cycles.isEmpty()) statusLabel->setText("Waiting for the first cycle..."); + else statusLabel->setText(QString::number(no) + " deleted cycles removed, ep.csv updated"); + + updateSummary(); + updateFitPointsButtons(); +} + +QVector> BatteryParamsWnd::collectCycleMarkers() +{ + QVector> markers; + + for(int i = 0; i < cycles.size(); i++) + { + if(cycles[i].pulseStartKey > 0) markers.append(qMakePair(QString(BATTERYPARAMS_DEFAULT_PULSE_START_MARKER), cycles[i].pulseStartKey)); + if(cycles[i].pulseEndKey > 0) markers.append(qMakePair(QString(BATTERYPARAMS_DEFAULT_PULSE_END_MARKER), cycles[i].pulseEndKey)); + if(cycles[i].pauseStartKey > 0) markers.append(qMakePair(QString(BATTERYPARAMS_DEFAULT_PAUSE_START_MARKER), cycles[i].pauseStartKey)); + if(cycles[i].pauseEndKey > 0) markers.append(qMakePair(QString(BATTERYPARAMS_DEFAULT_PAUSE_END_MARKER), cycles[i].pauseEndKey)); + } + + return markers; +} + +void BatteryParamsWnd::onStoreNewPoints() +{ + fittedPositions.clear(); + fittedOriginals.clear(); + for(int i = 0; i < cycles.size(); i++) fillCycleRow(i, cycles[i]); + + emit sigPointsStored(collectCycleMarkers()); + + updateFitPointsButtons(); + statusLabel->setText("Points stored to ep.csv"); +} + void BatteryParamsWnd::onClear() { fittedPositions.clear(); fittedOriginals.clear(); + deletedCycleRows.clear(); + removedMarkerKeys.clear(); updateFitPointsButtons(); cycles.clear(); cyclesTable->setRowCount(0); + chargeCycles.clear(); + chargeCyclesTable->setRowCount(0); statusLabel->setText("Waiting for the first cycle..."); updateSummary(); } @@ -503,6 +1228,13 @@ void BatteryParamsWnd::setSettings(batteryparams_settings_t aSettings) if(settingsDlg != NULL) settingsDlg->setSettings(settings); } +void BatteryParamsWnd::setExtractionRunning(bool running) +{ + extractionRunning = running; + if(settingsDlg != NULL) settingsDlg->setExtractionRunning(running); + updateFitPointsButtons(); +} + void BatteryParamsWnd::updateSettingsLabel() { settingsLabel->setText(QString(settings.model == BATTERYPARAMS_MODEL_SECOND_ORDER ? "2nd order" : "1st order") + @@ -523,6 +1255,7 @@ void BatteryParamsWnd::onSettings() settingsDlg->setSettings(settings); settingsDlg->setPlotSettings(plotSettings); + settingsDlg->setExtractionRunning(extractionRunning); if(settingsDlg->exec() != QDialog::Accepted) return; @@ -586,6 +1319,7 @@ void BatteryParamsWnd::analyzeCycles(QVector *target, QPr QApplication::processEvents(); } + if((*target)[i].incomplete) continue; BatteryParamsExtraction::analyzeCycle(&(*target)[i], usedSettings); } @@ -596,6 +1330,7 @@ void BatteryParamsWnd::analyzeCycles(QVector *target, QPr QFutureWatcher watcher; QFuture future = QtConcurrent::map(*target, [usedSettings](batteryparams_cycle_t &cycle) { + if(cycle.incomplete) return; BatteryParamsExtraction::analyzeCycle(&cycle, usedSettings); }); @@ -623,6 +1358,7 @@ void BatteryParamsWnd::recalculate() /*Already collected cycles keep their samples, so changed settings are applied to them as well instead of only to the cycles still to come. Fitting takes a moment per cycle, so the progress is shown*/ + if(extractionRunning) return; if(cycles.isEmpty()) return; QProgressDialog progressDialog(QString("%1 cycles detected\nRecalculating battery parameters...").arg(cycles.size()), @@ -636,6 +1372,8 @@ void BatteryParamsWnd::recalculate() progressDialog.setWindowTitle("Battery parameters"); progressDialog.setMinimumWidth(320); progressDialog.setValue(0); + + fitInProgress = true; QApplication::processEvents(); for(int i = 0; i < cycles.size(); i++) @@ -656,6 +1394,8 @@ void BatteryParamsWnd::recalculate() progressDialog.close(); + endFit(); + updateSummary(); } @@ -706,6 +1446,7 @@ void BatteryParamsWnd::onResistanceTrend() batteryparams_trend_t r0 = trendCreate("R0", QColor(200, 60, 20)); batteryparams_trend_t r1 = trendCreate("R1", QColor(30, 110, 200)); batteryparams_trend_t r2 = trendCreate("R2", QColor(30, 150, 60)); + batteryparams_trend_t rTotal = trendCreate("Rtotal", QColor(130, 60, 170)); for(int i = 0; i < cycles.size(); i++) { @@ -722,13 +1463,21 @@ void BatteryParamsWnd::onResistanceTrend() r1.soc.append(cycles[i].soc); r1.value.append(cycles[i].r1 * 1000.0); + if(cycles[i].resistanceValid) + { + double total = cycles[i].resistance + cycles[i].r1; + if(cycles[i].model == BATTERYPARAMS_MODEL_SECOND_ORDER) total += cycles[i].r2; + rTotal.soc.append(cycles[i].soc); + rTotal.value.append(total * 1000.0); + } + if(cycles[i].model != BATTERYPARAMS_MODEL_SECOND_ORDER) continue; r2.soc.append(cycles[i].soc); r2.value.append(cycles[i].r2 * 1000.0); } - trends << r0 << r1 << r2; + trends << r0 << r1 << r2 << rTotal; trendShow(&resistanceTrendWnd, "Resistance vs SoC", "R [mOhm]", trends); } diff --git a/Source/Windows/BatteryParams/batteryparamswnd.h b/Source/Windows/BatteryParams/batteryparamswnd.h index d0826cc..3c01624 100644 --- a/Source/Windows/BatteryParams/batteryparamswnd.h +++ b/Source/Windows/BatteryParams/batteryparamswnd.h @@ -8,7 +8,10 @@ #include #include #include +#include #include +#include +#include #include "Processing/batteryparamsextraction.h" #include "batterycyclewnd.h" @@ -28,18 +31,25 @@ class BatteryParamsWnd : public QWidget void setProfileName(QString name); void setSettings(batteryparams_settings_t settings); + void setExtractionRunning(bool running); void addCycles(QVector newCycles, QProgressDialog *progressDialog); + void addChargeCycles(QVector newCharges); signals: void sigSettingsChanged(batteryparams_settings_t settings); + void sigPointsStored(QVector> markers); public slots: void onCycleStarted(unsigned int index, double key); void onCycleFinished(batteryparams_cycle_t cycle); + void onChargeCycleFinished(batteryparams_charge_cycle_t cycle); void onClear(); private slots: void onExport(); + void onDeleteCycle(); + void onStatistics(); + void onStoreNewPoints(); void onSettings(); void onResistanceTrend(); void onCapacitanceTrend(); @@ -51,9 +61,12 @@ private slots: void onFitCyclePoints(); void onFitPointsSave(); void onFitPointsRestore(); + void onFindNewStartPoint(); void onSweepRequested(batteryfitinterval_sweep_t mode, double fixedValue, double from, double to, int steps, bool compare); void onCycleSelected(int row, int column); + void onCycleContextMenu(const QPoint &pos); + void onSaveNewCycles(); void onCycleUpdated(batteryparams_cycle_t cycle); private: @@ -69,6 +82,8 @@ private slots: QPushButton *fitPointsButton; QPushButton *fitPointsSaveButton; QPushButton *fitPointsRestoreButton; + QPushButton *fitPointsFindStartButton; + QPushButton *recalculateButton; QLabel *settingsLabel; BatteryParamsSettingsDlg *settingsDlg; @@ -81,12 +96,23 @@ private slots: BatteryFitIntervalWnd *fitIntervalWnd; batteryparams_settings_t settings; + bool extractionRunning; batteryparams_plot_settings_t plotSettings; int parallelAnswer; QLabel *summaryLabel; + QPushButton *statisticsButton; + QTabWidget *cycleTabs; QTableWidget *cyclesTable; + QTableWidget *chargeCyclesTable; + QVector chargeCycles; QPushButton *clearButton; QPushButton *exportButton; + QPushButton *saveCyclesButton; + QPushButton *storeCyclesButton; + QSet deletedCycleRows; + QVector removedMarkerKeys; + bool fitInProgress; + QVector pendingCycles; BatteryCycleWnd *cycleWnd; QVector fittedPositions; QVector fittedOriginals; @@ -100,6 +126,12 @@ private slots: QTableWidgetItem* createItem(QString text); void addCycleRow(batteryparams_cycle_t cycle); + void addChargeCycleRow(batteryparams_charge_cycle_t cycle); + void openCycleData(int row); + void deleteCycleAt(int row); + void fitCycleAt(int row); + void endFit(); + QVector> collectCycleMarkers(); void fillCycleRow(int row, batteryparams_cycle_t cycle); void updateSummary(); void recalculate(); diff --git a/Source/Windows/DataAnalyzer/dataanalyzer.cpp b/Source/Windows/DataAnalyzer/dataanalyzer.cpp index 720aab0..dc87727 100644 --- a/Source/Windows/DataAnalyzer/dataanalyzer.cpp +++ b/Source/Windows/DataAnalyzer/dataanalyzer.cpp @@ -4,6 +4,9 @@ #include #include #include +#include +#include +#include #include #include #include @@ -125,6 +128,12 @@ QStringList DataAnalyzer::listConsumptionProfiles() listConsumptionProfilesInDir(dir, "", profileList, 0); + std::sort(profileList.begin(), profileList.end(), [this](const QString &a, const QString &b){ + QDateTime ta = QFileInfo(QDir(wsDirPath).filePath(a)).lastModified(); + QDateTime tb = QFileInfo(QDir(wsDirPath).filePath(b)).lastModified(); + return ta > tb; + }); + return profileList; } diff --git a/Source/Windows/DataAnalyzer/dataanalyzerprofile.cpp b/Source/Windows/DataAnalyzer/dataanalyzerprofile.cpp index 26220f5..0cdd41f 100644 --- a/Source/Windows/DataAnalyzer/dataanalyzerprofile.cpp +++ b/Source/Windows/DataAnalyzer/dataanalyzerprofile.cpp @@ -10,6 +10,9 @@ #include #include #include +#include +#include +#include #define PLOT_MINIMUM_SIZE_HEIGHT 100 #define PLOT_MINIMUM_SIZE_WIDTH 500 @@ -260,6 +263,134 @@ void DataAnalyzerProfile::processingVolCurConDone(QVector > vc, } } +void DataAnalyzerProfile::saveBatterySettings(const batteryparams_settings_t &settings) +{ + QJsonObject obj; + obj["relaxationThreshold"] = settings.relaxationThreshold; + obj["relaxationWindow"] = settings.relaxationWindow; + obj["relaxationFilter"] = settings.relaxationFilter; + obj["model"] = (int)settings.model; + obj["fitEnd"] = (int)settings.fitEnd; + obj["tauGridPoints"] = settings.tauGridPoints; + obj["tauSeparation"] = settings.tauSeparation; + obj["capacity"] = settings.capacity; + obj["initialSoc"] = settings.initialSoc; + obj["plotDecimation"] = settings.plotDecimation; + + QFile file(wsDirPath + "/" + profileName + "/batteryparams.json"); + if(file.open(QIODevice::WriteOnly | QIODevice::Truncate)) + { + file.write(QJsonDocument(obj).toJson(QJsonDocument::Indented)); + file.close(); + } +} + +bool DataAnalyzerProfile::loadBatterySettings(batteryparams_settings_t *settings) +{ + if(settings == NULL) return false; + + QFile file(wsDirPath + "/" + profileName + "/batteryparams.json"); + if(!file.open(QIODevice::ReadOnly)) return false; + + QByteArray data = file.readAll(); + file.close(); + + QJsonParseError error; + QJsonDocument doc = QJsonDocument::fromJson(data, &error); + if(error.error != QJsonParseError::NoError || !doc.isObject()) return false; + + QJsonObject obj = doc.object(); + batteryparams_settings_t loaded = BatteryParamsExtraction::settingsDefault(); + + loaded.relaxationThreshold = obj.value("relaxationThreshold").toDouble(loaded.relaxationThreshold); + loaded.relaxationWindow = obj.value("relaxationWindow").toDouble(loaded.relaxationWindow); + loaded.relaxationFilter = obj.value("relaxationFilter").toDouble(loaded.relaxationFilter); + loaded.model = (batteryparams_model_t)obj.value("model").toInt((int)loaded.model); + loaded.fitEnd = (batteryparams_fit_end_t)obj.value("fitEnd").toInt((int)loaded.fitEnd); + loaded.tauGridPoints = obj.value("tauGridPoints").toInt(loaded.tauGridPoints); + loaded.tauSeparation = obj.value("tauSeparation").toDouble(loaded.tauSeparation); + loaded.capacity = obj.value("capacity").toDouble(loaded.capacity); + loaded.initialSoc = obj.value("initialSoc").toDouble(loaded.initialSoc); + loaded.plotDecimation = obj.value("plotDecimation").toInt(loaded.plotDecimation); + + *settings = loaded; + return true; +} + +void DataAnalyzerProfile::onBatterySettingsChanged(batteryparams_settings_t settings) +{ + saveBatterySettings(settings); +} + +void DataAnalyzerProfile::onBatteryPointsStored(QVector> cycleMarkers) +{ + /*Every pulse/pause marker is replaced with the current set reported by the + battery parameters window, so moved points, newly completed cycles and removed + cycles are all reflected. Markers that do not belong to a cycle (for example the + charge markers) are kept as they were*/ + QVector> rebuilt; + + for(int i = 0; i < loadedMarkers.size(); i++) + { + QString name = loadedMarkers[i].first.trimmed(); + if(name == BATTERYPARAMS_DEFAULT_PULSE_START_MARKER || + name == BATTERYPARAMS_DEFAULT_PULSE_END_MARKER || + name == BATTERYPARAMS_DEFAULT_PAUSE_START_MARKER || + name == BATTERYPARAMS_DEFAULT_PAUSE_END_MARKER) continue; + rebuilt.append(loadedMarkers[i]); + } + + for(int i = 0; i < cycleMarkers.size(); i++) + rebuilt.append(qMakePair(cycleMarkers[i].first, (int)qRound(cycleMarkers[i].second))); + + std::sort(rebuilt.begin(), rebuilt.end(), [](const QPair &a, const QPair &b){ + return a.second < b.second; + }); + + loadedMarkers = rebuilt; + + QString epPath = wsDirPath + "/" + profileName + "/ep.csv"; + QStringList headerLines; + QFile in(epPath); + + if(in.open(QIODevice::ReadOnly | QIODevice::Text)) + { + while(!in.atEnd()) + { + QString line = QString::fromUtf8(in.readLine()); + QString trimmed = line.trimmed(); + int comma = trimmed.lastIndexOf(','); + bool isData = false; + + if(comma >= 0) + { + bool ok; + trimmed.mid(comma + 1).trimmed().toInt(&ok); + isData = ok; + } + + if(isData) break; + + while(line.endsWith('\n') || line.endsWith('\r')) line.chop(1); + headerLines.append(line); + } + in.close(); + } + + if(headerLines.isEmpty()) headerLines.append("Energy point info"); + + QFile out(epPath); + if(out.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text)) + { + QTextStream ts(&out); + for(int i = 0; i < headerLines.size(); i++) ts << headerLines[i] << "\n"; + for(int i = 0; i < loadedMarkers.size(); i++) ts << loadedMarkers[i].first << "," << loadedMarkers[i].second << "\n"; + out.close(); + } + + applyMarkersToPlots(loadedMarkers); +} + void DataAnalyzerProfile::processingEPDone(QVector > epData) { loadedMarkers = epData; @@ -351,23 +482,28 @@ void DataAnalyzerProfile::onBatteryAnalyzer() } /*Capacity is stored with the profile, so the offline analysis can show the - used state of charge the same way the live one does*/ + used state of charge the same way the live one does. If a saved battery + parameters configuration exists for this profile, it is used as is so the + capacity, relaxation and extraction settings do not have to be set again*/ { QVector> summaryInfo = parseSummaryFile(wsDirPath + "/" + profileName + "/OpenEPT.txt"); double capacity = getValueForKey(summaryInfo, "Battery capacity [mAh]").toDouble(); batteryparams_settings_t settings = extraction.getSettings(); - if(capacity > 0) - { - settings.capacity = capacity; - extraction.setSettings(settings); - } + if(capacity > 0) settings.capacity = capacity; + + batteryparams_settings_t saved; + if(loadBatterySettings(&saved)) settings = saved; + + extraction.setSettings(settings); } if(batteryParamsWnd == NULL) { batteryParamsWnd = new BatteryParamsWnd(); batteryParamsWnd->setAttribute(Qt::WA_QuitOnClose, false); + connect(batteryParamsWnd, &BatteryParamsWnd::sigPointsStored, this, &DataAnalyzerProfile::onBatteryPointsStored); + connect(batteryParamsWnd, &BatteryParamsWnd::sigSettingsChanged, this, &DataAnalyzerProfile::onBatterySettingsChanged); } batteryParamsWnd->setProfileName(profileName); @@ -400,6 +536,8 @@ void DataAnalyzerProfile::onBatteryAnalyzer() progressDialog.setValue(0); QApplication::processEvents(); + extraction.onReset(); + extraction.setCaptureIncomplete(true); extraction.onNewSamplesReceived(loadedVoltage, loadedCurrent, loadedVoltageKeys, loadedCurrentKeys); progressDialog.setValue(1); @@ -423,6 +561,8 @@ void DataAnalyzerProfile::onBatteryAnalyzer() QApplication::processEvents(); } + extraction.flushIncompleteCycle(); + cycleNo = extraction.getCycles().size(); if(cycleNo == 0) @@ -439,6 +579,45 @@ void DataAnalyzerProfile::onBatteryAnalyzer() progressDialog.close(); + { + QVector chargeCycles; + unsigned int chargeIndex = 0; + double chargeStartKey = -1; + + for(int i = 0; i < loadedMarkers.size(); i++) + { + QString name = loadedMarkers[i].first.trimmed(); + + if(name == "Charge Start") + { + chargeStartKey = loadedMarkers[i].second; + } + else if(name == "Charge End" && chargeStartKey >= 0) + { + double chargeEndKey = loadedMarkers[i].second; + double capacity = 0; + + for(int s = 1; s < loadedCurrentKeys.size() && s < loadedCurrent.size(); s++) + { + if(loadedCurrentKeys[s] < chargeStartKey) continue; + if(loadedCurrentKeys[s] > chargeEndKey) break; + capacity += loadedCurrent[s] * (loadedCurrentKeys[s] - loadedCurrentKeys[s - 1]) / 3600000.0; + } + + batteryparams_charge_cycle_t chargeCycle; + chargeIndex++; + chargeCycle.index = chargeIndex; + chargeCycle.startKey = chargeStartKey; + chargeCycle.endKey = chargeEndKey; + chargeCycle.capacity = qAbs(capacity); + chargeCycles.append(chargeCycle); + chargeStartKey = -1; + } + } + + if(!chargeCycles.isEmpty()) batteryParamsWnd->addChargeCycles(chargeCycles); + } + batteryParamsWnd->show(); batteryParamsWnd->raise(); batteryParamsWnd->activateWindow(); diff --git a/Source/Windows/DataAnalyzer/dataanalyzerprofile.h b/Source/Windows/DataAnalyzer/dataanalyzerprofile.h index 60e67a6..d3a59cc 100644 --- a/Source/Windows/DataAnalyzer/dataanalyzerprofile.h +++ b/Source/Windows/DataAnalyzer/dataanalyzerprofile.h @@ -49,6 +49,8 @@ public slots: void onDetachClicked(); void processingVolCurConDone(QVector > vc, QVector> cons); void processingEPDone(QVector> epData); + void onBatteryPointsStored(QVector> cycleMarkers); + void onBatterySettingsChanged(batteryparams_settings_t settings); void updateProgress(int percentage); void updateProgressText(QString text); @@ -57,6 +59,8 @@ public slots: void createCurrentSubWin(); void createConsumptionSubWin(); void applyMarkersToPlots(QVector> markers); + void saveBatterySettings(const batteryparams_settings_t &settings); + bool loadBatterySettings(batteryparams_settings_t *settings); QVector> parseSummaryFile(const QString &filePath); QString getValueForKey(const QVector > &parsedData, const QString &key); diff --git a/Source/Windows/Device/devicewnd.cpp b/Source/Windows/Device/devicewnd.cpp index 8c8ed5a..076754b 100644 --- a/Source/Windows/Device/devicewnd.cpp +++ b/Source/Windows/Device/devicewnd.cpp @@ -62,6 +62,8 @@ DeviceWnd::DeviceWnd(QWidget *parent) : connect(energyControlWnd, &EnergyControlWnd::sigBatParamViewRequested, this, &DeviceWnd::sigBatParamViewRequested); connect(energyControlWnd, &EnergyControlWnd::sigBatParamCapacityChanged, this, &DeviceWnd::sigBatParamCapacityChanged); connect(energyControlWnd, &EnergyControlWnd::sigBatParamRelaxationChanged, this, &DeviceWnd::sigBatParamRelaxationChanged); + connect(energyControlWnd, &EnergyControlWnd::sigBatParamExtractionRunning, this, &DeviceWnd::sigBatParamExtractionRunning); + connect(energyControlWnd, &EnergyControlWnd::sigChargeMarkersEnabled, this, &DeviceWnd::sigChargeMarkersEnabled); connect(energyControlWnd, &EnergyControlWnd::sigLoadWaveClear, this, &DeviceWnd::sigLoadWaveClear); connect(energyControlWnd, SIGNAL(sigChargingCurrentStatusChanged(bool)), this, SLOT(onChargingCurrentStatusChanged(bool))); connect(energyControlWnd, SIGNAL(sigChargingCurrentChanged(unsigned int)), this, SLOT(onChargingCurrentChanged(unsigned int))); @@ -128,6 +130,7 @@ DeviceWnd::DeviceWnd(QWidget *parent) : connect(ui->refreshPusb, SIGNAL(clicked(bool)), this, SLOT(onRefreshAcquisiton())); connect(ui->ConsolePusb, SIGNAL(clicked(bool)), this, SLOT(onConsolePressed())); connect(ui->DataStatisticsPushb, SIGNAL(clicked(bool)), this, SLOT(onDataAnalyzerPressed())); + connect(ui->BatteryParamsPushb, &QPushButton::clicked, this, &DeviceWnd::sigBatParamViewRequested); connect(ui->samplingPeriodLine, SIGNAL(returnPressed()), this, SLOT(onSamplingPeriodChanged())); connect(ui->streamServerInterfComb, SIGNAL(currentTextChanged(QString)), this, SLOT(onInterfaceChanged(QString))); diff --git a/Source/Windows/Device/devicewnd.h b/Source/Windows/Device/devicewnd.h index c5b3b6c..225a64a 100644 --- a/Source/Windows/Device/devicewnd.h +++ b/Source/Windows/Device/devicewnd.h @@ -206,6 +206,8 @@ class DeviceWnd : public QWidget void sigBatParamViewRequested(); void sigBatParamCapacityChanged(double capacity); void sigBatParamRelaxationChanged(bool enabled, double thresholdMv, double windowS, double filterMs); + void sigBatParamExtractionRunning(bool running); + void sigChargeMarkersEnabled(bool enabled); void sigLoadWaveClear(); void sigChargingCurrentChanged(unsigned int current); void sigChargingTermCurrentChanged(unsigned int current); diff --git a/Source/Windows/Device/devicewnd.ui b/Source/Windows/Device/devicewnd.ui index 1c7ce3c..95d0c22 100644 --- a/Source/Windows/Device/devicewnd.ui +++ b/Source/Windows/Device/devicewnd.ui @@ -1260,6 +1260,65 @@ + + + + + + + Arial + 10 + + + + Battery params + + + + + + + + 30 + 30 + + + + + 30 + 30 + + + + Open the battery parameters view (available while the battery parameter extraction runs) + + + + + + + :/images/NewSet/battery.png:/images/NewSet/battery.png + + + + + + + Qt::Horizontal + + + QSizePolicy::Minimum + + + + 40 + 20 + + + + + + diff --git a/Source/Windows/Device/energycontrolwnd.cpp b/Source/Windows/Device/energycontrolwnd.cpp index 9efd0f7..dc3ab00 100644 --- a/Source/Windows/Device/energycontrolwnd.cpp +++ b/Source/Windows/Device/energycontrolwnd.cpp @@ -178,10 +178,22 @@ EnergyControlWnd::EnergyControlWnd(QWidget *parent) : QVBoxLayout *batParamLayout = new QVBoxLayout(batParamWidget); batParamLayout->setContentsMargins(0, 0, 0, 0); + QHBoxLayout *batParamLibRow = new QHBoxLayout(); + QLabel *batParamLibLabel = new QLabel("Library", this); + batParamLibLabel->setFixedSize(ENTRY_LABEL_WIDTH, ENTRY_ROW_HEIGHT); + batParamLibraryCombo = new QComboBox(this); + batParamLibraryCombo->setFixedHeight(ENTRY_ROW_HEIGHT); + batParamLibraryCombo->setMinimumWidth(ENTRY_EDIT_WIDTH + ENTRY_UNIT_WIDTH); + batParamLibraryCombo->setToolTip("Saved battery parameter waves. Select one to load its settings back into the fields and the region table."); + batParamLibRow->addWidget(batParamLibLabel); + batParamLibRow->addWidget(batParamLibraryCombo, 1); + batParamLibraryDeleteButton = createSmallButton("Delete", batParamLibRow); + batParamLayout->addLayout(batParamLibRow); + + connect(batParamLibraryCombo, QOverload::of(&QComboBox::activated), this, &EnergyControlWnd::onBatParamLibrarySelected); + connect(batParamLibraryDeleteButton, &QPushButton::clicked, this, &EnergyControlWnd::onBatParamLibraryDelete); + batParamLayout->addLayout(createEntryRow("Battery Capacity", "mAh", loadEntryEdits)); - batParamLayout->addLayout(createEntryRow("Extraction Accuracy", "%", loadEntryEdits)); - batParamLayout->addLayout(createEntryRow("Maximum Current", "mA", loadEntryEdits)); - batParamLayout->addLayout(createEntryRow("Pause Duration", "ms", loadEntryEdits)); batParamLayout->addLayout(createEntryRow("Marker Guard", "ms", loadEntryEdits)); QHBoxLayout *batParamRelaxRow = new QHBoxLayout(); @@ -197,25 +209,10 @@ EnergyControlWnd::EnergyControlWnd(QWidget *parent) : batParamRelaxRow->addStretch(); batParamLayout->addLayout(batParamRelaxRow); - batParamLayout->addLayout(createEntryRow("Relax Threshold", "mV", loadEntryEdits)); - batParamLayout->addLayout(createEntryRow("Relax Window", "s", loadEntryEdits)); - batParamLayout->addLayout(createEntryRow("Relax Filter", "ms", loadEntryEdits)); loadEntryEdits["Battery Capacity"]->setText("500"); - loadEntryEdits["Extraction Accuracy"]->setText("1"); - loadEntryEdits["Maximum Current"]->setText("1000"); - loadEntryEdits["Pause Duration"]->setText("1000"); loadEntryEdits["Marker Guard"]->setText("1"); - loadEntryEdits["Relax Threshold"]->setText("5"); - loadEntryEdits["Relax Window"]->setText("60"); - loadEntryEdits["Relax Filter"]->setText("1000"); loadEntryEdits["Battery Capacity"]->setToolTip("Nominal battery capacity"); - loadEntryEdits["Extraction Accuracy"]->setToolTip("Charge extracted by a single pulse, in percent of the battery capacity"); - loadEntryEdits["Maximum Current"]->setToolTip("Pulse amplitude, pause is always 0 mA"); - loadEntryEdits["Pause Duration"]->setToolTip("Relaxation time between two pulses"); loadEntryEdits["Marker Guard"]->setToolTip("Distance between a current step and the marker that follows it.\nKeeps every marker inside a settled level instead of on the step itself.\nMust cover the load response time, a few sample periods at least"); - loadEntryEdits["Relax Threshold"]->setToolTip("Voltage span allowed inside the relaxation window, the pause ends when the battery stays within it"); - loadEntryEdits["Relax Window"]->setToolTip("Time window the voltage has to stay inside the threshold before the pause is ended"); - loadEntryEdits["Relax Filter"]->setToolTip("Voltage is averaged over this window, in milliseconds, before it is compared with the threshold.\nThe averaged voltage is drawn over the live voltage plot.\n0 turns the filter off"); batParamInfoLabel = new QLabel(this); batParamInfoLabel->setStyleSheet("color: gray;"); @@ -224,26 +221,44 @@ EnergyControlWnd::EnergyControlWnd(QWidget *parent) : batParamSaveWaveButton->setToolTip("Save generated wave to library for later use"); loadButtons.insert("SaveBatParamWave", batParamSaveWaveButton); batParamSaveRow->addWidget(batParamInfoLabel, 1); + batParamAddRegionButton = createSmallButton("Add Region", batParamSaveRow); + batParamRemoveRegionButton = createSmallButton("Remove Region", batParamSaveRow); + batParamClearRegionButton = createSmallButton("Clear", batParamSaveRow); batParamLayout->addLayout(batParamSaveRow); connect(batParamSaveWaveButton, &QPushButton::clicked, this, &EnergyControlWnd::onLoadWaveSave); - - batParamTable = createWaveTable(false); + connect(batParamAddRegionButton, &QPushButton::clicked, this, &EnergyControlWnd::onBatParamAddRegion); + connect(batParamRemoveRegionButton, &QPushButton::clicked, this, &EnergyControlWnd::onBatParamRemoveRegion); + connect(batParamClearRegionButton, &QPushButton::clicked, this, &EnergyControlWnd::onBatParamClearRegions); + + batParamTable = new QTableWidget(0, 8, this); + QStringList batParamRegionHeader; + batParamRegionHeader << "SoC hi [%]" << "SoC lo [%]" << "Acc [%]" << "Amp [mA]" + << "Pause [ms]" << "R thr [mV]" << "R win [s]" << "R filt [ms]"; + batParamTable->setHorizontalHeaderLabels(batParamRegionHeader); + batParamTable->horizontalHeader()->setMinimumSectionSize(40); + batParamTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); + batParamTable->horizontalHeader()->setStretchLastSection(true); + batParamTable->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + batParamTable->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); + batParamTable->verticalHeader()->setDefaultSectionSize(22); + batParamTable->setSelectionBehavior(QAbstractItemView::SelectRows); + batParamTable->setMinimumHeight(140); + batParamTable->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + batParamTable->setToolTip("Extraction regions over the state of charge. Each row is a SoC range with its own accuracy, amplitude, pause and relaxation.\nThe region matching the current state of charge is used for the next pulse.\nColumns: SoC high %, SoC low %, accuracy %, amplitude mA, pause ms, relax threshold mV, relax window s, relax filter ms."); batParamLayout->addWidget(batParamTable, 1); + batParamRegionsInit(); + batParamWidget->setVisible(false); loadTopLayout->addWidget(batParamWidget); connect(loadEntryEdits["Battery Capacity"], &QLineEdit::textChanged, this, &EnergyControlWnd::onBatParamChanged); - connect(loadEntryEdits["Extraction Accuracy"], &QLineEdit::textChanged, this, &EnergyControlWnd::onBatParamChanged); - connect(loadEntryEdits["Maximum Current"], &QLineEdit::textChanged, this, &EnergyControlWnd::onBatParamChanged); - connect(loadEntryEdits["Pause Duration"], &QLineEdit::textChanged, this, &EnergyControlWnd::onBatParamChanged); connect(loadEntryEdits["Marker Guard"], &QLineEdit::textChanged, this, &EnergyControlWnd::onBatParamChanged); - connect(loadEntryEdits["Relax Threshold"], &QLineEdit::textChanged, this, &EnergyControlWnd::onBatParamChanged); - connect(loadEntryEdits["Relax Window"], &QLineEdit::textChanged, this, &EnergyControlWnd::onBatParamChanged); - connect(loadEntryEdits["Relax Filter"], &QLineEdit::textChanged, this, &EnergyControlWnd::onBatParamChanged); + connect(batParamTable, &QTableWidget::cellChanged, this, &EnergyControlWnd::onBatParamChanged); connect(batParamRelaxCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(onBatParamChanged())); refreshCustomWaveLibraryCombo(); + refreshBatParamLibraryCombo(); updateStdWaveInfo(); updateCustomWaveInfo(); updateBatParamInfo(); @@ -331,7 +346,21 @@ EnergyControlWnd::EnergyControlWnd(QWidget *parent) : chargerTopLayout->addLayout(createSectionHeader("Parameters")); chargerTopLayout->addLayout(createEntryRow("Current", "mA", chargerEntryEdits)); chargerTopLayout->addLayout(createEntryRow("Term Voltage", "V", chargerEntryEdits)); - chargerTopLayout->addLayout(createEntryRow("Term Current", "%", chargerEntryEdits)); + QHBoxLayout *termCurrentRow = new QHBoxLayout(); + QLabel *termCurrentLabel = new QLabel("Term Current", this); + termCurrentLabel->setObjectName("Term CurrentLabel"); + termCurrentLabel->setFixedSize(ENTRY_LABEL_WIDTH, ENTRY_ROW_HEIGHT); + chargerTermCurrentCombo = new QComboBox(this); + chargerTermCurrentCombo->setObjectName("Term CurrentComboBox"); + chargerTermCurrentCombo->setFixedSize(ENTRY_EDIT_WIDTH + ENTRY_UNIT_WIDTH, ENTRY_ROW_HEIGHT); + chargerTermCurrentCombo->addItem("Disabled", 0); + chargerTermCurrentCombo->addItem("5 %", 5); + chargerTermCurrentCombo->addItem("10 %", 10); + chargerTermCurrentCombo->addItem("20 %", 20); + termCurrentRow->addWidget(termCurrentLabel); + termCurrentRow->addWidget(chargerTermCurrentCombo); + termCurrentRow->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Minimum)); + chargerTopLayout->addLayout(termCurrentRow); chargerTopLayout->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding)); chargerTopLayout->addLayout(createButtonRow("Set", "Set", chargerButtons)); chargerTopLayout->addLayout(createButtonRow("StartStop", "Start", chargerButtons)); @@ -342,12 +371,12 @@ EnergyControlWnd::EnergyControlWnd(QWidget *parent) : connect(chargerEntryEdits["Current"], &QLineEdit::textChanged, this, &EnergyControlWnd::onChargerEntryChanged); connect(chargerEntryEdits["Term Voltage"], &QLineEdit::textChanged, this, &EnergyControlWnd::onChargerEntryChanged); - connect(chargerEntryEdits["Term Current"], &QLineEdit::textChanged, this, &EnergyControlWnd::onChargerEntryChanged); + chargerTermCurrentChanged = false; + connect(chargerTermCurrentCombo, QOverload::of(&QComboBox::currentIndexChanged), this, [this](int){ chargerTermCurrentChanged = true; }); // Initialize all entries as "not changed" chargerEntryChanged["Current"] = false; chargerEntryChanged["Term Voltage"] = false; - chargerEntryChanged["Term Current"] = false; connect(chargerButtons["Set"], &QPushButton::clicked, this, &EnergyControlWnd::onChargingConfigSet); connect(chargerButtons["StartStop"], &QPushButton::clicked, this, &EnergyControlWnd::onChargingStartStop); @@ -423,6 +452,7 @@ EnergyControlWnd::EnergyControlWnd(QWidget *parent) : paramLeftLayout->addLayout(createEntryRow("Charge Current", "mA", chdischEntryEdits)); paramLeftLayout->addLayout(createTimeEntryRow("Charge Relax Time", chdischTimeEdits)); paramLeftLayout->addLayout(createEntryRow("Cycles", "", chdischEntryEdits)); + chdischEntryEdits["Cycles"]->setText("1"); // --- Right side: radio buttons ("Start with") --- QVBoxLayout *paramRightLayout = new QVBoxLayout(); @@ -430,8 +460,13 @@ EnergyControlWnd::EnergyControlWnd(QWidget *parent) : QStringList radioNames = {"Discharge", "Charge"}; paramRightLayout->addLayout(createRadioButtonRow("Start with", 2, radioNames, chdischDirectionGroups)); paramRightLayout->addLayout(createCheckButtonRow("Write To File", chdischCheckBox)); + paramRightLayout->addLayout(createCheckButtonRow("Charge Markers", chdischCheckBox)); + chdischCheckBox["Charge Markers"]->setToolTip("Place Charge Start / Charge End markers and report the mAh charged into the battery between them"); paramRightLayout->addStretch(); + connect(chdischCheckBox["Charge Markers"], &QCheckBox::toggled, + this, &EnergyControlWnd::sigChargeMarkersEnabled); + connect(chdischDirectionGroups["Start with"], QOverload::of(&QButtonGroup::buttonClicked), this, &EnergyControlWnd::onChdischDirectionChanged); connect(chdischCheckBox["Write To File"], &QCheckBox::toggled, @@ -987,6 +1022,9 @@ void EnergyControlWnd::chDischStartDischargeRelaxTimeout() connect(chdischDischargeRelaxTimer, &QTimer::timeout, this, &EnergyControlWnd::onChDschDischargeRelaxTick); } + chdischDischargeRelaxRemaining = chdischTimeEdits["Discharge Relax Time"]->time(); + chdischTimeEdits["Discharge Relax Timeout"]->setTime(chdischDischargeRelaxRemaining); + chdischDischargeRelaxTimer->start(); } @@ -1003,6 +1041,9 @@ void EnergyControlWnd::chDischStartChargeRelaxTimeout() connect(chdischChargeRelaxTimer, &QTimer::timeout, this, &EnergyControlWnd::onChDschChargeRelaxTick); } + chdischChargeRelaxRemaining = chdischTimeEdits["Charge Relax Time"]->time(); + chdischTimeEdits["Charge Relax Timeout"]->setTime(chdischChargeRelaxRemaining); + chdischChargeRelaxTimer->start(); } @@ -1158,7 +1199,6 @@ bool EnergyControlWnd::chdischDoneCurrentStep() bool EnergyControlWnd::chdischMoveToNextStep() { - QTime now = QTime::currentTime(); if(chdischCycleSteps[chdischCurrentStepIndex].status != StepDone) return false; chdischCurrentStepIndex += 1; if(chdischCurrentStepIndex == 4) @@ -1166,7 +1206,15 @@ bool EnergyControlWnd::chdischMoveToNextStep() chdischCycleCompleted(); return true; } - else + chdischStartStep(); + chdischCycleSteps[chdischCurrentStepIndex].status = StepOngoing; + chdischUpdateCycleStatusSteps(chdischCycleSteps); + return true; +} + +void EnergyControlWnd::chdischStartStep() +{ + QTime now = QTime::currentTime(); { if(chdischCycleSteps[chdischCurrentStepIndex].state == ChDschCharge) { @@ -1237,13 +1285,23 @@ bool EnergyControlWnd::chdischMoveToNextStep() chDischStartDischargeRelaxTimeout(); } } - chdischCycleSteps[chdischCurrentStepIndex].status = StepOngoing; - chdischUpdateCycleStatusSteps(chdischCycleSteps); - return true; } void EnergyControlWnd::chdischCycleCompleted() { + chdischCyclesDone += 1; + if(chdischCyclesDone < chdischCyclesTotal) + { + for(int i = 0; i < 4; i++) + { + chdischCycleSteps[i].status = StepUnknown; + } + chdischCurrentStepIndex = 0; + chdischStartStep(); + chdischCycleSteps[chdischCurrentStepIndex].status = StepOngoing; + chdischUpdateCycleStatusSteps(chdischCycleSteps); + return; + } chdischStartStatusSet(false, ChDschUnknown); if(chdischCheckBox["Write To File"]->isChecked()) { @@ -1285,7 +1343,7 @@ void EnergyControlWnd::underVoltageStatusSet(bool enabled) break; break; case ModeChDisch: - if(chdischStartStopStatus && uVoltage) + if(chdischStartStopStatus && uVoltage && chdischCycleSteps[chdischCurrentStepIndex].state == ChDschDischarge) { chdischDoneCurrentStep(); chdischMoveToNextStep(); @@ -1425,6 +1483,7 @@ bool EnergyControlWnd::loadCurrentStatusSet(bool status) } loadStartStopStatus = status; loadButtons["Set"]->setEnabled(!loadStartStopStatus); + emit sigBatParamExtractionRunning(status && (loadModeGet() == LoadModeBatParamExtraction)); if(loadStartStopStatus) { loadButtons["StartStop"]->setText("Stop"); @@ -1507,9 +1566,10 @@ void EnergyControlWnd::chargerTermVoltageSet(float voltage) void EnergyControlWnd::chargerTermCurrentSet(int current) { - chargerEntryEdits["Term Current"]->blockSignals(true); - chargerEntryEdits["Term Current"]->setText(QString::number(current)); - chargerEntryEdits["Term Current"]->blockSignals(false); + chargerTermCurrentCombo->blockSignals(true); + int idx = chargerTermCurrentCombo->findData(current); + if(idx >= 0) chargerTermCurrentCombo->setCurrentIndex(idx); + chargerTermCurrentCombo->blockSignals(false); } bool EnergyControlWnd::chargerCurrentStatusSet(bool status) @@ -1533,7 +1593,7 @@ bool EnergyControlWnd::chargerCurrentStatusSet(bool status) chargerTimeEdits["Charging Stop Time"]->setEnabled(false); chargerEntryEdits["Current"]->setEnabled(false); chargerEntryEdits["Term Voltage"]->setEnabled(false); - chargerEntryEdits["Term Current"]->setEnabled(false); + chargerTermCurrentCombo->setEnabled(false); statusControlButtons["LoadDisable"]->setEnabled(false); statusControlButtons["PPathDisable"]->setEnabled(false); @@ -1554,7 +1614,7 @@ bool EnergyControlWnd::chargerCurrentStatusSet(bool status) chargerTimeEdits["Charging Stop Time"]->setTime(now); chargerEntryEdits["Current"]->setEnabled(true); chargerEntryEdits["Term Voltage"]->setEnabled(true); - chargerEntryEdits["Term Current"]->setEnabled(true); + chargerTermCurrentCombo->setEnabled(true); statusControlButtons["LoadDisable"]->setEnabled(true); statusControlButtons["PPathDisable"]->setEnabled(true); @@ -1585,12 +1645,12 @@ void EnergyControlWnd::chargingDone() QMessageBox *msgBox = new QMessageBox(this); switch(mode){ case ModeCharge: - msgBox->setIcon(QMessageBox::Warning); - msgBox->setWindowTitle("Warning"); + msgBox->setIcon(QMessageBox::Information); + msgBox->setWindowTitle("Charging"); + msgBox->setText("Charging completed"); if(chargingStartStopStatus) { emit sigChargingCurrentStatusChanged(false); - msgBox->setText("Charging completed"); } msgBox->setStandardButtons(QMessageBox::Ok); msgBox->show(); @@ -1598,7 +1658,7 @@ void EnergyControlWnd::chargingDone() break; break; case ModeChDisch: - if(chdischStartStopStatus) + if(chdischStartStopStatus && chdischCycleSteps[chdischCurrentStepIndex].state == ChDschCharge) { chdischDoneCurrentStep(); chdischMoveToNextStep(); @@ -1737,10 +1797,17 @@ bool EnergyControlWnd::chdischStartStatusSet(bool status, ChDschState state) chdischEntryEdits["Charge Current"]->setEnabled(false); chdischEntryEdits["Cycles"]->setEnabled(false); + chdischCyclesTotal = chdischEntryEdits["Cycles"]->text().toInt(); + if(chdischCyclesTotal < 1) chdischCyclesTotal = 1; + chdischCyclesDone = 0; + statusControlButtons["LoadDisable"]->setEnabled(false); statusControlButtons["PPathDisable"]->setEnabled(false); statusControlButtons["BatteryDisable"]->setEnabled(false); + if(chdischChargeRelaxTimer) chdischChargeRelaxTimer->stop(); + if(chdischDischargeRelaxTimer) chdischDischargeRelaxTimer->stop(); + chdischDischargeRelaxRemaining = chdischTimeEdits["Discharge Relax Time"]->time(); chdischTimeEdits["Discharge Relax Timeout"]->setTime(chdischDischargeRelaxRemaining); @@ -1755,6 +1822,12 @@ bool EnergyControlWnd::chdischStartStatusSet(bool status, ChDschState state) setTabControlsEnabled(loadTab, false); setTabControlsEnabled(chargerTab, false); + if(chdischDischargeIsBatParam()) + { + batParamViewButton->setVisible(false); + batParamViewButton->setEnabled(true); + } + chdischCycleSteps[chdischCurrentStepIndex].status = StepOngoing; chdischUpdateCycleStatusSteps(chdischCycleSteps); } @@ -1775,14 +1848,14 @@ bool EnergyControlWnd::chdischStartStatusSet(bool status, ChDschState state) chdischTimeEdits["Discharge Stop Time"]->setTime(now); chdischDischargeStop(); } - if(chdischCycleStartStep.state == ChDschChargeRelax) - { - chdischChargeRelaxTimer->stop(); - } - if(chdischCycleStartStep.state == ChDschDischargeRelax) - { - chdischDischargeRelaxTimer->stop(); - } + if(chdischChargeRelaxTimer) chdischChargeRelaxTimer->stop(); + if(chdischDischargeRelaxTimer) chdischDischargeRelaxTimer->stop(); + + chdischChargeRelaxRemaining = chdischTimeEdits["Charge Relax Time"]->time(); + chdischTimeEdits["Charge Relax Timeout"]->setTime(chdischChargeRelaxRemaining); + chdischDischargeRelaxRemaining = chdischTimeEdits["Discharge Relax Time"]->time(); + chdischTimeEdits["Discharge Relax Timeout"]->setTime(chdischDischargeRelaxRemaining); + chdischTimeEdits["Discharge Relax Time"]->setEnabled(true); chdischTimeEdits["Charge Relax Time"]->setEnabled(true); chdischComboBoxEdits["Discharge Profile"]->setEnabled(true); @@ -1799,6 +1872,10 @@ bool EnergyControlWnd::chdischStartStatusSet(bool status, ChDschState state) setTabControlsEnabled(loadTab, true); setTabControlsEnabled(chargerTab, true); + + batParamViewButton->setEnabled(false); + batParamViewButton->setVisible(false); + if(chdischCurrentStepIndex < 4) { chdischCycleSteps[chdischCurrentStepIndex].status = StepDone; @@ -1886,7 +1963,7 @@ void EnergyControlWnd::onLoadModeChanged(const QString &mode) standardWaveWidget->setVisible(mode == "Standard Wave"); customWaveWidget->setVisible(mode == "Custom Wave"); batParamWidget->setVisible(mode == "Bat Param Extraction"); - batParamViewButton->setVisible(mode == "Bat Param Extraction"); + batParamViewButton->setVisible(false); } LoadMode EnergyControlWnd::loadModeGet() @@ -1983,9 +2060,103 @@ QString EnergyControlWnd::getCustomWaveLibraryName(int index) void EnergyControlWnd::onWaveLibraryChanged() { refreshCustomWaveLibraryCombo(); + refreshBatParamLibraryCombo(); chdischRefreshLibraryCombo(); } +void EnergyControlWnd::refreshBatParamLibraryCombo() +{ + QString current = batParamLibraryCombo->currentText(); + QList waves = WaveformLibrary::instance().getWaves(); + int index; + + batParamLibraryCombo->blockSignals(true); + batParamLibraryCombo->clear(); + batParamLibraryCombo->addItem("