123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429 |
- package Warning
- import (
- "Cold_mqtt/conf"
- "Cold_mqtt/lib"
- "Cold_mqtt/logs"
- "Cold_mqtt/models/Device"
- "fmt"
- "github.com/astaxie/beego/cache"
- _ "github.com/astaxie/beego/cache/redis"
- "github.com/beego/beego/v2/adapter/orm"
- _ "github.com/go-sql-driver/mysql"
- "strconv"
- "strings"
- "time"
- )
- type Warning struct {
- Id int64 `orm:"pk;column(ID);size(11);auto;"`
- T_pid int `orm:"size(256);null"` // Account.Company 绑定公司
- T_tp int `orm:"index;size(200);null"` // 报警类型 ->WarningList
- T_sn string `orm:"index;size(256);null"` // 设备序列号
- T_D_name string `orm:"size(256);null"` // 设备名称
- T_id int `orm:"index;size(200);null"` // 传感器 ID
- T_DS_name string `orm:"size(256);null"` // 传感器名称
- T_Remark string `orm:"type(text);"` // 采集内容
- T_t float32 `orm:"size(256);"` // 温度
- T_rh float32 `orm:"size(256);"` // 湿度
- T_site string `orm:"size(256);"` // GPS
- T_sp int `orm:"size(11);"` // 传感器参数id
- T_Ut time.Time `orm:"index;type(timestamp);null;"` // 采集时间
- T_fUt time.Time `orm:"type(timestamp);null;"` // 首次采集时间
- T_Text string `orm:"type(text);null"` // 处理备注
- T_Log string `orm:"type(text);null"` // 通知日志
- T_Msid int64 `orm:"size(256);null"` // 消息ID
- T_State int `orm:"size(2);default(2)"` // 0 删除 1 不处理 2 已处理 3 未处理
- CreateTime time.Time `orm:"column(create_time);type(timestamp);null;auto_now_add"` //auto_now_add 第一次保存时才设置时间
- UpdateTime time.Time `orm:"column(update_time);type(timestamp);null;auto_now"` // auto_now 每次 model 保存时都会对时间自动更新
- }
- // 多字段索引
- func (u *Warning) TableIndex() [][]string {
- return [][]string{
- []string{"T_pid", "T_tp", "T_State"},
- }
- }
- func (t *Warning) TableName() string {
- return "warning" // 数据库名称 // ************** 替换 FormulaList **************
- }
- var redisCache_Warning cache.Cache
- var redisCache_WarningStart cache.Cache // 缓存报警开始 时间点
- func init() {
- //注册模型
- orm.RegisterModel(new(Warning))
- config := fmt.Sprintf(`{"key":"%s","conn":"%s","dbNum":"%s","password":"%s"}`,
- "redis_WarningNum", conf.Redis_address, conf.Redis_dbNum, conf.Redis_password)
- logs.Println(config)
- var err error
- redisCache_Warning, err = cache.NewCache("redis", config)
- if err != nil || redisCache_Warning == nil {
- errMsg := "failed to init redis"
- logs.Println(errMsg, err)
- }
- config = fmt.Sprintf(`{"key":"%s","conn":"%s","dbNum":"%s","password":"%s"}`,
- "redis_WarningStart", conf.Redis_address, conf.Redis_dbNum, conf.Redis_password)
- logs.Println(config)
- redisCache_WarningStart, err = cache.NewCache("redis", config)
- if err != nil || redisCache_WarningStart == nil {
- errMsg := "failed to init redis"
- logs.Println(errMsg, err)
- }
- }
- // ---------------- Redis -------------------
- // Redis_Set(m.T_sn,m) // Redis 更新缓存
- func Redis_Warning_Set(key string) (err error) {
- err = redisCache_Warning.Put(key, "", 24*time.Hour)
- if err != nil {
- logs.Println("set key:", key)
- }
- return
- }
- func Redis_Warning_Repeat_T_sn_Msid(key string) (is bool) {
- if redisCache_Warning.IsExist(key) {
- redisCache_Warning.Put(key, "", 60*time.Minute)
- //println("找到key:",key)
- return true
- }
- redisCache_Warning.Put(key, "", 60*time.Minute)
- return false
- }
- // 缓存报警次数 cut 持续秒 (计次,剩余时间s)
- func Redis_Warning_Num(key string) (int64, int) {
- if redisCache_Warning.IsExist(key) {
- //logs.Println("Redis_Warning_Num 找到key:", key)
- r := redisCache_Warning.Get(key)
- if r == nil {
- return 0, 0
- }
- value_str := string(r.([]byte))
- value_str_list := strings.Split(value_str, "|")
- if len(value_str_list) != 2 {
- return 0, 0
- }
- logs.Println("value_str_list:", value_str_list) //value_str_list: [[1 1677724222]]
- value_int, _ := strconv.ParseInt(value_str_list[0], 10, 64)
- cut := int(time.Unix(lib.To_int64(value_str_list[1]), 0).Unix() - time.Now().Unix()) // 计算 还剩 s秒时间
- return value_int, cut
- }
- return 0, 0
- }
- // 缓存报警次数 cut 持续秒 (计次,剩余时间s)
- func Redis_Warning_Num_W(key, cuts string) (int64, int) {
- cut, err := strconv.Atoi(cuts)
- if err != nil {
- logs.PrintlnError("Redis_Warning_Num err:", err)
- }
- if redisCache_Warning.IsExist(key) {
- //logs.Println("Redis_Warning_Num 找到key:", key)
- r := redisCache_Warning.Get(key)
- if r == nil {
- goto breakHere // 跳转到标签
- }
- value_str := string(r.([]byte))
- value_str_list := strings.Split(value_str, "|")
- logs.Println("value_str_list:", value_str_list) //value_str_list: [[1 1677724222]]
- if len(value_str_list) != 2 {
- goto breakHere // 跳转到标签
- }
- value_int, _ := strconv.ParseInt(value_str_list[0], 10, 64)
- value_int += 1 // 数量
- //logs.Println("有数据 value_int:", value_int)
- cut = int(time.Unix(lib.To_int64(value_str_list[1]), 0).Unix() - time.Now().Unix()) // 计算 还剩 s秒时间
- redisCache_Warning.Put(key, fmt.Sprintf("%d|%s", value_int, value_str_list[1]), time.Duration(cut)*time.Second)
- logs.Println("Redis_Warning_Num KEY:", key, "->", value_int, " 还剩时间 ->", cut)
- return value_int, cut
- }
- breakHere:
- //logs.Println("没有数据 value_int:", 1)
- s, _ := time.ParseDuration(fmt.Sprintf("%ds", cut))
- redisCache_Warning.Put(key, fmt.Sprintf("1|%d", time.Now().Add(s).Unix()), time.Duration(cut)*time.Second)
- logs.Println("Redis_Warning_Num NewKEY:", key, " cut:", cut)
- return 1, cut
- }
- // 管理员 缓存报警次数
- func Redis_WarningToAdmin_Num(key string) bool {
- if redisCache_Warning.IsExist(key) {
- ////logs.Println("Redis_Warning_Num 找到key:", key)
- //r := redisCache_Warning.Get(key)
- //value_str := string(r.([]byte))
- //value_int, _ := strconv.ParseInt(value_str, 10, 64)
- //value_int += 1
- ////logs.Println("有数据 value_int:", value_int)
- ////redisCache_Warning.Put(key, strconv.FormatInt(value_int, 10), 11*time.Minute)
- return false
- }
- //logs.Println("没有数据 value_int:", 1)
- redisCache_Warning.Put(key, "1", 30*time.Minute)
- return true
- }
- // --- 缓存 报警时间,减轻数据库压力
- func Redis_WarningTimeListIs(m Warning) bool {
- key := m.T_sn + "|" + strconv.Itoa(m.T_id) + "|" + strconv.Itoa(m.T_tp) + "|" + m.T_Ut.Format("2006-01-02 15:04:05")
- if redisCache_WarningStart.IsExist(key) {
- return true
- }
- redisCache_WarningStart.Put(key, "", 60*time.Minute)
- return false
- }
- // 首次开始时间
- func Redis_WarningStart(m Warning) time.Time {
- key := m.T_sn + "|" + strconv.Itoa(m.T_id) + "|" + strconv.Itoa(m.T_tp)
- if redisCache_WarningStart.IsExist(key) {
- // 上一条报警时间
- val := redisCache_WarningStart.Get(key)
- // 将字符串转换为整数
- unixTime, err := strconv.ParseInt(string(val.([]uint8)), 10, 64)
- if err == nil {
- // 转换为 time.Time 类型
- time_ut_lod := time.Unix(unixTime, 0)
- if time_ut_lod != m.T_fUt {
- logs.Println("报警首时间不一样 (提示):",time_ut_lod.Format("2006-01-02 15:04:05"),m.T_fUt.Format("2006-01-02 15:04:05"))
- }
- return time_ut_lod
- }
- logs.Println("时间转换错误:",string(val.([]uint8)), err.Error())
- }
- redisCache_WarningStart.Put(key, fmt.Sprintf("%d", m.T_fUt.Unix()), 60*time.Minute)
- return m.T_fUt
- }
- //func Redis_WarningStart(m Warning, time_ut time.Time) (bool, time.Time) {
- // key := m.T_sn + "|" + strconv.Itoa(m.T_id) + "|" + strconv.Itoa(m.T_tp)
- // logs_s := ""
- // logs_s += key + "|" + time_ut.Format("2006-01-02 15:04:05") + "=>"
- // if redisCache_WarningStart.IsExist(key) {
- // // 上一条报警时间
- // val := redisCache_WarningStart.Get(key)
- //
- // // 将字符串转换为整数
- // //logs.Println("val:[]uint8 ",val.([]uint8), string(val.([]uint8)))
- // unixTime, err := strconv.ParseInt(string(val.([]uint8)), 10, 64)
- // if err != nil {
- // logs.Println("时间转换错误:",string(val.([]uint8)), err.Error())
- // goto to1
- // }
- //
- // // 转换为 time.Time 类型
- // time_ut_lod := time.Unix(unixTime, 0)
- //
- // logs_s += "找到上一条报警时间" + time_ut_lod.Format("2006-01-02 15:04:05") + ","
- // // 计算时间差
- // duration := time_ut.Sub(time_ut_lod)
- //
- // // 判断是否在 2~4 分钟范围
- // if duration < 2*time.Minute || duration >= 4*time.Minute {
- // logs_s += "距离间隔" + strconv.Itoa(int(duration)) + "秒,时间不在2~4分钟间隔范围,跳过报警!"
- // logs.Println("报警时间计算处理:", logs_s)
- // return false, time_ut_lod
- // }
- //
- // lib.PeriodWTime(m.T_fUt,m.T_fUt,2)
- // // 在当前时间上加2分钟
- // time_ut = time_ut.Add(2 * time.Minute)
- //
- // redisCache_WarningStart.Put(key, fmt.Sprintf("%d", time_ut.Unix()) , 60*time.Minute)
- // logs_s += "最终时间" + time_ut_lod.Format("2006-01-02 15:04:05")
- // logs.Println("报警时间计算处理:", logs_s)
- // return true, time_ut
- // }
- //to1:
- // redisCache_WarningStart.Put(key, fmt.Sprintf("%d", time_ut.Unix()), 60*time.Minute)
- // logs_s += "最终时间" + time_ut.Format("2006-01-02 15:04:05")
- // logs.Println("报警时间计算处理:", logs_s)
- // return true, time_ut
- //}
- // 清除报警机制
- func Redis_WarningStart_DelK(m Warning) (time.Time, bool) {
- key := m.T_sn + "|" + strconv.Itoa(m.T_id) + "|" + strconv.Itoa(m.T_tp)
- if redisCache_WarningStart.IsExist(key) {
- val := redisCache_WarningStart.Get(key)
- redisCache_WarningStart.Delete(key)
- unixTime, err := strconv.ParseInt(string(val.([]uint8)), 10, 64)
- if err != nil {
- logs.Println("时间转换错误:", string(val.([]uint8)), err.Error())
- }
- // 转换为 time.Time 类型
- time_ut_lod := time.Unix(unixTime, 0)
- return time_ut_lod, true
- }
- return time.Now(), false
- }
- // ---------------- 特殊方法 -------------------
- //
- // func Is2Subtable(T_tp int) bool {
- // //109 市电断电报警 市电断电报警,0,1,0,0,99999,0,0,0,0,0,0,0,0,0,0,0,0| 1
- // //110 市电已恢复 市电已恢复,0,1,0,0,99999,0,0,0,0,0,0,0,0,0,0,0,0| 1
- // values := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 109, 110}
- //
- // for _, value := range values {
- // if T_tp == value {
- //
- // return true
- // }
- // }
- // return false
- // }
- //
- // 添加
- func Add_Warning(m Warning) (id int64, err error) {
- // 查看 sn 是否有归属
- if m.T_pid == 0 { // 寻找报警归属
- if len(m.T_sn) > 1 {
- r_Device, err := Device.Read_Device_ByT_sn(m.T_sn)
- if err != nil {
- logs.Println("MessageDisconnected 没有该设备:", m.T_sn)
- }
- m.T_pid = r_Device.T_pid
- }
- }
- if m.T_id == -1 {
- m.T_DS_name = m.T_D_name
- }
- if len(m.T_DS_name) == 0 {
- m.T_DS_name = m.T_D_name
- }
- //if(conf.Test_server){
- // logs.Println("Add_Warning:",m)
- // return id, err
- //}
- o := orm.NewOrm()
- id, err = o.Insert(&m)
- if err != nil {
- logs.PrintlnError("Add_Warning err:", err)
- }
- // 插入分表
- //warningDB := WarningDB{
- // T_pid: int32(m.T_pid),
- // T_tp: m.T_tp,
- // T_sn: m.T_sn,
- // T_D_name: m.T_D_name,
- // T_id: int32(m.T_id),
- // T_DS_name: m.T_DS_name,
- // T_Remark: m.T_Remark,
- // T_Ut: m.T_Ut,
- // T_fUt: m.T_fUt,
- // T_Text: m.T_Text,
- // T_Log: m.T_Log,
- // T_Msid: m.T_Msid,
- // T_State: m.T_State,
- // CreateTime: m.CreateTime,
- // UpdateTime: m.UpdateTime,
- //}
- //warningDB.Create("warning_" + m.T_Ut.Format("2006_01"))
- INSERT("warning_"+m.T_Ut.Format("2006_01"), m.Id) // 旧 备份
- logs.PrintlnWData("WData", m.T_pid, m.T_tp, m.T_sn, m.T_Remark) // 记录报警日志
- return id, err
- }
- // 修改
- func Update_Warning(r Warning, cols ...string) bool {
- o := orm.NewOrm()
- if _, err := o.Update(&r, cols...); err == nil {
- //logs.Println("Number of records updated in database:", num)
- // 插入备份表
- UPDATE("warning_"+r.T_Ut.Format("2006_01"), r.Id, r.T_Log)
- return true
- }
- return false
- }
- // 追加 日志
- func Add_Warning_Log(r *Warning, T_Log string) {
- r.T_Log = r.T_Log + T_Log
- return
- }
- func Add_DeviceLogs(T_tp int, r_Device Device.Device, T_Remark string) Warning {
- var Warning_r Warning
- Warning_r.T_pid = r_Device.T_pid
- Warning_r.T_tp = T_tp
- Warning_r.T_sn = r_Device.T_sn
- Warning_r.T_D_name = r_Device.T_devName
- Warning_r.T_DS_name = r_Device.T_devName
- Warning_r.T_id = -1
- Warning_r.T_Remark = T_Remark
- Warning_r.T_Ut = time.Now()
- Warning_r.T_State = 1
- // 查看 sn 是否有归属
- if Warning_r.T_pid == 0 { // 寻找报警归属
- if len(Warning_r.T_sn) > 10 {
- r_Device, err := Device.Read_Device_ByT_sn(Warning_r.T_sn)
- if err != nil {
- logs.Println("MessageDisconnected 没有该设备:", Warning_r.T_sn)
- }
- Warning_r.T_pid = r_Device.T_pid
- }
- }
- // 添加报警
- id, _ := Add_Warning(Warning_r)
- Warning_r.Id = id
- return Warning_r
- }
- // 指定设备与类型最新的记录
- func Read_T_snT_tp(T_sn string, T_tp int) Warning {
- o := orm.NewOrm()
- // 也可以直接使用 Model 结构体作为表名
- qs := o.QueryTable(new(Warning))
- var r Warning
- qs.Filter("T_sn", T_sn).Filter("T_tp", T_tp).OrderBy("-T_Ut").One(&r)
- return r
- }
- // 指定设备与类型消息ID最新的记录
- func Read_T_snT_tpT_Msid(T_sn string, T_tp, T_Msid int) Warning {
- o := orm.NewOrm()
- // 也可以直接使用 Model 结构体作为表名
- qs := o.QueryTable(new(Warning))
- var r Warning
- qs.Filter("T_sn", T_sn).Filter("T_tp", T_tp).Filter("T_Msid", T_Msid).OrderBy("-T_Ut").One(&r)
- return r
- }
- // 指定设备与类型消息ID最新的记录
- func Read_T_snT_idT_tp(T_sn string, T_id, T_tp int) Warning {
- o := orm.NewOrm()
- // 也可以直接使用 Model 结构体作为表名
- qs := o.QueryTable(new(Warning))
- var r Warning
- qs.Filter("T_sn", T_sn).Filter("T_id", T_id).Filter("T_tp", T_tp).OrderBy("-T_Ut").One(&r)
- return r
- }
|