Exemplo n.º 1
0
    def __init__(self, environment, data_path=None, parent=None):
        logging.debug(">>")
        self.environment = environment
        self.pytrainer_main = parent
        self.data_path = data_path
        self.xml_tree = None
        self.tmpdir = environment.temp_dir
        self.confdir = environment.conf_dir
        self.conffile = environment.conf_file
        self.gpxdir = environment.gpx_dir
        self.extensiondir = environment.extension_dir
        self.plugindir = environment.plugin_dir
        self.uc = UC()
        self.profilewindow = None

        environment.clear_temp_dir()

        #Profile Options and Defaults
        self.profile_options = {
            "prf_name": "default",
            "prf_gender": "",
            "prf_weight": "",
            "prf_height": "",
            "prf_age": "",
            "prf_ddbb": "sqlite",
            "prf_ddbbhost": "",
            "prf_ddbbname": "",
            "prf_ddbbuser": "",
            "prf_ddbbpass": "",
            "version": "0.0",
            "prf_us_system": "False",
            "prf_hrzones_karvonen": "False",
            "prf_maxhr": "",
            "prf_minhr": "",
            "auto_launch_file_selection": "False",
            "import_default_tab": "0",
            "default_viewer": "0",
            "window_size": "800, 640",
            "activitypool_size": "10",
        }

        #Parse pytrainer configuration file
        self.config_file = environment.conf_file
        self.configuration = self._parse_config_file(self.config_file)
        logging.debug("Configuration retrieved: " + str(self.configuration))
        #self.pytrainer_main.ddbb = DDBB(self, pytrainer_main=self.pytrainer_main)
        self.uc.set_us(self.prf_us_system)
        self._setZones()
        logging.debug("<<")
Exemplo n.º 2
0
    def __init__(self, filename=None, data_path=None):
        # Based in Django's approach -> http://code.djangoproject.com/svn/django/trunk/django/__init__.py
        self.version = __import__('pytrainer').get_version()
        #Process command line options
        self.startup_options = self.get_options()
        #Setup logging
        self.environment = Environment(platform.get_platform(),
                                       self.startup_options.conf_dir)
        self.environment.create_directories()
        self.set_logging(self.startup_options.log_level,
                         self.startup_options.log_type)
        logging.debug('>>')
        logging.debug("pytrainer version %s" % (self.version))
        self.data_path = data_path
        self.date = Date()
        self.ddbb = None
        # Checking profile
        logging.debug('Checking configuration and profile...')
        self.profile = Profile(self.environment, self.data_path, self)
        self.uc = UC()
        self.windowmain = None
        self.ddbb = DDBB(self.profile, self)
        logging.debug('connecting to DDBB')
        self.ddbb.connect()

        initialize_data(self.ddbb, self.environment.conf_dir)

        self._sport_service = SportService(self.ddbb)
        self.record = Record(self._sport_service, data_path, self)
        self.athlete = Athlete(data_path, self)
        self.stats = Stats(self._sport_service, self)
        pool_size = self.profile.getIntValue("pytraining",
                                             "activitypool_size",
                                             default=1)
        self.activitypool = ActivityPool(self, size=pool_size)
        #preparamos la ventana principal
        self.windowmain = Main(self._sport_service,
                               data_path,
                               self,
                               self.version,
                               gpxDir=self.profile.gpxdir)
        self.date = Date(self.windowmain.calendar)
        self.waypoint = Waypoint(data_path, self)
        self.extension = Extension(data_path, self)
        self.plugins = Plugins(data_path, self)
        self.importdata = Importdata(self._sport_service, data_path, self,
                                     self.profile)
        self.loadPlugins()
        self.loadExtensions()
        self.windowmain.setup()
        self.windowmain.on_calendar_selected(None)
        self.refreshMainSportList()
        self.windowmain.run()
        logging.debug('<<')
Exemplo n.º 3
0
    def __init__(self):
        logging.debug(">>")
        # The first two variables are singletons themselves, profile_options
        # doesn't change, only xml_tree needs to be protected by has_attr.
        self.environment = Environment()
        self.uc = UC()
        #Profile Options and Defaults
        self.profile_options = {
            "prf_name": "default",
            "prf_gender": "",
            "prf_weight": "",
            "prf_height": "",
            "prf_age": "",
            "prf_ddbb": "sqlite",
            "prf_ddbbhost": "",
            "prf_ddbbname": "",
            "prf_ddbbuser": "",
            "prf_ddbbpass": "",
            "version": "0.0",
            "prf_us_system": "False",
            "prf_hrzones_karvonen": "False",
            "prf_maxhr": "",
            "prf_minhr": "",
            "auto_launch_file_selection": "False",
            "import_default_tab": "0",
            "default_viewer": "0",
            "window_size": "800, 640",
            "activitypool_size": "10",
            "prf_startscreen": "current_day",
        }

        if not hasattr(self, 'xml_tree'):
            self.xml_tree = None
            #Parse pytrainer configuration file
            self.refreshConfiguration()

        logging.debug("<<")
Exemplo n.º 4
0
    def __init__(self, environment, data_path = None, parent = None):
        logging.debug(">>")
        self.environment = environment
        self.pytrainer_main = parent
        self.data_path = data_path
        self.xml_tree = None
        self.tmpdir = environment.temp_dir
        self.confdir = environment.conf_dir
        self.conffile = environment.conf_file
        self.gpxdir = environment.gpx_dir
        self.extensiondir = environment.extension_dir
        self.plugindir = environment.plugin_dir
        self.uc = UC()
        self.profilewindow = None
        
        environment.clear_temp_dir()

        #Profile Options and Defaults
        self.profile_options = {
            "prf_name":"default",
            "prf_gender":"",
            "prf_weight":"",
            "prf_height":"",
            "prf_age":"",
            "prf_ddbb":"sqlite",
            "prf_ddbbhost":"",
            "prf_ddbbname":"",
            "prf_ddbbuser":"",
            "prf_ddbbpass":"",
            "version":"0.0",
            "prf_us_system":"False",
            "prf_hrzones_karvonen":"False",
            "prf_maxhr":"",
            "prf_minhr":"",
            "auto_launch_file_selection":"False",
            "import_default_tab":"0",
            "default_viewer":"0",
            "window_size":"800, 640",
            "activitypool_size": "10",
            }

        #Parse pytrainer configuration file
        self.config_file = environment.conf_file
        self.configuration = self._parse_config_file(self.config_file)
        logging.debug("Configuration retrieved: "+str(self.configuration))
        #self.pytrainer_main.ddbb = DDBB(self, pytrainer_main=self.pytrainer_main)
        self.uc.set_us(self.prf_us_system)
        self._setZones()
        logging.debug("<<")
Exemplo n.º 5
0
class Profile(Singleton):
    def __init__(self):
        logging.debug(">>")
        # The first two variables are singletons themselves, profile_options
        # doesn't change, only xml_tree needs to be protected by has_attr.
        self.environment = Environment()
        self.uc = UC()
        #Profile Options and Defaults
        self.profile_options = {
            "prf_name": "default",
            "prf_gender": "",
            "prf_weight": "",
            "prf_height": "",
            "prf_age": "",
            "prf_ddbb": "sqlite",
            "prf_ddbbhost": "",
            "prf_ddbbname": "",
            "prf_ddbbuser": "",
            "prf_ddbbpass": "",
            "version": "0.0",
            "prf_us_system": "False",
            "prf_hrzones_karvonen": "False",
            "prf_maxhr": "",
            "prf_minhr": "",
            "auto_launch_file_selection": "False",
            "import_default_tab": "0",
            "default_viewer": "0",
            "window_size": "800, 640",
            "activitypool_size": "10",
            "prf_startscreen": "current_day",
        }

        if not hasattr(self, 'xml_tree'):
            self.xml_tree = None
            #Parse pytrainer configuration file
            self.refreshConfiguration()

        logging.debug("<<")

    @property
    def data_path(self):
        return self.environment.data_path

    @property
    def tmpdir(self):
        return self.environment.temp_dir

    @property
    def confdir(self):
        return self.environment.conf_dir

    @property
    def config_file(self):
        return self.environment.conf_file

    @property
    def gpxdir(self):
        return self.environment.gpx_dir

    @property
    def extensiondir(self):
        return self.environment.extension_dir

    @property
    def plugindir(self):
        return self.environment.plugin_dir

    @property
    def sqlalchemy_url(self):
        ddbb_type = self.getValue("pytraining", "prf_ddbb")
        ddbb_host = self.getValue("pytraining", "prf_ddbbhost")
        ddbb = self.getValue("pytraining", "prf_ddbbname")
        ddbb_user = self.getValue("pytraining", "prf_ddbbuser")
        ddbb_pass = self.getValue("pytraining", "prf_ddbbpass")
        if ddbb_type == "sqlite":
            return "sqlite:///%s/pytrainer.ddbb" % self.confdir
        else:
            return "{type}://{user}:{passwd}@{host}/{db}".format(
                type=ddbb_type,
                user=ddbb_user,
                passwd=ddbb_pass,
                host=ddbb_host,
                db=ddbb)

    def refreshConfiguration(self):
        logging.debug(">>")
        self.configuration = self._parse_config_file(self.config_file)
        logging.debug("Configuration retrieved: %s", str(self.configuration))
        self.uc.set_us(self.prf_us_system)
        self._setZones()
        logging.debug("<<")

    def _setZones(self):
        #maxhr = self.getValue("pytraining","prf_maxhr")
        #resthr = self.getValue("pytraining","prf_minhr")
        try:
            maxhr = int(self.getValue("pytraining", "prf_maxhr"))
        except Exception as e:
            logging.error("Failed when retrieving Max Heartrate value: %s" % e)
            logging.info("Setting Max Heartrate to default value: 190")
            maxhr = 190
        try:
            resthr = int(self.getValue("pytraining", "prf_minhr"))
        except Exception as e:
            logging.error("Failed when retrieving Min Heartrate value: %s" % e)
            logging.info("Setting Min Heartrate to default value: 65")
            resthr = 65
        self.maxhr = maxhr
        self.rethr = resthr

        if self.getValue("pytraining", "prf_hrzones_karvonen") == "True":
            #karvonen method
            targethr1 = ((maxhr - resthr) * 0.50) + resthr
            targethr2 = ((maxhr - resthr) * 0.60) + resthr
            targethr3 = ((maxhr - resthr) * 0.70) + resthr
            targethr4 = ((maxhr - resthr) * 0.80) + resthr
            targethr5 = ((maxhr - resthr) * 0.90) + resthr
            targethr6 = maxhr
        else:
            #not karvonen method
            targethr1 = maxhr * 0.50
            targethr2 = maxhr * 0.60
            targethr3 = maxhr * 0.70
            targethr4 = maxhr * 0.80
            targethr5 = maxhr * 0.90
            targethr6 = maxhr

        self.zone1 = (targethr1, targethr2, "#ffff99", _("Moderate activity"))
        self.zone2 = (targethr2, targethr3, "#ffcc00", _("Weight Control"))
        self.zone3 = (targethr3, targethr4, "#ff9900", _("Aerobic"))
        self.zone4 = (targethr4, targethr5, "#ff6600", _("Anaerobic"))
        self.zone5 = (targethr5, targethr6, "#ff0000", _("VO2 MAX"))

    def getMaxHR(self):
        return self.maxhr

    def getRestHR(self):
        return self.resthr

    def getZones(self):
        return self.zone5, self.zone4, self.zone3, self.zone2, self.zone1

    def _parse_config_file(self, config_file):
        '''
        Parse the xml configuration file and convert to a dict

        returns: dict with option as key
        '''
        if config_file is None:
            logging.error("Configuration file value not set")
            logging.error("Fatal error, exiting")
            exit(-3)
        elif not os.path.isfile(config_file):  #File not found
            logging.error("Configuration '%s' file does not exist" %
                          config_file)
            logging.info("No profile found. Creating default one")
            self.setProfile(self.profile_options)
        elif os.stat(config_file)[stat.ST_SIZE] == 0:  #File is empty
            logging.error("Configuration '%s' file is empty" % config_file)
            logging.info("Creating default profile")
            self.setProfile(self.profile_options)
        else:
            logging.debug("Attempting to parse content from %s", config_file)
            parser = etree.XMLParser(encoding='UTF8', recover=True)
            try:
                self.xml_tree = etree.parse(config_file, parser=parser)
            except Exception as e:
                logging.error("Error %s while parsing file %s. Exiting", e,
                              config_file)
                exit(-3)
        #Have a populated xml tree, get pytraining node (root) and convert it to a dict
        pytraining_tag = self.xml_tree.getroot()
        config = {}
        config_needs_update = False
        for key, default in self.profile_options.items():
            value = pytraining_tag.get(key)
            #If property is not found, set it to the default
            if value is None:
                config_needs_update = True
                value = default
            config[key] = value
        #Added a property, so update config
        if config_needs_update:
            self.setProfile(config)
        #Set shorthand var for units of measurement
        self.prf_us_system = True if config[
            "prf_us_system"] == "True" else False
        return config

    def getIntValue(self, tag, variable, default=0):
        ''' Function to return conf value as int
            returns
            -- default if cannot convert to int
            -- None if variable not found
        '''
        result = self.getValue(tag, variable)
        if result is None:
            return None
        try:
            result = int(result)
        except Exception as e:
            logging.debug(str(e))
            result = default
        return result

    def getValue(self, tag, variable):
        if tag != "pytraining":
            print "ERROR - pytraining is the only profile tag supported"
            return None
        elif not self.configuration.has_key(variable):
            return None
        return self.configuration[variable]

    def setValue(self, tag, variable, value, delay_write=False):
        logging.debug(">>")
        if tag != "pytraining":
            logging.error(
                "ERROR: pytraining is the only profile tag supported")
        logging.debug("Setting %s to %s" % (variable, value))
        if self.xml_tree is None:
            #new config file....
            self.xml_tree = etree.parse(
                StringIO(
                    '''<?xml version='1.0' encoding='UTF-8'?><pytraining />''')
            )
        self.xml_tree.getroot().set(variable, value.decode('utf-8'))
        if not delay_write:
            self.saveProfile()
        logging.debug("<<")

    def setProfile(self, list_options):
        logging.debug(">>")
        for option, value in list_options.items():
            logging.debug("Adding " + option + "|" + value)
            self.setValue("pytraining", option, value, delay_write=True)
        self.uc.set_us(list_options['prf_us_system'])
        logging.debug("<<")

    def saveProfile(self):
        logging.debug("Writting configuration...")
        self.xml_tree.write(self.config_file,
                            xml_declaration=True,
                            encoding='UTF-8')
Exemplo n.º 6
0
    def __init__(self, filename=None, data_path=None):
        # Based on Django's approach -> http://code.djangoproject.com/svn/django/trunk/django/__init__.py
        self.version = __import__('pytrainer').get_version()
        #Process command line options
        self.startup_options = self.get_options()
        #Setup logging
        self.environment = Environment(self.startup_options.conf_dir,
                                       data_path)
        self.environment.create_directories()
        self.environment.clear_temp_dir()
        self.set_logging(self.startup_options.log_level,
                         self.startup_options.log_type)
        logging.debug('>>')
        logging.info("pytrainer version %s" % (self.version))
        self.data_path = data_path

        # Checking profile
        logging.debug('Checking configuration and profile...')
        self.profile = Profile()
        # Write the default config to disk
        self.profile.saveProfile()
        self.uc = UC()
        self.profilewindow = None
        self.ddbb = DDBB(self.profile.sqlalchemy_url)
        logging.debug('connecting to DDBB')
        self.ddbb.connect()

        logging.info('Checking if some upgrade action is needed...')
        initialize_data(self.ddbb, self.environment.conf_dir)

        # Loading shared services
        logging.debug('Loading sport service...')
        self._sport_service = SportService(self.ddbb)
        logging.debug('Loading record service...')
        self.record = Record(self._sport_service, data_path, self)
        logging.debug('Loading athlete service...')
        self.athlete = Athlete(data_path, self)
        logging.debug('Loading stats service...')
        self.stats = Stats(self)
        logging.debug('Initializing activity pool...')
        pool_size = self.profile.getIntValue("pytraining",
                                             "activitypool_size",
                                             default=1)
        self.activitypool = ActivityService(self, size=pool_size)

        #Loading main window
        self.windowmain = None
        logging.debug('Loading main window...')
        self.windowmain = Main(self._sport_service,
                               data_path,
                               self,
                               self.version,
                               gpxDir=self.profile.gpxdir)

        # Select initial date depending on user's preference
        self.selectInitialDate()

        logging.debug('Loading waypoint service...')
        self.waypoint = WaypointService(data_path, self)
        logging.debug('Loading extension service...')
        self.extension = Extension(data_path, self)
        logging.debug('Loading plugins service...')
        self.plugins = Plugins(data_path, self)
        self.importdata = Importdata(self._sport_service, data_path, self,
                                     self.profile)
        logging.debug('Loading plugins...')
        self.loadPlugins()
        logging.debug('Loading extensions...')
        self.loadExtensions()
        logging.debug('Setting values for graphs, maps and waypoint editor...')
        self.windowmain.setup()
        self.windowmain.on_calendar_selected(None)
        logging.debug('Refreshing sport list... is this needed?')
        self.refreshMainSportList()
        logging.debug('Launching main window...')
        self.windowmain.run()
        logging.debug('<<')
Exemplo n.º 7
0
class Profile:
    def __init__(self, environment, data_path=None, parent=None):
        logging.debug(">>")
        self.environment = environment
        self.pytrainer_main = parent
        self.data_path = data_path
        self.xml_tree = None
        self.tmpdir = environment.temp_dir
        self.confdir = environment.conf_dir
        self.conffile = environment.conf_file
        self.gpxdir = environment.gpx_dir
        self.extensiondir = environment.extension_dir
        self.plugindir = environment.plugin_dir
        self.uc = UC()
        self.profilewindow = None

        environment.clear_temp_dir()

        #Profile Options and Defaults
        self.profile_options = {
            "prf_name": "default",
            "prf_gender": "",
            "prf_weight": "",
            "prf_height": "",
            "prf_age": "",
            "prf_ddbb": "sqlite",
            "prf_ddbbhost": "",
            "prf_ddbbname": "",
            "prf_ddbbuser": "",
            "prf_ddbbpass": "",
            "version": "0.0",
            "prf_us_system": "False",
            "prf_hrzones_karvonen": "False",
            "prf_maxhr": "",
            "prf_minhr": "",
            "auto_launch_file_selection": "False",
            "import_default_tab": "0",
            "default_viewer": "0",
            "window_size": "800, 640",
            "activitypool_size": "10",
        }

        #Parse pytrainer configuration file
        self.config_file = environment.conf_file
        self.configuration = self._parse_config_file(self.config_file)
        logging.debug("Configuration retrieved: " + str(self.configuration))
        #self.pytrainer_main.ddbb = DDBB(self, pytrainer_main=self.pytrainer_main)
        self.uc.set_us(self.prf_us_system)
        self._setZones()
        logging.debug("<<")

    def _setZones(self):
        #maxhr = self.getValue("pytraining","prf_maxhr")
        #resthr = self.getValue("pytraining","prf_minhr")
        try:
            maxhr = int(self.getValue("pytraining", "prf_maxhr"))
        except Exception as e:
            logging.error("Failed when retrieving Max Heartrate value: %s" % e)
            logging.info("Setting Max Heartrate to default value: 190")
            maxhr = 190
        try:
            resthr = int(self.getValue("pytraining", "prf_minhr"))
        except Exception as e:
            logging.error("Failed when retrieving Min Heartrate value: %s" % e)
            logging.info("Setting Min Heartrate to default value: 65")
            resthr = 65
        self.maxhr = maxhr
        self.rethr = resthr

        if self.getValue("pytraining", "prf_hrzones_karvonen") == "True":
            #karvonen method
            targethr1 = ((maxhr - resthr) * 0.50) + resthr
            targethr2 = ((maxhr - resthr) * 0.60) + resthr
            targethr3 = ((maxhr - resthr) * 0.70) + resthr
            targethr4 = ((maxhr - resthr) * 0.80) + resthr
            targethr5 = ((maxhr - resthr) * 0.90) + resthr
            targethr6 = maxhr
        else:
            #not karvonen method
            targethr1 = maxhr * 0.50
            targethr2 = maxhr * 0.60
            targethr3 = maxhr * 0.70
            targethr4 = maxhr * 0.80
            targethr5 = maxhr * 0.90
            targethr6 = maxhr

        self.zone1 = (targethr1, targethr2, "#ffff99", _("Moderate activity"))
        self.zone2 = (targethr2, targethr3, "#ffcc00", _("Weight Control"))
        self.zone3 = (targethr3, targethr4, "#ff9900", _("Aerobic"))
        self.zone4 = (targethr4, targethr5, "#ff6600", _("Anaerobic"))
        self.zone5 = (targethr5, targethr6, "#ff0000", _("VO2 MAX"))

    def getMaxHR(self):
        return self.maxhr

    def getRestHR(self):
        return self.resthr

    def getZones(self):
        return self.zone5, self.zone4, self.zone3, self.zone2, self.zone1

    def getConfFile(self):
        if not os.path.isfile(self.conffile):
            return False
        else:
            return self.conffile

    def _parse_config_file(self, config_file):
        '''
        Parse the xml configuration file and convert to a dict

        returns: dict with option as key
        '''
        if config_file is None:
            logging.error("Configuration file value not set")
            logging.error("Fatal error, exiting")
            exit(-3)
        if not os.path.isfile(config_file):  #File not found
            logging.error("Configuration '%s' file does not exist" %
                          config_file)
            logging.info("No profile found. Creating default one")
            self.setProfile(self.profile_options)
        if os.stat(config_file)[stat.ST_SIZE] == 0:  #File is empty
            logging.error("Configuration '%s' file is empty" % config_file)
            logging.info("Creating default profile")
            self.setProfile(self.profile_options)
        logging.debug("Attempting to parse content from " + config_file)
        try:
            parser = etree.XMLParser(encoding='UTF8', recover=True)
            self.xml_tree = etree.parse(config_file, parser=parser)
            #Have a populated xml tree, get pytraining node (root) and convert it to a dict
            pytraining_tag = self.xml_tree.getroot()
            config = {}
            config_needs_update = False
            for key, default in self.profile_options.items():
                value = pytraining_tag.get(key)
                #If property is not found, set it to the default
                if value is None:
                    config_needs_update = True
                    value = default
                config[key] = value
            #Added a property, so update config
            if config_needs_update:
                self.setProfile(config)
            #Set shorthand var for units of measurement
            self.prf_us_system = True if config[
                "prf_us_system"] == "True" else False
            return config
        except Exception as e:
            logging.error("Error parsing file: %s. Exiting" % config_file)
            logging.error(str(e))
            logging.error("Fatal error, exiting")
            exit(-3)

    def getIntValue(self, tag, variable, default=0):
        ''' Function to return conf value as int
            returns
            -- default if cannot convert to int
            -- None if variable not found
        '''
        result = self.getValue(tag, variable)
        if result is None:
            return None
        try:
            result = int(result)
        except Exception as e:
            logging.debug(str(e))
            result = default
        return result

    def getValue(self, tag, variable):
        if tag != "pytraining":
            print "ERROR - pytraining is the only profile tag supported"
            return None
        elif not self.configuration.has_key(variable):
            return None
        return self.configuration[variable]

    def setValue(self, tag, variable, value, delay_write=False):
        logging.debug(">>")
        if tag != "pytraining":
            print "ERROR - pytraining is the only profile tag supported"
        logging.debug("Setting %s to %s" % (variable, value))
        if self.xml_tree is None:
            #new config file....
            self.xml_tree = etree.parse(
                StringIO(
                    '''<?xml version='1.0' encoding='UTF-8'?><pytraining />''')
            )
        self.xml_tree.getroot().set(variable, value.decode('utf-8'))
        if not delay_write:
            logging.debug("Writting...")
            self.xml_tree.write(self.config_file,
                                xml_declaration=True,
                                encoding='UTF-8')
        logging.debug("<<")

    def setProfile(self, list_options):
        logging.debug(">>")
        for option, value in list_options.items():
            logging.debug("Adding " + option + "|" + value)
            self.setValue("pytraining", option, value, delay_write=True)
        self.xml_tree.write(self.config_file,
                            xml_declaration=True,
                            encoding='UTF-8')
        self.uc.set_us(list_options['prf_us_system'])
        logging.debug("<<")

    def editProfile(self, sport_service):
        logging.debug(">>")
        from gui.windowprofile import WindowProfile
        logging.debug("retrieving configuration data")
        #Refresh configuration
        self.configuration = self._parse_config_file(self.config_file)
        if self.profilewindow is None:
            self.profilewindow = WindowProfile(
                sport_service,
                self.data_path,
                self,
                pytrainer_main=self.pytrainer_main)
            logging.debug("setting data values")
            self.profilewindow.setValues(self.configuration)
            self.profilewindow.run()
            self.profilewindow = None
        else:
            self.profilewindow.setValues(self.configuration)
            self.profilewindow.present()
        self.configuration = self._parse_config_file(self.config_file)
        logging.debug("<<")

    def actualize_mainsportlist(self):
        logging.debug("--")
        self.pytrainer_main.refreshMainSportList()
Exemplo n.º 8
0
class Profile:
    def __init__(self, environment, data_path = None, parent = None):
        logging.debug(">>")
        self.environment = environment
        self.pytrainer_main = parent
        self.data_path = data_path
        self.xml_tree = None
        self.tmpdir = environment.temp_dir
        self.confdir = environment.conf_dir
        self.conffile = environment.conf_file
        self.gpxdir = environment.gpx_dir
        self.extensiondir = environment.extension_dir
        self.plugindir = environment.plugin_dir
        self.uc = UC()
        self.profilewindow = None
        
        environment.clear_temp_dir()

        #Profile Options and Defaults
        self.profile_options = {
            "prf_name":"default",
            "prf_gender":"",
            "prf_weight":"",
            "prf_height":"",
            "prf_age":"",
            "prf_ddbb":"sqlite",
            "prf_ddbbhost":"",
            "prf_ddbbname":"",
            "prf_ddbbuser":"",
            "prf_ddbbpass":"",
            "version":"0.0",
            "prf_us_system":"False",
            "prf_hrzones_karvonen":"False",
            "prf_maxhr":"",
            "prf_minhr":"",
            "auto_launch_file_selection":"False",
            "import_default_tab":"0",
            "default_viewer":"0",
            "window_size":"800, 640",
            "activitypool_size": "10",
            }

        #Parse pytrainer configuration file
        self.config_file = environment.conf_file
        self.configuration = self._parse_config_file(self.config_file)
        logging.debug("Configuration retrieved: "+str(self.configuration))
        #self.pytrainer_main.ddbb = DDBB(self, pytrainer_main=self.pytrainer_main)
        self.uc.set_us(self.prf_us_system)
        self._setZones()
        logging.debug("<<")

    def _setZones(self):
        #maxhr = self.getValue("pytraining","prf_maxhr")
        #resthr = self.getValue("pytraining","prf_minhr")
        try:
            maxhr = int(self.getValue("pytraining","prf_maxhr"))
        except Exception as e:
            logging.error("Failed when retrieving Max Heartrate value: %s" %e)
            logging.info("Setting Max Heartrate to default value: 190")
            maxhr = 190
        try:
            resthr = int(self.getValue("pytraining","prf_minhr"))
        except Exception as e:
            logging.error("Failed when retrieving Min Heartrate value: %s" %e)
            logging.info("Setting Min Heartrate to default value: 65")
            resthr = 65
        self.maxhr = maxhr
        self.rethr = resthr

        if self.getValue("pytraining","prf_hrzones_karvonen")=="True":
            #karvonen method
            targethr1 = ((maxhr - resthr) * 0.50) + resthr
            targethr2 = ((maxhr - resthr) * 0.60) + resthr
            targethr3 = ((maxhr - resthr) * 0.70) + resthr
            targethr4 = ((maxhr - resthr) * 0.80) + resthr
            targethr5 = ((maxhr - resthr) * 0.90) + resthr
            targethr6 = maxhr
        else:
            #not karvonen method
            targethr1 = maxhr * 0.50
            targethr2 = maxhr * 0.60
            targethr3 = maxhr * 0.70
            targethr4 = maxhr * 0.80
            targethr5 = maxhr * 0.90
            targethr6 = maxhr

        self.zone1 = (targethr1,targethr2,"#ffff99",_("Moderate activity"))
        self.zone2 = (targethr2,targethr3,"#ffcc00",_("Weight Control"))
        self.zone3 = (targethr3,targethr4,"#ff9900",_("Aerobic"))
        self.zone4 = (targethr4,targethr5,"#ff6600",_("Anaerobic"))
        self.zone5 = (targethr5,targethr6,"#ff0000",_("VO2 MAX"))
        
    def getMaxHR(self):
        return self.maxhr
        
    def getRestHR(self):
        return self.resthr

    def getZones(self):
        return self.zone5,self.zone4,self.zone3,self.zone2,self.zone1

    def getConfFile(self):
        if not os.path.isfile(self.conffile):
            return False
        else:
            return self.conffile

    def _parse_config_file(self, config_file):
        '''
        Parse the xml configuration file and convert to a dict

        returns: dict with option as key
        '''
        if config_file is None:
            logging.error("Configuration file value not set")
            logging.error("Fatal error, exiting")
            exit(-3)
        if not os.path.isfile(config_file): #File not found
            logging.error("Configuration '%s' file does not exist" % config_file)
            logging.info("No profile found. Creating default one")
            self.setProfile(self.profile_options)
        if os.stat(config_file)[stat.ST_SIZE] == 0: #File is empty
            logging.error("Configuration '%s' file is empty" % config_file)
            logging.info("Creating default profile")
            self.setProfile(self.profile_options)
        logging.debug("Attempting to parse content from "+ config_file)
        try:
            parser = etree.XMLParser(encoding='UTF8', recover=True)
            self.xml_tree = etree.parse(config_file, parser=parser)
            #Have a populated xml tree, get pytraining node (root) and convert it to a dict
            pytraining_tag = self.xml_tree.getroot()
            config = {}
            config_needs_update = False
            for key, default in self.profile_options.items():
                value = pytraining_tag.get(key)
                #If property is not found, set it to the default
                if value is None:
                    config_needs_update = True
                    value = default
                config[key] = value
            #Added a property, so update config
            if config_needs_update:
                self.setProfile(config)
            #Set shorthand var for units of measurement
            self.prf_us_system = True if config["prf_us_system"] == "True" else False
            return config
        except Exception as e:
            logging.error("Error parsing file: %s. Exiting" % config_file)
            logging.error(str(e))
            logging.error("Fatal error, exiting")
            exit(-3)

    def getIntValue(self, tag, variable, default=0):
        ''' Function to return conf value as int
            returns
            -- default if cannot convert to int
            -- None if variable not found
        '''
        result = self.getValue(tag, variable)
        if result is None:
            return None
        try:
            result = int(result)
        except Exception as e:
            logging.debug(str(e))
            result = default
        return result

    def getValue(self, tag, variable):
        if tag != "pytraining":
            print "ERROR - pytraining is the only profile tag supported"
            return None
        elif not self.configuration.has_key(variable):
            return None
        return self.configuration[variable]

    def setValue(self, tag, variable, value, delay_write=False):
        logging.debug(">>")
        if tag != "pytraining":
            print "ERROR - pytraining is the only profile tag supported"
        logging.debug("Setting %s to %s" % (variable, value))
        if self.xml_tree is None:
            #new config file....
            self.xml_tree = etree.parse(StringIO('''<?xml version='1.0' encoding='UTF-8'?><pytraining />'''))
        self.xml_tree.getroot().set(variable, value.decode('utf-8'))
        if not delay_write:
            logging.debug("Writting...")
            self.xml_tree.write(self.config_file, xml_declaration=True, encoding='UTF-8')
        logging.debug("<<")

    def setProfile(self,list_options):
        logging.debug(">>")
        for option, value in list_options.items():
            logging.debug("Adding "+option+"|"+value)
            self.setValue("pytraining",option,value,delay_write=True)
        self.xml_tree.write(self.config_file, xml_declaration=True, encoding='UTF-8')
        self.uc.set_us(list_options['prf_us_system'])
        logging.debug("<<")

    def editProfile(self, sport_service):
        logging.debug(">>")
        from gui.windowprofile import WindowProfile
        logging.debug("retrieving configuration data")
        #Refresh configuration
        self.configuration = self._parse_config_file(self.config_file)
        if self.profilewindow is None:
            self.profilewindow = WindowProfile(sport_service, self.data_path, self, pytrainer_main=self.pytrainer_main)
            logging.debug("setting data values")
            self.profilewindow.setValues(self.configuration)
            self.profilewindow.run()
            self.profilewindow = None
        else:
            self.profilewindow.setValues(self.configuration)
            self.profilewindow.present()
        self.configuration = self._parse_config_file(self.config_file)
        logging.debug("<<")

    def actualize_mainsportlist(self):
        logging.debug("--")
        self.pytrainer_main.refreshMainSportList()