Initial LanUps implementation and native installers
This commit is contained in:
commit
67a043c89b
66 files changed
+2870
No files matched your search
@@ -0,0 +1,61 @@
|
||||
package nut
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func ReadUPS(address, name string, timeout time.Duration) (map[string]string, error) {
|
||||
deadline := time.Now().Add(timeout)
|
||||
conn, err := net.DialTimeout("tcp", address, timeout)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer conn.Close()
|
||||
if err := conn.SetDeadline(deadline); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
request := "LIST VAR " + name
|
||||
if _, err := fmt.Fprintln(conn, request); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
scanner := bufio.NewScanner(io.LimitReader(conn, 256*1024))
|
||||
if !scanner.Scan() {
|
||||
return nil, incomplete(scanner)
|
||||
}
|
||||
if scanner.Text() != "BEGIN "+request {
|
||||
return nil, fmt.Errorf("NUT: %s", scanner.Text())
|
||||
}
|
||||
values := make(map[string]string)
|
||||
prefix := "VAR " + name + " "
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
if line == "END "+request {
|
||||
if strings.TrimSpace(values["ups.status"]) == "" {
|
||||
return nil, errors.New("NUT 未返回 ups.status")
|
||||
}
|
||||
return values, nil
|
||||
}
|
||||
row, ok := strings.CutPrefix(line, prefix)
|
||||
key, quoted, separated := strings.Cut(row, " ")
|
||||
if !ok || !separated || key == "" || len(quoted) < 2 || quoted[0] != '"' || quoted[len(quoted)-1] != '"' {
|
||||
return nil, fmt.Errorf("NUT: %s", line)
|
||||
}
|
||||
values[key] = nutEscapes.Replace(quoted[1 : len(quoted)-1])
|
||||
}
|
||||
return nil, incomplete(scanner)
|
||||
}
|
||||
|
||||
var nutEscapes = strings.NewReplacer(`\\`, `\`, `\"`, `"`)
|
||||
|
||||
func incomplete(scanner *bufio.Scanner) error {
|
||||
if err := scanner.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
return io.ErrUnexpectedEOF
|
||||
}
|
||||
Reference in new issue
Block a user