Esempio n. 1
0
def main():
    """
    Delete the appropreate file in 'ramdisk_dir/events' and execute the
    appropreate script in 'event' if it exists.
    """

    event = int(sys.argv[1])
    kmotion_dir = os.getcwd()[:-5]

    try:
        mutex.acquire(kmotion_dir, 'core_rc')
        parser = configparser.ConfigParser()
        parser.read('./core_rc')
    finally:
        mutex.release(kmotion_dir, 'core_rc')

    ramdisk_dir = parser.get('dirs', 'ramdisk_dir')
    event_file = '%s/events/%s' % (ramdisk_dir, event)
    if os.path.isfile(event_file):
        os.remove(event_file)

    exe_file = '%s/event/event_end%02i.sh' % (kmotion_dir, event)
    if os.path.isfile(exe_file):
        logger.log('executing: %s' % exe_file, 'CRIT')
        os.popen3('nohup %s &' % exe_file)
Esempio n. 2
0
def main():
    """
    Delete the appropreate file in 'ramdisk_dir/events' and execute the
    appropreate script in 'event' if it exists.
    """

    event = int(sys.argv[1])
    kmotion_dir = os.getcwd()[:-5]
    
    try:
        mutex.acquire(kmotion_dir, 'core_rc')   
        parser = ConfigParser.SafeConfigParser()
        parser.read('./core_rc') 
    finally:
        mutex.release(kmotion_dir, 'core_rc')
        
    ramdisk_dir = parser.get('dirs', 'ramdisk_dir')
    event_file = '%s/events/%s' % (ramdisk_dir, event)
    if os.path.isfile(event_file):
        os.remove(event_file)
    
    exe_file = '%s/event/event_end%02i.sh' % (kmotion_dir, event)
    if os.path.isfile(exe_file):
        logger.log('executing: %s' % exe_file, 'CRIT')
        os.popen3('nohup %s &' % exe_file)
Esempio n. 3
0
def add_event(new_event):
    """ 
    Add an event to the beginning of the 'logs' file
    
    args    : new_event ... the string to add
    excepts : 
    return  : none
    """

    kmotion_dir = os.getcwd()[:-5]
    try:
        mutex.acquire(kmotion_dir, 'logs')
        f_obj = open('%s/www/logs' % kmotion_dir, 'r+')
        dblob = f_obj.read()
        events = dblob.split('$')
        if len(events) > 29:  # truncate logs
            events.pop()
        events = '$'.join(events)
        f_obj.seek(0)
        f_obj.write(new_event)
        f_obj.writelines(events)
        f_obj.truncate()  # adj to new file length
        f_obj.close()
    finally:
        mutex.release(kmotion_dir, 'logs')
Esempio n. 4
0
    def on_frame(self, controller):

        count = 50

        position = Leap.Vector()
        direction = Leap.Vector()
        velocity = Leap.Vector()

        for i in range(0, count - 1):
            hand = controller.frame(i).hands
            if hand[0].is_valid:
                position = position + hand[0].palm_position
                direction = direction + hand[0].direction
                velocity = velocity + hand[0].palm_velocity

        confidence = controller.frame().hands[0].confidence
        grab = controller.frame().hands[0].grab_strength

        position = position / count
        direction = direction / count
        velocity = velocity / count

        mutex.acquire()
        try:
            leap_context["velocity"] = velocity
            leap_context["position"] = position
            leap_context["direction"] = direction
            leap_context["box"] = controller.frame().interaction_box
            leap_context["confidence"] = confidence
            leap_context["grab"] = grab
        finally:
            mutex.release()
Esempio n. 5
0
def main():
    """
    Creates the appropreate file in 'ramdisk_dir/events' and execute the
    appropreate script in 'event' if it exists.
    """

    event = int(sys.argv[1])
    kmotion_dir = os.getcwd()[:-5]

    try:
        mutex.acquire(kmotion_dir, 'core_rc')
        parser = ConfigParser.SafeConfigParser()
        parser.read('./core_rc')
    finally:
        mutex.release(kmotion_dir, 'core_rc')

    ramdisk_dir = parser.get('dirs', 'ramdisk_dir')
    f_obj = open('%s/events/%s' % (ramdisk_dir, event), 'w')
    print >> f_obj, ''
    f_obj.close()

    exe_file = '%s/event/event_start%02i.sh' % (kmotion_dir, event)
    if os.path.isfile(exe_file):
        logger.log('executing: %s' % exe_file, 'CRIT')
        os.popen3('nohup %s &' % exe_file)
Esempio n. 6
0
    def on_frame(self, controller):

        count = 50

        position = Leap.Vector()
        direction = Leap.Vector()
        velocity = Leap.Vector()

        for i in range(0, count - 1):
            hand = controller.frame(i).hands
            if hand[0].is_valid:
                position = position + hand[0].palm_position
                direction = direction + hand[0].direction
                velocity = velocity + hand[0].palm_velocity

        confidence = controller.frame().hands[0].confidence
        grab = controller.frame().hands[0].grab_strength

        position = position / count
        direction = direction / count
        velocity = velocity / count

        mutex.acquire()
        try:
            leap_context["velocity"] = velocity
            leap_context["position"] = position
            leap_context["direction"] = direction
            leap_context["box"] = controller.frame().interaction_box
            leap_context["confidence"] = confidence
            leap_context["grab"] = grab
        finally:
            mutex.release()
Esempio n. 7
0
def add_event(new_event):
    """ 
    Add an event to the beginning of the 'logs' file
    
    args    : new_event ... the string to add
    excepts : 
    return  : none
    """
    
    kmotion_dir = os.getcwd()[:-5]
    try:
        mutex.acquire(kmotion_dir, 'logs')
        f_obj = open('%s/www/logs' % kmotion_dir, 'r+')
        dblob = f_obj.read()
        events = dblob.split('$')
        if len(events) > 500: # truncate logs
            events.pop()
        events = '$'.join(events)
        f_obj.seek(0)
        f_obj.write(new_event)
        f_obj.writelines(events)
        f_obj.truncate() # adj to new file length
        f_obj.close()
    finally:
        mutex.release(kmotion_dir, 'logs')
Esempio n. 8
0
def init_configs(kmotion_dir):
    """
    Init kmotion configs ready for deamon reloading.
    
    args    : 
    excepts : 
    return  : none
    """

    try:
        mutex.acquire(kmotion_dir, 'kmotion_rc')   
        parser = ConfigParser.SafeConfigParser()
        parser.read('../kmotion_rc') 
    finally:
        mutex.release(kmotion_dir, 'kmotion_rc')
        
    ramdisk_dir = parser.get('dirs', 'ramdisk_dir')
    
    try: # wrapping in a try - except because parsing data from kmotion_rc
        init_core.update_rcs(kmotion_dir, ramdisk_dir)
    except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
        print '\ncorrupt \'kmotion_rc\' : %s\n' % sys.exc_info()[1]
        sys.exit()
            
    try: # wrapping in a try - except because parsing data from kmotion_rc
        init_core.gen_vhost(kmotion_dir)
    except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
        print '\ncorrupt \'kmotion_rc\' : %s\n' % sys.exc_info()[1]
        sys.exit()
    
    # init the ramdisk dir
    init_core.init_ramdisk_dir(kmotion_dir)
    # init motion_conf directory with motion.conf, thread1.conf ...
    init_motion.gen_motion_configs(kmotion_dir)
Esempio n. 9
0
def init_configs(kmotion_dir):
    """
    Init kmotion configs ready for deamon reloading.
    
    args    : 
    excepts : 
    return  : none
    """

    try:
        mutex.acquire(kmotion_dir, 'core_rc')
        parser = ConfigParser.SafeConfigParser()
        parser.read('./core_rc')
    finally:
        mutex.release(kmotion_dir, 'core_rc')

    ramdisk_dir = parser.get('dirs', 'ramdisk_dir')

    try:  # wrapping in a try - except because parsing data from kmotion_rc
        init_core.update_rcs(kmotion_dir, ramdisk_dir)
    except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
        print '\ncorrupt \'kmotion_rc\' : %s\n' % sys.exc_info()[1]
        sys.exit()

    try:  # wrapping in a try - except because parsing data from kmotion_rc
        init_core.gen_vhost(kmotion_dir)
    except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
        print '\ncorrupt \'kmotion_rc\' : %s\n' % sys.exc_info()[1]
        sys.exit()

    # init the ramdisk dir
    init_core.init_ramdisk_dir(kmotion_dir)
    # init motion_conf directory with motion.conf, thread1.conf ...
    init_motion.gen_motion_configs(kmotion_dir)
Esempio n. 10
0
 def set_version(self, version):
     """        
     Sets the 'version_latest' in '../www/www_rc'
     
     args    : 
     excepts : 
     return  : str ... the version string
     """
     
     parser = self.mutex_www_parser_rd(self.kmotion_dir)
     parser.set('system', 'version_latest', version)
     self.mutex_www_parser_wr(self.kmotion_dir, parser)
     
     mutex.acquire(self.kmotion_dir, 'www_rc') 
     sort_rc.sort_rc('../www/www_rc')
     mutex.release(self.kmotion_dir, 'www_rc')
Esempio n. 11
0
def mutex_www_parser_wr(kmotion_dir, parser, www_rc):
    """
    Safely write a parser instance to 'www_rc' under mutex control.
    
    args    : kmotion_dir ... the 'root' directory of kmotion
              parser      ... the parser instance 
    excepts : 
    return  : 
    """
	
    try:
        mutex.acquire(kmotion_dir, 'www_rc')
        with open(www_rc, 'w') as f_obj:
	    parser.write(f_obj)
    finally:
        mutex.release(kmotion_dir, 'www_rc')
Esempio n. 12
0
    def set_version(self, version):
        """        
        Sets the 'version_latest' in '../www/www_rc'
        
        args    : 
        excepts : 
        return  : str ... the version string
        """

        parser = self.mutex_www_parser_rd(self.kmotion_dir)
        parser.set('system', 'version_latest', version)
        self.mutex_www_parser_wr(self.kmotion_dir, parser)

        mutex.acquire(self.kmotion_dir, 'www_rc')
        sort_rc.sort_rc('../www/www_rc')
        mutex.release(self.kmotion_dir, 'www_rc')
Esempio n. 13
0
    def mutex_core_parser_rd(self, kmotion_dir):
        """
        Safely generate a parser instance and under mutex control read 'core_rc'
        returning the parser instance.
        
        args    : kmotion_dir ... the 'root' directory of kmotion   
        excepts : 
        return  : parser ... a parser instance
        """

        parser = configparser.ConfigParser()
        try:
            mutex.acquire(kmotion_dir, 'core_rc')
            parser.read('%s/core/core_rc' % kmotion_dir)
        finally:
            mutex.release(kmotion_dir, 'core_rc')
        return parser
Esempio n. 14
0
def mutex_kmotion_parser_rd(kmotion_dir):
    """
    Safely generate a parser instance and under mutex control read 'kmotion_rc'
    returning the parser instance.
    
    args    : kmotion_dir ... the 'root' directory of kmotion   
    excepts : 
    return  : parser ... a parser instance
    """
    
    parser = ConfigParser.SafeConfigParser()
    try:
        mutex.acquire(kmotion_dir, 'kmotion_rc')
        parser.read('%s/kmotion_rc' % kmotion_dir)
    finally:
        mutex.release(kmotion_dir, 'kmotion_rc')
    return parser
Esempio n. 15
0
    def mutex_www_parser_wr(self, kmotion_dir, parser):
        """
        Safely write a parser instance to 'www_rc' under mutex control.
        
        args    : kmotion_dir ... the 'root' directory of kmotion
                  parser      ... the parser instance 
        excepts : 
        return  : 
        """

        try:
            mutex.acquire(kmotion_dir, 'www_rc')
            f_obj = open('%s/www/www_rc' % kmotion_dir, 'w')
            parser.write(f_obj)
            f_obj.close()
        finally:
            mutex.release(kmotion_dir, 'www_rc')
Esempio n. 16
0
def mutex_www_parser_wr(kmotion_dir, parser):
    """
    Safely write a parser instance to 'www_rc' under mutex control.
    
    args    : kmotion_dir ... the 'root' directory of kmotion
              parser      ... the parser instance 
    excepts : 
    return  : 
    """

    try:
        mutex.acquire(kmotion_dir, 'www_rc')
        f_obj = open('%s/www/www_rc' % kmotion_dir, 'w')
        parser.write(f_obj)
        f_obj.close()
    finally:
        mutex.release(kmotion_dir, 'www_rc')
Esempio n. 17
0
def read_config():
    """
    Read config from www_rc.

    args    :
    excepts : 
    return  : none
    """

    try:
        mutex.acquire(kmotion_dir, 'www_rc')   
        parser = ConfigParser.SafeConfigParser()
        parser.read('../www/www_rc') 
    finally:
        mutex.release(kmotion_dir, 'www_rc')
    
    for feed in range(1, 17):

        feed_enabled[feed] = parser.getboolean('motion_feed%02i' % feed, 'feed_enabled')
        feed_url[feed] = parser.get('motion_feed%02i' % feed, 'feed_url')
        feed_proxy[feed] = parser.get('motion_feed%02i' % feed, 'feed_proxy')
        feed_lgn_name[feed] = parser.get('motion_feed%02i' % feed, 'feed_lgn_name')
        feed_lgn_pw[feed] = parser.get('motion_feed%02i' % feed, 'feed_lgn_pw')
        
        ptz_enabled[feed] = parser.getboolean('motion_feed%02i' % feed, 'ptz_enabled')
        ptz_track_type[feed] = int(parser.get('motion_feed%02i' % feed, 'ptz_track_type'))
        ptz_park_enabled[feed] = parser.getboolean('motion_feed%02i' % feed, 'ptz_park_enabled')
        ptz_calib_first[feed] = parser.getboolean('motion_feed%02i' % feed, 'ptz_calib_first')
        ptz_park_delay[feed] = int(parser.get('motion_feed%02i' % feed, 'ptz_park_delay'))

        ptz_step[feed][X] = int(parser.get('motion_feed%02i' % feed, 'ptz_step_x'))
        ptz_step[feed][Y] = int(parser.get('motion_feed%02i' % feed, 'ptz_step_y'))
        ptz_park[feed][X] = int(parser.get('motion_feed%02i' % feed, 'ptz_park_x'))
        ptz_park[feed][Y] = int(parser.get('motion_feed%02i' % feed, 'ptz_park_y'))

        ptz_preset1[feed][X] = int(parser.get('motion_feed%02i' % feed, 'ptz_preset1_x'))
        ptz_preset1[feed][Y] = int(parser.get('motion_feed%02i' % feed, 'ptz_preset1_y'))
        ptz_preset2[feed][X] = int(parser.get('motion_feed%02i' % feed, 'ptz_preset2_x'))
        ptz_preset2[feed][Y] = int(parser.get('motion_feed%02i' % feed, 'ptz_preset2_y'))
        ptz_preset3[feed][X] = int(parser.get('motion_feed%02i' % feed, 'ptz_preset3_x'))
        ptz_preset3[feed][Y] = int(parser.get('motion_feed%02i' % feed, 'ptz_preset3_y'))
        ptz_preset4[feed][X] = int(parser.get('motion_feed%02i' % feed, 'ptz_preset4_x'))
        ptz_preset4[feed][Y] = int(parser.get('motion_feed%02i' % feed, 'ptz_preset4_y'))
Esempio n. 18
0
def load_rc():
    """
    Calculate kmotion dir and read core_rc  

    args    : 
    excepts : 
    return  : tuple ... (kmotion_dir, motion_reload_bug)
    """

    kmotion_dir = os.getcwd()[:-5]
    try:
        mutex.acquire(kmotion_dir, 'core_rc')
        parser = configparser.ConfigParser()
        parser.read('./core_rc')
    finally:
        mutex.release(kmotion_dir, 'core_rc')

    return (kmotion_dir, parser.get('workaround',
                                    'motion_reload_bug') == 'True')
Esempio n. 19
0
def load_rc():
    """
    Calculate kmotion dir and read kmotion_rc  

    args    : 
    excepts : 
    return  : tuple ... (kmotion_dir, motion_reload_bug)
    """
    
    kmotion_dir = os.getcwd()[:-5]
    try:
        mutex.acquire(kmotion_dir, 'kmotion_rc')   
        parser = ConfigParser.SafeConfigParser()
        parser.read('../kmotion_rc') 
    finally:
        mutex.release(kmotion_dir, 'kmotion_rc')
    
    return (kmotion_dir, 
            parser.getboolean('workaround', 'motion_reload_bug'))
Esempio n. 20
0
def update_rcs(kmotion_dir, ramdisk_dir):
    
    """
    Update the rc's during a 'kmotion' or 'kmotion reload'
    
    args    : kmotion_dir ... the 'root' directory of kmotion
              ramdisk_dir ... the 'root' directory of ramdisk
    excepts :
    return  : none
    """
    
    # copy 'images_dbase_dir' from 'kmotion_rc' to 'www_rc' 
    logger.log('update_rcs() - Copy \'images_dbase_dir\' from \'kmotion_rc\' to \'www_rc\'', 'DEBUG')
    parser = ConfigParser.SafeConfigParser()
    parser.read('%s/kmotion_rc' % kmotion_dir)
    images_dbase_dir = parser.get('dirs', 'images_dbase_dir')
    parser = mutex_www_parser_rd(kmotion_dir)
    parser.set('system', 'images_dbase_dir', images_dbase_dir)
    mutex_www_parser_wr(kmotion_dir, parser)
        
    # set 'ramdisk_dir' in core_rc
    logger.log('update_rcs() - Setting ramdisk_dir to \'%s\' in core_rc' % ramdisk_dir, 'DEBUG')
    parser = mutex_core_parser_rd(kmotion_dir)
    parser.set('dirs', 'ramdisk_dir', ramdisk_dir )
    mutex_core_parser_wr(kmotion_dir, parser)
    
    # set the 'ramdisk_dir' in 'www_rc'
    logger.log('update_rcs() - Setting ramdisk_dir to \'%s\' in www_rc' % ramdisk_dir, 'DEBUG')
    parser = mutex_www_parser_rd(kmotion_dir)
    parser.set('system', 'ramdisk_dir', ramdisk_dir)
    mutex_www_parser_wr(kmotion_dir, parser)
    
    # copy 'version' from 'core_rc' to 'www_rc' 
    logger.log('update_rcs() - Copy \'version\' from \'core_rc\' to \'www_rc\'', 'DEBUG')
    parser = mutex_core_parser_rd(kmotion_dir)
    version = parser.get('version', 'string')
    parser = mutex_www_parser_rd(kmotion_dir)
    parser.set('system', 'version', version)
    parser.set('system', 'version_latest', version)
    mutex_www_parser_wr(kmotion_dir, parser)
    
    # Sets the 'func_f??_enabled' in 'www_rc' by scanning for valid files in 
    # the 'func' directory. Valid files have the format 'func<01-16>.sh'.
    logger.log('update_rcs() - Setting the \'func_f??_enabled\' in \'www_rc\'', 'DEBUG')
    parser = mutex_www_parser_rd(kmotion_dir)
    for func_num in range(1, 17):
        if os.path.isfile('%s/func/func%02i.sh' % (kmotion_dir, func_num)):
            parser.set('system', 'func_f%02i_enabled' % func_num, 'true')
        else:
            parser.set('system', 'func_f%02i_enabled' % func_num, 'false')
    mutex_www_parser_wr(kmotion_dir, parser)
    
    # copy 'msg' to 'www_rc' 
    logger.log('update_rcs() - Copy \'msg\' to \'www_rc\'', 'DEBUG') 
    # user generated file so error trap
    try:
        f_obj = open('../msg')
        msg = f_obj.read()
        f_obj.close()
    except IOError:
        msg = ''
        logger.log('update_rcs() - unable to read \'msg\'', 'DEBUG') 
        
    msg = msg.replace('\n', '<br>') 
    parser = mutex_www_parser_rd(kmotion_dir)
    parser.set('system', 'msg', msg)
    mutex_www_parser_wr(kmotion_dir, parser)
    
    sort_rc.sort_rc('%s/kmotion_rc' % kmotion_dir)
    try:
        mutex.acquire(kmotion_dir, 'www_rc') 
        sort_rc.sort_rc('%s/www/www_rc' % kmotion_dir) 
    finally:
        mutex.release(kmotion_dir, 'www_rc')
        
    try:
        mutex.acquire(kmotion_dir, 'core_rc') 
        sort_rc.sort_rc('%s/core/core_rc' % kmotion_dir)
    finally:
        mutex.release(kmotion_dir, 'core_rc')
Esempio n. 21
0
def read_config():
    """
    Read config from www_rc.

    args    :
    excepts : 
    return  : none
    """

    try:
        mutex.acquire(kmotion_dir, 'www_rc')
        parser = ConfigParser.SafeConfigParser()
        parser.read('../www/www_rc')
    finally:
        mutex.release(kmotion_dir, 'www_rc')

    for feed in range(1, 17):

        feed_enabled[feed] = parser.get('motion_feed%02i' % feed,
                                        'feed_enabled') == 'true'
        feed_url[feed] = parser.get('motion_feed%02i' % feed, 'feed_url')
        feed_proxy[feed] = parser.get('motion_feed%02i' % feed, 'feed_proxy')
        feed_lgn_name[feed] = parser.get('motion_feed%02i' % feed,
                                         'feed_lgn_name')
        feed_lgn_pw[feed] = parser.get('motion_feed%02i' % feed, 'feed_lgn_pw')

        ptz_enabled[feed] = parser.get('motion_feed%02i' % feed,
                                       'ptz_enabled') == 'true'
        ptz_track_type[feed] = int(
            parser.get('motion_feed%02i' % feed, 'ptz_track_type'))
        ptz_park_enabled[feed] = parser.get('motion_feed%02i' % feed,
                                            'ptz_park_enabled') == 'true'
        ptz_calib_first[feed] = parser.get('motion_feed%02i' % feed,
                                           'ptz_calib_first') == 'true'
        ptz_park_delay[feed] = int(
            parser.get('motion_feed%02i' % feed, 'ptz_park_delay'))

        ptz_step[feed][X] = int(
            parser.get('motion_feed%02i' % feed, 'ptz_step_x'))
        ptz_step[feed][Y] = int(
            parser.get('motion_feed%02i' % feed, 'ptz_step_y'))
        ptz_park[feed][X] = int(
            parser.get('motion_feed%02i' % feed, 'ptz_park_x'))
        ptz_park[feed][Y] = int(
            parser.get('motion_feed%02i' % feed, 'ptz_park_y'))

        ptz_preset1[feed][X] = int(
            parser.get('motion_feed%02i' % feed, 'ptz_preset1_x'))
        ptz_preset1[feed][Y] = int(
            parser.get('motion_feed%02i' % feed, 'ptz_preset1_y'))
        ptz_preset2[feed][X] = int(
            parser.get('motion_feed%02i' % feed, 'ptz_preset2_x'))
        ptz_preset2[feed][Y] = int(
            parser.get('motion_feed%02i' % feed, 'ptz_preset2_y'))
        ptz_preset3[feed][X] = int(
            parser.get('motion_feed%02i' % feed, 'ptz_preset3_x'))
        ptz_preset3[feed][Y] = int(
            parser.get('motion_feed%02i' % feed, 'ptz_preset3_y'))
        ptz_preset4[feed][X] = int(
            parser.get('motion_feed%02i' % feed, 'ptz_preset4_x'))
        ptz_preset4[feed][Y] = int(
            parser.get('motion_feed%02i' % feed, 'ptz_preset4_y'))
Esempio n. 22
0
def add_startup_event():
    """ 
    Add a startup event to the 'logs' file. If the previous event was not a
    shutdown event insert an incorrect shutdown warning into the 'logs' file.
    
    Calculate the date and time of the incorrect shutdown by looking for 
    the last jpeg written.
    
    args    : 
    excepts : 
    return  : none
    """
    
    logger.log('add_startup_event() - adding startup event', 'DEBUG')
    kmotion_dir = os.getcwd()[:-5]
    
    # if last event did not include 'shutting down' text, either the first 
    # run or a power fail crashed the system
    try:
        mutex.acquire(kmotion_dir, 'logs')   
        
        log_file = '%s/www/logs' % kmotion_dir
        if not os.path.isfile(log_file):
            f_obj = open(log_file, 'w')
            f_obj.write(time.strftime('$%d/%m/%Y#%H:%M:%S#Initial kmotion startup'))
            f_obj.close()
        
        f_obj = open(log_file, 'r+')
        dblob = f_obj.read()
        f_obj.close()
    finally:
        mutex.release(kmotion_dir, 'logs')
        
    events = dblob.split('$')
    
    error_flag = False
    for i in range(len(events) - 1, -1, -1):
        
        if events[i].find('shutting down') == -1:
            error_flag = False
            break
        
        if events[i].find('Initial') == -1 or events[i].find('starting up') == -1:
            error_flag = True
            break
      
    if error_flag: 
            
        logger.log('add_startup_event() - missing \'shutting down\' event - Incorrect shutdown', 'DEBUG')
            
        # so first we need the ramdisk location
        try:
            mutex.acquire(kmotion_dir, 'kmotion_rc') 
            parser = ConfigParser.SafeConfigParser()
            parser.read('../kmotion_rc')
        finally:
            mutex.release(kmotion_dir, 'kmotion_rc')
        
	ramdisk_dir = parser.get('dirs', 'ramdisk_dir')
	max_feed = int(parser.get('misc', 'max_feed'))
        # so we can scan for the latest jpeg files to get the latest times
        latests = []
        for feed in range(1, max_feed):
            jpegs = os.listdir('%s/%02i' % (ramdisk_dir, feed))
            
            if len(jpegs) > 1: # ie we have some jpegs
                jpegs.sort()
                latests.append(jpegs[-2][:-4]) # skip 'latest_jpeg' file
            
        # get the latest filename, calculate its time and date and construct an 
        # event string
        latests.sort()
        if len(latests) > 0: # as long as a feed has run at some time !      
            latest = latests[-1]
            year =   latest[:4]
            month =  latest[4:6]
            day =    latest[6:8]
            hour =   latest[8:10]
            min_ =   latest[10:12]
            sec =    latest[12:]
            new_event = '$%s/%s/%s#%s:%s:%s#Incorrect shutdown / Mains failure' % (day, month, year, hour, min_, sec)
            add_event(new_event)
    
    # in all cases add a starting up message
    add_event(time.strftime('$%d/%m/%Y#%H:%M:%S#kmotion starting up'))
Esempio n. 23
0
def on_idle():

    global radius
    global radius_speed

    global alpha
    global alpha_speed

    global beta
    global beta_speed

    hand_position = None
    hand_direction = None
    hand_velocity = None
    box = None
    confidence = None
    grab = None

    mutex.acquire()
    try:
        if "position" in leap_context:
            hand_position = leap_context["position"]
        if "direction" in leap_context:
            hand_direction = leap_context["direction"]
        if "velocity" in leap_context:
            hand_velocity = leap_context["velocity"]
        if "box" in leap_context:
            box = leap_context["box"]
        if "confidence" in leap_context:
            confidence = leap_context["confidence"]
        if "grab" in leap_context:
            grab = leap_context["grab"]
    finally:
        mutex.release()

    camera_position = graphiti.get_attribute("og:space:camera:position")

    cam_pos = Leap.Vector()
    cam_pos.x = camera_position[0]
    cam_pos.y = camera_position[1]
    cam_pos.z = camera_position[2]

    alpha_acceleration = 0.0
    beta_acceleration = 0.0
    radius_acceleration = 0.0
    action = ""
    x_action = ""
    y_action = ""
    z_action = ""
    if not (hand_position is None or hand_direction is None or hand_velocity is None or box is None or confidence < 0.1):

        hand_position = box.normalize_point(hand_position)
        hand_velocity = box.normalize_point(hand_velocity)

        hand_pos = Leap.Vector()
        hand_pos.x = 2.0 * hand_position.z - 1.0
        hand_pos.y = -(2.0 * hand_position.y - 1.0)
        hand_pos.z = 2.0 * hand_position.x - 1.0

        if hand_pos.z > 0.0:
            z_action = "Right "
            z_sign = 1.0
        elif hand_pos.z < -0.0:
            z_action = "Left "
            z_sign = -1.0
        else:
            z_sign = 0.0

        if hand_pos.y > 0.0:
            y_action = "Down "
            y_sign = 1.0
        elif hand_pos.y < -0.0:
            y_sign = -1.0
            y_action = "Up "
        else:
            y_sign = 0.0

        if hand_pos.x > 0.0:
            x_action = " Back"
            x_sign = 1.0
        elif hand_pos.x < -0.0:
            x_action = " Front"
            x_sign = -1.0
        else:
            x_sign = 0.0

        threshold = 0.45
        if abs(hand_pos.z) >= threshold:
            action += z_action
            hand_pos.z = (1.0 / threshold) * (hand_pos.z - z_sign * threshold)
            alpha_acceleration = z_sign * (abs(hand_pos.z * hand_pos.z)) / 300

        threshold = 0.3
        if abs(hand_pos.y) >= threshold:
            action += y_action
            hand_pos.y = (1.0 / threshold) * (hand_pos.y - y_sign * threshold)
            beta_acceleration = -y_sign * 0.1

        if abs(hand_pos.x) >= threshold:
            action += x_action
            hand_pos.x = (1.0 / threshold) * (hand_pos.x - x_sign * threshold)
            radius_acceleration = x_sign *  0.1

        if len(action) == 0:
            action += "Neutral"

    if grab == 1.0:
        alpha_speed = 0.0
        beta_speed = 0.0
        radius_speed = 0.0
        alpha_acceleration = 0.0
        beta_acceleration = 0.0
        radius_acceleration = 0.0
        graphiti.set_attribute("og:space:title", "string", "Freeze")
        return

    alpha_speed += alpha_acceleration
    alpha += alpha_speed

    beta_speed += beta_acceleration
    beta += beta_speed 

    radius_speed += radius_acceleration
    radius += radius_speed

    max_beta = 100.0
    min_beta = - 100.0
    if beta > max_beta:
        beta = max_beta
    if beta < min_beta:
        beta = min_beta

    max_radius = 200
    min_radius = 10
    if radius > max_radius:
        radius = max_radius
    if radius < min_radius:
        radius = min_radius

    cam_pos.x = radius * math.cos(alpha)
    cam_pos.y = beta
    cam_pos.z = radius * math.sin(alpha)

    graphiti.set_attribute("og:space:camera:position", "vec3", "{0} {1} {2}".format(cam_pos.x, cam_pos.y, cam_pos.z))
    graphiti.set_attribute("og:space:title", "string", action)
    graphiti.set_attribute("og:space:camera:target", "vec3", "0.0 {0} 0.0".format(cam_pos.y))

    alpha_speed = alpha_speed * 0.8
    beta_speed = beta_speed * 0.8
    radius_speed = radius_speed * 0.8
Esempio n. 24
0
def add_startup_event():
    """ 
    Add a startup event to the 'logs' file. If the previous event was not a
    shutdown event insert an incorrect shutdown warning into the 'logs' file.
    
    Calculate the date and time of the incorrect shutdown by looking for 
    the last jpeg written.
    
    args    : 
    excepts : 
    return  : none
    """

    logger.log('add_startup_event() - adding startup event', 'DEBUG')
    kmotion_dir = os.getcwd()[:-5]

    # if last event did not include 'shutting down' text, either the first
    # run or a power fail crashed the system
    try:
        mutex.acquire(kmotion_dir, 'logs')

        log_file = '%s/www/logs' % kmotion_dir
        if not os.path.isfile(log_file):
            f_obj = open(log_file, 'w')
            f_obj.write(
                time.strftime('$%d/%m/%Y#%H:%M:%S#Initial kmotion startup'))
            f_obj.close()

        f_obj = open(log_file, 'r+')
        dblob = f_obj.read()
        f_obj.close()
    finally:
        mutex.release(kmotion_dir, 'logs')

    events = dblob.split('$')
    if len(events) > 1 and events[1].find('shutting') == -1 and events[1].find(
            'Initial') == -1 and events[1].find('Deleting') == -1:
        logger.log(
            'add_startup_event() - missing \'shutting down\' event - Incorrect shutdown',
            'DEBUG')
        # so first we need the ramdisk location

        try:
            mutex.acquire(kmotion_dir, 'core_rc')
            parser = configparser.ConfigParser()
            parser.read('../core/core_rc')
        finally:
            mutex.release(kmotion_dir, 'core_rc')

        ramdisk_dir = parser.get('dirs', 'ramdisk_dir')

        # so we can scan for the latest jpeg files to get the latest times
        latests = []
        for feed in range(1, 17):
            jpegs = os.listdir('%s/%02i' % (ramdisk_dir, feed))

            if len(jpegs) > 1:  # ie we have some jpegs
                jpegs.sort()
                latests.append(jpegs[-2][:-4])  # skip 'latest_jpeg' file

        # get the latest filename, calculate its time and date and construct an
        # event string
        latests.sort()
        if len(latests) > 0:  # as long as a feed has run at some time !
            latest = latests[-1]
            year = latest[:4]
            month = latest[4:6]
            day = latest[6:8]
            hour = latest[8:10]
            min_ = latest[10:12]
            sec = latest[12:]
            new_event = '$%s/%s/%s#%s:%s:%s#Incorrect shutdown / Mains failure' % (
                day, month, year, hour, min_, sec)
            add_event(new_event)

    # in all cases add a starting up message
    add_event(time.strftime('$%d/%m/%Y#%H:%M:%S#kmotion starting up'))
Esempio n. 25
0
def main():
    """
    Waits on the 'fifo_settings_wr' fifo until data received then parse the data
    and modifiy 'www_rc', also updates 'feeds_cache'
    
    ine ... interleave enabled
    fse ... full screen enabled
    lbe ... low bandwidth enabled
    lce ... low CPU enabled
    skf ... skip archive frames
    are ... archive button enabled
    lge ... logs button enabled
    coe ... config button enabled
    fue ... func button enabled
    spa ... msg button enabled
    abe ... about button enabled
    loe ... logout button enabled
    
    sec ... secure config
    coh ... config hash code
    
    fma ... feed mask
    
    fen ... feed enabled
    fpl ... feed pal 
    fde ... feed device
    fin ... feed input
    ful ... feed url
    fpr ... feed proxy
    fln ... feed loggin name
    flp ... feed loggin password
    fwd ... feed width
    fhe ... feed height
    fna ... feed name
    fbo ... feed show box
    ffp ... feed fps
    fpe ... feed snap enabled
    fsn ... feed snap interval
    ffe ... feed smovie enabled
    fme ... feed movie enabled
    fup ... feed updates
    
    psx ... PTZ step x
    psy ... PTZ step y
    ptt ... PTZ track type
    pte ... PTZ enabled
    ptc ... PTZ calib first
    pts ... PTZ servo settle
    ppe ... PTZ park enabled
    ppd ... PTZ park delay
    ppx ... PTZ park x
    ppy ... PTZ park y
    p1x ... PTZ preset 1 x
    p1y ... PTZ preset 1 y
    p2x ... PTZ preset 2 x
    p2y ... PTZ preset 2 y
    p3x ... PTZ preset 3 x
    p3y ... PTZ preset 3 y
    p4x ... PTZ preset 4 x
    p4y ... PTZ preset 4 y
    
    st1 ... schedule time line 1
    st2 ... schedule time line 2
    st3 ... schedule time line 3
    st4 ... schedule time line 4
    st5 ... schedule time line 5
    st6 ... schedule time line 6
    st7 ... schedule time line 7
    
    ed1 ... exception time line 1 dates   
    ed2 ... exception time line 2 dates      
    ed3 ... exception time line 3 dates    
    ed4 ... exception time line 4 dates
    ed5 ... exception time line 5 dates
    ed6 ... exception time line 6 dates
    ed7 ... exception time line 7 dates

    et1 ... exception time line 1    
    et2 ... exception time line 2       
    et3 ... exception time line 3    
    et4 ... exception time line 4
    et5 ... exception time line 5
    et6 ... exception time line 6
    et7 ... exception time line 7

    dif ... display feeds
    col ... color select
    dis ... display select
    
    chk ... length check
    
    args    : 
    excepts : 
    return  : none
    """

    logger.log('starting daemon ...', 'CRIT')
    kmotion_dir = os.getcwd()[:-5]

    reload_ptz_config = False
    reload_all_config = False

    RELOAD_PTZ = [
        'psx', 'psy', 'ptc', 'pts', 'ppe', 'ppd', 'ppx', 'ppy', 'p1x', 'p1y',
        'p2x', 'p2y', 'p3x', 'p3y', 'p4x', 'p4y'
    ]

    RELOAD_ALL = [
        'fma', 'fen', 'fpl', 'fde', 'fin', 'ful', 'fpr', 'fln', 'flp', 'fwd',
        'fhe', 'fbo', 'ffp', 'fpe', 'fsn', 'ffe', 'fme', 'fup', 'ptt', 'pte',
        'st1', 'st2', 'st3', 'st4', 'st5', 'st6', 'st7', 'ed1', 'ed2', 'ed3',
        'wd4', 'ed5', 'ed6', 'ed7', 'et1', 'et2', 'et3', 'et4', 'et5', 'et6',
        'et7'
    ]

    update_feeds_cache(kmotion_dir)

    while True:

        logger.log('waiting on FIFO pipe data', 'DEBUG')
        data = subprocess.Popen(
            ['cat', '%s/www/fifo_settings_wr' % kmotion_dir],
            stdout=subprocess.PIPE).communicate()[0]
        data = data.rstrip()
        logger.log('FIFO pipe data: %s' % data, 'DEBUG')

        if len(data) < 8:
            continue

        if len(data) > 7 and data[-8:] == '99999999':  # FIFO purge
            logger.log('FIFO purge', 'DEBUG')
            continue

        if int(data[-8:]) != len(data) - 13:  # filter checksum
            logger.log('data checksum error - rejecting data', 'CRIT')
            continue

        masks_modified = []  # reset masks changed list
        parser = mutex_www_parser_rd(kmotion_dir)
        for raw_data in data.split('$'):
            if raw_data == '': continue  # filter starting ''
            split_data = raw_data.split(':')

            if len(split_data[0]) > 3:
                key = split_data[0][:3]
                index = int(split_data[0][3:])
            else:
                key = split_data[0]  # the 3 digit key ie 'fen' or 'fha'
                index = 0  # optional list pointer for the id
            value = split_data[1]
            if key == 'ine':  # interleave
                parser.set('misc', 'misc1_interleave', num_bool(value))
            elif key == 'fse':  # full screen
                parser.set('misc', 'misc1_full_screen', num_bool(value))
            elif key == 'lbe':  # low bandwidth
                parser.set('misc', 'misc1_low_bandwidth', num_bool(value))
            elif key == 'lce':  # low cpu
                parser.set('misc', 'misc1_low_cpu', num_bool(value))
            elif key == 'skf':  # skip archive frames enabled
                parser.set('misc', 'misc1_skip_frames', num_bool(value))
            elif key == 'are':  # archive button enabled
                parser.set('misc', 'misc2_archive_button_enabled',
                           num_bool(value))
            elif key == 'lge':  # logs button enabled
                parser.set('misc', 'misc2_logs_button_enabled',
                           num_bool(value))
            elif key == 'coe':  # config button enabled
                parser.set('misc', 'misc2_config_button_enabled',
                           num_bool(value))
            elif key == 'fue':  # function button enabled
                parser.set('misc', 'misc2_func_button_enabled',
                           num_bool(value))
            elif key == 'spa':  # update button enabled
                parser.set('misc', 'misc2_msg_button_enabled', num_bool(value))
            elif key == 'abe':  # about button enabled
                parser.set('misc', 'misc2_about_button_enabled',
                           num_bool(value))
            elif key == 'loe':  # logout button enabled
                parser.set('misc', 'misc2_logout_button_enabled',
                           num_bool(value))

            elif key == 'sec':  # secure config
                parser.set('misc', 'misc3_secure', num_bool(value))
            elif key == 'coh':  # config hash
                parser.set('misc', 'misc3_config_hash', value)

            elif key == 'fma':  # feed mask
                parser.set('motion_feed%02i' % index, 'feed_mask', value)
                masks_modified.append((index, value))

            elif key == 'fen':  # feed enabled
                parser.set('motion_feed%02i' % index, 'feed_enabled',
                           num_bool(value))
            elif key == 'fpl':  # feed pal
                parser.set('motion_feed%02i' % index, 'feed_pal',
                           num_bool(value))
            elif key == 'fde':  # feed device
                parser.set('motion_feed%02i' % index, 'feed_device', value)
            elif key == 'fin':  # feed input
                parser.set('motion_feed%02i' % index, 'feed_input', value)
            elif key == 'ful':  # feed url
                parser.set('motion_feed%02i' % index, 'feed_url',
                           de_sanitise(value))
            elif key == 'fpr':  # feed proxy
                parser.set('motion_feed%02i' % index, 'feed_proxy',
                           de_sanitise(value))
            elif key == 'fln':  # feed loggin name
                parser.set('motion_feed%02i' % index, 'feed_lgn_name',
                           de_sanitise(value))
            elif key == 'flp':  # feed loggin password
                # check to see if default *'d password is returned
                if de_sanitise(value) != '*' * len(
                        parser.get('motion_feed%02i' % index, 'feed_lgn_pw')):
                    parser.set('motion_feed%02i' % index, 'feed_lgn_pw',
                               de_sanitise(value))
            elif key == 'fwd':  # feed width
                parser.set('motion_feed%02i' % index, 'feed_width', value)
            elif key == 'fhe':  # feed height
                parser.set('motion_feed%02i' % index, 'feed_height', value)
            elif key == 'fna':  # feed name
                parser.set('motion_feed%02i' % index, 'feed_name',
                           de_sanitise(value))
            elif key == 'fbo':  # feed show box
                parser.set('motion_feed%02i' % index, 'feed_show_box',
                           num_bool(value))
            elif key == 'ffp':  # feed fps
                parser.set('motion_feed%02i' % index, 'feed_fps', value)
            elif key == 'fpe':  # feed snap enabled
                parser.set('motion_feed%02i' % index, 'feed_snap_enabled',
                           num_bool(value))
            elif key == 'fsn':  # feed snap interval
                parser.set('motion_feed%02i' % index, 'feed_snap_interval',
                           value)
            elif key == 'ffe':  # feed smovie enabled
                parser.set('motion_feed%02i' % index, 'feed_smovie_enabled',
                           num_bool(value))
            elif key == 'fme':  # feed movie enabled
                parser.set('motion_feed%02i' % index, 'feed_movie_enabled',
                           num_bool(value))

            elif key == 'psx':  # ptz step x
                parser.set('motion_feed%02i' % index, 'ptz_step_x', value)
            elif key == 'psy':  # ptz step y
                parser.set('motion_feed%02i' % index, 'ptz_step_y', value)
            elif key == 'ptt':  # ptz calib first
                parser.set('motion_feed%02i' % index, 'ptz_track_type', value)

            elif key == 'pte':  # ptz enabled
                parser.set('motion_feed%02i' % index, 'ptz_enabled',
                           num_bool(value))
            elif key == 'ptc':  # ptz calib first
                parser.set('motion_feed%02i' % index, 'ptz_calib_first',
                           num_bool(value))
            elif key == 'pts':  # ptz servo settle
                parser.set('motion_feed%02i' % index, 'ptz_servo_settle',
                           value)
            elif key == 'ppe':  # ptz park enable
                parser.set('motion_feed%02i' % index, 'ptz_park_enabled',
                           num_bool(value))
            elif key == 'ppd':  # ptz park delay
                parser.set('motion_feed%02i' % index, 'ptz_park_delay', value)
            elif key == 'ppx':  # ptz park x
                parser.set('motion_feed%02i' % index, 'ptz_park_x', value)
            elif key == 'ppy':  # ptz park y
                parser.set('motion_feed%02i' % index, 'ptz_park_y', value)
            elif key == 'p1x':  # ptz preset 1 x
                parser.set('motion_feed%02i' % index, 'ptz_preset1_x', value)
            elif key == 'p1y':  # ptz preset 1 y
                parser.set('motion_feed%02i' % index, 'ptz_preset1_y', value)
            elif key == 'p2x':  # ptz preset 2 x
                parser.set('motion_feed%02i' % index, 'ptz_preset2_x', value)
            elif key == 'p2y':  # ptz preset 2 y
                parser.set('motion_feed%02i' % index, 'ptz_preset2_y', value)
            elif key == 'p3x':  # ptz preset 3 x
                parser.set('motion_feed%02i' % index, 'ptz_preset3_x', value)
            elif key == 'p3y':  # ptz preset 3 y
                parser.set('motion_feed%02i' % index, 'ptz_preset3_y', value)
            elif key == 'p4x':  # ptz preset 4 x
                parser.set('motion_feed%02i' % index, 'ptz_preset4_x', value)
            elif key == 'p4y':  # ptz preset 4 y
                parser.set('motion_feed%02i' % index, 'ptz_preset4_y', value)

            elif key == 'st1':  # schedule time line 1
                parser.set('schedule%i' % index, 'tline1', value)
            elif key == 'st2':  # schedule time line 2
                parser.set('schedule%i' % index, 'tline2', value)
            elif key == 'st3':  # schedule time line 3
                parser.set('schedule%i' % index, 'tline3', value)
            elif key == 'st4':  # schedule time line 4
                parser.set('schedule%i' % index, 'tline4', value)
            elif key == 'st5':  # schedule time line 5
                parser.set('schedule%i' % index, 'tline5', value)
            elif key == 'st6':  # schedule time line 6
                parser.set('schedule%i' % index, 'tline6', value)
            elif key == 'st7':  # schedule time line 7
                parser.set('schedule%i' % index, 'tline7', value)

            elif key == 'ed1':  # exception time line 1 dates
                parser.set('schedule_except%i' % index, 'tline1_dates', value)
            elif key == 'ed2':  # exception time line 2 dates
                parser.set('schedule_except%i' % index, 'tline2_dates', value)
            elif key == 'ed3':  # exception time line 3 dates
                parser.set('schedule_except%i' % index, 'tline3_dates', value)
            elif key == 'ed4':  # exception time line 4 dates
                parser.set('schedule_except%i' % index, 'tline4_dates', value)
            elif key == 'ed5':  # exception time line 5 dates
                parser.set('schedule_except%i' % index, 'tline5_dates', value)
            elif key == 'ed6':  # exception time line 6 dates
                parser.set('schedule_except%i' % index, 'tline6_dates', value)
            elif key == 'ed7':  # exception time line 7 dates
                parser.set('schedule_except%i' % index, 'tline7_dates', value)

            elif key == 'et1':  # exception time line 1
                parser.set('schedule_except%i' % index, 'tline1', value)
            elif key == 'et2':  # exception time line 2
                parser.set('schedule_except%i' % index, 'tline2', value)
            elif key == 'et3':  # exception time line 3
                parser.set('schedule_except%i' % index, 'tline3', value)
            elif key == 'et4':  # exception time line 4
                parser.set('schedule_except%i' % index, 'tline4', value)
            elif key == 'et5':  # exception time line 5
                parser.set('schedule_except%i' % index, 'tline5', value)
            elif key == 'et6':  # exception time line 6
                parser.set('schedule_except%i' % index, 'tline6', value)
            elif key == 'et7':  # exception time line 7
                parser.set('schedule_except%i' % index, 'tline7', value)

            elif key == 'dif':  # display feeds
                parser.set('misc', 'misc4_display_feeds_%02i' % index, value)
            elif key == 'col':  # color select
                parser.set('misc', 'misc4_color_select', value)
            elif key == 'dis':  # display select
                parser.set('misc', 'misc4_display_select', value)

            # if key fits flag for reload everything including the ptz daemon,
            # motion and everything else, slow and painfull
            if key in RELOAD_ALL: reload_all_config = True

            # if key fits flag for reload the ptz daemon only. the ptz daemon is
            # quick to reload and does not have the crashy pants of a motion
            # reload !
            if key in RELOAD_PTZ: reload_ptz_config = True

        mutex_www_parser_wr(kmotion_dir, parser)
        mutex.acquire(kmotion_dir, 'www_rc')
        sort_rc.sort_rc('%s/www/www_rc' % kmotion_dir)
        mutex.release(kmotion_dir, 'www_rc')
        update_feeds_cache(kmotion_dir)

        # has to be here, image width, height have to be written to 'www_rc'
        # before mask can be made
        for i in range(len(masks_modified)):
            create_mask(kmotion_dir, masks_modified[i][0],
                        masks_modified[i][1])

        if reload_all_config:
            init_motion.gen_motion_configs(kmotion_dir)
            daemon_whip.reload_all_configs()
            reload_all_config = False
            reload_ptz_config = False
            continue  # skip 'reload_ptz_config', already done

        if reload_ptz_config:
            daemon_whip.reload_ptz_config()
            reload_ptz_config = False
Esempio n. 26
0
def on_idle():

    global radius
    global radius_speed

    global alpha
    global alpha_speed

    global beta
    global beta_speed

    hand_position = None
    hand_direction = None
    hand_velocity = None
    box = None
    confidence = None
    grab = None

    mutex.acquire()
    try:
        if "position" in leap_context:
            hand_position = leap_context["position"]
        if "direction" in leap_context:
            hand_direction = leap_context["direction"]
        if "velocity" in leap_context:
            hand_velocity = leap_context["velocity"]
        if "box" in leap_context:
            box = leap_context["box"]
        if "confidence" in leap_context:
            confidence = leap_context["confidence"]
        if "grab" in leap_context:
            grab = leap_context["grab"]
    finally:
        mutex.release()

    camera_position = graphiti.get_attribute("og:space:camera:position")

    cam_pos = Leap.Vector()
    cam_pos.x = camera_position[0]
    cam_pos.y = camera_position[1]
    cam_pos.z = camera_position[2]

    alpha_acceleration = 0.0
    beta_acceleration = 0.0
    radius_acceleration = 0.0
    action = ""
    x_action = ""
    y_action = ""
    z_action = ""
    if not (hand_position is None or hand_direction is None
            or hand_velocity is None or box is None or confidence < 0.1):

        hand_position = box.normalize_point(hand_position)
        hand_velocity = box.normalize_point(hand_velocity)

        hand_pos = Leap.Vector()
        hand_pos.x = 2.0 * hand_position.z - 1.0
        hand_pos.y = -(2.0 * hand_position.y - 1.0)
        hand_pos.z = 2.0 * hand_position.x - 1.0

        if hand_pos.z > 0.0:
            z_action = "Right "
            z_sign = 1.0
        elif hand_pos.z < -0.0:
            z_action = "Left "
            z_sign = -1.0
        else:
            z_sign = 0.0

        if hand_pos.y > 0.0:
            y_action = "Down "
            y_sign = 1.0
        elif hand_pos.y < -0.0:
            y_sign = -1.0
            y_action = "Up "
        else:
            y_sign = 0.0

        if hand_pos.x > 0.0:
            x_action = " Back"
            x_sign = 1.0
        elif hand_pos.x < -0.0:
            x_action = " Front"
            x_sign = -1.0
        else:
            x_sign = 0.0

        threshold = 0.45
        if abs(hand_pos.z) >= threshold:
            action += z_action
            hand_pos.z = (1.0 / threshold) * (hand_pos.z - z_sign * threshold)
            alpha_acceleration = z_sign * (abs(hand_pos.z * hand_pos.z)) / 300

        threshold = 0.3
        if abs(hand_pos.y) >= threshold:
            action += y_action
            hand_pos.y = (1.0 / threshold) * (hand_pos.y - y_sign * threshold)
            beta_acceleration = -y_sign * 0.1

        if abs(hand_pos.x) >= threshold:
            action += x_action
            hand_pos.x = (1.0 / threshold) * (hand_pos.x - x_sign * threshold)
            radius_acceleration = x_sign * 0.1

        if len(action) == 0:
            action += "Neutral"

    if grab == 1.0:
        alpha_speed = 0.0
        beta_speed = 0.0
        radius_speed = 0.0
        alpha_acceleration = 0.0
        beta_acceleration = 0.0
        radius_acceleration = 0.0
        graphiti.set_attribute("og:space:title", "string", "Freeze")
        return

    alpha_speed += alpha_acceleration
    alpha += alpha_speed

    beta_speed += beta_acceleration
    beta += beta_speed

    radius_speed += radius_acceleration
    radius += radius_speed

    max_beta = 100.0
    min_beta = -100.0
    if beta > max_beta:
        beta = max_beta
    if beta < min_beta:
        beta = min_beta

    max_radius = 200
    min_radius = 10
    if radius > max_radius:
        radius = max_radius
    if radius < min_radius:
        radius = min_radius

    cam_pos.x = radius * math.cos(alpha)
    cam_pos.y = beta
    cam_pos.z = radius * math.sin(alpha)

    graphiti.set_attribute(
        "og:space:camera:position", "vec3",
        "{0} {1} {2}".format(cam_pos.x, cam_pos.y, cam_pos.z))
    graphiti.set_attribute("og:space:title", "string", action)
    graphiti.set_attribute("og:space:camera:target", "vec3",
                           "0.0 {0} 0.0".format(cam_pos.y))

    alpha_speed = alpha_speed * 0.8
    beta_speed = beta_speed * 0.8
    radius_speed = radius_speed * 0.8
Esempio n. 27
0
def main():  
    """
    Waits on the 'fifo_settings_wr' fifo until data received then parse the data
    and modifiy 'www_rc', also updates 'feeds_cache'
    
    ine ... interleave enabled
    fse ... full screen enabled
    lbe ... low bandwidth enabled
    lce ... low CPU enabled
    skf ... skip archive frames
    are ... archive button enabled
    lge ... logs button enabled
    coe ... config button enabled
    fue ... func button enabled
    spa ... msg button enabled
    abe ... about button enabled
    loe ... logout button enabled
    
    sec ... secure config
    coh ... config hash code
    
    fma ... feed mask
    
    fen ... feed enabled
    fpl ... feed pal 
    fde ... feed device
    fin ... feed input
    ful ... feed url
    fpr ... feed proxy
    fln ... feed loggin name
    flp ... feed loggin password
    fwd ... feed width
    fhe ... feed height
    fna ... feed name
    fbo ... feed show box
    ffp ... feed fps
    fpe ... feed snap enabled
    fsn ... feed snap interval
    ffe ... feed smovie enabled
    fme ... feed movie enabled
    fup ... feed updates
    
    psx ... PTZ step x
    psy ... PTZ step y
    ptt ... PTZ track type
    pte ... PTZ enabled
    ptc ... PTZ calib first
    pts ... PTZ servo settle
    ppe ... PTZ park enabled
    ppd ... PTZ park delay
    ppx ... PTZ park x
    ppy ... PTZ park y
    p1x ... PTZ preset 1 x
    p1y ... PTZ preset 1 y
    p2x ... PTZ preset 2 x
    p2y ... PTZ preset 2 y
    p3x ... PTZ preset 3 x
    p3y ... PTZ preset 3 y
    p4x ... PTZ preset 4 x
    p4y ... PTZ preset 4 y
    
    st1 ... schedule time line 1
    st2 ... schedule time line 2
    st3 ... schedule time line 3
    st4 ... schedule time line 4
    st5 ... schedule time line 5
    st6 ... schedule time line 6
    st7 ... schedule time line 7
    
    ed1 ... exception time line 1 dates   
    ed2 ... exception time line 2 dates      
    ed3 ... exception time line 3 dates    
    ed4 ... exception time line 4 dates
    ed5 ... exception time line 5 dates
    ed6 ... exception time line 6 dates
    ed7 ... exception time line 7 dates

    et1 ... exception time line 1    
    et2 ... exception time line 2       
    et3 ... exception time line 3    
    et4 ... exception time line 4
    et5 ... exception time line 5
    et6 ... exception time line 6
    et7 ... exception time line 7

    dif ... display feeds
    col ... color select
    dis ... display select
    
    chk ... length check
    
    args    : 
    excepts : 
    return  : none
    """
    
    logger.log('starting daemon ...', 'CRIT')
    kmotion_dir = os.getcwd()[:-5]
    
    reload_ptz_config = False
    reload_all_config = False
    
    RELOAD_PTZ =  ['psx', 'psy', 'ptc', 'pts', 'ppe', 'ppd', 'ppx', 'ppy',
                   'p1x', 'p1y', 'p2x', 'p2y', 'p3x', 'p3y', 'p4x', 'p4y']
    
    RELOAD_ALL =  ['fma', 'fen', 'fpl', 'fde', 'fin', 'ful', 'fpr', 'fln', 
                   'flp', 'fwd', 'fhe', 'fbo', 'ffp', 'fpe', 'fsn', 'ffe', 
                   'fme', 'fup', 'ptt', 'pte', 'st1', 'st2', 'st3',
                   'st4', 'st5', 'st6', 'st7', 'ed1', 'ed2', 'ed3', 'wd4',
                   'ed5', 'ed6', 'ed7', 'et1', 'et2', 'et3', 'et4', 'et5',
                   'et6', 'et7']
    
    update_feeds_cache(kmotion_dir)

    while True:
        
        logger.log('waiting on FIFO pipe data', 'DEBUG')
        data = subprocess.Popen(['cat', '%s/www/fifo_settings_wr' % kmotion_dir], stdout=subprocess.PIPE).communicate()[0]
        data = data.rstrip()
        logger.log('FIFO pipe data: %s' % data, 'DEBUG')
        
        if len(data) < 8:
            continue
        
        if len(data) > 7 and data[-8:] == '99999999': # FIFO purge
            logger.log('FIFO purge', 'DEBUG')
            continue

        if int(data[-8:]) != len(data) - 13: # filter checksum
            logger.log('data checksum error - rejecting data', 'CRIT')
            continue
        
        masks_modified = [] # reset masks changed list
        parser = mutex_www_parser_rd(kmotion_dir)
        for raw_data in data.split('$'):
            if raw_data == '': continue # filter starting ''
            split_data = raw_data.split(':')

            if len(split_data[0]) > 3:
                key = split_data[0][:3]
                index = int(split_data[0][3:])
            else:
                key = split_data[0] # the 3 digit key ie 'fen' or 'fha'
                index = 0           # optional list pointer for the id
            value = split_data[1]
            if key == 'ine': # interleave
                parser.set('misc', 'misc1_interleave', num_bool(value))
            elif key == 'fse': # full screen
                parser.set('misc', 'misc1_full_screen', num_bool(value))
            elif key == 'lbe': # low bandwidth
                parser.set('misc', 'misc1_low_bandwidth', num_bool(value))
            elif key == 'lce': # low cpu
                parser.set('misc', 'misc1_low_cpu', num_bool(value))
            elif key == 'skf': # skip archive frames enabled
                parser.set('misc', 'misc1_skip_frames', num_bool(value))
            elif key == 'are': # archive button enabled
                parser.set('misc', 'misc2_archive_button_enabled', num_bool(value))
            elif key == 'lge': # logs button enabled
                parser.set('misc', 'misc2_logs_button_enabled', num_bool(value))
            elif key == 'coe': # config button enabled
                parser.set('misc', 'misc2_config_button_enabled', num_bool(value))
            elif key == 'fue': # function button enabled
                parser.set('misc', 'misc2_func_button_enabled', num_bool(value))
            elif key == 'spa': # update button enabled
                parser.set('misc', 'misc2_msg_button_enabled', num_bool(value))
            elif key == 'abe': # about button enabled
                parser.set('misc', 'misc2_about_button_enabled', num_bool(value))
            elif key == 'loe': # logout button enabled
                parser.set('misc', 'misc2_logout_button_enabled', num_bool(value))

            elif key == 'sec': # secure config
                parser.set('misc', 'misc3_secure', num_bool(value))
            elif key == 'coh': # config hash
                parser.set('misc', 'misc3_config_hash', value)
        
            elif key == 'fma': # feed mask
                parser.set('motion_feed%02i' % index, 'feed_mask', value)
                masks_modified.append((index, value))
        
            elif key == 'fen': # feed enabled
                parser.set('motion_feed%02i' % index, 'feed_enabled', num_bool(value))
            elif key == 'fpl': # feed pal 
                parser.set('motion_feed%02i' % index, 'feed_pal', num_bool(value))
            elif key == 'fde': # feed device
                parser.set('motion_feed%02i' % index, 'feed_device', value)
            elif key == 'fin': # feed input
                parser.set('motion_feed%02i' % index, 'feed_input', value)
            elif key == 'ful': # feed url
                parser.set('motion_feed%02i' % index, 'feed_url', de_sanitise(value))
            elif key == 'fpr': # feed proxy
                parser.set('motion_feed%02i' % index, 'feed_proxy', de_sanitise(value))
            elif key == 'fln': # feed loggin name
                parser.set('motion_feed%02i' % index, 'feed_lgn_name', de_sanitise(value))
            elif key == 'flp': # feed loggin password
                # check to see if default *'d password is returned
                if de_sanitise(value) != '*' * len(parser.get('motion_feed%02i' % index, 'feed_lgn_pw')):
                    parser.set('motion_feed%02i' % index, 'feed_lgn_pw', de_sanitise(value))
            elif key == 'fwd': # feed width
                parser.set('motion_feed%02i' % index, 'feed_width', value)
            elif key == 'fhe': # feed height
                parser.set('motion_feed%02i' % index, 'feed_height', value)
            elif key == 'fna': # feed name
                parser.set('motion_feed%02i' % index, 'feed_name', de_sanitise(value))
            elif key == 'fbo': # feed show box
                parser.set('motion_feed%02i' % index, 'feed_show_box', num_bool(value))
            elif key == 'ffp': # feed fps
                parser.set('motion_feed%02i' % index, 'feed_fps', value)
            elif key == 'fpe': # feed snap enabled
                parser.set('motion_feed%02i' % index, 'feed_snap_enabled', num_bool(value))
            elif key == 'fsn': # feed snap interval
                parser.set('motion_feed%02i' % index, 'feed_snap_interval', value)
            elif key == 'ffe': # feed smovie enabled
                parser.set('motion_feed%02i' % index, 'feed_smovie_enabled', num_bool(value))
            elif key == 'fme': # feed movie enabled
                parser.set('motion_feed%02i' % index, 'feed_movie_enabled', num_bool(value))
                
            elif key == 'psx': # ptz step x
                parser.set('motion_feed%02i' % index, 'ptz_step_x', value)                
            elif key == 'psy': # ptz step y
                parser.set('motion_feed%02i' % index, 'ptz_step_y', value)
            elif key == 'ptt': # ptz calib first
                parser.set('motion_feed%02i' % index, 'ptz_track_type', value)
        
            elif key == 'pte': # ptz enabled
                parser.set('motion_feed%02i' % index, 'ptz_enabled', num_bool(value))
            elif key == 'ptc': # ptz calib first
                parser.set('motion_feed%02i' % index, 'ptz_calib_first', num_bool(value))
            elif key == 'pts': # ptz servo settle
                parser.set('motion_feed%02i' % index, 'ptz_servo_settle', value)
            elif key == 'ppe': # ptz park enable
                parser.set('motion_feed%02i' % index, 'ptz_park_enabled', num_bool(value))
            elif key == 'ppd': # ptz park delay
                parser.set('motion_feed%02i' % index, 'ptz_park_delay', value)
            elif key == 'ppx': # ptz park x
                parser.set('motion_feed%02i' % index, 'ptz_park_x', value)
            elif key == 'ppy': # ptz park y
                parser.set('motion_feed%02i' % index, 'ptz_park_y', value)
            elif key == 'p1x': # ptz preset 1 x
                parser.set('motion_feed%02i' % index, 'ptz_preset1_x', value)                
            elif key == 'p1y': # ptz preset 1 y
                parser.set('motion_feed%02i' % index, 'ptz_preset1_y', value)
            elif key == 'p2x': # ptz preset 2 x
                parser.set('motion_feed%02i' % index, 'ptz_preset2_x', value)                
            elif key == 'p2y': # ptz preset 2 y
                parser.set('motion_feed%02i' % index, 'ptz_preset2_y', value)
            elif key == 'p3x': # ptz preset 3 x
                parser.set('motion_feed%02i' % index, 'ptz_preset3_x', value)                
            elif key == 'p3y': # ptz preset 3 y
                parser.set('motion_feed%02i' % index, 'ptz_preset3_y', value)
            elif key == 'p4x': # ptz preset 4 x
                parser.set('motion_feed%02i' % index, 'ptz_preset4_x', value)                
            elif key == 'p4y': # ptz preset 4 y
                parser.set('motion_feed%02i' % index, 'ptz_preset4_y', value)
        
            elif key == 'st1': # schedule time line 1
                parser.set('schedule%i' % index, 'tline1', value)
            elif key == 'st2': # schedule time line 2
                parser.set('schedule%i' % index, 'tline2', value)
            elif key == 'st3': # schedule time line 3
                parser.set('schedule%i' % index, 'tline3', value)
            elif key == 'st4': # schedule time line 4
                parser.set('schedule%i' % index, 'tline4', value)
            elif key == 'st5': # schedule time line 5
                parser.set('schedule%i' % index, 'tline5', value)
            elif key == 'st6': # schedule time line 6
                parser.set('schedule%i' % index, 'tline6', value)
            elif key == 'st7': # schedule time line 7
                parser.set('schedule%i' % index, 'tline7', value)
                
            elif key == 'ed1': # exception time line 1 dates
                parser.set('schedule_except%i' % index, 'tline1_dates', value)
            elif key == 'ed2': # exception time line 2 dates
                parser.set('schedule_except%i' % index, 'tline2_dates', value)
            elif key == 'ed3': # exception time line 3 dates
                parser.set('schedule_except%i' % index, 'tline3_dates', value)
            elif key == 'ed4': # exception time line 4 dates
                parser.set('schedule_except%i' % index, 'tline4_dates', value)
            elif key == 'ed5': # exception time line 5 dates
                parser.set('schedule_except%i' % index, 'tline5_dates', value)
            elif key == 'ed6': # exception time line 6 dates
                parser.set('schedule_except%i' % index, 'tline6_dates', value)
            elif key == 'ed7': # exception time line 7 dates
                parser.set('schedule_except%i' % index, 'tline7_dates', value)
                
            elif key == 'et1': # exception time line 1
                parser.set('schedule_except%i' % index, 'tline1', value)
            elif key == 'et2': # exception time line 2
                parser.set('schedule_except%i' % index, 'tline2', value)
            elif key == 'et3': # exception time line 3
                parser.set('schedule_except%i' % index, 'tline3', value)
            elif key == 'et4': # exception time line 4
                parser.set('schedule_except%i' % index, 'tline4', value)
            elif key == 'et5': # exception time line 5
                parser.set('schedule_except%i' % index, 'tline5', value)
            elif key == 'et6': # exception time line 6
                parser.set('schedule_except%i' % index, 'tline6', value)
            elif key == 'et7': # exception time line 7
                parser.set('schedule_except%i' % index, 'tline7', value)
                
            elif key == 'dif': # display feeds
                parser.set('misc', 'misc4_display_feeds_%02i' % index, value)
            elif key == 'col': # color select
                parser.set('misc', 'misc4_color_select', value)
            elif key == 'dis': # display select
                parser.set('misc', 'misc4_display_select', value)
                
            # if key fits flag for reload everything including the ptz daemon, 
            # motion and everything else, slow and painfull
            if key in RELOAD_ALL : reload_all_config = True
            
            # if key fits flag for reload the ptz daemon only. the ptz daemon is
            # quick to reload and does not have the crashy pants of a motion 
            # reload !
            if key in RELOAD_PTZ : reload_ptz_config = True
            
        mutex_www_parser_wr(kmotion_dir, parser)
        mutex.acquire(kmotion_dir, 'www_rc')
        sort_rc.sort_rc('%s/www/www_rc' % kmotion_dir)
        mutex.release(kmotion_dir, 'www_rc')
        update_feeds_cache(kmotion_dir)
        
        # has to be here, image width, height have to be written to 'www_rc'
        # before mask can be made
        for i in range(len(masks_modified)):
            create_mask(kmotion_dir, masks_modified[i][0], masks_modified[i][1])
        
        if reload_all_config: 
            init_motion.gen_motion_configs(kmotion_dir)
            daemon_whip.reload_all_configs()
            reload_all_config = False
            reload_ptz_config = False
            continue # skip 'reload_ptz_config', already done
    
        if reload_ptz_config: 
            daemon_whip.reload_ptz_config()
            reload_ptz_config = False