package mappers
import (
"fmt"
"reflect"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/klog/v2"
"github.com/kubeedge/kubeedge/cloud/pkg/apis/devices/v1alpha1"
"github.com/kubeedge/kubeedge/cloud/pkg/common/informers"
"github.com/kubeedge/kubeedge/cloud/pkg/common/modules"
"github.com/kubeedge/kubeedge/cloud/pkg/devicetwin/dtclient"
"github.com/kubeedge/kubeedge/cloud/pkg/devicetwin/mappers"
)
const (
groupName = "devices.kubeedge.io"
)
// DeviceTwinMapper defines the mapper for devices to twin
type DeviceTwinMapper struct {
dtClient dtclient.DeviceTwinClient
}
// NewDeviceTwinMapper creates a new DeviceTwinMapper
func NewDeviceTwinMapper(dtClient dtclient.DeviceTwinClient) mappers.Mapper {
return &DeviceTwinMapper{
dtClient: dtClient,
}
}
// Start starts the mapper
func (d *DeviceTwinMapper) Start() {
informers.NewSharedInformerFactory(d.dtClient, 0).Devices().V1alpha1().Devices().Informer().AddEventHandler(d)
}
// OnAdd handles addition of a device
func (d *DeviceTwinMapper) OnAdd(obj interface{}) {
device := obj.(*v1alpha1.Device)
if err := d.dtClient.CreateOrUpdateDeviceTwin(device); err != nil {
klog.Errorf("failed to create or update device twin for device %v: %v", device.Name, err)
}
}
// OnUpdate handles update of a device
func (d *DeviceTwinMapper) OnUpdate(oldObj, newObj interface{}) {
device := newObj.(*v1alpha1.Device)
if err := d.dtClient.CreateOrUpdateDeviceTwin(device); err != nil {
klog.Errorf("failed to create or update device twin for device %v: %v", device.Name, err)
}
}
// OnDelete handles deletion of a device
func (d *DeviceTwinMapper) OnDelete(obj interface{}) {
var device *v1alpha1.Device
switch t := obj.(type) {
case *v1alpha1.Device:
device = t
case runtime.Object:
device = obj.(*v1alpha1.Device)
default:
klog.Errorf("unknown type: %v", reflect.TypeOf(obj))
return
}
if err := d.dtClient.DeleteDeviceTwin(device.Name); err != nil {
klog.Errorf("failed to delete device twin for
评论已关闭