加入等待继电器释放,加入程序停止执行时释放所有资源
This commit is contained in:
@@ -1,9 +1,15 @@
|
||||
package relay
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/grid-x/modbus"
|
||||
"go.uber.org/zap"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Relay interface {
|
||||
@@ -56,6 +62,29 @@ func (r *device) Off(num int) error {
|
||||
func New(address string) (Relay, error) {
|
||||
zap.S().Infoln("连接继电器: ", address)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||
defer cancel()
|
||||
a := make(chan struct{})
|
||||
go func() {
|
||||
defer close(a)
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
zap.S().Infoln("等待继电器资源释放超时:", address)
|
||||
return
|
||||
case <-time.After(3 * time.Second):
|
||||
_, err := os.OpenFile(address, os.O_RDWR, 0666)
|
||||
var e *fs.PathError
|
||||
if errors.As(err, &e) && strings.Contains(e.Error(), "busy") {
|
||||
zap.S().Infoln("等待继电器资源释放:", address)
|
||||
} else {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
<-a
|
||||
|
||||
h := modbus.NewRTUClientHandler(address)
|
||||
h.SlaveID = 1
|
||||
h.BaudRate = 9600
|
||||
|
||||
Reference in New Issue
Block a user