def __init__(self, log_level=log.INFO, use_curses=False, win_size=(24, 80)): self.TITLE = self.__doc__.split('\n')[0].rstrip('.').strip() if use_curses: try: import curses except ImportError: self._curses = None else: self._curses = curses self._init_curses(win_size) else: self._curses = None root_logger = log.getLogger() self.curses_log_handler = None if use_curses: # route log messages to a file to avoid messages # "polluting" the display from pybot.core.log import FileHandler hndlr = FileHandler(self.__class__.__name__ + '.log', mode='w') hndlr.setFormatter(root_logger.handlers[0].formatter) # replaces the default handler which outputs messages on the console root_logger.handlers[0] = hndlr self.log_stream = open(hndlr.baseFilename) # add a handler for displaying them in curses hndlr = self.get_curses_log_handler() if hndlr: root_logger.addHandler(hndlr) self.curses_log_handler = hndlr root_logger.setLevel(log_level) root_logger.info("log level set to : %s", log.getLevelName(root_logger.getEffectiveLevel())) self.log = log.getLogger(self.__class__.__name__) self.log.info("log level set to : %s", log.getLevelName(self.log.getEffectiveLevel())) GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) self.spi = DSPinSpiDev(spi_bus=0, spi_dev=0)
def __init__(self, arm, panel, logger): self.arm = arm self.panel = panel self.logger = logger or log.getLogger(name=self.__class__.__name__) self._terminated = False self._worker = None
def start(self): logger = log.getLogger() logger.info((' ' + self.TITLE + ' ').center(80, '-')) interrupted = False try: log.info('>>> Setting up') self.setup() log.info('>>> Running (Ctrl-C to interrupt)') self.run() except KeyboardInterrupt: print("\010\010 ") self.log.warn('--- Interrupted ---') interrupted = True except Exception as e: self.log.exception("Unexpected error: %s", e) finally: log.info('>>> Cleanup') self.cleanup(interrupted) if self.curses_log_handler: self.curses_log_handler.enabled = False if self._curses: log.info('>>> curses cleanup') curses = self._curses self.win_main.keypad(0) curses.nocbreak() curses.echo() curses.endwin() log.info('>>> All done.')
# -*- coding: utf-8 -*- import time from .core import Register, DmxlError from pybot.dynamixel.dmxl_bus_intf import DynamixelBusInterface import pybot.core.log as logging __author__ = 'Eric Pascual' logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) class Joint(object): """ Joints are moved by servos, and this class acts as the interface between the user's vision based in terms of the physical aspects of the joint and the corresponding commands and settings of the servo. By instance, when dealing with position we talk about angles and not servo steps. """ ORIENTATION_CCW = 1 ORIENTATION_CW = -1 DEFAULT_SETUP = { 'angles_origin': 0, 'angles_orientation': ORIENTATION_CCW, 'angles_range': (0, 300), 'angles_resolution': 300. / 1023, 'speed_resolution': 360. * 114 / 1023 / 60, }
def run_daemon(mount_point, dev_type='LCD03', no_splash=False): daemon_logger = log.getLogger('daemon') try: from pybot.raspi import i2c_bus except ImportError: from dummy import DummyDevice device = DummyDevice() daemon_logger.warn('not running on RasPi => using dummy device') else: if dev_type == 'lcd03': from pybot.lcd.lcd_i2c import LCD03 device_class = LCD03 elif dev_type == 'lcd05': from pybot.lcd.lcd_i2c import LCD05 device_class = LCD05 elif '.' in dev_type: parts = dev_type.split('.') module_name = '.'.join(parts[:-1]) class_name = parts[-1] try: import importlib module = importlib.import_module(module_name) except ImportError: raise DaemonError( 'unsupported device type (module not found: %s)' % module_name) else: try: device_class = getattr(module, class_name) except AttributeError: raise DaemonError( 'unsupported device type (class not found: %s)' % dev_type) else: raise DaemonError('unsupported device type (%s)' % dev_type) if device_class: from pybot.lcd.ansi import ANSITerm daemon_logger.info('terminal device type : %s', device_class.__name__) device = ANSITerm(device_class(i2c_bus)) else: raise DaemonError('cannot determine device type') def cleanup_mount_point(mp): [os.remove(p) for p in glob.glob(os.path.join(mp, '*'))] exit_code = 1 # suppose error by default try: mount_point = os.path.abspath(mount_point) cleanup_mount_point(mount_point) daemon_logger.info('starting FUSE daemon (mount point: %s)', mount_point) FUSE(LCDFSOperations(device, no_splash), mount_point, nothreads=True, foreground=False, debug=False, direct_io=True, allow_other=True) daemon_logger.info('returned from FUSE()') except Exception as e: daemon_logger.fatal(e) exit_code = 1 else: exit_code = 0 finally: daemon_logger.info("cleaning up mount point") cleanup_mount_point(mount_point) daemon_logger.info('exiting with code=%d', exit_code) return exit_code
def main(): """ No-arg main, for usage as console_script setup entry point ..see:: setuptools documentation """ log_dir = "/var/log" if os.geteuid() == 0 else os.path.expanduser('~') logging.config.dictConfig( log.get_logging_configuration({ 'handlers': { 'file': { 'filename': os.path.join(log_dir, 'lcdfs.log'), } } })) logger = log.getLogger() logger.info('-' * 40) logger.info('Starting') try: import pkg_resources except ImportError: pass else: PKG_NAME = 'pybot-lcd-fuse' version = pkg_resources.require(PKG_NAME)[0].version logger.info('Version : %s', version) logger.info('-' * 40) BUILTIN_TYPES = ('lcd03', 'lcd05') def dev_type(s): if '.' in s or s.lower() in BUILTIN_TYPES: return s raise ArgumentTypeError('invalid LCD type') def existing_dir(s): if not os.path.isdir(s): raise ArgumentTypeError('path not found or not a dir (%s)' % s) return s parser = cli.get_argument_parser() parser.add_argument('mount_point', nargs='?', help='file system mount point', type=existing_dir, default='/mnt/lcdfs') parser.add_argument( '-t', '--device-type', dest='dev_type', type=dev_type, default=BUILTIN_TYPES[0], help="type of LCD, either builtin (%s) or fully qualified class name" % ('|'.join(BUILTIN_TYPES))) parser.add_argument( '--no-splash', dest='no_splash', action='store_true', help="do not display the default splash text (host name, IP,...)") args = parser.parse_args() logger.setLevel(logging.DEBUG if args.verbose else logging.INFO) def log_error_banner(error, unexpected=False): title = 'unexpected error' if unexpected else 'abnormal termination ' logger.fatal((' ' + title + ' ').center(40, '!')) logger.fatal(error) logger.fatal('!' * 40) try: run_daemon(args.mount_point, args.dev_type, args.no_splash) except DaemonError as e: log_error_banner(e) except Exception as e: log_error_banner(e, unexpected=True) else: logger.info(' terminated normally '.center(40, '='))
#!/usr/bin/env python # -*- coding: utf-8 -*- from pybot.core import log _log = log.getLogger(__name__) class SpiDev(object): def open(self, bus, device): _log.warn('open(%s, %s)', bus, device) def close(self): _log.warn('close()') def xfer(self, data): _log.warn('xfer(%s)', data) return [0] * len(data) def xfer2(self, data): _log.warn('xfer2(%s)', data) return [0] * len(data)
# -*- coding: utf-8 -*- import unittest from pybot.core import log from pybot.youpi2.kin import Kinematics __author__ = 'Eric Pascual' log.logging.basicConfig(format="%(msg)s") logger = log.getLogger() class IKTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.kin = Kinematics(parent=logger) cls.kin.log_setLevel(log.DEBUG) def test_01(self): q = self.kin.ik( 2 * Kinematics.L_SEGMENT + Kinematics.L_GRIPPER - Kinematics.X_OFFSET_FROM_ROTATION_AXIS, 0, Kinematics.Z_SHOULDER, 0) for angle, expected in zip(q, [0.0, 90.0, 0.0, 0.0]): self.assertAlmostEqual(angle, expected, places=1) def test_02(self): q = self.kin.ik( Kinematics.L_SEGMENT - Kinematics.X_OFFSET_FROM_ROTATION_AXIS, 0, Kinematics.Z_SHOULDER - Kinematics.L_SEGMENT -