Example #1
0
def encode_config(config, flat=True):
    msg = ConfigMsg()
    for k, v in config.items():
        ## @todo add more checks here?
        if type(v) == int:
            msg.ints.append(IntParameter(k, v))
        elif type(v) == bool:
            msg.bools.append(BoolParameter(k, v))
        elif type(v) == str:
            msg.strs.append(StrParameter(k, v))
        elif sys.version_info.major < 3 and isinstance(v, unicode):
            msg.strs.append(StrParameter(k, v))
        elif type(v) == float:
            msg.doubles.append(DoubleParameter(k, v))
        elif type(v) == dict or isinstance(v, Config):
            if flat is True:
                def flatten(g):
                    groups = []
                    for _name, group in g['groups'].items():
                        groups.extend(flatten(group))
                        groups.append(GroupState(group['name'], group['state'], group['id'], group['parent']))
                    return groups
                msg.groups.append(GroupState(v['name'], v['state'], v['id'], v['parent']))
                msg.groups.extend(flatten(v))
            else:
                msg.groups = [GroupState(x['name'], x['state'], x['id'], x['parent']) for x in v]

    return msg
def deserializeFromYaml(yaml_str):
    cfg = yaml.load(yaml_str)
    if not isinstance(cfg, dict):
        return None

    msg = Config()

    if 'bools' in cfg and isinstance(cfg['bools'], list):
        for p in cfg['bools']:
            try:
                msg.bools.append(BoolParameter(p['name'], p['value']))
            except Exception:
                pass

    if 'ints' in cfg and isinstance(cfg['ints'], list):
        for p in cfg['ints']:
            try:
                msg.ints.append(IntParameter(p['name'], p['value']))
            except Exception:
                pass

    if 'strs' in cfg and isinstance(cfg['strs'], list):
        for p in cfg['strs']:
            try:
                msg.strs.append(StrParameter(p['name'], p['value']))
            except Exception:
                pass

    if 'doubles' in cfg and isinstance(cfg['doubles'], list):
        for p in cfg['doubles']:
            try:
                msg.doubles.append(DoubleParameter(p['name'], p['value']))
            except Exception:
                pass

    return msg