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

Last change on this file since 17168 was 16727, checked in by tbretz, 11 years ago
Make use of the new StateMachineAsio which gets the CPU consumption to basically 0 by a more intelligent event management.
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_mes[A]: Measured current"
309 "|I_max[A]: Current limit")
310 {
311 // nothing happens here.
312 }
313};
314
315// ------------------------------------------------------------------------
316
317template <class T, class S>
318class StateMachineAgilent : public StateMachineAsio<T>
319{
320private:
321 S fAgilent;
322
323 int Disconnect()
324 {
325 // Close all connections
326 fAgilent.PostClose(false);
327
328 /*
329 // Now wait until all connection have been closed and
330 // all pending handlers have been processed
331 poll();
332 */
333
334 return T::GetCurrentState();
335 }
336
337 int Reconnect(const EventImp &evt)
338 {
339 // Close all connections to supress the warning in SetEndpoint
340 fAgilent.PostClose(false);
341
342 // Now wait until all connection have been closed and
343 // all pending handlers have been processed
344 ba::io_service::poll();
345
346 if (evt.GetBool())
347 fAgilent.SetEndpoint(evt.GetString());
348
349 // Now we can reopen the connection
350 fAgilent.PostClose(true);
351
352 return T::GetCurrentState();
353 }
354
355 int Execute()
356 {
357 return fAgilent.GetState();
358 }
359
360 bool CheckEventSize(size_t has, const char *name, size_t size)
361 {
362 if (has==size)
363 return true;
364
365 ostringstream msg;
366 msg << name << " - Received event has " << has << " bytes, but expected " << size << ".";
367 T::Fatal(msg);
368 return false;
369 }
370
371 int SetVerbosity(const EventImp &evt)
372 {
373 if (!CheckEventSize(evt.GetSize(), "SetVerbosity", 1))
374 return T::kSM_FatalError;
375
376 fAgilent.SetVerbose(evt.GetBool());
377
378 return T::GetCurrentState();
379 }
380
381 int SetDebugRx(const EventImp &evt)
382 {
383 if (!CheckEventSize(evt.GetSize(), "SetDebugRx", 1))
384 return T::kSM_FatalError;
385
386 fAgilent.SetDebugRx(evt.GetBool());
387
388 return T::GetCurrentState();
389 }
390
391 int SetPower(const EventImp &evt)
392 {
393 if (!CheckEventSize(evt.GetSize(), "SetPower", 1))
394 return T::kSM_FatalError;
395
396 fAgilent.SetPower(evt.GetBool());
397
398 return T::GetCurrentState();
399 }
400
401 int PowerCycle(const EventImp &evt)
402 {
403 if (!CheckEventSize(evt.GetSize(), "PowerCyle", 2))
404 return T::kSM_FatalError;
405
406 if (evt.GetShort()<60)
407 {
408 T::Warn("Power cycle delays of less than 60s not allowed.");
409 return T::GetCurrentState();
410 }
411
412 fAgilent.PowerCycle(evt.GetShort());
413
414 return T::GetCurrentState();
415 }
416
417
418public:
419 StateMachineAgilent(ostream &out=cout) :
420 StateMachineAsio<T>(out, "AGILENT_CONTROL"), fAgilent(*this, *this)
421 {
422 // State names
423 T::AddStateName(State::kDisconnected, "Disconnected",
424 "Agilent not connected via ethernet.");
425 T::AddStateName(State::kConnected, "Connected",
426 "Ethernet connection to Agilent established, but not data received yet.");
427
428 T::AddStateName(State::kVoltageOff, "VoltageOff",
429 "The measured output voltage is lower than 0.1V");
430 T::AddStateName(State::kVoltageLow, "VoltageLow",
431 "The measured output voltage is higher than 0.1V, but lower than the command voltage");
432 T::AddStateName(State::kVoltageOn, "VoltageOn",
433 "The measured output voltage is higher than 0.1V and comparable to the command voltage");
434 T::AddStateName(State::kVoltageHigh, "VoltageHigh",
435 "The measured output voltage is higher than the command voltage!");
436
437 // Verbosity commands
438 T::AddEvent("SET_VERBOSE", "B:1")
439 (bind(&StateMachineAgilent::SetVerbosity, this, placeholders::_1))
440 ("set verbosity state"
441 "|verbosity[bool]:disable or enable verbosity for received data (yes/no)");
442
443 T::AddEvent("SET_DEBUG_RX", "B:1")
444 (bind(&StateMachineAgilent::SetVerbosity, this, placeholders::_1))
445 ("set debug state"
446 "|debug[bool]:disable or enable verbosity for received raw data (yes/no)");
447
448 T::AddEvent("SET_POWER", "B:1")
449 (bind(&StateMachineAgilent::SetPower, this, placeholders::_1))
450 ("Enable or disable power output"
451 "|output[bool]:set power output to 'on' or 'off'");
452
453 T::AddEvent("POWER_CYCLE", "S:1")
454 (bind(&StateMachineAgilent::PowerCycle, this, placeholders::_1))
455 ("Power cycle the power output"
456 "|delay[short]:Defines the delay between switching off and on.");
457
458
459 // Conenction commands
460 T::AddEvent("DISCONNECT", State::kConnected)
461 (bind(&StateMachineAgilent::Disconnect, this))
462 ("disconnect from ethernet");
463
464 T::AddEvent("RECONNECT", "O", State::kDisconnected, State::kConnected)
465 (bind(&StateMachineAgilent::Reconnect, this, placeholders::_1))
466 ("(Re)connect ethernet connection to Agilent, a new address can be given"
467 "|[host][string]:new ethernet address in the form <host:port>");
468
469 fAgilent.StartConnect();
470 }
471
472 void SetEndpoint(const string &url)
473 {
474 fAgilent.SetEndpoint(url);
475 }
476
477 int EvalOptions(Configuration &conf)
478 {
479 fAgilent.SetVerbose(!conf.Get<bool>("quiet"));
480 fAgilent.SetDebugRx(conf.Get<bool>("debug-rx"));
481 fAgilent.SetInterval(conf.Get<uint16_t>("interval"));
482
483 SetEndpoint(conf.Get<string>("addr"));
484
485 return -1;
486 }
487};
488
489// ------------------------------------------------------------------------
490
491#include "Main.h"
492
493template<class T, class S, class R>
494int RunShell(Configuration &conf)
495{
496 return Main::execute<T, StateMachineAgilent<S, R>>(conf);
497}
498
499void SetupConfiguration(Configuration &conf)
500{
501 po::options_description control("agilent_ctrl control options");
502 control.add_options()
503 ("no-dim", po_bool(), "Disable dim services")
504 ("addr,a", var<string>("10.0.100.220:5025"), "network address of Agilent")
505 ("debug-rx", po_bool(false), "Enable raw debug output wehen receiving data")
506 ("interval", var<uint16_t>(15), "Interval in seconds in which the Agilent status is requested")
507 ("quiet,q", po_bool(true), "Disable printing contents of all received messages (except dynamic data) in clear text.")
508 ;
509
510 conf.AddOptions(control);
511}
512
513/*
514 Extract usage clause(s) [if any] for SYNOPSIS.
515 Translators: "Usage" and "or" here are patterns (regular expressions) which
516 are used to match the usage synopsis in program output. An example from cp
517 (GNU coreutils) which contains both strings:
518 Usage: cp [OPTION]... [-T] SOURCE DEST
519 or: cp [OPTION]... SOURCE... DIRECTORY
520 or: cp [OPTION]... -t DIRECTORY SOURCE...
521 */
522void PrintUsage()
523{
524 cout <<
525 "The agilentctrl controls the FACT camera power supply.\n\n"
526 "\n"
527 "The default is that the program is started without user intercation. "
528 "All actions are supposed to arrive as DimCommands. Using the -c "
529 "option, a local shell can be initialized. With h or help a short "
530 "help message about the usuage can be brought to the screen.\n"
531 "\n"
532 "Usage: agilentctrl [-c type] [OPTIONS]\n"
533 " or: agilentctrl [OPTIONS]\n";
534 cout << endl;
535}
536
537void PrintHelp()
538{
539 Main::PrintHelp<StateMachineAgilent<StateMachine, ConnectionAgilent>>();
540}
541
542int main(int argc, const char* argv[])
543{
544 Configuration conf(argv[0]);
545 conf.SetPrintUsage(PrintUsage);
546 Main::SetupConfiguration(conf);
547 SetupConfiguration(conf);
548
549 if (!conf.DoParse(argc, argv, PrintHelp))
550 return 127;
551
552 //try
553 {
554 // No console access at all
555 if (!conf.Has("console"))
556 {
557 if (conf.Get<bool>("no-dim"))
558 return RunShell<LocalStream, StateMachine, ConnectionAgilent>(conf);
559 else
560 return RunShell<LocalStream, StateMachineDim, ConnectionDimAgilent>(conf);
561 }
562 // Cosole access w/ and w/o Dim
563 if (conf.Get<bool>("no-dim"))
564 {
565 if (conf.Get<int>("console")==0)
566 return RunShell<LocalShell, StateMachine, ConnectionAgilent>(conf);
567 else
568 return RunShell<LocalConsole, StateMachine, ConnectionAgilent>(conf);
569 }
570 else
571 {
572 if (conf.Get<int>("console")==0)
573 return RunShell<LocalShell, StateMachineDim, ConnectionDimAgilent>(conf);
574 else
575 return RunShell<LocalConsole, StateMachineDim, ConnectionDimAgilent>(conf);
576 }
577 }
578 /*catch (std::exception& e)
579 {
580 cerr << "Exception: " << e.what() << endl;
581 return -1;
582 }*/
583
584 return 0;
585}
Note: See TracBrowser for help on using the repository browser.