FatAgent/internal/report.go
mei bf18a04040 feat(internal): 添加空调状态上报功能
- 新增 Report 函数,实现空调状态的定期上报
- 添加 airConditionerBodyMessage 结构体用于构造上报数据
- 使用 http.Client 发送 POST 请求到上报 URL
- 在 main.go 中调用 Report 函数,替换原有的空实现
2025-08-20 10:07:10 +08:00

87 lines
1.7 KiB
Go
Raw Permalink 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 internal
import (
"bytes"
"encoding/json"
"io"
"log"
"net/http"
"time"
"git.mmeiblog.cn/mei/FatAgent/configs"
"git.mmeiblog.cn/mei/FatAgent/pkg"
)
const (
reportPath = "/receive/airConditioner"
httpTimeout = 30 * time.Second
)
type airConditionerBodyMessage struct {
AgentID int `json:"agentID"`
Timestamp int64 `json:"timestamp"`
Message pkg.ACStatus `json:"message"`
}
var httpClient = &http.Client{
Timeout: httpTimeout,
}
func Report() {
now := time.Now().Unix()
ac, err := pkg.NewACController(configs.AC_PORT)
if err != nil {
log.Printf("错误:创建控制器失败: %v", err)
return
}
ACStatus, err := ac.GetAllStatus()
if err != nil {
log.Printf("错误:查询状态失败: %v", err)
return
}
payload := airConditionerBodyMessage{
AgentID: configs.AGENT_ID,
Timestamp: now,
Message: *ACStatus,
}
bodyBytes, err := json.Marshal(payload)
if err != nil {
log.Printf("错误JSON序列化失败: %v", err)
return
}
url := configs.REPORT_URL + reportPath
req, err := http.NewRequest("POST", url, bytes.NewReader(bodyBytes))
if err != nil {
log.Printf("错误创建HTTP请求失败: %v", err)
return
}
req.Header.Add("x-api-key", configs.X_API_KEY)
req.Header.Add("Content-Type", "application/json")
res, err := httpClient.Do(req)
if err != nil {
log.Printf("错误发送HTTP请求失败: %v", err)
return
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
log.Printf("警告HTTP响应状态码非200状态码: %d", res.StatusCode)
return
}
body, err := io.ReadAll(res.Body)
if err != nil {
log.Printf("错误读取HTTP响应失败: %v", err)
return
}
log.Printf("上报成功,响应内容:%s", body)
}