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

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