Class: SmaApi::Http
- Inherits:
-
Object
- Object
- SmaApi::Http
- Defined in:
- lib/sma_api/http.rb
Overview
Net::HTTP wrapper for the SMA Inverter web interface
Instance Method Summary collapse
-
#create_session ⇒ String
Creates a session using the supplied password.
-
#destroy_session ⇒ String
Logout and clear the session.
-
#download(url, path) ⇒ Object
Download the file specified by url and store it in a file on the local file system.
-
#initialize(host:, password:, sid: nil) ⇒ Http
constructor
A new instance of Http.
-
#post(url, payload = {}) ⇒ Hash
Perform a HTTP POST.
-
#sid ⇒ String
The current session id.
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_session ⇒ String
Creates a session using the supplied password
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_session ⇒ String
Logout and clear the session. This is the same as using Logout from the web interface
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.
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.
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 |
#sid ⇒ String
The current session id. If empty, it will create a new session
69 70 71 72 73 |
# File 'lib/sma_api/http.rb', line 69 def sid create_session if @sid.empty? @sid end |