83 lines
2.6 KiB
Go
83 lines
2.6 KiB
Go
package main
|
||
|
||
import (
|
||
"encoding/hex"
|
||
"fmt"
|
||
"net"
|
||
"regexp"
|
||
"time"
|
||
)
|
||
|
||
// ExtractDeviceIDFromBatchRaw 从批量原始数据中提取设备ID(序列号形如 1513343-01 或 ABC123-01)
|
||
func ExtractDeviceIDFromBatchRaw(data string) string {
|
||
m := regexp.MustCompile(`([A-Za-z0-9]+)-\d+`).FindStringSubmatch(data)
|
||
if len(m) == 2 {
|
||
Logger.Printf("从原始数据提取到设备ID: %s", m[1])
|
||
return m[1]
|
||
}
|
||
Logger.Printf("未能从原始数据中提取设备ID,跳过转发")
|
||
return ""
|
||
}
|
||
|
||
// ForwardRawData 将原始数据转发到设备配置的 TCP 目标
|
||
func ForwardRawData(deviceID string, raw string) error {
|
||
if deviceID == "" {
|
||
Logger.Printf("转发跳过:deviceID 为空")
|
||
return nil
|
||
}
|
||
|
||
dev, err := GetDevice(deviceID)
|
||
if err != nil {
|
||
Logger.Printf("查询设备配置失败 deviceID=%s: %v", deviceID, err)
|
||
return err
|
||
}
|
||
if dev == nil {
|
||
Logger.Printf("未找到设备配置 deviceID=%s,跳过转发", deviceID)
|
||
return nil
|
||
}
|
||
if !dev.ForwardEnable {
|
||
Logger.Printf("设备未启用转发 deviceID=%s,跳过转发", deviceID)
|
||
return nil
|
||
}
|
||
if !dev.Host.Valid || dev.Host.String == "" || !dev.Port.Valid || dev.Port.Int64 <= 0 {
|
||
Logger.Printf("设备转发目标未配置完整 deviceID=%s host=%v port=%v,跳过转发", deviceID, dev.Host, dev.Port)
|
||
return nil
|
||
}
|
||
|
||
address := fmt.Sprintf("%s:%d", dev.Host.String, dev.Port.Int64)
|
||
Logger.Printf("准备连接转发目标 deviceID=%s addr=%s", deviceID, address)
|
||
|
||
conn, err := net.DialTimeout("tcp", address, 5*time.Second)
|
||
if err != nil {
|
||
Logger.Printf("连接转发目标失败 deviceID=%s addr=%s: %v", deviceID, address, err)
|
||
return err
|
||
}
|
||
defer conn.Close()
|
||
Logger.Printf("连接转发目标成功 deviceID=%s addr=%s", deviceID, address)
|
||
|
||
if dev.RegCodeHex.Valid && dev.RegCodeHex.String != "" {
|
||
bytes, decErr := hex.DecodeString(dev.RegCodeHex.String)
|
||
if decErr != nil {
|
||
Logger.Printf("注册码HEX解码失败 deviceID=%s hex=%s: %v(将继续发送原始数据)", deviceID, dev.RegCodeHex.String, decErr)
|
||
} else {
|
||
Logger.Printf("发送注册码 deviceID=%s bytes=%d", deviceID, len(bytes))
|
||
if _, werr := conn.Write(bytes); werr != nil {
|
||
Logger.Printf("发送注册码失败 deviceID=%s: %v", deviceID, werr)
|
||
return werr
|
||
}
|
||
time.Sleep(1 * time.Second)
|
||
}
|
||
} else {
|
||
Logger.Printf("未配置注册码 deviceID=%s,直接发送原始数据", deviceID)
|
||
}
|
||
|
||
Logger.Printf("发送原始数据 deviceID=%s bytes=%d", deviceID, len(raw))
|
||
_, err = conn.Write([]byte(raw))
|
||
if err != nil {
|
||
Logger.Printf("发送原始数据失败 deviceID=%s: %v", deviceID, err)
|
||
return err
|
||
}
|
||
Logger.Printf("完成转发 deviceID=%s", deviceID)
|
||
return nil
|
||
}
|