package models import ( "context" "encoding/hex" "errors" ) // ErrMalformedColor is returned by light.ColorRGBf when the color value is invalid. var ErrMalformedColor = errors.New("Malformed color in light") // A Light represents a bulb. type Light struct { ID int `json:"id" db:"id"` BridgeID int `json:"bridgeId" db:"bridge_id"` GroupID int `json:"groupId" db:"group_id"` InternalID string `json:"internalId" db:"internal_id"` Name string `json:"name" db:"name"` On bool `json:"on" db:"enabled"` Color string `json:"color" db:"color"` Brightness uint8 `json:"brightness" db:"brightness"` } // SetColorRGB sets the color with an RGB value. func (light *Light) SetColorRGB(r, g, b uint8) { light.Color = hex.EncodeToString([]byte{r, g, b}) } // SetColorRGBf sets the color with an RGB value as floats between `0.0` and `1.0`. func (light *Light) SetColorRGBf(r, g, b float64) { light.SetColorRGB(uint8(r*255), uint8(g*255), uint8(b*255)) } // ColorRGB gets the RGB values. func (light *Light) ColorRGB() (r, g, b uint8, err error) { if light.Color == "" { return 0, 0, 0, nil } bytes, err := hex.DecodeString(light.Color) if err != nil || len(bytes) != 3 { return 0, 0, 0, ErrMalformedColor } return bytes[0], bytes[1], bytes[2], nil } // ColorRGBf returns the float values of the RGB color. func (light *Light) ColorRGBf() (r, g, b float64, err error) { r8, g8, b8, err := light.ColorRGB() if err != nil { return 0, 0, 0, err } return float64(r8) / 255, float64(g8) / 255, float64(b8) / 255, nil } // LightRepository is an interface for all database operations // the Light model makes. type LightRepository interface { FindByID(ctx context.Context, id int) (Light, error) FindByInternalID(ctx context.Context, internalID string) (Light, error) List(ctx context.Context) ([]Light, error) ListByBridge(ctx context.Context, bridge Bridge) ([]Light, error) ListByGroup(ctx context.Context, group Group) ([]Light, error) Insert(ctx context.Context, light Light) (Light, error) Update(ctx context.Context, light Light) error Remove(ctx context.Context, light Light) error }