82 lines
2.0 KiB
Go
82 lines
2.0 KiB
Go
package saft_hat
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"github.com/gogf/gf/v2/frame/g"
|
|
"io/ioutil"
|
|
"net/http"
|
|
"strconv"
|
|
"time"
|
|
)
|
|
|
|
// 定义设备上传速度频率请求【我们请求平台】
|
|
type UploadRateReq struct {
|
|
g.Meta `path:"/device/rate" method:"post" tags:"安全帽相关" summary:"更新设备数据发送频率"`
|
|
Data string `json:"data" dc:"设备号"` // 设备数据
|
|
RateTime int `json:"rateTime" dc:"上传频率单位是S"` // 上传频率
|
|
}
|
|
|
|
type UploadRateRes struct {
|
|
Code int `json:"code"` // 响应代码
|
|
Data string `json:"data"` // 设备数据
|
|
Msg string `json:"msg"` // 响应消息
|
|
}
|
|
|
|
func (h Hat) UpdateRate(ctx context.Context, req *UploadRateReq) (res *UploadRateRes, err error) {
|
|
res = new(UploadRateRes)
|
|
// 获取请求参数
|
|
rateTime := req.RateTime
|
|
data := req.Data
|
|
timestamp := time.Now().Unix()
|
|
|
|
// 准备生成签名的参数
|
|
params := map[string]string{
|
|
"appid": appid,
|
|
"data": data,
|
|
"rate_time": strconv.Itoa(rateTime),
|
|
"secret": secret,
|
|
"timestamp": strconv.FormatInt(timestamp, 10),
|
|
}
|
|
// 生成签名
|
|
sign := GenerateSignature(params)
|
|
|
|
// 构造请求体
|
|
payload := map[string]interface{}{
|
|
"appid": appid,
|
|
"data": data,
|
|
"rate_time": rateTime,
|
|
"timestamp": timestamp,
|
|
"secret": secret,
|
|
"sign": sign,
|
|
}
|
|
payloadBytes, err := json.Marshal(payload)
|
|
if err != nil {
|
|
return res, err
|
|
}
|
|
|
|
// 发送POST请求
|
|
resp, err := http.Post("https://www.loctp.com/api/crm/v1/uploadRate", "application/json", bytes.NewBuffer(payloadBytes))
|
|
if err != nil {
|
|
return res, err
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
// 检查响应
|
|
respBody, err := ioutil.ReadAll(resp.Body)
|
|
err = json.Unmarshal(respBody, &res)
|
|
if err != nil {
|
|
return res, err
|
|
}
|
|
|
|
// 把 respBody 转化为 UploadRateRes
|
|
err = json.Unmarshal(respBody, &res)
|
|
if err != nil {
|
|
// 处理错误,例如打印或返回错误
|
|
fmt.Println("Error unmarshalling res:", err)
|
|
}
|
|
return res, err
|
|
}
|