From e65ed89053f5a093bd860bcde05488d3bff9e08f Mon Sep 17 00:00:00 2001 From: Athemis Date: Thu, 31 Jan 2019 17:17:37 +0100 Subject: [PATCH] new camera worker functional in standalone mode --- phytopi/camera/camera.py | 52 +++++++++++++++++++++++++--------------- 1 file changed, 33 insertions(+), 19 deletions(-) diff --git a/phytopi/camera/camera.py b/phytopi/camera/camera.py index 8608127..800d801 100644 --- a/phytopi/camera/camera.py +++ b/phytopi/camera/camera.py @@ -1,48 +1,62 @@ import io import os import sys +import stat import subprocess import signal +from enum import Enum from phytopi import db, models, app +# map commands +camera_cmds = { + 'start_timelapse': 'tl 1', + 'stop_timelapse': 'tl 0', +} + +class CameraStatus(Enum): + STOPPED = 0 + IDLE = 1 + TIMELAPSE = 2 + VIDEO = 3 + class CameraWorker(object): - def __init__(self, pidfile='/tmp/raspimjpeg.pid', executable='/usr/local/bin/raspimjpeg', fifo='/dev/shm/mjpeg/mjpeg_fifo', app=None): + def __init__(self, pidfile='/tmp/raspimjpeg.pid', executable='/usr/local/bin/raspimjpeg', fifo='/dev/shm/mjpeg/FIFO', app=None): self.pidfile = pidfile self.executable = executable self.fifo = fifo self.proc = None self.pid = None self.app = app + self.status = CameraStatus.STOPPED def start(self): - # create FIFO if not existent - if not os.path.isfile(self.fifo): - os.mkfifo(self.fifo) + # create FIFO + os.mkfifo(self.fifo) # check if process is already running if os.path.isfile(self.pidfile): - with open(self.pidfile) as fh: + with open(self.pidfile, 'r') as fh: self.pid = int(fh.read()) # if not, spawn new process and create pid file - self.proc = subprocess.Popen(self.executable, stdout=subprocess.PIPE) + self.proc = subprocess.Popen([self.executable]) self.pid = self.proc.pid - with open(self.pidfile) as fh: - fh.write(self.pid) + with open(self.pidfile, 'w') as fh: + fh.write(str(self.pid)) + self.status = CameraStatus.IDLE def stop(self): - # if process was spawned by this instance, killing is easy - if self.proc: - self.proc.kill() - else: - # otherwise send SIGTERM to pid - os.kill(self.pid, signal.SIGTERM) + os.killpg(os.getpgid(self.pid), signal.SIGTERM) os.unlink(self.fifo) + os.unlink(self.pidfile) + self.status = CameraStatus.STOPPED def send_cmd(self, cmd): - with open(self.fifo, 'w') as fh: - fh.write(cmd) - - def read_output(self): - return self.proc.stdout.readlines() \ No newline at end of file + if cmd in camera_cmds: + with open(self.fifo, 'w') as fh: + fh.write(cmd) + if cmd == camera_cmds['start_timelapse']: + self.status = CameraStatus.TIMELAPSE + if cmd == camera_cmds['stop_timelapse']: + self.status = CameraStatus.IDLE \ No newline at end of file