22// Created by sajith on 3/25/21.
33//
44
5+ #include < iostream>
6+ #include < random>
7+ #include < thread>
8+
9+ #include " sensors/SunlightSensor.h"
10+
11+ namespace sensors
12+ {
13+ SunlightSensor::SunlightSensor (const std::chrono::seconds sleepTime, std::mutex &mtx) : sleepTime{sleepTime},
14+ mtx{mtx} {}
15+
16+ void SunlightSensor::subcribe (caretaker::PlantCareTaker &c)
17+ {
18+ caretakers.insert (&c);
19+ }
20+
21+ void SunlightSensor::operator ()()
22+ {
23+ for (;;)
24+ {
25+ std::unique_lock<std::mutex> lock (mtx);
26+ const auto sunlight = isSunlight ();
27+ updateState (sunlight);
28+
29+ std::cout << " Sun shines: " << std::boolalpha << sunlight << " \n " ;
30+
31+ if (isTooMuchSunlight (sunlight))
32+ {
33+ for (auto p : caretakers)
34+ p->closeWindowBlinds ();
35+ sensorOn = false ;
36+ }
37+ else if (isTooLittleSunlight (sunlight))
38+ {
39+ for (auto p : caretakers)
40+ p->openWindowBlinds ();
41+ sensorOn = true ;
42+ }
43+
44+ lock.unlock ();
45+ std::this_thread::sleep_for (sleepTime);
46+ }
47+ }
48+
49+ void SunlightSensor::updateState (const bool sunlight)
50+ {
51+ const auto currentTime = std::chrono::system_clock::now ();
52+ if (sunlight and sensorOn)
53+ {
54+ sunlightOnFrom = sunlightOnFrom ? *sunlightOnFrom : currentTime;
55+ sunlightOffFrom = std::nullopt ;
56+ }
57+ else if (not sunlight)
58+ {
59+ sunlightOffFrom = sunlightOffFrom ? *sunlightOffFrom : currentTime;
60+ sunlightOnFrom = std::nullopt ;
61+ }
62+ }
63+
64+ bool SunlightSensor::isTooMuchSunlight (const bool sunlight)
65+ {
66+ if (sunlight)
67+ {
68+ const auto timeNow = std::chrono::system_clock::now ();
69+ std::chrono::duration<double > elapsedSeconds = timeNow - (*sunlightOnFrom);
70+ return elapsedSeconds.count () > threshold;
71+ }
72+ return false ;
73+ }
74+
75+ bool SunlightSensor::isTooLittleSunlight (const bool sunlight)
76+ {
77+ if (not sunlight)
78+ {
79+ const auto timeNow = std::chrono::system_clock::now ();
80+ std::chrono::duration<double > elapsedSeconds = timeNow - (*sunlightOffFrom);
81+ return elapsedSeconds.count () > threshold;
82+ }
83+ return false ;
84+ }
85+
86+ bool SunlightSensor::isSunlight () const
87+ {
88+ /* We simulate changes of sunlight by generating random numbers that represent
89+ * a probability of change in sunlight: if the sun shines or not.
90+ */
91+ static bool sunShines = false ;
92+ static std::mt19937 generator;
93+ auto prob = std::uniform_int_distribution<int >(1 , 100 )(generator);
94+ if (prob >= 80 )
95+ sunShines = !sunShines;
96+ return sunShines;
97+ }
98+ }
0 commit comments