The main server, and probably only repository in this org.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

103 lines
2.4 KiB

package models
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
goColor "github.com/gerow/go-color"
)
// A Light represents a bulb.
type Light struct {
ID int `json:"id"`
BridgeID int `json:"bridgeId"`
InternalID string `json:"-"`
Name string `json:"name"`
On bool `json:"on"`
Color LightColor `json:"color"`
}
// LightColor represent a HSB color.
type LightColor struct {
Hue uint16
Sat uint8
Bri uint8
}
// SetRGB sets the light color's RGB.
func (color *LightColor) SetRGB(r, g, b uint8) {
rgb := goColor.RGB{
R: float64(r) / 255,
G: float64(g) / 255,
B: float64(b) / 255,
}
hsl := rgb.ToHSL()
color.Hue = uint16(hsl.H * 65535)
color.Sat = uint8(hsl.S * 255)
color.Bri = uint8(hsl.L * 255)
}
// String prints the color as HSB.
func (color *LightColor) String() string {
return fmt.Sprintf("%d,%d,%d", color.Hue, color.Sat, color.Bri)
}
// Equals returns true if all the light's values are the same.
func (color *LightColor) Equals(other LightColor) bool {
return color.Hue == other.Hue && color.Sat == other.Sat && color.Bri == other.Bri
}
// Parse parses three comma separated number.
func (color *LightColor) Parse(src string) error {
split := strings.SplitN(src, ",", 3)
if len(split) < 3 {
return errors.New("H,S,V format is incomplete")
}
hue, err := strconv.ParseUint(split[0], 10, 16)
if err != nil {
return err
}
sat, err := strconv.ParseUint(split[1], 10, 16)
if err != nil {
return err
}
bri, err := strconv.ParseUint(split[2], 10, 16)
if err != nil {
return err
}
color.Hue = uint16(hue)
color.Sat = uint8(sat)
color.Bri = uint8(bri)
// Hue doesn't like 0 and 255 for Sat and Bri.
if color.Sat < 1 {
color.Sat = 1
} else if color.Sat > 254 {
color.Sat = 254
}
if color.Bri < 1 {
color.Bri = 1
} else if color.Bri > 254 {
color.Bri = 254
}
return 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)
Insert(ctx context.Context, light Light) (Light, error)
Update(ctx context.Context, light Light) error
Remove(ctx context.Context, light Light) error
}