fix: 调整一些bug
This commit is contained in:
parent
0ba3f638f4
commit
ceb83afff2
@ -19,6 +19,7 @@ func StartHTTPServer(address string) error {
|
||||
http.HandleFunc("/api/data", handleGetData)
|
||||
http.HandleFunc("/api/sensors", handleGetSensors)
|
||||
http.HandleFunc("/api/clients", handleGetClients)
|
||||
http.HandleFunc("/api/trigger-query", handleTriggerQuery)
|
||||
fmt.Printf("HTTP服务器已启动,正在监听 %s\n", address)
|
||||
return http.ListenAndServe(address, nil)
|
||||
}
|
||||
@ -156,6 +157,7 @@ func handleGetSensors(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "编码JSON失败:"+err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
func handleGetClients(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
@ -166,3 +168,27 @@ func handleGetClients(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "编码JSON失败:"+err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
// 处理手动触发查询指令的API
|
||||
func handleTriggerQuery(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
if r.Method != "POST" {
|
||||
http.Error(w, "只支持POST请求", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
// 触发向所有在线客户端发送查询指令
|
||||
sent := triggerManualQuery()
|
||||
|
||||
response := map[string]interface{}{
|
||||
"success": true,
|
||||
"message": fmt.Sprintf("已向%d个客户端发送查询指令", sent),
|
||||
"sent_count": sent,
|
||||
}
|
||||
|
||||
if err := json.NewEncoder(w).Encode(response); err != nil {
|
||||
log.Printf("错误: 编码响应JSON失败: %v", err)
|
||||
http.Error(w, "编码JSON失败:"+err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
@ -22,6 +22,7 @@ type ClientInfo struct {
|
||||
var (
|
||||
clientsMutex sync.Mutex
|
||||
clients = make(map[string]*ClientInfo)
|
||||
clientConns = make(map[string]net.Conn) // 存储客户端连接
|
||||
)
|
||||
|
||||
// StartTCPServer 启动TCP服务器
|
||||
@ -55,6 +56,11 @@ func handleConnection(conn net.Conn) {
|
||||
|
||||
addClient(remoteAddr)
|
||||
|
||||
// 存储连接以便手动查询使用
|
||||
clientsMutex.Lock()
|
||||
clientConns[remoteAddr] = conn
|
||||
clientsMutex.Unlock()
|
||||
|
||||
// 启动定时发送指令的goroutine
|
||||
go sendPeriodicCommand(conn, remoteAddr)
|
||||
|
||||
@ -69,6 +75,10 @@ func handleConnection(conn net.Conn) {
|
||||
Logger.Printf("客户端断开连接 %s", remoteAddr)
|
||||
}
|
||||
removeClient(remoteAddr)
|
||||
// 清理连接映射
|
||||
clientsMutex.Lock()
|
||||
delete(clientConns, remoteAddr)
|
||||
clientsMutex.Unlock()
|
||||
break
|
||||
}
|
||||
|
||||
@ -92,6 +102,10 @@ func handleConnection(conn net.Conn) {
|
||||
if _, err := conn.Write([]byte(resp)); err != nil {
|
||||
Logger.Printf("发送响应到客户端 %s 失败: %v", remoteAddr, err)
|
||||
removeClient(remoteAddr)
|
||||
// 清理连接映射
|
||||
clientsMutex.Lock()
|
||||
delete(clientConns, remoteAddr)
|
||||
clientsMutex.Unlock()
|
||||
break
|
||||
}
|
||||
|
||||
@ -282,6 +296,7 @@ func startClientCleanup() {
|
||||
for addr, client := range clients {
|
||||
if now.Sub(client.LastSeen) > 24*time.Hour {
|
||||
delete(clients, addr)
|
||||
delete(clientConns, addr) // 同时清理连接
|
||||
Logger.Printf("移除过期客户端: %s", addr)
|
||||
}
|
||||
}
|
||||
@ -290,3 +305,31 @@ func startClientCleanup() {
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// triggerManualQuery 手动触发向所有在线客户端发送查询指令
|
||||
func triggerManualQuery() int {
|
||||
clientsMutex.Lock()
|
||||
defer clientsMutex.Unlock()
|
||||
|
||||
sentCount := 0
|
||||
command := "@1602301014A*0!\n"
|
||||
|
||||
for addr, client := range clients {
|
||||
// 检查客户端是否在线(最近10分钟内活跃)
|
||||
if time.Since(client.LastSeen) < 10*time.Minute {
|
||||
if conn, exists := clientConns[addr]; exists {
|
||||
if _, err := conn.Write([]byte(command)); err != nil {
|
||||
Logger.Printf("手动发送查询指令到客户端 %s 失败: %v", addr, err)
|
||||
// 连接可能已断开,从映射中移除
|
||||
delete(clientConns, addr)
|
||||
} else {
|
||||
TCPDataLogger.Printf("手动发送查询指令到客户端 %s: %s", addr, strings.TrimSpace(command))
|
||||
sentCount++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Logger.Printf("手动查询指令已发送到 %d 个客户端", sentCount)
|
||||
return sentCount
|
||||
}
|
||||
|
||||
@ -275,6 +275,9 @@
|
||||
// 检查连接状态
|
||||
checkConnectionStatus();
|
||||
connectionCheckTimer = setInterval(checkConnectionStatus, 30000); // 每30秒检查一次
|
||||
|
||||
// 显示数据库中的最新数据(不发送TCP查询指令)
|
||||
fetchLatestData();
|
||||
});
|
||||
|
||||
// 初始化日期选择器
|
||||
@ -784,13 +787,35 @@
|
||||
// 先获取一次当前最新数据
|
||||
fetchLatestData();
|
||||
|
||||
// 触发TCP服务器发送查询指令,等待3秒后再次获取最新数据
|
||||
// 发送TCP查询指令
|
||||
fetch('/api/trigger-query', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
console.log(`查询指令已发送到 ${data.sent_count} 个设备`);
|
||||
// 等待3秒后获取最新数据(给设备响应时间)
|
||||
setTimeout(() => {
|
||||
fetchLatestData();
|
||||
loadData(); // 也刷新一下表格数据
|
||||
latestDataElement.style.opacity = 1;
|
||||
document.getElementById('queryLatestBtn').textContent = '查询最新数据';
|
||||
}, 3000);
|
||||
} else {
|
||||
console.error('发送查询指令失败:', data.message);
|
||||
latestDataElement.style.opacity = 1;
|
||||
document.getElementById('queryLatestBtn').textContent = '查询最新数据';
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('发送查询指令出错:', error);
|
||||
latestDataElement.style.opacity = 1;
|
||||
document.getElementById('queryLatestBtn').textContent = '查询最新数据';
|
||||
});
|
||||
}
|
||||
|
||||
// 页面卸载时清除定时器
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user