RemoteMatlabReq.cpp 8.2 KB
Newer Older
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
/*
 * Nomad Instrument Control Software
 *
 * Copyright 2011 Institut Laue-Langevin
 *
 * Licensed under the EUPL, Version 1.1 only (the "License");
 * You may not use this work except in compliance with the Licence.
 * You may obtain a copy of the Licence at:
 *
 * http://joinup.ec.europa.eu/software/page/eupl
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the Licence is distributed on an "AS IS" basis,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the Licence for the specific language governing permissions and
 * limitations under the Licence.
 */

#include <InstrumentManager/InstrumentManager.h>
#include <controllers/common/acquisition/Count.h>
#include <controllers/common/scanlegacy/ScanInfo.h>
#include <ics/Utilities/Calculations.h>
#include <common/connection/RestJsonHttpConnection.h>
#include <boost/lexical_cast.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <fstream>
#include <iostream>
#include <common/base/ServerProperties.h>
#include "RemoteMatlabReq.h"

namespace tas {

using namespace std;
using namespace common;
using namespace boost;
using namespace cameo;
using boost::property_tree::ptree;

const std::string RemoteMatlabReq::TYPE = "tas_remote_matlab_req";
const std::string RemoteMatlabReq::MATLAB_APPLICATION = "matlab";
const std::string RemoteMatlabReq::NUMOR_RESPONDER = "tas_numor";
const int32 RemoteMatlabReq::LOG_TYPE = 1;
const int32 RemoteMatlabReq::LIVE_TYPE = 2;

RemoteMatlabReq::RemoteMatlabReq(const std::string& name) :
	RemoteMatlab(name) {
}

RemoteMatlabReq::RemoteMatlabReq(const RemoteMatlabReq& controller) :
	RemoteMatlab(controller) {
}

RemoteMatlabReq::~RemoteMatlabReq() {

	// Stop the remote application.
	m_matlabApplication->stop();

	// Wait for the termination
	application::State state = m_matlabApplication->waitFor();

	cout << "Matlab application terminated with state " << application::toString(state) << endl;
}

void RemoteMatlabReq::postConfiguration() {

67
68
	RemoteMatlab::postConfiguration();

69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
	registerUpdater(scanController->serializerEvent, &RemoteMatlabReq::updateNumor, this);
	//registerUpdater(scanController->getCount()->statusMessage, &RemoteMatlabReq::updateCountStatusMessage, this);
	registerUpdater(countSpy->statusMessage, &RemoteMatlabReq::updateCountStatusMessage, this);

	if (serverEndpoint() == "") {
		m_server.reset(new Server(application::This::getServer().getEndpoint()));

	} else {
		m_server.reset(new Server(serverEndpoint()));
	}

	initialized = initApplication();
}

bool RemoteMatlabReq::initApplication() {

	// Do not initialize if it is already done
	if (initialized()) {
		return true;
	}

	try {

		// Start the Matlab server
93
		if (!m_server->isAvailable(10000)) {
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
			cout << "Matlab server is not available" << endl;
			return false;
		}

		cout << "Matlab server is connected to " << getName() << endl;

		m_matlabApplication = m_server->connect(MATLAB_APPLICATION);
		if (m_matlabApplication->exists()) {
			// The application exists from a previous server session
			m_matlabApplication->kill();
			application::State state = m_matlabApplication->waitFor();
			cout << "Terminated matlab application " << state << endl;
		}

		m_matlabApplication = m_server->start(MATLAB_APPLICATION);

		if (!m_matlabApplication->exists()) {
			cout << "No matlab application" << endl;
			return false;
		}

		// Create the requester.
		m_requester = application::Requester::create(*m_matlabApplication, NUMOR_RESPONDER);

		if (m_requester.get() == 0) {
			cout << "requester error" << endl;
			return false;
		}

		// Application initialized.
		initialized = true;

		return true;

	} catch (...) {
		// Currently an exception can occur during isAvailable.
		cout << "Unexpected exception during matlab connection" << endl;
	}

	return false;
}

void RemoteMatlabReq::updateNumor() {

	// Send the numor to be computed if there is something to serialize
139
140
141
	if (scanController->serializerEvent()
			&& active()) {

142
143
144
145
146
147
148
149
150
151
152
		// Send the numor
		if (test()) {
			sendNumor(testNumor(), false);
		} else {
			sendNumor(scanController->numor(), false);
		}
	}
}

void RemoteMatlabReq::updateCountStatusMessage() {

153
154
155
	if ((countSpy->statusMessage() == "Close data")
			&& scanController->getScanInfo()->running()
			&& active()) {
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

		cout << "Send the numor for live refresh" << endl;

		// Send the numor
		if (test()) {
			sendNumor(testNumor(), true);
		} else {
			sendNumor(scanController->numor(), true);
		}
	}
}

void RemoteMatlabReq::sendNumor(int32 numor, bool live) {

	if (!initApplication()) {
		return;
	}

	// Get the content of the numor.
	string numorName = lexical_cast<string>(numor);
	size_t size = numorName.size();
	if (size < 6) {
		string prefix(6 - size, '0');
		numorName = prefix + numorName;
	}

182
183
184
185
186
	// Not log when the calculation is for live process.
	if (!live) {
		LogStream logStream = log(Level::s_Info).property(scanController->logAcquisitionType)
													.property(scanController->logNumor)
													.property(scanController->logSubtitle);
187

188
189
		logStream << numorName << " in Q" << image(numor, "q") << endlog;
	}
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

	string numorFileName(ServerProperties::getInstance()->getNomadDataPath());
	numorFileName += numorName;

	ifstream numorFile;
	numorFile.open(numorFileName.c_str());

	stringstream stream;
	stream << numorFile.rdbuf();

	// Serialize the request.
	proto::NumorRequest request;
	if (live) {
		request.mutable_info()->set_type(proto::NumorInfo_Type_LIVE);
	} else {
		request.mutable_info()->set_type(proto::NumorInfo_Type_LOG);
	}

	request.mutable_info()->set_propid(getProposalId());
	request.mutable_info()->set_proposal(getProposalName());
	request.mutable_info()->set_instrid(getInstrumentId());
	request.mutable_info()->set_instrument(getInstrumentName());
	request.mutable_info()->set_sampid(getSampleId());
	request.mutable_info()->set_sample(getSampleName());
	request.mutable_info()->set_cycle(getCycleId());
	request.mutable_info()->set_imageid(getImageName());
	request.mutable_info()->set_numor(lexical_cast<string>(numor));

	request.set_content(stream.str());

	// Send the message.
	m_requester->sendBinary(request.SerializeAsString());

	cout << getName() << " sent numor request " << numor << endl;

	// Wait for the response synchronously.
	// Note that responses can be processed asynchronously if the server is able to.
	string data;
	m_requester->receiveBinary(data);

	proto::NumorResponse response;
	response.ParseFromString(data);

	if (response.mutable_info()->type() == proto::NumorInfo_Type_LOG) {
		sendImageToFluentd(response);

	} else {
		setContentFromBinaryData(response.image());
	}
}

void RemoteMatlabReq::start() {

	// Send the numor
	sendNumor(testNumor(), true);
}

void RemoteMatlabReq::sendImageToFluentd(const proto::NumorResponse& response) {

	// Encode the JSON message
	ptree message;
	message.put("id", Date().toString());
	message.put("mt", "acq");
	message.put("name", "numor");
	message.put("type", "number");
	message.put("value", response.info().numor());
	message.put("output", "null");
	message.put("level", "info");
	message.put("propid", response.info().propid());
	message.put("instrid", response.info().instrid());
	message.put("sampleid", response.info().sampid());
	message.put("sample", response.info().sample());
	message.put("cycleid", response.info().cycle());
	message.put("imagefile", response.info().imageid());

	// The binary content of the image is a string and we encode it in base64
	message.put("imagedata", Calculations::encodeBase64(response.image()));

	stringstream os;
	write_json(os, message, false);

	std::string instrumentName = response.info().instrument();
	boost::to_upper(instrumentName);

	RestJsonHttpConnection con;

	try {
		con.openUrl("localhost", "8888");

		// New environment variable.
		if (ServerProperties::getInstance()->getNomadSenddata() == "0") {
			// If 0 send data to dev database.
			con.setPath(string("/oracle.forward.") + instrumentName + "_DEV");

		} else if (ServerProperties::getInstance()->getNomadSenddata() == "1") {
			// If 1 send data to prod database.
			con.setPath(string("/oracle.forward.") + instrumentName);
		}

		con.setData(os.str());
		boost::property_tree::ptree response = con.send(false);

	} catch (const Exception& e) {
		// log to server
		cerr << e.printStack() << endl;
	}

}

}