go_rain_dtu/data_process.go
2025-04-24 14:44:30 +08:00

81 lines
2.2 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 (
"time"
)
// 传感器数据结构
type SensorData struct {
WindSpeed int
WindForce int
WindDirection8 int
WindDirection360 int
Humidity int
Temperature int
Noise int
PM25 int
PM10 int
AtmPressure int
Lux20WH int
Lux20WL int
Light20W int
OpticalRain int
CompassAngle int
SolarRadiation int
Timestamp time.Time
}
// 解析传感器数据
func parseData(data []byte) *SensorData {
// 检查响应格式是否正确
if len(data) < 37 || data[0] != 0x01 || data[1] != 0x03 || data[2] != 0x20 {
logger.Println("响应格式无效")
return nil
}
// 提取数据部分
dataBytes := data[3:35] // 跳过地址码、功能码、长度不包括CRC
sensorData := SensorData{
WindSpeed: bytesToInt(dataBytes[0:2]),
WindForce: bytesToInt(dataBytes[2:4]),
WindDirection8: bytesToInt(dataBytes[4:6]),
WindDirection360: bytesToInt(dataBytes[6:8]),
Humidity: bytesToInt(dataBytes[8:10]),
Temperature: bytesToInt(dataBytes[10:12]),
Noise: bytesToInt(dataBytes[12:14]),
PM25: bytesToInt(dataBytes[14:16]),
PM10: bytesToInt(dataBytes[16:18]),
AtmPressure: bytesToInt(dataBytes[18:20]),
Lux20WH: bytesToInt(dataBytes[20:22]),
Lux20WL: bytesToInt(dataBytes[22:24]),
Light20W: bytesToInt(dataBytes[24:26]),
OpticalRain: bytesToInt(dataBytes[26:28]),
CompassAngle: bytesToInt(dataBytes[28:30]),
SolarRadiation: bytesToInt(dataBytes[30:32]),
Timestamp: time.Now(),
}
return &sensorData
}
// 记录传感器数据到日志
func logSensorData(data SensorData) {
logger.Printf("[传感器] 时间: %s, 温度: %.1f°C, 湿度: %.1f%%, 风速: %.2fm/s (%d°), 雨量: %.1fmm, PM2.5: %dμg/m³",
data.Timestamp.Format("2006-01-02 15:04:05"),
float64(data.Temperature)/10.0,
float64(data.Humidity)/10.0,
float64(data.WindSpeed)/100.0,
data.WindDirection360,
float64(data.OpticalRain)/10.0,
data.PM25)
}
// 将两个字节转换为整数
func bytesToInt(bytes []byte) int {
if len(bytes) != 2 {
return 0
}
return int(bytes[0])<<8 | int(bytes[1])
}