-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweather.cpp
More file actions
80 lines (67 loc) · 1.85 KB
/
weather.cpp
File metadata and controls
80 lines (67 loc) · 1.85 KB
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
#include <iostream>
#include "weather.h"
#include "dataFetcher.h"
std::mutex Weather::wMutex_;
Weather::Weather(): t_{}, stop_(false)
{
t_ = std::thread{ &Weather::UpdateWeather, this };
}
Weather& Weather::getInstance() {
std::lock_guard<std::mutex> lock(Weather::wMutex_);
static Weather instance;
return instance;
}
WeatherInfo Weather::GetWeather()
{
return weatherInfo_;
}
void Weather::UpdateLocation(const std::string& areaName)
{
std::lock_guard lk(Weather::updateMtx_);
locationDetails_ = DataFetcher::GetLocationDetailsFromAreaName(areaName, provider_);
ready_ = true;
cv.notify_one();
}
bool Weather::CheckIfFetcherIsRunning() const
{
return isFetcherRunning_;
}
void Weather::SetConfig(uint32_t interval, const WeatherProvider& provider)
{
interval_ = interval;
provider_ = provider;
}
void Weather::UpdateWeather()
{
while (!stop_)
{
if (provider_.apiKey_.empty())
{
std::this_thread::sleep_for(std::chrono::seconds(1)); //wait for config to be set.
}
else if (locationDetails_.locationName_.empty())
{
std::this_thread::sleep_for(std::chrono::seconds(1)); //wait for location to be set.
}
else
{
std::unique_lock lk(updateMtx_);
cv.wait(lk, [&] {return ready_;});
// after the wait, we own the lock.
weatherInfo_ = DataFetcher::GetWeatherFromLatLng(locationDetails_, provider_);
isFetcherRunning_ = true;
lk.unlock();
cv.notify_one();
std::this_thread::sleep_for(std::chrono::minutes(interval_));
}
}
}
Weather::~Weather()
{
stop_ = true;
std::this_thread::sleep_for(std::chrono::minutes(interval_)); // wait for sync thread to stop neatly.
if (t_.joinable())
{
t_.join();
}
}