Ejemplo n.º 1
0
def _reconfigure():
    try:
        from echomesh.base import Settings
    except:
        _SETTINGS.settings_update(None)
    else:
        Settings.add_client(_SETTINGS)
Ejemplo n.º 2
0
def _reconfigure():
    try:
        from echomesh.base import Settings
    except:
        _SETTINGS.settings_update(None)
    else:
        Settings.add_client(_SETTINGS)
Ejemplo n.º 3
0
 def __init__(self, instance, peers, settings_name):
     super(PeerSocketBase, self).__init__()
     self.instance = instance
     self.peers = peers
     self.settings_name = settings_name
     self.add_slave(self.peers)
     self.port = -1
     self.socket = None
     Settings.add_client(self)
Ejemplo n.º 4
0
def set_settings(_, *values):
    if values:
        assignment = Leafs.leafs(Settings.assign(values))
        for address, value in six.iteritems(assignment):
            LOGGER.info('Set %s=%s', '.'.join(address), value)
        Settings.update_clients()
    elif Settings.MERGE_SETTINGS.has_changes():
        LOGGER.info(
            Yaml.encode_one(dict(Settings.MERGE_SETTINGS.get_changes())))
    else:
        LOGGER.info('You have made no changes.')
Ejemplo n.º 5
0
def set_settings(_, *values):
    if values:
        assignment = Leafs.leafs(Settings.assign(values))
        for address, value in six.iteritems(assignment):
            LOGGER.info('Set %s=%s', '.'.join(address), value)
        Settings.update_clients()
    elif Settings.MERGE_SETTINGS.has_changes():
        LOGGER.info(
            Yaml.encode_one(dict(Settings.MERGE_SETTINGS.get_changes())))
    else:
        LOGGER.info('You have made no changes.')
Ejemplo n.º 6
0
 def __init__(self, port, bind_port, hostname, socket_type):
     super(Socket, self).__init__()
     self.port = port
     self.bind_port = bind_port
     self.hostname = hostname
     self.socket_type = socket_type
     self.socket = None
     self.buffer = ''
     self.queue = queue.Queue()
     self.max_size = MAX_SIZE
     Settings.add_client(self)
Ejemplo n.º 7
0
 def _on_run(self):
     super(ScoreMaster, self)._on_run()
     if self.startup:
         self.startup = False
         try:
             self._load_elements(Settings.get('load'))
         except:
             LOGGER.error()
         try:
             self.start_elements(Settings.get('start'))
         except:
             LOGGER.error()
Ejemplo n.º 8
0
 def _on_run(self):
     super(ScoreMaster, self)._on_run()
     if self.startup:
         self.startup = False
         try:
             self._load_elements(Settings.get('load'))
         except:
             LOGGER.error()
         try:
             self.start_elements(Settings.get('start'))
         except:
             LOGGER.error()
Ejemplo n.º 9
0
 def callback(self, data):
     data = Yaml.decode_one(data)
     event = data['event']
     if event == 'start':
         self.after_server_starts()
     elif event == 'closeButtonPressed':
         if Settings.get('execution', 'close_button_quits'):
             Quit.request_quit()
         elif Settings.get('execution', 'close_button_closes_window'):
             Visualizer.set_visible(False)
     else:
         # print(data)
         pass
Ejemplo n.º 10
0
def transfer(_, **data):
    backup_directory = os.path.join(Path.data_path(), '.echomesh-xfer')

    try:
        shutil.rmtree(backup_directory)
    except OSError:
        pass

    directories = data.get('directories', [])
    if '' in directories:
        directories = os.listdir(Path.data_path())

    for directory in directories:
        parent = os.path.dirname(os.path.join(backup_directory, directory))
        MakeDirs.parent_makedirs(parent)
        shutil.move(os.path.join(Path.data_path(), directory), parent)

    for f, value in six.iteritems(data.get('files')):
        fname = os.path.join(Path.data_path(), f)
        MakeDirs.parent_makedirs(fname)
        with open(fname, 'w') as o:
            o.write(value['contents'])
        os.utime(fname, (value['atime'], value['mtime']))

    if Settings.get('execution', 'delete_backups_after_transfer'):
        try:
            shutil.rmtree(backup_directory)
        except:
            pass
Ejemplo n.º 11
0
 def get(self, *path):
     with self.lock:
         value = self.clients.get(path)
         if not value:
             value = Expression.convert(Settings.get(*path))
             self.clients[path] = value
         return value
Ejemplo n.º 12
0
 def get(self, *path):
     with self.lock:
         value = self.clients.get(path)
         if not value:
             value = Expression.convert(Settings.get(*path))
             self.clients[path] = value
         return value
Ejemplo n.º 13
0
def save(_, *values):
    if values:
        SetSettings.set_settings(_, *values)
    files = Settings.save(False)
    if files:
        LOGGER.info('Settings saved to %s.', Join.join_file_names(files))
    else:
        LOGGER.error('There are no settings changes to save.')
Ejemplo n.º 14
0
def display(callback):
    use_pi3d = Settings.get('pi3d', 'enable')
    if use_pi3d:
        from echomesh.graphics.Pi3dDisplay import Pi3dDisplay
        return Pi3dDisplay()

    else:
        from echomesh.graphics.CDisplay import CDisplay
        return CDisplay(callback)
Ejemplo n.º 15
0
def display(callback):
    use_pi3d = Settings.get('pi3d', 'enable')
    if use_pi3d:
        from echomesh.graphics.Pi3dDisplay import Pi3dDisplay
        return Pi3dDisplay()

    else:
        from echomesh.graphics.CDisplay import CDisplay
        return CDisplay(callback)
Ejemplo n.º 16
0
    def __init__(self, count=None, order='rgb', device=DEFAULT_SPI_DEVICE,
                 gamma=DEFAULT_GAMMA, period=None, **description):
        self.enabled = SetupDebianSpiLights.lights_enabled()
        if not self.enabled:
            LOGGER.info('SPI running in emulation mode.')
        self.gamma = gamma
        self.order = cechomesh.get_spi_order(order)
        self.period = period
        self.period_set = period is not None

        self.count_set = count is not None
        if self.count_set:
            self._set_count(count)
        Settings.add_client(self)
        if self.enabled:
            self._device = open(device, 'wb')
        super(Spi, self).__init__(
          is_redirect=False, period=self.period, **description)
Ejemplo n.º 17
0
 def __init__(self, parent, description):
     super(Audio, self).__init__(parent, description)
     if Settings.get('audio', 'output', 'enable'):
         try:
             self.add_mutual_pause_slave(CPlayer(self, **description))
         except:
             LOGGER.error()
     else:
         LOGGER.info('Audio disabled for %s', description.get('file', None))
     description.clear_accessed()
Ejemplo n.º 18
0
 def __init__(self, parent, description):
     super(Audio, self).__init__(parent, description)
     if Settings.get('audio', 'output', 'enable'):
         try:
             self.add_mutual_pause_slave(CPlayer(self, **description))
         except:
             LOGGER.error()
     else:
         LOGGER.info('Audio disabled for %s', description.get('file', None))
     description.clear_accessed()
Ejemplo n.º 19
0
    def _evaluate(self):
        color_list = cechomesh.to_color_list(self.patterns()[0])

        columns = (color_list.columns or
                   Settings.get('light', 'visualizer', 'layout')[0])

        result = cechomesh.scroll_color_list(
          color_list, self.get('dx'), self.get('dy'), columns=columns,
          wrap=self.get('wrap'), smooth=self.get('smooth'),
          transform=self.get('transform'))
        return result
Ejemplo n.º 20
0
    def __init__(self):
        super(Instance, self).__init__()

        def do_quit():
            pause_outputs()
            self.pause()
            self.unload()

        Quit.register_atexit(do_quit)
        gpio = Settings.get('hardware', 'gpio')
        if gpio['enable']:
            GPIO.on_gpio(Quit.request_quit,
                         gpio['shutdown_pin'],
                         gpio['shutdown_pin_pull_up'],
                         gpio['shutdown_pin_bounce_time'])

        CLog.initialize()
        self.score_master = ScoreMaster.ScoreMaster()
        self.peers = Peers.Peers(self)
        self.socket = PeerSocket.PeerSocket(self, self.peers)

        self.display = Display.display(self.callback)
        self.keyboard_runnable = self.osc = None
        if Settings.get('execution', 'control_program'):
            from echomesh.util.thread import Keyboard
            args = {}
            keyboard, self.keyboard_runnable = Keyboard.keyboard(
              self, new_thread=USE_KEYBOARD_THREAD or self.display)

        osc_client = Settings.get('osc', 'client', 'enable')
        osc_server = Settings.get('osc', 'server', 'enable')
        if osc_client or osc_server:
            from echomesh.sound.Osc import Osc
            self.osc = Osc(osc_client, osc_server)

        self.add_mutual_pause_slave(
            self.socket, self.keyboard_runnable, self.osc)
        self.add_slave(self.score_master)
        self.add_slave(self.display)
        self.set_broadcasting(False)
        self.timeout = Settings.get('network', 'timeout')
Ejemplo n.º 21
0
 def __init__(self, parent, description):
     super(Image, self).__init__(parent, description)
     if Settings.get('pi3d', 'enable'):
         try:
             self.sprite = ImageSprite(self, **description)
         except:
             LOGGER.error("Couldn't open image file")
         else:
             self.add_slave(self.sprite)
     else:
         LOGGER.info('Playing image %s', description.get('file', '(none)'))
     description.clear_accessed()
Ejemplo n.º 22
0
 def after_server_starts(self):
     if cechomesh.LOADED:
         run_after(self.run,
                   Expression.convert(Settings.get('execution',
                                                   'delay_before_run')))
     else:
         self.run()
         if self.display:
             self.display_loop()
         elif not USE_KEYBOARD_THREAD and self.keyboard_runnable:
             self.keyboard_runnable.loop()
         else:
             while self.is_running:
                 time.sleep(self.timeout)
Ejemplo n.º 23
0
def get_settings(_, *items):
    failures = []
    if items:
        successes = []
        for i in items:
            parts = i.split('.')
            try:
                value = Settings.get(*parts)
            except:
                failures.append(i)
            else:
                successes.append([i, value])
    else:
        assignments = Settings.assignments().items()
        successes = [('.'.join(s), v) for s, v in assignments]

    if successes or failures:
        for value, result in successes:
            LOGGER.info('%s=%s', value, result)
        if failures:
            LOGGER.error('Didn\'t understand %s', Join.join_words(failures))
        LOGGER.info('')
    else:
        LOGGER.info('No settings variables have been set.\n')
Ejemplo n.º 24
0
    def __init__(self,
                 count=None,
                 order='rgb',
                 device=DEFAULT_SPI_DEVICE,
                 gamma=DEFAULT_GAMMA,
                 period=None,
                 **description):
        self.enabled = SetupDebianSpiLights.lights_enabled()
        if not self.enabled:
            LOGGER.info('SPI running in emulation mode.')
        self.gamma = gamma
        self.order = cechomesh.get_spi_order(order)
        self.period = period
        self.period_set = period is not None

        self.count_set = count is not None
        if self.count_set:
            self._set_count(count)
        Settings.add_client(self)
        if self.enabled:
            self._device = open(device, 'wb')
        super(Spi, self).__init__(is_redirect=False,
                                  period=self.period,
                                  **description)
Ejemplo n.º 25
0
def get_settings(_, *items):
    failures = []
    if items:
        successes = []
        for i in items:
            parts = i.split('.')
            try:
                value = Settings.get(*parts)
            except:
                failures.append(i)
            else:
                successes.append([i, value])
    else:
        assignments = Settings.assignments().items()
        successes = [('.'.join(s), v) for s, v in assignments]

    if successes or failures:
        for value, result in successes:
            LOGGER.info('%s=%s', value, result)
        if failures:
            LOGGER.error('Didn\'t understand %s', Join.join_words(failures))
        LOGGER.info('')
    else:
        LOGGER.info('No settings variables have been set.\n')
Ejemplo n.º 26
0
    def _evaluate(self):
        color_list = cechomesh.to_color_list(self.patterns()[0])

        columns = (color_list.columns or
                   Settings.get('light', 'visualizer', 'layout')[0])

        result = cechomesh.scroll_color_list(
          color_list, self.get('dx'), self.get('dy'), columns=columns,
          wrap=self.get('wrap'), smooth=self.get('smooth'),
          transform=self.get('transform'))
        global LAST_LIST
        if False and result != LAST_LIST:
            LAST_LIST = result
            print(result, color_list)
        return result
Ejemplo n.º 27
0
def _settings(_, *names):
    settings = Settings.get_settings()
    names = set(names)
    keys = set(settings.keys())
    if 'all' in names:
        names = keys

    bad = names - set(settings.keys())
    if bad:
        LOGGER.error("Don't understand settings %s.", join_words(bad))
        names -= bad
    if names:
        _format(dict((k, v) for k, v in settings.items() if k in names))
    else:
        LOGGER.info('    Possible settings are:\n    ' +
                    join_words(settings.keys()))
Ejemplo n.º 28
0
    def _evaluate(self):
        color_lists = self.patterns()
        assert len(color_lists) == 1
        color_list = color_lists[0]

        columns = self.get('columns') or getattr(color_list, 'columns', 0)
        rows = self.get('rows')

        if rows:
            columns = columns or cechomesh.compute_rows(len(color_list), rows)
        elif columns:
            rows = cechomesh.compute_rows(len(color_list), columns)
        else:
            columns, rows = Settings.get('light', 'visualizer', 'layout')

        return cechomesh.mirror_color_list(color_list, int(columns), int(rows),
                                           bool(self.get('reverse_x')),
                                           bool(self.get('reverse_y')))
Ejemplo n.º 29
0
def keyboard(instance, writer=sys.stdout, reader=sys.stdin.readline,
             new_thread=True):
    def processor(line):
        try:
            return Command.execute(instance, line)
        except:
            LOGGER.error('Error processing command line.')

    sleep = Expression.convert(Settings.get('execution',
                                            'delay_before_keyboard_activates'))
    keyboard = Keyboard(sleep=sleep, message=MESSAGE, processor=processor,
                        writer=writer, reader=reader)
    if new_thread:
        runnable = ThreadRunnable(target=keyboard.loop)
        runnable.add_mutual_pause_slave(keyboard)
        return keyboard, runnable
    else:
        return keyboard, keyboard
Ejemplo n.º 30
0
    def _evaluate(self):
        color_lists = self.patterns()
        assert len(color_lists) == 1
        color_list = color_lists[0]

        columns = self.get('columns') or getattr(color_list, 'columns', 0)
        rows = self.get('rows')

        if rows:
            columns = columns or cechomesh.compute_rows(len(color_list), rows)
        elif columns:
            rows = cechomesh.compute_rows(len(color_list), columns)
        else:
            columns, rows = Settings.get('light', 'visualizer', 'layout')

        return cechomesh.mirror_color_list(
          color_list, int(columns), int(rows),
          bool(self.get('reverse_x')), bool(self.get('reverse_y')))
Ejemplo n.º 31
0
    def __init__(self):
        super(Pi3dDisplay, self).__init__()
        self.timeout = Expression.convert(Settings.get('network', 'timeout'))
        keywords = {}

        background = Settings.get('pi3d', 'background')
        if background:
            keywords.update(background=background)

        dimensions = Settings.get('pi3d', 'dimensions')
        if dimensions:
            x, y, width, height = dimensions
            keywords.update(x=x, y=y, width=width, height=height)

        for k in ['aspect', 'depth', 'far', 'near', 'tk', 'window_title']:
            keywords[k] = Settings.get('pi3d', k)

        from pi3d import Display
        self.display = Display.create(**keywords)
        Settings.add_client(self)
        Shader.SHADER()
Ejemplo n.º 32
0
    def __init__(self):
        super(Pi3dDisplay, self).__init__()
        self.timeout = Expression.convert(Settings.get('network', 'timeout'))
        keywords = {}

        background = Settings.get('pi3d', 'background')
        if background:
            keywords.update(background=background)

        dimensions = Settings.get('pi3d', 'dimensions')
        if dimensions:
            x, y, width, height = dimensions
            keywords.update(x=x, y=y, width=width, height=height)

        for k in ['aspect', 'depth', 'far', 'near', 'tk', 'window_title']:
            keywords[k] = Settings.get('pi3d', k)

        from pi3d import Display
        self.display = Display.create(**keywords)
        Settings.add_client(self)
        Shader.SHADER()
Ejemplo n.º 33
0
def _route_items(items, successes, failures):
    for v in items:
        try:
            successes.append([v, Settings.get(*v.split('.'))])
        except:
            failures.append(v)
Ejemplo n.º 34
0
def _main():
    import sys

    times = []

    def p(msg=''):
        """Print progress messages while echomesh loads."""
        print(msg, end='\n' if msg else '')
        global COUNT
        dot = str(COUNT % 10) if USE_DIGITS_FOR_PROGRESS_BAR else '.'
        print(dot, end='')
        COUNT += 1

        sys.stdout.flush()

        import time
        times.append(time.time())

    p('Loading echomesh ')

    from echomesh.base import Version
    if Version.TOO_NEW:
        print(Version.ERROR)

    from echomesh.base import Path
    if not Path.project_path():
        return
    p()

    Path.fix_home_directory_environment_variable()
    p()

    Path.fix_sys_path()
    p()

    from echomesh.base import Settings
    p()

    Settings.read_settings(sys.argv[1:])
    p()

    if Settings.get('execution', 'autostart') and not Settings.get(
            'permission', 'autostart'):
        print()
        from echomesh.util import Log
        Log.logger(__name__).info('No permission to autostart')
        return
    p()

    from echomesh.base import Quit
    p()

    Quit.register_atexit(Settings.save)
    p()

    from echomesh.Instance import Instance
    p()

    instance = Instance()
    print()
    p()

    if Settings.get('diagnostics', 'startup_times'):
        print()
        for i in range(len(times) - 1):
            print(i, ':', int(1000 * (times[i + 1] - times[i])))
        print()

    instance.main()
Ejemplo n.º 35
0
def input_level_maker():
    return cechomesh.AudioLoudness(
        name=Settings.get('audio', 'input', 'device_name'),
        channels=Settings.get('audio', 'input', 'channels'),
        chunk_size=Settings.get('audio', 'input', 'chunk_size'),
        sample_rate=Settings.get('audio', 'input', 'sample_rate')).loudness
Ejemplo n.º 36
0
 def f(echomesh_instance, **_):
     name = function.__name__.strip('_')
     if Settings.get('permission', name):
         function(echomesh_instance)
     else:
         LOGGER.error("You don't have permission to run '%s'.", name)
Ejemplo n.º 37
0
 def __init__(self, *sockets):
     super(SelectLoop, self).__init__(name='SelectLoop')
     self.sockets = dict((s.socket, s) for s in sockets)
     Settings.add_client(self)
Ejemplo n.º 38
0
 def f(echomesh_instance, **_):
     name = function.__name__.strip('_')
     if Settings.get('permission', name):
         function(echomesh_instance)
     else:
         LOGGER.error("You don't have permission to run '%s'.", name)
Ejemplo n.º 39
0
def _main():
    import sys

    times = []

    def p(msg=''):
        """Print progress messages while echomesh loads."""
        print(msg, end='\n' if msg else '')
        global COUNT
        dot = str(COUNT % 10) if USE_DIGITS_FOR_PROGRESS_BAR else '.'
        print(dot, end='')
        COUNT += 1

        sys.stdout.flush()

        import time
        times.append(time.time())

    p('Loading echomesh ')

    from echomesh.base import Version
    if Version.TOO_NEW:
        print(Version.ERROR)

    from echomesh.base import Path
    if not Path.project_path():
        return
    p()

    Path.fix_home_directory_environment_variable()
    p()

    Path.fix_sys_path()
    p()

    from echomesh.base import Settings
    p()

    Settings.read_settings(sys.argv[1:])
    p()

    if Settings.get('execution', 'autostart') and not Settings.get(
            'permission', 'autostart'):
        print()
        from echomesh.util import Log
        Log.logger(__name__).info('No permission to autostart')
        return
    p()

    from echomesh.base import Quit
    p()

    Quit.register_atexit(Settings.save)
    p()

    from echomesh.Instance import Instance
    p()

    instance = Instance()
    print()
    p()

    if Settings.get('diagnostics', 'startup_times'):
        print()
        for i in range(len(times) - 1):
            print(i, ':', int(1000 * (times[i + 1] - times[i])))
        print()

    instance.main()
Ejemplo n.º 40
0
 def _on_run(self):
     super(OscClient, self)._on_run()
     self.client = None
     self.port = None
     self.host = None
     Settings.add_client(self)
Ejemplo n.º 41
0
 def settings_update(self, get):
     with self.lock:
         for path in self.clients.keys():
             self.clients[path] = Expression.convert(Settings.get(*path))
Ejemplo n.º 42
0
 def _on_pause(self):
     Settings.remove_client(self)
     super(OscClient, self)._on_pause()
     self.client.close()
     self.client = None
Ejemplo n.º 43
0
 def __init__(self):
     self.clients = {}
     self.lock = Lock.Lock()
     Settings.add_client(self)
Ejemplo n.º 44
0
def lights_enabled(prompt_to_fix=False):
    global _LIGHTS_ENABLED
    if _LIGHTS_ENABLED is None:
        _LIGHTS_ENABLED = (Settings.get('light', 'enable')
                           and _test_spi(prompt_to_fix)) or False
    return _LIGHTS_ENABLED
Ejemplo n.º 45
0
 def __init__(self):
     super(OscServer, self).__init__()
     self.server = None
     self.port = None
     Settings.add_client(self)
Ejemplo n.º 46
0
def _allowed(operation):
    return Settings.get('permission', operation)
Ejemplo n.º 47
0
 def __init__(self):
     Settings.add_client(self)
Ejemplo n.º 48
0
def initialize():
    cechomesh.LOADED and cechomesh.init_log()
    Settings.add_client(_Redirector())
Ejemplo n.º 49
0
def _allowed(operation):
    return Settings.get('permission', operation)
Ejemplo n.º 50
0
def _route_items(items, successes, failures):
    for v in items:
        try:
            successes.append([v, Settings.get(*v.split('.'))])
        except:
            failures.append(v)
Ejemplo n.º 51
0
 def __init__(self):
     super(OscServer, self).__init__()
     self.server = None
     self.port = None
     Settings.add_client(self)
Ejemplo n.º 52
0
 def __init__(self, *sockets):
     super(SelectLoop, self).__init__(name='SelectLoop')
     self.sockets = dict((s.socket, s) for s in sockets)
     Settings.add_client(self)