]> git.madduck.net Git - etc/awesome.git/blob - widgets/weather.lua

madduck's git repository

Every one of the projects in this repository is available at the canonical URL git://git.madduck.net/madduck/pub/<projectpath> — see each project's metadata for the exact URL.

All patches and comments are welcome. Please squash your changes to logical commits before using git-format-patch and git-send-email to patches@git.madduck.net. If you'd read over the Git project's submission guidelines and adhered to them, I'd be especially grateful.

SSH access, as well as push access can be individually arranged.

If you use my repositories frequently, consider adding the following snippet to ~/.gitconfig and using the third clone URL listed for each project:

[url "git://git.madduck.net/madduck/"]
  insteadOf = madduck:

84c1564ee49c585c1d3f05d1a52ca62837737c0c
[etc/awesome.git] / widgets / weather.lua
1
2 --[[
3                                                   
4      Licensed under GNU General Public License v2 
5       * (c) 2015, Luke Bonham                     
6                                                   
7 --]]
8
9 local newtimer     = require("lain.helpers").newtimer
10 local read_pipe    = require("lain.helpers").read_pipe
11
12 local async        = require("lain.asyncshell")
13 local json         = require("lain.util").dkjson
14 local lain_icons   = require("lain.helpers").icons_dir
15
16 local naughty      = require("naughty")
17 local wibox        = require("wibox")
18
19 local math         = { floor  = math.floor }
20 local mouse        = mouse
21 local os           = { time   = os.time }
22 local string       = { format = string.format,
23                        gsub   = string.gsub }
24
25 local tonumber     = tonumber
26 local setmetatable = setmetatable
27
28 -- OpenWeatherMap
29 -- current weather and X-days forecast
30 -- lain.widgets.weather
31
32 local function worker(args)
33     local weather               = {}
34     local args                  = args or {}
35     local APPID                 = args.APPID or "3e321f9414eaedbfab34983bda77a66e" -- lain default
36     local timeout               = args.timeout or 900   -- 15 min
37     local timeout_forecast      = args.timeout or 86400 -- 24 hrs
38     local current_call          = args.current_call  or "curl -s 'http://api.openweathermap.org/data/2.5/weather?id=%s&units=%s&lang=%s&APPID=%s'"
39     local forecast_call         = args.forecast_call or "curl -s 'http://api.openweathermap.org/data/2.5/forecast/daily?id=%s&units=%s&lang=%s&cnt=%s&APPID=%s'"
40     local city_id               = args.city_id or 0 -- placeholder
41     local utc                   = args.utc or 0
42
43     local units                 = args.units or "metric"
44     local lang                  = args.lang or "en"
45     local cnt                   = args.cnt or 5
46     local date_cmd              = args.date_cmd or "date -u -d @%d +'%%a %%d'"
47     local icons_path            = args.icons_path or lain_icons .. "openweathermap/"
48     local notification_preset   = args.notification_preset or {}
49     local notification_text_fun = args.notification_text_fun or
50                                   function (wn)
51                                       local day = string.gsub(read_pipe(string.format(date_cmd, wn["dt"])), "\n", "")
52                                       local tmin = math.floor(wn["temp"]["min"])
53                                       local tmax = math.floor(wn["temp"]["max"])
54                                       local desc = wn["weather"][1]["description"]
55
56                                       return string.format("<b>%s</b>: %s, %d - %d ", day, desc, tmin, tmax)
57                                   end
58     local weather_na_markup     = args.weather_na_markup or " N/A "
59     local followmouse           = args.followmouse or false
60     local settings              = args.settings or function() end
61
62     weather.widget    = wibox.widget.textbox(weather_na_markup)
63     weather.icon_path = icons_path .. "na.png"
64     weather.icon      = wibox.widget.imagebox(weather.icon_path)
65
66     function weather.show(t_out)
67         weather.hide()
68
69         if followmouse then
70             notification_preset.screen = mouse.screen
71         end
72
73         if not weather.notification_text then
74             weather.forecast_update()
75         end
76
77
78         weather.notification = naughty.notify({
79             text    = weather.notification_text,
80             icon    = weather.icon_path,
81             timeout = t_out,
82             preset  = notification_preset
83         })
84     end
85
86     function weather.hide()
87         if weather.notification then
88             naughty.destroy(weather.notification)
89             weather.notification = nil
90         end
91     end
92
93     function weather.attach(obj)
94         obj:connect_signal("mouse::enter", function()
95             weather.show(0)
96         end)
97         obj:connect_signal("mouse::leave", function()
98             weather.hide()
99         end)
100     end
101
102     function weather.forecast_update()
103         local cmd = string.format(forecast_call, city_id, units, lang, cnt, APPID)
104         async.request(cmd, function(f)
105             local pos, err
106             weather_now, pos, err = json.decode(f, 1, nil)
107
108             if not err and weather_now and tonumber(weather_now["cod"]) == 200 then
109                 weather.notification_text = ''
110                 for i = 1, weather_now["cnt"] do
111                     weather.notification_text = weather.notification_text ..
112                                                 notification_text_fun(weather_now["list"][i])
113
114                     if i < weather_now["cnt"] then
115                         weather.notification_text = weather.notification_text .. "\n"
116                     end
117                 end
118             end
119         end)
120     end
121
122     function weather.update()
123         local cmd = string.format(current_call, city_id, units, lang, APPID)
124         local utc_midnight_cmd   = ("date -u -d 'today 00:00:00' +'%%s'")
125
126         async.request(cmd, function(f)
127             local pos, err, icon
128             weather_now, pos, err = json.decode(f, 1, nil)
129
130             if not err and weather_now and tonumber(weather_now["cod"]) == 200 then
131                 -- weather icon based on localtime
132
133                 now     = os.time()
134                 utc_midnight   = string.gsub(read_pipe(string.format(utc_midnight_cmd)), "\n", "")
135
136                 if utc > 0 then
137                     if (now  - (utc * 3600)) >= tonumber(utc_midnight) then 
138                        now = now - 86400
139                     end
140                 else
141                     if (now  - (utc * 3600)) <= tonumber(utc_midnight) then 
142                        now = now + 86400
143                     end
144                 end
145                 sunrise = tonumber(weather_now["sys"]["sunrise"])
146                 sunset  = tonumber(weather_now["sys"]["sunset"])
147                 icon    = weather_now["weather"][1]["icon"]
148
149                 if sunrise <= now and now <= sunset then
150                     icon = string.gsub(icon, "n", "d")
151                 else
152                     icon = string.gsub(icon, "d", "n")
153                 end
154
155                 weather.icon_path = icons_path .. icon .. ".png"
156
157                 widget = weather.widget
158                 settings()
159             else
160                 weather.icon_path = icons_path .. "na.png"
161                 weather.widget:set_markup(weather_na_markup)
162             end
163
164             weather.icon:set_image(weather.icon_path)
165         end)
166     end
167
168     weather.attach(weather.widget)
169
170     newtimer("weather-" .. city_id, timeout, weather.update)
171     newtimer("weather_forecast-" .. city_id, timeout, weather.forecast_update)
172
173     return setmetatable(weather, { __index = weather.widget })
174 end
175
176 return setmetatable({}, { __call = function(_, ...) return worker(...) end })