Pass value to command line

Is there any way to pass value to command line from a slider? I tried searching but couldn’t find what I’m looking for.

Here is an example. I have a slider and input select:

[code]input_slider:
input_lr_fl_bri:
name: “Brightness”
initial: 0
min: 0
max: 255
step: 1

input_select:
input_lr_fl_ct:
name: “Color Temperature”
options:
- Cool
- Soft
- Warm

group:
Living_Room_FL_Control:
name: “Floor Lamps”
entities:
- input_slider.input_lr_fl_bri
- input_select.input_lr_fl_ct[/code]

And let’s say I have something setup like this:

shell_command: livingroomfloorlamps: ~/shell_scripts/philipshue/group_livingroom '{"on":$1,"ct":$2,"bri":$3,"transitiontime":150}'

I’m controlling a group of lights which simply makes one RESTful API request instead of two. Home Assistant does not expose light groups from my Philips Hue Bridge.

For this task, I would setup 5 automations for two inputs:

[code]automation:

  • alias: “LR FL Off”
    trigger:
    • platform: state
      entity_id: input_slider.input_lr_fl_br
      to: 0
      action:
      … # Execute the shell script to turn off the living room floor lamps.
  • alias: “LR FL On”
    trigger:
    • platform: numeric_state
      entity_id: input_slider.input_lr_fl_br
      above: 0
      action:
      … # Execute the shell script to set the desired brightness.

      Pass in the color temperature if the lights’ previous state is “off”

      and now it’s “on.”

  • alias: “LR FL CT Cool” # “Color Temperature”
    trigger:
    • platform: state
      entity_id: input_select.input_lr_fl_ct
      state: “Cool”
      condition:
      platform: numeric_state
      entity_id: input_slider.input_lr_fl_bri
      above: 0
      action:
      … # Execute the shell script and pass in the “ct” value of “154.”
  • alias: “LR FL CT Soft” # “Color Temperature”
    trigger:
    • platform: state
      entity_id: input_select.input_lr_fl_ct
      state: “Soft”
      condition:
      platform: numeric_state
      entity_id: input_slider.input_lr_fl_bri
      above: 0
      action:
      … # Execute the shell script and pass in the “ct” value of “369.”
  • alias: “LR FL CT Warm” # “Color Temperature”
    trigger:
    • platform: state
      entity_id: input_select.input_lr_fl_ct
      state: “Warm”
      condition:
      platform: numeric_state
      entity_id: input_slider.input_lr_fl_bri
      above: 0
      action:
      … # Execute the shell script and pass in the “ct” value of “500.”[/code]

What can I do to accomplish my task? If only Home Assistant could show me the groups from my Philips Hue bridge.

Okay. Due to the implementation of shell_command, I can’t think of any possibility of passing parameters to a command_shell service.

So, I’ve came up with a solution.

Let’s start with ~/shell_scripts/setlightgroup:

#!/bin/bash HA_PHUE_HOST="philipshue1" HA_PHUECONF=~/.homeassistant/phue.conf HA_PHUEAPIKEY=$(cat $HA_PHUECONF | awk '{print $3}' | sed -e 's/\"//g' -e 's/}//g'); num='^[0-9]+$' if ! [[ $1 =~ $num ]]; then echo "Not a number." &>2 exit 1 fi if [ -z "$2" ]; then echo "Please enter Entity ID for brightness." &>2 exit 1 fi if [ -z "$3" ]; then echo "Please enter Entity ID for color temperature." &>2 exit 1 fi if ! [[ $4 =~ $num ]]; then echo "Not a number." &>2 exit 1 fi LIGHT_BRI=$(curl -X GET http://localhost:8123/api/states/$2 2> /dev/null | \ tail -n2 | head -n1 | awk '{print $2}' | sed -e 's/"//g' ) LIGHT_CT=$(curl -X GET http://localhost:8123/api/states/$3 2> /dev/null | \ tail -n2 | head -n1 | awk '{print $2}' | sed -e 's/"//g' ) if [ $LIGHT_BRI -gt 0 ]; then CT_Mireds=154 if [ $LIGHT_CT == "Cool" ]; then CT_Mireds=154 elif [ $LIGHT_CT == "Soft" ]; then CT_Mireds=369 elif [ $LIGHT_CT == "Warm" ]; then CT_Mireds=500 fi curl -X PUT -H "Content-Type: application/json" \ -d '{"on":true,"bri":'$LIGHT_BRI',"ct":'$CT_Mireds',"transitiontime":'$4'}' \ http://$HA_PHUE_HOST/api/$HA_PHUEAPIKEY/groups/$1/action 2> /dev/null else curl -X PUT -H "Content-Type: application/json" \ -d '{"on":false,"transitiontime":'$4'}' \ http://$HA_PHUE_HOST/api/$HA_PHUEAPIKEY/groups/$1/action 2> /dev/null fi exit 0

First, the script checks for parameters to make sure they are in check. Second, it gathers the state of the input elements that were set from the frontend. Third, it checks to see if the brightness is greater than 0 and checks what color temperature is set to, be it cool, soft white, or warm white. If the brightness is set to 0, the light turns off. That’s the end of the shell script.

Now to configuration.yaml:

I like to hide my two living room floor lamps. I’ll show you the code:

customize: light.living_room_left: hidden: true light.living_room_right: hidden: true

Next is shell_command:

shell_command: group_lr_fl: ~/shell_scripts/setlightgroup 1 input_slider.input_lr_fl_bri input_select.input_lr_fl_ct 10

This script gets executed by the two input elements, so it’s time to show the two inputs:

[code]input_slider:
input_lr_fl_bri:
name: “Brightness”
initial: 0
min: 0
max: 255
step: 1

input_select:
input_lr_fl_ct:
name: “Color Temperature”
options:
- Cool
- Soft
- Warm[/code]

The inputs are explanatory, so now here’s the last part:

[code]automation:

  • alias: “LR FL Dimmer”
    trigger:
    platform: state
    entity_id: input_slider.input_lr_fl_bri
    action:
    service: shell_command.group_lr_fl
  • alias: “LR FL Color Temperature”
    trigger:
    platform: state
    entity_id: input_select.input_lr_fl_ct
    action:
    service: shell_command.group_lr_fl[/code]

Notice how I left out the parameters for an internal state? It’s simply a “catch-all” state.

Put them all together and now you have the ability to change the brightness and pre-set color temperature.

However, that part is not over yet, so I do have one last question: Is there any way to set initial values that are dependent on group’s brightness and color temperature? A way to execute a shell_command during startup of Home Assistant?

Hey there,

I was also wanting to pass arguments/parameters to a shell command. I created a new component called ‘templated_shell_command’. It is basically a copy-paste of the normal ‘shell_command’ but instead of just running the command, it passes it through the template engine first and then runs the output of that. So, you can save the following as templated_shell_command.py in your custom_components directory:

import logging
import subprocess

import voluptuous as vol

import homeassistant.helpers.config_validation as cv
from homeassistant.helpers import template
from homeassistant.exceptions import TemplateError

DOMAIN = 'templated_shell_command'

_LOGGER = logging.getLogger(__name__)

CONFIG_SCHEMA = vol.Schema({
    DOMAIN: vol.Schema({
        cv.slug: cv.string,
    }),
}, extra=vol.ALLOW_EXTRA)

SHELL_COMMAND_SCHEMA = vol.Schema({})


def setup(hass, config):
    """Setup the shell_command component."""
    conf = config.get(DOMAIN, {})

    def service_handler(call):
        """Execute a shell command service."""
        try:
            cmd = template.render(hass, conf[call.service])
            subprocess.call(cmd, shell=True,
                            stdout=subprocess.DEVNULL,
                            stderr=subprocess.DEVNULL)
        except TemplateError as ex:
            if ex.args and ex.args[0].startswith("UndefinedError: 'None' has no attribute"):
                # Common during HA startup - so just a warning
                _LOGGER.warning(ex)
                return
            _LOGGER.error(ex)
        except subprocess.SubprocessError:
            _LOGGER.exception('Error running command')

    for name in conf.keys():
        hass.services.register(DOMAIN, name, service_handler,
                               schema=SHELL_COMMAND_SCHEMA)
    return True

Then, to use it, add to your config:

templated_shell_command:
  test_cmd: 'echo "{{ states.sun.sun.attributes.elevation }}" >> /tmp/templated_shell_command_test &'

and call it just as you would a normal shell command:

  service: templated_shell_command.test_cmd

As an example of how I use it, here’s how I have a input_select to pick the pan-tilt preset for my foscam that gets acted on once I change it in the web interface:

templated_shell_command:
  camera_office_preset: 'foscam_preset {{ states.input_select.camera_office_preset.state }} &'

input_select:
  camera_office_preset:
    name: 'Office camera preset'
    options:
      - 'off'
      - 'left'
      - 'right'
    initial: 'off'

automation:
  alias: "Change office camera preset"
  trigger:
    - platform: state
      entity_id: input_select.camera_office_preset
  action:
    service: templated_shell_command.camera_office_preset
7 Likes

Very nice templated solution. Any interest in modifying the shell_command component to be template-compatible? I think you could put the template rendering code around the regular command and issue a PR to see what Paulus thinks and get it through. If you don’t have time or interest, I can do it. I really want this capability too.

I just added your mods to shell_command and it works beautifully. Old shell commands (that have no templated info in them) still work fine too. Now I can set my AC to any temperature using an input slider and IR commands. Epic.

Yeah, I thought about just modifying the shell_command and submit a PR, but just didn’t get around to it yet because of the additional stuff required, such as a test and documentation. Will try to do it soon.

Let me know if you need help with those steps. I’m all gung-ho about the capability and just blogged and posted a video using it.

Isn’t it funny how our wives push us to go that extra step in getting it off phones and on to other terminals (tablets, remotes, etc) for them to use?

What do you mean?

@dennisaion, haha yes, totally. My wife doesn’t want to pull out her phone and press a few buttons to get the lights to go on or off. she wants one tiny action. The IR remote works well in a one-bedroom apt.

1 Like

@partofthething Mine asked for physical switches (also single action) around the house. And so the Wall Mounted Touchscreen project ( Wall mounted touchscreen ) was born. :laughing:

@hordur I couldn’t wait. I’m sorry. The template capability is now live in 0.22.

1 Like

This is awesome! I couldn’t find the explanation of the write up. Is there a simple example of how you set brightness or color of lights? I’m not familiar with the oncmd used in the link. Thanks!

1 Like

I’m trying too use a template in a sheel command. I´m using a input slider to pass the value.

Here is my setup:

input_slider:
 tv_volume:
    name: TV Volume
    initial: 8
    min: 1
    max: 20
    step: 1

shell_command:
 lg_volume_9: sudo echo ke 01 9 > /dev/ttyUSB0
 set_volume_tv: 'sudo echo kf 01 {{ states.sensor.input_slider.volume_tv | int }} > /dev/ttyUSB0'

When I run the lg_volume_9 works very well, but when I run set_volume_tv doesn´t work.

I try also transform the input slider as a sensor and doesn´t work.

What is the solution for me?

Thank´s

try:

set_volume_tv: 'sudo echo kf 01 {{ states.input_slider.volume_tv.state | int }} > /dev/ttyUSB0'

Thanks for the help.

But don’t work.

I m trying other away. My Lg tv have netcast, i will try use the input slider to change te volume.

Sorry,
I’ve got mines working without quotes:
set_volume_tv: sudo echo kf 01 {{ states.input_slider.volume_tv.state | int }} > /dev/ttyUSB0

Is it possible to use shell_command with data_template or some way to pass the entity_id as a variable to the shell command?

I’m trying to use one shell command for many things and I want to reference the calling entity name in the shell command.

This currently works but doesn’t allow much flexibility because the light name is specified.

shell_command:
  light_dim: ''/usr/local/bin/light_dim.sh {{ states.input_slider.light_office_ceiling.state | int }}'

Obviously this doesn’t work but something like:

shell_command:
  light_dim: '/usr/local/bin/light_dim.sh {{ states.input_slider.{{ state.entity_id }}.name }}'

That way I don’t have to have a shell command for each light.

In your shell_command, just use:

shell_command:
  light_dim: '/usr/local/bin/light_dim.sh {{ value }}'

Then, in your automation,

  action: 
    - service: shell_command.light_dom
      data_template:
        value: >
          {% template logic to determine value to send %}

“value” is passed as an argument to the shell_command.

5 Likes
  1. How did someone like your post before me??
  2. THANKS! I thought the parameters for data_template had to be available in the component.