fix: 修改hex流发送逻辑

This commit is contained in:
fengyarnom 2025-05-15 16:14:09 +08:00
parent 60e37d73c5
commit ebf811f981

View File

@ -2,8 +2,10 @@ package tcp
import ( import (
"encoding/binary" "encoding/binary"
"encoding/hex"
"fmt" "fmt"
"net" "net"
"strings"
"sync" "sync"
"time" "time"
@ -13,9 +15,9 @@ import (
) )
const ( const (
queryCmd = "01 03 01 F4 00 10 04 08" // 读取寄存器命令 queryCmd = "010301F400100408" // 读取寄存器命令
resetCmd = "01 06 60 02 00 5A B6 31" // 清除雨量统计命令 resetCmd = "0106600200005AB6" // 清除雨量统计命令
tcpPort = ":10004" // TCP服务器端口 tcpPort = ":10004" // TCP服务器端口
) )
type SensorComm struct { type SensorComm struct {
@ -39,8 +41,13 @@ func (s *SensorComm) sendQuery() error {
s.mu.Lock() s.mu.Lock()
defer s.mu.Unlock() defer s.mu.Unlock()
cmd := hexStringToBytes(queryCmd) cmd, err := hex.DecodeString(queryCmd)
_, err := s.conn.Write(cmd) if err != nil {
logger.Logger.Printf("解析命令失败: %v", err)
return err
}
_, err = s.conn.Write(cmd)
if err != nil { if err != nil {
logger.Logger.Printf("发送查询命令失败: %v", err) logger.Logger.Printf("发送查询命令失败: %v", err)
return err return err
@ -173,24 +180,30 @@ func handleConnection(sensor *SensorComm) {
// 辅助函数:将十六进制字符串转换为字节数组 // 辅助函数:将十六进制字符串转换为字节数组
func hexStringToBytes(s string) []byte { func hexStringToBytes(s string) []byte {
var bytes []byte // 移除空格
var b byte s = strings.ReplaceAll(s, " ", "")
var ok bool
for i := 0; i < len(s); i++ { // 确保字符串长度是偶数
if s[i] == ' ' { if len(s)%2 != 0 {
continue return nil
}
bytes := make([]byte, len(s)/2)
for i := 0; i < len(s); i += 2 {
// 转换高位
high, ok := hexCharToByte(s[i])
if !ok {
return nil
} }
if b, ok = hexCharToByte(s[i]); !ok { // 转换低位
continue low, ok := hexCharToByte(s[i+1])
if !ok {
return nil
} }
if i%2 == 0 { // 组合高位和低位
bytes = append(bytes, b<<4) bytes[i/2] = high<<4 | low
} else {
bytes[len(bytes)-1] |= b
}
} }
return bytes return bytes