This commit is contained in:
jiangyong27 2024-05-21 20:45:32 +08:00
parent a79e5bdfcd
commit 09e271dd35
8 changed files with 1022 additions and 2 deletions

42
device/device.go Normal file
View File

@ -0,0 +1,42 @@
package device
import mqtt "github.com/eclipse/paho.mqtt.golang"
var (
BrandUstone = "ustone"
BrandESP8266 = "esp8266"
BrandFushua = "fushua"
BrandZhiheng = "zhiheng"
BrandUsr = "usr"
BrandVzenith = "vzenith"
)
type Message struct {
MsgId string
MsgTime int64
MsgType string
Topic string
DeviceId string
Data map[string]interface{}
}
type Callback func(message *Message)
type Device interface {
KeepAlive() error
Operate(string) error
}
type Voice interface {
Device
Play(string) error
}
func NewVoice(brand, model, deviceId string, client mqtt.Client, callback Callback) Voice {
if brand == BrandZhiheng {
return NewZhihengVoice(deviceId, client, callback)
} else if brand == BrandFushua {
return NewFushuaVoice(deviceId, client, callback)
}
return nil
}

View File

@ -0,0 +1,127 @@
package device
import (
"errors"
"fmt"
mqtt "github.com/eclipse/paho.mqtt.golang"
log "github.com/sirupsen/logrus"
"github.com/spf13/cast"
"strings"
"sync"
"time"
)
var (
EWSTypeRaw = "raw"
)
type Esp8266WifiSwitch struct {
sync.Mutex
brand string
model string
deviceId string
client mqtt.Client
callback Callback
}
func NewEsp8266WifiSwitch(deviceId string, mqttClient mqtt.Client, callback Callback) *Esp8266WifiSwitch {
u := &Esp8266WifiSwitch{
client: mqttClient,
deviceId: deviceId,
callback: callback,
brand: BrandESP8266,
model: "wsp8",
}
if callback != nil {
var token mqtt.Token = nil
if deviceId == "#" {
token = mqttClient.Subscribe(fmt.Sprintf("%s/%s/%s", u.brand, u.model, deviceId), 2, u.Callback)
} else {
token = mqttClient.Subscribe(fmt.Sprintf("%s/%s/%s/#", u.brand, u.model, deviceId), 2, u.Callback)
}
if err := token.Error(); err != nil {
log.Errorf("[%s:%s] device[%s] Subscribe error:%s", u.brand, u.model, deviceId, err.Error())
}
}
return u
}
func (u *Esp8266WifiSwitch) TurnOn(idx int) error {
if u.deviceId == "#" {
return nil
}
topic := fmt.Sprintf("%s/%s/%s/cmd", u.brand, u.model, u.deviceId)
publishACK := u.client.Publish(topic, 0, false, fmt.Sprintf("a%d", idx+1))
publishACK.WaitTimeout(time.Second)
return publishACK.Error()
}
func (u *Esp8266WifiSwitch) TurnOff(idx int) error {
if u.deviceId == "#" {
return nil
}
topic := fmt.Sprintf("%s/%s/%s/cmd", u.brand, u.model, u.deviceId)
publishACK := u.client.Publish(topic, 0, false, fmt.Sprintf("c%d", idx+1))
publishACK.WaitTimeout(time.Second)
return publishACK.Error()
}
func (u *Esp8266WifiSwitch) KeepAlive() error {
if u.deviceId == "#" {
return nil
}
topic := fmt.Sprintf("%s/%s/%s/cmd", u.brand, u.model, u.deviceId)
publishACK := u.client.Publish(topic, 0, false, "qa") //查询继电器状态
publishACK.WaitTimeout(time.Second)
return publishACK.Error()
}
func (u *Esp8266WifiSwitch) Operate(cmd string) error {
if u.deviceId == "#" {
return errors.New("不支持的操作#")
}
topic := fmt.Sprintf("%s/%s/%s/cmd", u.brand, u.model, u.deviceId)
publishACK := u.client.Publish(topic, 0, false, cmd) //查询继电器状态
publishACK.WaitTimeout(time.Second)
return publishACK.Error()
}
func (u *Esp8266WifiSwitch) Callback(client mqtt.Client, message mqtt.Message) {
u.Lock()
defer u.Unlock()
topic := message.Topic()
payload := message.Payload()
// res的才回调忽略cmd请求
if !strings.HasSuffix(topic, "res") {
return
}
log.Debugf("[%s][%s] deviceId[%s] topic[%s] payloyad[%s]", u.brand, u.model, u.deviceId, topic, string(payload))
var callMsg Message
callMsg.MsgType = EWSTypeRaw
callMsg.MsgTime = time.Now().Unix()
callMsg.MsgId = cast.ToString(message.MessageID())
callMsg.DeviceId = u.getDeviceId(topic)
callMsg.Topic = topic
callMsg.Data = make(map[string]interface{})
callMsg.Data["raw"] = string(payload)
u.callback(&callMsg)
}
func (u *Esp8266WifiSwitch) getDeviceId(topic string) string {
devId := u.deviceId
if devId == "#" {
fields := strings.Split(topic, "/")
if len(fields) >= 2 {
devId = fields[2]
}
}
return devId
}

102
device/fushua_voice.go Normal file
View File

@ -0,0 +1,102 @@
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 (
FSTypeGetinfo = "getinfo"
)
type FsVoice struct {
sync.Mutex
deviceId string
client mqtt.Client
callback Callback
brand string
model string
}
func NewFushuaVoice(deviceId string, client mqtt.Client, callback Callback) *FsVoice {
s := &FsVoice{
deviceId: deviceId,
client: client,
callback: callback,
brand: BrandFushua,
model: "voice",
}
if callback != nil {
client.Subscribe(fmt.Sprintf("%s/%s/%s", s.brand, s.model, deviceId), 2, s.Callback)
}
return s
}
func (s *FsVoice) Operate(cmd string) error {
return s.Play(cmd)
}
func (s *FsVoice) KeepAlive() error {
if s.deviceId == "#" {
return nil
}
topic := fmt.Sprintf("%s/%s/%s/cmd", s.brand, s.model, s.deviceId)
payload := fmt.Sprintf(`{"cmd":"getinfo","msgid":"%s"}`, cast.ToString(time.Now().UnixMilli()))
publishACK := s.client.Publish(topic, 2, false, payload)
publishACK.WaitTimeout(time.Second)
return publishACK.Error()
}
func (s *FsVoice) Play(tts string) error {
if s.deviceId == "#" {
return nil
}
topic := fmt.Sprintf("%s/%s/%s/cmd", s.brand, s.model, s.deviceId)
payload := fmt.Sprintf(`{"cmd":"voice","msgid":"%s","msg":"%s"}`, cast.ToString(time.Now().UnixMilli()), tts)
publishACK := s.client.Publish(topic, 2, false, payload)
publishACK.WaitTimeout(time.Second)
return publishACK.Error()
}
func (s *FsVoice) getDeviceId(topic string) string {
devId := s.deviceId
if devId == "#" {
fields := strings.Split(topic, "/")
if len(fields) >= 3 {
devId = fields[2]
}
}
return devId
}
func (s *FsVoice) Callback(client mqtt.Client, message mqtt.Message) {
s.Lock()
defer s.Unlock()
topic := message.Topic()
payload := message.Payload()
if strings.HasSuffix(topic, "cmd") {
return
}
log.Debugf("[%s][%s] deviceId[%s] topic[%s] payloyad[%s]", s.brand, s.model, s.deviceId, topic, string(payload))
var callMsg Message
callMsg.MsgType = FSTypeGetinfo
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)
}

84
device/usr_n520.go Normal file
View File

@ -0,0 +1,84 @@
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)
}

View File

@ -0,0 +1,233 @@
package device
import (
"encoding/json"
"errors"
"fmt"
mqtt "github.com/eclipse/paho.mqtt.golang"
log "github.com/sirupsen/logrus"
"github.com/spf13/cast"
"strings"
"sync"
"time"
)
var (
UWSTypeInfo1 = "info1"
UWSTypeInfo2 = "info2"
UWSTypeInfo3 = "info3"
UWSTypeState = "state"
UWSTypeSensor = "sensor"
UWSTypePower = "power"
UWSTypeResult = "result"
)
type UstoneWifiSwitch struct {
sync.Mutex
brand string
model string
deviceId string
client mqtt.Client
callback Callback
}
func NewUstoneWifiSwitch(deviceId string, mqtt mqtt.Client, callback Callback) *UstoneWifiSwitch {
u := &UstoneWifiSwitch{
brand: BrandUstone,
model: "wsp1",
client: mqtt,
deviceId: deviceId,
callback: callback,
}
if callback != nil {
if deviceId == "#" {
mqtt.Subscribe(fmt.Sprintf("v2/tele/%s/#", u.model), 2, u.Callback)
mqtt.Subscribe(fmt.Sprintf("v2/stat/%s/#", u.model), 2, u.Callback)
} else {
mqtt.Subscribe(fmt.Sprintf("v2/tele/%s/%s/#", u.model, u.deviceId), 2, u.Callback)
mqtt.Subscribe(fmt.Sprintf("v2/stat/%s/%s/#", u.model, u.deviceId), 2, u.Callback)
}
}
return u
}
func (u *UstoneWifiSwitch) TurnOn() error {
if u.deviceId == "#" {
return nil
}
topic := fmt.Sprintf("v2/cmnd/%s/%s/Power0", u.model, u.deviceId)
publishACK := u.client.Publish(topic, 0, false, "1")
publishACK.WaitTimeout(time.Second)
return publishACK.Error()
}
func (u *UstoneWifiSwitch) TurnOff() error {
if u.deviceId == "#" {
return nil
}
topic := fmt.Sprintf("v2/cmnd/%s/%s/Power0", u.model, u.deviceId)
publishACK := u.client.Publish(topic, 0, false, "0")
publishACK.WaitTimeout(time.Second)
return publishACK.Error()
}
func (u *UstoneWifiSwitch) TurnOver() error {
if u.deviceId == "#" {
return nil
}
topic := fmt.Sprintf("v2/cmnd/%s/%s/Power0", u.model, u.deviceId)
publishACK := u.client.Publish(topic, 0, false, "2")
publishACK.WaitTimeout(time.Second)
return publishACK.Error()
}
func (u *UstoneWifiSwitch) SetPeriod(sec int64) error {
if u.deviceId == "#" {
return nil
}
topic := fmt.Sprintf("v2/cmnd/%s/%s/TelePeriod", u.model, u.deviceId)
publishACK := u.client.Publish(topic, 0, false, cast.ToString(sec))
publishACK.WaitTimeout(time.Second)
return publishACK.Error()
}
func (u *UstoneWifiSwitch) Operate(cmd string) error {
cmd = strings.ToLower(cmd)
if cmd == "on" {
return u.TurnOn()
} else if cmd == "off" {
return u.TurnOff()
} else if cmd == "over" {
return u.TurnOver()
} else if cmd == "keepalive" {
return u.KeepAlive()
}
return errors.New("不支持的命令[on|off|over|keepalive]")
}
func (u *UstoneWifiSwitch) KeepAlive() error {
return nil
}
func (u *UstoneWifiSwitch) Callback(client mqtt.Client, message mqtt.Message) {
u.Lock()
defer u.Unlock()
topic := message.Topic()
payload := message.Payload()
log.Debugf("[USTONE][%s] deviceId[%s] topic[%s] payloyad[%s]",
u.model, u.deviceId, topic, string(payload))
if u.callback != nil {
msgId := cast.ToString(message.MessageID())
if strings.HasSuffix(topic, "STATE") {
u.updateState(msgId, topic, payload)
} else if strings.HasSuffix(topic, "SENSOR") {
u.updateSensor(msgId, topic, payload)
} else if strings.HasSuffix(topic, "INFO1") || strings.HasSuffix(topic, "INFO2") || strings.HasSuffix(topic, "INFO3") {
u.updateInfo(msgId, topic, payload)
}
}
}
func (u *UstoneWifiSwitch) getDeviceId(topic string) string {
devId := u.deviceId
if devId == "#" {
fields := strings.Split(topic, "/")
if len(fields) >= 4 {
devId = fields[3]
}
}
return devId
}
func (u *UstoneWifiSwitch) updateInfo(msgId, topic string, payload []byte) {
mp := make(map[string]interface{})
if err := json.Unmarshal(payload, &mp); err != nil {
log.Errorf("topic[%s] paylooad[%s] error :%s", topic, string(payload), err.Error())
return
}
devId := u.getDeviceId(topic)
message := &Message{}
message.DeviceId = devId
message.Topic = topic
message.MsgTime = time.Now().Unix()
message.MsgId = msgId
message.Data = make(map[string]interface{})
if strings.HasSuffix(topic, "INFO1") {
i := cast.ToStringMap(mp["Info1"])
message.MsgType = UWSTypeInfo1
message.Data["module"] = cast.ToString(i["Module"])
message.Data["version"] = cast.ToString(i["Version"])
message.Data["raw"] = i
} else if strings.HasSuffix(topic, "INFO2") {
i := cast.ToStringMap(mp["Info2"])
message.MsgType = UWSTypeInfo2
message.Data["hostname"] = cast.ToString(i["Hostname"])
message.Data["ip_address"] = cast.ToString(i["IPAddress"])
message.Data["raw"] = i
} else if strings.HasSuffix(topic, "INFO3") {
i := cast.ToStringMap(mp["Info3"])
message.MsgType = UWSTypeInfo3
message.Data["boot_count"] = cast.ToString(i["BootCount"])
message.Data["raw"] = i
}
u.callback(message)
}
func (u *UstoneWifiSwitch) updateState(msgId, topic string, payload []byte) {
mp := make(map[string]interface{})
if err := json.Unmarshal(payload, &mp); err != nil {
log.Errorf("paylooad[%s] error :%s", string(payload), err.Error())
return
}
wifi := cast.ToStringMap(mp["Wifi"])
message := &Message{}
message.DeviceId = u.getDeviceId(topic)
message.Topic = topic
message.MsgType = UWSTypeState
message.MsgTime = time.Now().Unix()
message.MsgId = msgId
message.Data = make(map[string]interface{})
message.Data["power"] = cast.ToString(mp["POWER"])
message.Data["bssid"] = cast.ToString(wifi["BSSId"])
message.Data["ssid"] = cast.ToString(wifi["SSId"])
message.Data["raw"] = mp
u.callback(message)
}
func (u *UstoneWifiSwitch) updateSensor(msgId, topic string, payload []byte) {
mp := make(map[string]interface{})
if err := json.Unmarshal(payload, &mp); err != nil {
log.Errorf("paylooad[%s] error :%s", string(payload), err.Error())
return
}
energy := cast.ToStringMap(mp["ENERGY"])
totalStartTime, _ := time.ParseInLocation("2006-01-02T15:04:05", cast.ToString(energy["TotalStartTime"]), time.Local)
message := &Message{}
message.DeviceId = u.getDeviceId(topic)
message.Topic = topic
message.MsgType = UWSTypeSensor
message.MsgTime = time.Now().Unix()
message.MsgId = msgId
message.Data = make(map[string]interface{})
message.Data["total_start_time"] = totalStartTime.Unix()
message.Data["total_energy"] = cast.ToFloat64(energy["Total"])
message.Data["today_energy"] = cast.ToFloat64(energy["Today"])
message.Data["yesterday_energy"] = cast.ToFloat64(energy["Yesterday"])
message.Data["raw"] = energy
u.callback(message)
}

231
device/vzenith_r5.go Normal file
View File

@ -0,0 +1,231 @@
package device
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
mqtt "github.com/eclipse/paho.mqtt.golang"
log "github.com/sirupsen/logrus"
"github.com/smbrave/goutil"
"github.com/spf13/cast"
"github.com/tidwall/gjson"
"strings"
"sync"
"time"
)
var (
VzenithTypeRaw = "raw"
VzenithTypeIvsResult = "ivs_result"
VzenithTypeSerialData = "serial_data"
)
type VzenithR5 struct {
sync.Mutex
brand string
model string
deviceId string
client mqtt.Client
callback Callback
}
func NewVzenithR5(deviceId string, client mqtt.Client, call Callback) *VzenithR5 {
u := &VzenithR5{
brand: BrandVzenith,
model: "r5",
deviceId: deviceId,
client: client,
callback: call,
}
if call != nil {
var token mqtt.Token = nil
if deviceId == "#" {
token = client.Subscribe(fmt.Sprintf("%s/%s/%s", u.brand, u.model, deviceId), 2, u.Callback)
} else {
token = client.Subscribe(fmt.Sprintf("%s/%s/%s/#", u.brand, u.model, deviceId), 2, u.Callback)
}
if err := token.Error(); err != nil {
log.Errorf("brand[%s] model[%s] device[%s] Subscribe error:%s", u.brand, u.model, deviceId, err.Error())
}
}
return u
}
func (u *VzenithR5) IvsTrigger() error {
if u.deviceId == "#" {
return errors.New("no deviceId")
}
params := make(map[string]interface{})
params["id"] = cast.ToString(goutil.GetBigID(0, 0))
params["sn"] = u.deviceId
params["name"] = "ivs_trigger"
params["version"] = "1.0"
params["timestamp"] = time.Now().Unix()
params["payload"] = map[string]interface{}{
"type": "ivs_trigger",
"body": map[string]interface{}{},
}
payload := goutil.EncodeJSON(params)
topic := fmt.Sprintf("%s/%s/%s/down/ivs_trigger", u.brand, u.model, u.deviceId)
publishACK := u.client.Publish(topic, 2, false, payload)
publishACK.WaitTimeout(time.Second)
return publishACK.Error()
}
func (u *VzenithR5) KeepAlive() error {
params := make(map[string]interface{})
params["id"] = cast.ToString(goutil.GetBigID(0, 0))
params["sn"] = u.deviceId
params["name"] = "get_device_timestamp"
params["version"] = "1.0"
params["timestamp"] = time.Now().Unix()
params["payload"] = map[string]interface{}{
"type": "get_device_timestamp",
"body": map[string]interface{}{},
}
payload := goutil.EncodeJSON(params)
topic := fmt.Sprintf("%s/%s/%s/down/get_device_timestamp", u.brand, u.model, u.deviceId)
publishACK := u.client.Publish(topic, 2, false, payload)
publishACK.WaitTimeout(time.Second)
return publishACK.Error()
}
func (u *VzenithR5) Operate(string) error {
return nil
}
func (u *VzenithR5) SendSerialData(channel int, data []byte) error {
dataBase64 := base64.StdEncoding.EncodeToString(data)
dataLen := len(dataBase64)
params := make(map[string]interface{})
params["id"] = cast.ToString(goutil.GetBigID(0, 0))
params["sn"] = u.deviceId
params["name"] = "serial_data"
params["version"] = "1.0"
params["timestamp"] = time.Now().Unix()
params["payload"] = map[string]interface{}{
"type": "serial_data",
"body": map[string]interface{}{
"serialData": []map[string]interface{}{
{
"serialChannel": channel,
"data": dataBase64,
"dataLen": dataLen,
},
},
},
}
payload := goutil.EncodeJSON(params)
topic := fmt.Sprintf("%s/%s/%s/down/serial_data", u.brand, u.model, u.deviceId)
publishACK := u.client.Publish(topic, 2, false, payload)
publishACK.WaitTimeout(time.Second)
return publishACK.Error()
}
func (u *VzenithR5) getDeviceId(topic string) string {
devId := u.deviceId
if devId == "#" {
fields := strings.Split(topic, "/")
if len(fields) >= 3 {
devId = fields[2]
}
}
return devId
}
func (s *VzenithR5) Callback(client mqtt.Client, message mqtt.Message) {
s.Lock()
defer s.Unlock()
topic := message.Topic()
payload := message.Payload()
log.Infof("[vzenith][R5] deviceId[%s] topic[%s] payloyad[%s]", s.deviceId, topic, string(payload))
if strings.HasSuffix(topic, "ivs_result") {
s.parseIvsResult(cast.ToString(message.MessageID()), topic, payload)
return
}
if strings.HasSuffix(topic, "up/serial_data") {
s.parseSerialData(cast.ToString(message.MessageID()), topic, payload)
return
}
if strings.HasSuffix(topic, "down/get_device_timestamp") {
return
}
var callMsg Message
callMsg.MsgType = VzenithTypeRaw
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)
}
func (s *VzenithR5) parseSerialData(msgId, topic string, payload []byte) {
mp := make(map[string]interface{})
if err := json.Unmarshal(payload, &mp); err != nil {
log.Errorf("paylooad[%s] error :%s", string(payload), err.Error())
return
}
g := gjson.Parse(string(payload))
message := &Message{}
message.DeviceId = s.getDeviceId(topic)
message.Topic = topic
message.MsgType = VzenithTypeSerialData
message.MsgTime = time.Now().Unix()
message.MsgTime = cast.ToInt64(mp["timestamp"])
message.MsgId = msgId
data := g.Get("payload.body.SerialData.data")
channel := g.Get("payload.body.SerialData.serialChannel").Int()
d, _ := base64.StdEncoding.DecodeString(data.String())
message.Data = make(map[string]interface{})
message.Data["data"] = string(d)
message.Data["channel"] = channel
s.callback(message)
}
func (s *VzenithR5) parseIvsResult(msgId, topic string, payload []byte) {
mp := make(map[string]interface{})
if err := json.Unmarshal(payload, &mp); err != nil {
log.Errorf("paylooad[%s] error :%s", string(payload), err.Error())
return
}
g := gjson.Parse(string(payload))
message := &Message{}
message.DeviceId = s.getDeviceId(topic)
message.Topic = topic
message.MsgType = VzenithTypeIvsResult
message.MsgTime = time.Now().Unix()
message.MsgTime = cast.ToInt64(mp["timestamp"])
message.MsgId = msgId
license := g.Get("payload.AlarmInfoPlate.result.PlateResult.license")
lic, _ := base64.StdEncoding.DecodeString(license.String())
message.Data = make(map[string]interface{})
message.Data["license"] = string(lic)
s.callback(message)
}

197
device/zhiheng_voice.go Normal file
View File

@ -0,0 +1,197 @@
package device
import (
"encoding/json"
"fmt"
mqtt "github.com/eclipse/paho.mqtt.golang"
log "github.com/sirupsen/logrus"
"github.com/smbrave/goutil"
"github.com/spf13/cast"
"strings"
"sync"
"time"
)
var (
ZHTypeGetDevStatus = "getDevStatus"
ZHTypeSetTime = "setTime"
ZHTypeStartTts = "startTts"
ZHTypeStopAudio = "stopAudio"
ZHTypeNextAudio = "nextAudio"
ZHTypePauseAudio = "pauseAudio"
ZHTypeSetAudioVol = "setAudioVol"
)
type ZhihengVoice struct {
sync.Mutex
deviceId string
client mqtt.Client
callback Callback
brand string
model string
}
func NewZhihengVoice(deviceId string, client mqtt.Client, callback Callback) *ZhihengVoice {
s := &ZhihengVoice{
deviceId: deviceId,
client: client,
callback: callback,
brand: BrandZhiheng,
model: "voice",
}
if callback != nil {
if deviceId == "#" {
client.Subscribe(fmt.Sprintf("%s/%s/#", s.brand, s.model), 2, s.Callback)
} else {
client.Subscribe(fmt.Sprintf("%s/%s/%s/#", s.brand, s.model, deviceId), 2, s.Callback)
}
}
return s
}
func (s *ZhihengVoice) Operate(cmd string) error {
return s.Play(cmd)
}
func (s *ZhihengVoice) KeepAlive() error {
if s.deviceId == "#" {
return nil
}
topic := fmt.Sprintf("%s/%s/%s/cmd", s.brand, s.model, s.deviceId)
payload := `{"method":"getDevStatus"}`
publishACK := s.client.Publish(topic, 2, false, payload)
publishACK.WaitTimeout(time.Second)
return publishACK.Error()
}
func (s *ZhihengVoice) Play(tts string) error {
if s.deviceId == "#" {
return nil
}
params := make(map[string]interface{})
params["method"] = "startTts"
params["content"] = tts
topic := fmt.Sprintf("%s/%s/%s/cmd", s.brand, s.model, s.deviceId)
publishACK := s.client.Publish(topic, 2, false, goutil.EncodeJSON(params))
publishACK.WaitTimeout(time.Second)
return publishACK.Error()
}
func (s *ZhihengVoice) GetWelcome() error {
if s.deviceId == "#" {
return nil
}
params := make(map[string]interface{})
params["method"] = "getWelcome"
topic := fmt.Sprintf("%s/%s/%s/cmd", s.brand, s.model, s.deviceId)
publishACK := s.client.Publish(topic, 2, false, goutil.EncodeJSON(params))
publishACK.WaitTimeout(time.Second)
return publishACK.Error()
}
func (s *ZhihengVoice) GetSimCheck() error {
if s.deviceId == "#" {
return nil
}
params := make(map[string]interface{})
params["method"] = "getSimCheck"
topic := fmt.Sprintf("%s/%s/%s/cmd", s.brand, s.model, s.deviceId)
publishACK := s.client.Publish(topic, 2, false, goutil.EncodeJSON(params))
publishACK.WaitTimeout(time.Second)
return publishACK.Error()
}
func (s *ZhihengVoice) SetLed(colors []string) error {
if s.deviceId == "#" {
return nil
}
params := make(map[string]interface{})
params["method"] = "setLed"
params["colors"] = colors
topic := fmt.Sprintf("%s/%s/%s/cmd", s.brand, s.model, s.deviceId)
publishACK := s.client.Publish(topic, 2, false, goutil.EncodeJSON(params))
publishACK.WaitTimeout(time.Second)
return publishACK.Error()
}
func (s *ZhihengVoice) SetLedMode() error {
if s.deviceId == "#" {
return nil
}
params := make(map[string]interface{})
params["method"] = "setLedMode1"
params["colors"] = []string{"#FF0000", "#00FF00", "#0000FF", "#000000", "#FFFFFF", "#FFFF00", "#00FFFF", "#FF00FF"}
params["hasClockwise"] = false
params["speed"] = 5
topic := fmt.Sprintf("%s/%s/%s/cmd", s.brand, s.model, s.deviceId)
publishACK := s.client.Publish(topic, 2, false, goutil.EncodeJSON(params))
publishACK.WaitTimeout(time.Second)
return publishACK.Error()
}
func (s *ZhihengVoice) CloseLed() error {
return s.SetLed([]string{"#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000"})
}
func (s *ZhihengVoice) SetAudioVol(vol int) error {
if s.deviceId == "#" {
return nil
}
params := make(map[string]interface{})
params["method"] = "setAudioVol"
params["vol"] = vol
topic := fmt.Sprintf("%s/%s/%s/cmd", s.brand, s.model, s.deviceId)
publishACK := s.client.Publish(topic, 2, false, goutil.EncodeJSON(params))
publishACK.WaitTimeout(time.Second)
return publishACK.Error()
}
func (s *ZhihengVoice) Reboot() error {
if s.deviceId == "#" {
return nil
}
params := make(map[string]interface{})
params["method"] = "reboot"
topic := fmt.Sprintf("%s/%s/%s/cmd", s.brand, s.model, s.deviceId)
publishACK := s.client.Publish(topic, 2, false, goutil.EncodeJSON(params))
publishACK.WaitTimeout(time.Second)
return publishACK.Error()
}
func (s *ZhihengVoice) getDeviceId(topic string) string {
devId := s.deviceId
if devId == "#" {
fields := strings.Split(topic, "/")
if len(fields) >= 3 {
devId = fields[2]
}
}
return devId
}
func (s *ZhihengVoice) Callback(client mqtt.Client, message mqtt.Message) {
s.Lock()
defer s.Unlock()
topic := message.Topic()
payload := message.Payload()
// res的才回调忽略cmd请求
if strings.HasSuffix(topic, "cmd") {
return
}
log.Debugf("[%s][%s] deviceId[%s] topic[%s] payloyad[%s]", s.brand, s.model, s.deviceId, topic, string(payload))
var callMsg Message
callMsg.MsgType = FSTypeGetinfo
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)
}

8
go.mod
View File

@ -4,15 +4,16 @@ go 1.18
require (
github.com/bradfitz/gomemcache v0.0.0-20230905024940-24af94b03874
github.com/eclipse/paho.mqtt.golang v1.4.3
github.com/gin-gonic/gin v1.9.1
github.com/gomodule/redigo v1.8.9
github.com/google/uuid v1.6.0
github.com/influxdata/influxdb1-client v0.0.0-20220302092344-a9ab5670611c
github.com/minio/minio-go v6.0.14+incompatible
github.com/qiniu/go-sdk/v7 v7.19.0
github.com/sirupsen/logrus v1.9.3
github.com/smbrave/goutil v0.0.0-20240105134047-64fe0dfafba2
github.com/spf13/cast v1.6.0
github.com/tidwall/gjson v1.17.1
github.com/wechatpay-apiv3/wechatpay-go v0.2.18
golang.org/x/crypto v0.9.0
gorm.io/gorm v1.25.6
@ -28,6 +29,7 @@ require (
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.14.0 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/gorilla/websocket v1.5.0 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/json-iterator/go v1.1.12 // indirect
@ -38,11 +40,13 @@ require (
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.0.8 // indirect
github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.0 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.11 // indirect
golang.org/x/arch v0.3.0 // indirect
golang.org/x/net v0.10.0 // indirect
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4 // indirect
golang.org/x/sync v0.1.0 // indirect
golang.org/x/sys v0.16.0 // indirect
golang.org/x/text v0.9.0 // indirect
google.golang.org/protobuf v1.30.0 // indirect