fix:修复一些问题

This commit is contained in:
yarnom 2025-09-08 13:48:49 +08:00
parent 61e2d780ce
commit 79f5ae89df
4 changed files with 36 additions and 49 deletions

View File

@ -116,17 +116,14 @@ func parseBatchData(data string) ([]SensorReading, error) {
// 保存批量传感器数据到数据库 // 保存批量传感器数据到数据库
func SaveBatchSensorData(readings []SensorReading) error { func SaveBatchSensorData(readings []SensorReading) error {
for _, reading := range readings { for _, reading := range readings {
deviceID := 0 deviceID := ""
if idx := strings.Index(reading.SerialNumber, "-"); idx > 0 { if idx := strings.Index(reading.SerialNumber, "-"); idx > 0 {
idPart := reading.SerialNumber[:idx] deviceID = reading.SerialNumber[:idx]
if v, err := strconv.Atoi(idPart); err == nil {
deviceID = v
}
} }
if deviceID > 0 { if deviceID != "" {
if err := EnsureDeviceExists(deviceID); err != nil { if err := EnsureDeviceExists(deviceID); err != nil {
return fmt.Errorf("确保设备 %d 存在失败: %v", deviceID, err) return fmt.Errorf("确保设备 %s 存在失败: %v", deviceID, err)
} }
} }

22
db.go
View File

@ -3,6 +3,7 @@ package main
import ( import (
"database/sql" "database/sql"
"fmt" "fmt"
"strings"
"time" "time"
_ "github.com/go-sql-driver/mysql" _ "github.com/go-sql-driver/mysql"
@ -49,25 +50,25 @@ func CloseDB() {
} }
// EnsureDeviceExists 确保设备存在,不存在则创建为默认配置 // EnsureDeviceExists 确保设备存在,不存在则创建为默认配置
func EnsureDeviceExists(deviceID int) error { func EnsureDeviceExists(deviceID string) error {
if deviceID <= 0 { if strings.TrimSpace(deviceID) == "" {
return nil return nil
} }
_, err := db.Exec( _, err := db.Exec(
"INSERT INTO devices (id, forward_enable, host, port) VALUES (?, 0, NULL, NULL) ON DUPLICATE KEY UPDATE id = id", "INSERT INTO devices (device_id, forward_enable, host, port) VALUES (?, 0, NULL, NULL) ON DUPLICATE KEY UPDATE device_id = device_id",
deviceID, deviceID,
) )
return err return err
} }
// 保存传感器数据 - 将浮点值转换为整数存储添加温度与设备ID支持 // 保存传感器数据 - 将浮点值转换为整数存储添加温度与设备ID(字符串)支持
func SaveSensorData(sensorID int, x, y, z, temperature float64, deviceID int) error { func SaveSensorData(sensorID int, x, y, z, temperature float64, deviceID string) error {
xInt := int(x * SCALING_FACTOR) xInt := int(x * SCALING_FACTOR)
yInt := int(y * SCALING_FACTOR) yInt := int(y * SCALING_FACTOR)
zInt := int(z * SCALING_FACTOR) zInt := int(z * SCALING_FACTOR)
tempInt := int(temperature * SCALING_FACTOR) tempInt := int(temperature * SCALING_FACTOR)
if deviceID > 0 { if strings.TrimSpace(deviceID) != "" {
query := `INSERT INTO sensor_data (sensor_id, x_value, y_value, z_value, temperature, device_id) VALUES (?, ?, ?, ?, ?, ?)` query := `INSERT INTO sensor_data (sensor_id, x_value, y_value, z_value, temperature, device_id) VALUES (?, ?, ?, ?, ?, ?)`
_, err := db.Exec(query, sensorID, xInt, yInt, zInt, tempInt, deviceID) _, err := db.Exec(query, sensorID, xInt, yInt, zInt, tempInt, deviceID)
return err return err
@ -227,18 +228,19 @@ type SensorData struct {
// Device 表映射 // Device 表映射
type Device struct { type Device struct {
ID int ID int
DeviceID string
ForwardEnable bool ForwardEnable bool
Host sql.NullString Host sql.NullString
Port sql.NullInt64 Port sql.NullInt64
RegCodeHex sql.NullString RegCodeHex sql.NullString
} }
// GetDevice 获取设备配置 // GetDevice 获取设备配置按设备字符串ID
func GetDevice(deviceID int) (*Device, error) { func GetDevice(deviceID string) (*Device, error) {
row := db.QueryRow(`SELECT id, COALESCE(forward_enable, 0) as forward_enable, host, port, reg_code_hex FROM devices WHERE id = ?`, deviceID) row := db.QueryRow(`SELECT id, device_id, COALESCE(forward_enable, 0) as forward_enable, host, port, reg_code_hex FROM devices WHERE device_id = ?`, deviceID)
var d Device var d Device
var fe int var fe int
if err := row.Scan(&d.ID, &fe, &d.Host, &d.Port, &d.RegCodeHex); err != nil { if err := row.Scan(&d.ID, &d.DeviceID, &fe, &d.Host, &d.Port, &d.RegCodeHex); err != nil {
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
return nil, nil return nil, nil
} }

View File

@ -4,32 +4,22 @@ import (
"encoding/hex" "encoding/hex"
"fmt" "fmt"
"net" "net"
"regexp"
"time" "time"
) )
// ExtractDeviceIDFromBatchRaw 从批量原始数据中提取设备ID序列号形如 1513343-01 // ExtractDeviceIDFromBatchRaw 从批量原始数据中提取设备ID序列号形如 1513343-01 或 ABC123-01
func ExtractDeviceIDFromBatchRaw(data string) int { func ExtractDeviceIDFromBatchRaw(data string) string {
for i := 0; i < len(data); i++ { m := regexp.MustCompile(`([A-Za-z0-9]+)-\d+`).FindStringSubmatch(data)
if data[i] >= '0' && data[i] <= '9' { if len(m) == 2 {
j := i return m[1]
for j < len(data) && data[j] >= '0' && data[j] <= '9' {
j++
}
if j < len(data) && data[j] == '-' {
var v int
for k := i; k < j; k++ {
v = v*10 + int(data[k]-'0')
}
return v
}
}
} }
return 0 return ""
} }
// ForwardRawData 将原始数据转发到设备配置的 TCP 目标 // ForwardRawData 将原始数据转发到设备配置的 TCP 目标
func ForwardRawData(deviceID int, raw string) error { func ForwardRawData(deviceID string, raw string) error {
if deviceID <= 0 { if deviceID == "" {
return nil return nil
} }
dev, err := GetDevice(deviceID) dev, err := GetDevice(deviceID)

View File

@ -4,7 +4,6 @@ import (
"fmt" "fmt"
"net" "net"
"regexp" "regexp"
"strconv"
) )
// StartUDPServer 启动UDP服务器 // StartUDPServer 启动UDP服务器
@ -58,10 +57,10 @@ func handleUDPPacket(conn *net.UDPConn, addr *net.UDPAddr, data []byte) {
} }
// 尝试提取设备ID并透传原始数据 // 尝试提取设备ID并透传原始数据
if deviceID := ExtractDeviceIDFromBatchRaw(rawData); deviceID > 0 { if deviceID := ExtractDeviceIDFromBatchRaw(rawData); deviceID != "" {
go func(id int, payload string) { go func(id string, payload string) {
if fErr := ForwardRawData(id, payload); fErr != nil { if fErr := ForwardRawData(id, payload); fErr != nil {
Logger.Printf("转发设备 %d 数据失败: %v", id, fErr) Logger.Printf("转发设备 %s 数据失败: %v", id, fErr)
} }
}(deviceID, rawData) }(deviceID, rawData)
} }
@ -78,19 +77,18 @@ func handleUDPPacket(conn *net.UDPConn, addr *net.UDPAddr, data []byte) {
TCPDataLogger.Printf("解析成功 - UDP客户端: %s, 传感器ID: %d, 值: X=%.3f, Y=%.3f, Z=%.3f, 温度=%.1f°C", TCPDataLogger.Printf("解析成功 - UDP客户端: %s, 传感器ID: %d, 值: X=%.3f, Y=%.3f, Z=%.3f, 温度=%.1f°C",
remoteAddr, sensorID, x, y, z, temperature) remoteAddr, sensorID, x, y, z, temperature)
if err := SaveSensorData(sensorID, x, y, z, temperature, 0); err != nil { if err := SaveSensorData(sensorID, x, y, z, temperature, ""); err != nil {
Logger.Printf("保存传感器数据失败: %v", err) Logger.Printf("保存传感器数据失败: %v", err)
} }
// 从原始字符串尝试提取设备ID并透传 // 从原始字符串尝试提取设备ID并透传
if m := regexp.MustCompile(`([0-9]+)-\d+`).FindStringSubmatch(rawData); len(m) == 2 { if m := regexp.MustCompile(`([A-Za-z0-9]+)-\d+`).FindStringSubmatch(rawData); len(m) == 2 {
if id, convErr := strconv.Atoi(m[1]); convErr == nil && id > 0 { id := m[1]
go func(id int, payload string) { go func(id string, payload string) {
if fErr := ForwardRawData(id, payload); fErr != nil { if fErr := ForwardRawData(id, payload); fErr != nil {
Logger.Printf("转发设备 %d 数据失败: %v", id, fErr) Logger.Printf("转发设备 %s 数据失败: %v", id, fErr)
} }
}(id, rawData) }(id, rawData)
}
} }
} else { } else {
TCPDataLogger.Printf("无法解析从UDP客户端 %s 接收到的数据: %s, 错误: %v", remoteAddr, rawData, parseErr) TCPDataLogger.Printf("无法解析从UDP客户端 %s 接收到的数据: %s, 错误: %v", remoteAddr, rawData, parseErr)