HASS.Agent: Windows client to receive notifications, use commands, sensors, quick actions and more!

2022.11.4 doesn’t support the mediaplayer yet, you need at least a 2022.12.* beta variant.

You can get the installer here: https://github.com/LAB02-Research/HASS.Agent/releases/download/2022.12.0-beta4/HASS.Agent.Installer.exe

No need to uninstall your current version, just run this and it should work :slight_smile:

YUP That was it. Sorry the last message you sent I misread and kept installing the stable version, gosh darn.

Anyways, thanks for being so patient and helping out.

Really no problem at all, glad it’s working for you!

Thanks so much for this. Works like a champ and has a much nicer UI than what I was using before.

OK! I’ll work on it :smiley:

What’s your intent behind your current logo btw? I want to design something that makes sense for you and the users. I can also just keep it the same but make it compatible with the Windows look.

Awesome!

I just took an icon of a satellite, as it kinda functions as a satellite for Home Assistant. So if you want to go a completely different route, feel free! There’s no special connection I have with it or anything like that.

1 Like

Thank you @RNeal for taking the time to post, I really appreciate it :slight_smile:

If I understood you correctly, then you, like me, periodically have iotlink crashes, then you can read here the option of how to restart the iotlink service. I have created a sensor that monitors the iotlink and as soon as the sensor is unavailable, a batnik is launched that restarts the iotlink service

I gave up on IOT Link and now use HASS.Agent. Seems to work much better for me. Thanks anyway.

1 Like

I will share my version of how you can scatter the running process into categories. This will be very useful if you need, for example, to automate the control of the brightness of the computer monitor screen and divide the brightness of the screen for games, for movies, for work. For example, before the game was launched, the screen brightness was 10-20%, and the brightness of 40% is set in the game, and as the game was minimized to the tray, the brightness will return to the one that was before switching to the game. You can also use this option for computer coolers, for a specific game, by setting the desired effect, or when starting the game, turn on the ambilight on the monitor.

You can read a post about how to adjust the brightness control of a computer monitor screen here

You can watch the video for understanding and how you can use Hotlink\HassAgent

  1. Control of custom RGB backlight on a computer using LED + IO Link or HassAgent

  2. This is how ambilight works and which automatically turns on and off when you start or turn off games

  3. Home Assistant. Automating Hyperion

  4. Home Assistant. Led FX. Music Visualization

The sensor of the active window itself is taken from here

This is how the card looks for entering keywords and the category of the process being performed
image

First, we create auxiliary text input elements. We need them to enter keywords and this will work in conjunction with the sensor that monitors the active window.

input_text:
  pc_livingroom_games_keywords:
    name: 'Living room: Computer. Games. Keywords'
    min: 0
    max: 100000
    icon: mdi:google-controller

  pc_livingroom_videoplayer_keywords:
    name: 'Living room: Computer. Video player. Keywords'
    min: 0
    max: 100000
    icon: mdi:video

  pc_livingroom_browser_keywords:
    name: 'Living room: Computer. Browser. Keywords'
    min: 0
    max: 100000
    icon: mdi:web

Let’s create a sensor that will compare keywords with the sensor of the active window and sort them into categories game, movie, browser etc

#Sensor Living Room: Computer. Game
sensor:
  - platform: template
    sensors:
      hassagent_pc_livingroom_running_game:
        friendly_name: "Living room: Computer. Game"
        icon_template: mdi:google-controller
        value_template: >
            {% set activewindow = states("sensor.pc_livingroom_activewindow") %}
            {% set games = states("input_text.pc_livingroom_games_keywords") %}
            {% if activewindow | string is search(find=games) %} on
            {% else %} off
            {% endif %}


#Sensor Living Room: Computer. Video Player
  - platform: template
    sensors:
      hassagent_pc_livingroom_running_videoplayer:
        friendly_name: "Living room: Computer. Video Player"
        icon_template: mdi:video
        value_template: >
            {% set activewindow = states("sensor.pc_livingroom_activewindow") %}
            {% set videoplayer = states("input_text.pc_livingroom_videoplayer_keywords") %}
            {% if activewindow | string is search(find=videoplayer) %} on
            {% else %} off
            {% endif %}


#Sensor Living Room: Computer. Browser
  - platform: template
    sensors:
      hassagent_pc_livingroom_running_browser:
        friendly_name: "Living room: Computer. Browser"
        icon_template: mdi:web
        value_template: >
            {% set activewindow = states("sensor.pc_livingroom_activewindow") %}
            {% set browser = states("input_text.pc_livingroom_browser_keywords") %}
            {% if activewindow | string is search(find=browser) %} on
            {% else %} off
            {% endif %}

For example, I will give automation for adjusting the brightness of the screen for games.

alias: 'Living room: Monitor. Auto brightness of the screen. Games'
description: >-
  Will automatically adjust the screen brightness for games. When starting the game
  the brightness will be set to 40%, and when the game is turned off, the brightness
  will be restored from history
trigger:
  - platform: state
    entity_id:
      - sensor.hassagent_pc_livingroom_running_game
    from: 'off'
    to: 'on'
    id: The game is running
  - platform: state
    entity_id:
      - sensor.hassagent_pc_livingroom_running_game
    from: 'on'
    to: 'off'
    id: The game is off
condition:
  - condition: template
    value_template: '{{ is_state("switch.pc_livingroom", "on") }}'
action:
  - choose:
      - conditions:
          - condition: trigger
            id: The game is running
        sequence:
          - service: scene.create
            data:
              snapshot_entities:
                - light.livingroom_monitor_brightness
              scene_id: livingroom_monitor_brightness_history
          - delay:
              hours: 0
              minutes: 0
              seconds: 5
              milliseconds: 0
          - service: light.turn_on
            data:
              brightness_pct: 40
            target:
              entity_id: light.livingroom_monitor_brightness
      - conditions:
          - condition: trigger
            id: The game is off
        sequence:
          - service: scene.turn_on
            target:
              entity_id: scene.livingroom_monitor_brightness_history
            metadata: {}
    default: []
mode: single

Текст на русском (Text in Russian)

Поделюсь своим вариантом, как можно разбросать запущенный процесс по категориям. Это будет очень полезным, если нужно например автоматизировать управление яркости экрана компьютерного монитора и разделить яркость экрана для игр, для фильмов, для работы. Например до запуска игры яркость экрана была 10-20%, а в игре выставляется яркость 40% и как свернули игру в трей, яркость вернется к той, которая была до переключения в игру. Можно также использовать такой вариант для компьютерных кулеров, для конкретной игры, выставив нужный эффект или при запуске игры включить амбилайт на мониторе.

Почитать пост про то, как настроить управление яркости экрана компьютерного монитора можете здесь

Можете посмотреть видео для понимания и как можно использовать IOTLink\HassAgent

  1. Управление кастомной RGB подсветки на компьютере с помощью WLED + IOTLink или HassAgent

  2. Вот так выглядит работа амбилайт и которая автоматически включается и выключается при запуске или выключении игр

  3. Home Assistant. Автоматизируем Hyperion

  4. Home Assistant. LedFX. Визуализация музыки

Сам сенсор активного окна берется отсюда

Так выглядит карточка для ввода ключевых слов и категории выполняемого процесса
image

Сперва создаем вспомогательные элементы ввод текста. Они нам нужны для ввода ключевых слов и это будет работать в связке с сенсором который отслеживает активное окно.

input_text:
  pc_livingroom_games_keywords:
    name: 'Гостиная: Компьютер. Игры. Ключевые слова'
    min: 0
    max: 100000
    icon: mdi:google-controller

  pc_livingroom_videoplayer_keywords:
    name: 'Гостиная: Компьютер. Видеоплеер. Ключевые слова'
    min: 0
    max: 100000
    icon: mdi:video

  pc_livingroom_browser_keywords:
    name: 'Гостиная: Компьютер. Браузер. Ключевые слова'
    min: 0
    max: 100000
    icon: mdi:web

Создадим сенсор, который будет сверять ключевые слова с сенсором активного окна и раскидывать по категориям игра, кино, браузер и т.д

sensor:
  - platform: template
    sensors:
      hassagent_pc_livingroom_running_game:
        friendly_name: "Гостиная: Компьютер. Игра"
        icon_template: mdi:google-controller
        value_template: >
            {% set activewindow = states("sensor.pc_livingroom_activewindow") %}
            {% set games = states("input_text.pc_livingroom_games_keywords") %}
            {% if activewindow | string is search(find=games) %} on
            {% else %} off
            {% endif %}


#Сенсор Гостиная: Компьютер. Видеоплеер
  - platform: template
    sensors:
      hassagent_pc_livingroom_running_videoplayer:
        friendly_name: "Гостиная: Компьютер. Видеоплеер"
        icon_template: mdi:video
        value_template: >
            {% set activewindow = states("sensor.pc_livingroom_activewindow") %}
            {% set videoplayer = states("input_text.pc_livingroom_videoplayer_keywords") %}
            {% if activewindow | string is search(find=videoplayer) %} on
            {% else %} off
            {% endif %}


#Сенсор Гостиная: Компьютер. Браузер
  - platform: template
    sensors:
      hassagent_pc_livingroom_running_browser:
        friendly_name: "Гостиная: Компьютер. Браузер"
        icon_template: mdi:web
        value_template: >
            {% set activewindow = states("sensor.pc_livingroom_activewindow") %}
            {% set browser = states("input_text.pc_livingroom_browser_keywords") %}
            {% if activewindow | string is search(find=browser) %} on
            {% else %} off
            {% endif %}

Для примера приведу автоматизацию для регулировки яркости экрана для игр.

alias: 'Гостиная: Монитор. Авто яркость экрана. Игры'
description: >-
  Будет автоматически регулировать яркость экрана для игр. При запуске игры
  будет выставляться яркость на 40%, а когда игра будет выключена, то яркость
  будет восстановлена из истории
trigger:
  - platform: state
    entity_id:
      - sensor.hassagent_pc_livingroom_running_game
    from: 'off'
    to: 'on'
    id: Игра запущена
  - platform: state
    entity_id:
      - sensor.hassagent_pc_livingroom_running_game
    from: 'on'
    to: 'off'
    id: Игра выключена
condition:
  - condition: template
    value_template: '{{ is_state("switch.pc_livingroom", "on") }}'
action:
  - choose:
      - conditions:
          - condition: trigger
            id: Игра запущена
        sequence:
          - service: scene.create
            data:
              snapshot_entities:
                - light.livingroom_monitor_brightness
              scene_id: livingroom_monitor_brightness_history
          - delay:
              hours: 0
              minutes: 0
              seconds: 5
              milliseconds: 0
          - service: light.turn_on
            data:
              brightness_pct: 40
            target:
              entity_id: light.livingroom_monitor_brightness
      - conditions:
          - condition: trigger
            id: Игра выключена
        sequence:
          - service: scene.turn_on
            target:
              entity_id: scene.livingroom_monitor_brightness_history
            metadata: {}
    default: []
mode: single

1 Like

Really great work @DivanX10, thank you so much for sharing! :heart:

1 Like

Great piece of software @SamKr! I am enjoying it very much. However, I am experiencing a few issues with the LastSystemStateChange sensor. From what I’ve read I don’t think they have been addressed in this thread yet.

Last System State Change Sensor

I am trying to use the LastSystemStateChange sensor determine whether my pc is sleeping, shutdown, locked, etc. Unfortunately neither the agent or satellite service is able to detect a shutdown or suspend state when this sensor is active (lock and unlock work fine). This occurs even when set to a polling rate of one second. The status instantly changes to unavailable when a shutdown or suspend is triggered. I assume this is due to the availability_topic switching to offline in the sensor’s mqtt json config? I have programmed around this unavailable state with a template sensor in Home Assistant, but that just leaves me with SessionUnlock or whatever the active state was before the shutdown/suspend trigger.

Furthermore, sometimes when the computer resumes from a suspended state there is a reading discrepancy between the HASS Agent and Satellite service for this sensor. The HASS Agent sensor will report resume (correct), while the Satellite service sensor will report suspend (which should be what was reported when the suspend was triggered to begin with).

I’m not sure if these are known issues or if I have misunderstood the purpose of this sensor, so please let me know what you think.

2 Likes

Figured out how to implement the adjustment of screen brightness through HassAgent. We create a team and choose anything, since it doesn’t matter, but the color suits us

We create a light object using mqtt light and prescribe as below. You can control the brightness of the monitor screen

mqtt:
  light:
    - name: "Living room: Monitor. Screen Brightness"
      unique_id: "pc_livingroom_monitor_brightness"
      object_id: "pc_livingroom_monitor_brightness"
      command_topic: "homeassistant/light/LIVINGROOM/pc_livingroom_screen_brightness/action"
      brightness_command_topic: "homeassistant/light/LIVINGROOM/pc_livingroom_screen_brightness/action"
      brightness_command_template: "%LOCALAPPDATA%\\Microsoft\\WindowsApps\\Monitorian.exe /set {{ value }}"
      brightness_scale: 100
      on_command_type: 'brightness'
      icon: mdi:monitor-shimmer

To keep the brightness level in the auxiliary element number and for the values to be equal, then you need to use this code

{{ state_attr("light.pc_livingroom_monitor_brightness", "brightness")|multiply(0.392)|round(0) }}
1 Like

Hey all,

Been messing around today, and I’ve converted the RAM Usage of the HASS Agent from Percent into Usage/Total.

Now, most people probably don’t need this, but I find it easier to visualize a number rather than a percentage, so I though I’d share in-case anyone wanted it. It does require the use of a WMI Sensor and a template sensor to achieve, at least, for me it did.

HASS Agent WMI Query Sensor:

 WMI Query: SELECT Capacity FROM Win32_PhysicalMemory
    Scope: \\.\Root\CIMV2

I called laptop_ramtotal, but obviously, feel free to call it what you wish.

Home Assistant Template Sensor:

 - sensor:
        - name: "RAM Usage"
          state: >
            {% set ram = states('sensor.laptop_memoryusage') | float %}
            {% set ramTotal = states('sensor.laptop_ramtotal') | int * 2 / 1024 / 1024 / 1024 %}
            {% set usage = ramTotal | float / 100 * ram | round(0, default=0) %}
            {% set state = usage | string + "GB" + "/" + ramTotal | string + "GB" %}
    
            {{state}}

The sensor makes the assumption that you have 2 identical sticks of RAM installed, which you should have for performance, but if you only have 1 stick, simply remove the * 2.

sensor.laptop_memoryusage is my percentage sensor reported by HASS Agent by default. I simply changed my entity in the card from the HASS Percent Entity to my own sensor.

4 Likes

Thanks for the information. Useful. The more different examples there are with different implementations, the better it will be. Even if one of you finds it useless, it can be useful to the other. I’ll give you a :+1:. If there are other implementations, share :smiley:

I found an interesting feature in the work of Hass Agent. It’s about running the program through the Hass Agent. How do I run the program correctly?

If I put a check mark on run as ‘low integrity’, I can start the hyperion program by clicking on the button, but the hyperion program will start without displaying an icon in the Windows tray, and if without a check mark on run as ‘low integrity’, then clicking on the button, the hyperion program will not start.

This is what the button looks like, which, when pressed, launches the program

This is what the tray icon looks like when you just run the program, and if we run it with run as ‘low integrity’, then there will be no such icon in the tray
image

To run the program without the check mark on run as ‘low integrity’ and so that the program icon in the Windows tray is visible, I run the program through service: mqtt.publish in this way

You can find out the topic here

service: mqtt.publish
data:
  topic: homeassistant/button/LIVINGROOM/pc_livingroom_hyperion_launch/action
  payload: hyperiond

Here’s the most interesting thing, you can specify anything in the payload and hyperion will start anyway. Any of the options below will work and the hyperion program will run

service: mqtt.publish
data:
  topic: homeassistant/button/LIVINGROOM/pc_livingroom_hyperion_launch/action
  payload: C:\Program Files\Hyperion\bin\hyperiond.exe

---------------------------------------------------------------------------------------
service: mqtt.publish
data:
  topic: homeassistant/button/LIVINGROOM/pc_livingroom_hyperion_launch/action
  payload: hyperiond

---------------------------------------------------------------------------------------
service: mqtt.publish
data:
  topic: homeassistant/button/LIVINGROOM/pc_livingroom_hyperion_launch/action
  payload: ' '

Now the following. If you do not specify anything in the command field and leave the field empty, then you can run any program through service: mqtt.publish, though not any program. I use Windows 11 x64.

The cmd console doesn’t start for some reason

service: mqtt.publish
data:
  topic: homeassistant/button/LIVINGROOM/LIVINGROOM_launching_program/action
  payload: '"C:\Windows\System32\cmd.exe'"

And notepad starts

service: mqtt.publish
data:
  topic: homeassistant/button/LIVINGROOM/LIVINGROOM_launching_program/action
  payload: '"C:\Program Files\Notepad++\notepad++.exe"'
Текст на русском (Text in Russian)

Обнаружил интересную особенность в работе Hass Agent. Речь про запуск программы через Hass Agent. Как вообще правильно запускать программу?

Если я поставлю галочку на run as ‘low integrity’, я могу запустить программу hyperion нажав на кнопку, но программа hyperion запустится без отображения иконки в трее Windows, а если без галочки на run as ‘low integrity’, то нажав на кнопку, программа hyperion не запустится.

Так выглядит кнопка, которая при нажатии запускает программу

Так выглядит иконка в трее, когда просто запускаешь программу, а если запустим с run as ‘low integrity’, то такой иконки в трее не будет
image

Чтобы запустить программу без установленной галочки на run as ‘low integrity’ и чтобы была видна иконка программы в трее Windows, я запускаю программу через service: mqtt.publish таким образом

Узнать топик можно здесь

service: mqtt.publish
data:
  topic: homeassistant/button/LIVINGROOM/pc_livingroom_hyperion_launch/action
  payload: hyperiond

Вот тут самое интересное, в payload можно указать что угодно и все равно запустится hyperiond. Любой из вариантов ниже будет работать и программа hyperiond будет запускаться

service: mqtt.publish
data:
  topic: homeassistant/button/LIVINGROOM/pc_livingroom_hyperion_launch/action
  payload: C:\Program Files\Hyperion\bin\hyperiond.exe

---------------------------------------------------------------------------------------
service: mqtt.publish
data:
  topic: homeassistant/button/LIVINGROOM/pc_livingroom_hyperion_launch/action
  payload: hyperiond

---------------------------------------------------------------------------------------
service: mqtt.publish
data:
  topic: homeassistant/button/LIVINGROOM/pc_livingroom_hyperion_launch/action
  payload: ' '

Теперь следующее. Если в поле команды не указывать ничего и оставить поле пустым, то можно запустить любую программу через service: mqtt.publish, правда не любую программу. Использую Windows 11 x64.

Консоль cmd почему-то не запускается

service: mqtt.publish
data:
  topic: homeassistant/button/LIVINGROOM/LIVINGROOM_launching_program/action
  payload: '"C:\Windows\System32\cmd.exe'"

А блокнот запускается

service: mqtt.publish
data:
  topic: homeassistant/button/LIVINGROOM/LIVINGROOM_launching_program/action
  payload: '"C:\Program Files\Notepad++\notepad++.exe"'
2 Likes

Hi @DivanX10,

You’re beginning to understand HASS.Agent better than I do :grin: You’re right about everything, I’ll sum up the reasons etc:

  • When you create a CustomCommand, with the command defined within HASS.Agent, it will run ‘headless’, this means in the background without anything visible. This is ideal for commands that run and then close, but not so much for normal applications. I’ll add a ‘run normal’ checkbox, so you can use it to launch applications in normal mode. [hassagent-104]

  • When you run with ‘low integrity’, it will use a special method from within Windows to launch, which prevents it from writing to certain places on your harddrive. This is best for specific commands, not entire applications, because of the way it’s launched and restricted by Windows itself (I have no control over that).

  • When you don’t provide a command in HASS.Agent, but instead use the MQTT action topic, it will launch normal (within userspace, so visible). I’m not sure why the cmd won’t show, but that might be because the console doesn’t receive any actual command and closes itself.

If you need any more info (or changes), let me know :smiley:

1 Like

Thanks for sharing! I’ve added it to the docs. :heart:

I slightly altered the operation of the sensor for games by keywords, as I encountered a false trigger of the sensor for games when watching YouTube. On YouTube, keywords can match keywords for games and then when watching a game on YouTube, the game sensor will work. For example, keywords for games contain such words.

Halo Infinite|4 Engine|God of War|Forza Horizon

We launch YouTube with the game Halo Infinite and the game sensor will work for us, since the auxiliary element for the game has the keyword Halo Infinite. If we launch an online movie, the sensor game will work, although the game is not actually running.

What kind of content and where did it come from? Content is an auxiliary element text for keywords for content, everything that you watch through the browser, for example online movies, TV series, YouTube. This is how keywords for content look like

online|YouTube

Below is an example of a sensor that has a game check != content == ‘on’. If I watch YouTube or online movies and the keywords of the content match the keywords for the games, then the sensor game will not work

Note
ignorecase=True - ignoring the case comparison
ignorecase=False - don’t ignore the case comparison
games_kws - keywords for games
content_kws - keywords for content

Below is an example of a sensor for a game that has a check. If I watch YouTube or online movies and the keywords of the content match the keywords for the games, then the sensor game will not work

{% if game == True and content == False %} on

sensor:
  - platform: template
    sensors:
      hassagent_pc_livingroom_running_game:
        friendly_name: "Living room: Computer. Game"
        icon_template: mdi:google-controller
        value_template: >
            {% set activewindow = states("sensor.pc_livingroom_activewindow") %}
            {% set games_kws = states("input_text.pc_livingroom_games_keywords") %}
            {% set content_kws = states("input_text.pc_livingroom_content_keywords") %}
            {% set game = activewindow | string is search(find=games_kws, ignorecase=False) %}
            {% set content = activewindow | string is search(find=content_kws, ignorecase=False) %}
            {% if game == True and content == False %} on
            {% else %} off
            {% endif %}

Note that the template uses ignorecase=False\True. Why is this necessary and how does it work?

ignorecase is used to enable or disable case checking in words. We don’t always need a keyword search to be conducted for any case in words, but we need a keyword search to be conducted for a specific word and with a specific case. It all depends on the situation. I will give examples below

ignorecase=False - do not ignore the case comparison. The search will be case-sensitive and if the active sensor has HALO INFINITE, the word will not be detected, and if the active sensor has Halo Infinite, the word will be detected

Halo Infinite|4 Engine|God of War|Forza Horizon

ignorecase=True - ignore the case comparison. The search will be case-insensitive and if the active sensor has HALO INFINITY\Halo Infinity\HaLO INFINITE, the word will be detected regardless of which case it is specified in the keywords

HaLO INFINITE|4 EnGIne|God OF War|FORZa HoRIzon

To check the operation of ignorecase, you can use the options below

If we need to display a word instead of True\False

{{ 'HALO Infinite' | regex_findall("Halo Infinite") }}
{{ 'HALO Infinite' | regex_findall("HALO Infinite") }}
{{ 'HALO Infinite' | regex_findall("Halo Infinite", ignorecase=True) }}
{{ 'HALO Infinite' | regex_findall("Halo Infinite", ignorecase=False) }}

If we need to display True\False instead of the word

{{ 'HALO Infinite' | string is search("Halo Infinite") }}
{{ 'HALO Infinite' | string is search("HALO Infinite") }}
{{ 'HALO Infinite' | string is search(find="Halo Infinite", ignorecase=True) }}
{{ 'HALO Infinite' | string is search(find="Halo Infinite", ignorecase=False) }}

I will be glad if you offer your own version of the sensor for working with keywords

Текст на русском (Text in Russian)

Я не много переделал работу сенсора для игр по ключевым словам, так как столкнулся с ложным срабатыванием сенсора для игр при просмотре YouTube. На YouTube ключевые слова могут совпадать с ключевыми словами для игр и тогда при просмотре игры на YouTube сработает сенсор игра. Например в ключевых словах для игр указаны такие слова.

Halo Infinite|4 Engine|God of War|Forza Horizon

Запускаем YouTube с игрой Halo Infinite и у нас сработает сенсор игра, так как во вспомогательном элементе для игры имеется ключевое слово Halo Infinite. Если запустим онлайн фильм, то сработает сенсор игра, хотя игра не запущена в действительности.

Что за контент и откуда он взялся? Контент это вспомогательный элемент текст для ключевых слов для контента, все что смотрите через браузер, например онлайн фильмы, сериалы, YouTube. Вот так выглядят ключевые слова для контента

онлайн|YouTube

Примечание
ignorecase=True - игнорируем сравнение регистра
ignorecase=False - не игнорируем сравнение регистра
games_kws - ключевые слова для игр
content_kws - ключевые слова для контента

Ниже пример сенсора для игры который имеет проверку. Если смотрю YouTube или онлайн кино и ключевые слова контента совпадают с ключевыми словами для игр, то сенсор игра не сработает

{% if game == True and content == False %} on

sensor:
  - platform: template
    sensors:
      hassagent_pc_livingroom_running_game:
        friendly_name: "Гостиная: Компьютер. Игра"
        icon_template: mdi:google-controller
        value_template: >
            {% set activewindow = states("sensor.pc_livingroom_activewindow") %}
            {% set games_kws = states("input_text.pc_livingroom_games_keywords") %}
            {% set content_kws = states("input_text.pc_livingroom_content_keywords") %}
            {% set game = activewindow | string is search(find=games_kws, ignorecase=False) %}
            {% set content = activewindow | string is search(find=content_kws, ignorecase=False) %}
            {% if game == True and content == False %} on
            {% else %} off
            {% endif %}

Обратите внимание, что в шаблоне используется ignorecase=False\True. Зачем это нужно и как оно работает?

ignorecase используется для включения или выключения проверки регистра в словах. Не всегда нам нужно, чтобы поиск по ключевым словам велся на любой регистр в словах, а нужно, чтобы поиск по ключевым словам велся на конкретное слово и с конкретным регистром. Все зависит от ситуации. Ниже приведу примеры

ignorecase=False - не игнорируем сравнение регистра. Поиск будет с соблюдением регистра и если в активном сенсоре будет HALO INFINITE, то слово не будет обнаружено, а если активном сенсоре будет Halo Infinite, то слово будет обнаружено

Halo Infinite|4 Engine|God of War|Forza Horizon

ignorecase=True - игнорируем сравнение регистра. Поиск будет без соблюдения регистра и если в активном сенсоре будет HALO INFINITE\Halo Infinite\HaLO INFINITE, то слово будет обнаружено независимо в каком регистре оно указано в ключевых словах

HaLO INFINITE|4 EnGIne|God OF War|FORZa HoRIzon

Для проверки работы ignorecase можно использовать варианты ниже

Если нам нужно отображать слово вместо True\False

{{ 'HALO Infinite' | regex_findall("Halo Infinite") }}
{{ 'HALO Infinite' | regex_findall("HALO Infinite") }}
{{ 'HALO Infinite' | regex_findall("Halo Infinite", ignorecase=True) }}
{{ 'HALO Infinite' | regex_findall("Halo Infinite", ignorecase=False) }}

Если нам нужно отображать True\False вместо слова

{{ 'HALO Infinite' | string is search("Halo Infinite") }}
{{ 'HALO Infinite' | string is search("HALO Infinite") }}
{{ 'HALO Infinite' | string is search(find="Halo Infinite", ignorecase=True) }}
{{ 'HALO Infinite' | string is search(find="Halo Infinite", ignorecase=False) }}

Буду рад, если вы предложите свой вариант сенсора по работе с ключевыми словами

1 Like

I’ll be honest…I haven’t read your full post but figured I’d share a simpler way that I use for my gamesSensor. I created a custom WMIQuery that lets me know if the game’s process is running.

This is the full query for the games I monitor right now.

Select * from Win32_Process Where Name = ‘bf2042.exe’ OR Name = ‘HorizonZeroDawn.exe’ OR Name = ‘HaloInfinite.exe’ OR Name = ‘Cyberpunk2077.exe’ OR Name = ‘BlackOpsColdWar.exe’ OR Name = ‘ModernWarfare.exe’ OR Name = ‘GoW.exe’ OR Name = ‘reactivedrop.exe’

With this setup, it doesnt matter if the game is in the background…as long as it is running, the sensor will show the relevant process. This is what it looks like if I’m playing CyberPunk.

Works brilliantly for my use case.

2 Likes