Mapping a string item to a number so it can be graphed

What is the correct way to map a String that is returned from a channel binding to a number, so that it can be graphed?

I have a binding where the underlying value is a String

String TeslaNumberState “nState [MAP(tesla.map):%s]” {channel=“tesla:models:1:state”}

The map file is simply:

online=2
asleep=0

But this keeps the value as a String. Ideally I would like to transform it to a Number and not a String, so that it can be persisted and graphed by rrd4j. I don’t see any easy way to do this.

Thanks.

First create a new “Dummy-Item”.

.items

Number TeslaState_num           "Tesla State as Number[%s]"     

an then create a Rule to make the Transformation.

.rules

rule "Tesla State String to Number"
  when
    Item TeslaNumberState changed
  then
  
  if (TeslaNumberState.state == "online"){
    TeslaState_num.postUpdate (2)
    return;
  }
   if (TeslaNumberState.state == "asleep"){
    TeslaState_num.postUpdate (0)
    return;
  }
end

I didn’t test it, but I think it should work.

1 Like

That approach works for me.

I use almost exactly that rule layout.

OFF = 0

ON = 10

Thanks. I did something like that. I was just wondering if there was a way to do it without creating a rule to set a new variable.

Not really. As a String-Item is a String-Item and remains a String-Item. A Number-Item is a Num…:wink:

Cheers,
Peter

You’re reliant on the binding supplying channels suitable for Items of this type or that type. Some bindings provide many choices, some few/none.

The new profile feature allows some manipulation between channel and Item, but I do not think it (yet) provides for this kind of mapping or transformation.

This is a quite old thread, but I just came across with the same question and found the solution based on this thread: JavaScript - Transformation Services missing in openhab 4

Mapping a string like true/false to a number to display it in a chart works well using a profile:

Number bs1_move "Wohnzimmer [%.0f]"  <motion> (gMove, gRRD4J) ["Presence"] {channel="mqtt:topic:zigbee2mqtt:Bewegungssensor_1:bs1_occupancy"[profile="transform:JS", toItemScript="bewegung2number.js"] }

The JS file looks like:

(function(i) {
    console.log("bewegung2number: %s", i)
    if (i == "false") {return 0}
    if (i == "true") {return 1}
    return 2
    })(input)

Maybe this will help others with a similar issue.