| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617 |
- // 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()
- }
|