智汀家庭云-快速入门:开发第一个插件(智汀家庭云功能介绍品牌插件篇)

开发您的第一个插件

此文档描述如何开发一个简单插件,面向插件开发者。

开发前先阅读插件设计概要:智汀家庭云-开发指南Golang: 插件模块

1. 插件实现

  1. 获取sdk
 go get github.com/zhiting-tech/smartassistant 
  1. 定义设备
package plugin import "github.com/zhiting-tech/smartassistant/pkg/plugin/sdk/instance" type Device struct { Light instance.LightBulb Info0 instance.Info // 根据实际设备功能组合定义 } func NewDevice() *Device { return &Device{ Light: instance.NewLightBulb(), Info0: instance.NewInfo(), } } 
  1. 实现设备接口
package plugin import ( "github.com/zhiting-tech/smartassistant/pkg/plugin/sdk/instance" "github.com/zhiting-tech/smartassistant/pkg/plugin/sdk/server" ) type Device struct { Light instance.LightBulb Info0 instance.Info // 根据实际设备功能组合定义 identity string ch 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 file COPY ./html ./html ENTRYPOINT ["/app/demo-plugin"] 
  • 编译镜像
docker build -f your_plugin_Dockerfile -t your_plugin_name 
  • 更多

智汀家庭云-开发指南Golang:设备插件开发

3. Demo

demo-plugin : 通过上文的插件实现教程实现的示例插件;这是一个模拟设备写的一个简单插件服务,不依赖硬件,实现了核心插件的功能

发表回复

您的邮箱地址不会被公开。必填项已用 * 标注