config.py (2360B)
1 # strix/motion/config.py 2 # 3 # Copyright (C) 2017 Brian C. Lane 4 # 5 # This program is free software; you can redistribute it and/or modify 6 # it under the terms of the GNU General Public License as published by 7 # the Free Software Foundation; either version 2 of the License, or 8 # (at your option) any later version. 9 # 10 # This program is distributed in the hope that it will be useful, 11 # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 # GNU General Public License for more details. 14 # 15 # You should have received a copy of the GNU General Public License 16 # along with this program. If not, see <http://www.gnu.org/licenses/>. 17 import os 18 19 class MotionConfig(): 20 """ Parse a motion configuration file into dicts 21 22 Last key wins. Threads are stored in self.thread["thread-N"] 23 """ 24 config = {} 25 thread = {} 26 _thread_n = 0 27 28 def thread_n(self) -> str: 29 """ Return an incrementing thread-N string 30 31 :returns: str 32 """ 33 self._thread_n += 1 34 return "thread-%d" % self._thread_n 35 36 def split(self, s): 37 """ Split the line into key and optional values. 38 39 :returns: (k, v) where v may be "" 40 """ 41 try: 42 k, v = s.strip().split(" ", 1) 43 44 # thread|camera is a special case, can be more than 1 45 if k == "thread" or k == "camera": 46 k = self.thread_n() 47 except ValueError: 48 k = s 49 v = "" 50 return (k, v) 51 52 def parse(self, config_path): 53 """ Parse a motion config file 54 55 :returns: dict 56 """ 57 with open(config_path) as f: 58 return dict([ 59 self.split(line) 60 for line in f.readlines() 61 if line.strip() and not line.startswith("#")]) 62 63 def __init__(self, config_path): 64 self.config = self.parse(config_path) 65 for t in filter(lambda k: k.startswith("thread") or k.startswith("camera"), self.config.keys()): 66 thread_path = self.config[t] 67 if not thread_path.startswith("/"): 68 # Turn the relative path into an absolute one using the config_path 69 thread_path = os.path.abspath(os.path.join(os.path.dirname(config_path), thread_path)) 70 self.thread[t] = self.parse(thread_path)