-
Notifications
You must be signed in to change notification settings - Fork 0
/
light.go
86 lines (74 loc) · 1.94 KB
/
light.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package devices
import (
"fmt"
"github.com/galenliu/gateway/pkg/addon/properties"
"strconv"
"strings"
)
type LightHandler interface {
TurnOn() error
TurnOff() error
SetBrightness(brightness int) error
}
type Light struct {
*Device
OnOff properties.BooleanEntity
Brightness properties.IntegerEntity
ColorMode properties.Entity
Color properties.Entity
ColorTemperature properties.Entity
}
func NewLightBulb(id string, opts ...Option) *Light {
device := NewDevice(DeviceDescription{
Id: id,
AtType: []Capability{CapabilityLight, CapabilityOnOffSwitch},
}, opts...)
if device == nil {
return nil
}
return &Light{Device: device}
}
func (light *Light) AddProperties(props ...properties.Entity) {
for _, p := range props {
switch p.GetAtType() {
case properties.TypeOnOffProperty:
light.OnOff = p.(properties.BooleanEntity)
case properties.TypeBrightnessProperty:
light.Brightness = p.(properties.IntegerEntity)
case properties.TypeColorModeProperty:
light.ColorMode = p
case properties.TypeColorProperty:
light.Color = p
case properties.TypeColorTemperatureProperty:
light.ColorTemperature = p
}
light.Device.AddProperty(p)
}
}
func (light *Light) TurnOn() error {
return light.OnOff.TurnOn()
}
func (light *Light) TurnOff() error {
return light.OnOff.TurnOff()
}
func (light *Light) Toggle() error {
if light.OnOff.IsOn() {
return light.TurnOn()
} else {
return light.TurnOff()
}
}
func (light *Light) SetBrightness(brightness int) error {
if light.Brightness != nil {
return light.Brightness.SetValue(properties.Integer(brightness))
}
return fmt.Errorf("brightness not set for light")
}
func Color16ToRGB(colorStr string) (red, green, blue int, err error) {
color64, err := strconv.ParseInt(strings.TrimPrefix(colorStr, "#"), 16, 32)
if err != nil {
return
}
colorInt := int(color64)
return colorInt >> 16, (colorInt & 0x00FF00) >> 8, colorInt & 0x0000FF, nil
}