openHAB 3 ECMA executeCommandLine

Example how to executeCommandLine script in javascript, parse result and update items.

var logger = Java.type('org.slf4j.LoggerFactory').getLogger('org.openhab.rule.switcherStatus');

try{
  var regStatus = /Device is (ON|OFF)/gm;
  var regCurrent = /Electric Current is: (\d+\.\d+)/gm;
  var regPowerConsumption = /Power consumption is: (\d{0,4})/gm;
  var regAutoShutdown = /Auto shutdown device in: (\d{0,2}:\d{0,2}:\d{0,2})/gm;

  
  var Exec = Java.type('org.openhab.core.model.script.actions.Exec');
  var Duration = Java.type('java.time.Duration');
  var dur = Duration.ofSeconds(10);
  // https://github.com/NightRang3r/Switcher-V2-Python
  var execRes = Exec.executeCommandLine(dur,'/etc/openhab/scripts/switcher.py',2);
  //logger.info("gotResult:" + execRes);
  
  var mStatus = regStatus.exec(execRes);
  var mCurrent = regCurrent.exec(execRes);
  var mPower = regPowerConsumption.exec(execRes);
  var mShutdown = regAutoShutdown.exec(execRes);
  
  
  logger.info("status: " + mStatus[1])
  logger.info("current: " + mCurrent[1])
  logger.info("power: " + mPower[1])
  logger.info("shutdown: " + (mShutdown ? mShutdown[1] : ''))
  
  events.sendCommand('switcher_status', mStatus[1] === 'ON' ? ON : OFF);
  events.sendCommand('switcher_current', parseFloat(mCurrent[1]));
  events.sendCommand('switcher_power', parseFloat(mPower[1]));
  if(mShutdown){
    events.sendCommand('switcher_autoshutdown', mShutdown[1]);
  }   
}
catch(e){
  logger.error("err:" + e);
}
6 Likes

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.