source: trunk/FACT++/src/fadctrl.cc@ 16736

Last change on this file since 16736 was 16732, checked in by tbretz, 11 years ago
Make use of the new StateMachineAsio which gets the CPU consumption to basically 0 by a more intelligent event management.
File size: 76.2 KB
Line 
1#include <functional>
2
3#include "Dim.h"
4#include "Event.h"
5#include "Shell.h"
6#include "StateMachineDim.h"
7#include "StateMachineAsio.h"
8#include "Connection.h"
9#include "LocalControl.h"
10#include "Configuration.h"
11#include "Console.h"
12#include "Converter.h"
13#include "HeadersFAD.h"
14
15#include "tools.h"
16
17#include "DimDescriptionService.h"
18#include "EventBuilderWrapper.h"
19
20namespace ba = boost::asio;
21namespace bs = boost::system;
22
23using ba::ip::tcp;
24
25using namespace std;
26
27// ------------------------------------------------------------------------
28
29class ConnectionFAD : public Connection
30{
31 uint16_t fSlot;
32// tcp::endpoint fEndpoint;
33
34 vector<uint16_t> fBuffer;
35
36protected:
37 FAD::EventHeader fEventHeader;
38 FAD::ChannelHeader fChannelHeader[FAD::kNumChannels];
39
40private:
41 bool fIsVerbose;
42 bool fIsHexOutput;
43 bool fIsDataOutput;
44 bool fBlockTransmission;
45
46 uint64_t fCounter;
47
48 FAD::EventHeader fBufEventHeader;
49 vector<uint16_t> fTargetRoi;
50
51protected:
52 void PrintEventHeader()
53 {
54 Out() << endl << kBold << "Header received (N=" << dec << fCounter << "):" << endl;
55 Out() << fEventHeader;
56 if (fIsHexOutput)
57 Out() << Converter::GetHex<uint16_t>(fEventHeader, 16) << endl;
58 }
59
60 void PrintChannelHeaders()
61 {
62 Out() << dec << endl;
63
64 for (unsigned int c=0; c<FAD::kNumChips; c++)
65 {
66 Out() << "ROI|" << fEventHeader.Crate() << ":" << fEventHeader.Board() << ":" << c << ":";
67 for (unsigned int ch=0; ch<FAD::kNumChannelsPerChip; ch++)
68 Out() << " " << setw(4) << fChannelHeader[c+ch*FAD::kNumChips].fRegionOfInterest;
69 Out() << endl;
70 }
71
72 Out() << "CEL|" << fEventHeader.Crate() << ":" <<fEventHeader.Board() << ": ";
73 for (unsigned int c=0; c<FAD::kNumChips; c++)
74 {
75 if (0)//fIsFullChannelHeader)
76 {
77 for (unsigned int ch=0; ch<FAD::kNumChannelsPerChip; ch++)
78 Out() << " " << setw(4) << fChannelHeader[c+ch*FAD::kNumChips].fStartCell;
79 Out() << endl;
80 }
81 else
82 {
83 Out() << " ";
84 const uint16_t cel = fChannelHeader[c*FAD::kNumChannelsPerChip].fStartCell;
85 for (unsigned int ch=1; ch<FAD::kNumChannelsPerChip; ch++)
86 if (cel!=fChannelHeader[c+ch*FAD::kNumChips].fStartCell)
87 {
88 Out() << "!";
89 break;
90 }
91 Out() << cel;
92 }
93 }
94 Out() << endl;
95
96 if (fIsHexOutput)
97 Out() << Converter::GetHex<uint16_t>(fChannelHeader, 16) << endl;
98
99 }
100
101 virtual void UpdateFirstHeader()
102 {
103 }
104
105 virtual void UpdateEventHeader()
106 {
107 // emit service with trigger counter from header
108 if (fIsVerbose)
109 PrintEventHeader();
110 }
111
112 virtual void UpdateChannelHeaders()
113 {
114 // emit service with trigger counter from header
115 if (fIsVerbose)
116 PrintChannelHeaders();
117
118 }
119
120 virtual void UpdateData(const uint16_t *data, size_t sz)
121 {
122 // emit service with trigger counter from header
123 if (fIsVerbose && fIsDataOutput)
124 Out() << Converter::GetHex<uint16_t>(data, sz, 16, true) << endl;
125 }
126
127private:
128 enum
129 {
130 kReadHeader = 1,
131 kReadData = 2,
132 };
133
134 void HandleReceivedData(const bs::error_code& err, size_t bytes_received, int type)
135 {
136 // Do not schedule a new read if the connection failed.
137 if (bytes_received==0 || err)
138 {
139 if (err==ba::error::eof)
140 Warn("Connection to "+URL()+" closed by remote host (FAD).");
141
142 // 107: Transport endpoint is not connected (bs::error_code(107, bs::system_category))
143 // 125: Operation canceled
144 if (err && err!=ba::error::eof && // Connection closed by remote host
145 err!=ba::error::basic_errors::not_connected && // Connection closed by remote host
146 err!=ba::error::basic_errors::operation_aborted) // Connection closed by us
147 {
148 ostringstream str;
149 str << "Reading from " << URL() << ": " << err.message() << " (" << err << ")";// << endl;
150 Error(str);
151 }
152 PostClose(err!=ba::error::basic_errors::operation_aborted);
153 return;
154 }
155
156 if (type==kReadHeader)
157 {
158 if (bytes_received!=sizeof(FAD::EventHeader))
159 {
160 ostringstream str;
161 str << "Bytes received (" << bytes_received << " don't match header size " << sizeof(FAD::EventHeader);
162 Error(str);
163 PostClose(false);
164 return;
165 }
166
167 fEventHeader = fBuffer;
168
169 if (fEventHeader.fStartDelimiter!=FAD::kDelimiterStart)
170 {
171 ostringstream str;
172 str << "Invalid header received: start delimiter wrong, received ";
173 str << hex << fEventHeader.fStartDelimiter << ", expected " << FAD::kDelimiterStart << ".";
174 Error(str);
175 PostClose(false);
176 return;
177 }
178
179 if (fCounter==0)
180 UpdateFirstHeader();
181
182 UpdateEventHeader();
183
184 EventBuilderWrapper::This->debugHead(fEventHeader);
185
186 fBuffer.resize(fEventHeader.fPackageLength-sizeof(FAD::EventHeader)/2);
187 AsyncRead(ba::buffer(fBuffer), kReadData);
188 AsyncWait(fInTimeout, 2000, &Connection::HandleReadTimeout);
189
190 return;
191 }
192
193 fInTimeout.cancel();
194
195 if (ntohs(fBuffer.back())!=FAD::kDelimiterEnd)
196 {
197 ostringstream str;
198 str << "Invalid data received: end delimiter wrong, received ";
199 str << hex << ntohs(fBuffer.back()) << ", expected " << FAD::kDelimiterEnd << ".";
200 Error(str);
201 PostClose(false);
202 return;
203 }
204
205 uint8_t *ptr = reinterpret_cast<uint8_t*>(fBuffer.data());
206 uint8_t *end = ptr + fBuffer.size()*2;
207 for (unsigned int i=0; i<FAD::kNumChannels; i++)
208 {
209 if (ptr+sizeof(FAD::ChannelHeader) > end)
210 {
211 Error("Channel header exceeds buffer size.");
212 PostClose(false);
213 return;
214 }
215
216 fChannelHeader[i] = vector<uint16_t>((uint16_t*)ptr, (uint16_t*)ptr+sizeof(FAD::ChannelHeader)/2);
217 ptr += sizeof(FAD::ChannelHeader);
218
219 //UpdateChannelHeader(i);
220
221 if (ptr+fChannelHeader[i].fRegionOfInterest*2 > end)
222 {
223 Error("Data block exceeds buffer size.");
224 PostClose(false);
225 return;
226 }
227
228 const uint16_t *data = reinterpret_cast<uint16_t*>(ptr);
229 UpdateData(data, fChannelHeader[i].fRegionOfInterest*2);
230 ptr += fChannelHeader[i].fRegionOfInterest*2;
231 }
232
233 if (fIsVerbose)
234 UpdateChannelHeaders();
235
236 fCounter++;
237
238 fBuffer.resize(sizeof(FAD::EventHeader)/2);
239 AsyncRead(ba::buffer(fBuffer), kReadHeader);
240 }
241
242 void HandleReadTimeout(const bs::error_code &error)
243 {
244 if (error==ba::error::basic_errors::operation_aborted)
245 return;
246
247 if (error)
248 {
249 ostringstream str;
250 str << "Read timeout of " << URL() << ": " << error.message() << " (" << error << ")";// << endl;
251 Error(str);
252
253 PostClose();
254 return;
255
256 }
257
258 if (!is_open())
259 {
260 // For example: Here we could schedule a new accept if we
261 // would not want to allow two connections at the same time.
262 return;
263 }
264
265 // Check whether the deadline has passed. We compare the deadline
266 // against the current time since a new asynchronous operation
267 // may have moved the deadline before this actor had a chance
268 // to run.
269 if (fInTimeout.expires_at() > ba::deadline_timer::traits_type::now())
270 return;
271
272 Error("Timeout reading data from "+URL());
273 PostClose();
274 }
275
276 // This is called when a connection was established
277 void ConnectionEstablished()
278 {
279 fBufEventHeader.clear();
280 fBufEventHeader.fEventCounter = 1;
281 fBufEventHeader.fStatus = 0xf000|
282 FAD::EventHeader::kDenable|
283 FAD::EventHeader::kDwrite|
284 FAD::EventHeader::kDcmLocked|
285 FAD::EventHeader::kDcmReady|
286 FAD::EventHeader::kSpiSclk;
287
288 fEventHeader.clear();
289 for (unsigned int i=0; i<FAD::kNumChannels; i++)
290 fChannelHeader[i].clear();
291
292 fCounter = 0;
293
294 fBuffer.resize(sizeof(FAD::EventHeader)/2);
295 AsyncRead(ba::buffer(fBuffer), kReadHeader);
296
297// for (int i=0; i<36; i++)
298// CmdSetRoi(i, 100);
299
300// Cmd(FAD::kCmdTriggerLine, true);
301// Cmd(FAD::kCmdSingleTrigger);
302 }
303
304public:
305 void PostCmd(std::vector<uint16_t> cmd)
306 {
307 if (fBlockTransmission || !IsConnected())
308 return;
309
310#ifdef DEBUG_TX
311 ostringstream msg;
312 msg << "Sending command:" << hex;
313 msg << " 0x" << setw(4) << setfill('0') << cmd[0];
314 msg << " (+ " << cmd.size()-1 << " bytes data)";
315 Message(msg);
316#endif
317 transform(cmd.begin(), cmd.end(), cmd.begin(), htons);
318
319 PostMessage(cmd);
320 }
321
322 void PostCmd(uint16_t cmd)
323 {
324 if (fBlockTransmission || !IsConnected())
325 return;
326
327#ifdef DEBUG_TX
328 ostringstream msg;
329 msg << "Sending command:" << hex;
330 msg << " 0x" << setw(4) << setfill('0') << cmd;
331 Message(msg);
332#endif
333 cmd = htons(cmd);
334 PostMessage(&cmd, sizeof(uint16_t));
335 }
336
337 void PostCmd(uint16_t cmd, uint16_t data)
338 {
339 if (fBlockTransmission || !IsConnected())
340 return;
341
342#ifdef DEBUG_TX
343 ostringstream msg;
344 msg << "Sending command:" << hex;
345 msg << " 0x" << setw(4) << setfill('0') << cmd;
346 msg << " 0x" << setw(4) << setfill('0') << data;
347 Message(msg);
348#endif
349 const uint16_t d[2] = { htons(cmd), htons(data) };
350 PostMessage(d, sizeof(d));
351 }
352
353public:
354 ConnectionFAD(ba::io_service& ioservice, MessageImp &imp, uint16_t slot) :
355 Connection(ioservice, imp()), fSlot(slot),
356 fIsVerbose(false), fIsHexOutput(false), fIsDataOutput(false),
357 fBlockTransmission(false), fCounter(0),
358 fTargetRoi(FAD::kNumChannels)
359 {
360 // Maximum possible needed space:
361 // The full header, all channels with all DRS bins
362 // Two trailing shorts
363 fBuffer.reserve(sizeof(FAD::EventHeader) + FAD::kNumChannels*(sizeof(FAD::ChannelHeader) + FAD::kMaxBins*sizeof(uint16_t)) + 2*sizeof(uint16_t));
364
365 SetLogStream(&imp);
366 }
367
368 void Cmd(FAD::Enable cmd, bool on=true)
369 {
370 switch (cmd)
371 {
372 case FAD::kCmdDrsEnable: fBufEventHeader.Enable(FAD::EventHeader::kDenable, on); break;
373 case FAD::kCmdDwrite: fBufEventHeader.Enable(FAD::EventHeader::kDwrite, on); break;
374 case FAD::kCmdTriggerLine: fBufEventHeader.Enable(FAD::EventHeader::kTriggerLine, on); break;
375 case FAD::kCmdBusyOn: fBufEventHeader.Enable(FAD::EventHeader::kBusyOn, on); break;
376 case FAD::kCmdBusyOff: fBufEventHeader.Enable(FAD::EventHeader::kBusyOff, on); break;
377 case FAD::kCmdContTrigger: fBufEventHeader.Enable(FAD::EventHeader::kContTrigger, on); break;
378 case FAD::kCmdSocket: fBufEventHeader.Enable(FAD::EventHeader::kSock17, !on); break;
379 default:
380 break;
381 }
382
383 PostCmd(cmd + (on ? 0 : 0x100));
384 }
385
386 // ------------------------------
387
388 // IMPLEMENT: Abs/Rel
389 void CmdPhaseShift(int16_t val)
390 {
391 vector<uint16_t> cmd(abs(val)+2, FAD::kCmdPhaseApply);
392 cmd[0] = FAD::kCmdPhaseReset;
393 cmd[1] = val<0 ? FAD::kCmdPhaseDecrease : FAD::kCmdPhaseIncrease;
394 PostCmd(cmd);
395 }
396
397 bool CmdSetTriggerRate(int32_t val)
398 {
399 if (val<0 || val>0xffff)
400 return false;
401
402 fBufEventHeader.fTriggerGeneratorPrescaler = val;
403 PostCmd(FAD::kCmdWriteRate, val);//uint8_t(1000./val/12.5));
404 //PostCmd(FAD::kCmdWriteExecute);
405
406 return true;
407 }
408
409 void CmdSetRunNumber(uint32_t num)
410 {
411 fBufEventHeader.fRunNumber = num;
412
413 PostCmd(FAD::kCmdWriteRunNumberLSW, num&0xffff);
414 PostCmd(FAD::kCmdWriteRunNumberMSW, num>>16);
415 PostCmd(FAD::kCmdWriteExecute);
416 }
417
418 void CmdSetRegister(uint8_t addr, uint16_t val)
419 {
420 // Allowed addr: [0, MAX_ADDR]
421 // Allowed value: [0, MAX_VAL]
422 PostCmd(FAD::kCmdWrite + addr, val);
423 PostCmd(FAD::kCmdWriteExecute);
424 }
425
426 bool CmdSetDacValue(int8_t addr, uint16_t val)
427 {
428 if (addr<0)
429 {
430 for (unsigned int i=0; i<=FAD::kMaxDacAddr; i++)
431 {
432 fBufEventHeader.fDac[i] = val;
433 PostCmd(FAD::kCmdWriteDac + i, val);
434 }
435 PostCmd(FAD::kCmdWriteExecute);
436 return true;
437 }
438
439 if (uint8_t(addr)>FAD::kMaxDacAddr) // NDAC
440 return false;
441
442 fBufEventHeader.fDac[addr] = val;
443
444 PostCmd(FAD::kCmdWriteDac + addr, val);
445 PostCmd(FAD::kCmdWriteExecute);
446 return true;
447 }
448
449 bool CmdSetRoi(int8_t addr, uint16_t val)
450 {
451 if (val>FAD::kMaxRoiValue)
452 return false;
453
454 if (addr<0)
455 {
456 for (unsigned int i=0; i<=FAD::kMaxRoiAddr; i++)
457 {
458 fTargetRoi[i] = val;
459 PostCmd(FAD::kCmdWriteRoi + i, val);
460 }
461 PostCmd(FAD::kCmdWriteExecute);
462 return true;
463 }
464
465 if (uint8_t(addr)>FAD::kMaxRoiAddr)
466 return false;
467
468 fTargetRoi[addr] = val;
469
470 PostCmd(FAD::kCmdWriteRoi + addr, val);
471 PostCmd(FAD::kCmdWriteExecute);
472 return true;
473 }
474
475 bool CmdSetRoi(uint16_t val) { return CmdSetRoi(-1, val); }
476
477 void SetVerbose(bool b)
478 {
479 fIsVerbose = b;
480 }
481
482 void SetHexOutput(bool b)
483 {
484 fIsHexOutput = b;
485 }
486
487 void SetDataOutput(bool b)
488 {
489 fIsDataOutput = b;
490 }
491
492 void SetBlockTransmission(bool b)
493 {
494 fBlockTransmission = b;
495 }
496
497 bool IsTransmissionBlocked() const
498 {
499 return fBlockTransmission;
500 }
501
502 void PrintEvent()
503 {
504 if (fCounter>0)
505 {
506 PrintEventHeader();
507 PrintChannelHeaders();
508 }
509 else
510 Out() << "No event received yet." << endl;
511 }
512
513 bool HasCorrectRoi() const
514 {
515 for (int i=0; i<FAD::kNumChannels; i++)
516 if (fTargetRoi[i]!=fChannelHeader[i].fRegionOfInterest)
517 return false;
518
519 return true;
520 }
521
522 bool HasCorrectHeader() const
523 {
524 return fEventHeader==fBufEventHeader;
525 }
526
527 bool IsConfigured() const
528 {
529 return HasCorrectRoi() && HasCorrectHeader();
530 }
531
532 void PrintCheckHeader()
533 {
534 Out() << "================================================================================" << endl;
535 fEventHeader.print(Out());
536 Out() << "--------------------------------------------------------------------------------" << endl;
537 fBufEventHeader.print(Out());
538 Out() << "================================================================================" << endl;
539 }
540
541 const FAD::EventHeader &GetConfiguration() const { return fBufEventHeader; }
542};
543
544// ------------------------------------------------------------------------
545
546template <class T>
547class StateMachineFAD : public StateMachineAsio<T>, public EventBuilderWrapper
548{
549private:
550 typedef map<uint8_t, ConnectionFAD*> BoardList;
551
552 BoardList fBoards;
553
554 bool fIsVerbose;
555 bool fIsHexOutput;
556 bool fIsDataOutput;
557 bool fDebugTx;
558
559 bool CheckEventSize(size_t has, const char *name, size_t size)
560 {
561 if (has==size)
562 return true;
563
564 ostringstream msg;
565 msg << name << " - Received event has " << has << " bytes, but expected " << size << ".";
566 T::Fatal(msg);
567 return false;
568 }
569
570 int Cmd(FAD::Enable command)
571 {
572 for (BoardList::iterator i=fBoards.begin(); i!=fBoards.end(); i++)
573 i->second->Cmd(command);
574
575 return T::GetCurrentState();
576 }
577
578 int SendCmd(const EventImp &evt)
579 {
580 if (!CheckEventSize(evt.GetSize(), "SendCmd", 4))
581 return T::kSM_FatalError;
582
583 if (evt.GetUInt()>0xffff)
584 {
585 T::Warn("Command value out of range (0-65535).");
586 return T::GetCurrentState();
587 }
588
589 for (BoardList::iterator i=fBoards.begin(); i!=fBoards.end(); i++)
590 i->second->PostCmd(evt.GetUInt());
591
592 return T::GetCurrentState();
593 }
594
595 int SendCmdData(const EventImp &evt)
596 {
597 if (!CheckEventSize(evt.GetSize(), "SendCmdData", 8))
598 return T::kSM_FatalError;
599
600 const uint32_t *ptr = evt.Ptr<uint32_t>();
601
602 if (ptr[0]>0xffff)
603 {
604 T::Warn("Command value out of range (0-65535).");
605 return T::GetCurrentState();
606 }
607
608 if (ptr[1]>0xffff)
609 {
610 T::Warn("Data value out of range (0-65535).");
611 return T::GetCurrentState();
612 }
613
614 for (BoardList::iterator i=fBoards.begin(); i!=fBoards.end(); i++)
615 i->second->PostCmd(ptr[0], ptr[1]);
616
617 return T::GetCurrentState();
618 }
619
620 int CmdEnable(const EventImp &evt, FAD::Enable command)
621 {
622 if (!CheckEventSize(evt.GetSize(), "CmdEnable", 1))
623 return T::kSM_FatalError;
624
625 for (BoardList::iterator i=fBoards.begin(); i!=fBoards.end(); i++)
626 i->second->Cmd(command, evt.GetBool());
627
628 return T::GetCurrentState();
629 }
630
631 bool Check(const uint32_t *dat, uint32_t maxaddr, uint32_t maxval)
632 {
633 if (dat[0]>maxaddr)
634 {
635 ostringstream msg;
636 msg << hex << "Address " << dat[0] << " out of range, max=" << maxaddr << ".";
637 T::Error(msg);
638 return false;
639 }
640
641 if (dat[1]>maxval)
642 {
643 ostringstream msg;
644 msg << hex << "Value " << dat[1] << " out of range, max=" << maxval << ".";
645 T::Error(msg);
646 return false;
647 }
648
649 return true;
650 }
651
652 int SetRegister(const EventImp &evt)
653 {
654 if (!CheckEventSize(evt.GetSize(), "SetRegister", 8))
655 return T::kSM_FatalError;
656
657 const uint32_t *dat = evt.Ptr<uint32_t>();
658
659 if (!Check(dat, FAD::kMaxRegAddr, FAD::kMaxRegValue))
660 return T::GetCurrentState();
661
662 for (BoardList::iterator i=fBoards.begin(); i!=fBoards.end(); i++)
663 i->second->CmdSetRegister(dat[0], dat[1]);
664
665 return T::GetCurrentState();
666 }
667
668 int SetRoi(const EventImp &evt)
669 {
670 if (!CheckEventSize(evt.GetSize(), "SetRoi", 8))
671 return T::kSM_FatalError;
672
673 const int32_t *dat = evt.Ptr<int32_t>();
674
675 for (BoardList::iterator i=fBoards.begin(); i!=fBoards.end(); i++)
676 if (!i->second->CmdSetRoi(dat[0], dat[1]))
677 {
678 ostringstream msg;
679 msg << hex << "Channel " << dat[0] << " or Value " << dat[1] << " out of range.";
680 T::Error(msg);
681 return T::GetCurrentState();
682 }
683
684
685 return T::GetCurrentState();
686 }
687
688 int SetDac(const EventImp &evt)
689 {
690 if (!CheckEventSize(evt.GetSize(), "SetDac", 8))
691 return T::kSM_FatalError;
692
693 const int32_t *dat = evt.Ptr<int32_t>();
694
695 for (BoardList::iterator i=fBoards.begin(); i!=fBoards.end(); i++)
696 if (!i->second->CmdSetDacValue(dat[0], dat[1]))
697 {
698 ostringstream msg;
699 msg << hex << "Channel " << dat[0] << " or Value " << dat[1] << " out of range.";
700 T::Error(msg);
701 return T::GetCurrentState();
702 }
703
704 return T::GetCurrentState();
705 }
706
707 int Trigger(int n)
708 {
709 for (int nn=0; nn<n; nn++)
710 for (BoardList::iterator i=fBoards.begin(); i!=fBoards.end(); i++)
711 i->second->Cmd(FAD::kCmdSingleTrigger);
712
713 return T::GetCurrentState();
714 }
715
716 int SendTriggers(const EventImp &evt)
717 {
718 if (!CheckEventSize(evt.GetSize(), "SendTriggers", 4))
719 return T::kSM_FatalError;
720
721 Trigger(evt.GetUInt());
722
723 return T::GetCurrentState();
724 }
725/*
726 int StartRun(const EventImp &evt, bool start)
727 {
728 if (!CheckEventSize(evt.GetSize(), "StartRun", 0))
729 return T::kSM_FatalError;
730
731 for (BoardList::iterator i=fBoards.begin(); i!=fBoards.end(); i++)
732 i->second->Cmd(FAD::kCmdRun, start);
733
734 return T::GetCurrentState();
735 }
736*/
737 int PhaseShift(const EventImp &evt)
738 {
739 if (!CheckEventSize(evt.GetSize(), "PhaseShift", 2))
740 return T::kSM_FatalError;
741
742 for (BoardList::iterator i=fBoards.begin(); i!=fBoards.end(); i++)
743 i->second->CmdPhaseShift(evt.GetShort());
744
745 return T::GetCurrentState();
746 }
747
748 int SetTriggerRate(const EventImp &evt)
749 {
750 if (!CheckEventSize(evt.GetSize(), "SetTriggerRate", 4))
751 return T::kSM_FatalError;
752
753 if (evt.GetUInt()>0xffff)
754 {
755 ostringstream msg;
756 msg << hex << "Value " << evt.GetUShort() << " out of range, max=" << 0xffff << "(?)";
757 T::Error(msg);
758 return T::GetCurrentState();
759 }
760
761 for (BoardList::iterator i=fBoards.begin(); i!=fBoards.end(); i++)
762 i->second->CmdSetTriggerRate(evt.GetUInt());
763
764 return T::GetCurrentState();
765 }
766
767 int SetRunNumber(const EventImp &evt)
768 {
769 if (!CheckEventSize(evt.GetSize(), "SetRunNumber", 8))
770 return T::kSM_FatalError;
771
772 const uint64_t num = evt.GetUXtra();
773
774 if (num<=0 || num>FAD::kMaxRunNumber)
775 {
776 ostringstream msg;
777 msg << "Run number " << num << " out of range [1;" << FAD::kMaxRunNumber << "]";
778 T::Error(msg);
779 return T::GetCurrentState();
780 }
781
782 if (!IncreaseRunNumber(num))
783 return T::GetCurrentState();
784
785 for (BoardList::iterator i=fBoards.begin(); i!=fBoards.end(); i++)
786 i->second->CmdSetRunNumber(GetRunNumber());
787
788 return T::GetCurrentState();
789 }
790
791 int SetMaxMemoryBuffer(const EventImp &evt)
792 {
793 if (!CheckEventSize(evt.GetSize(), "SetMaxMemoryBuffer", 2))
794 return T::kSM_FatalError;
795
796 const int16_t mem = evt.GetShort();
797
798 if (mem<=0)
799 {
800 ostringstream msg;
801 msg << hex << "Value " << mem << " out of range.";
802 T::Error(msg);
803 return T::GetCurrentState();
804 }
805
806 SetMaxMemory(mem);
807
808 return T::GetCurrentState();
809 }
810
811 int SetEventTimeoutSec(const EventImp &evt)
812 {
813 if (!CheckEventSize(evt.GetSize(), "SetEventTimeoutSec", 2))
814 return T::kSM_FatalError;
815
816 const int16_t sec = evt.GetShort();
817
818 if (sec<=0)
819 {
820 ostringstream msg;
821 msg << hex << "Value " << sec << " out of range.";
822 T::Error(msg);
823 return T::GetCurrentState();
824 }
825
826 SetEventTimeout(sec);
827
828 return T::GetCurrentState();
829 }
830
831 int SetFileFormat(const EventImp &evt)
832 {
833 if (!CheckEventSize(evt.GetSize(), "SetFileFormat", 2))
834 return T::kSM_FatalError;
835
836 const uint16_t fmt = evt.GetUShort();
837
838 // A simple way to make sure that no invalid file format
839 // is passed to the event builder
840 switch (fmt)
841 {
842 case FAD::kNone:
843 case FAD::kDebug:
844 case FAD::kFits:
845 case FAD::kCfitsio:
846 case FAD::kRaw:
847 case FAD::kCalib:
848 SetOutputFormat(FAD::FileFormat_t(fmt));
849 break;
850 default:
851 T::Error("File format unknonw.");
852 return T::GetCurrentState();
853 }
854
855 return T::GetCurrentState();
856 }
857
858 int StartDrsCalibration()
859 {
860 SetOutputFormat(FAD::kCalib);
861 return T::GetCurrentState();
862 }
863
864 int ResetSecondaryDrsBaseline()
865 {
866 EventBuilderWrapper::ResetSecondaryDrsBaseline();
867 return T::GetCurrentState();
868 }
869
870 int LoadDrsCalibration(const EventImp &evt)
871 {
872 EventBuilderWrapper::LoadDrsCalibration(evt.GetText());
873 return T::GetCurrentState();
874 }
875/*
876 int Test(const EventImp &evt)
877 {
878 if (!CheckEventSize(evt.GetSize(), "Test", 2))
879 return T::kSM_FatalError;
880
881
882 SetMode(evt.GetShort());
883
884 return T::GetCurrentState();
885 }*/
886
887
888 int SetVerbosity(const EventImp &evt)
889 {
890 if (!CheckEventSize(evt.GetSize(), "SetVerbosity", 1))
891 return T::kSM_FatalError;
892
893 for (BoardList::iterator i=fBoards.begin(); i!=fBoards.end(); i++)
894 i->second->SetVerbose(evt.GetBool());
895
896 return T::GetCurrentState();
897 }
898
899 int SetHexOutput(const EventImp &evt)
900 {
901 if (!CheckEventSize(evt.GetSize(), "SetHexOutput", 1))
902 return T::kSM_FatalError;
903
904 for (BoardList::iterator i=fBoards.begin(); i!=fBoards.end(); i++)
905 i->second->SetHexOutput(evt.GetBool());
906
907 return T::GetCurrentState();
908 }
909
910 int SetDataOutput(const EventImp &evt)
911 {
912 if (!CheckEventSize(evt.GetSize(), "SetDataOutput", 1))
913 return T::kSM_FatalError;
914
915 for (BoardList::iterator i=fBoards.begin(); i!=fBoards.end(); i++)
916 i->second->SetDataOutput(evt.GetBool());
917
918 return T::GetCurrentState();
919 }
920
921 int SetDebugTx(const EventImp &evt)
922 {
923 if (!CheckEventSize(evt.GetSize(), "SetDebugTx", 1))
924 return T::kSM_FatalError;
925
926 for (BoardList::iterator i=fBoards.begin(); i!=fBoards.end(); i++)
927 i->second->SetDebugTx(evt.GetBool());
928
929 return T::GetCurrentState();
930 }
931
932 const BoardList::iterator GetSlot(uint16_t slot)
933 {
934 const BoardList::iterator it=fBoards.find(slot);
935 if (it==fBoards.end())
936 {
937 ostringstream str;
938 str << "Slot " << slot << " not found.";
939 T::Warn(str);
940 }
941
942 return it;
943 }
944
945 int PrintEvent(const EventImp &evt)
946 {
947 if (!CheckEventSize(evt.GetSize(), "PrintEvent", 2))
948 return T::kSM_FatalError;
949
950 const int16_t slot = evt.Get<int16_t>();
951
952 if (slot<0)
953 {
954 for (BoardList::iterator i=fBoards.begin(); i!=fBoards.end(); i++)
955 i->second->PrintEvent();
956 }
957 else
958 {
959 const BoardList::iterator it=GetSlot(slot);
960 if (it!=fBoards.end())
961 it->second->PrintEvent();
962 }
963
964 return T::GetCurrentState();
965 }
966
967 int SetBlockTransmission(const EventImp &evt)
968 {
969 if (!CheckEventSize(evt.GetSize(), "SetBlockTransmission", 3))
970 return T::kSM_FatalError;
971
972 const int16_t slot = evt.Get<int32_t>();
973
974 const BoardList::iterator it=GetSlot(slot);
975 if (it!=fBoards.end())
976 it->second->SetBlockTransmission(evt.Get<uint8_t>(2));
977
978 return T::GetCurrentState();
979 }
980
981 int SetBlockTransmissionRange(const EventImp &evt)
982 {
983 if (!CheckEventSize(evt.GetSize(), "SetBlockTransmissionRange", 5))
984 return T::kSM_FatalError;
985
986 const int16_t *slot = evt.Ptr<int16_t>();
987 const bool block = evt.Get<uint8_t>(4);
988
989 for (int i=slot[0]; i<=slot[1]; i++)
990 {
991 const BoardList::iterator it=GetSlot(i);
992 if (it!=fBoards.end())
993 it->second->SetBlockTransmission(block);
994 }
995
996 return T::GetCurrentState();
997 }
998
999 int SetIgnoreSlot(const EventImp &evt)
1000 {
1001 if (!CheckEventSize(evt.GetSize(), "SetIgnoreSlot", 3))
1002 return T::kSM_FatalError;
1003
1004 const uint16_t slot = evt.Get<uint16_t>();
1005
1006 if (slot>39)
1007 {
1008 T::Warn("Slot out of range (0-39).");
1009 return T::GetCurrentState();
1010 }
1011
1012 SetIgnore(slot, evt.Get<uint8_t>(2));
1013
1014 return T::GetCurrentState();
1015 }
1016
1017 int SetIgnoreSlots(const EventImp &evt)
1018 {
1019 if (!CheckEventSize(evt.GetSize(), "SetIgnoreSlots", 5))
1020 return T::kSM_FatalError;
1021
1022 const int16_t *slot = evt.Ptr<int16_t>();
1023 const bool block = evt.Get<uint8_t>(4);
1024
1025 if (slot[0]<0 || slot[1]>39 || slot[0]>slot[1])
1026 {
1027 T::Warn("Slot out of range.");
1028 return T::GetCurrentState();
1029 }
1030
1031 for (int i=slot[0]; i<=slot[1]; i++)
1032 SetIgnore(i, block);
1033
1034 return T::GetCurrentState();
1035 }
1036
1037 int StartConfigure(const EventImp &evt)
1038 {
1039 const string name = evt.Ptr<char>(16);
1040
1041 fTargetConfig = fConfigs.find(name);
1042 if (fTargetConfig==fConfigs.end())
1043 {
1044 T::Error("StartConfigure - Run-type '"+name+"' not found.");
1045 return T::GetCurrentState();
1046 }
1047
1048 // FIXME: What about an error state?
1049 const uint32_t runno = StartNewRun(evt.Get<int64_t>(), evt.Get<int64_t>(8), *fTargetConfig);
1050 if (runno==0)
1051 return FAD::State::kConnected;
1052
1053 ostringstream str;
1054 str << "Starting configuration for run " << runno << " (" << name << ")";
1055 T::Message(str.str());
1056
1057 if (runno>=1000)
1058 T::Warn("Run number exceeds logical maximum of 999 - this is no problem for writing but might give raise to problems in the analysis.");
1059
1060 const FAD::Configuration &conf = fTargetConfig->second;
1061
1062 for (BoardList::iterator it=fBoards.begin(); it!=fBoards.end(); it++)
1063 {
1064 ConnectionFAD &fad = *it->second;
1065
1066 fad.Cmd(FAD::kCmdBusyOn, true); // continously on
1067 fad.Cmd(FAD::kCmdTriggerLine, false);
1068 fad.Cmd(FAD::kCmdContTrigger, false);
1069 fad.Cmd(FAD::kCmdSocket, true);
1070 fad.Cmd(FAD::kCmdBusyOff, false); // normal when BusyOn==0
1071
1072 fad.Cmd(FAD::kCmdDwrite, conf.fDwrite);
1073 fad.Cmd(FAD::kCmdDrsEnable, conf.fDenable);
1074
1075 for (int i=0; i<FAD::kNumDac; i++)
1076 fad.CmdSetDacValue(i, conf.fDac[i]);
1077
1078 for (int i=0; i<FAD::kNumChips; i++)
1079 for (int j=0; j<FAD::kNumChannelsPerChip; j++)
1080 fad.CmdSetRoi(i*FAD::kNumChannelsPerChip+j, conf.fRoi[j]);
1081
1082 fad.CmdSetTriggerRate(conf.fTriggerRate);
1083 fad.CmdSetRunNumber(runno);
1084 fad.Cmd(FAD::kCmdResetEventCounter);
1085 fad.Cmd(FAD::kCmdTriggerLine, true);
1086 //fad.Cmd(FAD::kCmdSingleTrigger);
1087 //fad.Cmd(FAD::kCmdTriggerLine, true);
1088 }
1089
1090 fConfigTimer = Time(Time::none);
1091
1092 // Now the old run is stopped already. So all other servers can start a new run
1093 // (Note that we might need another step which only checks if the continous trigger
1094 // is wwitched off, too)
1095 const int64_t runs[2] = { runno, runno+1 };
1096 fDimStartRun.Update(runs);
1097
1098 // T::Info(" ==> TODO: Insert/update run configuration in database!");
1099
1100 return FAD::State::kConfiguring1;
1101 }
1102
1103 int ResetConfig()
1104 {
1105 const int64_t runs[2] = { -1, GetRunNumber() };
1106 fDimStartRun.Update(runs);
1107
1108 return FAD::State::kConnected;
1109 }
1110
1111 void CloseRun(uint32_t runid)
1112 {
1113 if (runid==GetRunNumber()-1)
1114 ResetConfig();
1115 }
1116
1117 int AddAddress(const EventImp &evt)
1118 {
1119 const string addr = Tools::Trim(evt.GetText());
1120
1121 const tcp::endpoint endpoint = GetEndpoint(addr);
1122 if (endpoint==tcp::endpoint())
1123 return T::GetCurrentState();
1124
1125 for (BoardList::const_iterator i=fBoards.begin(); i!=fBoards.end(); i++)
1126 {
1127 if (i->second->GetEndpoint()==endpoint)
1128 {
1129 T::Warn("Address "+addr+" already known.... ignored.");
1130 return T::GetCurrentState();
1131 }
1132 }
1133
1134 AddEndpoint(endpoint);
1135
1136 return T::GetCurrentState();
1137 }
1138
1139 int RemoveSlot(const EventImp &evt)
1140 {
1141 if (!CheckEventSize(evt.GetSize(), "RemoveSlot", 2))
1142 return T::kSM_FatalError;
1143
1144 const int16_t slot = evt.GetShort();
1145
1146 const BoardList::iterator it = GetSlot(slot);
1147
1148 if (it==fBoards.end())
1149 return T::GetCurrentState();
1150
1151 ConnectSlot(slot, tcp::endpoint());
1152
1153 delete it->second;
1154 fBoards.erase(it);
1155
1156 return T::GetCurrentState();
1157 }
1158
1159 int ListSlots()
1160 {
1161 for (BoardList::iterator i=fBoards.begin(); i!=fBoards.end(); i++)
1162 {
1163 const int &idx = i->first;
1164 const ConnectionFAD *fad = i->second;
1165
1166 ostringstream str;
1167 str << "Slot " << setw(2) << idx << ": " << fad->GetEndpoint();
1168
1169 if (fad->IsConnecting())
1170 str << " (0:connecting, ";
1171 else
1172 {
1173 if (fad->IsClosed())
1174 str << " (0:disconnected, ";
1175 if (fad->IsConnected())
1176 str << " (0:connected, ";
1177 }
1178
1179 switch (fStatus2[idx])
1180 {
1181 case 0: str << "1:disconnected)"; break;
1182 case 8: str << "1:connected)"; break;
1183 default: str << "1:connecting)"; break;
1184 }
1185
1186 if (fad->IsTransmissionBlocked())
1187 str << " [cmd_blocked]";
1188
1189 if (fStatus2[idx]==8 && IsIgnored(idx))
1190 str << " [data_ignored]";
1191
1192 if (fad->IsConnected() && fStatus2[idx]==8 && fad->IsConfigured())
1193 str << " [configured]";
1194
1195 T::Out() << str.str() << endl;
1196 }
1197
1198 T::Out() << "Event builder thread:";
1199 if (!IsThreadRunning())
1200 T::Out() << " not";
1201 T::Out() << " running" << endl;
1202
1203 // FIXME: Output state
1204
1205 return T::GetCurrentState();
1206 }
1207
1208 void EnableConnection(ConnectionFAD *ptr, bool enable=true)
1209 {
1210 if (!enable)
1211 {
1212 ptr->PostClose(false);
1213 return;
1214 }
1215
1216 if (!ptr->IsDisconnected())
1217 {
1218 ostringstream str;
1219 str << ptr->GetEndpoint();
1220
1221 T::Warn("Connection to "+str.str()+" already in progress.");
1222 return;
1223 }
1224
1225 ptr->StartConnect();
1226 }
1227
1228 void EnableAll(bool enable=true)
1229 {
1230 for (BoardList::iterator i=fBoards.begin(); i!=fBoards.end(); i++)
1231 EnableConnection(i->second, enable);
1232 }
1233
1234 int CloseOpenFiles()
1235 {
1236 EventBuilderWrapper::CloseOpenFiles();
1237 return T::GetCurrentState();
1238 }
1239
1240 int EnableSlot(const EventImp &evt, bool enable)
1241 {
1242 if (!CheckEventSize(evt.GetSize(), "EnableSlot", 2))
1243 return T::kSM_FatalError;
1244
1245 const int16_t slot = evt.GetShort();
1246
1247 const BoardList::iterator it = GetSlot(slot);
1248 if (it==fBoards.end())
1249 return T::GetCurrentState();
1250
1251 EnableConnection(it->second, enable);
1252 ConnectSlot(it->first, enable ? it->second->GetEndpoint() : tcp::endpoint());
1253
1254 return T::GetCurrentState();
1255 }
1256
1257 int ToggleSlot(const EventImp &evt)
1258 {
1259 if (!CheckEventSize(evt.GetSize(), "ToggleSlot", 2))
1260 return T::kSM_FatalError;
1261
1262 const int16_t slot = evt.GetShort();
1263
1264 const BoardList::iterator it = GetSlot(slot);
1265 if (it==fBoards.end())
1266 return T::GetCurrentState();
1267
1268 const bool enable = it->second->IsDisconnected();
1269
1270 EnableConnection(it->second, enable);
1271 ConnectSlot(it->first, enable ? it->second->GetEndpoint() : tcp::endpoint());
1272
1273 return T::GetCurrentState();
1274 }
1275
1276 int StartConnection()
1277 {
1278 vector<tcp::endpoint> addr(40);
1279
1280 for (BoardList::iterator i=fBoards.begin(); i!=fBoards.end(); i++)
1281 addr[i->first] = i->second->GetEndpoint();
1282
1283 StartThread(addr);
1284 EnableAll(true);
1285
1286 return T::GetCurrentState();
1287 }
1288
1289 int StopConnection()
1290 {
1291 Exit();
1292 EnableAll(false);
1293 return T::GetCurrentState();
1294 }
1295
1296 int AbortConnection()
1297 {
1298 Abort();
1299 EnableAll(false);
1300 return T::GetCurrentState();
1301 }
1302
1303 int Reset(bool soft)
1304 {
1305 ResetThread(soft);
1306 return T::GetCurrentState();
1307 }
1308
1309 // ============================================================================
1310/*
1311 bool ProcessReconnection(const list<ReconnectionSlot>::iterator &it)
1312 {
1313 auto board = GetSlot(it->slot);
1314 if (board==fBoards.end())
1315 return false;
1316
1317 ConnectionFAD *fad = board->second;
1318
1319 // ----------------------------------------------
1320 // Disconnect
1321 // ----------------------------------------------
1322 if (it->state==0)
1323 {
1324 if (!fad->IsConnected())
1325 return false;
1326
1327 EnableConnection(fad, false);
1328 ConnectSlot(it->slot, tcp::endpoint());
1329
1330 it->time = Time();
1331 it->state = 1;
1332
1333 return true;
1334 }
1335
1336 // ----------------------------------------------
1337 // Wait for disconnect or timeout
1338 // ----------------------------------------------
1339 if (it->state==1)
1340 {
1341 if (!fad->IsDisconnected() && it->time+boost::posix_time::seconds(10)>Time())
1342 return true;
1343
1344 it->time = Time();
1345 it->state = 2;
1346
1347 return true;
1348 }
1349
1350 // ----------------------------------------------
1351 // Wait for timeout after disconnect / Re-connect
1352 // ----------------------------------------------
1353 if (it->state==2)
1354 {
1355 if (it->time+boost::posix_time::seconds(3)>Time())
1356 return true;
1357
1358 EnableConnection(fad, true);
1359 ConnectSlot(it->slot, fad->GetEndpoint());
1360
1361 it->time = Time();
1362 it->state = 3;
1363
1364 return true;
1365 }
1366
1367 // ----------------------------------------------
1368 // Wait for connect or timeout / Re-start
1369 // ----------------------------------------------
1370 if (!fad->IsConnected() && it->time+boost::posix_time::seconds(10)>Time())
1371 return true;
1372
1373 // 'Fix' the information which got lost during re-connection
1374 fad->Cmd(FAD::kCmdBusyOff, false);
1375 fad->Cmd(FAD::kCmdSocket, false);
1376 fad->Cmd(FAD::kCmdTriggerLine, true);
1377
1378 return false;
1379 }
1380*/
1381 // ============================================================================
1382
1383 vector<uint8_t> fStatus1;
1384 vector<uint8_t> fStatus2;
1385 bool fStatusT;
1386
1387 int Execute()
1388 {
1389 // ===== Evaluate connection status =====
1390
1391 uint16_t nclosed1 = 0;
1392 uint16_t nconnecting1 = 0;
1393 uint16_t nconnecting2 = 0;
1394 uint16_t nconnected1 = 0;
1395 uint16_t nconnected2 = 0;
1396 uint16_t nconfigured = 0;
1397
1398 vector<uint8_t> stat1(40);
1399 vector<uint8_t> stat2(40);
1400
1401 int cnt = 0; // counter for enabled board
1402
1403 const bool runs = IsThreadRunning();
1404
1405 for (int idx=0; idx<40; idx++)
1406 {
1407 // ----- Command socket -----
1408 const BoardList::const_iterator &slot = fBoards.find(idx);
1409 if (slot!=fBoards.end())
1410 {
1411 const ConnectionFAD *c = slot->second;
1412 if (c->IsDisconnected())
1413 {
1414 stat1[idx] = 0;
1415 nclosed1++;
1416
1417 //DisconnectSlot(idx);
1418 }
1419 if (c->IsConnecting())
1420 {
1421 stat1[idx] = 1;
1422 nconnecting1++;
1423 }
1424 if (c->IsConnected())
1425 {
1426 stat1[idx] = 2;
1427 nconnected1++;
1428
1429 if (c->IsConfigured())
1430 {
1431 stat1[idx] = 3;
1432 nconfigured++;
1433 }
1434 }
1435
1436 cnt++;
1437 }
1438
1439 // ----- Event builder -----
1440
1441 stat2[idx] = 0; // disconnected
1442 if (!runs)
1443 continue;
1444
1445 if (IsConnecting(idx))
1446 {
1447 nconnecting2++;
1448 stat2[idx] = 1; // connecting
1449 }
1450
1451 if (IsConnected(idx))
1452 {
1453 nconnected2++;
1454 stat2[idx] = 8; // connected
1455 }
1456 }
1457
1458 // ===== Send connection status via dim =====
1459
1460 if (fStatus1!=stat1 || fStatus2!=stat2 || fStatusT!=runs)
1461 {
1462 fStatus1 = stat1;
1463 fStatus2 = stat2;
1464 fStatusT = runs;
1465 UpdateConnectionStatus(stat1, stat2, runs);
1466 }
1467
1468 // ===== Return connection status =====
1469
1470 // Keep the state during reconnection (theoretically, can only be WritingData)
1471/* if (fReconnectionList.size()>0)
1472 {
1473 bool isnew = true;
1474 for (auto it=fReconnectionList.begin(); it!=fReconnectionList.end(); it++)
1475 if (it->state>0)
1476 {
1477 isnew = false;
1478 break;
1479 }
1480
1481 if (isnew)
1482 {
1483 for (BoardList::iterator it=fBoards.begin(); it!=fBoards.end(); it++)
1484 it->second->Cmd(FAD::kCmdBusyOn, true); // continously on
1485 }
1486
1487 // Loop over all scheduled re-connections
1488 for (auto it=fReconnectionList.begin(); it!=fReconnectionList.end(); it++)
1489 {
1490 if (ProcessReconnection(it))
1491 continue;
1492
1493 const lock_guard<mutex> guard(fMutexReconnect);
1494 fReconnectionList.erase(it);
1495 }
1496
1497 if (fReconnectionList.size()==0)
1498 {
1499 for (BoardList::iterator it=fBoards.begin(); it!=fBoards.end(); it++)
1500 it->second->Cmd(FAD::kCmdBusyOff, false);
1501 }
1502
1503 return T::GetCurrentState();
1504 }
1505*/
1506 // fadctrl: Always connecting if not disabled
1507 // event builder:
1508 if (nconnecting1==0 && nconnected1>0 && nconnected2==nconnected1)
1509 {
1510 if (T::GetCurrentState()==FAD::State::kConfiguring1)
1511 {
1512 // We need some delay so that the FAD is not busy anymore
1513 // and really sees the software trigger
1514 // FIXME: Do we need this to be configurable?
1515 //if (Time()-fConfigTimer<boost::posix_time::milliseconds(3000))
1516
1517 // Wait until the configuration commands to all boards
1518 // have been sent and achknowledged
1519 for (BoardList::iterator it=fBoards.begin(); it!=fBoards.end(); it++)
1520 if (!it->second->IsTxQueueEmpty())
1521 return FAD::State::kConfiguring1;
1522
1523 if (!fConfigTimer)
1524 fConfigTimer = Time();
1525
1526 // Wait a short moment to ensure that all board have processed
1527 // the received data
1528 if (Time()-fConfigTimer<boost::posix_time::milliseconds(250))
1529 return FAD::State::kConfiguring1;
1530
1531 for (BoardList::iterator it=fBoards.begin(); it!=fBoards.end(); it++)
1532 it->second->Cmd(FAD::kCmdSingleTrigger);
1533
1534 return FAD::State::kConfiguring2;
1535 }
1536
1537 // If all boards are configured and we are configuring
1538 // go on and start the FADs
1539 if (T::GetCurrentState()==FAD::State::kConfiguring2)
1540 {
1541 // If not all boards have yet received the proper
1542 // configuration
1543 if (nconfigured!=nconnected1)
1544 return FAD::State::kConfiguring2;
1545
1546 // FIXME: Distinguish between not all boards have received
1547 // the configuration and the configuration is not consistent
1548
1549 for (BoardList::iterator it=fBoards.begin(); it!=fBoards.end(); it++)
1550 {
1551 ConnectionFAD &fad = *it->second;
1552
1553 // Make sure that after switching on the trigger line
1554 // there needs to be some waiting before all boards
1555 // can be assumed to be listening
1556 fad.Cmd(FAD::kCmdResetEventCounter);
1557 fad.Cmd(FAD::kCmdSocket, false);
1558 //fad.Cmd(FAD::kCmdTriggerLine, true);
1559 if (fTargetConfig->second.fContinousTrigger)
1560 fad.Cmd(FAD::kCmdContTrigger, true);
1561 fad.Cmd(FAD::kCmdBusyOn, false); // continously on
1562
1563 // FIXME: How do we find out when the FADs
1564 // successfully enabled the trigger lines?
1565 }
1566
1567// const lock_guard<mutex> guard(fMutexReconnect);
1568// fReconnectionList.clear();
1569
1570 return FAD::State::kConfigured;
1571 }
1572
1573 if (T::GetCurrentState()==FAD::State::kConfigured)
1574 {
1575 // Stay in Configured as long as we have a valid
1576 // configuration and the run has not yet been started
1577 // (means the the event builder has received its
1578 // first event)
1579 if (IsRunWaiting() && nconfigured==nconnected1)
1580 return FAD::State::kConfigured;
1581
1582 if (!IsRunWaiting())
1583 T::Message("Run successfully started... first data received.");
1584 if (nconfigured!=nconnected1)
1585 T::Message("Configuration of some boards changed.");
1586 }
1587
1588 // FIXME: Rename WritingData to TakingData
1589 return IsRunInProgress() ? FAD::State::kRunInProgress : FAD::State::kConnected;
1590 }
1591
1592 if (nconnecting1>0 || nconnecting2>0 || nconnected1!=nconnected2)
1593 return FAD::State::kConnecting;
1594
1595 // nconnected1 == nconnected2 == 0
1596 return runs ? FAD::State::kDisconnected : FAD::State::kOffline;
1597 }
1598
1599 void AddEndpoint(const tcp::endpoint &addr)
1600 {
1601 int i=0;
1602 while (i<40)
1603 {
1604 if (fBoards.find(i)==fBoards.end())
1605 break;
1606 i++;
1607 }
1608
1609 if (i==40)
1610 {
1611 T::Warn("Not more than 40 slots allowed.");
1612 return;
1613 }
1614
1615 ConnectionFAD *fad = new ConnectionFAD(*this, *this, i);
1616
1617 fad->SetEndpoint(addr);
1618 fad->SetVerbose(fIsVerbose);
1619 fad->SetHexOutput(fIsHexOutput);
1620 fad->SetDataOutput(fIsDataOutput);
1621 fad->SetDebugTx(fDebugTx);
1622
1623 fBoards[i] = fad;
1624 }
1625
1626
1627 DimDescribedService fDimStartRun;
1628 DimDescribedService fDimConnection;
1629
1630 void UpdateConnectionStatus(const vector<uint8_t> &stat1, const vector<uint8_t> &stat2, bool thread)
1631 {
1632 vector<uint8_t> stat(41);
1633
1634 for (int i=0; i<40; i++)
1635 stat[i] = stat1[i]|(stat2[i]<<3);
1636
1637 stat[40] = thread;
1638
1639 fDimConnection.Update(stat);
1640 }
1641
1642public:
1643 StateMachineFAD(ostream &out=cout) :
1644 StateMachineAsio<T>(out, "FAD_CONTROL"),
1645 EventBuilderWrapper(*static_cast<MessageImp*>(this)),
1646 fStatus1(40), fStatus2(40), fStatusT(false),
1647 fDimStartRun("FAD_CONTROL/START_RUN", "X:1;X:1",
1648 "Run numbers"
1649 "|run[idx]:Run no of last conf'd run (-1 if reset or none config'd yet)"
1650 "|next[idx]:Run number which will be assigned to next configuration"),
1651 fDimConnection("FAD_CONTROL/CONNECTIONS", "C:40;C:1",
1652 "Connection status of FAD boards"
1653 "|status[bitpattern]:lower bits stat1, upper bits stat2, for every board. 40=thread"
1654 "|thread[bool]:true or false whether the event builder threads are running")
1655 {
1656 ResetConfig();
1657 SetOutputFormat(FAD::kNone);
1658
1659 // State names
1660 T::AddStateName(FAD::State::kOffline, "Disengaged",
1661 "All enabled FAD boards are disconnected and the event-builer thread is not running.");
1662
1663 T::AddStateName(FAD::State::kDisconnected, "Disconnected",
1664 "All enabled FAD boards are disconnected, but the event-builder thread is running.");
1665
1666 T::AddStateName(FAD::State::kConnecting, "Connecting",
1667 "Only some enabled FAD boards are connected.");
1668
1669 T::AddStateName(FAD::State::kConnected, "Connected",
1670 "All enabled FAD boards are connected..");
1671
1672 T::AddStateName(FAD::State::kConfiguring1, "Configuring1",
1673 "Waiting 3 seconds for all FADs to be configured before requesting configuration.");
1674
1675 T::AddStateName(FAD::State::kConfiguring2, "Configuring2",
1676 "Waiting until all boards returned their configuration and they are valid.");
1677
1678 T::AddStateName(FAD::State::kConfigured, "Configured",
1679 "The configuration of all boards was successfully cross checked. Waiting for events with a new run number to receive.");
1680
1681 T::AddStateName(FAD::State::kRunInProgress, "RunInProgress",
1682 "Events currently received by the event builder will be flagged to be written, no end-of-run event occured yet.");
1683
1684 // FAD Commands
1685 T::AddEvent("SEND_CMD", "I:1", FAD::State::kConnecting, FAD::State::kConnected, FAD::State::kRunInProgress)
1686 (bind(&StateMachineFAD::SendCmd, this, placeholders::_1))
1687 ("Send a command to the FADs. Values between 0 and 0xffff are allowed."
1688 "|command[uint16]:Command to be transmittted.");
1689 T::AddEvent("SEND_DATA", "I:2", FAD::State::kConnecting, FAD::State::kConnected, FAD::State::kRunInProgress)
1690 (bind(&StateMachineFAD::SendCmdData, this, placeholders::_1))
1691 ("Send a command with data to the FADs. Values between 0 and 0xffff are allowed."
1692 "|command[uint16]:Command to be transmittted."
1693 "|data[uint16]:Data to be sent with the command.");
1694
1695 T::AddEvent("ENABLE_SRCLK", "B:1", FAD::State::kConnecting, FAD::State::kConnected, FAD::State::kRunInProgress)
1696 (bind(&StateMachineFAD::CmdEnable, this, placeholders::_1, FAD::kCmdSrclk))
1697 ("Set SRCLK");
1698 T::AddEvent("ENABLE_BUSY_OFF", "B:1", FAD::State::kConnecting, FAD::State::kConnected, FAD::State::kRunInProgress)
1699 (bind(&StateMachineFAD::CmdEnable, this, placeholders::_1, FAD::kCmdBusyOff))
1700 ("Set BUSY continously low");
1701 T::AddEvent("ENABLE_BUSY_ON", "B:1", FAD::State::kConnecting, FAD::State::kConnected, FAD::State::kRunInProgress)
1702 (bind(&StateMachineFAD::CmdEnable, this, placeholders::_1, FAD::kCmdBusyOn))
1703 ("Set BUSY constantly high (has priority over BUSY_OFF)");
1704 T::AddEvent("ENABLE_SCLK", "B:1", FAD::State::kConnecting, FAD::State::kConnected, FAD::State::kRunInProgress)
1705 (bind(&StateMachineFAD::CmdEnable, this, placeholders::_1, FAD::kCmdSclk))
1706 ("Set SCLK");
1707 T::AddEvent("ENABLE_DRS", "B:1", FAD::State::kConnecting, FAD::State::kConnected, FAD::State::kRunInProgress)
1708 (bind(&StateMachineFAD::CmdEnable, this, placeholders::_1, FAD::kCmdDrsEnable))
1709 ("Switch Domino wave");
1710 T::AddEvent("ENABLE_DWRITE", "B:1", FAD::State::kConnecting, FAD::State::kConnected, FAD::State::kRunInProgress)
1711 (bind(&StateMachineFAD::CmdEnable, this, placeholders::_1, FAD::kCmdDwrite))
1712 ("Set Dwrite (possibly high / always low)");
1713 T::AddEvent("ENABLE_CONTINOUS_TRIGGER", "B:1", FAD::State::kConnecting, FAD::State::kConnected, FAD::State::kRunInProgress)
1714 (bind(&StateMachineFAD::CmdEnable, this, placeholders::_1, FAD::kCmdContTrigger))
1715 ("Enable continous (internal) trigger.");
1716 T::AddEvent("ENABLE_TRIGGER_LINE", "B:1", FAD::State::kConnecting, FAD::State::kConnected, FAD::State::kRunInProgress)
1717 (bind(&StateMachineFAD::CmdEnable, this, placeholders::_1, FAD::kCmdTriggerLine))
1718 ("Incoming triggers can be accepted/will not be accepted");
1719 T::AddEvent("ENABLE_COMMAND_SOCKET_MODE", "B:1", FAD::State::kConnecting, FAD::State::kConnected, FAD::State::kRunInProgress)
1720 (bind(&StateMachineFAD::CmdEnable, this, placeholders::_1, FAD::kCmdSocket))
1721 ("Set debug mode (yes: dump events through command socket, no=dump events through other sockets)");
1722
1723 T::AddEvent("SET_TRIGGER_RATE", "I:1", FAD::State::kConnecting, FAD::State::kConnected, FAD::State::kRunInProgress)
1724 (bind(&StateMachineFAD::SetTriggerRate, this, placeholders::_1))
1725 ("Enable continous trigger");
1726 T::AddEvent("SEND_SINGLE_TRIGGER")
1727 (bind(&StateMachineFAD::Trigger, this, 1))
1728 ("Issue software triggers");
1729 T::AddEvent("SEND_N_TRIGGERS", "I", FAD::State::kConnecting, FAD::State::kConnected, FAD::State::kRunInProgress)
1730 (bind(&StateMachineFAD::SendTriggers, this, placeholders::_1))
1731 ("Issue N software triggers (note that these are the triggers sent, not the triggers executed)"
1732 "|N[int]: Number of triggers to be sent to the board.");
1733 /*
1734 T::AddEvent("START_RUN", "", FAD::kConnecting, FAD::kConnected, FAD::kRunInProgress)
1735 (bind(&StateMachineFAD::StartRun, this, placeholders::_1, true))
1736 ("Set FAD DAQ mode. when started, no configurations must be send.");
1737 T::AddEvent("STOP_RUN", FAD::kConnecting, FAD::kConnected, FAD::kRunInProgress)
1738 (bind(&StateMachineFAD::StartRun, this, placeholders::_1, false))
1739 ("");
1740 */
1741 T::AddEvent("PHASE_SHIFT", "S:1", FAD::State::kConnecting, FAD::State::kConnected, FAD::State::kRunInProgress)
1742 (bind(&StateMachineFAD::PhaseShift, this, placeholders::_1))
1743 ("Adjust ADC phase (in 'steps')"
1744 "|phase[short]");
1745
1746 T::AddEvent("RESET_EVENT_COUNTER", FAD::State::kConnecting, FAD::State::kConnected, FAD::State::kRunInProgress)
1747 (bind(&StateMachineFAD::Cmd, this, FAD::kCmdResetEventCounter))
1748 ("Reset the FAD boards' event counter to 0.");
1749
1750 T::AddEvent("SET_RUN_NUMBER", "X:1", FAD::State::kConnecting, FAD::State::kConnected, FAD::State::kRunInProgress)
1751 (bind(&StateMachineFAD::SetRunNumber, this, placeholders::_1))
1752 ("Sent a new run-number to the boards"
1753 "|num[int]:Run number");
1754
1755 T::AddEvent("SET_MAX_MEMORY", "S:1")
1756 (bind(&StateMachineFAD::SetMaxMemoryBuffer, this, placeholders::_1))
1757 ("Set maximum memory buffer size allowed to be consumed by the EventBuilder to buffer events."
1758 "|memory[short]:Buffer size in Mega-bytes.");
1759
1760 T::AddEvent("SET_EVENT_TIMEOUT", "S:1")
1761 (bind(&StateMachineFAD::SetEventTimeoutSec, this, placeholders::_1))
1762 ("Set the timeout after which an event expires which was not completely received yet."
1763 "|timeout[sec]:Timeout in seconds [1;32767]");
1764
1765 T::AddEvent("SET_REGISTER", "I:2", FAD::State::kConnecting, FAD::State::kConnected, FAD::State::kRunInProgress)
1766 (bind(&StateMachineFAD::SetRegister, this, placeholders::_1))
1767 ("set register to value"
1768 "|addr[short]:Address of register"
1769 "|val[short]:Value to be set");
1770
1771 // FIXME: Maybe add a mask which channels should be set?
1772 T::AddEvent("SET_REGION_OF_INTEREST", "I:2", FAD::State::kConnecting, FAD::State::kConnected, FAD::State::kRunInProgress)
1773 (bind(&StateMachineFAD::SetRoi, this, placeholders::_1))
1774 ("Set region-of-interest to value"
1775 "|channel[short]:Channel on each chip for which the ROI is set (0-8), -1 for all"
1776 "|val[short]:Value to be set");
1777
1778 // FIXME: Maybe add a mask which channels should be set?
1779 T::AddEvent("SET_DAC_VALUE", "I:2", FAD::State::kConnecting, FAD::State::kConnected, FAD::State::kRunInProgress)
1780 (bind(&StateMachineFAD::SetDac, this, placeholders::_1))
1781 ("Set DAC numbers in range to value"
1782 "|addr[short]:Address of register (-1 for all)"
1783 "|val[short]:Value to be set");
1784
1785 T::AddEvent("CONFIGURE", "X:2;C", FAD::State::kConnected, FAD::State::kConfigured, FAD::State::kRunInProgress)
1786 (bind(&StateMachineFAD::StartConfigure, this, placeholders::_1))
1787 ("Configure a new run. If the internla trigger is enabled this might even start a new run."
1788 "|time_max[s]:Maximum time before the run is closed in seconds (0: unlimited)"
1789 "|num_max[int]:Maximum number of events before the run is closed in seconds (0: unlimited)"
1790 "|run_type[string]:Run type which describes the runs");
1791
1792 T::AddEvent("RESET_CONFIGURE", FAD::State::kConfiguring1, FAD::State::kConfiguring2, FAD::State::kConfigured)
1793 (bind(&StateMachineFAD::ResetConfig, this))
1794 ("If configuration failed and the fadctrl is waiting for something, use this to reset the state.");
1795
1796 // Verbosity commands
1797 T::AddEvent("SET_VERBOSE", "B:1")
1798 (bind(&StateMachineFAD::SetVerbosity, this, placeholders::_1))
1799 ("Set verbosity state"
1800 "|verbosity[bool]:disable or enable verbosity for received data (yes/no), except dynamic data");
1801
1802 T::AddEvent("SET_HEX_OUTPUT", "B:1")
1803 (bind(&StateMachineFAD::SetHexOutput, this, placeholders::_1))
1804 ("Enable or disable hex output for received data"
1805 "|hexout[bool]:disable or enable hex output for received data (yes/no)");
1806
1807 T::AddEvent("SET_DATA_OUTPUT", "B:1")
1808 (bind(&StateMachineFAD::SetDataOutput, this, placeholders::_1))
1809 ("Enable or disable printing of the received adc data to the console"
1810 "|dataout[bool]:disable or enable data output for received data (yes/no)");
1811
1812 T::AddEvent("SET_DEBUG_TX", "B:1")
1813 (bind(&StateMachineFAD::SetDebugTx, this, placeholders::_1))
1814 ("Enable or disable the output of messages in case of successfull data transmission to the boards."
1815 "|debug[bool]:disable or enable debug output for transmitted data (yes/no)");
1816
1817 T::AddEvent("PRINT_EVENT", "S:1")
1818 (bind(&StateMachineFAD::PrintEvent, this, placeholders::_1))
1819 ("Print (last) event"
1820 "|board[short]:slot from which the event should be printed (-1 for all)");
1821
1822 T::AddEvent("BLOCK_TRANSMISSION", "S:1;B:1")
1823 (bind(&StateMachineFAD::SetBlockTransmission, this, placeholders::_1))
1824 ("Blocks the transmission of commands to the given slot. Use with care! For debugging pupose only!"
1825 "|slot[short]:Slot to which the command transmission should be blocked (0-39)"
1826 "|enable[bool]:Whether the command transmission should be blockes (yes) or allowed (no)");
1827
1828 T::AddEvent("BLOCK_TRANSMISSION_RANGE", "S:2;B:1")
1829 (bind(&StateMachineFAD::SetBlockTransmissionRange, this, placeholders::_1))
1830 ("Blocks the transmission of commands to the given range of slots. Use with care! For debugging pupose only!"
1831 "|first[short]:First slot to which the command transmission should be blocked (0-39)"
1832 "|last[short]:Last slot to which the command transmission should be blocked (0-39)"
1833 "|enable[bool]:Whether the command transmission should be blockes (yes) or allowed (no)");
1834
1835 T::AddEvent("IGNORE_EVENTS", "S:1;B:1")
1836 (bind(&StateMachineFAD::SetIgnoreSlot, this, placeholders::_1))
1837 ("Instructs the event-builder to ignore events from the given slot but still read the data from the socket."
1838 "|slot[short]:Slot from which the data should be ignored when building events"
1839 "|enable[bool]:Whether the event builder should ignore data from this slot (yes) or allowed (no)");
1840
1841 T::AddEvent("IGNORE_EVENTS_RANGE", "S:2;B:1")
1842 (bind(&StateMachineFAD::SetIgnoreSlots, this, placeholders::_1))
1843 ("Instructs the event-builder to ignore events from the given slot but still read the data from the socket."
1844 "|first[short]:First slot from which the data should be ignored when building events"
1845 "|last[short]:Last slot from which the data should be ignored when building events"
1846 "|enable[bool]:Whether the event builder should ignore data from this slot (yes) or allowed (no)");
1847
1848 T::AddEvent("CLOSE_OPEN_FILES", FAD::State::kDisconnected, FAD::State::kConnecting, FAD::State::kConnected, FAD::State::kRunInProgress)
1849 (bind(&StateMachineFAD::CloseOpenFiles, this))
1850 ("Close all run files opened by the EventBuilder.");
1851
1852 //T::AddEvent("TEST", "S:1")
1853 // (bind(&StateMachineFAD::Test, this, placeholders::_1))
1854 // ("");
1855
1856
1857
1858 // Conenction commands
1859 T::AddEvent("START", FAD::State::kOffline)
1860 (bind(&StateMachineFAD::StartConnection, this))
1861 ("Start EventBuilder thread and connect all valid slots.");
1862
1863 T::AddEvent("STOP", FAD::State::kDisconnected, FAD::State::kConnecting, FAD::State::kConnected, FAD::State::kRunInProgress)
1864 (bind(&StateMachineFAD::StopConnection, this))
1865 ("Stop EventBuilder thread (still write buffered events) and disconnect all slots.");
1866
1867 T::AddEvent("ABORT", FAD::State::kDisconnected, FAD::State::kConnecting, FAD::State::kConnected, FAD::State::kRunInProgress)
1868 (bind(&StateMachineFAD::AbortConnection, this))
1869 ("Immediately abort EventBuilder thread and disconnect all slots.");
1870
1871 T::AddEvent("SOFT_RESET", FAD::State::kConnected, FAD::State::kRunInProgress)
1872 (bind(&StateMachineFAD::Reset, this, true))
1873 ("Wait for buffers to drain, close all files and reinitialize event builder thread.");
1874
1875 T::AddEvent("HARD_RESET", FAD::State::kConnected, FAD::State::kRunInProgress)
1876 (bind(&StateMachineFAD::Reset, this, false))
1877 ("Free all buffers, close all files and reinitialize event builder thread.");
1878
1879 T::AddEvent("CONNECT", "S:1", FAD::State::kDisconnected, FAD::State::kConnecting, FAD::State::kConnected)
1880 (bind(&StateMachineFAD::EnableSlot, this, placeholders::_1, true))
1881 ("Connect a disconnected slot.");
1882
1883 T::AddEvent("DISCONNECT", "S:1", FAD::State::kConnecting, FAD::State::kConnected)
1884 (bind(&StateMachineFAD::EnableSlot, this, placeholders::_1, false))
1885 ("Disconnect a connected slot.");
1886
1887 T::AddEvent("TOGGLE", "S:1", FAD::State::kDisconnected, FAD::State::kConnecting, FAD::State::kConnected)
1888 (bind(&StateMachineFAD::ToggleSlot, this, placeholders::_1))
1889 ("");
1890
1891 T::AddEvent("SET_FILE_FORMAT", "S:1")
1892 (bind(&StateMachineFAD::SetFileFormat, this, placeholders::_1))
1893 ("");
1894
1895 T::AddEvent("START_DRS_CALIBRATION")
1896 (bind(&StateMachineFAD::StartDrsCalibration, this))
1897 ("");
1898
1899 T::AddEvent("RESET_SECONDARY_DRS_BASELINE")
1900 (bind(&StateMachineFAD::ResetSecondaryDrsBaseline, this))
1901 ("");
1902
1903 T::AddEvent("LOAD_DRS_CALIBRATION", "C")
1904 (bind(&StateMachineFAD::LoadDrsCalibration, this, placeholders::_1))
1905 ("Load a DRS calibration file"
1906 "|absolute path");
1907
1908
1909 T::AddEvent("ADD_ADDRESS", "C", FAD::State::kOffline)
1910 (bind(&StateMachineFAD::AddAddress, this, placeholders::_1))
1911 ("Add the address of a DRS4 board to the first free slot"
1912 "|IP[string]:address in the format <address:port>");
1913 T::AddEvent("REMOVE_SLOT", "S:1", FAD::State::kOffline)
1914 (bind(&StateMachineFAD::RemoveSlot, this, placeholders::_1))
1915 ("Remove the Iaddress in slot n. For a list see LIST"
1916 "|slot[short]:Remove the address in slot n from the list");
1917 T::AddEvent("LIST_SLOTS")
1918 (bind(&StateMachineFAD::ListSlots, this))
1919 ("Print a list of all available board addressesa and whether they are enabled");
1920 }
1921
1922 ~StateMachineFAD()
1923 {
1924 for (BoardList::const_iterator i=fBoards.begin(); i!=fBoards.end(); i++)
1925 delete i->second;
1926 fBoards.clear();
1927 }
1928
1929 tcp::endpoint GetEndpoint(const string &base)
1930 {
1931 const size_t p0 = base.find_first_of(':');
1932 const size_t p1 = base.find_last_of(':');
1933
1934 if (p0==string::npos || p0!=p1)
1935 {
1936 T::Out() << kRed << "GetEndpoint - Wrong format ('host:port' expected)" << endl;
1937 return tcp::endpoint();
1938 }
1939
1940 tcp::resolver resolver(StateMachineAsio<T>::get_io_service());
1941
1942 boost::system::error_code ec;
1943
1944 const tcp::resolver::query query(base.substr(0, p0), base.substr(p0+1));
1945 const tcp::resolver::iterator iterator = resolver.resolve(query, ec);
1946
1947 if (ec)
1948 {
1949 T::Out() << kRed << "GetEndpoint - Couldn't resolve endpoint '" << base << "': " << ec.message();
1950 return tcp::endpoint();
1951 }
1952
1953 return *iterator;
1954 }
1955
1956 typedef map<string, FAD::Configuration> Configs;
1957 Configs fConfigs;
1958 Configs::const_iterator fTargetConfig;
1959
1960 Time fConfigTimer;
1961
1962
1963 template<class V>
1964 bool CheckConfigVal(Configuration &conf, V max, const string &name, const string &sub)
1965 {
1966 if (!conf.HasDef(name, sub))
1967 {
1968 T::Error("Neither "+name+"default nor "+name+sub+" found.");
1969 return false;
1970 }
1971
1972 const V val = conf.GetDef<V>(name, sub);
1973
1974 if (val<=max)
1975 return true;
1976
1977 ostringstream str;
1978 str << name << sub << "=" << val << " exceeds allowed maximum of " << max << "!";
1979 T::Error(str);
1980
1981 return false;
1982 }
1983
1984 int EvalOptions(Configuration &conf)
1985 {
1986 // ---------- General setup ---------
1987 fIsVerbose = !conf.Get<bool>("quiet");
1988 fIsHexOutput = conf.Get<bool>("hex-out");
1989 fIsDataOutput = conf.Get<bool>("data-out");
1990 fDebugTx = conf.Get<bool>("debug-tx");
1991
1992 // ---------- Setup event builder ---------
1993 SetMaxMemory(conf.Get<unsigned int>("max-mem"));
1994 SetEventTimeout(conf.Get<uint16_t>("event-timeout"));
1995
1996 if (!InitRunNumber(conf.Get<string>("destination-folder")))
1997 return 1;
1998
1999 // ---------- Setup run types ---------
2000 const vector<string> types = conf.Vec<string>("run-type");
2001 if (types.size()==0)
2002 T::Warn("No run-types defined.");
2003 else
2004 T::Message("Defining run-types");
2005 for (vector<string>::const_iterator it=types.begin();
2006 it!=types.end(); it++)
2007 {
2008 T::Message(" -> "+ *it);
2009
2010 if (fConfigs.count(*it)>0)
2011 {
2012 T::Error("Run-type "+*it+" defined twice.");
2013 return 2;
2014 }
2015
2016 FAD::Configuration target;
2017
2018 if (!CheckConfigVal<bool>(conf, true, "enable-drs.", *it) ||
2019 !CheckConfigVal<bool>(conf, true, "enable-dwrite.", *it) ||
2020 !CheckConfigVal<bool>(conf, true, "enable-continous-trigger.", *it))
2021 return 3;
2022
2023 target.fDenable = conf.GetDef<bool>("enable-drs.", *it);
2024 target.fDwrite = conf.GetDef<bool>("enable-dwrite.", *it);
2025 target.fContinousTrigger = conf.GetDef<bool>("enable-continous-trigger.", *it);
2026
2027 target.fTriggerRate = 0;
2028 //if (target.fContinousTrigger)
2029 {
2030 if (!CheckConfigVal<uint16_t>(conf, 0xffff, "trigger-rate.", *it))
2031 return 4;
2032
2033 target.fTriggerRate = conf.GetDef<uint16_t>("trigger-rate.", *it);
2034 }
2035
2036 for (int i=0; i<FAD::kNumChannelsPerChip; i++)
2037 {
2038 ostringstream str;
2039 str << "roi-ch" << i << '.';
2040
2041 if (!CheckConfigVal<uint16_t>(conf, FAD::kMaxRoiValue, "roi.", *it) &&
2042 !CheckConfigVal<uint16_t>(conf, FAD::kMaxRoiValue, str.str(), *it))
2043 return 5;
2044
2045 target.fRoi[i] = conf.HasDef(str.str(), *it) ?
2046 conf.GetDef<uint16_t>(str.str(), *it) :
2047 conf.GetDef<uint16_t>("roi.", *it);
2048 }
2049
2050 for (int i=0; i<FAD::kNumDac; i++)
2051 {
2052 ostringstream str;
2053 str << "dac-" << i << '.';
2054
2055 if (!CheckConfigVal<uint16_t>(conf, FAD::kMaxDacValue, "dac.", *it) &&
2056 !CheckConfigVal<uint16_t>(conf, FAD::kMaxDacValue, str.str(), *it))
2057 return 6;
2058
2059 target.fDac[i] = conf.HasDef(str.str(), *it) ?
2060 conf.GetDef<uint16_t>(str.str(), *it) :
2061 conf.GetDef<uint16_t>("dac.", *it);
2062 }
2063
2064 fConfigs[*it] = target;
2065 }
2066
2067 // FIXME: Add a check about unsused configurations
2068
2069 // ---------- Setup board addresses for fake-fad ---------
2070
2071 if (conf.Has("debug-addr"))
2072 {
2073 const string addr = conf.Get<string>("debug-addr");
2074 const int num = conf.Get<unsigned int>("debug-num");
2075
2076 const tcp::endpoint endpoint = GetEndpoint(addr);
2077 if (endpoint==tcp::endpoint())
2078 return 7;
2079
2080 for (int i=0; i<num; i++)
2081 AddEndpoint(tcp::endpoint(endpoint.address(), endpoint.port()+8*i));
2082
2083 if (conf.Get<bool>("start"))
2084 StartConnection();
2085 return -1;
2086 }
2087
2088 // ---------- Setup board addresses for the real camera ---------
2089
2090 if (conf.Has("base-addr"))
2091 {
2092 string base = conf.Get<string>("base-addr");
2093
2094 if (base=="def" || base =="default")
2095 base = "10.0.128.128:31919";
2096
2097 const tcp::endpoint endpoint = GetEndpoint(base);
2098 if (endpoint==tcp::endpoint())
2099 return 8;
2100
2101 const ba::ip::address_v4::bytes_type ip = endpoint.address().to_v4().to_bytes();
2102
2103 if (ip[2]>250 || ip[3]>244)
2104 {
2105 T::Out() << kRed << "EvalConfiguration - IP address given by --base-addr out-of-range." << endl;
2106 return 9;
2107 }
2108
2109 for (int crate=0; crate<4; crate++)
2110 for (int board=0; board<10; board++)
2111 {
2112 ba::ip::address_v4::bytes_type target = endpoint.address().to_v4().to_bytes();
2113 target[2] += crate;
2114 target[3] += board;
2115
2116 AddEndpoint(tcp::endpoint(ba::ip::address_v4(target), endpoint.port()));
2117 }
2118
2119 if (conf.Get<bool>("start"))
2120 StartConnection();
2121 return -1;
2122
2123 }
2124
2125 // ---------- Setup board addresses one by one ---------
2126
2127 if (conf.Has("addr"))
2128 {
2129 const vector<string> addrs = conf.Vec<string>("addr");
2130 for (vector<string>::const_iterator i=addrs.begin(); i<addrs.end(); i++)
2131 {
2132 const tcp::endpoint endpoint = GetEndpoint(*i);
2133 if (endpoint==tcp::endpoint())
2134 return 10;
2135
2136 AddEndpoint(endpoint);
2137 }
2138
2139 if (conf.Get<bool>("start"))
2140 StartConnection();
2141 return -1;
2142 }
2143 return -1;
2144 }
2145
2146};
2147
2148// ------------------------------------------------------------------------
2149
2150#include "Main.h"
2151
2152template<class T, class S>
2153int RunShell(Configuration &conf)
2154{
2155 return Main::execute<T, StateMachineFAD<S>>(conf);
2156}
2157
2158void SetupConfiguration(Configuration &conf)
2159{
2160 po::options_description control("FAD control options");
2161 control.add_options()
2162 ("quiet,q", po_bool(true), "Disable printing contents of all received messages in clear text.")
2163 ("hex-out", po_bool(), "Enable printing contents of all printed messages also as hex data.")
2164 ("data-out", po_bool(), "Enable printing received event data.")
2165 ("debug-tx", po_bool(), "Enable debugging of ethernet transmission.")
2166 ;
2167
2168 po::options_description connect("FAD connection options");
2169 connect.add_options()
2170 ("addr", vars<string>(), "Network address of FAD")
2171 ("base-addr", var<string>(), "Base address of all FAD")
2172 ("debug-num,n", var<unsigned int>(40), "Sets the number of fake boards to be connected locally")
2173 ("debug-addr", var<string>(), "")
2174 ("start", po_bool(false), "Start the connction immediately after boot")
2175 ;
2176
2177 po::options_description builder("Event builder options");
2178 builder.add_options()
2179 ("max-mem,m", var<unsigned int>(100), "Maximum memory the event builder thread is allowed to consume for its event buffer")
2180 ("event-timeout", var<uint16_t>(30), "After how many seconds is an event considered to be timed out? (<=0: disabled)")
2181 ("destination-folder", var<string>(""), "Destination folder (base folder) for the event builder binary data files.")
2182 ;
2183
2184 po::options_description runtype("Run type configuration");
2185 runtype.add_options()
2186 ("run-type", vars<string>(), "Run type, e.g. data, pedestal, drs-calibration, light-pulser")
2187 ("enable-dwrite.*", var<bool>(), "")
2188 ("enable-drs.*", var<bool>(), "")
2189 ("enable-continous-trigger.*", var<bool>(), "")
2190 ("trigger-rate.*", var<uint16_t>(), "")
2191 ("dac.*", var<uint16_t>(), "")
2192 ("dac-0.*", var<uint16_t>(), "")
2193 ("dac-1.*", var<uint16_t>(), "")
2194 ("dac-2.*", var<uint16_t>(), "")
2195 ("dac-3.*", var<uint16_t>(), "")
2196 ("dac-4.*", var<uint16_t>(), "")
2197 ("dac-5.*", var<uint16_t>(), "")
2198 ("dac-6.*", var<uint16_t>(), "")
2199 ("dac-7.*", var<uint16_t>(), "")
2200 ("roi.*", var<uint16_t>(), "")
2201 ("roi-ch0.*", var<uint16_t>(), "")
2202 ("roi-ch1.*", var<uint16_t>(), "")
2203 ("roi-ch2.*", var<uint16_t>(), "")
2204 ("roi-ch3.*", var<uint16_t>(), "")
2205 ("roi-ch4.*", var<uint16_t>(), "")
2206 ("roi-ch5.*", var<uint16_t>(), "")
2207 ("roi-ch6.*", var<uint16_t>(), "")
2208 ("roi-ch7.*", var<uint16_t>(), "")
2209 ("roi-ch8.*", var<uint16_t>(), "")
2210 ;
2211
2212 conf.AddEnv("dns", "DIM_DNS_NODE");
2213 conf.AddEnv("host", "DIM_HOST_NODE");
2214
2215 conf.AddOptions(control);
2216 conf.AddOptions(connect);
2217 conf.AddOptions(builder);
2218 conf.AddOptions(runtype);
2219}
2220
2221void PrintUsage()
2222{
2223 cout <<
2224 "The fadctrl controls the FAD boards.\n"
2225 "\n"
2226 "The default is that the program is started without user intercation. "
2227 "All actions are supposed to arrive as DimCommands. Using the -c "
2228 "option, a local shell can be initialized. With h or help a short "
2229 "help message about the usuage can be brought to the screen.\n"
2230 "\n"
2231 "Usage: fadctrl [-c type] [OPTIONS]\n"
2232 " or: fadctrl [OPTIONS]\n";
2233 cout << endl;
2234}
2235
2236void PrintHelp()
2237{
2238 Main::PrintHelp<StateMachineFAD<StateMachine>>();
2239
2240 /* Additional help text which is printed after the configuration
2241 options goes here */
2242}
2243
2244int main(int argc, const char* argv[])
2245{
2246 Configuration conf(argv[0]);
2247 conf.SetPrintUsage(PrintUsage);
2248 Main::SetupConfiguration(conf);
2249 SetupConfiguration(conf);
2250
2251 if (!conf.DoParse(argc, argv, PrintHelp))
2252 return 127;
2253
2254// try
2255 {
2256 // No console access at all
2257 if (!conf.Has("console"))
2258 {
2259// if (conf.Get<bool>("no-dim"))
2260// return RunShell<LocalStream, StateMachine>(conf);
2261// else
2262 return RunShell<LocalStream, StateMachineDim>(conf);
2263 }
2264
2265 // Cosole access w/ and w/o Dim
2266/* if (conf.Get<bool>("no-dim"))
2267 {
2268 if (conf.Get<int>("console")==0)
2269 return RunShell<LocalShell, StateMachine>(conf);
2270 else
2271 return RunShell<LocalConsole, StateMachine>(conf);
2272 }
2273 else
2274*/ {
2275 if (conf.Get<int>("console")==0)
2276 return RunShell<LocalShell, StateMachineDim>(conf);
2277 else
2278 return RunShell<LocalConsole, StateMachineDim>(conf);
2279 }
2280 }
2281/* catch (std::exception& e)
2282 {
2283 cerr << "Exception: " << e.what() << endl;
2284 return -1;
2285 }*/
2286
2287 return 0;
2288}
Note: See TracBrowser for help on using the repository browser.