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

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