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

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