HABApp - Easy automation with openHAB

is there a (preferred) way to use a map file when sending a command to an OH item with HABApp?

I am using a normal dictionary to make the transformation.
e.g.

map = {1: 'ON', 2: 'OFF'}
item.oh_send_command(map[value])

If you like you can also use the DictParameter:

def __init__(self):
    ...
    self.map = HABApp.DictParameter('my_param')
...
    self.item.oh_send_command(self.map[value])

Could you explain what you like to achive? I used map files in rules only to display the mapped state in log statements. Typically openHAB uses the map file tp transform values

As examples, I use map files to translate IR commands and Sonos stations in rules:

Brook=x-sonos-http:track%3ailps5n6J_%7cfiHveUhv_.mp4?sid\=283&flags\=8224&sn\=3
Crickets=x-sonos-http:track%3a94Cw346b2%7cBR5hxSbzu.mp4?sid\=283&flags\=8224&sn\=3
Birds=x-sonos-http:track%3a0GeNnY1W8F%7c0fZG_p1Dqd.mp4?sid\=283&flags\=8224&sn\=3
Daily=x-sonos-http:daily_calm_track%3aMaL0dPV%7c4t6C-LXsjt.mp4?sid\=283&flags\=8224&sn\=3
Rain=x-sonos-http:track%3aqaQ4fCgjp%7cD7lklLoUJ.mp4?sid\=283&flags\=8224&sn\=3
Majestic=x-sonos-http:track%3aKYEHnQ-_i2%7cKLQIoJ_U0t.mp4?sid\=283&flags\=8224&sn\=3
Campfire=x-sonos-http:track%3aiuebVijhp%7cqZJQCeL9X.mp4?sid\=283&flags\=8224&sn\=3
Glide=x-sonos-http:track%3asWY-NpVx7D%7cFm24_n5Nlf.mp4?sid\=283&flags\=8224&sn\=3
Yosemite=x-sonos-http:track%3aGK70DLm%7cy3e9blLJa.mp4?sid\=283&flags\=8224&sn\=3
Rain_Light=x-sonos-http:track%3aT9EuwlYbO%7ctv-Mljj9k.mp4?sid\=283&flags\=8224&sn\=3
---
Toggle={"Protocol":"NEC","Bits":32,"Data":"0x10af8877"}
Cool={"Protocol":"NEC","Bits":32,"Data":"0x10af906f"}
Fan={"Protocol":"NEC","Bits":32,"Data":"0x10afe01f"}

Ideally I’d like to not re-define them in each rule for maintainability.

I typically create some output driver rules for similar outputs and use a HABApp proxy item to interact with them.
As an alternative if you name the rule properly you can use get_rule('rule name') and call methods directly.
In your case however I’d just use a HABApp.DictParameter file as I’ve described.

Good news everyone!

I just released HABApp 0.30.3 !

2 Likes

I would like to run HABApp in a Docker container, so i wanted to ask whether there might also be a docker-compose file for it. I didn’t find anything in the docs or in the forum.

This is a snippet of my compose file

version: '2.0'
services:
  habapp:
    image: spacemanspiff2007/habapp:0.20.1
    restart: always
    volumes:
        - ./openhab/habapp:/config
    environment:
      - TZ=Europe/Berlin
  openhab:
    image: openhab/openhab:3.1.0.M3-debian
    restart: always
    hostname: openhab
    tty: true
    cap_add:
      - NET_ADMIN
      - NET_RAW
    devices: 
      - /dev/ttyACM0
    privileged: true
    environment:
      - USER_ID=1000
    volumes:
      - ./openhab/timezone:/etc/timezone:ro 
      - ./openhab/conf:/openhab/conf
      - ./openhab/userdata:/openhab/userdata
      - ./openhab/addons:/openhab/addons

@Dominik_Bernhardt thank you very much for sharing the composer-file! On my Raspberry Pi 4 i had to do the following to make the container work:

wget http://ftp.us.debian.org/debian/pool/main/libs/libseccomp/libseccomp2_2.5.1-1_armhf.deb
sudo dpkg -i libseccomp2_2.5.1-1_armhf.deb

Now everything works so far, i have adjusted the config file and i see OH-logs and events, but how do i have to proceed if i want to connect Visual Studio Code with HABApp so that i get the automatic completion of the syntax?

Just install the same version of HABApp in your local python venv that you have running in your container.
This will enable your IDE to auto complete.

1 Like

Another solution is to use the remote editing feature of visual studio code. From there you should be able to select the venv and get the auto complte.

Thats how i did it.

Sorry to catch this discussion. Tried today with a complete fresh setup to switch to OH3 and one of my first things was to install HABApp (even without one single binding installed). I strictly followed the installation description but all my attempts failed with the following:

(habapp) admin@openHAB3:/opt/habapp $ habapp --config /etc/openhab/habapp/
Creating logging.yml in /etc/openhab/habapp
Error loading logging config: Unable to configure handler 'EventFile'
Error loading logging config: Unable to configure handler 'EventFile'
Executing <Task pending coro=<Runtime.start() running at /opt/habapp/lib/python3.7/site-packages/HABApp/core/wrapper.py:90> created at /opt/habapp/lib/python3.7/site-packages/HABApp/__main__.py:32> took 0.165 seconds
Executing <Task pending coro=<try_uuid() running at /opt/habapp/lib/python3.7/site-packages/HABApp/openhab/connection_handler/http_connection.py:339> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x7f94daea38>()] created at /usr/lib/python3.7/asyncio/base_events.py:396> created at /usr/lib/python3.7/asyncio/tasks.py:325> took 0.039 seconds
Disconnected! Expected success but got status 401 for /rest/things/
Task exception was never retrieved
future: <Task finished coro=<LoadAllOpenhabItems.on_connect_function() done, defined at /opt/habapp/lib/python3.7/site-packages/HABApp/core/wrapper.py:115> exception=CancelledError() created at /usr/lib/python3.7/asyncio/tasks.py:325>
source_traceback: Object created at (most recent call last):
  File "/opt/habapp/bin/habapp", line 8, in <module>
    sys.exit(main())
  File "/opt/habapp/lib/python3.7/site-packages/HABApp/__main__.py", line 33, in main
    HABApp.core.const.loop.run_forever()
  File "/usr/lib/python3.7/asyncio/base_events.py", line 539, in run_forever
    self._run_once()
  File "/usr/lib/python3.7/asyncio/base_events.py", line 1767, in _run_once
    handle._run()
  File "/usr/lib/python3.7/asyncio/events.py", line 88, in _run
    self._context.run(self._callback, *self._args)
  File "/opt/habapp/lib/python3.7/site-packages/HABApp/openhab/connection_handler/http_connection.py", line 370, in try_uuid
    ON_CONNECTED()
  File "/opt/habapp/lib/python3.7/site-packages/HABApp/openhab/connection_logic/_plugin.py", line 58, in on_connect
    p.on_connect()
  File "/opt/habapp/lib/python3.7/site-packages/HABApp/openhab/connection_logic/_plugin.py", line 40, in on_connect
    self.fut = asyncio.create_task(self.on_connect_function())
  File "/usr/lib/python3.7/asyncio/tasks.py", line 325, in create_task
    return loop.create_task(coro)
concurrent.futures._base.CancelledError
Disconnected! Expected success but got status 401 for /rest/things/
Task exception was never retrieved
future: <Task finished coro=<LoadAllOpenhabItems.on_connect_function() done, defined at /opt/habapp/lib/python3.7/site-packages/HABApp/core/wrapper.py:115> exception=CancelledError() created at /usr/lib/python3.7/asyncio/tasks.py:325>

Please note, that i have renamed the default user to admin. For me it looks like some access issue but i dont know where to search further. I have installed and uninstalled it now many times. Last time i gave 777 to all files and folders in /opt/habapp and /etc/openhab/habapp and i also tried to change ownership to the user ‘openhab’. Nothing out of this worked.

Thanks in advance
Patrick
Would be very happy if anyone could assist, or shall i create a complete new topic for this issue (or even switch to github?) I am lost somehow …

It looks like two issues:

  • A permission issue that should be solved with recursive write access to /etc/openhab/habapp
  • Missing basic auth.

You can verify the first one is working correctly if HABApp is creating the default files in the folder.
Once this works you can enter your credentials for openhab3.

1 Like

Hey @Spaceman_Spiff,

i precluded the permission issue with giving 777 to the complete directory and files. But your other hint made my day. After setting the basic auth via UI, entering my user credentials into config.yml within /etc/openhab/habapp/ and setting up the number item HABapp_Ping it worked fine.

Thx a lot for your help!

hello Sebastian,
i’m struggling with debugging rules. i use visual studio code over linux installation.

  • set up interpreter as /opt/habapp/bin/python3
  • have perfectly working hapapp with oh3 (starting habapp service, rules are run correctly)
    when i press F5 to run debug, starting from a working rule, IDE , on line super().init() , says:

    File “/opt/habapp/lib/python3.8/site-packages/HABApp/rule/rule.py”, line 44, in init
    raise RuntimeError('Rule files are not meant to be executed directly! ’
    RuntimeError: Rule files are not meant to be executed directly! Put the file in the HABApp “rule” folder and HABApp will load it automatically.

what i’m missing? thank you in advance

Hi Stefano,

I am not sure how you are proceeding.
You can’t “run” the rules directly, the rules are loaded by HABApp automatically.
You have to run HABApp in VSCode and then you can debug the rules once they are loaded.

Great! that’s exactly what it’s needed: running habapp i can debug rules correctly. thank you as always for you support

Thanks @Dibbler42 that works perfect!

1 Like

The event ValueChangeEvent does not trigger for a Group while the specific event GroupItemStateChangedEvent does. Is this a bug or intended behavior?

I have a group item that sums the readings from several smart plugs

Group:Number:SUM gTotalPower   "Consumo totale [%.0f W]"   <meter_icon>
Number Power_Forni          "Pw_Forno/Microonde [%.0f]"  <heating>        (,gTotalPower) { channel="xxxx" }

I’ve tried to write a simple rule to print on the console the value of the item when it changes, as follows

import HABApp
from HABApp.core.events import ValueUpdateEvent, ValueChangeEvent
from HABApp.openhab.items import SwitchItem,GroupItem,NumberItem
from HABApp.openhab.events import ItemCommandEvent,ItemStateChangedEvent,GroupItemStateChangedEvent

class MyOpenhabRule(HABApp.Rule):

    def __init__(self):
        super().__init__()

        # get items
        test_gPower = GroupItem.get_item('gTotalPower')
        test_Forni  = NumberItem.get_item('Power_Forni')

        print(f'Total Power {test_gPower}') 
        print(f'Power Forni {test_Forni}') 

        # Trigger on item commands
        test_gPower.listen_event(self.change_power,ValueChangeEvent) #GroupItemStateChangedEvent)
        test_Forni.listen_event(self.change_power,ValueChangeEvent) #,ItemStateChangedEvent)

    def change_power(self, event):
        print( f'Event received {event}')

MyOpenhabRule()     

It turns out that the updates of the Number Item ‘Power_Forni’ are printed while the ones of the Group Item ‘gTotalPower’ are not.

If I change the event in the listen_event from ValueChangEvent to GroupItemStateChangedEvent then I see printouts of the gTotalPower item updates.

Is this an error or an intended feature?

Thank you for your attention,

PS. I installed HABApp with openhabian-config today. I do not know how to determine the version (there’s no -v switch apparently)

I am not 100% sure.
The problem is, that the group item handling is different than the normal item handling even though it should be the same.
Normal items emit an ItemStateEvent when they update their state and afterwards they emit an ItemStateChangedEvent (if the state changed).
Group items however only emit an ItemStateChangedEvent.

If HABApp triggers on it with a ValueChangeEvent would it also make sense then to also trigger on a ValueUpdateEvent?
Does it make sense to trigger on both events with only one event on the event bus?

Maybe some of the other users can share their opinion, too.
I’d like to get some different perspective on the issue.
@yfaway @Dominik_Bernhardt @Dibbler42 @magnuslsjoberg @dan12345

It’s one of the first lines in the HABApp.log.