We control the brightness of the computer monitor screen

We control the brightness of the computer monitor screen using IOTLink. Not all computer monitors have a light sensor and automatic brightness adjustment, but this is possible if the monitor supports brightness adjustment programmatically. If your monitor has DDC/CI support, then you can change the brightness of the monitor screen. All this is done in Windows OS. You can automate the brightness of the screen for different situations. For example, on a sunny day, the brightness of the screen can be increased to a comfortable level by an external light sensor. If it is dark, then the brightness of the screen can be reduced. We launched the game, before the game was launched, the screen brightness was 20%, and the game will be 50-60%. Turned off the game and started surfing the Internet or working, then the screen brightness will be 20-30%. We decided to watch a movie, the screen brightness is 40%.

I would be grateful if you have your own version of controlling the brightness of the monitor screen and you share it or post examples of how you can do better. Thanks.

We put the Monitoring program on Windows, which adjusts the brightness of the screen and use the slider to check whether the screen brightness adjustment works, if so, then continue on

Run the CMD console and enter the command, where /set 10 is the brightness level from 0 to 100

%LOCALAPPDATA%\Microsoft\WindowsApps\Monitorian.exe /set 10 - brightness level 10%
%LOCALAPPDATA%\Microsoft\WindowsApps\Monitorian.exe /set 20 - brightness level 20%
%LOCALAPPDATA%\Microsoft\WindowsApps\Monitorian.exe /set 40 - brightness level 40%
%LOCALAPPDATA%\Microsoft\WindowsApps\Monitorian.exe /set 80 - brightness level 80%
%LOCALAPPDATA%\Microsoft\WindowsApps\Monitorian.exe /set 100 - brightness level 100%

If everything works fine, go ahead

We put the IOTLink program on Windows and read documentation on launching the program via IOTLink

Next, through the service, we check the screen brightness change and it should work. While we are specifying a specific number for brightness, then we will use a variable, the main thing is that it works for you.

service: mqtt.publish
data:
  topic: iotlink/workgroup/livingroom/commands/run
  payload: >-
    { "command": "C:\\Windows\\System32\\cmd.exe", "args":"/k
    %LOCALAPPDATA%\\Microsoft\\WindowsApps\\Monitorian.exe /set 40", 
    "path": "C:\\Windows\\System32","user": "", "visible": false, "fallback":
    true }

Now that we have the screen brightness adjustment working, we need to add lighting to the template, through which we will control the brightness of the monitor screen. You can read more about Template Light here

Create 3 objects:

  1. switch mqtt - read more here
  2. input_number - read more here
  3. light - we use Template Light
  1. Let’s create a switch. You can create any switch, but I use switch mqtt
switch:
  - platform: mqtt
    unique_id: switch livingroom monitor brightness
    object_id: livingroom monitor brightness
    name: "Living room: Monitor. Screen Brightness"
    command_topic: "hass/switch/livingroom/monitor_brightness"
    state_topic: "hass/switch/livingroom/monitor_brightness"
    retain: true
    qos: 0
    icon: mdi:monitor
  1. Let’s create an auxiliary element number, which we will use mqtt.publish to adjust the brightness of the screen
input_number:
    pc_livingroom_monitor_brightness:
      name: "Living room: Monitor. Screen Brightness"
      min: 0
      max: 100
      step: 1
      mode: box
      icon: mdi:monitor
  1. We create a template for adjusting the brightness of the screen, where we will insert a switch and an auxiliary element. Note that I specified value: “{{ (brightness)|int / 2.55 }}”. This is done specifically for the reason that the screen brightness is from 0 to 100, and brightness is from 0 to 255, so I had to divide 255/2.55=100, which corresponds to the brightness level of the screen
light:
  - platform: template
    lights:
      livingroom_monitor_brightness:
        friendly_name: "Living room: Monitor. Screen Brightness"
        value_template: '{{ is_state("switch.livingroom_monitor_brightness", "on") }}'
        level_template: '{{states("input_number.pc_livingroom_monitor_brightness")|round(0)|int * 2.55}}'
        turn_on:
          service: switch.turn_on
          target:
            entity_id: switch.livingroom_monitor_brightness
        turn_off:
          service: switch.turn_off
          target:
            entity_id: switch.livingroom_monitor_brightness
        set_level:
          service: input_number.set_value
          data:
            value: "{{ (brightness)|int / 2.55 }}"
          target:
            entity_id: input_number.pc_livingroom_monitor_brightness

  1. We check for errors and if everything is OK, restart the Home Assistant

  2. Creating automation to adjust the brightness of the screen

alias: 'Living room: Monitor. Brightness adjustment'
description: Adjust the brightness of the monitor
trigger:
  - platform: state
    entity_id:
      - input_number.pc_livingroom_monitor_brightness
condition: []
action:
  - service: mqtt.publish
    data:
      topic: iotlink/workgroup/livingroom/commands/run
      payload: >-
        { "command": "C:\\Windows\\System32\\cmd.exe", "args":"/k
        %LOCALAPPDATA%\\Microsoft\\WindowsApps\\Monitorian.exe /set 
        {{states("input_number.pc_livingroom_monitor_brightness")|round(0)}}", 
        "path": "C:\\Windows\\System32","user": "", "visible": false,
        "fallback": true }
mode: single

  1. We display the lighting card and adjust the brightness of the screen

image

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

Управляем яркостью экрана компьютерного монитора с помощью IOTLink. Не все компьютерные мониторы имеют датчик света и автоматическую регулировку яркости, но такая возможность есть, если монитор поддерживает регулировку яркости программно. Если ваш монитор имеет поддержку DDC/CI, тогда вы сможете менять яркость экрана монитора. Все это делается в ОС Windows. Можно автоматизировать яркость экрана под различные ситуации. Например, солнечный день, по внешнему датчику света яркость экрана можно увеличить до комфортного вам уровня. Если темно, то яркость экрана можно снизить. Запустили игру, до запуска игры яркость экрана была 20%, а в игре будет 50-60%. Выключили игру и начали серфить в интернете или работать, то яркость экрана будет 20-30%. Решили посмотреть кино, яркость экрана 40%.

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

Ставим на Windows программу Monitorian, которая регулирует яркость экрана и ползунком проверяем, работает ли регулировка яркости экрана, если да, то продолжаем дальше

Запускаем консоль CMD и вводим команду, где /set 10 это уровень яркости от 0 до 100

%LOCALAPPDATA%\Microsoft\WindowsApps\Monitorian.exe /set 10 - уровень яркости 10%
%LOCALAPPDATA%\Microsoft\WindowsApps\Monitorian.exe /set 20 - уровень яркости 20%
%LOCALAPPDATA%\Microsoft\WindowsApps\Monitorian.exe /set 40 - уровень яркости 40%
%LOCALAPPDATA%\Microsoft\WindowsApps\Monitorian.exe /set 80 - уровень яркости 80%
%LOCALAPPDATA%\Microsoft\WindowsApps\Monitorian.exe /set 100 - уровень яркости 100%

Если все работает, отлично, идем дальше

Ставим на Windows программу IOTLink и читаем документацию по запуске программы через IOTLink

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

service: mqtt.publish
data:
  topic: iotlink/workgroup/livingroom/commands/run
  payload: >-
    { "command": "C:\\Windows\\System32\\cmd.exe", "args":"/k
    %LOCALAPPDATA%\\Microsoft\\WindowsApps\\Monitorian.exe /set 40", 
    "path": "C:\\Windows\\System32","user": "", "visible": false, "fallback":
    true }

Теперь, когда у нас работает регулировка яркости экрана, нам нужно, это дело добавить в шаблон освещение, через который мы будем управлять яркостью экрана монитора. Более подробнее про Template Light можно прочитать здесь

Создадим 3 объекта:

  1. switch mqtt - подробнее читаем здесь
  2. input_number - подробнее читаем здесь
  3. light - используем Template Light
  1. Создадим выключатель. Выключатель можно создать любой, но я использую switch mqtt
switch:
  - platform: mqtt
    unique_id: switch livingroom monitor brightness
    object_id: livingroom monitor brightness
    name: "Гостиная: Монитор. Яркость экрана"
    command_topic: "hass/switch/livingroom/monitor_brightness"
    state_topic: "hass/switch/livingroom/monitor_brightness"
    retain: true
    qos: 0
    icon: mdi:monitor
  1. Создадим вспомогательный элемент число, который будем использовать mqtt.publish для регулировки яркости экрана
input_number:
    pc_livingroom_monitor_brightness:
      name: "Гостиная: Монитор. Яркость экрана"
      min: 0
      max: 100
      step: 1
      mode: box
      icon: mdi:monitor
  1. Создаем шаблон для регулировки яркости экрана, куда мы вставим выключатель и вспомогательный элемент число. Note that I specified value: “{{ (brightness)|int / 2.55 }}”. This is done specifically for the reason that the screen brightness is from 0 to 100, and brightness is from 0 to 255, so I had to divide 255/2.55=100, which corresponds to the brightness level of the screen
light:
  - platform: template
    lights:
      livingroom_monitor_brightness:
        friendly_name: "Гостиная: Монитор. Яркость экрана"
        value_template: '{{ is_state("switch.livingroom_monitor_brightness", "on") }}'
        level_template: '{{states("input_number.pc_livingroom_monitor_brightness")|round(0)|int * 2.55}}'
        turn_on:
          service: switch.turn_on
          target:
            entity_id: switch.livingroom_monitor_brightness
        turn_off:
          service: switch.turn_off
          target:
            entity_id: switch.livingroom_monitor_brightness
        set_level:
          service: input_number.set_value
          data:
            value: "{{ (brightness)|int / 2.55 }}"
          target:
            entity_id: input_number.pc_livingroom_monitor_brightness

  1. Проверяем на наличие ошибок и если все ок, перезапускаем Home Assistant

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

alias: 'Гостиная: Монитор. Регулировка яркости'
description: Регулируем яркость монитора
trigger:
  - platform: state
    entity_id:
      - input_number.pc_livingroom_monitor_brightness
condition: []
action:
  - service: mqtt.publish
    data:
      topic: iotlink/workgroup/livingroom/commands/run
      payload: >-
        { "command": "C:\\Windows\\System32\\cmd.exe", "args":"/k
        %LOCALAPPDATA%\\Microsoft\\WindowsApps\\Monitorian.exe /set 
        {{states("input_number.pc_livingroom_monitor_brightness")|round(0)}}", 
        "path": "C:\\Windows\\System32","user": "", "visible": false,
        "fallback": true }
mode: single

  1. Выводим карточку освещение и регулируем яркость экрана

image

5 Likes

This is neat. I had been wondering if this was possible. I’ll have to give it a go. Thanks!

In the continuation of the topic on automatic brightness adjustment of the monitor screen. I am using Hass Agent integration to determine which program is running and scattered the processes into categories: game, video player. browser, content and general, as well as tied to the light sensor and divided into dark and light. This will allow you to set the desired screen brightness to suit your needs. For example, we have a light in the room turned on by a light sensor and we have our own threshold when the light level of the light sensor becomes below the specified threshold. This is the threshold I use to determine whether it is light or dark. Moreover, the brightness values in the auxiliary element are recorded automatically if we change the brightness of the screen both manually and through the voice assistant. This will save us from manually entering numbers to adjust the brightness.

For clarity, this is how my card looks with settings for automatically adjusting the brightness of the monitor screen

Watch the video

How to do it?

  1. Installing the Hass Agent integration

  2. Creating a sensor an active window and a command


  3. Let’s create any switch as a blocker that will be used in automation conditions and if the switch is ON, then auto brightness will work, if OFF, then auto brightness will not work. Also, the sensor will participate in the condition that the computer is turned on.

  4. Creating an auxiliary text input element. We need it to enter keywords and it 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
  1. We are creating an auxiliary element number for entering values that will be used to adjust the brightness of the monitor screen. I have several of them and are divided by light level light and dark. We create several elements for different categories: game, video player, browser, general. Below I have given examples only for light and dark and one category, then you create the same for other categories
input_number
  pc_livingroom_monitor_brightness_game_light:
    name: "Living room: Monitor. Brightness. Game. Light"
    min: 0
    max: 100
    step: 1
    mode: box
    icon: mdi:monitor

  pc_livingroom_monitor_brightness_game_dark:
    name: "Living room: Monitor. Brightness. Game. Dark"
    min: 0
    max: 100
    step: 1
    mode: box
    icon: mdi:monitor

  1. 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:
  - 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, ignorecase=False) %} on
            {% else %} off
            {% endif %}

  - 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, ignorecase=False) %} on
            {% else %} off
            {% endif %}

  - 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, ignorecase=False) %} on
            {% else %} off
            {% endif %}

  1. Let’s create a lighting object, to adjust the brightness of the monitor screen using MQTT Light
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

  1. Creating automation. For example, I will give automation for adjusting the brightness of the screen for games. The same is done for both the browser and the general. This automation reads the values from the auxiliary number elements to adjust the brightness of the screen, and also makes changes to these elements.
alias: 'Living room: Monitor. Auto brightness of the screen. Games'
description: >-
  Automatic brightness adjustment of the monitor screen. When launching the application
  brightness is set according to the set brightness settings for light
  and dark time of day. and when the application is closed, the brightness will be
  restored from history. Automatic level adjustment is also configured.
  brightness for the running application
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
  - platform: state
    entity_id:
      - light.pc_livingroom_monitor_brightness
    id: Screen. Screen Brightness
    attribute: brightness
condition:
  - condition: template
    value_template: '{{ is_state("switch.pc_livingroom", "on") }}'
  - condition: template
    value_template: '{{ is_state("switch.livingroom_monitor_auto_brightness", "on") }}'
action:
  - choose:
      - conditions:
          - condition: trigger
            id: The game is running
        sequence:
          - choose:
              - conditions:
                  - condition: template
                    value_template: >-
                      {{
                      states("sensor.gostinaia_datchik_sveta_potolochnaia_liustra_illuminance_lux")|float(default=10) 

                      <
                      states("input_number.lights_in_the_livingroom_low_lux")|round(0)
                      }}
                sequence:
                  - service: scene.create
                    data:
                      snapshot_entities:
                        - light.pc_livingroom_monitor_brightness
                      scene_id: pc_livingroom_monitor_brightness_game_history
                  - delay:
                      hours: 0
                      minutes: 0
                      seconds: 5
                      milliseconds: 0
                  - service: light.turn_on
                    data:
                      brightness_pct: >-
                        {{
                        states("input_number.pc_livingroom_monitor_brightness_game_dark")|round(0)
                        }}
                    target:
                      entity_id: light.pc_livingroom_monitor_brightness
              - conditions:
                  - condition: template
                    value_template: >-
                      {{
                      states("sensor.gostinaia_datchik_sveta_potolochnaia_liustra_illuminance_lux")|float(default=10) 

                      >
                      states("input_number.lights_in_the_livingroom_low_lux")|round(0)
                      }}
                sequence:
                  - service: scene.create
                    data:
                      snapshot_entities:
                        - light.pc_livingroom_monitor_brightness
                      scene_id: pc_livingroom_monitor_brightness_game_history
                  - delay:
                      hours: 0
                      minutes: 0
                      seconds: 5
                      milliseconds: 0
                  - service: light.turn_on
                    data:
                      brightness_pct: >-
                        {{
                        states("input_number.pc_livingroom_monitor_brightness_game_light")|round(0)
                        }}
                    target:
                      entity_id: light.pc_livingroom_monitor_brightness
            default: []
      - conditions:
          - condition: trigger
            id: The game is off
        sequence:
          - service: scene.turn_on
            target:
              entity_id: scene.pc_livingroom_monitor_brightness_game_history
            metadata: {}
      - conditions:
          - condition: trigger
            id: Screen. Screen Brightness
          - condition: template
            value_template: '{{ is_state("sensor.hassagent_pc_livingroom_running_game","on") }}'
        sequence:
          - choose:
              - conditions:
                  - condition: template
                    value_template: >-
                      {{
                      states("sensor.gostinaia_datchik_sveta_potolochnaia_liustra_illuminance_lux")|float(default=10) 

                      <
                      states("input_number.lights_in_the_livingroom_low_lux")|round(0)
                      }}
                sequence:
                  - service: input_number.set_value
                    data:
                      value: >-
                        {{ state_attr("light.pc_livingroom_monitor_brightness",
                        "brightness")|multiply(0.392)|round(0) }}
                    target:
                      entity_id: input_number.pc_livingroom_monitor_brightness_game_dark
              - conditions:
                  - condition: template
                    value_template: >-
                      {{
                      states("sensor.gostinaia_datchik_sveta_potolochnaia_liustra_illuminance_lux")|float(default=10) 

                      >
                      states("input_number.lights_in_the_livingroom_low_lux")|round(0)
                      }}
                sequence:
                  - service: input_number.set_value
                    data:
                      value: >-
                        {{ state_attr("light.pc_livingroom_monitor_brightness",
                        "brightness")|multiply(0.392)|round(0) }}
                    target:
                      entity_id: input_number.pc_livingroom_monitor_brightness_game_light
            default: []
    default: []
mode: single
Текст на русском(Text in Russian)

В продолжении темы по автоматической регулировки яркости экрана монитора. Я использую интеграцию Hass Agent для определения, какая программа запущена и разбросал процессы по категориям: игра, видеоплеер. браузер, контент и общее, а также привязал к датчику света и разделил на темно и светло. Это позволит выставить нужную яркость экрана под свои нужды. Например у нас свет в комнате включается по датчику света и у нас есть свой порог, когда уровень света у датчика света станет ниже указанного порога. Вот этот порог я и использую для определения светло или темно. Причем значения яркости во вспомогательный элемент число записывается автоматически, если мы изменим яркость экрана как вручную, так и через голосовой помощник. Это избавит нас вручную вносить числа для регулировки яркости.

Для наглядности так выглядит моя карточка с настройками для автоматической регулировки яркости экрана монитора

Смотрим видео
https://youtu.be/81Nr9BlzLvk

Как это сделать?

  1. Ставим интеграцию Hass Agent

  2. Создаем сенсор активное окно и команду


  3. Создадим любой выключатель в качестве блокировщика, который будет использоваться в условиях автоматизации и если выключатель будет ON, то автояркость будет работать, если OFF, то автояркость работать не будет. Также в условии будет участвовать сенсор, что компьютер включен.

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

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
  1. Создаем вспомогательный элемент число для внесения значении, которые будут использоваться для регулировки яркости экрана монитора. У меня их несколько и разделены по уровню света светло и темно. Создаем несколько элементов для разных категории: игра, видеоплеер, браузер, общее. Ниже я привел примеры только для светло и темно и одну категорию, дальше создаете аналогично и для других категории
input_number
  pc_livingroom_monitor_brightness_game_light:
    name: "Гостиная: Монитор. Яркость. Игра. Светло"
    min: 0
    max: 100
    step: 1
    mode: box
    icon: mdi:monitor


  pc_livingroom_monitor_brightness_game_dark:
    name: "Гостиная: Монитор. Яркость. Игра. Темно"
    min: 0
    max: 100
    step: 1
    mode: box
    icon: mdi:monitor

  1. Создадим сенсор, который будет сверять ключевые слова с сенсором активного окна и раскидывать по категориям игра, кино, браузер и т.д
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, ignorecase=False) %} 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, ignorecase=False) %} 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, ignorecase=False) %} on
            {% else %} off
            {% endif %}

  1. Создадим объект освещение, для регулировки яркости экрана монитора используя MQTT Light
mqtt:
  light:
    - name: "Гостиная: Монитор. Яркость экрана"
      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

  1. Создаем автоматизацию. Для примера приведу автоматизацию для регулировки яркости экрана для игр. Аналогично делается и для браузера и для общее. Эта автоматизация считывает значения из вспомогательных элементов число для регулировки яркости экрана, а также вносит изменения в эти элементы.
alias: 'Гостиная: Монитор. Автояркость экрана. Игры'
description: >-
  Автоматическая регулировка яркости экрана монитора. При запуске приложения
  выставляется яркость согласно выставленным настройкам для яркости для светлого
  и темного времени суток. а когда приложение будет закрыто, то яркость будет
  восстановлена из истории. Также настроена автоматическая корректировка уровня
  яркости для запущенного приложения
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: Игра выключена
  - platform: state
    entity_id:
      - light.pc_livingroom_monitor_brightness
    id: Монитор. Яркость экрана
    attribute: brightness
condition:
  - condition: template
    value_template: '{{ is_state("switch.pc_livingroom", "on") }}'
  - condition: template
    value_template: '{{ is_state("switch.livingroom_monitor_auto_brightness", "on") }}'
action:
  - choose:
      - conditions:
          - condition: trigger
            id: Игра запущена
        sequence:
          - choose:
              - conditions:
                  - condition: template
                    value_template: >-
                      {{
                      states("sensor.gostinaia_datchik_sveta_potolochnaia_liustra_illuminance_lux")|float(default=10) 

                      <
                      states("input_number.lights_in_the_livingroom_low_lux")|round(0)
                      }}
                sequence:
                  - service: scene.create
                    data:
                      snapshot_entities:
                        - light.pc_livingroom_monitor_brightness
                      scene_id: pc_livingroom_monitor_brightness_game_history
                  - delay:
                      hours: 0
                      minutes: 0
                      seconds: 5
                      milliseconds: 0
                  - service: light.turn_on
                    data:
                      brightness_pct: >-
                        {{
                        states("input_number.pc_livingroom_monitor_brightness_game_dark")|round(0)
                        }}
                    target:
                      entity_id: light.pc_livingroom_monitor_brightness
              - conditions:
                  - condition: template
                    value_template: >-
                      {{
                      states("sensor.gostinaia_datchik_sveta_potolochnaia_liustra_illuminance_lux")|float(default=10) 

                      >
                      states("input_number.lights_in_the_livingroom_low_lux")|round(0)
                      }}
                sequence:
                  - service: scene.create
                    data:
                      snapshot_entities:
                        - light.pc_livingroom_monitor_brightness
                      scene_id: pc_livingroom_monitor_brightness_game_history
                  - delay:
                      hours: 0
                      minutes: 0
                      seconds: 5
                      milliseconds: 0
                  - service: light.turn_on
                    data:
                      brightness_pct: >-
                        {{
                        states("input_number.pc_livingroom_monitor_brightness_game_light")|round(0)
                        }}
                    target:
                      entity_id: light.pc_livingroom_monitor_brightness
            default: []
      - conditions:
          - condition: trigger
            id: Игра выключена
        sequence:
          - service: scene.turn_on
            target:
              entity_id: scene.pc_livingroom_monitor_brightness_game_history
            metadata: {}
      - conditions:
          - condition: trigger
            id: Монитор. Яркость экрана
          - condition: template
            value_template: '{{ is_state("sensor.hassagent_pc_livingroom_running_game","on") }}'
        sequence:
          - choose:
              - conditions:
                  - condition: template
                    value_template: >-
                      {{
                      states("sensor.gostinaia_datchik_sveta_potolochnaia_liustra_illuminance_lux")|float(default=10) 

                      <
                      states("input_number.lights_in_the_livingroom_low_lux")|round(0)
                      }}
                sequence:
                  - service: input_number.set_value
                    data:
                      value: >-
                        {{ state_attr("light.pc_livingroom_monitor_brightness",
                        "brightness")|multiply(0.392)|round(0) }}
                    target:
                      entity_id: input_number.pc_livingroom_monitor_brightness_game_dark
              - conditions:
                  - condition: template
                    value_template: >-
                      {{
                      states("sensor.gostinaia_datchik_sveta_potolochnaia_liustra_illuminance_lux")|float(default=10) 

                      >
                      states("input_number.lights_in_the_livingroom_low_lux")|round(0)
                      }}
                sequence:
                  - service: input_number.set_value
                    data:
                      value: >-
                        {{ state_attr("light.pc_livingroom_monitor_brightness",
                        "brightness")|multiply(0.392)|round(0) }}
                    target:
                      entity_id: input_number.pc_livingroom_monitor_brightness_game_light
            default: []
    default: []
mode: single
3 Likes

That’s very impressive, thank you so much for sharing!
Do you know if there is a command in case you are using two or more monitors to define /set 20 to that specific monitor? It seems it always default to monitor 1

You can find out more about the teams here. You can create one entity to adjust the brightness of all monitors, or create separate 3 light entities for three monitors and then combine the light into a group, so you can adjust the brightness of the monitor individually or simultaneously

Command-line options

You can use command-line options to get/set the brightness or contrast.

Actions Options
Get brightness of a monitor. /get
Get brightness of a specified monitor. /get [Device Instance ID]
Get brightness of all monitors. /get all
Set brightness of a monitor. /set [Brightness]
Set brightness of a specified monitor. /set [Device Instance ID] [Brightness]
Set brightness of all monitors. /set all [Brightness]

The device instance ID is an unique identifier given by the OS to each monitor. It must be enclosed in quotes.

You can switch to contrast by inserting contrast after /get or /set (e.g. /get contrast all).

If this app is called with /get or /set, it will return

[Device Instance ID] [Monitor name] [Brightness] B

B’ at the end indicates brightness. In addition, ‘*’ will be added in the case of a selected monitor.

If this app is called with /get contrast or /set contrast, it will return

[Device Instance ID] [Monitor name] [Contrast] C

‘C’ at the end indicates contrast. If contrast is not supported by a monitor, ‘-’ will be shown instead.

The brightness or contrast ranges from 0 to 100%. When you use /set option, it can be specified with the number itself (e.g. 20), increase (e.g. +10) or decrease (e.g. -10).

The options can be executed consecutively (e.g. monitorian /set 20 /set contrast 40).

1 Like

Thank you so much! That worked, the only change I had to make to the code was single quotation on the payload for MQQT so the double quotation required by monitorian would work:

service: mqtt.publish
data:
  topic: iotlink/workgroup/pc-name/commands/run
  payload: >-
    { "command": "C:\\Windows\\System32\\cmd.exe", "args":'/k
    %LOCALAPPDATA%\\Microsoft\\WindowsApps\\Monitorian.exe /set
    "DISPLAY\\DELA0D1\\5&1ee2d73e&1&UID4355\"
    {{states("input_number.pc_dell_monitor_brightness")|round(0)}}',  "path":
    "C:\\Windows\\System32","user": "", "visible": false, "fallback": true }
  qos: 0
  retain: false

and the switch platform is moving into mqtt so I did instead:

mqtt:
  switch:
    - unique_id: switch.dell_monitor_brightness
      object_id: dell_monitor_brightness
......

Great tutorial!! Cheers :grin:

and will it work this way if we specify the monitor name at the end after /set?

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

I wish it did as it took me hours to figure it out :joy: but their documentation mentions:

The device instance ID is an unique identifier given by the OS to each monitor. It must be enclosed in quotes.

If we head to the CMD and hit /get all it shows the ID which in my case is this weird string:

"DISPLAY\\DELA0D1\\5&1ee2d73e&1&UID4355\"

I tried using all verions of just DELA0D1 or just 5&1ee2d73e&1&UID4355 but it only works with the string above.

I think it’s better for you to ask the author of this project himself to show a clear example