summaryrefslogtreecommitdiff
path: root/weather.go
blob: 1ce93f2b045df6e2fe59a0bdeb6573b0854a2990 (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
// openweathermap API
package weather

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"strconv"
	"time"
)

const baseURL = `http://api.openweathermap.org/data/2.5/weather`

type Current struct {
	Coord      Coord
	Weather    []Weather
	Main       Main
	Wind       Wind
	Clouds     Clouds
	Rain       Rain
	Snow       Snow
	Visibility int
	DT         Timestamp // time of data calculation, unix, UTC
	Sys        Sys
	ID         int    // City ID
	Name       string // City Name
	Cod        int    `json:"-"` // bogus int/string
	Message    string
}

func (c Current) String() string {
	if c.Message != "" {
		return c.Message
	}
	s := fmt.Sprintf("%v: ", c.Name)
	for _, w := range c.Weather {
		s += fmt.Sprintf("%v, ", w)
	}
	s += fmt.Sprintf("%v, %v", c.Main, c.Wind)
	return s
}

type Coord struct {
	Lon float64 // longitude
	Lat float64 // latitude
}

func (c Coord) String() string {
	return fmt.Sprint(c.Lon, c.Lat)
}

type Cond int

type Weather struct {
	ID          Cond   `json:"id"` // Station ID
	Main        string // Group of weather parameters
	Description string // Weather condition within the group
	Icon        string // Weather con id
}

func (w Weather) String() string {
	return fmt.Sprint(w.ID)
}

type Main struct {
	Temp      float64 // Temperature, Default Kelvin, Metric: Celsius
	Pressure  int     // Atmospheric pressure, hPa
	Humidity  int     // Humidity, %
	TempMin   float64 `json:"temp_min"`   // min temp
	TempMax   float64 `json:"temp_max"`   // max temp
	SeaLevel  int     `json:"sea_level"`  // pressure on the sea level, hPa
	GrndLevel int     `json:"grnd_level"` // pressure on the ground level, hPa
}

func (m Main) String() string {
	return fmt.Sprintf("%v°C, pressure: %v hPa, humidity: %v%%",
		m.Temp, m.Pressure, m.Humidity)
}

type Wind struct {
	Speed float64 // Wind speed. Default meter/sec
	Deg   float64 // Wind direction, degrees (meteorogical)
	Gust  float64
}

func (w Wind) String() string {
	s := fmt.Sprintf("wind: %v° %v m/s", w.Deg, w.Speed)
	if w.Gust != 0 {
		s += fmt.Sprintf(" gust %v m/s", w.Gust)
	}
	return s
}

type Clouds struct {
	All int // Cloudness, %
}

func (c Clouds) String() string {
	return fmt.Sprintf("clouds: %v%%", c.All)
}

type Rain struct {
	Vol float64 `json:"3h"` // Rain volume for last 3 hours
}

func (r Rain) String() string {
	if r.Vol == 0 {
		return ""
	}
	return fmt.Sprintf("rain: %v mm/3h", r.Vol)
}

type Snow struct {
	Vol float64 `json:"3h"` // Snow volume for last 3 hours
}

func (s Snow) String() string {
	if s.Vol == 0 {
		return ""
	}
	return fmt.Sprintf("snow: %v mm/3h", s.Vol)
}

type Sys struct {
	Country string    // Country code
	Sunrise Timestamp // Sunrise time, unix, UTC
	Sunset  Timestamp // Sunset time, unix, UTC
}

func (s Sys) String() string {
	return fmt.Sprintf("country: %v sunrise: %v sunset: %v",
		s.Country, s.Sunrise, s.Sunset)
}

type Timestamp struct{ time.Time }

func (t *Timestamp) MarshalJSON() ([]byte, error) {
	ts := t.Unix()
	stamp := fmt.Sprint(ts)
	return []byte(stamp), nil
}

func (t *Timestamp) UnmarshalJSON(b []byte) error {
	ts, err := strconv.Atoi(string(b))
	if err != nil {
		return err
	}
	*t = Timestamp{time.Unix(int64(ts), 0)}
	return nil
}

func get(param string) (Current, error) {
	var c Current
	resp, err := http.Get(baseURL + "?units=metric" + param)
	if err != nil {
		return c, err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return c, err
	}
	err = json.Unmarshal(body, &c)
	return c, err
}

func ByCityName(name string) (Current, error) {
	return get(fmt.Sprintf("&q=%v", url.QueryEscape(name)))
}

func ByCityID(id int) (Current, error) {
	return get(fmt.Sprintf("&id=%v", id))
}

func ByGeoCoord(lon, lat float64) (Current, error) {
	return get(fmt.Sprintf("&lon=%v&lat=%v", lon, lat))
}

func ByZIPCode(zip int, country string) (Current, error) {
	return get(fmt.Sprintf("&zip=%v,%v", zip, country))
}

func (c Cond) String() string {
	if cc, ok := condCodes[c]; ok {
		return cc
	}
	return "unknown"
}

var condCodes = map[Cond]string{
	// Thunderstorm
	200: `thunderstorm with light rain`,
	201: `thunderstorm with rain`,
	202: `thunderstorm with heavy rain`,
	210: `light thunderstorm`,
	211: `thunderstorm`,
	212: `heavy thunderstorm`,
	221: `ragged thunderstorm`,
	230: `thunderstorm with light drizzle`,
	231: `thunderstorm with drizzle`,
	232: `thunderstorm with heavy drizzle`,

	// Drizzle
	300: `light intensity drizzle`,
	301: `drizzle`,
	302: `heavy intensity drizzle`,
	310: `light intensity drizzle rain`,
	311: `drizzle rain`,
	312: `heavy intensity drizzle rain`,
	313: `shower rain and drizzle`,
	314: `heavy shower rain and drizzle`,
	321: `shower drizzle`,

	// Rain
	500: `light rain`,
	501: `moderate rain`,
	502: `heavy intensity rain`,
	503: `very heavy rain`,
	504: `extreme rain`,
	511: `freezing rain`,
	520: `light intensity shower rain`,
	521: `shower rain`,
	522: `heavy intensity shower rain`,
	531: `ragged shower rain`,

	// Snow
	600: `light snow`,
	601: `snow`,
	602: `heavy snow`,
	611: `sleet`,
	612: `shower sleet`,
	615: `light rain and snow`,
	616: `rain and snow`,
	620: `light shower snow`,
	621: `shower snow`,
	622: `heavy shower snow`,

	// Atmosphere
	701: `mist`,
	711: `smoke`,
	721: `haze`,
	731: `sand, dust whirls`,
	741: `fog`,
	751: `sand`,
	761: `dust`,
	762: `volcanic ash`,
	771: `squalls`,
	781: `tornado`,

	// Clouds
	800: `clear sky`,
	801: `few clouds`,
	802: `scattered clouds`,
	803: `broken clouds`,
	804: `overcast clouds`,

	// Extreme
	900: `tornado`,
	901: `tropical storm`,
	902: `hurricane`,
	903: `cold`,
	904: `hot`,
	905: `windy`,
	906: `hail`,

	// Additional
	951: `calm`,
	952: `light breeze`,
	953: `gentle breeze`,
	954: `moderate breeze`,
	955: `fresh breeze`,
	956: `strong breeze`,
	957: `high wind, near gale`,
	958: `gale`,
	959: `severe gale`,
	960: `storm`,
	961: `violent storm`,
	962: `hurricane`,
}