Device.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. package controllers
  2. import (
  3. "AIOTCOER/Handle"
  4. "AIOTCOER/lib"
  5. "AIOTCOER/logs"
  6. "AIOTCOER/models/Device"
  7. "AIOTCOER/models/Product"
  8. "encoding/json"
  9. "fmt"
  10. beego "github.com/beego/beego/v2/server/web"
  11. "github.com/beego/beego/v2/server/web/context"
  12. "github.com/gorilla/websocket"
  13. "net/http"
  14. "strings"
  15. "time"
  16. )
  17. type DeviceController struct {
  18. beego.Controller
  19. }
  20. func (c *DeviceController) WS() {
  21. ws, err := upgrader.Upgrade(c.Ctx.ResponseWriter, c.Ctx.Request, nil)
  22. if err != nil {
  23. logs.Println("MySocketController:", err)
  24. }
  25. // 退出
  26. defer func() {
  27. lib.ClearSubscription(ws) // 清楚订阅
  28. ws.CloseHandler()
  29. }()
  30. // 这里是我用户的结构体,你可以按自己需要定义
  31. logs.Println("ws上线:", fmt.Sprintf("%p", ws))
  32. for {
  33. var msg RecvWs
  34. err := ws.ReadJSON(&msg)
  35. if err != nil {
  36. logs.Println("ReadJSON err:", err)
  37. if strings.Contains(err.Error(), "websocket: close 1005") {
  38. ws.Close()
  39. return
  40. }
  41. lib.WebsocketWriteJSON(ws, lib.JSONR{Code: lib.Error, Msg: "数据异常!"})
  42. continue
  43. }
  44. Device_r_ := Device.Device{T_sn: msg.Sn}
  45. if !Device_r_.Read_Tidy() {
  46. lib.WebsocketWriteJSON(ws, lib.JSONR{Code: lib.Error, Msg: "验证失败!"})
  47. continue
  48. }
  49. if len(Device_r_.T_ckey) != 0 {
  50. if Device_r_.T_ckey != msg.Password {
  51. lib.WebsocketWriteJSON(ws, lib.JSONR{Code: lib.Error, Msg: "验证失败 !"})
  52. continue
  53. }
  54. }
  55. // 1 订阅SN数据 2 解绑SN数据 3 项设备发送数据
  56. switch msg.Type {
  57. case 0: // 0 心跳
  58. lib.WebsocketWriteJSON(ws, lib.JSONR{Code: lib.Success, Msg: "ok!"})
  59. break
  60. case 1: // 1 订阅SN数据
  61. SubConn := []*websocket.Conn{}
  62. // 从map中读取数据
  63. val, ok := lib.WsSubClinets.Load(msg.Sn)
  64. if ok {
  65. SubConn = val.([]*websocket.Conn)
  66. }
  67. SubConn_is := true // 重复订阅 标签
  68. for _, v := range SubConn {
  69. if v == ws {
  70. fmt.Println("重复订阅:", fmt.Sprintf("%p", v), msg.Sn)
  71. SubConn_is = false
  72. lib.WebsocketWriteJSON(ws, lib.JSONR{Code: lib.Error, Msg: "重复订阅!"})
  73. break
  74. }
  75. }
  76. if SubConn_is { // 防止重复订阅
  77. SubConn = append(SubConn, ws)
  78. // 写入map
  79. lib.WsSubClinets.Store(msg.Sn, SubConn)
  80. }
  81. lib.WebsocketWriteJSON(ws, lib.JSONR{Code: lib.Success, Msg: "ok!"})
  82. case 2: // 2 解绑SN数据
  83. // 从map中读取数据
  84. val, ok := lib.WsSubClinets.Load(msg.Sn)
  85. if ok {
  86. SubConn := val.([]*websocket.Conn)
  87. for i, v := range SubConn {
  88. if v == ws {
  89. fmt.Println("删除订阅:", fmt.Sprintf("%p", v), msg.Sn)
  90. SubConn = append(SubConn[:i], SubConn[i+1:]...)
  91. lib.WsSubClinets.Store(msg.Sn, SubConn)
  92. break
  93. }
  94. }
  95. }
  96. lib.WebsocketWriteJSON(ws, lib.JSONR{Code: lib.Success, Msg: "ok!"})
  97. case 3: // 3 项设备发送数据
  98. json_str, _ := json.Marshal(msg.Json)
  99. err = Handle.PushHandle(&Device_r_, Device_r_.T_sn, string(json_str))
  100. if err != nil {
  101. lib.WebsocketWriteJSON(ws, lib.JSONR{Code: lib.Error, Msg: "e!", Data: err.Error()})
  102. break
  103. }
  104. default:
  105. lib.WebsocketWriteJSON(ws, lib.JSONR{Code: lib.Error, Msg: "Type 错误!"})
  106. break
  107. }
  108. }
  109. }
  110. func (c *DeviceController) SSE() {
  111. T_sn := c.GetString("T_sn")
  112. T_ckey := c.GetString("T_ckey")
  113. if len(T_sn) == 0 {
  114. c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_sn!"}
  115. c.ServeJSON()
  116. return
  117. }
  118. Device_r := Device.Device{T_sn: T_sn}
  119. if !Device_r.Read_Tidy() {
  120. c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "验证失败!"}
  121. c.ServeJSON()
  122. return
  123. }
  124. if len(Device_r.T_ckey) != 0 {
  125. if Device_r.T_ckey != T_ckey {
  126. c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "验证失败 !"}
  127. c.ServeJSON()
  128. return
  129. }
  130. }
  131. c.Ctx.ResponseWriter.Header().Set("Content-Type", "text/event-stream")
  132. c.Ctx.ResponseWriter.Header().Set("Cache-Control", "no-cache")
  133. c.Ctx.ResponseWriter.Header().Set("Connection", "keep-alive")
  134. //
  135. SubConn := []*context.Response{}
  136. // 从map中读取数据
  137. val, ok := lib.SseSubClinets.Load(Device_r.T_sn)
  138. if ok {
  139. SubConn = val.([]*context.Response)
  140. }
  141. SubConn = append(SubConn, c.Ctx.ResponseWriter)
  142. // 写入map
  143. lib.SseSubClinets.Store(Device_r.T_sn, SubConn)
  144. // 退出 删除订阅
  145. defer func() {
  146. // 从map中读取数据
  147. val, ok = lib.SseSubClinets.Load(Device_r.T_sn)
  148. if ok {
  149. SubConn = val.([]*context.Response)
  150. for i, v := range SubConn {
  151. if v == c.Ctx.ResponseWriter {
  152. fmt.Println("删除订阅:", fmt.Sprintf("%p", v), Device_r.T_sn)
  153. SubConn = append(SubConn[:i], SubConn[i+1:]...)
  154. lib.SseSubClinets.Store(Device_r.T_sn, SubConn)
  155. break
  156. }
  157. }
  158. }
  159. }()
  160. //data, _ := json.Marshal(Device_r.T_dataJson)
  161. //fmt.Println(string(data))
  162. lib.SseWriteJSON(c.Ctx.ResponseWriter,[]byte(Device_r.T_data))
  163. for true {
  164. // Sleep for 1 second before sending the next update
  165. time.Sleep(1 * time.Second)
  166. }
  167. // Close the connection
  168. c.Ctx.ResponseWriter.WriteHeader(http.StatusOK)
  169. }
  170. func (c *DeviceController) List() {
  171. PageIndex, _ := c.GetInt("PageIndex", 0)
  172. PageSize, _ := c.GetInt("PageSize", 10)
  173. Devicer := Device.Device{}
  174. c.ParseForm(&Devicer)
  175. ProductTyper := Product.ProductType{T_ProductID: Devicer.T_ProductID}
  176. if !ProductTyper.Read() {
  177. c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "ProductID E!"}
  178. c.ServeJSON()
  179. return
  180. }
  181. T_uuid := c.GetString("T_uuid")
  182. if T_uuid != ProductTyper.T_uuid {
  183. c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_uuid!"}
  184. c.ServeJSON()
  185. return
  186. }
  187. Device_r, Total := Devicer.Lists(PageIndex, PageSize)
  188. c.Data["json"] = lib.JSONR{Code: lib.Success, Msg: "ok!", Data: lib.C_Page(Device_r, PageIndex, PageSize, Total)}
  189. c.ServeJSON()
  190. return
  191. }
  192. func (c *DeviceController) Add() {
  193. // 验证秘钥
  194. ProductType_r := Product.ProductType{}
  195. c.ParseForm(&ProductType_r)
  196. ProductKey := ProductType_r.T_ProductKey
  197. fmt.Println(ProductType_r)
  198. fmt.Println("T_ProductID:",c.Ctx.Input.Query("T_ProductID"))
  199. if len(ProductType_r.T_ProductID) != 8 {
  200. c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_ProductID!"}
  201. c.ServeJSON()
  202. return
  203. }
  204. if !ProductType_r.Read() {
  205. c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_ProductID !"}
  206. c.ServeJSON()
  207. return
  208. }
  209. if ProductType_r.T_ProductKey != ProductKey {
  210. c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_ProductKey!"}
  211. c.ServeJSON()
  212. return
  213. }
  214. // 创建sn
  215. T_sn := c.GetString("T_sn")
  216. Device_r := Device.Device{T_ProductID: ProductType_r.T_ProductID, T_sn: T_sn}
  217. //
  218. CreateNum, _ := c.GetInt("T_CreateNum", 1)
  219. if CreateNum == 1 || len(Device_r.T_sn) >= 2 {
  220. // 单个
  221. if !Device_r.CreateSn(1) {
  222. c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_sn 重复!"}
  223. c.ServeJSON()
  224. return
  225. }
  226. c.Data["json"] = lib.JSONR{Code: lib.Success, Msg: "ok!", Data: map[string]string{"T_sn": Device_r.T_sn, "T_password": Device_r.T_password}}
  227. c.ServeJSON()
  228. return
  229. } else {
  230. // 多个
  231. var Device_List []map[string]string
  232. for i := 1; i <= CreateNum; i++ {
  233. Device_rr := Device_r
  234. Device_rr.CreateSn(i)
  235. Device_List = append(Device_List, map[string]string{"T_sn": Device_rr.T_sn, "T_password": Device_rr.T_password})
  236. }
  237. c.Data["json"] = lib.JSONR{Code: lib.Success, Msg: "ok!", Data: Device_List}
  238. c.ServeJSON()
  239. return
  240. }
  241. }
  242. func (c *DeviceController) Update() {
  243. Devicer := Device.Device{T_sn: c.GetString("T_sn")}
  244. if !Devicer.Read_Tidy() {
  245. c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "SN E!"}
  246. c.ServeJSON()
  247. return
  248. }
  249. if len(Devicer.T_ckey) != 0 {
  250. if Devicer.T_ckey != c.GetString("T_ckey") {
  251. c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_ckey E!"}
  252. c.ServeJSON()
  253. return
  254. }
  255. }
  256. if len(Devicer.T_ckey) != 0 {
  257. Devicer.T_RelayData = c.GetString("T_RelayData")
  258. if !Devicer.Update("T_RelayData") {
  259. c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "E!"}
  260. c.ServeJSON()
  261. return
  262. }
  263. }
  264. println("T_ckey:",Devicer.T_ckey)
  265. if len(Devicer.T_ckey) == 0 && len(c.GetString("T_ckey")) != 0{
  266. Devicer.T_ckey = c.GetString("T_ckey")
  267. Devicer.Update("T_ckey")
  268. }
  269. c.Data["json"] = lib.JSONR{Code: lib.Success, Msg: "ok!"}
  270. c.ServeJSON()
  271. return
  272. }
  273. //func (c *DeviceController) Activation() {
  274. //
  275. // if len(c.GetString("T_sn")) == 0 {
  276. // c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "SN E!"}
  277. // c.ServeJSON()
  278. // return
  279. // }
  280. //
  281. // Devicer := Device.Device{T_sn: c.GetString("T_sn")}
  282. //
  283. // if !Devicer.Read_Tidy() {
  284. // c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "SN E!"}
  285. // c.ServeJSON()
  286. // return
  287. // }
  288. //
  289. // fmt.Println("T_ckey:",len(Devicer.T_ckey))
  290. // if len(Devicer.T_ckey) != 0 {
  291. // c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "设备已激活!"}
  292. // c.ServeJSON()
  293. // return
  294. // }
  295. //
  296. // fmt.Println(Devicer)
  297. // Devicer.T_ckey = lib.GetRandstring(32, "", 1)
  298. //
  299. // if !Devicer.Update("T_ckey") {
  300. // c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "E!"}
  301. // c.ServeJSON()
  302. // return
  303. // }
  304. //
  305. // c.Data["json"] = lib.JSONR{Code: lib.Success, Msg: "ok!",Data: Devicer.T_ckey}
  306. // c.ServeJSON()
  307. // return
  308. //}
  309. func (c *DeviceController) Get() {
  310. Devicer := Device.Device{}
  311. c.ParseForm(&Devicer)
  312. if !Devicer.Read_Tidy() {
  313. c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "SN E!"}
  314. c.ServeJSON()
  315. return
  316. }
  317. if len(Devicer.T_ckey) != 0 {
  318. if Devicer.T_ckey != c.GetString("T_ckey") {
  319. c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_ckey E!"}
  320. c.ServeJSON()
  321. return
  322. }
  323. }
  324. c.Data["json"] = lib.JSONR{Code: lib.Success, Msg: "ok!", Data: Devicer}
  325. c.ServeJSON()
  326. return
  327. }
  328. func (c *DeviceController) Push() {
  329. Devicer := Device.Device{}
  330. c.ParseForm(&Devicer)
  331. T_data := c.GetString("T_data")
  332. if len(T_data) == 0 {
  333. c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_data E!"}
  334. c.ServeJSON()
  335. return
  336. }
  337. if !Devicer.Read_Tidy() {
  338. c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "SN E!"}
  339. c.ServeJSON()
  340. return
  341. }
  342. if len(Devicer.T_ckey) != 0 {
  343. if Devicer.T_ckey != c.GetString("T_ckey") {
  344. c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_ckey E!"}
  345. c.ServeJSON()
  346. return
  347. }
  348. }
  349. err := Handle.PushHandle(&Devicer, Devicer.T_sn, T_data)
  350. if err != nil {
  351. c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "e!", Data: err.Error()}
  352. c.ServeJSON()
  353. return
  354. }
  355. c.Data["json"] = lib.JSONR{Code: lib.Success, Msg: "ok!"}
  356. c.ServeJSON()
  357. return
  358. }
  359. func (c *DeviceController) DataList() {
  360. Devicer := Device.Device{T_sn: c.GetString("T_sn")}
  361. if !Devicer.Read_Tidy() {
  362. c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "SN E!"}
  363. c.ServeJSON()
  364. return
  365. }
  366. if len(Devicer.T_ckey) != 0 {
  367. if Devicer.T_ckey != c.GetString("T_ckey") {
  368. c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_ckey E!"}
  369. c.ServeJSON()
  370. return
  371. }
  372. }
  373. DeviceData_Form := Device.DeviceData_Form{}
  374. c.ParseForm(&DeviceData_Form)
  375. if len(DeviceData_Form.T_jointTab) < 1 {
  376. c.Data["json"] = lib.JSONS{Code: lib.Error, Msg: "T_jointTab !"}
  377. c.ServeJSON()
  378. return
  379. }
  380. JSONR_r := Device.Data_List(DeviceData_Form.T_sn+"_"+DeviceData_Form.T_jointTab, DeviceData_Form.T_jsonFind, DeviceData_Form.T_jsonSort, DeviceData_Form.PageIndex, DeviceData_Form.PageSize)
  381. c.Data["json"] = JSONR_r
  382. c.ServeJSON()
  383. return
  384. }
  385. func (c *DeviceController) SSELog() {
  386. T_sn := c.GetString("T_sn")
  387. if len(T_sn) == 0 {
  388. c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_sn!"}
  389. c.ServeJSON()
  390. return
  391. }
  392. Device_r := Device.Device{T_sn: T_sn}
  393. if !Device_r.Read_Tidy() {
  394. c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "验证失败!"}
  395. c.ServeJSON()
  396. return
  397. }
  398. if len(Device_r.T_ckey) != 0 {
  399. if Device_r.T_ckey != c.GetString("T_ckey") {
  400. c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "验证失败 !"}
  401. c.ServeJSON()
  402. return
  403. }
  404. }
  405. c.Ctx.ResponseWriter.Header().Set("Content-Type", "text/event-stream")
  406. c.Ctx.ResponseWriter.Header().Set("Cache-Control", "no-cache")
  407. c.Ctx.ResponseWriter.Header().Set("Connection", "keep-alive")
  408. //
  409. SubConn := []*context.Response{}
  410. // 从map中读取数据
  411. val, ok := lib.SseLogSubClinets.Load(Device_r.T_sn)
  412. if ok {
  413. SubConn = val.([]*context.Response)
  414. }
  415. SubConn = append(SubConn, c.Ctx.ResponseWriter)
  416. // 写入map
  417. lib.SseLogSubClinets.Store(Device_r.T_sn, SubConn)
  418. // 退出 删除订阅
  419. defer func() {
  420. // 从map中读取数据
  421. val, ok = lib.SseLogSubClinets.Load(Device_r.T_sn)
  422. if ok {
  423. SubConn = val.([]*context.Response)
  424. for i, v := range SubConn {
  425. if v == c.Ctx.ResponseWriter {
  426. fmt.Println("删除订阅:", fmt.Sprintf("%p", v), Device_r.T_sn)
  427. SubConn = append(SubConn[:i], SubConn[i+1:]...)
  428. lib.SseLogSubClinets.Store(Device_r.T_sn, SubConn)
  429. break
  430. }
  431. }
  432. }
  433. }()
  434. //data, _ := json.Marshal(Device_r.T_dataJson)
  435. //fmt.Println(string(data))
  436. lib.SseWriteJSON(c.Ctx.ResponseWriter,[]byte("OK"))
  437. for true {
  438. // Sleep for 1 second before sending the next update
  439. time.Sleep(1 * time.Second)
  440. }
  441. // Close the connection
  442. c.Ctx.ResponseWriter.WriteHeader(http.StatusOK)
  443. }