본문 바로가기
Programming/Hammerspoon

[HS] weather api 를 사용하여 메뉴바에 날씨정보 표시하기

by NAMP 2023. 2. 15.

weather api

weather api 를 사용하여 메뉴바에 날씨정보를 표시한다.

해당 API 를 사용하기 위해서는 `key` 발급이 필요하다.

local urlApi = 'http://api.weatherapi.com/v1/current.json?key=[YOUR_KEY]&q=Seoul&lang=ko'
local menubar = hs.menubar.new()
local menuData = {}

메뉴 갱신 함수

주기적으로 호출해서 날씨 정보에 따라 메뉴를 갱신한다.

local function updateMenubar()
  menubar:setTooltip("Weather Info")
  menubar:setMenu(menuData)
end

날씨 정보 얻기

위에서 정의한 urlApi 로 요청을 보내면 다음과 같은 응답을 받는다.

{
    "location": {
        "name": "Seoul",
        "region": "",
        "country": "South Korea",
        "lat": 37.57,
        "lon": 127.0,
        "tz_id": "Asia/Seoul",
        "localtime_epoch": 1676363080,
        "localtime": "2023-02-14 17:24"
    },
    "current": {
        "last_updated_epoch": 1676362500,
        "last_updated": "2023-02-14 17:15",
        "temp_c": 6.0,
        "temp_f": 42.8,
        "is_day": 1,
        "condition": {
            "text": "대체로 맑음",
            "icon": "//cdn.weatherapi.com/weather/64x64/day/116.png",
            "code": 1003
        },
        "wind_mph": 5.6,
        "wind_kph": 9.0,
        "wind_degree": 20,
        "wind_dir": "NNE",
        "pressure_mb": 1022.0,
        "pressure_in": 30.18,
        "precip_mm": 0.0,
        "precip_in": 0.0,
        "humidity": 36,
        "cloud": 50,
        "feelslike_c": 4.2,
        "feelslike_f": 39.5,
        "vis_km": 10.0,
        "vis_miles": 6.0,
        "uv": 3.0,
        "gust_mph": 6.3,
        "gust_kph": 10.1
    }
}

이 중에서 current.condition.icon 값을 이용하여 메뉴바에 아이콘을 그린다.

local function getWeather()
  hs.http.doAsyncRequest(urlApi, "GET", nil, nil, function(code, body, htable)
    if code ~= 200 then
      print('get weather error:' .. code)
      return
    end
    local rawjson = hs.json.decode(body)
    local current = rawjson.current

    local icon = hs.image.imageFromURL('http:' .. current.condition.icon)
    icon = icon:setSize({ h = 32, w = 32 })
    menubar:setIcon(icon)

    table.insert(menuData, { title = current.condition.text })

    local titlestr = string.format('🌡 %s℃', current.temp_c)
    table.insert(menuData, { title = titlestr })

    updateMenubar()
  end)
end

실행

getWeather()
hs.timer.doEvery(3600, getWeather)

한시간에 한번씩 정보를 갱신한다.

참고

댓글