### Create a Generic HABApp Rule with Parameters Source: https://github.com/spacemanspiff2007/habapp/blob/master/docs/getting_started.rst Shows how to create HABApp rules that accept parameters during instantiation. This allows for more generic rules that can be applied to different items or logic. The example demonstrates creating multiple rule instances with varying parameters. ```python # ------------ hide: start ------------ async def run(): # ------------ hide: stop ------------- import HABApp class MyFirstRule(HABApp.Rule): def __init__(self, my_parameter): super().__init__() self.param = my_parameter self.run.soon(self.say_something) def say_something(self): print(f'Param {self.param}') # This is normal python code, so you can create Rule instances as you like for i in range(2): MyFirstRule(i) for t in ['Text 1', 'Text 2']: MyFirstRule(t) # ------------ hide: start ------------ from rule_runner import SimpleRuleRunner SimpleRuleRunner().run(run()) ``` -------------------------------- ### Post Values to HABApp Items Source: https://github.com/spacemanspiff2007/habapp/blob/master/docs/getting_started.rst Demonstrates how to post values to a HABApp item, which automatically creates events on the event bus. The example shows creating an item locally and then updating its value multiple times. It also includes a basic comparison of the item's value. ```python # ------------ hide: start ------------ import logging import sys root = logging.getLogger('HABApp') root.setLevel(logging.DEBUG) handler = logging.StreamHandler(sys.stdout) handler.setLevel(logging.DEBUG) formatter = logging.Formatter('[%(name)15s] %(levelname)8s | %(message)s') handler.setFormatter(formatter) root.addHandler(handler) async def run(): # ------------ hide: stop ------------- import HABApp from HABApp.core.items import Item class MyFirstRule(HABApp.Rule): def __init__(self): super().__init__() # Get the item or create it if it does not exist self.my_item = Item.get_create_item('Item_Name') self.run.soon(self.say_something) def say_something(self): # Post updates to the item through the internal event bus self.my_item.post_value('Test') self.my_item.post_value('Change') # The item value can be used in comparisons through this shortcut ... if self.my_item == 'Change': ``` -------------------------------- ### Create and Get HABApp Items Source: https://github.com/spacemanspiff2007/habapp/blob/master/docs/getting_started.rst Illustrates how to create a new item within the HABApp local item registry or retrieve an existing one using `Item.get_create_item()`. This is fundamental for managing application state and data within HABApp. ```python # ------------ hide: start ------------ async def run(): # ------------ hide: stop ------------- from HABApp.core.items import Item # This will create an item in the local (HABApp) item registry item = Item.get_create_item("an-item-name", "a value") # ------------ hide: start ------------ from rule_runner import SimpleRuleRunner SimpleRuleRunner().run(run()) ``` -------------------------------- ### Configure HABApp Autostart with systemd Source: https://github.com/spacemanspiff2007/habapp/blob/master/docs/installation.rst Sets up HABApp to automatically start on system boot using systemd. This involves creating a service file with specific unit, service, and install configurations, then reloading the systemd daemon and enabling the service. ```bash sudo nano /etc/systemd/system/habapp.service [Unit] Description=HABApp Documentation=https://habapp.readthedocs.io After=network-online.target [Service] Type=simple User=openhab Group=openhab Restart=on-failure RestartSec=10min UMask=002 ExecStart=/opt/habapp/bin/habapp -c PATH_TO_CONFIGURATION_FOLDER [Install] WantedBy=multi-user.target sudo systemctl --system daemon-reload sudo systemctl enable habapp.service sudo systemctl start habapp.service sudo systemctl stop habapp.service sudo systemctl restart habapp.service sudo systemctl status habapp.service ``` -------------------------------- ### Enable and Manage HABApp Autostart (Bash) Source: https://github.com/spacemanspiff2007/habapp/wiki/Installation-&-Autostart Reloads the systemd manager configuration, enables the HABApp service to start on boot, and provides commands to start and check the status of the HABApp service. ```bash sudo systemctl --system daemon-reload sudo systemctl enable habapp.service sudo systemctl start habapp.service sudo systemctl status habapp.service ``` -------------------------------- ### Create a Simple HABApp Rule Source: https://github.com/spacemanspiff2007/habapp/blob/master/docs/getting_started.rst Demonstrates how to create a basic HABApp rule by defining a class that inherits from HABApp.Rule and scheduling a method to run shortly after instantiation. This rule prints a message to the console. ```python # ------------ hide: start ------------ async def run(): # ------------ hide: stop ------------- import HABApp # Rules are classes that inherit from HABApp.Rule class MyFirstRule(HABApp.Rule): def __init__(self): super().__init__() # Use run.at to schedule things directly after instantiation, # don't do blocking things in __init__ self.run.soon(self.say_something) def say_something(self): print('That was easy!') # Rules MyFirstRule() # ------------ hide: start ------------ from rule_runner import SimpleRuleRunner SimpleRuleRunner().run(run()) ``` -------------------------------- ### Get Item and Post Value Source: https://github.com/spacemanspiff2007/habapp/blob/master/docs/getting_started.rst This code fetches an item by its name and then posts a new value to it. It's a fundamental operation for interacting with items in HABApp. ```python from HABApp.core.items import Item i = Item.get_item('Item_Name') i.post_value('Changed value') ``` -------------------------------- ### openHAB Runner Configuration Example (YAML) Source: https://github.com/spacemanspiff2007/habapp/blob/master/tools/readme.md Example YAML configuration for the openHAB runner, defining installations with paths, Java versions, file synchronization rules, and tasks to run on start and close. ```yaml - name: openhab 4.2 path: "./path/Openhab/Installations/4.2/" java: /path/to/Java/jdk17.0.6_10 # --- optional and can be omitted, will only run when this installation is selected --- sync: [] tasks: on_start: [] on_close: [] ``` -------------------------------- ### Configure HABApp Systemd Service (Systemd Unit File) Source: https://github.com/spacemanspiff2007/habapp/wiki/Installation-&-Autostart Defines a systemd service unit for HABApp, enabling it to start automatically on boot. It specifies the user, group, and the command to execute for starting HABApp. Ensure `openhab` user and group are correct for your system. ```systemd [Unit] Description=HABApp After=network-online.target [Service] Type=simple User=openhab Group=openhab ExecStart=/opt/habapp/bin/habapp -c PATH_TO_CONFIGURATION_FOLDER [Install] WantedBy=multi-user.target ``` -------------------------------- ### Listen for Item Not Changing for a Duration Source: https://github.com/spacemanspiff2007/habapp/blob/master/docs/getting_started.rst This example shows how to set up a rule that triggers an event when an item remains constant for a specified duration (10 seconds in this case). It uses `watch_change` and `listen_event` to monitor item state. ```python from HABApp.core.items import Item from HABApp.core.events import ItemNoChangeEvent class MyFirstRule(HABApp.Rule): def __init__(self): super().__init__() self.my_item = Item.get_create_item('Item_Name') watcher = self.my_item.watch_change(10) watcher.listen_event(self.item_constant) def item_constant(self, event: ItemNoChangeEvent): print(f'{event}') MyFirstRule() ``` -------------------------------- ### Listen for Item Value Updates and Changes in HABApp Source: https://github.com/spacemanspiff2007/habapp/blob/master/docs/getting_started.rst Demonstrates how to use HABApp's `listen_event` function and item-specific methods to react to ValueUpdateEvent and ValueChangeEvent. It shows how to define callback functions for these events and access event details. ```python import HABApp from HABApp.core.items import Item from HABApp.core.events import ValueUpdateEventFilter, ValueChangeEventFilter, ValueChangeEvent, ValueUpdateEvent class MyFirstRule(HABApp.Rule): def __init__(self): super().__init__() # Get the item or create it if it does not exist self.my_item = Item.get_create_item('Item_Name') # Run this function whenever the item receives an ValueUpdateEvent self.listen_event(self.my_item, self.item_updated, ValueUpdateEventFilter()) # If you already have an item you can use the more convenient method of the item # This is the recommended way to use the event listener self.my_item.listen_event(self.item_updated, ValueUpdateEventFilter()) # Run this function whenever the item receives an ValueChangeEvent self.my_item.listen_event(self.item_changed, ValueChangeEventFilter()) # the function has 1 argument which is the event def item_updated(self, event: ValueUpdateEvent): print(f'{event.name} updated value: "{event.value}"') print(f'Last update of {self.my_item.name}: {self.my_item.last_update}') def item_changed(self, event: ValueChangeEvent): # Event handling for value changes pass MyFirstRule() ``` -------------------------------- ### Install HABApp Development Version from GitHub Source: https://github.com/spacemanspiff2007/habapp/blob/master/docs/installation.rst Install a development version of HABApp directly from a GitHub branch (e.g., 'Develop'). This requires activating a virtual environment, uninstalling any existing HABApp installation, and then using pip to install from the git repository. Ensure the virtual environment is correctly set up before proceeding. ```shell # Activate virtual environment (Linux) source bin/activate # Activate virtual environment (Windows) Scripts\activate # Remove existing installation python3 -m pip uninstall habapp # Install from GitHub branch python3 -m pip install git+https://github.com/spacemanspiff2007/HABApp.git@Develop # Run HABApp (example) habapp --config PATH_TO_CONFIGURATION_FOLDER ``` -------------------------------- ### Upgrade Pip and Install HABApp (Bash) Source: https://github.com/spacemanspiff2007/habapp/wiki/Installation-&-Autostart Upgrades the pip package installer within the activated virtual environment and then installs the HABApp package. Ensure the virtual environment is activated before running these commands. ```bash python3 -m pip install --upgrade pip python3 -m pip install habapp ``` -------------------------------- ### Compare Item Timestamps with Deltas in HABApp Source: https://github.com/spacemanspiff2007/habapp/blob/master/docs/getting_started.rst Illustrates how to utilize item timestamps (`last_change`, `last_update`) in HABApp for rule logic. It shows direct comparisons with time deltas using `newer_than` and `older_than`, and how to obtain the time difference from now using `delta_now()`. ```python import HABApp from HABApp.core.items import Item from HABApp.rule.scheduler import minutes, seconds, InstantView class TimestampRule(HABApp.Rule): def __init__(self): super().__init__() # This item was created by another rule, that's why "get_item" is used self.my_item = Item.get_item('Item_Name') # There are also functions available which support both building the delta directly and using an object if self.my_item.last_change.newer_than(minutes=2, seconds=30): print('Item was changed in the last 2min 30s') if self.my_item.last_change.older_than(seconds(30)): print('Item was changed before 30s') # if you want to do calculations you can also get a delta delta_to_now = self.my_item.last_change.delta_now() # Instead of dealing with timestamps you can also have the same convenience # for arbitrary timestamps by using the InstantView object timestamp = InstantView.now() assert timestamp.newer_than(minutes=1) delta_to_now = timestamp.delta_now() # moving forward / backwards in time in_one_minute = timestamp.add(minutes=1) in_one_minute = timestamp + seconds(60) in_one_minute = timestamp + 60 in_one_minute = timestamp + 'PT60S' assert in_one_minute.newer_than(timestamp) TimestampRule() ``` -------------------------------- ### Run HABApp (Bash) Source: https://github.com/spacemanspiff2007/habapp/wiki/Installation-&-Autostart Executes the HABApp application. The `-c` flag specifies the path to the configuration folder. Replace `PATH_TO_CONFIGURATION_FOLDER` with the actual path. ```bash habapp -c PATH_TO_CONFIGURATION_FOLDER ``` -------------------------------- ### Install HABApp Dependencies (Bash) Source: https://github.com/spacemanspiff2007/habapp/wiki/Installation-&-Autostart Installs necessary development packages for Python 3 using apt. This is a prerequisite for creating and managing Python virtual environments. ```bash sudo apt install python3-dev python3-venv ``` -------------------------------- ### Run HABApp Docker container Source: https://github.com/spacemanspiff2007/habapp/blob/master/docs/installation.rst This command starts a HABApp Docker container with specified configurations. It maps a local directory for configuration, sets environment variables for timezone and user/group IDs, and runs the latest HABApp image interactively. The `--rm` flag ensures the container is removed upon exit. ```bash docker run --rm -it --name habapp \ -v ${PWD}/habapp_config:/habapp/config \ -e TZ=Europe/Berlin \ -e USER_ID=9001 \ -e GROUP_ID=9001 \ spacemanspiff2007/habapp:latest ``` -------------------------------- ### Create and Activate HABApp Virtual Environment (Bash) Source: https://github.com/spacemanspiff2007/habapp/wiki/Installation-&-Autostart Creates a Python virtual environment named 'habapp' in the current directory and then activates it. Activating the environment ensures that subsequent Python package installations are isolated to this environment. ```bash python3 -m venv habapp cd habapp source bin/activate ``` -------------------------------- ### Run custom extended HABApp image Source: https://github.com/spacemanspiff2007/habapp/blob/master/docs/installation.rst This command starts a Docker container using your custom-built `my_habapp_extended:latest` image. It's similar to running the base HABApp image, including volume mounting for configuration and setting environment variables. ```bash docker run --rm -it --name habapp \ -v ${PWD}/habapp_config:/habapp/config \ -e TZ=Europe/Berlin \ -e USER_ID=9001 \ -e GROUP_ID=9001 \ my_habapp_extended:latest ``` -------------------------------- ### Print Item Changes and Last Change Source: https://github.com/spacemanspiff2007/habapp/blob/master/docs/getting_started.rst This snippet demonstrates how to print notifications when an item's name changes and display the last modification time of a specific item. It utilizes f-strings for formatted output. ```python print(f'{event.name} changed from "{event.old_value}" to "{event.value}"') print(f'Last change of {self.my_item.name}: {self.my_item.last_change}') ``` -------------------------------- ### Create and Activate HABApp Virtual Environment (Windows) Source: https://github.com/spacemanspiff2007/habapp/blob/master/docs/installation.rst Steps to create a Python virtual environment for HABApp on Windows systems. This isolates HABApp dependencies from the system's Python installation. It involves navigating to a directory, creating the environment using `venv`, and activating it using a batch script. ```batch cd C:\path\to\your\directory python -m venv habapp cd habapp Scripts\activate ``` -------------------------------- ### Create and Activate HABApp Virtual Environment (Linux) Source: https://github.com/spacemanspiff2007/habapp/blob/master/docs/installation.rst Steps to create a Python virtual environment for HABApp on Linux systems. This isolates HABApp dependencies from the system's Python installation. It involves navigating to a directory, creating the environment using `venv`, and activating it using the `source` command. ```bash cd /opt python3 -m venv habapp cd habapp source bin/activate ``` -------------------------------- ### Dockerfile for HABApp with additional libraries Source: https://github.com/spacemanspiff2007/habapp/blob/master/docs/installation.rst This Dockerfile demonstrates how to build a custom HABApp image that includes additional Python libraries like scipy, pandas, and numpy. It uses a multi-stage build process, first installing build dependencies and wheels, then installing the runtime dependencies and the specified Python packages into the final image. ```dockerfile FROM spacemanspiff2007/habapp:latest as buildimage RUN set -eux; \ # Install required build dependencies (Optional) apt-get update; \ DEBIAN_FRONTEND=noninteractive apt-get install --no-install-recommends -y \ build-essential; \ # Prepare python packages pip3 wheel \ --wheel-dir=/root/wheels \ # Replace 'scipy pandas numpy' with your libraries scipy pandas numpy FROM spacemanspiff2007/habapp:latest COPY --from=buildimage /root/wheels /root/wheels RUN set -eux; \ # Install required runtime dependencies (Optional) apt-get update; \ DEBIAN_FRONTEND=noninteractive apt-get install --no-install-recommends -y \ bash; \ apt-get clean; \ rm -rf /var/lib/apt/lists/*; \ # Install python packages and cleanup pip3 install \ --no-index \ --find-links=/root/wheels \ # Replace 'scipy pandas numpy' with your libraries scipy pandas numpy; \ rm -rf /root/wheels ``` -------------------------------- ### Conditional Value Posting with post_value_if Source: https://github.com/spacemanspiff2007/habapp/blob/master/docs/getting_started.rst This snippet demonstrates the `post_value_if` convenience function for conditionally posting values to an item. It shows how to post if a value is not equal to, or if it is equal to, a specified value. ```python from HABApp.core.items import Item class MyFirstRule(HABApp.Rule): def __init__(self): super().__init__() self.my_item = Item.get_create_item('Item_Name') self.run.soon(self.say_something) def say_something(self): # This construct if self.my_item != 'overwrite value': self.my_item.post_value('Test') # ... is equivalent to self.my_item.post_value_if('Test', not_equal='overwrite value') # This construct if self.my_item == 'overwrite value': self.my_item.post_value('Test') # ... is equivalent to self.my_item.post_value_if('Test', equal='overwrite value') MyFirstRule() ``` -------------------------------- ### Install HABApp using pip Source: https://github.com/spacemanspiff2007/habapp/blob/master/docs/installation.rst Installs the latest version of HABApp using pip within an activated virtual environment. It also upgrades pip and setuptools to ensure compatibility. The command assumes the virtual environment is already activated. ```bash python3 -m pip install --upgrade pip setuptools python3 -m pip install habapp ``` -------------------------------- ### Install a Specific HABApp Version Source: https://github.com/spacemanspiff2007/habapp/blob/master/docs/installation.rst Installs a specific version of HABApp using pip. This is useful for rolling back to a known stable version or testing a particular release. The version number is appended to the package name with `==`. ```bash python3 -m pip install HABApp==23.12.0 ``` -------------------------------- ### HABApp MultiModeItem Basic Example in Python Source: https://github.com/spacemanspiff2007/habapp/blob/master/docs/util.rst Demonstrates the basic usage of HABApp's MultiModeItem. It shows how to create a MultiModeItem, define and add modes with priorities, listen for value updates, and enable/disable modes. This example is suitable for understanding the fundamental concepts of MultiModeItem. ```python import HABApp from HABApp.core.events import ValueUpdateEventFilter from HABApp.util.multimode import MultiModeItem, ValueMode class MyMultiModeItemTestRule(HABApp.Rule): def __init__(self): super().__init__() # create a new MultiModeItem item = MultiModeItem.get_create_item('MultiModeTestItem') item.listen_event(self.item_update, ValueUpdateEventFilter()) # create two different modes which we will use and add them to the item auto = ValueMode('Automatic', initial_value=5) manu = ValueMode('Manual', initial_value=0) # Add the auto mode with priority 0 and the manual mode with priority 10 item.add_mode(0, auto).add_mode(10, manu) # This shows how to enable/disable a mode and how to get a mode from the item print('disable/enable the higher priority mode') item.get_mode('manual').set_enabled(False) # disable mode item.get_mode('manual').set_value(11) # setting a value will enable it again # This shows that changes of the lower priority is only shown when # the mode with the higher priority gets disabled print('') print('Set value of lower priority') auto.set_value(55) print('Disable higher priority') manu.set_enabled(False) def item_update(self, event): print(f'State: {event.value}') MyMultiModeItemTestRule() ``` -------------------------------- ### Pull HABApp Docker image Source: https://github.com/spacemanspiff2007/habapp/blob/master/docs/installation.rst This command downloads the latest version of the HABApp Docker image from Docker Hub. Ensure Docker is installed and configured on your system before running this command. ```bash docker pull spacemanspiff2007/habapp:latest ``` -------------------------------- ### View HABApp Command Line Arguments Source: https://github.com/spacemanspiff2007/habapp/blob/master/docs/installation.rst Execute HABApp with the '-h' flag to display all available command-line arguments and their descriptions. This is useful for understanding the different options for running and configuring HABApp from the terminal. ```shell habapp -h ``` ```python import HABApp.__main__ HABApp.__cmd_args__.parse_args(['-h']) ``` -------------------------------- ### HABApp openHAB Rule Example Source: https://github.com/spacemanspiff2007/habapp/blob/master/docs/interface_openhab.rst This is a basic example of an openHAB rule written using HABApp in Python. It demonstrates how to structure and implement rules within the HABApp framework. ```python from HABApp import Rule class MyRule(Rule): def __init__(self): super().__init__() # Add your rule logic here print("MyRule initialized!") MyRule() ``` -------------------------------- ### HABApp Logging: Full YAML Configuration Example Source: https://github.com/spacemanspiff2007/habapp/blob/master/docs/logging.rst This is a comprehensive example of a HABApp logging configuration in YAML format. It includes definitions for formatters, file handlers (default and custom), and loggers. This configuration sets up logging for HABApp itself and a custom logger named 'MyRule', directing their output to specified files with defined formats and levels. ```yaml # ----------------------------------------------------------------------------------- # Configuration of the available output formats # ----------------------------------------------------------------------------------- formatters: HABApp_format: format: '[%(asctime)s] [%(name)25s] %(levelname)8s | %(message)s' # ----------------------------------------------------------------------------------- # Configuration of the available file handlers (output files) # ----------------------------------------------------------------------------------- handlers: HABApp_default: class: HABApp.config.logging.MidnightRotatingFileHandler filename: 'HABApp.log' maxBytes: 10_000_000 backupCount: 3 formatter: HABApp_format level: DEBUG MyRuleHandler: class: HABApp.config.logging.MidnightRotatingFileHandler filename: 'c:\\HABApp\\Logs\\MyRule.log' maxBytes: 10_000_000 backupCount: 3 formatter: HABApp_format level: DEBUG # ----------------------------------------------------------------------------------- # Configuration of all available loggers and their configuration # ----------------------------------------------------------------------------------- loggers: HABApp: level: DEBUG handlers: - HABApp_default propagate: False MyRule: level: DEBUG handlers: - MyRuleHandler propagate: False ``` -------------------------------- ### Stop and update HABApp Docker image Source: https://github.com/spacemanspiff2007/habapp/blob/master/docs/installation.rst These commands first stop the running HABApp container named 'habapp' and then pull the latest version of the HABApp Docker image from Docker Hub, preparing for an update. ```bash docker stop habapp docker pull spacemanspiff2007/habapp:latest ``` -------------------------------- ### Build custom extended HABApp image Source: https://github.com/spacemanspiff2007/habapp/blob/master/docs/installation.rst This command builds a Docker image with the tag `my_habapp_extended:latest` using the current directory's Dockerfile. This allows you to create a personalized HABApp image with your specific configurations and dependencies. ```bash docker build -t my_habapp_extended:latest . ``` -------------------------------- ### Manage openHAB Things with HABapp Python Source: https://context7.com/spacemanspiff2007/habapp/llms.txt Provides examples of how to retrieve information about a specific thing in openHAB, such as its status and label, and how to enable or disable a thing using the HABapp library. It demonstrates the `get_thing` and `set_thing_enabled` functions. ```python def manage_things(self): """Work with things""" # Get thing information thing = self.oh.get_thing('zwave:device:controller:node15') if thing: self.log.info(f"Thing status: {thing.status}") self.log.info(f"Thing label: {thing.label}") # Enable/disable thing self.oh.set_thing_enabled('zwave:device:controller:node15', enabled=False) # Re-enable self.oh.set_thing_enabled('zwave:device:controller:node15', enabled=True) ``` -------------------------------- ### Run HabApp Rules with SimpleRuleRunner (Python) Source: https://github.com/spacemanspiff2007/habapp/blob/master/docs/troubleshooting.rst This snippet demonstrates how to initialize and run rules within HabApp using the SimpleRuleRunner. It imports the necessary runner class and executes a predefined 'run()' function. Ensure 'rule_runner' is installed and 'run()' is defined elsewhere in the project. ```python from rule_runner import SimpleRuleRunner SimpleRuleRunner().run(run()) ``` -------------------------------- ### MQTT Rule Example in Python Source: https://github.com/spacemanspiff2007/habapp/blob/master/readme.md This Python code demonstrates how to create a HABApp rule for MQTT automation. It utilizes asyncio to schedule periodic publishing of random values to a MQTT topic and listens for updates on specific topics. It also shows how to create and manage a MqttItem to store and track changes in topic payloads. ```python import datetime import random import HABapp from HABApp.mqtt.items import MqttItem from HABApp.core.events import ValueChangeEvent, ValueChangeEventFilter, ValueUpdateEvent, ValueUpdateEventFilter class ExampleMqttTestRule(HABApp.Rule): def __init__(self): super().__init__() self.run.every( start_time=datetime.timedelta(seconds=60), interval=datetime.timedelta(seconds=30), callback=self.publish_rand_value ) # this will trigger every time a message is received under "test/test" self.listen_event('test/test', self.topic_updated, ValueUpdateEventFilter()) # This will create an item which will store the payload of the topic so it can be accessed later. self.item = MqttItem.get_create_item('test/value_stored') # Since the payload is now stored we can trigger only if the value has changed self.item.listen_event(self.item_topic_updated, ValueChangeEventFilter()) def publish_rand_value(self): print('test mqtt_publish') self.mqtt.publish('test/test', str(random.randint(0, 1000))) def topic_updated(self, event: ValueUpdateEvent): assert isinstance(event, ValueUpdateEvent), type(event) print( f'mqtt topic "test/test" updated to {event.value}') def item_topic_updated(self, event: ValueChangeEvent): print(self.item.value) # will output the current item value print( f'mqtt topic "test/value_stored" changed from {event.old_value} to {event.value}') ExampleMqttTestRule() ``` -------------------------------- ### Perform Color Operations (RGB, HSB) with HabApp Source: https://context7.com/spacemanspiff2007/habapp/llms.txt Illustrates various color operations using RGB and HSB color types in HabApp. It shows how to create colors, convert between RGB and HSB, and apply these colors to a `ColorItem` (like an LED). The example includes cycling through a list of predefined colors with timed delays. Requires `RGB`, `HSB`, `ColorItem`, `self.log`, and `self.run` to be available. ```python def demonstrate_color_operations(self): """Color type operations""" # Create RGB color red = RGB(r=255, g=0, b=0) green = RGB(r=0, g=255, b=0) blue = RGB(r=0, g=0, b=255) # Create HSB color yellow_hsb = HSB(hue=60, saturation=100, brightness=100) cyan_hsb = HSB(hue=180, saturation=100, brightness=100) # Convert between types red_hsb = red.to_hsb() self.log.info( f"Red in HSB: H={red_hsb.hue}, S={red_hsb.saturation}, " f"B={red_hsb.brightness}" ) yellow_rgb = yellow_hsb.to_rgb() self.log.info( f"Yellow in RGB: R={yellow_rgb.r}, G={yellow_rgb.g}, B={yellow_rgb.b}" ) # Apply to ColorItem led = ColorItem.get_item('RGBLed') led.oh_send_command(red) # Cycle through colors colors = [ RGB(255, 0, 0), # Red RGB(0, 255, 0), # Green RGB(0, 0, 255), # Blue HSB(60, 100, 100), # Yellow HSB(300, 100, 100) # Magenta ] for i, color in enumerate(colors): self.run.countdown(i * 2, lambda c=color: led.oh_send_command(c)) ``` -------------------------------- ### Search openHAB Items by Type and Tags in Python Source: https://context7.com/spacemanspiff2007/habapp/llms.txt Demonstrates how to search for openHAB items using HABApp's `get_items` method. This example shows finding all SwitchItems tagged with 'Light' and turning them off. ```python def demonstrate_item_search(self): """Search for items""" # Find all switches tagged 'Light' lights = self.get_items(type=SwitchItem, tags='Light') for light in lights: light.off() # Find items by name pattern temp_sensors = self.get_items( type=NumberItem, ``` -------------------------------- ### HABApp openHAB Item Type Examples (Python) Source: https://github.com/spacemanspiff2007/habapp/blob/master/docs/interface_openhab.rst Demonstrates how to create, retrieve, and interact with different openHAB item types within HABApp using Python. This includes ContactItem and SwitchItem, showcasing their respective methods. ```python import HABApp from HABApp.openhab.items import ContactItem, SwitchItem HABApp.core.Items.add_item(ContactItem('MyContact', initial_value='OPEN')) HABApp.core.Items.add_item(SwitchItem('MySwitch', initial_value='OFF')) my_contact = ContactItem.get_item('MyContact') if my_contact.is_open(): print('Contact is open!') my_switch = SwitchItem.get_item('MySwitch') if my_switch.is_on(): my_switch.off() ``` -------------------------------- ### HABApp Logging: Python Rule Example Source: https://github.com/spacemanspiff2007/habapp/blob/master/docs/logging.rst This Python code snippet demonstrates how to use the HABApp logging library within a rule. It shows how to get a logger instance and log messages at different levels. Ensure the logging system is configured in logging.yml for this to function correctly. ```python from HABApp.openhab import, from HABApp.core.items import ItemManager class MyRule(RuleBase): def __init__(self): super().__init__() self.log.info("MyRule started!") def on_vm_command(self, command: str): self.log.debug(f"Received command: {command}") if command == "test": self.log.warning("This is a test warning") self.log.error("This is a test error") elif command == "test2": self.log.info("This is another test") else: self.log.info("Command not recognized") ``` -------------------------------- ### Demonstrate GroupItem Operations in Python Source: https://context7.com/spacemanspiff2007/habapp/llms.txt Explains how to work with GroupItems in HABApp, including iterating through group members to access individual item states and sending commands to them. It also demonstrates how to get the aggregated state of the group. ```python def demonstrate_group_operations(self): """GroupItem methods""" # Get all members for member in self.lights_group.members: self.log.info(f"Member: {member.name}, State: {member.value}") if isinstance(member, SwitchItem) and member.is_on(): member.off() # Group state reflects aggregation function group_state = self.lights_group.value self.log.info(f"Group state: {group_state}") ``` -------------------------------- ### Create or Get HABApp Item Source: https://github.com/spacemanspiff2007/habapp/blob/master/docs/rule.rst Demonstrates how to get or create items within HABApp. `get_create_item` will create an item if it doesn't exist, while `get_item` will raise an exception if the item is not found. This ensures proper item class instantiation and provides type hints for IDEs. ```python from HABApp.core.items import Item my_item = Item.get_create_item('MyItem', initial_value=5) # This will create the item if it does not exist my_item = Item.get_item('MyItem') # This will raise an exception if the item is not found print(my_item) ``` -------------------------------- ### HABApp MultiModeItem Advanced Example in Python Source: https://github.com/spacemanspiff2007/habapp/blob/master/docs/util.rst Illustrates advanced features of HABApp's MultiModeItem, including automatic mode disabling based on custom logic and using functions to calculate mode values. It also shows how to integrate logging for better debugging. This example is for users needing more complex control flow. ```python import logging import sys import HABapp from HABApp.core.events import ValueUpdateEventFilter from HABApp.util.multimode import MultiModeItem, ValueMode root = logging.getLogger('AdvancedMultiMode') root.setLevel(logging.DEBUG) handler = logging.StreamHandler(sys.stdout) handler.setLevel(logging.DEBUG) formatter = logging.Formatter('[%(name)17s] %(levelname)8s | %(message)s') handler.setFormatter(formatter) root.addHandler(handler) class MyMultiModeItemTestRule(HABApp.Rule): def __init__(self): super().__init__() # create a new MultiModeItem item = MultiModeItem.get_create_item('MultiModeTestItem') item.listen_event(self.item_update, ValueUpdateEventFilter()) # helper to print the heading so we have a nice output def print_heading(_heading): print('') print('-' * 80) print(_heading) print('-' * 80) for p, m in item.all_modes(): print(f'Prio {p:2d}: {m}') print('') log = logging.getLogger('AdvancedMultiMode') # create modes and add them auto = ValueMode('Automatic', initial_value=5, logger=log) manu = ValueMode('Manual', initial_value=10, logger=log) item.add_mode(0, auto).add_mode(10, manu) # it is possible to automatically disable a mode # this will disable the manual mode if the automatic mode # sets a value greater equal manual mode print_heading('Automatically disable mode') # A custom function can also disable the mode: manu.auto_disable_func = lambda low, own: low >= own auto.set_value(11) # <-- manual now gets disabled because auto.set_value(4) # the lower priority value is >= itself # It is possible to use functions to calculate the new value for a mode. # E.g. shutter control and the manual mode moves the shades. If it's dark the automatic def item_update(self, event): print(f'State: {event.value}') MyMultiModeItemTestRule() ``` -------------------------------- ### Python HABApp MQTT Rule - Subscribe and Publish Source: https://context7.com/spacemanspiff2007/habapp/llms.txt This Python code defines a HABApp rule for MQTT integration. It demonstrates subscribing to multiple MQTT topics with different QoS levels, creating and managing MQTT items, listening for value changes and updates, and publishing various data types including strings, numbers, dictionaries, and lists. It also includes examples of publishing on a schedule and dynamic subscription management. ```python import HABApp from HABApp.mqtt.items import MqttItem from HABApp.core.events import ValueChangeEventFilter, ValueUpdateEventFilter from datetime import datetime import json class MQTTRule(HABApp.Rule): def __init__(self): super().__init__() # Subscribe to topics self.mqtt.subscribe('home/sensors/#', qos=1) self.mqtt.subscribe('home/commands/#', qos=2) # Multiple subscriptions with different QoS self.mqtt.subscribe([ ('home/critical/#', 2), ('home/info/#', 0), ('home/status/#', 1) ]) # Create MQTT items to store values self.temperature = MqttItem.get_create_item('home/temperature', 20.0) self.humidity = MqttItem.get_create_item('home/humidity', 50.0) self.status = MqttItem.get_create_item('home/status') # Listen to MQTT topic changes self.temperature.listen_event( self.on_temperature_change, ValueChangeEventFilter() ) # Listen to all updates (even if value unchanged) self.listen_event( 'home/heartbeat', self.on_heartbeat, ValueUpdateEventFilter() ) # Listen to any topic matching pattern self.listen_event( 'home/sensors/+/battery', self.on_battery_update, ValueUpdateEventFilter() ) # Publish on schedule self.run.at( self.run.trigger.interval(0, 60), self.publish_status ) def on_temperature_change(self, event): """Handle temperature changes""" old_temp = event.old_value new_temp = event.value self.log.info(f"Temperature changed from {old_temp}°C to {new_temp}°C") # Publish alert if temperature too high if new_temp > 30: self.mqtt.publish( 'home/alerts/temperature', json.dumps({ 'level': 'warning', 'value': new_temp, 'timestamp': datetime.now().isoformat() }), qos=2, retain=True ) def on_heartbeat(self, event): """Process heartbeat messages""" self.log.debug(f"Heartbeat: {event.value}") def on_battery_update(self, event): """Monitor battery levels from sensors""" topic = event.name battery_level = event.value # Extract sensor name from topic sensor_name = topic.split('/')[2] if battery_level < 20: self.log.warning( f"Low battery on {sensor_name}: {battery_level}%" ) self.mqtt.publish( f'home/alerts/battery/{sensor_name}', {'sensor': sensor_name, 'level': battery_level}, qos=1, retain=True ) def publish_examples(self): """Various publishing examples""" # Publish string self.mqtt.publish('home/status', 'online', qos=1, retain=True) # Publish number self.mqtt.publish('home/temperature', 22.5) # Publish dict (auto-converted to JSON) self.mqtt.publish('home/sensor/data', { 'temperature': 22.5, 'humidity': 55, 'timestamp': datetime.now().isoformat() }) # Publish list (auto-converted to JSON) self.mqtt.publish('home/sensor/readings', [22.5, 55, 1013.25]) # Publish via item self.temperature.publish(23.0, qos=1, retain=True) # Alternative: send command (publishes to topic) self.temperature.command_value(23.0) def publish_status(self): """Periodic status publishing""" status_data = { 'timestamp': datetime.now().isoformat(), 'uptime': self.get_uptime(), 'temperature': self.temperature.value, 'humidity': self.humidity.value, 'rules_loaded': len(self.get_rule(None)) } self.mqtt.publish( 'home/habapp/status', status_data, qos=1, retain=True ) def get_uptime(self): """Calculate uptime (example)""" # Implementation would track start time return "1d 5h 23m" def dynamic_subscriptions(self): """Subscribe and unsubscribe at runtime""" # Subscribe to new topic self.mqtt.subscribe('home/dynamic/sensor', qos=1) # Unsubscribe from topic self.mqtt.unsubscribe('home/dynamic/sensor') # Unsubscribe from multiple topics self.mqtt.unsubscribe([ 'home/temp1', 'home/temp2', 'home/temp3' ]) def bridging_mqtt_openhab(self): """Bridge between MQTT and openHAB""" # Listen to MQTT ``` -------------------------------- ### Example MQTT Rule Implementation in Python Source: https://github.com/spacemanspiff2007/habapp/blob/master/docs/interface_mqtt.rst A sample MQTT rule implemented in Python using HABApp. This snippet shows how to define and execute a rule that interacts with MQTT messages, likely for automation or device control. ```python from HABApp.openhab.items import StringItem from HABApp.mqtt.events import MqttMessageEvent class MqttRule(SimpleRule): def __init__(self): super().__init__() self.add_timer(datetime.timedelta(seconds=10), self.send_hello_world) self.mqtt_subscriber.add_listener(self.mqtt_listener, "lawnmower/status") def mqtt_listener(self, mqtt_event: MqttMessageEvent): self.log.info(f"Received MQTT message: {mqtt_event.payload}") def send_hello_world(self): self.log.info("Sending hello world") self.mqtt_publisher.publish("lawnmower/command", "start") ``` -------------------------------- ### Demonstrate ContactItem Operations in Python Source: https://context7.com/spacemanspiff2007/habapp/llms.txt Provides examples for interacting with ContactItems in HABApp, such as checking if a contact is open or closed, and programmatically setting the contact state to open or closed. Commonly used for sensors like door/window contacts. ```python def demonstrate_contact_operations(self): """ContactItem methods""" if self.contact.is_open(): self.log.warning("Window is open!") elif self.contact.is_closed(): self.log.info("Window is closed") # Post state self.contact.open() self.contact.closed() ``` -------------------------------- ### Listen to Item Events with Filters in HABApp Python Source: https://context7.com/spacemanspiff2007/habapp/llms.txt This Python code demonstrates how to listen to various item events in HABApp, such as state changes, updates, and commands, using different event filters. It includes examples for simple filters, value-based conditions, specific transitions, and inactivity detection. Dependencies include the HABApp library and relevant item types. ```python import HABapp from HABApp.openhab.items import NumberItem, ContactItem, SwitchItem from HABApp.openhab.events import ( ItemStateChangedEventFilter, ItemStateUpdatedEventFilter, ItemCommandEventFilter ) from HABApp.core.events import ValueChangeEventFilter, AndFilterGroup from datetime import timedelta class EventListenerRule(HABapp.Rule): def __init__(self): super().__init__() # Listen to any state change self.listen_event( 'TemperatureSensor', self.on_temperature_change, ItemStateChangedEventFilter() ) # Listen only when temperature goes above 25°C self.listen_event( 'TemperatureSensor', self.on_high_temperature, ItemStateChangedEventFilter(value=lambda v: v > 25) ) # Listen to all updates (even if value unchanged) self.listen_event( 'HeartbeatSensor', self.on_sensor_update, ItemStateUpdatedEventFilter() ) # Listen to commands sent to item self.listen_event( 'MainSwitch', self.on_switch_command, ItemCommandEventFilter() ) # Listen to specific state transitions contact = ContactItem.get_item('DoorSensor') contact.listen_event( self.on_door_opened, ItemStateChangedEventFilter(value='OPEN', old_value='CLOSED') ) # Watch for no update/change for duration self.motion = SwitchItem.get_item('MotionSensor') self.motion.watch_change(timedelta(minutes=10)) self.listen_event( 'MotionSensor', self.on_no_motion, HABApp.core.events.ItemNoChangeEventFilter() ) def on_temperature_change(self, event): """Handles any temperature change""" self.log.info( f"Temperature changed from {event.old_value}°C to {event.value}°C" ) def on_high_temperature(self, event): """Only called when temperature exceeds threshold""" self.log.warning(f"High temperature alert: {event.value}°C") self.openhab.send_command('CoolingSystem', 'ON') def on_sensor_update(self, event): """Called on every update, even if value unchanged""" self.log.debug(f"Heartbeat received: {event.value}") def on_switch_command(self, event): """Called when command sent to switch""" self.log.info(f"Switch commanded to: {event.value}") def on_door_opened(self, event): """Called only when door transitions from CLOSED to OPEN""" self.log.warning("Door opened!") self.openhab.send_command('AlarmTrigger', 'ON') def on_no_motion(self, event): """Called when no motion detected for 10 minutes""" self.log.info(f"No motion for {event.seconds} seconds") self.openhab.send_command('SecurityMode', 'AWAY') EventListenerRule() ```