source: trunk/FACT++/scripts/Main.js@ 15358

Last change on this file since 15358 was 15354, checked in by tbretz, 12 years ago
improved the handling of fad losses; removed AGILENT_CONTROL temporarily from the list of required servers; added checks for datalogger subscriptions; tried to add a setup which allows taking simple calibration data at day time.
File size: 39.8 KB
Line 
1/**
2 * @fileOverview This file has functions related to documenting JavaScript.
3 * @author <a href="mailto:thomas.bretz@epfl.ch">Thomas Bretz</a>
4 */
5'use strict';
6
7dim.log("Start: "+__FILE__+" ["+__DATE__+"]");
8
9// This should be set in dimctrl.rc as JavaScript.schedule-database.
10// It is sent together with the script to the dimserver.
11// If started directly, it has to be set after the command:
12//
13// .js scripts/Main.js schedule-database=...
14//
15if (!$['schedule-database'])
16 throw new Error("Environment 'schedule-database' not set!");
17
18//dimctrl.defineState(37, "TimeOutBeforeTakingData", "MCP took more than 5minutes to start TakingData");
19
20// ================================================================
21// Code related to the schedule
22// ================================================================
23
24//this is just the class implementation of 'Observation'
25include('scripts/Observation_class.js');
26
27/*
28// this file just contains the definition of
29// the variable observations, which builds our nightly schedule, hence the filename
30include('scripts/schedule.js');
31
32// make Observation objects from user input and check if 'date' is increasing.
33for (var i=0; i<observations.length; i++)
34{
35 observations[i] = new Observation(observations[i]);
36
37 // check if the start date given by the user is increasing.
38 if (i>0 && observations[i].start <= observations[i-1].start)
39 {
40 throw new Error("Start time '"+ observations[i].start.toUTCString()+
41 "' in row "+i+" exceeds start time in row "+(i-1));
42 }
43}
44*/
45
46include('scripts/getSchedule.js');
47
48var observations = [ ];
49
50// Get the observation scheduled for 'now' from the table and
51// return its index
52function getObservation(now)
53{
54 if (now==undefined)
55 now = new Date();
56
57 if (isNaN(now.valueOf()))
58 throw new Error("Date argument in getObservation invalid.");
59
60 observations = getSchedule();
61
62 for (var i=0; i<observations.length; i++)
63 if (now<observations[i].start)
64 return i-1;
65
66 return observations.length-1;
67}
68
69// ================================================================
70// Code to check whether observation is allowed
71// ================================================================
72/*
73function currentEst(source)
74{
75 var moon = new Moon();
76 if (!moon.isUp)
77 return 7.7;
78
79 var dist = Sky.dist(moon, source);
80
81 var alt = 90-moon.toLocal().zd;
82
83 var lc = dist*alt*pow(Moon.disk(), 6)/360/360;
84
85 var cur = 7.7+4942*lc;
86
87 return cur;
88}
89
90function thresholdEst(source) // relative threshold (ratio)
91{
92 // Assumption:
93 // atmosphere is 70km, shower taks place after 60km, earth radius 6400km
94 // just using the cosine law
95 // This fits very well with MC results: See Roger Firpo, p.45
96 // "Study of the MAGIC telescope sensitivity for Large Zenith Angle observations"
97
98 var c = Math.cos(Math.Pi-source.zd);
99 var ratio = (10*sqrt(409600*c*c+9009) + 6400*c - 60)/10;
100
101 // assumption: Energy threshold increases linearily with current
102 // assumption: Energy threshold increases linearily with distance
103
104 return ratio*currentEst(source)/7.7;
105}
106*/
107
108// ----------------------------------------------------------------
109
110// ================================================================
111// Code related to monitoring the fad system
112// ================================================================
113
114var sub_incomplete = new Subscription("FAD_CONTROL/INCOMPLETE");
115
116var incomplete = 0;
117
118sub_incomplete.onchange = function(evt)
119{
120 if (!evt.data)
121 return;
122
123 var inc = evt.obj['incomplete'];
124 if (!inc || inc>0xffffffffff)
125 return;
126
127 if (incomplete>0)
128 return;
129
130 if (dim.state("MCP").name!="TakingData")
131 return;
132
133 incomplete = inc;
134
135 console.out("Sending MCP/STOP");
136 dim.send("MCP/STOP");
137}
138
139var sub_connections = new Subscription("FAD_CONTROL/CONNECTIONS");
140
141/**
142 * call-back function of FAD_CONTROL/CONNECTIONS
143 * store IDs of problematic FADs
144 *
145 */
146/*
147sub_connections.onchange = function(evt)
148{
149 // This happens, but why?
150 if (!evt.obj['status'])
151 return;
152
153 this.reset = [ ];
154
155 for (var x=0; x<40; x++)
156 if (evt.obj['status'][x]!=66 && evt.obj['status'][x]!=67)
157 this.reset.push(x);
158
159 if (this.reset.length==0)
160 return;
161
162 //m.alarm("FAD board loss detected...");
163 dim.send("MCP/RESET");
164 dim.send("FAD_CONTROL/CLOSE_OPEN_FILES");
165}
166*/
167
168/**
169 * reconnect to problematic FADs
170 *
171 * Dis- and Reconnects to FADs, found to be problematic by call-back function
172 * onchange() to have a different CONNECTION value than 66 or 67.
173 *
174 * @returns
175 * a boolean is returned.
176 * reconnect returns true if:
177 * * nothing needed to be reset --> no problems found by onchange()
178 * * the reconnection went fine.
179 *
180 * reconnect *never returns false* so far.
181 *
182 * @example
183 * if (!sub_connections.reconnect())
184 * exit();
185 */
186sub_connections.reconnect = function()
187{
188 // this.reset is a list containing the IDs of FADs,
189 // which have neither CONNECTION==66 nor ==67, whatever this means :-)
190 if (this.reset.length==0)
191 return true;
192
193 console.out(" Reconnect: start ["+this.reset.length+"]");
194
195 for (var i=0; i<this.reset.length; i++)
196 dim.send("FAD_CONTROL/DISCONNECT", this.reset[i]);
197
198 v8.sleep(3000);
199
200 while (this.reset.length)
201 dim.send("FAD_CONTROL/CONNECT", this.reset.pop());
202
203 v8.sleep(1000);
204 dim.wait("FAD_CONTROL", "Connected", 3000);
205
206 console.out(" Reconnect: end");
207
208 return true;
209}
210
211// ================================================================
212// Code related to taking data
213// ================================================================
214
215var startrun = new Subscription("FAD_CONTROL/START_RUN");
216startrun.get(5000);
217
218function reconnect(list, txt)
219{ /*
220 var reset = [ ];
221
222 for (var i=0; i<list.length; i++)
223 {
224 console.out(" FAD %2d".$(list[i])+" lost during "+txt);
225 reset.push(parseInt(list[i]/10));
226 }
227
228 reset = reset.filter(function(elem,pos){return reset.indexOf(elem)==pos;});
229
230 console.out("");
231 console.out(" FADs belong to crate(s): "+reset);
232 console.out("");
233*/
234 console.out("");
235 console.out("Trying automatic reconnect ["+txt+"]...");
236
237 for (var i=0; i<list.length; i++)
238 {
239 console.out(" ...disconnect "+list[i]);
240 dim.send("FAD_CONTROL/DISCONNECT", list[i]);
241 }
242
243 console.out(" ...waiting for 5s");
244 v8.sleep(5000);
245
246 for (var i=0; i<list.length; i++)
247 {
248 console.out(" ...reconnect "+list[i]);
249 dim.send("FAD_CONTROL/CONNECT", list[i]);
250 }
251
252 console.out(" ...waiting for 1s");
253 v8.sleep(1000);
254 console.out("");
255}
256
257function takeRun(type, count, time)
258{
259 if (!count)
260 count = -1;
261 if (!time)
262 time = -1;
263
264 var nextrun = startrun.get().obj['next'];
265 console.out(" Take run %3d".$(nextrun)+": N="+count+" T="+time+"s ["+type+"]");
266
267 incomplete = 0;
268 dim.send("MCP/START", time?time:-1, count?count:-1, type);
269
270 // FIXME: Replace by callback?
271 //
272 // DN: I believe instead of waiting for 'TakingData' one could split this
273 // up into two checks with an extra condition:
274 // if type == 'data':
275 // wait until ThresholdCalibration starts:
276 // --> this time should be pretty identical for each run
277 // if this takes longer than say 3s:
278 // there might be a problem with one/more FADs
279 //
280 // wait until "TakingData":
281 // --> this seems to take even some minutes sometimes...
282 // (might be optimized rather soon, but still in the moment...)
283 // if this takes way too long:
284 // there might be something broken,
285 // so maybe a very high time limit is ok here.
286 // I think there is not much that can go wrong,
287 // when the Thr-Calib has already started. Still it might be nice
288 // If in the future RateControl is written so to find out that
289 // in case the threshold finding algorithm does
290 // *not converge as usual*
291 // it can complain, and in this way give a hint, that the weather
292 // might be a little bit too bad.
293 // else:
294 // wait until "TakingData":
295 // --> in a non-data run this time should be pretty short again
296 // if this takes longer than say 3s:
297 // there might be a problem with one/more FADs
298 //
299
300 // Use this if you use the rate control to calibrate by rates
301 //if (!dim.wait("MCP", "TakingData", -300000) )
302 //{
303 // throw new Error("MCP took longer than 5 minutes to start TakingData"+
304 // "maybe this idicates a problem with one of the FADs?");
305 //}
306
307 // Here we could check and handle fad losses
308
309 try
310 {
311 dim.wait("MCP", "TakingData", 15000);
312 }
313 catch (e)
314 {
315 console.out("");
316 console.out("MCP: "+dim.state("MCP").name);
317 console.out("FAD_CONTROL: "+dim.state("FAD_CONTROL").name);
318 console.out("FTM_CONTROL: "+dim.state("FTM_CONTROL").name);
319 console.out("");
320
321 if (dim.state("MCP").name!="Configuring3" ||
322 dim.state("FAD_CONTROL").name!="Configuring2")
323 throw e;
324
325 console.out("");
326 console.out("Waiting for fadctrl to get configured timed out... checking for in-run FAD loss.");
327
328 var con = sub_connections.get();
329 var stat = con.obj['status'];
330
331 console.out("Sending MCP/RESET");
332 dim.send("MCP/RESET");
333
334 dim.wait("FTM_CONTROL", "Idle", 3000);
335 dim.wait("FAD_CONTROL", "Connected", 3000);
336 dim.wait("MCP", "Idle", 3000);
337
338 /*** FOR REMOVE ***/
339 var reset = [ ];
340
341 for (var i=0; i<40; i++)
342 if (stat[i]!=0x43)
343 {
344 console.out(" FAD %2d".$(i)+" not in Configured state.");
345 reset.push(parseInt(i/10));
346 }
347
348 reset = reset.filter(function(elem,pos){return reset.indexOf(elem)==pos;});
349
350 if (reset.length>0)
351 {
352 console.out("");
353 console.out(" FADs belong to crate(s): "+reset);
354 console.out("");
355 }
356 /**** FOR REMOVE ****/
357
358 var list = [];
359 for (var i=0; i<40; i++)
360 if (stat[i]!=0x43)
361 list.push(i);
362
363 reconnect(list, "configuration");
364
365 throw e;
366 }
367
368 dim.wait("MCP", "Idle", time>0 ? time*1250 : undefined); // run time plus 25%
369
370 if (incomplete)
371 {
372 console.out("Incomplete: "+incomplete);
373
374 console.out("");
375 console.out("MCP: "+dim.state("MCP").name);
376 console.out("FAD_CONTROL: "+dim.state("FAD_CONTROL").name);
377 console.out("FTM_CONTROL: "+dim.state("FTM_CONTROL").name);
378 console.out("");
379
380 dim.wait("MCP", "Idle", 3000);
381 dim.wait("FTM_CONTROL", "Idle", 3000);
382
383 // Necessary to allow the disconnect, reconnect
384 dim.send("FAD_CONTROL/CLOSE_OPEN_FILES");
385 dim.wait("FAD_CONTROL", "Connected", 3000);
386
387 var list = [];
388 for (var i=0; i<40; i++)
389 if (incomplete&(1<<i))
390 list.push(i);
391
392 reconnect(list, "data taking");
393
394 throw new Error("In-run FAD loss detected.");
395 }
396
397 //console.out(" Take run: end");
398
399 // DN: currently reconnect() never returns false
400 // .. but it can fail of course.
401 //if (!sub_connections.reconnect())
402 // exit();
403
404 return true;//sub_connections.reconnect();
405}
406
407// ----------------------------------------------------------------
408
409function doDrsCalibration(where)
410{
411 console.out(" Take DRS calibration ["+where+"]");
412
413 service_feedback.voltageOff();
414
415 var tm = new Date();
416
417 while (1)
418 {
419 dim.send("FAD_CONTROL/START_DRS_CALIBRATION");
420 if (!takeRun("drs-pedestal", 1000)) // 40 / 20s (50Hz)
421 continue;
422
423 // Does that fix the runopen before runclose problem?
424 //dim.wait("FAD_CONTROL", "Connected", 3000);
425 //v8.sleep(1000);
426
427 if (!takeRun("drs-gain", 1000)) // 40 / 20s (50Hz)
428 continue;
429
430 // Does that fix the runopen before runclose problem?
431 //dim.wait("FAD_CONTROL", "Connected", 3000);
432 //v8.sleep(1000);
433
434 if (!takeRun("drs-pedestal", 1000)) // 40 / 20s (50Hz)
435 continue;
436
437 dim.send("FAD_CONTROL/SET_FILE_FORMAT", 2);
438 if (!takeRun("drs-pedestal", 1000)) // 40 / 20s (50Hz)
439 continue;
440 if (!takeRun("drs-time", 1000)) // 40 / 20s (50Hz)
441 continue;
442
443 dim.send("FAD_CONTROL/RESET_SECONDARY_DRS_BASELINE");
444 if (!takeRun("pedestal", 1000)) // 40 / 10s (80Hz)
445 continue;
446
447 dim.send("FAD_CONTROL/SET_FILE_FORMAT", 2);
448 if (!takeRun("pedestal", 1000)) // 40 / 10s (80Hz)
449 continue;
450 // -----------
451 // 4'40 / 2'00
452
453 break;
454 }
455
456 console.out(" DRS calibration done [%.1f]".$((new Date()-tm)/1000));
457}
458
459// ================================================================
460// Code related to the lid
461// ================================================================
462
463function OpenLid()
464{
465 /*
466 while (Sun.horizon(-13).isUp)
467 {
468 var now = new Date();
469 var minutes_until_sunset = (Sun.horizon(-13).set - now)/60000;
470 console.out(now.toUTCString()+": Sun above FACT-horizon, lid cannot be opened: sleeping 1min, remaining %.1fmin".$(minutes_until_sunset));
471 v8.sleep(60000);
472 }*/
473
474 var isClosed = dim.state("LID_CONTROL").name=="Closed";
475
476 var tm = new Date();
477
478 // Wait for lid to be open
479 if (isClosed)
480 {
481 console.out(" Open lid: start");
482 dim.send("LID_CONTROL/OPEN");
483 }
484 dim.wait("LID_CONTROL", "Open", 30000);
485
486 if (isClosed)
487 console.out(" Open lid: done [%.1fs]".$((new Date()-tm)/1000));
488}
489
490function CloseLid()
491{
492 var isOpen = dim.state("LID_CONTROL").name=="Open";
493
494 var tm = new Date();
495
496 // Wait for lid to be open
497 if (isOpen)
498 {
499 console.out(" Close lid: start");
500 dim.send("LID_CONTROL/CLOSE");
501 }
502 dim.wait("LID_CONTROL", "Closed", 30000);
503
504 if (isOpen)
505 console.out(" Close lid: end [%.1fs]".$((new Date()-tm)/1000));
506}
507
508// ================================================================
509// Code related to switching bias voltage on and off
510// ================================================================
511
512var service_feedback = new Subscription("FEEDBACK/DEVIATION");
513
514service_feedback.onchange = function(evt)
515{
516 if (this.cnt && evt.counter>this.cnt+12)
517 return;
518
519 this.voltageStep = null;
520 if (!evt.data)
521 return;
522
523 var delta = evt.obj['DeltaBias'];
524
525 var avg = 0;
526 for (var i=0; i<320; i++)
527 avg += delta[i];
528 avg /= 320;
529
530 if (this.previous)
531 this.voltageStep = Math.abs(avg-this.previous);
532
533 this.previous = avg;
534
535 console.out(" DeltaV="+this.voltageStep);
536}
537
538// DN: Why is voltageOff() implemented as
539// a method of a Subscription to a specific Service
540// I naively would think of voltageOff() as an unbound function.
541// I seems to me it has to be a method of a Subscription object, in order
542// to use the update counting method. But does it have to be
543// a Subscription to FEEDBACK/DEVIATION, or could it work with other services as well?
544service_feedback.voltageOff = function()
545{
546 var state = dim.state("BIAS_CONTROL").name;
547
548 // check of feedback has to be switched on
549 var isOn = state=="VoltageOn" || state=="Ramping";
550 if (isOn)
551 {
552 console.out(" Voltage off: start");
553
554 // Supress the possibility that the bias control is
555 // ramping and will reject the command to switch the
556 // voltage off
557 var isControl = dim.state("FEEDBACK").name=="CurrentControl";
558 if (isControl)
559 {
560 console.out(" Suspending feedback.");
561 dim.send("FEEDBACK/ENABLE_OUTPUT", false);
562 dim.wait("FEEDBACK", "CurrentCtrlIdle", 3000);
563 }
564
565 // Switch voltage off
566 console.out(" Voltage on: switch off");
567 dim.send("BIAS_CONTROL/SET_ZERO_VOLTAGE");
568
569 // If the feedback was enabled, re-enable it
570 if (isControl)
571 {
572 console.out(" Resuming feedback.");
573 dim.send("FEEDBACK/ENABLE_OUTPUT", true);
574 dim.wait("FEEDBACK", "CurrentControl", 3000);
575 }
576 }
577
578 dim.wait("BIAS_CONTROL", "VoltageOff", 5000);
579
580 // FEEDBACK stays in CurrentCtrl when Voltage is off but output enabled
581 // dim.wait("FEEDBACK", "CurrentCtrlIdle", 1000);
582
583 if (isOn)
584 console.out(" Voltage off: end");
585}
586
587// DN: The name of the method voltageOn() in the context of the method
588// voltageOff() is a little bit misleading, since when voltageOff() returns
589// the caller can be sure the voltage is off, but when voltageOn() return
590// this is not the case, in the sense, that the caller can now take data.
591// instead the caller of voltageOn() *must* call waitForVoltageOn() afterwards
592// in order to safely take good-quality data.
593// This could lead to nasty bugs in the sense, that the second call might
594// be forgotten by somebody
595//
596// so I suggest to rename voltageOn() --> prepareVoltageOn()
597// waitForVoltageOn() stays as it is
598// and one creates a third method called:voltageOn() like this
599/* service_feedback.voltageOn = function()
600 * {
601 * this.prepareVoltageOn();
602 * this.waitForVoltageOn();
603 * }
604 *
605 * */
606// For convenience.
607
608service_feedback.voltageOn = function()
609{
610 //if (Sun.horizon("FACT").isUp)
611 // throw new Error("Sun is above FACT-horizon, voltage cannot be switched on.");
612
613 var isOff = dim.state("BIAS_CONTROL").name=="VoltageOff";
614 if (isOff)
615 {
616 console.out(" Voltage on: switch on");
617 //console.out(JSON.stringify(dim.state("BIAS_CONTROL")));
618
619 dim.send("BIAS_CONTROL/SET_GLOBAL_DAC", 1);
620 }
621
622 // Wait until voltage on
623 dim.wait("BIAS_CONTROL", "VoltageOn", 5000);
624
625 // From now on the feedback waits for a valid report from the FSC
626 // and than switchs to CurrentControl
627 dim.wait("FEEDBACK", "CurrentControl", 60000);
628
629 if (isOff)
630 {
631 console.out(" Voltage on: cnt="+this.cnt);
632
633 this.previous = undefined;
634 this.cnt = this.get().counter;
635 this.voltageStep = undefined;
636 }
637}
638
639service_feedback.waitForVoltageOn = function()
640{
641 // waiting 45sec for the current control to stabilize...
642 // v8.sleep(45000);
643
644 // ----- Wait for at least three updates -----
645 // The feedback is started as if the camera where at 0deg
646 // Then after the first temp update, the temperature will be set to the
647 // correct value (this has already happened)
648 // So we only have to wait for the current to get stable.
649 // This should happen after three to five current updates.
650 // So we want one recent temperature update
651 // and three recent current updates
652
653 // Avoid output if condition is already fulfilled
654 if (this.cnt && this.get().counter>this.cnt+10)
655 return;
656
657 // FIXME: timeout missing
658 console.out(" Feedback wait: start");
659
660 function func(service)
661 {
662 if ((service.cnt!=undefined && service.get().counter>service.cnt+10) ||
663 (service.voltageStep && service.voltageStep<0.02))
664 return true;
665 }
666
667 var now = new Date();
668 //v8.timeout(5*60000, func, this);
669 while ((this.cnt==undefined || this.get().counter<=this.cnt+10) && (!this.voltageStep || this.voltageStep>0.02))
670 v8.sleep();
671
672 console.out(" Feedback wait: end [dV=%.3f, cnt=%d, %.2fs]".$(this.voltageStep, this.get().counter, (new Date()-now)/1000));
673}
674
675// ================================================================
676// Function to shutdown the system
677// ================================================================
678
679function Shutdown()
680{
681 console.out("Shutdown: start");
682
683 service_feedback.voltageOff();
684 CloseLid();
685 dim.send("DRIVE_CONTROL/PARK");
686
687 console.out("Waiting for telescope to park. This may take a while.");
688
689 // FIXME: This might not work is the drive is already close to park position
690 dim.wait("DRIVE_CONTROL", "Locked", 3000);
691
692 var sub = new Subscription("DRIVE_CONTROL/POINTING_POSITION");
693 sub.get(5000); // FIXME: Proper error message in case of failure
694
695 function func()
696 {
697 var report = sub.get();
698
699 var zd = report.obj['Zd'];
700 var az = report.obj['Az'];
701
702 if (zd>100 && Math.abs(az)<1)
703 return true;
704
705 return undefined;
706 }
707
708 var now = new Date();
709 v8.timeout(150000, func);
710
711 //dim.send("FEEDBACK/STOP");
712 dim.send("FEEDBACK/ENABLE_OUTPUT", false);
713 dim.send("FTM_CONTROL/STOP_TRIGGER");
714
715 dim.wait("FEEDBACK", "CurrentCtrlIdle", 3000);
716 dim.wait("FTM_CONTROL", "Idle", 3000);
717
718 var report = sub.get();
719
720 console.out("");
721 console.out("Shutdown procedure seems to be finished...");
722 console.out(" Telescope at Zd=%.1fdeg Az=%.1fdeg".$(report.obj['Zd'], report.obj['Az']));
723 console.out(" Please make sure the park position was reached");
724 console.out(" and the telescope is not moving anymore.");
725 console.out(" Please check that the lid is closed and the voltage switched off.");
726 console.out("");
727 console.out("Shutdown: end ["+(new Date()-now)/1000+"s]");
728
729 sub.close();
730}
731
732// ================================================================
733// Check datalogger subscriptions
734// ================================================================
735
736var datalogger_subscriptions = new Subscription("DATA_LOGGER/SUBSCRIPTIONS");
737datalogger_subscriptions.get(3000, false);
738
739datalogger_subscriptions.check = function()
740{
741 var obj = this.get();
742 if (!obj.data)
743 throw new Error("DATA_LOGGER/SUBSCRIPTIONS not available.");
744
745 var expected =
746 [
747 "BIAS_CONTROL/CURRENT",
748 "BIAS_CONTROL/DAC",
749 "BIAS_CONTROL/NOMINAL",
750 "BIAS_CONTROL/VOLTAGE",
751 "DRIVE_CONTROL/POINTING_POSITION",
752 "DRIVE_CONTROL/SOURCE_POSITION",
753 "DRIVE_CONTROL/STATUS",
754 "DRIVE_CONTROL/TRACKING_POSITION",
755 "FAD_CONTROL/CONNECTIONS",
756 "FAD_CONTROL/DAC",
757 "FAD_CONTROL/DNA",
758 "FAD_CONTROL/DRS_RUNS",
759 "FAD_CONTROL/EVENTS",
760 "FAD_CONTROL/FEEDBACK_DATA",
761 "FAD_CONTROL/FILE_FORMAT",
762 "FAD_CONTROL/FIRMWARE_VERSION",
763 "FAD_CONTROL/INCOMPLETE",
764 "FAD_CONTROL/PRESCALER",
765 "FAD_CONTROL/REFERENCE_CLOCK",
766 "FAD_CONTROL/REGION_OF_INTEREST",
767 "FAD_CONTROL/RUNS",
768 "FAD_CONTROL/RUN_NUMBER",
769 "FAD_CONTROL/START_RUN",
770 "FAD_CONTROL/STATISTICS1",
771 "FAD_CONTROL/STATISTICS2",
772 "FAD_CONTROL/STATS",
773 "FAD_CONTROL/STATUS",
774 "FAD_CONTROL/TEMPERATURE",
775 "FEEDBACK/CALIBRATED_CURRENTS",
776 "FEEDBACK/CALIBRATION",
777 "FEEDBACK/DEVIATION",
778 "FEEDBACK/REFERENCE",
779 "FSC_CONTROL/CURRENT",
780 "FSC_CONTROL/HUMIDITY",
781 "FSC_CONTROL/TEMPERATURE",
782 "FSC_CONTROL/VOLTAGE",
783 "FTM_CONTROL/COUNTER",
784 "FTM_CONTROL/DYNAMIC_DATA",
785 "FTM_CONTROL/ERROR",
786 "FTM_CONTROL/FTU_LIST",
787 "FTM_CONTROL/PASSPORT",
788 "FTM_CONTROL/STATIC_DATA",
789 "FTM_CONTROL/TRIGGER_RATES",
790 "LID_CONTROL/DATA",
791 "MAGIC_LIDAR/DATA",
792 "MAGIC_WEATHER/DATA",
793 "MCP/CONFIGURATION",
794 "PWR_CONTROL/DATA",
795 "RATE_CONTROL/THRESHOLD",
796 "RATE_SCAN/DATA",
797 "RATE_SCAN/PROCESS_DATA",
798 "TEMPERATURE/DATA",
799 "TIME_CHECK/OFFSET",
800 "TNG_WEATHER/DATA",
801 "TNG_WEATHER/DUST",
802 ];
803
804 function map(entry)
805 {
806 if (entry.length==0)
807 return undefined;
808
809 var rc = entry.split(',');
810 if (rc.length!=2)
811 throw new Error("Subscription list entry '"+entry+"' has wrong number of elements.");
812 return rc;
813 }
814
815 var list = obj.data.split('\n').map(map);
816
817 function check(name)
818 {
819 if (list.every(function(el){return el[0]!=name;}))
820 throw new Error("Subscription to '"+name+"' not available.");
821 }
822
823 expected.forEach(check);
824}
825
826
827
828// ================================================================
829// Crosscheck all states
830// ================================================================
831
832// ----------------------------------------------------------------
833// Do a standard startup to bring the system in into a well
834// defined state
835// ----------------------------------------------------------------
836include('scripts/Startup.js');
837
838// ----------------------------------------------------------------
839// Check that everything we need is availabel to receive commands
840// (FIXME: Should that go to the general CheckState?)
841// ----------------------------------------------------------------
842console.out("Checking send.");
843checkSend(["MCP", "DRIVE_CONTROL", "LID_CONTROL", "FAD_CONTROL", "FEEDBACK"]);
844console.out("Checking send: done");
845
846// ----------------------------------------------------------------
847// Bring feedback into the correct operational state
848// ----------------------------------------------------------------
849console.out("Feedback init: start.");
850service_feedback.get(5000);
851
852dim.send("FEEDBACK/ENABLE_OUTPUT", true);
853dim.send("FEEDBACK/START_CURRENT_CONTROL", 0.);
854
855v8.timeout(3000, function() { var n = dim.state("FEEDBACK").name; if (n=="CurrentCtrlIdle" || n=="CurrentControl") return true; });
856
857// ----------------------------------------------------------------
858// Connect to the DRS_RUNS service
859// ----------------------------------------------------------------
860console.out("Drs runs init: start.");
861
862var sub_drsruns = new Subscription("FAD_CONTROL/DRS_RUNS");
863sub_drsruns.get(5000);
864// FIXME: Check if the last DRS calibration was complete?
865
866function getTimeSinceLastDrsCalib()
867{
868 // ----- Time since last DRS Calibration [min] ------
869 var runs = sub_drsruns.get(0);
870 var diff = (new Date()-runs.time)/60000;
871
872 // Warning: 'roi=300' is a number which is not intrisically fixed
873 // but can change depending on the taste of the observers
874 var valid = runs.obj['run'][2]>0 && runs.obj['roi']==300;
875
876 if (valid)
877 console.out(" Last DRS calib: %.1fmin ago".$(diff));
878 else
879 console.out(" No valid drs calibration available");
880
881 return valid ? diff : null;
882}
883
884// ----------------------------------------------------------------
885// Make sure we will write files
886// ----------------------------------------------------------------
887dim.send("FAD_CONTROL/SET_FILE_FORMAT", 2);
888
889// ----------------------------------------------------------------
890// Print some information for the user about the
891// expected first oberservation
892// ----------------------------------------------------------------
893var test = getObservation();
894if (test!=undefined)
895{
896 var n = new Date();
897 if (test==-1)
898 console.out(n.toUTCString()+": First observation scheduled for "+observations[0].start.toUTCString());
899 if (test>=0 && test<observations.length)
900 console.out(n.toUTCString()+": First observation should start immediately.");
901 if (observations[0].start>n+12*3600*1000)
902 console.out(n.toUTCString()+": No observations scheduled for the next 12 hours!");
903}
904
905// ----------------------------------------------------------------
906// Start main loop
907// ----------------------------------------------------------------
908console.out("Start main loop.");
909
910var run = -2; // getObservation never called
911var sub;
912var lastId;
913var sun = Sun.horizon(-13);
914var system_on; // undefined
915
916while (1)
917{
918 // Check if observation position is still valid
919 // If source position has changed, set run=0
920 var idxObs = getObservation();
921 if (idxObs===undefined)
922 break;
923
924 // we are still waiting for the first observation in the schedule
925 if (idxObs==-1)
926 {
927 // flag that the first observation will be in the future
928 run = -1;
929 v8.sleep(1000);
930 continue;
931 }
932
933 // Check if we have to take action do to sun-rise
934 var was_up = sun.isUp;
935 sun = Sun.horizon(-13);
936 if (!was_up && sun.isUp)
937 {
938 console.out("", "Sun rise detected.... automatic shutdown initiated!");
939 // FIXME: State check?
940 Shutdown();
941 system_on = false;
942 continue;
943 }
944
945 // Current and next observation target
946 var obs = observations[idxObs];
947 var nextObs = observations[idxObs+1];
948
949 // Check if observation target has changed
950 if (lastId!=obs.id) // !Object.isEqual(obs, nextObs)
951 {
952 console.out("--- "+obs.id+" ---");
953 console.out("Current time: "+new Date().toUTCString());
954 console.out("Current observation: "+obs.start.toUTCString());
955 if (nextObs!=undefined)
956 console.out("Next observation: "+nextObs.start.toUTCString());
957 console.out("");
958
959 // This is the first source, but we do not come from
960 // a scheduled 'START', so we have to check if the
961 // telescop is operational already
962 sub = 0;
963 if (run<0)
964 {
965 //Startup(); // -> Bias On/Off?, Lid open/closed?
966 //CloseLid();
967 }
968
969 // The first observation had a start-time in the past...
970 // In this particular case start with the last entry
971 // in the list of measurements
972 if (run==-2)
973 sub = obs.length-1;
974
975 run = 0;
976 }
977 lastId = obs.id;
978
979 if (nextObs==undefined && obs[obs.length-1].task!="SHUTDOWN")
980 throw Error("Last scheduled measurement must be a shutdown.");
981
982 // We are done with all measurement slots for this
983 // observation... wait for next observation
984 if (sub>=obs.length)
985 {
986 v8.sleep(1000);
987 continue;
988 }
989
990 if (system_on===false && task!="STARTUP")
991 {
992 v8.sleep(1000);
993 continue;
994 }
995
996 // Check if sun is still up... only DATA and RATESCAN must be suppressed
997 if ((obs[sub].task=="DATA" || obs[sub].task=="RATESCAN") && sun.isUp)
998 {
999 var now = new Date();
1000 var remaining = (sun.set - now)/60000;
1001 console.out(now.toUTCString()+" - "+obs[sub].task+": Sun above FACT-horizon: sleeping 1min, remaining %.1fmin".$(remaining));
1002 v8.sleep(60000);
1003 continue;
1004 }
1005
1006 console.out("\n"+(new Date()).toUTCString()+": Current measurement: "+obs[sub]);
1007
1008 var power_states = sun.isUp || system_on===false ? [ "DriveOff" ] : [ "SystemOn" ];
1009 var drive_states = sun.isUp || system_on===false ? undefined : [ "Armed", "Tracking", "OnTrack" ];
1010
1011 // A scheduled task was found, lets check if all servers are
1012 // still only and in reasonable states. If this is not the case,
1013 // something unexpected must have happend and the script is aborted.
1014 //console.out(" Checking states [general]");
1015 var table =
1016 [
1017 [ "TNG_WEATHER" ],
1018 [ "MAGIC_WEATHER" ],
1019 [ "CHAT" ],
1020 [ "SMART_FACT" ],
1021 [ "TEMPERATURE" ],
1022 [ "DATA_LOGGER", [ "NightlyFileOpen", "WaitForRun", "Logging" ] ],
1023 [ "FSC_CONTROL", [ "Connected" ] ],
1024 [ "MCP", [ "Idle" ] ],
1025 [ "TIME_CHECK", [ "Valid" ] ],
1026 [ "PWR_CONTROL", power_states/*[ "SystemOn" ]*/ ],
1027// [ "AGILENT_CONTROL", [ "VoltageOn" ] ],
1028 [ "BIAS_CONTROL", [ "VoltageOff", "VoltageOn", "Ramping" ] ],
1029 [ "FEEDBACK", [ "CurrentControl", "CurrentCtrlIdle" ] ],
1030 [ "LID_CONTROL", [ "Open", "Closed" ] ],
1031 [ "DRIVE_CONTROL", drive_states/*[ "Armed", "Tracking", "OnTrack" ]*/ ],
1032 [ "FTM_CONTROL", [ "Idle", "TriggerOn" ] ],
1033 [ "FAD_CONTROL", [ "Connected", "WritingData" ] ],
1034 [ "RATE_SCAN", [ "Connected" ] ],
1035 [ "RATE_CONTROL", [ "Connected", "GlobalThresholdSet", "InProgress" ] ],
1036 ];
1037
1038
1039 if (!checkStates(table))
1040 {
1041 throw new Error("Something unexpected has happened. One of the servers"+
1042 "is in a state in which it should not be. Please,"+
1043 "try to find out what happened...");
1044 }
1045
1046 datalogger_subscriptions.check();
1047
1048 // Check if obs.task is one of the one-time-tasks
1049 switch (obs[sub].task)
1050 {
1051 case "STARTUP":
1052 console.out(" STARTUP", "");
1053 CloseLid();
1054
1055 doDrsCalibration("startup"); // will switch the voltage off
1056
1057 service_feedback.voltageOn();
1058 service_feedback.waitForVoltageOn();
1059
1060 // Before we can switch to 3000 we have to make the right DRS calibration
1061 console.out(" Take single p.e. run.");
1062 while (!takeRun("pedestal", 5000));
1063
1064 // It is unclear what comes next, so we better switch off the voltage
1065 service_feedback.voltageOff();
1066 system_on = true;
1067 break;
1068
1069 case "SHUTDOWN":
1070 console.out(" SHUTDOWN", "");
1071 Shutdown();
1072 system_on = false;
1073
1074 // FIXME: Avoid new observations after a shutdown until
1075 // the next startup (set run back to -2?)
1076 console.out(" Waiting for next startup.", "");
1077 sub++;
1078 continue;
1079
1080 case "IDLE":
1081 v8.sleep(1000);
1082 continue;
1083
1084 case "DRSCALIB":
1085 console.out(" DRSCALIB", "");
1086 doDrsCalibration("drscalib"); // will switch the voltage off
1087 break;
1088
1089 case "SINGLEPE":
1090 console.out(" SINGLE-PE", "");
1091
1092 // The lid must be closes
1093 CloseLid();
1094
1095 // Check if DRS calibration is necessary
1096 var diff = getTimeSinceLastDrsCalib();
1097 if (diff>30 || diff==null)
1098 doDrsCalibration("singlepe"); // will turn voltage off
1099
1100 // The voltage must be on
1101 service_feedback.voltageOn();
1102 service_feedback.waitForVoltageOn();
1103
1104 // Before we can switch to 3000 we have to make the right DRS calibration
1105 console.out(" Take single p.e. run.");
1106 while (!takeRun("pedestal", 5000));
1107
1108 // It is unclear what comes next, so we better switch off the voltage
1109 service_feedback.voltageOff();
1110 break;
1111
1112 case "RATESCAN":
1113 console.out(" RATESCAN", "");
1114
1115 var tm1 = new Date();
1116
1117 // This is a workaround to make sure that we really catch
1118 // the new state and not the old one
1119 dim.send("DRIVE_CONTROL/STOP");
1120 dim.wait("DRIVE_CONTROL", "Armed", 5000);
1121
1122 // The lid must be open
1123 OpenLid();
1124
1125 // The voltage must be switched on
1126 service_feedback.voltageOn();
1127
1128 if (obs.source != undefined)
1129 dim.send("DRIVE_CONTROL/TRACK_ON", obs[sub].source);
1130 else
1131 dim.send("DRIVE_CONTROL/TRACK", obs[sub].ra, obs[sub].dec);
1132
1133 dim.wait("DRIVE_CONTROL", "OnTrack", 150000); // 110s for turning and 30s for stabilizing
1134
1135 service_feedback.waitForVoltageOn();
1136
1137 var tm2 = new Date();
1138
1139 // Start rate scan
1140 dim.send("RATE_SCAN/START_THRESHOLD_SCAN", 50, 1000, -10);
1141
1142 // Lets wait if the ratescan really starts... this might take a few
1143 // seconds because RATE_SCAN configures the ftm and is waiting for
1144 // it to be configured.
1145 dim.wait("RATE_SCAN", "InProgress", 10000);
1146 dim.wait("RATE_SCAN", "Connected", 2700000);
1147
1148 // this line is actually some kind of hack.
1149 // after the Ratescan, no data is written to disk. I don't know why, but it happens all the time
1150 // So I decided to put this line here as a kind of patchwork....
1151 //dim.send("FAD_CONTROL/SET_FILE_FORMAT", 2);
1152
1153 console.out(" Ratescan done [%.1fs, %.1fs]".$((tm2-tm1)/1000, (new Date()-tm2)/1000));
1154 break; // case "RATESCAN"
1155
1156 case "DATA":
1157
1158 // ========================== case "DATA" ============================
1159 /*
1160 if (Sun.horizon("FACT").isUp)
1161 {
1162 console.out(" SHUTDOWN","");
1163 Shutdown();
1164 console.out(" Exit forced due to broken schedule", "");
1165 exit();
1166 }
1167 */
1168 // Calculate remaining time for this observation in minutes
1169 var remaining = nextObs==undefined ? 0 : (nextObs.start-new Date())/60000;
1170
1171 // ------------------------------------------------------------
1172
1173 console.out(" Run #"+run+" (remaining "+parseInt(remaining)+"min)");
1174
1175 // ----- Time since last DRS Calibration [min] ------
1176 var diff = getTimeSinceLastDrsCalib();
1177
1178 // Changine pointing position and take calibration...
1179 // ...every four runs (every ~20min)
1180 // ...if at least ten minutes of observation time are left
1181 // ...if this is the first run on the source
1182 var point = (run%4==0 && remaining>10) || run==0;
1183
1184 // Take DRS Calib...
1185 // ...every four runs (every ~20min)
1186 // ...at last every two hours
1187 // ...when DRS temperature has changed by more than 2deg (?)
1188 // ...when more than 15min of observation are left
1189 // ...no drs calibration was done yet
1190 var drscal = (run%4==0 && (remaining>15 && diff>70)) || diff==null;
1191
1192 if (point)
1193 {
1194 // Change wobble position every four runs,
1195 // start with alternating wobble positions each day
1196 var wobble = (parseInt(run/4) + parseInt(new Date()/1000/3600/24-0.5))%2+1;
1197
1198 //console.out(" Move telescope to '"+source+"' "+offset+" "+wobble);
1199 console.out(" Move telescope to '"+obs[sub].source+"' ["+wobble+"]");
1200
1201 //var offset = observations[obs][2];
1202 //var wobble = observations[obs][3 + parseInt(run/4)%2];
1203
1204 //dim.send("DRIVE_CONTROL/TRACK_SOURCE", offset, wobble, source);
1205
1206 dim.send("DRIVE_CONTROL/TRACK_WOBBLE", wobble, obs[sub].source);
1207
1208 // Do we have to check if the telescope is really moving?
1209 // We can cross-check the SOURCE service later
1210 }
1211
1212 if (drscal)
1213 doDrsCalibration("data"); // will turn voltage off
1214
1215 OpenLid();
1216
1217 // voltage must be switched on after the lid is open for the
1218 // feedback to adapt the voltage properly to the night-sky
1219 // background light level.
1220 service_feedback.voltageOn();
1221
1222 // This is now th right time to wait for th drive to be stable
1223 dim.wait("DRIVE_CONTROL", "OnTrack", 150000); // 110s for turning and 30s for stabilizing
1224
1225 // Now we have to be prepared for data-taking:
1226 // make sure voltage is on
1227 service_feedback.waitForVoltageOn();
1228
1229 // If pointing had changed, do calibration
1230 if (point)
1231 {
1232 console.out(" Calibration.");
1233
1234 // Calibration (2% of 20')
1235 while (1)
1236 {
1237 if (!takeRun("pedestal", 1000)) // 80 Hz -> 10s
1238 continue;
1239 if (!takeRun("light-pulser-ext", 1000)) // 80 Hz -> 10s
1240 continue;
1241 break;
1242 }
1243 }
1244
1245 console.out(" Taking data: start [5min]");
1246
1247 var len = 300;
1248 while (len>0)
1249 {
1250 var time = new Date();
1251 if (takeRun("data", -1, len)) // Take data (5min)
1252 break;
1253
1254 len -= parseInt((new Date()-time)/1000);
1255 }
1256
1257 console.out(" Taking data: done");
1258 run++;
1259
1260 continue; // case "DATA"
1261 }
1262
1263 if (nextObs!=undefined && sub==obs.length-1)
1264 console.out(" Waiting for next observation scheduled for "+nextObs.start.toUTCString(),"");
1265
1266 sub++;
1267}
1268
1269sub_drsruns.close();
1270
1271// ================================================================
1272// Comments and ToDo goes here
1273// ================================================================
1274
1275// error handline : http://www.sitepoint.com/exceptional-exception-handling-in-javascript/
1276// classes: http://www.phpied.com/3-ways-to-define-a-javascript-class/
1277//
1278// Arguments: TakeFirstDrsCalib
1279// To be determined: How to stop the script without foreceful interruption?
Note: See TracBrowser for help on using the repository browser.