From 8d2c87a67c760fbafcc7fa1067a4289a4d32e4cc Mon Sep 17 00:00:00 2001 From: Michael Santos Date: Sun, 15 Nov 2026 16:42:31 -0500 Subject: [PATCH] feat: support Kasa smart bulbs --- internal/controller/controller.go | 93 ++++++++++++++++++--- internal/controller/controller_test.go | 78 +++++++++++++++++- internal/kasa/client.go | 107 ++++++++++++++++++++++++- internal/kasa/discover.go | 9 ++- internal/kasa/model.go | 39 +++++++-- 5 files changed, 300 insertions(+), 26 deletions(-) diff --git a/internal/controller/controller.go b/internal/controller/controller.go index a0132c1..e00a873 100644 --- a/internal/controller/controller.go +++ b/internal/controller/controller.go @@ -214,6 +214,27 @@ func (c *Controller) pollPlug(ctx context.Context, client kasa.Client) { serviceName := fmt.Sprintf("%s%s/%d/state", prefix, hostIdent, outlet.Index) tags := []string{"kasa", "plug", "power"} + desc := fmt.Sprintf("%s outlet %d state", outlet.Alias, outlet.Index) + attrs := map[string]string{ + "outlet": strconv.Itoa(outlet.Index), + "alias": outlet.Alias, + "ip": client.DeviceHost(), + "outlet_id": outlet.OutletID, + } + if outlet.IsBulb { + tags = []string{"kasa", "bulb", "light"} + desc = fmt.Sprintf("%s light state", outlet.Alias) + attrs["brightness"] = strconv.Itoa(outlet.Brightness) + if outlet.ColorTemp > 0 { + attrs["color_temp"] = strconv.Itoa(outlet.ColorTemp) + } + if outlet.Hue > 0 { + attrs["hue"] = strconv.Itoa(outlet.Hue) + } + if outlet.Saturation > 0 { + attrs["saturation"] = strconv.Itoa(outlet.Saturation) + } + } if c.cfg.Tag != "" { tags = append(tags, c.cfg.Tag) } @@ -226,13 +247,8 @@ func (c *Controller) pollPlug(ctx context.Context, client kasa.Client) { TTL: c.cfg.RiemannTTL, Time: now, Tags: tags, - Description: fmt.Sprintf("%s outlet %d state", outlet.Alias, outlet.Index), - Attributes: map[string]string{ - "outlet": strconv.Itoa(outlet.Index), - "alias": outlet.Alias, - "ip": client.DeviceHost(), - "outlet_id": outlet.OutletID, - }, + Description: desc, + Attributes: attrs, }) } @@ -324,24 +340,42 @@ func (c *Controller) handleCommandEvent(ctx context.Context, ev *riemann.Event) return } + lightOpts, hasLightOpts := parseLightOptions(ev.Attributes) + // 4. Check if state change is actually needed cacheKey := fmt.Sprintf("%s/%d", client.DeviceHost(), outletIndex) c.mu.RLock() currentState, cached := c.stateCache[cacheKey] c.mu.RUnlock() - if cached && currentState == desiredState { + if cached && currentState == desiredState && !hasLightOpts { if c.cfg.Verbose { log.Printf("plug %s outlet %d already in desired state (%v), no-op", client.DeviceHost(), outletIndex, desiredState) } return } - // 5. Execute hardware command on plug - log.Printf("executing command: setting plug %s outlet %d -> %v", client.DeviceHost(), outletIndex, desiredState) - if err := client.SetOutlet(ctx, outletIndex, desiredState); err != nil { - log.Printf("failed to set outlet state: %v", err) - return + // 5. Execute hardware command on plug or bulb + if hasLightOpts { + if lc, ok := client.(kasa.LightController); ok { + log.Printf("executing command: setting bulb %s -> %v", client.DeviceHost(), desiredState) + if err := lc.SetLight(ctx, desiredState, lightOpts); err != nil { + log.Printf("failed to set light state: %v", err) + return + } + } else { + log.Printf("executing command: setting plug %s outlet %d -> %v", client.DeviceHost(), outletIndex, desiredState) + if err := client.SetOutlet(ctx, outletIndex, desiredState); err != nil { + log.Printf("failed to set outlet state: %v", err) + return + } + } + } else { + log.Printf("executing command: setting plug %s outlet %d -> %v", client.DeviceHost(), outletIndex, desiredState) + if err := client.SetOutlet(ctx, outletIndex, desiredState); err != nil { + log.Printf("failed to set outlet state: %v", err) + return + } } // 6. Update local cache @@ -396,3 +430,36 @@ func (c *Controller) publishSingleState(client kasa.Client, outletIndex int, sta log.Printf("confirmed state published: %s = %v", serviceName, metricVal) } } + +func parseLightOptions(attrs map[string]string) (kasa.LightOptions, bool) { + var opts kasa.LightOptions + var hasOpts bool + if len(attrs) == 0 { + return opts, false + } + if v, ok := attrs["brightness"]; ok { + if n, err := strconv.Atoi(v); err == nil { + opts.Brightness = &n + hasOpts = true + } + } + if v, ok := attrs["color_temp"]; ok { + if n, err := strconv.Atoi(v); err == nil { + opts.ColorTemp = &n + hasOpts = true + } + } + if v, ok := attrs["hue"]; ok { + if n, err := strconv.Atoi(v); err == nil { + opts.Hue = &n + hasOpts = true + } + } + if v, ok := attrs["saturation"]; ok { + if n, err := strconv.Atoi(v); err == nil { + opts.Saturation = &n + hasOpts = true + } + } + return opts, hasOpts +} diff --git a/internal/controller/controller_test.go b/internal/controller/controller_test.go index 2fff0c8..5896ad8 100644 --- a/internal/controller/controller_test.go +++ b/internal/controller/controller_test.go @@ -12,10 +12,12 @@ import ( ) type mockKasaClient struct { - host string - alias string - outlets []kasa.OutletState - mu sync.Mutex + host string + alias string + outlets []kasa.OutletState + lastOpts kasa.LightOptions + lightCalls int + mu sync.Mutex } func (m *mockKasaClient) GetOutlets(ctx context.Context) ([]kasa.OutletState, error) { @@ -35,6 +37,23 @@ func (m *mockKasaClient) SetOutlet(ctx context.Context, outletIndex int, state b return nil } +func (m *mockKasaClient) SetLight(ctx context.Context, state bool, opts kasa.LightOptions) error { + m.mu.Lock() + defer m.mu.Unlock() + m.lightCalls++ + m.lastOpts = opts + if len(m.outlets) > 0 { + m.outlets[0].State = state + if opts.Brightness != nil { + m.outlets[0].Brightness = *opts.Brightness + } + if opts.ColorTemp != nil { + m.outlets[0].ColorTemp = *opts.ColorTemp + } + } + return nil +} + func (m *mockKasaClient) DeviceHost() string { return m.host } @@ -111,3 +130,54 @@ func TestControllerHandleCommand(t *testing.T) { t.Fatalf("expected outlet 0 to be false after off command") } } + +func TestControllerHandleBulbCommand(t *testing.T) { + mockBulb := &mockKasaClient{ + host: "192.0.2.2", + alias: "kl125", + outlets: []kasa.OutletState{ + {Index: 0, Alias: "Desk Lamp", State: false, IsBulb: true, Brightness: 100, ColorTemp: 2700}, + }, + } + + cfg := &config.Config{ + RiemannTTL: 60 * time.Second, + ServicePrefix: "kasa/", + Tag: "kl125", + Verbose: true, + } + + pub := riemann.NewPublisher(cfg) + sub := riemann.NewSubscriber(cfg) + + ctrl := New(cfg, []kasa.Client{mockBulb}, pub, sub) + ctrl.clientMap["kl125"] = mockBulb + ctrl.clientMap["192.0.2.2"] = mockBulb + + // Turn bulb ON with brightness and color_temp attributes + cmdEvent := &riemann.Event{ + Host: "kl125", + Service: "kasa/kl125/0/set", + State: "on", + Metric: 1.0, + TimeMicros: time.Now().UnixMicro(), + Tags: []string{"plug-command"}, + Attributes: map[string]string{ + "brightness": "40", + "color_temp": "3000", + }, + } + + ctrl.handleCommandEvent(context.Background(), cmdEvent) + + if !mockBulb.outlets[0].State { + t.Fatalf("expected bulb to be on") + } + if mockBulb.outlets[0].Brightness != 40 || mockBulb.outlets[0].ColorTemp != 3000 { + t.Fatalf("expected brightness=40 color_temp=3000, got brightness=%d color_temp=%d", + mockBulb.outlets[0].Brightness, mockBulb.outlets[0].ColorTemp) + } + if mockBulb.lightCalls != 1 { + t.Fatalf("expected 1 SetLight call, got %d", mockBulb.lightCalls) + } +} diff --git a/internal/kasa/client.go b/internal/kasa/client.go index ec7c0cd..4f896d5 100644 --- a/internal/kasa/client.go +++ b/internal/kasa/client.go @@ -4,10 +4,24 @@ import ( "context" "encoding/json" "fmt" + "strings" "sync" ) -// Client defines the interface for communicating with a smart plug device. +// LightOptions specifies optional lighting parameters when controlling a smart bulb. +type LightOptions struct { + Brightness *int + ColorTemp *int + Hue *int + Saturation *int +} + +// LightController is an optional interface implemented by clients that support smart bulb parameters. +type LightController interface { + SetLight(ctx context.Context, state bool, opts LightOptions) error +} + +// Client defines the interface for communicating with a smart plug or bulb device. type Client interface { GetOutlets(ctx context.Context) ([]OutletState, error) SetOutlet(ctx context.Context, outletIndex int, state bool) error @@ -24,6 +38,7 @@ type DeviceClient struct { legacyMode bool alias string + isBulb bool children []ChildOutlet mu sync.RWMutex } @@ -96,8 +111,11 @@ func (c *DeviceClient) GetOutlets(ctx context.Context) ([]OutletState, error) { return nil, fmt.Errorf("device %s returned error code %d", c.host, info.ErrCode) } + bulb := isSmartBulb(info) + c.mu.Lock() c.alias = info.Alias + c.isBulb = bulb c.children = info.Children c.mu.Unlock() @@ -117,6 +135,25 @@ func (c *DeviceClient) GetOutlets(ctx context.Context) ([]OutletState, error) { OnTime: ch.OnTime, }) } + } else if bulb { + // Smart bulb (e.g. KL125) + alias := info.Alias + if alias == "" { + alias = c.host + } + var st OutletState + st.Index = 0 + st.Alias = alias + st.OnTime = info.OnTime + st.IsBulb = true + if info.LightState != nil { + st.State = info.LightState.OnOff == 1 + st.Brightness = info.LightState.Brightness + st.ColorTemp = info.LightState.ColorTemp + st.Hue = info.LightState.Hue + st.Saturation = info.LightState.Saturation + } + outlets = append(outlets, st) } else { // Single plug (e.g. KP115, HS100) alias := info.Alias @@ -135,12 +172,26 @@ func (c *DeviceClient) GetOutlets(ctx context.Context) ([]OutletState, error) { return outlets, nil } -// SetOutlet turns an outlet on or off. +func isSmartBulb(info GetSysInfoResult) bool { + return strings.Contains(strings.ToUpper(info.MicType), "SMARTBULB") || + strings.Contains(strings.ToUpper(info.Type), "SMARTBULB") || + info.LightState != nil +} + +// SetOutlet turns an outlet or smart bulb on or off. func (c *DeviceClient) SetOutlet(ctx context.Context, outletIndex int, state bool) error { c.mu.RLock() + isBulb := c.isBulb children := c.children c.mu.RUnlock() + if isBulb { + if outletIndex != 0 { + return fmt.Errorf("outlet index %d out of bounds (smart bulb has 1 light)", outletIndex) + } + return c.SetLight(ctx, state, LightOptions{}) + } + stateInt := 0 if state { stateInt = 1 @@ -175,3 +226,55 @@ func (c *DeviceClient) SetOutlet(ctx context.Context, outletIndex int, state boo return nil } + +// SetLight sets the power state and optional lighting parameters on a Kasa smart bulb. +func (c *DeviceClient) SetLight(ctx context.Context, state bool, opts LightOptions) error { + onOff := 0 + if state { + onOff = 1 + } + + params := map[string]any{ + "on_off": onOff, + "transition_period": 0, + } + if opts.Brightness != nil { + params["brightness"] = *opts.Brightness + } + if opts.ColorTemp != nil { + params["color_temp"] = *opts.ColorTemp + } + if opts.Hue != nil { + params["hue"] = *opts.Hue + } + if opts.Saturation != nil { + params["saturation"] = *opts.Saturation + } + + payload := map[string]any{ + "smartlife.iot.smartbulb.lightingservice": map[string]any{ + "transition_light_state": params, + }, + } + + reqBytes, err := json.Marshal(payload) + if err != nil { + return fmt.Errorf("failed to marshal transition_light_state request: %w", err) + } + + respJSON, err := c.send(ctx, string(reqBytes)) + if err != nil { + return fmt.Errorf("failed to set light state on %s: %w", c.host, err) + } + + var resp TransitionLightStateResponse + if err := json.Unmarshal([]byte(respJSON), &resp); err != nil { + return fmt.Errorf("failed to unmarshal transition_light_state response from %s: %w", c.host, err) + } + + if resp.LightingService.TransitionLightState.ErrCode != 0 { + return fmt.Errorf("transition_light_state error code %d from %s", resp.LightingService.TransitionLightState.ErrCode, c.host) + } + + return nil +} diff --git a/internal/kasa/discover.go b/internal/kasa/discover.go index 75164e0..7c77391 100644 --- a/internal/kasa/discover.go +++ b/internal/kasa/discover.go @@ -296,13 +296,20 @@ func parseDiscoveryPacket(data []byte, remoteAddr *net.UDPAddr) (DiscoveredDevic var sysResp SysInfoResponse if err := json.Unmarshal(decrypted, &sysResp); err == nil && sysResp.System.GetSysInfo.DeviceId != "" { info := sysResp.System.GetSysInfo + devType := info.MicType + if devType == "" { + devType = info.Type + } + if devType == "" { + devType = "IOT.SMARTPLUGSWITCH" + } return DiscoveredDevice{ IP: ip, Port: 9999, DeviceModel: info.Model, DeviceID: info.DeviceId, MAC: info.MAC, - DeviceType: "IOT.SMARTPLUGSWITCH", + DeviceType: devType, EncryptType: "XOR", }, true } diff --git a/internal/kasa/model.go b/internal/kasa/model.go index da0369b..be9825f 100644 --- a/internal/kasa/model.go +++ b/internal/kasa/model.go @@ -1,12 +1,27 @@ package kasa -// OutletState is a normalized representation of an outlet on a Kasa device. +// OutletState is a normalized representation of an outlet or bulb on a Kasa device. type OutletState struct { - Index int `json:"index"` - OutletID string `json:"outlet_id,omitempty"` - Alias string `json:"alias"` - State bool `json:"state"` - OnTime int `json:"on_time"` + Index int `json:"index"` + OutletID string `json:"outlet_id,omitempty"` + Alias string `json:"alias"` + State bool `json:"state"` + OnTime int `json:"on_time"` + IsBulb bool `json:"is_bulb,omitempty"` + Brightness int `json:"brightness,omitempty"` + ColorTemp int `json:"color_temp,omitempty"` + Hue int `json:"hue,omitempty"` + Saturation int `json:"saturation,omitempty"` +} + +// LightState represents the light_state object returned by Kasa smart bulbs (e.g. KL125). +type LightState struct { + OnOff int `json:"on_off"` + Mode string `json:"mode,omitempty"` + Hue int `json:"hue,omitempty"` + Saturation int `json:"saturation,omitempty"` + ColorTemp int `json:"color_temp,omitempty"` + Brightness int `json:"brightness,omitempty"` } // ChildOutlet represents one outlet on a multi-plug strip (e.g. KP303). @@ -24,8 +39,11 @@ type GetSysInfoResult struct { Alias string `json:"alias"` MAC string `json:"mac"` DeviceId string `json:"deviceId"` + MicType string `json:"mic_type,omitempty"` + Type string `json:"type,omitempty"` RelayState int `json:"relay_state"` OnTime int `json:"on_time"` + LightState *LightState `json:"light_state,omitempty"` Children []ChildOutlet `json:"children,omitempty"` } @@ -44,3 +62,12 @@ type SetRelayStateResponse struct { } `json:"set_relay_state"` } `json:"system"` } + +// TransitionLightStateResponse wraps the smartlife.iot.smartbulb.lightingservice transition_light_state response. +type TransitionLightStateResponse struct { + LightingService struct { + TransitionLightState struct { + ErrCode int `json:"err_code"` + } `json:"transition_light_state"` + } `json:"smartlife.iot.smartbulb.lightingservice"` +} -- knotmirror 0.0.1