Relay.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package Handle
  2. import (
  3. "AIOTCOER/lib"
  4. "AIOTCOER/logs"
  5. "AIOTCOER/models/Device"
  6. "encoding/json"
  7. "go.mongodb.org/mongo-driver/bson"
  8. "io/ioutil"
  9. "net/http"
  10. "strings"
  11. "time"
  12. )
  13. // 转发 匹配TAB
  14. func Relay(Msid string, Device_r *Device.Device, JointTab string, ArticleSlide *bson.M) {
  15. // 将bson.M转换为map[string]interface{}
  16. // fmt.Println("Relay:",JointTab,*ArticleSlide)
  17. jsonData, err := json.Marshal(*ArticleSlide)
  18. if err != nil {
  19. logs.Println(Msid, "Relay json.Marshal!")
  20. return
  21. }
  22. //fmt.Println("Relay-:",JointTab,*ArticleSlide)
  23. for _, value := range Device_r.T_RelayDataJson {
  24. //value = {
  25. // "T_tabs": "AAAA.AAAA",
  26. // "T_name": "推送报警",
  27. // "T_pushid": 0,
  28. // "T_pub": "/aaa/{$sn}/AAAA"
  29. //},
  30. if value["T_tabs"] == JointTab || value["T_tabs"] == "*" {
  31. // 替换发布号变量
  32. T_pub := strings.Replace(lib.To_string(value["T_pub"]), "{$sn}", Device_r.T_sn, -1) // {$sn} :代表当前数据设备编号SN
  33. if len(T_pub) == 0 {
  34. logs.Println(Msid, "订阅号错误!")
  35. return
  36. }
  37. // 推送 数据
  38. go HTTPPush(T_pub, jsonData)
  39. //// 流量统计
  40. //sd, sdis := StatisticalData.FlowCountMap[Device_r.T_ProductID]
  41. //if sdis {
  42. // sd = &StatisticalData.FlowCount_T{}
  43. // StatisticalData.FlowCountMap[Device_r.T_ProductID] = sd
  44. //}
  45. //sd.T_relay += 1
  46. }
  47. }
  48. }
  49. // 推送
  50. func HTTPPush(url string, data []byte) {
  51. payload := strings.NewReader(string(data))
  52. client := &http.Client{
  53. Timeout: 3 * time.Second, // 设置超时时间为5秒
  54. }
  55. req, err := http.NewRequest("POST", url, payload)
  56. if err != nil {
  57. logs.Println("Relay -> API!!!:", url, any(err))
  58. return
  59. }
  60. req.Header.Add("Content-Type", "application/json")
  61. res, err := client.Do(req)
  62. if err != nil {
  63. logs.Println("Relay -> API!!!:", url, any(err))
  64. return
  65. }
  66. defer res.Body.Close()
  67. body, err := ioutil.ReadAll(res.Body)
  68. if err != nil {
  69. logs.Println("Relay -> API!!!:", url, any(err))
  70. return
  71. }
  72. logs.Println("Relay -> API Body:", string(body))
  73. return
  74. }