-
Notifications
You must be signed in to change notification settings - Fork 1
/
paho_mqtt_pub_weather.rb
68 lines (46 loc) · 1.68 KB
/
paho_mqtt_pub_weather.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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
52
53
54
55
56
57
58
59
60
61
62
63
64
require 'paho-mqtt'
require 'net/http' # +++
require 'json' # +++
# New functions for current_weather
def current_weather(city)
f = File.open('api_key.txt') # A single line file containing your API Key
# -- You'll have to make your own.
api_key = f.read
f.close
uri = URI("https://api.openweathermap.org/data/2.5/weather?q=#{city}&appid=#{api_key}")
Net::HTTP.start(uri.host, uri.port,:use_ssl => uri.scheme == 'https') do |http|
request = Net::HTTP::Get.new uri
response = http.request request # Net::HTTPResponse object
retval = JSON.parse(response.body)
return retval
end
end
# Kelvin to Farenheit conversion
def k_to_f(k_temp)
f_temp = 32 + (k_temp.to_f - 273.15)*9/5
return f_temp.round(2)
end
##################################################
### Create a simple client with default attributes
client = PahoMqtt::Client.new
### Register a callback for puback event when the Broker acknowledges a publication
waiting_puback = true # A flag so we can wait for the acknowledgement
client.on_puback do
waiting_puback = false
puts "Message Acknowledged by Broker"
end
### Connect to the test broker on port 1883 (Unencrypted mode)
client.connect('localhost', 1883)
### New weather publications
cities = ["San Jose","Tucson","Phoenix","Atlanta"]
cities.each do |city|
report = current_weather(city)
current_temperature_k = k_to_f(report["main"]["temp"])
waiting_puback=true
client.publish("/weather/#{city}", "#{current_temperature_k} ", false, 1)
while waiting_puback do
sleep(0.001)
end
end
### Call an explicit disconnect
client.disconnect