iot

package module
v1.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 16, 2022 License: Apache-2.0 Imports: 21 Imported by: 0

README

huaweicloud-iot-device-sdk-go

huaweicloud-iot-device-sdk-go提供设备接入华为云IoT物联网平台的Go版本的SDK,提供设备和平台之间通讯能力,以及设备服务、网关服务、OTA等高级服务。IoT设备开发者使用SDK可以大大简化开发复杂度,快速的接入平台。

支持如下功能:

版本说明

当前稳定版本:v1.0.1

安装和构建

安装和构建的过程取决于你是使用go的 modules(推荐) 还是还是GOPATH

Modules

如果你使用 modules 只需要导入包"github.com/ctlove0523/huaweicloud-iot-device-sdk-go"即可使用。当你使用go build命令构建项目时,依赖的包会自动被下载。注意使用go build命令构建时会自动下载最新版本,最新版本还没有达到release的标准可能存在一些尚未修复的bug。如果想使用稳定的发布版本可以从release 获取最新稳定的版本号,并在go.mod文件中指定版本号。

module example

go 1.15

require github.com/ctlove0523/huaweicloud-iot-device-sdk-go v0.0.1-alpha
GOPATH

如果你使用GOPATH,下面的一条命令即可实现安装

go get github.com/ctlove0523/huaweicloud-iot-device-sdk-go

使用API

SDK提供了异步client,下面所有的方法都有对应的异步方法。

设备连接鉴权
使用密钥鉴权

1、首先,在华为云IoT平台创建一个设备,设备的信息如下:

设备ID:5fdb75cccbfe2f02ce81d4bf_go-mqtt

设备密钥:123456789

2、使用SDK创建一个Device对象,并初始化Device。

import (
	"fmt"
	"github.com/ctlove0523/huaweicloud-iot-device-sdk-go"
	"time"
)

func main() {
	// 创建一个设备并初始化
	device := iot.CreateIotDevice("5fdb75cccbfe2f02ce81d4bf_go-mqtt", "123456789", "tls://iot-mqtts.cn-north-4.myhuaweicloud.com:8883")
	device.Init()
	if device.IsConnected() {
		fmt.Println("device connect huawei iot platform success")
	} else {
		fmt.Println("device connect huawei iot platform failed")
	}
}

iot-mqtts.cn-north-4.myhuaweicloud.com为华为IoT平台(基础班)在华为云北京四的访问端点,如果你购买了标准版或企业版,请将iot-mqtts.cn-north-4.myhuaweicloud.com更换为对应的MQTT协议接入端点。

使用x.509证书鉴权

1、根据华为云文档创建证书并注册设备

华为云文档

2、使用SDK创建一个使用x.509证书鉴权的设备并初始化

使用x.509证书鉴权需要获取平台的ca证书,并已经创建获取了设备的证书,具体可以参考上面的华为云文档。

caPath := "your ca path"
certFilePath := "your cert path"
certKeyFilePath := "your key path"

config := iot.DeviceConfig{
	Id:              "your device id",
	Servers:         "tls://iot-mqtts.cn-north-4.myhuaweicloud.com:8883",
	AuthType:        iot.AUTH_TYPE_X509,
	ServerCaPath:    caPath,
	CertFilePath:    certFilePath,
	CertKeyFilePath: certKeyFilePath,
}

device := iot.CreateIotDeviceWitConfig(config)

res := device.Init()
fmt.Println(res)

使用x.509证书鉴权必须设置AuthType的值为1(iot.AUTH_TYPE_X509),否则默认使用密码进行鉴权

设备命令

1、首先,在华为云IoT平台创建一个设备,设备的信息如下:

设备ID:5fdb75cccbfe2f02ce81d4bf_go-mqtt

设备密钥:123456789

2、使用SDK创建一个Device对象,并初始化Device。

// 创建一个设备并初始化
device := iot.CreateIotDevice("5fdb75cccbfe2f02ce81d4bf_go-mqtt", "123456789", "tls://iot-mqtts.cn-north-4.myhuaweicloud.com:8883")
device.Init()
if device.IsConnected() {
	fmt.Println("device connect huawei iot platform success")
} else {
	fmt.Println("device connect huawei iot platform failed")
}

3、注册命令处理handler,支持注册多个handler并且按照注册的顺序回调

// 添加用于处理平台下发命令的callback
device.AddCommandHandler(func(command iot.Command) bool {
	fmt.Println("First command handler begin to process command.")
	return true
})

device.AddCommandHandler(func(command iot.Command) bool {
	fmt.Println("Second command handler begin to process command.")
	return true
})

4、通过应用侧API向设备下发一个命令,可以看到程序输出如下:

device connect huawei iot platform success
First command handler begin to process command.
Second command handler begin to process command.
完整样例
import (
	"fmt"
	"github.com/ctlove0523/huaweicloud-iot-device-sdk-go"
	"time"
)

// 处理平台下发的同步命令
func main() {
	// 创建一个设备并初始化
	device := iot.CreateIotDevice("5fdb75cccbfe2f02ce81d4bf_go-mqtt", "123456789", "tls://iot-mqtts.cn-north-4.myhuaweicloud.com:8883")
	device.Init()
	if device.IsConnected() {
		fmt.Println("device connect huawei iot platform success")
	} else {
		fmt.Println("device connect huawei iot platform failed")
	}

	// 添加用于处理平台下发命令的callback
	device.AddCommandHandler(func(command iot.Command) bool {
		fmt.Println("First command handler begin to process command.")
		return true
	})

	device.AddCommandHandler(func(command iot.Command) bool {
		fmt.Println("Second command handler begin to process command.")
		return true
	})
	time.Sleep(1 * time.Minute)
}

设备支持的命令定义在产品中

设备消息

1、首先,在华为云IoT平台创建一个设备,设备的信息如下:

设备ID:5fdb75cccbfe2f02ce81d4bf_go-mqtt

设备密钥:123456789

2、使用SDK创建一个Device对象,并初始化Device。

device := iot.CreateIotDevice("5fdb75cccbfe2f02ce81d4bf_go-mqtt", "123456789", "tls://iot-mqtts.cn-north-4.myhuaweicloud.com:8883")
	device.Init()
设备消息上报
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)
平台消息下发

接收平台下发的消息,只需注册消息处理handler,支持注册多个handler并按照注册顺序回调。

// 注册平台下发消息的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
})
完整样例
import (
	"fmt"
	iot "github.com/ctlove0523/huaweicloud-iot-device-sdk-go"
	uuid "github.com/satori/go.uuid"
	"time"
)

func main() {
	// 创建一个设备并初始化
	device := iot.CreateIotDevice("5fdb75cccbfe2f02ce81d4bf_go-mqtt", "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",
	}
	device.SendMessage(message)
	time.Sleep(2 * time.Minute)

}
设备属性

1、首先,在华为云IoT平台创建一个设备,并在该设备下创建3个子设备,设备及子设备的信息如下:

设备ID:5fdb75cccbfe2f02ce81d4bf_go-mqtt

设备密钥:123456789

子设备ID:5fdb75cccbfe2f02ce81d4bf_sub-device-1

子设备ID:5fdb75cccbfe2f02ce81d4bf_sub-device-2

子设备ID:5fdb75cccbfe2f02ce81d4bf_sub-device-3

2、使用SDK创建一个Device对象,并初始化Device。

// 创建设备并初始化
device := iot.CreateIotDevice("5fdb75cccbfe2f02ce81d4bf_go-mqtt", "123456789", "tls://iot-mqtts.cn-north-4.myhuaweicloud.com:8883")
device.Init()
fmt.Printf("device connected: %v\n", device.IsConnected())
设备属性上报

使用ReportProperties(properties ServiceProperty) bool 上报设备属性

// 设备上报属性
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)
网关批量设备属性上报

使用BatchReportSubDevicesProperties(service DevicesService) 实现网关批量设备属性上报

// 批量上报子设备属性
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,
})
平台设置设备属性

使用AddPropertiesSetHandler(handler DevicePropertiesSetHandler) 注册平台设置设备属性handler,当接收到平台的命令时SDK回调。

// 注册平台设置属性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
})
平台查询设备属性

使用SetPropertyQueryHandler(handler DevicePropertyQueryHandler)注册平台查询设备属性handler,当接收到平台的查询请求时SDK回调。

// 注册平台查询设备属性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",
	}
})
设备侧获取平台的设备影子数据

使用QueryDeviceShadow(query DevicePropertyQueryRequest, handler DevicePropertyQueryResponseHandler) 可以查询平台的设备影子数据,当接收到平台的响应后SDK自动回调DevicePropertyQueryResponseHandler

// 设备查询设备影子数据
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))
})
完整样例
import (
	"fmt"
	iot "github.com/ctlove0523/huaweicloud-iot-device-sdk-go"
	"time"
)

func main() {
	// 创建设备并初始化
	device := iot.CreateIotDevice("5fdb75cccbfe2f02ce81d4bf_go-mqtt", "123456789", "tls://iot-mqtts.cn-north-4.myhuaweicloud.com:8883")
	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"`
}
文件上传/下载管理
文件上传
device := iot.CreateIotDevice("5fdb75cccbfe2f02ce81d4bf_go-mqtt", "xxx", "tls://iot-mqtts.cn-north-4.myhuaweicloud.com:8883")
device.Init()

device.UploadFile("D/software/mqttfx/chentong.txt")
网关与子设备管理

当前SDK没有内置mqtt broker模块,对mqtt broker的支持正在开发中

网关接收子设备新增和删除通知

网关如果要处理子设备新增和删除,需要注册对应的handler让SDK调用。

device := iot.CreateIotDevice("xxx", "xxx", "tls://iot-mqtts.cn-north-4.myhuaweicloud.com:8883")

// 处理子设备添加
device.SetSubDevicesAddHandler(func(devices iot.SubDeviceInfo) {
	for _, info := range devices.Devices {
		fmt.Println("handle device add")
		fmt.Println(iot.Interface2JsonString(info))
	}
})

// 处理子设备删除
device.SetSubDevicesDeleteHandler(func(devices iot.SubDeviceInfo) {
	for _, info := range devices.Devices {
		fmt.Println("handle device delete")
		fmt.Println(iot.Interface2JsonString(info))
	}
})

device.Init()
网关同步子设备列表
  • 同步所有版本的子设备

    device := iot.CreateIotDevice("xxx", "xxx", "tls://iot-mqtts.cn-north-4.myhuaweicloud.com:8883")
    device.Init()
    device.SyncAllVersionSubDevices()
    
  • 同步指定版本的子设备

    device := iot.CreateIotDevice("xxx", "xxx", "tls://iot-mqtts.cn-north-4.myhuaweicloud.com:8883")
    device.Init()
    device.SyncSubDevices(version int)
    
网关新增子设备
device := iot.CreateIotDevice("xxx", "xxx", "tls://iot-mqtts.cn-north-4.myhuaweicloud.com:8883")
device.Init()
result:= device.AddSubDevices(deviceInfos) // deviceInfos 的类型为[]DeviceInfo
网关删除子设备
device := iot.CreateIotDevice("xxx", "xxx", "tls://iot-mqtts.cn-north-4.myhuaweicloud.com:8883")
device.Init()
result:= device.DeleteSubDevices(deviceIds) // deviceIds的类型为[]string
网关更新子设备状态
device := iot.CreateIotDevice("xxx", "xxx", "tls://iot-mqtts.cn-north-4.myhuaweicloud.com:8883")
device.Init()
result:= device.UpdateSubDeviceState(subDevicesStatus) //subDevicesStatus的类型SubDevicesStatus
设备信息上报

设备可以向平台上报SDK版本、软固件版本信息,其中SDK的版本信息SDK自动填充

device := iot.CreateIotDevice("xxx", "xxx", "tls://iot-mqtts.cn-north-4.myhuaweicloud.com:8883")
device.Init()

device.ReportDeviceInfo("1.0", "2.0")
设备日志收集

设备日志功能主要包括:平台下发日志收集命令,设备上报平台指定时间段内的日志;设备调用接口主动上报日志。

  • 设备响应平台日志收集命令

    设备响应日志收集功能需要实现日志收集函数,函数的定义如下:

    // 设备状态日志收集器
    type DeviceStatusLogCollector func(endTime string) []DeviceLogEntry
    
    // 设备属性日志收集器
    type DevicePropertyLogCollector func(endTime string) []DeviceLogEntry
    
    // 设备消息日志收集器
    type DeviceMessageLogCollector func(endTime string) []DeviceLogEntry
    
    // 设备命令日志收集器
    type DeviceCommandLogCollector func(endTime string) []DeviceLogEntry
    

    函数需要返回endTime之前的所有日志,DeviceLogEntry包括日志记录时间、日志类型以及日志内容。当设备收到平台下发日志收集请求后,SDK会自动的上报日志直到平台关闭日志收集或endTime范围内没有任何日志内容。

    日志收集函数的设置如下:

    device := iot.CreateIotDevice("5fdb75cccbfe2f02ce81d4bf_go-mqtt", "xxx", "tls://iot-mqtts.cn-north-4.myhuaweicloud.com:8883")
    
    // 设置设备状态日志收集器
    device.SetDeviceStatusLogCollector(func(endTime string) []iot.DeviceLogEntry {
    	return []iot.DeviceLogEntry{}
    })
    device.Init()
    
  • 设备主动上报日志

    设备可以调用ReportLogs(logs []DeviceLogEntry) bool 函数主动上报日志。

HTTP协议上报消息和属性

华为云IoT物联网平台支持使用HTTP协议上报消息和属性(该功能目前处于α阶段,尚未对外开放,具体开放时间参考华为云IoT物联网平台公告)。使用HTTP协议上报消息和属性非常简单方便,SDK对接口进行了封装,接口使用的对象和MQTT协议一致。使用HTTP协议的设备接口定义如下:

type HttpDevice interface {
	SendMessage(message Message) bool
	ReportProperties(properties DeviceProperties) bool
}

使用样例参考:http_device_samples.go

使用设备发放服务

有两种方法可以使用设备发放服务动态获取设备连接平台的地址

方法1:通过设备发放服务获取设备连接平台的地址,然后创建设备

id := "device_id"
pwd := "your device password"

bootstrapClient, err := iot.NewBootstrapClient(id, pwd)
if err != nil {
	fmt.Printf("create bs client failed")
	return
}

server := bootstrapClient.Boot()
if len(server) == 0 {
	fmt.Println("get server address failed")
	return
}

device := iot.CreateIotDevice(id, pwd, server)
device.Init()

方法2:在创建设备时启动设备发放服务

id := "device_id"
pwd := "your device password"
config := iot.DeviceConfig{
	Id:           id,
	Password:     pwd,
	UseBootstrap: true,
}
device := iot.CreateIotDeviceWitConfig(config)
initRes := device.Init()
fmt.Println(initRes)

time.Sleep(1 * time.Minute)

报告bugs

如果你在使用过程中遇到任何问题或bugs,请通过issue的方式上报问题或bug,我们将会在第一时间内答复。上报问题或bugs时请尽量提供以下内容:

  • 使用的版本
  • 使用场景
  • 重现问题或bug的样例代码
  • 错误信息
  • ······

贡献

该项目欢迎来自所有人的pull request。

Documentation

Index

Constants

View Source
const (
	// MessageDownTopic 平台下发消息topic
	MessageDownTopic string = "$oc/devices/{device_id}/sys/messages/down"

	// MessageUpTopic 设备上报消息topic
	MessageUpTopic string = "$oc/devices/{device_id}/sys/messages/up"

	// CommandDownTopic 平台下发命令topic
	CommandDownTopic string = "$oc/devices/{device_id}/sys/commands/#"

	// CommandResponseTopic 设备响应平台命令
	CommandResponseTopic string = "$oc/devices/{device_id}/sys/commands/response/request_id="

	// PropertiesUpTopic 设备上报属性
	PropertiesUpTopic string = "$oc/devices/{device_id}/sys/properties/report"

	// PropertiesSetRequestTopic 平台设置属性topic
	PropertiesSetRequestTopic string = "$oc/devices/{device_id}/sys/properties/set/#"

	// PropertiesSetResponseTopic 设备响应平台属性设置topic
	PropertiesSetResponseTopic string = "$oc/devices/{device_id}/sys/properties/set/response/request_id="

	// PropertiesQueryRequestTopic 平台查询设备属性
	PropertiesQueryRequestTopic string = "$oc/devices/{device_id}/sys/properties/get/#"

	// PropertiesQueryResponseTopic 设备响应平台属性查询
	PropertiesQueryResponseTopic string = "$oc/devices/{device_id}/sys/properties/get/response/request_id="

	// DeviceShadowQueryRequestTopic 设备侧获取平台的设备影子数据
	DeviceShadowQueryRequestTopic string = "$oc/devices/{device_id}/sys/shadow/get/request_id="

	// DeviceShadowQueryResponseTopic 设备侧响应获取平台设备影子
	DeviceShadowQueryResponseTopic string = "$oc/devices/{device_id}/sys/shadow/get/response/#"

	// GatewayBatchReportSubDeviceTopic 网关批量上报子设备属性
	GatewayBatchReportSubDeviceTopic string = "$oc/devices/{device_id}/sys/gateway/sub_devices/properties/report"

	// FileActionUpload 平台下发文件上传和下载URL
	FileActionUpload   string = "upload"
	FileActionDownload string = "download"

	// DeviceToPlatformTopic 设备或网关向平台发送请求
	DeviceToPlatformTopic string = "$oc/devices/{device_id}/sys/events/up"

	// PlatformEventToDeviceTopic 平台向设备下发事件topic
	PlatformEventToDeviceTopic string = "$oc/devices/{device_id}/sys/events/down"
)
View Source
const (
	AuthTypePassword uint8 = 0
	AuthTypeX509     uint8 = 1
)

Variables

This section is empty.

Functions

func CreateAsyncIotDevice added in v1.0.0

func CreateAsyncIotDevice(id, password, servers string) *asyncDevice

func CreateAsyncIotDeviceWitConfig added in v1.0.0

func CreateAsyncIotDeviceWitConfig(config DeviceConfig) *asyncDevice

func CreateAsyncIotDeviceWithQos added in v1.0.0

func CreateAsyncIotDeviceWithQos(id, password, servers string, qos byte) *asyncDevice

func CreateMqttClientId added in v1.0.2

func CreateMqttClientId(deviceId string) string

func GetEventTimeStamp added in v0.0.2

func GetEventTimeStamp() string

设备采集数据UTC时间(格式:yyyyMMdd'T'HHmmss'Z'),如:20161219T114920Z。 设备上报数据不带该参数或参数格式错误时,则数据上报时间以平台时间为准。

func Interface2JsonString

func Interface2JsonString(v interface{}) string

func OsName added in v0.0.2

func OsName() string

func SdkInfo added in v0.0.2

func SdkInfo() map[string]string

Types

type AsyncDevice added in v1.0.0

type AsyncDevice interface {
	BaseDevice
	AsyncGateway
	SendMessage(message Message) AsyncResult
	ReportProperties(properties DeviceProperties) AsyncResult
	BatchReportSubDevicesProperties(service DevicesService) AsyncResult
	QueryDeviceShadow(query DevicePropertyQueryRequest, handler DevicePropertyQueryResponseHandler) AsyncResult
	UploadFile(filename string) AsyncResult
	DownloadFile(filename string) AsyncResult
	ReportDeviceInfo(swVersion, fwVersion string) AsyncResult
	ReportLogs(logs []DeviceLogEntry) AsyncResult
}

type AsyncGateway added in v1.0.0

type AsyncGateway interface {

	// 网关更新子设备状态
	UpdateSubDeviceState(subDevicesStatus SubDevicesStatus) AsyncResult

	// 网关删除子设备
	DeleteSubDevices(deviceIds []string) AsyncResult

	// 网关添加子设备
	AddSubDevices(deviceInfos []DeviceInfo) AsyncResult

	// 网关同步子设备列表,默认实现不指定版本
	SyncAllVersionSubDevices() AsyncResult

	// 网关同步特定版本子设备列表
	SyncSubDevices(version int) AsyncResult
	// contains filtered or unexported methods
}

type AsyncResult added in v1.0.0

type AsyncResult interface {
	Wait() bool

	WaitTimeout(time.Duration) bool

	Done() <-chan struct{}

	Error() error
}

type BaseDevice added in v1.0.0

type BaseDevice interface {
	Init() bool
	DisConnect()
	IsConnected() bool

	AddMessageHandler(handler MessageHandler)
	AddCommandHandler(handler CommandHandler)
	AddPropertiesSetHandler(handler DevicePropertiesSetHandler)
	SetPropertyQueryHandler(handler DevicePropertyQueryHandler)
	SetSwFwVersionReporter(handler SwFwVersionReporter)
	SetDeviceUpgradeHandler(handler DeviceUpgradeHandler)

	SetDeviceStatusLogCollector(collector DeviceStatusLogCollector)
	SetDevicePropertyLogCollector(collector DevicePropertyLogCollector)
	SetDeviceMessageLogCollector(collector DeviceMessageLogCollector)
	SetDeviceCommandLogCollector(collector DeviceCommandLogCollector)
}

type BaseServiceEvent added in v0.0.2

type BaseServiceEvent struct {
	ServiceId string `json:"service_id"`
	EventType string `json:"event_type"`
	EventTime string `json:"event_time,omitempty"`
}

type BooleanAsyncResult added in v1.0.0

type BooleanAsyncResult struct {
	// contains filtered or unexported fields
}

func NewBooleanAsyncResult added in v1.0.0

func NewBooleanAsyncResult() *BooleanAsyncResult

func (*BooleanAsyncResult) Done added in v1.0.0

func (b *BooleanAsyncResult) Done() <-chan struct{}

Done implements the Token Done method.

func (*BooleanAsyncResult) Error added in v1.0.0

func (b *BooleanAsyncResult) Error() error

func (*BooleanAsyncResult) Result added in v1.0.0

func (bar *BooleanAsyncResult) Result() bool

func (*BooleanAsyncResult) Wait added in v1.0.0

func (b *BooleanAsyncResult) Wait() bool

Wait implements the Token Wait method.

func (*BooleanAsyncResult) WaitTimeout added in v1.0.0

func (b *BooleanAsyncResult) WaitTimeout(d time.Duration) bool

WaitTimeout implements the Token WaitTimeout method.

type BootstrapClient added in v1.0.2

type BootstrapClient interface {
	Boot() string
	Close()
}

func NewBootstrapClient added in v1.0.2

func NewBootstrapClient(id, password string) (BootstrapClient, error)

type Command

type Command struct {
	ObjectDeviceId string      `json:"object_device_id"`
	ServiceId      string      `json:"service_id""`
	CommandName    string      `json:"command_name"`
	Paras          interface{} `json:"paras"`
}

设备命令

type CommandHandler

type CommandHandler func(Command) (bool, interface{})

处理平台下发的命令

type CommandResponse

type CommandResponse struct {
	ResultCode   byte        `json:"result_code"`
	ResponseName string      `json:"response_name"`
	Paras        interface{} `json:"paras"`
}

type Data added in v0.0.2

type Data struct {
	ObjectDeviceId string      `json:"object_device_id,omitempty"`
	Services       []DataEntry `json:"services"`
}

type DataEntry added in v0.0.2

type DataEntry struct {
	ServiceId string      `json:"service_id"`
	EventType string      `json:"event_type"`
	EventTime string      `json:"event_time"`
	Paras     interface{} `json:"paras"` // 不同类型的请求paras使用的结构体不同
}

type Device

type Device interface {
	BaseDevice
	Gateway
	SendMessage(message Message) bool
	ReportProperties(properties DeviceProperties) bool
	BatchReportSubDevicesProperties(service DevicesService) bool
	QueryDeviceShadow(query DevicePropertyQueryRequest, handler DevicePropertyQueryResponseHandler)
	UploadFile(filename string) bool
	DownloadFile(filename string) bool
	ReportDeviceInfo(swVersion, fwVersion string)
	ReportLogs(logs []DeviceLogEntry) bool
}

func CreateIotDevice

func CreateIotDevice(id, password, servers string) Device

func CreateIotDeviceWitConfig added in v0.0.4

func CreateIotDeviceWitConfig(config DeviceConfig) Device

func CreateIotDeviceWithQos added in v0.0.2

func CreateIotDeviceWithQos(id, password, servers string, qos byte) Device

type DeviceCommandLogCollector added in v1.0.0

type DeviceCommandLogCollector func(endTime string) []DeviceLogEntry

设备命令日志收集器

type DeviceConfig added in v0.0.4

type DeviceConfig struct {
	Id                 string
	Password           string
	VerifyTimestamp    bool
	Servers            string
	Qos                byte
	BatchSubDeviceSize int
	AuthType           uint8
	ServerCaPath       string
	CertFilePath       string
	CertKeyFilePath    string
	UseBootstrap       bool // 使用设备引导功能开关,true-使用,false-不使用
}

type DeviceError added in v1.0.0

type DeviceError struct {
	// contains filtered or unexported fields
}

func (*DeviceError) Error added in v1.0.0

func (err *DeviceError) Error() string

type DeviceInfo added in v0.0.2

type DeviceInfo struct {
	ParentDeviceId string      `json:"parent_device_id,omitempty"`
	NodeId         string      `json:"node_id,omitempty"`
	DeviceId       string      `json:"device_id,omitempty"`
	Name           string      `json:"name,omitempty"`
	Description    string      `json:"description,omitempty"`
	ManufacturerId string      `json:"manufacturer_id,omitempty"`
	Model          string      `json:"model,omitempty"`
	ProductId      string      `json:"product_id"`
	FwVersion      string      `json:"fw_version,omitempty"`
	SwVersion      string      `json:"sw_version,omitempty"`
	Status         string      `json:"status,omitempty"`
	ExtensionInfo  interface{} `json:"extension_info,omitempty"`
}

type DeviceLogEntry added in v1.0.0

type DeviceLogEntry struct {
	Timestamp string `json:"timestamp"` // 日志产生时间
	Type      string `json:"type"`      // 日志类型:DEVICE_STATUS,DEVICE_PROPERTY ,DEVICE_MESSAGE ,DEVICE_COMMAND
	Content   string `json:"content"`   // 日志内容
}

type DeviceMessageLogCollector added in v1.0.0

type DeviceMessageLogCollector func(endTime string) []DeviceLogEntry

设备消息日志收集器

type DeviceProperties added in v0.0.2

type DeviceProperties struct {
	Services []DevicePropertyEntry `json:"services"`
}

设备属性

type DevicePropertiesSetHandler

type DevicePropertiesSetHandler func(message DevicePropertyDownRequest) bool

平台设置设备属性

type DevicePropertyDownRequest

type DevicePropertyDownRequest struct {
	ObjectDeviceId string                           `json:"object_device_id"`
	Services       []DevicePropertyDownRequestEntry `json:"services"`
}

平台设置设备属性==================================================

type DevicePropertyDownRequestEntry

type DevicePropertyDownRequestEntry struct {
	ServiceId  string      `json:"service_id"`
	Properties interface{} `json:"properties"`
}

type DevicePropertyEntry added in v0.0.2

type DevicePropertyEntry struct {
	ServiceId  string      `json:"service_id"`
	Properties interface{} `json:"properties"`
	EventTime  string      `json:"event_time"`
}

设备的一个属性

type DevicePropertyLogCollector added in v1.0.0

type DevicePropertyLogCollector func(endTime string) []DeviceLogEntry

设备属性日志收集器

type DevicePropertyQueryHandler

type DevicePropertyQueryHandler func(query DevicePropertyQueryRequest) DevicePropertyEntry

平台查询设备属性

type DevicePropertyQueryRequest

type DevicePropertyQueryRequest struct {
	ObjectDeviceId string `json:"object_device_id"`
	ServiceId      string `json:"service_id"`
}

平台设置设备属性==================================================

type DevicePropertyQueryResponse

type DevicePropertyQueryResponse struct {
	ObjectDeviceId string             `json:"object_device_id"`
	Shadow         []DeviceShadowData `json:"shadow"`
}

type DevicePropertyQueryResponseHandler

type DevicePropertyQueryResponseHandler func(response DevicePropertyQueryResponse)

设备获取设备影子数据

type DeviceService

type DeviceService struct {
	DeviceId string                `json:"device_id"`
	Services []DevicePropertyEntry `json:"services"`
}

type DeviceShadowData

type DeviceShadowData struct {
	ServiceId string                     `json:"service_id"`
	Desired   DeviceShadowPropertiesData `json:"desired"`
	Reported  DeviceShadowPropertiesData `json:"reported"`
	Version   int                        `json:"version"`
}

type DeviceShadowPropertiesData

type DeviceShadowPropertiesData struct {
	Properties interface{} `json:"properties"`
	EventTime  string      `json:"event_time"`
}

type DeviceStatus added in v0.0.2

type DeviceStatus struct {
	DeviceId string `json:"device_id"`
	Status   string `json:"status"` // 子设备状态。 OFFLINE:设备离线 ONLINE:设备上线
}

type DeviceStatusLogCollector added in v1.0.0

type DeviceStatusLogCollector func(endTime string) []DeviceLogEntry

设备状态日志收集器

type DeviceUpgradeHandler added in v0.0.2

type DeviceUpgradeHandler func(upgradeType byte, info UpgradeInfo) UpgradeProgress

设备执行软件/固件升级.upgradeType = 0 软件升级,upgradeType = 1 固件升级

type DevicesService

type DevicesService struct {
	Devices []DeviceService `json:"devices"`
}

type FileRequest added in v0.0.2

type FileRequest struct {
	ObjectDeviceId string                    `json:"object_device_id"`
	Services       []FileRequestServiceEvent `json:"services"`
}

设备获取文件上传下载请求体

type FileRequestServiceEvent added in v0.0.2

type FileRequestServiceEvent struct {
	BaseServiceEvent
	Paras FileRequestServiceEventParas `json:"paras"`
}

type FileRequestServiceEventParas added in v0.0.2

type FileRequestServiceEventParas struct {
	FileName       string      `json:"file_name"`
	FileAttributes interface{} `json:"file_attributes"`
}

设备获取文件上传下载URL参数

type FileResponse added in v0.0.2

type FileResponse struct {
	ObjectDeviceId string                     `json:"object_device_id"`
	Services       []FileResponseServiceEvent `json:"services"`
}

平台下发文件上传和下载URL响应

type FileResponseServiceEvent added in v0.0.2

type FileResponseServiceEvent struct {
	BaseServiceEvent
	Paras FileResponseServiceEventParas `json:"paras"`
}

type FileResponseServiceEventParas added in v0.0.2

type FileResponseServiceEventParas struct {
	Url            string      `json:"url"`
	BucketName     string      `json:"bucket_name"`
	ObjectName     string      `json:"object_name"`
	Expire         int         `json:"expire"`
	FileAttributes interface{} `json:"file_attributes"`
}

平台下发响应参数

type FileResultResponse added in v0.0.2

type FileResultResponse struct {
	ObjectDeviceId string                           `json:"object_device_id"`
	Services       []FileResultResponseServiceEvent `json:"services"`
}

func CreateFileUploadDownLoadResultResponse added in v0.0.2

func CreateFileUploadDownLoadResultResponse(filename, action string, result bool) FileResultResponse

文件上传下载管理

type FileResultResponseServiceEvent added in v0.0.2

type FileResultResponseServiceEvent struct {
	BaseServiceEvent
	Paras FileResultServiceEventParas `json:"paras"`
}

type FileResultServiceEventParas added in v0.0.2

type FileResultServiceEventParas struct {
	ObjectName        string `json:"object_name"`
	ResultCode        int    `json:"result_code"`
	StatusCode        int    `json:"status_code"`
	StatusDescription string `json:"status_description"`
}

上报文件上传下载结果参数

type Gateway added in v0.0.2

type Gateway interface {

	// 网关更新子设备状态
	UpdateSubDeviceState(subDevicesStatus SubDevicesStatus) bool

	// 网关删除子设备
	DeleteSubDevices(deviceIds []string) bool

	// 网关添加子设备
	AddSubDevices(deviceInfos []DeviceInfo) bool

	// 网关同步子设备列表,默认实现不指定版本
	SyncAllVersionSubDevices()

	// 网关同步特定版本子设备列表
	SyncSubDevices(version int)
	// contains filtered or unexported methods
}

type HttpClient added in v0.0.2

type HttpClient interface {
	UploadFile(filename, uri string) bool
	DownloadFile(filename, uri string) bool
}

仅用于设备上传文件

func CreateHttpClient added in v0.0.2

func CreateHttpClient() HttpClient

type HttpDevice added in v1.0.1

type HttpDevice interface {

	// 上报消息
	SendMessage(message Message) bool

	// 上报属性
	ReportProperties(properties DeviceProperties) bool
}

使用HTTP协议的设备,当前使用HTTP协议的设备只支持上报消息和上报属性

func CreateHttpDevice added in v1.0.1

func CreateHttpDevice(config HttpDeviceConfig) HttpDevice

type HttpDeviceConfig added in v1.0.1

type HttpDeviceConfig struct {
	Id              string
	Password        string
	Server          string // https://iot-mqtts.cn-north-4.myhuaweicloud.com:443
	MaxConnsPerHost int
	MaxIdleConns    int
}

type LogCollectionConfig added in v1.0.0

type LogCollectionConfig struct {
	// contains filtered or unexported fields
}

type Message

type Message struct {
	ObjectDeviceId string `json:"object_device_id"`
	Name           string `json:"name"`
	Id             string `json:"id"`
	Content        string `json:"content"`
}

消息

type MessageHandler

type MessageHandler func(message Message) bool

设备消息

type ReportDeviceInfoEventParas added in v0.0.4

type ReportDeviceInfoEventParas struct {
	DeviceSdkVersion string `json:"device_sdk_version,omitempty"`
	SwVersion        string `json:"sw_version,omitempty"`
	FwVersion        string `json:"fw_version,omitempty"`
}

设备信息上报请求参数

type ReportDeviceInfoRequest added in v0.0.4

type ReportDeviceInfoRequest struct {
	ObjectDeviceId string                         `json:"object_device_id,omitempty"`
	Services       []ReportDeviceInfoServiceEvent `json:"services,omitempty"`
}

上报设备信息请求

type ReportDeviceInfoServiceEvent added in v0.0.4

type ReportDeviceInfoServiceEvent struct {
	BaseServiceEvent
	Paras ReportDeviceInfoEventParas `json:"paras,omitempty"`
}

type ReportDeviceLogRequest added in v1.0.0

type ReportDeviceLogRequest struct {
	Services []ReportDeviceLogServiceEvent `json:"services,omitempty"`
}

上报设备日志请求

type ReportDeviceLogServiceEvent added in v1.0.0

type ReportDeviceLogServiceEvent struct {
	BaseServiceEvent
	Paras DeviceLogEntry `json:"paras,omitempty"`
}

type Result added in v1.0.2

type Result struct {
	Flag chan int
	// contains filtered or unexported fields
}

func (*Result) Complete added in v1.0.2

func (b *Result) Complete(res string)

func (*Result) CompleteError added in v1.0.2

func (b *Result) CompleteError(err error)

func (*Result) Error added in v1.0.2

func (b *Result) Error() error

func (*Result) Value added in v1.0.2

func (b *Result) Value() string

func (*Result) Wait added in v1.0.2

func (b *Result) Wait() bool

func (*Result) WaitTimeout added in v1.0.2

func (b *Result) WaitTimeout(d time.Duration) bool

type SubDeviceInfo added in v0.0.2

type SubDeviceInfo struct {
	Devices []DeviceInfo `json:"devices"`
	Version int          `json:"version"`
}

添加子设备

type SubDevicesAddHandler added in v0.0.2

type SubDevicesAddHandler func(devices SubDeviceInfo)

子设备添加回调函数

type SubDevicesDeleteHandler added in v0.0.2

type SubDevicesDeleteHandler func(devices SubDeviceInfo)

子设备删除糊掉函数

type SubDevicesStatus added in v0.0.2

type SubDevicesStatus struct {
	DeviceStatuses []DeviceStatus `json:"device_statuses"`
}

网关更新子设备状态

type SwFwVersionReporter added in v0.0.2

type SwFwVersionReporter func() (string, string)

设备上报软固件版本,第一个返回值为软件版本,第二个返回值为固件版本

type UpgradeInfo added in v0.0.2

type UpgradeInfo struct {
	Version     string `json:"version"`      //软固件包版本号
	Url         string `json:"url"`          //软固件包下载地址
	FileSize    int    `json:"file_size"`    //软固件包文件大小
	AccessToken string `json:"access_token"` //软固件包url下载地址的临时token
	Expires     string `json:"expires"`      //access_token的超期时间
	Sign        string `json:"sign"`         //软固件包MD5值
}

平台下发的升级信息

type UpgradeProgress added in v0.0.2

type UpgradeProgress struct {
	ResultCode  int    `json:"result_code"`
	Progress    int    `json:"progress"`    // 设备的升级进度,范围:0到100
	Version     string `json:"version"`     // 设备当前版本号
	Description string `json:"description"` // 升级状态描述信息,可以返回具体升级失败原因。
}

设备升级状态响应,用于设备向平台反馈进度,错误信息等 ResultCode: 设备的升级状态,结果码定义如下: 0:处理成功 1:设备使用中 2:信号质量差 3:已经是最新版本 4:电量不足 5:剩余空间不足 6:下载超时 7:升级包校验失败 8:升级包类型不支持 9:内存不足 10:安装升级包失败 255: 内部异常

Directories

Path Synopsis
bs
log

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL