laserpssokintck.cpp 10.8 KB
Newer Older
Lucio Zambon's avatar
Lucio Zambon committed
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
/***************************************************************************
 *   Copyright (C) 2007 by    *
 *      *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#include "laserpssokintck.h"
#include <qtango.h>
	char tmBuffer[80];
	QFont myFont("Helvetica", 14, QFont::Bold);

void timestamp() 
{
	struct tm *mytime;
	time_t myTime_t;
	myTime_t = time(NULL);
	mytime = localtime(&myTime_t);
	strftime(tmBuffer, 79, "%Y-%m-%d %H:%M:%S ", mytime);
	return;
}
int laserpssokintck::myReadBoolArray(QString attrName, vector<bool> & attrVal)
{
	try {
		plc_server->read_attribute((const char *)attrName.toStdString().c_str()) >> attrVal;
		return 1;
	}
	catch (const Tango::DevFailed &e) {
		timestamp();
		cout << tmBuffer << "exception reading attribute: " << attrName.toStdString() << endl;
	}
	catch (...) {
		timestamp();
		cout << tmBuffer << "default exception reading attribute: " << attrName.toStdString() << endl;
	}
	return 0;
}

void laserpssokintck::refresh() {
	vector<bool> stat;
	for (unsigned i=0; i < attributes.size(); i++) {
		if (myReadBoolArray(attributes[i], stat)) {
			for (unsigned j=0; j < states.size(); j++) {
				if (states[j].attr == attributes[i]) {
					states[j].value = (int) (states[j].bit>=0? stat[states[j].bit]: !stat[-1 - states[j].bit]);
					mySetTextColor(states[j].label, (states[j].value? "OK": "NOK"), "#000000", (states[j].value? "#00C800": "#DC0000"));
				}
			}
		}
	}
	for (unsigned k=0; k < derivedCond.size(); k++) {
		derivedCond[k].value = derivedCond[k].isAnd;
		for (unsigned a=0; a < derivedCond[k].attr.size(); a++) {
			derivedCond[k].value = derivedCond[k].isAnd? derivedCond[k].value && states[derivedCond[k].attr[a]].value: derivedCond[k].value || states[derivedCond[k].attr[a]].value;
		}
		for (unsigned c=0; c < derivedCond[k].cond.size(); c++) {
			derivedCond[k].value = derivedCond[k].isAnd? derivedCond[k].value && derivedCond[derivedCond[k].cond[c]].value: derivedCond[k].value || derivedCond[derivedCond[k].cond[c]].value;
		}
		mySetTextColor(derivedCond[k].label, (derivedCond[k].value? "OK": "NOK"), "#000000", (derivedCond[k].value? "#00C800": "#DC0000"));	
	}
}


bool readJsonFile(std::string file_path, QVariantList& result) {
	QFile file_obj(QString::fromStdString(file_path));
	if (!file_obj.open(QIODevice::ReadOnly)) {
		std::cout << "Failed to open " << file_path << std::endl;
		exit(0);
	}
	QTextStream file_text(&file_obj);
	QString json_string;
	json_string = file_text.readAll();
	file_obj.close();
	QByteArray json_bytes = json_string.toLocal8Bit();
	QJsonParseError error;
	auto json_doc = QJsonDocument::fromJson(json_bytes, &error);
	if (json_doc.isNull()) {
		std::cout << "Failed to create JSON doc: " << error.errorString().toStdString() <<  std::endl;
		return false;
	}
	if (json_doc.isArray()) {
		QJsonArray json_obj = json_doc.array();
		result = json_obj.toVariantList();
	}
	else {
		std::cout << "JSON is not an array." << std::endl;
		return false;
	}
	return true;
}

int laserpssokintck::mySetTextColor(QLabel *widget, const char *text, const char *color, const char *bgcolor) {
	QPalette button;
	widget->setText(text);
	button.setColor(QPalette::Window, QColor(bgcolor));
	button.setColor(QPalette::WindowText, QColor(color));
	widget->setPalette(button);
	return 0;
}
void laserpssokintck::handleButton(int n) {
	cout << "button: " << n << ", cmd: " << infoButton[n].toStdString() << endl;
	if (myprocess->state() == QProcess::Running) {
		myprocess->kill();
		myprocess->waitForFinished(3000);
	}
	myprocess->start(infoButton[n]);
}
int laserpssokintck::displayRow(QMap<QString, QVariant> map, int x) {
	// https://stackoverflow.com/questions/21150890/qt-5-assign-slot-with-parameters-to-a-qpushbutton
	int pbOffset = 0;
	if (map["link"].toString() != "") {
		pbOffset = 30;
		QPushButton *pb = new QPushButton(this);
		pb->setGeometry(5, y+5, 20, 21);
		pb->setIconSize(QSize(20, 21));
		pb->setIcon(QPixmap(imgpath+"/info.png"));
		connect(pb, SIGNAL(clicked()), &mapper, SLOT(map()));
		mapper.setMapping(pb, infoButton.size());
		infoButton.push_back(map["link"].toString());
	}
	QString str = (map["operation"].toString() == "NOT"? "NOT ": "")+map["title"].toString();
	QLabel* t = new QLabel(str, this);
	t->setGeometry(5+pbOffset, y, x-10-pbOffset, yStep);
	t->setToolTip(map["description"].toString());
	if (description) {
		QTextEdit* d = new QTextEdit("", this);
		d->setGeometry(this->x, y, descriptionWidth, yStep);
		d->setReadOnly(true);
		d->setFontPointSize(10);
		d->setPlainText(map["description"].toString());
	}
	QLabel* s = new QLabel("?", this);
	mySetTextColor(s, "???", "#000000", "#888888");
	s->setAutoFillBackground(true);
	s->setAlignment(Qt::AlignCenter);
	s->setGeometry(x+10, y+4, 50, yStep-8);
	s->setToolTip("DBX "+map["data-db"].toString()+" - "+map["attr"].toString()+"["+map["attr-bit"].toString()+"]");
	int bit = (int) map["attr-bit"].toDouble();
	if (map["operation"].toString() == "NOT") bit = -1 - bit;
	states.push_back({s, map["attr"].toString(), bit, -1});
	appendAttr(map["attr"].toString());
	return states.size()-1;
}

void laserpssokintck::appendAttr(QString attr) {
	for (unsigned i=0; i < attributes.size(); i++) {
		if (attributes[i] == attr) return;
	}
	attributes.push_back(attr);
}

int laserpssokintck::parseBlock(QMap<QString, QVariant> map, int x, int &cond) {
	if (map["operands"].canConvert<QVariantList>()) {
		QLabel* l = new QLabel("?", this);
		l->setGeometry(x+xStep, 0, 70, yStep);
		mySetTextColor(l, (map["operation"].toString()=="AND"? "AND":"OR"), "#0000FF", "#444444");
		l->setAlignment(Qt::AlignCenter);
		QVariantList list = map["operands"].toList();
		int dy = 0;
		int c;
		dercond dc;
		dc.isAnd = map["operation"].toString()=="AND";
		for (int i=0; i < list.count(); i++) {
			dy += parseBlock(list[i].toMap(), x+xStep, c);
			if (c>=0) dc.attr.push_back(c);
			else dc.cond.push_back(-1 - c);
		}
		QFrame* f = new QFrame(this);
		f->setFrameStyle(QFrame::Box);
		f->setGeometry(0, by, x+1, y-by+1);
		f->lower();
		if (x != this->x) {
			QFrame* s = new QFrame(this);
			s->setFrameStyle(QFrame::Box);
			s->setGeometry(x, yStep, 71, y-yStep+1);
			QLabel* cl = new QLabel("?", this);
			mySetTextColor(cl, "???", "#000000", "#888888");
			cl->setAutoFillBackground(true);
			cl->setAlignment(Qt::AlignCenter);
			cl->setGeometry(x+10, (y)/2, 50, yStep-8);
			dc.label = cl;
			derivedCond.push_back(dc);
			cond = 0 - derivedCond.size();
		}
		else {
			connect(&mapper, SIGNAL(mapped(int)), this, SLOT(handleButton(int)));
		}
		by = y;
		return dy;
	}
	else {
		cond = displayRow(map, x);
		y += yStep;
		return yStep;
	}	
}
void laserpssokintck::preDisplayRow(QMap<QString, QVariant> map, int x) {
	int pbOffset = 0;
	if (map["link"].toString() != "") pbOffset = 30;
	QString str = (map["operation"].toString() == "NOT"? "NOT ": "")+map["title"].toString();
	QFontMetrics fm(myFont);
	int width=fm.horizontalAdvance(str);
	if (xOffset > x-10-pbOffset-width) xOffset = x-10-pbOffset-width;
}

void laserpssokintck::preParseBlock(QMap<QString, QVariant> map, int x) {
	QVariantList list = map["operands"].toList();
	if (map["operands"].canConvert<QVariantList>()) {
		for (int i=0; i < list.count(); i++) {
			preParseBlock(list[i].toMap(), x+xStep);
		}
	}
	else {
		preDisplayRow(map, x);
	}	
}

laserpssokintck::laserpssokintck(QWidget *parent) : QWidget(parent) {
	if (qApp->arguments().count() < 2 || qApp->arguments()[1]=="-h" || qApp->arguments()[1]=="--help") {
		cout << "Usage: " << qApp->arguments()[0].toStdString() << " configuration file (JSON)" << endl;
		exit(0);
	}
	description = false;
	descriptionWidth = 0;
	if (qApp->arguments().count() > 2 && qApp->arguments()[2]=="description") {
		description = true;
		descriptionWidth = 500;
	}	
	x=620; y=30; xStep=-70; yStep=30, by=30, xOffset = 10000;
	QSettings settings("fermi", "acs");
	// load (or set) path for images
	if (settings.contains("imgpath")) {
		imgpath = settings.value("imgpath").toString();
	}
	else {
		settings.setValue("imgpath", "/runtime/fermi/share/images/acs");
	}
	if (!imgpath.endsWith("/")) {
		imgpath = imgpath + "/";
	}
	try {
		plc_server = new Tango::DeviceProxy("srv-tango-srf-01.fcs.elettra.trieste.it:20000/slu/interlock/laser_pss");
	}
	catch (const Tango::DevFailed &e) {
		timestamp();
		cout << tmBuffer << "Fatal Error: Access Control Device Server not responding, the application will be terminated immediately" << endl;
		exit(1);
	}
	catch (...) {
		timestamp();
		cout << tmBuffer << "Fatal Error: Access Control Device Server not responding, the application will be terminated immediately" << endl;
		exit(1);
	}
	ui.setupUi(this);
	myprocess = new QProcess(this);
	QApplication::setFont(myFont);
	QVariantList list0;
    	if (readJsonFile(qApp->arguments()[1].toStdString() , list0)) {
		QMap<QString, QVariant> map0 = list0[0].toMap();
		int c;
		preParseBlock(list0[1].toMap(), x);
		preDisplayRow(map0, x+xStep);
		x -= xOffset;
		parseBlock(list0[1].toMap(), x, c);
		this->setGeometry(0, 0, x+descriptionWidth, y+yStep);
		this->setMaximumSize(x+descriptionWidth, y+yStep);
		this->setMinimumSize(x+descriptionWidth, y+yStep);
		this->setWindowTitle(map0["title"].toString());
		QFrame* f = new QFrame(this);
		f->setFrameStyle(QFrame::Box);
		f->setGeometry(0, y, x, yStep+1);
		f->setStyleSheet("background-color: rgb(200,255,200)");
		displayRow(map0, x+xStep);
	}
	else {
		cout << "ERROR: cannot read JSON file" << endl;
		exit(0);
	}
	refresh();
	try {
		timer = new QTimer(this);
		timer->setInterval(1000);
		timer->setSingleShot(false);
		connect(timer, SIGNAL(timeout()), this, SLOT(refresh()));
		timer->start();
	}
	catch (const Tango::DevFailed &e) {
		timestamp();
		cout << tmBuffer << "cannot connect UI" << endl;
	}
	catch (...) {int
		timestamp();
		cout << tmBuffer << "default exception, cannot setup UI" << endl;
	}
}

laserpssokintck::~laserpssokintck() {
	exit(0);
}