iot

package module
v1.0.1-alpha.0...-8451ba6 Latest Latest
Warning

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

Go to latest
Published: Jul 1, 2021 License: Apache-2.0 Imports: 20 Imported by: 0

README

huaweicloud-iot-device-sdk-go

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

支持如下功能:

版本说明

当前稳定版本:v1.0.0

安装和构建

安装和构建的过程取决于你是使用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协议接入端点。

设备命令

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 函数主动上报日志。

报告bugs

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

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

贡献

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

Documentation

Index

Constants

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	// 平台向设备下发事件topic
	PlatformEventToDeviceTopic string = "$oc/devices/{device_id}/sys/events/down"
)

Variables

This section is empty.

Functions

func CreateAsyncIotDevice

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

func CreateAsyncIotDeviceWitConfig

func CreateAsyncIotDeviceWitConfig(config DeviceConfig) *asyncDevice

func CreateAsyncIotDeviceWithQos

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

func GetEventTimeStamp

func GetEventTimeStamp() string

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

func Interface2JsonString

func Interface2JsonString(v interface{}) string

func OsName

func OsName() string

func SdkInfo

func SdkInfo() map[string]string

Types

type AsyncDevice

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

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

type AsyncResult interface {
	Wait() bool

	WaitTimeout(time.Duration) bool

	Done() <-chan struct{}

	Error() error
}

type BaseDevice

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

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

type BooleanAsyncResult

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

func NewBooleanAsyncResult

func NewBooleanAsyncResult() *BooleanAsyncResult

func (*BooleanAsyncResult) Done

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

Done implements the Token Done method.

func (*BooleanAsyncResult) Error

func (b *BooleanAsyncResult) Error() error

func (*BooleanAsyncResult) Result

func (bar *BooleanAsyncResult) Result() bool

func (*BooleanAsyncResult) Wait

func (b *BooleanAsyncResult) Wait() bool

Wait implements the Token Wait method.

func (*BooleanAsyncResult) WaitTimeout

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

WaitTimeout implements the Token WaitTimeout method.

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

处理平台下发的命令

type CommandResponse

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

type Data

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

type DataEntry

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

func CreateIotDeviceWitConfig(config DeviceConfig) Device

func CreateIotDeviceWithQos

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

type DeviceCommandLogCollector

type DeviceCommandLogCollector func(endTime string) []DeviceLogEntry

设备命令日志收集器

type DeviceConfig

type DeviceConfig struct {
	Id                 string
	Password           string
	Servers            string
	Qos                byte
	BatchSubDeviceSize int
}

type DeviceError

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

func (*DeviceError) Error

func (err *DeviceError) Error() string

type DeviceInfo

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

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

type DeviceMessageLogCollector func(endTime string) []DeviceLogEntry

设备消息日志收集器

type DeviceProperties

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

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

设备的一个属性

type DevicePropertyLogCollector

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

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

type DeviceStatusLogCollector

type DeviceStatusLogCollector func(endTime string) []DeviceLogEntry

设备状态日志收集器

type DeviceUpgradeHandler

type DeviceUpgradeHandler func(upgradeType byte, info UpgradeInfo) UpgradeProgress

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

type DevicesService

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

type FileRequest

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

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

type FileRequestServiceEvent

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

type FileRequestServiceEventParas

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

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

type FileResponse

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

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

type FileResponseServiceEvent

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

type FileResponseServiceEventParas

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

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

func CreateFileUploadDownLoadResultResponse

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

文件上传下载管理

type FileResultResponseServiceEvent

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

type FileResultServiceEventParas

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

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

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

仅用于设备上传文件

func CreateHttpClient

func CreateHttpClient() HttpClient

type LogCollectionConfig

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

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

设备信息上报请求参数

type ReportDeviceInfoRequest

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

上报设备信息请求

type ReportDeviceInfoServiceEvent

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

type ReportDeviceLogRequest

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

上报设备日志请求

type ReportDeviceLogServiceEvent

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

type SubDeviceInfo

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

添加子设备

type SubDevicesAddHandler

type SubDevicesAddHandler func(devices SubDeviceInfo)

子设备添加回调函数

type SubDevicesDeleteHandler

type SubDevicesDeleteHandler func(devices SubDeviceInfo)

子设备删除糊掉函数

type SubDevicesStatus

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

网关更新子设备状态

type SwFwVersionReporter

type SwFwVersionReporter func() (string, string)

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

type UpgradeInfo

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

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
log

Jump to

Keyboard shortcuts

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