def setup_logging(logging_level, config_dict): # Need to match signature pylint: disable=unused-argument """ Setup logging for running in standalone mode.""" syslog.openlog('wee_MQTTSS', syslog.LOG_PID | syslog.LOG_CONS) if logging_level: syslog.setlogmask(syslog.LOG_UPTO(syslog.LOG_DEBUG)) else: syslog.setlogmask(syslog.LOG_UPTO(syslog.LOG_INFO))
def main(): syslog.openlog('wee_observer', syslog.LOG_PID | syslog.LOG_CONS) parser = optparse.OptionParser(usage=usage) parser.add_option('--version', dest='version', action='store_true', help='display driver version') parser.add_option('--debug', dest='debug', action='store_true', help='display diagnostic information while running') parser.add_option('--host', dest='host', metavar="HOST", help='ip address of interface on which to listen', default='') parser.add_option('--port', dest='port', type=int, metavar="PORT", help='port on which driver should listen', default=Observer.DEFAULT_LISTEN_PORT) parser.add_option('--test-decode', dest='filename', metavar='FILENAME', help='test the decoding') (options, _) = parser.parse_args() if options.version: print "driver version %s" % DRIVER_VERSION exit(1) if options.debug is not None: syslog.setlogmask(syslog.LOG_UPTO(syslog.LOG_DEBUG)) else: syslog.setlogmask(syslog.LOG_UPTO(syslog.LOG_INFO)) if options.filename: data = '' with open(options.filename, "r") as f: data = f.read() print Observer.decode_data(data) exit(0) print "driver version %s" % DRIVER_VERSION print "listen on %s:%s" % (options.host, options.port) station = Observer(options.host, options.port) queue = Queue.Queue() t = ListenThread(station, queue) t.start() while True: try: data = queue.get(True, 10) print "raw data:", _fmt(data) pkt = Observer.decode_data(data) print "raw packet:", pkt time.sleep(5) except Queue.Empty: pass except KeyboardInterrupt: print "keyboard interrupt, shutting down" t.stop_running() break t.join()
def main(): import sys import json syslog.openlog('wee_' + DRIVER_SHORT_NAME, syslog.LOG_PID | syslog.LOG_CONS) parser = optparse.OptionParser(usage=usage) parser.add_option('--version', dest='version', action='store_true', help='display driver version') parser.add_option('--debug', dest='debug', action='store_true', help='display diagnostic information while running') 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('--url', dest='url', metavar="URL", help='Full URL of the MicroServer including path info to XML data') parser.add_option('--host', dest='host', metavar="HOST", help='hostname or ip address of the MicroServer') parser.add_option('--port', dest='port', type=int, metavar="PORT", default=80, help='port on which the MicroServer is listening') parser.add_option('--test-parse', dest='filename', metavar='FILENAME', help='test the xml parsing') (options, _) = parser.parse_args() if options.version: print("%s driver version %s" % (DRIVER_SHORT_NAME, DRIVER_VERSION)) exit(1) weeutil.logger.setup(DRIVER_SHORT_NAME, {}) if options.debug is not None: syslog.setlogmask(syslog.LOG_UPTO(syslog.LOG_DEBUG)) weewx.debug = 1 else: syslog.setlogmask(syslog.LOG_UPTO(syslog.LOG_INFO)) weewx.debug = 0 if options.filename: data = '' with open(options.filename, "r") as f: data = f.read() record = ColumbiaMicroServerStation.parse_data(data) json.dump(record, sys.stdout) exit(0) url = "http://%s:%s" % (options.host, options.port) if options.url: url = options.url print("get data from %s" % url) data = ColumbiaMicroServerStation.get_data(url) if options.debug: print("data: ", data) record = ColumbiaMicroServerStation.parse_data(data) #print("record: ", record) json.dump(record, sys.stdout)
def main(): syslog.openlog('wee_ip100', syslog.LOG_PID | syslog.LOG_CONS) parser = optparse.OptionParser(usage=usage) parser.add_option('--version', dest='version', action='store_true', help='display driver version') parser.add_option('--debug', dest='debug', action='store_true', help='display diagnostic information while running') parser.add_option('--host', dest='host', metavar="HOST", help='hostname or ip address of the IP-100') parser.add_option('--port', dest='port', type=int, metavar="PORT", default=80, help='port on which IP-100 is listening') parser.add_option('--test-parse', dest='filename', metavar='FILENAME', help='test the xml parsing') (options, _) = parser.parse_args() if options.version: print "ip100 driver version %s" % DRIVER_VERSION exit(1) if options.debug is not None: syslog.setlogmask(syslog.LOG_UPTO(syslog.LOG_DEBUG)) else: syslog.setlogmask(syslog.LOG_UPTO(syslog.LOG_INFO)) if options.filename: data = '' with open(options.filename, "r") as f: data = f.read() packet = IP100Station.parse_data(data) print packet exit(0) url = "http://%s:%s" % (options.host, options.port) print "get data from %s" % url data = IP100Station.get_data(url) if options.debug: print "data: ", data packet = IP100Station.parse_data(data) print "packet: ", packet
def main(): syslog.openlog('wee_tracer', syslog.LOG_PID | syslog.LOG_CONS) parser = optparse.OptionParser(usage=usage) parser.add_option('--version', dest='version', action='store_true', help='display driver version') parser.add_option('--debug', dest='debug', action='store_true', help='display diagnostic information while running') parser.add_option('--port', dest='port', metavar='PORT', help='serial port to which the station is connected', default=Tracer.DEFAULT_PORT) parser.add_option('--baud-rate', dest='baud_rate', metavar='BAUD_RATE', help='modbus slave baud rate', type=int, default=Tracer.DEFAULT_BAUD_RATE) parser.add_option('--timeout', dest='timeout', metavar='TIMEOUT', help='modbus timeout, in seconds', type=int, default=Tracer.DEFAULT_TIMEOUT) (options, _) = parser.parse_args() if options.version: print "driver version %s" % DRIVER_VERSION exit(1) if options.debug is not None: syslog.setlogmask(syslog.LOG_UPTO(syslog.LOG_DEBUG)) else: syslog.setlogmask(syslog.LOG_UPTO(syslog.LOG_INFO)) with Tracer(options.port, options.baud_rate, options.timeout) as station: print("device info:") data = station.get_info() pretty_print(data, 2) print("device ratings:") data = station.get_ratings() pretty_print(data, 2) print("device settings:") data = station.get_settings() pretty_print(data, 2) print("status:") data = station.get_status() pretty_print(data, 2) print("data:") data = station.get_data() pretty_print(data, 2) print("coils:") data = station.get_coils() pretty_print(data, 2) print("statistics:") data = station.get_statistics() pretty_print(data, 2)
def __init__ (self, ident, coreTuple, debug=False, facility=syslog.LOG_USER): if debug: logUpTo=syslog.LOG_DEBUG else: logUpTo=syslog.LOG_INFO if facility is None: facility = syslog.LOG_USER elif facility == "local0": facility = syslog.LOG_LOCAL0 elif facility == "local1": facility = syslog.LOG_LOCAL1 elif facility == "local2": facility = syslog.LOG_LOCAL2 elif facility == "local3": facility = syslog.LOG_LOCAL3 elif facility == "local4": facility = syslog.LOG_LOCAL4 elif facility == "local5": facility = syslog.LOG_LOCAL5 elif facility == "local6": facility = syslog.LOG_LOCAL6 elif facility == "local7": facility = syslog.LOG_LOCAL7 syslog.openlog(ident.encode('UTF-8'), syslog.LOG_PID, facility) syslog.setlogmask(syslog.LOG_UPTO(logUpTo)) self.coretextList = [unicode(x).replace(u',', u',') for x in coreTuple] self.recommendedLogfile = u'/var/log/claritynow/{0}.log'.format(ident)
def setUp(self): global config_path global cwd weewx.debug = 1 syslog.openlog('test_templates', syslog.LOG_CONS) syslog.setlogmask(syslog.LOG_UPTO(syslog.LOG_DEBUG)) # Save and set the current working directory in case some service changes it. if not cwd: cwd = os.getcwd() else: os.chdir(cwd) try : self.config_dict = configobj.ConfigObj(config_path, file_error=True) except IOError: sys.stderr.write("Unable to open configuration file %s" % config_path) # Reraise the exception (this will eventually cause the program to exit) raise except configobj.ConfigObjError: sys.stderr.write("Error while parsing configuration file %s" % config_path) raise # Remove the old directory: try: test_html_dir = os.path.join(self.config_dict['WEEWX_ROOT'], self.config_dict['StdReport']['HTML_ROOT']) shutil.rmtree(test_html_dir) except OSError, e: if os.path.exists(test_html_dir): print >> sys.stderr, "\nUnable to remove old test directory %s", test_html_dir print >> sys.stderr, "Reason:", e print >> sys.stderr, "Aborting" exit(1)
def log_upto(log_level=None): """Set what level of logging we want.""" if log_level is None: log_level = syslog.LOG_INFO elif isinstance(log_level, six.string_types): log_level = log_levels.get(log_level, syslog.LOG_INFO) syslog.setlogmask(syslog.LOG_UPTO(log_level))
def configure(self, config_dict): parser = self.get_parser() self.add_options(parser) options, _ = parser.parse_args() if options.debug is not None: weewx.debug = options.debug syslog.setlogmask(syslog.LOG_UPTO(syslog.LOG_DEBUG)) prompt = False if options.noprompt else True self.do_options(options, parser, config_dict, prompt)
def setLogLevel(level, isDaemon): option = syslog.LOG_PID if not isDaemon: option |= syslog.LOG_PERROR syslog.openlog(str(QApplication.applicationName()), option, syslog.LOG_USER) atexit.register(Application.cleanup) if level == 0: syslog.setlogmask(syslog.LOG_UPTO(syslog.LOG_WARNING)) elif level == 1: syslog.setlogmask(syslog.LOG_UPTO(syslog.LOG_NOTICE)) elif level == 2: syslog.setlogmask(syslog.LOG_UPTO(syslog.LOG_INFO)) else: syslog.setlogmask(syslog.LOG_UPTO(syslog.LOG_DEBUG)) syslog.syslog(syslog.LOG_INFO, "INFO logging to syslog")
def setLevel(self, level): if level != Log.DEBUG and \ level != Log.WARNING and \ level != Log.ERROR and \ level != Log.INFO : raise IncorrectLogLevel else: self.level = level self.syslog_level = Log.syslog_level[level] self.logger.setLevel(self.level) syslog.setlogmask(syslog.LOG_UPTO(self.syslog_level))
def __init__(self, level=WARNING): self.logger = logging.getLogger() formatter = logging.Formatter( "%(name)s %(levelname)s %(asctime)s %(message)s") console = logging.StreamHandler(stream=sys.stderr) console.setFormatter(formatter) self.logger.addHandler(console) syslog.openlog(ident=Log.SYSLOG_IDENT, logoption=syslog.LOG_PID) self.level = level self.syslog_level = Log.syslog_level[level] self.logger.setLevel(self.level) syslog.setlogmask(syslog.LOG_UPTO(syslog.LOG_WARNING))
def setup_logging(_initialized=[False]): """Initialize logging infrastructure.""" # Takes no arguments; see http://effbot.org/zone/default-values.htm if _initialized[0]: syslog.closelog() opts = syslog.LOG_PID | syslog.LOG_NDELAY facility = syslog.LOG_LOCAL0 if _args.facility: fac_name = ''.join(('LOG_', _args.facility.upper())) # We can assert this because we limit choices to _facilities_choices. assert fac_name in dir(syslog) facility = syslog.__dict__[fac_name] syslog.openlog(_pgm[:8], opts, facility) if _args.verbose == 0: syslog.setlogmask(syslog.LOG_UPTO(syslog.LOG_NOTICE)) if _args.verbose == 1: syslog.setlogmask(syslog.LOG_UPTO(syslog.LOG_INFO)) elif _args.verbose > 1: syslog.setlogmask(syslog.LOG_UPTO(syslog.LOG_DEBUG)) _initialized[0] = True return None
def __init__(self, log_facility, log_level_str): try: syslog.openlog(logoption=syslog.LOG_PID, facility=log_facility) except IOError: try: syslog.openlog(syslog.LOG_PID, log_facility) except IOError: try: syslog.openlog('cephlm', syslog.LOG_PID, log_facility) except Exception: raise syslog.setlogmask(syslog.LOG_UPTO(SYSLOG_LEVEL_MAP[log_level_str])) logging.Handler.__init__(self)
def main(debug): global TAG TAG = TAG # Syslog option to append PID & send to facility LOCAL0 for all seisrec logs if debug: #if debug, print syslog output to stderr for manual debugging as well syslog.openlog(ident=TAG, logoption=(syslog.LOG_PID), facility=syslog.LOG_LOCAL0) syslog.setlogmask(syslog.LOG_UPTO(syslog.LOG_DEBUG)) else: syslog.openlog(ident=TAG, logoption=syslog.LOG_PID, facility=syslog.LOG_LOCAL0) syslog.setlogmask(syslog.LOG_UPTO(syslog.LOG_NOTICE)) syslog.syslog(syslog.LOG_NOTICE, "SafeWave Server | " + commitHash) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("localhost", 1883, 60) client.loop_forever() return 0
def setUp(self): global config_path global cwd weewx.debug = 1 syslog.openlog('test_sim', syslog.LOG_CONS) syslog.setlogmask(syslog.LOG_UPTO(syslog.LOG_DEBUG)) # Save and set the current working directory in case some service changes it. if not cwd: cwd = os.getcwd() else: os.chdir(cwd) try: self.config_dict = configobj.ConfigObj(config_path, file_error=True) except IOError: sys.stderr.write("Unable to open configuration file %s" % config_path) # Reraise the exception (this will eventually cause the program to exit) raise except configobj.ConfigObjError: sys.stderr.write("Error while parsing configuration file %s" % config_path) raise # Fiddle with config_dict to reflect the database in use: self.config_dict['DataBindings']['wx_binding'][ 'database'] = self.database (first_ts, last_ts) = _get_first_last(self.config_dict) try: with weewx.manager.open_manager_with_config( self.config_dict, 'wx_binding') as dbmanager: if dbmanager.firstGoodStamp( ) == first_ts and dbmanager.lastGoodStamp() == last_ts: print "\nSimulator need not be run" return except weedb.OperationalError: pass # This will generate the simulator data: engine = weewx.engine.StdEngine(self.config_dict) try: engine.run() except weewx.StopNow: pass
def init_logging(target=TARGET_CONSOLE,level=DEFAULT_LOG_LEVEL): global global_target global global_level if not type(level) is int: raise RuntimeError("Unknown log level value %s" % level) global_target=target global_level=level if target==TARGET_CONSOLE: pass elif target==TARGET_SYSLOG: syslog.openlog("arpwatch",0,syslog.LOG_USER) syslog.setlogmask(syslog.LOG_UPTO(global_level)) else: raise RuntimeError("Unknown target value")
def main(argv, global_vars, local_vars): try: options, remainder = getopt.getopt(argv[1:], 'c:h', ['config=', 'help']) for opt, arg in options: if opt in ('-c', '--config'): config_file = arg # load config file exec( compile(open(config_file).read(), config_file, 'exec'), global_vars, local_vars ) elif opt in ('-h', '--help'): usage(argv) exit(1) except getopt.GetoptError as e: print(e) usage(argv) exit(1) try: syslog.openlog("gandyn", syslog.LOG_PERROR, syslog.LOG_LOCAL0) syslog.setlogmask(syslog.LOG_UPTO(LOG_LEVEL)) syslog.syslog(syslog.LOG_INFO, "Started") public_ip_retriever = ipretriever.adapter.Ipify() gandi_updater = GandiDomainUpdater(API_KEY, DOMAIN_NAME, RECORD) # get DNS record ip address previous_ip_address = gandi_updater.get_record_value() syslog.syslog(syslog.LOG_DEBUG, 'DNS record IP address : %s' % previous_ip_address) # get current ip address current_ip_address = public_ip_retriever.get_public_ip() syslog.syslog(syslog.LOG_DEBUG, 'Current public IP address : %s' % current_ip_address) if current_ip_address != previous_ip_address: # update record value gandi_updater.update_record_value(current_ip_address, TTL) syslog.syslog(syslog.LOG_INFO, 'DNS updated') else: syslog.syslog(syslog.LOG_DEBUG, 'Public IP address unchanged. Nothing to do.') syslog.syslog(syslog.LOG_INFO, "Finished") except xmlrpc.client.Fault as e: syslog.syslog(syslog.LOG_ERR, 'An error occured using Gandi API : %s ' % e) except ipretriever.Fault as e: syslog.syslog(syslog.LOG_ERR, 'An error occured retrieving public IP address : %s' % e)
def loadconfig(): config = ConfigParser.RawConfigParser() try: config.read(config_path) # syslogマスク設定 loglevel = config.get('Global', 'LogLevel') syslog.setlogmask(syslog.LOG_UPTO(LOG[loglevel])) slog(LOG['DEBUG'], "LogLevel: " + loglevel) # その他設定の読み込み global interval, cache, plugindir interval = 24 cache = '/var/cache/ddns' plugindir = os.path.join(os.getcwd(), 'plugin') interval = config.getint('Global', 'UpdateInterval') cache = os.path.normpath(config.get('Global', 'CacheDir')) pdir = config.get('Global', 'PluginDir') if "/" == pdir[0]: plugindir = os.path.normpath(pdir) else: plugindir = os.path.normpath(os.path.join(os.getcwd(), pdir)) slog(LOG['DEBUG'], "UpdateInterval: " + str(interval)) slog(LOG['DEBUG'], "CacheDir: " + cache) slog(LOG['DEBUG'], "PluginDir: " + plugindir) if not os.path.exists(cache): os.makedirs(cache) # IPアドレスチェックサービスリストの読み込み servers = config.items('IPAddrChecker') global ip_checker ip_checker = [] for key, url in servers: ip_checker.append(url) slog(LOG['DEBUG'], "IPChecker: " + url) except ConfigParser.MissingSectionHeaderError: slog(LOG['WARNING'], "MissingSectionHeader") return False except ConfigParser.NoSectionError: slog(LOG['WARNING'], "NoSectionError") return False except ConfigParser.NoOptionError: slog(LOG['WARNING'], "NoOptionError") return False except: slog(LOG['ERR'], "Unexpected error: " + str(sys.exc_info()[:2])) return False return True
def main(): import optparse syslog.openlog('wee_bloomsky', syslog.LOG_PID | syslog.LOG_CONS) parser = optparse.OptionParser(usage=usage) parser.add_option('--version', dest='version', action='store_true', help='display Bloomsky driver version number') parser.add_option('--debug', dest='debug', action='store_true', help='display diagnostic information while running') parser.add_option('--run-driver', dest='run_driver', action='store_true', metavar='RUN_DRIVER', help='run 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') (opts, args) = parser.parse_args() # if --debug raise our log level if opts.debug: 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) # run the driver if opts.run_driver: run_driver(opts.api_key) # get Bloomsky API JSON response if opts.jdata: get_json_data(opts.api_key)
def main(): import optparse syslog.openlog('wee_netatmo', syslog.LOG_PID | syslog.LOG_CONS) parser = optparse.OptionParser(usage=usage) parser.add_option('--version', dest='version', action='store_true', help='display driver version') parser.add_option('--debug', dest='debug', action='store_true', help='display diagnostic information while running') parser.add_option('--run-sniff-driver', dest='ts', action='store_true', help='run the driver in packet sniff mode') parser.add_option('--run-cloud-driver', dest='tc', action='store_true', help='run the driver in cloud client mode') parser.add_option('--test-parse', dest='tp', metavar='FILENAME', help='test the tcp packet parser') parser.add_option('--username', dest='username', metavar='USERNAME', help='username for cloud mode') parser.add_option('--password', dest='password', metavar='PASSWORD', help='password for cloud mode') parser.add_option('--client-id', dest='ci', metavar='CLIENT_ID', help='client_id for cloud mode') parser.add_option('--client-secret', dest='cs', metavar='CLIENT_SECRET', help='client_secret for cloud mode') parser.add_option('--get-stn-data', dest='sdata', action='store_true', help='get formatted station data from cloud') parser.add_option('--get-json-data', dest='jdata', action='store_true', help='get all cloud data as json response') (opts, args) = parser.parse_args() if opts.debug: syslog.setlogmask(syslog.LOG_UPTO(syslog.LOG_DEBUG)) if opts.ts: run_packet_driver() if opts.tc: run_cloud_driver(opts.username, opts.password, opts.ci, opts.cs) if opts.tp: test_parse(options.tp) if opts.sdata: get_station_data(opts.username, opts.password, opts.ci, opts.cs) if opts.jdata: get_json_data(opts.username, opts.password, opts.ci, opts.cs)
def setLevel(self, log_level): '''! Set the current level of logging. @param log_level (int) log level which will be shown on stdout (DEBUG, INFO, WARNING, ERROR or CRITICAL) @exception Raise TypeError if incorrect parameter type ''' if not isString(log_level) and not type(log_level) == int: raise TypeError("Log Level must be a number or a string") if type(log_level) == int: self.__log_level = log_level else: self.__log_level = self.__str_to_int_level(log_level) if type(log_level) == int: if (self.__log_level > self.DEBUG) or (self.__log_level < self.CRITICAL): self.__log_level = self.INFO syslog.setlogmask(syslog.LOG_UPTO(self.__log_level))
def main(): import sys, os script_home = os.path.abspath(os.path.dirname(__file__)) parent = os.path.pardir sys.path.append(os.path.abspath(os.path.join(script_home, parent))) import cfg.globalconfig as globalconfig globalconfig.load_global_config() config = globalconfig.get_global_config() syslog.openlog(config.get("notifier", "name"), logoption=syslog.LOG_PID) syslog.setlogmask( syslog.LOG_UPTO(getattr(syslog, config.get("notifier", "log_level")))) pid_file = config.get("notifier", 'pid_file') if not os.path.isabs(pid_file): # it's relative to our home directory pid_file = os.path.abspath(os.path.join(script_home, pid_file)) show_stats = config.getboolean("notifier", "show_stats") if show_stats: stats_file = config.get("notifier", "stats_file") if not os.path.isabs(stats_file): stats_file = os.path.abspath(os.path.join(script_home, stats_file)) else: stats_file = None notifier = Notifier(address=(config.get("notifier", 'wait_on_address'), config.getint("notifier", 'wait_on_port')), pidfile=pid_file, name=config.get("notifier", 'name'), foreground=config.getboolean("notifier", 'foreground'), listen_queue_len=config.getint("notifier", 'listen_queue_len'), show_stats=show_stats, stats_file=stats_file) notifier.do_from_arg(sys.argv[1] if len(sys.argv) == 2 else None)
def Setup(ident=None, device=None, priority=None, project=None, log_path=None): if InfraLog._CONFIG is not None and InfraLog._CONFIG[ "DEVICE"] & InfraLog.DEV_SYSLOG: syslog.closelog() InfraLog._CONFIG = { "IDENT": ident if ident is not None else "?", "DEVICE": device if device is not None else InfraLog.DEV_NULL, "PRIORITY": priority if priority is not None else InfraLog.PRI_WARNING, "PROJECT": project, "LOGPATH": log_path } if InfraLog._CONFIG["DEVICE"] & InfraLog.DEV_SYSLOG: syslog.openlog(InfraLog._CONFIG["IDENT"], syslog.LOG_PID, syslog.LOG_LOCAL0) syslog.setlogmask(syslog.LOG_UPTO(InfraLog._CONFIG["PRIORITY"])) return
print("example /dev/rfcomm0 or /dev/serial0") port = self._prompt('port', '/dev/serial0') return {'port': port} # define a main entry point for basic testing of the station without weewx # engine and service overhead. invoke this as follows: # PYTHONPATH=/usr/share/weewx python3 bin/user/weatherradio.py if __name__ == '__main__': import optparse usage = """%prog [options] [--help]""" syslog.openlog('weatherradio', syslog.LOG_PID | syslog.LOG_CONS) syslog.setlogmask(syslog.LOG_UPTO(syslog.LOG_DEBUG)) parser = optparse.OptionParser(usage=usage) parser.add_option('--version', dest='version', action='store_true', help='display driver version') parser.add_option('--port', dest='port', metavar='PORT', help='serial port to which the station is connected', default=DEFAULT_PORT) (options, args) = parser.parse_args() if options.version: print("weatherradio driver version %s" % DRIVER_VERSION) exit(0) with Station(options.port) as s: while True: print(time.time(), Station.parse_readings(s.get_readings()))
def main(options, args, engine_class=StdEngine): """Prepare the main loop and run it. Mostly consists of a bunch of high-level preparatory calls, protected by try blocks in the case of an exception.""" # Set the logging facility. syslog.openlog(options.log_label, syslog.LOG_PID | syslog.LOG_CONS) # Set up the signal handlers. signal.signal(signal.SIGHUP, sigHUPhandler) signal.signal(signal.SIGTERM, sigTERMhandler) syslog.syslog(syslog.LOG_INFO, "engine: Initializing weewx version %s" % weewx.__version__) syslog.syslog(syslog.LOG_INFO, "engine: Using Python %s" % sys.version) syslog.syslog(syslog.LOG_INFO, "engine: Platform %s" % platform.platform()) syslog.syslog(syslog.LOG_INFO, "engine: Locale is '%s'" % locale.setlocale(locale.LC_ALL)) # Save the current working directory. A service might # change it. In case of a restart, we need to change it back. cwd = os.getcwd() # Get the path to the configuration file config_path = os.path.abspath(args[0]) if options.daemon: syslog.syslog(syslog.LOG_INFO, "engine: pid file is %s" % options.pidfile) daemon.daemonize(pidfile=options.pidfile) # For backward compatibility, recognize loop_on_init from command-line loop_on_init = options.loop_on_init # Make sure the system time is not out of date (a common problem with the Raspberry Pi). # Do this by making sure the system time is later than the creation time of the config file sane = os.stat(config_path).st_ctime n = 0 while weewx.launchtime_ts < sane: # Log any problems every minute. if n % 120 == 0: syslog.syslog( syslog.LOG_INFO, "engine: Waiting for sane time. Current time is %s" % weeutil.weeutil.timestamp_to_string(weewx.launchtime_ts)) n += 1 time.sleep(0.5) weewx.launchtime_ts = time.time() while True: os.chdir(cwd) config_dict = getConfiguration(config_path) # Look for the debug flag. If set, ask for extra logging weewx.debug = int(config_dict.get('debug', 0)) if weewx.debug: syslog.setlogmask(syslog.LOG_UPTO(syslog.LOG_DEBUG)) else: syslog.setlogmask(syslog.LOG_UPTO(syslog.LOG_INFO)) syslog.syslog(syslog.LOG_DEBUG, "engine: Debug is %s" % weewx.debug) # See if there is a loop_on_init directive in the configuration, but # use it only if nothing was specified via command-line. if loop_on_init is None: loop_on_init = to_bool(config_dict.get('loop_on_init', False)) try: syslog.syslog(syslog.LOG_DEBUG, "engine: Initializing engine") # Create and initialize the engine engine = engine_class(config_dict) syslog.syslog( syslog.LOG_INFO, "engine: Starting up weewx version %s" % weewx.__version__) # Start the engine. It should run forever unless an exception # occurs. Log it if the function returns. engine.run() syslog.syslog( syslog.LOG_CRIT, "engine: Unexpected exit from main loop. Program exiting.") # Catch any console initialization error: except InitializationError as e: # Log it: syslog.syslog(syslog.LOG_CRIT, "engine: Unable to load driver: %s" % e) # See if we should loop, waiting for the console to be ready. # Otherwise, just exit. if loop_on_init: syslog.syslog(syslog.LOG_CRIT, " **** Waiting 60 seconds then retrying...") time.sleep(60) syslog.syslog(syslog.LOG_NOTICE, "engine: retrying...") else: syslog.syslog(syslog.LOG_CRIT, " **** Exiting...") sys.exit(weewx.IO_ERROR) # Catch any recoverable weewx I/O errors: except weewx.WeeWxIOError as e: # Caught an I/O error. Log it, wait 60 seconds, then try again syslog.syslog(syslog.LOG_CRIT, "engine: Caught WeeWxIOError: %s" % e) if options.exit: syslog.syslog(syslog.LOG_CRIT, " **** Exiting...") sys.exit(weewx.IO_ERROR) syslog.syslog(syslog.LOG_CRIT, " **** Waiting 60 seconds then retrying...") time.sleep(60) syslog.syslog(syslog.LOG_NOTICE, "engine: retrying...") except (weedb.CannotConnect, weedb.DisconnectError) as e: # No connection to the database server. Log it, wait 120 seconds, then try again syslog.syslog(syslog.LOG_CRIT, "engine: Database connection exception: %s" % e) if options.exit: syslog.syslog(syslog.LOG_CRIT, " **** Exiting...") sys.exit(weewx.DB_ERROR) syslog.syslog(syslog.LOG_CRIT, " **** Waiting 2 minutes then retrying...") time.sleep(120) syslog.syslog(syslog.LOG_NOTICE, "engine: retrying...") except weedb.OperationalError as e: # Caught a database error. Log it, wait 120 seconds, then try again syslog.syslog( syslog.LOG_CRIT, "engine: Database OperationalError exception: %s" % e) if options.exit: syslog.syslog(syslog.LOG_CRIT, " **** Exiting...") sys.exit(weewx.DB_ERROR) syslog.syslog(syslog.LOG_CRIT, " **** Waiting 2 minutes then retrying...") time.sleep(120) syslog.syslog(syslog.LOG_NOTICE, "engine: retrying...") except OSError as e: # Caught an OS error. Log it, wait 10 seconds, then try again syslog.syslog(syslog.LOG_CRIT, "engine: Caught OSError: %s" % e) weeutil.weeutil.log_traceback(" **** ", syslog.LOG_DEBUG) syslog.syslog(syslog.LOG_CRIT, " **** Waiting 10 seconds then retrying...") time.sleep(10) syslog.syslog(syslog.LOG_NOTICE, "engine: retrying...") except Restart: syslog.syslog(syslog.LOG_NOTICE, "engine: Received signal HUP. Restarting.") except Terminate: syslog.syslog( syslog.LOG_INFO, "engine: Terminating weewx version %s" % weewx.__version__) weeutil.weeutil.log_traceback(" **** ", syslog.LOG_DEBUG) # Reraise the exception (this should cause the program to exit) raise # Catch any keyboard interrupts and log them except KeyboardInterrupt: syslog.syslog(syslog.LOG_CRIT, "engine: Keyboard interrupt.") # Reraise the exception (this should cause the program to exit) raise # Catch any non-recoverable errors. Log them, exit except Exception as ex: # Caught unrecoverable error. Log it, exit syslog.syslog(syslog.LOG_CRIT, "engine: Caught unrecoverable exception in engine:") syslog.syslog(syslog.LOG_CRIT, " **** %s" % ex) # Include a stack traceback in the log: weeutil.weeutil.log_traceback(" **** ", syslog.LOG_CRIT) syslog.syslog(syslog.LOG_CRIT, " **** Exiting.") # Reraise the exception (this should cause the program to exit) raise
def logit(lvl, msg): syslog.openlog(name) syslog.setlogmask(syslog.LOG_UPTO(min_lvl)) syslog.syslog(''.join(('(', LEVELS[lvl], ') ', msg))) syslog.closelog()
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()
def main(options, args, EngineClass=StdEngine): """Prepare the main loop and run it. Mostly consists of a bunch of high-level preparatory calls, protected by try blocks in the case of an exception.""" # Set the logging facility. syslog.openlog('weewx', syslog.LOG_PID | syslog.LOG_CONS) # Set up the signal handlers. signal.signal(signal.SIGHUP, sigHUPhandler) signal.signal(signal.SIGTERM, sigTERMhandler) syslog.syslog(syslog.LOG_INFO, "engine: Initializing weewx version %s" % weewx.__version__) syslog.syslog(syslog.LOG_INFO, "engine: Using Python %s" % sys.version) syslog.syslog(syslog.LOG_INFO, "engine: Platform %s" % platform.platform()) # Save the current working directory. A service might # change it. In case of a restart, we need to change it back. cwd = os.getcwd() if options.daemon: syslog.syslog(syslog.LOG_INFO, "engine: pid file is %s" % options.pidfile) daemon.daemonize(pidfile=options.pidfile) while True: os.chdir(cwd) config_path = os.path.abspath(args[0]) config_dict = getConfiguration(config_path) # Look for the debug flag. If set, ask for extra logging weewx.debug = int(config_dict.get('debug', 0)) if weewx.debug: syslog.setlogmask(syslog.LOG_UPTO(syslog.LOG_DEBUG)) else: syslog.setlogmask(syslog.LOG_UPTO(syslog.LOG_INFO)) try: syslog.syslog(syslog.LOG_DEBUG, "engine: Initializing engine") # Create and initialize the engine engine = EngineClass(config_dict) syslog.syslog( syslog.LOG_INFO, "engine: Starting up weewx version %s" % weewx.__version__) # Start the engine engine.run() # Catch any console initialization error: except InitializationError, e: # Log it: syslog.syslog(syslog.LOG_CRIT, "engine: Unable to load driver: %s" % e) # See if we should loop, waiting for the console to be ready, or exit: if options.loop_on_init: syslog.syslog(syslog.LOG_CRIT, " **** Waiting 60 seconds then retrying...") time.sleep(60) syslog.syslog(syslog.LOG_NOTICE, "engine: retrying...") else: syslog.syslog(syslog.LOG_CRIT, " **** Exiting...") sys.exit(weewx.IO_ERROR) # Catch any recoverable weewx I/O errors: except weewx.WeeWxIOError, e: # Caught an I/O error. Log it, wait 60 seconds, then try again syslog.syslog(syslog.LOG_CRIT, "engine: Caught WeeWxIOError: %s" % e) if options.exit: syslog.syslog(syslog.LOG_CRIT, " **** Exiting...") sys.exit(weewx.IO_ERROR) syslog.syslog(syslog.LOG_CRIT, " **** Waiting 60 seconds then retrying...") time.sleep(60) syslog.syslog(syslog.LOG_NOTICE, "engine: retrying...")
def __enter__(self): self._oldloglevel = syslog.setlogmask(syslog.LOG_UPTO(self._level))