Jython, threading, locking and debouncing

I have an Item that I update with text, which then gets processed through TTS and played as an announcements on speakers around the house. There is a small delay while getting the speakers in and out of multiroom audio mode (Sony’s HomeShare “party mode”). If I did not use start_new_thread, this rule would sit and wait for the audio alert to complete, which would include starting and stopping the party for each alert. At the other end in the audio_alert function, I loop through the queue until it is empty. In this way, I can keep feeding things into the queue, while keeping the existing party looping in a separate thread. One party fed asynchronously! Bumpity bumpity bumpity…

from thread import start_new_thread
from personal.utils import audio_alert, ALERT_QUEUE

@rule("Alert: Audio notification")
@when("Item Audio_Notification received command")
def audio_notification(event):
    if event.itemCommand.toString() not in ALERT_QUEUE.queue:
        ALERT_QUEUE.put_nowait(event.itemCommand.toString())
        audio_notification.log.debug(u"added to queue\n{}".format(event.itemCommand))
        if ALERT_QUEUE.qsize() == 1:
            audio_notification.log.warn(u"started audio_alert\n{}".format(event.itemCommand))
            start_new_thread(audio_alert, ())
    else:
        audio_notification.log.warn(u"alert already in queue\n{}".format(event.itemCommand))

The important bit for you is…

start_new_thread(audio_alert, ())

The audio_alert is the function being called and the () is an empty set of arguments for the function.

To get the time of the last update, you could use persistence with an everyUpdate strategy, set a variable, or use a timer. I’ve never run into a need for something like this. If you post a specific example, then I’d put something together for you. It may be something useful to add to the helper libraries.

2 Likes