实现 chirp stack transport 的Send方法
This commit is contained in:
@@ -1,7 +1,10 @@
|
||||
package lora
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"git.huangwc.com/pig/pig-farm-controller/internal/infra/logs"
|
||||
"git.huangwc.com/pig/pig-farm-controller/internal/infra/transport/lora/chirp_stack_proto/client/device_service"
|
||||
"github.com/go-openapi/runtime"
|
||||
httptransport "github.com/go-openapi/runtime/client"
|
||||
"github.com/go-openapi/strfmt"
|
||||
@@ -15,6 +18,8 @@ type ChirpStackConfig struct {
|
||||
ServerAddress string
|
||||
// APIKey 是用于认证的 API 密钥。
|
||||
APIKey string
|
||||
// LoRaWAN 端口, 需要和设备一致
|
||||
Fport int64
|
||||
}
|
||||
|
||||
// GenerateAPIKey 用于补齐API Key作为请求头时缺失的部分
|
||||
@@ -50,3 +55,37 @@ func NewChirpStackTransport(config ChirpStackConfig, logger *logs.Logger) *Chirp
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *ChirpStackTransport) Send(deviceID string, payload []byte) error {
|
||||
// 1. 构建 API 请求体。
|
||||
// - Confirmed: true 表示确认消息, 设为false将不保证消息送达(但可以节约下行容量)。
|
||||
// - Data: 经过 Base64 编码的数据。
|
||||
// - FPort: LoRaWAN 端口。
|
||||
body := device_service.DeviceServiceEnqueueBody{
|
||||
QueueItem: &device_service.DeviceServiceEnqueueParamsBodyQueueItem{
|
||||
Confirmed: true,
|
||||
Data: payload,
|
||||
FPort: c.config.Fport,
|
||||
},
|
||||
}
|
||||
|
||||
// 2. 构建 API 请求参数。
|
||||
// - WithTimeout 设置一个合理的请求超时。
|
||||
// - WithQueueItemDevEui 指定目标设备的 EUI。
|
||||
// - WithBody 设置请求体。
|
||||
params := device_service.NewDeviceServiceEnqueueParams().
|
||||
WithTimeout(10 * time.Second).
|
||||
WithQueueItemDevEui(deviceID).
|
||||
WithBody(body)
|
||||
|
||||
// 3. 调用生成的客户端方法来发送请求。
|
||||
// c.authInfo 是您在 NewChirpStackTransport 中创建的认证信息。
|
||||
_, err := c.client.DeviceService.DeviceServiceEnqueue(params, c.authInfo)
|
||||
if err != nil {
|
||||
c.logger.Errorf("设备 %s 调用ChirpStack Enqueue失败: %v", deviceID, err)
|
||||
return err
|
||||
}
|
||||
|
||||
c.logger.Infof("设备 %s 调用ChirpStack Enqueue成功", deviceID)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -2,4 +2,6 @@ package transport
|
||||
|
||||
// Communicator 用于其他设备通信
|
||||
type Communicator interface {
|
||||
// Send 用于发送一条单向数据(不等待回信)
|
||||
Send(deviceID string, payload []byte) error
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user