-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathOpenMeteoClient.cs
568 lines (489 loc) · 20.8 KB
/
OpenMeteoClient.cs
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Text.Json;
using System.Globalization;
namespace OpenMeteo
{
/// <summary>
/// Handles GET Requests and performs API Calls.
/// </summary>
public class OpenMeteoClient
{
private readonly string _weatherApiUrl = "https://api.open-meteo.com/v1/forecast";
private readonly string _geocodeApiUrl = "https://geocoding-api.open-meteo.com/v1/search";
private readonly string _airQualityApiUrl = "https://air-quality-api.open-meteo.com/v1/air-quality";
private readonly HttpController httpController;
/// <summary>
/// Creates a new <seealso cref="OpenMeteoClient"/> object and sets the neccessary variables (httpController, CultureInfo)
/// </summary>
public OpenMeteoClient()
{
httpController = new HttpController();
}
/// <summary>
/// Performs two GET-Requests (first geocoding api for latitude,longitude, then weather forecast)
/// </summary>
/// <param name="location">Name of city</param>
/// <returns>If successful returns an awaitable Task containing WeatherForecast or NULL if request failed</returns>
public async Task<WeatherForecast?> QueryAsync(string location)
{
GeocodingOptions geocodingOptions = new GeocodingOptions(location);
// Get location Information
GeocodingApiResponse? response = await GetGeocodingDataAsync(geocodingOptions);
if (response == null || response.Locations == null)
return null;
WeatherForecastOptions options = new WeatherForecastOptions
{
Latitude = response.Locations[0].Latitude,
Longitude = response.Locations[0].Longitude,
Current = CurrentOptions.All // Get all current weather data if nothing else is provided
};
return await GetWeatherForecastAsync(options);
}
/// <summary>
/// Performs two GET-Requests (first geocoding api for latitude,longitude, then weather forecast)
/// </summary>
/// <param name="options">Geocoding options</param>
/// <returns>If successful awaitable <see cref="Task"/> or NULL</returns>
public async Task<WeatherForecast?> QueryAsync(GeocodingOptions options)
{
// Get City Information
GeocodingApiResponse? response = await GetLocationDataAsync(options);
if (response == null || response?.Locations == null)
return null;
WeatherForecastOptions weatherForecastOptions = new WeatherForecastOptions
{
Latitude = response.Locations[0].Latitude,
Longitude = response.Locations[0].Longitude,
Current = CurrentOptions.All // Get all current weather data if nothing else is provided
};
return await GetWeatherForecastAsync(weatherForecastOptions);
}
/// <summary>
/// Performs one GET-Request
/// </summary>
/// <param name="options"></param>
/// <returns>Awaitable Task containing WeatherForecast or NULL</returns>
public async Task<WeatherForecast?> QueryAsync(WeatherForecastOptions options)
{
try
{
return await GetWeatherForecastAsync(options);
}
catch (Exception)
{
return null;
}
}
/// <summary>
/// Performs one GET-Request to get weather information
/// </summary>
/// <param name="latitude">City latitude</param>
/// <param name="longitude">City longitude</param>
/// <returns>Awaitable Task containing WeatherForecast or NULL</returns>
public async Task<WeatherForecast?> QueryAsync(float latitude, float longitude)
{
WeatherForecastOptions options = new WeatherForecastOptions
{
Latitude = latitude,
Longitude = longitude,
};
return await QueryAsync(options);
}
/// <summary>
/// Gets Weather Forecast for a given location with individual options
/// </summary>
/// <param name="location"></param>
/// <param name="options"></param>
/// <returns><see cref="WeatherForecast"/> for the FIRST found result for <paramref name="location"/></returns>
public async Task<WeatherForecast?> QueryAsync(string location, WeatherForecastOptions options)
{
GeocodingApiResponse? geocodingApiResponse = await GetLocationDataAsync(location);
if (geocodingApiResponse == null || geocodingApiResponse?.Locations == null)
return null;
options.Longitude = geocodingApiResponse.Locations[0].Longitude;
options.Latitude = geocodingApiResponse.Locations[0].Latitude;
return await GetWeatherForecastAsync(options);
}
/// <summary>
/// Gets air quality data for a given location with individual options
/// </summary>
/// <param name="options">options for air quality request</param>
/// <returns><see cref="AirQuality"/> if successfull or <see cref="null"/> if failed</returns>
public async Task<AirQuality?> QueryAsync(AirQualityOptions options)
{
return await GetAirQualityAsync(options);
}
/// <summary>
/// Performs one GET-Request to Open-Meteo Geocoding API
/// </summary>
/// <param name="location">Name of a location or city</param>
/// <returns></returns>
public async Task<GeocodingApiResponse?> GetLocationDataAsync(string location)
{
GeocodingOptions geocodingOptions = new GeocodingOptions(location);
return await GetLocationDataAsync(geocodingOptions);
}
public async Task<GeocodingApiResponse?> GetLocationDataAsync(GeocodingOptions options)
{
return await GetGeocodingDataAsync(options);
}
/// <summary>
/// Performs one GET-Request to get a (float, float) tuple
/// </summary>
/// <param name="location">Name of a city or location</param>
/// <returns>(latitude, longitude) tuple of first found location or null if no location was found</returns>
public async Task<(float latitude, float longitude)?> GetLocationLatitudeLongitudeAsync(string location)
{
GeocodingApiResponse? response = await GetLocationDataAsync(location);
if (response == null || response?.Locations == null)
return null;
return (response.Locations[0].Latitude, response.Locations[0].Longitude);
}
public WeatherForecast? Query(WeatherForecastOptions options)
{
return QueryAsync(options).GetAwaiter().GetResult();
}
public WeatherForecast? Query(float latitude, float longitude)
{
return QueryAsync(latitude, longitude).GetAwaiter().GetResult();
}
public WeatherForecast? Query(string location, WeatherForecastOptions options)
{
return QueryAsync(location, options).GetAwaiter().GetResult();
}
public WeatherForecast? Query(GeocodingOptions options)
{
return QueryAsync(options).GetAwaiter().GetResult();
}
public WeatherForecast? Query(string location)
{
return QueryAsync(location).GetAwaiter().GetResult();
}
public AirQuality? Query(AirQualityOptions options)
{
return QueryAsync(options).GetAwaiter().GetResult();
}
private async Task<AirQuality?> GetAirQualityAsync(AirQualityOptions options)
{
try
{
HttpResponseMessage response = await httpController.Client.GetAsync(MergeUrlWithOptions(_airQualityApiUrl, options));
response.EnsureSuccessStatusCode();
AirQuality? airQuality = await JsonSerializer.DeserializeAsync<AirQuality>(await response.Content.ReadAsStreamAsync(), new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
return airQuality;
}
catch (HttpRequestException e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
return null;
}
}
/// <summary>
/// Converts a given weathercode to it's string representation
/// </summary>
/// <param name="weathercode"></param>
/// <returns><see cref="string"/> Weathercode string representation</returns>
public string WeathercodeToString(int weathercode)
{
switch (weathercode)
{
case 0:
return "Clear sky";
case 1:
return "Mainly clear";
case 2:
return "Partly cloudy";
case 3:
return "Overcast";
case 45:
return "Fog";
case 48:
return "Depositing rime Fog";
case 51:
return "Light drizzle";
case 53:
return "Moderate drizzle";
case 55:
return "Dense drizzle";
case 56:
return "Light freezing drizzle";
case 57:
return "Dense freezing drizzle";
case 61:
return "Slight rain";
case 63:
return "Moderate rain";
case 65:
return "Heavy rain";
case 66:
return "Light freezing rain";
case 67:
return "Heavy freezing rain";
case 71:
return "Slight snow fall";
case 73:
return "Moderate snow fall";
case 75:
return "Heavy snow fall";
case 77:
return "Snow grains";
case 80:
return "Slight rain showers";
case 81:
return "Moderate rain showers";
case 82:
return "Violent rain showers";
case 85:
return "Slight snow showers";
case 86:
return "Heavy snow showers";
case 95:
return "Thunderstorm";
case 96:
return "Thunderstorm with light hail";
case 99:
return "Thunderstorm with heavy hail";
default:
return "Invalid weathercode";
}
}
private async Task<WeatherForecast?> GetWeatherForecastAsync(WeatherForecastOptions options)
{
try
{
HttpResponseMessage response = await httpController.Client.GetAsync(MergeUrlWithOptions(_weatherApiUrl, options));
response.EnsureSuccessStatusCode();
WeatherForecast? weatherForecast = await JsonSerializer.DeserializeAsync<WeatherForecast>(await response.Content.ReadAsStreamAsync(), new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
return weatherForecast;
}
catch (HttpRequestException e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
return null;
}
}
private async Task<GeocodingApiResponse?> GetGeocodingDataAsync(GeocodingOptions options)
{
try
{
HttpResponseMessage response = await httpController.Client.GetAsync(MergeUrlWithOptions(_geocodeApiUrl, options));
response.EnsureSuccessStatusCode();
GeocodingApiResponse? geocodingData = await JsonSerializer.DeserializeAsync<GeocodingApiResponse>(await response.Content.ReadAsStreamAsync(), new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
return geocodingData;
}
catch (HttpRequestException e)
{
Console.WriteLine("Can't find " + options.Name + ". Please make sure that the name is valid.");
Console.WriteLine(e.Message);
return null;
}
}
private string MergeUrlWithOptions(string url, WeatherForecastOptions? options)
{
if (options == null) return url;
UriBuilder uri = new UriBuilder(url);
bool isFirstParam = false;
// If no query given, add '?' to start the query string
if (uri.Query == string.Empty)
{
uri.Query = "?";
// isFirstParam becomes true because the query string is new
isFirstParam = true;
}
// Add the properties
// Begin with Latitude and Longitude since they're required
if (isFirstParam)
uri.Query += "latitude=" + options.Latitude.ToString(CultureInfo.InvariantCulture);
else
uri.Query += "&latitude=" + options.Latitude.ToString(CultureInfo.InvariantCulture);
uri.Query += "&longitude=" + options.Longitude.ToString(CultureInfo.InvariantCulture);
uri.Query += "&temperature_unit=" + options.Temperature_Unit.ToString();
uri.Query += "&windspeed_unit=" + options.Windspeed_Unit.ToString();
uri.Query += "&precipitation_unit=" + options.Precipitation_Unit.ToString();
if (options.Timezone != string.Empty)
uri.Query += "&timezone=" + options.Timezone;
uri.Query += "&timeformat=" + options.Timeformat.ToString();
uri.Query += "&past_days=" + options.Past_Days;
if (options.Start_date != string.Empty)
uri.Query += "&start_date=" + options.Start_date;
if (options.End_date != string.Empty)
uri.Query += "&end_date=" + options.End_date;
// Now we iterate through hourly and daily
// Hourly
if (options.Hourly.Count > 0)
{
bool firstHourlyElement = true;
uri.Query += "&hourly=";
foreach (var option in options.Hourly)
{
if (firstHourlyElement)
{
uri.Query += option.ToString();
firstHourlyElement = false;
}
else
{
uri.Query += "," + option.ToString();
}
}
}
// Daily
if (options.Daily.Count > 0)
{
bool firstDailyElement = true;
uri.Query += "&daily=";
foreach (var option in options.Daily)
{
if (firstDailyElement)
{
uri.Query += option.ToString();
firstDailyElement = false;
}
else
{
uri.Query += "," + option.ToString();
}
}
}
// 0.2.0 Weather models
// cell_selection
uri.Query += "&cell_selection=" + options.Cell_Selection;
// Models
if (options.Models.Count > 0)
{
bool firstModelsElement = true;
uri.Query += "&models=";
foreach (var option in options.Models)
{
if (firstModelsElement)
{
uri.Query += option.ToString();
firstModelsElement = false;
}
else
{
uri.Query += "," + option.ToString();
}
}
}
// new current parameter
if (options.Current.Count > 0)
{
bool firstCurrentElement = true;
uri.Query += "¤t=";
foreach (var option in options.Current)
{
if (firstCurrentElement)
{
uri.Query += option.ToString();
firstCurrentElement = false;
}
else
{
uri.Query += "," + option.ToString();
}
}
}
// new minutely_15 parameter
if (options.Minutely15.Count > 0)
{
bool firstMinutelyElement = true;
uri.Query += "&minutely_15=";
foreach (var option in options.Minutely15)
{
if (firstMinutelyElement)
{
uri.Query += option.ToString();
firstMinutelyElement = false;
}
else
{
uri.Query += "," + option.ToString();
}
}
}
return uri.ToString();
}
/// <summary>
/// Combines a given url with an options object to create a url for GET requests
/// </summary>
/// <returns>url+queryString</returns>
private string MergeUrlWithOptions(string url, GeocodingOptions options)
{
if (options == null) return url;
UriBuilder uri = new UriBuilder(url);
bool isFirstParam = false;
// If no query given, add '?' to start the query string
if (uri.Query == string.Empty)
{
uri.Query = "?";
// isFirstParam becomes true because the query string is new
isFirstParam = true;
}
// Now we check every property and set the value, if neccessary
if (isFirstParam)
uri.Query += "name=" + options.Name;
else
uri.Query += "&name=" + options.Name;
if(options.Count >0)
uri.Query += "&count=" + options.Count;
if (options.Format != string.Empty)
uri.Query += "&format=" + options.Format;
if (options.Language != string.Empty)
uri.Query += "&language=" + options.Language;
return uri.ToString();
}
/// <summary>
/// Combines a given url with an options object to create a url for GET requests
/// </summary>
/// <returns>url+queryString</returns>
private string MergeUrlWithOptions(string url, AirQualityOptions options)
{
if (options == null) return url;
UriBuilder uri = new UriBuilder(url);
bool isFirstParam = false;
// If no query given, add '?' to start the query string
if (uri.Query == string.Empty)
{
uri.Query = "?";
// isFirstParam becomes true because the query string is new
isFirstParam = true;
}
// Now we check every property and set the value, if neccessary
if (isFirstParam)
uri.Query += "latitude=" + options.Latitude.ToString(CultureInfo.InvariantCulture);
else
uri.Query += "&latitude=" + options.Latitude.ToString(CultureInfo.InvariantCulture);
uri.Query += "&longitude=" + options.Longitude.ToString(CultureInfo.InvariantCulture);
if (options.Domains != string.Empty)
uri.Query += "&domains=" + options.Domains;
if (options.Timeformat != string.Empty)
uri.Query += "&timeformat=" + options.Timeformat;
if (options.Timezone != string.Empty)
uri.Query += "&timezone=" + options.Timezone;
// Finally add hourly array
if (options.Hourly.Count >= 0)
{
bool firstHourlyElement = true;
uri.Query += "&hourly=";
foreach (var option in options.Hourly)
{
if (firstHourlyElement)
{
uri.Query += option.ToString();
firstHourlyElement = false;
}
else
{
uri.Query += "," + option.ToString();
}
}
}
return uri.ToString();
}
}
}