Relay.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package Handle
  2. import (
  3. "Yunlot/lib"
  4. "Yunlot/logs"
  5. "Yunlot/models/Device"
  6. "encoding/json"
  7. "go.mongodb.org/mongo-driver/bson"
  8. "io/ioutil"
  9. "net/http"
  10. "strings"
  11. "time"
  12. )
  13. func Relay(Device_r *Device.Device, JointTab string, ArticleSlide *bson.M) {
  14. for key, value := range Device_r.T_ProductJson.T_RelayDataJson {
  15. if key == JointTab || key == "*" {
  16. x := value.(map[string]interface{})
  17. // 替换发布号变量
  18. T_pub := strings.Replace(lib.To_string(x["T_pub"]), "{$sn}", Device_r.T_sn, -1) // {$sn} :代表当前数据设备编号SN
  19. T_pub = strings.Replace(T_pub, "{$project}", Device_r.T_project, -1) // {$project}:代表设备项目服务
  20. if len(T_pub) == 0 {
  21. logs.Println("订阅号错误!")
  22. return
  23. }
  24. // 将bson.M对象转换为JSON格式
  25. jsonData, err := json.Marshal(ArticleSlide)
  26. if err != nil {
  27. continue
  28. }
  29. switch lib.To_int(x["T_mode"]) {
  30. case 0: // Nats
  31. logs.Println("Relay -> Nats:", T_pub, string(jsonData))
  32. err = lib.Nats.Publish("T_pub", jsonData)
  33. if err != nil {
  34. // 发送失败3秒后再次尝试
  35. go func() {
  36. time.Sleep(time.Second * 3)
  37. lib.Nats.Publish("T_pub", jsonData)
  38. }()
  39. }
  40. break
  41. case 1: // API
  42. logs.Println("Relay -> API:", T_pub, string(jsonData))
  43. go func() {
  44. payload := strings.NewReader(string(jsonData))
  45. client := &http.Client{
  46. Timeout: 3 * time.Second, // 设置超时时间为5秒
  47. }
  48. req, err := http.NewRequest("POST", T_pub, payload)
  49. if err != nil {
  50. logs.Println("Relay -> API!!!:", T_pub, any(err))
  51. return
  52. }
  53. req.Header.Add("Content-Type", "application/json")
  54. res, err := client.Do(req)
  55. if err != nil {
  56. logs.Println("Relay -> API!!!:", T_pub, any(err))
  57. return
  58. }
  59. defer res.Body.Close()
  60. body, err := ioutil.ReadAll(res.Body)
  61. if err != nil {
  62. logs.Println("Relay -> API!!!:", T_pub, any(err))
  63. return
  64. }
  65. logs.Println("Relay -> API Body:", string(body))
  66. }()
  67. break
  68. case 2: // MQTT
  69. logs.Println("Relay -> MQTT:", T_pub, string(jsonData))
  70. //lib.Mqtt_publish(T_pub, jsonData)
  71. break
  72. }
  73. }
  74. }
  75. }