mirror of
https://gitee.com/XM-GO/PandaX.git
synced 2026-04-23 02:48:34 +08:00
50 lines
1.2 KiB
Go
50 lines
1.2 KiB
Go
package mqttclient
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"math/rand"
|
|
"time"
|
|
)
|
|
|
|
const (
|
|
RpcRespTopic = `v1/devices/me/rpc/response/%d`
|
|
RpcReqTopic = `v1/devices/me/rpc/request/%d`
|
|
)
|
|
|
|
const (
|
|
SingleMode = "single"
|
|
DoubleMode = "double"
|
|
)
|
|
|
|
type RpcRequest struct {
|
|
RequestId int
|
|
Mode string //单向、双向 单项只发送不等待响应 双向需要等到响应
|
|
Timeout int // 设置双向时,等待的超时时间
|
|
}
|
|
|
|
// RequestCmd 下发指令
|
|
func (rpc RpcRequest) RequestCmd(deviceId, rpcPayload string) error {
|
|
topic := fmt.Sprintf(RpcReqTopic, rpc.RequestId)
|
|
value, ok := Session.Load(deviceId)
|
|
if !ok {
|
|
return errors.New("未获取到设备的MQTT连接")
|
|
}
|
|
return Publish(topic, value.(string), rpcPayload)
|
|
}
|
|
|
|
func (rpc RpcRequest) Pub(deviceId, reqPayload string) error {
|
|
topic := fmt.Sprintf(RpcRespTopic, rpc.RequestId)
|
|
value, ok := Session.Load(deviceId)
|
|
if !ok {
|
|
return errors.New("未获取到设备的MQTT连接")
|
|
}
|
|
return Publish(topic, value.(string), reqPayload)
|
|
}
|
|
|
|
func (rpc *RpcRequest) GetRequestId() {
|
|
rand.Seed(time.Now().UnixNano())
|
|
// 生成随机整数
|
|
rpc.RequestId = rand.Intn(10000) + 1 // 生成0到99之间的随机整数
|
|
}
|