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

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