调整目录结构和增加样例

This commit is contained in:
ctlove0523 2020-12-20 15:08:43 +08:00
parent 433eb6ff4a
commit 8c95c4f31f
10 changed files with 351 additions and 294 deletions

View File

@ -1,4 +1,4 @@
package iotdevice
package iot
const (
MessageDownTopic string = "$oc/devices/{device_id}/sys/messages/down"

121
handlers.go Normal file
View File

@ -0,0 +1,121 @@
package iot
type CommandHandler func(Command) bool
// 设备命令
type Command struct {
ObjectDeviceId string `json:"object_device_id"`
ServiceId string `json:"service_id""`
CommandName string `json:"command_name"`
Paras interface{} `json:"paras"`
}
type CommandResponse struct {
ResultCode byte `json:"result_code"`
ResponseName string `json:"response_name"`
Paras interface{} `json:"paras"`
}
func SuccessIotCommandResponse() CommandResponse {
return CommandResponse{
ResultCode: 0,
}
}
func FailedIotCommandResponse() CommandResponse {
return CommandResponse{
ResultCode: 1,
}
}
// 设备消息
type MessageHandler func(message Message) bool
type Message struct {
ObjectDeviceId string `json:"object_device_id"`
Name string `json:"name"`
Id string `json:"id"`
Content interface{} `json:"content"`
}
// 设备属性上报
type ServiceProperty struct {
Services []ServicePropertyEntry `json:"services"`
}
type ServicePropertyEntry struct {
ServiceId string `json:"service_id"`
Properties interface{} `json:"properties"`
EventTime string `json:"event_time"`
}
// 平台设置设备属性==================================================
type DevicePropertiesSetHandler func(message DevicePropertyDownRequest) bool
type DevicePropertyDownRequest struct {
ObjectDeviceId string `json:"object_device_id"`
Services []DevicePropertyDownRequestEntry `json:"services"`
}
type DevicePropertyDownRequestEntry struct {
ServiceId string `json:"service_id"`
Properties interface{} `json:"properties"`
}
type DevicePropertyDownResponse struct {
ResultCode byte `json:"result_code"`
ResultDesc string `json:"result_desc"`
}
func SuccessPropertiesSetResponse() DevicePropertyDownResponse {
return DevicePropertyDownResponse{
ResultCode: 0,
ResultDesc: "success set properties",
}
}
func FailedPropertiesSetResponse() DevicePropertyDownResponse {
return DevicePropertyDownResponse{
ResultCode: 1,
ResultDesc: "failed set properties",
}
}
// 平台设置设备属性==================================================
// 平台查询设备属性
type DevicePropertyQueryHandler func(query DevicePropertyQueryRequest) ServicePropertyEntry
type DevicePropertyQueryRequest struct {
ObjectDeviceId string `json:"object_device_id"`
ServiceId string `json:"service_id"`
}
// 设备获取设备影子数据
type DevicePropertyQueryResponseHandler func(response DevicePropertyQueryResponse)
type DevicePropertyQueryResponse struct {
ObjectDeviceId string `json:"object_device_id"`
Shadow []DeviceShadowData `json:"shadow"`
}
type DeviceShadowData struct {
ServiceId string `json:"service_id"`
Desired DeviceShadowPropertiesData `json:"desired"`
Reported DeviceShadowPropertiesData `json:"reported"`
Version int `json:"version"`
}
type DeviceShadowPropertiesData struct {
Properties interface{} `json:"properties"`
EventTime string `json:"event_time"`
}
// 网关批量上报子设备属性
type DevicesService struct {
Devices []DeviceService `json:"devices"`
}
type DeviceService struct {
DeviceId string `json:"device_id"`
Services []ServicePropertyEntry `json:"services"`
}

View File

@ -1,121 +0,0 @@
package handlers
type IotCommandHandler func(IotCommand) bool
// 设备命令
type IotCommand struct {
ObjectDeviceId string `json:"object_device_id"`
ServiceId string `json:"service_id""`
CommandName string `json:"command_name"`
Paras interface{} `json:"paras"`
}
type IotCommandResponse struct {
ResultCode byte `json:"result_code"`
ResponseName string `json:"response_name"`
Paras interface{} `json:"paras"`
}
func SuccessIotCommandResponse() IotCommandResponse {
return IotCommandResponse{
ResultCode: 0,
}
}
func FailedIotCommandResponse() IotCommandResponse {
return IotCommandResponse{
ResultCode: 1,
}
}
// 设备消息
type IotMessageHandler func(message IotMessage) bool
type IotMessage struct {
ObjectDeviceId string `json:"object_device_id"`
Name string `json:"name"`
Id string `json:"id"`
Content interface{} `json:"content"`
}
// 设备属性上报
type IotServiceProperty struct {
Services []IotServicePropertyEntry `json:"services"`
}
type IotServicePropertyEntry struct {
ServiceId string `json:"service_id"`
Properties interface{} `json:"properties"`
EventTime string `json:"event_time"`
}
// 平台设置设备属性==================================================
type IotDevicePropertiesSetHandler func(message IotDevicePropertyDownRequest) bool
type IotDevicePropertyDownRequest struct {
ObjectDeviceId string `json:"object_device_id"`
Services []IotDevicePropertyDownRequestEntry `json:"services"`
}
type IotDevicePropertyDownRequestEntry struct {
ServiceId string `json:"service_id"`
Properties interface{} `json:"properties"`
}
type IotDevicePropertyDownResponse struct {
ResultCode byte `json:"result_code"`
ResultDesc string `json:"result_desc"`
}
func SuccessPropertiesSetResponse() IotDevicePropertyDownResponse {
return IotDevicePropertyDownResponse{
ResultCode: 0,
ResultDesc: "success set properties",
}
}
func FailedPropertiesSetResponse() IotDevicePropertyDownResponse {
return IotDevicePropertyDownResponse{
ResultCode: 1,
ResultDesc: "failed set properties",
}
}
// 平台设置设备属性==================================================
// 平台查询设备属性
type IotDevicePropertyQueryHandler func(query IotDevicePropertyQueryRequest) IotServicePropertyEntry
type IotDevicePropertyQueryRequest struct {
ObjectDeviceId string `json:"object_device_id"`
ServiceId string `json:"service_id"`
}
// 设备获取设备影子数据
type IotDevicePropertyQueryResponseHandler func(response IotDevicePropertyQueryResponse)
type IotDevicePropertyQueryResponse struct {
ObjectDeviceId string `json:"object_device_id"`
Shadow []IotDeviceShadowData `json:"shadow"`
}
type IotDeviceShadowData struct {
ServiceId string `json:"service_id"`
Desired IotDeviceShadowPropertiesData `json:"desired"`
Reported IotDeviceShadowPropertiesData `json:"reported"`
Version int `json:"version"`
}
type IotDeviceShadowPropertiesData struct {
Properties interface{} `json:"properties"`
EventTime string `json:"event_time"`
}
// 网关批量上报子设备属性
type IotDevicesService struct {
Devices []IotDeviceService `json:"devices"`
}
type IotDeviceService struct {
DeviceId string `json:"device_id"`
Services []IotServicePropertyEntry `json:"services"`
}

View File

@ -1,25 +1,24 @@
package iotdevice
package iot
import (
"encoding/json"
"fmt"
mqtt "github.com/eclipse/paho.mqtt.golang"
"github.com/satori/go.uuid"
"huaweicloud-iot-device-sdk-go/handlers"
"strings"
)
type IotDevice interface {
type Device interface {
Init() bool
IsConnected() bool
SendMessage(message handlers.IotMessage) bool
ReportProperties(properties handlers.IotServiceProperty) bool
BatchReportSubDevicesProperties(service handlers.IotDevicesService)
QueryDeviceShadow(query handlers.IotDevicePropertyQueryRequest, handler handlers.IotDevicePropertyQueryResponseHandler)
AddMessageHandler(handler handlers.IotMessageHandler)
AddCommandHandler(handler handlers.IotCommandHandler)
AddPropertiesSetHandler(handler handlers.IotDevicePropertiesSetHandler)
SetPropertyQueryHandler(handler handlers.IotDevicePropertyQueryHandler)
SendMessage(message Message) bool
ReportProperties(properties ServiceProperty) bool
BatchReportSubDevicesProperties(service DevicesService)
QueryDeviceShadow(query DevicePropertyQueryRequest, handler DevicePropertyQueryResponseHandler)
AddMessageHandler(handler MessageHandler)
AddCommandHandler(handler CommandHandler)
AddPropertiesSetHandler(handler DevicePropertiesSetHandler)
SetPropertyQueryHandler(handler DevicePropertyQueryHandler)
}
type iotDevice struct {
@ -27,17 +26,17 @@ type iotDevice struct {
Password string
Servers string
client mqtt.Client
commandHandlers []handlers.IotCommandHandler
messageHandlers []handlers.IotMessageHandler
propertiesSetHandlers []handlers.IotDevicePropertiesSetHandler
propertyQueryHandler handlers.IotDevicePropertyQueryHandler
propertiesQueryResponseHandler handlers.IotDevicePropertyQueryResponseHandler
commandHandlers []CommandHandler
messageHandlers []MessageHandler
propertiesSetHandlers []DevicePropertiesSetHandler
propertyQueryHandler DevicePropertyQueryHandler
propertiesQueryResponseHandler DevicePropertyQueryResponseHandler
topics map[string]string
}
func (device *iotDevice) createMessageMqttHandler() func(client mqtt.Client, message mqtt.Message) {
messageHandler := func(client mqtt.Client, message mqtt.Message) {
msg := &handlers.IotMessage{}
msg := &Message{}
if json.Unmarshal(message.Payload(), msg) != nil {
fmt.Println("unmarshal device message failed")
}
@ -52,7 +51,7 @@ func (device *iotDevice) createMessageMqttHandler() func(client mqtt.Client, mes
func (device *iotDevice) createCommandMqttHandler() func(client mqtt.Client, message mqtt.Message) {
commandHandler := func(client mqtt.Client, message mqtt.Message) {
command := &handlers.IotCommand{}
command := &Command{}
if json.Unmarshal(message.Payload(), command) != nil {
fmt.Println("unmarshal failed")
}
@ -63,11 +62,11 @@ func (device *iotDevice) createCommandMqttHandler() func(client mqtt.Client, mes
}
var res string
if handleFlag {
res = JsonString(handlers.SuccessIotCommandResponse())
res = Interface2JsonString(SuccessIotCommandResponse())
} else {
res = JsonString(handlers.FailedIotCommandResponse())
res = Interface2JsonString(FailedIotCommandResponse())
}
if token := device.client.Publish(device.topics[CommandResponseTopicName]+TopicRequestId(message.Topic()), 1, false, res);
if token := device.client.Publish(device.topics[CommandResponseTopicName]+GetTopicRequestId(message.Topic()), 1, false, res);
token.Wait() && token.Error() != nil {
fmt.Println("send command response failed")
}
@ -78,7 +77,7 @@ func (device *iotDevice) createCommandMqttHandler() func(client mqtt.Client, mes
func (device *iotDevice) createPropertiesSetMqttHandler() func(client mqtt.Client, message mqtt.Message) {
propertiesSetHandler := func(client mqtt.Client, message mqtt.Message) {
propertiesSetRequest := &handlers.IotDevicePropertyDownRequest{}
propertiesSetRequest := &DevicePropertyDownRequest{}
if json.Unmarshal(message.Payload(), propertiesSetRequest) != nil {
fmt.Println("unmarshal failed")
}
@ -90,11 +89,11 @@ func (device *iotDevice) createPropertiesSetMqttHandler() func(client mqtt.Clien
var res string
if handleFlag {
res = JsonString(handlers.SuccessPropertiesSetResponse())
res = Interface2JsonString(SuccessPropertiesSetResponse())
} else {
res = JsonString(handlers.FailedPropertiesSetResponse())
res = Interface2JsonString(FailedPropertiesSetResponse())
}
if token := device.client.Publish(device.topics[PropertiesSetResponseTopicName]+TopicRequestId(message.Topic()), 1, false, res);
if token := device.client.Publish(device.topics[PropertiesSetResponseTopicName]+GetTopicRequestId(message.Topic()), 1, false, res);
token.Wait() && token.Error() != nil {
fmt.Println("send properties set response failed")
}
@ -105,14 +104,14 @@ func (device *iotDevice) createPropertiesSetMqttHandler() func(client mqtt.Clien
func (device *iotDevice) createPropertiesQueryMqttHandler() func(client mqtt.Client, message mqtt.Message) {
propertiesQueryHandler := func(client mqtt.Client, message mqtt.Message) {
propertiesQueryRequest := &handlers.IotDevicePropertyQueryRequest{}
propertiesQueryRequest := &DevicePropertyQueryRequest{}
if json.Unmarshal(message.Payload(), propertiesQueryRequest) != nil {
fmt.Println("unmarshal failed")
}
queryResult := device.propertyQueryHandler(*propertiesQueryRequest)
responseToPlatform := JsonString(queryResult)
if token := device.client.Publish(device.topics[PropertiesQueryResponseTopicName]+TopicRequestId(message.Topic()), 1, false, responseToPlatform);
responseToPlatform := Interface2JsonString(queryResult)
if token := device.client.Publish(device.topics[PropertiesQueryResponseTopicName]+GetTopicRequestId(message.Topic()), 1, false, responseToPlatform);
token.Wait() && token.Error() != nil {
fmt.Println("send properties set response failed")
}
@ -123,7 +122,7 @@ func (device *iotDevice) createPropertiesQueryMqttHandler() func(client mqtt.Cli
func (device *iotDevice) createPropertiesQueryResponseMqttHandler() func(client mqtt.Client, message mqtt.Message) {
propertiesQueryResponseHandler := func(client mqtt.Client, message mqtt.Message) {
propertiesQueryResponse := &handlers.IotDevicePropertyQueryResponse{}
propertiesQueryResponse := &DevicePropertyQueryResponse{}
if json.Unmarshal(message.Payload(), propertiesQueryResponse) != nil {
fmt.Println("unmarshal failed")
}
@ -198,8 +197,8 @@ func (device *iotDevice) IsConnected() bool {
return false
}
func (device *iotDevice) SendMessage(message handlers.IotMessage) bool {
messageData := JsonString(message)
func (device *iotDevice) SendMessage(message Message) bool {
messageData := Interface2JsonString(message)
if token := device.client.Publish(device.topics[MessageUpTopicName], 2, false, messageData);
token.Wait() && token.Error() != nil {
fmt.Println("send message failed")
@ -209,8 +208,8 @@ func (device *iotDevice) SendMessage(message handlers.IotMessage) bool {
return true
}
func (device *iotDevice) ReportProperties(properties handlers.IotServiceProperty) bool {
propertiesData := JsonString(properties)
func (device *iotDevice) ReportProperties(properties ServiceProperty) bool {
propertiesData := Interface2JsonString(properties)
if token := device.client.Publish(device.topics[PropertiesUpTopicName], 2, false, propertiesData);
token.Wait() && token.Error() != nil {
fmt.Println("report properties failed")
@ -219,31 +218,31 @@ func (device *iotDevice) ReportProperties(properties handlers.IotServiceProperty
return true
}
func (device *iotDevice) BatchReportSubDevicesProperties(service handlers.IotDevicesService) {
if token:=device.client.Publish(device.topics[GatewayBatchReportSubDeviceTopicName],2,false,JsonString(service));
token.Wait() && token.Error() != nil {
func (device *iotDevice) BatchReportSubDevicesProperties(service DevicesService) {
if token:=device.client.Publish(device.topics[GatewayBatchReportSubDeviceTopicName],2,false, Interface2JsonString(service));
token.Wait() && token.Error() != nil {
fmt.Println("batch report sub device properties failed")
}
}
func (device *iotDevice) QueryDeviceShadow(query handlers.IotDevicePropertyQueryRequest, handler handlers.IotDevicePropertyQueryResponseHandler) {
func (device *iotDevice) QueryDeviceShadow(query DevicePropertyQueryRequest, handler DevicePropertyQueryResponseHandler) {
device.propertiesQueryResponseHandler = handler
requestId := uuid.NewV4()
fmt.Println(requestId)
if token := device.client.Publish(device.topics[DeviceShadowQueryRequestTopicName]+requestId.String(), 2, false, JsonString(query));
if token := device.client.Publish(device.topics[DeviceShadowQueryRequestTopicName]+requestId.String(), 2, false, Interface2JsonString(query));
token.Wait() && token.Error() != nil {
fmt.Println("query device shadow data failed")
}
}
func (device *iotDevice) AddMessageHandler(handler handlers.IotMessageHandler) {
func (device *iotDevice) AddMessageHandler(handler MessageHandler) {
if handler == nil {
return
}
device.messageHandlers = append(device.messageHandlers, handler)
}
func (device *iotDevice) AddCommandHandler(handler handlers.IotCommandHandler) {
func (device *iotDevice) AddCommandHandler(handler CommandHandler) {
if handler == nil {
return
}
@ -251,18 +250,18 @@ func (device *iotDevice) AddCommandHandler(handler handlers.IotCommandHandler) {
device.commandHandlers = append(device.commandHandlers, handler)
}
func (device *iotDevice) AddPropertiesSetHandler(handler handlers.IotDevicePropertiesSetHandler) {
func (device *iotDevice) AddPropertiesSetHandler(handler DevicePropertiesSetHandler) {
if handler == nil {
return
}
device.propertiesSetHandlers = append(device.propertiesSetHandlers, handler)
}
func (device *iotDevice) SetPropertyQueryHandler(handler handlers.IotDevicePropertyQueryHandler) {
func (device *iotDevice) SetPropertyQueryHandler(handler DevicePropertyQueryHandler) {
device.propertyQueryHandler = handler
}
//func (device *iotDevice) SetPropertiesQueryResponseHandler(handler handlers.IotDevicePropertyQueryResponseHandler) {
//func (device *iotDevice) SetPropertiesQueryResponseHandler(handler samples.IotDevicePropertyQueryResponseHandler) {
// device.propertiesQueryResponseHandler = handler
//}
@ -276,27 +275,27 @@ func assembleClientId(device *iotDevice) string {
return strings.Join(segments, "_")
}
func CreateIotDevice(id, password, servers string) IotDevice {
func CreateIotDevice(id, password, servers string) Device {
device := &iotDevice{}
device.Id = id
device.Password = password
device.Servers = servers
device.messageHandlers = []handlers.IotMessageHandler{}
device.commandHandlers = []handlers.IotCommandHandler{}
device.messageHandlers = []MessageHandler{}
device.commandHandlers = []CommandHandler{}
// 初始化设备相关的所有topic
device.topics = make(map[string]string)
device.topics[MessageDownTopicName] = TopicFormat(MessageDownTopic, id)
device.topics[CommandDownTopicName] = TopicFormat(CommandDownTopic, id)
device.topics[CommandResponseTopicName] = TopicFormat(CommandResponseTopic, id)
device.topics[MessageUpTopicName] = TopicFormat(MessageUpTopic, id)
device.topics[PropertiesUpTopicName] = TopicFormat(PropertiesUpTopic, id)
device.topics[PropertiesSetRequestTopicName] = TopicFormat(PropertiesSetRequestTopic, id)
device.topics[PropertiesSetResponseTopicName] = TopicFormat(PropertiesSetResponseTopic, id)
device.topics[PropertiesQueryRequestTopicName] = TopicFormat(PropertiesQueryRequestTopic, id)
device.topics[PropertiesQueryResponseTopicName] = TopicFormat(PropertiesQueryResponseTopic, id)
device.topics[DeviceShadowQueryRequestTopicName] = TopicFormat(DeviceShadowQueryRequestTopic, id)
device.topics[DeviceShadowQueryResponseTopicName] = TopicFormat(DeviceShadowQueryResponseTopic, id)
device.topics[GatewayBatchReportSubDeviceTopicName] = TopicFormat(GatewayBatchReportSubDeviceTopic, id)
device.topics[MessageDownTopicName] = FormatTopic(MessageDownTopic, id)
device.topics[CommandDownTopicName] = FormatTopic(CommandDownTopic, id)
device.topics[CommandResponseTopicName] = FormatTopic(CommandResponseTopic, id)
device.topics[MessageUpTopicName] = FormatTopic(MessageUpTopic, id)
device.topics[PropertiesUpTopicName] = FormatTopic(PropertiesUpTopic, id)
device.topics[PropertiesSetRequestTopicName] = FormatTopic(PropertiesSetRequestTopic, id)
device.topics[PropertiesSetResponseTopicName] = FormatTopic(PropertiesSetResponseTopic, id)
device.topics[PropertiesQueryRequestTopicName] = FormatTopic(PropertiesQueryRequestTopic, id)
device.topics[PropertiesQueryResponseTopicName] = FormatTopic(PropertiesQueryResponseTopic, id)
device.topics[DeviceShadowQueryRequestTopicName] = FormatTopic(DeviceShadowQueryRequestTopic, id)
device.topics[DeviceShadowQueryResponseTopicName] = FormatTopic(DeviceShadowQueryResponseTopic, id)
device.topics[GatewayBatchReportSubDeviceTopicName] = FormatTopic(GatewayBatchReportSubDeviceTopic, id)
return device
}

110
main.go
View File

@ -1,110 +0,0 @@
package main
import (
"encoding/json"
"fmt"
"huaweicloud-iot-device-sdk-go/handlers"
"huaweicloud-iot-device-sdk-go/iotdevice"
"time"
)
func main() {
device := iotdevice.CreateIotDevice("5fdb75cccbfe2f02ce81d4bf_go-mqtt", "123456789", "tcp://iot-mqtts.cn-north-4.myhuaweicloud.com:1883")
device.Init()
device.AddCommandHandler(func(command handlers.IotCommand) bool {
fmt.Println("I get command from platform")
return true
})
device.AddMessageHandler(func(message handlers.IotMessage) bool {
fmt.Println("get message from platform")
fmt.Println(message.Content)
return true
})
device.AddPropertiesSetHandler(func(message handlers.IotDevicePropertyDownRequest) bool {
fmt.Println("I get property set command")
fmt.Println(message)
return true
})
device.SetPropertyQueryHandler(func(query handlers.IotDevicePropertyQueryRequest) handlers.IotServicePropertyEntry {
return handlers.IotServicePropertyEntry{
ServiceId: "value",
Properties: SelfProperties{
Value: "QUERY RESPONSE",
MsgType: "query property",
},
EventTime: "2020-12-19 02:23:24",
}
})
message := handlers.IotMessage{
ObjectDeviceId: "chen tong",
Name: "chen tong send message",
Id: "id",
Content: "hello platform",
}
device.SendMessage(message)
props := handlers.IotServicePropertyEntry{
ServiceId: "value",
EventTime: "2020-12-19 02:23:24",
Properties: SelfProperties{
Value: "chen tong",
MsgType: "10",
},
}
var content []handlers.IotServicePropertyEntry
content = append(content, props)
services := handlers.IotServiceProperty{
Services: content,
}
device.ReportProperties(services)
device.QueryDeviceShadow(handlers.IotDevicePropertyQueryRequest{
ServiceId: "value",
}, func(response handlers.IotDevicePropertyQueryResponse) {
fmt.Println(response.Shadow)
})
// 批量上报子设备属性
subDevice1 := handlers.IotDeviceService{
DeviceId: "5fdb75cccbfe2f02ce81d4bf_sub-device-1",
Services: content,
}
subDevice2 := handlers.IotDeviceService{
DeviceId: "5fdb75cccbfe2f02ce81d4bf_sub-device-2",
Services: content,
}
subDevice3 := handlers.IotDeviceService{
DeviceId: "5fdb75cccbfe2f02ce81d4bf_sub-device-3",
Services: content,
}
var devices []handlers.IotDeviceService
devices = append(devices, subDevice1, subDevice2, subDevice3)
fmt.Println("begin to batch report")
fmt.Println(JsonString(handlers.IotDevicesService{
Devices: devices,
}))
device.BatchReportSubDevicesProperties(handlers.IotDevicesService{
Devices: devices,
})
time.Sleep(time.Hour)
}
func JsonString(v interface{}) string {
byteData, err := json.Marshal(v)
if err != nil {
return ""
}
return string(byteData)
}
type SelfProperties struct {
Value string `json:"value"`
MsgType string `json:"msgType"`
}

View File

@ -0,0 +1,21 @@
package main
import (
"fmt"
"huaweicloud-iot-device-sdk-go"
"time"
)
// 处理平台下发的同步命令
func main() {
// 创建一个设备并初始化
device := iot.CreateIotDevice("5fdb75cccbfe2f02ce81d4bf_go-mqtt", "123456789", "tcp://iot-mqtts.cn-north-4.myhuaweicloud.com:1883")
device.Init()
// 添加用于处理平台下发命令的callback
device.AddCommandHandler(func(command iot.Command) bool {
fmt.Println("I get command from platform")
return true
})
time.Sleep(1 * time.Minute)
}

38
samples/message/msg.go Normal file
View File

@ -0,0 +1,38 @@
package main
import (
"fmt"
uuid "github.com/satori/go.uuid"
iot "huaweicloud-iot-device-sdk-go"
"time"
)
func main() {
// 创建一个设备并初始化
device := iot.CreateIotDevice("5fdb75cccbfe2f02ce81d4bf_go-mqtt", "123456789", "tcp://iot-mqtts.cn-north-4.myhuaweicloud.com:1883")
device.Init()
// 注册平台下发消息的callback当收到平台下发的消息时调用此callback.
// 支持注册多个callback并且按照注册顺序调用
device.AddMessageHandler(func(message iot.Message) bool {
fmt.Println("first handler called" + iot.Interface2JsonString(message))
return true
})
device.AddMessageHandler(func(message iot.Message) bool {
fmt.Println("second handler called" + iot.Interface2JsonString(message))
return true
})
//向平台发送消息
message := iot.Message{
ObjectDeviceId: uuid.NewV4().String(),
Name: "Fist send message to platform",
Id: uuid.NewV4().String(),
Content: "Hello Huawei IoT Platform",
}
device.SendMessage(message)
time.Sleep(2 * time.Minute)
}

View File

@ -0,0 +1,85 @@
package main
import (
"fmt"
iot "huaweicloud-iot-device-sdk-go"
"time"
)
func main() {
// 创建设备并初始化
device := iot.CreateIotDevice("5fdb75cccbfe2f02ce81d4bf_go-mqtt", "123456789", "tcp://iot-mqtts.cn-north-4.myhuaweicloud.com:1883")
device.Init()
fmt.Printf("device connected: %v\n", device.IsConnected())
// 注册平台设置属性callback,当应用通过API设置设备属性时会调用此callback支持注册多个callback
device.AddPropertiesSetHandler(func(propertiesSetRequest iot.DevicePropertyDownRequest) bool {
fmt.Println("I get property set command")
fmt.Printf("request is %s", iot.Interface2JsonString(propertiesSetRequest))
return true
})
// 注册平台查询设备属性callback当平台查询设备属性时此callback被调用仅支持设置一个callback
device.SetPropertyQueryHandler(func(query iot.DevicePropertyQueryRequest) iot.ServicePropertyEntry {
return iot.ServicePropertyEntry{
ServiceId: "value",
Properties: DemoProperties{
Value: "QUERY RESPONSE",
MsgType: "query property",
},
EventTime: "2020-12-19 02:23:24",
}
})
// 设备上报属性
props := iot.ServicePropertyEntry{
ServiceId: "value",
EventTime: iot.DataCollectionTime(),
Properties: DemoProperties{
Value: "chen tong",
MsgType: "23",
},
}
var content []iot.ServicePropertyEntry
content = append(content, props)
services := iot.ServiceProperty{
Services: content,
}
device.ReportProperties(services)
// 设备查询设备影子数据
device.QueryDeviceShadow(iot.DevicePropertyQueryRequest{
ServiceId: "value",
}, func(response iot.DevicePropertyQueryResponse) {
fmt.Printf("query device shadow success.\n,device shadow data is %s\n",iot.Interface2JsonString(response))
})
// 批量上报子设备属性
subDevice1 := iot.DeviceService{
DeviceId: "5fdb75cccbfe2f02ce81d4bf_sub-device-1",
Services: content,
}
subDevice2 := iot.DeviceService{
DeviceId: "5fdb75cccbfe2f02ce81d4bf_sub-device-2",
Services: content,
}
subDevice3 := iot.DeviceService{
DeviceId: "5fdb75cccbfe2f02ce81d4bf_sub-device-3",
Services: content,
}
var devices []iot.DeviceService
devices = append(devices, subDevice1, subDevice2, subDevice3)
device.BatchReportSubDevicesProperties(iot.DevicesService{
Devices: devices,
})
time.Sleep(1 * time.Minute)
}
type DemoProperties struct {
Value string `json:"value"`
MsgType string `json:"msgType"`
}

16
samples/test.go Normal file
View File

@ -0,0 +1,16 @@
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now().UTC()
//now = now.Add(8 * time.Hour)
fmt.Println(now.Format("20060102T150405Z"))
fmt.Println(now.Location())
fmt.Println(now.Zone())
fmt.Println(now.Unix())
}

View File

@ -1,4 +1,4 @@
package iotdevice
package iot
import (
"crypto/hmac"
@ -9,6 +9,7 @@ import (
"time"
)
// 时间戳为设备连接平台时的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, "-", "")
@ -17,13 +18,20 @@ func TimeStamp() string {
return strFormatTime
}
// 设备采集数据UTC时间格式yyyyMMdd'T'HHmmss'Z'20161219T114920Z。
//设备上报数据不带该参数或参数格式错误时,则数据上报时间以平台时间为准。
func DataCollectionTime() string {
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))
}
func JsonString(v interface{}) string {
func Interface2JsonString(v interface{}) string {
byteData, err := json.Marshal(v)
if err != nil {
return ""
@ -31,10 +39,10 @@ func JsonString(v interface{}) string {
return string(byteData)
}
func TopicRequestId(topic string) string {
func GetTopicRequestId(topic string) string {
return strings.Split(topic, "=")[1]
}
func TopicFormat(topic, deviceId string) string {
func FormatTopic(topic, deviceId string) string {
return strings.ReplaceAll(topic, "{device_id}", deviceId)
}