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

Last change on this file since 19558 was 19531, checked in by tbretz, 6 years ago
No special handling for PREPARE required.
File size: 56.7 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 if (user)
819 console.out(" User: "+user);
820
821 if (cmd.toUpperCase()=="RELOADSOURCES")
822 {
823 dim.log("Reloading source table scheduled before next pointing operation.");
824 triggerReloadSources = true;
825 return;
826 }
827
828 irq = cmd ? cmd : "stop";
829
830 dim.send("MCP/STOP");
831
832 if (irq.toUpperCase()=="PREPARE")
833 {
834 triggerReloadSources = true;
835 dim.send("DRIVE_CONTROL/STOP");
836 irq = undefined;
837 }
838
839 /*
840 if (fDimFTM.state()==FTM::State::kTriggerOn)
841 {
842 Message("Stopping FTM");
843 Dim::SendCommandNB("FTM_CONTROL/STOP_TRIGGER");
844 }
845
846 // FIXME: Do step 2 only when FTM is stopped
847 if (fDimFAD.state()==FAD::State::kConnected || fDimFAD.state()==FAD::State::kRunInProgress)
848 {
849 if (fDimFAD.state()==FAD::State::kRunInProgress)
850 Dim::SendCommandNB("FAD_CONTROL/CLOSE_OPEN_FILES");
851 }
852
853 return GetCurrentState();
854 */
855
856 // This will stop a rate scan in progress
857 if (dim.state("RATE_SCAN").name=="InProgress")
858 dim.send("RATE_SCAN/STOP");
859}
860
861dimctrl.setInterruptHandler(handleIrq);
862
863// ----------------------------------------------------------------
864// Make sure we will write files
865// ----------------------------------------------------------------
866dim.send("FAD_CONTROL/SET_FILE_FORMAT", 6);
867
868// ----------------------------------------------------------------
869// Print some information for the user about the
870// expected first oberservation
871// ----------------------------------------------------------------
872var test = getObservation();
873if (test!=undefined)
874{
875 var n = new Date();
876 if (observations.length>0 && test==-1)
877 dim.log("First observation scheduled for "+observations[0].start.toUTCString()+" [id="+observations[0].id+"]");
878 if (test>=0 && test<observations.length)
879 dim.log("First observation should start immediately ["+observations[test].start.toUTCString()+", id="+observations[test].id+"]");
880 if (observations.length>0 && observations[0].start>n+12*3600*1000)
881 dim.log("No observations scheduled for the next 12 hours!");
882 if (observations.length==0)
883 dim.log("No observations scheduled!");
884}
885
886// ----------------------------------------------------------------
887// Start main loop
888// ----------------------------------------------------------------
889dim.log("Entering main loop.");
890console.out("");
891
892var run = -2; // getObservation never called
893var sub;
894var lastId;
895var nextId;
896var sun = Sun.horizon(-12);
897var system_on; // undefined
898
899function processIrq()
900{
901 if (!irq)
902 return false;
903
904 while (irq.toUpperCase()=="PREPARE")
905 v8.sleep(10);
906
907 if (irq.toUpperCase()=="RESCHEDULE")
908 {
909 irq = undefined;
910 return false;
911 }
912
913 if (irq.toUpperCase()=="OFF")
914 {
915 service_feedback.voltageOff();
916 dim.send("FAD_CONTROL/CLOSE_OPEN_FILES");
917 return true;
918 }
919
920 /*
921 if (irq.toUpperCase()=="STOP")
922 {
923 dim.send("FAD_CONTROL/CLOSE_OPEN_FILES");
924 dim.send("MCP/STOP");
925 return true;
926 }*/
927
928 if (irq.toUpperCase()=="SHUTDOWN")
929 {
930 Shutdown();
931 return true;
932 }
933
934 dim.log("IRQ "+irq+" unhandled... stopping script.");
935 return true;
936}
937
938while (!processIrq())
939{
940 // Check if observation position is still valid
941 // If source position has changed, set run=0
942 var idxObs = getObservation();
943 if (idxObs===undefined)
944 break;
945
946 // we are still waiting for the first observation in the schedule
947 if (idxObs==-1)
948 {
949 // flag that the first observation will be in the future
950 run = -1;
951 v8.sleep(1000);
952 continue;
953 }
954
955 // Check if we have to take action do to sun-rise
956 var was_up = sun.isUp;
957 sun = Sun.horizon(-12);
958 if (!was_up && sun.isUp)
959 {
960 console.out("");
961 dim.log("Sun rise detected.... automatic shutdown initiated!");
962 // FIXME: State check?
963 Shutdown();
964 system_on = false;
965 continue;
966 }
967
968 // Current and next observation target
969 var obs = observations[idxObs];
970 var nextObs = observations[idxObs+1];
971
972 // Check if observation target has changed
973 if (lastId!=obs.id) // !Object.isEqual(obs, nextObs)
974 {
975 dim.log("Starting new observation ["+obs.start.toUTCString()+", id="+obs.id+"]");
976
977 // This is the first source, but we do not come from
978 // a scheduled 'START', so we have to check if the
979 // telescop is operational already
980 sub = 0;
981 if (run<0)
982 {
983 //Startup(); // -> Bias On/Off?, Lid open/closed?
984 //CloseLid();
985 }
986
987 // The first observation had a start-time in the past...
988 // In this particular case start with the last entry
989 // in the list of measurements
990 if (run==-2)
991 sub = obs.length-1;
992
993 run = 0;
994 lastId = obs.id;
995 }
996
997 //dim.log("DEBUG: Next observation scheduled for "+nextObs.start.toUTCString()+" [id="+nextObs.id+"]");
998 if (nextObs && nextId!=nextObs.id)
999 {
1000 dim.log("Next observation scheduled for "+nextObs.start.toUTCString()+" [id="+nextObs.id+"]");
1001 console.out("");
1002 nextId = nextObs.id;
1003 }
1004
1005 if (!nextObs && nextId)
1006 {
1007 if (obs[sub].task=="SUSPEND")
1008 dim.log("Further observation suspended.");
1009 else
1010 dim.log("No further observation scheduled.");
1011 console.out("");
1012 nextId = undefined;
1013 }
1014
1015 //if (nextObs==undefined && obs[obs.length-1].task!="SHUTDOWN")
1016 // throw Error("Last scheduled measurement must be a shutdown.");
1017
1018 // We are done with all measurement slots for this
1019 // observation... wait for next observation
1020 if (sub>=obs.length)
1021 {
1022 v8.sleep(1000);
1023 continue;
1024 }
1025
1026 if (system_on===false && obs[sub].task!="STARTUP")
1027 {
1028 v8.sleep(1000);
1029 continue;
1030 }
1031
1032 // Check if sun is still up... only DATA and */
1033 if ((obs[sub].task=="DATA" || obs[sub].task=="RATESCAN" || obs[sub].task=="RATESCAN2" ) && sun.isUp)
1034 {
1035 var now = new Date();
1036 var remaining = (sun.set - now)/60000;
1037 console.out(now.toUTCString()+" - "+obs[sub].task+": Sun above FACT-horizon: sleeping 1min, remaining %.1fmin".$(remaining));
1038 v8.sleep(60000);
1039 continue;
1040 }
1041
1042
1043 if (obs[sub].task!="IDLE" && (obs[sub].task!="DATA" && run>0))
1044 dim.log("New task ["+obs[sub]+"]");
1045
1046 // FIXME: Maybe print a warning if Drive is on during day time!
1047
1048 // It is not ideal that we allow the drive to be on during day time, but
1049 // otherwise it is difficult to allow e.g. the STARTUP at the beginning of the night
1050 var power_states = sun.isUp || !system_on ? [ "DriveOff", "SystemOn" ] : [ "SystemOn" ];
1051 var drive_states = sun.isUp || !system_on ? undefined : [ "Initialized", "Tracking", "OnTrack" ];
1052
1053 // A scheduled task was found, lets check if all servers are
1054 // still only and in reasonable states. If this is not the case,
1055 // something unexpected must have happend and the script is aborted.
1056 //console.out(" Checking states [general]");
1057 var table =
1058 [
1059 [ "TNG_WEATHER" ],
1060 [ "MAGIC_WEATHER" ],
1061 [ "RAIN_SENSOR" ],
1062 [ "CHAT" ],
1063 [ "SMART_FACT" ],
1064 [ "TEMPERATURE" ],
1065 [ "DATA_LOGGER", [ "NightlyFileOpen", "WaitForRun", "Logging" ] ],
1066 [ "FSC_CONTROL", [ "Connected" ] ],
1067 [ "MCP", [ "Idle" ] ],
1068 [ "TIME_CHECK", [ "Valid" ] ],
1069 [ "PWR_CONTROL", power_states/*[ "SystemOn" ]*/ ],
1070 [ "AGILENT_CONTROL_24V", [ "VoltageOn" ] ],
1071 [ "AGILENT_CONTROL_50V", [ "VoltageOn" ] ],
1072 //[ "AGILENT_CONTROL_80V", [ "VoltageOn" ] ],
1073 [ "AGILENT_CONTROL_80V", [ "VoltageOn", "Disconnected" ] ], //hack to allow for data taking while agilent not available
1074 [ "BIAS_CONTROL", [ "VoltageOff", "VoltageOn", "Ramping" ] ],
1075 [ "FEEDBACK", [ "Calibrated", "InProgress", "OnStandby", "Warning", "Critical" ] ],
1076 [ "LID_CONTROL", [ "Open", "Closed" ] ],
1077 [ "DRIVE_CONTROL", drive_states/*[ "Armed", "Tracking", "OnTrack" ]*/ ],
1078 [ "FTM_CONTROL", [ "Valid", "TriggerOn" ] ],
1079 [ "FAD_CONTROL", [ "Connected", "RunInProgress" ] ],
1080 [ "RATE_SCAN", [ "Connected" ] ],
1081 [ "RATE_CONTROL", [ "Connected", "GlobalThresholdSet", "InProgress" ] ],
1082 [ "GPS_CONTROL", [ "Locked" ] ],
1083 [ "SQM_CONTROL", [ "Disconnected", "Connected", "Valid" ] ],
1084 [ "PFMINI_CONTROL", [ "Disconnected", "Connected", "Receiving" ] ],
1085 [ "BIAS_TEMP", [ "Valid" ] ],
1086 [ "SCHEDULER", [ /*"Connected",*/ "Armed" ] ],
1087 ];
1088
1089
1090 if (!checkStates(table))
1091 {
1092 throw new Error("Something unexpected has happened. One of the servers "+
1093 "is in a state in which it should not be. Please,"+
1094 "try to find out what happened...");
1095 }
1096
1097 datalogger_subscriptions.check();
1098
1099 // If this is an observation which needs the voltage to be swicthed on
1100 // skip that if the voltage is not stable
1101 /*
1102 if (obs[sub].task=="DATA" || obs[sub].task=="RATESCAN")
1103 {
1104 var state = dim.state("FEEDBACK").name;
1105 if (state=="Warning" || state=="Critical" || state=="OnStandby")
1106 {
1107 v8.sleep(1000);
1108 continue;
1109 }
1110 }*/
1111
1112
1113 // Check if obs.task is one of the one-time-tasks
1114 switch (obs[sub].task)
1115 {
1116 case "IDLE":
1117 v8.sleep(5000);
1118 continue;
1119
1120 case "SUSPEND":
1121 case "SLEEP":
1122 Shutdown("unlock"); //GoToSleep();
1123
1124 dim.log("Task finished ["+obs[sub].task+"].");
1125 console.out("");
1126 sub++;
1127 continue;
1128
1129 case "STARTUP":
1130 CloseLid();
1131
1132 doDrsCalibration("startup"); // will switch the voltage off
1133
1134 if (irq)
1135 break;
1136
1137 service_feedback.voltageOn();
1138 service_feedback.waitForVoltageOn();
1139
1140 // Before we can switch to 3000 we have to make the right DRS calibration
1141 dim.log("Taking single p.e. run.");
1142 while (!irq && !takeRun("single-pe", 10000));
1143
1144 // It is unclear what comes next, so we better switch off the voltage
1145 service_feedback.voltageOff();
1146
1147 system_on = true;
1148 dim.log("Task finished [STARTUP]");
1149 console.out("");
1150 break;
1151
1152 case "SHUTDOWN":
1153 Shutdown("singlepe");
1154 system_on = false;
1155
1156 // FIXME: Avoid new observations after a shutdown until
1157 // the next startup (set run back to -2?)
1158 sub++;
1159 dim.log("Task finished [SHUTDOWN]");
1160 console.out("");
1161 //console.out(" Waiting for next startup.", "");
1162 continue;
1163
1164 case "DRSCALIB":
1165 doDrsCalibration("drscalib"); // will switch the voltage off
1166 dim.log("Task finished [DRSCALIB]");
1167 console.out("");
1168 break;
1169
1170 case "SINGLEPE":
1171 // The lid must be closes
1172 CloseLid();
1173
1174 // Check if DRS calibration is necessary
1175 var diff = getTimeSinceLastDrsCalib();
1176 if (diff>30 || diff==null)
1177 {
1178 doDrsCalibration("singlepe"); // will turn voltage off
1179 if (irq)
1180 break;
1181 }
1182
1183 // The voltage must be on
1184 service_feedback.voltageOn();
1185 service_feedback.waitForVoltageOn();
1186
1187 // Before we can switch to 3000 we have to make the right DRS calibration
1188 dim.log("Taking single p.e. run.");
1189 while (!irq && !takeRun("single-pe", 10000));
1190
1191 // It is unclear what comes next, so we better switch off the voltage
1192 service_feedback.voltageOff();
1193 dim.log("Task finished [SINGLE-PE]");
1194 console.out("");
1195 break;
1196
1197 case "OVTEST":
1198 var locked = dim.state("DRIVE_CONTROL").name=="Locked";
1199 if (!locked)
1200 dim.send("DRIVE_CONTROL/PARK");
1201
1202 dim.send("FEEDBACK/STOP");
1203
1204 // The lid must be closed
1205 CloseLid();
1206
1207 if (!locked)
1208 {
1209 //console.out("Waiting for telescope to park. This may take a while.");
1210 dim.wait("DRIVE_CONTROL", "Locked", 3000);
1211 dim.send("DRIVE_CONTROL/UNLOCK");
1212 }
1213
1214 // Check if DRS calibration is necessary
1215 var diff = getTimeSinceLastDrsCalib();
1216 if (diff>30 || diff==null)
1217 {
1218 doDrsCalibration("ovtest"); // will turn voltage off
1219 if (irq)
1220 break;
1221 }
1222
1223 // The voltage must be on
1224 service_feedback.voltageOn(0.4);
1225 service_feedback.waitForVoltageOn();
1226
1227 dim.log("Taking single p.e. run (0.4V)");
1228 while (!irq && !takeRun("single-pe", 10000));
1229
1230 for (var i=5; i<18 && !irq; i++)
1231 {
1232 dim.send("FEEDBACK/STOP");
1233 dim.wait("FEEDBACK", "Calibrated", 3000);
1234 dim.wait("BIAS_CONTROL", "VoltageOn", 3000);
1235 dim.send("FEEDBACK/START", i*0.1);
1236 dim.wait("FEEDBACK", "InProgress", 45000);
1237 dim.wait("BIAS_CONTROL", "VoltageOn", 60000); // FIXME: 30000?
1238 service_feedback.waitForVoltageOn();
1239 dim.log("Taking single p.e. run ("+(i*0.1)+"V)");
1240 while (!irq && !takeRun("single-pe", 10000));
1241 }
1242
1243 // It is unclear what comes next, so we better switch off the voltage
1244 service_feedback.voltageOff();
1245 dim.log("Task finished [OVTEST]");
1246 console.out("");
1247 break;
1248
1249 case "RATESCAN":
1250 var tm1 = new Date();
1251
1252 // This is a workaround to make sure that we really catch
1253 // the new OnTrack state later and not the old one
1254 dim.send("DRIVE_CONTROL/STOP");
1255 dim.wait("DRIVE_CONTROL", "Initialized", 15000);
1256
1257 // The lid must be open
1258 OpenLid();
1259
1260 // Switch the voltage to a reduced level (Ubd)
1261 service_feedback.voltageOn(0);
1262
1263 if (obs[sub].source != null) // undefined != null -> false
1264 {
1265 dim.log("Pointing telescope to '"+obs[sub].source+"'.");
1266 dim.send("DRIVE_CONTROL/TRACK_ON", obs[sub].source);
1267 }
1268 else
1269 {
1270 dim.log("Pointing telescope to ra="+obs[sub].ra+" dec="+obs[sub].dec);
1271 dim.send("DRIVE_CONTROL/TRACK", obs[sub].ra, obs[sub].dec);
1272 }
1273
1274 dim.wait("DRIVE_CONTROL", "OnTrack", 150000); // 110s for turning and 30s for stabilizing
1275
1276 // Now tracking stable, switch voltage to nominal level and wait
1277 // for stability.
1278 service_feedback.voltageOn();
1279 service_feedback.waitForVoltageOn();
1280
1281 if (!irq)
1282 {
1283 dim.log("Starting calibration.");
1284
1285 // Calibration (2% of 20')
1286 while (!irq)
1287 {
1288 if (irq || !takeRun("pedestal", 1000)) // 80 Hz -> 10s
1289 continue;
1290 //if (irq || !takeRun("light-pulser-ext", 1000)) // 80 Hz -> 10s
1291 // continue;
1292 break;
1293 }
1294
1295 var tm2 = new Date();
1296
1297 dim.log("Starting ratescan.");
1298
1299 //set reference to whole camera (in case it was changed)
1300 dim.send("RATE_SCAN/SET_REFERENCE_CAMERA");
1301 // Start rate scan
1302 dim.send("RATE_SCAN/START_THRESHOLD_SCAN", 50, 1000, -10, "default");
1303
1304 // Lets wait if the ratescan really starts... this might take a few
1305 // seconds because RATE_SCAN configures the ftm and is waiting for
1306 // it to be configured.
1307 dim.wait("RATE_SCAN", "InProgress", 10000);
1308 dim.wait("RATE_SCAN", "Connected", 2700000);
1309
1310 // Here one could implement a watchdog for the feedback as well, but what is the difference
1311 // whether finally one has to find out if the feedback was in the correct state
1312 // or the ratescan was interrupted?
1313
1314 // this line is actually some kind of hack.
1315 // after the Ratescan, no data is written to disk. I don't know why, but it happens all the time
1316 // So I decided to put this line here as a kind of patchwork....
1317 //dim.send("FAD_CONTROL/SET_FILE_FORMAT", 6);
1318
1319 dim.log("Ratescan done [%.1fs, %.1fs]".$((tm2-tm1)/1000, (new Date()-tm2)/1000));
1320 }
1321
1322 dim.log("Task finished [RATESCAN]");
1323 console.out("");
1324 break; // case "RATESCAN"
1325
1326 case "RATESCAN2":
1327 var tm1 = new Date();
1328
1329 // This is a workaround to make sure that we really catch
1330 // the new OnTrack state later and not the old one
1331 dim.send("DRIVE_CONTROL/STOP");
1332 dim.wait("DRIVE_CONTROL", "Initialized", 15000);
1333
1334 if (obs[sub].rstype=="dark-bias-off")
1335 service_feedback.voltageOff();
1336 else
1337 {
1338 // Switch the voltage to a reduced level (Ubd)
1339 var bias = dim.state("BIAS_CONTROL").name;
1340 if (bias=="VoltageOn" || bias=="Ramping")
1341 service_feedback.voltageOn(0);
1342 }
1343
1344 // Open the lid if required
1345 if (!obs[sub].lidclosed)
1346 OpenLid();
1347 else
1348 CloseLid();
1349
1350 // track source/position or move to position
1351 if (obs[sub].lidclosed)
1352 {
1353 dim.log("Moving telescope to zd="+obs[sub].zd+" az="+obs[sub].az);
1354 dim.send("DRIVE_CONTROL/MOVE_TO", obs[sub].zd, obs[sub].az);
1355 v8.sleep(3000);
1356 dim.wait("DRIVE_CONTROL", "Initialized", 150000); // 110s for turning and 30s for stabilizing
1357 }
1358 else
1359 {
1360 if (obs[sub].source != null) // undefined != null -> false
1361 {
1362 dim.log("Pointing telescope to '"+obs[sub].source+"'.");
1363 dim.send("DRIVE_CONTROL/TRACK_ON", obs[sub].source);
1364 }
1365 else
1366 {
1367 dim.log("Pointing telescope to ra="+obs[sub].ra+" dec="+obs[sub].dec);
1368 dim.send("DRIVE_CONTROL/TRACK", obs[sub].ra, obs[sub].dec);
1369 }
1370
1371 dim.wait("DRIVE_CONTROL", "OnTrack", 150000); // 110s for turning and 30s for stabilizing
1372 }
1373
1374 // Now tracking stable, switch voltage to nominal level and wait
1375 // for stability.
1376 if (obs[sub].rstype!="dark-bias-off")
1377 {
1378 service_feedback.voltageOn();
1379 service_feedback.waitForVoltageOn();
1380 }
1381
1382 if (!irq)
1383 {
1384 var tm2 = new Date();
1385
1386 dim.log("Starting ratescan 2/1 ["+obs[sub].rstype+"]");
1387
1388 //set reference to whole camera (in case it was changed)
1389 dim.send("RATE_SCAN/SET_REFERENCE_CAMERA");
1390 // Start rate scan
1391 dim.send("RATE_SCAN/START_THRESHOLD_SCAN", 50, 300, 20, obs[sub].rstype);
1392
1393 // Lets wait if the ratescan really starts... this might take a few
1394 // seconds because RATE_SCAN configures the ftm and is waiting for
1395 // it to be configured.
1396 dim.wait("RATE_SCAN", "InProgress", 10000);
1397 //FIXME: discuss what best value is here
1398 dim.wait("RATE_SCAN", "Connected", 2700000);//45min
1399 //dim.wait("RATE_SCAN", "Connected", 1200000);//3.3h
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/1 done [%.1fs, %.1fs]".$((tm2-tm1)/1000, (new Date()-tm2)/1000));
1411 }
1412
1413 if (!irq)
1414 {
1415 var tm2 = new Date();
1416
1417 dim.log("Starting ratescan 2/2 ["+obs[sub].rstype+"]");
1418
1419 // Start rate scan
1420 dim.send("RATE_SCAN/START_THRESHOLD_SCAN", 300, 1000, 100, obs[sub].rstype);
1421
1422 // Lets wait if the ratescan really starts... this might take a few
1423 // seconds because RATE_SCAN configures the ftm and is waiting for
1424 // it to be configured.
1425 dim.wait("RATE_SCAN", "InProgress", 10000);
1426 dim.wait("RATE_SCAN", "Connected", 2700000);
1427
1428 // Here one could implement a watchdog for the feedback as well, but what is the difference
1429 // whether finally one has to find out if the feedback was in the correct state
1430 // or the ratescan was interrupted?
1431
1432 // this line is actually some kind of hack.
1433 // after the Ratescan, no data is written to disk. I don't know why, but it happens all the time
1434 // So I decided to put this line here as a kind of patchwork....
1435 //dim.send("FAD_CONTROL/SET_FILE_FORMAT", 6);
1436
1437 dim.log("Ratescan 2/2 done [%.1fs, %.1fs]".$((tm2-tm1)/1000, (new Date()-tm2)/1000));
1438 }
1439
1440 dim.log("Task finished [RATESCAN2]");
1441 console.out("");
1442 break; // case "RATESCAN2"
1443
1444 case "CUSTOM":
1445
1446 // This is a workaround to make sure that we really catch
1447 // the new OnTrack state later and not the old one
1448 dim.send("DRIVE_CONTROL/STOP");
1449 dim.wait("DRIVE_CONTROL", "Initialized", 15000);
1450
1451 // Ramp bias if needed
1452 if (!obs[sub].biason)
1453 service_feedback.voltageOff();
1454 else
1455 {
1456 // Switch the voltage to a reduced level (Ubd)
1457 var bias = dim.state("BIAS_CONTROL").name;
1458 if (bias=="VoltageOn" || bias=="Ramping")
1459 service_feedback.voltageOn(0);
1460 }
1461 // Close lid
1462 CloseLid();
1463
1464 // Move to position (zd/az)
1465 dim.log("Moving telescope to zd="+obs[sub].zd+" az="+obs[sub].az);
1466 dim.send("DRIVE_CONTROL/MOVE_TO", obs[sub].zd, obs[sub].az);
1467 v8.sleep(3000);
1468 dim.wait("DRIVE_CONTROL", "Initialized", 150000); // 110s for turning and 30s for stabilizing
1469
1470 // Now tracking stable, switch voltage to nominal level and wait
1471 // for stability.
1472 if (obs[sub].biason)
1473 {
1474 service_feedback.voltageOn();
1475 service_feedback.waitForVoltageOn();
1476 }
1477
1478 if (!irq)
1479 {
1480 dim.log("Taking custom run with time "+obs[sub].time+"s, threshold="+obs[sub].threshold+", biason="+obs[sub].biason);
1481
1482 var customRun = function()
1483 {
1484 v8.sleep(500);//wait that configuration is set
1485 dim.wait("FTM_CONTROL", "TriggerOn", 15000);
1486 dim.send("FAD_CONTROL/SEND_SINGLE_TRIGGER");
1487 dim.send("RATE_CONTROL/STOP");
1488 dim.send("FTM_CONTROL/STOP_TRIGGER");
1489 dim.wait("FTM_CONTROL", "Valid", 3000);
1490 dim.send("FTM_CONTROL/ENABLE_TRIGGER", true);
1491 dim.send("FTM_CONTROL/SET_TIME_MARKER_DELAY", 123);
1492 dim.send("FTM_CONTROL/SET_THRESHOLD", -1, obs[sub].threshold);
1493 v8.sleep(500);//wait that configuration is set
1494 dim.send("FTM_CONTROL/START_TRIGGER");
1495 dim.wait("FTM_CONTROL", "TriggerOn", 15000);
1496 }
1497
1498 takeRun("custom", -1, obs[sub].time, customRun);
1499 }
1500 dim.log("Task finished [CUSTOM].");
1501 dim.log("");
1502 break; // case "CUSTOM"
1503
1504 case "DATA":
1505
1506 // ========================== case "DATA" ============================
1507 /*
1508 if (Sun.horizon("FACT").isUp)
1509 {
1510 console.out(" SHUTDOWN","");
1511 Shutdown();
1512 console.out(" Exit forced due to broken schedule", "");
1513 exit();
1514 }
1515 */
1516
1517 // Calculate remaining time for this observation in minutes
1518 var remaining = nextObs==undefined ? 0 : (nextObs.start-new Date())/60000;
1519 //dim.log("DEBUG: remaining: "+remaining+" nextObs="+nextObs+" start="+nextObs.start);
1520
1521 // ------------------------------------------------------------
1522
1523 dim.log("Run count "+run+" [remaining "+parseInt(remaining)+"min]");
1524
1525 // ----- Time since last DRS Calibration [min] ------
1526 var diff = getTimeSinceLastDrsCalib();
1527
1528 // Changine pointing position and take calibration...
1529 // ...every four runs (every ~20min)
1530 // ...if at least ten minutes of observation time are left
1531 // ...if this is the first run on the source
1532 var point = (run%4==0 && remaining>10 && !obs[sub].orbit) || run==0; // undefined==null -> true!
1533
1534 // Take DRS Calib...
1535 // ...every four runs (every ~20min)
1536 // ...at last every two hours
1537 // ...when DRS temperature has changed by more than 2deg (?)
1538 // ...when more than 15min of observation are left
1539 // ...no drs calibration was done yet
1540 var drscal = (run%4==0 && (remaining>15 && diff>70)) || diff==null;
1541
1542 if (point)
1543 {
1544 // Switch the voltage to a reduced voltage level
1545 if (!obs[sub].grb)
1546 service_feedback.voltageOn(0);
1547
1548 // Change wobble position every four runs,
1549 // start with alternating wobble positions each day
1550 var wobble = (parseInt(run/4) + parseInt(new Date()/1000/3600/24-0.5))%2+1;
1551 var angle = obs[sub].angle == null ? Math.random()*360 : obs[sub].angle;
1552
1553 if (obs[sub].orbit) // != undefined, != null, != 0
1554 dim.log("Pointing telescope to '"+obs[sub].source+"' [orbit="+obs[sub].orbit+"min, angle="+angle+"]");
1555 else
1556 dim.log("Pointing telescope to '"+obs[sub].source+"' [wobble="+wobble+"]");
1557
1558 // This is a workaround to make sure that we really catch
1559 // the new OnTrack state later and not the old one
1560 dim.send("DRIVE_CONTROL/STOP");
1561 dim.wait("DRIVE_CONTROL", "Initialized", 15000);
1562
1563 if (triggerReloadSources) // It's all synchronous - no need to wait here
1564 {
1565 dim.send("DRIVE_CONTROL/RELOAD_SOURCES");
1566 triggerReloadSources = false;
1567 dim.log("Reloading source table triggered in drivectrl.");
1568 }
1569
1570 if (obs[sub].orbit) // != undefined, != null, != 0
1571 dim.send("DRIVE_CONTROL/TRACK_ORBIT", angle, obs[sub].orbit, obs[sub].source);
1572 else
1573 dim.send("DRIVE_CONTROL/TRACK_WOBBLE", wobble, obs[sub].source);
1574
1575 // Do we have to check if the telescope is really moving?
1576 // We can cross-check the SOURCE service later
1577 }
1578
1579 if (drscal && !obs[sub].nodrs)
1580 {
1581 doDrsCalibration("data"); // will turn voltage off
1582 }
1583
1584 // Now we switch on the voltage and a significant amount of
1585 // time has been passed, so do the check again.
1586 sun = Sun.horizon(-12);
1587 if (!was_up && sun.isUp)
1588 {
1589 dim.log("Sun rise detected....");
1590 continue;
1591 }
1592
1593 if (irq)
1594 continue;
1595
1596 OpenLid(obs[sub].grb);
1597
1598 // This is now the right time to wait for the drive to be stable
1599 if (!obs[sub].grb)
1600 dim.wait("DRIVE_CONTROL", "OnTrack", 150000); // 110s for turning and 30s for stabilizing
1601 else
1602 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; });
1603
1604 // Now check the voltage... (do not start a lot of stuff just to do nothing)
1605 var state = dim.state("FEEDBACK").name;
1606 if (state=="Warning" || state=="Critical" || state=="OnStandby")
1607 {
1608 v8.sleep(60000);
1609 continue;
1610 }
1611
1612 // Now we are 'OnTrack', so we can ramp to nominal voltage
1613 // and wait for the feedback to get stable
1614 //if (!obs[sub].grb || dim.state("FEEDBACK").name!="InProgress")
1615 service_feedback.voltageOn();
1616 if (!obs[sub].grb)
1617 service_feedback.waitForVoltageOn();
1618
1619 // For the first run to be taken (ratecontrol)
1620 // Lid must be != Closed
1621 // Drive must be >= Moving
1622 // Setting the threshold can take 2-3 seconds
1623
1624 if (obs[sub].grb && run==0)
1625 {
1626 // Instead of a pedestal run, we take a very short grb mode run
1627 // which is a classical data run but does not change the thresholds
1628 // This gives the voltages (typ. 5s) and currents (typ. 3s) time to
1629 // stabilize and threshold setting for the next run will be
1630 // reliable and fast but we have data already
1631 dim.log("Starting GRB mode.");
1632
1633 // Whatever we do... it does not make sense to start with a closed lid
1634 // If the lid is not yet open, wait for the lid to be open and
1635 // go on as usual.
1636 if (dim.state("LID_CONTROL").name!="Open")
1637 {
1638 dim.log("Waiting for an open lid.");
1639 dim.wait("LID_CONTROL", "Open", 30000);
1640 service_feedback.waitForVoltageOn();
1641 }
1642
1643 // Doing this manually makes it more flexible but turns off
1644 // automatic Critical mode checking of the feedback and
1645 // automatic reconnect
1646 var nextrun = sub_startrun.get().obj['next'];
1647 dim.log("Take run %3d".$(nextrun)+" [grb-mode]");
1648
1649 dim.send("MCP/START", -1, -1, "grb"); // Use previous threshold settings if ratecontrol "InProgress"
1650 dim.wait("MCP", "TakingData", 15000);
1651
1652 dim.wait("FEEDBACK", "InProgress", 45000); // This is most likely the first to happen
1653 dim.wait("DRIVE_CONTROL", "OnTrack", 150000); // 110s for turning and 30s for stabilizing
1654
1655 v8.sleep(1000); // By now we should have collected the required three current events in FEEDBACK
1656 // Current are averaged over 10s. So by now we should have a reasonable idea of the brightness of the sky
1657 // Individual pixels might still suffer wrong settings
1658 // Starting a new run takes less than 2s (for 60s runs this is 3%)
1659 }
1660
1661 // If pointing had changed, do calibration
1662 if (!irq && point && !obs[sub].grb)
1663 {
1664 dim.log("Starting calibration.");
1665
1666 // Calibration (2% of 20')
1667 while (!irq)
1668 {
1669 if (irq || !takeRun("pedestal", 1000)) // 80 Hz -> 10s
1670 continue;
1671// if (irq || !takeRun("light-pulser-ext", 1000)) // 80 Hz -> 10s
1672// continue;
1673 break;
1674 }
1675 }
1676
1677 //console.out(" Taking data: start [5min]");
1678
1679 // FIXME: What do we do if during calibration something has happened
1680 // e.g. drive went to ERROR? Maybe we have to check all states again?
1681
1682 var twilight = Sun.horizon(-16).isUp;
1683
1684 if (twilight || (obs[sub].grb && run<4))
1685 {
1686 for (var i=0; i<5 && !irq; i++)
1687 takeRun("data", -1, 60); // Take data (1min)
1688 }
1689 else
1690 {
1691 var len = 300;
1692 while (!irq && len>15)
1693 {
1694 var time = new Date();
1695 if (takeRun("data", -1, len)) // Take data (5min)
1696 break;
1697
1698 len -= parseInt((new Date()-time)/1000);
1699 }
1700 }
1701
1702 //console.out(" Taking data: done");
1703 run++;
1704
1705 continue; // case "DATA"
1706 }
1707
1708 if (nextObs!=undefined && sub==obs.length-1)
1709 dim.log("Next observation will start at "+nextObs.start.toUTCString()+" [id="+nextObs.id+"]");
1710
1711 sub++;
1712}
1713
1714sub_drsruns.close();
1715
1716dim.log("Left main loop [irq="+irq+"]");
1717
1718// ================================================================
1719// Comments and ToDo goes here
1720// ================================================================
1721
1722// error handline : http://www.sitepoint.com/exceptional-exception-handling-in-javascript/
1723// classes: http://www.phpied.com/3-ways-to-define-a-javascript-class/
Note: See TracBrowser for help on using the repository browser.