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

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