62 lines
1.5 KiB
Go
62 lines
1.5 KiB
Go
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
|
|
}
|