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

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