瀏覽代碼

告警通知-完成定时抓取并发送

sixian 2 年之前
父節點
當前提交
f524f82caa

+ 14 - 0
app/data/controller/calcTask.go

@@ -8,6 +8,8 @@ import (
 	"iot_manager_service/app/data/model"
 	"iot_manager_service/app/data/service"
 	device "iot_manager_service/app/device/service"
+	system "iot_manager_service/app/system/dao"
+	warnService "iot_manager_service/app/warn/service"
 	"iot_manager_service/util/cache"
 	"iot_manager_service/util/logger"
 	"net/http"
@@ -35,6 +37,18 @@ func CalcTask() {
 		service.EnvironmentDataService.DayDataSync()
 	})
 
+	//处理告警消息
+	_ = c.AddFunc("0 * */1 * * ?", func() {
+		//抓取数据
+		tenant := system.Tenant{}
+		tenants, _ := tenant.GetTenants(0, 1000)
+		for _, t := range tenants {
+			warnService.PlatformAlarmService.Refresh(int(t.ID))
+		}
+		//发送告警
+		warnService.TaskWarnService.HandlingAlarms()
+	})
+
 	c.Start()
 }
 

+ 1 - 1
app/warn/controller/platformAlarmController.go

@@ -102,7 +102,7 @@ func (c platformAlarmCrl) HandleAlert(ctx *gin.Context) {
 	armHandle, _ := strconv.Atoi(ctx.Query("armHandle"))
 	remark := ctx.Query("remark")
 
-	err := service.PlatformAlarmService.HannleAlart(claims.TenantId, id, armHandle, remark)
+	err := service.PlatformAlarmService.HandleAlarm(claims.TenantId, id, armHandle, remark)
 	if err != nil {
 		ctx.JSON(http.StatusBadRequest, err)
 		return

+ 6 - 1
app/warn/dao/noticeRecordDao.go

@@ -16,7 +16,7 @@ type NoticeRecord struct {
 	Status          int    `gorm:"comment:发送状态;" json:"status"`
 	SendType        int    `gorm:"comment:发送方式1短信2邮件" json:"sendType"`
 	SendTypeName    string `gorm:"comment:发送方式" json:"SendTypeName"`
-	SendValue       int    `gorm:"comment:手机号或邮件" json:"sendValue"`
+	SendValue       string `gorm:"comment:手机号或邮件" json:"sendValue"`
 	SendName        string `gorm:"comment:收件人" json:"sendName"`
 	PlatformAlarmId int
 	PlatformAlarm   PlatformAlarm
@@ -59,3 +59,8 @@ func (r NoticeRecord) GetList(filter model.RequestNoticeRecordFilter) ([]NoticeR
 	//fmt.Printf("total = %v", total)
 	return list, total, err
 }
+
+func (r NoticeRecord) Create() error {
+	err := Db.Debug().Create(&r).Error
+	return err
+}

+ 8 - 0
app/warn/dao/noticeSetDao.go

@@ -68,3 +68,11 @@ func (s *NoticeSet) Delete() error {
 	}).Delete(&s).Error
 	return err
 }
+
+// GetNoticeList 返回告警接收人全部信息
+func (s NoticeSet) GetNoticeList(deviceType int, sn string) ([]NoticeSet, error) {
+	var list []NoticeSet
+	err := Db.Debug().Where("device_sn=999999").Or("device_type=?", deviceType).Or("device_sn=?", sn).Find(&list).Error
+	//fmt.Printf("err = %v \n", err)
+	return list, err
+}

+ 6 - 0
app/warn/dao/platformAlarmDao.go

@@ -104,3 +104,9 @@ func (a PlatformAlarm) GetWarnCount() (int64, error) {
 	}).Where("arm_time>?", getTime).Count(&count).Error
 	return count, err
 }
+
+func (a PlatformAlarm) GetsAlarmByTime(start string) ([]PlatformAlarm, error) {
+	var list []PlatformAlarm
+	err := Db.Debug().Model(&a).Where("status=0 and arm_time>?", start).Find(&list).Order("id desc").Error
+	return list, err
+}

+ 8 - 1
app/warn/model/noticeRecordModel.go

@@ -14,7 +14,7 @@ type ResposeNoticeRecordData struct {
 	SendUser       string `json:"sendUser"`
 	SendTime       string `json:"sendTime"`
 	SendType       int    `json:"sendType"`
-	SendValue      int    `json:"sendValue"`
+	SendValue      string `json:"sendValue"`
 	CreateTime     string `json:"createTime"`
 	TenantID       string `json:"tenantId"`
 	ArmContend     string `json:"armContend"`
@@ -34,3 +34,10 @@ type RequestNoticeRecordFilter struct {
 	Current int `form:"current"` //当前分页
 	Size    int `form:"size"`    //每页数量
 }
+
+type ReceiveList struct {
+	NoticeSetId          int
+	UserName             string //接收用户名
+	NoticeMode           int    //通知方式 1短信 2邮件
+	NoticeReceiveAccount string //接收报警账号
+}

+ 45 - 9
app/warn/service/noticeSetService.go

@@ -2,6 +2,7 @@ package service
 
 import (
 	"fmt"
+	systemDao "iot_manager_service/app/system/dao"
 	systemService "iot_manager_service/app/system/service"
 	"iot_manager_service/app/warn/dao"
 	"iot_manager_service/app/warn/model"
@@ -98,9 +99,8 @@ func (s noticeSetService) Update(post model.NoticeUpdateData, tenantId int) erro
 		BusinessNoticeModesName: post.ShowBusinessTypeName,
 		DevUserIds:              post.NoticeOperationMan,
 		BusinessUserIds:         post.NoticeBusinessMan,
-
-		DevUserIdsName:      s.getUserName(post.NoticeOperationMan),
-		BusinessUserIdsName: s.getUserName(post.NoticeBusinessMan),
+		DevUserIdsName:          s.getUserName(post.NoticeOperationMan),
+		BusinessUserIdsName:     s.getUserName(post.NoticeBusinessMan),
 	}
 	return set.UpdateOrSave()
 }
@@ -154,18 +154,54 @@ func (s noticeSetService) getUserName(ids string) string {
 		fm[v] = i
 	}
 	userList, _ := systemService.UserService.List("", "", 0, 1000)
-	new := []string{}
+	var nameList []string
 	for _, detail := range userList {
 		id := strconv.Itoa(int(detail.ID))
 		if _, ok := fm[id]; ok {
-			new = append(new, detail.Name)
+			nameList = append(nameList, detail.Name)
 		}
 	}
-	return strings.Join(new, ",")
+	return strings.Join(nameList, ",")
 }
 
-func (s noticeSetService) Remove(id string, tenant_id int) error {
-	fmt.Printf("id = %v", id)
-	noticeSet := dao.NoticeSet{DeviceSn: id, TenantId: strconv.Itoa(tenant_id)}
+func (s noticeSetService) Remove(id string, tenantId int) error {
+	noticeSet := dao.NoticeSet{DeviceSn: id, TenantId: strconv.Itoa(tenantId)}
 	return noticeSet.Delete()
 }
+
+// GetReceiveList 查出接收人
+func (s noticeSetService) GetReceiveList(deviceType int, sn string, armSource int) (map[string]model.ReceiveList, error) {
+	list, _ := dao.NoticeSet{}.GetNoticeList(deviceType, sn)
+	receives := make(map[string]model.ReceiveList)
+	for _, set := range list {
+		userIds := set.BusinessUserIds         //接收用户
+		noticeModes := set.BusinessNoticeModes //接收的通知方式
+		if armSource == 1 {
+			userIds = set.DevUserIds
+			noticeModes = set.DevUserNoticeModes
+		}
+		usersArr := strings.Split(userIds, ",")
+		noticeModesArr := strings.Split(noticeModes, ",")
+
+		for _, userId := range usersArr {
+			var user systemDao.User
+			parseInt, _ := strconv.ParseInt(userId, 10, 64)
+			user.ID = parseInt
+			user.GetUser()
+			for _, noticeModeStr := range noticeModesArr {
+				noticeModeNum, _ := strconv.ParseInt(noticeModeStr, 10, 64)
+				account := user.Email
+				if noticeModeStr == "1" {
+					account = user.Phone
+				}
+				receives[userId+noticeModeStr] = model.ReceiveList{
+					NoticeSetId:          int(set.ID),
+					UserName:             user.Name,
+					NoticeMode:           int(noticeModeNum),
+					NoticeReceiveAccount: account,
+				}
+			}
+		}
+	}
+	return receives, nil
+}

+ 10 - 6
app/warn/service/platformAlarmService.go

@@ -13,6 +13,7 @@ var PlatformAlarmService = new(platformAlarmService)
 
 type platformAlarmService struct{}
 
+// GetList 报警列表
 func (s platformAlarmService) GetList(tenantId int, filter model.RequestPlatFormAlartFilter) ([]model.PlatFormAlartData, int64, error) {
 	var list []model.PlatFormAlartData
 	dao := dao.PlatformAlarm{
@@ -44,10 +45,10 @@ func (s platformAlarmService) GetList(tenantId int, filter model.RequestPlatForm
 	return list, i, err
 }
 
+// Refresh 同步边缘接口报警数据
 func (s platformAlarmService) Refresh(tenantId int) error {
 	viewDao := dao.ViewsAllCode{TenantId: tenantId}
 	alls, err := viewDao.GetAlls()
-
 	if err != nil {
 		return err
 	}
@@ -57,12 +58,8 @@ func (s platformAlarmService) Refresh(tenantId int) error {
 			newAllCode[viewsAllCode.Sn] = viewsAllCode
 		}
 	}
-	//fmt.Printf("newAllCode = %v", newAllCode)
 	edgeService := edgeService.RecordAlarmRecord{}
 	maxId, maxUpDateTime := dao.PlatformAlarm{}.GetMaxIdAndUpDateTime()
-	//fmt.Printf("maxId = %v\n", maxId)
-	//fmt.Printf("maxUpDateTime = %v\n", maxUpDateTime)
-
 	list, err := edgeService.SyncAlartRecord(maxId, maxUpDateTime)
 	if err != nil {
 		return err
@@ -106,7 +103,8 @@ func (s platformAlarmService) Refresh(tenantId int) error {
 
 }
 
-func (s platformAlarmService) HannleAlart(tenant_id int, id int, armHandle int, remark string) error {
+// HandleAlarm 告警处理
+func (s platformAlarmService) HandleAlarm(tenant_id int, id int, armHandle int, remark string) error {
 	dao := dao.PlatformAlarm{
 		ID:             id,
 		ArmHandle:      armHandle,
@@ -121,3 +119,9 @@ func (s platformAlarmService) GetWarnCount(tenantId int, deviceType int) (int64,
 	alarm := dao.PlatformAlarm{TenantId: strconv.Itoa(tenantId), ArmDeviceType: deviceType}
 	return alarm.GetWarnCount()
 }
+
+// GetNotNotifyAlarm 返回最近几天没有发送告警通知的警告
+func (s platformAlarmService) GetNotNotifyAlarm(day int) ([]dao.PlatformAlarm, error) {
+	start := time.Now().AddDate(0, 0, -day).Format("2006-01-02- 15:04:05")
+	return dao.PlatformAlarm{}.GetsAlarmByTime(start)
+}

+ 57 - 4
app/warn/service/taskWarnService.go

@@ -1,17 +1,70 @@
 package service
 
+import (
+	"errors"
+	"fmt"
+	"iot_manager_service/app/warn/dao"
+	"iot_manager_service/config"
+	"iot_manager_service/util/notify"
+)
+
+var TaskWarnService = new(taskWarnService)
+
 // 定时任务处理的service
-type TaskWarnService struct {
+type taskWarnService struct {
 }
 
 // HandlingAlarms 报警处理
-func (receiver TaskWarnService) HandlingAlarms() {
+func (receiver taskWarnService) HandlingAlarms() {
 	/*
-		TODO: 未处理
 		1. 查出平台 platformAlarmService.go 最近3天的 status = 0 未处理的 报警记录
 		2. 根据报警 sn 查出设置的报警人相关信息,可能是多个报警方式
 		3. 执行发短信或邮件逻辑,发送内容
 		4. 保存相关日志到 noticeRecordService.go 下
 	*/
-
+	alarm, _ := PlatformAlarmService.GetNotNotifyAlarm(3)
+	for _, platformAlarm := range alarm {
+		sn := platformAlarm.ArmDeviceSn
+		deviceType := platformAlarm.ArmDeviceType
+		armSource := 1
+		receiveList, _ := NoticeSetService.GetReceiveList(deviceType, sn, armSource)
+		armSourceName := "运维"
+		if armSource == 2 {
+			armSourceName = "业务"
+		}
+		for _, receive := range receiveList {
+			//告警内容拼装
+			sendMsgFormat := "%v,您好:%v的%v于%v检测到%v,请确认并执行维护。"
+			name := "【" + platformAlarm.LampPoleName + "】" + platformAlarm.ArmDeviceName
+			sendMsg := fmt.Sprintf(sendMsgFormat, receive.UserName, platformAlarm.LampPoleLocation, name, platformAlarm.ArmTime, platformAlarm.ArmContent)
+			sendErr := errors.New("")
+			//去发送消息
+			SendTypeName := "邮件"
+			switch receive.NoticeMode {
+			case 1:
+				SendTypeName = "短信"
+				sendErr = notify.SendTencentSms([]string{"+86" + receive.NoticeReceiveAccount}, config.Instance().MonitNotice.Sms.Tencent.WarnSmsTemplateID, []string{platformAlarm.LampPoleName, platformAlarm.LampPoleSn, platformAlarm.ArmContent})
+			case 2:
+				sendErr = notify.SendEmail(sendMsg, armSourceName+"通知", receive.NoticeReceiveAccount)
+			}
+			sendStatus := 1
+			if sendErr != nil {
+				sendStatus = 0
+			}
+			//保存消息记录
+			dao.NoticeRecord{
+				NoticeSetId:     receive.NoticeSetId,
+				ArmClassify:     armSource,
+				Content:         sendMsg,
+				Status:          sendStatus,
+				SendType:        receive.NoticeMode,
+				SendTypeName:    SendTypeName,
+				SendValue:       receive.NoticeReceiveAccount,
+				SendName:        receive.UserName,
+				PlatformAlarmId: platformAlarm.ID,
+			}.Create()
+			//标记已发送
+			dao.PlatformAlarm{ID: platformAlarm.ID, Status: 1}.Update()
+		}
+	}
 }

+ 1 - 0
go.mod

@@ -54,6 +54,7 @@ require (
 	github.com/onsi/gomega v1.20.0 // indirect
 	github.com/pelletier/go-toml/v2 v2.0.1 // indirect
 	github.com/pkg/errors v0.9.1 // indirect
+	github.com/robfig/cron/v3 v3.0.0 // indirect
 	github.com/rs/xid v1.4.0 // indirect
 	github.com/tebeka/strftime v0.1.5 // indirect
 	github.com/ugorji/go/codec v1.2.7 // indirect