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

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