[persistence] improve building the ItemHistoryDTO (#4194)

Signed-off-by: Jörg Sautter <joerg.sautter@gmx.net>
This commit is contained in:
joerg1985
2024-04-21 21:21:03 +02:00
committed by GitHub
parent 10a20af50c
commit ba463dd7e6
3 changed files with 19 additions and 10 deletions
@@ -406,7 +406,6 @@ public class PersistenceResource implements RESTResource {
}
Iterable<HistoricItem> result;
State state;
long quantity = 0L;
@@ -446,23 +445,24 @@ public class PersistenceResource implements RESTResource {
Iterator<HistoricItem> it = result.iterator();
// Iterate through the data
HistoricItem lastItem = null;
State lastState = null;
while (it.hasNext()) {
HistoricItem historicItem = it.next();
state = historicItem.getState();
State state = historicItem.getState();
long timestamp = historicItem.getTimestamp().toInstant().toEpochMilli();
// For 'binary' states, we need to replicate the data
// to avoid diagonal lines
if (state instanceof OnOffType || state instanceof OpenClosedType) {
if (lastItem != null) {
dto.addData(historicItem.getTimestamp().toInstant().toEpochMilli(), lastItem.getState());
if (lastState != null && !lastState.equals(state)) {
dto.addData(timestamp, lastState);
quantity++;
}
}
dto.addData(historicItem.getTimestamp().toInstant().toEpochMilli(), state);
dto.addData(timestamp, state);
quantity++;
lastItem = historicItem;
lastState = state;
}
if (boundary) {
@@ -15,6 +15,7 @@ package org.openhab.core.persistence.dto;
import java.util.ArrayList;
import java.util.List;
import org.openhab.core.library.types.DecimalType;
import org.openhab.core.library.types.QuantityType;
import org.openhab.core.types.State;
@@ -41,12 +42,15 @@ public class ItemHistoryDTO {
* @param time the time of the record
* @param state the state at this time
*/
public void addData(Long time, State state) {
public void addData(long time, State state) {
HistoryDataBean newVal = new HistoryDataBean();
newVal.time = time;
if (state instanceof QuantityType quantityState) {
// we strip the unit from the state, since historic item states are expected to be all in the default unit
newVal.state = quantityState.toBigDecimal().toString();
} else if (state instanceof DecimalType decimalType) {
// use BigDecimal.toString() to hit the internal cache
newVal.state = decimalType.toBigDecimal().toString();
} else {
newVal.state = state.toString();
}
@@ -54,7 +58,7 @@ public class ItemHistoryDTO {
}
public static class HistoryDataBean {
public Long time;
public long time;
public String state;
}
}
@@ -358,7 +358,12 @@ public class QuantityType<T extends Quantity<T>> extends Number
}
public BigDecimal toBigDecimal() {
return new BigDecimal(quantity.getValue().toString());
Number value = quantity.getValue();
if (value instanceof BigDecimal decimal) {
return decimal;
} else {
return new BigDecimal(value.toString());
}
}
@Override