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