Exemplo n.º 1
0
def parse_config(ctx, param, value):
    if not value:
        raise click.BadParameter('This option is required')
    else:
        cfg = file_helper.read(value)
        if not cfg:
            raise click.BadParameter(f'File "{value}" not found')

        try:
            if type(cfg['applications']) != ruamel.yaml.comments.CommentedSeq:
                raise click.BadParameter(f'The "applications" must be a list')

            for app in cfg['applications']:
                validate_app(app)
        except KeyError:
            cfg['applications'] = []

        try:
            for i, model in enumerate(cfg['models']):
                validate_model(model, i + 1)
        except KeyError:
            cfg['models'] = []

        try:
            if type(cfg['post_cmds']) != ruamel.yaml.comments.CommentedSeq:
                raise click.BadParameter(f'The "post_cmds" must be a list')

            for cmd_file in cfg['post_cmds']:
                validate_post_cmds(cmd_file)
        except KeyError:
            cfg['post_cmds'] = []

        return cfg, value
Exemplo n.º 2
0
def test_list_files():
    base_content = {
        'val_int': 1,
        'val_str': 'str',
        'val_bytes': b'\x00',
        'val_bool': True
    }
    base_dir = 'list_dir/'
    num_files = 100

    all_contents = {}
    for x in range(num_files):
        base_content['val_int'] += 1
        base_content['val_str'] += str(x)
        base_content['val_bytes'] += x.to_bytes(1, 'big')
        base_content['val_bool'] = not base_content['val_bool']

        all_contents[f'file_{x}.yml'] = dict(base_content)

    for x in range(num_files):
        file_name = f'file_{x}.yml'
        file_helper.write(base_dir + file_name, all_contents[file_name])

    filenames = file_helper.list_files(base_dir)

    for x in range(num_files):
        assert file_helper.read(base_dir + filenames[x]) == \
            all_contents[filenames[x]]
Exemplo n.º 3
0
def parse_template(ctx, param, value):
    if not value:
        return value

    template = file_helper.read(value)
    if not template:
        raise click.BadParameter(f'File "{value}" not found')

    try:
        name, name_is_seq = template_helper.get_field(template, 'name')
        validate_name(ctx, param, name)
        template['name_is_seq'] = name_is_seq
    except KeyError:
        name = None

    try:
        network, _ = template_helper.get_field(template, 'network')
        validate_network(ctx, param, network)
    except KeyError:
        network = None

    try:
        uuid, _ = template_helper.get_field(template, 'uuid')
        uuid = validate_uuid(ctx, param, address)
    except KeyError:
        uuid = None

    try:
        address, addr_is_seq = template_helper.get_field(template, 'address', custom_pattern=template['name'])
        address = validate_addr(ctx, param, address)
        template['addr_is_seq'] = addr_is_seq
    except KeyError:
        address = random_addr()

    return (name, network, address, uuid, template)
Exemplo n.º 4
0
def validate_post_cmds(value):
    file = file_helper.read(value)
    if not file:
        raise click.BadParameter(f'File "{value}" not found')

    try:
        commands = file['commands']
        if type(commands) != ruamel.yaml.comments.CommentedSeq:
            raise click.BadParameter(f'On {value} file, The "commands" must be'
                                     f' a list')
        for i, cmd in enumerate(commands):
            validate_single_cmd(value, i + 1, cmd)
    except KeyError:
        raise click.BadParameter(f'Not found "commands" keyword on {value}'
                                 f' file')
Exemplo n.º 5
0
def parse_template(ctx, param, value):
    if not value:
        return value

    template = file_helper.read(value)
    if not template:
        raise click.BadParameter(f'File "{value}" not found')

    try:
        name, name_is_seq = template_helper.get_field(template, 'name')
        validate_name(ctx, param, name)
    except KeyError:
        raise click.BadParameter(f'Field "name" not found in template file '
                                 f'"{value}"')
    except click.BadParameter as bp:
        if name_is_seq:
            template_helper.update_sequence(template, 'name')
        raise bp

    try:
        key, _ = template_helper.get_field(template, 'key')
        validate_key(ctx, param, key)
    except KeyError:
        key = random_key()

    key_index = random_key_index()
    validate_key_index(key_index)

    if len(key) < 32:
        key = bytes.fromhex(key) + bytes((32 - len(key)) // 2)
    elif len(key) > 32:
        key = bytes.fromhex(key)[0:16]
    else:
        key = bytes.fromhex(key)

    net_data = NetworkData(name=name,
                           key=key,
                           key_index=bytes.fromhex(key_index),
                           iv_index=bytes(4))
    net_data.save()

    if name_is_seq:
        template_helper.update_sequence(template, 'name')

    click.echo(click.style('A new network was created', fg='green'))
    click.echo(click.style(str(net_data), fg='green'))

    ctx.exit()
Exemplo n.º 6
0
def test_write_read():
    content = {
        'val_int': 95,
        'val_str': 'october',
        'val_bytes': b'\x24',
        'val_bool': True
    }

    assert file_helper.file_exist('write_read_file.yml') is False

    file_helper.write('write_read_file.yml', content)

    assert file_helper.file_exist('write_read_file.yml') is True

    r_content = file_helper.read('write_read_file.yml')

    assert r_content['val_int'] == 95
    assert r_content['val_str'] == 'october'
    assert r_content['val_bytes'] == b'\x24'
    assert r_content['val_bool'] is True
Exemplo n.º 7
0
 def load(cls, filename):
     return cls(**file_helper.read(filename))
Exemplo n.º 8
0
async def config_task(target: str, client_element: Element, config: dict):
    tries = 3
    total_steps = len(config['applications'])
    for m in config['models']:
        total_steps += 1
        if 'publication' in m.keys():
            total_steps += 1
        if 'subscription' in m.keys():
            total_steps += len(m['subscription'])
    for cmd_file in config['post_cmds']:
        file = file_helper.read(cmd_file)
        total_steps += len(file['commands'])

    with tqdm(range(total_steps)) as pbar:
        success = True

        for app in config['applications']:
            for t in range(tries):
                success = await appkey_add(client_element, target, app)
                if success:
                    break
            if not success:
                click.echo(click.style(f'\nError on appkey add. Application: '
                                       f'{app}', fg='red'))
                return None
            pbar.update(1)

        for model in config['models']:
            for t in range(tries):
                success = await model_app_bind(client_element, target,
                                               bytes.fromhex(model['id']),
                                               model['application'])
                if success:
                    break
            if not success:
                click.echo(click.style(f'\nError on model app bind. '
                                       f'Model id: 0x{model["id"]}', fg='red'))
                return None
            pbar.update(1)

            if 'publication' in model:
                for t in range(tries):
                    success = await model_publication_set(
                        client_element, target, bytes.fromhex(model['id']),
                        bytes.fromhex(model['publication']),
                        model['application'])
                    if success:
                        break
                if not success:
                    click.echo(click.style(f'\nError on model publication set.'
                                           f' Model id: 0x{model["id"]}',
                                           fg='red'))
                    return None
                pbar.update(1)

            if 'subscription' in model:
                for s in model['subscription']:
                    for t in range(tries):
                        success = await model_subscription_add(
                            client_element, target, bytes.fromhex(model['id']),
                            bytes.fromhex(s))
                        if success:
                            break
                    if not success:
                        click.echo(click.style(f'\nError on model subscription'
                                               f' add. Model id: 0x'
                                               f'{model["id"]}', fg='red'))
                        return None
                    pbar.update(1)

        for post_cmd in config['post_cmds']:
            file = file_helper.read(post_cmd)
            for cmd in file['commands']:
                tries = cmd['tries'] if 'tries' in cmd.keys() else 1
                application = cmd['application'] if \
                    'application' in cmd.keys() else ''
                for t in range(tries):
                    success = await send_cmd(client_element, target,
                                             bytes.fromhex(cmd['opcode']),
                                             bytes.fromhex(cmd['parameters']),
                                             application)
                    await asyncio.sleep(.1)
                if not success:
                    click.echo(click.style(f'\nError on send cmd. cmd file: '
                                           f'{post_cmd}', fg='red'))
                    return None
                pbar.update(1)
Exemplo n.º 9
0
def parse_template(ctx, param, value):
    if not value:
        return value

    template = file_helper.read(value)
    if not template:
        raise click.BadParameter(f'File "{value}" not found')

    try:
        name, name_is_seq = template_helper.get_field(template, 'name')
        validate_name(ctx, param, name)
    except KeyError:
        raise click.BadParameter(f'Field "name" not found in template file '
                                 f'"{value}"')
    except click.BadParameter as bp:
        if name_is_seq:
            template_helper.update_sequence(template, 'name')
        raise bp

    try:
        network, net_is_seq = template_helper.get_field(template, 'network')
        validate_network(ctx, param, network)
    except KeyError:
        raise click.BadParameter(f'Field "network" not found in template file '
                                 f'"{value}"')
    except click.BadParameter as bp:
        if net_is_seq:
            template_helper.update_sequence(template, 'network')
        raise bp

    try:
        key, _ = template_helper.get_field(template, 'key')
        validate_key(ctx, param, key)
    except KeyError:
        key = random_key()

    key_index = random_key_index()
    validate_key_index(key_index)

    if len(key) < 32:
        key = bytes.fromhex(key) + bytes((32 - len(key)) // 2)
    elif len(key) > 32:
        key = bytes.fromhex(key)[0:16]
    else:
        key = bytes.fromhex(key)

    app_data = ApplicationData(name=name,
                               key=key,
                               key_index=bytes.fromhex(key_index),
                               network=network)
    app_data.save()

    net_data = NetworkData.load(base_dir + net_dir + network + '.yml')
    if app_data.name not in net_data.apps:
        net_data.apps.append(app_data.name)
    net_data.save()

    if name_is_seq:
        template_helper.update_sequence(template, 'name')
    if net_is_seq:
        template_helper.update_sequence(template, 'network')

    click.echo(click.style('A new application was created', fg='green'))
    click.echo(click.style(str(app_data), fg='green'))

    ctx.exit()