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

Last change on this file since 19713 was 19709, checked in by tbretz, 5 years ago
Added new GTC dust.
File size: 56.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 console.out(" DeltaUov=%.3f (%.3f) [N(>0.033V)=%d]".$(avg, avg-this.last, cnt));
317
318 this.ok = cnt<3;// || (this.last!=undefined && Math.abs(this.last-avg)<0.002);
319 this.last = avg;
320}
321
322service_feedback.voltageOff = function()
323{
324 var state = dim.state("BIAS_CONTROL").name;
325
326 if (state=="Disconnected")
327 {
328 console.out(" Voltage off: bias crate disconnected!");
329 return;
330 }
331
332 // check of feedback has to be switched on
333 var isOn = state=="VoltageOn" || state=="Ramping";
334 if (isOn)
335 {
336 dim.log("Switching voltage off.");
337
338 if (dim.state("FTM_CONTROL").name=="TriggerOn")
339 {
340 dim.send("FTM_CONTROL/STOP_TRIGGER");
341 dim.wait("FTM_CONTROL", "Valid", 3000);
342 }
343
344 // Supress the possibility that the bias control is
345 // ramping and will reject the command to switch the
346 // voltage off
347 //dim.send("FEEDBACK/STOP");
348 //dim.wait("FEEDBACK", "Calibrated", 3000);
349
350 // Make sure we are not in Ramping anymore
351 //dim.wait("BIAS_CONTROL", "VoltageOn", 3000);
352
353 // Switch voltage off
354 dim.send("BIAS_CONTROL/SET_ZERO_VOLTAGE");
355 }
356
357 dim.wait("BIAS_CONTROL", "VoltageOff", 60000); // FIXME: 30000?
358 dim.wait("FEEDBACK", "Calibrated", 3000);
359
360 // FEEDBACK stays in CurrentCtrl when Voltage is off but output enabled
361 // dim.wait("FEEDBACK", "CurrentCtrlIdle", 1000);
362
363 if (isOn)
364 dim.log("Voltage off.");
365}
366
367// DN: The name of the method voltageOn() in the context of the method
368// voltageOff() is a little bit misleading, since when voltageOff() returns
369// the caller can be sure the voltage is off, but when voltageOn() return
370// this is not the case, in the sense, that the caller can now take data.
371// instead the caller of voltageOn() *must* call waitForVoltageOn() afterwards
372// in order to safely take good-quality data.
373// This could lead to nasty bugs in the sense, that the second call might
374// be forgotten by somebody
375//
376// so I suggest to rename voltageOn() --> prepareVoltageOn()
377// waitForVoltageOn() stays as it is
378// and one creates a third method called:voltageOn() like this
379/* service_feedback.voltageOn = function()
380 * {
381 * this.prepareVoltageOn();
382 * this.waitForVoltageOn();
383 * }
384 *
385 * */
386// For convenience.
387
388service_feedback.voltageOn = function(ov)
389{
390 if (isNaN(ov))
391 ov = 1.1;
392
393 if (this.ov!=ov && dim.state("FEEDBACK").name=="InProgress") // FIXME: Warning, OnStandby, Critical if (ov<this.ov)
394 {
395 dim.log("Stoping feedback.");
396 if (dim.state("FTM_CONTROL").name=="TriggerOn")
397 {
398 dim.send("FTM_CONTROL/STOP_TRIGGER");
399 dim.wait("FTM_CONTROL", "Valid", 3000);
400 }
401
402 dim.send("FEEDBACK/STOP");
403 dim.wait("FEEDBACK", "Calibrated", 3000);
404
405 // Make sure we are not in Ramping anymore
406 dim.wait("BIAS_CONTROL", "VoltageOn", 3000);
407 }
408
409 var isOff = dim.state("FEEDBACK").name=="Calibrated";
410 if (isOff)
411 {
412 dim.log("Switching voltage to Uov="+ov+"V.");
413
414 dim.send("FEEDBACK/START", ov);
415
416 // FIXME: We could miss "InProgress" if it immediately changes to "Warning"
417 // Maybe a dim.timeout state>8 ?
418 dim.wait("FEEDBACK", "InProgress", 45000);
419
420 this.ov = ov;
421 }
422
423 // Wait until voltage on
424 dim.wait("BIAS_CONTROL", "VoltageOn", 60000); // FIXME: 30000?
425}
426
427service_feedback.waitForVoltageOn = function()
428{
429 // Avoid output if condition is already fulfilled
430 dim.log("Waiting for voltage to be stable.");
431
432 function func()
433 {
434 if (irq || this.ok==true)
435 return true;
436 }
437
438 var now = new Date();
439
440 this.last = undefined;
441 this.ok = false;
442 v8.timeout(4*60000, func, this); // FIMXE: Remove 4!
443 this.ok = undefined;
444
445 if (irq)
446 dim.log("Waiting for stable voltage interrupted.");
447 else
448 dim.log("Voltage stable within limits");
449}
450
451// ================================================================
452// Function to shutdown the system
453// ================================================================
454
455function Shutdown(type)
456{
457 if (!type)
458 type = "default";
459
460 dim.log("Starting shutdown ["+type+"].");
461
462 var now1 = new Date();
463
464 var bias = dim.state("BIAS_CONTROL").name;
465 if (bias=="VoltageOn" || bias=="Ramping")
466 service_feedback.voltageOn(0);
467
468 CloseLid();
469
470 var now2 = new Date();
471
472 dim.send("DRIVE_CONTROL/PARK");
473
474 console.out("","Waiting for telescope to park. This may take a while.");
475
476 // FIXME: This might not work is the drive is already close to park position
477 //dim.wait("DRIVE_CONTROL", "Parking", 3000);
478
479 /*
480 // Check if DRS calibration is necessary
481 var diff = getTimeSinceLastDrsCalib();
482 if (diff>30 || diff==null)
483 {
484 doDrsCalibration("singlepe"); // will turn voltage off
485 if (irq)
486 break;
487 }*/
488
489 //take single pe run if required
490 if (type=="singlepe")
491 {
492 dim.log("Taking single-pe run.");
493
494 // The voltage must be on
495 service_feedback.voltageOn();
496 service_feedback.waitForVoltageOn();
497
498 // Before we can switch to 3000 we have to make the right DRS calibration
499 dim.log("Taking single p.e. run.");
500 while (!irq && !takeRun("single-pe", 10000));
501
502 /*
503 Maybe we need to send a trigger... but data runs contain pedestal triggers... so it should work in any case...
504 var customRun = function()
505 {
506 v8.sleep(500);//wait that configuration is set
507 dim.wait("FTM_CONTROL", "TriggerOn", 15000);
508 dim.send("FAD_CONTROL/SEND_SINGLE_TRIGGER");
509 dim.send("RATE_CONTROL/STOP");
510 dim.send("FTM_CONTROL/STOP_TRIGGER");
511 dim.wait("FTM_CONTROL", "Valid", 3000);
512 dim.send("FTM_CONTROL/ENABLE_TRIGGER", true);
513 dim.send("FTM_CONTROL/SET_TIME_MARKER_DELAY", 123);
514 dim.send("FTM_CONTROL/SET_THRESHOLD", -1, obs[sub].threshold);
515 v8.sleep(500);//wait that configuration is set
516 dim.send("FTM_CONTROL/START_TRIGGER");
517 dim.wait("FTM_CONTROL", "TriggerOn", 15000);
518 }*/
519 }
520
521 //wait until drive is in locked (after it reached park position)
522 dim.wait("DRIVE_CONTROL", "Locked", 150000);
523
524 //unlock drive if task was sleep
525 if (type=="unlock")
526 dim.send("DRIVE_CONTROL/UNLOCK");
527
528
529 // It is unclear what comes next, so we better switch off the voltage
530 service_feedback.voltageOff();
531
532 dim.log("Finishing shutdown.");
533
534 var now3 = new Date();
535
536 dim.send("FTM_CONTROL/STOP_TRIGGER");
537 dim.wait("FTM_CONTROL", "Valid", 3000);
538
539 if (bias!="Disconnected")
540 dim.wait("FEEDBACK", "Calibrated", 3000);
541
542 if (type!="unlock")
543 {
544 dim.send("BIAS_CONTROL/DISCONNECT");
545
546 var pwrctrl_state = dim.state("PWR_CONTROL").name;
547 if (pwrctrl_state=="SystemOn" ||
548 pwrctrl_state=="BiasOff" ||
549 pwrctrl_state=="DriveOn")
550 dim.send("PWR_CONTROL/TOGGLE_DRIVE");
551
552 dim.wait("BIAS_CONTROL", "Disconnected", 3000);
553 dim.wait("PWR_CONTROL", "DriveOff", 6000);
554 }
555
556 var sub = new Subscription("DRIVE_CONTROL/POINTING_POSITION");
557 sub.get(5000); // FIXME: Proper error message in case of failure
558
559 var report = sub.get();
560
561 console.out("");
562 console.out("Shutdown procedure ["+type+"] seems to be finished...");
563 console.out(" "+new Date().toUTCString());
564 console.out(" Telescope at Zd=%.1fdeg Az=%.1fdeg".$(report.obj['Zd'], report.obj['Az']));
565 console.out(" Please check on the web cam that the park position was reached");
566 console.out(" and the telescope is not moving anymore.");
567 console.out(" Please check visually that the lid is really closed and");
568 console.out(" that the biasctrl really switched the voltage off.", "");
569 console.out(" DRIVE_CONTROL: "+dim.state("DRIVE_CONTROL").name);
570 console.out(" FEEDBACK: "+dim.state("FEEDBACK").name);
571 console.out(" FTM_CONTROL: "+dim.state("FTM_CONTROL").name);
572 console.out(" BIAS_CONTROL: "+dim.state("BIAS_CONTROL").name);
573 console.out(" PWR_CONTROL: "+dim.state("PWR_CONTROL").name);
574 console.out("");
575 dim.log("Shutdown: end ["+(now2-now1)/1000+"s, "+(now3-now2)/1000+"s, "+(new Date()-now3)/1000+"s]");
576 console.out("");
577
578 sub.close();
579}
580
581
582// ================================================================
583// Function to set the system to sleep-mode
584// ================================================================
585// FIXME: do not repeat code from shutdown-function
586/*
587function GoToSleep()
588{
589 CloseLid();
590
591 var isArmed = dim.state("DRIVE_CONTROL").name=="Armed";
592 if (!isArmed)
593 {
594 dim.log("Drive not ready to move. -> send STOP");
595 dim.send("DRIVE_CONTROL/STOP");
596 dim.wait("DRIVE_CONTROL", "Armed", 5000);
597 }
598
599 dim.send("DRIVE_CONTROL/MOVE_TO 101 0");//park position
600 var sub = new Subscription("DRIVE_CONTROL/POINTING_POSITION");
601 sub.get(5000); // FIXME: Proper error message in case of failure
602
603 function func()
604 {
605 var report = sub.get();
606
607 var zd = report.obj['Zd'];
608 var az = report.obj['Az'];
609
610 if (zd>100 && Math.abs(az)<1)
611 return true;
612
613 return undefined;
614 }
615
616 try { v8.timeout(150000, func); }
617 catch (e)
618 {
619 var p = sub.get();
620 dim.log('Park position not reached? Telescope at Zd='+p.obj['Zd']+' Az='+p.obj['Az']);
621 }
622 var p2 = sub.get();
623 dim.log('Telescope at Zd=%.1fdeg Az=%.1fdeg'.$(p2.obj['Zd'], p2.obj['Az']));
624 sub.close();
625}
626*/
627
628// ================================================================
629// Check datalogger subscriptions
630// ================================================================
631
632var datalogger_subscriptions = new Subscription("DATA_LOGGER/SUBSCRIPTIONS");
633datalogger_subscriptions.get(3000, false);
634
635datalogger_subscriptions.check = function()
636{
637 var obj = this.get();
638 if (!obj.data)
639 throw new Error("DATA_LOGGER/SUBSCRIPTIONS not available.");
640
641 var expected =
642 [
643 "AGILENT_CONTROL_24V/DATA",
644 "AGILENT_CONTROL_50V/DATA",
645 "AGILENT_CONTROL_80V/DATA",
646 "BIAS_CONTROL/CURRENT",
647 "BIAS_CONTROL/DAC",
648 "BIAS_CONTROL/NOMINAL",
649 "BIAS_CONTROL/VOLTAGE",
650 "DRIVE_CONTROL/POINTING_POSITION",
651 "DRIVE_CONTROL/SOURCE_POSITION",
652 "DRIVE_CONTROL/STATUS",
653 "DRIVE_CONTROL/TRACKING_POSITION",
654 "FAD_CONTROL/CONNECTIONS",
655 "FAD_CONTROL/DAC",
656 "FAD_CONTROL/DNA",
657 "FAD_CONTROL/DRS_RUNS",
658 "FAD_CONTROL/EVENTS",
659 "FAD_CONTROL/FEEDBACK_DATA",
660 "FAD_CONTROL/FILE_FORMAT",
661 "FAD_CONTROL/FIRMWARE_VERSION",
662 "FAD_CONTROL/INCOMPLETE",
663 "FAD_CONTROL/PRESCALER",
664 "FAD_CONTROL/REFERENCE_CLOCK",
665 "FAD_CONTROL/REGION_OF_INTEREST",
666 "FAD_CONTROL/RUNS",
667 "FAD_CONTROL/RUN_NUMBER",
668 "FAD_CONTROL/START_RUN",
669 "FAD_CONTROL/STATISTICS1",
670 "FAD_CONTROL/STATS",
671 "FAD_CONTROL/STATUS",
672 "FAD_CONTROL/TEMPERATURE",
673 "FEEDBACK/CALIBRATED_CURRENTS",
674 "FEEDBACK/CALIBRATION",
675 "FEEDBACK/CALIBRATION_R8",
676 "FEEDBACK/CALIBRATION_STEPS",
677/* "FEEDBACK/REFERENCE",*/
678 "FSC_CONTROL/CURRENT",
679 "FSC_CONTROL/HUMIDITY",
680 "FSC_CONTROL/TEMPERATURE",
681 "FSC_CONTROL/VOLTAGE",
682 "FTM_CONTROL/COUNTER",
683 "FTM_CONTROL/DYNAMIC_DATA",
684 "FTM_CONTROL/ERROR",
685 "FTM_CONTROL/FTU_LIST",
686 "FTM_CONTROL/PASSPORT",
687 "FTM_CONTROL/STATIC_DATA",
688 "FTM_CONTROL/TRIGGER_RATES",
689 "GPS_CONTROL/NEMA",
690 "SQM_CONTROL/DATA",
691 //"LID_CONTROL/DATA",
692 "LID_CONTROL/MOTORS",
693 "MAGIC_LIDAR/DATA",
694 "MAGIC_WEATHER/DATA",
695 "RAIN_SENSOR/DATA",
696 "MCP/CONFIGURATION",
697 "PWR_CONTROL/DATA",
698 "RATE_CONTROL/THRESHOLD",
699 "RATE_SCAN/DATA",
700 "RATE_SCAN/PROCESS_DATA",
701 "TEMPERATURE/DATA",
702 "TIME_CHECK/OFFSET",
703 "TNG_WEATHER/DATA",
704 "TNG_WEATHER/DUST",
705 "GTC_DUST/DATA",
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/PREPARE_GRB"); // STOP + RELOAD_SOURCES
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 if (drive_states && obs[sub].grb)
1054 drive_states.push("Stopping");
1055
1056 // A scheduled task was found, lets check if all servers are
1057 // still only and in reasonable states. If this is not the case,
1058 // something unexpected must have happend and the script is aborted.
1059 //console.out(" Checking states [general]");
1060 var table =
1061 [
1062 [ "GTC_DUST" ],
1063 [ "TNG_WEATHER" ],
1064 [ "MAGIC_WEATHER" ],
1065 [ "RAIN_SENSOR" ],
1066 [ "CHAT" ],
1067 [ "SMART_FACT" ],
1068 [ "TEMPERATURE" ],
1069 [ "DATA_LOGGER", [ "NightlyFileOpen", "WaitForRun", "Logging" ] ],
1070 [ "FSC_CONTROL", [ "Connected" ] ],
1071 [ "MCP", [ "Idle" ] ],
1072 [ "TIME_CHECK", [ "Valid" ] ],
1073 [ "PWR_CONTROL", power_states/*[ "SystemOn" ]*/ ],
1074 [ "AGILENT_CONTROL_24V", [ "VoltageOn" ] ],
1075 [ "AGILENT_CONTROL_50V", [ "VoltageOn" ] ],
1076 //[ "AGILENT_CONTROL_80V", [ "VoltageOn" ] ],
1077 [ "AGILENT_CONTROL_80V", [ "VoltageOn", "Disconnected" ] ], //hack to allow for data taking while agilent not available
1078 [ "BIAS_CONTROL", [ "VoltageOff", "VoltageOn", "Ramping" ] ],
1079 [ "FEEDBACK", [ "Calibrated", "InProgress", "OnStandby", "Warning", "Critical" ] ],
1080 [ "LID_CONTROL", [ "Open", "Closed" ] ],
1081 [ "DRIVE_CONTROL", drive_states/*[ "Armed", "Tracking", "OnTrack" ]*/ ],
1082 [ "FTM_CONTROL", [ "Valid", "TriggerOn" ] ],
1083 [ "FAD_CONTROL", [ "Connected", "RunInProgress" ] ],
1084 [ "RATE_SCAN", [ "Connected" ] ],
1085 [ "RATE_CONTROL", [ "Connected", "GlobalThresholdSet", "InProgress" ] ],
1086 [ "GPS_CONTROL", [ "Locked" ] ],
1087 [ "SQM_CONTROL", [ "Disconnected", "Connected", "Valid" ] ],
1088 [ "PFMINI_CONTROL", [ "Disconnected", "Connected", "Receiving" ] ],
1089 [ "BIAS_TEMP", [ "Valid" ] ],
1090 [ "SCHEDULER", [ /*"Connected",*/ "Armed" ] ],
1091 ];
1092
1093
1094 if (!checkStates(table))
1095 {
1096 throw new Error("Something unexpected has happened. One of the servers "+
1097 "is in a state in which it should not be. Please,"+
1098 "try to find out what happened...");
1099 }
1100
1101 datalogger_subscriptions.check();
1102
1103 // If this is an observation which needs the voltage to be swicthed on
1104 // skip that if the voltage is not stable
1105 /*
1106 if (obs[sub].task=="DATA" || obs[sub].task=="RATESCAN")
1107 {
1108 var state = dim.state("FEEDBACK").name;
1109 if (state=="Warning" || state=="Critical" || state=="OnStandby")
1110 {
1111 v8.sleep(1000);
1112 continue;
1113 }
1114 }*/
1115
1116
1117 // Check if obs.task is one of the one-time-tasks
1118 switch (obs[sub].task)
1119 {
1120 case "IDLE":
1121 v8.sleep(5000);
1122 continue;
1123
1124 case "SUSPEND":
1125 case "SLEEP":
1126 Shutdown("unlock"); //GoToSleep();
1127
1128 dim.log("Task finished ["+obs[sub].task+"].");
1129 console.out("");
1130 sub++;
1131 continue;
1132
1133 case "STARTUP":
1134 CloseLid();
1135
1136 doDrsCalibration("startup"); // will switch the voltage off
1137
1138 if (irq)
1139 break;
1140
1141 service_feedback.voltageOn();
1142 service_feedback.waitForVoltageOn();
1143
1144 // Before we can switch to 3000 we have to make the right DRS calibration
1145 dim.log("Taking single p.e. run.");
1146 while (!irq && !takeRun("single-pe", 10000));
1147
1148 // It is unclear what comes next, so we better switch off the voltage
1149 service_feedback.voltageOff();
1150
1151 system_on = true;
1152 dim.log("Task finished [STARTUP]");
1153 console.out("");
1154 break;
1155
1156 case "SHUTDOWN":
1157 Shutdown("singlepe");
1158 system_on = false;
1159
1160 // FIXME: Avoid new observations after a shutdown until
1161 // the next startup (set run back to -2?)
1162 sub++;
1163 dim.log("Task finished [SHUTDOWN]");
1164 console.out("");
1165 //console.out(" Waiting for next startup.", "");
1166 continue;
1167
1168 case "DRSCALIB":
1169 doDrsCalibration("drscalib"); // will switch the voltage off
1170 dim.log("Task finished [DRSCALIB]");
1171 console.out("");
1172 break;
1173
1174 case "SINGLEPE":
1175 // The lid must be closes
1176 CloseLid();
1177
1178 // Check if DRS calibration is necessary
1179 var diff = getTimeSinceLastDrsCalib();
1180 if (diff>30 || diff==null)
1181 {
1182 doDrsCalibration("singlepe"); // will turn voltage off
1183 if (irq)
1184 break;
1185 }
1186
1187 // The voltage must be on
1188 service_feedback.voltageOn();
1189 service_feedback.waitForVoltageOn();
1190
1191 // Before we can switch to 3000 we have to make the right DRS calibration
1192 dim.log("Taking single p.e. run.");
1193 while (!irq && !takeRun("single-pe", 10000));
1194
1195 // It is unclear what comes next, so we better switch off the voltage
1196 service_feedback.voltageOff();
1197 dim.log("Task finished [SINGLE-PE]");
1198 console.out("");
1199 break;
1200
1201 case "OVTEST":
1202 var locked = dim.state("DRIVE_CONTROL").name=="Locked";
1203 if (!locked)
1204 dim.send("DRIVE_CONTROL/PARK");
1205
1206 dim.send("FEEDBACK/STOP");
1207
1208 // The lid must be closed
1209 CloseLid();
1210
1211 if (!locked)
1212 {
1213 //console.out("Waiting for telescope to park. This may take a while.");
1214 dim.wait("DRIVE_CONTROL", "Locked", 3000);
1215 dim.send("DRIVE_CONTROL/UNLOCK");
1216 }
1217
1218 // Check if DRS calibration is necessary
1219 var diff = getTimeSinceLastDrsCalib();
1220 if (diff>30 || diff==null)
1221 {
1222 doDrsCalibration("ovtest"); // will turn voltage off
1223 if (irq)
1224 break;
1225 }
1226
1227 // The voltage must be on
1228 service_feedback.voltageOn(0.4);
1229 service_feedback.waitForVoltageOn();
1230
1231 dim.log("Taking single p.e. run (0.4V)");
1232 while (!irq && !takeRun("single-pe", 10000));
1233
1234 for (var i=5; i<18 && !irq; i++)
1235 {
1236 dim.send("FEEDBACK/STOP");
1237 dim.wait("FEEDBACK", "Calibrated", 3000);
1238 dim.wait("BIAS_CONTROL", "VoltageOn", 3000);
1239 dim.send("FEEDBACK/START", i*0.1);
1240 dim.wait("FEEDBACK", "InProgress", 45000);
1241 dim.wait("BIAS_CONTROL", "VoltageOn", 60000); // FIXME: 30000?
1242 service_feedback.waitForVoltageOn();
1243 dim.log("Taking single p.e. run ("+(i*0.1)+"V)");
1244 while (!irq && !takeRun("single-pe", 10000));
1245 }
1246
1247 // It is unclear what comes next, so we better switch off the voltage
1248 service_feedback.voltageOff();
1249 dim.log("Task finished [OVTEST]");
1250 console.out("");
1251 break;
1252
1253 case "RATESCAN":
1254 var tm1 = new Date();
1255
1256 // This is a workaround to make sure that we really catch
1257 // the new OnTrack state later and not the old one
1258 dim.send("DRIVE_CONTROL/STOP");
1259 dim.wait("DRIVE_CONTROL", "Initialized", 15000);
1260
1261 // The lid must be open
1262 OpenLid();
1263
1264 // Switch the voltage to a reduced level (Ubd)
1265 service_feedback.voltageOn(0);
1266
1267 if (obs[sub].source != null) // undefined != null -> false
1268 {
1269 dim.log("Pointing telescope to '"+obs[sub].source+"'.");
1270 dim.send("DRIVE_CONTROL/TRACK_ON", obs[sub].source);
1271 }
1272 else
1273 {
1274 dim.log("Pointing telescope to ra="+obs[sub].ra+" dec="+obs[sub].dec);
1275 dim.send("DRIVE_CONTROL/TRACK", obs[sub].ra, obs[sub].dec);
1276 }
1277
1278 dim.wait("DRIVE_CONTROL", "OnTrack", 150000); // 110s for turning and 30s for stabilizing
1279
1280 // Now tracking stable, switch voltage to nominal level and wait
1281 // for stability.
1282 service_feedback.voltageOn();
1283 service_feedback.waitForVoltageOn();
1284
1285 if (!irq)
1286 {
1287 dim.log("Starting calibration.");
1288
1289 // Calibration (2% of 20')
1290 while (!irq)
1291 {
1292 if (irq || !takeRun("pedestal", 1000)) // 80 Hz -> 10s
1293 continue;
1294 //if (irq || !takeRun("light-pulser-ext", 1000)) // 80 Hz -> 10s
1295 // continue;
1296 break;
1297 }
1298
1299 var tm2 = new Date();
1300
1301 dim.log("Starting ratescan.");
1302
1303 //set reference to whole camera (in case it was changed)
1304 dim.send("RATE_SCAN/SET_REFERENCE_CAMERA");
1305 // Start rate scan
1306 dim.send("RATE_SCAN/START_THRESHOLD_SCAN", 50, 1000, -10, "default");
1307
1308 // Lets wait if the ratescan really starts... this might take a few
1309 // seconds because RATE_SCAN configures the ftm and is waiting for
1310 // it to be configured.
1311 dim.wait("RATE_SCAN", "InProgress", 10000);
1312 dim.wait("RATE_SCAN", "Connected", 2700000);
1313
1314 // Here one could implement a watchdog for the feedback as well, but what is the difference
1315 // whether finally one has to find out if the feedback was in the correct state
1316 // or the ratescan was interrupted?
1317
1318 // this line is actually some kind of hack.
1319 // after the Ratescan, no data is written to disk. I don't know why, but it happens all the time
1320 // So I decided to put this line here as a kind of patchwork....
1321 //dim.send("FAD_CONTROL/SET_FILE_FORMAT", 6);
1322
1323 dim.log("Ratescan done [%.1fs, %.1fs]".$((tm2-tm1)/1000, (new Date()-tm2)/1000));
1324 }
1325
1326 dim.log("Task finished [RATESCAN]");
1327 console.out("");
1328 break; // case "RATESCAN"
1329
1330 case "RATESCAN2":
1331 var tm1 = new Date();
1332
1333 // This is a workaround to make sure that we really catch
1334 // the new OnTrack state later and not the old one
1335 dim.send("DRIVE_CONTROL/STOP");
1336 dim.wait("DRIVE_CONTROL", "Initialized", 15000);
1337
1338 if (obs[sub].rstype=="dark-bias-off")
1339 service_feedback.voltageOff();
1340 else
1341 {
1342 // Switch the voltage to a reduced level (Ubd)
1343 var bias = dim.state("BIAS_CONTROL").name;
1344 if (bias=="VoltageOn" || bias=="Ramping")
1345 service_feedback.voltageOn(0);
1346 }
1347
1348 // Open the lid if required
1349 if (!obs[sub].lidclosed)
1350 OpenLid();
1351 else
1352 CloseLid();
1353
1354 // track source/position or move to position
1355 if (obs[sub].lidclosed)
1356 {
1357 dim.log("Moving telescope to zd="+obs[sub].zd+" az="+obs[sub].az);
1358 dim.send("DRIVE_CONTROL/MOVE_TO", obs[sub].zd, obs[sub].az);
1359 v8.sleep(3000);
1360 dim.wait("DRIVE_CONTROL", "Initialized", 150000); // 110s for turning and 30s for stabilizing
1361 }
1362 else
1363 {
1364 if (obs[sub].source != null) // undefined != null -> false
1365 {
1366 dim.log("Pointing telescope to '"+obs[sub].source+"'.");
1367 dim.send("DRIVE_CONTROL/TRACK_ON", obs[sub].source);
1368 }
1369 else
1370 {
1371 dim.log("Pointing telescope to ra="+obs[sub].ra+" dec="+obs[sub].dec);
1372 dim.send("DRIVE_CONTROL/TRACK", obs[sub].ra, obs[sub].dec);
1373 }
1374
1375 dim.wait("DRIVE_CONTROL", "OnTrack", 150000); // 110s for turning and 30s for stabilizing
1376 }
1377
1378 // Now tracking stable, switch voltage to nominal level and wait
1379 // for stability.
1380 if (obs[sub].rstype!="dark-bias-off")
1381 {
1382 service_feedback.voltageOn();
1383 service_feedback.waitForVoltageOn();
1384 }
1385
1386 if (!irq)
1387 {
1388 var tm2 = new Date();
1389
1390 dim.log("Starting ratescan 2/1 ["+obs[sub].rstype+"]");
1391
1392 //set reference to whole camera (in case it was changed)
1393 dim.send("RATE_SCAN/SET_REFERENCE_CAMERA");
1394 // Start rate scan
1395 dim.send("RATE_SCAN/START_THRESHOLD_SCAN", 50, 300, 20, obs[sub].rstype);
1396
1397 // Lets wait if the ratescan really starts... this might take a few
1398 // seconds because RATE_SCAN configures the ftm and is waiting for
1399 // it to be configured.
1400 dim.wait("RATE_SCAN", "InProgress", 10000);
1401 //FIXME: discuss what best value is here
1402 dim.wait("RATE_SCAN", "Connected", 2700000);//45min
1403 //dim.wait("RATE_SCAN", "Connected", 1200000);//3.3h
1404
1405 // Here one could implement a watchdog for the feedback as well, but what is the difference
1406 // whether finally one has to find out if the feedback was in the correct state
1407 // or the ratescan was interrupted?
1408
1409 // this line is actually some kind of hack.
1410 // after the Ratescan, no data is written to disk. I don't know why, but it happens all the time
1411 // So I decided to put this line here as a kind of patchwork....
1412 //dim.send("FAD_CONTROL/SET_FILE_FORMAT", 6);
1413
1414 dim.log("Ratescan 2/1 done [%.1fs, %.1fs]".$((tm2-tm1)/1000, (new Date()-tm2)/1000));
1415 }
1416
1417 if (!irq)
1418 {
1419 var tm2 = new Date();
1420
1421 dim.log("Starting ratescan 2/2 ["+obs[sub].rstype+"]");
1422
1423 // Start rate scan
1424 dim.send("RATE_SCAN/START_THRESHOLD_SCAN", 300, 1000, 100, obs[sub].rstype);
1425
1426 // Lets wait if the ratescan really starts... this might take a few
1427 // seconds because RATE_SCAN configures the ftm and is waiting for
1428 // it to be configured.
1429 dim.wait("RATE_SCAN", "InProgress", 10000);
1430 dim.wait("RATE_SCAN", "Connected", 2700000);
1431
1432 // Here one could implement a watchdog for the feedback as well, but what is the difference
1433 // whether finally one has to find out if the feedback was in the correct state
1434 // or the ratescan was interrupted?
1435
1436 // this line is actually some kind of hack.
1437 // after the Ratescan, no data is written to disk. I don't know why, but it happens all the time
1438 // So I decided to put this line here as a kind of patchwork....
1439 //dim.send("FAD_CONTROL/SET_FILE_FORMAT", 6);
1440
1441 dim.log("Ratescan 2/2 done [%.1fs, %.1fs]".$((tm2-tm1)/1000, (new Date()-tm2)/1000));
1442 }
1443
1444 dim.log("Task finished [RATESCAN2]");
1445 console.out("");
1446 break; // case "RATESCAN2"
1447
1448 case "CUSTOM":
1449
1450 // This is a workaround to make sure that we really catch
1451 // the new OnTrack state later and not the old one
1452 dim.send("DRIVE_CONTROL/STOP");
1453 dim.wait("DRIVE_CONTROL", "Initialized", 15000);
1454
1455 // Ramp bias if needed
1456 if (!obs[sub].biason)
1457 service_feedback.voltageOff();
1458 else
1459 {
1460 // Switch the voltage to a reduced level (Ubd)
1461 var bias = dim.state("BIAS_CONTROL").name;
1462 if (bias=="VoltageOn" || bias=="Ramping")
1463 service_feedback.voltageOn(0);
1464 }
1465 // Close lid
1466 CloseLid();
1467
1468 // Move to position (zd/az)
1469 dim.log("Moving telescope to zd="+obs[sub].zd+" az="+obs[sub].az);
1470 dim.send("DRIVE_CONTROL/MOVE_TO", obs[sub].zd, obs[sub].az);
1471 v8.sleep(3000);
1472 dim.wait("DRIVE_CONTROL", "Initialized", 150000); // 110s for turning and 30s for stabilizing
1473
1474 // Now tracking stable, switch voltage to nominal level and wait
1475 // for stability.
1476 if (obs[sub].biason)
1477 {
1478 service_feedback.voltageOn();
1479 service_feedback.waitForVoltageOn();
1480 }
1481
1482 if (!irq)
1483 {
1484 dim.log("Taking custom run with time "+obs[sub].time+"s, threshold="+obs[sub].threshold+", biason="+obs[sub].biason);
1485
1486 var customRun = function()
1487 {
1488 v8.sleep(500);//wait that configuration is set
1489 dim.wait("FTM_CONTROL", "TriggerOn", 15000);
1490 dim.send("FAD_CONTROL/SEND_SINGLE_TRIGGER");
1491 dim.send("RATE_CONTROL/STOP");
1492 dim.send("FTM_CONTROL/STOP_TRIGGER");
1493 dim.wait("FTM_CONTROL", "Valid", 3000);
1494 dim.send("FTM_CONTROL/ENABLE_TRIGGER", true);
1495 dim.send("FTM_CONTROL/SET_TIME_MARKER_DELAY", 123);
1496 dim.send("FTM_CONTROL/SET_THRESHOLD", -1, obs[sub].threshold);
1497 v8.sleep(500);//wait that configuration is set
1498 dim.send("FTM_CONTROL/START_TRIGGER");
1499 dim.wait("FTM_CONTROL", "TriggerOn", 15000);
1500 }
1501
1502 takeRun("custom", -1, obs[sub].time, customRun);
1503 }
1504 dim.log("Task finished [CUSTOM].");
1505 dim.log("");
1506 break; // case "CUSTOM"
1507
1508 case "DATA":
1509
1510 // ========================== case "DATA" ============================
1511 /*
1512 if (Sun.horizon("FACT").isUp)
1513 {
1514 console.out(" SHUTDOWN","");
1515 Shutdown();
1516 console.out(" Exit forced due to broken schedule", "");
1517 exit();
1518 }
1519 */
1520
1521 // Calculate remaining time for this observation in minutes
1522 var remaining = nextObs==undefined ? 0 : (nextObs.start-new Date())/60000;
1523 //dim.log("DEBUG: remaining: "+remaining+" nextObs="+nextObs+" start="+nextObs.start);
1524
1525 // ------------------------------------------------------------
1526
1527 dim.log("Run count "+run+" [remaining "+parseInt(remaining)+"min]");
1528
1529 // ----- Time since last DRS Calibration [min] ------
1530 var diff = getTimeSinceLastDrsCalib();
1531
1532 // Changine pointing position and take calibration...
1533 // ...every four runs (every ~20min)
1534 // ...if at least ten minutes of observation time are left
1535 // ...if this is the first run on the source
1536 var point = (run%4==0 && remaining>10 && !obs[sub].orbit) || run==0; // undefined==null -> true!
1537
1538 // Take DRS Calib...
1539 // ...every four runs (every ~20min)
1540 // ...at last every two hours
1541 // ...when DRS temperature has changed by more than 2deg (?)
1542 // ...when more than 15min of observation are left
1543 // ...no drs calibration was done yet
1544 var drscal = (run%4==0 && (remaining>15 && diff>70)) || diff==null;
1545
1546 if (point)
1547 {
1548 // Switch the voltage to a reduced voltage level
1549 if (!obs[sub].grb)
1550 service_feedback.voltageOn(0);
1551
1552 // Change wobble position every four runs,
1553 // start with alternating wobble positions each day
1554 var wobble = (parseInt(run/4) + parseInt(new Date()/1000/3600/24-0.5))%2+1;
1555 var angle = obs[sub].angle == null ? Math.random()*360 : obs[sub].angle;
1556
1557 if (obs[sub].orbit) // != undefined, != null, != 0
1558 dim.log("Pointing telescope to '"+obs[sub].source+"' [orbit="+obs[sub].orbit+"min, angle="+angle+"]");
1559 else
1560 dim.log("Pointing telescope to '"+obs[sub].source+"' [wobble="+wobble+"]");
1561
1562 // This is a workaround to make sure that we really catch
1563 // the new OnTrack state later and not the old one
1564 dim.send("DRIVE_CONTROL/STOP");
1565 dim.wait("DRIVE_CONTROL", "Initialized", 15000);
1566
1567 if (triggerReloadSources) // It's all synchronous - no need to wait here
1568 {
1569 dim.send("DRIVE_CONTROL/RELOAD_SOURCES");
1570 triggerReloadSources = false;
1571 dim.log("Reloading source table triggered in drivectrl.");
1572 }
1573
1574 if (obs[sub].orbit) // != undefined, != null, != 0
1575 dim.send("DRIVE_CONTROL/TRACK_ORBIT", angle, obs[sub].orbit, obs[sub].source);
1576 else
1577 dim.send("DRIVE_CONTROL/TRACK_WOBBLE", wobble, obs[sub].source);
1578
1579 // Do we have to check if the telescope is really moving?
1580 // We can cross-check the SOURCE service later
1581 }
1582
1583 if (drscal && !obs[sub].nodrs)
1584 {
1585 doDrsCalibration("data"); // will turn voltage off
1586 }
1587
1588 // Now we switch on the voltage and a significant amount of
1589 // time has been passed, so do the check again.
1590 sun = Sun.horizon(-12);
1591 if (!was_up && sun.isUp)
1592 {
1593 dim.log("Sun rise detected....");
1594 continue;
1595 }
1596
1597 if (irq)
1598 continue;
1599
1600 OpenLid(obs[sub].grb);
1601
1602 // This is now the right time to wait for the drive to be stable
1603 if (!obs[sub].grb)
1604 dim.wait("DRIVE_CONTROL", "OnTrack", 150000); // 110s for turning and 30s for stabilizing
1605 else
1606 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; });
1607
1608 // Now check the voltage... (do not start a lot of stuff just to do nothing)
1609 var state = dim.state("FEEDBACK").name;
1610 if (state=="Warning" || state=="Critical" || state=="OnStandby")
1611 {
1612 v8.sleep(60000);
1613 continue;
1614 }
1615
1616 // Now we are 'OnTrack', so we can ramp to nominal voltage
1617 // and wait for the feedback to get stable
1618 //if (!obs[sub].grb || dim.state("FEEDBACK").name!="InProgress")
1619 service_feedback.voltageOn();
1620 if (!obs[sub].grb)
1621 service_feedback.waitForVoltageOn();
1622
1623 // For the first run to be taken (ratecontrol)
1624 // Lid must be != Closed
1625 // Drive must be >= Moving
1626 // Setting the threshold can take 2-3 seconds
1627
1628 if (obs[sub].grb && run==0)
1629 {
1630 // Instead of a pedestal run, we take a very short grb mode run
1631 // which is a classical data run but does not change the thresholds
1632 // This gives the voltages (typ. 5s) and currents (typ. 3s) time to
1633 // stabilize and threshold setting for the next run will be
1634 // reliable and fast but we have data already
1635 dim.log("Starting GRB mode.");
1636
1637 // Whatever we do... it does not make sense to start with a closed lid
1638 // If the lid is not yet open, wait for the lid to be open and
1639 // go on as usual.
1640 if (dim.state("LID_CONTROL").name!="Open")
1641 {
1642 dim.log("Waiting for an open lid.");
1643 dim.wait("LID_CONTROL", "Open", 30000);
1644 service_feedback.waitForVoltageOn();
1645 }
1646
1647 // Doing this manually makes it more flexible but turns off
1648 // automatic Critical mode checking of the feedback and
1649 // automatic reconnect
1650 var nextrun = sub_startrun.get().obj['next'];
1651 dim.log("Take run %3d".$(nextrun)+" [grb-mode]");
1652
1653 dim.send("MCP/START", -1, -1, "grb"); // Use previous threshold settings if ratecontrol "InProgress"
1654 dim.wait("MCP", "TakingData", 15000);
1655
1656 dim.wait("FEEDBACK", "InProgress", 45000); // This is most likely the first to happen
1657 dim.wait("DRIVE_CONTROL", "OnTrack", 150000); // 110s for turning and 30s for stabilizing
1658
1659 v8.sleep(1000); // By now we should have collected the required three current events in FEEDBACK
1660 // Current are averaged over 10s. So by now we should have a reasonable idea of the brightness of the sky
1661 // Individual pixels might still suffer wrong settings
1662 // Starting a new run takes less than 2s (for 60s runs this is 3%)
1663 }
1664
1665 // If pointing had changed, do calibration
1666 if (!irq && point && !obs[sub].grb)
1667 {
1668 dim.log("Starting calibration.");
1669
1670 // Calibration (2% of 20')
1671 while (!irq)
1672 {
1673 if (irq || !takeRun("pedestal", 1000)) // 80 Hz -> 10s
1674 continue;
1675// if (irq || !takeRun("light-pulser-ext", 1000)) // 80 Hz -> 10s
1676// continue;
1677 break;
1678 }
1679 }
1680
1681 //console.out(" Taking data: start [5min]");
1682
1683 // FIXME: What do we do if during calibration something has happened
1684 // e.g. drive went to ERROR? Maybe we have to check all states again?
1685
1686 var twilight = Sun.horizon(-16).isUp;
1687
1688 if (twilight || (obs[sub].grb && run<4))
1689 {
1690 for (var i=0; i<5 && !irq; i++)
1691 takeRun("data", -1, 60); // Take data (1min)
1692 }
1693 else
1694 {
1695 var len = 300;
1696 while (!irq && len>15)
1697 {
1698 var time = new Date();
1699 if (takeRun("data", -1, len)) // Take data (5min)
1700 break;
1701
1702 len -= parseInt((new Date()-time)/1000);
1703 }
1704 }
1705
1706 //console.out(" Taking data: done");
1707 run++;
1708
1709 continue; // case "DATA"
1710 }
1711
1712 if (nextObs!=undefined && sub==obs.length-1)
1713 dim.log("Next observation will start at "+nextObs.start.toUTCString()+" [id="+nextObs.id+"]");
1714
1715 sub++;
1716}
1717
1718sub_drsruns.close();
1719
1720dim.log("Left main loop [irq="+irq+"]");
1721
1722// ================================================================
1723// Comments and ToDo goes here
1724// ================================================================
1725
1726// error handline : http://www.sitepoint.com/exceptional-exception-handling-in-javascript/
1727// classes: http://www.phpied.com/3-ways-to-define-a-javascript-class/
Note: See TracBrowser for help on using the repository browser.