From 7aa1a9e293cf054df68b6ade282133a2181b0dd2 Mon Sep 17 00:00:00 2001 From: ctlove0523 <478309639@qq.com> Date: Mon, 29 Mar 2021 21:53:03 +0800 Subject: [PATCH] prepare for async --- async/message/msg.go | 42 ++++++++++++++++++++++++++++++++++++++++++ async_device.go | 2 +- 2 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 async/message/msg.go diff --git a/async/message/msg.go b/async/message/msg.go new file mode 100644 index 0000000..a09c111 --- /dev/null +++ b/async/message/msg.go @@ -0,0 +1,42 @@ +package main + +import ( + "fmt" + iot "github.com/ctlove0523/huaweicloud-iot-device-sdk-go" + uuid "github.com/satori/go.uuid" + "time" +) + +func main() { + // 创建一个设备并初始化 + device := iot.CreateAsyncIotDevice("5fdb75cccbfe2f02ce81d4bf_liqian", "123456789", "tls://iot-mqtts.cn-north-4.myhuaweicloud.com:8883") + 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", + } + asyncResult:=device.SendMessage(message) + if asyncResult.Wait() && asyncResult.Error()!= nil { + fmt.Println("async send message failed") + } else { + fmt.Println("async send message success") + } + time.Sleep(2 * time.Minute) + +} diff --git a/async_device.go b/async_device.go index 534223a..8062c1f 100644 --- a/async_device.go +++ b/async_device.go @@ -9,7 +9,7 @@ import ( type AsyncDevice interface { BaseDevice Gateway - SendMessage(message Message) AsyncResult + SendMessage(message Message) BooleanAsyncResult ReportProperties(properties DeviceProperties) AsyncResult BatchReportSubDevicesProperties(service DevicesService) AsyncResult QueryDeviceShadow(query DevicePropertyQueryRequest, handler DevicePropertyQueryResponseHandler) AsyncResult