ewelink

package module
v0.0.0-...-0503464 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 25, 2023 License: MIT Imports: 17 Imported by: 2

README

Ewelink SDK to control your eWelink smart devices.

Build Status Reviewdog Go Report Card GoDoc Codacy Badge

Check out the API Documentation http://godoc.org/github.com/NicklasWallgren/ewelink

Installation

The library can be installed through go get

go get github.com/NicklasWallgren/ewelink

Supported versions

We support the two major Go versions, which are 1.15 and 1.16 at the moment.

Features

  • Retrieve devices
  • Turn on/off devices
  • Get power consumption [TODO]

Examples

Initiate power state request

import (
    "context"
    "fmt"
    "github.com/NicklasWallgren/ewelink"
)

instance := ewelink.New()

// authenticate using email
session, err := instance.AuthenticateWithEmail(
	context.Background(), ewelink.NewConfiguration("REGION"), "EMAIL", "PASSWORD")

// retrieve the list of registered devices
devices, err := instance.GetDevices(context.Background(), session)

// turn on the outlet(s) of the first device
response, err := instance.SetDevicePowerState(context.Background(), session, &devices.Devicelist[0], true)

fmt.Println(response)
fmt.Println(err)

Custom AppId and AppSecret

You can provide your own AppId and AppSecret, which can be retrieved from https://dev.ewelink.cc.

ewelink.NewConfiguration("REGION", ewelink.WithAppID("APP_ID"), ewelink.WithAppSecret("APP_SECRET"))

Unit tests

go test -v -race ./...
Code Guide

We use GitHub Actions to make sure the codebase is consistent (golangci-lint run) and continuously tested (go test -v -race $(go list ./... | grep -v vendor)). We try to keep comments at a maximum of 120 characters of length and code at 120.

Contributing

If you find any problems or have suggestions about this library, please submit an issue. Moreover, any pull request, code review and feedback are welcome.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var APIErrorCauses = struct {
	WrongRegion         APIErrorCause
	AuthenticationError APIErrorCause
	InvalidRequest      APIErrorCause
	InternalError       APIErrorCause
	UnknownError        APIErrorCause
}{
	WrongRegion:         "Wrong region",
	AuthenticationError: "Authentication required",
	InvalidRequest:      "Invalid request",
	InternalError:       "Internal server error",
}

APIErrorCauses holds information about all known api error causes.

Functions

This section is empty.

Types

type APIErrorCause

type APIErrorCause string

APIErrorCause corresponds to a typical api error cause.

type ActionPayload

type ActionPayload struct {
	Action     string     `json:"action"`
	UserAgent  string     `json:"userAgent"`
	Parameters parameters `json:"params"`
	APIKey     string     `json:"apikey"`
	DeviceID   string     `json:"deviceid"`
	Sequence   int64      `json:"sequence"`
}

ActionPayload struct.

type AppInformation

type AppInformation struct{}

AppInformation struct.

type Application

type Application struct {
	AppVersion string
	Version    string
	ApkVersion string
}

Application contains the application specific fields.

func (Application) String

func (a Application) String() string

type AuthenticateActionPayload

type AuthenticateActionPayload struct {
	Action     string `json:"action"`
	APIKey     string `json:"apikey"`
	AppID      string `json:"appid"`
	UserAgent  string `json:"userAgent"`
	Version    string `json:"version"`
	Nonce      string `json:"nonce"`
	ApkVersion string `json:"apkVersion"`
	Os         string `json:"os"`
	At         string `json:"at"`
	Ts         string `json:"ts"`
	Model      string `json:"model"`
	RomVersion string `json:"romVersion"`
	Sequence   int64  `json:"sequence"`
}

AuthenticateActionPayload struct.

type AuthenticationResponse

type AuthenticationResponse struct {
	At   string `json:"at"`
	Rt   string `json:"rt"`
	User User   `json:"user"`
	// contains filtered or unexported fields
}

AuthenticationResponse struct.

func (*AuthenticationResponse) Decode

func (a *AuthenticationResponse) Decode(payload io.ReadCloser) (Response, error)

func (AuthenticationResponse) Envelope

func (h AuthenticationResponse) Envelope() Envelope

func (AuthenticationResponse) String

func (a AuthenticationResponse) String() string

type Authenticator

type Authenticator interface {
	Authenticate(context context.Context, client Client, session *Session) error
}

Authenticator is the interface implemented by types that authenticate a user.

func NewEmailAuthenticator

func NewEmailAuthenticator(email string, password string) Authenticator

NewEmailAuthenticator returns a new instance of 'NewEmailAuthenticator.

func NewPhoneNumberAuthenticator

func NewPhoneNumberAuthenticator(phoneNumber string, password string) Authenticator

NewPhoneNumberAuthenticator returns a new instance of 'NewPhoneNumberAuthenticator.

type Client

type Client interface {
	// contains filtered or unexported methods
}

Client is the interface implemented by types that can invoke the Ewelink API.

type Configuration

type Configuration struct {
	// The user account region
	Region       string
	APIURL       string
	WebsocketURL *url.URL
	AppID        string
	AppSecret    string
}

Configuration contains the configuration specific fields.

func NewConfiguration

func NewConfiguration(region string, optionFunc ...ConfigurationOptionFunc) *Configuration

NewConfiguration creates a new Configuration.

func (Configuration) String

func (c Configuration) String() string

type ConfigurationOptionFunc

type ConfigurationOptionFunc func(c *Configuration)

ConfigurationOptionFunc option definition.

func WithAppID

func WithAppID(appID string) ConfigurationOptionFunc

WithAppID option func to provide custom AppID.

func WithAppSecret

func WithAppSecret(appSecret string) ConfigurationOptionFunc

WithAppSecret option func to provide custom AppSecret.

type Device

type Device struct {
	Settings struct {
		OpsNotify   int `json:"opsNotify"`
		OpsHistory  int `json:"opsHistory"`
		AlarmNotify int `json:"alarmNotify"`
	} `json:"settings"`
	Group     string        `json:"group"`
	Online    bool          `json:"online"`
	Groups    []interface{} `json:"groups"`
	DevGroups []interface{} `json:"devGroups"`
	ID        string        `json:"_id"`
	Name      string        `json:"name"`
	Type      string        `json:"type"`
	DeviceID  string        `json:"deviceid"`
	Apikey    string        `json:"apikey"`
	Extra     struct {
		Extra struct {
			Description  string `json:"description"`
			BrandID      string `json:"brandId"`
			Apmac        string `json:"apmac"`
			Mac          string `json:"mac"`
			UI           string `json:"ui"`
			ModelInfo    string `json:"modelInfo"`
			Model        string `json:"model"`
			Manufacturer string `json:"manufacturer"`
			Uiid         int    `json:"uiid"`
			StaMac       string `json:"staMac"`
		} `json:"extra"`
		ID string `json:"_id"`
	} `json:"extra"`
	CreatedAt  time.Time `json:"createdAt"`
	V          int       `json:"__v"`
	OnlineTime time.Time `json:"onlineTime"`
	IP         string    `json:"ip"`
	Location   string    `json:"location"`
	Params     struct {
		Rssi   int    `json:"rssi"`
		StaMac string `json:"staMac"`
		Timers []struct {
			Enabled          int    `json:"enabled"`
			Type             string `json:"type"`
			At               string `json:"at"`
			MID              string `json:"mId"`
			CoolkitTimerType string `json:"coolkit_timer_type"`
			Do               struct {
				Switch string `json:"switch"`
			} `json:"do"`
		} `json:"timers"`
		Startup       string   `json:"startup"`
		FwVersion     string   `json:"fwVersion"`
		Switch        string   `json:"switch"`
		Switches      []string `json:"switches"`
		ControlType   int      `json:"controlType"`
		PartnerApikey string   `json:"partnerApikey"`
		BindInfos     struct {
			Gaction []string `json:"gaction"`
		} `json:"bindInfos"`
	} `json:"params"`
	OfflineTime  time.Time     `json:"offlineTime"`
	DeviceStatus string        `json:"deviceStatus"`
	SharedTo     []interface{} `json:"sharedTo"`
	Devicekey    string        `json:"devicekey"`
	DeviceURL    string        `json:"deviceUrl"`
	BrandName    string        `json:"brandName"`
	ShowBrand    bool          `json:"showBrand"`
	BrandLogoURL string        `json:"brandLogoUrl"`
	ProductModel string        `json:"productModel"`
	DevConfig    struct{}      `json:"devConfig"`
	Uiid         int           `json:"uiid"`
	Tags         struct {
		DisableTimers []struct {
			Do struct {
				Switch string `json:"switch"`
			} `json:"do"`
			CoolkitTimerType string `json:"coolkit_timer_type"`
			MID              string `json:"mId"`
			At               string `json:"at"`
			Type             string `json:"type"`
			Enabled          int    `json:"enabled"`
		} `json:"disable_timers"`
	} `json:"tags,omitempty"`
}

Device struct. nolint:maligned

func (*Device) String

func (d *Device) String() string

type DeviceOutletPowerStateAction

type DeviceOutletPowerStateAction struct {
	PowerOn []bool `json:"switches"`
	// contains filtered or unexported fields
}

DeviceOutletPowerStateAction device with multiple outlets.

func (DeviceOutletPowerStateAction) MarshalJSON

func (d DeviceOutletPowerStateAction) MarshalJSON() ([]byte, error)

MarshalJSON returns a JSON encoded 'DeviceOutletPowerStateAction'.

type DevicePowerStateParameters

type DevicePowerStateParameters struct {
	PowerOn bool `json:"switch"`
	// contains filtered or unexported fields
}

DevicePowerStateParameters for devices with only one outlet.

func (DevicePowerStateParameters) MarshalJSON

func (d DevicePowerStateParameters) MarshalJSON() ([]byte, error)

MarshalJSON returns a JSON encoded 'DevicePowerStateParameters'.

type DevicesResponse

type DevicesResponse struct {
	Devicelist []Device `json:"devicelist"`
	// contains filtered or unexported fields
}

DevicesResponse struct.

func (*DevicesResponse) Decode

func (d *DevicesResponse) Decode(payload io.ReadCloser) (Response, error)

func (DevicesResponse) Envelope

func (h DevicesResponse) Envelope() Envelope

func (DevicesResponse) String

func (d DevicesResponse) String() string

type Envelope

type Envelope interface {
	Code() int
	Cause() string
}

Envelope interface.

type Ewelink struct {
	// contains filtered or unexported fields
}

Ewelink contains the validator and Configuration context.

func New

func New(options ...Option) *Ewelink

New returns a new instance of 'Ewelink'.

func (Ewelink) Authenticate

func (e Ewelink) Authenticate(context context.Context, configuration *Configuration, authenticator Authenticator, options ...SessionOptionFunc) (*Session, error)

Authenticate - Authenticates a new user session using an authenticator.

func (Ewelink) AuthenticateWithEmail

func (e Ewelink) AuthenticateWithEmail(context context.Context, configuration *Configuration, email string, password string, options ...SessionOptionFunc) (*Session, error)

AuthenticateWithEmail - Authenticates a new user session using email as identifier.

func (Ewelink) AuthenticateWithPhoneNumber

func (e Ewelink) AuthenticateWithPhoneNumber(context context.Context, configuration *Configuration, phoneNumber string, password string, options ...SessionOptionFunc) (*Session, error)

AuthenticateWithPhoneNumber - Authenticates a new user session using phoneNumber as identifier.

func (Ewelink) GetDevice

func (e Ewelink) GetDevice(ctx context.Context, session *Session, deviceID string) (*Device, error)

GetDevice - Returns information about a device.

func (Ewelink) GetDevices

func (e Ewelink) GetDevices(ctx context.Context, session *Session) (*DevicesResponse, error)

GetDevices - Returns information about the devices.

func (Ewelink) SetDeviceOutletPowerState

func (e Ewelink) SetDeviceOutletPowerState(context context.Context, session *Session, device *Device, stateOn bool, outletIndex int) (Response, error)

SetDeviceOutletPowerState - Toggles an outlet of a device The outlet indices start at 0.

func (Ewelink) SetDevicePowerState

func (e Ewelink) SetDevicePowerState(context context.Context, session *Session, device *Device, stateOn bool) (Response, error)

SetDevicePowerState - Toggles the outlet(s) of a device.

type HTTPRequest

type HTTPRequest interface {
	Method() string
	URI() string
	Query() *url.Values
	Payload() payload
	Headers() *http.Header
	Response() Response
	IsToBeSigned() bool
	Session() *Session
}

HTTPRequest interface.

type IOSDevice

type IOSDevice struct {
	// contains filtered or unexported fields
}

IOSDevice holds the contextual information for a IOS device.

func (IOSDevice) Imei

func (i IOSDevice) Imei() string

Imei returns the IOS IMEI.

func (IOSDevice) Model

func (i IOSDevice) Model() string

Model returns the IOS model.

func (IOSDevice) Os

func (i IOSDevice) Os() string

Os returns the Os model.

func (IOSDevice) RomVersion

func (i IOSDevice) RomVersion() string

RomVersion returns the Rom version.

func (IOSDevice) String

func (i IOSDevice) String() string

type MobileDevice

type MobileDevice interface {
	Model() string
	Imei() string
	Os() string
	RomVersion() string
}

MobileDevice is the interface implemented by types that can deliver information about a mobile device.

type Option

type Option func(evelink *Ewelink)

Option option definition.

type Response

type Response interface {
	Decode(payload io.ReadCloser) (Response, error)
	Envelope() Envelope
}

Response interface.

type Session

type Session struct {
	MobileDevice        MobileDevice
	Application         *Application
	AuthenticationToken string
	User                *User
	Configuration       *Configuration
}

Session holds the session metadata.

func (Session) String

func (s Session) String() string

type SessionOptionFunc

type SessionOptionFunc func(session *Session)

SessionOptionFunc option definition.

type SetDeviceOutletPowerStateResponse

type SetDeviceOutletPowerStateResponse struct {
	// contains filtered or unexported fields
}

SetDeviceOutletPowerStateResponse struct.

func (*SetDeviceOutletPowerStateResponse) Decode

func (SetDeviceOutletPowerStateResponse) Envelope

func (w SetDeviceOutletPowerStateResponse) Envelope() Envelope

func (SetDeviceOutletPowerStateResponse) String

type SetDevicePowerStateResponse

type SetDevicePowerStateResponse struct {
	// contains filtered or unexported fields
}

SetDevicePowerStateResponse struct.

func (*SetDevicePowerStateResponse) Decode

func (r *SetDevicePowerStateResponse) Decode(payload io.ReadCloser) (Response, error)

func (SetDevicePowerStateResponse) Envelope

func (w SetDevicePowerStateResponse) Envelope() Envelope

func (SetDevicePowerStateResponse) String

type User

type User struct {
	ID              string      `json:"_id"`
	Email           string      `json:"email"`
	Password        string      `json:"password"`
	AppID           string      `json:"appid"`
	CreatedAt       string      `json:"createdat"`
	APIKey          string      `json:"apikey"`
	Online          bool        `json:"online"`
	OnlineTime      string      `json:"onlinetime"`
	IP              string      `json:"ip"`
	Location        string      `json:"location"`
	Language        string      `json:"lang"`
	OfflineTime     string      `json:"offlinetime"`
	BindInformation interface{} `json:"bindInfos"`
	AppInformation  interface{} `json:"appInfos"`
	UserStatus      string      `json:"userstatus"`
	UnknownField01  int         `json:"__v"`
}

User struct.

func (User) String

func (u User) String() string

type WebsocketClient

type WebsocketClient interface {
	// contains filtered or unexported methods
}

WebsocketClient is the interface implemented by types that can invoke the Ewelink Websocket Api.

type WebsocketRequest

type WebsocketRequest interface {
	Payload() payload
	Response() Response
	Session() *Session
}

WebsocketRequest interface.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL