mirror of
https://gitee.com/XM-GO/PandaX.git
synced 2026-05-01 09:31:28 +08:00
优化
This commit is contained in:
@@ -3,13 +3,11 @@ package mqttclient
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
RpcRespTopic = `v1/devices/me/rpc/response/%d`
|
||||
RpcReqTopic = `v1/devices/me/rpc/request/%d`
|
||||
RpcRespTopic = `v1/devices/me/rpc/response/%s`
|
||||
RpcReqTopic = `v1/devices/me/rpc/request/%s`
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -18,7 +16,7 @@ const (
|
||||
)
|
||||
|
||||
type RpcRequest struct {
|
||||
RequestId int
|
||||
RequestId string
|
||||
Mode string //单向、双向 单项只发送不等待响应 双向需要等到响应
|
||||
Timeout int // 设置双向时,等待的超时时间
|
||||
}
|
||||
@@ -41,9 +39,3 @@ func (rpc RpcRequest) Pub(deviceId, reqPayload string) error {
|
||||
}
|
||||
return Publish(topic, value.(string), reqPayload)
|
||||
}
|
||||
|
||||
func (rpc *RpcRequest) GetRequestId() {
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
// 生成随机整数
|
||||
rpc.RequestId = rand.Intn(10000) + 1 // 生成0到99之间的随机整数
|
||||
}
|
||||
|
||||
47
iothub/client/udpclient/udp.go
Normal file
47
iothub/client/udpclient/udp.go
Normal file
@@ -0,0 +1,47 @@
|
||||
package udpclient
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"net"
|
||||
"pandax/pkg/global"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type UdpClientT struct {
|
||||
Conn *net.UDPConn
|
||||
Addr *net.UDPAddr
|
||||
}
|
||||
|
||||
var UdpClient sync.Map
|
||||
|
||||
func Send(deviceId, msg string) error {
|
||||
if conn, ok := UdpClient.Load(deviceId); ok {
|
||||
conn := conn.(*UdpClientT)
|
||||
global.Log.Infof("设备%s, 发送指令%s", deviceId, msg)
|
||||
_, err := conn.Conn.WriteToUDP([]byte(msg), conn.Addr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
global.Log.Infof("设备%s TCP连接不存在, 发送指令失败", deviceId)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func SendHex(deviceId, msg string) error {
|
||||
if conn, ok := UdpClient.Load(deviceId); ok {
|
||||
conn := conn.(*UdpClientT)
|
||||
global.Log.Infof("设备%s, 发送指令%s", deviceId, msg)
|
||||
b, err := hex.DecodeString(msg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = conn.Conn.WriteToUDP(b, conn.Addr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
global.Log.Infof("设备%s TCP连接不存在, 发送指令失败", deviceId)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user