def load_from_config_dict(self, config_dict): """Retrieve phenology models, part I. """ phenology_models_dict = {} try: weewx_root = config_dict['WEEWX_ROOT'] std_report = config_dict['StdReport'] skin_root = std_report.get('SKIN_ROOT', 'skins') phenology_report = std_report['PhenologyReport'] is_enabled = weeutil.weeutil.to_bool(phenology_report['enable']) phenology_skin = phenology_report['skin'] phenology_skin_path = os.path.join(weewx_root, skin_root, phenology_skin) os.chdir(phenology_skin_path) (dummy, phenology_skin_dict) = weecfg.read_config('skin.conf') extras = phenology_skin_dict['Extras'] self.load_from_extras(extras) except KeyError as e: LOG.error("No XTypes. Missing parameter: {}".format(e)) except AttributeError as e: LOG.error("Bad 'enable': {}".format(e)) except (IOError, OSError, SyntaxError) as e: LOG.error("No XTypes. {}".format(e)) return self
def main(): import optparse import weecfg syslog.openlog('wee_cmon', syslog.LOG_PID | syslog.LOG_CONS) parser = optparse.OptionParser(usage=usage) parser.add_option('--config', dest='cfgfn', type=str, metavar="FILE", help="Use configuration file FILE. Default is /etc/weewx/weewx.conf or /home/weewx/weewx.conf") parser.add_option('--binding', dest="binding", metavar="BINDING", default='cmon_binding', help="The data binding to use. Default is 'cmon_binding'.") parser.add_option('--test-collector', dest='tc', action='store_true', help='test the data collector') parser.add_option('--test-driver', dest='td', action='store_true', help='test the driver') parser.add_option('--test-service', dest='ts', action='store_true', help='test the service') parser.add_option('--update', dest='update', action='store_true', help='update schema to v3') (options, args) = parser.parse_args() if options.update: _, config_dict = weecfg.read_config(options.cfgfn, args) update_to_v3(config_dict, options.binding) elif options.tc: test_collector() elif options.td: test_driver() elif options.ts: test_service()
def main_line(): """Testing only. This function is called only when this module is run stand-alone. """ import weewx.engine import weewx.station import weecfg import weeutil.logger config_path = '/home/crhode/WeeWX/weewx/weewx.conf' (config_path, config_dict) = weecfg.read_config(config_path) config_dict.walk(disable_timing) weewx.debug = weeutil.weeutil.to_int(config_dict.get('debug', ZERO)) weeutil.logger.setup('wee_reports', config_dict) stn_info = weewx.station.StationInfo(**config_dict['Station']) try: binding = config_dict['StdArchive']['data_binding'] except KeyError: binding = 'wx_binding' db_manager = weewx.manager.DBBinder(config_dict).get_manager(binding) ts = db_manager.lastGoodStamp() record = db_manager.getRecord(ts) report_engine = weewx.reportengine.StdReportEngine(config_dict, stn_info, record=record, gen_ts=None) skin_dict = report_engine._build_skin_dict('PhenologyReport') phenology_service = user.phenologyservice.PhenologyService( report_engine, config_dict) image_generator = PhenologyImageGenerator( config_dict=config_dict, skin_dict=skin_dict, gen_ts=None, first_run=False, stn_info=stn_info, record=record, ) image_generator.setup() image_generator.start() image_generator.finalize() phenology_service.shutDown() return
def load_from_extras(self, extras): """Retrieve phenology models, part II. """ try: phenology_models = extras['phenologies'] (dummy, phenology_models_dict) = weecfg.read_config(phenology_models) name_models = extras['models'] except KeyError as e: LOG.error("No XTypes. Missing parameter: {}".format(e)) except AssertionError: LOG.error("PhenologyReport is not enabled.") except (IOError, SyntaxError) as e: LOG.error("No XTypes. {}".format(e)) self.southern_hemisphere_start_month_offset = phenology_models_dict.get( 'southern_hemisphere_start_month_offset') models_dict = phenology_models_dict.get('Phenologies', {}) self.harvest(models_dict, name_models) return self
def main(): import optparse import weecfg import weewx def get_ids(stn_dict): """Display BloomSky device IDs associated with an API key.""" # get a BloomskyDriver object driver = BloomskyDriver(**stn_dict) ids = driver.ids if len(ids) > 1: print("Found BloomSky device IDs: %s" % ', '.join(ids)) elif len(ids) == 1: print("Found BloomSky device ID: %s" % ', '.join(ids)) else: print("No BloomSky device IDS found") driver.closePort() exit(0) def test_driver(stn_dict): """Test the BloomSky driver.""" # wrap in a try..except so we can pickup a keyboard interrupt try: # get a BloomskyDriver object driver = BloomskyDriver(**stn_dict) # continuously get loop packets and print them to screen for pkt in driver.genLoopPackets(): print(weeutil.weeutil.timestamp_to_string(pkt['dateTime']), pkt) except KeyboardInterrupt: # we have a keyboard interrupt so shut down driver.closePort() def get_json_data(stn_dict): """Obtain BloomSky API response and display in JSON format.""" # extract the API key api_key = stn_dict.get('api_key') # if we have an API key then get the data otherwise exit after # informing the user about the problem if api_key: # get an ApiClient object api_client = ApiClient(api_key=api_key) # get the JSON response raw_data = api_client.sd.get_data() # do we have any raw data? if raw_data is not None: # yes, display the JSON response on screen print(json.dumps(raw_data, sort_keys=True, indent=2)) else: # no, display an appropriate message print("Unable to obtain JSON data") exit(0) else: print("BloomSky API key required.") print("Specify API key in configuration file under [Bloomsky] or use --api_key option.") print("Exiting.") exit(1) usage = """Usage: python -m user.bloomsky --help python -m user.bloomsky --version python -m user.bloomsky --test-driver [CONFIG_FILE|--config=CONFIG_FILE] [--api-key=API_KEY] [--debug=0|1|2|3] python -m user.bloomsky --get-json-data [CONFIG_FILE|--config=CONFIG_FILE] [--api-key=API_KEY] [--debug=0|1|2|3] python -m user.bloomsky --get-device-ids [CONFIG_FILE|--config=CONFIG_FILE] [--api-key=API_KEY] [--debug=0|1|2|3]""" parser = optparse.OptionParser(usage=usage) parser.add_option('--version', dest='version', action='store_true', help='display BloomSky driver version number') parser.add_option('--config', dest='config_path', metavar='CONFIG_FILE', help="use configuration file CONFIG_FILE.") parser.add_option('--debug', dest='debug', metavar='DEBUG', help='use WeeWX debug level DEBUG') parser.add_option('--test-driver', dest='test_driver', action='store_true', metavar='TEST_DRIVER', help='test the BloomSky driver') parser.add_option('--api-key', dest='api_key', metavar='API_KEY', help='BloomSky API key') parser.add_option('--get-json-data', dest='jdata', action='store_true', help='get BloomSky API json response') parser.add_option('--get-device-ids', dest='get_ids', action='store_true', help='get BloomSky device IDs associated with an API key') (opts, args) = parser.parse_args() # get config_dict to use config_path, config_dict = weecfg.read_config(opts.config_path, args) print("Using configuration file %s" % config_path) stn_dict = config_dict.get('Bloomsky', {}) # set weewx.debug as necessary if opts.debug is not None: _debug = weeutil.weeutil.to_int(opts.debug) else: _debug = weeutil.weeutil.to_int(config_dict.get('debug', 0)) weewx.debug = _debug # Now we can set up the user customized logging but we need to handle both # v3 and v4 logging. V4 logging is very easy but v3 logging requires us to # set up syslog and raise our log level based on weewx.debug try: # assume v 4 logging weeutil.logger.setup('weewx', config_dict) except AttributeError: # must be v3 logging, so first set the defaults for the system logger syslog.openlog('weewx', syslog.LOG_PID | syslog.LOG_CONS) # now raise the log level if required if weewx.debug > 0: syslog.setlogmask(syslog.LOG_UPTO(syslog.LOG_DEBUG)) # display driver version number if opts.version: print("%s driver version: %s" % (DRIVER_NAME, DRIVER_VERSION)) exit(0) # do we have a specific API key to use if opts.api_key: stn_dict['api_key'] = opts.api_key obfuscated = ''.join(('"....', opts.api_key[-4:], '"')) print("Using BloomSky API key %s" % obfuscated) # display device IDs if opts.get_ids: get_ids(stn_dict) exit(0) # run the driver if opts.test_driver: test_driver(stn_dict) exit(0) # get BloomSky API JSON response if opts.jdata: get_json_data(stn_dict) exit(0) # otherwise print our help parser.print_help()
PYTHONPATH=/home/weewx/bin python lowBattery.py --help""" # Force debug: weewx.debug = 1 # Create a command line parser: parser = OptionParser(usage=usage, epilog=epilog) parser.add_option("--config", dest="config_path", metavar="CONFIG_FILE", help="Use configuration file CONFIG_FILE.") # Parse the arguments and options (options, args) = parser.parse_args() try: config_path, config_dict = weecfg.read_config(options.config_path, args) except IOError as e: exit("Unable to open configuration file: %s" % e) print("Using configuration file %s" % config_path) # Set logging configuration: weeutil.logger.setup('lowBattery', config_dict) if 'Alarm' not in config_dict: exit("No [Alarm] section in the configuration file %s" % config_path) # This is the fake packet that we'll use pack = {'txBatteryStatus': 1.0, 'dateTime': int(time.time())} # We need the main WeeWX engine in order to bind to the event, but we don't need
This module is imported from the main executable, so anything put here will be executed before anything else happens. This makes it a good place to put user extensions. """ import locale # This will use the locale specified by the environment variable 'LANG' # Other options are possible. See: # http://docs.python.org/2/library/locale.html#locale.setlocale locale.setlocale(locale.LC_ALL, '') # added by # QUETELARD from datetime import datetime import os # end added import weewx.manager import weecfg # added by QUETELARD # when program start, in first get lastUpdate of database file_name = os.environ['HOME'] + "/root/weewx.conf" config_dict = weecfg.read_config(file_name) config_dict = config_dict[1] db_binding = 'wx_binding' dbm = weewx.manager.open_manager_with_config(config_dict, db_binding) last_update_stop = int(dbm._read_metadata('lastUpdate')) dbm.close # end added
def run(self, args, options): if options.version: print(weewx.__version__) sys.exit(0) if options.list_drivers: weecfg.print_drivers() sys.exit(0) # # Check for errors in the options. # # We must be doing one of install, upgrade, and reconfigure: if sum(1 if x is True else 0 for x in [options.install, options.upgrade, options.reconfigure]) != 1: sys.exit( "Must specify one and only one of --install, --upgrade, or --reconfigure." ) # Check for missing --dist-config if (options.install or options.upgrade) and not options.dist_config: sys.exit( "The commands --install and --upgrade require option --dist-config." ) if options.install and not options.output: sys.exit("The --install command requires option --output.") # The install option does not take an old config file if options.install and (options.config_path or len(args)): sys.exit( "The --install command does not require the config option.") # # Error checking done. Now run the commands. # # First, fiddle with option --altitude to convert it into a list: if options.altitude: options.altitude = options.altitude.split(",") if options.install or options.upgrade: # These options require a distribution config file. # Open it up and parse it: try: dist_config_dict = configobj.ConfigObj(options.dist_config, file_error=True) except IOError as e: sys.exit("Unable to open distribution configuration file: %s" % e) except SyntaxError as e: sys.exit( "Syntax error in distribution configuration file '%s': %s" % (options.dist_config, e)) # The install command uses the distribution config file as its input. # Other commands use an existing config file. if options.install: config_dict = dist_config_dict else: try: config_path, config_dict = weecfg.read_config( options.config_path, args) except SyntaxError as e: sys.exit("Syntax error in configuration file: %s" % e) except IOError as e: sys.exit("Unable to open configuration file: %s" % e) self.logger.log("Using configuration file %s" % config_path) output_path = None if options.upgrade: # Update the config dictionary, then merge it with the distribution # dictionary weecfg.update_and_merge(config_dict, dist_config_dict) # Save to the specified output output_path = options.output if options.install or options.reconfigure: # Modify the configuration contents self.modify_config(config_dict, options) # Save to the specified output, or the original location if # output is not specified output_path = options.output if options.output else config_path if output_path is not None: # Save the file. self.save_config(config_dict, output_path, not options.no_backup)
def run(self, args, options): if options.version: print(weewx.__version__) sys.exit(0) if options.list_drivers: weecfg.print_drivers() sys.exit(0) # # If we got to this point, the verb must be --install, --upgrade, or --reconfigure. # Check for errors in the options. # # We can do one and only one of install, upgrade, and reconfigure: if (options.install and options.upgrade) \ or (options.install and options.reconfigure) \ or (options.upgrade and options.reconfigure): sys.exit("Must specify one and only one of --install, --upgrade, or --reconfigure.") # Check for missing --dist-config if (options.install or options.upgrade) and not options.dist_config: sys.exit("The commands --install and --upgrade require option --dist-config.") # Check for missing config file if options.upgrade and not (options.config_path or args): sys.exit("The command --upgrade requires an existing configuration file.") if options.install and not options.output: sys.exit("The --install command requires option --output.") # The install option does not take an old config file if options.install and (options.config_path or args): sys.exit("A configuration file cannot be used with the --install command.") # # Now run the commands. # # First, fiddle with option --altitude to convert it into a list: if options.altitude: options.altitude = options.altitude.split(",") if options.install or options.upgrade: # These options require a distribution config file. # Open it up and parse it: try: dist_config_dict = configobj.ConfigObj(options.dist_config, file_error=True, encoding='utf-8') except IOError as e: sys.exit("Unable to open distribution configuration file: %s" % e) except SyntaxError as e: sys.exit("Syntax error in distribution configuration file '%s': %s" % (options.dist_config, e)) # The install command uses the distribution config file as its input. # Other commands use an existing config file. if options.install: config_dict = dist_config_dict else: try: config_path, config_dict = weecfg.read_config(options.config_path, args) except SyntaxError as e: sys.exit("Syntax error in configuration file: %s" % e) except IOError as e: sys.exit("Unable to open configuration file: %s" % e) self.logger.log("Using configuration file %s" % config_path) if options.upgrade: # Update the config dictionary, then merge it with the distribution # dictionary weecfg.update_and_merge(config_dict, dist_config_dict) elif options.install or options.reconfigure: # Extract stn_info from the config_dict and command-line options: stn_info = self.get_stn_info(config_dict, options) # Use it to modify the configuration file. weecfg.modify_config(config_dict, stn_info, self.logger, options.debug) else: sys.exit("Internal logic error in config.py") # For the path to the final file, use whatever was specified by --output, # or the original path if that wasn't specified output_path = options.output or config_path # Save weewx.conf, backing up any old file. backup_path = weecfg.save(config_dict, output_path, not options.no_backup) if backup_path: self.logger.log("Saved backup to %s" % backup_path)
def execute_report(self, args, conn, host, address): import weecfg import weewx.station import weewx.reportengine import weeutil.rsyncupload try: logdbg("RemoteWebserverReport: " + str(args)) _config_path, config_dict = weecfg.read_config(None, None) ts = float(args[1]) html_root = args[3] stn_info = weewx.station.StationInfo(**config_dict['Station']) save_entries = [ "SKIN_ROOT", "HTML_ROOT", "data_binding", "log_success", "log_failure", "w34Highcharts" ] for key in config_dict['StdReport']: if key not in save_entries: del config_dict['StdReport'][key] config_dict['StdReport']['w34Highcharts'][ 'skin'] = 'w34Highcharts-day' config_dict['StdReport']['w34Highcharts']['CheetahGenerator'] = { 'search_list_extensions': 'user.w34highchartsSearchX.w34highcharts_' + args[2].split('/')[-1].split('.')[0], 'encoding': 'strict_ascii', 'ToDate': { 'DayJSON': { 'template': args[2], 'HTML_ROOT': html_root } } } try: binding = config_dict['StdArchive']['data_binding'] except KeyError: binding = 'wx_binding' with weewx.manager.DBBinder(config_dict) as db_binder: db_manager = db_binder.get_manager(binding) for _ in range(1500): record = db_manager.getRecord(ts) if record == None: ts = ts + 60 else: break if record == None: ts = db_manager.firstGoodStamp() record = db_manager.getRecord(ts) weewx.reportengine.StdReportEngine(config_dict, stn_info, record=record, gen_ts=ts).run() logdbg("RemoteWebserverReport: Report complete") if host != address: try: weeutil.rsyncupload.RsyncUpload( local_root=os.path.join(html_root, 'json_day'), remote_root=os.path.join(html_root, 'json_day'), server=self.address, user=None, port=None, ssh_options=None, compress=False, delete=False, log_success=True).run() logdbg("RemoteWebserverReport: Rsync complete") except IOError as e: logerr("RemoteWebserverReport: " + e) except Exception as e: logerr("RemoteWebserverReport: " + e) finally: try: conn.close() except Exception as e: logdbg("RemoteWebserverReport: " + e)
try: dist_config_dict = configobj.ConfigObj(options.dist_config, file_error=True) except IOError, e: sys.exit("Unable to open distribution configuration file: %s" % e) except SyntaxError, e: sys.exit("Syntax error in distribution configuration file '%s': %s" % (options.dist_config, e)) # The install command uses the distribution config file as its input. # Other commands use an existing config file. if options.install: config_dict = dist_config_dict else: try: config_path, config_dict = weecfg.read_config( options.config_path, args) except SyntaxError, e: sys.exit("Syntax error in configuration file: %s" % e) except IOError, e: sys.exit("Unable to open configuration file: %s" % e) self.logger.log("Using configuration file %s" % config_path) output_path = None if options.upgrade: # Update the config dictionary, then merge it with the distribution # dictionary weecfg.update_and_merge(config_dict, dist_config_dict) # Save to the specified output output_path = options.output
def main(): # Set defaults for the system logger: syslog.openlog('weewxwd', syslog.LOG_PID|syslog.LOG_CONS) # Create a command line parser: parser = optparse.OptionParser(description=description, usage=usage, epilog=epilog) # Add the various options: parser.add_option("--create-archive", dest="create_archive", action='store_true', help="Create the Weewx-WD archive database.") parser.add_option("--drop-daily", dest="drop_daily", action='store_true', help="Drop the Weewx-WD daily summary tables.") parser.add_option('--backfill-daily', dest='backfill_daily', action='store_true', help='Backfill Weewx-WD daily summary tables from Weewx-WD archive.') parser.add_option("--reconfigure", dest="reconfigure", action='store_true', help="Create a new Weewx-WD archive database using configuration information found " "in the configuration file. In particular, the new database will use the unit " "system found in option [StdConvert][target_unit]. The new database will have " "the same name as the old database, with a '_new' on the end.") parser.add_option("--string-check", dest="string_check", action="store_true", help="Check a sqlite version of the Weewx-WD database to " "see whether it contains embedded strings.") parser.add_option("--copy-v2-data", dest="copy_v2", action='store_true', help="Copy historical Weewx-WD observation data from Weewx archive to Weewx-WD archive.") parser.add_option("--clear-v2-data", dest="clear_v2", action='store_true', help="Clear historical Weewx-WD data from Weewx (not Weewx-WD) archive. NOTE: This option will irreversibly clear all data stored in the 'extraTemp1' and 'extraTemp2' fields in the Weewx (not Weewx-WD) archive.") parser.add_option('--version', dest='version', action='store_true', help='Display Weewx-WD executable file versions.') parser.add_option('--status', dest='status', action='store_true', help='Display Weewx-WD archive status.') parser.add_option('--config', dest='config_path', type=str, metavar="CONFIG_PATH", help="Use configuration file CONFIG_PATH. Default is /etc/weewx/weewx.conf or /home/weewx/weewx.conf.") parser.add_option("--wx-binding", dest="wxbinding", metavar="WX_BINDING_NAME", default='wx_binding', help="The weewx data binding. Default is 'wx_binding'.") parser.add_option("--wd-binding", dest="wdbinding", metavar="WD_BINDING_NAME", default='wd_binding', help="The Weewx-WD data binding. Default is 'wd_binding'.") parser.add_option("--fix", dest="fix", action="store_true", help="Fix any embedded strings in a sqlite database.") # Now we are ready to parse the command line: (options, args) = parser.parse_args() if options.version: print "Weewx-WD weewxwd_config version: %s" % WEEWXWD_CONFIG_VERSION print "Weewx-WD weewxwd version: %s" % user.weewxwd3.WEEWXWD_VERSION print "Weewx-WD SLE version: %s" % user.wdSearchX3.WEEWXWD_SLE_VERSION print "Weewx-WD Astronomical SLE version: %s" % user.wdAstroSearchX3.WEEWXWD_ASTRO_SLE_VERSION print "Weewx-WD Tagged Statistics version: %s" % user.wdTaggedStats3.WEEWXWD_TAGGED_STATS_VERSION print "Weewx-WD Stacked Windrose Generator version: %s" % user.imageStackedWindRose3.WEEWXWD_STACKED_WINDROSE_VERSION exit(1) config_path, config_dict = weecfg.read_config(options.config_path, args) print "Using configuration file %s" % config_path db_binding_wd, db_binding_wx = get_bindings(config_dict) db_binding_wx = options.wxbinding db_binding_wd = options.wdbinding database_wx = config_dict['DataBindings'][db_binding_wx]['database'] database_wd = config_dict['DataBindings'][db_binding_wd]['database'] print "Using database binding '%s', which is bound to database '%s'" % (db_binding_wx, database_wx) print "Using database binding '%s', which is bound to database '%s'" % (db_binding_wd, database_wd) if options.status: print_status(config_dict, db_binding_wd, db_binding_wx) exit(1) if options.create_archive: createMainDatabase(config_dict, db_binding_wd) if options.reconfigure: reconfigMainDatabase(config_dict, db_binding_wd) if options.drop_daily: dropDaily(config_dict, db_binding_wd) if options.backfill_daily: backfillDaily(config_dict, db_binding_wd) if options.string_check: string_check(config_dict, db_binding_wd, options.fix) if options.copy_v2: copy_v2_data(config_dict, db_binding_wd, db_binding_wx) exit(1) if options.clear_v2: clear_v2_data(config_dict, db_binding_wx) exit(1)
def main(): import optparse syslog.openlog('xmlparse', syslog.LOG_PID | syslog.LOG_CONS) parser = optparse.OptionParser(usage=usage) parser.add_option('--version', dest='version', action='store_true', help='display driver version number') parser.add_option('--config', dest='config_path', metavar='CONFIG_FILE', help="use configuration file CONFIG_FILE.") parser.add_option('--run-driver', dest='run_driver', action='store_true', metavar='RUN_DRIVER', help='run the xmlparse driver') # yet to be implemented # parser.add_option('--run-service', dest='run_service', action='store_true', # metavar='RUN_SERVICE', help='run the Bloomsky service') parser.add_option('--path', dest='xml_path', metavar='XML_PATH', help='path and file name of xml file') parser.add_option('--display-xml', dest='display_xml', action='store_true', help='display the parsed xml file contents') parser.add_option('--pretty-print-xml', dest='pprint_xml', action='store_true', help='pretty print the parsed xml file contents') (opts, args) = parser.parse_args() # display driver version number if opts.version: print "%s driver version: %s" % (DRIVER_NAME, DRIVER_VERSION) exit(0) # get config_dict to use config_path, config_dict = weecfg.read_config(opts.config_path, args) # inform the user of the config file being used print "Using configuration file %s" % config_path # extract the XML driver stanza as a config dict xml_config_dict = config_dict.get(DRIVER_NAME, {}) # run the driver if opts.run_driver: run_driver(xml_config_dict) # pretty print the xml data if opts.pprint_xml: # get the path and file name to use as our source, it can be # specified by a command line parameter or obtained from a WeeWX # config file _xml_path = opts.xml_path if opts.xml_path else xml_config_dict.get('path') # pretty print the XML data pprint_xml_data(_xml_path) exit(0) # display the xml data if opts.display_xml: # get the path and file name to use as our source, it can be # specified by a command line parameter or obtained from a WeeWX # config file _xml_path = opts.xml_path if opts.xml_path else xml_config_dict.get('path') # display the XML data display_xml_data(_xml_path) exit(0) # if we reached here then display our usage info parser.print_help()