smawebboxgo

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

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

Go to latest
Published: Sep 8, 2018 License: Apache-2.0 Imports: 20 Imported by: 0

README

Travis project status badge Project Goreport card analysis badge GoDoc

Go API client for SMA Sunny WebBox

The data loggers Sunny WebBox and Sunny WebBox with Bluetooth continuously record all the data of a PV plant. This is then averaged over a configurable interval and cached. The data can be transmitted at regular intervals to the Sunny Portal for analysis and visualization.

Via the Sunny WebBox and Sunny WebBox with Bluetooth RPC interface, selected data from the PV plant can be transmitted to a remote terminal by means of an RPC protocol (Remote Procedure Call protocol). Related documents:

Overview

  • API version: 1.4.0

This is an unofficial Go API client which currently supports Sunny WebBox with Bluetooth.

Requirements

Run:

go get golang.org/x/oauth2
go get github.com/manios/sma-webbox-go

Usage

Currently this client supports the following procedures:

  • RPC_GET_PLANT_OVERVIEW
  • RPC_GET_DEVICES
  • RPC_GET_PROCESS_DATA_CHANNEL
  • RPC_GET_PROCESS_DATA

To run sample code you can have a look on ./examples directory.

Important Note

According to the official docs the interval between two queries should not be less than 30 seconds.

Create a new client

To create a new client object:

// Set up a new client
smaClient := sma.NewWebboxClient("http://mysolarpark:82")

where http://mysolarpark:82 is the HTTP address and port of your Sunny WebBox in the internet. HTTP Basic Authentication is not supported yet.

Get plant overview

To get a general overview of the solar plant you can execute the following:

// Get plant overview
plantResponse, err := smaClient.GetPlantOverview()

if err != nil {
    panic(err)
}

fmt.Printf("Plant response:%+v\nPlant result:%+v\n", plantResponse, plantResponse.Result)

This will output a response that may look like this (it may vary depending on your solar plant setup):

Plant response:{Result:0xc42010e260 Format:JSON Proc:GetPlantOverview Version:1.0 Id:1536393036 Error_:}
Plant result:&{Overview:[{Meta:GriPwr Name:Power Unit:W Value:20278} {Meta:GriEgyTdy Name:Day yield Unit:kWh Value:44.455} {Meta:GriEgyTot Name:Total yield Unit:kWh Value:659.318} {Meta:OpStt Name:Condition Unit: Value:Ok, Ok, Ok} {Meta:Msg Name:Message Unit: Value:}]}

Get devices

To list all the devices attached to Sunny WebBox execute:

// Get a list of all devices in the park
devicesResponse, err := smaClient.GetDevices()
    
if err != nil {
    panic(err)
} 

fmt.Printf("Device response:%+v\nDevice result:%+v\n", devicesResponse, devicesResponse.Result)

This will output a response that may look like this (it may vary depending on your solar plant setup):

Device response:{Result:0xc420182120 Format:JSON Proc:GetDevices Version:1.0 Id:1536393047 Error_:}
Device result:&{Devices:[{Key:0042:a1bd74d3 Name:SN: 5182157032} {Key:0042:a1bd8a1e Name:SN: 5182163426} {Key:0042:a1bda169 Name:SN: 5182169449} {Key:0042:a1bdb610 Name:SN: 5182169552} {Key:0042:a1bdb616 Name:SN: 2110169558} {Key:0080:7dcb7484 Name:SN: 5182485636} {Key:0088:00006874 Name:SN: 26740}] TotalDevicesReturned:7}

Get process data channels

To get the data channels offered by a specific given device :

// Get the data channels offered by the given device
processDataChannels, err := smaClient.GetProcessDataChannels("0042:a1bd74d3")

if err != nil {
    panic(err)
} 

fmt.Printf("Process data channels response:%+v\nData channels result:%+v\n", processDataChannels, processDataChannels.Result)

where "0145:ad221af2" is the uid of a device returned by GetDevices() function.

This will output a response that may look like this (it may vary depending on your solar plant setup):

Process data channels response:{Result:map[0145:ad221af2:[Ipv Upv-Ist Fac Pac Riso h-On h-Total E-Total Netz-Ein]] Format:JSON Proc:GetProcessDataChannels Version:1.0 Id:1536393199 Error_:}
Data channels result:map[0145:ad221af2:[Ipv Upv-Ist Fac Pac Riso h-On h-Total E-Total Netz-Ein]

Get process data

To return the current data of a specific device , you can use the following:

// Get the current data for the given device
processData, err := smaClient.GetProcessData("0145:ad221af2")

if err != nil {
    panic(err)
} 

fmt.Printf("Process data response:%+v\nData result:%+v\n", processData, processData.Result.Devices[0])

This will output a response that may look like this (it may vary depending on your solar plant setup):

Process data response:{Result:0xc4201282e0 Format:JSON Proc:GetProcessData Version:1.0 Id:1536393257 Error_:}
Data result:{Channels:[{Meta:Ipv Name:DC current input Unit:A Value:5.367} {Meta:Upv-Ist Name:DC voltage input Unit:V Value:531.43} {Meta:WindVel m/s Name:Wind speed Unit:m/s Value:0} {Meta:TmpAmb C Name:Ambient temperature Unit:°C Value:0} {Meta:IntSolIrr Name:Insolation Unit:W/m^2 Value:0} {Meta:Fac Name:Grid frequency Unit:Hz Value:50.01} {Meta:Iac-Ist Name:Grid current Unit:A Value:0} {Meta:Pac Name:Power Unit:W Value:3574} {Meta:Riso Name:Insulation resistance Unit:Ohm Value:3000000} {Meta:TmpMdul C Name:Module temperature Unit:°C Value:0} {Meta:h-On Name:Feed-in time Unit:h Value:30138.18} {Meta:h-Total Name:Operating time Unit:h Value:30535.05} {Meta:E-Total Name:Total yield Unit:kWh Value:173777.824} {Meta:Netz-Ein Name:Number of grid connections Unit: Value:2902}] Key:0080:7dc674d3}

Acknowledgements

This project would never come into life without the help and inspiration from the following resources:

Feature requests / support

This is a free time project so, any bugs or feature requests should be done as new issues.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ContextOAuth2 takes a oauth2.TokenSource as authentication for the request.
	ContextOAuth2 = contextKey("token")

	// ContextBasicAuth takes BasicAuth as authentication for the request.
	ContextBasicAuth = contextKey("basic")

	// ContextAccessToken takes a string oauth2 access token as authentication for the request.
	ContextAccessToken = contextKey("accesstoken")

	// ContextAPIKey takes an APIKey as authentication for the request
	ContextAPIKey = contextKey("apikey")
)

Functions

func CacheExpires

func CacheExpires(r *http.Response) time.Time

CacheExpires helper function to determine remaining time before repeating a request.

Types

type APIClient

type APIClient struct {
	DeviceApi *DeviceApiService

	PlantApi *PlantApiService

	ProcessDataApi *ProcessDataApiService
	// contains filtered or unexported fields
}

APIClient manages communication with the SMA WebBox RPC over HTTP REST API API v1.4.0 In most cases there should be only one, shared, APIClient.

func NewAPIClient

func NewAPIClient(cfg *Configuration) *APIClient

NewAPIClient creates a new API client. Requires a userAgent string describing your application. optionally a custom http.Client to allow for advanced features such as caching.

func (*APIClient) ChangeBasePath

func (c *APIClient) ChangeBasePath(path string)

Change base path to allow switching to mocks

type APIKey

type APIKey struct {
	Key    string
	Prefix string
}

APIKey provides API key based authentication to a request passed via context using ContextAPIKey

type APIResponse

type APIResponse struct {
	*http.Response `json:"-"`
	Message        string `json:"message,omitempty"`
	// Operation is the name of the swagger operation.
	Operation string `json:"operation,omitempty"`
	// RequestURL is the request URL. This value is always available, even if the
	// embedded *http.Response is nil.
	RequestURL string `json:"url,omitempty"`
	// Method is the HTTP method used for the request.  This value is always
	// available, even if the embedded *http.Response is nil.
	Method string `json:"method,omitempty"`
	// Payload holds the contents of the response body (which may be nil or empty).
	// This is provided here as the raw response.Body() reader will have already
	// been drained.
	Payload []byte `json:"-"`
}

func NewAPIResponse

func NewAPIResponse(r *http.Response) *APIResponse

func NewAPIResponseWithError

func NewAPIResponseWithError(errorMessage string) *APIResponse

type ApiError

type ApiError struct {
	//
	Format string `json:"format"`
	//
	Proc string `json:"proc"`
	//
	Version string `json:"version"`
	//
	Id string `json:"id"`
	//
	Error_ string `json:"error,omitempty"`
}

type BasicAuth

type BasicAuth struct {
	UserName string `json:"userName,omitempty"`
	Password string `json:"password,omitempty"`
}

BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth

type Channel

type Channel struct {
	// The meta name which uniquely defines the channel (e.g. \"ExtSolIrr\").
	Meta string `json:"meta,omitempty"`
	// The translated display name (e.g. \"External irradiation\"). Defining this element is optional. (optional)
	Name string `json:"name,omitempty"`
	// The unit of the channel (e.g. \"W/m^2\"). For channels which have no unit, an empty string must be entered. (optional)
	Unit string `json:"unit,omitempty"`
	// The value of the channel (e.g. \"843\"). Defining this element is optional. (optional)
	Value string `json:"value,omitempty"`
}

type Configuration

type Configuration struct {
	BasePath      string            `json:"basePath,omitempty"`
	Host          string            `json:"host,omitempty"`
	Scheme        string            `json:"scheme,omitempty"`
	DefaultHeader map[string]string `json:"defaultHeader,omitempty"`
	UserAgent     string            `json:"userAgent,omitempty"`
	HTTPClient    *http.Client
}

func NewConfiguration

func NewConfiguration() *Configuration

func (*Configuration) AddDefaultHeader

func (c *Configuration) AddDefaultHeader(key string, value string)

type Device

type Device struct {
	// A unique device key (e.g. \"SB21TL06:2000106925\").
	Key string `json:"key,omitempty"`
	// The user-definable name of the device (e.g. \"INV left\"). Defining this element is optional. If the element is used but no name was defined, “`null“` is entered.
	Name string `json:"name,omitempty"`
}

type DeviceApiService

type DeviceApiService service

func (*DeviceApiService) GetDevices

DeviceApiService Devices connected to SMA Webbox

  • @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
  • @param rpcbody A JSON request which contains an encrypted JWT token and a groupId. The encrypted token is valid for a random time in the range between [5,10] seconds.

@return DevicesResponse

type DeviceChannelValues

type DeviceChannelValues struct {
	Channels []Channel `json:"channels,omitempty"`
	// The unique id (key) of the device
	Key string `json:"key,omitempty"`
}

type DeviceDataChannels

type DeviceDataChannels struct {
	Result map[string][]string `json:"result,omitempty"`
	//
	Format string `json:"format"`
	//
	Proc string `json:"proc"`
	//
	Version string `json:"version"`
	//
	Id string `json:"id"`
	//
	Error_ string `json:"error,omitempty"`
}

type DeviceDataChannelsDeviceRequest

type DeviceDataChannelsDeviceRequest struct {
	//
	Device string `json:"device,omitempty"`
}

type DeviceDataChannelsRequest

type DeviceDataChannelsRequest struct {
	//
	Format string `json:"format,omitempty"`
	//
	Proc string `json:"proc,omitempty"`
	//
	Version string `json:"version,omitempty"`
	//
	Id     string                           `json:"id,omitempty"`
	Params *DeviceDataChannelsDeviceRequest `json:"params,omitempty"`
}

type DevicesChannelValuesDto

type DevicesChannelValuesDto struct {
	Devices []DeviceChannelValues `json:"devices,omitempty"`
}

type DevicesDto

type DevicesDto struct {
	Devices              []Device `json:"devices,omitempty"`
	TotalDevicesReturned int32    `json:"totalDevicesReturned,omitempty"`
}

type DevicesResponse

type DevicesResponse struct {
	Result *DevicesDto `json:"result,omitempty"`
	//
	Format string `json:"format"`
	//
	Proc string `json:"proc"`
	//
	Version string `json:"version"`
	//
	Id string `json:"id"`
	//
	Error_ string `json:"error,omitempty"`
}

type GenericRequest

type GenericRequest struct {
	//
	Format string `json:"format,omitempty"`
	//
	Proc string `json:"proc,omitempty"`
	//
	Version string `json:"version,omitempty"`
	//
	Id string `json:"id,omitempty"`
}

Mother of all requests

type GenericSwaggerError

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

GenericSwaggerError Provides access to the body, error and model on returned errors.

func (GenericSwaggerError) Body

func (e GenericSwaggerError) Body() []byte

Body returns the raw bytes of the response

func (GenericSwaggerError) Error

func (e GenericSwaggerError) Error() string

Error returns non-empty string if there was an error.

func (GenericSwaggerError) Model

func (e GenericSwaggerError) Model() interface{}

Model returns the unpacked model of the error

type PlantApiService

type PlantApiService service

func (*PlantApiService) GetPlantOverview

func (a *PlantApiService) GetPlantOverview(ctx context.Context, rpcbody GenericRequest) (PlantOverviewResponse, *http.Response, error)

PlantApiService Photovoltaic plant Overview values Returns an object with the following plant data:<ul><li>POWER</li><li>DAILY-YIELD</li><li>TOTAL-YIELD</li><li>STATUS</li><li>ERROR</li></ul>

  • @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
  • @param rpcbody A JSON request which contains an encrypted JWT token and a groupId. The encrypted token is valid for a random time in the range between [5,10] seconds.

@return PlantOverviewResponse

type PlantOverview

type PlantOverview struct {
	Overview []Channel `json:"overview,omitempty"`
}

type PlantOverviewResponse

type PlantOverviewResponse struct {
	Result *PlantOverview `json:"result,omitempty"`
	// Format of the response. In current implementation it always returns: JSON
	Format string `json:"format"`
	// Name of the RPC call. For this call it is: PlantOverview
	Proc string `json:"proc"`
	// Returns the API version of this response
	Version string `json:"version"`
	// A random
	Id string `json:"id"`
	//
	Error_ string `json:"error,omitempty"`
}

type ProcessDataApiService

type ProcessDataApiService service

func (*ProcessDataApiService) GetProcessData

ProcessDataApiService Returns process data for up to 5 devices per request.

  • @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
  • @param rpcbody A JSON request which contains an encrypted JWT token and a groupId. The encrypted token is valid for a random time in the range between [5,10] seconds.

@return ProcessDataResponse

func (*ProcessDataApiService) GetProcessDataChannels

ProcessDataApiService List of the process data channels for a particular device type. Returns a list with the meta names of the available process data channels for a particular device type.

  • @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
  • @param rpcbody A JSON request which contains an encrypted JWT token and a groupId. The encrypted token is valid for a random time in the range between [5,10] seconds.

@return ProcessDataChannelsResponse

type ProcessDataChannelsResponse

type ProcessDataChannelsResponse struct {
	Result map[string][]string `json:"result,omitempty"`
	//
	Format string `json:"format"`
	//
	Proc string `json:"proc"`
	//
	Version string `json:"version"`
	//
	Id string `json:"id"`
	//
	Error_ string `json:"error,omitempty"`
}

type ProcessDataRequest

type ProcessDataRequest struct {
	//
	Format string `json:"format,omitempty"`
	//
	Proc string `json:"proc,omitempty"`
	//
	Version string `json:"version,omitempty"`
	//
	Id     string                              `json:"id,omitempty"`
	Params *ProcessDataRequestDevicesContainer `json:"params,omitempty"`
}

type ProcessDataRequestDeviceObject

type ProcessDataRequestDeviceObject struct {
	// A device unique key
	Key string `json:"key,omitempty"`
	//
	Channels []string `json:"channels,omitempty"`
}

type ProcessDataRequestDevicesContainer

type ProcessDataRequestDevicesContainer struct {
	//
	Devices []ProcessDataRequestDeviceObject `json:"devices,omitempty"`
}

type ProcessDataResponse

type ProcessDataResponse struct {
	Result *DevicesChannelValuesDto `json:"result,omitempty"`
	//
	Format string `json:"format"`
	//
	Proc string `json:"proc"`
	//
	Version string `json:"version"`
	//
	Id string `json:"id"`
	//
	Error_ string `json:"error,omitempty"`
}

type WebboxClient

type WebboxClient struct {
	// The Url of SMA Sunny Webbox
	URL       string
	ApiClient *APIClient
}

https://stackoverflow.com/a/42872183/1411901 https://stackoverflow.com/questions/20895552/how-to-read-input-from-console-line https://stackoverflow.com/questions/19303137/golang-read-ints-from-stdin-until-eof-while-reporting-format-errors

func NewWebboxClient

func NewWebboxClient(url string) WebboxClient

func (*WebboxClient) GetDevices

func (w *WebboxClient) GetDevices() (DevicesResponse, error)

GetDevices returns an object which contains a list of the devices which are attached to SMA Webbox device.

func (*WebboxClient) GetPlantOverview

func (w *WebboxClient) GetPlantOverview() (PlantOverviewResponse, error)

func (*WebboxClient) GetProcessData

func (w *WebboxClient) GetProcessData(deviceUid string) (ProcessDataResponse, error)

func (*WebboxClient) GetProcessDataChannels

func (w *WebboxClient) GetProcessDataChannels(deviceID string) (ProcessDataChannelsResponse, error)

func (*WebboxClient) GetProcessDataForDevices

func (w *WebboxClient) GetProcessDataForDevices(devList []ProcessDataRequestDeviceObject) (ProcessDataResponse, error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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