-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathupscontroller.cpp
More file actions
411 lines (348 loc) · 13.4 KB
/
upscontroller.cpp
File metadata and controls
411 lines (348 loc) · 13.4 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
#include <QDebug>
#include <QFile>
#include <QFileInfo>
#include <QDateTime>
#include <unistd.h>
#include "qprocess.h"
#include "qserialport.h"
#include <QIODevice>
#include "upscontroller.h"
UpsController::UpsController(QObject *parent, const QString &upsDeviceName) :
QObject(parent),
upsDeviceName(upsDeviceName)
{
qInfo() << "starting UpsController... 1210";
QProcess p;
p.start("/bin/bash", {"/etc/udev/rules.d/drivers"}, QIODevice::OpenModeFlag::ReadOnly);
p.waitForFinished();
if (p.exitCode() == 0)
{
qInfo() << "drivers loaded";
sleep(2);
} else {
qWarning() << "USB probe failed (" << p.exitCode() << ") " << p.readAllStandardError() << p.readAllStandardError();
}
available_ports = QSerialPortInfo::availablePorts();
//available_clients[current_client] // check that current_client points to the first item
changeState(UPS_STATE::TEST_CONNECTION);
doWork();
}
bool UpsController::getNextClient(){
bool ok = false;
size_t l = sizeof(available_clients) / sizeof(UPS_CLIENT);
if (++current_client < l) {
ok = true;
}
return ok;
}
void UpsController::doWork() {
//qDebug() << QString("dowork(%1)").arg(stateName(ups_state));
switch (ups_state) {
case UPS_STATE::TEST_CONNECTION:
qDebug() << QString("client: %1 try #%2 of %3").arg(available_clients[current_client]).arg(connection_tries + 1).arg(MAX_CONNECTIONS_TRIED);
connect_client();
break;
case UPS_STATE::TEST_FAIL:
sleep(NEXT_CONNECTION_WAIT_SECS);
if (++connection_tries == MAX_CONNECTIONS_TRIED) {
connection_tries = 0;
if (getNextClient()) {
qInfo() << "max tries reached, trying next client (" << available_clients[current_client] << ")";
changeState(UPS_STATE::TEST_CONNECTION);
doWork();
} else {
qInfo("No more clients to test, there is not UPS");
changeState(UPS_STATE::ERROR);
// QUIT ???
}
} else {
changeState(UPS_STATE::TEST_CONNECTION);
doWork();
}
break;
case UPS_STATE::TEST_OK:
changeState(UPS_STATE::CHECK);
connect(&m_pollSaiStatusTimer, &QTimer::timeout, this, &UpsController::sendUpsCommand);
m_pollSaiStatusTimer.start(1000);
break;
case UPS_STATE::CHECK:
break;
case UPS_STATE::WAITING:
// do nothing
usleep(10000);
break;
case UPS_STATE::ERROR:
break;
default:
qDebug() << "S: ??? " << stateName(ups_state);
// do nothing
usleep(10000);
doWork();
break;
}
}
void UpsController::connect_client() {
qDebug() << "testing client " << available_clients[current_client];
switch (available_clients[current_client]) {
case NUT:
try {
m_nutClient = new nut::TcpClient("localhost", 3493);
QString test = QString::fromStdString(m_nutClient->getDeviceVariableValue(upsDeviceName.toStdString(), "ups.status")[0]);
qDebug() << "NUT driver test: " << test;
if (test.contains("DRIVER-NOT-CONNECTED")) {
qWarning() << "NUT driver not connected";
changeState(UPS_STATE::TEST_FAIL);
} else {
qInfo("NUT client connected");
m_nutClient->authenticate("admin", "admin");
changeState(UPS_STATE::TEST_OK);
}
} catch (nut::NutException e) {
qWarning() << "NUT driver error: " << QString::fromStdString(e.str());
changeState(UPS_STATE::TEST_FAIL);
}
doWork();
break;
case MODBUS:
if (!checkMODBUSPort()) {
doWork();
}
break;
default:
qWarning("UNKNOWN UPS CLIENT!");
break;
}
}
bool UpsController::checkMODBUSPort() {
bool ok = true;
qDebug() << "checkMODBUSPort()";
/*** port scan (disabled due to issues with peripherals board
if (current_port < available_ports.length()) {
QSerialPortInfo &portInfo = available_ports[current_port];
mb_portname = portInfo.portName();
*/
mb_portname = "/dev/ttySAI";
qDebug() << "trying MODBUS on port " << mb_portname;
modbusDevice = new QModbusRtuSerialMaster(this);
modbusDevice->setConnectionParameter(QModbusDevice::SerialPortNameParameter, mb_portname);
modbusDevice->setConnectionParameter(QModbusDevice::SerialParityParameter, QSerialPort::MarkParity);
modbusDevice->setConnectionParameter(QModbusDevice::SerialBaudRateParameter, QSerialPort::Baud19200);
modbusDevice->setConnectionParameter(QModbusDevice::SerialDataBitsParameter, QSerialPort::Data8);
modbusDevice->setConnectionParameter(QModbusDevice::SerialStopBitsParameter, QSerialPort::OneStop);
modbusDevice->setTimeout(2000); // milliseconds
modbusDevice->setNumberOfRetries(1);
if (modbusDevice->connectDevice()) {
qDebug() << "device connected";
MBtestRequest();
} else {
qWarning() << "No serial port available";
changeState(UPS_STATE::TEST_FAIL);
ok = false;
}
/* port scan (disabled due to issues with peripherals board
} else {
qWarning() << "No serial ports available";
changeState(UPS_STATE::TEST_FAIL);
ok = false;
}
*/
return ok;
}
void UpsController::MBtestRequest() {
//qDebug() << "MBtestRequest (" << mb_portname << ")";
changeState(UPS_STATE::WAITING);
// the test request also puts the UPS online
QModbusDataUnit pdu = QModbusDataUnit(QModbusDataUnit::RegisterType::HoldingRegisters, MB_REG_ONLINE, 2);
if (auto *reply = modbusDevice->sendWriteRequest(pdu, MODBUS_SLAVE_ID)) {
if (!reply->isFinished())
connect(reply, &QModbusReply::finished, this, &UpsController::MBtestResponse);
else
delete reply; // broadcast replies return immediately
} else {
qWarning() << "MODBUS Read error (online): " << modbusDevice->errorString();
changeState(UPS_STATE::TEST_FAIL);
}
}
void UpsController::MBtestResponse() {
//qDebug() << "MBtestResponse (" << mb_portname << ")";
UPS_STATE newUpsState = UPS_STATE::TEST_CONNECTION;
auto reply = qobject_cast<QModbusReply *>(sender());
if (!reply)
return;
if (reply->error() == QModbusDevice::NoError) {
qDebug() << QString("MODBUS test reply OK (%1, state: %2").arg(mb_portname).arg(stateName(ups_state));
newUpsState = UPS_STATE::TEST_OK;
} else if (reply->error() == QModbusDevice::ProtocolError) {
qWarning() << QString("Test read response error: %1 (MODBUS exception: 0x%2 from %3)")
.arg(reply->errorString())
.arg(reply->rawResult().exceptionCode(), -1, 16)
.arg(mb_portname);
} else {
qWarning() << QString("Test read response error: %1 (code: 0x%2) from %3")
.arg(reply->errorString())
.arg(reply->error(), -1, 16)
.arg(mb_portname);
}
if (newUpsState != UPS_STATE::TEST_OK) {
current_port++;
}
changeState(newUpsState);
reply->deleteLater();
doWork();
}
void UpsController::sendUpsCommand()
{
static bool waitingForUpsOnline = false;
QString upsState = "";
QModbusDataUnit pdu;
if (ups_state == UPS_STATE::WAITING) {
qDebug() << "sendUpsCommand UPS_STATE::WAITING";
return;
}
switch (available_clients[current_client]) {
case NUT:
try {
upsState = QString::fromStdString(m_nutClient->getDeviceVariableValue(upsDeviceName.toStdString(), "ups.status")[0]);
} catch (std::exception e) {
//qWarning() << "Nut driver error while requesting ups data. Details: " << QString::fromStdString(e.what());
qWarning() << "Nut driver error while requesting ups data.";
return;
}
//qDebug() << upsState;
if (upsState.contains("BYPASS") && !waitingForUpsOnline) {
try {
m_nutClient->executeDeviceCommand(upsDeviceName.toStdString(), "load.on"); // Be sure that the UPS is online mode!
waitingForUpsOnline = true;
} catch (std::exception e) {
//qWarning() << "Nut driver error while setting UPS online mode. Details: " << QString::fromStdString(e.what());
qWarning() << "Nut driver error while setting UPS online mode.";
}
} else if (upsState == "OL" && waitingForUpsOnline) {
waitingForUpsOnline = false;
}
qDebug() << "NUT newUpsState " << upsState;
emit newUpsState(upsState);
break;
case MODBUS:
//qDebug() << "sendUpsCommand MODBUS (" << mb_portname << ")";
// Read alarm registers
pdu = QModbusDataUnit(QModbusDataUnit::RegisterType::HoldingRegisters, MB_REG_ALARM, 1);
if (auto *reply = modbusDevice->sendReadRequest(pdu, MODBUS_SLAVE_ID)) {
if (!reply->isFinished())
connect(reply, &QModbusReply::finished, this, &UpsController::MODBUSresponse);
else
delete reply;
} else {
qWarning() << "MODBUS Read error (alarm): " << modbusDevice->errorString();
}
// Read battery registers
pdu = QModbusDataUnit(QModbusDataUnit::RegisterType::HoldingRegisters, MB_REG_BATTERY, 4);
if (auto *reply = modbusDevice->sendReadRequest(pdu, MODBUS_SLAVE_ID)) {
if (!reply->isFinished())
connect(reply, &QModbusReply::finished, this, &UpsController::MODBUSresponse);
else
delete reply;
} else {
qWarning() << "MODBUS Read error (battery): " << modbusDevice->errorString();
}
switch (ups_state) {
case UPS_STATE::CHECK:
changeState(UPS_STATE::WAITING);
break;
default:
break;
}
break;
default:
// do nothing
break;
}
}
QString UpsController::stateName(UPS_STATE state) {
QString r = "unknown";
switch (state) {
case UPS_STATE::OUT: r = "OUT"; break;
case UPS_STATE::TEST_CONNECTION: r = "TEST_CONNECTION"; break;
case UPS_STATE::TEST_OK: r = "TEST_OK"; break;
case UPS_STATE::TEST_FAIL: r = "TEST_FAIL"; break;
case UPS_STATE::CHECK: r = "CHECK"; break;
case UPS_STATE::WAITING: r = "WAITING"; break;
case UPS_STATE::ERROR: r = "ERROR"; break;
}
return r;
}
void UpsController::changeState(UPS_STATE newstate) {
//qDebug() << QString("state change from %1 to %2").arg(stateName(ups_state)).arg(stateName(newstate));
ups_state = newstate;
}
void UpsController::MODBUSresponse() {
QString upsState = "OB: OFF";
auto reply = qobject_cast<QModbusReply *>(sender());
if (!reply)
return;
if (reply->error() == QModbusDevice::NoError) {
//qDebug() << QString("MODBUS reply OK (%1, state: %2").arg(mb_portname).arg(stateName(ups_state));
switch (ups_state) {
case UPS_STATE::TEST_CONNECTION:
changeState(UPS_STATE::TEST_OK);
doWork();
break;
case UPS_STATE::WAITING:
changeState(UPS_STATE::CHECK);
break;
default:
break;
}
const QModbusDataUnit unit = reply->result();
int batlvl = 0;
int minleft = 0;
switch (unit.startAddress()) {
case MB_REG_ALARM:
if (1 & unit.value(0) >> MB_ALARM_AC_BIT) {
upsState = "OL: on";
} else {
upsState = "OB: OFF";
}
break;
case MB_REG_BATTERY:
/*** debug ***
for (int i = 0, total = int(unit.valueCount()); i < total; ++i) {
const QString entry = QString("Address: %1, Value: %2")
.arg(unit.startAddress() + i)
.arg(QString::number(unit.value(i), unit.registerType() <= QModbusDataUnit::Coils ? 10 : 16));
qDebug() << "MODBUS: " << entry;
}
//*/
batlvl = unit.value(0);
minleft = unit.value(2)/60;
upsState = QString(" battery level: %1% (minutes left: %2)").arg(batlvl).arg(minleft);
break;
/*
case MB_REG_ONLINE:
qDebug() << "MB_REG_ONLINE completed";
modbus_state = ONLINE_OK;
break;
*/
default:
// ignore response
upsState = "";
break;
}
} else if (reply->error() == QModbusDevice::ProtocolError) {
qWarning() << QString("Read response error: %1 (MODBUS exception: 0x%2 from %3)")
.arg(reply->errorString())
.arg(reply->rawResult().exceptionCode(), -1, 16)
.arg(mb_portname);
} else {
qWarning() << QString("Read response error: %1 (code: 0x%2) from %3")
.arg(reply->errorString())
.arg(reply->error(), -1, 16)
.arg(mb_portname);
}
reply->deleteLater();
if (upsState.length() > 1) {
qDebug() << "MODBUS newUpsState: " << upsState;
emit newUpsState(upsState);
}
doWork();
}