package controllers import ( conf "ColdP_server/conf" "ColdP_server/controllers/MqttServer" "ColdP_server/controllers/lib" "ColdP_server/models/Company" "ColdP_server/models/Device" "ColdP_server/models/Warning" "context" "encoding/json" "fmt" beego "github.com/beego/beego/v2/server/web" "io" "log" "math" "strconv" "strings" "time" ) // DeviceController 设备管理页面 type DeviceController struct { beego.Controller } // DeviceManagerHtml 返回页面 func (c *DeviceController) DeviceManagerHtml() { //验证是否登录 is, admin := lib.VerificationController(&c.Controller) if !is { return } //类名列表 classList := Company.Read_CompanyClass_All(admin.T_pid, "") c.Data["Class_List"] = classList c.TplName = "Device/Device.html" } // DeviceList 获取设备列表 func (c *DeviceController) DeviceList() { tName := c.GetString("deviceName") //设备名称 page, _ := c.GetInt64("currentPage") //当前页码 tClassify, _ := c.GetInt("deviceClass") //设备分类 is, admin := lib.VerificationController(&c.Controller) fmt.Println("当前用户的PID为:", admin.T_pid) if !is { //用户未登录 c.Data["json"] = lib.JSONS{202, "身份认证失效", nil} c.ServeJSON() return } device_list, count := Device.Read_DeviceSensor_List_T_ClassOr(admin.T_pid, tClassify, tName, tName, -1, int(page), conf.Page_size) var pageCount int if (int(count) % conf.Page_size) != 0 { pageCount = int(count) / conf.Page_size pageCount++ } c.Data["json"] = lib.PageHelper{int(count), pageCount, int(page), int(page) >= pageCount, page <= 1, device_list} c.ServeJSON() return } // CompanyClass 获取公司设备类目 func (c *DeviceController) CompanyClass() { is, admin := lib.VerificationController(&c.Controller) if !is { c.Data["json"] = lib.JSONS{202, "用户未登录", nil} c.ServeJSON() return } //类名列表 classList := Company.Read_CompanyClass_All(admin.T_pid, "") c.Data["json"] = classList c.ServeJSON() } // DataRepeat 数据重传 func (c *DeviceController) DataRepeat() { b_, _ := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey")) if !b_ { c.Data["json"] = lib.JSONS{Code: 201, Msg: "User_tokey Err!"} c.ServeJSON() return } t := MqttServer.DataRepeat_C{} bytes, _ := io.ReadAll(c.Ctx.Request.Body) json.Unmarshal(bytes, &t) fmt.Println("浏览器接收数据:", t) s, _ := time.Parse("2006-01-02 15:04:05", t.StartTime) e, _ := time.Parse("2006-01-02 15:04:05", t.EndTime) // 发送MQTT for k, v := range t.Sns { topic := fmt.Sprintf("/pub/%s", k) repeatPub := MqttServer.DataRepeat_Pub{Sn: k, Type: 9, Mid: time.Now().Unix(), Data: MqttServer.DataRepeat_Pub_Data{Start: s.Unix(), End: e.Unix(), Id: v}} msg, _ := json.Marshal(repeatPub) mqttId := strings.Split(Device.ReadDeviceMqttId(k), "\"")[0] client, err := MqttServer.GetMqttClient(mqttId) if err != nil { log.Printf("Error getting MQTT client for SN: %s, %v", k, err) continue } for i := 0; i < 3; i++ { time.Sleep(time.Second * time.Duration(i+1)) if err := MqttServer.PubMqttMessage(client, topic, msg); err != nil { log.Printf("Error publishing MQTT message for SN: %s, %v", k, err) c.Data["json"] = lib.JSONS{Code: 0, Msg: "设置失败", Data: k} return } } client.Disconnect() client.Terminate() } c.Data["json"] = lib.JSONS{Code: 200, Msg: "数据重传成功", Data: nil} c.ServeJSON() return } // ReadDeviation 读取偏差值 func (c *DeviceController) ReadDeviation() { b_, _ := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey")) if !b_ { c.Data["json"] = lib.JSONS{Code: 201, Msg: "User_tokey Err!"} c.ServeJSON() return } t := make(map[string][]int) bytes, _ := io.ReadAll(c.Ctx.Request.Body) if err := json.Unmarshal(bytes, &t); err != nil { log.Printf("Error unmarshalling JSON: %v", err) c.Data["json"] = lib.JSONS{Code: 400, Msg: "Bad Request"} c.ServeJSON() return } fmt.Println("浏览器接收数据:", t) // MQTT发送 fmt.Println("发送MQTT t:", t) deviation := make(chan string, 10) var count = 0 for k, v := range t { topicSub := fmt.Sprintf("/sub/%s", k) topicPub := fmt.Sprintf("/pub/%s", k) mqttId := Device.ReadDeviceMqttId(k) client, err := MqttServer.GetMqttClient(mqttId) if err != nil { log.Printf("Error getting MQTT client for SN: %s, %v", k, err) continue } // 订阅主题 if err := MqttServer.Subscript(client, topicSub, deviation, "\"type\":7,"); err != nil { log.Printf("Error subscribing to MQTT topic for SN: %s, %v", k, err) c.Data["json"] = lib.JSONS{Code: 1, Msg: "mqtt订阅连接失败", Data: nil} return continue } pubData, _ := json.Marshal(MqttServer.Deviation_Pub{ Sn: k, Type: 7, Mid: time.Now().Unix(), Data: v, }) if err := MqttServer.PubMqttMessage(client, topicPub, pubData); err != nil { log.Printf("Error publishing MQTT message for SN: %s, %v", k, err) c.Data["json"] = lib.JSONS{Code: 1, Msg: "mqtt发送失败", Data: k} continue } count++ } deviceRepeatData := make([]string, 0) timeout := time.After(10 * time.Second) // 设置超时时间 for count > 0 { select { case v := <-deviation: fmt.Println("channel收到数据:", v) fmt.Println("count:", count) deviceRepeatData = append(deviceRepeatData, v) count-- case <-timeout: log.Println("Timeout waiting for MQTT responses") c.Data["json"] = lib.JSONS{Code: 500, Msg: "Timeout waiting for MQTT responses"} c.ServeJSON() return } } close(deviation) fmt.Println("响应数据:", deviceRepeatData) c.Data["json"] = lib.JSONS{Code: 200, Msg: "偏差值上传成功", Data: deviceRepeatData} c.ServeJSON() return } // WriteDeviation 设置偏差值 func (c *DeviceController) WriteDeviation() { b_, _ := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey")) if !b_ { c.Data["json"] = lib.JSONS{Code: 201, Msg: "User_tokey Err!"} c.ServeJSON() return } bytes, _ := io.ReadAll(c.Ctx.Request.Body) fmt.Println("请求json:", string(bytes)) data := make([]MqttServer.Deviation_Sub, 0) if err := json.Unmarshal(bytes, &data); err != nil { log.Printf("Error unmarshalling JSON: %v", err) c.Data["json"] = lib.JSONS{Code: 400, Msg: "Bad Request"} c.ServeJSON() return } // 处理每个设备的数据 for _, v := range data { go func(v MqttServer.Deviation_Sub) { v.Type = 8 v.Mid = int(time.Now().Unix()) mqttId := Device.ReadDeviceMqttId(v.Sn) client, err := MqttServer.GetMqttClient(mqttId) if err != nil { log.Printf("Error getting MQTT client for SN: %s, %v", v.Sn, err) return } msgBytes, err := json.Marshal(v) if err != nil { log.Printf("Error marshalling JSON for SN: %s, %v", v.Sn, err) client.Disconnect() client.Terminate() return } for i := 0; i < 3; i++ { time.Sleep(time.Second * time.Duration(i+1)) if err := MqttServer.PubMqttMessage(client, fmt.Sprintf("/pub/%s", v.Sn), msgBytes); err != nil { log.Printf("Error publishing MQTT message for SN: %s, %v", v.Sn, err) c.Data["json"] = lib.JSONS{Code: 0, Msg: "设置失败", Data: v.Sn} return } } client.Disconnect() client.Terminate() }(v) } c.Data["json"] = lib.JSONS{Code: 200, Msg: "设置偏差值成功!", Data: nil} c.ServeJSON() return } // ReadSensor 读取偏差值 func (c *DeviceController) ReadSensor() { b_, _ := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey")) if !b_ { c.Data["json"] = lib.JSONS{Code: 201, Msg: "User_tokey Err!"} c.ServeJSON() return } t := make(map[string][]int) bytes, _ := io.ReadAll(c.Ctx.Request.Body) if err := json.Unmarshal(bytes, &t); err != nil { log.Printf("Error unmarshalling JSON: %v", err) c.Data["json"] = lib.JSONS{Code: 400, Msg: "Bad Request"} c.ServeJSON() return } fmt.Println("浏览器接收数据:", t) // MQTT发送 fmt.Println("发送MQTT t:", t) deviation := make(chan string, 10) var count = 0 for k, v := range t { topicSub := fmt.Sprintf("/sub/%s", k) topicPub := fmt.Sprintf("/pub/%s", k) mqttId := Device.ReadDeviceMqttId(k) client, err := MqttServer.GetMqttClient(mqttId) if err != nil { log.Printf("Error getting MQTT client for SN: %s, %v", k, err) continue } // 订阅主题 if err := MqttServer.Subscript(client, topicSub, deviation, "\"type\":5,"); err != nil { log.Printf("Error subscribing to MQTT topic for SN: %s, %v", k, err) continue } pubData, _ := json.Marshal(MqttServer.Deviation_Pub{ Sn: k, Type: 5, Mid: time.Now().Unix(), Data: v, }) if err := MqttServer.PubMqttMessage(client, topicPub, pubData); err != nil { log.Printf("Error publishing MQTT message for SN: %s, %v", k, err) c.Data["json"] = lib.JSONS{Code: 1, Msg: "mqtt发送失败", Data: k} continue } count++ } deviceRepeatData := make([]string, 0) timeout := time.After(10 * time.Second) // 设置超时时间 for count > 0 { select { case v := <-deviation: fmt.Println("channel收到数据:", v) fmt.Println("count:", count) deviceRepeatData = append(deviceRepeatData, v) count-- case <-timeout: log.Println("Timeout waiting for MQTT responses") c.Data["json"] = lib.JSONS{Code: 500, Msg: "Timeout waiting for MQTT responses"} c.ServeJSON() return } } close(deviation) fmt.Println("响应数据:", deviceRepeatData) c.Data["json"] = lib.JSONS{Code: 200, Msg: "偏差值上传成功", Data: deviceRepeatData} c.ServeJSON() return } // WriteSensor 设置偏差值 func (c *DeviceController) WriteSensor() { b_, _ := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey")) if !b_ { c.Data["json"] = lib.JSONS{Code: 201, Msg: "User_tokey Err!"} c.ServeJSON() return } bytes, err := io.ReadAll(c.Ctx.Request.Body) if err != nil { log.Printf("Error reading request body: %v", err) c.Data["json"] = lib.JSONS{Code: 500, Msg: "Internal Server Error"} c.ServeJSON() return } fmt.Println("请求json:", string(bytes)) data := make([]MqttServer.Sensor_Sub, 0) if err := json.Unmarshal(bytes, &data); err != nil { log.Printf("Error unmarshalling JSON: %v", err) c.Data["json"] = lib.JSONS{Code: 400, Msg: "Bad Request"} c.ServeJSON() return } // 设置上下文超时 ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() // 处理每个设备的数据 for _, v := range data { go func(v MqttServer.Sensor_Sub) { select { case <-ctx.Done(): log.Printf("Context canceled or timeout for SN: %s", v.Sn) return default: } v.Type = 6 v.Mid = int(time.Now().Unix()) mqttId := Device.ReadDeviceMqttId(v.Sn) client, err := MqttServer.GetMqttClient(mqttId) if err != nil { log.Printf("Error getting MQTT client for SN: %s, %v", v.Sn, err) return } msgBytes, err := json.Marshal(v) if err != nil { log.Printf("Error marshalling JSON for SN: %s, %v", v.Sn, err) client.Disconnect() client.Terminate() return } for i := 0; i < 3; i++ { time.Sleep(time.Second * time.Duration(i+1)) select { case <-ctx.Done(): log.Printf("Context canceled or timeout for SN: %s", v.Sn) client.Disconnect() client.Terminate() return default: } if err := MqttServer.PubMqttMessage(client, fmt.Sprintf("/pub/%s", v.Sn), msgBytes); err != nil { log.Printf("Error publishing MQTT message for SN: %s, %v", v.Sn, err) c.Data["json"] = lib.JSONS{Code: 0, Msg: "设置失败", Data: v.Sn} return } } client.Disconnect() client.Terminate() }(v) } c.Data["json"] = lib.JSONS{Code: 200, Msg: "设置偏差值成功!", Data: nil} c.ServeJSON() return } // 列表 - func (c *DeviceController) DeviceWarning_List_html() { // 验证登录 b_, admin_r := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey")) if !b_ { c.Data["json"] = lib.JSONS{Code: 201, Msg: "User_tokey Err!"} c.ServeJSON() return } c.Data["Admin_r"] = admin_r page, _ := c.GetInt("page") println(page) if page < 1 { page = 1 } c.Data["Admin_r"] = admin_r bindSN := c.GetStrings("bindSN") tpList := c.GetStrings("tpList") T_sn := c.GetString("T_sn") if len(T_sn) != 0 { bindSN = append(bindSN, T_sn) c.Data["T_sn"] = T_sn } Time_start := c.GetString("Time_start") Time_end := c.GetString("Time_end") if len(Time_start) == 0 && len(Time_end) == 0 { Time_start = time.Now().Format("2006-01-02") + " 00:00:00" Time_end = time.Now().Format("2006-01-02") + " 23:59:59" } c.Data["Time_start"] = Time_start c.Data["Time_end"] = Time_end //c.Data["Class_List"] = Device.Read_DeviceWarningList_All_1() //T_Title := "" //if Class_1 > 0 { // T_Title = Device.Read_DeviceWarningList_ById(Class_1).T_name //} pageSize := c.GetString("pageSize", "100") pageSizeInt, _ := strconv.Atoi(pageSize) //atoi, _ := strconv.Atoi(pageSizes.PageSize) getString := c.GetString("t_tp") t_tp, _ := strconv.Atoi(getString) var cnt int64 DeviceWarning_List, cnt := Warning.Read_Warning_List(admin_r.T_pid, bindSN, tpList, Time_start, Time_end, t_tp, page, pageSizeInt) c.Data["List"] = DeviceWarning_List page_size := math.Ceil(float64(cnt) / float64(pageSizeInt)) c.Data["Page"] = page c.Data["Page_size"] = page_size c.Data["Pages"] = lib.Func_page(int64(page), int64(page_size)) c.Data["cnt"] = cnt // 将sync.Map中的数据转存到切片中 c.TplName = "Device/DeviceWarning.html" } // GetWarningtype 获取报警类型 func (c *DeviceController) GetWarningtype() { var results []struct { Key int Value string } Warning.WarningType_list.Range(func(key, value any) bool { // 确保类型断言成功 if k, ok := key.(int); ok { if v, ok := value.(string); ok { // 创建匿名结构体实例并添加到切片 results = append(results, struct { Key int Value string }{Key: k, Value: v}) } else { fmt.Println("Value is not of type string") } } else { fmt.Println("Key is not of type int") } return true // 继续遍历 }) c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!", Data: results} c.ServeJSON() log.Println(results) } func (c *DeviceController) DeviceWarning_() { // 验证登录 //b_, admin_r := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey")) //if !b_ { // c.Data["json"] = lib.JSONS{Code: 201, Msg: "User_tokey Err!"} // c.ServeJSON() // return //} c.Data["WarningType"] = Warning.Read_WarningType_All() c.TplName = "Device/DeviceWarning-.html" } // DeviceWarning_Post 添加报警 func (c *DeviceController) DeviceWarning_Post() { // 验证登录 b_, admin_r := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey")) if !b_ { c.Ctx.Redirect(302, "Login") return } T_tp, _ := c.GetInt("T_tp") T_sn := c.GetString("T_sn") T_id, _ := c.GetInt("T_id") T_Ut := c.GetString("T_Ut") T_Remark := c.GetString("T_Remark") r_Device, err := Device.Read_Device_ByT_sn(T_sn) if err != nil { c.Data["json"] = lib.JSONS{Code: 201, Msg: "E!", Data: "SN 错误!!!"} c.ServeJSON() return } // 获取 传感器 参数 DeviceSensor_r, is := Device.Read_DeviceSensor_ByT_sn(r_Device.T_sn, T_id) if !is { c.Data["json"] = lib.JSONS{Code: 201, Msg: "E!", Data: "编号 错误!!!"} c.ServeJSON() return } t1, _ := time.ParseInLocation("2006-01-02 15:04:05", T_Ut, time.Local) // +8 时差 t_c := Warning.Warning{ T_pid: admin_r.T_pid, T_tp: T_tp, T_sn: T_sn, T_D_name: r_Device.T_devName, T_id: T_id, T_DS_name: DeviceSensor_r.T_name, T_Ut: t1, T_State: 1, T_Remark: T_Remark, } Warning.Add_Warning(t_c) c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!"} c.ServeJSON() return } // DeviceWarning_Del 删除报警 func (c *DeviceController) DeviceWarning_Del() { // 验证登录 b_, admin_r := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey")) if !b_ { c.Ctx.Redirect(302, "Login") return } Id, _ := c.GetInt("Id") if Id > 1000 { Warning.Delete_Warning(admin_r.T_pid, Id) } c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!"} c.ServeJSON() return } // DeviceWarning_DelS 批量删除 func (c *DeviceController) DeviceWarning_DelS() { // 验证登录 b_, admin_r := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey")) if !b_ { c.Ctx.Redirect(302, "Login") return } type SelectedItem struct { Id string `json:"id"` Ut string `json:"ut"` // 假设"ut"字段是时间戳字符串 } type SelectedItems struct { SelectedIds []SelectedItem `json:"selectedIds"` } var SelectedIds SelectedItems //var selectedIds map[string]any err := json.Unmarshal(c.Ctx.Input.RequestBody, &SelectedIds) log.Println(SelectedIds.SelectedIds) for _, v := range SelectedIds.SelectedIds { Warning.Delete_Warning_List(v.Id, v.Ut, admin_r.T_pid) } if err != nil { c.Data["json"] = lib.JSONS{Code: 201, Msg: "E!", Data: "数据格式错误!!!"} c.ServeJSON() } else { c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!"} c.ServeJSON() } } // Device_Copy 复制并添加 func (c *DeviceController) Device_Copy() { // 验证登录 b_, _ := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey")) if !b_ { c.Ctx.Redirect(302, "Login") return } type T_data struct { T_sn string `json:"t_sn"` T_id int `json:"t_id"` T_Rh any `json:"t_rh"` T_Site string `json:"t_site"` T_T any `json:"t_t"` CreateTime string `json:"createTime"` } var data T_data json.Unmarshal(c.Ctx.Input.RequestBody, &data) r := Device.Read_DeviceParameter_SNNo(data.T_sn) parse, _ := time.Parse("2006-01-02 15:04:05", data.CreateTime) data.CreateTime = parse.Add(time.Duration(r[0].T_saveT) * time.Second).Format("2006-01-02 15:04:05") itoa := strconv.Itoa(data.T_id) Device.Copy_DeviceData(data.T_sn, itoa, data.T_Rh, data.T_T, data.T_Site, data.CreateTime) c.Data["json"] = lib.JSONS{Code: 200, Msg: "设置成功", Data: data} c.ServeJSON() } // DeviceWarningUpdate 修改报警 func (c *DeviceController) DeviceWarningUpdate() { // 验证登录 b_, admin_r := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey")) if !b_ { c.Ctx.Redirect(302, "Login") return } var data struct { ColumnName string `json:"columnName"` NewValue string `json:"newValue"` RowId string `json:"rowId"` T_Ut string `json:"T_Ut"` SN string `json:"sn"` } json.Unmarshal(c.Ctx.Input.RequestBody, &data) log.Println(admin_r.T_pid) Warning.Update_DeviceParameter_Warning(data.ColumnName, data.NewValue, data.RowId, data.T_Ut) c.Data["json"] = lib.JSONS{Code: 200, Msg: "设置成功", Data: data} c.ServeJSON() } // GetDeviceALLSN 根据pid获取所有sn func (c *DeviceController) GetDeviceALLSN() { // 验证登录 b_, admin_r := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey")) if !b_ { c.Ctx.Redirect(302, "Login") return } r := Device.Read_Device_All_SN(admin_r.T_pid) log.Println(r) c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!", Data: r} c.ServeJSON() } // GetDeviceALLTID 根据SN获取所有探头 func (c *DeviceController) GetDeviceALLTID() { // 验证登录 b_, _ := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey")) if !b_ { c.Ctx.Redirect(302, "Login") return } getString := c.GetString("sn") r := Device.Get_DeviceSensor_Tid_ByT_sn(getString) c.Data["json"] = lib.JSONS{Code: 200, Msg: "设置成功", Data: r} c.ServeJSON() } // DeviceWarningAdd 复制添加报警 func (c *DeviceController) DeviceWarningAdd() { // 验证登录 b_, admin_r := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey")) if !b_ { c.Ctx.Redirect(302, "Login") return } var data struct { T_tp_name string `json:"column1"` T__d_name string `json:"column2"` T_DS_name string `json:"column3"` T_Remark string `json:"column4"` T_State string `json:"column5"` T_Ut string `json:"column6"` RowId string `json:"rowId"` SN string `json:"sn"` T_id string `json:"t_id"` } json.Unmarshal(c.Ctx.Input.RequestBody, &data) atoi, _ := strconv.Atoi(data.T_id) r_Device, err := Device.Read_Device_ByT_sn(data.SN) if err != nil { c.Data["json"] = lib.JSONS{Code: 201, Msg: "E!", Data: "SN 错误!!!"} c.ServeJSON() return } T_tp := Warning.Read_WarningType(data.T_tp_name) t1, _ := time.ParseInLocation("2006-01-02 15:04:05", data.T_Ut, time.Local) // +8 时差 t_c := Warning.Warning{ T_pid: admin_r.T_pid, T_tp: T_tp, T_sn: data.SN, T_D_name: r_Device.T_devName, T_id: atoi, T_DS_name: data.T_DS_name, T_Ut: t1, T_State: 1, T_Remark: data.T_Remark, } Warning.Add_Warning(t_c) c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!"} c.ServeJSON() return } // SiftWarningType 根据报警类型筛选 func (c *DeviceController) SiftWarningType() { // 验证登录 b_, _ := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey")) if !b_ { c.Ctx.Redirect(302, "Login") return } }