From 4587c29ec563d38570ce2d3ddf2fdea8b5e21fef Mon Sep 17 00:00:00 2001 From: fengyarnom Date: Thu, 29 May 2025 19:33:07 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E6=81=A2=E5=A4=8D=E4=B8=80=E4=BA=9B?= =?UTF-8?q?=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tcp_server.go | 56 +++++++++++++++++++++++++-------------------------- 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/tcp_server.go b/tcp_server.go index 9ea4e88..299cf13 100644 --- a/tcp_server.go +++ b/tcp_server.go @@ -62,18 +62,18 @@ func handleConnection(conn net.Conn) { clientsMutex.Unlock() // 注释掉自动发送指令 - 设备刚连接时立即发送一次查询指令 - // go func() { - // time.Sleep(2 * time.Second) // 等待2秒让连接稳定 - // command := "@1602301014A*0!\n" - // if _, err := conn.Write([]byte(command)); err != nil { - // Logger.Printf("发送连接后查询指令到客户端 %s 失败: %v", remoteAddr, err) - // } else { - // TCPDataLogger.Printf("发送连接后查询指令到客户端 %s: %s", remoteAddr, strings.TrimSpace(command)) - // } - // }() + go func() { + time.Sleep(2 * time.Second) // 等待2秒让连接稳定 + command := "@1602301014A*0!\n" + if _, err := conn.Write([]byte(command)); err != nil { + Logger.Printf("发送连接后查询指令到客户端 %s 失败: %v", remoteAddr, err) + } else { + TCPDataLogger.Printf("发送连接后查询指令到客户端 %s: %s", remoteAddr, strings.TrimSpace(command)) + } + }() - // 注释掉自动发送指令 - 启动定时发送指令的goroutine - // go sendPeriodicCommand(conn, remoteAddr) + // 启动定时发送指令的goroutine(30分钟间隔) + go sendPeriodicCommand(conn, remoteAddr) buffer := make([]byte, 1024) @@ -159,23 +159,23 @@ func handleConnection(conn net.Conn) { } } -// 注释掉自动发送指令 - sendPeriodicCommand 每5分钟发送一次查询指令 -// func sendPeriodicCommand(conn net.Conn, remoteAddr string) { -// ticker := time.NewTicker(5 * time.Minute) -// defer ticker.Stop() -// -// for { -// select { -// case <-ticker.C: -// command := "@1602301014A*0!\n" -// if _, err := conn.Write([]byte(command)); err != nil { -// Logger.Printf("发送定时指令到客户端 %s 失败: %v", remoteAddr, err) -// return // 连接断开,退出goroutine -// } -// TCPDataLogger.Printf("发送定时指令到客户端 %s: %s", remoteAddr, strings.TrimSpace(command)) -// } -// } -// } +// sendPeriodicCommand 每30分钟发送一次查询指令 +func sendPeriodicCommand(conn net.Conn, remoteAddr string) { + ticker := time.NewTicker(30 * time.Minute) + defer ticker.Stop() + + for { + select { + case <-ticker.C: + command := "@1602301014A*0!\n" + if _, err := conn.Write([]byte(command)); err != nil { + Logger.Printf("发送定时指令到客户端 %s 失败: %v", remoteAddr, err) + return // 连接断开,退出goroutine + } + TCPDataLogger.Printf("发送定时指令到客户端 %s: %s", remoteAddr, strings.TrimSpace(command)) + } + } +} // parseData 使用正则表达式解析传感器数据,支持新格式 #{1602301014-01,1,1,28.4,-6.884,1.540}! func parseData(data string) (int, float64, float64, float64, float64, error) {