2024-07-26 19:58:34 +00:00
|
|
|
package gpio
|
|
|
|
|
|
|
|
import (
|
2024-08-19 14:07:46 +00:00
|
|
|
"context"
|
2024-07-26 19:58:34 +00:00
|
|
|
"io"
|
|
|
|
"log"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
gpio "github.com/stianeikeland/go-rpio/v4"
|
|
|
|
)
|
|
|
|
|
2024-08-19 14:07:46 +00:00
|
|
|
const (
|
|
|
|
waitCtxTimeout = 100 * time.Microsecond
|
|
|
|
)
|
|
|
|
|
2024-07-26 19:58:34 +00:00
|
|
|
type gpioPin struct {
|
|
|
|
logger *log.Logger
|
|
|
|
pin gpio.Pin
|
|
|
|
}
|
|
|
|
|
|
|
|
type Pin interface {
|
|
|
|
Init() error
|
|
|
|
PowerOn()
|
2024-08-19 14:07:46 +00:00
|
|
|
PowerOnCtx(ctx context.Context)
|
2024-07-26 19:58:34 +00:00
|
|
|
io.Closer
|
|
|
|
}
|
|
|
|
|
|
|
|
func New(logger *log.Logger, pin uint8) Pin {
|
|
|
|
return gpioPin{
|
|
|
|
logger: logger,
|
|
|
|
pin: gpio.Pin(pin),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p gpioPin) Init() error {
|
|
|
|
return gpio.Open()
|
|
|
|
}
|
|
|
|
|
2024-08-19 14:07:46 +00:00
|
|
|
func waitCtx(ctx context.Context, timeout time.Duration) {
|
|
|
|
deadline := time.Now().Add(timeout)
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return
|
|
|
|
default:
|
|
|
|
if time.Now().After(deadline) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
time.Sleep(waitCtxTimeout)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p gpioPin) sendOnOffSignal(ctx context.Context) {
|
2024-07-26 19:58:34 +00:00
|
|
|
p.pin.Output()
|
|
|
|
p.logger.Println("Power on 0/3 + 100ms")
|
|
|
|
p.pin.Low()
|
|
|
|
p.pin.Toggle()
|
2024-08-19 14:07:46 +00:00
|
|
|
waitCtx(ctx, 100*time.Millisecond)
|
2024-07-26 19:58:34 +00:00
|
|
|
|
|
|
|
p.logger.Println("Power on 1/3 + 3s")
|
|
|
|
p.pin.High()
|
|
|
|
p.pin.Toggle()
|
2024-08-19 14:07:46 +00:00
|
|
|
waitCtx(ctx, 3*time.Second)
|
2024-07-26 19:58:34 +00:00
|
|
|
|
|
|
|
p.logger.Println("Power on 2/3 + 30s")
|
|
|
|
p.pin.Low()
|
|
|
|
p.pin.Toggle()
|
2024-08-19 14:07:46 +00:00
|
|
|
waitCtx(ctx, 30*time.Second)
|
2024-07-26 19:58:34 +00:00
|
|
|
|
|
|
|
p.logger.Println("Power on 3/3")
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p gpioPin) PowerOn() {
|
2024-08-19 14:07:46 +00:00
|
|
|
p.sendOnOffSignal(context.Background())
|
2024-07-26 19:58:34 +00:00
|
|
|
}
|
|
|
|
|
2024-08-19 14:07:46 +00:00
|
|
|
func (p gpioPin) PowerOnCtx(ctx context.Context) {
|
|
|
|
p.sendOnOffSignal(ctx)
|
2024-07-26 19:58:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (p gpioPin) Close() error {
|
|
|
|
return gpio.Close()
|
|
|
|
}
|