Files
rpicontrol/internal/PinControlService/Pin.go
2022-12-30 18:42:48 +01:00

99 lines
1.9 KiB
Go

package PinControlService
import (
"errors"
log "github.com/sirupsen/logrus"
)
type Pin struct {
Id int
Name string
Direction PinDirection
PullConfig PinPull
InitialState PinCommand
PinHandle HardwarePinInterface
SendPollingEvents bool
SendChangeEvents bool
}
func NewPin(config PinConfig) Pin {
p := Pin{
Direction: config.Direction,
PullConfig: config.PullConfig,
Name: config.Name,
Id: config.PinNumber,
PinHandle: NewHardwarePin(config.PinNumber),
}
if config.SendPollingEvents != nil {
p.SendPollingEvents = *config.SendPollingEvents
} else {
p.SendPollingEvents = true
}
if config.SendChangeEvents != nil {
p.SendChangeEvents = *config.SendChangeEvents
} else {
p.SendChangeEvents = true
}
if config.InitialState != "" {
p.InitialState = PinCommand(config.InitialState)
} else {
p.InitialState = Off
}
return p
}
func (p *Pin) State() PinState {
if state := p.PinHandle.Read(); State(state) == HighState {
return StateOn
} else {
return StateOff
}
}
func (p *Pin) Command(cmd PinCommand) error {
log.Debugf("try to send command %s for pin %s (pin no: %d)", cmd, p.Name, p.Id)
if p.Direction != Output {
return errors.New("pin is not an output")
}
if cmd == On {
p.PinHandle.High()
} else if cmd == Off {
p.PinHandle.Low()
} else if cmd == Toggle {
p.PinHandle.Toggle()
} else {
return errors.New("unknown command")
}
return nil
}
func (p *Pin) Configure() {
if p.Direction == Input {
p.PinHandle.Input()
} else if p.Direction == Output {
p.PinHandle.Output()
_ = p.Command(p.InitialState)
}
p.PinHandle.Detect(AnyEdge)
if p.PullConfig == PullUp {
p.PinHandle.PullUp()
} else if p.PullConfig == PullDown {
p.PinHandle.PullDown()
} else if p.PullConfig == PullOff {
p.PinHandle.PullOff()
}
}
func (p *Pin) Changed() bool {
return p.PinHandle.EdgeDetected()
}