DeviceController.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975
  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. "io"
  13. "log"
  14. "math"
  15. "strconv"
  16. "strings"
  17. "sync"
  18. "time"
  19. beego "github.com/beego/beego/v2/server/web"
  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_, admin_r := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  242. // 账号(T_name) 和 用户ID(T_id)。
  243. logs.Println("WriteDeviation1 日志 - 账号: %s, 用户ID: %v", admin_r.T_name, admin_r.Id)
  244. if !b_ {
  245. c.Data["json"] = lib.JSONS{Code: 201, Msg: "User_tokey Err!"}
  246. c.ServeJSON()
  247. return
  248. }
  249. bytes, _ := io.ReadAll(c.Ctx.Request.Body)
  250. data := make([]MqttServer.Deviation_Sub, 0)
  251. if err := json.Unmarshal(bytes, &data); err != nil {
  252. log.Printf("Error unmarshalling JSON: %v", err)
  253. c.Data["json"] = lib.JSONS{Code: 400, Msg: "mqtt请求失败"}
  254. c.ServeJSON()
  255. return
  256. }
  257. var wg sync.WaitGroup
  258. successfulSns := make(map[string]bool) // 记录成功的SN
  259. mutex := &sync.Mutex{} // 保护对successfulSns的访问
  260. failSn := make([]string, 0)
  261. handleResult := func(sn string, success bool) {
  262. mutex.Lock()
  263. defer mutex.Unlock()
  264. if success {
  265. successfulSns[sn] = true
  266. } else {
  267. failSn = append(failSn, sn)
  268. }
  269. }
  270. // 处理每个设备的数据
  271. for _, v := range data {
  272. // 输出 账号 和 目标设备 SN
  273. logs.Println("WriteDeviation2 日志 - 账号: %s,用户ID: %v 目标设备SN: %s", admin_r.T_name, admin_r.Id, v.Sn)
  274. wg.Add(1)
  275. go func(v MqttServer.Deviation_Sub) {
  276. defer wg.Done()
  277. v.Type = 8
  278. v.Mid = int64(int(time.Now().Unix()))
  279. mqttId := Device.ReadDeviceMqttId(v.Sn)
  280. topicPub := fmt.Sprintf("/pub/%s", v.Sn)
  281. msgBytes, err := json.Marshal(v)
  282. if err != nil {
  283. log.Printf("Error marshalling JSON for SN: %s, %v", v.Sn, err)
  284. handleResult(v.Sn, false)
  285. return
  286. }
  287. if len(mqttId) != 0 {
  288. clos := make([]string, 0)
  289. if client, ok := MqttServer.MqttCon.Get(mqttId); ok {
  290. err = MqttServer.MqttPublish(client, topicPub, msgBytes)
  291. var cold MqttServer.ClodpServer
  292. if err != nil {
  293. cold.Sn = v.Sn
  294. cold.T_id = v.Data[0].Id
  295. cold.T_h = v.Data[0].H
  296. cold.T_t = v.Data[0].T
  297. cold.IsTrue = 1
  298. cold.Types = 8
  299. cold.CreateTime = time.Now()
  300. cold.UpdateTime = time.Now()
  301. err := MqttServer.Add_ClodpServer(cold)
  302. if err != nil {
  303. logs.Error("设置参数失败", err)
  304. }
  305. failSn = append(failSn, v.Sn)
  306. }
  307. time.Sleep(3 * time.Second)
  308. if len(v.Data) > 0 {
  309. coldp, err := MqttServer.FindClodpServerBySnAndId(v.Sn, v.Data[0].Id, 8)
  310. if err != nil {
  311. failSn = append(failSn, v.Sn)
  312. }
  313. if len(coldp.Sn) == 0 {
  314. coldp.Sn = v.Sn
  315. coldp.T_id = v.Data[0].Id
  316. coldp.T_h = v.Data[0].H
  317. coldp.T_t = v.Data[0].T
  318. coldp.IsTrue = 1
  319. coldp.Types = 8
  320. coldp.CreateTime = time.Now()
  321. coldp.UpdateTime = time.Now()
  322. err := MqttServer.Add_ClodpServer(coldp)
  323. if err != nil {
  324. logs.Error("设置参数失败", err)
  325. }
  326. failSn = append(failSn, v.Sn)
  327. }
  328. if coldp.T_h != v.Data[0].H || coldp.T_t != v.Data[0].T {
  329. coldp.T_h = v.Data[0].H
  330. coldp.T_t = v.Data[0].T
  331. coldp.IsTrue = 1
  332. clos = append(clos, "t_t")
  333. clos = append(clos, "t_h")
  334. clos = append(clos, "is_true")
  335. MqttServer.Update_ClodpServer(coldp, clos...)
  336. }
  337. }
  338. }
  339. }
  340. }(v)
  341. }
  342. wg.Wait()
  343. if len(failSn) > 0 {
  344. c.Data["json"] = lib.JSONS{Code: 1201, Msg: "部分设置失败", Data: failSn}
  345. } else {
  346. c.Data["json"] = lib.JSONS{Code: 200, Msg: "设置偏差值成功!", Data: nil}
  347. }
  348. c.ServeJSON()
  349. }
  350. // WriteDeviationAll 批量设置偏差值
  351. func (c *DeviceController) WriteDeviationAll() {
  352. b_, _ := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  353. if !b_ {
  354. c.Data["json"] = lib.JSONS{Code: 201, Msg: "User_tokey Err!"}
  355. c.ServeJSON()
  356. return
  357. }
  358. bytes, _ := io.ReadAll(c.Ctx.Request.Body)
  359. fmt.Println("请求json:", string(bytes))
  360. var data MqttServer.Deviation_SubAll
  361. if err := json.Unmarshal(bytes, &data); err != nil {
  362. log.Printf("Error unmarshalling JSON: %v", err)
  363. c.Data["json"] = lib.JSONS{Code: 400, Msg: "mqtt请求失败"}
  364. c.ServeJSON()
  365. return
  366. }
  367. var wg sync.WaitGroup
  368. successfulSns := make(map[string]bool) // 记录成功的SN
  369. mutex := &sync.Mutex{} // 保护对successfulSns的访问
  370. failSn := make([]string, 0)
  371. handleResult := func(sn string, success bool) {
  372. mutex.Lock()
  373. defer mutex.Unlock()
  374. if success {
  375. successfulSns[sn] = true
  376. } else {
  377. failSn = append(failSn, sn)
  378. }
  379. }
  380. // 处理每个设备的数据
  381. for i, sn := range data.Sn {
  382. subData := data.Data[i]
  383. wg.Add(1)
  384. go func(sn string, subData MqttServer.Deviation_Sub_Data) {
  385. defer wg.Done()
  386. sub_data := make([]MqttServer.Deviation_Sub_Data, 0)
  387. sub_data = append(sub_data, subData)
  388. v := MqttServer.Deviation_Sub{
  389. Type: 8,
  390. Sn: sn,
  391. Mid: int64(int(time.Now().Unix())),
  392. Data: sub_data,
  393. }
  394. mqttId := Device.ReadDeviceMqttId(v.Sn)
  395. topicPub := fmt.Sprintf("/pub/%s", v.Sn)
  396. msgBytes, err := json.Marshal(v)
  397. if len(mqttId) != 0 {
  398. clos := make([]string, 0)
  399. if client, ok := MqttServer.MqttCon.Get(mqttId); ok {
  400. err = MqttServer.MqttPublish(client, topicPub, msgBytes)
  401. var cold MqttServer.ClodpServer
  402. if err != nil {
  403. cold.Sn = v.Sn
  404. cold.T_id = v.Data[0].Id
  405. cold.T_h = v.Data[0].H
  406. cold.T_t = v.Data[0].T
  407. cold.IsTrue = 1
  408. cold.Types = 8
  409. cold.CreateTime = time.Now()
  410. cold.UpdateTime = time.Now()
  411. err := MqttServer.Add_ClodpServer(cold)
  412. if err != nil {
  413. logs.Error("设置参数失败", err)
  414. }
  415. handleResult(v.Sn, false)
  416. }
  417. time.Sleep(3 * time.Second)
  418. if len(v.Data) > 0 {
  419. coldp, err := MqttServer.FindClodpServerBySnAndId(v.Sn, v.Data[0].Id, 8)
  420. log.Println("得到参数", coldp)
  421. if err != nil {
  422. failSn = append(failSn, v.Sn)
  423. }
  424. if len(coldp.Sn) == 0 {
  425. coldp.Sn = v.Sn
  426. coldp.T_id = v.Data[0].Id
  427. coldp.T_h = v.Data[0].H
  428. coldp.T_t = v.Data[0].T
  429. coldp.IsTrue = 1
  430. coldp.Types = 8
  431. coldp.CreateTime = time.Now()
  432. coldp.UpdateTime = time.Now()
  433. err := MqttServer.Add_ClodpServer(coldp)
  434. if err != nil {
  435. logs.Error("设置参数失败", err)
  436. }
  437. handleResult(v.Sn, false)
  438. }
  439. if coldp.T_h != v.Data[0].H || coldp.T_t != v.Data[0].T {
  440. coldp.T_h = v.Data[0].H
  441. coldp.T_t = v.Data[0].T
  442. coldp.IsTrue = 1
  443. clos = append(clos, "t_t")
  444. clos = append(clos, "t_h")
  445. clos = append(clos, "is_true")
  446. MqttServer.Update_ClodpServer(coldp, clos...)
  447. handleResult(v.Sn, false)
  448. }
  449. }
  450. }
  451. }
  452. }(sn, subData)
  453. }
  454. wg.Wait()
  455. if len(failSn) > 0 {
  456. c.Data["json"] = lib.JSONS{Code: 1201, Msg: "部分设置失败", Data: failSn}
  457. } else {
  458. c.Data["json"] = lib.JSONS{Code: 200, Msg: "设置偏差值成功!", Data: nil}
  459. }
  460. c.ServeJSON()
  461. }
  462. // ReadSensor 读取传感器参数
  463. func (c *DeviceController) ReadSensor() {
  464. b_, _ := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  465. if !b_ {
  466. c.Data["json"] = lib.JSONS{Code: 201, Msg: "User_tokey Err!"}
  467. c.ServeJSON()
  468. return
  469. }
  470. t := make(map[string][]int)
  471. bytes, _ := io.ReadAll(c.Ctx.Request.Body)
  472. if err := json.Unmarshal(bytes, &t); err != nil {
  473. log.Printf("Error unmarshalling JSON: %v", err)
  474. c.Data["json"] = lib.JSONS{Code: 400, Msg: "Bad Request"}
  475. c.ServeJSON()
  476. return
  477. }
  478. fmt.Println("浏览器接收数据:", t)
  479. for k, v := range t {
  480. topicPub := fmt.Sprintf("/pub/%s", k)
  481. mqttId := Device.ReadDeviceMqttId(k)
  482. pubData, err := json.Marshal(MqttServer.Deviation_Pub{
  483. Sn: k,
  484. Type: 5,
  485. Mid: time.Now().Unix(),
  486. Data: v,
  487. })
  488. if err != nil {
  489. logs.Error("json序列化失败")
  490. }
  491. if len(mqttId) != 0 {
  492. if client, ok := MqttServer.MqttCon.Get(mqttId); ok {
  493. err = MqttServer.MqttPublish(client, topicPub, pubData)
  494. if err != nil {
  495. logs.Error("发送失败")
  496. c.Data["json"] = lib.JSONS{Code: 200, Msg: "读取传感器参数失败", Data: nil}
  497. c.ServeJSON()
  498. return
  499. } else {
  500. if len(v) > 0 {
  501. time.Sleep(3 * time.Second)
  502. coldp, err := MqttServer.FindClodpServerBySnAndId(k, v[0], 6)
  503. if err != nil {
  504. logs.Error("发送失败")
  505. c.Data["json"] = lib.JSONS{Code: 500, Msg: "读取传感器参数失败", Data: nil}
  506. c.ServeJSON()
  507. return
  508. }
  509. if len(coldp.Sn) == 0 {
  510. logs.Error("发送失败")
  511. c.Data["json"] = lib.JSONS{Code: 500, Msg: "读取传感器参数失败", Data: nil}
  512. c.ServeJSON()
  513. return
  514. }
  515. c.Data["json"] = lib.JSONS{Code: 200, Msg: "偏差值上传成功", Data: coldp}
  516. c.ServeJSON()
  517. return
  518. }
  519. }
  520. }
  521. }
  522. }
  523. }
  524. // WriteSensor 设置传感器参数
  525. func (c *DeviceController) WriteSensor() {
  526. b_, _ := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  527. if !b_ {
  528. c.Data["json"] = lib.JSONS{Code: 201, Msg: "User_tokey Err!"}
  529. c.ServeJSON()
  530. return
  531. }
  532. bytes, err := io.ReadAll(c.Ctx.Request.Body)
  533. if err != nil {
  534. log.Printf("Error reading request body: %v", err)
  535. c.Data["json"] = lib.JSONS{Code: 500, Msg: "Internal Server Error"}
  536. c.ServeJSON()
  537. return
  538. }
  539. fmt.Println("请求json:", string(bytes))
  540. clos := make([]string, 0)
  541. data := make([]MqttServer.Sensor_Sub, 0)
  542. if err := json.Unmarshal(bytes, &data); err != nil {
  543. log.Printf("Error unmarshalling JSON: %v", err)
  544. c.Data["json"] = lib.JSONS{Code: 400, Msg: "Bad Request"}
  545. c.ServeJSON()
  546. return
  547. }
  548. for _, v := range data {
  549. mqttId := Device.ReadDeviceMqttId(v.Sn)
  550. topicPub := fmt.Sprintf("/pub/%s", v.Sn)
  551. v.Type = 6
  552. v.Mid = int(time.Now().Unix())
  553. msgBytes, err := json.Marshal(v)
  554. if err != nil {
  555. log.Printf("Error marshalling JSON for SN: %s, %v", v.Sn, err)
  556. return
  557. }
  558. log.Println("传感器下发参数", v)
  559. if client, ok := MqttServer.MqttCon.Get(mqttId); ok {
  560. err = MqttServer.MqttPublish(client, topicPub, msgBytes)
  561. if err != nil {
  562. if len(v.Data) > 0 {
  563. coldpServer := MqttServer.ClodpServer{
  564. Sn: v.Sn,
  565. T_id: v.Data[0].Id,
  566. IsTrue: 1,
  567. Sense: v.Data[0].Sense,
  568. Speed: v.Data[0].Speed,
  569. Types: 6,
  570. CreateTime: time.Now(),
  571. UpdateTime: time.Now(),
  572. }
  573. MqttServer.Add_ClodpServer(coldpServer)
  574. }
  575. c.Data["json"] = lib.JSONS{Code: 500, Msg: "传感器参数失败", Data: nil}
  576. c.ServeJSON()
  577. return
  578. } else {
  579. if len(v.Data) > 0 {
  580. time.Sleep(3 * time.Second)
  581. coldp, err := MqttServer.FindClodpServerBySnAndId(v.Sn, v.Data[0].Id, v.Type)
  582. if len(coldp.Sn) == 0 || err != nil {
  583. if len(v.Data) > 0 {
  584. coldpServer := MqttServer.ClodpServer{
  585. Sn: v.Sn,
  586. T_id: v.Data[0].Id,
  587. IsTrue: 1,
  588. Sense: v.Data[0].Sense,
  589. Speed: v.Data[0].Speed,
  590. Types: 6,
  591. CreateTime: time.Now(),
  592. UpdateTime: time.Now(),
  593. }
  594. MqttServer.Add_ClodpServer(coldpServer)
  595. }
  596. c.Data["json"] = lib.JSONS{Code: 500, Msg: "读取传感器参数失败", Data: nil}
  597. c.ServeJSON()
  598. return
  599. }
  600. if len(v.Data) > 0 && (v.Data[0].Speed != coldp.Speed || v.Data[0].Sense != coldp.Sense) {
  601. coldp.Sense = v.Data[0].Sense
  602. coldp.Speed = v.Data[0].Speed
  603. coldp.IsTrue = 1
  604. clos = append(clos, "speed")
  605. clos = append(clos, "sense")
  606. clos = append(clos, "is_true")
  607. MqttServer.Update_ClodpServer(coldp, clos...)
  608. }
  609. c.Data["json"] = lib.JSONS{Code: 200, Msg: "偏差值上传成功", Data: coldp}
  610. c.ServeJSON()
  611. return
  612. }
  613. }
  614. }
  615. }
  616. }
  617. // 列表 -
  618. func (c *DeviceController) DeviceWarning_List_html() {
  619. // 验证登录
  620. b_, admin_r := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  621. if !b_ {
  622. c.Data["json"] = lib.JSONS{Code: 201, Msg: "User_tokey Err!"}
  623. c.ServeJSON()
  624. return
  625. }
  626. c.Data["Admin_r"] = admin_r
  627. page, _ := c.GetInt("page")
  628. println(page)
  629. if page < 1 {
  630. page = 1
  631. }
  632. c.Data["Admin_r"] = admin_r
  633. bindSN := c.GetStrings("bindSN")
  634. tpList := c.GetStrings("tpList")
  635. T_sn := c.GetString("T_sn")
  636. if len(T_sn) != 0 {
  637. bindSN = append(bindSN, T_sn)
  638. c.Data["T_sn"] = T_sn
  639. }
  640. Time_start := c.GetString("Time_start")
  641. Time_end := c.GetString("Time_end")
  642. if len(Time_start) == 0 && len(Time_end) == 0 {
  643. Time_start = time.Now().Format("2006-01-02") + " 00:00:00"
  644. Time_end = time.Now().Format("2006-01-02") + " 23:59:59"
  645. }
  646. c.Data["Time_start"] = Time_start
  647. c.Data["Time_end"] = Time_end
  648. //c.Data["Class_List"] = Device.Read_DeviceWarningList_All_1()
  649. //T_Title := ""
  650. //if Class_1 > 0 {
  651. // T_Title = Device.Read_DeviceWarningList_ById(Class_1).T_name
  652. //}
  653. pageSize := c.GetString("pageSize", "100")
  654. pageSizeInt, _ := strconv.Atoi(pageSize)
  655. //atoi, _ := strconv.Atoi(pageSizes.PageSize)
  656. getString := c.GetString("t_tp")
  657. t_tp, _ := strconv.Atoi(getString)
  658. var cnt int64
  659. DeviceWarning_List, cnt := Warning.Read_Warning_List(admin_r.T_pid, bindSN, tpList, Time_start, Time_end, t_tp, page, pageSizeInt)
  660. c.Data["List"] = DeviceWarning_List
  661. page_size := math.Ceil(float64(cnt) / float64(pageSizeInt))
  662. c.Data["Page"] = page
  663. c.Data["Page_size"] = page_size
  664. c.Data["Pages"] = lib.Func_page(int64(page), int64(page_size))
  665. c.Data["cnt"] = cnt
  666. // 将sync.Map中的数据转存到切片中
  667. c.TplName = "Device/DeviceWarning.html"
  668. }
  669. // GetWarningtype 获取报警类型
  670. func (c *DeviceController) GetWarningtype() {
  671. var results []struct {
  672. Key int
  673. Value string
  674. }
  675. Warning.WarningType_list.Range(func(key, value any) bool {
  676. // 确保类型断言成功
  677. if k, ok := key.(int); ok {
  678. if v, ok := value.(string); ok {
  679. // 创建匿名结构体实例并添加到切片
  680. results = append(results, struct {
  681. Key int
  682. Value string
  683. }{Key: k, Value: v})
  684. } else {
  685. fmt.Println("Value is not of type string")
  686. }
  687. } else {
  688. fmt.Println("Key is not of type int")
  689. }
  690. return true // 继续遍历
  691. })
  692. c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!", Data: results}
  693. c.ServeJSON()
  694. log.Println(results)
  695. }
  696. func (c *DeviceController) DeviceWarning_() {
  697. // 验证登录
  698. //b_, admin_r := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  699. //if !b_ {
  700. // c.Data["json"] = lib.JSONS{Code: 201, Msg: "User_tokey Err!"}
  701. // c.ServeJSON()
  702. // return
  703. //}
  704. c.Data["WarningType"] = Warning.Read_WarningType_All()
  705. c.TplName = "Device/DeviceWarning-.html"
  706. }
  707. // DeviceWarning_Post 添加报警
  708. func (c *DeviceController) DeviceWarning_Post() {
  709. // 验证登录
  710. b_, admin_r := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  711. if !b_ {
  712. c.Ctx.Redirect(302, "Login")
  713. return
  714. }
  715. T_tp, _ := c.GetInt("T_tp")
  716. T_sn := c.GetString("T_sn")
  717. T_id, _ := c.GetInt("T_id")
  718. T_Ut := c.GetString("T_Ut")
  719. T_Remark := c.GetString("T_Remark")
  720. r_Device, err := Device.Read_Device_ByT_sn(T_sn)
  721. if err != nil {
  722. c.Data["json"] = lib.JSONS{Code: 201, Msg: "E!", Data: "SN 错误!!!"}
  723. c.ServeJSON()
  724. return
  725. }
  726. // 获取 传感器 参数
  727. DeviceSensor_r, is := Device.Read_DeviceSensor_ByT_sn(r_Device.T_sn, T_id)
  728. if !is {
  729. c.Data["json"] = lib.JSONS{Code: 201, Msg: "E!", Data: "编号 错误!!!"}
  730. c.ServeJSON()
  731. return
  732. }
  733. t1, _ := time.ParseInLocation("2006-01-02 15:04:05", T_Ut, time.Local) // +8 时差
  734. t_c := Warning.Warning{
  735. T_pid: admin_r.T_pid,
  736. T_tp: T_tp,
  737. T_sn: T_sn,
  738. T_D_name: r_Device.T_devName,
  739. T_id: T_id,
  740. T_DS_name: DeviceSensor_r.T_name,
  741. T_Ut: t1,
  742. T_State: 1,
  743. T_Remark: T_Remark,
  744. }
  745. Warning.Add_Warning(t_c)
  746. c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!"}
  747. c.ServeJSON()
  748. return
  749. }
  750. // DeviceWarning_Del 删除报警
  751. func (c *DeviceController) DeviceWarning_Del() {
  752. // 验证登录
  753. b_, admin_r := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  754. if !b_ {
  755. c.Ctx.Redirect(302, "Login")
  756. return
  757. }
  758. Id, _ := c.GetInt("Id")
  759. Ut := c.GetString("Ut")
  760. if Id > 1000 && len(Ut) > 0 {
  761. Warning.Delete_Warning(admin_r.T_pid, Id, Ut)
  762. }
  763. c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!"}
  764. c.ServeJSON()
  765. return
  766. }
  767. // DeviceWarning_DelS 批量删除
  768. func (c *DeviceController) DeviceWarning_DelS() {
  769. // 验证登录
  770. b_, admin_r := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  771. if !b_ {
  772. c.Ctx.Redirect(302, "Login")
  773. return
  774. }
  775. type SelectedItem struct {
  776. Id string `json:"id"`
  777. Ut string `json:"ut"` // 假设"ut"字段是时间戳字符串
  778. }
  779. type SelectedItems struct {
  780. SelectedIds []SelectedItem `json:"selectedIds"`
  781. }
  782. var SelectedIds SelectedItems
  783. //var selectedIds map[string]any
  784. err := json.Unmarshal(c.Ctx.Input.RequestBody, &SelectedIds)
  785. log.Println(SelectedIds.SelectedIds)
  786. for _, v := range SelectedIds.SelectedIds {
  787. Warning.Delete_Warning_List(v.Id, v.Ut, admin_r.T_pid)
  788. }
  789. if err != nil {
  790. c.Data["json"] = lib.JSONS{Code: 201, Msg: "E!", Data: "数据格式错误!!!"}
  791. c.ServeJSON()
  792. } else {
  793. c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!"}
  794. c.ServeJSON()
  795. }
  796. }
  797. // Device_Copy 复制并添加
  798. func (c *DeviceController) Device_Copy() {
  799. // 验证登录
  800. b_, _ := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  801. if !b_ {
  802. c.Ctx.Redirect(302, "Login")
  803. return
  804. }
  805. type T_data struct {
  806. T_sn string `json:"t_sn"`
  807. T_id int `json:"t_id"`
  808. T_Rh any `json:"t_rh"`
  809. T_Site string `json:"t_site"`
  810. T_T any `json:"t_t"`
  811. CreateTime string `json:"createTime"`
  812. }
  813. var data T_data
  814. json.Unmarshal(c.Ctx.Input.RequestBody, &data)
  815. r := Device.Read_DeviceParameter_SNNo(data.T_sn)
  816. parse, _ := time.Parse("2006-01-02 15:04:05", data.CreateTime)
  817. data.CreateTime = parse.Add(time.Duration(r[0].T_saveT) * time.Second).Format("2006-01-02 15:04:05")
  818. itoa := strconv.Itoa(data.T_id)
  819. Device.Copy_DeviceData(data.T_sn, itoa, data.T_Rh, data.T_T, data.T_Site, data.CreateTime)
  820. c.Data["json"] = lib.JSONS{Code: 200, Msg: "设置成功", Data: data}
  821. c.ServeJSON()
  822. }
  823. // DeviceWarningUpdate 修改报警
  824. func (c *DeviceController) DeviceWarningUpdate() {
  825. // 验证登录
  826. b_, admin_r := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  827. if !b_ {
  828. c.Ctx.Redirect(302, "Login")
  829. return
  830. }
  831. var data struct {
  832. ColumnName string `json:"columnName"`
  833. NewValue string `json:"newValue"`
  834. RowId string `json:"rowId"`
  835. T_Ut string `json:"T_Ut"`
  836. SN string `json:"sn"`
  837. }
  838. json.Unmarshal(c.Ctx.Input.RequestBody, &data)
  839. log.Println(admin_r.T_pid)
  840. Warning.Update_DeviceParameter_Warning(data.ColumnName, data.NewValue, data.RowId, data.T_Ut)
  841. c.Data["json"] = lib.JSONS{Code: 200, Msg: "设置成功", Data: data}
  842. c.ServeJSON()
  843. }
  844. // GetDeviceALLSN 根据pid获取所有sn
  845. func (c *DeviceController) GetDeviceALLSN() {
  846. // 验证登录
  847. b_, admin_r := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  848. if !b_ {
  849. c.Ctx.Redirect(302, "Login")
  850. return
  851. }
  852. r := Device.Read_Device_All_SN(admin_r.T_pid)
  853. log.Println(r)
  854. c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!", Data: r}
  855. c.ServeJSON()
  856. }
  857. // GetDeviceALLTID 根据SN获取所有探头
  858. func (c *DeviceController) GetDeviceALLTID() {
  859. // 验证登录
  860. b_, _ := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  861. if !b_ {
  862. c.Ctx.Redirect(302, "Login")
  863. return
  864. }
  865. getString := c.GetString("sn")
  866. r := Device.Get_DeviceSensor_Tid_ByT_sn(getString)
  867. c.Data["json"] = lib.JSONS{Code: 200, Msg: "设置成功", Data: r}
  868. c.ServeJSON()
  869. }
  870. // DeviceWarningAdd 复制添加报警
  871. func (c *DeviceController) DeviceWarningAdd() {
  872. // 验证登录
  873. b_, admin_r := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  874. if !b_ {
  875. c.Ctx.Redirect(302, "Login")
  876. return
  877. }
  878. var data struct {
  879. T_tp_name string `json:"column1"`
  880. T__d_name string `json:"column2"`
  881. T_DS_name string `json:"column3"`
  882. T_Remark string `json:"column4"`
  883. T_State string `json:"column5"`
  884. T_Ut string `json:"column6"`
  885. RowId string `json:"rowId"`
  886. SN string `json:"sn"`
  887. T_id string `json:"t_id"`
  888. }
  889. json.Unmarshal(c.Ctx.Input.RequestBody, &data)
  890. atoi, _ := strconv.Atoi(data.T_id)
  891. r_Device, err := Device.Read_Device_ByT_sn(data.SN)
  892. if err != nil {
  893. c.Data["json"] = lib.JSONS{Code: 201, Msg: "E!", Data: "SN 错误!!!"}
  894. c.ServeJSON()
  895. return
  896. }
  897. T_tp := Warning.Read_WarningType(data.T_tp_name)
  898. t1, _ := time.ParseInLocation("2006-01-02 15:04:05", data.T_Ut, time.Local) // +8 时差
  899. t_c := Warning.Warning{
  900. T_pid: admin_r.T_pid,
  901. T_tp: T_tp,
  902. T_sn: data.SN,
  903. T_D_name: r_Device.T_devName,
  904. T_id: atoi,
  905. T_DS_name: data.T_DS_name,
  906. T_Ut: t1,
  907. T_State: 1,
  908. T_Remark: data.T_Remark,
  909. }
  910. Warning.Add_Warning(t_c)
  911. c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!"}
  912. c.ServeJSON()
  913. return
  914. }
  915. // SiftWarningType 根据报警类型筛选
  916. func (c *DeviceController) SiftWarningType() {
  917. // 验证登录
  918. b_, _ := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  919. if !b_ {
  920. c.Ctx.Redirect(302, "Login")
  921. return
  922. }
  923. }