Files
defrost_v2/defrost.cpp
T
2020-12-08 20:33:52 +03:00

121 lines
3.0 KiB
C++

#include "configparser.h"
#include "globals.h"
#include "ModbusServiceListenThread.h"
#include "libdiff.h"
#include <climits>
#include <iostream>
#include <sstream>
#include <unistd.h>
#include <sys/file.h>
#include <sys/io.h>
#include <errno.h>
#include <cmath>
#include <stdio.h>
const int BASE_DEFAULT = 0x3BC;
string Read(FILE *f)
{
char buffer[256];
string result = "";
while (fgets(buffer, sizeof(buffer), f) != nullptr)
{
result += buffer;
}
return result;
}
void temperature_update(const string &cmd)
{
// other helper variables
float temperature = 1.5;
auto output = popen(cmd.c_str(), "r");
if (output == nullptr) return;
string value = Read(output);
pclose(output);
temperature = atof(value.c_str());
registers[REGISTER_CUR_TEMP] = (int)(temperature * 100);
registers[REGISTER_SECONDARY_TEMP] = (int)(temperature * 100);
}
int main(int argc, char *argv[])
{
try {
// ����� lock-file, ����� ���������� ������ ���� ��������� �������
int lockfile = open("/tmp/defrost.lock", O_RDWR | O_CREAT, 0777);
if (lockfile == -1)
{
cout << "Unable to open file for locking, errno = " << errno << "\n";
return 1;
}
if (flock(lockfile, LOCK_EX | LOCK_NB) == -1)
{
cout << "Unable to lock file, errno = " << errno << "\n";
return 1;
}
// load config
ConfigParser cfg;
cfg.Load(argv[1]);
mainlog.InitLogging(cfg.GetParam("LogPath"), LIBLOGSINGLEFILE, "defrost", true);
mainlog.LogString("Defrost service started");
int port_base = BASE_DEFAULT;
auto port_address = cfg.GetParamSilent("PortAddress");
if (port_address != "")
{
port_base = atoi(port_address.c_str());
}
if (ioperm(port_base, 1, 1))
{
mainlog.LogString("Access to port denied");
return EXIT_FAILURE;
}
string measure_command = cfg.GetParam("MeasureCommand");
if (pthread_mutex_init(&register_mutex, NULL) != 0)
{
mainlog.LogString("Unable to create registers_mutex");
return EXIT_FAILURE;
}
registers[REGISTER_ON_TEMP] = 100;
registers[REGISTER_OFF_TEMP] = 500;
registers[REGISTER_MODE] = 0;
// run modbus service listen thread
ModbusServiceListenThread *modbus_service = new ModbusServiceListenThread(&mainlog, atoi(cfg.GetParam("ListenPort").c_str()));
modbus_service->Start();
int io_value = 0;
// loop forever updating the temperature values every second
while (true)
{
LockMutex(register_mutex);
temperature_update(measure_command);
int mode = registers[REGISTER_MODE];
if (mode == 0)
{
if (registers[REGISTER_CUR_TEMP] < registers[REGISTER_ON_TEMP]) io_value = 1;
else if (registers[REGISTER_CUR_TEMP] > registers[REGISTER_OFF_TEMP]) io_value = 0;
}
else if (mode == 1)
{
io_value = registers[REGISTER_CUR_STATE];
}
registers[REGISTER_CUR_STATE] = io_value;
outb(io_value, port_base);
ReleaseMutex(register_mutex);
sleep(1);
}
}
catch (string s)
{
cerr << "Exception: " << s << "\n";
return EXIT_FAILURE;
}
return 0;
}