This repository has been archived by the owner on May 7, 2020. It is now read-only.
/
QuantityType.java
378 lines (332 loc) · 13.8 KB
/
QuantityType.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
/**
* Copyright (c) 2014,2018 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.smarthome.core.library.types;
import static org.eclipse.jdt.annotation.DefaultLocation.*;
import java.math.BigDecimal;
import java.util.IllegalFormatConversionException;
import javax.measure.Dimension;
import javax.measure.IncommensurableException;
import javax.measure.Quantity;
import javax.measure.UnconvertibleException;
import javax.measure.Unit;
import javax.measure.UnitConverter;
import javax.measure.quantity.Dimensionless;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.eclipse.smarthome.core.library.unit.SmartHomeUnits;
import org.eclipse.smarthome.core.types.Command;
import org.eclipse.smarthome.core.types.PrimitiveType;
import org.eclipse.smarthome.core.types.State;
import org.eclipse.smarthome.core.types.UnDefType;
import org.eclipse.smarthome.core.types.util.UnitUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tec.uom.se.AbstractUnit;
import tec.uom.se.quantity.Quantities;
/**
* The measure type extends DecimalType to handle physical unit measurement
*
* @author Gaël L'hopital - Initial contribution
*
*/
@NonNullByDefault({ PARAMETER, RETURN_TYPE, FIELD, TYPE_ARGUMENT }) // TYPE_BOUNDS can not be used here since
// javax.measure.quantity.* interfaces are not
// annotated.
public class QuantityType<T extends Quantity<T>> extends Number
implements PrimitiveType, State, Command, Comparable<QuantityType<T>> {
private final Logger logger = LoggerFactory.getLogger(QuantityType.class);
private static final long serialVersionUID = 8828949721938234629L;
private static final BigDecimal HUNDRED = BigDecimal.valueOf(100);
public static final QuantityType<Dimensionless> ZERO = new QuantityType<>(0, AbstractUnit.ONE);
public static final QuantityType<Dimensionless> ONE = new QuantityType<>(1, AbstractUnit.ONE);
// Regular expression to split unit from value
// split on any blank character, even none (\\s*) which occurs after a digit (?<=\\d) and before
// a "unit" character ?=[a-zA-Z°µ%'] which itself must not be preceded by plus/minus digit (?![\\+\\-]?\\d).
// The later would be an exponent from the scalar value.
private static final String UNIT_PATTERN = "(?<=\\d)\\s*(?=[a-zA-Z°µ%'](?![\\+\\-]?\\d))";
private final Quantity<T> quantity;
/**
* Creates a new {@link QuantityType} with the given value. The value may contain a unit. The specific
* {@link Quantity} is obtained by {@link Quantities#getQuantity(CharSequence)}.
*
* @param value the non null value representing a quantity with an optional unit.
*/
@SuppressWarnings("unchecked")
public QuantityType(String value) {
String[] constituents = value.split(UNIT_PATTERN);
// getQuantity needs a space between numeric value and unit
String formatted = String.join(" ", constituents);
quantity = (Quantity<T>) Quantities.getQuantity(formatted);
}
/**
* Creates a new {@link QuantityType} with the given value and {@link Unit}.
*
* @param value the non null measurement value.
* @param unit the non null measurement unit.
* @param conversionUnits the optional unit map which is used to determine the {@link MeasurementSystem} specific
* unit for conversion.
*/
public QuantityType(Number value, Unit<T> unit) {
// Avoid scientific notation for double
BigDecimal bd = new BigDecimal(value.toString());
quantity = (Quantity<T>) Quantities.getQuantity(bd, unit);
}
/**
* Private constructor for arithmetic operations.
*
* @param quantity the {@link Quantity} for the new {@link QuantityType}.
*/
private QuantityType(Quantity<T> quantity) {
this.quantity = quantity;
}
/**
* Static access to {@link QuantityType#QuantityType(double, Unit)}.
*
* @param value the non null measurement value.
* @param unit the non null measurement unit.
* @return a new {@link QuantityType}
*/
public static <T extends Quantity<T>> QuantityType<T> valueOf(double value, Unit<T> unit) {
return new QuantityType<T>(value, unit);
}
@Override
public String toString() {
return toFullString();
}
public static QuantityType<? extends Quantity<?>> valueOf(String value) {
return new QuantityType<>(value);
}
@SuppressWarnings("unchecked")
@Override
public boolean equals(@Nullable Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof QuantityType)) {
return false;
}
QuantityType<?> other = (QuantityType<?>) obj;
if (!quantity.getUnit().getDimension().equals(other.quantity.getUnit().getDimension())) {
return false;
} else if (compareTo((QuantityType<T>) other) != 0) {
return false;
}
return true;
}
@Override
public int compareTo(QuantityType<T> o) {
if (quantity.getUnit().isCompatible(o.quantity.getUnit())) {
QuantityType<T> v1 = this.toUnit(getUnit().getSystemUnit());
QuantityType<?> v2 = o.toUnit(o.getUnit().getSystemUnit());
if (v1 != null && v2 != null) {
return Double.compare(v1.doubleValue(), v2.doubleValue());
} else {
throw new IllegalArgumentException("Unable to convert to system unit during compare.");
}
} else {
throw new IllegalArgumentException("Can not compare incompatible units.");
}
}
public Unit<T> getUnit() {
return quantity.getUnit();
}
public Dimension getDimension() {
return getUnit().getDimension();
}
/**
* Convert this QuantityType to a new {@link QuantityType} using the given target unit.
*
* @param targetUnit the unit to which this {@link QuantityType} will be converted to.
* @return the new {@link QuantityType} in the given {@link Unit} or {@code null} in case of a
*/
@SuppressWarnings("unchecked")
public @Nullable QuantityType<T> toUnit(Unit<?> targetUnit) {
if (!targetUnit.equals(getUnit())) {
try {
UnitConverter uc = getUnit().getConverterToAny(targetUnit);
Quantity<?> result = Quantities.getQuantity(uc.convert(quantity.getValue()), targetUnit);
return new QuantityType<T>(result.getValue(), (Unit<T>) targetUnit);
} catch (UnconvertibleException | IncommensurableException e) {
logger.debug("Unable to convert unit from {} to {}", getUnit(), targetUnit);
return null;
}
}
return this;
}
@SuppressWarnings("unchecked")
public @Nullable QuantityType<T> toUnit(String targetUnit) {
Unit<T> unit = (Unit<T>) AbstractUnit.parse(targetUnit);
if (unit != null) {
return toUnit(unit);
}
return null;
}
public BigDecimal toBigDecimal() {
return new BigDecimal(quantity.getValue().toString());
}
@Override
public int hashCode() {
final int prime = 31;
int tmp = prime * getUnit().hashCode();
tmp += prime * (quantity.getValue() == null ? 0 : quantity.getValue().hashCode());
return tmp;
}
@Override
public String format(@Nullable String pattern) {
String formatPattern = pattern;
if (formatPattern != null && formatPattern.contains(UnitUtils.UNIT_PLACEHOLDER)) {
String unitSymbol = getUnit().equals(SmartHomeUnits.PERCENT) ? "%%" : getUnit().toString();
formatPattern = formatPattern.replace(UnitUtils.UNIT_PLACEHOLDER, unitSymbol);
}
// The value could be an integer value. Try to convert to BigInteger in
// order to have access to more conversion formats.
try {
return String.format(formatPattern, toBigDecimal().toBigIntegerExact());
} catch (ArithmeticException ae) {
// Could not convert to integer value without loss of
// information. Fall through to default behavior.
} catch (IllegalFormatConversionException ifce) {
// The conversion is not valid for the type BigInteger. This
// happens, if the format is like "%.1f" but the value is an
// integer. Fall through to default behavior.
}
return String.format(formatPattern, toBigDecimal());
}
@Override
public int intValue() {
return quantity.getValue().intValue();
}
@Override
public long longValue() {
return quantity.getValue().longValue();
}
@Override
public float floatValue() {
return quantity.getValue().floatValue();
}
@Override
public double doubleValue() {
return quantity.getValue().doubleValue();
}
@Override
public String toFullString() {
return quantity.toString();
}
@Override
public State as(@Nullable Class<? extends @Nullable State> target) {
if (target == OnOffType.class) {
if (intValue() == 0) {
return OnOffType.OFF;
} else if (SmartHomeUnits.PERCENT.equals(getUnit())) {
return toBigDecimal().compareTo(BigDecimal.ZERO) > 0 ? OnOffType.ON : OnOffType.OFF;
} else if (toBigDecimal().compareTo(BigDecimal.ONE) == 0) {
return OnOffType.ON;
} else {
return UnDefType.UNDEF;
}
} else if (target == UpDownType.class) {
if (doubleValue() == 0) {
return UpDownType.UP;
} else if (toBigDecimal().compareTo(BigDecimal.ONE) == 0) {
return UpDownType.DOWN;
} else {
return UnDefType.UNDEF;
}
} else if (target == OpenClosedType.class) {
if (doubleValue() == 0) {
return OpenClosedType.CLOSED;
} else if (toBigDecimal().compareTo(BigDecimal.ONE) == 0) {
return OpenClosedType.OPEN;
} else {
return UnDefType.UNDEF;
}
} else if (target == HSBType.class) {
return new HSBType(DecimalType.ZERO, PercentType.ZERO,
new PercentType(this.toBigDecimal().multiply(HUNDRED)));
} else if (target == PercentType.class) {
if (SmartHomeUnits.PERCENT.equals(getUnit())) {
return new PercentType(toBigDecimal());
}
return new PercentType(toBigDecimal().multiply(HUNDRED));
} else if (target == DecimalType.class) {
return new DecimalType(toBigDecimal());
} else {
return State.super.as(target);
}
}
/**
* Returns the sum of the given {@link QuantityType} with this QuantityType.
*
* @param state the {@link QuantityType} to add to this QuantityType.
* @return the sum of the given {@link QuantityType} with this QuantityType.
*/
public QuantityType<T> add(QuantityType<T> state) {
return new QuantityType<T>(this.quantity.add(state.quantity));
}
/**
* Negates the value of this QuantityType leaving its unit untouched.
*
* @return the negated value of this QuantityType.
*/
public QuantityType<T> negate() {
return new QuantityType<>(quantity.multiply(-1));
}
/**
* Subtract the given {@link QuantityType} from this QuantityType.
*
* @param state the {@link QuantityType} to subtract from this QuantityType.
* @return the difference by subtracting the given {@link QuantityType} from this QuantityType.
*/
public QuantityType<T> subtract(QuantityType<T> state) {
return new QuantityType<T>(this.quantity.subtract(state.quantity));
}
/**
* Multiply this {@link QuantityType} by the given value.
*
* @param value the value this {@link QuantityType} should be multiplied with.
* @return the product of the given value with this {@link QuantityType}.
*/
public QuantityType<?> multiply(BigDecimal value) {
return new QuantityType<>(this.quantity.multiply(value));
}
/**
* Multiply this QuantityType by the given {@link QuantityType}.
*
* @param state the {@link QuantityType} with which this QuantityType should be multiplied with.
* @return the product of the given {@link QuantityType} and this QuantityType.
*/
public QuantityType<?> multiply(QuantityType<?> state) {
return new QuantityType<>(this.quantity.multiply(state.quantity));
}
/**
* Divide this QuantityType by the given value.
*
* @param value the value this {@link QuantityType} should be divided by.
* @return the quotient from this QuantityType and the given value.
*/
public QuantityType<?> divide(BigDecimal value) {
return new QuantityType<>(this.quantity.divide(value));
}
/**
* Divide this QuantityType by the given {@link QuantityType}.
*
* @param state the {@link QuantityType} this QuantityType should be divided by.
* @return the quotient from this QuantityType and the given {@link QuantityType}.
*/
public QuantityType<?> divide(QuantityType<?> state) {
return new QuantityType<>(this.quantity.divide(state.quantity));
}
}