Parsing an MQTT message in rules

Once you have the value stored in an integer you might want to implement something like this in the rule instead of checkKthBit.

Items:

Switch      Port8       "Port 8" 
Switch      Port7       "Port 7" 
Switch      Port6       "Port 6" 
Switch      Port5       "Port 5" 
Switch      Port4       "Port 4"   
Switch      Port3       "Port 3" 
Switch      Port2       "Port 2" 
Switch      Port1       "Port 1"

Rule:

//  AllBits must be defined as an integer.  The value from MQTT will be store here
var Integer AllBits  

when ???? changed 
then
    // Place the value from the REGEX in AllBits (possibly converting to an integer beforehand)
    
    if (AllBits >= 128 ) {
        Port8.postUpdate(ON)
        AllBits = AllBits - 128
    }
    else {
        Port8.postUpdate(OFF)
    }
    if (AllBits >= 64 ) {
        Port7.postUpdate(ON)
        AllBits = AllBits - 64
    }
    else {
        Port7.postUpdate(OFF)
    }
    if (AllBits >= 32 ) {
        Port6.postUpdate(ON)
        AllBits = AllBits - 32
    }
    else {
        Port6.postUpdate(OFF)
    }
    }if (AllBits >= 16 ) {
        Port5.postUpdate(ON)
        AllBits = AllBits - 16
    }
    else {
        Port5.postUpdate(OFF)
    }
    if (AllBits >= 8 ) {
        Port4.postUpdate(ON)
        AllBits = AllBits - 8
    }
    else {
        Port4.postUpdate(OFF)
    }
    if (AllBits >= 4 ) {
        Port3.postUpdate(ON)
        AllBits = AllBits - 4
    }
    else {
        Port3.postUpdate(OFF)
    }
    if (AllBits >= 2 ) {
        Port2.postUpdate(ON)
        AllBits = AllBits - 2
    }
    else {
        Port2.postUpdate(OFF)
    }
    if (AllBits >= 1 ) {
        Port1.postUpdate(ON)
        AllBits = AllBits - 1
    }
    else {
        Port1.postUpdate(OFF)
    }
end

I haven’t tested this but VSC shows no syntax errors. Its not as elegant as checkKthBit but easier to understand (IMO)

1 Like