| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601 |
- // 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
- }
- // 计算从课程开始到现在的秒数,减去暂停累计时间
- operTime := int(time.Since(runDateTime).Seconds()) - runningCourse.PauseTotalTime
- // 创建操作日志记录
- operLog := models.CourseOperLog{
- RunLogID: runningCourse.RunLogID,
- RunCourseID: runningCourse.RunCourseID,
- RunOperID: runOperID,
- 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()
- }
|