summaryrefslogtreecommitdiff
path: root/weather-widget/weather.lua
blob: e3fe118ebef6f076478fa01fee7f91a1191614c9 (plain)
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
-------------------------------------------------
-- Weather Widget based on the OpenWeatherMap
-- https://openweathermap.org/
--
-- @author Pavel Makhov
-- @copyright 2020 Pavel Makhov
-------------------------------------------------
local awful = require("awful")
local watch = require("awful.widget.watch")
local json = require("json")
local naughty = require("naughty")
local wibox = require("wibox")
local gears = require("gears")
local beautiful = require("beautiful")

local HOME_DIR = os.getenv("HOME")
local WIDGET_DIR = HOME_DIR .. '/.config/awesome/awesome-wm-widgets/weather-widget'
local GET_FORECAST_CMD = [[bash -c "curl -s --show-error -X GET '%s'"]]

local function show_warning(message)
    naughty.notify {
        preset = naughty.config.presets.critical,
        title = 'Weather Widget',
        text = message
    }
end

local weather_widget = {}
local warning_shown = false
local notification
local tooltip = awful.tooltip {
    mode = 'outside',
    preferred_positions = {'bottom'}
}

local weather_popup = awful.popup {
    ontop = true,
    visible = false,
    shape = gears.shape.rounded_rect,
    border_width = 1,
    border_color = beautiful.bg_focus,
    maximum_width = 400,
    offset = {y = 5},
    widget = {}
}

--- Maps openWeatherMap icon name to file name w/o extension
local icon_map = {
    ["01d"] = "clear-sky",
    ["02d"] = "few-clouds",
    ["03d"] = "scattered-clouds",
    ["04d"] = "broken-clouds",
    ["09d"] = "shower-rain",
    ["10d"] = "rain",
    ["11d"] = "thunderstorm",
    ["13d"] = "snow",
    ["50d"] = "mist",
    ["01n"] = "clear-sky-night",
    ["02n"] = "few-clouds-night",
    ["03n"] = "scattered-clouds-night",
    ["04n"] = "broken-clouds-night",
    ["09n"] = "shower-rain-night",
    ["10n"] = "rain-night",
    ["11n"] = "thunderstorm-night",
    ["13n"] = "snow-night",
    ["50n"] = "mist-night"
}

--- Return wind direction as a string
local function to_direction(degrees)
    -- Ref: https://www.campbellsci.eu/blog/convert-wind-directions
    if degrees == nil then return "Unknown dir" end
    local directions = {
        "N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW",
        "WSW", "W", "WNW", "NW", "NNW", "N"
    }
    return directions[math.floor((degrees % 360) / 22.5) + 1]
end

--- Convert degrees Celsius to Fahrenheit
local function celsius_to_fahrenheit(c) return c * 9 / 5 + 32 end

-- Convert degrees Fahrenheit to Celsius
local function fahrenheit_to_celsius(f) return (f - 32) * 5 / 9 end

local function gen_temperature_str(temp, fmt_str, show_other_units, units)
    local temp_str = string.format(fmt_str, temp)
    local s = temp_str .. '°' .. (units == 'metric' and 'C' or 'F')

    if (show_other_units) then
        local temp_conv, units_conv
        if (units == 'metric') then
            temp_conv = celsius_to_fahrenheit(temp)
            units_conv = 'F'
        else
            temp_conv = fahrenheit_to_celsius(temp)
            units_conv = 'C'
        end

        local temp_conv_str = string.format(fmt_str, temp_conv)
        s = s .. ' ' .. '(' .. temp_conv_str .. '°' .. units_conv .. ')'
    end
    return s
end

local function uvi_index_color(uvi)
    local color
    if uvi >= 0 and uvi < 3 then color = '#A3BE8C'
    elseif uvi >= 3 and uvi < 6 then color = '#EBCB8B'
    elseif uvi >= 6 and uvi < 8 then color = '#D08770'
    elseif uvi >= 8 and uvi < 11 then color = '#BF616A'
    elseif uvi >= 11 then color = '#B48EAD'
    end

    return '<span weight="bold" foreground="' .. color .. '">' .. uvi .. '</span>'
end

local function worker(args)

    local args = args or {}

    --- Validate required parameters
    if args.coordinates == nil or args.api_key == nil then
        show_warning('Required parameters are not set: ' ..
                         (args.coordinates == nil and '<b>coordinates</b>' or '') ..
                         (args.api_key == nil and ', <b>api_key</b> ' or ''))
        return
    end

    local coordinates = args.coordinates
    local api_key = args.api_key
    local font_name = args.font_name or beautiful.font:gsub("%s%d+$", "")
    local units = args.units or 'metric'
    local time_format_12h = args.time_format_12h
    local both_units_widget = args.both_units_widget or false
    local show_hourly_forecast = args.show_hourly_forecast
    local show_daily_forecast = args.show_daily_forecast
    local icon_pack_name = args.icons or 'weather-underground-icons'
    local icons_extension = args.icons_extension or '.png'

    local owm_one_cal_api =
        ('https://api.openweathermap.org/data/2.5/onecall' .. 
            '?lat=' .. coordinates[1] .. '&lon=' .. coordinates[2] .. '&appid=' .. api_key ..
            '&units=' .. units .. '&exclude=minutely' ..
            (show_hourly_forecast == false and ',hourly' or '') ..
            (show_daily_forecast == false and ',daily' or ''))

    weather_widget = wibox.widget {
        {
            {
                id = 'icon',
                resize = true,
                widget = wibox.widget.imagebox
            },
            valign = 'center',
            widget = wibox.container.place,
        },
        {
            id = 'txt',
            widget = wibox.widget.textbox
        },
        layout = wibox.layout.fixed.horizontal,
        set_image = function(self, path)
            self:get_children_by_id('icon')[1].image = path
        end,
        set_text = function(self, text)
            self:get_children_by_id('txt')[1].text = text
        end,
        is_ok = function(self, is_ok)
            if is_ok then
                self:get_children_by_id('icon')[1]:set_opacity(1)
                self:get_children_by_id('icon')[1]:emit_signal('widget:redraw_needed')
            else
                self:get_children_by_id('icon')[1]:set_opacity(0.2)
                self:get_children_by_id('icon')[1]:emit_signal('widget:redraw_needed')
            end
        end
    }

    local current_weather_widget = wibox.widget {
        {
            {
                {
                    id = 'icon',
                    resize = true,
                    forced_width = 128,
                    forced_height = 128,
                    widget = wibox.widget.imagebox
                },
                align = 'center',
                widget = wibox.container.place
            },
            {
                id = 'description',
                font = font_name .. ' 10',
                align = 'center',
                widget = wibox.widget.textbox
            },
            forced_width = 128,
            layout = wibox.layout.align.vertical
        },
        {
            {
                {
                    id = 'temp',
                    font = font_name .. ' 48',
                    widget = wibox.widget.textbox
                },
                {
                    id = 'feels_like_temp',
                    align = 'center',
                    font = font_name .. ' 9',
                    widget = wibox.widget.textbox
                },
                layout = wibox.layout.fixed.vertical
            },
            {
                {
                    id = 'wind',
                    font = font_name .. ' 9',
                    widget = wibox.widget.textbox
                },
                {
                    id = 'humidity',
                    font = font_name .. ' 9',
                    widget = wibox.widget.textbox
                },
                {
                    id = 'uv',
                    font = font_name .. ' 9',
                    widget = wibox.widget.textbox
                },
                expand = 'inside',
                layout = wibox.layout.align.vertical
            },
            spacing = 16,
            forced_width = 150,
            layout = wibox.layout.fixed.vertical
        },
        forced_width = 300,
        layout = wibox.layout.flex.horizontal,
        update = function(self, weather)
            self:get_children_by_id('icon')[1]:set_image(WIDGET_DIR .. '/icons/' .. icon_pack_name .. '/' .. icon_map[weather.weather[1].icon] .. icons_extension)
            self:get_children_by_id('temp')[1]:set_text(gen_temperature_str(weather.temp, '%.0f', false, units))
            self:get_children_by_id('feels_like_temp')[1]:set_text('Feels like ' .. gen_temperature_str(weather.feels_like, '%.0f', false, units))
            self:get_children_by_id('description')[1]:set_text(weather.weather[1].description)
            self:get_children_by_id('wind')[1]:set_markup('Wind: <b>' .. weather.wind_speed .. 'm/s (' .. to_direction(weather.wind_deg) .. ')</b>')
            self:get_children_by_id('humidity')[1]:set_markup('Humidity: <b>' .. weather.humidity .. '%</b>')
            self:get_children_by_id('uv')[1]:set_markup('UV: ' .. uvi_index_color(weather.uvi))
        end
    }


    local daily_forecast_widget = {
        forced_width = 300,
        layout = wibox.layout.flex.horizontal,
        update = function(self, forecast, timezone_offset)
            local count = #self
            for i = 0, count do self[i]=nil end
            for i, day in ipairs(forecast) do
                if i > 5 then break end
                local day_forecast = wibox.widget {
                    {
                        text = os.date('%a', tonumber(day.dt) + tonumber(timezone_offset)),
                        align = 'center',
                        font = font_name .. ' 9',
                        widget = wibox.widget.textbox
                    },
                    {
                        {
                            {
                                image = WIDGET_DIR .. '/icons/' .. icon_pack_name .. '/' .. icon_map[day.weather[1].icon] .. icons_extension,
                                resize = true,
                                forced_width = 48,
                                forced_height = 48,
                                widget = wibox.widget.imagebox
                            },
                            align = 'center',
                            layout = wibox.container.place
                        },
                        {
                            text = day.weather[1].description,
                            font = font_name .. ' 8',
                            align = 'center',
                            forced_height = 50,
                            widget = wibox.widget.textbox
                        },
                        layout = wibox.layout.fixed.vertical
                    },
                    {
                        {
                            text = gen_temperature_str(day.temp.day, '%.0f', false, units),
                            align = 'center',
                            font = font_name .. ' 9',
                            widget = wibox.widget.textbox
                        },
                        {
                            text = gen_temperature_str(day.temp.night, '%.0f', false, units),
                            align = 'center',
                            font = font_name .. ' 9',
                            widget = wibox.widget.textbox
                        },
                        layout = wibox.layout.fixed.vertical
                    },
                    spacing = 8,
                    layout = wibox.layout.fixed.vertical
                }
                table.insert(self, day_forecast)
            end
        end
    }

    local hourly_forecast_graph = wibox.widget {
        step_width = 12,
        color = '#EBCB8B',
        background_color = beautiful.bg_normal,
        forced_height = 100,
        forced_width = 300,
        widget = wibox.widget.graph,
        set_max_value = function(self, new_max_value)
            self.max_value = new_max_value
        end,
        set_min_value = function(self, new_min_value)
            self.min_value = new_min_value
        end
    }

    local hourly_forecast_widget = {
        layout = wibox.layout.fixed.vertical,
        update = function(self, hourly)
            local hours_below = {
                id = 'hours',
                layout = wibox.layout.flex.horizontal
            }
            local temp_below = {
                id = 'temp',
                forced_width = 300,
                layout = wibox.layout.flex.horizontal
            }

            local max_temp = -1000
            local min_temp = 1000
            local values = {}
            for i, hour in ipairs(hourly) do
                if i > 25 then break end
                values[i] = hour.temp
                if max_temp < hour.temp then max_temp = hour.temp end
                if min_temp > hour.temp then min_temp = hour.temp end
                if (i - 1) % 5 == 0 then
                    table.insert(hours_below, wibox.widget {
                        text = os.date(time_format_12h and '%I%p' or '%H:00', tonumber(hour.dt)),
                        align = 'center',
                        font = font_name .. ' 9',
                        widget = wibox.widget.textbox
                    })
                    table.insert(temp_below, wibox.widget {
                        markup = '<span foreground="#2E3440">' .. string.format('%.0f', hour.temp) .. '°' .. '</span>',
                        align = 'center',
                        font = font_name .. ' 9',
                        widget = wibox.widget.textbox
                    })
                end
            end
            hourly_forecast_graph:set_max_value(max_temp)
            hourly_forecast_graph:set_min_value(min_temp * 0.7) -- move graph a bit up
            for i, value in ipairs(values) do
                hourly_forecast_graph:add_value(value)
            end

            local count = #self
            for i = 0, count do self[i]=nil end


            table.insert(self, temp_below)
            table.insert(self, wibox.widget{
                {
                    hourly_forecast_graph,
                    reflection = {horizontal = true},
                    widget = wibox.container.mirror
                },
                {
                    temp_below,
                    valign = 'bottom',
                    widget = wibox.container.place
                },
                id = 'graph',
                layout = wibox.layout.stack
            })
            table.insert(self, hours_below)
        end
    }

    local function update_widget(widget, stdout, stderr)
        if stderr ~= '' then
            if not warning_shown then
                if stderr ~= 'curl: (52) Empty reply from server' then
                    show_warning(stderr)
                end
                warning_shown = true
                widget:is_ok(false)
                tooltip:add_to_object(widget)

                widget:connect_signal('mouse::enter', function() tooltip.text = stderr end)
            end
            return
        end

        warning_shown = false
        tooltip:remove_from_object(widget)
        widget:is_ok(true)

        local result = json.decode(stdout)

        widget:set_image(WIDGET_DIR .. '/icons/' .. icon_pack_name .. '/' .. icon_map[result.current.weather[1].icon] .. icons_extension)
        widget:set_text(gen_temperature_str(result.current.temp, '%.0f', both_units_widget, units))

        current_weather_widget:update(result.current)

        local final_widget = {
            current_weather_widget,
            spacing = 16,
            layout = wibox.layout.fixed.vertical
        }

        if show_hourly_forecast then
            hourly_forecast_widget:update(result.hourly)
            table.insert(final_widget, hourly_forecast_widget)
        end

        if show_daily_forecast then
            daily_forecast_widget:update(result.daily, result.timezone_offset)
            table.insert(final_widget, daily_forecast_widget)
        end

        weather_popup:setup({
            {
                final_widget,
                margins = 10,
                widget = wibox.container.margin
            },
            bg = beautiful.bg_normal,
            widget = wibox.container.background
        })
    end

    weather_widget:buttons(awful.util.table.join(awful.button({}, 1, function()
            if weather_popup.visible then
                weather_popup.visible = not weather_popup.visible
            else
                weather_popup:move_next_to(mouse.current_widget_geometry)
            end
        end)))

    watch(
        string.format(GET_FORECAST_CMD, owm_one_cal_api),
        120,  -- API limit is 1k req/day; day has 1440 min; every 2 min is good
        update_widget, weather_widget
    )

    return weather_widget
end

return setmetatable(weather_widget, {__call = function(_, ...) return worker(...) end})