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

设备插件模块

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

使用 plugin-sdk 可以忽略不重要的逻辑,快速实现插件

插件实现

  1. 获取sdk
    go get github.com/zhiting-tech/smartassistant
  1. 定义设备

sdk中提供了预定义的设备模型,使用模型可以方便SA有效进行管理和控制

请参考智汀家庭云-开发指南Golang: 插件模块:4.1.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 main

import (
  "github.com/zhiting-tech/smartassistant/pkg/plugin/sdk/server"
)

type Device interface {
  Identity() string             // 获取设备唯一值
  Info() server.DeviceInfo      // 设备详情
  Setup() error                 // 初始化设备属性
  Update() error                // 更新设备所有属性值
  Close() error                 // 回收所有资源
  GetChannel() server.WatchChan // 返回通知channel
}

实现如下:

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
  // 根据实际设备功能组合定义
}

func NewDevice() *Device {
  return &Device{
    Light: instance.NewLightBulb(),
    Info0: instance.NewInfo(),
  }
}

func (d *Device) Info() plugin.DeviceInfo {
  // 该方法返回设备的主要信息
  panic("implement me")
}

func (d *Device) Setup() error {
  // 设置设备的属性和相关配置(比如设备id、型号、厂商等,以及设备的属性更新触发函数)
  panic("implement me")
}

func (d *Device) Update() error {
  // 该方法在获取设备所有属性值时调用,通过调用attribute.SetBool()等方法更新
  panic("implement me")
}

func (d *Device) Close() error {
  // 自定义退出相关资源的回收
  panic("implement me")
}

func (d *Device) GetChannel() plugin.WatchChan {
  // 返回WatchChan频道,用于状态变更推送
  panic("implement me")
}

  1. 初始化和运行

定义好设备和实现方法后,运行插件服务(包括grpc和http服务)

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() {
    // 发现设备,并将设备添加到manager中
    d := NewDevice()
    p.Manager.AddDevice(d)
  }()
  err := sdk.Run(p)
  if err != nil {
    log.Panicln(err)
  }
}

这样服务就会运行起来,并通过SA的etcd地址0.0.0.0:2379注册插件服务, SA会通过etcd发现插件服务并且建立通道开始通信并且转发请求和命令

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值