Hi there!
I’m automatically persisting all items which are in a specific group. For all such items I basically run the follwing script:
(function (context) {
var logger = Java.type('org.slf4j.LoggerFactory').getLogger('org.openhab.model.script.Rules.Persistor');
Number.isNaN = Number.isNaN || function(value) {
return value !== value
}
var hasNumber = function(item) {
return !isNaN(parseFloat(item.state))
}
var isConvertibleToNumber = function(item) {
var Transformation = Java.type("org.openhab.core.transform.actions.Transformation")
var transformedState = Transformation.transform("MAP", "persistor.map", item.state.toString())
if (!isNaN(transformedState)) {
return true
} else {
logger.error("item " + item.name + " not persitable, state=" + item.state)
return false
}
}
context.persistItemState = function (item) {
if (!hasNumber(item) && !isConvertibleToNumber(item)) {
logger.error(item.name + " is no number but " + parsedState + " (was: " + item.state + "), skipping!")
} else {
var persistence = Java.type("org.openhab.core.persistence.extensions.PersistenceExtensions")
persistence.persist(item, "influxdb")
persistence.persist(item, "mapdb")
persistence.persist(item)
logger.debug("Item changed: " + item.name + ", persisted value " + item.state + " to InfluxDB, MapDB and default persistence")
}
}
})(this)
In my persistor.map
I’ve the following entries:
ON=1
OFF=0
OPEN=1
CLOSED=0
The problem I wanted to solve with this is this: Sometimes I see that a number value cannot be persisted in InfluxDB (exception from the persistence layer) because it previously tried to persist a string:
[ERROR] [org.influxdb.impl.BatchProcessor ] - Batch could not be sent. Data will be lost
org.influxdb.InfluxDBException$FieldTypeConflictException: partial write: field type conflict: input field "value" on measurement "light-brightness-percent" is type float, already exists as type string dropped=2
at org.influxdb.InfluxDBException.buildExceptionFromErrorMessage(InfluxDBException.java:144) ~[bundleFile:?]
I assume it was something like NULL
or UNDEF
. So I decided to do a check before persisting.
I did the mapping check because my number conversion check does not work for switches and contacts although in InfluxDB I see Integer values instead of Strings.
But doing that mapping check is a rather big smell in the code since it couples the inner workings of the persistence layer to my map. My question is if there’s a better way to prevent my initial problem.
Best regards,
ceedee