source: trunk/FACT++/src/ftmctrl.cc@ 10732

Last change on this file since 10732 was 10727, checked in by tbretz, 14 years ago
Some fixes about LPext and LPint; DimStaticData::fEnable is now 90 not 80.
File size: 53.1 KB
Line 
1#include <boost/bind.hpp>
2#include <boost/array.hpp>
3#if BOOST_VERSION < 104400
4#if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ > 4))
5#undef BOOST_HAS_RVALUE_REFS
6#endif
7#endif
8#include <boost/thread.hpp>
9#include <boost/asio/error.hpp>
10#include <boost/asio/deadline_timer.hpp>
11
12#include "Dim.h"
13#include "Event.h"
14#include "Shell.h"
15#include "StateMachineDim.h"
16#include "Connection.h"
17#include "Configuration.h"
18#include "Timers.h"
19#include "Console.h"
20#include "Converter.h"
21
22#include "FACT.h"
23#include "tools.h"
24
25#include "LocalControl.h"
26#include "HeadersFTM.h"
27
28
29namespace ba = boost::asio;
30namespace bs = boost::system;
31
32using namespace std;
33
34// ------------------------------------------------------------------------
35
36class ConnectionFTM : public Connection
37{
38 vector<uint16_t> fBuffer;
39
40 bool fHasHeader;
41 int fState;
42
43 bool fIsVerbose;
44 bool fIsDynamicOut;
45 bool fIsHexOutput;
46
47// string fDefaultSetup;
48
49 // --verbose
50 // --hex-out
51 // --dynamic-out
52 // --load-file
53 // --leds
54 // --trigger-interval
55 // --physcis-coincidence
56 // --calib-coincidence
57 // --physcis-window
58 // --physcis-window
59 // --trigger-delay
60 // --time-marker-delay
61 // --dead-time
62 // --clock-conditioner-r0
63 // --clock-conditioner-r1
64 // --clock-conditioner-r8
65 // --clock-conditioner-r9
66 // --clock-conditioner-r11
67 // --clock-conditioner-r13
68 // --clock-conditioner-r14
69 // --clock-conditioner-r15
70 // ...
71
72protected:
73 map<uint16_t, int> fCounter;
74
75 FTM::Header fHeader;
76 FTM::FtuList fFtuList;
77 FTM::StaticData fStaticData;
78 FTM::DynamicData fDynamicData;
79 FTM::Error fError;
80
81 virtual void UpdateFirstHeader()
82 {
83 // FIXME: Message() ?
84 Out() << endl << kBold << "First header received:" << endl;
85 Out() << fHeader;
86 if (fIsHexOutput)
87 Out() << Converter::GetHex<uint16_t>(fHeader, 16) << endl;
88 }
89
90 virtual void UpdateHeader()
91 {
92 // emit service with trigger counter from header
93 if (!fIsVerbose)
94 return;
95
96 if (fHeader.fType==FTM::kDynamicData && !fIsDynamicOut)
97 return;
98
99 Out() << endl << kBold << "Header received:" << endl;
100 Out() << fHeader;
101 if (fIsHexOutput)
102 Out() << Converter::GetHex<uint16_t>(fHeader, 16) << endl;
103 }
104
105 virtual void UpdateFtuList()
106 {
107 if (!fIsVerbose)
108 return;
109
110 Out() << endl << kBold << "FtuList received:" << endl;
111 Out() << fFtuList;
112 if (fIsHexOutput)
113 Out() << Converter::GetHex<uint16_t>(fFtuList, 16) << endl;
114 }
115
116 virtual void UpdateStaticData()
117 {
118 if (!fIsVerbose)
119 return;
120
121 Out() << endl << kBold << "Static data received:" << endl;
122 Out() << fStaticData;
123 if (fIsHexOutput)
124 Out() << Converter::GetHex<uint16_t>(fStaticData, 16) << endl;
125 }
126
127 virtual void UpdateDynamicData()
128 {
129 if (!fIsDynamicOut)
130 return;
131
132 Out() << endl << kBold << "Dynamic data received:" << endl;
133 Out() << fDynamicData;
134 if (fIsHexOutput)
135 Out() << Converter::GetHex<uint16_t>(fDynamicData, 16) << endl;
136 }
137
138 virtual void UpdateError()
139 {
140 if (!fIsVerbose)
141 return;
142
143 Out() << endl << kRed << "Error received:" << endl;
144 Out() << fError;
145 if (fIsHexOutput)
146 Out() << Converter::GetHex<uint16_t>(fError, 16) << endl;
147 }
148
149 virtual void UpdateCounter()
150 {
151 if (!fIsVerbose)
152 return;
153
154 if (!fIsDynamicOut)
155 return;
156
157 Out() << "Received: ";
158 Out() << "H=" << fCounter[FTM::kHeader] << " ";
159 Out() << "S=" << fCounter[FTM::kStaticData] << " ";
160 Out() << "D=" << fCounter[FTM::kDynamicData] << " ";
161 Out() << "F=" << fCounter[FTM::kFtuList] << " ";
162 Out() << "E=" << fCounter[FTM::kErrorList] << " ";
163 Out() << "R=" << fCounter[FTM::kRegister] << endl;
164 }
165
166 bool CheckConsistency()
167 {
168 bool warn1 = false;
169 if (fStaticData.IsEnabled(FTM::StaticData::kPedestal) != (fStaticData.GetSequencePed() >0) ||
170 fStaticData.IsEnabled(FTM::StaticData::kLPint) != (fStaticData.GetSequenceLPint()>0) ||
171 fStaticData.IsEnabled(FTM::StaticData::kLPext) != (fStaticData.GetSequenceLPext()>0))
172 {
173 warn1 = true;
174 fStaticData.Enable(FTM::StaticData::kPedestal, fStaticData.GetSequencePed()>0);
175 fStaticData.Enable(FTM::StaticData::kLPint, fStaticData.GetSequenceLPint()>0);
176 fStaticData.Enable(FTM::StaticData::kLPext, fStaticData.GetSequenceLPext()>0);
177 }
178
179 bool warn2 = false;
180 const uint16_t ref = fStaticData[0].fPrescaling;
181 for (int i=1; i<40; i++)
182 {
183 if (fStaticData[i].fPrescaling != ref)
184 {
185 warn2 = true;
186 fStaticData[i].fPrescaling = ref;
187 }
188 }
189
190 if (warn1)
191 Warn("GeneralSettings not consistent with trigger sequence.");
192 if (warn2)
193 Warn("Prescaling not consistent for all boards.");
194
195 return !warn1 && !warn2;
196 }
197
198private:
199 void HandleReceivedData(const bs::error_code& err, size_t bytes_received, int /*type*/)
200 {
201 // Do not schedule a new read if the connection failed.
202 if (bytes_received==0 || err)
203 {
204 if (err==ba::error::eof)
205 Warn("Connection closed by remote host (FTM).");
206
207 // 107: Transport endpoint is not connected (bs::error_code(107, bs::system_category))
208 // 125: Operation canceled
209 if (err && err!=ba::error::eof && // Connection closed by remote host
210 err!=ba::error::basic_errors::not_connected && // Connection closed by remote host
211 err!=ba::error::basic_errors::operation_aborted) // Connection closed by us
212 {
213 stringstream str;
214 str << "Reading from " << URL() << ": " << err.message() << " (" << err << ")";// << endl;
215 Error(str);
216 }
217 PostClose(err!=ba::error::basic_errors::operation_aborted);
218 return;
219 }
220
221 // If we have not yet received a header we expect one now
222 // This could be moved to a HandleReceivedHeader function
223 if (!fHasHeader)
224 {
225 if (bytes_received!=sizeof(FTM::Header))
226 {
227 stringstream str;
228 str << "Excepted " << sizeof(FTM::Header) << " bytes (FTM::Header) but received " << bytes_received << ".";
229 Error(str);
230 PostClose(false);
231 return;
232 }
233
234 fHeader = fBuffer;
235
236 // Check the data integrity
237 if (fHeader.fDelimiter!=FTM::kDelimiterStart)
238 {
239 stringstream str;
240 str << "Invalid header received: start delimiter wrong, received " << hex << fHeader.fDelimiter << " expected " << FTM::kDelimiterStart << ".";
241 Error(str);
242 PostClose(false);
243 return;
244 }
245
246 fHasHeader = true;
247
248 // Convert FTM state into FtmCtrl state
249 switch (fHeader.fState)
250 {
251 case FTM::kFtmIdle:
252 case FTM::kFtmConfig:
253 fState = FTM::kIdle;
254 break;
255
256 case FTM::kFtmCalib:
257 case FTM::kFtmRunning:
258 fState = FTM::kTakingData;
259 break;
260 }
261
262 if (++fCounter[FTM::kHeader]==1)
263 UpdateFirstHeader();
264
265 UpdateCounter();
266 UpdateHeader();
267
268 // Start reading of data
269 switch (fHeader.fType)
270 {
271 case FTM::kStaticData:
272 case FTM::kDynamicData:
273 case FTM::kFtuList:
274 case FTM::kRegister:
275 case FTM::kErrorList:
276 // This is not very efficient because the space is reallocated
277 // maybe we can check if the capacity of the std::vector
278 // is ever decreased. If not, everythign is fine.
279 fBuffer.resize(fHeader.fDataSize);
280 AsyncRead(ba::buffer(fBuffer));
281 AsyncWait(fInTimeout, 50, &Connection::HandleReadTimeout);
282 return;
283
284 default:
285 stringstream str;
286 str << "Unknonw type " << fHeader.fType << " in received header." << endl;
287 Error(str);
288 PostClose(false);
289 return;
290 }
291
292 return;
293 }
294
295 // Check the data integrity (check end delimiter)
296 if (ntohs(fBuffer.back())!=FTM::kDelimiterEnd)
297 {
298 stringstream str;
299 str << "Invalid data received: end delimiter wrong, received ";
300 str << hex << ntohs(fBuffer.back()) << " expected " << FTM::kDelimiterEnd << ".";
301 Error(str);
302 PostClose(false);
303 return;
304 }
305
306 // Remove end delimiter
307 fBuffer.pop_back();
308
309 try
310 {
311 // If we have already received a header this is the data now
312 // This could be moved to a HandleReceivedData function
313
314 fCounter[fHeader.fType]++;
315 UpdateCounter();
316
317 switch (fHeader.fType)
318 {
319 case FTM::kFtuList:
320 fFtuList = fBuffer;
321 UpdateFtuList();
322 break;
323
324 case FTM::kStaticData:
325 fStaticData = fBuffer;
326
327 if (fCounter[FTM::kStaticData]==1)
328 if (!CheckConsistency())
329 {
330 CmdSendStatDat();
331 break;
332 }
333
334 UpdateStaticData();
335 break;
336
337 case FTM::kDynamicData:
338 fDynamicData = fBuffer;
339 UpdateDynamicData();
340 break;
341
342 case FTM::kRegister:
343 if (fIsVerbose)
344 {
345 Out() << endl << kBold << "Register received: " << endl;
346 Out() << "Addr: " << ntohs(fBuffer[0]) << endl;
347 Out() << "Value: " << ntohs(fBuffer[1]) << endl;
348 }
349 break;
350
351 case FTM::kErrorList:
352 fError = fBuffer;
353 UpdateError();
354 break;
355
356 default:
357 stringstream str;
358 str << "Unknonw type " << fHeader.fType << " in header." << endl;
359 Error(str);
360 PostClose(false);
361 return;
362 }
363 }
364 catch (const logic_error &e)
365 {
366 stringstream str;
367 str << "Exception converting buffer into data structure: " << e.what();
368 Error(str);
369 PostClose(false);
370 return;
371 }
372
373 fInTimeout.cancel();
374
375 fHeader.clear();
376 fHasHeader = false;
377 fBuffer.resize(sizeof(FTM::Header)/2);
378 AsyncRead(ba::buffer(fBuffer));
379 }
380
381 // This is called when a connection was established
382 void ConnectionEstablished()
383 {
384 fState = FTM::kConnected;
385 fCounter.clear();
386
387 fHeader.clear();
388 fHasHeader = false;
389 fBuffer.resize(sizeof(FTM::Header)/2);
390 AsyncRead(ba::buffer(fBuffer));
391
392// if (!fDefaultSetup.empty())
393// LoadStaticData(fDefaultSetup);
394
395 // Get a header and configdata!
396 CmdReqStatDat();
397
398 // get the DNA of the FTUs
399 CmdPing();
400 }
401
402 void HandleReadTimeout(const bs::error_code &error)
403 {
404 if (error && error!=ba::error::basic_errors::operation_aborted)
405 {
406 stringstream str;
407 str << "Read timeout of " << URL() << ": " << error.message() << " (" << error << ")";// << endl;
408 Error(str);
409
410 PostClose();
411 return;
412
413 }
414
415 if (!is_open())
416 {
417 // For example: Here we could schedule a new accept if we
418 // would not want to allow two connections at the same time.
419 return;
420 }
421
422 // Check whether the deadline has passed. We compare the deadline
423 // against the current time since a new asynchronous operation
424 // may have moved the deadline before this actor had a chance
425 // to run.
426 if (fInTimeout.expires_at() > ba::deadline_timer::traits_type::now())
427 return;
428
429 Error("Timeout reading data from "+URL());
430
431 PostClose();
432 }
433
434
435 template<size_t N>
436 void PostCmd(boost::array<uint16_t, N> dat, uint16_t u1=0, uint16_t u2=0, uint16_t u3=0, uint16_t u4=0)
437 {
438 boost::array<uint16_t, 5> cmd = {{ '@', u1, u2, u3, u4 }};
439
440 stringstream msg;
441 msg << "Sending command:" << hex;
442 msg << " 0x" << setw(4) << setfill('0') << cmd[0];
443 msg << " 0x" << setw(4) << setfill('0') << u1;
444 msg << " 0x" << setw(4) << setfill('0') << u2;
445 msg << " 0x" << setw(4) << setfill('0') << u3;
446 msg << " 0x" << setw(4) << setfill('0') << u4;
447 msg << " (+" << dec << dat.size() << " words)";
448 Message(msg);
449
450 vector<uint16_t> out(cmd.size()+dat.size());
451
452 transform(cmd.begin(), cmd.end(), out.begin(), htons);
453 transform(dat.begin(), dat.end(), out.begin()+cmd.size(), htons);
454
455 PostMessage(out);
456 }
457
458 void PostCmd(vector<uint16_t> dat, uint16_t u1=0, uint16_t u2=0, uint16_t u3=0, uint16_t u4=0)
459 {
460 boost::array<uint16_t, 5> cmd = {{ '@', u1, u2, u3, u4 }};
461
462 stringstream msg;
463 msg << "Sending command:" << hex;
464 msg << " 0x" << setw(4) << setfill('0') << cmd[0];
465 msg << " 0x" << setw(4) << setfill('0') << u1;
466 msg << " 0x" << setw(4) << setfill('0') << u2;
467 msg << " 0x" << setw(4) << setfill('0') << u3;
468 msg << " 0x" << setw(4) << setfill('0') << u4;
469 msg << " (+" << dec << dat.size() << " words)";
470 Message(msg);
471
472 vector<uint16_t> out(cmd.size()+dat.size());
473
474 transform(cmd.begin(), cmd.end(), out.begin(), htons);
475 copy(dat.begin(), dat.end(), out.begin()+cmd.size());
476
477 PostMessage(out);
478 }
479
480 void PostCmd(uint16_t u1=0, uint16_t u2=0, uint16_t u3=0, uint16_t u4=0)
481 {
482 PostCmd(boost::array<uint16_t, 0>(), u1, u2, u3, u4);
483 }
484public:
485
486 static const uint16_t kMaxAddr;
487
488public:
489 ConnectionFTM(ba::io_service& ioservice, MessageImp &imp) : Connection(ioservice, imp()),
490 fState(0), fIsVerbose(true), fIsDynamicOut(true), fIsHexOutput(true)
491 {
492 SetLogStream(&imp);
493 }
494
495 void CmdToggleLed()
496 {
497 PostCmd(FTM::kCmdToggleLed);
498 }
499
500 void CmdPing()
501 {
502 PostCmd(FTM::kCmdPing);
503 }
504
505 void CmdReqDynDat()
506 {
507 PostCmd(FTM::kCmdRead, FTM::kCmdDynamicData);
508 }
509
510 void CmdReqStatDat()
511 {
512 PostCmd(FTM::kCmdRead, FTM::kCmdStaticData);
513 }
514
515 void CmdSendStatDat()
516 {
517 PostCmd(fStaticData.HtoN(), FTM::kCmdWrite, FTM::kCmdStaticData);
518
519 // Request the changed configuration to ensure the
520 // change is distributed in the network
521 CmdReqStatDat();
522 }
523
524 void CmdStartRun()
525 {
526 PostCmd(FTM::kCmdStartRun, FTM::kStartRun);
527
528 // Update state information by requesting a new header
529 CmdGetRegister(0);
530 }
531
532 void CmdStopRun()
533 {
534 PostCmd(FTM::kCmdStopRun);
535
536 // Update state information by requesting a new header
537 CmdGetRegister(0);
538 }
539
540 void CmdTakeNevents(uint32_t n)
541 {
542 const boost::array<uint16_t, 2> data = {{ uint16_t(n>>16), uint16_t(n&0xffff) }};
543 PostCmd(data, FTM::kCmdStartRun, FTM::kTakeNevents);
544
545 // Update state information by requesting a new header
546 CmdGetRegister(0);
547 }
548
549 bool CmdSetRegister(uint16_t addr, uint16_t val)
550 {
551 if (addr>kMaxAddr)
552 return false;
553
554 const boost::array<uint16_t, 2> data = {{ addr, val }};
555 PostCmd(data, FTM::kCmdWrite, FTM::kCmdRegister);
556
557 // Request the changed configuration to ensure the
558 // change is distributed in the network
559 CmdReqStatDat();
560
561 return true;
562 }
563
564 bool CmdGetRegister(uint16_t addr)
565 {
566 if (addr>kMaxAddr)
567 return false;
568
569 const boost::array<uint16_t, 1> data = {{ addr }};
570 PostCmd(data, FTM::kCmdRead, FTM::kCmdRegister);
571
572 return true;
573 }
574
575 bool CmdDisableReports(bool b)
576 {
577 PostCmd(FTM::kCmdDisableReports, b ? uint16_t(0) : uint16_t(1));
578 return true;
579 }
580
581 void SetVerbose(bool b)
582 {
583 fIsVerbose = b;
584 }
585
586 void SetHexOutput(bool b)
587 {
588 fIsHexOutput = b;
589 }
590
591 void SetDynamicOut(bool b)
592 {
593 fIsDynamicOut = b;
594 }
595/*
596 void SetDefaultSetup(const string &file)
597 {
598 fDefaultSetup = file;
599 }
600*/
601 bool LoadStaticData(string name)
602 {
603 if (name.rfind(".bin")!=name.length()-5)
604 name += ".bin";
605
606 ifstream fin(name);
607 if (!fin)
608 return false;
609
610 FTM::StaticData data;
611
612 fin.read(reinterpret_cast<char*>(&data), sizeof(FTM::StaticData));
613
614 if (fin.gcount()<streamsize(sizeof(FTM::StaticData)))
615 return false;
616
617 if (fin.fail() || fin.eof())
618 return false;
619
620 if (fin.peek()!=-1)
621 return false;
622
623 fStaticData = data;
624
625 CmdSendStatDat();
626
627 return true;
628 }
629
630 bool SaveStaticData(string name) const
631 {
632 if (name.rfind(".bin")!=name.length()-5)
633 name += ".bin";
634
635 ofstream fout(name);
636 if (!fout)
637 return false;
638
639 fout.write(reinterpret_cast<const char*>(&fStaticData), sizeof(FTM::StaticData));
640
641 return !fout.bad();
642 }
643
644 bool SetThreshold(int32_t patch, int32_t value)
645 {
646 if (patch>159)
647 return false;
648
649 if (value<0 || value>0xffff)
650 return false;
651
652 if (patch<0)
653 {
654 bool ident = true;
655 for (int i=0; i<160; i++)
656 if (fStaticData[i/4].fDAC[patch%4] != value)
657 {
658 ident = false;
659 break;
660 }
661
662 if (ident)
663 return true;
664
665 for (int i=0; i<160; i++)
666 fStaticData[i/4].fDAC[i%4] = value;
667 }
668 else
669 {
670 if (fStaticData[patch/4].fDAC[patch%4] == value)
671 return true;
672
673 fStaticData[patch/4].fDAC[patch%4] = value;
674 }
675
676 // Maybe move to a "COMMIT" command?
677 CmdSendStatDat();
678
679 return true;
680 }
681
682 bool SetPrescaling(uint32_t value)
683 {
684 if (value>0xffff)
685 return false;
686
687 bool ident = true;
688 for (int i=0; i<40; i++)
689 if (fStaticData[i].fPrescaling != value)
690 {
691 ident = false;
692 break;
693 }
694
695 if (ident)
696 return true;
697
698 for (int i=0; i<40; i++)
699 fStaticData[i].fPrescaling = value;
700
701 // Maybe move to a "COMMIT" command?
702 CmdSendStatDat();
703
704 return true;
705 }
706
707 bool EnableFTU(int32_t board, bool enable)
708 {
709 if (board>39)
710 return false;
711
712 if (board<0)
713 {
714 if (enable)
715 fStaticData.EnableAllFTU();
716 else
717 fStaticData.DisableAllFTU();
718 }
719 else
720 {
721 if (enable)
722 fStaticData.EnableFTU(board);
723 else
724 fStaticData.DisableFTU(board);
725
726 }
727
728 // Maybe move to a "COMMIT" command?
729 CmdSendStatDat();
730
731 return true;
732 }
733
734 bool ToggleFTU(uint32_t board)
735 {
736 if (board>39)
737 return false;
738
739 fStaticData.ToggleFTU(board);
740
741 // Maybe move to a "COMMIT" command?
742 CmdSendStatDat();
743
744 return true;
745 }
746
747 bool SetVal(uint16_t *dest, uint32_t val, uint32_t max)
748 {
749 if (val>max)
750 return false;
751
752 if (*dest==val)
753 return true;
754
755 *dest = val;
756
757 CmdSendStatDat();
758
759 return true;
760 }
761
762 bool SetTriggerInterval(uint32_t val)
763 {
764 return SetVal(&fStaticData.fTriggerInterval, val,
765 FTM::StaticData::kMaxTriggerInterval);
766 }
767
768 bool SetTriggerDelay(uint32_t val)
769 {
770 return SetVal(&fStaticData.fDelayTrigger, val,
771 FTM::StaticData::kMaxDelayTrigger);
772 }
773
774 bool SetTimeMarkerDelay(uint32_t val)
775 {
776 return SetVal(&fStaticData.fDelayTimeMarker, val,
777 FTM::StaticData::kMaxDelayTimeMarker);
778 }
779
780 bool SetDeadTime(uint32_t val)
781 {
782 return SetVal(&fStaticData.fDeadTime, val,
783 FTM::StaticData::kMaxDeadTime);
784 }
785
786 void Enable(FTM::StaticData::GeneralSettings type, bool enable)
787 {
788 fStaticData.Enable(type, enable);
789 }
790
791 bool SetTriggerSeq(const uint8_t d[3])
792 {
793 const uint16_t oldset = fStaticData.fGeneralSettings;
794 const uint16_t oldseq = fStaticData.fTriggerSequence;
795
796 if (d[0]>FTM::StaticData::kMaxSequence ||
797 d[1]>FTM::StaticData::kMaxSequence ||
798 d[2]>FTM::StaticData::kMaxSequence)
799 return false;
800
801 fStaticData.Enable(FTM::StaticData::kPedestal, d[0]>0);
802 fStaticData.Enable(FTM::StaticData::kLPext, d[1]>0);
803 fStaticData.Enable(FTM::StaticData::kLPint, d[2]>0);
804
805 fStaticData.fTriggerSequence =
806 (uint16_t(d[0])<<10) | (uint16_t(d[2])<<5) | uint16_t(d[1]);
807
808 if (oldseq!=fStaticData.fTriggerSequence || oldset!=fStaticData.fGeneralSettings)
809 CmdSendStatDat();
810
811 return true;
812 }
813
814 bool SetTriggerMultiplicity(uint16_t n)
815 {
816 if (n==0 || n>FTM::StaticData::kMaxMultiplicity)
817 return false;
818
819 if (n==fStaticData.fMultiplicityPhysics)
820 return true;
821
822 fStaticData.fMultiplicityPhysics = n;
823
824 CmdSendStatDat();
825
826 return true;
827 }
828
829 bool SetTriggerWindow(uint16_t win)
830 {
831 if (win>FTM::StaticData::kMaxWindow)
832 return false;
833
834 if (win==fStaticData.fWindowPhysics)
835 return true;
836
837 fStaticData.fWindowPhysics = win;
838
839 CmdSendStatDat();
840
841 return true;
842 }
843
844 bool SetCalibMultiplicity(uint16_t n)
845 {
846 if (n==0 || n>FTM::StaticData::kMaxMultiplicity)
847 return false;
848
849 if (n==fStaticData.fMultiplicityCalib)
850 return true;
851
852 fStaticData.fMultiplicityCalib = n;
853
854 CmdSendStatDat();
855
856 return true;
857 }
858
859 bool SetCalibWindow(uint16_t win)
860 {
861 if (win>FTM::StaticData::kMaxWindow)
862 return false;
863
864 if (win==fStaticData.fWindowCalib)
865 return true;
866
867 fStaticData.fWindowCalib = win;
868
869 CmdSendStatDat();
870
871 return true;
872 }
873
874 int GetState() const { return IsConnected() ? fState : (int)FTM::kDisconnected; }
875};
876
877const uint16_t ConnectionFTM::kMaxAddr = 0xfff;
878
879// ------------------------------------------------------------------------
880
881#include "DimDescriptionService.h"
882
883class ConnectionDimFTM : public ConnectionFTM
884{
885private:
886
887 DimDescribedService fDimPassport;
888 DimDescribedService fDimTriggerCounter;
889 DimDescribedService fDimError;
890 DimDescribedService fDimFtuList;
891 DimDescribedService fDimStaticData;
892 DimDescribedService fDimDynamicData;
893 DimDescribedService fDimCounter;
894
895 template<class T>
896 void Update(DimDescribedService &svc, const T &data) const
897 {
898 //cout << "Update: " << svc.getName() << " (" << sizeof(T) << ")" << endl;
899 svc.setData(const_cast<T*>(&data), sizeof(T));
900 svc.updateService();
901 }
902
903 void UpdateFirstHeader()
904 {
905 ConnectionFTM::UpdateFirstHeader();
906
907 const FTM::DimPassport data(fHeader);
908 Update(fDimPassport, data);
909 }
910
911 void UpdateHeader()
912 {
913 ConnectionFTM::UpdateHeader();
914
915 const FTM::DimTriggerCounter data(fHeader);
916 Update(fDimTriggerCounter, data);
917 }
918
919 void UpdateFtuList()
920 {
921 ConnectionFTM::UpdateFtuList();
922
923 const FTM::DimFtuList data(fHeader, fFtuList);
924 Update(fDimFtuList, data);
925 }
926
927 void UpdateStaticData()
928 {
929 ConnectionFTM::UpdateStaticData();
930
931 const FTM::DimStaticData data(fHeader, fStaticData);
932 Update(fDimStaticData, data);
933 }
934
935 void UpdateDynamicData()
936 {
937 ConnectionFTM::UpdateDynamicData();
938
939 const FTM::DimDynamicData data(fHeader, fDynamicData);
940 Update(fDimDynamicData, data);
941 }
942
943 void UpdateError()
944 {
945 ConnectionFTM::UpdateError();
946
947 const FTM::DimError data(fHeader, fError);
948 Update(fDimError, data);
949 }
950
951 void UpdateCounter()
952 {
953 ConnectionFTM::UpdateCounter();
954
955 const uint32_t counter[6] =
956 {
957 fCounter[FTM::kHeader],
958 fCounter[FTM::kStaticData],
959 fCounter[FTM::kDynamicData],
960 fCounter[FTM::kFtuList],
961 fCounter[FTM::kErrorList],
962 fCounter[FTM::kRegister],
963 };
964
965 Update(fDimCounter, counter);
966 }
967
968public:
969 ConnectionDimFTM(ba::io_service& ioservice, MessageImp &imp) :
970 ConnectionFTM(ioservice, imp),
971 fDimPassport ("FTM_CONTROL/PASSPORT", "X:1;S:1", ""),
972 fDimTriggerCounter("FTM_CONTROL/TRIGGER_COUNTER", "X:1;I:1", ""),
973 fDimError ("FTM_CONTROL/ERROR", "X:1;S:1;S:28", ""),
974 fDimFtuList ("FTM_CONTROL/FTU_LIST", "X:1;X:1;S:1;C:4;X:40;C:40;C:40", ""),
975 fDimStaticData ("FTM_CONTROL/STATIC_DATA", "X:1;S:1;S:1;X:1;S:1;S:3;S:1;S:1;S:1;S:1;S:1;S:1;I:1;S:8;S:90;S:160;S:40;S:40", ""),
976 fDimDynamicData ("FTM_CONTROL/DYNAMIC_DATA", "X:1;X:1;F:4;I:160;I:40;S:40;S:40", ""),
977 fDimCounter ("FTM_CONTROL/COUNTER", "I:6", "")
978 {
979 }
980
981 // A B [C] [D] E [F] G H [I] J K [L] M N O P Q R [S] T U V W [X] Y Z
982};
983
984// ------------------------------------------------------------------------
985
986template <class T, class S>
987class StateMachineFTM : public T, public ba::io_service, public ba::io_service::work
988{
989 int Wrap(boost::function<void()> f)
990 {
991 f();
992 return T::GetCurrentState();
993 }
994
995 boost::function<int(const EventImp &)> Wrapper(boost::function<void()> func)
996 {
997 return boost::bind(&StateMachineFTM::Wrap, this, func);
998 }
999
1000private:
1001 S fFTM;
1002
1003 enum states_t
1004 {
1005 kStateDisconnected = FTM::kDisconnected,
1006 kStateConnected = FTM::kConnected,
1007 kStateIdle = FTM::kIdle,
1008 kStateTakingData = FTM::kTakingData,
1009
1010 kCmdTest
1011 };
1012
1013 bool CheckEventSize(size_t has, const char *name, size_t size)
1014 {
1015 if (has==size)
1016 return true;
1017
1018 stringstream msg;
1019 msg << name << " - Received event has " << has << " bytes, but expected " << size << ".";
1020 T::Fatal(msg);
1021 return false;
1022 }
1023
1024 int SetRegister(const EventImp &evt)
1025 {
1026 if (!CheckEventSize(evt.GetSize(), "SetRegister", 8))
1027 return T::kSM_FatalError;
1028
1029 const unsigned int *dat = reinterpret_cast<const unsigned int*>(evt.GetData());
1030
1031 if (dat[1]>uint16_t(-1))
1032 {
1033 stringstream msg;
1034 msg << hex << "Value " << dat[1] << " out of range.";
1035 T::Error(msg);
1036 return T::GetCurrentState();
1037 }
1038
1039
1040 if (dat[0]>uint16_t(-1) || !fFTM.CmdSetRegister(dat[0], dat[1]))
1041 {
1042 stringstream msg;
1043 msg << hex << "Address " << dat[0] << " out of range.";
1044 T::Error(msg);
1045 }
1046
1047 return T::GetCurrentState();
1048 }
1049
1050 int GetRegister(const EventImp &evt)
1051 {
1052 if (!CheckEventSize(evt.GetSize(), "GetRegister", 4))
1053 return T::kSM_FatalError;
1054
1055 const unsigned int addr = evt.GetInt();
1056 if (addr>uint16_t(-1) || !fFTM.CmdGetRegister(addr))
1057 {
1058 stringstream msg;
1059 msg << hex << "Address " << addr << " out of range.";
1060 T::Error(msg);
1061 }
1062
1063 return T::GetCurrentState();
1064 }
1065
1066 int TakeNevents(const EventImp &evt)
1067 {
1068 if (!CheckEventSize(evt.GetSize(), "TakeNevents", 4))
1069 return T::kSM_FatalError;
1070
1071 const unsigned int dat = evt.GetUInt();
1072
1073 /*
1074 if (dat[1]>uint32_t(-1))
1075 {
1076 stringstream msg;
1077 msg << hex << "Value " << dat[1] << " out of range.";
1078 T::Error(msg);
1079 return T::GetCurrentState();
1080 }*/
1081
1082 fFTM.CmdTakeNevents(dat);
1083
1084 return T::GetCurrentState();
1085 }
1086
1087 int DisableReports(const EventImp &evt)
1088 {
1089 if (!CheckEventSize(evt.GetSize(), "DisableReports", 1))
1090 return T::kSM_FatalError;
1091
1092 fFTM.CmdDisableReports(evt.GetText()[0]!=0);
1093
1094 return T::GetCurrentState();
1095 }
1096
1097 int SetVerbosity(const EventImp &evt)
1098 {
1099 if (!CheckEventSize(evt.GetSize(), "SetVerbosity", 1))
1100 return T::kSM_FatalError;
1101
1102 fFTM.SetVerbose(evt.GetText()[0]!=0);
1103
1104 return T::GetCurrentState();
1105 }
1106
1107 int SetHexOutput(const EventImp &evt)
1108 {
1109 if (!CheckEventSize(evt.GetSize(), "SetHexOutput", 1))
1110 return T::kSM_FatalError;
1111
1112 fFTM.SetHexOutput(evt.GetText()[0]!=0);
1113
1114 return T::GetCurrentState();
1115 }
1116
1117 int SetDynamicOut(const EventImp &evt)
1118 {
1119 if (!CheckEventSize(evt.GetSize(), "SetDynamicOut", 1))
1120 return T::kSM_FatalError;
1121
1122 fFTM.SetDynamicOut(evt.GetText()[0]!=0);
1123
1124 return T::GetCurrentState();
1125 }
1126
1127 int LoadStaticData(const EventImp &evt)
1128 {
1129 if (fFTM.LoadStaticData(evt.GetString()))
1130 return T::GetCurrentState();
1131
1132 stringstream msg;
1133 msg << "Loading static data from file '" << evt.GetString() << "' failed ";
1134
1135 if (errno)
1136 msg << "(" << strerror(errno) << ")";
1137 else
1138 msg << "(wrong size, expected " << sizeof(FTM::StaticData) << " bytes)";
1139
1140 T::Warn(msg);
1141
1142 return T::GetCurrentState();
1143 }
1144
1145 int SaveStaticData(const EventImp &evt)
1146 {
1147 if (fFTM.SaveStaticData(evt.GetString()))
1148 return T::GetCurrentState();
1149
1150 stringstream msg;
1151 msg << "Writing static data to file '" << evt.GetString() << "' failed ";
1152 msg << "(" << strerror(errno) << ")";
1153
1154 T::Warn(msg);
1155
1156 return T::GetCurrentState();
1157 }
1158
1159 int SetThreshold(const EventImp &evt)
1160 {
1161 if (!CheckEventSize(evt.GetSize(), "SetThreshold", 8))
1162 return T::kSM_FatalError;
1163
1164 const int32_t *data = reinterpret_cast<const int32_t*>(evt.GetData());
1165
1166 if (!fFTM.SetThreshold(data[0], data[1]))
1167 T::Warn("SetThreshold - Maximum allowed patch number 159, valid value range 0-0xffff");
1168
1169 return T::GetCurrentState();
1170 }
1171
1172 int EnableFTU(const EventImp &evt)
1173 {
1174 if (!CheckEventSize(evt.GetSize(), "EnableFTU", 5))
1175 return T::kSM_FatalError;
1176
1177 const int32_t &board = *reinterpret_cast<const int32_t*>(evt.GetText());
1178 const int8_t &enable = *reinterpret_cast<const int8_t*>(evt.GetText()+4);
1179
1180 if (!fFTM.EnableFTU(board, enable))
1181 T::Warn("EnableFTU - Board number must be <40.");
1182
1183 return T::GetCurrentState();
1184 }
1185
1186 int ToggleFTU(const EventImp &evt)
1187 {
1188 if (!CheckEventSize(evt.GetSize(), "ToggleFTU", 4))
1189 return T::kSM_FatalError;
1190
1191 if (!fFTM.ToggleFTU(evt.GetInt()))
1192 T::Warn("ToggleFTU - Allowed range of boards 0-39.");
1193
1194 return T::GetCurrentState();
1195 }
1196
1197 int SetTriggerInterval(const EventImp &evt)
1198 {
1199 if (!CheckEventSize(evt.GetSize(), "SetTriggerInterval", 4))
1200 return T::kSM_FatalError;
1201
1202 if (!fFTM.SetTriggerInterval(evt.GetInt()))
1203 T::Warn("SetTriggerInterval - Value out of range.");
1204
1205 return T::GetCurrentState();
1206 }
1207
1208 int SetTriggerDelay(const EventImp &evt)
1209 {
1210 if (!CheckEventSize(evt.GetSize(), "SetTriggerDelay", 4))
1211 return T::kSM_FatalError;
1212
1213 if (!fFTM.SetTriggerDelay(evt.GetInt()))
1214 T::Warn("SetTriggerDealy - Value out of range.");
1215
1216 return T::GetCurrentState();
1217 }
1218
1219 int SetTimeMarkerDelay(const EventImp &evt)
1220 {
1221 if (!CheckEventSize(evt.GetSize(), "SetTimeMarkerDelay", 4))
1222 return T::kSM_FatalError;
1223
1224 if (!fFTM.SetTimeMarkerDelay(evt.GetInt()))
1225 T::Warn("SetTimeMarkerDelay - Value out of range.");
1226
1227 return T::GetCurrentState();
1228 }
1229
1230 int SetPrescaling(const EventImp &evt)
1231 {
1232 if (!CheckEventSize(evt.GetSize(), "SetPrescaling", 4))
1233 return T::kSM_FatalError;
1234
1235 if (!fFTM.SetPrescaling(evt.GetInt()-1))
1236 T::Warn("SetPrescaling - Value out of range.");
1237
1238 return T::GetCurrentState();
1239 }
1240
1241 int SetTriggerSeq(const EventImp &evt)
1242 {
1243 if (!CheckEventSize(evt.GetSize(), "SetTriggerSeq", 3))
1244 return T::kSM_FatalError;
1245
1246 const uint8_t *data = reinterpret_cast<const uint8_t*>(evt.GetData());
1247
1248 if (!fFTM.SetTriggerSeq(data))
1249 T::Warn("SetTriggerSeq - Value out of range.");
1250
1251 return T::GetCurrentState();
1252 }
1253
1254 int SetDeadTime(const EventImp &evt)
1255 {
1256 if (!CheckEventSize(evt.GetSize(), "SetDeadTime", 4))
1257 return T::kSM_FatalError;
1258
1259 if (!fFTM.SetDeadTime(evt.GetInt()))
1260 T::Warn("SetDeadTime - Value out of range.");
1261
1262 return T::GetCurrentState();
1263 }
1264
1265 int SetTriggerMultiplicity(const EventImp &evt)
1266 {
1267 if (!CheckEventSize(evt.GetSize(), "SetTriggerMultiplicity", 2))
1268 return T::kSM_FatalError;
1269
1270 if (!fFTM.SetTriggerMultiplicity(evt.GetUShort()))
1271 T::Warn("SetTriggerMultiplicity - Value out of range.");
1272
1273 return T::GetCurrentState();
1274 }
1275
1276 int SetCalibMultiplicity(const EventImp &evt)
1277 {
1278 if (!CheckEventSize(evt.GetSize(), "SetCalibMultiplicity", 2))
1279 return T::kSM_FatalError;
1280
1281 if (!fFTM.SetCalibMultiplicity(evt.GetUShort()))
1282 T::Warn("SetCalibMultiplicity - Value out of range.");
1283
1284 return T::GetCurrentState();
1285 }
1286
1287 int SetTriggerWindow(const EventImp &evt)
1288 {
1289 if (!CheckEventSize(evt.GetSize(), "SetTriggerWindow", 2))
1290 return T::kSM_FatalError;
1291
1292 if (!fFTM.SetTriggerWindow(evt.GetUShort()))
1293 T::Warn("SetTriggerWindow - Value out of range.");
1294
1295 return T::GetCurrentState();
1296 }
1297
1298 int SetCalibWindow(const EventImp &evt)
1299 {
1300 if (!CheckEventSize(evt.GetSize(), "SetCalibWindow", 2))
1301 return T::kSM_FatalError;
1302
1303 if (!fFTM.SetCalibWindow(evt.GetUShort()))
1304 T::Warn("SetCalibWindow - Value out of range.");
1305
1306 return T::GetCurrentState();
1307 }
1308
1309
1310 int Enable(const EventImp &evt, FTM::StaticData::GeneralSettings type)
1311 {
1312 if (!CheckEventSize(evt.GetSize(), "Enable", 1))
1313 return T::kSM_FatalError;
1314
1315 fFTM.Enable(type, evt.GetText()[0]!=0);
1316
1317 return T::GetCurrentState();
1318 }
1319
1320 int Disconnect()
1321 {
1322 // Close all connections
1323 fFTM.PostClose(false);
1324
1325 /*
1326 // Now wait until all connection have been closed and
1327 // all pending handlers have been processed
1328 poll();
1329 */
1330
1331 return T::GetCurrentState();
1332 }
1333
1334 int Reconnect(const EventImp &evt)
1335 {
1336 // Close all connections to supress the warning in SetEndpoint
1337 fFTM.PostClose(false);
1338
1339 // Now wait until all connection have been closed and
1340 // all pending handlers have been processed
1341 poll();
1342
1343 if (evt.GetText()[0]!=0)
1344 fFTM.SetEndpoint(evt.GetString());
1345
1346 // Now we can reopen the connection
1347 fFTM.PostClose(true);
1348
1349 return T::GetCurrentState();
1350 }
1351
1352 /*
1353 int Transition(const Event &evt)
1354 {
1355 switch (evt.GetTargetState())
1356 {
1357 case kStateDisconnected:
1358 case kStateConnected:
1359 }
1360
1361 return T::kSM_FatalError;
1362 }*/
1363
1364 int Execute()
1365 {
1366 // Dispatch (execute) at most one handler from the queue. In contrary
1367 // to run_one(), it doesn't wait until a handler is available
1368 // which can be dispatched, so poll_one() might return with 0
1369 // handlers dispatched. The handlers are always dispatched/executed
1370 // synchronously, i.e. within the call to poll_one()
1371 poll_one();
1372
1373 return fFTM.GetState();
1374 }
1375
1376public:
1377 StateMachineFTM(ostream &out=cout) :
1378 T(out, "FTM_CONTROL"), ba::io_service::work(static_cast<ba::io_service&>(*this)),
1379 fFTM(*this, *this)
1380 {
1381 // ba::io_service::work is a kind of keep_alive for the loop.
1382 // It prevents the io_service to go to stopped state, which
1383 // would prevent any consecutive calls to run()
1384 // or poll() to do nothing. reset() could also revoke to the
1385 // previous state but this might introduce some overhead of
1386 // deletion and creation of threads and more.
1387
1388 // State names
1389 AddStateName(kStateDisconnected, "Disconnected",
1390 "FTM board not connected via ethernet.");
1391
1392 AddStateName(kStateConnected, "Connected",
1393 "Ethernet connection to FTM established (no state received yet).");
1394
1395 AddStateName(kStateIdle, "Idle",
1396 "Ethernet connection to FTM established, FTM in idle state.");
1397
1398 AddStateName(kStateTakingData, "TakingData",
1399 "Ethernet connection to FTM established, FTM is in taking data state.");
1400
1401 // FTM Commands
1402 AddEvent("TOGGLE_LED", kStateIdle)
1403 (Wrapper(boost::bind(&ConnectionFTM::CmdToggleLed, &fFTM)))
1404 ("toggle led");
1405
1406 AddEvent("PING", kStateIdle)
1407 (Wrapper(boost::bind(&ConnectionFTM::CmdPing, &fFTM)))
1408 ("send ping");
1409
1410 AddEvent("REQUEST_DYNAMIC_DATA", kStateIdle)
1411 (Wrapper(boost::bind(&ConnectionFTM::CmdReqDynDat, &fFTM)))
1412 ("request transmission of dynamic data block");
1413
1414 AddEvent("REQUEST_STATIC_DATA", kStateIdle)
1415 (Wrapper(boost::bind(&ConnectionFTM::CmdReqStatDat, &fFTM)))
1416 ("request transmission of static data from FTM to memory");
1417
1418 AddEvent("GET_REGISTER", "I", kStateIdle)
1419 (boost::bind(&StateMachineFTM::GetRegister, this, _1))
1420 ("read register from address addr"
1421 "|addr[short]:Address of register");
1422
1423 AddEvent("SET_REGISTER", "I:2", kStateIdle)
1424 (boost::bind(&StateMachineFTM::SetRegister, this, _1))
1425 ("set register to value"
1426 "|addr[short]:Address of register"
1427 "|val[short]:Value to be set");
1428
1429 AddEvent("START_RUN", kStateIdle)
1430 (Wrapper(boost::bind(&ConnectionFTM::CmdStartRun, &fFTM)))
1431 ("start a run (start distributing triggers)");
1432
1433 AddEvent("STOP_RUN", kStateTakingData)
1434 (Wrapper(boost::bind(&ConnectionFTM::CmdStopRun, &fFTM)))
1435 ("stop a run (stop distributing triggers)");
1436
1437 AddEvent("TAKE_N_EVENTS", "I", kStateIdle)
1438 (boost::bind(&StateMachineFTM::TakeNevents, this, _1))
1439 ("take n events (distribute n triggers)|number[int]:Number of events to be taken");
1440
1441 AddEvent("DISABLE_REPORTS", "B", kStateIdle)
1442 (boost::bind(&StateMachineFTM::DisableReports, this, _1))
1443 ("disable sending rate reports"
1444 "|status[bool]:disable or enable that the FTM sends rate reports (yes/no)");
1445
1446 AddEvent("SET_THRESHOLD", "I:2", kStateIdle)
1447 (boost::bind(&StateMachineFTM::SetThreshold, this, _1))
1448 ("Set the comparator threshold"
1449 "|Patch[idx]:Index of the patch (0-159), -1 for all"
1450 "|Threshold[counts]:Threshold to be set in binary counts");
1451
1452 AddEvent("SET_PRESCALING", "I:1", kStateIdle)
1453 (boost::bind(&StateMachineFTM::SetPrescaling, this, _1))
1454 (""
1455 "|[]:");
1456
1457 AddEvent("ENABLE_FTU", "I:1;B:1", kStateIdle)
1458 (boost::bind(&StateMachineFTM::EnableFTU, this, _1))
1459 ("Enable or disable FTU"
1460 "|Board[idx]:Index of the board (0-39), -1 for all"
1461 "|Enable[bool]:Whether FTU should be enabled or disabled (yes/no)");
1462
1463 AddEvent("TOGGLE_FTU", "I:1", kStateIdle)
1464 (boost::bind(&StateMachineFTM::ToggleFTU, this, _1))
1465 ("Toggle status of FTU (this is mainly meant to be used in the GUI)"
1466 "|Board[idx]:Index of the board (0-39)");
1467
1468 AddEvent("SET_TRIGGER_INTERVAL", "I:1", kStateIdle)
1469 (boost::bind(&StateMachineFTM::SetTriggerInterval, this, _1))
1470 ("Sets the trigger interval which is the distance between two consecutive artificial triggers."
1471 "|interval[int]:The applied trigger interval is: interval*4ns+8ns");
1472
1473 AddEvent("SET_TRIGGER_DELAY", "I:1", kStateIdle)
1474 (boost::bind(&StateMachineFTM::SetTriggerDelay, this, _1))
1475 (""
1476 "|delay[int]:The applied trigger delay is: delay*4ns+8ns");
1477
1478 AddEvent("SET_TIME_MARKER_DELAY", "I:1", kStateIdle)
1479 (boost::bind(&StateMachineFTM::SetTimeMarkerDelay, this, _1))
1480 (""
1481 "|delay[int]:The applied time marker delay is: delay*4ns+8ns");
1482
1483 AddEvent("SET_DEAD_TIME", "I:1", kStateIdle)
1484 (boost::bind(&StateMachineFTM::SetDeadTime, this, _1))
1485 (""
1486 "|dead_time[int]:The applied dead time is: dead_time*4ns+8ns");
1487
1488 AddEvent("ENABLE_TRIGGER", "B:1", kStateIdle)
1489 (boost::bind(&StateMachineFTM::Enable, this, _1, FTM::StaticData::kTrigger))
1490 ("Switch on the physics trigger"
1491 "|Enable[bool]:Enable physics trigger (yes/no)");
1492
1493 // FIXME: Switch on/off depending on sequence
1494 AddEvent("ENABLE_EXT1", "B:1", kStateIdle)
1495 (boost::bind(&StateMachineFTM::Enable, this, _1, FTM::StaticData::kExt1))
1496 ("Switch on the triggers through the first external line"
1497 "|Enable[bool]:Enable ext1 trigger (yes/no)");
1498
1499 // FIXME: Switch on/off depending on sequence
1500 AddEvent("ENABLE_EXT2", "B:1", kStateIdle)
1501 (boost::bind(&StateMachineFTM::Enable, this, _1, FTM::StaticData::kExt2))
1502 ("Switch on the triggers through the second external line"
1503 "|Enable[bool]:Enable ext2 trigger (yes/no)");
1504
1505 AddEvent("ENABLE_VETO", "B:1", kStateIdle)
1506 (boost::bind(&StateMachineFTM::Enable, this, _1, FTM::StaticData::kVeto))
1507 ("Enable veto line"
1508 "|Enable[bool]:Enable veto (yes/no)");
1509
1510 AddEvent("SET_TRIGGER_SEQUENCE", "C:3", kStateIdle)
1511 (boost::bind(&StateMachineFTM::SetTriggerSeq, this, _1))
1512 ("Setup the sequence of artificial triggers produced by the FTM"
1513 "|Ped[int]:number of pedestal triggers in a row"
1514 "|LPint[int]:number of triggers of the internal light pulser"
1515 "|LPext[int]:number of triggers of the external light pulser");
1516
1517 AddEvent("SET_TRIGGER_MULTIPLICITY", "S:1", kStateIdle)
1518 (boost::bind(&StateMachineFTM::SetTriggerMultiplicity, this, _1))
1519 ("Setup the Multiplicity condition for physcis triggers"
1520 "|N[int]:Number of requirered coincident triggers from sum-patches (1-40)");
1521
1522 AddEvent("SET_TRIGGER_WINDOW", "S:1", kStateIdle)
1523 (boost::bind(&StateMachineFTM::SetTriggerWindow, this, _1))
1524 ("");
1525
1526 AddEvent("SET_CALIBRATION_MULTIPLICITY", "S:1", kStateIdle)
1527 (boost::bind(&StateMachineFTM::SetCalibMultiplicity, this, _1))
1528 ("Setup the Multiplicity condition for artificial (calibration) triggers"
1529 "|N[int]:Number of requirered coincident triggers from sum-patches (1-40)");
1530
1531 AddEvent("SET_CALIBRATION_WINDOW", "S:1", kStateIdle)
1532 (boost::bind(&StateMachineFTM::SetCalibWindow, this, _1))
1533 ("");
1534
1535
1536 // Load/save static data block
1537 T::AddEvent("SAVE", "C", kStateIdle)
1538 (boost::bind(&StateMachineFTM::SaveStaticData, this, _1))
1539 ("Saves the static data (FTM configuration) from memory to a file"
1540 "|filename[string]:Filename (can include a path), .bin is automatically added");
1541
1542 T::AddEvent("LOAD", "C", kStateIdle)
1543 (boost::bind(&StateMachineFTM::LoadStaticData, this, _1))
1544 ("Loads the static data (FTM configuration) from a file into memory and sends it to the FTM"
1545 "|filename[string]:Filename (can include a path), .bin is automatically added");
1546
1547
1548
1549 // Verbosity commands
1550 T::AddEvent("SET_VERBOSE", "B")
1551 (boost::bind(&StateMachineFTM::SetVerbosity, this, _1))
1552 ("set verbosity state"
1553 "|verbosity[bool]:disable or enable verbosity for received data (yes/no), except dynamic data");
1554
1555 T::AddEvent("SET_HEX_OUTPUT", "B")
1556 (boost::bind(&StateMachineFTM::SetHexOutput, this, _1))
1557 ("enable or disable hex output for received data"
1558 "|hexout[bool]:disable or enable hex output for received data (yes/no)");
1559
1560 T::AddEvent("SET_DYNAMIC_OUTPUT", "B")
1561 (boost::bind(&StateMachineFTM::SetDynamicOut, this, _1))
1562 ("enable or disable output for received dynamic data (data is still broadcasted via Dim)"
1563 "|dynout[bool]:disable or enable output for dynamic data (yes/no)");
1564
1565
1566 // Conenction commands
1567 AddEvent("DISCONNECT", kStateConnected, kStateIdle)
1568 (boost::bind(&StateMachineFTM::Disconnect, this))
1569 ("disconnect from ethernet");
1570
1571 AddEvent("RECONNECT", "O", kStateDisconnected, kStateConnected, kStateIdle)
1572 (boost::bind(&StateMachineFTM::Reconnect, this, _1))
1573 ("(Re)connect ethernet connection to FTM, a new address can be given"
1574 "|[host][string]:new ethernet address in the form <host:port>");
1575
1576 // Other
1577 AddEvent(kCmdTest, "TEST", "O")
1578 (boost::bind(&StateMachineFTM::Test, this, _1))
1579 ("Just for test purpose, do not use");
1580
1581 fFTM.StartConnect();
1582 }
1583
1584 void SetEndpoint(const string &url)
1585 {
1586 fFTM.SetEndpoint(url);
1587 }
1588
1589 bool SetConfiguration(const Configuration &conf)
1590 {
1591 SetEndpoint(conf.Get<string>("addr"));
1592
1593 fFTM.SetVerbose(!conf.Get<bool>("quiet"));
1594 fFTM.SetHexOutput(conf.Get<bool>("hex-out"));
1595 fFTM.SetDynamicOut(conf.Get<bool>("dynamic-out"));
1596
1597// fFTM.SetDefaultSetup(conf.Get<string>("default-setup"));
1598
1599 return true;
1600 }
1601};
1602
1603// ------------------------------------------------------------------------
1604
1605void RunThread(StateMachineImp *io_service)
1606{
1607 // This is necessary so that the StateMachien Thread can signal the
1608 // Readline to exit
1609 io_service->Run();
1610 Readline::Stop();
1611}
1612
1613template<class S, class T>
1614int RunDim(Configuration &conf)
1615{
1616 WindowLog wout;
1617
1618 /*
1619 static Test shell(conf.GetName().c_str(), conf.Get<int>("console")!=1);
1620
1621 WindowLog &win = shell.GetStreamIn();
1622 WindowLog &wout = shell.GetStreamOut();
1623 */
1624
1625 if (conf.Has("log"))
1626 if (!wout.OpenLogFile(conf.Get<string>("log")))
1627 wout << kRed << "ERROR - Couldn't open log-file " << conf.Get<string>("log") << ": " << strerror(errno) << endl;
1628
1629 // Start io_service.Run to use the StateMachineImp::Run() loop
1630 // Start io_service.run to only use the commandHandler command detaching
1631 StateMachineFTM<S, T> io_service(wout);
1632 if (!io_service.SetConfiguration(conf))
1633 return -1;
1634
1635 io_service.Run();
1636
1637 /*
1638 shell.SetReceiver(io_service);
1639
1640 boost::thread t(boost::bind(RunThread, &io_service));
1641 // boost::thread t(boost::bind(&StateMachineFTM<S>::Run, &io_service));
1642
1643 shell.Run(); // Run the shell
1644 io_service.Stop(); // Signal Loop-thread to stop
1645 // io_service.Close(); // Obsolete, done by the destructor
1646
1647 // Wait until the StateMachine has finished its thread
1648 // before returning and destroying the dim objects which might
1649 // still be in use.
1650 t.join();
1651 */
1652
1653 return 0;
1654}
1655
1656template<class T, class S, class R>
1657int RunShell(Configuration &conf)
1658{
1659 static T shell(conf.GetName().c_str(), conf.Get<int>("console")!=1);
1660
1661 WindowLog &win = shell.GetStreamIn();
1662 WindowLog &wout = shell.GetStreamOut();
1663
1664 if (conf.Has("log"))
1665 if (!wout.OpenLogFile(conf.Get<string>("log")))
1666 win << kRed << "ERROR - Couldn't open log-file " << conf.Get<string>("log") << ": " << strerror(errno) << endl;
1667
1668 StateMachineFTM<S, R> io_service(wout);
1669 if (!io_service.SetConfiguration(conf))
1670 return -1;
1671
1672 shell.SetReceiver(io_service);
1673
1674 boost::thread t(boost::bind(RunThread, &io_service));
1675 // boost::thread t(boost::bind(&StateMachineFTM<S>::Run, &io_service));
1676
1677 shell.Run(); // Run the shell
1678 io_service.Stop(); // Signal Loop-thread to stop
1679 // io_service.Close(); // Obsolete, done by the destructor
1680
1681 // Wait until the StateMachine has finished its thread
1682 // before returning and destroying the dim objects which might
1683 // still be in use.
1684 t.join();
1685
1686 return 0;
1687}
1688
1689void SetupConfiguration(Configuration &conf)
1690{
1691 const string n = conf.GetName()+".log";
1692
1693 po::options_description config("Program options");
1694 config.add_options()
1695 ("dns", var<string>("localhost"), "Dim nameserver host name (Overwites DIM_DNS_NODE environment variable)")
1696 ("log,l", var<string>(n), "Write log-file")
1697 ("no-dim,d", po_bool(), "Disable dim services")
1698 ("console,c", var<int>(), "Use console (0=shell, 1=simple buffered, X=simple unbuffered)")
1699 ;
1700
1701 po::options_description control("FTM control options");
1702 control.add_options()
1703 ("addr,a", var<string>("localhost:5000"), "Network address of FTM")
1704 ("quiet,q", po_bool(), "Disable printing contents of all received messages (except dynamic data) in clear text.")
1705 ("hex-out", po_bool(), "Enable printing contents of all printed messages also as hex data.")
1706 ("dynamic-out", po_bool(), "Enable printing received dynamic data.")
1707// ("default-setup", var<string>(), "Binary file with static data loaded whenever a connection to the FTM was established.")
1708 ;
1709
1710 conf.AddEnv("dns", "DIM_DNS_NODE");
1711
1712 conf.AddOptions(config);
1713 conf.AddOptions(control);
1714}
1715
1716/*
1717 Extract usage clause(s) [if any] for SYNOPSIS.
1718 Translators: "Usage" and "or" here are patterns (regular expressions) which
1719 are used to match the usage synopsis in program output. An example from cp
1720 (GNU coreutils) which contains both strings:
1721 Usage: cp [OPTION]... [-T] SOURCE DEST
1722 or: cp [OPTION]... SOURCE... DIRECTORY
1723 or: cp [OPTION]... -t DIRECTORY SOURCE...
1724 */
1725void PrintUsage()
1726{
1727 cout <<
1728 "The ftmctrl controls the FTM (FACT Trigger Master) board.\n"
1729 "\n"
1730 "The default is that the program is started without user intercation. "
1731 "All actions are supposed to arrive as DimCommands. Using the -c "
1732 "option, a local shell can be initialized. With h or help a short "
1733 "help message about the usuage can be brought to the screen.\n"
1734 "\n"
1735 "Usage: ftmctrl [-c type] [OPTIONS]\n"
1736 " or: ftmctrl [OPTIONS]\n";
1737 cout << endl;
1738}
1739
1740void PrintHelp()
1741{
1742 /* Additional help text which is printed after the configuration
1743 options goes here */
1744
1745 /*
1746 cout << "bla bla bla" << endl << endl;
1747 cout << endl;
1748 cout << "Environment:" << endl;
1749 cout << "environment" << endl;
1750 cout << endl;
1751 cout << "Examples:" << endl;
1752 cout << "test exam" << endl;
1753 cout << endl;
1754 cout << "Files:" << endl;
1755 cout << "files" << endl;
1756 cout << endl;
1757 */
1758}
1759
1760int main(int argc, const char* argv[])
1761{
1762 Configuration conf(argv[0]);
1763 conf.SetPrintUsage(PrintUsage);
1764 SetupConfiguration(conf);
1765
1766 po::variables_map vm;
1767 try
1768 {
1769 vm = conf.Parse(argc, argv);
1770 }
1771#if BOOST_VERSION > 104000
1772 catch (po::multiple_occurrences &e)
1773 {
1774 cout << "Error: " << e.what() << " of '" << e.get_option_name() << "' option." << endl;
1775 cout << endl;
1776 return -1;
1777 }
1778#endif
1779 catch (std::exception &e)
1780 {
1781 cout << "Error: " << e.what() << endl;
1782 cout << endl;
1783
1784 return -1;
1785 }
1786
1787 if (conf.HasPrint())
1788 return -1;
1789
1790 if (conf.HasVersion())
1791 {
1792 FACT::PrintVersion(argv[0]);
1793 return -1;
1794 }
1795
1796 if (conf.HasHelp())
1797 {
1798 PrintHelp();
1799 return -1;
1800 }
1801
1802 Dim::Setup(conf.Get<string>("dns"));
1803
1804 //try
1805 {
1806 // No console access at all
1807 if (!conf.Has("console"))
1808 {
1809 if (conf.Get<bool>("no-dim"))
1810 return RunDim<StateMachine, ConnectionFTM>(conf);
1811 else
1812 return RunDim<StateMachineDim, ConnectionDimFTM>(conf);
1813 }
1814 // Cosole access w/ and w/o Dim
1815 if (conf.Get<bool>("no-dim"))
1816 {
1817 if (conf.Get<int>("console")==0)
1818 return RunShell<LocalShell, StateMachine, ConnectionFTM>(conf);
1819 else
1820 return RunShell<LocalConsole, StateMachine, ConnectionFTM>(conf);
1821 }
1822 else
1823 {
1824 if (conf.Get<int>("console")==0)
1825 return RunShell<LocalShell, StateMachineDim, ConnectionDimFTM>(conf);
1826 else
1827 return RunShell<LocalConsole, StateMachineDim, ConnectionDimFTM>(conf);
1828 }
1829 }
1830 /*catch (std::exception& e)
1831 {
1832 cerr << "Exception: " << e.what() << endl;
1833 return -1;
1834 }*/
1835
1836 return 0;
1837}
Note: See TracBrowser for help on using the repository browser.