Class: Hass

Inherits:
Object
  • Object
show all
Defined in:
lib/ws_light/hass.rb

Overview

Home Assistant notifier

Instance Method Summary collapse

Constructor Details

#initialize(url, password, logger) ⇒ Hass

Returns a new instance of Hass.



6
7
8
9
10
# File 'lib/ws_light/hass.rb', line 6

def initialize(url, password, logger)
  @url = url
  @password = password
  @logger = logger
end

Instance Method Details

#notify(state = true, sensor_name = 'motion', friendly_name = 'Motion Sensor') ⇒ Object



12
13
14
15
16
# File 'lib/ws_light/hass.rb', line 12

def notify(state = true, sensor_name = 'motion', friendly_name = 'Motion Sensor')
  url = "#{@url}/api/states/sensor.#{sensor_name}"
  data = { 'state' => (state ? 'on' : 'off'), 'attributes' => { 'friendly_name' => friendly_name } }.to_json
  Thread.new { send_data(url, data) }
end

#send_data(url, data) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/ws_light/hass.rb', line 18

def send_data(url, data)
  uri = URI(url)
  puts "Starting request to #{url} with data #{data}"
  https = Net::HTTP.new(uri.host, uri.port)
  request = Net::HTTP::Post.new(uri.path)
  request['Authorization'] = "Bearer #{@password}"
  request['Accept-Encoding'] = 'deflate'
  request.body = data
  https.use_ssl = true if uri.scheme == 'https'
  response = https.request request
  @logger.log("Request to Home Assistant failed (#{response.code}): #{response.body}") #  if response.code > 299
end