Monoprice 6-zone Audio amp items, sitemap & rules

Nice code. I’m not posting this to say you should change anything, just some ideas that might help reduce the lines of code a bit.

  1. If you put all your MonoPrice_Satus Items into a Group, you can simplify your “MonoPrice Status on Command change” Rule in one of several ways. I’ll show how using a for loop:
    ...
    matcher.find()
    Thread::sleep(1000)
    for(var int i = 1; i <= MonoPrice_Statuses.members.size; i=i+1){
        postUpdate("MonoPrice_Status_G"+i, matcher.group(i))
    }

You could also apply some of the ideas from Design Pattern: Associated Items

  1. It makes no sense to declare pattern and matcher as global variables if you are going to recreate them every time your rule runs. Either set them to their value where you declare them as a global, or don’t declare them as global and declare them as local to the Rule. This applies to the other gloval variables. They should not be global unless their value needs to be used across multiple executions of the same rule or by more than one rule.

  2. A sleep of one second is starting to push the max you should sleep for in a Rule. I would use a Timer to avoid tieing up the execution thread.

    ...
    matcher.find()
    createTimer(now.plusSeconds(1), [|
        for(var int i = 1; i <= MonoPrice_Statuses.members.size; i=i+1){
            postUpdate("MonoPrice_Status_G"+i, matcher.group(i))
        }
    ]
  1. In your remaining rules it looks like we can apply some of the Associated Items concepts as well to eliminate some of the switch statements:
    if(MonoPrice_Status_G3.state == "01"){
        val int num = Integer::parseInt(MonoPrice_Status_G3.state.toString)
        postUpdate("MonoPrice_Z"+num+"_Power", "ON")
    }
    else {
        ...
  1. “Refresh Switch” can use the same for loop approach above to reduce the lines of code:
    for(var int i=11; i <= 16; i = i+1){
        AudioMTX.sendCommand("%3f"+i+"%0D%0A")
        Thread::sleep(1000)
        MonoPrice_Status.postUpdate(AudioMTX_Receive.state.toString.trim)
    }
  1. Replace all of the Group/Persistence hacks to get the Item that triggered the Rule with the new implicit variable triggeringItem where applicable. I’m not super clear on how all of this works together so it isn’t clear whether this is applicable.

Thanks for posting!

2 Likes