// controllers/用户.go package controllers import ( "Tech/common" "Tech/models" "bytes" "encoding/json" "fmt" "io" "net/http" "time" "github.com/beego/beego/v2/client/orm" beego "github.com/beego/beego/v2/server/web" ) func init() { // // 启动后台协程定期更新电调模型数据 // go func() { // // 初始化延迟1秒执行,避免系统启动时的资源竞争 // time.Sleep(1 * time.Second) // // 定时每5秒获取一次数据 // ticker := time.NewTicker(5 * time.Second) // defer ticker.Stop() // for { // select { // case <-ticker.C: // updateElectricalData() // } // } // }() } // // updateElectricalData 从电调服务获取数据并更新模型 // func updateElectricalData() { // defer func() { // if r := recover(); r != nil { // fmt.Printf("更新电调数据时发生错误: %v\n", r) // } // }() // // 获取 ElectricModelManager 单例实例 // manager := models.GetInstance() // // 获取模型列表副本,避免长时间持有锁 // manager.Mutex.RLock() // modelsCopy := make(map[string]models.EViewMapModel) // for k, v := range manager.Models { // modelsCopy[k] = v // } // manager.Mutex.RUnlock() // // 如果 Models 为空,不进行任何处理 // if len(modelsCopy) == 0 { // return // } // // 遍历已有模型并分别更新 // for _, viewMapModel := range modelsCopy { // if len(viewMapModel.Models) > 0 && time.Since(viewMapModel.LastBatchUpdate) >= 5*time.Second { // // 获取第一个模型作为参考来构建请求参数 // firstModel := viewMapModel.Models[0] // // 从配置获取电调服务地址 // electricalIP, err := beego.AppConfig.String("ElectricalIP") // if err != nil { // fmt.Printf("读取电调服务IP配置失败: %v\n", err) // continue // } // electricalPort, err := beego.AppConfig.Int("ElectricalPort") // if err != nil { // fmt.Printf("读取电调服务端口配置失败: %v\n", err) // continue // } // // 构造电调服务地址 // electricalAddr := fmt.Sprintf("http://%s:%d/ServerCtrl/AllEqpmtList", electricalIP, electricalPort) // // 准备请求数据 // type RequestData struct { // LineID int `json:"lineID"` // StationID int `json:"StationID"` // ViewID int `json:"ViewID"` // } // reqData := RequestData{ // LineID: firstModel.LineID, // // StationID: firstModel.StationID, // // ViewID: firstModel.ViewID, // } // // 将请求数据转换为JSON // reqBody, err := json.Marshal(reqData) // if err != nil { // fmt.Printf("构造请求数据失败: %v\n", err) // continue // } // // 发送POST请求获取数据 // resp, err := http.Post(electricalAddr, "application/json", bytes.NewBuffer(reqBody)) // if err != nil { // fmt.Printf("调用电调服务获取所有设备列表接口失败: %v\n", err) // continue // } // // 读取响应体 // bodyBytes, err := io.ReadAll(resp.Body) // resp.Body.Close() // if err != nil { // fmt.Printf("读取电调服务响应失败: %v\n", err) // continue // } // // 检查响应状态 // if resp.StatusCode != http.StatusOK { // fmt.Printf("电调服务返回异常状态码: %d,响应内容: %s\n", resp.StatusCode, string(bodyBytes)) // continue // } // // 解析JSON响应 // var result map[string]interface{} // if err := json.Unmarshal(bodyBytes, &result); err != nil { // fmt.Printf("解析电调服务响应失败: %v\n", err) // continue // } // // 检查是否有data字段 // if data, exists := result["data"]; exists { // // 解析data中的设备列表并更新到模型管理器 // var equipments []models.DiandiaoModel // if equipBytes, err := json.Marshal(data); err == nil { // if err := json.Unmarshal(equipBytes, &equipments); err == nil { // // 更新总包设备数据 (在更新时加锁) // manager.UpdateBatchData(equipments) // fmt.Printf("成功更新线路%d的电调模型数据\n", firstModel.LineID) // } else { // fmt.Printf("解析设备列表失败: %v\n", err) // } // } // } // } // } // } type EDispatchController struct { beego.Controller } // /courserun/eqpmtstatus 更新电调设备状态 func (c *EDispatchController) Eqpmtvalue() { var req models.DiandiaoModel requestBody := c.Ctx.Input.RequestBody println("Request Body:", string(requestBody)) if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil { c.Ctx.Output.SetStatus(400) c.Data["json"] = map[string]interface{}{ "code": 400, "msg": "请求参数格式错误: " + err.Error(), } c.ServeJSON() return } // 获取 ElectricModelManager 单例实例 manager := models.GetInstance() // 更新单个设备数据 manager.UpdateSingleDevice(req) c.Data["json"] = map[string]interface{}{ "code": 200, "msg": "更新电调设备状态", } c.ServeJSON() } // /操作日志req type Addctrllog_req struct { CtrlType int `json:"CtrlType"` CtrlSubType int `json:"CtrlSubType"` CtrlFrom int `json:"CtrlFrom"` CtrlUser string `json:"CtrlUser"` Param1 string `json:"Param1"` Param2 string `json:"Param2"` Param3 string `json:"Param3"` Param4 string `json:"Param4"` Param5 string `json:"Param5"` } // 自动评价数据结构体 type AutoEvaData struct { RunLogID int `orm:"column(运行记录编号)" json:"runLogID"` SeqNo int `orm:"column(序号)" json:"seqNo"` EvaName string `orm:"column(评价名称)" json:"evaName"` CourseID int `orm:"column(课程ID)" json:"courseID"` IsOperated int `orm:"column(是否操作)" json:"isOperated"` NodeID int `orm:"column(节点ID)" json:"nodeID"` EvaType int `orm:"column(评价类型)" json:"evaType"` TextParam1 string `orm:"column(文本参数1)" json:"textParam1"` TextParam2 string `orm:"column(文本参数2)" json:"textParam2"` TextParam3 string `orm:"column(文本参数3)" json:"textParam3"` TextParam4 string `orm:"column(文本参数4)" json:"textParam4"` TextParam5 string `orm:"column(文本参数5)" json:"textParam5"` } // 评价结果结构体 type EvaResult struct { Code int `json:"code"` // 状态码:200-成功,400-失败 Message string `json:"message"` // 描述信息 EvaName string `json:"evaName"` // 评价名称 IsOperated int `json:"isOperated"` // 是否操作:0-未操作,1-已操作 OperScore float64 `json:"operScore"` // 操作得分 CourseScore float64 `json:"courseScore"` // 课程总分 SeqNo int `json:"seqNo"` // 序号 } // /实现自动评价 func (c *EDispatchController) DoAutoEva(req Addctrllog_req) EvaResult { // 获取数据库连接 o := orm.NewOrm() // 查找当前正在运行的课程 var runningCourse models.CourseRunLog err := o.QueryTable(new(models.CourseRunLog)). Filter("CourseTime", 0). OrderBy("-RunLogID"). One(&runningCourse) if err != nil { // 如果没有找到正在运行的课程,返回错误结果 return EvaResult{ Code: 400, Message: "没有找到正在运行的课程", } } // 使用自定义SQL查询获取自动评价所需数据 var autoEvaData []AutoEvaData sql := `SELECT a.运行记录编号, a.序号, a.评价名称, b.课程ID, a.是否操作, b.节点ID, a.评价类型, b.文本参数1, b.文本参数2, b.文本参数3, b.文本参数4, b.文本参数5 FROM CourseEvaLog a JOIN CourseOperationNode b ON a.评价映射ID = b.节点ID WHERE a.运行记录编号 = ? AND a.评价类型 = 1 ORDER BY a.序号` _, err = o.Raw(sql, runningCourse.RunLogID).QueryRows(&autoEvaData) if err != nil { return EvaResult{ Code: 400, Message: "查询评价数据失败: " + err.Error(), } } // 如果没有评价数据,返回提示信息 if len(autoEvaData) == 0 { return EvaResult{ Code: 200, Message: "当前课程没有评价数据", CourseScore: runningCourse.CourseScore, } } // 查找第一个未操作的记录 var foundEvaData *AutoEvaData var firstSeqNo int = -1 for _, evaData := range autoEvaData { if evaData.IsOperated == 0 { if firstSeqNo == -1 { firstSeqNo = evaData.SeqNo } // 检查当前操作的序号是否是第一个未操作的序号 if evaData.SeqNo == firstSeqNo { foundEvaData = &evaData break } } } // 如果没有找到未操作的记录,返回已完成提示 if foundEvaData == nil { return EvaResult{ Code: 200, Message: "所有评价项已完成", CourseScore: runningCourse.CourseScore, } } // 检查参数1和参数2是否为空 if req.Param1 == "" || req.Param2 == "" { return EvaResult{ Code: 400, Message: "操作参数不能为空", EvaName: foundEvaData.EvaName, IsOperated: 0, OperScore: 0, CourseScore: runningCourse.CourseScore, SeqNo: foundEvaData.SeqNo, } } // 比较参数1和参数2 if req.Param1 == foundEvaData.TextParam1 && req.Param2 == foundEvaData.TextParam2 { // 参数匹配,需要更新对应的CourseEvaLog记录 var evaLog models.CourseEvaLog err = o.QueryTable(new(models.CourseEvaLog)). Filter("RunLogID", foundEvaData.RunLogID). Filter("SeqNo", foundEvaData.SeqNo). One(&evaLog) if err != nil { return EvaResult{ Code: 400, Message: "查询评价记录失败: " + err.Error(), } } // 计算操作时间 operTime := 0 // 只有在课程未结束时才计算操作时间(暂停标记为-1表示课程结束) if runningCourse.PauseFlag != -1 { // 解析课程开始时间 startTime, err := time.ParseInLocation("2006-01-02 15:04:05", runningCourse.RunDateTime, time.Local) if err != nil { return EvaResult{ Code: 400, Message: "解析课程开始时间失败: " + err.Error(), } } operTime = int(time.Since(startTime).Seconds()) - runningCourse.PauseTotalTime // 确保操作时间不为负数 if operTime < 0 { operTime = 0 } } // 计算操作得分 operScore := 0.0 // 已操作,得分为评价赋分-评价失分 operScore = float64(evaLog.EvaScore - evaLog.EvaDeduction) // 更新CourseEvaLog表中的是否操作字段、操作得分和操作时间 _, err = o.Raw(` UPDATE CourseEvaLog SET 是否操作 = ?, 操作得分 = ?, 操作时间 = ? WHERE 运行记录编号 = ? AND 序号 = ? `, 1, operScore, operTime, foundEvaData.RunLogID, foundEvaData.SeqNo).Exec() if err != nil { return EvaResult{ Code: 400, Message: "更新节点操作状态失败: " + err.Error(), } } // 重新计算整个课程的总得分 var totalScore float64 err = o.Raw(` SELECT COALESCE(SUM(操作得分), 0) FROM CourseEvaLog WHERE 运行记录编号 = ? `, foundEvaData.RunLogID).QueryRow(&totalScore) if err != nil { return EvaResult{ Code: 400, Message: "计算总得分失败: " + err.Error(), } } // 更新课程运行日志中的总得分 _, err = o.Raw(` UPDATE CourseRunLog SET 课程得分 = ? WHERE 运行记录编号 = ? `, totalScore, foundEvaData.RunLogID).Exec() if err != nil { return EvaResult{ Code: 400, Message: "更新总得分失败: " + err.Error(), } } // 创建通知数据 notificationData := map[string]interface{}{ "type": "evaluation_update", "runLogID": foundEvaData.RunLogID, "seqNo": foundEvaData.SeqNo, "evaName": foundEvaData.EvaName, "isOperated": 1, "operScore": operScore, "courseScore": totalScore, "timestamp": time.Now().Format("2006-01-02 15:04:05"), } // 通过SSE广播评价更新消息 common.GlobalSSEManager.BroadcastMessage("evaluation_update", notificationData) // 返回成功结果 return EvaResult{ Code: 200, Message: "评价成功", EvaName: foundEvaData.EvaName, IsOperated: 1, OperScore: operScore, CourseScore: totalScore, SeqNo: foundEvaData.SeqNo, } } else { // 参数不匹配 return EvaResult{ Code: 400, Message: "操作参数不匹配", EvaName: foundEvaData.EvaName, IsOperated: 0, OperScore: 0, CourseScore: runningCourse.CourseScore, SeqNo: foundEvaData.SeqNo, } } } // /courserun/add_ctrl_log 添加电调控制日志 func (c *EDispatchController) Addctrllog() { var req Addctrllog_req requestBody := c.Ctx.Input.RequestBody println("Request Body:", string(requestBody)) if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil { c.Ctx.Output.SetStatus(400) c.Data["json"] = map[string]interface{}{ "code": 400, "msg": "请求参数格式错误: " + err.Error(), } c.ServeJSON() return } // 调用自动评价函数并获取评价结果 evaResult := c.DoAutoEva(req) // 获取数据库连接 o := orm.NewOrm() // 查找当前正在运行的课程 var runningCourse models.CourseRunLog err := o.QueryTable(new(models.CourseRunLog)). Filter("CourseTime", 0). OrderBy("-RunLogID"). One(&runningCourse) if err != nil { c.Ctx.Output.SetStatus(400) c.Data["json"] = map[string]interface{}{ "code": 400, "msg": "查找当前运行课程失败: " + err.Error(), } c.ServeJSON() return } // 查找当前运行课程中最大的RunOperID var maxOperLog models.CourseOperLog var runOperID int err = o.QueryTable(new(models.CourseOperLog)). Filter("RunLogID", runningCourse.RunLogID). OrderBy("-RunOperID"). One(&maxOperLog) if err != nil && err != orm.ErrNoRows { c.Ctx.Output.SetStatus(500) c.Data["json"] = map[string]interface{}{ "code": 500, "msg": "查询操作日志失败: " + err.Error(), } c.ServeJSON() return } if err == orm.ErrNoRows { // 如果没有找到记录,则从1开始 runOperID = 1 } else { // 找到记录,则取最大值加1 runOperID = maxOperLog.RunOperID + 1 } runDateTime, err := time.ParseInLocation("2006-01-02 15:04:05", runningCourse.RunDateTime, time.Local) if err != nil { c.Data["json"] = map[string]interface{}{ "code": 500, "msg": "解析课程开始时间失败: " + err.Error(), "runStatus": 0, "data": nil, } c.ServeJSON() return } var curTemplateID = 0 // 根据req.CtrlType和req.CtrlSubType查询TemplateOperation表获取模板ID var templateOp models.TemplateOperation err = o.QueryTable(new(models.TemplateOperation)). Filter("Category", req.CtrlType). Filter("SubCategory", req.CtrlSubType). One(&templateOp) if err == nil { curTemplateID = templateOp.TemplateID } else { // 如果没有找到模板操作记录,则使用默认模板ID curTemplateID = 0 } // 计算从课程开始到现在的秒数,减去暂停累计时间 operTime := int(time.Since(runDateTime).Seconds()) - runningCourse.PauseTotalTime // 创建操作日志记录 operLog := models.CourseOperLog{ RunLogID: runningCourse.RunLogID, RunCourseID: runningCourse.RunCourseID, RunOperID: runOperID, TemplateID: curTemplateID, OperName: req.CtrlUser, OperTime: operTime, OperScore: 0, // 默认分数为0 OperParam1: req.Param1, OperParam2: req.Param2, OperParam3: req.Param3, OperParam4: req.Param4, OperParam5: req.Param5, } // 插入操作日志记录到数据库 _, err = o.Insert(&operLog) if err != nil { c.Ctx.Output.SetStatus(500) c.Data["json"] = map[string]interface{}{ "code": 500, "msg": "插入操作日志失败: " + err.Error(), } c.ServeJSON() return } // 返回包含评价结果的信息 c.Data["json"] = map[string]interface{}{ "code": evaResult.Code, "msg": "添加操作日志成功", "evaMessage": evaResult.Message, "evaName": evaResult.EvaName, "isOperated": evaResult.IsOperated, "operScore": evaResult.OperScore, "courseScore": evaResult.CourseScore, "seqNo": evaResult.SeqNo, } c.ServeJSON() } // /serverctrl/subsysstatus 获取电调设备状态 func (c *EDispatchController) SubSysStatus() { // 从配置文件读取电调服务IP和端口 electricalIP, err := beego.AppConfig.String("ElectricalIP") if err != nil { c.Data["json"] = map[string]interface{}{ "code": 500, "msg": "读取电调服务IP配置失败: " + err.Error(), } c.ServeJSON() return } electricalPort, err := beego.AppConfig.Int("ElectricalPort") if err != nil { c.Data["json"] = map[string]interface{}{ "code": 500, "msg": "读取电调服务端口配置失败: " + err.Error(), } c.ServeJSON() return } // 构造电调服务地址 electricalAddr := fmt.Sprintf("http://%s:%d/ServerCtrl/SubSysStatus", electricalIP, electricalPort) // 构造请求体,使用空的JSON对象 reqBody := "{}" // 创建带适当头部的请求 req, err := http.NewRequest("POST", electricalAddr, bytes.NewBufferString(reqBody)) if err != nil { c.Data["json"] = map[string]interface{}{ "code": 500, "msg": "创建请求失败: " + err.Error(), } c.ServeJSON() return } // 设置Content-Type头部 req.Header.Set("Content-Type", "application/json") // 创建HTTP客户端并发送请求 client := &http.Client{} resp, err := client.Do(req) if err != nil { c.Data["json"] = map[string]interface{}{ "code": 500, "msg": "调用电调服务获取子系统状态接口失败: " + err.Error(), } c.ServeJSON() return } defer resp.Body.Close() // 检查响应状态 if resp.StatusCode != http.StatusOK { bodyBytes, _ := io.ReadAll(resp.Body) c.Data["json"] = map[string]interface{}{ "code": 500, "msg": fmt.Sprintf("电调服务返回异常状态码: %d,响应内容: %s", resp.StatusCode, string(bodyBytes)), } c.ServeJSON() return } // 读取并解析响应体 bodyBytes, err := io.ReadAll(resp.Body) if err != nil { c.Data["json"] = map[string]interface{}{ "code": 500, "msg": "读取电调服务响应失败: " + err.Error(), } c.ServeJSON() return } // 尝试解析电调服务返回的JSON var result map[string]interface{} if err := json.Unmarshal(bodyBytes, &result); err != nil { // 如果解析失败,返回原始内容 c.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8") c.Ctx.Output.Body(bodyBytes) return } // 如果解析成功,直接返回JSON结果 c.Data["json"] = result c.ServeJSON() } func (c *EDispatchController) UpdateTestStatus() { } // /serverCtrl/alleqpmtlist 获取所有设备列表 func (c *EDispatchController) AllEqpmtList() { // 转换缓存数据为指定格式 type EquipmentData struct { DataID string `json:"dataId"` DataName string `json:"dataName"` Value string `json:"value"` ID string `json:"id"` EqpmtTypeID int `json:"eqpmtTypeID"` } // 从配置文件读取电调服务IP和端口 electricalIP, err := beego.AppConfig.String("ElectricalIP") if err != nil { c.Data["json"] = map[string]interface{}{ "code": 500, "msg": "读取电调服务IP配置失败: " + err.Error(), } c.ServeJSON() return } electricalPort, err := beego.AppConfig.Int("ElectricalPort") if err != nil { c.Data["json"] = map[string]interface{}{ "code": 500, "msg": "读取电调服务端口配置失败: " + err.Error(), } c.ServeJSON() return } // 获取全量数据更新间隔配置,默认10秒 fullDataIntervalSeconds := 10 if interval, err := beego.AppConfig.Int("EGetAllDataInterval"); err == nil { fullDataIntervalSeconds = interval } // 构造电调服务地址 electricalAddr := fmt.Sprintf("http://%s:%d/ServerCtrl/AllEqpmtList", electricalIP, electricalPort) // 获取最新的课程运行记录以获取线路号 o := orm.NewOrm() var latestCourse models.CourseRunLog err = o.QueryTable(new(models.CourseRunLog)). OrderBy("-RunLogID"). One(&latestCourse) if err != nil && err != orm.ErrNoRows { c.Data["json"] = map[string]interface{}{ "code": 500, "msg": "查询最新课程运行记录失败: " + err.Error(), } c.ServeJSON() return } // 如果没有找到运行记录,默认线路号为0 lineID := 0 if err != orm.ErrNoRows { // 根据运行课程ID查询课程信息以获取线路号 var courseInfo models.CourseInfo err = o.QueryTable(new(models.CourseInfo)). Filter("CourseID", latestCourse.RunCourseID). One(&courseInfo) if err != nil && err != orm.ErrNoRows { c.Data["json"] = map[string]interface{}{ "code": 500, "msg": "查询课程信息失败: " + err.Error(), } c.ServeJSON() return } if err != orm.ErrNoRows { lineID = courseInfo.LineNo } } // 使用客户端IP作为客户端标识 clientID := c.Ctx.Input.IP() // 获取 ElectricModelManager 单例实例 manager := models.GetInstance() // 注册客户端 manager.RegisterClient(clientID) // 注意:不再在函数退出时注销客户端,而是由 ElectricModelManager 内部定期清理长时间未访问的客户端 // 检查是否应该发送全量数据 shouldSendFullData := manager.ShouldSendFullData(fullDataIntervalSeconds) // 准备请求数据 type RequestData struct { LineID int `json:"lineID"` StationID int `json:"StationID"` ViewID int `json:"ViewID"` } reqData := RequestData{ LineID: lineID, StationID: 0, ViewID: 0, } // 将请求数据转换为JSON reqBody, err := json.Marshal(reqData) if err != nil { c.Data["json"] = map[string]interface{}{ "code": 500, "msg": "构造请求数据失败: " + err.Error(), } c.ServeJSON() return } // 调用电调服务获取所有设备列表接口,使用POST方法 resp, err := http.Post(electricalAddr, "application/json", bytes.NewBuffer(reqBody)) if err != nil { c.Data["json"] = map[string]interface{}{ "code": 500, "msg": "调用电调服务获取所有设备列表接口失败: " + err.Error(), } c.ServeJSON() return } defer resp.Body.Close() // 检查响应状态 if resp.StatusCode != http.StatusOK { bodyBytes, _ := io.ReadAll(resp.Body) c.Data["json"] = map[string]interface{}{ "code": 500, "msg": fmt.Sprintf("电调服务返回异常状态码: %d,响应内容: %s", resp.StatusCode, string(bodyBytes)), } c.ServeJSON() return } // 读取并解析响应体 bodyBytes, err := io.ReadAll(resp.Body) if err != nil { c.Data["json"] = map[string]interface{}{ "code": 500, "msg": "读取电调服务响应失败: " + err.Error(), } c.ServeJSON() return } // 尝试解析JSON响应 var result map[string]interface{} if err := json.Unmarshal(bodyBytes, &result); err != nil { // 如果不是JSON格式,作为字符串返回 c.Data["json"] = map[string]interface{}{ "code": 200, "msg": "获取所有设备列表失败", "data": string(bodyBytes), } } else { // 如果是JSON格式,检查是否有data字段 if data, exists := result["data"]; exists { // 解析data中的设备列表并更新到模型管理器 var equipments []models.DiandiaoModel if equipBytes, err := json.Marshal(data); err == nil { if err := json.Unmarshal(equipBytes, &equipments); err == nil { // 更新总包设备数据 manager.UpdateBatchData(equipments) } } // 构建当前设备数据映射 currentDataMapping := make(map[string]string) var equipmentsData []EquipmentData // isFirst := true for _, model := range equipments { equip := EquipmentData{ DataID: model.EqpmtStrID, ID: model.EqpmtStrID, DataName: model.EqpmtStdName, EqpmtTypeID: model.EqpmtTypeID, } if model.CMDType == 0 { //设备状态 equip.Value = fmt.Sprintf("%d", model.EqpmtStatus) } else if model.CMDType == 1 { //设备数据控制 equip.Value = fmt.Sprintf("%d", model.FValue) } // if isFirst { // // 生成0到100之间的随机整数 // equip.Value = fmt.Sprintf("%d", rand.Intn(101)) // isFirst = false // } // 添加到当前数据映射 currentDataMapping[model.EqpmtStrID] = equip.Value equipmentsData = append(equipmentsData, equip) } // 如果应该发送全量数据 if shouldSendFullData { c.Data["json"] = equipmentsData manager.UpdateFullDataTimestamp() manager.UpdateClientData(clientID, currentDataMapping) } else { // 否则只返回变化的数据 changedData := manager.CompareWithClientData(clientID, currentDataMapping) // 构建变化的设备数据列表 var changedEquipmentsData []EquipmentData for _, equip := range equipmentsData { if _, changed := changedData[equip.ID]; changed { changedEquipmentsData = append(changedEquipmentsData, equip) } } // 确保不会返回nil,即使没有变化也返回空数组 if changedEquipmentsData == nil { changedEquipmentsData = []EquipmentData{} } c.Data["json"] = changedEquipmentsData // 更新客户端数据记录 manager.UpdateClientData(clientID, currentDataMapping) } } else { // 如果没有data字段,返回整个响应 c.Data["json"] = map[string]interface{}{ "code": 500, "msg": "获取所有设备列表失败", } } } c.ServeJSON() } // // /serverCtrl/alleqpmtlist2 获取所有设备列表 测试使用 // func (c *EDispatchController) AllEqpmtList2() { // // 转换缓存数据为指定格式 // type EquipmentData struct { // DataID string `json:"dataId"` // DataName string `json:"dataName"` // Value string `json:"value"` // ID string `json:"id"` // } // // 从配置文件读取电调服务IP和端口 // electricalIP, err := beego.AppConfig.String("ElectricalIP") // if err != nil { // c.Data["json"] = map[string]interface{}{ // "code": 500, // "msg": "读取电调服务IP配置失败: " + err.Error(), // } // c.ServeJSON() // return // } // electricalPort, err := beego.AppConfig.Int("ElectricalPort") // if err != nil { // c.Data["json"] = map[string]interface{}{ // "code": 500, // "msg": "读取电调服务端口配置失败: " + err.Error(), // } // c.ServeJSON() // return // } // // 构造电调服务地址 // electricalAddr := fmt.Sprintf("http://%s:%d/ServerCtrl/AllEqpmtList", electricalIP, electricalPort) // // 获取最新的课程运行记录以获取线路号 // o := orm.NewOrm() // var latestCourse models.CourseRunLog // err = o.QueryTable(new(models.CourseRunLog)). // OrderBy("-RunLogID"). // One(&latestCourse) // if err != nil && err != orm.ErrNoRows { // c.Data["json"] = map[string]interface{}{ // "code": 500, // "msg": "查询最新课程运行记录失败: " + err.Error(), // } // c.ServeJSON() // return // } // // 如果没有找到运行记录,默认线路号为0 // lineID := 0 // if err != orm.ErrNoRows { // // 根据运行课程ID查询课程信息以获取线路号 // var courseInfo models.CourseInfo // err = o.QueryTable(new(models.CourseInfo)). // Filter("CourseID", latestCourse.RunCourseID). // One(&courseInfo) // if err != nil && err != orm.ErrNoRows { // c.Data["json"] = map[string]interface{}{ // "code": 500, // "msg": "查询课程信息失败: " + err.Error(), // } // c.ServeJSON() // return // } // if err != orm.ErrNoRows { // lineID = courseInfo.LineNo // } // } // // 生成请求key // model := models.DiandiaoModel{ // LineID: lineID, // } // key := model.GenerateModelKey() // // 获取 ElectricModelManager 单例实例 // manager := models.GetInstance() // // 检查缓存中是否存在对应key的数据,且最后更新时间在5秒内 // if viewMapModel, exists := manager.GetModelByKey(key); exists { // // 检查最后总包更新时间是否在5秒内 // if time.Since(viewMapModel.LastBatchUpdate) <= 5*time.Second || time.Since(viewMapModel.LastDeviceUpdate) <= 5*time.Second { // var equipmentsData []EquipmentData // for _, model := range viewMapModel.Models { // equip := EquipmentData{ // DataID: model.EqpmtStrID, // ID: model.EqpmtStrID, // DataName: model.EqpmtStdName, // } // switch model.CMDType { // case 0: //设备状态 // equip.Value = fmt.Sprintf("%d", model.EqpmtStatus) // case 1: //设备数据控制 // equip.Value = fmt.Sprintf("%d", model.FValue) // } // equipmentsData = append(equipmentsData, equip) // } // c.Data["json"] = equipmentsData // // 使用缓存数据 // // c.Data["json"] = map[string]interface{}{ // // "code": 200, // // "msg": "获取所有设备列表成功(缓存)", // // "data": equipmentsData, // // } // c.ServeJSON() // return // } // } // // 准备请求数据 // type RequestData struct { // LineID int `json:"lineID"` // StationID int `json:"StationID"` // ViewID int `json:"ViewID"` // } // reqData := RequestData{ // LineID: lineID, // StationID: 0, // ViewID: 0, // } // // 将请求数据转换为JSON // reqBody, err := json.Marshal(reqData) // if err != nil { // c.Data["json"] = map[string]interface{}{ // "code": 500, // "msg": "构造请求数据失败: " + err.Error(), // } // c.ServeJSON() // return // } // // 调用电调服务获取所有设备列表接口,使用POST方法 // resp, err := http.Post(electricalAddr, "application/json", bytes.NewBuffer(reqBody)) // if err != nil { // c.Data["json"] = map[string]interface{}{ // "code": 500, // "msg": "调用电调服务获取所有设备列表接口失败: " + err.Error(), // } // c.ServeJSON() // return // } // defer resp.Body.Close() // // 检查响应状态 // if resp.StatusCode != http.StatusOK { // bodyBytes, _ := io.ReadAll(resp.Body) // c.Data["json"] = map[string]interface{}{ // "code": 500, // "msg": fmt.Sprintf("电调服务返回异常状态码: %d,响应内容: %s", resp.StatusCode, string(bodyBytes)), // } // c.ServeJSON() // return // } // // 读取并解析响应体 // bodyBytes, err := io.ReadAll(resp.Body) // if err != nil { // c.Data["json"] = map[string]interface{}{ // "code": 500, // "msg": "读取电调服务响应失败: " + err.Error(), // } // c.ServeJSON() // return // } // // 尝试解析JSON响应 // var result map[string]interface{} // if err := json.Unmarshal(bodyBytes, &result); err != nil { // // 如果不是JSON格式,作为字符串返回 // c.Data["json"] = map[string]interface{}{ // "code": 200, // "msg": "获取所有设备列表成功", // "data": string(bodyBytes), // } // } else { // // 如果是JSON格式,检查是否有data字段 // if data, exists := result["data"]; exists { // // 解析data中的设备列表并更新到模型管理器 // var equipments []models.DiandiaoModel // if equipBytes, err := json.Marshal(data); err == nil { // if err := json.Unmarshal(equipBytes, &equipments); err == nil { // // 更新总包设备数据 // manager.UpdateBatchData(equipments) // } // } // var equipmentsData []EquipmentData // for _, model := range equipments { // equip := EquipmentData{ // DataID: model.EqpmtStrID, // ID: model.EqpmtStrID, // DataName: model.EqpmtStdName, // } // if model.CMDType == 0 { //设备状态 // equip.Value = fmt.Sprintf("%d", model.EqpmtStatus) // } else if model.CMDType == 1 { //设备数据控制 // equip.Value = fmt.Sprintf("%d", model.FValue) // } // equipmentsData = append(equipmentsData, equip) // } // c.Data["json"] = equipmentsData // // // 返回响应 // // c.Data["json"] = map[string]interface{}{ // // "code": 200, // // "msg": "获取所有设备列表成功", // // "data": equipmentsData, // // } // } else { // // 如果没有data字段,返回整个响应 // c.Data["json"] = map[string]interface{}{ // "code": 500, // "msg": "获取所有设备列表失败", // } // } // } // c.ServeJSON() // } // /serverctrl/seteqpmtoper 设置电调设备操作 func (c *EDispatchController) Seteqpmtoper() { // 定义接收的请求数据结构 var req struct { EqpmtStrID string `json:"EqpmtStrID"` LineID int `json:"LineID"` CMDType int `json:"CMDType"` EqpmtStatus int `json:"EqpmtStatus"` FValue int `json:"fValue"` } // 解析请求体中的JSON数据 if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil { c.Ctx.Output.SetStatus(400) c.Data["json"] = map[string]interface{}{ "code": 400, "msg": "请求参数格式错误: " + err.Error(), } c.ServeJSON() return } // 如果LineID为0,则尝试获取最近一次运行课程的线路ID lineID := req.LineID if lineID == 0 { o := orm.NewOrm() var lastCourse models.CourseRunLog // 查询最后运行的课程 err := o.QueryTable(new(models.CourseRunLog)). OrderBy("-RunLogID"). One(&lastCourse) if err == nil { // 找到最后一门课程,查询其对应的课程信息以获取线路号 var courseInfo models.CourseInfo err = o.QueryTable(new(models.CourseInfo)). Filter("CourseID", lastCourse.RunCourseID). One(&courseInfo) if err == nil { lineID = courseInfo.LineNo } else { // 查询失败,使用默认值 lineID = 555 } } else { // 没有找到历史课程,使用默认值 lineID = 555 } } // 构造转发给电调服务器的请求数据 forwardReq := struct { EqpmtStrID string `json:"EqpmtStrID"` LineID int `json:"LineID"` EqpmtStdName string `json:"EqpmtStdName"` CMDType int `json:"CMDType"` EqpmtStatus int `json:"EqpmtStatus"` CtrlType int `json:"CtrlType"` OpeMark int `json:"OpeMark"` FValue int `json:"fValue"` NValueType int `json:"nValueType"` IsReset int `json:"IsReset"` }{ EqpmtStrID: req.EqpmtStrID, LineID: lineID, EqpmtStdName: "", // 默认空值 CMDType: req.CMDType, EqpmtStatus: req.EqpmtStatus, CtrlType: 1, // 默认值 OpeMark: 0, // 默认值 FValue: req.FValue, NValueType: 0, // 默认值 IsReset: 0, // 默认值 } // 将构造好的请求数据序列化为JSON forwardReqBody, err := json.Marshal(forwardReq) if err != nil { c.Data["json"] = map[string]interface{}{ "code": 500, "msg": "构造转发请求数据失败: " + err.Error(), } c.ServeJSON() return } // 从配置文件读取电调服务IP和端口 electricalIP, err := beego.AppConfig.String("ElectricalIP") if err != nil { c.Data["json"] = map[string]interface{}{ "code": 500, "msg": "读取电调服务IP配置失败: " + err.Error(), } c.ServeJSON() return } electricalPort, err := beego.AppConfig.Int("ElectricalPort") if err != nil { c.Data["json"] = map[string]interface{}{ "code": 500, "msg": "读取电调服务端口配置失败: " + err.Error(), } c.ServeJSON() return } // 构造电调服务地址 electricalAddr := fmt.Sprintf("http://%s:%d/ServerCtrl/SetEqpmtOper", electricalIP, electricalPort) // 将请求数据转发到电调服务器 resp, err := http.Post(electricalAddr, "application/json", bytes.NewBuffer(forwardReqBody)) if err != nil { c.Data["json"] = map[string]interface{}{ "code": 500, "msg": "转发请求到电调服务器失败: " + err.Error(), } c.ServeJSON() return } defer resp.Body.Close() fmt.Println("Seteqpmtoper 发送 JSON:", string(forwardReqBody)) // 读取响应体以便打印,然后将其重新放回供后续处理 respBodyBytes, err := io.ReadAll(resp.Body) if err != nil { fmt.Printf("Seteqpmtoper: 读取响应用于打印失败: %v\n", err) } else { fmt.Println("Seteqpmtoper 接收 JSON:", string(respBodyBytes)) // 由于后续代码还会读取 resp.Body,这里把数据重新放回 resp.Body = io.NopCloser(bytes.NewBuffer(respBodyBytes)) } // 读取响应体 bodyBytes, err := io.ReadAll(resp.Body) if err != nil { c.Data["json"] = map[string]interface{}{ "code": 500, "msg": "读取电调服务响应失败: " + err.Error(), } c.ServeJSON() return } // 检查响应状态 if resp.StatusCode != http.StatusOK { c.Data["json"] = map[string]interface{}{ "code": resp.StatusCode, "msg": fmt.Sprintf("电调服务返回异常状态码: %d,响应内容: %s", resp.StatusCode, string(bodyBytes)), } c.ServeJSON() return } // 尝试解析响应为JSON var result map[string]interface{} if err := json.Unmarshal(bodyBytes, &result); err != nil { // 如果不是JSON格式,原样返回 c.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8") c.Ctx.Output.Body(bodyBytes) return } // 返回电调服务器的响应 c.Data["json"] = result c.ServeJSON() } // /serverctrl/seteqpmtfault 设置设备故障 func (c *EDispatchController) Seteqpmtfault() { // 定义接收的请求数据结构 var req struct { EqpmtStrID string `json:"EqpmtStrID"` LineID int `json:"LineID"` EventType int `json:"EventType"` EventId int `json:"EventId"` } // 解析请求体中的JSON数据 if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil { c.Ctx.Output.SetStatus(400) c.Data["json"] = map[string]interface{}{ "code": 400, "msg": "请求参数格式错误: " + err.Error(), } c.ServeJSON() return } // 如果LineID为0,则尝试获取最近一次运行课程的线路ID lineID := req.LineID if lineID == 0 { o := orm.NewOrm() var lastCourse models.CourseRunLog // 查询最后运行的课程 err := o.QueryTable(new(models.CourseRunLog)). OrderBy("-RunLogID"). One(&lastCourse) if err == nil { // 找到最后一门课程,查询其对应的课程信息以获取线路号 var courseInfo models.CourseInfo err = o.QueryTable(new(models.CourseInfo)). Filter("CourseID", lastCourse.RunCourseID). One(&courseInfo) if err == nil { lineID = courseInfo.LineNo } else { // 查询失败,使用默认值 lineID = 555 } } else { // 没有找到历史课程,使用默认值 lineID = 555 } } // 构造转发给电调服务器的请求数据 forwardReq := struct { EqpmtStrID string `json:"EqpmtStrID"` LineID int `json:"LineID"` EventType int `json:"EventType"` EventId int `json:"EventId"` }{ EqpmtStrID: req.EqpmtStrID, LineID: lineID, EventType: req.EventType, EventId: req.EventId, } // 将构造好的请求数据序列化为JSON forwardReqBody, err := json.Marshal(forwardReq) if err != nil { c.Data["json"] = map[string]interface{}{ "code": 500, "msg": "构造转发请求数据失败: " + err.Error(), } c.ServeJSON() return } // 从配置文件读取电调服务IP和端口 electricalIP, err := beego.AppConfig.String("ElectricalIP") if err != nil { c.Data["json"] = map[string]interface{}{ "code": 500, "msg": "读取电调服务IP配置失败: " + err.Error(), } c.ServeJSON() return } electricalPort, err := beego.AppConfig.Int("ElectricalPort") if err != nil { c.Data["json"] = map[string]interface{}{ "code": 500, "msg": "读取电调服务端口配置失败: " + err.Error(), } c.ServeJSON() return } // 构造电调服务地址 electricalAddr := fmt.Sprintf("http://%s:%d/ServerCtrl/SetEqpmtFault", electricalIP, electricalPort) // 将请求数据转发到电调服务器 resp, err := http.Post(electricalAddr, "application/json", bytes.NewBuffer(forwardReqBody)) if err != nil { c.Data["json"] = map[string]interface{}{ "code": 500, "msg": "转发请求到电调服务器失败: " + err.Error(), } c.ServeJSON() return } defer resp.Body.Close() // 读取响应体 bodyBytes, err := io.ReadAll(resp.Body) if err != nil { c.Data["json"] = map[string]interface{}{ "code": 500, "msg": "读取电调服务响应失败: " + err.Error(), } c.ServeJSON() return } // 检查响应状态 if resp.StatusCode != http.StatusOK { c.Data["json"] = map[string]interface{}{ "code": resp.StatusCode, "msg": fmt.Sprintf("电调服务返回异常状态码: %d,响应内容: %s", resp.StatusCode, string(bodyBytes)), } c.ServeJSON() return } // 尝试解析响应为JSON var result map[string]interface{} if err := json.Unmarshal(bodyBytes, &result); err != nil { // 如果不是JSON格式,原样返回 c.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8") c.Ctx.Output.Body(bodyBytes) return } // 返回电调服务器的响应 c.Data["json"] = result c.ServeJSON() } // /serverctrl/geteqpmtfault 获取设备故障 func (c *EDispatchController) GetEqpmtFault() { // 从配置文件读取电调服务IP和端口 electricalIP, err := beego.AppConfig.String("ElectricalIP") if err != nil { c.Data["json"] = map[string]interface{}{ "code": 500, "msg": "读取电调服务IP配置失败: " + err.Error(), } c.ServeJSON() return } electricalPort, err := beego.AppConfig.Int("ElectricalPort") if err != nil { c.Data["json"] = map[string]interface{}{ "code": 500, "msg": "读取电调服务端口配置失败: " + err.Error(), } c.ServeJSON() return } // 构造电调服务地址 electricalAddr := fmt.Sprintf("http://%s:%d/ServerCtrl/GetEqpmtFault", electricalIP, electricalPort) // 构造请求体,使用空的JSON对象 reqBody := "{}" // 创建带适当头部的请求 req, err := http.NewRequest("POST", electricalAddr, bytes.NewBufferString(reqBody)) if err != nil { c.Data["json"] = map[string]interface{}{ "code": 500, "msg": "创建请求失败: " + err.Error(), } c.ServeJSON() return } // 设置Content-Type头部 req.Header.Set("Content-Type", "application/json") // 创建HTTP客户端并发送请求 client := &http.Client{} resp, err := client.Do(req) if err != nil { c.Data["json"] = map[string]interface{}{ "code": 500, "msg": "调用电调服务获取设备故障接口失败: " + err.Error(), } c.ServeJSON() return } defer resp.Body.Close() // 检查响应状态 if resp.StatusCode != http.StatusOK { bodyBytes, _ := io.ReadAll(resp.Body) c.Data["json"] = map[string]interface{}{ "code": 500, "msg": fmt.Sprintf("电调服务返回异常状态码: %d,响应内容: %s", resp.StatusCode, string(bodyBytes)), } c.ServeJSON() return } // 读取并解析响应体 bodyBytes, err := io.ReadAll(resp.Body) if err != nil { c.Data["json"] = map[string]interface{}{ "code": 500, "msg": "读取电调服务响应失败: " + err.Error(), } c.ServeJSON() return } // 解析电调服务器的响应 var serverResp map[string]interface{} if err := json.Unmarshal(bodyBytes, &serverResp); err != nil { c.Data["json"] = map[string]interface{}{ "code": 500, "msg": "解析电调服务响应失败: " + err.Error(), } c.ServeJSON() return } // 检查是否有data字段 data, exists := serverResp["data"] if !exists { c.Data["json"] = map[string]interface{}{ "code": 500, "msg": "电调服务响应缺少data字段", } c.ServeJSON() return } // 解析data字段 dataBytes, _ := json.Marshal(data) var faultData []map[string]interface{} if err := json.Unmarshal(dataBytes, &faultData); err != nil { c.Data["json"] = map[string]interface{}{ "code": 500, "msg": "解析故障数据失败: " + err.Error(), } c.ServeJSON() return } // 转换为UI需要的格式 type UIFaultData struct { SeqNo int `json:"SeqNo"` EqpmtID string `json:"EqpmtID"` EqpmtName string `json:"EqpmtName"` FaultID int `json:"FaultID"` FaultTime int `json:"FaultTime"` EqpmtTypeID int `json:"EqpmtTypeID"` } var uiData []UIFaultData seqNo := 1 for _, item := range faultData { eqpmtID, _ := item["EqpmtID"].(string) EqpmtTypeID, _ := item["EqpmtTypeID"].(int) // 解析设备故障数组 eqpmtFault, ok := item["EqpmtFault"].([]interface{}) if !ok || len(eqpmtFault) == 0 { continue } // 取第一个故障记录 faultMap, ok := eqpmtFault[0].(map[string]interface{}) if !ok { continue } faultID, _ := faultMap["FaultID"].(float64) // JSON数字默认解析为float64 // 解析故障时间并计算相对于当前时间的秒数 faultTimeStr, _ := faultMap["FaultTime"].(string) faultTime, err := time.ParseInLocation("2006-01-02 15:04:05", faultTimeStr, time.Local) if err != nil { fmt.Printf("解析故障时间失败: %v\n", err) continue } // 计算距离现在多少秒 secondsAgo := int(time.Since(faultTime).Seconds()) uiFault := UIFaultData{ SeqNo: seqNo, EqpmtID: eqpmtID, EqpmtName: "", // 原始数据中未提供设备名称,留空 FaultID: int(faultID), FaultTime: secondsAgo, EqpmtTypeID: int(EqpmtTypeID), } uiData = append(uiData, uiFault) seqNo++ } // 构造返回给UI的数据 result := map[string]interface{}{ "code": 200, "data": uiData, "msg": serverResp["msg"], } c.Data["json"] = result c.ServeJSON() }