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

Last change on this file since 19512 was 19452, checked in by tbretz, 6 years ago
This implements changes which are required for follow-up observations. Note that up to date these are untested and will be rolled out and debugged in La Palam in the next days.
File size: 55.9 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 if (observations.length==0)
42 return -1;
43
44 var suspended = -1;
45
46 var rc = observations.length-1;
47
48 for (var i=0; i<observations.length; i++)
49 {
50 // Find the first observation which is in the future
51 if (observations[i].start>now)
52 {
53 rc = i-1;
54 break;
55 }
56
57 // If the loop just passed a suspend, i.e. it is in the past, set the suspend flag
58 if (observations[i][0].task=="SUSPEND")
59 suspended = i;
60
61 // If the loop just passed a resume, i.e. it is in the past, remove the suspend flag
62 if (observations[i][0].task=="RESUME")
63 suspended = -1;
64 }
65
66 // Now rc contains the index of the first observation in the past
67
68 // If the system is in suspend mode, the suspend observation is
69 // returned as recent measurement. For convenience (to avoid that
70 // the next observation is announced), all future observations
71 // are removed.
72 if (suspended>=0)
73 {
74 observations.splice(suspended+1);
75 return suspended;
76 }
77
78 // Observations have already been resumed and the last scheduled
79 // observation is the resume itself: remove the resume and
80 // all leading suspend/resume pairs until the last observation
81 // is found
82 while (rc>=0 && observations[rc][0].task=="RESUME")
83 {
84 observations.splice(rc--, 1);
85
86 // Find previous suspend
87 if (rc>=0 && observations[rc][0].task=="SUSPEND")
88 observations.splice(rc--, 1);
89 }
90
91 return rc;
92}
93
94// ================================================================
95// Code to check whether observation is allowed
96// ================================================================
97/*
98function currentEst(source)
99{
100 var moon = new Moon();
101 if (!moon.isUp)
102 return 7.7;
103
104 var dist = Sky.dist(moon, source);
105
106 var alt = 90-moon.toLocal().zd;
107
108 var lc = dist*alt*pow(Moon.disk(), 6)/360/360;
109
110 var cur = 7.7+4942*lc;
111
112 return cur;
113}
114
115function thresholdEst(source) // relative threshold (ratio)
116{
117 // Assumption:
118 // atmosphere is 70km, shower taks place after 60km, earth radius 6400km
119 // just using the cosine law
120 // This fits very well with MC results: See Roger Firpo, p.45
121 // "Study of the MAGIC telescope sensitivity for Large Zenith Angle observations"
122
123 var c = Math.cos(Math.Pi-source.zd);
124 var ratio = (10*sqrt(409600*c*c+9009) + 6400*c - 60)/10;
125
126 // assumption: Energy threshold increases linearily with current
127 // assumption: Energy threshold increases linearily with distance
128
129 return ratio*currentEst(source)/7.7;
130}
131*/
132
133// ================================================================
134// Code to perform the DRS calib sequence
135// ================================================================
136
137var irq;
138
139function doDrsCalibration(where)
140{
141 dim.log("Starting DRS calibration ["+where+"]");
142
143 service_feedback.voltageOff();
144
145 var tm = new Date();
146
147 while (!irq)
148 {
149 dim.send("FAD_CONTROL/START_DRS_CALIBRATION");
150 if (irq || !takeRun("drs-pedestal", 1000)) // 40 / 20s (50Hz)
151 continue;
152
153 if (irq || !takeRun("drs-gain", 1000)) // 40 / 20s (50Hz)
154 continue;
155
156 if (where!="data")
157 {
158 if (irq || !takeRun("drs-pedestal", 1000)) // 40 / 20s (50Hz)
159 continue;
160 }
161
162 break;
163 }
164
165 if (where!="data")
166 {
167 dim.send("FAD_CONTROL/SET_FILE_FORMAT", 6);
168
169 while (!irq && !takeRun("drs-pedestal", 1000)); // 40 / 20s (50Hz)
170 while (!irq && !takeRun("drs-time", 1000)); // 40 / 20s (50Hz)
171 }
172
173 while (!irq)
174 {
175 dim.send("FAD_CONTROL/RESET_SECONDARY_DRS_BASELINE");
176 if (takeRun("pedestal", 1000)) // 40 / 10s (80Hz)
177 break;
178 }
179
180 dim.send("FAD_CONTROL/SET_FILE_FORMAT", 6);
181
182 while (!irq && !takeRun("pedestal", 1000)); // 40 / 10s (80Hz)
183 // -----------
184 // 4'40 / 2'00
185
186 if (irq)
187 dim.log("DRS calibration interrupted [%.1fs]".$((new Date()-tm)/1000));
188 else
189 dim.log("DRS calibration done [%.1fs]".$((new Date()-tm)/1000));
190}
191
192// ================================================================
193// Code related to the lid
194// ================================================================
195
196function OpenLid(fast)
197{
198 /*
199 while (Sun.horizon(-13).isUp)
200 {
201 var now = new Date();
202 var minutes_until_sunset = (Sun.horizon(-13).set - now)/60000;
203 console.out(now.toUTCString()+": Sun above FACT-horizon, lid cannot be opened: sleeping 1min, remaining %.1fmin".$(minutes_until_sunset));
204 v8.sleep(60000);
205 }*/
206
207 var isClosed = dim.state("LID_CONTROL").name=="Closed";
208 var isInconsistent = dim.state("LID_CONTROL").name=="Inconsistent";
209
210 var tm = new Date();
211
212 // Wait for lid to be open
213 if (isClosed || isInconsistent)
214 {
215 dim.log("Opening lid");
216 dim.send("LID_CONTROL/OPEN");
217
218 dim.log("Turning off IR camera LEDs...");
219
220 var cam = new Curl("fact@cam/cgi-bin/user/Config.cgi");
221 cam.data.push("action=set");
222 cam.data.push("Camera.System.Title=Camera1");
223 cam.data.push("Camera.General.IRControl.Value=2");
224 cam.data.push("Camera.System.Display=ALL");
225 cam.data.push("Camera.Environment=OUTDOOR");
226 var ret = cam.send();
227 dim.log("Camera response: "+ret.data.replace(/\n/g,"/")+" ["+ret.rc+"]");
228 }
229
230 if (!fast)
231 return;
232
233 dim.wait("LID_CONTROL", "Open", 30000);
234
235 if (isClosed || isInconsistent)
236 dim.log("Lid open [%.1fs]".$((new Date()-tm)/1000));
237}
238
239function CloseLid()
240{
241 var isOpen = dim.state("LID_CONTROL").name=="Open";
242
243 var tm = new Date();
244
245 // Wait for lid to be open
246 if (isOpen)
247 {
248 if (dim.state("FTM_CONTROL").name=="TriggerOn")
249 {
250 dim.send("FTM_CONTROL/STOP_TRIGGER");
251 dim.wait("FTM_CONTROL", "Valid", 3000);
252 }
253
254 dim.log("Closing lid.");
255 dim.send("LID_CONTROL/CLOSE");
256 }
257 v8.timeout(30000, function() { if (dim.state("LID_CONTROL").name=="Closed" || dim.state("LID_CONTROL").name=="Inconsistent") return true; });
258 //dim.wait("LID_CONTROL", "Closed", 30000);
259 //dim.wait("LID_CONTROL", "Inconsistent", 30000);
260
261 if (isOpen)
262 dim.log("Lid closed [%.1fs]".$((new Date()-tm)/1000));
263}
264
265// ================================================================
266// Interrupt data taking in case of high currents
267// ================================================================
268dim.onchange['FEEDBACK'] = function(state)
269{
270 if ((state.name=="Critical" || state.name=="OnStandby") &&
271 (this.prev!="Critical" && this.prev!="OnStandby"))
272 {
273 console.out("Feedback state changed from "+this.prev+" to "+state.name+" [Main.js]");
274 irq = "RESCHEDULE";
275 }
276 this.prev=state.name;
277}
278
279// ================================================================
280// Code related to switching bias voltage on and off
281// ================================================================
282
283var service_feedback = new Subscription("FEEDBACK/CALIBRATED_CURRENTS");
284
285service_feedback.onchange = function(evt)
286{
287 if (!evt.data)
288 return;
289
290 if (this.ok==undefined)
291 return;
292
293 var Unom = evt.obj['U_nom'];
294 var Uov = evt.obj['U_ov'];
295 if (!Uov)
296 return;
297
298 var cnt = 0;
299 var avg = 0;
300 for (var i=0; i<320; i++)
301 {
302 // This is a fix for the channel with a shortcut
303 if (i==272)
304 continue;
305
306 var dU = Uov[i]-Unom;
307
308 // 0.022 corresponds to 1 DAC count (90V/4096)
309 if (Math.abs(dU)>0.033)
310 cnt++;
311
312 avg += dU;
313 }
314 avg /= 320;
315
316 this.ok = cnt<3;// || (this.last!=undefined && Math.abs(this.last-avg)<0.002);
317
318 console.out(" DeltaUov=%.3f (%.3f) [N(>0.033V)=%d]".$(avg, avg-this.last, cnt));
319
320 this.last = avg;
321}
322
323service_feedback.voltageOff = function()
324{
325 var state = dim.state("BIAS_CONTROL").name;
326
327 if (state=="Disconnected")
328 {
329 console.out(" Voltage off: bias crate disconnected!");
330 return;
331 }
332
333 // check of feedback has to be switched on
334 var isOn = state=="VoltageOn" || state=="Ramping";
335 if (isOn)
336 {
337 dim.log("Switching voltage off.");
338
339 if (dim.state("FTM_CONTROL").name=="TriggerOn")
340 {
341 dim.send("FTM_CONTROL/STOP_TRIGGER");
342 dim.wait("FTM_CONTROL", "Valid", 3000);
343 }
344
345 // Supress the possibility that the bias control is
346 // ramping and will reject the command to switch the
347 // voltage off
348 //dim.send("FEEDBACK/STOP");
349 //dim.wait("FEEDBACK", "Calibrated", 3000);
350
351 // Make sure we are not in Ramping anymore
352 //dim.wait("BIAS_CONTROL", "VoltageOn", 3000);
353
354 // Switch voltage off
355 dim.send("BIAS_CONTROL/SET_ZERO_VOLTAGE");
356 }
357
358 dim.wait("BIAS_CONTROL", "VoltageOff", 60000); // FIXME: 30000?
359 dim.wait("FEEDBACK", "Calibrated", 3000);
360
361 // FEEDBACK stays in CurrentCtrl when Voltage is off but output enabled
362 // dim.wait("FEEDBACK", "CurrentCtrlIdle", 1000);
363
364 if (isOn)
365 dim.log("Voltage off.");
366}
367
368// DN: The name of the method voltageOn() in the context of the method
369// voltageOff() is a little bit misleading, since when voltageOff() returns
370// the caller can be sure the voltage is off, but when voltageOn() return
371// this is not the case, in the sense, that the caller can now take data.
372// instead the caller of voltageOn() *must* call waitForVoltageOn() afterwards
373// in order to safely take good-quality data.
374// This could lead to nasty bugs in the sense, that the second call might
375// be forgotten by somebody
376//
377// so I suggest to rename voltageOn() --> prepareVoltageOn()
378// waitForVoltageOn() stays as it is
379// and one creates a third method called:voltageOn() like this
380/* service_feedback.voltageOn = function()
381 * {
382 * this.prepareVoltageOn();
383 * this.waitForVoltageOn();
384 * }
385 *
386 * */
387// For convenience.
388
389service_feedback.voltageOn = function(ov)
390{
391 if (isNaN(ov))
392 ov = 1.1;
393
394 if (this.ov!=ov && dim.state("FEEDBACK").name=="InProgress") // FIXME: Warning, OnStandby, Critical if (ov<this.ov)
395 {
396 dim.log("Stoping feedback.");
397 if (dim.state("FTM_CONTROL").name=="TriggerOn")
398 {
399 dim.send("FTM_CONTROL/STOP_TRIGGER");
400 dim.wait("FTM_CONTROL", "Valid", 3000);
401 }
402
403 dim.send("FEEDBACK/STOP");
404 dim.wait("FEEDBACK", "Calibrated", 3000);
405
406 // Make sure we are not in Ramping anymore
407 dim.wait("BIAS_CONTROL", "VoltageOn", 3000);
408 }
409
410 var isOff = dim.state("FEEDBACK").name=="Calibrated";
411 if (isOff)
412 {
413 dim.log("Switching voltage to Uov="+ov+"V.");
414
415 dim.send("FEEDBACK/START", ov);
416
417 // FIXME: We could miss "InProgress" if it immediately changes to "Warning"
418 // Maybe a dim.timeout state>8 ?
419 dim.wait("FEEDBACK", "InProgress", 45000);
420
421 this.ov = ov;
422 }
423
424 // Wait until voltage on
425 dim.wait("BIAS_CONTROL", "VoltageOn", 60000); // FIXME: 30000?
426}
427
428service_feedback.waitForVoltageOn = function()
429{
430 // Avoid output if condition is already fulfilled
431 dim.log("Waiting for voltage to be stable.");
432
433 function func()
434 {
435 if (irq || this.ok==true)
436 return true;
437 }
438
439 var now = new Date();
440
441 this.last = undefined;
442 this.ok = false;
443 v8.timeout(4*60000, func, this); // FIMXE: Remove 4!
444 this.ok = undefined;
445
446 if (irq)
447 dim.log("Waiting for stable voltage interrupted.");
448 else
449 dim.log("Voltage stable within limits");
450}
451
452// ================================================================
453// Function to shutdown the system
454// ================================================================
455
456function Shutdown(type)
457{
458 if (!type)
459 type = "default";
460
461 dim.log("Starting shutdown ["+type+"].");
462
463 var now1 = new Date();
464
465 var bias = dim.state("BIAS_CONTROL").name;
466 if (bias=="VoltageOn" || bias=="Ramping")
467 service_feedback.voltageOn(0);
468
469 CloseLid();
470
471 var now2 = new Date();
472
473 dim.send("DRIVE_CONTROL/PARK");
474
475 console.out("","Waiting for telescope to park. This may take a while.");
476
477 // FIXME: This might not work is the drive is already close to park position
478 //dim.wait("DRIVE_CONTROL", "Parking", 3000);
479
480 /*
481 // Check if DRS calibration is necessary
482 var diff = getTimeSinceLastDrsCalib();
483 if (diff>30 || diff==null)
484 {
485 doDrsCalibration("singlepe"); // will turn voltage off
486 if (irq)
487 break;
488 }*/
489
490 //take single pe run if required
491 if (type=="singlepe")
492 {
493 dim.log("Taking single-pe run.");
494
495 // The voltage must be on
496 service_feedback.voltageOn();
497 service_feedback.waitForVoltageOn();
498
499 // Before we can switch to 3000 we have to make the right DRS calibration
500 dim.log("Taking single p.e. run.");
501 while (!irq && !takeRun("single-pe", 10000));
502
503 /*
504 Maybe we need to send a trigger... but data runs contain pedestal triggers... so it should work in any case...
505 var customRun = function()
506 {
507 v8.sleep(500);//wait that configuration is set
508 dim.wait("FTM_CONTROL", "TriggerOn", 15000);
509 dim.send("FAD_CONTROL/SEND_SINGLE_TRIGGER");
510 dim.send("RATE_CONTROL/STOP");
511 dim.send("FTM_CONTROL/STOP_TRIGGER");
512 dim.wait("FTM_CONTROL", "Valid", 3000);
513 dim.send("FTM_CONTROL/ENABLE_TRIGGER", true);
514 dim.send("FTM_CONTROL/SET_TIME_MARKER_DELAY", 123);
515 dim.send("FTM_CONTROL/SET_THRESHOLD", -1, obs[sub].threshold);
516 v8.sleep(500);//wait that configuration is set
517 dim.send("FTM_CONTROL/START_TRIGGER");
518 dim.wait("FTM_CONTROL", "TriggerOn", 15000);
519 }*/
520 }
521
522 //wait until drive is in locked (after it reached park position)
523 dim.wait("DRIVE_CONTROL", "Locked", 150000);
524
525 //unlock drive if task was sleep
526 if (type=="unlock")
527 dim.send("DRIVE_CONTROL/UNLOCK");
528
529
530 // It is unclear what comes next, so we better switch off the voltage
531 service_feedback.voltageOff();
532
533 dim.log("Finishing shutdown.");
534
535 var now3 = new Date();
536
537 dim.send("FTM_CONTROL/STOP_TRIGGER");
538 dim.wait("FTM_CONTROL", "Valid", 3000);
539
540 if (bias!="Disconnected")
541 dim.wait("FEEDBACK", "Calibrated", 3000);
542
543 if (type!="unlock")
544 {
545 dim.send("BIAS_CONTROL/DISCONNECT");
546
547 var pwrctrl_state = dim.state("PWR_CONTROL").name;
548 if (pwrctrl_state=="SystemOn" ||
549 pwrctrl_state=="BiasOff" ||
550 pwrctrl_state=="DriveOn")
551 dim.send("PWR_CONTROL/TOGGLE_DRIVE");
552
553 dim.wait("BIAS_CONTROL", "Disconnected", 3000);
554 dim.wait("PWR_CONTROL", "DriveOff", 6000);
555 }
556
557 var sub = new Subscription("DRIVE_CONTROL/POINTING_POSITION");
558 sub.get(5000); // FIXME: Proper error message in case of failure
559
560 var report = sub.get();
561
562 console.out("");
563 console.out("Shutdown procedure ["+type+"] seems to be finished...");
564 console.out(" "+new Date().toUTCString());
565 console.out(" Telescope at Zd=%.1fdeg Az=%.1fdeg".$(report.obj['Zd'], report.obj['Az']));
566 console.out(" Please check on the web cam that the park position was reached");
567 console.out(" and the telescope is not moving anymore.");
568 console.out(" Please check visually that the lid is really closed and");
569 console.out(" that the biasctrl really switched the voltage off.", "");
570 console.out(" DRIVE_CONTROL: "+dim.state("DRIVE_CONTROL").name);
571 console.out(" FEEDBACK: "+dim.state("FEEDBACK").name);
572 console.out(" FTM_CONTROL: "+dim.state("FTM_CONTROL").name);
573 console.out(" BIAS_CONTROL: "+dim.state("BIAS_CONTROL").name);
574 console.out(" PWR_CONTROL: "+dim.state("PWR_CONTROL").name);
575 console.out("");
576 dim.log("Shutdown: end ["+(now2-now1)/1000+"s, "+(now3-now2)/1000+"s, "+(new Date()-now3)/1000+"s]");
577 console.out("");
578
579 sub.close();
580}
581
582
583// ================================================================
584// Function to set the system to sleep-mode
585// ================================================================
586// FIXME: do not repeat code from shutdown-function
587/*
588function GoToSleep()
589{
590 CloseLid();
591
592 var isArmed = dim.state("DRIVE_CONTROL").name=="Armed";
593 if (!isArmed)
594 {
595 dim.log("Drive not ready to move. -> send STOP");
596 dim.send("DRIVE_CONTROL/STOP");
597 dim.wait("DRIVE_CONTROL", "Armed", 5000);
598 }
599
600 dim.send("DRIVE_CONTROL/MOVE_TO 101 0");//park position
601 var sub = new Subscription("DRIVE_CONTROL/POINTING_POSITION");
602 sub.get(5000); // FIXME: Proper error message in case of failure
603
604 function func()
605 {
606 var report = sub.get();
607
608 var zd = report.obj['Zd'];
609 var az = report.obj['Az'];
610
611 if (zd>100 && Math.abs(az)<1)
612 return true;
613
614 return undefined;
615 }
616
617 try { v8.timeout(150000, func); }
618 catch (e)
619 {
620 var p = sub.get();
621 dim.log('Park position not reached? Telescope at Zd='+p.obj['Zd']+' Az='+p.obj['Az']);
622 }
623 var p2 = sub.get();
624 dim.log('Telescope at Zd=%.1fdeg Az=%.1fdeg'.$(p2.obj['Zd'], p2.obj['Az']));
625 sub.close();
626}
627*/
628
629// ================================================================
630// Check datalogger subscriptions
631// ================================================================
632
633var datalogger_subscriptions = new Subscription("DATA_LOGGER/SUBSCRIPTIONS");
634datalogger_subscriptions.get(3000, false);
635
636datalogger_subscriptions.check = function()
637{
638 var obj = this.get();
639 if (!obj.data)
640 throw new Error("DATA_LOGGER/SUBSCRIPTIONS not available.");
641
642 var expected =
643 [
644 "AGILENT_CONTROL_24V/DATA",
645 "AGILENT_CONTROL_50V/DATA",
646 "AGILENT_CONTROL_80V/DATA",
647 "BIAS_CONTROL/CURRENT",
648 "BIAS_CONTROL/DAC",
649 "BIAS_CONTROL/NOMINAL",
650 "BIAS_CONTROL/VOLTAGE",
651 "DRIVE_CONTROL/POINTING_POSITION",
652 "DRIVE_CONTROL/SOURCE_POSITION",
653 "DRIVE_CONTROL/STATUS",
654 "DRIVE_CONTROL/TRACKING_POSITION",
655 "FAD_CONTROL/CONNECTIONS",
656 "FAD_CONTROL/DAC",
657 "FAD_CONTROL/DNA",
658 "FAD_CONTROL/DRS_RUNS",
659 "FAD_CONTROL/EVENTS",
660 "FAD_CONTROL/FEEDBACK_DATA",
661 "FAD_CONTROL/FILE_FORMAT",
662 "FAD_CONTROL/FIRMWARE_VERSION",
663 "FAD_CONTROL/INCOMPLETE",
664 "FAD_CONTROL/PRESCALER",
665 "FAD_CONTROL/REFERENCE_CLOCK",
666 "FAD_CONTROL/REGION_OF_INTEREST",
667 "FAD_CONTROL/RUNS",
668 "FAD_CONTROL/RUN_NUMBER",
669 "FAD_CONTROL/START_RUN",
670 "FAD_CONTROL/STATISTICS1",
671 "FAD_CONTROL/STATS",
672 "FAD_CONTROL/STATUS",
673 "FAD_CONTROL/TEMPERATURE",
674 "FEEDBACK/CALIBRATED_CURRENTS",
675 "FEEDBACK/CALIBRATION",
676 "FEEDBACK/CALIBRATION_R8",
677 "FEEDBACK/CALIBRATION_STEPS",
678/* "FEEDBACK/REFERENCE",*/
679 "FSC_CONTROL/CURRENT",
680 "FSC_CONTROL/HUMIDITY",
681 "FSC_CONTROL/TEMPERATURE",
682 "FSC_CONTROL/VOLTAGE",
683 "FTM_CONTROL/COUNTER",
684 "FTM_CONTROL/DYNAMIC_DATA",
685 "FTM_CONTROL/ERROR",
686 "FTM_CONTROL/FTU_LIST",
687 "FTM_CONTROL/PASSPORT",
688 "FTM_CONTROL/STATIC_DATA",
689 "FTM_CONTROL/TRIGGER_RATES",
690 "GPS_CONTROL/NEMA",
691 "SQM_CONTROL/DATA",
692 //"LID_CONTROL/DATA",
693 "LID_CONTROL/MOTORS",
694 "MAGIC_LIDAR/DATA",
695 "MAGIC_WEATHER/DATA",
696 "RAIN_SENSOR/DATA",
697 "MCP/CONFIGURATION",
698 "PWR_CONTROL/DATA",
699 "RATE_CONTROL/THRESHOLD",
700 "RATE_SCAN/DATA",
701 "RATE_SCAN/PROCESS_DATA",
702 "TEMPERATURE/DATA",
703 "TIME_CHECK/OFFSET",
704 "TNG_WEATHER/DATA",
705 "TNG_WEATHER/DUST",
706 "PFMINI_CONTROL/DATA",
707 "BIAS_TEMP/DATA",
708 ];
709
710 function map(entry)
711 {
712 if (entry.length==0)
713 return undefined;
714
715 var rc = entry.split(',');
716 if (rc.length!=2)
717 throw new Error("Subscription list entry '"+entry+"' has wrong number of elements.");
718 return rc;
719 }
720
721 var list = obj.data.split('\n').map(map);
722 function check(name)
723 {
724 if (list.every(function(el){return el==undefined || el[0]!=name;}))
725 throw new Error("Subscription to '"+name+"' not available.");
726 }
727
728 expected.forEach(check);
729}
730
731
732
733// ================================================================
734// Crosscheck all states
735// ================================================================
736
737// ----------------------------------------------------------------
738// Do a standard startup to bring the system in into a well
739// defined state
740// ----------------------------------------------------------------
741include('scripts/Startup.js');
742
743// ================================================================
744// Code to monitor clock conditioner
745// ================================================================
746
747var sub_counter = new Subscription("FTM_CONTROL/COUNTER");
748sub_counter.onchange = function(evt)
749{
750 if (evt.qos>0 && evt.qos!=2 && evt.qos&0x100==0)
751 throw new Error("FTM reports: clock conditioner not locked.");
752}
753
754// ================================================================
755// Code related to monitoring the fad system
756// ================================================================
757
758// This code is here, because scripts/Startup.js needs the
759// same subscriptions... to be revised.
760var sub_incomplete = new Subscription("FAD_CONTROL/INCOMPLETE");
761var sub_connections = new Subscription("FAD_CONTROL/CONNECTIONS");
762var sub_startrun = new Subscription("FAD_CONTROL/START_RUN");
763sub_startrun.get(5000);
764
765include('scripts/takeRun.js');
766
767// ----------------------------------------------------------------
768// Check that everything we need is availabel to receive commands
769// (FIXME: Should that go to the general CheckState?)
770// ----------------------------------------------------------------
771//console.out("Checking send.");
772checkSend(["MCP", "DRIVE_CONTROL", "LID_CONTROL", "FAD_CONTROL", "FEEDBACK"]);
773//console.out("Checking send: done");
774
775// ----------------------------------------------------------------
776// Bring feedback into the correct operational state
777// ----------------------------------------------------------------
778//console.out("Feedback init: start.");
779service_feedback.get(5000);
780
781// ----------------------------------------------------------------
782// Connect to the DRS_RUNS service
783// ----------------------------------------------------------------
784//console.out("Drs runs init: start.");
785
786var sub_drsruns = new Subscription("FAD_CONTROL/DRS_RUNS");
787sub_drsruns.get(5000);
788// FIXME: Check if the last DRS calibration was complete?
789
790function getTimeSinceLastDrsCalib()
791{
792 // ----- Time since last DRS Calibration [min] ------
793 var runs = sub_drsruns.get(0);
794 var diff = (new Date()-runs.time)/60000;
795
796 // Warning: 'roi=300' is a number which is not intrisically fixed
797 // but can change depending on the taste of the observers
798 var valid = runs.obj['run'][2]>0 && runs.obj['roi']==300;
799
800 if (valid)
801 dim.log("Last DRS calibration was %.1fmin ago".$(diff));
802 else
803 dim.log("No valid DRS calibration available.");
804
805 return valid ? diff : null;
806}
807
808// ----------------------------------------------------------------
809// Install interrupt handler
810// ----------------------------------------------------------------
811var triggerReloadSources = false;
812
813function handleIrq(cmd, args, time, user)
814{
815 console.out("Interrupt received:");
816 console.out(" IRQ: "+cmd);
817 console.out(" Time: "+time);
818 console.out(" User: "+user);
819
820 if (cmd.toUpperCase()=="RELOADSOURCES")
821 {
822 dim.log("Reloading source table scheduled before next pointing operation.");
823 triggerReloadSources = true;
824 return;
825 }
826
827 irq = cmd ? cmd : "stop";
828
829 // This will end a run in progress as if it where correctly stopped
830 if (dim.state("MCP").name=="TakingData")
831 dim.send("MCP/STOP");
832
833 // This will stop a rate scan in progress
834 if (dim.state("RATE_SCAN").name=="InProgress")
835 dim.send("RATE_SCAN/STOP");
836}
837
838dimctrl.setInterruptHandler(handleIrq);
839
840// ----------------------------------------------------------------
841// Make sure we will write files
842// ----------------------------------------------------------------
843dim.send("FAD_CONTROL/SET_FILE_FORMAT", 6);
844
845// ----------------------------------------------------------------
846// Print some information for the user about the
847// expected first oberservation
848// ----------------------------------------------------------------
849var test = getObservation();
850if (test!=undefined)
851{
852 var n = new Date();
853 if (observations.length>0 && test==-1)
854 dim.log("First observation scheduled for "+observations[0].start.toUTCString()+" [id="+observations[0].id+"]");
855 if (test>=0 && test<observations.length)
856 dim.log("First observation should start immediately ["+observations[test].start.toUTCString()+", id="+observations[test].id+"]");
857 if (observations.length>0 && observations[0].start>n+12*3600*1000)
858 dim.log("No observations scheduled for the next 12 hours!");
859 if (observations.length==0)
860 dim.log("No observations scheduled!");
861}
862
863// ----------------------------------------------------------------
864// Start main loop
865// ----------------------------------------------------------------
866dim.log("Entering main loop.");
867console.out("");
868
869var run = -2; // getObservation never called
870var sub;
871var lastId;
872var nextId;
873var sun = Sun.horizon(-12);
874var system_on; // undefined
875
876function processIrq()
877{
878 if (!irq)
879 return false;
880
881 if (irq.toUpperCase()=="RESCHEDULE")
882 {
883 irq = undefined;
884 return false;
885 }
886
887 if (irq.toUpperCase()=="OFF")
888 {
889 service_feedback.voltageOff();
890 dim.send("FAD_CONTROL/CLOSE_OPEN_FILES");
891 return true;
892 }
893
894 /*
895 if (irq.toUpperCase()=="STOP")
896 {
897 dim.send("FAD_CONTROL/CLOSE_OPEN_FILES");
898 dim.send("MCP/STOP");
899 return true;
900 }*/
901
902 if (irq.toUpperCase()=="SHUTDOWN")
903 {
904 Shutdown();
905 return true;
906 }
907
908 dim.log("IRQ "+irq+" unhandled... stopping script.");
909 return true;
910}
911
912while (!processIrq())
913{
914 // Check if observation position is still valid
915 // If source position has changed, set run=0
916 var idxObs = getObservation();
917 if (idxObs===undefined)
918 break;
919
920 // we are still waiting for the first observation in the schedule
921 if (idxObs==-1)
922 {
923 // flag that the first observation will be in the future
924 run = -1;
925 v8.sleep(1000);
926 continue;
927 }
928
929 // Check if we have to take action do to sun-rise
930 var was_up = sun.isUp;
931 sun = Sun.horizon(-12);
932 if (!was_up && sun.isUp)
933 {
934 console.out("");
935 dim.log("Sun rise detected.... automatic shutdown initiated!");
936 // FIXME: State check?
937 Shutdown();
938 system_on = false;
939 continue;
940 }
941
942 // Current and next observation target
943 var obs = observations[idxObs];
944 var nextObs = observations[idxObs+1];
945
946 // Check if observation target has changed
947 if (lastId!=obs.id) // !Object.isEqual(obs, nextObs)
948 {
949 dim.log("Starting new observation ["+obs.start.toUTCString()+", id="+obs.id+"]");
950
951 // This is the first source, but we do not come from
952 // a scheduled 'START', so we have to check if the
953 // telescop is operational already
954 sub = 0;
955 if (run<0)
956 {
957 //Startup(); // -> Bias On/Off?, Lid open/closed?
958 //CloseLid();
959 }
960
961 // The first observation had a start-time in the past...
962 // In this particular case start with the last entry
963 // in the list of measurements
964 if (run==-2)
965 sub = obs.length-1;
966
967 run = 0;
968 lastId = obs.id;
969 }
970
971 //dim.log("DEBUG: Next observation scheduled for "+nextObs.start.toUTCString()+" [id="+nextObs.id+"]");
972 if (nextObs && nextId!=nextObs.id)
973 {
974 dim.log("Next observation scheduled for "+nextObs.start.toUTCString()+" [id="+nextObs.id+"]");
975 console.out("");
976 nextId = nextObs.id;
977 }
978
979 if (!nextObs && nextId)
980 {
981 if (obs[sub].task=="SUSPEND")
982 dim.log("Further observation suspended.");
983 else
984 dim.log("No further observation scheduled.");
985 console.out("");
986 nextId = undefined;
987 }
988
989 //if (nextObs==undefined && obs[obs.length-1].task!="SHUTDOWN")
990 // throw Error("Last scheduled measurement must be a shutdown.");
991
992 // We are done with all measurement slots for this
993 // observation... wait for next observation
994 if (sub>=obs.length)
995 {
996 v8.sleep(1000);
997 continue;
998 }
999
1000 if (system_on===false && obs[sub].task!="STARTUP")
1001 {
1002 v8.sleep(1000);
1003 continue;
1004 }
1005
1006 // Check if sun is still up... only DATA and */
1007 if ((obs[sub].task=="DATA" || obs[sub].task=="RATESCAN" || obs[sub].task=="RATESCAN2" ) && sun.isUp)
1008 {
1009 var now = new Date();
1010 var remaining = (sun.set - now)/60000;
1011 console.out(now.toUTCString()+" - "+obs[sub].task+": Sun above FACT-horizon: sleeping 1min, remaining %.1fmin".$(remaining));
1012 v8.sleep(60000);
1013 continue;
1014 }
1015
1016
1017 if (obs[sub].task!="IDLE" && (obs[sub].task!="DATA" && run>0))
1018 dim.log("New task ["+obs[sub]+"]");
1019
1020 // FIXME: Maybe print a warning if Drive is on during day time!
1021
1022 // It is not ideal that we allow the drive to be on during day time, but
1023 // otherwise it is difficult to allow e.g. the STARTUP at the beginning of the night
1024 var power_states = sun.isUp || !system_on ? [ "DriveOff", "SystemOn" ] : [ "SystemOn" ];
1025 var drive_states = sun.isUp || !system_on ? undefined : [ "Initialized", "Tracking", "OnTrack" ];
1026
1027 // A scheduled task was found, lets check if all servers are
1028 // still only and in reasonable states. If this is not the case,
1029 // something unexpected must have happend and the script is aborted.
1030 //console.out(" Checking states [general]");
1031 var table =
1032 [
1033 [ "TNG_WEATHER" ],
1034 [ "MAGIC_WEATHER" ],
1035 [ "RAIN_SENSOR" ],
1036 [ "CHAT" ],
1037 [ "SMART_FACT" ],
1038 [ "TEMPERATURE" ],
1039 [ "DATA_LOGGER", [ "NightlyFileOpen", "WaitForRun", "Logging" ] ],
1040 [ "FSC_CONTROL", [ "Connected" ] ],
1041 [ "MCP", [ "Idle" ] ],
1042 [ "TIME_CHECK", [ "Valid" ] ],
1043 [ "PWR_CONTROL", power_states/*[ "SystemOn" ]*/ ],
1044 [ "AGILENT_CONTROL_24V", [ "VoltageOn" ] ],
1045 [ "AGILENT_CONTROL_50V", [ "VoltageOn" ] ],
1046 //[ "AGILENT_CONTROL_80V", [ "VoltageOn" ] ],
1047 [ "AGILENT_CONTROL_80V", [ "VoltageOn", "Disconnected" ] ], //hack to allow for data taking while agilent not available
1048 [ "BIAS_CONTROL", [ "VoltageOff", "VoltageOn", "Ramping" ] ],
1049 [ "FEEDBACK", [ "Calibrated", "InProgress", "OnStandby", "Warning", "Critical" ] ],
1050 [ "LID_CONTROL", [ "Open", "Closed" ] ],
1051 [ "DRIVE_CONTROL", drive_states/*[ "Armed", "Tracking", "OnTrack" ]*/ ],
1052 [ "FTM_CONTROL", [ "Valid", "TriggerOn" ] ],
1053 [ "FAD_CONTROL", [ "Connected", "RunInProgress" ] ],
1054 [ "RATE_SCAN", [ "Connected" ] ],
1055 [ "RATE_CONTROL", [ "Connected", "GlobalThresholdSet", "InProgress" ] ],
1056 [ "GPS_CONTROL", [ "Locked" ] ],
1057 [ "SQM_CONTROL", [ "Disconnected", "Connected", "Valid" ] ],
1058 [ "PFMINI_CONTROL", [ "Disconnected", "Connected", "Receiving" ] ],
1059 [ "BIAS_TEMP", [ "Valid" ] ],
1060 ];
1061
1062
1063 if (!checkStates(table))
1064 {
1065 throw new Error("Something unexpected has happened. One of the servers "+
1066 "is in a state in which it should not be. Please,"+
1067 "try to find out what happened...");
1068 }
1069
1070 datalogger_subscriptions.check();
1071
1072 // If this is an observation which needs the voltage to be swicthed on
1073 // skip that if the voltage is not stable
1074 /*
1075 if (obs[sub].task=="DATA" || obs[sub].task=="RATESCAN")
1076 {
1077 var state = dim.state("FEEDBACK").name;
1078 if (state=="Warning" || state=="Critical" || state=="OnStandby")
1079 {
1080 v8.sleep(1000);
1081 continue;
1082 }
1083 }*/
1084
1085
1086 // Check if obs.task is one of the one-time-tasks
1087 switch (obs[sub].task)
1088 {
1089 case "IDLE":
1090 v8.sleep(5000);
1091 continue;
1092
1093 case "SUSPEND":
1094 case "SLEEP":
1095 Shutdown("unlock"); //GoToSleep();
1096
1097 dim.log("Task finished ["+obs[sub].task+"].");
1098 console.out("");
1099 sub++;
1100 continue;
1101
1102 case "STARTUP":
1103 CloseLid();
1104
1105 doDrsCalibration("startup"); // will switch the voltage off
1106
1107 if (irq)
1108 break;
1109
1110 service_feedback.voltageOn();
1111 service_feedback.waitForVoltageOn();
1112
1113 // Before we can switch to 3000 we have to make the right DRS calibration
1114 dim.log("Taking single p.e. run.");
1115 while (!irq && !takeRun("single-pe", 10000));
1116
1117 // It is unclear what comes next, so we better switch off the voltage
1118 service_feedback.voltageOff();
1119
1120 system_on = true;
1121 dim.log("Task finished [STARTUP]");
1122 console.out("");
1123 break;
1124
1125 case "SHUTDOWN":
1126 Shutdown("singlepe");
1127 system_on = false;
1128
1129 // FIXME: Avoid new observations after a shutdown until
1130 // the next startup (set run back to -2?)
1131 sub++;
1132 dim.log("Task finished [SHUTDOWN]");
1133 console.out("");
1134 //console.out(" Waiting for next startup.", "");
1135 continue;
1136
1137 case "DRSCALIB":
1138 doDrsCalibration("drscalib"); // will switch the voltage off
1139 dim.log("Task finished [DRSCALIB]");
1140 console.out("");
1141 break;
1142
1143 case "SINGLEPE":
1144 // The lid must be closes
1145 CloseLid();
1146
1147 // Check if DRS calibration is necessary
1148 var diff = getTimeSinceLastDrsCalib();
1149 if (diff>30 || diff==null)
1150 {
1151 doDrsCalibration("singlepe"); // will turn voltage off
1152 if (irq)
1153 break;
1154 }
1155
1156 // The voltage must be on
1157 service_feedback.voltageOn();
1158 service_feedback.waitForVoltageOn();
1159
1160 // Before we can switch to 3000 we have to make the right DRS calibration
1161 dim.log("Taking single p.e. run.");
1162 while (!irq && !takeRun("single-pe", 10000));
1163
1164 // It is unclear what comes next, so we better switch off the voltage
1165 service_feedback.voltageOff();
1166 dim.log("Task finished [SINGLE-PE]");
1167 console.out("");
1168 break;
1169
1170 case "OVTEST":
1171 var locked = dim.state("DRIVE_CONTROL").name=="Locked";
1172 if (!locked)
1173 dim.send("DRIVE_CONTROL/PARK");
1174
1175 dim.send("FEEDBACK/STOP");
1176
1177 // The lid must be closed
1178 CloseLid();
1179
1180 if (!locked)
1181 {
1182 //console.out("Waiting for telescope to park. This may take a while.");
1183 dim.wait("DRIVE_CONTROL", "Locked", 3000);
1184 dim.send("DRIVE_CONTROL/UNLOCK");
1185 }
1186
1187 // Check if DRS calibration is necessary
1188 var diff = getTimeSinceLastDrsCalib();
1189 if (diff>30 || diff==null)
1190 {
1191 doDrsCalibration("ovtest"); // will turn voltage off
1192 if (irq)
1193 break;
1194 }
1195
1196 // The voltage must be on
1197 service_feedback.voltageOn(0.4);
1198 service_feedback.waitForVoltageOn();
1199
1200 dim.log("Taking single p.e. run (0.4V)");
1201 while (!irq && !takeRun("single-pe", 10000));
1202
1203 for (var i=5; i<18 && !irq; i++)
1204 {
1205 dim.send("FEEDBACK/STOP");
1206 dim.wait("FEEDBACK", "Calibrated", 3000);
1207 dim.wait("BIAS_CONTROL", "VoltageOn", 3000);
1208 dim.send("FEEDBACK/START", i*0.1);
1209 dim.wait("FEEDBACK", "InProgress", 45000);
1210 dim.wait("BIAS_CONTROL", "VoltageOn", 60000); // FIXME: 30000?
1211 service_feedback.waitForVoltageOn();
1212 dim.log("Taking single p.e. run ("+(i*0.1)+"V)");
1213 while (!irq && !takeRun("single-pe", 10000));
1214 }
1215
1216 // It is unclear what comes next, so we better switch off the voltage
1217 service_feedback.voltageOff();
1218 dim.log("Task finished [OVTEST]");
1219 console.out("");
1220 break;
1221
1222 case "RATESCAN":
1223 var tm1 = new Date();
1224
1225 // This is a workaround to make sure that we really catch
1226 // the new OnTrack state later and not the old one
1227 dim.send("DRIVE_CONTROL/STOP");
1228 dim.wait("DRIVE_CONTROL", "Initialized", 15000);
1229
1230 // The lid must be open
1231 OpenLid();
1232
1233 // Switch the voltage to a reduced level (Ubd)
1234 service_feedback.voltageOn(0);
1235
1236 if (obs[sub].source != null) // undefined != null -> false
1237 {
1238 dim.log("Pointing telescope to '"+obs[sub].source+"'.");
1239 dim.send("DRIVE_CONTROL/TRACK_ON", obs[sub].source);
1240 }
1241 else
1242 {
1243 dim.log("Pointing telescope to ra="+obs[sub].ra+" dec="+obs[sub].dec);
1244 dim.send("DRIVE_CONTROL/TRACK", obs[sub].ra, obs[sub].dec);
1245 }
1246
1247 dim.wait("DRIVE_CONTROL", "OnTrack", 150000); // 110s for turning and 30s for stabilizing
1248
1249 // Now tracking stable, switch voltage to nominal level and wait
1250 // for stability.
1251 service_feedback.voltageOn();
1252 service_feedback.waitForVoltageOn();
1253
1254 if (!irq)
1255 {
1256 dim.log("Starting calibration.");
1257
1258 // Calibration (2% of 20')
1259 while (!irq)
1260 {
1261 if (irq || !takeRun("pedestal", 1000)) // 80 Hz -> 10s
1262 continue;
1263 //if (irq || !takeRun("light-pulser-ext", 1000)) // 80 Hz -> 10s
1264 // continue;
1265 break;
1266 }
1267
1268 var tm2 = new Date();
1269
1270 dim.log("Starting ratescan.");
1271
1272 //set reference to whole camera (in case it was changed)
1273 dim.send("RATE_SCAN/SET_REFERENCE_CAMERA");
1274 // Start rate scan
1275 dim.send("RATE_SCAN/START_THRESHOLD_SCAN", 50, 1000, -10, "default");
1276
1277 // Lets wait if the ratescan really starts... this might take a few
1278 // seconds because RATE_SCAN configures the ftm and is waiting for
1279 // it to be configured.
1280 dim.wait("RATE_SCAN", "InProgress", 10000);
1281 dim.wait("RATE_SCAN", "Connected", 2700000);
1282
1283 // Here one could implement a watchdog for the feedback as well, but what is the difference
1284 // whether finally one has to find out if the feedback was in the correct state
1285 // or the ratescan was interrupted?
1286
1287 // this line is actually some kind of hack.
1288 // after the Ratescan, no data is written to disk. I don't know why, but it happens all the time
1289 // So I decided to put this line here as a kind of patchwork....
1290 //dim.send("FAD_CONTROL/SET_FILE_FORMAT", 6);
1291
1292 dim.log("Ratescan done [%.1fs, %.1fs]".$((tm2-tm1)/1000, (new Date()-tm2)/1000));
1293 }
1294
1295 dim.log("Task finished [RATESCAN]");
1296 console.out("");
1297 break; // case "RATESCAN"
1298
1299 case "RATESCAN2":
1300 var tm1 = new Date();
1301
1302 // This is a workaround to make sure that we really catch
1303 // the new OnTrack state later and not the old one
1304 dim.send("DRIVE_CONTROL/STOP");
1305 dim.wait("DRIVE_CONTROL", "Initialized", 15000);
1306
1307 if (obs[sub].rstype=="dark-bias-off")
1308 service_feedback.voltageOff();
1309 else
1310 {
1311 // Switch the voltage to a reduced level (Ubd)
1312 var bias = dim.state("BIAS_CONTROL").name;
1313 if (bias=="VoltageOn" || bias=="Ramping")
1314 service_feedback.voltageOn(0);
1315 }
1316
1317 // Open the lid if required
1318 if (!obs[sub].lidclosed)
1319 OpenLid();
1320 else
1321 CloseLid();
1322
1323 // track source/position or move to position
1324 if (obs[sub].lidclosed)
1325 {
1326 dim.log("Moving telescope to zd="+obs[sub].zd+" az="+obs[sub].az);
1327 dim.send("DRIVE_CONTROL/MOVE_TO", obs[sub].zd, obs[sub].az);
1328 v8.sleep(3000);
1329 dim.wait("DRIVE_CONTROL", "Initialized", 150000); // 110s for turning and 30s for stabilizing
1330 }
1331 else
1332 {
1333 if (obs[sub].source != null) // undefined != null -> false
1334 {
1335 dim.log("Pointing telescope to '"+obs[sub].source+"'.");
1336 dim.send("DRIVE_CONTROL/TRACK_ON", obs[sub].source);
1337 }
1338 else
1339 {
1340 dim.log("Pointing telescope to ra="+obs[sub].ra+" dec="+obs[sub].dec);
1341 dim.send("DRIVE_CONTROL/TRACK", obs[sub].ra, obs[sub].dec);
1342 }
1343
1344 dim.wait("DRIVE_CONTROL", "OnTrack", 150000); // 110s for turning and 30s for stabilizing
1345 }
1346
1347 // Now tracking stable, switch voltage to nominal level and wait
1348 // for stability.
1349 if (obs[sub].rstype!="dark-bias-off")
1350 {
1351 service_feedback.voltageOn();
1352 service_feedback.waitForVoltageOn();
1353 }
1354
1355 if (!irq)
1356 {
1357 var tm2 = new Date();
1358
1359 dim.log("Starting ratescan 2/1 ["+obs[sub].rstype+"]");
1360
1361 //set reference to whole camera (in case it was changed)
1362 dim.send("RATE_SCAN/SET_REFERENCE_CAMERA");
1363 // Start rate scan
1364 dim.send("RATE_SCAN/START_THRESHOLD_SCAN", 50, 300, 20, obs[sub].rstype);
1365
1366 // Lets wait if the ratescan really starts... this might take a few
1367 // seconds because RATE_SCAN configures the ftm and is waiting for
1368 // it to be configured.
1369 dim.wait("RATE_SCAN", "InProgress", 10000);
1370 //FIXME: discuss what best value is here
1371 dim.wait("RATE_SCAN", "Connected", 2700000);//45min
1372 //dim.wait("RATE_SCAN", "Connected", 1200000);//3.3h
1373
1374 // Here one could implement a watchdog for the feedback as well, but what is the difference
1375 // whether finally one has to find out if the feedback was in the correct state
1376 // or the ratescan was interrupted?
1377
1378 // this line is actually some kind of hack.
1379 // after the Ratescan, no data is written to disk. I don't know why, but it happens all the time
1380 // So I decided to put this line here as a kind of patchwork....
1381 //dim.send("FAD_CONTROL/SET_FILE_FORMAT", 6);
1382
1383 dim.log("Ratescan 2/1 done [%.1fs, %.1fs]".$((tm2-tm1)/1000, (new Date()-tm2)/1000));
1384 }
1385
1386 if (!irq)
1387 {
1388 var tm2 = new Date();
1389
1390 dim.log("Starting ratescan 2/2 ["+obs[sub].rstype+"]");
1391
1392 // Start rate scan
1393 dim.send("RATE_SCAN/START_THRESHOLD_SCAN", 300, 1000, 100, obs[sub].rstype);
1394
1395 // Lets wait if the ratescan really starts... this might take a few
1396 // seconds because RATE_SCAN configures the ftm and is waiting for
1397 // it to be configured.
1398 dim.wait("RATE_SCAN", "InProgress", 10000);
1399 dim.wait("RATE_SCAN", "Connected", 2700000);
1400
1401 // Here one could implement a watchdog for the feedback as well, but what is the difference
1402 // whether finally one has to find out if the feedback was in the correct state
1403 // or the ratescan was interrupted?
1404
1405 // this line is actually some kind of hack.
1406 // after the Ratescan, no data is written to disk. I don't know why, but it happens all the time
1407 // So I decided to put this line here as a kind of patchwork....
1408 //dim.send("FAD_CONTROL/SET_FILE_FORMAT", 6);
1409
1410 dim.log("Ratescan 2/2 done [%.1fs, %.1fs]".$((tm2-tm1)/1000, (new Date()-tm2)/1000));
1411 }
1412
1413 dim.log("Task finished [RATESCAN2]");
1414 console.out("");
1415 break; // case "RATESCAN2"
1416
1417 case "CUSTOM":
1418
1419 // This is a workaround to make sure that we really catch
1420 // the new OnTrack state later and not the old one
1421 dim.send("DRIVE_CONTROL/STOP");
1422 dim.wait("DRIVE_CONTROL", "Initialized", 15000);
1423
1424 // Ramp bias if needed
1425 if (!obs[sub].biason)
1426 service_feedback.voltageOff();
1427 else
1428 {
1429 // Switch the voltage to a reduced level (Ubd)
1430 var bias = dim.state("BIAS_CONTROL").name;
1431 if (bias=="VoltageOn" || bias=="Ramping")
1432 service_feedback.voltageOn(0);
1433 }
1434 // Close lid
1435 CloseLid();
1436
1437 // Move to position (zd/az)
1438 dim.log("Moving telescope to zd="+obs[sub].zd+" az="+obs[sub].az);
1439 dim.send("DRIVE_CONTROL/MOVE_TO", obs[sub].zd, obs[sub].az);
1440 v8.sleep(3000);
1441 dim.wait("DRIVE_CONTROL", "Initialized", 150000); // 110s for turning and 30s for stabilizing
1442
1443 // Now tracking stable, switch voltage to nominal level and wait
1444 // for stability.
1445 if (obs[sub].biason)
1446 {
1447 service_feedback.voltageOn();
1448 service_feedback.waitForVoltageOn();
1449 }
1450
1451 if (!irq)
1452 {
1453 dim.log("Taking custom run with time "+obs[sub].time+"s, threshold="+obs[sub].threshold+", biason="+obs[sub].biason);
1454
1455 var customRun = function()
1456 {
1457 v8.sleep(500);//wait that configuration is set
1458 dim.wait("FTM_CONTROL", "TriggerOn", 15000);
1459 dim.send("FAD_CONTROL/SEND_SINGLE_TRIGGER");
1460 dim.send("RATE_CONTROL/STOP");
1461 dim.send("FTM_CONTROL/STOP_TRIGGER");
1462 dim.wait("FTM_CONTROL", "Valid", 3000);
1463 dim.send("FTM_CONTROL/ENABLE_TRIGGER", true);
1464 dim.send("FTM_CONTROL/SET_TIME_MARKER_DELAY", 123);
1465 dim.send("FTM_CONTROL/SET_THRESHOLD", -1, obs[sub].threshold);
1466 v8.sleep(500);//wait that configuration is set
1467 dim.send("FTM_CONTROL/START_TRIGGER");
1468 dim.wait("FTM_CONTROL", "TriggerOn", 15000);
1469 }
1470
1471 takeRun("custom", -1, obs[sub].time, customRun);
1472 }
1473 dim.log("Task finished [CUSTOM].");
1474 dim.log("");
1475 break; // case "CUSTOM"
1476
1477 case "DATA":
1478
1479 // ========================== case "DATA" ============================
1480 /*
1481 if (Sun.horizon("FACT").isUp)
1482 {
1483 console.out(" SHUTDOWN","");
1484 Shutdown();
1485 console.out(" Exit forced due to broken schedule", "");
1486 exit();
1487 }
1488 */
1489
1490 // Calculate remaining time for this observation in minutes
1491 var remaining = nextObs==undefined ? 0 : (nextObs.start-new Date())/60000;
1492 //dim.log("DEBUG: remaining: "+remaining+" nextObs="+nextObs+" start="+nextObs.start);
1493
1494 // ------------------------------------------------------------
1495
1496 dim.log("Run count "+run+" [remaining "+parseInt(remaining)+"min]");
1497
1498 // ----- Time since last DRS Calibration [min] ------
1499 var diff = getTimeSinceLastDrsCalib();
1500
1501 // Changine pointing position and take calibration...
1502 // ...every four runs (every ~20min)
1503 // ...if at least ten minutes of observation time are left
1504 // ...if this is the first run on the source
1505 var point = (run%4==0 && remaining>10 && !obs[sub].orbit) || run==0; // undefined==null -> true!
1506
1507 // Take DRS Calib...
1508 // ...every four runs (every ~20min)
1509 // ...at last every two hours
1510 // ...when DRS temperature has changed by more than 2deg (?)
1511 // ...when more than 15min of observation are left
1512 // ...no drs calibration was done yet
1513 var drscal = (run%4==0 && (remaining>15 && diff>70)) || diff==null;
1514
1515 if (point)
1516 {
1517 // Switch the voltage to a reduced voltage level
1518 service_feedback.voltageOn(0);
1519
1520 // Change wobble position every four runs,
1521 // start with alternating wobble positions each day
1522 var wobble = (parseInt(run/4) + parseInt(new Date()/1000/3600/24-0.5))%2+1;
1523 var angle = obs[sub].angle == null ? Math.random()*360 : obs[sub].angle;
1524
1525 if (obs[sub].orbit) // != undefined, != null, != 0
1526 dim.log("Pointing telescope to '"+obs[sub].source+"' [orbit="+obs[sub].orbit+"min, angle="+angle+"]");
1527 else
1528 dim.log("Pointing telescope to '"+obs[sub].source+"' [wobble="+wobble+"]");
1529
1530 // This is a workaround to make sure that we really catch
1531 // the new OnTrack state later and not the old one
1532 dim.send("DRIVE_CONTROL/STOP");
1533 dim.wait("DRIVE_CONTROL", "Initialized", 15000);
1534
1535 if (triggerReloadSources) // It's all synchronous - no need to wait here
1536 {
1537 dim.send("DRIVE_CONTROL/RELOAD_SOURCES");
1538 triggerReloadSources = false;
1539 dim.log("Reloading source table triggered in drivectrl.");
1540 }
1541
1542 if (obs[sub].orbit) // != undefined, != null, != 0
1543 dim.send("DRIVE_CONTROL/TRACK_ORBIT", angle, obs[sub].orbit, obs[sub].source);
1544 else
1545 dim.send("DRIVE_CONTROL/TRACK_WOBBLE", wobble, obs[sub].source);
1546
1547 // Do we have to check if the telescope is really moving?
1548 // We can cross-check the SOURCE service later
1549 }
1550
1551 if (drscal && !obs[sub].nodrs)
1552 {
1553 doDrsCalibration("data"); // will turn voltage off
1554
1555 // Now we switch on the voltage and a significant amount of
1556 // time has been passed, so do the check again.
1557 sun = Sun.horizon(-12);
1558 if (!was_up && sun.isUp)
1559 {
1560 dim.log("Sun rise detected....");
1561 continue;
1562 }
1563 }
1564
1565 if (irq)
1566 continue;
1567
1568 OpenLid(obs[sub].grb);
1569
1570 // This is now the right time to wait for the drive to be stable
1571 if (!obs[sub].grb)
1572 dim.wait("DRIVE_CONTROL", "OnTrack", 150000); // 110s for turning and 30s for stabilizing
1573 else
1574 v8.timeout(150000, function() { if (dim.state("DRIVE_CONTROL").name=="Approaching" || dim.state("DRIVE_CONTROL").name=="Tracking" || dim.state("DRIVE_CONTROL").name=="OnTrack") return true; });
1575
1576 // Now check the voltage... (do not start a lot of stuff just to do nothing)
1577 var state = dim.state("FEEDBACK").name;
1578 if (state=="Warning" || state=="Critical" || state=="OnStandby")
1579 {
1580 v8.sleep(60000);
1581 continue;
1582 }
1583
1584 // Now we are 'OnTrack', so we can ramp to nominal voltage
1585 // and wait for the feedback to get stable
1586 service_feedback.voltageOn();
1587 if (!obs[sub].grb)
1588 service_feedback.waitForVoltageOn();
1589
1590 // For the first run to be taken (ratecontrol)
1591 // Lid must be != Closed
1592 // Drive must be >= Moving
1593 // Setting the threshold can take 2-3 seconds
1594
1595 if (obs[sub].grb && run==0)
1596 {
1597 // Instead of a pedestal run, we take a very short grb mode run
1598 // which is a classical data run but does not change the thresholds
1599 // This gives the voltages (typ. 5s) and currents (typ. 3s) time to
1600 // stabilize and threshold setting for the next run will be
1601 // reliable and fast but we have data already
1602 dim.log("Starting GRB mode.");
1603
1604 // Whatever we do... it does not make sense to start with a closed lid
1605 // If the lid is not yet open, wait for the lid to be open and
1606 // go on as usual.
1607 if (dim.state("LID_CONTROL")!="Open")
1608 {
1609 dim.wait("LID_CONTROL", "Open", 30000);
1610 service_feedback.waitForVoltageOn();
1611 }
1612
1613 // Doing this manually makes it more flexible but turns off
1614 // automatic Critical mode checking of the feedback and
1615 // automatic reconnect
1616 var nextrun = sub_startrun.get().obj['next'];
1617 dim.log("Take run %3d".$(nextrun)+" [grb-mode]");
1618
1619 dim.send("MCP/START", -1, -1, "grb"); // Use previous threshold settings if ratecontrol "InProgress"
1620 dim.wait("MCP", "TakingData", 15000);
1621
1622 dim.wait("FEEDBACK", "InProgress", 45000); // This is most likely the first to happen
1623 dim.wait("DRIVE_CONTROL", "Tracking", 150000); // 110s for turning and 30s for stabilizing
1624
1625 v8.wait(1000); // By now we should have collected the required three current events in FEEDBACK
1626 // Current are averaged over 10s. So by now we should have a reasonable idea of the brightness of the sky
1627 // Individual pixels might still suffer wrong settings
1628 // Starting a new run takes less than 2s (for 60s runs this is 3%)
1629 }
1630
1631 // If pointing had changed, do calibration
1632 if (!irq && point && !obs[sub].grb)
1633 {
1634 dim.log("Starting calibration.");
1635
1636 // Calibration (2% of 20')
1637 while (!irq)
1638 {
1639 if (irq || !takeRun("pedestal", 1000)) // 80 Hz -> 10s
1640 continue;
1641// if (irq || !takeRun("light-pulser-ext", 1000)) // 80 Hz -> 10s
1642// continue;
1643 break;
1644 }
1645 }
1646
1647 //console.out(" Taking data: start [5min]");
1648
1649 // FIXME: What do we do if during calibration something has happened
1650 // e.g. drive went to ERROR? Maybe we have to check all states again?
1651
1652 var twilight = Sun.horizon(-16).isUp;
1653
1654 if (twilight || obs[sub].grb)
1655 {
1656 for (var i=0; i<5 && !irq; i++)
1657 takeRun("data", -1, 60); // Take data (1min)
1658 }
1659 else
1660 {
1661 var len = 300;
1662 while (!irq && len>15)
1663 {
1664 var time = new Date();
1665 if (takeRun("data", -1, len)) // Take data (5min)
1666 break;
1667
1668 len -= parseInt((new Date()-time)/1000);
1669 }
1670 }
1671
1672 //console.out(" Taking data: done");
1673 run++;
1674
1675 continue; // case "DATA"
1676 }
1677
1678 if (nextObs!=undefined && sub==obs.length-1)
1679 dim.log("Next observation will start at "+nextObs.start.toUTCString()+" [id="+nextObs.id+"]");
1680
1681 sub++;
1682}
1683
1684sub_drsruns.close();
1685
1686dim.log("Left main loop [irq="+irq+"]");
1687
1688// ================================================================
1689// Comments and ToDo goes here
1690// ================================================================
1691
1692// error handline : http://www.sitepoint.com/exceptional-exception-handling-in-javascript/
1693// classes: http://www.phpied.com/3-ways-to-define-a-javascript-class/
Note: See TracBrowser for help on using the repository browser.