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

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