初始提交
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
package tcpreader
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"FireLeave_tool/logger"
|
||||
)
|
||||
|
||||
// TemperatureResult 温度读取程序返回的数据
|
||||
type TemperatureResult struct {
|
||||
Tmp float64 `json:"tmp"`
|
||||
}
|
||||
|
||||
// TCPClient TCP 客户端
|
||||
type TCPClient struct {
|
||||
addr string // 地址,例如 "127.0.0.1:59881"
|
||||
deviceUUID string // 关联的 DeviceUUID
|
||||
conn net.Conn
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
// NewTCPClient 创建新的 TCP 客户端
|
||||
func NewTCPClient(deviceUUID string, tempPort int) (*TCPClient, error) {
|
||||
addr := fmt.Sprintf("127.0.0.1:%d", tempPort)
|
||||
|
||||
conn, err := net.DialTimeout("tcp", addr, 5*time.Second)
|
||||
if err != nil {
|
||||
logger.Logger.Printf("Connect TCP server %s failed (DeviceUUID=%s): %v", addr, deviceUUID, err)
|
||||
return nil, fmt.Errorf("connect TCP server %s failed: %v", addr, err)
|
||||
}
|
||||
|
||||
client := &TCPClient{
|
||||
addr: addr,
|
||||
deviceUUID: deviceUUID,
|
||||
conn: conn,
|
||||
}
|
||||
logger.Logger.Printf("TCP client created successfully: DeviceUUID=%s, Address=%s", deviceUUID, addr)
|
||||
return client, nil
|
||||
}
|
||||
|
||||
// ReadTemperatureResult 读取温度程序数据
|
||||
func (tc *TCPClient) ReadTemperatureResult() (TemperatureResult, error) {
|
||||
tc.mu.Lock()
|
||||
defer tc.mu.Unlock()
|
||||
|
||||
tc.conn.SetReadDeadline(time.Now().Add(10 * time.Second))
|
||||
reader := bufio.NewReader(tc.conn)
|
||||
message, err := reader.ReadString('\n')
|
||||
if err != nil {
|
||||
logger.Logger.Printf("Read temperature data failed (DeviceUUID=%s, Address=%s): %v", tc.deviceUUID, tc.addr, err)
|
||||
return TemperatureResult{}, fmt.Errorf("read temperature data failed: %v", err)
|
||||
}
|
||||
|
||||
var result TemperatureResult
|
||||
if err := json.Unmarshal([]byte(message), &result); err != nil {
|
||||
logger.Logger.Printf("Parse temperature data failed (DeviceUUID=%s, Address=%s): %v", tc.deviceUUID, tc.addr, err)
|
||||
return TemperatureResult{}, fmt.Errorf("parse temperature data failed: %v", err)
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Close 关闭 TCP 连接
|
||||
func (tc *TCPClient) Close() {
|
||||
tc.mu.Lock()
|
||||
defer tc.mu.Unlock()
|
||||
if tc.conn != nil {
|
||||
tc.conn.Close()
|
||||
logger.Logger.Printf("Close TCP connection: DeviceUUID=%s, Address=%s", tc.deviceUUID, tc.addr)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user