This commit is contained in:
fengyarnom 2025-05-14 17:31:15 +08:00
commit 5b24835496
13 changed files with 2017 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
logs/

66
angle.go.bak Normal file
View File

@ -0,0 +1,66 @@
package main
import (
"fmt"
"io"
"log"
"net"
"time"
)
func handleConnection(conn net.Conn) {
defer conn.Close()
// 客户端地址信息
remoteAddr := conn.RemoteAddr().String()
fmt.Printf("客户端 %s 已连接\n", remoteAddr)
// 设置连接超时
conn.SetReadDeadline(time.Now().Add(time.Hour * 24)) // 24小时超时可以根据需要调整
buffer := make([]byte, 1024)
for {
// 读取客户端发送的数据
n, err := conn.Read(buffer)
if err != nil {
if err == io.EOF {
fmt.Printf("客户端 %s 已断开连接\n", remoteAddr)
} else {
fmt.Printf("从客户端 %s 读取数据时出错: %v\n", remoteAddr, err)
}
break
}
// 在终端显示接收到的数据
receivedData := buffer[:n]
fmt.Printf("从 %s 接收到数据: %s\n", remoteAddr, string(receivedData))
// 可选:回复客户端确认消息
// conn.Write([]byte("服务器已收到消息"))
}
}
func main() {
// 监听端口
port := ":10002"
listener, err := net.Listen("tcp", port)
if err != nil {
log.Fatalf("无法监听端口 %s: %v", port, err)
}
defer listener.Close()
fmt.Printf("TCP服务器已启动正在监听端口 %s\n", port)
// 接受连接并处理
for {
conn, err := listener.Accept()
if err != nil {
fmt.Printf("接受连接失败: %v\n", err)
continue
}
// 为每个连接创建一个goroutine
go handleConnection(conn)
}
}

206
db.go Normal file
View File

@ -0,0 +1,206 @@
package main
import (
"database/sql"
"fmt"
"time"
_ "github.com/go-sql-driver/mysql"
)
var db *sql.DB
const SCALING_FACTOR = 1000 // 浮点数到整数的转换因子
// 初始化数据库连接
func InitDB() error {
// 调整这些参数以匹配你的MySQL配置
username := "root"
password := "root" // 请替换为你的实际密码
host := "localhost"
port := "3306"
dbName := "probe_db"
// 连接字符串
dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?parseTime=true", username, password, host, port, dbName)
var err error
db, err = sql.Open("mysql", dsn)
if err != nil {
return err
}
// 测试连接
err = db.Ping()
if err != nil {
return err
}
// 设置连接池参数
db.SetMaxOpenConns(10)
db.SetMaxIdleConns(5)
db.SetConnMaxLifetime(time.Minute * 5)
return nil
}
// 关闭数据库连接
func CloseDB() {
if db != nil {
db.Close()
}
}
// 保存传感器数据 - 将浮点值转换为整数存储
func SaveSensorData(sensorID int, x, y, z float64) error {
// 转换为整数乘以1000并四舍五入
xInt := int(x * SCALING_FACTOR)
yInt := int(y * SCALING_FACTOR)
zInt := int(z * SCALING_FACTOR)
query := `INSERT INTO sensor_data (sensor_id, x_value, y_value, z_value) VALUES (?, ?, ?, ?)`
_, err := db.Exec(query, sensorID, xInt, yInt, zInt)
return err
}
// 获取传感器数据 - 从整数转换回浮点数
// 获取传感器数据 - 添加时间范围
func GetSensorData(sensorID int, limit int, startDate time.Time, endDate time.Time) ([]SensorData, error) {
// 基本查询
query := `SELECT id, sensor_id, x_value, y_value, z_value,
timestamp as timestamp
FROM sensor_data
WHERE sensor_id = ?`
// 添加查询条件
var args []interface{}
args = append(args, sensorID)
// 添加日期范围
if !startDate.IsZero() {
query += " AND timestamp >= ?"
args = append(args, startDate)
}
if !endDate.IsZero() {
query += " AND timestamp <= ?"
args = append(args, endDate)
}
// 添加排序和限制
query += " ORDER BY timestamp DESC LIMIT ?"
args = append(args, limit)
// 执行查询
rows, err := db.Query(query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
var result []SensorData
for rows.Next() {
var data SensorData
var xInt, yInt, zInt int
err := rows.Scan(&data.ID, &data.SensorID, &xInt, &yInt, &zInt, &data.Timestamp)
if err != nil {
return nil, err
}
// 从整数转换回浮点数
data.X = float64(xInt) / SCALING_FACTOR
data.Y = float64(yInt) / SCALING_FACTOR
data.Z = float64(zInt) / SCALING_FACTOR
result = append(result, data)
}
return result, nil
}
// 获取所有传感器数据
func GetAllSensorData(limit int, startDate time.Time, endDate time.Time) ([]SensorData, error) {
// 基本查询
query := `SELECT id, sensor_id, x_value, y_value, z_value,
timestamp as timestamp
FROM sensor_data
WHERE 1=1`
// 添加查询条件
var args []interface{}
// 添加日期范围
if !startDate.IsZero() {
query += " AND timestamp >= ?"
args = append(args, startDate)
}
if !endDate.IsZero() {
query += " AND timestamp <= ?"
args = append(args, endDate)
}
// 添加排序和限制
query += " ORDER BY timestamp DESC LIMIT ?"
args = append(args, limit)
// 执行查询
rows, err := db.Query(query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
var result []SensorData
for rows.Next() {
var data SensorData
var xInt, yInt, zInt int
err := rows.Scan(&data.ID, &data.SensorID, &xInt, &yInt, &zInt, &data.Timestamp)
if err != nil {
return nil, err
}
// 从整数转换回浮点数
data.X = float64(xInt) / SCALING_FACTOR
data.Y = float64(yInt) / SCALING_FACTOR
data.Z = float64(zInt) / SCALING_FACTOR
result = append(result, data)
}
return result, nil
}
// 获取所有传感器ID
func GetAllSensorIDs() ([]int, error) {
query := `SELECT DISTINCT sensor_id FROM sensor_data ORDER BY sensor_id`
rows, err := db.Query(query)
if err != nil {
return nil, err
}
defer rows.Close()
var ids []int
for rows.Next() {
var id int
if err := rows.Scan(&id); err != nil {
return nil, err
}
ids = append(ids, id)
}
return ids, nil
}
// SensorData 结构用于存储传感器数据
type SensorData struct {
ID int `json:"id"`
SensorID int `json:"sensor_id"`
X float64 `json:"x"`
Y float64 `json:"y"`
Z float64 `json:"z"`
Timestamp time.Time `json:"timestamp"`
}

7
go.mod Normal file
View File

@ -0,0 +1,7 @@
module probe-monitor
go 1.24.2
require github.com/go-sql-driver/mysql v1.9.2
require filippo.io/edwards25519 v1.1.0 // indirect

4
go.sum Normal file
View File

@ -0,0 +1,4 @@
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
github.com/go-sql-driver/mysql v1.9.2 h1:4cNKDYQ1I84SXslGddlsrMhc8k4LeDVj6Ad6WRjiHuU=
github.com/go-sql-driver/mysql v1.9.2/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU=

169
http_server.go Normal file
View File

@ -0,0 +1,169 @@
package main
import (
"encoding/json"
"fmt"
"html/template"
"time"
"log"
"net/http"
"os"
"path/filepath"
"strconv"
)
// 启动HTTP服务器
func StartHTTPServer(address string) error {
// 主页
http.HandleFunc("/", handleIndex)
// API路由
http.HandleFunc("/api/data", handleGetData)
http.HandleFunc("/api/sensors", handleGetSensors)
http.HandleFunc("/api/clients", handleGetClients)
fmt.Printf("HTTP服务器已启动正在监听 %s\n", address)
return http.ListenAndServe(address, nil)
}
// 处理主页
func handleIndex(w http.ResponseWriter, r *http.Request) {
log.Printf("接收到主页请求: %s", r.URL.Path)
// 确保templates目录存在
templatePath := "templates/index.html"
absPath, _ := filepath.Abs(templatePath)
_, err := os.Stat(templatePath)
if os.IsNotExist(err) {
log.Printf("错误: 模板文件不存在: %s", absPath)
http.Error(w, "模板文件不存在", http.StatusInternalServerError)
return
}
tmpl, err := template.ParseFiles(templatePath)
if err != nil {
log.Printf("错误: 无法解析模板: %v", err)
http.Error(w, "无法加载模板:"+err.Error(), http.StatusInternalServerError)
return
}
log.Printf("模板加载成功,开始渲染")
err = tmpl.Execute(w, nil)
if err != nil {
log.Printf("错误: 渲染模板出错: %v", err)
http.Error(w, "渲染模板出错:"+err.Error(), http.StatusInternalServerError)
}
log.Printf("模板渲染完成")
}
// 处理获取传感器数据的API
func handleGetData(w http.ResponseWriter, r *http.Request) {
log.Printf("接收到获取数据请求: %s", r.URL.String())
w.Header().Set("Content-Type", "application/json")
// 获取查询参数
sensorIDStr := r.URL.Query().Get("sensor_id")
limitStr := r.URL.Query().Get("limit")
startDateStr := r.URL.Query().Get("start_date")
endDateStr := r.URL.Query().Get("end_date")
// 默认值
limit := 500
// 处理传感器ID
var sensorID int
var err error
if sensorIDStr != "" && sensorIDStr != "all" {
sensorID, err = strconv.Atoi(sensorIDStr)
if err != nil {
log.Printf("错误: 无效的传感器ID: %s", sensorIDStr)
http.Error(w, "无效的传感器ID", http.StatusBadRequest)
return
}
}
// 处理限制条数
if limitStr != "" {
limit, err = strconv.Atoi(limitStr)
if err != nil || limit <= 0 {
log.Printf("错误: 无效的记录数限制: %s", limitStr)
http.Error(w, "无效的记录数限制", http.StatusBadRequest)
return
}
}
// 处理日期范围
var startDate, endDate time.Time
if startDateStr != "" {
startDate, err = time.Parse("2006-01-02T15:04", startDateStr)
if err != nil {
log.Printf("错误: 无效的开始日期: %s, %v", startDateStr, err)
http.Error(w, "无效的开始日期", http.StatusBadRequest)
return
}
}
if endDateStr != "" {
endDate, err = time.Parse("2006-01-02T15:04", endDateStr)
if err != nil {
log.Printf("错误: 无效的结束日期: %s, %v", endDateStr, err)
http.Error(w, "无效的结束日期", http.StatusBadRequest)
return
}
}
// 获取数据
var data []SensorData
if sensorIDStr == "all" || sensorIDStr == "" {
data, err = GetAllSensorData(limit, startDate, endDate)
} else {
data, err = GetSensorData(sensorID, limit, startDate, endDate)
}
if err != nil {
log.Printf("错误: 获取数据失败: %v", err)
http.Error(w, "获取数据失败:"+err.Error(), http.StatusInternalServerError)
return
}
log.Printf("成功获取到 %d 条数据记录", len(data))
// 返回JSON
if err := json.NewEncoder(w).Encode(data); err != nil {
log.Printf("错误: 编码JSON失败: %v", err)
http.Error(w, "编码JSON失败"+err.Error(), http.StatusInternalServerError)
}
}
// 处理获取所有传感器ID的API
func handleGetSensors(w http.ResponseWriter, r *http.Request) {
log.Printf("接收到获取传感器列表请求")
w.Header().Set("Content-Type", "application/json")
// 获取所有传感器ID
sensorIDs, err := GetAllSensorIDs()
if err != nil {
log.Printf("错误: 获取传感器ID失败: %v", err)
http.Error(w, "获取传感器ID失败"+err.Error(), http.StatusInternalServerError)
return
}
log.Printf("成功获取到 %d 个传感器ID", len(sensorIDs))
// 返回JSON
if err := json.NewEncoder(w).Encode(sensorIDs); err != nil {
log.Printf("错误: 编码JSON失败: %v", err)
http.Error(w, "编码JSON失败"+err.Error(), http.StatusInternalServerError)
}
}
func handleGetClients(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
clients := getAllClients()
if err := json.NewEncoder(w).Encode(clients); err != nil {
log.Printf("错误: 编码客户端信息JSON失败: %v", err)
http.Error(w, "编码JSON失败"+err.Error(), http.StatusInternalServerError)
}
}

89
logger.go Normal file
View File

@ -0,0 +1,89 @@
// logger.go
package main
import (
"fmt"
"io"
"log"
"os"
"path/filepath"
"time"
)
// 日志文件
var (
logFile *os.File
Logger *log.Logger // 导出Logger供其他包使用
TCPDataLogger *log.Logger // 专门用于记录TCP数据的日志
)
// 初始化日志系统
func InitLogger() error {
// 创建logs目录
logsDir := "logs"
if err := os.MkdirAll(logsDir, 0755); err != nil {
return fmt.Errorf("创建日志目录失败: %v", err)
}
// 创建当天的日志文件
today := time.Now().Format("2006-01-02")
logFilePath := filepath.Join(logsDir, fmt.Sprintf("server_%s.log", today))
file, err := os.OpenFile(logFilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return fmt.Errorf("打开日志文件失败: %v", err)
}
logFile = file
// 创建一个多输出的logger同时写入文件和控制台
multiWriter := io.MultiWriter(os.Stdout, file)
Logger = log.New(multiWriter, "", log.Ldate|log.Ltime|log.Lshortfile)
// 创建TCP数据日志文件
tcpDataFilePath := filepath.Join(logsDir, fmt.Sprintf("tcp_data_%s.log", today))
tcpDataFile, err := os.OpenFile(tcpDataFilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return fmt.Errorf("打开TCP数据日志文件失败: %v", err)
}
// TCP数据日志同时写入文件和控制台
tcpDataMultiWriter := io.MultiWriter(os.Stdout, tcpDataFile)
TCPDataLogger = log.New(tcpDataMultiWriter, "TCP_DATA: ", log.Ldate|log.Ltime)
// 替换标准日志
log.SetOutput(multiWriter)
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
Logger.Println("日志系统初始化完成")
return nil
}
// 关闭日志文件
func CloseLogger() {
if logFile != nil {
logFile.Close()
}
}
// 日志轮转,每天创建新的日志文件
func StartLogRotation() {
go func() {
for {
// 等待到明天0点
now := time.Now()
next := now.Add(24 * time.Hour)
next = time.Date(next.Year(), next.Month(), next.Day(), 0, 0, 0, 0, next.Location())
duration := next.Sub(now)
time.Sleep(duration)
// 重新初始化日志
Logger.Println("开始日志轮转...")
CloseLogger()
if err := InitLogger(); err != nil {
log.Printf("日志轮转失败: %v", err)
}
}
}()
}

51
main.go Normal file
View File

@ -0,0 +1,51 @@
package main
import (
"fmt"
"log"
"sync"
)
func main() {
// 初始化日志
if err := InitLogger(); err != nil {
log.Fatalf("初始化日志系统失败: %v", err)
}
defer CloseLogger()
// 启动日志轮转
StartLogRotation()
// 初始化数据库
err := InitDB()
if err != nil {
log.Fatalf("初始化数据库失败: %v", err)
}
defer CloseDB()
fmt.Println("iProbe 斜侧仪监控系统启动中...")
var wg sync.WaitGroup
// 启动TCP服务器
wg.Add(1)
go func() {
defer wg.Done()
if err := StartTCPServer(":10002"); err != nil {
log.Fatalf("TCP服务器启动失败: %v", err)
}
}()
// 启动HTTP服务器
wg.Add(1)
go func() {
defer wg.Done()
if err := StartHTTPServer(":10001"); err != nil {
log.Fatalf("HTTP服务器启动失败: %v", err)
}
}()
fmt.Println("服务器已启动成功")
fmt.Println("- HTTP接口: http://localhost:10001")
fmt.Println("- TCP接口: localhost:10002")
wg.Wait()
}

BIN
probe-monitor Executable file

Binary file not shown.

99
static/css/main.css Normal file
View File

@ -0,0 +1,99 @@
/* 基本样式和Flex布局 */
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
.header {
padding: 10px;
text-align: center;
border-bottom: 1px solid #ddd;
}
.container {
max-width: 1200px;
margin: 0 auto;
padding: 15px;
}
.controls {
display: flex;
flex-wrap: wrap;
gap: 10px;
margin-bottom: 20px;
padding: 10px;
border: 1px solid #ddd;
border-radius: 5px;
}
.control-group {
display: flex;
align-items: center;
gap: 5px;
}
select, input, button {
padding: 5px;
}
button {
cursor: pointer;
}
.chart-container {
margin-bottom: 20px;
border: 1px solid #ddd;
border-radius: 5px;
padding: 10px;
}
canvas {
width: 100%;
max-height: 400px;
}
.table-container {
overflow-x: auto;
margin-bottom: 20px;
border: 1px solid #ddd;
border-radius: 5px;
padding: 10px;
}
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #f8f8f8;
}
tr:nth-child(even) {
background-color: #f9f9f9;
}
.footer {
text-align: center;
padding: 10px;
border-top: 1px solid #ddd;
}
/* 响应式设计 */
@media (max-width: 768px) {
.controls {
flex-direction: column;
align-items: stretch;
}
.control-group {
justify-content: space-between;
}
}

431
static/js/main.js Normal file
View File

@ -0,0 +1,431 @@
let sensorChart = null;
let refreshInterval = null;
let allSensors = [];
let currentSensorData = [];
// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
// 初始化日期选择器为今天
initializeDatePickers();
// 加载所有传感器ID
loadSensors();
// 添加事件监听器
setupEventListeners();
// 设置自动刷新
setupAutoRefresh();
});
// 初始化日期选择器
function initializeDatePickers() {
const now = new Date();
const today = now.toISOString().split('T')[0];
const time = now.toTimeString().split(' ')[0].substring(0, 5);
// 设置默认的开始时间为当天00:00
document.getElementById('startDate').value = `${today}T00:00`;
// 设置默认的结束时间为当前时间
document.getElementById('endDate').value = `${today}T${time}`;
}
// 设置事件监听器
function setupEventListeners() {
// 查询按钮
document.getElementById('queryBtn').addEventListener('click', function() {
loadData();
});
// 重置按钮
document.getElementById('resetBtn').addEventListener('click', function() {
resetFilters();
});
// 传感器选择变化
document.getElementById('sensorSelect').addEventListener('change', function() {
loadData();
});
// 记录数限制变化
document.getElementById('limitSelect').addEventListener('change', function() {
loadData();
});
// 导出CSV按钮
document.getElementById('exportBtn').addEventListener('click', function() {
exportToCSV();
});
}
// 设置自动刷新
function setupAutoRefresh() {
const autoRefreshCheckbox = document.getElementById('autoRefresh');
// 初始化自动刷新
if (autoRefreshCheckbox.checked) {
startAutoRefresh();
}
// 监听复选框变化
autoRefreshCheckbox.addEventListener('change', function() {
if (this.checked) {
startAutoRefresh();
} else {
stopAutoRefresh();
}
});
}
// 开始自动刷新
function startAutoRefresh() {
if (refreshInterval) {
clearInterval(refreshInterval);
}
refreshInterval = setInterval(loadData, 10000); // 10秒刷新一次
}
// 停止自动刷新
function stopAutoRefresh() {
if (refreshInterval) {
clearInterval(refreshInterval);
refreshInterval = null;
}
}
// 重置筛选条件
function resetFilters() {
initializeDatePickers();
document.getElementById('sensorSelect').value = 'all';
document.getElementById('limitSelect').value = '100';
loadData();
}
// 加载所有传感器ID
function loadSensors() {
fetch('/api/sensors')
.then(response => {
if (!response.ok) {
throw new Error('获取传感器列表失败');
}
return response.json();
})
.then(data => {
allSensors = data;
updateSensorSelect(data);
// 加载数据
loadData();
})
.catch(error => {
console.error('加载传感器列表出错:', error);
alert('加载传感器列表出错: ' + error.message);
});
}
// 更新传感器选择下拉框
function updateSensorSelect(sensors) {
const select = document.getElementById('sensorSelect');
// 保留"所有传感器"选项
const allOption = select.querySelector('option[value="all"]');
select.innerHTML = '';
select.appendChild(allOption);
if (sensors.length === 0) {
const option = document.createElement('option');
option.value = '';
option.textContent = '没有可用的传感器';
select.appendChild(option);
return;
}
sensors.forEach(id => {
const option = document.createElement('option');
option.value = id;
option.textContent = `传感器 ${id}`;
select.appendChild(option);
});
}
// 加载传感器数据
function loadData() {
const sensorID = document.getElementById('sensorSelect').value;
const limit = document.getElementById('limitSelect').value;
const startDate = document.getElementById('startDate').value;
const endDate = document.getElementById('endDate').value;
let url = '/api/data?';
let params = [];
// 添加查询参数
if (sensorID !== 'all') {
params.push(`sensor_id=${sensorID}`);
}
if (limit) {
params.push(`limit=${limit}`);
}
if (startDate) {
params.push(`start_date=${encodeURIComponent(startDate)}`);
}
if (endDate) {
params.push(`end_date=${encodeURIComponent(endDate)}`);
}
url += params.join('&');
// 显示加载状态
document.getElementById('queryBtn').textContent = '加载中...';
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error('获取传感器数据失败');
}
return response.json();
})
.then(data => {
currentSensorData = data;
updateTable(data);
updateChart(data);
document.getElementById('queryBtn').textContent = '查询数据';
})
.catch(error => {
console.error('加载数据出错:', error);
alert('加载数据出错: ' + error.message);
document.getElementById('queryBtn').textContent = '查询数据';
});
}
// 更新数据表格
function updateTable(data) {
const tableBody = document.getElementById('tableBody');
tableBody.innerHTML = '';
if (data.length === 0) {
const row = document.createElement('tr');
row.innerHTML = '<td colspan="6" style="text-align: center;">没有数据</td>';
tableBody.appendChild(row);
return;
}
data.forEach(item => {
const row = document.createElement('tr');
// 解析时间并调整为中国时间UTC+8
const date = new Date(item.timestamp);
// 减去8小时因为数据库时间似乎比实际时间早了8小时
date.setHours(date.getHours() - 8);
// 格式化为中文日期时间格式
const formattedDate =
date.getFullYear() + '/' +
(date.getMonth() + 1).toString().padStart(2, '0') + '/' +
date.getDate().toString().padStart(2, '0') + ' ' +
date.getHours().toString().padStart(2, '0') + ':' +
date.getMinutes().toString().padStart(2, '0') + ':' +
date.getSeconds().toString().padStart(2, '0');
row.innerHTML =
'<td>' + item.id + '</td>' +
'<td>' + item.sensor_id + '</td>' +
'<td>' + item.x.toFixed(3) + '</td>' +
'<td>' + item.y.toFixed(3) + '</td>' +
'<td>' + item.z.toFixed(3) + '</td>' +
'<td>' + formattedDate + '</td>';
tableBody.appendChild(row);
});
}
// 更新图表
function updateChart(data) {
// 准备图表数据
const chartData = prepareChartData(data);
// 如果图表已经存在,销毁它
if (sensorChart) {
sensorChart.destroy();
}
// 获取图表Canvas
const ctx = document.getElementById('sensorChart').getContext('2d');
// 创建新图表
sensorChart = new Chart(ctx, {
type: 'line',
data: chartData,
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
title: {
display: true,
text: '传感器数据趋势'
},
tooltip: {
callbacks: {
label: function(context) {
let label = context.dataset.label || '';
if (label) {
label += ': ';
}
if (context.parsed.y !== null) {
label += context.parsed.y.toFixed(3);
}
return label;
}
}
}
},
scales: {
x: {
title: {
display: true,
text: '时间'
}
},
y: {
title: {
display: true,
text: '值'
}
}
}
}
});
}
// 准备图表数据
function prepareChartData(data) {
// 如果没有数据,返回空数据集
if (data.length === 0) {
return {
labels: [],
datasets: []
};
}
// 反转数据以便按时间先后顺序显示
const sortedData = [...data].sort((a, b) => {
return new Date(a.timestamp) - new Date(b.timestamp);
});
// 获取所有传感器ID
let sensorIDs = [...new Set(sortedData.map(item => item.sensor_id))];
// 按传感器ID分组数据
let datasets = [];
let labels = [];
// 准备时间标签(使用第一个传感器的数据)
if (sensorIDs.length > 0) {
const firstSensorData = sortedData.filter(item => item.sensor_id === sensorIDs[0]);
labels = firstSensorData.map(item => {
const date = new Date(item.timestamp);
date.setHours(date.getHours() - 8); // 调整时区
return date.toLocaleString('zh-CN', {
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit'
});
});
}
// 定义颜色
const colors = [
'rgb(75, 192, 192)',
'rgb(255, 99, 132)',
'rgb(54, 162, 235)',
'rgb(255, 205, 86)',
'rgb(153, 102, 255)',
'rgb(255, 159, 64)'
];
// 为X, Y, Z创建不同的数据集
const dataTypes = [
{ key: 'x', label: 'X值' },
{ key: 'y', label: 'Y值' },
{ key: 'z', label: 'Z值' }
];
sensorIDs.forEach((sensorID, sensorIndex) => {
const sensorData = sortedData.filter(item => item.sensor_id === sensorID);
dataTypes.forEach((type, typeIndex) => {
const colorIndex = (sensorIndex * dataTypes.length + typeIndex) % colors.length;
datasets.push({
label: `传感器${sensorID} - ${type.label}`,
data: sensorData.map(item => item[type.key]),
fill: false,
borderColor: colors[colorIndex],
tension: 0.1
});
});
});
return {
labels: labels,
datasets: datasets
};
}
// 导出到CSV文件
function exportToCSV() {
if (currentSensorData.length === 0) {
alert('没有数据可导出');
return;
}
// 准备CSV内容
let csvContent = "ID,传感器ID,X值,Y值,Z值,时间戳\n";
currentSensorData.forEach(item => {
// 解析时间并调整为中国时间
const date = new Date(item.timestamp);
date.setHours(date.getHours() - 8);
// 格式化日期
const formattedDate =
date.getFullYear() + '/' +
(date.getMonth() + 1).toString().padStart(2, '0') + '/' +
date.getDate().toString().padStart(2, '0') + ' ' +
date.getHours().toString().padStart(2, '0') + ':' +
date.getMinutes().toString().padStart(2, '0') + ':' +
date.getSeconds().toString().padStart(2, '0');
// 添加一行数据
csvContent +=
item.id + "," +
item.sensor_id + "," +
item.x.toFixed(3) + "," +
item.y.toFixed(3) + "," +
item.z.toFixed(3) + "," +
formattedDate + "\n";
});
// 创建Blob对象
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
// 创建下载链接
const link = document.createElement("a");
const url = URL.createObjectURL(blob);
// 设置下载属性
link.setAttribute("href", url);
link.setAttribute("download", "sensor_data.csv");
// 添加到文档并点击
document.body.appendChild(link);
link.click();
// 清理
document.body.removeChild(link);
}

255
tcp_server.go Normal file
View File

@ -0,0 +1,255 @@
// tcp_server.go
package main
import (
"fmt"
"io"
"net"
"regexp"
"strconv"
"strings"
"sync"
"time"
)
// 客户端信息结构
type ClientInfo struct {
IP string // IP地址
Port string // 端口
LastSeen time.Time // 最后活跃时间
}
// 客户端列表(使用互斥锁保护的映射)
var (
clientsMutex sync.Mutex
clients = make(map[string]*ClientInfo)
)
// StartTCPServer 启动TCP服务器
func StartTCPServer(address string) error {
listener, err := net.Listen("tcp", address)
if err != nil {
return err
}
// 启动客户端清理
startClientCleanup()
Logger.Printf("TCP服务器已启动正在监听 %s\n", address)
for {
conn, err := listener.Accept()
if err != nil {
Logger.Printf("接受连接失败: %v", err)
continue
}
go handleConnection(conn)
}
}
// handleConnection 处理客户端连接
func handleConnection(conn net.Conn) {
defer conn.Close()
// 获取客户端信息
remoteAddr := conn.RemoteAddr().String()
Logger.Printf("新的客户端连接: %s", remoteAddr)
// 添加到在线客户端列表
addClient(remoteAddr)
buffer := make([]byte, 1024)
for {
// 读取数据
n, err := conn.Read(buffer)
if err != nil {
if err != io.EOF {
Logger.Printf("从客户端读取失败 %s: %v", remoteAddr, err)
} else {
Logger.Printf("客户端断开连接 %s", remoteAddr)
}
removeClient(remoteAddr)
break
}
// 将字节数据转换为字符串,并记录原始数据
rawData := string(buffer[:n])
TCPDataLogger.Printf("从客户端 %s 接收到原始数据: %s", remoteAddr, rawData)
// 尝试解析数据
sensorID, x, y, z, err := parseData(rawData)
if err == nil {
TCPDataLogger.Printf("解析成功 - 客户端: %s, 传感器ID: %d, 值: X=%.3f, Y=%.3f, Z=%.3f",
remoteAddr, sensorID, x, y, z)
// 保存数据到数据库
if err := SaveSensorData(sensorID, x, y, z); err != nil {
Logger.Printf("保存传感器数据失败: %v", err)
}
} else {
TCPDataLogger.Printf("无法解析从客户端 %s 接收到的数据: %s, 错误: %v", remoteAddr, rawData, err)
}
// 发送响应
resp := "OK\n"
if _, err := conn.Write([]byte(resp)); err != nil {
Logger.Printf("发送响应到客户端 %s 失败: %v", remoteAddr, err)
removeClient(remoteAddr)
break
}
// 更新客户端最后活跃时间
updateClientLastSeen(remoteAddr)
}
}
// parseData 使用正则表达式解析传感器数据
func parseData(data string) (int, float64, float64, float64, error) {
// 使用正则表达式匹配数据格式
pattern := regexp.MustCompile(`(\d+):([-]?\d+\.\d+),\s*([-]?\d+\.\d+),\s*([-]?\d+\.\d+)`)
matches := pattern.FindStringSubmatch(data)
if len(matches) != 5 {
return 0, 0, 0, 0, fmt.Errorf("数据格式不正确: %s", data)
}
// 解析传感器ID和三个浮点数值
sensorID, err := strconv.Atoi(matches[1])
if err != nil {
return 0, 0, 0, 0, fmt.Errorf("解析传感器ID失败: %v", err)
}
x, err := strconv.ParseFloat(strings.TrimSpace(matches[2]), 64)
if err != nil {
return 0, 0, 0, 0, fmt.Errorf("解析X值失败: %v", err)
}
y, err := strconv.ParseFloat(strings.TrimSpace(matches[3]), 64)
if err != nil {
return 0, 0, 0, 0, fmt.Errorf("解析Y值失败: %v", err)
}
z, err := strconv.ParseFloat(strings.TrimSpace(matches[4]), 64)
if err != nil {
return 0, 0, 0, 0, fmt.Errorf("解析Z值失败: %v", err)
}
return sensorID, x, y, z, nil
}
// addClient 添加客户端
func addClient(addr string) {
clientsMutex.Lock()
defer clientsMutex.Unlock()
// 解析地址
host, port, err := net.SplitHostPort(addr)
if err != nil {
Logger.Printf("解析客户端地址失败 %s: %v", addr, err)
host = addr
port = "unknown"
}
// 添加或更新客户端
clients[addr] = &ClientInfo{
IP: host,
Port: port,
LastSeen: time.Now(),
}
Logger.Printf("添加新客户端: %s", addr)
}
// updateClientLastSeen 更新客户端最后活跃时间
func updateClientLastSeen(addr string) {
clientsMutex.Lock()
defer clientsMutex.Unlock()
if client, exists := clients[addr]; exists {
client.LastSeen = time.Now()
}
}
// removeClient 移除客户端
func removeClient(addr string) {
clientsMutex.Lock()
defer clientsMutex.Unlock()
// 我们只更新最后活跃时间而不实际删除,
// 这样前端可以知道客户端已断开连接
if client, exists := clients[addr]; exists {
client.LastSeen = time.Now()
Logger.Printf("客户端标记为断开连接: %s", addr)
}
}
// getAllClients 获取所有客户端信息
func getAllClients() []map[string]interface{} {
clientsMutex.Lock()
defer clientsMutex.Unlock()
now := time.Now()
result := make([]map[string]interface{}, 0, len(clients))
for addr, client := range clients {
// 计算最后活跃时间
lastSeenDuration := now.Sub(client.LastSeen)
// 如果超过1天未活跃则删除
if lastSeenDuration > 24*time.Hour {
delete(clients, addr)
continue
}
// 在线状态 - 10分钟内有活动
isOnline := lastSeenDuration < 10*time.Minute
result = append(result, map[string]interface{}{
"address": addr,
"ip": client.IP,
"port": client.Port,
"lastSeen": client.LastSeen,
"isOnline": isOnline,
"lastSeenFormatted": formatDuration(lastSeenDuration),
})
}
return result
}
// formatDuration 格式化持续时间为友好的字符串
func formatDuration(d time.Duration) string {
if d < time.Minute {
return "刚刚"
} else if d < time.Hour {
return fmt.Sprintf("%d分钟前", int(d.Minutes()))
} else if d < 24*time.Hour {
return fmt.Sprintf("%d小时前", int(d.Hours()))
} else {
return fmt.Sprintf("%d天前", int(d.Hours()/24))
}
}
// startClientCleanup 启动清理过期客户端的goroutine
func startClientCleanup() {
go func() {
for {
time.Sleep(1 * time.Hour) // 每小时检查一次
clientsMutex.Lock()
now := time.Now()
for addr, client := range clients {
if now.Sub(client.LastSeen) > 24*time.Hour {
delete(clients, addr)
Logger.Printf("移除过期客户端: %s", addr)
}
}
clientsMutex.Unlock()
}
}()
}

639
templates/index.html Normal file
View File

@ -0,0 +1,639 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>测斜仪数据</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
.header {
padding: 10px;
text-align: center;
border-bottom: 1px solid #ddd;
}
.container {
max-width: 1200px;
margin: 0 auto;
padding: 15px;
}
.controls {
display: flex;
flex-wrap: wrap;
gap: 10px;
margin-bottom: 20px;
padding: 10px;
border: 1px solid #ddd;
border-radius: 1px;
}
.control-group {
display: flex;
align-items: center;
gap: 5px;
}
select, input, button {
padding: 5px;
}
button {
cursor: pointer;
}
.chart-container {
margin-bottom: 20px;
border: 1px solid #ddd;
border-radius: 1px;
padding: 10px;
}
canvas {
width: 100%;
max-height: 400px;
}
.table-container {
overflow-x: auto;
margin-bottom: 20px;
border: 1px solid #ddd;
border-radius: 5px;
padding: 10px;
}
h2{
text-align:center;
}
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #f8f8f8;
}
tr:nth-child(even) {
background-color: #f9f9f9;
}
.footer {
text-align: center;
padding: 10px;
border-top: 1px solid #ddd;
}
@media (max-width: 768px) {
.controls {
flex-direction: column;
align-items: stretch;
}
.control-group {
justify-content: space-between;
}
}
</style>
</head>
<body>
<div class="header">
<h1>测斜仪数据</h1>
</div>
<div class="container">
<div class="controls">
<div class="control-group">
<label for="sensorSelect">选择探头:</label>
<select id="sensorSelect">
<option value="all">所有探头</option>
</select>
</div>
<div class="control-group">
<label for="limitSelect">显示记录数:</label>
<select id="limitSelect">
<option value="10">10</option>
<option value="50">50</option>
<option value="100">100</option>
<option value="200">200</option>
<option value="500" selected>500</option>
<option value="1000">1000</option>
<option value="2000">2000</option>
<option value="5000">5000</option>
</select>
</div>
<div class="control-group">
<label for="startDate">开始日期:</label>
<input type="datetime-local" id="startDate">
</div>
<div class="control-group">
<label for="endDate">结束日期:</label>
<input type="datetime-local" id="endDate">
</div>
<div class="control-group">
<button id="queryBtn">查询数据</button>
<button id="resetBtn">重置筛选</button>
</div>
<div class="control-group">
<label>
<input type="checkbox" id="autoRefresh">
自动刷新 (10分钟周期)
</label>
</div>
</div>
<!-- 图表区域 -->
<div class="chart-container">
<h2>传感器数据图表</h2>
<canvas id="sensorChart"></canvas>
</div>
<!-- 数据表格 -->
<div class="table-container">
<h2>传感器数据表格</h2>
<button id="exportBtn">导出CSV</button>
<table id="dataTable">
<thead>
<tr>
<th>数据编号</th>
<th>探头地址</th>
<th>时间</th>
<th>X</th>
<th>Y</th>
<th>Z</th>
</tr>
</thead>
<tbody id="tableBody">
<!-- 数据将通过JavaScript动态添加 -->
</tbody>
</table>
</div>
</div>
<!-- 内联JavaScript -->
<script>
// 全局变量
let sensorChart = null;
let refreshInterval = null;
let allSensors = [];
let currentSensorData = [];
// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
// 初始化日期选择器为今天
initializeDatePickers();
// 加载所有传感器ID
loadSensors();
// 添加事件监听器
setupEventListeners();
// 设置自动刷新
setupAutoRefresh();
});
// 初始化日期选择器
function initializeDatePickers() {
// 获取当前时间(使用本地时间)
const now = new Date();
// 格式化日期和时间为HTML datetime-local输入格式 YYYY-MM-DDThh:mm
const year = now.getFullYear();
const month = (now.getMonth() + 1).toString().padStart(2, '0'); // 月份从0开始
const day = now.getDate().toString().padStart(2, '0');
const hours = now.getHours().toString().padStart(2, '0');
const minutes = now.getMinutes().toString().padStart(2, '0');
const today = `${year}-${month}-${day}`;
const currentTime = `${hours}:${minutes}`;
// 设置默认的开始时间为当天00:00
document.getElementById('startDate').value = `${today}T00:00`;
// 设置默认的结束时间为当前时间
document.getElementById('endDate').value = `${today}T${currentTime}`;
console.log("当前设置的开始时间:", document.getElementById('startDate').value);
console.log("当前设置的结束时间:", document.getElementById('endDate').value);
}
// 设置事件监听器
function setupEventListeners() {
// 查询按钮
document.getElementById('queryBtn').addEventListener('click', function() {
loadData();
});
// 重置按钮
document.getElementById('resetBtn').addEventListener('click', function() {
resetFilters();
});
// 传感器选择变化
document.getElementById('sensorSelect').addEventListener('change', function() {
loadData();
});
// 记录数限制变化
document.getElementById('limitSelect').addEventListener('change', function() {
loadData();
});
// 导出CSV按钮
document.getElementById('exportBtn').addEventListener('click', function() {
exportToCSV();
});
}
// 设置自动刷新
function setupAutoRefresh() {
const autoRefreshCheckbox = document.getElementById('autoRefresh');
// 初始化自动刷新
if (autoRefreshCheckbox.checked) {
startAutoRefresh();
}
// 监听复选框变化
autoRefreshCheckbox.addEventListener('change', function() {
if (this.checked) {
startAutoRefresh();
} else {
stopAutoRefresh();
}
});
}
// 开始自动刷新
function startAutoRefresh() {
if (refreshInterval) {
clearInterval(refreshInterval);
}
refreshInterval = setInterval(loadData, 1000 * 60 * 10);
}
// 停止自动刷新
function stopAutoRefresh() {
if (refreshInterval) {
clearInterval(refreshInterval);
refreshInterval = null;
}
}
// 重置筛选条件
function resetFilters() {
initializeDatePickers();
document.getElementById('sensorSelect').value = 'all';
document.getElementById('limitSelect').value = '100';
loadData();
}
// 加载所有传感器ID
function loadSensors() {
fetch('/api/sensors')
.then(response => {
if (!response.ok) {
throw new Error('获取传感器列表失败');
}
return response.json();
})
.then(data => {
allSensors = data;
updateSensorSelect(data);
// 加载数据
loadData();
})
.catch(error => {
console.error('加载传感器列表出错:', error);
alert('加载传感器列表出错: ' + error.message);
});
}
// 更新传感器选择下拉框
function updateSensorSelect(sensors) {
const select = document.getElementById('sensorSelect');
// 保留"所有传感器"选项
const allOption = select.querySelector('option[value="all"]');
select.innerHTML = '';
select.appendChild(allOption);
if (sensors.length === 0) {
const option = document.createElement('option');
option.value = '';
option.textContent = '没有可用的传感器';
select.appendChild(option);
return;
}
sensors.forEach(id => {
const option = document.createElement('option');
option.value = id;
option.textContent = `探头 ${id}`;
select.appendChild(option);
});
}
// 加载传感器数据
function loadData() {
const sensorID = document.getElementById('sensorSelect').value;
const limit = document.getElementById('limitSelect').value;
const startDate = document.getElementById('startDate').value;
const endDate = document.getElementById('endDate').value;
let url = '/api/data?';
let params = [];
// 添加查询参数
if (sensorID !== 'all') {
params.push(`sensor_id=${sensorID}`);
}
if (limit) {
params.push(`limit=${limit}`);
}
if (startDate) {
params.push(`start_date=${encodeURIComponent(startDate)}`);
}
if (endDate) {
params.push(`end_date=${encodeURIComponent(endDate)}`);
}
url += params.join('&');
// 显示加载状态
document.getElementById('queryBtn').textContent = '加载中...';
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error('获取传感器数据失败');
}
return response.json();
})
.then(data => {
currentSensorData = data;
updateTable(data);
updateChart(data);
document.getElementById('queryBtn').textContent = '查询数据';
})
.catch(error => {
console.error('加载数据出错:', error);
alert('加载数据出错: ' + error.message);
document.getElementById('queryBtn').textContent = '查询数据';
});
}
// 更新数据表格
function updateTable(data) {
const tableBody = document.getElementById('tableBody');
tableBody.innerHTML = '';
if (data.length === 0) {
const row = document.createElement('tr');
row.innerHTML = '<td colspan="6" style="text-align: center;">没有数据</td>';
tableBody.appendChild(row);
return;
}
data.forEach(item => {
const row = document.createElement('tr');
// 解析时间并调整为中国时间UTC+8
const date = new Date(item.timestamp);
// 减去8小时因为数据库时间似乎比实际时间早了8小时
date.setHours(date.getHours() - 8);
// 格式化为中文日期时间格式
const formattedDate =
date.getFullYear() + '/' +
(date.getMonth() + 1).toString().padStart(2, '0') + '/' +
date.getDate().toString().padStart(2, '0') + ' ' +
date.getHours().toString().padStart(2, '0') + ':' +
date.getMinutes().toString().padStart(2, '0') + ':' +
date.getSeconds().toString().padStart(2, '0');
row.innerHTML =
'<td>' + item.id + '</td>' +
'<td>' + item.sensor_id + '</td>' +
'<td>' + formattedDate + '</td>' +
'<td>' + item.x.toFixed(3) + '</td>' +
'<td>' + item.y.toFixed(3) + '</td>' +
'<td>' + item.z.toFixed(3) + '</td>' ;
tableBody.appendChild(row);
});
}
// 更新图表
function updateChart(data) {
// 准备图表数据
const chartData = prepareChartData(data);
// 如果图表已经存在,销毁它
if (sensorChart) {
sensorChart.destroy();
}
// 获取图表Canvas
const ctx = document.getElementById('sensorChart').getContext('2d');
// 创建新图表
sensorChart = new Chart(ctx, {
type: 'line',
data: chartData,
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
title: {
display: true,
text: '历史数据'
},
tooltip: {
callbacks: {
label: function(context) {
let label = context.dataset.label || '';
if (label) {
label += ': ';
}
if (context.parsed.y !== null) {
label += context.parsed.y.toFixed(3);
}
return label;
}
}
}
},
scales: {
x: {
title: {
display: true,
text: '时间'
}
},
y: {
title: {
display: true,
text: '值'
}
}
}
}
});
}
// 准备图表数据
function prepareChartData(data) {
// 如果没有数据,返回空数据集
if (data.length === 0) {
return {
labels: [],
datasets: []
};
}
// 反转数据以便按时间先后顺序显示
const sortedData = [...data].sort((a, b) => {
return new Date(a.timestamp) - new Date(b.timestamp);
});
// 获取所有传感器ID
let sensorIDs = [...new Set(sortedData.map(item => item.sensor_id))];
// 按传感器ID分组数据
let datasets = [];
let labels = [];
// 准备时间标签(使用第一个传感器的数据)
if (sensorIDs.length > 0) {
const firstSensorData = sortedData.filter(item => item.sensor_id === sensorIDs[0]);
labels = firstSensorData.map(item => {
const date = new Date(item.timestamp);
date.setHours(date.getHours() - 8); // 调整时区
return date.toLocaleString('zh-CN', {
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
});
});
}
// 定义颜色
const colors = [
'rgb(75, 192, 192)',
'rgb(255, 99, 132)',
'rgb(54, 162, 235)',
'rgb(255, 205, 86)',
'rgb(153, 102, 255)',
'rgb(255, 159, 64)'
];
// 为X, Y, Z创建不同的数据集
const dataTypes = [
{ key: 'x', label: 'X' },
{ key: 'y', label: 'Y' },
{ key: 'z', label: 'Z' }
];
sensorIDs.forEach((sensorID, sensorIndex) => {
const sensorData = sortedData.filter(item => item.sensor_id === sensorID);
dataTypes.forEach((type, typeIndex) => {
const colorIndex = (sensorIndex * dataTypes.length + typeIndex) % colors.length;
datasets.push({
label: `探头${sensorID} - ${type.label}`,
data: sensorData.map(item => item[type.key]),
fill: false,
borderColor: colors[colorIndex],
tension: 0.1
});
});
});
return {
labels: labels,
datasets: datasets
};
}
// 导出到CSV文件
function exportToCSV() {
if (currentSensorData.length === 0) {
alert('没有数据可导出');
return;
}
// 准备CSV内容
let csvContent = "数据编号,探头地址编号,X,Y,Z,时间\n";
currentSensorData.forEach(item => {
// 解析时间并调整为中国时间
const date = new Date(item.timestamp);
date.setHours(date.getHours() - 8);
// 格式化日期
const formattedDate =
date.getFullYear() + '/' +
(date.getMonth() + 1).toString().padStart(2, '0') + '/' +
date.getDate().toString().padStart(2, '0') + ' ' +
date.getHours().toString().padStart(2, '0') + ':' +
date.getMinutes().toString().padStart(2, '0') + ':' +
date.getSeconds().toString().padStart(2, '0');
// 添加一行数据
csvContent +=
item.id + "," +
item.sensor_id + "," +
item.x.toFixed(3) + "," +
item.y.toFixed(3) + "," +
item.z.toFixed(3) + "," +
formattedDate + "\n";
});
// 创建Blob对象
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
// 创建下载链接
const link = document.createElement("a");
const url = URL.createObjectURL(blob);
// 设置下载属性
link.setAttribute("href", url);
link.setAttribute("download", "sensor_data.csv");
// 添加到文档并点击
document.body.appendChild(link);
link.click();
// 清理
document.body.removeChild(link);
}
</script>
</body>
</html>