-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
led_driver.go
85 lines (72 loc) · 1.91 KB
/
led_driver.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
package gpio
import (
"gobot.io/x/gobot/v2"
)
// LedDriver represents a digital Led
type LedDriver struct {
*driver
high bool
}
// NewLedDriver return a new LedDriver given a DigitalWriter and pin.
//
// Supported options:
//
// "WithName"
//
// Adds the following API Commands:
//
// "Brightness" - See LedDriver.Brightness
// "Toggle" - See LedDriver.Toggle
// "On" - See LedDriver.On
// "Off" - See LedDriver.Off
func NewLedDriver(a DigitalWriter, pin string, opts ...interface{}) *LedDriver {
//nolint:forcetypeassert // no error return value, so there is no better way
d := &LedDriver{
driver: newDriver(a.(gobot.Connection), "LED", append(opts, withPin(pin))...),
}
d.AddCommand("Brightness", func(params map[string]interface{}) interface{} {
level := byte(params["level"].(float64)) //nolint:forcetypeassert // ok here
return d.Brightness(level)
})
d.AddCommand("Toggle", func(params map[string]interface{}) interface{} {
return d.Toggle()
})
d.AddCommand("On", func(params map[string]interface{}) interface{} {
return d.On()
})
d.AddCommand("Off", func(params map[string]interface{}) interface{} {
return d.Off()
})
return d
}
// State return true if the led is On and false if the led is Off
func (d *LedDriver) State() bool {
return d.high
}
// On sets the led to a high state.
func (d *LedDriver) On() error {
if err := d.digitalWrite(d.driverCfg.pin, 1); err != nil {
return err
}
d.high = true
return nil
}
// Off sets the led to a low state.
func (d *LedDriver) Off() error {
if err := d.digitalWrite(d.driverCfg.pin, 0); err != nil {
return err
}
d.high = false
return nil
}
// Toggle sets the led to the opposite of it's current state
func (d *LedDriver) Toggle() error {
if d.State() {
return d.Off()
}
return d.On()
}
// Brightness sets the led to the specified level of brightness
func (d *LedDriver) Brightness(level byte) error {
return d.pwmWrite(d.driverCfg.pin, level)
}