package kasa import ( "context" "encoding/json" "fmt" "strings" "sync" ) // LightOptions specifies optional lighting parameters when controlling a smart bulb. type LightOptions struct { Brightness *int ColorTemp *int Hue *int Saturation *int TransitionPeriod *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 DeviceHost() string DeviceAlias() string Close() error } type DeviceClient struct { host string username string password string klap *KLAPSession legacyMode bool alias string isBulb bool children []ChildOutlet mu sync.RWMutex } // NewClient creates a new Client for the target host. func NewClient(host, username, password string) (*DeviceClient, error) { klap, err := NewKLAPSession(host, 80, username, password) if err != nil { return nil, err } return &DeviceClient{ host: host, username: username, password: password, klap: klap, }, nil } func (c *DeviceClient) DeviceHost() string { return c.host } func (c *DeviceClient) DeviceAlias() string { c.mu.RLock() defer c.mu.RUnlock() if c.alias != "" { return c.alias } return c.host } func (c *DeviceClient) Close() error { return nil } func (c *DeviceClient) send(ctx context.Context, reqJSON string) (string, error) { if c.legacyMode { return SendLegacy(ctx, c.host, 9999, reqJSON) } resp, err := c.klap.Send(ctx, reqJSON) if err != nil { // If port 80 failed to connect or was refused, try falling back to legacy port 9999 if resp == "" { legacyResp, legacyErr := SendLegacy(ctx, c.host, 9999, reqJSON) if legacyErr == nil { c.legacyMode = true return legacyResp, nil } } return "", err } return resp, nil } // GetOutlets retrieves current sysinfo and extracts all outlet states. func (c *DeviceClient) GetOutlets(ctx context.Context) ([]OutletState, error) { respJSON, err := c.send(ctx, `{"system":{"get_sysinfo":{}}}`) if err != nil { return nil, fmt.Errorf("failed to get sysinfo from %s: %w", c.host, err) } var resp SysInfoResponse if err := json.Unmarshal([]byte(respJSON), &resp); err != nil { return nil, fmt.Errorf("failed to unmarshal sysinfo from %s: %w", c.host, err) } info := resp.System.GetSysInfo if info.ErrCode != 0 { 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() var outlets []OutletState if len(info.Children) > 0 { // Multi-outlet power strip (e.g. KP303, HS300) for i, ch := range info.Children { alias := ch.Alias if alias == "" { alias = fmt.Sprintf("Outlet %d", i) } outlets = append(outlets, OutletState{ Index: i, OutletID: ch.ID, Alias: alias, State: ch.State == 1, 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 if alias == "" { alias = c.host } outlets = append(outlets, OutletState{ Index: 0, OutletID: "", Alias: alias, State: info.RelayState == 1, OnTime: info.OnTime, }) } return outlets, nil } 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{}) } reqJSON, err := buildRelayPayload(children, outletIndex, state) if err != nil { return err } respJSON, err := c.send(ctx, reqJSON) if err != nil { return fmt.Errorf("failed to set outlet state on %s: %w", c.host, err) } var resp SetRelayStateResponse if err := json.Unmarshal([]byte(respJSON), &resp); err != nil { return fmt.Errorf("failed to unmarshal set_relay_state response from %s: %w", c.host, err) } if resp.System.SetRelayState.ErrCode != 0 { return fmt.Errorf("set_relay_state error code %d from %s", resp.System.SetRelayState.ErrCode, c.host) } return nil } func buildRelayPayload(children []ChildOutlet, outletIndex int, state bool) (string, error) { stateInt := 0 if state { stateInt = 1 } if len(children) > 0 { if outletIndex < 0 || outletIndex >= len(children) { return "", fmt.Errorf("outlet index %d out of bounds (device has %d outlets)", outletIndex, len(children)) } childID := children[outletIndex].ID return fmt.Sprintf(`{"context":{"child_ids":["%s"]},"system":{"set_relay_state":{"state":%d}}}`, childID, stateInt), nil } return fmt.Sprintf(`{"system":{"set_relay_state":{"state":%d}}}`, stateInt), 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 { reqJSON, err := buildLightPayload(state, opts) if err != nil { return err } respJSON, err := c.send(ctx, reqJSON) 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 } func buildLightPayload(state bool, opts LightOptions) (string, error) { onOff := 0 if state { onOff = 1 } transitionPeriod := 0 if opts.TransitionPeriod != nil { transitionPeriod = *opts.TransitionPeriod } params := map[string]any{ "on_off": onOff, "transition_period": transitionPeriod, } 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) } return string(reqBytes), nil }