Call Shell Script from AppDaemon

I am wondering if it is possible to call a shell script / command from an Appdaemon program ? I would like to get a new picture from a webcam if motion is detected, but use Appdaemon to avoid setting all kind moving parts up.

Cheers !

Its just Python, so you should be able to use the ordinary Subprocess library (not that I’ve done it from appdaemon)

https://docs.python.org/3.6/library/subprocess.html

1 Like

Thanks for the hint.

I gave it a try, but I don’t get the expected result. The script below seems to run and the subprocess returns the exit code 0. However, I expect that the picture should be update in the folder and this never happens. Running the same command as the HASS user works without any issues.

Any thoughts ?

import appdaemon.appapi as appapi
import subprocess

#
#
# Args:
#

class Motion_Cam(appapi.AppDaemon):

  def initialize(self):
    # Subscribe to sensors
    if "sensor" in self.args:
      self.listen_state(self.motion, self.args["sensor"])
    else:
      self.log("No sensor specified, doing nothing")

  def motion(self, entity, attribute, old, new, kwargs):
    if ("state" in new and new["state"] == "on" and old["state"] == "off") or new == "on":
      self.log("Get a new picture ")
      returncode = subprocess.call('/usr/bin/fswebcam -r 640x480 /var/lib/homeassistant/camera/livingroom.jpg',shell=True)
      self.log(str(returncode))

args needs to be a list not a string. See the section starting args should be a sequence of program arguments in the python doc page.

Also, I don’t think you need shell=True for this command. It won’t stop it working, but will take unnecessary time.

Unfortunately that does not help. I changed the code to the following, but still it does not work.

cmd = ['/usr/bin/fswebcam','-r 640x480','/var/lib/homeassistant/camera/livingroom.jpg']
returncode = subprocess.call(cmd)

From the doc page
Note in particular that options (such as -input) and arguments (such as eggs.txt) that are separated by whitespace in the shell go in separate list elements,

So

Needs to be two separate elements.

Graham, thanks for all your hints!

I am sure I already tried all combinations, but now reduced it to only command and one parameter. Still the program runs when triggered, but it seems that the external command is never called (despite the fact that the return code comes back with 0). I dont see any updated image from the program.

I also tried to call the program as the HASS user and can confirm that this seems to work.

cmd = ['/usr/bin/fswebcam','/var/lib/homeassistant/camera/livingroom.jpg']
returncode = subprocess.call(cmd)

Argh !!

Just found out that AppDaemon runs as its own user and this one did not have access to the Video device. Changing access rights fixed it.

Thanks for you help on this !!!

1 Like