电调.go 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617
  1. // controllers/用户.go
  2. package controllers
  3. import (
  4. "Tech/common"
  5. "Tech/models"
  6. "bytes"
  7. "encoding/json"
  8. "fmt"
  9. "io"
  10. "net/http"
  11. "time"
  12. "github.com/beego/beego/v2/client/orm"
  13. beego "github.com/beego/beego/v2/server/web"
  14. )
  15. func init() {
  16. // // 启动后台协程定期更新电调模型数据
  17. // go func() {
  18. // // 初始化延迟1秒执行,避免系统启动时的资源竞争
  19. // time.Sleep(1 * time.Second)
  20. // // 定时每5秒获取一次数据
  21. // ticker := time.NewTicker(5 * time.Second)
  22. // defer ticker.Stop()
  23. // for {
  24. // select {
  25. // case <-ticker.C:
  26. // updateElectricalData()
  27. // }
  28. // }
  29. // }()
  30. }
  31. // // updateElectricalData 从电调服务获取数据并更新模型
  32. // func updateElectricalData() {
  33. // defer func() {
  34. // if r := recover(); r != nil {
  35. // fmt.Printf("更新电调数据时发生错误: %v\n", r)
  36. // }
  37. // }()
  38. // // 获取 ElectricModelManager 单例实例
  39. // manager := models.GetInstance()
  40. // // 获取模型列表副本,避免长时间持有锁
  41. // manager.Mutex.RLock()
  42. // modelsCopy := make(map[string]models.EViewMapModel)
  43. // for k, v := range manager.Models {
  44. // modelsCopy[k] = v
  45. // }
  46. // manager.Mutex.RUnlock()
  47. // // 如果 Models 为空,不进行任何处理
  48. // if len(modelsCopy) == 0 {
  49. // return
  50. // }
  51. // // 遍历已有模型并分别更新
  52. // for _, viewMapModel := range modelsCopy {
  53. // if len(viewMapModel.Models) > 0 && time.Since(viewMapModel.LastBatchUpdate) >= 5*time.Second {
  54. // // 获取第一个模型作为参考来构建请求参数
  55. // firstModel := viewMapModel.Models[0]
  56. // // 从配置获取电调服务地址
  57. // electricalIP, err := beego.AppConfig.String("ElectricalIP")
  58. // if err != nil {
  59. // fmt.Printf("读取电调服务IP配置失败: %v\n", err)
  60. // continue
  61. // }
  62. // electricalPort, err := beego.AppConfig.Int("ElectricalPort")
  63. // if err != nil {
  64. // fmt.Printf("读取电调服务端口配置失败: %v\n", err)
  65. // continue
  66. // }
  67. // // 构造电调服务地址
  68. // electricalAddr := fmt.Sprintf("http://%s:%d/ServerCtrl/AllEqpmtList", electricalIP, electricalPort)
  69. // // 准备请求数据
  70. // type RequestData struct {
  71. // LineID int `json:"lineID"`
  72. // StationID int `json:"StationID"`
  73. // ViewID int `json:"ViewID"`
  74. // }
  75. // reqData := RequestData{
  76. // LineID: firstModel.LineID,
  77. // // StationID: firstModel.StationID,
  78. // // ViewID: firstModel.ViewID,
  79. // }
  80. // // 将请求数据转换为JSON
  81. // reqBody, err := json.Marshal(reqData)
  82. // if err != nil {
  83. // fmt.Printf("构造请求数据失败: %v\n", err)
  84. // continue
  85. // }
  86. // // 发送POST请求获取数据
  87. // resp, err := http.Post(electricalAddr, "application/json", bytes.NewBuffer(reqBody))
  88. // if err != nil {
  89. // fmt.Printf("调用电调服务获取所有设备列表接口失败: %v\n", err)
  90. // continue
  91. // }
  92. // // 读取响应体
  93. // bodyBytes, err := io.ReadAll(resp.Body)
  94. // resp.Body.Close()
  95. // if err != nil {
  96. // fmt.Printf("读取电调服务响应失败: %v\n", err)
  97. // continue
  98. // }
  99. // // 检查响应状态
  100. // if resp.StatusCode != http.StatusOK {
  101. // fmt.Printf("电调服务返回异常状态码: %d,响应内容: %s\n", resp.StatusCode, string(bodyBytes))
  102. // continue
  103. // }
  104. // // 解析JSON响应
  105. // var result map[string]interface{}
  106. // if err := json.Unmarshal(bodyBytes, &result); err != nil {
  107. // fmt.Printf("解析电调服务响应失败: %v\n", err)
  108. // continue
  109. // }
  110. // // 检查是否有data字段
  111. // if data, exists := result["data"]; exists {
  112. // // 解析data中的设备列表并更新到模型管理器
  113. // var equipments []models.DiandiaoModel
  114. // if equipBytes, err := json.Marshal(data); err == nil {
  115. // if err := json.Unmarshal(equipBytes, &equipments); err == nil {
  116. // // 更新总包设备数据 (在更新时加锁)
  117. // manager.UpdateBatchData(equipments)
  118. // fmt.Printf("成功更新线路%d的电调模型数据\n", firstModel.LineID)
  119. // } else {
  120. // fmt.Printf("解析设备列表失败: %v\n", err)
  121. // }
  122. // }
  123. // }
  124. // }
  125. // }
  126. // }
  127. type EDispatchController struct {
  128. beego.Controller
  129. }
  130. // /courserun/eqpmtstatus 更新电调设备状态
  131. func (c *EDispatchController) Eqpmtvalue() {
  132. var req models.DiandiaoModel
  133. requestBody := c.Ctx.Input.RequestBody
  134. println("Request Body:", string(requestBody))
  135. if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil {
  136. c.Ctx.Output.SetStatus(400)
  137. c.Data["json"] = map[string]interface{}{
  138. "code": 400,
  139. "msg": "请求参数格式错误: " + err.Error(),
  140. }
  141. c.ServeJSON()
  142. return
  143. }
  144. // 获取 ElectricModelManager 单例实例
  145. manager := models.GetInstance()
  146. // 更新单个设备数据
  147. manager.UpdateSingleDevice(req)
  148. c.Data["json"] = map[string]interface{}{
  149. "code": 200,
  150. "msg": "更新电调设备状态",
  151. }
  152. c.ServeJSON()
  153. }
  154. // /操作日志req
  155. type Addctrllog_req struct {
  156. CtrlType int `json:"CtrlType"`
  157. CtrlSubType int `json:"CtrlSubType"`
  158. CtrlFrom int `json:"CtrlFrom"`
  159. CtrlUser string `json:"CtrlUser"`
  160. Param1 string `json:"Param1"`
  161. Param2 string `json:"Param2"`
  162. Param3 string `json:"Param3"`
  163. Param4 string `json:"Param4"`
  164. Param5 string `json:"Param5"`
  165. }
  166. // 自动评价数据结构体
  167. type AutoEvaData struct {
  168. RunLogID int `orm:"column(运行记录编号)" json:"runLogID"`
  169. SeqNo int `orm:"column(序号)" json:"seqNo"`
  170. EvaName string `orm:"column(评价名称)" json:"evaName"`
  171. CourseID int `orm:"column(课程ID)" json:"courseID"`
  172. IsOperated int `orm:"column(是否操作)" json:"isOperated"`
  173. NodeID int `orm:"column(节点ID)" json:"nodeID"`
  174. EvaType int `orm:"column(评价类型)" json:"evaType"`
  175. TextParam1 string `orm:"column(文本参数1)" json:"textParam1"`
  176. TextParam2 string `orm:"column(文本参数2)" json:"textParam2"`
  177. TextParam3 string `orm:"column(文本参数3)" json:"textParam3"`
  178. TextParam4 string `orm:"column(文本参数4)" json:"textParam4"`
  179. TextParam5 string `orm:"column(文本参数5)" json:"textParam5"`
  180. }
  181. // 评价结果结构体
  182. type EvaResult struct {
  183. Code int `json:"code"` // 状态码:200-成功,400-失败
  184. Message string `json:"message"` // 描述信息
  185. EvaName string `json:"evaName"` // 评价名称
  186. IsOperated int `json:"isOperated"` // 是否操作:0-未操作,1-已操作
  187. OperScore float64 `json:"operScore"` // 操作得分
  188. CourseScore float64 `json:"courseScore"` // 课程总分
  189. SeqNo int `json:"seqNo"` // 序号
  190. }
  191. // /实现自动评价
  192. func (c *EDispatchController) DoAutoEva(req Addctrllog_req) EvaResult {
  193. // 获取数据库连接
  194. o := orm.NewOrm()
  195. // 查找当前正在运行的课程
  196. var runningCourse models.CourseRunLog
  197. err := o.QueryTable(new(models.CourseRunLog)).
  198. Filter("CourseTime", 0).
  199. OrderBy("-RunLogID").
  200. One(&runningCourse)
  201. if err != nil {
  202. // 如果没有找到正在运行的课程,返回错误结果
  203. return EvaResult{
  204. Code: 400,
  205. Message: "没有找到正在运行的课程",
  206. }
  207. }
  208. // 使用自定义SQL查询获取自动评价所需数据
  209. var autoEvaData []AutoEvaData
  210. sql := `SELECT a.运行记录编号, a.序号, a.评价名称, b.课程ID, a.是否操作, b.节点ID,
  211. a.评价类型, b.文本参数1, b.文本参数2, b.文本参数3, b.文本参数4, b.文本参数5
  212. FROM CourseEvaLog a JOIN CourseOperationNode b ON a.评价映射ID = b.节点ID
  213. WHERE a.运行记录编号 = ? AND a.评价类型 = 1 ORDER BY a.序号`
  214. _, err = o.Raw(sql, runningCourse.RunLogID).QueryRows(&autoEvaData)
  215. if err != nil {
  216. return EvaResult{
  217. Code: 400,
  218. Message: "查询评价数据失败: " + err.Error(),
  219. }
  220. }
  221. // 如果没有评价数据,返回提示信息
  222. if len(autoEvaData) == 0 {
  223. return EvaResult{
  224. Code: 200,
  225. Message: "当前课程没有评价数据",
  226. CourseScore: runningCourse.CourseScore,
  227. }
  228. }
  229. // 查找第一个未操作的记录
  230. var foundEvaData *AutoEvaData
  231. var firstSeqNo int = -1
  232. for _, evaData := range autoEvaData {
  233. if evaData.IsOperated == 0 {
  234. if firstSeqNo == -1 {
  235. firstSeqNo = evaData.SeqNo
  236. }
  237. // 检查当前操作的序号是否是第一个未操作的序号
  238. if evaData.SeqNo == firstSeqNo {
  239. foundEvaData = &evaData
  240. break
  241. }
  242. }
  243. }
  244. // 如果没有找到未操作的记录,返回已完成提示
  245. if foundEvaData == nil {
  246. return EvaResult{
  247. Code: 200,
  248. Message: "所有评价项已完成",
  249. CourseScore: runningCourse.CourseScore,
  250. }
  251. }
  252. // 检查参数1和参数2是否为空
  253. if req.Param1 == "" || req.Param2 == "" {
  254. return EvaResult{
  255. Code: 400,
  256. Message: "操作参数不能为空",
  257. EvaName: foundEvaData.EvaName,
  258. IsOperated: 0,
  259. OperScore: 0,
  260. CourseScore: runningCourse.CourseScore,
  261. SeqNo: foundEvaData.SeqNo,
  262. }
  263. }
  264. // 比较参数1和参数2
  265. if req.Param1 == foundEvaData.TextParam1 && req.Param2 == foundEvaData.TextParam2 {
  266. // 参数匹配,需要更新对应的CourseEvaLog记录
  267. var evaLog models.CourseEvaLog
  268. err = o.QueryTable(new(models.CourseEvaLog)).
  269. Filter("RunLogID", foundEvaData.RunLogID).
  270. Filter("SeqNo", foundEvaData.SeqNo).
  271. One(&evaLog)
  272. if err != nil {
  273. return EvaResult{
  274. Code: 400,
  275. Message: "查询评价记录失败: " + err.Error(),
  276. }
  277. }
  278. // 计算操作时间
  279. operTime := 0
  280. // 只有在课程未结束时才计算操作时间(暂停标记为-1表示课程结束)
  281. if runningCourse.PauseFlag != -1 {
  282. // 解析课程开始时间
  283. startTime, err := time.ParseInLocation("2006-01-02 15:04:05", runningCourse.RunDateTime, time.Local)
  284. if err != nil {
  285. return EvaResult{
  286. Code: 400,
  287. Message: "解析课程开始时间失败: " + err.Error(),
  288. }
  289. }
  290. operTime = int(time.Since(startTime).Seconds()) - runningCourse.PauseTotalTime
  291. // 确保操作时间不为负数
  292. if operTime < 0 {
  293. operTime = 0
  294. }
  295. }
  296. // 计算操作得分
  297. operScore := 0.0
  298. // 已操作,得分为评价赋分-评价失分
  299. operScore = float64(evaLog.EvaScore - evaLog.EvaDeduction)
  300. // 更新CourseEvaLog表中的是否操作字段、操作得分和操作时间
  301. _, err = o.Raw(`
  302. UPDATE CourseEvaLog
  303. SET 是否操作 = ?, 操作得分 = ?, 操作时间 = ?
  304. WHERE 运行记录编号 = ? AND 序号 = ?
  305. `, 1, operScore, operTime, foundEvaData.RunLogID, foundEvaData.SeqNo).Exec()
  306. if err != nil {
  307. return EvaResult{
  308. Code: 400,
  309. Message: "更新节点操作状态失败: " + err.Error(),
  310. }
  311. }
  312. // 重新计算整个课程的总得分
  313. var totalScore float64
  314. err = o.Raw(`
  315. SELECT COALESCE(SUM(操作得分), 0)
  316. FROM CourseEvaLog
  317. WHERE 运行记录编号 = ?
  318. `, foundEvaData.RunLogID).QueryRow(&totalScore)
  319. if err != nil {
  320. return EvaResult{
  321. Code: 400,
  322. Message: "计算总得分失败: " + err.Error(),
  323. }
  324. }
  325. // 更新课程运行日志中的总得分
  326. _, err = o.Raw(`
  327. UPDATE CourseRunLog
  328. SET 课程得分 = ?
  329. WHERE 运行记录编号 = ?
  330. `, totalScore, foundEvaData.RunLogID).Exec()
  331. if err != nil {
  332. return EvaResult{
  333. Code: 400,
  334. Message: "更新总得分失败: " + err.Error(),
  335. }
  336. }
  337. // 创建通知数据
  338. notificationData := map[string]interface{}{
  339. "type": "evaluation_update",
  340. "runLogID": foundEvaData.RunLogID,
  341. "seqNo": foundEvaData.SeqNo,
  342. "evaName": foundEvaData.EvaName,
  343. "isOperated": 1,
  344. "operScore": operScore,
  345. "courseScore": totalScore,
  346. "timestamp": time.Now().Format("2006-01-02 15:04:05"),
  347. }
  348. // 通过SSE广播评价更新消息
  349. common.GlobalSSEManager.BroadcastMessage("evaluation_update", notificationData)
  350. // 返回成功结果
  351. return EvaResult{
  352. Code: 200,
  353. Message: "评价成功",
  354. EvaName: foundEvaData.EvaName,
  355. IsOperated: 1,
  356. OperScore: operScore,
  357. CourseScore: totalScore,
  358. SeqNo: foundEvaData.SeqNo,
  359. }
  360. } else {
  361. // 参数不匹配
  362. return EvaResult{
  363. Code: 400,
  364. Message: "操作参数不匹配",
  365. EvaName: foundEvaData.EvaName,
  366. IsOperated: 0,
  367. OperScore: 0,
  368. CourseScore: runningCourse.CourseScore,
  369. SeqNo: foundEvaData.SeqNo,
  370. }
  371. }
  372. }
  373. // /courserun/add_ctrl_log 添加电调控制日志
  374. func (c *EDispatchController) Addctrllog() {
  375. var req Addctrllog_req
  376. requestBody := c.Ctx.Input.RequestBody
  377. println("Request Body:", string(requestBody))
  378. if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil {
  379. c.Ctx.Output.SetStatus(400)
  380. c.Data["json"] = map[string]interface{}{
  381. "code": 400,
  382. "msg": "请求参数格式错误: " + err.Error(),
  383. }
  384. c.ServeJSON()
  385. return
  386. }
  387. // 调用自动评价函数并获取评价结果
  388. evaResult := c.DoAutoEva(req)
  389. // 获取数据库连接
  390. o := orm.NewOrm()
  391. // 查找当前正在运行的课程
  392. var runningCourse models.CourseRunLog
  393. err := o.QueryTable(new(models.CourseRunLog)).
  394. Filter("CourseTime", 0).
  395. OrderBy("-RunLogID").
  396. One(&runningCourse)
  397. if err != nil {
  398. c.Ctx.Output.SetStatus(400)
  399. c.Data["json"] = map[string]interface{}{
  400. "code": 400,
  401. "msg": "查找当前运行课程失败: " + err.Error(),
  402. }
  403. c.ServeJSON()
  404. return
  405. }
  406. // 查找当前运行课程中最大的RunOperID
  407. var maxOperLog models.CourseOperLog
  408. var runOperID int
  409. err = o.QueryTable(new(models.CourseOperLog)).
  410. Filter("RunLogID", runningCourse.RunLogID).
  411. OrderBy("-RunOperID").
  412. One(&maxOperLog)
  413. if err != nil && err != orm.ErrNoRows {
  414. c.Ctx.Output.SetStatus(500)
  415. c.Data["json"] = map[string]interface{}{
  416. "code": 500,
  417. "msg": "查询操作日志失败: " + err.Error(),
  418. }
  419. c.ServeJSON()
  420. return
  421. }
  422. if err == orm.ErrNoRows {
  423. // 如果没有找到记录,则从1开始
  424. runOperID = 1
  425. } else {
  426. // 找到记录,则取最大值加1
  427. runOperID = maxOperLog.RunOperID + 1
  428. }
  429. runDateTime, err := time.ParseInLocation("2006-01-02 15:04:05", runningCourse.RunDateTime, time.Local)
  430. if err != nil {
  431. c.Data["json"] = map[string]interface{}{
  432. "code": 500,
  433. "msg": "解析课程开始时间失败: " + err.Error(),
  434. "runStatus": 0,
  435. "data": nil,
  436. }
  437. c.ServeJSON()
  438. return
  439. }
  440. var curTemplateID = 0
  441. // 根据req.CtrlType和req.CtrlSubType查询TemplateOperation表获取模板ID
  442. var templateOp models.TemplateOperation
  443. err = o.QueryTable(new(models.TemplateOperation)).
  444. Filter("Category", req.CtrlType).
  445. Filter("SubCategory", req.CtrlSubType).
  446. One(&templateOp)
  447. if err == nil {
  448. curTemplateID = templateOp.TemplateID
  449. } else {
  450. // 如果没有找到模板操作记录,则使用默认模板ID
  451. curTemplateID = 0
  452. }
  453. // 计算从课程开始到现在的秒数,减去暂停累计时间
  454. operTime := int(time.Since(runDateTime).Seconds()) - runningCourse.PauseTotalTime
  455. // 创建操作日志记录
  456. operLog := models.CourseOperLog{
  457. RunLogID: runningCourse.RunLogID,
  458. RunCourseID: runningCourse.RunCourseID,
  459. RunOperID: runOperID,
  460. TemplateID: curTemplateID,
  461. OperName: req.CtrlUser,
  462. OperTime: operTime,
  463. OperScore: 0, // 默认分数为0
  464. OperParam1: req.Param1,
  465. OperParam2: req.Param2,
  466. OperParam3: req.Param3,
  467. OperParam4: req.Param4,
  468. OperParam5: req.Param5,
  469. }
  470. // 插入操作日志记录到数据库
  471. _, err = o.Insert(&operLog)
  472. if err != nil {
  473. c.Ctx.Output.SetStatus(500)
  474. c.Data["json"] = map[string]interface{}{
  475. "code": 500,
  476. "msg": "插入操作日志失败: " + err.Error(),
  477. }
  478. c.ServeJSON()
  479. return
  480. }
  481. // 返回包含评价结果的信息
  482. c.Data["json"] = map[string]interface{}{
  483. "code": evaResult.Code,
  484. "msg": "添加操作日志成功",
  485. "evaMessage": evaResult.Message,
  486. "evaName": evaResult.EvaName,
  487. "isOperated": evaResult.IsOperated,
  488. "operScore": evaResult.OperScore,
  489. "courseScore": evaResult.CourseScore,
  490. "seqNo": evaResult.SeqNo,
  491. }
  492. c.ServeJSON()
  493. }
  494. // /serverctrl/subsysstatus 获取电调设备状态
  495. func (c *EDispatchController) SubSysStatus() {
  496. // 从配置文件读取电调服务IP和端口
  497. electricalIP, err := beego.AppConfig.String("ElectricalIP")
  498. if err != nil {
  499. c.Data["json"] = map[string]interface{}{
  500. "code": 500,
  501. "msg": "读取电调服务IP配置失败: " + err.Error(),
  502. }
  503. c.ServeJSON()
  504. return
  505. }
  506. electricalPort, err := beego.AppConfig.Int("ElectricalPort")
  507. if err != nil {
  508. c.Data["json"] = map[string]interface{}{
  509. "code": 500,
  510. "msg": "读取电调服务端口配置失败: " + err.Error(),
  511. }
  512. c.ServeJSON()
  513. return
  514. }
  515. // 构造电调服务地址
  516. electricalAddr := fmt.Sprintf("http://%s:%d/ServerCtrl/SubSysStatus", electricalIP, electricalPort)
  517. // 构造请求体,使用空的JSON对象
  518. reqBody := "{}"
  519. // 创建带适当头部的请求
  520. req, err := http.NewRequest("POST", electricalAddr, bytes.NewBufferString(reqBody))
  521. if err != nil {
  522. c.Data["json"] = map[string]interface{}{
  523. "code": 500,
  524. "msg": "创建请求失败: " + err.Error(),
  525. }
  526. c.ServeJSON()
  527. return
  528. }
  529. // 设置Content-Type头部
  530. req.Header.Set("Content-Type", "application/json")
  531. // 创建HTTP客户端并发送请求
  532. client := &http.Client{}
  533. resp, err := client.Do(req)
  534. if err != nil {
  535. c.Data["json"] = map[string]interface{}{
  536. "code": 500,
  537. "msg": "调用电调服务获取子系统状态接口失败: " + err.Error(),
  538. }
  539. c.ServeJSON()
  540. return
  541. }
  542. defer resp.Body.Close()
  543. // 检查响应状态
  544. if resp.StatusCode != http.StatusOK {
  545. bodyBytes, _ := io.ReadAll(resp.Body)
  546. c.Data["json"] = map[string]interface{}{
  547. "code": 500,
  548. "msg": fmt.Sprintf("电调服务返回异常状态码: %d,响应内容: %s", resp.StatusCode, string(bodyBytes)),
  549. }
  550. c.ServeJSON()
  551. return
  552. }
  553. // 读取并解析响应体
  554. bodyBytes, err := io.ReadAll(resp.Body)
  555. if err != nil {
  556. c.Data["json"] = map[string]interface{}{
  557. "code": 500,
  558. "msg": "读取电调服务响应失败: " + err.Error(),
  559. }
  560. c.ServeJSON()
  561. return
  562. }
  563. // 尝试解析电调服务返回的JSON
  564. var result map[string]interface{}
  565. if err := json.Unmarshal(bodyBytes, &result); err != nil {
  566. // 如果解析失败,返回原始内容
  567. c.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8")
  568. c.Ctx.Output.Body(bodyBytes)
  569. return
  570. }
  571. // 如果解析成功,直接返回JSON结果
  572. c.Data["json"] = result
  573. c.ServeJSON()
  574. }
  575. func (c *EDispatchController) UpdateTestStatus() {
  576. }
  577. // /serverCtrl/alleqpmtlist 获取所有设备列表
  578. func (c *EDispatchController) AllEqpmtList() {
  579. // 转换缓存数据为指定格式
  580. type EquipmentData struct {
  581. DataID string `json:"dataId"`
  582. DataName string `json:"dataName"`
  583. Value string `json:"value"`
  584. ID string `json:"id"`
  585. EqpmtTypeID int `json:"eqpmtTypeID"`
  586. }
  587. // 从配置文件读取电调服务IP和端口
  588. electricalIP, err := beego.AppConfig.String("ElectricalIP")
  589. if err != nil {
  590. c.Data["json"] = map[string]interface{}{
  591. "code": 500,
  592. "msg": "读取电调服务IP配置失败: " + err.Error(),
  593. }
  594. c.ServeJSON()
  595. return
  596. }
  597. electricalPort, err := beego.AppConfig.Int("ElectricalPort")
  598. if err != nil {
  599. c.Data["json"] = map[string]interface{}{
  600. "code": 500,
  601. "msg": "读取电调服务端口配置失败: " + err.Error(),
  602. }
  603. c.ServeJSON()
  604. return
  605. }
  606. // 获取全量数据更新间隔配置,默认10秒
  607. fullDataIntervalSeconds := 10
  608. if interval, err := beego.AppConfig.Int("EGetAllDataInterval"); err == nil {
  609. fullDataIntervalSeconds = interval
  610. }
  611. // 构造电调服务地址
  612. electricalAddr := fmt.Sprintf("http://%s:%d/ServerCtrl/AllEqpmtList", electricalIP, electricalPort)
  613. // 获取最新的课程运行记录以获取线路号
  614. o := orm.NewOrm()
  615. var latestCourse models.CourseRunLog
  616. err = o.QueryTable(new(models.CourseRunLog)).
  617. OrderBy("-RunLogID").
  618. One(&latestCourse)
  619. if err != nil && err != orm.ErrNoRows {
  620. c.Data["json"] = map[string]interface{}{
  621. "code": 500,
  622. "msg": "查询最新课程运行记录失败: " + err.Error(),
  623. }
  624. c.ServeJSON()
  625. return
  626. }
  627. // 如果没有找到运行记录,默认线路号为0
  628. lineID := 0
  629. if err != orm.ErrNoRows {
  630. // 根据运行课程ID查询课程信息以获取线路号
  631. var courseInfo models.CourseInfo
  632. err = o.QueryTable(new(models.CourseInfo)).
  633. Filter("CourseID", latestCourse.RunCourseID).
  634. One(&courseInfo)
  635. if err != nil && err != orm.ErrNoRows {
  636. c.Data["json"] = map[string]interface{}{
  637. "code": 500,
  638. "msg": "查询课程信息失败: " + err.Error(),
  639. }
  640. c.ServeJSON()
  641. return
  642. }
  643. if err != orm.ErrNoRows {
  644. lineID = courseInfo.LineNo
  645. }
  646. }
  647. // 使用客户端IP作为客户端标识
  648. clientID := c.Ctx.Input.IP()
  649. // 获取 ElectricModelManager 单例实例
  650. manager := models.GetInstance()
  651. // 注册客户端
  652. manager.RegisterClient(clientID)
  653. // 注意:不再在函数退出时注销客户端,而是由 ElectricModelManager 内部定期清理长时间未访问的客户端
  654. // 检查是否应该发送全量数据
  655. shouldSendFullData := manager.ShouldSendFullData(fullDataIntervalSeconds)
  656. // 准备请求数据
  657. type RequestData struct {
  658. LineID int `json:"lineID"`
  659. StationID int `json:"StationID"`
  660. ViewID int `json:"ViewID"`
  661. }
  662. reqData := RequestData{
  663. LineID: lineID,
  664. StationID: 0,
  665. ViewID: 0,
  666. }
  667. // 将请求数据转换为JSON
  668. reqBody, err := json.Marshal(reqData)
  669. if err != nil {
  670. c.Data["json"] = map[string]interface{}{
  671. "code": 500,
  672. "msg": "构造请求数据失败: " + err.Error(),
  673. }
  674. c.ServeJSON()
  675. return
  676. }
  677. // 调用电调服务获取所有设备列表接口,使用POST方法
  678. resp, err := http.Post(electricalAddr, "application/json", bytes.NewBuffer(reqBody))
  679. if err != nil {
  680. c.Data["json"] = map[string]interface{}{
  681. "code": 500,
  682. "msg": "调用电调服务获取所有设备列表接口失败: " + err.Error(),
  683. }
  684. c.ServeJSON()
  685. return
  686. }
  687. defer resp.Body.Close()
  688. // 检查响应状态
  689. if resp.StatusCode != http.StatusOK {
  690. bodyBytes, _ := io.ReadAll(resp.Body)
  691. c.Data["json"] = map[string]interface{}{
  692. "code": 500,
  693. "msg": fmt.Sprintf("电调服务返回异常状态码: %d,响应内容: %s", resp.StatusCode, string(bodyBytes)),
  694. }
  695. c.ServeJSON()
  696. return
  697. }
  698. // 读取并解析响应体
  699. bodyBytes, err := io.ReadAll(resp.Body)
  700. if err != nil {
  701. c.Data["json"] = map[string]interface{}{
  702. "code": 500,
  703. "msg": "读取电调服务响应失败: " + err.Error(),
  704. }
  705. c.ServeJSON()
  706. return
  707. }
  708. // 尝试解析JSON响应
  709. var result map[string]interface{}
  710. if err := json.Unmarshal(bodyBytes, &result); err != nil {
  711. // 如果不是JSON格式,作为字符串返回
  712. c.Data["json"] = map[string]interface{}{
  713. "code": 200,
  714. "msg": "获取所有设备列表失败",
  715. "data": string(bodyBytes),
  716. }
  717. } else {
  718. // 如果是JSON格式,检查是否有data字段
  719. if data, exists := result["data"]; exists {
  720. // 解析data中的设备列表并更新到模型管理器
  721. var equipments []models.DiandiaoModel
  722. if equipBytes, err := json.Marshal(data); err == nil {
  723. if err := json.Unmarshal(equipBytes, &equipments); err == nil {
  724. // 更新总包设备数据
  725. manager.UpdateBatchData(equipments)
  726. }
  727. }
  728. // 构建当前设备数据映射
  729. currentDataMapping := make(map[string]string)
  730. var equipmentsData []EquipmentData
  731. // isFirst := true
  732. for _, model := range equipments {
  733. equip := EquipmentData{
  734. DataID: model.EqpmtStrID,
  735. ID: model.EqpmtStrID,
  736. DataName: model.EqpmtStdName,
  737. EqpmtTypeID: model.EqpmtTypeID,
  738. }
  739. if model.CMDType == 0 { //设备状态
  740. equip.Value = fmt.Sprintf("%d", model.EqpmtStatus)
  741. } else if model.CMDType == 1 { //设备数据控制
  742. equip.Value = fmt.Sprintf("%d", model.FValue)
  743. }
  744. // if isFirst {
  745. // // 生成0到100之间的随机整数
  746. // equip.Value = fmt.Sprintf("%d", rand.Intn(101))
  747. // isFirst = false
  748. // }
  749. // 添加到当前数据映射
  750. currentDataMapping[model.EqpmtStrID] = equip.Value
  751. equipmentsData = append(equipmentsData, equip)
  752. }
  753. // 如果应该发送全量数据
  754. if shouldSendFullData {
  755. c.Data["json"] = equipmentsData
  756. manager.UpdateFullDataTimestamp()
  757. manager.UpdateClientData(clientID, currentDataMapping)
  758. } else {
  759. // 否则只返回变化的数据
  760. changedData := manager.CompareWithClientData(clientID, currentDataMapping)
  761. // 构建变化的设备数据列表
  762. var changedEquipmentsData []EquipmentData
  763. for _, equip := range equipmentsData {
  764. if _, changed := changedData[equip.ID]; changed {
  765. changedEquipmentsData = append(changedEquipmentsData, equip)
  766. }
  767. }
  768. // 确保不会返回nil,即使没有变化也返回空数组
  769. if changedEquipmentsData == nil {
  770. changedEquipmentsData = []EquipmentData{}
  771. }
  772. c.Data["json"] = changedEquipmentsData
  773. // 更新客户端数据记录
  774. manager.UpdateClientData(clientID, currentDataMapping)
  775. }
  776. } else {
  777. // 如果没有data字段,返回整个响应
  778. c.Data["json"] = map[string]interface{}{
  779. "code": 500,
  780. "msg": "获取所有设备列表失败",
  781. }
  782. }
  783. }
  784. c.ServeJSON()
  785. }
  786. // // /serverCtrl/alleqpmtlist2 获取所有设备列表 测试使用
  787. // func (c *EDispatchController) AllEqpmtList2() {
  788. // // 转换缓存数据为指定格式
  789. // type EquipmentData struct {
  790. // DataID string `json:"dataId"`
  791. // DataName string `json:"dataName"`
  792. // Value string `json:"value"`
  793. // ID string `json:"id"`
  794. // }
  795. // // 从配置文件读取电调服务IP和端口
  796. // electricalIP, err := beego.AppConfig.String("ElectricalIP")
  797. // if err != nil {
  798. // c.Data["json"] = map[string]interface{}{
  799. // "code": 500,
  800. // "msg": "读取电调服务IP配置失败: " + err.Error(),
  801. // }
  802. // c.ServeJSON()
  803. // return
  804. // }
  805. // electricalPort, err := beego.AppConfig.Int("ElectricalPort")
  806. // if err != nil {
  807. // c.Data["json"] = map[string]interface{}{
  808. // "code": 500,
  809. // "msg": "读取电调服务端口配置失败: " + err.Error(),
  810. // }
  811. // c.ServeJSON()
  812. // return
  813. // }
  814. // // 构造电调服务地址
  815. // electricalAddr := fmt.Sprintf("http://%s:%d/ServerCtrl/AllEqpmtList", electricalIP, electricalPort)
  816. // // 获取最新的课程运行记录以获取线路号
  817. // o := orm.NewOrm()
  818. // var latestCourse models.CourseRunLog
  819. // err = o.QueryTable(new(models.CourseRunLog)).
  820. // OrderBy("-RunLogID").
  821. // One(&latestCourse)
  822. // if err != nil && err != orm.ErrNoRows {
  823. // c.Data["json"] = map[string]interface{}{
  824. // "code": 500,
  825. // "msg": "查询最新课程运行记录失败: " + err.Error(),
  826. // }
  827. // c.ServeJSON()
  828. // return
  829. // }
  830. // // 如果没有找到运行记录,默认线路号为0
  831. // lineID := 0
  832. // if err != orm.ErrNoRows {
  833. // // 根据运行课程ID查询课程信息以获取线路号
  834. // var courseInfo models.CourseInfo
  835. // err = o.QueryTable(new(models.CourseInfo)).
  836. // Filter("CourseID", latestCourse.RunCourseID).
  837. // One(&courseInfo)
  838. // if err != nil && err != orm.ErrNoRows {
  839. // c.Data["json"] = map[string]interface{}{
  840. // "code": 500,
  841. // "msg": "查询课程信息失败: " + err.Error(),
  842. // }
  843. // c.ServeJSON()
  844. // return
  845. // }
  846. // if err != orm.ErrNoRows {
  847. // lineID = courseInfo.LineNo
  848. // }
  849. // }
  850. // // 生成请求key
  851. // model := models.DiandiaoModel{
  852. // LineID: lineID,
  853. // }
  854. // key := model.GenerateModelKey()
  855. // // 获取 ElectricModelManager 单例实例
  856. // manager := models.GetInstance()
  857. // // 检查缓存中是否存在对应key的数据,且最后更新时间在5秒内
  858. // if viewMapModel, exists := manager.GetModelByKey(key); exists {
  859. // // 检查最后总包更新时间是否在5秒内
  860. // if time.Since(viewMapModel.LastBatchUpdate) <= 5*time.Second || time.Since(viewMapModel.LastDeviceUpdate) <= 5*time.Second {
  861. // var equipmentsData []EquipmentData
  862. // for _, model := range viewMapModel.Models {
  863. // equip := EquipmentData{
  864. // DataID: model.EqpmtStrID,
  865. // ID: model.EqpmtStrID,
  866. // DataName: model.EqpmtStdName,
  867. // }
  868. // switch model.CMDType {
  869. // case 0: //设备状态
  870. // equip.Value = fmt.Sprintf("%d", model.EqpmtStatus)
  871. // case 1: //设备数据控制
  872. // equip.Value = fmt.Sprintf("%d", model.FValue)
  873. // }
  874. // equipmentsData = append(equipmentsData, equip)
  875. // }
  876. // c.Data["json"] = equipmentsData
  877. // // 使用缓存数据
  878. // // c.Data["json"] = map[string]interface{}{
  879. // // "code": 200,
  880. // // "msg": "获取所有设备列表成功(缓存)",
  881. // // "data": equipmentsData,
  882. // // }
  883. // c.ServeJSON()
  884. // return
  885. // }
  886. // }
  887. // // 准备请求数据
  888. // type RequestData struct {
  889. // LineID int `json:"lineID"`
  890. // StationID int `json:"StationID"`
  891. // ViewID int `json:"ViewID"`
  892. // }
  893. // reqData := RequestData{
  894. // LineID: lineID,
  895. // StationID: 0,
  896. // ViewID: 0,
  897. // }
  898. // // 将请求数据转换为JSON
  899. // reqBody, err := json.Marshal(reqData)
  900. // if err != nil {
  901. // c.Data["json"] = map[string]interface{}{
  902. // "code": 500,
  903. // "msg": "构造请求数据失败: " + err.Error(),
  904. // }
  905. // c.ServeJSON()
  906. // return
  907. // }
  908. // // 调用电调服务获取所有设备列表接口,使用POST方法
  909. // resp, err := http.Post(electricalAddr, "application/json", bytes.NewBuffer(reqBody))
  910. // if err != nil {
  911. // c.Data["json"] = map[string]interface{}{
  912. // "code": 500,
  913. // "msg": "调用电调服务获取所有设备列表接口失败: " + err.Error(),
  914. // }
  915. // c.ServeJSON()
  916. // return
  917. // }
  918. // defer resp.Body.Close()
  919. // // 检查响应状态
  920. // if resp.StatusCode != http.StatusOK {
  921. // bodyBytes, _ := io.ReadAll(resp.Body)
  922. // c.Data["json"] = map[string]interface{}{
  923. // "code": 500,
  924. // "msg": fmt.Sprintf("电调服务返回异常状态码: %d,响应内容: %s", resp.StatusCode, string(bodyBytes)),
  925. // }
  926. // c.ServeJSON()
  927. // return
  928. // }
  929. // // 读取并解析响应体
  930. // bodyBytes, err := io.ReadAll(resp.Body)
  931. // if err != nil {
  932. // c.Data["json"] = map[string]interface{}{
  933. // "code": 500,
  934. // "msg": "读取电调服务响应失败: " + err.Error(),
  935. // }
  936. // c.ServeJSON()
  937. // return
  938. // }
  939. // // 尝试解析JSON响应
  940. // var result map[string]interface{}
  941. // if err := json.Unmarshal(bodyBytes, &result); err != nil {
  942. // // 如果不是JSON格式,作为字符串返回
  943. // c.Data["json"] = map[string]interface{}{
  944. // "code": 200,
  945. // "msg": "获取所有设备列表成功",
  946. // "data": string(bodyBytes),
  947. // }
  948. // } else {
  949. // // 如果是JSON格式,检查是否有data字段
  950. // if data, exists := result["data"]; exists {
  951. // // 解析data中的设备列表并更新到模型管理器
  952. // var equipments []models.DiandiaoModel
  953. // if equipBytes, err := json.Marshal(data); err == nil {
  954. // if err := json.Unmarshal(equipBytes, &equipments); err == nil {
  955. // // 更新总包设备数据
  956. // manager.UpdateBatchData(equipments)
  957. // }
  958. // }
  959. // var equipmentsData []EquipmentData
  960. // for _, model := range equipments {
  961. // equip := EquipmentData{
  962. // DataID: model.EqpmtStrID,
  963. // ID: model.EqpmtStrID,
  964. // DataName: model.EqpmtStdName,
  965. // }
  966. // if model.CMDType == 0 { //设备状态
  967. // equip.Value = fmt.Sprintf("%d", model.EqpmtStatus)
  968. // } else if model.CMDType == 1 { //设备数据控制
  969. // equip.Value = fmt.Sprintf("%d", model.FValue)
  970. // }
  971. // equipmentsData = append(equipmentsData, equip)
  972. // }
  973. // c.Data["json"] = equipmentsData
  974. // // // 返回响应
  975. // // c.Data["json"] = map[string]interface{}{
  976. // // "code": 200,
  977. // // "msg": "获取所有设备列表成功",
  978. // // "data": equipmentsData,
  979. // // }
  980. // } else {
  981. // // 如果没有data字段,返回整个响应
  982. // c.Data["json"] = map[string]interface{}{
  983. // "code": 500,
  984. // "msg": "获取所有设备列表失败",
  985. // }
  986. // }
  987. // }
  988. // c.ServeJSON()
  989. // }
  990. // /serverctrl/seteqpmtoper 设置电调设备操作
  991. func (c *EDispatchController) Seteqpmtoper() {
  992. // 定义接收的请求数据结构
  993. var req struct {
  994. EqpmtStrID string `json:"EqpmtStrID"`
  995. LineID int `json:"LineID"`
  996. CMDType int `json:"CMDType"`
  997. EqpmtStatus int `json:"EqpmtStatus"`
  998. FValue int `json:"fValue"`
  999. }
  1000. // 解析请求体中的JSON数据
  1001. if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil {
  1002. c.Ctx.Output.SetStatus(400)
  1003. c.Data["json"] = map[string]interface{}{
  1004. "code": 400,
  1005. "msg": "请求参数格式错误: " + err.Error(),
  1006. }
  1007. c.ServeJSON()
  1008. return
  1009. }
  1010. // 如果LineID为0,则尝试获取最近一次运行课程的线路ID
  1011. lineID := req.LineID
  1012. if lineID == 0 {
  1013. o := orm.NewOrm()
  1014. var lastCourse models.CourseRunLog
  1015. // 查询最后运行的课程
  1016. err := o.QueryTable(new(models.CourseRunLog)).
  1017. OrderBy("-RunLogID").
  1018. One(&lastCourse)
  1019. if err == nil {
  1020. // 找到最后一门课程,查询其对应的课程信息以获取线路号
  1021. var courseInfo models.CourseInfo
  1022. err = o.QueryTable(new(models.CourseInfo)).
  1023. Filter("CourseID", lastCourse.RunCourseID).
  1024. One(&courseInfo)
  1025. if err == nil {
  1026. lineID = courseInfo.LineNo
  1027. } else {
  1028. // 查询失败,使用默认值
  1029. lineID = 555
  1030. }
  1031. } else {
  1032. // 没有找到历史课程,使用默认值
  1033. lineID = 555
  1034. }
  1035. }
  1036. // 构造转发给电调服务器的请求数据
  1037. forwardReq := struct {
  1038. EqpmtStrID string `json:"EqpmtStrID"`
  1039. LineID int `json:"LineID"`
  1040. EqpmtStdName string `json:"EqpmtStdName"`
  1041. CMDType int `json:"CMDType"`
  1042. EqpmtStatus int `json:"EqpmtStatus"`
  1043. CtrlType int `json:"CtrlType"`
  1044. OpeMark int `json:"OpeMark"`
  1045. FValue int `json:"fValue"`
  1046. NValueType int `json:"nValueType"`
  1047. IsReset int `json:"IsReset"`
  1048. }{
  1049. EqpmtStrID: req.EqpmtStrID,
  1050. LineID: lineID,
  1051. EqpmtStdName: "", // 默认空值
  1052. CMDType: req.CMDType,
  1053. EqpmtStatus: req.EqpmtStatus,
  1054. CtrlType: 1, // 默认值
  1055. OpeMark: 0, // 默认值
  1056. FValue: req.FValue,
  1057. NValueType: 0, // 默认值
  1058. IsReset: 0, // 默认值
  1059. }
  1060. // 将构造好的请求数据序列化为JSON
  1061. forwardReqBody, err := json.Marshal(forwardReq)
  1062. if err != nil {
  1063. c.Data["json"] = map[string]interface{}{
  1064. "code": 500,
  1065. "msg": "构造转发请求数据失败: " + err.Error(),
  1066. }
  1067. c.ServeJSON()
  1068. return
  1069. }
  1070. // 从配置文件读取电调服务IP和端口
  1071. electricalIP, err := beego.AppConfig.String("ElectricalIP")
  1072. if err != nil {
  1073. c.Data["json"] = map[string]interface{}{
  1074. "code": 500,
  1075. "msg": "读取电调服务IP配置失败: " + err.Error(),
  1076. }
  1077. c.ServeJSON()
  1078. return
  1079. }
  1080. electricalPort, err := beego.AppConfig.Int("ElectricalPort")
  1081. if err != nil {
  1082. c.Data["json"] = map[string]interface{}{
  1083. "code": 500,
  1084. "msg": "读取电调服务端口配置失败: " + err.Error(),
  1085. }
  1086. c.ServeJSON()
  1087. return
  1088. }
  1089. // 构造电调服务地址
  1090. electricalAddr := fmt.Sprintf("http://%s:%d/ServerCtrl/SetEqpmtOper", electricalIP, electricalPort)
  1091. // 将请求数据转发到电调服务器
  1092. resp, err := http.Post(electricalAddr, "application/json", bytes.NewBuffer(forwardReqBody))
  1093. if err != nil {
  1094. c.Data["json"] = map[string]interface{}{
  1095. "code": 500,
  1096. "msg": "转发请求到电调服务器失败: " + err.Error(),
  1097. }
  1098. c.ServeJSON()
  1099. return
  1100. }
  1101. defer resp.Body.Close()
  1102. fmt.Println("Seteqpmtoper 发送 JSON:", string(forwardReqBody))
  1103. // 读取响应体以便打印,然后将其重新放回供后续处理
  1104. respBodyBytes, err := io.ReadAll(resp.Body)
  1105. if err != nil {
  1106. fmt.Printf("Seteqpmtoper: 读取响应用于打印失败: %v\n", err)
  1107. } else {
  1108. fmt.Println("Seteqpmtoper 接收 JSON:", string(respBodyBytes))
  1109. // 由于后续代码还会读取 resp.Body,这里把数据重新放回
  1110. resp.Body = io.NopCloser(bytes.NewBuffer(respBodyBytes))
  1111. }
  1112. // 读取响应体
  1113. bodyBytes, err := io.ReadAll(resp.Body)
  1114. if err != nil {
  1115. c.Data["json"] = map[string]interface{}{
  1116. "code": 500,
  1117. "msg": "读取电调服务响应失败: " + err.Error(),
  1118. }
  1119. c.ServeJSON()
  1120. return
  1121. }
  1122. // 检查响应状态
  1123. if resp.StatusCode != http.StatusOK {
  1124. c.Data["json"] = map[string]interface{}{
  1125. "code": resp.StatusCode,
  1126. "msg": fmt.Sprintf("电调服务返回异常状态码: %d,响应内容: %s", resp.StatusCode, string(bodyBytes)),
  1127. }
  1128. c.ServeJSON()
  1129. return
  1130. }
  1131. // 尝试解析响应为JSON
  1132. var result map[string]interface{}
  1133. if err := json.Unmarshal(bodyBytes, &result); err != nil {
  1134. // 如果不是JSON格式,原样返回
  1135. c.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8")
  1136. c.Ctx.Output.Body(bodyBytes)
  1137. return
  1138. }
  1139. // 返回电调服务器的响应
  1140. c.Data["json"] = result
  1141. c.ServeJSON()
  1142. }
  1143. // /serverctrl/seteqpmtfault 设置设备故障
  1144. func (c *EDispatchController) Seteqpmtfault() {
  1145. // 定义接收的请求数据结构
  1146. var req struct {
  1147. EqpmtStrID string `json:"EqpmtStrID"`
  1148. LineID int `json:"LineID"`
  1149. EventType int `json:"EventType"`
  1150. EventId int `json:"EventId"`
  1151. }
  1152. // 解析请求体中的JSON数据
  1153. if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil {
  1154. c.Ctx.Output.SetStatus(400)
  1155. c.Data["json"] = map[string]interface{}{
  1156. "code": 400,
  1157. "msg": "请求参数格式错误: " + err.Error(),
  1158. }
  1159. c.ServeJSON()
  1160. return
  1161. }
  1162. // 如果LineID为0,则尝试获取最近一次运行课程的线路ID
  1163. lineID := req.LineID
  1164. if lineID == 0 {
  1165. o := orm.NewOrm()
  1166. var lastCourse models.CourseRunLog
  1167. // 查询最后运行的课程
  1168. err := o.QueryTable(new(models.CourseRunLog)).
  1169. OrderBy("-RunLogID").
  1170. One(&lastCourse)
  1171. if err == nil {
  1172. // 找到最后一门课程,查询其对应的课程信息以获取线路号
  1173. var courseInfo models.CourseInfo
  1174. err = o.QueryTable(new(models.CourseInfo)).
  1175. Filter("CourseID", lastCourse.RunCourseID).
  1176. One(&courseInfo)
  1177. if err == nil {
  1178. lineID = courseInfo.LineNo
  1179. } else {
  1180. // 查询失败,使用默认值
  1181. lineID = 555
  1182. }
  1183. } else {
  1184. // 没有找到历史课程,使用默认值
  1185. lineID = 555
  1186. }
  1187. }
  1188. // 构造转发给电调服务器的请求数据
  1189. forwardReq := struct {
  1190. EqpmtStrID string `json:"EqpmtStrID"`
  1191. LineID int `json:"LineID"`
  1192. EventType int `json:"EventType"`
  1193. EventId int `json:"EventId"`
  1194. }{
  1195. EqpmtStrID: req.EqpmtStrID,
  1196. LineID: lineID,
  1197. EventType: req.EventType,
  1198. EventId: req.EventId,
  1199. }
  1200. // 将构造好的请求数据序列化为JSON
  1201. forwardReqBody, err := json.Marshal(forwardReq)
  1202. if err != nil {
  1203. c.Data["json"] = map[string]interface{}{
  1204. "code": 500,
  1205. "msg": "构造转发请求数据失败: " + err.Error(),
  1206. }
  1207. c.ServeJSON()
  1208. return
  1209. }
  1210. // 从配置文件读取电调服务IP和端口
  1211. electricalIP, err := beego.AppConfig.String("ElectricalIP")
  1212. if err != nil {
  1213. c.Data["json"] = map[string]interface{}{
  1214. "code": 500,
  1215. "msg": "读取电调服务IP配置失败: " + err.Error(),
  1216. }
  1217. c.ServeJSON()
  1218. return
  1219. }
  1220. electricalPort, err := beego.AppConfig.Int("ElectricalPort")
  1221. if err != nil {
  1222. c.Data["json"] = map[string]interface{}{
  1223. "code": 500,
  1224. "msg": "读取电调服务端口配置失败: " + err.Error(),
  1225. }
  1226. c.ServeJSON()
  1227. return
  1228. }
  1229. // 构造电调服务地址
  1230. electricalAddr := fmt.Sprintf("http://%s:%d/ServerCtrl/SetEqpmtFault", electricalIP, electricalPort)
  1231. // 将请求数据转发到电调服务器
  1232. resp, err := http.Post(electricalAddr, "application/json", bytes.NewBuffer(forwardReqBody))
  1233. if err != nil {
  1234. c.Data["json"] = map[string]interface{}{
  1235. "code": 500,
  1236. "msg": "转发请求到电调服务器失败: " + err.Error(),
  1237. }
  1238. c.ServeJSON()
  1239. return
  1240. }
  1241. defer resp.Body.Close()
  1242. // 读取响应体
  1243. bodyBytes, err := io.ReadAll(resp.Body)
  1244. if err != nil {
  1245. c.Data["json"] = map[string]interface{}{
  1246. "code": 500,
  1247. "msg": "读取电调服务响应失败: " + err.Error(),
  1248. }
  1249. c.ServeJSON()
  1250. return
  1251. }
  1252. // 检查响应状态
  1253. if resp.StatusCode != http.StatusOK {
  1254. c.Data["json"] = map[string]interface{}{
  1255. "code": resp.StatusCode,
  1256. "msg": fmt.Sprintf("电调服务返回异常状态码: %d,响应内容: %s", resp.StatusCode, string(bodyBytes)),
  1257. }
  1258. c.ServeJSON()
  1259. return
  1260. }
  1261. // 尝试解析响应为JSON
  1262. var result map[string]interface{}
  1263. if err := json.Unmarshal(bodyBytes, &result); err != nil {
  1264. // 如果不是JSON格式,原样返回
  1265. c.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8")
  1266. c.Ctx.Output.Body(bodyBytes)
  1267. return
  1268. }
  1269. // 返回电调服务器的响应
  1270. c.Data["json"] = result
  1271. c.ServeJSON()
  1272. }
  1273. // /serverctrl/geteqpmtfault 获取设备故障
  1274. func (c *EDispatchController) GetEqpmtFault() {
  1275. // 从配置文件读取电调服务IP和端口
  1276. electricalIP, err := beego.AppConfig.String("ElectricalIP")
  1277. if err != nil {
  1278. c.Data["json"] = map[string]interface{}{
  1279. "code": 500,
  1280. "msg": "读取电调服务IP配置失败: " + err.Error(),
  1281. }
  1282. c.ServeJSON()
  1283. return
  1284. }
  1285. electricalPort, err := beego.AppConfig.Int("ElectricalPort")
  1286. if err != nil {
  1287. c.Data["json"] = map[string]interface{}{
  1288. "code": 500,
  1289. "msg": "读取电调服务端口配置失败: " + err.Error(),
  1290. }
  1291. c.ServeJSON()
  1292. return
  1293. }
  1294. // 构造电调服务地址
  1295. electricalAddr := fmt.Sprintf("http://%s:%d/ServerCtrl/GetEqpmtFault", electricalIP, electricalPort)
  1296. // 构造请求体,使用空的JSON对象
  1297. reqBody := "{}"
  1298. // 创建带适当头部的请求
  1299. req, err := http.NewRequest("POST", electricalAddr, bytes.NewBufferString(reqBody))
  1300. if err != nil {
  1301. c.Data["json"] = map[string]interface{}{
  1302. "code": 500,
  1303. "msg": "创建请求失败: " + err.Error(),
  1304. }
  1305. c.ServeJSON()
  1306. return
  1307. }
  1308. // 设置Content-Type头部
  1309. req.Header.Set("Content-Type", "application/json")
  1310. // 创建HTTP客户端并发送请求
  1311. client := &http.Client{}
  1312. resp, err := client.Do(req)
  1313. if err != nil {
  1314. c.Data["json"] = map[string]interface{}{
  1315. "code": 500,
  1316. "msg": "调用电调服务获取设备故障接口失败: " + err.Error(),
  1317. }
  1318. c.ServeJSON()
  1319. return
  1320. }
  1321. defer resp.Body.Close()
  1322. // 检查响应状态
  1323. if resp.StatusCode != http.StatusOK {
  1324. bodyBytes, _ := io.ReadAll(resp.Body)
  1325. c.Data["json"] = map[string]interface{}{
  1326. "code": 500,
  1327. "msg": fmt.Sprintf("电调服务返回异常状态码: %d,响应内容: %s", resp.StatusCode, string(bodyBytes)),
  1328. }
  1329. c.ServeJSON()
  1330. return
  1331. }
  1332. // 读取并解析响应体
  1333. bodyBytes, err := io.ReadAll(resp.Body)
  1334. if err != nil {
  1335. c.Data["json"] = map[string]interface{}{
  1336. "code": 500,
  1337. "msg": "读取电调服务响应失败: " + err.Error(),
  1338. }
  1339. c.ServeJSON()
  1340. return
  1341. }
  1342. // 解析电调服务器的响应
  1343. var serverResp map[string]interface{}
  1344. if err := json.Unmarshal(bodyBytes, &serverResp); err != nil {
  1345. c.Data["json"] = map[string]interface{}{
  1346. "code": 500,
  1347. "msg": "解析电调服务响应失败: " + err.Error(),
  1348. }
  1349. c.ServeJSON()
  1350. return
  1351. }
  1352. // 检查是否有data字段
  1353. data, exists := serverResp["data"]
  1354. if !exists {
  1355. c.Data["json"] = map[string]interface{}{
  1356. "code": 500,
  1357. "msg": "电调服务响应缺少data字段",
  1358. }
  1359. c.ServeJSON()
  1360. return
  1361. }
  1362. // 解析data字段
  1363. dataBytes, _ := json.Marshal(data)
  1364. var faultData []map[string]interface{}
  1365. if err := json.Unmarshal(dataBytes, &faultData); err != nil {
  1366. c.Data["json"] = map[string]interface{}{
  1367. "code": 500,
  1368. "msg": "解析故障数据失败: " + err.Error(),
  1369. }
  1370. c.ServeJSON()
  1371. return
  1372. }
  1373. // 转换为UI需要的格式
  1374. type UIFaultData struct {
  1375. SeqNo int `json:"SeqNo"`
  1376. EqpmtID string `json:"EqpmtID"`
  1377. EqpmtName string `json:"EqpmtName"`
  1378. FaultID int `json:"FaultID"`
  1379. FaultTime int `json:"FaultTime"`
  1380. EqpmtTypeID int `json:"EqpmtTypeID"`
  1381. }
  1382. var uiData []UIFaultData
  1383. seqNo := 1
  1384. for _, item := range faultData {
  1385. eqpmtID, _ := item["EqpmtID"].(string)
  1386. EqpmtTypeID, _ := item["EqpmtTypeID"].(int)
  1387. // 解析设备故障数组
  1388. eqpmtFault, ok := item["EqpmtFault"].([]interface{})
  1389. if !ok || len(eqpmtFault) == 0 {
  1390. continue
  1391. }
  1392. // 取第一个故障记录
  1393. faultMap, ok := eqpmtFault[0].(map[string]interface{})
  1394. if !ok {
  1395. continue
  1396. }
  1397. faultID, _ := faultMap["FaultID"].(float64) // JSON数字默认解析为float64
  1398. // 解析故障时间并计算相对于当前时间的秒数
  1399. faultTimeStr, _ := faultMap["FaultTime"].(string)
  1400. faultTime, err := time.ParseInLocation("2006-01-02 15:04:05", faultTimeStr, time.Local)
  1401. if err != nil {
  1402. fmt.Printf("解析故障时间失败: %v\n", err)
  1403. continue
  1404. }
  1405. // 计算距离现在多少秒
  1406. secondsAgo := int(time.Since(faultTime).Seconds())
  1407. uiFault := UIFaultData{
  1408. SeqNo: seqNo,
  1409. EqpmtID: eqpmtID,
  1410. EqpmtName: "", // 原始数据中未提供设备名称,留空
  1411. FaultID: int(faultID),
  1412. FaultTime: secondsAgo,
  1413. EqpmtTypeID: int(EqpmtTypeID),
  1414. }
  1415. uiData = append(uiData, uiFault)
  1416. seqNo++
  1417. }
  1418. // 构造返回给UI的数据
  1419. result := map[string]interface{}{
  1420. "code": 200,
  1421. "data": uiData,
  1422. "msg": serverResp["msg"],
  1423. }
  1424. c.Data["json"] = result
  1425. c.ServeJSON()
  1426. }