开发您的第一个插件
此文档形容如何开发一个简略插件,面向插件开发者。
开发前先浏览插件设计概要:智汀家庭云-开发指南Golang: 插件模块
插件实现
获取sdkgo get github.com/zhiting-tech/smartassistant
定义设施
package pluginimport "github.com/zhiting-tech/smartassistant/pkg/plugin/sdk/instance"type Device struct {Light instance.LightBulbInfo0 instance.Info// 依据理论设施性能组合定义 }func NewDevice() *Device {return &Device{ Light: instance.NewLightBulb(), Info0: instance.NewInfo(),} }
实现设施接口
package pluginimport ("github.com/zhiting-tech/smartassistant/pkg/plugin/sdk/instance""github.com/zhiting-tech/smartassistant/pkg/plugin/sdk/server" )type Device struct {Light instance.LightBulbInfo0 instance.Info// 依据理论设施性能组合定义identity stringch server.WatchChan } func NewDevice() *Device {return &Device{Light: instance.NewLightBulb(),Info0: instance.NewInfo(),ch: make(server.WatchChan, 10),}} func (d *Device) Info() plugin.DeviceInfo { // 该办法返回设施的次要信息return d.identity }func (d *Device) Setup() error {// 设置设施的属性和相干配置(比方设施id、型号、厂商等,以及设施的属性更新触发函数)d.Info0.Identity.SetString("123456")d.Info0.Model.SetString("model")d.Info0.Manufacturer.SetString("manufacturer")d.LightBulb.Brightness.SetRange(1, 100)d.LightBulb.ColorTemp.SetRange(1000, 5000)d.LightBulb.Power.SetUpdateFunc(d.update("power"))d.LightBulb.Brightness.SetUpdateFunc(d.update("brightness"))d.LightBulb.ColorTemp.SetUpdateFunc(d.update("color_temp"))return nil
}
func (d *Device) Update() error {// 该办法在获取设施所有属性值时调用,通过调用attribute.SetBool()等办法更新d.LightBulb.Power.SetString("on")d.LightBulb.Brightness.SetInt(100)d.LightBulb.ColorTemp.SetInt(2000)return nil}func (d *Device) Close() error {
// 自定义退出相干资源的回收
close(d.ch)return nil}func (d *Device) GetChannel() plugin.WatchChan {// 返回WatchChan频道,用于状态变更推送return d.ch}
1.初始化和运行
package main import ("log""github.com/zhiting-tech/smartassistant/pkg/plugin/sdk/server"sdk "github.com/zhiting-tech/smartassistant/pkg/server/sdk" ) func main() {p := plugin.NewPluginServer("demo")go func() { // 发现设施 d := NewDevice() p.Manager.AddDevice(d)}()err := sdk.Run(p)if err != nil { log.Panicln(err)}}
2. 镜像编译和部署
临时仅反对以镜像形式装置插件,调试失常后,编译成镜像提供给SA
Dockerfile示例参考
FROM golang:1.16-alpine as builder RUN apk add build-base COPY . /app WORKDIR /app RUN go env -w GOPROXY="goproxy.cn,direct" RUN go build -ldflags="-w -s" -o demo-plugin FROM alpine WORKDIR /app COPY --from=builder /app/demo-plugin /app/demo-plugin# static fileCOPY ./html ./htmlENTRYPOINT ["/app/demo-plugin"]
- 编译镜像
docker build -f your_plugin_Dockerfile -t your_plugin_name - 更多
智汀家庭云-开发指南Golang:设施插件开发
3. Demo
demo-plugin : 通过上文的插件实现教程实现的示例插件;这是一个模仿设施写的一个简略插件服务,不依赖硬件,实现了外围插件的性能