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

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