-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcooler.cpp
More file actions
83 lines (72 loc) · 1.82 KB
/
cooler.cpp
File metadata and controls
83 lines (72 loc) · 1.82 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
81
82
83
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
#include <wiringPi.h>
#include <softPwm.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <ctime>
#define LOG_FILE ("/var/log/cooler.log")
bool shouldStop = false;
int pin = 19;
std::string getCurrentTime() {
std::time_t now = std::time(nullptr);
char buf[80];
std::strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", std::localtime(&now));
return std::string(buf);
}
void writeToLogFile(const std::string& message) {
std::ofstream logFile(LOG_FILE, std::ios_base::app);
if (logFile.is_open()) {
logFile << getCurrentTime() << " " << message << std::endl;
logFile.close();
} else {
std::cerr << "Unable to open log file." << std::endl;
}
}
void sigHandler(int signo) {
if(signo == SIGTERM) {
shouldStop = true;
} else if(signo == SIGINT) {
printf("\nExiting...\n");
shouldStop = true;
}
}
void temperatureReadLoop() {
FILE *fp;
int temperature;
while(!shouldStop) {
fp = fopen("/sys/class/thermal/thermal_zone0/temp", "r");
fscanf(fp, "%d", &temperature);
fclose(fp);
if (temperature < 40000) {
softPwmWrite(pin, 0);
} else if (temperature < 45000) {
softPwmWrite(pin, 25);
} else if (temperature < 50000) {
softPwmWrite(pin, 50);
} else if (temperature < 60000) {
softPwmWrite(pin, 75);
} else {
softPwmWrite(pin, 100);
}
std::ostringstream oss;
oss.precision(2);
oss << std::fixed;
oss << (temperature / 1000.0);
writeToLogFile(oss.str());
sleep(5);
}
softPwmStop(pin);
}
int main() {
signal(SIGTERM, sigHandler);
signal(SIGINT, sigHandler);
wiringPiSetup();
pinMode(pin, OUTPUT);
softPwmCreate(pin, 0, 100);
temperatureReadLoop();
}