Exemplo n.º 1
0
 def __init__(self, ENVIRON, SENSORQ, MIC):
     self.ENVIRON = ENVIRON
     self.TOPDIR = ENVIRON["topdir"]
     #Lee AutoLevel - set initial value for background noise
     self.ENVIRON["avg_noise"] = 100
     filename = os.path.join(self.TOPDIR, "static/sqlite/robotAI.sqlite")
     #get the module configuration info
     if os.path.isfile(filename):
         config = getConfigData(self.TOPDIR, "Listen")
         if "ERROR" in config:
             print("ListenLoop: Error getting Config: " + config["ERROR"])
         else:
             debugFlag = getConfig(config, "Listen_2debug")
             self.hotword = getConfig(config, "Listen_hotword")
             self.sense_desc = getConfig(config, "Listen_sensitivity")
             self.sensitivty = getSensitivity(self.sense_desc)
     #Set debug level based on details in config DB
     self.logger = logging.getLogger(__name__)
     if debugFlag == 'TRUE':
         self.logger.level = logging.DEBUG
     else:
         self.logger.level = logging.INFO
     self.SENSORQ = SENSORQ
     self.mic = MIC
     #set variable for snowboy
     self.interrupted = False
Exemplo n.º 2
0
    def __init__(self, ENVIRON, SENSORQ, MIC):
        self.Mic = MIC
        self.ENVIRON = ENVIRON
        self.SENSORQ = SENSORQ
        self.TOPDIR = ENVIRON["topdir"]
        self.api_url = ENVIRON["api_url"]
        self.api_token = ENVIRON["api_token"]
        self.api_login = ENVIRON["api_login"]
        filename = os.path.join(self.TOPDIR, "static/sqlite/robotAI.sqlite")
        #get the module configuration info
        if os.path.isfile(filename):
            config = getConfigData(self.TOPDIR, "Timer")
            if "ERROR" in config:
                print("TimerLoop: Error getting Config: " + config["ERROR"])
                debugFlag = 'TRUE'
            else:
                debugFlag = getConfig(config, "Timer_2debug")
                ignoreMins = getConfig(config, "Timer_ignore")
                if ignoreMins is None or not isinstance(ignoreMins, int):
                    self.ignoreMins = 10
                else:
                    self.ignoreMins = ignoreMins

        #Set debug level based on details in config DB
        self.logger = logging.getLogger(__name__)
        logging.basicConfig()
        if debugFlag == 'TRUE':
            self.logger.level = logging.DEBUG
        else:
            self.logger.level = logging.INFO
        self.alertCache = {
        }  #list of alerts that we need to monitor for exipry
        self.expiryCache = {}  #list containing last run of expiry alerts
        self.curDate = datetime.date.today(
        )  #used to compare to now() to determine if day has changed
    def __init__(self, ENVIRON, SENSORQ, MIC):
        self.Mic = MIC
        self.ENVIRON = ENVIRON
        self.SENSORQ = SENSORQ
        self.TOPDIR = ENVIRON["topdir"]
        filename = os.path.join(self.TOPDIR, "static/sqlite/robotAI.sqlite")
        if os.path.isfile(filename):
            config = getConfigData(self.TOPDIR, "Motion")
            if "ERROR" in config:
                print ("MotionLoop: Error getting Config: " + config["ERROR"])
                debugFlag = 'TRUE'
            else:
                debugFlag = getConfig(config, "Motion_2debug")

        #Set debug level based on details in config DB
        self.logger = logging.getLogger(__name__)
        logging.basicConfig()
        if debugFlag=='TRUE':
            self.logger.level = logging.DEBUG
        else:
            self.logger.level = logging.INFO

        # setup variables for motion detection process
        #-------------------------------------------------
        self.detector = getConfig(config, "Motion_detectMethod")
        self.framesCheck = 10                           
        self.motionChat = getConfig(config, "Motion_motionChat")
        self.securitychat = getConfig(config, "Motion_securityChat")
        self.imagePath = os.path.join(self.TOPDIR, "static/images/")
        # try to get the integer values from config
        try:
            self.chatDelay = int(getConfig(config, "Motion_waitChat"))
            self.delay = int(getConfig(config, "Motion_waitDetect"))
            self.min_area = int(getConfig(config, "Motion_minarea"))
            self.detectPin = int(getConfig(config, "Motion_detectPin"))
        except:
            self.Mic.say("There is a problem with one of the configuration values, so I am using my defaults.")
            self.chatDelay = 0
            self.delay = 10
            self.min_area = 500
            self.detectPin = 0
            
        # variables required to pre-fetch the security chat JSON
        self.api_token = ENVIRON["api_token"]
        self.api_login = ENVIRON["api_login"]
        self.api_url = ENVIRON["api_url"]
        self.chatfile = os.path.join(self.TOPDIR, "static/securityChat.json")

        # set lastChat so it triggers a chat if motion detected after startup
        self.lastChat = datetime.datetime.today() - datetime.timedelta(minutes=self.chatDelay)
        # set non to blank as we handle that below using len(self.motionChat)
        if not self.motionChat:
            self.motionChat = ''
        self.logger.debug("Chat triggered by motion is %s" % self.motionChat)
        self.logger.debug("Minimum area for movement is %s" % self.min_area)
        self.logger.debug("Delay between detection events %s seconds" % self.delay)
        self.logger.debug("Delay between chat events %s minutes" % self.chatDelay)
        self.logger.debug("Path for saving images is %s" % self.imagePath)
def securityWarn(text, mic, ENVIRON, logger):
    # get variables required for sending the email
    TOPDIR = ENVIRON["topdir"]
    api_token = ENVIRON["api_token"]
    api_login = ENVIRON["api_login"]
    version = ENVIRON["version"]
    api_url = ENVIRON["api_url"]
    config = getConfigData(TOPDIR, "Motion")
    if "ERROR" in config or config == None:
        mic.say(
            "Sorry, I could not access the motion sensor configuration. I cannot complete the task"
        )
        return
    else:
        """ *******************************************************
        Sync the images folder to a cloud location for security
        - insert your own code into function synchFolder() below
        ****************************************************** """
        res = synchFolder(ENVIRON, logger)

        # send notification(s) on chosen channel(s)
        motion_email = config["Motion_notifyEmail"]
        motion_phone = config["Motion_notifyPhone"]
        motion_message = config["Motion_notifyText"]
        # try sending a text message via phone module (need to add logic to check if phone enabled)
        # maybe replace SMS via AWS with this method
        if len(motion_phone) > 0:
            folder = os.path.join(TOPDIR, 'static/python27/')
            stamp = time.strftime("%y%m%d%H%M%S")
            file = stamp + '.text'
            filepath = os.path.join(folder, file)
            f = open(filepath, "w+")
            f.write(motion_phone + ':' + motion_message)
            f.close()
        # if am email has been configured then send an email
        if len(motion_email) > 0:
            jsonpkg = {
                "subscriberID": api_login,
                "token": api_token,
                "version": version,
                "email": motion_email,
                "dtime": dtime
            }
            api_url = os.path.join(api_url, 'email')
            response = sendToRobotAPI('POST', api_url, jsonpkg, mic, logger,
                                      ENVIRON)
        # if a phone number has been configured then send an SMS
        '''
Exemplo n.º 5
0
 def __init__(self, text, mic, ENVIRON):
     self.Mic = mic
     self.Text = text
     self.api_token = ENVIRON["api_token"]
     self.api_login = ENVIRON["api_login"]
     self.api_url = ENVIRON["api_url"]
     TOPDIR = ENVIRON["topdir"]
     logLevel = ENVIRON["loglvl"]
     self.logger = logging.getLogger(__name__)
     self.logger.level = logLevel
     MyConfig = getConfigData(TOPDIR, "Weather")
     if "ERROR" in MyConfig or MyConfig == None:
         self.Mic.say("Sorry, I could not access the weather configuration data. I cannot complete the task")
         return
     else:
         self.weather_loc = MyConfig["Weather_location"]
         self.weather_fmt = MyConfig["Weather_format"]
         self.loc = self.weather_loc.split(",")
     self.ENVIRON = ENVIRON
    def __init__(self, ENVIRON, SENSORQ, MIC):
        self.Mic = MIC
        self.ENVIRON = ENVIRON
        TOPDIR = ENVIRON["topdir"]

        #get the module configuration info
        filename = os.path.join(TOPDIR, "static/sqlite/robotAI.sqlite")
        config = getConfigData(TOPDIR, "WebSocket")
        if "ERROR" in config:
            print("serverSocket: Error getting Config: " + config["ERROR"])
            debugFlag = 'TRUE'
        else:
            debugFlag = getConfig(config, "WebSocket_2debug")
            self.URL = getConfig(config, "WebSocket_socketurl")

        #Set debug level based on details in config DB
        self.logger = logging.getLogger(__name__)
        logging.basicConfig()
        if debugFlag == 'TRUE':
            self.logger.level = logging.DEBUG
        else:
            self.logger.level = logging.INFO
Exemplo n.º 7
0
# Get general configuration details and setup logging
#---------------------------------------------------------
logging.basicConfig()
logger = logging.getLogger("robotAI")
isConfig = False  #set to false before we check for file
face_url = "http://localhost:5000"  #set default in case no General config
TOPDIR = os.path.dirname(os.path.realpath(__file__))
filename = os.path.join(TOPDIR, "static/sqlite/robotAI.sqlite")
# If config DB does not exist then assume its the first time code has been run and get starter DB
if not os.path.isfile(filename):
    starterDB = os.path.join(TOPDIR, "static/sqlite/starterDB.sqlite")
    from shutil import copyfile
    copyfile(starterDB, filename)
# Still allow for the fact that starter DB might be missing
if os.path.isfile(filename):
    cfg_general = getConfigData(TOPDIR, "General")
    if "ERROR" in cfg_general:
        debugFlag = "TRUE"
        logger.warning("ERROR accessing config: " + cfg_general["ERROR"])
    else:
        isConfig = True
        face_url = getConfig(cfg_general, "General_def_face")
        debugFlag = getConfig(cfg_general, "General_debug")
else:
    debugFlag = "TRUE"
    logger.warning("CONFIG ERROR Could not find file " + filename)
    cfg_general = None

# added verbal announcement if debug else pause few seconds
if debugFlag == 'TRUE':
    logger.setLevel(level=logging.DEBUG)
Exemplo n.º 8
0
def eventHandle(text, mic, ENVIRON, handle=1):
    sl = text.split(":")
    id = sl[1]
    logger = logging.getLogger(__name__)

    #set default text to say if we dont find the event details in cache
    sText = "That is odd. I need to remind you about an event but I cannot find the text. Perhaps it was deleted."

    #Get config details for the timer module
    TOPDIR = ENVIRON["topdir"]
    filename = os.path.join(TOPDIR, "static/sqlite/robotAI.sqlite")
    if os.path.isfile(filename):
        # get timer module configuration information or use defaults
        config = getConfigData(TOPDIR, "Timer")
        if "ERROR" in config:
            logger.warning("Error getting Timer sensor config: " +
                           config["ERROR"])
            def_alarm = "doorDingDong.wav"
            debugFlag = 'TRUE'
        else:
            def_alarm = getConfig(config, "Timer_def_alarm")
            debugFlag = getConfig(config, "Timer_2debug")

    if debugFlag == 'TRUE':
        logger.level = logging.DEBUG

    # get api detalis from the environment
    api_token = ENVIRON["api_token"]
    api_login = ENVIRON["api_login"]
    api_url = ENVIRON["api_url"]
    api_url = os.path.join(api_url, 'event', id)
    logger.debug("Path to call Event API will be %s " % api_url)

    # if expiry only then do it and exit
    if handle == 0:
        logger.debug("Expired event, so we will just mark it off as expired ")
        updateEvent(api_login, api_token, api_url, mic, logger, ENVIRON)
        return

    alarm = os.path.join(TOPDIR, "static/audio", def_alarm)

    # fetch details of the alert from the daily file cache
    # NOTE THAT ORDER OF VALUES IN LIST RETURNED BY API MATTERS  ***********
    #===========================================================================
    filename = os.path.join(TOPDIR, "static/alerts.p")
    try:
        with open(filename, 'rb') as f:
            events = pickle.load(f)
            for event in events:
                #print event
                if str(event[0]) == str(id):
                    sText = event[5]
                    execute = event[6]
    except:
        sText == "That is odd. I need to remind you about an event but I was not able to find the details on file. "

    # Work out what we should be doing about this particular alert
    # --------------------------------------------------------------------------
    filename = os.path.join(TOPDIR, "client/modules/TimerLoopCustom.py")
    if execute == 'alert' or execute == None:
        # Todo Work out how to handle snoozing of alerts by the user
        mic.play(alarm)
        mic.say(sText)
    # set environment variable for security mode on
    elif execute == 'securityOn':
        logger.debug("Turning security camera mode on")
        ENVIRON["motion"] = True
        ENVIRON["security"] = True
    # set environment variable for security mode off
    elif execute == 'securityOff':
        logger.debug("Turning security camera mode off")
        ENVIRON["motion"] = False
        ENVIRON["security"] = False
    # if chat is selected then use the text as the chat item to fetch
    elif execute == 'chat':
        from ChatBot import chatBot
        bot = chatBot(sText, mic, ENVIRON)
        bot.doChat(sText)
    # if chat is selected then use the text as the chat item to fetch
    elif execute == 'command':
        ENVIRON["command"] = sText
    # check for file which the user can add custom functions into
    else:
        mic.say(
            "A calendar event expired but I am note sure how to handle it. You may need to update it online."
        )

    # Flag the event as expired using API
    updateEvent(api_login, api_token, api_url, mic, logger, ENVIRON)