[SOLVED] Get/Set Item State and imports when used in libraries

Tags: #<Tag:0x00007fc20b1e26f0> #<Tag:0x00007fc20b1e1f70> #<Tag:0x00007fc20b1e1b88>

I am looking around the forum for about an hour but was not able to get the solution that works.

What import do I have to declare and what is the syntax to retrieve and set item state?

Thanks in advance

The official documentaion help any?

rules?

Sorry was not precise enough, thought the tag would do it:
context is JSR223 and Jython

Sorry, I missed the code you tried. We help you but you need to put forth some effort too.

Item Defs

Dimmer testGU10L "Test Lamp L [%d %%]"  { channel="hue:0100:00212E00C488:6:brightness" } 
Dimmer testGU10M "Test Lamp M [%d %%]"  { channel="hue:0100:00212E00C488:2:brightness" } 

Rule for putting item state to log every 10sec (does not resolve “items”

This script uses a decorated cron rule that will generate logs every 10s and can be used to test your initial setup.


from core.rules import rule
from core.triggers import when
from core.log import logging, LOG_PREFIX
log = logging.getLogger(LOG_PREFIX + ".this.is.my.log")

@rule("Jython Hello World (cron decorators)", description="This is an example cron triggered rule using decorators", tags=["Test tag", "Hello World"])# description and tags are optional
@when("Time cron 0/10 * * * * ?")
def hello_world_cron_decorators(event):
    log.info("Hello World to log")
    log.info(items["testGU10L"])

the doc :https://openhab-scripters.github.io/openhab-helper-libraries/Guides/But%20How%20Do%20I.html#items

states:

items["My_Item"]
# or after importing anything within the ``core`` package
items.My_Item
# or
ir.getItem("My_Item").state

neither works (does not resolve “items”

@5iver any ideas?

would you show us the exact error you are getting in the console?

I agree with Michael… what is the error that is being logged? The examples in the documentation definitely all work :wink:!

I also noticed that what you posted looks to be an older version of the hello_world.py example script. When was the last time you upgraded the helper libraries? The easiest would be to use the beta Jython bundle…

1 Like

I am running OH in docker and using cont-init.d for initializing/downloading helper and jython (see below). This was convenient for me, though seems to be outdated.

I will go for the new way and beta test.
I have a question:
I have added pyyaml to my installation:

sudo pip install --upgrade --target=/datavol/openhab-2.5.1/openhab_conf/automation/lib/python 'pyyaml==3.10'

Any idea how do I add the pyyaml support once I change the EXTRA_JAVA_OPTS?

10-jsr223-jython:

#!/bin/bash -x

JYTHON_VERSION="2.7.0"
JYTHON_HOME="${OPENHAB_CONF}/automation/jython"

export EXTRA_JAVA_OPTS="${EXTRA_JAVA_OPTS} -Xbootclasspath/a:${JYTHON_HOME}/jython.jar -Dpython.home=${JYTHON_HOME} -Dpython.path=${JYTHON_HOME}/Lib:${OPENHAB_CONF}/automation/lib/python"


function cleanup_compiled_classes() {
  # Clears Jython's compiled classes
  if [ -d "${OPENHAB_CONF}/automation/lib/python" ]; then
    find ${OPENHAB_CONF}/automation/lib/python -name '*\$py.class' -delete
  fi
  if [ -d "${JYTHON_HOME}/Lib" ]; then
    find ${JYTHON_HOME}/Lib -name '*\$py.class' -delete
  fi
}

function download_jython_libraries() {
  # Download and install Jython
  if [ ! -d "${JYTHON_HOME}" ]; then
    mkdir -p "${JYTHON_HOME}"
    wget -nv -O /tmp/jython-installer.jar http://search.maven.org/maven2/org/python/jython-installer/${JYTHON_VERSION}/jython-installer-${JYTHON_VERSION}.jar
    java -jar /tmp/jython-installer.jar -s -d ${JYTHON_HOME}/ -t standard -e demo doc src
    rm /tmp/jython-installer.jar
    # chmod -R o+w ${JYTHON_HOME}
    chown -R openhab:openhab ${JYTHON_HOME}
  fi
}

function enable_next_generation_rule_engine() {
  # Enable the Next Generation Rule Engine
  set +e
  MISC_LINE=$(grep '^[[:space:]]\?misc' ${OPENHAB_CONF}/services/addons.cfg)
  if [ $? -eq 0 ]; then
    # ensure we have ruleengine enabled
    if [[ ${MISC_LINE} == *"ruleengine"* ]]; then
      echo "New rule engine is already included in the addons.cfg"
    else
      sed -i 's/misc\s\?=\s\?/misc = ruleengine,/' ${OPENHAB_CONF}/services/addons.cfg
    fi
  else
    # Just append last line
    echo "Append 'misc = ruleengine' to ${OPENHAB_CONF}/services/addons.cfg"
    echo "misc = ruleengine" >> ${OPENHAB_CONF}/services/addons.cfg
  fi
}


download_jython_libraries
cleanup_compiled_classes
#enable_next_generation_rule_engine

and 10-openhab-helper-libraries:

#!/bin/bash -x

OPENHAB_AUTOMATION="${OPENHAB_CONF}/automation"
OPENHAB_HL_AUTOMATION="${OPENHAB_AUTOMATION}/openhab-helper-libraries/Core/automation"
OPENHAB_HL_URL="https://github.com/openhab-scripters/openhab-helper-libraries/archive/master.zip"

declare -A LANGUAGES=( ["groovy"]="groovy" ["javascript"]="js" ["python"]="py" )

function verify_directory_structure() {

  # before making any changes let's first verify that we can make the required changes
  verify_directory "${OPENHAB_AUTOMATION}"
  for SUBDIR in jsr223 lib; do
    verify_directory "${OPENHAB_AUTOMATION}/${SUBDIR}"
    for LANGUAGE in "${!LANGUAGES[@]}"; do
      verify_directory "${OPENHAB_AUTOMATION}/${SUBDIR}/$LANGUAGE/community"
      verify_directory "${OPENHAB_AUTOMATION}/${SUBDIR}/$LANGUAGE/personal"

      verify_symlink "${OPENHAB_AUTOMATION}/${SUBDIR}/${LANGUAGE}/core" "${OPENHAB_HL_AUTOMATION}/${SUBDIR}/${LANGUAGE}/core"
    done
  done
}

function create_directory_structure() {
  create_directory "${OPENHAB_AUTOMATION}"
  for SUBDIR in jsr223 lib; do
    create_directory "${OPENHAB_AUTOMATION}/${SUBDIR}"
    for LANGUAGE in "${!LANGUAGES[@]}"; do
      create_directory "${OPENHAB_AUTOMATION}/${SUBDIR}/$LANGUAGE/community"
      chmod g+w "${OPENHAB_AUTOMATION}/${SUBDIR}/$LANGUAGE/community"
      create_directory "${OPENHAB_AUTOMATION}/${SUBDIR}/$LANGUAGE/personal"
      chmod g+w "${OPENHAB_AUTOMATION}/${SUBDIR}/$LANGUAGE/personal"

      create_symlink "${OPENHAB_AUTOMATION}/${SUBDIR}/${LANGUAGE}/core" "${OPENHAB_HL_AUTOMATION}/${SUBDIR}/${LANGUAGE}/core"
    done
  done
}

function verify_directory() {
  local DIRECTORY=$1
  if [ -L "${DIRECTORY}" ]; then
    echo "ERROR: Cannot create directory ${DIRECTORY}. A symlink with that link name already exists."
    exit 1
  elif [ -f "${DIRECTORY}" ]; then
    echo "ERROR: Cannot create directory ${DIRECTORY}. A file with that name already exists."
    exit 1
  fi
}

function create_directory() {
  local DIRECTORY=$1
  if [ ! -d "${DIRECTORY}" ]; then
    mkdir -p "${DIRECTORY}"
    if [ $? -ne 0 ]; then
      echo "ERROR: Could not create directory ${DIRECTORY}."
      exit 1
    fi
  else
    echo "Directory ${DIRECTORY} already exists."
  fi
}

function verify_symlink() {
  local LINK_NAME=$1
  local TARGET=$2
  if [ -L "${LINK_NAME}" ]; then
    local LINK_TARGET="$(readlink ${LINK_NAME})"
    if [ "${LINK_TARGET}" != "${TARGET}" ]; then
      echo "ERROR: A symlink with ${LINK_NAME} already exists pointing to a different target."
      exit 1
    fi
  elif [ -e "${LINK_NAME}" ]; then
    echo "ERROR: File or directory with name ${LINK_NAME} already exists."
    exit 1
  fi
}

function create_symlink() {
  local LINK_NAME=$1
  local TARGET=$2
  if [ ! -L "${LINK_NAME}" ]; then
    ln -s "${TARGET}" "${LINK_NAME}"
    if [ $? -ne 0 ]; then
      echo "ERROR: Could not create symlink ${LINK_NAME} to ${TARGET}."
      exit 1
    fi
  else
     echo "Symlink ${LINK_NAME} already exists."
  fi
function create_initial_configuration() {
  for LANGUAGE in "${!LANGUAGES[@]}"; do
    if [ ! -f "${OPENHAB_AUTOMATION}/lib/${LANGUAGE}/configuration.${LANGUAGES[$LANGUAGE]}" ]; then
      cp "${OPENHAB_HL_AUTOMATION}/lib/${LANGUAGE}/configuration.${LANGUAGES[$LANGUAGE]}.example" "${OPENHAB_AUTOMATION}/lib/${LANGUAGE}/configuration.${LANGUAGES[$LANGUAGE]}"
    fi
  done
}

function download_helper_libraries() {
  # Download the Helper Libraries for openHAB Scripted Automation
  echo "Downloading openhab-helper-libraries-master archive from Github."
  wget -nv -O /tmp/openhab-helper-libraries-master.zip "${OPENHAB_HL_URL}"
  if [ $? -ne 0 ]; then
    echo "ERROR: Failed to download the helper libraries form Github."
    exit 1
  fi

  unzip -q /tmp/openhab-helper-libraries-master.zip -d /tmp -x \
    "openhab-helper-libraries-master/.github/*" \
    "openhab-helper-libraries-master/.gitignore" \
    "openhab-helper-libraries-master/docs/*" \
    "openhab-helper-libraries-master/Docker/*" \
    "openhab-helper-libraries-master/Sphinx/*"
  if [ $? != 0 ]; then
    echo "ERROR: Failed to extract the helper libraries zip file."
    exit 1
  fi

  rm /tmp/openhab-helper-libraries-master.zip
}

function install_helper_libraries() {
  mv /tmp/openhab-helper-libraries-master "${OPENHAB_AUTOMATION}/openhab-helper-libraries"
  # update ownership
  chown -R openhab:openhab "${OPENHAB_AUTOMATION}"
}

function enable_next_generation_rule_engine() {
  # Enable the Next Generation Rule Engine
  set +e
  MISC_LINE=$(grep '^[[:space:]]\?misc' ${OPENHAB_CONF}/services/addons.cfg)
  if [ $? -eq 0 ]; then
    # ensure we have ruleengine enabled
    if [[ ${MISC_LINE} == *"ruleengine"* ]]; then
      echo "New rule engine is already included in the addons.cfg."
    else
      sed -i 's/misc\s\?=\s\?/misc = ruleengine,/' ${OPENHAB_CONF}/services/addons.cfg
    fi
  else
    # Just append last line
    echo "Append 'misc = ruleengine' to ${OPENHAB_CONF}/services/addons.cfg."
    echo "misc = ruleengine" >> ${OPENHAB_CONF}/services/addons.cfg
  fi
}


if [ ! -d "${OPENHAB_AUTOMATION}/openhab-helper-libraries" ]; then
  # verify if installation is possible
  verify_directory_structure
  download_helper_libraries

  # make the required changes and install the libraries
  create_directory_structure
  install_helper_libraries

  # create initial configuration if required
  create_initial_configuration

  # enable the next genereation rule engine if required
  enable_next_generation_rule_engine
else
  echo "Helper Libraries for openHAB Scripted Automation already installed."
fi

Remove everything about Jython except the python.path.

What you reported as an error is only a warning from pylint in VSCode. It sounds like you still do nt have your pylintrc setup properly.

I have done a new clean install of helper libraries and used the new bundle.
Now everything works as expected in my hello world code. I had a mess in my installtion.

Thanks for support

Unfortunately, I still have an issue when I want to access “items” in a helper library and not in the class with decoration.

2020-02-16 17:47:46.974 [ERROR] [jsr223.jython.Test Light Control    ] - Traceback (most recent call last):
  File "/openhab/conf/automation/lib/python/core/log.py", line 51, in wrapper
    return fn(*args, **kwargs)
  File "<script>", line 49, in execute
  File "/openhab/conf/automation/lib/python/personal/LightControlLib.py", line 105, in execute
    self.togLight(itm)
  File "/openhab/conf/automation/lib/python/personal/LightControlLib.py", line 133, in togLight
    if items["testGU10L"] == 0:

What import do I need in my library module in order to resolve the “items”?

I imported

from core.jsr223.scope import events, items

seems to work now

:+1:

items is included in the default script scope. There is nothing that you need to import to access this in a script. To access items in a module, like you are doing, you will need to import it into the module like this…

from core.jsr223.scope import items

Same as here…

1 Like

Sorry, it just got into my mind that I had a similar issue with events, I dug it out and finally found the solution the same time you replied back. It was so long ago I made my first try to migrate to new rules.

Thank you again for your support, it is amazing!

1 Like