Ability to save a scene (Real-time)

I think scenes are not hassios current strong point. I really wish they could be evolved a little more. I was thinking it would be great if you could set all the lights how are you want them then save that as a scene. This would include turning on lights, setting light damn levels, setting colors of lights. If you could export the current state of how your lights are set to a scene that would be awesome.

Seems like you have everything you need to be able to do this.

There’s an external tool that can pretty much do this (with some limitations though): SceneGen

I’ll check it out. Thanks. Wish it was built in. With this work with hassio on a pi?

I have never used it myself, so I can’t make any statements about that. Just wanted to share what I have read here a while ago. :angel:

I’m gonna try it out now. Thanks!

It does not work with hassio. So the request still stands.

Wish to have that too.
Maybe the God of HASSIO addon has time for it … @frenck

PS beeer/coffe donation would help

Not sure if that thing still works, it hasn’t been updated in the past 2 years…

Nevertheless, I don’t think this is add-on material. You can, however, install and use this using the “SSH & Web Terminal” community add-on.

Thanks. I did get it to work with adding the “SSH & Web Terminal”, thanks for that. In addition to the online instructions for installing SceneGen, I had to run this command:

pip3 install requests

I also had to modify the SceneGen.Py to change the format the file is exported as. The existing file dump for scenes does not work with hassio. If anyone is interested I can upload the code modifications.

I do still think there is value in adding something similar to this in hassio. Other competitive products make creating scenes easy. I don’t love this solution, since it requires having to edit config files. It should be as easy as saving the current scene and assigning a name to it.

My thought anyway.

2 months ago was working, can’t remember which HASS version was using)… in order to check now with latest HASS release I will need to install it again on a separate pi3 with Hassbian or something

yes please

That would be awesome :slight_smile:

Open a PR?

1 Like

Sorry I do not know what is that, I am a newb amateur :slight_smile:

Nevertheless I made an image of HASSBIAN and installed on a fresh pi3, but I receive this error I guess is related to the new authentication ???

pi@hassbian:~/scenegen $ ./scenegen.py http://192.168.1.253:8123 -k mypassword
-bash: ./scenegen.py: Permission denied

I would like this feature too! The first step is to break out Home Assistant scenes from the external scenes provided by an integration (architecture issue here) and then we can start adding a “store” feature. Initially as a service scene_core.store called with

{
  "name": "Evening Living Room",
  "entity_id": [
    "light.living_room_wall",
    "light.living_room_ceiling"
  ],
}

However, don’t hold your breath waiting till I do it. I am kinda chipping at projects left and right and this one is not high on the list.

I am happy to guide someone in making this a reality.

1 Like

Here is the code, I had to redo everything as if hassio removed it all :confused: I didn’t have time to retest it, but this should be in a format for hassio and you can dump into your configuration file.

scenegen.py

#!/usr/bin/python3

import requests
import argparse
import configparser
import sys

light_color_types = ["xy_color", "rgb_color", "color_temp", "color_name"]

def error(message):
    sys.stderr.write("error: %s\n" % message)
    sys.exit(1)

def get_states(url, key):
  if key != None:
    headers = {'x-ha-access': key}
  else:
    headers = {}
    
  apiurl = url + "/api/states"
  
  r = requests.get(apiurl, headers=headers)
  
  if r.status_code != 200:
    error("Error calling Home Assistant: {}, {}".format(r.status_code, r.reason))
    
  return r.json()

def output_attrs(state, args):
  parts = state["entity_id"].split(".")
  type = parts[0]
  name = parts[1]
  light_attrs = ["transition", "profile", "brightness", "flash"]
  light_color_types = ["xy_color", "rgb_color", "color_temp", "color_name"]
  if type == "light" and "light" in args.types:
    print ("      {}:".format(state["entity_id"]))
    print ("        state: {}".format(state["state"]))
    for attr in light_attrs:      
      if attr in state["attributes"]:
          print("        {}: {}".format(attr, round(float(state["attributes"][attr]))))
    for color_type in light_color_types:
      if color_type in state["attributes"] and args.colortype == color_type:
        print("        {}: {}".format(color_type, state["attributes"][color_type]))
  if type == "switch" and "switch" in args.types:
    print ("      {}:".format(state["entity_id"]))
    print ("        state: {}".format(state["state"]))
  
def main():

  # Get command line args
  
  parser = argparse.ArgumentParser()

  parser.add_argument("url", help="url for Home Assistant instance")
  parser.add_argument("-k", "--key", help="API Key of Home Assistant instance")
  parser.add_argument("-s", "--scenename", help="Name of scene to generate", default = "My New Scene")
  parser.add_argument("-m", "--mapfile", help="Name of mapfile to enable device filtering")
  parser.add_argument("-f", "--filter", help="Comma separated list of device collections as defined in mapfile")
  parser.add_argument("-c", "--colortype", help="color type to use", default = "color_temp", choices = light_color_types)
  parser.add_argument("-t", "--types", help="list of device types to include", default = "light,switch")
  args = parser.parse_args()
  
  devices = {}
  if args.mapfile:
    config = configparser.ConfigParser()
    config.read_file(open(args.mapfile))
    for section in config.sections():
      devices[section] = {}
      for option in config.options(section):
        devices[section][option] = config.get(section, option)
  
  filters = []
  if args.filter:
    if args.mapfile:
      filters = args.filter.split(",")
    else:
      error("Must specify a mapfile if using filters")
  try:
    states = get_states(args.url, args.key)
    print("  - name: {}".format(args.scenename))
    print("    entities:")
    for state in states:
      if args.mapfile:
        if args.filter:
          for filter in filters:
            if filter in devices and state["entity_id"] in devices[filter]:
              output_attrs(state, args)
        else:
          for section in devices:
            if state["entity_id"] in devices[section]:
              output_attrs(state, args)
      else:
        output_attrs(state, args)

  except:
    raise
 
if __name__ == "__main__":
    main()
1 Like

thanks a lot. Could you please tell me what steps to do: copy this file in config folder? And after that?

Here are the steps to install. Remember, HASSIO is installed in whats called a container. As soon as the system is rebooted everything you’ve done is removed. I suggest moving scenegen into the custom components folder with hassio’s config folder once installed. This will keep the modifications to the python script from being removed. Here are the steps I did to get this to work. I still am hopping that someone will make this more permeant.

Step 1:

sudo pip3 install configparser

Step 2:

pip3 install requests

Step 3:
$ git clone https://github.com/home-assistant/scenegen.git

Step 4:

cd scenegen

Step 5:

nano /scenegen/scenegen.py`

Step 6:
Replace everything in the file with the code I uploaded above.

To run:
./scenegen.py http://yourHassioIP:8123 -k yourPassword > /root/config/sceneName.txt

You should be able to take the output from the file and use that in your config. Hope that helps.

Thanks a lot. I did all and have an error. The HASS password is correct, I also gave the command with sudo at beginning but same result

user@ubuntu:~/scenegen$ ./scenegen.py http://192.168.1.1:8123 -k password > /root/config/sceneName.txt
-bash: /root/config/sceneName.txt: Permission denied


root@ubuntu:/home/user/scenegen# ./scenegen.py http://192.168.1.1:8123 -k password > /root/config/sceneName.txt
bash: /root/config/sceneName.txt: No such file or directory
root@ubuntu:/home/user/scenegen# dir
CLA.md  CODE_OF_CONDUCT.md  LICENSE.md  map.cfg  README.md  scenegen.py
root@ubuntu:/home/user/scenegen#