123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597 |
- package service
- import (
- "encoding/json"
- "fmt"
- "rtzh_elec_temperature/datachannel"
- "rtzh_elec_temperature/global"
- "rtzh_elec_temperature/logger"
- "rtzh_elec_temperature/models/bo"
- "rtzh_elec_temperature/mqtt"
- "rtzh_elec_temperature/rtelec_app_public_lib/utils"
- "rtzh_elec_temperature/tools"
- "strconv"
- "strings"
- "sync"
- "time"
- "github.com/astaxie/beego/orm"
- "git.rtzhtech.cn/iss/public-lib/model"
- "git.rtzhtech.cn/iss/public-lib/logic"
- "github.com/spf13/cast"
- )
- type LinkEventService struct {
- BaseService
- }
- type LinkInfo struct {
- Deviceid int `json:"deviceid"`
- Modelid int `json:"modelid"`
- Strategyid int64 `json:"strategyid"`
- Strategyname string `json:"strategyname"`
- Srcappid int `json:"srcappid"`
- Dstappid int `json:"dstappid"` //联动目标Appid
- Linkfromid int64 `json:"linkfromid"`
- Linktoid int64 `json:"linktoid"`
- Fromdeviceid int `json:"fromdeviceid"`
- Actid int64 `json:"actid"`
- Fromattrname string `json:"fromattrname"`
- Linktype int `json:"linktype"`
- TargValue float64 `json:"targ_value"`
- Than int `json:"than"`
- Relation int `json:"relation"`
- Delay int `json:"delay"`
- Targetattrname string `json:"targetattrname"`
- //目标动作点的指令值
- Actvalue float64 `json:"actvalue"`
- //目标动作点的指令描述
- Actdesc string `json:"actdesc"`
- }
- //map[int][]LinkInfo
- var LinkData = sync.Map{} // make(map[int][]LinkInfo)
- //联动描述
- var LinkDescription = make(map[int64]string)
- //联动消息结构
- type LinkeBody struct {
- Srcappid int32
- Destappid int32
- Eventid int64
- Eventdesc string
- Linktype int
- Strategyid int64 `json:"strategyid"`
- Linktoid int64
- Actid int64
- Beforestatus string
- Afterstatus string
- Result string
- Reply int // 1- 动作执行成功 0-动作执行失败
- MessageId string
- }
- //发送消息
- type LinkRequest struct {
- Deviceid int `json:"deviceid"`
- Strategyid int64 `json:"strategyid"`
- Srcappid int `json:"srcappid"`
- Dstappid int `json:"dstappid"`
- Strategyname string `json:"strategyname"`
- Linktype int `json:"linktype"`
- Linkfromid int64 `json:"linkfromid"`
- Actid int64 `json:"actid"`
- }
- //初始化
- func init() {
- logger.Logger.Println("rtelec联动事件服务初始化")
- //等待应用注册结果
- go func() {
- for {
- data, ok := <-datachannel.Service_LinkEventReply_Chanl
- if ok {
- utils.MessageIds.Remove(tools.IsEmpty(data["mid"]))
- if destappid, ok := data["destappid"]; ok {
- insObj := RtelecManageApp()
- //只处理目标应用为当前应用的事件回复
- if destappid == insObj.RegAppID {
- logger.Logger.Debug(fmt.Sprintf("=======接收到联动事件回复结果:%+v", data))
- }
- }
- }
- }
- }()
- //等待联动策略更新通知
- go func() {
- _, ok := <-datachannel.Service_LinkInfoNotice_Chanl
- if ok {
- //重新加载联动策略
- isLoadLinkInfo = false
- new(LinkEventService).GetLinkInfo(0)
- }
- }()
- }
- //告警数据列表列表
- func (t *LinkEventService) LinkDataList(startDate, endDate int, source_address, targ_address, device_name string, pageIndex, pageSize int) (map[string]interface{}, error) {
- AppId := cast.ToInt(RtelecManageApp().RegAppID)
- l := logic.NewAlarmStrategyLogic()
- type linkData struct {
- id int `json:"id"`
- Eventid int64 `json:"eventid,string"`
- Eventdesc string `json:"eventdesc"`
- Date string `json:"date"`
- Beforestatus string `json:"beforestatus"`
- Afterstatus string `json:"afterstatus"`
- Result string `json:"result"`
- Create_at string `json:"create_at"`
- SourceAddress string `json:"source_address"`
- TargeAddress string `json:"targe_address"`
- Cpname string `json:"cpname"`
- Strategyname string `json:"strategyname"`
- Devicename string `json:"devicename"`
- Linktype string `json:"linktype"`
- }
- sqlCommandText := `select a.id,eventid,b.strategyname,eventdesc,from_unixtime(timestamp) date,beforestatus,afterstatus,result,a.create_at,concat(c.zonename,'/',c.positionname) source_address,concat(d.zonename,'/',d.positionname) targe_address,cpname,d.devicename,linktype from link_event a inner join (select a.strategyid,a.strategyname,linkfromid,linktoid,actid,case linktype when 1 then '测点联动' when 2 then '模拟IO量输入事件联动' when 3 then '数字量IO量输入联动' when 4 then '模拟IO量输出事件联动' when 5 then '数字量IO量输出联动' when 6 then '辅控事件联动' else null end linktype from
- link_strategy a inner join link_relation_obj b on a.strategyid=b.strategyid
- inner join link_relation_action c on a.strategyid=c.strategyid) b on a.strategyid=b.strategyid
- left join (select mpid,zonename,positionname from dev_mpinfo union select mpid,zonename,positionname from video_mpinfo) c on b.linkfromid=c.mpid
- left join (select p1.cpid,p1.cpname,p1.zonename,p1.positionname,p1.deviceid,p2.devicename from dev_cpinfo p1,dev_devinfo p2 where p1.deviceid=p2.deviceid union select p1.mpid cpid,p1.mpname cpname,p1.zonename,p1.positionname,p1.deviceid,p2.device_name devicename from video_mpinfo p1,video_devinfo p2 where p1.deviceid=p2.device_id )d on b.linktoid=d.cpid`
- totalSql := "select count(1) recordcount from link_event a inner join (select a.strategyid,a.strategyname,linkfromid,linktoid,actid from link_strategy a inner join link_relation_obj b on a.strategyid=b.strategyid inner join link_relation_action c on a.strategyid=c.strategyid) b on a.strategyid=b.strategyid " +
- " left join dev_mpinfo c on b.linkfromid=mpid left join dev_cpinfo d on b.linktoid=d.cpid left join dev_devinfo e on d.deviceid=e.deviceid"
- var sqlCondition []string
- if source_address != "" {
- sqlCondition = append(sqlCondition, fmt.Sprintf("concat(c.zonename,'/',c.positionname) like '%%%s%%'", source_address))
- }
- if targ_address != "" {
- sqlCondition = append(sqlCondition, fmt.Sprintf("concat(d.zonename,'/',d.positionname) like '%%%s%%'", targ_address))
- }
- if device_name != "" {
- sqlCondition = append(sqlCondition, fmt.Sprintf("e.devicename like '%%%s%%'", device_name))
- }
- if startDate > 0 && endDate > 0 {
- sqlCondition = append(sqlCondition, fmt.Sprintf("a.timestamp between %d and %d", startDate, endDate))
- } else if startDate > 0 {
- sqlCondition = append(sqlCondition, fmt.Sprintf("a.timestamp>=%d", startDate))
- } else if endDate > 0 {
- sqlCondition = append(sqlCondition, fmt.Sprintf("a.timestamp<=%d", endDate))
- }
- sqlCondition = append(sqlCondition, fmt.Sprintf("(a.dstappid=%d or a.srcappid=%d)", AppId, AppId))
- if len(sqlCondition) > 0 {
- sqlCommandText += " where " + strings.Join(sqlCondition, " and ")
- totalSql += " where " + strings.Join(sqlCondition, " and ")
- }
- sqlCommandText += fmt.Sprintf(" order by a.id desc limit %d,%d", (pageIndex-1)*pageSize, pageSize)
- var list []linkData
- err := l.SvcCtx.AlarmStrategy.Base.Raw(sqlCommandText, &list)
- var total Alarm_Total
- if err == nil {
- l.SvcCtx.AlarmStrategy.Base.Raw(totalSql, &total)
- }
- if len(list) == 0 {
- return map[string]interface{}{"list": []interface{}{}, "total": total.Recordcount}, err
- } else {
- return map[string]interface{}{"list": list, "total": total.Recordcount}, err
- }
- }
- //处理收到的联动消息
- func (t *LinkEventService) LinkMessage(data map[string]interface{}) {
- var parameter LinkeBody
- //解析消息
- if len(data) > 0 {
- if v, ok := data["srcappid"]; ok {
- parameter.Srcappid = cast.ToInt32(v)
- }
- if v, ok := data["destappid"]; ok {
- parameter.Destappid = cast.ToInt32(v)
- }
- if v, ok := data["eventid"]; ok {
- parameter.Eventid, _ = strconv.ParseInt(string(v.(json.Number)), 10, 64)
- }
- if v, ok := data["strategyid"]; ok {
- parameter.Strategyid, _ = strconv.ParseInt(string(v.(json.Number)), 10, 64)
- }
- if v, ok := data["linktoid"]; ok {
- parameter.Linktoid, _ = strconv.ParseInt(string(v.(json.Number)), 10, 64)
- }
- if v, ok := data["linktype"]; ok {
- parameter.Linktype = cast.ToInt(v)
- }
- if v, ok := data["eventdesc"]; ok {
- parameter.Eventdesc = cast.ToString(v)
- }
- if v, ok := data["actid"]; ok {
- parameter.Actid, _ = strconv.ParseInt(string(v.(json.Number)), 10, 64)
- }
- if messageId, ok := data["mid"]; ok {
- parameter.MessageId = cast.ToString(messageId)
- }
- } else {
- logger.Logger.Println("接收的联动消息为空!")
- return
- }
- if int(parameter.Destappid) == cast.ToInt(RtelecManageApp().RegAppID) {
- t.HandleLinkEventByMessage(parameter)
- }
- }
- //处理联动消息事件
- func (t *LinkEventService) HandleLinkEventByMessage(parameter LinkeBody) {
- appid := cast.ToInt64(RtelecManageApp().RegAppID)
- commandInfo, err := t.GetLinkByStrategyId(parameter.Strategyid, parameter.Linktoid, parameter.Actid)
- if err == nil {
- if len(commandInfo) > 0 {
- for _, info := range commandInfo {
- var commandField CommandMgr
- commandField.DeviceId = info.Deviceid
- commandField.AttrName = info.Targetattrname
- commandField.State = int(info.Actvalue)
- commandField.Actid = info.Actid
- var state = t.getBeforestatus(info.Deviceid, info.Targetattrname)
- //发送指令
- var messageId = tools.GetUid()
- msgObj := new(utils.MsgStateManage)
- msgObj.SetMessageStateObj(messageId, utils.MsgState{Success: false, State: false, Message: ""})
- Result := utils.MsgState{}
- raddelay, _ := bo.GetSysParamValue("readdelay", "5")
- commandObj := new(CommandService)
- for i := 0; i < 5; i++ {
- commandObj.Command(commandField, messageId, 1)
- Result = msgObj.HanderMesage(messageId, cast.ToInt(raddelay))
- if Result.Success {
- break
- }
- }
- eventObject := logic.NewLinkEventLogic()
- var field model.LinkEvent
- field.Eventid = new(utils.ToolsLogic).GetOnlyId(appid)
- stateText := info.Actdesc
- //判断成功状态
- if Result.Success {
- ExecuteState, _ := commandObj.CheckState(commandField)
- if ExecuteState {
- parameter.Reply = 1
- field.Result = fmt.Sprintf("%s成功", stateText)
- } else {
- parameter.Reply = 0
- field.Result = fmt.Sprintf("%s失败", stateText)
- }
- } else {
- parameter.Reply = 0
- field.Result = Result.Message
- }
- var desc = t.LinkDesc(info.Linktoid) + fmt.Sprintf("将设备控制状态更改为:%s,执行结果:%s", stateText, field.Result)
- field.Eventdesc = desc
- field.Strategyid = info.Strategyid
- field.Timestamp = time.Now().Local().Unix()
- field.Linktoid = info.Linktoid
- field.Beforestatus = tools.IsEmpty(state)
- field.Afterstatus = stateText
- field.Srcappid = parameter.Srcappid
- field.Dstappid = parameter.Destappid
- field.CreateAt = time.Now()
- field.UpdateAt = time.Now()
- parameter.Beforestatus = field.Beforestatus
- parameter.Afterstatus = field.Afterstatus
- parameter.Result = field.Result
- err := eventObject.AddLinkEvent(&field)
- filedByte, _ := json.Marshal(field)
- if err == nil {
- //进行联动消息处理后的回复
- go t.PublishLinkReply(parameter)
- new(LogService).SaveLog(fmt.Sprintf("添加联动事件成功,联动内容:%s", string(filedByte)))
- } else {
- new(LogService).SaveLog(fmt.Sprintf("添加联动事件失败,联动内容:%s,失败原因:%s", string(filedByte), err.Error()))
- }
- }
- } else {
- logger.Logger.Println("进行联动时未查询到联动对象")
- }
- } else {
- logger.Logger.Error(fmt.Sprintf("查询联动对象时出现错误:%s", err.Error()))
- }
- }
- //判断是否有联动配并触发联动事件
- func (t *LinkEventService) HandleLinkEvent(Field *HistoryService) {
- appid := cast.ToInt32(RtelecManageApp().RegAppID)
- Link_Info, err := t.GetLinkInfo(int(Field.Model.Deviceid))
- if err == nil && len(Link_Info) > 0 {
- var isLink = false //是否触发联动标识
- //前置测点运算关系,默认为无 1-与,2-或,3-无
- preRelation := 4
- currentLinkInfo := LinkInfo{}
- var linkdesc = ""
- logger.Logger.Debug(fmt.Sprintf("当前设备%d的联动配置:%+v", Field.Model.Deviceid, Link_Info))
- for AttrName, AttrValue := range Field.AttrInfo {
- attrvalue := AttrValue.(float64)
- for _, info := range Link_Info {
- if int(Field.Model.Deviceid) == info.Fromdeviceid && AttrName == info.Fromattrname {
- var tmpIsLink = false
- switch info.Than {
- case 1:
- if attrvalue > info.TargValue {
- tmpIsLink = true
- linkdesc = fmt.Sprintf("联动条件为>%d", int(info.TargValue))
- }
- case 2:
- if attrvalue == info.TargValue {
- tmpIsLink = true
- linkdesc = fmt.Sprintf("联动条件=%d", int(info.TargValue))
- }
- case 3:
- if attrvalue < info.TargValue {
- tmpIsLink = true
- linkdesc = fmt.Sprintf("联动条件<%d", int(info.TargValue))
- }
- case 4:
- if attrvalue >= info.TargValue {
- tmpIsLink = true
- linkdesc = fmt.Sprintf("联动条件>=%d", int(info.TargValue))
- }
- case 5:
- if attrvalue <= info.TargValue {
- tmpIsLink = true
- linkdesc = fmt.Sprintf("联动条件<=%d", int(info.TargValue))
- }
- }
- if preRelation == 2 {
- //或者
- isLink = isLink || tmpIsLink
- } else if preRelation == 1 {
- //与
- isLink = isLink && tmpIsLink
- }
- if isLink {
- //当前满足联动条件的配置信息
- currentLinkInfo = info
- }
- preRelation = info.Relation
- }
- }
- }
- if isLink {
- //内部处理不发消息
- if currentLinkInfo.Dstappid == int(appid) {
- logger.Logger.Debug(fmt.Sprintf("设备%d属性%s触发联动事件%s控制点%d动作%s,延时%d秒执行", currentLinkInfo.Fromdeviceid, currentLinkInfo.Fromattrname, currentLinkInfo.Strategyname, currentLinkInfo.Targetattrname, currentLinkInfo.Actdesc, currentLinkInfo.Delay))
- if currentLinkInfo.Delay > 0 {
- //当前联动事件延迟时长
- time.Sleep(time.Duration(currentLinkInfo.Delay) * time.Second)
- }
- var commandField CommandMgr
- //向目标设备及控制点发送控制指令
- commandField.DeviceId = currentLinkInfo.Deviceid
- commandField.AttrName = currentLinkInfo.Targetattrname
- commandField.State = int(currentLinkInfo.Actvalue)
- var state = t.getBeforestatus(currentLinkInfo.Deviceid, currentLinkInfo.Targetattrname)
- //发送指令
- var messageId = tools.GetUid()
- msgObj := new(utils.MsgStateManage)
- msgObj.SetMessageStateObj(messageId, utils.MsgState{Success: false, State: false, Message: ""})
- commandObj := new(CommandService)
- commandObj.Command(commandField, messageId, 1)
- Result := msgObj.HanderMesage(messageId, 10)
- eventObject := logic.NewLinkEventLogic()
- var field model.LinkEvent
- field.Eventid = new(utils.ToolsLogic).GetOnlyId(int64(appid))
- field.Beforestatus = tools.IsEmpty(state)
- field.Afterstatus = tools.IsEmpty(state)
- //判断成功状态
- if Result.Success {
- ExecuteState, _ := commandObj.CheckState(commandField)
- if ExecuteState {
- field.Afterstatus = strconv.Itoa(int(currentLinkInfo.Actvalue))
- field.Result = fmt.Sprintf("%s成功", currentLinkInfo.Actdesc)
- } else {
- field.Result = fmt.Sprintf("%s失败", currentLinkInfo.Actdesc)
- }
- } else {
- field.Result = Result.Message
- }
- desc := t.LinkDesc(currentLinkInfo.Linktoid) + fmt.Sprintf("触发条件:%s,将设备控制状态更改为:%s,执行结果:%s", linkdesc, currentLinkInfo.Actdesc, field.Result)
- field.Eventdesc = desc
- field.Strategyid = currentLinkInfo.Strategyid
- field.Timestamp = time.Now().Local().Unix()
- field.Linktoid = currentLinkInfo.Linktoid
- field.Srcappid = int32(currentLinkInfo.Srcappid)
- field.Dstappid = int32(appid)
- err := eventObject.AddLinkEvent(&field)
- filedByte, _ := json.Marshal(field)
- if err == nil {
- new(LogService).SaveLog(fmt.Sprintf("添加联动事件成功,联动内容:%s", string(filedByte)))
- } else {
- new(LogService).SaveLog(fmt.Sprintf("添加联动事件失败,联动内容:%s,失败原因:%s", string(filedByte), err.Error()))
- }
- } else {
- t.SendLinkMessage(currentLinkInfo)
- }
- }
- }
- }
- var isLoadLinkInfo = false
- //获取联动信息
- func (t *LinkEventService) GetLinkInfo(DeviceId int) ([]LinkInfo, error) {
- if DeviceId == 0 {
- if isLoadLinkInfo {
- return nil, nil
- }
- isLoadLinkInfo = true
- LinkData = sync.Map{}
- logger.Logger.Debug(fmt.Sprintf("====初始化联动策略===="))
- LinkObject := logic.NewLinkStrategyLogic()
- var AppId = RtelecManageApp().RegAppID
- var list []LinkInfo
- var sqlCommandText = "select b.deviceid,a.strategyid,a.appid srcappid,strategyname,linktype,linkfromid,value targ_value,than,relation,b.appid dstappid,linktoid,modelid,a.deviceid fromdeviceid,a.attrname fromattrname,b.actid,b.attrname targerattrname,b.actvalue,b.actdesc,b.delay " +
- fmt.Sprintf("from (select a.strategyid,a.appid,a.strategyname,a.linktype,b.linkfromid,b.value,b.than,b.relation,mp.deviceid,mp.attrname from link_strategy a inner join link_relation_obj b on a.strategyid=b.strategyid inner join dev_mpinfo mp on b.linkfromid=mp.mpid where a.disable=1 and a.appid=%s) a ", AppId) +
- fmt.Sprintf("left join (select strategyid,b.attrname,c.appid,c.deviceid,linktoid,c.modelid,a.actid,a.delay,cp.value actvalue,cp.actdesc from link_relation_action a inner join dev_cpinfo b on a.linktoid=b.cpid inner join dev_devinfo c on b.deviceid=c.deviceid inner join dev_cpaction cp on a.actid=cp.actid) b on a.strategyid=b.strategyid ")
- logger.Logger.Debug(sqlCommandText)
- err := LinkObject.SvcCtx.LinkStrategy.Base.Raw(sqlCommandText, &list)
- if err == nil {
- for _, val := range list {
- //var deviceList []LinkInfo
- //deviceList = append(deviceList, val)
- //LinkData[val.Deviceid] = deviceList
- if val.Dstappid == 0 {
- //尝试查询判断是否视频设备
- type VideoDeviceInfo struct {
- Dstappid int
- Deviceid int64
- Actid int64
- Linktoid int64
- Mpname string
- }
- sql := fmt.Sprintf(`select b.deviceid,a.strategyid,a.appid srcappid,strategyname,linktype,linkfromid,value targ_value,than,relation,b.appid dstappid,linktoid,modelid,a.deviceid fromdeviceid,a.attrname fromattrname,b.actid,b.attrname mpname,b.actvalue,b.actdesc,b.delay
- from (select a.strategyid,a.appid,a.strategyname,a.linktype,b.linkfromid,b.value,b.than,b.relation,mp.deviceid,mp.attrname from link_strategy a inner join link_relation_obj b on a.strategyid=b.strategyid inner join dev_mpinfo mp on b.linkfromid=mp.mpid where a.disable=1 and a.appid=%s and a.strategyid=%s) a
- left join (select a.strategyid,a.linktoid,b.mpname attrname,c.appid,c.device_id deviceid,c.model modelid,a.actid,a.delay,cp.acttype actvalue,cp.actdesc from link_relation_action a inner join video_mpinfo b on a.linktoid=b.mpid inner join video_devinfo c on b.deviceid=c.device_id left join video_action cp on a.actid=cp.actid where a.strategyid=%s) b on a.strategyid=b.strategyid`, AppId, tools.IsEmpty(val.Strategyid), tools.IsEmpty(val.Strategyid))
- var videoDeviceList []VideoDeviceInfo
- err := LinkObject.SvcCtx.LinkStrategy.Base.Raw(sql, &videoDeviceList)
- if err != nil {
- logger.Logger.Error(err)
- logger.Logger.Println(sql)
- continue
- }
- if len(videoDeviceList) == 0 {
- logger.Logger.Println(fmt.Sprintf("未发现测点%d关联的设备信息!", val.Linktoid))
- continue
- }
- val.Dstappid = videoDeviceList[0].Dstappid
- val.Deviceid = int(videoDeviceList[0].Deviceid)
- val.Targetattrname = videoDeviceList[0].Mpname
- val.Actid = videoDeviceList[0].Actid
- val.Linktoid = videoDeviceList[0].Linktoid
- }
- logger.Logger.Debug(fmt.Sprintf("====初始化加载联动策略:%+v", val))
- lst, has := LinkData.Load(val.Fromdeviceid)
- if has {
- lst2 := lst.([]LinkInfo)
- lst2 = append(lst2, val)
- LinkData.Store(val.Fromdeviceid, lst2)
- } else {
- lst := []LinkInfo{val}
- LinkData.Store(val.Fromdeviceid, lst)
- }
- }
- } else {
- logger.Logger.Error(err)
- logger.Logger.Println(sqlCommandText)
- }
- isLoadLinkInfo = false
- return list, err
- } else {
- lst, _ := LinkData.Load(DeviceId)
- if lst == nil {
- return []LinkInfo{}, nil
- }
- return lst.([]LinkInfo), nil
- }
- }
- func (t *LinkEventService) getBeforestatus(deviceId int, attrname string) int {
- deviceServiceIns := new(DeviceService)
- //获取设备的模型信息
- deviceModelInfo := deviceServiceIns.GetComboxListById(int32(deviceId))
- if deviceModelInfo == nil {
- logger.Logger.Error("未发现模型配置信息")
- return 0
- }
- ormrow, err := new(bo.Global).GetCodeInfo("model_table_mapping", cast.ToString(deviceModelInfo.Modelid))
- if err != nil || tools.IsEmpty(ormrow["name"]) == "" {
- logger.Logger.Error(fmt.Sprintf("未找到模型id=%d对应的数据表关系", deviceModelInfo.Modelid))
- return 0
- }
- localtablename := "t_data_" + tools.IsEmpty(ormrow["name"])
- var result = 0
- o := orm.NewOrm()
- var sqlCommandText = "select " + attrname + " val from " + localtablename + " where deviceid=? order by id desc limit 1 "
- var sqlparameter = []interface{}{deviceId}
- var table []orm.Params
- _, err = o.Raw(sqlCommandText, sqlparameter).Values(&table)
- if err == nil && len(table) > 0 {
- result, _ = strconv.Atoi(tools.IsEmpty(table[0]["val"]))
- } else {
- logger.Logger.Error(err, fmt.Sprintf("SQL:%s 参数:%+v", sqlCommandText, sqlparameter))
- }
- return result
- }
- //获取联动信息
- func (t *LinkEventService) GetLinkByStrategyId(strategyid, linktoid, actid int64) ([]LinkInfo, error) {
- LinkObject := logic.NewLinkStrategyLogic()
- var Result []LinkInfo
- var sqlCommandText = "select DISTINCT e.deviceid,e.modelid,e.attrname targetattrname,a.strategyid,linktoid,d.value actvalue,d.actdesc,d.actid " +
- " from link_strategy a inner join link_relation_obj b on a.strategyid=b.strategyid inner join link_relation_action c on a.strategyid=c.strategyid inner join dev_cpaction d on d.cpid=c.linktoid inner join dev_cpinfo e on d.cpid=e.cpid " +
- fmt.Sprintf("where a.disable=1 and a.strategyid=%d and linktoid=%d and d.actid=%d", strategyid, linktoid, actid)
- err := LinkObject.SvcCtx.LinkStrategy.Base.Raw(sqlCommandText, &Result)
- if err != nil {
- logger.Logger.Error(err)
- logger.Logger.Println(sqlCommandText)
- }
- return Result, err
- }
- //根据联动目标ID获得描述
- func (t *LinkEventService) LinkDesc(linktoId int64) string {
- if desc, ok := LinkDescription[linktoId]; ok {
- return desc
- } else {
- mpInfo := logic.NewMpInfoLogic()
- type Mpfield struct {
- Eventdesc string `json:"eventdesc"`
- }
- var list []Mpfield
- var sqlCommandText = fmt.Sprintf("select concat(c.name,',区域:',a.zonename,',位置:',a.positionname,',控制点名称:',a.cpname) eventdesc from dev_cpinfo a inner join dev_devinfo b on a.deviceid=b.deviceid inner join sys_station c on b.stationid=c.stationid where a.cpid=%d", linktoId)
- err := mpInfo.SvcCtx.DevMpinfo.Base.Raw(sqlCommandText, &list)
- if err == nil && len(list) > 0 {
- LinkDescription[linktoId] = list[0].Eventdesc + ","
- }
- return LinkDescription[linktoId]
- }
- }
- //联动消息回复
- func (t *LinkEventService) PublishLinkReply(replyContent LinkeBody) {
- var parameter = make(map[string]interface{})
- parameter["srcappid"] = replyContent.Srcappid
- parameter["destappid"] = replyContent.Destappid
- parameter["eventid"] = replyContent.Eventid
- parameter["eventdesc"] = replyContent.Eventdesc
- parameter["linktype"] = replyContent.Linktype
- parameter["strategyid"] = replyContent.Strategyid
- parameter["linktoid"] = replyContent.Linktoid
- parameter["actid"] = replyContent.Actid
- parameter["beforestatus"] = replyContent.Beforestatus
- parameter["afterstatus"] = replyContent.Afterstatus
- parameter["result"] = replyContent.Result
- parameter["reply"] = replyContent.Reply
- parameter["mid"] = replyContent.MessageId
- parameter["timestamp"] = time.Now().Unix()
- messageContent, _ := json.Marshal(parameter)
- logger.Logger.Debug(fmt.Sprintf("=====联动消息回复主题(%s)内容:%s", global.Rtelec_Topics["link_reply"], string(messageContent)))
- mqtt.PublishMessage(global.Rtelec_Topics["link_reply"], string(messageContent))
- }
- //发送联动消息
- func (t *LinkEventService) SendLinkMessage(record LinkInfo) {
- var parameter = make(map[string]interface{})
- parameter["srcappid"] = record.Srcappid
- parameter["destappid"] = record.Dstappid
- parameter["eventid"] = new(logic.ToolsLogic).GetOnlyId(cast.ToInt64(RtelecManageApp().RegAppID))
- parameter["eventdesc"] = record.Strategyname
- parameter["linktype"] = record.Linktype
- parameter["strategyid"] = record.Strategyid
- parameter["linktoid"] = record.Linktoid
- parameter["actid"] = record.Actid
- parameter["mid"] = tools.GetUid()
- messageContent, _ := json.Marshal(parameter)
- logger.Logger.Debug(fmt.Sprintf("=====发送联动消息主题(%s)内容:%s", global.Rtelec_Topics["link_request"], string(messageContent)))
- mqtt.PublishMessage(global.Rtelec_Topics["link_request"], string(messageContent))
- }
|