In this thread I want to share a script with you that I created to make use the “say” action.
Requirements that I had:
- reusable function to avoid duplicate code
- set the volume to a predefined level while saying something and reset it afterwards
- do not speak if the device is playing music
Prerequisites:
- Setup the device - thing+item (In my case 2 Google Home Mini/Nest)
- Setup TTS: https://next.openhab.org/addons/voice/googletts/
–> Attention: In openhab 3 OAuth is used instead of a service account - Setup Rich’s Timer Manager: https://github.com/rkoshak/openhab-rules-tools/tree/main/timer_mgr
- Create a new JS file and place it here: “…/automation/lib/javascript/personal/notifications.js”
(function(context) {
this.OPENHAB_CONF = (this.OPENHAB_CONF === undefined) ? java.lang.System.getenv("OPENHAB_CONF") : this.OPENHAB_CONF;
load(OPENHAB_CONF+'/automation/lib/javascript/community/timerMgr.js');
this.logger = (this.logger === undefined) ? Java.type("org.slf4j.LoggerFactory").getLogger("org.openhab.model.script.Rules.notifications") : this.logger;
this.voice = (this.voice === undefined) ? Java.type("org.openhab.core.model.script.actions.Voice") : this.voice;
this.tm = (this.tm === undefined) ? new TimerMgr() : this.tm;
context.say = function(tts,duration) {
//Get current volume
var volumeLR = context.items["GHLivingRoom_Volume"];
var volumeOF = context.items["GHOffice_Volume"];
if(context.items["GHLivingRoom_Control"] == PAUSE){
context.events.sendCommand("GHLivingRoom_Volume", 40);
this.voice.say(tts, "googletts:deDEWavenetC", "chromecast:chromecast:2ae2e226dd29fad4d20afc65e4bc4061")
this.tm.check("notificationSay", duration,
function() { context.events.sendCommand("GHLivingRoom_Volume", volumeLR); });
}
else if(context.items["GHOffice_Control"] == PAUSE){
context.events.sendCommand("GHOffice_Volume", 40);
this.voice.say(tts, "googletts:deDEWavenetC", "chromecast:chromecast:38a71a03c5265c00036a43e0fb39b7b5")
this.tm.check("notificationSay", duration,
function() { context.events.sendCommand("GHOffice_Volume", volumeOF); });
}
}
})(this)
- Create a new rule in MainUI and select “execute a given script” --> ECMA
this.OPENHAB_CONF = (this.OPENHAB_CONF === undefined) ? java.lang.System.getenv("OPENHAB_CONF") : this.OPENHAB_CONF;
load(this.OPENHAB_CONF+'/automation/lib/javascript/personal/notifications.js');
say("Hello","1s");
I hope it helps you!
If there is anything that can be improved, please let me know.