huaweicloud-iot-device-sdk-go/util.go

64 lines
1.7 KiB
Go
Raw Normal View History

2020-12-20 15:08:43 +08:00
package iot
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"strings"
"time"
)
2020-12-20 15:08:43 +08:00
// 时间戳为设备连接平台时的UTC时间格式为YYYYMMDDHH如UTC 时间2018/7/24 17:56:20 则应表示为2018072417。
func TimeStamp() string {
strFormatTime := time.Now().Format("2006-01-02 15:04:05")
strFormatTime = strings.ReplaceAll(strFormatTime, "-", "")
strFormatTime = strings.ReplaceAll(strFormatTime, " ", "")
strFormatTime = strFormatTime[0:10]
return strFormatTime
}
2020-12-20 15:08:43 +08:00
// 设备采集数据UTC时间格式yyyyMMdd'T'HHmmss'Z'20161219T114920Z。
//设备上报数据不带该参数或参数格式错误时,则数据上报时间以平台时间为准。
2020-12-22 23:35:42 +08:00
func GetEventTimeStamp() string {
2020-12-20 15:08:43 +08:00
now := time.Now().UTC()
return now.Format("20060102T150405Z")
}
func HmacSha256(data string, secret string) string {
h := hmac.New(sha256.New, []byte(secret))
h.Write([]byte(data))
return hex.EncodeToString(h.Sum(nil))
}
2020-12-20 15:08:43 +08:00
func Interface2JsonString(v interface{}) string {
2020-12-22 23:35:42 +08:00
if v == nil {
return ""
}
byteData, err := json.Marshal(v)
if err != nil {
return ""
}
return string(byteData)
}
2020-12-20 15:08:43 +08:00
func GetTopicRequestId(topic string) string {
return strings.Split(topic, "=")[1]
}
2020-12-20 15:08:43 +08:00
func FormatTopic(topic, deviceId string) string {
return strings.ReplaceAll(topic, "{device_id}", deviceId)
}
2020-12-22 23:35:42 +08:00
// 根据当前运行的操作系统重新修改文件路径以适配操作系统
func SmartFileName(filename string) string {
// Windows操作系统适配
if strings.Contains(OsName(), "windows") {
pathParts := strings.Split(filename, "/")
pathParts[0] = pathParts[0] + ":"
2020-12-23 23:08:35 +08:00
return strings.Join(pathParts, "\\")
2020-12-22 23:35:42 +08:00
}
return filename
}