source: trunk/FACT++/src/agilentctrl.cc@ 17360

Last change on this file since 17360 was 17360, checked in by tbretz, 11 years ago
The description in the DATA service were in the wrong order
File size: 17.1 KB
Line 
1#include <functional>
2
3#include "Dim.h"
4#include "Event.h"
5#include "StateMachineDim.h"
6#include "StateMachineAsio.h"
7#include "Connection.h"
8#include "LocalControl.h"
9#include "Configuration.h"
10
11#include "tools.h"
12
13#include "HeadersAgilent.h"
14
15namespace ba = boost::asio;
16namespace bs = boost::system;
17namespace dummy = ba::placeholders;
18
19using namespace std;
20using namespace Agilent;
21
22// ------------------------------------------------------------------------
23
24class ConnectionAgilent : public Connection
25{
26 bool fIsVerbose;
27 bool fDebugRx;
28
29 uint16_t fInterval;
30
31 boost::asio::deadline_timer fTimeout;
32 boost::asio::deadline_timer fTimeoutPowerCycle;
33 boost::asio::streambuf fBuffer;
34
35 Data fData;
36
37 Time fLastReceived;
38 Time fLastCommand;
39
40protected:
41
42 virtual void UpdateDim(const Data &)
43 {
44 }
45
46 void RequestStatus()
47 {
48 if (IsConnected())
49 PostMessage(string("*IDN?\nvolt?\nmeas:volt?\nmeas:curr?\ncurr?\n"));
50
51 fTimeout.expires_from_now(boost::posix_time::seconds(fInterval));
52 fTimeout.async_wait(boost::bind(&ConnectionAgilent::HandleStatusTimer,
53 this, dummy::error));
54 }
55
56
57 void HandleStatusTimer(const bs::error_code &error)
58 {
59 // 125: Operation canceled (bs::error_code(125, bs::system_category))
60 if (error && error!=ba::error::basic_errors::operation_aborted)
61 {
62 ostringstream str;
63 str << "Status request timeout of " << URL() << ": " << error.message() << " (" << error << ")";// << endl;
64 Error(str);
65
66 PostClose(false);
67 return;
68 }
69
70 if (!is_open())
71 {
72 // For example: Here we could schedule a new accept if we
73 // would not want to allow two connections at the same time.
74 PostClose(true);
75 return;
76 }
77
78 // Check whether the deadline has passed. We compare the deadline
79 // against the current time since a new asynchronous operation
80 // may have moved the deadline before this actor had a chance
81 // to run.
82 if (fTimeout.expires_at() > ba::deadline_timer::traits_type::now())
83 return;
84
85 RequestStatus();
86 }
87
88 void HandlePowerCycle(const bs::error_code &error)
89 {
90 // 125: Operation canceled (bs::error_code(125, bs::system_category))
91 if (error && error!=ba::error::basic_errors::operation_aborted)
92 {
93 ostringstream str;
94 str << "Power cycle timeout of " << URL() << ": " << error.message() << " (" << error << ")";// << endl;
95 Error(str);
96
97 PostClose(false);
98 return;
99 }
100
101 if (!is_open())
102 {
103 // For example: Here we could schedule a new accept if we
104 // would not want to allow two connections at the same time.
105 PostClose(true);
106 return;
107 }
108
109 // Check whether the deadline has passed. We compare the deadline
110 // against the current time since a new asynchronous operation
111 // may have moved the deadline before this actor had a chance
112 // to run.
113 if (fTimeout.expires_at() > ba::deadline_timer::traits_type::now())
114 return;
115
116 SetPower(true);
117 }
118
119private:
120 void StartRead(int line=0)
121 {
122 ba::async_read_until(*this, fBuffer, "\n",
123 boost::bind(&ConnectionAgilent::HandleReceivedData, this,
124 dummy::error, dummy::bytes_transferred, line+1));
125 }
126
127 void HandleReceivedData(const bs::error_code& err, size_t bytes_received, int line)
128 {
129
130 // Do not schedule a new read if the connection failed.
131 if (bytes_received==0 || err)
132 {
133 if (err==ba::error::eof)
134 Warn("Connection closed by remote host (FTM).");
135
136 // 107: Transport endpoint is not connected (bs::error_code(107, bs::system_category))
137 // 125: Operation canceled
138 if (err && err!=ba::error::eof && // Connection closed by remote host
139 err!=ba::error::basic_errors::not_connected && // Connection closed by remote host
140 err!=ba::error::basic_errors::operation_aborted) // Connection closed by us
141 {
142 ostringstream str;
143 str << "Reading from " << URL() << ": " << err.message() << " (" << err << ")";// << endl;
144 Error(str);
145 }
146 PostClose(err!=ba::error::basic_errors::operation_aborted);
147 return;
148 }
149
150
151 if (fDebugRx)
152 {
153 Out() << kBold << "Received (" << bytes_received << ", " << fBuffer.size() << " bytes):" << endl;
154 Out() << "-----\n" << string(ba::buffer_cast<const char*>(fBuffer.data()), bytes_received) << "-----\n";
155 }
156
157 istream is(&fBuffer);
158
159 string str;
160 getline(is, str, '\n');
161
162 try
163 {
164 switch (line)
165 {
166 case 1: Out() << "ID: " << str << endl; break;
167 case 2: fData.fVoltageSet = stof(str); break;
168 case 3: fData.fVoltageMeasured = stof(str); break;
169 case 4: fData.fCurrentMeasured = stof(str); break;
170 case 5: fData.fCurrentLimit = stof(str); break;
171 default:
172 return;
173 }
174 }
175 catch (const exception &e)
176 {
177 Error("String conversion failed for '"+str+" ("+e.what()+")");
178 return;
179 }
180
181 if (line==5)
182 {
183 if (fIsVerbose)
184 {
185 Out() << "Voltage: " << fData.fVoltageMeasured << "V/" << fData.fVoltageSet << "V\n";
186 Out() << "Current: " << fData.fCurrentMeasured << "A/" << fData.fCurrentLimit << "A\n" << endl;
187 }
188
189 UpdateDim(fData);
190
191 fLastReceived = Time();
192
193 line = 0;
194
195 }
196
197 StartRead(line);
198 }
199
200
201 // This is called when a connection was established
202 void ConnectionEstablished()
203 {
204 fBuffer.prepare(1000);
205
206 StartRead();
207 RequestStatus();
208 }
209
210public:
211
212 ConnectionAgilent(ba::io_service& ioservice, MessageImp &imp) : Connection(ioservice, imp()),
213 fIsVerbose(true), fDebugRx(false), fTimeout(ioservice), fTimeoutPowerCycle(ioservice)
214 {
215 SetLogStream(&imp);
216 }
217
218 void SetVerbose(bool b)
219 {
220 fIsVerbose = b;
221 }
222
223 void SetDebugRx(bool b)
224 {
225 fDebugRx = b;
226 }
227
228 void SetInterval(uint16_t i)
229 {
230 fInterval = i;
231 }
232
233 bool SetPower(bool on)
234 {
235 if (!IsConnected())
236 return false;
237
238 if (fLastCommand+boost::posix_time::seconds(59)>Time())
239 {
240 Error("Last power command within the last 59 seconds... ignored.");
241 return false;
242 }
243
244 PostMessage("outp "+string(on?"on":"off")+"\n*IDN?\nvolt?\nmeas:volt?\nmeas:curr?\ncurr?\n");
245 fLastCommand = Time();
246
247 // Stop any pending power cycling
248 fTimeoutPowerCycle.cancel();
249
250 return true;
251 }
252
253 void PowerCycle(uint16_t seconds)
254 {
255 if (!SetPower(false))
256 return;
257
258 fTimeoutPowerCycle.expires_from_now(boost::posix_time::seconds(seconds));
259 fTimeoutPowerCycle.async_wait(boost::bind(&ConnectionAgilent::HandlePowerCycle,
260 this, dummy::error));
261 }
262
263 int GetState()
264 {
265 if (!IsConnected())
266 return State::kDisconnected;
267
268 if (fLastReceived+boost::posix_time::seconds(fInterval*2)<Time())
269 return State::kDisconnected;
270
271 if (fData.fCurrentMeasured<0)
272 return State::kConnected;
273
274 if (fData.fVoltageMeasured<0.1)
275 return State::kVoltageOff;
276
277 if (fData.fVoltageMeasured<fData.fVoltageSet-0.1)
278 return State::kVoltageLow;
279
280 if (fData.fVoltageMeasured>fData.fVoltageSet+0.1)
281 return State::kVoltageHigh;
282
283 return State::kVoltageOn;
284 }
285};
286
287// ------------------------------------------------------------------------
288
289#include "DimDescriptionService.h"
290
291class ConnectionDimAgilent : public ConnectionAgilent
292{
293private:
294
295 DimDescribedService fDim;
296
297 void UpdateDim(const Data &data)
298 {
299 fDim.Update(data);
300 }
301
302public:
303 ConnectionDimAgilent(ba::io_service& ioservice, MessageImp &imp) :
304 ConnectionAgilent(ioservice, imp),
305 fDim("AGILENT_CONTROL/DATA", "F:1;F:1;F:1;F:1",
306 "|U_nom[V]: Nominal output voltage"
307 "|U_mes[V]: Measured output voltage"
308 "|I_max[A]: Current limit"
309 "|I_mes[A]: Measured current")
310)
311 {
312 // nothing happens here.
313 }
314};
315
316// ------------------------------------------------------------------------
317
318template <class T, class S>
319class StateMachineAgilent : public StateMachineAsio<T>
320{
321private:
322 S fAgilent;
323
324 int Disconnect()
325 {
326 // Close all connections
327 fAgilent.PostClose(false);
328
329 /*
330 // Now wait until all connection have been closed and
331 // all pending handlers have been processed
332 poll();
333 */
334
335 return T::GetCurrentState();
336 }
337
338 int Reconnect(const EventImp &evt)
339 {
340 // Close all connections to supress the warning in SetEndpoint
341 fAgilent.PostClose(false);
342
343 // Now wait until all connection have been closed and
344 // all pending handlers have been processed
345 ba::io_service::poll();
346
347 if (evt.GetBool())
348 fAgilent.SetEndpoint(evt.GetString());
349
350 // Now we can reopen the connection
351 fAgilent.PostClose(true);
352
353 return T::GetCurrentState();
354 }
355
356 int Execute()
357 {
358 return fAgilent.GetState();
359 }
360
361 bool CheckEventSize(size_t has, const char *name, size_t size)
362 {
363 if (has==size)
364 return true;
365
366 ostringstream msg;
367 msg << name << " - Received event has " << has << " bytes, but expected " << size << ".";
368 T::Fatal(msg);
369 return false;
370 }
371
372 int SetVerbosity(const EventImp &evt)
373 {
374 if (!CheckEventSize(evt.GetSize(), "SetVerbosity", 1))
375 return T::kSM_FatalError;
376
377 fAgilent.SetVerbose(evt.GetBool());
378
379 return T::GetCurrentState();
380 }
381
382 int SetDebugRx(const EventImp &evt)
383 {
384 if (!CheckEventSize(evt.GetSize(), "SetDebugRx", 1))
385 return T::kSM_FatalError;
386
387 fAgilent.SetDebugRx(evt.GetBool());
388
389 return T::GetCurrentState();
390 }
391
392 int SetPower(const EventImp &evt)
393 {
394 if (!CheckEventSize(evt.GetSize(), "SetPower", 1))
395 return T::kSM_FatalError;
396
397 fAgilent.SetPower(evt.GetBool());
398
399 return T::GetCurrentState();
400 }
401
402 int PowerCycle(const EventImp &evt)
403 {
404 if (!CheckEventSize(evt.GetSize(), "PowerCyle", 2))
405 return T::kSM_FatalError;
406
407 if (evt.GetShort()<60)
408 {
409 T::Warn("Power cycle delays of less than 60s not allowed.");
410 return T::GetCurrentState();
411 }
412
413 fAgilent.PowerCycle(evt.GetShort());
414
415 return T::GetCurrentState();
416 }
417
418
419public:
420 StateMachineAgilent(ostream &out=cout) :
421 StateMachineAsio<T>(out, "AGILENT_CONTROL"), fAgilent(*this, *this)
422 {
423 // State names
424 T::AddStateName(State::kDisconnected, "Disconnected",
425 "Agilent not connected via ethernet.");
426 T::AddStateName(State::kConnected, "Connected",
427 "Ethernet connection to Agilent established, but not data received yet.");
428
429 T::AddStateName(State::kVoltageOff, "VoltageOff",
430 "The measured output voltage is lower than 0.1V");
431 T::AddStateName(State::kVoltageLow, "VoltageLow",
432 "The measured output voltage is higher than 0.1V, but lower than the command voltage");
433 T::AddStateName(State::kVoltageOn, "VoltageOn",
434 "The measured output voltage is higher than 0.1V and comparable to the command voltage");
435 T::AddStateName(State::kVoltageHigh, "VoltageHigh",
436 "The measured output voltage is higher than the command voltage!");
437
438 // Verbosity commands
439 T::AddEvent("SET_VERBOSE", "B:1")
440 (bind(&StateMachineAgilent::SetVerbosity, this, placeholders::_1))
441 ("set verbosity state"
442 "|verbosity[bool]:disable or enable verbosity for received data (yes/no)");
443
444 T::AddEvent("SET_DEBUG_RX", "B:1")
445 (bind(&StateMachineAgilent::SetVerbosity, this, placeholders::_1))
446 ("set debug state"
447 "|debug[bool]:disable or enable verbosity for received raw data (yes/no)");
448
449 T::AddEvent("SET_POWER", "B:1")
450 (bind(&StateMachineAgilent::SetPower, this, placeholders::_1))
451 ("Enable or disable power output"
452 "|output[bool]:set power output to 'on' or 'off'");
453
454 T::AddEvent("POWER_CYCLE", "S:1")
455 (bind(&StateMachineAgilent::PowerCycle, this, placeholders::_1))
456 ("Power cycle the power output"
457 "|delay[short]:Defines the delay between switching off and on.");
458
459
460 // Conenction commands
461 T::AddEvent("DISCONNECT", State::kConnected)
462 (bind(&StateMachineAgilent::Disconnect, this))
463 ("disconnect from ethernet");
464
465 T::AddEvent("RECONNECT", "O", State::kDisconnected, State::kConnected)
466 (bind(&StateMachineAgilent::Reconnect, this, placeholders::_1))
467 ("(Re)connect ethernet connection to Agilent, a new address can be given"
468 "|[host][string]:new ethernet address in the form <host:port>");
469
470 fAgilent.StartConnect();
471 }
472
473 void SetEndpoint(const string &url)
474 {
475 fAgilent.SetEndpoint(url);
476 }
477
478 int EvalOptions(Configuration &conf)
479 {
480 fAgilent.SetVerbose(!conf.Get<bool>("quiet"));
481 fAgilent.SetDebugRx(conf.Get<bool>("debug-rx"));
482 fAgilent.SetInterval(conf.Get<uint16_t>("interval"));
483
484 SetEndpoint(conf.Get<string>("addr"));
485
486 return -1;
487 }
488};
489
490// ------------------------------------------------------------------------
491
492#include "Main.h"
493
494template<class T, class S, class R>
495int RunShell(Configuration &conf)
496{
497 return Main::execute<T, StateMachineAgilent<S, R>>(conf);
498}
499
500void SetupConfiguration(Configuration &conf)
501{
502 po::options_description control("agilent_ctrl control options");
503 control.add_options()
504 ("no-dim", po_bool(), "Disable dim services")
505 ("addr,a", var<string>("10.0.100.220:5025"), "network address of Agilent")
506 ("debug-rx", po_bool(false), "Enable raw debug output wehen receiving data")
507 ("interval", var<uint16_t>(15), "Interval in seconds in which the Agilent status is requested")
508 ("quiet,q", po_bool(true), "Disable printing contents of all received messages (except dynamic data) in clear text.")
509 ;
510
511 conf.AddOptions(control);
512}
513
514/*
515 Extract usage clause(s) [if any] for SYNOPSIS.
516 Translators: "Usage" and "or" here are patterns (regular expressions) which
517 are used to match the usage synopsis in program output. An example from cp
518 (GNU coreutils) which contains both strings:
519 Usage: cp [OPTION]... [-T] SOURCE DEST
520 or: cp [OPTION]... SOURCE... DIRECTORY
521 or: cp [OPTION]... -t DIRECTORY SOURCE...
522 */
523void PrintUsage()
524{
525 cout <<
526 "The agilentctrl controls the FACT camera power supply.\n\n"
527 "\n"
528 "The default is that the program is started without user intercation. "
529 "All actions are supposed to arrive as DimCommands. Using the -c "
530 "option, a local shell can be initialized. With h or help a short "
531 "help message about the usuage can be brought to the screen.\n"
532 "\n"
533 "Usage: agilentctrl [-c type] [OPTIONS]\n"
534 " or: agilentctrl [OPTIONS]\n";
535 cout << endl;
536}
537
538void PrintHelp()
539{
540 Main::PrintHelp<StateMachineAgilent<StateMachine, ConnectionAgilent>>();
541}
542
543int main(int argc, const char* argv[])
544{
545 Configuration conf(argv[0]);
546 conf.SetPrintUsage(PrintUsage);
547 Main::SetupConfiguration(conf);
548 SetupConfiguration(conf);
549
550 if (!conf.DoParse(argc, argv, PrintHelp))
551 return 127;
552
553 //try
554 {
555 // No console access at all
556 if (!conf.Has("console"))
557 {
558 if (conf.Get<bool>("no-dim"))
559 return RunShell<LocalStream, StateMachine, ConnectionAgilent>(conf);
560 else
561 return RunShell<LocalStream, StateMachineDim, ConnectionDimAgilent>(conf);
562 }
563 // Cosole access w/ and w/o Dim
564 if (conf.Get<bool>("no-dim"))
565 {
566 if (conf.Get<int>("console")==0)
567 return RunShell<LocalShell, StateMachine, ConnectionAgilent>(conf);
568 else
569 return RunShell<LocalConsole, StateMachine, ConnectionAgilent>(conf);
570 }
571 else
572 {
573 if (conf.Get<int>("console")==0)
574 return RunShell<LocalShell, StateMachineDim, ConnectionDimAgilent>(conf);
575 else
576 return RunShell<LocalConsole, StateMachineDim, ConnectionDimAgilent>(conf);
577 }
578 }
579 /*catch (std::exception& e)
580 {
581 cerr << "Exception: " << e.what() << endl;
582 return -1;
583 }*/
584
585 return 0;
586}
Note: See TracBrowser for help on using the repository browser.