Example #1
0
def main():
    """conf['image']['trackbars']"""

    scr = os.path.dirname(os.path.abspath(__file__))
    my_conf = MyConfig(scr + "/rezobox_server.ini")
    conf = my_conf.conf
    print("Configuration du serveur: {}\n".format(conf))

    disp = Display(my_conf)

    if not conf['image']['thread']:
        print('Test kinect sans thread')
        while 1:
            disp.one_loop()
    else:
        print('Test kinect avec thread')
        kinect_thread(disp)
Example #2
0
    def __init__(self, expn=None, exp_path=None, config=None, loglevel=log.NO):
        self.LOGLEVEL = loglevel

        myconfig = MyConfig()
        if expn is not None and exp_path is not None:
            self.EXPN = expn
            self.FOLDER = os.path.join(exp_path, str(expn))
            self.config = myconfig  #load_config(self.FOLDER)
            log.info(self.LOGLEVEL, "Load experiment #{}".format(self.EXPN))
        elif config is not None:
            self.config = config
            exp_path = os.path.join(self.config.ROOT_PATH,
                                    self.config.EXP_FOLDER)
            os.makedirs(exp_path, exist_ok=True)
            self.EXPN = 1 + len(utils.listdir(exp_path))
            self.FOLDER = os.path.join(self.config.ROOT_PATH,
                                       self.config.EXP_FOLDER, str(self.EXPN))
            log.info(self.LOGLEVEL, self.__str__())
        else:
            raise RuntimeError()
Example #3
0
def daemon():
    #Spawn process per a section header.
    location = os.path.dirname(os.path.realpath(__file__))
    try:
        config = MyConfig(os.path.join(location, 'monitor.config'))
    except (ValueError, KeyError) as msg:
        LOGGER.critical(msg)
        sys.exit(1)
    manager = multiprocessing.Manager()
    health_dict = manager.dict()
    #Can I move this into the below loop? <------------------------###
    for section in config.__dict__.keys():
        if 'grpc' not in section:
            health_dict[section] = False
    health_dict['flushed'] = False
    jobs = []
    #Create lock object to ensure gRPC is only used once
    lock = multiprocessing.Lock()
    for section in config.__dict__.keys():
        if 'grpc' not in section:
            d = multiprocessing.Process(name=section, target=monitor, args=(
                section,
                lock,
                config,
                health_dict
                )
            )
            jobs.append(d)
            d.start()
    try:
        for job in jobs:
            job.join()
    except KeyboardInterrupt:
        print('Keyboard interrupt received.')
        for job in jobs:
            job.terminate()
            job.join()
Example #4
0
#!/usr/bin/python3
import os
import os.path
import sqlite3
from argparse import ArgumentParser
from operator import itemgetter
from math import log
from sys import float_info
import utils
from myconfig import MyConfig
from dirwalk import walkIndex

config = MyConfig()

#change cwd to the word recognizer directory
words_dir = config.getWordRecognizerDir()
os.chdir(words_dir)
#chdir done

############################################################
#                Create Bigram Database                    #
############################################################

CREATE_BIGRAM_DDL = '''
CREATE TABLE bigram (
      prefix TEXT NOT NULL,
      postfix TEXT NOT NULL,
      freq INTEGER NOT NULL
      );
'''
Example #5
0
                    "rvec": rvecs.tolist(),
                    "tvec": tvecs.tolist()
                }).encode("utf-8")
                # #print(data)
                self.sender.send_to(data, ("224.0.0.11", 18888))

            if cv2.waitKey(100) == 27:
                break

        cv2.destroyAllWindows()


if __name__ == "__main__":

    cam = 0
    cf = MyConfig("./charuco.ini")
    conf = cf.conf
    apply_all_cam_settings(conf["HD5000"], cam)

    ct = CharucoTest(cam, cf)

    # #ct.create_markers_pdf()
    # #ct.create_chessboard_png()
    # #ct.create_images_calibration()
    # #ct.show_some_images()
    # #ct.read_chessboards()
    # #ct.calibrate_camera()
    # #ct.calibration_test_init()
    # #ct.calibration_test()
    # #ct.translation_rotation_test()
    ct.detect_one_real_marker()
Example #6
0
#!/usr/bin/python3
import os
import os.path
import sys
from argparse import ArgumentParser
from myconfig import MyConfig
from utils import read_file

config = MyConfig()


def handleError(error):
    sys.exit(error)


def mergeSubIndex(output, path):
    for root, dirs, files in os.walk(path, topdown=True, onerror=handleError):
        for onefile in files:
            filepath = os.path.join(root, onefile)
            if onefile.endswith(config.getIndexPostfix()):
                data = read_file(filepath)
                output.writelines([data])
            else:
                print('Unexpected file:' + filepath)


def iterateSubDirectory(oldroot, newroot, level):
    #Merge the index in oldroot
    if level <= 0:
        newindex = newroot + config.getIndexPostfix()
        dirname = os.path.dirname(newindex)
Example #7
0
from dirwalk import walkIndexFast


INSERT_NGRAM_DML = '''
INSERT INTO ngram(words, freq) VALUES(?, 1);
'''

UPDATE_NGRAM_DML = '''
UPDATE ngram SET freq = freq + 1 WHERE words = ?;
'''

PRUNE_NGRAM_DML = '''
DELETE FROM ngram WHERE freq <= ?;
'''

config = MyConfig()

#maximum combine number
N = config.getMaximumCombineNumber()

#change cwd to the word recognizer directory
words_dir = config.getWordRecognizerDir()
os.chdir(words_dir)
#chdir done


def handleOneDocument(infile, cur, length):
    print(infile, length)

    infilestatuspath = infile + config.getStatusPostfix()
    infilestatus = utils.load_status(infilestatuspath)
Example #8
0
class operateGarage(MyLog):
    def __init__(self, args=None):
        super(operateGarage, self).__init__()
        self.ProgramName = "operate Garage Shutters"
        self.Version = "Unknown"
        self.log = None
        self.IsStopping = False
        self.ProgramComplete = False

        if args.ConfigFile == None:
            self.ConfigFile = "/etc/operateGarage.conf"
        else:
            self.ConfigFile = args.ConfigFile

        self.console = SetupLogger("shutters_console",
                                   log_file="",
                                   stream=True)

        ## should be re-enabled before actual production use
        # if os.geteuid() != 0:
        #     self.LogConsole("You need to have root privileges to run this script.\nPlease try again, this time using 'sudo'.")
        #     sys.exit(1)

        if not os.path.isfile(self.ConfigFile):
            self.LogConsole("Creating new config file : " + self.ConfigFile)
            defaultConfigFile = os.path.dirname(
                os.path.realpath(__file__)) + '/defaultConfig.conf'
            print(defaultConfigFile)
            if not os.path.isfile(defaultConfigFile):
                self.LogConsole("Failure to create new config file: " +
                                defaultConfigFile)
                sys.exit(1)
            else:
                copyfile(defaultConfigFile, self.ConfigFile)

        # read config file
        self.config = MyConfig(filename=self.ConfigFile, log=self.console)
        result = self.config.LoadConfig()
        if not result:
            self.LogConsole("Failure to load configuration parameters")
            sys.exit(1)

        # log errors in this module to a file
        self.log = SetupLogger("shutters",
                               self.config.LogLocation + "operateGarage.log")
        self.config.log = self.log

        if self.IsLoaded():
            self.LogWarn("operateGarage.py is already loaded.")
            sys.exit(1)

        if not self.startPIGPIO():
            self.LogConsole("Not able to start PIGPIO")
            sys.exit(1)

        self.shutter = Shutter(log=self.log, config=self.config)

        # atexit.register(self.Close)
        # signal.signal(signal.SIGTERM, self.Close)
        # signal.signal(signal.SIGINT, self.Close)

        self.mqtt = MQTT(kwargs={
            'log': self.log,
            'shutter': self.shutter,
            'config': self.config
        })

        self.ProcessCommand(args)

    #------------------------ operateGarage::IsLoaded -----------------------------
    #return true if program is already loaded
    def IsLoaded(self):

        file_path = '/var/lock/' + os.path.basename(__file__)
        global file_handle

        try:
            file_handle = open(file_path, 'w')
            fcntl.lockf(file_handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
            return False
        except IOError:
            return True

    #--------------------- operateGarage::startPIGPIO ------------------------------
    def startPIGPIO(self):
        if sys.version_info[0] < 3:
            import commands
            status, process = commands.getstatusoutput('pidof pigpiod')
            if status:  #  it wasn't running, so start it
                self.LogInfo("pigpiod was not running")
                commands.getstatusoutput(
                    'sudo pigpiod -l -n localhost')  # try to  start it
                time.sleep(0.5)
                # check it again
                status, process = commands.getstatusoutput('pidof pigpiod')
        else:
            import subprocess
            status, process = subprocess.getstatusoutput('pidof pigpiod')
            if status:  #  it wasn't running, so start it
                self.LogInfo("pigpiod was not running")
                subprocess.getstatusoutput(
                    'sudo pigpiod -l -n localhost')  # try to  start it
                time.sleep(0.5)
                # check it again
                status, process = subprocess.getstatusoutput('pidof pigpiod')

        if not status:  # if it was started successfully (or was already running)...
            pigpiod_process = process
            self.LogInfo("pigpiod is running, process ID is {} ".format(
                pigpiod_process))

            try:
                pi = pigpio.pi()  # local GPIO only
                self.LogInfo("pigpio's pi instantiated")
            except Exception as e:
                start_pigpiod_exception = str(e)
                self.LogError("problem instantiating pi: {}".format(
                    start_pigpiod_exception))
        else:
            self.LogError("start pigpiod was unsuccessful.")
            return False
        return True

    #--------------------- operateGarage::ProcessCommand -----------------------------------------------
    def ProcessCommand(self, args):
        if ((args.shutterName != "") and (args.down == True)):
            self.shutter.lower(self.config.ShuttersByName[args.shutterName])
        elif ((args.shutterName != "") and (args.up == True)):
            self.shutter.rise(self.config.ShuttersByName[args.shutterName])
        elif ((args.shutterName != "") and (args.stop == True)):
            self.shutter.stop(self.config.ShuttersByName[args.shutterName])
        elif (args.mqtt == True):
            self.mqtt.setDaemon(True)
            self.mqtt.start()

        else:
            parser.print_help()

    #    if (args.mqtt == True):
    #        self.mqtt.setDaemon(True)
    #        self.mqtt.start()

    #    if (args.mqtt == True):
    #    self.mqtt.join()
        self.LogInfo("Process Command Completed....")
        #self.Close()

    #---------------------operateGarage::Close----------------------------------------

    def Close(self, signum=None, frame=None):

        # we dont really care about the errors that may be generated on shutdown
        try:
            self.IsStopping = True
        except Exception as e1:
            self.LogErrorLine("Error Closing Monitor: " + str(e1))

        self.LogError("operateGarage Shutdown")

        try:
            self.ProgramComplete = True
            if (not self.mqtt == None):
                self.LogError(
                    "Stopping MQTT Listener. This can take up to 1 second...")
                self.mqtt.shutdown_flag.set()
                self.mqtt.join()
                self.LogError("MQTT Listener stopped. Now exiting.")
            sys.exit(0)
        except:
            pass
Example #9
0
#!/usr/bin/python3
import os
import sqlite3
from argparse import ArgumentParser
import utils
from myconfig import MyConfig
from dirwalk import walkIndex


config = MyConfig()

#default pinyin total frequency
default = config.getDefaultPinyinTotalFrequency()

#minimum pinyin frequency
minimum = config.getMinimumPinyinFrequency()

#change cwd to the word recognizer directory
words_dir = config.getWordRecognizerDir()
os.chdir(words_dir)
#chdir done


atomic_words_dict = {}
merged_words_dict = {}


def load_atomic_words(filename):
    wordsfile = open(filename, "r")
    for oneline in wordsfile.readlines():
        oneline = oneline.rstrip(os.linesep)
Example #10
0
import os, sys
from time import sleep
import threading

from twisted.internet.endpoints import TCP4ServerEndpoint
from twisted.internet.protocol import Protocol, Factory
from twisted.internet import reactor

from myconfig import MyConfig
from kinect import Display

# Variable globale
scr = os.path.dirname(os.path.abspath(__file__))

# L'object configuration
conf_obj = MyConfig(scr + "/rezobox_server.ini")
CONF = conf_obj.conf
print("Configuration du serveur: {}\n".format(CONF))

TCP_PORT = CONF["server"]["port"]
TEMPO = float(CONF["server"]["tempo"])
TO_BLEND = None


class MyTcpServer(Protocol):
    def __init__(self, factory):
        self.factory = factory
        self.loop = 1

    def connectionMade(self):
        self.addr = self.transport.client
Example #11
0
#!/usr/bin/python3
import os
import os.path
import sqlite3
from argparse import ArgumentParser
from operator import itemgetter
from math import log
from sys import float_info
import utils
from myconfig import MyConfig
from dirwalk import walkIndex


config = MyConfig()

#change cwd to the word recognizer directory
words_dir = config.getWordRecognizerDir()
os.chdir(words_dir)
#chdir done


############################################################
#                Create Bigram Database                    #
############################################################


CREATE_BIGRAM_DDL = '''
CREATE TABLE bigram (
      prefix TEXT NOT NULL,
      postfix TEXT NOT NULL,
      freq INTEGER NOT NULL
Example #12
0
#!/usr/bin/python3
import os
import sqlite3
from argparse import ArgumentParser
import utils
from myconfig import MyConfig
from dirwalk import walkIndex

config = MyConfig()

#default pinyin total frequency
default = config.getDefaultPinyinTotalFrequency()

#minimum pinyin frequency
minimum = config.getMinimumPinyinFrequency()

#change cwd to the word recognizer directory
words_dir = config.getWordRecognizerDir()
os.chdir(words_dir)
#chdir done

atomic_words_dict = {}
merged_words_dict = {}


def load_atomic_words(filename):
    wordsfile = open(filename, "r")
    for oneline in wordsfile.readlines():
        oneline = oneline.rstrip(os.linesep)

        if len(oneline) == 0:
Example #13
0
                    data = json.dumps({
                        "rvec": rvec.tolist(),
                        "tvec": tvec.tolist()
                    }).encode("utf-8")
                    self.sender.send_to(data, ("224.0.0.11", 18888))

            if cv2.waitKey(100) == 27:
                break

        cv2.destroyAllWindows()


if __name__ == "__main__":

    cam = 0
    cf = MyConfig("./aruco.ini")
    conf = cf.conf
    apply_all_cam_settings(conf["HD5000"], cam)

    at = ArucoTest(cam, cf)
    # #at.get_data_calibration()
    # #at.calibrate()
    at.validating_real_time_results()
"""
Rodrigues
[[ 2.2335851 ]
 [-2.0081005 ]
 [ 0.34698185]]

(array([[ 0.09461465, -0.99137014,  0.09073787],
       [-0.96433645, -0.11390218, -0.23891737],
Example #14
0
#!/usr/bin/python3
import os
import sqlite3
from argparse import ArgumentParser
from operator import itemgetter
import utils
from myconfig import MyConfig
from dirwalk import walkIndex

config = MyConfig()

#change cwd to the word recognizer directory
words_dir = config.getWordRecognizerDir()
os.chdir(words_dir)
#chdir done

############################################################
#                     Get Threshold                        #
############################################################

SELECT_WORD_DML = '''
SELECT freq from ngram where words = ?;
'''

def getWordFrequency(conn, word):
    sep = config.getWordSep()
    word_str = sep + word + sep

    cur = conn.cursor()
    row = cur.execute(SELECT_WORD_DML, (word_str, )).fetchone()
Example #15
0
#!/usr/bin/python3
import os
import os.path
import sys
from argparse import ArgumentParser
from myconfig import MyConfig
from utils import read_file


config = MyConfig()


def handleError(error):
    sys.exit(error)


def mergeSubIndex(output, path):
    for root, dirs, files in os.walk(path, topdown=True, onerror=handleError):
        for onefile in files:
            filepath = os.path.join(root, onefile)
            if onefile.endswith(config.getIndexPostfix()):
                data = read_file(filepath)
                output.writelines([data])
            else:
                print('Unexpected file:' + filepath)


def iterateSubDirectory(oldroot, newroot, level):
    #Merge the index in oldroot
    if level <= 0:
        newindex = newroot + config.getIndexPostfix()
Example #16
0
from myconfig import MyConfig

config = MyConfig()

print(config.some_text)
Example #17
0
#!/usr/bin/python3
import os
import os.path
import sys
from subprocess import Popen, PIPE
from argparse import ArgumentParser
from operator import itemgetter
import utils
from myconfig import MyConfig


config = MyConfig()

#change cwd to the libpinyin data directory
libpinyin_dir = config.getToolsDir()
libpinyin_sub_dir = os.path.join(libpinyin_dir, 'data')
os.chdir(libpinyin_sub_dir)
#chdir done


def handleError(error):
    sys.exit(error)


def handleOneModel(modelfile, reportfile):
    modelfilestatuspath = modelfile + config.getStatusPostfix()
    modelfilestatus = utils.load_status(modelfilestatuspath)
    if not utils.check_epoch(modelfilestatus, 'Generate'):
        raise utils.EpochError('Please generate first.\n')
    if utils.check_epoch(modelfilestatus, 'Estimate'):
        return
Example #18
0
""" api """
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
####
from password_strength import PasswordPolicy
import pyotp
####
from mymongo import MyMongo
from mylog import MyLog
from myconfig import MyConfig

# pylint: disable=fixme

c = MyConfig()
l = MyLog(c.cfg['virtualenv']['dir'] + '_api')

appname = c.cfg['virtualenv']['dir']

mongohost = c.cfg['dbs']['mongo']['host']
mongodb = c.cfg['dbs']['mongo']['db']
sessionHashSecret = c.cfg['session']['hash_secret']

passpolicylength = c.cfg['password_strength']['length']
passpolicyuppercase = c.cfg['password_strength']['uppercase']
passpolicynumbers = c.cfg['password_strength']['numbers']
passpolicyspecial = c.cfg['password_strength']['special']
passpolicy = PasswordPolicy.from_names(
    length=passpolicylength,  # min length
    uppercase=passpolicyuppercase,  # need min. uppercase letters
    numbers=passpolicynumbers,  # need min. digits
Example #19
0
from myconfig import MyConfig

config = MyConfig(["settings.toml", ".secrets.toml"])

print(config.some_text)
print(config.some_secrets_text)
print(config.some_text_env)
Example #20
0
#!/usr/bin/python3
import os
import os.path
import sys
from subprocess import Popen, PIPE
from argparse import ArgumentParser
import utils
from myconfig import MyConfig
from dirwalk import walkIndexFast

config = MyConfig()

#change cwd to the libpinyin data directory
libpinyin_dir = config.getToolsDir()
libpinyin_sub_dir = os.path.join(libpinyin_dir, 'data')
os.chdir(libpinyin_sub_dir)
#chdir done


#Note: all file passed here should be trained.
def generateOneText(infile, modelfile, reportfile):
    infilestatuspath = infile + config.getStatusPostfix()
    infilestatus = utils.load_status(infilestatuspath)
    if not utils.check_epoch(infilestatus, 'MergeSequence'):
        raise utils.EpochError('Please mergeseq first.\n')
    if utils.check_epoch(infilestatus, 'Generate'):
        return False

    #begin processing
    cmdline = ['../utils/training/gen_k_mixture_model', \
                   '--maximum-occurs-allowed', \
Example #21
0
from myconfig import MyConfig
from dirwalk import walkIndexFast

INSERT_NGRAM_DML = '''
INSERT INTO ngram(words, freq) VALUES(?, 1);
'''

UPDATE_NGRAM_DML = '''
UPDATE ngram SET freq = freq + 1 WHERE words = ?;
'''

PRUNE_NGRAM_DML = '''
DELETE FROM ngram WHERE freq <= ?;
'''

config = MyConfig()

#maximum combine number
N = config.getMaximumCombineNumber()

#change cwd to the word recognizer directory
words_dir = config.getWordRecognizerDir()
os.chdir(words_dir)
#chdir done


def handleOneDocument(infile, cur, length):
    print(infile, length)

    infilestatuspath = infile + config.getStatusPostfix()
    infilestatus = utils.load_status(infilestatuspath)
Example #22
0
class operateShutters(MyLog):
    def __init__(self, args=None):
        super(operateShutters, self).__init__()
        self.ProgramName = "operate Somfy Shutters"
        self.Version = "Unknown"
        self.log = None
        self.IsStopping = False
        self.ProgramComplete = False

        if args.ConfigFile is None:
            self.ConfigFile = "/etc/operateShutters.conf"
        else:
            self.ConfigFile = args.ConfigFile

        self.console = SetupLogger("shutters_console",
                                   log_file="",
                                   stream=True)

        if os.geteuid() != 0:
            self.LogConsole(
                "You need to have root privileges to run this script.\nPlease try again, this time using 'sudo'."
            )
            sys.exit(1)

        if not os.path.isfile(self.ConfigFile):
            self.LogConsole("Creating new config file : " + self.ConfigFile)
            defaultConfigFile = os.path.dirname(
                os.path.realpath(__file__)) + '/defaultConfig.conf'
            print(defaultConfigFile)
            if not os.path.isfile(defaultConfigFile):
                self.LogConsole("Failure to create new config file: " +
                                defaultConfigFile)
                sys.exit(1)
            else:
                copyfile(defaultConfigFile, self.ConfigFile)

        # read config file
        self.config = MyConfig(filename=self.ConfigFile, log=self.console)
        result = self.config.LoadConfig()
        if not result:
            self.LogConsole("Failure to load configuration parameters")
            sys.exit(1)

        # log errors in this module to a file
        self.log = SetupLogger("shutters",
                               self.config.LogLocation + "operateShutters.log")
        self.config.log = self.log

        if self.IsLoaded():
            self.LogWarn("operateShutters.py is already loaded.")
            sys.exit(1)

        # if not self.startPIGPIO():
        #    self.LogConsole("Not able to start PIGPIO")
        #    sys.exit(1)

        self.shutter = Shutter(log=self.log, config=self.config)

        # atexit.register(self.Close)
        # signal.signal(signal.SIGTERM, self.Close)
        # signal.signal(signal.SIGINT, self.Close)

        self.schedule = Schedule(log=self.log, config=self.config)
        self.scheduler = None
        self.webServer = None

        if args.echo:
            self.alexa = Alexa(kwargs={
                'log': self.log,
                'shutter': self.shutter,
                'config': self.config
            })

        if args.mqtt:
            self.mqtt = MQTT(kwargs={
                'log': self.log,
                'shutter': self.shutter,
                'config': self.config
            })

        self.ProcessCommand(args)

    # ------------------------ operateShutters::IsLoaded -----------------------------
    # return true if program is already loaded
    def IsLoaded(self):

        file_path = '/var/lock/' + os.path.basename(__file__)
        global file_handle

        try:
            file_handle = open(file_path, 'w')
            fcntl.lockf(file_handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
            return False
        except IOError:
            return True

    # --------------------- operateShutters::startPIGPIO ------------------------------
    def startPIGPIO(self):
        pigpio_args = "-l -a"
        pigpio_host = ""
        pigpio_port = 8888

        if os.environ.get('PIGPIO_ARGS') is not None:
            self.LogInfo("Using the following env PiGPIO args to start: " +
                         os.environ.get('PIGPIO_ARGS'))
            pigpio_args = os.environ.get('PIGPIO_ARGS')
        else:
            self.LogInfo("Using the following PiGPIO args to start: '-l -a'")

        if self.config.PiGPIOPort is not None:
            if os.environ.get('PIGPIO_PORT') is not None:
                self.LogInfo("Using the following env PiGPIO port to start: " +
                             os.environ.get('PIGPIO_PORT'))
                pigpio_port = os.environ.get('PIGPIO_PORT')
            else:
                self.LogInfo(
                    "Using the following default PiGPIO port to start: 8888")
                pigpio_port = 8888
        else:
            self.LogInfo("Using the following config PiGPIO port to start: " +
                         str(self.config.PiGPIOPort))
            pigpio_port = self.config.PiGPIOPort

        if self.config.PiGPIOHost is not None:
            if os.environ.get('PIGPIO_ADDR') is not None:
                self.LogInfo("Using the following env PiGPIO host to start: " +
                             os.environ.get('PIGPIO_ADDR'))
                pigpio_host = os.environ.get('PIGPIO_ADDR')
            else:
                self.LogInfo(
                    "Using the following defaultPiGPIO host to start: ''")
                pigpio_host = ""
        else:
            self.LogInfo("Using the following config PiGPIO host to start: " +
                         str(self.config.PiGPIOHost))
            pigpio_host = self.config.PiGPIOHost

        if sys.version_info[0] < 3:
            import commands
            status, process = commands.getstatusoutput('pidof pigpiod')
            if status:  # it wasn't running, so start it
                self.LogInfo("pigpiod was not running")
                commands.getstatusoutput('pigpiod ' +
                                         pigpio_args)  # try to  start it
                time.sleep(0.5)
                # check it again
                status, process = commands.getstatusoutput('pidof pigpiod')
        else:
            import subprocess
            status, process = subprocess.getstatusoutput('pidof pigpiod')
            if status:  # it wasn't running, so start it
                self.LogInfo("pigpiod was not running")
                subprocess.getstatusoutput('pigpiod ' +
                                           pigpio_args)  # try to  start it
                time.sleep(0.5)
                # check it again
                status, process = subprocess.getstatusoutput('pidof pigpiod')

        if not status:  # if it was started successfully (or was already running)...
            pigpiod_process = process
            self.LogInfo("pigpiod is running, process ID is {} ".format(
                pigpiod_process))

            try:
                if pigpio_host == "":
                    self.LogInfo("Connecting to localhost")
                    pi = pigpio.pi()
                else:
                    self.LogInfo("Connecting to : " + pigpio_host + ":" +
                                 pigpio_port)
                    pi = pigpio.pi(pigpio_host, pigpio_port)
                self.LogInfo("pigpio's pi instantiated")
            except Exception as e:
                start_pigpiod_exception = str(e)
                self.LogError("problem instantiating pi: {}".format(
                    start_pigpiod_exception))
        else:
            self.LogError("start pigpiod was unsuccessful.")
            return False
        return True

    # --------------------- operateShutters::ProcessCommand -----------------------------------------------
    def ProcessCommand(self, args):
        if (args.shutterName != "") and (args.down == True):
            self.shutter.lower(self.config.ShuttersByName[args.shutterName])
        elif (args.shutterName != "") and (args.up == True):
            self.shutter.rise(self.config.ShuttersByName[args.shutterName])
        elif (args.shutterName != "") and (args.stop == True):
            self.shutter.stop(self.config.ShuttersByName[args.shutterName])
        elif (args.shutterName != "") and (args.program == True):
            self.shutter.program(self.config.ShuttersByName[args.shutterName])
        elif (args.shutterName != "") and (args.demo == True):
            self.LogInfo("lowering shutter for 7 seconds")
            self.shutter.lowerPartial(
                self.config.ShuttersByName[args.shutterName], 7)
            time.sleep(7)
            self.LogInfo("rise shutter for 7 seconds")
            self.shutter.risePartial(
                self.config.ShuttersByName[args.shutterName], 7)
        elif (args.shutterName != "") and (args.duskdawn is not None):
            self.schedule.addRepeatEventBySunrise(
                [self.config.ShuttersByName[args.shutterName]], 'up',
                args.duskdawn[1],
                ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'])
            self.schedule.addRepeatEventBySunset(
                [self.config.ShuttersByName[args.shutterName]], 'down',
                args.duskdawn[0],
                ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'])
            self.scheduler = Scheduler(
                kwargs={
                    'log': self.log,
                    'schedule': self.schedule,
                    'shutter': self.shutter,
                    'config': self.config
                })
            self.scheduler.setDaemon(True)
            self.scheduler.start()
            if args.echo:
                self.alexa.setDaemon(True)
                self.alexa.start()
            if args.mqtt:
                self.mqtt.setDaemon(True)
                self.mqtt.start()
            self.scheduler.join()
        elif args.auto:
            self.schedule.loadScheudleFromConfig()
            self.scheduler = Scheduler(
                kwargs={
                    'log': self.log,
                    'schedule': self.schedule,
                    'shutter': self.shutter,
                    'config': self.config
                })
            self.scheduler.setDaemon(True)
            self.scheduler.start()
            if args.echo:
                self.alexa.setDaemon(True)
                self.alexa.start()
            if args.mqtt:
                self.mqtt.setDaemon(True)
                self.mqtt.start()
            self.webServer = FlaskAppWrapper(
                name='WebServer',
                static_url_path=os.path.dirname(os.path.realpath(__file__)) +
                '/html',
                log=self.log,
                shutter=self.shutter,
                schedule=self.schedule,
                config=self.config)
            self.webServer.run()
        else:
            parser.print_help()

        if args.echo:
            self.alexa.setDaemon(True)
            self.alexa.start()
        if args.mqtt:
            self.mqtt.setDaemon(True)
            self.mqtt.start()

        if args.echo:
            self.alexa.join()
        if args.mqtt:
            self.mqtt.join()
        self.LogInfo("Process Command Completed....")
        self.Close()

    # ---------------------operateShutters::Close----------------------------------------
    def Close(self, signum=None, frame=None):

        # we dont really care about the errors that may be generated on shutdown
        try:
            self.IsStopping = True
        except Exception as e1:
            self.LogErrorLine("Error Closing Monitor: " + str(e1))

        self.LogError("operateShutters Shutdown")

        try:
            self.ProgramComplete = True
            if self.scheduler is not None:
                self.LogError(
                    "Stopping Scheduler. This can take up to 1 second...")
                self.scheduler.shutdown_flag.set()
                self.scheduler.join()
                self.LogError("Scheduler stopped. Now exiting.")
            if self.alexa is not None:
                self.LogError(
                    "Stopping Alexa Listener. This can take up to 1 second...")
                self.alexa.shutdown_flag.set()
                self.alexa.join()
                self.LogError("Alexa Listener stopped. Now exiting.")
            if self.mqtt is not None:
                self.LogError(
                    "Stopping MQTT Listener. This can take up to 1 second...")
                self.mqtt.shutdown_flag.set()
                self.mqtt.join()
                self.LogError("MQTT Listener stopped. Now exiting.")
            if self.webServer is not None:
                self.LogError(
                    "Stopping WebServer. This can take up to 1 second...")
                self.webServer.shutdown_server()
                self.LogError("WebServer stopped. Now exiting.")
            sys.exit(0)
        except:
            pass
Example #23
0
#!/usr/bin/python3
import os
import os.path
import sys
from subprocess import Popen, PIPE
from argparse import ArgumentParser
from operator import itemgetter
import utils
from myconfig import MyConfig

config = MyConfig()

#change cwd to the libpinyin data directory
libpinyin_dir = config.getToolsDir()
libpinyin_sub_dir = os.path.join(libpinyin_dir, 'data')
os.chdir(libpinyin_sub_dir)
#chdir done


def handleError(error):
    sys.exit(error)


def handleOneModel(modelfile, reportfile):
    modelfilestatuspath = modelfile + config.getStatusPostfix()
    modelfilestatus = utils.load_status(modelfilestatuspath)
    if not utils.check_epoch(modelfilestatus, 'Generate'):
        raise utils.EpochError('Please generate first.\n')
    if utils.check_epoch(modelfilestatus, 'Estimate'):
        return
Example #24
0
#!/usr/bin/python3
import os
import os.path
import sys
from subprocess import Popen, PIPE
from argparse import ArgumentParser
import utils
from myconfig import MyConfig


#Please `make -f Makefile.data prepare` first

config = MyConfig()

#change cwd to the libpinyin data directory
libpinyin_dir = config.getEvalsDir()
libpinyin_sub_dir = os.path.join(libpinyin_dir, 'data')
os.chdir(libpinyin_sub_dir)
#chdir done

datafiles = [config.getFinalModelFileName(), \
             config.getEvalsTextFileName(), \
             'deleted_bigram.db']


def checkData():
    #check data files
    for onefile in datafiles:
        if not os.access(onefile, os.F_OK):
            sys.exit('missing one data file:' + onefile)
Example #25
0
#!/usr/bin/python3
import os
import os.path
import sys
from subprocess import Popen, PIPE
from argparse import ArgumentParser
from myconfig import MyConfig
import utils

config = MyConfig()

#change cwd to the libpinyin data directory
libpinyin_dir = config.getToolsDir()
libpinyin_sub_dir = os.path.join(libpinyin_dir, 'data')
os.chdir(libpinyin_sub_dir)
#chdir done


def validateModel(modelfile):
    #begin processing
    cmdline = ['../utils/training/validate_k_mixture_model', \
                   modelfile]

    subprocess = Popen(cmdline, shell=False, close_fds=True)

    (pid, status) = os.waitpid(subprocess.pid, 0)
    if status != 0:
        sys.exit('Corrupted model found when validating:' + modelfile)
    #end processing

Example #26
0
    def __init__(self, args=None):
        super(operateGarage, self).__init__()
        self.ProgramName = "operate Garage Shutters"
        self.Version = "Unknown"
        self.log = None
        self.IsStopping = False
        self.ProgramComplete = False

        if args.ConfigFile == None:
            self.ConfigFile = "/etc/operateGarage.conf"
        else:
            self.ConfigFile = args.ConfigFile

        self.console = SetupLogger("shutters_console",
                                   log_file="",
                                   stream=True)

        ## should be re-enabled before actual production use
        # if os.geteuid() != 0:
        #     self.LogConsole("You need to have root privileges to run this script.\nPlease try again, this time using 'sudo'.")
        #     sys.exit(1)

        if not os.path.isfile(self.ConfigFile):
            self.LogConsole("Creating new config file : " + self.ConfigFile)
            defaultConfigFile = os.path.dirname(
                os.path.realpath(__file__)) + '/defaultConfig.conf'
            print(defaultConfigFile)
            if not os.path.isfile(defaultConfigFile):
                self.LogConsole("Failure to create new config file: " +
                                defaultConfigFile)
                sys.exit(1)
            else:
                copyfile(defaultConfigFile, self.ConfigFile)

        # read config file
        self.config = MyConfig(filename=self.ConfigFile, log=self.console)
        result = self.config.LoadConfig()
        if not result:
            self.LogConsole("Failure to load configuration parameters")
            sys.exit(1)

        # log errors in this module to a file
        self.log = SetupLogger("shutters",
                               self.config.LogLocation + "operateGarage.log")
        self.config.log = self.log

        if self.IsLoaded():
            self.LogWarn("operateGarage.py is already loaded.")
            sys.exit(1)

        if not self.startPIGPIO():
            self.LogConsole("Not able to start PIGPIO")
            sys.exit(1)

        self.shutter = Shutter(log=self.log, config=self.config)

        # atexit.register(self.Close)
        # signal.signal(signal.SIGTERM, self.Close)
        # signal.signal(signal.SIGINT, self.Close)

        self.mqtt = MQTT(kwargs={
            'log': self.log,
            'shutter': self.shutter,
            'config': self.config
        })

        self.ProcessCommand(args)
Example #27
0
    addr = addrs[0]
    return addr['addr']

def sendEmail(conf, addr):
    server = smtplib.SMTP(conf['SMTP_SERVER'], conf['SMTP_PORT'])
    server.ehlo()
    server.starttls()
    server.login(conf['USERNAME'], conf['PASSD'])

    BODY = '\r\n'.join(['To: %s' % conf['TO'],
                       'From: %s' % conf['FROM'],
                       'Subject: %s' % conf['SUBJECT'],
                       '',
                       'The address of your Raspberry Pi on eth0 is %s' % addr])

    print(BODY)
    try:
        server.sendmail(conf['USERNAME'], conf['TO'], BODY)
        print('Email Sent')
    except:
        print('Error sending email')

    server.quit()

if __name__ == "__main__":
    sleep(10)
    conf = MyConfig()
    addr = getIP()
    print(addr)
    sendEmail(conf, addr)
Example #28
0
#!/usr/bin/python3
import os
import os.path
import sys
from subprocess import Popen, PIPE
from argparse import ArgumentParser
import utils
from myconfig import MyConfig

#Please `make -f Makefile.data prepare` first

config = MyConfig()

#change cwd to the libpinyin data directory
libpinyin_dir = config.getEvalsDir()
libpinyin_sub_dir = os.path.join(libpinyin_dir, 'data')
os.chdir(libpinyin_sub_dir)
#chdir done

datafiles = [config.getFinalModelFileName(), \
             config.getEvalsTextFileName(), \
             'deleted_bigram.db']


def checkData():
    #check data files
    for onefile in datafiles:
        if not os.access(onefile, os.F_OK):
            sys.exit('missing one data file:' + onefile)

Example #29
0
#!/usr/bin/python3
import os
import os.path
import sys
from subprocess import Popen, PIPE
from argparse import ArgumentParser
from myconfig import MyConfig
import utils


config = MyConfig()

#change cwd to the libpinyin data directory
libpinyin_dir = config.getToolsDir()
libpinyin_sub_dir = os.path.join(libpinyin_dir, 'data')
os.chdir(libpinyin_sub_dir)
#chdir done


def validateModel(modelfile):
    #begin processing
    cmdline = ['../utils/training/validate_k_mixture_model', \
                   modelfile]

    subprocess = Popen(cmdline, shell=False, close_fds=True)

    (pid, status) = os.waitpid(subprocess.pid, 0)
    if status != 0:
        sys.exit('Corrupted model found when validating:' + modelfile)
    #end processing