package device import ( "encoding/json" "fmt" mqtt "github.com/eclipse/paho.mqtt.golang" log "github.com/sirupsen/logrus" "github.com/spf13/cast" "strings" "sync" "time" ) var ( UsrTypeRaw = "raw" ) type UsrN520 struct { sync.Mutex deviceId string client mqtt.Client callback Callback brand string model string } func NewUsrN520(deviceId string, client mqtt.Client, call Callback) *UsrN520 { u := &UsrN520{ deviceId: deviceId, client: client, callback: call, brand: BrandUsr, model: "n520", } if call != nil { if deviceId != "#" { client.Subscribe(fmt.Sprintf("%s/%s/%s/#", u.brand, u.model, deviceId), 2, u.Callback) } else { client.Subscribe(fmt.Sprintf("%s/%s/#", u.brand, u.model), 2, u.Callback) } } return u } func (u *UsrN520) KeepAlive() error { return nil } func (u *UsrN520) Operate(string) error { return nil } func (u *UsrN520) getDeviceId(topic string) string { devId := u.deviceId if devId == "#" { fields := strings.Split(topic, "/") if len(fields) >= 3 { devId = fields[2] } } return devId } func (s *UsrN520) Callback(client mqtt.Client, message mqtt.Message) { s.Lock() defer s.Unlock() topic := message.Topic() payload := message.Payload() log.Debugf("[%s][%s] deviceId[%s] topic[%s] payloyad[%s]", s.brand, s.model, s.deviceId, topic, string(payload)) var callMsg Message callMsg.MsgType = UsrTypeRaw callMsg.MsgTime = time.Now().Unix() callMsg.MsgId = cast.ToString(message.MessageID()) callMsg.DeviceId = s.getDeviceId(topic) callMsg.Topic = topic callMsg.Data = make(map[string]interface{}) json.Unmarshal([]byte(payload), &callMsg.Data) s.callback(&callMsg) }