Class: AirThingsApiConnection
- Inherits:
-
Object
- Object
- AirThingsApiConnection
- Defined in:
- lib/logstash/inputs/airthings.rb
Overview
Generate a repeating message.
This plugin is intented only as an example.
Instance Method Summary collapse
- #get_devices ⇒ Object
- #get_latest_values(device_id) ⇒ Object
- #get_token ⇒ Object
-
#initialize(client_id, client_secret, logger) ⇒ AirThingsApiConnection
constructor
A new instance of AirThingsApiConnection.
- #send_request(method_class, path) ⇒ Object
Constructor Details
#initialize(client_id, client_secret, logger) ⇒ AirThingsApiConnection
Returns a new instance of AirThingsApiConnection.
11 12 13 14 15 16 17 18 19 20 21 |
# File 'lib/logstash/inputs/airthings.rb', line 11 def initialize(client_id, client_secret, logger) @session = Net::HTTP.start("ext-api.airthings.com", 443, use_ssl: true) @logger = logger @client_id = client_id @client_secret = client_secret @token_hash = { expires: 0 } end |
Instance Method Details
#get_devices ⇒ Object
74 75 76 77 78 |
# File 'lib/logstash/inputs/airthings.rb', line 74 def get_devices resp = self.send_request(Net::HTTP::Get, "/v1/devices") return resp["devices"] end |
#get_latest_values(device_id) ⇒ Object
80 81 82 83 84 |
# File 'lib/logstash/inputs/airthings.rb', line 80 def get_latest_values(device_id) resp = self.send_request(Net::HTTP::Get, "/v1/devices/#{device_id}/latest-samples") return resp["data"] end |
#get_token ⇒ Object
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/logstash/inputs/airthings.rb', line 23 def get_token now = Time.now.to_i expires = @token_hash[:expires] if expires < now @logger.debug("Getting new Airthings API access token") req = Net::HTTP::Post.new("https://accounts-api.airthings.com/v1/token") req.body = JSON.generate({ grant_type: "client_credentials", client_id: @client_id, client_secret: @client_secret.value, scope: [ "read:device:current_values" ] }) req["Content-Type"] = "application/json" resp = @session.request(req) resp_json = JSON.parse(resp.body) @token_hash = { expires: now + resp_json["expires_in"] - 60, response: resp_json } end return @token_hash[:response]["access_token"] end |
#send_request(method_class, path) ⇒ Object
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
# File 'lib/logstash/inputs/airthings.rb', line 53 def send_request(method_class, path) unless path.start_with?("/") path = "/" + path end req = method_class.new("https://ext-api.airthings.com" + path) req["Accept"] = "application/json" req["Authorization"] = "Bearer " + self.get_token resp = @session.request(req) resp_json = JSON.parse(resp.body) error = resp_json["error_description"] if error @logger.error("Error received from Airthings API", :error => error) end return resp_json end |