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

Last change on this file since 12420 was 12377, checked in by tbretz, 13 years ago
Fixed a command description and improved some log message.
File size: 70.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 "Connection.h"
8#include "Configuration.h"
9#include "Console.h"
10#include "Converter.h"
11#include "HeadersFAD.h"
12
13#include "tools.h"
14
15#include "DimDescriptionService.h"
16#include "EventBuilderWrapper.h"
17
18namespace ba = boost::asio;
19namespace bs = boost::system;
20
21using ba::ip::tcp;
22
23using namespace std;
24
25// ------------------------------------------------------------------------
26
27class ConnectionFAD : public Connection
28{
29 uint16_t fSlot;
30// tcp::endpoint fEndpoint;
31
32 vector<uint16_t> fBuffer;
33
34protected:
35 FAD::EventHeader fEventHeader;
36 FAD::ChannelHeader fChannelHeader[FAD::kNumChannels];
37
38private:
39 bool fIsVerbose;
40 bool fIsHexOutput;
41 bool fIsDataOutput;
42 bool fBlockTransmission;
43
44 uint64_t fCounter;
45
46 FAD::EventHeader fBufEventHeader;
47 vector<uint16_t> fTargetRoi;
48
49protected:
50 void PrintEventHeader()
51 {
52 Out() << endl << kBold << "Header received (N=" << dec << fCounter << "):" << endl;
53 Out() << fEventHeader;
54 if (fIsHexOutput)
55 Out() << Converter::GetHex<uint16_t>(fEventHeader, 16) << endl;
56 }
57
58 void PrintChannelHeaders()
59 {
60 Out() << dec << endl;
61
62 for (unsigned int c=0; c<FAD::kNumChips; c++)
63 {
64 Out() << "ROI|" << fEventHeader.Crate() << ":" << fEventHeader.Board() << ":" << c << ":";
65 for (unsigned int ch=0; ch<FAD::kNumChannelsPerChip; ch++)
66 Out() << " " << setw(4) << fChannelHeader[c+ch*FAD::kNumChips].fRegionOfInterest;
67 Out() << endl;
68 }
69
70 Out() << "CEL|" << fEventHeader.Crate() << ":" <<fEventHeader.Board() << ": ";
71 for (unsigned int c=0; c<FAD::kNumChips; c++)
72 {
73 if (0)//fIsFullChannelHeader)
74 {
75 for (unsigned int ch=0; ch<FAD::kNumChannelsPerChip; ch++)
76 Out() << " " << setw(4) << fChannelHeader[c+ch*FAD::kNumChips].fStartCell;
77 Out() << endl;
78 }
79 else
80 {
81 Out() << " ";
82 const uint16_t cel = fChannelHeader[c*FAD::kNumChannelsPerChip].fStartCell;
83 for (unsigned int ch=1; ch<FAD::kNumChannelsPerChip; ch++)
84 if (cel!=fChannelHeader[c+ch*FAD::kNumChips].fStartCell)
85 {
86 Out() << "!";
87 break;
88 }
89 Out() << cel;
90 }
91 }
92 Out() << endl;
93
94 if (fIsHexOutput)
95 Out() << Converter::GetHex<uint16_t>(fChannelHeader, 16) << endl;
96
97 }
98
99 virtual void UpdateFirstHeader()
100 {
101 }
102
103 virtual void UpdateEventHeader()
104 {
105 // emit service with trigger counter from header
106 if (fIsVerbose)
107 PrintEventHeader();
108 }
109
110 virtual void UpdateChannelHeaders()
111 {
112 // emit service with trigger counter from header
113 if (fIsVerbose)
114 PrintChannelHeaders();
115
116 }
117
118 virtual void UpdateData(const uint16_t *data, size_t sz)
119 {
120 // emit service with trigger counter from header
121 if (fIsVerbose && fIsDataOutput)
122 Out() << Converter::GetHex<uint16_t>(data, sz, 16, true) << endl;
123 }
124
125private:
126 enum
127 {
128 kReadHeader = 1,
129 kReadData = 2,
130 };
131
132 void HandleReceivedData(const bs::error_code& err, size_t bytes_received, int type)
133 {
134 // Do not schedule a new read if the connection failed.
135 if (bytes_received==0 || err)
136 {
137 if (err==ba::error::eof)
138 Warn("Connection to "+URL()+" closed by remote host (FAD).");
139
140 // 107: Transport endpoint is not connected (bs::error_code(107, bs::system_category))
141 // 125: Operation canceled
142 if (err && err!=ba::error::eof && // Connection closed by remote host
143 err!=ba::error::basic_errors::not_connected && // Connection closed by remote host
144 err!=ba::error::basic_errors::operation_aborted) // Connection closed by us
145 {
146 ostringstream str;
147 str << "Reading from " << URL() << ": " << err.message() << " (" << err << ")";// << endl;
148 Error(str);
149 }
150 PostClose(err!=ba::error::basic_errors::operation_aborted);
151 return;
152 }
153
154 EventBuilderWrapper::This->debugStream(fSlot*7, fBuffer.data(), bytes_received);
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(fSlot*7, 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 IsConfigured() const
514 {
515 bool identical = true;
516 for (int i=0; i<FAD::kNumChannels; i++)
517 if (fTargetRoi[i]!=fChannelHeader[i].fRegionOfInterest)
518 {
519 identical = false;
520 break;
521 }
522
523 return fEventHeader==fBufEventHeader && identical;
524 }
525
526 const FAD::EventHeader &GetConfiguration() const { return fBufEventHeader; }
527};
528
529// ------------------------------------------------------------------------
530
531template <class T>
532class StateMachineFAD : public T, public EventBuilderWrapper, public ba::io_service, public ba::io_service::work
533{
534private:
535 typedef map<uint8_t, ConnectionFAD*> BoardList;
536
537 BoardList fBoards;
538
539 bool fIsVerbose;
540 bool fIsHexOutput;
541 bool fIsDataOutput;
542 bool fDebugTx;
543
544 bool CheckEventSize(size_t has, const char *name, size_t size)
545 {
546 if (has==size)
547 return true;
548
549 ostringstream msg;
550 msg << name << " - Received event has " << has << " bytes, but expected " << size << ".";
551 T::Fatal(msg);
552 return false;
553 }
554
555 int Cmd(FAD::Enable command)
556 {
557 for (BoardList::iterator i=fBoards.begin(); i!=fBoards.end(); i++)
558 i->second->Cmd(command);
559
560 return T::GetCurrentState();
561 }
562
563 int SendCmd(const EventImp &evt)
564 {
565 if (!CheckEventSize(evt.GetSize(), "SendCmd", 4))
566 return T::kSM_FatalError;
567
568 if (evt.GetUInt()>0xffff)
569 {
570 T::Warn("Command value out of range (0-65535).");
571 return T::GetCurrentState();
572 }
573
574 for (BoardList::iterator i=fBoards.begin(); i!=fBoards.end(); i++)
575 i->second->PostCmd(evt.GetUInt());
576
577 return T::GetCurrentState();
578 }
579
580 int SendCmdData(const EventImp &evt)
581 {
582 if (!CheckEventSize(evt.GetSize(), "SendCmdData", 8))
583 return T::kSM_FatalError;
584
585 const uint32_t *ptr = evt.Ptr<uint32_t>();
586
587 if (ptr[0]>0xffff)
588 {
589 T::Warn("Command value out of range (0-65535).");
590 return T::GetCurrentState();
591 }
592
593 if (ptr[1]>0xffff)
594 {
595 T::Warn("Data value out of range (0-65535).");
596 return T::GetCurrentState();
597 }
598
599 for (BoardList::iterator i=fBoards.begin(); i!=fBoards.end(); i++)
600 i->second->PostCmd(ptr[0], ptr[1]);
601
602 return T::GetCurrentState();
603 }
604
605 int CmdEnable(const EventImp &evt, FAD::Enable command)
606 {
607 if (!CheckEventSize(evt.GetSize(), "CmdEnable", 1))
608 return T::kSM_FatalError;
609
610 for (BoardList::iterator i=fBoards.begin(); i!=fBoards.end(); i++)
611 i->second->Cmd(command, evt.GetBool());
612
613 return T::GetCurrentState();
614 }
615
616 bool Check(const uint32_t *dat, uint32_t maxaddr, uint32_t maxval)
617 {
618 if (dat[0]>maxaddr)
619 {
620 ostringstream msg;
621 msg << hex << "Address " << dat[0] << " out of range, max=" << maxaddr << ".";
622 T::Error(msg);
623 return false;
624 }
625
626 if (dat[1]>maxval)
627 {
628 ostringstream msg;
629 msg << hex << "Value " << dat[1] << " out of range, max=" << maxval << ".";
630 T::Error(msg);
631 return false;
632 }
633
634 return true;
635 }
636
637 int SetRegister(const EventImp &evt)
638 {
639 if (!CheckEventSize(evt.GetSize(), "SetRegister", 8))
640 return T::kSM_FatalError;
641
642 const uint32_t *dat = evt.Ptr<uint32_t>();
643
644 if (!Check(dat, FAD::kMaxRegAddr, FAD::kMaxRegValue))
645 return T::GetCurrentState();
646
647 for (BoardList::iterator i=fBoards.begin(); i!=fBoards.end(); i++)
648 i->second->CmdSetRegister(dat[0], dat[1]);
649
650 return T::GetCurrentState();
651 }
652
653 int SetRoi(const EventImp &evt)
654 {
655 if (!CheckEventSize(evt.GetSize(), "SetRoi", 8))
656 return T::kSM_FatalError;
657
658 const int32_t *dat = evt.Ptr<int32_t>();
659
660 for (BoardList::iterator i=fBoards.begin(); i!=fBoards.end(); i++)
661 if (!i->second->CmdSetRoi(dat[0], dat[1]))
662 {
663 ostringstream msg;
664 msg << hex << "Channel " << dat[0] << " or Value " << dat[1] << " out of range.";
665 T::Error(msg);
666 return false;
667 }
668
669
670 return T::GetCurrentState();
671 }
672
673 int SetDac(const EventImp &evt)
674 {
675 if (!CheckEventSize(evt.GetSize(), "SetDac", 8))
676 return T::kSM_FatalError;
677
678 const int32_t *dat = evt.Ptr<int32_t>();
679
680 for (BoardList::iterator i=fBoards.begin(); i!=fBoards.end(); i++)
681 if (!i->second->CmdSetDacValue(dat[0], dat[1]))
682 {
683 ostringstream msg;
684 msg << hex << "Channel " << dat[0] << " or Value " << dat[1] << " out of range.";
685 T::Error(msg);
686 return false;
687 }
688
689 return T::GetCurrentState();
690 }
691
692 int Trigger(int n)
693 {
694 for (int nn=0; nn<n; nn++)
695 for (BoardList::iterator i=fBoards.begin(); i!=fBoards.end(); i++)
696 i->second->Cmd(FAD::kCmdSingleTrigger);
697
698 return T::GetCurrentState();
699 }
700
701 int SendTriggers(const EventImp &evt)
702 {
703 if (!CheckEventSize(evt.GetSize(), "SendTriggers", 4))
704 return T::kSM_FatalError;
705
706 Trigger(evt.GetUInt());
707
708 return T::GetCurrentState();
709 }
710
711 int StartRun(const EventImp &evt, bool start)
712 {
713 if (!CheckEventSize(evt.GetSize(), "StartRun", 0))
714 return T::kSM_FatalError;
715
716 for (BoardList::iterator i=fBoards.begin(); i!=fBoards.end(); i++)
717 i->second->Cmd(FAD::kCmdRun, start);
718
719 return T::GetCurrentState();
720 }
721
722 int PhaseShift(const EventImp &evt)
723 {
724 if (!CheckEventSize(evt.GetSize(), "PhaseShift", 2))
725 return T::kSM_FatalError;
726
727 for (BoardList::iterator i=fBoards.begin(); i!=fBoards.end(); i++)
728 i->second->CmdPhaseShift(evt.GetShort());
729
730 return T::GetCurrentState();
731 }
732
733 int SetTriggerRate(const EventImp &evt)
734 {
735 if (!CheckEventSize(evt.GetSize(), "SetTriggerRate", 4))
736 return T::kSM_FatalError;
737
738 if (evt.GetUInt()>0xffff)
739 {
740 ostringstream msg;
741 msg << hex << "Value " << evt.GetUShort() << " out of range, max=" << 0xffff << "(?)";
742 T::Error(msg);
743 return false;
744 }
745
746 for (BoardList::iterator i=fBoards.begin(); i!=fBoards.end(); i++)
747 i->second->CmdSetTriggerRate(evt.GetUInt());
748
749 return T::GetCurrentState();
750 }
751
752 int SetRunNumber(const EventImp &evt)
753 {
754 if (!CheckEventSize(evt.GetSize(), "SetRunNumber", 8))
755 return T::kSM_FatalError;
756
757 const uint64_t num = evt.GetUXtra();
758
759 if (num>FAD::kMaxRunNumber)
760 {
761 ostringstream msg;
762 msg << "Run number " << num << " out of range (max=" << FAD::kMaxRunNumber << ")";
763 T::Error(msg);
764 return false;
765 }
766
767 if (num>0 && num<GetRunNumber())
768 {
769 ostringstream msg;
770 msg << "Given run number (" << num << ") smaller than next run number (" << GetRunNumber() << ") which will be opened by the event builder";
771 T::Error(msg);
772 return false;
773 }
774
775 IncreaseRunNumber(num);
776
777 for (BoardList::iterator i=fBoards.begin(); i!=fBoards.end(); i++)
778 i->second->CmdSetRunNumber(num);
779
780 return T::GetCurrentState();
781 }
782
783 int SetMaxMemoryBuffer(const EventImp &evt)
784 {
785 if (!CheckEventSize(evt.GetSize(), "SetMaxMemoryBuffer", 2))
786 return T::kSM_FatalError;
787
788 const int16_t mem = evt.GetShort();
789
790 if (mem<=0)
791 {
792 ostringstream msg;
793 msg << hex << "Value " << mem << " out of range.";
794 T::Error(msg);
795 return false;
796 }
797
798 SetMaxMemory(mem);
799
800 return T::GetCurrentState();
801 }
802
803 int SetFileFormat(const EventImp &evt)
804 {
805 if (!CheckEventSize(evt.GetSize(), "SetFileFormat", 2))
806 return T::kSM_FatalError;
807
808 const uint16_t fmt = evt.GetUShort();
809
810 switch (fmt)
811 {
812 case 0: SetOutputFormat(kNone); break;
813 case 1: SetOutputFormat(kDebug); break;
814 case 2: SetOutputFormat(kFits); break;
815 case 3: SetOutputFormat(kRaw); break;
816 case 4: SetOutputFormat(kCalib); break;
817 default:
818 T::Error("File format unknonw.");
819 return false;
820 }
821
822 return T::GetCurrentState();
823 }
824
825 int LoadDrsCalibration(const EventImp &evt)
826 {
827 EventBuilderWrapper::LoadDrsCalibration(evt.GetText());
828 return T::GetCurrentState();
829 }
830
831 int Test(const EventImp &evt)
832 {
833 if (!CheckEventSize(evt.GetSize(), "Test", 2))
834 return T::kSM_FatalError;
835
836
837 SetMode(evt.GetShort());
838
839 return T::GetCurrentState();
840 }
841
842
843 int SetVerbosity(const EventImp &evt)
844 {
845 if (!CheckEventSize(evt.GetSize(), "SetVerbosity", 1))
846 return T::kSM_FatalError;
847
848 for (BoardList::iterator i=fBoards.begin(); i!=fBoards.end(); i++)
849 i->second->SetVerbose(evt.GetBool());
850
851 return T::GetCurrentState();
852 }
853
854 int SetHexOutput(const EventImp &evt)
855 {
856 if (!CheckEventSize(evt.GetSize(), "SetHexOutput", 1))
857 return T::kSM_FatalError;
858
859 for (BoardList::iterator i=fBoards.begin(); i!=fBoards.end(); i++)
860 i->second->SetHexOutput(evt.GetBool());
861
862 return T::GetCurrentState();
863 }
864
865 int SetDataOutput(const EventImp &evt)
866 {
867 if (!CheckEventSize(evt.GetSize(), "SetDataOutput", 1))
868 return T::kSM_FatalError;
869
870 for (BoardList::iterator i=fBoards.begin(); i!=fBoards.end(); i++)
871 i->second->SetDataOutput(evt.GetBool());
872
873 return T::GetCurrentState();
874 }
875
876 int SetDebugTx(const EventImp &evt)
877 {
878 if (!CheckEventSize(evt.GetSize(), "SetDebugTx", 1))
879 return T::kSM_FatalError;
880
881 for (BoardList::iterator i=fBoards.begin(); i!=fBoards.end(); i++)
882 i->second->SetDebugTx(evt.GetBool());
883
884 return T::GetCurrentState();
885 }
886
887 int SetDebugEb(const EventImp &evt)
888 {
889 if (!CheckEventSize(evt.GetSize(), "SetDebugEb", 1))
890 return T::kSM_FatalError;
891
892 SetDebugLog(evt.GetBool());
893
894 return T::GetCurrentState();
895 }
896
897 const BoardList::iterator GetSlot(uint16_t slot)
898 {
899 const BoardList::iterator it=fBoards.find(slot);
900 if (it==fBoards.end())
901 {
902 ostringstream str;
903 str << "Slot " << slot << " not found.";
904 T::Warn(str);
905 }
906
907 return it;
908 }
909
910 int PrintEvent(const EventImp &evt)
911 {
912 if (!CheckEventSize(evt.GetSize(), "PrintEvent", 2))
913 return T::kSM_FatalError;
914
915 const int16_t slot = evt.Get<int16_t>();
916
917 if (slot<0)
918 {
919 for (BoardList::iterator i=fBoards.begin(); i!=fBoards.end(); i++)
920 i->second->PrintEvent();
921 }
922 else
923 {
924 const BoardList::iterator it=GetSlot(slot);
925 if (it!=fBoards.end())
926 it->second->PrintEvent();
927 }
928
929 return T::GetCurrentState();
930 }
931
932 int SetBlockTransmission(const EventImp &evt)
933 {
934 if (!CheckEventSize(evt.GetSize(), "SetBlockTransmission", 3))
935 return T::kSM_FatalError;
936
937 const int16_t slot = evt.Get<int32_t>();
938
939 const BoardList::iterator it=GetSlot(slot);
940 if (it!=fBoards.end())
941 it->second->SetBlockTransmission(evt.Get<uint8_t>(2));
942
943 return T::GetCurrentState();
944 }
945
946 int SetBlockTransmissionRange(const EventImp &evt)
947 {
948 if (!CheckEventSize(evt.GetSize(), "SetBlockTransmissionRange", 5))
949 return T::kSM_FatalError;
950
951 const int16_t *slot = evt.Ptr<int16_t>();
952 const bool block = evt.Get<uint8_t>(4);
953
954 for (int i=slot[0]; i<=slot[1]; i++)
955 {
956 const BoardList::iterator it=GetSlot(i);
957 if (it!=fBoards.end())
958 it->second->SetBlockTransmission(block);
959 }
960
961 return T::GetCurrentState();
962 }
963
964 int SetIgnoreSlot(const EventImp &evt)
965 {
966 if (!CheckEventSize(evt.GetSize(), "SetIgnoreSlot", 3))
967 return T::kSM_FatalError;
968
969 const uint16_t slot = evt.Get<uint16_t>();
970
971 if (slot>39)
972 {
973 T::Warn("Slot out of range (0-39).");
974 return T::GetCurrentState();
975 }
976
977 SetIgnore(slot, evt.Get<uint8_t>(2));
978
979 return T::GetCurrentState();
980 }
981
982 int SetIgnoreSlots(const EventImp &evt)
983 {
984 if (!CheckEventSize(evt.GetSize(), "SetIgnoreSlots", 5))
985 return T::kSM_FatalError;
986
987 const int16_t *slot = evt.Ptr<int16_t>();
988 const bool block = evt.Get<uint8_t>(4);
989
990 if (slot[0]<0 || slot[1]>39 || slot[0]>slot[1])
991 {
992 T::Warn("Slot out of range.");
993 return T::GetCurrentState();
994 }
995
996 for (int i=slot[0]; i<=slot[1]; i++)
997 SetIgnore(i, block);
998
999 return T::GetCurrentState();
1000 }
1001
1002 int SetDumpStream(const EventImp &evt)
1003 {
1004 if (!CheckEventSize(evt.GetSize(), "SetDumpStream", 1))
1005 return T::kSM_FatalError;
1006
1007 SetDebugStream(evt.Get<uint8_t>());
1008
1009 return T::GetCurrentState();
1010 }
1011
1012 int SetDumpRecv(const EventImp &evt)
1013 {
1014 if (!CheckEventSize(evt.GetSize(), "SetDumpRecv", 1))
1015 return T::kSM_FatalError;
1016
1017 SetDebugRead(evt.Get<uint8_t>());
1018
1019 return T::GetCurrentState();
1020 }
1021
1022 int StartConfigure(const EventImp &evt)
1023 {
1024 const string name = evt.Ptr<char>(16);
1025
1026 fTargetConfig = fConfigs.find(name);
1027 if (fTargetConfig==fConfigs.end())
1028 {
1029 T::Error("StartConfigure - Run-type '"+name+"' not found.");
1030 return T::GetCurrentState();
1031 }
1032
1033 if (fNightAsInt!=Time().NightAsInt())
1034 {
1035 ostringstream out;
1036 out << "Night changed from " << fNightAsInt << " to " << Time().NightAsInt() << "... determining new run-number.";
1037 T::Info(out);
1038
1039 // FIXME: What about an error state?
1040 fNightAsInt = InitRunNumber();
1041 if (fNightAsInt<0)
1042 return FAD::kConnected;
1043 }
1044
1045 const uint32_t runno = StartNewRun(evt.Get<uint64_t>(), evt.Get<uint64_t>(8), *fTargetConfig);
1046
1047 ostringstream str;
1048 str << "Starting configuration for run " << runno << " (" << name << ")";
1049 T::Message(str.str());
1050
1051 if (runno>=1000)
1052 T::Warn("Run number exceeds logical maximum of 999 - this is no problem for writing but might give raise to problems in the analysis.");
1053
1054 const FAD::Configuration &conf = fTargetConfig->second;
1055
1056 for (BoardList::iterator it=fBoards.begin(); it!=fBoards.end(); it++)
1057 {
1058 ConnectionFAD &fad = *it->second;
1059
1060 fad.Cmd(FAD::kCmdBusyOn, true); // continously on
1061 fad.Cmd(FAD::kCmdTriggerLine, false);
1062 fad.Cmd(FAD::kCmdContTrigger, false);
1063 fad.Cmd(FAD::kCmdSocket, true);
1064 fad.Cmd(FAD::kCmdBusyOff, false); // normal when BusyOn==0
1065
1066 fad.Cmd(FAD::kCmdDwrite, conf.fDwrite);
1067 fad.Cmd(FAD::kCmdDrsEnable, conf.fDenable);
1068
1069 for (int i=0; i<FAD::kNumDac; i++)
1070 fad.CmdSetDacValue(i, conf.fDac[i]);
1071
1072 for (int i=0; i<FAD::kNumChips; i++)
1073 for (int j=0; j<FAD::kNumChannelsPerChip; j++)
1074 fad.CmdSetRoi(i*FAD::kNumChannelsPerChip+j, conf.fRoi[j]);
1075
1076 fad.CmdSetTriggerRate(conf.fTriggerRate);
1077 fad.CmdSetRunNumber(runno);
1078 fad.Cmd(FAD::kCmdResetEventCounter);
1079 fad.Cmd(FAD::kCmdTriggerLine, true);
1080 //fad.Cmd(FAD::kCmdSingleTrigger);
1081 //fad.Cmd(FAD::kCmdTriggerLine, true);
1082 }
1083
1084 // Now the old run is stopped already. So all other servers can start a new run
1085 // (Note that we might need another step which only checks if the continous trigger
1086 // is wwitched off, too)
1087 const int64_t runs[2] = { runno, runno+1 };
1088 fDimStartRun.Update(runs);
1089
1090 T::Info(" ==> TODO: Insert/update run configuration in database!");
1091
1092 fConfigTimer = Time();
1093
1094 return FAD::kConfiguring1;
1095 }
1096
1097 int ResetConfig()
1098 {
1099 const int64_t runs[2] = { -1, GetRunNumber() };
1100 fDimStartRun.Update(runs);
1101
1102 return FAD::kConnected;
1103 }
1104
1105 void CloseRun(uint32_t runid)
1106 {
1107 if (runid==GetRunNumber()-1)
1108 ResetConfig();
1109 }
1110
1111 int AddAddress(const EventImp &evt)
1112 {
1113 const string addr = Tools::Trim(evt.GetText());
1114
1115 const tcp::endpoint endpoint = GetEndpoint(addr);
1116 if (endpoint==tcp::endpoint())
1117 return T::GetCurrentState();
1118
1119 for (BoardList::const_iterator i=fBoards.begin(); i!=fBoards.end(); i++)
1120 {
1121 if (i->second->GetEndpoint()==endpoint)
1122 {
1123 T::Warn("Address "+addr+" already known.... ignored.");
1124 return T::GetCurrentState();
1125 }
1126 }
1127
1128 AddEndpoint(endpoint);
1129
1130 return T::GetCurrentState();
1131 }
1132
1133 int RemoveSlot(const EventImp &evt)
1134 {
1135 if (!CheckEventSize(evt.GetSize(), "RemoveSlot", 2))
1136 return T::kSM_FatalError;
1137
1138 const int16_t slot = evt.GetShort();
1139
1140 const BoardList::iterator it = GetSlot(slot);
1141
1142 if (it==fBoards.end())
1143 return T::GetCurrentState();
1144
1145 ConnectSlot(slot, tcp::endpoint());
1146
1147 delete it->second;
1148 fBoards.erase(it);
1149
1150 return T::GetCurrentState();
1151 }
1152
1153 int ListSlots()
1154 {
1155 for (BoardList::iterator i=fBoards.begin(); i!=fBoards.end(); i++)
1156 {
1157 const int &idx = i->first;
1158 const ConnectionFAD *fad = i->second;
1159
1160 ostringstream str;
1161 str << "Slot " << setw(2) << idx << ": " << fad->GetEndpoint();
1162
1163 if (fad->IsConnecting())
1164 str << " (0:connecting, ";
1165 else
1166 {
1167 if (fad->IsClosed())
1168 str << " (0:disconnected, ";
1169 if (fad->IsConnected())
1170 str << " (0:connected, ";
1171 }
1172
1173 switch (fStatus2[idx])
1174 {
1175 case 0: str << "1-7:not connected)"; break;
1176 case 8: str << "1-7:connected)"; break;
1177 default: str << "1-7:connecting [" << (int)(fStatus2[idx]-1) << "])"; break;
1178 }
1179
1180 if (fad->IsTransmissionBlocked())
1181 str << " [cmd_blocked]";
1182
1183 if (fStatus2[idx]==8 && IsIgnored(idx))
1184 str << " [data_ignored]";
1185
1186 if (fStatusC[idx])
1187 str << " [configured]";
1188
1189 T::Out() << str.str() << endl;
1190 }
1191
1192 T::Out() << "Event builder thread:";
1193 if (!IsThreadRunning())
1194 T::Out() << " not";
1195 T::Out() << " running" << endl;
1196
1197 // FIXME: Output state
1198
1199 return T::GetCurrentState();
1200 }
1201
1202 void EnableConnection(ConnectionFAD *ptr, bool enable=true)
1203 {
1204 if (!enable)
1205 {
1206 ptr->PostClose(false);
1207 return;
1208 }
1209
1210 if (!ptr->IsDisconnected())
1211 {
1212 ostringstream str;
1213 str << ptr->GetEndpoint();
1214
1215 T::Warn("Connection to "+str.str()+" already in progress.");
1216 return;
1217 }
1218
1219 ptr->StartConnect();
1220 }
1221
1222 void EnableAll(bool enable=true)
1223 {
1224 for (BoardList::iterator i=fBoards.begin(); i!=fBoards.end(); i++)
1225 EnableConnection(i->second, enable);
1226 }
1227
1228 int CloseOpenFiles()
1229 {
1230 EventBuilderWrapper::CloseOpenFiles();
1231 return T::GetCurrentState();
1232 }
1233
1234 int EnableSlot(const EventImp &evt, bool enable)
1235 {
1236 if (!CheckEventSize(evt.GetSize(), "EnableSlot", 2))
1237 return T::kSM_FatalError;
1238
1239 const int16_t slot = evt.GetShort();
1240
1241 const BoardList::iterator it = GetSlot(slot);
1242 if (it==fBoards.end())
1243 return T::GetCurrentState();
1244
1245 EnableConnection(it->second, enable);
1246 ConnectSlot(it->first, enable ? it->second->GetEndpoint() : tcp::endpoint());
1247
1248 return T::GetCurrentState();
1249 }
1250
1251 int ToggleSlot(const EventImp &evt)
1252 {
1253 if (!CheckEventSize(evt.GetSize(), "ToggleSlot", 2))
1254 return T::kSM_FatalError;
1255
1256 const int16_t slot = evt.GetShort();
1257
1258 const BoardList::iterator it = GetSlot(slot);
1259 if (it==fBoards.end())
1260 return T::GetCurrentState();
1261
1262 const bool enable = it->second->IsDisconnected();
1263
1264 EnableConnection(it->second, enable);
1265 ConnectSlot(it->first, enable ? it->second->GetEndpoint() : tcp::endpoint());
1266
1267 return T::GetCurrentState();
1268 }
1269
1270 int StartConnection()
1271 {
1272 vector<tcp::endpoint> addr(40);
1273
1274 for (BoardList::iterator i=fBoards.begin(); i!=fBoards.end(); i++)
1275 addr[i->first] = i->second->GetEndpoint();
1276
1277 StartThread(addr);
1278 EnableAll(true);
1279
1280 return T::GetCurrentState();
1281 }
1282
1283 int StopConnection()
1284 {
1285 Exit();
1286 EnableAll(false);
1287 return T::GetCurrentState();
1288 }
1289
1290 int AbortConnection()
1291 {
1292 Abort();
1293 EnableAll(false);
1294 return T::GetCurrentState();
1295 }
1296
1297 int Reset(bool soft)
1298 {
1299 ResetThread(soft);
1300 return T::GetCurrentState();
1301 }
1302
1303 vector<uint8_t> fStatus1;
1304 vector<uint8_t> fStatus2;
1305 vector<uint8_t> fStatusC;
1306 bool fStatusT;
1307
1308 int Execute()
1309 {
1310 // Dispatch (execute) at most one handler from the queue. In contrary
1311 // to run_one(), it doesn't wait until a handler is available
1312 // which can be dispatched, so poll_one() might return with 0
1313 // handlers dispatched. The handlers are always dispatched/executed
1314 // synchronously, i.e. within the call to poll_one()
1315 poll_one();
1316
1317 // ===== Evaluate connection status =====
1318
1319 uint16_t nclosed1 = 0;
1320 uint16_t nconnecting1 = 0;
1321 uint16_t nconnecting2 = 0;
1322 uint16_t nconnected1 = 0;
1323 uint16_t nconnected2 = 0;
1324 uint16_t nconfigured = 0;
1325
1326 vector<uint8_t> stat1(40);
1327 vector<uint8_t> stat2(40);
1328
1329 int cnt = 0; // counter for enabled board
1330
1331 const bool runs = IsThreadRunning();
1332
1333 for (int idx=0; idx<40; idx++)
1334 {
1335 // ----- Command socket -----
1336 const BoardList::const_iterator &slot = fBoards.find(idx);
1337 if (slot!=fBoards.end())
1338 {
1339 const ConnectionFAD *c = slot->second;
1340 if (c->IsDisconnected())
1341 {
1342 stat1[idx] = 0;
1343 nclosed1++;
1344
1345 //DisconnectSlot(idx);
1346 }
1347 if (c->IsConnecting())
1348 {
1349 stat1[idx] = 1;
1350 nconnecting1++;
1351 }
1352 if (c->IsConnected())
1353 {
1354 stat1[idx] = 2;
1355 nconnected1++;
1356
1357 if (c->IsConfigured())
1358 {
1359 stat1[idx] = 3;
1360 nconfigured++;
1361 }
1362 }
1363
1364 cnt++;
1365 }
1366
1367 // ----- Event builder -----
1368
1369 if (!runs)
1370 continue;
1371
1372 stat2[idx] = GetNumConnected(idx);
1373
1374 if (runs && IsConnecting(idx))
1375 {
1376 nconnecting2++;
1377 stat2[idx]++;
1378 }
1379
1380 if (IsConnected(idx))
1381 {
1382 stat2[idx]++;
1383 nconnected2++;
1384 }
1385 }
1386
1387 // ===== Send connection status via dim =====
1388
1389 if (fStatus1!=stat1 || fStatus2!=stat2 || fStatusT!=runs)
1390 {
1391 fStatus1 = stat1;
1392 fStatus2 = stat2;
1393 fStatusT = runs;
1394 UpdateConnectionStatus(stat1, stat2, runs);
1395 }
1396
1397 // ===== Return connection status =====
1398
1399 // fadctrl: Always connecting if not disabled
1400 // event builder:
1401 if (nconnecting1==0 && nconnected1>0 && nconnected2==nconnected1)
1402 {
1403 if (T::GetCurrentState()==FAD::kConfiguring1)
1404 {
1405 // We need some delay so that the FAD is not busy anymore
1406 // and really sees the software trigger
1407 // FIXME: Do we need this to be configurable?
1408 if (Time()-fConfigTimer<boost::posix_time::milliseconds(3000))
1409 return FAD::kConfiguring1;
1410
1411 for (BoardList::iterator it=fBoards.begin(); it!=fBoards.end(); it++)
1412 it->second->Cmd(FAD::kCmdSingleTrigger);
1413
1414 return FAD::kConfiguring2;
1415 }
1416
1417 // If all boards are configured and we are configuring
1418 // go on and start the FADs
1419 if (T::GetCurrentState()==FAD::kConfiguring2)
1420 {
1421 // If not all boards have yet received the proper
1422 // configuration
1423 if (nconfigured!=nconnected1)
1424 return FAD::kConfiguring2;
1425
1426 // FIXME: Distinguish between not all boards have received
1427 // the configuration and the configuration is not consistent
1428
1429 for (BoardList::iterator it=fBoards.begin(); it!=fBoards.end(); it++)
1430 {
1431 ConnectionFAD &fad = *it->second;
1432
1433 // Make sure that after switching on the trigger line
1434 // there needs to be some waiting before all boards
1435 // can be assumed to be listening
1436 fad.Cmd(FAD::kCmdResetEventCounter);
1437 fad.Cmd(FAD::kCmdSocket, false);
1438 //fad.Cmd(FAD::kCmdTriggerLine, true);
1439 if (fTargetConfig->second.fContinousTrigger)
1440 fad.Cmd(FAD::kCmdContTrigger, true);
1441 fad.Cmd(FAD::kCmdBusyOn, false); // continously on
1442
1443 // FIXME: How do we find out when the FADs
1444 // successfully enabled the trigger lines?
1445 }
1446 return FAD::kConfigured;
1447 }
1448
1449 if (T::GetCurrentState()==FAD::kConfigured)
1450 {
1451 // Stay in Configured as long as we have a valid
1452 // configuration and the run has not yet been started
1453 // (means the the event builder has received its
1454 // first event)
1455 if (!IsRunStarted() && nconfigured==nconnected1)
1456 return FAD::kConfigured;
1457
1458 if (IsRunStarted())
1459 T::Message("Run successfully started... (gotNewRun called)");
1460 if (nconfigured!=nconnected1)
1461 T::Message("Configuration of some boards changed.");
1462 }
1463
1464 return GetNumFilesOpen()>0 ? FAD::kWritingData : FAD::kConnected;
1465 }
1466
1467 if (nconnecting1>0 || nconnecting2>0 || nconnected1!=nconnected2)
1468 return FAD::kConnecting;
1469
1470 // nconnected1 == nconnected2 == 0
1471 return runs ? FAD::kDisconnected : FAD::kOffline;
1472 }
1473
1474 void AddEndpoint(const tcp::endpoint &addr)
1475 {
1476 int i=0;
1477 while (i<40)
1478 {
1479 if (fBoards.find(i)==fBoards.end())
1480 break;
1481 i++;
1482 }
1483
1484 if (i==40)
1485 {
1486 T::Warn("Not more than 40 slots allowed.");
1487 return;
1488 }
1489
1490 ConnectionFAD *fad = new ConnectionFAD(*this, *this, i);
1491
1492 fad->SetEndpoint(addr);
1493 fad->SetVerbose(fIsVerbose);
1494 fad->SetHexOutput(fIsHexOutput);
1495 fad->SetDataOutput(fIsDataOutput);
1496 fad->SetDebugTx(fDebugTx);
1497
1498 fBoards[i] = fad;
1499 }
1500
1501
1502 DimDescribedService fDimStartRun;
1503 DimDescribedService fDimConnection;
1504
1505 void UpdateConnectionStatus(const vector<uint8_t> &stat1, const vector<uint8_t> &stat2, bool thread)
1506 {
1507 vector<uint8_t> stat(41);
1508
1509 for (int i=0; i<40; i++)
1510 stat[i] = stat1[i]|(stat2[i]<<3);
1511
1512 stat[40] = thread;
1513
1514 fDimConnection.Update(stat);
1515 }
1516
1517public:
1518 StateMachineFAD(ostream &out=cout) :
1519 T(out, "FAD_CONTROL"), EventBuilderWrapper(*static_cast<MessageImp*>(this)), ba::io_service::work(static_cast<ba::io_service&>(*this)),
1520 fStatus1(40), fStatus2(40), fStatusC(40), fStatusT(false),
1521 fDimStartRun("FAD_CONTROL/START_RUN", "X:2", "|run[idx]:Run number of last configured run (-1 if configuration was reset or no run was yet configured)|next[idx]:Run number which will be asigned to next configuration"),
1522 fDimConnection("FAD_CONTROL/CONNECTIONS", "C:40;C:1", "")
1523 {
1524 // ba::io_service::work is a kind of keep_alive for the loop.
1525 // It prevents the io_service to go to stopped state, which
1526 // would prevent any consecutive calls to run()
1527 // or poll() to do nothing. reset() could also revoke to the
1528 // previous state but this might introduce some overhead of
1529 // deletion and creation of threads and more.
1530 ResetConfig();
1531
1532 // State names
1533 T::AddStateName(FAD::kOffline, "Disengaged",
1534 "All enabled FAD boards are disconnected and the event-builer thread is not running.");
1535
1536 T::AddStateName(FAD::kDisconnected, "Disconnected",
1537 "All enabled FAD boards are disconnected, but the event-builder thread is running.");
1538
1539 T::AddStateName(FAD::kConnecting, "Connecting",
1540 "Only some enabled FAD boards are connected.");
1541
1542 T::AddStateName(FAD::kConnected, "Connected",
1543 "All enabled FAD boards are connected..");
1544
1545 T::AddStateName(FAD::kConfiguring1, "Configuring1",
1546 "Waiting 3 seconds for all FADs to be configured before requesting configuration.");
1547
1548 T::AddStateName(FAD::kConfiguring2, "Configuring2",
1549 "Waiting until all boards returned their configuration and they are valid.");
1550
1551 T::AddStateName(FAD::kConfigured, "Configured",
1552 "The configuration of all boards was successfully cross checked. Waiting for events with a new run number to receive.");
1553
1554 T::AddStateName(FAD::kWritingData, "WritingData",
1555 "The event builder has an open file (that does not mean that new events are currently received)");
1556
1557 // FAD Commands
1558 T::AddEvent("SEND_CMD", "I:1", FAD::kConnecting, FAD::kConnected, FAD::kWritingData)
1559 (bind(&StateMachineFAD::SendCmd, this, placeholders::_1))
1560 ("Send a command to the FADs. Values between 0 and 0xffff are allowed."
1561 "|command[uint16]:Command to be transmittted.");
1562 T::AddEvent("SEND_DATA", "I:2", FAD::kConnecting, FAD::kConnected, FAD::kWritingData)
1563 (bind(&StateMachineFAD::SendCmdData, this, placeholders::_1))
1564 ("Send a command with data to the FADs. Values between 0 and 0xffff are allowed."
1565 "|command[uint16]:Command to be transmittted."
1566 "|data[uint16]:Data to be sent with the command.");
1567
1568 T::AddEvent("ENABLE_SRCLK", "B:1", FAD::kConnecting, FAD::kConnected, FAD::kWritingData)
1569 (bind(&StateMachineFAD::CmdEnable, this, placeholders::_1, FAD::kCmdSrclk))
1570 ("Set SRCLK");
1571 T::AddEvent("ENABLE_BUSY_OFF", "B:1", FAD::kConnecting, FAD::kConnected, FAD::kWritingData)
1572 (bind(&StateMachineFAD::CmdEnable, this, placeholders::_1, FAD::kCmdBusyOff))
1573 ("Set BUSY continously low");
1574 T::AddEvent("ENABLE_BUSY_ON", "B:1", FAD::kConnecting, FAD::kConnected, FAD::kWritingData)
1575 (bind(&StateMachineFAD::CmdEnable, this, placeholders::_1, FAD::kCmdBusyOn))
1576 ("Set BUSY constantly high (has priority over BUSY_OFF)");
1577 T::AddEvent("ENABLE_SCLK", "B:1", FAD::kConnecting, FAD::kConnected, FAD::kWritingData)
1578 (bind(&StateMachineFAD::CmdEnable, this, placeholders::_1, FAD::kCmdSclk))
1579 ("Set SCLK");
1580 T::AddEvent("ENABLE_DRS", "B:1", FAD::kConnecting, FAD::kConnected, FAD::kWritingData)
1581 (bind(&StateMachineFAD::CmdEnable, this, placeholders::_1, FAD::kCmdDrsEnable))
1582 ("Switch Domino wave");
1583 T::AddEvent("ENABLE_DWRITE", "B:1", FAD::kConnecting, FAD::kConnected, FAD::kWritingData)
1584 (bind(&StateMachineFAD::CmdEnable, this, placeholders::_1, FAD::kCmdDwrite))
1585 ("Set Dwrite (possibly high / always low)");
1586 T::AddEvent("ENABLE_CONTINOUS_TRIGGER", "B:1", FAD::kConnecting, FAD::kConnected, FAD::kWritingData)
1587 (bind(&StateMachineFAD::CmdEnable, this, placeholders::_1, FAD::kCmdContTrigger))
1588 ("Enable continous (internal) trigger.");
1589 T::AddEvent("ENABLE_TRIGGER_LINE", "B:1", FAD::kConnecting, FAD::kConnected, FAD::kWritingData)
1590 (bind(&StateMachineFAD::CmdEnable, this, placeholders::_1, FAD::kCmdTriggerLine))
1591 ("Incoming triggers can be accepted/will not be accepted");
1592 T::AddEvent("ENABLE_COMMAND_SOCKET_MODE", "B:1", FAD::kConnecting, FAD::kConnected, FAD::kWritingData)
1593 (bind(&StateMachineFAD::CmdEnable, this, placeholders::_1, FAD::kCmdSocket))
1594 ("Set debug mode (yes: dump events through command socket, no=dump events through other sockets)");
1595
1596 T::AddEvent("SET_TRIGGER_RATE", "I:1", FAD::kConnecting, FAD::kConnected, FAD::kWritingData)
1597 (bind(&StateMachineFAD::SetTriggerRate, this, placeholders::_1))
1598 ("Enable continous trigger");
1599 T::AddEvent("SEND_SINGLE_TRIGGER")
1600 (bind(&StateMachineFAD::Trigger, this, 1))
1601 ("Issue software triggers");
1602 T::AddEvent("SEND_N_TRIGGERS", "I", FAD::kConnecting, FAD::kConnected, FAD::kWritingData)
1603 (bind(&StateMachineFAD::SendTriggers, this, placeholders::_1))
1604 ("Issue software triggers");
1605 T::AddEvent("START_RUN", "", FAD::kConnecting, FAD::kConnected, FAD::kWritingData)
1606 (bind(&StateMachineFAD::StartRun, this, placeholders::_1, true))
1607 ("Set FAD DAQ mode. when started, no configurations must be send.");
1608 T::AddEvent("STOP_RUN", FAD::kConnecting, FAD::kConnected, FAD::kWritingData)
1609 (bind(&StateMachineFAD::StartRun, this, placeholders::_1, false))
1610 ("");
1611 T::AddEvent("PHASE_SHIFT", "S:1", FAD::kConnecting, FAD::kConnected, FAD::kWritingData)
1612 (bind(&StateMachineFAD::PhaseShift, this, placeholders::_1))
1613 ("Adjust ADC phase (in 'steps')");
1614
1615 T::AddEvent("RESET_EVENT_COUNTER", FAD::kConnecting, FAD::kConnected, FAD::kWritingData)
1616 (bind(&StateMachineFAD::Cmd, this, FAD::kCmdResetEventCounter))
1617 ("");
1618
1619 T::AddEvent("SET_RUN_NUMBER", "X:1", FAD::kConnecting, FAD::kConnected, FAD::kWritingData)
1620 (bind(&StateMachineFAD::SetRunNumber, this, placeholders::_1))
1621 ("");
1622
1623 T::AddEvent("SET_MAX_MEMORY", "S:1")
1624 (bind(&StateMachineFAD::SetMaxMemoryBuffer, this, placeholders::_1))
1625 ("Set maximum memory buffer size allowed to be consumed by the EventBuilder to buffer events."
1626 "|memory[short]:Buffer size in Mega-bytes.");
1627
1628 T::AddEvent("SET_REGISTER", "I:2", FAD::kConnecting, FAD::kConnected, FAD::kWritingData)
1629 (bind(&StateMachineFAD::SetRegister, this, placeholders::_1))
1630 ("set register to value"
1631 "|addr[short]:Address of register"
1632 "|val[short]:Value to be set");
1633
1634 // FIXME: Maybe add a mask which channels should be set?
1635 T::AddEvent("SET_REGION_OF_INTEREST", "I:2", FAD::kConnecting, FAD::kConnected, FAD::kWritingData)
1636 (bind(&StateMachineFAD::SetRoi, this, placeholders::_1))
1637 ("Set region-of-interest to value"
1638 "|channel[short]:Channel on each chip for which the ROI is set (0-8), -1 for all"
1639 "|val[short]:Value to be set");
1640
1641 // FIXME: Maybe add a mask which channels should be set?
1642 T::AddEvent("SET_DAC_VALUE", "I:2", FAD::kConnecting, FAD::kConnected, FAD::kWritingData)
1643 (bind(&StateMachineFAD::SetDac, this, placeholders::_1))
1644 ("Set DAC numbers in range to value"
1645 "|addr[short]:Address of register (-1 for all)"
1646 "|val[short]:Value to be set");
1647
1648 T::AddEvent("CONFIGURE", "X:2;C", FAD::kConnected, FAD::kConfigured, FAD::kWritingData)
1649 (bind(&StateMachineFAD::StartConfigure, this, placeholders::_1))
1650 ("");
1651
1652 T::AddEvent("RESET_CONFIGURE", FAD::kConfiguring1, FAD::kConfiguring2, FAD::kConfigured)
1653 (bind(&StateMachineFAD::ResetConfig, this))
1654 ("");
1655
1656 // Verbosity commands
1657 T::AddEvent("SET_VERBOSE", "B:1")
1658 (bind(&StateMachineFAD::SetVerbosity, this, placeholders::_1))
1659 ("Set verbosity state"
1660 "|verbosity[bool]:disable or enable verbosity for received data (yes/no), except dynamic data");
1661
1662 T::AddEvent("SET_HEX_OUTPUT", "B:1")
1663 (bind(&StateMachineFAD::SetHexOutput, this, placeholders::_1))
1664 ("Enable or disable hex output for received data"
1665 "|hexout[bool]:disable or enable hex output for received data (yes/no)");
1666
1667 T::AddEvent("SET_DATA_OUTPUT", "B:1")
1668 (bind(&StateMachineFAD::SetDataOutput, this, placeholders::_1))
1669 ("");
1670
1671 T::AddEvent("SET_DEBUG_TX", "B:1")
1672 (bind(&StateMachineFAD::SetDebugTx, this, placeholders::_1))
1673 ("Enable or disable the output of messages in case of successfull data transmission to the boards."
1674 "|debug[bool]:disable or enable debug output for transmitted data (yes/no)");
1675
1676 T::AddEvent("SET_DEBUG_EVENT_BUILDER_OUT", "B:1")
1677 (bind(&StateMachineFAD::SetDebugEb, this, placeholders::_1))
1678 ("");
1679
1680 T::AddEvent("PRINT_EVENT", "S:1")
1681 (bind(&StateMachineFAD::PrintEvent, this, placeholders::_1))
1682 ("Print (last) event"
1683 "|board[short]:slot from which the event should be printed (-1 for all)");
1684
1685 T::AddEvent("DUMP_STREAM", "B:1")
1686 (bind(&StateMachineFAD::SetDumpStream, this, placeholders::_1))
1687 ("For debugging purpose: the binary data stream read from the sockets 0-7 can be dumped to files."
1688 "|switch[bool]:Enable (yes) or disable (no)");
1689
1690 T::AddEvent("DUMP_RECV", "B:1")
1691 (bind(&StateMachineFAD::SetDumpRecv, this, placeholders::_1))
1692 ("For debugging purpose: the times when data has been receives are dumped to a file."
1693 "|switch[bool]:Enable (yes) or disable (no)");
1694
1695 T::AddEvent("BLOCK_TRANSMISSION", "S:1;B:1")
1696 (bind(&StateMachineFAD::SetBlockTransmission, this, placeholders::_1))
1697 ("Blocks the transmission of commands to the given slot. Use with care! For debugging pupose only!"
1698 "|slot[short]:Slot to which the command transmission should be blocked (0-39)"
1699 "|enable[bool]:Whether the command transmission should be blockes (yes) or allowed (no)");
1700
1701 T::AddEvent("BLOCK_TRANSMISSION_RANGE", "S:2;B:1")
1702 (bind(&StateMachineFAD::SetBlockTransmissionRange, this, placeholders::_1))
1703 ("Blocks the transmission of commands to the given range of slots. Use with care! For debugging pupose only!"
1704 "|first[short]:First slot to which the command transmission should be blocked (0-39)"
1705 "|last[short]:Last slot to which the command transmission should be blocked (0-39)"
1706 "|enable[bool]:Whether the command transmission should be blockes (yes) or allowed (no)");
1707
1708 T::AddEvent("IGNORE_EVENTS", "S:1;B:1")
1709 (bind(&StateMachineFAD::SetIgnoreSlot, this, placeholders::_1))
1710 ("Instructs the event-builder to ignore events from the given slot but still read the data from the socket."
1711 "|slot[short]:Slot from which the data should be ignored when building events"
1712 "|enable[bool]:Whether the event builder should ignore data from this slot (yes) or allowed (no)");
1713
1714 T::AddEvent("IGNORE_EVENTS_RANGE", "S:2;B:1")
1715 (bind(&StateMachineFAD::SetIgnoreSlots, this, placeholders::_1))
1716 ("Instructs the event-builder to ignore events from the given slot but still read the data from the socket."
1717 "|first[short]:First slot from which the data should be ignored when building events"
1718 "|last[short]:Last slot from which the data should be ignored when building events"
1719 "|enable[bool]:Whether the event builder should ignore data from this slot (yes) or allowed (no)");
1720
1721 T::AddEvent("CLOSE_OPEN_FILES", FAD::kDisconnected, FAD::kConnecting, FAD::kConnected, FAD::kWritingData)
1722 (bind(&StateMachineFAD::CloseOpenFiles, this))
1723 ("Close all run files opened by the EventBuilder.");
1724
1725 T::AddEvent("TEST", "S:1")
1726 (bind(&StateMachineFAD::Test, this, placeholders::_1))
1727 ("");
1728
1729
1730
1731 // Conenction commands
1732 T::AddEvent("START", FAD::kOffline)
1733 (bind(&StateMachineFAD::StartConnection, this))
1734 ("Start EventBuilder thread and connect all valid slots.");
1735
1736 T::AddEvent("STOP", FAD::kDisconnected, FAD::kConnecting, FAD::kConnected, FAD::kWritingData)
1737 (bind(&StateMachineFAD::StopConnection, this))
1738 ("Stop EventBuilder thread (still write buffered events) and disconnect all slots.");
1739
1740 T::AddEvent("ABORT", FAD::kDisconnected, FAD::kConnecting, FAD::kConnected, FAD::kWritingData)
1741 (bind(&StateMachineFAD::AbortConnection, this))
1742 ("Immediately abort EventBuilder thread and disconnect all slots.");
1743
1744 T::AddEvent("SOFT_RESET", FAD::kConnected, FAD::kWritingData)
1745 (bind(&StateMachineFAD::Reset, this, true))
1746 ("Wait for buffers to drain, close all files and reinitialize event builder thread.");
1747
1748 T::AddEvent("HARD_RESET", FAD::kConnected, FAD::kWritingData)
1749 (bind(&StateMachineFAD::Reset, this, false))
1750 ("Free all buffers, close all files and reinitialize event builder thread.");
1751
1752 T::AddEvent("CONNECT", "S:1", FAD::kDisconnected, FAD::kConnecting, FAD::kConnected)
1753 (bind(&StateMachineFAD::EnableSlot, this, placeholders::_1, true))
1754 ("Connect a disconnected slot.");
1755
1756 T::AddEvent("DISCONNECT", "S:1", FAD::kConnecting, FAD::kConnected)
1757 (bind(&StateMachineFAD::EnableSlot, this, placeholders::_1, false))
1758 ("Disconnect a connected slot.");
1759
1760 T::AddEvent("TOGGLE", "S:1", FAD::kDisconnected, FAD::kConnecting, FAD::kConnected)
1761 (bind(&StateMachineFAD::ToggleSlot, this, placeholders::_1))
1762 ("");
1763
1764 T::AddEvent("SET_FILE_FORMAT", "S:1")
1765 (bind(&StateMachineFAD::SetFileFormat, this, placeholders::_1))
1766 ("");
1767
1768 T::AddEvent("LOAD_DRS_CALIBRATION", "C")
1769 (bind(&StateMachineFAD::LoadDrsCalibration, this, placeholders::_1))
1770 ("");
1771
1772
1773 T::AddEvent("ADD_ADDRESS", "C", FAD::kOffline)
1774 (bind(&StateMachineFAD::AddAddress, this, placeholders::_1))
1775 ("Add the address of a DRS4 board to the first free slot"
1776 "|IP[string]:address in the format <address:port>");
1777 T::AddEvent("REMOVE_SLOT", "S:1", FAD::kOffline)
1778 (bind(&StateMachineFAD::RemoveSlot, this, placeholders::_1))
1779 ("Remove the Iaddress in slot n. For a list see LIST"
1780 "|slot[short]:Remove the address in slot n from the list");
1781 T::AddEvent("LIST_SLOTS")
1782 (bind(&StateMachineFAD::ListSlots, this))
1783 ("Print a list of all available board addressesa and whether they are enabled");
1784 }
1785
1786 ~StateMachineFAD()
1787 {
1788 for (BoardList::const_iterator i=fBoards.begin(); i!=fBoards.end(); i++)
1789 delete i->second;
1790 fBoards.clear();
1791 }
1792
1793 tcp::endpoint GetEndpoint(const string &base)
1794 {
1795 const size_t p0 = base.find_first_of(':');
1796 const size_t p1 = base.find_last_of(':');
1797
1798 if (p0==string::npos || p0!=p1)
1799 {
1800 T::Out() << kRed << "GetEndpoint - Wrong format ('host:port' expected)" << endl;
1801 return tcp::endpoint();
1802 }
1803
1804 tcp::resolver resolver(get_io_service());
1805
1806 boost::system::error_code ec;
1807
1808 const tcp::resolver::query query(base.substr(0, p0), base.substr(p0+1));
1809 const tcp::resolver::iterator iterator = resolver.resolve(query, ec);
1810
1811 if (ec)
1812 {
1813 T::Out() << kRed << "GetEndpoint - Couldn't resolve endpoint '" << base << "': " << ec.message();
1814 return tcp::endpoint();
1815 }
1816
1817 return *iterator;
1818 }
1819
1820 typedef map<string, FAD::Configuration> Configs;
1821 Configs fConfigs;
1822 Configs::const_iterator fTargetConfig;
1823
1824 Time fConfigTimer;
1825
1826
1827 template<class V>
1828 bool CheckConfigVal(Configuration &conf, V max, const string &name, const string &sub)
1829 {
1830 if (!conf.HasDef(name, sub))
1831 {
1832 T::Error("Neither "+name+"default nor "+name+sub+" found.");
1833 return false;
1834 }
1835
1836 const V val = conf.GetDef<V>(name, sub);
1837
1838 if (val<=max)
1839 return true;
1840
1841 ostringstream str;
1842 str << name << sub << "=" << val << " exceeds allowed maximum of " << max << "!";
1843 T::Error(str);
1844
1845 return false;
1846 }
1847
1848 int64_t fNightAsInt;
1849
1850 int EvalOptions(Configuration &conf)
1851 {
1852 // ---------- General setup ---------
1853 fIsVerbose = !conf.Get<bool>("quiet");
1854 fIsHexOutput = conf.Get<bool>("hex-out");
1855 fIsDataOutput = conf.Get<bool>("data-out");
1856 fDebugTx = conf.Get<bool>("debug-tx");
1857
1858 // ---------- Setup event builder ---------
1859 SetMaxMemory(conf.Get<unsigned int>("max-mem"));
1860
1861 fNightAsInt = InitRunNumber(conf.Get<string>("destination-folder"));
1862 if (fNightAsInt<0)
1863 return 1;
1864
1865 // ---------- Setup run types ---------
1866 const vector<string> types = conf.Vec<string>("run-type");
1867 if (types.size()==0)
1868 T::Warn("No run-types defined.");
1869 else
1870 T::Message("Defining run-types");
1871 for (vector<string>::const_iterator it=types.begin();
1872 it!=types.end(); it++)
1873 {
1874 T::Message(" -> "+ *it);
1875
1876 if (fConfigs.count(*it)>0)
1877 {
1878 T::Error("Run-type "+*it+" defined twice.");
1879 return 2;
1880 }
1881
1882 FAD::Configuration target;
1883
1884 if (!CheckConfigVal<bool>(conf, true, "enable-drs.", *it) ||
1885 !CheckConfigVal<bool>(conf, true, "enable-dwrite.", *it) ||
1886 !CheckConfigVal<bool>(conf, true, "enable-continous-trigger.", *it))
1887 return 3;
1888
1889 target.fDenable = conf.GetDef<bool>("enable-drs.", *it);
1890 target.fDwrite = conf.GetDef<bool>("enable-dwrite.", *it);
1891 target.fContinousTrigger = conf.GetDef<bool>("enable-continous-trigger.", *it);
1892
1893 target.fTriggerRate = 0;
1894 //if (target.fContinousTrigger)
1895 {
1896 if (!CheckConfigVal<uint16_t>(conf, 0xffff, "trigger-rate.", *it))
1897 return 4;
1898
1899 target.fTriggerRate = conf.GetDef<uint16_t>("trigger-rate.", *it);
1900 }
1901
1902 for (int i=0; i<FAD::kNumChannelsPerChip; i++)
1903 {
1904 ostringstream str;
1905 str << "roi-ch" << i << '.';
1906
1907 if (!CheckConfigVal<uint16_t>(conf, FAD::kMaxRoiValue, "roi.", *it) &&
1908 !CheckConfigVal<uint16_t>(conf, FAD::kMaxRoiValue, str.str(), *it))
1909 return 5;
1910
1911 target.fRoi[i] = conf.HasDef(str.str(), *it) ?
1912 conf.GetDef<uint16_t>(str.str(), *it) :
1913 conf.GetDef<uint16_t>("roi.", *it);
1914 }
1915
1916 for (int i=0; i<FAD::kNumDac; i++)
1917 {
1918 ostringstream str;
1919 str << "dac-" << i << '.';
1920
1921 if (!CheckConfigVal<uint16_t>(conf, FAD::kMaxDacValue, "dac.", *it) &&
1922 !CheckConfigVal<uint16_t>(conf, FAD::kMaxDacValue, str.str(), *it))
1923 return 6;
1924
1925 target.fDac[i] = conf.HasDef(str.str(), *it) ?
1926 conf.GetDef<uint16_t>(str.str(), *it) :
1927 conf.GetDef<uint16_t>("dac.", *it);
1928 }
1929
1930 fConfigs[*it] = target;
1931 }
1932
1933 // FIXME: Add a check about unsused configurations
1934
1935 // ---------- Setup board addresses for fake-fad ---------
1936
1937 if (conf.Has("debug-addr"))
1938 {
1939 const string addr = conf.Get<string>("debug-addr");
1940 const int num = conf.Get<unsigned int>("debug-num");
1941
1942 const tcp::endpoint endpoint = GetEndpoint(addr);
1943 if (endpoint==tcp::endpoint())
1944 return 7;
1945
1946 for (int i=0; i<num; i++)
1947 AddEndpoint(tcp::endpoint(endpoint.address(), endpoint.port()+8*i));
1948
1949 StartConnection();
1950 return -1;
1951 }
1952
1953 // ---------- Setup board addresses for the real camera ---------
1954
1955 if (conf.Has("base-addr"))
1956 {
1957 string base = conf.Get<string>("base-addr");
1958
1959 if (base=="def" || base =="default")
1960 base = "10.0.128.128:31919";
1961
1962 const tcp::endpoint endpoint = GetEndpoint(base);
1963 if (endpoint==tcp::endpoint())
1964 return 8;
1965
1966 const ba::ip::address_v4::bytes_type ip = endpoint.address().to_v4().to_bytes();
1967
1968 if (ip[2]>250 || ip[3]>244)
1969 {
1970 T::Out() << kRed << "EvalConfiguration - IP address given by --base-addr out-of-range." << endl;
1971 return 9;
1972 }
1973
1974 for (int crate=0; crate<4; crate++)
1975 for (int board=0; board<10; board++)
1976 {
1977 ba::ip::address_v4::bytes_type target = endpoint.address().to_v4().to_bytes();
1978 target[2] += crate;
1979 target[3] += board;
1980
1981 AddEndpoint(tcp::endpoint(ba::ip::address_v4(target), endpoint.port()));
1982 }
1983
1984 StartConnection();
1985 return -1;
1986
1987 }
1988
1989 // ---------- Setup board addresses one by one ---------
1990
1991 if (conf.Has("addr"))
1992 {
1993 const vector<string> addrs = conf.Get<vector<string>>("addr");
1994 for (vector<string>::const_iterator i=addrs.begin(); i<addrs.end(); i++)
1995 {
1996 const tcp::endpoint endpoint = GetEndpoint(*i);
1997 if (endpoint==tcp::endpoint())
1998 return 10;
1999
2000 AddEndpoint(endpoint);
2001 }
2002
2003 StartConnection();
2004 return -1;
2005 }
2006 return -1;
2007 }
2008
2009};
2010
2011// ------------------------------------------------------------------------
2012
2013#include "Main.h"
2014
2015template<class T, class S>
2016int RunShell(Configuration &conf)
2017{
2018 return Main::execute<T, StateMachineFAD<S>>(conf);
2019}
2020
2021void SetupConfiguration(Configuration &conf)
2022{
2023 po::options_description control("FAD control options");
2024 control.add_options()
2025 ("quiet,q", po_bool(), "Disable printing contents of all received messages in clear text.")
2026 ("hex-out", po_bool(), "Enable printing contents of all printed messages also as hex data.")
2027 ("data-out", po_bool(), "Enable printing received event data.")
2028 ("debug-tx", po_bool(), "Enable debugging of ethernet transmission.")
2029 ;
2030
2031 po::options_description connect("FAD connection options");
2032 connect.add_options()
2033 ("addr", vars<string>(), "Network address of FAD")
2034 ("base-addr", var<string>(), "Base address of all FAD")
2035 ("debug-num,n", var<unsigned int>(40), "Sets the number of fake boards to be connected locally")
2036 ("debug-addr", var<string>(), "")
2037 ;
2038
2039 po::options_description builder("Event builder options");
2040 builder.add_options()
2041 ("max-mem,m", var<unsigned int>(100), "Maximum memory the event builder thread is allowed to consume for its event buffer")
2042 ("destination-folder", var<string>(""), "Destination folder (base folder) for the event builder binary data files.")
2043 ;
2044
2045 po::options_description runtype("Run type configuration");
2046 runtype.add_options()
2047 ("run-type", vars<string>(), "Run type, e.g. data, pedestal, drs-calibration, light-pulser")
2048 ("enable-dwrite.*", var<bool>(), "")
2049 ("enable-drs.*", var<bool>(), "")
2050 ("enable-continous-trigger.*", var<bool>(), "")
2051 ("trigger-rate.*", var<uint16_t>(), "")
2052 ("dac.*", var<uint16_t>(), "")
2053 ("dac-0.*", var<uint16_t>(), "")
2054 ("dac-1.*", var<uint16_t>(), "")
2055 ("dac-2.*", var<uint16_t>(), "")
2056 ("dac-3.*", var<uint16_t>(), "")
2057 ("dac-4.*", var<uint16_t>(), "")
2058 ("dac-5.*", var<uint16_t>(), "")
2059 ("dac-6.*", var<uint16_t>(), "")
2060 ("dac-7.*", var<uint16_t>(), "")
2061 ("roi.*", var<uint16_t>(), "")
2062 ("roi-ch0.*", var<uint16_t>(), "")
2063 ("roi-ch1.*", var<uint16_t>(), "")
2064 ("roi-ch2.*", var<uint16_t>(), "")
2065 ("roi-ch3.*", var<uint16_t>(), "")
2066 ("roi-ch4.*", var<uint16_t>(), "")
2067 ("roi-ch5.*", var<uint16_t>(), "")
2068 ("roi-ch6.*", var<uint16_t>(), "")
2069 ("roi-ch7.*", var<uint16_t>(), "")
2070 ("roi-ch8.*", var<uint16_t>(), "")
2071 ;
2072
2073 conf.AddEnv("dns", "DIM_DNS_NODE");
2074 conf.AddEnv("host", "DIM_HOST_NODE");
2075
2076 conf.AddOptions(control);
2077 conf.AddOptions(connect);
2078 conf.AddOptions(builder);
2079 conf.AddOptions(runtype);
2080}
2081
2082void PrintUsage()
2083{
2084 cout <<
2085 "The fadctrl controls the FAD boards.\n"
2086 "\n"
2087 "The default is that the program is started without user intercation. "
2088 "All actions are supposed to arrive as DimCommands. Using the -c "
2089 "option, a local shell can be initialized. With h or help a short "
2090 "help message about the usuage can be brought to the screen.\n"
2091 "\n"
2092 "Usage: fadctrl [-c type] [OPTIONS]\n"
2093 " or: fadctrl [OPTIONS]\n";
2094 cout << endl;
2095}
2096
2097void PrintHelp()
2098{
2099 Main::PrintHelp<StateMachineFAD<StateMachine>>();
2100
2101 /* Additional help text which is printed after the configuration
2102 options goes here */
2103}
2104
2105int main(int argc, const char* argv[])
2106{
2107 Configuration conf(argv[0]);
2108 conf.SetPrintUsage(PrintUsage);
2109 Main::SetupConfiguration(conf);
2110 SetupConfiguration(conf);
2111
2112 if (!conf.DoParse(argc, argv, PrintHelp))
2113 return -1;
2114
2115// try
2116 {
2117 // No console access at all
2118 if (!conf.Has("console"))
2119 {
2120// if (conf.Get<bool>("no-dim"))
2121// return RunShell<LocalStream, StateMachine>(conf);
2122// else
2123 return RunShell<LocalStream, StateMachineDim>(conf);
2124 }
2125 // Cosole access w/ and w/o Dim
2126/* if (conf.Get<bool>("no-dim"))
2127 {
2128 if (conf.Get<int>("console")==0)
2129 return RunShell<LocalShell, StateMachine>(conf);
2130 else
2131 return RunShell<LocalConsole, StateMachine>(conf);
2132 }
2133 else
2134*/ {
2135 if (conf.Get<int>("console")==0)
2136 return RunShell<LocalShell, StateMachineDim>(conf);
2137 else
2138 return RunShell<LocalConsole, StateMachineDim>(conf);
2139 }
2140 }
2141/* catch (std::exception& e)
2142 {
2143 cerr << "Exception: " << e.what() << endl;
2144 return -1;
2145 }*/
2146
2147 return 0;
2148}
Note: See TracBrowser for help on using the repository browser.