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

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