Files
tuya-mqtt/openhab2/rules/tuya-switch.rules
2018-06-11 10:19:40 +02:00

87 lines
3.2 KiB
Plaintext

import java.util.concurrent.locks.ReentrantLock
val ReentrantLock locktuya = new ReentrantLock
var db = true
rule "Tuya switcher"
when
Member of gTuyaSwitches received command
then
var appName = "tuya.switch";
logInfo(appName, "Member " + triggeringItem.name + " changed to " + receivedCommand);
try {
// Lock transmitter so other executed rules dont't use it at the same time.
// Concurrent calls of the rule will wait till the resource is free again.
locktuya.lock();
val name = triggeringItem.name.toString.split("_switch").get(0);
val config = name + "_config";
var relatedConfig = gTuyaConfigs.allMembers.filter [ conf | conf.name.contains(config.toString) ].head;
config = relatedConfig.label;
var args = config + " " + receivedCommand.toString;
tuya_Args.sendCommand(args);
// Wait for the command to complete
while(tuya.state != OFF){
Thread::sleep(100);
}
// Mulltiple trigger do not work if there is no break here
// maybe external skript needs some time to properly free resources.
Thread::sleep(400);
// Set related item
var trigger = name + "_trigger";
var relatedTrigger = gTuyaConfigs.allMembers.filter [ conf | conf.name.contains(trigger.toString) ].head;
if(relatedTrigger != null){
var triggerItem = gTuyaSwitches.allMembers.filter [ conf | conf.name.contains(relatedTrigger.label.toString) ].head;
logInfo(appName, "Triggered: " + triggerItem.name.toString);
triggerItem.postUpdate(receivedCommand);
}
var output = tuya_Out.state.toString.replaceAll("\r|\n"," ");
if(output != "ON" && output != "OFF"){
logError(appName, "State changed to " + output)
} else {
logInfo(appName, "State changed to " + output)
}
}catch(Throwable t) {
logInfo(appName, t);
}
finally {
// Free the resource for the next call.
locktuya.unlock()
}
end
rule "Tuya status cron"
when
Time cron "0 0/5 * * * ?"
then
var appName = "tuya.cron";
logInfo(appName, "Cron status update");
if(!locktuya.isLocked()){
locktuya.lock();
var titerator = gTuyaSwitches.members.iterator
while(titerator.hasNext){
val det = titerator.next
val config = det.name.toString.split("_switch").get(0) + "_config";
var relatedConfig = gTuyaConfigs.allMembers.filter [ conf | conf.name.contains(config.toString) ].head;
config = relatedConfig.label;
var args = config + " now";
var output = executeCommandLine("node /etc/openhab2/scripts/tuyaapi_openhab/tuya.js " + args, 5000);
det.postUpdate(output);
if(output != "ON" && output != "OFF"){
logError(appName, "State changed to " + output)
} else {
logInfo(appName, "State changed to " + output)
}
if(db) { logInfo(appName, "Update [{}]", args)}
}
locktuya.unlock()
}
end