From b82c0c57b7657c33f86ef4f63c46d1639c3d77f3 Mon Sep 17 00:00:00 2001 From: Tom Keffer Date: Fri, 27 Mar 2015 17:47:06 -0700 Subject: [PATCH] Adding logic for --modify --- bin/wee_config | 69 ++++++++++++++++++++++++++--------------- bin/weeutil/config.py | 71 +++++++++++++++++++++++++++++-------------- setup.py | 14 ++++----- 3 files changed, 101 insertions(+), 53 deletions(-) diff --git a/bin/wee_config b/bin/wee_config index 82861ac7c..b69895005 100755 --- a/bin/wee_config +++ b/bin/wee_config @@ -18,7 +18,6 @@ import configobj import weewx import weeutil.config -from weeutil.config import save_path, mkdir, _as_string my_dir = os.path.abspath(os.path.dirname(__file__)) search_locations = [os.path.normpath(os.path.join(my_dir, '..')), '/etc/weewx', '/home/weewx'] @@ -26,6 +25,14 @@ search_locations = [os.path.normpath(os.path.join(my_dir, '..')), '/etc/weewx', minor_comment_block = [""] major_comment_block = ["", "##############################################################################", ""] +stn_info_defaults = {'location' : '', + 'latitude' : '0', + 'longitude' : '0', + 'altitude' : '[0, meter]', + 'units' : 'metric', + 'station_type' : 'Vantage', + 'driver' : 'weewx.drivers.Vantage'} + usage="""wee_config --help wee_config --version wee_config --list-drivers @@ -34,9 +41,9 @@ usage="""wee_config --help wee_config --merge CONFIG_FILE|--config=CONFIG_FILE --dist-config=DIST_CONFIG --output=OUT_CONFIG wee_config --modify CONFIG_FILE|--config=CONFIG_FILE - [--driver=(DRIVER|prompt)] + [--driver=DRIVER] [--latitude=yy.y] [--longitude=xx.x] [--altitude=zz.z,(foot|meter)] - [--description="Home Sweet Home"] [--units=(us|metric)] + [--location="Home Sweet Home"] [--units=(us|metric)] [--output=OUT_CONFIG] [--no-prompt] COMMANDS: @@ -89,16 +96,15 @@ def main(): help="Where the results should be written.") parser.add_option("--no-prompt", action="store_true", help="Do not issue prompts. Use default values or specified options.") - parser.add_option("--driver", metavar="(DRIVER|prompt)", dest="driver", - help="Add the specified driver DRIVER to the configuration file. " - "If --driver=prompt is used, you will be prompted for the driver name.") + parser.add_option("--driver", metavar="DRIVER", dest="driver", + help="Use the driver DRIVER, e.g., weewx.driver.vantage. ") parser.add_option("--latitude", metavar="yy.y", help="The station latitude") parser.add_option("--longitude", metavar="xx.x", help="The station longitude") - parser.add_option("--altitude", metavar="zz,(foot|meter)", + parser.add_option("--altitude", metavar="zz,(foot|meter)", default='[0, meter]', help="The station altitude in either feet or meters. E.g., '750,foot'") - parser.add_option("--description", + parser.add_option("--location", help="""A text description of the station. For example, "Santa's workshop, North Pole" """) parser.add_option("--units", choices=["us", "metric"], metavar="(metric|us)", help="Set display units to 'metric' or 'us'") @@ -130,7 +136,7 @@ def main(): if options.merge and not options.output: exit("Command --merge requires option --output") - # Get the configuration file: + # Looks good. Get the configuration file: config_path, config_dict = weeutil.config.read_config(options.config_path, args, locations=search_locations) print "Using configuration file found at", config_path @@ -143,7 +149,7 @@ def main(): try: dist_config_dict = configobj.ConfigObj(options.dist_config, file_error=True) except SyntaxError, e: - exit("Syntax error in distribution configuration file '%s': %s" % (dist_config, e)) + exit("Syntax error in distribution configuration file '%s': %s" % (options.dist_config, e)) # Update the old configuration file: weeutil.config.update_config(config_dict) @@ -153,6 +159,35 @@ def main(): save_me = True + if options.modify: + + # Get defaults out of the config file: + stn_info = weeutil.config.get_station_info(config_dict) + + # Get command line overrides, and apply them to stn_info: + for k in stn_info: + if hasattr(options, k) and getattr(options,k) is not None: + stn_info[k] = getattr(options, k) + + # If any are still None, replace them with defaults: + for k in stn_info_defaults: + if stn_info[k] is None: + stn_info[k] = stn_info_defaults[k] + + # Unless --no-prompt has been specified, give the user a chance to change things: + if not options.no_prompt: + stn_info.update(weeutil.config.prompt_for_info(**stn_info)) + + if not options.driver: + driver = prompt_for_driver(stn_info.get('driver')) + stn_info['driver'] = driver + + # Look up driver info: + driver_editor, driver_name, driver_version = weeutil.config.load_driver_editor(stn_info.get('driver')) + + print "Station info", stn_info + exit() + if save_me: # Save the resultant config file, backing up as necessary. @@ -184,20 +219,6 @@ def main(): sys.exit("Nothing done.") return 0 -def get_station_info(config_dict): - """Extract station info from config dictionary.""" - stn_info = dict() - if config_dict is not None and 'Station' in config_dict: - stn_info['location'] = _as_string(config_dict['Station'].get('location')) - stn_info['latitude'] = config_dict['Station'].get('latitude') - stn_info['longitude'] = config_dict['Station'].get('longitude') - stn_info['altitude'] = config_dict['Station'].get('altitude') - if 'station_type' in config_dict['Station']: - stn_info['station_type'] = config_dict['Station']['station_type'] - if stn_info['station_type'] in config_dict: - stn_info['driver'] = config_dict[stn_info['station_type']]['driver'] - return stn_info - def prompt_for_driver(dflt_driver=None): """Get the information about each driver, return as a dictionary.""" infos = weeutil.config.get_driver_infos() diff --git a/bin/weeutil/config.py b/bin/weeutil/config.py index 056b10e70..ab941a666 100644 --- a/bin/weeutil/config.py +++ b/bin/weeutil/config.py @@ -522,6 +522,25 @@ def replace_string(a_dict, label, value): else: a_dict[k] = a_dict[k].replace(label, value) +def get_station_info(config_dict): + """Extract station info from config dictionary.""" + stn_info = dict() + if config_dict is not None: + if 'Station' in config_dict: + stn_info['location'] = _as_string(config_dict['Station'].get('location')) + stn_info['latitude'] = config_dict['Station'].get('latitude') + stn_info['longitude'] = config_dict['Station'].get('longitude') + stn_info['altitude'] = config_dict['Station'].get('altitude') + if 'station_type' in config_dict['Station']: + stn_info['station_type'] = config_dict['Station']['station_type'] + if stn_info['station_type'] in config_dict: + stn_info['driver'] = config_dict[stn_info['station_type']]['driver'] + if 'StdReport' in config_dict: + # TODO: Perhaps we could add some smarts here? + stn_info['units'] = None + + return stn_info + def get_driver_infos(): """Scan the drivers folder, extracting information about each available driver. Return as a dictionary, keyed by driver name.""" @@ -550,21 +569,29 @@ def get_driver_infos(): return driver_info_dict -def prompt_for_info(dflt_loc=None, dflt_lat='90.000', dflt_lon='0.000', - dflt_alt=['0', 'meter'], dflt_units='metric'): +def load_driver_editor(driver): + """Load the configuration editor from the driver file""" + __import__(driver) + driver_module = sys.modules[driver] + loader_function = getattr(driver_module, 'confeditor_loader') + editor = loader_function() + return editor, driver_module.DRIVER_NAME, driver_module.DRIVER_VERSION + +def prompt_for_info(location=None, latitude='90.000', longitude='0.000', + altitude=['0', 'meter'], units='metric', **kwargs): # # Description # print "Enter a brief description of the station, such as its location. For example:" print "Santa's Workshop, North Pole" - msg = "description: [%s]: " % dflt_loc if dflt_loc else "description: " + msg = "description: [%s]: " % location if location else "description: " loc = None while loc is None: ans = raw_input(msg).strip() if ans: loc = ans - elif dflt_loc: - loc = dflt_loc + elif location: + loc = location # # Altitude @@ -572,7 +599,7 @@ def prompt_for_info(dflt_loc=None, dflt_lat='90.000', dflt_lon='0.000', print "Specify altitude, with units 'foot' or 'meter'. For example:" print "35, foot" print "12, meter" - msg = "altitude [%s]: " % _as_string(dflt_alt) if dflt_alt else "altitude: " + msg = "altitude [%s]: " % _as_string(altitude) if altitude else "altitude: " alt = None while alt is None: ans = raw_input(msg).strip() @@ -587,8 +614,8 @@ def prompt_for_info(dflt_loc=None, dflt_lat='90.000', dflt_lon='0.000', alt = [parts[0].strip(), parts[1].strip()] except (ValueError, TypeError): pass - elif dflt_alt: - alt = dflt_alt + elif altitude: + alt = altitude if not alt: print "Unrecognized response. Try again." @@ -611,28 +638,28 @@ def get_val(msg, low_limit, high_limit, dflt_v): return v print "Specify latitude in decimal degrees, negative for south." - msg = "latitude [%s]: " % dflt_lat if dflt_lat else "latitude: " - lat = get_val(msg, -90, 90, dflt_lat) + msg = "latitude [%s]: " % latitude if latitude else "latitude: " + lat = get_val(msg, -90, 90, latitude) print "Specify longitude in decimal degrees, negative for west." - msg = "longitude [%s]: " % dflt_lon if dflt_lon else "longitude: " - lon = get_val(msg, -180, 180, dflt_lon) + msg = "longitude [%s]: " % longitude if longitude else "longitude: " + lon = get_val(msg, -180, 180, longitude) # # Display units # print "Indicate the preferred units for display: 'metric' or 'us'" - msg = "units [%s]: " % dflt_units if dflt_units else "units: " - units = None - while units is None: + msg = "units [%s]: " % units if units else "units: " + uni = None + while uni is None: ans = raw_input(msg).strip().lower() if ans: if ans in ['metric', 'us']: - units = ans - elif dflt_units: - units = dflt_units + uni = ans + elif units: + uni = units - return {'location': loc, - 'altitude': alt, - 'latitude': lat, + return {'location' : loc, + 'altitude' : alt, + 'latitude' : lat, 'longitude': lon, - 'units': units} + 'units' : uni} diff --git a/setup.py b/setup.py index 365c81e3a..b43feb374 100755 --- a/setup.py +++ b/setup.py @@ -474,13 +474,13 @@ def configure_conf(config_fn, info, dryrun=False): weeutil.config.save_path(config_fn) shutil.move(config.filename, config_fn) -def load_editor(driver): - """Load the configuration editor from the driver file""" - __import__(driver) - driver_module = sys.modules[driver] - loader_function = getattr(driver_module, 'confeditor_loader') - editor = loader_function() - return editor, driver_module.DRIVER_NAME, driver_module.DRIVER_VERSION +# def load_editor(driver): +# """Load the configuration editor from the driver file""" +# __import__(driver) +# driver_module = sys.modules[driver] +# loader_function = getattr(driver_module, 'confeditor_loader') +# editor = loader_function() +# return editor, driver_module.DRIVER_NAME, driver_module.DRIVER_VERSION def prompt_for_driver(dflt_driver=None): """Get the information about each driver, return as a dictionary."""