Convert Item String to Number

New to OH2, please appologize my dumbness…

I’m trying to use a timeline to monitor the usage of my Sonos system. In the following code, I’m trying to convert an item (Sonos_Speaker_State) which is a String type (PLAYING, PAUSED_PLAYBACK, …) into a Number type (0,1,2,…) to persist this into rrd4j so I can use a timeline into Habpanel.

Here is my Sonos.items :

String Sonos_Speaker_State "Sonos Player State" {channel="sonos:PLAY5:RINCON_B8E937F9993801400:state"}
Number Sonos_State_Number  "Sonos State Number"

Here is my rule to convert the String type to a Number type :

rule "Sonos State to Number"
when
	Item Sonos_Speaker_State changed 
then
	if(Sonos_Speaker_State.state=="PLAYING") {
	Sonos_State_Number=1
	}
	if(Sonos_Speaker_State.state=="PAUSED_PLAYBACK") {
	Sonos_State_Number=0
	}
end

Where is my mistake?

The log shows : “Rule ‘Sonos State to Number’: An error occurred during the script execution: Cannot assign a value in null context.”

Thank you for your help, OH2 beginner here…

You can’t just type

Item = value

Like when you assign a variable. To change the state of an item you need to use

Item.postUpdate(value)

So in your case

	if(Sonos_Speaker_State.state=="PLAYING") {
	Sonos_State_Number.postUpdate(1)
	}
	if(Sonos_Speaker_State.state=="PAUSED_PLAYBACK") {
	Sonos_State_Number.postUpdate(0)
	}

That’s it! Thanks for the quick reply! Works perfectly.

By the way, how can I syntax “Else” :

if(Sonos_Speaker_State.state=="PLAYING") {
	Sonos_State_Number.postUpdate(1)
	}
else    {
	Sonos_State_Number.postUpdate(0)
	}

Thanks for the help once again.

You can use an else if like this

	if(Sonos_Speaker_State.state=="PLAYING") {
	Sonos_State_Number.postUpdate(1)
	}
	else if(Sonos_Speaker_State.state=="PAUSED_PLAYBACK") {
	Sonos_State_Number.postUpdate(0)
	}

However, in your case (no pun intended) I would use a switch statement:

switch Sonos_Speaker_State.state {
    case "PLAYING":
        Sonos_State_Number.postUpdate(1)
    case "PAUSED_PLAYBACK":
        Sonos_State_Number.postUpdate(0)
}

Especially if you want to use more than two different cases.

1 Like

You may want to verify that you got the States correctly. From the documentation it appears that there is not state PLAYING or PAUSED_PLAYBACK, but rather PLAY and PAUSE