angle_dtu/angle.go
2025-09-08 11:44:56 +08:00

139 lines
3.4 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package main
import (
"fmt"
"log"
"regexp"
"strconv"
"strings"
)
// 单个传感器数据结构
type SensorReading struct {
SerialNumber string // 传感器序列号,如 8513343-01
GroupID int // 组ID如 1
SensorID int // 传感器ID如 1-16
Temperature float64 // 温度值,如 32.9
X float64 // X轴值如 0.848
Y float64 // Y轴值如 2.100
Z float64 // Z轴默认为0
}
// 解析批量传感器数据
func parseBatchData(data string) ([]SensorReading, error) {
// 检查是否是批量数据格式
if !strings.Contains(data, "#{") || !strings.Contains(data, "}!") {
return nil, fmt.Errorf("不是批量数据格式")
}
// 提取批量数据部分 - 使用非贪婪匹配确保正确捕获内容
batchPattern := regexp.MustCompile(`#\{([\s\S]*?)\}!`)
batchMatches := batchPattern.FindStringSubmatch(data)
if len(batchMatches) != 2 {
return nil, fmt.Errorf("批量数据格式不正确")
}
// 获取批量数据内容
batchContent := batchMatches[1]
// 记录原始批量数据内容,用于调试
log.Printf("解析批量数据内容: %s", batchContent)
// 按行分割
lines := strings.Split(batchContent, "\n")
var readings []SensorReading
// 行解析正则表达式 - 匹配格式如: 8513343-01,1,1,32.9,0.848,2.100
linePattern := regexp.MustCompile(`([^,]+),(\d+),(\d+),([-]?\d+\.\d+),([-]?\d+\.\d+),([-]?\d+\.\d+)`)
for _, line := range lines {
// 清理行
line = strings.TrimSpace(line)
if line == "" {
continue
}
// 处理可能存在的回车符
line = strings.ReplaceAll(line, "\r", "")
// 解析行
matches := linePattern.FindStringSubmatch(line)
if len(matches) != 7 {
// 记录不匹配的行
log.Printf("无法匹配行: %s", line)
continue // 跳过不匹配的行
}
// 解析各个字段
serialNumber := matches[1]
groupID, err := strconv.Atoi(matches[2])
if err != nil {
continue
}
sensorID, err := strconv.Atoi(matches[3])
if err != nil {
continue
}
temperature, err := strconv.ParseFloat(matches[4], 64)
if err != nil {
continue
}
x, err := strconv.ParseFloat(matches[5], 64)
if err != nil {
continue
}
y, err := strconv.ParseFloat(matches[6], 64)
if err != nil {
continue
}
// 创建传感器读数对象
reading := SensorReading{
SerialNumber: serialNumber,
GroupID: groupID,
SensorID: sensorID,
Temperature: temperature,
X: x,
Y: y,
Z: 0.0, // Z轴默认为0
}
readings = append(readings, reading)
}
if len(readings) == 0 {
return nil, fmt.Errorf("未找到有效的传感器数据")
}
return readings, nil
}
// 保存批量传感器数据到数据库
func SaveBatchSensorData(readings []SensorReading) error {
for _, reading := range readings {
deviceID := 0
if idx := strings.Index(reading.SerialNumber, "-"); idx > 0 {
idPart := reading.SerialNumber[:idx]
if v, err := strconv.Atoi(idPart); err == nil {
deviceID = v
}
}
if deviceID > 0 {
if err := EnsureDeviceExists(deviceID); err != nil {
return fmt.Errorf("确保设备 %d 存在失败: %v", deviceID, err)
}
}
if err := SaveSensorData(reading.SensorID, reading.X, reading.Y, reading.Z, reading.Temperature, deviceID); err != nil {
return fmt.Errorf("保存传感器 %d 数据失败: %v", reading.SensorID, err)
}
}
return nil
}