michielpost / Q42.HueApi

C# helper library to talk to the Philips Hue bridge
MIT License
411 stars 114 forks source link

Type Enum rather then string in state #127

Closed KevinAnthony closed 6 years ago

KevinAnthony commented 6 years ago

It would be very useful if we replaced the state.Type of lights with a enum rather then a string. something like

[Flags]
enum LightTypes {
    [Description("on/off light")]
    OnOffLight = 1,
    [Description("dimmable light")]
    DimmableLight = 2,
    [Description("color Temperature Ligh")]
    TempatureLight = 4,
    [Description("color light")]
    ColorLight = 8,
    [Description("extended color light")]
    ExtendedColorLight = 16,

    //Extended Types
    OnOff = OnOffLight | DimmableLight | TempatureLight | ColorLight | ExtendedColorLight,
    Dimmable = DimmableLight | TempatureLight | ColorLight| ExtendedColorLight,
    Tempature = TempatureLight | ColorLight| ExtendedColorLight,
    RGB = ColorLight | ExtendedColorLight
}

and you could parse the incoming values like this

public static T GetEnum<T>(this string description)
{
    Type type = typeof(T);
    if (!type.IsEnum) throw new InvalidOperationException();
    foreach (FieldInfo field in type.GetFields())
    {
        if (Attribute.GetCustomAttribute(field,
            typeof(DescriptionAttribute)) is DescriptionAttribute attribute)
        {
            if (attribute.Description.Equals(description, StringComparison.OrdinalIgnoreCase))
                return (T)field.GetValue(null);
        }
        else
        {
            if (field.Name.Equals(description, StringComparison.OrdinalIgnoreCase))
                return (T)field.GetValue(null);
        }
    }
    return default(T);
}
michielpost commented 6 years ago

Yes, sounds good. But are these the only possible values of the light.type field? The documentation has no specification and it might change and break the library in the future.

Maybe it's better to create an extra property, so we keep the raw string value, and an extra Unknown enum value for unknown types?

Are you able to make a Pull Request? That would be awesome. Thanks!

michielpost commented 6 years ago

I think it's best to create an extension method for this.