Please help me understand this programming concept


(Jeremy Whittaker) #1

All,

I wrote this app that unlocks the door when the sensor is opened. However, I noticed I can comment out the following line.

// subscribe(lock1, "unlock", doorUnlockedHandler, [filterEvents: false])

Why is it that I do not need to subscribe to the lock in order to unlock it? Do you only need to subscribe when you’re polling for statuses?

/**
 *  Unlock It When It Opens
 *
 *  Author: Jeremy R. Whittaker
 */
preferences {
	section("When the door opens..."){
		input "contact1", "capability.contactSensor", title: "Where?"
	}
	section("Unlock the lock...") {
		input "lock1","capability.lock", multiple: true
	}
}

def installed() {
	subscribe(contact1, "contact", contactHandler)
//    subscribe(lock1, "unlock", doorUnlockedHandler, [filterEvents: false])
}

def updated() {
	unsubscribe()
	subscribe(contact1, "contact", contactHandler)
//    subscribe(lock1, "unlock", doorUnlockedHandler, [filterEvents: false])
}

def contactHandler(evt) {
	log.debug "$evt.value"
	if (evt.value == "open") {
		lock1.unlock()
        log.debug "Lock ${lock1} was: ${evt.value}"
	}
}

(Steve S) #2

The subscribe() is subscribing to the events. In your case, you want to be notified when the contact sensor has something happen, so you are subscribing to the “contact” events from the contact sensor. Subscribing is telling the sensor that you want to be notified when something happens.

Then, when you want to tell the lock to unlock, you send the unlock command with lock1.unlock().


(Jeremy Whittaker) #3

Ah ok, perfect, so it’s only necessary when you want to poll a device. It is not necessary to control a device. Thanks @stevesell


(Steve S) #4

You’re actually telling the device that you want to be put on the list of apps to be notified when an particular event occurs – you’re not really polling.


(Chrisb) #5

I my mind I think of them as triggers. I need to subscribe to these events to use them as triggers.

In your case, the trigger is the sensor opening. When that sensor opens it’s going to trigger my program to run, therefore I need to subscribe to it.

Because the locking/unlocking of the lock doesn’t trigger anything you don’t need to subscribe to it. You’re going to tell the lock what to do, but you don’t need to lock to tell you (or the program) anything in order for the program to operate.