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

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