mqtt.go
1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package mqtt
import (
"encoding/json"
pahomqtt "github.com/eclipse/paho.mqtt.golang"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/constant"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/mqtt"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/redis"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
"time"
)
func Start() {
mqtt.StartSubscribe(constant.MQTT_TOPIC, func(client pahomqtt.Client, message pahomqtt.Message) {
payload := make(map[string]interface{})
err := json.Unmarshal(message.Payload(), &payload)
if err != nil {
log.Logger.Error("车间数据json解析失败:" + err.Error())
return
}
if workShop, ok := payload["WorkShop"]; ok {
for key, item := range payload {
if key == "WorkShop" {
continue
}
deviceWorkShop := &domain.DeviceWorkShop{}
mBytes, err := json.Marshal(item)
if err != nil {
continue
}
err = json.Unmarshal(mBytes, deviceWorkShop)
if err != nil {
continue
}
// 获取当前时间
deviceWorkShop.CurrTime = time.Now()
// 车间名称
deviceWorkShop.WorkShop = workShop.(string)
// 设备名称
deviceWorkShop.DeviceSn = key
workShopBytes, err := json.Marshal(deviceWorkShop)
if err != nil {
continue
}
err = redis.GetRedis().LPush(constant.REDIS_WORKSHOP_KEY, string(workShopBytes)).Err()
if err != nil {
log.Logger.Error("车间设备数据加入redis失败:" + err.Error())
}
}
}
log.Logger.Info("MQTT", map[string]interface{}{
"Topic": message.Topic(),
"MessageId": message.MessageID(),
"Message": payload,
})
})
}