def stop_command(self, index, command, returncode): """ Indicate that a command stopped. :param index: The index of the command. :param command: The command that was executed, as an unicode string. :param returncode: The exit status. """ self.stream.write( self.format_output( "{}\t[{}]\n", " " * (self.longest_len - len(command)), success("success") if returncode == 0 else error("failed"), )) if returncode != 0: self.binary_stream.write(self.output_map[index].getvalue()) self.stream.write( self.format_output( "{}) {} {}\n", warning(important(index + 1)), error("Command exited with"), important(error(returncode)), )) del self.output_map[index]
def pysteon(ctx, debug, root): _setup_logging(debug=debug) ctx.obj = {'debug': debug} logger.debug("Using configuration root at: %s.", important(root)) # Make sure the root directory exists. os.makedirs(root, exist_ok=True) database_path = os.path.join(root, 'database.sqlite') try: logger.debug("Loading database at %s.", important(database_path)) database = Database.load_from_file(database_path) except OSError: logger.debug( "No database found at %s. A default one will be used.", important(database_path), ) database = Database() ctx.obj['database'] = database @ctx.call_on_close def close(): logger.debug("Closing database at %s.", important(database_path)) try: database.close() except OSError as ex: logger.warning( "Could not close database to %s ! Error was: %s", important(database_path), error(str(ex)), )
def close(): logger.debug("Closing database at %s.", important(database_path)) try: database.close() except OSError as ex: logger.warning( "Could not close database to %s ! Error was: %s", important(database_path), error(str(ex)), )
def get_device_info(ctx, device): loop = ctx.obj['loop'] plm = ctx.obj['plm'] info = loop.run_until_complete(plm.get_device_info(device.identity)) logger.info("Device information for: %s", important(device)) logger.info("Ramp rate: %s second(s)", info['ramp_rate']) logger.info("On level: %s", info['on_level']) logger.info("LED level: %d / 100", info['led_level']) logger.info("X10 house code: %s", info['x10_house_code']) logger.info("X10 unit code: %s", info['x10_unit_code'])
def plm(ctx, serial_port_url): logger.debug( "Connecting with PowerLine Modem on serial port: %s. Please wait...", important(serial_port_url), ) loop = ctx.obj['loop'] = asyncio.get_event_loop() plm = ctx.obj['plm'] = PowerLineModem( serial_port_url=serial_port_url, loop=loop, ) @ctx.call_on_close def close(): logger.debug("Closing %s. Please wait...", important(str(plm))) plm.close() logger.debug("Closed %s.", important(str(plm))) logger.debug( "Connected with: %s.", important(str(plm)), )
def monitor(ctx, automate_module): debug = ctx.obj['debug'] loop = ctx.obj['loop'] plm = ctx.obj['plm'] database = ctx.obj['database'] try: logger.info( "Monitoring %s...", important(plm), ) loop.add_signal_handler(signal.SIGINT, plm.interrupt) automate = Automate(plm=plm, database=database, loop=loop) automate.load_module('pysteon.automation.default') if automate_module: automate.load_module(automate_module) async def run(): async with automate: await plm.monitor(on_event_callback=automate.handle_message) try: loop.run_until_complete(run()) finally: loop.remove_signal_handler(signal.SIGINT) logger.info( "No longer monitoring %s.", important(plm), ) except Exception as ex: if debug: logger.exception("Unexpected error.") else: logger.error("Unexpected error: %s.", ex)
def _load_firmware(self, dev): logger.info("Loading firmware: %s", important(self.firmwareFilename)) firmware = array('B') with open(self.firmwareFilename, 'rb') as f: firmware.fromfile(f, 8073) header = array('B', b'\x89\x1f\x2b') # length_l, length_h, ? try: if dev.write(0x1, header + firmware[0:4093]) != 4096: return False if dev.write(0x1, firmware[4093:]) != 3980: return False except usb.core.USBError as e: logger.error("Firmware loading error: " + str(e)) return True
def start_command(self, index, command): """ Indicate that a command stopped. :param index: The index of the command. :param command: The command that is about to be executed, as an unicode string. """ self.stream.write( self.format_output( "{}) {}", warning(important(index + 1)), command, )) self.stream.flush() self.output_map[index] = BytesIO()
def add_watch(self, path): if not ((self.watch_flags & flags.ONLYDIR) and not os.path.isdir(path)): wd = self.inotify.add_watch(path, self.watch_flags) self.wds[wd] = path logger.debug('Watch %s', important(path))
def rm_watch(self, wd): logger.debug('Stop Watching %s', important(self.wds[wd])) self.inotify.rm_watch(wd) self.wds.pop(wd)
def add_watch(self, path): if not ((self.watch_flags & flags.ONLYDIR) and not os.path.isdir(path)): wd = self.inotify.add_watch(path, self.watch_flags) self.wds[wd] = path logger.debug('Watch %s', important(path))
def main(): # check dependencies are available check_exe_available('latexpand') # setup docopt and logging args = docopt(__doc__, version='0.1.1') logger_format = '%(asctime)s [%(levelname)s] - %(message)s' chromalog.basicConfig( level=logging.DEBUG if args['--verbose'] else logging.INFO, format=logger_format) logger = logging.getLogger('texstrip') # disable parser logger logging.getLogger('strip_comments').setLevel(logging.INFO) # the main TeX input file main_file = args['<main>'] logger.info('using {} as the main file'.format(main_file)) # create the target dir output_dir = os.path.join(os.getcwd(), args['--outdir']) os.makedirs(output_dir, exist_ok=True) logger.info("using {} as the output dir".format(output_dir)) # 1) expand the main file target_main_file = os.path.join(output_dir, os.path.basename(main_file)) # names for intermediate files expanded_main_file = os.path.join(output_dir, 'expanded.tex.strip') stripped_main_file = os.path.join(output_dir, 'stripped.tex.strip') if target_main_file == main_file: raise Exception('target main file is the same as the source') cmd = 'latexpand --empty-comments -o {} {}'.format(expanded_main_file, main_file) subprocess.run(cmd, shell=True, check=True) logger.debug('Finished: {}'.format(cmd)) if args['<extra>']: for extra in args['<extra>']: # detect files outside working tree path = pathlib.Path(extra) logging.info("copying %s", path) if str(path.relative_to('.')).startswith('..'): logging.fatal("can't copy files outside current dir %s", extra) sys.exit(1) if path.parent == '.': shutil.copy(path, output_dir) else: new_dir = pathlib.Path(output_dir) / path.parent new_dir.mkdir(parents=True, exist_ok=True) shutil.copy(path, new_dir) # 2) remove comments strip_comments.strip_comments_from_files(expanded_main_file, stripped_main_file) # 3) clean up shutil.copyfile(stripped_main_file, target_main_file) # remove intermediate files unless --keep if not args['--keep']: os.remove(expanded_main_file) os.remove(stripped_main_file) if args['--build']: os.chdir(output_dir) build_cmd = "latexmk -pdf {}".format(target_main_file) subprocess.run(build_cmd, shell=True, check=True) build_cmd = "latexmk -C {}".format(target_main_file) subprocess.run(build_cmd, shell=True, check=True) from chromalog.mark.helpers.simple import success, important logger.info("%s The stripped version is at %s" % (success("Done!"), important(target_main_file)))
def close(): logger.debug("Closing %s. Please wait...", important(str(plm))) plm.close() logger.debug("Closed %s.", important(str(plm)))
def rm_watch(self, wd): logger.debug('Stop Watching %s', important(self.wds[wd])) self.inotify.rm_watch(wd) self.wds.pop(wd)
async def all_link(plm, alias, description): async with plm.all_linking_session(group=group, mode=mode): logger.info( "Waiting for a device to be all-linked for a maximum of %s" " second(s)...", timeout, ) future = plm.wait_all_linking_completed() loop.add_signal_handler(signal.SIGINT, future.cancel) try: all_link_info = await future except asyncio.CancelledError: logger.warning( "All linking was cancelled before completion.", ) return finally: loop.remove_signal_handler(signal.SIGINT) if all_link_info['mode'] is None: logger.warning( "All linking failed with %s-%s (%s) in mode %s.", important(all_link_info['identity']), hex(all_link_info['group']), all_link_info['subcategory'], important(mode), ) else: logger.info( "All linking succeeded with %s-%s (%s) in mode %s.", important(all_link_info['identity']), hex(all_link_info['group']), all_link_info['subcategory'], important(mode), ) identity = all_link_info['identity'] device = database.get_device(identity) # Make sure to keep the existing information. if device: logger.info( "Device %s is known already. Updating the entry.", device, ) if alias is None: alias = device.alias if description is None: description = device.description database.set_device( identity=identity, alias=alias, description=description, category=all_link_info['category'], subcategory=all_link_info['subcategory'], firmware_version=all_link_info['firmware_version'], )
def link(ctx, group, mode, timeout, alias, description): debug = ctx.obj['debug'] loop = ctx.obj['loop'] plm = ctx.obj['plm'] database = ctx.obj['database'] try: logger.info( "Starting all-linking process on %s for group %s in mode '%s'...", important(plm), important(hex(group)), important(mode), ) async def all_link(plm, alias, description): async with plm.all_linking_session(group=group, mode=mode): logger.info( "Waiting for a device to be all-linked for a maximum of %s" " second(s)...", timeout, ) future = plm.wait_all_linking_completed() loop.add_signal_handler(signal.SIGINT, future.cancel) try: all_link_info = await future except asyncio.CancelledError: logger.warning( "All linking was cancelled before completion.", ) return finally: loop.remove_signal_handler(signal.SIGINT) if all_link_info['mode'] is None: logger.warning( "All linking failed with %s-%s (%s) in mode %s.", important(all_link_info['identity']), hex(all_link_info['group']), all_link_info['subcategory'], important(mode), ) else: logger.info( "All linking succeeded with %s-%s (%s) in mode %s.", important(all_link_info['identity']), hex(all_link_info['group']), all_link_info['subcategory'], important(mode), ) identity = all_link_info['identity'] device = database.get_device(identity) # Make sure to keep the existing information. if device: logger.info( "Device %s is known already. Updating the entry.", device, ) if alias is None: alias = device.alias if description is None: description = device.description database.set_device( identity=identity, alias=alias, description=description, category=all_link_info['category'], subcategory=all_link_info['subcategory'], firmware_version=all_link_info['firmware_version'], ) loop.add_signal_handler(signal.SIGINT, plm.interrupt) try: loop.run_until_complete(all_link(plm, alias, description)) finally: loop.remove_signal_handler(signal.SIGINT) except Exception as ex: if debug: logger.exception("Unexpected error.") else: logger.error("Unexpected error: %s.", ex) finally: logger.info("All-linking process completed.")
def info(ctx, fetch): debug = ctx.obj['debug'] loop = ctx.obj['loop'] plm = ctx.obj['plm'] database = ctx.obj['database'] try: logger.info( "Device information for PowerLine Modem on serial port: %s", important(plm.serial_port_url), ) logger.info( "Device category: %s (%s)", important(plm.device_category.title), plm.device_category.examples, ) logger.info( "Device subcategory: %s", important(plm.device_subcategory.title), ) logger.info("Identity: %s", important(plm.identity)) logger.info("Firmware version: %s", important(plm.firmware_version)) controllers, responders = loop.run_until_complete( plm.get_all_link_records(), ) devices = database.get_devices() if fetch: missing_device_identities = { record.identity for record in chain(controllers, responders) if devices.get(record.identity) is None } if missing_device_identities: logger.info( "Fetching missing device information for %d device(s)...", len(missing_device_identities), ) for index, identity in enumerate( missing_device_identities, start=1, ): logger.info( "[%d/%d] %s...", index, len(missing_device_identities), identity, ) try: device_info = loop.run_until_complete( asyncio.wait_for( plm.id_request(identity), 2, ), ) except asyncio.TimeoutError: logger.info( "[%d/%d] %s: %s", index, len(missing_device_identities), identity, error("timed out"), ) else: devices[identity] = database.set_device( identity=device_info['identity'], alias=None, description=None, category=device_info['category'], subcategory=device_info['subcategory'], firmware_version=device_info['firmware_version'], ) logger.info( "[%d/%d] %s: %s", index, len(missing_device_identities), identity, success("success"), ) logger.info("Done fetching missing device information.") if controllers: logger.info("Controllers:") for controller in controllers: device = devices.get(controller.identity) if device: logger.info("%s - %s", controller, success(device)) else: logger.info("%s", controller) if responders: logger.info("Responders:") for responder in responders: device = devices.get(responder.identity) if device: logger.info("%s - %s", responder, success(device)) else: logger.info("%s", responder) except Exception as ex: if debug: logger.exception("Unexpected error.") else: logger.error("Unexpected error: %s.", ex)
import logging import chromalog from chromalog.mark.helpers.simple import success, error, important chromalog.basicConfig(format="%(message)s", level=logging.INFO) logger = logging.getLogger() filename = r'/var/lib/status' logger.info("Booting up system: %s", success("OK")) logger.info("Booting up network: %s", error("FAIL")) logger.info("Reading file at %s: %s", important(filename), success("OK"))
error, ) formatter = ColorizingFormatter('[%(levelname)s] %(message)s') handler = ColorizingStreamHandler() handler.setFormatter(formatter) logger = logging.getLogger() logger.setLevel(logging.DEBUG) logger.addHandler(handler) logger.info("This is a regular info log message.") logger.info( "Trying to read user information from %s using a json parser.", important(r'/usr/local/mylib/user-info.json'), ) logger.warning( "Unable to read the file at %s ! Something is wrong.", important(r'/usr/local/mylib/user-info.json'), ) logger.error("Something went really wrong !") logger.info( "This is a %s and this is an %s.", success("success"), error("error"), ) logger.info( "You can combine %s and %s to get an %s !", success("success"), important("important"),