eventRT/handler/alarm_upload.go

157 lines
3.1 KiB
Go
Raw Permalink Normal View History

2026-06-25 14:45:57 +08:00
// Package handler define HTTP handler functions for eventRT service
package handler
import (
"errors"
"eventRT/constants"
"eventRT/event"
"eventRT/logger"
"net/http"
"regexp"
"github.com/gin-gonic/gin"
"github.com/gofrs/uuid"
)
func PostAlarmHandler(c *gin.Context) {
ctx := c.Request.Context()
record, err := checkAndGenPostAlarmParam(c)
if err != nil {
logger.Error(ctx, "check and gen param failed", "error", err)
c.JSON(http.StatusBadRequest, gin.H{
"code": 1,
"msg": "check and gen param failed",
})
return
}
if err := event.PersistAndPublishEvent(ctx, record); err != nil {
logger.Error(ctx, "persist and publish event failed", "error", err)
c.JSON(http.StatusInternalServerError, gin.H{
"code": 2,
"msg": "persist and publish event failed",
})
return
}
c.JSON(http.StatusOK, gin.H{
"code": 0,
"msg": "success",
})
}
func checkAndGenPostAlarmParam(c *gin.Context) (*event.EventRecord, error) {
a := new(alarm)
if err := c.ShouldBindJSON(a); err != nil {
return nil, err
}
ok, err := regexp.MatchString(`ssu\d{3}`, a.DeviceNo)
if err != nil {
return nil, err
}
if !ok {
return nil, errors.New("invalid device_no")
}
if a.AlarmCode < 1 || a.AlarmCode > 10 {
return nil, errors.New("invalid alarm_code")
}
if a.AlarmStatus < 0 || a.AlarmStatus > 1 {
return nil, errors.New("invalid alarm_status")
}
event, err := a.ConvertToEvent(c.RemoteIP()) // TODO
if err != nil {
return nil, err
}
return event, nil
}
var almCode2Name = []string{
0: "", // 占位
1: "通信异常",
2: "AD故障",
3: "同步秒脉冲异常",
4: "备用",
5: "单元初始化",
6: "读参数错",
7: "备用",
8: "启动采样-内部转换信号",
9: "秒内采样点数过量",
10: "秒内采样点数欠量",
}
type alarm struct {
DriverName string `bson:"driver_name" json:"driver_name"`
DeviceNo string `bson:"device_no" json:"device_no"`
AlarmCode int `bson:"alarm_code" json:"alarm_code"`
AlarmTime int64 `bson:"alarm_time" json:"alarm_time"`
AlarmStatus int `bson:"alarm_status" json:"alarm_status"`
}
func (a *alarm) ConvertToEvent(op string) (*event.EventRecord, error) {
e := new(event.EventRecord)
uid, err := uuid.NewV4()
if err != nil {
return nil, err
}
if a != nil {
e.EventName = almCode2Name[a.AlarmCode]
e.EventUUID = uid.String()
e.Type = a.GetType()
e.Priority = a.GetPriority()
e.Status = constants.EventStatusHappened
e.Timestamp = a.AlarmTime
e.From = "station"
e.Operations = append(e.Operations, event.OperationRecord{
Action: "happen",
Op: op,
TS: a.AlarmTime,
})
e.Origin = map[string]any{
"driver_name": a.DriverName,
"device_no": a.DeviceNo,
"alarm_code": a.AlarmCode,
"alarm_time": a.AlarmTime,
"alarm_status": a.AlarmStatus,
}
}
return e, nil
}
func (a *alarm) GetType() int {
switch a.AlarmCode {
case 4, 5, 7, 8:
return 0
case 9, 10:
return 3
case 1, 2, 3, 6:
return 6
}
return -1
}
func (a *alarm) GetPriority() int {
switch a.AlarmCode {
case 4, 5, 7, 8:
return 1
case 9, 10:
return 4
case 1, 2, 3, 6:
return 7
}
return -1
}