1
0
mirror of https://github.com/hybridgroup/gobot.git synced 2025-04-24 13:48:49 +08:00

Added ability to make a relay driver inverted (#674)

* gpio: Added ability to make a relay driver inverted
This commit is contained in:
Andre Engelbrecht 2019-06-25 06:13:17 +01:00 committed by Ron Evans
parent 36730e33cf
commit c7d6ea7569
2 changed files with 50 additions and 2 deletions

View File

@ -8,6 +8,7 @@ type RelayDriver struct {
name string
connection DigitalWriter
high bool
Inverted bool
gobot.Commander
}
@ -23,6 +24,7 @@ func NewRelayDriver(a DigitalWriter, pin string) *RelayDriver {
pin: pin,
connection: a,
high: false,
Inverted: false,
Commander: gobot.NewCommander(),
}
@ -63,6 +65,9 @@ func (l *RelayDriver) Connection() gobot.Connection {
// State return true if the relay is On and false if the relay is Off
func (l *RelayDriver) State() bool {
if l.Inverted {
return !l.high
}
return l.high
}
@ -71,7 +76,13 @@ func (l *RelayDriver) On() (err error) {
if err = l.connection.DigitalWrite(l.Pin(), 1); err != nil {
return
}
l.high = true
if l.Inverted {
l.high = false
} else {
l.high = true
}
return
}
@ -80,7 +91,13 @@ func (l *RelayDriver) Off() (err error) {
if err = l.connection.DigitalWrite(l.Pin(), 0); err != nil {
return
}
l.high = false
if l.Inverted {
l.high = true
} else {
l.high = false
}
return
}

View File

@ -10,6 +10,9 @@ import (
var _ gobot.Driver = (*RelayDriver)(nil)
// Helper to return low/high value for testing
func (l *RelayDriver) High() bool { return l.high }
func initTestRelayDriver() *RelayDriver {
a := newGpioTestAdaptor()
a.testAdaptorDigitalWrite = func() (err error) {
@ -52,6 +55,17 @@ func TestRelayDriverToggle(t *testing.T) {
gobottest.Assert(t, d.State(), false)
}
func TestRelayDriverToggleInverted(t *testing.T) {
d := initTestRelayDriver()
d.Inverted = true
d.Off()
gobottest.Assert(t, d.State(), false)
d.Toggle()
gobottest.Assert(t, d.State(), true)
d.Toggle()
gobottest.Assert(t, d.State(), false)
}
func TestRelayDriverCommands(t *testing.T) {
d := initTestRelayDriver()
gobottest.Assert(t, d.Command("Off")(nil), nil)
@ -63,3 +77,20 @@ func TestRelayDriverCommands(t *testing.T) {
gobottest.Assert(t, d.Command("Toggle")(nil), nil)
gobottest.Assert(t, d.State(), false)
}
func TestRelayDriverCommandsInverted(t *testing.T) {
d := initTestRelayDriver()
d.Inverted = true
gobottest.Assert(t, d.Command("Off")(nil), nil)
gobottest.Assert(t, d.High(), true)
gobottest.Assert(t, d.State(), false)
gobottest.Assert(t, d.Command("On")(nil), nil)
gobottest.Assert(t, d.High(), false)
gobottest.Assert(t, d.State(), true)
gobottest.Assert(t, d.Command("Toggle")(nil), nil)
gobottest.Assert(t, d.High(), true)
gobottest.Assert(t, d.State(), false)
}