Nats.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package Nats
  2. import (
  3. "ColdP_server/conf"
  4. "ColdP_server/controllers/lib"
  5. "ColdP_server/models/Account"
  6. "ColdP_server/models/Device"
  7. "errors"
  8. "fmt"
  9. "github.com/nats-io/nats.go"
  10. "github.com/vmihailenco/msgpack/v5"
  11. "time"
  12. )
  13. func Init() {
  14. fmt.Println("============Nats init============")
  15. var err error
  16. // 连接Nats服务器
  17. lib.Nats, err = nats.Connect("nats://" + conf.NatsServer_Url)
  18. if err != nil {
  19. fmt.Println("nats 连接失败!")
  20. panic(err)
  21. }
  22. fmt.Println("nats OK!")
  23. }
  24. func Read_New_DeviceData(T_sn string, T_id int) (Device.DeviceData_, error) {
  25. type T_R struct {
  26. Code int16 `xml:"Code"`
  27. Msg string `xml:"Msg"`
  28. Data Device.DeviceData_ `xml:"Data"`
  29. }
  30. type T_Req struct {
  31. T_sn string `xml:"T_sn"`
  32. T_id int `xml:"T_id"`
  33. }
  34. var t_Req T_Req
  35. t_Req.T_sn = T_sn
  36. t_Req.T_id = T_id
  37. marshal, err2 := msgpack.Marshal(&t_Req)
  38. if err2 != nil {
  39. return Device.DeviceData_{}, err2
  40. }
  41. var t_R T_R
  42. request, err := lib.Nats.Request("Read_New_DeviceData", marshal, 3*time.Second)
  43. if err != nil {
  44. return Device.DeviceData_{}, err
  45. }
  46. err = msgpack.Unmarshal(request.Data, &t_R)
  47. if err != nil {
  48. return Device.DeviceData_{}, errors.New(t_R.Msg)
  49. }
  50. if t_R.Code == 200 {
  51. return t_R.Data, nil
  52. }
  53. return Device.DeviceData_{}, errors.New(t_R.Msg)
  54. }
  55. func Verification(GetCookie string, GetString string) (bool, Account.Admin) {
  56. Admin_tokey := GetCookie
  57. if len(Admin_tokey) == 0 {
  58. Admin_tokey = GetString
  59. }
  60. if len(Admin_tokey) == 0 {
  61. return false, Account.Admin{}
  62. }
  63. // 请求-响应, 向 verification 发布一个 `ToKey` 请求数据,设置超时间3秒,如果有多个响应,只接收第一个收到的消息
  64. msg, err := lib.Nats.Request("Cold_Admin_verification", []byte(Admin_tokey), 3*time.Second)
  65. if err != nil {
  66. return false, Account.Admin{}
  67. }
  68. fmt.Printf("Cold_Admin_verification : %s\n", string(msg.Data))
  69. type T_R struct {
  70. Code int16 `xml:"Code"`
  71. Msg string `xml:"Msg"`
  72. Data Account.Admin `xml:"Data"` // 泛型
  73. }
  74. var t_R T_R
  75. err = msgpack.Unmarshal(msg.Data, &t_R)
  76. if err != nil || t_R.Code != 200 {
  77. return false, Account.Admin{}
  78. }
  79. return true, t_R.Data
  80. }