DeviceController.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970
  1. package controllers
  2. import (
  3. "ColdP_server/conf"
  4. "ColdP_server/controllers/MqttServer"
  5. "ColdP_server/controllers/lib"
  6. "ColdP_server/logs"
  7. "ColdP_server/models/Company"
  8. "ColdP_server/models/Device"
  9. "ColdP_server/models/Warning"
  10. "encoding/json"
  11. "fmt"
  12. beego "github.com/beego/beego/v2/server/web"
  13. "io"
  14. "log"
  15. "math"
  16. "strconv"
  17. "strings"
  18. "sync"
  19. "time"
  20. )
  21. // DeviceController 设备管理页面
  22. type DeviceController struct {
  23. beego.Controller
  24. }
  25. // DeviceManagerHtml 返回页面
  26. func (c *DeviceController) DeviceManagerHtml() {
  27. //验证是否登录
  28. is, admin := lib.VerificationController(&c.Controller)
  29. if !is {
  30. return
  31. }
  32. //类名列表
  33. classList := Company.Read_CompanyClass_All(admin.T_pid, "")
  34. c.Data["Class_List"] = classList
  35. c.TplName = "Device/Device.html"
  36. }
  37. func (c *DeviceController) DeviceList() {
  38. tName := c.GetString("deviceName") // 设备名称
  39. page, _ := c.GetInt64("currentPage") // 当前页码
  40. tClassify, _ := c.GetInt("deviceClass") // 设备分类
  41. is, admin := lib.VerificationController(&c.Controller)
  42. fmt.Println("当前用户的PID为:", admin.T_pid)
  43. if !is {
  44. // 用户未登录
  45. c.Data["json"] = lib.JSONS{202, "身份认证失效", nil}
  46. c.ServeJSON()
  47. return
  48. }
  49. device_list, count := Device.Read_DeviceSensor_List_T_ClassOr(admin.T_pid, tClassify, tName, tName, -1, int(page), conf.Page_size)
  50. var pageCount int
  51. if (int(count) % conf.Page_size) != 0 {
  52. pageCount = int(count) / conf.Page_size
  53. pageCount++
  54. }
  55. var wg sync.WaitGroup
  56. for i := range device_list {
  57. wg.Add(1)
  58. go func(deviceList *Device.DeviceSensor_) {
  59. defer func() {
  60. if r := recover(); r != nil {
  61. logs.Debug("协程出现异常: %v", r)
  62. }
  63. }()
  64. defer wg.Done()
  65. t := Device.Read_DeviceData(deviceList.T_sn, deviceList.T_id)
  66. err2, m := Device.ReadDeviceSensorParameter(deviceList.T_Sp)
  67. if err2 != nil {
  68. logs.Error("Error getting device sensor parameter for SN: %s, %v", deviceList.T_sn, err2)
  69. }
  70. coldp, _ := MqttServer.FindClodpServerBySnAndId(deviceList.T_sn, deviceList.T_id, 8)
  71. deviceList.T_tDeviation = 1201
  72. deviceList.T_RhDeviation = 1201
  73. if len(coldp.Sn) != 0 {
  74. deviceList.T_tDeviation = coldp.T_t
  75. deviceList.T_RhDeviation = coldp.T_h
  76. deviceList.Is_true = coldp.IsTrue
  77. }
  78. deviceList.T_Tlower = m.T_Tlower
  79. deviceList.T_Tupper = m.T_Tupper
  80. deviceList.T_RHlower = m.T_RHlower
  81. deviceList.T_RHupper = m.T_RHupper
  82. deviceList.T_t = t.T_t
  83. deviceList.T_rh = t.T_rh
  84. }(&device_list[i])
  85. }
  86. wg.Wait()
  87. c.Data["json"] = lib.PageHelper{int(count), pageCount, int(page), int(page) >= pageCount, page <= 1, device_list}
  88. c.ServeJSON()
  89. return
  90. }
  91. // CompanyClass 获取公司设备类目
  92. func (c *DeviceController) CompanyClass() {
  93. is, admin := lib.VerificationController(&c.Controller)
  94. if !is {
  95. c.Data["json"] = lib.JSONS{202, "用户未登录", nil}
  96. c.ServeJSON()
  97. return
  98. }
  99. //类名列表
  100. classList := Company.Read_CompanyClass_All(admin.T_pid, "")
  101. c.Data["json"] = classList
  102. c.ServeJSON()
  103. }
  104. // DataRepeat 数据重传
  105. func (c *DeviceController) DataRepeat() {
  106. b_, _ := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  107. if !b_ {
  108. c.Data["json"] = lib.JSONS{Code: 201, Msg: "User_tokey Err!"}
  109. c.ServeJSON()
  110. return
  111. }
  112. t := MqttServer.DataRepeat_C{}
  113. bytes, _ := io.ReadAll(c.Ctx.Request.Body)
  114. json.Unmarshal(bytes, &t)
  115. fmt.Println("浏览器接收数据:", t)
  116. s, _ := time.Parse("2006-01-02 15:04:05", t.StartTime)
  117. e, _ := time.Parse("2006-01-02 15:04:05", t.EndTime)
  118. var wg sync.WaitGroup
  119. failSn := make([]string, 0)
  120. // 发送MQTT
  121. for k, v := range t.Sns {
  122. wg.Add(1)
  123. log.Println("传感器参数", v)
  124. go func(k string, v []string) {
  125. defer wg.Done()
  126. if len(v[0]) > 0 {
  127. atoi, _ := strconv.Atoi(v[0])
  128. topicPub := fmt.Sprintf("/pub/%s", k)
  129. repeatPub := MqttServer.DataRepeat_Pub{
  130. Sn: k, Type: 9, Mid: time.Now().Unix(), Data: MqttServer.DataRepeat_Pub_Data{Start: s.Unix(), End: e.Unix(), Id: []int{atoi}}}
  131. msg, _ := json.Marshal(repeatPub)
  132. mqttId := strings.Split(Device.ReadDeviceMqttId(k), "\"")[0]
  133. topicSub := fmt.Sprintf("/sub/%s", k)
  134. timeout := 5 * time.Second
  135. if len(mqttId) != 0 {
  136. ack, _, err := MqttServer.SendAndWaitForAck(mqttId, topicPub, topicSub, msg, timeout)
  137. if ack {
  138. } else {
  139. logs.Error("连接失败", err)
  140. failSn = append(failSn, k)
  141. }
  142. }
  143. }
  144. }(k, v)
  145. }
  146. wg.Wait()
  147. if len(failSn) > 0 {
  148. c.Data["json"] = lib.JSONS{Code: 1201, Msg: "部分重传失败", Data: failSn}
  149. } else {
  150. c.Data["json"] = lib.JSONS{Code: 200, Msg: "重传数据成功!", Data: nil}
  151. }
  152. c.ServeJSON()
  153. }
  154. func (c *DeviceController) ReadDeviation() {
  155. // 用户令牌验证
  156. b_, _ := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  157. if !b_ {
  158. c.Data["json"] = lib.JSONS{Code: 201, Msg: "User_tokey Err!"}
  159. c.ServeJSON()
  160. return
  161. }
  162. t := make(map[string][]int)
  163. bytes, err := io.ReadAll(c.Ctx.Request.Body)
  164. if err != nil {
  165. log.Printf("Error reading request body: %v", err)
  166. c.Data["json"] = lib.JSONS{Code: 400, Msg: "Bad Request"}
  167. c.ServeJSON()
  168. return
  169. }
  170. if err := json.Unmarshal(bytes, &t); err != nil {
  171. log.Printf("Error unmarshalling JSON: %v", err)
  172. c.Data["json"] = lib.JSONS{Code: 400, Msg: "Bad Request"}
  173. c.ServeJSON()
  174. return
  175. }
  176. fmt.Println("浏览器接收数据:", t)
  177. var errors []string
  178. for k, v := range t {
  179. if len(v) > 0 {
  180. coldp, err := MqttServer.FindClodpServerBySnAndId(k, v[0], 8)
  181. if err != nil || len(coldp.Sn) == 0 {
  182. //topicSub := fmt.Sprintf("/sub/%s", k)
  183. topicPub := fmt.Sprintf("/pub/%s", k)
  184. mqttId := Device.ReadDeviceMqttId(k)
  185. //timeout := 5 * time.Second
  186. // 订阅主题操作,设置超时控制
  187. pubData, err := json.Marshal(MqttServer.Deviation_Pub{
  188. Sn: k,
  189. Type: 7,
  190. Mid: time.Now().Unix(),
  191. Data: v,
  192. })
  193. if err != nil {
  194. log.Printf("Error marshalling JSON for SN: %s, %v", k, err)
  195. errors = append(errors, fmt.Sprintf("设备: %s 序列化消息失败 %v", k, err))
  196. continue
  197. }
  198. if len(mqttId) != 0 {
  199. if client, ok := MqttServer.MqttCon.Get(mqttId); ok {
  200. err = MqttServer.MqttPublish(client, topicPub, pubData)
  201. time.Sleep(3 * time.Second)
  202. coldp, err = MqttServer.FindClodpServerBySnAndId(k, v[0], 8)
  203. if err != nil || len(coldp.Sn) == 0 {
  204. c.Data["json"] = lib.JSONS{Code: 500, Msg: "同步参数失败", Data: nil}
  205. c.ServeJSON()
  206. return
  207. }
  208. }
  209. var sub MqttServer.Deviation_Sub
  210. sub.Sn = coldp.Sn
  211. sub.Data = []MqttServer.Deviation_Sub_Data{
  212. MqttServer.Deviation_Sub_Data{
  213. Id: coldp.T_id,
  214. T: coldp.T_t,
  215. H: coldp.T_h,
  216. },
  217. }
  218. c.Data["json"] = lib.JSONS{Code: 200, Msg: "读取参数成功", Data: sub}
  219. c.ServeJSON()
  220. return
  221. }
  222. } else {
  223. var sub MqttServer.Deviation_Sub
  224. sub.Sn = coldp.Sn
  225. sub.Data = []MqttServer.Deviation_Sub_Data{
  226. MqttServer.Deviation_Sub_Data{
  227. Id: coldp.T_id,
  228. T: coldp.T_t,
  229. H: coldp.T_h,
  230. },
  231. }
  232. c.Data["json"] = lib.JSONS{Code: 200, Msg: "读取参数成功", Data: sub}
  233. c.ServeJSON()
  234. return
  235. }
  236. }
  237. }
  238. }
  239. // WriteDeviation 设置偏差值
  240. func (c *DeviceController) WriteDeviation() {
  241. b_, _ := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  242. if !b_ {
  243. c.Data["json"] = lib.JSONS{Code: 201, Msg: "User_tokey Err!"}
  244. c.ServeJSON()
  245. return
  246. }
  247. bytes, _ := io.ReadAll(c.Ctx.Request.Body)
  248. data := make([]MqttServer.Deviation_Sub, 0)
  249. if err := json.Unmarshal(bytes, &data); err != nil {
  250. log.Printf("Error unmarshalling JSON: %v", err)
  251. c.Data["json"] = lib.JSONS{Code: 400, Msg: "mqtt请求失败"}
  252. c.ServeJSON()
  253. return
  254. }
  255. var wg sync.WaitGroup
  256. successfulSns := make(map[string]bool) // 记录成功的SN
  257. mutex := &sync.Mutex{} // 保护对successfulSns的访问
  258. failSn := make([]string, 0)
  259. handleResult := func(sn string, success bool) {
  260. mutex.Lock()
  261. defer mutex.Unlock()
  262. if success {
  263. successfulSns[sn] = true
  264. } else {
  265. failSn = append(failSn, sn)
  266. }
  267. }
  268. // 处理每个设备的数据
  269. for _, v := range data {
  270. wg.Add(1)
  271. go func(v MqttServer.Deviation_Sub) {
  272. defer wg.Done()
  273. v.Type = 8
  274. v.Mid = int64(int(time.Now().Unix()))
  275. mqttId := Device.ReadDeviceMqttId(v.Sn)
  276. topicPub := fmt.Sprintf("/pub/%s", v.Sn)
  277. msgBytes, err := json.Marshal(v)
  278. if err != nil {
  279. log.Printf("Error marshalling JSON for SN: %s, %v", v.Sn, err)
  280. handleResult(v.Sn, false)
  281. return
  282. }
  283. if len(mqttId) != 0 {
  284. clos := make([]string, 0)
  285. if client, ok := MqttServer.MqttCon.Get(mqttId); ok {
  286. err = MqttServer.MqttPublish(client, topicPub, msgBytes)
  287. var cold MqttServer.ClodpServer
  288. if err != nil {
  289. cold.Sn = v.Sn
  290. cold.T_id = v.Data[0].Id
  291. cold.T_h = v.Data[0].H
  292. cold.T_t = v.Data[0].T
  293. cold.IsTrue = 1
  294. cold.Types = 8
  295. cold.CreateTime = time.Now()
  296. cold.UpdateTime = time.Now()
  297. err := MqttServer.Add_ClodpServer(cold)
  298. if err != nil {
  299. logs.Error("设置参数失败", err)
  300. }
  301. failSn = append(failSn, v.Sn)
  302. }
  303. time.Sleep(3 * time.Second)
  304. if len(v.Data) > 0 {
  305. coldp, err := MqttServer.FindClodpServerBySnAndId(v.Sn, v.Data[0].Id, 8)
  306. if err != nil {
  307. failSn = append(failSn, v.Sn)
  308. }
  309. if len(coldp.Sn) == 0 {
  310. coldp.Sn = v.Sn
  311. coldp.T_id = v.Data[0].Id
  312. coldp.T_h = v.Data[0].H
  313. coldp.T_t = v.Data[0].T
  314. coldp.IsTrue = 1
  315. coldp.Types = 8
  316. coldp.CreateTime = time.Now()
  317. coldp.UpdateTime = time.Now()
  318. err := MqttServer.Add_ClodpServer(coldp)
  319. if err != nil {
  320. logs.Error("设置参数失败", err)
  321. }
  322. failSn = append(failSn, v.Sn)
  323. }
  324. if coldp.T_h != v.Data[0].H || coldp.T_t != v.Data[0].T {
  325. coldp.T_h = v.Data[0].H
  326. coldp.T_t = v.Data[0].T
  327. coldp.IsTrue = 1
  328. clos = append(clos, "t_t")
  329. clos = append(clos, "t_h")
  330. clos = append(clos, "is_true")
  331. MqttServer.Update_ClodpServer(coldp, clos...)
  332. }
  333. }
  334. }
  335. }
  336. }(v)
  337. }
  338. wg.Wait()
  339. if len(failSn) > 0 {
  340. c.Data["json"] = lib.JSONS{Code: 1201, Msg: "部分设置失败", Data: failSn}
  341. } else {
  342. c.Data["json"] = lib.JSONS{Code: 200, Msg: "设置偏差值成功!", Data: nil}
  343. }
  344. c.ServeJSON()
  345. }
  346. // WriteDeviationAll 批量设置偏差值
  347. func (c *DeviceController) WriteDeviationAll() {
  348. b_, _ := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  349. if !b_ {
  350. c.Data["json"] = lib.JSONS{Code: 201, Msg: "User_tokey Err!"}
  351. c.ServeJSON()
  352. return
  353. }
  354. bytes, _ := io.ReadAll(c.Ctx.Request.Body)
  355. fmt.Println("请求json:", string(bytes))
  356. var data MqttServer.Deviation_SubAll
  357. if err := json.Unmarshal(bytes, &data); err != nil {
  358. log.Printf("Error unmarshalling JSON: %v", err)
  359. c.Data["json"] = lib.JSONS{Code: 400, Msg: "mqtt请求失败"}
  360. c.ServeJSON()
  361. return
  362. }
  363. var wg sync.WaitGroup
  364. successfulSns := make(map[string]bool) // 记录成功的SN
  365. mutex := &sync.Mutex{} // 保护对successfulSns的访问
  366. failSn := make([]string, 0)
  367. handleResult := func(sn string, success bool) {
  368. mutex.Lock()
  369. defer mutex.Unlock()
  370. if success {
  371. successfulSns[sn] = true
  372. } else {
  373. failSn = append(failSn, sn)
  374. }
  375. }
  376. // 处理每个设备的数据
  377. for i, sn := range data.Sn {
  378. subData := data.Data[i]
  379. wg.Add(1)
  380. go func(sn string, subData MqttServer.Deviation_Sub_Data) {
  381. defer wg.Done()
  382. sub_data := make([]MqttServer.Deviation_Sub_Data, 0)
  383. sub_data = append(sub_data, subData)
  384. v := MqttServer.Deviation_Sub{
  385. Type: 8,
  386. Sn: sn,
  387. Mid: int64(int(time.Now().Unix())),
  388. Data: sub_data,
  389. }
  390. mqttId := Device.ReadDeviceMqttId(v.Sn)
  391. topicPub := fmt.Sprintf("/pub/%s", v.Sn)
  392. msgBytes, err := json.Marshal(v)
  393. if len(mqttId) != 0 {
  394. clos := make([]string, 0)
  395. if client, ok := MqttServer.MqttCon.Get(mqttId); ok {
  396. err = MqttServer.MqttPublish(client, topicPub, msgBytes)
  397. var cold MqttServer.ClodpServer
  398. if err != nil {
  399. cold.Sn = v.Sn
  400. cold.T_id = v.Data[0].Id
  401. cold.T_h = v.Data[0].H
  402. cold.T_t = v.Data[0].T
  403. cold.IsTrue = 1
  404. cold.Types = 8
  405. cold.CreateTime = time.Now()
  406. cold.UpdateTime = time.Now()
  407. err := MqttServer.Add_ClodpServer(cold)
  408. if err != nil {
  409. logs.Error("设置参数失败", err)
  410. }
  411. handleResult(v.Sn, false)
  412. }
  413. time.Sleep(3 * time.Second)
  414. if len(v.Data) > 0 {
  415. coldp, err := MqttServer.FindClodpServerBySnAndId(v.Sn, v.Data[0].Id, 8)
  416. log.Println("得到参数", coldp)
  417. if err != nil {
  418. failSn = append(failSn, v.Sn)
  419. }
  420. if len(coldp.Sn) == 0 {
  421. coldp.Sn = v.Sn
  422. coldp.T_id = v.Data[0].Id
  423. coldp.T_h = v.Data[0].H
  424. coldp.T_t = v.Data[0].T
  425. coldp.IsTrue = 1
  426. coldp.Types = 8
  427. coldp.CreateTime = time.Now()
  428. coldp.UpdateTime = time.Now()
  429. err := MqttServer.Add_ClodpServer(coldp)
  430. if err != nil {
  431. logs.Error("设置参数失败", err)
  432. }
  433. handleResult(v.Sn, false)
  434. }
  435. if coldp.T_h != v.Data[0].H || coldp.T_t != v.Data[0].T {
  436. coldp.T_h = v.Data[0].H
  437. coldp.T_t = v.Data[0].T
  438. coldp.IsTrue = 1
  439. clos = append(clos, "t_t")
  440. clos = append(clos, "t_h")
  441. clos = append(clos, "is_true")
  442. MqttServer.Update_ClodpServer(coldp, clos...)
  443. handleResult(v.Sn, false)
  444. }
  445. }
  446. }
  447. }
  448. }(sn, subData)
  449. }
  450. wg.Wait()
  451. if len(failSn) > 0 {
  452. c.Data["json"] = lib.JSONS{Code: 1201, Msg: "部分设置失败", Data: failSn}
  453. } else {
  454. c.Data["json"] = lib.JSONS{Code: 200, Msg: "设置偏差值成功!", Data: nil}
  455. }
  456. c.ServeJSON()
  457. }
  458. // ReadSensor 读取传感器参数
  459. func (c *DeviceController) ReadSensor() {
  460. b_, _ := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  461. if !b_ {
  462. c.Data["json"] = lib.JSONS{Code: 201, Msg: "User_tokey Err!"}
  463. c.ServeJSON()
  464. return
  465. }
  466. t := make(map[string][]int)
  467. bytes, _ := io.ReadAll(c.Ctx.Request.Body)
  468. if err := json.Unmarshal(bytes, &t); err != nil {
  469. log.Printf("Error unmarshalling JSON: %v", err)
  470. c.Data["json"] = lib.JSONS{Code: 400, Msg: "Bad Request"}
  471. c.ServeJSON()
  472. return
  473. }
  474. fmt.Println("浏览器接收数据:", t)
  475. for k, v := range t {
  476. topicPub := fmt.Sprintf("/pub/%s", k)
  477. mqttId := Device.ReadDeviceMqttId(k)
  478. pubData, err := json.Marshal(MqttServer.Deviation_Pub{
  479. Sn: k,
  480. Type: 5,
  481. Mid: time.Now().Unix(),
  482. Data: v,
  483. })
  484. if err != nil {
  485. logs.Error("json序列化失败")
  486. }
  487. if len(mqttId) != 0 {
  488. if client, ok := MqttServer.MqttCon.Get(mqttId); ok {
  489. err = MqttServer.MqttPublish(client, topicPub, pubData)
  490. if err != nil {
  491. logs.Error("发送失败")
  492. c.Data["json"] = lib.JSONS{Code: 200, Msg: "读取传感器参数失败", Data: nil}
  493. c.ServeJSON()
  494. return
  495. } else {
  496. if len(v) > 0 {
  497. time.Sleep(3 * time.Second)
  498. coldp, err := MqttServer.FindClodpServerBySnAndId(k, v[0], 6)
  499. if err != nil {
  500. logs.Error("发送失败")
  501. c.Data["json"] = lib.JSONS{Code: 500, Msg: "读取传感器参数失败", Data: nil}
  502. c.ServeJSON()
  503. return
  504. }
  505. if len(coldp.Sn) == 0 {
  506. logs.Error("发送失败")
  507. c.Data["json"] = lib.JSONS{Code: 500, Msg: "读取传感器参数失败", Data: nil}
  508. c.ServeJSON()
  509. return
  510. }
  511. c.Data["json"] = lib.JSONS{Code: 200, Msg: "偏差值上传成功", Data: coldp}
  512. c.ServeJSON()
  513. return
  514. }
  515. }
  516. }
  517. }
  518. }
  519. }
  520. // WriteSensor 设置传感器参数
  521. func (c *DeviceController) WriteSensor() {
  522. b_, _ := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  523. if !b_ {
  524. c.Data["json"] = lib.JSONS{Code: 201, Msg: "User_tokey Err!"}
  525. c.ServeJSON()
  526. return
  527. }
  528. bytes, err := io.ReadAll(c.Ctx.Request.Body)
  529. if err != nil {
  530. log.Printf("Error reading request body: %v", err)
  531. c.Data["json"] = lib.JSONS{Code: 500, Msg: "Internal Server Error"}
  532. c.ServeJSON()
  533. return
  534. }
  535. fmt.Println("请求json:", string(bytes))
  536. clos := make([]string, 0)
  537. data := make([]MqttServer.Sensor_Sub, 0)
  538. if err := json.Unmarshal(bytes, &data); err != nil {
  539. log.Printf("Error unmarshalling JSON: %v", err)
  540. c.Data["json"] = lib.JSONS{Code: 400, Msg: "Bad Request"}
  541. c.ServeJSON()
  542. return
  543. }
  544. for _, v := range data {
  545. mqttId := Device.ReadDeviceMqttId(v.Sn)
  546. topicPub := fmt.Sprintf("/pub/%s", v.Sn)
  547. v.Type = 6
  548. v.Mid = int(time.Now().Unix())
  549. msgBytes, err := json.Marshal(v)
  550. if err != nil {
  551. log.Printf("Error marshalling JSON for SN: %s, %v", v.Sn, err)
  552. return
  553. }
  554. log.Println("传感器下发参数", v)
  555. if client, ok := MqttServer.MqttCon.Get(mqttId); ok {
  556. err = MqttServer.MqttPublish(client, topicPub, msgBytes)
  557. if err != nil {
  558. if len(v.Data) > 0 {
  559. coldpServer := MqttServer.ClodpServer{
  560. Sn: v.Sn,
  561. T_id: v.Data[0].Id,
  562. IsTrue: 1,
  563. Sense: v.Data[0].Sense,
  564. Speed: v.Data[0].Speed,
  565. Types: 6,
  566. CreateTime: time.Now(),
  567. UpdateTime: time.Now(),
  568. }
  569. MqttServer.Add_ClodpServer(coldpServer)
  570. }
  571. c.Data["json"] = lib.JSONS{Code: 500, Msg: "传感器参数失败", Data: nil}
  572. c.ServeJSON()
  573. return
  574. } else {
  575. if len(v.Data) > 0 {
  576. time.Sleep(3 * time.Second)
  577. coldp, err := MqttServer.FindClodpServerBySnAndId(v.Sn, v.Data[0].Id, v.Type)
  578. if len(coldp.Sn) == 0 || err != nil {
  579. if len(v.Data) > 0 {
  580. coldpServer := MqttServer.ClodpServer{
  581. Sn: v.Sn,
  582. T_id: v.Data[0].Id,
  583. IsTrue: 1,
  584. Sense: v.Data[0].Sense,
  585. Speed: v.Data[0].Speed,
  586. Types: 6,
  587. CreateTime: time.Now(),
  588. UpdateTime: time.Now(),
  589. }
  590. MqttServer.Add_ClodpServer(coldpServer)
  591. }
  592. c.Data["json"] = lib.JSONS{Code: 500, Msg: "读取传感器参数失败", Data: nil}
  593. c.ServeJSON()
  594. return
  595. }
  596. if len(v.Data) > 0 && (v.Data[0].Speed != coldp.Speed || v.Data[0].Sense != coldp.Sense) {
  597. coldp.Sense = v.Data[0].Sense
  598. coldp.Speed = v.Data[0].Speed
  599. coldp.IsTrue = 1
  600. clos = append(clos, "speed")
  601. clos = append(clos, "sense")
  602. clos = append(clos, "is_true")
  603. MqttServer.Update_ClodpServer(coldp, clos...)
  604. }
  605. c.Data["json"] = lib.JSONS{Code: 200, Msg: "偏差值上传成功", Data: coldp}
  606. c.ServeJSON()
  607. return
  608. }
  609. }
  610. }
  611. }
  612. }
  613. // 列表 -
  614. func (c *DeviceController) DeviceWarning_List_html() {
  615. // 验证登录
  616. b_, admin_r := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  617. if !b_ {
  618. c.Data["json"] = lib.JSONS{Code: 201, Msg: "User_tokey Err!"}
  619. c.ServeJSON()
  620. return
  621. }
  622. c.Data["Admin_r"] = admin_r
  623. page, _ := c.GetInt("page")
  624. println(page)
  625. if page < 1 {
  626. page = 1
  627. }
  628. c.Data["Admin_r"] = admin_r
  629. bindSN := c.GetStrings("bindSN")
  630. tpList := c.GetStrings("tpList")
  631. T_sn := c.GetString("T_sn")
  632. if len(T_sn) != 0 {
  633. bindSN = append(bindSN, T_sn)
  634. c.Data["T_sn"] = T_sn
  635. }
  636. Time_start := c.GetString("Time_start")
  637. Time_end := c.GetString("Time_end")
  638. if len(Time_start) == 0 && len(Time_end) == 0 {
  639. Time_start = time.Now().Format("2006-01-02") + " 00:00:00"
  640. Time_end = time.Now().Format("2006-01-02") + " 23:59:59"
  641. }
  642. c.Data["Time_start"] = Time_start
  643. c.Data["Time_end"] = Time_end
  644. //c.Data["Class_List"] = Device.Read_DeviceWarningList_All_1()
  645. //T_Title := ""
  646. //if Class_1 > 0 {
  647. // T_Title = Device.Read_DeviceWarningList_ById(Class_1).T_name
  648. //}
  649. pageSize := c.GetString("pageSize", "100")
  650. pageSizeInt, _ := strconv.Atoi(pageSize)
  651. //atoi, _ := strconv.Atoi(pageSizes.PageSize)
  652. getString := c.GetString("t_tp")
  653. t_tp, _ := strconv.Atoi(getString)
  654. var cnt int64
  655. DeviceWarning_List, cnt := Warning.Read_Warning_List(admin_r.T_pid, bindSN, tpList, Time_start, Time_end, t_tp, page, pageSizeInt)
  656. c.Data["List"] = DeviceWarning_List
  657. page_size := math.Ceil(float64(cnt) / float64(pageSizeInt))
  658. c.Data["Page"] = page
  659. c.Data["Page_size"] = page_size
  660. c.Data["Pages"] = lib.Func_page(int64(page), int64(page_size))
  661. c.Data["cnt"] = cnt
  662. // 将sync.Map中的数据转存到切片中
  663. c.TplName = "Device/DeviceWarning.html"
  664. }
  665. // GetWarningtype 获取报警类型
  666. func (c *DeviceController) GetWarningtype() {
  667. var results []struct {
  668. Key int
  669. Value string
  670. }
  671. Warning.WarningType_list.Range(func(key, value any) bool {
  672. // 确保类型断言成功
  673. if k, ok := key.(int); ok {
  674. if v, ok := value.(string); ok {
  675. // 创建匿名结构体实例并添加到切片
  676. results = append(results, struct {
  677. Key int
  678. Value string
  679. }{Key: k, Value: v})
  680. } else {
  681. fmt.Println("Value is not of type string")
  682. }
  683. } else {
  684. fmt.Println("Key is not of type int")
  685. }
  686. return true // 继续遍历
  687. })
  688. c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!", Data: results}
  689. c.ServeJSON()
  690. log.Println(results)
  691. }
  692. func (c *DeviceController) DeviceWarning_() {
  693. // 验证登录
  694. //b_, admin_r := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  695. //if !b_ {
  696. // c.Data["json"] = lib.JSONS{Code: 201, Msg: "User_tokey Err!"}
  697. // c.ServeJSON()
  698. // return
  699. //}
  700. c.Data["WarningType"] = Warning.Read_WarningType_All()
  701. c.TplName = "Device/DeviceWarning-.html"
  702. }
  703. // DeviceWarning_Post 添加报警
  704. func (c *DeviceController) DeviceWarning_Post() {
  705. // 验证登录
  706. b_, admin_r := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  707. if !b_ {
  708. c.Ctx.Redirect(302, "Login")
  709. return
  710. }
  711. T_tp, _ := c.GetInt("T_tp")
  712. T_sn := c.GetString("T_sn")
  713. T_id, _ := c.GetInt("T_id")
  714. T_Ut := c.GetString("T_Ut")
  715. T_Remark := c.GetString("T_Remark")
  716. r_Device, err := Device.Read_Device_ByT_sn(T_sn)
  717. if err != nil {
  718. c.Data["json"] = lib.JSONS{Code: 201, Msg: "E!", Data: "SN 错误!!!"}
  719. c.ServeJSON()
  720. return
  721. }
  722. // 获取 传感器 参数
  723. DeviceSensor_r, is := Device.Read_DeviceSensor_ByT_sn(r_Device.T_sn, T_id)
  724. if !is {
  725. c.Data["json"] = lib.JSONS{Code: 201, Msg: "E!", Data: "编号 错误!!!"}
  726. c.ServeJSON()
  727. return
  728. }
  729. t1, _ := time.ParseInLocation("2006-01-02 15:04:05", T_Ut, time.Local) // +8 时差
  730. t_c := Warning.Warning{
  731. T_pid: admin_r.T_pid,
  732. T_tp: T_tp,
  733. T_sn: T_sn,
  734. T_D_name: r_Device.T_devName,
  735. T_id: T_id,
  736. T_DS_name: DeviceSensor_r.T_name,
  737. T_Ut: t1,
  738. T_State: 1,
  739. T_Remark: T_Remark,
  740. }
  741. Warning.Add_Warning(t_c)
  742. c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!"}
  743. c.ServeJSON()
  744. return
  745. }
  746. // DeviceWarning_Del 删除报警
  747. func (c *DeviceController) DeviceWarning_Del() {
  748. // 验证登录
  749. b_, admin_r := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  750. if !b_ {
  751. c.Ctx.Redirect(302, "Login")
  752. return
  753. }
  754. Id, _ := c.GetInt("Id")
  755. if Id > 1000 {
  756. Warning.Delete_Warning(admin_r.T_pid, Id)
  757. }
  758. c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!"}
  759. c.ServeJSON()
  760. return
  761. }
  762. // DeviceWarning_DelS 批量删除
  763. func (c *DeviceController) DeviceWarning_DelS() {
  764. // 验证登录
  765. b_, admin_r := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  766. if !b_ {
  767. c.Ctx.Redirect(302, "Login")
  768. return
  769. }
  770. type SelectedItem struct {
  771. Id string `json:"id"`
  772. Ut string `json:"ut"` // 假设"ut"字段是时间戳字符串
  773. }
  774. type SelectedItems struct {
  775. SelectedIds []SelectedItem `json:"selectedIds"`
  776. }
  777. var SelectedIds SelectedItems
  778. //var selectedIds map[string]any
  779. err := json.Unmarshal(c.Ctx.Input.RequestBody, &SelectedIds)
  780. log.Println(SelectedIds.SelectedIds)
  781. for _, v := range SelectedIds.SelectedIds {
  782. Warning.Delete_Warning_List(v.Id, v.Ut, admin_r.T_pid)
  783. }
  784. if err != nil {
  785. c.Data["json"] = lib.JSONS{Code: 201, Msg: "E!", Data: "数据格式错误!!!"}
  786. c.ServeJSON()
  787. } else {
  788. c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!"}
  789. c.ServeJSON()
  790. }
  791. }
  792. // Device_Copy 复制并添加
  793. func (c *DeviceController) Device_Copy() {
  794. // 验证登录
  795. b_, _ := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  796. if !b_ {
  797. c.Ctx.Redirect(302, "Login")
  798. return
  799. }
  800. type T_data struct {
  801. T_sn string `json:"t_sn"`
  802. T_id int `json:"t_id"`
  803. T_Rh any `json:"t_rh"`
  804. T_Site string `json:"t_site"`
  805. T_T any `json:"t_t"`
  806. CreateTime string `json:"createTime"`
  807. }
  808. var data T_data
  809. json.Unmarshal(c.Ctx.Input.RequestBody, &data)
  810. r := Device.Read_DeviceParameter_SNNo(data.T_sn)
  811. parse, _ := time.Parse("2006-01-02 15:04:05", data.CreateTime)
  812. data.CreateTime = parse.Add(time.Duration(r[0].T_saveT) * time.Second).Format("2006-01-02 15:04:05")
  813. itoa := strconv.Itoa(data.T_id)
  814. Device.Copy_DeviceData(data.T_sn, itoa, data.T_Rh, data.T_T, data.T_Site, data.CreateTime)
  815. c.Data["json"] = lib.JSONS{Code: 200, Msg: "设置成功", Data: data}
  816. c.ServeJSON()
  817. }
  818. // DeviceWarningUpdate 修改报警
  819. func (c *DeviceController) DeviceWarningUpdate() {
  820. // 验证登录
  821. b_, admin_r := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  822. if !b_ {
  823. c.Ctx.Redirect(302, "Login")
  824. return
  825. }
  826. var data struct {
  827. ColumnName string `json:"columnName"`
  828. NewValue string `json:"newValue"`
  829. RowId string `json:"rowId"`
  830. T_Ut string `json:"T_Ut"`
  831. SN string `json:"sn"`
  832. }
  833. json.Unmarshal(c.Ctx.Input.RequestBody, &data)
  834. log.Println(admin_r.T_pid)
  835. Warning.Update_DeviceParameter_Warning(data.ColumnName, data.NewValue, data.RowId, data.T_Ut)
  836. c.Data["json"] = lib.JSONS{Code: 200, Msg: "设置成功", Data: data}
  837. c.ServeJSON()
  838. }
  839. // GetDeviceALLSN 根据pid获取所有sn
  840. func (c *DeviceController) GetDeviceALLSN() {
  841. // 验证登录
  842. b_, admin_r := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  843. if !b_ {
  844. c.Ctx.Redirect(302, "Login")
  845. return
  846. }
  847. r := Device.Read_Device_All_SN(admin_r.T_pid)
  848. log.Println(r)
  849. c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!", Data: r}
  850. c.ServeJSON()
  851. }
  852. // GetDeviceALLTID 根据SN获取所有探头
  853. func (c *DeviceController) GetDeviceALLTID() {
  854. // 验证登录
  855. b_, _ := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  856. if !b_ {
  857. c.Ctx.Redirect(302, "Login")
  858. return
  859. }
  860. getString := c.GetString("sn")
  861. r := Device.Get_DeviceSensor_Tid_ByT_sn(getString)
  862. c.Data["json"] = lib.JSONS{Code: 200, Msg: "设置成功", Data: r}
  863. c.ServeJSON()
  864. }
  865. // DeviceWarningAdd 复制添加报警
  866. func (c *DeviceController) DeviceWarningAdd() {
  867. // 验证登录
  868. b_, admin_r := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  869. if !b_ {
  870. c.Ctx.Redirect(302, "Login")
  871. return
  872. }
  873. var data struct {
  874. T_tp_name string `json:"column1"`
  875. T__d_name string `json:"column2"`
  876. T_DS_name string `json:"column3"`
  877. T_Remark string `json:"column4"`
  878. T_State string `json:"column5"`
  879. T_Ut string `json:"column6"`
  880. RowId string `json:"rowId"`
  881. SN string `json:"sn"`
  882. T_id string `json:"t_id"`
  883. }
  884. json.Unmarshal(c.Ctx.Input.RequestBody, &data)
  885. atoi, _ := strconv.Atoi(data.T_id)
  886. r_Device, err := Device.Read_Device_ByT_sn(data.SN)
  887. if err != nil {
  888. c.Data["json"] = lib.JSONS{Code: 201, Msg: "E!", Data: "SN 错误!!!"}
  889. c.ServeJSON()
  890. return
  891. }
  892. T_tp := Warning.Read_WarningType(data.T_tp_name)
  893. t1, _ := time.ParseInLocation("2006-01-02 15:04:05", data.T_Ut, time.Local) // +8 时差
  894. t_c := Warning.Warning{
  895. T_pid: admin_r.T_pid,
  896. T_tp: T_tp,
  897. T_sn: data.SN,
  898. T_D_name: r_Device.T_devName,
  899. T_id: atoi,
  900. T_DS_name: data.T_DS_name,
  901. T_Ut: t1,
  902. T_State: 1,
  903. T_Remark: data.T_Remark,
  904. }
  905. Warning.Add_Warning(t_c)
  906. c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!"}
  907. c.ServeJSON()
  908. return
  909. }
  910. // SiftWarningType 根据报警类型筛选
  911. func (c *DeviceController) SiftWarningType() {
  912. // 验证登录
  913. b_, _ := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  914. if !b_ {
  915. c.Ctx.Redirect(302, "Login")
  916. return
  917. }
  918. }