12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- package Handle
- import (
- "Yunlot/lib"
- "Yunlot/logs"
- "Yunlot/models/Device"
- "encoding/json"
- "go.mongodb.org/mongo-driver/bson"
- "io/ioutil"
- "net/http"
- "strings"
- "time"
- )
- func Relay(Device_r *Device.Device, JointTab string, ArticleSlide *bson.M) {
- for key, value := range Device_r.T_ProductJson.T_RelayDataJson {
- if key == JointTab || key == "*" {
- x := value.(map[string]interface{})
- // 替换发布号变量
- T_pub := strings.Replace(lib.To_string(x["T_pub"]), "{$sn}", Device_r.T_sn, -1) // {$sn} :代表当前数据设备编号SN
- T_pub = strings.Replace(T_pub, "{$project}", Device_r.T_project, -1) // {$project}:代表设备项目服务
- if len(T_pub) == 0 {
- logs.Println("订阅号错误!")
- return
- }
- // 将bson.M对象转换为JSON格式
- jsonData, err := json.Marshal(ArticleSlide)
- if err != nil {
- continue
- }
- switch lib.To_int(x["T_mode"]) {
- case 0: // Nats
- logs.Println("Relay -> Nats:", T_pub, string(jsonData))
- err = lib.Nats.Publish("T_pub", jsonData)
- if err != nil {
- // 发送失败3秒后再次尝试
- go func() {
- time.Sleep(time.Second * 3)
- lib.Nats.Publish("T_pub", jsonData)
- }()
- }
- break
- case 1: // API
- logs.Println("Relay -> API:", T_pub, string(jsonData))
- go func() {
- payload := strings.NewReader(string(jsonData))
- client := &http.Client{
- Timeout: 3 * time.Second, // 设置超时时间为5秒
- }
- req, err := http.NewRequest("POST", T_pub, payload)
- if err != nil {
- logs.Println("Relay -> API!!!:", T_pub, any(err))
- return
- }
- req.Header.Add("Content-Type", "application/json")
- res, err := client.Do(req)
- if err != nil {
- logs.Println("Relay -> API!!!:", T_pub, any(err))
- return
- }
- defer res.Body.Close()
- body, err := ioutil.ReadAll(res.Body)
- if err != nil {
- logs.Println("Relay -> API!!!:", T_pub, any(err))
- return
- }
- logs.Println("Relay -> API Body:", string(body))
- }()
- break
- case 2: // MQTT
- logs.Println("Relay -> MQTT:", T_pub, string(jsonData))
- //lib.Mqtt_publish(T_pub, jsonData)
- break
- }
- }
- }
- }
|