Class: SmaApi::Http

Inherits:
Object
  • Object
show all
Defined in:
lib/sma_api/http.rb

Overview

Net::HTTP wrapper for the SMA Inverter web interface

Instance Method Summary collapse

Constructor Details

#initialize(host:, password:, sid: nil) ⇒ Http

Returns a new instance of Http.



9
10
11
12
13
# File 'lib/sma_api/http.rb', line 9

def initialize(host:, password:, sid: nil)
  @host = host
  @password = password
  @sid = sid || ''
end

Instance Method Details

#create_sessionString

Creates a session using the supplied password

Returns:

  • (String)

    the session id that will be used in subsequent requests.

Raises:

  • (SmaApi::Error)

    Creating session failed, for example if the password is wrong



55
56
57
58
59
60
61
62
63
64
# File 'lib/sma_api/http.rb', line 55

def create_session
  payload = {
    right: 'usr', pass: @password
  }
  result = JSON.parse(http.post('/dyn/login.json', payload.to_json).body).fetch('result', {})

  raise SmaApi::Error, 'Creating session failed' unless result['sid']

  @sid = result['sid']
end

#destroy_sessionString

Logout and clear the session. This is the same as using Logout from the web interface

Returns:

  • (String)

    An empty session id



78
79
80
81
82
# File 'lib/sma_api/http.rb', line 78

def destroy_session
  post('/dyn/logout.json', {})

  @sid = ''
end

#download(url, path) ⇒ Object

Download the file specified by url and store it in a file on the local file system.

Parameters:

  • url (String)

    URL without /fs prefix. It should start with a ‘/’

  • path (String)

    Path of the local file



37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/sma_api/http.rb', line 37

def download(url, path)
  create_session if @sid.empty?

  file = File.open(path, 'wb')

  begin
    res = retrieve_file(url)

    file.write(res.body)
  ensure
    file.close
  end
end

#post(url, payload = {}) ⇒ Hash

Perform a HTTP POST.

Parameters:

  • url (String)

    URL. It should start with a ‘/’

  • payload (Hash) (defaults to: {})

    The payload that will be used in the post

Returns:

  • (Hash)

    The response

Raises:



20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/sma_api/http.rb', line 20

def post(url, payload = {})
  create_session if @sid.empty?

  response = JSON.parse(http.post(url_with_sid(url), payload.to_json).body)

  return response unless response.key? 'err'

  raise SmaApi::Error, "Error #{response['err']} during request" unless response['err'] == 401

  create_session
  post(url, payload)
end

#sidString

The current session id. If empty, it will create a new session

Returns:

  • (String)

    the session id that will be used in subsequent requests.



69
70
71
72
73
# File 'lib/sma_api/http.rb', line 69

def sid
  create_session if @sid.empty?

  @sid
end