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