How big is my OpenHab Setup

that is true, but now I have proof, haha

1 Like

I have modified the code a little bit :slight_smile:
Fix all the pylint warnings and added the ability to count the JSR rules also. Which are provided by the API.

import sys
import glob
import re
import logging

import requests

# Modify these variables to fit your system
URL_OPENHAB = "http://localhost:8080"
THING_ITEM_NAME = "openHAB_AllThings"
ITEM_ITEM_NAME = "openHAB_AllItems"
RULE_ITEM_NAME = "openHAB_AllRules"
RULE_PATH = "/etc/openhab2/rules/*.rules"
PATH_FOR_LOG = "/var/log/openhab2/rules_count.log"

logging.basicConfig(level=logging.DEBUG)
LOGGER = logging.getLogger('rules_count')

#LOGGER.setLevel(logging.DEBUG)
FH = logging.FileHandler(PATH_FOR_LOG)
FH.setLevel(logging.DEBUG)
FORMATTER = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
FH.setFormatter(FORMATTER)
LOGGER.addHandler(FH)

try:
    ITEMS = len(requests.get(url=URL_OPENHAB + "/rest/items?recursive=false").json())
    LOGGER.info("found %s Items", str(ITEMS))
    requests.post(url=URL_OPENHAB + "/rest/items/" + ITEM_ITEM_NAME, data=str(ITEMS), verify=False)
except: # catch *all* exceptions
    LOGGER.error(sys.exc_info())

try:
    THINGS = len(requests.get(url=URL_OPENHAB + "/rest/things").json())
    LOGGER.info("found %s Things", str(THINGS))
    requests.post(url=URL_OPENHAB + "/rest/items/" + THING_ITEM_NAME, data=str(THINGS), verify=False)
except: # catch *all* exceptions
    LOGGER.error(sys.exc_info())

try:
    JSR_RULES_COUNT = len(requests.get(url=URL_OPENHAB + "/rest/rules").json())
    LOGGER.info("found %s JSR Rules", str(JSR_RULES_COUNT))
except:
    LOGGER.error(sys.exc_info())

try:
    RULES = 0
    WHENS = 0
    THENS = 0
    ENDS = 0
    COUNTER = []
    for fileName in glob.glob(RULE_PATH):
        with open(fileName, 'r') as rule_file:

            fileContent = rule_file.read()
            fileContent = re.sub(re.compile(r"/\*.*?\*/", re.DOTALL), "", fileContent)
            fileContent = re.sub(re.compile(r"//.*?\n"), "", fileContent)

            rules_in_this_file = len(re.findall(r'\brule\b', fileContent, re.IGNORECASE))
            RULES += rules_in_this_file
            LOGGER.debug("found " + str(rules_in_this_file) + " rules in file" + fileName)

            whens_in_this_file = len(re.findall(r'\bwhen\b', fileContent, re.IGNORECASE))
            WHENS += whens_in_this_file
            LOGGER.debug("found " + str(whens_in_this_file) + " whens in file" + fileName)

            thens_in_this_file = len(re.findall(r'\bthen\b', fileContent, re.IGNORECASE))
            THENS += thens_in_this_file
            LOGGER.debug("found " + str(thens_in_this_file) + " thens in file" + fileName)

            ends_in_this_file = len(re.findall(r'\bend\b', fileContent, re.IGNORECASE))
            ENDS += ends_in_this_file
            LOGGER.debug("found " + str(ends_in_this_file) + " ends in file" + fileName)

    COUNTER.append(RULES)
    COUNTER.append(WHENS)
    COUNTER.append(THENS)
    COUNTER.append(ENDS)
    RULES_COUNT = min(COUNTER)

    LOGGER.info("counting %s rules", str(RULES_COUNT))

    RULES_COUNT += JSR_RULES_COUNT
    requests.post(url=URL_OPENHAB + "/rest/items/" + RULE_ITEM_NAME, data=str(RULES_COUNT), verify=False)
except: # catch *all* exceptions
    LOGGER.error(sys.exc_info())

2 Likes

Is this code still working for you? I noticed my Things show up as 1 nowadays.

I also see some errors:

2022-02-20 11:46:55.603 [ERROR] [rg.apache.cxf.jaxrs.utils.JAXRSUtils] - No message body reader has been found for class java.lang.String, ContentType: application/octet-stream
2022-02-20 11:46:55.604 [WARN ] [s.impl.WebApplicationExceptionMapper] - javax.ws.rs.WebApplicationException: HTTP 415 Unsupported Media Type

Which I have fixed by changing the code to:

headers = {'accept':'*/*','content-type':'application/json'}

try: 
    items = len(requests.get(url = url_openhab + "/rest/items?recursive=false").json())
    logger.info("found " + str(items) + " Items" )
    requests.get(url = url_openhab + "/rest/items/" + item_item_name, data = str(items), verify=False, headers=headers)
except: # catch *all* exceptions
    logger.error( sys.exc_info() )

try: 
    things = len(requests.get(url = url_openhab + "/rest/things").json())
    logger.info("found " + str(things) + " Things" )
    requests.get(url = url_openhab + "/rest/items/" + thing_item_name, data = str(things), verify=False, headers=headers_post)
except: # catch *all* exceptions
    logger.error( sys.exc_info() )

But it still gives me 1 Thing.

I also tried with an API token:

access_token = 'oh.countmystuff.yourtoken'

headers = {'accept':'*/*','content-type':'application/json'} #,'Authorization': 'Bearer {}'.format(access_token)}

headers_post = {'accept':'*/*','content-type':'text/plain'} #,'Authorization': 'Bearer {}'.format(access_token)}


logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('count_my_stuff')
#logger.setLevel(logging.DEBUG)
fh = logging.FileHandler(path_for_log)
fh.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)


try: 
    items = len(requests.get(url = url_openhab + "/rest/items?recursive=false").json())
    logger.info("found " + str(items) + " Items" )
    requests.put(url = url_openhab + "/rest/items/" + item_item_name, data = str(items), verify=False, headers=headers)
except: # catch *all* exceptions
    logger.error( sys.exc_info() )

try: 
    things = len(requests.get(url = url_openhab + "/rest/things").json())
    logger.info("found " + str(things) + " Things" )
    requests.post(url = url_openhab + "/rest/items/" + thing_item_name, data = str(things), verify=False, headers=headers_post)
except: # catch *all* exceptions
    logger.error( sys.exc_info() )

Still 1 thing.

NB I’m no coder, I just try stuff till it works.

1 Like

OK I managed to solve it:

#!/bin/sh
localUrl=http://YOURIP:8080/rest/things
localHeader='Accept: application/json'
authentication='Authorization: Bearer TOKEN'

NumberThings=$(curl -s -X 'GET' ${localUrl} \
  -H "${localHeader}" \
  -H "${authentication}" \
| python3 -m json.tool | grep \"channels\" | wc -l )

echo $NumberThings
exit

Change YOURIP and TOKEN to your settings. I believe it is not possible to get the number of things from the REST API without authentication.

Now I get the correct number of things, which corresponds with what OH says.