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

Last change on this file since 11520 was 11520, checked in by tbretz, 13 years ago
Request static data instead of just the register.
File size: 78.2 KB
Line 
1#include <array>
2
3#include "Dim.h"
4#include "Event.h"
5#include "Shell.h"
6#include "StateMachineDim.h"
7#include "Connection.h"
8#include "Configuration.h"
9#include "Console.h"
10#include "Converter.h"
11
12#include "tools.h"
13
14#include "HeadersFTM.h"
15
16
17namespace ba = boost::asio;
18namespace bs = boost::system;
19
20using namespace std;
21using namespace std::placeholders;
22
23// ------------------------------------------------------------------------
24
25class ConnectionFTM : public Connection
26{
27public:
28 enum States
29 {
30 // State Machine states
31 kDisconnected = 1,
32 kConnected,
33 kIdle,
34 kConfigured, // Returned if idle and fBufStaticData==fStaticData
35 kTakingData,
36 };
37
38private:
39 vector<uint16_t> fBuffer;
40
41 bool fHasHeader;
42 FTM::States fState;
43
44 bool fIsVerbose;
45 bool fIsDynamicOut;
46 bool fIsHexOutput;
47
48// string fDefaultSetup;
49
50 // --verbose
51 // --hex-out
52 // --dynamic-out
53 // --load-file
54 // --leds
55 // --trigger-interval
56 // --physcis-coincidence
57 // --calib-coincidence
58 // --physcis-window
59 // --physcis-window
60 // --trigger-delay
61 // --time-marker-delay
62 // --dead-time
63 // --clock-conditioner-r0
64 // --clock-conditioner-r1
65 // --clock-conditioner-r8
66 // --clock-conditioner-r9
67 // --clock-conditioner-r11
68 // --clock-conditioner-r13
69 // --clock-conditioner-r14
70 // --clock-conditioner-r15
71 // ...
72
73protected:
74 map<uint16_t, uint32_t> fCounter;
75
76 FTM::Header fHeader;
77 FTM::FtuList fFtuList;
78 FTM::StaticData fStaticData;
79 FTM::DynamicData fDynamicData;
80 FTM::Error fError;
81
82 FTM::StaticData fBufStaticData;
83
84 virtual void UpdateFirstHeader()
85 {
86 // FIXME: Message() ?
87 Out() << endl << kBold << "First header received:" << endl;
88 Out() << fHeader;
89 if (fIsHexOutput)
90 Out() << Converter::GetHex<uint16_t>(fHeader, 16) << endl;
91 }
92
93 virtual void UpdateHeader()
94 {
95 // emit service with trigger counter from header
96 if (!fIsVerbose)
97 return;
98
99 if (fHeader.fType==FTM::kDynamicData && !fIsDynamicOut)
100 return;
101
102 Out() << endl << kBold << "Header received:" << endl;
103 Out() << fHeader;
104 if (fIsHexOutput)
105 Out() << Converter::GetHex<uint16_t>(fHeader, 16) << endl;
106 }
107
108 virtual void UpdateFtuList()
109 {
110 if (!fIsVerbose)
111 return;
112
113 Out() << endl << kBold << "FtuList received:" << endl;
114 Out() << fFtuList;
115 if (fIsHexOutput)
116 Out() << Converter::GetHex<uint16_t>(fFtuList, 16) << endl;
117 }
118
119 virtual void UpdateStaticData()
120 {
121 if (!fIsVerbose)
122 return;
123
124 Out() << endl << kBold << "Static data received:" << endl;
125 Out() << fStaticData;
126 if (fIsHexOutput)
127 Out() << Converter::GetHex<uint16_t>(fStaticData, 16) << endl;
128 }
129
130 virtual void UpdateDynamicData()
131 {
132 if (!fIsDynamicOut)
133 return;
134
135 Out() << endl << kBold << "Dynamic data received:" << endl;
136 Out() << fDynamicData;
137 if (fIsHexOutput)
138 Out() << Converter::GetHex<uint16_t>(fDynamicData, 16) << endl;
139 }
140
141 virtual void UpdateError()
142 {
143 if (!fIsVerbose)
144 return;
145
146 Out() << endl << kRed << "Error received:" << endl;
147 Out() << fError;
148 if (fIsHexOutput)
149 Out() << Converter::GetHex<uint16_t>(fError, 16) << endl;
150 }
151
152 virtual void UpdateCounter()
153 {
154 if (!fIsVerbose)
155 return;
156
157 if (!fIsDynamicOut)
158 return;
159
160 Out() << "Received: ";
161 Out() << "H=" << fCounter[FTM::kHeader] << " ";
162 Out() << "S=" << fCounter[FTM::kStaticData] << " ";
163 Out() << "D=" << fCounter[FTM::kDynamicData] << " ";
164 Out() << "F=" << fCounter[FTM::kFtuList] << " ";
165 Out() << "E=" << fCounter[FTM::kErrorList] << " ";
166 Out() << "R=" << fCounter[FTM::kRegister] << endl;
167 }
168
169 bool CheckConsistency(FTM::StaticData &data)
170 {
171 bool warn1 = false;
172 if (data.IsEnabled(FTM::StaticData::kPedestal) != (data.GetSequencePed() >0) ||
173 data.IsEnabled(FTM::StaticData::kLPint) != (data.GetSequenceLPint()>0) ||
174 data.IsEnabled(FTM::StaticData::kLPext) != (data.GetSequenceLPext()>0))
175 {
176 warn1 = true;
177 data.Enable(FTM::StaticData::kPedestal, data.GetSequencePed()>0);
178 data.Enable(FTM::StaticData::kLPint, data.GetSequenceLPint()>0);
179 data.Enable(FTM::StaticData::kLPext, data.GetSequenceLPext()>0);
180 }
181
182 bool warn2 = false;
183 const uint16_t ref = data[0].fPrescaling;
184 for (int i=1; i<40; i++)
185 {
186 if (data[i].fPrescaling != ref)
187 {
188 warn2 = true;
189 data[i].fPrescaling = ref;
190 }
191 }
192
193 if (warn1)
194 Warn("GeneralSettings not consistent with trigger sequence.");
195 if (warn2)
196 Warn("Prescaling not consistent for all boards.");
197
198 return !warn1 && !warn2;
199 }
200
201private:
202 void HandleReceivedData(const bs::error_code& err, size_t bytes_received, int /*type*/)
203 {
204 // Do not schedule a new read if the connection failed.
205 if (bytes_received==0 || err)
206 {
207 if (err==ba::error::eof)
208 Warn("Connection closed by remote host (FTM).");
209
210 // 107: Transport endpoint is not connected (bs::error_code(107, bs::system_category))
211 // 125: Operation canceled
212 if (err && err!=ba::error::eof && // Connection closed by remote host
213 err!=ba::error::basic_errors::not_connected && // Connection closed by remote host
214 err!=ba::error::basic_errors::operation_aborted) // Connection closed by us
215 {
216 ostringstream str;
217 str << "Reading from " << URL() << ": " << err.message() << " (" << err << ")";// << endl;
218 Error(str);
219 }
220 PostClose(err!=ba::error::basic_errors::operation_aborted);
221 return;
222 }
223
224 // If we have not yet received a header we expect one now
225 // This could be moved to a HandleReceivedHeader function
226 if (!fHasHeader)
227 {
228 if (bytes_received!=sizeof(FTM::Header))
229 {
230 ostringstream str;
231 str << "Excepted " << sizeof(FTM::Header) << " bytes (FTM::Header) but received " << bytes_received << ".";
232 Error(str);
233 PostClose(false);
234 return;
235 }
236
237 fHeader = fBuffer;
238
239 // Check the data integrity
240 if (fHeader.fDelimiter!=FTM::kDelimiterStart)
241 {
242 ostringstream str;
243 str << "Invalid header received: start delimiter wrong, received ";
244 str << hex << fHeader.fDelimiter << ", expected " << FTM::kDelimiterStart << ".";
245 Error(str);
246 PostClose(false);
247 return;
248 }
249
250 fHasHeader = true;
251
252 // Convert FTM state into FtmCtrl state
253 if (++fCounter[FTM::kHeader]==1)
254 UpdateFirstHeader();
255
256 UpdateCounter();
257 UpdateHeader();
258
259 // Start reading of data
260 switch (fHeader.fType)
261 {
262 case FTM::kStaticData:
263 case FTM::kDynamicData:
264 case FTM::kFtuList:
265 case FTM::kRegister:
266 case FTM::kErrorList:
267 // This is not very efficient because the space is reallocated
268 // maybe we can check if the capacity of the std::vector
269 // is ever decreased. If not, everythign is fine.
270 fBuffer.resize(fHeader.fDataSize);
271 AsyncRead(ba::buffer(fBuffer));
272 AsyncWait(fInTimeout, 50, &Connection::HandleReadTimeout);
273 return;
274
275 default:
276 ostringstream str;
277 str << "Unknonw type " << fHeader.fType << " in received header." << endl;
278 Error(str);
279 PostClose(false);
280 return;
281 }
282
283 return;
284 }
285
286 // Check the data integrity (check end delimiter)
287 if (ntohs(fBuffer.back())!=FTM::kDelimiterEnd)
288 {
289 ostringstream str;
290 str << "Invalid data received: end delimiter wrong, received ";
291 str << hex << ntohs(fBuffer.back()) << ", expected " << FTM::kDelimiterEnd << ".";
292 Error(str);
293 PostClose(false);
294 return;
295 }
296
297 // Remove end delimiter
298 fBuffer.pop_back();
299
300 try
301 {
302 // If we have already received a header this is the data now
303 // This could be moved to a HandleReceivedData function
304
305 fCounter[fHeader.fType]++;
306 UpdateCounter();
307
308 switch (fHeader.fType)
309 {
310 case FTM::kFtuList:
311 fFtuList = fBuffer;
312 UpdateFtuList();
313 break;
314
315 case FTM::kStaticData:
316 if (fCounter[FTM::kStaticData]==1)
317 {
318 // This check is only done at startup
319 FTM::StaticData data(fBuffer);
320 if (!CheckConsistency(data))
321 {
322 CmdSendStatDat(data);
323 break;
324 }
325 }
326
327 fStaticData = fBuffer;
328 UpdateStaticData();
329 break;
330
331 case FTM::kDynamicData:
332 fDynamicData = fBuffer;
333 UpdateDynamicData();
334 break;
335
336 case FTM::kRegister:
337 if (fIsVerbose)
338 {
339 Out() << endl << kBold << "Register received: " << endl;
340 Out() << "Addr: " << ntohs(fBuffer[0]) << endl;
341 Out() << "Value: " << ntohs(fBuffer[1]) << endl;
342 }
343 break;
344
345 case FTM::kErrorList:
346 fError = fBuffer;
347 UpdateError();
348 break;
349
350 default:
351 ostringstream str;
352 str << "Unknonw type " << fHeader.fType << " in header." << endl;
353 Error(str);
354 PostClose(false);
355 return;
356 }
357 }
358 catch (const logic_error &e)
359 {
360 ostringstream str;
361 str << "Exception converting buffer into data structure: " << e.what();
362 Error(str);
363 PostClose(false);
364 return;
365 }
366
367 fInTimeout.cancel();
368
369 //fHeader.clear();
370 fHasHeader = false;
371 fBuffer.resize(sizeof(FTM::Header)/2);
372 AsyncRead(ba::buffer(fBuffer));
373 }
374
375 // This is called when a connection was established
376 void ConnectionEstablished()
377 {
378 fCounter.clear();
379 fBufStaticData.clear();
380
381 fHeader.clear();
382 fHasHeader = false;
383 fBuffer.resize(sizeof(FTM::Header)/2);
384 AsyncRead(ba::buffer(fBuffer));
385
386// if (!fDefaultSetup.empty())
387// LoadStaticData(fDefaultSetup);
388
389 // Get a header and configdata!
390 CmdReqStatDat();
391
392 // get the DNA of the FTUs
393 CmdPing();
394 }
395
396 void HandleReadTimeout(const bs::error_code &error)
397 {
398 if (error==ba::error::basic_errors::operation_aborted)
399 return;
400
401 if (error)
402 {
403 ostringstream str;
404 str << "Read timeout of " << URL() << ": " << error.message() << " (" << error << ")";// << endl;
405 Error(str);
406
407 PostClose();
408 return;
409
410 }
411
412 if (!is_open())
413 {
414 // For example: Here we could schedule a new accept if we
415 // would not want to allow two connections at the same time.
416 return;
417 }
418
419 // Check whether the deadline has passed. We compare the deadline
420 // against the current time since a new asynchronous operation
421 // may have moved the deadline before this actor had a chance
422 // to run.
423 if (fInTimeout.expires_at() > ba::deadline_timer::traits_type::now())
424 return;
425
426 Error("Timeout reading data from "+URL());
427
428 PostClose();
429 }
430
431
432 template<size_t N>
433 void PostCmd(array<uint16_t, N> dat, uint16_t u1=0, uint16_t u2=0, uint16_t u3=0, uint16_t u4=0)
434 {
435 array<uint16_t, 5> cmd = {{ '@', u1, u2, u3, u4 }};
436
437 ostringstream msg;
438 msg << "Sending command:" << hex;
439 msg << " 0x" << setw(4) << setfill('0') << cmd[0];
440 msg << " 0x" << setw(4) << setfill('0') << u1;
441 msg << " 0x" << setw(4) << setfill('0') << u2;
442 msg << " 0x" << setw(4) << setfill('0') << u3;
443 msg << " 0x" << setw(4) << setfill('0') << u4;
444 msg << " (+" << dec << dat.size() << " words)";
445 Message(msg);
446
447 vector<uint16_t> out(cmd.size()+dat.size());
448
449 transform(cmd.begin(), cmd.end(), out.begin(), htons);
450 transform(dat.begin(), dat.end(), out.begin()+cmd.size(), htons);
451
452 PostMessage(out);
453 }
454
455 void PostCmd(vector<uint16_t> dat, uint16_t u1=0, uint16_t u2=0, uint16_t u3=0, uint16_t u4=0)
456 {
457 array<uint16_t, 5> cmd = {{ '@', u1, u2, u3, u4 }};
458
459 ostringstream msg;
460 msg << "Sending command:" << hex;
461 msg << " 0x" << setw(4) << setfill('0') << cmd[0];
462 msg << " 0x" << setw(4) << setfill('0') << u1;
463 msg << " 0x" << setw(4) << setfill('0') << u2;
464 msg << " 0x" << setw(4) << setfill('0') << u3;
465 msg << " 0x" << setw(4) << setfill('0') << u4;
466 msg << " (+" << dec << dat.size() << " words)";
467 Message(msg);
468
469 vector<uint16_t> out(cmd.size()+dat.size());
470
471 transform(cmd.begin(), cmd.end(), out.begin(), htons);
472 copy(dat.begin(), dat.end(), out.begin()+cmd.size());
473
474 PostMessage(out);
475 }
476
477 void PostCmd(uint16_t u1=0, uint16_t u2=0, uint16_t u3=0, uint16_t u4=0)
478 {
479 PostCmd(array<uint16_t, 0>(), u1, u2, u3, u4);
480 }
481public:
482
483// static const uint16_t kMaxAddr;
484
485public:
486 ConnectionFTM(ba::io_service& ioservice, MessageImp &imp) : Connection(ioservice, imp()),
487 fIsVerbose(true), fIsDynamicOut(true), fIsHexOutput(true)
488 {
489 SetLogStream(&imp);
490 }
491
492 void CmdToggleLed()
493 {
494 PostCmd(FTM::kCmdToggleLed);
495 }
496
497 void CmdPing()
498 {
499 PostCmd(FTM::kCmdPing);
500 }
501
502 void CmdReqDynDat()
503 {
504 PostCmd(FTM::kCmdRead, FTM::kCmdDynamicData);
505 }
506
507 void CmdReqStatDat()
508 {
509 PostCmd(FTM::kCmdRead, FTM::kCmdStaticData);
510 }
511
512 void CmdSendStatDat(const FTM::StaticData &data)
513 {
514 fBufStaticData = data;
515
516 PostCmd(data.HtoN(), FTM::kCmdWrite, FTM::kCmdStaticData);
517
518 // Request the changed configuration to ensure the
519 // change is distributed in the network
520 CmdReqStatDat();
521 }
522
523 void CmdStartRun()
524 {
525 PostCmd(FTM::kCmdStartRun, FTM::kStartRun);
526
527 // Update state information by requesting a new header
528 CmdGetRegister(0);
529 }
530
531 void CmdStopRun()
532 {
533 PostCmd(FTM::kCmdStopRun);
534
535 // Update state information by requesting a new header
536 CmdGetRegister(0);
537 }
538
539 void CmdTakeNevents(uint32_t n)
540 {
541 const array<uint16_t, 2> data = {{ uint16_t(n>>16), uint16_t(n&0xffff) }};
542 PostCmd(data, FTM::kCmdStartRun, FTM::kTakeNevents);
543
544 // Update state information by requesting a new header
545 CmdGetRegister(0);
546 }
547
548 bool CmdSetRegister(uint16_t addr, uint16_t val)
549 {
550 if (addr>FTM::StaticData::kMaxAddr)
551 return false;
552
553 const array<uint16_t, 2> data = {{ addr, val }};
554 PostCmd(data, FTM::kCmdWrite, FTM::kCmdRegister);
555
556 reinterpret_cast<uint16_t*>(&fBufStaticData)[addr] = val;
557
558 // Request the changed configuration to ensure the
559 // change is distributed in the network
560 CmdReqStatDat();
561
562 return true;
563 }
564
565 bool CmdGetRegister(uint16_t addr)
566 {
567 if (addr>FTM::StaticData::kMaxAddr)
568 return false;
569
570 const array<uint16_t, 1> data = {{ addr }};
571 PostCmd(data, FTM::kCmdRead, FTM::kCmdRegister);
572
573 return true;
574 }
575
576 bool CmdResetCrate(uint16_t addr)
577 {
578 if (addr>3)
579 return false;
580
581 PostCmd(FTM::kCmdCrateReset, 1<<addr);
582
583 return true;
584 }
585
586 bool CmdResetCamera()
587 {
588 PostCmd(FTM::kCmdCrateReset, FTM::kResetCrate0);
589 PostCmd(FTM::kCmdCrateReset, FTM::kResetCrate1);
590 PostCmd(FTM::kCmdCrateReset, FTM::kResetCrate2);
591 PostCmd(FTM::kCmdCrateReset, FTM::kResetCrate3);
592
593 return true;
594 }
595
596 bool CmdDisableReports(bool b)
597 {
598 PostCmd(FTM::kCmdDisableReports, b ? uint16_t(0) : uint16_t(1));
599 return true;
600 }
601
602
603 void SetVerbose(bool b)
604 {
605 fIsVerbose = b;
606 }
607
608 void SetHexOutput(bool b)
609 {
610 fIsHexOutput = b;
611 }
612
613 void SetDynamicOut(bool b)
614 {
615 fIsDynamicOut = b;
616 }
617/*
618 void SetDefaultSetup(const string &file)
619 {
620 fDefaultSetup = file;
621 }
622*/
623
624 bool LoadStaticData(string name)
625 {
626 if (name.rfind(".bin")!=name.length()-4)
627 name += ".bin";
628
629 ifstream fin(name);
630 if (!fin)
631 return false;
632
633 FTM::StaticData data;
634
635 fin.read(reinterpret_cast<char*>(&data), sizeof(FTM::StaticData));
636
637 if (fin.gcount()<streamsize(sizeof(FTM::StaticData)))
638 return false;
639
640 if (fin.fail() || fin.eof())
641 return false;
642
643 if (fin.peek()!=-1)
644 return false;
645
646 CmdSendStatDat(data);
647
648 return true;
649 }
650
651 bool SaveStaticData(string name) const
652 {
653 if (name.rfind(".bin")!=name.length()-4)
654 name += ".bin";
655
656 ofstream fout(name);
657 if (!fout)
658 return false;
659
660 fout.write(reinterpret_cast<const char*>(&fStaticData), sizeof(FTM::StaticData));
661
662 return !fout.bad();
663 }
664
665 bool SetThreshold(int32_t patch, int32_t value)
666 {
667 if (patch>159)
668 return false;
669
670 if (value<0 || value>0xffff)
671 return false;
672
673 if (patch<0)
674 {
675 FTM::StaticData data(fStaticData);
676
677 bool ident = true;
678 for (int i=0; i<160; i++)
679 if (data[i/4].fDAC[patch%4] != value)
680 {
681 ident = false;
682 break;
683 }
684
685 if (ident)
686 return true;
687
688 for (int i=0; i<160; i++)
689 data[i/4].fDAC[i%4] = value;
690
691 // Maybe move to a "COMMIT" command?
692 CmdSendStatDat(data);
693
694 return true;
695 }
696
697 /*
698 if (data[patch/4].fDAC[patch%4] == value)
699 return true;
700
701 data[patch/4].fDAC[patch%4] = value;
702
703 CmdSendStatDat(data);
704 return true;
705 */
706
707 // Calculate offset in static data block
708 const uint16_t addr = (uintptr_t(&fStaticData[patch/4].fDAC[patch%4])-uintptr_t(&fStaticData))/2;
709
710 // From CmdSetRegister
711 const array<uint16_t, 2> data = {{ addr, uint16_t(value) }};
712 PostCmd(data, FTM::kCmdWrite, FTM::kCmdRegister);
713
714 reinterpret_cast<uint16_t*>(&fBufStaticData)[addr] = value;
715
716 // Now execute change before the static data is requested back
717 PostCmd(FTM::kCmdConfigFTU, (patch/40) | (((patch/4)%10)<<8));
718
719 //CmdGetRegister(addr);
720 CmdReqStatDat();
721
722 return true;
723 }
724
725 bool SetPrescaling(uint32_t value)
726 {
727 if (value>0xffff)
728 return false;
729
730 FTM::StaticData data(fStaticData);
731
732 bool ident = true;
733 for (int i=0; i<40; i++)
734 if (data[i].fPrescaling != value)
735 {
736 ident = false;
737 break;
738 }
739
740 if (ident)
741 return true;
742
743 data.SetPrescaling(value);
744
745 // Maybe move to a "COMMIT" command?
746 CmdSendStatDat(data);
747
748 return true;
749 }
750
751 bool EnableFTU(int32_t board, bool enable)
752 {
753 if (board>39)
754 return false;
755
756 FTM::StaticData data(fStaticData);
757
758 if (board<0)
759 {
760 if (enable)
761 data.EnableAllFTU();
762 else
763 data.DisableAllFTU();
764 }
765 else
766 {
767 if (enable)
768 data.EnableFTU(board);
769 else
770 data.DisableFTU(board);
771
772 }
773
774 // Maybe move to a "COMMIT" command?
775 CmdSendStatDat(data);
776
777 return true;
778 }
779
780 bool ToggleFTU(uint32_t board)
781 {
782 if (board>39)
783 return false;
784
785 FTM::StaticData data(fStaticData);
786
787 data.ToggleFTU(board);
788
789 // Maybe move to a "COMMIT" command?
790 CmdSendStatDat(data);
791
792 return true;
793 }
794
795 bool SetVal(uint16_t *dest, uint32_t val, uint32_t max)
796 {
797 if (val>max)
798 return false;
799
800 if (*dest==val)
801 return true;
802
803 FTM::StaticData data(fStaticData);
804
805 dest = reinterpret_cast<uint16_t*>(&data) + (dest - reinterpret_cast<uint16_t*>(&fStaticData));
806
807 *dest = val;
808
809 CmdSendStatDat(data);
810
811 return true;
812 }
813
814 bool SetTriggerInterval(uint32_t val)
815 {
816 return SetVal(&fStaticData.fTriggerInterval, val,
817 FTM::StaticData::kMaxTriggerInterval);
818 }
819
820 bool SetTriggerDelay(uint32_t val)
821 {
822 return SetVal(&fStaticData.fDelayTrigger, val,
823 FTM::StaticData::kMaxDelayTrigger);
824 }
825
826 bool SetTimeMarkerDelay(uint32_t val)
827 {
828 return SetVal(&fStaticData.fDelayTimeMarker, val,
829 FTM::StaticData::kMaxDelayTimeMarker);
830 }
831
832 bool SetDeadTime(uint32_t val)
833 {
834 return SetVal(&fStaticData.fDeadTime, val,
835 FTM::StaticData::kMaxDeadTime);
836 }
837
838 void Enable(FTM::StaticData::GeneralSettings type, bool enable)
839 {
840 //if (fStaticData.IsEnabled(type)==enable)
841 // return;
842
843 FTM::StaticData data(fStaticData);
844 data.Enable(type, enable);
845 CmdSendStatDat(data);
846 }
847
848 bool SetTriggerSeq(const uint16_t d[3])
849 {
850 if (d[0]>FTM::StaticData::kMaxSequence ||
851 d[1]>FTM::StaticData::kMaxSequence ||
852 d[2]>FTM::StaticData::kMaxSequence)
853 return false;
854
855 FTM::StaticData data(fStaticData);
856
857 /*
858 data.Enable(FTM::StaticData::kPedestal, d[0]>0);
859 data.Enable(FTM::StaticData::kLPext, d[1]>0);
860 data.Enable(FTM::StaticData::kLPint, d[2]>0);
861 */
862
863 data.SetSequence(d[0], d[2], d[1]);
864
865 //if (fStaticData.fTriggerSeq !=data.fTriggerSequence ||
866 // fStaticData.fGeneralSettings!=data.fGeneralSettings)
867 // CmdSendStatDat(data);
868
869 CmdSendStatDat(data);
870
871 return true;
872 }
873
874 bool SetTriggerMultiplicity(uint16_t n)
875 {
876 if (n==0 || n>FTM::StaticData::kMaxMultiplicity)
877 return false;
878
879 if (n==fStaticData.fMultiplicityPhysics)
880 return true;
881
882 FTM::StaticData data(fStaticData);
883
884 data.fMultiplicityPhysics = n;
885
886 CmdSendStatDat(data);
887
888 return true;
889 }
890
891 bool SetTriggerWindow(uint16_t win)
892 {
893 if (win>FTM::StaticData::kMaxWindow)
894 return false;
895
896 if (win==fStaticData.fWindowPhysics)
897 return true;
898
899 FTM::StaticData data(fStaticData);
900
901 data.fWindowPhysics = win;
902
903 CmdSendStatDat(data);
904
905 return true;
906 }
907
908 bool SetCalibMultiplicity(uint16_t n)
909 {
910 if (n==0 || n>FTM::StaticData::kMaxMultiplicity)
911 return false;
912
913 if (n==fStaticData.fMultiplicityCalib)
914 return true;
915
916 FTM::StaticData data(fStaticData);
917
918 data.fMultiplicityCalib = n;
919
920 CmdSendStatDat(data);
921
922 return true;
923 }
924
925 bool SetCalibWindow(uint16_t win)
926 {
927 if (win>FTM::StaticData::kMaxWindow)
928 return false;
929
930 if (win==fStaticData.fWindowCalib)
931 return true;
932
933 FTM::StaticData data(fStaticData);
934
935 data.fWindowCalib = win;
936
937 CmdSendStatDat(data);
938
939 return true;
940 }
941
942 bool SetClockRegister(const uint64_t reg[])
943 {
944 FTM::StaticData data(fStaticData);
945
946 for (int i=0; i<8; i++)
947 if (reg[i]>0xffffffff)
948 return false;
949
950 data.SetClockRegister(reg);
951
952 CmdSendStatDat(data);
953
954 return true;
955 }
956
957 bool EnablePixel(int16_t idx, bool enable)
958 {
959 if (idx<-1 || idx>FTM::StaticData::kMaxPixelIdx)
960 return false;
961
962 if (idx==-1)
963 {
964 FTM::StaticData data(fStaticData);
965
966 for (int i=0; i<=FTM::StaticData::kMaxPixelIdx; i++)
967 data.EnablePixel(i, enable);
968
969 CmdSendStatDat(data);
970
971 return true;
972 }
973
974 /*
975 data.EnablePixel(idx, enable);
976 CmdSendStatDat(data);
977 return true;
978 */
979
980 FTM::StaticData data(fStaticData);
981
982 const uintptr_t base = uintptr_t(&data);
983 const uint16_t *mem = data.EnablePixel(idx, enable);
984
985 // Calculate offset in static data block
986 const uint16_t addr = (uintptr_t(mem)-base)/2;
987
988 // From CmdSetRegister
989 const array<uint16_t, 2> cmd = {{ addr, *mem }};
990 PostCmd(cmd, FTM::kCmdWrite, FTM::kCmdRegister);
991
992 reinterpret_cast<uint16_t*>(&fBufStaticData)[addr] = *mem;
993
994 // Now execute change before the static data is requested back
995 PostCmd(FTM::kCmdConfigFTU, (idx/360) | (((idx/36)%10)<<8));
996
997 // Now request the register back to ensure consistency
998 //CmdGetRegister(addr);
999 CmdReqStatDat();
1000
1001 return true;
1002 }
1003
1004 bool DisableAllPixelsExcept(uint16_t idx)
1005 {
1006 if (idx>FTM::StaticData::kMaxPixelIdx)
1007 return false;
1008
1009 FTM::StaticData data(fStaticData);
1010
1011 for (int i=0; i<=FTM::StaticData::kMaxPixelIdx; i++)
1012 data.EnablePixel(i, i==idx);
1013
1014 CmdSendStatDat(data);
1015
1016 return true;
1017 }
1018
1019 bool DisableAllPatchesExcept(uint16_t idx)
1020 {
1021 if (idx>FTM::StaticData::kMaxPatchIdx)
1022 return false;
1023
1024 FTM::StaticData data(fStaticData);
1025
1026 for (int i=0; i<=FTM::StaticData::kMaxPixelIdx; i++)
1027 data.EnablePixel(i, i/9==idx);
1028
1029 CmdSendStatDat(data);
1030
1031 return true;
1032 }
1033
1034 bool TogglePixel(uint16_t idx)
1035 {
1036 if (idx>FTM::StaticData::kMaxPixelIdx)
1037 return false;
1038
1039 FTM::StaticData data(fStaticData);
1040
1041 data.EnablePixel(idx, !fStaticData.Enabled(idx));
1042
1043 CmdSendStatDat(data);
1044
1045 return true;
1046 }
1047
1048 States GetState() const
1049 {
1050 if (!IsConnected())
1051 return kDisconnected;
1052
1053 switch (fHeader.fState)
1054 {
1055 case FTM::kFtmUndefined:
1056 return kConnected;
1057
1058 case FTM::kFtmRunning:
1059 case FTM::kFtmCalib:
1060 return kTakingData;
1061
1062 case FTM::kFtmIdle:
1063 case FTM::kFtmConfig:
1064 return fStaticData == fBufStaticData ? kConfigured : kIdle;
1065 }
1066
1067 throw runtime_error("ConnectionFTM::GetState - Impossible code reached.");
1068 }
1069
1070 int GetCounter(FTM::Types type) { return fCounter[type]; }
1071
1072 const FTM::StaticData &GetStaticData() const { return fStaticData; }
1073};
1074
1075//const uint16_t ConnectionFTM::kMaxAddr = 0xfff;
1076
1077// ------------------------------------------------------------------------
1078
1079#include "DimDescriptionService.h"
1080
1081class ConnectionDimFTM : public ConnectionFTM
1082{
1083private:
1084
1085 DimDescribedService fDimPassport;
1086 DimDescribedService fDimTriggerCounter;
1087 DimDescribedService fDimError;
1088 DimDescribedService fDimFtuList;
1089 DimDescribedService fDimStaticData;
1090 DimDescribedService fDimDynamicData;
1091 DimDescribedService fDimCounter;
1092
1093 void UpdateFirstHeader()
1094 {
1095 ConnectionFTM::UpdateFirstHeader();
1096
1097 const FTM::DimPassport data(fHeader);
1098 fDimPassport.Update(data);
1099 }
1100
1101 void UpdateHeader()
1102 {
1103 ConnectionFTM::UpdateHeader();
1104
1105 if (fHeader.fType!=FTM::kDynamicData)
1106 return;
1107
1108 const FTM::DimTriggerCounter data(fHeader);
1109 fDimTriggerCounter.Update(data);
1110 }
1111
1112 void UpdateFtuList()
1113 {
1114 ConnectionFTM::UpdateFtuList();
1115
1116 const FTM::DimFtuList data(fHeader, fFtuList);
1117 fDimFtuList.Update(data);
1118 }
1119
1120 void UpdateStaticData()
1121 {
1122 ConnectionFTM::UpdateStaticData();
1123
1124 const FTM::DimStaticData data(fHeader, fStaticData);
1125 fDimStaticData.Update(data);
1126 }
1127
1128 void UpdateDynamicData()
1129 {
1130 ConnectionFTM::UpdateDynamicData();
1131
1132 const FTM::DimDynamicData data(fHeader, fDynamicData);
1133 fDimDynamicData.Update(data);
1134 }
1135
1136 void UpdateError()
1137 {
1138 ConnectionFTM::UpdateError();
1139
1140 const FTM::DimError data(fHeader, fError);
1141 fDimError.Update(data);
1142 }
1143
1144 void UpdateCounter()
1145 {
1146 ConnectionFTM::UpdateCounter();
1147
1148 const uint32_t counter[6] =
1149 {
1150 fCounter[FTM::kHeader],
1151 fCounter[FTM::kStaticData],
1152 fCounter[FTM::kDynamicData],
1153 fCounter[FTM::kFtuList],
1154 fCounter[FTM::kErrorList],
1155 fCounter[FTM::kRegister],
1156 };
1157
1158 fDimCounter.Update(counter);
1159 }
1160
1161public:
1162 ConnectionDimFTM(ba::io_service& ioservice, MessageImp &imp) :
1163 ConnectionFTM(ioservice, imp),
1164 fDimPassport ("FTM_CONTROL/PASSPORT", "X:1;S:1", ""),
1165 fDimTriggerCounter("FTM_CONTROL/TRIGGER_COUNTER", "X:1;I:1", ""),
1166 fDimError ("FTM_CONTROL/ERROR", "X:1;S:1;S:28", ""),
1167 fDimFtuList ("FTM_CONTROL/FTU_LIST", "X:1;X:1;S:1;C:4;X:40;C:40;C:40", ""),
1168 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;I:8;S:90;S:160;S:40;S:40", ""),
1169 fDimDynamicData ("FTM_CONTROL/DYNAMIC_DATA", "X:1;X:1;F:4;I:160;I:40;S:40;S:40", ""),
1170 fDimCounter ("FTM_CONTROL/COUNTER", "I:6", "")
1171 {
1172 }
1173
1174 // 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
1175};
1176
1177// ------------------------------------------------------------------------
1178
1179template <class T, class S>
1180class StateMachineFTM : public T, public ba::io_service, public ba::io_service::work
1181{
1182 int Wrap(boost::function<void()> f)
1183 {
1184 f();
1185 return T::GetCurrentState();
1186 }
1187
1188 function<int(const EventImp &)> Wrapper(function<void()> func)
1189 {
1190 return bind(&StateMachineFTM::Wrap, this, func);
1191 }
1192
1193private:
1194 S fFTM;
1195
1196 bool CheckEventSize(size_t has, const char *name, size_t size)
1197 {
1198 if (has==size)
1199 return true;
1200
1201 ostringstream msg;
1202 msg << name << " - Received event has " << has << " bytes, but expected " << size << ".";
1203 T::Fatal(msg);
1204 return false;
1205 }
1206
1207 int SetRegister(const EventImp &evt)
1208 {
1209 if (!CheckEventSize(evt.GetSize(), "SetRegister", 8))
1210 return T::kSM_FatalError;
1211
1212 const uint32_t *dat = evt.Ptr<uint32_t>();
1213
1214 if (dat[1]>uint16_t(-1))
1215 {
1216 ostringstream msg;
1217 msg << hex << "Value " << dat[1] << " out of range.";
1218 T::Error(msg);
1219 return T::GetCurrentState();
1220 }
1221
1222
1223 if (dat[0]>uint16_t(-1) || !fFTM.CmdSetRegister(dat[0], dat[1]))
1224 {
1225 ostringstream msg;
1226 msg << hex << "Address " << dat[0] << " out of range.";
1227 T::Error(msg);
1228 }
1229
1230 return T::GetCurrentState();
1231 }
1232
1233 int GetRegister(const EventImp &evt)
1234 {
1235 if (!CheckEventSize(evt.GetSize(), "GetRegister", 4))
1236 return T::kSM_FatalError;
1237
1238 const unsigned int addr = evt.GetInt();
1239 if (addr>uint16_t(-1) || !fFTM.CmdGetRegister(addr))
1240 {
1241 ostringstream msg;
1242 msg << hex << "Address " << addr << " out of range.";
1243 T::Error(msg);
1244 }
1245
1246 return T::GetCurrentState();
1247 }
1248
1249 int TakeNevents(const EventImp &evt)
1250 {
1251 if (!CheckEventSize(evt.GetSize(), "TakeNevents", 4))
1252 return T::kSM_FatalError;
1253
1254 const unsigned int dat = evt.GetUInt();
1255
1256 /*
1257 if (dat[1]>uint32_t(-1))
1258 {
1259 ostringstream msg;
1260 msg << hex << "Value " << dat[1] << " out of range.";
1261 T::Error(msg);
1262 return T::GetCurrentState();
1263 }*/
1264
1265 fFTM.CmdTakeNevents(dat);
1266
1267 return T::GetCurrentState();
1268 }
1269
1270 int DisableReports(const EventImp &evt)
1271 {
1272 if (!CheckEventSize(evt.GetSize(), "DisableReports", 1))
1273 return T::kSM_FatalError;
1274
1275 fFTM.CmdDisableReports(evt.GetBool());
1276
1277 return T::GetCurrentState();
1278 }
1279
1280 int SetVerbosity(const EventImp &evt)
1281 {
1282 if (!CheckEventSize(evt.GetSize(), "SetVerbosity", 1))
1283 return T::kSM_FatalError;
1284
1285 fFTM.SetVerbose(evt.GetBool());
1286
1287 return T::GetCurrentState();
1288 }
1289
1290 int SetHexOutput(const EventImp &evt)
1291 {
1292 if (!CheckEventSize(evt.GetSize(), "SetHexOutput", 1))
1293 return T::kSM_FatalError;
1294
1295 fFTM.SetHexOutput(evt.GetBool());
1296
1297 return T::GetCurrentState();
1298 }
1299
1300 int SetDynamicOut(const EventImp &evt)
1301 {
1302 if (!CheckEventSize(evt.GetSize(), "SetDynamicOut", 1))
1303 return T::kSM_FatalError;
1304
1305 fFTM.SetDynamicOut(evt.GetBool());
1306
1307 return T::GetCurrentState();
1308 }
1309
1310 int LoadStaticData(const EventImp &evt)
1311 {
1312 if (fFTM.LoadStaticData(evt.GetString()))
1313 return T::GetCurrentState();
1314
1315 ostringstream msg;
1316 msg << "Loading static data from file '" << evt.GetString() << "' failed ";
1317
1318 if (errno)
1319 msg << "(" << strerror(errno) << ")";
1320 else
1321 msg << "(wrong size, expected " << sizeof(FTM::StaticData) << " bytes)";
1322
1323 T::Warn(msg);
1324
1325 return T::GetCurrentState();
1326 }
1327
1328 int SaveStaticData(const EventImp &evt)
1329 {
1330 if (fFTM.SaveStaticData(evt.GetString()))
1331 return T::GetCurrentState();
1332
1333 ostringstream msg;
1334 msg << "Writing static data to file '" << evt.GetString() << "' failed ";
1335 msg << "(" << strerror(errno) << ")";
1336
1337 T::Warn(msg);
1338
1339 return T::GetCurrentState();
1340 }
1341
1342 int SetThreshold(const EventImp &evt)
1343 {
1344 if (!CheckEventSize(evt.GetSize(), "SetThreshold", 8))
1345 return T::kSM_FatalError;
1346
1347 const int32_t *data = evt.Ptr<int32_t>();
1348
1349 if (!fFTM.SetThreshold(data[0], data[1]))
1350 T::Warn("SetThreshold - Maximum allowed patch number 159, valid value range 0-0xffff");
1351
1352 return T::GetCurrentState();
1353 }
1354
1355 int EnableFTU(const EventImp &evt)
1356 {
1357 if (!CheckEventSize(evt.GetSize(), "EnableFTU", 5))
1358 return T::kSM_FatalError;
1359
1360 const int32_t &board = evt.Get<int32_t>();
1361 const int8_t &enable = evt.Get<int8_t>(4);
1362
1363 if (!fFTM.EnableFTU(board, enable))
1364 T::Warn("EnableFTU - Board number must be <40.");
1365
1366 return T::GetCurrentState();
1367 }
1368
1369 int ToggleFTU(const EventImp &evt)
1370 {
1371 if (!CheckEventSize(evt.GetSize(), "ToggleFTU", 4))
1372 return T::kSM_FatalError;
1373
1374 if (!fFTM.ToggleFTU(evt.GetInt()))
1375 T::Warn("ToggleFTU - Allowed range of boards 0-39.");
1376
1377 return T::GetCurrentState();
1378 }
1379
1380 int SetTriggerInterval(const EventImp &evt)
1381 {
1382 if (!CheckEventSize(evt.GetSize(), "SetTriggerInterval", 4))
1383 return T::kSM_FatalError;
1384
1385 if (!fFTM.SetTriggerInterval(evt.GetInt()))
1386 T::Warn("SetTriggerInterval - Value out of range.");
1387
1388 return T::GetCurrentState();
1389 }
1390
1391 int SetTriggerDelay(const EventImp &evt)
1392 {
1393 if (!CheckEventSize(evt.GetSize(), "SetTriggerDelay", 4))
1394 return T::kSM_FatalError;
1395
1396 if (!fFTM.SetTriggerDelay(evt.GetInt()))
1397 T::Warn("SetTriggerDealy - Value out of range.");
1398
1399 return T::GetCurrentState();
1400 }
1401
1402 int SetTimeMarkerDelay(const EventImp &evt)
1403 {
1404 if (!CheckEventSize(evt.GetSize(), "SetTimeMarkerDelay", 4))
1405 return T::kSM_FatalError;
1406
1407 if (!fFTM.SetTimeMarkerDelay(evt.GetInt()))
1408 T::Warn("SetTimeMarkerDelay - Value out of range.");
1409
1410 return T::GetCurrentState();
1411 }
1412
1413 int SetPrescaling(const EventImp &evt)
1414 {
1415 if (!CheckEventSize(evt.GetSize(), "SetPrescaling", 4))
1416 return T::kSM_FatalError;
1417
1418 if (!fFTM.SetPrescaling(evt.GetInt()-1))
1419 T::Warn("SetPrescaling - Value out of range.");
1420
1421 return T::GetCurrentState();
1422 }
1423
1424 int SetTriggerSeq(const EventImp &evt)
1425 {
1426 if (!CheckEventSize(evt.GetSize(), "SetTriggerSeq", 6))
1427 return T::kSM_FatalError;
1428
1429 const uint16_t *data = evt.Ptr<uint16_t>();
1430
1431 if (!fFTM.SetTriggerSeq(data))
1432 T::Warn("SetTriggerSeq - Value out of range.");
1433
1434 return T::GetCurrentState();
1435 }
1436
1437 int SetDeadTime(const EventImp &evt)
1438 {
1439 if (!CheckEventSize(evt.GetSize(), "SetDeadTime", 4))
1440 return T::kSM_FatalError;
1441
1442 if (!fFTM.SetDeadTime(evt.GetInt()))
1443 T::Warn("SetDeadTime - Value out of range.");
1444
1445 return T::GetCurrentState();
1446 }
1447
1448 int SetTriggerMultiplicity(const EventImp &evt)
1449 {
1450 if (!CheckEventSize(evt.GetSize(), "SetTriggerMultiplicity", 2))
1451 return T::kSM_FatalError;
1452
1453 if (!fFTM.SetTriggerMultiplicity(evt.GetUShort()))
1454 T::Warn("SetTriggerMultiplicity - Value out of range.");
1455
1456 return T::GetCurrentState();
1457 }
1458
1459 int SetCalibMultiplicity(const EventImp &evt)
1460 {
1461 if (!CheckEventSize(evt.GetSize(), "SetCalibMultiplicity", 2))
1462 return T::kSM_FatalError;
1463
1464 if (!fFTM.SetCalibMultiplicity(evt.GetUShort()))
1465 T::Warn("SetCalibMultiplicity - Value out of range.");
1466
1467 return T::GetCurrentState();
1468 }
1469
1470 int SetTriggerWindow(const EventImp &evt)
1471 {
1472 if (!CheckEventSize(evt.GetSize(), "SetTriggerWindow", 2))
1473 return T::kSM_FatalError;
1474
1475 if (!fFTM.SetTriggerWindow(evt.GetUShort()))
1476 T::Warn("SetTriggerWindow - Value out of range.");
1477
1478 return T::GetCurrentState();
1479 }
1480
1481 int SetCalibWindow(const EventImp &evt)
1482 {
1483 if (!CheckEventSize(evt.GetSize(), "SetCalibWindow", 2))
1484 return T::kSM_FatalError;
1485
1486 if (!fFTM.SetCalibWindow(evt.GetUShort()))
1487 T::Warn("SetCalibWindow - Value out of range.");
1488
1489 return T::GetCurrentState();
1490 }
1491
1492 int SetClockRegister(const EventImp &evt)
1493 {
1494 if (!CheckEventSize(evt.GetSize(), "SetClockRegister", 8*8))
1495 return T::kSM_FatalError;
1496
1497 const uint64_t *reg = evt.Ptr<uint64_t>();
1498
1499 if (!fFTM.SetClockRegister(reg))
1500 T::Warn("SetClockRegister - Value out of range.");
1501
1502 return T::GetCurrentState();
1503 }
1504
1505 int SetClockFrequency(const EventImp &evt)
1506 {
1507 if (!CheckEventSize(evt.GetSize(), "SetClockFrequency", 2))
1508 return T::kSM_FatalError;
1509
1510 const map<uint16_t,array<uint64_t, 8>>::const_iterator it =
1511 fClockCondSetup.find(evt.GetUShort());
1512
1513 if (it==fClockCondSetup.end())
1514 {
1515 T::Warn("SetClockFrequency - Frequency not supported.");
1516 return T::GetCurrentState();
1517 }
1518
1519 if (!fFTM.SetClockRegister(it->second.data()))
1520 T::Warn("SetClockFrequency - Register values out of range.");
1521
1522 return T::GetCurrentState();
1523 }
1524
1525 int Enable(const EventImp &evt, FTM::StaticData::GeneralSettings type)
1526 {
1527 if (!CheckEventSize(evt.GetSize(), "Enable", 1))
1528 return T::kSM_FatalError;
1529
1530 fFTM.Enable(type, evt.GetBool());
1531
1532 return T::GetCurrentState();
1533 }
1534
1535 int EnablePixel(const EventImp &evt, bool b)
1536 {
1537 if (!CheckEventSize(evt.GetSize(), "EnablePixel", 2))
1538 return T::kSM_FatalError;
1539
1540 if (!fFTM.EnablePixel(evt.GetUShort(), b))
1541 T::Warn("EnablePixel - Value out of range.");
1542
1543 return T::GetCurrentState();
1544 }
1545
1546 int DisableAllPixelsExcept(const EventImp &evt)
1547 {
1548 if (!CheckEventSize(evt.GetSize(), "DisableAllPixelsExcept", 2))
1549 return T::kSM_FatalError;
1550
1551 if (!fFTM.DisableAllPixelsExcept(evt.GetUShort()))
1552 T::Warn("DisableAllPixelsExcept - Value out of range.");
1553
1554 return T::GetCurrentState();
1555 }
1556
1557 int DisableAllPatchesExcept(const EventImp &evt)
1558 {
1559 if (!CheckEventSize(evt.GetSize(), "DisableAllPatchesExcept", 2))
1560 return T::kSM_FatalError;
1561
1562 if (!fFTM.DisableAllPatchesExcept(evt.GetUShort()))
1563 T::Warn("DisableAllPatchesExcept - Value out of range.");
1564
1565 return T::GetCurrentState();
1566 }
1567
1568 int TogglePixel(const EventImp &evt)
1569 {
1570 if (!CheckEventSize(evt.GetSize(), "TogglePixel", 2))
1571 return T::kSM_FatalError;
1572
1573 if (!fFTM.TogglePixel(evt.GetUShort()))
1574 T::Warn("TogglePixel - Value out of range.");
1575
1576 return T::GetCurrentState();
1577 }
1578
1579 int ResetCrate(const EventImp &evt)
1580 {
1581 if (!CheckEventSize(evt.GetSize(), "ResetCrate", 2))
1582 return T::kSM_FatalError;
1583
1584 fFTM.CmdResetCrate(evt.GetUShort());
1585
1586 return T::GetCurrentState();
1587 }
1588
1589 int Disconnect()
1590 {
1591 // Close all connections
1592 fFTM.PostClose(false);
1593
1594 /*
1595 // Now wait until all connection have been closed and
1596 // all pending handlers have been processed
1597 poll();
1598 */
1599
1600 return T::GetCurrentState();
1601 }
1602
1603 int Reconnect(const EventImp &evt)
1604 {
1605 // Close all connections to supress the warning in SetEndpoint
1606 fFTM.PostClose(false);
1607
1608 // Now wait until all connection have been closed and
1609 // all pending handlers have been processed
1610 poll();
1611
1612 if (evt.GetBool())
1613 fFTM.SetEndpoint(evt.GetString());
1614
1615 // Now we can reopen the connection
1616 fFTM.PostClose(true);
1617
1618 return T::GetCurrentState();
1619 }
1620
1621 /*
1622 int Transition(const Event &evt)
1623 {
1624 switch (evt.GetTargetState())
1625 {
1626 case kDisconnected:
1627 case kConnected:
1628 }
1629
1630 return T::kSM_FatalError;
1631 }*/
1632
1633 int64_t fCounterReg;
1634 int64_t fCounterStat;
1635
1636 typedef map<string, FTM::StaticData> Configs;
1637 Configs fConfigs;
1638 Configs::const_iterator fTargetConfig;
1639
1640 int ConfigureFTM(const EventImp &evt)
1641 {
1642 const string name = evt.GetText();
1643
1644 fTargetConfig = fConfigs.find(name);
1645 if (fTargetConfig==fConfigs.end())
1646 {
1647 T::Error("ConfigureFTM - Run-type '"+name+"' not found.");
1648 return T::GetCurrentState();
1649 }
1650
1651 T::Message("Starting configuration for '"+name+"'");
1652
1653 fCounterReg = fFTM.GetCounter(FTM::kRegister);
1654 fFTM.CmdStopRun();
1655
1656 return FTM::kConfiguring1;
1657 }
1658
1659 int ResetConfig()
1660 {
1661 return fFTM.GetState();
1662 }
1663
1664 int Execute()
1665 {
1666 // Dispatch (execute) at most one handler from the queue. In contrary
1667 // to run_one(), it doesn't wait until a handler is available
1668 // which can be dispatched, so poll_one() might return with 0
1669 // handlers dispatched. The handlers are always dispatched/executed
1670 // synchronously, i.e. within the call to poll_one()
1671 poll_one();
1672
1673 // If FTM is neither in data taking nor idle,
1674 // leave configuration state
1675 switch (fFTM.GetState())
1676 {
1677 case ConnectionFTM::kDisconnected: return FTM::kDisconnected;
1678 case ConnectionFTM::kConnected: return FTM::kConnected;
1679 default:
1680 break;
1681 }
1682
1683 switch (T::GetCurrentState())
1684 {
1685 case FTM::kConfiguring1:
1686 // If FTM has received an anwer to the stop_run command
1687 // the counter for the registers has been increased
1688 if (fFTM.GetCounter(FTM::kRegister)<=fCounterReg)
1689 break;
1690
1691 // If now the state is not idle as expected this means we had
1692 // an error (maybe old events waiting in the queue)
1693 if (fFTM.GetState()!=ConnectionFTM::kIdle &&
1694 fFTM.GetState()!=ConnectionFTM::kConfigured)
1695 return FTM::kConfigError1;
1696
1697 fCounterStat = fFTM.GetCounter(FTM::kStaticData);
1698
1699 T::Message("Trigger successfully disabled... sending new configuration.");
1700
1701 fFTM.CmdSendStatDat(fTargetConfig->second);
1702
1703 // Next state is: wait for the answer to our configuration
1704 return FTM::kConfiguring2;
1705
1706 case FTM::kConfiguring2:
1707 case FTM::kConfigured:
1708 // If FTM has received an anwer to the stop_run command
1709 // the counter for the registers has been increased
1710 if (fFTM.GetCounter(FTM::kStaticData)<=fCounterStat)
1711 break;
1712
1713 // If now the configuration is not what we expected
1714 // we had an error (maybe old events waiting in the queue?)
1715 // ======================
1716 if (fFTM.GetState()!=ConnectionFTM::kConfigured)
1717 return FTM::kConfigError2;
1718 // ======================
1719
1720 // Check configuration again when a new static data block
1721 // will be received
1722 fCounterStat = fFTM.GetCounter(FTM::kStaticData);
1723
1724 T::Message("Sending new configuration was successfull.");
1725
1726 // Next state is: wait for the answer to our configuration
1727 return FTM::kConfigured;
1728
1729 default:
1730 switch (fFTM.GetState())
1731 {
1732 case ConnectionFTM::kIdle: return FTM::kIdle;
1733 case ConnectionFTM::kConfigured: return FTM::kIdle;
1734 case ConnectionFTM::kTakingData: return FTM::kTakingData;
1735 default:
1736 throw runtime_error("StateMachienFTM - Execute() - Inavlid state.");
1737 }
1738 }
1739
1740 if (T::GetCurrentState()==FTM::kConfigured &&
1741 fFTM.GetState()==ConnectionFTM::kTakingData)
1742 return FTM::kTakingData;
1743
1744 return T::GetCurrentState();
1745 }
1746
1747public:
1748 StateMachineFTM(ostream &out=cout) :
1749 T(out, "FTM_CONTROL"), ba::io_service::work(static_cast<ba::io_service&>(*this)),
1750 fFTM(*this, *this)
1751 {
1752 // ba::io_service::work is a kind of keep_alive for the loop.
1753 // It prevents the io_service to go to stopped state, which
1754 // would prevent any consecutive calls to run()
1755 // or poll() to do nothing. reset() could also revoke to the
1756 // previous state but this might introduce some overhead of
1757 // deletion and creation of threads and more.
1758
1759
1760 // State names
1761 T::AddStateName(FTM::kDisconnected, "Disconnected",
1762 "FTM board not connected via ethernet.");
1763
1764 T::AddStateName(FTM::kConnected, "Connected",
1765 "Ethernet connection to FTM established (no state received yet).");
1766
1767 T::AddStateName(FTM::kIdle, "Idle",
1768 "Ethernet connection to FTM established, FTM in idle state.");
1769
1770 T::AddStateName(FTM::kConfiguring1, "Configuring1",
1771 "Command to diable run sent... waiting for response.");
1772 T::AddStateName(FTM::kConfiguring2, "Configuring2",
1773 "New configuration sent... waiting for response.");
1774 T::AddStateName(FTM::kConfigured, "Configured",
1775 "Received answer identical with target configuration.");
1776
1777 T::AddStateName(FTM::kTakingData, "TakingData",
1778 "Ethernet connection to FTM established, FTM is in taking data state.");
1779
1780 T::AddStateName(FTM::kConfigError1, "ErrorInConfig1", "");
1781 T::AddStateName(FTM::kConfigError2, "ErrorInConfig2", "");
1782
1783 // FTM Commands
1784 T::AddEvent("TOGGLE_LED", FTM::kIdle)
1785 (Wrapper(bind(&ConnectionFTM::CmdToggleLed, &fFTM)))
1786 ("toggle led");
1787
1788 T::AddEvent("PING", FTM::kIdle)
1789 (Wrapper(bind(&ConnectionFTM::CmdPing, &fFTM)))
1790 ("send ping");
1791
1792 T::AddEvent("REQUEST_DYNAMIC_DATA", FTM::kIdle)
1793 (Wrapper(bind(&ConnectionFTM::CmdReqDynDat, &fFTM)))
1794 ("request transmission of dynamic data block");
1795
1796 T::AddEvent("REQUEST_STATIC_DATA", FTM::kIdle)
1797 (Wrapper(bind(&ConnectionFTM::CmdReqStatDat, &fFTM)))
1798 ("request transmission of static data from FTM to memory");
1799
1800 T::AddEvent("GET_REGISTER", "I", FTM::kIdle)
1801 (bind(&StateMachineFTM::GetRegister, this, placeholders::_1))
1802 ("read register from address addr"
1803 "|addr[short]:Address of register");
1804
1805 T::AddEvent("SET_REGISTER", "I:2", FTM::kIdle)
1806 (bind(&StateMachineFTM::SetRegister, this, placeholders::_1))
1807 ("set register to value"
1808 "|addr[short]:Address of register"
1809 "|val[short]:Value to be set");
1810
1811 T::AddEvent("START_RUN", FTM::kIdle, FTM::kConfigured)
1812 (Wrapper(bind(&ConnectionFTM::CmdStartRun, &fFTM)))
1813 ("start a run (start distributing triggers)");
1814
1815 T::AddEvent("STOP_RUN", FTM::kTakingData)
1816 (Wrapper(bind(&ConnectionFTM::CmdStopRun, &fFTM)))
1817 ("stop a run (stop distributing triggers)");
1818
1819 T::AddEvent("TAKE_N_EVENTS", "I", FTM::kIdle)
1820 (bind(&StateMachineFTM::TakeNevents, this, placeholders::_1))
1821 ("take n events (distribute n triggers)|number[int]:Number of events to be taken");
1822
1823 T::AddEvent("DISABLE_REPORTS", "B", FTM::kIdle)
1824 (bind(&StateMachineFTM::DisableReports, this, placeholders::_1))
1825 ("disable sending rate reports"
1826 "|status[bool]:disable or enable that the FTM sends rate reports (yes/no)");
1827
1828 T::AddEvent("SET_THRESHOLD", "I:2", FTM::kIdle, FTM::kTakingData)
1829 (bind(&StateMachineFTM::SetThreshold, this, placeholders::_1))
1830 ("Set the comparator threshold"
1831 "|Patch[idx]:Index of the patch (0-159), -1 for all"
1832 "|Threshold[counts]:Threshold to be set in binary counts");
1833
1834 T::AddEvent("SET_PRESCALING", "I:1", FTM::kIdle)
1835 (bind(&StateMachineFTM::SetPrescaling, this, placeholders::_1))
1836 (""
1837 "|[]:");
1838
1839 T::AddEvent("ENABLE_FTU", "I:1;B:1", FTM::kIdle)
1840 (bind(&StateMachineFTM::EnableFTU, this, placeholders::_1))
1841 ("Enable or disable FTU"
1842 "|Board[idx]:Index of the board (0-39), -1 for all"
1843 "|Enable[bool]:Whether FTU should be enabled or disabled (yes/no)");
1844
1845 T::AddEvent("DISABLE_PIXEL", "S:1", FTM::kIdle, FTM::kTakingData)
1846 (bind(&StateMachineFTM::EnablePixel, this, placeholders::_1, false))
1847 ("(-1 or all)");
1848
1849 T::AddEvent("ENABLE_PIXEL", "S:1", FTM::kIdle, FTM::kTakingData)
1850 (bind(&StateMachineFTM::EnablePixel, this, placeholders::_1, true))
1851 ("(-1 or all)");
1852
1853 T::AddEvent("DISABLE_ALL_PIXELS_EXCEPT", "S:1", FTM::kIdle)
1854 (bind(&StateMachineFTM::DisableAllPixelsExcept, this, placeholders::_1))
1855 ("");
1856
1857 T::AddEvent("DISABLE_ALL_PATCHES_EXCEPT", "S:1", FTM::kIdle)
1858 (bind(&StateMachineFTM::DisableAllPatchesExcept, this, placeholders::_1))
1859 ("");
1860
1861 T::AddEvent("TOGGLE_PIXEL", "S:1", FTM::kIdle)
1862 (bind(&StateMachineFTM::TogglePixel, this, placeholders::_1))
1863 ("");
1864
1865 T::AddEvent("TOGGLE_FTU", "I:1", FTM::kIdle)
1866 (bind(&StateMachineFTM::ToggleFTU, this, placeholders::_1))
1867 ("Toggle status of FTU (this is mainly meant to be used in the GUI)"
1868 "|Board[idx]:Index of the board (0-39)");
1869
1870 T::AddEvent("SET_TRIGGER_INTERVAL", "I:1", FTM::kIdle)
1871 (bind(&StateMachineFTM::SetTriggerInterval, this, placeholders::_1))
1872 ("Sets the trigger interval which is the distance between two consecutive artificial triggers."
1873 "|interval[int]:The applied trigger interval is: interval*4ns+8ns");
1874
1875 T::AddEvent("SET_TRIGGER_DELAY", "I:1", FTM::kIdle)
1876 (bind(&StateMachineFTM::SetTriggerDelay, this, placeholders::_1))
1877 (""
1878 "|delay[int]:The applied trigger delay is: delay*4ns+8ns");
1879
1880 T::AddEvent("SET_TIME_MARKER_DELAY", "I:1", FTM::kIdle)
1881 (bind(&StateMachineFTM::SetTimeMarkerDelay, this, placeholders::_1))
1882 (""
1883 "|delay[int]:The applied time marker delay is: delay*4ns+8ns");
1884
1885 T::AddEvent("SET_DEAD_TIME", "I:1", FTM::kIdle)
1886 (bind(&StateMachineFTM::SetDeadTime, this, placeholders::_1))
1887 (""
1888 "|dead_time[int]:The applied dead time is: dead_time*4ns+8ns");
1889
1890 T::AddEvent("ENABLE_TRIGGER", "B:1", FTM::kIdle)
1891 (bind(&StateMachineFTM::Enable, this, placeholders::_1, FTM::StaticData::kTrigger))
1892 ("Switch on the physics trigger"
1893 "|Enable[bool]:Enable physics trigger (yes/no)");
1894
1895 // FIXME: Switch on/off depending on sequence
1896 T::AddEvent("ENABLE_EXT1", "B:1", FTM::kIdle)
1897 (bind(&StateMachineFTM::Enable, this, placeholders::_1, FTM::StaticData::kExt1))
1898 ("Switch on the triggers through the first external line"
1899 "|Enable[bool]:Enable ext1 trigger (yes/no)");
1900
1901 // FIXME: Switch on/off depending on sequence
1902 T::AddEvent("ENABLE_EXT2", "B:1", FTM::kIdle)
1903 (bind(&StateMachineFTM::Enable, this, placeholders::_1, FTM::StaticData::kExt2))
1904 ("Switch on the triggers through the second external line"
1905 "|Enable[bool]:Enable ext2 trigger (yes/no)");
1906
1907 T::AddEvent("ENABLE_VETO", "B:1", FTM::kIdle)
1908 (bind(&StateMachineFTM::Enable, this, placeholders::_1, FTM::StaticData::kVeto))
1909 ("Enable veto line"
1910 "|Enable[bool]:Enable veto (yes/no)");
1911
1912 T::AddEvent("ENABLE_CLOCK_CONDITIONER", "B:1", FTM::kIdle)
1913 (bind(&StateMachineFTM::Enable, this, placeholders::_1, FTM::StaticData::kClockConditioner))
1914 ("Enable clock conidtioner output in favor of time marker output"
1915 "|Enable[bool]:Enable clock conditioner (yes/no)");
1916
1917 T::AddEvent("SET_TRIGGER_SEQUENCE", "S:3", FTM::kIdle)
1918 (bind(&StateMachineFTM::SetTriggerSeq, this, placeholders::_1))
1919 ("Setup the sequence of artificial triggers produced by the FTM"
1920 "|Ped[short]:number of pedestal triggers in a row"
1921 "|LPext[short]:number of triggers of the external light pulser"
1922 "|LPint[short]:number of triggers of the internal light pulser");
1923
1924 T::AddEvent("SET_TRIGGER_MULTIPLICITY", "S:1", FTM::kIdle)
1925 (bind(&StateMachineFTM::SetTriggerMultiplicity, this, placeholders::_1))
1926 ("Setup the Multiplicity condition for physcis triggers"
1927 "|N[int]:Number of requirered coincident triggers from sum-patches (1-40)");
1928
1929 T::AddEvent("SET_TRIGGER_WINDOW", "S:1", FTM::kIdle)
1930 (bind(&StateMachineFTM::SetTriggerWindow, this, placeholders::_1))
1931 ("");
1932
1933 T::AddEvent("SET_CALIBRATION_MULTIPLICITY", "S:1", FTM::kIdle)
1934 (bind(&StateMachineFTM::SetCalibMultiplicity, this, placeholders::_1))
1935 ("Setup the Multiplicity condition for artificial (calibration) triggers"
1936 "|N[int]:Number of requirered coincident triggers from sum-patches (1-40)");
1937
1938 T::AddEvent("SET_CALIBRATION_WINDOW", "S:1", FTM::kIdle)
1939 (bind(&StateMachineFTM::SetCalibWindow, this, placeholders::_1))
1940 ("");
1941
1942 T::AddEvent("SET_CLOCK_FREQUENCY", "S:1", FTM::kIdle)
1943 (bind(&StateMachineFTM::SetClockFrequency, this, placeholders::_1))
1944 ("");
1945
1946 T::AddEvent("SET_CLOCK_REGISTER", "X:8", FTM::kIdle)
1947 (bind(&StateMachineFTM::SetClockRegister, this, placeholders::_1))
1948 ("");
1949
1950 // A new configure will first stop the FTM this means
1951 // we can allow it in idle _and_ taking data
1952 T::AddEvent("CONFIGURE", "C", FTM::kIdle, FTM::kTakingData)
1953 (bind(&StateMachineFTM::ConfigureFTM, this, placeholders::_1))
1954 ("");
1955
1956 T::AddEvent("RESET_CONFIGURE", FTM::kConfiguring1, FTM::kConfiguring2, FTM::kConfigured, FTM::kConfigError1, FTM::kConfigError2)
1957 (bind(&StateMachineFTM::ResetConfig, this))
1958 ("");
1959
1960
1961
1962 T::AddEvent("RESET_CRATE", "S:1", FTM::kIdle)
1963 (bind(&StateMachineFTM::ResetCrate, this, placeholders::_1))
1964 ("Reset one of the crates 0-3"
1965 "|crate[short]:Crate number to be reseted (0-3)");
1966
1967 T::AddEvent("RESET_CAMERA", FTM::kIdle)
1968 (Wrapper(bind(&ConnectionFTM::CmdResetCamera, &fFTM)))
1969 ("Reset all crates. The commands are sent in the order 0,1,2,3");
1970
1971
1972 // Load/save static data block
1973 T::AddEvent("SAVE", "C", FTM::kIdle)
1974 (bind(&StateMachineFTM::SaveStaticData, this, placeholders::_1))
1975 ("Saves the static data (FTM configuration) from memory to a file"
1976 "|filename[string]:Filename (can include a path), .bin is automatically added");
1977
1978 T::AddEvent("LOAD", "C", FTM::kIdle)
1979 (bind(&StateMachineFTM::LoadStaticData, this, placeholders::_1))
1980 ("Loads the static data (FTM configuration) from a file into memory and sends it to the FTM"
1981 "|filename[string]:Filename (can include a path), .bin is automatically added");
1982
1983
1984
1985 // Verbosity commands
1986 T::AddEvent("SET_VERBOSE", "B")
1987 (bind(&StateMachineFTM::SetVerbosity, this, placeholders::_1))
1988 ("set verbosity state"
1989 "|verbosity[bool]:disable or enable verbosity for received data (yes/no), except dynamic data");
1990
1991 T::AddEvent("SET_HEX_OUTPUT", "B")
1992 (bind(&StateMachineFTM::SetHexOutput, this, placeholders::_1))
1993 ("enable or disable hex output for received data"
1994 "|hexout[bool]:disable or enable hex output for received data (yes/no)");
1995
1996 T::AddEvent("SET_DYNAMIC_OUTPUT", "B")
1997 (bind(&StateMachineFTM::SetDynamicOut, this, placeholders::_1))
1998 ("enable or disable output for received dynamic data (data is still broadcasted via Dim)"
1999 "|dynout[bool]:disable or enable output for dynamic data (yes/no)");
2000
2001
2002 // Conenction commands
2003 T::AddEvent("DISCONNECT", FTM::kConnected, FTM::kIdle)
2004 (bind(&StateMachineFTM::Disconnect, this))
2005 ("disconnect from ethernet");
2006
2007 T::AddEvent("RECONNECT", "O", FTM::kDisconnected, FTM::kConnected, FTM::kIdle, FTM::kConfigured)
2008 (bind(&StateMachineFTM::Reconnect, this, placeholders::_1))
2009 ("(Re)connect ethernet connection to FTM, a new address can be given"
2010 "|[host][string]:new ethernet address in the form <host:port>");
2011
2012 fFTM.StartConnect();
2013 }
2014
2015 void SetEndpoint(const string &url)
2016 {
2017 fFTM.SetEndpoint(url);
2018 }
2019
2020 map<uint16_t, array<uint64_t, 8>> fClockCondSetup;
2021
2022 template<class V>
2023 bool CheckConfigVal(Configuration &conf, V max, const string &name, const string &sub)
2024 {
2025 if (!conf.HasDef(name, sub))
2026 {
2027 T::Error("Neither "+name+"default nor "+name+sub+" found.");
2028 return false;
2029 }
2030
2031 const V val = conf.GetDef<V>(name, sub);
2032
2033 if (val<=max)
2034 return true;
2035
2036 ostringstream str;
2037 str << name << sub << "=" << val << " exceeds allowed maximum of " << max << "!";
2038 T::Error(str);
2039
2040 return false;
2041 }
2042
2043 int EvalOptions(Configuration &conf)
2044 {
2045 // ---------- General setup ----------
2046 fFTM.SetVerbose(!conf.Get<bool>("quiet"));
2047 fFTM.SetHexOutput(conf.Get<bool>("hex-out"));
2048 fFTM.SetDynamicOut(conf.Get<bool>("dynamic-out"));
2049
2050 // ---------- Setup clock conditioner frequencies ----------
2051 const vector<uint16_t> freq = conf.Vec<uint16_t>("clock-conditioner.frequency");
2052 if (freq.size()==0)
2053 T::Warn("No frequencies for the clock-conditioner defined.");
2054 else
2055 T::Message("Defining clock conditioner frequencies");
2056 for (vector<uint16_t>::const_iterator it=freq.begin();
2057 it!=freq.end(); it++)
2058 {
2059 if (fClockCondSetup.count(*it)>0)
2060 {
2061 T::Error("clock-conditioner frequency defined twice.");
2062 return 1;
2063 }
2064
2065 if (!conf.HasDef("clock-conditioner.R0.", *it) ||
2066 !conf.HasDef("clock-conditioner.R1.", *it) ||
2067 !conf.HasDef("clock-conditioner.R8.", *it) ||
2068 !conf.HasDef("clock-conditioner.R9.", *it) ||
2069 !conf.HasDef("clock-conditioner.R11.", *it) ||
2070 !conf.HasDef("clock-conditioner.R13.", *it) ||
2071 !conf.HasDef("clock-conditioner.R14.", *it) ||
2072 !conf.HasDef("clock-conditioner.R15.", *it))
2073 {
2074 T::Error("clock-conditioner values incomplete.");
2075 return 1;
2076 }
2077
2078 array<uint64_t, 8> &arr = fClockCondSetup[*it];
2079
2080 arr[0] = conf.GetDef<Hex<uint32_t>>("clock-conditioner.R0.", *it);
2081 arr[1] = conf.GetDef<Hex<uint32_t>>("clock-conditioner.R1.", *it);
2082 arr[2] = conf.GetDef<Hex<uint32_t>>("clock-conditioner.R8.", *it);
2083 arr[3] = conf.GetDef<Hex<uint32_t>>("clock-conditioner.R9.", *it);
2084 arr[4] = conf.GetDef<Hex<uint32_t>>("clock-conditioner.R11.", *it);
2085 arr[5] = conf.GetDef<Hex<uint32_t>>("clock-conditioner.R13.", *it);
2086 arr[6] = conf.GetDef<Hex<uint32_t>>("clock-conditioner.R14.", *it);
2087 arr[7] = conf.GetDef<Hex<uint32_t>>("clock-conditioner.R15.", *it);
2088
2089 ostringstream out;
2090 out << " -> " << setw(4) << *it << "MHz:" << hex << setfill('0');
2091 for (int i=0; i<8; i++)
2092 out << " " << setw(8) << arr[i];
2093 T::Message(out.str());
2094 }
2095
2096 // ---------- Setup run types ---------
2097 const vector<string> types = conf.Vec<string>("run-type");
2098 if (types.size()==0)
2099 T::Warn("No run-types defined.");
2100 else
2101 T::Message("Defining run-types");
2102 for (vector<string>::const_iterator it=types.begin();
2103 it!=types.end(); it++)
2104 {
2105 T::Message(" -> "+ *it);
2106
2107 if (fConfigs.count(*it)>0)
2108 {
2109 T::Error("Run-type "+*it+" defined twice.");
2110 return 2;
2111 }
2112
2113 FTM::StaticData data;
2114
2115 const uint16_t frq = conf.GetDef<uint16_t>("sampling-frequency.", *it);
2116 if (fClockCondSetup.count(frq)==0)
2117 {
2118 T::Error("sampling-frequency."+*it+" - frequency not available.");
2119 return 2;
2120 }
2121
2122 data.SetClockRegister(fClockCondSetup[frq].data());
2123
2124 // Trigger sequence ped:lp1:lp2
2125 // (data. is used here as an abbreviation for FTM::StaticData::
2126 if (!CheckConfigVal<bool> (conf, true, "enable-trigger.", *it) ||
2127 !CheckConfigVal<bool> (conf, true, "enable-external-1.", *it) ||
2128 !CheckConfigVal<bool> (conf, true, "enable-external-2.", *it) ||
2129 !CheckConfigVal<bool> (conf, true, "enable-veto.", *it) ||
2130 !CheckConfigVal<bool> (conf, true, "enable-clock-conditioner.", *it) ||
2131 !CheckConfigVal<uint16_t>(conf, data.kMaxSequence, "trigger-sequence-ped.", *it) ||
2132 !CheckConfigVal<uint16_t>(conf, data.kMaxSequence, "trigger-sequence-lp-ext.", *it) ||
2133 !CheckConfigVal<uint16_t>(conf, data.kMaxSequence, "trigger-sequence-lp-int.", *it) ||
2134 !CheckConfigVal<uint16_t>(conf, data.kMaxTriggerInterval, "trigger-interval.", *it) ||
2135 !CheckConfigVal<uint16_t>(conf, data.kMaxMultiplicity, "multiplicity-physics.", *it) ||
2136 !CheckConfigVal<uint16_t>(conf, data.kMaxMultiplicity, "multiplicity-calib.", *it) ||
2137 !CheckConfigVal<uint16_t>(conf, data.kMaxWindow, "coincidence-window-physics.", *it) ||
2138 !CheckConfigVal<uint16_t>(conf, data.kMaxWindow, "coincidence-window-calib.", *it) ||
2139 !CheckConfigVal<uint16_t>(conf, data.kMaxDeadTime, "dead-time.", *it) ||
2140 !CheckConfigVal<uint16_t>(conf, data.kMaxDelayTrigger, "trigger-delay.", *it) ||
2141 !CheckConfigVal<uint16_t>(conf, data.kMaxDelayTimeMarker, "time-marker-delay.", *it) ||
2142 !CheckConfigVal<uint16_t>(conf, 0xffff, "ftu-report-interval.", *it) ||
2143 0)
2144 return 2;
2145
2146 data.Enable(data.kTrigger, conf.GetDef<bool>("enable-trigger.", *it));
2147 data.Enable(data.kExt1, conf.GetDef<bool>("enable-external-1.", *it));
2148 data.Enable(data.kExt2, conf.GetDef<bool>("enable-external-2.", *it));
2149 data.Enable(data.kVeto, conf.GetDef<bool>("enable-veto.", *it));
2150 data.Enable(data.kClockConditioner, conf.GetDef<bool>("enable-clock-conditioner.", *it));
2151
2152 // [ms] Interval between two artificial triggers (no matter which type) minimum 1ms, 10 bit
2153 data.fTriggerInterval = conf.GetDef<uint16_t>("trigger-interval.", *it);
2154 data.fMultiplicityPhysics = conf.GetDef<uint16_t>("multiplicity-physics.", *it);
2155 data.fMultiplicityCalib = conf.GetDef<uint16_t>("multiplicity-calib.", *it);
2156 data.fWindowPhysics = conf.GetDef<uint16_t>("coincidence-window-physics.", *it); /// (4ns * x + 8ns)
2157 data.fWindowCalib = conf.GetDef<uint16_t>("coincidence-window-calib.", *it); /// (4ns * x + 8ns)
2158 data.fDelayTrigger = conf.GetDef<uint16_t>("trigger-delay.", *it); /// (4ns * x + 8ns)
2159 data.fDelayTimeMarker = conf.GetDef<uint16_t>("time-marker-delay.", *it); /// (4ns * x + 8ns)
2160 data.fDeadTime = conf.GetDef<uint16_t>("dead-time.", *it); /// (4ns * x + 8ns)
2161
2162 data.SetPrescaling(conf.GetDef<uint16_t>("ftu-report-interval.", *it));
2163
2164 const uint16_t seqped = conf.GetDef<uint16_t>("trigger-sequence-ped.", *it);
2165 const uint16_t seqint = conf.GetDef<uint16_t>("trigger-sequence-lp-int.", *it);
2166 const uint16_t seqext = conf.GetDef<uint16_t>("trigger-sequence-lp-ext.", *it);
2167
2168 data.SetSequence(seqped, seqint, seqext);
2169
2170 data.EnableAllFTU();
2171 data.EnableAllPixel();
2172
2173 const vector<uint16_t> pat1 = conf.Vec<uint16_t>("disable-patch.default");
2174 const vector<uint16_t> pat2 = conf.Vec<uint16_t>("disable-patch."+*it);
2175
2176 const vector<uint16_t> pix1 = conf.Vec<uint16_t>("disable-pixel.default");
2177 const vector<uint16_t> pix2 = conf.Vec<uint16_t>("disable-pixel."+*it);
2178
2179 vector<uint16_t> pat, pix;
2180 pat.insert(pat.end(), pat1.begin(), pat1.end());
2181 pat.insert(pat.end(), pat2.begin(), pat2.end());
2182 pix.insert(pix.end(), pix1.begin(), pix1.end());
2183 pix.insert(pix.end(), pix2.begin(), pix2.end());
2184
2185 for (vector<uint16_t>::const_iterator ip=pat.begin(); ip!=pat.end(); ip++)
2186 {
2187 if (*ip>FTM::StaticData::kMaxPatchIdx)
2188 {
2189 ostringstream str;
2190 str << "disable-patch.*=" << *ip << " exceeds allowed maximum of " << FTM::StaticData::kMaxPatchIdx << "!";
2191 T::Error(str);
2192 return 2;
2193 }
2194 data.DisableFTU(*ip);
2195 }
2196 for (vector<uint16_t>::const_iterator ip=pix.begin(); ip!=pix.end(); ip++)
2197 {
2198 if (*ip>FTM::StaticData::kMaxPixelIdx)
2199 {
2200 ostringstream str;
2201 str << "disable-pixel.*=" << *ip << " exceeds allowed maximum of " << FTM::StaticData::kMaxPixelIdx << "!";
2202 T::Error(str);
2203 return 2;
2204 }
2205 data.EnablePixel(*ip, false);
2206 }
2207
2208 fConfigs[*it] = data;
2209
2210 /*
2211 threshold-A data[n].fDAC[0] = val
2212 threshold-B data[n].fDAC[1] = val
2213 threshold-C data[n].fDAC[2] = val
2214 threshold-D data[n].fDAC[3] = val
2215 threshold-H data[n].fDAC[4] = val
2216 */
2217
2218 // kMaxDAC = 0xfff,
2219 }
2220
2221 // FIXME: Add a check about unsused configurations
2222
2223 // ---------- FOR TESTING PURPOSE ---------
2224
2225 // fFTM.SetDefaultSetup(conf.Get<string>("default-setup"));
2226 fConfigs["test"] = FTM::StaticData();
2227
2228 // ---------- Setup connection endpoint ---------
2229 SetEndpoint(conf.Get<string>("addr"));
2230
2231 return -1;
2232 }
2233};
2234
2235// ------------------------------------------------------------------------
2236
2237#include "Main.h"
2238
2239/*
2240void RunThread(StateMachineImp *io_service)
2241{
2242 // This is necessary so that the StateMachien Thread can signal the
2243 // Readline to exit
2244 io_service->Run();
2245 Readline::Stop();
2246}
2247*/
2248/*
2249template<class S, class T>
2250int RunDim(Configuration &conf)
2251{
2252 WindowLog wout;
2253
2254 ReadlineColor::PrintBootMsg(wout, conf.GetName(), false);
2255
2256 if (conf.Has("log"))
2257 if (!wout.OpenLogFile(conf.Get<string>("log")))
2258 wout << kRed << "ERROR - Couldn't open log-file " << conf.Get<string>("log") << ": " << strerror(errno) << endl;
2259
2260 // Start io_service.Run to use the StateMachineImp::Run() loop
2261 // Start io_service.run to only use the commandHandler command detaching
2262 StateMachineFTM<S, T> io_service(wout);
2263 if (!io_service.EvalConfiguration(conf))
2264 return -1;
2265
2266 io_service.Run();
2267
2268 return 0;
2269}
2270*/
2271
2272template<class T, class S, class R>
2273int RunShell(Configuration &conf)
2274{
2275 return Main<T, StateMachineFTM<S, R>>(conf);
2276/*
2277 static T shell(conf.GetName().c_str(), conf.Get<int>("console")!=1);
2278
2279 WindowLog &win = shell.GetStreamIn();
2280 WindowLog &wout = shell.GetStreamOut();
2281
2282 if (conf.Has("log"))
2283 if (!wout.OpenLogFile(conf.Get<string>("log")))
2284 win << kRed << "ERROR - Couldn't open log-file " << conf.Get<string>("log") << ": " << strerror(errno) << endl;
2285
2286 StateMachineFTM<S, R> io_service(wout);
2287 if (!io_service.EvalConfiguration(conf))
2288 return -1;
2289
2290 shell.SetReceiver(io_service);
2291
2292 boost::thread t(bind(RunThread, &io_service));
2293 // boost::thread t(bind(&StateMachineFTM<S>::Run, &io_service));
2294
2295 if (conf.Has("cmd"))
2296 {
2297 const vector<string> v = conf.Get<vector<string>>("cmd");
2298 for (vector<string>::const_iterator it=v.begin(); it!=v.end(); it++)
2299 shell.ProcessLine(*it);
2300 }
2301
2302 if (conf.Has("exec"))
2303 {
2304 const vector<string> v = conf.Get<vector<string>>("exec");
2305 for (vector<string>::const_iterator it=v.begin(); it!=v.end(); it++)
2306 shell.Execute(*it);
2307 }
2308
2309 if (conf.Get<bool>("quit"))
2310 shell.Stop();
2311
2312 shell.Run(); // Run the shell
2313 io_service.Stop(); // Signal Loop-thread to stop
2314 // io_service.Close(); // Obsolete, done by the destructor
2315
2316 // Wait until the StateMachine has finished its thread
2317 // before returning and destroying the dim objects which might
2318 // still be in use.
2319 t.join();
2320
2321 return 0;
2322 */
2323}
2324
2325void SetupConfiguration(Configuration &conf)
2326{
2327 const string n = conf.GetName()+".log";
2328
2329 po::options_description config("Program options");
2330 config.add_options()
2331 ("dns", var<string>("localhost"), "Dim nameserver host name (Overwites DIM_DNS_NODE environment variable)")
2332 ("log,l", var<string>(n), "Write log-file")
2333 ("no-dim,d", po_bool(), "Disable dim services")
2334 ("console,c", var<int>(), "Use console (0=shell, 1=simple buffered, X=simple unbuffered)")
2335 ("cmd", vars<string>(), "Execute one or more commands at startup")
2336 ("exec,e", vars<string>(), "Execute one or more scrips at startup")
2337 ("quit", po_switch(), "Quit after startup");
2338 ;
2339
2340 po::options_description control("Control options");
2341 control.add_options()
2342 ("addr,a", var<string>("localhost:5000"), "Network address of FTM")
2343 ("quiet,q", po_bool(), "Disable printing contents of all received messages (except dynamic data) in clear text.")
2344 ("hex-out", po_bool(), "Enable printing contents of all printed messages also as hex data.")
2345 ("dynamic-out", po_bool(), "Enable printing received dynamic data.")
2346// ("default-setup", var<string>(), "Binary file with static data loaded whenever a connection to the FTM was established.")
2347 ;
2348
2349 po::options_description runtype("Run type configuration");
2350 runtype.add_options()
2351 ("clock-conditioner.frequency", vars<uint16_t>(), "Frequencies for which to setup the clock-conditioner")
2352 ("clock-conditioner.R0.*", var<Hex<uint32_t>>(), "Clock-conditioner R0 (replace * by the defined frequency)")
2353 ("clock-conditioner.R1.*", var<Hex<uint32_t>>(), "Clock-conditioner R1 (replace * by the defined frequency)")
2354 ("clock-conditioner.R8.*", var<Hex<uint32_t>>(), "Clock-conditioner R8 (replace * by the defined frequency)")
2355 ("clock-conditioner.R9.*", var<Hex<uint32_t>>(), "Clock-conditioner R9 (replace * by the defined frequency)")
2356 ("clock-conditioner.R11.*", var<Hex<uint32_t>>(), "Clock-conditioner R11 (replace * by the defined frequency)")
2357 ("clock-conditioner.R13.*", var<Hex<uint32_t>>(), "Clock-conditioner R13 (replace * by the defined frequency)")
2358 ("clock-conditioner.R14.*", var<Hex<uint32_t>>(), "Clock-conditioner R14 (replace * by the defined frequency)")
2359 ("clock-conditioner.R15.*", var<Hex<uint32_t>>(), "Clock-conditioner R15 (replace * by the defined frequency)")
2360 ("run-type", vars<string>(), "")
2361 ("sampling-frequency.*", var<uint16_t>(), "")
2362 ("enable-trigger.*", var<bool>(), "")
2363 ("enable-external-1.*", var<bool>(), "")
2364 ("enable-external-2.*", var<bool>(), "")
2365 ("enable-veto.*", var<bool>(), "")
2366 ("enable-clock-conditioner.*", var<bool>(), "")
2367 ("trigger-interval.*", var<uint16_t>(), "")
2368 ("trigger-sequence-ped.*", var<uint16_t>(), "")
2369 ("trigger-sequence-lp-int.*", var<uint16_t>(), "")
2370 ("trigger-sequence-lp-ext.*", var<uint16_t>(), "")
2371 ("multiplicity-physics.*", var<uint16_t>(), "")
2372 ("multiplicity-calib.*", var<uint16_t>(), "")
2373 ("coincidence-window-physics.*", var<uint16_t>(), "")
2374 ("coincidence-window-calib.*", var<uint16_t>(), "")
2375 ("dead-time.*", var<uint16_t>(), "")
2376 ("trigger-delay.*", var<uint16_t>(), "")
2377 ("time-marker-delay.*", var<uint16_t>(), "")
2378 ("diable-pixel.*", vars<uint16_t>(), "")
2379 ("diable-patch.*", vars<uint16_t>(), "")
2380 ("ftu-report-interval.*", var<uint16_t>(), "")
2381 ;
2382
2383 conf.AddEnv("dns", "DIM_DNS_NODE");
2384
2385 conf.AddOptions(config);
2386 conf.AddOptions(control);
2387 conf.AddOptions(runtype);
2388}
2389
2390/*
2391 Extract usage clause(s) [if any] for SYNOPSIS.
2392 Translators: "Usage" and "or" here are patterns (regular expressions) which
2393 are used to match the usage synopsis in program output. An example from cp
2394 (GNU coreutils) which contains both strings:
2395 Usage: cp [OPTION]... [-T] SOURCE DEST
2396 or: cp [OPTION]... SOURCE... DIRECTORY
2397 or: cp [OPTION]... -t DIRECTORY SOURCE...
2398 */
2399void PrintUsage()
2400{
2401 cout <<
2402 "The ftmctrl controls the FTM (FACT Trigger Master) board.\n"
2403 "\n"
2404 "The default is that the program is started without user intercation. "
2405 "All actions are supposed to arrive as DimCommands. Using the -c "
2406 "option, a local shell can be initialized. With h or help a short "
2407 "help message about the usuage can be brought to the screen.\n"
2408 "\n"
2409 "Usage: ftmctrl [-c type] [OPTIONS]\n"
2410 " or: ftmctrl [OPTIONS]\n";
2411 cout << endl;
2412}
2413
2414void PrintHelp()
2415{
2416 /* Additional help text which is printed after the configuration
2417 options goes here */
2418
2419 /*
2420 cout << "bla bla bla" << endl << endl;
2421 cout << endl;
2422 cout << "Environment:" << endl;
2423 cout << "environment" << endl;
2424 cout << endl;
2425 cout << "Examples:" << endl;
2426 cout << "test exam" << endl;
2427 cout << endl;
2428 cout << "Files:" << endl;
2429 cout << "files" << endl;
2430 cout << endl;
2431 */
2432}
2433
2434int main(int argc, const char* argv[])
2435{
2436 Configuration conf(argv[0]);
2437 conf.SetPrintUsage(PrintUsage);
2438 SetupConfiguration(conf);
2439
2440 po::variables_map vm;
2441 try
2442 {
2443 vm = conf.Parse(argc, argv);
2444 }
2445#if BOOST_VERSION > 104000
2446 catch (po::multiple_occurrences &e)
2447 {
2448 cerr << "Program options invalid due to: " << e.what() << " of '" << e.get_option_name() << "'." << endl;
2449 return -1;
2450 }
2451#endif
2452 catch (exception& e)
2453 {
2454 cerr << "Program options invalid due to: " << e.what() << endl;
2455 return -1;
2456 }
2457
2458 if (conf.HasVersion() || conf.HasPrint())
2459 return -1;
2460
2461 if (conf.HasHelp())
2462 {
2463 PrintHelp();
2464 return -1;
2465 }
2466
2467 Dim::Setup(conf.Get<string>("dns"));
2468
2469 //try
2470 {
2471 // No console access at all
2472 if (!conf.Has("console"))
2473 {
2474 if (conf.Get<bool>("no-dim"))
2475 return RunShell<LocalStream, StateMachine, ConnectionFTM>(conf);
2476 else
2477 return RunShell<LocalStream, StateMachineDim, ConnectionDimFTM>(conf);
2478 }
2479 // Cosole access w/ and w/o Dim
2480 if (conf.Get<bool>("no-dim"))
2481 {
2482 if (conf.Get<int>("console")==0)
2483 return RunShell<LocalShell, StateMachine, ConnectionFTM>(conf);
2484 else
2485 return RunShell<LocalConsole, StateMachine, ConnectionFTM>(conf);
2486 }
2487 else
2488 {
2489 if (conf.Get<int>("console")==0)
2490 return RunShell<LocalShell, StateMachineDim, ConnectionDimFTM>(conf);
2491 else
2492 return RunShell<LocalConsole, StateMachineDim, ConnectionDimFTM>(conf);
2493 }
2494 }
2495 /*catch (std::exception& e)
2496 {
2497 cerr << "Exception: " << e.what() << endl;
2498 return -1;
2499 }*/
2500
2501 return 0;
2502}
Note: See TracBrowser for help on using the repository browser.